query
stringlengths 7
3.3k
| positive
sequencelengths 1
1
| negative
sequencelengths 9
9
|
---|---|---|
set the insetsFrameLayout to display the content in fullscreen
under the statusBar and navigationBar
@param fullscreen | [
"public void setFullscreen(boolean fullscreen) {\n if (mBuilder.mScrimInsetsLayout != null) {\n mBuilder.mScrimInsetsLayout.setTintStatusBar(!fullscreen);\n mBuilder.mScrimInsetsLayout.setTintNavigationBar(!fullscreen);\n }\n }"
] | [
"private void registerColumns() {\n\t\tfor (int i = 0; i < cols.length; i++) {\n\t\t\tDJCrosstabColumn crosstabColumn = cols[i];\n\n\t\t\tJRDesignCrosstabColumnGroup ctColGroup = new JRDesignCrosstabColumnGroup();\n\t\t\tctColGroup.setName(crosstabColumn.getProperty().getProperty());\n\t\t\tctColGroup.setHeight(crosstabColumn.getHeaderHeight());\n\n\t\t\tJRDesignCrosstabBucket bucket = new JRDesignCrosstabBucket();\n\n bucket.setValueClassName(crosstabColumn.getProperty().getValueClassName());\n\n\t\t\tJRDesignExpression bucketExp = ExpressionUtils.createExpression(\"$F{\"+crosstabColumn.getProperty().getProperty()+\"}\", crosstabColumn.getProperty().getValueClassName());\n\t\t\tbucket.setExpression(bucketExp);\n\n\t\t\tctColGroup.setBucket(bucket);\n\n\t\t\tJRDesignCellContents colHeaerContent = new JRDesignCellContents();\n\t\t\tJRDesignTextField colTitle = new JRDesignTextField();\n\n\t\t\tJRDesignExpression colTitleExp = new JRDesignExpression();\n\t\t\tcolTitleExp.setValueClassName(crosstabColumn.getProperty().getValueClassName());\n\t\t\tcolTitleExp.setText(\"$V{\"+crosstabColumn.getProperty().getProperty()+\"}\");\n\n\n\t\t\tcolTitle.setExpression(colTitleExp);\n\t\t\tcolTitle.setWidth(crosstabColumn.getWidth());\n\t\t\tcolTitle.setHeight(crosstabColumn.getHeaderHeight());\n\n\t\t\t//The height can be the sum of the heights of all the columns starting from the current one, up to the inner most one.\n\t\t\tint auxWidth = calculateRowHeaderMaxWidth(crosstabColumn);\n\t\t\tcolTitle.setWidth(auxWidth);\n\n\t\t\tStyle headerstyle = crosstabColumn.getHeaderStyle() == null ? this.djcross.getColumnHeaderStyle(): crosstabColumn.getHeaderStyle();\n\n\t\t\tif (headerstyle != null){\n\t\t\t\tlayoutManager.applyStyleToElement(headerstyle,colTitle);\n\t\t\t\tcolHeaerContent.setBackcolor(headerstyle.getBackgroundColor());\n\t\t\t}\n\n\n\t\t\tcolHeaerContent.addElement(colTitle);\n\t\t\tcolHeaerContent.setMode( ModeEnum.OPAQUE );\n\n\t\t\tboolean fullBorder = i <= 0; //Only outer most will have full border\n\t\t\tapplyCellBorder(colHeaerContent, fullBorder, false);\n\n\t\t\tctColGroup.setHeader(colHeaerContent);\n\n\t\t\tif (crosstabColumn.isShowTotals())\n\t\t\t\tcreateColumTotalHeader(ctColGroup,crosstabColumn,fullBorder);\n\n\n\t\t\ttry {\n\t\t\t\tjrcross.addColumnGroup(ctColGroup);\n\t\t\t} catch (JRException e) {\n\t\t\t\tlog.error(e.getMessage(),e);\n\t\t\t}\n\t\t}\n\t}",
"void throwCloudExceptionIfInFailedState() {\n if (this.isStatusFailed()) {\n if (this.errorBody() != null) {\n throw new CloudException(\"Async operation failed with provisioning state: \" + this.status(), this.response(), this.errorBody());\n } else {\n throw new CloudException(\"Async operation failed with provisioning state: \" + this.status(), this.response());\n }\n }\n }",
"public static rewritepolicylabel_rewritepolicy_binding[] get(nitro_service service, String labelname) throws Exception{\n\t\trewritepolicylabel_rewritepolicy_binding obj = new rewritepolicylabel_rewritepolicy_binding();\n\t\tobj.set_labelname(labelname);\n\t\trewritepolicylabel_rewritepolicy_binding response[] = (rewritepolicylabel_rewritepolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void setBeliefValue(String agent_name, final String belief_name,\n final Object new_value, Connector connector) {\n\n ((IExternalAccess) connector.getAgentsExternalAccess(agent_name))\n .scheduleStep(new IComponentStep<Integer>() {\n\n public IFuture<Integer> execute(IInternalAccess ia) {\n IBDIInternalAccess bia = (IBDIInternalAccess) ia;\n bia.getBeliefbase().getBelief(belief_name)\n .setFact(new_value);\n return null;\n }\n }).get(new ThreadSuspendable());\n }",
"public static void setPropertySafely(Marshaller marshaller, String name, Object value) {\n try {\n marshaller.setProperty(name, value);\n } catch (PropertyException e) {\n LOGGER.warn(String.format(\"Can't set \\\"%s\\\" property to given marshaller\", name), e);\n }\n }",
"public static String formatConnectionEstablishmentMessage(final String connectionName, final String host, final String connectionReason) {\n\t\treturn CON_ESTABLISHMENT_FORMAT.format(new Object[] { connectionName, host, connectionReason });\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}",
"public String getRandomHoliday(String earliest, String latest) {\n String dateString = \"\";\n DateTimeFormatter parser = ISODateTimeFormat.date();\n DateTime earlyDate = parser.parseDateTime(earliest);\n DateTime lateDate = parser.parseDateTime(latest);\n List<Holiday> holidays = new LinkedList<>();\n\n int min = Integer.parseInt(earlyDate.toString().substring(0, 4));\n int max = Integer.parseInt(lateDate.toString().substring(0, 4));\n int range = max - min + 1;\n int randomYear = (int) (Math.random() * range) + min;\n\n for (Holiday s : EquivalenceClassTransformer.HOLIDAYS) {\n holidays.add(s);\n }\n Collections.shuffle(holidays);\n\n for (Holiday holiday : holidays) {\n dateString = convertToReadableDate(holiday.forYear(randomYear));\n if (toDate(dateString).after(toDate(earliest)) && toDate(dateString).before(toDate(latest))) {\n break;\n }\n }\n return dateString;\n }",
"public GeoPolygon addHoles(List<List<GeoPoint>> holes) {\n\t\tContracts.assertNotNull( holes, \"holes\" );\n\t\tthis.rings.addAll( holes );\n\t\treturn this;\n\t}"
] |
Print a class's relations | [
"public void printRelations(ClassDoc c) {\n\tOptions opt = optionProvider.getOptionsFor(c);\n\tif (hidden(c) || c.name().equals(\"\")) // avoid phantom classes, they may pop up when the source uses annotations\n\t return;\n\t// Print generalization (through the Java superclass)\n\tType s = c.superclassType();\n\tClassDoc sc = s != null && !s.qualifiedTypeName().equals(Object.class.getName()) ? s.asClassDoc() : null;\n\tif (sc != null && !c.isEnum() && !hidden(sc))\n\t relation(opt, RelationType.EXTENDS, c, sc, null, null, null);\n\t// Print generalizations (through @extends tags)\n\tfor (Tag tag : c.tags(\"extends\"))\n\t if (!hidden(tag.text()))\n\t\trelation(opt, RelationType.EXTENDS, c, c.findClass(tag.text()), null, null, null);\n\t// Print realizations (Java interfaces)\n\tfor (Type iface : c.interfaceTypes()) {\n\t ClassDoc ic = iface.asClassDoc();\n\t if (!hidden(ic))\n\t\trelation(opt, RelationType.IMPLEMENTS, c, ic, null, null, null);\n\t}\n\t// Print other associations\n\tallRelation(opt, RelationType.COMPOSED, c);\n\tallRelation(opt, RelationType.NAVCOMPOSED, c);\n\tallRelation(opt, RelationType.HAS, c);\n\tallRelation(opt, RelationType.NAVHAS, c);\n\tallRelation(opt, RelationType.ASSOC, c);\n\tallRelation(opt, RelationType.NAVASSOC, c);\n\tallRelation(opt, RelationType.DEPEND, c);\n }"
] | [
"private static byte calculateChecksum(byte[] buffer) {\n\t\tbyte checkSum = (byte)0xFF;\n\t\tfor (int i=1; i<buffer.length-1; i++) {\n\t\t\tcheckSum = (byte) (checkSum ^ buffer[i]);\n\t\t}\n\t\tlogger.trace(String.format(\"Calculated checksum = 0x%02X\", checkSum));\n\t\treturn checkSum;\n\t}",
"private CmsTemplateMapperConfiguration getConfiguration(final CmsObject cms) {\n\n if (!m_enabled) {\n return CmsTemplateMapperConfiguration.EMPTY_CONFIG;\n }\n\n if (m_configPath == null) {\n m_configPath = OpenCms.getSystemInfo().getConfigFilePath(cms, \"template-mapping.xml\");\n }\n\n return (CmsTemplateMapperConfiguration)(CmsVfsMemoryObjectCache.getVfsMemoryObjectCache().loadVfsObject(\n cms,\n m_configPath,\n new Transformer() {\n\n @Override\n public Object transform(Object input) {\n\n try {\n CmsFile file = cms.readFile(m_configPath, CmsResourceFilter.IGNORE_EXPIRATION);\n SAXReader saxBuilder = new SAXReader();\n try (ByteArrayInputStream stream = new ByteArrayInputStream(file.getContents())) {\n Document document = saxBuilder.read(stream);\n CmsTemplateMapperConfiguration config = new CmsTemplateMapperConfiguration(cms, document);\n return config;\n }\n } catch (Exception e) {\n LOG.warn(e.getLocalizedMessage(), e);\n return new CmsTemplateMapperConfiguration(); // empty configuration, does not do anything\n }\n\n }\n }));\n }",
"public static Method findSetMethod(Field field, DatabaseType databaseType, boolean throwExceptions)\n\t\t\tthrows IllegalArgumentException {\n\t\tMethod fieldSetMethod = findMethodFromNames(field, false, throwExceptions,\n\t\t\t\tmethodFromField(field, \"set\", databaseType, true), methodFromField(field, \"set\", databaseType, false));\n\t\tif (fieldSetMethod == null) {\n\t\t\treturn null;\n\t\t}\n\t\tif (fieldSetMethod.getReturnType() != void.class) {\n\t\t\tif (throwExceptions) {\n\t\t\t\tthrow new IllegalArgumentException(\"Return type of set method \" + fieldSetMethod.getName() + \" returns \"\n\t\t\t\t\t\t+ fieldSetMethod.getReturnType() + \" instead of void\");\n\t\t\t} else {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\treturn fieldSetMethod;\n\t}",
"private void updateCurrencyFormats(ProjectProperties properties, char decimalSeparator, char thousandsSeparator)\n {\n String prefix = \"\";\n String suffix = \"\";\n String currencySymbol = quoteFormatCharacters(properties.getCurrencySymbol());\n\n switch (properties.getSymbolPosition())\n {\n case AFTER:\n {\n suffix = currencySymbol;\n break;\n }\n\n case BEFORE:\n {\n prefix = currencySymbol;\n break;\n }\n\n case AFTER_WITH_SPACE:\n {\n suffix = \" \" + currencySymbol;\n break;\n }\n\n case BEFORE_WITH_SPACE:\n {\n prefix = currencySymbol + \" \";\n break;\n }\n }\n\n StringBuilder pattern = new StringBuilder(prefix);\n pattern.append(\"#0\");\n\n int digits = properties.getCurrencyDigits().intValue();\n if (digits > 0)\n {\n pattern.append('.');\n for (int i = 0; i < digits; i++)\n {\n pattern.append(\"0\");\n }\n }\n\n pattern.append(suffix);\n\n String primaryPattern = pattern.toString();\n\n String[] alternativePatterns = new String[7];\n alternativePatterns[0] = primaryPattern + \";(\" + primaryPattern + \")\";\n pattern.insert(prefix.length(), \"#,#\");\n String secondaryPattern = pattern.toString();\n alternativePatterns[1] = secondaryPattern;\n alternativePatterns[2] = secondaryPattern + \";(\" + secondaryPattern + \")\";\n\n pattern.setLength(0);\n pattern.append(\"#0\");\n\n if (digits > 0)\n {\n pattern.append('.');\n for (int i = 0; i < digits; i++)\n {\n pattern.append(\"0\");\n }\n }\n\n String noSymbolPrimaryPattern = pattern.toString();\n alternativePatterns[3] = noSymbolPrimaryPattern;\n alternativePatterns[4] = noSymbolPrimaryPattern + \";(\" + noSymbolPrimaryPattern + \")\";\n pattern.insert(0, \"#,#\");\n String noSymbolSecondaryPattern = pattern.toString();\n alternativePatterns[5] = noSymbolSecondaryPattern;\n alternativePatterns[6] = noSymbolSecondaryPattern + \";(\" + noSymbolSecondaryPattern + \")\";\n\n m_currencyFormat.applyPattern(primaryPattern, alternativePatterns, decimalSeparator, thousandsSeparator);\n }",
"public ThumborUrlBuilder trim(TrimPixelColor value, int colorTolerance) {\n if (colorTolerance < 0 || colorTolerance > 442) {\n throw new IllegalArgumentException(\"Color tolerance must be between 0 and 442.\");\n }\n if (colorTolerance > 0 && value == null) {\n throw new IllegalArgumentException(\"Trim pixel color value must not be null.\");\n }\n isTrim = true;\n trimPixelColor = value;\n trimColorTolerance = colorTolerance;\n return this;\n }",
"protected List<CmsResource> getTopFolders(List<CmsResource> folders) {\n\n List<String> folderPaths = new ArrayList<String>();\n List<CmsResource> topFolders = new ArrayList<CmsResource>();\n Map<String, CmsResource> foldersByPath = new HashMap<String, CmsResource>();\n for (CmsResource folder : folders) {\n folderPaths.add(folder.getRootPath());\n foldersByPath.put(folder.getRootPath(), folder);\n }\n Collections.sort(folderPaths);\n Set<String> topFolderPaths = new HashSet<String>(folderPaths);\n for (int i = 0; i < folderPaths.size(); i++) {\n for (int j = i + 1; j < folderPaths.size(); j++) {\n if (folderPaths.get(j).startsWith((folderPaths.get(i)))) {\n topFolderPaths.remove(folderPaths.get(j));\n } else {\n break;\n }\n }\n }\n for (String path : topFolderPaths) {\n topFolders.add(foldersByPath.get(path));\n }\n return topFolders;\n }",
"public static base_response add(nitro_service client, nssimpleacl resource) throws Exception {\n\t\tnssimpleacl addresource = new nssimpleacl();\n\t\taddresource.aclname = resource.aclname;\n\t\taddresource.aclaction = resource.aclaction;\n\t\taddresource.td = resource.td;\n\t\taddresource.srcip = resource.srcip;\n\t\taddresource.destport = resource.destport;\n\t\taddresource.protocol = resource.protocol;\n\t\taddresource.ttl = resource.ttl;\n\t\treturn addresource.add_resource(client);\n\t}",
"public static List<KoreanPhraseExtractor.KoreanPhrase> extractPhrases(Seq<KoreanToken> tokens, boolean filterSpam, boolean includeHashtags) {\n return JavaConversions.seqAsJavaList(\n TwitterKoreanProcessor.extractPhrases(tokens, filterSpam, includeHashtags)\n );\n }",
"public void fireRelationReadEvent(Relation relation)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.relationRead(relation);\n }\n }\n }"
] |
This method computes the eigen vector with the largest eigen value by using the
direct power method. This technique is the easiest to implement, but the slowest to converge.
Works only if all the eigenvalues are real.
@param A The matrix. Not modified.
@return If it converged or not. | [
"public boolean computeDirect( DMatrixRMaj A ) {\n\n initPower(A);\n\n boolean converged = false;\n\n for( int i = 0; i < maxIterations && !converged; i++ ) {\n// q0.print();\n \n CommonOps_DDRM.mult(A,q0,q1);\n double s = NormOps_DDRM.normPInf(q1);\n CommonOps_DDRM.divide(q1,s,q2);\n\n converged = checkConverged(A);\n }\n\n return converged;\n }"
] | [
"public void setCurrencyDigits(Integer currDigs)\n {\n if (currDigs == null)\n {\n currDigs = DEFAULT_CURRENCY_DIGITS;\n }\n set(ProjectField.CURRENCY_DIGITS, currDigs);\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 }",
"public static List<Artifact> getAllArtifacts(final Module module){\n final List<Artifact> artifacts = new ArrayList<Artifact>();\n\n for(final Module subModule: module.getSubmodules()){\n artifacts.addAll(getAllArtifacts(subModule));\n }\n\n artifacts.addAll(module.getArtifacts());\n\n return artifacts;\n }",
"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 QueryBuilder<T, ID> groupBy(String columnName) {\n\t\tFieldType fieldType = verifyColumnName(columnName);\n\t\tif (fieldType.isForeignCollection()) {\n\t\t\tthrow new IllegalArgumentException(\"Can't groupBy foreign collection field: \" + columnName);\n\t\t}\n\t\taddGroupBy(ColumnNameOrRawSql.withColumnName(columnName));\n\t\treturn this;\n\t}",
"public static Field getDeclaredFieldWithPath(Class<?> clazz, String path) {\n\n int lastDot = path.lastIndexOf('.');\n\n if (lastDot > -1) {\n String parentPath = path.substring(0, lastDot);\n String fieldName = path.substring(lastDot + 1);\n Field parentField = getDeclaredFieldWithPath(clazz, parentPath);\n return getDeclaredFieldInHierarchy(parentField.getType(), fieldName);\n } else {\n return getDeclaredFieldInHierarchy(clazz, path);\n }\n }",
"public static sslpolicylabel[] get(nitro_service service) throws Exception{\n\t\tsslpolicylabel obj = new sslpolicylabel();\n\t\tsslpolicylabel[] response = (sslpolicylabel[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static appflowpolicy_appflowpolicylabel_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappflowpolicy_appflowpolicylabel_binding obj = new appflowpolicy_appflowpolicylabel_binding();\n\t\tobj.set_name(name);\n\t\tappflowpolicy_appflowpolicylabel_binding response[] = (appflowpolicy_appflowpolicylabel_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static CharSequence getRelativeTimeSpanString(Context context, ReadableInstant time, int flags) {\n boolean abbrevRelative = (flags & (FORMAT_ABBREV_RELATIVE | FORMAT_ABBREV_ALL)) != 0;\n\n // We set the millis to 0 so we aren't off by a fraction of a second when counting intervals\n DateTime now = DateTime.now(time.getZone()).withMillisOfSecond(0);\n DateTime timeDt = new DateTime(time).withMillisOfSecond(0);\n boolean past = !now.isBefore(timeDt);\n Interval interval = past ? new Interval(timeDt, now) : new Interval(now, timeDt);\n\n int resId;\n long count;\n if (Minutes.minutesIn(interval).isLessThan(Minutes.ONE)) {\n count = Seconds.secondsIn(interval).getSeconds();\n if (past) {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_num_seconds_ago;\n }\n else {\n resId = R.plurals.joda_time_android_num_seconds_ago;\n }\n }\n else {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_in_num_seconds;\n }\n else {\n resId = R.plurals.joda_time_android_in_num_seconds;\n }\n }\n }\n else if (Hours.hoursIn(interval).isLessThan(Hours.ONE)) {\n count = Minutes.minutesIn(interval).getMinutes();\n if (past) {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_num_minutes_ago;\n }\n else {\n resId = R.plurals.joda_time_android_num_minutes_ago;\n }\n }\n else {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_in_num_minutes;\n }\n else {\n resId = R.plurals.joda_time_android_in_num_minutes;\n }\n }\n }\n else if (Days.daysIn(interval).isLessThan(Days.ONE)) {\n count = Hours.hoursIn(interval).getHours();\n if (past) {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_num_hours_ago;\n }\n else {\n resId = R.plurals.joda_time_android_num_hours_ago;\n }\n }\n else {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_in_num_hours;\n }\n else {\n resId = R.plurals.joda_time_android_in_num_hours;\n }\n }\n }\n else if (Weeks.weeksIn(interval).isLessThan(Weeks.ONE)) {\n count = Days.daysIn(interval).getDays();\n if (past) {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_num_days_ago;\n }\n else {\n resId = R.plurals.joda_time_android_num_days_ago;\n }\n }\n else {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_in_num_days;\n }\n else {\n resId = R.plurals.joda_time_android_in_num_days;\n }\n }\n }\n else {\n return formatDateRange(context, time, time, flags);\n }\n\n String format = context.getResources().getQuantityString(resId, (int) count);\n return String.format(format, count);\n }"
] |
Retrieve all addresses of a host by it's address. NetBIOS hosts can
have many names for a given IP address. The name and IP address make the
NetBIOS address. This provides a way to retrieve the other names for a
host with the same IP address.
@param addr the address to query
@throws UnknownHostException if address cannot be resolved | [
"public static NbtAddress[] getAllByAddress( NbtAddress addr )\n throws UnknownHostException {\n try {\n NbtAddress[] addrs = CLIENT.getNodeStatus( addr );\n cacheAddressArray( addrs );\n return addrs;\n } catch( UnknownHostException uhe ) {\n throw new UnknownHostException( \"no name with type 0x\" +\n Hexdump.toHexString( addr.hostName.hexCode, 2 ) +\n ((( addr.hostName.scope == null ) ||\n ( addr.hostName.scope.length() == 0 )) ?\n \" with no scope\" : \" with scope \" + addr.hostName.scope ) +\n \" for host \" + addr.getHostAddress() );\n }\n }"
] | [
"@Override\n protected void onLoad() {\n\tsuper.onLoad();\n\n\t// these styles need to be the same for the box and shadow so\n\t// that we can measure properly\n\tmatchStyles(\"display\");\n\tmatchStyles(\"fontSize\");\n\tmatchStyles(\"fontFamily\");\n\tmatchStyles(\"fontWeight\");\n\tmatchStyles(\"lineHeight\");\n\tmatchStyles(\"paddingTop\");\n\tmatchStyles(\"paddingRight\");\n\tmatchStyles(\"paddingBottom\");\n\tmatchStyles(\"paddingLeft\");\n\n\tadjustSize();\n }",
"private static String buildErrorMsg(List<String> dependencies, String message) {\n final StringBuilder buffer = new StringBuilder();\n boolean isFirstElement = true;\n for (String dependency : dependencies) {\n if (!isFirstElement) {\n buffer.append(\", \");\n }\n // check if it is an instance of Artifact - add the gavc else append the object\n buffer.append(dependency);\n\n isFirstElement = false;\n }\n return String.format(message, buffer.toString());\n }",
"public static final Date getDate(InputStream is) throws IOException\n {\n long timeInSeconds = getInt(is);\n if (timeInSeconds == 0x93406FFF)\n {\n return null;\n }\n timeInSeconds -= 3600;\n timeInSeconds *= 1000;\n return DateHelper.getDateFromLong(timeInSeconds);\n }",
"public static Date max(Date d1, Date d2)\n {\n Date result;\n if (d1 == null)\n {\n result = d2;\n }\n else\n if (d2 == null)\n {\n result = d1;\n }\n else\n {\n result = (d1.compareTo(d2) > 0) ? d1 : d2;\n }\n return result;\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 }",
"public void useNewSOAPServiceWithOldClientAndRedirection() throws Exception {\n URL wsdlURL = getClass().getResource(\"/CustomerService.wsdl\");\n com.example.customerservice.CustomerServiceService service = \n new com.example.customerservice.CustomerServiceService(wsdlURL);\n \n com.example.customerservice.CustomerService customerService = \n service.getCustomerServiceRedirectPort();\n\n System.out.println(\"Using new SOAP CustomerService with old client and the redirection\");\n \n customer.v1.Customer customer = createOldCustomer(\"Barry Old to New SOAP With Redirection\");\n customerService.updateCustomer(customer);\n customer = customerService.getCustomerByName(\"Barry Old to New SOAP With Redirection\");\n printOldCustomerDetails(customer);\n }",
"private static void alterHtmlDocs(Options opt, String outputFolder, String packageName, String className,\n\t String htmlFileName, Pattern insertPointPattern, RootDoc root) throws IOException {\n\t// setup files\n\tFile output = new File(outputFolder, packageName.replace(\".\", \"/\"));\n\tFile htmlFile = new File(output, htmlFileName);\n\tFile alteredFile = new File(htmlFile.getAbsolutePath() + \".uml\");\n\tif (!htmlFile.exists()) {\n\t System.err.println(\"Expected file not found: \" + htmlFile.getAbsolutePath());\n\t return;\n\t}\n\n\t// parse & rewrite\n\tBufferedWriter writer = null;\n\tBufferedReader reader = null;\n\tboolean matched = false;\n\ttry {\n\t writer = new BufferedWriter(new OutputStreamWriter(new\n\t\t FileOutputStream(alteredFile), opt.outputEncoding));\n\t reader = new BufferedReader(new InputStreamReader(new\n\t\t FileInputStream(htmlFile), opt.outputEncoding));\n\n\t String line;\n\t while ((line = reader.readLine()) != null) {\n\t\twriter.write(line);\n\t\twriter.newLine();\n\t\tif (!matched && insertPointPattern.matcher(line).matches()) {\n\t\t matched = true;\n\t\t\t\n\t\t String tag;\n\t\t if (opt.autoSize)\n\t\t tag = String.format(UML_AUTO_SIZED_DIV_TAG, className);\n\t\t else\n tag = String.format(UML_DIV_TAG, className);\n\t\t if (opt.collapsibleDiagrams)\n\t\t \ttag = String.format(EXPANDABLE_UML, tag, \"Show UML class diagram\", \"Hide UML class diagram\");\n\t\t writer.write(\"<!-- UML diagram added by UMLGraph version \" +\n\t\t \t\tVersion.VERSION + \n\t\t\t\t\" (http://www.spinellis.gr/umlgraph/) -->\");\n\t\t writer.newLine();\n\t\t writer.write(tag);\n\t\t writer.newLine();\n\t\t}\n\t }\n\t} finally {\n\t if (writer != null)\n\t\twriter.close();\n\t if (reader != null)\n\t\treader.close();\n\t}\n\n\t// if altered, delete old file and rename new one to the old file name\n\tif (matched) {\n\t htmlFile.delete();\n\t alteredFile.renameTo(htmlFile);\n\t} else {\n\t root.printNotice(\"Warning, could not find a line that matches the pattern '\" + insertPointPattern.pattern() \n\t\t + \"'.\\n Class diagram reference not inserted\");\n\t alteredFile.delete();\n\t}\n }",
"protected boolean checkForAndHandleZeros() {\n // check for zeros along off diagonal\n for( int i = x2-1; i >= x1; i-- ) {\n if( isOffZero(i) ) {\n// System.out.println(\"steps at split = \"+steps);\n resetSteps();\n splits[numSplits++] = i;\n x1 = i+1;\n return true;\n }\n }\n\n // check for zeros along diagonal\n for( int i = x2-1; i >= x1; i-- ) {\n if( isDiagonalZero(i)) {\n// System.out.println(\"steps at split = \"+steps);\n pushRight(i);\n resetSteps();\n splits[numSplits++] = i;\n x1 = i+1;\n return true;\n }\n }\n return false;\n }",
"public Set<DeviceAnnouncement> findUnreachablePlayers() {\n ensureRunning();\n Set<DeviceAnnouncement> result = new HashSet<DeviceAnnouncement>();\n for (DeviceAnnouncement candidate: DeviceFinder.getInstance().getCurrentDevices()) {\n if (!Util.sameNetwork(matchedAddress.getNetworkPrefixLength(), matchedAddress.getAddress(), candidate.getAddress())) {\n result.add(candidate);\n }\n }\n return Collections.unmodifiableSet(result);\n }"
] |
Returns a flag indicating if also expired resources should be found.
@return A flag indicating if also expired resources should be found. | [
"protected Boolean getIgnoreExpirationDate() {\n\n Boolean isIgnoreExpirationDate = parseOptionalBooleanValue(m_configObject, JSON_KEY_IGNORE_EXPIRATION_DATE);\n return (null == isIgnoreExpirationDate) && (m_baseConfig != null)\n ? Boolean.valueOf(m_baseConfig.getGeneralConfig().getIgnoreExpirationDate())\n : isIgnoreExpirationDate;\n }"
] | [
"private I_CmsSearchResultWrapper getSearchResults() {\n\n // The second parameter is just ignored - so it does not matter\n m_searchController.updateFromRequestParameters(pageContext.getRequest().getParameterMap(), false);\n I_CmsSearchControllerCommon common = m_searchController.getCommon();\n // Do not search for empty query, if configured\n if (common.getState().getQuery().isEmpty()\n && (!common.getConfig().getIgnoreQueryParam() && !common.getConfig().getSearchForEmptyQueryParam())) {\n return new CmsSearchResultWrapper(m_searchController, null, null, m_cms, null);\n }\n Map<String, String[]> queryParams = null;\n boolean isEditMode = CmsJspTagEditable.isEditableRequest(pageContext.getRequest());\n if (isEditMode) {\n String params = \"\";\n if (common.getConfig().getIgnoreReleaseDate()) {\n params += \"&fq=released:[* TO *]\";\n }\n if (common.getConfig().getIgnoreExpirationDate()) {\n params += \"&fq=expired:[* TO *]\";\n }\n if (!params.isEmpty()) {\n queryParams = CmsRequestUtil.createParameterMap(params.substring(1));\n }\n }\n CmsSolrQuery query = new CmsSolrQuery(null, queryParams);\n m_searchController.addQueryParts(query, m_cms);\n try {\n // use \"complicated\" constructor to allow more than 50 results -> set ignoreMaxResults to true\n // also set resource filter to allow for returning unreleased/expired resources if necessary.\n CmsSolrResultList solrResultList = m_index.search(\n m_cms,\n query.clone(), // use a clone of the query, since the search function manipulates the query (removes highlighting parts), but we want to keep the original one.\n true,\n isEditMode ? CmsResourceFilter.IGNORE_EXPIRATION : null);\n return new CmsSearchResultWrapper(m_searchController, solrResultList, query, m_cms, null);\n } catch (CmsSearchException e) {\n LOG.warn(Messages.get().getBundle().key(Messages.LOG_TAG_SEARCH_SEARCH_FAILED_0), e);\n return new CmsSearchResultWrapper(m_searchController, null, query, m_cms, e);\n }\n }",
"private int determineForkedJvmCount(TestsCollection testCollection) {\n int cores = Runtime.getRuntime().availableProcessors();\n int jvmCount;\n if (this.parallelism.equals(PARALLELISM_AUTO)) {\n if (cores >= 8) {\n // Maximum parallel jvms is 4, conserve some memory and memory bandwidth.\n jvmCount = 4;\n } else if (cores >= 4) {\n // Make some space for the aggregator.\n jvmCount = 3;\n } else if (cores == 3) {\n // Yes, three-core chips are a thing.\n jvmCount = 2;\n } else {\n // even for dual cores it usually makes no sense to fork more than one\n // JVM.\n jvmCount = 1;\n }\n } else if (this.parallelism.equals(PARALLELISM_MAX)) {\n jvmCount = Runtime.getRuntime().availableProcessors();\n } else {\n try {\n jvmCount = Math.max(1, Integer.parseInt(parallelism));\n } catch (NumberFormatException e) {\n throw new BuildException(\"parallelism must be 'auto', 'max' or a valid integer: \"\n + parallelism);\n }\n }\n\n if (!testCollection.hasReplicatedSuites()) {\n jvmCount = Math.min(testCollection.testClasses.size(), jvmCount);\n }\n return jvmCount;\n }",
"public static int nullity(SingularValueDecomposition_F64 svd , double threshold ) {\n int ret = 0;\n\n double w[]= svd.getSingularValues();\n\n int N = svd.numberOfSingularValues();\n\n int numCol = svd.numCols();\n\n for( int j = 0; j < N; j++ ) {\n if( w[j] <= threshold) ret++;\n }\n return ret + numCol-N;\n }",
"@Override\n public void onNewState(CrawlerContext context, StateVertex vertex) {\n LOG.debug(\"onNewState\");\n StateBuilder state = outModelCache.addStateIfAbsent(vertex);\n visitedStates.putIfAbsent(state.getName(), vertex);\n\n saveScreenshot(context.getBrowser(), state.getName(), vertex);\n\n outputBuilder.persistDom(state.getName(), context.getBrowser().getUnStrippedDom());\n }",
"public static List<? extends Expression> getMethodArguments(ASTNode methodCall) {\r\n if (methodCall instanceof ConstructorCallExpression) {\r\n return extractExpressions(((ConstructorCallExpression) methodCall).getArguments());\r\n } else if (methodCall instanceof MethodCallExpression) {\r\n return extractExpressions(((MethodCallExpression) methodCall).getArguments());\r\n } else if (methodCall instanceof StaticMethodCallExpression) {\r\n return extractExpressions(((StaticMethodCallExpression) methodCall).getArguments());\r\n } else if (respondsTo(methodCall, \"getArguments\")) {\r\n throw new RuntimeException(); // TODO: remove, should never happen\r\n }\r\n return new ArrayList<Expression>();\r\n }",
"protected List<Integer> getPageSizes() {\n\n try {\n return Collections.singletonList(Integer.valueOf(m_configObject.getInt(JSON_KEY_PAGESIZE)));\n } catch (JSONException e) {\n List<Integer> result = null;\n String pageSizesString = null;\n try {\n pageSizesString = m_configObject.getString(JSON_KEY_PAGESIZE);\n String[] pageSizesArray = pageSizesString.split(\"-\");\n if (pageSizesArray.length > 0) {\n result = new ArrayList<>(pageSizesArray.length);\n for (int i = 0; i < pageSizesArray.length; i++) {\n result.add(Integer.valueOf(pageSizesArray[i]));\n }\n }\n return result;\n } catch (NumberFormatException | JSONException e1) {\n LOG.warn(Messages.get().getBundle().key(Messages.LOG_PARSING_PAGE_SIZES_FAILED_1, pageSizesString), e);\n }\n if (null == m_baseConfig) {\n if (LOG.isInfoEnabled()) {\n LOG.info(Messages.get().getBundle().key(Messages.LOG_NO_PAGESIZE_SPECIFIED_0), e);\n }\n return null;\n } else {\n return m_baseConfig.getPaginationConfig().getPageSizes();\n }\n }\n }",
"public WebSocketContext sendToTagged(String message, String tag, boolean excludeSelf) {\n return sendToConnections(message, tag, manager.tagRegistry(), excludeSelf);\n }",
"public void setDropShadowColor(int color) {\n GradientDrawable.Orientation orientation = getDropShadowOrientation();\n\n final int endColor = color & 0x00FFFFFF;\n mDropShadowDrawable = new GradientDrawable(orientation,\n new int[] {\n color,\n endColor,\n });\n invalidate();\n }",
"public static base_response add(nitro_service client, clusterinstance resource) throws Exception {\n\t\tclusterinstance addresource = new clusterinstance();\n\t\taddresource.clid = resource.clid;\n\t\taddresource.deadinterval = resource.deadinterval;\n\t\taddresource.hellointerval = resource.hellointerval;\n\t\taddresource.preemption = resource.preemption;\n\t\treturn addresource.add_resource(client);\n\t}"
] |
Get a random sample of k out of n elements.
See Algorithm S, D. E. Knuth, The Art of Computer Programming, Vol. 2, p.142. | [
"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 }"
] | [
"private void checkPrimaryKey(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n if (classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, true) &&\r\n classDef.getPrimaryKeys().isEmpty())\r\n {\r\n LogHelper.warn(true,\r\n getClass(),\r\n \"checkPrimaryKey\",\r\n \"The class \"+classDef.getName()+\" has no primary key\");\r\n }\r\n }",
"public synchronized Widget measureChild(final int dataIndex, boolean calculateOffset) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"measureChild dataIndex = %d\", dataIndex);\n\n Widget widget = mContainer.get(dataIndex);\n if (widget != null) {\n synchronized (mMeasuredChildren) {\n mMeasuredChildren.add(dataIndex);\n }\n }\n return widget;\n }",
"public String getString(Integer offset)\n {\n String result = null;\n\n if (offset != null)\n {\n byte[] value = m_map.get(offset);\n if (value != null)\n {\n result = MPPUtility.getString(value, 0);\n }\n }\n\n return (result);\n }",
"public Photo getInfo(String photoId, String secret) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_INFO);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n if (secret != null) {\r\n parameters.put(\"secret\", secret);\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photoElement = response.getPayload();\r\n\r\n return PhotoUtils.createPhoto(photoElement);\r\n }",
"protected void handleResponse(int responseCode, InputStream inputStream) {\n BufferedReader rd = null;\n try {\n // Buffer the result into a string\n rd = new BufferedReader(new InputStreamReader(inputStream));\n StringBuilder sb = new StringBuilder();\n String line;\n while((line = rd.readLine()) != null) {\n sb.append(line);\n }\n log.info(\"HttpHook [\" + hookName + \"] received \" + responseCode + \" response: \" + sb);\n } catch (IOException e) {\n log.error(\"Error while reading response for HttpHook [\" + hookName + \"]\", e);\n } finally {\n if (rd != null) {\n try {\n rd.close();\n } catch (IOException e) {\n // no-op\n }\n }\n }\n }",
"public AlbumArt requestArtworkFrom(final DataReference artReference, final CdjStatus.TrackType trackType) {\n ensureRunning();\n AlbumArt artwork = findArtInMemoryCaches(artReference); // First check the in-memory artwork caches.\n if (artwork == null) {\n artwork = requestArtworkInternal(artReference, trackType, false);\n }\n return artwork;\n }",
"public void processDefaultCurrency(Row row)\n {\n ProjectProperties properties = m_project.getProjectProperties();\n properties.setCurrencySymbol(row.getString(\"curr_symbol\"));\n properties.setSymbolPosition(CURRENCY_SYMBOL_POSITION_MAP.get(row.getString(\"pos_curr_fmt_type\")));\n properties.setCurrencyDigits(row.getInteger(\"decimal_digit_cnt\"));\n properties.setThousandsSeparator(row.getString(\"digit_group_symbol\").charAt(0));\n properties.setDecimalSeparator(row.getString(\"decimal_symbol\").charAt(0));\n }",
"public RedwoodConfiguration neatExit(){\r\n tasks.add(new Runnable() { public void run() {\r\n Runtime.getRuntime().addShutdownHook(new Thread(){\r\n @Override public void run(){ Redwood.stop(); }\r\n });\r\n }});\r\n return this;\r\n }",
"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 }"
] |
Finds all providers for the given service.
@param serviceName
The fully qualified name of the service interface.
@return
The ordered set of providers for the service if any exists.
Otherwise, it returns an empty list.
@throws IllegalArgumentException if serviceName is <tt>null</tt> | [
"public static synchronized List<Class< ? >> locateAll(final String serviceName) {\n if ( serviceName == null ) {\n throw new IllegalArgumentException( \"serviceName cannot be null\" );\n }\n List<Class< ? >> classes = new ArrayList<Class< ? >>();\n if ( factories != null ) {\n List<Callable<Class< ? >>> l = factories.get( serviceName );\n if ( l != null ) {\n for ( Callable<Class< ? >> c : l ) {\n try {\n classes.add( c.call() );\n } catch ( Exception e ) {\n }\n }\n }\n }\n return classes;\n }"
] | [
"public GridCoverage2D call() {\n try {\n BufferedImage coverageImage = this.tiledLayer.createBufferedImage(\n this.tilePreparationInfo.getImageWidth(),\n this.tilePreparationInfo.getImageHeight());\n Graphics2D graphics = coverageImage.createGraphics();\n try {\n for (SingleTilePreparationInfo tileInfo: this.tilePreparationInfo.getSingleTiles()) {\n final TileTask task;\n if (tileInfo.getTileRequest() != null) {\n task = new SingleTileLoaderTask(\n tileInfo.getTileRequest(), this.errorImage, tileInfo.getTileIndexX(),\n tileInfo.getTileIndexY(), this.failOnError, this.registry, this.context);\n } else {\n task = new PlaceHolderImageTask(this.tiledLayer.getMissingTileImage(),\n tileInfo.getTileIndexX(), tileInfo.getTileIndexY());\n }\n Tile tile = task.call();\n if (tile.getImage() != null) {\n graphics.drawImage(tile.getImage(),\n tile.getxIndex() * this.tiledLayer.getTileSize().width,\n tile.getyIndex() * this.tiledLayer.getTileSize().height, null);\n }\n }\n } finally {\n graphics.dispose();\n }\n\n GridCoverageFactory factory = CoverageFactoryFinder.getGridCoverageFactory(null);\n GeneralEnvelope gridEnvelope = new GeneralEnvelope(this.tilePreparationInfo.getMapProjection());\n gridEnvelope.setEnvelope(this.tilePreparationInfo.getGridCoverageOrigin().x,\n this.tilePreparationInfo.getGridCoverageOrigin().y,\n this.tilePreparationInfo.getGridCoverageMaxX(),\n this.tilePreparationInfo.getGridCoverageMaxY());\n return factory.create(this.tiledLayer.createCommonUrl(), coverageImage, gridEnvelope,\n null, null, null);\n } catch (Exception e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }",
"public void signIn(String key, Collection<WebSocketConnection> connections) {\n if (connections.isEmpty()) {\n return;\n }\n Map<WebSocketConnection, WebSocketConnection> newMap = new HashMap<>();\n for (WebSocketConnection conn : connections) {\n newMap.put(conn, conn);\n }\n ConcurrentMap<WebSocketConnection, WebSocketConnection> bag = ensureConnectionList(key);\n bag.putAll(newMap);\n }",
"private GregorianCalendar getLastReleventDate(GregorianCalendar currentDate) {\n\t\tint age=this.getProperties().getMaxFileAge();\n\t\tGregorianCalendar result=new GregorianCalendar(currentDate.get(Calendar.YEAR),currentDate.get(Calendar.MONTH),currentDate.get(Calendar.DAY_OF_MONTH));\n\t\tresult.add(Calendar.DAY_OF_MONTH, -age);\n\t\treturn result;\n\t}",
"public void readData(BufferedReader in) throws IOException {\r\n String line, value;\r\n // skip old variables if still present\r\n lexOptions.readData(in);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n try {\r\n tlpParams = (TreebankLangParserParams) Class.forName(value).newInstance();\r\n } catch (Exception e) {\r\n IOException ioe = new IOException(\"Problem instantiating parserParams: \" + line);\r\n ioe.initCause(e);\r\n throw ioe;\r\n }\r\n line = in.readLine();\r\n // ensure backwards compatibility\r\n if (line.matches(\"^forceCNF.*\")) {\r\n value = line.substring(line.indexOf(' ') + 1);\r\n forceCNF = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n }\r\n value = line.substring(line.indexOf(' ') + 1);\r\n doPCFG = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n doDep = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n freeDependencies = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n directional = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n genStop = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n distance = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n coarseDistance = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n dcTags = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n if ( ! line.matches(\"^nPrune.*\")) {\r\n throw new RuntimeException(\"Expected nPrune, found: \" + line);\r\n }\r\n value = line.substring(line.indexOf(' ') + 1);\r\n nodePrune = Boolean.parseBoolean(value);\r\n line = in.readLine(); // get rid of last line\r\n if (line.length() != 0) {\r\n throw new RuntimeException(\"Expected blank line, found: \" + line);\r\n }\r\n }",
"private synchronized HostServerGroupEffect getHostEffect(PathAddress address, String host, Resource root) {\n if (requiresMapping) {\n map(root);\n requiresMapping = false;\n }\n Set<String> mapped = hostsToGroups.get(host);\n if (mapped == null) {\n // Unassigned host. Treat like an unassigned profile or socket-binding-group;\n // i.e. available to all server group scoped roles.\n // Except -- WFLY-2085 -- the master HC is not open to all s-g-s-rs\n Resource hostResource = root.getChild(PathElement.pathElement(HOST, host));\n if (hostResource != null) {\n ModelNode dcModel = hostResource.getModel().get(DOMAIN_CONTROLLER);\n if (!dcModel.hasDefined(REMOTE)) {\n mapped = Collections.emptySet(); // prevents returning HostServerGroupEffect.forUnassignedHost(address, host)\n }\n }\n }\n return mapped == null ? HostServerGroupEffect.forUnassignedHost(address, host)\n : HostServerGroupEffect.forMappedHost(address, mapped, host);\n\n }",
"private void addSingleUnique(StringBuilder sb, FieldType fieldType, List<String> additionalArgs,\n\t\t\tList<String> statementsAfter) {\n\t\tStringBuilder alterSb = new StringBuilder();\n\t\talterSb.append(\" UNIQUE (\");\n\t\tappendEscapedEntityName(alterSb, fieldType.getColumnName());\n\t\talterSb.append(')');\n\t\tadditionalArgs.add(alterSb.toString());\n\t}",
"public BoxFile.Info commit(String digest, List<BoxFileUploadSessionPart> parts,\n Map<String, String> attributes, String ifMatch, String ifNoneMatch) {\n\n URL commitURL = this.sessionInfo.getSessionEndpoints().getCommitEndpoint();\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), commitURL, HttpMethod.POST);\n request.addHeader(HttpHeaders.DIGEST, DIGEST_HEADER_PREFIX_SHA + digest);\n request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON);\n\n if (ifMatch != null) {\n request.addHeader(HttpHeaders.IF_MATCH, ifMatch);\n }\n\n if (ifNoneMatch != null) {\n request.addHeader(HttpHeaders.IF_NONE_MATCH, ifNoneMatch);\n }\n\n //Creates the body of the request\n String body = this.getCommitBody(parts, attributes);\n request.setBody(body);\n\n BoxAPIResponse response = request.send();\n //Retry the commit operation after the given number of seconds if the HTTP response code is 202.\n if (response.getResponseCode() == 202) {\n String retryInterval = response.getHeaderField(\"retry-after\");\n if (retryInterval != null) {\n try {\n Thread.sleep(new Integer(retryInterval) * 1000);\n } catch (InterruptedException ie) {\n throw new BoxAPIException(\"Commit retry failed. \", ie);\n }\n\n return this.commit(digest, parts, attributes, ifMatch, ifNoneMatch);\n }\n }\n\n if (response instanceof BoxJSONResponse) {\n //Create the file instance from the response\n return this.getFile((BoxJSONResponse) response);\n } else {\n throw new BoxAPIException(\"Commit response content type is not application/json. The response code : \"\n + response.getResponseCode());\n }\n }",
"private <T> void add(EjbDescriptor<T> ejbDescriptor) {\n InternalEjbDescriptor<T> internalEjbDescriptor = InternalEjbDescriptor.of(ejbDescriptor);\n ejbByName.put(ejbDescriptor.getEjbName(), internalEjbDescriptor);\n ejbByClass.put(ejbDescriptor.getBeanClass(), internalEjbDescriptor.getEjbName());\n }",
"public V get(final K1 firstKey, final K2 secondKey) {\n\t\t// existence check on inner map\n\t\tfinal HashMap<K2, V> innerMap = map.get(firstKey);\n\t\tif( innerMap == null ) {\n\t\t\treturn null;\n\t\t}\n\t\treturn innerMap.get(secondKey);\n\t}"
] |
Unlink the specified reference object.
More info see OJB doc.
@param source The source object with the specified reference field.
@param attributeName The field name of the reference to unlink.
@param target The referenced object to unlink. | [
"public boolean unlink(Object source, String attributeName, Object target)\r\n {\r\n return linkOrUnlink(false, source, attributeName, false);\r\n }"
] | [
"public static BoxConfig readFrom(Reader reader) throws IOException {\n JsonObject config = JsonObject.readFrom(reader);\n JsonObject settings = (JsonObject) config.get(\"boxAppSettings\");\n String clientId = settings.get(\"clientID\").asString();\n String clientSecret = settings.get(\"clientSecret\").asString();\n JsonObject appAuth = (JsonObject) settings.get(\"appAuth\");\n String publicKeyId = appAuth.get(\"publicKeyID\").asString();\n String privateKey = appAuth.get(\"privateKey\").asString();\n String passphrase = appAuth.get(\"passphrase\").asString();\n String enterpriseId = config.get(\"enterpriseID\").asString();\n return new BoxConfig(clientId, clientSecret, enterpriseId, publicKeyId, privateKey, passphrase);\n }",
"public static String getPublicIPAddress() throws Exception {\n final String IPV4_REGEX = \"\\\\A(25[0-5]|2[0-4]\\\\d|[0-1]?\\\\d?\\\\d)(\\\\.(25[0-5]|2[0-4]\\\\d|[0-1]?\\\\d?\\\\d)){3}\\\\z\";\n\n String ipAddr = null;\n Enumeration e = NetworkInterface.getNetworkInterfaces();\n while (e.hasMoreElements()) {\n NetworkInterface n = (NetworkInterface) e.nextElement();\n Enumeration ee = n.getInetAddresses();\n while (ee.hasMoreElements()) {\n InetAddress i = (InetAddress) ee.nextElement();\n\n // Pick the first non loop back address\n if ((!i.isLoopbackAddress() && i.isSiteLocalAddress()) ||\n i.getHostAddress().matches(IPV4_REGEX)) {\n ipAddr = i.getHostAddress();\n break;\n }\n }\n if (ipAddr != null) {\n break;\n }\n }\n\n return ipAddr;\n }",
"public Optional<SoyMsgBundle> resolve(final Optional<Locale> locale) throws IOException {\n if (!locale.isPresent()) {\n return Optional.absent();\n }\n\n synchronized (msgBundles) {\n SoyMsgBundle soyMsgBundle = null;\n if (isHotReloadModeOff()) {\n soyMsgBundle = msgBundles.get(locale.get());\n }\n if (soyMsgBundle == null) {\n soyMsgBundle = createSoyMsgBundle(locale.get());\n if (soyMsgBundle == null) {\n soyMsgBundle = createSoyMsgBundle(new Locale(locale.get().getLanguage()));\n }\n\n if (soyMsgBundle == null && fallbackToEnglish) {\n soyMsgBundle = createSoyMsgBundle(Locale.ENGLISH);\n }\n\n if (soyMsgBundle == null) {\n return Optional.absent();\n }\n\n if (isHotReloadModeOff()) {\n msgBundles.put(locale.get(), soyMsgBundle);\n }\n }\n\n return Optional.fromNullable(soyMsgBundle);\n }\n }",
"public static Date parseEpochTimestamp(String value)\n {\n Date result = null;\n\n if (value.length() > 0)\n {\n if (!value.equals(\"-1 -1\"))\n {\n Calendar cal = DateHelper.popCalendar(JAVA_EPOCH);\n\n int index = value.indexOf(' ');\n if (index == -1)\n {\n if (value.length() < 6)\n {\n value = \"000000\" + value;\n value = value.substring(value.length() - 6);\n }\n\n int hours = Integer.parseInt(value.substring(0, 2));\n int minutes = Integer.parseInt(value.substring(2, 4));\n int seconds = Integer.parseInt(value.substring(4));\n\n cal.set(Calendar.HOUR, hours);\n cal.set(Calendar.MINUTE, minutes);\n cal.set(Calendar.SECOND, seconds);\n }\n else\n {\n long astaDays = Long.parseLong(value.substring(0, index));\n int astaSeconds = Integer.parseInt(value.substring(index + 1));\n\n cal.add(Calendar.DAY_OF_YEAR, (int) (astaDays - ASTA_EPOCH));\n cal.set(Calendar.MILLISECOND, 0);\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.HOUR, 0);\n cal.add(Calendar.SECOND, astaSeconds);\n }\n\n result = cal.getTime();\n DateHelper.pushCalendar(cal);\n }\n }\n\n return result;\n }",
"public static final Date utc2date(Long time) {\n\n // don't accept negative values\n if (time == null || time < 0) return null;\n \n // add the timezone offset\n time += timezoneOffsetMillis(new Date(time));\n\n return new Date(time);\n }",
"public static csvserver_spilloverpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_spilloverpolicy_binding obj = new csvserver_spilloverpolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_spilloverpolicy_binding response[] = (csvserver_spilloverpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public final void setWeekDays(SortedSet<WeekDay> weekDays) {\n\n m_weekDays.clear();\n if (null != weekDays) {\n m_weekDays.addAll(weekDays);\n }\n }",
"public void writeTo(Writer destination) {\n Element eltRuleset = new Element(\"ruleset\");\n addAttribute(eltRuleset, \"name\", name);\n addChild(eltRuleset, \"description\", description);\n for (PmdRule pmdRule : rules) {\n Element eltRule = new Element(\"rule\");\n addAttribute(eltRule, \"ref\", pmdRule.getRef());\n addAttribute(eltRule, \"class\", pmdRule.getClazz());\n addAttribute(eltRule, \"message\", pmdRule.getMessage());\n addAttribute(eltRule, \"name\", pmdRule.getName());\n addAttribute(eltRule, \"language\", pmdRule.getLanguage());\n addChild(eltRule, \"priority\", String.valueOf(pmdRule.getPriority()));\n if (pmdRule.hasProperties()) {\n Element ruleProperties = processRuleProperties(pmdRule);\n if (ruleProperties.getContentSize() > 0) {\n eltRule.addContent(ruleProperties);\n }\n }\n eltRuleset.addContent(eltRule);\n }\n XMLOutputter serializer = new XMLOutputter(Format.getPrettyFormat());\n try {\n serializer.output(new Document(eltRuleset), destination);\n } catch (IOException e) {\n throw new IllegalStateException(\"An exception occurred while serializing PmdRuleSet.\", e);\n }\n }",
"public void setKey(int keyIndex, float time, final float[] values)\n {\n int index = keyIndex * mFloatsPerKey;\n Integer valSize = mFloatsPerKey-1;\n\n if (values.length != valSize)\n {\n throw new IllegalArgumentException(\"This key needs \" + valSize.toString() + \" float per value\");\n }\n mKeys[index] = time;\n System.arraycopy(values, 0, mKeys, index + 1, values.length);\n }"
] |
Use this API to flush cachecontentgroup resources. | [
"public static base_responses flush(nitro_service client, cachecontentgroup resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcachecontentgroup flushresources[] = new cachecontentgroup[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tflushresources[i] = new cachecontentgroup();\n\t\t\t\tflushresources[i].name = resources[i].name;\n\t\t\t\tflushresources[i].query = resources[i].query;\n\t\t\t\tflushresources[i].host = resources[i].host;\n\t\t\t\tflushresources[i].selectorvalue = resources[i].selectorvalue;\n\t\t\t\tflushresources[i].force = resources[i].force;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, flushresources,\"flush\");\n\t\t}\n\t\treturn result;\n\t}"
] | [
"private void readAssignment(Resource resource, Assignment assignment)\n {\n Task task = m_activityMap.get(assignment.getActivity());\n if (task != null)\n {\n task.addResourceAssignment(resource);\n }\n }",
"public AsciiTable setHtmlElementTranslator(HtmlElementTranslator htmlElementTranslator) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setHtmlElementTranslator(htmlElementTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"private boolean isSecuredByPolicy(Server server) {\n boolean isSecured = false;\n\n EndpointInfo ei = server.getEndpoint().getEndpointInfo();\n\n PolicyEngine pe = bus.getExtension(PolicyEngine.class);\n if (null == pe) {\n LOG.finest(\"No Policy engine found\");\n return isSecured;\n }\n\n Destination destination = server.getDestination();\n EndpointPolicy ep = pe.getServerEndpointPolicy(ei, destination, null);\n Collection<Assertion> assertions = ep.getChosenAlternative();\n for (Assertion a : assertions) {\n if (a instanceof TransportBinding) {\n TransportBinding tb = (TransportBinding) a;\n TransportToken tt = tb.getTransportToken();\n AbstractToken t = tt.getToken();\n if (t instanceof HttpsToken) {\n isSecured = true;\n break;\n }\n }\n }\n\n Policy policy = ep.getPolicy();\n List<PolicyComponent> pcList = policy.getPolicyComponents();\n for (PolicyComponent a : pcList) {\n if (a instanceof TransportBinding) {\n TransportBinding tb = (TransportBinding) a;\n TransportToken tt = tb.getTransportToken();\n AbstractToken t = tt.getToken();\n if (t instanceof HttpsToken) {\n isSecured = true;\n break;\n }\n }\n }\n\n return isSecured;\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 static List<String> getAllUserStoreNamesOnNode(AdminClient adminClient, Integer nodeId) {\n List<String> storeNames = Lists.newArrayList();\n List<StoreDefinition> storeDefinitionList = adminClient.metadataMgmtOps.getRemoteStoreDefList(nodeId)\n .getValue();\n\n for(StoreDefinition storeDefinition: storeDefinitionList) {\n storeNames.add(storeDefinition.getName());\n }\n return storeNames;\n }",
"private static void parseStencilSet(JSONObject modelJSON,\n Diagram current) throws JSONException {\n // get stencil type\n if (modelJSON.has(\"stencilset\")) {\n JSONObject object = modelJSON.getJSONObject(\"stencilset\");\n String url = null;\n String namespace = null;\n\n if (object.has(\"url\")) {\n url = object.getString(\"url\");\n }\n\n if (object.has(\"namespace\")) {\n namespace = object.getString(\"namespace\");\n }\n\n current.setStencilset(new StencilSet(url,\n namespace));\n }\n }",
"public int size(final K1 firstKey) {\n\t\t// existence check on inner map\n\t\tfinal HashMap<K2, HashMap<K3, V>> innerMap = map.get(firstKey);\n\t\tif( innerMap == null ) {\n\t\t\treturn 0;\n\t\t}\n\t\treturn innerMap.size();\n\t}",
"public void setRGB(int red, int green, int blue) throws Exception {\r\n\r\n CmsColor color = new CmsColor();\r\n color.setRGB(red, green, blue);\r\n\r\n m_red = red;\r\n m_green = green;\r\n m_blue = blue;\r\n m_hue = color.getHue();\r\n m_saturation = color.getSaturation();\r\n m_brightness = color.getValue();\r\n\r\n m_tbRed.setText(Integer.toString(m_red));\r\n m_tbGreen.setText(Integer.toString(m_green));\r\n m_tbBlue.setText(Integer.toString(m_blue));\r\n m_tbHue.setText(Integer.toString(m_hue));\r\n m_tbSaturation.setText(Integer.toString(m_saturation));\r\n m_tbBrightness.setText(Integer.toString(m_brightness));\r\n m_tbHexColor.setText(color.getHex());\r\n setPreview(color.getHex());\r\n\r\n updateSliders();\r\n }",
"private RawGcsCreationToken put(final GcsRestCreationToken token, ByteBuffer chunk,\n final boolean isFinalChunk, long timeoutMillis) throws IOException {\n final int length = chunk.remaining();\n HTTPRequest req = createPutRequest(token, chunk, isFinalChunk, timeoutMillis, length);\n HTTPRequestInfo info = new HTTPRequestInfo(req);\n HTTPResponse response;\n try {\n response = urlfetch.fetch(req);\n } catch (IOException e) {\n throw createIOException(info, e);\n }\n return handlePutResponse(token, isFinalChunk, length, info, response);\n }"
] |
Make a copy of JobContext of current thread
@return the copy of current job context or an empty job context | [
"static JobContext copy() {\n JobContext current = current_.get();\n //JobContext ctxt = new JobContext(keepParent ? current : null);\n JobContext ctxt = new JobContext(null);\n if (null != current) {\n ctxt.bag_.putAll(current.bag_);\n }\n return ctxt;\n }"
] | [
"public static String lookupIfEmpty( final String value,\n final Map<String, String> props,\n final String key ) {\n return value != null ? value : props.get(key);\n }",
"public void sendValue(int nodeId, int endpoint, int value) {\n\t\tZWaveNode node = this.getNode(nodeId);\n\t\tZWaveSetCommands zwaveCommandClass = null;\n\t\tSerialMessage serialMessage = null;\n\t\t\n\t\tfor (ZWaveCommandClass.CommandClass commandClass : new ZWaveCommandClass.CommandClass[] { ZWaveCommandClass.CommandClass.SWITCH_MULTILEVEL, ZWaveCommandClass.CommandClass.SWITCH_BINARY, ZWaveCommandClass.CommandClass.BASIC }) {\n\t\t\tzwaveCommandClass = (ZWaveSetCommands)node.resolveCommandClass(commandClass, endpoint);\n\t\t\tif (zwaveCommandClass != null)\n\t\t\t\tbreak;\n\t\t}\n\t\t\n\t\tif (zwaveCommandClass == null) {\n\t\t\tlogger.error(\"No Command Class found on node {}, instance/endpoint {} to request level.\", nodeId, endpoint);\n\t\t\treturn;\n\t\t}\n\t\t\t \n\t\tserialMessage = node.encapsulate(zwaveCommandClass.setValueMessage(value), (ZWaveCommandClass)zwaveCommandClass, endpoint);\n\t\t\n\t\tif (serialMessage != null)\n\t\t\tthis.sendData(serialMessage);\n\t\t\n\t\t// read back level on \"ON\" command\n\t\tif (((ZWaveCommandClass)zwaveCommandClass).getCommandClass() == ZWaveCommandClass.CommandClass.SWITCH_MULTILEVEL && value == 255)\n\t\t\tthis.requestValue(nodeId, endpoint);\n\t}",
"private static FieldType getPlaceholder(final Class<?> type, final int fieldID)\n {\n return new FieldType()\n {\n @Override public FieldTypeClass getFieldTypeClass()\n {\n return FieldTypeClass.UNKNOWN;\n }\n\n @Override public String name()\n {\n return \"UNKNOWN\";\n }\n\n @Override public int getValue()\n {\n return fieldID;\n }\n\n @Override public String getName()\n {\n return \"Unknown \" + (type == null ? \"\" : type.getSimpleName() + \"(\" + fieldID + \")\");\n }\n\n @Override public String getName(Locale locale)\n {\n return getName();\n }\n\n @Override public DataType getDataType()\n {\n return null;\n }\n\n @Override public FieldType getUnitsType()\n {\n return null;\n }\n\n @Override public String toString()\n {\n return getName();\n }\n };\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 }",
"@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 }",
"@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}",
"private double sumSquaredDiffs()\n { \n double mean = getArithmeticMean();\n double squaredDiffs = 0;\n for (int i = 0; i < getSize(); i++)\n {\n double diff = mean - dataSet[i];\n squaredDiffs += (diff * diff);\n }\n return squaredDiffs;\n }",
"public int executeRefresh(DatabaseConnection databaseConnection, T data, ObjectCache objectCache)\n\t\t\tthrows SQLException {\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tID id = (ID) idField.extractJavaFieldValue(data);\n\t\t// we don't care about the cache here\n\t\tT result = super.execute(databaseConnection, id, null);\n\t\tif (result == null) {\n\t\t\treturn 0;\n\t\t}\n\t\t// copy each field from the result into the passed in object\n\t\tfor (FieldType fieldType : resultsFieldTypes) {\n\t\t\tif (fieldType != idField) {\n\t\t\t\tfieldType.assignField(connectionSource, data, fieldType.extractJavaFieldValue(result), false,\n\t\t\t\t\t\tobjectCache);\n\t\t\t}\n\t\t}\n\t\treturn 1;\n\t}",
"public ClientConfig setIdleConnectionTimeout(long idleConnectionTimeout, TimeUnit unit) {\n if (idleConnectionTimeout <= 0) {\n this.idleConnectionTimeoutMs = -1;\n } else {\n if(unit.toMinutes(idleConnectionTimeout) < 10) {\n throw new IllegalArgumentException(\"idleConnectionTimeout should be minimum of 10 minutes\");\n }\n this.idleConnectionTimeoutMs = unit.toMillis(idleConnectionTimeout);\n }\n return this;\n }"
] |
Returns Task field name of supplied code no.
@param key - the code no of required Task field
@return - field name | [
"private String getTaskField(int key)\n {\n String result = null;\n\n if ((key > 0) && (key < m_taskNames.length))\n {\n result = m_taskNames[key];\n }\n\n return (result);\n }"
] | [
"public static rnatparam get(nitro_service service) throws Exception{\n\t\trnatparam obj = new rnatparam();\n\t\trnatparam[] response = (rnatparam[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"private Observable<Indexable> invokeReadyTasksAsync(final InvocationContext context) {\n TaskGroupEntry<TaskItem> readyTaskEntry = super.getNext();\n final List<Observable<Indexable>> observables = new ArrayList<>();\n // Enumerate the ready tasks (those with dependencies resolved) and kickoff them concurrently\n //\n while (readyTaskEntry != null) {\n final TaskGroupEntry<TaskItem> currentEntry = readyTaskEntry;\n final TaskItem currentTaskItem = currentEntry.data();\n if (currentTaskItem instanceof ProxyTaskItem) {\n observables.add(invokeAfterPostRunAsync(currentEntry, context));\n } else {\n observables.add(invokeTaskAsync(currentEntry, context));\n }\n readyTaskEntry = super.getNext();\n }\n return Observable.mergeDelayError(observables);\n }",
"public 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 void addStory(File caseManager, String storyName,\n String testPath, String user, String feature, String benefit) throws BeastException {\n FileWriter caseManagerWriter;\n\n String storyClass = SystemReader.createClassName(storyName);\n try {\n BufferedReader reader = new BufferedReader(new FileReader(\n caseManager));\n String targetLine1 = \" public void \"\n + MASReader.createFirstLowCaseName(storyName) + \"() {\";\n String targetLine2 = \" Result result = JUnitCore.runClasses(\" + testPath + \".\"\n + storyClass + \".class);\";\n String in;\n while ((in = reader.readLine()) != null) {\n if (in.equals(targetLine1)) {\n while ((in = reader.readLine()) != null) {\n if (in.equals(targetLine2)) {\n reader.close();\n // This test is already written in the case manager.\n return;\n }\n }\n reader.close();\n throw new BeastException(\"Two different stories with the same name (same method name) are being created in the same CaseManager file. That is not possible. Please, change the name of the story: \" + testPath + \".\"\n + storyClass + \".java\");\n }\n }\n reader.close();\n caseManagerWriter = new FileWriter(caseManager, true);\n caseManagerWriter.write(\" /**\\n\");\n caseManagerWriter.write(\" * This is the story: \" + storyName\n + \"\\n\");\n caseManagerWriter.write(\" * requested by: \" + user + \"\\n\");\n caseManagerWriter.write(\" * providing the feature: \" + feature\n + \"\\n\");\n caseManagerWriter.write(\" * so the user gets the benefit: \"\n + benefit + \"\\n\");\n caseManagerWriter.write(\" */\\n\");\n caseManagerWriter.write(\" @Test\\n\");\n caseManagerWriter.write(\" public void \"\n + MASReader.createFirstLowCaseName(storyName) + \"() {\\n\");\n caseManagerWriter.write(\" Result result = JUnitCore.runClasses(\" + testPath\n + \".\" + storyClass + \".class);\\n\");\n caseManagerWriter.write(\" Assert.assertTrue(result.wasSuccessful());\\n\");\n caseManagerWriter.write(\" }\\n\");\n caseManagerWriter.write(\"\\n\");\n caseManagerWriter.flush();\n caseManagerWriter.close();\n } catch (IOException e) {\n Logger logger = Logger.getLogger(\"CreateMASCaseManager.createTest\");\n logger.info(\"ERROR writing the file\");\n }\n\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 }",
"private void readRecurringData(ProjectCalendarException bce, Project.Calendars.Calendar.Exceptions.Exception exception)\n {\n RecurrenceType rt = getRecurrenceType(NumberHelper.getInt(exception.getType()));\n if (rt != null)\n {\n RecurringData rd = new RecurringData();\n rd.setStartDate(bce.getFromDate());\n rd.setFinishDate(bce.getToDate());\n rd.setRecurrenceType(rt);\n rd.setRelative(getRelative(NumberHelper.getInt(exception.getType())));\n rd.setOccurrences(NumberHelper.getInteger(exception.getOccurrences()));\n\n switch (rd.getRecurrenceType())\n {\n case DAILY:\n {\n rd.setFrequency(getFrequency(exception));\n break;\n }\n\n case WEEKLY:\n {\n rd.setWeeklyDaysFromBitmap(NumberHelper.getInteger(exception.getDaysOfWeek()), DAY_MASKS);\n rd.setFrequency(getFrequency(exception));\n break;\n }\n\n case MONTHLY:\n {\n if (rd.getRelative())\n {\n rd.setDayOfWeek(Day.getInstance(NumberHelper.getInt(exception.getMonthItem()) - 2));\n rd.setDayNumber(Integer.valueOf(NumberHelper.getInt(exception.getMonthPosition()) + 1));\n }\n else\n {\n rd.setDayNumber(NumberHelper.getInteger(exception.getMonthDay()));\n }\n rd.setFrequency(getFrequency(exception));\n break;\n }\n\n case YEARLY:\n {\n if (rd.getRelative())\n {\n rd.setDayOfWeek(Day.getInstance(NumberHelper.getInt(exception.getMonthItem()) - 2));\n rd.setDayNumber(Integer.valueOf(NumberHelper.getInt(exception.getMonthPosition()) + 1));\n }\n else\n {\n rd.setDayNumber(NumberHelper.getInteger(exception.getMonthDay()));\n }\n rd.setMonthNumber(Integer.valueOf(NumberHelper.getInt(exception.getMonth()) + 1));\n break;\n }\n }\n\n if (rd.getRecurrenceType() != RecurrenceType.DAILY || rd.getDates().length > 1)\n {\n bce.setRecurring(rd);\n }\n }\n }",
"public @Nullable ChangeEvent<BsonDocument> getUnprocessedEventForDocumentId(\n final BsonValue documentId\n ) {\n final ChangeEvent<BsonDocument> event;\n nsLock.readLock().lock();\n try {\n event = this.events.get(documentId);\n } finally {\n nsLock.readLock().unlock();\n }\n\n nsLock.writeLock().lock();\n try {\n this.events.remove(documentId);\n return event;\n } finally {\n nsLock.writeLock().unlock();\n }\n }",
"public Double score(final String member) {\n return doWithJedis(new JedisCallable<Double>() {\n @Override\n public Double call(Jedis jedis) {\n return jedis.zscore(getKey(), member);\n }\n });\n }",
"public FieldType getFieldByAlias(FieldTypeClass typeClass, String alias)\n {\n return m_aliasMap.get(new Pair<FieldTypeClass, String>(typeClass, alias));\n }"
] |
Starts or stops capturing.
@param capture If true, capturing is started. If false, it is stopped.
@param fps Capturing FPS (frames per second). | [
"public void setCapture(boolean capture, float fps) {\n capturing = capture;\n NativeTextureCapturer.setCapture(getNative(), capture, fps);\n }"
] | [
"public static BoxUser.Info createEnterpriseUser(BoxAPIConnection api, String login, String name) {\n return createEnterpriseUser(api, login, name, null);\n }",
"public static final GVRPickedObject[] pickVisible(GVRScene scene) {\n sFindObjectsLock.lock();\n try {\n final GVRPickedObject[] result = NativePicker.pickVisible(scene.getNative());\n return result;\n } finally {\n sFindObjectsLock.unlock();\n }\n }",
"public void printInterceptorChain(InterceptorChain chain) {\n Iterator<Interceptor<? extends Message>> it = chain.iterator();\n String phase = \"\";\n StringBuilder builder = null;\n while (it.hasNext()) {\n Interceptor<? extends Message> interceptor = it.next();\n if (interceptor instanceof DemoInterceptor) {\n continue;\n }\n if (interceptor instanceof PhaseInterceptor) {\n PhaseInterceptor pi = (PhaseInterceptor)interceptor;\n if (!phase.equals(pi.getPhase())) {\n if (builder != null) {\n System.out.println(builder.toString());\n } else {\n builder = new StringBuilder(100);\n }\n builder.setLength(0);\n builder.append(\" \");\n builder.append(pi.getPhase());\n builder.append(\": \");\n phase = pi.getPhase();\n }\n String id = pi.getId();\n int idx = id.lastIndexOf('.');\n if (idx != -1) {\n id = id.substring(idx + 1);\n }\n builder.append(id);\n builder.append(' ');\n }\n }\n\n }",
"protected void parseOperationsLR(Symbol ops[], TokenList tokens, Sequence sequence) {\n\n if( tokens.size == 0 )\n return;\n\n TokenList.Token token = tokens.first;\n\n if( token.getType() != Type.VARIABLE )\n throw new ParseError(\"The first token in an equation needs to be a variable and not \"+token);\n\n boolean hasLeft = false;\n while( token != null ) {\n if( token.getType() == Type.FUNCTION ) {\n throw new ParseError(\"Function encountered with no parentheses\");\n } else if( token.getType() == Type.VARIABLE ) {\n if( hasLeft ) {\n if( isTargetOp(token.previous,ops)) {\n token = createOp(token.previous.previous,token.previous,token,tokens,sequence);\n }\n } else {\n hasLeft = true;\n }\n } else {\n if( token.previous.getType() == Type.SYMBOL ) {\n throw new ParseError(\"Two symbols next to each other. \"+token.previous+\" and \"+token);\n }\n }\n token = token.next;\n }\n }",
"public void addIterator(OJBIterator iterator)\r\n {\r\n /**\r\n * only add iterators that are not null and non-empty.\r\n */\r\n if (iterator != null)\r\n {\r\n if (iterator.hasNext())\r\n {\r\n setNextIterator();\r\n m_rsIterators.add(iterator);\r\n }\r\n }\r\n }",
"@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n\tprivate IntegrationFlowBuilder getFlowBuilder() {\n\n\t\tIntegrationFlowBuilder flowBuilder;\n\t\tURLName urlName = this.properties.getUrl();\n\n\t\tif (this.properties.isIdleImap()) {\n\t\t\tflowBuilder = getIdleImapFlow(urlName);\n\t\t}\n\t\telse {\n\n\t\t\tMailInboundChannelAdapterSpec adapterSpec;\n\t\t\tswitch (urlName.getProtocol().toUpperCase()) {\n\t\t\t\tcase \"IMAP\":\n\t\t\t\tcase \"IMAPS\":\n\t\t\t\t\tadapterSpec = getImapFlowBuilder(urlName);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"POP3\":\n\t\t\t\tcase \"POP3S\":\n\t\t\t\t\tadapterSpec = getPop3FlowBuilder(urlName);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\t\"Unsupported mail protocol: \" + urlName.getProtocol());\n\t\t\t}\n\t\t\tflowBuilder = IntegrationFlows.from(\n\t\t\t\t\tadapterSpec.javaMailProperties(getJavaMailProperties(urlName))\n\t\t\t\t\t\t\t.selectorExpression(this.properties.getExpression())\n\t\t\t\t\t\t\t.shouldDeleteMessages(this.properties.isDelete()),\n\t\t\t\t\tnew Consumer<SourcePollingChannelAdapterSpec>() {\n\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void accept(\n\t\t\t\t\t\t\t\tSourcePollingChannelAdapterSpec sourcePollingChannelAdapterSpec) {\n\t\t\t\t\t\t\tsourcePollingChannelAdapterSpec.poller(MailSourceConfiguration.this.defaultPoller);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t});\n\n\t\t}\n\t\treturn flowBuilder;\n\t}",
"private void populateRelation(TaskField field, Task sourceTask, String relationship) throws MPXJException\n {\n int index = 0;\n int length = relationship.length();\n\n //\n // Extract the identifier\n //\n while ((index < length) && (Character.isDigit(relationship.charAt(index)) == true))\n {\n ++index;\n }\n\n Integer taskID;\n try\n {\n taskID = Integer.valueOf(relationship.substring(0, index));\n }\n\n catch (NumberFormatException ex)\n {\n throw new MPXJException(MPXJException.INVALID_FORMAT + \" '\" + relationship + \"'\");\n }\n\n //\n // Now find the task, so we can extract the unique ID\n //\n Task targetTask;\n if (field == TaskField.PREDECESSORS)\n {\n targetTask = m_projectFile.getTaskByID(taskID);\n }\n else\n {\n targetTask = m_projectFile.getTaskByUniqueID(taskID);\n }\n\n //\n // If we haven't reached the end, we next expect to find\n // SF, SS, FS, FF\n //\n RelationType type = null;\n Duration lag = null;\n\n if (index == length)\n {\n type = RelationType.FINISH_START;\n lag = Duration.getInstance(0, TimeUnit.DAYS);\n }\n else\n {\n if ((index + 1) == length)\n {\n throw new MPXJException(MPXJException.INVALID_FORMAT + \" '\" + relationship + \"'\");\n }\n\n type = RelationTypeUtility.getInstance(m_locale, relationship.substring(index, index + 2));\n\n index += 2;\n\n if (index == length)\n {\n lag = Duration.getInstance(0, TimeUnit.DAYS);\n }\n else\n {\n if (relationship.charAt(index) == '+')\n {\n ++index;\n }\n\n lag = DurationUtility.getInstance(relationship.substring(index), m_formats.getDurationDecimalFormat(), m_locale);\n }\n }\n\n if (type == null)\n {\n throw new MPXJException(MPXJException.INVALID_FORMAT + \" '\" + relationship + \"'\");\n }\n\n // We have seen at least one example MPX file where an invalid task ID\n // is present. We'll ignore this as the schedule is otherwise valid.\n if (targetTask != null)\n {\n Relation relation = sourceTask.addPredecessor(targetTask, type, lag);\n m_eventManager.fireRelationReadEvent(relation);\n }\n }",
"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}",
"public static authenticationlocalpolicy_authenticationvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationlocalpolicy_authenticationvserver_binding obj = new authenticationlocalpolicy_authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationlocalpolicy_authenticationvserver_binding response[] = (authenticationlocalpolicy_authenticationvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Retains only beans which are enabled.
@param beans The mutable set of beans to filter
@param beanManager The bean manager
@return a mutable set of enabled beans | [
"public static <T extends Bean<?>> Set<T> removeDisabledBeans(Set<T> beans, final BeanManagerImpl beanManager) {\n if (beans.isEmpty()) {\n return beans;\n } else {\n for (Iterator<T> iterator = beans.iterator(); iterator.hasNext();) {\n if (!isBeanEnabled(iterator.next(), beanManager.getEnabled())) {\n iterator.remove();\n }\n }\n return beans;\n }\n }"
] | [
"private boolean isOrdinal(int paramType) {\n\t\tswitch ( paramType ) {\n\t\t\tcase Types.INTEGER:\n\t\t\tcase Types.NUMERIC:\n\t\t\tcase Types.SMALLINT:\n\t\t\tcase Types.TINYINT:\n\t\t\tcase Types.BIGINT:\n\t\t\tcase Types.DECIMAL: //for Oracle Driver\n\t\t\tcase Types.DOUBLE: //for Oracle Driver\n\t\t\tcase Types.FLOAT: //for Oracle Driver\n\t\t\t\treturn true;\n\t\t\tcase Types.CHAR:\n\t\t\tcase Types.LONGVARCHAR:\n\t\t\tcase Types.VARCHAR:\n\t\t\t\treturn false;\n\t\t\tdefault:\n\t\t\t\tthrow new HibernateException( \"Unable to persist an Enum in a column of SQL Type: \" + paramType );\n\t\t}\n\t}",
"private void sendCloseMessage() {\n\n this.lock(() -> {\n\n TcpChannelHub.this.writeMetaDataForKnownTID(0, outWire, null, 0);\n\n TcpChannelHub.this.outWire.writeDocument(false, w ->\n w.writeEventName(EventId.onClientClosing).text(\"\"));\n\n }, TryLock.LOCK);\n\n // wait up to 1 seconds to receive an close request acknowledgment from the server\n try {\n final boolean await = receivedClosedAcknowledgement.await(1, TimeUnit.SECONDS);\n if (!await)\n if (Jvm.isDebugEnabled(getClass()))\n Jvm.debug().on(getClass(), \"SERVER IGNORED CLOSE REQUEST: shutting down the client anyway as the \" +\n \"server did not respond to the close() request.\");\n } catch (InterruptedException ignore) {\n Thread.currentThread().interrupt();\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 }",
"private void handleGetVersionResponse(SerialMessage incomingMessage) {\n\t\tthis.ZWaveLibraryType = incomingMessage.getMessagePayloadByte(12);\n\t\tthis.zWaveVersion = new String(ArrayUtils.subarray(incomingMessage.getMessagePayload(), 0, 11));\n\t\tlogger.debug(String.format(\"Got MessageGetVersion response. Version = %s, Library Type = 0x%02X\", zWaveVersion, ZWaveLibraryType));\n\t}",
"public static boolean isToStringMethod(Method method) {\n return (method != null && method.getName().equals(\"readString\") && method.getParameterTypes().length == 0);\n }",
"private String hibcProcess(String source) {\n\n // HIBC 2.6 allows up to 110 characters, not including the \"+\" prefix or the check digit\n if (source.length() > 110) {\n throw new OkapiException(\"Data too long for HIBC LIC\");\n }\n\n source = source.toUpperCase();\n if (!source.matches(\"[A-Z0-9-\\\\. \\\\$/+\\\\%]+?\")) {\n throw new OkapiException(\"Invalid characters in input\");\n }\n\n int counter = 41;\n for (int i = 0; i < source.length(); i++) {\n counter += positionOf(source.charAt(i), HIBC_CHAR_TABLE);\n }\n counter = counter % 43;\n\n char checkDigit = HIBC_CHAR_TABLE[counter];\n\n encodeInfo += \"HIBC Check Digit Counter: \" + counter + \"\\n\";\n encodeInfo += \"HIBC Check Digit: \" + checkDigit + \"\\n\";\n\n return \"+\" + source + checkDigit;\n }",
"private boolean detectWSAddressingFeature(InterceptorProvider provider, Bus bus) {\n //detect on the bus level\n if (bus.getFeatures() != null) {\n Iterator<Feature> busFeatures = bus.getFeatures().iterator();\n while (busFeatures.hasNext()) {\n Feature busFeature = busFeatures.next();\n if (busFeature instanceof WSAddressingFeature) {\n return true;\n }\n }\n }\n\n //detect on the endpoint/client level\n Iterator<Interceptor<? extends Message>> interceptors = provider.getInInterceptors().iterator();\n while (interceptors.hasNext()) {\n Interceptor<? extends Message> ic = interceptors.next();\n if (ic instanceof MAPAggregator) {\n return true;\n }\n }\n\n return false;\n }",
"public void prepareFilter( float transition ) {\n try {\n method.invoke( filter, new Object[] { new Float( transition ) } );\n }\n catch ( Exception e ) {\n throw new IllegalArgumentException(\"Error setting value for property: \"+property);\n }\n\t}",
"public static gslbservice_stats get(nitro_service service, String servicename) throws Exception{\n\t\tgslbservice_stats obj = new gslbservice_stats();\n\t\tobj.set_servicename(servicename);\n\t\tgslbservice_stats response = (gslbservice_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}"
] |
Add a dependency task group for this model.
@param dependency the dependency.
@return key to be used as parameter to taskResult(string) method to retrieve result of root
task in the given dependency task group | [
"protected String addDependency(TaskGroup.HasTaskGroup dependency) {\n Objects.requireNonNull(dependency);\n this.taskGroup().addDependencyTaskGroup(dependency.taskGroup());\n return dependency.taskGroup().key();\n }"
] | [
"public static void dumpNodeAnim(AiNodeAnim nodeAnim) {\n for (int i = 0; i < nodeAnim.getNumPosKeys(); i++) {\n System.out.println(i + \": \" + nodeAnim.getPosKeyTime(i) + \n \" ticks, \" + nodeAnim.getPosKeyVector(i, Jassimp.BUILTIN));\n }\n }",
"public static void checkOperatorIsValid(int operatorCode) {\n switch (operatorCode) {\n case OPERATOR_LT:\n case OPERATOR_LE:\n case OPERATOR_EQ:\n case OPERATOR_NE:\n case OPERATOR_GE:\n case OPERATOR_GT:\n case OPERATOR_UNKNOWN:\n return;\n default:\n throw new IllegalStateException(String.format(Locale.US, ERROR_INVALID_CODE, operatorCode));\n }\n }",
"public void forAllIndexDescriptorColumns(String template, Properties attributes) throws XDocletException\r\n {\r\n String fields = _curIndexDescriptorDef.getProperty(PropertyHelper.OJB_PROPERTY_FIELDS);\r\n FieldDescriptorDef fieldDef;\r\n String name;\r\n\r\n for (CommaListIterator it = new CommaListIterator(fields); it.hasNext();)\r\n {\r\n name = it.getNext();\r\n fieldDef = _curClassDef.getField(name);\r\n if (fieldDef == null)\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.INDEX_FIELD_MISSING,\r\n new String[]{name, _curIndexDescriptorDef.getName(), _curClassDef.getName()}));\r\n }\r\n _curIndexColumn = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN);\r\n generate(template);\r\n }\r\n _curIndexColumn = null;\r\n }",
"public void notifyHeaderItemMoved(int fromPosition, int toPosition) {\n if (fromPosition < 0 || toPosition < 0 || fromPosition >= headerItemCount || toPosition >= headerItemCount) {\n throw new IndexOutOfBoundsException(\"The given fromPosition \" + fromPosition + \" or toPosition \" + toPosition + \" is not within the position bounds for header items [0 - \" + (headerItemCount - 1) + \"].\");\n }\n notifyItemMoved(fromPosition, toPosition);\n }",
"public Script getScript(int id) {\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = SQLService.getInstance().getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_SCRIPT +\n \" WHERE id = ?\"\n );\n statement.setInt(1, id);\n results = statement.executeQuery();\n if (results.next()) {\n return scriptFromSQLResult(results);\n }\n } catch (Exception e) {\n\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return null;\n }",
"public void setReadTimeout(int readTimeout) {\n\t\tthis.client = this.client.newBuilder()\n\t\t\t\t.readTimeout(readTimeout, TimeUnit.MILLISECONDS)\n\t\t\t\t.build();\n\t}",
"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 base_response unset(nitro_service client, ntpserver resource, String[] args) throws Exception{\n\t\tntpserver unsetresource = new ntpserver();\n\t\tunsetresource.serverip = resource.serverip;\n\t\tunsetresource.servername = resource.servername;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"@SuppressWarnings(\"boxing\")\r\n public OAuth1Token getAccessToken(OAuth1RequestToken oAuthRequestToken, String verifier) {\r\n OAuth10aService service = new ServiceBuilder(apiKey)\r\n .apiSecret(sharedSecret)\r\n .build(FlickrApi.instance());\r\n\r\n // Flickr seems to return invalid token sometimes so retry a few times.\r\n // See http://www.flickr.com/groups/api/discuss/72157628028927244/\r\n OAuth1Token accessToken = null;\r\n boolean success = false;\r\n for (int i = 0; i < maxGetTokenRetries && !success; i++) {\r\n try {\r\n accessToken = service.getAccessToken(oAuthRequestToken, verifier);\r\n success = true;\r\n } catch (OAuthException | IOException | InterruptedException | ExecutionException e) {\r\n if (i == maxGetTokenRetries - 1) {\r\n logger.error(String.format(\"OAuthService.getAccessToken failing after %d tries, re-throwing exception\", i), e);\r\n throw new FlickrRuntimeException(e);\r\n } else {\r\n logger.warn(String.format(\"OAuthService.getAccessToken failed, try number %d: %s\", i, e.getMessage()));\r\n try {\r\n Thread.sleep(500);\r\n } catch (InterruptedException ie) {\r\n // Do nothing\r\n }\r\n }\r\n }\r\n }\r\n\r\n return accessToken;\r\n }"
] |
Returns the default jdbc type for the given java type.
@param javaType The qualified java type
@return The default jdbc type | [
"public static String getDefaultJdbcTypeFor(String javaType)\r\n {\r\n return _jdbcMappings.containsKey(javaType) ? (String)_jdbcMappings.get(javaType) : JDBC_DEFAULT_TYPE;\r\n }"
] | [
"public static base_responses update(nitro_service client, responderpolicy resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tresponderpolicy updateresources[] = new responderpolicy[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new responderpolicy();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].rule = resources[i].rule;\n\t\t\t\tupdateresources[i].action = resources[i].action;\n\t\t\t\tupdateresources[i].undefaction = resources[i].undefaction;\n\t\t\t\tupdateresources[i].comment = resources[i].comment;\n\t\t\t\tupdateresources[i].logaction = resources[i].logaction;\n\t\t\t\tupdateresources[i].appflowaction = resources[i].appflowaction;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public T modifyFile(final String name, final List<String> path, final byte[] existingHash, final byte[] newHash, final boolean isDirectory) {\n return modifyFile(name, path, existingHash, newHash, isDirectory, null);\n }",
"public static void closeWithWarning(Closeable c) {\n if (c != null) {\n try {\n c.close();\n } catch (IOException e) {\n LOG.warning(\"Caught exception during close(): \" + e);\n }\n }\n }",
"public List<Widget> getAllViews() {\n List<Widget> views = new ArrayList<>();\n for (Widget child: mContent.getChildren()) {\n Widget item = ((ListItemHostWidget) child).getGuest();\n if (item != null) {\n views.add(item);\n }\n }\n return views;\n }",
"public Reply getReplyInfo(String topicId, String replyId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_REPLIES_GET_INFO);\r\n parameters.put(\"topic_id\", topicId);\r\n parameters.put(\"reply_id\", replyId);\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 replyElement = response.getPayload();\r\n\r\n return parseReply(replyElement);\r\n }",
"public IExternalAccess getAgentsExternalAccess(String agent_name) {\n\n return cmsService.getExternalAccess(getAgentID(agent_name)).get(\n new ThreadSuspendable());\n }",
"public static Diagram parseJson(String json,\n Boolean keepGlossaryLink) throws JSONException {\n JSONObject modelJSON = new JSONObject(json);\n return parseJson(modelJSON,\n keepGlossaryLink);\n }",
"@Override\n public final Boolean optBool(final String key) {\n if (this.obj.optString(key, null) == null) {\n return null;\n } else {\n return this.obj.optBoolean(key);\n }\n }",
"private void readHeaderProperties(BufferedInputStream stream) throws IOException\n {\n String header = readHeaderString(stream);\n for (String property : header.split(\"\\\\|\"))\n {\n String[] expression = property.split(\"=\");\n m_properties.put(expression[0], expression[1]);\n }\n }"
] |
Print the common class node's properties | [
"private void nodeProperties(Options opt) {\n\tOptions def = opt.getGlobalOptions();\n\tif (opt.nodeFontName != def.nodeFontName)\n\t w.print(\",fontname=\\\"\" + opt.nodeFontName + \"\\\"\");\n\tif (opt.nodeFontColor != def.nodeFontColor)\n\t w.print(\",fontcolor=\\\"\" + opt.nodeFontColor + \"\\\"\");\n\tif (opt.nodeFontSize != def.nodeFontSize)\n\t w.print(\",fontsize=\" + fmt(opt.nodeFontSize));\n\tw.print(opt.shape.style);\n\tw.println(\"];\");\n }"
] | [
"public RedwoodConfiguration showOnlyChannels(final Object[] channels){\r\n tasks.add(new Runnable() { public void run() { Redwood.showOnlyChannels(channels); } });\r\n return this;\r\n }",
"public static ComplexNumber Divide(ComplexNumber z1, ComplexNumber z2) {\r\n\r\n ComplexNumber conj = ComplexNumber.Conjugate(z2);\r\n\r\n double a = z1.real * conj.real + ((z1.imaginary * conj.imaginary) * -1);\r\n double b = z1.real * conj.imaginary + (z1.imaginary * conj.real);\r\n\r\n double c = z2.real * conj.real + ((z2.imaginary * conj.imaginary) * -1);\r\n\r\n return new ComplexNumber(a / c, b / c);\r\n }",
"public Map<String, String> getUploadParameters() {\r\n Map<String, String> parameters = new TreeMap<>();\r\n\r\n\r\n String title = getTitle();\r\n if (title != null) {\r\n parameters.put(\"title\", title);\r\n }\r\n\r\n String description = getDescription();\r\n if (description != null) {\r\n parameters.put(\"description\", description);\r\n }\r\n\r\n Collection<String> tags = getTags();\r\n if (tags != null) {\r\n parameters.put(\"tags\", StringUtilities.join(tags, \" \"));\r\n }\r\n\r\n if (isHidden() != null) {\r\n parameters.put(\"hidden\", isHidden().booleanValue() ? \"1\" : \"0\");\r\n }\r\n\r\n if (getSafetyLevel() != null) {\r\n parameters.put(\"safety_level\", getSafetyLevel());\r\n }\r\n\r\n if (getContentType() != null) {\r\n parameters.put(\"content_type\", getContentType());\r\n }\r\n\r\n if (getPhotoId() != null) {\r\n parameters.put(\"photo_id\", getPhotoId());\r\n }\r\n\r\n parameters.put(\"is_public\", isPublicFlag() ? \"1\" : \"0\");\r\n parameters.put(\"is_family\", isFamilyFlag() ? \"1\" : \"0\");\r\n parameters.put(\"is_friend\", isFriendFlag() ? \"1\" : \"0\");\r\n parameters.put(\"async\", isAsync() ? \"1\" : \"0\");\r\n\r\n return parameters;\r\n }",
"public Response executeToResponse(HttpConnection connection) {\n InputStream is = null;\n try {\n is = this.executeToInputStream(connection);\n Response response = getResponse(is, Response.class, getGson());\n response.setStatusCode(connection.getConnection().getResponseCode());\n response.setReason(connection.getConnection().getResponseMessage());\n return response;\n } catch (IOException e) {\n throw new CouchDbException(\"Error retrieving response code or message.\", e);\n } finally {\n close(is);\n }\n }",
"public static long bytesToNumber(byte[] buffer, int start, int length) {\n long result = 0;\n for (int index = start; index < start + length; index++) {\n result = (result << 8) + unsign(buffer[index]);\n }\n return result;\n }",
"public synchronized void setSendingStatus(boolean send) throws IOException {\n if (isSendingStatus() == send) {\n return;\n }\n\n if (send) { // Start sending status packets.\n ensureRunning();\n if ((getDeviceNumber() < 1) || (getDeviceNumber() > 4)) {\n throw new IllegalStateException(\"Can only send status when using a standard player number, 1 through 4.\");\n }\n\n BeatFinder.getInstance().start();\n BeatFinder.getInstance().addLifecycleListener(beatFinderLifecycleListener);\n\n final AtomicBoolean stillRunning = new AtomicBoolean(true);\n sendingStatus = stillRunning; // Allow other threads to stop us when necessary.\n\n Thread sender = new Thread(null, new Runnable() {\n @Override\n public void run() {\n while (stillRunning.get()) {\n sendStatus();\n try {\n Thread.sleep(getStatusInterval());\n } catch (InterruptedException e) {\n logger.warn(\"beat-link VirtualCDJ status sender thread was interrupted; continuing\");\n }\n }\n }\n }, \"beat-link VirtualCdj status sender\");\n sender.setDaemon(true);\n sender.start();\n\n if (isSynced()) { // If we are supposed to be synced, we need to respond to master beats and tempo changes.\n addMasterListener(ourSyncMasterListener);\n }\n\n if (isPlaying()) { // Start the beat sender too, if we are supposed to be playing.\n beatSender.set(new BeatSender(metronome));\n }\n } else { // Stop sending status packets, and responding to master beats and tempo changes if we were synced.\n BeatFinder.getInstance().removeLifecycleListener(beatFinderLifecycleListener);\n removeMasterListener(ourSyncMasterListener);\n\n sendingStatus.set(false); // Stop the status sending thread.\n sendingStatus = null; // Indicate that we are no longer sending status.\n final BeatSender activeSender = beatSender.get(); // And stop the beat sender if we have one.\n if (activeSender != null) {\n activeSender.shutDown();\n beatSender.set(null);\n }\n }\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 }",
"public synchronized X509Certificate getCertificateByHostname(final String hostname) throws KeyStoreException, CertificateParsingException, InvalidKeyException, CertificateExpiredException, CertificateNotYetValidException, SignatureException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException, UnrecoverableKeyException{\n\n\t\tString alias = _subjectMap.get(getSubjectForHostname(hostname));\n\n\t\tif(alias != null) {\n\t\t\treturn (X509Certificate)_ks.getCertificate(alias);\n\t\t}\n return getMappedCertificateForHostname(hostname);\n\t}",
"protected Path normalizePath(final Path parent, final String path) {\n return parent.resolve(path).toAbsolutePath().normalize();\n }"
] |
Add properties to 'properties' map on transaction start
@param type - of transaction | [
"protected void addPropertiesStart(String type) {\n putProperty(PropertyKey.Host.name(), IpUtils.getHostName());\n putProperty(PropertyKey.Type.name(), type);\n putProperty(PropertyKey.Status.name(), Status.Start.name());\n }"
] | [
"public static Double getDistanceBetweenCoordinates(Tuple2<Double, Double> point1, Tuple2<Double, Double> point2) {\r\n // sqrt( (x2-x1)^2 + (y2-y2)^2 )\r\n Double xDiff = point1._1() - point2._1();\r\n Double yDiff = point1._2() - point2._2();\r\n return Math.sqrt(xDiff * xDiff + yDiff * yDiff);\r\n }",
"private void validatePermissions(final File dirPath, final File file) {\n\n // Check execute and read permissions for parent dirPath\n if( !dirPath.canExecute() || !dirPath.canRead() ) {\n validFilePermissions = false;\n filePermissionsProblemPath = dirPath.getAbsolutePath();\n return;\n }\n\n // Check read and write permissions for properties file\n if( !file.canRead() || !file.canWrite() ) {\n validFilePermissions = false;\n filePermissionsProblemPath = dirPath.getAbsolutePath();\n }\n\n }",
"public void recordConnectionEstablishmentTimeUs(SocketDestination dest, long connEstTimeUs) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordConnectionEstablishmentTimeUs(null, connEstTimeUs);\n recordConnectionEstablishmentTimeUs(null, connEstTimeUs);\n } else {\n this.connectionEstablishmentRequestCounter.addRequest(connEstTimeUs * Time.NS_PER_US);\n }\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}",
"protected boolean closeAtomically() {\n if (isClosed.compareAndSet(false, true)) {\n Closeable.closeQuietly(networkStatsListener);\n return true;\n } else {\n //was already closed.\n return false;\n }\n }",
"@VisibleForTesting\n protected static Dimension getSize(\n final ScalebarAttributeValues scalebarParams,\n final ScaleBarRenderSettings settings, final Dimension maxLabelSize) {\n final float width;\n final float height;\n if (scalebarParams.getOrientation().isHorizontal()) {\n width = 2 * settings.getPadding()\n + settings.getIntervalLengthInPixels() * scalebarParams.intervals\n + settings.getLeftLabelMargin() + settings.getRightLabelMargin();\n height = 2 * settings.getPadding()\n + settings.getBarSize() + settings.getLabelDistance()\n + Label.getRotatedHeight(maxLabelSize, scalebarParams.getLabelRotation());\n } else {\n width = 2 * settings.getPadding()\n + settings.getLabelDistance() + settings.getBarSize()\n + Label.getRotatedWidth(maxLabelSize, scalebarParams.getLabelRotation());\n height = 2 * settings.getPadding()\n + settings.getTopLabelMargin()\n + settings.getIntervalLengthInPixels() * scalebarParams.intervals\n + settings.getBottomLabelMargin();\n }\n return new Dimension((int) Math.ceil(width), (int) Math.ceil(height));\n }",
"private void registerPerformanceMonitor(String beanName,\n BeanDefinitionRegistry registry) {\n\n String perfMonitorName = beanName + \"PerformanceMonitor\";\n if (!registry.containsBeanDefinition(perfMonitorName)) {\n BeanDefinitionBuilder initializer =\n BeanDefinitionBuilder.rootBeanDefinition(PerformanceMonitorBean.class);\n registry.registerBeanDefinition(perfMonitorName, initializer.getBeanDefinition());\n }\n }",
"public void editComment(String commentId, String commentText) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT_COMMENT);\r\n\r\n parameters.put(\"comment_id\", commentId);\r\n parameters.put(\"comment_text\", commentText);\r\n\r\n // Note: This method requires an HTTP POST request.\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n // This method has no specific response - It returns an empty\r\n // sucess response if it completes without error.\r\n }",
"@Pure\n\tpublic static <K, V> Map<K, V> operator_minus(Map<K, V> left, final Pair<? extends K, ? extends V> right) {\n\t\treturn Maps.filterEntries(left, new Predicate<Entry<K, V>>() {\n\t\t\t@Override\n\t\t\tpublic boolean apply(Entry<K, V> input) {\n\t\t\t\treturn !Objects.equal(input.getKey(), right.getKey()) || !Objects.equal(input.getValue(), right.getValue());\n\t\t\t}\n\t\t});\n\t}"
] |
Upgrade the lock on the given object to the given lock mode. The call has
no effect if the object's current lock is already at or above that level of
lock mode.
@param obj object to acquire a lock on.
@param lockMode lock mode to acquire. The lock modes
are <code>READ</code> , <code>UPGRADE</code> , and <code>WRITE</code> .
@exception LockNotGrantedException Description of Exception | [
"public void lock(Object obj, int lockMode) throws LockNotGrantedException\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"lock object was called on tx \" + this + \", object is \" + obj.toString());\r\n checkOpen();\r\n RuntimeObject rtObject = new RuntimeObject(obj, this);\r\n lockAndRegister(rtObject, lockMode, isImplicitLocking(), getRegistrationList());\r\n// if(isImplicitLocking()) moveToLastInOrderList(rtObject.getIdentity());\r\n }"
] | [
"private void createSuiteList(List<ISuite> suites,\n File outputDirectory,\n boolean onlyFailures) throws Exception\n {\n VelocityContext context = createContext();\n context.put(SUITES_KEY, suites);\n context.put(ONLY_FAILURES_KEY, onlyFailures);\n generateFile(new File(outputDirectory, SUITES_FILE),\n SUITES_FILE + TEMPLATE_EXTENSION,\n context);\n }",
"public static base_response add(nitro_service client, dnsview resource) throws Exception {\n\t\tdnsview addresource = new dnsview();\n\t\taddresource.viewname = resource.viewname;\n\t\treturn addresource.add_resource(client);\n\t}",
"public DomainList getPhotostreamDomains(Date date, int perPage, int page) throws FlickrException {\n return getDomains(METHOD_GET_PHOTOSTREAM_DOMAINS, null, null, date, perPage, page);\n\n }",
"public String getTexCoordAttr(String texName)\n {\n GVRTexture tex = textures.get(texName);\n if (tex != null)\n {\n return tex.getTexCoordAttr();\n }\n return null;\n }",
"public synchronized void start() {\n\t\tif ((todoFlags & RECORD_CPUTIME) != 0) {\n\t\t\tcurrentStartCpuTime = getThreadCpuTime(threadId);\n\t\t} else {\n\t\t\tcurrentStartCpuTime = -1;\n\t\t}\n\t\tif ((todoFlags & RECORD_WALLTIME) != 0) {\n\t\t\tcurrentStartWallTime = System.nanoTime();\n\t\t} else {\n\t\t\tcurrentStartWallTime = -1;\n\t\t}\n\t\tisRunning = true;\n\t}",
"public static double I(int n, double x) {\r\n if (n < 0)\r\n throw new IllegalArgumentException(\"the variable n out of range.\");\r\n else if (n == 0)\r\n return I0(x);\r\n else if (n == 1)\r\n return I(x);\r\n\r\n if (x == 0.0)\r\n return 0.0;\r\n\r\n double ACC = 40.0;\r\n double BIGNO = 1.0e+10;\r\n double BIGNI = 1.0e-10;\r\n\r\n double tox = 2.0 / Math.abs(x);\r\n double bip = 0, ans = 0.0;\r\n double bi = 1.0;\r\n\r\n for (int j = 2 * (n + (int) Math.sqrt(ACC * n)); j > 0; j--) {\r\n double bim = bip + j * tox * bi;\r\n bip = bi;\r\n bi = bim;\r\n\r\n if (Math.abs(bi) > BIGNO) {\r\n ans *= BIGNI;\r\n bi *= BIGNI;\r\n bip *= BIGNI;\r\n }\r\n\r\n if (j == n)\r\n ans = bip;\r\n }\r\n\r\n ans *= I0(x) / bi;\r\n return x < 0.0 && n % 2 == 1 ? -ans : ans;\r\n }",
"private final boolean matchPattern(byte[][] patterns, int bufferIndex)\n {\n boolean match = false;\n for (byte[] pattern : patterns)\n {\n int index = 0;\n match = true;\n for (byte b : pattern)\n {\n if (b != m_buffer[bufferIndex + index])\n {\n match = false;\n break;\n }\n ++index;\n }\n if (match)\n {\n break;\n }\n }\n return match;\n }",
"public Bundler put(String key, CharSequence value) {\n delegate.putCharSequence(key, value);\n return this;\n }",
"private void addListeners(ProjectReader reader)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n reader.addProjectListener(listener);\n }\n }\n }"
] |
create a HTTP POST request.
@return {@link HttpConnection} | [
"public static HttpConnection createPost(URI uri, String body, String contentType) {\n HttpConnection connection = Http.POST(uri, \"application/json\");\n if(body != null) {\n setEntity(connection, body, contentType);\n }\n return connection;\n }"
] | [
"private static void checkPreconditions(final Map<Object, Object> mapping) {\n\t\tif( mapping == null ) {\n\t\t\tthrow new NullPointerException(\"mapping should not be null\");\n\t\t} else if( mapping.isEmpty() ) {\n\t\t\tthrow new IllegalArgumentException(\"mapping should not be empty\");\n\t\t}\n\t}",
"private GridLines getGridLines(byte[] data, int offset)\n {\n Color normalLineColor = ColorType.getInstance(data[offset]).getColor();\n LineStyle normalLineStyle = LineStyle.getInstance(data[offset + 3]);\n int intervalNumber = data[offset + 4];\n LineStyle intervalLineStyle = LineStyle.getInstance(data[offset + 5]);\n Color intervalLineColor = ColorType.getInstance(data[offset + 6]).getColor();\n return new GridLines(normalLineColor, normalLineStyle, intervalNumber, intervalLineStyle, intervalLineColor);\n }",
"private void highlightSlice(PieModel _Slice) {\n\n int color = _Slice.getColor();\n _Slice.setHighlightedColor(Color.argb(\n 0xff,\n Math.min((int) (mHighlightStrength * (float) Color.red(color)), 0xff),\n Math.min((int) (mHighlightStrength * (float) Color.green(color)), 0xff),\n Math.min((int) (mHighlightStrength * (float) Color.blue(color)), 0xff)\n ));\n }",
"public void logAttributeWarning(PathAddress address, String attribute) {\n logAttributeWarning(address, null, null, attribute);\n }",
"private void writeTasks() throws IOException\n {\n writeAttributeTypes(\"task_types\", TaskField.values());\n\n m_writer.writeStartList(\"tasks\");\n for (Task task : m_projectFile.getChildTasks())\n {\n writeTask(task);\n }\n m_writer.writeEndList();\n }",
"public List<TimephasedWork> getTimephasedBaselineWork(int index)\n {\n return m_timephasedBaselineWork[index] == null ? null : m_timephasedBaselineWork[index].getData();\n }",
"public List<Index<Field>> allIndexes() {\n List<Index<Field>> indexesOfAnyType = new ArrayList<Index<Field>>();\n indexesOfAnyType.addAll(listIndexType(null, ListableIndex.class));\n return indexesOfAnyType;\n }",
"public static void shutdownDomain(final ModelControllerClient client, final int timeout) throws IOException, OperationExecutionException {\n // Note the following two operations used to shutdown a domain don't seem to work well in a composite operation.\n // The operation occasionally sees a java.util.concurrent.CancellationException because the operation client\n // is likely closed before the AsyncFuture.get() is complete. Using a non-composite operation doesn't seem to\n // have this issue.\n\n // First shutdown the servers\n final ModelNode stopServersOp = Operations.createOperation(\"stop-servers\");\n stopServersOp.get(\"blocking\").set(true);\n stopServersOp.get(\"timeout\").set(timeout);\n ModelNode response = client.execute(stopServersOp);\n if (!Operations.isSuccessfulOutcome(response)) {\n throw new OperationExecutionException(\"Failed to stop servers.\", stopServersOp, response);\n }\n\n // Now shutdown the host\n final ModelNode address = determineHostAddress(client);\n final ModelNode shutdownOp = Operations.createOperation(\"shutdown\", address);\n response = client.execute(shutdownOp);\n if (Operations.isSuccessfulOutcome(response)) {\n // Wait until the process has died\n while (true) {\n if (isDomainRunning(client, true)) {\n try {\n TimeUnit.MILLISECONDS.sleep(20L);\n } catch (InterruptedException e) {\n LOGGER.trace(\"Interrupted during sleep\", e);\n }\n } else {\n break;\n }\n }\n } else {\n throw new OperationExecutionException(\"Failed to shutdown host.\", shutdownOp, response);\n }\n }",
"protected void mergeHardcodedResultsFrom(Configuration otherConfiguration) {\r\n Map<Dotted, AnalysisResult> resultsMap = hardcodedResults.build().stream()\r\n .collect(Collectors.toMap(r -> r.className, r -> r));\r\n resultsMap.putAll(otherConfiguration.hardcodedResults());\r\n hardcodedResults = ImmutableSet.<AnalysisResult>builder().addAll(resultsMap.values());\r\n }"
] |
Returns a new iterable filtering any null references.
@param unfiltered
the unfiltered iterable. May not be <code>null</code>.
@return an unmodifiable iterable containing all elements of the original iterable without any <code>null</code> references. Never <code>null</code>. | [
"@Pure\n\tpublic static <T> Iterable<T> filterNull(Iterable<T> unfiltered) {\n\t\treturn Iterables.filter(unfiltered, Predicates.notNull());\n\t}"
] | [
"private boolean relevant(File currentLogFile, GregorianCalendar lastRelevantDate) {\n\t\tString fileName=currentLogFile.getName();\n\t\tPattern p = Pattern.compile(APPENER_DATE_DEFAULT_PATTERN);\n\t\tMatcher m = p.matcher(fileName);\n\t\tif(m.find()){\n\t\t\tint year=Integer.parseInt(m.group(1));\n\t\t\tint month=Integer.parseInt(m.group(2));\n\t\t\tint dayOfMonth=Integer.parseInt(m.group(3));\n\t\t\tGregorianCalendar fileDate=new GregorianCalendar(year, month, dayOfMonth);\n\t\t\tfileDate.add(Calendar.MONTH,-1); //Because of Calendar save the month such that January is 0\n\t\t\treturn fileDate.compareTo(lastRelevantDate)>0;\n\t\t}\n\t\telse{\n\t\t\treturn false;\n\t\t}\n\t}",
"public void setAngle(float angle) {\n this.angle = angle;\n float cos = (float) Math.cos(angle);\n float sin = (float) Math.sin(angle);\n m00 = cos;\n m01 = sin;\n m10 = -sin;\n m11 = cos;\n }",
"protected static PreparedStatement memorize(final PreparedStatement target, final ConnectionHandle connectionHandle) {\n\t\treturn (PreparedStatement) Proxy.newProxyInstance(\n\t\t\t\tPreparedStatementProxy.class.getClassLoader(),\n\t\t\t\tnew Class[] {PreparedStatementProxy.class},\n\t\t\t\tnew MemorizeTransactionProxy(target, connectionHandle));\n\t}",
"public void addForeignkey(String relationName, String remoteTable, List localColumns, List remoteColumns)\r\n {\r\n ForeignkeyDef foreignkeyDef = new ForeignkeyDef(relationName, remoteTable);\r\n\r\n // the field arrays have the same length if we already checked the constraints\r\n for (int idx = 0; idx < localColumns.size(); idx++)\r\n {\r\n foreignkeyDef.addColumnPair((String)localColumns.get(idx),\r\n (String)remoteColumns.get(idx));\r\n }\r\n\r\n // we got to determine whether this foreignkey is already present \r\n ForeignkeyDef def = null;\r\n\r\n for (Iterator it = getForeignkeys(); it.hasNext();)\r\n {\r\n def = (ForeignkeyDef)it.next();\r\n if (foreignkeyDef.equals(def))\r\n {\r\n return;\r\n }\r\n }\r\n foreignkeyDef.setOwner(this);\r\n _foreignkeys.add(foreignkeyDef);\r\n }",
"public void loadClassifier(String loadPath, Properties props) throws ClassCastException, IOException, ClassNotFoundException {\r\n InputStream is;\r\n // ms, 10-04-2010: check first is this path exists in our CLASSPATH. This\r\n // takes priority over the file system.\r\n if ((is = loadStreamFromClasspath(loadPath)) != null) {\r\n Timing.startDoing(\"Loading classifier from \" + loadPath);\r\n loadClassifier(is);\r\n is.close();\r\n Timing.endDoing();\r\n } else {\r\n loadClassifier(new File(loadPath), props);\r\n }\r\n }",
"private void processHyperlinkData(ResourceAssignment assignment, byte[] data)\n {\n if (data != null)\n {\n int offset = 12;\n\n offset += 12;\n String hyperlink = MPPUtility.getUnicodeString(data, offset);\n offset += ((hyperlink.length() + 1) * 2);\n\n offset += 12;\n String address = MPPUtility.getUnicodeString(data, offset);\n offset += ((address.length() + 1) * 2);\n\n offset += 12;\n String subaddress = MPPUtility.getUnicodeString(data, offset);\n offset += ((subaddress.length() + 1) * 2);\n\n offset += 12;\n String screentip = MPPUtility.getUnicodeString(data, offset);\n\n assignment.setHyperlink(hyperlink);\n assignment.setHyperlinkAddress(address);\n assignment.setHyperlinkSubAddress(subaddress);\n assignment.setHyperlinkScreenTip(screentip);\n }\n }",
"@Nullable\n public ResultT first() {\n final CoreRemoteMongoCursor<ResultT> cursor = iterator();\n if (!cursor.hasNext()) {\n return null;\n }\n return cursor.next();\n }",
"public static boolean isRevisionDumpFile(DumpContentType dumpContentType) {\n\t\tif (WmfDumpFile.REVISION_DUMP.containsKey(dumpContentType)) {\n\t\t\treturn WmfDumpFile.REVISION_DUMP.get(dumpContentType);\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\"Unsupported dump type \"\n\t\t\t\t\t+ dumpContentType);\n\t\t}\n\t}",
"public int getCostRateTableIndex()\n {\n Integer value = (Integer) getCachedValue(AssignmentField.COST_RATE_TABLE);\n return value == null ? 0 : value.intValue();\n }"
] |
It is required that T be Serializable | [
"@SuppressWarnings(\"unchecked\")\n public <T> DistributedFuture<GROUP, T> createFuture(HazeltaskTask<GROUP> task) {\n DistributedFuture<GROUP, T> future = new DistributedFuture<GROUP, T>(topologyService, task.getGroup(), task.getId());\n this.futures.put(task.getId(), (DistributedFuture<GROUP, Serializable>) future);\n return future;\n }"
] | [
"public List<Integer> getPathOrder(int profileId) {\n ArrayList<Integer> pathOrder = new ArrayList<Integer>();\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \"\n + Constants.DB_TABLE_PATH + \" WHERE \"\n + Constants.GENERIC_PROFILE_ID + \" = ? \"\n + \" ORDER BY \" + Constants.PATH_PROFILE_PATH_ORDER + \" ASC\"\n );\n queryStatement.setInt(1, profileId);\n results = queryStatement.executeQuery();\n while (results.next()) {\n pathOrder.add(results.getInt(Constants.GENERIC_ID));\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n logger.info(\"pathOrder = {}\", pathOrder);\n return pathOrder;\n }",
"public void notifyEventListeners(ZWaveEvent event) {\n\t\tlogger.debug(\"Notifying event listeners\");\n\t\tfor (ZWaveEventListener listener : this.zwaveEventListeners) {\n\t\t\tlogger.trace(\"Notifying {}\", listener.toString());\n\t\t\tlistener.ZWaveIncomingEvent(event);\n\t\t}\n\t}",
"public final File getTaskDirectory() {\n createIfMissing(this.working, \"Working\");\n try {\n return Files.createTempDirectory(this.working.toPath(), TASK_DIR_PREFIX).toFile();\n } catch (IOException e) {\n throw new AssertionError(\"Unable to create temporary directory in '\" + this.working + \"'\");\n }\n }",
"public void renumberIDs()\n {\n if (!isEmpty())\n {\n Collections.sort(this);\n T firstEntity = get(0);\n int id = NumberHelper.getInt(firstEntity.getID());\n if (id != 0)\n {\n id = 1;\n }\n\n for (T entity : this)\n {\n entity.setID(Integer.valueOf(id++));\n }\n }\n }",
"private String quoteFormatCharacters(String literal)\n {\n StringBuilder sb = new StringBuilder();\n int length = literal.length();\n char c;\n\n for (int loop = 0; loop < length; loop++)\n {\n c = literal.charAt(loop);\n switch (c)\n {\n case '0':\n case '#':\n case '.':\n case '-':\n case ',':\n case 'E':\n case ';':\n case '%':\n {\n sb.append(\"'\");\n sb.append(c);\n sb.append(\"'\");\n break;\n }\n\n default:\n {\n sb.append(c);\n break;\n }\n }\n }\n\n return (sb.toString());\n }",
"public void setAutoClose(boolean autoClose) {\n this.autoClose = autoClose;\n\n if (autoCloseHandlerRegistration != null) {\n autoCloseHandlerRegistration.removeHandler();\n autoCloseHandlerRegistration = null;\n }\n\n if (autoClose) {\n autoCloseHandlerRegistration = registerHandler(addValueChangeHandler(event -> close()));\n }\n }",
"private String readLine(boolean trim) throws IOException {\n boolean done = false;\n boolean sawCarriage = false;\n // bytes to trim (the \\r and the \\n)\n int removalBytes = 0;\n while (!done) {\n if (isReadBufferEmpty()) {\n offset = 0;\n end = 0;\n int bytesRead = inputStream.read(buffer, end, Math.min(DEFAULT_READ_COUNT, buffer.length - end));\n if (bytesRead < 0) {\n // we failed to read anything more...\n throw new IOException(\"Reached the end of the stream\");\n } else {\n end += bytesRead;\n }\n }\n\n int originalOffset = offset;\n for (; !done && offset < end; offset++) {\n if (buffer[offset] == LF) {\n int cpLength = offset - originalOffset + 1;\n if (trim) {\n int length = 0;\n if (buffer[offset] == LF) {\n length ++;\n if (sawCarriage) {\n length++;\n }\n }\n cpLength -= length;\n }\n\n if (cpLength > 0) {\n copyToStrBuffer(buffer, originalOffset, cpLength);\n } else {\n // negative length means we need to trim a \\r from strBuffer\n removalBytes = cpLength;\n }\n done = true;\n } else {\n // did not see newline:\n sawCarriage = buffer[offset] == CR;\n }\n }\n\n if (!done) {\n copyToStrBuffer(buffer, originalOffset, end - originalOffset);\n offset = end;\n }\n }\n int strLength = strBufferIndex + removalBytes;\n strBufferIndex = 0;\n return new String(strBuffer, 0, strLength, charset);\n }",
"public PeriodicEvent runAfter(Runnable task, float delay) {\n validateDelay(delay);\n return new Event(task, delay);\n }",
"GcsRestCreationToken handlePutResponse(final GcsRestCreationToken token,\n final boolean isFinalChunk,\n final int length,\n final HTTPRequestInfo reqInfo,\n HTTPResponse resp) throws Error, IOException {\n switch (resp.getResponseCode()) {\n case 200:\n if (!isFinalChunk) {\n throw new RuntimeException(\"Unexpected response code 200 on non-final chunk. Request: \\n\"\n + URLFetchUtils.describeRequestAndResponse(reqInfo, resp));\n } else {\n return null;\n }\n case 308:\n if (isFinalChunk) {\n throw new RuntimeException(\"Unexpected response code 308 on final chunk: \"\n + URLFetchUtils.describeRequestAndResponse(reqInfo, resp));\n } else {\n return new GcsRestCreationToken(token.filename, token.uploadId, token.offset + length);\n }\n default:\n throw HttpErrorHandler.error(resp.getResponseCode(),\n URLFetchUtils.describeRequestAndResponse(reqInfo, resp));\n }\n }"
] |
Is the transport secured by a policy | [
"private boolean isSecuredByPolicy(Server server) {\n boolean isSecured = false;\n\n EndpointInfo ei = server.getEndpoint().getEndpointInfo();\n\n PolicyEngine pe = bus.getExtension(PolicyEngine.class);\n if (null == pe) {\n LOG.finest(\"No Policy engine found\");\n return isSecured;\n }\n\n Destination destination = server.getDestination();\n EndpointPolicy ep = pe.getServerEndpointPolicy(ei, destination, null);\n Collection<Assertion> assertions = ep.getChosenAlternative();\n for (Assertion a : assertions) {\n if (a instanceof TransportBinding) {\n TransportBinding tb = (TransportBinding) a;\n TransportToken tt = tb.getTransportToken();\n AbstractToken t = tt.getToken();\n if (t instanceof HttpsToken) {\n isSecured = true;\n break;\n }\n }\n }\n\n Policy policy = ep.getPolicy();\n List<PolicyComponent> pcList = policy.getPolicyComponents();\n for (PolicyComponent a : pcList) {\n if (a instanceof TransportBinding) {\n TransportBinding tb = (TransportBinding) a;\n TransportToken tt = tb.getTransportToken();\n AbstractToken t = tt.getToken();\n if (t instanceof HttpsToken) {\n isSecured = true;\n break;\n }\n }\n }\n\n return isSecured;\n }"
] | [
"public void setPosition(float x, float y, float z) {\n if (isActive()) {\n mIODevice.setPosition(x, y, z);\n }\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 }",
"protected boolean equivalentClaims(Claim claim1, Claim claim2) {\n\t\treturn claim1.getMainSnak().equals(claim2.getMainSnak())\n\t\t\t\t&& isSameSnakSet(claim1.getAllQualifiers(),\n\t\t\t\t\t\tclaim2.getAllQualifiers());\n\t}",
"public static double Cosh(double x, int nTerms) {\r\n if (nTerms < 2) return x;\r\n if (nTerms == 2) {\r\n return 1 + (x * x) / 2D;\r\n } else {\r\n\r\n double mult = x * x;\r\n double fact = 2;\r\n int factS = 4;\r\n double result = 1 + mult / fact;\r\n for (int i = 3; i <= nTerms; i++) {\r\n mult *= x * x;\r\n fact *= factS * (factS - 1);\r\n factS += 2;\r\n result += mult / fact;\r\n }\r\n\r\n return result;\r\n }\r\n }",
"@PrefMetadata(type = CmsHiddenBuiltinPreference.class)\n public String getExplorerFileEntryOptions() {\n\n if (m_settings.getExplorerFileEntryOptions() == null) {\n return \"\";\n } else {\n return \"\" + m_settings.getExplorerFileEntryOptions();\n }\n }",
"public static void scaleRow( double alpha , DMatrixRMaj A , int row ) {\n int idx = row*A.numCols;\n for (int col = 0; col < A.numCols; col++) {\n A.data[idx++] *= alpha;\n }\n }",
"public static aaauser_aaagroup_binding[] get(nitro_service service, String username) throws Exception{\n\t\taaauser_aaagroup_binding obj = new aaauser_aaagroup_binding();\n\t\tobj.set_username(username);\n\t\taaauser_aaagroup_binding response[] = (aaauser_aaagroup_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static <T> Collection<MemberResponse<T>> executeOptimistic(IExecutorService execSvc, Set<Member> members, Callable<T> callable) {\n \treturn executeOptimistic(execSvc, members, callable, 60, TimeUnit.SECONDS);\n }",
"public HomekitRoot createBridge(\n HomekitAuthInfo authInfo,\n String label,\n String manufacturer,\n String model,\n String serialNumber)\n throws IOException {\n HomekitRoot root = new HomekitRoot(label, http, localAddress, authInfo);\n root.addAccessory(new HomekitBridge(label, serialNumber, model, manufacturer));\n return root;\n }"
] |
Checks if the DPI value is already set for GeoServer. | [
"private static boolean isDpiSet(final Multimap<String, String> extraParams) {\n String searchKey = \"FORMAT_OPTIONS\";\n for (String key: extraParams.keys()) {\n if (key.equalsIgnoreCase(searchKey)) {\n for (String value: extraParams.get(key)) {\n if (value.toLowerCase().contains(\"dpi:\")) {\n return true;\n }\n }\n }\n }\n return false;\n }"
] | [
"public void seekToSeasonYear(String seasonString, String yearString) {\n Season season = Season.valueOf(seasonString);\n assert(season != null);\n \n seekToIcsEventYear(SEASON_ICS_FILE, yearString, season.getSummary());\n }",
"private void recordTime(Tracked op,\n long timeNS,\n long numEmptyResponses,\n long valueSize,\n long keySize,\n long getAllAggregateRequests) {\n counters.get(op).addRequest(timeNS,\n numEmptyResponses,\n valueSize,\n keySize,\n getAllAggregateRequests);\n\n if (logger.isTraceEnabled() && !storeName.contains(\"aggregate\") && !storeName.contains(\"voldsys$\"))\n logger.trace(\"Store '\" + storeName + \"' logged a \" + op.toString() + \" request taking \" +\n ((double) timeNS / voldemort.utils.Time.NS_PER_MS) + \" ms\");\n }",
"public void perform() {\n for (int i = 0; i < operations.size(); i++) {\n operations.get(i).process();\n }\n }",
"public CmsJspDateSeriesBean getToDateSeries() {\n\n if (m_dateSeries == null) {\n m_dateSeries = new CmsJspDateSeriesBean(this, m_cms.getRequestContext().getLocale());\n }\n return m_dateSeries;\n }",
"public static Cluster vacateZone(Cluster currentCluster, int dropZoneId) {\n Cluster returnCluster = Cluster.cloneCluster(currentCluster);\n // Go over each node in the zone being dropped\n for(Integer nodeId: currentCluster.getNodeIdsInZone(dropZoneId)) {\n // For each node grab all the partitions it hosts\n for(Integer partitionId: currentCluster.getNodeById(nodeId).getPartitionIds()) {\n // Now for each partition find a new home..which would be a node\n // in one of the existing zones\n int finalZoneId = -1;\n int finalNodeId = -1;\n int adjacentPartitionId = partitionId;\n do {\n adjacentPartitionId = (adjacentPartitionId + 1)\n % currentCluster.getNumberOfPartitions();\n finalNodeId = currentCluster.getNodeForPartitionId(adjacentPartitionId).getId();\n finalZoneId = currentCluster.getZoneForPartitionId(adjacentPartitionId).getId();\n if(adjacentPartitionId == partitionId) {\n logger.error(\"PartitionId \" + partitionId + \"stays unchanged \\n\");\n } else {\n logger.info(\"PartitionId \" + partitionId\n + \" goes together with partition \" + adjacentPartitionId\n + \" on node \" + finalNodeId + \" in zone \" + finalZoneId);\n returnCluster = UpdateClusterUtils.createUpdatedCluster(returnCluster,\n finalNodeId,\n Lists.newArrayList(partitionId));\n }\n } while(finalZoneId == dropZoneId);\n }\n }\n return returnCluster;\n }",
"public List<Release> listReleases(String appName) {\n return connection.execute(new ReleaseList(appName), apiKey);\n }",
"public double distanceSquared(Vector3d v) {\n double dx = x - v.x;\n double dy = y - v.y;\n double dz = z - v.z;\n\n return dx * dx + dy * dy + dz * dz;\n }",
"public String getResourceFilename() {\n switch (resourceType) {\n case ANDROID_ASSETS:\n return assetPath\n .substring(assetPath.lastIndexOf(File.separator) + 1);\n\n case ANDROID_RESOURCE:\n return resourceFilePath.substring(\n resourceFilePath.lastIndexOf(File.separator) + 1);\n\n case LINUX_FILESYSTEM:\n return filePath.substring(filePath.lastIndexOf(File.separator) + 1);\n\n case NETWORK:\n return url.getPath().substring(url.getPath().lastIndexOf(\"/\") + 1);\n\n case INPUT_STREAM:\n return inputStreamName;\n\n default:\n return null;\n }\n }",
"public ResponseFromManager generateUpdateExecuteTask(ParallelTask task) {\n\n // add to map now; as can only pass final\n ParallelTaskManager.getInstance().addTaskToInProgressMap(\n task.getTaskId(), task);\n logger.info(\"Added task {} to the running inprogress map...\",\n task.getTaskId());\n\n boolean useReplacementVarMap = false;\n boolean useReplacementVarMapNodeSpecific = false;\n Map<String, StrStrMap> replacementVarMapNodeSpecific = null;\n Map<String, String> replacementVarMap = null;\n\n ResponseFromManager batchResponseFromManager = null;\n\n switch (task.getRequestReplacementType()) {\n case UNIFORM_VAR_REPLACEMENT:\n useReplacementVarMap = true;\n useReplacementVarMapNodeSpecific = false;\n replacementVarMap = task.getReplacementVarMap();\n break;\n case TARGET_HOST_SPECIFIC_VAR_REPLACEMENT:\n useReplacementVarMap = false;\n useReplacementVarMapNodeSpecific = true;\n replacementVarMapNodeSpecific = task\n .getReplacementVarMapNodeSpecific();\n break;\n case NO_REPLACEMENT:\n useReplacementVarMap = false;\n useReplacementVarMapNodeSpecific = false;\n break;\n default:\n logger.error(\"error request replacement type. default as no replacement\");\n }// end switch\n\n // generate content in nodedata\n InternalDataProvider dp = InternalDataProvider.getInstance();\n dp.genNodeDataMap(task);\n\n VarReplacementProvider.getInstance()\n .updateRequestWithReplacement(task, useReplacementVarMap,\n replacementVarMap, useReplacementVarMapNodeSpecific,\n replacementVarMapNodeSpecific);\n\n batchResponseFromManager = \n sendTaskToExecutionManager(task);\n\n removeTaskFromInProgressMap(task.getTaskId());\n logger.info(\n \"Removed task {} from the running inprogress map... \"\n + \". This task should be garbage collected if there are no other pointers.\",\n task.getTaskId());\n return batchResponseFromManager;\n\n }"
] |
Gets the positions.
@return the positions | [
"public int[] getPositions() {\n int[] list;\n if (assumeSinglePosition) {\n list = new int[1];\n list[0] = super.startPosition();\n return list;\n } else {\n try {\n processEncodedPayload();\n list = mtasPosition.getPositions();\n if (list != null) {\n return mtasPosition.getPositions();\n }\n } catch (IOException e) {\n log.debug(e);\n // do nothing\n }\n int start = super.startPosition();\n int end = super.endPosition();\n list = new int[end - start];\n for (int i = start; i < end; i++)\n list[i - start] = i;\n return list;\n }\n }"
] | [
"public ModelNode buildExecutableRequest(CommandContext ctx) throws Exception {\n try {\n for (FailureDescProvider h : providers) {\n effectiveProviders.add(h);\n }\n // In case some key-store needs to be persisted\n for (String ks : ksToStore) {\n composite.get(Util.STEPS).add(ElytronUtil.storeKeyStore(ctx, ks));\n effectiveProviders.add(new FailureDescProvider() {\n @Override\n public String stepFailedDescription() {\n return \"Storing the key-store \" + ksToStore;\n }\n });\n }\n // Final steps\n for (int i = 0; i < finalSteps.size(); i++) {\n composite.get(Util.STEPS).add(finalSteps.get(i));\n effectiveProviders.add(finalProviders.get(i));\n }\n return composite;\n } catch (Exception ex) {\n try {\n failureOccured(ctx, null);\n } catch (Exception ex2) {\n ex.addSuppressed(ex2);\n }\n throw ex;\n }\n }",
"@Deprecated\n\t@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n\tpublic Map<String, PrimitiveAttribute<?>> getAttributes() {\n\t\tif (!isPrimitiveOnly()) {\n\t\t\tthrow new UnsupportedOperationException(\"Primitive API not supported for nested association values\");\n\t\t}\n\t\treturn (Map) attributes;\n\t}",
"public synchronized void jumpToBeat(int beat) {\n\n if (beat < 1) {\n beat = 1;\n } else {\n beat = wrapBeat(beat);\n }\n\n if (playing.get()) {\n metronome.jumpToBeat(beat);\n } else {\n whereStopped.set(metronome.getSnapshot(metronome.getTimeOfBeat(beat)));\n }\n }",
"public DiscreteInterval minus(DiscreteInterval other) {\n return new DiscreteInterval(this.min - other.max, this.max - other.min);\n }",
"public boolean shouldCache(String requestUri) {\n\t\tString uri = requestUri.toLowerCase();\n\t\treturn checkContains(uri, cacheIdentifiers) || checkSuffixes(uri, cacheSuffixes);\n\t}",
"@JmxOperation(description = \"Forcefully invoke the log cleaning\")\n public void cleanLogs() {\n synchronized(lock) {\n try {\n for(Environment environment: environments.values()) {\n environment.cleanLog();\n }\n } catch(DatabaseException e) {\n throw new VoldemortException(e);\n }\n }\n }",
"public void put(@NotNull final Transaction txn, final long localId,\n final int blobId, @NotNull final ByteIterable value) {\n primaryStore.put(txn, PropertyKey.propertyKeyToEntry(new PropertyKey(localId, blobId)), value);\n allBlobsIndex.put(txn, IntegerBinding.intToCompressedEntry(blobId), LongBinding.longToCompressedEntry(localId));\n }",
"public void setSchema(String schema)\n {\n if (schema == null)\n {\n schema = \"\";\n }\n else\n {\n if (!schema.isEmpty() && !schema.endsWith(\".\"))\n {\n schema = schema + '.';\n }\n }\n m_schema = schema;\n }",
"public void updateShownOptions(boolean showModeSwitch, boolean showAddKeyOption) {\n\n if (showModeSwitch != m_showModeSwitch) {\n m_upperLeftComponent.removeAllComponents();\n m_upperLeftComponent.addComponent(m_languageSwitch);\n if (showModeSwitch) {\n m_upperLeftComponent.addComponent(m_modeSwitch);\n }\n m_upperLeftComponent.addComponent(m_filePathLabel);\n m_showModeSwitch = showModeSwitch;\n }\n if (showAddKeyOption != m_showAddKeyOption) {\n if (showAddKeyOption) {\n m_optionsComponent.addComponent(m_lowerLeftComponent, 0, 1);\n m_optionsComponent.addComponent(m_lowerRightComponent, 1, 1);\n } else {\n m_optionsComponent.removeComponent(0, 1);\n m_optionsComponent.removeComponent(1, 1);\n }\n m_showAddKeyOption = showAddKeyOption;\n }\n }"
] |
Create the OJB_CLAZZ pseudo column based on CASE WHEN.
This column defines the Class to be instantiated.
@param buf | [
"private void appendClazzColumnForSelect(StringBuffer buf)\r\n {\r\n ClassDescriptor cld = getSearchClassDescriptor();\r\n ClassDescriptor[] clds = getMultiJoinedClassDescriptors(cld);\r\n\r\n if (clds.length == 0)\r\n {\r\n return;\r\n }\r\n \r\n buf.append(\",CASE\");\r\n\r\n for (int i = clds.length; i > 0; i--)\r\n {\r\n buf.append(\" WHEN \");\r\n\r\n ClassDescriptor subCld = clds[i - 1];\r\n FieldDescriptor[] fieldDescriptors = subCld.getPkFields();\r\n\r\n TableAlias alias = getTableAliasForClassDescriptor(subCld);\r\n for (int j = 0; j < fieldDescriptors.length; j++)\r\n {\r\n FieldDescriptor field = fieldDescriptors[j];\r\n if (j > 0)\r\n {\r\n buf.append(\" AND \");\r\n }\r\n appendColumn(alias, field, buf);\r\n buf.append(\" IS NOT NULL\");\r\n }\r\n buf.append(\" THEN '\").append(subCld.getClassNameOfObject()).append(\"'\");\r\n }\r\n buf.append(\" ELSE '\").append(cld.getClassNameOfObject()).append(\"'\");\r\n buf.append(\" END AS \" + SqlHelper.OJB_CLASS_COLUMN);\r\n }"
] | [
"private ProjectFile handleSQLiteFile(InputStream stream) throws Exception\n {\n File file = InputStreamHelper.writeStreamToTempFile(stream, \".sqlite\");\n\n try\n {\n Class.forName(\"org.sqlite.JDBC\");\n String url = \"jdbc:sqlite:\" + file.getCanonicalPath();\n Set<String> tableNames = populateTableNames(url);\n\n if (tableNames.contains(\"EXCEPTIONN\"))\n {\n return readProjectFile(new AstaDatabaseFileReader(), file);\n }\n\n if (tableNames.contains(\"PROJWBS\"))\n {\n Connection connection = null;\n try\n {\n Properties props = new Properties();\n props.setProperty(\"date_string_format\", \"yyyy-MM-dd HH:mm:ss\");\n connection = DriverManager.getConnection(url, props);\n PrimaveraDatabaseReader reader = new PrimaveraDatabaseReader();\n reader.setConnection(connection);\n addListeners(reader);\n return reader.read();\n }\n finally\n {\n if (connection != null)\n {\n connection.close();\n }\n }\n }\n\n if (tableNames.contains(\"ZSCHEDULEITEM\"))\n {\n return readProjectFile(new MerlinReader(), file);\n }\n\n return null;\n }\n\n finally\n {\n FileHelper.deleteQuietly(file);\n }\n }",
"public static void main(String[] args) throws Exception {\r\n System.err.println(\"CRFBiasedClassifier invoked at \" + new Date()\r\n + \" with arguments:\");\r\n for (String arg : args) {\r\n System.err.print(\" \" + arg);\r\n }\r\n System.err.println();\r\n\r\n Properties props = StringUtils.argsToProperties(args);\r\n CRFBiasedClassifier crf = new CRFBiasedClassifier(props);\r\n String testFile = crf.flags.testFile;\r\n String loadPath = crf.flags.loadClassifier;\r\n\r\n if (loadPath != null) {\r\n crf.loadClassifierNoExceptions(loadPath, props);\r\n } else if (crf.flags.loadJarClassifier != null) {\r\n crf.loadJarClassifier(crf.flags.loadJarClassifier, props);\r\n } else {\r\n crf.loadDefaultClassifier();\r\n }\r\n if(crf.flags.classBias != null) {\r\n StringTokenizer biases = new java.util.StringTokenizer(crf.flags.classBias,\",\");\r\n while (biases.hasMoreTokens()) {\r\n StringTokenizer bias = new java.util.StringTokenizer(biases.nextToken(),\":\");\r\n String cname = bias.nextToken();\r\n double w = Double.parseDouble(bias.nextToken());\r\n crf.setBiasWeight(cname,w);\r\n System.err.println(\"Setting bias for class \"+cname+\" to \"+w);\r\n }\r\n }\r\n\r\n if (testFile != null) {\r\n DocumentReaderAndWriter readerAndWriter = crf.makeReaderAndWriter();\r\n if (crf.flags.printFirstOrderProbs) {\r\n crf.printFirstOrderProbs(testFile, readerAndWriter);\r\n } else if (crf.flags.printProbs) {\r\n crf.printProbs(testFile, readerAndWriter);\r\n } else if (crf.flags.useKBest) {\r\n int k = crf.flags.kBest;\r\n crf.classifyAndWriteAnswersKBest(testFile, k, readerAndWriter);\r\n } else {\r\n crf.classifyAndWriteAnswers(testFile, readerAndWriter);\r\n }\r\n }\r\n }",
"private static void parseStencil(JSONObject modelJSON,\n Shape current) throws JSONException {\n // get stencil type\n if (modelJSON.has(\"stencil\")) {\n JSONObject stencil = modelJSON.getJSONObject(\"stencil\");\n // TODO other attributes of stencil\n String stencilString = \"\";\n if (stencil.has(\"id\")) {\n stencilString = stencil.getString(\"id\");\n }\n current.setStencil(new StencilType(stencilString));\n }\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 byte[] copy(byte[] array, int from, int to) {\n if(to - from < 0) {\n return new byte[0];\n } else {\n byte[] a = new byte[to - from];\n System.arraycopy(array, from, a, 0, to - from);\n return a;\n }\n }",
"private String getDateTimeString(Date value)\n {\n String result = null;\n if (value != null)\n {\n Calendar cal = DateHelper.popCalendar(value);\n StringBuilder sb = new StringBuilder(16);\n sb.append(m_fourDigitFormat.format(cal.get(Calendar.YEAR)));\n sb.append(m_twoDigitFormat.format(cal.get(Calendar.MONTH) + 1));\n sb.append(m_twoDigitFormat.format(cal.get(Calendar.DAY_OF_MONTH)));\n sb.append('T');\n sb.append(m_twoDigitFormat.format(cal.get(Calendar.HOUR_OF_DAY)));\n sb.append(m_twoDigitFormat.format(cal.get(Calendar.MINUTE)));\n sb.append(m_twoDigitFormat.format(cal.get(Calendar.SECOND)));\n sb.append('Z');\n result = sb.toString();\n DateHelper.pushCalendar(cal);\n }\n return result;\n }",
"public PartitionInfo partitionInfo(String partitionKey) {\n if (partitionKey == null) {\n throw new UnsupportedOperationException(\"Cannot get partition information for null partition key.\");\n }\n URI uri = new DatabaseURIHelper(db.getDBUri()).partition(partitionKey).build();\n return client.couchDbClient.get(uri, PartitionInfo.class);\n }",
"private void updateProjectProperties(Task task)\n {\n ProjectProperties props = m_projectFile.getProjectProperties();\n props.setComments(task.getNotes());\n }",
"@Nullable\n public T getItem(final int position) {\n if (position < 0 || position >= mObjects.size()) {\n return null;\n }\n return mObjects.get(position);\n }"
] |
Return a replica of this instance with the quality value of the given MediaType.
@return the same instance if the given MediaType doesn't have a quality value, or a new one otherwise | [
"public MediaType copyQualityValue(MediaType mediaType) {\n\t\tif (!mediaType.parameters.containsKey(PARAM_QUALITY_FACTOR)) {\n\t\t\treturn this;\n\t\t}\n\t\tMap<String, String> params = new LinkedHashMap<String, String>(this.parameters);\n\t\tparams.put(PARAM_QUALITY_FACTOR, mediaType.parameters.get(PARAM_QUALITY_FACTOR));\n\t\treturn new MediaType(this, params);\n\t}"
] | [
"public String convertToPrefixLength() throws AddressStringException {\n\t\tIPAddress address = toAddress();\n\t\tInteger prefix;\n\t\tif(address == null) {\n\t\t\tif(isPrefixOnly()) {\n\t\t\t\tprefix = getNetworkPrefixLength();\n\t\t\t} else {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t} else {\n\t\t\tprefix = address.getBlockMaskPrefixLength(true);\n\t\t\tif(prefix == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\treturn IPAddressSegment.toUnsignedString(prefix, 10, \n\t\t\t\tnew StringBuilder(IPAddressSegment.toUnsignedStringLength(prefix, 10) + 1).append(IPAddress.PREFIX_LEN_SEPARATOR)).toString();\n\t}",
"public Date getTime(Integer type)\n {\n Date result = null;\n\n byte[] item = m_map.get(type);\n if (item != null)\n {\n result = MPPUtility.getTime(item, 0);\n }\n\n return (result);\n }",
"private void deliverMediaDetailsUpdate(final MediaDetails details) {\n for (MediaDetailsListener listener : getMediaDetailsListeners()) {\n try {\n listener.detailsAvailable(details);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering media details response to listener\", t);\n }\n }\n }",
"public static vpntrafficpolicy_vpnglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpntrafficpolicy_vpnglobal_binding obj = new vpntrafficpolicy_vpnglobal_binding();\n\t\tobj.set_name(name);\n\t\tvpntrafficpolicy_vpnglobal_binding response[] = (vpntrafficpolicy_vpnglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private boolean canSuccessorProceed() {\n\n if (predecessor != null && !predecessor.canSuccessorProceed()) {\n return false;\n }\n\n synchronized (this) {\n while (responseCount < groups.size()) {\n try {\n wait();\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n return false;\n }\n }\n return !failed;\n }\n }",
"public ParallelTaskBuilder prepareHttpPut(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.getHttpMeta().setHttpMethod(HttpMethod.PUT);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\n\n }",
"public static <T> String join(Collection<T> col, String delim) {\n StringBuilder sb = new StringBuilder();\n Iterator<T> iter = col.iterator();\n if (iter.hasNext())\n sb.append(iter.next().toString());\n while (iter.hasNext()) {\n sb.append(delim);\n sb.append(iter.next().toString());\n }\n return sb.toString();\n }",
"public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {\n final ResourceRoot deploymentRoot = phaseContext.getDeploymentUnit().getAttachment(Attachments.DEPLOYMENT_ROOT);\n final ModuleSpecification moduleSpecification = phaseContext.getDeploymentUnit().getAttachment(\n Attachments.MODULE_SPECIFICATION);\n if(deploymentRoot == null)\n return;\n final ServicesAttachment servicesAttachments = phaseContext.getDeploymentUnit().getAttachment(Attachments.SERVICES);\n if(servicesAttachments != null && !servicesAttachments.getServiceImplementations(ServiceActivator.class.getName()).isEmpty()) {\n moduleSpecification.addSystemDependency(MSC_DEP);\n }\n }",
"public EventBus emitAsync(String event, Object... args) {\n return _emitWithOnceBus(eventContextAsync(event, args));\n }"
] |
Find the path to use .
Uses java annotations first and if not found, uses kubernetes annotations on the service object.
@param service
The target service.
@param qualifiers
The set of qualifiers.
@return Returns the resolved path of '/' as a fallback. | [
"private static String getPath(Service service, Annotation... qualifiers) {\n for (Annotation q : qualifiers) {\n if (q instanceof Scheme) {\n return ((Scheme) q).value();\n }\n }\n\n if (service.getMetadata() != null && service.getMetadata().getAnnotations() != null) {\n String s = service.getMetadata().getAnnotations().get(SERVICE_SCHEME);\n if (s != null && s.isEmpty()) {\n return s;\n }\n }\n return DEFAULT_PATH;\n }"
] | [
"public ProjectCalendar getEffectiveCalendar()\n {\n ProjectCalendar result = getCalendar();\n if (result == null)\n {\n result = getParentFile().getDefaultCalendar();\n }\n return result;\n }",
"public static BoxLegalHoldPolicy.Info createOngoing(BoxAPIConnection api, String name, String description) {\n URL url = ALL_LEGAL_HOLD_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n JsonObject requestJSON = new JsonObject()\n .add(\"policy_name\", name)\n .add(\"is_ongoing\", true);\n if (description != null) {\n requestJSON.add(\"description\", description);\n }\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n BoxLegalHoldPolicy createdPolicy = new BoxLegalHoldPolicy(api, responseJSON.get(\"id\").asString());\n return createdPolicy.new Info(responseJSON);\n }",
"public String stripThreadName(String threadId)\n {\n if (threadId == null)\n {\n return null;\n }\n else\n {\n int index = threadId.lastIndexOf('@');\n return index >= 0 ? threadId.substring(0, index) : threadId;\n }\n }",
"private String joinElements(int length)\n {\n StringBuilder sb = new StringBuilder();\n for (int index = 0; index < length; index++)\n {\n sb.append(m_elements.get(index));\n }\n return sb.toString();\n }",
"public static base_response create(nitro_service client, sslfipskey resource) throws Exception {\n\t\tsslfipskey createresource = new sslfipskey();\n\t\tcreateresource.fipskeyname = resource.fipskeyname;\n\t\tcreateresource.modulus = resource.modulus;\n\t\tcreateresource.exponent = resource.exponent;\n\t\treturn createresource.perform_operation(client,\"create\");\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 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}",
"public BoxFile.Info getFileInfo(String fileID) {\n URL url = FILE_INFO_URL_TEMPLATE.build(this.api.getBaseURL(), fileID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n BoxFile file = new BoxFile(this.api, jsonObject.get(\"id\").asString());\n return file.new Info(response.getJSON());\n }",
"public int tally() {\n long currentTimeMillis = clock.currentTimeMillis();\n\n // calculates time for which we remove any errors before\n final long removeTimesBeforeMillis = currentTimeMillis - windowMillis;\n\n synchronized (queue) {\n // drain out any expired timestamps but don't drain past empty\n while (!queue.isEmpty() && queue.peek() < removeTimesBeforeMillis) {\n queue.removeFirst();\n }\n return queue.size();\n }\n }"
] |
Validate some of the properties of this layer. | [
"public void postConstruct() throws URISyntaxException {\n WmsVersion.lookup(this.version);\n Assert.isTrue(validateBaseUrl(), \"invalid baseURL\");\n\n Assert.isTrue(this.layers.length > 0, \"There must be at least one layer defined for a WMS request\" +\n \" to make sense\");\n\n // OpenLayers 2 compatibility. It will post a single empty style no matter how many layers there are\n\n if (this.styles != null && this.styles.length != this.layers.length && this.styles.length == 1 &&\n this.styles[0].trim().isEmpty()) {\n this.styles = null;\n } else {\n Assert.isTrue(this.styles == null || this.layers.length == this.styles.length,\n String.format(\n \"If styles are defined then there must be one for each layer. Number of\" +\n \" layers: %s\\nStyles: %s\", this.layers.length,\n Arrays.toString(this.styles)));\n }\n\n if (this.imageFormat.indexOf('/') < 0) {\n LOGGER.warn(\"The format {} should be a mime type\", this.imageFormat);\n this.imageFormat = \"image/\" + this.imageFormat;\n }\n\n Assert.isTrue(this.method == HttpMethod.GET || this.method == HttpMethod.POST,\n String.format(\"Unsupported method %s for WMS layer\", this.method.toString()));\n }"
] | [
"public static <InnerT> Observable<InnerT> convertListToInnerAsync(Observable<List<InnerT>> innerList) {\n return innerList.flatMap(new Func1<List<InnerT>, Observable<InnerT>>() {\n @Override\n public Observable<InnerT> call(List<InnerT> inners) {\n return Observable.from(inners);\n }\n });\n }",
"public static boolean isPostJDK5(String bytecodeVersion) {\n return JDK5.equals(bytecodeVersion)\n || JDK6.equals(bytecodeVersion)\n || JDK7.equals(bytecodeVersion)\n || JDK8.equals(bytecodeVersion);\n }",
"public static base_response add(nitro_service client, linkset resource) throws Exception {\n\t\tlinkset addresource = new linkset();\n\t\taddresource.id = resource.id;\n\t\treturn addresource.add_resource(client);\n\t}",
"protected final void setDefaultValue() {\n\n m_start = null;\n m_end = null;\n m_patterntype = PatternType.NONE;\n m_dayOfMonth = 0;\n m_exceptions.clear();\n m_individualDates.clear();\n m_interval = 0;\n m_isEveryWorkingDay = false;\n m_isWholeDay = false;\n m_month = Month.JANUARY;\n m_seriesEndDate = null;\n m_seriesOccurrences = 0;\n m_weekDays.clear();\n m_weeksOfMonth.clear();\n m_endType = EndType.SINGLE;\n m_parentSeriesId = null;\n }",
"public GVRTexture getSplashTexture(GVRContext gvrContext) {\n Bitmap bitmap = BitmapFactory.decodeResource( //\n gvrContext.getContext().getResources(), //\n R.drawable.__default_splash_screen__);\n GVRTexture tex = new GVRTexture(gvrContext);\n tex.setImage(new GVRBitmapImage(gvrContext, bitmap));\n return tex;\n }",
"@Override\n public String getText() {\n String retType = AstToTextHelper.getClassText(returnType);\n String exceptionTypes = AstToTextHelper.getThrowsClauseText(exceptions);\n String parms = AstToTextHelper.getParametersText(parameters);\n return AstToTextHelper.getModifiersText(modifiers) + \" \" + retType + \" \" + name + \"(\" + parms + \") \" + exceptionTypes + \" { ... }\";\n }",
"protected DataSource wrapAsDataSource(JdbcConnectionDescriptor jcd,\r\n ObjectPool connectionPool)\r\n {\r\n final boolean allowConnectionUnwrap;\r\n if (jcd == null)\r\n {\r\n allowConnectionUnwrap = false;\r\n }\r\n else\r\n {\r\n final Properties properties = jcd.getConnectionPoolDescriptor().getDbcpProperties();\r\n final String allowConnectionUnwrapParam;\r\n allowConnectionUnwrapParam = properties.getProperty(PARAM_NAME_UNWRAP_ALLOWED);\r\n allowConnectionUnwrap = allowConnectionUnwrapParam != null &&\r\n Boolean.valueOf(allowConnectionUnwrapParam).booleanValue();\r\n }\r\n final PoolingDataSource dataSource;\r\n dataSource = new PoolingDataSource(connectionPool);\r\n dataSource.setAccessToUnderlyingConnectionAllowed(allowConnectionUnwrap);\r\n\r\n if(jcd != null)\r\n {\r\n final AbandonedConfig ac = jcd.getConnectionPoolDescriptor().getAbandonedConfig();\r\n if (ac.getRemoveAbandoned() && ac.getLogAbandoned()) {\r\n final LoggerWrapperPrintWriter loggerPiggyBack;\r\n loggerPiggyBack = new LoggerWrapperPrintWriter(log, Logger.ERROR);\r\n dataSource.setLogWriter(loggerPiggyBack);\r\n }\r\n }\r\n return dataSource;\r\n }",
"public static byte[] encode(byte[] ba, int offset, long v) {\n ba[offset + 0] = (byte) (v >>> 56);\n ba[offset + 1] = (byte) (v >>> 48);\n ba[offset + 2] = (byte) (v >>> 40);\n ba[offset + 3] = (byte) (v >>> 32);\n ba[offset + 4] = (byte) (v >>> 24);\n ba[offset + 5] = (byte) (v >>> 16);\n ba[offset + 6] = (byte) (v >>> 8);\n ba[offset + 7] = (byte) (v >>> 0);\n return ba;\n }",
"public String format(String value) {\n StringBuilder s = new StringBuilder();\n\n if (value != null && value.trim().length() > 0) {\n boolean continuationLine = false;\n\n s.append(getName()).append(\":\");\n if (isFirstLineEmpty()) {\n s.append(\"\\n\");\n continuationLine = true;\n }\n\n try {\n BufferedReader reader = new BufferedReader(new StringReader(value));\n String line;\n while ((line = reader.readLine()) != null) {\n if (continuationLine && line.trim().length() == 0) {\n // put a dot on the empty continuation lines\n s.append(\" .\\n\");\n } else {\n s.append(\" \").append(line).append(\"\\n\");\n }\n\n continuationLine = true;\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n return s.toString();\n }"
] |
Use this API to add sslcipher. | [
"public static base_response add(nitro_service client, sslcipher resource) throws Exception {\n\t\tsslcipher addresource = new sslcipher();\n\t\taddresource.ciphergroupname = resource.ciphergroupname;\n\t\taddresource.ciphgrpalias = resource.ciphgrpalias;\n\t\treturn addresource.add_resource(client);\n\t}"
] | [
"public void setCurrencySymbol(String symbol)\n {\n if (symbol == null)\n {\n symbol = DEFAULT_CURRENCY_SYMBOL;\n }\n\n set(ProjectField.CURRENCY_SYMBOL, symbol);\n }",
"static InjectionProvider<?>[] toArray(final Set<InjectionProvider<?>> injectionProviders) {\n return injectionProviders.toArray(new InjectionProvider<?>[injectionProviders.size()]);\n }",
"public static double J(int n, double x) {\r\n int j, m;\r\n double ax, bj, bjm, bjp, sum, tox, ans;\r\n boolean jsum;\r\n\r\n double ACC = 40.0;\r\n double BIGNO = 1.0e+10;\r\n double BIGNI = 1.0e-10;\r\n\r\n if (n == 0) return J0(x);\r\n if (n == 1) return J(x);\r\n\r\n ax = Math.abs(x);\r\n if (ax == 0.0) return 0.0;\r\n else if (ax > (double) n) {\r\n tox = 2.0 / ax;\r\n bjm = J0(ax);\r\n bj = J(ax);\r\n for (j = 1; j < n; j++) {\r\n bjp = j * tox * bj - bjm;\r\n bjm = bj;\r\n bj = bjp;\r\n }\r\n ans = bj;\r\n } else {\r\n tox = 2.0 / ax;\r\n m = 2 * ((n + (int) Math.sqrt(ACC * n)) / 2);\r\n jsum = false;\r\n bjp = ans = sum = 0.0;\r\n bj = 1.0;\r\n for (j = m; j > 0; j--) {\r\n bjm = j * tox * bj - bjp;\r\n bjp = bj;\r\n bj = bjm;\r\n if (Math.abs(bj) > BIGNO) {\r\n bj *= BIGNI;\r\n bjp *= BIGNI;\r\n ans *= BIGNI;\r\n sum *= BIGNI;\r\n }\r\n if (jsum) sum += bj;\r\n jsum = !jsum;\r\n if (j == n) ans = bjp;\r\n }\r\n sum = 2.0 * sum - bj;\r\n ans /= sum;\r\n }\r\n\r\n return x < 0.0 && n % 2 == 1 ? -ans : ans;\r\n }",
"public static List<String> getDefaultConversionProviderChain(){\n List<String> defaultChain = getMonetaryConversionsSpi()\n .getDefaultProviderChain();\n Objects.requireNonNull(defaultChain, \"No default provider chain provided by SPI: \" +\n getMonetaryConversionsSpi().getClass().getName());\n return defaultChain;\n }",
"public Number getUnits(int field) throws MPXJException\n {\n Number result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n try\n {\n result = Double.valueOf(m_formats.getUnitsDecimalFormat().parse(m_fields[field]).doubleValue() * 100);\n }\n\n catch (ParseException ex)\n {\n throw new MPXJException(\"Failed to parse units\", ex);\n }\n }\n else\n {\n result = null;\n }\n\n return (result);\n }",
"public BoxFolder.Info createFolder(String name) {\n JsonObject parent = new JsonObject();\n parent.add(\"id\", this.getID());\n\n JsonObject newFolder = new JsonObject();\n newFolder.add(\"name\", name);\n newFolder.add(\"parent\", parent);\n\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), CREATE_FOLDER_URL.build(this.getAPI().getBaseURL()),\n \"POST\");\n request.setBody(newFolder.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxFolder createdFolder = new BoxFolder(this.getAPI(), responseJSON.get(\"id\").asString());\n return createdFolder.new Info(responseJSON);\n }",
"public List<TimephasedWork> getCompleteWork(ProjectCalendar calendar, ResourceAssignment resourceAssignment, byte[] data)\n {\n LinkedList<TimephasedWork> list = new LinkedList<TimephasedWork>();\n\n if (calendar != null && data != null && data.length > 2 && MPPUtility.getShort(data, 0) > 0)\n {\n Date startDate = resourceAssignment.getStart();\n double finishTime = MPPUtility.getInt(data, 24);\n\n int blockCount = MPPUtility.getShort(data, 0);\n double previousCumulativeWork = 0;\n TimephasedWork previousAssignment = null;\n\n int index = 32;\n int currentBlock = 0;\n while (currentBlock < blockCount && index + 20 <= data.length)\n {\n double time = MPPUtility.getInt(data, index + 0);\n\n // If the start of this block is before the start of the assignment, or after the end of the assignment\n // the values don't make sense, so we'll just set the start of this block to be the start of the assignment.\n // This deals with an issue where odd timephased data like this was causing an MPP file to be read\n // extremely slowly.\n if (time < 0 || time > finishTime)\n {\n time = 0;\n }\n else\n {\n time /= 80;\n }\n Duration startWork = Duration.getInstance(time, TimeUnit.MINUTES);\n\n double currentCumulativeWork = (long) MPPUtility.getDouble(data, index + 4);\n double assignmentDuration = currentCumulativeWork - previousCumulativeWork;\n previousCumulativeWork = currentCumulativeWork;\n assignmentDuration /= 1000;\n Duration totalWork = Duration.getInstance(assignmentDuration, TimeUnit.MINUTES);\n time = (long) MPPUtility.getDouble(data, index + 12);\n time /= 125;\n time *= 6;\n Duration workPerDay = Duration.getInstance(time, TimeUnit.MINUTES);\n\n Date start;\n if (startWork.getDuration() == 0)\n {\n start = startDate;\n }\n else\n {\n start = calendar.getDate(startDate, startWork, true);\n }\n\n TimephasedWork assignment = new TimephasedWork();\n assignment.setStart(start);\n assignment.setAmountPerDay(workPerDay);\n assignment.setTotalAmount(totalWork);\n\n if (previousAssignment != null)\n {\n Date finish = calendar.getDate(startDate, startWork, false);\n previousAssignment.setFinish(finish);\n if (previousAssignment.getStart().getTime() == previousAssignment.getFinish().getTime())\n {\n list.removeLast();\n }\n }\n\n list.add(assignment);\n previousAssignment = assignment;\n\n index += 20;\n ++currentBlock;\n }\n\n if (previousAssignment != null)\n {\n Duration finishWork = Duration.getInstance(finishTime / 80, TimeUnit.MINUTES);\n Date finish = calendar.getDate(startDate, finishWork, false);\n previousAssignment.setFinish(finish);\n if (previousAssignment.getStart().getTime() == previousAssignment.getFinish().getTime())\n {\n list.removeLast();\n }\n }\n }\n\n return list;\n }",
"public static String[] randomResourceNames(String prefix, int maxLen, int count) {\n String[] names = new String[count];\n ResourceNamer resourceNamer = SdkContext.getResourceNamerFactory().createResourceNamer(\"\");\n for (int i = 0; i < count; i++) {\n names[i] = resourceNamer.randomName(prefix, maxLen);\n }\n return names;\n }",
"public ListExternalToolsOptions searchTerm(String searchTerm) {\n if(searchTerm == null || searchTerm.length() < 3) {\n throw new IllegalArgumentException(\"Search term must be at least 3 characters\");\n }\n addSingleItem(\"search_term\", searchTerm);\n return this;\n }"
] |
This method extracts data for a single calendar from a Phoenix file.
@param calendar calendar data | [
"private void readCalendar(Calendar calendar)\n {\n // Create the calendar\n ProjectCalendar mpxjCalendar = m_projectFile.addCalendar();\n mpxjCalendar.setName(calendar.getName());\n\n // Default all days to working\n for (Day day : Day.values())\n {\n mpxjCalendar.setWorkingDay(day, true);\n }\n\n // Mark non-working days\n List<NonWork> nonWorkingDays = calendar.getNonWork();\n for (NonWork nonWorkingDay : nonWorkingDays)\n {\n // TODO: handle recurring exceptions\n if (nonWorkingDay.getType().equals(\"internal_weekly\"))\n {\n mpxjCalendar.setWorkingDay(nonWorkingDay.getWeekday(), false);\n }\n }\n\n // Add default working hours for working days\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 Collection<Blog> getList() throws FlickrException {\r\n List<Blog> blogs = new ArrayList<Blog>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIST);\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element blogsElement = response.getPayload();\r\n NodeList blogNodes = blogsElement.getElementsByTagName(\"blog\");\r\n for (int i = 0; i < blogNodes.getLength(); i++) {\r\n Element blogElement = (Element) blogNodes.item(i);\r\n Blog blog = new Blog();\r\n blog.setId(blogElement.getAttribute(\"id\"));\r\n blog.setName(blogElement.getAttribute(\"name\"));\r\n blog.setNeedPassword(\"1\".equals(blogElement.getAttribute(\"needspassword\")));\r\n blog.setUrl(blogElement.getAttribute(\"url\"));\r\n blogs.add(blog);\r\n }\r\n return blogs;\r\n }",
"public <T extends Widget & Checkable> List<T> getCheckedWidgets() {\n List<T> checked = new ArrayList<>();\n\n for (Widget c : getChildren()) {\n if (c instanceof Checkable && ((Checkable) c).isChecked()) {\n checked.add((T) c);\n }\n }\n\n return checked;\n }",
"private void processKnownType(FieldType type)\n {\n //System.out.println(\"Header: \" + type);\n //System.out.println(ByteArrayHelper.hexdump(m_data, m_dataOffset, 36, false, 16, \"\"));\n\n GraphicalIndicator indicator = m_container.getCustomField(type).getGraphicalIndicator();\n indicator.setFieldType(type);\n int flags = m_data[m_dataOffset];\n indicator.setProjectSummaryInheritsFromSummaryRows((flags & 0x08) != 0);\n indicator.setSummaryRowsInheritFromNonSummaryRows((flags & 0x04) != 0);\n indicator.setDisplayGraphicalIndicators((flags & 0x02) != 0);\n indicator.setShowDataValuesInToolTips((flags & 0x01) != 0);\n m_dataOffset += 20;\n\n int nonSummaryRowOffset = MPPUtility.getInt(m_data, m_dataOffset) - 36;\n m_dataOffset += 4;\n\n int summaryRowOffset = MPPUtility.getInt(m_data, m_dataOffset) - 36;\n m_dataOffset += 4;\n\n int projectSummaryOffset = MPPUtility.getInt(m_data, m_dataOffset) - 36;\n m_dataOffset += 4;\n\n int dataSize = MPPUtility.getInt(m_data, m_dataOffset) - 36;\n m_dataOffset += 4;\n\n //System.out.println(\"Data\");\n //System.out.println(ByteArrayHelper.hexdump(m_data, m_dataOffset, dataSize, false, 16, \"\"));\n\n int maxNonSummaryRowOffset = m_dataOffset + summaryRowOffset;\n int maxSummaryRowOffset = m_dataOffset + projectSummaryOffset;\n int maxProjectSummaryOffset = m_dataOffset + dataSize;\n\n m_dataOffset += nonSummaryRowOffset;\n\n while (m_dataOffset + 2 < maxNonSummaryRowOffset)\n {\n indicator.addNonSummaryRowCriteria(processCriteria(type));\n }\n\n while (m_dataOffset + 2 < maxSummaryRowOffset)\n {\n indicator.addSummaryRowCriteria(processCriteria(type));\n }\n\n while (m_dataOffset + 2 < maxProjectSummaryOffset)\n {\n indicator.addProjectSummaryCriteria(processCriteria(type));\n }\n }",
"@Deprecated\r\n public static URL buildUrl(String host, int port, String path, Map<String, String> parameters) throws MalformedURLException {\r\n return buildUrl(\"http\", port, path, parameters);\r\n }",
"public String addPostRunDependent(FunctionalTaskItem dependent) {\n Objects.requireNonNull(dependent);\n return this.taskGroup().addPostRunDependent(dependent);\n }",
"public void addClass(ClassNode node) {\n node = node.redirect();\n String name = node.getName();\n ClassNode stored = classes.get(name);\n if (stored != null && stored != node) {\n // we have a duplicate class!\n // One possibility for this is, that we declared a script and a\n // class in the same file and named the class like the file\n SourceUnit nodeSource = node.getModule().getContext();\n SourceUnit storedSource = stored.getModule().getContext();\n String txt = \"Invalid duplicate class definition of class \" + node.getName() + \" : \";\n if (nodeSource == storedSource) {\n // same class in same source\n txt += \"The source \" + nodeSource.getName() + \" contains at least two definitions of the class \" + node.getName() + \".\\n\";\n if (node.isScriptBody() || stored.isScriptBody()) {\n txt += \"One of the classes is an explicit generated class using the class statement, the other is a class generated from\" +\n \" the script body based on the file name. Solutions are to change the file name or to change the class name.\\n\";\n }\n } else {\n txt += \"The sources \" + nodeSource.getName() + \" and \" + storedSource.getName() + \" each contain a class with the name \" + node.getName() + \".\\n\";\n }\n nodeSource.getErrorCollector().addErrorAndContinue(\n new SyntaxErrorMessage(new SyntaxException(txt, node.getLineNumber(), node.getColumnNumber(), node.getLastLineNumber(), node.getLastColumnNumber()), nodeSource)\n );\n }\n classes.put(name, node);\n\n if (classesToCompile.containsKey(name)) {\n ClassNode cn = classesToCompile.get(name);\n cn.setRedirect(node);\n classesToCompile.remove(name);\n }\n }",
"public synchronized Set<RegistrationPoint> getRegistrationPoints() {\n Set<RegistrationPoint> result = new HashSet<>();\n for (List<RegistrationPoint> registrationPoints : registrationPoints.values()) {\n result.addAll(registrationPoints);\n }\n return Collections.unmodifiableSet(result);\n }",
"public void recordCheckoutQueueLength(SocketDestination dest, int queueLength) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordCheckoutQueueLength(null, queueLength);\n recordCheckoutQueueLength(null, queueLength);\n } else {\n this.checkoutQueueLengthHistogram.insert(queueLength);\n checkMonitoringInterval();\n }\n }",
"public void setWeeklyDay(Day day, boolean value)\n {\n if (value)\n {\n m_days.add(day);\n }\n else\n {\n m_days.remove(day);\n }\n }"
] |
Sets either the upper or low triangle of a matrix to zero | [
"public static void zeroTriangle( boolean upper , DMatrixRBlock A )\n {\n int blockLength = A.blockLength;\n\n if( upper ) {\n for( int i = 0; i < A.numRows; i += blockLength ) {\n int h = Math.min(blockLength,A.numRows-i);\n\n for( int j = i; j < A.numCols; j += blockLength ) {\n int w = Math.min(blockLength,A.numCols-j);\n\n int index = i*A.numCols + h*j;\n\n if( j == i ) {\n for( int k = 0; k < h; k++ ) {\n for( int l = k+1; l < w; l++ ) {\n A.data[index + w*k+l ] = 0;\n }\n }\n } else {\n for( int k = 0; k < h; k++ ) {\n for( int l = 0; l < w; l++ ) {\n A.data[index + w*k+l ] = 0;\n }\n }\n }\n }\n }\n } else {\n for( int i = 0; i < A.numRows; i += blockLength ) {\n int h = Math.min(blockLength,A.numRows-i);\n\n for( int j = 0; j <= i; j += blockLength ) {\n int w = Math.min(blockLength,A.numCols-j);\n\n int index = i*A.numCols + h*j;\n\n if( j == i ) {\n for( int k = 0; k < h; k++ ) {\n int z = Math.min(k,w);\n for( int l = 0; l < z; l++ ) {\n A.data[index + w*k+l ] = 0;\n }\n }\n } else {\n for( int k = 0; k < h; k++ ) {\n for( int l = 0; l < w; l++ ) {\n A.data[index + w*k+l ] = 0;\n }\n }\n }\n }\n }\n }\n }"
] | [
"protected Violation createViolation(Integer lineNumber, String sourceLine, String message) {\n Violation violation = new Violation();\n violation.setRule(this);\n violation.setSourceLine(sourceLine);\n violation.setLineNumber(lineNumber);\n violation.setMessage(message);\n return violation;\n }",
"public static GVRCameraRig makeInstance(GVRContext gvrContext) {\n final GVRCameraRig result = gvrContext.getApplication().getDelegate().makeCameraRig(gvrContext);\n result.init(gvrContext);\n return result;\n }",
"public static Node removePartitionsFromNode(final Node node,\n final Set<Integer> donatedPartitions) {\n List<Integer> deepCopy = new ArrayList<Integer>(node.getPartitionIds());\n deepCopy.removeAll(donatedPartitions);\n return updateNode(node, deepCopy);\n }",
"public Iterable<BoxMetadataCascadePolicy.Info> getMetadataCascadePolicies(String... fields) {\n Iterable<BoxMetadataCascadePolicy.Info> cascadePoliciesInfo =\n BoxMetadataCascadePolicy.getAll(this.getAPI(), this.getID(), fields);\n\n return cascadePoliciesInfo;\n }",
"private List<I_CmsSearchConfigurationSortOption> getSortOptions() {\n\n final List<I_CmsSearchConfigurationSortOption> options = new ArrayList<I_CmsSearchConfigurationSortOption>();\n final CmsXmlContentValueSequence sortOptions = m_xml.getValueSequence(XML_ELEMENT_SORTOPTIONS, m_locale);\n if (sortOptions == null) {\n return null;\n } else {\n for (int i = 0; i < sortOptions.getElementCount(); i++) {\n final I_CmsSearchConfigurationSortOption option = parseSortOption(\n sortOptions.getValue(i).getPath() + \"/\");\n if (option != null) {\n options.add(option);\n }\n }\n return options;\n }\n }",
"public static appflowpolicylabel get(nitro_service service, String labelname) throws Exception{\n\t\tappflowpolicylabel obj = new appflowpolicylabel();\n\t\tobj.set_labelname(labelname);\n\t\tappflowpolicylabel response = (appflowpolicylabel) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static Shell createConsoleShell(String prompt, String appName, Object... handlers) {\n ConsoleIO io = new ConsoleIO();\n\n List<String> path = new ArrayList<String>(1);\n path.add(prompt);\n\n MultiMap<String, Object> modifAuxHandlers = new ArrayHashMultiMap<String, Object>();\n modifAuxHandlers.put(\"!\", io);\n\n Shell theShell = new Shell(new Shell.Settings(io, io, modifAuxHandlers, false),\n new CommandTable(new DashJoinedNamer(true)), path);\n theShell.setAppName(appName);\n\n theShell.addMainHandler(theShell, \"!\");\n theShell.addMainHandler(new HelpCommandHandler(), \"?\");\n for (Object h : handlers) {\n theShell.addMainHandler(h, \"\");\n }\n\n return theShell;\n }",
"private ColumnDefinition[] columnDefinitions(ColumnDefinition[] columns, String[] order)\n {\n Map<String, ColumnDefinition> map = makeColumnMap(columns);\n ColumnDefinition[] result = new ColumnDefinition[order.length];\n for (int index = 0; index < order.length; index++)\n {\n result[index] = map.get(order[index]);\n }\n return result;\n }",
"public void setModificationState(ModificationState newModificationState)\r\n {\r\n if(newModificationState != modificationState)\r\n {\r\n if(log.isDebugEnabled())\r\n {\r\n log.debug(\"object state transition for object \" + this.oid + \" (\"\r\n + modificationState + \" --> \" + newModificationState + \")\");\r\n// try{throw new Exception();}catch(Exception e)\r\n// {\r\n// e.printStackTrace();\r\n// }\r\n }\r\n modificationState = newModificationState;\r\n }\r\n }"
] |
Use this API to delete ntpserver resources. | [
"public static base_responses delete(nitro_service client, ntpserver resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tntpserver deleteresources[] = new ntpserver[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new ntpserver();\n\t\t\t\tdeleteresources[i].serverip = resources[i].serverip;\n\t\t\t\tdeleteresources[i].servername = resources[i].servername;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}"
] | [
"public AbstractGraph getModuleGraph(final String moduleId) {\n final ModuleHandler moduleHandler = new ModuleHandler(repoHandler);\n final DbModule module = moduleHandler.getModule(moduleId);\n final DbOrganization organization = moduleHandler.getOrganization(module);\n\n filters.setCorporateFilter(new CorporateFilter(organization));\n\n final AbstractGraph graph = new ModuleGraph();\n addModuleToGraph(module, graph, 0);\n\n return graph;\n }",
"protected Object getProxyFromResultSet() throws PersistenceBrokerException\r\n {\r\n // 1. get Identity of current row:\r\n Identity oid = getIdentityFromResultSet();\r\n\r\n // 2. return a Proxy instance:\r\n return getBroker().createProxy(getItemProxyClass(), oid);\r\n }",
"private static void dumpRelationList(List<Relation> relations)\n {\n if (relations != null && relations.isEmpty() == false)\n {\n if (relations.size() > 1)\n {\n System.out.print('\"');\n }\n boolean first = true;\n for (Relation relation : relations)\n {\n if (!first)\n {\n System.out.print(',');\n }\n first = false;\n System.out.print(relation.getTargetTask().getID());\n Duration lag = relation.getLag();\n if (relation.getType() != RelationType.FINISH_START || lag.getDuration() != 0)\n {\n System.out.print(relation.getType());\n }\n\n if (lag.getDuration() != 0)\n {\n if (lag.getDuration() > 0)\n {\n System.out.print(\"+\");\n }\n System.out.print(lag);\n }\n }\n if (relations.size() > 1)\n {\n System.out.print('\"');\n }\n }\n }",
"static DisplayMetrics getDisplayMetrics(final Context context) {\n final WindowManager\n windowManager =\n (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);\n final DisplayMetrics metrics = new DisplayMetrics();\n windowManager.getDefaultDisplay().getMetrics(metrics);\n return metrics;\n }",
"@SuppressWarnings(\"deprecation\")\n public ResponseFromManager sendTaskToExecutionManager(ParallelTask task) {\n\n ResponseFromManager commandResponseFromManager = null;\n ActorRef executionManager = null;\n try {\n // Start new job\n logger.info(\"!!STARTED sendAgentCommandToManager : \"\n + task.getTaskId() + \" at \"\n + PcDateUtils.getNowDateTimeStr());\n\n executionManager = ActorConfig.createAndGetActorSystem().actorOf(\n Props.create(ExecutionManager.class, task),\n \"ExecutionManager-\" + task.getTaskId());\n\n final FiniteDuration duration = Duration.create(task.getConfig()\n .getTimeoutAskManagerSec(), TimeUnit.SECONDS);\n // Timeout timeout = new\n // Timeout(FiniteDuration.parse(\"300 seconds\"));\n Future<Object> future = Patterns.ask(executionManager,\n new InitialRequestToManager(task), new Timeout(duration));\n\n // set ref\n task.executionManager = executionManager;\n\n commandResponseFromManager = (ResponseFromManager) Await.result(\n future, duration);\n\n logger.info(\"!!COMPLETED sendTaskToExecutionManager : \"\n + task.getTaskId() + \" at \"\n + PcDateUtils.getNowDateTimeStr()\n + \" \\t\\t GenericResponseMap in future size: \"\n + commandResponseFromManager.getResponseCount());\n\n } catch (Exception ex) {\n logger.error(\"Exception in sendTaskToExecutionManager {} details {}: \",\n ex, ex);\n\n } finally {\n // stop the manager\n if (executionManager != null && !executionManager.isTerminated()) {\n ActorConfig.createAndGetActorSystem().stop(executionManager);\n }\n\n if (task.getConfig().isAutoSaveLogToLocal()) {\n task.saveLogToLocal();\n }\n\n }\n\n return commandResponseFromManager;\n\n }",
"public Label htmlLabel(String html) {\n\n Label label = new Label();\n label.setContentMode(ContentMode.HTML);\n label.setValue(html);\n return label;\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 }",
"public AbstractSqlCreator setParameter(String name, Object value) {\n ppsc.setParameter(name, value);\n return this;\n }",
"protected String createGlobalStyle()\n {\n StringBuilder ret = new StringBuilder();\n ret.append(createFontFaces());\n ret.append(\"\\n\");\n ret.append(defaultStyle);\n return ret.toString();\n }"
] |
2-D Double array to integer array.
@param array Double array.
@return Integer array. | [
"public static int[][] toInt(double[][] array) {\n int[][] n = new int[array.length][array[0].length];\n for (int i = 0; i < array.length; i++) {\n for (int j = 0; j < array[0].length; j++) {\n n[i][j] = (int) array[i][j];\n }\n }\n return n;\n }"
] | [
"public boolean isEUI64(boolean partial) {\n\t\tint segmentCount = getSegmentCount();\n\t\tint endIndex = addressSegmentIndex + segmentCount;\n\t\tif(addressSegmentIndex <= 5) {\n\t\t\tif(endIndex > 6) {\n\t\t\t\tint index3 = 5 - addressSegmentIndex;\n\t\t\t\tIPv6AddressSegment seg3 = getSegment(index3);\n\t\t\t\tIPv6AddressSegment seg4 = getSegment(index3 + 1);\n\t\t\t\treturn seg4.matchesWithMask(0xfe00, 0xff00) && seg3.matchesWithMask(0xff, 0xff);\n\t\t\t} else if(partial && endIndex == 6) {\n\t\t\t\tIPv6AddressSegment seg3 = getSegment(5 - addressSegmentIndex);\n\t\t\t\treturn seg3.matchesWithMask(0xff, 0xff);\n\t\t\t}\n\t\t} else if(partial && addressSegmentIndex == 6 && endIndex > 6) {\n\t\t\tIPv6AddressSegment seg4 = getSegment(6 - addressSegmentIndex);\n\t\t\treturn seg4.matchesWithMask(0xfe00, 0xff00);\n\t\t}\n\t\treturn partial;\n\t}",
"public static Thread addShutdownHook(final Process process) {\n final Thread thread = new Thread(new Runnable() {\n @Override\n public void run() {\n if (process != null) {\n process.destroy();\n try {\n process.waitFor();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n }\n }\n });\n thread.setDaemon(true);\n Runtime.getRuntime().addShutdownHook(thread);\n return thread;\n }",
"public double[] getScaleDenominators() {\n double[] dest = new double[this.scaleDenominators.length];\n System.arraycopy(this.scaleDenominators, 0, dest, 0, this.scaleDenominators.length);\n return dest;\n }",
"public void symm2x2_fast( double a11 , double a12, double a22 )\n {\n// double p = (a11 - a22)*0.5;\n// double r = Math.sqrt(p*p + a12*a12);\n//\n// value0.real = a22 + a12*a12/(r-p);\n// value1.real = a22 - a12*a12/(r+p);\n// }\n//\n// public void symm2x2_std( double a11 , double a12, double a22 )\n// {\n double left = (a11+a22)*0.5;\n double b = (a11-a22)*0.5;\n double right = Math.sqrt(b*b+a12*a12);\n value0.real = left + right;\n value1.real = left - right;\n }",
"public ArrayList<Double> segmentCost(ProjectCalendar projectCalendar, List<TimephasedCost> cost, TimescaleUnits rangeUnits, ArrayList<DateRange> dateList)\n {\n ArrayList<Double> result = new ArrayList<Double>(dateList.size());\n int lastStartIndex = 0;\n\n //\n // Iterate through the list of dates range we are interested in.\n // Each date range in this list corresponds to a column\n // shown on the \"timescale\" view by MS Project\n //\n for (DateRange range : dateList)\n {\n //\n // If the current date range does not intersect with any of the\n // assignment date ranges in the list, then we show a zero\n // duration for this date range.\n //\n int startIndex = lastStartIndex == -1 ? -1 : getStartIndex(range, cost, lastStartIndex);\n if (startIndex == -1)\n {\n result.add(NumberHelper.DOUBLE_ZERO);\n }\n else\n {\n //\n // We have found an assignment which intersects with the current\n // date range, call the method below to determine how\n // much time from this resource assignment can be allocated\n // to the current date range.\n //\n result.add(getRangeCost(projectCalendar, rangeUnits, range, cost, startIndex));\n lastStartIndex = startIndex;\n }\n }\n\n return result;\n }",
"private void proxyPause() {\n logger.info(\"Pausing after cluster state has changed to allow proxy bridges to be established. \"\n + \"Will start rebalancing work on servers in \"\n + proxyPauseSec\n + \" seconds.\");\n try {\n Thread.sleep(TimeUnit.SECONDS.toMillis(proxyPauseSec));\n } catch(InterruptedException e) {\n logger.warn(\"Sleep interrupted in proxy pause.\");\n }\n }",
"protected View postDeclineView() {\n\t\treturn new TopLevelWindowRedirect() {\n\t\t\t@Override\n\t\t\tprotected String getRedirectUrl(Map<String, ?> model) {\n\t\t\t\treturn postDeclineUrl;\n\t\t\t}\n\t\t};\n\t}",
"public static void closeThrowSqlException(Closeable closeable, String label) throws SQLException {\n\t\tif (closeable != null) {\n\t\t\ttry {\n\t\t\t\tcloseable.close();\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow SqlExceptionUtil.create(\"could not close \" + label, e);\n\t\t\t}\n\t\t}\n\t}",
"public static authenticationradiusaction get(nitro_service service, String name) throws Exception{\n\t\tauthenticationradiusaction obj = new authenticationradiusaction();\n\t\tobj.set_name(name);\n\t\tauthenticationradiusaction response = (authenticationradiusaction) obj.get_resource(service);\n\t\treturn response;\n\t}"
] |
Return the list of module that uses the targeted artifact
@param gavc String
@param filters FiltersHolder
@return List<DbModule> | [
"public List<DbModule> getAncestors(final String gavc, final FiltersHolder filters) {\n final DbArtifact dbArtifact = getArtifact(gavc);\n return repositoryHandler.getAncestors(dbArtifact, filters);\n }"
] | [
"private static void renderFreemarkerTemplate(Path templatePath, Map vars, Path outputPath)\n throws IOException, TemplateException\n {\n if(templatePath == null)\n throw new WindupException(\"templatePath is null\");\n\n freemarker.template.Configuration freemarkerConfig = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_26);\n DefaultObjectWrapperBuilder objectWrapperBuilder = new DefaultObjectWrapperBuilder(freemarker.template.Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);\n objectWrapperBuilder.setUseAdaptersForContainers(true);\n objectWrapperBuilder.setIterableSupport(true);\n freemarkerConfig.setObjectWrapper(objectWrapperBuilder.build());\n freemarkerConfig.setTemplateLoader(new FurnaceFreeMarkerTemplateLoader());\n Template template = freemarkerConfig.getTemplate(templatePath.toString().replace('\\\\', '/'));\n try (FileWriter fw = new FileWriter(outputPath.toFile()))\n {\n template.process(vars, fw);\n }\n }",
"public static base_response unset(nitro_service client, rnatparam resource, String[] args) throws Exception{\n\t\trnatparam unsetresource = new rnatparam();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"@JmxGetter(name = \"avgFetchKeysNetworkTimeMs\", description = \"average time spent on network, for fetch keys\")\n public double getAvgFetchKeysNetworkTimeMs() {\n return networkTimeCounterMap.get(Operation.FETCH_KEYS).getAvgEventValue() / Time.NS_PER_MS;\n }",
"public String calculateLabelUnit(final CoordinateReferenceSystem mapCrs) {\n String unit;\n if (this.labelProjection != null) {\n unit = this.labelCRS.getCoordinateSystem().getAxis(0).getUnit().toString();\n } else {\n unit = mapCrs.getCoordinateSystem().getAxis(0).getUnit().toString();\n }\n\n return unit;\n }",
"public void setup( int numSamples , int sampleSize ) {\n mean = new double[ sampleSize ];\n A.reshape(numSamples,sampleSize,false);\n sampleIndex = 0;\n numComponents = -1;\n }",
"public Metadata remove(String path) {\n this.values.remove(this.pathToProperty(path));\n this.addOp(\"remove\", path, (String) null);\n return this;\n }",
"protected boolean clearSpecial(DatabaseConnection connection, Logger logger) {\n\t\tNestedConnection currentSaved = specialConnection.get();\n\t\tboolean cleared = false;\n\t\tif (connection == null) {\n\t\t\t// ignored\n\t\t} else if (currentSaved == null) {\n\t\t\tlogger.error(\"no connection has been saved when clear() called\");\n\t\t} else if (currentSaved.connection == connection) {\n\t\t\tif (currentSaved.decrementAndGet() == 0) {\n\t\t\t\t// we only clear the connection if nested counter is 0\n\t\t\t\tspecialConnection.set(null);\n\t\t\t}\n\t\t\tcleared = true;\n\t\t} else {\n\t\t\tlogger.error(\"connection saved {} is not the one being cleared {}\", currentSaved.connection, connection);\n\t\t}\n\t\t// release should then be called after clear\n\t\treturn cleared;\n\t}",
"private Date readOptionalDate(JSONValue val) {\n\n JSONString str = null == val ? null : val.isString();\n if (str != null) {\n try {\n return new Date(Long.parseLong(str.stringValue()));\n } catch (@SuppressWarnings(\"unused\") NumberFormatException e) {\n // do nothing - return the default value\n }\n }\n return null;\n }",
"protected final void setDerivedEndType() {\n\n m_endType = getPatternType().equals(PatternType.NONE) || getPatternType().equals(PatternType.INDIVIDUAL)\n ? EndType.SINGLE\n : null != getSeriesEndDate() ? EndType.DATE : EndType.TIMES;\n }"
] |
Manual check because introducing a capability can't be done without a full refactoring.
This has to go as soon as the management interfaces are redesigned.
@param context the OperationContext
@param otherManagementEndpoint : the address to check that may provide an exposed jboss-remoting endpoint.
@throws OperationFailedException in case we can't remove the management resource. | [
"public static void isManagementResourceRemoveable(OperationContext context, PathAddress otherManagementEndpoint) throws OperationFailedException {\n ModelNode remotingConnector;\n try {\n remotingConnector = context.readResourceFromRoot(\n PathAddress.pathAddress(PathElement.pathElement(SUBSYSTEM, \"jmx\"), PathElement.pathElement(\"remoting-connector\", \"jmx\")), false).getModel();\n } catch (Resource.NoSuchResourceException ex) {\n return;\n }\n if (!remotingConnector.hasDefined(USE_MGMT_ENDPOINT) ||\n (remotingConnector.hasDefined(USE_MGMT_ENDPOINT) && context.resolveExpressions(remotingConnector.get(USE_MGMT_ENDPOINT)).asBoolean(true))) {\n try {\n context.readResourceFromRoot(otherManagementEndpoint, false);\n } catch (NoSuchElementException ex) {\n throw RemotingLogger.ROOT_LOGGER.couldNotRemoveResource(context.getCurrentAddress());\n }\n }\n }"
] | [
"private Path getTempDir() {\n if (this.tempDir == null) {\n if (this.dir != null) {\n this.tempDir = dir;\n } else {\n this.tempDir = getProject().getBaseDir().toPath();\n }\n }\n return tempDir;\n }",
"public synchronized void shutdown() {\n checkIsRunning();\n try {\n beanManager().fireEvent(new ContainerBeforeShutdown(id), BeforeDestroyed.Literal.APPLICATION);\n } finally {\n discard(id);\n // Destroy all the dependent beans correctly\n creationalContext.release();\n beanManager().fireEvent(new ContainerShutdown(id), Destroyed.Literal.APPLICATION);\n bootstrap.shutdown();\n WeldSELogger.LOG.weldContainerShutdown(id);\n }\n }",
"public CollectionRequest<Task> findByTag(String tag) {\n \n String path = String.format(\"/tags/%s/tasks\", tag);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }",
"public static <R extends Resource<?>, U extends PaginatedResponse<R>> Flux<R> getResources(U response) {\n return Flux.fromIterable(response.getResources());\n }",
"public static String getTemplateAsString(String fileName) throws IOException {\n // in .jar file\n String fNameJar = getFileNameInPath(fileName);\n InputStream inStream = DomUtils.class.getResourceAsStream(\"/\"\n + fNameJar);\n if (inStream == null) {\n // try to find file normally\n File f = new File(fileName);\n if (f.exists()) {\n inStream = new FileInputStream(f);\n } else {\n throw new IOException(\"Cannot find \" + fileName + \" or \"\n + fNameJar);\n }\n }\n\n BufferedReader bufferedReader = new BufferedReader(\n new InputStreamReader(inStream));\n String line;\n StringBuilder stringBuilder = new StringBuilder();\n\n while ((line = bufferedReader.readLine()) != null) {\n stringBuilder.append(line).append(\"\\n\");\n }\n\n bufferedReader.close();\n return stringBuilder.toString();\n }",
"private String getProject(CmsObject cms, CmsFavoriteEntry entry) throws CmsException {\n\n String result = m_projectLabels.get(entry.getProjectId());\n if (result == null) {\n result = cms.readProject(entry.getProjectId()).getName();\n m_projectLabels.put(entry.getProjectId(), result);\n }\n return result;\n }",
"private void writeCalendar(ProjectCalendar record) throws IOException\n {\n //\n // Test used to ensure that we don't write the default calendar used for the \"Unassigned\" resource\n //\n if (record.getParent() == null || record.getResource() != null)\n {\n m_buffer.setLength(0);\n\n if (record.getParent() == null)\n {\n m_buffer.append(MPXConstants.BASE_CALENDAR_RECORD_NUMBER);\n m_buffer.append(m_delimiter);\n if (record.getName() != null)\n {\n m_buffer.append(record.getName());\n }\n }\n else\n {\n m_buffer.append(MPXConstants.RESOURCE_CALENDAR_RECORD_NUMBER);\n m_buffer.append(m_delimiter);\n m_buffer.append(record.getParent().getName());\n }\n\n for (DayType day : record.getDays())\n {\n if (day == null)\n {\n day = DayType.DEFAULT;\n }\n m_buffer.append(m_delimiter);\n m_buffer.append(day.getValue());\n }\n\n m_buffer.append(MPXConstants.EOL);\n m_writer.write(m_buffer.toString());\n\n ProjectCalendarHours[] hours = record.getHours();\n for (int loop = 0; loop < hours.length; loop++)\n {\n if (hours[loop] != null)\n {\n writeCalendarHours(record, hours[loop]);\n }\n }\n\n if (!record.getCalendarExceptions().isEmpty())\n {\n //\n // A quirk of MS Project is that these exceptions must be\n // in date order in the file, otherwise they are ignored.\n // The getCalendarExceptions method now guarantees that\n // the exceptions list is sorted when retrieved.\n //\n for (ProjectCalendarException ex : record.getCalendarExceptions())\n {\n writeCalendarException(record, ex);\n }\n }\n\n m_eventManager.fireCalendarWrittenEvent(record);\n }\n }",
"public static base_response update(nitro_service client, vridparam resource) throws Exception {\n\t\tvridparam updateresource = new vridparam();\n\t\tupdateresource.sendtomaster = resource.sendtomaster;\n\t\treturn updateresource.update_resource(client);\n\t}",
"private Optional<String> getXsrfFromHtmlBody(HttpResponse loginResponse) throws IOException {\n Optional<Cookie> gerritAccountCookie = findGerritAccountCookie();\n if (gerritAccountCookie.isPresent()) {\n Matcher matcher = GERRIT_AUTH_PATTERN.matcher(EntityUtils.toString(loginResponse.getEntity(), Consts.UTF_8));\n if (matcher.find()) {\n return Optional.of(matcher.group(1));\n }\n }\n return Optional.absent();\n }"
] |
Creates the graphic element to be shown when the datasource is empty | [
"protected void setWhenNoDataBand() {\n log.debug(\"setting up WHEN NO DATA band\");\n String whenNoDataText = getReport().getWhenNoDataText();\n Style style = getReport().getWhenNoDataStyle();\n if (whenNoDataText == null || \"\".equals(whenNoDataText))\n return;\n JRDesignBand band = new JRDesignBand();\n getDesign().setNoData(band);\n\n JRDesignTextField text = new JRDesignTextField();\n JRDesignExpression expression = ExpressionUtils.createStringExpression(\"\\\"\" + whenNoDataText + \"\\\"\");\n text.setExpression(expression);\n\n if (style == null) {\n style = getReport().getOptions().getDefaultDetailStyle();\n }\n\n if (getReport().isWhenNoDataShowTitle()) {\n LayoutUtils.copyBandElements(band, getDesign().getTitle());\n LayoutUtils.copyBandElements(band, getDesign().getPageHeader());\n }\n if (getReport().isWhenNoDataShowColumnHeader())\n LayoutUtils.copyBandElements(band, getDesign().getColumnHeader());\n\n int offset = LayoutUtils.findVerticalOffset(band);\n text.setY(offset);\n applyStyleToElement(style, text);\n text.setWidth(getReport().getOptions().getPrintableWidth());\n text.setHeight(50);\n band.addElement(text);\n log.debug(\"OK setting up WHEN NO DATA band\");\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 PartitionInfo partitionInfo(String partitionKey) {\n if (partitionKey == null) {\n throw new UnsupportedOperationException(\"Cannot get partition information for null partition key.\");\n }\n URI uri = new DatabaseURIHelper(db.getDBUri()).partition(partitionKey).build();\n return client.couchDbClient.get(uri, PartitionInfo.class);\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 }",
"protected void initValid(EnhancedAnnotation<T> annotatedAnnotation) {\n this.valid = false;\n for (Class<? extends Annotation> annotationType : getMetaAnnotationTypes()) {\n if (annotatedAnnotation.isAnnotationPresent(annotationType)) {\n this.valid = true;\n }\n }\n }",
"protected int getCenterChild(CacheDataSet cache) {\n if (cache.count() == 0)\n return -1;\n\n int id = cache.getId(0);\n switch (getGravityInternal()) {\n case TOP:\n case LEFT:\n case FRONT:\n case FILL:\n break;\n case BOTTOM:\n case RIGHT:\n case BACK:\n id = cache.getId(cache.count() - 1);\n break;\n case CENTER:\n int i = cache.count() / 2;\n while (i < cache.count() && i >= 0) {\n id = cache.getId(i);\n if (cache.getStartDataOffset(id) <= 0) {\n if (cache.getEndDataOffset(id) >= 0) {\n break;\n } else {\n i++;\n }\n } else {\n i--;\n }\n }\n break;\n default:\n break;\n }\n\n Log.d(LAYOUT, TAG, \"getCenterChild = %d \", id);\n return id;\n }",
"public static vpnglobal_auditnslogpolicy_binding[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tvpnglobal_auditnslogpolicy_binding obj = new vpnglobal_auditnslogpolicy_binding();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tvpnglobal_auditnslogpolicy_binding[] response = (vpnglobal_auditnslogpolicy_binding[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}",
"public <T extends OutputStream> T write(T os) throws IOException {\n close();\n\n if (!(this.os instanceof ByteArrayOutputStream))\n throw new IllegalStateException(\"Cannot write to another target if setOutputStream has been called\");\n final byte[] content = ((ByteArrayOutputStream) this.os).toByteArray();\n\n if (packer != null)\n packer.pack(new JarInputStream(new ByteArrayInputStream(content)), os);\n else\n os.write(content);\n\n os.close();\n return os;\n }",
"public static <T> T createObject(final Class<T> clazz, final Object[] args, final Map<String,Object> vars) \n throws NoSuchConstructorException, AmbiguousConstructorException, ReflectiveOperationException {\n return invokeSetters(findConstructor(clazz, args).newInstance(args), vars);\n }",
"public Number getCostVariance()\n {\n Number variance = (Number) getCachedValue(TaskField.COST_VARIANCE);\n if (variance == null)\n {\n Number cost = getCost();\n Number baselineCost = getBaselineCost();\n if (cost != null && baselineCost != null)\n {\n variance = NumberHelper.getDouble(cost.doubleValue() - baselineCost.doubleValue());\n set(TaskField.COST_VARIANCE, variance);\n }\n }\n return (variance);\n }"
] |
Return key Values of an Identity
@param cld
@param oid
@param convertToSql
@return Object[]
@throws PersistenceBrokerException | [
"public ValueContainer[] getKeyValues(ClassDescriptor cld, Identity oid, boolean convertToSql) throws PersistenceBrokerException\r\n {\r\n FieldDescriptor[] pkFields = cld.getPkFields();\r\n ValueContainer[] result = new ValueContainer[pkFields.length];\r\n Object[] pkValues = oid.getPrimaryKeyValues();\r\n\r\n try\r\n {\r\n for(int i = 0; i < result.length; i++)\r\n {\r\n FieldDescriptor fd = pkFields[i];\r\n Object cv = pkValues[i];\r\n if(convertToSql)\r\n {\r\n // BRJ : apply type and value mapping\r\n cv = fd.getFieldConversion().javaToSql(cv);\r\n }\r\n result[i] = new ValueContainer(cv, fd.getJdbcType());\r\n }\r\n }\r\n catch(Exception e)\r\n {\r\n throw new PersistenceBrokerException(\"Can't generate primary key values for given Identity \" + oid, e);\r\n }\r\n return result;\r\n }"
] | [
"public static final CurrencySymbolPosition parseCurrencySymbolPosition(String value)\n {\n CurrencySymbolPosition result = CurrencySymbolPosition.BEFORE;\n\n switch (NumberHelper.getInt(value))\n {\n case 0:\n {\n result = CurrencySymbolPosition.BEFORE;\n break;\n }\n\n case 1:\n {\n result = CurrencySymbolPosition.AFTER;\n break;\n }\n\n case 2:\n {\n result = CurrencySymbolPosition.BEFORE_WITH_SPACE;\n break;\n }\n\n case 3:\n {\n result = CurrencySymbolPosition.AFTER_WITH_SPACE;\n break;\n }\n }\n\n return (result);\n }",
"private URL[] getClasspath(JobInstance ji, JobRunnerCallback cb) throws JqmPayloadException\n {\n switch (ji.getJD().getPathType())\n {\n case MAVEN:\n return mavenResolver.resolve(ji);\n case MEMORY:\n return new URL[0];\n case FS:\n default:\n return fsResolver.getLibraries(ji.getNode(), ji.getJD());\n }\n }",
"private void processDependencies() throws SQLException\n {\n List<Row> rows = getRows(\"select * from zdependency where zproject=?\", m_projectID);\n for (Row row : rows)\n {\n Task nextTask = m_project.getTaskByUniqueID(row.getInteger(\"ZNEXTACTIVITY_\"));\n Task prevTask = m_project.getTaskByUniqueID(row.getInteger(\"ZPREVIOUSACTIVITY_\"));\n Duration lag = row.getDuration(\"ZLAG_\");\n RelationType type = row.getRelationType(\"ZTYPE\");\n Relation relation = nextTask.addPredecessor(prevTask, type, lag);\n relation.setUniqueID(row.getInteger(\"Z_PK\"));\n }\n }",
"public static void directoryCheck(String dir) throws IOException {\n\t\tfinal File file = new File(dir);\n\n\t\tif (!file.exists()) {\n\t\t\tFileUtils.forceMkdir(file);\n\t\t}\n\t}",
"public ConfigBuilder withMasterName(final String masterName) {\n if (masterName == null || \"\".equals(masterName)) {\n throw new IllegalArgumentException(\"masterName is null or empty: \" + masterName);\n }\n this.masterName = masterName;\n return this;\n }",
"static GVRPickedObject makeHitMesh(long colliderPointer, float distance, float hitx, float hity, float hitz,\n int faceIndex, float barycentricx, float barycentricy, float barycentricz,\n float texu, float texv, float normalx, float normaly, float normalz)\n {\n GVRCollider collider = GVRCollider.lookup(colliderPointer);\n if (collider == null)\n {\n Log.d(TAG, \"makeHit: cannot find collider for %x\", colliderPointer);\n return null;\n }\n return new GVRPicker.GVRPickedObject(collider, new float[] { hitx, hity, hitz }, distance, faceIndex,\n new float[] {barycentricx, barycentricy, barycentricz},\n new float[]{ texu, texv },\n new float[]{normalx, normaly, normalz});\n }",
"public InputStream call(String methodName, MessageLite request) throws DatastoreException {\n logger.fine(\"remote datastore call \" + methodName);\n\n long startTime = System.currentTimeMillis();\n try {\n HttpResponse httpResponse;\n try {\n rpcCount.incrementAndGet();\n ProtoHttpContent payload = new ProtoHttpContent(request);\n HttpRequest httpRequest = client.buildPostRequest(resolveURL(methodName), payload);\n httpRequest.getHeaders().put(API_FORMAT_VERSION_HEADER, API_FORMAT_VERSION);\n // Don't throw an HTTPResponseException on error. It converts the response to a String and\n // throws away the original, whereas we need the raw bytes to parse it as a proto.\n httpRequest.setThrowExceptionOnExecuteError(false);\n // Datastore requests typically time out after 60s; set the read timeout to slightly longer\n // than that by default (can be overridden via the HttpRequestInitializer).\n httpRequest.setReadTimeout(65 * 1000);\n if (initializer != null) {\n initializer.initialize(httpRequest);\n }\n httpResponse = httpRequest.execute();\n if (!httpResponse.isSuccessStatusCode()) {\n try (InputStream content = GzipFixingInputStream.maybeWrap(httpResponse.getContent())) {\n throw makeException(url, methodName, content,\n httpResponse.getContentType(), httpResponse.getContentCharset(), null,\n httpResponse.getStatusCode());\n }\n }\n return GzipFixingInputStream.maybeWrap(httpResponse.getContent());\n } catch (SocketTimeoutException e) {\n throw makeException(url, methodName, Code.DEADLINE_EXCEEDED, \"Deadline exceeded\", e);\n } catch (IOException e) {\n throw makeException(url, methodName, Code.UNAVAILABLE, \"I/O error\", e);\n }\n } finally {\n long elapsedTime = System.currentTimeMillis() - startTime;\n logger.fine(\"remote datastore call \" + methodName + \" took \" + elapsedTime + \" ms\");\n }\n }",
"protected void initValid(EnhancedAnnotation<T> annotatedAnnotation) {\n this.valid = false;\n for (Class<? extends Annotation> annotationType : getMetaAnnotationTypes()) {\n if (annotatedAnnotation.isAnnotationPresent(annotationType)) {\n this.valid = true;\n }\n }\n }",
"@Override\r\n public V put(K key, V value) {\r\n if (fast) {\r\n synchronized (this) {\r\n Map<K, V> temp = cloneMap(map);\r\n V result = temp.put(key, value);\r\n map = temp;\r\n return (result);\r\n }\r\n } else {\r\n synchronized (map) {\r\n return (map.put(key, value));\r\n }\r\n }\r\n }"
] |
Utility function that copies a string array and add another string to
first
@param arr Original array of strings
@param add
@return Copied array of strings | [
"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 static <X> ServiceTypeLoader<X> load(Class<X> serviceType) {\n return load(serviceType, Thread.currentThread().getContextClassLoader());\n }",
"public static <T extends JsonRtn> T parseJsonRtn(String jsonRtn, Class<T> jsonRtnClazz) {\n T rtn = JSONObject.parseObject(jsonRtn, jsonRtnClazz);\n appendErrorHumanMsg(rtn);\n return rtn;\n }",
"public static void resize(GVRMesh mesh, float size) {\n float dim[] = getBoundingSize(mesh);\n float maxsize = 0.0f;\n\n if (dim[0] > maxsize) maxsize = dim[0];\n if (dim[1] > maxsize) maxsize = dim[1];\n if (dim[2] > maxsize) maxsize = dim[2];\n\n scale(mesh, size / maxsize);\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 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 }",
"@Override\n public final Boolean optBool(final String key) {\n if (this.obj.optString(key, null) == null) {\n return null;\n } else {\n return this.obj.optBoolean(key);\n }\n }",
"public static boolean setCustomResponseForDefaultProfile(String pathName, String customData) {\n try {\n return setCustomForDefaultProfile(pathName, true, customData);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }",
"public static DMatrixRMaj identity(int numRows , int numCols )\n {\n DMatrixRMaj ret = new DMatrixRMaj(numRows,numCols);\n\n int small = numRows < numCols ? numRows : numCols;\n\n for( int i = 0; i < small; i++ ) {\n ret.set(i,i,1.0);\n }\n\n return ret;\n }",
"private long getTotalTime(ProjectCalendarDateRanges exception, Date date, boolean after)\n {\n long currentTime = DateHelper.getCanonicalTime(date).getTime();\n long total = 0;\n for (DateRange range : exception)\n {\n total += getTime(range.getStart(), range.getEnd(), currentTime, after);\n }\n return (total);\n }"
] |
Try to obtain the value that is cached for the given key in the given resource.
If no value is cached, the provider is used to compute it and store it afterwards.
@param resource the resource. If it is <code>null</code>, the provider will be used to compute the value.
@param key the cache key. May not be <code>null</code>.
@param provider the strategy to compute the value if necessary. May not be <code>null</code>. | [
"@Override\n\tpublic <T> T get(Object key, Resource resource, Provider<T> provider) {\n\t\tif(resource == null) {\n\t\t\treturn provider.get();\n\t\t}\n\t\tCacheAdapter adapter = getOrCreate(resource);\n\t\tT element = adapter.<T>internalGet(key);\n\t\tif (element==null) {\n\t\t\telement = provider.get();\n\t\t\tcacheMiss(adapter);\n\t\t\tadapter.set(key, element);\n\t\t} else {\n\t\t\tcacheHit(adapter);\n\t\t}\n\t\tif (element == CacheAdapter.NULL) {\n\t\t\treturn null;\n\t\t}\n\t\treturn element;\n\t}"
] | [
"public static base_responses unset(nitro_service client, bridgetable resources[], String[] args) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tbridgetable unsetresources[] = new bridgetable[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tunsetresources[i] = new bridgetable();\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}",
"protected void loadEntries(final StorageAwareResource resource, final ZipInputStream zipIn) throws IOException {\n zipIn.getNextEntry();\n BufferedInputStream _bufferedInputStream = new BufferedInputStream(zipIn);\n this.readContents(resource, _bufferedInputStream);\n zipIn.getNextEntry();\n BufferedInputStream _bufferedInputStream_1 = new BufferedInputStream(zipIn);\n this.readResourceDescription(resource, _bufferedInputStream_1);\n if (this.storeNodeModel) {\n zipIn.getNextEntry();\n BufferedInputStream _bufferedInputStream_2 = new BufferedInputStream(zipIn);\n this.readNodeModel(resource, _bufferedInputStream_2);\n }\n }",
"private static void listResourceNotes(ProjectFile file)\n {\n for (Resource resource : file.getResources())\n {\n String notes = resource.getNotes();\n\n if (notes.length() != 0)\n {\n System.out.println(\"Notes for \" + resource.getName() + \": \" + notes);\n }\n }\n\n System.out.println();\n }",
"public void addAuxHandler(Object handler, String prefix) {\n if (handler == null) {\n throw new NullPointerException();\n }\n auxHandlers.put(prefix, handler);\n allHandlers.add(handler);\n\n addDeclaredMethods(handler, prefix);\n inputConverter.addDeclaredConverters(handler);\n outputConverter.addDeclaredConverters(handler);\n\n if (handler instanceof ShellDependent) {\n ((ShellDependent)handler).cliSetShell(this);\n }\n }",
"public static <K,V> MultiValueMap<K,V> unmodifiableMultiValueMap(MultiValueMap<? extends K, ? extends V> map) {\n\t\tAssert.notNull(map, \"'map' must not be null\");\n\t\tMap<K, List<V>> result = new LinkedHashMap<K, List<V>>(map.size());\n\t\tfor (Map.Entry<? extends K, ? extends List<? extends V>> entry : map.entrySet()) {\n\t\t\tList<V> values = Collections.unmodifiableList(entry.getValue());\n\t\t\tresult.put(entry.getKey(), values);\n\t\t}\n\t\tMap<K, List<V>> unmodifiableMap = Collections.unmodifiableMap(result);\n\t\treturn toMultiValueMap(unmodifiableMap);\n\t}",
"public void createProductDelivery(final String productLogicalName, final Delivery delivery, final String user, final String password) throws GrapesCommunicationException, AuthenticationException { \n \tfinal Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getProductDelivery(productLogicalName));\n final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, delivery);\n\n client.destroy();\n if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){\n final String message = \"Failed to create a delivery\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n }",
"public void startDockerMachine(String cliPathExec, String machineName) {\n commandLineExecutor.execCommand(createDockerMachineCommand(cliPathExec), \"start\", machineName);\n this.manuallyStarted = true;\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 }",
"private Variable createVariableInferred(TokenList.Token t0, Variable variableRight) {\n Variable result;\n\n if( t0.getType() == Type.WORD ) {\n switch( variableRight.getType()) {\n case MATRIX:\n alias(new DMatrixRMaj(1,1),t0.getWord());\n break;\n\n case SCALAR:\n if( variableRight instanceof VariableInteger) {\n alias(0,t0.getWord());\n } else {\n alias(1.0,t0.getWord());\n }\n break;\n\n case INTEGER_SEQUENCE:\n alias((IntegerSequence)null,t0.getWord());\n break;\n\n default:\n throw new RuntimeException(\"Type not supported for assignment: \"+variableRight.getType());\n }\n\n result = variables.get(t0.getWord());\n } else {\n result = t0.getVariable();\n }\n return result;\n }"
] |
Serializes this RuleSet in an XML document.
@param destination The writer to which the XML document shall be written. | [
"public void writeTo(Writer destination) {\n Element eltRuleset = new Element(\"ruleset\");\n addAttribute(eltRuleset, \"name\", name);\n addChild(eltRuleset, \"description\", description);\n for (PmdRule pmdRule : rules) {\n Element eltRule = new Element(\"rule\");\n addAttribute(eltRule, \"ref\", pmdRule.getRef());\n addAttribute(eltRule, \"class\", pmdRule.getClazz());\n addAttribute(eltRule, \"message\", pmdRule.getMessage());\n addAttribute(eltRule, \"name\", pmdRule.getName());\n addAttribute(eltRule, \"language\", pmdRule.getLanguage());\n addChild(eltRule, \"priority\", String.valueOf(pmdRule.getPriority()));\n if (pmdRule.hasProperties()) {\n Element ruleProperties = processRuleProperties(pmdRule);\n if (ruleProperties.getContentSize() > 0) {\n eltRule.addContent(ruleProperties);\n }\n }\n eltRuleset.addContent(eltRule);\n }\n XMLOutputter serializer = new XMLOutputter(Format.getPrettyFormat());\n try {\n serializer.output(new Document(eltRuleset), destination);\n } catch (IOException e) {\n throw new IllegalStateException(\"An exception occurred while serializing PmdRuleSet.\", e);\n }\n }"
] | [
"public ItemRequest<Task> removeProject(String task) {\n \n String path = String.format(\"/tasks/%s/removeProject\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }",
"private void addClass(URLClassLoader loader, JarEntry jarEntry, XMLStreamWriter writer, boolean mapClassMethods) throws ClassNotFoundException, XMLStreamException, IntrospectionException\n {\n String className = jarEntry.getName().replaceAll(\"\\\\.class\", \"\").replaceAll(\"/\", \".\");\n writer.writeStartElement(\"class\");\n writer.writeAttribute(\"name\", className);\n\n Set<Method> methodSet = new HashSet<Method>();\n Class<?> aClass = loader.loadClass(className);\n\n processProperties(writer, methodSet, aClass);\n\n if (mapClassMethods && !Modifier.isInterface(aClass.getModifiers()))\n {\n processClassMethods(writer, aClass, methodSet);\n }\n writer.writeEndElement();\n }",
"private ServerDetails createInitialDeployDetailsFromOldDeployDetails(ServerDetails oldDeployerDetails) {\n RepositoryConf oldDeployRepositoryConfig = oldDeployerDetails.getDeployReleaseRepository();\n RepositoryConf oldSnapshotDeployRepositoryConfig = oldDeployerDetails.getDeploySnapshotRepository();\n RepositoryConf deployReleaseRepos = oldDeployRepositoryConfig == null ? RepositoryConf.emptyRepositoryConfig : oldDeployRepositoryConfig;\n RepositoryConf deploySnapshotRepos = oldSnapshotDeployRepositoryConfig == null ? RepositoryConf.emptyRepositoryConfig : oldSnapshotDeployRepositoryConfig;\n return new ServerDetails(oldDeployerDetails.getArtifactoryName(), oldDeployerDetails.getArtifactoryUrl(),\n deployReleaseRepos, deploySnapshotRepos, null, null, null, null);\n }",
"public static int cudnnSoftmaxForward(\n cudnnHandle handle, \n int algo, \n int mode, \n Pointer alpha, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor yDesc, \n Pointer y)\n {\n return checkResult(cudnnSoftmaxForwardNative(handle, algo, mode, alpha, xDesc, x, beta, yDesc, y));\n }",
"public static Function<String, String> createStringTemplateSource(\n I_CmsFormatterBean formatter,\n Supplier<CmsXmlContent> contentSupplier) {\n\n return key -> {\n String result = null;\n if (formatter != null) {\n result = formatter.getAttributes().get(key);\n }\n if (result == null) {\n CmsXmlContent content = contentSupplier.get();\n if (content != null) {\n result = content.getHandler().getParameter(key);\n }\n }\n return result;\n };\n }",
"public <G extends T> RendererBuilder<T> bind(Class<G> clazz, Renderer<? extends G> prototype) {\n if (clazz == null || prototype == null) {\n throw new IllegalArgumentException(\n \"The binding RecyclerView binding can't be configured using null instances\");\n }\n prototypes.add(prototype);\n binding.put(clazz, prototype.getClass());\n return this;\n }",
"private void renderAsLI(Writer writer, ProjectModel project, Iterator<Link> links, boolean wrap) throws IOException\n {\n if (!links.hasNext())\n return;\n\n if (wrap)\n writer.append(\"<ul>\");\n while (links.hasNext())\n {\n Link link = links.next();\n writer.append(\"<li>\");\n renderLink(writer, project, link);\n writer.append(\"</li>\");\n }\n if (wrap)\n writer.append(\"</ul>\");\n }",
"public static void copy(String in, Writer out) throws IOException {\n\t\tAssert.notNull(in, \"No input String specified\");\n\t\tAssert.notNull(out, \"No Writer specified\");\n\t\ttry {\n\t\t\tout.write(in);\n\t\t}\n\t\tfinally {\n\t\t\ttry {\n\t\t\t\tout.close();\n\t\t\t}\n\t\t\tcatch (IOException ex) {\n\t\t\t}\n\t\t}\n\t}",
"public Object getAttributeValue(String attributeName) {\n\t\tAttribute attribute = getAllAttributes().get(attributeName);\n\t\tif (attribute != null) {\n\t\t\treturn attribute.getValue();\n\t\t}\n\t\treturn null;\n\t}"
] |
Creates the actual path to the xml file of the module. | [
"private String createPomPath(String relativePath, String moduleName) {\n if (!moduleName.contains(\".xml\")) {\n // Inside the parent pom, the reference is to the pom.xml file\n return relativePath + \"/\" + POM_NAME;\n }\n // There is a reference to another xml file, which is not the pom.\n String dirName = relativePath.substring(0, relativePath.indexOf(\"/\"));\n return dirName + \"/\" + moduleName;\n }"
] | [
"private final boolean matchPattern(byte[][] patterns, int bufferIndex)\n {\n boolean match = false;\n for (byte[] pattern : patterns)\n {\n int index = 0;\n match = true;\n for (byte b : pattern)\n {\n if (b != m_buffer[bufferIndex + index])\n {\n match = false;\n break;\n }\n ++index;\n }\n if (match)\n {\n break;\n }\n }\n return match;\n }",
"private Serializable doWorkInIsolationTransaction(final SharedSessionContractImplementor session)\n\t\t\tthrows HibernateException {\n\t\tclass Work extends AbstractReturningWork<IntegralDataTypeHolder> {\n\t\t\tprivate final SharedSessionContractImplementor localSession = session;\n\n\t\t\t@Override\n\t\t\tpublic IntegralDataTypeHolder execute(Connection connection) throws SQLException {\n\t\t\t\ttry {\n\t\t\t\t\treturn doWorkInCurrentTransactionIfAny( localSession );\n\t\t\t\t}\n\t\t\t\tcatch ( RuntimeException sqle ) {\n\t\t\t\t\tthrow new HibernateException( \"Could not get or update next value\", sqle );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t//we want to work out of transaction\n\t\tboolean workInTransaction = false;\n\t\tWork work = new Work();\n\t\tSerializable generatedValue = session.getTransactionCoordinator().createIsolationDelegate().delegateWork( work, workInTransaction );\n\t\treturn generatedValue;\n\t}",
"private static void verifyJUnit4Present() {\n try {\n Class<?> clazz = Class.forName(\"org.junit.runner.Description\");\n if (!Serializable.class.isAssignableFrom(clazz)) {\n JvmExit.halt(SlaveMain.ERR_OLD_JUNIT);\n }\n } catch (ClassNotFoundException e) {\n JvmExit.halt(SlaveMain.ERR_NO_JUNIT);\n }\n }",
"public void credentialsMigration(T overrider, Class overriderClass) {\n try {\n deployerMigration(overrider, overriderClass);\n resolverMigration(overrider, overriderClass);\n } catch (NoSuchFieldException | IllegalAccessException | IOException e) {\n converterErrors.add(getConversionErrorMessage(overrider, e));\n }\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 }",
"private static Set<String> imageOrientationsOf(ImageMetadata metadata) {\n\n String exifIFD0DirName = new ExifIFD0Directory().getName();\n\n Tag[] tags = Arrays.stream(metadata.getDirectories())\n .filter(dir -> dir.getName().equals(exifIFD0DirName))\n .findFirst()\n .map(Directory::getTags)\n .orElseGet(() -> new Tag[0]);\n\n return Arrays.stream(tags)\n .filter(tag -> tag.getType() == 274)\n .map(Tag::getRawValue)\n .collect(Collectors.toSet());\n }",
"public static Method getGetterPropertyMethod(Class<?> type,\r\n\t\t\tString propertyName) {\r\n\t\tString sourceMethodName = \"get\"\r\n\t\t\t\t+ BeanUtils.capitalizePropertyName(propertyName);\r\n\r\n\t\tMethod sourceMethod = BeanUtils.getMethod(type, sourceMethodName);\r\n\r\n\t\tif (sourceMethod == null) {\r\n\t\t\tsourceMethodName = \"is\"\r\n\t\t\t\t\t+ BeanUtils.capitalizePropertyName(propertyName);\r\n\t\t\tsourceMethod = BeanUtils.getMethod(type, sourceMethodName);\r\n\t\t\tif (sourceMethod != null\r\n\t\t\t\t\t&& sourceMethod.getReturnType() != Boolean.TYPE) {\r\n\t\t\t\tsourceMethod = null;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn sourceMethod;\r\n\t}",
"public void cache(String key, Object obj) {\n H.Session sess = session();\n if (null != sess) {\n sess.cache(key, obj);\n } else {\n app().cache().put(key, obj);\n }\n }",
"public void cross(Vector3d v1, Vector3d v2) {\n double tmpx = v1.y * v2.z - v1.z * v2.y;\n double tmpy = v1.z * v2.x - v1.x * v2.z;\n double tmpz = v1.x * v2.y - v1.y * v2.x;\n\n x = tmpx;\n y = tmpy;\n z = tmpz;\n }"
] |
The test that checks if clipping is needed.
@param f
feature to test
@param scale
scale
@return true if clipping is needed | [
"private boolean exceedsScreenDimensions(InternalFeature f, double scale) {\n\t\tEnvelope env = f.getBounds();\n\t\treturn (env.getWidth() * scale > MAXIMUM_TILE_COORDINATE) ||\n\t\t\t\t(env.getHeight() * scale > MAXIMUM_TILE_COORDINATE);\n\t}"
] | [
"public static int colorSpline(int x, int numKnots, int[] xknots, int[] yknots) {\n\t\tint span;\n\t\tint numSpans = numKnots - 3;\n\t\tfloat k0, k1, k2, k3;\n\t\tfloat c0, c1, c2, c3;\n\t\t\n\t\tif (numSpans < 1)\n\t\t\tthrow new IllegalArgumentException(\"Too few knots in spline\");\n\t\t\n\t\tfor (span = 0; span < numSpans; span++)\n\t\t\tif (xknots[span+1] > x)\n\t\t\t\tbreak;\n\t\tif (span > numKnots-3)\n\t\t\tspan = numKnots-3;\n\t\tfloat t = (float)(x-xknots[span]) / (xknots[span+1]-xknots[span]);\n\t\tspan--;\n\t\tif (span < 0) {\n\t\t\tspan = 0;\n\t\t\tt = 0;\n\t\t}\n\n\t\tint v = 0;\n\t\tfor (int i = 0; i < 4; i++) {\n\t\t\tint shift = i * 8;\n\t\t\t\n\t\t\tk0 = (yknots[span] >> shift) & 0xff;\n\t\t\tk1 = (yknots[span+1] >> shift) & 0xff;\n\t\t\tk2 = (yknots[span+2] >> shift) & 0xff;\n\t\t\tk3 = (yknots[span+3] >> shift) & 0xff;\n\t\t\t\n\t\t\tc3 = m00*k0 + m01*k1 + m02*k2 + m03*k3;\n\t\t\tc2 = m10*k0 + m11*k1 + m12*k2 + m13*k3;\n\t\t\tc1 = m20*k0 + m21*k1 + m22*k2 + m23*k3;\n\t\t\tc0 = m30*k0 + m31*k1 + m32*k2 + m33*k3;\n\t\t\tint n = (int)(((c3*t + c2)*t + c1)*t + c0);\n\t\t\tif (n < 0)\n\t\t\t\tn = 0;\n\t\t\telse if (n > 255)\n\t\t\t\tn = 255;\n\t\t\tv |= n << shift;\n\t\t}\n\t\t\n\t\treturn v;\n\t}",
"public Object putNodeMetaData(Object key, Object value) {\n if (key == null) throw new GroovyBugError(\"Tried to set meta data with null key on \" + this + \".\");\n if (metaDataMap == null) {\n metaDataMap = new ListHashMap();\n }\n return metaDataMap.put(key, value);\n }",
"public User getLimits() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIMITS);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element userElement = response.getPayload();\r\n User user = new User();\r\n user.setId(userElement.getAttribute(\"nsid\"));\r\n NodeList photoNodes = userElement.getElementsByTagName(\"photos\");\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element plElement = (Element) photoNodes.item(i);\r\n PhotoLimits pl = new PhotoLimits();\r\n user.setPhotoLimits(pl);\r\n pl.setMaxDisplay(plElement.getAttribute(\"maxdisplaypx\"));\r\n pl.setMaxUpload(plElement.getAttribute(\"maxupload\"));\r\n }\r\n NodeList videoNodes = userElement.getElementsByTagName(\"videos\");\r\n for (int i = 0; i < videoNodes.getLength(); i++) {\r\n Element vlElement = (Element) videoNodes.item(i);\r\n VideoLimits vl = new VideoLimits();\r\n user.setPhotoLimits(vl);\r\n vl.setMaxDuration(vlElement.getAttribute(\"maxduration\"));\r\n vl.setMaxUpload(vlElement.getAttribute(\"maxupload\"));\r\n }\r\n return user;\r\n }",
"public static base_responses update(nitro_service client, nspbr6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnspbr6 updateresources[] = new nspbr6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nspbr6();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].action = resources[i].action;\n\t\t\t\tupdateresources[i].srcipv6 = resources[i].srcipv6;\n\t\t\t\tupdateresources[i].srcipop = resources[i].srcipop;\n\t\t\t\tupdateresources[i].srcipv6val = resources[i].srcipv6val;\n\t\t\t\tupdateresources[i].srcport = resources[i].srcport;\n\t\t\t\tupdateresources[i].srcportop = resources[i].srcportop;\n\t\t\t\tupdateresources[i].srcportval = resources[i].srcportval;\n\t\t\t\tupdateresources[i].destipv6 = resources[i].destipv6;\n\t\t\t\tupdateresources[i].destipop = resources[i].destipop;\n\t\t\t\tupdateresources[i].destipv6val = resources[i].destipv6val;\n\t\t\t\tupdateresources[i].destport = resources[i].destport;\n\t\t\t\tupdateresources[i].destportop = resources[i].destportop;\n\t\t\t\tupdateresources[i].destportval = resources[i].destportval;\n\t\t\t\tupdateresources[i].srcmac = resources[i].srcmac;\n\t\t\t\tupdateresources[i].protocol = resources[i].protocol;\n\t\t\t\tupdateresources[i].protocolnumber = resources[i].protocolnumber;\n\t\t\t\tupdateresources[i].vlan = resources[i].vlan;\n\t\t\t\tupdateresources[i].Interface = resources[i].Interface;\n\t\t\t\tupdateresources[i].priority = resources[i].priority;\n\t\t\t\tupdateresources[i].msr = resources[i].msr;\n\t\t\t\tupdateresources[i].monitor = resources[i].monitor;\n\t\t\t\tupdateresources[i].nexthop = resources[i].nexthop;\n\t\t\t\tupdateresources[i].nexthopval = resources[i].nexthopval;\n\t\t\t\tupdateresources[i].nexthopvlan = resources[i].nexthopvlan;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"private void removeXmlBundleFile() throws CmsException {\n\n lockLocalization(null);\n m_cms.deleteResource(m_resource, CmsResource.DELETE_PRESERVE_SIBLINGS);\n m_resource = null;\n\n }",
"public void fire(TestCaseEvent event) {\n TestCaseResult testCase = testCaseStorage.get();\n event.process(testCase);\n\n notifier.fire(event);\n }",
"private ClassDescriptor discoverDescriptor(Class clazz)\r\n {\r\n ClassDescriptor result = (ClassDescriptor) descriptorTable.get(clazz.getName());\r\n\r\n if (result == null)\r\n {\r\n Class superClass = clazz.getSuperclass();\r\n // only recurse if the superClass is not java.lang.Object\r\n if (superClass != null)\r\n {\r\n result = discoverDescriptor(superClass);\r\n }\r\n if (result == null)\r\n {\r\n // we're also checking the interfaces as there could be normal\r\n // mappings for them in the repository (using factory-class,\r\n // factory-method, and the property field accessor)\r\n Class[] interfaces = clazz.getInterfaces();\r\n\r\n if ((interfaces != null) && (interfaces.length > 0))\r\n {\r\n for (int idx = 0; (idx < interfaces.length) && (result == null); idx++)\r\n {\r\n result = discoverDescriptor(interfaces[idx]);\r\n }\r\n }\r\n }\r\n\r\n if (result != null)\r\n {\r\n /**\r\n * Kuali Foundation modification -- 6/19/2009\r\n */\r\n \tsynchronized (descriptorTable) {\r\n /**\r\n * End of Kuali Foundation modification\r\n */\r\n \t\tdescriptorTable.put(clazz.getName(), result);\r\n /**\r\n * Kuali Foundation modification -- 6/19/2009\r\n */\r\n \t}\r\n /**\r\n * End of Kuali Foundation modification\r\n */\r\n }\r\n }\r\n return result;\r\n }",
"public static Trajectory getTrajectoryByID(List<? extends Trajectory> t, int id){\n\t\tTrajectory track = null;\n\t\tfor(int i = 0; i < t.size() ; i++){\n\t\t\tif(t.get(i).getID()==id){\n\t\t\t\ttrack = t.get(i);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn track;\n\t}",
"@JsonIgnore\n public void setUnknownFields(final Map<String,Object> unknownFields) {\n this.unknownFields.clear();\n this.unknownFields.putAll(unknownFields);\n }"
] |
For a given set of calendar data, this method sets the working
day status for each day, and if present, sets the hours for that
day.
NOTE: MPP14 defines the concept of working weeks. MPXJ does not
currently support this, and thus we only read the working hours
for the default working week.
@param data calendar data block
@param defaultCalendar calendar to use for default values
@param cal calendar instance
@param isBaseCalendar true if this is a base calendar | [
"private void processCalendarHours(byte[] data, ProjectCalendar defaultCalendar, ProjectCalendar cal, boolean isBaseCalendar)\n {\n // Dump out the calendar related data and fields.\n //MPPUtility.dataDump(data, true, false, false, false, true, false, true);\n\n int offset;\n ProjectCalendarHours hours;\n int periodIndex;\n int index;\n int defaultFlag;\n int periodCount;\n Date start;\n long duration;\n Day day;\n List<DateRange> dateRanges = new ArrayList<DateRange>(5);\n\n for (index = 0; index < 7; index++)\n {\n offset = getCalendarHoursOffset() + (60 * index);\n defaultFlag = data == null ? 1 : MPPUtility.getShort(data, offset);\n day = Day.getInstance(index + 1);\n\n if (defaultFlag == 1)\n {\n if (isBaseCalendar)\n {\n if (defaultCalendar == null)\n {\n cal.setWorkingDay(day, DEFAULT_WORKING_WEEK[index]);\n if (cal.isWorkingDay(day))\n {\n hours = cal.addCalendarHours(Day.getInstance(index + 1));\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING);\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON);\n }\n }\n else\n {\n boolean workingDay = defaultCalendar.isWorkingDay(day);\n cal.setWorkingDay(day, workingDay);\n if (workingDay)\n {\n hours = cal.addCalendarHours(Day.getInstance(index + 1));\n for (DateRange range : defaultCalendar.getHours(day))\n {\n hours.addRange(range);\n }\n }\n }\n }\n else\n {\n cal.setWorkingDay(day, DayType.DEFAULT);\n }\n }\n else\n {\n dateRanges.clear();\n\n periodIndex = 0;\n periodCount = MPPUtility.getShort(data, offset + 2);\n while (periodIndex < periodCount)\n {\n int startOffset = offset + 8 + (periodIndex * 2);\n start = MPPUtility.getTime(data, startOffset);\n int durationOffset = offset + 20 + (periodIndex * 4);\n duration = MPPUtility.getDuration(data, durationOffset);\n Date end = new Date(start.getTime() + duration);\n dateRanges.add(new DateRange(start, end));\n ++periodIndex;\n }\n\n if (dateRanges.isEmpty())\n {\n cal.setWorkingDay(day, false);\n }\n else\n {\n cal.setWorkingDay(day, true);\n hours = cal.addCalendarHours(Day.getInstance(index + 1));\n\n for (DateRange range : dateRanges)\n {\n hours.addRange(range);\n }\n }\n }\n }\n }"
] | [
"@Override\n public Collection<EnhancedAnnotatedConstructor<T>> getEnhancedConstructors(Class<? extends Annotation> annotationType) {\n Set<EnhancedAnnotatedConstructor<T>> ret = new HashSet<EnhancedAnnotatedConstructor<T>>();\n for (EnhancedAnnotatedConstructor<T> constructor : constructors) {\n if (constructor.isAnnotationPresent(annotationType)) {\n ret.add(constructor);\n }\n }\n return ret;\n }",
"private void addGreeting(String guestbookName, String user, String message)\n throws DatastoreException {\n Entity.Builder greeting = Entity.newBuilder();\n greeting.setKey(makeKey(GUESTBOOK_KIND, guestbookName, GREETING_KIND));\n greeting.getMutableProperties().put(USER_PROPERTY, makeValue(user).build());\n greeting.getMutableProperties().put(MESSAGE_PROPERTY, makeValue(message).build());\n greeting.getMutableProperties().put(DATE_PROPERTY, makeValue(new Date()).build());\n Key greetingKey = insert(greeting.build());\n System.out.println(\"greeting key is: \" + greetingKey);\n }",
"private int getInt(List<byte[]> blocks)\n {\n int result;\n if (blocks.isEmpty() == false)\n {\n byte[] data = blocks.remove(0);\n result = MPPUtility.getInt(data, 0);\n }\n else\n {\n result = 0;\n }\n return (result);\n }",
"private void populateRelation(TaskField field, Task sourceTask, String relationship) throws MPXJException\n {\n int index = 0;\n int length = relationship.length();\n\n //\n // Extract the identifier\n //\n while ((index < length) && (Character.isDigit(relationship.charAt(index)) == true))\n {\n ++index;\n }\n\n Integer taskID;\n try\n {\n taskID = Integer.valueOf(relationship.substring(0, index));\n }\n\n catch (NumberFormatException ex)\n {\n throw new MPXJException(MPXJException.INVALID_FORMAT + \" '\" + relationship + \"'\");\n }\n\n //\n // Now find the task, so we can extract the unique ID\n //\n Task targetTask;\n if (field == TaskField.PREDECESSORS)\n {\n targetTask = m_projectFile.getTaskByID(taskID);\n }\n else\n {\n targetTask = m_projectFile.getTaskByUniqueID(taskID);\n }\n\n //\n // If we haven't reached the end, we next expect to find\n // SF, SS, FS, FF\n //\n RelationType type = null;\n Duration lag = null;\n\n if (index == length)\n {\n type = RelationType.FINISH_START;\n lag = Duration.getInstance(0, TimeUnit.DAYS);\n }\n else\n {\n if ((index + 1) == length)\n {\n throw new MPXJException(MPXJException.INVALID_FORMAT + \" '\" + relationship + \"'\");\n }\n\n type = RelationTypeUtility.getInstance(m_locale, relationship.substring(index, index + 2));\n\n index += 2;\n\n if (index == length)\n {\n lag = Duration.getInstance(0, TimeUnit.DAYS);\n }\n else\n {\n if (relationship.charAt(index) == '+')\n {\n ++index;\n }\n\n lag = DurationUtility.getInstance(relationship.substring(index), m_formats.getDurationDecimalFormat(), m_locale);\n }\n }\n\n if (type == null)\n {\n throw new MPXJException(MPXJException.INVALID_FORMAT + \" '\" + relationship + \"'\");\n }\n\n // We have seen at least one example MPX file where an invalid task ID\n // is present. We'll ignore this as the schedule is otherwise valid.\n if (targetTask != null)\n {\n Relation relation = sourceTask.addPredecessor(targetTask, type, lag);\n m_eventManager.fireRelationReadEvent(relation);\n }\n }",
"public 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 }",
"protected boolean checkvalue(String colorvalue) {\n\n boolean valid = validateColorValue(colorvalue);\n if (valid) {\n if (colorvalue.length() == 4) {\n char[] chr = colorvalue.toCharArray();\n for (int i = 1; i < 4; i++) {\n String foo = String.valueOf(chr[i]);\n colorvalue = colorvalue.replaceFirst(foo, foo + foo);\n }\n }\n m_textboxColorValue.setValue(colorvalue, true);\n m_colorField.getElement().getStyle().setBackgroundColor(colorvalue);\n m_colorValue = colorvalue;\n }\n return valid;\n }",
"private void batchStatusLog(int batchCount,\n int numBatches,\n int partitionStoreCount,\n int numPartitionStores,\n long totalTimeMs) {\n // Calculate the estimated end time and pretty print stats\n double rate = 1;\n long estimatedTimeMs = 0;\n if(numPartitionStores > 0) {\n rate = partitionStoreCount / numPartitionStores;\n estimatedTimeMs = (long) (totalTimeMs / rate) - totalTimeMs;\n }\n\n StringBuilder sb = new StringBuilder();\n sb.append(\"Batch Complete!\")\n .append(Utils.NEWLINE)\n .append(\"\\tbatches moved: \")\n .append(batchCount)\n .append(\" out of \")\n .append(numBatches)\n .append(Utils.NEWLINE)\n .append(\"\\tPartition stores moved: \")\n .append(partitionStoreCount)\n .append(\" out of \")\n .append(numPartitionStores)\n .append(Utils.NEWLINE)\n .append(\"\\tPercent done: \")\n .append(decimalFormatter.format(rate * 100.0))\n .append(Utils.NEWLINE)\n .append(\"\\tEstimated time left: \")\n .append(estimatedTimeMs)\n .append(\" ms (\")\n .append(TimeUnit.MILLISECONDS.toHours(estimatedTimeMs))\n .append(\" hours)\");\n RebalanceUtils.printBatchLog(batchCount, logger, sb.toString());\n }",
"public static boolean changeHost(String hostName,\n boolean enable,\n boolean disable,\n boolean remove,\n boolean isEnabled,\n boolean exists) throws Exception {\n\n // Open the file that is the first\n // command line parameter\n File hostsFile = new File(\"/etc/hosts\");\n FileInputStream fstream = new FileInputStream(\"/etc/hosts\");\n\n File outFile = null;\n BufferedWriter bw = null;\n // only do file output for destructive operations\n if (!exists && !isEnabled) {\n outFile = File.createTempFile(\"HostsEdit\", \".tmp\");\n bw = new BufferedWriter(new FileWriter(outFile));\n System.out.println(\"File name: \" + outFile.getPath());\n }\n\n // Get the object of DataInputStream\n DataInputStream in = new DataInputStream(fstream);\n BufferedReader br = new BufferedReader(new InputStreamReader(in));\n String strLine;\n boolean foundHost = false;\n boolean hostEnabled = false;\n\n\t\t/*\n * Group 1 - possible commented out host entry\n\t\t * Group 2 - destination address\n\t\t * Group 3 - host name\n\t\t * Group 4 - everything else\n\t\t */\n Pattern pattern = Pattern.compile(\"\\\\s*(#?)\\\\s*([^\\\\s]+)\\\\s*([^\\\\s]+)(.*)\");\n while ((strLine = br.readLine()) != null) {\n\n Matcher matcher = pattern.matcher(strLine);\n\n // if there is a match to the pattern and the host name is the same as the one we want to set\n if (matcher.find() &&\n matcher.group(3).toLowerCase().compareTo(hostName.toLowerCase()) == 0) {\n foundHost = true;\n if (remove) {\n // skip this line altogether\n continue;\n } else if (enable) {\n // we will disregard group 2 and just set it to 127.0.0.1\n if (!exists && !isEnabled)\n bw.write(\"127.0.0.1 \" + matcher.group(3) + matcher.group(4));\n } else if (disable) {\n if (!exists && !isEnabled)\n bw.write(\"# \" + matcher.group(2) + \" \" + matcher.group(3) + matcher.group(4));\n } else if (isEnabled && matcher.group(1).compareTo(\"\") == 0) {\n // host exists and there is no # before it\n hostEnabled = true;\n }\n } else {\n // just write the line back out\n if (!exists && !isEnabled)\n bw.write(strLine);\n }\n\n if (!exists && !isEnabled)\n bw.write('\\n');\n }\n\n // if we didn't find the host in the file but need to enable it\n if (!foundHost && enable) {\n // write a new host entry\n if (!exists && !isEnabled)\n bw.write(\"127.0.0.1 \" + hostName + '\\n');\n }\n // Close the input stream\n in.close();\n\n if (!exists && !isEnabled) {\n bw.close();\n outFile.renameTo(hostsFile);\n }\n\n // return false if the host wasn't found\n if (exists && !foundHost)\n return false;\n\n // return false if the host wasn't enabled\n if (isEnabled && !hostEnabled)\n return false;\n\n return true;\n }",
"private void merge(Integer cid1, Integer cid2) {\n Collection<String> klass1 = classix.get(cid1);\n Collection<String> klass2 = classix.get(cid2);\n\n // if klass1 is the smaller, swap the two\n if (klass1.size() < klass2.size()) {\n Collection<String> tmp = klass2;\n klass2 = klass1;\n klass1 = tmp;\n\n Integer itmp = cid2;\n cid2 = cid1;\n cid1 = itmp;\n }\n\n // now perform the actual merge\n for (String id : klass2) {\n klass1.add(id);\n recordix.put(id, cid1);\n }\n\n // delete the smaller class, and we're done\n classix.remove(cid2);\n }"
] |
set the property destination type for given property
@param propertyName
@param destinationType | [
"public void setPropertyDestinationType(Class<?> clazz, String propertyName,\r\n\t\t\tTypeReference<?> destinationType) {\r\n\t\tpropertiesDestinationTypes.put(new ClassProperty(clazz, propertyName), destinationType);\r\n\t}"
] | [
"private RelationType getRelationType(Integer gpType)\n {\n RelationType result = null;\n if (gpType != null)\n {\n int index = NumberHelper.getInt(gpType);\n if (index > 0 && index < RELATION.length)\n {\n result = RELATION[index];\n }\n }\n\n if (result == null)\n {\n result = RelationType.FINISH_START;\n }\n\n return result;\n }",
"private static String buildErrorMsg(List<String> dependencies, String message) {\n final StringBuilder buffer = new StringBuilder();\n boolean isFirstElement = true;\n for (String dependency : dependencies) {\n if (!isFirstElement) {\n buffer.append(\", \");\n }\n // check if it is an instance of Artifact - add the gavc else append the object\n buffer.append(dependency);\n\n isFirstElement = false;\n }\n return String.format(message, buffer.toString());\n }",
"static JndiContext createJndiContext() throws NamingException\n {\n try\n {\n if (!NamingManager.hasInitialContextFactoryBuilder())\n {\n JndiContext ctx = new JndiContext();\n NamingManager.setInitialContextFactoryBuilder(ctx);\n return ctx;\n }\n else\n {\n return (JndiContext) NamingManager.getInitialContext(null);\n }\n }\n catch (Exception e)\n {\n jqmlogger.error(\"Could not create JNDI context: \" + e.getMessage());\n NamingException ex = new NamingException(\"Could not initialize JNDI Context\");\n ex.setRootCause(e);\n throw ex;\n }\n }",
"public static Date getTimestampFromLong(long timestamp)\n {\n TimeZone tz = TimeZone.getDefault();\n Date result = new Date(timestamp - tz.getRawOffset());\n\n if (tz.inDaylightTime(result) == true)\n {\n int savings;\n\n if (HAS_DST_SAVINGS == true)\n {\n savings = tz.getDSTSavings();\n }\n else\n {\n savings = DEFAULT_DST_SAVINGS;\n }\n\n result = new Date(result.getTime() - savings);\n }\n return (result);\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 }",
"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 }",
"public void deployApplication(String applicationName, String... classpathLocations) throws IOException {\n\n final List<URL> classpathElements = Arrays.stream(classpathLocations)\n .map(classpath -> Thread.currentThread().getContextClassLoader().getResource(classpath))\n .collect(Collectors.toList());\n\n deployApplication(applicationName, classpathElements.toArray(new URL[classpathElements.size()]));\n }",
"public static auditmessages[] get(nitro_service service) throws Exception{\n\t\tauditmessages obj = new auditmessages();\n\t\tauditmessages[] response = (auditmessages[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"private Map<UUID, FieldType> populateCustomFieldMap()\n {\n byte[] data = m_taskProps.getByteArray(Props.CUSTOM_FIELDS);\n int length = MPPUtility.getInt(data, 0);\n int index = length + 36;\n\n // 4 byte record count\n int recordCount = MPPUtility.getInt(data, index);\n index += 4;\n\n // 8 bytes per record\n index += (8 * recordCount);\n \n Map<UUID, FieldType> map = new HashMap<UUID, FieldType>();\n while (index < data.length)\n {\n int blockLength = MPPUtility.getInt(data, index); \n if (blockLength <= 0 || index + blockLength > data.length)\n {\n break;\n }\n \n int fieldID = MPPUtility.getInt(data, index + 4);\n FieldType field = FieldTypeHelper.getInstance(fieldID);\n UUID guid = MPPUtility.getGUID(data, index + 160);\n map.put(guid, field);\n index += blockLength;\n }\n return map;\n }"
] |
Scroll to the specific position
@param position
@return the new current item after the scrolling processed. | [
"public int scrollToItem(int position) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"scrollToItem position = %d\", position);\n scrollToPosition(position);\n return mCurrentItemIndex;\n }"
] | [
"@Override\n public void close() {\n // unregister MBeans\n if(stats != null) {\n try {\n if(this.jmxEnabled)\n JmxUtils.unregisterMbean(getAggregateMetricName());\n } catch(Exception e) {}\n stats.close();\n }\n factory.close();\n queuedPool.close();\n }",
"private void writeResourceBaselines(Project.Resources.Resource xmlResource, Resource mpxjResource)\n {\n Project.Resources.Resource.Baseline baseline = m_factory.createProjectResourcesResourceBaseline();\n boolean populated = false;\n\n Number cost = mpxjResource.getBaselineCost();\n if (cost != null && cost.intValue() != 0)\n {\n populated = true;\n baseline.setCost(DatatypeConverter.printCurrency(cost));\n }\n\n Duration work = mpxjResource.getBaselineWork();\n if (work != null && work.getDuration() != 0)\n {\n populated = true;\n baseline.setWork(DatatypeConverter.printDuration(this, work));\n }\n\n if (populated)\n {\n xmlResource.getBaseline().add(baseline);\n baseline.setNumber(BigInteger.ZERO);\n }\n\n for (int loop = 1; loop <= 10; loop++)\n {\n baseline = m_factory.createProjectResourcesResourceBaseline();\n populated = false;\n\n cost = mpxjResource.getBaselineCost(loop);\n if (cost != null && cost.intValue() != 0)\n {\n populated = true;\n baseline.setCost(DatatypeConverter.printCurrency(cost));\n }\n\n work = mpxjResource.getBaselineWork(loop);\n if (work != null && work.getDuration() != 0)\n {\n populated = true;\n baseline.setWork(DatatypeConverter.printDuration(this, work));\n }\n\n if (populated)\n {\n xmlResource.getBaseline().add(baseline);\n baseline.setNumber(BigInteger.valueOf(loop));\n }\n }\n }",
"public void setHostName(String hostName) {\n if (hostName == null || hostName.contains(\":\")) {\n return;\n }\n ODO_HOST = hostName;\n BASE_URL = \"http://\" + ODO_HOST + \":\" + API_PORT + \"/\" + API_BASE + \"/\";\n }",
"private List<ExpandableWrapper<P, C>> generateFlattenedParentChildList(List<P> parentList) {\n List<ExpandableWrapper<P, C>> flatItemList = new ArrayList<>();\n\n int parentCount = parentList.size();\n for (int i = 0; i < parentCount; i++) {\n P parent = parentList.get(i);\n generateParentWrapper(flatItemList, parent, parent.isInitiallyExpanded());\n }\n\n return flatItemList;\n }",
"public static ipv6 get(nitro_service service) throws Exception{\n\t\tipv6 obj = new ipv6();\n\t\tipv6[] response = (ipv6[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public void transformConfig() throws Exception {\n\n List<TransformEntry> entries = readTransformEntries(new File(m_xsltDir, \"transforms.xml\"));\n for (TransformEntry entry : entries) {\n transform(entry.getConfigFile(), entry.getXslt());\n }\n m_isDone = true;\n }",
"public boolean equalId(Element otherElement) {\r\n\t\tif (getElementId() == null || otherElement.getElementId() == null) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\treturn getElementId().equalsIgnoreCase(otherElement.getElementId());\r\n\t}",
"public void setFromJSON(Context context, JSONObject properties) {\n String backgroundResStr = optString(properties, Properties.background);\n if (backgroundResStr != null && !backgroundResStr.isEmpty()) {\n final int backgroundResId = getId(context, backgroundResStr, \"drawable\");\n setBackGround(context.getResources().getDrawable(backgroundResId, null));\n }\n\n setBackgroundColor(getJSONColor(properties, Properties.background_color, getBackgroundColor()));\n setGravity(optInt(properties, TextContainer.Properties.gravity, getGravity()));\n setRefreshFrequency(optEnum(properties, Properties.refresh_freq, getRefreshFrequency()));\n setTextColor(getJSONColor(properties, Properties.text_color, getTextColor()));\n setText(optString(properties, Properties.text, (String) getText()));\n setTextSize(optFloat(properties, Properties.text_size, getTextSize()));\n\n final JSONObject typefaceJson = optJSONObject(properties, Properties.typeface);\n\n if (typefaceJson != null) {\n try {\n Typeface typeface = WidgetLib.getTypefaceManager().getTypeface(typefaceJson);\n setTypeface(typeface);\n } catch (Throwable e) {\n Log.e(TAG, e, \"Couldn't set typeface from properties: %s\", typefaceJson);\n }\n }\n }",
"public T withStatement(Statement statement) {\n\t\tPropertyIdValue pid = statement.getMainSnak()\n\t\t\t\t.getPropertyId();\n\t\tArrayList<Statement> pidStatements = this.statements.get(pid);\n\t\tif (pidStatements == null) {\n\t\t\tpidStatements = new ArrayList<Statement>();\n\t\t\tthis.statements.put(pid, pidStatements);\n\t\t}\n\n\t\tpidStatements.add(statement);\n\t\treturn getThis();\n\t}"
] |
This method populates the task model from data read from an MPX file.
@param record data read from an MPX file
@param isText flag indicating whether the textual or numeric data is being supplied | [
"public void update(Record record, boolean isText) throws MPXJException\n {\n int length = record.getLength();\n\n for (int i = 0; i < length; i++)\n {\n if (isText == true)\n {\n add(getTaskCode(record.getString(i)));\n }\n else\n {\n add(record.getInteger(i).intValue());\n }\n }\n }"
] | [
"public static JqmClient getClient(String name, Properties p, boolean cached)\n {\n Properties p2 = null;\n if (binder == null)\n {\n bind();\n }\n if (p == null)\n {\n p2 = props;\n }\n else\n {\n p2 = new Properties(props);\n p2.putAll(p);\n }\n return binder.getClientFactory().getClient(name, p2, cached);\n }",
"public void remove(Identity oid)\r\n {\r\n try\r\n {\r\n jcsCache.remove(oid.toString());\r\n }\r\n catch (CacheException e)\r\n {\r\n throw new RuntimeCacheException(e.getMessage());\r\n }\r\n }",
"public static void stopService() {\n DaemonStarter.currentPhase.set(LifecyclePhase.STOPPING);\n final CountDownLatch cdl = new CountDownLatch(1);\n Executors.newSingleThreadExecutor().execute(() -> {\n DaemonStarter.getLifecycleListener().stopping();\n DaemonStarter.daemon.stop();\n cdl.countDown();\n });\n\n try {\n int timeout = DaemonStarter.lifecycleListener.get().getShutdownTimeoutSeconds();\n if (!cdl.await(timeout, TimeUnit.SECONDS)) {\n DaemonStarter.rlog.error(\"Failed to stop gracefully\");\n DaemonStarter.abortSystem();\n }\n } catch (InterruptedException e) {\n DaemonStarter.rlog.error(\"Failure awaiting stop\", e);\n Thread.currentThread().interrupt();\n }\n\n }",
"public EndpointOverride getPath(int pathId, String clientUUID, String[] filters) throws Exception {\n EndpointOverride endpoint = null;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n String queryString = this.getPathSelectString();\n queryString += \" AND \" + Constants.DB_TABLE_PATH + \".\" + Constants.GENERIC_ID + \"=\" + pathId + \";\";\n statement = sqlConnection.prepareStatement(queryString);\n statement.setString(1, clientUUID);\n\n results = statement.executeQuery();\n\n if (results.next()) {\n endpoint = this.getEndpointOverrideFromResultSet(results);\n endpoint.setFilters(filters);\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return endpoint;\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 static void checkCreateUpload(CmsObject cms, CmsUgcConfiguration config, String name, long size)\n throws CmsUgcException {\n\n if (!config.getUploadParentFolder().isPresent()) {\n String message = Messages.get().container(Messages.ERR_NO_UPLOADS_ALLOWED_0).key(\n cms.getRequestContext().getLocale());\n throw new CmsUgcException(CmsUgcConstants.ErrorCode.errNoUploadAllowed, message);\n }\n\n if (config.getMaxUploadSize().isPresent()) {\n if (config.getMaxUploadSize().get().longValue() < size) {\n String message = Messages.get().container(Messages.ERR_UPLOAD_TOO_BIG_1, name).key(\n cms.getRequestContext().getLocale());\n throw new CmsUgcException(CmsUgcConstants.ErrorCode.errMaxUploadSizeExceeded, message);\n }\n }\n\n if (config.getValidExtensions().isPresent()) {\n List<String> validExtensions = config.getValidExtensions().get();\n boolean foundExtension = false;\n for (String extension : validExtensions) {\n if (name.toLowerCase().endsWith(extension.toLowerCase())) {\n foundExtension = true;\n break;\n }\n }\n if (!foundExtension) {\n String message = Messages.get().container(Messages.ERR_UPLOAD_FILE_EXTENSION_NOT_ALLOWED_1, name).key(\n cms.getRequestContext().getLocale());\n throw new CmsUgcException(CmsUgcConstants.ErrorCode.errInvalidExtension, message);\n }\n }\n }",
"public Double getProgress() {\n\n if (state.equals(ParallelTaskState.IN_PROGRESS)) {\n if (requestNum != 0) {\n return 100.0 * ((double) responsedNum / (double) requestNumActual);\n } else {\n return 0.0;\n }\n }\n\n if (state.equals(ParallelTaskState.WAITING)) {\n return 0.0;\n }\n\n // fix task if fail validation, still try to poll progress 0901\n if (state.equals(ParallelTaskState.COMPLETED_WITH_ERROR)\n || state.equals(ParallelTaskState.COMPLETED_WITHOUT_ERROR)) {\n return 100.0;\n }\n\n return 0.0;\n\n }",
"public void processField(String template, Properties attributes) throws XDocletException\r\n {\r\n String name = OjbMemberTagsHandler.getMemberName();\r\n String defaultType = getDefaultJdbcTypeForCurrentMember();\r\n String defaultConversion = getDefaultJdbcConversionForCurrentMember();\r\n FieldDescriptorDef fieldDef = _curClassDef.getField(name);\r\n String attrName;\r\n\r\n if (fieldDef == null)\r\n {\r\n fieldDef = new FieldDescriptorDef(name);\r\n _curClassDef.addField(fieldDef);\r\n }\r\n LogHelper.debug(false, OjbTagsHandler.class, \"processField\", \" Processing field \"+fieldDef.getName());\r\n\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n fieldDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n // storing additional info for later use\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_JAVA_TYPE,\r\n OjbMemberTagsHandler.getMemberType().getQualifiedName());\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_JDBC_TYPE, defaultType);\r\n if (defaultConversion != null)\r\n { \r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_CONVERSION, defaultConversion);\r\n }\r\n\r\n _curFieldDef = fieldDef;\r\n generate(template);\r\n _curFieldDef = null;\r\n }",
"private static int[] getMode2PrimaryCodewords(String postcode, int country, int service) {\r\n\r\n for (int i = 0; i < postcode.length(); i++) {\r\n if (postcode.charAt(i) < '0' || postcode.charAt(i) > '9') {\r\n postcode = postcode.substring(0, i);\r\n break;\r\n }\r\n }\r\n\r\n int postcodeNum = Integer.parseInt(postcode);\r\n\r\n int[] primary = new int[10];\r\n primary[0] = ((postcodeNum & 0x03) << 4) | 2;\r\n primary[1] = ((postcodeNum & 0xfc) >> 2);\r\n primary[2] = ((postcodeNum & 0x3f00) >> 8);\r\n primary[3] = ((postcodeNum & 0xfc000) >> 14);\r\n primary[4] = ((postcodeNum & 0x3f00000) >> 20);\r\n primary[5] = ((postcodeNum & 0x3c000000) >> 26) | ((postcode.length() & 0x3) << 4);\r\n primary[6] = ((postcode.length() & 0x3c) >> 2) | ((country & 0x3) << 4);\r\n primary[7] = (country & 0xfc) >> 2;\r\n primary[8] = ((country & 0x300) >> 8) | ((service & 0xf) << 2);\r\n primary[9] = ((service & 0x3f0) >> 4);\r\n\r\n return primary;\r\n }"
] |
Post the specified photo to a blog.
@param photo
The photo metadata
@param blogId
The blog ID
@throws FlickrException | [
"public void postPhoto(Photo photo, String blogId) throws FlickrException {\r\n postPhoto(photo, blogId, null);\r\n }"
] | [
"private double getConstraint(double x1, double x2)\n {\n double c1,c2,h;\n c1 = -x1*x1-x2*x2+1+0.1*Math.cos(16*Math.atan(x1/x2));\n c2 = (x1-0.5)*(x1-0.5)+(x2-0.5)*(x2-0.5)-0.5;\n if(c1>c2)\n h = (c1>0)?c1:0;\n else\n h = (c2>0)?c2:0;\n return h;\n }",
"public static <T> List<T> load(ClassLoader classLoader, Class<T> serviceType) {\n List<T> foundServices = new ArrayList<>();\n Iterator<T> iterator = ServiceLoader.load(serviceType, classLoader).iterator();\n\n while (checkHasNextSafely(iterator)) {\n try {\n T item = iterator.next();\n foundServices.add(item);\n LOGGER.debug(String.format(\"Found %s [%s]\", serviceType.getSimpleName(), item.toString()));\n } catch (ServiceConfigurationError e) {\n LOGGER.trace(\"Can't find services using Java SPI\", e);\n LOGGER.error(e.getMessage());\n }\n }\n return foundServices;\n }",
"private void addChildrenForGroupsNode(I_CmsOuTreeType type, String ouItem) {\n\n try {\n // Cut of type-specific prefix from ouItem with substring()\n List<CmsGroup> groups = m_app.readGroupsForOu(m_cms, ouItem.substring(1), type, false);\n for (CmsGroup group : groups) {\n Pair<String, CmsUUID> key = Pair.of(type.getId(), group.getId());\n Item groupItem = m_treeContainer.addItem(key);\n if (groupItem == null) {\n groupItem = getItem(key);\n }\n groupItem.getItemProperty(PROP_SID).setValue(group.getId());\n groupItem.getItemProperty(PROP_NAME).setValue(getIconCaptionHTML(group, CmsOuTreeType.GROUP));\n groupItem.getItemProperty(PROP_TYPE).setValue(type);\n setChildrenAllowed(key, false);\n m_treeContainer.setParent(key, ouItem);\n }\n } catch (CmsException e) {\n LOG.error(\"Can not read group\", e);\n }\n }",
"protected Query buildPrefetchQuery(Collection ids)\r\n {\r\n CollectionDescriptor cds = getCollectionDescriptor();\r\n QueryByCriteria query = buildPrefetchQuery(ids, cds.getForeignKeyFieldDescriptors(getItemClassDescriptor()));\r\n\r\n // check if collection must be ordered\r\n if (!cds.getOrderBy().isEmpty())\r\n {\r\n Iterator iter = cds.getOrderBy().iterator();\r\n while (iter.hasNext())\r\n {\r\n query.addOrderBy((FieldHelper) iter.next());\r\n }\r\n }\r\n\r\n return query;\r\n }",
"public DockerContainerObjectBuilder<T> withContainerObjectClass(Class<T> containerObjectClass) {\n if (containerObjectClass == null) {\n throw new IllegalArgumentException(\"container object class cannot be null\");\n }\n this.containerObjectClass = containerObjectClass;\n\n //First we check if this ContainerObject is defining a @CubeDockerFile in static method\n final List<Method> methodsWithCubeDockerFile =\n ReflectionUtil.getMethodsWithAnnotation(containerObjectClass, CubeDockerFile.class);\n\n if (methodsWithCubeDockerFile.size() > 1) {\n throw new IllegalArgumentException(\n String.format(\n \"More than one %s annotation found and only one was expected. Methods where annotation was found are: %s\",\n CubeDockerFile.class.getSimpleName(), methodsWithCubeDockerFile));\n }\n\n classHasMethodWithCubeDockerFile = !methodsWithCubeDockerFile.isEmpty();\n classDefinesCubeDockerFile = containerObjectClass.isAnnotationPresent(CubeDockerFile.class);\n classDefinesImage = containerObjectClass.isAnnotationPresent(Image.class);\n\n if (classHasMethodWithCubeDockerFile) {\n methodWithCubeDockerFile = methodsWithCubeDockerFile.get(0);\n boolean isMethodStatic = Modifier.isStatic(methodWithCubeDockerFile.getModifiers());\n boolean methodHasNoArguments = methodWithCubeDockerFile.getParameterCount() == 0;\n boolean methodReturnsAnArchive = Archive.class.isAssignableFrom(methodWithCubeDockerFile.getReturnType());\n if (!isMethodStatic || !methodHasNoArguments || !methodReturnsAnArchive) {\n throw new IllegalArgumentException(\n String.format(\"Method %s annotated with %s is expected to be static, no args and return %s.\",\n methodWithCubeDockerFile, CubeDockerFile.class.getSimpleName(), Archive.class.getSimpleName()));\n }\n }\n\n // User has defined @CubeDockerfile on the class and a method\n if (classHasMethodWithCubeDockerFile && classDefinesCubeDockerFile) {\n throw new IllegalArgumentException(\n String.format(\n \"More than one %s annotation found and only one was expected. Both class and method %s has the annotation.\",\n CubeDockerFile.class.getSimpleName(), methodWithCubeDockerFile));\n }\n\n // User has defined @CubeDockerfile and @Image\n if ((classHasMethodWithCubeDockerFile || classDefinesCubeDockerFile) && classDefinesImage) {\n throw new IllegalArgumentException(\n String.format(\"Container Object %s has defined %s annotation and %s annotation together.\",\n containerObjectClass.getSimpleName(), Image.class.getSimpleName(),\n CubeDockerFile.class.getSimpleName()));\n }\n\n // User has not defined either @CubeDockerfile or @Image\n if (!classDefinesCubeDockerFile && !classDefinesImage && !classHasMethodWithCubeDockerFile) {\n throw new IllegalArgumentException(\n String.format(\"Container Object %s is not annotated with either %s or %s annotations.\",\n containerObjectClass.getName(), CubeDockerFile.class.getSimpleName(), Image.class.getSimpleName()));\n }\n\n return this;\n }",
"private void beforeBatch(BatchBackend backend) {\n\t\tif ( this.purgeAtStart ) {\n\t\t\t// purgeAll for affected entities\n\t\t\tIndexedTypeSet targetedTypes = searchFactoryImplementor.getIndexedTypesPolymorphic( rootIndexedTypes );\n\t\t\tfor ( IndexedTypeIdentifier type : targetedTypes ) {\n\t\t\t\t// needs do be in-sync work to make sure we wait for the end of it.\n\t\t\t\tbackend.doWorkInSync( new PurgeAllLuceneWork( tenantId, type ) );\n\t\t\t}\n\t\t\tif ( this.optimizeAfterPurge ) {\n\t\t\t\tbackend.optimize( targetedTypes );\n\t\t\t}\n\t\t}\n\t}",
"public String getRepoKey() {\n String repoKey;\n if (isDynamicMode()) {\n repoKey = keyFromText;\n } else {\n repoKey = keyFromSelect;\n }\n return repoKey;\n }",
"public static final void getByteArray(byte[] data, int offset, int size, byte[] buffer, int bufferOffset)\n {\n System.arraycopy(data, offset, buffer, bufferOffset, size);\n }",
"public boolean process(DMatrixRMaj A , int numSingularValues, DMatrixRMaj nullspace ) {\n decomposition.decompose(A);\n\n if( A.numRows > A.numCols ) {\n Q.reshape(A.numCols,Math.min(A.numRows,A.numCols));\n decomposition.getQ(Q, true);\n } else {\n Q.reshape(A.numCols, A.numCols);\n decomposition.getQ(Q, false);\n }\n\n nullspace.reshape(Q.numRows,numSingularValues);\n CommonOps_DDRM.extract(Q,0,Q.numRows,Q.numCols-numSingularValues,Q.numCols,nullspace,0,0);\n\n return true;\n }"
] |
Convert an object to a set.
@param mapper the object mapper
@param source the source object
@param targetElementType the target set element type
@return set | [
"public static <E> Set<E> setify(ObjectMapper mapper, Object source, Class<E> targetElementType) {\n return (Set<E>) collectify(mapper, source, Set.class, targetElementType);\n }"
] | [
"protected boolean checkActionPackages(String classPackageName) {\n\t\tif (actionPackages != null) {\n\t\t\tfor (String packageName : actionPackages) {\n\t\t\t\tString strictPackageName = packageName + \".\";\n\t\t\t\tif (classPackageName.equals(packageName) || classPackageName.startsWith(strictPackageName))\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"public static void validateObserverMethod(ObserverMethod<?> observerMethod, BeanManager beanManager, ObserverMethod<?> originalObserverMethod) {\n Set<Annotation> qualifiers = observerMethod.getObservedQualifiers();\n if (observerMethod.getBeanClass() == null) {\n throw EventLogger.LOG.observerMethodsMethodReturnsNull(\"getBeanClass\", observerMethod);\n }\n if (observerMethod.getObservedType() == null) {\n throw EventLogger.LOG.observerMethodsMethodReturnsNull(\"getObservedType\", observerMethod);\n }\n Bindings.validateQualifiers(qualifiers, beanManager, observerMethod, \"ObserverMethod.getObservedQualifiers\");\n if (observerMethod.getReception() == null) {\n throw EventLogger.LOG.observerMethodsMethodReturnsNull(\"getReception\", observerMethod);\n }\n if (observerMethod.getTransactionPhase() == null) {\n throw EventLogger.LOG.observerMethodsMethodReturnsNull(\"getTransactionPhase\", observerMethod);\n }\n if (originalObserverMethod != null && (!observerMethod.getBeanClass().equals(originalObserverMethod.getBeanClass()))) {\n throw EventLogger.LOG.beanClassMismatch(originalObserverMethod, observerMethod);\n }\n if (!(observerMethod instanceof SyntheticObserverMethod) && !hasNotifyOverriden(observerMethod.getClass(), observerMethod)) {\n throw EventLogger.LOG.notifyMethodNotImplemented(observerMethod);\n }\n }",
"public static gslbvserver_spilloverpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tgslbvserver_spilloverpolicy_binding obj = new gslbvserver_spilloverpolicy_binding();\n\t\tobj.set_name(name);\n\t\tgslbvserver_spilloverpolicy_binding response[] = (gslbvserver_spilloverpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static <K, V> Map<K, V> immutableMapView(Map<K, V> map) {\n if (map instanceof ImmutableMap<?, ?>) {\n return map;\n }\n return Collections.unmodifiableMap(map);\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 }",
"private static String removeLastDot(final String pkgName) {\n\t\treturn pkgName.charAt(pkgName.length() - 1) == Characters.DOT ? pkgName.substring(0, pkgName.length() - 1) : pkgName;\n\t}",
"public static String getTabularData(String[] labels, String[][] data, int padding) {\n int[] size = new int[labels.length];\n \n for (int i = 0; i < labels.length; i++) {\n size[i] = labels[i].length() + padding;\n }\n \n for (String[] row : data) {\n for (int i = 0; i < labels.length; i++) {\n if (row[i].length() >= size[i]) {\n size[i] = row[i].length() + padding;\n }\n }\n }\n \n StringBuffer tabularData = new StringBuffer();\n \n for (int i = 0; i < labels.length; i++) {\n tabularData.append(labels[i]);\n tabularData.append(fill(' ', size[i] - labels[i].length()));\n }\n \n tabularData.append(\"\\n\");\n \n for (int i = 0; i < labels.length; i++) {\n tabularData.append(fill('=', size[i] - 1)).append(\" \");\n }\n \n tabularData.append(\"\\n\");\n \n \n for (String[] row : data) {\n for (int i = 0; i < labels.length; i++) {\n tabularData.append(row[i]);\n tabularData.append(fill(' ', size[i] - row[i].length()));\n }\n \n tabularData.append(\"\\n\");\n }\n \n return tabularData.toString();\n }",
"public void authenticate() {\n URL url;\n try {\n url = new URL(this.getTokenURL());\n } catch (MalformedURLException e) {\n assert false : \"An invalid token URL indicates a bug in the SDK.\";\n throw new RuntimeException(\"An invalid token URL indicates a bug in the SDK.\", e);\n }\n\n String jwtAssertion = this.constructJWTAssertion();\n\n String urlParameters = String.format(JWT_GRANT_TYPE, this.getClientID(), this.getClientSecret(), jwtAssertion);\n\n BoxAPIRequest request = new BoxAPIRequest(this, url, \"POST\");\n request.shouldAuthenticate(false);\n request.setBody(urlParameters);\n\n String json;\n try {\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n json = response.getJSON();\n } catch (BoxAPIException ex) {\n // Use the Date advertised by the Box server as the current time to synchronize clocks\n List<String> responseDates = ex.getHeaders().get(\"Date\");\n NumericDate currentTime;\n if (responseDates != null) {\n String responseDate = responseDates.get(0);\n SimpleDateFormat dateFormat = new SimpleDateFormat(\"EEE, d MMM yyyy HH:mm:ss zzz\");\n try {\n Date date = dateFormat.parse(responseDate);\n currentTime = NumericDate.fromMilliseconds(date.getTime());\n } catch (ParseException e) {\n currentTime = NumericDate.now();\n }\n } else {\n currentTime = NumericDate.now();\n }\n\n // Reconstruct the JWT assertion, which regenerates the jti claim, with the new \"current\" time\n jwtAssertion = this.constructJWTAssertion(currentTime);\n urlParameters = String.format(JWT_GRANT_TYPE, this.getClientID(), this.getClientSecret(), jwtAssertion);\n\n // Re-send the updated request\n request = new BoxAPIRequest(this, url, \"POST\");\n request.shouldAuthenticate(false);\n request.setBody(urlParameters);\n\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n json = response.getJSON();\n }\n\n JsonObject jsonObject = JsonObject.readFrom(json);\n this.setAccessToken(jsonObject.get(\"access_token\").asString());\n this.setLastRefresh(System.currentTimeMillis());\n this.setExpires(jsonObject.get(\"expires_in\").asLong() * 1000);\n\n //if token cache is specified, save to cache\n if (this.accessTokenCache != null) {\n String key = this.getAccessTokenCacheKey();\n JsonObject accessTokenCacheInfo = new JsonObject()\n .add(\"accessToken\", this.getAccessToken())\n .add(\"lastRefresh\", this.getLastRefresh())\n .add(\"expires\", this.getExpires());\n\n this.accessTokenCache.put(key, accessTokenCacheInfo.toString());\n }\n }",
"private byte[] getData(List<byte[]> blocks, int length)\n {\n byte[] result;\n\n if (blocks.isEmpty() == false)\n {\n if (length < 4)\n {\n length = 4;\n }\n\n result = new byte[length];\n int offset = 0;\n byte[] data;\n\n while (offset < length)\n {\n data = blocks.remove(0);\n System.arraycopy(data, 0, result, offset, data.length);\n offset += data.length;\n }\n }\n else\n {\n result = null;\n }\n\n return (result);\n }"
] |
Calculates how much of a time range is before or after a
target intersection point.
@param start time range start
@param end time range end
@param target target intersection point
@param after true if time after target required, false for time before
@return length of time in milliseconds | [
"private long getTime(Date start, Date end, long target, boolean after)\n {\n long total = 0;\n if (start != null && end != null)\n {\n Date startTime = DateHelper.getCanonicalTime(start);\n Date endTime = DateHelper.getCanonicalTime(end);\n\n Date startDay = DateHelper.getDayStartDate(start);\n Date finishDay = DateHelper.getDayStartDate(end);\n\n //\n // Handle the case where the end of the range is at midnight -\n // this will show up as the start and end days not matching\n //\n if (startDay.getTime() != finishDay.getTime())\n {\n endTime = DateHelper.addDays(endTime, 1);\n }\n\n int diff = DateHelper.compare(startTime, endTime, target);\n if (diff == 0)\n {\n if (after == true)\n {\n total = (endTime.getTime() - target);\n }\n else\n {\n total = (target - startTime.getTime());\n }\n }\n else\n {\n if ((after == true && diff < 0) || (after == false && diff > 0))\n {\n total = (endTime.getTime() - startTime.getTime());\n }\n }\n }\n return (total);\n }"
] | [
"public static boolean isCompleteZip(File file) throws IOException, NonScannableZipException {\n\n FileChannel channel = null;\n try {\n channel = new FileInputStream(file).getChannel();\n\n long size = channel.size();\n if (size < ENDLEN) { // Obvious case\n return false;\n }\n else if (validateEndRecord(file, channel, size - ENDLEN)) { // typical case where file is complete and end record has no comment\n return true;\n }\n\n // Either file is incomplete or the end of central directory record includes an arbitrary length comment\n // So, we have to scan backwards looking for an end of central directory record\n return scanForEndSig(file, channel);\n }\n finally {\n safeClose(channel);\n }\n }",
"public ContentAssistEntry createProposal(final String proposal, final ContentAssistContext context, final Procedure1<? super ContentAssistEntry> init) {\n return this.createProposal(proposal, context.getPrefix(), context, ContentAssistEntry.KIND_UNKNOWN, init);\n }",
"public final void notifyHeaderItemRangeChanged(int positionStart, int itemCount) {\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount >= headerItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \" + (positionStart + itemCount - 1) + \"] is not within the position bounds for header items [0 - \" + (headerItemCount - 1) + \"].\");\n }\n notifyItemRangeChanged(positionStart, itemCount);\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 }",
"private void readPredecessor(Task currTask, Project.Tasks.Task.PredecessorLink link)\n {\n BigInteger uid = link.getPredecessorUID();\n if (uid != null)\n {\n Task prevTask = m_projectFile.getTaskByUniqueID(Integer.valueOf(uid.intValue()));\n if (prevTask != null)\n {\n RelationType type;\n if (link.getType() != null)\n {\n type = RelationType.getInstance(link.getType().intValue());\n }\n else\n {\n type = RelationType.FINISH_START;\n }\n\n TimeUnit lagUnits = DatatypeConverter.parseDurationTimeUnits(link.getLagFormat());\n\n Duration lagDuration;\n int lag = NumberHelper.getInt(link.getLinkLag());\n if (lag == 0)\n {\n lagDuration = Duration.getInstance(0, lagUnits);\n }\n else\n {\n if (lagUnits == TimeUnit.PERCENT || lagUnits == TimeUnit.ELAPSED_PERCENT)\n {\n lagDuration = Duration.getInstance(lag, lagUnits);\n }\n else\n {\n lagDuration = Duration.convertUnits(lag / 10.0, TimeUnit.MINUTES, lagUnits, m_projectFile.getProjectProperties());\n }\n }\n\n Relation relation = currTask.addPredecessor(prevTask, type, lagDuration);\n m_eventManager.fireRelationReadEvent(relation);\n }\n }\n }",
"private TreeMap<Integer, Integer> createTaskMap(FieldMap fieldMap, FixedMeta taskFixedMeta, FixedData taskFixedData, Var2Data taskVarData)\n {\n TreeMap<Integer, Integer> taskMap = new TreeMap<Integer, Integer>();\n int uniqueIdOffset = fieldMap.getFixedDataOffset(TaskField.UNIQUE_ID);\n Integer taskNameKey = fieldMap.getVarDataKey(TaskField.NAME);\n int itemCount = taskFixedMeta.getAdjustedItemCount();\n int uniqueID;\n Integer key;\n\n //\n // First three items are not tasks, so let's skip them\n //\n for (int loop = 3; loop < itemCount; loop++)\n {\n byte[] data = taskFixedData.getByteArrayValue(loop);\n if (data != null)\n {\n byte[] metaData = taskFixedMeta.getByteArrayValue(loop);\n\n //\n // Check for the deleted task flag\n //\n int flags = MPPUtility.getInt(metaData, 0);\n if ((flags & 0x02) != 0)\n {\n // Project stores the deleted tasks unique id's into the fixed data as well\n // and at least in one case the deleted task was listed twice in the list\n // the second time with data with it causing a phantom task to be shown.\n // See CalendarErrorPhantomTasks.mpp\n //\n // So let's add the unique id for the deleted task into the map so we don't\n // accidentally include the task later.\n //\n uniqueID = MPPUtility.getShort(data, TASK_UNIQUE_ID_FIXED_OFFSET); // Only a short stored for deleted tasks?\n key = Integer.valueOf(uniqueID);\n if (taskMap.containsKey(key) == false)\n {\n taskMap.put(key, null); // use null so we can easily ignore this later\n }\n }\n else\n {\n //\n // Do we have a null task?\n //\n if (data.length == NULL_TASK_BLOCK_SIZE)\n {\n uniqueID = MPPUtility.getInt(data, TASK_UNIQUE_ID_FIXED_OFFSET);\n key = Integer.valueOf(uniqueID);\n if (taskMap.containsKey(key) == false)\n {\n taskMap.put(key, Integer.valueOf(loop));\n }\n }\n else\n {\n //\n // We apply a heuristic here - if we have more than 75% of the data, we assume\n // the task is valid.\n //\n int maxSize = fieldMap.getMaxFixedDataSize(0);\n if (maxSize == 0 || ((data.length * 100) / maxSize) > 75)\n {\n uniqueID = MPPUtility.getInt(data, uniqueIdOffset);\n key = Integer.valueOf(uniqueID);\n\n // Accept this task if it does not have a deleted unique ID or it has a deleted unique ID but the name is not null\n if (!taskMap.containsKey(key) || taskVarData.getUnicodeString(key, taskNameKey) != null)\n {\n taskMap.put(key, Integer.valueOf(loop));\n }\n }\n }\n }\n }\n }\n\n return (taskMap);\n }",
"@Override\n public ModelNode resolveValue(ExpressionResolver resolver, ModelNode value) throws OperationFailedException {\n\n // Pass non-OBJECT values through the superclass so it can reject weird values and, in the odd chance\n // that's how this object is set up, turn undefined into a default list value.\n ModelNode superResult = value.getType() == ModelType.OBJECT ? value : super.resolveValue(resolver, value);\n\n // If it's not an OBJECT (almost certainly UNDEFINED), then nothing more we can do\n if (superResult.getType() != ModelType.OBJECT) {\n return superResult;\n }\n\n // Resolve each field.\n // Don't mess with the original value\n ModelNode clone = superResult == value ? value.clone() : superResult;\n ModelNode result = new ModelNode();\n for (AttributeDefinition field : valueTypes) {\n String fieldName = field.getName();\n if (clone.has(fieldName)) {\n result.get(fieldName).set(field.resolveValue(resolver, clone.get(fieldName)));\n } else {\n // Input doesn't have a child for this field.\n // Don't create one in the output unless the AD produces a default value.\n // TBH this doesn't make a ton of sense, since any object should have\n // all of its fields, just some may be undefined. But doing it this\n // way may avoid breaking some code that is incorrectly checking node.has(\"xxx\")\n // instead of node.hasDefined(\"xxx\")\n ModelNode val = field.resolveValue(resolver, new ModelNode());\n if (val.isDefined()) {\n result.get(fieldName).set(val);\n }\n }\n }\n // Validate the entire object\n getValidator().validateParameter(getName(), result);\n return result;\n }",
"public List<Response> bulk(List<?> objects, boolean allOrNothing) {\n assertNotEmpty(objects, \"objects\");\n InputStream responseStream = null;\n HttpConnection connection;\n try {\n final JsonObject jsonObject = new JsonObject();\n if(allOrNothing) {\n jsonObject.addProperty(\"all_or_nothing\", true);\n }\n final URI uri = new DatabaseURIHelper(dbUri).bulkDocsUri();\n jsonObject.add(\"docs\", getGson().toJsonTree(objects));\n connection = Http.POST(uri, \"application/json\");\n if (jsonObject.toString().length() != 0) {\n connection.setRequestBody(jsonObject.toString());\n }\n couchDbClient.execute(connection);\n responseStream = connection.responseAsInputStream();\n List<Response> bulkResponses = getResponseList(responseStream, getGson(),\n DeserializationTypes.LC_RESPONSES);\n for(Response response : bulkResponses) {\n response.setStatusCode(connection.getConnection().getResponseCode());\n }\n return bulkResponses;\n }\n catch (IOException e) {\n throw new CouchDbException(\"Error retrieving response input stream.\", e);\n } finally {\n close(responseStream);\n }\n }",
"static boolean isInCircle(float x, float y, float centerX, float centerY, float\n radius) {\n return Math.abs(x - centerX) < radius && Math.abs(y - centerY) < radius;\n }"
] |
Gets the current user.
@param api the API connection of the current user.
@return the current user. | [
"public static BoxUser getCurrentUser(BoxAPIConnection api) {\n URL url = GET_ME_URL.build(api.getBaseURL());\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n return new BoxUser(api, jsonObject.get(\"id\").asString());\n }"
] | [
"private YearWeek with(int newYear, int newWeek) {\n if (year == newYear && week == newWeek) {\n return this;\n }\n return of(newYear, newWeek);\n }",
"private void changeClusterAndStores(String clusterKey,\n final Cluster cluster,\n String storesKey,\n final List<StoreDefinition> storeDefs) {\n metadataStore.writeLock.lock();\n try {\n VectorClock updatedVectorClock = ((VectorClock) metadataStore.get(clusterKey, null)\n .get(0)\n .getVersion()).incremented(metadataStore.getNodeId(),\n System.currentTimeMillis());\n metadataStore.put(clusterKey, Versioned.value((Object) cluster, updatedVectorClock));\n\n // now put new stores\n updatedVectorClock = ((VectorClock) metadataStore.get(storesKey, null)\n .get(0)\n .getVersion()).incremented(metadataStore.getNodeId(),\n System.currentTimeMillis());\n metadataStore.put(storesKey, Versioned.value((Object) storeDefs, updatedVectorClock));\n\n } catch(Exception e) {\n logger.info(\"Error while changing cluster to \" + cluster + \"for key \" + clusterKey);\n throw new VoldemortException(e);\n } finally {\n metadataStore.writeLock.unlock();\n }\n }",
"private void handleApplicationCommandRequest(SerialMessage incomingMessage) {\n\t\tlogger.trace(\"Handle Message Application Command Request\");\n\t\tint nodeId = incomingMessage.getMessagePayloadByte(1);\n\t\tlogger.debug(\"Application Command Request from Node \" + nodeId);\n\t\tZWaveNode node = getNode(nodeId);\n\t\t\n\t\tif (node == null) {\n\t\t\tlogger.warn(\"Node {} not initialized yet, ignoring message.\", nodeId);\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tnode.resetResendCount();\n\t\t\n\t\tint commandClassCode = incomingMessage.getMessagePayloadByte(3);\n\t\tZWaveCommandClass.CommandClass commandClass = ZWaveCommandClass.CommandClass.getCommandClass(commandClassCode);\n\n\t\tif (commandClass == null) {\n\t\t\tlogger.error(String.format(\"Unsupported command class 0x%02x\", commandClassCode));\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tlogger.debug(String.format(\"Incoming command class %s (0x%02x)\", commandClass.getLabel(), commandClass.getKey()));\n\t\tZWaveCommandClass zwaveCommandClass = node.getCommandClass(commandClass);\n\t\t\n\t\t// We got an unsupported command class, return.\n\t\tif (zwaveCommandClass == null) {\n\t\t\tlogger.error(String.format(\"Unsupported command class %s (0x%02x)\", commandClass.getLabel(), commandClassCode));\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tlogger.trace(\"Found Command Class {}, passing to handleApplicationCommandRequest\", zwaveCommandClass.getCommandClass().getLabel());\n\t\tzwaveCommandClass.handleApplicationCommandRequest(incomingMessage, 4, 1);\n\n\t\tif (incomingMessage.getMessageClass() == this.lastSentMessage.getExpectedReply() && nodeId == this.lastSentMessage.getMessageNode() && !incomingMessage.isTransActionCanceled()) {\n\t\t\t\tnotifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));\n\t\t\t\ttransactionCompleted.release();\n\t\t\t\tlogger.trace(\"Released. Transaction completed permit count -> {}\", transactionCompleted.availablePermits());\n\t\t}\n\t}",
"public FastTrackTable getTable(FastTrackTableType type)\n {\n FastTrackTable result = m_tables.get(type);\n if (result == null)\n {\n result = EMPTY_TABLE;\n }\n return result;\n }",
"private void readCollectionElement(\n\t\tfinal Object optionalOwner,\n\t\tfinal Serializable optionalKey,\n\t\tfinal CollectionPersister persister,\n\t\tfinal CollectionAliases descriptor,\n\t\tfinal ResultSet rs,\n\t\tfinal SharedSessionContractImplementor session)\n\t\t\t\tthrows HibernateException, SQLException {\n\n\t\tfinal PersistenceContext persistenceContext = session.getPersistenceContext();\n\n\t\t//implement persister.readKey using the grid type (later)\n\t\tfinal Serializable collectionRowKey = (Serializable) persister.readKey(\n\t\t\t\trs,\n\t\t\t\tdescriptor.getSuffixedKeyAliases(),\n\t\t\t\tsession\n\t\t);\n\n\t\tif ( collectionRowKey != null ) {\n\t\t\t// we found a collection element in the result set\n\n\t\t\tif ( log.isDebugEnabled() ) {\n\t\t\t\tlog.debug(\n\t\t\t\t\t\t\"found row of collection: \" +\n\t\t\t\t\t\tMessageHelper.collectionInfoString( persister, collectionRowKey, getFactory() )\n\t\t\t\t\t);\n\t\t\t}\n\n\t\t\tObject owner = optionalOwner;\n\t\t\tif ( owner == null ) {\n\t\t\t\towner = persistenceContext.getCollectionOwner( collectionRowKey, persister );\n\t\t\t\tif ( owner == null ) {\n\t\t\t\t\t//TODO: This is assertion is disabled because there is a bug that means the\n\t\t\t\t\t//\t original owner of a transient, uninitialized collection is not known\n\t\t\t\t\t//\t if the collection is re-referenced by a different object associated\n\t\t\t\t\t//\t with the current Session\n\t\t\t\t\t//throw new AssertionFailure(\"bug loading unowned collection\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tPersistentCollection rowCollection = persistenceContext.getLoadContexts()\n\t\t\t\t\t.getCollectionLoadContext( rs )\n\t\t\t\t\t.getLoadingCollection( persister, collectionRowKey );\n\n\t\t\tif ( rowCollection != null ) {\n\t\t\t\thydrateRowCollection( persister, descriptor, rs, owner, rowCollection );\n\t\t\t}\n\n\t\t}\n\t\telse if ( optionalKey != null ) {\n\t\t\t// we did not find a collection element in the result set, so we\n\t\t\t// ensure that a collection is created with the owner's identifier,\n\t\t\t// since what we have is an empty collection\n\n\t\t\tif ( log.isDebugEnabled() ) {\n\t\t\t\tlog.debug(\n\t\t\t\t\t\t\"result set contains (possibly empty) collection: \" +\n\t\t\t\t\t\tMessageHelper.collectionInfoString( persister, optionalKey, getFactory() )\n\t\t\t\t\t);\n\t\t\t}\n\n\t\t\tpersistenceContext.getLoadContexts()\n\t\t\t\t\t.getCollectionLoadContext( rs )\n\t\t\t\t\t.getLoadingCollection( persister, optionalKey ); // handle empty collection\n\n\t\t}\n\n\t\t// else no collection element, but also no owner\n\n\t}",
"public String getUrl(){\n\t\tfinal StringBuilder sb = new StringBuilder();\n\t\tsb.append(\"http://\");\n\t\tsb.append(getHttpConfiguration().getBindHost().get());\n\t\tsb.append(\":\");\n\t\tsb.append(getHttpConfiguration().getPort());\n\t\t\n\t\treturn sb.toString();\n\t}",
"public void setIndirectionHandlerClass(Class indirectionHandlerClass)\r\n {\r\n if(indirectionHandlerClass == null)\r\n {\r\n //throw new MetadataException(\"No IndirectionHandlerClass specified.\");\r\n /**\r\n * andrew.clute\r\n * Allow the default IndirectionHandler for the given ProxyFactory implementation\r\n * when the parameter is not given\r\n */\r\n indirectionHandlerClass = getDefaultIndirectionHandlerClass();\r\n }\r\n if(indirectionHandlerClass.isInterface()\r\n || Modifier.isAbstract(indirectionHandlerClass.getModifiers())\r\n || !getIndirectionHandlerBaseClass().isAssignableFrom(indirectionHandlerClass))\r\n {\r\n throw new MetadataException(\"Illegal class \"\r\n + indirectionHandlerClass.getName()\r\n + \" specified for IndirectionHandlerClass. Must be a concrete subclass of \"\r\n + getIndirectionHandlerBaseClass().getName());\r\n }\r\n _indirectionHandlerClass = indirectionHandlerClass;\r\n }",
"public void switchDataSource(BoneCPConfig newConfig) throws SQLException {\n\t\tlogger.info(\"Switch to new datasource requested. New Config: \"+newConfig);\n\t\tDataSource oldDS = getTargetDataSource();\n \n\t\tif (!(oldDS instanceof BoneCPDataSource)){\n\t\t\tthrow new SQLException(\"Unknown datasource type! Was expecting BoneCPDataSource but received \"+oldDS.getClass()+\". Not switching datasource!\");\n\t\t}\n\t\t\n\t\tBoneCPDataSource newDS = new BoneCPDataSource(newConfig);\n\t\tnewDS.getConnection().close(); // initialize a connection (+ throw it away) to force the datasource to initialize the pool\n\t\t\n\t\t// force application to start using the new one \n\t\tsetTargetDataSource(newDS);\n\t\t\n\t\tlogger.info(\"Shutting down old datasource slowly. Old Config: \"+oldDS);\n\t\t// tell the old datasource to terminate. This terminates the pool lazily so existing checked out connections can still be used.\n\t\t((BoneCPDataSource)oldDS).close();\n\t}",
"public int executeTask(final TransactionalProtocolClient.TransactionalOperationListener<ServerOperation> listener, final ServerUpdateTask task) {\n try {\n return execute(listener, task.getServerIdentity(), task.getOperation());\n } catch (OperationFailedException e) {\n // Handle failures operation transformation failures\n final ServerIdentity identity = task.getServerIdentity();\n final ServerOperation serverOperation = new ServerOperation(identity, task.getOperation(), null, null, OperationResultTransformer.ORIGINAL_RESULT);\n final TransactionalProtocolClient.PreparedOperation<ServerOperation> result = BlockingQueueOperationListener.FailedOperation.create(serverOperation, e);\n listener.operationPrepared(result);\n recordExecutedRequest(new ExecutedServerRequest(identity, result.getFinalResult(), OperationResultTransformer.ORIGINAL_RESULT));\n return 1; // 1 ms timeout since there is no reason to wait for the locally stored result\n }\n\n }"
] |
Update the repeat number for a client path
@param newNum new repeat number of the path
@param path_id ID of the path
@param client_uuid UUID of the client
@throws Exception exception | [
"public void updateRepeatNumber(int newNum, int path_id, String client_uuid) throws Exception {\n updateRequestResponseTables(\"repeat_number\", newNum, getProfileIdFromPathID(path_id), client_uuid, path_id);\n }"
] | [
"public static String getParentIdFromAgent(Launcher launcher, final String imageID, final String host) throws IOException, InterruptedException {\n return launcher.getChannel().call(new MasterToSlaveCallable<String, IOException>() {\n public String call() throws IOException {\n return DockerUtils.getParentId(imageID, host);\n }\n });\n }",
"public int updateRaw(DatabaseConnection connection, String statement, String[] arguments) throws SQLException {\n\t\tlogger.debug(\"running raw update statement: {}\", statement);\n\t\tif (arguments.length > 0) {\n\t\t\t// need to do the (Object) cast to force args to be a single object\n\t\t\tlogger.trace(\"update arguments: {}\", (Object) arguments);\n\t\t}\n\t\tCompiledStatement compiledStatement = connection.compileStatement(statement, StatementType.UPDATE, noFieldTypes,\n\t\t\t\tDatabaseConnection.DEFAULT_RESULT_FLAGS, false);\n\t\ttry {\n\t\t\tassignStatementArguments(compiledStatement, arguments);\n\t\t\treturn compiledStatement.runUpdate();\n\t\t} finally {\n\t\t\tIOUtils.closeThrowSqlException(compiledStatement, \"compiled statement\");\n\t\t}\n\t}",
"public static base_responses flush(nitro_service client, cacheobject resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcacheobject flushresources[] = new cacheobject[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tflushresources[i] = new cacheobject();\n\t\t\t\tflushresources[i].locator = resources[i].locator;\n\t\t\t\tflushresources[i].url = resources[i].url;\n\t\t\t\tflushresources[i].host = resources[i].host;\n\t\t\t\tflushresources[i].port = resources[i].port;\n\t\t\t\tflushresources[i].groupname = resources[i].groupname;\n\t\t\t\tflushresources[i].httpmethod = resources[i].httpmethod;\n\t\t\t\tflushresources[i].force = resources[i].force;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, flushresources,\"flush\");\n\t\t}\n\t\treturn result;\n\t}",
"public void growMaxLength( int arrayLength , boolean preserveValue ) {\n if( arrayLength < 0 )\n throw new IllegalArgumentException(\"Negative array length. Overflow?\");\n // see if multiplying numRows*numCols will cause an overflow. If it won't then pick the smaller of the two\n if( numRows != 0 && numCols <= Integer.MAX_VALUE / numRows ) {\n // save the user from themselves\n arrayLength = Math.min(numRows*numCols, arrayLength);\n }\n if( nz_values == null || arrayLength > this.nz_values.length ) {\n double[] data = new double[ arrayLength ];\n int[] row_idx = new int[ arrayLength ];\n\n if( preserveValue ) {\n if( nz_values == null )\n throw new IllegalArgumentException(\"Can't preserve values when uninitialized\");\n System.arraycopy(this.nz_values, 0, data, 0, this.nz_length);\n System.arraycopy(this.nz_rows, 0, row_idx, 0, this.nz_length);\n }\n\n this.nz_values = data;\n this.nz_rows = row_idx;\n }\n }",
"public void add(Vector3d v1) {\n x += v1.x;\n y += v1.y;\n z += v1.z;\n }",
"public void setReadTimeout(int millis) {\n\t\t// Hack to get round Spring's dynamic loading of http client stuff\n\t\tClientHttpRequestFactory f = getRequestFactory();\n\t\tif (f instanceof SimpleClientHttpRequestFactory) {\n\t\t\t((SimpleClientHttpRequestFactory) f).setReadTimeout(millis);\n\t\t}\n\t\telse {\n\t\t\t((HttpComponentsClientHttpRequestFactory) f).setReadTimeout(millis);\n\t\t}\n\t}",
"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 }",
"private File makeDestFile(URL src) {\n if (dest == null) {\n throw new IllegalArgumentException(\"Please provide a download destination\");\n }\n\n File destFile = dest;\n if (destFile.isDirectory()) {\n //guess name from URL\n String name = src.toString();\n if (name.endsWith(\"/\")) {\n name = name.substring(0, name.length() - 1);\n }\n name = name.substring(name.lastIndexOf('/') + 1);\n destFile = new File(dest, name);\n } else {\n //create destination directory\n File parent = destFile.getParentFile();\n if (parent != null) {\n parent.mkdirs();\n }\n }\n return destFile;\n }",
"public float getColorR(int vertex, int colorset) {\n if (!hasColors(colorset)) {\n throw new IllegalStateException(\"mesh has no colorset \" + colorset);\n }\n \n checkVertexIndexBounds(vertex);\n /* bound checks for colorset are done by java for us */\n \n return m_colorsets[colorset].getFloat(vertex * 4 * SIZEOF_FLOAT);\n }"
] |
Converts the transpose of a row major matrix into a row major block matrix.
@param src Original DMatrixRMaj. Not modified.
@param dst Equivalent DMatrixRBlock. Modified. | [
"public static void convertTranSrc(DMatrixRMaj src , DMatrixRBlock dst )\n {\n if( src.numRows != dst.numCols || src.numCols != dst.numRows )\n throw new IllegalArgumentException(\"Incompatible matrix shapes.\");\n\n for( int i = 0; i < dst.numRows; i += dst.blockLength ) {\n int blockHeight = Math.min( dst.blockLength , dst.numRows - i);\n\n for( int j = 0; j < dst.numCols; j += dst.blockLength ) {\n int blockWidth = Math.min( dst.blockLength , dst.numCols - j);\n\n int indexDst = i*dst.numCols + blockHeight*j;\n int indexSrc = j*src.numCols + i;\n\n for( int l = 0; l < blockWidth; l++ ) {\n int rowSrc = indexSrc + l*src.numCols;\n int rowDst = indexDst + l;\n for( int k = 0; k < blockHeight; k++ , rowDst += blockWidth ) {\n dst.data[ rowDst ] = src.data[rowSrc++];\n }\n }\n }\n }\n }"
] | [
"public static ProjectWriter getProjectWriter(String name) throws InstantiationException, IllegalAccessException\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 ProjectWriter> fileClass = WRITER_MAP.get(extension);\n if (fileClass == null)\n {\n throw new IllegalArgumentException(\"Cannot write files of type: \" + name);\n }\n\n ProjectWriter file = fileClass.newInstance();\n\n return (file);\n }",
"private void performPermissionCheck(CmsObject cms) throws CmsPermissionViolationException {\n\n if (cms.getRequestContext().getCurrentUser().isGuestUser()) {\n throw new CmsPermissionViolationException(null);\n }\n }",
"public static ProxyMetaClass getInstance(Class theClass) throws IntrospectionException {\n MetaClassRegistry metaRegistry = GroovySystem.getMetaClassRegistry();\n MetaClass meta = metaRegistry.getMetaClass(theClass);\n return new ProxyMetaClass(metaRegistry, theClass, meta);\n }",
"public static lbvserver_rewritepolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_rewritepolicy_binding obj = new lbvserver_rewritepolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_rewritepolicy_binding response[] = (lbvserver_rewritepolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void remove(RowKey key) {\n\t\tcurrentState.put( key, new AssociationOperation( key, null, REMOVE ) );\n\t}",
"public static PropertyOrder.Builder makeOrder(String property,\n PropertyOrder.Direction direction) {\n return PropertyOrder.newBuilder()\n .setProperty(makePropertyReference(property))\n .setDirection(direction);\n }",
"public void rotateToFaceCamera(final GVRTransform transform) {\n //see http://stackoverflow.com/questions/5782658/extracting-yaw-from-a-quaternion\n final GVRTransform t = getMainCameraRig().getHeadTransform();\n final Quaternionf q = new Quaternionf(0, t.getRotationY(), 0, t.getRotationW()).normalize();\n\n transform.rotateWithPivot(q.w, q.x, q.y, q.z, 0, 0, 0);\n }",
"public ItemRequest<Section> createInProject(String project) {\n \n String path = String.format(\"/projects/%s/sections\", project);\n return new ItemRequest<Section>(this, Section.class, path, \"POST\");\n }",
"private ProjectFile readTextFile(InputStream inputStream) throws MPXJException\n {\n ProjectReader reader = new AstaTextFileReader();\n addListeners(reader);\n return reader.read(inputStream);\n }"
] |
Gets the boxed type of a class
@param type The type
@return The boxed type | [
"public static Type boxedType(Type type) {\n if (type instanceof Class<?>) {\n return boxedClass((Class<?>) type);\n } else {\n return type;\n }\n }"
] | [
"static <T extends GridDialect> T getDialectFacetOrNull(GridDialect gridDialect, Class<T> facetType) {\n\t\tif ( hasFacet( gridDialect, facetType ) ) {\n\t\t\t@SuppressWarnings(\"unchecked\")\n\t\t\tT asFacet = (T) gridDialect;\n\t\t\treturn asFacet;\n\t\t}\n\n\t\treturn null;\n\t}",
"private void merge(Map<String, NodeT> source, Map<String, NodeT> target) {\n for (Map.Entry<String, NodeT> entry : source.entrySet()) {\n String key = entry.getKey();\n if (!target.containsKey(key)) {\n target.put(key, entry.getValue());\n }\n }\n }",
"private Object runWithPossibleProxySwap(Method method, Object target, Object[] args)\n\t\t\tthrows IllegalAccessException, InvocationTargetException {\n\t\tObject result;\n\t\t// swap with proxies to these too.\n\t\tif (method.getName().equals(\"createStatement\")){\n\t\t\tresult = memorize((Statement)method.invoke(target, args), this.connectionHandle.get());\n\t\t}\n\t\telse if (method.getName().equals(\"prepareStatement\")){\n\t\t\tresult = memorize((PreparedStatement)method.invoke(target, args), this.connectionHandle.get());\n\t\t}\n\t\telse if (method.getName().equals(\"prepareCall\")){\n\t\t\tresult = memorize((CallableStatement)method.invoke(target, args), this.connectionHandle.get());\n\t\t}\n\t\telse result = method.invoke(target, args);\n\t\treturn result;\n\t}",
"public static boolean xpathExists(Node document, String xpathExpression, Map<String, String> namespaceMapping) throws XPathException,\n MarshallingException\n {\n Boolean result = (Boolean) executeXPath(document, xpathExpression, namespaceMapping, XPathConstants.BOOLEAN);\n return result != null && result;\n }",
"public RedwoodConfiguration loggingClass(final Class<?> classToIgnoreInTraces){\r\n tasks.add(new Runnable() { public void run() { Redwood.addLoggingClass(classToIgnoreInTraces.getName()); } });\r\n return this;\r\n }",
"@JsonAnySetter\n public void setUnknownField(final String name, final Object value) {\n this.unknownFields.put(name, value);\n }",
"public static <K, V, T> Map<K, List<Versioned<V>>> getAll(Store<K, V, T> storageEngine,\n Iterable<K> keys,\n Map<K, T> transforms) {\n Map<K, List<Versioned<V>>> result = newEmptyHashMap(keys);\n for(K key: keys) {\n List<Versioned<V>> value = storageEngine.get(key,\n transforms != null ? transforms.get(key)\n : null);\n if(!value.isEmpty())\n result.put(key, value);\n }\n return result;\n }",
"public static List<String> getChildrenParentMayNotExist(ZkClient zkClient, String path) {\n try {\n return zkClient.getChildren(path);\n } catch (ZkNoNodeException e) {\n return null;\n }\n }",
"public 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 }"
] |
This method is called to try to catch any invalid tasks that may have sneaked past all our other checks.
This is done by validating the tasks by task ID. | [
"private void postProcessTasks()\n {\n List<Task> allTasks = m_file.getTasks();\n if (allTasks.size() > 1)\n {\n Collections.sort(allTasks);\n\n int taskID = -1;\n int lastTaskID = -1;\n\n for (int i = 0; i < allTasks.size(); i++)\n {\n Task task = allTasks.get(i);\n taskID = NumberHelper.getInt(task.getID());\n // In Project the tasks IDs are always contiguous so we can spot invalid tasks by making sure all\n // IDs are represented.\n if (!task.getNull() && lastTaskID != -1 && taskID > lastTaskID + 1)\n {\n // This task looks to be invalid.\n task.setNull(true);\n }\n else\n {\n lastTaskID = taskID;\n }\n }\n }\n }"
] | [
"@Override\n protected void onDraw(Canvas canvas) {\n super.onDraw(canvas);\n\n // If the API level is less than 11, we can't rely on the view animation system to\n // do the scrolling animation. Need to tick it here and call postInvalidate() until the scrolling is done.\n if (Build.VERSION.SDK_INT < 11) {\n tickScrollAnimation();\n if (!mScroller.isFinished()) {\n mGraph.postInvalidate();\n }\n }\n }",
"private Map<String, String> parseAttributes(I_CmsXmlContentLocation formatterLoc) {\n\n Map<String, String> result = new LinkedHashMap<>();\n for (I_CmsXmlContentValueLocation mappingLoc : formatterLoc.getSubValues(N_ATTRIBUTE)) {\n String key = CmsConfigurationReader.getString(m_cms, mappingLoc.getSubValue(N_KEY));\n String value = CmsConfigurationReader.getString(m_cms, mappingLoc.getSubValue(N_VALUE));\n result.put(key, value);\n }\n return Collections.unmodifiableMap(result);\n }",
"static JDOClass getJDOClass(Class c)\r\n\t{\r\n\t\tJDOClass rc = null;\r\n\t\ttry\r\n\t\t{\r\n\t\t\tJavaModelFactory javaModelFactory = RuntimeJavaModelFactory.getInstance();\r\n\t\t\tJavaModel javaModel = javaModelFactory.getJavaModel(c.getClassLoader());\r\n\t\t\tJDOModel m = JDOModelFactoryImpl.getInstance().getJDOModel(javaModel);\r\n\t\t\trc = m.getJDOClass(c.getName());\r\n\t\t}\r\n\t\tcatch (RuntimeException ex)\r\n\t\t{\r\n\t\t\tthrow new JDOFatalInternalException(\"Not a JDO class: \" + c.getName()); \r\n\t\t}\r\n\t\treturn rc;\r\n\t}",
"public void setMonth(String monthStr) {\n\n final Month month = Month.valueOf(monthStr);\n if ((m_model.getMonth() == null) || !m_model.getMonth().equals(monthStr)) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setMonth(month);\n onValueChange();\n\n }\n });\n }\n }",
"protected void removeEmptyDirectories(File outputDirectory)\n {\n if (outputDirectory.exists())\n {\n for (File file : outputDirectory.listFiles(new EmptyDirectoryFilter()))\n {\n file.delete();\n }\n }\n }",
"public SimpleConfiguration getClientConfiguration() {\n SimpleConfiguration clientConfig = new SimpleConfiguration();\n Iterator<String> iter = getKeys();\n while (iter.hasNext()) {\n String key = iter.next();\n if (key.startsWith(CONNECTION_PREFIX) || key.startsWith(ACCUMULO_PREFIX)\n || key.startsWith(CLIENT_PREFIX)) {\n clientConfig.setProperty(key, getRawString(key));\n }\n }\n return clientConfig;\n }",
"public static void init() {\n reports.clear();\n Reflections reflections = new Reflections(REPORTS_PACKAGE);\n final Set<Class<? extends Report>> reportClasses = reflections.getSubTypesOf(Report.class);\n\n for(Class<? extends Report> c : reportClasses) {\n LOG.info(\"Report class: \" + c.getName());\n try {\n reports.add(c.newInstance());\n } catch (IllegalAccessException | InstantiationException e) {\n LOG.error(\"Error while loading report implementation classes\", e);\n }\n }\n\n if(LOG.isInfoEnabled()) {\n LOG.info(String.format(\"Detected %s reports\", reports.size()));\n }\n }",
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void pushEvent(String eventName) {\n if (eventName == null || eventName.trim().equals(\"\"))\n return;\n\n pushEvent(eventName, null);\n }",
"public void clipTile(InternalTile tile, double scale, Coordinate panOrigin) throws GeomajasException {\n\t\tlog.debug(\"clipTile before {}\", tile);\n\t\tList<InternalFeature> orgFeatures = tile.getFeatures();\n\t\ttile.setFeatures(new ArrayList<InternalFeature>());\n\t\tGeometry maxScreenBbox = null; // The tile's maximum bounds in screen space. Used for clipping.\n\t\tfor (InternalFeature feature : orgFeatures) {\n\t\t\t// clip feature if necessary\n\t\t\tif (exceedsScreenDimensions(feature, scale)) {\n\t\t\t\tlog.debug(\"feature {} exceeds screen dimensions\", feature);\n\t\t\t\tInternalFeatureImpl vectorFeature = (InternalFeatureImpl) feature.clone();\n\t\t\t\ttile.setClipped(true);\n\t\t\t\tvectorFeature.setClipped(true);\n\t\t\t\tif (null == maxScreenBbox) {\n\t\t\t\t\tmaxScreenBbox = JTS.toGeometry(getMaxScreenEnvelope(tile, panOrigin));\n\t\t\t\t}\n\t\t\t\tGeometry clipped = maxScreenBbox.intersection(feature.getGeometry());\n\t\t\t\tvectorFeature.setClippedGeometry(clipped);\n\t\t\t\ttile.addFeature(vectorFeature);\n\t\t\t} else {\n\t\t\t\ttile.addFeature(feature);\n\t\t\t}\n\t\t}\n\t\tlog.debug(\"clipTile after {}\", tile);\n\t}"
] |
Sets the alert sound to be played.
Passing {@code null} disables the notification sound.
@param sound the file name or song name to be played
when receiving the notification
@return this | [
"public PayloadBuilder sound(final String sound) {\n if (sound != null) {\n aps.put(\"sound\", sound);\n } else {\n aps.remove(\"sound\");\n }\n return this;\n }"
] | [
"public void setDay(Day d)\n {\n if (m_day != null)\n {\n m_parentCalendar.removeHoursFromDay(this);\n }\n\n m_day = d;\n\n m_parentCalendar.attachHoursToDay(this);\n }",
"public static base_response unset(nitro_service client, snmpalarm resource, String[] args) throws Exception{\n\t\tsnmpalarm unsetresource = new snmpalarm();\n\t\tunsetresource.trapname = resource.trapname;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public 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 static Chart getMSDLineChart(Trajectory t, int lagMin, int lagMax,\n\t\t\tAbstractMeanSquaredDisplacmentEvaluator msdeval) {\n\n\t\tdouble[] xData = new double[lagMax - lagMin + 1];\n\t\tdouble[] yData = new double[lagMax - lagMin + 1];\n\t\tmsdeval.setTrajectory(t);\n\t\tmsdeval.setTimelag(lagMin);\n\t\tfor (int i = lagMin; i < lagMax + 1; i++) {\n\t\t\tmsdeval.setTimelag(i);\n\t\t\tdouble msdhelp = msdeval.evaluate()[0];\n\t\t\txData[i - lagMin] = i;\n\t\t\tyData[i - lagMin] = msdhelp;\n\t\t}\n\n\t\t// Create Chart\n\t\tChart chart = QuickChart.getChart(\"MSD Line\", \"LAG\", \"MSD\", \"MSD\",\n\t\t\t\txData, yData);\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}",
"public byte[] getResource(String pluginName, String fileName) throws Exception {\n // TODO: This is going to be slow.. future improvement is to cache the data instead of searching all jars\n for (String jarFilename : jarInformation) {\n JarFile jarFile = new JarFile(new File(jarFilename));\n Enumeration<?> enumer = jarFile.entries();\n\n // Use the Plugin-Name manifest entry to match with the provided pluginName\n String jarPluginName = jarFile.getManifest().getMainAttributes().getValue(\"Plugin-Name\");\n\n if (!jarPluginName.equals(pluginName)) {\n continue;\n }\n\n while (enumer.hasMoreElements()) {\n Object element = enumer.nextElement();\n String elementName = element.toString();\n\n // Skip items in the jar that don't start with \"resources/\"\n if (!elementName.startsWith(\"resources/\")) {\n continue;\n }\n\n elementName = elementName.replace(\"resources/\", \"\");\n if (elementName.equals(fileName)) {\n // get the file from the jar\n ZipEntry ze = jarFile.getEntry(element.toString());\n\n InputStream fileStream = jarFile.getInputStream(ze);\n byte[] data = new byte[(int) ze.getSize()];\n DataInputStream dataIs = new DataInputStream(fileStream);\n dataIs.readFully(data);\n dataIs.close();\n return data;\n }\n }\n }\n throw new FileNotFoundException(\"Could not find resource\");\n }",
"public static String format(ImageFormat format) {\n if (format == null) {\n throw new IllegalArgumentException(\"You must specify an image format.\");\n }\n return FILTER_FORMAT + \"(\" + format.value + \")\";\n }",
"private static void handlePing(final Channel channel, final ManagementProtocolHeader header) throws IOException {\n final ManagementProtocolHeader response = new ManagementPongHeader(header.getVersion());\n final MessageOutputStream output = channel.writeMessage();\n try {\n writeHeader(response, output);\n output.close();\n } finally {\n StreamUtils.safeClose(output);\n }\n }",
"private List<DomainControllerData> readFromFile(String directoryName) {\n List<DomainControllerData> data = new ArrayList<DomainControllerData>();\n if (directoryName == null) {\n return data;\n }\n\n if (conn == null) {\n init();\n }\n\n try {\n if (usingPreSignedUrls()) {\n PreSignedUrlParser parsedPut = new PreSignedUrlParser(pre_signed_put_url);\n directoryName = parsedPut.getPrefix();\n }\n String key = S3Util.sanitize(directoryName) + \"/\" + S3Util.sanitize(DC_FILE_NAME);\n GetResponse val = conn.get(location, key, null);\n if (val.object != null) {\n byte[] buf = val.object.data;\n if (buf != null && buf.length > 0) {\n try {\n data = S3Util.domainControllerDataFromByteBuffer(buf);\n } catch (Exception e) {\n throw HostControllerLogger.ROOT_LOGGER.failedMarshallingDomainControllerData();\n }\n }\n }\n return data;\n } catch (IOException e) {\n throw HostControllerLogger.ROOT_LOGGER.cannotAccessS3File(e.getLocalizedMessage());\n }\n }",
"public ItemRequest<Task> dependencies(String task) {\n \n String path = String.format(\"/tasks/%s/dependencies\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"GET\");\n }"
] |
Helper method to send message on outputStream and account for network
time stats.
@param outputStream
@param message
@throws IOException | [
"protected void sendMessage(DataOutputStream outputStream, Message message) throws IOException {\n long startNs = System.nanoTime();\n ProtoUtils.writeMessage(outputStream, message);\n if(streamStats != null) {\n streamStats.reportNetworkTime(operation,\n Utils.elapsedTimeNs(startNs, System.nanoTime()));\n }\n }"
] | [
"public static int colorSpline(int x, int numKnots, int[] xknots, int[] yknots) {\n\t\tint span;\n\t\tint numSpans = numKnots - 3;\n\t\tfloat k0, k1, k2, k3;\n\t\tfloat c0, c1, c2, c3;\n\t\t\n\t\tif (numSpans < 1)\n\t\t\tthrow new IllegalArgumentException(\"Too few knots in spline\");\n\t\t\n\t\tfor (span = 0; span < numSpans; span++)\n\t\t\tif (xknots[span+1] > x)\n\t\t\t\tbreak;\n\t\tif (span > numKnots-3)\n\t\t\tspan = numKnots-3;\n\t\tfloat t = (float)(x-xknots[span]) / (xknots[span+1]-xknots[span]);\n\t\tspan--;\n\t\tif (span < 0) {\n\t\t\tspan = 0;\n\t\t\tt = 0;\n\t\t}\n\n\t\tint v = 0;\n\t\tfor (int i = 0; i < 4; i++) {\n\t\t\tint shift = i * 8;\n\t\t\t\n\t\t\tk0 = (yknots[span] >> shift) & 0xff;\n\t\t\tk1 = (yknots[span+1] >> shift) & 0xff;\n\t\t\tk2 = (yknots[span+2] >> shift) & 0xff;\n\t\t\tk3 = (yknots[span+3] >> shift) & 0xff;\n\t\t\t\n\t\t\tc3 = m00*k0 + m01*k1 + m02*k2 + m03*k3;\n\t\t\tc2 = m10*k0 + m11*k1 + m12*k2 + m13*k3;\n\t\t\tc1 = m20*k0 + m21*k1 + m22*k2 + m23*k3;\n\t\t\tc0 = m30*k0 + m31*k1 + m32*k2 + m33*k3;\n\t\t\tint n = (int)(((c3*t + c2)*t + c1)*t + c0);\n\t\t\tif (n < 0)\n\t\t\t\tn = 0;\n\t\t\telse if (n > 255)\n\t\t\t\tn = 255;\n\t\t\tv |= n << shift;\n\t\t}\n\t\t\n\t\treturn v;\n\t}",
"private void unregisterAllServlets() {\n\n for (String endpoint : registeredServlets) {\n registeredServlets.remove(endpoint);\n web.unregister(endpoint);\n LOG.info(\"endpoint {} unregistered\", endpoint);\n }\n\n }",
"public BoxRetentionPolicyAssignment.Info assignToMetadataTemplate(String templateID,\r\n MetadataFieldFilter... fieldFilters) {\r\n return BoxRetentionPolicyAssignment.createAssignmentToMetadata(this.getAPI(), this.getID(), templateID,\r\n fieldFilters);\r\n }",
"public 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 }",
"private void processFields(Map<FieldType, String> map, Row row, FieldContainer container)\n {\n for (Map.Entry<FieldType, String> entry : map.entrySet())\n {\n FieldType field = entry.getKey();\n String name = entry.getValue();\n\n Object value;\n switch (field.getDataType())\n {\n case INTEGER:\n {\n value = row.getInteger(name);\n break;\n }\n\n case BOOLEAN:\n {\n value = Boolean.valueOf(row.getBoolean(name));\n break;\n }\n\n case DATE:\n {\n value = row.getDate(name);\n break;\n }\n\n case CURRENCY:\n case NUMERIC:\n case PERCENTAGE:\n {\n value = row.getDouble(name);\n break;\n }\n\n case DELAY:\n case WORK:\n case DURATION:\n {\n value = row.getDuration(name);\n break;\n }\n\n case RESOURCE_TYPE:\n {\n value = RESOURCE_TYPE_MAP.get(row.getString(name));\n break;\n }\n\n case TASK_TYPE:\n {\n value = TASK_TYPE_MAP.get(row.getString(name));\n break;\n }\n\n case CONSTRAINT:\n {\n value = CONSTRAINT_TYPE_MAP.get(row.getString(name));\n break;\n }\n\n case PRIORITY:\n {\n value = PRIORITY_MAP.get(row.getString(name));\n break;\n }\n\n case GUID:\n {\n value = row.getUUID(name);\n break;\n }\n\n default:\n {\n value = row.getString(name);\n break;\n }\n }\n\n container.set(field, value);\n }\n }",
"public static String termValue(String term) {\n int i = term.indexOf(MtasToken.DELIMITER);\n String value = null;\n if (i >= 0) {\n value = term.substring((i + MtasToken.DELIMITER.length()));\n value = (value.length() > 0) ? value : null;\n }\n return (value == null) ? null : value.replace(\"\\u0000\", \"\");\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 }",
"private void writeProperties() throws IOException\n {\n writeAttributeTypes(\"property_types\", ProjectField.values());\n writeFields(\"property_values\", m_projectFile.getProjectProperties(), ProjectField.values());\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 }"
] |
Gets container with alls groups of a certain user.
@param cms cmsobject
@param user to find groups for
@param caption caption property
@param iconProp property
@param ou ou
@param propStatus status property
@param iconProvider the icon provider
@return Indexed Container | [
"public static IndexedContainer getGroupsOfUser(\n CmsObject cms,\n CmsUser user,\n String caption,\n String iconProp,\n String ou,\n String propStatus,\n Function<CmsGroup, CmsCssIcon> iconProvider) {\n\n IndexedContainer container = new IndexedContainer();\n container.addContainerProperty(caption, String.class, \"\");\n container.addContainerProperty(ou, String.class, \"\");\n container.addContainerProperty(propStatus, Boolean.class, new Boolean(true));\n if (iconProvider != null) {\n container.addContainerProperty(iconProp, CmsCssIcon.class, null);\n }\n try {\n for (CmsGroup group : cms.getGroupsOfUser(user.getName(), true)) {\n Item item = container.addItem(group);\n item.getItemProperty(caption).setValue(group.getSimpleName());\n item.getItemProperty(ou).setValue(group.getOuFqn());\n if (iconProvider != null) {\n item.getItemProperty(iconProp).setValue(iconProvider.apply(group));\n }\n }\n } catch (CmsException e) {\n LOG.error(\"Unable to read groups from user\", e);\n }\n return container;\n }"
] | [
"private void addIndex(IndexDescriptorDef indexDescDef, TableDef tableDef)\r\n {\r\n IndexDef indexDef = tableDef.getIndex(indexDescDef.getName());\r\n\r\n if (indexDef == null)\r\n {\r\n indexDef = new IndexDef(indexDescDef.getName(),\r\n indexDescDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_UNIQUE, false));\r\n tableDef.addIndex(indexDef);\r\n }\r\n\r\n try\r\n {\r\n String fieldNames = indexDescDef.getProperty(PropertyHelper.OJB_PROPERTY_FIELDS);\r\n ArrayList fields = ((ClassDescriptorDef)indexDescDef.getOwner()).getFields(fieldNames);\r\n FieldDescriptorDef fieldDef;\r\n\r\n for (Iterator it = fields.iterator(); it.hasNext();)\r\n {\r\n fieldDef = (FieldDescriptorDef)it.next();\r\n indexDef.addColumn(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN));\r\n }\r\n }\r\n catch (NoSuchFieldException ex)\r\n {\r\n // won't happen if we already checked the constraints\r\n }\r\n }",
"public void sendJsonToUser(Object data, String username) {\n sendToUser(JSON.toJSONString(data), username);\n }",
"private List<Row> createTimeEntryRowList(String shiftData) throws ParseException\n {\n List<Row> list = new ArrayList<Row>();\n String[] shifts = shiftData.split(\",|:\");\n int index = 1;\n while (index < shifts.length)\n {\n index += 2;\n int entryCount = Integer.parseInt(shifts[index]);\n index++;\n\n for (int entryIndex = 0; entryIndex < entryCount; entryIndex++)\n {\n Integer exceptionTypeID = Integer.valueOf(shifts[index + 0]);\n Date startTime = DatatypeConverter.parseBasicTime(shifts[index + 1]);\n Date endTime = DatatypeConverter.parseBasicTime(shifts[index + 2]);\n\n Map<String, Object> map = new HashMap<String, Object>();\n map.put(\"START_TIME\", startTime);\n map.put(\"END_TIME\", endTime);\n map.put(\"EXCEPTIOP\", exceptionTypeID);\n\n list.add(new MapRow(map));\n\n index += 3;\n }\n }\n\n return list;\n }",
"public static Integer convertProfileIdentifier(String profileIdentifier) throws Exception {\n Integer profileId = -1;\n if (profileIdentifier == null) {\n throw new Exception(\"A profileIdentifier must be specified\");\n } else {\n try {\n profileId = Integer.parseInt(profileIdentifier);\n } catch (NumberFormatException ne) {\n // this is OK.. just means it's not a #\n // try to get it by name instead\n profileId = ProfileService.getInstance().getIdFromName(profileIdentifier);\n\n }\n }\n logger.info(\"Profile id is {}\", profileId);\n return profileId;\n }",
"private void showSettingsMenu(final Cursor cursor) {\n Log.d(TAG, \"showSettingsMenu\");\n enableSettingsCursor(cursor);\n context.runOnGlThread(new Runnable() {\n @Override\n public void run() {\n new SettingsView(context, scene, CursorManager.this,\n settingsCursor.getIoDevice().getCursorControllerId(), cursor, new\n SettingsChangeListener() {\n @Override\n public void onBack(boolean cascading) {\n disableSettingsCursor();\n }\n\n @Override\n public int onDeviceChanged(IoDevice device) {\n // we are changing the io device on the settings cursor\n removeCursorFromScene(settingsCursor);\n IoDevice clickedDevice = getAvailableIoDevice(device);\n settingsCursor.setIoDevice(clickedDevice);\n addCursorToScene(settingsCursor);\n return device.getCursorControllerId();\n }\n });\n }\n });\n }",
"public ImmutableList<CandidateElement> extract(StateVertex currentState)\n\t\t\tthrows CrawljaxException {\n\t\tLinkedList<CandidateElement> results = new LinkedList<>();\n\n\t\tif (!checkedElements.checkCrawlCondition(browser)) {\n\t\t\tLOG.info(\"State {} did not satisfy the CrawlConditions.\", currentState.getName());\n\t\t\treturn ImmutableList.of();\n\t\t}\n\t\tLOG.debug(\"Looking in state: {} for candidate elements\", currentState.getName());\n\n\t\ttry {\n\t\t\tDocument dom = DomUtils.asDocument(browser.getStrippedDomWithoutIframeContent());\n\t\t\textractElements(dom, results, \"\");\n\t\t} catch (IOException e) {\n\t\t\tLOG.error(e.getMessage(), e);\n\t\t\tthrow new CrawljaxException(e);\n\t\t}\n\t\tif (randomizeElementsOrder) {\n\t\t\tCollections.shuffle(results);\n\t\t}\n\t\tcurrentState.setElementsFound(results);\n\t\tLOG.debug(\"Found {} new candidate elements to analyze!\", results.size());\n\t\treturn ImmutableList.copyOf(results);\n\t}",
"public static netbridge_vlan_binding[] get(nitro_service service, String name) throws Exception{\n\t\tnetbridge_vlan_binding obj = new netbridge_vlan_binding();\n\t\tobj.set_name(name);\n\t\tnetbridge_vlan_binding response[] = (netbridge_vlan_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static void acceptsUrl(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_U, OPT_URL), \"bootstrap url\")\n .withRequiredArg()\n .describedAs(\"url\")\n .ofType(String.class);\n }",
"public static lbvserver_stats get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_stats obj = new lbvserver_stats();\n\t\tobj.set_name(name);\n\t\tlbvserver_stats response = (lbvserver_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}"
] |
Subtracts the given range from this range, to produce either zero, one, or two address ranges that contain the addresses in this range and not in the given range.
If the result has length 2, the two ranges are in increasing order.
@param other
@return | [
"public IPAddressSeqRange[] subtract(IPAddressSeqRange other) {\n\t\tIPAddress otherLower = other.getLower();\n\t\tIPAddress otherUpper = other.getUpper();\n\t\tIPAddress lower = this.getLower();\n\t\tIPAddress upper = this.getUpper();\n\t\tif(compareLowValues(lower, otherLower) < 0) {\n\t\t\tif(compareLowValues(upper, otherUpper) > 0) { // l ol ou u\n\t\t\t\treturn createPair(lower, otherLower.increment(-1), otherUpper.increment(1), upper);\n\t\t\t} else {\n\t\t\t\tint comp = compareLowValues(upper, otherLower);\n\t\t\t\tif(comp < 0) { // l u ol ou\n\t\t\t\t\treturn createSingle();\n\t\t\t\t} else if(comp == 0) { // l u == ol ou\n\t\t\t\t\treturn createSingle(lower, upper.increment(-1));\n\t\t\t\t}\n\t\t\t\treturn createSingle(lower, otherLower.increment(-1)); // l ol u ou \n\t\t\t}\n\t\t} else if(compareLowValues(otherUpper, upper) >= 0) { // ol l u ou\n\t\t\treturn createEmpty();\n\t\t} else {\n\t\t\tint comp = compareLowValues(otherUpper, lower);\n\t\t\tif(comp < 0) {\n\t\t\t\treturn createSingle(); // ol ou l u\n\t\t\t} else if(comp == 0) {\n\t\t\t\treturn createSingle(lower.increment(1), upper); //ol ou == l u\n\t\t\t}\n\t\t\treturn createSingle(otherUpper.increment(1), upper); // ol l ou u \n\t\t}\n\t}"
] | [
"public void characters(char ch[], int start, int length)\r\n {\r\n if (m_CurrentString == null)\r\n m_CurrentString = new String(ch, start, length);\r\n else\r\n m_CurrentString += new String(ch, start, length);\r\n }",
"static void initializeExtension(ExtensionRegistry extensionRegistry, String module,\n ManagementResourceRegistration rootRegistration,\n ExtensionRegistryType extensionRegistryType) {\n try {\n boolean unknownModule = false;\n boolean initialized = false;\n for (Extension extension : Module.loadServiceFromCallerModuleLoader(module, Extension.class)) {\n ClassLoader oldTccl = WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(extension.getClass());\n try {\n if (unknownModule || !extensionRegistry.getExtensionModuleNames().contains(module)) {\n // This extension wasn't handled by the standalone.xml or domain.xml parsing logic, so we\n // need to initialize its parsers so we can display what XML namespaces it supports\n extensionRegistry.initializeParsers(extension, module, null);\n // AS7-6190 - ensure we initialize parsers for other extensions from this module\n // now that we know the registry was unaware of the module\n unknownModule = true;\n }\n extension.initialize(extensionRegistry.getExtensionContext(module, rootRegistration, extensionRegistryType));\n } finally {\n WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTccl);\n }\n initialized = true;\n }\n if (!initialized) {\n throw ControllerLogger.ROOT_LOGGER.notFound(\"META-INF/services/\", Extension.class.getName(), module);\n }\n } catch (ModuleNotFoundException e) {\n // Treat this as a user mistake, e.g. incorrect module name.\n // Throw OFE so post-boot it only gets logged at DEBUG.\n throw ControllerLogger.ROOT_LOGGER.extensionModuleNotFound(e, module);\n } catch (ModuleLoadException e) {\n // The module is there but can't be loaded. Treat this as an internal problem.\n // Throw a runtime exception so it always gets logged at ERROR in the server log with stack trace details.\n throw ControllerLogger.ROOT_LOGGER.extensionModuleLoadingFailure(e, module);\n }\n }",
"public HiveShellContainer evaluateStatement(List<? extends Script> scripts, Object target, TemporaryFolder temporaryFolder, Statement base) throws Throwable {\n container = null;\n FileUtil.setPermission(temporaryFolder.getRoot(), FsPermission.getDirDefault());\n try {\n LOGGER.info(\"Setting up {} in {}\", getName(), temporaryFolder.getRoot().getAbsolutePath());\n container = createHiveServerContainer(scripts, target, temporaryFolder);\n base.evaluate();\n return container;\n } finally {\n tearDown();\n }\n }",
"public static RgbaColor fromRgba(String rgba) {\n if (rgba.length() == 0) return getDefaultColor();\n\n String[] parts = getRgbaParts(rgba).split(\",\");\n if (parts.length == 4) {\n return new RgbaColor(parseInt(parts[0]),\n parseInt(parts[1]),\n parseInt(parts[2]),\n parseFloat(parts[3]));\n }\n else {\n return getDefaultColor();\n }\n }",
"protected void associateBatched(Collection owners, Collection children)\r\n {\r\n CollectionDescriptor cds = getCollectionDescriptor();\r\n PersistentField field = cds.getPersistentField();\r\n PersistenceBroker pb = getBroker();\r\n Class ownerTopLevelClass = pb.getTopLevelClass(getOwnerClassDescriptor().getClassOfObject());\r\n Class collectionClass = cds.getCollectionClass(); // this collection type will be used:\r\n HashMap ownerIdsToLists = new HashMap(owners.size());\r\n\r\n IdentityFactory identityFactory = pb.serviceIdentity();\r\n // initialize the owner list map\r\n for (Iterator it = owners.iterator(); it.hasNext();)\r\n {\r\n Object owner = it.next();\r\n ownerIdsToLists.put(identityFactory.buildIdentity(getOwnerClassDescriptor(), owner), new ArrayList());\r\n }\r\n\r\n // build the children lists for the owners\r\n for (Iterator it = children.iterator(); it.hasNext();)\r\n {\r\n Object child = it.next();\r\n // BRJ: use cld for real class, relatedObject could be Proxy\r\n ClassDescriptor cld = getDescriptorRepository().getDescriptorFor(ProxyHelper.getRealClass(child));\r\n\r\n Object[] fkValues = cds.getForeignKeyValues(child, cld);\r\n Identity ownerId = identityFactory.buildIdentity(null, ownerTopLevelClass, fkValues);\r\n List list = (List) ownerIdsToLists.get(ownerId);\r\n if (list != null)\r\n {\r\n list.add(child);\r\n }\r\n }\r\n\r\n // connect children list to owners\r\n for (Iterator it = owners.iterator(); it.hasNext();)\r\n {\r\n Object result;\r\n Object owner = it.next();\r\n Identity ownerId = identityFactory.buildIdentity(owner);\r\n List list = (List) ownerIdsToLists.get(ownerId);\r\n\r\n if ((collectionClass == null) && field.getType().isArray())\r\n {\r\n int length = list.size();\r\n Class itemtype = field.getType().getComponentType();\r\n result = Array.newInstance(itemtype, length);\r\n for (int j = 0; j < length; j++)\r\n {\r\n Array.set(result, j, list.get(j));\r\n }\r\n }\r\n else\r\n {\r\n ManageableCollection col = createCollection(cds, collectionClass);\r\n for (Iterator it2 = list.iterator(); it2.hasNext();)\r\n {\r\n col.ojbAdd(it2.next());\r\n }\r\n result = col;\r\n }\r\n\r\n Object value = field.get(owner);\r\n if ((value instanceof CollectionProxyDefaultImpl) && (result instanceof Collection))\r\n {\r\n ((CollectionProxyDefaultImpl) value).setData((Collection) result);\r\n }\r\n else\r\n {\r\n field.set(owner, result);\r\n }\r\n }\r\n }",
"public Task<Void> resendConfirmationEmail(@NonNull final String email) {\n return dispatcher.dispatchTask(\n new Callable<Void>() {\n @Override\n public Void call() {\n resendConfirmationEmailInternal(email);\n return null;\n }\n });\n }",
"public static ObjectModelResolver get(String resolverId) {\n List<ObjectModelResolver> resolvers = getResolvers();\n\n for (ObjectModelResolver resolver : resolvers) {\n if (resolver.accept(resolverId)) {\n return resolver;\n }\n }\n\n return null;\n }",
"public void recordCheckoutTimeUs(SocketDestination dest, long checkoutTimeUs) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordCheckoutTimeUs(null, checkoutTimeUs);\n recordCheckoutTimeUs(null, checkoutTimeUs);\n } else {\n this.checkoutTimeRequestCounter.addRequest(checkoutTimeUs * Time.NS_PER_US);\n }\n }",
"public static <T> int createTable(ConnectionSource connectionSource, Class<T> dataClass) throws SQLException {\n\t\tDao<T, ?> dao = DaoManager.createDao(connectionSource, dataClass);\n\t\treturn doCreateTable(dao, false);\n\t}"
] |
Creates the project used to import module resources and sets it on the CmsObject.
@param cms the CmsObject to set the project on
@param module the module
@return the created project
@throws CmsException if something goes wrong | [
"protected CmsProject createAndSetModuleImportProject(CmsObject cms, CmsModule module) throws CmsException {\n\n CmsProject importProject = cms.createProject(\n org.opencms.module.Messages.get().getBundle(cms.getRequestContext().getLocale()).key(\n org.opencms.module.Messages.GUI_IMPORT_MODULE_PROJECT_NAME_1,\n new Object[] {module.getName()}),\n org.opencms.module.Messages.get().getBundle(cms.getRequestContext().getLocale()).key(\n org.opencms.module.Messages.GUI_IMPORT_MODULE_PROJECT_DESC_1,\n new Object[] {module.getName()}),\n OpenCms.getDefaultUsers().getGroupAdministrators(),\n OpenCms.getDefaultUsers().getGroupAdministrators(),\n CmsProject.PROJECT_TYPE_TEMPORARY);\n cms.getRequestContext().setCurrentProject(importProject);\n cms.copyResourceToProject(\"/\");\n return importProject;\n }"
] | [
"@IntRange(from = 0, to = OPAQUE)\n private static int resolveLineAlpha(\n @IntRange(from = 0, to = OPAQUE) final int sceneAlpha,\n final float maxDistance,\n final float distance) {\n final float alphaPercent = 1f - distance / maxDistance;\n final int alpha = (int) ((float) OPAQUE * alphaPercent);\n return alpha * sceneAlpha / OPAQUE;\n }",
"public static authenticationlocalpolicy_authenticationvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationlocalpolicy_authenticationvserver_binding obj = new authenticationlocalpolicy_authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationlocalpolicy_authenticationvserver_binding response[] = (authenticationlocalpolicy_authenticationvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"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 String getEditorParameter(CmsObject cms, String editor, String param) {\n\n String path = OpenCms.getSystemInfo().getConfigFilePath(cms, \"editors/\" + editor + \".properties\");\n CmsVfsMemoryObjectCache cache = CmsVfsMemoryObjectCache.getVfsMemoryObjectCache();\n CmsParameterConfiguration config = (CmsParameterConfiguration)cache.getCachedObject(cms, path);\n if (config == null) {\n try {\n CmsFile file = cms.readFile(path);\n try (ByteArrayInputStream input = new ByteArrayInputStream(file.getContents())) {\n config = new CmsParameterConfiguration(input); // Uses ISO-8859-1, should be OK for config parameters\n cache.putCachedObject(cms, path, config);\n }\n } catch (CmsVfsResourceNotFoundException e) {\n return null;\n } catch (Exception e) {\n LOG.error(e.getLocalizedMessage(), e);\n return null;\n }\n }\n return config.getString(param, null);\n }",
"private static MessageInfo mapMessageInfo(MessageInfoType messageInfoType) {\n MessageInfo messageInfo = new MessageInfo();\n if (messageInfoType != null) {\n messageInfo.setFlowId(messageInfoType.getFlowId());\n messageInfo.setMessageId(messageInfoType.getMessageId());\n messageInfo.setOperationName(messageInfoType.getOperationName());\n messageInfo.setPortType(messageInfoType.getPorttype() == null\n ? \"\" : messageInfoType.getPorttype().toString());\n messageInfo.setTransportType(messageInfoType.getTransport());\n }\n return messageInfo;\n }",
"protected void layoutChild(final int dataIndex) {\n Widget child = mContainer.get(dataIndex);\n if (child != null) {\n float offset = mOffset.get(Axis.X);\n if (!equal(offset, 0)) {\n updateTransform(child, Axis.X, offset);\n }\n\n offset = mOffset.get(Axis.Y);\n if (!equal(offset, 0)) {\n updateTransform(child, Axis.Y, offset);\n }\n\n offset = mOffset.get(Axis.Z);\n if (!equal(offset, 0)) {\n updateTransform(child, Axis.Z, offset);\n }\n }\n }",
"@Override\n public boolean awaitCompletion(long timeout, TimeUnit unit) throws InterruptedException {\n long deadline = unit.toMillis(timeout) + System.currentTimeMillis();\n lock.lock(); try {\n assert shutdown;\n while(activeCount != 0) {\n long remaining = deadline - System.currentTimeMillis();\n if (remaining <= 0) {\n break;\n }\n condition.await(remaining, TimeUnit.MILLISECONDS);\n }\n boolean allComplete = activeCount == 0;\n if (!allComplete) {\n ProtocolLogger.ROOT_LOGGER.debugf(\"ActiveOperation(s) %s have not completed within %d %s\", activeRequests.keySet(), timeout, unit);\n }\n return allComplete;\n } finally {\n lock.unlock();\n }\n }",
"public FluoMutationGenerator put(Column col, CharSequence value) {\n return put(col, value.toString().getBytes(StandardCharsets.UTF_8));\n }",
"public String getRepoKey() {\n String repoKey;\n if (isDynamicMode()) {\n repoKey = keyFromText;\n } else {\n repoKey = keyFromSelect;\n }\n return repoKey;\n }"
] |
Handles the response of the MemoryGetId request.
The MemoryGetId function gets the home and node id from the controller memory.
@param incomingMessage the response message to process. | [
"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 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 }",
"@JmxGetter(name = \"getChunkIdToNumChunks\", description = \"Returns a string representation of the map of chunk id to number of chunks\")\n public String getChunkIdToNumChunks() {\n StringBuilder builder = new StringBuilder();\n for(Entry<Object, Integer> entry: fileSet.getChunkIdToNumChunks().entrySet()) {\n builder.append(entry.getKey().toString() + \" - \" + entry.getValue().toString() + \", \");\n }\n return builder.toString();\n }",
"private void populateRecurringException(ProjectCalendarException mpxjException, Exceptions.Exception xmlException)\n {\n RecurringData data = mpxjException.getRecurring();\n xmlException.setEnteredByOccurrences(Boolean.TRUE);\n xmlException.setOccurrences(NumberHelper.getBigInteger(data.getOccurrences()));\n\n switch (data.getRecurrenceType())\n {\n case DAILY:\n {\n xmlException.setType(BigInteger.valueOf(7));\n xmlException.setPeriod(NumberHelper.getBigInteger(data.getFrequency()));\n break;\n }\n\n case WEEKLY:\n {\n xmlException.setType(BigInteger.valueOf(6));\n xmlException.setPeriod(NumberHelper.getBigInteger(data.getFrequency()));\n xmlException.setDaysOfWeek(getDaysOfTheWeek(data));\n break;\n }\n\n case MONTHLY:\n {\n xmlException.setPeriod(NumberHelper.getBigInteger(data.getFrequency()));\n if (data.getRelative())\n {\n xmlException.setType(BigInteger.valueOf(5));\n xmlException.setMonthItem(BigInteger.valueOf(data.getDayOfWeek().getValue() + 2));\n xmlException.setMonthPosition(BigInteger.valueOf(NumberHelper.getInt(data.getDayNumber()) - 1));\n }\n else\n {\n xmlException.setType(BigInteger.valueOf(4));\n xmlException.setMonthDay(NumberHelper.getBigInteger(data.getDayNumber()));\n }\n break;\n }\n\n case YEARLY:\n {\n xmlException.setMonth(BigInteger.valueOf(NumberHelper.getInt(data.getMonthNumber()) - 1));\n if (data.getRelative())\n {\n xmlException.setType(BigInteger.valueOf(3));\n xmlException.setMonthItem(BigInteger.valueOf(data.getDayOfWeek().getValue() + 2));\n xmlException.setMonthPosition(BigInteger.valueOf(NumberHelper.getInt(data.getDayNumber()) - 1));\n }\n else\n {\n xmlException.setType(BigInteger.valueOf(2));\n xmlException.setMonthDay(NumberHelper.getBigInteger(data.getDayNumber()));\n }\n }\n }\n }",
"public ItemRequest<Team> findById(String team) {\n \n String path = String.format(\"/teams/%s\", team);\n return new ItemRequest<Team>(this, Team.class, path, \"GET\");\n }",
"public static base_response delete(nitro_service client, Long clid) throws Exception {\n\t\tclusterinstance deleteresource = new clusterinstance();\n\t\tdeleteresource.clid = clid;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"protected void reportWorked(int workIncrement, int currentUnitIndex) {\n if (this.progress != null) {\n if (this.progress.isCanceled()) {\n // Only AbortCompilation can stop the compiler cleanly.\n // We check cancellation again following the call to compile.\n throw new AbortCompilation(true, null);\n }\n this.progress.worked(workIncrement, (this.totalUnits* this.remainingIterations) - currentUnitIndex - 1);\n }\n }",
"public Metadata setMetadata(String templateName, String scope, Metadata metadata) {\n Metadata metadataValue = null;\n\n try {\n metadataValue = this.createMetadata(templateName, scope, metadata);\n } catch (BoxAPIException e) {\n if (e.getResponseCode() == 409) {\n Metadata metadataToUpdate = new Metadata(scope, templateName);\n for (JsonValue value : metadata.getOperations()) {\n if (value.asObject().get(\"value\").isNumber()) {\n metadataToUpdate.add(value.asObject().get(\"path\").asString(),\n value.asObject().get(\"value\").asFloat());\n } else if (value.asObject().get(\"value\").isString()) {\n metadataToUpdate.add(value.asObject().get(\"path\").asString(),\n value.asObject().get(\"value\").asString());\n } else if (value.asObject().get(\"value\").isArray()) {\n ArrayList<String> list = new ArrayList<String>();\n for (JsonValue jsonValue : value.asObject().get(\"value\").asArray()) {\n list.add(jsonValue.asString());\n }\n metadataToUpdate.add(value.asObject().get(\"path\").asString(), list);\n }\n }\n metadataValue = this.updateMetadata(metadataToUpdate);\n }\n }\n\n return metadataValue;\n }",
"@Inject\n public void setQueue(EventQueue queue) {\n if (epi == null) {\n MessageToEventMapper mapper = new MessageToEventMapper();\n mapper.setMaxContentLength(maxContentLength);\n\n epi = new EventProducerInterceptor(mapper, queue);\n }\n }",
"public void setFrustum(Matrix4f projMatrix)\n {\n if (projMatrix != null)\n {\n if (mProjMatrix == null)\n {\n mProjMatrix = new float[16];\n }\n mProjMatrix = projMatrix.get(mProjMatrix, 0);\n mScene.setPickVisible(false);\n if (mCuller != null)\n {\n mCuller.set(projMatrix);\n }\n else\n {\n mCuller = new FrustumIntersection(projMatrix);\n }\n }\n mProjection = projMatrix;\n }"
] |
Calculate Median value.
@param values Values.
@return Median. | [
"public static int Median( int[] values ){\n int total = 0, n = values.length;\n\n // for all values\n for ( int i = 0; i < n; i++ )\n {\n // accumalate total\n total += values[i];\n }\n\n int halfTotal = total / 2;\n int median = 0, v = 0;\n\n // find median value\n for ( ; median < n; median++ )\n {\n v += values[median];\n if ( v >= halfTotal )\n break;\n }\n\n return median;\n }"
] | [
"private void revisitMessages(Definitions def) {\n List<RootElement> rootElements = def.getRootElements();\n List<ItemDefinition> toAddDefinitions = new ArrayList<ItemDefinition>();\n for (RootElement root : rootElements) {\n if (root instanceof Message) {\n if (!existsMessageItemDefinition(rootElements,\n root.getId())) {\n ItemDefinition itemdef = Bpmn2Factory.eINSTANCE.createItemDefinition();\n itemdef.setId(root.getId() + \"Type\");\n toAddDefinitions.add(itemdef);\n ((Message) root).setItemRef(itemdef);\n }\n }\n }\n for (ItemDefinition id : toAddDefinitions) {\n def.getRootElements().add(id);\n }\n }",
"@SafeVarargs\n public static <K> Set<K> set(final K... keys) {\n return new LinkedHashSet<K>(Arrays.asList(keys));\n }",
"private void doExecute(Connection conn) throws SQLException\r\n {\r\n PreparedStatement stmt;\r\n int size;\r\n\r\n size = _methods.size();\r\n if ( size == 0 )\r\n {\r\n return;\r\n }\r\n stmt = conn.prepareStatement(_sql);\r\n try\r\n {\r\n m_platform.afterStatementCreate(stmt);\r\n }\r\n catch ( PlatformException e )\r\n {\r\n if ( e.getCause() instanceof SQLException )\r\n {\r\n throw (SQLException)e.getCause();\r\n }\r\n else\r\n {\r\n throw new SQLException(e.getMessage());\r\n }\r\n }\r\n try\r\n {\r\n m_platform.beforeBatch(stmt);\r\n }\r\n catch ( PlatformException e )\r\n {\r\n if ( e.getCause() instanceof SQLException )\r\n {\r\n throw (SQLException)e.getCause();\r\n }\r\n else\r\n {\r\n throw new SQLException(e.getMessage());\r\n }\r\n }\r\n try\r\n {\r\n for ( int i = 0; i < size; i++ )\r\n {\r\n Method method = (Method) _methods.get(i);\r\n try\r\n {\r\n if ( method.equals(ADD_BATCH) )\r\n {\r\n /**\r\n * we invoke on the platform and pass the stmt as an arg.\r\n */\r\n m_platform.addBatch(stmt);\r\n }\r\n else\r\n {\r\n method.invoke(stmt, (Object[]) _params.get(i));\r\n }\r\n }\r\n catch (IllegalArgumentException ex)\r\n {\r\n\t\t\t\t\tStringBuffer buffer = generateExceptionMessage(i, stmt, ex);\r\n\t\t\t\t\tthrow new SQLException(buffer.toString());\r\n }\r\n catch ( IllegalAccessException ex )\r\n {\r\n\t\t\t\t\tStringBuffer buffer = generateExceptionMessage(i, stmt, ex);\r\n throw new SQLException(buffer.toString());\r\n }\r\n catch ( InvocationTargetException ex )\r\n {\r\n Throwable th = ex.getTargetException();\r\n\r\n if ( th == null )\r\n {\r\n th = ex;\r\n }\r\n if ( th instanceof SQLException )\r\n {\r\n throw ((SQLException) th);\r\n }\r\n else\r\n {\r\n throw new SQLException(th.toString());\r\n }\r\n }\r\n\t\t\t\tcatch (PlatformException e)\r\n\t\t\t\t{\r\n\t\t\t\t\tthrow new SQLException(e.toString());\r\n\t\t\t\t}\r\n }\r\n try\r\n {\r\n /**\r\n * this will call the platform specific call\r\n */\r\n m_platform.executeBatch(stmt);\r\n }\r\n catch ( PlatformException e )\r\n {\r\n if ( e.getCause() instanceof SQLException )\r\n {\r\n throw (SQLException)e.getCause();\r\n }\r\n else\r\n {\r\n throw new SQLException(e.getMessage());\r\n }\r\n }\r\n\r\n }\r\n finally\r\n {\r\n stmt.close();\r\n _methods.clear();\r\n _params.clear();\r\n }\r\n }",
"public void setEndTime(final Date date) {\r\n\r\n if (!Objects.equals(m_model.getEnd(), date)) {\r\n m_model.setEnd(date);\r\n valueChanged();\r\n }\r\n\r\n }",
"protected void processDeletions(CmsObject cms, List<CmsResource> toDelete) throws CmsException {\n\n Collections.sort(toDelete, (a, b) -> b.getRootPath().compareTo(a.getRootPath()));\n for (CmsResource deleteRes : toDelete) {\n m_report.print(\n org.opencms.importexport.Messages.get().container(org.opencms.importexport.Messages.RPT_DELFOLDER_0),\n I_CmsReport.FORMAT_NOTE);\n m_report.print(\n org.opencms.report.Messages.get().container(\n org.opencms.report.Messages.RPT_ARGUMENT_1,\n deleteRes.getRootPath()));\n CmsLock lock = cms.getLock(deleteRes);\n if (lock.isUnlocked()) {\n lock(cms, deleteRes);\n }\n cms.deleteResource(deleteRes, CmsResource.DELETE_PRESERVE_SIBLINGS);\n m_report.println(\n org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0),\n I_CmsReport.FORMAT_OK);\n\n }\n }",
"private Map<String, Class<? extends RulePhase>> loadPhases()\n {\n Map<String, Class<? extends RulePhase>> phases;\n phases = new HashMap<>();\n Furnace furnace = FurnaceHolder.getFurnace();\n for (RulePhase phase : furnace.getAddonRegistry().getServices(RulePhase.class))\n {\n @SuppressWarnings(\"unchecked\")\n Class<? extends RulePhase> unwrappedClass = (Class<? extends RulePhase>) Proxies.unwrap(phase).getClass();\n String simpleName = unwrappedClass.getSimpleName();\n phases.put(classNameToMapKey(simpleName), unwrappedClass);\n }\n return Collections.unmodifiableMap(phases);\n }",
"public static void parse(Reader src, StatementHandler handler)\n throws IOException {\n new NTriplesParser(src, handler).parse();\n }",
"protected void appendWhereClause(ClassDescriptor cld, boolean useLocking, StringBuffer stmt)\r\n {\r\n FieldDescriptor[] pkFields = cld.getPkFields();\r\n FieldDescriptor[] fields;\r\n\r\n fields = pkFields;\r\n if(useLocking)\r\n {\r\n FieldDescriptor[] lockingFields = cld.getLockingFields();\r\n if(lockingFields.length > 0)\r\n {\r\n fields = new FieldDescriptor[pkFields.length + lockingFields.length];\r\n System.arraycopy(pkFields, 0, fields, 0, pkFields.length);\r\n System.arraycopy(lockingFields, 0, fields, pkFields.length, lockingFields.length);\r\n }\r\n }\r\n\r\n appendWhereClause(fields, stmt);\r\n }",
"public static boolean isAvailable() throws Exception {\n try {\n Registry myRegistry = LocateRegistry.getRegistry(\"127.0.0.1\", port);\n com.groupon.odo.proxylib.hostsedit.rmi.Message impl = (com.groupon.odo.proxylib.hostsedit.rmi.Message) myRegistry.lookup(SERVICE_NAME);\n return true;\n } catch (Exception e) {\n return false;\n }\n }"
] |
if any item in toCheck is present in collection
@param <T>
@param collection
@param toCheck
@return | [
"public static <T> boolean containsAny(Collection<T> collection, Collection<T> toCheck){\r\n for(T c: toCheck){\r\n if(collection.contains(c))\r\n return true;\r\n }\r\n return false;\r\n \r\n }"
] | [
"private FullTypeSignature getTypeSignature(Class<?> clazz) {\r\n\t\tStringBuilder sb = new StringBuilder();\r\n\t\tif (clazz.isArray()) {\r\n\t\t\tsb.append(clazz.getName());\r\n\t\t} else if (clazz.isPrimitive()) {\r\n\t\t\tsb.append(primitiveTypesMap.get(clazz).toString());\r\n\t\t} else {\r\n\t\t\tsb.append('L').append(clazz.getName()).append(';');\r\n\t\t}\r\n\t\treturn TypeSignatureFactory.getTypeSignature(sb.toString(), false);\r\n\r\n\t}",
"public static String encodeScheme(String scheme, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(scheme, encoding, HierarchicalUriComponents.Type.SCHEME);\n\t}",
"protected List<TransformationDescription> buildChildren() {\n if(children.isEmpty()) {\n return Collections.emptyList();\n }\n final List<TransformationDescription> children = new ArrayList<TransformationDescription>();\n for(final TransformationDescriptionBuilder builder : this.children) {\n children.add(builder.build());\n }\n return children;\n }",
"@Override\n public void onDismiss(DialogInterface dialog) {\n if (mOldDialog != null && mOldDialog == dialog) {\n // This is the callback from the old progress dialog that was already dismissed before\n // the device orientation change, so just ignore it.\n return;\n }\n super.onDismiss(dialog);\n }",
"public static ServiceActivator create(final ModelNode endpointConfig, final URI managementURI, final String serverName, final String serverProcessName,\n final String authKey, final boolean managementSubsystemEndpoint, final Supplier<SSLContext> sslContextSupplier) {\n\n return new DomainServerCommunicationServices(endpointConfig, managementURI, serverName, serverProcessName, authKey, managementSubsystemEndpoint, sslContextSupplier);\n }",
"private DecompilerSettings getDefaultSettings(File outputDir)\n {\n DecompilerSettings settings = new DecompilerSettings();\n procyonConf.setDecompilerSettings(settings);\n settings.setOutputDirectory(outputDir.getPath());\n settings.setShowSyntheticMembers(false);\n settings.setForceExplicitImports(true);\n\n if (settings.getTypeLoader() == null)\n settings.setTypeLoader(new ClasspathTypeLoader());\n return settings;\n }",
"public int getVersion() {\n ResultSet resultSet = session.execute(format(VERSION_QUERY, getTableName()));\n Row result = resultSet.one();\n if (result == null) {\n return 0;\n }\n return result.getInt(0);\n }",
"private void writeAssignments()\n {\n for (ResourceAssignment assignment : m_projectFile.getResourceAssignments())\n {\n Resource resource = assignment.getResource();\n if (resource != null)\n {\n Task task = assignment.getTask();\n if (task != null && task.getUniqueID().intValue() != 0 && !task.getSummary())\n {\n writeAssignment(assignment);\n }\n }\n }\n }",
"public List<T> nextPermutationAsList()\n {\n List<T> permutation = new ArrayList<T>(elements.length);\n return nextPermutationAsList(permutation);\n }"
] |
Get the sub registry for the domain.
@param range the version range
@return the sub registry | [
"public TransformersSubRegistration getDomainRegistration(final ModelVersionRange range) {\n final PathAddress address = PathAddress.EMPTY_ADDRESS;\n return new TransformersSubRegistrationImpl(range, domain, address);\n }"
] | [
"private static OkHttpClient getUnsafeOkHttpClient() {\n try {\n // Create a trust manager that does not validate certificate chains\n final TrustManager[] trustAllCerts = new TrustManager[] {\n new X509TrustManager() {\n @Override\n public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n @Override\n public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n @Override\n public java.security.cert.X509Certificate[] getAcceptedIssuers() {\n return null;\n }\n }\n };\n\n // Install the all-trusting trust manager\n final SSLContext sslContext = SSLContext.getInstance(\"SSL\");\n sslContext.init(null, trustAllCerts, new java.security.SecureRandom());\n // Create an ssl socket factory with our all-trusting manager\n final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();\n\n OkHttpClient okHttpClient = new OkHttpClient();\n okHttpClient.setSslSocketFactory(sslSocketFactory);\n okHttpClient.setHostnameVerifier(new HostnameVerifier() {\n @Override\n public boolean verify(String hostname, SSLSession session) {\n return true;\n }\n });\n\n return okHttpClient;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }",
"@Nonnull\n private ReferencedEnvelope getFeatureBounds(\n final MfClientHttpRequestFactory clientHttpRequestFactory,\n final MapAttributeValues mapValues, final ExecutionContext context) {\n final MapfishMapContext mapContext = createMapContext(mapValues);\n\n String layerName = mapValues.zoomToFeatures.layer;\n ReferencedEnvelope bounds = new ReferencedEnvelope();\n for (MapLayer layer: mapValues.getLayers()) {\n context.stopIfCanceled();\n\n if ((!StringUtils.isEmpty(layerName) && layerName.equals(layer.getName())) ||\n (StringUtils.isEmpty(layerName) && layer instanceof AbstractFeatureSourceLayer)) {\n AbstractFeatureSourceLayer featureLayer = (AbstractFeatureSourceLayer) layer;\n FeatureSource<?, ?> featureSource =\n featureLayer.getFeatureSource(clientHttpRequestFactory, mapContext);\n FeatureCollection<?, ?> features;\n try {\n features = featureSource.getFeatures();\n } catch (IOException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n\n if (!features.isEmpty()) {\n final ReferencedEnvelope curBounds = features.getBounds();\n bounds.expandToInclude(curBounds);\n }\n }\n }\n\n return bounds;\n }",
"void createDirectory(Path path) throws IOException {\n\t\tif (Files.exists(path) && Files.isDirectory(path)) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.readOnly) {\n\t\t\tthrow new FileNotFoundException(\n\t\t\t\t\t\"The requested directory \\\"\"\n\t\t\t\t\t\t\t+ path.toString()\n\t\t\t\t\t\t\t+ \"\\\" does not exist and we are in read-only mode, so it cannot be created.\");\n\t\t}\n\n\t\tFiles.createDirectory(path);\n\t}",
"private void CalculateMap(IntRange inRange, IntRange outRange, int[] map) {\r\n double k = 0, b = 0;\r\n\r\n if (inRange.getMax() != inRange.getMin()) {\r\n k = (double) (outRange.getMax() - outRange.getMin()) / (double) (inRange.getMax() - inRange.getMin());\r\n b = (double) (outRange.getMin()) - k * inRange.getMin();\r\n }\r\n\r\n for (int i = 0; i < 256; i++) {\r\n int v = (int) i;\r\n\r\n if (v >= inRange.getMax())\r\n v = outRange.getMax();\r\n else if (v <= inRange.getMin())\r\n v = outRange.getMin();\r\n else\r\n v = (int) (k * v + b);\r\n\r\n map[i] = v;\r\n }\r\n }",
"public static cmpparameter get(nitro_service service) throws Exception{\n\t\tcmpparameter obj = new cmpparameter();\n\t\tcmpparameter[] response = (cmpparameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"@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 void hide() {\n div.removeFromParent();\n if (scrollDisabled) {\n RootPanel.get().getElement().getStyle().setOverflow(Style.Overflow.AUTO);\n }\n if (type == LoaderType.CIRCULAR) {\n preLoader.removeFromParent();\n } else if (type == LoaderType.PROGRESS) {\n progress.removeFromParent();\n }\n }",
"protected void checkObserverMethods() {\n Collection<EnhancedAnnotatedMethod<?, ? super T>> observerMethods = BeanMethods.getObserverMethods(this.getEnhancedAnnotated());\n Collection<EnhancedAnnotatedMethod<?, ? super T>> asyncObserverMethods = BeanMethods.getAsyncObserverMethods(this.getEnhancedAnnotated());\n checkObserverMethods(observerMethods);\n checkObserverMethods(asyncObserverMethods);\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<Symmetry454Date> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<Symmetry454Date>) super.localDateTime(temporal);\n }"
] |
Set the rate types.
@param rateTypes the rate types, not null and not empty.
@return this, for chaining.
@throws IllegalArgumentException when not at least one {@link RateType} is provided. | [
"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 }"
] | [
"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 String getProperty(String key, String defaultValue) {\n return mProperties.getProperty(key, defaultValue);\n }",
"public static String toJson(Calendar cal) {\n if (cal == null) {\n return NULL_VALUE;\n }\n\n CharBuf buffer = CharBuf.create(26);\n writeDate(cal.getTime(), buffer);\n\n return buffer.toString();\n }",
"private String formatTime(Date value)\n {\n return (value == null ? null : m_formats.getTimeFormat().format(value));\n }",
"public Integer getTextureMagFilter(AiTextureType type, int index) {\n checkTexRange(type, index);\n\n Property p = getProperty(PropertyKey.TEX_MAG_FILTER.m_key);\n\n if (null == p || null == p.getData()) {\n return (Integer) m_defaults.get(PropertyKey.TEX_MAG_FILTER);\n }\n Object rawValue = p.getData();\n if (rawValue instanceof java.nio.ByteBuffer)\n {\n java.nio.IntBuffer ibuf = ((java.nio.ByteBuffer) rawValue).asIntBuffer();\n return ibuf.get();\n }\n else\n {\n return (Integer) rawValue;\n }\n }",
"public final void setColorPreferred(boolean preferColor) {\n if (this.preferColor.compareAndSet(!preferColor, preferColor) && isRunning()) {\n stop();\n try {\n start();\n } catch (Exception e) {\n logger.error(\"Unexplained exception restarting; we had been running already!\", e);\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}",
"@Override\n public final int getInt(final int i) {\n int val = this.array.optInt(i, Integer.MIN_VALUE);\n if (val == Integer.MIN_VALUE) {\n throw new ObjectMissingException(this, \"[\" + i + \"]\");\n }\n return val;\n }",
"public EventBus emitSync(String event, Object... args) {\n return _emitWithOnceBus(eventContextSync(event, args));\n }"
] |
Parse rate.
@param value rate value
@return Rate instance | [
"public static final Rate parseRate(BigDecimal value)\n {\n Rate result = null;\n\n if (value != null)\n {\n result = new Rate(value, TimeUnit.HOURS);\n }\n\n return (result);\n }"
] | [
"public static base_response update(nitro_service client, gslbsite resource) throws Exception {\n\t\tgslbsite updateresource = new gslbsite();\n\t\tupdateresource.sitename = resource.sitename;\n\t\tupdateresource.metricexchange = resource.metricexchange;\n\t\tupdateresource.nwmetricexchange = resource.nwmetricexchange;\n\t\tupdateresource.sessionexchange = resource.sessionexchange;\n\t\tupdateresource.triggermonitor = resource.triggermonitor;\n\t\treturn updateresource.update_resource(client);\n\t}",
"ArgumentsBuilder param(String param, Integer value) {\n if (value != null) {\n args.add(param);\n args.add(value.toString());\n }\n return this;\n }",
"private boolean shouldIgnore(String typeReference)\n {\n typeReference = typeReference.replace('/', '.').replace('\\\\', '.');\n return JavaClassIgnoreResolver.singletonInstance().matches(typeReference);\n }",
"public void setTargetBytecode(String version) {\n if (CompilerConfiguration.PRE_JDK5.equals(version) || CompilerConfiguration.POST_JDK5.equals(version)) {\n this.targetBytecode = version;\n }\n }",
"@SuppressWarnings(\"unchecked\")\n private void setProxyRequestHeaders(HttpServletRequest httpServletRequest,\n HttpMethod httpMethodProxyRequest) throws Exception {\n RequestInformation requestInfo = requestInformation.get();\n String hostName = HttpUtilities.getHostNameFromURL(httpServletRequest.getRequestURL().toString());\n // Get an Enumeration of all of the header names sent by the client\n Boolean stripTransferEncoding = false;\n Enumeration<String> enumerationOfHeaderNames = httpServletRequest.getHeaderNames();\n while (enumerationOfHeaderNames.hasMoreElements()) {\n String stringHeaderName = enumerationOfHeaderNames.nextElement();\n if (stringHeaderName.equalsIgnoreCase(STRING_CONTENT_LENGTH_HEADER_NAME)) {\n // don't add this header\n continue;\n }\n\n // The forwarding proxy may supply a POST encoding hint in ODO-POST-TYPE\n if (stringHeaderName.equalsIgnoreCase(\"ODO-POST-TYPE\") &&\n httpServletRequest.getHeader(\"ODO-POST-TYPE\").startsWith(\"content-length:\")) {\n stripTransferEncoding = true;\n }\n\n logger.info(\"Current header: {}\", stringHeaderName);\n // As per the Java Servlet API 2.5 documentation:\n // Some headers, such as Accept-Language can be sent by clients\n // as several headers each with a different value rather than\n // sending the header as a comma separated list.\n // Thus, we get an Enumeration of the header values sent by the\n // client\n Enumeration<String> enumerationOfHeaderValues = httpServletRequest.getHeaders(stringHeaderName);\n\n while (enumerationOfHeaderValues.hasMoreElements()) {\n String stringHeaderValue = enumerationOfHeaderValues.nextElement();\n // In case the proxy host is running multiple virtual servers,\n // rewrite the Host header to ensure that we get content from\n // the correct virtual server\n if (stringHeaderName.equalsIgnoreCase(STRING_HOST_HEADER_NAME) &&\n requestInfo.handle) {\n String hostValue = getHostHeaderForHost(hostName);\n if (hostValue != null) {\n stringHeaderValue = hostValue;\n }\n }\n\n Header header = new Header(stringHeaderName, stringHeaderValue);\n // Set the same header on the proxy request\n httpMethodProxyRequest.addRequestHeader(header);\n }\n }\n\n // this strips transfer encoding headers and adds in the appropriate content-length header\n // based on the hint provided in the ODO-POST-TYPE header(sent from BrowserMobProxyHandler)\n if (stripTransferEncoding) {\n httpMethodProxyRequest.removeRequestHeader(\"transfer-encoding\");\n\n // add content length back in based on the ODO information\n String contentLengthHint = httpServletRequest.getHeader(\"ODO-POST-TYPE\");\n String[] contentLengthParts = contentLengthHint.split(\":\");\n httpMethodProxyRequest.addRequestHeader(\"content-length\", contentLengthParts[1]);\n\n // remove the odo-post-type header\n httpMethodProxyRequest.removeRequestHeader(\"ODO-POST-TYPE\");\n }\n\n // bail if we aren't fully handling this request\n if (!requestInfo.handle) {\n return;\n }\n\n // deal with header overrides for the request\n processRequestHeaderOverrides(httpMethodProxyRequest);\n }",
"private void readResourceExtendedAttributes(Project.Resources.Resource xml, Resource mpx)\n {\n for (Project.Resources.Resource.ExtendedAttribute attrib : xml.getExtendedAttribute())\n {\n int xmlFieldID = Integer.parseInt(attrib.getFieldID()) & 0x0000FFFF;\n ResourceField mpxFieldID = MPPResourceField.getInstance(xmlFieldID);\n TimeUnit durationFormat = DatatypeConverter.parseDurationTimeUnits(attrib.getDurationFormat(), null);\n DatatypeConverter.parseExtendedAttribute(m_projectFile, mpx, attrib.getValue(), mpxFieldID, durationFormat);\n }\n }",
"public void setIntegerAttribute(String name, Integer value) {\n\t\tensureValue();\n\t\tAttribute attribute = new IntegerAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetValue().getAllAttributes().put(name, attribute);\n\t}",
"public static void addActionsTo(\n SourceBuilder code,\n Set<MergeAction> mergeActions,\n boolean forBuilder) {\n SetMultimap<String, String> nounsByVerb = TreeMultimap.create();\n mergeActions.forEach(mergeAction -> {\n if (forBuilder || !mergeAction.builderOnly) {\n nounsByVerb.put(mergeAction.verb, mergeAction.noun);\n }\n });\n List<String> verbs = ImmutableList.copyOf(nounsByVerb.keySet());\n String lastVerb = getLast(verbs, null);\n for (String verb : nounsByVerb.keySet()) {\n code.add(\", %s%s\", (verbs.size() > 1 && verb.equals(lastVerb)) ? \"and \" : \"\", verb);\n List<String> nouns = ImmutableList.copyOf(nounsByVerb.get(verb));\n for (int i = 0; i < nouns.size(); ++i) {\n String separator = (i == 0) ? \"\" : (i == nouns.size() - 1) ? \" and\" : \",\";\n code.add(\"%s %s\", separator, nouns.get(i));\n }\n }\n }",
"public void writeLine(String pattern, Object... parameters) {\n String line = (parameters == null || parameters.length == 0) ? pattern\n : String.format(pattern, parameters);\n lines.add(0, line); // we'll write bottom to top, then purge unwritten\n // lines from end\n updateHUD();\n }"
] |
Gets the final transform of the bone.
@return the 4x4 matrix representing the final transform of the
bone during animation, which comprises bind pose and skeletal
transform at the current time of the animation. | [
"public Matrix4f getFinalTransformMatrix()\n {\n final FloatBuffer fb = ByteBuffer.allocateDirect(4*4*4).order(ByteOrder.nativeOrder()).asFloatBuffer();\n NativeBone.getFinalTransformMatrix(getNative(), fb);\n return new Matrix4f(fb);\n }"
] | [
"public static appfwprofile_xmlvalidationurl_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_xmlvalidationurl_binding obj = new appfwprofile_xmlvalidationurl_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_xmlvalidationurl_binding response[] = (appfwprofile_xmlvalidationurl_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void writeCostRateTables(Project.Resources.Resource xml, Resource mpx)\n {\n //Rates rates = m_factory.createProjectResourcesResourceRates();\n //xml.setRates(rates);\n //List<Project.Resources.Resource.Rates.Rate> ratesList = rates.getRate();\n\n List<Project.Resources.Resource.Rates.Rate> ratesList = null;\n\n for (int tableIndex = 0; tableIndex < 5; tableIndex++)\n {\n CostRateTable table = mpx.getCostRateTable(tableIndex);\n if (table != null)\n {\n Date from = DateHelper.FIRST_DATE;\n for (CostRateTableEntry entry : table)\n {\n if (costRateTableWriteRequired(entry, from))\n {\n if (ratesList == null)\n {\n Rates rates = m_factory.createProjectResourcesResourceRates();\n xml.setRates(rates);\n ratesList = rates.getRate();\n }\n\n Project.Resources.Resource.Rates.Rate rate = m_factory.createProjectResourcesResourceRatesRate();\n ratesList.add(rate);\n\n rate.setCostPerUse(DatatypeConverter.printCurrency(entry.getCostPerUse()));\n rate.setOvertimeRate(DatatypeConverter.printRate(entry.getOvertimeRate()));\n rate.setOvertimeRateFormat(DatatypeConverter.printTimeUnit(entry.getOvertimeRateFormat()));\n rate.setRatesFrom(from);\n from = entry.getEndDate();\n rate.setRatesTo(from);\n rate.setRateTable(BigInteger.valueOf(tableIndex));\n rate.setStandardRate(DatatypeConverter.printRate(entry.getStandardRate()));\n rate.setStandardRateFormat(DatatypeConverter.printTimeUnit(entry.getStandardRateFormat()));\n }\n }\n }\n }\n }",
"protected void updatePicker(MotionEvent event, boolean isActive)\n {\n final MotionEvent newEvent = (event != null) ? event : null;\n final ControllerPick controllerPick = new ControllerPick(mPicker, newEvent, isActive);\n context.runOnGlThread(controllerPick);\n }",
"public static void sqrt(Complex_F64 input, Complex_F64 root)\n {\n double r = input.getMagnitude();\n double a = input.real;\n\n root.real = Math.sqrt((r+a)/2.0);\n root.imaginary = Math.sqrt((r-a)/2.0);\n if( input.imaginary < 0 )\n root.imaginary = -root.imaginary;\n }",
"public void actionPerformed(java.awt.event.ActionEvent actionEvent)\r\n {\r\n new Thread()\r\n {\r\n public void run()\r\n {\r\n final java.sql.Connection conn = new JDlgDBConnection(containingFrame, false).showAndReturnConnection();\r\n if (conn != null)\r\n {\r\n javax.swing.SwingUtilities.invokeLater(new Runnable()\r\n {\r\n public void run()\r\n {\r\n JIFrmDatabase frm = new JIFrmDatabase(conn);\r\n containingFrame.getContentPane().add(frm);\r\n frm.setVisible(true);\r\n }\r\n });\r\n }\r\n }\r\n }.start();\r\n }",
"public static final Integer getInteger(String value)\n {\n Integer result;\n\n try\n {\n result = Integer.valueOf(Integer.parseInt(value));\n }\n\n catch (Exception ex)\n {\n result = null;\n }\n\n return (result);\n }",
"public void writeNameValuePair(String name, String value) throws IOException\n {\n internalWriteNameValuePair(name, escapeString(value));\n }",
"public void setDividerPadding(float padding, final Axis axis) {\n if (axis == getOrientationAxis()) {\n super.setDividerPadding(padding, axis);\n } else {\n Log.w(TAG, \"Cannot apply divider padding for wrong axis [%s], orientation = %s\",\n axis, getOrientation());\n }\n }",
"public ManageableCollection getCollectionByQuery(Class collectionClass, Query query)\n throws PersistenceBrokerException\n {\n return referencesBroker.getCollectionByQuery(collectionClass, query, false);\n }"
] |
Init the bundle type member variable.
@return the bundle type of the opened resource. | [
"private CmsMessageBundleEditorTypes.BundleType initBundleType() {\n\n String resourceTypeName = OpenCms.getResourceManager().getResourceType(m_resource).getTypeName();\n return CmsMessageBundleEditorTypes.BundleType.toBundleType(resourceTypeName);\n }"
] | [
"private ProjectFile handleZipFile(InputStream stream) throws Exception\n {\n File dir = null;\n\n try\n {\n dir = InputStreamHelper.writeZipStreamToTempDir(stream);\n ProjectFile result = handleDirectory(dir);\n if (result != null)\n {\n return result;\n }\n }\n\n finally\n {\n FileHelper.deleteQuietly(dir);\n }\n\n return null;\n }",
"public static void checkVectorAddition() {\n DoubleMatrix x = new DoubleMatrix(3, 1, 1.0, 2.0, 3.0);\n DoubleMatrix y = new DoubleMatrix(3, 1, 4.0, 5.0, 6.0);\n DoubleMatrix z = new DoubleMatrix(3, 1, 5.0, 7.0, 9.0);\n\n check(\"checking vector addition\", x.add(y).equals(z));\n }",
"public User getLimits() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIMITS);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element userElement = response.getPayload();\r\n User user = new User();\r\n user.setId(userElement.getAttribute(\"nsid\"));\r\n NodeList photoNodes = userElement.getElementsByTagName(\"photos\");\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element plElement = (Element) photoNodes.item(i);\r\n PhotoLimits pl = new PhotoLimits();\r\n user.setPhotoLimits(pl);\r\n pl.setMaxDisplay(plElement.getAttribute(\"maxdisplaypx\"));\r\n pl.setMaxUpload(plElement.getAttribute(\"maxupload\"));\r\n }\r\n NodeList videoNodes = userElement.getElementsByTagName(\"videos\");\r\n for (int i = 0; i < videoNodes.getLength(); i++) {\r\n Element vlElement = (Element) videoNodes.item(i);\r\n VideoLimits vl = new VideoLimits();\r\n user.setPhotoLimits(vl);\r\n vl.setMaxDuration(vlElement.getAttribute(\"maxduration\"));\r\n vl.setMaxUpload(vlElement.getAttribute(\"maxupload\"));\r\n }\r\n return user;\r\n }",
"public void authenticate(String authCode) {\n URL url = null;\n try {\n url = new URL(this.tokenURL);\n } catch (MalformedURLException e) {\n assert false : \"An invalid token URL indicates a bug in the SDK.\";\n throw new RuntimeException(\"An invalid token URL indicates a bug in the SDK.\", e);\n }\n\n String urlParameters = String.format(\"grant_type=authorization_code&code=%s&client_id=%s&client_secret=%s\",\n authCode, this.clientID, this.clientSecret);\n\n BoxAPIRequest request = new BoxAPIRequest(this, url, \"POST\");\n request.shouldAuthenticate(false);\n request.setBody(urlParameters);\n\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n String json = response.getJSON();\n\n JsonObject jsonObject = JsonObject.readFrom(json);\n this.accessToken = jsonObject.get(\"access_token\").asString();\n this.refreshToken = jsonObject.get(\"refresh_token\").asString();\n this.lastRefresh = System.currentTimeMillis();\n this.expires = jsonObject.get(\"expires_in\").asLong() * 1000;\n }",
"public String computeTrackSignature(final String title, final SearchableItem artist, final int duration,\n final WaveformDetail waveformDetail, final BeatGrid beatGrid) {\n final String safeTitle = (title == null)? \"\" : title;\n final String artistName = (artist == null)? \"[no artist]\" : artist.label;\n try {\n // Compute the SHA-1 hash of our fields\n MessageDigest digest = MessageDigest.getInstance(\"SHA1\");\n digest.update(safeTitle.getBytes(\"UTF-8\"));\n digest.update((byte) 0);\n digest.update(artistName.getBytes(\"UTF-8\"));\n digest.update((byte) 0);\n digestInteger(digest, duration);\n digest.update(waveformDetail.getData());\n for (int i = 1; i <= beatGrid.beatCount; i++) {\n digestInteger(digest, beatGrid.getBeatWithinBar(i));\n digestInteger(digest, (int)beatGrid.getTimeWithinTrack(i));\n }\n byte[] result = digest.digest();\n\n // Create a hex string representation of the hash\n StringBuilder hex = new StringBuilder(result.length * 2);\n for (byte aResult : result) {\n hex.append(Integer.toString((aResult & 0xff) + 0x100, 16).substring(1));\n }\n\n return hex.toString();\n\n } catch (NullPointerException e) {\n logger.info(\"Returning null track signature because an input element was null.\", e);\n } catch (NoSuchAlgorithmException e) {\n logger.error(\"Unable to obtain SHA-1 MessageDigest instance for computing track signatures.\", e);\n } catch (UnsupportedEncodingException e) {\n logger.error(\"Unable to work with UTF-8 string encoding for computing track signatures.\", e);\n }\n return null; // We were unable to compute a signature\n }",
"private void checkAnonymous(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 access = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_ACCESS);\r\n\r\n if (!\"anonymous\".equals(access))\r\n {\r\n throw new ConstraintException(\"The access property of the field \"+fieldDef.getName()+\" defined in class \"+fieldDef.getOwner().getName()+\" cannot be changed\");\r\n }\r\n\r\n if ((fieldDef.getName() == null) || (fieldDef.getName().length() == 0))\r\n {\r\n throw new ConstraintException(\"An anonymous field defined in class \"+fieldDef.getOwner().getName()+\" has no name\");\r\n }\r\n }",
"protected Collection loadData() throws PersistenceBrokerException\r\n {\r\n PersistenceBroker broker = getBroker();\r\n try\r\n {\r\n Collection result;\r\n\r\n if (_data != null) // could be set by listener\r\n {\r\n result = _data;\r\n }\r\n else if (_size != 0)\r\n {\r\n // TODO: returned ManageableCollection should extend Collection to avoid\r\n // this cast\r\n result = (Collection) broker.getCollectionByQuery(getCollectionClass(), getQuery());\r\n }\r\n else\r\n {\r\n result = (Collection)getCollectionClass().newInstance();\r\n }\r\n return result;\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new PersistenceBrokerException(ex);\r\n }\r\n finally\r\n {\r\n releaseBroker(broker);\r\n }\r\n }",
"public boolean putAtomic(C instance, K key, V value, Map<K, V> snapshot) {\n Assert.checkNotNullParam(\"key\", key);\n final Map<K, V> newMap;\n final int oldSize = snapshot.size();\n if (oldSize == 0) {\n newMap = Collections.singletonMap(key, value);\n } else if (oldSize == 1) {\n final Map.Entry<K, V> entry = snapshot.entrySet().iterator().next();\n final K oldKey = entry.getKey();\n if (oldKey.equals(key)) {\n return false;\n } else {\n newMap = new FastCopyHashMap<K, V>(snapshot);\n newMap.put(key, value);\n }\n } else {\n newMap = new FastCopyHashMap<K, V>(snapshot);\n newMap.put(key, value);\n }\n return updater.compareAndSet(instance, snapshot, newMap);\n }",
"@RequestMapping(value = \"/api/profile\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getList(Model model) throws Exception {\n logger.info(\"Using a GET request to list profiles\");\n return Utils.getJQGridJSON(profileService.findAllProfiles(), \"profiles\");\n }"
] |
Triggers collapse of the parent. | [
"@UiThread\n protected void collapseView() {\n setExpanded(false);\n onExpansionToggled(true);\n\n if (mParentViewHolderExpandCollapseListener != null) {\n mParentViewHolderExpandCollapseListener.onParentCollapsed(getAdapterPosition());\n }\n }"
] | [
"private void createAndLockDescriptorFile() throws CmsException {\n\n String sitePath = m_sitepath + m_basename + CmsMessageBundleEditorTypes.Descriptor.POSTFIX;\n m_desc = m_cms.createResource(\n sitePath,\n OpenCms.getResourceManager().getResourceType(CmsMessageBundleEditorTypes.BundleType.DESCRIPTOR.toString()));\n m_descFile = LockedFile.lockResource(m_cms, m_desc);\n m_descFile.setCreated(true);\n }",
"public CompletableFuture<Void> stop() {\n numPendingStopRequests.incrementAndGet();\n return startStop.stop().thenRun(numPendingStopRequests::decrementAndGet);\n }",
"private InputStream getErrorStream() {\n InputStream errorStream = this.connection.getErrorStream();\n if (errorStream != null) {\n final String contentEncoding = this.connection.getContentEncoding();\n if (contentEncoding != null && contentEncoding.equalsIgnoreCase(\"gzip\")) {\n try {\n errorStream = new GZIPInputStream(errorStream);\n } catch (IOException e) {\n // just return the error stream as is\n }\n }\n }\n\n return errorStream;\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 }",
"private ColorItem buildColorItem(int colorId, String label) {\n Color color;\n String colorName;\n switch (colorId) {\n case 0:\n color = new Color(0, 0, 0, 0);\n colorName = \"No Color\";\n break;\n case 1:\n color = Color.PINK;\n colorName = \"Pink\";\n break;\n case 2:\n color = Color.RED;\n colorName = \"Red\";\n break;\n case 3:\n color = Color.ORANGE;\n colorName = \"Orange\";\n break;\n case 4:\n color = Color.YELLOW;\n colorName = \"Yellow\";\n break;\n case 5:\n color = Color.GREEN;\n colorName = \"Green\";\n break;\n case 6:\n color = Color.CYAN;\n colorName = \"Aqua\";\n break;\n case 7:\n color = Color.BLUE;\n colorName = \"Blue\";\n break;\n case 8:\n color = new Color(128, 0, 128);\n colorName = \"Purple\";\n break;\n default:\n color = new Color(0, 0, 0, 0);\n colorName = \"Unknown Color\";\n }\n return new ColorItem(colorId, label, color, colorName);\n }",
"public void setVec3(String key, float x, float y, float z)\n {\n checkKeyIsUniform(key);\n NativeLight.setVec3(getNative(), key, x, y, z);\n }",
"public static Bitmap flip(Bitmap src) {\n Matrix m = new Matrix();\n m.preScale(-1, 1);\n return Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), m, false);\n }",
"private void writeCalendar(ProjectCalendar mpxjCalendar, net.sf.mpxj.planner.schema.Calendar plannerCalendar) throws JAXBException\n {\n //\n // Populate basic details\n //\n plannerCalendar.setId(getIntegerString(mpxjCalendar.getUniqueID()));\n plannerCalendar.setName(getString(mpxjCalendar.getName()));\n\n //\n // Set working and non working days\n //\n DefaultWeek dw = m_factory.createDefaultWeek();\n plannerCalendar.setDefaultWeek(dw);\n dw.setMon(getWorkingDayString(mpxjCalendar, Day.MONDAY));\n dw.setTue(getWorkingDayString(mpxjCalendar, Day.TUESDAY));\n dw.setWed(getWorkingDayString(mpxjCalendar, Day.WEDNESDAY));\n dw.setThu(getWorkingDayString(mpxjCalendar, Day.THURSDAY));\n dw.setFri(getWorkingDayString(mpxjCalendar, Day.FRIDAY));\n dw.setSat(getWorkingDayString(mpxjCalendar, Day.SATURDAY));\n dw.setSun(getWorkingDayString(mpxjCalendar, Day.SUNDAY));\n\n //\n // Set working hours\n //\n OverriddenDayTypes odt = m_factory.createOverriddenDayTypes();\n plannerCalendar.setOverriddenDayTypes(odt);\n List<OverriddenDayType> typeList = odt.getOverriddenDayType();\n Sequence uniqueID = new Sequence(0);\n\n //\n // This is a bit arbitrary, so not ideal, however...\n // The idea here is that MS Project allows us to specify working hours\n // for each day of the week individually. Planner doesn't do this,\n // but instead allows us to specify working hours for each day type.\n // What we are doing here is stepping through the days of the week to\n // find the first working day, then using the hours for that day\n // as the hours for the working day type in Planner.\n //\n for (int dayLoop = 1; dayLoop < 8; dayLoop++)\n {\n Day day = Day.getInstance(dayLoop);\n if (mpxjCalendar.isWorkingDay(day))\n {\n processWorkingHours(mpxjCalendar, uniqueID, day, typeList);\n break;\n }\n }\n\n //\n // Process exception days\n //\n Days plannerDays = m_factory.createDays();\n plannerCalendar.setDays(plannerDays);\n List<net.sf.mpxj.planner.schema.Day> dayList = plannerDays.getDay();\n processExceptionDays(mpxjCalendar, dayList);\n\n m_eventManager.fireCalendarWrittenEvent(mpxjCalendar);\n\n //\n // Process any derived calendars\n //\n List<net.sf.mpxj.planner.schema.Calendar> calendarList = plannerCalendar.getCalendar();\n\n for (ProjectCalendar mpxjDerivedCalendar : mpxjCalendar.getDerivedCalendars())\n {\n net.sf.mpxj.planner.schema.Calendar plannerDerivedCalendar = m_factory.createCalendar();\n calendarList.add(plannerDerivedCalendar);\n writeCalendar(mpxjDerivedCalendar, plannerDerivedCalendar);\n }\n }",
"protected void debugLog(String operationType, Long receivedTimeInMs) {\n long durationInMs = receivedTimeInMs - (this.parsedRequestOriginTimeInMs);\n int numVectorClockEntries = (this.parsedVectorClock == null ? 0\n : this.parsedVectorClock.getVersionMap()\n .size());\n logger.debug(\"Received a new request. Operation type: \" + operationType + \" , Key(s): \"\n + keysHexString(this.parsedKeys) + \" , Store: \" + this.storeName\n + \" , Origin time (in ms): \" + (this.parsedRequestOriginTimeInMs)\n + \" , Request received at time(in ms): \" + receivedTimeInMs\n + \" , Num vector clock entries: \" + numVectorClockEntries\n + \" , Duration from RESTClient to CoordinatorRestRequestValidator(in ms): \"\n + durationInMs);\n\n }"
] |
Retrieve the version number | [
"@Override\n\tpublic Object getCurrentVersion(Serializable id, SharedSessionContractImplementor session) throws HibernateException {\n\n\t\tif ( log.isTraceEnabled() ) {\n\t\t\tlog.trace( \"Getting version: \" + MessageHelper.infoString( this, id, getFactory() ) );\n\t\t}\n\t\tfinal Tuple resultset = getFreshTuple( EntityKeyBuilder.fromPersister( this, id, session ), session );\n\n\t\tif ( resultset == null ) {\n\t\t\treturn null;\n\t\t}\n\t\telse {\n\t\t\treturn gridVersionType.nullSafeGet( resultset, getVersionColumnName(), session, null );\n\t\t}\n\t}"
] | [
"public ParallelTaskBuilder prepareHttpDelete(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n\n cb.getHttpMeta().setHttpMethod(HttpMethod.DELETE);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\n }",
"public static void setField(Object object, String field, Object value) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {\n\t\tClass<?> clazz = object.getClass();\n\t\tMethod m = clazz.getMethod( PROPERTY_ACCESSOR_PREFIX_SET + capitalize( field ), value.getClass() );\n\t\tm.invoke( object, value );\n\t}",
"private void printStatistics(UsageStatistics usageStatistics,\n\t\t\tString entityLabel) {\n\t\tSystem.out.println(\"Processed \" + usageStatistics.count + \" \"\n\t\t\t\t+ entityLabel + \":\");\n\t\tSystem.out.println(\" * Labels: \" + usageStatistics.countLabels\n\t\t\t\t+ \", descriptions: \" + usageStatistics.countDescriptions\n\t\t\t\t+ \", aliases: \" + usageStatistics.countAliases);\n\t\tSystem.out.println(\" * Statements: \" + usageStatistics.countStatements\n\t\t\t\t+ \", with references: \"\n\t\t\t\t+ usageStatistics.countReferencedStatements);\n\t}",
"public static String encodePathSegment(String segment, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(segment, encoding, HierarchicalUriComponents.Type.PATH_SEGMENT);\n\t}",
"public static linkset[] get(nitro_service service) throws Exception{\n\t\tlinkset obj = new linkset();\n\t\tlinkset[] response = (linkset[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"private String getProject(CmsObject cms, CmsFavoriteEntry entry) throws CmsException {\n\n String result = m_projectLabels.get(entry.getProjectId());\n if (result == null) {\n result = cms.readProject(entry.getProjectId()).getName();\n m_projectLabels.put(entry.getProjectId(), result);\n }\n return result;\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 static final BigInteger printDurationInIntegerTenthsOfMinutes(Duration duration)\n {\n BigInteger result = null;\n\n if (duration != null && duration.getDuration() != 0)\n {\n result = BigInteger.valueOf((long) printDurationFractionsOfMinutes(duration, 10));\n }\n\n return result;\n }",
"public static String taskListToString(List<RebalanceTaskInfo> infos) {\n StringBuffer sb = new StringBuffer();\n for (RebalanceTaskInfo info : infos) {\n sb.append(\"\\t\").append(info.getDonorId()).append(\" -> \").append(info.getStealerId()).append(\" : [\");\n for (String storeName : info.getPartitionStores()) {\n sb.append(\"{\").append(storeName).append(\" : \").append(info.getPartitionIds(storeName)).append(\"}\");\n }\n sb.append(\"]\").append(Utils.NEWLINE);\n }\n return sb.toString();\n }"
] |
Returns a button component. On click, it triggers adding a bundle descriptor.
@return a button for adding a descriptor to a bundle. | [
"@SuppressWarnings(\"serial\")\n private Component createAddDescriptorButton() {\n\n Button addDescriptorButton = CmsToolBar.createButton(\n FontOpenCms.COPY_LOCALE,\n m_messages.key(Messages.GUI_ADD_DESCRIPTOR_0));\n\n addDescriptorButton.setDisableOnClick(true);\n\n addDescriptorButton.addClickListener(new ClickListener() {\n\n @SuppressWarnings(\"synthetic-access\")\n public void buttonClick(ClickEvent event) {\n\n Map<Object, Object> filters = getFilters();\n m_table.clearFilters();\n if (!m_model.addDescriptor()) {\n CmsVaadinUtils.showAlert(\n m_messages.key(Messages.ERR_BUNDLE_DESCRIPTOR_CREATION_FAILED_0),\n m_messages.key(Messages.ERR_BUNDLE_DESCRIPTOR_CREATION_FAILED_DESCRIPTION_0),\n null);\n } else {\n IndexedContainer newContainer = null;\n try {\n newContainer = m_model.getContainerForCurrentLocale();\n m_table.setContainerDataSource(newContainer);\n initFieldFactories();\n initStyleGenerators();\n setEditMode(EditMode.MASTER);\n m_table.setColumnCollapsingAllowed(true);\n adjustVisibleColumns();\n m_options.updateShownOptions(m_model.hasMasterMode(), m_model.canAddKeys());\n m_options.setEditMode(m_model.getEditMode());\n } catch (IOException | CmsException e) {\n // Can never appear here, since container is created by addDescriptor already.\n LOG.error(e.getLocalizedMessage(), e);\n }\n }\n setFilters(filters);\n }\n });\n return addDescriptorButton;\n }"
] | [
"@DELETE\n @Path(\"/{name}\" + ServerAPI.GET_CORPORATE_GROUPIDS)\n public Response removeCorporateGroupIdPrefix(@Auth final DbCredential credential, @PathParam(\"name\") final String organizationId, final String corporateGroupId){\n LOG.info(\"Got an remove a corporate groupId prefix request for organization \" + organizationId +\".\");\n if(!credential.getRoles().contains(DbCredential.AvailableRoles.DATA_UPDATER)){\n throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).build());\n }\n\n if(corporateGroupId == null || corporateGroupId.isEmpty()){\n LOG.error(\"No corporate GroupId to remove!\");\n return Response.serverError().status(HttpStatus.BAD_REQUEST_400).build();\n }\n\n getOrganizationHandler().removeCorporateGroupId(organizationId, corporateGroupId);\n\n return Response.ok(\"done\").build();\n }",
"private BasicCredentialsProvider getCredentialsProvider() {\n return new BasicCredentialsProvider() {\n private Set<AuthScope> authAlreadyTried = Sets.newHashSet();\n\n @Override\n public Credentials getCredentials(AuthScope authscope) {\n if (authAlreadyTried.contains(authscope)) {\n return null;\n }\n authAlreadyTried.add(authscope);\n return super.getCredentials(authscope);\n }\n };\n }",
"public boolean shouldIncrementVersionBasedOnResources(CmsObject cms) throws CmsException {\n\n if (m_checkpointTime == 0) {\n return true;\n }\n\n // adjust the site root, if necessary\n CmsObject cmsClone = adjustSiteRootIfNecessary(cms, this);\n\n // calculate the module resources\n List<CmsResource> moduleResources = calculateModuleResources(cmsClone, this);\n\n for (CmsResource resource : moduleResources) {\n try {\n List<CmsResource> resourcesToCheck = Lists.newArrayList();\n resourcesToCheck.add(resource);\n if (resource.isFolder()) {\n resourcesToCheck.addAll(cms.readResources(resource, CmsResourceFilter.IGNORE_EXPIRATION, true));\n }\n for (CmsResource resourceToCheck : resourcesToCheck) {\n if (resourceToCheck.getDateLastModified() > m_checkpointTime) {\n return true;\n }\n }\n } catch (CmsException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n continue;\n }\n }\n return false;\n }",
"@ArgumentsChecked\n\t@Throws(IllegalNullArgumentException.class)\n\tpublic static int checkInteger(@Nonnull final Number number) {\n\t\tCheck.notNull(number, \"number\");\n\t\tif (!isInIntegerRange(number)) {\n\t\t\tthrow new IllegalNumberRangeException(number.toString(), INTEGER_MIN, INTEGER_MAX);\n\t\t}\n\n\t\treturn number.intValue();\n\t}",
"private void executeRequest(HttpMethod httpMethodProxyRequest,\n HttpServletRequest httpServletRequest,\n PluginResponse httpServletResponse,\n History history) throws Exception {\n int intProxyResponseCode = 999;\n // Create a default HttpClient\n HttpClient httpClient = new HttpClient();\n HttpState state = new HttpState();\n\n try {\n httpMethodProxyRequest.setFollowRedirects(false);\n ArrayList<String> headersToRemove = getRemoveHeaders();\n\n httpClient.getParams().setSoTimeout(60000);\n\n httpServletRequest.setAttribute(\"com.groupon.odo.removeHeaders\", headersToRemove);\n\n // exception handling for httpclient\n HttpMethodRetryHandler noretryhandler = new HttpMethodRetryHandler() {\n public boolean retryMethod(\n final HttpMethod method,\n final IOException exception,\n int executionCount) {\n return false;\n }\n };\n\n httpMethodProxyRequest.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, noretryhandler);\n\n intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest.getHostConfiguration(), httpMethodProxyRequest, state);\n } catch (Exception e) {\n // Return a gateway timeout\n httpServletResponse.setStatus(504);\n httpServletResponse.setHeader(Constants.HEADER_STATUS, \"504\");\n httpServletResponse.flushBuffer();\n return;\n }\n logger.info(\"Response code: {}, {}\", intProxyResponseCode,\n HttpUtilities.getURL(httpMethodProxyRequest.getURI().toString()));\n\n // Pass the response code back to the client\n httpServletResponse.setStatus(intProxyResponseCode);\n\n // Pass response headers back to the client\n Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();\n for (Header header : headerArrayResponse) {\n // remove transfer-encoding header. The http libraries will handle this encoding\n if (header.getName().toLowerCase().equals(\"transfer-encoding\")) {\n continue;\n }\n\n httpServletResponse.setHeader(header.getName(), header.getValue());\n }\n\n // there is no data for a HTTP 304 or 204\n if (intProxyResponseCode != HttpServletResponse.SC_NOT_MODIFIED &&\n intProxyResponseCode != HttpServletResponse.SC_NO_CONTENT) {\n // Send the content to the client\n httpServletResponse.resetBuffer();\n httpServletResponse.getOutputStream().write(httpMethodProxyRequest.getResponseBody());\n }\n\n // copy cookies to servlet response\n for (Cookie cookie : state.getCookies()) {\n javax.servlet.http.Cookie servletCookie = new javax.servlet.http.Cookie(cookie.getName(), cookie.getValue());\n\n if (cookie.getPath() != null) {\n servletCookie.setPath(cookie.getPath());\n }\n\n if (cookie.getDomain() != null) {\n servletCookie.setDomain(cookie.getDomain());\n }\n\n // convert expiry date to max age\n if (cookie.getExpiryDate() != null) {\n servletCookie.setMaxAge((int) ((cookie.getExpiryDate().getTime() - System.currentTimeMillis()) / 1000));\n }\n\n servletCookie.setSecure(cookie.getSecure());\n\n servletCookie.setVersion(cookie.getVersion());\n\n if (cookie.getComment() != null) {\n servletCookie.setComment(cookie.getComment());\n }\n\n httpServletResponse.addCookie(servletCookie);\n }\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 }",
"public void setAll() {\n\tshowAttributes = true;\n\tshowEnumerations = true;\n\tshowEnumConstants = true;\n\tshowOperations = true;\n\tshowConstructors = true;\n\tshowVisibility = true;\n\tshowType = true;\n }",
"CueList getCueList(int rekordboxId, CdjStatus.TrackSourceSlot slot, Client client)\n throws IOException {\n Message response = client.simpleRequest(Message.KnownType.CUE_LIST_REQ, null,\n client.buildRMST(Message.MenuIdentifier.DATA, slot), new NumberField(rekordboxId));\n if (response.knownType == Message.KnownType.CUE_LIST) {\n return new CueList(response);\n }\n logger.error(\"Unexpected response type when requesting cue list: {}\", response);\n return null;\n }",
"public void stopServer() throws Exception {\n if (!externalDatabaseHost) {\n try (Connection sqlConnection = getConnection()) {\n sqlConnection.prepareStatement(\"SHUTDOWN\").execute();\n } catch (Exception e) {\n }\n\n try {\n server.stop();\n } catch (Exception e) {\n }\n }\n }"
] |
Get the named method from the class
@param c The class to get the method from
@param name The method name
@param argTypes The argument types
@return The method | [
"public static <T> Method getMethod(Class<T> c, String name, Class<?>... argTypes) {\n try {\n return c.getMethod(name, argTypes);\n } catch(NoSuchMethodException e) {\n throw new IllegalArgumentException(e);\n }\n }"
] | [
"public synchronized void shutdown(){\r\n\r\n\t\tif (!this.poolShuttingDown){\r\n\t\t\tlogger.info(\"Shutting down connection pool...\");\r\n\t\t\tthis.poolShuttingDown = true;\r\n\t\t\tthis.shutdownStackTrace = captureStackTrace(SHUTDOWN_LOCATION_TRACE);\r\n\t\t\tthis.keepAliveScheduler.shutdownNow(); // stop threads from firing.\r\n\t\t\tthis.maxAliveScheduler.shutdownNow(); // stop threads from firing.\r\n\t\t\tthis.connectionsScheduler.shutdownNow(); // stop threads from firing.\r\n\t\t\tthis.asyncExecutor.shutdownNow();\r\n\r\n\t\t\ttry {\r\n\t\t\t\tthis.connectionsScheduler.awaitTermination(5, TimeUnit.SECONDS);\r\n\r\n\t\t\t\tthis.maxAliveScheduler.awaitTermination(5, TimeUnit.SECONDS);\r\n\t\t\t\tthis.keepAliveScheduler.awaitTermination(5, TimeUnit.SECONDS);\r\n\t\t\t\tthis.asyncExecutor.awaitTermination(5, TimeUnit.SECONDS);\r\n\t\t\t\t\r\n\t\t\t\tif (this.closeConnectionExecutor != null){\r\n\t\t\t\t\tthis.closeConnectionExecutor.shutdownNow();\r\n\t\t\t\t\tthis.closeConnectionExecutor.awaitTermination(5, TimeUnit.SECONDS);\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t} catch (InterruptedException e) {\r\n\t\t\t\t// do nothing\r\n\t\t\t}\r\n\t\t\tthis.connectionStrategy.terminateAllConnections();\r\n\t\t\tunregisterDriver();\r\n\t\t\tregisterUnregisterJMX(false);\r\n\t\t\tif (finalizableRefQueue != null) {\r\n\t\t\t\tfinalizableRefQueue.close();\r\n\t\t\t}\r\n\t\t\t logger.info(\"Connection pool has been shutdown.\");\r\n\t\t}\r\n\t}",
"@NonNull\n @Override\n public File getParent(@NonNull final File from) {\n if (from.getPath().equals(getRoot().getPath())) {\n // Already at root, we can't go higher\n return from;\n } else if (from.getParentFile() != null) {\n return from.getParentFile();\n } else {\n return from;\n }\n }",
"private void processFile(InputStream is) throws MPXJException\n {\n try\n {\n InputStreamReader reader = new InputStreamReader(is, CharsetHelper.UTF8);\n Tokenizer tk = new ReaderTokenizer(reader)\n {\n @Override protected boolean startQuotedIsValid(StringBuilder buffer)\n {\n return buffer.length() == 1 && buffer.charAt(0) == '<';\n }\n };\n\n tk.setDelimiter(DELIMITER);\n ArrayList<String> columns = new ArrayList<String>();\n String nextTokenPrefix = null;\n\n while (tk.getType() != Tokenizer.TT_EOF)\n {\n columns.clear();\n TableDefinition table = null;\n\n while (tk.nextToken() == Tokenizer.TT_WORD)\n {\n String token = tk.getToken();\n if (columns.size() == 0)\n {\n if (token.charAt(0) == '#')\n {\n int index = token.lastIndexOf(':');\n if (index != -1)\n {\n String headerToken;\n if (token.endsWith(\"-\") || token.endsWith(\"=\"))\n {\n headerToken = token;\n token = null;\n }\n else\n {\n headerToken = token.substring(0, index);\n token = token.substring(index + 1);\n }\n\n RowHeader header = new RowHeader(headerToken);\n table = m_tableDefinitions.get(header.getType());\n columns.add(header.getID());\n }\n }\n else\n {\n if (token.charAt(0) == 0)\n {\n processFileType(token);\n }\n }\n }\n\n if (table != null && token != null)\n {\n if (token.startsWith(\"<\\\"\") && !token.endsWith(\"\\\">\"))\n {\n nextTokenPrefix = token;\n }\n else\n {\n if (nextTokenPrefix != null)\n {\n token = nextTokenPrefix + DELIMITER + token;\n nextTokenPrefix = null;\n }\n\n columns.add(token);\n }\n }\n }\n\n if (table != null && columns.size() > 1)\n {\n // System.out.println(table.getName() + \" \" + columns.size());\n // ColumnDefinition[] columnDefs = table.getColumns();\n // int unknownIndex = 1;\n // for (int xx = 0; xx < columns.size(); xx++)\n // {\n // String x = columns.get(xx);\n // String columnName = xx < columnDefs.length ? (columnDefs[xx] == null ? \"UNKNOWN\" + (unknownIndex++) : columnDefs[xx].getName()) : \"?\";\n // System.out.println(columnName + \": \" + x + \", \");\n // }\n // System.out.println();\n\n TextFileRow row = new TextFileRow(table, columns, m_epochDateFormat);\n List<Row> rows = m_tables.get(table.getName());\n if (rows == null)\n {\n rows = new LinkedList<Row>();\n m_tables.put(table.getName(), rows);\n }\n rows.add(row);\n }\n }\n }\n\n catch (Exception ex)\n {\n throw new MPXJException(MPXJException.READ_ERROR, ex);\n }\n }",
"public static String detokenize(List<String> tokens) {\n return TwitterKoreanProcessor.detokenize(JavaConversions.iterableAsScalaIterable(tokens));\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 static base_response clear(nitro_service client) throws Exception {\n\t\tgslbldnsentries clearresource = new gslbldnsentries();\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}",
"public void visitOpen(String packaze, int access, String... modules) {\n if (mv != null) {\n mv.visitOpen(packaze, access, modules);\n }\n }",
"public User getUploadStatus() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_UPLOAD_STATUS);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element userElement = response.getPayload();\r\n User user = new User();\r\n user.setId(userElement.getAttribute(\"id\"));\r\n user.setPro(\"1\".equals(userElement.getAttribute(\"ispro\")));\r\n user.setUsername(XMLUtilities.getChildValue(userElement, \"username\"));\r\n\r\n Element bandwidthElement = XMLUtilities.getChild(userElement, \"bandwidth\");\r\n user.setBandwidthMax(bandwidthElement.getAttribute(\"max\"));\r\n user.setBandwidthUsed(bandwidthElement.getAttribute(\"used\"));\r\n user.setIsBandwidthUnlimited(\"1\".equals(bandwidthElement.getAttribute(\"unlimited\")));\r\n\r\n Element filesizeElement = XMLUtilities.getChild(userElement, \"filesize\");\r\n user.setFilesizeMax(filesizeElement.getAttribute(\"max\"));\r\n\r\n Element setsElement = XMLUtilities.getChild(userElement, \"sets\");\r\n user.setSetsCreated(setsElement.getAttribute(\"created\"));\r\n user.setSetsRemaining(setsElement.getAttribute(\"remaining\"));\r\n\r\n Element videosElement = XMLUtilities.getChild(userElement, \"videos\");\r\n user.setVideosUploaded(videosElement.getAttribute(\"uploaded\"));\r\n user.setVideosRemaining(videosElement.getAttribute(\"remaining\"));\r\n\r\n Element videoSizeElement = XMLUtilities.getChild(userElement, \"videosize\");\r\n user.setVideoSizeMax(videoSizeElement.getAttribute(\"maxbytes\"));\r\n\r\n return user;\r\n }",
"public static int nullity(SingularValueDecomposition_F64 svd , double threshold ) {\n int ret = 0;\n\n double w[]= svd.getSingularValues();\n\n int N = svd.numberOfSingularValues();\n\n int numCol = svd.numCols();\n\n for( int j = 0; j < N; j++ ) {\n if( w[j] <= threshold) ret++;\n }\n return ret + numCol-N;\n }"
] |
Called by the engine to trigger the cleanup at the end of a payload thread. | [
"public static int forceCleanup(Thread t)\n {\n int i = 0;\n for (Map.Entry<ConnectionPool, Set<ConnPair>> e : conns.entrySet())\n {\n for (ConnPair c : e.getValue())\n {\n if (c.thread.equals(t))\n {\n try\n {\n // This will in turn remove it from the static Map.\n c.conn.getHandler().invoke(c.conn, Connection.class.getMethod(\"close\"), null);\n }\n catch (Throwable e1)\n {\n e1.printStackTrace();\n }\n i++;\n }\n }\n }\n return i;\n }"
] | [
"public String getAccuracyDescription(int numDigits) {\r\n NumberFormat nf = NumberFormat.getNumberInstance();\r\n nf.setMaximumFractionDigits(numDigits);\r\n Triple<Double, Integer, Integer> accu = getAccuracyInfo();\r\n return nf.format(accu.first()) + \" (\" + accu.second() + \"/\" + (accu.second() + accu.third()) + \")\";\r\n }",
"public static PJsonObject parseSpec(final String spec) {\n final JSONObject jsonSpec;\n try {\n jsonSpec = new JSONObject(spec);\n } catch (JSONException e) {\n throw new RuntimeException(\"Cannot parse the spec file: \" + spec, e);\n }\n return new PJsonObject(jsonSpec, \"spec\");\n }",
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public int getCount(String event) {\n EventDetail eventDetail = getLocalDataStore().getEventDetail(event);\n if (eventDetail != null) return eventDetail.getCount();\n\n return -1;\n }",
"public static <T> String listToString(List<T> list, final boolean justValue,\r\n final String separator) {\r\n StringBuilder s = new StringBuilder();\r\n for (Iterator<T> wordIterator = list.iterator(); wordIterator.hasNext();) {\r\n T o = wordIterator.next();\r\n s.append(wordToString(o, justValue, separator));\r\n if (wordIterator.hasNext()) {\r\n s.append(' ');\r\n }\r\n }\r\n return s.toString();\r\n }",
"protected String getFormattedDatatypeValue(ICompositeNode node, AbstractRule rule, String text) throws ValueConverterException {\n\t\tObject value = valueConverter.toValue(text, rule.getName(), node);\n\t\ttext = valueConverter.toString(value, rule.getName());\n\t\treturn text;\n\t}",
"public boolean isHoliday(String dateString) {\n boolean isHoliday = false;\n for (Holiday date : EquivalenceClassTransformer.HOLIDAYS) {\n if (convertToReadableDate(date.forYear(Integer.parseInt(dateString.substring(0, 4)))).equals(dateString)) {\n isHoliday = true;\n }\n }\n return isHoliday;\n }",
"public synchronized int put(byte[] src, int off, int len) {\n if (available == capacity) {\n return 0;\n }\n\n // limit is last index to put + 1\n int limit = idxPut < idxGet ? idxGet : capacity;\n int count = Math.min(limit - idxPut, len);\n System.arraycopy(src, off, buffer, idxPut, count);\n idxPut += count;\n\n if (idxPut == capacity) {\n // Array end reached, check if we have more\n int count2 = Math.min(len - count, idxGet);\n if (count2 > 0) {\n System.arraycopy(src, off + count, buffer, 0, count2);\n idxPut = count2;\n count += count2;\n } else {\n idxPut = 0;\n }\n }\n available += count;\n return count;\n }",
"public void setKeywords(final List<String> keywords) {\n StringBuilder builder = new StringBuilder();\n for (String keyword: keywords) {\n if (builder.length() > 0) {\n builder.append(',');\n }\n builder.append(keyword.trim());\n }\n this.keywords = Optional.of(builder.toString());\n }",
"public void setTimeWarp(String l) {\n\n long warp = CmsContextInfo.CURRENT_TIME;\n try {\n warp = Long.parseLong(l);\n } catch (NumberFormatException e) {\n // if parsing the time warp fails, it will be set to -1 (i.e. disabled)\n }\n m_settings.setTimeWarp(warp);\n }"
] |
Builds sql clause to load data into a database.
@param config Load configuration.
@param prefix Prefix for temporary resources.
@return the load DDL | [
"public static String load(LoadConfiguration config, String prefix) {\n\t\tif (config.getMode() == Mode.INSERT) {\n\t\t\treturn loadInsert(config, prefix);\n\t\t}\n\t\telse if (config.getMode() == Mode.UPDATE) {\n\t\t\treturn loadUpdate(config, prefix);\n\t\t}\n\t\tthrow new IllegalArgumentException(\"Unsupported mode \" + config.getMode());\n\t}"
] | [
"public void print() {\n Iterator<String> iter = getKeys();\n while (iter.hasNext()) {\n String key = iter.next();\n log.info(key + \" = \" + getRawString(key));\n }\n }",
"public static int compare(Integer n1, Integer n2)\n {\n int result;\n if (n1 == null || n2 == null)\n {\n result = (n1 == null && n2 == null ? 0 : (n1 == null ? 1 : -1));\n }\n else\n {\n result = n1.compareTo(n2);\n }\n return (result);\n }",
"private static void listResources(ProjectFile file)\n {\n for (Resource resource : file.getResources())\n {\n System.out.println(\"Resource: \" + resource.getName() + \" (Unique ID=\" + resource.getUniqueID() + \") Start=\" + resource.getStart() + \" Finish=\" + resource.getFinish());\n }\n System.out.println();\n }",
"public void attachMetadataCache(SlotReference slot, File file)\n throws IOException {\n ensureRunning();\n if (slot.player < 1 || slot.player > 4 || DeviceFinder.getInstance().getLatestAnnouncementFrom(slot.player) == null) {\n throw new IllegalArgumentException(\"unable to attach metadata cache for player \" + slot.player);\n }\n if ((slot.slot != CdjStatus.TrackSourceSlot.USB_SLOT) && (slot.slot != CdjStatus.TrackSourceSlot.SD_SLOT)) {\n throw new IllegalArgumentException(\"unable to attach metadata cache for slot \" + slot.slot);\n }\n\n MetadataCache cache = new MetadataCache(file);\n final MediaDetails slotDetails = getMediaDetailsFor(slot);\n if (cache.sourceMedia != null && slotDetails != null) {\n if (!slotDetails.hashKey().equals(cache.sourceMedia.hashKey())) {\n throw new IllegalArgumentException(\"Cache was created for different media (\" + cache.sourceMedia.hashKey() +\n \") than is in the slot (\" + slotDetails.hashKey() + \").\");\n }\n if (slotDetails.hasChanged(cache.sourceMedia)) {\n logger.warn(\"Media has changed (\" + slotDetails + \") since cache was created (\" + cache.sourceMedia +\n \"). Attaching anyway as instructed.\");\n }\n }\n attachMetadataCacheInternal(slot, cache);\n }",
"public EventBus emit(EventObject event, Object... args) {\n return _emitWithOnceBus(eventContext(event, args));\n }",
"private Map<UUID, List<DateRange>> processDayTypes(List<MapRow> types)\n {\n Map<UUID, List<DateRange>> map = new HashMap<UUID, List<DateRange>>();\n for (MapRow row : types)\n {\n List<DateRange> ranges = new ArrayList<DateRange>();\n for (MapRow range : row.getRows(\"TIME_RANGES\"))\n {\n ranges.add(new DateRange(range.getDate(\"START\"), range.getDate(\"END\")));\n }\n map.put(row.getUUID(\"UUID\"), ranges);\n }\n\n return map;\n }",
"public SingleProfileBackup getProfileBackupData(int profileID, String clientUUID) throws Exception {\n SingleProfileBackup singleProfileBackup = new SingleProfileBackup();\n List<PathOverride> enabledPaths = new ArrayList<>();\n\n List<EndpointOverride> paths = PathOverrideService.getInstance().getPaths(profileID, clientUUID, null);\n for (EndpointOverride override : paths) {\n if (override.getRequestEnabled() || override.getResponseEnabled()) {\n PathOverride pathOverride = new PathOverride();\n pathOverride.setPathName(override.getPathName());\n if (override.getRequestEnabled()) {\n pathOverride.setRequestEnabled(true);\n }\n if (override.getResponseEnabled()) {\n pathOverride.setResponseEnabled(true);\n }\n\n pathOverride.setEnabledEndpoints(override.getEnabledEndpoints());\n enabledPaths.add(pathOverride);\n }\n }\n singleProfileBackup.setEnabledPaths(enabledPaths);\n\n Client backupClient = ClientService.getInstance().findClient(clientUUID, profileID);\n ServerGroup activeServerGroup = ServerRedirectService.getInstance().getServerGroup(backupClient.getActiveServerGroup(), profileID);\n singleProfileBackup.setActiveServerGroup(activeServerGroup);\n\n return singleProfileBackup;\n }",
"public Script updateName(int id, String name) throws Exception {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = SQLService.getInstance().getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_SCRIPT +\n \" SET \" + Constants.SCRIPT_NAME + \" = ? \" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, name);\n statement.setInt(2, 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\n return this.getScript(id);\n }",
"public static FileStatus[] getDataChunkFiles(FileSystem fs,\n Path path,\n final int partitionId,\n final int replicaType) throws IOException {\n return fs.listStatus(path, new PathFilter() {\n\n public boolean accept(Path input) {\n if(input.getName().matches(\"^\" + Integer.toString(partitionId) + \"_\"\n + Integer.toString(replicaType) + \"_[\\\\d]+\\\\.data\")) {\n return true;\n } else {\n return false;\n }\n }\n });\n }"
] |
The primary run loop of the event processor. | [
"@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 }"
] | [
"private static Predicate join(final String joinWord, final List<Predicate> preds) {\n return new Predicate() {\n public void init(AbstractSqlCreator creator) {\n for (Predicate p : preds) {\n p.init(creator);\n }\n }\n public String toSql() {\n StringBuilder sb = new StringBuilder()\n .append(\"(\");\n boolean first = true;\n for (Predicate p : preds) {\n if (!first) {\n sb.append(\" \").append(joinWord).append(\" \");\n }\n sb.append(p.toSql());\n first = false;\n }\n return sb.append(\")\").toString();\n }\n };\n }",
"protected DatabaseConnection getSavedConnection() {\n\t\tNestedConnection nested = specialConnection.get();\n\t\tif (nested == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn nested.connection;\n\t\t}\n\t}",
"@SuppressWarnings(\"unchecked\")\r\n\tpublic List<Difference> compare() {\r\n\t\tDiff diff = new Diff(this.controlDOM, this.testDOM);\r\n\t\tDetailedDiff detDiff = new DetailedDiff(diff);\r\n\t\treturn detDiff.getAllDifferences();\r\n\t}",
"boolean processUnstable() {\n boolean change = !unstable;\n if (change) { // Only once until the process is removed. A process is unstable until removed.\n unstable = true;\n HostControllerLogger.ROOT_LOGGER.managedServerUnstable(serverName);\n }\n return change;\n }",
"public SourceBuilder addLine(String fmt, Object... args) {\n add(fmt, args);\n source.append(LINE_SEPARATOR);\n return this;\n }",
"static Type getRawType(Type genericType, Map<TypeVariable, Type> typeVariableMap) {\n\t\tType resolvedType = genericType;\n\t\tif (genericType instanceof TypeVariable) {\n\t\t\tTypeVariable tv = (TypeVariable) genericType;\n\t\t\tresolvedType = typeVariableMap.get(tv);\n\t\t\tif (resolvedType == null) {\n\t\t\t\tresolvedType = extractBoundForTypeVariable(tv);\n\t\t\t}\n\t\t}\n\t\tif (resolvedType instanceof ParameterizedType) {\n\t\t\treturn ((ParameterizedType) resolvedType).getRawType();\n\t\t}\n\t\telse {\n\t\t\treturn resolvedType;\n\t\t}\n\t}",
"public void get( int row , int col , Complex_F64 output ) {\n ops.get(mat,row,col,output);\n }",
"public QueryBuilder<T, ID> selectColumns(String... columns) {\n\t\tfor (String column : columns) {\n\t\t\taddSelectColumnToList(column);\n\t\t}\n\t\treturn this;\n\t}",
"private void initUpperLeftComponent() {\n\n m_upperLeftComponent = new HorizontalLayout();\n m_upperLeftComponent.setHeight(\"100%\");\n m_upperLeftComponent.setSpacing(true);\n m_upperLeftComponent.setDefaultComponentAlignment(Alignment.MIDDLE_RIGHT);\n m_upperLeftComponent.addComponent(m_languageSwitch);\n m_upperLeftComponent.addComponent(m_filePathLabel);\n\n }"
] |
Figures out the correct class loader to use for a proxy for a given bean | [
"public static ClassLoader resolveClassLoaderForBeanProxy(String contextId, Class<?> proxiedType, TypeInfo typeInfo, ProxyServices proxyServices) {\n Class<?> superClass = typeInfo.getSuperClass();\n if (superClass.getName().startsWith(JAVA)) {\n ClassLoader cl = proxyServices.getClassLoader(proxiedType);\n if (cl == null) {\n cl = Thread.currentThread().getContextClassLoader();\n }\n return cl;\n }\n return Container.instance(contextId).services().get(ProxyServices.class).getClassLoader(superClass);\n }"
] | [
"public ParallelTask execute(ParallecResponseHandler handler) {\n\n ParallelTask task = new ParallelTask();\n\n try {\n targetHostMeta = new TargetHostMeta(targetHosts);\n\n final ParallelTask taskReal = new ParallelTask(requestProtocol,\n concurrency, httpMeta, targetHostMeta, sshMeta, tcpMeta, udpMeta, pingMeta,\n handler, responseContext, \n replacementVarMapNodeSpecific, replacementVarMap,\n requestReplacementType, \n config);\n\n task = taskReal;\n\n logger.info(\"***********START_PARALLEL_HTTP_TASK_\"\n + task.getTaskId() + \"***********\");\n\n // throws ParallelTaskInvalidException\n task.validateWithFillDefault();\n\n task.setSubmitTime(System.currentTimeMillis());\n\n if (task.getConfig().isEnableCapacityAwareTaskScheduler()) {\n\n //late initialize the task scheduler\n ParallelTaskManager.getInstance().initTaskSchedulerIfNot();\n // add task to the wait queue\n ParallelTaskManager.getInstance().getWaitQ().add(task);\n\n logger.info(\"Enabled CapacityAwareTaskScheduler. Submitted task to waitQ in builder.. \"\n + task.getTaskId());\n\n } else {\n\n logger.info(\n \"Disabled CapacityAwareTaskScheduler. Immediately execute task {} \",\n task.getTaskId());\n\n Runnable director = new Runnable() {\n\n public void run() {\n ParallelTaskManager.getInstance()\n .generateUpdateExecuteTask(taskReal);\n }\n };\n new Thread(director).start();\n }\n\n if (this.getMode() == TaskRunMode.SYNC) {\n logger.info(\"Executing task {} in SYNC mode... \",\n task.getTaskId());\n\n while (task != null && !task.isCompleted()) {\n try {\n Thread.sleep(500L);\n } catch (InterruptedException e) {\n logger.error(\"InterruptedException \" + e);\n }\n }\n }\n } catch (ParallelTaskInvalidException ex) {\n\n logger.info(\"Request is invalid with missing parts. Details: \"\n + ex.getMessage() + \" Cannot execute at this time. \"\n + \" Please review your request and try again.\\nCommand:\"\n + httpMeta.toString());\n\n task.setState(ParallelTaskState.COMPLETED_WITH_ERROR);\n task.getTaskErrorMetas().add(\n new TaskErrorMeta(TaskErrorType.VALIDATION_ERROR,\n \"validation eror\"));\n\n } catch (Exception t) {\n logger.error(\"fail task builder. Unknown error: \" + t, t);\n task.setState(ParallelTaskState.COMPLETED_WITH_ERROR);\n task.getTaskErrorMetas().add(\n new TaskErrorMeta(TaskErrorType.UNKNOWN, \"unknown eror\",\n t));\n }\n\n logger.info(\"***********FINISH_PARALLEL_HTTP_TASK_\" + task.getTaskId()\n + \"***********\");\n return task;\n\n }",
"public static void checkEigenvalues() {\n DoubleMatrix A = new DoubleMatrix(new double[][]{\n {3.0, 2.0, 0.0},\n {2.0, 3.0, 2.0},\n {0.0, 2.0, 3.0}\n });\n\n DoubleMatrix E = new DoubleMatrix(3, 1);\n\n NativeBlas.dsyev('N', 'U', 3, A.data, 0, 3, E.data, 0);\n check(\"checking existence of dsyev...\", true);\n }",
"public static final Date getTime(byte[] data, int offset)\n {\n int time = getShort(data, offset) / 10;\n Calendar cal = DateHelper.popCalendar(EPOCH_DATE);\n cal.set(Calendar.HOUR_OF_DAY, (time / 60));\n cal.set(Calendar.MINUTE, (time % 60));\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MILLISECOND, 0);\n DateHelper.pushCalendar(cal);\n return (cal.getTime());\n }",
"public boolean isDockerMachineInstalled(String cliPathExec) {\n try {\n commandLineExecutor.execCommand(createDockerMachineCommand(cliPathExec));\n return true;\n } catch (Exception e) {\n return false;\n }\n }",
"private static JSONObject parseTarget(Shape target) throws JSONException {\n JSONObject targetObject = new JSONObject();\n\n targetObject.put(\"resourceId\",\n target.getResourceId().toString());\n\n return targetObject;\n }",
"public Plugin[] getPlugins(Boolean onlyValid) {\n Configuration[] configurations = ConfigurationService.getInstance().getConfigurations(Constants.DB_TABLE_CONFIGURATION_PLUGIN_PATH);\n\n ArrayList<Plugin> plugins = new ArrayList<Plugin>();\n\n if (configurations == null) {\n return new Plugin[0];\n }\n\n for (Configuration config : configurations) {\n Plugin plugin = new Plugin();\n plugin.setId(config.getId());\n plugin.setPath(config.getValue());\n\n File path = new File(plugin.getPath());\n if (path.isDirectory()) {\n plugin.setStatus(Constants.PLUGIN_STATUS_VALID);\n plugin.setStatusMessage(\"Valid\");\n } else {\n plugin.setStatus(Constants.PLUGIN_STATUS_NOT_DIRECTORY);\n plugin.setStatusMessage(\"Path is not a directory\");\n }\n\n if (!onlyValid || plugin.getStatus() == Constants.PLUGIN_STATUS_VALID) {\n plugins.add(plugin);\n }\n }\n\n return plugins.toArray(new Plugin[0]);\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 ConverterServerBuilder processTimeout(long processTimeout, TimeUnit timeUnit) {\n assertNumericArgument(processTimeout, false);\n this.processTimeout = timeUnit.toMillis(processTimeout);\n return this;\n }",
"public void printExtraClasses(RootDoc root) {\n\tSet<String> names = new HashSet<String>(classnames.keySet()); \n\tfor(String className: names) {\n\t ClassInfo info = getClassInfo(className, true);\n\t if (info.nodePrinted)\n\t\tcontinue;\n\t ClassDoc c = root.classNamed(className);\n\t if(c != null) {\n\t\tprintClass(c, false);\n\t\tcontinue;\n\t }\n\t // Handle missing classes:\n\t Options opt = optionProvider.getOptionsFor(className);\n\t if(opt.matchesHideExpression(className))\n\t\tcontinue;\n\t w.println(linePrefix + \"// \" + className);\n\t w.print(linePrefix + info.name + \"[label=\");\n\t externalTableStart(opt, className, classToUrl(className));\n\t innerTableStart();\n\t String qualifiedName = qualifiedName(opt, className);\n\t int startTemplate = qualifiedName.indexOf('<');\n\t int idx = qualifiedName.lastIndexOf('.', startTemplate < 0 ? qualifiedName.length() - 1 : startTemplate);\n\t if(opt.postfixPackage && idx > 0 && idx < (qualifiedName.length() - 1)) {\n\t\tString packageName = qualifiedName.substring(0, idx);\n\t\tString cn = qualifiedName.substring(idx + 1);\n\t\ttableLine(Align.CENTER, Font.CLASS.wrap(opt, escape(cn)));\n\t\ttableLine(Align.CENTER, Font.PACKAGE.wrap(opt, packageName));\n\t } else {\n\t\ttableLine(Align.CENTER, Font.CLASS.wrap(opt, escape(qualifiedName)));\n\t }\n\t innerTableEnd();\n\t externalTableEnd();\n\t if (className == null || className.length() == 0)\n\t\tw.print(\",URL=\\\"\" + classToUrl(className) + \"\\\"\");\n\t nodeProperties(opt);\n\t}\n }"
] |
Sets the current switch index based on object name.
This function finds the child of the scene object
this component is attached to and sets the switch
index to reference it so this is the object that
will be displayed.
If it is out of range, none of the children will be shown.
@param childName name of child to select
@see GVRSceneObject#getChildByIndex(int) | [
"public void selectByName(String childName)\n {\n int i = 0;\n GVRSceneObject owner = getOwnerObject();\n if (owner == null)\n {\n return;\n }\n for (GVRSceneObject child : owner.children())\n {\n if (child.getName().equals(childName))\n {\n mSwitchIndex = i;\n return;\n }\n ++i;\n } \n }"
] | [
"public static base_responses clear(nitro_service client, route6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\troute6 clearresources[] = new route6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tclearresources[i] = new route6();\n\t\t\t\tclearresources[i].routetype = resources[i].routetype;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, clearresources,\"clear\");\n\t\t}\n\t\treturn result;\n\t}",
"@Subscribe\n public void onEnd(AggregatedQuitEvent e) {\n try {\n writeHints(hintsFile, hints);\n } catch (IOException exception) {\n outer.log(\"Could not write back the hints file.\", exception, Project.MSG_ERR);\n }\n }",
"void createDirectory(Path path) throws IOException {\n\t\tif (Files.exists(path) && Files.isDirectory(path)) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.readOnly) {\n\t\t\tthrow new FileNotFoundException(\n\t\t\t\t\t\"The requested directory \\\"\"\n\t\t\t\t\t\t\t+ path.toString()\n\t\t\t\t\t\t\t+ \"\\\" does not exist and we are in read-only mode, so it cannot be created.\");\n\t\t}\n\n\t\tFiles.createDirectory(path);\n\t}",
"private static Iterable<String> splitAndOmitEmpty(final String str, final char splitChar) {\n return new Iterable<String>() {\n @Override\n public Iterator<String> iterator() {\n return new Iterator<String>() {\n\n int startIdx = 0;\n String next = null;\n\n @Override\n public boolean hasNext() {\n while (next == null && startIdx < str.length()) {\n int idx = str.indexOf(splitChar, startIdx);\n if (idx == startIdx) {\n // Omit empty string\n startIdx++;\n continue;\n }\n if (idx >= 0) {\n // Found the next part\n next = str.substring(startIdx, idx);\n startIdx = idx;\n } else {\n // The last part\n if (startIdx < str.length()) {\n next = str.substring(startIdx);\n startIdx = str.length();\n }\n break;\n }\n }\n return next != null;\n }\n\n @Override\n public String next() {\n if (hasNext()) {\n String next = this.next;\n this.next = null;\n return next;\n }\n throw new NoSuchElementException(\"No more element\");\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException(\"Remove not supported\");\n }\n };\n }\n };\n }",
"public static double[][] invert(double[][] matrix) {\n\n\t\tif(isSolverUseApacheCommonsMath) {\n\t\t\t// Use LU from common math\n\t\t\tLUDecomposition lu = new LUDecomposition(new Array2DRowRealMatrix(matrix));\n\t\t\tdouble[][] matrixInverse = lu.getSolver().getInverse().getData();\n\n\t\t\treturn matrixInverse;\n\t\t}\n\t\telse {\n\t\t\treturn org.jblas.Solve.pinv(new org.jblas.DoubleMatrix(matrix)).toArray2();\n\t\t}\n\t}",
"private void updateMax(MtasRBTreeNode n, MtasRBTreeNode c) {\n if (c != null) {\n if (n.max < c.max) {\n n.max = c.max;\n }\n }\n }",
"public static XClass getMemberType() throws XDocletException\r\n {\r\n if (getCurrentField() != null) {\r\n return getCurrentField().getType();\r\n }\r\n else if (getCurrentMethod() != null) {\r\n XMethod method = getCurrentMethod();\r\n\r\n if (MethodTagsHandler.isGetterMethod(method)) {\r\n return method.getReturnType().getType();\r\n }\r\n else if (MethodTagsHandler.isSetterMethod(method)) {\r\n XParameter param = (XParameter)method.getParameters().iterator().next();\r\n\r\n return param.getType();\r\n }\r\n }\r\n return null;\r\n }",
"@Deprecated\n public int getEntityTypeId(@NotNull final String entityType, final boolean allowCreate) {\n return getEntityTypeId(txnProvider, entityType, allowCreate);\n }",
"public void commandLoop() throws IOException {\n for (Object handler : allHandlers) {\n if (handler instanceof ShellManageable) {\n ((ShellManageable)handler).cliEnterLoop();\n }\n }\n output.output(appName, outputConverter);\n String command = \"\";\n while (true) {\n try {\n command = input.readCommand(path);\n if (command.trim().equals(\"exit\")) {\n if (lineProcessor == null)\n break;\n else {\n path = savedPath;\n lineProcessor = null;\n }\n }\n\n processLine(command);\n } catch (TokenException te) {\n lastException = te;\n output.outputException(command, te);\n } catch (CLIException clie) {\n lastException = clie;\n if (!command.trim().equals(\"exit\")) {\n output.outputException(clie);\n }\n }\n }\n for (Object handler : allHandlers) {\n if (handler instanceof ShellManageable) {\n ((ShellManageable)handler).cliLeaveLoop();\n }\n }\n }"
] |
Validates operation model against the definition and its parameters
@param operation model node of type {@link ModelType#OBJECT}, representing an operation request
@throws OperationFailedException if the value is not valid
@deprecated Not used by the WildFly management kernel; will be removed in a future release | [
"@Deprecated\n public void validateOperation(final ModelNode operation) throws OperationFailedException {\n if (operation.hasDefined(ModelDescriptionConstants.OPERATION_NAME) && deprecationData != null && deprecationData.isNotificationUseful()) {\n ControllerLogger.DEPRECATED_LOGGER.operationDeprecated(getName(),\n PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR)).toCLIStyleString());\n }\n for (AttributeDefinition ad : this.parameters) {\n ad.validateOperation(operation);\n }\n }"
] | [
"public MIMEType addParameter(String name, String value) {\n Map<String, String> copy = new LinkedHashMap<>(this.parameters);\n copy.put(name, value);\n return new MIMEType(type, subType, copy);\n }",
"protected BufferedImage createErrorImage(final Rectangle area) {\n final BufferedImage bufferedImage = new BufferedImage(area.width, area.height, TYPE_INT_ARGB_PRE);\n final Graphics2D graphics = bufferedImage.createGraphics();\n try {\n graphics.setBackground(ColorParser.toColor(this.configuration.getTransparentTileErrorColor()));\n graphics.clearRect(0, 0, area.width, area.height);\n return bufferedImage;\n } finally {\n graphics.dispose();\n }\n }",
"private void writeTermStatisticsToFile(UsageStatistics usageStatistics,\n\t\t\tString fileName) {\n\n\t\t// Make sure all keys are present in label count map:\n\t\tfor (String key : usageStatistics.aliasCounts.keySet()) {\n\t\t\tcountKey(usageStatistics.labelCounts, key, 0);\n\t\t}\n\t\tfor (String key : usageStatistics.descriptionCounts.keySet()) {\n\t\t\tcountKey(usageStatistics.labelCounts, key, 0);\n\t\t}\n\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(fileName))) {\n\n\t\t\tout.println(\"Language,Labels,Descriptions,Aliases\");\n\t\t\tfor (Entry<String, Integer> entry : usageStatistics.labelCounts\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tcountKey(usageStatistics.aliasCounts, entry.getKey(), 0);\n\t\t\t\tint aCount = usageStatistics.aliasCounts.get(entry.getKey());\n\t\t\t\tcountKey(usageStatistics.descriptionCounts, entry.getKey(), 0);\n\t\t\t\tint dCount = usageStatistics.descriptionCounts.get(entry\n\t\t\t\t\t\t.getKey());\n\t\t\t\tout.println(entry.getKey() + \",\" + entry.getValue() + \",\"\n\t\t\t\t\t\t+ dCount + \",\" + aCount);\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}",
"public Map<Integer, RandomVariable> getGradient(){\r\n\r\n\t\tint numberOfCalculationSteps = getFunctionList().size();\r\n\r\n\t\tRandomVariable[] omegaHat = new RandomVariable[numberOfCalculationSteps];\r\n\r\n\t\tomegaHat[numberOfCalculationSteps-1] = new RandomVariableFromDoubleArray(1.0);\r\n\r\n\t\tfor(int variableIndex = numberOfCalculationSteps-2; variableIndex >= 0; variableIndex--){\r\n\r\n\t\t\tomegaHat[variableIndex] = new RandomVariableFromDoubleArray(0.0);\r\n\r\n\t\t\tArrayList<Integer> childrenList = getAADRandomVariableFromList(variableIndex).getChildrenIndices();\r\n\r\n\t\t\tfor(int functionIndex:childrenList){\r\n\t\t\t\tRandomVariable D_i_j = getPartialDerivative(functionIndex, variableIndex);\r\n\t\t\t\tomegaHat[variableIndex] = omegaHat[variableIndex].addProduct(D_i_j, omegaHat[functionIndex]);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tArrayList<Integer> arrayListOfAllIndicesOfDependentRandomVariables = getArrayListOfAllIndicesOfDependentRandomVariables();\r\n\r\n\t\tMap<Integer, RandomVariable> gradient = new HashMap<Integer, RandomVariable>();\r\n\r\n\t\tfor(Integer indexOfDependentRandomVariable: arrayListOfAllIndicesOfDependentRandomVariables){\r\n\t\t\tgradient.put(indexOfDependentRandomVariable, omegaHat[arrayListOfAllIndicesOfDependentRandomVariables.get(indexOfDependentRandomVariable)]);\r\n\t\t}\r\n\r\n\t\treturn gradient;\r\n\t}",
"void forcedUndeployScan() {\n\n if (acquireScanLock()) {\n try {\n ROOT_LOGGER.tracef(\"Performing a post-boot forced undeploy scan for scan directory %s\", deploymentDir.getAbsolutePath());\n ScanContext scanContext = new ScanContext(deploymentOperations);\n\n // Add remove actions to the plan for anything we count as\n // deployed that we didn't find on the scan\n for (Map.Entry<String, DeploymentMarker> missing : scanContext.toRemove.entrySet()) {\n // remove successful deployment and left will be removed\n if (scanContext.registeredDeployments.containsKey(missing.getKey())) {\n scanContext.registeredDeployments.remove(missing.getKey());\n }\n }\n Set<String> scannedDeployments = new HashSet<String>(scanContext.registeredDeployments.keySet());\n scannedDeployments.removeAll(scanContext.persistentDeployments);\n\n List<ScannerTask> scannerTasks = scanContext.scannerTasks;\n for (String toUndeploy : scannedDeployments) {\n scannerTasks.add(new UndeployTask(toUndeploy, deploymentDir, scanContext.scanStartTime, true));\n }\n try {\n executeScannerTasks(scannerTasks, deploymentOperations, true);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n\n ROOT_LOGGER.tracef(\"Forced undeploy scan complete\");\n } catch (Exception e) {\n ROOT_LOGGER.scanException(e, deploymentDir.getAbsolutePath());\n } finally {\n releaseScanLock();\n }\n }\n }",
"public <V> V attach(final AttachmentKey<V> key, final V value) {\n assert key != null;\n return key.cast(contextAttachments.put(key, value));\n }",
"public void setOutlineCode(int index, String value)\n {\n set(selectField(TaskFieldLists.CUSTOM_OUTLINE_CODE, index), value);\n }",
"static JDOClass getJDOClass(Class c)\r\n\t{\r\n\t\tJDOClass rc = null;\r\n\t\ttry\r\n\t\t{\r\n\t\t\tJavaModelFactory javaModelFactory = RuntimeJavaModelFactory.getInstance();\r\n\t\t\tJavaModel javaModel = javaModelFactory.getJavaModel(c.getClassLoader());\r\n\t\t\tJDOModel m = JDOModelFactoryImpl.getInstance().getJDOModel(javaModel);\r\n\t\t\trc = m.getJDOClass(c.getName());\r\n\t\t}\r\n\t\tcatch (RuntimeException ex)\r\n\t\t{\r\n\t\t\tthrow new JDOFatalInternalException(\"Not a JDO class: \" + c.getName()); \r\n\t\t}\r\n\t\treturn rc;\r\n\t}",
"private void initDurationPanel() {\n\n m_durationPrefixLabel.setText(Messages.get().key(Messages.GUI_SERIALDATE_DURATION_PREFIX_0));\n m_durationAfterPostfixLabel.setText(Messages.get().key(Messages.GUI_SERIALDATE_DURATION_ENDTYPE_OCC_POSTFIX_0));\n m_seriesEndDate.setDateOnly(true);\n m_seriesEndDate.setAllowInvalidValue(true);\n m_seriesEndDate.setValue(m_model.getSeriesEndDate());\n m_seriesEndDate.getTextField().addFocusHandler(new FocusHandler() {\n\n public void onFocus(FocusEvent event) {\n\n if (handleChange()) {\n onSeriesEndDateFocus(event);\n }\n\n }\n });\n }"
] |
The quick way to detect for a tier of devices.
This method detects for devices which can
display iPhone-optimized web content.
Includes iPhone, iPod Touch, Android, Windows Phone 7 and 8, BB10, WebOS, Playstation Vita, etc.
@return detection of any device in the iPhone/Android/Windows Phone/BlackBerry/WebOS Tier | [
"public boolean detectTierIphone() {\r\n\r\n if (detectIphoneOrIpod()\r\n || detectAndroidPhone()\r\n || detectWindowsPhone()\r\n || detectBlackBerry10Phone()\r\n || (detectBlackBerryWebKit() && detectBlackBerryTouch())\r\n || detectPalmWebOS()\r\n || detectBada()\r\n || detectTizen()\r\n || detectFirefoxOSPhone()\r\n || detectSailfishPhone()\r\n || detectUbuntuPhone()\r\n || detectGamingHandheld()) {\r\n return true;\r\n }\r\n return false;\r\n }"
] | [
"@JavaScriptMethod\n @SuppressWarnings({\"UnusedDeclaration\"})\n public LoadBuildsResponse loadBuild(String buildId) {\n LoadBuildsResponse response = new LoadBuildsResponse();\n // When we load a new build we need also to reset the promotion plugin.\n // The null plugin is related to 'None' plugin.\n setPromotionPlugin(null);\n try {\n this.currentPromotionCandidate = promotionCandidates.get(buildId);\n if (this.currentPromotionCandidate == null) {\n throw new IllegalArgumentException(\"Can't find build by ID: \" + buildId);\n }\n List<String> repositoryKeys = getRepositoryKeys();\n List<UserPluginInfo> plugins = getPromotionsUserPluginInfo();\n PromotionConfig promotionConfig = getPromotionConfig();\n String defaultTargetRepository = getDefaultPromotionTargetRepository();\n if (StringUtils.isNotBlank(defaultTargetRepository) && repositoryKeys.contains(defaultTargetRepository)) {\n promotionConfig.setTargetRepo(defaultTargetRepository);\n }\n response.addRepositories(repositoryKeys);\n response.setPlugins(plugins);\n response.setPromotionConfig(promotionConfig);\n response.setSuccess(true);\n } catch (Exception e) {\n response.setResponseMessage(e.getMessage());\n }\n return response;\n }",
"@Override\n public final PObject getObject(final String key) {\n PObject result = optObject(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }",
"protected <T1> void dispatchCommand(final BiConsumer<P, T1> action, final T1 routable1) {\n routingFor(routable1)\n .routees()\n .forEach(routee -> routee.receiveCommand(action, routable1));\n }",
"private void buildTransformers_3_0(ResourceTransformationDescriptionBuilder builder) {\n /*\n ====== Resource root address: [\"subsystem\" => \"remoting\"] - Current version: 4.0.0; legacy version: 3.0.0 =======\n --- Problems for relative address to root [\"configuration\" => \"endpoint\"]:\n Different 'default' for attribute 'sasl-protocol'. Current: \"remote\"; legacy: \"remoting\" ## both are valid also for legacy servers\n --- Problems for relative address to root [\"connector\" => \"*\"]:\n Missing attributes in current: []; missing in legacy [sasl-authentication-factory, ssl-context]\n Missing parameters for operation 'add' in current: []; missing in legacy [sasl-authentication-factory, ssl-context]\n --- Problems for relative address to root [\"http-connector\" => \"*\"]:\n Missing attributes in current: []; missing in legacy [sasl-authentication-factory]\n Missing parameters for operation 'add' in current: []; missing in legacy [sasl-authentication-factory]\n --- Problems for relative address to root [\"remote-outbound-connection\" => \"*\"]:\n Missing attributes in current: []; missing in legacy [authentication-context]\n Different 'alternatives' for attribute 'protocol'. Current: [\"authentication-context\"]; legacy: undefined\n Different 'alternatives' for attribute 'security-realm'. Current: [\"authentication-context\"]; legacy: undefined\n Different 'alternatives' for attribute 'username'. Current: [\"authentication-context\"]; legacy: undefined\n Missing parameters for operation 'add' in current: []; missing in legacy [authentication-context]\n Different 'alternatives' for parameter 'protocol' of operation 'add'. Current: [\"authentication-context\"]; legacy: undefined\n Different 'alternatives' for parameter 'security-realm' of operation 'add'. Current: [\"authentication-context\"]; legacy: undefined\n Different 'alternatives' for parameter 'username' of operation 'add'. Current: [\"authentication-context\"]; legacy: undefined\n */\n\n builder.addChildResource(ConnectorResource.PATH).getAttributeBuilder()\n .setDiscard(DiscardAttributeChecker.UNDEFINED, ConnectorCommon.SASL_AUTHENTICATION_FACTORY, ConnectorResource.SSL_CONTEXT)\n .addRejectCheck(RejectAttributeChecker.DEFINED, ConnectorCommon.SASL_AUTHENTICATION_FACTORY, ConnectorResource.SSL_CONTEXT);\n\n builder.addChildResource(RemotingEndpointResource.ENDPOINT_PATH).getAttributeBuilder()\n .setValueConverter(new AttributeConverter.DefaultAttributeConverter() {\n @Override\n protected void convertAttribute(PathAddress address, String attributeName, ModelNode attributeValue, TransformationContext context) {\n if (!attributeValue.isDefined()) {\n attributeValue.set(\"remoting\"); //if value is not defined, set it to EAP 7.0 default valueRemotingSubsystemTransformersTestCase\n }\n }\n }, RemotingSubsystemRootResource.SASL_PROTOCOL);\n\n builder.addChildResource(HttpConnectorResource.PATH).getAttributeBuilder()\n .setDiscard(DiscardAttributeChecker.UNDEFINED, ConnectorCommon.SASL_AUTHENTICATION_FACTORY)\n .addRejectCheck(RejectAttributeChecker.DEFINED, ConnectorCommon.SASL_AUTHENTICATION_FACTORY);\n\n builder.addChildResource(RemoteOutboundConnectionResourceDefinition.ADDRESS).getAttributeBuilder()\n .setDiscard(DiscardAttributeChecker.UNDEFINED, ConnectorCommon.SASL_AUTHENTICATION_FACTORY)\n .addRejectCheck(RejectAttributeChecker.DEFINED, RemoteOutboundConnectionResourceDefinition.AUTHENTICATION_CONTEXT);\n }",
"public static base_response clear(nitro_service client) throws Exception {\n\t\tnspbr6 clearresource = new nspbr6();\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}",
"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 }",
"public static Object readObject(File file) throws IOException,\n ClassNotFoundException {\n FileInputStream fileIn = new FileInputStream(file);\n ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(fileIn));\n try {\n return in.readObject();\n } finally {\n IoUtils.safeClose(in);\n }\n }",
"@Deprecated\n public int getEntityTypeId(@NotNull final String entityType, final boolean allowCreate) {\n return getEntityTypeId(txnProvider, entityType, allowCreate);\n }",
"public boolean hasRequiredClientProps() {\n boolean valid = true;\n valid &= verifyStringPropSet(CONNECTION_APPLICATION_NAME_PROP, CLIENT_APPLICATION_NAME_PROP);\n valid &= verifyStringPropSet(ACCUMULO_USER_PROP, CLIENT_ACCUMULO_USER_PROP);\n valid &= verifyStringPropSet(ACCUMULO_PASSWORD_PROP, CLIENT_ACCUMULO_PASSWORD_PROP);\n valid &= verifyStringPropSet(ACCUMULO_INSTANCE_PROP, CLIENT_ACCUMULO_INSTANCE_PROP);\n return valid;\n }"
] |
Convert an Object to a Date, without an Exception | [
"public static java.sql.Date getDate(Object value) {\n try {\n return toDate(value);\n } catch (ParseException pe) {\n pe.printStackTrace();\n return null;\n }\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 }",
"private void revisitMessages(Definitions def) {\n List<RootElement> rootElements = def.getRootElements();\n List<ItemDefinition> toAddDefinitions = new ArrayList<ItemDefinition>();\n for (RootElement root : rootElements) {\n if (root instanceof Message) {\n if (!existsMessageItemDefinition(rootElements,\n root.getId())) {\n ItemDefinition itemdef = Bpmn2Factory.eINSTANCE.createItemDefinition();\n itemdef.setId(root.getId() + \"Type\");\n toAddDefinitions.add(itemdef);\n ((Message) root).setItemRef(itemdef);\n }\n }\n }\n for (ItemDefinition id : toAddDefinitions) {\n def.getRootElements().add(id);\n }\n }",
"protected void setupRegistration() {\n if (isServiceWorkerSupported()) {\n Navigator.serviceWorker.register(getResource()).then(object -> {\n logger.info(\"Service worker has been successfully registered\");\n registration = (ServiceWorkerRegistration) object;\n\n onRegistered(new ServiceEvent(), registration);\n\n // Observe service worker lifecycle\n observeLifecycle(registration);\n\n // Setup Service Worker events events\n setupOnControllerChangeEvent();\n setupOnMessageEvent();\n setupOnErrorEvent();\n return null;\n }, error -> {\n logger.info(\"ServiceWorker registration failed: \" + error);\n return null;\n });\n } else {\n logger.info(\"Service worker is not supported by this browser.\");\n }\n }",
"public static int cudnnOpTensor(\n cudnnHandle handle, \n cudnnOpTensorDescriptor opTensorDesc, \n Pointer alpha1, \n cudnnTensorDescriptor aDesc, \n Pointer A, \n Pointer alpha2, \n cudnnTensorDescriptor bDesc, \n Pointer B, \n Pointer beta, \n cudnnTensorDescriptor cDesc, \n Pointer C)\n {\n return checkResult(cudnnOpTensorNative(handle, opTensorDesc, alpha1, aDesc, A, alpha2, bDesc, B, beta, cDesc, C));\n }",
"private void readWBS()\n {\n Map<Integer, List<MapRow>> levelMap = new HashMap<Integer, List<MapRow>>();\n for (MapRow row : m_tables.get(\"STR\"))\n {\n Integer level = row.getInteger(\"LEVEL_NUMBER\");\n List<MapRow> items = levelMap.get(level);\n if (items == null)\n {\n items = new ArrayList<MapRow>();\n levelMap.put(level, items);\n }\n items.add(row);\n }\n\n int level = 1;\n while (true)\n {\n List<MapRow> items = levelMap.get(Integer.valueOf(level++));\n if (items == null)\n {\n break;\n }\n\n for (MapRow row : items)\n {\n m_wbsFormat.parseRawValue(row.getString(\"CODE_VALUE\"));\n String parentWbsValue = m_wbsFormat.getFormattedParentValue();\n String wbsValue = m_wbsFormat.getFormattedValue();\n row.setObject(\"WBS\", wbsValue);\n row.setObject(\"PARENT_WBS\", parentWbsValue);\n }\n\n final AlphanumComparator comparator = new AlphanumComparator();\n Collections.sort(items, new Comparator<MapRow>()\n {\n @Override public int compare(MapRow o1, MapRow o2)\n {\n return comparator.compare(o1.getString(\"WBS\"), o2.getString(\"WBS\"));\n }\n });\n\n for (MapRow row : items)\n {\n String wbs = row.getString(\"WBS\");\n if (wbs != null && !wbs.isEmpty())\n {\n ChildTaskContainer parent = m_wbsMap.get(row.getString(\"PARENT_WBS\"));\n if (parent == null)\n {\n parent = m_projectFile;\n }\n\n Task task = parent.addTask();\n String name = row.getString(\"CODE_TITLE\");\n if (name == null || name.isEmpty())\n {\n name = wbs;\n }\n task.setName(name);\n task.setWBS(wbs);\n task.setSummary(true);\n m_wbsMap.put(wbs, task);\n }\n }\n }\n }",
"public void setAttributes(Object feature, Map<String, Attribute> attributes) throws LayerException {\n\t\tfor (Map.Entry<String, Attribute> entry : attributes.entrySet()) {\n\t\t\tString name = entry.getKey();\n\t\t\tif (!name.equals(getGeometryAttributeName())) {\n\t\t\t\tasFeature(feature).setAttribute(name, entry.getValue());\n\t\t\t}\n\t\t}\n\t}",
"private static void addFormatInfoEval(byte[] eval, int size, EccLevel ecc_level, int pattern) {\n\n int format = pattern;\n int seq;\n int i;\n\n switch(ecc_level) {\n case L: format += 0x08; break;\n case Q: format += 0x18; break;\n case H: format += 0x10; break;\n }\n\n seq = QR_ANNEX_C[format];\n\n for (i = 0; i < 6; i++) {\n eval[(i * size) + 8] = (byte) ((((seq >> i) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);\n }\n\n for (i = 0; i < 8; i++) {\n eval[(8 * size) + (size - i - 1)] = (byte) ((((seq >> i) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);\n }\n\n for (i = 0; i < 6; i++) {\n eval[(8 * size) + (5 - i)] = (byte) ((((seq >> (i + 9)) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);\n }\n\n for (i = 0; i < 7; i++) {\n eval[(((size - 7) + i) * size) + 8] = (byte) ((((seq >> (i + 8)) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);\n }\n\n eval[(7 * size) + 8] = (byte) ((((seq >> 6) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);\n eval[(8 * size) + 8] = (byte) ((((seq >> 7) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);\n eval[(8 * size) + 7] = (byte) ((((seq >> 8) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);\n }",
"public static <T> DatabaseTableConfig<T> fromReader(BufferedReader reader) throws SQLException {\n\t\tDatabaseTableConfig<T> config = new DatabaseTableConfig<T>();\n\t\tboolean anything = false;\n\t\twhile (true) {\n\t\t\tString line;\n\t\t\ttry {\n\t\t\t\tline = reader.readLine();\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow SqlExceptionUtil.create(\"Could not read DatabaseTableConfig from stream\", e);\n\t\t\t}\n\t\t\tif (line == null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// we do this so we can support multiple class configs per file\n\t\t\tif (line.equals(CONFIG_FILE_END_MARKER)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// we do this so we can support multiple class configs per file\n\t\t\tif (line.equals(CONFIG_FILE_FIELDS_START)) {\n\t\t\t\treadFields(reader, config);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// skip empty lines or comments\n\t\t\tif (line.length() == 0 || line.startsWith(\"#\") || line.equals(CONFIG_FILE_START_MARKER)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tString[] parts = line.split(\"=\", -2);\n\t\t\tif (parts.length != 2) {\n\t\t\t\tthrow new SQLException(\"DatabaseTableConfig reading from stream cannot parse line: \" + line);\n\t\t\t}\n\t\t\treadTableField(config, parts[0], parts[1]);\n\t\t\tanything = true;\n\t\t}\n\t\t// if we got any config lines then we return the config\n\t\tif (anything) {\n\t\t\treturn config;\n\t\t} else {\n\t\t\t// otherwise we return null for none\n\t\t\treturn null;\n\t\t}\n\t}",
"public final URI render(\n final MapfishMapContext mapContext,\n final ScalebarAttributeValues scalebarParams,\n final File tempFolder,\n final Template template)\n throws IOException, ParserConfigurationException {\n final double dpi = mapContext.getDPI();\n\n // get the map bounds\n final Rectangle paintArea = new Rectangle(mapContext.getMapSize());\n MapBounds bounds = mapContext.getBounds();\n\n final DistanceUnit mapUnit = getUnit(bounds);\n final Scale scale = bounds.getScale(paintArea, PDF_DPI);\n final double scaleDenominator = scale.getDenominator(scalebarParams.geodetic,\n bounds.getProjection(), dpi, bounds.getCenter());\n\n DistanceUnit scaleUnit = scalebarParams.getUnit();\n if (scaleUnit == null) {\n scaleUnit = mapUnit;\n }\n\n // adjust scalebar width and height to the DPI value\n final double maxLengthInPixel = (scalebarParams.getOrientation().isHorizontal()) ?\n scalebarParams.getSize().width : scalebarParams.getSize().height;\n\n final double maxIntervalLengthInWorldUnits = DistanceUnit.PX.convertTo(maxLengthInPixel, scaleUnit)\n * scaleDenominator / scalebarParams.intervals;\n final double niceIntervalLengthInWorldUnits =\n getNearestNiceValue(maxIntervalLengthInWorldUnits, scaleUnit, scalebarParams.lockUnits);\n\n final ScaleBarRenderSettings settings = new ScaleBarRenderSettings();\n settings.setParams(scalebarParams);\n settings.setMaxSize(scalebarParams.getSize());\n settings.setPadding(getPadding(settings));\n\n // start the rendering\n File path = null;\n if (template.getConfiguration().renderAsSvg(scalebarParams.renderAsSvg)) {\n // render scalebar as SVG\n final SVGGraphics2D graphics2D = CreateMapProcessor.createSvgGraphics(scalebarParams.getSize());\n\n try {\n tryLayout(\n graphics2D, scaleUnit, scaleDenominator,\n niceIntervalLengthInWorldUnits, settings, 0);\n\n path = File.createTempFile(\"scalebar-graphic-\", \".svg\", tempFolder);\n CreateMapProcessor.saveSvgFile(graphics2D, path);\n } finally {\n graphics2D.dispose();\n }\n } else {\n // render scalebar as raster graphic\n double dpiRatio = mapContext.getDPI() / PDF_DPI;\n final BufferedImage bufferedImage = new BufferedImage(\n (int) Math.round(scalebarParams.getSize().width * dpiRatio),\n (int) Math.round(scalebarParams.getSize().height * dpiRatio),\n TYPE_4BYTE_ABGR);\n final Graphics2D graphics2D = bufferedImage.createGraphics();\n\n try {\n AffineTransform saveAF = new AffineTransform(graphics2D.getTransform());\n graphics2D.scale(dpiRatio, dpiRatio);\n tryLayout(\n graphics2D, scaleUnit, scaleDenominator,\n niceIntervalLengthInWorldUnits, settings, 0);\n graphics2D.setTransform(saveAF);\n\n path = File.createTempFile(\"scalebar-graphic-\", \".png\", tempFolder);\n ImageUtils.writeImage(bufferedImage, \"png\", path);\n } finally {\n graphics2D.dispose();\n }\n }\n\n return path.toURI();\n }"
] |
Log long string using verbose tag
@param TAG The tag.
@param longString The long string. | [
"public static void logLong(String TAG, String longString) {\n InputStream is = new ByteArrayInputStream( longString.getBytes() );\n @SuppressWarnings(\"resource\")\n Scanner scan = new Scanner(is);\n while (scan.hasNextLine()) {\n Log.v(TAG, scan.nextLine());\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 Where<T, ID> not() {\n\t\t/*\n\t\t * Special circumstance here when we have a needs future with a not. Something like and().not().like(...). In\n\t\t * this case we satisfy the and()'s future as the not() but the not() becomes the new needs-future.\n\t\t */\n\t\tNot not = new Not();\n\t\taddClause(not);\n\t\taddNeedsFuture(not);\n\t\treturn this;\n\t}",
"public void setImage(final GVRImage imageData)\n {\n mImage = imageData;\n if (imageData != null)\n NativeTexture.setImage(getNative(), imageData, imageData.getNative());\n else\n NativeTexture.setImage(getNative(), null, 0);\n }",
"public void validateUniqueIDsForMicrosoftProject()\n {\n if (!isEmpty())\n {\n for (T entity : this)\n {\n if (NumberHelper.getInt(entity.getUniqueID()) > MS_PROJECT_MAX_UNIQUE_ID)\n {\n renumberUniqueIDs();\n break;\n }\n }\n }\n }",
"private void initializeLogging() {\n\t\t// Since logging is static, make sure this is done only once even if\n\t\t// multiple clients are created (e.g., during tests)\n\t\tif (consoleAppender != null) {\n\t\t\treturn;\n\t\t}\n\n\t\tconsoleAppender = new ConsoleAppender();\n\t\tconsoleAppender.setLayout(new PatternLayout(LOG_PATTERN));\n\t\tconsoleAppender.setThreshold(Level.INFO);\n\t\tLevelRangeFilter filter = new LevelRangeFilter();\n\t\tfilter.setLevelMin(Level.TRACE);\n\t\tfilter.setLevelMax(Level.INFO);\n\t\tconsoleAppender.addFilter(filter);\n\t\tconsoleAppender.activateOptions();\n\t\torg.apache.log4j.Logger.getRootLogger().addAppender(consoleAppender);\n\n\t\terrorAppender = new ConsoleAppender();\n\t\terrorAppender.setLayout(new PatternLayout(LOG_PATTERN));\n\t\terrorAppender.setThreshold(Level.WARN);\n\t\terrorAppender.setTarget(ConsoleAppender.SYSTEM_ERR);\n\t\terrorAppender.activateOptions();\n\t\torg.apache.log4j.Logger.getRootLogger().addAppender(errorAppender);\n\t}",
"public static <T> boolean addAll(Collection<T> target, Iterable<? extends T> iterable) {\n if (iterable instanceof Collection) {\n return target.addAll((Collection<? extends T>) iterable);\n }\n return Iterators.addAll(target, iterable.iterator());\n }",
"private void addSubMatrixVariables(List<TokenList.Token> inputs, List<Variable> variables) {\n for (int i = 0; i < inputs.size(); i++) {\n TokenList.Token t = inputs.get(i);\n if( t.getType() != Type.VARIABLE )\n throw new ParseError(\"Expected variables only in sub-matrix input, not \"+t.getType());\n Variable v = t.getVariable();\n if( v.getType() == VariableType.INTEGER_SEQUENCE || isVariableInteger(t) ) {\n variables.add(v);\n } else {\n throw new ParseError(\"Expected an integer, integer sequence, or array range to define a submatrix\");\n }\n }\n }",
"public void setStringValue(String value) {\n\n if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(value)) {\n try {\n m_editValue = CmsLocationValue.parse(value);\n m_currentValue = m_editValue.cloneValue();\n displayValue();\n if ((m_popup != null) && m_popup.isVisible()) {\n m_popupContent.displayValues(m_editValue);\n updateMarkerPosition();\n }\n } catch (Exception e) {\n CmsLog.log(e.getLocalizedMessage() + \"\\n\" + CmsClientStringUtil.getStackTrace(e, \"\\n\"));\n }\n } else {\n m_currentValue = null;\n displayValue();\n }\n }",
"private static XMLStreamException unexpectedElement(final XMLStreamReader reader) {\n return SecurityManagerLogger.ROOT_LOGGER.unexpectedElement(reader.getName(), reader.getLocation());\n }"
] |
Return the lines of a CharSequence as a List of String.
@param self a CharSequence object
@return a list of lines
@throws java.io.IOException if an error occurs
@since 1.8.2 | [
"public static List<String> readLines(CharSequence self) throws IOException {\n return IOGroovyMethods.readLines(new StringReader(self.toString()));\n }"
] | [
"public static String trim(String s, int maxWidth) {\r\n if (s.length() <= maxWidth) {\r\n return (s);\r\n }\r\n return (s.substring(0, maxWidth));\r\n }",
"private JarFile loadJar(File archive) throws DecompilationException\n {\n try\n {\n return new JarFile(archive);\n }\n catch (IOException ex)\n {\n throw new DecompilationException(\"Can't load .jar: \" + archive.getPath(), ex);\n }\n }",
"protected boolean _load ()\r\n {\r\n java.sql.ResultSet rs = null;\r\n try\r\n {\r\n // This synchronization is necessary for Oracle JDBC drivers 8.1.7, 9.0.1, 9.2.0.1\r\n // The documentation says synchronization is done within the driver, but they\r\n // must have overlooked something. Without the lock we'd get mysterious error\r\n // messages. \r\n synchronized(getDbMeta())\r\n {\r\n getDbMetaTreeModel().setStatusBarMessage(\"Reading columns for table \" + getSchema().getCatalog().getCatalogName() + \".\" + getSchema().getSchemaName() + \".\" + getTableName());\r\n rs = getDbMeta().getColumns(getSchema().getCatalog().getCatalogName(), \r\n getSchema().getSchemaName(),\r\n getTableName(), \"%\");\r\n final java.util.ArrayList alNew = new java.util.ArrayList();\r\n while (rs.next())\r\n {\r\n alNew.add(new DBMetaColumnNode(getDbMeta(), getDbMetaTreeModel(), DBMetaTableNode.this, rs.getString(\"COLUMN_NAME\")));\r\n }\r\n alChildren = alNew; \r\n javax.swing.SwingUtilities.invokeLater(new Runnable()\r\n {\r\n public void run()\r\n {\r\n getDbMetaTreeModel().nodeStructureChanged(DBMetaTableNode.this);\r\n }\r\n });\r\n rs.close();\r\n }\r\n }\r\n catch (java.sql.SQLException sqlEx)\r\n {\r\n this.getDbMetaTreeModel().reportSqlError(\"Error retrieving columns\", sqlEx);\r\n try\r\n {\r\n if (rs != null) rs.close ();\r\n }\r\n catch (java.sql.SQLException sqlEx2)\r\n {\r\n this.getDbMetaTreeModel().reportSqlError(\"Error retrieving columns\", sqlEx2);\r\n }\r\n return false;\r\n }\r\n return true;\r\n }",
"private ProjectFile readTextFile(InputStream inputStream) throws MPXJException\n {\n ProjectReader reader = new AstaTextFileReader();\n addListeners(reader);\n return reader.read(inputStream);\n }",
"private void processTasks(Gantt gantt)\n {\n ProjectCalendar calendar = m_projectFile.getDefaultCalendar();\n\n for (Gantt.Tasks.Task ganttTask : gantt.getTasks().getTask())\n {\n String wbs = ganttTask.getID();\n ChildTaskContainer parentTask = getParentTask(wbs);\n\n Task task = parentTask.addTask();\n //ganttTask.getB() // bar type\n //ganttTask.getBC() // bar color\n task.setCost(ganttTask.getC());\n task.setName(ganttTask.getContent());\n task.setDuration(ganttTask.getD());\n task.setDeadline(ganttTask.getDL());\n //ganttTask.getH() // height\n //ganttTask.getIn(); // indent\n task.setWBS(wbs);\n task.setPercentageComplete(ganttTask.getPC());\n task.setStart(ganttTask.getS());\n //ganttTask.getU(); // Unknown\n //ganttTask.getVA(); // Valign\n\n task.setFinish(calendar.getDate(task.getStart(), task.getDuration(), false));\n m_taskMap.put(wbs, task);\n }\n }",
"public String get(final String key) {\n final Collection<Argument> args = map.get(key);\n if (args != null) {\n return args.iterator().hasNext() ? args.iterator().next().getValue() : null;\n }\n return null;\n }",
"public static Map<String, List<String>> getResponseHeaders(String stringUrl) throws IOException {\n return getResponseHeaders(stringUrl, true);\n }",
"public OperationTransformerEntry resolveOperationTransformer(final PathAddress address, final String operationName, PlaceholderResolver placeholderResolver) {\n final Iterator<PathElement> iterator = address.iterator();\n final OperationTransformerEntry entry = resolveOperationTransformer(iterator, operationName, placeholderResolver);\n if(entry != null) {\n return entry;\n }\n // Default is forward unchanged\n return FORWARD;\n }",
"public BoxFile.Info getFileInfo(String fileID) {\n URL url = FILE_INFO_URL_TEMPLATE.build(this.api.getBaseURL(), fileID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n BoxFile file = new BoxFile(this.api, jsonObject.get(\"id\").asString());\n return file.new Info(response.getJSON());\n }"
] |
EAP 7.1 | [
"private void buildTransformers_4_0(ResourceTransformationDescriptionBuilder builder) {\n\n // We need to do custom transformation of the attribute in the root resource\n // related to endpoint configs, as these were moved to the root from a previous child resource\n EndPointWriteTransformer endPointWriteTransformer = new EndPointWriteTransformer();\n builder.getAttributeBuilder()\n .setDiscard(DiscardAttributeChecker.ALWAYS, endpointAttrArray)\n .end()\n .addOperationTransformationOverride(\"add\")\n //.inheritResourceAttributeDefinitions() // don't inherit as we discard\n .setCustomOperationTransformer(new EndPointAddTransformer())\n .end()\n .addOperationTransformationOverride(\"write-attribute\")\n //.inheritResourceAttributeDefinitions() // don't inherit as we discard\n .setCustomOperationTransformer(endPointWriteTransformer)\n .end()\n .addOperationTransformationOverride(\"undefine-attribute\")\n //.inheritResourceAttributeDefinitions() // don't inherit as we discard\n .setCustomOperationTransformer(endPointWriteTransformer)\n .end();\n }"
] | [
"public void updateExceptions(SortedSet<Date> exceptions) {\r\n\r\n SortedSet<Date> e = null == exceptions ? new TreeSet<Date>() : exceptions;\r\n if (!m_model.getExceptions().equals(e)) {\r\n m_model.setExceptions(e);\r\n m_view.updateExceptions();\r\n valueChanged();\r\n sizeChanged();\r\n }\r\n\r\n }",
"public static int cudnnConvolutionForward(\n cudnnHandle handle, \n Pointer alpha, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n cudnnFilterDescriptor wDesc, \n Pointer w, \n cudnnConvolutionDescriptor convDesc, \n int algo, \n Pointer workSpace, \n long workSpaceSizeInBytes, \n Pointer beta, \n cudnnTensorDescriptor yDesc, \n Pointer y)\n {\n return checkResult(cudnnConvolutionForwardNative(handle, alpha, xDesc, x, wDesc, w, convDesc, algo, workSpace, workSpaceSizeInBytes, beta, yDesc, y));\n }",
"private void registerRows() {\n\t\tfor (int i = 0; i < rows.length; i++) {\n\t\t\tDJCrosstabRow crosstabRow = rows[i];\n\n\t\t\tJRDesignCrosstabRowGroup ctRowGroup = new JRDesignCrosstabRowGroup();\n\n\t\t\tctRowGroup.setWidth(crosstabRow.getHeaderWidth());\n\n\t\t\tctRowGroup.setName(crosstabRow.getProperty().getProperty());\n\n\t\t\tJRDesignCrosstabBucket rowBucket = new JRDesignCrosstabBucket();\n\n //New in JR 4.1+\n rowBucket.setValueClassName(crosstabRow.getProperty().getValueClassName());\n\n\t\t\tctRowGroup.setBucket(rowBucket);\n\n\t\t\tJRDesignExpression bucketExp = ExpressionUtils.createExpression(\"$F{\"+crosstabRow.getProperty().getProperty()+\"}\", crosstabRow.getProperty().getValueClassName());\n\t\t\trowBucket.setExpression(bucketExp);\n\n\n\t\t\tJRDesignCellContents rowHeaderContents = new JRDesignCellContents();\n\t\t\tJRDesignTextField rowTitle = new JRDesignTextField();\n\n\t\t\tJRDesignExpression rowTitExp = new JRDesignExpression();\n\t\t\trowTitExp.setValueClassName(crosstabRow.getProperty().getValueClassName());\n\t\t\trowTitExp.setText(\"$V{\"+crosstabRow.getProperty().getProperty()+\"}\");\n\n\t\t\trowTitle.setExpression(rowTitExp);\n\t\t\trowTitle.setWidth(crosstabRow.getHeaderWidth());\n\n\t\t\t//The width can be the sum of the with of all the rows starting from the current one, up to the inner most one.\n\t\t\tint auxHeight = getRowHeaderMaxHeight(crosstabRow);\n//\t\t\tint auxHeight = crosstabRow.getHeight(); //FIXME getRowHeaderMaxHeight() must be FIXED because it breaks when 1rs row shows total and 2nd doesn't\n\t\t\trowTitle.setHeight(auxHeight);\n\n\t\t\tStyle headerstyle = crosstabRow.getHeaderStyle() == null ? this.djcross.getRowHeaderStyle(): crosstabRow.getHeaderStyle();\n\n\t\t\tif (headerstyle != null){\n\t\t\t\tlayoutManager.applyStyleToElement(headerstyle, rowTitle);\n\t\t\t\trowHeaderContents.setBackcolor(headerstyle.getBackgroundColor());\n\t\t\t}\n\n\t\t\trowHeaderContents.addElement(rowTitle);\n\t\t\trowHeaderContents.setMode( ModeEnum.OPAQUE );\n\n\t\t\tboolean fullBorder = i <= 0; //Only outer most will have full border\n\t\t\tapplyCellBorder(rowHeaderContents, false, fullBorder);\n\n\t\t\tctRowGroup.setHeader(rowHeaderContents );\n\n\t\t\tif (crosstabRow.isShowTotals())\n\t\t\t\tcreateRowTotalHeader(ctRowGroup,crosstabRow,fullBorder);\n\n\n\t\t\ttry {\n\t\t\t\tjrcross.addRowGroup(ctRowGroup);\n\t\t\t} catch (JRException e) {\n\t\t\t\tlog.error(e.getMessage(),e);\n\t\t\t}\n\n\t\t}\n\t}",
"public static Class<?>[] toClassArray(Collection<Class<?>> collection) {\n\t\tif (collection == null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn collection.toArray(new Class<?>[collection.size()]);\n\t}",
"public int getIndexFromOffset(int offset)\n {\n int result = -1;\n\n for (int loop = 0; loop < m_offset.length; loop++)\n {\n if (m_offset[loop] == offset)\n {\n result = loop;\n break;\n }\n }\n\n return (result);\n }",
"public static byte[] decodeBase64(String value) {\n int byteShift = 4;\n int tmp = 0;\n boolean done = false;\n final StringBuilder buffer = new StringBuilder();\n\n for (int i = 0; i != value.length(); i++) {\n final char c = value.charAt(i);\n final int sixBit = (c < 123) ? EncodingGroovyMethodsSupport.TRANSLATE_TABLE[c] : 66;\n\n if (sixBit < 64) {\n if (done)\n throw new RuntimeException(\"= character not at end of base64 value\"); // TODO: change this exception type\n\n tmp = (tmp << 6) | sixBit;\n\n if (byteShift-- != 4) {\n buffer.append((char) ((tmp >> (byteShift * 2)) & 0XFF));\n }\n\n } else if (sixBit == 64) {\n\n byteShift--;\n done = true;\n\n } else if (sixBit == 66) {\n // RFC 2045 says that I'm allowed to take the presence of\n // these characters as evidence of data corruption\n // So I will\n throw new RuntimeException(\"bad character in base64 value\"); // TODO: change this exception type\n }\n\n if (byteShift == 0) byteShift = 4;\n }\n\n try {\n return buffer.toString().getBytes(\"ISO-8859-1\");\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(\"Base 64 decode produced byte values > 255\"); // TODO: change this exception type\n }\n }",
"public 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 Class<T> getProxyClass() {\n String suffix = \"_$$_Weld\" + getProxyNameSuffix();\n String proxyClassName = getBaseProxyName();\n if (!proxyClassName.endsWith(suffix)) {\n proxyClassName = proxyClassName + suffix;\n }\n if (proxyClassName.startsWith(JAVA)) {\n proxyClassName = proxyClassName.replaceFirst(JAVA, \"org.jboss.weld\");\n }\n Class<T> proxyClass = null;\n Class<?> originalClass = bean != null ? bean.getBeanClass() : proxiedBeanType;\n BeanLogger.LOG.generatingProxyClass(proxyClassName);\n try {\n // First check to see if we already have this proxy class\n proxyClass = cast(classLoader == null? proxyServices.loadClass(originalClass, proxyClassName) : classLoader.loadClass(proxyClassName));\n } catch (ClassNotFoundException e) {\n // Create the proxy class for this instance\n try {\n proxyClass = createProxyClass(originalClass, proxyClassName);\n } catch (Throwable e1) {\n //attempt to load the class again, just in case another thread\n //defined it between the check and the create method\n try {\n proxyClass = cast(classLoader == null? proxyServices.loadClass(originalClass, proxyClassName) : classLoader.loadClass(proxyClassName));\n } catch (ClassNotFoundException e2) {\n BeanLogger.LOG.catchingDebug(e1);\n throw BeanLogger.LOG.unableToLoadProxyClass(bean, proxiedBeanType, e1);\n }\n }\n }\n return proxyClass;\n }",
"public void setSizes(Collection<Size> sizes) {\r\n for (Size size : sizes) {\r\n if (size.getLabel() == Size.SMALL) {\r\n smallSize = size;\r\n } else if (size.getLabel() == Size.SQUARE) {\r\n squareSize = size;\r\n } else if (size.getLabel() == Size.THUMB) {\r\n thumbnailSize = size;\r\n } else if (size.getLabel() == Size.MEDIUM) {\r\n mediumSize = size;\r\n } else if (size.getLabel() == Size.LARGE) {\r\n largeSize = size;\r\n } else if (size.getLabel() == Size.LARGE_1600) {\r\n large1600Size = size;\r\n } else if (size.getLabel() == Size.LARGE_2048) {\r\n large2048Size = size;\r\n } else if (size.getLabel() == Size.ORIGINAL) {\r\n originalSize = size;\r\n } else if (size.getLabel() == Size.SQUARE_LARGE) {\r\n squareLargeSize = size;\r\n } else if (size.getLabel() == Size.SMALL_320) {\r\n small320Size = size;\r\n } else if (size.getLabel() == Size.MEDIUM_640) {\r\n medium640Size = size;\r\n } else if (size.getLabel() == Size.MEDIUM_800) {\r\n medium800Size = size;\r\n } else if (size.getLabel() == Size.VIDEO_PLAYER) {\r\n videoPlayer = size;\r\n } else if (size.getLabel() == Size.SITE_MP4) {\r\n siteMP4 = size;\r\n } else if (size.getLabel() == Size.VIDEO_ORIGINAL) {\r\n videoOriginal = size;\r\n }\r\n else if (size.getLabel() == Size.MOBILE_MP4) {\r\n \tmobileMP4 = size;\r\n }\r\n else if (size.getLabel() == Size.HD_MP4) {\r\n \thdMP4 = size;\r\n }\r\n }\r\n }"
] |
Record the checkout queue length
@param dest Destination of the socket to checkout. Will actually record
if null. Otherwise will call this on self and corresponding child
with this param null.
@param queueLength The number of entries in the "synchronous" checkout
queue. | [
"public void recordCheckoutQueueLength(SocketDestination dest, int queueLength) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordCheckoutQueueLength(null, queueLength);\n recordCheckoutQueueLength(null, queueLength);\n } else {\n this.checkoutQueueLengthHistogram.insert(queueLength);\n checkMonitoringInterval();\n }\n }"
] | [
"public static appfwpolicylabel_stats get(nitro_service service, String labelname) throws Exception{\n\t\tappfwpolicylabel_stats obj = new appfwpolicylabel_stats();\n\t\tobj.set_labelname(labelname);\n\t\tappfwpolicylabel_stats response = (appfwpolicylabel_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"public static boolean isTodoItem(final Document todoItemDoc) {\n return todoItemDoc.containsKey(ID_KEY)\n && todoItemDoc.containsKey(TASK_KEY)\n && todoItemDoc.containsKey(CHECKED_KEY);\n }",
"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}",
"private void resetCalendar() {\n _calendar = getCalendar();\n if (_defaultTimeZone != null) {\n _calendar.setTimeZone(_defaultTimeZone);\n }\n _currentYear = _calendar.get(Calendar.YEAR);\n }",
"private static final double printDurationFractionsOfMinutes(Duration duration, int factor)\n {\n double result = 0;\n\n if (duration != null)\n {\n result = duration.getDuration();\n\n switch (duration.getUnits())\n {\n case HOURS:\n case ELAPSED_HOURS:\n {\n result *= 60;\n break;\n }\n\n case DAYS:\n {\n result *= (60 * 8);\n break;\n }\n\n case ELAPSED_DAYS:\n {\n result *= (60 * 24);\n break;\n }\n\n case WEEKS:\n {\n result *= (60 * 8 * 5);\n break;\n }\n\n case ELAPSED_WEEKS:\n {\n result *= (60 * 24 * 7);\n break;\n }\n\n case MONTHS:\n {\n result *= (60 * 8 * 5 * 4);\n break;\n }\n\n case ELAPSED_MONTHS:\n {\n result *= (60 * 24 * 30);\n break;\n }\n\n case YEARS:\n {\n result *= (60 * 8 * 5 * 52);\n break;\n }\n\n case ELAPSED_YEARS:\n {\n result *= (60 * 24 * 365);\n break;\n }\n\n default:\n {\n break;\n }\n }\n }\n\n result *= factor;\n\n return (result);\n }",
"public static synchronized void registerDao(ConnectionSource connectionSource, Dao<?, ?> dao) {\n\t\tif (connectionSource == null) {\n\t\t\tthrow new IllegalArgumentException(\"connectionSource argument cannot be null\");\n\t\t}\n\t\taddDaoToClassMap(new ClassConnectionSource(connectionSource, dao.getDataClass()), dao);\n\t}",
"public void setModelByText(String model) {\r\n try {\r\n InputStream is = new ByteArrayInputStream(model.getBytes());\r\n this.model = SCXMLParser.parse(new InputSource(is), null, customActionsFromTagExtensions());\r\n this.setStateMachine(this.model);\r\n } catch (IOException | SAXException | ModelException e) {\r\n e.printStackTrace();\r\n }\r\n }",
"protected void statusInfoMessage(final String tag) {\n if(logger.isInfoEnabled()) {\n logger.info(tag + \" : [partition: \" + currentPartition + \", partitionFetched: \"\n + currentPartitionFetched\n + \"] for store \" + storageEngine.getName());\n }\n }",
"public Client findClient(String clientUUID, Integer profileId) throws Exception {\n Client client = null;\n /* ERROR CODE: 500 WHEN TRYING TO DELETE A SERVER GROUP.\n THIS APPEARS TO BE BECAUSE CLIENT UUID IS NULL.\n */\n /* CODE ADDED TO PREVENT NULL POINTERS. */\n if (clientUUID == null) {\n clientUUID = \"\";\n }\n\n // first see if the clientUUID is actually a uuid.. it might be a friendlyName and need conversion\n /* A UUID IS A UNIVERSALLY UNIQUE IDENTIFIER. */\n if (clientUUID.compareTo(Constants.PROFILE_CLIENT_DEFAULT_ID) != 0 &&\n !clientUUID.matches(\"[\\\\w]{8}-[\\\\w]{4}-[\\\\w]{4}-[\\\\w]{4}-[\\\\w]{12}\")) {\n Client tmpClient = this.findClientFromFriendlyName(profileId, clientUUID);\n\n // if we can't find a client then fall back to the default ID\n if (tmpClient == null) {\n clientUUID = Constants.PROFILE_CLIENT_DEFAULT_ID;\n } else {\n return tmpClient;\n }\n }\n\n PreparedStatement statement = null;\n ResultSet results = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n String queryString = \"SELECT * FROM \" + Constants.DB_TABLE_CLIENT +\n \" WHERE \" + Constants.CLIENT_CLIENT_UUID + \" = ?\";\n\n if (profileId != null) {\n queryString += \" AND \" + Constants.GENERIC_PROFILE_ID + \"=?\";\n }\n\n statement = sqlConnection.prepareStatement(queryString);\n statement.setString(1, clientUUID);\n\n if (profileId != null) {\n statement.setInt(2, profileId);\n }\n\n results = statement.executeQuery();\n if (results.next()) {\n client = this.getClientFromResultSet(results);\n }\n } catch (Exception e) {\n throw e;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return client;\n }"
] |
Execute a redirected request
@param stringStatusCode
@param httpMethodProxyRequest
@param httpServletRequest
@param httpServletResponse
@throws Exception | [
"private void processRedirect(String stringStatusCode,\n HttpMethod httpMethodProxyRequest,\n HttpServletRequest httpServletRequest,\n HttpServletResponse httpServletResponse) throws Exception {\n // Check if the proxy response is a redirect\n // The following code is adapted from\n // org.tigris.noodle.filters.CheckForRedirect\n // Hooray for open source software\n\n String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();\n if (stringLocation == null) {\n throw new ServletException(\"Received status code: \"\n + stringStatusCode + \" but no \"\n + STRING_LOCATION_HEADER\n + \" header was found in the response\");\n }\n // Modify the redirect to go to this proxy servlet rather than the proxied host\n String stringMyHostName = httpServletRequest.getServerName();\n if (httpServletRequest.getServerPort() != 80) {\n stringMyHostName += \":\" + httpServletRequest.getServerPort();\n }\n stringMyHostName += httpServletRequest.getContextPath();\n httpServletResponse.sendRedirect(stringLocation.replace(\n getProxyHostAndPort() + this.getProxyPath(),\n stringMyHostName));\n }"
] | [
"public PersonTagList<PersonTag> getList(String photoId) throws FlickrException {\r\n\r\n // Delegating this to photos.people.PeopleInterface - Naming standard would be to use PeopleInterface but having 2 the same name can cause issues\r\n com.flickr4java.flickr.photos.people.PeopleInterface pi = new com.flickr4java.flickr.photos.people.PeopleInterface(apiKey, sharedSecret, transportAPI);\r\n return pi.getList(photoId);\r\n }",
"private void addProgressInterceptor() {\n httpClient.networkInterceptors().add(new Interceptor() {\n @Override\n public Response intercept(Interceptor.Chain chain) throws IOException {\n final Request request = chain.request();\n final Response originalResponse = chain.proceed(request);\n if (request.tag() instanceof ApiCallback) {\n final ApiCallback callback = (ApiCallback) request.tag();\n return originalResponse.newBuilder()\n .body(new ProgressResponseBody(originalResponse.body(), callback)).build();\n }\n return originalResponse;\n }\n });\n }",
"public String getString(Integer type)\n {\n String result = null;\n\n byte[] item = m_map.get(type);\n if (item != null)\n {\n result = m_data.getString(getOffset(item));\n }\n\n return (result);\n }",
"public List<DbLicense> getModuleLicenses(final String moduleId,\n final LicenseMatcher licenseMatcher) {\n final DbModule module = getModule(moduleId);\n\n final List<DbLicense> licenses = new ArrayList<>();\n final FiltersHolder filters = new FiltersHolder();\n final ArtifactHandler artifactHandler = new ArtifactHandler(repositoryHandler, licenseMatcher);\n\n for (final String gavc : DataUtils.getAllArtifacts(module)) {\n licenses.addAll(artifactHandler.getArtifactLicenses(gavc, filters));\n }\n\n return licenses;\n }",
"public void checkConstraints(String checkLevel) throws ConstraintException\r\n {\r\n // now checking constraints\r\n FieldDescriptorConstraints fieldConstraints = new FieldDescriptorConstraints();\r\n ReferenceDescriptorConstraints refConstraints = new ReferenceDescriptorConstraints();\r\n CollectionDescriptorConstraints collConstraints = new CollectionDescriptorConstraints();\r\n\r\n for (Iterator it = getFields(); it.hasNext();)\r\n {\r\n fieldConstraints.check((FieldDescriptorDef)it.next(), checkLevel);\r\n }\r\n for (Iterator it = getReferences(); it.hasNext();)\r\n {\r\n refConstraints.check((ReferenceDescriptorDef)it.next(), checkLevel);\r\n }\r\n for (Iterator it = getCollections(); it.hasNext();)\r\n {\r\n collConstraints.check((CollectionDescriptorDef)it.next(), checkLevel);\r\n }\r\n new ClassDescriptorConstraints().check(this, checkLevel);\r\n }",
"@UiHandler(\"m_atNumber\")\r\n void onWeekOfMonthChange(ValueChangeEvent<String> event) {\r\n\r\n if (handleChange()) {\r\n m_controller.setWeekOfMonth(event.getValue());\r\n }\r\n }",
"public void setDefaults(Annotation[] defaultAnnotations) {\n if (defaultAnnotations == null) {\n return;\n }\n for (Annotation each : defaultAnnotations) {\n Class<? extends Annotation> key = each.annotationType();\n if (Title.class.equals(key) || Description.class.equals(key)) {\n continue;\n }\n if (!annotations.containsKey(key)) {\n annotations.put(key, each);\n }\n }\n }",
"public Map<String, String> decompose(Frontier frontier, String modelText) {\r\n if (!(frontier instanceof SCXMLFrontier)) {\r\n return null;\r\n }\n\r\n TransitionTarget target = ((SCXMLFrontier) frontier).getRoot().nextState;\r\n Map<String, String> variables = ((SCXMLFrontier) frontier).getRoot().variables;\n\r\n Map<String, String> decomposition = new HashMap<String, String>();\r\n decomposition.put(\"target\", target.getId());\n\r\n StringBuilder packedVariables = new StringBuilder();\r\n for (Map.Entry<String, String> variable : variables.entrySet()) {\r\n packedVariables.append(variable.getKey());\r\n packedVariables.append(\"::\");\r\n packedVariables.append(variable.getValue());\r\n packedVariables.append(\";\");\r\n }\n\r\n decomposition.put(\"variables\", packedVariables.toString());\r\n decomposition.put(\"model\", modelText);\n\r\n return decomposition;\r\n }",
"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 }"
] |
Returns a client model from a ResultSet
@param result resultset containing client information
@return Client or null
@throws Exception exception | [
"private Client getClientFromResultSet(ResultSet result) throws Exception {\n Client client = new Client();\n client.setId(result.getInt(Constants.GENERIC_ID));\n client.setUUID(result.getString(Constants.CLIENT_CLIENT_UUID));\n client.setFriendlyName(result.getString(Constants.CLIENT_FRIENDLY_NAME));\n client.setProfile(ProfileService.getInstance().findProfile(result.getInt(Constants.GENERIC_PROFILE_ID)));\n client.setIsActive(result.getBoolean(Constants.CLIENT_IS_ACTIVE));\n client.setActiveServerGroup(result.getInt(Constants.CLIENT_ACTIVESERVERGROUP));\n return client;\n }"
] | [
"private ClassDescriptorDef ensureClassDef(XClass original)\r\n {\r\n String name = original.getQualifiedName();\r\n ClassDescriptorDef classDef = _model.getClass(name);\r\n\r\n if (classDef == null)\r\n {\r\n classDef = new ClassDescriptorDef(original);\r\n _model.addClass(classDef);\r\n }\r\n return classDef;\r\n }",
"public synchronized List<String> propertyListOf(Class<?> c) {\n String cn = c.getName();\n List<String> ls = repo.get(cn);\n if (ls != null) {\n return ls;\n }\n Set<Class<?>> circularReferenceDetector = new HashSet<>();\n ls = propertyListOf(c, circularReferenceDetector, null);\n repo.put(c.getName(), ls);\n return ls;\n }",
"public <T> T get(String key, Class<T> type) {\n Object value = this.data.get(key);\n if (value != null && type.isAssignableFrom(value.getClass())) {\n return (T) value;\n }\n return null;\n }",
"@SuppressWarnings(\"serial\")\n private Button createSaveExitButton() {\n\n Button saveExitBtn = CmsToolBar.createButton(\n FontOpenCms.SAVE_EXIT,\n m_messages.key(Messages.GUI_BUTTON_SAVE_AND_EXIT_0));\n saveExitBtn.addClickListener(new ClickListener() {\n\n public void buttonClick(ClickEvent event) {\n\n saveAction();\n closeAction();\n\n }\n });\n saveExitBtn.setEnabled(false);\n return saveExitBtn;\n }",
"@Override\n public final Double optDouble(final String key, final Double defaultValue) {\n Double result = optDouble(key);\n return result == null ? defaultValue : result;\n }",
"public static String getSerializedVectorClock(VectorClock vc) {\n VectorClockWrapper vcWrapper = new VectorClockWrapper(vc);\n String serializedVC = \"\";\n try {\n serializedVC = mapper.writeValueAsString(vcWrapper);\n } catch(Exception e) {\n e.printStackTrace();\n }\n return serializedVC;\n }",
"public synchronized Message menuRequestTyped(Message.KnownType requestType, Message.MenuIdentifier targetMenu,\n CdjStatus.TrackSourceSlot slot, CdjStatus.TrackType trackType, Field... arguments)\n throws IOException {\n\n if (!menuLock.isHeldByCurrentThread()) {\n throw new IllegalStateException(\"renderMenuItems() cannot be called without first successfully calling tryLockingForMenuOperation()\");\n }\n\n Field[] combinedArguments = new Field[arguments.length + 1];\n combinedArguments[0] = buildRMST(targetMenu, slot, trackType);\n System.arraycopy(arguments, 0, combinedArguments, 1, arguments.length);\n final Message response = simpleRequest(requestType, Message.KnownType.MENU_AVAILABLE, combinedArguments);\n final NumberField reportedRequestType = (NumberField)response.arguments.get(0);\n if (reportedRequestType.getValue() != requestType.protocolValue) {\n throw new IOException(\"Menu request did not return result for same type as request; sent type: \" +\n requestType.protocolValue + \", received type: \" + reportedRequestType.getValue() +\n \", response: \" + response);\n }\n return response;\n }",
"private void appendJoinSQL92(Join join, StringBuffer where, StringBuffer buf)\r\n {\r\n if (join.isOuter)\r\n {\r\n buf.append(\" LEFT OUTER JOIN \");\r\n }\r\n else\r\n {\r\n buf.append(\" INNER JOIN \");\r\n }\r\n if (join.right.hasJoins())\r\n {\r\n buf.append(\"(\");\r\n appendTableWithJoins(join.right, where, buf);\r\n buf.append(\")\");\r\n }\r\n else\r\n {\r\n appendTableWithJoins(join.right, where, buf);\r\n }\r\n buf.append(\" ON \");\r\n join.appendJoinEqualities(buf);\r\n }",
"public static void hideOnlyChannels(Object... channels){\r\n for(LogRecordHandler handler : handlers){\r\n if(handler instanceof VisibilityHandler){\r\n VisibilityHandler visHandler = (VisibilityHandler) handler;\r\n visHandler.showAll();\r\n for (Object channel : channels) {\r\n visHandler.alsoHide(channel);\r\n }\r\n }\r\n }\r\n }"
] |
Adds the parent package to the java.protocol.handler.pkgs system property. | [
"public static void configureProtocolHandler() {\n final String pkgs = System.getProperty(\"java.protocol.handler.pkgs\");\n String newValue = \"org.mapfish.print.url\";\n if (pkgs != null && !pkgs.contains(newValue)) {\n newValue = newValue + \"|\" + pkgs;\n } else if (pkgs != null) {\n newValue = pkgs;\n }\n System.setProperty(\"java.protocol.handler.pkgs\", newValue);\n }"
] | [
"private void writeBooleanField(String fieldName, Object value) throws IOException\n {\n boolean val = ((Boolean) value).booleanValue();\n if (val)\n {\n m_writer.writeNameValuePair(fieldName, val);\n }\n }",
"public static base_response unset(nitro_service client, snmpoption resource, String[] args) throws Exception{\n\t\tsnmpoption unsetresource = new snmpoption();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public <Ex extends Throwable> Try<R,Ex> execute(T input,Class<Ex> classes){\n\t\t\n\t\treturn Try.withCatch( ()->transactionTemplate.execute(status-> transaction.apply(input)),classes);\n\t\t \n\t}",
"public void printInferredDependencies(ClassDoc c) {\n\tif (hidden(c))\n\t return;\n\n\tOptions opt = optionProvider.getOptionsFor(c);\n\tSet<Type> types = new HashSet<Type>();\n\t// harvest method return and parameter types\n\tfor (MethodDoc method : filterByVisibility(c.methods(false), opt.inferDependencyVisibility)) {\n\t types.add(method.returnType());\n\t for (Parameter parameter : method.parameters()) {\n\t\ttypes.add(parameter.type());\n\t }\n\t}\n\t// and the field types\n\tif (!opt.inferRelationships) {\n\t for (FieldDoc field : filterByVisibility(c.fields(false), opt.inferDependencyVisibility)) {\n\t\ttypes.add(field.type());\n\t }\n\t}\n\t// see if there are some type parameters\n\tif (c.asParameterizedType() != null) {\n\t ParameterizedType pt = c.asParameterizedType();\n\t types.addAll(Arrays.asList(pt.typeArguments()));\n\t}\n\t// see if type parameters extend something\n\tfor(TypeVariable tv: c.typeParameters()) {\n\t if(tv.bounds().length > 0 )\n\t\ttypes.addAll(Arrays.asList(tv.bounds()));\n\t}\n\n\t// and finally check for explicitly imported classes (this\n\t// assumes there are no unused imports...)\n\tif (opt.useImports)\n\t types.addAll(Arrays.asList(importedClasses(c)));\n\n\t// compute dependencies\n\tfor (Type type : types) {\n\t // skip primitives and type variables, as well as dependencies\n\t // on the source class\n\t if (type.isPrimitive() || type instanceof WildcardType || type instanceof TypeVariable\n\t\t || c.toString().equals(type.asClassDoc().toString()))\n\t\tcontinue;\n\n\t // check if the destination is excluded from inference\n\t ClassDoc fc = type.asClassDoc();\n\t if (hidden(fc))\n\t\tcontinue;\n\t \n\t // check if source and destination are in the same package and if we are allowed\n\t // to infer dependencies between classes in the same package\n\t if(!opt.inferDepInPackage && c.containingPackage().equals(fc.containingPackage()))\n\t\tcontinue;\n\n\t // if source and dest are not already linked, add a dependency\n\t RelationPattern rp = getClassInfo(c, true).getRelation(fc.toString());\n\t if (rp == null || rp.matchesOne(new RelationPattern(RelationDirection.OUT))) {\n\t\trelation(opt, RelationType.DEPEND, c, fc, \"\", \"\", \"\");\n\t }\n\t \n\t}\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 void keyboardSupportEnabled(Activity activity, boolean enable) {\n if (getContent() != null && getContent().getChildCount() > 0) {\n if (mKeyboardUtil == null) {\n mKeyboardUtil = new KeyboardUtil(activity, getContent().getChildAt(0));\n mKeyboardUtil.disable();\n }\n\n if (enable) {\n mKeyboardUtil.enable();\n } else {\n mKeyboardUtil.disable();\n }\n }\n }",
"public static Timespan create(Timespan... timespans) {\n if (timespans == null) {\n return null;\n }\n\n if (timespans.length == 0) {\n return ZERO_MILLISECONDS;\n }\n\n Timespan res = timespans[0];\n\n for (int i = 1; i < timespans.length; i++) {\n Timespan timespan = timespans[i];\n res = res.add(timespan);\n }\n\n return res;\n }",
"public void symm2x2_fast( double a11 , double a12, double a22 )\n {\n// double p = (a11 - a22)*0.5;\n// double r = Math.sqrt(p*p + a12*a12);\n//\n// value0.real = a22 + a12*a12/(r-p);\n// value1.real = a22 - a12*a12/(r+p);\n// }\n//\n// public void symm2x2_std( double a11 , double a12, double a22 )\n// {\n double left = (a11+a22)*0.5;\n double b = (a11-a22)*0.5;\n double right = Math.sqrt(b*b+a12*a12);\n value0.real = left + right;\n value1.real = left - right;\n }",
"public static BoxConfig readFrom(Reader reader) throws IOException {\n JsonObject config = JsonObject.readFrom(reader);\n JsonObject settings = (JsonObject) config.get(\"boxAppSettings\");\n String clientId = settings.get(\"clientID\").asString();\n String clientSecret = settings.get(\"clientSecret\").asString();\n JsonObject appAuth = (JsonObject) settings.get(\"appAuth\");\n String publicKeyId = appAuth.get(\"publicKeyID\").asString();\n String privateKey = appAuth.get(\"privateKey\").asString();\n String passphrase = appAuth.get(\"passphrase\").asString();\n String enterpriseId = config.get(\"enterpriseID\").asString();\n return new BoxConfig(clientId, clientSecret, enterpriseId, publicKeyId, privateKey, passphrase);\n }"
] |
1-D Perlin noise function.
@param x X Value.
@return Returns function's value at point x. | [
"public double Function1D(double x) {\n double frequency = initFrequency;\n double amplitude = initAmplitude;\n double sum = 0;\n\n // octaves\n for (int i = 0; i < octaves; i++) {\n sum += SmoothedNoise(x * frequency) * amplitude;\n\n frequency *= 2;\n amplitude *= persistence;\n }\n return sum;\n }"
] | [
"public 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 }",
"protected List splitInCriteria(Object attribute, Collection values, boolean negative, int inLimit)\r\n {\r\n List result = new ArrayList();\r\n Collection inCollection = new ArrayList();\r\n\r\n if (values == null || values.isEmpty())\r\n {\r\n // OQL creates empty Criteria for late binding\r\n result.add(buildInCriteria(attribute, negative, values));\r\n }\r\n else\r\n {\r\n Iterator iter = values.iterator();\r\n\r\n while (iter.hasNext())\r\n {\r\n inCollection.add(iter.next());\r\n if (inCollection.size() == inLimit || !iter.hasNext())\r\n {\r\n result.add(buildInCriteria(attribute, negative, inCollection));\r\n inCollection = new ArrayList();\r\n }\r\n }\r\n }\r\n return result;\r\n }",
"protected Object getProxyFromResultSet() throws PersistenceBrokerException\r\n {\r\n // 1. get Identity of current row:\r\n Identity oid = getIdentityFromResultSet();\r\n\r\n // 2. return a Proxy instance:\r\n return getBroker().createProxy(getItemProxyClass(), oid);\r\n }",
"public static String format(ImageFormat format) {\n if (format == null) {\n throw new IllegalArgumentException(\"You must specify an image format.\");\n }\n return FILTER_FORMAT + \"(\" + format.value + \")\";\n }",
"private boolean isReadRequired(ValueGeneration valueGeneration, GenerationTiming matchTiming) {\n\t\treturn valueGeneration != null && valueGeneration.getValueGenerator() == null &&\n\t\t\t\ttimingsMatch( valueGeneration.getGenerationTiming(), matchTiming );\n\t}",
"public static base_responses add(nitro_service client, dnsaaaarec resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdnsaaaarec addresources[] = new dnsaaaarec[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dnsaaaarec();\n\t\t\t\taddresources[i].hostname = resources[i].hostname;\n\t\t\t\taddresources[i].ipv6address = resources[i].ipv6address;\n\t\t\t\taddresources[i].ttl = resources[i].ttl;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"static void addDeployOperationStep(final CompositeOperationBuilder builder, final DeploymentDescription deployment) {\n final String name = deployment.getName();\n\n final Set<String> serverGroups = deployment.getServerGroups();\n // If the server groups are empty this is a standalone deployment\n if (serverGroups.isEmpty()) {\n final ModelNode address = createAddress(DEPLOYMENT, name);\n builder.addStep(createOperation(DEPLOYMENT_DEPLOY_OPERATION, address));\n } else {\n for (String serverGroup : serverGroups) {\n final ModelNode address = createAddress(SERVER_GROUP, serverGroup, DEPLOYMENT, name);\n builder.addStep(createOperation(DEPLOYMENT_DEPLOY_OPERATION, address));\n }\n }\n }",
"@SuppressWarnings(\"deprecation\")\n\tpublic static boolean dateEquals(java.util.Date d1, java.util.Date d2) {\n if (d1 == null || d2 == null) {\n return false;\n }\n\n return d1.getDate() == d2.getDate()\n && d1.getMonth() == d2.getMonth()\n && d1.getYear() == d2.getYear();\n }",
"public boolean evaluate(FieldContainer container, Map<GenericCriteriaPrompt, Object> promptValues)\n {\n boolean result = true;\n if (m_criteria != null)\n {\n result = m_criteria.evaluate(container, promptValues);\n\n //\n // If this row has failed, but it is a summary row, and we are\n // including related summary rows, then we need to recursively test\n // its children\n //\n if (!result && m_showRelatedSummaryRows && container instanceof Task)\n {\n for (Task task : ((Task) container).getChildTasks())\n {\n if (evaluate(task, promptValues))\n {\n result = true;\n break;\n }\n }\n }\n }\n\n return (result);\n }"
] |
Set the association in the entry state.
@param collectionRole the role of the association
@param association the association | [
"public void setAssociation(String collectionRole, Association association) {\n\t\tif ( associations == null ) {\n\t\t\tassociations = new HashMap<>();\n\t\t}\n\t\tassociations.put( collectionRole, association );\n\t}"
] | [
"private IndexedContainer createContainerForBundleWithoutDescriptor() throws IOException, CmsException {\n\n IndexedContainer container = new IndexedContainer();\n\n // create properties\n container.addContainerProperty(TableProperty.KEY, String.class, \"\");\n container.addContainerProperty(TableProperty.TRANSLATION, String.class, \"\");\n\n // add entries\n SortedProperties localization = getLocalization(m_locale);\n Set<Object> keySet = m_keyset.getKeySet();\n for (Object key : keySet) {\n\n Object itemId = container.addItem();\n Item item = container.getItem(itemId);\n item.getItemProperty(TableProperty.KEY).setValue(key);\n Object translation = localization.get(key);\n item.getItemProperty(TableProperty.TRANSLATION).setValue(null == translation ? \"\" : translation);\n }\n\n return container;\n }",
"public String join(List<String> list) {\n\n if (list == null) {\n return null;\n }\n\n StringBuilder sb = new StringBuilder();\n boolean first = true;\n for (String s : list) {\n\n if (s == null) {\n if (convertEmptyToNull) {\n s = \"\";\n } else {\n throw new IllegalArgumentException(\"StringListFlattener does not support null strings in the list. Consider calling setConvertEmptyToNull(true).\");\n }\n }\n\n if (!first) {\n sb.append(separator);\n }\n\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n if (c == escapeChar || c == separator) {\n sb.append(escapeChar);\n }\n sb.append(c);\n }\n\n first = false;\n }\n return sb.toString();\n }",
"private List<Object> doQueryAndInitializeNonLazyCollections(\n\t\t\tSharedSessionContractImplementor session,\n\t\t\tQueryParameters qp,\n\t\t\tOgmLoadingContext ogmLoadingContext,\n\t\t\tboolean returnProxies) {\n\n\n\t\t//TODO handles the read only\n\t\tfinal PersistenceContext persistenceContext = session.getPersistenceContext();\n\t\tboolean defaultReadOnlyOrig = persistenceContext.isDefaultReadOnly();\n\t\tpersistenceContext.beforeLoad();\n\t\tList<Object> result;\n\t\ttry {\n\t\t\ttry {\n\t\t\t\tresult = doQuery(\n\t\t\t\t\t\tsession,\n\t\t\t\t\t\tqp,\n\t\t\t\t\t\togmLoadingContext,\n\t\t\t\t\t\treturnProxies\n\t\t\t\t);\n\t\t\t}\n\t\t\tfinally {\n\t\t\t\tpersistenceContext.afterLoad();\n\t\t\t}\n\t\t\tpersistenceContext.initializeNonLazyCollections();\n\t\t}\n\t\tfinally {\n\t\t\t// Restore the original default\n\t\t\tpersistenceContext.setDefaultReadOnly( defaultReadOnlyOrig );\n\t\t}\n\n\t\tlog.debug( \"done entity load\" );\n\t\treturn result;\n\t}",
"protected String addDependency(TaskGroup.HasTaskGroup dependency) {\n Objects.requireNonNull(dependency);\n this.taskGroup().addDependencyTaskGroup(dependency.taskGroup());\n return dependency.taskGroup().key();\n }",
"public void copyTo(Gradient g) {\n\t\tg.numKnots = numKnots;\n\t\tg.map = (int[])map.clone();\n\t\tg.xKnots = (int[])xKnots.clone();\n\t\tg.yKnots = (int[])yKnots.clone();\n\t\tg.knotTypes = (byte[])knotTypes.clone();\n\t}",
"public ResultSetAndStatement executeSQL(\r\n final String sql,\r\n ClassDescriptor cld,\r\n ValueContainer[] values,\r\n boolean scrollable)\r\n throws PersistenceBrokerException\r\n {\r\n if (logger.isDebugEnabled()) logger.debug(\"executeSQL: \" + sql);\r\n final boolean isStoredprocedure = isStoredProcedure(sql);\r\n final StatementManagerIF sm = broker.serviceStatementManager();\r\n PreparedStatement stmt = null;\r\n ResultSet rs = null;\r\n try\r\n {\r\n stmt = sm.getPreparedStatement(cld, sql,\r\n scrollable, StatementManagerIF.FETCH_SIZE_NOT_EXPLICITLY_SET, isStoredprocedure);\r\n if (isStoredprocedure)\r\n {\r\n // Query implemented as a stored procedure, which must return a result set.\r\n // Query sytax is: { ?= call PROCEDURE_NAME(?,...,?)}\r\n getPlatform().registerOutResultSet((CallableStatement) stmt, 1);\r\n sm.bindValues(stmt, values, 2);\r\n stmt.execute();\r\n rs = (ResultSet) ((CallableStatement) stmt).getObject(1);\r\n }\r\n else\r\n {\r\n sm.bindValues(stmt, values, 1);\r\n rs = stmt.executeQuery();\r\n }\r\n\r\n // as we return the resultset for further operations, we cannot release the statement yet.\r\n // that has to be done by the JdbcAccess-clients (i.e. RsIterator, ProxyRsIterator and PkEnumeration.)\r\n return new ResultSetAndStatement(sm, stmt, rs, new SelectStatement()\r\n {\r\n public Query getQueryInstance()\r\n {\r\n return null;\r\n }\r\n\r\n public int getColumnIndex(FieldDescriptor fld)\r\n {\r\n return JdbcType.MIN_INT;\r\n }\r\n\r\n public String getStatement()\r\n {\r\n return sql;\r\n }\r\n });\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n // release resources on exception\r\n sm.closeResources(stmt, rs);\r\n logger.error(\"PersistenceBrokerException during the execution of the SQL query: \" + e.getMessage(), e);\r\n throw e;\r\n }\r\n catch (SQLException e)\r\n {\r\n // release resources on exception\r\n sm.closeResources(stmt, rs);\r\n throw ExceptionHelper.generateException(e, sql, cld, values, logger, null);\r\n }\r\n }",
"@Override\n public boolean setA(DMatrixRBlock A) {\n // Extract a lower triangular solution\n if( !decomposer.decompose(A) )\n return false;\n\n blockLength = A.blockLength;\n\n return true;\n }",
"public static float distance(final float ax, final float ay,\n final float bx, final float by) {\n return (float) Math.sqrt(\n (ax - bx) * (ax - bx) +\n (ay - by) * (ay - by)\n );\n }",
"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 }"
] |
Throw IllegalStateException if key is not present in map.
@param key the key to expect.
@param map the map to search.
@throws IllegalArgumentException if key is not in map. | [
"public static void keyPresent(final String key, final Map<String, ?> map) {\n if (!map.containsKey(key)) {\n throw new IllegalStateException(\n String.format(\"expected %s to be present\", key));\n }\n }"
] | [
"public <T> T getSPI(Class<T> spiType)\n {\n return getSPI(spiType, SecurityActions.getContextClassLoader());\n }",
"public static void checkMinimumArrayLength(String parameterName,\n int actualLength, int minimumLength) {\n if (actualLength < minimumLength) {\n throw Exceptions\n .IllegalArgument(\n \"Array %s should have at least %d elements, but it only has %d\",\n parameterName, minimumLength, actualLength);\n }\n }",
"public static ModelNode createLocalHostHostInfo(final LocalHostControllerInfo hostInfo, final ProductConfig productConfig,\n final IgnoredDomainResourceRegistry ignoredResourceRegistry, final Resource hostModelResource) {\n final ModelNode info = new ModelNode();\n info.get(NAME).set(hostInfo.getLocalHostName());\n info.get(RELEASE_VERSION).set(Version.AS_VERSION);\n info.get(RELEASE_CODENAME).set(Version.AS_RELEASE_CODENAME);\n info.get(MANAGEMENT_MAJOR_VERSION).set(Version.MANAGEMENT_MAJOR_VERSION);\n info.get(MANAGEMENT_MINOR_VERSION).set(Version.MANAGEMENT_MINOR_VERSION);\n info.get(MANAGEMENT_MICRO_VERSION).set(Version.MANAGEMENT_MICRO_VERSION);\n final String productName = productConfig.getProductName();\n final String productVersion = productConfig.getProductVersion();\n if(productName != null) {\n info.get(PRODUCT_NAME).set(productName);\n }\n if(productVersion != null) {\n info.get(PRODUCT_VERSION).set(productVersion);\n }\n ModelNode ignoredModel = ignoredResourceRegistry.getIgnoredResourcesAsModel();\n if (ignoredModel.hasDefined(IGNORED_RESOURCE_TYPE)) {\n info.get(IGNORED_RESOURCES).set(ignoredModel.require(IGNORED_RESOURCE_TYPE));\n }\n boolean ignoreUnaffectedServerGroups = hostInfo.isRemoteDomainControllerIgnoreUnaffectedConfiguration();\n IgnoredNonAffectedServerGroupsUtil.addCurrentServerGroupsToHostInfoModel(ignoreUnaffectedServerGroups, hostModelResource, info);\n return info;\n }",
"public void createRelationFieldMap(Props props)\n {\n byte[] fieldMapData = null;\n for (Integer key : RELATION_KEYS)\n {\n fieldMapData = props.getByteArray(key);\n if (fieldMapData != null)\n {\n break;\n }\n }\n\n if (fieldMapData == null)\n {\n populateDefaultData(getDefaultRelationData());\n }\n else\n {\n createFieldMap(fieldMapData);\n }\n }",
"public void updateMetadataVersions() {\n Properties versionProps = MetadataVersionStoreUtils.getProperties(this.systemStoreRepository.getMetadataVersionStore());\n Long newVersion = fetchNewVersion(SystemStoreConstants.CLUSTER_VERSION_KEY,\n null,\n versionProps);\n if(newVersion != null) {\n this.currentClusterVersion = newVersion;\n }\n }",
"public BoxTaskAssignment.Info addAssignment(BoxUser assignTo) {\n JsonObject taskJSON = new JsonObject();\n taskJSON.add(\"type\", \"task\");\n taskJSON.add(\"id\", this.getID());\n\n JsonObject assignToJSON = new JsonObject();\n assignToJSON.add(\"id\", assignTo.getID());\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"task\", taskJSON);\n requestJSON.add(\"assign_to\", assignToJSON);\n\n URL url = ADD_TASK_ASSIGNMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxTaskAssignment addedAssignment = new BoxTaskAssignment(this.getAPI(), responseJSON.get(\"id\").asString());\n return addedAssignment.new Info(responseJSON);\n }",
"private void readHeaderProperties(BufferedInputStream stream) throws IOException\n {\n String header = readHeaderString(stream);\n for (String property : header.split(\"\\\\|\"))\n {\n String[] expression = property.split(\"=\");\n m_properties.put(expression[0], expression[1]);\n }\n }",
"public LatLong getDestinationPoint(double bearing, double distance) {\n\n double brng = Math.toRadians(bearing);\n\n double lat1 = latToRadians();\n double lon1 = longToRadians();\n\n double lat2 = Math.asin(Math.sin(lat1)\n * Math.cos(distance / EarthRadiusMeters)\n + Math.cos(lat1) * Math.sin(distance / EarthRadiusMeters)\n * Math.cos(brng));\n\n double lon2 = lon1 + Math.atan2(Math.sin(brng)\n * Math.sin(distance / EarthRadiusMeters) * Math.cos(lat1),\n Math.cos(distance / EarthRadiusMeters)\n - Math.sin(lat1) * Math.sin(lat2));\n\n return new LatLong(Math.toDegrees(lat2), Math.toDegrees(lon2));\n\n }",
"private JSONObject getARP(final Context context) {\n try {\n final String nameSpaceKey = getNamespaceARPKey();\n if (nameSpaceKey == null) return null;\n\n final SharedPreferences prefs = StorageHelper.getPreferences(context, nameSpaceKey);\n final Map<String, ?> all = prefs.getAll();\n final Iterator<? extends Map.Entry<String, ?>> iter = all.entrySet().iterator();\n\n while (iter.hasNext()) {\n final Map.Entry<String, ?> kv = iter.next();\n final Object o = kv.getValue();\n if (o instanceof Number && ((Number) o).intValue() == -1) {\n iter.remove();\n }\n }\n final JSONObject ret = new JSONObject(all);\n getConfigLogger().verbose(getAccountId(), \"Fetched ARP for namespace key: \" + nameSpaceKey + \" values: \" + all.toString());\n return ret;\n } catch (Throwable t) {\n getConfigLogger().verbose(getAccountId(), \"Failed to construct ARP object\", t);\n return null;\n }\n }"
] |
Get path ID for a given profileId and pathName
@param pathName Name of path
@param profileId ID of profile
@return ID of path | [
"public int getPathId(String pathName, int profileId) {\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n // first get the pathId for the pathName/profileId\n int pathId = -1;\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT \" + Constants.GENERIC_ID + \" FROM \" + Constants.DB_TABLE_PATH\n + \" WHERE \" + Constants.PATH_PROFILE_PATHNAME + \"= ? \"\n + \" AND \" + Constants.GENERIC_PROFILE_ID + \"= ?\"\n );\n queryStatement.setString(1, pathName);\n queryStatement.setInt(2, profileId);\n results = queryStatement.executeQuery();\n if (results.next()) {\n pathId = results.getInt(Constants.GENERIC_ID);\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return pathId;\n }"
] | [
"@Deprecated\r\n private BufferedImage getOriginalImage(String suffix) throws IOException, FlickrException {\r\n StringBuffer buffer = getOriginalBaseImageUrl();\r\n buffer.append(suffix);\r\n return _getImage(buffer.toString());\r\n }",
"private void writeExceptions9(List<Project.Calendars.Calendar.WeekDays.WeekDay> dayList, List<ProjectCalendarException> exceptions)\n {\n for (ProjectCalendarException exception : exceptions)\n {\n boolean working = exception.getWorking();\n\n Project.Calendars.Calendar.WeekDays.WeekDay day = m_factory.createProjectCalendarsCalendarWeekDaysWeekDay();\n dayList.add(day);\n day.setDayType(BIGINTEGER_ZERO);\n day.setDayWorking(Boolean.valueOf(working));\n\n Project.Calendars.Calendar.WeekDays.WeekDay.TimePeriod period = m_factory.createProjectCalendarsCalendarWeekDaysWeekDayTimePeriod();\n day.setTimePeriod(period);\n period.setFromDate(exception.getFromDate());\n period.setToDate(exception.getToDate());\n\n if (working)\n {\n Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes times = m_factory.createProjectCalendarsCalendarWeekDaysWeekDayWorkingTimes();\n day.setWorkingTimes(times);\n List<Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime> timesList = times.getWorkingTime();\n\n for (DateRange range : exception)\n {\n Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime time = m_factory.createProjectCalendarsCalendarWeekDaysWeekDayWorkingTimesWorkingTime();\n timesList.add(time);\n\n time.setFromTime(range.getStart());\n time.setToTime(range.getEnd());\n }\n }\n }\n }",
"private void updateGhostStyle() {\n\n if (CmsStringUtil.isEmpty(m_realValue)) {\n if (CmsStringUtil.isEmpty(m_ghostValue)) {\n updateTextArea(m_realValue);\n return;\n }\n if (!m_focus) {\n setGhostStyleEnabled(true);\n updateTextArea(m_ghostValue);\n } else {\n // don't show ghost mode while focused\n setGhostStyleEnabled(false);\n }\n } else {\n setGhostStyleEnabled(false);\n updateTextArea(m_realValue);\n }\n }",
"public void setVec3(String key, float x, float y, float z)\n {\n checkKeyIsUniform(key);\n NativeLight.setVec3(getNative(), key, x, y, z);\n }",
"public void setSeriesEndDate(Date date) {\r\n\r\n if (!Objects.equals(m_model.getSeriesEndDate(), date)) {\r\n m_model.setSeriesEndDate(date);\r\n valueChanged();\r\n }\r\n\r\n }",
"protected boolean cannotInstantiate(Class<?> actionClass) {\n\t\treturn actionClass.isAnnotation() || actionClass.isInterface() || actionClass.isEnum()\n\t\t\t\t|| (actionClass.getModifiers() & Modifier.ABSTRACT) != 0 || actionClass.isAnonymousClass();\n\t}",
"protected void deliverLifecycleAnnouncement(final Logger logger, final boolean starting) {\n new Thread(new Runnable() {\n @Override\n public void run() {\n for (final LifecycleListener listener : getLifecycleListeners()) {\n try {\n if (starting) {\n listener.started(LifecycleParticipant.this);\n } else {\n listener.stopped(LifecycleParticipant.this);\n }\n } catch (Throwable t) {\n logger.warn(\"Problem delivering lifecycle announcement to listener\", t);\n }\n }\n }\n }, \"Lifecycle announcement delivery\").start();\n }",
"public void setSize(int size) {\n if (size != MaterialProgressDrawable.LARGE && size != MaterialProgressDrawable.DEFAULT) {\n return;\n }\n final DisplayMetrics metrics = getResources().getDisplayMetrics();\n if (size == MaterialProgressDrawable.LARGE) {\n mCircleHeight = mCircleWidth = (int) (CIRCLE_DIAMETER_LARGE * metrics.density);\n } else {\n mCircleHeight = mCircleWidth = (int) (CIRCLE_DIAMETER * metrics.density);\n }\n // force the bounds of the progress circle inside the circle view to\n // update by setting it to null before updating its size and then\n // re-setting it\n mCircleView.setImageDrawable(null);\n mProgress.updateSizes(size);\n mCircleView.setImageDrawable(mProgress);\n }",
"@Override\n protected void addBuildInfoProperties(BuildInfoBuilder builder) {\n if (envVars != null) {\n for (Map.Entry<String, String> entry : envVars.entrySet()) {\n builder.addProperty(BuildInfoProperties.BUILD_INFO_ENVIRONMENT_PREFIX + entry.getKey(), entry.getValue());\n }\n }\n\n if (sysVars != null) {\n for (Map.Entry<String, String> entry : sysVars.entrySet()) {\n builder.addProperty(entry.getKey(), entry.getValue());\n }\n }\n }"
] |
Retrieve the recurrence type.
@param value integer value
@return RecurrenceType instance | [
"private RecurrenceType getRecurrenceType(int value)\n {\n RecurrenceType result;\n if (value < 0 || value >= RECURRENCE_TYPES.length)\n {\n result = null;\n }\n else\n {\n result = RECURRENCE_TYPES[value];\n }\n\n return result;\n }"
] | [
"public void execute() {\n State currentState = state.getAndSet(State.RUNNING);\n if (currentState == State.RUNNING) {\n throw new IllegalStateException(\n \"ExecutionChain is already running!\");\n }\n executeRunnable = new ExecuteRunnable();\n }",
"public static GVRVideoSceneObjectPlayer<MediaPlayer> makePlayerInstance(final MediaPlayer mediaPlayer) {\n return new GVRVideoSceneObjectPlayer<MediaPlayer>() {\n @Override\n public MediaPlayer getPlayer() {\n return mediaPlayer;\n }\n\n @Override\n public void setSurface(Surface surface) {\n mediaPlayer.setSurface(surface);\n }\n\n @Override\n public void release() {\n mediaPlayer.release();\n }\n\n @Override\n public boolean canReleaseSurfaceImmediately() {\n return true;\n }\n\n @Override\n public void pause() {\n try {\n mediaPlayer.pause();\n } catch (final IllegalStateException exc) {\n //intentionally ignored; might have been released already or never got to be\n //initialized\n }\n }\n\n @Override\n public void start() {\n mediaPlayer.start();\n }\n\n @Override\n public boolean isPlaying() {\n return mediaPlayer.isPlaying();\n }\n };\n }",
"public synchronized Widget measureChild(final int dataIndex, boolean calculateOffset) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"measureChild dataIndex = %d\", dataIndex);\n\n Widget widget = mContainer.get(dataIndex);\n if (widget != null) {\n synchronized (mMeasuredChildren) {\n mMeasuredChildren.add(dataIndex);\n }\n }\n return widget;\n }",
"protected Object getFieldData(Integer id, FieldType type, byte[][] fixedData, Var2Data varData)\n {\n Object result = null;\n\n FieldItem item = m_map.get(type);\n if (item != null)\n {\n result = item.read(id, fixedData, varData);\n }\n\n return result;\n }",
"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 }",
"public static base_response add(nitro_service client, responderpolicy resource) throws Exception {\n\t\tresponderpolicy addresource = new responderpolicy();\n\t\taddresource.name = resource.name;\n\t\taddresource.rule = resource.rule;\n\t\taddresource.action = resource.action;\n\t\taddresource.undefaction = resource.undefaction;\n\t\taddresource.comment = resource.comment;\n\t\taddresource.logaction = resource.logaction;\n\t\taddresource.appflowaction = resource.appflowaction;\n\t\treturn addresource.add_resource(client);\n\t}",
"private static BoxRetentionPolicy.Info createRetentionPolicy(BoxAPIConnection api, String name, String type,\r\n int length, String action) {\r\n return createRetentionPolicy(api, name, type, length, action, null);\r\n }",
"public static void init(String jobId) {\n JobContext parent = current_.get();\n JobContext ctx = new JobContext(parent);\n current_.set(ctx);\n // don't call setJobId(String)\n // as it will trigger listeners -- TODO fix me\n ctx.jobId = jobId;\n if (null == parent) {\n Act.eventBus().trigger(new JobContextInitialized(ctx));\n }\n }",
"private void checkObjectCache(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (!CHECKLEVEL_STRICT.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n \r\n ObjectCacheDef objCacheDef = classDef.getObjectCache();\r\n\r\n if (objCacheDef == null)\r\n {\r\n return;\r\n }\r\n\r\n String objectCacheName = objCacheDef.getName();\r\n\r\n if ((objectCacheName == null) || (objectCacheName.length() == 0))\r\n {\r\n throw new ConstraintException(\"No class specified for the object-cache of class \"+classDef.getName());\r\n }\r\n\r\n try\r\n {\r\n InheritanceHelper helper = new InheritanceHelper();\r\n\r\n if (!helper.isSameOrSubTypeOf(objectCacheName, OBJECT_CACHE_INTERFACE))\r\n {\r\n throw new ConstraintException(\"The class \"+objectCacheName+\" specified as object-cache of class \"+classDef.getName()+\" does not implement the interface \"+OBJECT_CACHE_INTERFACE);\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"Could not find the class \"+ex.getMessage()+\" on the classpath while checking the object-cache class \"+objectCacheName+\" of class \"+classDef.getName());\r\n }\r\n }"
] |
Compute morse.
@param term the term
@return the string | [
"private String computeMorse(BytesRef term) {\n StringBuilder stringBuilder = new StringBuilder();\n int i = term.offset + prefixOffset;\n for (; i < term.length; i++) {\n if (ALPHABET_MORSE.containsKey(term.bytes[i])) {\n stringBuilder.append(ALPHABET_MORSE.get(term.bytes[i]) + \" \");\n } else if(term.bytes[i]!=0x00){\n return null;\n } else {\n break;\n }\n }\n return stringBuilder.toString();\n }"
] | [
"static <T> List<Template> getTemplates(T objectType) {\n try {\n List<Template> templates = new ArrayList<>();\n TEMP_FINDER.findAnnotations(templates, objectType);\n return templates;\n } catch (Exception e) {\n throw new IllegalStateException(e);\n }\n }",
"private void bindProcedure(PreparedStatement stmt, ClassDescriptor cld, Object obj, ProcedureDescriptor proc)\r\n throws SQLException\r\n {\r\n int valueSub = 0;\r\n\r\n // Figure out if we are using a callable statement. If we are, then we\r\n // will need to register one or more output parameters.\r\n CallableStatement callable = null;\r\n try\r\n {\r\n callable = (CallableStatement) stmt;\r\n }\r\n catch(Exception e)\r\n {\r\n m_log.error(\"Error while bind values for class '\" + (cld != null ? cld.getClassNameOfObject() : null)\r\n + \"', using stored procedure: \"+ proc, e);\r\n if(e instanceof SQLException)\r\n {\r\n throw (SQLException) e;\r\n }\r\n else\r\n {\r\n throw new PersistenceBrokerException(\"Unexpected error while bind values for class '\"\r\n + (cld != null ? cld.getClassNameOfObject() : null) + \"', using stored procedure: \"+ proc);\r\n }\r\n }\r\n\r\n // If we have a return value, then register it.\r\n if ((proc.hasReturnValue()) && (callable != null))\r\n {\r\n int jdbcType = proc.getReturnValueFieldRef().getJdbcType().getType();\r\n m_platform.setNullForStatement(stmt, valueSub + 1, jdbcType);\r\n callable.registerOutParameter(valueSub + 1, jdbcType);\r\n valueSub++;\r\n }\r\n\r\n // Process all of the arguments.\r\n Iterator iterator = proc.getArguments().iterator();\r\n while (iterator.hasNext())\r\n {\r\n ArgumentDescriptor arg = (ArgumentDescriptor) iterator.next();\r\n Object val = arg.getValue(obj);\r\n int jdbcType = arg.getJdbcType();\r\n setObjectForStatement(stmt, valueSub + 1, val, jdbcType);\r\n if ((arg.getIsReturnedByProcedure()) && (callable != null))\r\n {\r\n callable.registerOutParameter(valueSub + 1, jdbcType);\r\n }\r\n valueSub++;\r\n }\r\n }",
"private Set<HttpMethod> getHttpMethods(Method method) {\n Set<HttpMethod> httpMethods = new HashSet<>();\n\n if (method.isAnnotationPresent(GET.class)) {\n httpMethods.add(HttpMethod.GET);\n }\n if (method.isAnnotationPresent(PUT.class)) {\n httpMethods.add(HttpMethod.PUT);\n }\n if (method.isAnnotationPresent(POST.class)) {\n httpMethods.add(HttpMethod.POST);\n }\n if (method.isAnnotationPresent(DELETE.class)) {\n httpMethods.add(HttpMethod.DELETE);\n }\n\n return Collections.unmodifiableSet(httpMethods);\n }",
"public void validateOperation(final ModelNode operation) {\n if (operation == null) {\n return;\n }\n final PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR));\n final String name = operation.get(OP).asString();\n\n OperationEntry entry = root.getOperationEntry(address, name);\n if (entry == null) {\n throwOrWarnAboutDescriptorProblem(ControllerLogger.ROOT_LOGGER.noOperationEntry(name, address));\n }\n //noinspection ConstantConditions\n if (entry.getType() == EntryType.PRIVATE || entry.getFlags().contains(OperationEntry.Flag.HIDDEN)) {\n return;\n }\n if (entry.getOperationHandler() == null) {\n throwOrWarnAboutDescriptorProblem(ControllerLogger.ROOT_LOGGER.noOperationHandler(name, address));\n }\n final DescriptionProvider provider = getDescriptionProvider(operation);\n final ModelNode description = provider.getModelDescription(null);\n\n final Map<String, ModelNode> describedProperties = getDescribedRequestProperties(operation, description);\n final Map<String, ModelNode> actualParams = getActualRequestProperties(operation);\n\n checkActualOperationParamsAreDescribed(operation, describedProperties, actualParams);\n checkAllRequiredPropertiesArePresent(description, operation, describedProperties, actualParams);\n checkParameterTypes(description, operation, describedProperties, actualParams);\n\n //TODO check ranges\n }",
"public static Chart getMSDLineChart(Trajectory t, int lagMin, int lagMax,\n\t\t\tAbstractMeanSquaredDisplacmentEvaluator msdeval) {\n\n\t\tdouble[] xData = new double[lagMax - lagMin + 1];\n\t\tdouble[] yData = new double[lagMax - lagMin + 1];\n\t\tmsdeval.setTrajectory(t);\n\t\tmsdeval.setTimelag(lagMin);\n\t\tfor (int i = lagMin; i < lagMax + 1; i++) {\n\t\t\tmsdeval.setTimelag(i);\n\t\t\tdouble msdhelp = msdeval.evaluate()[0];\n\t\t\txData[i - lagMin] = i;\n\t\t\tyData[i - lagMin] = msdhelp;\n\t\t}\n\n\t\t// Create Chart\n\t\tChart chart = QuickChart.getChart(\"MSD Line\", \"LAG\", \"MSD\", \"MSD\",\n\t\t\t\txData, yData);\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}",
"public void setDataOffsets(int[] offsets)\n {\n assert(mLevels == offsets.length);\n NativeBitmapImage.updateCompressed(getNative(), mWidth, mHeight, mImageSize, mData, mLevels, offsets);\n mData = null;\n }",
"@Override\n\tpublic Iterator<? extends IPAddressSeqRange> prefixIterator(int prefixLength) {\n\t\tif(!isMultiple()) {\n\t\t\treturn new Iterator<IPAddressSeqRange>() {\n\t\t\t\tIPAddressSeqRange orig = IPAddressSeqRange.this;\n\n\t\t\t\t@Override\n\t\t\t\tpublic boolean hasNext() {\n\t\t\t\t\treturn orig != null;\n\t\t\t\t}\n\n\t\t\t @Override\n\t\t\t\tpublic IPAddressSeqRange next() {\n\t\t\t \tif(orig == null) {\n\t\t\t \t\tthrow new NoSuchElementException();\n\t\t\t \t}\n\t\t\t \tIPAddressSeqRange result = orig;\n\t\t\t \torig = null;\n\t\t\t \treturn result;\n\t\t\t }\n\t\t\t\n\t\t\t @Override\n\t\t\t\tpublic void remove() {\n\t\t\t \tthrow new UnsupportedOperationException();\n\t\t\t }\n\t\t\t};\n\t\t}\n\t\treturn new Iterator<IPAddressSeqRange>() {\n\t\t\tIterator<? extends IPAddress> prefixBlockIterator = prefixBlockIterator(prefixLength);\n\t\t\tprivate boolean first = true;\n\n\t\t\t@Override\n\t\t\tpublic boolean hasNext() {\n\t\t\t\treturn prefixBlockIterator.hasNext();\n\t\t\t}\n\n\t\t @Override\n\t\t\tpublic IPAddressSeqRange next() {\n\t\t \tIPAddress next = prefixBlockIterator.next();\n\t\t \tif(first) {\n\t\t \t\tfirst = false;\n\t\t \t\t// next is a prefix block\n\t\t \t\tIPAddress lower = getLower();\n\t\t \t\tif(hasNext()) {\n\t\t\t \t\tif(!lower.includesZeroHost(prefixLength)) {\n\t\t\t \t\t\treturn create(lower, next.getUpper());\n\t\t\t \t\t}\n\t\t \t\t} else {\n\t\t \t\t\tIPAddress upper = getUpper();\n\t\t \t\t\tif(!lower.includesZeroHost(prefixLength) || !upper.includesMaxHost(prefixLength)) {\n\t\t \t\t\t\treturn create(lower, upper);\n\t\t \t\t\t}\n\t\t \t\t}\n\t\t \t} else if(!hasNext()) {\n\t\t \t\tIPAddress upper = getUpper();\n\t\t \t\tif(!upper.includesMaxHost(prefixLength)) {\n\t\t \t\t\treturn create(next.getLower(), upper);\n\t\t \t\t}\n\t\t \t}\n\t\t \treturn next.toSequentialRange();\n\t\t }\n\t\t\n\t\t @Override\n\t\t\tpublic void remove() {\n\t\t \tthrow new UnsupportedOperationException();\n\t\t }\n\t\t};\n\t}",
"private void readResourceAssignments(Project gpProject)\n {\n Allocations allocations = gpProject.getAllocations();\n if (allocations != null)\n {\n for (Allocation allocation : allocations.getAllocation())\n {\n readResourceAssignment(allocation);\n }\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}"
] |
Patches the product module names
@param name String
@param moduleNames List<String> | [
"public void setProductModules(final String name, final List<String> moduleNames) {\n final DbProduct dbProduct = getProduct(name);\n dbProduct.setModules(moduleNames);\n repositoryHandler.store(dbProduct);\n }"
] | [
"protected void\t\tcalcWorld(Bone bone, int parentId)\n {\n getWorldMatrix(parentId, mTempMtxB); // WorldMatrix (parent) TempMtxB\n mTempMtxB.mul(bone.LocalMatrix); // WorldMatrix = WorldMatrix(parent) * LocalMatrix\n bone.WorldMatrix.set(mTempMtxB);\n }",
"public static StatisticsMatrix wrap( DMatrixRMaj m ) {\n StatisticsMatrix ret = new StatisticsMatrix();\n ret.setMatrix( m );\n\n return ret;\n }",
"private static String get(Properties p, String key, String defaultValue, Set<String> used){\r\n String rtn = p.getProperty(key, defaultValue);\r\n used.add(key);\r\n return rtn;\r\n }",
"private boolean computeEigenValues() {\n // make a copy of the internal tridiagonal matrix data for later use\n diagSaved = helper.copyDiag(diagSaved);\n offSaved = helper.copyOff(offSaved);\n\n vector.setQ(null);\n vector.setFastEigenvalues(true);\n\n // extract the eigenvalues\n if( !vector.process(-1,null,null) )\n return false;\n\n // save a copy of them since this data structure will be recycled next\n values = helper.copyEigenvalues(values);\n return true;\n }",
"public static boolean isSymmetric( DMatrixSparseCSC A , double tol ) {\n if( A.numRows != A.numCols )\n return false;\n\n int N = A.numCols;\n\n for (int i = 0; i < N; i++) {\n int idx0 = A.col_idx[i];\n int idx1 = A.col_idx[i+1];\n\n for (int index = idx0; index < idx1; index++) {\n int j = A.nz_rows[index];\n double value_ji = A.nz_values[index];\n double value_ij = A.get(i,j);\n\n if( Math.abs(value_ij-value_ji) > tol )\n return false;\n }\n }\n\n return true;\n }",
"public synchronized void addRange(final float range, final GVRSceneObject sceneObject)\n {\n if (null == sceneObject) {\n throw new IllegalArgumentException(\"sceneObject must be specified!\");\n }\n if (range < 0) {\n throw new IllegalArgumentException(\"range cannot be negative\");\n }\n\n final int size = mRanges.size();\n final float rangePow2 = range*range;\n final Object[] newElement = new Object[] {rangePow2, sceneObject};\n\n for (int i = 0; i < size; ++i) {\n final Object[] el = mRanges.get(i);\n final Float r = (Float)el[0];\n if (r > rangePow2) {\n mRanges.add(i, newElement);\n break;\n }\n }\n\n if (mRanges.size() == size) {\n mRanges.add(newElement);\n }\n\n final GVRSceneObject owner = getOwnerObject();\n if (null != owner) {\n owner.addChildObject(sceneObject);\n }\n }",
"public static BoxRetentionPolicyAssignment.Info createAssignmentToFolder(BoxAPIConnection api, String policyID,\r\n String folderID) {\r\n return createAssignment(api, policyID, new JsonObject().add(\"type\", TYPE_FOLDER).add(\"id\", folderID), null);\r\n }",
"public int[] indices(Collection<E> elems) {\r\n int[] indices = new int[elems.size()];\r\n int i = 0;\r\n for (E elem : elems) {\r\n indices[i++] = indexOf(elem);\r\n }\r\n return indices;\r\n }",
"@Pure\n\tpublic static <K, V> Pair<K, V> of(K k, V v) {\n\t\treturn new Pair<K, V>(k, v);\n\t}"
] |
Check the document field's type
and object
@param lhs The field to check
@param rhs The type
@return Expression: lhs $type rhs | [
"public static Expression type(String lhs, Type rhs) {\n return new Expression(lhs, \"$type\", rhs.toString());\n }"
] | [
"protected void markStatementsForDeletion(StatementDocument currentDocument,\n\t\t\tList<Statement> deleteStatements) {\n\t\tfor (Statement statement : deleteStatements) {\n\t\t\tboolean found = false;\n\t\t\tfor (StatementGroup sg : currentDocument.getStatementGroups()) {\n\t\t\t\tif (!sg.getProperty().equals(statement.getMainSnak().getPropertyId())) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tStatement changedStatement = null;\n\t\t\t\tfor (Statement existingStatement : sg) {\n\t\t\t\t\tif (existingStatement.equals(statement)) {\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\ttoDelete.add(statement.getStatementId());\n\t\t\t\t\t} else if (existingStatement.getStatementId().equals(\n\t\t\t\t\t\t\tstatement.getStatementId())) {\n\t\t\t\t\t\t// (we assume all existing statement ids to be nonempty\n\t\t\t\t\t\t// here)\n\t\t\t\t\t\tchangedStatement = existingStatement;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!found) {\n\t\t\t\t\tStringBuilder warning = new StringBuilder();\n\t\t\t\t\twarning.append(\"Cannot delete statement (id \")\n\t\t\t\t\t\t\t.append(statement.getStatementId())\n\t\t\t\t\t\t\t.append(\") since it is not present in data. Statement was:\\n\")\n\t\t\t\t\t\t\t.append(statement);\n\n\t\t\t\t\tif (changedStatement != null) {\n\t\t\t\t\t\twarning.append(\n\t\t\t\t\t\t\t\t\"\\nThe data contains another statement with the same id: maybe it has been edited? Other statement was:\\n\")\n\t\t\t\t\t\t\t\t.append(changedStatement);\n\t\t\t\t\t}\n\t\t\t\t\tlogger.warn(warning.toString());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"@GwtIncompatible(\"Class.getDeclaredFields\")\n\tpublic ToStringBuilder addDeclaredFields() {\n\t\tField[] fields = instance.getClass().getDeclaredFields();\n\t\tfor(Field field : fields) {\n\t\t\taddField(field);\n\t\t}\n\t\treturn this;\n\t}",
"public static final String getSelectedValue(ListBox list) {\n\tint index = list.getSelectedIndex();\n\treturn (index >= 0) ? list.getValue(index) : null;\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 }",
"public static ByteBuffer newDirectByteBuffer(long addr, int size, Object att) {\n dbbCC.setAccessible(true);\n Object b = null;\n try {\n b = dbbCC.newInstance(new Long(addr), new Integer(size), att);\n return ByteBuffer.class.cast(b);\n }\n catch(Exception e) {\n throw new IllegalStateException(String.format(\"Failed to create DirectByteBuffer: %s\", e.getMessage()));\n }\n }",
"public float getBoundsHeight(){\n if (mSceneObject != null) {\n GVRSceneObject.BoundingVolume v = mSceneObject.getBoundingVolume();\n return v.maxCorner.y - v.minCorner.y;\n }\n return 0f;\n }",
"public ModelSource resolveModel( Parent parent )\r\n throws UnresolvableModelException {\r\n\r\n Dependency parentDependency = new Dependency();\r\n parentDependency.setGroupId(parent.getGroupId());\r\n parentDependency.setArtifactId(parent.getArtifactId());\r\n parentDependency.setVersion(parent.getVersion());\r\n parentDependency.setClassifier(\"\");\r\n parentDependency.setType(\"pom\");\r\n\r\n Artifact parentArtifact = null;\r\n try\r\n {\r\n Iterable<ArtifactResult> artifactResults = depencencyResolver.resolveDependencies(\r\n projectBuildingRequest, singleton(parentDependency), null, null );\r\n Iterator<ArtifactResult> iterator = artifactResults.iterator();\r\n if (iterator.hasNext()) {\r\n parentArtifact = iterator.next().getArtifact();\r\n }\r\n } catch (DependencyResolverException e) {\r\n throw new UnresolvableModelException( e.getMessage(), parent.getGroupId(), parent.getArtifactId(),\r\n parent.getVersion(), e );\r\n }\r\n\r\n return resolveModel( parentArtifact.getGroupId(), parentArtifact.getArtifactId(), parentArtifact.getVersion() );\r\n }",
"public ApiClient setHttpClient(OkHttpClient newHttpClient) {\n if (!httpClient.equals(newHttpClient)) {\n newHttpClient.networkInterceptors().addAll(httpClient.networkInterceptors());\n httpClient.networkInterceptors().clear();\n newHttpClient.interceptors().addAll(httpClient.interceptors());\n httpClient.interceptors().clear();\n this.httpClient = newHttpClient;\n }\n return this;\n }",
"private void writeResourceAssignmentWorkgroupFields(ResourceAssignmentWorkgroupFields record) throws IOException\n {\n m_buffer.setLength(0);\n\n m_buffer.append(MPXConstants.RESOURCE_ASSIGNMENT_WORKGROUP_FIELDS_RECORD_NUMBER);\n m_buffer.append(m_delimiter);\n m_buffer.append(format(record.getMessageUniqueID()));\n m_buffer.append(m_delimiter);\n m_buffer.append(record.getConfirmed() ? \"1\" : \"0\");\n m_buffer.append(m_delimiter);\n m_buffer.append(record.getResponsePending() ? \"1\" : \"0\");\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDateTimeNull(record.getUpdateStart())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDateTimeNull(record.getUpdateFinish())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(record.getScheduleID()));\n\n stripTrailingDelimiters(m_buffer);\n m_buffer.append(MPXConstants.EOL);\n\n m_writer.write(m_buffer.toString());\n }"
] |
Reads a markdown link ID.
@param out
The StringBuilder to write to.
@param in
Input String.
@param start
Starting position.
@return The new position or -1 if this is no valid markdown link ID. | [
"public final static int readMdLinkId(final StringBuilder out, final String in, final int start)\n {\n int pos = start;\n int counter = 1;\n while (pos < in.length())\n {\n final char ch = in.charAt(pos);\n boolean endReached = false;\n switch (ch)\n {\n case '\\n':\n out.append(' ');\n break;\n case '[':\n counter++;\n out.append(ch);\n break;\n case ']':\n counter--;\n if (counter == 0)\n {\n endReached = true;\n }\n else\n {\n out.append(ch);\n }\n break;\n default:\n out.append(ch);\n break;\n }\n if (endReached)\n {\n break;\n }\n pos++;\n }\n\n return (pos == in.length()) ? -1 : pos;\n }"
] | [
"GVRShader makeTemplate(Class<? extends GVRShader> id, GVRContext ctx)\n {\n try\n {\n Constructor<? extends GVRShader> maker = id.getDeclaredConstructor(GVRContext.class);\n return maker.newInstance(ctx);\n }\n catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex)\n {\n try\n {\n Constructor<? extends GVRShader> maker = id.getDeclaredConstructor();\n return maker.newInstance();\n }\n catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex2)\n {\n ctx.getEventManager().sendEvent(ctx, IErrorEvents.class, \"onError\", new Object[] {ex2.getMessage(), this});\n return null;\n }\n }\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}",
"public static Attachment fromBinaryInputStream( InputStream inputStream, MediaType mediaType ) throws IOException {\n return fromBinaryBytes( ByteStreams.toByteArray( inputStream ), mediaType );\n }",
"public boolean setCustomResponse(String pathValue, String requestType, String customData) {\n try {\n JSONObject path = getPathFromEndpoint(pathValue, requestType);\n if (path == null) {\n String pathName = pathValue;\n createPath(pathName, pathValue, requestType);\n path = getPathFromEndpoint(pathValue, requestType);\n }\n String pathId = path.getString(\"pathId\");\n resetResponseOverride(pathId);\n setCustomResponse(pathId, customData);\n return toggleResponseOverride(pathId, true);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }",
"private boolean hasReceivedHeartbeat() {\n long currentTimeMillis = System.currentTimeMillis();\n boolean result = lastTimeMessageReceived + heartbeatTimeoutMs >= currentTimeMillis;\n\n if (!result)\n Jvm.warn().on(getClass(), Integer.toHexString(hashCode()) + \" missed heartbeat, lastTimeMessageReceived=\" + lastTimeMessageReceived\n + \", currentTimeMillis=\" + currentTimeMillis);\n return result;\n }",
"@UiHandler(\"m_atDay\")\r\n void onWeekDayChange(ValueChangeEvent<String> event) {\r\n\r\n if (handleChange()) {\r\n m_controller.setWeekDay(event.getValue());\r\n }\r\n }",
"public static void applyHyperLinkToElement(DynamicJasperDesign design, DJHyperLink djlink, JRDesignChart chart, String name) {\n\t\tJRDesignExpression hlpe = ExpressionUtils.createAndRegisterExpression(design, name, djlink.getExpression());\n\t\tchart.setHyperlinkReferenceExpression(hlpe);\n\t\tchart.setHyperlinkType( HyperlinkTypeEnum.REFERENCE ); //FIXME Should this be a parameter in the future?\n\t\t\t\t\n\t\tif (djlink.getTooltip() != null){\t\t\t\n\t\t\tJRDesignExpression tooltipExp = ExpressionUtils.createAndRegisterExpression(design, \"tooltip_\" + name, djlink.getTooltip());\n\t\t\tchart.setHyperlinkTooltipExpression(tooltipExp);\n\t\t}\n\t}",
"@SuppressWarnings(\"unchecked\")\n public static <T> AttachmentKey<T> create(final Class<? super T> valueClass) {\n return new SimpleAttachmentKey(valueClass);\n }",
"@Override\n\tpublic Object[] getDatabaseSnapshot(Serializable id, SharedSessionContractImplementor session)\n\t\t\tthrows HibernateException {\n\n\t\tif ( log.isTraceEnabled() ) {\n\t\t\tlog.trace( \"Getting current persistent state for: \" + MessageHelper.infoString( this, id, getFactory() ) );\n\t\t}\n\n\t\t//snapshot is a Map in the end\n\t\tfinal Tuple resultset = getFreshTuple( EntityKeyBuilder.fromPersister( this, id, session ), session );\n\n\t\t//if there is no resulting row, return null\n\t\tif ( resultset == null || resultset.getSnapshot().isEmpty() ) {\n\t\t\treturn null;\n\t\t}\n\t\t//otherwise return the \"hydrated\" state (ie. associations are not resolved)\n\t\tGridType[] types = gridPropertyTypes;\n\t\tObject[] values = new Object[types.length];\n\t\tboolean[] includeProperty = getPropertyUpdateability();\n\t\tfor ( int i = 0; i < types.length; i++ ) {\n\t\t\tif ( includeProperty[i] ) {\n\t\t\t\tvalues[i] = types[i].hydrate( resultset, getPropertyAliases( \"\", i ), session, null ); //null owner ok??\n\t\t\t}\n\t\t}\n\t\treturn values;\n\t}"
] |
Test whether the operation has a defined criteria attribute.
@param operation the operation
@return | [
"public static boolean isOperationDefined(final ModelNode operation) {\n for (final AttributeDefinition def : ROOT_ATTRIBUTES) {\n if (operation.hasDefined(def.getName())) {\n return true;\n }\n }\n return false;\n }"
] | [
"public static double blackModelSwaptionValue(\n\t\t\tdouble forwardSwaprate,\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike,\n\t\t\tdouble swapAnnuity)\n\t{\n\t\t// May be interpreted as a special version of the Black-Scholes Formula\n\t\treturn AnalyticFormulas.blackScholesGeneralizedOptionValue(forwardSwaprate, volatility, optionMaturity, optionStrike, swapAnnuity);\n\t}",
"private Map<String, String> generateCommonConfigPart() {\n\n Map<String, String> result = new HashMap<>();\n if (m_category != null) {\n result.put(CONFIGURATION_CATEGORY, m_category);\n }\n // append 'only leafs' to configuration\n if (m_onlyLeafs) {\n result.put(CONFIGURATION_ONLYLEAFS, null);\n }\n // append 'property' to configuration\n if (m_property != null) {\n result.put(CONFIGURATION_PROPERTY, m_property);\n }\n // append 'selectionType' to configuration\n if (m_selectiontype != null) {\n result.put(CONFIGURATION_SELECTIONTYPE, m_selectiontype);\n }\n return result;\n }",
"private Response sendJsonPostOrPut(OauthToken token, String url, String json,\n int connectTimeout, int readTimeout, String method) throws IOException {\n LOG.debug(\"Sending JSON \" + method + \" to URL: \" + url);\n Response response = new Response();\n\n HttpClient httpClient = createHttpClient(connectTimeout, readTimeout);\n HttpEntityEnclosingRequestBase action;\n if(\"POST\".equals(method)) {\n action = new HttpPost(url);\n } else if(\"PUT\".equals(method)) {\n action = new HttpPut(url);\n } else {\n throw new IllegalArgumentException(\"Method must be either POST or PUT\");\n }\n Long beginTime = System.currentTimeMillis();\n action.setHeader(\"Authorization\", \"Bearer\" + \" \" + token.getAccessToken());\n\n StringEntity requestBody = new StringEntity(json, ContentType.APPLICATION_JSON);\n action.setEntity(requestBody);\n try {\n HttpResponse httpResponse = httpClient.execute(action);\n\n String content = handleResponse(httpResponse, action);\n\n response.setContent(content);\n response.setResponseCode(httpResponse.getStatusLine().getStatusCode());\n Long endTime = System.currentTimeMillis();\n LOG.debug(\"POST call took: \" + (endTime - beginTime) + \"ms\");\n } finally {\n action.releaseConnection();\n }\n\n return response;\n }",
"public void writeNameValuePair(String name, int value) throws IOException\n {\n internalWriteNameValuePair(name, Integer.toString(value));\n }",
"public void inverse(GVRPose src)\n {\n if (getSkeleton() != src.getSkeleton())\n throw new IllegalArgumentException(\"GVRPose.copy: input pose is incompatible with this pose\");\n src.sync();\n int numbones = getNumBones();\n Bone srcBone = src.mBones[0];\n Bone dstBone = mBones[0];\n\n mNeedSync = true;\n srcBone.WorldMatrix.invertAffine(dstBone.WorldMatrix);\n srcBone.LocalMatrix.set(dstBone.WorldMatrix);\n if (sDebug)\n {\n Log.d(\"BONE\", \"invert: %s %s\", mSkeleton.getBoneName(0), dstBone.toString());\n\n }\n for (int i = 1; i < numbones; ++i)\n {\n srcBone = src.mBones[i];\n dstBone = mBones[i];\n srcBone.WorldMatrix.invertAffine(dstBone.WorldMatrix);\n dstBone.Changed = WORLD_ROT | WORLD_POS;\n if (sDebug)\n {\n Log.d(\"BONE\", \"invert: %s %s\", mSkeleton.getBoneName(i), dstBone.toString());\n }\n }\n sync();\n }",
"public void write(Configuration config)\n throws IOException {\n\n pp.startDocument();\n pp.startElement(\"duke\", null);\n\n // FIXME: here we should write the objects, but that's not\n // possible with the current API. we don't need that for the\n // genetic algorithm at the moment, but it would be useful.\n\n pp.startElement(\"schema\", null);\n\n writeElement(\"threshold\", \"\" + config.getThreshold());\n if (config.getMaybeThreshold() != 0.0)\n writeElement(\"maybe-threshold\", \"\" + config.getMaybeThreshold());\n\n for (Property p : config.getProperties())\n writeProperty(p);\n\n pp.endElement(\"schema\");\n\n String dbclass = config.getDatabase(false).getClass().getName();\n AttributeListImpl atts = new AttributeListImpl();\n atts.addAttribute(\"class\", \"CDATA\", dbclass);\n pp.startElement(\"database\", atts);\n pp.endElement(\"database\");\n\n if (config.isDeduplicationMode())\n for (DataSource src : config.getDataSources())\n writeDataSource(src);\n else {\n pp.startElement(\"group\", null);\n for (DataSource src : config.getDataSources(1))\n writeDataSource(src);\n pp.endElement(\"group\");\n\n pp.startElement(\"group\", null);\n for (DataSource src : config.getDataSources(2))\n writeDataSource(src);\n pp.endElement(\"group\");\n }\n\n pp.endElement(\"duke\");\n pp.endDocument();\n }",
"public void forAllProcedureArguments(String template, Properties attributes) throws XDocletException\r\n {\r\n String argNameList = _curProcedureDef.getProperty(PropertyHelper.OJB_PROPERTY_ARGUMENTS);\r\n\r\n for (CommaListIterator it = new CommaListIterator(argNameList); it.hasNext();)\r\n {\r\n _curProcedureArgumentDef = _curClassDef.getProcedureArgument(it.getNext());\r\n generate(template);\r\n }\r\n _curProcedureArgumentDef = null;\r\n }",
"public void addAccessory(HomekitAccessory accessory) {\n if (accessory.getId() <= 1 && !(accessory instanceof Bridge)) {\n throw new IndexOutOfBoundsException(\n \"The ID of an accessory used in a bridge must be greater than 1\");\n }\n addAccessorySkipRangeCheck(accessory);\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<DiscordianDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<DiscordianDate>) super.zonedDateTime(temporal);\n }"
] |
Utils for making collections out of arrays of primitive types. | [
"public static List<Integer> asList(int[] a) {\r\n List<Integer> result = new ArrayList<Integer>(a.length);\r\n for (int i = 0; i < a.length; i++) {\r\n result.add(Integer.valueOf(a[i]));\r\n }\r\n return result;\r\n }"
] | [
"public int delete(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException {\n\t\tif (mappedDelete == null) {\n\t\t\tmappedDelete = MappedDelete.build(dao, tableInfo);\n\t\t}\n\t\tint result = mappedDelete.delete(databaseConnection, data, objectCache);\n\t\tif (dao != null && !localIsInBatchMode.get()) {\n\t\t\tdao.notifyChanges();\n\t\t}\n\t\treturn result;\n\t}",
"public void forAllProcedures(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _curClassDef.getProcedures(); it.hasNext(); )\r\n {\r\n _curProcedureDef = (ProcedureDef)it.next();\r\n generate(template);\r\n }\r\n _curProcedureDef = null;\r\n }",
"public static String getFailureDescriptionAsString(final ModelNode result) {\n if (isSuccessfulOutcome(result)) {\n return \"\";\n }\n final String msg;\n if (result.hasDefined(ClientConstants.FAILURE_DESCRIPTION)) {\n if (result.hasDefined(ClientConstants.OP)) {\n msg = String.format(\"Operation '%s' at address '%s' failed: %s\", result.get(ClientConstants.OP), result.get(ClientConstants.OP_ADDR), result\n .get(ClientConstants.FAILURE_DESCRIPTION));\n } else {\n msg = String.format(\"Operation failed: %s\", result.get(ClientConstants.FAILURE_DESCRIPTION));\n }\n } else {\n msg = String.format(\"An unexpected response was found checking the deployment. Result: %s\", result);\n }\n return msg;\n }",
"public 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 void read(InputStream is) throws IOException\n {\n byte[] headerBlock = new byte[20];\n is.read(headerBlock);\n\n int headerLength = PEPUtility.getShort(headerBlock, 8);\n int recordCount = PEPUtility.getInt(headerBlock, 10);\n int recordLength = PEPUtility.getInt(headerBlock, 16);\n StreamHelper.skip(is, headerLength - headerBlock.length);\n\n byte[] record = new byte[recordLength];\n for (int recordIndex = 1; recordIndex <= recordCount; recordIndex++)\n {\n is.read(record);\n readRow(recordIndex, record);\n }\n }",
"private double goldenMean(double a, double b) {\r\n if (geometric) {\r\n return a * Math.pow(b / a, GOLDEN_SECTION);\r\n } else {\r\n return a + (b - a) * GOLDEN_SECTION;\r\n }\r\n }",
"void setFilters(Map<Object, Object> filters) {\n\n for (Object column : filters.keySet()) {\n Object filterValue = filters.get(column);\n if ((filterValue != null) && !filterValue.toString().isEmpty() && !m_table.isColumnCollapsed(column)) {\n m_table.setFilterFieldValue(column, filterValue);\n }\n }\n }",
"protected void destroyRequest(AsyncResourceRequest<V> resourceRequest) {\n if(resourceRequest != null) {\n try {\n // To hand control back to the owner of the\n // AsyncResourceRequest, treat \"destroy\" as an exception since\n // there is no resource to pass into useResource, and the\n // timeout has not expired.\n Exception e = new UnreachableStoreException(\"Client request was terminated while waiting in the queue.\");\n resourceRequest.handleException(e);\n } catch(Exception ex) {\n logger.error(\"Exception while destroying resource request:\", ex);\n }\n }\n }",
"public void writeNameValuePair(String name, double value) throws IOException\n {\n internalWriteNameValuePair(name, Double.toString(value));\n }"
] |
Sets the ssh priv key relative path wtih passphrase.
@param privKeyRelativePath the priv key relative path
@param passphrase the passphrase
@return the parallel task builder | [
"public ParallelTaskBuilder setSshPrivKeyRelativePathWtihPassphrase(\n String privKeyRelativePath, String passphrase) {\n this.sshMeta.setPrivKeyRelativePath(privKeyRelativePath);\n this.sshMeta.setPrivKeyUsePassphrase(true);\n this.sshMeta.setPassphrase(passphrase);\n this.sshMeta.setSshLoginType(SshLoginType.KEY);\n return this;\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 }",
"private void cascadeInsertFor(ObjectEnvelope mod, List alreadyPrepared)\r\n {\r\n // avoid endless recursion, so use List for registration\r\n if(alreadyPrepared.contains(mod.getIdentity())) return;\r\n alreadyPrepared.add(mod.getIdentity());\r\n\r\n ClassDescriptor cld = getTransaction().getBroker().getClassDescriptor(mod.getObject().getClass());\r\n\r\n List refs = cld.getObjectReferenceDescriptors(true);\r\n cascadeInsertSingleReferences(mod, refs, alreadyPrepared);\r\n\r\n List colls = cld.getCollectionDescriptors(true);\r\n cascadeInsertCollectionReferences(mod, colls, alreadyPrepared);\r\n }",
"public <T> T callFunction(\n final String name,\n final List<?> args,\n final @Nullable Long requestTimeout,\n final Class<T> resultClass,\n final CodecRegistry codecRegistry\n ) {\n return this.functionService\n .withCodecRegistry(codecRegistry)\n .callFunction(name, args, requestTimeout, resultClass);\n }",
"private void deselectChildren(CmsTreeItem item) {\r\n\r\n for (String childId : m_childrens.get(item.getId())) {\r\n CmsTreeItem child = m_categories.get(childId);\r\n deselectChildren(child);\r\n child.getCheckBox().setChecked(false);\r\n if (m_selectedCategories.contains(childId)) {\r\n m_selectedCategories.remove(childId);\r\n }\r\n }\r\n }",
"public void setT(int t) {\r\n this.t = Math.min((radius * 2 + 1) * (radius * 2 + 1) / 2, Math.max(0, t));\r\n }",
"private void populateEntityMap() throws SQLException\n {\n for (Row row : getRows(\"select * from z_primarykey\"))\n {\n m_entityMap.put(row.getString(\"Z_NAME\"), row.getInteger(\"Z_ENT\"));\n }\n }",
"private void readUnread(CommitData cd, Consumer<Entry<Key, Value>> locksSeen) {\n // TODO make async\n // TODO need to keep track of ranges read (not ranges passed in, but actual data read... user\n // may not iterate over entire range\n Map<Bytes, Set<Column>> columnsToRead = new HashMap<>();\n\n for (Entry<Bytes, Set<Column>> entry : cd.getRejected().entrySet()) {\n Set<Column> rowColsRead = columnsRead.get(entry.getKey());\n if (rowColsRead == null) {\n columnsToRead.put(entry.getKey(), entry.getValue());\n } else {\n HashSet<Column> colsToRead = new HashSet<>(entry.getValue());\n colsToRead.removeAll(rowColsRead);\n if (!colsToRead.isEmpty()) {\n columnsToRead.put(entry.getKey(), colsToRead);\n }\n }\n }\n\n for (Entry<Bytes, Set<Column>> entry : columnsToRead.entrySet()) {\n getImpl(entry.getKey(), entry.getValue(), locksSeen);\n }\n }",
"private PersistenceBroker obtainBroker()\r\n {\r\n PersistenceBroker _broker;\r\n try\r\n {\r\n if (pbKey == null)\r\n {\r\n //throw new OJBRuntimeException(\"Not possible to do action, cause no tx runnning and no PBKey is set\");\r\n log.warn(\"No tx runnning and PBKey is null, try to use the default PB\");\r\n _broker = PersistenceBrokerFactory.defaultPersistenceBroker();\r\n }\r\n else\r\n {\r\n _broker = PersistenceBrokerFactory.createPersistenceBroker(pbKey);\r\n }\r\n }\r\n catch (PBFactoryException e)\r\n {\r\n log.error(\"Could not obtain PB for PBKey \" + pbKey, e);\r\n throw new OJBRuntimeException(\"Unexpected micro-kernel exception\", e);\r\n }\r\n return _broker;\r\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 }"
] |
Generic method to extract Primavera fields and assign to MPXJ fields.
@param map map of MPXJ field types and Primavera field names
@param row Primavera data container
@param container MPXJ data contain | [
"private void processFields(Map<FieldType, String> map, Row row, FieldContainer container)\n {\n for (Map.Entry<FieldType, String> entry : map.entrySet())\n {\n FieldType field = entry.getKey();\n String name = entry.getValue();\n\n Object value;\n switch (field.getDataType())\n {\n case INTEGER:\n {\n value = row.getInteger(name);\n break;\n }\n\n case BOOLEAN:\n {\n value = Boolean.valueOf(row.getBoolean(name));\n break;\n }\n\n case DATE:\n {\n value = row.getDate(name);\n break;\n }\n\n case CURRENCY:\n case NUMERIC:\n case PERCENTAGE:\n {\n value = row.getDouble(name);\n break;\n }\n\n case DELAY:\n case WORK:\n case DURATION:\n {\n value = row.getDuration(name);\n break;\n }\n\n case RESOURCE_TYPE:\n {\n value = RESOURCE_TYPE_MAP.get(row.getString(name));\n break;\n }\n\n case TASK_TYPE:\n {\n value = TASK_TYPE_MAP.get(row.getString(name));\n break;\n }\n\n case CONSTRAINT:\n {\n value = CONSTRAINT_TYPE_MAP.get(row.getString(name));\n break;\n }\n\n case PRIORITY:\n {\n value = PRIORITY_MAP.get(row.getString(name));\n break;\n }\n\n case GUID:\n {\n value = row.getUUID(name);\n break;\n }\n\n default:\n {\n value = row.getString(name);\n break;\n }\n }\n\n container.set(field, value);\n }\n }"
] | [
"public static double elementMax( DMatrixSparseCSC A ) {\n if( A.nz_length == 0)\n return 0;\n\n // if every element is assigned a value then the first element can be a max.\n // Otherwise zero needs to be considered\n double max = A.isFull() ? A.nz_values[0] : 0;\n for(int i = 0; i < A.nz_length; i++ ) {\n double val = A.nz_values[i];\n if( val > max ) {\n max = val;\n }\n }\n\n return max;\n }",
"public Token add( Symbol symbol ) {\n Token t = new Token(symbol);\n push( t );\n return t;\n }",
"public static PersistenceBroker createPersistenceBroker(String jcdAlias,\r\n String user,\r\n String password) throws PBFactoryException\r\n {\r\n return PersistenceBrokerFactoryFactory.instance().\r\n createPersistenceBroker(jcdAlias, user, password);\r\n }",
"public void reportSqlError(String message, java.sql.SQLException sqlEx)\r\n {\r\n StringBuffer strBufMessages = new StringBuffer();\r\n java.sql.SQLException currentSqlEx = sqlEx;\r\n do\r\n {\r\n strBufMessages.append(\"\\n\" + sqlEx.getErrorCode() + \":\" + sqlEx.getMessage());\r\n currentSqlEx = currentSqlEx.getNextException();\r\n } while (currentSqlEx != null); \r\n System.err.println(message + strBufMessages.toString());\r\n sqlEx.printStackTrace();\r\n }",
"public void setStartTime(final Date date) {\r\n\r\n if (!Objects.equals(m_model.getStart(), date)) {\r\n removeExceptionsOnChange(new Command() {\r\n\r\n public void execute() {\r\n\r\n m_model.setStart(date);\r\n setPatternDefaultValues(date);\r\n valueChanged();\r\n }\r\n });\r\n }\r\n\r\n }",
"@Override\n public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {\n\n final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();\n List<ResourceRoot> resourceRoots = DeploymentUtils.allResourceRoots(deploymentUnit);\n for (ResourceRoot resourceRoot : resourceRoots) {\n if (IgnoreMetaInfMarker.isIgnoreMetaInf(resourceRoot)) {\n continue;\n }\n Manifest manifest = getManifest(resourceRoot);\n if (manifest != null)\n resourceRoot.putAttachment(Attachments.MANIFEST, manifest);\n }\n }",
"public Diff compare(String left, String right) {\n\t\treturn compare(getCtType(left), getCtType(right));\n\t}",
"private void readHeaderProperties(BufferedInputStream stream) throws IOException\n {\n String header = readHeaderString(stream);\n for (String property : header.split(\"\\\\|\"))\n {\n String[] expression = property.split(\"=\");\n m_properties.put(expression[0], expression[1]);\n }\n }",
"public static void setField(Object object, String field, Object value) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {\n\t\tClass<?> clazz = object.getClass();\n\t\tMethod m = clazz.getMethod( PROPERTY_ACCESSOR_PREFIX_SET + capitalize( field ), value.getClass() );\n\t\tm.invoke( object, value );\n\t}"
] |
Answers the ClassDescriptor referenced by 'super' ReferenceDescriptor.
@return ClassDescriptor or null | [
"public ClassDescriptor getSuperClassDescriptor()\r\n {\r\n if (!m_superCldSet)\r\n {\r\n if(getBaseClass() != null)\r\n {\r\n m_superCld = getRepository().getDescriptorFor(getBaseClass());\r\n if(m_superCld.isAbstract() || m_superCld.isInterface())\r\n {\r\n throw new MetadataException(\"Super class mapping only work for real class, but declared super class\" +\r\n \" is an interface or is abstract. Declared class: \" + m_superCld.getClassNameOfObject());\r\n }\r\n }\r\n m_superCldSet = true;\r\n }\r\n\r\n return m_superCld;\r\n }"
] | [
"public UriComponentsBuilder queryParams(MultiValueMap<String, String> params) {\n\t\tAssert.notNull(params, \"'params' must not be null\");\n\t\tthis.queryParams.putAll(params);\n\t\treturn this;\n\t}",
"public void setOffset(float offset, final Axis axis) {\n if (!equal(mOffset.get(axis), offset)) {\n mOffset.set(offset, axis);\n if (mContainer != null) {\n mContainer.onLayoutChanged(this);\n }\n }\n }",
"public static base_response add(nitro_service client, appfwjsoncontenttype resource) throws Exception {\n\t\tappfwjsoncontenttype addresource = new appfwjsoncontenttype();\n\t\taddresource.jsoncontenttypevalue = resource.jsoncontenttypevalue;\n\t\taddresource.isregex = resource.isregex;\n\t\treturn addresource.add_resource(client);\n\t}",
"@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 }",
"@Beta(SinceVersion.V1_1_0)\n public void close() {\n httpClient.dispatcher().executorService().shutdown();\n httpClient.connectionPool().evictAll();\n synchronized (httpClient.connectionPool()) {\n httpClient.connectionPool().notifyAll();\n }\n synchronized (AsyncTimeout.class) {\n AsyncTimeout.class.notifyAll();\n }\n }",
"@Override\n public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {\n try {\n if (exceptionRaised.get()) {\n return;\n }\n\n if (!(msg instanceof HttpRequest)) {\n // If there is no methodInfo, it means the request was already rejected.\n // What we received here is just residue of the request, which can be ignored.\n if (methodInfo != null) {\n ReferenceCountUtil.retain(msg);\n ctx.fireChannelRead(msg);\n }\n return;\n }\n HttpRequest request = (HttpRequest) msg;\n BasicHttpResponder responder = new BasicHttpResponder(ctx.channel(), sslEnabled);\n\n // Reset the methodInfo for the incoming request error handling\n methodInfo = null;\n methodInfo = prepareHandleMethod(request, responder, ctx);\n\n if (methodInfo != null) {\n ReferenceCountUtil.retain(msg);\n ctx.fireChannelRead(msg);\n } else {\n if (!responder.isResponded()) {\n // If not yet responded, just respond with a not found and close the connection\n HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);\n HttpUtil.setContentLength(response, 0);\n HttpUtil.setKeepAlive(response, false);\n ctx.channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);\n } else {\n // If already responded, just close the connection\n ctx.channel().close();\n }\n }\n } finally {\n ReferenceCountUtil.release(msg);\n }\n }",
"public Map getPathClasses()\r\n\t{\r\n\t\tif (m_pathClasses.isEmpty())\r\n\t\t{\r\n\t\t\tif (m_parentCriteria == null)\r\n\t\t\t{\r\n\t\t\t\tif (m_query == null)\r\n\t\t\t\t{\r\n\t\t\t\t\treturn m_pathClasses;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\treturn m_query.getPathClasses();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\treturn m_parentCriteria.getPathClasses();\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn m_pathClasses;\r\n\t\t}\r\n\t}",
"private boolean getRelative(int value)\n {\n boolean result;\n if (value < 0 || value >= RELATIVE_MAP.length)\n {\n result = false;\n }\n else\n {\n result = RELATIVE_MAP[value];\n }\n\n return result;\n }",
"public static ResourceKey key(Enum<?> enumValue, String key) {\n return new ResourceKey(enumValue.getClass().getName(), enumValue.name()).child(key);\n }"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.