query
stringlengths 7
3.3k
| positive
sequencelengths 1
1
| negative
sequencelengths 9
9
|
---|---|---|
from IsoFields in ThreeTen-Backport | [
"private static int weekRange(int weekBasedYear) {\n LocalDate date = LocalDate.of(weekBasedYear, 1, 1);\n // 53 weeks if year starts on Thursday, or Wed in a leap year\n if (date.getDayOfWeek() == THURSDAY || (date.getDayOfWeek() == WEDNESDAY && date.isLeapYear())) {\n return 53;\n }\n return 52;\n }"
] | [
"@UiHandler(\"m_currentTillEndCheckBox\")\n void onCurrentTillEndChange(ValueChangeEvent<Boolean> event) {\n\n if (handleChange()) {\n m_controller.setCurrentTillEnd(event.getValue());\n }\n }",
"public static void addOperation(final OperationContext context) {\n RbacSanityCheckOperation added = context.getAttachment(KEY);\n if (added == null) {\n // TODO support managed domain\n if (!context.isNormalServer()) return;\n context.addStep(createOperation(), INSTANCE, Stage.MODEL);\n context.attach(KEY, INSTANCE);\n }\n }",
"private static int getTrimmedWidth(BufferedImage img) {\n int height = img.getHeight();\n int width = img.getWidth();\n int trimmedWidth = 0;\n\n for (int i = 0; i < height; i++) {\n for (int j = width - 1; j >= 0; j--) {\n if (img.getRGB(j, i) != Color.WHITE.getRGB() && j > trimmedWidth) {\n trimmedWidth = j;\n break;\n }\n }\n }\n\n return trimmedWidth;\n }",
"public final void setConfigurationFiles(final Map<String, String> configurationFiles)\n throws URISyntaxException {\n this.configurationFiles.clear();\n this.configurationFileLastModifiedTimes.clear();\n for (Map.Entry<String, String> entry: configurationFiles.entrySet()) {\n if (!entry.getValue().contains(\":/\")) {\n // assume is a file\n this.configurationFiles.put(entry.getKey(), new File(entry.getValue()).toURI());\n } else {\n this.configurationFiles.put(entry.getKey(), new URI(entry.getValue()));\n }\n }\n\n if (this.configFileLoader != null) {\n this.validateConfigurationFiles();\n }\n }",
"public double getValueAsPrice(double evaluationTime, AnalyticModel model) {\n\t\tForwardCurve\tforwardCurve\t= model.getForwardCurve(forwardCurveName);\n\t\tDiscountCurve\tdiscountCurve\t= model.getDiscountCurve(discountCurveName);\n\n\t\tDiscountCurve\tdiscountCurveForForward = null;\n\t\tif(forwardCurve == null && forwardCurveName != null && forwardCurveName.length() > 0) {\n\t\t\t// User might like to get forward from discount curve.\n\t\t\tdiscountCurveForForward\t= model.getDiscountCurve(forwardCurveName);\n\n\t\t\tif(discountCurveForForward == null) {\n\t\t\t\t// User specified a name for the forward curve, but no curve was found.\n\t\t\t\tthrow new IllegalArgumentException(\"No curve of the name \" + forwardCurveName + \" was found in the model.\");\n\t\t\t}\n\t\t}\n\n\t\tdouble value = 0.0;\n\t\tfor(int periodIndex=0; periodIndex<schedule.getNumberOfPeriods(); periodIndex++) {\n\t\t\tdouble fixingDate\t= schedule.getFixing(periodIndex);\n\t\t\tdouble paymentDate\t= schedule.getPayment(periodIndex);\n\t\t\tdouble periodLength\t= schedule.getPeriodLength(periodIndex);\n\n\t\t\t/*\n\t\t\t * We do not count empty periods.\n\t\t\t * Since empty periods are an indication for a ill-specified product,\n\t\t\t * it might be reasonable to throw an illegal argument exception instead.\n\t\t\t */\n\t\t\tif(periodLength == 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tdouble forward = 0.0;\n\t\t\tif(forwardCurve != null) {\n\t\t\t\tforward\t\t\t+= forwardCurve.getForward(model, fixingDate, paymentDate-fixingDate);\n\t\t\t}\n\t\t\telse if(discountCurveForForward != null) {\n\t\t\t\t/*\n\t\t\t\t * Classical single curve case: using a discount curve as a forward curve.\n\t\t\t\t * This is only implemented for demonstration purposes (an exception would also be appropriate :-)\n\t\t\t\t */\n\t\t\t\tif(fixingDate != paymentDate) {\n\t\t\t\t\tforward\t\t\t+= (discountCurveForForward.getDiscountFactor(fixingDate) / discountCurveForForward.getDiscountFactor(paymentDate) - 1.0) / (paymentDate-fixingDate);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdouble discountFactor\t= paymentDate > evaluationTime ? discountCurve.getDiscountFactor(model, paymentDate) : 0.0;\n\t\t\tdouble payoffUnit = discountFactor * periodLength;\n\n\t\t\tdouble effektiveStrike = strike;\n\t\t\tif(isStrikeMoneyness) {\n\t\t\t\teffektiveStrike += getATMForward(model, true);\n\t\t\t}\n\n\t\t\tVolatilitySurface volatilitySurface\t= model.getVolatilitySurface(volatiltiySufaceName);\n\t\t\tif(volatilitySurface == null) {\n\t\t\t\tthrow new IllegalArgumentException(\"Volatility surface not found in model: \" + volatiltiySufaceName);\n\t\t\t}\n\t\t\tif(volatilitySurface.getQuotingConvention() == QuotingConvention.VOLATILITYLOGNORMAL) {\n\t\t\t\tdouble volatility = volatilitySurface.getValue(model, fixingDate, effektiveStrike, VolatilitySurface.QuotingConvention.VOLATILITYLOGNORMAL);\n\t\t\t\tvalue += AnalyticFormulas.blackScholesGeneralizedOptionValue(forward, volatility, fixingDate, effektiveStrike, payoffUnit);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Default to normal volatility as quoting convention\n\t\t\t\tdouble volatility = volatilitySurface.getValue(model, fixingDate, effektiveStrike, VolatilitySurface.QuotingConvention.VOLATILITYNORMAL);\n\t\t\t\tvalue += AnalyticFormulas.bachelierOptionValue(forward, volatility, fixingDate, effektiveStrike, payoffUnit);\n\t\t\t}\n\t\t}\n\n\t\treturn value / discountCurve.getDiscountFactor(model, evaluationTime);\n\t}",
"public void unlink(Object obj, ObjectReferenceDescriptor ord, boolean insert)\r\n {\r\n linkOrUnlink(false, obj, ord, insert);\r\n }",
"public static String implodeObjects(Iterable<?> objects) {\n\t\tStringBuilder builder = new StringBuilder();\n\t\tboolean first = true;\n\t\tfor (Object o : objects) {\n\t\t\tif (first) {\n\t\t\t\tfirst = false;\n\t\t\t} else {\n\t\t\t\tbuilder.append(\"|\");\n\t\t\t}\n\t\t\tbuilder.append(o.toString());\n\t\t}\n\t\treturn builder.toString();\n\t}",
"public static base_response add(nitro_service client, sslaction resource) throws Exception {\n\t\tsslaction addresource = new sslaction();\n\t\taddresource.name = resource.name;\n\t\taddresource.clientauth = resource.clientauth;\n\t\taddresource.clientcert = resource.clientcert;\n\t\taddresource.certheader = resource.certheader;\n\t\taddresource.clientcertserialnumber = resource.clientcertserialnumber;\n\t\taddresource.certserialheader = resource.certserialheader;\n\t\taddresource.clientcertsubject = resource.clientcertsubject;\n\t\taddresource.certsubjectheader = resource.certsubjectheader;\n\t\taddresource.clientcerthash = resource.clientcerthash;\n\t\taddresource.certhashheader = resource.certhashheader;\n\t\taddresource.clientcertissuer = resource.clientcertissuer;\n\t\taddresource.certissuerheader = resource.certissuerheader;\n\t\taddresource.sessionid = resource.sessionid;\n\t\taddresource.sessionidheader = resource.sessionidheader;\n\t\taddresource.cipher = resource.cipher;\n\t\taddresource.cipherheader = resource.cipherheader;\n\t\taddresource.clientcertnotbefore = resource.clientcertnotbefore;\n\t\taddresource.certnotbeforeheader = resource.certnotbeforeheader;\n\t\taddresource.clientcertnotafter = resource.clientcertnotafter;\n\t\taddresource.certnotafterheader = resource.certnotafterheader;\n\t\taddresource.owasupport = resource.owasupport;\n\t\treturn addresource.add_resource(client);\n\t}",
"public static Map<String, Object> introspect(Object obj) throws IntrospectionException, InvocationTargetException, IllegalAccessException {\n\t\tMap<String, Object> result = new HashMap<>();\n\t\tBeanInfo info = Introspector.getBeanInfo( obj.getClass() );\n\t\tfor ( PropertyDescriptor pd : info.getPropertyDescriptors() ) {\n\t\t\tMethod reader = pd.getReadMethod();\n\t\t\tString name = pd.getName();\n\t\t\tif ( reader != null && !\"class\".equals( name ) ) {\n\t\t\t\tresult.put( name, reader.invoke( obj ) );\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}"
] |
Sets the actual path for this ID
@param pathId ID of path
@param path value of path | [
"public void setPath(int pathId, String path) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + Constants.PATH_PROFILE_ACTUAL_PATH + \" = ? \" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, path);\n statement.setInt(2, pathId);\n statement.executeUpdate();\n statement.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }"
] | [
"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 }",
"private void maybeUpdateScrollbarPositions() {\r\n\r\n if (!isAttached()) {\r\n return;\r\n }\r\n\r\n if (m_scrollbar != null) {\r\n int vPos = getVerticalScrollPosition();\r\n if (m_scrollbar.getVerticalScrollPosition() != vPos) {\r\n m_scrollbar.setVerticalScrollPosition(vPos);\r\n }\r\n }\r\n }",
"public static <T> T invokeSetters(final T instance, final Map<String,Object> vars) \n throws ReflectiveOperationException {\n if (instance != null && vars != null) {\n final Class<?> clazz = instance.getClass();\n final Method[] methods = clazz.getMethods();\n for (final Entry<String,Object> entry : vars.entrySet()) {\n final String methodName = \"set\" + entry.getKey().substring(0, 1).toUpperCase(Locale.US) \n + entry.getKey().substring(1);\n boolean found = false;\n for (final Method method : methods) {\n if (methodName.equals(method.getName()) && method.getParameterTypes().length == 1) {\n method.invoke(instance, entry.getValue());\n found = true;\n break;\n }\n }\n if (!found) {\n throw new NoSuchMethodException(\"Expected setter named '\" + methodName \n + \"' for var '\" + entry.getKey() + \"'\");\n }\n }\n }\n return instance;\n }",
"protected FieldDescriptor getFieldDescriptor(TableAlias aTableAlias, PathInfo aPathInfo)\r\n {\r\n FieldDescriptor fld = null;\r\n String colName = aPathInfo.column;\r\n\r\n if (aTableAlias != null)\r\n {\r\n fld = aTableAlias.cld.getFieldDescriptorByName(colName);\r\n if (fld == null)\r\n {\r\n ObjectReferenceDescriptor ord = aTableAlias.cld.getObjectReferenceDescriptorByName(colName);\r\n if (ord != null)\r\n {\r\n fld = getFldFromReference(aTableAlias, ord);\r\n }\r\n else\r\n {\r\n fld = getFldFromJoin(aTableAlias, colName);\r\n }\r\n }\r\n }\r\n\r\n return fld;\r\n }",
"public static IPAddressSeqRange[] join(IPAddressSeqRange... ranges) {\n\t\tint joinedCount = 0;\n\t\tArrays.sort(ranges, Address.ADDRESS_LOW_VALUE_COMPARATOR);\n\t\tfor(int i = 0; i < ranges.length; i++) {\n\t\t\tIPAddressSeqRange range = ranges[i];\n\t\t\tif(range == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor(int j = i + 1; j < ranges.length; j++) {\n\t\t\t\tIPAddressSeqRange range2 = ranges[j];\n\t\t\t\tif(range2 == null) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tIPAddress upper = range.getUpper();\n\t\t\t\tIPAddress lower = range2.getLower();\n\t\t\t\tif(compareLowValues(upper, lower) >= 0\n\t\t\t\t\t\t|| upper.increment(1).equals(lower)) {\n\t\t\t\t\t//join them\n\t\t\t\t\tranges[i] = range = range.create(range.getLower(), range2.getUpper());\n\t\t\t\t\tranges[j] = null;\n\t\t\t\t\tjoinedCount++;\n\t\t\t\t} else break;\n\t\t\t}\n\t\t}\n\t\tif(joinedCount == 0) {\n\t\t\treturn ranges;\n\t\t}\n\t\tIPAddressSeqRange joined[] = new IPAddressSeqRange[ranges.length - joinedCount];\n\t\tfor(int i = 0, j = 0; i < ranges.length; i++) {\n\t\t\tIPAddressSeqRange range = ranges[i];\n\t\t\tif(range == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tjoined[j++] = range;\n\t\t\tif(j >= joined.length) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn joined;\n\t}",
"private String getCachedETag(HttpHost host, String file) {\n Map<String, Object> cachedETags = readCachedETags();\n\n @SuppressWarnings(\"unchecked\")\n Map<String, Object> hostMap =\n (Map<String, Object>)cachedETags.get(host.toURI());\n if (hostMap == null) {\n return null;\n }\n\n @SuppressWarnings(\"unchecked\")\n Map<String, String> etagMap = (Map<String, String>)hostMap.get(file);\n if (etagMap == null) {\n return null;\n }\n\n return etagMap.get(\"ETag\");\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}",
"public double areaSquared(HalfEdge hedge0, HalfEdge hedge1) {\n Point3d p0 = hedge0.tail().pnt;\n Point3d p1 = hedge0.head().pnt;\n Point3d p2 = hedge1.head().pnt;\n\n double dx1 = p1.x - p0.x;\n double dy1 = p1.y - p0.y;\n double dz1 = p1.z - p0.z;\n\n double dx2 = p2.x - p0.x;\n double dy2 = p2.y - p0.y;\n double dz2 = p2.z - p0.z;\n\n double x = dy1 * dz2 - dz1 * dy2;\n double y = dz1 * dx2 - dx1 * dz2;\n double z = dx1 * dy2 - dy1 * dx2;\n\n return x * x + y * y + z * z;\n }",
"public static List<String> readLines(CharSequence self) throws IOException {\n return IOGroovyMethods.readLines(new StringReader(self.toString()));\n }"
] |
Send a master handoff yield response to all registered listeners.
@param fromPlayer the device number that is responding to our request that it yield the tempo master role to us
@param yielded will be {@code true} if we should now be the tempo master | [
"private void deliverMasterYieldResponse(int fromPlayer, boolean yielded) {\n for (final MasterHandoffListener listener : getMasterHandoffListeners()) {\n try {\n listener.yieldResponse(fromPlayer, yielded);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering master yield response to listener\", t);\n }\n }\n }"
] | [
"public static base_responses update(nitro_service client, tmtrafficaction resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\ttmtrafficaction updateresources[] = new tmtrafficaction[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new tmtrafficaction();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].apptimeout = resources[i].apptimeout;\n\t\t\t\tupdateresources[i].sso = resources[i].sso;\n\t\t\t\tupdateresources[i].formssoaction = resources[i].formssoaction;\n\t\t\t\tupdateresources[i].persistentcookie = resources[i].persistentcookie;\n\t\t\t\tupdateresources[i].initiatelogout = resources[i].initiatelogout;\n\t\t\t\tupdateresources[i].kcdaccount = resources[i].kcdaccount;\n\t\t\t\tupdateresources[i].samlssoprofile = resources[i].samlssoprofile;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"private boolean isSplit(ProjectCalendar calendar, List<TimephasedWork> list)\n {\n boolean result = false;\n for (TimephasedWork assignment : list)\n {\n if (calendar != null && assignment.getTotalAmount().getDuration() == 0)\n {\n Duration calendarWork = calendar.getWork(assignment.getStart(), assignment.getFinish(), TimeUnit.MINUTES);\n if (calendarWork.getDuration() != 0)\n {\n result = true;\n break;\n }\n }\n }\n return result;\n }",
"public static String transformXPath(String originalXPath)\n {\n // use a list to maintain the multiple joined xqueries (if there are multiple queries joined with the \"|\" operator)\n List<StringBuilder> compiledXPaths = new ArrayList<>(1);\n\n int frameIdx = -1;\n boolean inQuote = false;\n int conditionLevel = 0;\n char startQuoteChar = 0;\n StringBuilder currentXPath = new StringBuilder();\n compiledXPaths.add(currentXPath);\n for (int i = 0; i < originalXPath.length(); i++)\n {\n char curChar = originalXPath.charAt(i);\n if (!inQuote && curChar == '[')\n {\n frameIdx++;\n conditionLevel++;\n currentXPath.append(\"[windup:startFrame(\").append(frameIdx).append(\") and windup:evaluate(\").append(frameIdx).append(\", \");\n }\n else if (!inQuote && curChar == ']')\n {\n conditionLevel--;\n currentXPath.append(\")]\");\n }\n else if (!inQuote && conditionLevel == 0 && curChar == '|')\n {\n // joining multiple xqueries\n currentXPath = new StringBuilder();\n compiledXPaths.add(currentXPath);\n }\n else\n {\n if (inQuote && curChar == startQuoteChar)\n {\n inQuote = false;\n startQuoteChar = 0;\n }\n else if (curChar == '\"' || curChar == '\\'')\n {\n inQuote = true;\n startQuoteChar = curChar;\n }\n\n if (!inQuote && originalXPath.startsWith(WINDUP_MATCHES_FUNCTION_PREFIX, i))\n {\n i += (WINDUP_MATCHES_FUNCTION_PREFIX.length() - 1);\n currentXPath.append(\"windup:matches(\").append(frameIdx).append(\", \");\n }\n else\n {\n currentXPath.append(curChar);\n }\n }\n }\n\n Pattern leadingAndTrailingWhitespace = Pattern.compile(\"(\\\\s*)(.*?)(\\\\s*)\");\n StringBuilder finalResult = new StringBuilder();\n for (StringBuilder compiledXPath : compiledXPaths)\n {\n if (StringUtils.isNotBlank(compiledXPath))\n {\n Matcher whitespaceMatcher = leadingAndTrailingWhitespace.matcher(compiledXPath);\n if (!whitespaceMatcher.matches())\n continue;\n\n compiledXPath = new StringBuilder();\n compiledXPath.append(whitespaceMatcher.group(1));\n compiledXPath.append(whitespaceMatcher.group(2));\n compiledXPath.append(\"/self::node()[windup:persist(\").append(frameIdx).append(\", \").append(\".)]\");\n compiledXPath.append(whitespaceMatcher.group(3));\n\n if (StringUtils.isNotBlank(finalResult))\n finalResult.append(\"|\");\n finalResult.append(compiledXPath);\n }\n }\n return finalResult.toString();\n }",
"private static int[] getMode3PrimaryCodewords(String postcode, int country, int service) {\r\n\r\n int[] postcodeNums = new int[postcode.length()];\r\n\r\n postcode = postcode.toUpperCase();\r\n for (int i = 0; i < postcodeNums.length; i++) {\r\n postcodeNums[i] = postcode.charAt(i);\r\n if (postcode.charAt(i) >= 'A' && postcode.charAt(i) <= 'Z') {\r\n // (Capital) letters shifted to Code Set A values\r\n postcodeNums[i] -= 64;\r\n }\r\n if (postcodeNums[i] == 27 || postcodeNums[i] == 31 || postcodeNums[i] == 33 || postcodeNums[i] >= 59) {\r\n // Not a valid postal code character, use space instead\r\n postcodeNums[i] = 32;\r\n }\r\n // Input characters lower than 27 (NUL - SUB) in postal code are interpreted as capital\r\n // letters in Code Set A (e.g. LF becomes 'J')\r\n }\r\n\r\n int[] primary = new int[10];\r\n primary[0] = ((postcodeNums[5] & 0x03) << 4) | 3;\r\n primary[1] = ((postcodeNums[4] & 0x03) << 4) | ((postcodeNums[5] & 0x3c) >> 2);\r\n primary[2] = ((postcodeNums[3] & 0x03) << 4) | ((postcodeNums[4] & 0x3c) >> 2);\r\n primary[3] = ((postcodeNums[2] & 0x03) << 4) | ((postcodeNums[3] & 0x3c) >> 2);\r\n primary[4] = ((postcodeNums[1] & 0x03) << 4) | ((postcodeNums[2] & 0x3c) >> 2);\r\n primary[5] = ((postcodeNums[0] & 0x03) << 4) | ((postcodeNums[1] & 0x3c) >> 2);\r\n primary[6] = ((postcodeNums[0] & 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 }",
"protected float transformLength(float w)\n {\n Matrix ctm = getGraphicsState().getCurrentTransformationMatrix();\n Matrix m = new Matrix();\n m.setValue(2, 0, w);\n return m.multiply(ctm).getTranslateX();\n }",
"public static <X> ServiceTypeLoader<X> load(Class<X> serviceType) {\n return load(serviceType, Thread.currentThread().getContextClassLoader());\n }",
"private void updateRoutingStrategies(Cluster cluster, List<StoreDefinition> storeDefs) {\n // acquire write lock\n writeLock.lock();\n try {\n VectorClock clock = new VectorClock();\n if(metadataCache.containsKey(ROUTING_STRATEGY_KEY))\n clock = (VectorClock) metadataCache.get(ROUTING_STRATEGY_KEY).getVersion();\n\n logger.info(\"Updating routing strategy for all stores\");\n HashMap<String, StoreDefinition> storeDefMap = makeStoreDefinitionMap(storeDefs);\n HashMap<String, RoutingStrategy> routingStrategyMap = createRoutingStrategyMap(cluster,\n storeDefMap);\n this.metadataCache.put(ROUTING_STRATEGY_KEY,\n new Versioned<Object>(routingStrategyMap,\n clock.incremented(getNodeId(),\n System.currentTimeMillis())));\n\n for(String storeName: storeNameTolisteners.keySet()) {\n RoutingStrategy updatedRoutingStrategy = routingStrategyMap.get(storeName);\n if(updatedRoutingStrategy != null) {\n try {\n for(MetadataStoreListener listener: storeNameTolisteners.get(storeName)) {\n listener.updateRoutingStrategy(updatedRoutingStrategy);\n listener.updateStoreDefinition(storeDefMap.get(storeName));\n }\n } catch(Exception e) {\n if(logger.isEnabledFor(Level.WARN))\n logger.warn(e, e);\n }\n }\n\n }\n } finally {\n writeLock.unlock();\n }\n }",
"public static String encodePathSegment(String segment, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(segment, encoding, HierarchicalUriComponents.Type.PATH_SEGMENT);\n\t}",
"public static String next(CharSequence self) {\n StringBuilder buffer = new StringBuilder(self);\n if (buffer.length() == 0) {\n buffer.append(Character.MIN_VALUE);\n } else {\n char last = buffer.charAt(buffer.length() - 1);\n if (last == Character.MAX_VALUE) {\n buffer.append(Character.MIN_VALUE);\n } else {\n char next = last;\n next++;\n buffer.setCharAt(buffer.length() - 1, next);\n }\n }\n return buffer.toString();\n }"
] |
Return the area polygon as the only feature in the feature collection.
@param mapAttributes the attributes that this aoi is part of. | [
"public SimpleFeatureCollection areaToFeatureCollection(\n @Nonnull final MapAttribute.MapAttributeValues mapAttributes) {\n Assert.isTrue(mapAttributes.areaOfInterest == this,\n \"map attributes passed in does not contain this area of interest object\");\n\n final SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();\n typeBuilder.setName(\"aoi\");\n CoordinateReferenceSystem crs = mapAttributes.getMapBounds().getProjection();\n typeBuilder.add(\"geom\", this.polygon.getClass(), crs);\n final SimpleFeature feature =\n SimpleFeatureBuilder.build(typeBuilder.buildFeatureType(), new Object[]{this.polygon}, \"aoi\");\n final DefaultFeatureCollection features = new DefaultFeatureCollection();\n features.add(feature);\n return features;\n }"
] | [
"public static void showOnlyChannels(Object... channels){\r\n for(LogRecordHandler handler : handlers){\r\n if(handler instanceof VisibilityHandler){\r\n VisibilityHandler visHandler = (VisibilityHandler) handler;\r\n visHandler.hideAll();\r\n for (Object channel : channels) {\r\n visHandler.alsoShow(channel);\r\n }\r\n }\r\n }\r\n }",
"public void ojbAdd(Object anObject)\r\n {\r\n DSetEntry entry = prepareEntry(anObject);\r\n entry.setPosition(elements.size());\r\n elements.add(entry);\r\n }",
"public static <T> AddQuery<T> start(T query, long correlationId) {\n return start(query, correlationId, \"default\", null);\n }",
"public Collection<Contact> getPublicList(String userId) throws FlickrException {\r\n List<Contact> contacts = new ArrayList<Contact>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PUBLIC_LIST);\r\n parameters.put(\"user_id\", userId);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element contactsElement = response.getPayload();\r\n NodeList contactNodes = contactsElement.getElementsByTagName(\"contact\");\r\n for (int i = 0; i < contactNodes.getLength(); i++) {\r\n Element contactElement = (Element) contactNodes.item(i);\r\n Contact contact = new Contact();\r\n contact.setId(contactElement.getAttribute(\"nsid\"));\r\n contact.setUsername(contactElement.getAttribute(\"username\"));\r\n contact.setIgnored(\"1\".equals(contactElement.getAttribute(\"ignored\")));\r\n contact.setOnline(OnlineStatus.fromType(contactElement.getAttribute(\"online\")));\r\n contact.setIconFarm(contactElement.getAttribute(\"iconfarm\"));\r\n contact.setIconServer(contactElement.getAttribute(\"iconserver\"));\r\n if (contact.getOnline() == OnlineStatus.AWAY) {\r\n contactElement.normalize();\r\n contact.setAwayMessage(XMLUtilities.getValue(contactElement));\r\n }\r\n contacts.add(contact);\r\n }\r\n return contacts;\r\n }",
"public static ConstraintType getInstance(Locale locale, String type)\n {\n int index = 0;\n\n String[] constraintTypes = LocaleData.getStringArray(locale, LocaleData.CONSTRAINT_TYPES);\n for (int loop = 0; loop < constraintTypes.length; loop++)\n {\n if (constraintTypes[loop].equalsIgnoreCase(type) == true)\n {\n index = loop;\n break;\n }\n }\n\n return (ConstraintType.getInstance(index));\n }",
"private PreparedStatement prepareBatchStatement(String sql)\r\n {\r\n String sqlCmd = sql.substring(0, 7);\r\n\r\n if (sqlCmd.equals(\"UPDATE \") || sqlCmd.equals(\"DELETE \") || (_useBatchInserts && sqlCmd.equals(\"INSERT \")))\r\n {\r\n PreparedStatement stmt = (PreparedStatement) _statements.get(sql);\r\n if (stmt == null)\r\n {\r\n // [olegnitz] for JDK 1.2 we need to list both PreparedStatement and Statement\r\n // interfaces, otherwise proxy.jar works incorrectly\r\n stmt = (PreparedStatement) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{\r\n PreparedStatement.class, Statement.class, BatchPreparedStatement.class},\r\n new PreparedStatementInvocationHandler(this, sql, m_jcd));\r\n _statements.put(sql, stmt);\r\n }\r\n return stmt;\r\n }\r\n else\r\n {\r\n return null;\r\n }\r\n }",
"private int getLiteralId(String literal) throws PersistenceBrokerException\r\n {\r\n ////logger.debug(\"lookup: \" + literal);\r\n try\r\n {\r\n return tags.getIdByTag(literal);\r\n }\r\n catch (NullPointerException t)\r\n {\r\n throw new MetadataException(\"unknown literal: '\" + literal + \"'\",t);\r\n }\r\n\r\n }",
"private boolean isEqual(FieldDescriptorDef first, FieldDescriptorDef second)\r\n {\r\n return first.getName().equals(second.getName()) &&\r\n first.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN).equals(second.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN)) &&\r\n first.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE).equals(second.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));\r\n }",
"public static MBeanServerConnection getMBeanServerConnection(Process p, boolean startAgent) {\n try {\n final JMXServiceURL serviceURL = getLocalConnectorAddress(p, startAgent);\n final JMXConnector connector = JMXConnectorFactory.connect(serviceURL);\n final MBeanServerConnection mbsc = connector.getMBeanServerConnection();\n return mbsc;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }"
] |
Start the first inner table of a class. | [
"private void firstInnerTableStart(Options opt) {\n\tw.print(linePrefix + linePrefix + \"<tr>\" + opt.shape.extraColumn() +\n\t\t\"<td><table border=\\\"0\\\" cellspacing=\\\"0\\\" \" +\n\t\t\"cellpadding=\\\"1\\\">\" + linePostfix);\n }"
] | [
"public Where<T, ID> reset() {\n\t\tfor (int i = 0; i < clauseStackLevel; i++) {\n\t\t\t// help with gc\n\t\t\tclauseStack[i] = null;\n\t\t}\n\t\tclauseStackLevel = 0;\n\t\treturn this;\n\t}",
"@SuppressWarnings(\"unchecked\")\r\n public static boolean addPropertyDefault(PropertiesImpl props, PropertyDefinition<?> propDef) {\r\n\r\n if ((props == null) || (props.getProperties() == null)) {\r\n throw new IllegalArgumentException(\"Props must not be null!\");\r\n }\r\n\r\n if (propDef == null) {\r\n return false;\r\n }\r\n\r\n List<?> defaultValue = propDef.getDefaultValue();\r\n if ((defaultValue != null) && (!defaultValue.isEmpty())) {\r\n switch (propDef.getPropertyType()) {\r\n case BOOLEAN:\r\n props.addProperty(new PropertyBooleanImpl(propDef.getId(), (List<Boolean>)defaultValue));\r\n break;\r\n case DATETIME:\r\n props.addProperty(new PropertyDateTimeImpl(propDef.getId(), (List<GregorianCalendar>)defaultValue));\r\n break;\r\n case DECIMAL:\r\n props.addProperty(new PropertyDecimalImpl(propDef.getId(), (List<BigDecimal>)defaultValue));\r\n break;\r\n case HTML:\r\n props.addProperty(new PropertyHtmlImpl(propDef.getId(), (List<String>)defaultValue));\r\n break;\r\n case ID:\r\n props.addProperty(new PropertyIdImpl(propDef.getId(), (List<String>)defaultValue));\r\n break;\r\n case INTEGER:\r\n props.addProperty(new PropertyIntegerImpl(propDef.getId(), (List<BigInteger>)defaultValue));\r\n break;\r\n case STRING:\r\n props.addProperty(new PropertyStringImpl(propDef.getId(), (List<String>)defaultValue));\r\n break;\r\n case URI:\r\n props.addProperty(new PropertyUriImpl(propDef.getId(), (List<String>)defaultValue));\r\n break;\r\n default:\r\n throw new RuntimeException(\"Unknown datatype! Spec change?\");\r\n }\r\n\r\n return true;\r\n }\r\n\r\n return false;\r\n }",
"protected B fields(List<F> fields) {\n if (instance.def.fields == null) {\n instance.def.fields = new ArrayList<F>(fields.size());\n }\n instance.def.fields.addAll(fields);\n return returnThis();\n }",
"public static String get(String language) {\n language = language.toLowerCase();\n if(\"ecmascript\".equals(language)) {\n language = \"javascript\";\n }\n\n String extension = extensions.get(language);\n if(extension == null) {\n return null;\n\n } else {\n return loadScriptEnv(language, extension);\n\n }\n }",
"public static int cudnnConvolutionBackwardBias(\n cudnnHandle handle, \n Pointer alpha, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n Pointer beta, \n cudnnTensorDescriptor dbDesc, \n Pointer db)\n {\n return checkResult(cudnnConvolutionBackwardBiasNative(handle, alpha, dyDesc, dy, beta, dbDesc, db));\n }",
"public ParallelTaskBuilder prepareHttpPost(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.getHttpMeta().setHttpMethod(HttpMethod.POST);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\n }",
"final void roll(final long timeForSuffix) {\n\n final File backupFile = this.prepareBackupFile(timeForSuffix);\n\n // close filename\n this.getAppender().closeFile();\n\n // rename filename on disk to filename+suffix(+number)\n this.doFileRoll(this.getAppender().getIoFile(), backupFile);\n\n // setup new file 'filename'\n this.getAppender().openFile();\n\n this.fireFileRollEvent(new FileRollEvent(this, backupFile));\n }",
"public ProjectCalendarWeek getWorkWeek(Date date)\n {\n ProjectCalendarWeek week = null;\n if (!m_workWeeks.isEmpty())\n {\n sortWorkWeeks();\n\n int low = 0;\n int high = m_workWeeks.size() - 1;\n long targetDate = date.getTime();\n\n while (low <= high)\n {\n int mid = (low + high) >>> 1;\n ProjectCalendarWeek midVal = m_workWeeks.get(mid);\n int cmp = 0 - DateHelper.compare(midVal.getDateRange().getStart(), midVal.getDateRange().getEnd(), targetDate);\n\n if (cmp < 0)\n {\n low = mid + 1;\n }\n else\n {\n if (cmp > 0)\n {\n high = mid - 1;\n }\n else\n {\n week = midVal;\n break;\n }\n }\n }\n }\n\n if (week == null && getParent() != null)\n {\n // Check base calendar as well for a work week.\n week = getParent().getWorkWeek(date);\n }\n return (week);\n }",
"public static base_responses unset(nitro_service client, String acl6name[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (acl6name != null && acl6name.length > 0) {\n\t\t\tnsacl6 unsetresources[] = new nsacl6[acl6name.length];\n\t\t\tfor (int i=0;i<acl6name.length;i++){\n\t\t\t\tunsetresources[i] = new nsacl6();\n\t\t\t\tunsetresources[i].acl6name = acl6name[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}"
] |
Set the model used by the left table.
@param model table model | [
"public void setLeftTableModel(TableModel model)\n {\n TableModel old = m_leftTable.getModel();\n m_leftTable.setModel(model);\n firePropertyChange(\"leftTableModel\", old, model);\n }"
] | [
"public static HashMap<String, JSONObject> flatRessources(JSONObject object) throws JSONException {\n HashMap<String, JSONObject> result = new HashMap<String, JSONObject>();\n\n // no cycle in hierarchies!!\n if (object.has(\"resourceId\") && object.has(\"childShapes\")) {\n result.put(object.getString(\"resourceId\"),\n object);\n JSONArray childShapes = object.getJSONArray(\"childShapes\");\n for (int i = 0; i < childShapes.length(); i++) {\n result.putAll(flatRessources(childShapes.getJSONObject(i)));\n }\n }\n ;\n\n return result;\n }",
"public static void checkXerbla() {\n double[] x = new double[9];\n System.out.println(\"Check whether we're catching XERBLA errors. If you see something like \\\"** On entry to DGEMM parameter number 4 had an illegal value\\\", it didn't work!\");\n try {\n NativeBlas.dgemm('N', 'N', 3, -1, 3, 1.0, x, 0, 3, x, 0, 3, 0.0, x, 0, 3);\n } catch (IllegalArgumentException e) {\n check(\"checking XERBLA\", e.getMessage().contains(\"XERBLA\"));\n return;\n }\n assert (false); // shouldn't happen\n }",
"protected SingleBusLocatorRegistrar getRegistrar(Bus bus) {\n SingleBusLocatorRegistrar registrar = busRegistrars.get(bus);\n if (registrar == null) {\n check(locatorClient, \"serviceLocator\", \"registerService\");\n registrar = new SingleBusLocatorRegistrar(bus);\n registrar.setServiceLocator(locatorClient);\n registrar.setEndpointPrefix(endpointPrefix);\n Map<String, String> endpointPrefixes = new HashMap<String, String>();\n endpointPrefixes.put(\"HTTP\", endpointPrefixHttp);\n endpointPrefixes.put(\"HTTPS\", endpointPrefixHttps);\n registrar.setEndpointPrefixes(endpointPrefixes);\n busRegistrars.put(bus, registrar);\n addLifeCycleListener(bus);\n }\n return registrar;\n }",
"public void validate() throws PackagingException {\n if (control == null || !control.isDirectory()) {\n throw new PackagingException(\"The 'control' attribute doesn't point to a directory. \" + control);\n }\n\n if (changesIn != null) {\n\n if (changesIn.exists() && (!changesIn.isFile() || !changesIn.canRead())) {\n throw new PackagingException(\"The 'changesIn' setting needs to point to a readable file. \" + changesIn + \" was not found/readable.\");\n }\n\n if (changesOut != null && !isWritableFile(changesOut)) {\n throw new PackagingException(\"Cannot write the output for 'changesOut' to \" + changesOut);\n }\n\n if (changesSave != null && !isWritableFile(changesSave)) {\n throw new PackagingException(\"Cannot write the output for 'changesSave' to \" + changesSave);\n }\n\n } else {\n if (changesOut != null || changesSave != null) {\n throw new PackagingException(\"The 'changesOut' or 'changesSave' settings may only be used when there is a 'changesIn' specified.\");\n }\n }\n\n if (Compression.toEnum(compression) == null) {\n throw new PackagingException(\"The compression method '\" + compression + \"' is not supported (expected 'none', 'gzip', 'bzip2' or 'xz')\");\n }\n\n if (deb == null) {\n throw new PackagingException(\"You need to specify where the deb file is supposed to be created.\");\n }\n\n getDigestCode(digest);\n }",
"@SuppressWarnings(\"unchecked\")\n public static <T> Serializer<T> unsafeGetSerializer(SerializerFactory serializerFactory,\n SerializerDefinition serializerDefinition) {\n return (Serializer<T>) serializerFactory.getSerializer(serializerDefinition);\n }",
"public Set<D> getMatchedDeclaration() {\n Set<D> bindedSet = new HashSet<D>();\n for (Map.Entry<ServiceReference<D>, Boolean> e : declarations.entrySet()) {\n if (e.getValue()) {\n bindedSet.add(getDeclaration(e.getKey()));\n }\n }\n return bindedSet;\n }",
"public Note add(String photoId, Note note) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ADD);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n Rectangle bounds = note.getBounds();\r\n if (bounds != null) {\r\n parameters.put(\"note_x\", String.valueOf(bounds.x));\r\n parameters.put(\"note_y\", String.valueOf(bounds.y));\r\n parameters.put(\"note_w\", String.valueOf(bounds.width));\r\n parameters.put(\"note_h\", String.valueOf(bounds.height));\r\n }\r\n String text = note.getText();\r\n if (text != null) {\r\n parameters.put(\"note_text\", text);\r\n }\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element noteElement = response.getPayload();\r\n note.setId(noteElement.getAttribute(\"id\"));\r\n return note;\r\n }",
"public Date getFinishDate()\n {\n Date result = (Date) getCachedValue(ProjectField.FINISH_DATE);\n if (result == null)\n {\n result = getParentFile().getFinishDate();\n }\n return (result);\n }",
"private void processGraphicalIndicators()\n {\n GraphicalIndicatorReader graphicalIndicatorReader = new GraphicalIndicatorReader();\n graphicalIndicatorReader.process(m_file.getCustomFields(), m_file.getProjectProperties(), m_projectProps);\n }"
] |
Run a task once, after a delay.
@param task
Task to run.
@param delay
Unit is seconds.
@return An interface that lets you query the status; cancel; or
reschedule the event. | [
"public PeriodicEvent runAfter(Runnable task, float delay) {\n validateDelay(delay);\n return new Event(task, delay);\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 CmsScheduledJobInfo getJob(String id) {\n\n Iterator<CmsScheduledJobInfo> it = m_jobs.iterator();\n while (it.hasNext()) {\n CmsScheduledJobInfo job = it.next();\n if (job.getId().equals(id)) {\n return job;\n }\n }\n // not found\n return null;\n }",
"public static Method[] getUniqueDeclaredMethods(Class<?> leafClass) throws IllegalArgumentException {\n final List<Method> methods = new ArrayList<Method>(32);\n doWithMethods(leafClass, new MethodCallback() {\n @Override\n public void doWith(Method method) {\n boolean knownSignature = false;\n Method methodBeingOverriddenWithCovariantReturnType = null;\n for (Method existingMethod : methods) {\n if (method.getName().equals(existingMethod.getName()) &&\n Arrays.equals(method.getParameterTypes(), existingMethod.getParameterTypes())) {\n // Is this a covariant return type situation?\n if (existingMethod.getReturnType() != method.getReturnType() &&\n existingMethod.getReturnType().isAssignableFrom(method.getReturnType())) {\n methodBeingOverriddenWithCovariantReturnType = existingMethod;\n } else {\n knownSignature = true;\n }\n break;\n }\n }\n if (methodBeingOverriddenWithCovariantReturnType != null) {\n methods.remove(methodBeingOverriddenWithCovariantReturnType);\n }\n if (!knownSignature) {\n methods.add(method);\n }\n }\n });\n return methods.toArray(new Method[methods.size()]);\n }",
"public VALUE put(KEY key, VALUE object) {\n CacheEntry<VALUE> entry;\n if (referenceType == ReferenceType.WEAK) {\n entry = new CacheEntry<>(new WeakReference<>(object), null);\n } else if (referenceType == ReferenceType.SOFT) {\n entry = new CacheEntry<>(new SoftReference<>(object), null);\n } else {\n entry = new CacheEntry<>(null, object);\n }\n\n countPutCountSinceEviction++;\n countPut++;\n if (isExpiring && nextCleanUpTimestamp == 0) {\n nextCleanUpTimestamp = System.currentTimeMillis() + expirationMillis + 1;\n }\n\n CacheEntry<VALUE> oldEntry;\n synchronized (this) {\n if (values.size() >= maxSize) {\n evictToTargetSize(maxSize - 1);\n }\n oldEntry = values.put(key, entry);\n }\n return getValueForRemoved(oldEntry);\n }",
"public void setContentType(String photoId, String contentType) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SET_CONTENTTYPE);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"content_type\", contentType);\r\n\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"public boolean isMaskCompatibleWithRange(int maskValue, Integer segmentPrefixLength) throws PrefixLenException {\r\n\t\tif(!isMultiple()) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\treturn super.isMaskCompatibleWithRange(maskValue, segmentPrefixLength, getNetwork().getPrefixConfiguration().allPrefixedAddressesAreSubnets());\r\n\t}",
"public static appfwprofile_safeobject_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_safeobject_binding obj = new appfwprofile_safeobject_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_safeobject_binding response[] = (appfwprofile_safeobject_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static final String getSelectedValue(ListBox list) {\n\tint index = list.getSelectedIndex();\n\treturn (index >= 0) ? list.getValue(index) : null;\n }",
"public List<Dependency> getModuleAncestors(final String moduleName, final String moduleVersion) throws GrapesCommunicationException {\n final Client client = getClient();\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactAncestors(moduleName, moduleVersion));\n final ClientResponse response = resource.queryParam(ServerAPI.SCOPE_COMPILE_PARAM, \"true\")\n .queryParam(ServerAPI.SCOPE_PROVIDED_PARAM, \"true\")\n .queryParam(ServerAPI.SCOPE_RUNTIME_PARAM, \"true\")\n .queryParam(ServerAPI.SCOPE_TEST_PARAM, \"true\")\n .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = String.format(FAILED_TO_GET_MODULE, \"get module ancestors\", moduleName, moduleVersion);\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n\n return response.getEntity(new GenericType<List<Dependency>>(){});\n }"
] |
Use this API to Import application. | [
"public static base_response Import(nitro_service client, application resource) throws Exception {\n\t\tapplication Importresource = new application();\n\t\tImportresource.apptemplatefilename = resource.apptemplatefilename;\n\t\tImportresource.appname = resource.appname;\n\t\tImportresource.deploymentfilename = resource.deploymentfilename;\n\t\treturn Importresource.perform_operation(client,\"Import\");\n\t}"
] | [
"private void addFoldersToSearchIn(final List<String> folders) {\n\n if (null == folders) {\n return;\n }\n\n for (String folder : folders) {\n if (!CmsResource.isFolder(folder)) {\n folder += \"/\";\n }\n\n m_foldersToSearchIn.add(folder);\n }\n }",
"public static String readStringFromUrlGeneric(String url)\n throws IOException {\n InputStream is = null;\n URL urlObj = null;\n String responseString = PcConstants.NA;\n try {\n urlObj = new URL(url);\n URLConnection con = urlObj.openConnection();\n\n con.setConnectTimeout(ParallecGlobalConfig.urlConnectionConnectTimeoutMillis);\n con.setReadTimeout(ParallecGlobalConfig.urlConnectionReadTimeoutMillis);\n is = con.getInputStream();\n\n BufferedReader rd = new BufferedReader(new InputStreamReader(is,\n Charset.forName(\"UTF-8\")));\n responseString = PcFileNetworkIoUtils.readAll(rd);\n\n } finally {\n\n if (is != null) {\n is.close();\n }\n\n }\n\n return responseString;\n }",
"protected void append(Object object, String indentation, int index) {\n\t\tif (indentation.length() == 0) {\n\t\t\tappend(object, index);\n\t\t\treturn;\n\t\t}\n\t\tif (object == null)\n\t\t\treturn;\n\t\tif (object instanceof String) {\n\t\t\tappend(indentation, (String)object, index);\n\t\t} else if (object instanceof StringConcatenation) {\n\t\t\tStringConcatenation other = (StringConcatenation) object;\n\t\t\tList<String> otherSegments = other.getSignificantContent();\n\t\t\tappendSegments(indentation, index, otherSegments, other.lineDelimiter);\n\t\t} else if (object instanceof StringConcatenationClient) {\n\t\t\tStringConcatenationClient other = (StringConcatenationClient) object;\n\t\t\tother.appendTo(new IndentedTarget(this, indentation, index));\n\t\t} else {\n\t\t\tfinal String text = getStringRepresentation(object);\n\t\t\tif (text != null) {\n\t\t\t\tappend(indentation, text, index);\n\t\t\t}\n\t\t}\n\t}",
"@RequestMapping(value = \"api/edit/repeatNumber\", method = RequestMethod.POST)\n public\n @ResponseBody\n String updateRepeatNumber(Model model, int newNum, int path_id,\n @RequestParam(defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) throws Exception {\n logger.info(\"want to update repeat number of path_id={}, to newNum={}\", path_id, newNum);\n editService.updateRepeatNumber(newNum, path_id, clientUUID);\n return null;\n }",
"static int[] toIntArray(List<Integer> integers) {\n\t\tint[] ints = new int[integers.size()];\n\t\tint i = 0;\n\t\tfor (Integer n : integers) {\n\t\t\tints[i++] = n;\n\t\t}\n\t\treturn ints;\n\t}",
"public static CharSequence formatDuration(Context context, ReadableDuration readableDuration) {\n Resources res = context.getResources();\n Duration duration = readableDuration.toDuration();\n\n final int hours = (int) duration.getStandardHours();\n if (hours != 0) {\n return res.getQuantityString(R.plurals.joda_time_android_duration_hours, hours, hours);\n }\n\n final int minutes = (int) duration.getStandardMinutes();\n if (minutes != 0) {\n return res.getQuantityString(R.plurals.joda_time_android_duration_minutes, minutes, minutes);\n }\n\n final int seconds = (int) duration.getStandardSeconds();\n return res.getQuantityString(R.plurals.joda_time_android_duration_seconds, seconds, seconds);\n }",
"@Override\n @SuppressFBWarnings(value = \"UL_UNRELEASED_LOCK\", justification = \"False positive from FindBugs\")\n public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {\n if (!isActive()) {\n throw new ContextNotActiveException();\n }\n checkContextInitialized();\n final BeanStore beanStore = getBeanStore();\n if (beanStore == null) {\n return null;\n }\n if (contextual == null) {\n throw ContextLogger.LOG.contextualIsNull();\n }\n BeanIdentifier id = getId(contextual);\n ContextualInstance<T> beanInstance = beanStore.get(id);\n if (beanInstance != null) {\n return beanInstance.getInstance();\n } else if (creationalContext != null) {\n LockedBean lock = null;\n try {\n if (multithreaded) {\n lock = beanStore.lock(id);\n beanInstance = beanStore.get(id);\n if (beanInstance != null) {\n return beanInstance.getInstance();\n }\n }\n T instance = contextual.create(creationalContext);\n if (instance != null) {\n beanInstance = new SerializableContextualInstanceImpl<Contextual<T>, T>(contextual, instance, creationalContext, serviceRegistry.get(ContextualStore.class));\n beanStore.put(id, beanInstance);\n }\n return instance;\n } finally {\n if (lock != null) {\n lock.unlock();\n }\n }\n } else {\n return null;\n }\n }",
"public void validate() throws PackagingException {\n if (control == null || !control.isDirectory()) {\n throw new PackagingException(\"The 'control' attribute doesn't point to a directory. \" + control);\n }\n\n if (changesIn != null) {\n\n if (changesIn.exists() && (!changesIn.isFile() || !changesIn.canRead())) {\n throw new PackagingException(\"The 'changesIn' setting needs to point to a readable file. \" + changesIn + \" was not found/readable.\");\n }\n\n if (changesOut != null && !isWritableFile(changesOut)) {\n throw new PackagingException(\"Cannot write the output for 'changesOut' to \" + changesOut);\n }\n\n if (changesSave != null && !isWritableFile(changesSave)) {\n throw new PackagingException(\"Cannot write the output for 'changesSave' to \" + changesSave);\n }\n\n } else {\n if (changesOut != null || changesSave != null) {\n throw new PackagingException(\"The 'changesOut' or 'changesSave' settings may only be used when there is a 'changesIn' specified.\");\n }\n }\n\n if (Compression.toEnum(compression) == null) {\n throw new PackagingException(\"The compression method '\" + compression + \"' is not supported (expected 'none', 'gzip', 'bzip2' or 'xz')\");\n }\n\n if (deb == null) {\n throw new PackagingException(\"You need to specify where the deb file is supposed to be created.\");\n }\n\n getDigestCode(digest);\n }",
"private int getColorWaveformBits(final ByteBuffer waveBytes, final int segment) {\n final int base = (segment * 2);\n final int big = Util.unsign(waveBytes.get(base));\n final int small = Util.unsign(waveBytes.get(base + 1));\n return big * 256 + small;\n }"
] |
Get the first non-white X point
@param img Image n memory
@return the x start | [
"private static int getTrimmedXStart(BufferedImage img) {\n int height = img.getHeight();\n int width = img.getWidth();\n int xStart = width;\n\n for (int i = 0; i < height; i++) {\n for (int j = 0; j < width; j++) {\n if (img.getRGB(j, i) != Color.WHITE.getRGB() && j < xStart) {\n xStart = j;\n break;\n }\n }\n }\n\n return xStart;\n }"
] | [
"protected I_CmsFacetQueryItem parseFacetQueryItem(JSONObject item) {\n\n String query;\n try {\n query = item.getString(JSON_KEY_QUERY_FACET_QUERY_QUERY);\n } catch (JSONException e) {\n // TODO: Log\n return null;\n }\n String label = parseOptionalStringValue(item, JSON_KEY_QUERY_FACET_QUERY_LABEL);\n return new CmsFacetQueryItem(query, label);\n }",
"@Override\n protected void onGraphDraw(Canvas _Canvas) {\n super.onGraphDraw(_Canvas);\n _Canvas.translate(-mCurrentViewport.left, -mCurrentViewport.top);\n drawBars(_Canvas);\n }",
"public static VectorTile.Tile.GeomType toGeomType(Geometry geometry) {\n VectorTile.Tile.GeomType result = VectorTile.Tile.GeomType.UNKNOWN;\n\n if(geometry instanceof Point\n || geometry instanceof MultiPoint) {\n result = VectorTile.Tile.GeomType.POINT;\n\n } else if(geometry instanceof LineString\n || geometry instanceof MultiLineString) {\n result = VectorTile.Tile.GeomType.LINESTRING;\n\n } else if(geometry instanceof Polygon\n || geometry instanceof MultiPolygon) {\n result = VectorTile.Tile.GeomType.POLYGON;\n }\n\n return result;\n }",
"public static final BigInteger printEarnedValueMethod(EarnedValueMethod value)\n {\n return (value == null ? BigInteger.valueOf(EarnedValueMethod.PERCENT_COMPLETE.getValue()) : BigInteger.valueOf(value.getValue()));\n }",
"private void installFastProcessAnnotatedTypeResolver(ServiceRegistry services) {\n ClassFileServices classFileServices = services.get(ClassFileServices.class);\n if (classFileServices != null) {\n final GlobalObserverNotifierService observers = services.get(GlobalObserverNotifierService.class);\n try {\n final FastProcessAnnotatedTypeResolver resolver = new FastProcessAnnotatedTypeResolver(observers.getAllObserverMethods());\n services.add(FastProcessAnnotatedTypeResolver.class, resolver);\n } catch (UnsupportedObserverMethodException e) {\n BootstrapLogger.LOG.notUsingFastResolver(e.getObserver());\n return;\n }\n }\n }",
"public T withAlias(String text, String languageCode) {\n\t\twithAlias(factory.getMonolingualTextValue(text, languageCode));\n\t\treturn getThis();\n\t}",
"private int[] readTypeAnnotations(final MethodVisitor mv,\n final Context context, int u, boolean visible) {\n char[] c = context.buffer;\n int[] offsets = new int[readUnsignedShort(u)];\n u += 2;\n for (int i = 0; i < offsets.length; ++i) {\n offsets[i] = u;\n int target = readInt(u);\n switch (target >>> 24) {\n case 0x00: // CLASS_TYPE_PARAMETER\n case 0x01: // METHOD_TYPE_PARAMETER\n case 0x16: // METHOD_FORMAL_PARAMETER\n u += 2;\n break;\n case 0x13: // FIELD\n case 0x14: // METHOD_RETURN\n case 0x15: // METHOD_RECEIVER\n u += 1;\n break;\n case 0x40: // LOCAL_VARIABLE\n case 0x41: // RESOURCE_VARIABLE\n for (int j = readUnsignedShort(u + 1); j > 0; --j) {\n int start = readUnsignedShort(u + 3);\n int length = readUnsignedShort(u + 5);\n createLabel(start, context.labels);\n createLabel(start + length, context.labels);\n u += 6;\n }\n u += 3;\n break;\n case 0x47: // CAST\n case 0x48: // CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT\n case 0x49: // METHOD_INVOCATION_TYPE_ARGUMENT\n case 0x4A: // CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT\n case 0x4B: // METHOD_REFERENCE_TYPE_ARGUMENT\n u += 4;\n break;\n // case 0x10: // CLASS_EXTENDS\n // case 0x11: // CLASS_TYPE_PARAMETER_BOUND\n // case 0x12: // METHOD_TYPE_PARAMETER_BOUND\n // case 0x17: // THROWS\n // case 0x42: // EXCEPTION_PARAMETER\n // case 0x43: // INSTANCEOF\n // case 0x44: // NEW\n // case 0x45: // CONSTRUCTOR_REFERENCE\n // case 0x46: // METHOD_REFERENCE\n default:\n u += 3;\n break;\n }\n int pathLength = readByte(u);\n if ((target >>> 24) == 0x42) {\n TypePath path = pathLength == 0 ? null : new TypePath(b, u);\n u += 1 + 2 * pathLength;\n u = readAnnotationValues(u + 2, c, true,\n mv.visitTryCatchAnnotation(target, path,\n readUTF8(u, c), visible));\n } else {\n u = readAnnotationValues(u + 3 + 2 * pathLength, c, true, null);\n }\n }\n return offsets;\n }",
"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 }",
"@Override\n public int getShadowSize() {\n\tElement shadowElement = shadow.getElement();\n\tshadowElement.setScrollTop(10000);\n\treturn shadowElement.getScrollTop();\n }"
] |
Get a list of referring domains for a photoset.
@param date
(Required) Stats will be returned for this date. A day according to Flickr Stats starts at midnight GMT for all users, and timestamps will
automatically be rounded down to the start of the day.
@param photosetId
(Optional) The id of the photoset to get stats for. If not provided, stats for all photos will be returned.
@param perPage
(Optional) Number of domains to return per page. If this argument is omitted, it defaults to 25. The maximum allowed value is 100.
@param page
(Optional) The page of results to return. If this argument is omitted, it defaults to 1.
@see "http://www.flickr.com/services/api/flickr.stats.getPhotosetDomains.html" | [
"public DomainList getPhotosetDomains(Date date, String photosetId, int perPage, int page) throws FlickrException {\n return getDomains(METHOD_GET_PHOTOSET_DOMAINS, \"photoset_id\", photosetId, date, perPage, page);\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}",
"public String getLinkColor(JSONObject jsonObject){\n if(jsonObject == null) return null;\n try {\n return jsonObject.has(\"color\") ? jsonObject.getString(\"color\") : \"\";\n } catch (JSONException e) {\n Logger.v(\"Unable to get Link Text Color with JSON - \"+e.getLocalizedMessage());\n return null;\n }\n }",
"private void processOutlineCodeValues() throws IOException\n {\n DirectoryEntry outlineCodeDir = (DirectoryEntry) m_projectDir.getEntry(\"TBkndOutlCode\");\n FixedMeta fm = new FixedMeta(new DocumentInputStream(((DocumentEntry) outlineCodeDir.getEntry(\"FixedMeta\"))), 10);\n FixedData fd = new FixedData(fm, new DocumentInputStream(((DocumentEntry) outlineCodeDir.getEntry(\"FixedData\"))));\n\n Map<Integer, FieldType> map = new HashMap<Integer, FieldType>();\n\n int items = fm.getItemCount();\n for (int loop = 0; loop < items; loop++)\n {\n byte[] data = fd.getByteArrayValue(loop);\n if (data.length < 18)\n {\n continue;\n }\n\n int index = MPPUtility.getShort(data, 0);\n int fieldID = MPPUtility.getInt(data, 12);\n FieldType fieldType = FieldTypeHelper.getInstance(fieldID);\n if (fieldType.getFieldTypeClass() != FieldTypeClass.UNKNOWN)\n {\n map.put(Integer.valueOf(index), fieldType);\n }\n }\n\n VarMeta outlineCodeVarMeta = new VarMeta9(new DocumentInputStream(((DocumentEntry) outlineCodeDir.getEntry(\"VarMeta\"))));\n Var2Data outlineCodeVarData = new Var2Data(outlineCodeVarMeta, new DocumentInputStream(((DocumentEntry) outlineCodeDir.getEntry(\"Var2Data\"))));\n\n Map<FieldType, List<Pair<String, String>>> valueMap = new HashMap<FieldType, List<Pair<String, String>>>();\n\n for (Integer id : outlineCodeVarMeta.getUniqueIdentifierArray())\n {\n FieldType fieldType = map.get(id);\n String value = outlineCodeVarData.getUnicodeString(id, VALUE);\n String description = outlineCodeVarData.getUnicodeString(id, DESCRIPTION);\n\n List<Pair<String, String>> list = valueMap.get(fieldType);\n if (list == null)\n {\n list = new ArrayList<Pair<String, String>>();\n valueMap.put(fieldType, list);\n }\n list.add(new Pair<String, String>(value, description));\n }\n\n for (Entry<FieldType, List<Pair<String, String>>> entry : valueMap.entrySet())\n {\n populateContainer(entry.getKey(), entry.getValue());\n }\n }",
"synchronized ArrayList<CTMessageDAO> getMessages(String userId){\n final String tName = Table.INBOX_MESSAGES.getName();\n Cursor cursor;\n ArrayList<CTMessageDAO> messageDAOArrayList = new ArrayList<>();\n try{\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n cursor= db.rawQuery(\"SELECT * FROM \"+tName+\" WHERE \" + USER_ID + \" = ? ORDER BY \" + KEY_CREATED_AT+ \" DESC\", new String[]{userId});\n if(cursor != null) {\n while(cursor.moveToNext()){\n CTMessageDAO ctMessageDAO = new CTMessageDAO();\n ctMessageDAO.setId(cursor.getString(cursor.getColumnIndex(_ID)));\n ctMessageDAO.setJsonData(new JSONObject(cursor.getString(cursor.getColumnIndex(KEY_DATA))));\n ctMessageDAO.setWzrkParams(new JSONObject(cursor.getString(cursor.getColumnIndex(WZRKPARAMS))));\n ctMessageDAO.setDate(cursor.getLong(cursor.getColumnIndex(KEY_CREATED_AT)));\n ctMessageDAO.setExpires(cursor.getLong(cursor.getColumnIndex(EXPIRES)));\n ctMessageDAO.setRead(cursor.getInt(cursor.getColumnIndex(IS_READ)));\n ctMessageDAO.setUserId(cursor.getString(cursor.getColumnIndex(USER_ID)));\n ctMessageDAO.setTags(cursor.getString(cursor.getColumnIndex(TAGS)));\n ctMessageDAO.setCampaignId(cursor.getString(cursor.getColumnIndex(CAMPAIGN)));\n messageDAOArrayList.add(ctMessageDAO);\n }\n cursor.close();\n }\n return messageDAOArrayList;\n }catch (final SQLiteException e){\n getConfigLogger().verbose(\"Error retrieving records from \" + tName, e);\n return null;\n } catch (JSONException e) {\n getConfigLogger().verbose(\"Error retrieving records from \" + tName, e.getMessage());\n return null;\n } finally {\n dbHelper.close();\n }\n }",
"private static String wordShapeChris2Long(String s, boolean omitIfInBoundary, int len, Collection<String> knownLCWords) {\r\n final char[] beginChars = new char[BOUNDARY_SIZE];\r\n final char[] endChars = new char[BOUNDARY_SIZE];\r\n int beginUpto = 0;\r\n int endUpto = 0;\r\n final Set<Character> seenSet = new TreeSet<Character>(); // TreeSet guarantees stable ordering; has no size parameter\r\n\r\n boolean nonLetters = false;\r\n\r\n for (int i = 0; i < len; i++) {\r\n int iIncr = 0;\r\n char c = s.charAt(i);\r\n char m = c;\r\n if (Character.isDigit(c)) {\r\n m = 'd';\r\n } else if (Character.isLowerCase(c)) {\r\n m = 'x';\r\n } else if (Character.isUpperCase(c) || Character.isTitleCase(c)) {\r\n m = 'X';\r\n }\r\n for (String gr : greek) {\r\n if (s.startsWith(gr, i)) {\r\n m = 'g';\r\n //System.out.println(s + \" :: \" + s.substring(i+1));\r\n iIncr = gr.length() - 1;\r\n break;\r\n }\r\n }\r\n if (m != 'x' && m != 'X') {\r\n nonLetters = true;\r\n }\r\n\r\n if (i < BOUNDARY_SIZE) {\r\n beginChars[beginUpto++] = m;\r\n } else if (i < len - BOUNDARY_SIZE) {\r\n seenSet.add(Character.valueOf(m));\r\n } else {\r\n endChars[endUpto++] = m;\r\n }\r\n i += iIncr;\r\n // System.out.println(\"Position skips to \" + i);\r\n }\r\n\r\n // Calculate size. This may be an upperbound, but is often correct\r\n int sbSize = beginUpto + endUpto + seenSet.size();\r\n if (knownLCWords != null) { sbSize++; }\r\n final StringBuilder sb = new StringBuilder(sbSize);\r\n // put in the beginning chars\r\n sb.append(beginChars, 0, beginUpto);\r\n // put in the stored ones sorted\r\n if (omitIfInBoundary) {\r\n for (Character chr : seenSet) {\r\n char ch = chr.charValue();\r\n boolean insert = true;\r\n for (int i = 0; i < beginUpto; i++) {\r\n if (beginChars[i] == ch) {\r\n insert = false;\r\n break;\r\n }\r\n }\r\n for (int i = 0; i < endUpto; i++) {\r\n if (endChars[i] == ch) {\r\n insert = false;\r\n break;\r\n }\r\n }\r\n if (insert) {\r\n sb.append(ch);\r\n }\r\n }\r\n } else {\r\n for (Character chr : seenSet) {\r\n sb.append(chr.charValue());\r\n }\r\n }\r\n // and add end ones\r\n sb.append(endChars, 0, endUpto);\r\n\r\n if (knownLCWords != null) {\r\n if (!nonLetters && knownLCWords.contains(s.toLowerCase())) {\r\n sb.append('k');\r\n }\r\n }\r\n // System.out.println(s + \" became \" + sb);\r\n return sb.toString();\r\n }",
"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}",
"protected String sourceLineTrimmed(ASTNode node) {\r\n return sourceCode.line(AstUtil.findFirstNonAnnotationLine(node, sourceCode) - 1);\r\n }",
"public static String createFolderPath(String path) {\n\n String[] pathParts = path.split(\"\\\\.\");\n String path2 = \"\";\n for (String part : pathParts) {\n if (path2.equals(\"\")) {\n path2 = part;\n } else {\n path2 = path2 + File.separator\n + changeFirstLetterToLowerCase(createClassName(part));\n }\n }\n\n return path2;\n }",
"public ItemRequest<Section> insertInProject(String project) {\n \n String path = String.format(\"/projects/%s/sections/insert\", project);\n return new ItemRequest<Section>(this, Section.class, path, \"POST\");\n }"
] |
Handles an initial response from a PUT or PATCH operation response by polling
the status of the operation until the long running operation terminates.
@param observable the initial observable from the PUT or PATCH operation.
@param <T> the return type of the caller
@param resourceType the java.lang.reflect.Type of the resource.
@return the terminal response for the operation.
@throws CloudException REST exception
@throws InterruptedException interrupted exception
@throws IOException thrown by deserialization | [
"private <T> ServiceResponse<T> getPutOrPatchResult(Observable<Response<ResponseBody>> observable, Type resourceType) throws CloudException, InterruptedException, IOException {\n Observable<ServiceResponse<T>> asyncObservable = getPutOrPatchResultAsync(observable, resourceType);\n return asyncObservable.toBlocking().last();\n }"
] | [
"public static java.sql.Timestamp toTimestamp(Object value) throws ParseException {\n if (value == null) {\n return null;\n }\n if (value instanceof java.sql.Timestamp) {\n return (java.sql.Timestamp) value;\n }\n if (value instanceof String) {\n\n if (\"\".equals((String) value)) {\n return null;\n }\n return new java.sql.Timestamp(IN_TIMESTAMP_FORMAT.parse((String) value).getTime());\n }\n\n return new java.sql.Timestamp(IN_TIMESTAMP_FORMAT.parse(value.toString()).getTime());\n }",
"public void enableClipRegion() {\n if (mClippingEnabled) {\n Log.w(TAG, \"Clipping has been enabled already for %s!\", getName());\n return;\n }\n Log.d(Log.SUBSYSTEM.WIDGET, TAG, \"enableClipping for %s [%f, %f, %f]\",\n getName(), getViewPortWidth(), getViewPortHeight(), getViewPortDepth());\n\n mClippingEnabled = true;\n\n GVRTexture texture = WidgetLib.getTextureHelper().getSolidColorTexture(Color.YELLOW);\n\n GVRSceneObject clippingObj = new GVRSceneObject(mContext, getViewPortWidth(), getViewPortHeight(), texture);\n clippingObj.setName(\"clippingObj\");\n clippingObj.getRenderData()\n .setRenderingOrder(GVRRenderData.GVRRenderingOrder.STENCIL)\n .setStencilTest(true)\n .setStencilFunc(GLES30.GL_ALWAYS, 1, 0xFF)\n .setStencilOp(GLES30.GL_KEEP, GLES30.GL_KEEP, GLES30.GL_REPLACE)\n .setStencilMask(0xFF);\n\n mSceneObject.addChildObject(clippingObj);\n\n for (Widget child : getChildren()) {\n setObjectClipped(child);\n }\n }",
"public static dnsglobal_binding get(nitro_service service) throws Exception{\n\t\tdnsglobal_binding obj = new dnsglobal_binding();\n\t\tdnsglobal_binding response = (dnsglobal_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public SwaptionDataLattice append(SwaptionDataLattice other, AnalyticModel model) {\r\n\r\n\t\tSwaptionDataLattice combined = new SwaptionDataLattice(referenceDate, quotingConvention, displacement,\r\n\t\t\t\tforwardCurveName, discountCurveName, floatMetaSchedule, fixMetaSchedule);\r\n\t\tcombined.entryMap.putAll(entryMap);\r\n\r\n\t\tif(quotingConvention == other.quotingConvention && displacement == other.displacement) {\r\n\t\t\tcombined.entryMap.putAll(other.entryMap);\r\n\t\t} else {\r\n\t\t\tSwaptionDataLattice converted = other.convertLattice(quotingConvention, displacement, model);\r\n\t\t\tcombined.entryMap.putAll(converted.entryMap);\r\n\t\t}\r\n\r\n\t\treturn combined;\r\n\t}",
"public static Integer convertPathIdentifier(String identifier, Integer profileId) throws Exception {\n Integer pathId = -1;\n try {\n pathId = Integer.parseInt(identifier);\n } catch (NumberFormatException ne) {\n // this is OK.. just means it's not a #\n if (profileId == null)\n throw new Exception(\"A profileId must be specified\");\n\n pathId = PathOverrideService.getInstance().getPathId(identifier, profileId);\n }\n\n return pathId;\n }",
"public void setAcquireRetryDelay(long acquireRetryDelay, TimeUnit timeUnit) {\n\t\tthis.acquireRetryDelayInMs = TimeUnit.MILLISECONDS.convert(acquireRetryDelay, timeUnit);\n\t}",
"public static final int getInt(byte[] data, int offset)\n {\n int result = 0;\n int i = offset;\n for (int shiftBy = 0; shiftBy < 32; shiftBy += 8)\n {\n result |= ((data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }",
"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 }",
"private long getWeightedMatchScore(Iterable<String> requestUriParts, Iterable<String> destUriParts) {\n // The score calculated below is a base 5 number\n // The score will have one digit for one part of the URI\n // This will allow for 27 parts in the path since log (Long.MAX_VALUE) to base 5 = 27.13\n // We limit the number of parts in the path to 25 using MAX_PATH_PARTS constant above to avoid overflow during\n // score calculation\n long score = 0;\n for (Iterator<String> rit = requestUriParts.iterator(), dit = destUriParts.iterator();\n rit.hasNext() && dit.hasNext(); ) {\n String requestPart = rit.next();\n String destPart = dit.next();\n if (requestPart.equals(destPart)) {\n score = (score * 5) + 4;\n } else if (PatternPathRouterWithGroups.GROUP_PATTERN.matcher(destPart).matches()) {\n score = (score * 5) + 3;\n } else {\n score = (score * 5) + 2;\n }\n }\n return score;\n }"
] |
Use this API to delete dnstxtrec. | [
"public static base_response delete(nitro_service client, dnstxtrec resource) throws Exception {\n\t\tdnstxtrec deleteresource = new dnstxtrec();\n\t\tdeleteresource.domain = resource.domain;\n\t\tdeleteresource.String = resource.String;\n\t\tdeleteresource.recordid = resource.recordid;\n\t\treturn deleteresource.delete_resource(client);\n\t}"
] | [
"public void addChild(final DiffNode node)\n\t{\n\t\tif (node == this)\n\t\t{\n\t\t\tthrow new IllegalArgumentException(\"Detected attempt to add a node to itself. \" +\n\t\t\t\t\t\"This would cause inifite loops and must never happen.\");\n\t\t}\n\t\telse if (node.isRootNode())\n\t\t{\n\t\t\tthrow new IllegalArgumentException(\"Detected attempt to add root node as child. \" +\n\t\t\t\t\t\"This is not allowed and must be a mistake.\");\n\t\t}\n\t\telse if (node.getParentNode() != null && node.getParentNode() != this)\n\t\t{\n\t\t\tthrow new IllegalArgumentException(\"Detected attempt to add child node that is already the \" +\n\t\t\t\t\t\"child of another node. Adding nodes multiple times is not allowed, since it could \" +\n\t\t\t\t\t\"cause infinite loops.\");\n\t\t}\n\t\tif (node.getParentNode() == null)\n\t\t{\n\t\t\tnode.setParentNode(this);\n\t\t}\n\t\tchildren.put(node.getElementSelector(), node);\n\t\tif (state == State.UNTOUCHED && node.hasChanges())\n\t\t{\n\t\t\tstate = State.CHANGED;\n\t\t}\n\t}",
"public static MetadataTemplate createMetadataTemplate(BoxAPIConnection api, String scope, String templateKey,\n String displayName, boolean hidden, List<Field> fields) {\n\n JsonObject jsonObject = new JsonObject();\n jsonObject.add(\"scope\", scope);\n jsonObject.add(\"displayName\", displayName);\n jsonObject.add(\"hidden\", hidden);\n\n if (templateKey != null) {\n jsonObject.add(\"templateKey\", templateKey);\n }\n\n JsonArray fieldsArray = new JsonArray();\n if (fields != null && !fields.isEmpty()) {\n for (Field field : fields) {\n JsonObject fieldObj = getFieldJsonObject(field);\n\n fieldsArray.add(fieldObj);\n }\n\n jsonObject.add(\"fields\", fieldsArray);\n }\n\n URL url = METADATA_TEMPLATE_SCHEMA_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n request.setBody(jsonObject.toString());\n\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n return new MetadataTemplate(responseJSON);\n }",
"public static boolean queryHasResult(Statement stmt, String sql) {\n try {\n ResultSet rs = stmt.executeQuery(sql);\n try {\n return rs.next();\n } finally {\n rs.close();\n }\n } catch (SQLException e) {\n throw new DukeException(e);\n }\n }",
"public boolean hasUser(String userId) {\r\n String normalized = normalizerUserName(userId);\r\n return loginToUser.containsKey(normalized) || emailToUser.containsKey(normalized);\r\n }",
"public NestedDef getNested(String name)\r\n {\r\n NestedDef nestedDef = null;\r\n\r\n for (Iterator it = _nested.iterator(); it.hasNext(); )\r\n {\r\n nestedDef = (NestedDef)it.next();\r\n if (nestedDef.getName().equals(name))\r\n {\r\n return nestedDef;\r\n }\r\n }\r\n return null;\r\n }",
"static AbstractLazyPatchableTarget createPatchableTarget(final String name, final LayerPathConfig layer, final File metadata, final InstalledImage image) throws IOException {\n // patchable target\n return new AbstractLazyPatchableTarget() {\n\n @Override\n public InstalledImage getInstalledImage() {\n return image;\n }\n\n @Override\n public File getModuleRoot() {\n return layer.modulePath;\n }\n\n @Override\n public File getBundleRepositoryRoot() {\n return layer.bundlePath;\n }\n\n public File getPatchesMetadata() {\n return metadata;\n }\n\n @Override\n public String getName() {\n return name;\n }\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 void setProjectionMatrix(float x1, float y1, float z1, float w1,\n float x2, float y2, float z2, float w2, float x3, float y3,\n float z3, float w3, float x4, float y4, float z4, float w4) {\n NativeCustomCamera.setProjectionMatrix(getNative(), x1, y1, z1, w1, x2,\n y2, z2, w2, x3, y3, z3, w3, x4, y4, z4, w4);\n }",
"private Server setUpServer() {\n Server server = new Server(port);\n ResourceHandler handler = new ResourceHandler();\n handler.setDirectoriesListed(true);\n handler.setWelcomeFiles(new String[]{\"index.html\"});\n handler.setResourceBase(getReportDirectoryPath().toAbsolutePath().toString());\n HandlerList handlers = new HandlerList();\n handlers.setHandlers(new Handler[]{handler, new DefaultHandler()});\n server.setStopAtShutdown(true);\n server.setHandler(handlers);\n return server;\n }"
] |
Update counters and call hooks.
@param handle connection handle. | [
"protected void postDestroyConnection(ConnectionHandle handle){\r\n\t\tConnectionPartition partition = handle.getOriginatingPartition();\r\n\r\n\t\tif (this.finalizableRefQueue != null && handle.getInternalConnection() != null){ //safety\r\n\t\t\tthis.finalizableRefs.remove(handle.getInternalConnection());\r\n\t\t\t//\t\t\tassert o != null : \"Did not manage to remove connection from finalizable ref queue\";\r\n\t\t}\r\n\r\n\t\tpartition.updateCreatedConnections(-1);\r\n\t\tpartition.setUnableToCreateMoreTransactions(false); // we can create new ones now, this is an optimization\r\n\r\n\r\n\t\t// \"Destroying\" for us means: don't put it back in the pool.\r\n\t\tif (handle.getConnectionHook() != null){\r\n\t\t\thandle.getConnectionHook().onDestroy(handle);\r\n\t\t}\r\n\r\n\t}"
] | [
"private Date getTime(String value) throws MPXJException\n {\n try\n {\n Number hours = m_twoDigitFormat.parse(value.substring(0, 2));\n Number minutes = m_twoDigitFormat.parse(value.substring(2, 4));\n\n Calendar cal = DateHelper.popCalendar();\n cal.set(Calendar.HOUR_OF_DAY, hours.intValue());\n cal.set(Calendar.MINUTE, minutes.intValue());\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MILLISECOND, 0);\n Date result = cal.getTime();\n DateHelper.pushCalendar(cal);\n \n return result;\n }\n\n catch (ParseException ex)\n {\n throw new MPXJException(\"Failed to parse time \" + value, ex);\n }\n }",
"public static void acceptsNodeMultiple(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_N, OPT_NODE), \"node id list\")\n .withRequiredArg()\n .describedAs(\"node-id-list\")\n .withValuesSeparatedBy(',')\n .ofType(Integer.class);\n }",
"@Override\n protected Deque<Step> childValue(Deque<Step> parentValue) {\n Deque<Step> queue = new LinkedList<>();\n queue.add(parentValue.getFirst());\n return queue;\n }",
"public static void parse(Reader src, StatementHandler handler)\n throws IOException {\n new NTriplesParser(src, handler).parse();\n }",
"@SuppressWarnings(\"unchecked\")\n\tpublic static Type getSuperclassTypeParameter(Class<?> subclass) {\n\t\tType superclass = subclass.getGenericSuperclass();\n\t\tif (superclass instanceof Class) {\n\t\t\tthrow new RuntimeException(\"Missing type parameter.\");\n\t\t}\n\t\treturn ((ParameterizedType) superclass).getActualTypeArguments()[0];\n\t}",
"public void setShowOutput(String mode) {\n try {\n this.outputMode = OutputMode.valueOf(mode.toUpperCase(Locale.ROOT));\n } catch (IllegalArgumentException e) {\n throw new IllegalArgumentException(\"showOutput accepts any of: \"\n + Arrays.toString(OutputMode.values()) + \", value is not valid: \" + mode);\n }\n }",
"public static DocumentBuilder getXmlParser() {\r\n DocumentBuilder db = null;\r\n try {\r\n DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\r\n dbf.setValidating(false);\r\n\r\n //Disable DTD loading and validation\r\n //See http://stackoverflow.com/questions/155101/make-documentbuilder-parse-ignore-dtd-references\r\n dbf.setFeature(\"http://apache.org/xml/features/nonvalidating/load-dtd-grammar\", false);\r\n dbf.setFeature(\"http://apache.org/xml/features/nonvalidating/load-external-dtd\", false);\r\n\r\n db = dbf.newDocumentBuilder();\r\n db.setErrorHandler(new SAXErrorHandler());\r\n\r\n } catch (ParserConfigurationException e) {\r\n System.err.printf(\"%s: Unable to create XML parser\\n\", XMLUtils.class.getName());\r\n e.printStackTrace();\r\n\r\n } catch(UnsupportedOperationException e) {\r\n System.err.printf(\"%s: API error while setting up XML parser. Check your JAXP version\\n\", XMLUtils.class.getName());\r\n e.printStackTrace();\r\n }\r\n\r\n return db;\r\n }",
"private void processResponse(Response<ByteArray, Object> response, Pipeline pipeline) {\n if(response == null) {\n logger.warn(\"RoutingTimedout on waiting for async ops; parallelResponseToWait: \"\n + numNodesPendingResponse + \"; preferred-1: \" + (preferred - 1)\n + \"; quorumOK: \" + quorumSatisfied + \"; zoneOK: \" + zonesSatisfied);\n } else {\n numNodesPendingResponse = numNodesPendingResponse - 1;\n numResponsesGot = numResponsesGot + 1;\n if(response.getValue() instanceof Exception\n && !(response.getValue() instanceof ObsoleteVersionException)) {\n if(logger.isDebugEnabled()) {\n logger.debug(\"PUT {key:\" + key + \"} handling async put error\");\n }\n if(response.getValue() instanceof QuotaExceededException) {\n /**\n * TODO Not sure if we need to count this Exception for\n * stats or silently ignore and just log a warning. While\n * QuotaExceededException thrown from other places mean the\n * operation failed, this one does not fail the operation\n * but instead stores slops. Introduce a new Exception in\n * client side to just monitor how mamy Async writes fail on\n * exceeding Quota?\n * \n */\n if(logger.isDebugEnabled()) {\n logger.debug(\"Received quota exceeded exception after a successful \"\n + pipeline.getOperation().getSimpleName() + \" call on node \"\n + response.getNode().getId() + \", store '\"\n + pipelineData.getStoreName() + \"', master-node '\"\n + pipelineData.getMaster().getId() + \"'\");\n }\n } else if(handleResponseError(response, pipeline, failureDetector)) {\n if(logger.isDebugEnabled()) {\n logger.debug(\"PUT {key:\" + key\n + \"} severe async put error, exiting parallel put stage\");\n }\n\n return;\n }\n if(PipelineRoutedStore.isSlopableFailure(response.getValue())\n || response.getValue() instanceof QuotaExceededException) {\n /**\n * We want to slop ParallelPuts which fail due to\n * QuotaExceededException.\n * \n * TODO Though this is not the right way of doing things, in\n * order to avoid inconsistencies and data loss, we chose to\n * slop the quota failed parallel puts.\n * \n * As a long term solution - 1) either Quota management\n * should be hidden completely in a routing layer like\n * Coordinator or 2) the Server should be able to\n * distinguish between serial and parallel puts and should\n * only quota for serial puts\n * \n */\n pipelineData.getSynchronizer().tryDelegateSlop(response.getNode());\n }\n\n if(logger.isDebugEnabled()) {\n logger.debug(\"PUT {key:\" + key + \"} handled async put error\");\n }\n\n } else {\n pipelineData.incrementSuccesses();\n failureDetector.recordSuccess(response.getNode(), response.getRequestTime());\n pipelineData.getZoneResponses().add(response.getNode().getZoneId());\n }\n }\n }",
"public static CmsShell getTopShell() {\n\n ArrayList<CmsShell> shells = SHELL_STACK.get();\n if (shells.isEmpty()) {\n return null;\n }\n return shells.get(shells.size() - 1);\n\n }"
] |
Creates an association row representing the given entry and adds it to the association managed by the given
persister. | [
"private RowKeyAndTuple createAndPutAssociationRowForInsert(Serializable key, PersistentCollection collection,\n\t\t\tAssociationPersister associationPersister, SharedSessionContractImplementor session, int i, Object entry) {\n\t\tRowKeyBuilder rowKeyBuilder = initializeRowKeyBuilder();\n\t\tTuple associationRow = new Tuple();\n\n\t\t// the collection has a surrogate key (see @CollectionId)\n\t\tif ( hasIdentifier ) {\n\t\t\tfinal Object identifier = collection.getIdentifier( entry, i );\n\t\t\tString[] names = { getIdentifierColumnName() };\n\t\t\tidentifierGridType.nullSafeSet( associationRow, identifier, names, session );\n\t\t}\n\n\t\tgetKeyGridType().nullSafeSet( associationRow, key, getKeyColumnNames(), session );\n\t\t// No need to write to where as we don't do where clauses in OGM :)\n\t\tif ( hasIndex ) {\n\t\t\tObject index = collection.getIndex( entry, i, this );\n\t\t\tindexGridType.nullSafeSet( associationRow, incrementIndexByBase( index ), getIndexColumnNames(), session );\n\t\t}\n\n\t\t// columns of referenced key\n\t\tfinal Object element = collection.getElement( entry );\n\t\tgetElementGridType().nullSafeSet( associationRow, element, getElementColumnNames(), session );\n\n\t\tRowKeyAndTuple result = new RowKeyAndTuple();\n\t\tresult.key = rowKeyBuilder.values( associationRow ).build();\n\t\tresult.tuple = associationRow;\n\n\t\tassociationPersister.getAssociation().put( result.key, result.tuple );\n\n\t\treturn result;\n\t}"
] | [
"public AT_Row setTargetTranslator(TargetTranslator targetTranslator) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setTargetTranslator(targetTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public static void redeployDeployments(OperationContext context, PathAddress deploymentsRootAddress, Set<String> deploymentNames) throws OperationFailedException {\n for (String deploymentName : deploymentNames) {\n PathAddress address = deploymentsRootAddress.append(DEPLOYMENT, deploymentName);\n OperationStepHandler handler = context.getRootResourceRegistration().getOperationHandler(address, REDEPLOY);\n ModelNode operation = addRedeployStep(address);\n ServerLogger.AS_ROOT_LOGGER.debugf(\"Redeploying %s at address %s with handler %s\", deploymentName, address, handler);\n assert handler != null;\n assert operation.isDefined();\n context.addStep(operation, handler, OperationContext.Stage.MODEL);\n }\n }",
"public static PersistenceStrategy<?, ?, ?> getInstance(\n\t\t\tCacheMappingType cacheMapping,\n\t\t\tEmbeddedCacheManager externalCacheManager,\n\t\t\tURL configurationUrl,\n\t\t\tJtaPlatform jtaPlatform,\n\t\t\tSet<EntityKeyMetadata> entityTypes,\n\t\t\tSet<AssociationKeyMetadata> associationTypes,\n\t\t\tSet<IdSourceKeyMetadata> idSourceTypes ) {\n\n\t\tif ( cacheMapping == CacheMappingType.CACHE_PER_KIND ) {\n\t\t\treturn getPerKindStrategy(\n\t\t\t\t\texternalCacheManager,\n\t\t\t\t\tconfigurationUrl,\n\t\t\t\t\tjtaPlatform\n\t\t\t);\n\t\t}\n\t\telse {\n\t\t\treturn getPerTableStrategy(\n\t\t\t\t\texternalCacheManager,\n\t\t\t\t\tconfigurationUrl,\n\t\t\t\t\tjtaPlatform,\n\t\t\t\t\tentityTypes,\n\t\t\t\t\tassociationTypes,\n\t\t\t\t\tidSourceTypes\n\t\t\t);\n\t\t}\n\t}",
"public List<PPVItemsType.PPVItem> getPPVItem()\n {\n if (ppvItem == null)\n {\n ppvItem = new ArrayList<PPVItemsType.PPVItem>();\n }\n return this.ppvItem;\n }",
"public static String getDumpFileName(DumpContentType dumpContentType,\n\t\t\tString projectName, String dateStamp) {\n\t\tif (dumpContentType == DumpContentType.JSON) {\n\t\t\treturn dateStamp + WmfDumpFile.getDumpFilePostfix(dumpContentType);\n\t\t} else {\n\t\t\treturn projectName + \"-\" + dateStamp\n\t\t\t\t\t+ WmfDumpFile.getDumpFilePostfix(dumpContentType);\n\t\t}\n\t}",
"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 }",
"private void stripCommas(TokenList tokens) {\n TokenList.Token t = tokens.getFirst();\n\n while( t != null ) {\n TokenList.Token next = t.next;\n if( t.getSymbol() == Symbol.COMMA ) {\n tokens.remove(t);\n }\n t = next;\n }\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 void runOnInvariantViolationPlugins(Invariant invariant,\n\t\t\tCrawlerContext context) {\n\t\tLOGGER.debug(\"Running OnInvariantViolationPlugins...\");\n\t\tcounters.get(OnInvariantViolationPlugin.class).inc();\n\t\tfor (Plugin plugin : plugins.get(OnInvariantViolationPlugin.class)) {\n\t\t\tif (plugin instanceof OnInvariantViolationPlugin) {\n\t\t\t\ttry {\n\t\t\t\t\tLOGGER.debug(\"Calling plugin {}\", plugin);\n\t\t\t\t\t((OnInvariantViolationPlugin) plugin).onInvariantViolation(\n\t\t\t\t\t\t\tinvariant, context);\n\t\t\t\t} catch (RuntimeException e) {\n\t\t\t\t\treportFailingPlugin(plugin, e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}"
] |
Attaches the menu drawer to the window. | [
"private static void attachToDecor(Activity activity, MenuDrawer menuDrawer) {\n ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView();\n ViewGroup decorChild = (ViewGroup) decorView.getChildAt(0);\n\n decorView.removeAllViews();\n decorView.addView(menuDrawer, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);\n\n menuDrawer.mContentContainer.addView(decorChild, decorChild.getLayoutParams());\n }"
] | [
"public void initSize(Rectangle rectangle) {\n\t\ttemplate = writer.getDirectContent().createTemplate(rectangle.getWidth(), rectangle.getHeight());\n\t}",
"private void checkQueryCustomizer(CollectionDescriptorDef collDef, String checkLevel) throws ConstraintException\r\n {\r\n if (!CHECKLEVEL_STRICT.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n \r\n String queryCustomizerName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_QUERY_CUSTOMIZER);\r\n\r\n if (queryCustomizerName == null)\r\n {\r\n return;\r\n }\r\n\r\n try\r\n {\r\n InheritanceHelper helper = new InheritanceHelper();\r\n\r\n if (!helper.isSameOrSubTypeOf(queryCustomizerName, QUERY_CUSTOMIZER_INTERFACE))\r\n {\r\n throw new ConstraintException(\"The class \"+queryCustomizerName+\" specified as query-customizer of collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" does not implement the interface \"+QUERY_CUSTOMIZER_INTERFACE);\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"The class \"+ex.getMessage()+\" specified as query-customizer of collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" was not found on the classpath\");\r\n }\r\n }",
"public void callFunction(String className, String methodName, PluginArguments pluginArgs, Object... args) throws Exception {\n Class<?> cls = getClass(className);\n\n ArrayList<Object> newArgs = new ArrayList<>();\n newArgs.add(pluginArgs);\n com.groupon.odo.proxylib.models.Method m = preparePluginMethod(newArgs, className, methodName, args);\n\n m.getMethod().invoke(cls, newArgs.toArray(new Object[0]));\n }",
"public double[] getRegressionCoefficients(RandomVariable value) {\n\t\tif(basisFunctions.length == 0) {\n\t\t\treturn new double[] { };\n\t\t}\n\t\telse if(basisFunctions.length == 1) {\n\t\t\t/*\n\t\t\t * Regression with one basis function is just a projection on that vector. <b,x>/<b,b>\n\t\t\t */\n\t\t\treturn new double[] { value.mult(basisFunctions[0]).getAverage() / basisFunctions[0].squared().getAverage() };\n\t\t}\n\t\telse if(basisFunctions.length == 2) {\n\t\t\t/*\n\t\t\t * Regression with two basis functions can be solved explicitly if determinant != 0 (otherwise we will fallback to SVD)\n\t\t\t */\n\t\t\tdouble a = basisFunctions[0].squared().getAverage();\n\t\t\tdouble b = basisFunctions[0].mult(basisFunctions[1]).average().squared().doubleValue();\n\t\t\tdouble c = b;\n\t\t\tdouble d = basisFunctions[1].squared().getAverage();\n\n\t\t\tdouble determinant = (a * d - b * c);\n\t\t\tif(determinant != 0) {\n\t\t\t\tdouble x = value.mult(basisFunctions[0]).getAverage();\n\t\t\t\tdouble y = value.mult(basisFunctions[1]).getAverage();\n\n\t\t\t\tdouble alpha0 = (d * x - b * y) / determinant;\n\t\t\t\tdouble alpha1 = (a * y - c * x) / determinant;\n\n\t\t\t\treturn new double[] { alpha0, alpha1 };\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * General case\n\t\t */\n\n\t\t// Build regression matrix\n\t\tdouble[][] BTB = new double[basisFunctions.length][basisFunctions.length];\n\t\tfor(int i=0; i<basisFunctions.length; i++) {\n\t\t\tfor(int j=0; j<=i; j++) {\n\t\t\t\tdouble covariance = basisFunctions[i].mult(basisFunctions[j]).getAverage();\n\t\t\t\tBTB[i][j] = covariance;\n\t\t\t\tBTB[j][i] = covariance;\n\t\t\t}\n\t\t}\n\n\t\tdouble[] BTX = new double[basisFunctions.length];\n\t\tfor(int i=0; i<basisFunctions.length; i++) {\n\t\t\tdouble covariance = basisFunctions[i].mult(value).getAverage();\n\t\t\tBTX[i] = covariance;\n\t\t}\n\n\t\treturn LinearAlgebra.solveLinearEquationLeastSquare(BTB, BTX);\n\t}",
"public static base_responses add(nitro_service client, dbdbprofile resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdbdbprofile addresources[] = new dbdbprofile[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dbdbprofile();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].interpretquery = resources[i].interpretquery;\n\t\t\t\taddresources[i].stickiness = resources[i].stickiness;\n\t\t\t\taddresources[i].kcdaccount = resources[i].kcdaccount;\n\t\t\t\taddresources[i].conmultiplex = resources[i].conmultiplex;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"public ItemRequest<CustomField> updateEnumOption(String enumOption) {\n \n String path = String.format(\"/enum_options/%s\", enumOption);\n return new ItemRequest<CustomField>(this, CustomField.class, path, \"PUT\");\n }",
"private void logRequestHistory(HttpMethod httpMethodProxyRequest, PluginResponse httpServletResponse,\n History history) {\n try {\n if (requestInformation.get().handle && requestInformation.get().client.getIsActive()) {\n logger.info(\"Storing history\");\n String createdDate;\n SimpleDateFormat sdf = new SimpleDateFormat();\n sdf.setTimeZone(new SimpleTimeZone(0, \"GMT\"));\n sdf.applyPattern(\"dd MMM yyyy HH:mm:ss\");\n createdDate = sdf.format(new Date()) + \" GMT\";\n\n history.setCreatedAt(createdDate);\n history.setRequestURL(HttpUtilities.getURL(httpMethodProxyRequest.getURI().toString()));\n history.setRequestParams(httpMethodProxyRequest.getQueryString() == null ? \"\"\n : httpMethodProxyRequest.getQueryString());\n history.setRequestHeaders(HttpUtilities.getHeaders(httpMethodProxyRequest));\n history.setResponseHeaders(HttpUtilities.getHeaders(httpServletResponse));\n history.setResponseCode(Integer.toString(httpServletResponse.getStatus()));\n history.setResponseContentType(httpServletResponse.getContentType());\n history.setResponseData(httpServletResponse.getContentString());\n history.setResponseBodyDecoded(httpServletResponse.isContentDecoded());\n HistoryService.getInstance().addHistory(history);\n logger.info(\"Done storing\");\n }\n } catch (URIException e) {\n e.printStackTrace();\n }\n }",
"public static <T> FastEvent<T> of(Class<T> type, BeanManagerImpl manager, ObserverNotifier notifier, Annotation... qualifiers) {\n ResolvedObservers<T> resolvedObserverMethods = notifier.<T> resolveObserverMethods(type, qualifiers);\n if (resolvedObserverMethods.isMetadataRequired()) {\n EventMetadata metadata = new EventMetadataImpl(type, null, qualifiers);\n CurrentEventMetadata metadataService = manager.getServices().get(CurrentEventMetadata.class);\n return new FastEventWithMetadataPropagation<T>(resolvedObserverMethods, metadata, metadataService);\n } else {\n return new FastEvent<T>(resolvedObserverMethods);\n }\n }",
"private String getProjectName() {\n String pName = Strings.emptyToNull(projectName);\n if (pName == null) { \n pName = Strings.emptyToNull(junit4.getProject().getName());\n }\n if (pName == null) {\n pName = \"(unnamed project)\"; \n }\n return pName;\n }"
] |
Find out which field in the incoming message contains the payload that is.
delivered to the service method. | [
"protected FieldDescriptor resolvePayloadField(Message message) {\n for (FieldDescriptor field : message.getDescriptorForType().getFields()) {\n if (message.hasField(field)) {\n return field;\n }\n }\n\n throw new RuntimeException(\"No payload found in message \" + message);\n }"
] | [
"public ItemRequest<Story> findById(String story) {\n \n String path = String.format(\"/stories/%s\", story);\n return new ItemRequest<Story>(this, Story.class, path, \"GET\");\n }",
"public BoxFile.Info restoreFile(String fileID) {\n URL url = RESTORE_FILE_URL_TEMPLATE.build(this.api.getBaseURL(), fileID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"POST\");\n JsonObject requestJSON = new JsonObject()\n .add(\"\", \"\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxFile restoredFile = new BoxFile(this.api, responseJSON.get(\"id\").asString());\n return restoredFile.new Info(responseJSON);\n }",
"public void setWorkingDay(Day day, DayType working)\n {\n DayType value;\n\n if (working == null)\n {\n if (isDerived())\n {\n value = DayType.DEFAULT;\n }\n else\n {\n value = DayType.WORKING;\n }\n }\n else\n {\n value = working;\n }\n\n m_days[day.getValue() - 1] = value;\n }",
"public static List<Object> listOfEntities(SharedSessionContractImplementor session, Type[] resultTypes, ClosableIterator<Tuple> tuples) {\n\t\tClass<?> returnedClass = resultTypes[0].getReturnedClass();\n\t\tTupleBasedEntityLoader loader = getLoader( session, returnedClass );\n\t\tOgmLoadingContext ogmLoadingContext = new OgmLoadingContext();\n\t\togmLoadingContext.setTuples( getTuplesAsList( tuples ) );\n\t\treturn loader.loadEntitiesFromTuples( session, LockOptions.NONE, ogmLoadingContext );\n\t}",
"@Override public void setID(Integer val)\n {\n ProjectFile parent = getParentFile();\n Integer previous = getID();\n if (previous != null)\n {\n parent.getResources().unmapID(previous);\n }\n parent.getResources().mapID(val, this);\n\n set(ResourceField.ID, val);\n }",
"public static base_responses update(nitro_service client, snmpalarm resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsnmpalarm updateresources[] = new snmpalarm[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new snmpalarm();\n\t\t\t\tupdateresources[i].trapname = resources[i].trapname;\n\t\t\t\tupdateresources[i].thresholdvalue = resources[i].thresholdvalue;\n\t\t\t\tupdateresources[i].normalvalue = resources[i].normalvalue;\n\t\t\t\tupdateresources[i].time = resources[i].time;\n\t\t\t\tupdateresources[i].state = resources[i].state;\n\t\t\t\tupdateresources[i].severity = resources[i].severity;\n\t\t\t\tupdateresources[i].logging = resources[i].logging;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public void onSplashScreenCreated(GVRSceneObject splashScreen) {\n GVRTransform transform = splashScreen.getTransform();\n transform.setPosition(0, 0, DEFAULT_SPLASH_Z);\n }",
"public boolean hasUser(String userId) {\r\n String normalized = normalizerUserName(userId);\r\n return loginToUser.containsKey(normalized) || emailToUser.containsKey(normalized);\r\n }",
"public static rnatip_stats get(nitro_service service, String Rnatip) throws Exception{\n\t\trnatip_stats obj = new rnatip_stats();\n\t\tobj.set_Rnatip(Rnatip);\n\t\trnatip_stats response = (rnatip_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}"
] |
Return a Halton number, sequence starting at index = 0, base > 1.
@param index The index of the sequence.
@param base The base of the sequence. Has to be greater than one (this is not checked).
@return The Halton number. | [
"public static double getHaltonNumberForGivenBase(long index, int base) {\n\t\tindex += 1;\n\n\t\tdouble x = 0.0;\n\t\tdouble factor = 1.0 / base;\n\t\twhile(index > 0) {\n\t\t\tx += (index % base) * factor;\n\t\t\tfactor /= base;\n\t\t\tindex /= base;\n\t\t}\n\n\t\treturn x;\n\t}"
] | [
"public GetAssignmentGroupOptions includes(List<Include> includes) {\n List<Include> assignmentDependents = Arrays.asList(Include.DISCUSSION_TOPIC, Include.ASSIGNMENT_VISIBILITY, Include.SUBMISSION);\n if(includes.stream().anyMatch(assignmentDependents::contains) && !includes.contains(Include.ASSIGNMENTS)) {\n throw new IllegalArgumentException(\"Including discussion topics, all dates, assignment visibility or submissions is only valid if you also include submissions\");\n }\n addEnumList(\"include[]\", includes);\n return this;\n }",
"public final void setAttributes(final Map<String, Attribute> attributes) {\n for (Map.Entry<String, Attribute> entry: attributes.entrySet()) {\n Object attribute = entry.getValue();\n if (!(attribute instanceof Attribute)) {\n final String msg =\n \"Attribute: '\" + entry.getKey() + \"' is not an attribute. It is a: \" + attribute;\n LOGGER.error(\"Error setting the Attributes: {}\", msg);\n throw new IllegalArgumentException(msg);\n } else {\n ((Attribute) attribute).setConfigName(entry.getKey());\n }\n }\n this.attributes = attributes;\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 }",
"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 }",
"@Override\n public void setValue(String value, boolean fireEvents) {\n\tboolean added = setSelectedValue(this, value, addMissingValue);\n\tif (added && fireEvents) {\n\t ValueChangeEvent.fire(this, getValue());\n\t}\n }",
"private <T> void deferNotification(T event, final EventMetadata metadata, final ObserverMethod<? super T> observer,\n final List<DeferredEventNotification<?>> notifications) {\n TransactionPhase transactionPhase = observer.getTransactionPhase();\n boolean before = transactionPhase.equals(TransactionPhase.BEFORE_COMPLETION);\n Status status = Status.valueOf(transactionPhase);\n notifications.add(new DeferredEventNotification<T>(contextId, event, metadata, observer, currentEventMetadata, status, before));\n }",
"private SubProject readSubProject(byte[] data, int uniqueIDOffset, int filePathOffset, int fileNameOffset, int subprojectIndex)\n {\n try\n {\n SubProject sp = new SubProject();\n int type = SUBPROJECT_TASKUNIQUEID0;\n\n if (uniqueIDOffset != -1)\n {\n int value = MPPUtility.getInt(data, uniqueIDOffset);\n type = MPPUtility.getInt(data, uniqueIDOffset + 4);\n switch (type)\n {\n case SUBPROJECT_TASKUNIQUEID0:\n case SUBPROJECT_TASKUNIQUEID1:\n case SUBPROJECT_TASKUNIQUEID2:\n case SUBPROJECT_TASKUNIQUEID3:\n case SUBPROJECT_TASKUNIQUEID4:\n case SUBPROJECT_TASKUNIQUEID5:\n case SUBPROJECT_TASKUNIQUEID6:\n {\n sp.setTaskUniqueID(Integer.valueOf(value));\n m_taskSubProjects.put(sp.getTaskUniqueID(), sp);\n break;\n }\n\n default:\n {\n if (value != 0)\n {\n sp.addExternalTaskUniqueID(Integer.valueOf(value));\n m_taskSubProjects.put(Integer.valueOf(value), sp);\n }\n break;\n }\n }\n\n // Now get the unique id offset for this subproject\n value = 0x00800000 + ((subprojectIndex - 1) * 0x00400000);\n sp.setUniqueIDOffset(Integer.valueOf(value));\n }\n\n if (type == SUBPROJECT_TASKUNIQUEID4)\n {\n sp.setFullPath(MPPUtility.getUnicodeString(data, filePathOffset));\n }\n else\n {\n //\n // First block header\n //\n filePathOffset += 18;\n\n //\n // String size as a 4 byte int\n //\n filePathOffset += 4;\n\n //\n // Full DOS path\n //\n sp.setDosFullPath(MPPUtility.getString(data, filePathOffset));\n filePathOffset += (sp.getDosFullPath().length() + 1);\n\n //\n // 24 byte block\n //\n filePathOffset += 24;\n\n //\n // 4 byte block size\n //\n int size = MPPUtility.getInt(data, filePathOffset);\n filePathOffset += 4;\n if (size == 0)\n {\n sp.setFullPath(sp.getDosFullPath());\n }\n else\n {\n //\n // 4 byte unicode string size in bytes\n //\n size = MPPUtility.getInt(data, filePathOffset);\n filePathOffset += 4;\n\n //\n // 2 byte data\n //\n filePathOffset += 2;\n\n //\n // Unicode string\n //\n sp.setFullPath(MPPUtility.getUnicodeString(data, filePathOffset, size));\n //filePathOffset += size;\n }\n\n //\n // Second block header\n //\n fileNameOffset += 18;\n\n //\n // String size as a 4 byte int\n //\n fileNameOffset += 4;\n\n //\n // DOS file name\n //\n sp.setDosFileName(MPPUtility.getString(data, fileNameOffset));\n fileNameOffset += (sp.getDosFileName().length() + 1);\n\n //\n // 24 byte block\n //\n fileNameOffset += 24;\n\n //\n // 4 byte block size\n //\n size = MPPUtility.getInt(data, fileNameOffset);\n fileNameOffset += 4;\n\n if (size == 0)\n {\n sp.setFileName(sp.getDosFileName());\n }\n else\n {\n //\n // 4 byte unicode string size in bytes\n //\n size = MPPUtility.getInt(data, fileNameOffset);\n fileNameOffset += 4;\n\n //\n // 2 byte data\n //\n fileNameOffset += 2;\n\n //\n // Unicode string\n //\n sp.setFileName(MPPUtility.getUnicodeString(data, fileNameOffset, size));\n //fileNameOffset += size;\n }\n }\n\n //System.out.println(sp.toString());\n\n // Add to the list of subprojects\n m_file.getSubProjects().add(sp);\n\n return (sp);\n }\n\n //\n // Admit defeat at this point - we have probably stumbled\n // upon a data format we don't understand, so we'll fail\n // gracefully here. This will now be reported as a missing\n // sub project error by end users of the library, rather\n // than as an exception being thrown.\n //\n catch (ArrayIndexOutOfBoundsException ex)\n {\n return (null);\n }\n }",
"public Try<R,Throwable> execute(T input){\n\t\treturn Try.withCatch( ()->transactionTemplate.execute(status-> transaction.apply(input)));\n\t\t \n\t}",
"@Override\n\tpublic boolean addAll(Collection<? extends T> collection) {\n\t\tboolean changed = false;\n\t\tfor (T data : collection) {\n\t\t\ttry {\n\t\t\t\tif (addElement(data)) {\n\t\t\t\t\tchanged = true;\n\t\t\t\t}\n\t\t\t} catch (SQLException e) {\n\t\t\t\tthrow new IllegalStateException(\"Could not create data elements in dao\", e);\n\t\t\t}\n\t\t}\n\t\treturn changed;\n\t}"
] |
Returns the names of the involved fields when post processing.
@return the names of the involved fields | [
"public Set<String> postProcessingFields() {\n Set<String> fields = new LinkedHashSet<>();\n query.forEach(condition -> fields.addAll(condition.postProcessingFields()));\n sort.forEach(condition -> fields.addAll(condition.postProcessingFields()));\n return fields;\n }"
] | [
"public void add(ServiceReference<S> declarationBinderRef) throws InvalidFilterException {\n BinderDescriptor binderDescriptor = new BinderDescriptor(declarationBinderRef);\n declarationBinders.put(declarationBinderRef, binderDescriptor);\n }",
"protected Map<String, TermImpl> getMonolingualUpdatedValues(Map<String, NameWithUpdate> updates) {\n \tMap<String, TermImpl> updatedValues = new HashMap<>();\n \tfor(NameWithUpdate update : updates.values()) {\n if (!update.write) {\n continue;\n }\n updatedValues.put(update.value.getLanguageCode(), monolingualToJackson(update.value));\n \t}\n \treturn updatedValues;\n }",
"public static boolean isDiagonalPositive( DMatrixRMaj a ) {\n for( int i = 0; i < a.numRows; i++ ) {\n if( !(a.get(i,i) >= 0) )\n return false;\n }\n return true;\n }",
"public static lbvserver_scpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_scpolicy_binding obj = new lbvserver_scpolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_scpolicy_binding response[] = (lbvserver_scpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private String getClassLabel(EntityIdValue entityIdValue) {\n\t\tClassRecord classRecord = this.classRecords.get(entityIdValue);\n\t\tString label;\n\t\tif (classRecord == null || classRecord.itemDocument == null) {\n\t\t\tlabel = entityIdValue.getId();\n\t\t} else {\n\t\t\tlabel = getLabel(entityIdValue, classRecord.itemDocument);\n\t\t}\n\n\t\tEntityIdValue labelOwner = this.labels.get(label);\n\t\tif (labelOwner == null) {\n\t\t\tthis.labels.put(label, entityIdValue);\n\t\t\treturn label;\n\t\t} else if (labelOwner.equals(entityIdValue)) {\n\t\t\treturn label;\n\t\t} else {\n\t\t\treturn label + \" (\" + entityIdValue.getId() + \")\";\n\t\t}\n\t}",
"public HttpRequestFactory makeClient(DatastoreOptions options) {\n Credential credential = options.getCredential();\n HttpTransport transport = options.getTransport();\n if (transport == null) {\n transport = credential == null ? new NetHttpTransport() : credential.getTransport();\n transport = transport == null ? new NetHttpTransport() : transport;\n }\n return transport.createRequestFactory(credential);\n }",
"public Sites getSitesInformation() throws IOException {\n\t\tMwDumpFile sitesTableDump = getMostRecentDump(DumpContentType.SITES);\n\t\tif (sitesTableDump == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// Create a suitable processor for such dumps and process the file:\n\t\tMwSitesDumpFileProcessor sitesDumpFileProcessor = new MwSitesDumpFileProcessor();\n\t\tsitesDumpFileProcessor.processDumpFileContents(\n\t\t\t\tsitesTableDump.getDumpFileStream(), sitesTableDump);\n\n\t\treturn sitesDumpFileProcessor.getSites();\n\t}",
"public String getGroup(String groupId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_GROUP);\r\n\r\n parameters.put(\"group_id\", groupId);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element payload = response.getPayload();\r\n return payload.getAttribute(\"url\");\r\n }",
"public final PJsonObject getJSONObject(final int i) {\n JSONObject val = this.array.optJSONObject(i);\n final String context = \"[\" + i + \"]\";\n if (val == null) {\n throw new ObjectMissingException(this, context);\n }\n return new PJsonObject(this, val, context);\n }"
] |
Use this API to fetch all the systemeventhistory resources that are configured on netscaler.
This uses systemeventhistory_args which is a way to provide additional arguments while fetching the resources. | [
"public static systemeventhistory[] get(nitro_service service, systemeventhistory_args args) throws Exception{\n\t\tsystemeventhistory obj = new systemeventhistory();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tsystemeventhistory[] response = (systemeventhistory[])obj.get_resources(service, option);\n\t\treturn response;\n\t}"
] | [
"public static base_response flush(nitro_service client, nssimpleacl resource) throws Exception {\n\t\tnssimpleacl flushresource = new nssimpleacl();\n\t\tflushresource.estsessions = resource.estsessions;\n\t\treturn flushresource.perform_operation(client,\"flush\");\n\t}",
"public void combine(CRFClassifier<IN> crf, double weight) {\r\n Timing timer = new Timing();\r\n\r\n // Check the CRFClassifiers are compatible\r\n if (!this.pad.equals(crf.pad)) {\r\n throw new RuntimeException(\"Incompatible CRFClassifier: pad does not match\");\r\n }\r\n if (this.windowSize != crf.windowSize) {\r\n throw new RuntimeException(\"Incompatible CRFClassifier: windowSize does not match\");\r\n }\r\n if (this.labelIndices.length != crf.labelIndices.length) {\r\n // Should match since this should be same as the windowSize\r\n throw new RuntimeException(\"Incompatible CRFClassifier: labelIndices length does not match\");\r\n }\r\n this.classIndex.addAll(crf.classIndex.objectsList());\r\n\r\n // Combine weights of the other classifier with this classifier,\r\n // weighing the other classifier's weights by weight\r\n // First merge the feature indicies\r\n int oldNumFeatures1 = this.featureIndex.size();\r\n int oldNumFeatures2 = crf.featureIndex.size();\r\n int oldNumWeights1 = this.getNumWeights();\r\n int oldNumWeights2 = crf.getNumWeights();\r\n this.featureIndex.addAll(crf.featureIndex.objectsList());\r\n this.knownLCWords.addAll(crf.knownLCWords);\r\n assert (weights.length == oldNumFeatures1);\r\n\r\n // Combine weights of this classifier with other classifier\r\n for (int i = 0; i < labelIndices.length; i++) {\r\n this.labelIndices[i].addAll(crf.labelIndices[i].objectsList());\r\n }\r\n System.err.println(\"Combining weights: will automatically match labelIndices\");\r\n combineWeights(crf, weight);\r\n\r\n int numFeatures = featureIndex.size();\r\n int numWeights = getNumWeights();\r\n long elapsedMs = timer.stop();\r\n System.err.println(\"numFeatures: orig1=\" + oldNumFeatures1 + \", orig2=\" + oldNumFeatures2 + \", combined=\"\r\n + numFeatures);\r\n System.err\r\n .println(\"numWeights: orig1=\" + oldNumWeights1 + \", orig2=\" + oldNumWeights2 + \", combined=\" + numWeights);\r\n System.err.println(\"Time to combine CRFClassifier: \" + Timing.toSecondsString(elapsedMs) + \" seconds\");\r\n }",
"String getFacetParamKey(String facet) {\n\n I_CmsSearchControllerFacetField fieldFacet = m_result.getController().getFieldFacets().getFieldFacetController().get(\n facet);\n if (fieldFacet != null) {\n return fieldFacet.getConfig().getParamKey();\n }\n I_CmsSearchControllerFacetRange rangeFacet = m_result.getController().getRangeFacets().getRangeFacetController().get(\n facet);\n if (rangeFacet != null) {\n return rangeFacet.getConfig().getParamKey();\n }\n I_CmsSearchControllerFacetQuery queryFacet = m_result.getController().getQueryFacet();\n if ((queryFacet != null) && queryFacet.getConfig().getName().equals(facet)) {\n return queryFacet.getConfig().getParamKey();\n }\n\n // Facet did not exist\n LOG.warn(Messages.get().getBundle().key(Messages.LOG_FACET_NOT_CONFIGURED_1, facet), new Throwable());\n\n return null;\n }",
"static <K, V> PageMetadata<K, V> mergeTokenAndQueryParameters(String paginationToken, final\n ViewQueryParameters<K, V> initialParameters) {\n\n // Decode the base64 token into JSON\n String json = new String(Base64.decodeBase64(paginationToken), Charset.forName(\"UTF-8\"));\n\n // Get a suitable Gson, we need any adapter registered for the K key type\n Gson paginationTokenGson = getGsonWithKeyAdapter(initialParameters);\n\n // Deserialize the pagination token JSON, using the appropriate K, V types\n PaginationToken token = paginationTokenGson.fromJson(json, PaginationToken.class);\n\n // Create new query parameters using the initial ViewQueryParameters as a starting point.\n ViewQueryParameters<K, V> tokenPageParameters = initialParameters.copy();\n\n // Merge the values from the token into the new query parameters\n tokenPageParameters.descending = token.descending;\n tokenPageParameters.endkey = token.endkey;\n tokenPageParameters.endkey_docid = token.endkey_docid;\n tokenPageParameters.inclusive_end = token.inclusive_end;\n tokenPageParameters.startkey = token.startkey;\n tokenPageParameters.startkey_docid = token.startkey_docid;\n\n return new PageMetadata<K, V>(token.direction, token\n .pageNumber, tokenPageParameters);\n }",
"public static base_response add(nitro_service client, sslaction resource) throws Exception {\n\t\tsslaction addresource = new sslaction();\n\t\taddresource.name = resource.name;\n\t\taddresource.clientauth = resource.clientauth;\n\t\taddresource.clientcert = resource.clientcert;\n\t\taddresource.certheader = resource.certheader;\n\t\taddresource.clientcertserialnumber = resource.clientcertserialnumber;\n\t\taddresource.certserialheader = resource.certserialheader;\n\t\taddresource.clientcertsubject = resource.clientcertsubject;\n\t\taddresource.certsubjectheader = resource.certsubjectheader;\n\t\taddresource.clientcerthash = resource.clientcerthash;\n\t\taddresource.certhashheader = resource.certhashheader;\n\t\taddresource.clientcertissuer = resource.clientcertissuer;\n\t\taddresource.certissuerheader = resource.certissuerheader;\n\t\taddresource.sessionid = resource.sessionid;\n\t\taddresource.sessionidheader = resource.sessionidheader;\n\t\taddresource.cipher = resource.cipher;\n\t\taddresource.cipherheader = resource.cipherheader;\n\t\taddresource.clientcertnotbefore = resource.clientcertnotbefore;\n\t\taddresource.certnotbeforeheader = resource.certnotbeforeheader;\n\t\taddresource.clientcertnotafter = resource.clientcertnotafter;\n\t\taddresource.certnotafterheader = resource.certnotafterheader;\n\t\taddresource.owasupport = resource.owasupport;\n\t\treturn addresource.add_resource(client);\n\t}",
"private static List<String> parseModifiers(int modifiers) {\n List<String> result = new ArrayList<String>();\n if (Modifier.isPrivate(modifiers)) {\n result.add(\"private\");\n }\n if (Modifier.isProtected(modifiers)) {\n result.add(\"protected\");\n }\n if (Modifier.isPublic(modifiers)) {\n result.add(\"public\");\n }\n if (Modifier.isAbstract(modifiers)) {\n result.add(\"abstract\");\n }\n if (Modifier.isFinal(modifiers)) {\n result.add(\"final\");\n }\n if (Modifier.isNative(modifiers)) {\n result.add(\"native\");\n }\n if (Modifier.isStatic(modifiers)) {\n result.add(\"static\");\n }\n if (Modifier.isStrict(modifiers)) {\n result.add(\"strict\");\n }\n if (Modifier.isSynchronized(modifiers)) {\n result.add(\"synchronized\");\n }\n if (Modifier.isTransient(modifiers)) {\n result.add(\"transient\");\n }\n if (Modifier.isVolatile(modifiers)) {\n result.add(\"volatile\");\n }\n if (Modifier.isInterface(modifiers)) {\n result.add(\"interface\");\n }\n return result;\n }",
"public static String getByteArrayDataAsString(String contentEncoding, byte[] bytes) {\n ByteArrayOutputStream byteout = null;\n if (contentEncoding != null &&\n contentEncoding.equals(\"gzip\")) {\n // GZIP\n ByteArrayInputStream bytein = null;\n GZIPInputStream zis = null;\n try {\n bytein = new ByteArrayInputStream(bytes);\n zis = new GZIPInputStream(bytein);\n byteout = new ByteArrayOutputStream();\n\n int res = 0;\n byte buf[] = new byte[1024];\n while (res >= 0) {\n res = zis.read(buf, 0, buf.length);\n if (res > 0) {\n byteout.write(buf, 0, res);\n }\n }\n\n zis.close();\n bytein.close();\n byteout.close();\n return byteout.toString();\n } catch (Exception e) {\n // No action to take\n }\n } else if (contentEncoding != null &&\n contentEncoding.equals(\"deflate\")) {\n try {\n // DEFLATE\n byte[] buffer = new byte[1024];\n Inflater decompresser = new Inflater();\n byteout = new ByteArrayOutputStream();\n decompresser.setInput(bytes);\n while (!decompresser.finished()) {\n int count = decompresser.inflate(buffer);\n byteout.write(buffer, 0, count);\n }\n byteout.close();\n decompresser.end();\n\n return byteout.toString();\n } catch (Exception e) {\n // No action to take\n }\n }\n\n return new String(bytes);\n }",
"private Duration getDuration(String value)\n {\n Duration result = null;\n\n if (value != null && value.length() != 0)\n {\n double seconds = getLong(value);\n double hours = seconds / (60 * 60);\n double days = hours / 8;\n\n if (days < 1)\n {\n result = Duration.getInstance(hours, TimeUnit.HOURS);\n }\n else\n {\n double durationDays = hours / 8;\n result = Duration.getInstance(durationDays, TimeUnit.DAYS);\n }\n }\n\n return (result);\n }",
"public String addClassification(String classificationType) {\n Metadata metadata = new Metadata().add(Metadata.CLASSIFICATION_KEY, classificationType);\n Metadata classification = this.createMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY,\n \"enterprise\", metadata);\n\n return classification.getString(Metadata.CLASSIFICATION_KEY);\n }"
] |
Use this API to fetch crvserver_policymap_binding resources of given name . | [
"public static crvserver_policymap_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcrvserver_policymap_binding obj = new crvserver_policymap_binding();\n\t\tobj.set_name(name);\n\t\tcrvserver_policymap_binding response[] = (crvserver_policymap_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"public static base_responses delete(nitro_service client, String Dnssuffix[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (Dnssuffix != null && Dnssuffix.length > 0) {\n\t\t\tdnssuffix deleteresources[] = new dnssuffix[Dnssuffix.length];\n\t\t\tfor (int i=0;i<Dnssuffix.length;i++){\n\t\t\t\tdeleteresources[i] = new dnssuffix();\n\t\t\t\tdeleteresources[i].Dnssuffix = Dnssuffix[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"public void close()\t{\n\t\tif (watchdog != null) {\n\t\t\twatchdog.cancel();\n\t\t\twatchdog = null;\n\t\t}\n\t\t\n\t\tdisconnect();\n\t\t\n\t\t// clear nodes collection and send queue\n\t\tfor (Object listener : this.zwaveEventListeners.toArray()) {\n\t\t\tif (!(listener instanceof ZWaveNode))\n\t\t\t\tcontinue;\n\t\t\t\n\t\t\tthis.zwaveEventListeners.remove(listener);\n\t\t}\n\t\t\n\t\tthis.zwaveNodes.clear();\n\t\tthis.sendQueue.clear();\n\t\t\n\t\tlogger.info(\"Stopped Z-Wave controller\");\n\t}",
"public CollectionRequest<Task> findByTag(String tag) {\n \n String path = String.format(\"/tags/%s/tasks\", tag);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }",
"private void precheckStateAllNull() throws IllegalStateException {\n if ((doubleValue != null) || (doubleArray != null)\n || (longValue != null) || (longArray != null)\n || (stringValue != null) || (stringArray != null)\n || (map != null)) {\n throw new IllegalStateException(\"Expected all properties to be empty: \" + this);\n }\n }",
"public Date getStartDate()\n {\n Date result = (Date) getCachedValue(ProjectField.START_DATE);\n if (result == null)\n {\n result = getParentFile().getStartDate();\n }\n return (result);\n }",
"public static String getDateTimeStrStandard(Date d) {\n if (d == null)\n return \"\";\n\n if (d.getTime() == 0L)\n return \"Never\";\n\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy.MM.dd.HH.mm.ss.SSSZ\");\n\n return sdf.format(d);\n }",
"public DescriptorRepository readDescriptorRepository(InputStream inst)\r\n {\r\n try\r\n {\r\n RepositoryPersistor persistor = new RepositoryPersistor();\r\n return persistor.readDescriptorRepository(inst);\r\n }\r\n catch (Exception e)\r\n {\r\n throw new MetadataException(\"Can not read repository \" + inst, e);\r\n }\r\n }",
"public static boolean setCustomRequestForDefaultClient(String profileName, String pathName, String customData) {\n try {\n return setCustomForDefaultClient(profileName, pathName, false, customData);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }",
"public final void setDefaultStyle(final Map<String, Style> defaultStyle) {\n this.defaultStyle = new HashMap<>(defaultStyle.size());\n for (Map.Entry<String, Style> entry: defaultStyle.entrySet()) {\n String normalizedName = GEOMETRY_NAME_ALIASES.get(entry.getKey().toLowerCase());\n\n if (normalizedName == null) {\n normalizedName = entry.getKey().toLowerCase();\n }\n\n this.defaultStyle.put(normalizedName, entry.getValue());\n }\n }"
] |
Remove script for a given ID
@param id ID of script
@throws Exception exception | [
"public void removeScript(int id) throws Exception {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = SQLService.getInstance().getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_SCRIPT +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, id);\n statement.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }"
] | [
"public void setDates(SortedSet<Date> dates) {\n\n if (!m_model.getIndividualDates().equals(dates)) {\n m_model.setIndividualDates(dates);\n onValueChange();\n }\n\n }",
"public BoxFolder.Info restoreFolder(String folderID) {\n URL url = RESTORE_FOLDER_URL_TEMPLATE.build(this.api.getBaseURL(), folderID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"POST\");\n JsonObject requestJSON = new JsonObject()\n .add(\"\", \"\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxFolder restoredFolder = new BoxFolder(this.api, responseJSON.get(\"id\").asString());\n return restoredFolder.new Info(responseJSON);\n }",
"private void addFoldersToSearchIn(final List<String> folders) {\n\n if (null == folders) {\n return;\n }\n\n for (String folder : folders) {\n if (!CmsResource.isFolder(folder)) {\n folder += \"/\";\n }\n\n m_foldersToSearchIn.add(folder);\n }\n }",
"@Override\n public final float getFloat(final int i) {\n double val = this.array.optDouble(i, Double.MAX_VALUE);\n if (val == Double.MAX_VALUE) {\n throw new ObjectMissingException(this, \"[\" + i + \"]\");\n }\n return (float) val;\n }",
"public static Boolean assertTrue(Boolean value, String message) {\n if (!Boolean.valueOf(value))\n throw new IllegalStateException(message);\n\n return value;\n }",
"public static synchronized void clearDaoCache() {\n\t\tif (classMap != null) {\n\t\t\tclassMap.clear();\n\t\t\tclassMap = null;\n\t\t}\n\t\tif (tableConfigMap != null) {\n\t\t\ttableConfigMap.clear();\n\t\t\ttableConfigMap = null;\n\t\t}\n\t}",
"public static <E> E parse(InputStream is, ParameterizedType<E> jsonObjectType) throws IOException {\n return mapperFor(jsonObjectType).parse(is);\n }",
"public static String rgb(int r, int g, int b) {\n if (r < -100 || r > 100) {\n throw new IllegalArgumentException(\"Red value must be between -100 and 100, inclusive.\");\n }\n if (g < -100 || g > 100) {\n throw new IllegalArgumentException(\"Green value must be between -100 and 100, inclusive.\");\n }\n if (b < -100 || b > 100) {\n throw new IllegalArgumentException(\"Blue value must be between -100 and 100, inclusive.\");\n }\n return FILTER_RGB + \"(\" + r + \",\" + g + \",\" + b + \")\";\n }",
"@Override\n public final Float optFloat(final String key, final Float defaultValue) {\n Float result = optFloat(key);\n return result == null ? defaultValue : result;\n }"
] |
a small static helper to set the image from the imageHolder nullSave to the imageView
@param imageHolder
@param imageView
@param tag used to identify imageViews and define different placeholders
@return true if an image was set | [
"public static boolean applyTo(ImageHolder imageHolder, ImageView imageView, String tag) {\n if (imageHolder != null && imageView != null) {\n return imageHolder.applyTo(imageView, tag);\n }\n return false;\n }"
] | [
"public ProjectCalendarException getException(Date date)\n {\n ProjectCalendarException exception = null;\n\n // We're working with expanded exceptions, which includes any recurring exceptions\n // expanded into individual entries.\n populateExpandedExceptions();\n if (!m_expandedExceptions.isEmpty())\n {\n sortExceptions();\n\n int low = 0;\n int high = m_expandedExceptions.size() - 1;\n long targetDate = date.getTime();\n\n while (low <= high)\n {\n int mid = (low + high) >>> 1;\n ProjectCalendarException midVal = m_expandedExceptions.get(mid);\n int cmp = 0 - DateHelper.compare(midVal.getFromDate(), midVal.getToDate(), targetDate);\n\n if (cmp < 0)\n {\n low = mid + 1;\n }\n else\n {\n if (cmp > 0)\n {\n high = mid - 1;\n }\n else\n {\n exception = midVal;\n break;\n }\n }\n }\n }\n\n if (exception == null && getParent() != null)\n {\n // Check base calendar as well for an exception.\n exception = getParent().getException(date);\n }\n return (exception);\n }",
"private void populateDefaultData(FieldItem[] defaultData)\n {\n for (FieldItem item : defaultData)\n {\n m_map.put(item.getType(), item);\n }\n }",
"public static int findLastIndexOf(Object self, int startIndex, Closure closure) {\n int result = -1;\n int i = 0;\n BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);\n for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); i++) {\n Object value = iter.next();\n if (i < startIndex) {\n continue;\n }\n if (bcw.call(value)) {\n result = i;\n }\n }\n return result;\n }",
"@Override\n\tpublic boolean addAll(Collection<? extends T> collection) {\n\t\tboolean changed = false;\n\t\tfor (T data : collection) {\n\t\t\ttry {\n\t\t\t\tif (addElement(data)) {\n\t\t\t\t\tchanged = true;\n\t\t\t\t}\n\t\t\t} catch (SQLException e) {\n\t\t\t\tthrow new IllegalStateException(\"Could not create data elements in dao\", e);\n\t\t\t}\n\t\t}\n\t\treturn changed;\n\t}",
"public int compareTo(WordTag wordTag) { \r\n int first = (word != null ? word().compareTo(wordTag.word()) : 0);\r\n if(first != 0)\r\n return first;\r\n else {\r\n if (tag() == null) {\r\n if (wordTag.tag() == null)\r\n return 0;\r\n else\r\n return -1;\r\n }\r\n return tag().compareTo(wordTag.tag());\r\n }\r\n }",
"public static boolean isBadXmlCharacter(char c) {\n boolean cDataCharacter = c < '\\u0020' && c != '\\t' && c != '\\r' && c != '\\n';\n cDataCharacter |= (c >= '\\uD800' && c < '\\uE000');\n cDataCharacter |= (c == '\\uFFFE' || c == '\\uFFFF');\n return cDataCharacter;\n }",
"private static <R> RowKey buildRowKey(AssociationKey associationKey, R row, AssociationRowAccessor<R> accessor) {\n\t\tString[] columnNames = associationKey.getMetadata().getRowKeyColumnNames();\n\t\tObject[] columnValues = new Object[columnNames.length];\n\n\t\tfor ( int i = 0; i < columnNames.length; i++ ) {\n\t\t\tString columnName = columnNames[i];\n\t\t\tcolumnValues[i] = associationKey.getMetadata().isKeyColumn( columnName ) ? associationKey.getColumnValue( columnName ) : accessor.get( row, columnName );\n\t\t}\n\n\t\treturn new RowKey( columnNames, columnValues );\n\t}",
"public synchronized void hide() {\n if (focusedQuad != null) {\n\n mDefocusAnimationFactory.create(focusedQuad)\n .setRequestLayoutOnTargetChange(false)\n .start().finish();\n\n focusedQuad = null;\n }\n Log.d(Log.SUBSYSTEM.WIDGET, TAG, \"hide Picker!\");\n }",
"protected Object getObjectFromResultSet() throws PersistenceBrokerException\r\n {\r\n\r\n try\r\n {\r\n // if all primitive attributes of the object are contained in the ResultSet\r\n // the fast direct mapping can be used\r\n return super.getObjectFromResultSet();\r\n }\r\n // if the full loading failed we assume that at least PK attributes are contained\r\n // in the ResultSet and perform a slower Identity based loading...\r\n // This may of course also fail and can throw another PersistenceBrokerException\r\n catch (PersistenceBrokerException e)\r\n {\r\n Identity oid = getIdentityFromResultSet();\r\n return getBroker().getObjectByIdentity(oid);\r\n }\r\n\r\n }"
] |
Get the processor graph to use for executing all the processors for the template.
@return the processor graph. | [
"public final ProcessorDependencyGraph getProcessorGraph() {\n if (this.processorGraph == null) {\n synchronized (this) {\n if (this.processorGraph == null) {\n final Map<String, Class<?>> attcls = new HashMap<>();\n for (Map.Entry<String, Attribute> attribute: this.attributes.entrySet()) {\n attcls.put(attribute.getKey(), attribute.getValue().getValueType());\n }\n this.processorGraph = this.processorGraphFactory.build(this.processors, attcls);\n }\n }\n }\n return this.processorGraph;\n }"
] | [
"private Map<String, String> mergeItem(\r\n String item,\r\n Map<String, String> localeValues,\r\n Map<String, String> resultLocaleValues) {\r\n\r\n if (resultLocaleValues.get(item) != null) {\r\n if (localeValues.get(item) != null) {\r\n localeValues.put(item, localeValues.get(item) + \" \" + resultLocaleValues.get(item));\r\n } else {\r\n localeValues.put(item, resultLocaleValues.get(item));\r\n }\r\n }\r\n\r\n return localeValues;\r\n }",
"public static boolean isTemplatePath(String string) {\n int sz = string.length();\n if (sz == 0) {\n return true;\n }\n for (int i = 0; i < sz; ++i) {\n char c = string.charAt(i);\n switch (c) {\n case ' ':\n case '\\t':\n case '\\b':\n case '<':\n case '>':\n case '(':\n case ')':\n case '[':\n case ']':\n case '{':\n case '}':\n case '!':\n case '@':\n case '#':\n case '*':\n case '?':\n case '%':\n case '|':\n case ',':\n case ':':\n case ';':\n case '^':\n case '&':\n return false;\n }\n }\n return true;\n }",
"private void recordRollbackLoader(final String patchId, PatchableTarget.TargetInfo target) {\n // setup the content loader paths\n final DirectoryStructure structure = target.getDirectoryStructure();\n final InstalledImage image = structure.getInstalledImage();\n final File historyDir = image.getPatchHistoryDir(patchId);\n final File miscRoot = new File(historyDir, PatchContentLoader.MISC);\n final File modulesRoot = structure.getModulePatchDirectory(patchId);\n final File bundlesRoot = structure.getBundlesPatchDirectory(patchId);\n final PatchContentLoader loader = PatchContentLoader.create(miscRoot, bundlesRoot, modulesRoot);\n //\n recordContentLoader(patchId, loader);\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 static java.util.Date newDateTime() {\n return new java.util.Date((System.currentTimeMillis() / SECOND_MILLIS) * SECOND_MILLIS);\n }",
"public Date getFinishDate()\n {\n Date finishDate = null;\n\n for (Task task : m_tasks)\n {\n //\n // If a hidden \"summary\" task is present we ignore it\n //\n if (NumberHelper.getInt(task.getUniqueID()) == 0)\n {\n continue;\n }\n\n //\n // Select the actual or forecast start date\n //\n Date taskFinishDate;\n taskFinishDate = task.getActualFinish();\n if (taskFinishDate == null)\n {\n taskFinishDate = task.getFinish();\n }\n\n if (taskFinishDate != null)\n {\n if (finishDate == null)\n {\n finishDate = taskFinishDate;\n }\n else\n {\n if (taskFinishDate.getTime() > finishDate.getTime())\n {\n finishDate = taskFinishDate;\n }\n }\n }\n }\n\n return (finishDate);\n }",
"private String getNotes(Row row)\n {\n String notes = row.getString(\"NOTET\");\n if (notes != null)\n {\n if (notes.isEmpty())\n {\n notes = null;\n }\n else\n {\n if (notes.indexOf(LINE_BREAK) != -1)\n {\n notes = notes.replace(LINE_BREAK, \"\\n\");\n }\n }\n }\n return notes;\n }",
"public static String toSafeFileName(String name) {\n int size = name.length();\n StringBuilder builder = new StringBuilder(size * 2);\n for (int i = 0; i < size; i++) {\n char c = name.charAt(i);\n boolean valid = c >= 'a' && c <= 'z';\n valid = valid || (c >= 'A' && c <= 'Z');\n valid = valid || (c >= '0' && c <= '9');\n valid = valid || (c == '_') || (c == '-') || (c == '.');\n\n if (valid) {\n builder.append(c);\n } else {\n // Encode the character using hex notation\n builder.append('x');\n builder.append(Integer.toHexString(i));\n }\n }\n return builder.toString();\n }",
"public BoxFileUploadSessionPartList listParts(int offset, int limit) {\n URL listPartsURL = this.sessionInfo.getSessionEndpoints().getListPartsEndpoint();\n URLTemplate template = new URLTemplate(listPartsURL.toString());\n\n QueryStringBuilder builder = new QueryStringBuilder();\n builder.appendParam(OFFSET_QUERY_STRING, offset);\n String queryString = builder.appendParam(LIMIT_QUERY_STRING, limit).toString();\n\n //Template is initalized with the full URL. So empty string for the path.\n URL url = template.buildWithQuery(\"\", queryString);\n\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, HttpMethod.GET);\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n return new BoxFileUploadSessionPartList(jsonObject);\n }"
] |
Create a HttpComponents HttpUriRequest object for the given HTTP method and URI specification.
@param httpMethod the HTTP method
@param uri the URI
@return the HttpComponents HttpUriRequest object | [
"protected HttpUriRequest createHttpRequest(HttpMethod httpMethod, URI uri) {\n\t\tswitch (httpMethod) {\n\t\t\tcase GET:\n\t\t\t\treturn new HttpGet(uri);\n\t\t\tcase DELETE:\n\t\t\t\treturn new HttpDelete(uri);\n\t\t\tcase HEAD:\n\t\t\t\treturn new HttpHead(uri);\n\t\t\tcase OPTIONS:\n\t\t\t\treturn new HttpOptions(uri);\n\t\t\tcase POST:\n\t\t\t\treturn new HttpPost(uri);\n\t\t\tcase PUT:\n\t\t\t\treturn new HttpPut(uri);\n\t\t\tcase TRACE:\n\t\t\t\treturn new HttpTrace(uri);\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid HTTP method: \" + httpMethod);\n\t\t}\n\t}"
] | [
"public Object getRealKey()\r\n {\r\n if(keyRealSubject != null)\r\n {\r\n return keyRealSubject;\r\n }\r\n else\r\n {\r\n TransactionExt tx = getTransaction();\r\n\r\n if((tx != null) && tx.isOpen())\r\n {\r\n prepareKeyRealSubject(tx.getBroker());\r\n }\r\n else\r\n {\r\n if(getPBKey() != null)\r\n {\r\n PBCapsule capsule = new PBCapsule(getPBKey(), null);\r\n\r\n try\r\n {\r\n prepareKeyRealSubject(capsule.getBroker());\r\n }\r\n finally\r\n {\r\n capsule.destroy();\r\n }\r\n }\r\n else\r\n {\r\n getLog().warn(\"No tx, no PBKey - can't materialise key with Identity \" + getKeyOid());\r\n }\r\n }\r\n }\r\n return keyRealSubject;\r\n }",
"protected boolean shouldApplyThisRuleTo(ClassNode classNode) {\r\n // TODO Consider caching applyTo, doNotApplyTo and associated WildcardPatterns\r\n boolean shouldApply = true;\r\n\r\n String applyTo = getApplyToClassNames();\r\n String doNotApplyTo = getDoNotApplyToClassNames();\r\n\r\n if (applyTo != null && applyTo.length() > 0) {\r\n WildcardPattern pattern = new WildcardPattern(applyTo, true);\r\n shouldApply = pattern.matches(classNode.getNameWithoutPackage()) || pattern.matches(classNode.getName());\r\n }\r\n\r\n if (shouldApply && doNotApplyTo != null && doNotApplyTo.length() > 0) {\r\n WildcardPattern pattern = new WildcardPattern(doNotApplyTo, true);\r\n shouldApply = !pattern.matches(classNode.getNameWithoutPackage()) && !pattern.matches(classNode.getName());\r\n }\r\n\r\n return shouldApply;\r\n }",
"private List<Rule> getStyleRules(final String styleProperty) {\n final List<Rule> styleRules = new ArrayList<>(this.json.size());\n\n for (Iterator<String> iterator = this.json.keys(); iterator.hasNext(); ) {\n String styleKey = iterator.next();\n if (styleKey.equals(JSON_STYLE_PROPERTY) ||\n styleKey.equals(MapfishStyleParserPlugin.JSON_VERSION)) {\n continue;\n }\n PJsonObject styleJson = this.json.getJSONObject(styleKey);\n final List<Rule> currentRules = createStyleRule(styleKey, styleJson, styleProperty);\n for (Rule currentRule: currentRules) {\n if (currentRule != null) {\n styleRules.add(currentRule);\n }\n }\n }\n\n return styleRules;\n }",
"public static void acceptsDir(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_D, OPT_DIR), \"directory path for input/output\")\n .withRequiredArg()\n .describedAs(\"dir-path\")\n .ofType(String.class);\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}",
"public static void findSomeStringProperties(ApiConnection connection)\n\t\t\tthrows MediaWikiApiErrorException, IOException {\n\t\tWikibaseDataFetcher wbdf = new WikibaseDataFetcher(connection, siteIri);\n\t\twbdf.getFilter().excludeAllProperties();\n\t\twbdf.getFilter().setLanguageFilter(Collections.singleton(\"en\"));\n\n\t\tArrayList<PropertyIdValue> stringProperties = new ArrayList<>();\n\n\t\tSystem.out\n\t\t\t\t.println(\"*** Trying to find string properties for the example ... \");\n\t\tint propertyNumber = 1;\n\t\twhile (stringProperties.size() < 5) {\n\t\t\tArrayList<String> fetchProperties = new ArrayList<>();\n\t\t\tfor (int i = propertyNumber; i < propertyNumber + 10; i++) {\n\t\t\t\tfetchProperties.add(\"P\" + i);\n\t\t\t}\n\t\t\tpropertyNumber += 10;\n\t\t\tMap<String, EntityDocument> results = wbdf\n\t\t\t\t\t.getEntityDocuments(fetchProperties);\n\t\t\tfor (EntityDocument ed : results.values()) {\n\t\t\t\tPropertyDocument pd = (PropertyDocument) ed;\n\t\t\t\tif (DatatypeIdValue.DT_STRING.equals(pd.getDatatype().getIri())\n\t\t\t\t\t\t&& pd.getLabels().containsKey(\"en\")) {\n\t\t\t\t\tstringProperties.add(pd.getEntityId());\n\t\t\t\t\tSystem.out.println(\"* Found string property \"\n\t\t\t\t\t\t\t+ pd.getEntityId().getId() + \" (\"\n\t\t\t\t\t\t\t+ pd.getLabels().get(\"en\") + \")\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tstringProperty1 = stringProperties.get(0);\n\t\tstringProperty2 = stringProperties.get(1);\n\t\tstringProperty3 = stringProperties.get(2);\n\t\tstringProperty4 = stringProperties.get(3);\n\t\tstringProperty5 = stringProperties.get(4);\n\n\t\tSystem.out.println(\"*** Done.\");\n\t}",
"public void 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 }",
"private Resource readResource(net.sf.mpxj.phoenix.schema.Project.Storepoints.Storepoint.Resources.Resource phoenixResource)\n {\n Resource mpxjResource = m_projectFile.addResource();\n\n TimeUnit rateUnits = phoenixResource.getMonetarybase();\n if (rateUnits == null)\n {\n rateUnits = TimeUnit.HOURS;\n }\n\n // phoenixResource.getMaximum()\n mpxjResource.setCostPerUse(phoenixResource.getMonetarycostperuse());\n mpxjResource.setStandardRate(new Rate(phoenixResource.getMonetaryrate(), rateUnits));\n mpxjResource.setStandardRateUnits(rateUnits);\n mpxjResource.setName(phoenixResource.getName());\n mpxjResource.setType(phoenixResource.getType());\n mpxjResource.setMaterialLabel(phoenixResource.getUnitslabel());\n //phoenixResource.getUnitsperbase()\n mpxjResource.setGUID(phoenixResource.getUuid());\n\n m_eventManager.fireResourceReadEvent(mpxjResource);\n\n return mpxjResource;\n }",
"public List<com.groupon.odo.proxylib.models.Method> getMethodsNotInGroup(int groupId) throws Exception {\n List<com.groupon.odo.proxylib.models.Method> allMethods = getAllMethods();\n List<com.groupon.odo.proxylib.models.Method> methodsNotInGroup = new ArrayList<com.groupon.odo.proxylib.models.Method>();\n List<com.groupon.odo.proxylib.models.Method> methodsInGroup = editService.getMethodsFromGroupId(groupId, null);\n\n for (int i = 0; i < allMethods.size(); i++) {\n boolean add = true;\n String methodName = allMethods.get(i).getMethodName();\n String className = allMethods.get(i).getClassName();\n\n for (int j = 0; j < methodsInGroup.size(); j++) {\n if ((methodName.equals(methodsInGroup.get(j).getMethodName())) &&\n (className.equals(methodsInGroup.get(j).getClassName()))) {\n add = false;\n }\n }\n if (add) {\n methodsNotInGroup.add(allMethods.get(i));\n }\n }\n return methodsNotInGroup;\n }"
] |
Creates a new CRFDatum from the preprocessed allData format, given the
document number, position number, and a List of Object labels.
@return A new CRFDatum | [
"protected List<CRFDatum> extractDatumSequence(int[][][] allData, int beginPosition, int endPosition,\r\n List<IN> labeledWordInfos) {\r\n List<CRFDatum> result = new ArrayList<CRFDatum>();\r\n int beginContext = beginPosition - windowSize + 1;\r\n if (beginContext < 0) {\r\n beginContext = 0;\r\n }\r\n // for the beginning context, add some dummy datums with no features!\r\n // TODO: is there any better way to do this?\r\n for (int position = beginContext; position < beginPosition; position++) {\r\n List<Collection<String>> cliqueFeatures = new ArrayList<Collection<String>>();\r\n for (int i = 0; i < windowSize; i++) {\r\n // create a feature list\r\n cliqueFeatures.add(Collections.<String>emptyList());\r\n }\r\n CRFDatum<Collection<String>, String> datum = new CRFDatum<Collection<String>, String>(cliqueFeatures,\r\n labeledWordInfos.get(position).get(AnswerAnnotation.class));\r\n result.add(datum);\r\n }\r\n // now add the real datums\r\n for (int position = beginPosition; position <= endPosition; position++) {\r\n List<Collection<String>> cliqueFeatures = new ArrayList<Collection<String>>();\r\n for (int i = 0; i < windowSize; i++) {\r\n // create a feature list\r\n Collection<String> features = new ArrayList<String>();\r\n for (int j = 0; j < allData[position][i].length; j++) {\r\n features.add(featureIndex.get(allData[position][i][j]));\r\n }\r\n cliqueFeatures.add(features);\r\n }\r\n CRFDatum<Collection<String>,String> datum = new CRFDatum<Collection<String>,String>(cliqueFeatures,\r\n labeledWordInfos.get(position).get(AnswerAnnotation.class));\r\n result.add(datum);\r\n }\r\n return result;\r\n }"
] | [
"private List<Bucket> lookup(Record record) {\n List<Bucket> buckets = new ArrayList();\n for (Property p : config.getLookupProperties()) {\n String propname = p.getName();\n Collection<String> values = record.getValues(propname);\n if (values == null)\n continue;\n\n for (String value : values) {\n String[] tokens = StringUtils.split(value);\n for (int ix = 0; ix < tokens.length; ix++) {\n Bucket b = store.lookupToken(propname, tokens[ix]);\n if (b == null || b.records == null)\n continue;\n long[] ids = b.records;\n if (DEBUG)\n System.out.println(propname + \", \" + tokens[ix] + \": \" + b.nextfree + \" (\" + b.getScore() + \")\");\n buckets.add(b);\n }\n }\n }\n\n return buckets;\n }",
"public StandaloneCommandBuilder addSecurityProperty(final String key, final String value) {\n securityProperties.put(key, value);\n return this;\n }",
"public static base_responses delete(nitro_service client, String ipv6address[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (ipv6address != null && ipv6address.length > 0) {\n\t\t\tnsip6 deleteresources[] = new nsip6[ipv6address.length];\n\t\t\tfor (int i=0;i<ipv6address.length;i++){\n\t\t\t\tdeleteresources[i] = new nsip6();\n\t\t\t\tdeleteresources[i].ipv6address = ipv6address[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"public void writeNameValuePair(String name, long value) throws IOException\n {\n internalWriteNameValuePair(name, Long.toString(value));\n }",
"public void update(int number) {\n byte[] numberInBytes = new byte[ByteUtils.SIZE_OF_INT];\n ByteUtils.writeInt(numberInBytes, number, 0);\n update(numberInBytes);\n }",
"public DbModule getModule(final String moduleId) {\n final DbModule dbModule = repositoryHandler.getModule(moduleId);\n\n if (dbModule == null) {\n throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)\n .entity(\"Module \" + moduleId + \" does not exist.\").build());\n }\n\n return dbModule;\n }",
"public static Type[] getActualTypeArguments(Type type) {\n Type resolvedType = Types.getCanonicalType(type);\n if (resolvedType instanceof ParameterizedType) {\n return ((ParameterizedType) resolvedType).getActualTypeArguments();\n } else {\n return EMPTY_TYPES;\n }\n }",
"public static Iterable<BoxFileVersionRetention.Info> getRetentions(\n final BoxAPIConnection api, QueryFilter filter, String ... fields) {\n filter.addFields(fields);\n return new BoxResourceIterable<BoxFileVersionRetention.Info>(api,\n ALL_RETENTIONS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), filter.toString()),\n DEFAULT_LIMIT) {\n\n @Override\n protected BoxFileVersionRetention.Info factory(JsonObject jsonObject) {\n BoxFileVersionRetention retention = new BoxFileVersionRetention(api, jsonObject.get(\"id\").asString());\n return retention.new Info(jsonObject);\n }\n };\n }",
"private void serializeEPR(EndpointReferenceType wsAddr, Node parent) throws ServiceLocatorException {\n try {\n JAXBElement<EndpointReferenceType> ep =\n WSA_OBJECT_FACTORY.createEndpointReference(wsAddr);\n createMarshaller().marshal(ep, parent);\n } catch (JAXBException e) {\n if (LOG.isLoggable(Level.SEVERE)) {\n LOG.log(Level.SEVERE,\n \"Failed to serialize endpoint data\", e);\n }\n throw new ServiceLocatorException(\"Failed to serialize endpoint data\", e);\n }\n }"
] |
Check if a dependency matches the filters
@param dependency
@return boolean | [
"public boolean shouldBeInReport(final DbDependency dependency) {\n if(dependency == null){\n return false;\n }\n if(dependency.getTarget() == null){\n return false;\n }\n if(corporateFilter != null){\n if(!decorator.getShowThirdparty() && !corporateFilter.filter(dependency)){\n return false;\n }\n if(!decorator.getShowCorporate() && corporateFilter.filter(dependency)){\n return false;\n }\n }\n\n if(!scopeHandler.filter(dependency)){\n return false;\n }\n\n return true;\n }"
] | [
"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 }",
"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 base_responses add(nitro_service client, clusternodegroup resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tclusternodegroup addresources[] = new clusternodegroup[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new clusternodegroup();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].strict = resources[i].strict;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"@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 void mergeSameWork(LinkedList<TimephasedWork> list)\n {\n LinkedList<TimephasedWork> result = new LinkedList<TimephasedWork>();\n\n TimephasedWork previousAssignment = null;\n for (TimephasedWork assignment : list)\n {\n if (previousAssignment == null)\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n result.add(assignment);\n }\n else\n {\n Duration previousAssignmentWork = previousAssignment.getAmountPerDay();\n Duration assignmentWork = assignment.getTotalAmount();\n\n if (NumberHelper.equals(previousAssignmentWork.getDuration(), assignmentWork.getDuration(), 0.01))\n {\n Date assignmentStart = previousAssignment.getStart();\n Date assignmentFinish = assignment.getFinish();\n double total = previousAssignment.getTotalAmount().getDuration();\n total += assignmentWork.getDuration();\n Duration totalWork = Duration.getInstance(total, TimeUnit.MINUTES);\n\n TimephasedWork merged = new TimephasedWork();\n merged.setStart(assignmentStart);\n merged.setFinish(assignmentFinish);\n merged.setAmountPerDay(assignmentWork);\n merged.setTotalAmount(totalWork);\n\n result.removeLast();\n assignment = merged;\n }\n else\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n }\n result.add(assignment);\n }\n\n previousAssignment = assignment;\n }\n\n list.clear();\n list.addAll(result);\n }",
"public Task<Void> confirmUser(@NonNull final String token, @NonNull final String tokenId) {\n return dispatcher.dispatchTask(\n new Callable<Void>() {\n @Override\n public Void call() {\n confirmUserInternal(token, tokenId);\n return null;\n }\n });\n }",
"private void readRelationships()\n {\n for (MapRow row : getTable(\"CONTAB\"))\n {\n Task task1 = m_projectFile.getTaskByUniqueID(row.getInteger(\"TASK_ID_1\"));\n Task task2 = m_projectFile.getTaskByUniqueID(row.getInteger(\"TASK_ID_2\"));\n\n if (task1 != null && task2 != null)\n {\n RelationType type = row.getRelationType(\"TYPE\");\n Duration lag = row.getDuration(\"LAG\");\n Relation relation = task2.addPredecessor(task1, type, lag);\n m_eventManager.fireRelationReadEvent(relation);\n }\n }\n }",
"protected Date getPickerDate() {\n try {\n JsDate pickerDate = getPicker().get(\"select\").obj;\n return new Date((long) pickerDate.getTime());\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n }",
"@Override\n public Map<String, Set<String>> cleanObsoleteContent() {\n if(!readWrite) {\n return Collections.emptyMap();\n }\n Map<String, Set<String>> cleanedContents = new HashMap<>(2);\n cleanedContents.put(MARKED_CONTENT, new HashSet<>());\n cleanedContents.put(DELETED_CONTENT, new HashSet<>());\n synchronized (contentHashReferences) {\n for (ContentReference fsContent : listLocalContents()) {\n if (!readWrite) {\n return Collections.emptyMap();\n }\n if (!contentHashReferences.containsKey(fsContent.getHexHash())) { //We have no reference to this content\n if (markAsObsolete(fsContent)) {\n cleanedContents.get(DELETED_CONTENT).add(fsContent.getContentIdentifier());\n } else {\n cleanedContents.get(MARKED_CONTENT).add(fsContent.getContentIdentifier());\n }\n } else {\n obsoleteContents.remove(fsContent.getHexHash()); //Remove existing references from obsoleteContents\n }\n }\n }\n return cleanedContents;\n }"
] |
Gets the Topsoe divergence.
@param p P vector.
@param q Q vector.
@return The Topsoe divergence between p and q. | [
"public static double TopsoeDivergence(double[] p, double[] q) {\n double r = 0;\n for (int i = 0; i < p.length; i++) {\n if (p[i] != 0 && q[i] != 0) {\n double den = p[i] + q[i];\n r += p[i] * Math.log(2 * p[i] / den) + q[i] * Math.log(2 * q[i] / den);\n }\n }\n return r;\n }"
] | [
"public int[] getDefalutValuesArray() {\n int[] defaultValues = new int[5];\n\n defaultValues[0] = GLES20.GL_LINEAR_MIPMAP_NEAREST; // MIN FILTER\n defaultValues[1] = GLES20.GL_LINEAR; // MAG FILTER\n defaultValues[2] = 1; // ANISO FILTER\n defaultValues[3] = GLES20.GL_CLAMP_TO_EDGE; // WRAP S\n defaultValues[4] = GLES20.GL_CLAMP_TO_EDGE; // WRAP T\n\n return defaultValues;\n }",
"public static String paramMapToString(final Map<String, String[]> parameters) {\n\n final StringBuffer result = new StringBuffer();\n for (final String key : parameters.keySet()) {\n String[] values = parameters.get(key);\n if (null == values) {\n result.append(key).append('&');\n } else {\n for (final String value : parameters.get(key)) {\n result.append(key).append('=').append(CmsEncoder.encode(value)).append('&');\n }\n }\n }\n // remove last '&'\n if (result.length() > 0) {\n result.setLength(result.length() - 1);\n }\n return result.toString();\n }",
"private JSONObject getConvertedResponseAsJson(SpellCheckResponse response) {\n\n if (null == response) {\n return null;\n }\n\n final JSONObject suggestions = new JSONObject();\n final Map<String, Suggestion> solrSuggestions = response.getSuggestionMap();\n\n // Add suggestions to the response\n for (final String key : solrSuggestions.keySet()) {\n\n // Indicator to ignore words that are erroneously marked as misspelled.\n boolean ignoreWord = false;\n\n // Suggestions that are in the form \"Xxxx\" -> \"xxxx\" should be ignored.\n if (Character.isUpperCase(key.codePointAt(0))) {\n final String lowercaseKey = key.toLowerCase();\n // If the suggestion map doesn't contain the lowercased word, ignore this entry.\n if (!solrSuggestions.containsKey(lowercaseKey)) {\n ignoreWord = true;\n }\n }\n\n if (!ignoreWord) {\n try {\n // Get suggestions as List\n final List<String> l = solrSuggestions.get(key).getAlternatives();\n suggestions.put(key, l);\n } catch (JSONException e) {\n LOG.debug(\"Exception while converting Solr spellcheckresponse to JSON. \", e);\n }\n }\n }\n\n return suggestions;\n }",
"@NotNull\n static MetaTreeImpl.Proto saveMetaTree(@NotNull final ITreeMutable metaTree,\n @NotNull final EnvironmentImpl env,\n @NotNull final ExpiredLoggableCollection expired) {\n final long newMetaTreeAddress = metaTree.save();\n final Log log = env.getLog();\n final int lastStructureId = env.getLastStructureId();\n final long dbRootAddress = log.write(DatabaseRoot.DATABASE_ROOT_TYPE, Loggable.NO_STRUCTURE_ID,\n DatabaseRoot.asByteIterable(newMetaTreeAddress, lastStructureId));\n expired.add(dbRootAddress, (int) (log.getWrittenHighAddress() - dbRootAddress));\n return new MetaTreeImpl.Proto(newMetaTreeAddress, dbRootAddress);\n }",
"public final void setValue(String value) {\n\n if ((null == value) || value.isEmpty()) {\n setDefaultValue();\n } else {\n try {\n tryToSetParsedValue(value);\n } catch (@SuppressWarnings(\"unused\") Exception e) {\n CmsDebugLog.consoleLog(\"Could not set invalid serial date value: \" + value);\n setDefaultValue();\n }\n }\n notifyOnValueChange();\n }",
"private RgbaColor withHsl(int index, float value) {\n float[] HSL = convertToHsl();\n HSL[index] = value;\n return RgbaColor.fromHsl(HSL);\n }",
"private boolean addDeploymentTypeBasedDependencies(ProjectModel projectModel, Pom modulePom)\n {\n if (projectModel.getProjectType() == null)\n return true;\n switch (projectModel.getProjectType()){\n case \"ear\":\n break;\n case \"war\":\n modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_SERVLET_31));\n break;\n case \"ejb\":\n modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_EJB_32));\n modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_CDI));\n modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_JAVAX_ANN));\n break;\n case \"ejb-client\":\n modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_EJB_CLIENT));\n break;\n }\n return false;\n }",
"public Set<String> rangeByScoreReverse(final ScoreRange scoreRange) {\n return doWithJedis(new JedisCallable<Set<String>>() {\n @Override\n public Set<String> call(Jedis jedis) {\n if (scoreRange.hasLimit()) {\n return jedis.zrevrangeByScore(getKey(), scoreRange.fromReverse(), scoreRange.toReverse(), scoreRange.offset(), scoreRange.count());\n } else {\n return jedis.zrevrangeByScore(getKey(), scoreRange.fromReverse(), scoreRange.toReverse());\n }\n }\n });\n }",
"public static JsonPatch generate(final JsonNode source, final JsonNode target, ReplaceMode replaceMode) {\n requireNonNull(source, \"source\");\n requireNonNull(target, \"target\");\n final DiffProcessor processor = new DiffProcessor(replaceMode, () -> unchangedValues(source, target));\n generateDiffs(processor, EMPTY_JSON_POINTER, source, target);\n return processor.getPatch();\n }"
] |
Add server redirect to a profile
@param region region
@param srcUrl source URL
@param destUrl destination URL
@param hostHeader host header
@param profileId profile ID
@param groupId group ID
@return ID of added ServerRedirect
@throws Exception exception | [
"public int addServerRedirect(String region, String srcUrl, String destUrl, String hostHeader, int profileId, int groupId) throws Exception {\n int serverId = -1;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\"INSERT INTO \" + Constants.DB_TABLE_SERVERS\n + \"(\" + Constants.SERVER_REDIRECT_REGION + \",\" +\n Constants.SERVER_REDIRECT_SRC_URL + \",\" +\n Constants.SERVER_REDIRECT_DEST_URL + \",\" +\n Constants.SERVER_REDIRECT_HOST_HEADER + \",\" +\n Constants.SERVER_REDIRECT_PROFILE_ID + \",\" +\n Constants.SERVER_REDIRECT_GROUP_ID + \")\"\n + \" VALUES (?, ?, ?, ?, ?, ?);\", PreparedStatement.RETURN_GENERATED_KEYS);\n statement.setString(1, region);\n statement.setString(2, srcUrl);\n statement.setString(3, destUrl);\n statement.setString(4, hostHeader);\n statement.setInt(5, profileId);\n statement.setInt(6, groupId);\n statement.executeUpdate();\n\n results = statement.getGeneratedKeys();\n\n if (results.next()) {\n serverId = results.getInt(1);\n } else {\n // something went wrong\n throw new Exception(\"Could not add path\");\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return serverId;\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 }",
"private void updateRemoveQ( int rowIndex ) {\n Qm.set(Q);\n Q.reshape(m_m,m_m, false);\n\n for( int i = 0; i < rowIndex; i++ ) {\n for( int j = 1; j < m; j++ ) {\n double sum = 0;\n for( int k = 0; k < m; k++ ) {\n sum += Qm.data[i*m+k]* U_tran.data[j*m+k];\n }\n Q.data[i*m_m+j-1] = sum;\n }\n }\n\n for( int i = rowIndex+1; i < m; i++ ) {\n for( int j = 1; j < m; j++ ) {\n double sum = 0;\n for( int k = 0; k < m; k++ ) {\n sum += Qm.data[i*m+k]* U_tran.data[j*m+k];\n }\n Q.data[(i-1)*m_m+j-1] = sum;\n }\n }\n }",
"public boolean checkSuffixes(String uri, String[] patterns) {\n\t\tfor (String pattern : patterns) {\n\t\t\tif (pattern.length() > 0) {\n\t\t\t\tif (uri.endsWith(pattern)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"public static Field read(DataInputStream is) throws IOException {\n final byte tag = is.readByte();\n final Field result;\n switch (tag) {\n case 0x0f:\n case 0x10:\n case 0x11:\n result = new NumberField(tag, is);\n break;\n\n case 0x14:\n result = new BinaryField(is);\n break;\n\n case 0x26:\n result = new StringField(is);\n break;\n\n default:\n throw new IOException(\"Unable to read a field with type tag \" + tag);\n }\n\n logger.debug(\"..received> {}\", result);\n return result;\n }",
"private void readCalendars()\n {\n Table cal = m_tables.get(\"CAL\");\n for (MapRow row : cal)\n {\n ProjectCalendar calendar = m_projectFile.addCalendar();\n m_calendarMap.put(row.getInteger(\"CALENDAR_ID\"), calendar);\n Integer[] days =\n {\n row.getInteger(\"SUNDAY_HOURS\"),\n row.getInteger(\"MONDAY_HOURS\"),\n row.getInteger(\"TUESDAY_HOURS\"),\n row.getInteger(\"WEDNESDAY_HOURS\"),\n row.getInteger(\"THURSDAY_HOURS\"),\n row.getInteger(\"FRIDAY_HOURS\"),\n row.getInteger(\"SATURDAY_HOURS\")\n };\n\n calendar.setName(row.getString(\"NAME\"));\n readHours(calendar, Day.SUNDAY, days[0]);\n readHours(calendar, Day.MONDAY, days[1]);\n readHours(calendar, Day.TUESDAY, days[2]);\n readHours(calendar, Day.WEDNESDAY, days[3]);\n readHours(calendar, Day.THURSDAY, days[4]);\n readHours(calendar, Day.FRIDAY, days[5]);\n readHours(calendar, Day.SATURDAY, days[6]);\n\n int workingDaysPerWeek = 0;\n for (Day day : Day.values())\n {\n if (calendar.isWorkingDay(day))\n {\n ++workingDaysPerWeek;\n }\n }\n\n Integer workingHours = null;\n for (int index = 0; index < 7; index++)\n {\n if (days[index].intValue() != 0)\n {\n workingHours = days[index];\n break;\n }\n }\n\n if (workingHours != null)\n {\n int workingHoursPerDay = countHours(workingHours);\n int minutesPerDay = workingHoursPerDay * 60;\n int minutesPerWeek = minutesPerDay * workingDaysPerWeek;\n int minutesPerMonth = 4 * minutesPerWeek;\n int minutesPerYear = 52 * minutesPerWeek;\n\n calendar.setMinutesPerDay(Integer.valueOf(minutesPerDay));\n calendar.setMinutesPerWeek(Integer.valueOf(minutesPerWeek));\n calendar.setMinutesPerMonth(Integer.valueOf(minutesPerMonth));\n calendar.setMinutesPerYear(Integer.valueOf(minutesPerYear));\n }\n }\n }",
"public void addRowAfter(I_CmsEditableGroupRow row) {\n\n int index = m_container.getComponentIndex(row);\n if (index >= 0) {\n Component component = m_newComponentFactory.get();\n I_CmsEditableGroupRow newRow = m_rowBuilder.buildRow(this, component);\n m_container.addComponent(newRow, index + 1);\n }\n updatePlaceholder();\n updateButtonBars();\n updateGroupValidation();\n }",
"public void setShortAttribute(String name, Short value) {\n\t\tensureValue();\n\t\tAttribute attribute = new ShortAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetValue().getAllAttributes().put(name, attribute);\n\t}",
"final public void setRealOffset(Integer start, Integer end) {\n if ((start == null) || (end == null)) {\n // do nothing\n } else if (start > end) {\n throw new IllegalArgumentException(\n \"Start real offset after end real offset\");\n } else {\n tokenRealOffset = new MtasOffset(start, end);\n }\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<Symmetry454Date> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<Symmetry454Date>) super.localDateTime(temporal);\n }"
] |
Returns true if the addon depends on reporting. | [
"private boolean addonDependsOnReporting(Addon addon)\n {\n for (AddonDependency dep : addon.getDependencies())\n {\n if (dep.getDependency().equals(this.addon))\n {\n return true;\n }\n boolean subDep = addonDependsOnReporting(dep.getDependency());\n if (subDep)\n {\n return true;\n }\n }\n return false;\n }"
] | [
"public void removeDropPasteWorker(DropPasteWorkerInterface worker)\r\n {\r\n this.dropPasteWorkerSet.remove(worker);\r\n java.util.Iterator it = this.dropPasteWorkerSet.iterator();\r\n int newDefaultActions = 0;\r\n while (it.hasNext())\r\n newDefaultActions |= ((DropPasteWorkerInterface)it.next()).getAcceptableActions(defaultDropTarget.getComponent());\r\n defaultDropTarget.setDefaultActions(newDefaultActions);\r\n }",
"private Table getTable(String name)\n {\n Table table = m_tables.get(name);\n if (table == null)\n {\n table = EMPTY_TABLE;\n }\n return table;\n }",
"public PhotoList<Photo> getPhotos(String photosetId, Set<String> extras, int privacy_filter, int perPage, int page) throws FlickrException {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PHOTOS);\r\n\r\n parameters.put(\"photoset_id\", photosetId);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", String.valueOf(perPage));\r\n }\r\n\r\n if (page > 0) {\r\n parameters.put(\"page\", String.valueOf(page));\r\n }\r\n\r\n if (privacy_filter > 0) {\r\n parameters.put(\"privacy_filter\", \"\" + privacy_filter);\r\n }\r\n\r\n if (extras != null && !extras.isEmpty()) {\r\n parameters.put(Extras.KEY_EXTRAS, StringUtilities.join(extras, \",\"));\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element photoset = response.getPayload();\r\n NodeList photoElements = photoset.getElementsByTagName(\"photo\");\r\n photos.setPage(photoset.getAttribute(\"page\"));\r\n photos.setPages(photoset.getAttribute(\"pages\"));\r\n photos.setPerPage(photoset.getAttribute(\"per_page\"));\r\n photos.setTotal(photoset.getAttribute(\"total\"));\r\n\r\n for (int i = 0; i < photoElements.getLength(); i++) {\r\n Element photoElement = (Element) photoElements.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement, photoset));\r\n }\r\n\r\n return photos;\r\n }",
"public static long stopNamedTimer(String timerName, int todoFlags) {\n\t\treturn stopNamedTimer(timerName, todoFlags, Thread.currentThread()\n\t\t\t\t.getId());\n\t}",
"public String getWorkplaceLink(CmsObject cms, String resourceName, boolean forceSecure) {\n\n String result = substituteLinkForUnknownTarget(cms, resourceName, forceSecure);\n return appendServerPrefix(cms, result, resourceName, true);\n\n }",
"public static String dump(final int displayOffset, final byte[] data, final int offset, final int len)\n {\n StringBuilder sb = new StringBuilder();\n Formatter formatter = new Formatter(sb);\n StringBuilder ascii = new StringBuilder();\n\n int dataNdx = offset;\n final int maxDataNdx = offset + len;\n final int lines = (len + 16) / 16;\n for (int i = 0; i < lines; i++) {\n ascii.append(\" |\");\n formatter.format(\"%08x \", displayOffset + (i * 16));\n\n for (int j = 0; j < 16; j++) {\n if (dataNdx < maxDataNdx) {\n byte b = data[dataNdx++];\n formatter.format(\"%02x \", b);\n ascii.append((b > MIN_VISIBLE && b < MAX_VISIBLE) ? (char) b : ' ');\n }\n else {\n sb.append(\" \");\n }\n\n if (j == 7) {\n sb.append(' ');\n }\n }\n\n ascii.append('|');\n sb.append(ascii).append('\\n');\n ascii.setLength(0);\n }\n\n formatter.close();\n return sb.toString();\n }",
"public Map<String, String> getTitleLocale() {\n\n if (m_localeTitles == null) {\n m_localeTitles = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n public Object transform(Object inputLocale) {\n\n Locale locale = null;\n if (null != inputLocale) {\n if (inputLocale instanceof Locale) {\n locale = (Locale)inputLocale;\n } else if (inputLocale instanceof String) {\n try {\n locale = LocaleUtils.toLocale((String)inputLocale);\n } catch (IllegalArgumentException | NullPointerException e) {\n // do nothing, just go on without locale\n }\n }\n }\n return getLocaleSpecificTitle(locale);\n }\n\n });\n }\n return m_localeTitles;\n }",
"public X509Certificate getMappedCertificateForHostname(String hostname) throws CertificateParsingException, InvalidKeyException, CertificateExpiredException, CertificateNotYetValidException, SignatureException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException, UnrecoverableKeyException\n\t{\n\t\tString subject = getSubjectForHostname(hostname);\n\n\t\tString thumbprint = _subjectMap.get(subject);\n\n\t\tif(thumbprint == null) {\n\n\t\t\tKeyPair kp = getRSAKeyPair();\n\n\t\t\tX509Certificate newCert = CertificateCreator.generateStdSSLServerCertificate(kp.getPublic(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t getSigningCert(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t getSigningPrivateKey(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t subject);\n\n\t\t\taddCertAndPrivateKey(hostname, newCert, kp.getPrivate());\n\n\t\t\tthumbprint = ThumbprintUtil.getThumbprint(newCert);\n\n\t\t\t_subjectMap.put(subject, thumbprint);\n\n\t\t\tif(persistImmediately) {\n\t\t\t\tpersist();\n\t\t\t}\n\n\t\t\treturn newCert;\n\n\t\t}\n return getCertificateByAlias(thumbprint);\n\n\n\t}",
"public int scrollToPage(int pageNumber) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"scrollToPage pageNumber = %d mPageCount = %d\",\n pageNumber, mPageCount);\n\n if (mSupportScrollByPage &&\n (mScrollOver || (pageNumber >= 0 && pageNumber <= mPageCount - 1))) {\n scrollToItem(getFirstItemIndexOnPage(pageNumber));\n } else {\n Log.w(TAG, \"Pagination is not enabled!\");\n }\n return mCurrentItemIndex;\n\t}"
] |
Rotate the specified photo. The only allowed values for degrees are 90, 180 and 270.
@param photoId
The photo ID
@param degrees
The degrees to rotate (90, 170 or 270) | [
"public void rotate(String photoId, int degrees) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ROTATE);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"degrees\", String.valueOf(degrees));\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 }"
] | [
"private void initDescriptor() throws CmsXmlException, CmsException {\n\n if (m_bundleType.equals(CmsMessageBundleEditorTypes.BundleType.DESCRIPTOR)) {\n m_desc = m_resource;\n } else {\n //First try to read from same folder like resource, if it fails use CmsMessageBundleEditorTypes.getDescriptor()\n try {\n m_desc = m_cms.readResource(m_sitepath + m_basename + CmsMessageBundleEditorTypes.Descriptor.POSTFIX);\n } catch (CmsVfsResourceNotFoundException e) {\n m_desc = CmsMessageBundleEditorTypes.getDescriptor(m_cms, m_basename);\n }\n }\n unmarshalDescriptor();\n\n }",
"@ArgumentsChecked\n\t@Throws(IllegalNullArgumentException.class)\n\tpublic static short checkShort(@Nonnull final Number number) {\n\t\tCheck.notNull(number, \"number\");\n\t\tif (!isInShortRange(number)) {\n\t\t\tthrow new IllegalNumberRangeException(number.toString(), SHORT_MIN, SHORT_MAX);\n\t\t}\n\n\t\treturn number.shortValue();\n\t}",
"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 CollectionRequest<Task> stories(String task) {\n \n String path = String.format(\"/tasks/%s/stories\", task);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }",
"private static void listSlack(ProjectFile file)\n {\n for (Task task : file.getTasks())\n {\n System.out.println(task.getName() + \" Total Slack=\" + task.getTotalSlack() + \" Start Slack=\" + task.getStartSlack() + \" Finish Slack=\" + task.getFinishSlack());\n }\n }",
"public byte[] toByteArray() {\n try {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n ObjectOutputStream oos = new ObjectOutputStream(baos);\n oos.writeObject(this);\n return baos.toByteArray();\n } catch (IOException e) {\n throw E.ioException(e);\n }\n }",
"private static void addTimePerComponent(HashMap<String, Long> mapComponentTimes,\tComponent component) {\n Long currentTimeOfComponent = 0L;\n String key = component.getComponentType();\n if (mapComponentTimes.containsKey(key)) {\n currentTimeOfComponent = mapComponentTimes.get(key);\n }\n //when transactions are run in parallel, we should log the longest transaction only to avoid that \n //for ex 'Total time' would be 100ms and transactions in parallel to hornetQ will be 2000ms \n Long maxTime = Math.max(component.getTime(), currentTimeOfComponent);\n mapComponentTimes.put(key, maxTime);\n }",
"public static String parseServers(String zookeepers) {\n int slashIndex = zookeepers.indexOf(\"/\");\n if (slashIndex != -1) {\n return zookeepers.substring(0, slashIndex);\n }\n return zookeepers;\n }",
"public static String format(final String code, final Properties options, final LineEnding lineEnding) {\n\t\tCheck.notEmpty(code, \"code\");\n\t\tCheck.notEmpty(options, \"options\");\n\t\tCheck.notNull(lineEnding, \"lineEnding\");\n\n\t\tfinal CodeFormatter formatter = ToolFactory.createCodeFormatter(options);\n\t\tfinal String lineSeparator = LineEnding.find(lineEnding, code);\n\t\tTextEdit te = null;\n\t\ttry {\n\t\t\tte = formatter.format(CodeFormatter.K_COMPILATION_UNIT, code, 0, code.length(), 0, lineSeparator);\n\t\t} catch (final Exception formatFailed) {\n\t\t\tLOG.warn(\"Formatting failed\", formatFailed);\n\t\t}\n\n\t\tString formattedCode = code;\n\t\tif (te == null) {\n\t\t\tLOG.info(\"Code cannot be formatted. Possible cause is unmatched source/target/compliance version.\");\n\t\t} else {\n\n\t\t\tfinal IDocument doc = new Document(code);\n\t\t\ttry {\n\t\t\t\tte.apply(doc);\n\t\t\t} catch (final Exception e) {\n\t\t\t\tLOG.warn(e.getLocalizedMessage(), e);\n\t\t\t}\n\t\t\tformattedCode = doc.get();\n\t\t}\n\t\treturn formattedCode;\n\t}"
] |
Use this API to unset the properties of gslbsite resources.
Properties that need to be unset are specified in args array. | [
"public static base_responses unset(nitro_service client, String sitename[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (sitename != null && sitename.length > 0) {\n\t\t\tgslbsite unsetresources[] = new gslbsite[sitename.length];\n\t\t\tfor (int i=0;i<sitename.length;i++){\n\t\t\t\tunsetresources[i] = new gslbsite();\n\t\t\t\tunsetresources[i].sitename = sitename[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}"
] | [
"public static boolean isToStringMethod(Method method) {\n return (method != null && method.getName().equals(\"readString\") && method.getParameterTypes().length == 0);\n }",
"public static boolean isDelayedQueue(final Jedis jedis, final String key) {\n return ZSET.equalsIgnoreCase(jedis.type(key));\n }",
"@Override\n public void registerChildren(ManagementResourceRegistration resourceRegistration) {\n // Register wildcard children last to prevent duplicate registration errors when override definitions exist\n for (ResourceDefinition rd : singletonChildren) {\n resourceRegistration.registerSubModel(rd);\n }\n for (ResourceDefinition rd : wildcardChildren) {\n resourceRegistration.registerSubModel(rd);\n }\n }",
"private TrackSourceSlot findTrackSourceSlot() {\n TrackSourceSlot result = TRACK_SOURCE_SLOT_MAP.get(packetBytes[41]);\n if (result == null) {\n return TrackSourceSlot.UNKNOWN;\n }\n return result;\n }",
"private void computeGradientAndHessian(DMatrixRMaj param )\n {\n // residuals = f(x) - y\n function.compute(param, residuals);\n\n computeNumericalJacobian(param,jacobian);\n\n CommonOps_DDRM.multTransA(jacobian, residuals, g);\n CommonOps_DDRM.multTransA(jacobian, jacobian, H);\n\n CommonOps_DDRM.extractDiag(H,Hdiag);\n }",
"private static int resolveDomainTimeoutAdder() {\n String propValue = WildFlySecurityManager.getPropertyPrivileged(DOMAIN_TEST_SYSTEM_PROPERTY, DEFAULT_DOMAIN_TIMEOUT_STRING);\n if (sysPropDomainValue == null || !sysPropDomainValue.equals(propValue)) {\n // First call or the system property changed\n sysPropDomainValue = propValue;\n int number = -1;\n try {\n number = Integer.valueOf(sysPropDomainValue);\n } catch (NumberFormatException nfe) {\n // ignored\n }\n\n if (number > 0) {\n defaultDomainValue = number; // this one is in ms\n } else {\n ControllerLogger.MGMT_OP_LOGGER.invalidDefaultBlockingTimeout(sysPropDomainValue, DOMAIN_TEST_SYSTEM_PROPERTY, DEFAULT_DOMAIN_TIMEOUT_ADDER);\n defaultDomainValue = DEFAULT_DOMAIN_TIMEOUT_ADDER;\n }\n }\n return defaultDomainValue;\n }",
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public int getInboxMessageUnreadCount(){\n synchronized (inboxControllerLock) {\n if (this.ctInboxController != null) {\n return ctInboxController.unreadCount();\n } else {\n getConfigLogger().debug(getAccountId(), \"Notification Inbox not initialized\");\n return -1;\n }\n }\n }",
"public void logAttributeWarning(PathAddress address, String attribute) {\n logAttributeWarning(address, null, null, attribute);\n }",
"public SimplifySpanBuild appendMultiClickable(SpecialClickableUnit specialClickableUnit, Object... specialUnitOrStrings) {\n processMultiClickableSpecialUnit(false, specialClickableUnit, specialUnitOrStrings);\n return this;\n }"
] |
Produces a new ConditionalCounter.
@return a new ConditionalCounter, where order of indices is reversed | [
"@SuppressWarnings( { \"unchecked\" })\r\n public static <K1, K2> TwoDimensionalCounter<K2, K1> reverseIndexOrder(TwoDimensionalCounter<K1, K2> cc) {\r\n // they typing on the outerMF is violated a bit, but it'll work....\r\n TwoDimensionalCounter<K2, K1> result = new TwoDimensionalCounter<K2, K1>((MapFactory) cc.outerMF,\r\n (MapFactory) cc.innerMF);\r\n\r\n for (K1 key1 : cc.firstKeySet()) {\r\n ClassicCounter<K2> c = cc.getCounter(key1);\r\n for (K2 key2 : c.keySet()) {\r\n double count = c.getCount(key2);\r\n result.setCount(key2, key1, count);\r\n }\r\n }\r\n return result;\r\n }"
] | [
"public PartialCollection<BoxItem.Info> getChildrenRange(long offset, long limit, String... fields) {\n QueryStringBuilder builder = new QueryStringBuilder()\n .appendParam(\"limit\", limit)\n .appendParam(\"offset\", offset);\n\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields).toString();\n }\n\n URL url = GET_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), builder.toString(), getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n String totalCountString = responseJSON.get(\"total_count\").toString();\n long fullSize = Double.valueOf(totalCountString).longValue();\n PartialCollection<BoxItem.Info> children = new PartialCollection<BoxItem.Info>(offset, limit, fullSize);\n JsonArray jsonArray = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : jsonArray) {\n JsonObject jsonObject = value.asObject();\n BoxItem.Info parsedItemInfo = (BoxItem.Info) BoxResource.parseInfo(this.getAPI(), jsonObject);\n if (parsedItemInfo != null) {\n children.add(parsedItemInfo);\n }\n }\n return children;\n }",
"public DbConn getConn()\n {\n Connection cnx = null;\n try\n {\n Thread.interrupted(); // this is VERY sad. Needed for Oracle driver which otherwise fails spectacularly.\n cnx = _ds.getConnection();\n if (cnx.getAutoCommit())\n {\n cnx.setAutoCommit(false);\n cnx.rollback(); // To ensure no open transaction created by the pool before changing TX mode\n }\n\n if (cnx.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED)\n {\n cnx.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);\n }\n\n return new DbConn(this, cnx);\n }\n catch (SQLException e)\n {\n DbHelper.closeQuietly(cnx); // May have been left open when the pool has given us a failed connection.\n throw new DatabaseException(e);\n }\n }",
"public T reverse() {\n String id = getId();\n String REVERSE = \"_REVERSE\";\n if (id.endsWith(REVERSE)) {\n setId(id.substring(0, id.length() - REVERSE.length()));\n }\n\n float start = mStart;\n float end = mEnd;\n mStart = end;\n mEnd = start;\n mReverse = !mReverse;\n return self();\n }",
"@Override\n public View getView(int position, View convertView, ViewGroup parent) {\n Country country = getItem(position);\n\n if (convertView == null) {\n convertView = new ImageView(getContext());\n }\n\n ((ImageView) convertView).setImageResource(getFlagResource(country));\n\n return convertView;\n }",
"public static rsskeytype get(nitro_service service) throws Exception{\n\t\trsskeytype obj = new rsskeytype();\n\t\trsskeytype[] response = (rsskeytype[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public static <K,V> SortedMap<K,V> asImmutable(SortedMap<K, ? extends V> self) {\n return Collections.unmodifiableSortedMap(self);\n }",
"public void put(final String key, final Object value) {\n if (TASK_DIRECTORY_KEY.equals(key) && this.values.keySet().contains(TASK_DIRECTORY_KEY)) {\n // ensure that no one overwrites the task directory\n throw new IllegalArgumentException(\"Invalid key: \" + key);\n }\n\n if (value == null) {\n throw new IllegalArgumentException(\n \"A null value was attempted to be put into the values object under key: \" + key);\n }\n this.values.put(key, value);\n }",
"private void printClassRecord(PrintStream out, ClassRecord classRecord,\n\t\t\tEntityIdValue entityIdValue) {\n\t\tprintTerms(out, classRecord.itemDocument, entityIdValue, \"\\\"\"\n\t\t\t\t+ getClassLabel(entityIdValue) + \"\\\"\");\n\t\tprintImage(out, classRecord.itemDocument);\n\n\t\tout.print(\",\" + classRecord.itemCount + \",\" + classRecord.subclassCount);\n\n\t\tprintClassList(out, classRecord.superClasses);\n\n\t\tHashSet<EntityIdValue> superClasses = new HashSet<>();\n\t\tfor (EntityIdValue superClass : classRecord.superClasses) {\n\t\t\taddSuperClasses(superClass, superClasses);\n\t\t}\n\n\t\tprintClassList(out, superClasses);\n\n\t\tprintRelatedProperties(out, classRecord);\n\n\t\tout.println(\"\");\n\t}",
"private void loadLocalizationFromXmlBundle(Locale locale) {\n\n CmsXmlContentValueSequence messages = m_xmlBundle.getValueSequence(\"Message\", locale);\n SortedProperties props = new SortedProperties();\n if (null != messages) {\n for (I_CmsXmlContentValue msg : messages.getValues()) {\n String msgpath = msg.getPath();\n props.put(\n m_xmlBundle.getStringValue(m_cms, msgpath + \"/Key\", locale),\n m_xmlBundle.getStringValue(m_cms, msgpath + \"/Value\", locale));\n }\n }\n m_localizations.put(locale, props);\n }"
] |
Scales the brightness of a pixel. | [
"public static int scale(Double factor, int pixel) {\n return rgb(\n (int) Math.round(factor * red(pixel)),\n (int) Math.round(factor * green(pixel)),\n (int) Math.round(factor * blue(pixel))\n );\n }"
] | [
"public final Template getTemplate(final String name) {\n final Template template = this.templates.get(name);\n if (template != null) {\n this.accessAssertion.assertAccess(\"Configuration\", this);\n template.assertAccessible(name);\n } else {\n throw new IllegalArgumentException(String.format(\"Template '%s' does not exist. Options are: \" +\n \"%s\", name, this.templates.keySet()));\n }\n return template;\n }",
"public static Operation createDeployOperation(final DeploymentDescription deployment) {\n Assert.checkNotNullParam(\"deployment\", deployment);\n final CompositeOperationBuilder builder = CompositeOperationBuilder.create(true);\n addDeployOperationStep(builder, deployment);\n return builder.build();\n }",
"@VisibleForTesting\n protected static String createLabelText(\n final DistanceUnit scaleUnit, final double value, final DistanceUnit intervalUnit) {\n double scaledValue = scaleUnit.convertTo(value, intervalUnit);\n\n // assume that there is no interval smaller then 0.0001\n scaledValue = Math.round(scaledValue * 10000) / 10000;\n String decimals = Double.toString(scaledValue).split(\"\\\\.\")[1];\n\n if (Double.valueOf(decimals) == 0) {\n return Long.toString(Math.round(scaledValue));\n } else {\n return Double.toString(scaledValue);\n }\n }",
"private boolean hasMultipleCostRates()\n {\n boolean result = false;\n CostRateTable table = getCostRateTable();\n if (table != null)\n {\n //\n // We assume here that if there is just one entry in the cost rate\n // table, this is an open ended rate which covers any work, it won't\n // have specific dates attached to it.\n //\n if (table.size() > 1)\n {\n //\n // If we have multiple rates in the table, see if the same rate\n // is in force at the start and the end of the aaaignment.\n //\n CostRateTableEntry startEntry = table.getEntryByDate(getStart());\n CostRateTableEntry finishEntry = table.getEntryByDate(getFinish());\n result = (startEntry != finishEntry);\n }\n }\n return result;\n }",
"public SparqlResult runQuery(String endpoint, String query) {\n return SparqlClient.execute(endpoint, query, username, password);\n }",
"public ItemRequest<Project> addCustomFieldSetting(String project) {\n \n String path = String.format(\"/projects/%s/addCustomFieldSetting\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\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 void copyProperties(Object dest, Object orig){\n\t\ttry {\n\t\t\tif (orig != null && dest != null){\n\t\t\t\tBeanUtils.copyProperties(dest, orig);\n\n\t\t\t\tPropertyUtils putils = new PropertyUtils();\n\t PropertyDescriptor origDescriptors[] = putils.getPropertyDescriptors(orig);\n\n\t\t\t\tfor (PropertyDescriptor origDescriptor : origDescriptors) {\n\t\t\t\t\tString name = origDescriptor.getName();\n\t\t\t\t\tif (\"class\".equals(name)) {\n\t\t\t\t\t\tcontinue; // No point in trying to set an object's class\n\t\t\t\t\t}\n\n\t\t\t\t\tClass propertyType = origDescriptor.getPropertyType();\n\t\t\t\t\tif (!Boolean.class.equals(propertyType) && !(Boolean.class.equals(propertyType)))\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tif (!putils.isReadable(orig, name)) { //because of bad convention\n\t\t\t\t\t\tMethod m = orig.getClass().getMethod(\"is\" + name.substring(0, 1).toUpperCase() + name.substring(1), (Class<?>[]) null);\n\t\t\t\t\t\tObject value = m.invoke(orig, (Object[]) null);\n\n\t\t\t\t\t\tif (putils.isWriteable(dest, name)) {\n\t\t\t\t\t\t\tBeanUtilsBean.getInstance().copyProperty(dest, name, value);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\tthrow new DJException(\"Could not copy properties for shared object: \" + orig +\", message: \" + e.getMessage(),e);\n\t\t}\n\t}",
"public final void notifyFooterItemMoved(int fromPosition, int toPosition) {\n if (fromPosition < 0 || toPosition < 0 || fromPosition >= footerItemCount || toPosition >= footerItemCount) {\n throw new IndexOutOfBoundsException(\"The given fromPosition \" + fromPosition\n + \" or toPosition \" + toPosition + \" is not within the position bounds for footer items [0 - \"\n + (footerItemCount - 1) + \"].\");\n }\n notifyItemMoved(fromPosition + headerItemCount + contentItemCount, toPosition + headerItemCount + contentItemCount);\n }"
] |
Save map to file
@param map Map to save
@param file File to save
@throws IOException I/O error | [
"public static void saveContentMap(Map<String, String> map, File file) throws IOException {\n\n FileWriter out = new FileWriter(file);\n for (String key : map.keySet()) {\n if (map.get(key) != null) {\n out.write(key.replace(\":\", \"#escapedtwodots#\") + \":\"\n + map.get(key).replace(\":\", \"#escapedtwodots#\") + \"\\r\\n\");\n }\n }\n out.close();\n }"
] | [
"public Set<ConstraintViolation> validate(int record) {\r\n\t\tSet<ConstraintViolation> errors = new LinkedHashSet<ConstraintViolation>();\r\n\t\tfor (int ds = 0; ds < 250; ++ds) {\r\n\t\t\ttry {\r\n\t\t\t\tDataSetInfo dataSetInfo = dsiFactory.create(IIM.DS(record, ds));\r\n\t\t\t\terrors.addAll(validate(dataSetInfo));\r\n\t\t\t} catch (InvalidDataSetException ignored) {\r\n\t\t\t\t// DataSetFactory doesn't know about this ds, so will skip it\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn errors;\r\n\t}",
"protected void rehash(int newCapacity) {\r\n\tint oldCapacity = table.length;\r\n\t//if (oldCapacity == newCapacity) return;\r\n\t\r\n\tlong oldTable[] = table;\r\n\tint oldValues[] = values;\r\n\tbyte oldState[] = state;\r\n\r\n\tlong newTable[] = new long[newCapacity];\r\n\tint newValues[] = new int[newCapacity];\r\n\tbyte newState[] = new byte[newCapacity];\r\n\r\n\tthis.lowWaterMark = chooseLowWaterMark(newCapacity,this.minLoadFactor);\r\n\tthis.highWaterMark = chooseHighWaterMark(newCapacity,this.maxLoadFactor);\r\n\r\n\tthis.table = newTable;\r\n\tthis.values = newValues;\r\n\tthis.state = newState;\r\n\tthis.freeEntries = newCapacity-this.distinct; // delta\r\n\t\r\n\tfor (int i = oldCapacity ; i-- > 0 ;) {\r\n\t\tif (oldState[i]==FULL) {\r\n\t\t\tlong element = oldTable[i];\r\n\t\t\tint index = indexOfInsertion(element);\r\n\t\t\tnewTable[index]=element;\r\n\t\t\tnewValues[index]=oldValues[i];\r\n\t\t\tnewState[index]=FULL;\r\n\t\t}\r\n\t}\r\n}",
"public Task<RemoteInsertOneResult> insertOne(final DocumentT document) {\n return dispatcher.dispatchTask(new Callable<RemoteInsertOneResult>() {\n @Override\n public RemoteInsertOneResult call() {\n return proxy.insertOne(document);\n }\n });\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 }",
"protected boolean isItemAccepted(byte[] key) {\n boolean entryAccepted = false;\n if (!fetchOrphaned) {\n if (isKeyNeeded(key)) {\n entryAccepted = true;\n }\n } else {\n if (!StoreRoutingPlan.checkKeyBelongsToNode(key, nodeId, initialCluster, storeDef)) {\n entryAccepted = true;\n }\n }\n return entryAccepted;\n }",
"public String getValueForDisplayValue(final String key) {\n if (mapDisplayValuesToValues.containsKey(key)) {\n return mapDisplayValuesToValues.get(key);\n }\n return key;\n }",
"public final void updateLastCheckTime(final String id, final long lastCheckTime) {\n final CriteriaBuilder builder = getSession().getCriteriaBuilder();\n final CriteriaUpdate<PrintJobStatusExtImpl> update =\n builder.createCriteriaUpdate(PrintJobStatusExtImpl.class);\n final Root<PrintJobStatusExtImpl> root = update.from(PrintJobStatusExtImpl.class);\n update.where(builder.equal(root.get(\"referenceId\"), id));\n update.set(root.get(\"lastCheckTime\"), lastCheckTime);\n getSession().createQuery(update).executeUpdate();\n }",
"public DJCrosstab build(){\r\n\t\tif (crosstab.getMeasures().isEmpty()){\r\n\t\t\tthrow new LayoutException(\"Crosstabs must have at least one measure\");\r\n\t\t}\r\n\t\tif (crosstab.getColumns().isEmpty()){\r\n\t\t\tthrow new LayoutException(\"Crosstabs must have at least one column\");\r\n\t\t}\r\n\t\tif (crosstab.getRows().isEmpty()){\r\n\t\t\tthrow new LayoutException(\"Crosstabs must have at least one row\");\r\n\t\t}\r\n\t\t\r\n\t\t\r\n\t\t//Ensure default dimension values\r\n\t\tfor (DJCrosstabColumn col : crosstab.getColumns()) {\r\n\t\t\tif (col.getWidth() == -1 && cellWidth != -1)\r\n\t\t\t\tcol.setWidth(cellWidth);\r\n\r\n\t\t\tif (col.getWidth() == -1 )\r\n\t\t\t\tcol.setWidth(DEFAULT_CELL_WIDTH);\r\n\r\n\t\t\tif (col.getHeaderHeight() == -1 && columnHeaderHeight != -1)\r\n\t\t\t\tcol.setHeaderHeight(columnHeaderHeight);\r\n\r\n\t\t\tif (col.getHeaderHeight() == -1)\r\n\t\t\t\tcol.setHeaderHeight(DEFAULT_COLUMN_HEADER_HEIGHT);\r\n\t\t}\r\n\r\n\t\tfor (DJCrosstabRow row : crosstab.getRows()) {\r\n\t\t\tif (row.getHeight() == -1 && cellHeight != -1)\r\n\t\t\t\trow.setHeight(cellHeight);\r\n\r\n\t\t\tif (row.getHeight() == -1 )\r\n\t\t\t\trow.setHeight(DEFAULT_CELL_HEIGHT);\r\n\r\n\t\t\tif (row.getHeaderWidth() == -1 && rowHeaderWidth != -1)\r\n\t\t\t\trow.setHeaderWidth(rowHeaderWidth);\r\n\r\n\t\t\tif (row.getHeaderWidth() == -1)\r\n\t\t\t\trow.setHeaderWidth(DEFAULT_ROW_HEADER_WIDTH);\r\n\r\n\t\t}\r\n\t\treturn crosstab;\r\n\t}",
"protected static List<String> parseMandatoryStringValues(JSONObject json, String key) throws JSONException {\n\n List<String> list = null;\n JSONArray array = json.getJSONArray(key);\n list = new ArrayList<String>(array.length());\n for (int i = 0; i < array.length(); i++) {\n try {\n String entry = array.getString(i);\n list.add(entry);\n } catch (JSONException e) {\n LOG.info(Messages.get().getBundle().key(Messages.LOG_OPTIONAL_STRING_ENTRY_UNPARSABLE_1, key), e);\n }\n }\n return list;\n }"
] |
Convert an object to a list of maps.
@param mapper the object mapper
@param source the source object
@return list | [
"public static List<Map<String, Object>> listify(ObjectMapper mapper, Object source) {\n return (List<Map<String, Object>>) collectify(mapper, source, List.class);\n }"
] | [
"protected boolean executeOperation(final TransactionalProtocolClient.TransactionalOperationListener<ServerOperation> listener, TransactionalProtocolClient client, final ServerIdentity identity, final ModelNode operation, final OperationResultTransformer transformer) {\n if(client == null) {\n return false;\n }\n final OperationMessageHandler messageHandler = new DelegatingMessageHandler(context);\n final OperationAttachments operationAttachments = new DelegatingOperationAttachments(context);\n final ServerOperation serverOperation = new ServerOperation(identity, operation, messageHandler, operationAttachments, transformer);\n try {\n DomainControllerLogger.HOST_CONTROLLER_LOGGER.tracef(\"Sending %s to %s\", operation, identity);\n final Future<OperationResponse> result = client.execute(listener, serverOperation);\n recordExecutedRequest(new ExecutedServerRequest(identity, result, transformer));\n } catch (IOException e) {\n final TransactionalProtocolClient.PreparedOperation<ServerOperation> result = BlockingQueueOperationListener.FailedOperation.create(serverOperation, e);\n listener.operationPrepared(result);\n recordExecutedRequest(new ExecutedServerRequest(identity, result.getFinalResult(), transformer));\n }\n return true;\n }",
"private Collection getOwnerObjects()\r\n {\r\n Collection owners = new Vector();\r\n while (hasNext())\r\n {\r\n owners.add(next());\r\n }\r\n return owners;\r\n }",
"@Override\n public void setBody(String body) {\n super.setBody(body);\n this.jsonValue = JsonValue.readFrom(body);\n }",
"public static String readFlowId(Message message) {\n if (!(message instanceof SoapMessage)) {\n return null;\n }\n String flowId = null;\n Header hdFlowId = ((SoapMessage)message).getHeader(FLOW_ID_QNAME);\n if (hdFlowId != null) {\n if (hdFlowId.getObject() instanceof String) {\n flowId = (String)hdFlowId.getObject();\n } else if (hdFlowId.getObject() instanceof Node) {\n Node headerNode = (Node)hdFlowId.getObject();\n flowId = headerNode.getTextContent();\n } else {\n LOG.warning(\"Found FlowId soap header but value is not a String or a Node! Value: \"\n + hdFlowId.getObject().toString());\n }\n }\n return flowId;\n }",
"public void swapSubstring(BitString other, int start, int length)\n {\n assertValidIndex(start);\n other.assertValidIndex(start);\n \n int word = start / WORD_LENGTH;\n\n int partialWordSize = (WORD_LENGTH - start) % WORD_LENGTH;\n if (partialWordSize > 0)\n {\n swapBits(other, word, 0xFFFFFFFF << (WORD_LENGTH - partialWordSize));\n ++word;\n }\n\n int remainingBits = length - partialWordSize;\n int stop = remainingBits / WORD_LENGTH;\n for (int i = word; i < stop; i++)\n {\n int temp = data[i];\n data[i] = other.data[i];\n other.data[i] = temp;\n }\n\n remainingBits %= WORD_LENGTH;\n if (remainingBits > 0)\n {\n swapBits(other, word, 0xFFFFFFFF >>> (WORD_LENGTH - remainingBits));\n }\n }",
"protected void addStatement(Statement statement, boolean isNew) {\n\t\tPropertyIdValue pid = statement.getMainSnak().getPropertyId();\n\n\t\t// This code maintains the following properties:\n\t\t// (1) the toKeep structure does not contain two statements with the\n\t\t// same statement id\n\t\t// (2) the toKeep structure does not contain two statements that can\n\t\t// be merged\n\t\tif (this.toKeep.containsKey(pid)) {\n\t\t\tList<StatementWithUpdate> statements = this.toKeep.get(pid);\n\t\t\tfor (int i = 0; i < statements.size(); i++) {\n\t\t\t\tStatement currentStatement = statements.get(i).statement;\n\t\t\t\tboolean currentIsNew = statements.get(i).write;\n\n\t\t\t\tif (!\"\".equals(currentStatement.getStatementId())\n\t\t\t\t\t\t&& currentStatement.getStatementId().equals(\n\t\t\t\t\t\t\t\tstatement.getStatementId())) {\n\t\t\t\t\t// Same, non-empty id: ignore existing statement as if\n\t\t\t\t\t// deleted\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tStatement newStatement = mergeStatements(statement,\n\t\t\t\t\t\tcurrentStatement);\n\t\t\t\tif (newStatement != null) {\n\t\t\t\t\tboolean writeNewStatement = (isNew || !newStatement\n\t\t\t\t\t\t\t.equals(statement))\n\t\t\t\t\t\t\t&& (currentIsNew || !newStatement\n\t\t\t\t\t\t\t\t\t.equals(currentStatement));\n\t\t\t\t\t// noWrite: (newS == statement && !isNew)\n\t\t\t\t\t// || (newS == cur && !curIsNew)\n\t\t\t\t\t// Write: (newS != statement || isNew )\n\t\t\t\t\t// && (newS != cur || curIsNew)\n\n\t\t\t\t\tstatements.set(i, new StatementWithUpdate(newStatement,\n\t\t\t\t\t\t\twriteNewStatement));\n\n\t\t\t\t\t// Impossible with default merge code:\n\t\t\t\t\t// Kept here for future extensions that may choose to not\n\t\t\t\t\t// reuse this id.\n\t\t\t\t\tif (!\"\".equals(statement.getStatementId())\n\t\t\t\t\t\t\t&& !newStatement.getStatementId().equals(\n\t\t\t\t\t\t\t\t\tstatement.getStatementId())) {\n\t\t\t\t\t\tthis.toDelete.add(statement.getStatementId());\n\t\t\t\t\t}\n\t\t\t\t\tif (!\"\".equals(currentStatement.getStatementId())\n\t\t\t\t\t\t\t&& !newStatement.getStatementId().equals(\n\t\t\t\t\t\t\t\t\tcurrentStatement.getStatementId())) {\n\t\t\t\t\t\tthis.toDelete.add(currentStatement.getStatementId());\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstatements.add(new StatementWithUpdate(statement, isNew));\n\t\t} else {\n\t\t\tList<StatementWithUpdate> statements = new ArrayList<>();\n\t\t\tstatements.add(new StatementWithUpdate(statement, isNew));\n\t\t\tthis.toKeep.put(pid, statements);\n\t\t}\n\t}",
"public static HikariConfig createHikariConfig(CmsParameterConfiguration config, String key) {\n\n Map<String, String> poolMap = Maps.newHashMap();\n for (Map.Entry<String, String> entry : config.entrySet()) {\n String suffix = getPropertyRelativeSuffix(KEY_DATABASE_POOL + \".\" + key, entry.getKey());\n if ((suffix != null) && !CmsStringUtil.isEmptyOrWhitespaceOnly(entry.getValue())) {\n String value = entry.getValue().trim();\n poolMap.put(suffix, value);\n }\n }\n\n // these are for backwards compatibility , all other properties not of the form db.pool.poolname.v11..... are ignored\n String jdbcUrl = poolMap.get(KEY_JDBC_URL);\n String params = poolMap.get(KEY_JDBC_URL_PARAMS);\n String driver = poolMap.get(KEY_JDBC_DRIVER);\n String user = poolMap.get(KEY_USERNAME);\n String password = poolMap.get(KEY_PASSWORD);\n String poolName = OPENCMS_URL_PREFIX + key;\n\n if ((params != null) && (jdbcUrl != null)) {\n jdbcUrl += params;\n }\n\n Properties hikariProps = new Properties();\n\n if (jdbcUrl != null) {\n hikariProps.put(\"jdbcUrl\", jdbcUrl);\n }\n if (driver != null) {\n hikariProps.put(\"driverClassName\", driver);\n }\n if (user != null) {\n user = OpenCms.getCredentialsResolver().resolveCredential(I_CmsCredentialsResolver.DB_USER, user);\n hikariProps.put(\"username\", user);\n }\n if (password != null) {\n password = OpenCms.getCredentialsResolver().resolveCredential(\n I_CmsCredentialsResolver.DB_PASSWORD,\n password);\n hikariProps.put(\"password\", password);\n }\n\n hikariProps.put(\"maximumPoolSize\", \"30\");\n\n // Properties of the form db.pool.poolname.v11.<foo> are directly passed to HikariCP as <foo>\n for (Map.Entry<String, String> entry : poolMap.entrySet()) {\n String suffix = getPropertyRelativeSuffix(\"v11\", entry.getKey());\n if (suffix != null) {\n hikariProps.put(suffix, entry.getValue());\n }\n }\n\n String configuredTestQuery = (String)(hikariProps.get(\"connectionTestQuery\"));\n String testQueryForDriver = testQueries.get(driver);\n if ((testQueryForDriver != null) && CmsStringUtil.isEmptyOrWhitespaceOnly(configuredTestQuery)) {\n hikariProps.put(\"connectionTestQuery\", testQueryForDriver);\n }\n hikariProps.put(\"registerMbeans\", \"true\");\n HikariConfig result = new HikariConfig(hikariProps);\n\n result.setPoolName(poolName.replace(\":\", \"_\"));\n return result;\n }",
"private EditorState getMasterState() {\n\n List<TableProperty> cols = new ArrayList<TableProperty>(4);\n cols.add(TableProperty.KEY);\n cols.add(TableProperty.DESCRIPTION);\n cols.add(TableProperty.DEFAULT);\n cols.add(TableProperty.TRANSLATION);\n return new EditorState(cols, true);\n }",
"protected static final float[] getSpreadInRange(float member, int count, int max, int offset) {\n // to find the spread, we first find the min that is a\n // multiple of max/count away from the member\n\n int interval = max / count;\n float min = (member + offset) % interval;\n\n if (min == 0 && member == max) {\n min += interval;\n }\n\n float[] range = new float[count];\n for (int i = 0; i < count; i++) {\n range[i] = min + interval * i + offset;\n }\n\n return range;\n }"
] |
Generates the path to an output file for a given source URL. Creates
all necessary parent directories for the destination file.
@param src the source
@return the path to the output file | [
"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 }"
] | [
"protected boolean isSavedConnection(DatabaseConnection connection) {\n\t\tNestedConnection currentSaved = specialConnection.get();\n\t\tif (currentSaved == null) {\n\t\t\treturn false;\n\t\t} else if (currentSaved.connection == connection) {\n\t\t\t// ignore the release when we have a saved connection\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}",
"public synchronized void removeAllSceneObjects() {\n final GVRCameraRig rig = getMainCameraRig();\n final GVRSceneObject head = rig.getOwnerObject();\n rig.removeAllChildren();\n\n NativeScene.removeAllSceneObjects(getNative());\n for (final GVRSceneObject child : mSceneRoot.getChildren()) {\n child.getParent().removeChildObject(child);\n }\n\n if (null != head) {\n mSceneRoot.addChildObject(head);\n }\n\n final int numControllers = getGVRContext().getInputManager().clear();\n if (numControllers > 0)\n {\n getGVRContext().getInputManager().selectController();\n }\n\n getGVRContext().runOnGlThread(new Runnable() {\n @Override\n public void run() {\n NativeScene.deleteLightsAndDepthTextureOnRenderThread(getNative());\n }\n });\n }",
"public static AccrueType getInstance(String type, Locale locale)\n {\n AccrueType result = null;\n\n String[] typeNames = LocaleData.getStringArray(locale, LocaleData.ACCRUE_TYPES);\n\n for (int loop = 0; loop < typeNames.length; loop++)\n {\n if (typeNames[loop].equalsIgnoreCase(type) == true)\n {\n result = AccrueType.getInstance(loop + 1);\n break;\n }\n }\n\n if (result == null)\n {\n result = AccrueType.PRORATED;\n }\n\n return (result);\n }",
"public static void unregisterContextualInstance(EjbDescriptor<?> descriptor) {\n Set<Class<?>> classes = CONTEXTUAL_SESSION_BEANS.get();\n classes.remove(descriptor.getBeanClass());\n if (classes.isEmpty()) {\n CONTEXTUAL_SESSION_BEANS.remove();\n }\n }",
"protected void registerUnregisterJMX(boolean doRegister) {\r\n\t\tif (this.mbs == null ){ // this way makes it easier for mocking.\r\n\t\t\tthis.mbs = ManagementFactory.getPlatformMBeanServer();\r\n\t\t}\r\n\t\ttry {\r\n\t\t\tString suffix = \"\";\r\n\r\n\t\t\tif (this.config.getPoolName()!=null){\r\n\t\t\t\tsuffix=\"-\"+this.config.getPoolName();\r\n\t\t\t}\r\n\r\n\t\t\tObjectName name = new ObjectName(MBEAN_BONECP +suffix);\r\n\t\t\tObjectName configname = new ObjectName(MBEAN_CONFIG + suffix);\r\n\r\n\r\n\t\t\tif (doRegister){\r\n\t\t\t\tif (!this.mbs.isRegistered(name)){\r\n\t\t\t\t\tthis.mbs.registerMBean(this.statistics, name);\r\n\t\t\t\t}\r\n\t\t\t\tif (!this.mbs.isRegistered(configname)){\r\n\t\t\t\t\tthis.mbs.registerMBean(this.config, configname);\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tif (this.mbs.isRegistered(name)){\r\n\t\t\t\t\tthis.mbs.unregisterMBean(name);\r\n\t\t\t\t}\r\n\t\t\t\tif (this.mbs.isRegistered(configname)){\r\n\t\t\t\t\tthis.mbs.unregisterMBean(configname);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} catch (Exception e) {\r\n\t\t\tlogger.error(\"Unable to start/stop JMX\", e);\r\n\t\t}\r\n\t}",
"public INode getLastCompleteNodeByOffset(INode node, int offsetPosition, int completionOffset) {\n\t\treturn internalGetLastCompleteNodeByOffset(node.getRootNode(), offsetPosition);\n\t}",
"private void removeObservation( int index ) {\n final int N = y.numRows-1;\n final double d[] = y.data;\n\n // shift\n for( int i = index; i < N; i++ ) {\n d[i] = d[i+1];\n }\n y.numRows--;\n }",
"protected List<I_CmsFacetQueryItem> parseFacetQueryItems(JSONObject queryFacetObject) throws JSONException {\n\n JSONArray items = queryFacetObject.getJSONArray(JSON_KEY_QUERY_FACET_QUERY);\n List<I_CmsFacetQueryItem> result = new ArrayList<I_CmsFacetQueryItem>(items.length());\n for (int i = 0; i < items.length(); i++) {\n I_CmsFacetQueryItem item = parseFacetQueryItem(items.getJSONObject(i));\n if (item != null) {\n result.add(item);\n }\n }\n return result;\n }",
"public Object toInternal(Attribute<?> attribute) throws GeomajasException {\n\t\tif (attribute instanceof PrimitiveAttribute<?>) {\n\t\t\treturn toPrimitiveObject((PrimitiveAttribute<?>) attribute);\n\t\t} else if (attribute instanceof AssociationAttribute<?>) {\n\t\t\treturn toAssociationObject((AssociationAttribute<?>) attribute);\n\t\t} else {\n\t\t\tthrow new GeomajasException(ExceptionCode.CONVERSION_PROBLEM, attribute);\n\t\t}\n\t}"
] |
Starts the Okapi Barcode UI.
@param args the command line arguments | [
"public static void main(String[] args) {\r\n Settings settings = new Settings();\r\n new JCommander(settings, args);\r\n\r\n if (!settings.isGuiSupressed()) {\r\n OkapiUI okapiUi = new OkapiUI();\r\n okapiUi.setVisible(true);\r\n } else {\r\n int returnValue;\r\n \r\n returnValue = commandLine(settings);\r\n \r\n if (returnValue != 0) {\r\n System.out.println(\"An error occurred\");\r\n }\r\n }\r\n }"
] | [
"public static Integer getDurationValue(ProjectProperties properties, Duration duration)\n {\n Integer result;\n if (duration == null)\n {\n result = null;\n }\n else\n {\n if (duration.getUnits() != TimeUnit.MINUTES)\n {\n duration = duration.convertUnits(TimeUnit.MINUTES, properties);\n }\n result = Integer.valueOf((int) duration.getDuration());\n }\n return (result);\n }",
"public static double blackScholesATMOptionValue(\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble forward,\n\t\t\tdouble payoffUnit)\n\t{\n\t\tif(optionMaturity < 0) {\n\t\t\treturn 0.0;\n\t\t}\n\n\t\t// Calculate analytic value\n\t\tdouble dPlus = 0.5 * volatility * Math.sqrt(optionMaturity);\n\t\tdouble dMinus = -dPlus;\n\n\t\tdouble valueAnalytic = (NormalDistribution.cumulativeDistribution(dPlus) - NormalDistribution.cumulativeDistribution(dMinus)) * forward * payoffUnit;\n\n\t\treturn valueAnalytic;\n\t}",
"public Automaton getAutomatonById(String id) throws IOException {\n if (idToVersion.containsKey(id)) {\n List<BytesRef> bytesArray = new ArrayList<>();\n Set<String> data = get(id);\n if (data != null) {\n Term term;\n for (String item : data) {\n term = new Term(\"dummy\", item);\n bytesArray.add(term.bytes());\n }\n Collections.sort(bytesArray);\n return Automata.makeStringUnion(bytesArray);\n }\n }\n return null;\n }",
"protected static InstallationModificationImpl.InstallationState load(final InstalledIdentity installedIdentity) throws IOException {\n final InstallationModificationImpl.InstallationState state = new InstallationModificationImpl.InstallationState();\n for (final Layer layer : installedIdentity.getLayers()) {\n state.putLayer(layer);\n }\n for (final AddOn addOn : installedIdentity.getAddOns()) {\n state.putAddOn(addOn);\n }\n return state;\n }",
"public static double[][] pseudoInverse(double[][] matrix){\n\t\tif(isSolverUseApacheCommonsMath) {\n\t\t\t// Use LU from common math\n\t\t\tSingularValueDecomposition svd = new SingularValueDecomposition(new Array2DRowRealMatrix(matrix));\n\t\t\tdouble[][] matrixInverse = svd.getSolver().getInverse().getData();\n\n\t\t\treturn matrixInverse;\n\t\t}\n\t\telse {\n\t\t\treturn org.jblas.Solve.pinv(new org.jblas.DoubleMatrix(matrix)).toArray2();\n\t\t}\n\t}",
"public static base_response add(nitro_service client, nspbr6 resource) throws Exception {\n\t\tnspbr6 addresource = new nspbr6();\n\t\taddresource.name = resource.name;\n\t\taddresource.td = resource.td;\n\t\taddresource.action = resource.action;\n\t\taddresource.srcipv6 = resource.srcipv6;\n\t\taddresource.srcipop = resource.srcipop;\n\t\taddresource.srcipv6val = resource.srcipv6val;\n\t\taddresource.srcport = resource.srcport;\n\t\taddresource.srcportop = resource.srcportop;\n\t\taddresource.srcportval = resource.srcportval;\n\t\taddresource.destipv6 = resource.destipv6;\n\t\taddresource.destipop = resource.destipop;\n\t\taddresource.destipv6val = resource.destipv6val;\n\t\taddresource.destport = resource.destport;\n\t\taddresource.destportop = resource.destportop;\n\t\taddresource.destportval = resource.destportval;\n\t\taddresource.srcmac = resource.srcmac;\n\t\taddresource.protocol = resource.protocol;\n\t\taddresource.protocolnumber = resource.protocolnumber;\n\t\taddresource.vlan = resource.vlan;\n\t\taddresource.Interface = resource.Interface;\n\t\taddresource.priority = resource.priority;\n\t\taddresource.state = resource.state;\n\t\taddresource.msr = resource.msr;\n\t\taddresource.monitor = resource.monitor;\n\t\taddresource.nexthop = resource.nexthop;\n\t\taddresource.nexthopval = resource.nexthopval;\n\t\taddresource.nexthopvlan = resource.nexthopvlan;\n\t\treturn addresource.add_resource(client);\n\t}",
"public static base_response unset(nitro_service client, filterhtmlinjectionparameter resource, String[] args) throws Exception{\n\t\tfilterhtmlinjectionparameter unsetresource = new filterhtmlinjectionparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"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 }",
"private static synchronized StreamHandler getStreamHandler() {\n if (methodHandler == null) {\n methodHandler = new ConsoleHandler();\n methodHandler.setFormatter(new Formatter() {\n @Override\n public String format(LogRecord record) {\n return record.getMessage() + \"\\n\";\n }\n });\n methodHandler.setLevel(Level.FINE);\n }\n return methodHandler;\n }"
] |
Extracts a house holder vector from the column of A and stores it in u
@param A Complex matrix with householder vectors stored in the lower left triangle
@param row0 first row in A (implicitly assumed to be r + i0)
@param row1 last row + 1 in A
@param col Column in A
@param u Output array storage
@param offsetU first index in U | [
"public static void extractHouseholderColumn( ZMatrixRMaj A ,\n int row0 , int row1 ,\n int col , double u[], int offsetU )\n {\n int indexU = (row0+offsetU)*2;\n u[indexU++] = 1;\n u[indexU++] = 0;\n\n for (int row = row0+1; row < row1; row++) {\n int indexA = A.getIndex(row,col);\n u[indexU++] = A.data[indexA];\n u[indexU++] = A.data[indexA+1];\n }\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 }",
"private void populateDefaultData(FieldItem[] defaultData)\n {\n for (FieldItem item : defaultData)\n {\n m_map.put(item.getType(), item);\n }\n }",
"private String safeToString(Object obj)\r\n\t{\r\n\t\tString toString = null;\r\n\t\tif (obj != null)\r\n\t\t{\r\n\t\t try\r\n\t\t {\r\n\t\t toString = obj.toString();\r\n\t\t }\r\n\t\t catch (Throwable ex)\r\n\t\t {\r\n\t\t toString = \"BAD toString() impl for \" + obj.getClass().getName();\r\n\t\t }\r\n\t\t}\r\n\t\treturn toString;\r\n\t}",
"public static sslaction get(nitro_service service, String name) throws Exception{\n\t\tsslaction obj = new sslaction();\n\t\tobj.set_name(name);\n\t\tsslaction response = (sslaction) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static <T> SortedSet<T> asImmutable(SortedSet<T> self) {\n return Collections.unmodifiableSortedSet(self);\n }",
"protected synchronized void quit() {\n log.debug(\"Stopping {}\", getName());\n closeServerSocket();\n\n // Close all handlers. Handler threads terminate if run loop exits\n synchronized (handlers) {\n for (ProtocolHandler handler : handlers) {\n handler.close();\n }\n handlers.clear();\n }\n log.debug(\"Stopped {}\", getName());\n }",
"public boolean matches(String uri) {\n\t\tif (uri == null) {\n\t\t\treturn false;\n\t\t}\n\t\tMatcher matcher = this.matchPattern.matcher(uri);\n\t\treturn matcher.matches();\n\t}",
"protected boolean isItemAccepted(byte[] key) {\n boolean entryAccepted = false;\n if (!fetchOrphaned) {\n if (isKeyNeeded(key)) {\n entryAccepted = true;\n }\n } else {\n if (!StoreRoutingPlan.checkKeyBelongsToNode(key, nodeId, initialCluster, storeDef)) {\n entryAccepted = true;\n }\n }\n return entryAccepted;\n }",
"public void postModule(final Module module, final String user, final String password) throws GrapesCommunicationException, AuthenticationException {\n final Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.moduleResourcePath());\n final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, module);\n\n client.destroy();\n if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){\n final String message = \"Failed to POST module\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n }"
] |
Synchronize the scroll positions of the scrollbars with the actual scroll
position of the content. | [
"private void maybeUpdateScrollbarPositions() {\r\n\r\n if (!isAttached()) {\r\n return;\r\n }\r\n\r\n if (m_scrollbar != null) {\r\n int vPos = getVerticalScrollPosition();\r\n if (m_scrollbar.getVerticalScrollPosition() != vPos) {\r\n m_scrollbar.setVerticalScrollPosition(vPos);\r\n }\r\n }\r\n }"
] | [
"private String formatRate(Rate value)\n {\n String result = null;\n if (value != null)\n {\n StringBuilder buffer = new StringBuilder(m_formats.getCurrencyFormat().format(value.getAmount()));\n buffer.append(\"/\");\n buffer.append(formatTimeUnit(value.getUnits()));\n result = buffer.toString();\n }\n return (result);\n }",
"public synchronized void initTaskSchedulerIfNot() {\n\n if (scheduler == null) {\n scheduler = Executors\n .newSingleThreadScheduledExecutor(DaemonThreadFactory\n .getInstance());\n CapacityAwareTaskScheduler runner = new CapacityAwareTaskScheduler();\n scheduler.scheduleAtFixedRate(runner,\n ParallecGlobalConfig.schedulerInitDelay,\n ParallecGlobalConfig.schedulerCheckInterval,\n TimeUnit.MILLISECONDS);\n logger.info(\"initialized daemon task scheduler to evaluate waitQ tasks.\");\n \n }\n }",
"@VisibleForTesting\n protected TextSymbolizer createTextSymbolizer(final PJsonObject styleJson) {\n final TextSymbolizer textSymbolizer = this.styleBuilder.createTextSymbolizer();\n\n // make sure that labels are also rendered if a part of the text would be outside\n // the view context, see http://docs.geoserver.org/stable/en/user/styling/sld-reference/labeling\n // .html#partials\n textSymbolizer.getOptions().put(\"partials\", \"true\");\n\n if (styleJson.has(JSON_LABEL)) {\n final Expression label =\n parseExpression(null, styleJson, JSON_LABEL,\n (final String labelValue) -> labelValue.replace(\"${\", \"\")\n .replace(\"}\", \"\"));\n\n textSymbolizer.setLabel(label);\n } else {\n return null;\n }\n\n textSymbolizer.setFont(createFont(textSymbolizer.getFont(), styleJson));\n\n if (styleJson.has(JSON_LABEL_ANCHOR_POINT_X) ||\n styleJson.has(JSON_LABEL_ANCHOR_POINT_Y) ||\n styleJson.has(JSON_LABEL_ALIGN) ||\n styleJson.has(JSON_LABEL_X_OFFSET) ||\n styleJson.has(JSON_LABEL_Y_OFFSET) ||\n styleJson.has(JSON_LABEL_ROTATION) ||\n styleJson.has(JSON_LABEL_PERPENDICULAR_OFFSET)) {\n textSymbolizer.setLabelPlacement(createLabelPlacement(styleJson));\n }\n\n if (!StringUtils.isEmpty(styleJson.optString(JSON_HALO_RADIUS)) ||\n !StringUtils.isEmpty(styleJson.optString(JSON_HALO_COLOR)) ||\n !StringUtils.isEmpty(styleJson.optString(JSON_HALO_OPACITY)) ||\n !StringUtils.isEmpty(styleJson.optString(JSON_LABEL_OUTLINE_WIDTH)) ||\n !StringUtils.isEmpty(styleJson.optString(JSON_LABEL_OUTLINE_COLOR))) {\n textSymbolizer.setHalo(createHalo(styleJson));\n }\n\n if (!StringUtils.isEmpty(styleJson.optString(JSON_FONT_COLOR)) ||\n !StringUtils.isEmpty(styleJson.optString(JSON_FONT_OPACITY))) {\n textSymbolizer.setFill(addFill(\n styleJson.optString(JSON_FONT_COLOR, \"black\"),\n styleJson.optString(JSON_FONT_OPACITY, \"1.0\")));\n }\n\n this.addVendorOptions(JSON_LABEL_ALLOW_OVERRUNS, styleJson, textSymbolizer);\n this.addVendorOptions(JSON_LABEL_AUTO_WRAP, styleJson, textSymbolizer);\n this.addVendorOptions(JSON_LABEL_CONFLICT_RESOLUTION, styleJson, textSymbolizer);\n this.addVendorOptions(JSON_LABEL_FOLLOW_LINE, styleJson, textSymbolizer);\n this.addVendorOptions(JSON_LABEL_GOODNESS_OF_FIT, styleJson, textSymbolizer);\n this.addVendorOptions(JSON_LABEL_GROUP, styleJson, textSymbolizer);\n this.addVendorOptions(JSON_LABEL_MAX_DISPLACEMENT, styleJson, textSymbolizer);\n this.addVendorOptions(JSON_LABEL_SPACE_AROUND, styleJson, textSymbolizer);\n\n return textSymbolizer;\n }",
"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 }",
"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}",
"private static void parseRessource(ArrayList<Shape> shapes,\n HashMap<String, JSONObject> flatJSON,\n String resourceId,\n Boolean keepGlossaryLink)\n throws JSONException {\n JSONObject modelJSON = flatJSON.get(resourceId);\n Shape current = getShapeWithId(modelJSON.getString(\"resourceId\"),\n shapes);\n\n parseStencil(modelJSON,\n current);\n\n parseProperties(modelJSON,\n current,\n keepGlossaryLink);\n parseOutgoings(shapes,\n modelJSON,\n current);\n parseChildShapes(shapes,\n modelJSON,\n current);\n parseDockers(modelJSON,\n current);\n parseBounds(modelJSON,\n current);\n parseTarget(shapes,\n modelJSON,\n current);\n }",
"private void setUserFieldValue(UDFAssignmentType udf, DataType dataType, Object value)\n {\n switch (dataType)\n {\n case DURATION:\n {\n udf.setTextValue(((Duration) value).toString());\n break;\n }\n\n case CURRENCY:\n {\n if (!(value instanceof Double))\n {\n value = Double.valueOf(((Number) value).doubleValue());\n }\n udf.setCostValue((Double) value);\n break;\n }\n\n case BINARY:\n {\n udf.setTextValue(\"\");\n break;\n }\n\n case STRING:\n {\n udf.setTextValue((String) value);\n break;\n }\n\n case DATE:\n {\n udf.setStartDateValue((Date) value);\n break;\n }\n\n case NUMERIC:\n {\n if (!(value instanceof Double))\n {\n value = Double.valueOf(((Number) value).doubleValue());\n }\n udf.setDoubleValue((Double) value);\n break;\n }\n\n case BOOLEAN:\n {\n udf.setIntegerValue(BooleanHelper.getBoolean((Boolean) value) ? Integer.valueOf(1) : Integer.valueOf(0));\n break;\n }\n\n case INTEGER:\n case SHORT:\n {\n udf.setIntegerValue(NumberHelper.getInteger((Number) value));\n break;\n }\n\n default:\n {\n throw new RuntimeException(\"Unconvertible data type: \" + dataType);\n }\n }\n }",
"public Where<T, ID> between(String columnName, Object low, Object high) throws SQLException {\n\t\taddClause(new Between(columnName, findColumnFieldType(columnName), low, high));\n\t\treturn this;\n\t}",
"public void setBundleActivator(String bundleActivator) {\n\t\tString old = mainAttributes.get(BUNDLE_ACTIVATOR);\n\t\tif (!bundleActivator.equals(old)) {\n\t\t\tthis.mainAttributes.put(BUNDLE_ACTIVATOR, bundleActivator);\n\t\t\tthis.modified = true;\n\t\t\tthis.bundleActivator = bundleActivator;\n\t\t}\n\t}"
] |
Is the given resource type id free?
@param id to be checked
@return boolean | [
"public static boolean isResourceTypeIdFree(int id) {\n\n try {\n OpenCms.getResourceManager().getResourceType(id);\n } catch (CmsLoaderException e) {\n return true;\n }\n return false;\n }"
] | [
"public static void mlock(Pointer addr, long len) {\n\n int res = Delegate.mlock(addr, new NativeLong(len));\n if(res != 0) {\n if(logger.isDebugEnabled()) {\n logger.debug(\"Mlock failed probably because of insufficient privileges, errno:\"\n + errno.strerror() + \", return value:\" + res);\n }\n } else {\n if(logger.isDebugEnabled())\n logger.debug(\"Mlock successfull\");\n\n }\n\n }",
"public static responderpolicylabel_binding get(nitro_service service, String labelname) throws Exception{\n\t\tresponderpolicylabel_binding obj = new responderpolicylabel_binding();\n\t\tobj.set_labelname(labelname);\n\t\tresponderpolicylabel_binding response = (responderpolicylabel_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static <T> void callInitializers(T instance, CreationalContext<T> creationalContext, BeanManagerImpl manager,\n Iterable<? extends MethodInjectionPoint<?, ?>> initializerMethods) {\n for (MethodInjectionPoint<?, ?> initializer : initializerMethods) {\n initializer.invoke(instance, null, manager, creationalContext, CreationException.class);\n }\n }",
"public QueryBuilder<T, ID> join(QueryBuilder<?, ?> joinedQueryBuilder) throws SQLException {\n\t\taddJoinInfo(JoinType.INNER, null, null, joinedQueryBuilder, JoinWhereOperation.AND);\n\t\treturn this;\n\t}",
"public ItemRequest<Task> addFollowers(String task) {\n \n String path = String.format(\"/tasks/%s/addFollowers\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }",
"public void detachMetadataCache(SlotReference slot) {\n MetadataCache oldCache = metadataCacheFiles.remove(slot);\n if (oldCache != null) {\n try {\n oldCache.close();\n } catch (IOException e) {\n logger.error(\"Problem closing metadata cache\", e);\n }\n deliverCacheUpdate(slot, null);\n }\n }",
"public static int lengthOfCodePoint(int codePoint)\n {\n if (codePoint < 0) {\n throw new InvalidCodePointException(codePoint);\n }\n if (codePoint < 0x80) {\n // normal ASCII\n // 0xxx_xxxx\n return 1;\n }\n if (codePoint < 0x800) {\n return 2;\n }\n if (codePoint < 0x1_0000) {\n return 3;\n }\n if (codePoint < 0x11_0000) {\n return 4;\n }\n // Per RFC3629, UTF-8 is limited to 4 bytes, so more bytes are illegal\n throw new InvalidCodePointException(codePoint);\n }",
"public List<DbComment> getComments(String entityId, String entityType) {\n return repositoryHandler.getComments(entityId, entityType);\n }",
"public String processProcedureArgument(Properties attributes) throws XDocletException\r\n {\r\n String id = attributes.getProperty(ATTRIBUTE_NAME);\r\n ProcedureArgumentDef argDef = _curClassDef.getProcedureArgument(id);\r\n String attrName;\r\n \r\n if (argDef == null)\r\n { \r\n argDef = new ProcedureArgumentDef(id);\r\n _curClassDef.addProcedureArgument(argDef);\r\n }\r\n\r\n attributes.remove(ATTRIBUTE_NAME);\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n argDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n return \"\";\r\n }"
] |
Read calendar hours and exception data.
@param calendar parent calendar
@param row calendar hours and exception data | [
"protected void processCalendarData(ProjectCalendar calendar, Row row)\n {\n int dayIndex = row.getInt(\"CD_DAY_OR_EXCEPTION\");\n if (dayIndex == 0)\n {\n processCalendarException(calendar, row);\n }\n else\n {\n processCalendarHours(calendar, row, dayIndex);\n }\n }"
] | [
"public static void addToString(\n SourceBuilder code,\n Datatype datatype,\n Map<Property, PropertyCodeGenerator> generatorsByProperty,\n boolean forPartial) {\n String typename = (forPartial ? \"partial \" : \"\") + datatype.getType().getSimpleName();\n Predicate<PropertyCodeGenerator> isOptional = generator -> {\n Initially initially = generator.initialState();\n return (initially == Initially.OPTIONAL || (initially == Initially.REQUIRED && forPartial));\n };\n boolean anyOptional = generatorsByProperty.values().stream().anyMatch(isOptional);\n boolean allOptional = generatorsByProperty.values().stream().allMatch(isOptional)\n && !generatorsByProperty.isEmpty();\n\n code.addLine(\"\")\n .addLine(\"@%s\", Override.class)\n .addLine(\"public %s toString() {\", String.class);\n if (allOptional) {\n bodyWithBuilderAndSeparator(code, datatype, generatorsByProperty, typename);\n } else if (anyOptional) {\n bodyWithBuilder(code, datatype, generatorsByProperty, typename, isOptional);\n } else {\n bodyWithConcatenation(code, generatorsByProperty, typename);\n }\n code.addLine(\"}\");\n }",
"private Properties parseFile(File file) throws InvalidDeclarationFileException {\n Properties properties = new Properties();\n InputStream is = null;\n try {\n is = new FileInputStream(file);\n properties.load(is);\n } catch (Exception e) {\n throw new InvalidDeclarationFileException(String.format(\"Error reading declaration file %s\", file.getAbsoluteFile()), e);\n } finally {\n if (is != null) {\n try {\n is.close();\n } catch (IOException e) {\n LOG.error(\"IOException thrown while trying to close the declaration file.\", e);\n }\n }\n }\n\n if (!properties.containsKey(Constants.ID)) {\n throw new InvalidDeclarationFileException(String.format(\"File %s is not a correct declaration, needs to contains an id property\", file.getAbsoluteFile()));\n }\n return properties;\n }",
"public void append(String str, String indentation) {\n\t\tif (indentation.isEmpty()) {\n\t\t\tappend(str);\n\t\t} else if (str != null)\n\t\t\tappend(indentation, str, segments.size());\n\t}",
"public int getCurrentMethodOrdinal(int overrideId, int pathId, String clientUUID, String[] filters) throws Exception {\n int currentOrdinal = 0;\n List<EnabledEndpoint> enabledEndpoints = getEnabledEndpoints(pathId, clientUUID, filters);\n for (EnabledEndpoint enabledEndpoint : enabledEndpoints) {\n if (enabledEndpoint.getOverrideId() == overrideId) {\n currentOrdinal++;\n }\n }\n return currentOrdinal;\n }",
"public FluoKeyValueGenerator set(RowColumnValue rcv) {\n setRow(rcv.getRow());\n setColumn(rcv.getColumn());\n setValue(rcv.getValue());\n return this;\n }",
"protected String generateCacheKey(\n CmsObject cms,\n String targetSiteRoot,\n String detailPagePart,\n String absoluteLink) {\n\n return cms.getRequestContext().getSiteRoot() + \":\" + targetSiteRoot + \":\" + detailPagePart + absoluteLink;\n }",
"public String build() {\n if (!root.containsKey(\"mdm\")) {\n insertCustomAlert();\n root.put(\"aps\", aps);\n }\n try {\n return mapper.writeValueAsString(root);\n } catch (final Exception e) {\n throw new RuntimeException(e);\n }\n }",
"public void set( int row , int col , double real , double imaginary ) {\n if( imaginary == 0 ) {\n set(row,col,real);\n } else {\n ops.set(mat,row,col, real, imaginary);\n }\n }",
"private void countCoordinateStatement(Statement statement,\n\t\t\tItemDocument itemDocument) {\n\t\tValue value = statement.getValue();\n\t\tif (!(value instanceof GlobeCoordinatesValue)) {\n\t\t\treturn;\n\t\t}\n\n\t\tGlobeCoordinatesValue coordsValue = (GlobeCoordinatesValue) value;\n\t\tif (!this.globe.equals((coordsValue.getGlobe()))) {\n\t\t\treturn;\n\t\t}\n\n\t\tint xCoord = (int) (((coordsValue.getLongitude() + 180.0) / 360.0) * this.width)\n\t\t\t\t% this.width;\n\t\tint yCoord = (int) (((coordsValue.getLatitude() + 90.0) / 180.0) * this.height)\n\t\t\t\t% this.height;\n\n\t\tif (xCoord < 0 || yCoord < 0 || xCoord >= this.width\n\t\t\t\t|| yCoord >= this.height) {\n\t\t\tSystem.out.println(\"Dropping out-of-range coordinate: \"\n\t\t\t\t\t+ coordsValue);\n\t\t\treturn;\n\t\t}\n\n\t\tcountCoordinates(xCoord, yCoord, itemDocument);\n\t\tthis.count += 1;\n\n\t\tif (this.count % 100000 == 0) {\n\t\t\treportProgress();\n\t\t\twriteImages();\n\t\t}\n\t}"
] |
Mark the top level deployment as being a JPA deployment. If the deployment is not a top level deployment the parent is
marked instead | [
"public static void mark(DeploymentUnit unit) {\n unit = DeploymentUtils.getTopDeploymentUnit(unit);\n unit.putAttachment(MARKER, Boolean.TRUE);\n }"
] | [
"protected Connection newConnectionFromDataSource(JdbcConnectionDescriptor jcd)\r\n throws LookupException\r\n {\r\n Connection retval = null;\r\n // use JNDI lookup\r\n DataSource ds = jcd.getDataSource();\r\n\r\n if (ds == null)\r\n {\r\n // [tomdz] Would it suffice to store the datasources only at the JCDs ?\r\n // Only possible problem would be serialization of the JCD because\r\n // the data source object in the JCD does not 'survive' this\r\n ds = (DataSource) dataSourceCache.get(jcd.getDatasourceName());\r\n }\r\n try\r\n {\r\n if (ds == null)\r\n {\r\n /**\r\n * this synchronization block won't be a big deal as we only look up\r\n * new datasources not found in the map.\r\n */\r\n synchronized (dataSourceCache)\r\n {\r\n InitialContext ic = new InitialContext();\r\n ds = (DataSource) ic.lookup(jcd.getDatasourceName());\r\n /**\r\n * cache the datasource lookup.\r\n */\r\n dataSourceCache.put(jcd.getDatasourceName(), ds);\r\n }\r\n }\r\n if (jcd.getUserName() == null)\r\n {\r\n retval = ds.getConnection();\r\n }\r\n else\r\n {\r\n retval = ds.getConnection(jcd.getUserName(), jcd.getPassWord());\r\n }\r\n }\r\n catch (SQLException sqlEx)\r\n {\r\n log.error(\"SQLException thrown while trying to get Connection from Datasource (\" +\r\n jcd.getDatasourceName() + \")\", sqlEx);\r\n throw new LookupException(\"SQLException thrown while trying to get Connection from Datasource (\" +\r\n jcd.getDatasourceName() + \")\", sqlEx);\r\n }\r\n catch (NamingException namingEx)\r\n {\r\n log.error(\"Naming Exception while looking up DataSource (\" + jcd.getDatasourceName() + \")\", namingEx);\r\n throw new LookupException(\"Naming Exception while looking up DataSource (\" + jcd.getDatasourceName() +\r\n \")\", namingEx);\r\n }\r\n // initialize connection\r\n initializeJdbcConnection(retval, jcd);\r\n if(log.isDebugEnabled()) log.debug(\"Create new connection using DataSource: \"+retval);\r\n return retval;\r\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 }",
"private File[] getFilesFromProperty(final String name, final Properties props) {\n String sep = WildFlySecurityManager.getPropertyPrivileged(\"path.separator\", null);\n String value = props.getProperty(name, null);\n if (value != null) {\n final String[] paths = value.split(Pattern.quote(sep));\n final int len = paths.length;\n final File[] files = new File[len];\n for (int i = 0; i < len; i++) {\n files[i] = new File(paths[i]);\n }\n return files;\n }\n return NO_FILES;\n }",
"private static boolean hasSelfPermissions(Context context, String... permissions) {\n for (String permission : permissions) {\n if (checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED) {\n return true;\n }\n }\n return false;\n }",
"protected void mergeHardcodedResultsFrom(Configuration otherConfiguration) {\r\n Map<Dotted, AnalysisResult> resultsMap = hardcodedResults.build().stream()\r\n .collect(Collectors.toMap(r -> r.className, r -> r));\r\n resultsMap.putAll(otherConfiguration.hardcodedResults());\r\n hardcodedResults = ImmutableSet.<AnalysisResult>builder().addAll(resultsMap.values());\r\n }",
"public static final Integer parseInteger(String value)\n {\n return (value == null || value.length() == 0 ? null : Integer.valueOf(Integer.parseInt(value)));\n }",
"public static boolean bidiagOuterBlocks( final int blockLength ,\n final DSubmatrixD1 A ,\n final double gammasU[],\n final double gammasV[])\n {\n// System.out.println(\"---------- Orig\");\n// A.original.print();\n\n int width = Math.min(blockLength,A.col1-A.col0);\n int height = Math.min(blockLength,A.row1-A.row0);\n\n int min = Math.min(width,height);\n\n for( int i = 0; i < min; i++ ) {\n //--- Apply reflector to the column\n\n // compute the householder vector\n if (!computeHouseHolderCol(blockLength, A, gammasU, i))\n return false;\n\n // apply to rest of the columns in the column block\n rank1UpdateMultR_Col(blockLength,A,i,gammasU[A.col0+i]);\n\n // apply to the top row block\n rank1UpdateMultR_TopRow(blockLength,A,i,gammasU[A.col0+i]);\n\n System.out.println(\"After column stuff\");\n A.original.print();\n\n //-- Apply reflector to the row\n if(!computeHouseHolderRow(blockLength,A,gammasV,i))\n return false;\n \n // apply to rest of the rows in the row block\n rank1UpdateMultL_Row(blockLength,A,i,i+1,gammasV[A.row0+i]);\n\n System.out.println(\"After update row\");\n A.original.print();\n\n // apply to the left column block\n // TODO THIS WON'T WORK!!!!!!!!!!!!!\n // Needs the whole matrix to have been updated by the left reflector to compute the correct solution\n// rank1UpdateMultL_LeftCol(blockLength,A,i,i+1,gammasV[A.row0+i]);\n\n System.out.println(\"After row stuff\");\n A.original.print();\n }\n\n return true;\n }",
"public static I_CmsSearchConfigurationPagination create(\n String pageParam,\n List<Integer> pageSizes,\n Integer pageNavLength) {\n\n return (pageParam != null) || (pageSizes != null) || (pageNavLength != null)\n ? new CmsSearchConfigurationPagination(pageParam, pageSizes, pageNavLength)\n : null;\n\n }",
"private static void attachToContent(Activity activity, MenuDrawer menuDrawer) {\n /**\n * Do not call mActivity#setContentView.\n * E.g. if using with a ListActivity, Activity#setContentView is overridden and dispatched to\n * MenuDrawer#setContentView, which then again would call Activity#setContentView.\n */\n ViewGroup content = (ViewGroup) activity.findViewById(android.R.id.content);\n content.removeAllViews();\n content.addView(menuDrawer, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);\n }"
] |
Converts a time represented as an integer to a Date instance.
@param time integer time
@return Date instance | [
"private Date getTimeFromInteger(Integer time)\n {\n Date result = null;\n\n if (time != null)\n {\n int minutes = time.intValue();\n int hours = minutes / 60;\n minutes -= (hours * 60);\n\n Calendar cal = DateHelper.popCalendar();\n cal.set(Calendar.MILLISECOND, 0);\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MINUTE, minutes);\n cal.set(Calendar.HOUR_OF_DAY, hours);\n result = cal.getTime();\n DateHelper.pushCalendar(cal);\n }\n\n return (result);\n }"
] | [
"public static snmpalarm[] get(nitro_service service) throws Exception{\n\t\tsnmpalarm obj = new snmpalarm();\n\t\tsnmpalarm[] response = (snmpalarm[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public static NotificationInfo getNotificationInfo(final Bundle extras) {\n if (extras == null) return new NotificationInfo(false, false);\n\n boolean fromCleverTap = extras.containsKey(Constants.NOTIFICATION_TAG);\n boolean shouldRender = fromCleverTap && extras.containsKey(\"nm\");\n return new NotificationInfo(fromCleverTap, shouldRender);\n }",
"@Override\n public SuggestionsInterface getSuggestionsInterface() {\n if (suggestionsInterface == null) {\n suggestionsInterface = new SuggestionsInterface(apiKey, sharedSecret, transport);\n }\n return suggestionsInterface;\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 static <R extends Resource<?>, U extends PaginatedResponse<R>> Flux<R> getResources(U response) {\n return Flux.fromIterable(response.getResources());\n }",
"public static Double checkLatitude(String name, Double latitude) {\n if (latitude == null) {\n throw new IndexException(\"{} required\", name);\n } else if (latitude < MIN_LATITUDE || latitude > MAX_LATITUDE) {\n throw new IndexException(\"{} must be in range [{}, {}], but found {}\",\n name,\n MIN_LATITUDE,\n MAX_LATITUDE,\n latitude);\n }\n return latitude;\n }",
"public static int[] Concatenate(int[] array, int[] array2) {\n int[] all = new int[array.length + array2.length];\n int idx = 0;\n\n //First array\n for (int i = 0; i < array.length; i++)\n all[idx++] = array[i];\n\n //Second array\n for (int i = 0; i < array2.length; i++)\n all[idx++] = array2[i];\n\n return all;\n }",
"public static LinearSolverDense<DMatrixRMaj> general(int numRows , int numCols ) {\n if( numRows == numCols )\n return linear(numRows);\n else\n return leastSquares(numRows,numCols);\n }",
"private void stop() {\n\t\tfor (int i = 0; i < mDownloadDispatchers.length; i++) {\n\t\t\tif (mDownloadDispatchers[i] != null) {\n\t\t\t\tmDownloadDispatchers[i].quit();\n\t\t\t}\n\t\t}\n\t}"
] |
Dump the buffer contents to a file
@param file
@throws IOException | [
"public void writeTo(File file) throws IOException {\n FileChannel channel = new FileOutputStream(file).getChannel();\n try {\n writeTo(channel);\n } finally {\n channel.close();\n }\n }"
] | [
"public static Map<FieldType, String> getDefaultAssignmentFieldMap()\n {\n Map<FieldType, String> map = new LinkedHashMap<FieldType, String>();\n\n map.put(AssignmentField.UNIQUE_ID, \"taskrsrc_id\");\n map.put(AssignmentField.GUID, \"guid\");\n map.put(AssignmentField.REMAINING_WORK, \"remain_qty\");\n map.put(AssignmentField.BASELINE_WORK, \"target_qty\");\n map.put(AssignmentField.ACTUAL_OVERTIME_WORK, \"act_ot_qty\");\n map.put(AssignmentField.BASELINE_COST, \"target_cost\");\n map.put(AssignmentField.ACTUAL_OVERTIME_COST, \"act_ot_cost\");\n map.put(AssignmentField.REMAINING_COST, \"remain_cost\");\n map.put(AssignmentField.ACTUAL_START, \"act_start_date\");\n map.put(AssignmentField.ACTUAL_FINISH, \"act_end_date\");\n map.put(AssignmentField.BASELINE_START, \"target_start_date\");\n map.put(AssignmentField.BASELINE_FINISH, \"target_end_date\");\n map.put(AssignmentField.ASSIGNMENT_DELAY, \"target_lag_drtn_hr_cnt\");\n\n return map;\n }",
"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 }",
"private void ensureIndexIsUnlocked(String dataDir) {\n\n Collection<File> lockFiles = new ArrayList<File>(2);\n lockFiles.add(\n new File(\n CmsFileUtil.addTrailingSeparator(CmsFileUtil.addTrailingSeparator(dataDir) + \"index\") + \"write.lock\"));\n lockFiles.add(\n new File(\n CmsFileUtil.addTrailingSeparator(CmsFileUtil.addTrailingSeparator(dataDir) + \"spellcheck\")\n + \"write.lock\"));\n for (File lockFile : lockFiles) {\n if (lockFile.exists()) {\n lockFile.delete();\n LOG.warn(\n \"Forcely unlocking index with data dir \\\"\"\n + dataDir\n + \"\\\" by removing file \\\"\"\n + lockFile.getAbsolutePath()\n + \"\\\".\");\n }\n }\n }",
"public static authenticationvserver_authenticationradiuspolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_authenticationradiuspolicy_binding obj = new authenticationvserver_authenticationradiuspolicy_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_authenticationradiuspolicy_binding response[] = (authenticationvserver_authenticationradiuspolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"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}",
"protected boolean isStoreValid() {\n boolean result = false;\n String requestURI = this.request.getUri();\n this.storeName = parseStoreName(requestURI);\n if(storeName != null) {\n result = true;\n } else {\n logger.error(\"Error when validating request. Missing store name.\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Missing store name. Critical error.\");\n }\n return result;\n }",
"public static void writeObject(File file, Object object) throws IOException {\n FileOutputStream fileOut = new FileOutputStream(file);\n ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(fileOut));\n try {\n out.writeObject(object);\n out.flush();\n // Force sync\n fileOut.getFD().sync();\n } finally {\n IoUtils.safeClose(out);\n }\n }",
"public int sharedSegments(Triangle t2) {\n\t\tint counter = 0;\n\n\t\tif(a.equals(t2.a)) {\n\t\t\tcounter++;\n\t\t}\n\t\tif(a.equals(t2.b)) {\n\t\t\tcounter++;\n\t\t}\n\t\tif(a.equals(t2.c)) {\n\t\t\tcounter++;\n\t\t}\n\t\tif(b.equals(t2.a)) {\n\t\t\tcounter++;\n\t\t}\n\t\tif(b.equals(t2.b)) {\n\t\t\tcounter++;\n\t\t}\n\t\tif(b.equals(t2.c)) {\n\t\t\tcounter++;\n\t\t}\n\t\tif(c.equals(t2.a)) {\n\t\t\tcounter++;\n\t\t}\n\t\tif(c.equals(t2.b)) {\n\t\t\tcounter++;\n\t\t}\n\t\tif(c.equals(t2.c)) {\n\t\t\tcounter++;\n\t\t}\n\n\t\treturn counter;\n\t}",
"public NodeList getAt(String name) {\n NodeList answer = new NodeList();\n for (Object child : this) {\n if (child instanceof Node) {\n Node childNode = (Node) child;\n Object temp = childNode.get(name);\n if (temp instanceof Collection) {\n answer.addAll((Collection) temp);\n } else {\n answer.add(temp);\n }\n }\n }\n return answer;\n }"
] |
Get a subset of the attributes of the provided class. An attribute is each public field in the class
or super class.
@param classToInspect the class to inspect
@param filter a predicate that returns true when a attribute should be kept in resulting
collection. | [
"public static Collection<Field> getAttributes(\n final Class<?> classToInspect, final Predicate<Field> filter) {\n Set<Field> allFields = new HashSet<>();\n getAllAttributes(classToInspect, allFields, Function.identity(), filter);\n return allFields;\n }"
] | [
"private File getDisabledMarkerFile(long version) throws PersistenceFailureException {\n File[] versionDirArray = ReadOnlyUtils.getVersionDirs(rootDir, version, version);\n if (versionDirArray.length == 0) {\n throw new PersistenceFailureException(\"getDisabledMarkerFile did not find the requested version directory\" +\n \" on disk. Version: \" + version + \", rootDir: \" + rootDir);\n }\n File disabledMarkerFile = new File(versionDirArray[0], DISABLED_MARKER_NAME);\n return disabledMarkerFile;\n }",
"@Override\n\tpublic Inet6Address toInetAddress() {\n\t\tif(hasZone()) {\n\t\t\tInet6Address result;\n\t\t\tif(hasNoValueCache() || (result = valueCache.inetAddress) == null) {\n\t\t\t\tvalueCache.inetAddress = result = (Inet6Address) toInetAddressImpl(getBytes());\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\t\treturn (Inet6Address) super.toInetAddress();\n\t}",
"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 }",
"private void handleMultiInstanceEncapResponse(\r\n\t\t\tSerialMessage serialMessage, int offset) {\r\n\t\tlogger.trace(\"Process Multi-instance Encapsulation\");\r\n\t\tint instance = serialMessage.getMessagePayloadByte(offset);\r\n\t\tint commandClassCode = serialMessage.getMessagePayloadByte(offset + 1);\r\n\t\tCommandClass commandClass = CommandClass.getCommandClass(commandClassCode);\r\n\r\n\t\tif (commandClass == null) {\r\n\t\t\tlogger.error(String.format(\"Unsupported command class 0x%02x\", commandClassCode));\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tlogger.debug(String.format(\"Node %d Requested Command Class = %s (0x%02x)\", this.getNode().getNodeId(), commandClass.getLabel() , commandClassCode));\r\n\t\tZWaveCommandClass zwaveCommandClass = this.getNode().getCommandClass(commandClass);\r\n\t\t\r\n\t\tif (zwaveCommandClass == null) {\r\n\t\t\tlogger.error(String.format(\"Unsupported command class %s (0x%02x)\", commandClass.getLabel(), commandClassCode));\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tlogger.debug(String.format(\"Node %d, Instance = %d, calling handleApplicationCommandRequest.\", this.getNode().getNodeId(), instance));\r\n\t\tzwaveCommandClass.handleApplicationCommandRequest(serialMessage, offset+ 3, instance);\r\n\t}",
"public CodePage getCodePage(int field)\n {\n CodePage result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n result = CodePage.getInstance(m_fields[field]);\n }\n else\n {\n result = CodePage.getInstance(null);\n }\n\n return (result);\n }",
"public static boolean containsUid(IdRange[] idRanges, long uid) {\r\n if (null != idRanges && idRanges.length > 0) {\r\n for (IdRange range : idRanges) {\r\n if (range.includes(uid)) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n }",
"public static File createDir(String dir) {\n // create outdir\n File directory = null;\n if(dir != null) {\n directory = new File(dir);\n if(!(directory.exists() || directory.mkdir())) {\n Utils.croak(\"Can't find or create directory \" + dir);\n }\n }\n return directory;\n }",
"public void setIdleMaxAge(long idleMaxAge, TimeUnit timeUnit) {\n\t\tthis.idleMaxAgeInSeconds = TimeUnit.SECONDS.convert(idleMaxAge, checkNotNull(timeUnit)); \n\t}",
"public void rotateWithPivot(float quatW, float quatX, float quatY,\n float quatZ, float pivotX, float pivotY, float pivotZ) {\n NativeTransform.rotateWithPivot(getNative(), quatW, quatX, quatY,\n quatZ, pivotX, pivotY, pivotZ);\n }"
] |
Generate the next permutation and return an array containing
the elements in the appropriate order.
@see #nextPermutationAsArray(Object[])
@see #nextPermutationAsList()
@return The next permutation as an array. | [
"@SuppressWarnings(\"unchecked\")\n public T[] nextPermutationAsArray()\n {\n T[] permutation = (T[]) Array.newInstance(elements.getClass().getComponentType(),\n permutationIndices.length);\n return nextPermutationAsArray(permutation);\n }"
] | [
"protected void eigenvalue2by2( int x1 ) {\n double a = diag[x1];\n double b = off[x1];\n double c = diag[x1+1];\n\n // normalize to reduce overflow\n double absA = Math.abs(a);\n double absB = Math.abs(b);\n double absC = Math.abs(c);\n\n double scale = absA > absB ? absA : absB;\n if( absC > scale ) scale = absC;\n\n // see if it is a pathological case. the diagonal must already be zero\n // and the eigenvalues are all zero. so just return\n if( scale == 0 ) {\n off[x1] = 0;\n diag[x1] = 0;\n diag[x1+1] = 0;\n return;\n }\n\n a /= scale;\n b /= scale;\n c /= scale;\n\n eigenSmall.symm2x2_fast(a,b,c);\n\n off[x1] = 0;\n diag[x1] = scale*eigenSmall.value0.real;\n diag[x1+1] = scale*eigenSmall.value1.real;\n }",
"protected Violation createViolation(SourceCode sourceCode, ASTNode node, String message) {\n String sourceLine = sourceCode.line(node.getLineNumber()-1);\n return createViolation(node.getLineNumber(), sourceLine, message);\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 boolean addType(TypeDefinition type) {\n\n if (type == null) {\n return false;\n }\n\n if (type.getBaseTypeId() == null) {\n return false;\n }\n\n // find base type\n TypeDefinition baseType = null;\n if (type.getBaseTypeId() == BaseTypeId.CMIS_DOCUMENT) {\n baseType = copyTypeDefintion(m_types.get(DOCUMENT_TYPE_ID).getTypeDefinition());\n } else if (type.getBaseTypeId() == BaseTypeId.CMIS_FOLDER) {\n baseType = copyTypeDefintion(m_types.get(FOLDER_TYPE_ID).getTypeDefinition());\n } else if (type.getBaseTypeId() == BaseTypeId.CMIS_RELATIONSHIP) {\n baseType = copyTypeDefintion(m_types.get(RELATIONSHIP_TYPE_ID).getTypeDefinition());\n } else if (type.getBaseTypeId() == BaseTypeId.CMIS_POLICY) {\n baseType = copyTypeDefintion(m_types.get(POLICY_TYPE_ID).getTypeDefinition());\n } else {\n return false;\n }\n\n AbstractTypeDefinition newType = (AbstractTypeDefinition)copyTypeDefintion(type);\n\n // copy property definition\n for (PropertyDefinition<?> propDef : baseType.getPropertyDefinitions().values()) {\n ((AbstractPropertyDefinition<?>)propDef).setIsInherited(Boolean.TRUE);\n newType.addPropertyDefinition(propDef);\n }\n\n // add it\n addTypeInternal(newType);\n return true;\n }",
"public Triple<Double, Integer, Integer> getAccuracyInfo()\r\n {\r\n int totalCorrect = tokensCorrect;\r\n int totalWrong = tokensCount - tokensCorrect;\r\n return new Triple<Double, Integer, Integer>((((double) totalCorrect) / tokensCount),\r\n totalCorrect, totalWrong);\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 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 CurrencyQueryBuilder setNumericCodes(int... codes) {\n return set(CurrencyQuery.KEY_QUERY_NUMERIC_CODES,\n Arrays.stream(codes).boxed().collect(Collectors.toList()));\n }",
"private void processRanges(List<DateRange> ranges, ProjectCalendarDateRanges container)\n {\n if (ranges != null)\n {\n for (DateRange range : ranges)\n {\n container.addRange(range);\n }\n }\n }"
] |
Add a calendar node.
@param parentNode parent node
@param calendar calendar | [
"private void addCalendar(MpxjTreeNode parentNode, final ProjectCalendar calendar)\n {\n MpxjTreeNode calendarNode = new MpxjTreeNode(calendar, CALENDAR_EXCLUDED_METHODS)\n {\n @Override public String toString()\n {\n return calendar.getName();\n }\n };\n parentNode.add(calendarNode);\n\n MpxjTreeNode daysFolder = new MpxjTreeNode(\"Days\");\n calendarNode.add(daysFolder);\n\n for (Day day : Day.values())\n {\n addCalendarDay(daysFolder, calendar, day);\n }\n\n MpxjTreeNode exceptionsFolder = new MpxjTreeNode(\"Exceptions\");\n calendarNode.add(exceptionsFolder);\n\n for (ProjectCalendarException exception : calendar.getCalendarExceptions())\n {\n addCalendarException(exceptionsFolder, exception);\n }\n }"
] | [
"public static List<ClassReference> analyze(WildcardImportResolver importResolver, Set<String> libraryPaths, Set<String> sourcePaths,\n Path sourceFile)\n {\n ASTParser parser = ASTParser.newParser(AST.JLS11);\n parser.setEnvironment(libraryPaths.toArray(new String[libraryPaths.size()]), sourcePaths.toArray(new String[sourcePaths.size()]), null, true);\n parser.setBindingsRecovery(false);\n parser.setResolveBindings(true);\n Map options = JavaCore.getOptions();\n JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);\n parser.setCompilerOptions(options);\n String fileName = sourceFile.getFileName().toString();\n parser.setUnitName(fileName);\n try\n {\n parser.setSource(FileUtils.readFileToString(sourceFile.toFile()).toCharArray());\n }\n catch (IOException e)\n {\n throw new ASTException(\"Failed to get source for file: \" + sourceFile.toString() + \" due to: \" + e.getMessage(), e);\n }\n parser.setKind(ASTParser.K_COMPILATION_UNIT);\n CompilationUnit cu = (CompilationUnit) parser.createAST(null);\n ReferenceResolvingVisitor visitor = new ReferenceResolvingVisitor(importResolver, cu, sourceFile.toString());\n cu.accept(visitor);\n return visitor.getJavaClassReferences();\n }",
"protected void setJsonValue(JsonObjectBuilder builder, T value) {\n // I don't like this - there should really be a way to construct a disconnected JSONValue...\n if (value instanceof Boolean) {\n builder.add(\"value\", (Boolean) value);\n } else if (value instanceof Double) {\n builder.add(\"value\", (Double) value);\n } else if (value instanceof Integer) {\n builder.add(\"value\", (Integer) value);\n } else if (value instanceof Long) {\n builder.add(\"value\", (Long) value);\n } else if (value instanceof BigInteger) {\n builder.add(\"value\", (BigInteger) value);\n } else if (value instanceof BigDecimal) {\n builder.add(\"value\", (BigDecimal) value);\n } else if (value == null) {\n builder.addNull(\"value\");\n } else {\n builder.add(\"value\", value.toString());\n }\n }",
"public List<String> getListAttribute(String section, String name) {\n return split(getAttribute(section, name));\n }",
"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 void setYearlyAbsoluteFromDate(Date date)\n {\n if (date != null)\n {\n Calendar cal = DateHelper.popCalendar(date);\n m_dayNumber = Integer.valueOf(cal.get(Calendar.DAY_OF_MONTH));\n m_monthNumber = Integer.valueOf(cal.get(Calendar.MONTH) + 1);\n DateHelper.pushCalendar(cal);\n }\n }",
"Map<String, EntityDocument> getEntityDocumentMap(int numOfEntities,\n\t\t\tWbGetEntitiesActionData properties)\n\t\t\tthrows MediaWikiApiErrorException, IOException {\n\t\tif (numOfEntities == 0) {\n\t\t\treturn Collections.emptyMap();\n\t\t}\n\t\tconfigureProperties(properties);\n\t\treturn this.wbGetEntitiesAction.wbGetEntities(properties);\n\t}",
"public StandaloneCommandBuilder setDebug(final boolean suspend, final int port) {\n debugArg = String.format(DEBUG_FORMAT, (suspend ? \"y\" : \"n\"), port);\n return this;\n }",
"private String formatDate(Date date) {\n\n if (null == m_dateFormat) {\n m_dateFormat = DateFormat.getDateInstance(\n 0,\n OpenCms.getWorkplaceManager().getWorkplaceLocale(getCmsObject()));\n }\n return m_dateFormat.format(date);\n }",
"public static void main(String[] args) {\r\n TreebankLanguagePack tlp = new PennTreebankLanguagePack();\r\n System.out.println(\"Start symbol: \" + tlp.startSymbol());\r\n String start = tlp.startSymbol();\r\n System.out.println(\"Should be true: \" + (tlp.isStartSymbol(start)));\r\n String[] strs = {\"-\", \"-LLB-\", \"NP-2\", \"NP=3\", \"NP-LGS\", \"NP-TMP=3\"};\r\n for (String str : strs) {\r\n System.out.println(\"String: \" + str + \" basic: \" + tlp.basicCategory(str) + \" basicAndFunc: \" + tlp.categoryAndFunction(str));\r\n }\r\n }"
] |
Un-serialize a Json into Module
@param module String
@return Module
@throws IOException | [
"public static Module unserializeModule(final String module) throws IOException {\n final ObjectMapper mapper = new ObjectMapper();\n mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);\n return mapper.readValue(module, Module.class);\n }"
] | [
"public static String getGetterName(String propertyName, Class type) {\n String prefix = type == boolean.class || type == Boolean.class ? \"is\" : \"get\";\n return prefix + MetaClassHelper.capitalize(propertyName);\n }",
"public static authenticationradiuspolicy_vpnglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationradiuspolicy_vpnglobal_binding obj = new authenticationradiuspolicy_vpnglobal_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationradiuspolicy_vpnglobal_binding response[] = (authenticationradiuspolicy_vpnglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public double[] getRegressionCoefficients(RandomVariable value) {\n\t\tif(basisFunctions.length == 0) {\n\t\t\treturn new double[] { };\n\t\t}\n\t\telse if(basisFunctions.length == 1) {\n\t\t\t/*\n\t\t\t * Regression with one basis function is just a projection on that vector. <b,x>/<b,b>\n\t\t\t */\n\t\t\treturn new double[] { value.mult(basisFunctions[0]).getAverage() / basisFunctions[0].squared().getAverage() };\n\t\t}\n\t\telse if(basisFunctions.length == 2) {\n\t\t\t/*\n\t\t\t * Regression with two basis functions can be solved explicitly if determinant != 0 (otherwise we will fallback to SVD)\n\t\t\t */\n\t\t\tdouble a = basisFunctions[0].squared().getAverage();\n\t\t\tdouble b = basisFunctions[0].mult(basisFunctions[1]).average().squared().doubleValue();\n\t\t\tdouble c = b;\n\t\t\tdouble d = basisFunctions[1].squared().getAverage();\n\n\t\t\tdouble determinant = (a * d - b * c);\n\t\t\tif(determinant != 0) {\n\t\t\t\tdouble x = value.mult(basisFunctions[0]).getAverage();\n\t\t\t\tdouble y = value.mult(basisFunctions[1]).getAverage();\n\n\t\t\t\tdouble alpha0 = (d * x - b * y) / determinant;\n\t\t\t\tdouble alpha1 = (a * y - c * x) / determinant;\n\n\t\t\t\treturn new double[] { alpha0, alpha1 };\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * General case\n\t\t */\n\n\t\t// Build regression matrix\n\t\tdouble[][] BTB = new double[basisFunctions.length][basisFunctions.length];\n\t\tfor(int i=0; i<basisFunctions.length; i++) {\n\t\t\tfor(int j=0; j<=i; j++) {\n\t\t\t\tdouble covariance = basisFunctions[i].mult(basisFunctions[j]).getAverage();\n\t\t\t\tBTB[i][j] = covariance;\n\t\t\t\tBTB[j][i] = covariance;\n\t\t\t}\n\t\t}\n\n\t\tdouble[] BTX = new double[basisFunctions.length];\n\t\tfor(int i=0; i<basisFunctions.length; i++) {\n\t\t\tdouble covariance = basisFunctions[i].mult(value).getAverage();\n\t\t\tBTX[i] = covariance;\n\t\t}\n\n\t\treturn LinearAlgebra.solveLinearEquationLeastSquare(BTB, BTX);\n\t}",
"public String addComment(String photosetId, String commentText) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ADD_COMMENT);\r\n\r\n parameters.put(\"photoset_id\", photosetId);\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 // response:\r\n // <comment id=\"97777-12492-72057594037942601\" />\r\n Element commentElement = response.getPayload();\r\n return commentElement.getAttribute(\"id\");\r\n }",
"public static Key toKey(RowColumn rc) {\n if ((rc == null) || (rc.getRow().equals(Bytes.EMPTY))) {\n return null;\n }\n Text row = ByteUtil.toText(rc.getRow());\n if ((rc.getColumn().equals(Column.EMPTY)) || !rc.getColumn().isFamilySet()) {\n return new Key(row);\n }\n Text cf = ByteUtil.toText(rc.getColumn().getFamily());\n if (!rc.getColumn().isQualifierSet()) {\n return new Key(row, cf);\n }\n Text cq = ByteUtil.toText(rc.getColumn().getQualifier());\n if (!rc.getColumn().isVisibilitySet()) {\n return new Key(row, cf, cq);\n }\n Text cv = ByteUtil.toText(rc.getColumn().getVisibility());\n return new Key(row, cf, cq, cv);\n }",
"public static Optional<Tag> parse(final String httpTag) {\r\n Tag result = null;\r\n boolean weak = false;\r\n String internal = httpTag;\r\n\r\n if (internal.startsWith(\"W/\")) {\r\n weak = true;\r\n internal = internal.substring(2);\r\n }\r\n\r\n if (internal.startsWith(\"\\\"\") && internal.endsWith(\"\\\"\")) {\r\n result = new Tag(\r\n internal.substring(1, internal.length() - 1), weak);\r\n }\r\n else if (internal.equals(\"*\")) {\r\n result = new Tag(\"*\", weak);\r\n }\r\n\r\n return Optional.ofNullable(result);\r\n }",
"public PagedList<V> convert(final PagedList<U> uList) {\n if (uList == null || uList.isEmpty()) {\n return new PagedList<V>() {\n @Override\n public Page<V> nextPage(String s) throws RestException, IOException {\n return null;\n }\n };\n }\n Page<U> uPage = uList.currentPage();\n final PageImpl<V> vPage = new PageImpl<>();\n vPage.setNextPageLink(uPage.nextPageLink());\n vPage.setItems(new ArrayList<V>());\n loadConvertedList(uPage, vPage);\n return new PagedList<V>(vPage) {\n @Override\n public Page<V> nextPage(String nextPageLink) throws RestException, IOException {\n Page<U> uPage = uList.nextPage(nextPageLink);\n final PageImpl<V> vPage = new PageImpl<>();\n vPage.setNextPageLink(uPage.nextPageLink());\n vPage.setItems(new ArrayList<V>());\n loadConvertedList(uPage, vPage);\n return vPage;\n }\n };\n }",
"public HttpServer build() {\n checkNotNull(baseUri);\n StandaloneWebConverterConfiguration configuration = makeConfiguration();\n // The configuration has to be configured both by a binder to make it injectable\n // and directly in order to trigger life cycle methods on the deployment container.\n ResourceConfig resourceConfig = ResourceConfig\n .forApplication(new WebConverterApplication(configuration))\n .register(configuration);\n if (sslContext == null) {\n return GrizzlyHttpServerFactory.createHttpServer(baseUri, resourceConfig);\n } else {\n return GrizzlyHttpServerFactory.createHttpServer(baseUri, resourceConfig, true, new SSLEngineConfigurator(sslContext));\n }\n }",
"private void\n executeSubBatch(final int batchId,\n RebalanceBatchPlanProgressBar progressBar,\n final Cluster batchRollbackCluster,\n final List<StoreDefinition> batchRollbackStoreDefs,\n final List<RebalanceTaskInfo> rebalanceTaskPlanList,\n boolean hasReadOnlyStores,\n boolean hasReadWriteStores,\n boolean finishedReadOnlyStores) {\n RebalanceUtils.printBatchLog(batchId,\n logger,\n \"Submitting rebalance tasks \");\n\n // Get an ExecutorService in place used for submitting our tasks\n ExecutorService service = RebalanceUtils.createExecutors(maxParallelRebalancing);\n\n // Sub-list of the above list\n final List<RebalanceTask> failedTasks = Lists.newArrayList();\n final List<RebalanceTask> incompleteTasks = Lists.newArrayList();\n\n // Semaphores for donor nodes - To avoid multiple disk sweeps\n Map<Integer, Semaphore> donorPermits = new HashMap<Integer, Semaphore>();\n for(Node node: batchRollbackCluster.getNodes()) {\n donorPermits.put(node.getId(), new Semaphore(1));\n }\n\n try {\n // List of tasks which will run asynchronously\n List<RebalanceTask> allTasks = executeTasks(batchId,\n progressBar,\n service,\n rebalanceTaskPlanList,\n donorPermits);\n RebalanceUtils.printBatchLog(batchId,\n logger,\n \"All rebalance tasks submitted\");\n\n // Wait and shutdown after (infinite) timeout\n RebalanceUtils.executorShutDown(service, Long.MAX_VALUE);\n RebalanceUtils.printBatchLog(batchId,\n logger,\n \"Finished waiting for executors\");\n\n // Collects all failures + incomplete tasks from the rebalance\n // tasks.\n List<Exception> failures = Lists.newArrayList();\n for(RebalanceTask task: allTasks) {\n if(task.hasException()) {\n failedTasks.add(task);\n failures.add(task.getError());\n } else if(!task.isComplete()) {\n incompleteTasks.add(task);\n }\n }\n\n if(failedTasks.size() > 0) {\n throw new VoldemortRebalancingException(\"Rebalance task terminated unsuccessfully on tasks \"\n + failedTasks,\n failures);\n }\n\n // If there were no failures, then we could have had a genuine\n // timeout ( Rebalancing took longer than the operator expected ).\n // We should throw a VoldemortException and not a\n // VoldemortRebalancingException ( which will start reverting\n // metadata ). The operator may want to manually then resume the\n // process.\n if(incompleteTasks.size() > 0) {\n throw new VoldemortException(\"Rebalance tasks are still incomplete / running \"\n + incompleteTasks);\n }\n\n } catch(VoldemortRebalancingException e) {\n\n logger.error(\"Failure while migrating partitions for rebalance task \"\n + batchId);\n\n if(hasReadOnlyStores && hasReadWriteStores\n && finishedReadOnlyStores) {\n // Case 0\n adminClient.rebalanceOps.rebalanceStateChange(null,\n batchRollbackCluster,\n null,\n batchRollbackStoreDefs,\n null,\n true,\n true,\n false,\n false,\n false);\n } else if(hasReadWriteStores && finishedReadOnlyStores) {\n // Case 4\n adminClient.rebalanceOps.rebalanceStateChange(null,\n batchRollbackCluster,\n null,\n batchRollbackStoreDefs,\n null,\n false,\n true,\n false,\n false,\n false);\n }\n\n throw e;\n\n } finally {\n if(!service.isShutdown()) {\n RebalanceUtils.printErrorLog(batchId,\n logger,\n \"Could not shutdown service cleanly for rebalance task \"\n + batchId,\n null);\n service.shutdownNow();\n }\n }\n }"
] |
If a given x is into an interval of the partition, this method returns the reference point of the corresponding interval.
If the given x is not contained in any interval of the partition, this method returns x.
@param x The point of interest.
@return The discretized value. | [
"public double d(double x){\n\t\tint intervalNumber =getIntervalNumber(x);\n\t\tif (intervalNumber==0 || intervalNumber==points.length) {\n\t\t\treturn x;\n\t\t}\n\t\treturn getIntervalReferencePoint(intervalNumber-1);\n\t}"
] | [
"@Override\n protected Deque<Step> childValue(Deque<Step> parentValue) {\n Deque<Step> queue = new LinkedList<>();\n queue.add(parentValue.getFirst());\n return queue;\n }",
"@Override\n\tpublic void Invoke(final String method, JSONArray args,\n\t\t\tHubInvokeCallback callback) {\n\n\t\tif (method == null)\n {\n throw new IllegalArgumentException(\"method\");\n }\n\n if (args == null)\n {\n throw new IllegalArgumentException(\"args\");\n }\n\n final String callbackId = mConnection.RegisterCallback(callback);\n\n HubInvocation hubData = new HubInvocation(mHubName, method, args, callbackId);\n\n String value = hubData.Serialize();\n\n mConnection.Send(value, new SendCallback() \n {\n\t\t\t@Override\n\t\t\tpublic void OnSent(CharSequence messageSent) {\n\t\t\t\tLog.v(TAG, \"Invoke of \" + method + \"sent to \" + mHubName);\n\t\t\t\t// callback.OnSent() ??!?!?\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void OnError(Exception ex) {\n\t\t\t\t// TODO Cancel the callback\n\t\t\t\tLog.e(TAG, \"Failed to invoke \" + method + \"on \" + mHubName);\n\t\t\t\tmConnection.RemoveCallback(callbackId);\n\t\t\t\t// callback.OnError() ?!?!?\n\t\t\t}\n });\n }",
"public static 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}",
"private void ensureLength(FieldDescriptorDef fieldDef, String checkLevel)\r\n {\r\n if (!fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_LENGTH))\r\n {\r\n String defaultLength = JdbcTypeHelper.getDefaultLengthFor(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));\r\n\r\n if (defaultLength != null)\r\n {\r\n LogHelper.warn(true,\r\n FieldDescriptorConstraints.class,\r\n \"ensureLength\",\r\n \"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" has no length setting though its jdbc type requires it (in most databases); using default length of \"+defaultLength);\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_LENGTH, defaultLength);\r\n }\r\n }\r\n }",
"public CmsMessageContainer validateWithMessage() {\n\n if (m_parsingFailed) {\n return Messages.get().container(Messages.ERR_SERIALDATE_INVALID_VALUE_0);\n }\n if (!isStartSet()) {\n return Messages.get().container(Messages.ERR_SERIALDATE_START_MISSING_0);\n }\n if (!isEndValid()) {\n return Messages.get().container(Messages.ERR_SERIALDATE_END_BEFORE_START_0);\n }\n String key = validatePattern();\n if (null != key) {\n return Messages.get().container(key);\n }\n key = validateDuration();\n if (null != key) {\n return Messages.get().container(key);\n }\n if (hasTooManyEvents()) {\n return Messages.get().container(\n Messages.ERR_SERIALDATE_TOO_MANY_EVENTS_1,\n Integer.valueOf(CmsSerialDateUtil.getMaxEvents()));\n }\n return null;\n }",
"public int blast(InputStream input, OutputStream output) throws IOException\n {\n m_input = input;\n m_output = output;\n\n int lit; /* true if literals are coded */\n int dict; /* log2(dictionary size) - 6 */\n int symbol; /* decoded symbol, extra bits for distance */\n int len; /* length for copy */\n int dist; /* distance for copy */\n int copy; /* copy counter */\n //unsigned char *from, *to; /* copy pointers */\n\n /* read header */\n lit = bits(8);\n if (lit > 1)\n {\n return -1;\n }\n dict = bits(8);\n if (dict < 4 || dict > 6)\n {\n return -2;\n }\n\n /* decode literals and length/distance pairs */\n do\n {\n if (bits(1) != 0)\n {\n /* get length */\n symbol = decode(LENCODE);\n len = BASE[symbol] + bits(EXTRA[symbol]);\n if (len == 519)\n {\n break; /* end code */\n }\n\n /* get distance */\n symbol = len == 2 ? 2 : dict;\n dist = decode(DISTCODE) << symbol;\n dist += bits(symbol);\n dist++;\n if (m_first != 0 && dist > m_next)\n {\n return -3; /* distance too far back */\n }\n\n /* copy length bytes from distance bytes back */\n do\n {\n //to = m_out + m_next;\n int to = m_next;\n int from = to - dist;\n copy = MAXWIN;\n if (m_next < dist)\n {\n from += copy;\n copy = dist;\n }\n copy -= m_next;\n if (copy > len)\n {\n copy = len;\n }\n len -= copy;\n m_next += copy;\n do\n {\n //*to++ = *from++;\n m_out[to++] = m_out[from++];\n }\n while (--copy != 0);\n if (m_next == MAXWIN)\n {\n //if (s->outfun(s->outhow, s->out, s->next)) return 1;\n m_output.write(m_out, 0, m_next);\n m_next = 0;\n m_first = 0;\n }\n }\n while (len != 0);\n }\n else\n {\n /* get literal and write it */\n symbol = lit != 0 ? decode(LITCODE) : bits(8);\n m_out[m_next++] = (byte) symbol;\n if (m_next == MAXWIN)\n {\n //if (s->outfun(s->outhow, s->out, s->next)) return 1;\n m_output.write(m_out, 0, m_next);\n m_next = 0;\n m_first = 0;\n }\n }\n }\n while (true);\n\n if (m_next != 0)\n {\n m_output.write(m_out, 0, m_next);\n }\n\n return 0;\n }",
"public static String dump(final int displayOffset, final byte[] data, final int offset, final int len)\n {\n StringBuilder sb = new StringBuilder();\n Formatter formatter = new Formatter(sb);\n StringBuilder ascii = new StringBuilder();\n\n int dataNdx = offset;\n final int maxDataNdx = offset + len;\n final int lines = (len + 16) / 16;\n for (int i = 0; i < lines; i++) {\n ascii.append(\" |\");\n formatter.format(\"%08x \", displayOffset + (i * 16));\n\n for (int j = 0; j < 16; j++) {\n if (dataNdx < maxDataNdx) {\n byte b = data[dataNdx++];\n formatter.format(\"%02x \", b);\n ascii.append((b > MIN_VISIBLE && b < MAX_VISIBLE) ? (char) b : ' ');\n }\n else {\n sb.append(\" \");\n }\n\n if (j == 7) {\n sb.append(' ');\n }\n }\n\n ascii.append('|');\n sb.append(ascii).append('\\n');\n ascii.setLength(0);\n }\n\n formatter.close();\n return sb.toString();\n }",
"private ClassNode getGenericsResolvedTypeOfFieldOrProperty(AnnotatedNode an, ClassNode type) {\n if (!type.isUsingGenerics()) return type;\n Map<String, GenericsType> connections = new HashMap();\n //TODO: inner classes mean a different this-type. This is ignored here!\n extractGenericsConnections(connections, typeCheckingContext.getEnclosingClassNode(), an.getDeclaringClass());\n type= applyGenericsContext(connections, type);\n return type;\n }",
"private void writeCustomFields() throws IOException\n {\n m_writer.writeStartList(\"custom_fields\");\n for (CustomField field : m_projectFile.getCustomFields())\n {\n writeCustomField(field);\n }\n m_writer.writeEndList();\n }"
] |
Retrieve an activity status.
@param mpxj MPXJ Task instance
@return activity status | [
"private String getActivityStatus(Task mpxj)\n {\n String result;\n if (mpxj.getActualStart() == null)\n {\n result = \"Not Started\";\n }\n else\n {\n if (mpxj.getActualFinish() == null)\n {\n result = \"In Progress\";\n }\n else\n {\n result = \"Completed\";\n }\n }\n return result;\n }"
] | [
"public void bindBundleToSceneObject(GVRScriptBundle scriptBundle, GVRSceneObject rootSceneObject)\n throws IOException, GVRScriptException\n {\n bindHelper(scriptBundle, rootSceneObject, BIND_MASK_SCENE_OBJECTS);\n }",
"public String getHostName() {\n if( addr instanceof NbtAddress ) {\n return ((NbtAddress)addr).getHostName();\n }\n return ((InetAddress)addr).getHostName();\n }",
"public Slice newSlice(long address, int size)\n {\n if (address <= 0) {\n throw new IllegalArgumentException(\"Invalid address: \" + address);\n }\n if (size == 0) {\n return Slices.EMPTY_SLICE;\n }\n return new Slice(null, address, size, 0, null);\n }",
"public static Map<String, String> getContentMap(File file, String separator) throws IOException {\n List<String> content = getContentLines(file);\n Map<String, String> map = new LinkedHashMap<String, String>();\n \n for (String line : content) {\n String[] spl = line.split(separator);\n if (line.trim().length() > 0) {\n map.put(spl[0], (spl.length > 1 ? spl[1] : \"\"));\n }\n }\n \n return map;\n }",
"public static base_responses update(nitro_service client, snmpmanager resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsnmpmanager updateresources[] = new snmpmanager[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new snmpmanager();\n\t\t\t\tupdateresources[i].ipaddress = resources[i].ipaddress;\n\t\t\t\tupdateresources[i].netmask = resources[i].netmask;\n\t\t\t\tupdateresources[i].domainresolveretry = resources[i].domainresolveretry;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"private void initDatesPanel() {\n\n m_startLabel.setText(Messages.get().key(Messages.GUI_SERIALDATE_TIME_STARTTIME_0));\n m_startTime.setAllowInvalidValue(true);\n m_startTime.setValue(m_model.getStart());\n m_endLabel.setText(Messages.get().key(Messages.GUI_SERIALDATE_TIME_ENDTIME_0));\n m_endTime.setAllowInvalidValue(true);\n m_endTime.setValue(m_model.getEnd());\n m_seriesCheckBox.setText(Messages.get().key(Messages.GUI_SERIALDATE_SERIES_CHECKBOX_0));\n m_wholeDayCheckBox.setText(Messages.get().key(Messages.GUI_SERIALDATE_WHOLE_DAY_CHECKBOX_0));\n m_currentTillEndCheckBox.setText(Messages.get().key(Messages.GUI_SERIALDATE_CURRENT_TILL_END_CHECKBOX_0));\n m_currentTillEndCheckBox.getButton().setTitle(\n Messages.get().key(Messages.GUI_SERIALDATE_CURRENT_TILL_END_CHECKBOX_HELP_0));\n }",
"public static void acceptsPartition(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_P, OPT_PARTITION), \"partition id list\")\n .withRequiredArg()\n .describedAs(\"partition-id-list\")\n .withValuesSeparatedBy(',')\n .ofType(Integer.class);\n }",
"protected <T> T getProperty(String key, Class<T> type) {\n Object returnValue = getProperty(key);\n if (returnValue != null) {\n return (T) returnValue;\n } else {\n return null;\n }\n }",
"protected String getLocaleSpecificTitle(Locale locale) {\n\n String result = null;\n\n try {\n\n if (isDetailRequest()) {\n // this is a request to a detail page\n CmsResource res = getDetailContent();\n CmsFile file = m_cms.readFile(res);\n CmsXmlContent content = CmsXmlContentFactory.unmarshal(m_cms, file);\n result = content.getHandler().getTitleMapping(m_cms, content, m_cms.getRequestContext().getLocale());\n if (result == null) {\n // title not found, maybe no mapping OR not available in the current locale\n // read the title of the detail resource as fall back (may contain mapping from another locale)\n result = m_cms.readPropertyObject(\n res,\n CmsPropertyDefinition.PROPERTY_TITLE,\n false,\n locale).getValue();\n }\n }\n if (result == null) {\n // read the title of the requested resource as fall back\n result = m_cms.readPropertyObject(\n m_cms.getRequestContext().getUri(),\n CmsPropertyDefinition.PROPERTY_TITLE,\n true,\n locale).getValue();\n }\n } catch (CmsException e) {\n LOG.debug(e.getLocalizedMessage(), e);\n }\n if (CmsStringUtil.isEmptyOrWhitespaceOnly(result)) {\n result = \"\";\n }\n\n return result;\n }"
] |
Return the numeric distance value in degrees.
@return the degrees | [
"public double getDegrees() {\n double kms = getValue(GeoDistanceUnit.KILOMETRES);\n return DistanceUtils.dist2Degrees(kms, DistanceUtils.EARTH_MEAN_RADIUS_KM);\n }"
] | [
"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 void initializeDomainRegistry(final TransformerRegistry registry) {\n\n //The chains for transforming will be as follows\n //For JBoss EAP: 8.0.0 -> 5.0.0 -> 4.0.0 -> 1.8.0 -> 1.7.0 -> 1.6.0 -> 1.5.0\n\n registerRootTransformers(registry);\n registerChainedManagementTransformers(registry);\n registerChainedServerGroupTransformers(registry);\n registerProfileTransformers(registry);\n registerSocketBindingGroupTransformers(registry);\n registerDeploymentTransformers(registry);\n }",
"public Range<App> listApps(String range) {\n return connection.execute(new AppList(range), apiKey);\n }",
"public static nslimitidentifier_stats[] get(nitro_service service) throws Exception{\n\t\tnslimitidentifier_stats obj = new nslimitidentifier_stats();\n\t\tnslimitidentifier_stats[] response = (nslimitidentifier_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}",
"protected void update(float scale) {\n // Updates only when the plane is in the scene\n GVRSceneObject owner = getOwnerObject();\n\n if ((owner != null) && isEnabled() && owner.isEnabled())\n {\n convertFromARtoVRSpace(scale);\n }\n }",
"private void emitStatusLine(AggregatedResultEvent result, TestStatus status, long timeMillis) throws IOException {\n final StringBuilder line = new StringBuilder();\n\n line.append(shortTimestamp(result.getStartTimestamp()));\n line.append(Strings.padEnd(statusNames.get(status), 8, ' '));\n line.append(formatDurationInSeconds(timeMillis));\n if (forkedJvmCount > 1) {\n line.append(String.format(Locale.ROOT, jvmIdFormat, result.getSlave().id));\n }\n line.append(\" | \");\n\n line.append(formatDescription(result.getDescription()));\n if (!result.isSuccessful()) {\n line.append(FAILURE_MARKER);\n }\n line.append(\"\\n\");\n\n if (showThrowable) {\n // GH-82 (cause for ignored tests). \n if (status == TestStatus.IGNORED && result instanceof AggregatedTestResultEvent) {\n final StringWriter sw = new StringWriter();\n PrefixedWriter pos = new PrefixedWriter(indent, sw, DEFAULT_MAX_LINE_WIDTH);\n pos.write(\"Cause: \");\n pos.write(((AggregatedTestResultEvent) result).getCauseForIgnored());\n pos.completeLine();\n line.append(sw.toString());\n }\n\n final List<FailureMirror> failures = result.getFailures();\n if (!failures.isEmpty()) {\n final StringWriter sw = new StringWriter();\n PrefixedWriter pos = new PrefixedWriter(indent, sw, DEFAULT_MAX_LINE_WIDTH);\n int count = 0;\n for (FailureMirror fm : failures) {\n count++;\n if (fm.isAssumptionViolation()) {\n pos.write(String.format(Locale.ROOT, \n \"Assumption #%d: %s\",\n count, MoreObjects.firstNonNull(fm.getMessage(), \"(no message)\")));\n } else {\n pos.write(String.format(Locale.ROOT, \n \"Throwable #%d: %s\",\n count,\n showStackTraces ? filterStackTrace(fm.getTrace()) : fm.getThrowableString()));\n }\n }\n pos.completeLine();\n if (sw.getBuffer().length() > 0) {\n line.append(sw.toString());\n }\n }\n }\n\n logShort(line);\n }",
"public static String implodeObjects(Iterable<?> objects) {\n\t\tStringBuilder builder = new StringBuilder();\n\t\tboolean first = true;\n\t\tfor (Object o : objects) {\n\t\t\tif (first) {\n\t\t\t\tfirst = false;\n\t\t\t} else {\n\t\t\t\tbuilder.append(\"|\");\n\t\t\t}\n\t\t\tbuilder.append(o.toString());\n\t\t}\n\t\treturn builder.toString();\n\t}",
"public static void registerOgmExternalizers(SerializationConfigurationBuilder cfg) {\n\t\tfor ( AdvancedExternalizer<?> advancedExternalizer : ogmExternalizers.values() ) {\n\t\t\tcfg.addAdvancedExternalizer( advancedExternalizer );\n\t\t}\n\t}",
"public <T extends CanvasReader> T getReader(Class<T> type, OauthToken oauthToken) {\n return getReader(type, oauthToken, null);\n }"
] |
Check the version to assure it is allowed.
@param pluginName plugin name which needs the dependency
@param dependency dependency which needs to be verified
@param requestedVersion requested/minimum version
@param availableVersion available version
@return version check problem or empty string when all is fine | [
"String checkVersion(String pluginName, String dependency, String requestedVersion, String availableVersion) {\n\t\tif (null == availableVersion) {\n\t\t\treturn \"Dependency \" + dependency + \" not found for \" + pluginName + \", version \" + requestedVersion +\n\t\t\t\t\t\" or higher needed.\\n\";\n\t\t}\n\t\tif (requestedVersion.startsWith(EXPR_START) || availableVersion.startsWith(EXPR_START)) {\n\t\t\treturn \"\";\n\t\t}\n\t\tVersion requested = new Version(requestedVersion);\n\t\tVersion available = new Version(availableVersion);\n\t\tif (requested.getMajor() != available.getMajor()) {\n\t\t\treturn \"Dependency \" + dependency + \" is provided in a incompatible API version for plug-in \" +\n\t\t\t\t\tpluginName + \", which requests version \" + requestedVersion +\n\t\t\t\t\t\", but version \" + availableVersion + \" supplied.\\n\";\n\t\t}\n\t\tif (requested.after(available)) {\n\t\t\treturn \"Dependency \" + dependency + \" too old for \" + pluginName + \", version \" + requestedVersion +\n\t\t\t\t\t\" or higher needed, but version \" + availableVersion + \" supplied.\\n\";\n\t\t}\n\t\treturn \"\";\n\t}"
] | [
"public LuaPreparedScript endPreparedScriptReturn(LuaValue value, LuaScriptConfig config) {\n add(new LuaAstReturnStatement(argument(value)));\n return endPreparedScript(config);\n }",
"public static String readUntilTag(Reader r) throws IOException {\r\n if (!r.ready()) {\r\n return \"\";\r\n }\r\n StringBuilder b = new StringBuilder();\r\n int c = r.read();\r\n while (c >= 0 && c != '<') {\r\n b.append((char) c);\r\n c = r.read();\r\n }\r\n return b.toString();\r\n }",
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public int getTotalVisits() {\n EventDetail ed = getLocalDataStore().getEventDetail(Constants.APP_LAUNCHED_EVENT);\n if (ed != null) return ed.getCount();\n\n return 0;\n }",
"private void processWorkingHours(ProjectCalendar mpxjCalendar, Sequence uniqueID, Day day, List<OverriddenDayType> typeList)\n {\n if (isWorkingDay(mpxjCalendar, day))\n {\n ProjectCalendarHours mpxjHours = mpxjCalendar.getCalendarHours(day);\n if (mpxjHours != null)\n {\n OverriddenDayType odt = m_factory.createOverriddenDayType();\n typeList.add(odt);\n odt.setId(getIntegerString(uniqueID.next()));\n List<Interval> intervalList = odt.getInterval();\n for (DateRange mpxjRange : mpxjHours)\n {\n Date rangeStart = mpxjRange.getStart();\n Date rangeEnd = mpxjRange.getEnd();\n\n if (rangeStart != null && rangeEnd != null)\n {\n Interval interval = m_factory.createInterval();\n intervalList.add(interval);\n interval.setStart(getTimeString(rangeStart));\n interval.setEnd(getTimeString(rangeEnd));\n }\n }\n }\n }\n }",
"@NonNull\n @Override\n public Loader<SortedList<File>> getLoader() {\n return new AsyncTaskLoader<SortedList<File>>(getActivity()) {\n\n FileObserver fileObserver;\n\n @Override\n public SortedList<File> loadInBackground() {\n File[] listFiles = mCurrentPath.listFiles();\n final int initCap = listFiles == null ? 0 : listFiles.length;\n\n SortedList<File> files = new SortedList<>(File.class, new SortedListAdapterCallback<File>(getDummyAdapter()) {\n @Override\n public int compare(File lhs, File rhs) {\n return compareFiles(lhs, rhs);\n }\n\n @Override\n public boolean areContentsTheSame(File file, File file2) {\n return file.getAbsolutePath().equals(file2.getAbsolutePath()) && (file.isFile() == file2.isFile());\n }\n\n @Override\n public boolean areItemsTheSame(File file, File file2) {\n return areContentsTheSame(file, file2);\n }\n }, initCap);\n\n\n files.beginBatchedUpdates();\n if (listFiles != null) {\n for (java.io.File f : listFiles) {\n if (isItemVisible(f)) {\n files.add(f);\n }\n }\n }\n files.endBatchedUpdates();\n\n return files;\n }\n\n /**\n * Handles a request to start the Loader.\n */\n @Override\n protected void onStartLoading() {\n super.onStartLoading();\n\n // handle if directory does not exist. Fall back to root.\n if (mCurrentPath == null || !mCurrentPath.isDirectory()) {\n mCurrentPath = getRoot();\n }\n\n // Start watching for changes\n fileObserver = new FileObserver(mCurrentPath.getPath(),\n FileObserver.CREATE |\n FileObserver.DELETE\n | FileObserver.MOVED_FROM | FileObserver.MOVED_TO\n ) {\n\n @Override\n public void onEvent(int event, String path) {\n // Reload\n onContentChanged();\n }\n };\n fileObserver.startWatching();\n\n forceLoad();\n }\n\n /**\n * Handles a request to completely reset the Loader.\n */\n @Override\n protected void onReset() {\n super.onReset();\n\n // Stop watching\n if (fileObserver != null) {\n fileObserver.stopWatching();\n fileObserver = null;\n }\n }\n };\n }",
"private void addToGraph(ClassDoc cd) {\n\t// avoid adding twice the same class, but don't rely on cg.getClassInfo\n\t// since there are other ways to add a classInfor than printing the class\n\tif (visited.contains(cd.toString()))\n\t return;\n\n\tvisited.add(cd.toString());\n\tcg.printClass(cd, false);\n\tcg.printRelations(cd);\n\tif (opt.inferRelationships)\n\t cg.printInferredRelations(cd);\n\tif (opt.inferDependencies)\n\t cg.printInferredDependencies(cd);\n }",
"private static double pointsDistance(Point a, Point b) {\n int dx = b.x - a.x;\n int dy = b.y - a.y;\n return Math.sqrt(dx * dx + dy * dy);\n }",
"@NonNull public CharSequence getQuery() {\n if (searchView != null) {\n return searchView.getQuery();\n } else if (supportView != null) {\n return supportView.getQuery();\n }\n throw new IllegalStateException(ERROR_NO_SEARCHVIEW);\n }",
"private PoolingHttpClientConnectionManager createConnectionMgr() {\n PoolingHttpClientConnectionManager connectionMgr;\n\n // prepare SSLContext\n SSLContext sslContext = buildSslContext();\n ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();\n // we allow to disable host name verification against CA certificate,\n // notice: in general this is insecure and should be avoided in production,\n // (this type of configuration is useful for development purposes)\n boolean noHostVerification = false;\n LayeredConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(\n sslContext,\n noHostVerification ? NoopHostnameVerifier.INSTANCE : new DefaultHostnameVerifier()\n );\n Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()\n .register(\"http\", plainsf)\n .register(\"https\", sslsf)\n .build();\n connectionMgr = new PoolingHttpClientConnectionManager(r, null, null,\n null, connectionPoolTimeToLive, TimeUnit.SECONDS);\n\n connectionMgr.setMaxTotal(maxConnectionsTotal);\n connectionMgr.setDefaultMaxPerRoute(maxConnectionsPerRoute);\n HttpHost localhost = new HttpHost(\"localhost\", 80);\n connectionMgr.setMaxPerRoute(new HttpRoute(localhost), maxConnectionsPerRoute);\n return connectionMgr;\n }"
] |
Validate the configuration.
@param validationErrors where to put the errors. | [
"public void validate(final List<Throwable> validationErrors) {\n if (this.matchers == null) {\n validationErrors.add(new IllegalArgumentException(\n \"Matchers cannot be null. There should be at least a !acceptAll matcher\"));\n }\n if (this.matchers != null && this.matchers.isEmpty()) {\n validationErrors.add(new IllegalArgumentException(\n \"There are no url matchers defined. There should be at least a \" +\n \"!acceptAll matcher\"));\n }\n }"
] | [
"public static linkset_interface_binding[] get(nitro_service service, String id) throws Exception{\n\t\tlinkset_interface_binding obj = new linkset_interface_binding();\n\t\tobj.set_id(id);\n\t\tlinkset_interface_binding response[] = (linkset_interface_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static void waitForStandalone(final ModelControllerClient client, final long startupTimeout)\n throws InterruptedException, RuntimeException, TimeoutException {\n waitForStandalone(null, client, startupTimeout);\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 }",
"public static String getDumpFileDirectoryName(\n\t\t\tDumpContentType dumpContentType, String dateStamp) {\n\t\treturn dumpContentType.toString().toLowerCase() + \"-\" + dateStamp;\n\t}",
"public void createPdfLayout(Dimension dim)\n {\n if (pdfdocument != null) //processing a PDF document\n {\n try {\n if (createImage)\n img = new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_RGB);\n Graphics2D ig = img.createGraphics();\n \n log.info(\"Creating PDF boxes\");\n VisualContext ctx = new VisualContext(null, null);\n \n boxtree = new CSSBoxTree(ig, ctx, dim, baseurl);\n boxtree.setConfig(config);\n boxtree.processDocument(pdfdocument, startPage, endPage);\n viewport = boxtree.getViewport();\n root = boxtree.getDocument().getDocumentElement();\n log.info(\"We have \" + boxtree.getLastId() + \" boxes\");\n viewport.initSubtree();\n \n log.info(\"Layout for \"+dim.width+\"px\");\n viewport.doLayout(dim.width, true, true);\n log.info(\"Resulting size: \" + viewport.getWidth() + \"x\" + viewport.getHeight() + \" (\" + viewport + \")\");\n \n log.info(\"Updating viewport size\");\n viewport.updateBounds(dim);\n log.info(\"Resulting size: \" + viewport.getWidth() + \"x\" + viewport.getHeight() + \" (\" + viewport + \")\");\n \n if (createImage && (viewport.getWidth() > dim.width || viewport.getHeight() > dim.height))\n {\n img = new BufferedImage(Math.max(viewport.getWidth(), dim.width),\n Math.max(viewport.getHeight(), dim.height),\n BufferedImage.TYPE_INT_RGB);\n ig = img.createGraphics();\n }\n \n log.info(\"Positioning for \"+img.getWidth()+\"x\"+img.getHeight()+\"px\");\n viewport.absolutePositions();\n \n clearCanvas();\n viewport.draw(new GraphicsRenderer(ig));\n setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));\n revalidate();\n } catch (ParserConfigurationException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n else if (root != null) //processing a DOM tree\n {\n super.createLayout(dim);\n }\n }",
"public static <T> void injectBoundFields(T instance, CreationalContext<T> creationalContext, BeanManagerImpl manager,\n Iterable<? extends FieldInjectionPoint<?, ?>> injectableFields) {\n for (FieldInjectionPoint<?, ?> injectableField : injectableFields) {\n injectableField.inject(instance, manager, creationalContext);\n }\n }",
"public AsciiTable setCharTranslator(CharacterTranslator charTranslator) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setCharTranslator(charTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"@Override\n public ResourceStorageLoadable getOrCreateResourceStorageLoadable(final StorageAwareResource resource) {\n try {\n final ResourceStorageProviderAdapter stateProvider = IterableExtensions.<ResourceStorageProviderAdapter>head(Iterables.<ResourceStorageProviderAdapter>filter(resource.getResourceSet().eAdapters(), ResourceStorageProviderAdapter.class));\n if ((stateProvider != null)) {\n final ResourceStorageLoadable inputStream = stateProvider.getResourceStorageLoadable(resource);\n if ((inputStream != null)) {\n return inputStream;\n }\n }\n InputStream _xifexpression = null;\n boolean _exists = resource.getResourceSet().getURIConverter().exists(this.getBinaryStorageURI(resource.getURI()), CollectionLiterals.<Object, Object>emptyMap());\n if (_exists) {\n _xifexpression = resource.getResourceSet().getURIConverter().createInputStream(this.getBinaryStorageURI(resource.getURI()));\n } else {\n InputStream _xblockexpression = null;\n {\n final AbstractFileSystemAccess2 fsa = this.getFileSystemAccess(resource);\n final String outputRelativePath = this.computeOutputPath(resource);\n _xblockexpression = fsa.readBinaryFile(outputRelativePath);\n }\n _xifexpression = _xblockexpression;\n }\n final InputStream inputStream_1 = _xifexpression;\n return this.createResourceStorageLoadable(inputStream_1);\n } catch (Throwable _e) {\n throw Exceptions.sneakyThrow(_e);\n }\n }",
"public Point3d[] getVertices() {\n Point3d[] vtxs = new Point3d[numVertices];\n for (int i = 0; i < numVertices; i++) {\n vtxs[i] = pointBuffer[vertexPointIndices[i]].pnt;\n }\n return vtxs;\n }"
] |
Stop announcing ourselves and listening for status updates. | [
"public synchronized void stop() {\n if (isRunning()) {\n try {\n setSendingStatus(false);\n } catch (Throwable t) {\n logger.error(\"Problem stopping sending status during shutdown\", t);\n }\n DeviceFinder.getInstance().removeIgnoredAddress(socket.get().getLocalAddress());\n socket.get().close();\n socket.set(null);\n broadcastAddress.set(null);\n updates.clear();\n setTempoMaster(null);\n setDeviceNumber((byte)0); // Set up for self-assignment if restarted.\n deliverLifecycleAnnouncement(logger, false);\n }\n }"
] | [
"public static void printDocumentation() {\n\t\tSystem.out\n\t\t\t\t.println(\"********************************************************************\");\n\t\tSystem.out.println(\"*** Wikidata Toolkit: GenderRatioProcessor\");\n\t\tSystem.out.println(\"*** \");\n\t\tSystem.out\n\t\t\t\t.println(\"*** This program will download and process dumps from Wikidata.\");\n\t\tSystem.out\n\t\t\t\t.println(\"*** It will compute the numbers of articles about humans across\");\n\t\tSystem.out\n\t\t\t\t.println(\"*** Wikimedia projects, and in particular it will count the articles\");\n\t\tSystem.out\n\t\t\t\t.println(\"*** for each sex/gender. Results will be stored in a CSV file.\");\n\t\tSystem.out.println(\"*** See source code for further details.\");\n\t\tSystem.out\n\t\t\t\t.println(\"********************************************************************\");\n\t}",
"public void fireAssignmentReadEvent(ResourceAssignment resourceAssignment)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.assignmentRead(resourceAssignment);\n }\n }\n }",
"public static DiscountCurve createDiscountCurveFromDiscountFactors(String name, double[] times, double[] givenDiscountFactors) {\n\t\tDiscountCurve discountFactors = new DiscountCurve(name);\n\n\t\tfor(int timeIndex=0; timeIndex<times.length;timeIndex++) {\n\t\t\tdiscountFactors.addDiscountFactor(times[timeIndex], givenDiscountFactors[timeIndex], times[timeIndex] > 0);\n\t\t}\n\n\t\treturn discountFactors;\n\t}",
"public ResourceIterator<Node> findEntities(GraphDatabaseService executionEngine) {\n\t\tResult result = executionEngine.execute( getFindEntitiesQuery() );\n\t\treturn result.columnAs( BaseNeo4jEntityQueries.ENTITY_ALIAS );\n\t}",
"public String getRemoteUrl(String defaultRemoteUrl) {\n if (StringUtils.isBlank(defaultRemoteUrl)) {\n RemoteConfig remoteConfig = getJenkinsScm().getRepositories().get(0);\n URIish uri = remoteConfig.getURIs().get(0);\n return uri.toPrivateString();\n }\n\n return defaultRemoteUrl;\n }",
"@Override\n public Symmetry454Date dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }",
"public Collection<String> getMethods() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_METHODS);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element methodsElement = response.getPayload();\r\n\r\n List<String> methods = new ArrayList<String>();\r\n NodeList methodElements = methodsElement.getElementsByTagName(\"method\");\r\n for (int i = 0; i < methodElements.getLength(); i++) {\r\n Element methodElement = (Element) methodElements.item(i);\r\n methods.add(XMLUtilities.getValue(methodElement));\r\n }\r\n return methods;\r\n }",
"private FieldType findForeignFieldType(Class<?> clazz, Class<?> foreignClass, Dao<?, ?> foreignDao)\n\t\t\tthrows SQLException {\n\t\tString foreignColumnName = fieldConfig.getForeignCollectionForeignFieldName();\n\t\tfor (FieldType fieldType : foreignDao.getTableInfo().getFieldTypes()) {\n\t\t\tif (fieldType.getType() == foreignClass\n\t\t\t\t\t&& (foreignColumnName == null || fieldType.getField().getName().equals(foreignColumnName))) {\n\t\t\t\tif (!fieldType.fieldConfig.isForeign() && !fieldType.fieldConfig.isForeignAutoRefresh()) {\n\t\t\t\t\t// this may never be reached\n\t\t\t\t\tthrow new SQLException(\"Foreign collection object \" + clazz + \" for field '\" + field.getName()\n\t\t\t\t\t\t\t+ \"' contains a field of class \" + foreignClass + \" but it's not foreign\");\n\t\t\t\t}\n\t\t\t\treturn fieldType;\n\t\t\t}\n\t\t}\n\t\t// build our complex error message\n\t\tStringBuilder sb = new StringBuilder();\n\t\tsb.append(\"Foreign collection class \").append(clazz.getName());\n\t\tsb.append(\" for field '\").append(field.getName()).append(\"' column-name does not contain a foreign field\");\n\t\tif (foreignColumnName != null) {\n\t\t\tsb.append(\" named '\").append(foreignColumnName).append('\\'');\n\t\t}\n\t\tsb.append(\" of class \").append(foreignClass.getName());\n\t\tthrow new SQLException(sb.toString());\n\t}",
"protected void emitWithBurstCheck(float[] particlePositions, float[] particleVelocities,\n float[] particleTimeStamps)\n {\n if ( burstMode )\n {\n if ( executeOnce )\n {\n emit(particlePositions, particleVelocities, particleTimeStamps);\n executeOnce = false;\n }\n }\n else\n {\n emit(particlePositions, particleVelocities, particleTimeStamps);\n }\n\n }"
] |
Check whether the given id is included in the list of includes and not excluded.
@param id id to check
@param includes list of include regular expressions
@param excludes list of exclude regular expressions
@return true when id included and not excluded | [
"protected boolean check(String id, List<String> includes, List<String> excludes) {\n\t\treturn check(id, includes) && !check(id, excludes);\n\t}"
] | [
"public void setMaxConnectionAge(long maxConnectionAge, TimeUnit timeUnit) {\n\t\tthis.maxConnectionAgeInSeconds = TimeUnit.SECONDS.convert(maxConnectionAge, timeUnit);\n\t}",
"public static boolean deleteDatabase(final StitchAppClientInfo appInfo,\n final String serviceName,\n final EmbeddedMongoClientFactory clientFactory,\n final String userId) {\n final String dataDir = appInfo.getDataDirectory();\n if (dataDir == null) {\n throw new IllegalArgumentException(\"StitchAppClient not configured with a data directory\");\n }\n\n final String instanceKey = String.format(\n \"%s-%s_sync_%s_%s\", appInfo.getClientAppId(), dataDir, serviceName, userId);\n final String dbPath = String.format(\n \"%s/%s/sync_mongodb_%s/%s/0/\", dataDir, appInfo.getClientAppId(), serviceName, userId);\n final MongoClient client =\n clientFactory.getClient(instanceKey, dbPath, appInfo.getCodecRegistry());\n\n for (final String listDatabaseName : client.listDatabaseNames()) {\n try {\n client.getDatabase(listDatabaseName).drop();\n } catch (Exception e) {\n // do nothing\n }\n }\n\n client.close();\n clientFactory.removeClient(instanceKey);\n\n return new File(dbPath).delete();\n }",
"private Object readMetadataFromXML(InputSource source, Class target)\r\n throws MalformedURLException, ParserConfigurationException, SAXException, IOException\r\n {\r\n // TODO: make this configurable\r\n boolean validate = false;\r\n \r\n // get a xml reader instance:\r\n SAXParserFactory factory = SAXParserFactory.newInstance();\r\n log.info(\"RepositoryPersistor using SAXParserFactory : \" + factory.getClass().getName());\r\n if (validate)\r\n {\r\n factory.setValidating(true);\r\n }\r\n SAXParser p = factory.newSAXParser();\r\n XMLReader reader = p.getXMLReader();\r\n if (validate)\r\n {\r\n reader.setErrorHandler(new OJBErrorHandler());\r\n }\r\n\r\n Object result;\r\n if (DescriptorRepository.class.equals(target))\r\n {\r\n // create an empty repository:\r\n DescriptorRepository repository = new DescriptorRepository();\r\n // create handler for building the repository structure\r\n ContentHandler handler = new RepositoryXmlHandler(repository);\r\n // tell parser to use our handler:\r\n reader.setContentHandler(handler);\r\n reader.parse(source);\r\n result = repository;\r\n }\r\n else if (ConnectionRepository.class.equals(target))\r\n {\r\n // create an empty repository:\r\n ConnectionRepository repository = new ConnectionRepository();\r\n // create handler for building the repository structure\r\n ContentHandler handler = new ConnectionDescriptorXmlHandler(repository);\r\n // tell parser to use our handler:\r\n reader.setContentHandler(handler);\r\n reader.parse(source);\r\n //LoggerFactory.getBootLogger().info(\"loading XML took \" + (stop - start) + \" msecs\");\r\n result = repository;\r\n }\r\n else\r\n throw new MetadataException(\"Could not build a repository instance for '\" + target +\r\n \"', using source \" + source);\r\n return result;\r\n }",
"public static BuildInfo appendBuildInfo(CpsScript cpsScript, Map<String, Object> stepVariables) {\n BuildInfo buildInfo = (BuildInfo) stepVariables.get(BUILD_INFO);\n if (buildInfo == null) {\n buildInfo = (BuildInfo) cpsScript.invokeMethod(\"newBuildInfo\", Maps.newLinkedHashMap());\n stepVariables.put(BUILD_INFO, buildInfo);\n }\n buildInfo.setCpsScript(cpsScript);\n return buildInfo;\n }",
"public static final Double getPercentage(byte[] data, int offset)\n {\n int value = MPPUtility.getShort(data, offset);\n Double result = null;\n if (value >= 0 && value <= 100)\n {\n result = NumberHelper.getDouble(value);\n }\n return result;\n }",
"private static String convertPathToResource(String path) {\n File file = new File(path);\n List<String> parts = new ArrayList<String>();\n do {\n parts.add(file.getName());\n file = file.getParentFile();\n }\n while (file != null);\n\n StringBuffer sb = new StringBuffer();\n int size = parts.size();\n for (int a = size - 1; a >= 0; a--) {\n if (sb.length() > 0) {\n sb.append(\"_\");\n }\n sb.append(parts.get(a));\n }\n\n // TODO: Better regex replacement\n return sb.toString().replace('-', '_').replace(\"+\", \"plus\").toLowerCase(Locale.US);\n }",
"public int color(Context ctx) {\n if (mColorInt == 0 && mColorRes != -1) {\n mColorInt = ContextCompat.getColor(ctx, mColorRes);\n }\n return mColorInt;\n }",
"private void writeDoubleField(String fieldName, Object value) throws IOException\n {\n double val = ((Number) value).doubleValue();\n if (val != 0)\n {\n m_writer.writeNameValuePair(fieldName, val);\n }\n }",
"public void unlock() {\n String queryString = new QueryStringBuilder().appendParam(\"fields\", \"lock\").toString();\n URL url = FILE_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"PUT\");\n\n JsonObject lockObject = new JsonObject();\n lockObject.add(\"lock\", JsonObject.NULL);\n\n request.setBody(lockObject.toString());\n request.send();\n }"
] |
Resets the calendar | [
"private void resetCalendar() {\n _calendar = getCalendar();\n if (_defaultTimeZone != null) {\n _calendar.setTimeZone(_defaultTimeZone);\n }\n _currentYear = _calendar.get(Calendar.YEAR);\n }"
] | [
"protected void append(Env env) {\n addAllWithFilter(this.envVars, env.envVars, filter.getPatternFilter());\n addAllWithFilter(this.sysVars, env.sysVars, filter.getPatternFilter());\n }",
"public static nsacl6[] get(nitro_service service) throws Exception{\n\t\tnsacl6 obj = new nsacl6();\n\t\tnsacl6[] response = (nsacl6[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"@Override\n public void setExpectedMaxSize( int numRows , int numCols ) {\n super.setExpectedMaxSize(numRows,numCols);\n\n // if the matrix that is being decomposed is smaller than the block we really don't\n // see the B matrix.\n if( numRows < blockWidth)\n B = new DMatrixRMaj(0,0);\n else\n B = new DMatrixRMaj(blockWidth,maxWidth);\n\n chol = new CholeskyBlockHelper_DDRM(blockWidth);\n }",
"public <T> T with( Closure<T> closure ) {\n return DefaultGroovyMethods.with( null, closure ) ;\n }",
"private List<String> getCommandLines(File file) {\n List<String> lines = new ArrayList<>();\n try (BufferedReader reader = new BufferedReader(new FileReader(file))) {\n String line = reader.readLine();\n while (line != null) {\n lines.add(line);\n line = reader.readLine();\n }\n } catch (Throwable e) {\n throw new IllegalStateException(\"Failed to process file \" + file.getAbsolutePath(), e);\n }\n return lines;\n }",
"public Gallery lookupGallery(String galleryId) throws FlickrException {\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_LOOKUP_GALLERY);\r\n parameters.put(\"url\", galleryId);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element galleryElement = response.getPayload();\r\n Gallery gallery = new Gallery();\r\n gallery.setId(galleryElement.getAttribute(\"id\"));\r\n gallery.setUrl(galleryElement.getAttribute(\"url\"));\r\n\r\n User owner = new User();\r\n owner.setId(galleryElement.getAttribute(\"owner\"));\r\n gallery.setOwner(owner);\r\n gallery.setCreateDate(galleryElement.getAttribute(\"date_create\"));\r\n gallery.setUpdateDate(galleryElement.getAttribute(\"date_update\"));\r\n gallery.setPrimaryPhotoId(galleryElement.getAttribute(\"primary_photo_id\"));\r\n gallery.setPrimaryPhotoServer(galleryElement.getAttribute(\"primary_photo_server\"));\r\n gallery.setVideoCount(galleryElement.getAttribute(\"count_videos\"));\r\n gallery.setPhotoCount(galleryElement.getAttribute(\"count_photos\"));\r\n gallery.setPrimaryPhotoFarm(galleryElement.getAttribute(\"farm\"));\r\n gallery.setPrimaryPhotoSecret(galleryElement.getAttribute(\"secret\"));\r\n\r\n gallery.setTitle(XMLUtilities.getChildValue(galleryElement, \"title\"));\r\n gallery.setDesc(XMLUtilities.getChildValue(galleryElement, \"description\"));\r\n return gallery;\r\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 }",
"public boolean add(long key) {\n final int index = ((((int) (key >>> 32)) ^ ((int) (key))) & 0x7fffffff) % capacity;\n final Entry entryOriginal = table[index];\n for (Entry entry = entryOriginal; entry != null; entry = entry.next) {\n if (entry.key == key) {\n return false;\n }\n }\n table[index] = new Entry(key, entryOriginal);\n size++;\n if (size > threshold) {\n setCapacity(2 * capacity);\n }\n return true;\n }",
"public void setLocale(String locale) {\n\n try {\n m_locale = LocaleUtils.toLocale(locale);\n } catch (IllegalArgumentException e) {\n LOG.error(Messages.get().getBundle().key(Messages.ERR_TAG_INVALID_LOCALE_1, \"cms:navigation\"), e);\n m_locale = null;\n }\n }"
] |
Set all unknown fields
@param unknownFields the new unknown fields | [
"@JsonIgnore\n public void setUnknownFields(final Map<String,Object> unknownFields) {\n this.unknownFields.clear();\n this.unknownFields.putAll(unknownFields);\n }"
] | [
"boolean lockSharedInterruptibly(final Integer permit, final long timeout, final TimeUnit unit) throws InterruptedException {\n if (permit == null) {\n throw new IllegalArgumentException();\n }\n return sync.tryAcquireSharedNanos(permit, unit.toNanos(timeout));\n }",
"private void readCalendars(Document cdp)\n {\n for (Calendar calendar : cdp.getCalendars().getCalendar())\n {\n readCalendar(calendar);\n }\n\n for (Calendar calendar : cdp.getCalendars().getCalendar())\n {\n ProjectCalendar child = m_calendarMap.get(calendar.getID());\n ProjectCalendar parent = m_calendarMap.get(calendar.getBaseCalendarID());\n if (parent == null)\n {\n m_projectFile.setDefaultCalendar(child);\n }\n else\n {\n child.setParent(parent);\n }\n }\n }",
"public static clusternodegroup_nslimitidentifier_binding[] get(nitro_service service, String name) throws Exception{\n\t\tclusternodegroup_nslimitidentifier_binding obj = new clusternodegroup_nslimitidentifier_binding();\n\t\tobj.set_name(name);\n\t\tclusternodegroup_nslimitidentifier_binding response[] = (clusternodegroup_nslimitidentifier_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public Collection<Photocount> getCounts(Date[] dates, Date[] takenDates) throws FlickrException {\r\n List<Photocount> photocounts = new ArrayList<Photocount>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_COUNTS);\r\n\r\n if (dates == null && takenDates == null) {\r\n throw new IllegalArgumentException(\"You must provide a value for either dates or takenDates\");\r\n }\r\n\r\n if (dates != null) {\r\n List<String> dateList = new ArrayList<String>();\r\n for (int i = 0; i < dates.length; i++) {\r\n dateList.add(String.valueOf(dates[i].getTime() / 1000L));\r\n }\r\n parameters.put(\"dates\", StringUtilities.join(dateList, \",\"));\r\n }\r\n\r\n if (takenDates != null) {\r\n List<String> takenDateList = new ArrayList<String>();\r\n for (int i = 0; i < takenDates.length; i++) {\r\n takenDateList.add(String.valueOf(takenDates[i].getTime() / 1000L));\r\n }\r\n parameters.put(\"taken_dates\", StringUtilities.join(takenDateList, \",\"));\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photocountsElement = response.getPayload();\r\n NodeList photocountNodes = photocountsElement.getElementsByTagName(\"photocount\");\r\n for (int i = 0; i < photocountNodes.getLength(); i++) {\r\n Element photocountElement = (Element) photocountNodes.item(i);\r\n Photocount photocount = new Photocount();\r\n photocount.setCount(photocountElement.getAttribute(\"count\"));\r\n photocount.setFromDate(photocountElement.getAttribute(\"fromdate\"));\r\n photocount.setToDate(photocountElement.getAttribute(\"todate\"));\r\n photocounts.add(photocount);\r\n }\r\n return photocounts;\r\n }",
"protected void deleteAlias(MonolingualTextValue alias) {\n String lang = alias.getLanguageCode();\n AliasesWithUpdate currentAliases = newAliases.get(lang);\n if (currentAliases != null) {\n currentAliases.aliases.remove(alias);\n currentAliases.deleted.add(alias);\n currentAliases.write = true;\n }\n }",
"public static URI setQueryParams(final URI initialUri, final Multimap<String, String> queryParams) {\n StringBuilder queryString = new StringBuilder();\n for (Map.Entry<String, String> entry: queryParams.entries()) {\n if (queryString.length() > 0) {\n queryString.append(\"&\");\n }\n queryString.append(entry.getKey()).append(\"=\").append(entry.getValue());\n }\n try {\n if (initialUri.getHost() == null && initialUri.getAuthority() != null) {\n return new URI(initialUri.getScheme(), initialUri.getAuthority(), initialUri.getPath(),\n queryString.toString(),\n initialUri.getFragment());\n } else {\n return new URI(initialUri.getScheme(), initialUri.getUserInfo(), initialUri.getHost(),\n initialUri.getPort(),\n initialUri.getPath(),\n queryString.toString(), initialUri.getFragment());\n }\n } catch (URISyntaxException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }",
"private void addMembersInclSupertypes(Collection memberNames, HashMap members, XClass type, String tagName, String paramName, String paramValue) throws XDocletException\r\n {\r\n addMembers(memberNames, members, type, tagName, paramName, paramValue);\r\n if (type.getInterfaces() != null) {\r\n for (Iterator it = type.getInterfaces().iterator(); it.hasNext(); ) {\r\n addMembersInclSupertypes(memberNames, members, (XClass)it.next(), tagName, paramName, paramValue);\r\n }\r\n }\r\n if (!type.isInterface() && (type.getSuperclass() != null)) {\r\n addMembersInclSupertypes(memberNames, members, type.getSuperclass(), tagName, paramName, paramValue);\r\n }\r\n }",
"protected boolean isDuplicate(String eventID) {\n if (this.receivedEvents == null) {\n this.receivedEvents = new LRUCache<String>();\n }\n\n return !this.receivedEvents.add(eventID);\n }",
"public final B accessToken(String accessToken) {\n requireNonNull(accessToken, \"accessToken\");\n checkArgument(!accessToken.isEmpty(), \"accessToken is empty.\");\n this.accessToken = accessToken;\n return self();\n }"
] |
Write to a context. Uses NullWritable for key so that only value of output string is ultimately written
@param cr the DataPipe to write to | [
"public void writeOutput(DataPipe cr) {\n try {\n context.write(NullWritable.get(), new Text(cr.getPipeDelimited(outTemplate)));\n } catch (Exception e) {\n throw new RuntimeException(\"Exception occurred while writing to Context\", e);\n }\n }"
] | [
"public void setTargetDirectory(String directory) {\n if (directory != null && directory.length() > 0) {\n this.targetDirectory = new File(directory);\n } else {\n this.targetDirectory = null;\n }\n }",
"public static double Sinh(double x, int nTerms) {\r\n if (nTerms < 2) return x;\r\n if (nTerms == 2) {\r\n return x + (x * x * x) / 6D;\r\n } else {\r\n\r\n double mult = x * x * x;\r\n double fact = 6;\r\n int factS = 5;\r\n double result = x + mult / fact;\r\n for (int i = 3; i <= nTerms; i++) {\r\n mult *= x * x;\r\n fact *= factS * (factS - 1);\r\n factS += 2;\r\n result += mult / fact;\r\n }\r\n\r\n return result;\r\n }\r\n }",
"@SuppressWarnings({\"UnusedDeclaration\"})\n protected void doApi(StaplerRequest req, StaplerResponse resp) throws IOException, ServletException {\n try {\n log.log(Level.INFO, \"Initiating Artifactory Release Staging using API\");\n // Enforce release permissions\n project.checkPermission(ArtifactoryPlugin.RELEASE);\n // In case a staging user plugin is configured, the init() method invoke it:\n init();\n // Read the values provided by the staging user plugin and assign them to data members in this class.\n // Those values can be overriden by URL arguments sent with the API:\n readStagingPluginValues();\n // Read values from the request and override the staging plugin values:\n overrideStagingPluginParams(req);\n // Schedule the release build:\n Queue.WaitingItem item = Jenkins.getInstance().getQueue().schedule(\n project, 0,\n new Action[]{this, new CauseAction(new Cause.UserIdCause())}\n );\n if (item == null) {\n log.log(Level.SEVERE, \"Failed to schedule a release build following a Release API invocation\");\n resp.setStatus(StaplerResponse.SC_INTERNAL_SERVER_ERROR);\n } else {\n String url = req.getContextPath() + '/' + item.getUrl();\n JSONObject json = new JSONObject();\n json.element(\"queueItem\", item.getId());\n json.element(\"releaseVersion\", getReleaseVersion());\n json.element(\"nextVersion\", getNextVersion());\n json.element(\"releaseBranch\", getReleaseBranch());\n // Must use getOutputStream as sendRedirect uses getOutputStream (and closes it)\n resp.getOutputStream().print(json.toString());\n resp.sendRedirect(201, url);\n }\n } catch (Exception e) {\n log.log(Level.SEVERE, \"Artifactory Release Staging API invocation failed: \" + e.getMessage(), e);\n resp.setStatus(StaplerResponse.SC_INTERNAL_SERVER_ERROR);\n ErrorResponse errorResponse = new ErrorResponse(StaplerResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());\n ObjectMapper mapper = new ObjectMapper();\n mapper.enable(SerializationFeature.INDENT_OUTPUT);\n resp.getWriter().write(mapper.writeValueAsString(errorResponse));\n }\n }",
"public String registerHandler(GFXEventHandler handler) {\n String uuid = UUID.randomUUID().toString();\n handlers.put(uuid, handler);\n return uuid;\n }",
"public static void composeThroughMask(Raster src, WritableRaster dst, Raster sel) {\n\t\tint x = src.getMinX();\n\t\tint y = src.getMinY();\n\t\tint w = src.getWidth();\n\t\tint h = src.getHeight();\n\n\t\tint srcRGB[] = null;\n\t\tint selRGB[] = null;\n\t\tint dstRGB[] = null;\n\n\t\tfor ( int i = 0; i < h; i++ ) {\n\t\t\tsrcRGB = src.getPixels(x, y, w, 1, srcRGB);\n\t\t\tselRGB = sel.getPixels(x, y, w, 1, selRGB);\n\t\t\tdstRGB = dst.getPixels(x, y, w, 1, dstRGB);\n\n\t\t\tint k = x;\n\t\t\tfor ( int j = 0; j < w; j++ ) {\n\t\t\t\tint sr = srcRGB[k];\n\t\t\t\tint dir = dstRGB[k];\n\t\t\t\tint sg = srcRGB[k+1];\n\t\t\t\tint dig = dstRGB[k+1];\n\t\t\t\tint sb = srcRGB[k+2];\n\t\t\t\tint dib = dstRGB[k+2];\n\t\t\t\tint sa = srcRGB[k+3];\n\t\t\t\tint dia = dstRGB[k+3];\n\n\t\t\t\tfloat a = selRGB[k+3]/255f;\n\t\t\t\tfloat ac = 1-a;\n\n\t\t\t\tdstRGB[k] = (int)(a*sr + ac*dir); \n\t\t\t\tdstRGB[k+1] = (int)(a*sg + ac*dig); \n\t\t\t\tdstRGB[k+2] = (int)(a*sb + ac*dib); \n\t\t\t\tdstRGB[k+3] = (int)(a*sa + ac*dia);\n\t\t\t\tk += 4;\n\t\t\t}\n\n\t\t\tdst.setPixels(x, y, w, 1, dstRGB);\n\t\t\ty++;\n\t\t}\n\t}",
"protected AllowableActions collectAllowableActions(CmsObject cms, CmsResource file) {\r\n\r\n try {\r\n\r\n if (file == null) {\r\n throw new IllegalArgumentException(\"File must not be null!\");\r\n }\r\n CmsLock lock = cms.getLock(file);\r\n CmsUser user = cms.getRequestContext().getCurrentUser();\r\n boolean canWrite = !cms.getRequestContext().getCurrentProject().isOnlineProject()\r\n && (lock.isOwnedBy(user) || lock.isLockableBy(user))\r\n && cms.hasPermissions(file, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.DEFAULT);\r\n boolean isReadOnly = !canWrite;\r\n boolean isFolder = file.isFolder();\r\n boolean isRoot = file.getRootPath().length() <= 1;\r\n\r\n Set<Action> aas = new LinkedHashSet<Action>();\r\n addAction(aas, Action.CAN_GET_OBJECT_PARENTS, !isRoot);\r\n addAction(aas, Action.CAN_GET_PROPERTIES, true);\r\n addAction(aas, Action.CAN_UPDATE_PROPERTIES, !isReadOnly);\r\n addAction(aas, Action.CAN_MOVE_OBJECT, !isReadOnly && !isRoot);\r\n addAction(aas, Action.CAN_DELETE_OBJECT, !isReadOnly && !isRoot);\r\n if (isFolder) {\r\n addAction(aas, Action.CAN_GET_DESCENDANTS, true);\r\n addAction(aas, Action.CAN_GET_CHILDREN, true);\r\n addAction(aas, Action.CAN_GET_FOLDER_PARENT, !isRoot);\r\n addAction(aas, Action.CAN_GET_FOLDER_TREE, true);\r\n addAction(aas, Action.CAN_CREATE_DOCUMENT, !isReadOnly);\r\n addAction(aas, Action.CAN_CREATE_FOLDER, !isReadOnly);\r\n addAction(aas, Action.CAN_DELETE_TREE, !isReadOnly);\r\n } else {\r\n addAction(aas, Action.CAN_GET_CONTENT_STREAM, true);\r\n addAction(aas, Action.CAN_SET_CONTENT_STREAM, !isReadOnly);\r\n addAction(aas, Action.CAN_GET_ALL_VERSIONS, true);\r\n }\r\n AllowableActionsImpl result = new AllowableActionsImpl();\r\n result.setAllowableActions(aas);\r\n return result;\r\n } catch (CmsException e) {\r\n handleCmsException(e);\r\n return null;\r\n }\r\n }",
"public void shutdown() {\n final Connection connection;\n synchronized (this) {\n if(shutdown) return;\n shutdown = true;\n connection = this.connection;\n if(connectTask != null) {\n connectTask.shutdown();\n }\n }\n if (connection != null) {\n connection.closeAsync();\n }\n }",
"@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n public void blacklistNode(int nodeId) {\n Collection<Node> nodesInCluster = adminClient.getAdminClientCluster().getNodes();\n\n if(blackListedNodes == null) {\n blackListedNodes = new ArrayList();\n }\n blackListedNodes.add(nodeId);\n\n for(Node node: nodesInCluster) {\n\n if(node.getId() == nodeId) {\n nodesToStream.remove(node);\n break;\n }\n\n }\n\n for(String store: storeNames) {\n try {\n SocketAndStreams sands = nodeIdStoreToSocketAndStreams.get(new Pair(store, nodeId));\n close(sands.getSocket());\n SocketDestination destination = nodeIdStoreToSocketRequest.get(new Pair(store,\n nodeId));\n streamingSocketPool.checkin(destination, sands);\n } catch(Exception ioE) {\n logger.error(ioE);\n }\n }\n }",
"public static void clear() {\n JobContext ctx = current_.get();\n if (null != ctx) {\n ctx.bag_.clear();\n JobContext parent = ctx.parent;\n if (null != parent) {\n current_.set(parent);\n ctx.parent = null;\n } else {\n current_.remove();\n Act.eventBus().trigger(new JobContextDestroyed(ctx));\n }\n }\n }"
] |
Use this API to fetch lbvserver_appflowpolicy_binding resources of given name . | [
"public static lbvserver_appflowpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_appflowpolicy_binding obj = new lbvserver_appflowpolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_appflowpolicy_binding response[] = (lbvserver_appflowpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"private void logUnexpectedStructure()\n {\n if (m_log != null)\n {\n m_log.println(\"ABORTED COLUMN - unexpected structure: \" + m_currentColumn.getClass().getSimpleName() + \" \" + m_currentColumn.getName());\n }\n }",
"public static final BigInteger printPriority(Priority priority)\n {\n int result = Priority.MEDIUM;\n\n if (priority != null)\n {\n result = priority.getValue();\n }\n\n return (BigInteger.valueOf(result));\n }",
"protected String pauseMsg() throws IOException {\n final WorkerStatus status = new WorkerStatus();\n status.setRunAt(new Date());\n status.setPaused(isPaused());\n return ObjectMapperFactory.get().writeValueAsString(status);\n }",
"private Table getTable(String name)\n {\n Table table = m_tables.get(name);\n if (table == null)\n {\n table = EMPTY_TABLE;\n }\n return table;\n }",
"public void startServer() throws Exception {\n if (!externalDatabaseHost) {\n try {\n this.port = Utils.getSystemPort(Constants.SYS_DB_PORT);\n server = Server.createTcpServer(\"-tcpPort\", String.valueOf(port), \"-tcpAllowOthers\").start();\n } catch (SQLException e) {\n if (e.toString().contains(\"java.net.UnknownHostException\")) {\n logger.error(\"Startup failure. Potential bug in OSX & Java7. Workaround: add name of local machine to '/etc/hosts.'\");\n logger.error(\"Example: 127.0.0.1 MacBook\");\n throw e;\n }\n }\n }\n }",
"public void sendEventsFromQueue() {\n if (null == queue || stopSending) {\n return;\n }\n LOG.fine(\"Scheduler called for sending events\");\n\n int packageSize = getEventsPerMessageCall();\n\n while (!queue.isEmpty()) {\n final List<Event> list = new ArrayList<Event>();\n int i = 0;\n while (i < packageSize && !queue.isEmpty()) {\n Event event = queue.remove();\n if (event != null && !filter(event)) {\n list.add(event);\n i++;\n }\n }\n if (list.size() > 0) {\n executor.execute(new Runnable() {\n public void run() {\n try {\n sendEvents(list);\n } catch (MonitoringException e) {\n e.logException(Level.SEVERE);\n }\n }\n });\n\n }\n }\n\n }",
"public boolean switchToStateAndCheckIfClone(final Eventable event, StateVertex newState,\n\t\t\t\t\t\t\t\t\t\t\t\tCrawlerContext context) {\n\t\tStateVertex cloneState = this.addStateToCurrentState(newState, event);\n\n\t\trunOnInvariantViolationPlugins(context);\n\n\t\tif (cloneState == null) {\n\t\t\tchangeState(newState);\n\t\t\tplugins.runOnNewStatePlugins(context, newState);\n\t\t\treturn true;\n\t\t} else {\n\t\t\tchangeState(cloneState);\n\t\t\treturn false;\n\t\t}\n\t}",
"private ImmutableList<Element> getNodeListForTagElement(Document dom,\n\t\t\tCrawlElement crawlElement,\n\t\t\tEventableConditionChecker eventableConditionChecker) {\n\n\t\tBuilder<Element> result = ImmutableList.builder();\n\n\t\tif (crawlElement.getTagName() == null) {\n\t\t\treturn result.build();\n\t\t}\n\n\t\tEventableCondition eventableCondition =\n\t\t\t\teventableConditionChecker.getEventableCondition(crawlElement.getId());\n\t\t// TODO Stefan; this part of the code should be re-factored, Hack-ed it this way to prevent\n\t\t// performance problems.\n\t\tImmutableList<String> expressions = getFullXpathForGivenXpath(dom, eventableCondition);\n\n\t\tNodeList nodeList = dom.getElementsByTagName(crawlElement.getTagName());\n\n\t\tfor (int k = 0; k < nodeList.getLength(); k++) {\n\n\t\t\tElement element = (Element) nodeList.item(k);\n\t\t\tboolean matchesXpath =\n\t\t\t\t\telementMatchesXpath(eventableConditionChecker, eventableCondition,\n\t\t\t\t\t\t\texpressions, element);\n\t\t\tLOG.debug(\"Element {} matches Xpath={}\", DomUtils.getElementString(element),\n\t\t\t\t\tmatchesXpath);\n\t\t\t/*\n\t\t\t * TODO Stefan This is a possible Thread-Interleaving problem, as / isChecked can return\n\t\t\t * false and when needed to add it can return true. / check if element is a candidate\n\t\t\t */\n\t\t\tString id = element.getNodeName() + \": \" + DomUtils.getAllElementAttributes(element);\n\t\t\tif (matchesXpath && !checkedElements.isChecked(id)\n\t\t\t\t\t&& !isExcluded(dom, element, eventableConditionChecker)) {\n\t\t\t\taddElement(element, result, crawlElement);\n\t\t\t} else {\n\t\t\t\tLOG.debug(\"Element {} was not added\", element);\n\t\t\t}\n\t\t}\n\t\treturn result.build();\n\t}",
"public static Optional<Field> getField(Class<?> type, final String fieldName) {\n Optional<Field> field = Iterables.tryFind(newArrayList(type.getDeclaredFields()), havingFieldName(fieldName));\n\n if (!field.isPresent() && type.getSuperclass() != null){\n field = getField(type.getSuperclass(), fieldName);\n }\n\n return field;\n }"
] |
Creates a new HTML-formatted label with the given content.
@param html the label content | [
"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 List<String> createBacktrace(final Throwable t) {\n final List<String> bTrace = new LinkedList<String>();\n for (final StackTraceElement ste : t.getStackTrace()) {\n bTrace.add(BT_PREFIX + ste.toString());\n }\n if (t.getCause() != null) {\n addCauseToBacktrace(t.getCause(), bTrace);\n }\n return bTrace;\n }",
"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 double normP2( DMatrixRMaj A ) {\n if( MatrixFeatures_DDRM.isVector(A)) {\n return normF(A);\n } else {\n return inducedP2(A);\n }\n }",
"private void addFilters(MpxjTreeNode parentNode, List<Filter> filters)\n {\n for (Filter field : filters)\n {\n final Filter f = field;\n MpxjTreeNode childNode = new MpxjTreeNode(field)\n {\n @Override public String toString()\n {\n return f.getName();\n }\n };\n parentNode.add(childNode);\n }\n }",
"public boolean shouldBeInReport(final DbDependency dependency) {\n if(dependency == null){\n return false;\n }\n if(dependency.getTarget() == null){\n return false;\n }\n if(corporateFilter != null){\n if(!decorator.getShowThirdparty() && !corporateFilter.filter(dependency)){\n return false;\n }\n if(!decorator.getShowCorporate() && corporateFilter.filter(dependency)){\n return false;\n }\n }\n\n if(!scopeHandler.filter(dependency)){\n return false;\n }\n\n return true;\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 synchronized boolean hasNext()\r\n {\r\n try\r\n {\r\n if (!isHasCalledCheck())\r\n {\r\n setHasCalledCheck(true);\r\n setHasNext(getRsAndStmt().m_rs.next());\r\n if (!getHasNext())\r\n {\r\n autoReleaseDbResources();\r\n }\r\n }\r\n }\r\n catch (Exception ex)\r\n {\r\n setHasNext(false);\r\n autoReleaseDbResources();\r\n if(ex instanceof ResourceClosedException)\r\n {\r\n throw (ResourceClosedException)ex;\r\n }\r\n if(ex instanceof SQLException)\r\n {\r\n throw new PersistenceBrokerSQLException(\"Calling ResultSet.next() failed\", (SQLException) ex);\r\n }\r\n else\r\n {\r\n throw new PersistenceBrokerException(\"Can't get next row from ResultSet\", ex);\r\n }\r\n }\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"hasNext() -> \" + getHasNext());\r\n\r\n return getHasNext();\r\n }",
"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 base_response add(nitro_service client, dnssuffix resource) throws Exception {\n\t\tdnssuffix addresource = new dnssuffix();\n\t\taddresource.Dnssuffix = resource.Dnssuffix;\n\t\treturn addresource.add_resource(client);\n\t}"
] |
Tries to load a class using the specified ResourceLoader. Returns null if the class is not found.
@param className
@param resourceLoader
@return the loaded class or null if the given class cannot be loaded | [
"public static <T> Class<T> loadClass(String className, ResourceLoader resourceLoader) {\n try {\n return cast(resourceLoader.classForName(className));\n } catch (ResourceLoadingException e) {\n return null;\n } catch (SecurityException e) {\n return null;\n }\n }"
] | [
"public static java.sql.Time getTime(Object value) {\n try {\n return toTime(value);\n } catch (ParseException pe) {\n pe.printStackTrace();\n return null;\n }\n }",
"public boolean shouldCache(String requestUri) {\n\t\tString uri = requestUri.toLowerCase();\n\t\treturn checkContains(uri, cacheIdentifiers) || checkSuffixes(uri, cacheSuffixes);\n\t}",
"protected void putConnectionBackInPartition(ConnectionHandle connectionHandle) throws SQLException {\r\n\r\n\t\tif (this.cachedPoolStrategy && ((CachedConnectionStrategy)this.connectionStrategy).tlConnections.dumbGet().getValue()){\r\n\t\t\tconnectionHandle.logicallyClosed.set(true);\r\n\t\t\t((CachedConnectionStrategy)this.connectionStrategy).tlConnections.set(new AbstractMap.SimpleEntry<ConnectionHandle, Boolean>(connectionHandle, false));\r\n\t\t} else {\r\n\t\t\tBlockingQueue<ConnectionHandle> queue = connectionHandle.getOriginatingPartition().getFreeConnections();\r\n\t\t\t\tif (!queue.offer(connectionHandle)){ // this shouldn't fail\r\n\t\t\t\t\tconnectionHandle.internalClose();\r\n\t\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t}",
"public int getPartition(byte[] key,\n byte[] value,\n int numReduceTasks) {\n try {\n /**\n * {@link partitionId} is the Voldemort primary partition that this\n * record belongs to.\n */\n int partitionId = ByteUtils.readInt(value, ByteUtils.SIZE_OF_INT);\n\n /**\n * This is the base number we will ultimately mod by {@link numReduceTasks}\n * to determine which reduce task to shuffle to.\n */\n int magicNumber = partitionId;\n\n if (getSaveKeys() && !buildPrimaryReplicasOnly) {\n /**\n * When saveKeys is enabled (which also implies we are generating\n * READ_ONLY_V2 format files), then we are generating files with\n * a replica type, with one file per replica.\n *\n * Each replica is sent to a different reducer, and thus the\n * {@link magicNumber} is scaled accordingly.\n *\n * The downside to this is that it is pretty wasteful. The files\n * generated for each replicas are identical to one another, so\n * there's no point in generating them independently in many\n * reducers.\n *\n * This is one of the reasons why buildPrimaryReplicasOnly was\n * written. In this mode, we only generate the files for the\n * primary replica, which means the number of reducers is\n * minimized and {@link magicNumber} does not need to be scaled.\n */\n int replicaType = (int) ByteUtils.readBytes(value,\n 2 * ByteUtils.SIZE_OF_INT,\n ByteUtils.SIZE_OF_BYTE);\n magicNumber = magicNumber * getStoreDef().getReplicationFactor() + replicaType;\n }\n\n if (!getReducerPerBucket()) {\n /**\n * Partition files can be split in many chunks in order to limit the\n * maximum file size downloaded and handled by Voldemort servers.\n *\n * {@link chunkId} represents which chunk of partition then current\n * record belongs to.\n */\n int chunkId = ReadOnlyUtils.chunk(key, getNumChunks());\n\n /**\n * When reducerPerBucket is disabled, all chunks are sent to a\n * different reducer. This increases parallelism at the expense\n * of adding more load on Hadoop.\n *\n * {@link magicNumber} is thus scaled accordingly, in order to\n * leverage the extra reducers available to us.\n */\n magicNumber = magicNumber * getNumChunks() + chunkId;\n }\n\n /**\n * Finally, we mod {@link magicNumber} by {@link numReduceTasks},\n * since the MapReduce framework expects the return of this function\n * to be bounded by the number of reduce tasks running in the job.\n */\n return magicNumber % numReduceTasks;\n } catch (Exception e) {\n throw new VoldemortException(\"Caught exception in getPartition()!\" +\n \" key: \" + ByteUtils.toHexString(key) +\n \", value: \" + ByteUtils.toHexString(value) +\n \", numReduceTasks: \" + numReduceTasks, e);\n }\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 }",
"protected ServiceName serviceName(final String name) {\n return baseServiceName != null ? baseServiceName.append(name) : null;\n }",
"public GVRAnimator findAnimation(String name)\n {\n for (GVRAnimator anim : mAnimations)\n {\n if (name.equals(anim.getName()))\n {\n return anim;\n }\n }\n return null;\n }",
"private void writeTask(Task mpxjTask, List<net.sf.mpxj.planner.schema.Task> taskList) throws JAXBException\n {\n net.sf.mpxj.planner.schema.Task plannerTask = m_factory.createTask();\n taskList.add(plannerTask);\n plannerTask.setEnd(getDateTimeString(mpxjTask.getFinish()));\n plannerTask.setId(getIntegerString(mpxjTask.getUniqueID()));\n plannerTask.setName(getString(mpxjTask.getName()));\n plannerTask.setNote(mpxjTask.getNotes());\n plannerTask.setPercentComplete(getIntegerString(mpxjTask.getPercentageWorkComplete()));\n plannerTask.setPriority(mpxjTask.getPriority() == null ? null : getIntegerString(mpxjTask.getPriority().getValue() * 10));\n plannerTask.setScheduling(getScheduling(mpxjTask.getType()));\n plannerTask.setStart(getDateTimeString(DateHelper.getDayStartDate(mpxjTask.getStart())));\n if (mpxjTask.getMilestone())\n {\n plannerTask.setType(\"milestone\");\n }\n else\n {\n plannerTask.setType(\"normal\");\n }\n plannerTask.setWork(getDurationString(mpxjTask.getWork()));\n plannerTask.setWorkStart(getDateTimeString(mpxjTask.getStart()));\n\n ConstraintType mpxjConstraintType = mpxjTask.getConstraintType();\n if (mpxjConstraintType != ConstraintType.AS_SOON_AS_POSSIBLE)\n {\n Constraint plannerConstraint = m_factory.createConstraint();\n plannerTask.setConstraint(plannerConstraint);\n if (mpxjConstraintType == ConstraintType.START_NO_EARLIER_THAN)\n {\n plannerConstraint.setType(\"start-no-earlier-than\");\n }\n else\n {\n if (mpxjConstraintType == ConstraintType.MUST_START_ON)\n {\n plannerConstraint.setType(\"must-start-on\");\n }\n }\n\n plannerConstraint.setTime(getDateTimeString(mpxjTask.getConstraintDate()));\n }\n\n //\n // Write predecessors\n //\n writePredecessors(mpxjTask, plannerTask);\n\n m_eventManager.fireTaskWrittenEvent(mpxjTask);\n\n //\n // Write child tasks\n //\n List<net.sf.mpxj.planner.schema.Task> childTaskList = plannerTask.getTask();\n for (Task task : mpxjTask.getChildTasks())\n {\n writeTask(task, childTaskList);\n }\n }",
"private static void registerImage(String imageId, String imageTag, String targetRepo,\n ArrayListMultimap<String, String> artifactsProps, int buildInfoId) throws IOException {\n DockerImage image = new DockerImage(imageId, imageTag, targetRepo, buildInfoId, artifactsProps);\n images.add(image);\n }"
] |
On complete.
Save response headers when needed.
@param response
the response
@return the response on single request | [
"public ResponseOnSingeRequest onComplete(Response response) {\n\n cancelCancellable();\n try {\n \n Map<String, List<String>> responseHeaders = null;\n if (responseHeaderMeta != null) {\n responseHeaders = new LinkedHashMap<String, List<String>>();\n if (responseHeaderMeta.isGetAll()) {\n for (Map.Entry<String, List<String>> header : response\n .getHeaders()) {\n responseHeaders.put(header.getKey().toLowerCase(Locale.ROOT), header.getValue());\n }\n } else {\n for (String key : responseHeaderMeta.getKeys()) {\n if (response.getHeaders().containsKey(key)) {\n responseHeaders.put(key.toLowerCase(Locale.ROOT),\n response.getHeaders().get(key));\n }\n }\n }\n }\n\n int statusCodeInt = response.getStatusCode();\n String statusCode = statusCodeInt + \" \" + response.getStatusText();\n String charset = ParallecGlobalConfig.httpResponseBodyCharsetUsesResponseContentType &&\n response.getContentType()!=null ? \n AsyncHttpProviderUtils.parseCharset(response.getContentType())\n : ParallecGlobalConfig.httpResponseBodyDefaultCharset;\n if(charset == null){\n getLogger().error(\"charset is not provided from response content type. Use default\");\n charset = ParallecGlobalConfig.httpResponseBodyDefaultCharset; \n }\n reply(response.getResponseBody(charset), false, null, null, statusCode,\n statusCodeInt, responseHeaders);\n } catch (IOException e) {\n getLogger().error(\"fail response.getResponseBody \" + e);\n }\n\n return null;\n }"
] | [
"public static void addToMediaStore(Context context, File file) {\n String[] path = new String[]{file.getPath()};\n MediaScannerConnection.scanFile(context, path, null, null);\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 synchronized FormInputValueHelper getInstance(\n\t\t\tInputSpecification inputSpecification, FormFillMode formFillMode) {\n\t\tif (instance == null)\n\t\t\tinstance = new FormInputValueHelper(inputSpecification,\n\t\t\t\t\tformFillMode);\n\t\treturn instance;\n\t}",
"private void readTaskBaselines(Project.Tasks.Task xmlTask, Task mpxjTask, TimeUnit durationFormat)\n {\n for (Project.Tasks.Task.Baseline baseline : xmlTask.getBaseline())\n {\n int number = NumberHelper.getInt(baseline.getNumber());\n\n Double cost = DatatypeConverter.parseCurrency(baseline.getCost());\n Duration duration = DatatypeConverter.parseDuration(m_projectFile, durationFormat, baseline.getDuration());\n Date finish = baseline.getFinish();\n Date start = baseline.getStart();\n Duration work = DatatypeConverter.parseDuration(m_projectFile, TimeUnit.HOURS, baseline.getWork());\n\n if (number == 0)\n {\n mpxjTask.setBaselineCost(cost);\n mpxjTask.setBaselineDuration(duration);\n mpxjTask.setBaselineFinish(finish);\n mpxjTask.setBaselineStart(start);\n mpxjTask.setBaselineWork(work);\n }\n else\n {\n mpxjTask.setBaselineCost(number, cost);\n mpxjTask.setBaselineDuration(number, duration);\n mpxjTask.setBaselineFinish(number, finish);\n mpxjTask.setBaselineStart(number, start);\n mpxjTask.setBaselineWork(number, work);\n }\n }\n }",
"public DbOrganization getOrganization(final DbArtifact dbArtifact) {\n final DbModule module = getModule(dbArtifact);\n\n if(module == null || module.getOrganization() == null){\n return null;\n }\n\n return repositoryHandler.getOrganization(module.getOrganization());\n }",
"public void updateSequenceElement(int[] sequence, int pos, int oldVal) {\r\n if(models != null){\r\n for(int i = 0; i < models.length; i++)\r\n models[i].updateSequenceElement(sequence, pos, oldVal);\r\n return; \r\n }\r\n model1.updateSequenceElement(sequence, pos, 0);\r\n model2.updateSequenceElement(sequence, pos, 0);\r\n }",
"public static base_responses delete(nitro_service client, String fipskeyname[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (fipskeyname != null && fipskeyname.length > 0) {\n\t\t\tsslfipskey deleteresources[] = new sslfipskey[fipskeyname.length];\n\t\t\tfor (int i=0;i<fipskeyname.length;i++){\n\t\t\t\tdeleteresources[i] = new sslfipskey();\n\t\t\t\tdeleteresources[i].fipskeyname = fipskeyname[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"public static void cleanIneligibleKeys(Map<ByteArray, Map<Value, Set<ClusterNode>>> keyVersionNodeSetMap,\n int requiredWrite) {\n Set<ByteArray> keysToDelete = new HashSet<ByteArray>();\n for (Map.Entry<ByteArray, Map<Value, Set<ClusterNode>>> entry : keyVersionNodeSetMap.entrySet()) {\n Set<Value> valuesToDelete = new HashSet<Value>();\n\n ByteArray key = entry.getKey();\n Map<Value, Set<ClusterNode>> valueNodeSetMap = entry.getValue();\n // mark version for deletion if not enough writes\n for (Map.Entry<Value, Set<ClusterNode>> versionNodeSetEntry : valueNodeSetMap.entrySet()) {\n Set<ClusterNode> nodeSet = versionNodeSetEntry.getValue();\n if (nodeSet.size() < requiredWrite) {\n valuesToDelete.add(versionNodeSetEntry.getKey());\n }\n }\n // delete versions\n for (Value v : valuesToDelete) {\n valueNodeSetMap.remove(v);\n }\n // mark key for deletion if no versions left\n if (valueNodeSetMap.size() == 0) {\n keysToDelete.add(key);\n }\n }\n // delete keys\n for (ByteArray k : keysToDelete) {\n keyVersionNodeSetMap.remove(k);\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}"
] |
Skip to the next matching short value.
@param buffer input data array
@param offset start offset into the input array
@param value value to match
@return offset of matching pattern | [
"public static int skipToNextMatchingShort(byte[] buffer, int offset, int value)\n {\n int nextOffset = offset;\n while (getShort(buffer, nextOffset) != value)\n {\n ++nextOffset;\n }\n nextOffset += 2;\n\n return nextOffset;\n }"
] | [
"public static int findLastIndexOf(Object self, int startIndex, Closure closure) {\n int result = -1;\n int i = 0;\n BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);\n for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); i++) {\n Object value = iter.next();\n if (i < startIndex) {\n continue;\n }\n if (bcw.call(value)) {\n result = i;\n }\n }\n return result;\n }",
"public Object get(String name, ObjectFactory<?> factory) {\n\t\tThreadScopeContext context = ThreadScopeContextHolder.getContext();\n\n\t\tObject result = context.getBean(name);\n\t\tif (null == result) {\n\t\t\tresult = factory.getObject();\n\t\t\tcontext.setBean(name, result);\n\t\t}\n\t\treturn result;\n\t}",
"public final int toCodePoints(char[] src, int srcOff, int srcLen, int[] dest, int destOff) {\n if (srcLen < 0) {\n throw new IllegalArgumentException(\"srcLen must be >= 0\");\n }\n int codePointCount = 0;\n for (int i = 0; i < srcLen; ) {\n final int cp = codePointAt(src, srcOff + i, srcOff + srcLen);\n final int charCount = Character.charCount(cp);\n dest[destOff + codePointCount++] = cp;\n i += charCount;\n }\n return codePointCount;\n }",
"public static double huntKennedyCMSFloorValue(\n\t\t\tdouble forwardSwaprate,\n\t\t\tdouble volatility,\n\t\t\tdouble swapAnnuity,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble swapMaturity,\n\t\t\tdouble payoffUnit,\n\t\t\tdouble optionStrike)\n\t{\n\t\tdouble huntKennedyCMSOptionValue = huntKennedyCMSOptionValue(forwardSwaprate, volatility, swapAnnuity, optionMaturity, swapMaturity, payoffUnit, optionStrike);\n\n\t\t// A floor is an option plus the strike (max(X,K) = max(X-K,0) + K)\n\t\treturn huntKennedyCMSOptionValue + optionStrike * payoffUnit;\n\t}",
"public static void pullImage(String imageTag, String username, String password, String host) throws IOException {\n final AuthConfig authConfig = new AuthConfig();\n authConfig.withUsername(username);\n authConfig.withPassword(password);\n\n DockerClient dockerClient = null;\n try {\n dockerClient = getDockerClient(host);\n dockerClient.pullImageCmd(imageTag).withAuthConfig(authConfig).exec(new PullImageResultCallback()).awaitSuccess();\n } finally {\n closeQuietly(dockerClient);\n }\n }",
"public PhotoList<Photo> getNotInSet(int perPage, int page) throws FlickrException {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", PhotosInterface.METHOD_GET_NOT_IN_SET);\r\n\r\n RequestContext requestContext = RequestContext.getRequestContext();\r\n\r\n List<String> extras = requestContext.getExtras();\r\n if (extras.size() > 0) {\r\n parameters.put(\"extras\", StringUtilities.join(extras, \",\"));\r\n }\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", Integer.toString(perPage));\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", Integer.toString(page));\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n photos.setPage(photosElement.getAttribute(\"page\"));\r\n photos.setPages(photosElement.getAttribute(\"pages\"));\r\n photos.setPerPage(photosElement.getAttribute(\"perpage\"));\r\n photos.setTotal(photosElement.getAttribute(\"total\"));\r\n\r\n NodeList photoElements = photosElement.getElementsByTagName(\"photo\");\r\n for (int i = 0; i < photoElements.getLength(); i++) {\r\n Element photoElement = (Element) photoElements.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement));\r\n }\r\n return photos;\r\n }",
"protected void checkConflictingRoles() {\n if (getType().isAnnotationPresent(Interceptor.class)) {\n throw BeanLogger.LOG.ejbCannotBeInterceptor(getType());\n }\n if (getType().isAnnotationPresent(Decorator.class)) {\n throw BeanLogger.LOG.ejbCannotBeDecorator(getType());\n }\n }",
"public static int cudnnSetTensor4dDescriptorEx(\n cudnnTensorDescriptor tensorDesc, \n int dataType, /** image data type */\n int n, /** number of inputs (batch size) */\n int c, /** number of input feature maps */\n int h, /** height of input section */\n int w, /** width of input section */\n int nStride, \n int cStride, \n int hStride, \n int wStride)\n {\n return checkResult(cudnnSetTensor4dDescriptorExNative(tensorDesc, dataType, n, c, h, w, nStride, cStride, hStride, wStride));\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 }"
] |
Generates a Map of query parameters for Module regarding the filters
@return Map<String, Object> | [
"public Map<String, Object> getModuleFieldsFilters() {\n final Map<String, Object> params = new HashMap<String, Object>();\n\n for(final Filter filter: filters){\n params.putAll(filter.moduleFilterFields());\n }\n\n return params;\n }"
] | [
"public static vpnvserver_authenticationradiuspolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_authenticationradiuspolicy_binding obj = new vpnvserver_authenticationradiuspolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_authenticationradiuspolicy_binding response[] = (vpnvserver_authenticationradiuspolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\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 }",
"@Override\n synchronized public V put(K key, V value) {\n V oldValue = this.get(key);\n try {\n super.put(key, value);\n writeBack(key, value);\n return oldValue;\n } catch(Exception e) {\n super.put(key, oldValue);\n writeBack(key, oldValue);\n throw new VoldemortException(\"Failed to put(\" + key + \", \" + value\n + \") in write through cache\", e);\n }\n }",
"public boolean toggleProfile(Boolean enabled) {\n // TODO: make this return values properly\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"active\", enabled.toString())\n };\n try {\n String uri = BASE_PROFILE + uriEncode(this._profileName) + \"/\" + BASE_CLIENTS + \"/\";\n if (_clientId == null) {\n uri += \"-1\";\n } else {\n uri += _clientId;\n }\n JSONObject response = new JSONObject(doPost(uri, params));\n } catch (Exception e) {\n // some sort of error\n System.out.println(e.getMessage());\n return false;\n }\n return true;\n }",
"public static double Y(double x) {\r\n if (x < 8.0) {\r\n double y = x * x;\r\n double ans1 = x * (-0.4900604943e13 + y * (0.1275274390e13\r\n + y * (-0.5153438139e11 + y * (0.7349264551e9\r\n + y * (-0.4237922726e7 + y * 0.8511937935e4)))));\r\n double ans2 = 0.2499580570e14 + y * (0.4244419664e12\r\n + y * (0.3733650367e10 + y * (0.2245904002e8\r\n + y * (0.1020426050e6 + y * (0.3549632885e3 + y)))));\r\n return (ans1 / ans2) + 0.636619772 * (J(x) * Math.log(x) - 1.0 / x);\r\n } else {\r\n double z = 8.0 / x;\r\n double y = z * z;\r\n double xx = x - 2.356194491;\r\n double ans1 = 1.0 + y * (0.183105e-2 + y * (-0.3516396496e-4\r\n + y * (0.2457520174e-5 + y * (-0.240337019e-6))));\r\n double ans2 = 0.04687499995 + y * (-0.2002690873e-3\r\n + y * (0.8449199096e-5 + y * (-0.88228987e-6\r\n + y * 0.105787412e-6)));\r\n return Math.sqrt(0.636619772 / x) *\r\n (Math.sin(xx) * ans1 + z * Math.cos(xx) * ans2);\r\n }\r\n }",
"public Operation.Info create( Symbol op , Variable left , Variable right ) {\n switch( op ) {\n case PLUS:\n return Operation.add(left, right, managerTemp);\n\n case MINUS:\n return Operation.subtract(left, right, managerTemp);\n\n case TIMES:\n return Operation.multiply(left, right, managerTemp);\n\n case RDIVIDE:\n return Operation.divide(left, right, managerTemp);\n\n case LDIVIDE:\n return Operation.divide(right, left, managerTemp);\n\n case POWER:\n return Operation.pow(left, right, managerTemp);\n\n case ELEMENT_DIVIDE:\n return Operation.elementDivision(left, right, managerTemp);\n\n case ELEMENT_TIMES:\n return Operation.elementMult(left, right, managerTemp);\n\n case ELEMENT_POWER:\n return Operation.elementPow(left, right, managerTemp);\n\n default:\n throw new RuntimeException(\"Unknown operation \" + op);\n }\n }",
"public void removeDropPasteWorker(DropPasteWorkerInterface worker)\r\n {\r\n this.dropPasteWorkerSet.remove(worker);\r\n java.util.Iterator it = this.dropPasteWorkerSet.iterator();\r\n int newDefaultActions = 0;\r\n while (it.hasNext())\r\n newDefaultActions |= ((DropPasteWorkerInterface)it.next()).getAcceptableActions(defaultDropTarget.getComponent());\r\n defaultDropTarget.setDefaultActions(newDefaultActions);\r\n }",
"public <T> T getNodeMetaData(Object key) {\n if (metaDataMap == null) {\n return (T) null;\n }\n return (T) metaDataMap.get(key);\n }",
"private Map<Integer, List<Row>> createTimeEntryMap(List<Row> rows) throws ParseException\n {\n Map<Integer, List<Row>> map = new HashMap<Integer, List<Row>>();\n for (Row row : rows)\n {\n Integer workPatternID = row.getInteger(\"ID\");\n String shifts = row.getString(\"SHIFTS\");\n map.put(workPatternID, createTimeEntryRowList(shifts));\n }\n return map;\n }"
] |
Use this API to fetch all the sslcipher resources that are configured on netscaler. | [
"public static sslcipher[] get(nitro_service service) throws Exception{\n\t\tsslcipher obj = new sslcipher();\n\t\tsslcipher[] response = (sslcipher[])obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"public PathAddress append(List<PathElement> additionalElements) {\n final ArrayList<PathElement> newList = new ArrayList<PathElement>(pathAddressList.size() + additionalElements.size());\n newList.addAll(pathAddressList);\n newList.addAll(additionalElements);\n return pathAddress(newList);\n }",
"public static base_responses update(nitro_service client, snmpmanager resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsnmpmanager updateresources[] = new snmpmanager[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new snmpmanager();\n\t\t\t\tupdateresources[i].ipaddress = resources[i].ipaddress;\n\t\t\t\tupdateresources[i].netmask = resources[i].netmask;\n\t\t\t\tupdateresources[i].domainresolveretry = resources[i].domainresolveretry;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public static long getVisibilityCacheWeight(FluoConfiguration conf) {\n long size = conf.getLong(VISIBILITY_CACHE_WEIGHT, VISIBILITY_CACHE_WEIGHT_DEFAULT);\n if (size <= 0) {\n throw new IllegalArgumentException(\n \"Cache size must be positive for \" + VISIBILITY_CACHE_WEIGHT);\n }\n return size;\n }",
"public static String get(String url, Map<String, String> customHeaders, Map<String, String> params) throws URISyntaxException, IOException, HTTPException {\n LOGGER.log(Level.INFO, \"Sending GET request to the url {0}\", url);\n\n URIBuilder uriBuilder = new URIBuilder(url);\n\n if (params != null && params.size() > 0) {\n for (Map.Entry<String, String> param : params.entrySet()) {\n uriBuilder.setParameter(param.getKey(), param.getValue());\n }\n }\n\n HttpGet httpGet = new HttpGet(uriBuilder.build());\n\n populateHeaders(httpGet, customHeaders);\n\n HttpClient httpClient = HttpClientBuilder.create().build();\n\n HttpResponse httpResponse = httpClient.execute(httpGet);\n\n int statusCode = httpResponse.getStatusLine().getStatusCode();\n if (isErrorStatus(statusCode)) {\n String jsonErrorResponse = EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);\n throw new HTTPException(statusCode, httpResponse.getStatusLine().getReasonPhrase(), jsonErrorResponse);\n }\n\n return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);\n }",
"public void setArgs(String[] args) {\n if (args == null) {\n args = new String[]{};\n }\n this.args = args;\n this.argsList = Collections.unmodifiableList(new ArrayList<String>(Arrays.asList(args)));\n }",
"public ForeignkeyDef getForeignkey(String name, String tableName)\r\n {\r\n String realName = (name == null ? \"\" : name);\r\n ForeignkeyDef def = null;\r\n\r\n for (Iterator it = getForeignkeys(); it.hasNext();)\r\n {\r\n def = (ForeignkeyDef)it.next();\r\n if (realName.equals(def.getName()) &&\r\n def.getTableName().equals(tableName))\r\n {\r\n return def;\r\n }\r\n }\r\n return null;\r\n }",
"public byte[] toArray() {\n byte[] copy = new byte[length];\n System.arraycopy(data, offset, copy, 0, length);\n return copy;\n }",
"public static <E, V> ServiceFuture<List<E>> fromHeaderPageResponse(Observable<ServiceResponseWithHeaders<Page<E>, V>> first, final Func1<String, Observable<ServiceResponseWithHeaders<Page<E>, V>>> next, final ListOperationCallback<E> callback) {\n final AzureServiceFuture<List<E>> serviceCall = new AzureServiceFuture<>();\n final PagingSubscriber<E> subscriber = new PagingSubscriber<>(serviceCall, new Func1<String, Observable<ServiceResponse<Page<E>>>>() {\n @Override\n public Observable<ServiceResponse<Page<E>>> call(String s) {\n return next.call(s)\n .map(new Func1<ServiceResponseWithHeaders<Page<E>, V>, ServiceResponse<Page<E>>>() {\n @Override\n public ServiceResponse<Page<E>> call(ServiceResponseWithHeaders<Page<E>, V> pageVServiceResponseWithHeaders) {\n return pageVServiceResponseWithHeaders;\n }\n });\n }\n }, callback);\n serviceCall.setSubscription(first\n .single()\n .subscribe(subscriber));\n return serviceCall;\n }",
"private void readTaskCustomFields(net.sf.mpxj.ganttproject.schema.Task gpTask, Task mpxjTask)\n {\n //\n // Populate custom field default values\n //\n Map<FieldType, Object> customFields = new HashMap<FieldType, Object>();\n for (Pair<FieldType, String> definition : m_taskPropertyDefinitions.values())\n {\n customFields.put(definition.getFirst(), definition.getSecond());\n }\n\n //\n // Update with custom field actual values\n //\n for (CustomTaskProperty property : gpTask.getCustomproperty())\n {\n Pair<FieldType, String> definition = m_taskPropertyDefinitions.get(property.getTaskpropertyId());\n if (definition != null)\n {\n //\n // Retrieve the value. If it is empty, use the default.\n //\n String value = property.getValueAttribute();\n if (value.isEmpty())\n {\n value = null;\n }\n\n //\n // If we have a value,convert it to the correct type\n //\n if (value != null)\n {\n Object result;\n\n switch (definition.getFirst().getDataType())\n {\n case NUMERIC:\n {\n if (value.indexOf('.') == -1)\n {\n result = Integer.valueOf(value);\n }\n else\n {\n result = Double.valueOf(value);\n }\n break;\n }\n\n case DATE:\n {\n try\n {\n result = m_dateFormat.parse(value);\n }\n catch (ParseException ex)\n {\n result = null;\n }\n break;\n }\n\n case BOOLEAN:\n {\n result = Boolean.valueOf(value.equals(\"true\"));\n break;\n }\n\n default:\n {\n result = value;\n break;\n }\n }\n\n if (result != null)\n {\n customFields.put(definition.getFirst(), result);\n }\n }\n }\n }\n\n for (Map.Entry<FieldType, Object> item : customFields.entrySet())\n {\n if (item.getValue() != null)\n {\n mpxjTask.set(item.getKey(), item.getValue());\n }\n }\n }"
] |
Formats a percentage value.
@param number MPXJ percentage value
@return Primavera percentage value | [
"private Double getPercentage(Number number)\n {\n Double result = null;\n\n if (number != null)\n {\n result = Double.valueOf(number.doubleValue() / 100);\n }\n\n return result;\n }"
] | [
"public static void checkDelegateType(Decorator<?> decorator) {\n\n Set<Type> types = new HierarchyDiscovery(decorator.getDelegateType()).getTypeClosure();\n\n for (Type decoratedType : decorator.getDecoratedTypes()) {\n if(!types.contains(decoratedType)) {\n throw BeanLogger.LOG.delegateMustSupportEveryDecoratedType(decoratedType, decorator);\n }\n }\n }",
"public static String changeFileNameSuffixTo(String filename, String suffix) {\n\n int dotPos = filename.lastIndexOf('.');\n if (dotPos != -1) {\n return filename.substring(0, dotPos + 1) + suffix;\n } else {\n // the string has no suffix\n return filename;\n }\n }",
"public void deployApplication(String applicationName, URL... urls) throws IOException {\n this.applicationName = applicationName;\n\n for (URL url : urls) {\n try (InputStream inputStream = url.openStream()) {\n deploy(inputStream);\n }\n }\n }",
"public void promote() {\n URL url = VERSION_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.fileID, \"current\");\n\n JsonObject jsonObject = new JsonObject();\n jsonObject.add(\"type\", \"file_version\");\n jsonObject.add(\"id\", this.getID());\n\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n request.setBody(jsonObject.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n this.parseJSON(JsonObject.readFrom(response.getJSON()));\n }",
"public static StoreDefinition getStoreDef(List<StoreDefinition> list, String name) {\n for(StoreDefinition def: list)\n if(def.getName().equals(name))\n return def;\n return null;\n }",
"public ExecInspection execStartVerbose(String containerId, String... commands) {\n this.readWriteLock.readLock().lock();\n try {\n String id = execCreate(containerId, commands);\n CubeOutput output = execStartOutput(id);\n\n return new ExecInspection(output, inspectExec(id));\n } finally {\n this.readWriteLock.readLock().unlock();\n }\n }",
"public static final Boolean parseExtendedAttributeBoolean(String value)\n {\n return ((value.equals(\"1\") ? Boolean.TRUE : Boolean.FALSE));\n }",
"private Map<Integer, List<Row>> createWorkPatternAssignmentMap(List<Row> rows) throws ParseException\n {\n Map<Integer, List<Row>> map = new HashMap<Integer, List<Row>>();\n for (Row row : rows)\n {\n Integer calendarID = row.getInteger(\"ID\");\n String workPatterns = row.getString(\"WORK_PATTERNS\");\n map.put(calendarID, createWorkPatternAssignmentRowList(workPatterns));\n }\n return map;\n }",
"public void fireAssignmentWrittenEvent(ResourceAssignment resourceAssignment)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.assignmentWritten(resourceAssignment);\n }\n }\n }"
] |
Sets the timeout used when connecting to the server.
@param timeout the time out to use
@return the builder | [
"public CliCommandBuilder setTimeout(final int timeout) {\n if (timeout > 0) {\n addCliArgument(CliArgument.TIMEOUT, Integer.toString(timeout));\n } else {\n addCliArgument(CliArgument.TIMEOUT, null);\n }\n return this;\n }"
] | [
"public List<String> getPropertyPaths() {\n List<String> result = new ArrayList<String>();\n\n for (String property : this.values.names()) {\n if (!property.startsWith(\"$\")) {\n result.add(this.propertyToPath(property));\n }\n }\n\n return result;\n }",
"public base_response enable_features(String[] features) throws Exception\n\t{\n\t\tbase_response result = null;\n\t\tnsfeature resource = new nsfeature();\n\t\tresource.set_feature(features);\n\t\toptions option = new options();\n\t\toption.set_action(\"enable\");\n\t\tresult = resource.perform_operation(this, option);\n\t\treturn result;\n\t}",
"private void writeAssignment(ResourceAssignment mpxj)\n {\n ResourceAssignmentType xml = m_factory.createResourceAssignmentType();\n m_project.getResourceAssignment().add(xml);\n Task task = mpxj.getTask();\n Task parentTask = task.getParentTask();\n Integer parentTaskUniqueID = parentTask == null ? null : parentTask.getUniqueID();\n\n xml.setActivityObjectId(mpxj.getTaskUniqueID());\n xml.setActualCost(getDouble(mpxj.getActualCost()));\n xml.setActualFinishDate(mpxj.getActualFinish());\n xml.setActualOvertimeUnits(getDuration(mpxj.getActualOvertimeWork()));\n xml.setActualRegularUnits(getDuration(mpxj.getActualWork()));\n xml.setActualStartDate(mpxj.getActualStart());\n xml.setActualUnits(getDuration(mpxj.getActualWork()));\n xml.setAtCompletionUnits(getDuration(mpxj.getRemainingWork()));\n xml.setPlannedCost(getDouble(mpxj.getActualCost()));\n xml.setFinishDate(mpxj.getFinish());\n xml.setGUID(DatatypeConverter.printUUID(mpxj.getGUID()));\n xml.setObjectId(mpxj.getUniqueID());\n xml.setPlannedDuration(getDuration(mpxj.getWork()));\n xml.setPlannedFinishDate(mpxj.getFinish());\n xml.setPlannedStartDate(mpxj.getStart());\n xml.setPlannedUnits(getDuration(mpxj.getWork()));\n xml.setPlannedUnitsPerTime(getPercentage(mpxj.getUnits()));\n xml.setProjectObjectId(PROJECT_OBJECT_ID);\n xml.setRateSource(\"Resource\");\n xml.setRemainingCost(getDouble(mpxj.getActualCost()));\n xml.setRemainingDuration(getDuration(mpxj.getRemainingWork()));\n xml.setRemainingFinishDate(mpxj.getFinish());\n xml.setRemainingStartDate(mpxj.getStart());\n xml.setRemainingUnits(getDuration(mpxj.getRemainingWork()));\n xml.setRemainingUnitsPerTime(getPercentage(mpxj.getUnits()));\n xml.setResourceObjectId(mpxj.getResourceUniqueID());\n xml.setStartDate(mpxj.getStart());\n xml.setWBSObjectId(parentTaskUniqueID);\n xml.getUDF().addAll(writeUDFType(FieldTypeClass.ASSIGNMENT, mpxj));\n }",
"public static boolean containsUid(IdRange[] idRanges, long uid) {\r\n if (null != idRanges && idRanges.length > 0) {\r\n for (IdRange range : idRanges) {\r\n if (range.includes(uid)) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n }",
"protected final boolean isGLThread() {\n final Thread glThread = sGLThread.get();\n return glThread != null && glThread.equals(Thread.currentThread());\n }",
"public CurrencyQueryBuilder setCountries(Locale... countries) {\n return set(CurrencyQuery.KEY_QUERY_COUNTRIES, Arrays.asList(countries));\n }",
"public static authenticationvserver_authenticationcertpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_authenticationcertpolicy_binding obj = new authenticationvserver_authenticationcertpolicy_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_authenticationcertpolicy_binding response[] = (authenticationvserver_authenticationcertpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static wisite_accessmethod_binding[] get(nitro_service service, String sitepath) throws Exception{\n\t\twisite_accessmethod_binding obj = new wisite_accessmethod_binding();\n\t\tobj.set_sitepath(sitepath);\n\t\twisite_accessmethod_binding response[] = (wisite_accessmethod_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public byte getByte(Integer type)\n {\n byte result = 0;\n\n byte[] item = m_map.get(type);\n if (item != null)\n {\n result = item[0];\n }\n\n return (result);\n }"
] |
Send a track metadata update announcement to all registered listeners. | [
"private void deliverTrackMetadataUpdate(int player, TrackMetadata metadata) {\n if (!getTrackMetadataListeners().isEmpty()) {\n final TrackMetadataUpdate update = new TrackMetadataUpdate(player, metadata);\n for (final TrackMetadataListener listener : getTrackMetadataListeners()) {\n try {\n listener.metadataChanged(update);\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering track metadata update to listener\", t);\n }\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 }",
"public static final void parseExtendedAttribute(ProjectFile file, FieldContainer mpx, String value, FieldType mpxFieldID, TimeUnit durationFormat)\n {\n if (mpxFieldID != null)\n {\n switch (mpxFieldID.getDataType())\n {\n case STRING:\n {\n mpx.set(mpxFieldID, value);\n break;\n }\n\n case DATE:\n {\n mpx.set(mpxFieldID, parseExtendedAttributeDate(value));\n break;\n }\n\n case CURRENCY:\n {\n mpx.set(mpxFieldID, parseExtendedAttributeCurrency(value));\n break;\n }\n\n case BOOLEAN:\n {\n mpx.set(mpxFieldID, parseExtendedAttributeBoolean(value));\n break;\n }\n\n case NUMERIC:\n {\n mpx.set(mpxFieldID, parseExtendedAttributeNumber(value));\n break;\n }\n\n case DURATION:\n {\n mpx.set(mpxFieldID, parseDuration(file, durationFormat, value));\n break;\n }\n\n default:\n {\n break;\n }\n }\n }\n }",
"private void processGeneratedProperties(\n\t\t\tSerializable id,\n\t\t\tObject entity,\n\t\t\tObject[] state,\n\t\t\tSharedSessionContractImplementor session,\n\t\t\tGenerationTiming matchTiming) {\n\n\t\tTuple tuple = getFreshTuple( EntityKeyBuilder.fromPersister( this, id, session ), session );\n\t\tsaveSharedTuple( entity, tuple, session );\n\n\t\tif ( tuple == null || tuple.getSnapshot().isEmpty() ) {\n\t\t\tthrow log.couldNotRetrieveEntityForRetrievalOfGeneratedProperties( getEntityName(), id );\n\t\t}\n\n\t\tint propertyIndex = -1;\n\t\tfor ( NonIdentifierAttribute attribute : getEntityMetamodel().getProperties() ) {\n\t\t\tpropertyIndex++;\n\t\t\tfinal ValueGeneration valueGeneration = attribute.getValueGenerationStrategy();\n\t\t\tif ( isReadRequired( valueGeneration, matchTiming ) ) {\n\t\t\t\tObject hydratedState = gridPropertyTypes[propertyIndex].hydrate( tuple, getPropertyAliases( \"\", propertyIndex ), session, entity );\n\t\t\t\tstate[propertyIndex] = gridPropertyTypes[propertyIndex].resolve( hydratedState, session, entity );\n\t\t\t\tsetPropertyValue( entity, propertyIndex, state[propertyIndex] );\n\t\t\t}\n\t\t}\n\t}",
"public static int cudnnSoftmaxBackward(\n cudnnHandle handle, \n int algo, \n int mode, \n Pointer alpha, \n cudnnTensorDescriptor yDesc, \n Pointer y, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n Pointer beta, \n cudnnTensorDescriptor dxDesc, \n Pointer dx)\n {\n return checkResult(cudnnSoftmaxBackwardNative(handle, algo, mode, alpha, yDesc, y, dyDesc, dy, beta, dxDesc, dx));\n }",
"private void cleanupLogs() throws IOException {\n logger.trace(\"Beginning log cleanup...\");\n int total = 0;\n Iterator<Log> iter = getLogIterator();\n long startMs = System.currentTimeMillis();\n while (iter.hasNext()) {\n Log log = iter.next();\n total += cleanupExpiredSegments(log) + cleanupSegmentsToMaintainSize(log);\n }\n if (total > 0) {\n logger.warn(\"Log cleanup completed. \" + total + \" files deleted in \" + (System.currentTimeMillis() - startMs) / 1000 + \" seconds\");\n } else {\n logger.trace(\"Log cleanup completed. \" + total + \" files deleted in \" + (System.currentTimeMillis() - startMs) / 1000 + \" seconds\");\n }\n }",
"public static boolean isPackageOrClassName(String s) {\n if (S.blank(s)) {\n return false;\n }\n S.List parts = S.fastSplit(s, \".\");\n if (parts.size() < 2) {\n return false;\n }\n for (String part: parts) {\n if (!Character.isJavaIdentifierStart(part.charAt(0))) {\n return false;\n }\n for (int i = 1, len = part.length(); i < len; ++i) {\n if (!Character.isJavaIdentifierPart(part.charAt(i))) {\n return false;\n }\n }\n }\n return true;\n }",
"public void loadAnimation(GVRAndroidResource animResource, String boneMap)\n {\n String filePath = animResource.getResourcePath();\n GVRContext ctx = mAvatarRoot.getGVRContext();\n GVRResourceVolume volume = new GVRResourceVolume(ctx, animResource);\n\n if (filePath.endsWith(\".bvh\"))\n {\n GVRAnimator animator = new GVRAnimator(ctx);\n animator.setName(filePath);\n try\n {\n BVHImporter importer = new BVHImporter(ctx);\n GVRSkeletonAnimation skelAnim;\n\n if (boneMap != null)\n {\n GVRSkeleton skel = importer.importSkeleton(animResource);\n skelAnim = importer.readMotion(skel);\n animator.addAnimation(skelAnim);\n\n GVRPoseMapper retargeter = new GVRPoseMapper(mSkeleton, skel, skelAnim.getDuration());\n retargeter.setBoneMap(boneMap);\n animator.addAnimation(retargeter);\n }\n else\n {\n skelAnim = importer.importAnimation(animResource, mSkeleton);\n animator.addAnimation(skelAnim);\n }\n addAnimation(animator);\n ctx.getEventManager().sendEvent(this,\n IAvatarEvents.class,\n \"onAnimationLoaded\",\n GVRAvatar.this,\n animator,\n filePath,\n null);\n }\n catch (IOException ex)\n {\n ctx.getEventManager().sendEvent(this,\n IAvatarEvents.class,\n \"onAnimationLoaded\",\n GVRAvatar.this,\n null,\n filePath,\n ex.getMessage());\n }\n }\n else\n {\n EnumSet<GVRImportSettings> settings = GVRImportSettings.getRecommendedSettingsWith(EnumSet.of(GVRImportSettings.OPTIMIZE_GRAPH, GVRImportSettings.NO_TEXTURING));\n\n GVRSceneObject animRoot = new GVRSceneObject(ctx);\n ctx.getAssetLoader().loadModel(volume, animRoot, settings, false, mLoadAnimHandler);\n }\n }",
"@Override\n public EnvironmentConfig setSetting(@NotNull final String key, @NotNull final Object value) {\n return (EnvironmentConfig) super.setSetting(key, value);\n }",
"public IndirectionHandler createIndirectionHandler(PBKey brokerKey, Identity id)\r\n {\r\n Object args[] = {brokerKey, id};\r\n\r\n try\r\n {\r\n return (IndirectionHandler) getIndirectionHandlerConstructor().newInstance(args);\r\n }\r\n catch(InvocationTargetException ex)\r\n {\r\n throw new PersistenceBrokerException(\"Exception while creating a new indirection handler instance\", ex);\r\n }\r\n catch(InstantiationException ex)\r\n {\r\n throw new PersistenceBrokerException(\"Exception while creating a new indirection handler instance\", ex);\r\n }\r\n catch(IllegalAccessException ex)\r\n {\r\n throw new PersistenceBrokerException(\"Exception while creating a new indirection handler instance\", ex);\r\n }\r\n }"
] |
This method allows the caller to determine if a given date is a
working day. This method takes account of calendar exceptions.
@param date Date to be tested
@return boolean value | [
"public boolean isWorkingDate(Date date)\n {\n Calendar cal = DateHelper.popCalendar(date);\n Day day = Day.getInstance(cal.get(Calendar.DAY_OF_WEEK));\n DateHelper.pushCalendar(cal);\n return isWorkingDate(date, day);\n }"
] | [
"public void setRefreshing(boolean refreshing) {\n if (refreshing && mRefreshing != refreshing) {\n // scale and show\n mRefreshing = refreshing;\n int endTarget = 0;\n if (!mUsingCustomStart) {\n switch (mDirection) {\n case BOTTOM:\n endTarget = getMeasuredHeight() - (int) (mSpinnerFinalOffset);\n break;\n case TOP:\n default:\n endTarget = (int) (mSpinnerFinalOffset - Math.abs(mOriginalOffsetTop));\n break;\n }\n } else {\n endTarget = (int) mSpinnerFinalOffset;\n }\n setTargetOffsetTopAndBottom(endTarget - mCurrentTargetOffsetTop,\n true /* requires update */);\n mNotify = false;\n startScaleUpAnimation(mRefreshListener);\n } else {\n setRefreshing(refreshing, false /* notify */);\n }\n }",
"private void logTimeTakenByRuleProvider(GraphContext graphContext, Context context, int ruleIndex, int timeTaken)\n {\n AbstractRuleProvider ruleProvider = (AbstractRuleProvider) context.get(RuleMetadataType.RULE_PROVIDER);\n if (ruleProvider == null)\n return;\n\n if (!timeTakenByProvider.containsKey(ruleProvider))\n {\n RuleProviderExecutionStatisticsModel model = new RuleProviderExecutionStatisticsService(graphContext)\n .create();\n model.setRuleIndex(ruleIndex);\n model.setRuleProviderID(ruleProvider.getMetadata().getID());\n model.setTimeTaken(timeTaken);\n\n timeTakenByProvider.put(ruleProvider, model.getElement().id());\n }\n else\n {\n RuleProviderExecutionStatisticsService service = new RuleProviderExecutionStatisticsService(graphContext);\n RuleProviderExecutionStatisticsModel model = service.getById(timeTakenByProvider.get(ruleProvider));\n int prevTimeTaken = model.getTimeTaken();\n model.setTimeTaken(prevTimeTaken + timeTaken);\n }\n logTimeTakenByPhase(graphContext, ruleProvider.getMetadata().getPhase(), timeTaken);\n }",
"private Properties parseXML(Document doc, String sectionName) {\n\t\tint found = -1;\n\t\tProperties results = new Properties();\n\t\tNodeList config = null;\n\t\tif (sectionName == null){\n\t\t\tconfig = doc.getElementsByTagName(\"default-config\");\n\t\t\tfound = 0;\n\t\t} else {\n\t\t\tconfig = doc.getElementsByTagName(\"named-config\");\n\t\t\tif(config != null && config.getLength() > 0) {\n\t\t\t\tfor (int i = 0; i < config.getLength(); i++) {\n\t\t\t\t\tNode node = config.item(i);\n\t\t\t\t\tif(node.getNodeType() == Node.ELEMENT_NODE ){\n\t\t\t\t\t\tNamedNodeMap attributes = node.getAttributes();\n\t\t\t\t\t\tif (attributes != null && attributes.getLength() > 0){\n\t\t\t\t\t\t\tNode name = attributes.getNamedItem(\"name\");\n\t\t\t\t\t\t\tif (name.getNodeValue().equalsIgnoreCase(sectionName)){\n\t\t\t\t\t\t\t\tfound = i;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (found == -1){\n\t\t\t\tconfig = null;\n\t\t\t\tlogger.warn(\"Did not find \"+sectionName+\" section in config file. Reverting to defaults.\");\n\t\t\t}\n\t\t}\n\n\t\tif(config != null && config.getLength() > 0) {\n\t\t\tNode node = config.item(found);\n\t\t\tif(node.getNodeType() == Node.ELEMENT_NODE){\n\t\t\t\tElement elementEntry = (Element)node;\n\t\t\t\tNodeList childNodeList = elementEntry.getChildNodes();\n\t\t\t\tfor (int j = 0; j < childNodeList.getLength(); j++) {\n\t\t\t\t\tNode node_j = childNodeList.item(j);\n\t\t\t\t\tif (node_j.getNodeType() == Node.ELEMENT_NODE) {\n\t\t\t\t\t\tElement piece = (Element) node_j;\n\t\t\t\t\t\tNamedNodeMap attributes = piece.getAttributes();\n\t\t\t\t\t\tif (attributes != null && attributes.getLength() > 0){\n\t\t\t\t\t\t\tresults.put(attributes.item(0).getNodeValue(), piece.getTextContent());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn results;\n\t}",
"final public void addPosition(int position) {\n if (tokenPosition == null) {\n tokenPosition = new MtasPosition(position);\n } else {\n tokenPosition.add(position);\n }\n }",
"protected ValueContainer[] getNonKeyValues(PersistenceBroker broker, ClassDescriptor cld, Object obj) throws PersistenceBrokerException\r\n {\r\n return broker.serviceBrokerHelper().getNonKeyRwValues(cld, obj);\r\n }",
"public static String getFlowContext() {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return null;\n }\n\n return instance.flowContext;\n }",
"protected static <T, A> ManagementRequestHandler<T, A> getFallbackHandler(final ManagementRequestHeader header) {\n return new ManagementRequestHandler<T, A>() {\n @Override\n public void handleRequest(final DataInput input, ActiveOperation.ResultHandler<T> resultHandler, ManagementRequestContext<A> context) throws IOException {\n final Exception error = ProtocolLogger.ROOT_LOGGER.noSuchResponseHandler(Integer.toHexString(header.getRequestId()));\n if(resultHandler.failed(error)) {\n safeWriteErrorResponse(context.getChannel(), context.getRequestHeader(), error);\n }\n }\n };\n }",
"public ParallelTaskBuilder setHttpPollerProcessor(\n HttpPollerProcessor httpPollerProcessor) {\n this.httpMeta.setHttpPollerProcessor(httpPollerProcessor);\n this.httpMeta.setPollable(true);\n return this;\n }",
"private static JSONObject parseStencilSet(StencilSet stencilSet) throws JSONException {\n if (stencilSet != null) {\n JSONObject stencilSetObject = new JSONObject();\n\n stencilSetObject.put(\"url\",\n stencilSet.getUrl().toString());\n stencilSetObject.put(\"namespace\",\n stencilSet.getNamespace().toString());\n\n return stencilSetObject;\n }\n\n return new JSONObject();\n }"
] |
Makes an ancestor filter. | [
"public static Filter.Builder makeAncestorFilter(Key ancestor) {\n return makeFilter(\n DatastoreHelper.KEY_PROPERTY_NAME, PropertyFilter.Operator.HAS_ANCESTOR,\n makeValue(ancestor));\n }"
] | [
"public static <K, V> HashMap<K, V> newEmptyHashMap(Iterable<?> iterable) {\n if(iterable instanceof Collection<?>)\n return Maps.newHashMapWithExpectedSize(((Collection<?>) iterable).size());\n return Maps.newHashMap();\n }",
"public synchronized void init() {\n channelFactory = new NioClientSocketChannelFactory(\n Executors.newCachedThreadPool(),\n Executors.newCachedThreadPool());\n\n datagramChannelFactory = new NioDatagramChannelFactory(\n Executors.newCachedThreadPool());\n\n timer = new HashedWheelTimer();\n }",
"@Override\n public void solve(DMatrixRMaj B, DMatrixRMaj X) {\n blockB.reshape(B.numRows,B.numCols,false);\n MatrixOps_DDRB.convert(B,blockB);\n\n // since overwrite B is true X does not need to be passed in\n alg.solve(blockB,null);\n\n MatrixOps_DDRB.convert(blockB,X);\n }",
"public static base_responses unset(nitro_service client, String ipaddress[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (ipaddress != null && ipaddress.length > 0) {\n\t\t\tnsrpcnode unsetresources[] = new nsrpcnode[ipaddress.length];\n\t\t\tfor (int i=0;i<ipaddress.length;i++){\n\t\t\t\tunsetresources[i] = new nsrpcnode();\n\t\t\t\tunsetresources[i].ipaddress = ipaddress[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}",
"public static int randomIntBetween(int min, int max) {\n Random rand = new Random();\n return rand.nextInt((max - min) + 1) + min;\n }",
"public static int timezoneOffset(H.Session session) {\n String s = null != session ? session.get(SESSION_KEY) : null;\n return S.notBlank(s) ? Integer.parseInt(s) : serverTimezoneOffset();\n }",
"public CustomHeadersInterceptor addHeaderMultimap(Map<String, List<String>> headers) {\n this.headers.putAll(headers);\n return this;\n }",
"private boolean isRedeployAfterRemoval(ModelNode operation) {\n return operation.hasDefined(DEPLOYMENT_OVERLAY_LINK_REMOVAL) &&\n operation.get(DEPLOYMENT_OVERLAY_LINK_REMOVAL).asBoolean();\n }",
"public static Element getChild(Element element, String name) {\r\n return (Element) element.getElementsByTagName(name).item(0);\r\n }"
] |
Validates the inputed color value.
@param colorvalue the value of the color
@return true if the inputed color value is valid | [
"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 static void checkPreconditions(final String regex, final String replacement) {\n\t\tif( regex == null ) {\n\t\t\tthrow new NullPointerException(\"regex should not be null\");\n\t\t} else if( regex.length() == 0 ) {\n\t\t\tthrow new IllegalArgumentException(\"regex should not be empty\");\n\t\t}\n\t\t\n\t\tif( replacement == null ) {\n\t\t\tthrow new NullPointerException(\"replacement should not be null\");\n\t\t}\n\t}",
"public static <T> void filterListToMap(final Map<String, T> destinationMap, final String[] nameMapping,\n\t\tfinal List<? extends T> sourceList) {\n\t\tif( destinationMap == null ) {\n\t\t\tthrow new NullPointerException(\"destinationMap should not be null\");\n\t\t} else if( nameMapping == null ) {\n\t\t\tthrow new NullPointerException(\"nameMapping should not be null\");\n\t\t} else if( sourceList == null ) {\n\t\t\tthrow new NullPointerException(\"sourceList should not be null\");\n\t\t} else if( nameMapping.length != sourceList.size() ) {\n\t\t\tthrow new SuperCsvException(\n\t\t\t\tString\n\t\t\t\t\t.format(\n\t\t\t\t\t\t\"the nameMapping array and the sourceList should be the same size (nameMapping length = %d, sourceList size = %d)\",\n\t\t\t\t\t\tnameMapping.length, sourceList.size()));\n\t\t}\n\t\t\n\t\tdestinationMap.clear();\n\t\t\n\t\tfor( int i = 0; i < nameMapping.length; i++ ) {\n\t\t\tfinal String key = nameMapping[i];\n\t\t\t\n\t\t\tif( key == null ) {\n\t\t\t\tcontinue; // null's in the name mapping means skip column\n\t\t\t}\n\t\t\t\n\t\t\t// no duplicates allowed\n\t\t\tif( destinationMap.containsKey(key) ) {\n\t\t\t\tthrow new SuperCsvException(String.format(\"duplicate nameMapping '%s' at index %d\", key, i));\n\t\t\t}\n\t\t\t\n\t\t\tdestinationMap.put(key, sourceList.get(i));\n\t\t}\n\t}",
"@Override\n public void onRotationSensor(long timeStamp, float rotationW, float rotationX, float rotationY, float rotationZ,\n float gyroX, float gyroY, float gyroZ) {\n GVRCameraRig cameraRig = null;\n if (mMainScene != null) {\n cameraRig = mMainScene.getMainCameraRig();\n }\n\n if (cameraRig != null) {\n cameraRig.setRotationSensorData(timeStamp, rotationW, rotationX, rotationY, rotationZ, gyroX, gyroY, gyroZ);\n updateSensoredScene();\n }\n }",
"public static final BigDecimal printRate(Rate rate)\n {\n BigDecimal result = null;\n if (rate != null && rate.getAmount() != 0)\n {\n result = new BigDecimal(rate.getAmount());\n }\n return result;\n }",
"protected void generateMopCalls(LinkedList<MethodNode> mopCalls, boolean useThis) {\n for (MethodNode method : mopCalls) {\n String name = getMopMethodName(method, useThis);\n Parameter[] parameters = method.getParameters();\n String methodDescriptor = BytecodeHelper.getMethodDescriptor(method.getReturnType(), method.getParameters());\n MethodVisitor mv = controller.getClassVisitor().visitMethod(ACC_PUBLIC | ACC_SYNTHETIC, name, methodDescriptor, null, null);\n controller.setMethodVisitor(mv);\n mv.visitVarInsn(ALOAD, 0);\n int newRegister = 1;\n OperandStack operandStack = controller.getOperandStack();\n for (Parameter parameter : parameters) {\n ClassNode type = parameter.getType();\n operandStack.load(parameter.getType(), newRegister);\n // increment to next register, double/long are using two places\n newRegister++;\n if (type == ClassHelper.double_TYPE || type == ClassHelper.long_TYPE) newRegister++;\n }\n operandStack.remove(parameters.length);\n ClassNode declaringClass = method.getDeclaringClass();\n // JDK 8 support for default methods in interfaces\n // this should probably be strenghtened when we support the A.super.foo() syntax\n int opcode = declaringClass.isInterface()?INVOKEINTERFACE:INVOKESPECIAL;\n mv.visitMethodInsn(opcode, BytecodeHelper.getClassInternalName(declaringClass), method.getName(), methodDescriptor, opcode == INVOKEINTERFACE);\n BytecodeHelper.doReturn(mv, method.getReturnType());\n mv.visitMaxs(0, 0);\n mv.visitEnd();\n controller.getClassNode().addMethod(name, ACC_PUBLIC | ACC_SYNTHETIC, method.getReturnType(), parameters, null, null);\n }\n }",
"void countNonZeroInV( int []parent ) {\n int []w = gwork.data;\n findMinElementIndexInRows(leftmost);\n createRowElementLinkedLists(leftmost,w);\n countNonZeroUsingLinkedList(parent,w);\n }",
"private void deleteUnusedCaseSteps( ReportModel model ) {\n\n for( ScenarioModel scenarioModel : model.getScenarios() ) {\n if( scenarioModel.isCasesAsTable() && !hasAttachment( scenarioModel ) ) {\n List<ScenarioCaseModel> cases = scenarioModel.getScenarioCases();\n for( int i = 1; i < cases.size(); i++ ) {\n ScenarioCaseModel caseModel = cases.get( i );\n caseModel.setSteps( Collections.<StepModel>emptyList() );\n }\n }\n }\n }",
"void handleAddKey() {\n\n String key = m_addKeyInput.getValue();\n if (m_listener.handleAddKey(key)) {\n Notification.show(\n key.isEmpty()\n ? m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_EMPTY_KEY_SUCCESSFULLY_ADDED_0)\n : m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_SUCCESSFULLY_ADDED_1, key));\n } else {\n CmsMessageBundleEditorTypes.showWarning(\n m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_ALREADEY_EXISTS_CAPTION_0),\n m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_ALREADEY_EXISTS_DESCRIPTION_1, key));\n\n }\n m_addKeyInput.focus();\n m_addKeyInput.selectAll();\n }",
"@Override\n public PaxDate date(int prolepticYear, int month, int dayOfMonth) {\n return PaxDate.of(prolepticYear, month, dayOfMonth);\n }"
] |
This should be called from a subclass constructor, if offset or length
are unknown at a time when SubIIMInputStream constructor is called. This
method shouldn't be called more than once.
@param offset
byte offset
@param length
byte length
@throws IOException
if underlying stream can't be read | [
"protected void setOffsetAndLength(long offset, int length) throws IOException {\r\n\t\tthis.offset = offset;\r\n\t\tthis.length = length;\r\n\t\tthis.position = 0;\r\n\r\n\t\tif (subStream.position() != offset) {\r\n\t\t\tsubStream.seek(offset);\r\n\t\t}\r\n\t}"
] | [
"private void readPredecessors(net.sf.mpxj.planner.schema.Task plannerTask)\n {\n Task mpxjTask = m_projectFile.getTaskByUniqueID(getInteger(plannerTask.getId()));\n\n Predecessors predecessors = plannerTask.getPredecessors();\n if (predecessors != null)\n {\n List<Predecessor> predecessorList = predecessors.getPredecessor();\n for (Predecessor predecessor : predecessorList)\n {\n Integer predecessorID = getInteger(predecessor.getPredecessorId());\n Task predecessorTask = m_projectFile.getTaskByUniqueID(predecessorID);\n if (predecessorTask != null)\n {\n Duration lag = getDuration(predecessor.getLag());\n if (lag == null)\n {\n lag = Duration.getInstance(0, TimeUnit.HOURS);\n }\n Relation relation = mpxjTask.addPredecessor(predecessorTask, RELATIONSHIP_TYPES.get(predecessor.getType()), lag);\n m_eventManager.fireRelationReadEvent(relation);\n }\n }\n }\n\n //\n // Process child tasks\n //\n List<net.sf.mpxj.planner.schema.Task> childTasks = plannerTask.getTask();\n for (net.sf.mpxj.planner.schema.Task childTask : childTasks)\n {\n readPredecessors(childTask);\n }\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 AT_Context setFrameTopBottomMargin(int frameTop, int frameBottom){\r\n\t\tif(frameTop>-1 && frameBottom>-1){\r\n\t\t\tthis.frameTopMargin = frameTop;\r\n\t\t\tthis.frameBottomMargin = frameBottom;\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public static sslcertkey get(nitro_service service, String certkey) throws Exception{\n\t\tsslcertkey obj = new sslcertkey();\n\t\tobj.set_certkey(certkey);\n\t\tsslcertkey response = (sslcertkey) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public void useXopAttachmentServiceWithProxy() throws Exception {\n\n final String serviceURI = \"http://localhost:\" + port + \"/services/attachments\";\n \n XopAttachmentService proxy = JAXRSClientFactory.create(serviceURI, \n XopAttachmentService.class);\n \n XopBean xop = createXopBean();\n \n System.out.println();\n System.out.println(\"Posting a XOP attachment with a proxy\");\n \n XopBean xopResponse = proxy.echoXopAttachment(xop);\n \n verifyXopResponse(xop, xopResponse);\n }",
"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 }",
"private void onScrollImpl(final Vector3Axis offset, final LayoutScroller.OnScrollListener listener) {\n if (!isScrolling()) {\n mScroller = new ScrollingProcessor(offset, listener);\n mScroller.scroll();\n }\n }",
"public List<String> getCorporateGroupIds(final String organizationId) {\n final DbOrganization dbOrganization = getOrganization(organizationId);\n return dbOrganization.getCorporateGroupIdPrefixes();\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 }"
] |
Use this API to rename a nsacl6 resource. | [
"public static base_response rename(nitro_service client, nsacl6 resource, String new_acl6name) throws Exception {\n\t\tnsacl6 renameresource = new nsacl6();\n\t\trenameresource.acl6name = resource.acl6name;\n\t\treturn renameresource.rename_resource(client,new_acl6name);\n\t}"
] | [
"public static void setViewBackground(View v, Drawable d) {\n if (Build.VERSION.SDK_INT >= 16) {\n v.setBackground(d);\n } else {\n v.setBackgroundDrawable(d);\n }\n }",
"public Map<DeckReference, TrackMetadata> getLoadedTracks() {\n ensureRunning();\n // Make a copy so callers get an immutable snapshot of the current state.\n return Collections.unmodifiableMap(new HashMap<DeckReference, TrackMetadata>(hotCache));\n }",
"public static int toIntWithDefault(String value, int defaultValue) {\n\n int result = defaultValue;\n try {\n result = Integer.parseInt(value);\n } catch (@SuppressWarnings(\"unused\") Exception e) {\n // Do nothing, return default.\n }\n return result;\n }",
"public static String format(final String code, final Properties options, final LineEnding lineEnding) {\n\t\tCheck.notEmpty(code, \"code\");\n\t\tCheck.notEmpty(options, \"options\");\n\t\tCheck.notNull(lineEnding, \"lineEnding\");\n\n\t\tfinal CodeFormatter formatter = ToolFactory.createCodeFormatter(options);\n\t\tfinal String lineSeparator = LineEnding.find(lineEnding, code);\n\t\tTextEdit te = null;\n\t\ttry {\n\t\t\tte = formatter.format(CodeFormatter.K_COMPILATION_UNIT, code, 0, code.length(), 0, lineSeparator);\n\t\t} catch (final Exception formatFailed) {\n\t\t\tLOG.warn(\"Formatting failed\", formatFailed);\n\t\t}\n\n\t\tString formattedCode = code;\n\t\tif (te == null) {\n\t\t\tLOG.info(\"Code cannot be formatted. Possible cause is unmatched source/target/compliance version.\");\n\t\t} else {\n\n\t\t\tfinal IDocument doc = new Document(code);\n\t\t\ttry {\n\t\t\t\tte.apply(doc);\n\t\t\t} catch (final Exception e) {\n\t\t\t\tLOG.warn(e.getLocalizedMessage(), e);\n\t\t\t}\n\t\t\tformattedCode = doc.get();\n\t\t}\n\t\treturn formattedCode;\n\t}",
"public Integer getBlockMaskPrefixLength(boolean network) {\n\t\tInteger prefixLen;\n\t\tif(network) {\n\t\t\tif(hasNoPrefixCache() || (prefixLen = prefixCache.networkMaskPrefixLen) == null) {\n\t\t\t\tprefixLen = setNetworkMaskPrefix(checkForPrefixMask(network));\n\t\t\t}\n\t\t} else {\n\t\t\tif(hasNoPrefixCache() || (prefixLen = prefixCache.hostMaskPrefixLen) == null) {\n\t\t\t\tprefixLen = setHostMaskPrefix(checkForPrefixMask(network));\n\t\t\t}\n\t\t}\n\t\tif(prefixLen < 0) {\n\t\t\treturn null;\n\t\t}\n\t\treturn prefixLen;\n\t}",
"@SuppressWarnings(\"WeakerAccess\")\n public Map<DeckReference, WaveformPreview> getLoadedPreviews() {\n ensureRunning();\n // Make a copy so callers get an immutable snapshot of the current state.\n return Collections.unmodifiableMap(new HashMap<DeckReference, WaveformPreview>(previewHotCache));\n }",
"private OJBIterator getReportQueryIteratorFromQuery(Query query, ClassDescriptor cld) throws PersistenceBrokerException\n {\n RsIteratorFactory factory = ReportRsIteratorFactoryImpl.getInstance();\n OJBIterator result = getRsIteratorFromQuery(query, cld, factory);\n\n if (query.usePaging())\n {\n result = new PagingIterator(result, query.getStartAtIndex(), query.getEndAtIndex());\n }\n\n return result;\n }",
"private void init() {\n logger.info(\"metadata init().\");\n\n writeLock.lock();\n try {\n // Required keys\n initCache(CLUSTER_KEY);\n\n // If stores definition storage engine is not null, initialize metadata\n // Add the mapping from key to the storage engine used\n if(this.storeDefinitionsStorageEngine != null) {\n initStoreDefinitions(null);\n } else {\n initCache(STORES_KEY);\n }\n\n // Initialize system store in the metadata cache\n initSystemCache();\n initSystemRoutingStrategies(getCluster());\n\n // Initialize with default if not present\n initCache(SLOP_STREAMING_ENABLED_KEY, true);\n initCache(PARTITION_STREAMING_ENABLED_KEY, true);\n initCache(READONLY_FETCH_ENABLED_KEY, true);\n initCache(QUOTA_ENFORCEMENT_ENABLED_KEY, true);\n initCache(REBALANCING_STEAL_INFO, new RebalancerState(new ArrayList<RebalanceTaskInfo>()));\n initCache(SERVER_STATE_KEY, VoldemortState.NORMAL_SERVER.toString());\n initCache(REBALANCING_SOURCE_CLUSTER_XML, null);\n initCache(REBALANCING_SOURCE_STORES_XML, null);\n\n\n } finally {\n writeLock.unlock();\n }\n }",
"public void writeTo(DataOutput outstream) throws Exception {\n S3Util.writeString(host, outstream);\n outstream.writeInt(port);\n S3Util.writeString(protocol, outstream);\n }"
] |
Retrieves the project finish date. If an explicit finish date has not been
set, this method calculates the finish date by looking for
the latest task finish date.
@return Finish Date | [
"public Date getFinishDate()\n {\n Date result = (Date) getCachedValue(ProjectField.FINISH_DATE);\n if (result == null)\n {\n result = getParentFile().getFinishDate();\n }\n return (result);\n }"
] | [
"private void clearQueues(final Context context) {\n synchronized (eventLock) {\n\n DBAdapter adapter = loadDBAdapter(context);\n DBAdapter.Table tableName = DBAdapter.Table.EVENTS;\n\n adapter.removeEvents(tableName);\n tableName = DBAdapter.Table.PROFILE_EVENTS;\n adapter.removeEvents(tableName);\n\n clearUserContext(context);\n }\n }",
"private void readCalendars()\n {\n Table cal = m_tables.get(\"CAL\");\n for (MapRow row : cal)\n {\n ProjectCalendar calendar = m_projectFile.addCalendar();\n m_calendarMap.put(row.getInteger(\"CALENDAR_ID\"), calendar);\n Integer[] days =\n {\n row.getInteger(\"SUNDAY_HOURS\"),\n row.getInteger(\"MONDAY_HOURS\"),\n row.getInteger(\"TUESDAY_HOURS\"),\n row.getInteger(\"WEDNESDAY_HOURS\"),\n row.getInteger(\"THURSDAY_HOURS\"),\n row.getInteger(\"FRIDAY_HOURS\"),\n row.getInteger(\"SATURDAY_HOURS\")\n };\n\n calendar.setName(row.getString(\"NAME\"));\n readHours(calendar, Day.SUNDAY, days[0]);\n readHours(calendar, Day.MONDAY, days[1]);\n readHours(calendar, Day.TUESDAY, days[2]);\n readHours(calendar, Day.WEDNESDAY, days[3]);\n readHours(calendar, Day.THURSDAY, days[4]);\n readHours(calendar, Day.FRIDAY, days[5]);\n readHours(calendar, Day.SATURDAY, days[6]);\n\n int workingDaysPerWeek = 0;\n for (Day day : Day.values())\n {\n if (calendar.isWorkingDay(day))\n {\n ++workingDaysPerWeek;\n }\n }\n\n Integer workingHours = null;\n for (int index = 0; index < 7; index++)\n {\n if (days[index].intValue() != 0)\n {\n workingHours = days[index];\n break;\n }\n }\n\n if (workingHours != null)\n {\n int workingHoursPerDay = countHours(workingHours);\n int minutesPerDay = workingHoursPerDay * 60;\n int minutesPerWeek = minutesPerDay * workingDaysPerWeek;\n int minutesPerMonth = 4 * minutesPerWeek;\n int minutesPerYear = 52 * minutesPerWeek;\n\n calendar.setMinutesPerDay(Integer.valueOf(minutesPerDay));\n calendar.setMinutesPerWeek(Integer.valueOf(minutesPerWeek));\n calendar.setMinutesPerMonth(Integer.valueOf(minutesPerMonth));\n calendar.setMinutesPerYear(Integer.valueOf(minutesPerYear));\n }\n }\n }",
"public Feature toDto(InternalFeature feature, int featureIncludes) throws GeomajasException {\n\t\tif (feature == null) {\n\t\t\treturn null;\n\t\t}\n\t\tFeature dto = new Feature(feature.getId());\n\t\tif ((featureIncludes & VectorLayerService.FEATURE_INCLUDE_ATTRIBUTES) != 0 && null != feature.getAttributes()) {\n\t\t\t// need to assure lazy attributes are converted to non-lazy attributes\n\t\t\tMap<String, Attribute> attributes = new HashMap<String, Attribute>();\n\t\t\tfor (Map.Entry<String, Attribute> entry : feature.getAttributes().entrySet()) {\n\t\t\t\tAttribute value = entry.getValue();\n\t\t\t\tif (value instanceof LazyAttribute) {\n\t\t\t\t\tvalue = ((LazyAttribute) value).instantiate();\n\t\t\t\t}\n\t\t\t\tattributes.put(entry.getKey(), value);\n\t\t\t}\n\t\t\tdto.setAttributes(attributes);\n\t\t}\n\t\tif ((featureIncludes & VectorLayerService.FEATURE_INCLUDE_LABEL) != 0) {\n\t\t\tdto.setLabel(feature.getLabel());\n\t\t}\n\t\tif ((featureIncludes & VectorLayerService.FEATURE_INCLUDE_GEOMETRY) != 0) {\n\t\t\tdto.setGeometry(toDto(feature.getGeometry()));\n\t\t}\n\t\tif ((featureIncludes & VectorLayerService.FEATURE_INCLUDE_STYLE) != 0 && null != feature.getStyleInfo()) {\n\t\t\tdto.setStyleId(feature.getStyleInfo().getStyleId());\n\t\t}\n\t\tInternalFeatureImpl vFeature = (InternalFeatureImpl) feature;\n\t\tdto.setClipped(vFeature.isClipped());\n\t\tdto.setUpdatable(feature.isEditable());\n\t\tdto.setDeletable(feature.isDeletable());\n\t\treturn dto;\n\t}",
"public synchronized void bindShader(GVRScene scene, boolean isMultiview)\n {\n GVRRenderPass pass = mRenderPassList.get(0);\n GVRShaderId shader = pass.getMaterial().getShaderType();\n GVRShader template = shader.getTemplate(getGVRContext());\n if (template != null)\n {\n template.bindShader(getGVRContext(), this, scene, isMultiview);\n }\n for (int i = 1; i < mRenderPassList.size(); ++i)\n {\n pass = mRenderPassList.get(i);\n shader = pass.getMaterial().getShaderType();\n template = shader.getTemplate(getGVRContext());\n if (template != null)\n {\n template.bindShader(getGVRContext(), pass, scene, isMultiview);\n }\n }\n }",
"@Override\n public void postCrawling(CrawlSession session, ExitStatus exitStatus) {\n LOG.debug(\"postCrawling\");\n StateFlowGraph sfg = session.getStateFlowGraph();\n checkSFG(sfg);\n // TODO: call state abstraction function to get distance matrix and run rscript on it to\n // create clusters\n String[][] clusters = null;\n // generateClusters(session);\n\n result = outModelCache.close(session, exitStatus, clusters);\n\n outputBuilder.write(result, session.getConfig(), clusters);\n StateWriter writer =\n new StateWriter(outputBuilder, sfg, ImmutableMap.copyOf(visitedStates));\n for (State state : result.getStates().values()) {\n try {\n writer.writeHtmlForState(state);\n } catch (Exception Ex) {\n LOG.info(\"couldn't write state :\" + state.getName());\n }\n }\n LOG.info(\"Crawl overview plugin has finished\");\n }",
"private Duration getDuration(TimeUnit units, Double duration)\n {\n Duration result = null;\n if (duration != null)\n {\n double durationValue = duration.doubleValue() * 100.0;\n\n switch (units)\n {\n case MINUTES:\n {\n durationValue *= MINUTES_PER_DAY;\n break;\n }\n\n case HOURS:\n {\n durationValue *= HOURS_PER_DAY;\n break;\n }\n\n case DAYS:\n {\n durationValue *= 3.0;\n break;\n }\n\n case WEEKS:\n {\n durationValue *= 0.6;\n break;\n }\n\n case MONTHS:\n {\n durationValue *= 0.15;\n break;\n }\n\n default:\n {\n throw new IllegalArgumentException(\"Unsupported time units \" + units);\n }\n }\n\n durationValue = Math.round(durationValue) / 100.0;\n\n result = Duration.getInstance(durationValue, units);\n }\n\n return result;\n }",
"private static void addProperties(EndpointReferenceType epr, SLProperties props) {\n MetadataType metadata = WSAEndpointReferenceUtils.getSetMetadata(epr);\n ServiceLocatorPropertiesType jaxbProps = SLPropertiesConverter.toServiceLocatorPropertiesType(props);\n\n JAXBElement<ServiceLocatorPropertiesType>\n slp = SL_OBJECT_FACTORY.createServiceLocatorProperties(jaxbProps);\n metadata.getAny().add(slp);\n }",
"public static base_responses add(nitro_service client, dospolicy resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdospolicy addresources[] = new dospolicy[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dospolicy();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].qdepth = resources[i].qdepth;\n\t\t\t\taddresources[i].cltdetectrate = resources[i].cltdetectrate;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"protected void generateRoutes()\n {\n try {\n\n//\t\t\tOptional<io.sinistral.proteus.annotations.Chain> typeLevelWrapAnnotation = Optional.ofNullable(controllerClass.getAnnotation(io.sinistral.proteus.annotations.Chain.class));\n//\t\t\t\n//\t\t\ttypeLevelWrapAnnotation.ifPresent( a -> {\n//\t\t\t\t \n//\t\t\t\tio.sinistral.proteus.annotations.Chain w = typeLevelWrapAnnotation.get();\n//\n//\t\t\t\tClass<? extends HandlerWrapper> wrapperClasses[] = w.value();\n//\n//\t\t\t\tfor (int i = 0; i < wrapperClasses.length; i++)\n//\t\t\t\t{\n//\t\t\t\t\tClass<? extends HandlerWrapper> wrapperClass = wrapperClasses[i];\n//\n//\t\t\t\t\tString wrapperName = generateFieldName(wrapperClass.getCanonicalName());\n//\n//\t\t\t\t\thandlerWrapperMap.put(wrapperClass, wrapperName);\n//\t\t\t\t}\n//\t\t\t\t\n//\t\t\t});\n//\t\t\t\n//\t\t\tfor(Method m : this.controllerClass.getDeclaredMethods())\n//\t\t\t{\n//\t\t\t\n//\t\t\t\tOptional<io.sinistral.proteus.annotations.Chain> methodLevelWrapAnnotation = Optional.ofNullable(m.getAnnotation(io.sinistral.proteus.annotations.Chain.class));\n//\t\t\t\t\n//\t\t\t\tmethodLevelWrapAnnotation.ifPresent( a -> {\n//\t\t\t\t\t \n//\t\t\t\t\tio.sinistral.proteus.annotations.Chain w = methodLevelWrapAnnotation.get();\n//\t\n//\t\t\t\t\tClass<? extends HandlerWrapper> wrapperClasses[] = w.value();\n//\t\n//\t\t\t\t\tfor (int i = 0; i < wrapperClasses.length; i++)\n//\t\t\t\t\t{\n//\t\t\t\t\t\tClass<? extends HandlerWrapper> wrapperClass = wrapperClasses[i];\n//\t\n//\t\t\t\t\t\tString wrapperName = generateFieldName(wrapperClass.getCanonicalName());\n//\t\n//\t\t\t\t\t\thandlerWrapperMap.put(wrapperClass, wrapperName);\n//\t\t\t\t\t}\n//\t\t\t\t\t\n//\t\t\t\t});\n//\n//\t\t\t}\n//\t\t\t\n//\t\t\tlog.info(\"handlerWrapperMap: \" + handlerWrapperMap);\n\n TypeSpec.Builder typeBuilder = TypeSpec.classBuilder(className).addModifiers(Modifier.PUBLIC)\n .addSuperinterface(ParameterizedTypeName.get(Supplier.class, RoutingHandler.class));\n\n ClassName extractorClass = ClassName.get(\"io.sinistral.proteus.server\", \"Extractors\");\n\n ClassName injectClass = ClassName.get(\"com.google.inject\", \"Inject\");\n\n\n MethodSpec.Builder constructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addAnnotation(injectClass);\n\n String className = this.controllerClass.getSimpleName().toLowerCase() + \"Controller\";\n\n typeBuilder.addField(this.controllerClass, className, Modifier.PROTECTED, Modifier.FINAL);\n\n ClassName wrapperClass = ClassName.get(\"io.undertow.server\", \"HandlerWrapper\");\n ClassName stringClass = ClassName.get(\"java.lang\", \"String\");\n ClassName mapClass = ClassName.get(\"java.util\", \"Map\");\n\n TypeName mapOfWrappers = ParameterizedTypeName.get(mapClass, stringClass, wrapperClass);\n\n TypeName annotatedMapOfWrappers = mapOfWrappers\n .annotated(AnnotationSpec.builder(com.google.inject.name.Named.class).addMember(\"value\", \"$S\", \"registeredHandlerWrappers\").build());\n\n typeBuilder.addField(mapOfWrappers, \"registeredHandlerWrappers\", Modifier.PROTECTED, Modifier.FINAL);\n\n\n constructor.addParameter(this.controllerClass, className);\n constructor.addParameter(annotatedMapOfWrappers, \"registeredHandlerWrappers\");\n\n constructor.addStatement(\"this.$N = $N\", className, className);\n constructor.addStatement(\"this.$N = $N\", \"registeredHandlerWrappers\", \"registeredHandlerWrappers\");\n\n addClassMethodHandlers(typeBuilder, this.controllerClass);\n\n typeBuilder.addMethod(constructor.build());\n\n JavaFile javaFile = JavaFile.builder(packageName, typeBuilder.build()).addStaticImport(extractorClass, \"*\").build();\n\n StringBuilder sb = new StringBuilder();\n\n javaFile.writeTo(sb);\n\n this.sourceString = sb.toString();\n\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n }\n }"
] |
Read exceptions for a calendar.
@param table calendar exception data
@param calendar calendar
@param exceptionID first exception ID | [
"private void addCalendarExceptions(Table table, ProjectCalendar calendar, Integer exceptionID)\n {\n Integer currentExceptionID = exceptionID;\n while (true)\n {\n MapRow row = table.find(currentExceptionID);\n if (row == null)\n {\n break;\n }\n\n Date date = row.getDate(\"DATE\");\n ProjectCalendarException exception = calendar.addCalendarException(date, date);\n if (row.getBoolean(\"WORKING\"))\n {\n exception.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING);\n exception.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON);\n }\n\n currentExceptionID = row.getInteger(\"NEXT_CALENDAR_EXCEPTION_ID\");\n }\n }"
] | [
"private String formatPriority(Priority value)\n {\n String result = null;\n\n if (value != null)\n {\n String[] priorityTypes = LocaleData.getStringArray(m_locale, LocaleData.PRIORITY_TYPES);\n int priority = value.getValue();\n if (priority < Priority.LOWEST)\n {\n priority = Priority.LOWEST;\n }\n else\n {\n if (priority > Priority.DO_NOT_LEVEL)\n {\n priority = Priority.DO_NOT_LEVEL;\n }\n }\n\n priority /= 100;\n\n result = priorityTypes[priority - 1];\n }\n\n return (result);\n }",
"public static URI createRestURI(\n final String matrixId, final int row, final int col,\n final WMTSLayerParam layerParam) throws URISyntaxException {\n String path = layerParam.baseURL;\n if (layerParam.dimensions != null) {\n for (int i = 0; i < layerParam.dimensions.length; i++) {\n String dimension = layerParam.dimensions[i];\n String value = layerParam.dimensionParams.optString(dimension);\n if (value == null) {\n value = layerParam.dimensionParams.getString(dimension.toUpperCase());\n }\n path = path.replace(\"{\" + dimension + \"}\", value);\n }\n }\n path = path.replace(\"{TileMatrixSet}\", layerParam.matrixSet);\n path = path.replace(\"{TileMatrix}\", matrixId);\n path = path.replace(\"{TileRow}\", String.valueOf(row));\n path = path.replace(\"{TileCol}\", String.valueOf(col));\n path = path.replace(\"{style}\", layerParam.style);\n path = path.replace(\"{Layer}\", layerParam.layer);\n\n return new URI(path);\n }",
"public void add(StatementRank rank, Resource subject) {\n\t\tif (this.bestRank == rank) {\n\t\t\tsubjects.add(subject);\n\t\t} else if(bestRank == StatementRank.NORMAL && rank == StatementRank.PREFERRED) {\n\t\t\t//We found a preferred statement\n\t\t\tsubjects.clear();\n\t\t\tbestRank = StatementRank.PREFERRED;\n\t\t\tsubjects.add(subject);\n\t\t}\n\t}",
"protected void mergeHardcodedResultsFrom(Configuration otherConfiguration) {\r\n Map<Dotted, AnalysisResult> resultsMap = hardcodedResults.build().stream()\r\n .collect(Collectors.toMap(r -> r.className, r -> r));\r\n resultsMap.putAll(otherConfiguration.hardcodedResults());\r\n hardcodedResults = ImmutableSet.<AnalysisResult>builder().addAll(resultsMap.values());\r\n }",
"public MtasCQLParserSentenceCondition createFullSentence()\n throws ParseException {\n if (fullCondition == null) {\n if (secondSentencePart == null) {\n if (firstBasicSentence != null) {\n fullCondition = new MtasCQLParserSentenceCondition(firstBasicSentence,\n ignoreClause, maximumIgnoreLength);\n\n } else {\n fullCondition = firstSentence;\n }\n fullCondition.setOccurence(firstMinimumOccurence,\n firstMaximumOccurence);\n if (firstOptional) {\n fullCondition.setOptional(firstOptional);\n }\n return fullCondition;\n } else {\n if (!orOperator) {\n if (firstBasicSentence != null) {\n firstBasicSentence.setOccurence(firstMinimumOccurence,\n firstMaximumOccurence);\n firstBasicSentence.setOptional(firstOptional);\n fullCondition = new MtasCQLParserSentenceCondition(\n firstBasicSentence, ignoreClause, maximumIgnoreLength);\n } else {\n firstSentence.setOccurence(firstMinimumOccurence,\n firstMaximumOccurence);\n firstSentence.setOptional(firstOptional);\n fullCondition = new MtasCQLParserSentenceCondition(firstSentence,\n ignoreClause, maximumIgnoreLength);\n }\n fullCondition.addSentenceToEndLatestSequence(\n secondSentencePart.createFullSentence());\n } else {\n MtasCQLParserSentenceCondition sentence = secondSentencePart\n .createFullSentence();\n if (firstBasicSentence != null) {\n sentence.addSentenceAsFirstOption(\n new MtasCQLParserSentenceCondition(firstBasicSentence,\n ignoreClause, maximumIgnoreLength));\n } else {\n sentence.addSentenceAsFirstOption(firstSentence);\n }\n fullCondition = sentence;\n }\n return fullCondition;\n }\n } else {\n return fullCondition;\n }\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 }",
"private LinkedList<TimephasedWork> readTimephasedAssignment(ProjectCalendar calendar, Project.Assignments.Assignment assignment, int type)\n {\n LinkedList<TimephasedWork> result = new LinkedList<TimephasedWork>();\n\n for (TimephasedDataType item : assignment.getTimephasedData())\n {\n if (NumberHelper.getInt(item.getType()) != type)\n {\n continue;\n }\n\n Date startDate = item.getStart();\n Date finishDate = item.getFinish();\n\n // Exclude ranges which don't have a start and end date.\n // These seem to be generated by Synchro and have a zero duration.\n if (startDate == null && finishDate == null)\n {\n continue;\n }\n\n Duration work = DatatypeConverter.parseDuration(m_projectFile, TimeUnit.MINUTES, item.getValue());\n if (work == null)\n {\n work = Duration.getInstance(0, TimeUnit.MINUTES);\n }\n else\n {\n work = Duration.getInstance(NumberHelper.round(work.getDuration(), 2), TimeUnit.MINUTES);\n }\n\n TimephasedWork tra = new TimephasedWork();\n tra.setStart(startDate);\n tra.setFinish(finishDate);\n tra.setTotalAmount(work);\n\n result.add(tra);\n }\n\n return result;\n }",
"public static RouteInfo of(ActionContext context) {\n H.Method m = context.req().method();\n String path = context.req().url();\n RequestHandler handler = context.handler();\n if (null == handler) {\n handler = UNKNOWN_HANDLER;\n }\n return new RouteInfo(m, path, handler);\n }",
"public static route6[] get(nitro_service service) throws Exception{\n\t\troute6 obj = new route6();\n\t\troute6[] response = (route6[])obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Reads a "message set" argument, and parses into an IdSet.
Currently only supports a single range of values. | [
"public IdRange[] parseIdRange(ImapRequestLineReader request)\n throws ProtocolException {\n CharacterValidator validator = new MessageSetCharValidator();\n String nextWord = consumeWord(request, validator);\n\n int commaPos = nextWord.indexOf(',');\n if (commaPos == -1) {\n return new IdRange[]{IdRange.parseRange(nextWord)};\n }\n\n List<IdRange> rangeList = new ArrayList<>();\n int pos = 0;\n while (commaPos != -1) {\n String range = nextWord.substring(pos, commaPos);\n IdRange set = IdRange.parseRange(range);\n rangeList.add(set);\n\n pos = commaPos + 1;\n commaPos = nextWord.indexOf(',', pos);\n }\n String range = nextWord.substring(pos);\n rangeList.add(IdRange.parseRange(range));\n return rangeList.toArray(new IdRange[rangeList.size()]);\n }"
] | [
"public Task<Void> sendResetPasswordEmail(@NonNull final String email) {\n return dispatcher.dispatchTask(\n new Callable<Void>() {\n @Override\n public Void call() {\n sendResetPasswordEmailInternal(email);\n return null;\n }\n });\n }",
"public int[] sampleBatchWithReplacement() {\n // Sample the indices with replacement.\n int[] batch = new int[batchSize];\n for (int i=0; i<batch.length; i++) {\n batch[i] = Prng.nextInt(numExamples);\n }\n return batch;\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 void afterLoading(CollectionProxyDefaultImpl colProxy)\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"loading a proxied collection a collection: \" + colProxy);\r\n Collection data = colProxy.getData();\r\n for (Iterator iterator = data.iterator(); iterator.hasNext();)\r\n {\r\n Object o = iterator.next();\r\n if(!isOpen())\r\n {\r\n log.error(\"Collection proxy materialization outside of a running tx, obj=\" + o);\r\n try{throw new Exception(\"Collection proxy materialization outside of a running tx, obj=\" + o);}\r\n catch(Exception e)\r\n {e.printStackTrace();}\r\n }\r\n else\r\n {\r\n Identity oid = getBroker().serviceIdentity().buildIdentity(o);\r\n ClassDescriptor cld = getBroker().getClassDescriptor(ProxyHelper.getRealClass(o));\r\n RuntimeObject rt = new RuntimeObject(o, oid, cld, false, ProxyHelper.isProxy(o));\r\n lockAndRegister(rt, Transaction.READ, isImplicitLocking(), getRegistrationList());\r\n }\r\n }\r\n unregisterFromCollectionProxy(colProxy);\r\n }",
"void reset()\n {\n if (!hasStopped)\n {\n throw new IllegalStateException(\"cannot reset a non stopped queue poller\");\n }\n hasStopped = false;\n run = true;\n lastLoop = null;\n loop = new Semaphore(0);\n }",
"public static String getImageIdFromAgent(Launcher launcher, final String imageTag, final String host) throws IOException, InterruptedException {\n return launcher.getChannel().call(new MasterToSlaveCallable<String, IOException>() {\n public String call() throws IOException {\n return DockerUtils.getImageIdFromTag(imageTag, host);\n }\n });\n }",
"private static long asciidump(InputStream is, PrintWriter pw) throws Exception\n {\n byte[] buffer = new byte[BUFFER_SIZE];\n long byteCount = 0;\n\n char c;\n int loop;\n int count;\n StringBuilder sb = new StringBuilder();\n\n while (true)\n {\n count = is.read(buffer);\n if (count == -1)\n {\n break;\n }\n\n byteCount += count;\n\n sb.setLength(0);\n for (loop = 0; loop < count; loop++)\n {\n c = (char) buffer[loop];\n if (c > 200 || c < 27)\n {\n c = ' ';\n }\n\n sb.append(c);\n }\n\n pw.print(sb.toString());\n }\n\n return (byteCount);\n }",
"@Override\n public EthiopicDate date(Era era, int yearOfEra, int month, int dayOfMonth) {\n return date(prolepticYear(era, yearOfEra), month, dayOfMonth);\n }",
"public RedwoodConfiguration loggingClass(final String classToIgnoreInTraces){\r\n tasks.add(new Runnable() { public void run() { Redwood.addLoggingClass(classToIgnoreInTraces); } });\r\n return this;\r\n }"
] |
Core implementation of matchPath. It is isolated so that it can be called
from TokenizedPattern. | [
"static boolean matchPath(String[] tokenizedPattern, String[] strDirs, boolean isCaseSensitive) {\n int patIdxStart = 0;\n int patIdxEnd = tokenizedPattern.length - 1;\n int strIdxStart = 0;\n int strIdxEnd = strDirs.length - 1;\n\n // up to first '**'\n while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) {\n String patDir = tokenizedPattern[patIdxStart];\n if (patDir.equals(DEEP_TREE_MATCH)) {\n break;\n }\n if (!match(patDir, strDirs[strIdxStart], isCaseSensitive)) {\n return false;\n }\n patIdxStart++;\n strIdxStart++;\n }\n if (strIdxStart > strIdxEnd) {\n // String is exhausted\n for (int i = patIdxStart; i <= patIdxEnd; i++) {\n if (!tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {\n return false;\n }\n }\n return true;\n } else {\n if (patIdxStart > patIdxEnd) {\n // String not exhausted, but pattern is. Failure.\n return false;\n }\n }\n\n // up to last '**'\n while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) {\n String patDir = tokenizedPattern[patIdxEnd];\n if (patDir.equals(DEEP_TREE_MATCH)) {\n break;\n }\n if (!match(patDir, strDirs[strIdxEnd], isCaseSensitive)) {\n return false;\n }\n patIdxEnd--;\n strIdxEnd--;\n }\n if (strIdxStart > strIdxEnd) {\n // String is exhausted\n for (int i = patIdxStart; i <= patIdxEnd; i++) {\n if (!tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {\n return false;\n }\n }\n return true;\n }\n\n while (patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd) {\n int patIdxTmp = -1;\n for (int i = patIdxStart + 1; i <= patIdxEnd; i++) {\n if (tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {\n patIdxTmp = i;\n break;\n }\n }\n if (patIdxTmp == patIdxStart + 1) {\n // '**/**' situation, so skip one\n patIdxStart++;\n continue;\n }\n // Find the pattern between padIdxStart & padIdxTmp in str between\n // strIdxStart & strIdxEnd\n int patLength = (patIdxTmp - patIdxStart - 1);\n int strLength = (strIdxEnd - strIdxStart + 1);\n int foundIdx = -1;\n strLoop:\n for (int i = 0; i <= strLength - patLength; i++) {\n for (int j = 0; j < patLength; j++) {\n String subPat = tokenizedPattern[patIdxStart + j + 1];\n String subStr = strDirs[strIdxStart + i + j];\n if (!match(subPat, subStr, isCaseSensitive)) {\n continue strLoop;\n }\n }\n\n foundIdx = strIdxStart + i;\n break;\n }\n\n if (foundIdx == -1) {\n return false;\n }\n\n patIdxStart = patIdxTmp;\n strIdxStart = foundIdx + patLength;\n }\n\n for (int i = patIdxStart; i <= patIdxEnd; i++) {\n if (!tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {\n return false;\n }\n }\n\n return true;\n }"
] | [
"public CustomField getCustomField(FieldType field)\n {\n CustomField result = m_configMap.get(field);\n if (result == null)\n {\n result = new CustomField(field, this);\n m_configMap.put(field, result);\n }\n return result;\n }",
"public static void indexResourceRoot(final ResourceRoot resourceRoot) throws DeploymentUnitProcessingException {\n if (resourceRoot.getAttachment(Attachments.ANNOTATION_INDEX) != null) {\n return;\n }\n\n VirtualFile indexFile = resourceRoot.getRoot().getChild(ModuleIndexBuilder.INDEX_LOCATION);\n if (indexFile.exists()) {\n try {\n IndexReader reader = new IndexReader(indexFile.openStream());\n resourceRoot.putAttachment(Attachments.ANNOTATION_INDEX, reader.read());\n ServerLogger.DEPLOYMENT_LOGGER.tracef(\"Found and read index at: %s\", indexFile);\n return;\n } catch (Exception e) {\n ServerLogger.DEPLOYMENT_LOGGER.cannotLoadAnnotationIndex(indexFile.getPathName());\n }\n }\n\n // if this flag is present and set to false then do not index the resource\n Boolean shouldIndexResource = resourceRoot.getAttachment(Attachments.INDEX_RESOURCE_ROOT);\n if (shouldIndexResource != null && !shouldIndexResource) {\n return;\n }\n\n final List<String> indexIgnorePathList = resourceRoot.getAttachment(Attachments.INDEX_IGNORE_PATHS);\n final Set<String> indexIgnorePaths;\n if (indexIgnorePathList != null && !indexIgnorePathList.isEmpty()) {\n indexIgnorePaths = new HashSet<String>(indexIgnorePathList);\n } else {\n indexIgnorePaths = null;\n }\n\n final VirtualFile virtualFile = resourceRoot.getRoot();\n final Indexer indexer = new Indexer();\n try {\n final VisitorAttributes visitorAttributes = new VisitorAttributes();\n visitorAttributes.setLeavesOnly(true);\n visitorAttributes.setRecurseFilter(new VirtualFileFilter() {\n public boolean accepts(VirtualFile file) {\n return indexIgnorePaths == null || !indexIgnorePaths.contains(file.getPathNameRelativeTo(virtualFile));\n }\n });\n\n final List<VirtualFile> classChildren = virtualFile.getChildren(new SuffixMatchFilter(\".class\", visitorAttributes));\n for (VirtualFile classFile : classChildren) {\n InputStream inputStream = null;\n try {\n inputStream = classFile.openStream();\n indexer.index(inputStream);\n } catch (Exception e) {\n ServerLogger.DEPLOYMENT_LOGGER.cannotIndexClass(classFile.getPathNameRelativeTo(virtualFile), virtualFile.getPathName(), e);\n } finally {\n VFSUtils.safeClose(inputStream);\n }\n }\n final Index index = indexer.complete();\n resourceRoot.putAttachment(Attachments.ANNOTATION_INDEX, index);\n ServerLogger.DEPLOYMENT_LOGGER.tracef(\"Generated index for archive %s\", virtualFile);\n } catch (Throwable t) {\n throw ServerLogger.ROOT_LOGGER.deploymentIndexingFailed(t);\n }\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 }",
"public static String createUnquotedConstant(String str) {\n if (str == null || str.isEmpty()) {\n return str;\n }\n if (str.startsWith(\"\\\"\")) {\n str = str.substring(1);\n }\n if (str.endsWith(\"\\\"\")) {\n str = str.substring(0,\n str.length() - 1);\n }\n return str;\n }",
"public ParallelTaskBuilder prepareHttpGet(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n \n cb.getHttpMeta().setHttpMethod(HttpMethod.GET);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n \n return cb;\n }",
"private FieldType findForeignFieldType(Class<?> clazz, Class<?> foreignClass, Dao<?, ?> foreignDao)\n\t\t\tthrows SQLException {\n\t\tString foreignColumnName = fieldConfig.getForeignCollectionForeignFieldName();\n\t\tfor (FieldType fieldType : foreignDao.getTableInfo().getFieldTypes()) {\n\t\t\tif (fieldType.getType() == foreignClass\n\t\t\t\t\t&& (foreignColumnName == null || fieldType.getField().getName().equals(foreignColumnName))) {\n\t\t\t\tif (!fieldType.fieldConfig.isForeign() && !fieldType.fieldConfig.isForeignAutoRefresh()) {\n\t\t\t\t\t// this may never be reached\n\t\t\t\t\tthrow new SQLException(\"Foreign collection object \" + clazz + \" for field '\" + field.getName()\n\t\t\t\t\t\t\t+ \"' contains a field of class \" + foreignClass + \" but it's not foreign\");\n\t\t\t\t}\n\t\t\t\treturn fieldType;\n\t\t\t}\n\t\t}\n\t\t// build our complex error message\n\t\tStringBuilder sb = new StringBuilder();\n\t\tsb.append(\"Foreign collection class \").append(clazz.getName());\n\t\tsb.append(\" for field '\").append(field.getName()).append(\"' column-name does not contain a foreign field\");\n\t\tif (foreignColumnName != null) {\n\t\t\tsb.append(\" named '\").append(foreignColumnName).append('\\'');\n\t\t}\n\t\tsb.append(\" of class \").append(foreignClass.getName());\n\t\tthrow new SQLException(sb.toString());\n\t}",
"public void init(Configuration configuration) {\n if (devMode && reload && !listeningToDispatcher) {\n // this is the only way I found to be able to get added to to\n // ConfigurationProvider list\n // listening to events in Dispatcher\n listeningToDispatcher = true;\n Dispatcher.addDispatcherListener(this);\n }\n }",
"public static int getPrecedence( int type, boolean throwIfInvalid ) {\n\n switch( type ) {\n\n case LEFT_PARENTHESIS:\n return 0;\n\n case EQUAL:\n case PLUS_EQUAL:\n case MINUS_EQUAL:\n case MULTIPLY_EQUAL:\n case DIVIDE_EQUAL:\n case INTDIV_EQUAL:\n case MOD_EQUAL:\n case POWER_EQUAL:\n case LOGICAL_OR_EQUAL:\n case LOGICAL_AND_EQUAL:\n case LEFT_SHIFT_EQUAL:\n case RIGHT_SHIFT_EQUAL:\n case RIGHT_SHIFT_UNSIGNED_EQUAL:\n case BITWISE_OR_EQUAL:\n case BITWISE_AND_EQUAL:\n case BITWISE_XOR_EQUAL:\n return 5;\n\n case QUESTION:\n return 10;\n\n case LOGICAL_OR:\n return 15;\n\n case LOGICAL_AND:\n return 20;\n\n case BITWISE_OR:\n case BITWISE_AND:\n case BITWISE_XOR:\n return 22;\n\n case COMPARE_IDENTICAL:\n case COMPARE_NOT_IDENTICAL:\n return 24;\n\n case COMPARE_NOT_EQUAL:\n case COMPARE_EQUAL:\n case COMPARE_LESS_THAN:\n case COMPARE_LESS_THAN_EQUAL:\n case COMPARE_GREATER_THAN:\n case COMPARE_GREATER_THAN_EQUAL:\n case COMPARE_TO:\n case FIND_REGEX:\n case MATCH_REGEX:\n case KEYWORD_INSTANCEOF:\n return 25;\n\n case DOT_DOT:\n case DOT_DOT_DOT:\n return 30;\n\n case LEFT_SHIFT:\n case RIGHT_SHIFT:\n case RIGHT_SHIFT_UNSIGNED:\n return 35;\n\n case PLUS:\n case MINUS:\n return 40;\n\n case MULTIPLY:\n case DIVIDE:\n case INTDIV:\n case MOD:\n return 45;\n\n case NOT:\n case REGEX_PATTERN:\n return 50;\n\n case SYNTH_CAST:\n return 55;\n\n case PLUS_PLUS:\n case MINUS_MINUS:\n case PREFIX_PLUS_PLUS:\n case PREFIX_MINUS_MINUS:\n case POSTFIX_PLUS_PLUS:\n case POSTFIX_MINUS_MINUS:\n return 65;\n\n case PREFIX_PLUS:\n case PREFIX_MINUS:\n return 70;\n\n case POWER:\n return 72;\n\n case SYNTH_METHOD:\n case LEFT_SQUARE_BRACKET:\n return 75;\n\n case DOT:\n case NAVIGATE:\n return 80;\n\n case KEYWORD_NEW:\n return 85;\n }\n\n if( throwIfInvalid ) {\n throw new GroovyBugError( \"precedence requested for non-operator\" );\n }\n\n return -1;\n }",
"private void handleGlobalArguments(CommandLine cmd) {\n\t\tif (cmd.hasOption(CMD_OPTION_DUMP_LOCATION)) {\n\t\t\tthis.dumpDirectoryLocation = cmd\n\t\t\t\t\t.getOptionValue(CMD_OPTION_DUMP_LOCATION);\n\t\t}\n\n\t\tif (cmd.hasOption(CMD_OPTION_OFFLINE_MODE)) {\n\t\t\tthis.offlineMode = true;\n\t\t}\n\n\t\tif (cmd.hasOption(CMD_OPTION_QUIET)) {\n\t\t\tthis.quiet = true;\n\t\t}\n\n\t\tif (cmd.hasOption(CMD_OPTION_CREATE_REPORT)) {\n\t\t\tthis.reportFilename = cmd.getOptionValue(CMD_OPTION_CREATE_REPORT);\n\t\t}\n\n\t\tif (cmd.hasOption(OPTION_FILTER_LANGUAGES)) {\n\t\t\tsetLanguageFilters(cmd.getOptionValue(OPTION_FILTER_LANGUAGES));\n\t\t}\n\n\t\tif (cmd.hasOption(OPTION_FILTER_SITES)) {\n\t\t\tsetSiteFilters(cmd.getOptionValue(OPTION_FILTER_SITES));\n\t\t}\n\n\t\tif (cmd.hasOption(OPTION_FILTER_PROPERTIES)) {\n\t\t\tsetPropertyFilters(cmd.getOptionValue(OPTION_FILTER_PROPERTIES));\n\t\t}\n\n\t\tif (cmd.hasOption(CMD_OPTION_LOCAL_DUMPFILE)) {\n\t\t\tthis.inputDumpLocation = cmd.getOptionValue(OPTION_LOCAL_DUMPFILE);\n\t\t}\n\t}"
] |
Saves meta tree, writes database root and flushes the log.
@param metaTree mutable meta tree
@param env enclosing environment
@param expired expired loggables (database root to be added)
@return database root loggable which is read again from the log. | [
"@NotNull\n static MetaTreeImpl.Proto saveMetaTree(@NotNull final ITreeMutable metaTree,\n @NotNull final EnvironmentImpl env,\n @NotNull final ExpiredLoggableCollection expired) {\n final long newMetaTreeAddress = metaTree.save();\n final Log log = env.getLog();\n final int lastStructureId = env.getLastStructureId();\n final long dbRootAddress = log.write(DatabaseRoot.DATABASE_ROOT_TYPE, Loggable.NO_STRUCTURE_ID,\n DatabaseRoot.asByteIterable(newMetaTreeAddress, lastStructureId));\n expired.add(dbRootAddress, (int) (log.getWrittenHighAddress() - dbRootAddress));\n return new MetaTreeImpl.Proto(newMetaTreeAddress, dbRootAddress);\n }"
] | [
"public static boolean setCustomRequestForDefaultClient(String profileName, String pathName, String customData) {\n try {\n return setCustomForDefaultClient(profileName, pathName, false, customData);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }",
"@Override\n public DiscordianDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }",
"public static Set<Annotation> flattenInterceptorBindings(EnhancedAnnotatedType<?> clazz, BeanManagerImpl beanManager, Collection<Annotation> annotations, boolean addTopLevelInterceptorBindings,\n boolean addInheritedInterceptorBindings) {\n Set<Annotation> flattenInterceptorBindings = new InterceptorBindingSet(beanManager);\n MetaAnnotationStore metaAnnotationStore = beanManager.getServices().get(MetaAnnotationStore.class);\n\n if (addTopLevelInterceptorBindings) {\n addInterceptorBindings(clazz, annotations, flattenInterceptorBindings, metaAnnotationStore);\n }\n if (addInheritedInterceptorBindings) {\n for (Annotation annotation : annotations) {\n addInheritedInterceptorBindings(clazz, annotation.annotationType(), metaAnnotationStore, flattenInterceptorBindings);\n }\n }\n return flattenInterceptorBindings;\n }",
"public static NodeList evaluateXpathExpression(String domStr, String xpathExpr)\n\t\t\tthrows XPathExpressionException, IOException {\n\t\tDocument dom = DomUtils.asDocument(domStr);\n\t\treturn evaluateXpathExpression(dom, xpathExpr);\n\t}",
"public static int getLineCount(String str) {\r\n if (null == str || str.isEmpty()) {\r\n return 0;\r\n }\r\n int count = 1;\r\n for (char c : str.toCharArray()) {\r\n if ('\\n' == c) {\r\n count++;\r\n }\r\n }\r\n return count;\r\n }",
"public boolean nextSplit() {\n if( numSplits == 0 )\n return false;\n x2 = splits[--numSplits];\n if( numSplits > 0 )\n x1 = splits[numSplits-1]+1;\n else\n x1 = 0;\n\n return true;\n }",
"private ServerBootstrap createBootstrap(final ChannelGroup channelGroup) throws Exception {\n EventLoopGroup bossGroup = new NioEventLoopGroup(bossThreadPoolSize,\n createDaemonThreadFactory(serviceName + \"-boss-thread-%d\"));\n EventLoopGroup workerGroup = new NioEventLoopGroup(workerThreadPoolSize,\n createDaemonThreadFactory(serviceName + \"-worker-thread-%d\"));\n ServerBootstrap bootstrap = new ServerBootstrap();\n bootstrap\n .group(bossGroup, workerGroup)\n .channel(NioServerSocketChannel.class)\n .childHandler(new ChannelInitializer<SocketChannel>() {\n @Override\n protected void initChannel(SocketChannel ch) throws Exception {\n channelGroup.add(ch);\n\n ChannelPipeline pipeline = ch.pipeline();\n if (sslHandlerFactory != null) {\n // Add SSLHandler if SSL is enabled\n pipeline.addLast(\"ssl\", sslHandlerFactory.create(ch.alloc()));\n }\n pipeline.addLast(\"codec\", new HttpServerCodec());\n pipeline.addLast(\"compressor\", new HttpContentCompressor());\n pipeline.addLast(\"chunkedWriter\", new ChunkedWriteHandler());\n pipeline.addLast(\"keepAlive\", new HttpServerKeepAliveHandler());\n pipeline.addLast(\"router\", new RequestRouter(resourceHandler, httpChunkLimit, sslHandlerFactory != null));\n if (eventExecutorGroup == null) {\n pipeline.addLast(\"dispatcher\", new HttpDispatcher());\n } else {\n pipeline.addLast(eventExecutorGroup, \"dispatcher\", new HttpDispatcher());\n }\n\n if (pipelineModifier != null) {\n pipelineModifier.modify(pipeline);\n }\n }\n });\n\n for (Map.Entry<ChannelOption, Object> entry : channelConfigs.entrySet()) {\n bootstrap.option(entry.getKey(), entry.getValue());\n }\n for (Map.Entry<ChannelOption, Object> entry : childChannelConfigs.entrySet()) {\n bootstrap.childOption(entry.getKey(), entry.getValue());\n }\n\n return bootstrap;\n }",
"@SuppressWarnings(\"unchecked\")\n public static <E> void serialize(E object, ParameterizedType<E> parameterizedType, OutputStream os) throws IOException {\n mapperFor(parameterizedType).serialize(object, os);\n }",
"public static String termPrefix(String term) {\n int i = term.indexOf(MtasToken.DELIMITER);\n String prefix = term;\n if (i >= 0) {\n prefix = term.substring(0, i);\n }\n return prefix.replace(\"\\u0000\", \"\");\n }"
] |
Fetches the contents of a file representation with asset path and writes them to the provided output stream.
@see <a href=https://developer.box.com/reference#section-x-rep-hints-header>X-Rep-Hints Header</a>
@param representationHint the X-Rep-Hints query for the representation to fetch.
@param assetPath the path of the asset for representations containing multiple files.
@param output the output stream to write the contents to. | [
"public void getRepresentationContent(String representationHint, String assetPath, OutputStream output) {\n\n List<Representation> reps = this.getInfoWithRepresentations(representationHint).getRepresentations();\n if (reps.size() < 1) {\n throw new BoxAPIException(\"No matching representations found\");\n }\n Representation representation = reps.get(0);\n String repState = representation.getStatus().getState();\n\n if (repState.equals(\"viewable\") || repState.equals(\"success\")) {\n\n this.makeRepresentationContentRequest(representation.getContent().getUrlTemplate(),\n assetPath, output);\n return;\n } else if (repState.equals(\"pending\") || repState.equals(\"none\")) {\n\n String repContentURLString = null;\n while (repContentURLString == null) {\n repContentURLString = this.pollRepInfo(representation.getInfo().getUrl());\n }\n\n this.makeRepresentationContentRequest(repContentURLString, assetPath, output);\n return;\n\n } else if (repState.equals(\"error\")) {\n\n throw new BoxAPIException(\"Representation had error status\");\n } else {\n\n throw new BoxAPIException(\"Representation had unknown status\");\n }\n\n }"
] | [
"private void readRelationships()\n {\n for (MapRow row : m_tables.get(\"REL\"))\n {\n Task predecessor = m_activityMap.get(row.getString(\"PREDECESSOR_ACTIVITY_ID\"));\n Task successor = m_activityMap.get(row.getString(\"SUCCESSOR_ACTIVITY_ID\"));\n if (predecessor != null && successor != null)\n {\n Duration lag = row.getDuration(\"LAG_VALUE\");\n RelationType type = row.getRelationType(\"LAG_TYPE\");\n\n successor.addPredecessor(predecessor, type, lag);\n }\n }\n }",
"private void deliverSyncCommand(byte command) {\n for (final SyncListener listener : getSyncListeners()) {\n try {\n switch (command) {\n\n case 0x01:\n listener.becomeMaster();\n\n case 0x10:\n listener.setSyncMode(true);\n break;\n\n case 0x20:\n listener.setSyncMode(false);\n break;\n\n }\n } catch (Throwable t) {\n logger.warn(\"Problem delivering sync command to listener\", t);\n }\n }\n }",
"public static base_response update(nitro_service client, nsspparams resource) throws Exception {\n\t\tnsspparams updateresource = new nsspparams();\n\t\tupdateresource.basethreshold = resource.basethreshold;\n\t\tupdateresource.throttle = resource.throttle;\n\t\treturn updateresource.update_resource(client);\n\t}",
"private void setPlaying(boolean playing) {\n PlaybackState oldState = currentSimpleState();\n if (oldState != null && oldState.playing != playing) {\n setPlaybackState(oldState.player, oldState.position, playing);\n }\n }",
"public static ManagementProtocolHeader parse(DataInput input) throws IOException {\n validateSignature(input);\n expectHeader(input, ManagementProtocol.VERSION_FIELD);\n int version = input.readInt();\n expectHeader(input, ManagementProtocol.TYPE);\n byte type = input.readByte();\n switch (type) {\n case ManagementProtocol.TYPE_REQUEST:\n return new ManagementRequestHeader(version, input);\n case ManagementProtocol.TYPE_RESPONSE:\n return new ManagementResponseHeader(version, input);\n case ManagementProtocol.TYPE_BYE_BYE:\n return new ManagementByeByeHeader(version);\n case ManagementProtocol.TYPE_PING:\n return new ManagementPingHeader(version);\n case ManagementProtocol.TYPE_PONG:\n return new ManagementPongHeader(version);\n default:\n throw ProtocolLogger.ROOT_LOGGER.invalidType(\"0x\" + Integer.toHexString(type));\n }\n }",
"public void dumpKnownFieldMaps(Props props)\n {\n //for (int key=131092; key < 131098; key++)\n for (int key = 50331668; key < 50331674; key++)\n {\n byte[] fieldMapData = props.getByteArray(Integer.valueOf(key));\n if (fieldMapData != null)\n {\n System.out.println(\"KEY: \" + key);\n createFieldMap(fieldMapData);\n System.out.println(toString());\n clear();\n }\n }\n }",
"public int getIntegerBelief(String name){\n Object belief = introspector.getBeliefBase(this).get(name);\n int count = 0;\n if (belief!=null) {\n count = (Integer) belief;\n }\n return (Integer) count;\n }",
"public int addServerGroup(String groupName, int profileId) throws Exception {\n int groupId = -1;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\"INSERT INTO \" + Constants.DB_TABLE_SERVER_GROUPS\n + \"(\" + Constants.GENERIC_NAME + \",\" +\n Constants.GENERIC_PROFILE_ID + \")\"\n + \" VALUES (?, ?);\", PreparedStatement.RETURN_GENERATED_KEYS);\n statement.setString(1, groupName);\n statement.setInt(2, profileId);\n statement.executeUpdate();\n\n results = statement.getGeneratedKeys();\n\n if (results.next()) {\n groupId = results.getInt(1);\n } else {\n // something went wrong\n throw new Exception(\"Could not add group\");\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return groupId;\n }",
"public Map<String, String> getParams() {\n\n Map<String, String> params = new HashMap<>(1);\n params.put(PARAM_COLLAPSED, Boolean.TRUE.toString());\n return params;\n }"
] |
Return a stream of resources from a response
@param response the response
@param <R> the resource type
@param <U> the response type
@return a stream of resources from the response | [
"public static <R extends Resource<?>, U extends PaginatedResponse<R>> Flux<R> getResources(U response) {\n return Flux.fromIterable(response.getResources());\n }"
] | [
"protected int parseZoneId() {\n int result = -1;\n String zoneIdStr = this.request.getHeader(RestMessageHeaders.X_VOLD_ZONE_ID);\n if(zoneIdStr != null) {\n try {\n int zoneId = Integer.parseInt(zoneIdStr);\n if(zoneId < 0) {\n logger.error(\"ZoneId cannot be negative. Assuming the default zone id.\");\n } else {\n result = zoneId;\n }\n } catch(NumberFormatException nfe) {\n logger.error(\"Exception when validating request. Incorrect zone id parameter. Cannot parse this to int: \"\n + zoneIdStr,\n nfe);\n }\n }\n return result;\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 }",
"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}",
"public static boolean oracleExists(CuratorFramework curator) {\n boolean exists = false;\n try {\n exists = curator.checkExists().forPath(ZookeeperPath.ORACLE_SERVER) != null\n && !curator.getChildren().forPath(ZookeeperPath.ORACLE_SERVER).isEmpty();\n } catch (Exception nne) {\n if (nne instanceof KeeperException.NoNodeException) {\n // you'll do nothing\n } else {\n throw new RuntimeException(nne);\n }\n }\n return exists;\n }",
"@Override\n public void setJobQueue(int jobId, Queue queue)\n {\n JqmClientFactory.getClient().setJobQueue(jobId, queue);\n }",
"private CostRateTableEntry getCostRateTableEntry(Date date)\n {\n CostRateTableEntry result;\n\n CostRateTable table = getCostRateTable();\n if (table == null)\n {\n Resource resource = getResource();\n result = new CostRateTableEntry(resource.getStandardRate(), TimeUnit.HOURS, resource.getOvertimeRate(), TimeUnit.HOURS, resource.getCostPerUse(), null);\n }\n else\n {\n if (table.size() == 1)\n {\n result = table.get(0);\n }\n else\n {\n result = table.getEntryByDate(date);\n }\n }\n\n return result;\n }",
"private void releaseConnection()\n {\n if (m_rs != null)\n {\n try\n {\n m_rs.close();\n }\n\n catch (SQLException ex)\n {\n // silently ignore errors on close\n }\n\n m_rs = null;\n }\n\n if (m_ps != null)\n {\n try\n {\n m_ps.close();\n }\n\n catch (SQLException ex)\n {\n // silently ignore errors on close\n }\n\n m_ps = null;\n }\n }",
"public static void pow(ComplexPolar_F64 a , int N , ComplexPolar_F64 result )\n {\n result.r = Math.pow(a.r,N);\n result.theta = N*a.theta;\n }",
"public ItemRequest<Team> removeUser(String team) {\n \n String path = String.format(\"/teams/%s/removeUser\", team);\n return new ItemRequest<Team>(this, Team.class, path, \"POST\");\n }"
] |
Change the color of the center which indicates the new color.
@param color int of the color. | [
"public void setNewCenterColor(int color) {\n\t\tmCenterNewColor = color;\n\t\tmCenterNewPaint.setColor(color);\n\t\tif (mCenterOldColor == 0) {\n\t\t\tmCenterOldColor = color;\n\t\t\tmCenterOldPaint.setColor(color);\n\t\t}\n\t\tif (onColorChangedListener != null && color != oldChangedListenerColor ) {\n\t\t\tonColorChangedListener.onColorChanged(color);\n\t\t\toldChangedListenerColor = color;\n\t\t}\n\t\tinvalidate();\n\t}"
] | [
"public ItemRequest<Webhook> getById(String webhook) {\n \n String path = String.format(\"/webhooks/%s\", webhook);\n return new ItemRequest<Webhook>(this, Webhook.class, path, \"GET\");\n }",
"public void setSingletonVariable(String name, WindupVertexFrame frame)\n {\n setVariable(name, Collections.singletonList(frame));\n }",
"private void sortFileList() {\n if (this.size() > 1) {\n Collections.sort(this.fileList, new Comparator() {\n\n public final int compare(final Object o1, final Object o2) {\n final File f1 = (File) o1;\n final File f2 = (File) o2;\n final Object[] f1TimeAndCount = backupSuffixHelper\n .backupTimeAndCount(f1.getName(), baseFile);\n final Object[] f2TimeAndCount = backupSuffixHelper\n .backupTimeAndCount(f2.getName(), baseFile);\n final long f1TimeSuffix = ((Long) f1TimeAndCount[0]).longValue();\n final long f2TimeSuffix = ((Long) f2TimeAndCount[0]).longValue();\n if ((0L == f1TimeSuffix) && (0L == f2TimeSuffix)) {\n final long f1Time = f1.lastModified();\n final long f2Time = f2.lastModified();\n if (f1Time < f2Time) {\n return -1;\n }\n if (f1Time > f2Time) {\n return 1;\n }\n return 0;\n }\n if (f1TimeSuffix < f2TimeSuffix) {\n return -1;\n }\n if (f1TimeSuffix > f2TimeSuffix) {\n return 1;\n }\n final int f1Count = ((Integer) f1TimeAndCount[1]).intValue();\n final int f2Count = ((Integer) f2TimeAndCount[1]).intValue();\n if (f1Count < f2Count) {\n return -1;\n }\n if (f1Count > f2Count) {\n return 1;\n }\n if (f1Count == f2Count) {\n if (fileHelper.isCompressed(f1)) {\n return -1;\n }\n if (fileHelper.isCompressed(f2)) {\n return 1;\n }\n }\n return 0;\n }\n });\n }\n }",
"public void addFilter(Filter filter)\n {\n if (filter.isTaskFilter())\n {\n m_taskFilters.add(filter);\n }\n\n if (filter.isResourceFilter())\n {\n m_resourceFilters.add(filter);\n }\n\n m_filtersByName.put(filter.getName(), filter);\n m_filtersByID.put(filter.getID(), filter);\n }",
"public static Object tryGetSingleton(Class<?> invokerClass, App app) {\n Object singleton = app.singleton(invokerClass);\n if (null == singleton) {\n if (isGlobalOrStateless(invokerClass, new HashSet<Class>())) {\n singleton = app.getInstance(invokerClass);\n }\n }\n if (null != singleton) {\n app.registerSingleton(singleton);\n }\n return singleton;\n }",
"protected synchronized ResourceRoot getSeamIntResourceRoot() throws DeploymentUnitProcessingException {\n try {\n if (seamIntResourceRoot == null) {\n final ModuleLoader moduleLoader = Module.getBootModuleLoader();\n Module extModule = moduleLoader.loadModule(EXT_CONTENT_MODULE);\n URL url = extModule.getExportedResource(SEAM_INT_JAR);\n if (url == null)\n throw ServerLogger.ROOT_LOGGER.noSeamIntegrationJarPresent(extModule);\n\n File file = new File(url.toURI());\n VirtualFile vf = VFS.getChild(file.toURI());\n final Closeable mountHandle = VFS.mountZip(file, vf, TempFileProviderService.provider());\n Service<Closeable> mountHandleService = new Service<Closeable>() {\n public void start(StartContext startContext) throws StartException {\n }\n\n public void stop(StopContext stopContext) {\n VFSUtils.safeClose(mountHandle);\n }\n\n public Closeable getValue() throws IllegalStateException, IllegalArgumentException {\n return mountHandle;\n }\n };\n ServiceBuilder<Closeable> builder = serviceTarget.addService(ServiceName.JBOSS.append(SEAM_INT_JAR),\n mountHandleService);\n builder.setInitialMode(ServiceController.Mode.ACTIVE).install();\n serviceTarget = null; // our cleanup service install work is done\n\n MountHandle dummy = MountHandle.create(null); // actual close is done by the MSC service above\n seamIntResourceRoot = new ResourceRoot(vf, dummy);\n }\n return seamIntResourceRoot;\n } catch (Exception e) {\n throw new DeploymentUnitProcessingException(e);\n }\n }",
"@Override\n public synchronized void stop(final StopContext context) {\n final boolean shutdownServers = runningModeControl.getRestartMode() == RestartMode.SERVERS;\n if (shutdownServers) {\n Runnable task = new Runnable() {\n @Override\n public void run() {\n try {\n serverInventory.shutdown(true, -1, true); // TODO graceful shutdown\n serverInventory = null;\n // client.getValue().setServerInventory(null);\n } finally {\n serverCallback.getValue().setCallbackHandler(null);\n context.complete();\n }\n }\n };\n try {\n executorService.getValue().execute(task);\n } catch (RejectedExecutionException e) {\n task.run();\n } finally {\n context.asynchronous();\n }\n } else {\n // We have to set the shutdown flag in any case\n serverInventory.shutdown(false, -1, true);\n serverInventory = null;\n }\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 }",
"private boolean isAbandoned(final SubmittedPrintJob printJob) {\n final long duration = ThreadPoolJobManager.this.jobQueue.timeSinceLastStatusCheck(\n printJob.getEntry().getReferenceId());\n final boolean abandoned =\n duration > TimeUnit.SECONDS.toMillis(ThreadPoolJobManager.this.abandonedTimeout);\n if (abandoned) {\n LOGGER.info(\"Job {} is abandoned (no status check within the last {} seconds)\",\n printJob.getEntry().getReferenceId(), ThreadPoolJobManager.this.abandonedTimeout);\n }\n return abandoned;\n }"
] |
Retrieve a single value property.
@param method method definition
@param object target object
@param map parameter values | [
"private void getSingleValue(Method method, Object object, Map<String, String> map)\n {\n Object value;\n try\n {\n value = filterValue(method.invoke(object));\n }\n catch (Exception ex)\n {\n value = ex.toString();\n }\n\n if (value != null)\n {\n map.put(getPropertyName(method), String.valueOf(value));\n }\n }"
] | [
"public static void registerAgent(Agent agent, String serviceName, String serviceType) throws FIPAException{\n DFAgentDescription dfd = new DFAgentDescription();\n ServiceDescription sd = new ServiceDescription();\n \n sd.setType(serviceType);\n sd.setName(serviceName);\n \n //NOTE El serviceType es un string que define el tipo de servicio publicado en el DF por el Agente X. \n // He escogido crear nombres en clave en jade.common.Definitions para este campo. \n //NOTE El serviceName es el nombre efectivo del servicio. \n // Esto es lo que el usuario va a definir en MockConfiguration.DFNameService y no el tipo como estaba puesto. \n // sd.setType(agentType);\n // sd.setName(agent.getLocalName());\n \n //Add services??\n \n // Sets the agent description\n dfd.setName(agent.getAID());\n dfd.addServices(sd);\n \n // Register the agent\n DFService.register(agent, dfd);\n }",
"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 }",
"private File[] getFilesFromProperty(final String name, final Properties props) {\n String sep = WildFlySecurityManager.getPropertyPrivileged(\"path.separator\", null);\n String value = props.getProperty(name, null);\n if (value != null) {\n final String[] paths = value.split(Pattern.quote(sep));\n final int len = paths.length;\n final File[] files = new File[len];\n for (int i = 0; i < len; i++) {\n files[i] = new File(paths[i]);\n }\n return files;\n }\n return NO_FILES;\n }",
"public String getDefaultTableName()\r\n {\r\n String name = getName();\r\n int lastDotPos = name.lastIndexOf('.');\r\n int lastDollarPos = name.lastIndexOf('$');\r\n\r\n return lastDollarPos > lastDotPos ? name.substring(lastDollarPos + 1) : name.substring(lastDotPos + 1);\r\n }",
"public 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 }",
"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 void unsetCurrentPersistenceBroker(PBKey key, PersistenceBrokerInternal broker)\r\n throws PBFactoryException\r\n {\r\n HashMap map = (HashMap) currentBrokerMap.get();\r\n WeakHashMap set = null;\r\n if(map != null)\r\n {\r\n set = (WeakHashMap) map.get(key);\r\n if(set != null)\r\n {\r\n set.remove(broker);\r\n if(set.isEmpty())\r\n {\r\n map.remove(key);\r\n }\r\n }\r\n if(map.isEmpty())\r\n {\r\n currentBrokerMap.set(null);\r\n synchronized(lock) {\r\n loadedHMs.remove(map);\r\n }\r\n }\r\n }\r\n }",
"public static String readTextFile(InputStream inputStream) {\n InputStreamReader streamReader = new InputStreamReader(inputStream);\n return readTextFile(streamReader);\n }",
"public void remove(Identity oid)\r\n {\r\n if (oid == null) return;\r\n\r\n ObjectCache cache = getCache(oid, null, METHOD_REMOVE);\r\n if (cache != null)\r\n {\r\n cache.remove(oid);\r\n }\r\n }"
] |
Set a knot color.
@param n the knot index
@param color the color | [
"public void setColor(int n, int color) {\n\t\tint firstColor = map[0];\n\t\tint lastColor = map[256-1];\n\t\tif (n > 0)\n\t\t\tfor (int i = 0; i < n; i++)\n\t\t\t\tmap[i] = ImageMath.mixColors((float)i/n, firstColor, color);\n\t\tif (n < 256-1)\n\t\t\tfor (int i = n; i < 256; i++)\n\t\t\t\tmap[i] = ImageMath.mixColors((float)(i-n)/(256-n), color, lastColor);\n\t}"
] | [
"private static String getColumnTitle(final PropertyDescriptor _property) {\n final StringBuilder buffer = new StringBuilder();\n final String name = _property.getName();\n buffer.append(Character.toUpperCase(name.charAt(0)));\n for (int i = 1; i < name.length(); i++) {\n final char c = name.charAt(i);\n if (Character.isUpperCase(c)) {\n buffer.append(' ');\n }\n buffer.append(c);\n }\n return buffer.toString();\n }",
"public static responderglobal_responderpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tresponderglobal_responderpolicy_binding obj = new responderglobal_responderpolicy_binding();\n\t\tresponderglobal_responderpolicy_binding response[] = (responderglobal_responderpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void setInvalidValues(final Set<String> invalidValues,\n final boolean isCaseSensitive,\n final String invalidValueErrorMessage) {\n if (isCaseSensitive) {\n this.invalidValues = invalidValues;\n } else {\n this.invalidValues = new HashSet<String>();\n for (String value : invalidValues) {\n this.invalidValues.add(value.toLowerCase());\n }\n }\n this.isCaseSensitive = isCaseSensitive;\n this.invalidValueErrorMessage = invalidValueErrorMessage;\n }",
"public void setHighlightStrength(float _highlightStrength) {\n mHighlightStrength = _highlightStrength;\n for (PieModel model : mPieData) {\n highlightSlice(model);\n }\n invalidateGlobal();\n }",
"public void remove(I_CmsEditableGroupRow row) {\n\n int index = m_container.getComponentIndex(row);\n if (index >= 0) {\n m_container.removeComponent(row);\n }\n updatePlaceholder();\n updateButtonBars();\n updateGroupValidation();\n }",
"static boolean matchPath(String[] tokenizedPattern, String[] strDirs, boolean isCaseSensitive) {\n int patIdxStart = 0;\n int patIdxEnd = tokenizedPattern.length - 1;\n int strIdxStart = 0;\n int strIdxEnd = strDirs.length - 1;\n\n // up to first '**'\n while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) {\n String patDir = tokenizedPattern[patIdxStart];\n if (patDir.equals(DEEP_TREE_MATCH)) {\n break;\n }\n if (!match(patDir, strDirs[strIdxStart], isCaseSensitive)) {\n return false;\n }\n patIdxStart++;\n strIdxStart++;\n }\n if (strIdxStart > strIdxEnd) {\n // String is exhausted\n for (int i = patIdxStart; i <= patIdxEnd; i++) {\n if (!tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {\n return false;\n }\n }\n return true;\n } else {\n if (patIdxStart > patIdxEnd) {\n // String not exhausted, but pattern is. Failure.\n return false;\n }\n }\n\n // up to last '**'\n while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) {\n String patDir = tokenizedPattern[patIdxEnd];\n if (patDir.equals(DEEP_TREE_MATCH)) {\n break;\n }\n if (!match(patDir, strDirs[strIdxEnd], isCaseSensitive)) {\n return false;\n }\n patIdxEnd--;\n strIdxEnd--;\n }\n if (strIdxStart > strIdxEnd) {\n // String is exhausted\n for (int i = patIdxStart; i <= patIdxEnd; i++) {\n if (!tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {\n return false;\n }\n }\n return true;\n }\n\n while (patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd) {\n int patIdxTmp = -1;\n for (int i = patIdxStart + 1; i <= patIdxEnd; i++) {\n if (tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {\n patIdxTmp = i;\n break;\n }\n }\n if (patIdxTmp == patIdxStart + 1) {\n // '**/**' situation, so skip one\n patIdxStart++;\n continue;\n }\n // Find the pattern between padIdxStart & padIdxTmp in str between\n // strIdxStart & strIdxEnd\n int patLength = (patIdxTmp - patIdxStart - 1);\n int strLength = (strIdxEnd - strIdxStart + 1);\n int foundIdx = -1;\n strLoop:\n for (int i = 0; i <= strLength - patLength; i++) {\n for (int j = 0; j < patLength; j++) {\n String subPat = tokenizedPattern[patIdxStart + j + 1];\n String subStr = strDirs[strIdxStart + i + j];\n if (!match(subPat, subStr, isCaseSensitive)) {\n continue strLoop;\n }\n }\n\n foundIdx = strIdxStart + i;\n break;\n }\n\n if (foundIdx == -1) {\n return false;\n }\n\n patIdxStart = patIdxTmp;\n strIdxStart = foundIdx + patLength;\n }\n\n for (int i = patIdxStart; i <= patIdxEnd; i++) {\n if (!tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {\n return false;\n }\n }\n\n return true;\n }",
"private ProjectFile handleDatabaseInDirectory(File directory) throws Exception\n {\n byte[] buffer = new byte[BUFFER_SIZE];\n File[] files = directory.listFiles();\n if (files != null)\n {\n for (File file : files)\n {\n if (file.isDirectory())\n {\n continue;\n }\n\n FileInputStream fis = new FileInputStream(file);\n int bytesRead = fis.read(buffer);\n fis.close();\n\n //\n // If the file is smaller than the buffer we are peeking into,\n // it's probably not a valid schedule file.\n //\n if (bytesRead != BUFFER_SIZE)\n {\n continue;\n }\n\n if (matchesFingerprint(buffer, BTRIEVE_FINGERPRINT))\n {\n return handleP3BtrieveDatabase(directory);\n }\n\n if (matchesFingerprint(buffer, STW_FINGERPRINT))\n {\n return handleSureTrakDatabase(directory);\n }\n }\n }\n return null;\n }",
"protected void initializeJdbcConnection(Connection con, JdbcConnectionDescriptor jcd)\r\n throws LookupException\r\n {\r\n try\r\n {\r\n PlatformFactory.getPlatformFor(jcd).initializeJdbcConnection(jcd, con);\r\n }\r\n catch (PlatformException e)\r\n {\r\n throw new LookupException(\"Platform dependent initialization of connection failed\", e);\r\n }\r\n }",
"protected Boolean getIgnoreExpirationDate() {\n\n Boolean isIgnoreExpirationDate = parseOptionalBooleanValue(m_configObject, JSON_KEY_IGNORE_EXPIRATION_DATE);\n return (null == isIgnoreExpirationDate) && (m_baseConfig != null)\n ? Boolean.valueOf(m_baseConfig.getGeneralConfig().getIgnoreExpirationDate())\n : isIgnoreExpirationDate;\n }"
] |
Get the schema for the Avro Record from the object container file | [
"public String getRecordSchema() throws IOException {\n Schema schema = getInputPathAvroSchema();\n String recSchema = schema.toString();\n return recSchema;\n }"
] | [
"private void printPropertyRecord(PrintStream out,\n\t\t\tPropertyRecord propertyRecord, PropertyIdValue propertyIdValue) {\n\n\t\tprintTerms(out, propertyRecord.propertyDocument, propertyIdValue, null);\n\n\t\tString datatype = \"Unknown\";\n\t\tif (propertyRecord.propertyDocument != null) {\n\t\t\tdatatype = getDatatypeLabel(propertyRecord.propertyDocument\n\t\t\t\t\t.getDatatype());\n\t\t}\n\n\t\tout.print(\",\"\n\t\t\t\t+ datatype\n\t\t\t\t+ \",\"\n\t\t\t\t+ propertyRecord.statementCount\n\t\t\t\t+ \",\"\n\t\t\t\t+ propertyRecord.itemCount\n\t\t\t\t+ \",\"\n\t\t\t\t+ propertyRecord.statementWithQualifierCount\n\t\t\t\t+ \",\"\n\t\t\t\t+ propertyRecord.qualifierCount\n\t\t\t\t+ \",\"\n\t\t\t\t+ propertyRecord.referenceCount\n\t\t\t\t+ \",\"\n\t\t\t\t+ (propertyRecord.statementCount\n\t\t\t\t\t\t+ propertyRecord.qualifierCount + propertyRecord.referenceCount));\n\n\t\tprintRelatedProperties(out, propertyRecord);\n\n\t\tout.println(\"\");\n\t}",
"String getDefaultReturnFields() {\n\n StringBuffer fields = new StringBuffer(\"\");\n fields.append(CmsSearchField.FIELD_PATH);\n fields.append(',');\n fields.append(CmsSearchField.FIELD_INSTANCEDATE).append('_').append(getSearchLocale().toString()).append(\"_dt\");\n fields.append(',');\n fields.append(CmsSearchField.FIELD_INSTANCEDATE_END).append('_').append(getSearchLocale().toString()).append(\n \"_dt\");\n fields.append(',');\n fields.append(CmsSearchField.FIELD_INSTANCEDATE_CURRENT_TILL).append('_').append(\n getSearchLocale().toString()).append(\"_dt\");\n fields.append(',');\n fields.append(CmsSearchField.FIELD_ID);\n fields.append(',');\n fields.append(CmsSearchField.FIELD_SOLR_ID);\n fields.append(',');\n fields.append(CmsSearchField.FIELD_DISPTITLE).append('_').append(getSearchLocale().toString()).append(\"_sort\");\n fields.append(',');\n fields.append(CmsSearchField.FIELD_LINK);\n return fields.toString();\n }",
"public void onCreate(T content, LayoutInflater layoutInflater, ViewGroup parent) {\n this.content = content;\n this.rootView = inflate(layoutInflater, parent);\n if (rootView == null) {\n throw new NotInflateViewException(\n \"Renderer instances have to return a not null view in inflateView method\");\n }\n this.rootView.setTag(this);\n setUpView(rootView);\n hookListeners(rootView);\n }",
"static void processFile(final IdentityPatchContext context, final File file, final PatchingTaskContext.Mode mode) throws IOException {\n if (mode == PatchingTaskContext.Mode.APPLY) {\n if (ENABLE_INVALIDATION) {\n updateJar(file, GOOD_ENDSIG_PATTERN, BAD_BYTE_SKIP, CRIPPLED_ENDSIG, GOOD_ENDSIG);\n backup(context, file);\n }\n } else if (mode == PatchingTaskContext.Mode.ROLLBACK) {\n updateJar(file, CRIPPLED_ENDSIG_PATTERN, BAD_BYTE_SKIP, GOOD_ENDSIG, CRIPPLED_ENDSIG);\n restore(context, file);\n } else {\n throw new IllegalStateException();\n }\n }",
"public final void setVolumeByIncrement(float level) throws IOException {\n Volume volume = this.getStatus().volume;\n float total = volume.level;\n\n if (volume.increment <= 0f) {\n throw new ChromeCastException(\"Volume.increment is <= 0\");\n }\n\n // With floating points we always have minor decimal variations, using the Math.min/max\n // works around this issue\n // Increase volume\n if (level > total) {\n while (total < level) {\n total = Math.min(total + volume.increment, level);\n setVolume(total);\n }\n // Decrease Volume\n } else if (level < total) {\n while (total > level) {\n total = Math.max(total - volume.increment, level);\n setVolume(total);\n }\n }\n }",
"public String getInvalidMessage(String key) {\n return invalidMessageOverride == null ? messageMixin.lookup(key, messageValueArgs) : MessageFormat.format(\n invalidMessageOverride, messageValueArgs);\n }",
"public static StringBuffer leftShift(String self, Object value) {\n return new StringBuffer(self).append(value);\n }",
"@UiHandler(\"m_currentTillEndCheckBox\")\n void onCurrentTillEndChange(ValueChangeEvent<Boolean> event) {\n\n if (handleChange()) {\n m_controller.setCurrentTillEnd(event.getValue());\n }\n }",
"public String getSafetyLevel() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_SAFETY_LEVEL);\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 personElement = response.getPayload();\r\n return personElement.getAttribute(\"safety_level\");\r\n }"
] |
Try to build an default PBKey for convenience PB create method.
@return PBKey or <code>null</code> if default key was not declared in
metadata | [
"private PBKey buildDefaultKey()\r\n {\r\n List descriptors = connectionRepository().getAllDescriptor();\r\n JdbcConnectionDescriptor descriptor;\r\n PBKey result = null;\r\n for (Iterator iterator = descriptors.iterator(); iterator.hasNext();)\r\n {\r\n descriptor = (JdbcConnectionDescriptor) iterator.next();\r\n if (descriptor.isDefaultConnection())\r\n {\r\n if(result != null)\r\n {\r\n log.error(\"Found additional connection descriptor with enabled 'default-connection' \"\r\n + descriptor.getPBKey() + \". This is NOT allowed. Will use the first found descriptor \" + result\r\n + \" as default connection\");\r\n }\r\n else\r\n {\r\n result = descriptor.getPBKey();\r\n }\r\n }\r\n }\r\n\r\n if(result == null)\r\n {\r\n log.info(\"No 'default-connection' attribute set in jdbc-connection-descriptors,\" +\r\n \" thus it's currently not possible to use 'defaultPersistenceBroker()' \" +\r\n \" convenience method to lookup PersistenceBroker instances. But it's possible\"+\r\n \" to enable this at runtime using 'setDefaultKey' method.\");\r\n }\r\n return result;\r\n }"
] | [
"protected String escapeApostrophes(String text) {\r\n\t\tString resultString;\r\n\t\tif (text.contains(\"'\")) {\r\n\t\t\tStringBuilder stringBuilder = new StringBuilder();\r\n\t\t\tstringBuilder.append(\"concat('\");\r\n\t\t\tstringBuilder.append(text.replace(\"'\", \"',\\\"'\\\",'\"));\r\n\t\t\tstringBuilder.append(\"')\");\r\n\t\t\tresultString = stringBuilder.toString();\r\n\t\t} else {\r\n\t\t\tresultString = \"'\" + text + \"'\";\r\n\t\t}\r\n\t\treturn resultString;\r\n\t}",
"public synchronized void init() {\n channelFactory = new NioClientSocketChannelFactory(\n Executors.newCachedThreadPool(),\n Executors.newCachedThreadPool());\n\n datagramChannelFactory = new NioDatagramChannelFactory(\n Executors.newCachedThreadPool());\n\n timer = new HashedWheelTimer();\n }",
"public static BoxRetentionPolicy.Info createIndefinitePolicy(BoxAPIConnection api, String name) {\r\n return createRetentionPolicy(api, name, TYPE_INDEFINITE, 0, ACTION_REMOVE_RETENTION);\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}",
"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 }",
"public Photo getListPhoto(String photoId) throws FlickrException {\n\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_LIST_PHOTO);\n\n parameters.put(\"photo_id\", photoId);\n\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\n if (response.isError()) {\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\n }\n\n Element photoElement = response.getPayload();\n Photo photo = new Photo();\n photo.setId(photoElement.getAttribute(\"id\"));\n\n List<Tag> tags = new ArrayList<Tag>();\n Element tagsElement = (Element) photoElement.getElementsByTagName(\"tags\").item(0);\n NodeList tagElements = tagsElement.getElementsByTagName(\"tag\");\n for (int i = 0; i < tagElements.getLength(); i++) {\n Element tagElement = (Element) tagElements.item(i);\n Tag tag = new Tag();\n tag.setId(tagElement.getAttribute(\"id\"));\n tag.setAuthor(tagElement.getAttribute(\"author\"));\n tag.setAuthorName(tagElement.getAttribute(\"authorname\"));\n tag.setRaw(tagElement.getAttribute(\"raw\"));\n tag.setValue(((Text) tagElement.getFirstChild()).getData());\n tags.add(tag);\n }\n photo.setTags(tags);\n return photo;\n }",
"public AssemblyResponse cancelAssembly(String url)\n throws RequestException, LocalOperationException {\n Request request = new Request(this);\n return new AssemblyResponse(request.delete(url, new HashMap<String, Object>()));\n }",
"public static final String printExtendedAttribute(MSPDIWriter writer, Object value, DataType type)\n {\n String result;\n\n if (type == DataType.DATE)\n {\n result = printExtendedAttributeDate((Date) value);\n }\n else\n {\n if (value instanceof Boolean)\n {\n result = printExtendedAttributeBoolean((Boolean) value);\n }\n else\n {\n if (value instanceof Duration)\n {\n result = printDuration(writer, (Duration) value);\n }\n else\n {\n if (type == DataType.CURRENCY)\n {\n result = printExtendedAttributeCurrency((Number) value);\n }\n else\n {\n if (value instanceof Number)\n {\n result = printExtendedAttributeNumber((Number) value);\n }\n else\n {\n result = value.toString();\n }\n }\n }\n }\n }\n\n return (result);\n }",
"@Override\n public void checkin(K key, V resource) {\n super.checkin(key, resource);\n // NB: Blocking checkout calls for synchronous requests get the resource\n // checked in above before processQueueLoop() attempts checkout below.\n // There is therefore a risk that asynchronous requests will be starved.\n processQueueLoop(key);\n }"
] |
Get the property name from the expression.
@param expression expression
@return property name | [
"private String getPropertyName(Expression expression) {\n\t\tif (!(expression instanceof PropertyName)) {\n\t\t\tthrow new IllegalArgumentException(\"Expression \" + expression + \" is not a PropertyName.\");\n\t\t}\n\t\tString name = ((PropertyName) expression).getPropertyName();\n\t\tif (name.endsWith(FilterService.ATTRIBUTE_ID)) {\n\t\t\t// replace by Hibernate id property, always refers to the id, even if named differently\n\t\t\tname = name.substring(0, name.length() - FilterService.ATTRIBUTE_ID.length()) + HIBERNATE_ID;\n\t\t}\n\t\treturn name;\n\t}"
] | [
"private void toNextDate(Calendar date, int interval) {\n\n long previousDate = date.getTimeInMillis();\n if (!m_weekOfMonthIterator.hasNext()) {\n date.add(Calendar.MONTH, interval);\n m_weekOfMonthIterator = m_weeksOfMonth.iterator();\n }\n toCorrectDateWithDay(date, m_weekOfMonthIterator.next());\n if (previousDate == date.getTimeInMillis()) { // this can happen if the fourth and the last week are checked.\n toNextDate(date);\n }\n\n }",
"protected AbstractColumn buildSimpleImageColumn() {\n\t\tImageColumn column = new ImageColumn();\n\t\tpopulateCommonAttributes(column);\n\t\tpopulateExpressionAttributes(column);\n\t\t\n\t\tcolumn.setExpression(customExpression);\n\t\tcolumn.setExpressionToGroupBy(customExpressionToGroupBy);\n\t\tcolumn.setExpressionForCalculation(customExpressionForCalculation);\n\t\t\n\t\tcolumn.setScaleMode(imageScaleMode);\n\t\treturn column;\n\t}",
"public static boolean ensureJedisConnection(final Jedis jedis) {\n final boolean jedisOK = testJedisConnection(jedis);\n if (!jedisOK) {\n try {\n jedis.quit();\n } catch (Exception e) {\n } // Ignore\n try {\n jedis.disconnect();\n } catch (Exception e) {\n } // Ignore\n jedis.connect();\n }\n return jedisOK;\n }",
"@JsonProperty(\"labels\")\n @JsonInclude(Include.NON_EMPTY)\n public Map<String, TermImpl> getLabelUpdates() {\n \treturn getMonolingualUpdatedValues(newLabels);\n }",
"public static <T> ServiceFuture<T> fromResponse(final Observable<ServiceResponse<T>> observable) {\n final ServiceFuture<T> serviceFuture = new ServiceFuture<>();\n serviceFuture.subscription = observable\n .last()\n .subscribe(new Action1<ServiceResponse<T>>() {\n @Override\n public void call(ServiceResponse<T> t) {\n serviceFuture.set(t.body());\n }\n }, new Action1<Throwable>() {\n @Override\n public void call(Throwable throwable) {\n serviceFuture.setException(throwable);\n }\n });\n return serviceFuture;\n }",
"public double nonNormalizedTreeDist(LblTree t1, LblTree t2) {\n\t\tinit(t1, t2);\n\t\tSTR = new int[size1][size2];\n\t\tcomputeOptimalStrategy();\n\t\treturn computeDistUsingStrArray(it1, it2);\n\t}",
"private void writeCustomFields() throws IOException\n {\n m_writer.writeStartList(\"custom_fields\");\n for (CustomField field : m_projectFile.getCustomFields())\n {\n writeCustomField(field);\n }\n m_writer.writeEndList();\n }",
"public Identity refreshIdentity()\r\n {\r\n Identity oldOid = getIdentity();\r\n this.oid = getBroker().serviceIdentity().buildIdentity(myObj);\r\n return oldOid;\r\n }",
"public static int getHostSegmentIndex(int networkPrefixLength, int bytesPerSegment, int bitsPerSegment) {\n\t\tif(bytesPerSegment > 1) {\n\t\t\tif(bytesPerSegment == 2) {\n\t\t\t\treturn networkPrefixLength >> 4;\n\t\t\t}\n\t\t\treturn networkPrefixLength / bitsPerSegment;\n\t\t}\n\t\treturn networkPrefixLength >> 3;\n\t}"
] |
Use this API to convert sslpkcs8. | [
"public static base_response convert(nitro_service client, sslpkcs8 resource) throws Exception {\n\t\tsslpkcs8 convertresource = new sslpkcs8();\n\t\tconvertresource.pkcs8file = resource.pkcs8file;\n\t\tconvertresource.keyfile = resource.keyfile;\n\t\tconvertresource.keyform = resource.keyform;\n\t\tconvertresource.password = resource.password;\n\t\treturn convertresource.perform_operation(client,\"convert\");\n\t}"
] | [
"private void processLayouts(Project phoenixProject)\n {\n //\n // Find the active layout\n //\n Layout activeLayout = getActiveLayout(phoenixProject);\n\n //\n // Create a list of the visible codes in the correct order\n //\n for (CodeOption option : activeLayout.getCodeOptions().getCodeOption())\n {\n if (option.isShown().booleanValue())\n {\n m_codeSequence.add(getUUID(option.getCodeUuid(), option.getCode()));\n }\n }\n }",
"public static String getSimpleClassName(String className) {\n\t\t// get the last part of the class name\n\t\tString[] parts = className.split(\"\\\\.\");\n\t\tif (parts.length <= 1) {\n\t\t\treturn className;\n\t\t} else {\n\t\t\treturn parts[parts.length - 1];\n\t\t}\n\t}",
"public static long addressToLong(InetAddress address) {\n long result = 0;\n for (byte element : address.getAddress()) {\n result = (result << 8) + unsign(element);\n }\n return result;\n }",
"@Override\n protected void addLineContent(BufferedReader bufferedFileReader, List<String> content, String line) throws IOException {\n // Is the line an empty comment \"#\" ?\n if (line.startsWith(COMMENT_PREFIX) && line.length() == 1) {\n String nextLine = bufferedFileReader.readLine();\n if (nextLine != null) {\n // Is the next line the realm name \"#$REALM_NAME=\" ?\n if (nextLine.startsWith(COMMENT_PREFIX) && nextLine.contains(REALM_COMMENT_PREFIX)) {\n // Realm name block detected!\n // The next line must be and empty comment \"#\"\n bufferedFileReader.readLine();\n // Avoid adding the realm block\n } else {\n // It's a user comment...\n content.add(line);\n content.add(nextLine);\n }\n } else {\n super.addLineContent(bufferedFileReader, content, line);\n }\n } else {\n super.addLineContent(bufferedFileReader, content, line);\n }\n }",
"public ClassNode parent(String name) {\n this.parent = infoBase.node(name);\n this.parent.addChild(this);\n for (ClassNode intf : parent.interfaces.values()) {\n addInterface(intf);\n }\n return this;\n }",
"public static filterglobal_filterpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tfilterglobal_filterpolicy_binding obj = new filterglobal_filterpolicy_binding();\n\t\tfilterglobal_filterpolicy_binding response[] = (filterglobal_filterpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"static ChangeEvent<BsonDocument> changeEventForLocalUpdate(\n final MongoNamespace namespace,\n final BsonValue documentId,\n final UpdateDescription update,\n final BsonDocument fullDocumentAfterUpdate,\n final boolean writePending\n ) {\n return new ChangeEvent<>(\n new BsonDocument(),\n OperationType.UPDATE,\n fullDocumentAfterUpdate,\n namespace,\n new BsonDocument(\"_id\", documentId),\n update,\n writePending);\n }",
"public void recordServerGroupResult(final String serverGroup, final boolean failed) {\n\n synchronized (this) {\n if (groups.contains(serverGroup)) {\n responseCount++;\n if (failed) {\n this.failed = true;\n }\n DomainControllerLogger.HOST_CONTROLLER_LOGGER.tracef(\"Recorded group result for '%s': failed = %s\",\n serverGroup, failed);\n notifyAll();\n }\n else {\n throw DomainControllerLogger.HOST_CONTROLLER_LOGGER.unknownServerGroup(serverGroup);\n }\n }\n }",
"public ItemRequest<Task> update(String task) {\n \n String path = String.format(\"/tasks/%s\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"PUT\");\n }"
] |
Check invariant.
@param browser The browser.
@return Whether the condition is satisfied or <code>false</code> when it it isn't or a
{@link CrawljaxException} occurs. | [
"@Override\r\n\tpublic boolean check(EmbeddedBrowser browser) {\r\n\t\tString js =\r\n\t\t\t\t\"try{ if(\" + expression + \"){return '1';}else{\" + \"return '0';}}catch(e){\"\r\n\t\t\t\t\t\t+ \" return '0';}\";\r\n\t\ttry {\r\n\t\t\tObject object = browser.executeJavaScript(js);\r\n\t\t\tif (object == null) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\treturn object.toString().equals(\"1\");\r\n\t\t} catch (CrawljaxException e) {\r\n\t\t\t// Exception is caught, check failed so return false;\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}"
] | [
"@Override\n\tpublic void validate() throws AddressStringException {\n\t\tif(isValidated()) {\n\t\t\treturn;\n\t\t}\n\t\tsynchronized(this) {\n\t\t\tif(isValidated()) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t//we know nothing about this address. See what it is.\n\t\t\ttry {\n\t\t\t\tparsedAddress = getValidator().validateAddress(this);\n\t\t\t\tisValid = true;\n\t\t\t} catch(AddressStringException e) {\n\t\t\t\tcachedException = e;\n\t\t\t\tisValid = false;\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t}",
"private String appendXmlEndingTag(String value) {\r\n StringBuilder sb = new StringBuilder();\r\n sb.append(\"</\").append(value).append(\">\");\n\r\n return sb.toString();\r\n }",
"public int update(DatabaseConnection databaseConnection, PreparedUpdate<T> preparedUpdate) throws SQLException {\n\t\tCompiledStatement compiledStatement = preparedUpdate.compile(databaseConnection, StatementType.UPDATE);\n\t\ttry {\n\t\t\tint result = compiledStatement.runUpdate();\n\t\t\tif (dao != null && !localIsInBatchMode.get()) {\n\t\t\t\tdao.notifyChanges();\n\t\t\t}\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tIOUtils.closeThrowSqlException(compiledStatement, \"compiled statement\");\n\t\t}\n\t}",
"protected synchronized void doWriteObjects(boolean isFlush) throws TransactionAbortedException, LockNotGrantedException\r\n {\r\n /*\r\n arminw:\r\n if broker isn't in PB-tx, start tx\r\n */\r\n if (!getBroker().isInTransaction())\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"call beginTransaction() on PB instance\");\r\n broker.beginTransaction();\r\n }\r\n\r\n // Notify objects of impending commits.\r\n performTransactionAwareBeforeCommit();\r\n\r\n // Now perfom the real work\r\n objectEnvelopeTable.writeObjects(isFlush);\r\n // now we have to perform the named objects\r\n namedRootsMap.performDeletion();\r\n namedRootsMap.performInsert();\r\n namedRootsMap.afterWriteCleanup();\r\n }",
"private TableAlias createTableAlias(String aTable, String aPath, String aUserAlias)\r\n {\r\n\t\tif (aUserAlias == null)\r\n\t\t{\r\n\t\t\treturn createTableAlias(aTable, aPath);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn createTableAlias(aTable, aUserAlias + ALIAS_SEPARATOR + aPath);\r\n\t\t}\r\n }",
"private static Class<?> getGenericReturnType(Method method, Class<?> source, int typeIndex, int nestingLevel) {\n\t\treturn extractType(method.getGenericReturnType(), source, typeIndex, null, null, nestingLevel, 1);\n\t}",
"public NodeT getNext() {\n String nextItemKey = queue.poll();\n if (nextItemKey == null) {\n return null;\n }\n return nodeTable.get(nextItemKey);\n }",
"protected String adaptFilePath(String filePath) {\n // Convert windows file path to target FS\n String targetPath = filePath.replaceAll(\"\\\\\\\\\", volumeType.getSeparator());\n\n return targetPath;\n }",
"public static <IN> PaddedList<IN> valueOf(List<IN> list, IN padding) {\r\n return new PaddedList<IN>(list, padding);\r\n }"
] |
The Baseline Finish field shows the planned completion date for a task
at the time you saved a baseline. Information in this field becomes
available when you set a baseline for a task.
@return Date | [
"public Date getBaselineFinish()\n {\n Object result = getCachedValue(TaskField.BASELINE_FINISH);\n if (result == null)\n {\n result = getCachedValue(TaskField.BASELINE_ESTIMATED_FINISH);\n }\n\n if (!(result instanceof Date))\n {\n result = null;\n }\n return (Date) result;\n }"
] | [
"public static EventType map(Event event) {\n EventType eventType = new EventType();\n eventType.setTimestamp(Converter.convertDate(event.getTimestamp()));\n eventType.setEventType(convertEventType(event.getEventType()));\n OriginatorType origType = mapOriginator(event.getOriginator());\n eventType.setOriginator(origType);\n MessageInfoType miType = mapMessageInfo(event.getMessageInfo());\n eventType.setMessageInfo(miType);\n eventType.setCustomInfo(convertCustomInfo(event.getCustomInfo()));\n eventType.setContentCut(event.isContentCut());\n if (event.getContent() != null) {\n DataHandler datHandler = getDataHandlerForString(event);\n eventType.setContent(datHandler);\n }\n return eventType;\n }",
"@Override\n public Object invoke(Object self, Method method, Method proceed, Object[] args) throws Throwable {\n if (\"destroy\".equals(method.getName()) && Marker.isMarker(0, method, args)) {\n if (bean.getEjbDescriptor().isStateful()) {\n if (!reference.isRemoved()) {\n reference.remove();\n }\n }\n return null;\n }\n\n if (!bean.isClientCanCallRemoveMethods() && isRemoveMethod(method)) {\n throw BeanLogger.LOG.invalidRemoveMethodInvocation(method);\n }\n Class<?> businessInterface = getBusinessInterface(method);\n if (reference.isRemoved() && isToStringMethod(method)) {\n return businessInterface.getName() + \" [REMOVED]\";\n }\n Object proxiedInstance = reference.getBusinessObject(businessInterface);\n\n if (!Modifier.isPublic(method.getModifiers())) {\n throw new EJBException(\"Not a business method \" + method.toString() +\". Do not call non-public methods on EJB's.\");\n }\n Object returnValue = Reflections.invokeAndUnwrap(proxiedInstance, method, args);\n BeanLogger.LOG.callProxiedMethod(method, proxiedInstance, args, returnValue);\n return returnValue;\n }",
"public boolean classifySentenceStdin(DocumentReaderAndWriter<IN> readerWriter)\r\n throws IOException\r\n {\r\n BufferedReader is = new BufferedReader(new InputStreamReader(System.in, flags.inputEncoding));\r\n String line;\r\n String text = \"\";\r\n String eol = \"\\n\";\r\n String sentence = \"<s>\";\r\n while ((line = is.readLine()) != null) {\r\n \t\r\n if (line.trim().equals(\"\")) {\r\n \t text += sentence + eol;\r\n \t ObjectBank<List<IN>> documents = makeObjectBankFromString(text, readerWriter);\r\n classifyAndWriteAnswers(documents, readerWriter);\r\n text = \"\";\r\n } else {\r\n \t text += line + eol;\r\n }\r\n }\r\n if (text.trim().equals(\"\")) {\r\n \treturn false;\r\n }\r\n return true;\r\n }",
"static File getTargetFile(final File root, final MiscContentItem item) {\n return PatchContentLoader.getMiscPath(root, item);\n }",
"public static Collection<CurrencyUnit> getCurrencies(String... providers) {\n return Optional.ofNullable(MONETARY_CURRENCIES_SINGLETON_SPI()).orElseThrow(\n () -> new MonetaryException(\"No MonetaryCurrenciesSingletonSpi loaded, check your system setup.\"))\n .getCurrencies(providers);\n }",
"public static final boolean setSelectedValue(ListBox list, String value, boolean addMissingValues) {\n\tif (value == null) {\n\t list.setSelectedIndex(0);\n\t return false;\n\t}\n\telse {\n\t int index = findValueInListBox(list, value);\n\t if (index >= 0) {\n\t\tlist.setSelectedIndex(index);\n\t\treturn true;\n\t }\n\n\t if (addMissingValues) {\n\t\tlist.addItem(value, value);\n\n\t\t// now that it's there, search again\n\t\tindex = findValueInListBox(list, value);\n\t\tlist.setSelectedIndex(index);\n\t\treturn true;\n\t }\n\n\t return false;\n\t}\n }",
"private void 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 static base_response update(nitro_service client, nsacl6 resource) throws Exception {\n\t\tnsacl6 updateresource = new nsacl6();\n\t\tupdateresource.acl6name = resource.acl6name;\n\t\tupdateresource.aclaction = resource.aclaction;\n\t\tupdateresource.srcipv6 = resource.srcipv6;\n\t\tupdateresource.srcipop = resource.srcipop;\n\t\tupdateresource.srcipv6val = resource.srcipv6val;\n\t\tupdateresource.srcport = resource.srcport;\n\t\tupdateresource.srcportop = resource.srcportop;\n\t\tupdateresource.srcportval = resource.srcportval;\n\t\tupdateresource.destipv6 = resource.destipv6;\n\t\tupdateresource.destipop = resource.destipop;\n\t\tupdateresource.destipv6val = resource.destipv6val;\n\t\tupdateresource.destport = resource.destport;\n\t\tupdateresource.destportop = resource.destportop;\n\t\tupdateresource.destportval = resource.destportval;\n\t\tupdateresource.srcmac = resource.srcmac;\n\t\tupdateresource.protocol = resource.protocol;\n\t\tupdateresource.protocolnumber = resource.protocolnumber;\n\t\tupdateresource.icmptype = resource.icmptype;\n\t\tupdateresource.icmpcode = resource.icmpcode;\n\t\tupdateresource.vlan = resource.vlan;\n\t\tupdateresource.Interface = resource.Interface;\n\t\tupdateresource.priority = resource.priority;\n\t\tupdateresource.established = resource.established;\n\t\treturn updateresource.update_resource(client);\n\t}",
"protected float[] transformPosition(float x, float y)\n {\n Point2D.Float point = super.transformedPoint(x, y);\n AffineTransform pageTransform = createCurrentPageTransformation();\n Point2D.Float transformedPoint = (Point2D.Float) pageTransform.transform(point, null);\n\n return new float[]{(float) transformedPoint.getX(), (float) transformedPoint.getY()};\n }"
] |
The user making this call must be a member of the team in order to add others.
The user to add must exist in the same organization as the team in order to be added.
The user to add can be referenced by their globally unique user ID or their email address.
Returns the full user record for the added user.
@param team Globally unique identifier for the team.
@return Request object | [
"public ItemRequest<Team> addUser(String team) {\n \n String path = String.format(\"/teams/%s/addUser\", team);\n return new ItemRequest<Team>(this, Team.class, path, \"POST\");\n }"
] | [
"String fetchToken(String tokenType) throws IOException, MediaWikiApiErrorException {\n\t\tMap<String, String> params = new HashMap<>();\n\t\tparams.put(ApiConnection.PARAM_ACTION, \"query\");\n\t\tparams.put(\"meta\", \"tokens\");\n\t\tparams.put(\"type\", tokenType);\n\n\t\ttry {\n\t\t\tJsonNode root = this.sendJsonRequest(\"POST\", params);\n\t\t\treturn root.path(\"query\").path(\"tokens\").path(tokenType + \"token\").textValue();\n\t\t} catch (IOException | MediaWikiApiErrorException e) {\n\t\t\tlogger.error(\"Error when trying to fetch token: \" + e.toString());\n\t\t}\n\t\treturn null;\n\t}",
"@JsonProperty(\"labels\")\n @JsonInclude(Include.NON_EMPTY)\n public Map<String, TermImpl> getLabelUpdates() {\n \treturn getMonolingualUpdatedValues(newLabels);\n }",
"@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients/{clientUUID}\", method = RequestMethod.DELETE)\n public\n @ResponseBody\n HashMap<String, Object> deleteClient(Model model,\n @PathVariable(\"profileIdentifier\") String profileIdentifier,\n @PathVariable(\"clientUUID\") String clientUUID) throws Exception {\n logger.info(\"Attempting to remove the following client: {}\", clientUUID);\n if (clientUUID.compareTo(Constants.PROFILE_CLIENT_DEFAULT_ID) == 0)\n throw new Exception(\"Default client cannot be deleted\");\n\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n clientService.remove(profileId, clientUUID);\n\n HashMap<String, Object> valueHash = new HashMap<String, Object>();\n valueHash.put(\"clients\", clientService.findAllClients(profileId));\n return valueHash;\n }",
"public Launcher addEnvironmentVariable(final String key, final String value) {\n env.put(key, value);\n return this;\n }",
"public static <T extends DMatrix> boolean decomposeSafe(DecompositionInterface<T> decomp, T M ) {\n if( decomp.inputModified() ) {\n return decomp.decompose(M.<T>copy());\n } else {\n return decomp.decompose(M);\n }\n }",
"public static policydataset_value_binding[] get(nitro_service service, String name) throws Exception{\n\t\tpolicydataset_value_binding obj = new policydataset_value_binding();\n\t\tobj.set_name(name);\n\t\tpolicydataset_value_binding response[] = (policydataset_value_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void populateAnnotations(Collection<Annotation> annotations) {\n for (Annotation each : annotations) {\n this.annotations.put(each.annotationType(), each);\n }\n }",
"private boolean isSpecial(final char chr) {\n\t\treturn ((chr == '.') || (chr == '?') || (chr == '*') || (chr == '^') || (chr == '$') || (chr == '+')\n\t\t\t\t|| (chr == '[') || (chr == ']') || (chr == '(') || (chr == ')') || (chr == '|') || (chr == '\\\\')\n\t\t\t\t|| (chr == '&'));\n\t}",
"private void readPattern(JSONObject patternJson) {\n\n setPatternType(readPatternType(patternJson));\n setInterval(readOptionalInt(patternJson, JsonKey.PATTERN_INTERVAL));\n setWeekDays(readWeekDays(patternJson));\n setDayOfMonth(readOptionalInt(patternJson, JsonKey.PATTERN_DAY_OF_MONTH));\n setEveryWorkingDay(readOptionalBoolean(patternJson, JsonKey.PATTERN_EVERYWORKINGDAY));\n setWeeksOfMonth(readWeeksOfMonth(patternJson));\n setIndividualDates(readDates(readOptionalArray(patternJson, JsonKey.PATTERN_DATES)));\n setMonth(readOptionalMonth(patternJson, JsonKey.PATTERN_MONTH));\n\n }"
] |
If the Artifact does not exist, it will add it to the database. Nothing if it already exit.
@param fromClient DbArtifact | [
"public void storeIfNew(final DbArtifact fromClient) {\n final DbArtifact existing = repositoryHandler.getArtifact(fromClient.getGavc());\n\n if(existing != null){\n existing.setLicenses(fromClient.getLicenses());\n store(existing);\n }\n\n if(existing == null){\n\t store(fromClient);\n }\n }"
] | [
"private Double getDouble(Number number)\n {\n Double result = null;\n\n if (number != null)\n {\n result = Double.valueOf(number.doubleValue());\n }\n\n return result;\n }",
"public <T> void setState(HttpConnectionInterceptor interceptor, String stateName, T\n stateObjectToStore) {\n Map<String, Object> state = interceptorStates.get(interceptor);\n if (state == null) {\n interceptorStates.put(interceptor, (state = new ConcurrentHashMap<String, Object>()));\n }\n state.put(stateName, stateObjectToStore);\n }",
"public SelectStatement getPreparedSelectStatement(Query query, ClassDescriptor cld)\r\n {\r\n SelectStatement sql = new SqlSelectStatement(m_platform, cld, query, logger);\r\n if (logger.isDebugEnabled())\r\n {\r\n logger.debug(\"SQL:\" + sql.getStatement());\r\n }\r\n return sql;\r\n }",
"public boolean isMaintenanceModeEnabled(String appName) {\n App app = connection.execute(new AppInfo(appName), apiKey);\n return app.isMaintenance();\n }",
"@Override\r\n public boolean containsKey(Object key) {\r\n // key could be not in original or in deltaMap\r\n // key could be not in original but in deltaMap\r\n // key could be in original but removed from deltaMap\r\n // key could be in original but mapped to something else in deltaMap\r\n Object value = deltaMap.get(key);\r\n if (value == null) {\r\n return originalMap.containsKey(key);\r\n }\r\n if (value == removedValue) {\r\n return false;\r\n }\r\n return true;\r\n }",
"public static void cacheParseFailure(XmlFileModel key)\n {\n map.put(getKey(key), new CacheDocument(true, null));\n }",
"public static void populateSubject(final LinkedHashMap<String, CommonProfile> profiles) {\n if (profiles != null && profiles.size() > 0) {\n final List<CommonProfile> listProfiles = ProfileHelper.flatIntoAProfileList(profiles);\n try {\n if (IS_FULLY_AUTHENTICATED_AUTHORIZER.isAuthorized(null, listProfiles)) {\n SecurityUtils.getSubject().login(new Pac4jToken(listProfiles, false));\n } else if (IS_REMEMBERED_AUTHORIZER.isAuthorized(null, listProfiles)) {\n SecurityUtils.getSubject().login(new Pac4jToken(listProfiles, true));\n }\n } catch (final HttpAction e) {\n throw new TechnicalException(e);\n }\n }\n }",
"public static Map<String, String> getMetadataFromSequenceFile(FileSystem fs, Path path) {\n try {\n Configuration conf = new Configuration();\n conf.setInt(\"io.file.buffer.size\", 4096);\n SequenceFile.Reader reader = new SequenceFile.Reader(fs, path, new Configuration());\n SequenceFile.Metadata meta = reader.getMetadata();\n reader.close();\n TreeMap<Text, Text> map = meta.getMetadata();\n Map<String, String> values = new HashMap<String, String>();\n for(Map.Entry<Text, Text> entry: map.entrySet())\n values.put(entry.getKey().toString(), entry.getValue().toString());\n\n return values;\n } catch(IOException e) {\n throw new RuntimeException(e);\n }\n }",
"private void writeTimeUnitsField(String fieldName, Object value) throws IOException\n {\n TimeUnit val = (TimeUnit) value;\n if (val != m_projectFile.getProjectProperties().getDefaultDurationUnits())\n {\n m_writer.writeNameValuePair(fieldName, val.toString());\n }\n }"
] |
Use this API to fetch all the sslocspresponder resources that are configured on netscaler. | [
"public static sslocspresponder[] get(nitro_service service) throws Exception{\n\t\tsslocspresponder obj = new sslocspresponder();\n\t\tsslocspresponder[] response = (sslocspresponder[])obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"protected final void error(final HttpServletResponse httpServletResponse, final Throwable e) {\n httpServletResponse.setContentType(\"text/plain\");\n httpServletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());\n try (PrintWriter out = httpServletResponse.getWriter()) {\n out.println(\"Error while processing request:\");\n LOGGER.error(\"Error while processing request\", e);\n } catch (IOException ex) {\n throw ExceptionUtils.getRuntimeException(ex);\n }\n }",
"private static double arcAngle(Point center, Point a, Point b, Rect area, int radius) {\n double angle = threePointsAngle(center, a, b);\n Point innerPoint = findMidnormalPoint(center, a, b, area, radius);\n Point midInsectPoint = new Point((a.x + b.x) / 2, (a.y + b.y) / 2);\n double distance = pointsDistance(midInsectPoint, innerPoint);\n if (distance > radius) {\n return 360 - angle;\n }\n return angle;\n }",
"public List<String> getServiceImplementations(String serviceTypeName) {\n final List<String> strings = services.get(serviceTypeName);\n return strings == null ? Collections.<String>emptyList() : Collections.unmodifiableList(strings);\n }",
"public static Method getGetterPropertyMethod(Class<?> type,\r\n\t\t\tString propertyName) {\r\n\t\tString sourceMethodName = \"get\"\r\n\t\t\t\t+ BeanUtils.capitalizePropertyName(propertyName);\r\n\r\n\t\tMethod sourceMethod = BeanUtils.getMethod(type, sourceMethodName);\r\n\r\n\t\tif (sourceMethod == null) {\r\n\t\t\tsourceMethodName = \"is\"\r\n\t\t\t\t\t+ BeanUtils.capitalizePropertyName(propertyName);\r\n\t\t\tsourceMethod = BeanUtils.getMethod(type, sourceMethodName);\r\n\t\t\tif (sourceMethod != null\r\n\t\t\t\t\t&& sourceMethod.getReturnType() != Boolean.TYPE) {\r\n\t\t\t\tsourceMethod = null;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn sourceMethod;\r\n\t}",
"public static void calculatePointDiff(Point2D _P1, Point2D _P2, Point2D _Result, float _Multiplier) {\n float diffX = _P2.getX() - _P1.getX();\n float diffY = _P2.getY() - _P1.getY();\n _Result.setX(_P1.getX() + (diffX * _Multiplier));\n _Result.setY(_P1.getY() + (diffY * _Multiplier));\n }",
"public HttpConnection setRequestBody(final String input) {\n try {\n final byte[] inputBytes = input.getBytes(\"UTF-8\");\n return setRequestBody(inputBytes);\n } catch (UnsupportedEncodingException e) {\n // This should never happen as every implementation of the java platform is required\n // to support UTF-8.\n throw new RuntimeException(e);\n }\n }",
"protected long getRevisionIdFromResponse(JsonNode response) throws JsonMappingException {\n\t\tif(response == null) {\n\t\t\tthrow new JsonMappingException(\"API response is null\");\n\t\t}\n\t\tJsonNode entity = null;\n\t\tif(response.has(\"entity\")) {\n\t\t\tentity = response.path(\"entity\");\n\t\t} else if(response.has(\"pageinfo\")) {\n\t\t\tentity = response.path(\"pageinfo\");\n\t\t} \n\t\tif(entity != null && entity.has(\"lastrevid\")) {\n\t\t\treturn entity.path(\"lastrevid\").asLong();\n\t\t}\n\t\tthrow new JsonMappingException(\"The last revision id could not be found in API response\");\n\t}",
"public static boolean isFloat(CharSequence self) {\n try {\n Float.valueOf(self.toString().trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n }",
"public AT_Row setPaddingBottomChar(Character paddingBottomChar) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingBottomChar(paddingBottomChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}"
] |
Make a sort order for use in a query. | [
"public static PropertyOrder.Builder makeOrder(String property,\n PropertyOrder.Direction direction) {\n return PropertyOrder.newBuilder()\n .setProperty(makePropertyReference(property))\n .setDirection(direction);\n }"
] | [
"public static Map<Integer, Integer> getMapOfContiguousPartitions(final Cluster cluster,\n int zoneId) {\n List<Integer> partitionIds = new ArrayList<Integer>(cluster.getPartitionIdsInZone(zoneId));\n Map<Integer, Integer> partitionIdToRunLength = Maps.newHashMap();\n\n if(partitionIds.isEmpty()) {\n return partitionIdToRunLength;\n }\n\n int lastPartitionId = partitionIds.get(0);\n int initPartitionId = lastPartitionId;\n\n for(int offset = 1; offset < partitionIds.size(); offset++) {\n int partitionId = partitionIds.get(offset);\n if(partitionId == lastPartitionId + 1) {\n lastPartitionId = partitionId;\n continue;\n }\n int runLength = lastPartitionId - initPartitionId + 1;\n\n partitionIdToRunLength.put(initPartitionId, runLength);\n\n initPartitionId = partitionId;\n lastPartitionId = initPartitionId;\n }\n\n int runLength = lastPartitionId - initPartitionId + 1;\n if(lastPartitionId == cluster.getNumberOfPartitions() - 1\n && partitionIdToRunLength.containsKey(0)) {\n // special case of contiguity that wraps around the ring.\n partitionIdToRunLength.put(initPartitionId, runLength + partitionIdToRunLength.get(0));\n partitionIdToRunLength.remove(0);\n } else {\n partitionIdToRunLength.put(initPartitionId, runLength);\n }\n\n return partitionIdToRunLength;\n }",
"public static void generateJavaFiles(String requirementsFolder,\n String platformName, String src_test_dir, String tests_package,\n String casemanager_package, String loggingPropFile)\n throws Exception {\n\n File reqFolder = new File(requirementsFolder);\n if (reqFolder.isDirectory()) {\n for (File f : reqFolder.listFiles()) {\n if (f.getName().endsWith(\".story\")) {\n try {\n SystemReader.generateJavaFilesForOneStory(\n f.getCanonicalPath(), platformName,\n src_test_dir, tests_package,\n casemanager_package, loggingPropFile);\n } catch (IOException e) {\n String message = \"ERROR: \" + e.getMessage();\n logger.severe(message);\n throw new BeastException(message, e);\n }\n }\n }\n for (File f : reqFolder.listFiles()) {\n if (f.isDirectory()) {\n SystemReader.generateJavaFiles(requirementsFolder\n + File.separator + f.getName(), platformName,\n src_test_dir, tests_package + \".\" + f.getName(),\n casemanager_package, loggingPropFile);\n }\n }\n } else if (reqFolder.getName().endsWith(\".story\")) {\n SystemReader.generateJavaFilesForOneStory(requirementsFolder,\n platformName, src_test_dir, tests_package,\n casemanager_package, loggingPropFile);\n } else {\n String message = \"No story file found in \" + requirementsFolder;\n logger.severe(message);\n throw new BeastException(message);\n }\n\n }",
"@SuppressWarnings(\"unchecked\")\n public <T> T getOptionValue(String name)\n {\n return (T) configurationOptions.get(name);\n }",
"private String getSlashyPath(final String path) {\n String changedPath = path;\n if (File.separatorChar != '/')\n changedPath = changedPath.replace(File.separatorChar, '/');\n\n return changedPath;\n }",
"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 }",
"public boolean isDeleted(Identity id)\r\n {\r\n ObjectEnvelope envelope = buffer.getByIdentity(id);\r\n\r\n return (envelope != null && envelope.needsDelete());\r\n }",
"protected Class<?> loadClass(String clazz) throws ClassNotFoundException {\n\t\tif (this.classLoader == null){\n\t\t\treturn Class.forName(clazz);\n\t\t}\n\n\t\treturn Class.forName(clazz, true, this.classLoader);\n\n\t}",
"private static <T> void readTableField(DatabaseTableConfig<T> config, String field, String value) {\n\t\tif (field.equals(FIELD_NAME_DATA_CLASS)) {\n\t\t\ttry {\n\t\t\t\t@SuppressWarnings(\"unchecked\")\n\t\t\t\tClass<T> clazz = (Class<T>) Class.forName(value);\n\t\t\t\tconfig.setDataClass(clazz);\n\t\t\t} catch (ClassNotFoundException e) {\n\t\t\t\tthrow new IllegalArgumentException(\"Unknown class specified for dataClass: \" + value);\n\t\t\t}\n\t\t} else if (field.equals(FIELD_NAME_TABLE_NAME)) {\n\t\t\tconfig.setTableName(value);\n\t\t}\n\t}",
"public static String readTextFile(InputStream inputStream) {\n InputStreamReader streamReader = new InputStreamReader(inputStream);\n return readTextFile(streamReader);\n }"
] |
Returns the port as configured by the system variables, fallback is the default port value
@param portIdentifier - SYS_*_PORT defined in Constants
@return | [
"public static int getSystemPort(String portIdentifier) {\n int defaultPort = 0;\n\n if (portIdentifier.compareTo(Constants.SYS_API_PORT) == 0) {\n defaultPort = Constants.DEFAULT_API_PORT;\n } else if (portIdentifier.compareTo(Constants.SYS_DB_PORT) == 0) {\n defaultPort = Constants.DEFAULT_DB_PORT;\n } else if (portIdentifier.compareTo(Constants.SYS_FWD_PORT) == 0) {\n defaultPort = Constants.DEFAULT_FWD_PORT;\n } else if (portIdentifier.compareTo(Constants.SYS_HTTP_PORT) == 0) {\n defaultPort = Constants.DEFAULT_HTTP_PORT;\n } else if (portIdentifier.compareTo(Constants.SYS_HTTPS_PORT) == 0) {\n defaultPort = Constants.DEFAULT_HTTPS_PORT;\n } else {\n return defaultPort;\n }\n\n String portStr = System.getenv(portIdentifier);\n return (portStr == null || portStr.isEmpty()) ? defaultPort : Integer.valueOf(portStr);\n }"
] | [
"public static DMatrixRMaj diagonal(int N , double min , double max , Random rand ) {\n return diagonal(N,N,min,max,rand);\n }",
"public void detachMetadataCache(SlotReference slot) {\n MetadataCache oldCache = metadataCacheFiles.remove(slot);\n if (oldCache != null) {\n try {\n oldCache.close();\n } catch (IOException e) {\n logger.error(\"Problem closing metadata cache\", e);\n }\n deliverCacheUpdate(slot, null);\n }\n }",
"public static Command newStartProcess(String processId,\n Map<String, Object> parameters) {\n return getCommandFactoryProvider().newStartProcess( processId,\n parameters );\n }",
"public List<Integer> getTrackIds() {\n ArrayList<Integer> results = new ArrayList<Integer>(trackCount);\n Enumeration<? extends ZipEntry> entries = zipFile.entries();\n while (entries.hasMoreElements()) {\n ZipEntry entry = entries.nextElement();\n if (entry.getName().startsWith(CACHE_METADATA_ENTRY_PREFIX)) {\n String idPart = entry.getName().substring(CACHE_METADATA_ENTRY_PREFIX.length());\n if (idPart.length() > 0) {\n results.add(Integer.valueOf(idPart));\n }\n }\n }\n\n return Collections.unmodifiableList(results);\n }",
"public static base_responses update(nitro_service client, systemuser resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsystemuser updateresources[] = new systemuser[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new systemuser();\n\t\t\t\tupdateresources[i].username = resources[i].username;\n\t\t\t\tupdateresources[i].password = resources[i].password;\n\t\t\t\tupdateresources[i].externalauth = resources[i].externalauth;\n\t\t\t\tupdateresources[i].promptstring = resources[i].promptstring;\n\t\t\t\tupdateresources[i].timeout = resources[i].timeout;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"@Nullable\n public ByteIterable get(@NotNull final Transaction txn, @NotNull final ByteIterable first) {\n return this.first.get(txn, first);\n }",
"public static final double getDouble(String value)\n {\n return (value == null || value.length() == 0 ? 0 : Double.parseDouble(value));\n }",
"private void addDependencyToGraph(final DbDependency dependency, final AbstractGraph graph, final int depth, final String parentId) {\n // In that case of Axway artifact we will add a module to the graph\n if (filters.getCorporateFilter().filter(dependency)) {\n final DbModule dbTarget = repoHandler.getModuleOf(dependency.getTarget());\n\n // if there is no module, add the artifact to the graph\n if(dbTarget == null){\n LOG.error(\"Got missing reference: \" + dependency.getTarget());\n final DbArtifact dbArtifact = DataUtils.createDbArtifact(dependency.getTarget());\n final String targetElementId = graph.getId(dbArtifact);\n graph.addElement(targetElementId, dbArtifact.getVersion(), false);\n graph.addDependency(parentId, targetElementId, dependency.getScope());\n return;\n }\n\n // Add the element to the graph\n addModuleToGraph(dbTarget, graph, depth + 1);\n\n //Add the dependency to the graph\n final String moduleElementId = graph.getId(dbTarget);\n graph.addDependency(parentId, moduleElementId, dependency.getScope());\n }\n // In case a third-party we will add an artifact\n else {\n final DbArtifact dbTarget = repoHandler.getArtifact(dependency.getTarget());\n if(dbTarget == null){\n LOG.error(\"Got missing artifact: \" + dependency.getTarget());\n return;\n }\n\n if(!graph.isTreated(graph.getId(dbTarget))){\n final ModelMapper modelMapper = new ModelMapper(repoHandler);\n final Artifact target = modelMapper.getArtifact(dbTarget);\n final String targetElementId = graph.getId(target);\n graph.addElement(targetElementId, target.getVersion(), false);\n graph.addDependency(parentId, targetElementId, dependency.getScope());\n }\n }\n }",
"public static base_responses delete(nitro_service client, route6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\troute6 deleteresources[] = new route6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new route6();\n\t\t\t\tdeleteresources[i].network = resources[i].network;\n\t\t\t\tdeleteresources[i].gateway = resources[i].gateway;\n\t\t\t\tdeleteresources[i].vlan = resources[i].vlan;\n\t\t\t\tdeleteresources[i].td = resources[i].td;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}"
] |
given the groupName, it returns the groupId
@param groupName name of group
@return ID of group | [
"public Integer getGroupIdFromName(String groupName) {\n return (Integer) sqlService.getFromTable(Constants.GENERIC_ID, Constants.GROUPS_GROUP_NAME, groupName,\n Constants.DB_TABLE_GROUPS);\n }"
] | [
"public static Command newSetGlobal(String identifier,\n Object object) {\n return getCommandFactoryProvider().newSetGlobal( identifier,\n object );\n }",
"public BoxFile.Info uploadFile(InputStream fileContent, String name, long fileSize, ProgressListener listener) {\n FileUploadParams uploadInfo = new FileUploadParams()\n .setContent(fileContent)\n .setName(name)\n .setSize(fileSize)\n .setProgressListener(listener);\n return this.uploadFile(uploadInfo);\n }",
"private AffineTransform getAlignmentTransform() {\n final int offsetX;\n switch (this.settings.getParams().getAlign()) {\n case LEFT:\n offsetX = 0;\n break;\n case RIGHT:\n offsetX = this.settings.getMaxSize().width - this.settings.getSize().width;\n break;\n case CENTER:\n default:\n offsetX = (int) Math\n .floor(this.settings.getMaxSize().width / 2.0 - this.settings.getSize().width / 2.0);\n break;\n }\n\n final int offsetY;\n switch (this.settings.getParams().getVerticalAlign()) {\n case TOP:\n offsetY = 0;\n break;\n case BOTTOM:\n offsetY = this.settings.getMaxSize().height - this.settings.getSize().height;\n break;\n case MIDDLE:\n default:\n offsetY = (int) Math.floor(this.settings.getMaxSize().height / 2.0 -\n this.settings.getSize().height / 2.0);\n break;\n }\n\n return AffineTransform.getTranslateInstance(Math.round(offsetX), Math.round(offsetY));\n }",
"public static base_response reset(nitro_service client) throws Exception {\n\t\tappfwlearningdata resetresource = new appfwlearningdata();\n\t\treturn resetresource.perform_operation(client,\"reset\");\n\t}",
"@Override\n public Symmetry010Date dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }",
"public String getSearchJsonModel() throws IOException {\n DbSearch search = new DbSearch();\n search.setArtifacts(new ArrayList<>());\n search.setModules(new ArrayList<>());\n return JsonUtils.serialize(search);\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 CollectionRequest<Team> findByUser(String user) {\n \n String path = String.format(\"/users/%s/teams\", user);\n return new CollectionRequest<Team>(this, Team.class, path, \"GET\");\n }",
"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 }"
] |
Clear all overrides, reset repeat counts for a response path
@param pathId ID of path
@param clientUUID UUID of client
@throws Exception exception | [
"public void clearResponseSettings(int pathId, String clientUUID) throws Exception {\n logger.info(\"clearing response settings\");\n this.setResponseEnabled(pathId, false, clientUUID);\n OverrideService.getInstance().disableAllOverrides(pathId, clientUUID, Constants.OVERRIDE_TYPE_RESPONSE);\n EditService.getInstance().updateRepeatNumber(Constants.OVERRIDE_TYPE_RESPONSE, pathId, clientUUID);\n }"
] | [
"public synchronized void hide() {\n if (focusedQuad != null) {\n\n mDefocusAnimationFactory.create(focusedQuad)\n .setRequestLayoutOnTargetChange(false)\n .start().finish();\n\n focusedQuad = null;\n }\n Log.d(Log.SUBSYSTEM.WIDGET, TAG, \"hide Picker!\");\n }",
"public int[] argb(int x, int y) {\n Pixel p = pixel(x, y);\n return new int[]{p.alpha(), p.red(), p.green(), p.blue()};\n }",
"public String[][] getRequiredRuleNames(Param param) {\n\t\tif (isFiltered(param)) {\n\t\t\treturn EMPTY_ARRAY;\n\t\t}\n\t\tAbstractElement elementToParse = param.elementToParse;\n\t\tString ruleName = param.ruleName;\n\t\tif (ruleName == null) {\n\t\t\treturn getRequiredRuleNames(param, elementToParse);\n\t\t}\n\t\treturn getAdjustedRequiredRuleNames(param, elementToParse, ruleName);\n\t}",
"public Metadata createMetadata(String typeName, Metadata metadata) {\n String scope = Metadata.scopeBasedOnType(typeName);\n return this.createMetadata(typeName, scope, metadata);\n }",
"public static BoxItem.Info getSharedItem(BoxAPIConnection api, String sharedLink) {\n return getSharedItem(api, sharedLink, null);\n }",
"private void processChildTasks(Task task, MapRow row) throws IOException\n {\n List<MapRow> tasks = row.getRows(\"TASKS\");\n if (tasks != null)\n {\n for (MapRow childTask : tasks)\n {\n processTask(task, childTask);\n }\n }\n }",
"public void setIntVec(IntBuffer data)\n {\n if (data == null)\n {\n throw new IllegalArgumentException(\"Input buffer for indices cannot be null\");\n }\n if (getIndexSize() != 4)\n {\n throw new UnsupportedOperationException(\"Cannot update integer indices with short array\");\n }\n if (data.isDirect())\n {\n if (!NativeIndexBuffer.setIntVec(getNative(), data))\n {\n throw new UnsupportedOperationException(\"Input array is wrong size\");\n }\n }\n else if (data.hasArray())\n {\n if (!NativeIndexBuffer.setIntArray(getNative(), data.array()))\n {\n throw new IllegalArgumentException(\"Data array incompatible with index buffer\");\n }\n }\n else\n {\n throw new UnsupportedOperationException(\"IntBuffer type not supported. Must be direct or have backing array\");\n }\n }",
"public List<WbSearchEntitiesResult> wbSearchEntities(String search, String language,\n Boolean strictLanguage, String type, Long limit, Long offset)\n throws MediaWikiApiErrorException {\n\n Map<String, String> parameters = new HashMap<String, String>();\n parameters.put(ApiConnection.PARAM_ACTION, \"wbsearchentities\");\n\n if (search != null) {\n parameters.put(\"search\", search);\n } else {\n throw new IllegalArgumentException(\n \"Search parameter must be specified for this action.\");\n }\n\n if (language != null) {\n parameters.put(\"language\", language);\n } else {\n throw new IllegalArgumentException(\n \"Language parameter must be specified for this action.\");\n }\n if (strictLanguage != null) {\n parameters.put(\"strictlanguage\", Boolean.toString(strictLanguage));\n }\n\n if (type != null) {\n parameters.put(\"type\", type);\n }\n\n if (limit != null) {\n parameters.put(\"limit\", Long.toString(limit));\n }\n\n if (offset != null) {\n parameters.put(\"continue\", Long.toString(offset));\n }\n\n List<WbSearchEntitiesResult> results = new ArrayList<>();\n\n try {\n JsonNode root = this.connection.sendJsonRequest(\"POST\", parameters);\n JsonNode entities = root.path(\"search\");\n for (JsonNode entityNode : entities) {\n try {\n JacksonWbSearchEntitiesResult ed = mapper.treeToValue(entityNode,\n JacksonWbSearchEntitiesResult.class);\n results.add(ed);\n } catch (JsonProcessingException e) {\n LOGGER.error(\"Error when reading JSON for entity \"\n + entityNode.path(\"id\").asText(\"UNKNOWN\") + \": \"\n + e.toString());\n }\n }\n } catch (IOException e) {\n LOGGER.error(\"Could not retrive data: \" + e.toString());\n }\n\n return results;\n }",
"public static void setDefaultHostName(String hostName) {\n if (hostName == null || hostName.contains(\":\")) {\n return;\n }\n DEFAULT_BASE_URL = \"http://\" + hostName + \":\" + DEFAULT_API_PORT + \"/\" + API_BASE + \"/\";\n }"
] |
Set the TableAlias for ClassDescriptor | [
"private void setTableAliasForClassDescriptor(ClassDescriptor aCld, TableAlias anAlias)\r\n {\r\n if (m_cldToAlias.get(aCld) == null)\r\n {\r\n m_cldToAlias.put(aCld, anAlias);\r\n } \r\n }"
] | [
"public byte[] getMessageBuffer() {\n\t\tByteArrayOutputStream resultByteBuffer = new ByteArrayOutputStream();\n\t\tbyte[] result;\n\t\tresultByteBuffer.write((byte)0x01);\n\t\tint messageLength = messagePayload.length + \n\t\t\t\t(this.messageClass == SerialMessageClass.SendData && \n\t\t\t\tthis.messageType == SerialMessageType.Request ? 5 : 3); // calculate and set length\n\t\t\n\t\tresultByteBuffer.write((byte) messageLength);\n\t\tresultByteBuffer.write((byte) messageType.ordinal());\n\t\tresultByteBuffer.write((byte) messageClass.getKey());\n\t\t\n\t\ttry {\n\t\t\tresultByteBuffer.write(messagePayload);\n\t\t} catch (IOException e) {\n\t\t\t\n\t\t}\n\n\t\t// callback ID and transmit options for a Send Data message.\n\t\tif (this.messageClass == SerialMessageClass.SendData && this.messageType == SerialMessageType.Request) {\n\t\t\tresultByteBuffer.write(transmitOptions);\n\t\t\tresultByteBuffer.write(callbackId);\n\t\t}\n\t\t\n\t\tresultByteBuffer.write((byte) 0x00);\n\t\tresult = resultByteBuffer.toByteArray();\n\t\tresult[result.length - 1] = 0x01;\n\t\tresult[result.length - 1] = calculateChecksum(result);\n\t\tlogger.debug(\"Assembled message buffer = \" + SerialMessage.bb2hex(result));\n\t\treturn result;\n\t}",
"private SiteRecord getSiteRecord(String siteKey) {\n\t\tSiteRecord siteRecord = this.siteRecords.get(siteKey);\n\t\tif (siteRecord == null) {\n\t\t\tsiteRecord = new SiteRecord(siteKey);\n\t\t\tthis.siteRecords.put(siteKey, siteRecord);\n\t\t}\n\t\treturn siteRecord;\n\t}",
"public boolean canLockBecauseOfInactivity(CmsObject cms, CmsUser user) {\n\n return !user.isManaged()\n && !user.isWebuser()\n && !OpenCms.getDefaultUsers().isDefaultUser(user.getName())\n && !OpenCms.getRoleManager().hasRole(cms, user.getName(), CmsRole.ROOT_ADMIN);\n }",
"public synchronized GeoInterface getGeoInterface() {\r\n if (geoInterface == null) {\r\n geoInterface = new GeoInterface(apiKey, sharedSecret, transport);\r\n }\r\n return geoInterface;\r\n }",
"public void setJobTypes(final Map<String, ? extends Class<?>> jobTypes) {\n checkJobTypes(jobTypes);\n this.jobTypes.clear();\n this.jobTypes.putAll(jobTypes);\n }",
"public boolean getBooleanProperty(String name, boolean defaultValue)\r\n {\r\n return PropertyHelper.toBoolean(_properties.getProperty(name), defaultValue);\r\n }",
"void endOfRunDb()\n {\n DbConn cnx = null;\n\n try\n {\n cnx = Helpers.getNewDbSession();\n\n // Done: put inside history & remove instance from queue.\n History.create(cnx, this.ji, this.resultStatus, endDate);\n jqmlogger.trace(\"An History was just created for job instance \" + this.ji.getId());\n cnx.runUpdate(\"ji_delete_by_id\", this.ji.getId());\n cnx.commit();\n }\n catch (RuntimeException e)\n {\n endBlockDbFailureAnalysis(e);\n }\n finally\n {\n Helpers.closeQuietly(cnx);\n }\n }",
"public byte[] toBytes(T object) {\n try {\n ByteArrayOutputStream stream = new ByteArrayOutputStream();\n ObjectOutputStream out = new ObjectOutputStream(stream);\n out.writeObject(object);\n return stream.toByteArray();\n } catch(IOException e) {\n throw new SerializationException(e);\n }\n }",
"@PostConstruct\n\tprotected void postConstruct() throws GeomajasException {\n\t\tif (null == baseTmsUrl) {\n\t\t\tthrow new GeomajasException(ExceptionCode.PARAMETER_MISSING, \"baseTmsUrl\");\n\t\t}\n\n\t\t// Make sure we have a base URL we can work with:\n\t\tif ((baseTmsUrl.startsWith(\"http://\") || baseTmsUrl.startsWith(\"https://\")) && !baseTmsUrl.endsWith(\"/\")) {\n\t\t\tbaseTmsUrl += \"/\";\n\t\t}\n\n\t\t// Make sure there is a correct RasterLayerInfo object:\n\t\tif (layerInfo == null || layerInfo == UNUSABLE_LAYER_INFO) {\n\t\t\ttry {\n\t\t\t\ttileMap = configurationService.getCapabilities(this);\n\t\t\t\tversion = tileMap.getVersion();\n\t\t\t\textension = tileMap.getTileFormat().getExtension();\n\t\t\t\tlayerInfo = configurationService.asLayerInfo(tileMap);\n\t\t\t\tusable = true;\n\t\t\t} catch (TmsLayerException e) {\n\t\t\t\t// a layer needs an info object to keep the DtoConfigurationPostProcessor happy !\n\t\t\t\tlayerInfo = UNUSABLE_LAYER_INFO;\n\t\t\t\tusable = false;\n\t\t\t\tlog.warn(\"The layer could not be correctly initialized: \" + getId(), e);\n\t\t\t}\n\t\t} else if (extension == null) {\n\t\t\tthrow new GeomajasException(ExceptionCode.PARAMETER_MISSING, \"extension\");\n\t\t}\n\n\t\tif (layerInfo != null) {\n\t\t\t// Finally prepare some often needed values:\n\t\t\tstate = new TileServiceState(geoService, layerInfo);\n\t\t\t// when proxying the real url will be resolved later on, just use a simple one for now\n\t\t\tboolean proxying = useCache || useProxy || null != authentication;\n\t\t\tif (tileMap != null && !proxying) {\n\t\t\t\turlBuilder = new TileMapUrlBuilder(tileMap);\n\t\t\t} else {\n\t\t\t\turlBuilder = new SimpleTmsUrlBuilder(extension);\n\t\t\t}\n\t\t}\n\t}"
] |
Deletes the specified shovel from specified virtual host.
@param vhost virtual host from where to delete the shovel
@param shovelname Shovel to be deleted. | [
"public void deleteShovel(String vhost, String shovelname) {\n\t this.deleteIgnoring404(uriWithPath(\"./parameters/shovel/\" + encodePathSegment(vhost) + \"/\" + encodePathSegment(shovelname)));\n }"
] | [
"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 }",
"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 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 static boolean checkConfiguredInModules() {\n\n Boolean result = m_moduleCheckCache.get();\n if (result == null) {\n result = Boolean.valueOf(getConfiguredTemplateMapping() != null);\n m_moduleCheckCache.set(result);\n }\n return result.booleanValue();\n }",
"public BeatGrid requestBeatGridFrom(final DataReference track) {\n for (BeatGrid cached : hotCache.values()) {\n if (cached.dataReference.equals(track)) { // Found a hot cue hit, use it.\n return cached;\n }\n }\n return requestBeatGridInternal(track, false);\n }",
"public static boolean isIdentity(DMatrix a , double tol )\n {\n for( int i = 0; i < a.getNumRows(); i++ ) {\n for( int j = 0; j < a.getNumCols(); j++ ) {\n if( i == j ) {\n if( Math.abs(a.get(i,j)-1.0) > tol )\n return false;\n } else {\n if( Math.abs(a.get(i,j)) > tol )\n return false;\n }\n }\n }\n return true;\n }",
"void commitTempFile(File temp) throws ConfigurationPersistenceException {\n if (!doneBootup.get()) {\n return;\n }\n if (!interactionPolicy.isReadOnly()) {\n FilePersistenceUtils.moveTempFileToMain(temp, mainFile);\n } else {\n FilePersistenceUtils.moveTempFileToMain(temp, lastFile);\n }\n }",
"public void setFirstOccurence(int min, int max) throws ParseException {\n if (fullCondition == null) {\n if ((min < 0) || (min > max) || (max < 1)) {\n throw new ParseException(\"Illegal number {\" + min + \",\" + max + \"}\");\n }\n if (min == 0) {\n firstOptional = true;\n }\n firstMinimumOccurence = Math.max(1, min);\n firstMaximumOccurence = max;\n } else {\n throw new ParseException(\"fullCondition already generated\");\n }\n }",
"public static base_response add(nitro_service client, autoscaleprofile resource) throws Exception {\n\t\tautoscaleprofile addresource = new autoscaleprofile();\n\t\taddresource.name = resource.name;\n\t\taddresource.type = resource.type;\n\t\taddresource.url = resource.url;\n\t\taddresource.apikey = resource.apikey;\n\t\taddresource.sharedsecret = resource.sharedsecret;\n\t\treturn addresource.add_resource(client);\n\t}"
] |
Get the beat grids available for all tracks currently loaded in any player, either on the play deck, or
in a hot cue.
@return the beat grids associated with all current players, including for any tracks loaded in their hot cue slots
@throws IllegalStateException if the BeatGridFinder is not running | [
"@SuppressWarnings(\"WeakerAccess\")\n public Map<DeckReference, BeatGrid> getLoadedBeatGrids() {\n ensureRunning();\n // Make a copy so callers get an immutable snapshot of the current state.\n return Collections.unmodifiableMap(new HashMap<DeckReference, BeatGrid>(hotCache));\n }"
] | [
"private void updateDb(String dbName, String webapp) {\n\n m_mainLayout.removeAllComponents();\n m_setupBean.setDatabase(dbName);\n CmsDbSettingsPanel panel = new CmsDbSettingsPanel(m_setupBean);\n m_panel[0] = panel;\n panel.initFromSetupBean(webapp);\n m_mainLayout.addComponent(panel);\n }",
"public boolean hasUser(String userId) {\r\n String normalized = normalizerUserName(userId);\r\n return loginToUser.containsKey(normalized) || emailToUser.containsKey(normalized);\r\n }",
"public static base_responses add(nitro_service client, autoscaleaction resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tautoscaleaction addresources[] = new autoscaleaction[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new autoscaleaction();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].type = resources[i].type;\n\t\t\t\taddresources[i].profilename = resources[i].profilename;\n\t\t\t\taddresources[i].parameters = resources[i].parameters;\n\t\t\t\taddresources[i].vmdestroygraceperiod = resources[i].vmdestroygraceperiod;\n\t\t\t\taddresources[i].quiettime = resources[i].quiettime;\n\t\t\t\taddresources[i].vserver = resources[i].vserver;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"private void writeBufferedValsToStorage() {\n List<Versioned<byte[]>> obsoleteVals = storageEngine.multiVersionPut(currBufferedKey,\n currBufferedVals);\n // log Obsolete versions in debug mode\n if(logger.isDebugEnabled() && obsoleteVals.size() > 0) {\n logger.debug(\"updateEntries (Streaming multi-version-put) rejected these versions as obsolete : \"\n + StoreUtils.getVersions(obsoleteVals) + \" for key \" + currBufferedKey);\n }\n currBufferedVals = new ArrayList<Versioned<byte[]>>(VALS_BUFFER_EXPECTED_SIZE);\n }",
"public static int cudnnGetActivationDescriptor(\n cudnnActivationDescriptor activationDesc, \n int[] mode, \n int[] reluNanOpt, \n double[] coef)/** ceiling for clipped RELU, alpha for ELU */\n {\n return checkResult(cudnnGetActivationDescriptorNative(activationDesc, mode, reluNanOpt, coef));\n }",
"private String filterTag(String tag) {\r\n\t AttributeValues answerAV = TagSet.getTagSet().fromTag(tag);\r\n\t answerAV.removeNonlexicalAttributes();\r\n\t return TagSet.getTagSet().toTag(answerAV);\r\n }",
"public static void unregisterContextualInstance(EjbDescriptor<?> descriptor) {\n Set<Class<?>> classes = CONTEXTUAL_SESSION_BEANS.get();\n classes.remove(descriptor.getBeanClass());\n if (classes.isEmpty()) {\n CONTEXTUAL_SESSION_BEANS.remove();\n }\n }",
"public static aaa_stats get(nitro_service service) throws Exception{\n\t\taaa_stats obj = new aaa_stats();\n\t\taaa_stats[] response = (aaa_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}",
"private void updateDateTimeFormats(ProjectProperties properties)\n {\n String[] timePatterns = getTimePatterns(properties);\n String[] datePatterns = getDatePatterns(properties);\n String[] dateTimePatterns = getDateTimePatterns(properties, timePatterns);\n\n m_dateTimeFormat.applyPatterns(dateTimePatterns);\n m_dateFormat.applyPatterns(datePatterns);\n m_timeFormat.applyPatterns(timePatterns);\n\n m_dateTimeFormat.setLocale(m_locale);\n m_dateFormat.setLocale(m_locale);\n\n m_dateTimeFormat.setNullText(m_nullText);\n m_dateFormat.setNullText(m_nullText);\n m_timeFormat.setNullText(m_nullText);\n\n m_dateTimeFormat.setAmPmText(properties.getAMText(), properties.getPMText());\n m_timeFormat.setAmPmText(properties.getAMText(), properties.getPMText());\n }"
] |
Use this API to delete sslcertkey. | [
"public static base_response delete(nitro_service client, sslcertkey resource) throws Exception {\n\t\tsslcertkey deleteresource = new sslcertkey();\n\t\tdeleteresource.certkey = resource.certkey;\n\t\treturn deleteresource.delete_resource(client);\n\t}"
] | [
"public WebSocketContext sendToUser(String message, String username) {\n return sendToConnections(message, username, manager.usernameRegistry(), true);\n }",
"public static double ChiSquare(double[] histogram1, double[] histogram2) {\n double r = 0;\n for (int i = 0; i < histogram1.length; i++) {\n double t = histogram1[i] + histogram2[i];\n if (t != 0)\n r += Math.pow(histogram1[i] - histogram2[i], 2) / t;\n }\n\n return 0.5 * r;\n }",
"public void setTargetTranslator(TargetTranslator targetTranslator) {\r\n\t\tif(targetTranslator!=null){\r\n\t\t\tthis.targetTranslator = targetTranslator;\r\n\t\t\tthis.charTranslator = null;\r\n\t\t\tthis.htmlElementTranslator = null;\r\n\t\t}\r\n\t}",
"private static Properties loadGradleProperties(FilePath gradlePropertiesFilePath)\n throws IOException, InterruptedException {\n return gradlePropertiesFilePath.act(new MasterToSlaveFileCallable<Properties>() {\n public Properties invoke(File gradlePropertiesFile, VirtualChannel channel) throws IOException, InterruptedException {\n Properties gradleProps = new Properties();\n if (gradlePropertiesFile.exists()) {\n debuggingLogger.fine(\"Gradle properties file exists at: \" + gradlePropertiesFile.getAbsolutePath());\n FileInputStream stream = null;\n try {\n stream = new FileInputStream(gradlePropertiesFile);\n gradleProps.load(stream);\n } catch (IOException e) {\n debuggingLogger.fine(\"IO exception occurred while trying to read properties file from: \" +\n gradlePropertiesFile.getAbsolutePath());\n throw new RuntimeException(e);\n } finally {\n IOUtils.closeQuietly(stream);\n }\n }\n return gradleProps;\n }\n });\n\n }",
"private void digestInteger(MessageDigest digest, int value) {\n byte[] valueBytes = new byte[4];\n Util.numberToBytes(value, valueBytes, 0, 4);\n digest.update(valueBytes);\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 }",
"public Object toInternal(Attribute<?> attribute) throws GeomajasException {\n\t\tif (attribute instanceof PrimitiveAttribute<?>) {\n\t\t\treturn toPrimitiveObject((PrimitiveAttribute<?>) attribute);\n\t\t} else if (attribute instanceof AssociationAttribute<?>) {\n\t\t\treturn toAssociationObject((AssociationAttribute<?>) attribute);\n\t\t} else {\n\t\t\tthrow new GeomajasException(ExceptionCode.CONVERSION_PROBLEM, attribute);\n\t\t}\n\t}",
"public Collection getReaders(Object obj)\r\n\t{\r\n\t\tCollection result = null;\r\n try\r\n {\r\n Identity oid = new Identity(obj, getBroker());\r\n byte selector = (byte) 'r';\r\n byte[] requestBarr = buildRequestArray(oid, selector);\r\n \r\n HttpURLConnection conn = getHttpUrlConnection();\r\n \r\n //post request\r\n BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream());\r\n out.write(requestBarr,0,requestBarr.length);\r\n out.flush();\t\t\r\n \r\n // read result from \r\n InputStream in = conn.getInputStream();\r\n ObjectInputStream ois = new ObjectInputStream(in);\r\n result = (Collection) ois.readObject();\r\n \r\n // cleanup\r\n ois.close();\r\n out.close();\r\n conn.disconnect();\t\t\r\n }\r\n catch (Throwable t)\r\n {\r\n throw new PersistenceBrokerException(t);\r\n }\r\n return result;\r\n\t}",
"@Override\n protected void stopInner() throws VoldemortException {\n List<VoldemortException> exceptions = new ArrayList<VoldemortException>();\n\n logger.info(\"Stopping services:\" + getIdentityNode().getId());\n /* Stop in reverse order */\n exceptions.addAll(stopOnlineServices());\n for(VoldemortService service: Utils.reversed(basicServices)) {\n try {\n service.stop();\n } catch(VoldemortException e) {\n exceptions.add(e);\n logger.error(e);\n }\n }\n logger.info(\"All services stopped for Node:\" + getIdentityNode().getId());\n\n if(exceptions.size() > 0)\n throw exceptions.get(0);\n // release lock of jvm heap\n JNAUtils.tryMunlockall();\n }"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.