query
stringlengths 7
3.3k
| positive
sequencelengths 1
1
| negative
sequencelengths 9
9
|
---|---|---|
Creates multiple aliases at once. | [
"public void alias( Object ...args ) {\n if( args.length % 2 == 1 )\n throw new RuntimeException(\"Even number of arguments expected\");\n\n for (int i = 0; i < args.length; i += 2) {\n aliasGeneric( args[i], (String)args[i+1]);\n }\n }"
] | [
"private void CalculateMap(IntRange inRange, IntRange outRange, int[] map) {\r\n double k = 0, b = 0;\r\n\r\n if (inRange.getMax() != inRange.getMin()) {\r\n k = (double) (outRange.getMax() - outRange.getMin()) / (double) (inRange.getMax() - inRange.getMin());\r\n b = (double) (outRange.getMin()) - k * inRange.getMin();\r\n }\r\n\r\n for (int i = 0; i < 256; i++) {\r\n int v = (int) i;\r\n\r\n if (v >= inRange.getMax())\r\n v = outRange.getMax();\r\n else if (v <= inRange.getMin())\r\n v = outRange.getMin();\r\n else\r\n v = (int) (k * v + b);\r\n\r\n map[i] = v;\r\n }\r\n }",
"protected boolean check(String id, List<String> includes) {\n\t\tif (null != includes) {\n\t\t\tfor (String check : includes) {\n\t\t\t\tif (check(id, check)) {\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 Type getCanonicalType(Class<?> clazz) {\n if (clazz.isArray()) {\n Class<?> componentType = clazz.getComponentType();\n Type resolvedComponentType = getCanonicalType(componentType);\n if (componentType != resolvedComponentType) {\n // identity check intentional\n // a different identity means that we actually replaced the component Class with a ParameterizedType\n return new GenericArrayTypeImpl(resolvedComponentType);\n }\n }\n if (clazz.getTypeParameters().length > 0) {\n Type[] actualTypeParameters = clazz.getTypeParameters();\n return new ParameterizedTypeImpl(clazz, actualTypeParameters, clazz.getDeclaringClass());\n }\n return clazz;\n }",
"private Map<UUID, FieldType> populateCustomFieldMap()\n {\n byte[] data = m_taskProps.getByteArray(Props.CUSTOM_FIELDS);\n int length = MPPUtility.getInt(data, 0);\n int index = length + 36;\n\n // 4 byte record count\n int recordCount = MPPUtility.getInt(data, index);\n index += 4;\n\n // 8 bytes per record\n index += (8 * recordCount);\n \n Map<UUID, FieldType> map = new HashMap<UUID, FieldType>();\n while (index < data.length)\n {\n int blockLength = MPPUtility.getInt(data, index); \n if (blockLength <= 0 || index + blockLength > data.length)\n {\n break;\n }\n \n int fieldID = MPPUtility.getInt(data, index + 4);\n FieldType field = FieldTypeHelper.getInstance(fieldID);\n UUID guid = MPPUtility.getGUID(data, index + 160);\n map.put(guid, field);\n index += blockLength;\n }\n return map;\n }",
"public ItemRequest<Attachment> findById(String attachment) {\n \n String path = String.format(\"/attachments/%s\", attachment);\n return new ItemRequest<Attachment>(this, Attachment.class, path, \"GET\");\n }",
"public void revisitThrowEvents(Definitions def) {\n List<RootElement> rootElements = def.getRootElements();\n List<Signal> toAddSignals = new ArrayList<Signal>();\n Set<Error> toAddErrors = new HashSet<Error>();\n Set<Escalation> toAddEscalations = new HashSet<Escalation>();\n Set<Message> toAddMessages = new HashSet<Message>();\n Set<ItemDefinition> toAddItemDefinitions = new HashSet<ItemDefinition>();\n for (RootElement root : rootElements) {\n if (root instanceof Process) {\n setThrowEventsInfo((Process) root,\n def,\n rootElements,\n toAddSignals,\n toAddErrors,\n toAddEscalations,\n toAddMessages,\n toAddItemDefinitions);\n }\n }\n for (Lane lane : _lanes) {\n setThrowEventsInfoForLanes(lane,\n def,\n rootElements,\n toAddSignals,\n toAddErrors,\n toAddEscalations,\n toAddMessages,\n toAddItemDefinitions);\n }\n for (Signal s : toAddSignals) {\n def.getRootElements().add(s);\n }\n for (Error er : toAddErrors) {\n def.getRootElements().add(er);\n }\n for (Escalation es : toAddEscalations) {\n def.getRootElements().add(es);\n }\n for (ItemDefinition idef : toAddItemDefinitions) {\n def.getRootElements().add(idef);\n }\n for (Message msg : toAddMessages) {\n def.getRootElements().add(msg);\n }\n }",
"private void addForward(AnalyticModel model, double fixingTime, RandomVariable forward, boolean isParameter) {\n\t\tdouble interpolationEntitiyTime;\n\t\tRandomVariable interpolationEntityForwardValue;\n\t\tswitch(interpolationEntityForward) {\n\t\tcase FORWARD:\n\t\tdefault:\n\t\t\tinterpolationEntitiyTime = fixingTime;\n\t\t\tinterpolationEntityForwardValue = forward;\n\t\t\tbreak;\n\t\tcase FORWARD_TIMES_DISCOUNTFACTOR:\n\t\t\tinterpolationEntitiyTime = fixingTime;\n\t\t\tinterpolationEntityForwardValue = forward.mult(model.getDiscountCurve(getDiscountCurveName()).getValue(model, fixingTime+getPaymentOffset(fixingTime)));\n\t\t\tbreak;\n\t\tcase ZERO:\n\t\t{\n\t\t\tdouble paymentOffset = getPaymentOffset(fixingTime);\n\t\t\tinterpolationEntitiyTime = fixingTime+paymentOffset;\n\t\t\tinterpolationEntityForwardValue = forward.mult(paymentOffset).add(1.0).log().div(paymentOffset);\n\t\t\tbreak;\n\t\t}\n\t\tcase DISCOUNTFACTOR:\n\t\t{\n\t\t\tdouble paymentOffset = getPaymentOffset(fixingTime);\n\t\t\tinterpolationEntitiyTime\t\t= fixingTime+paymentOffset;\n\t\t\tinterpolationEntityForwardValue = getValue(fixingTime).div(forward.mult(paymentOffset).add(1.0));\n\t\t\tbreak;\n\t\t}\n\t\t}\n\t\tsuper.addPoint(interpolationEntitiyTime, interpolationEntityForwardValue, isParameter);\n\t}",
"public static MethodNode findSAM(ClassNode type) {\n if (!Modifier.isAbstract(type.getModifiers())) return null;\n if (type.isInterface()) {\n List<MethodNode> methods = type.getMethods();\n MethodNode found=null;\n for (MethodNode mi : methods) {\n // ignore methods, that are not abstract and from Object\n if (!Modifier.isAbstract(mi.getModifiers())) continue;\n // ignore trait methods which have a default implementation\n if (Traits.hasDefaultImplementation(mi)) continue;\n if (mi.getDeclaringClass().equals(OBJECT_TYPE)) continue;\n if (OBJECT_TYPE.getDeclaredMethod(mi.getName(), mi.getParameters())!=null) continue;\n\n // we have two methods, so no SAM\n if (found!=null) return null;\n found = mi;\n }\n return found;\n\n } else {\n\n List<MethodNode> methods = type.getAbstractMethods();\n MethodNode found = null;\n if (methods!=null) {\n for (MethodNode mi : methods) {\n if (!hasUsableImplementation(type, mi)) {\n if (found!=null) return null;\n found = mi;\n }\n }\n }\n return found;\n }\n }",
"private void updateSortedServices() {\n List<T> copiedList = new ArrayList<T>(serviceMap.values());\n sortedServices = Collections.unmodifiableList(copiedList);\n if (changeListener != null) {\n changeListener.changed();\n }\n }"
] |
directive dynamic xxx,yy
@param node
@return | [
"protected DirectiveStatement parseDirectiveStatement(DirectiveStContext node)\r\n\t{\r\n\t\tDirectiveStContext stContext = (DirectiveStContext) node;\r\n\t\tDirectiveExpContext direExp = stContext.directiveExp();\r\n\t\tToken token = direExp.Identifier().getSymbol();\r\n\t\tString directive = token.getText().toLowerCase().intern();\r\n\t\tTerminalNode value = direExp.StringLiteral();\r\n\t\tList<TerminalNode> idNodeList = null;\r\n\t\tDirectiveExpIDListContext directExpidLisCtx = direExp.directiveExpIDList();\r\n\t\tif (directExpidLisCtx != null)\r\n\t\t{\r\n\t\t\tidNodeList = directExpidLisCtx.Identifier();\r\n\t\t}\r\n\r\n\t\tSet<String> idList = null;\r\n\t\tDirectiveStatement ds = null;\r\n\r\n\t\tif (value != null)\r\n\t\t{\r\n\t\t\tString idListValue = this.getStringValue(value.getText());\r\n\t\t\tidList = new HashSet(Arrays.asList(idListValue.split(\",\")));\r\n\t\t\tds = new DirectiveStatement(directive, idList, this.getBTToken(token));\r\n\r\n\t\t}\r\n\t\telse if (idNodeList != null)\r\n\t\t{\r\n\t\t\tidList = new HashSet<String>();\r\n\t\t\tfor (TerminalNode t : idNodeList)\r\n\t\t\t{\r\n\t\t\t\tidList.add(t.getText());\r\n\t\t\t}\r\n\t\t\tds = new DirectiveStatement(directive, idList, this.getBTToken(token));\r\n\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tds = new DirectiveStatement(directive, Collections.EMPTY_SET, this.getBTToken(token));\r\n\t\t}\r\n\r\n\t\tif (directive.equals(\"dynamic\"))\r\n\t\t{\r\n\r\n\t\t\tif (ds.getIdList().size() == 0)\r\n\t\t\t{\r\n\t\t\t\tdata.allDynamic = true;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tdata.dynamicObjectSet = ds.getIdList();\r\n\t\t\t}\r\n\t\t\tds = new DirectiveStatement(directive, Collections.EMPTY_SET, this.getBTToken(token));\r\n\t\t\t\r\n\t\t\treturn ds;\r\n\r\n\t\t}\r\n\t\telse if (directive.equalsIgnoreCase(\"safe_output_open\".intern()))\r\n\t\t{\r\n\t\t\tthis.pbCtx.isSafeOutput = true;\r\n\t\t\treturn ds;\r\n\t\t}\r\n\t\telse if (directive.equalsIgnoreCase(\"safe_output_close\".intern()))\r\n\t\t{\r\n\t\t\tthis.pbCtx.isSafeOutput = false;\r\n\t\t\treturn ds;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn ds;\r\n\t\t}\r\n\t}"
] | [
"@Override\n public Collection<EnhancedAnnotatedConstructor<T>> getEnhancedConstructors(Class<? extends Annotation> annotationType) {\n Set<EnhancedAnnotatedConstructor<T>> ret = new HashSet<EnhancedAnnotatedConstructor<T>>();\n for (EnhancedAnnotatedConstructor<T> constructor : constructors) {\n if (constructor.isAnnotationPresent(annotationType)) {\n ret.add(constructor);\n }\n }\n return ret;\n }",
"static void processRoot(final File root, final ProcessedLayers layers, final LayerPathSetter setter) throws IOException {\n final LayersConfig layersConfig = LayersConfig.getLayersConfig(root);\n // Process layers\n final File layersDir = new File(root, layersConfig.getLayersPath());\n if (!layersDir.exists()) {\n if (layersConfig.isConfigured()) {\n // Bad config from user\n throw PatchLogger.ROOT_LOGGER.installationNoLayersConfigFound(layersDir.getAbsolutePath());\n }\n // else this isn't a root that has layers and add-ons\n } else {\n // check for a valid layer configuration\n for (final String layer : layersConfig.getLayers()) {\n File layerDir = new File(layersDir, layer);\n if (!layerDir.exists()) {\n if (layersConfig.isConfigured()) {\n // Bad config from user\n throw PatchLogger.ROOT_LOGGER.installationMissingLayer(layer, layersDir.getAbsolutePath());\n }\n // else this isn't a standard layers and add-ons structure\n return;\n }\n layers.addLayer(layer, layerDir, setter);\n }\n }\n // Finally process the add-ons\n final File addOnsDir = new File(root, layersConfig.getAddOnsPath());\n final File[] addOnsList = addOnsDir.listFiles();\n if (addOnsList != null) {\n for (final File addOn : addOnsList) {\n layers.addAddOn(addOn.getName(), addOn, setter);\n }\n }\n }",
"public void fireCalendarWrittenEvent(ProjectCalendar calendar)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.calendarWritten(calendar);\n }\n }\n }",
"public int size(final K1 firstKey) {\n\t\t// existence check on inner map\n\t\tfinal HashMap<K2, HashMap<K3, V>> innerMap = map.get(firstKey);\n\t\tif( innerMap == null ) {\n\t\t\treturn 0;\n\t\t}\n\t\treturn innerMap.size();\n\t}",
"@Override\n public void addVariable(String varName, Object value) {\n synchronized (mGlobalVariables) {\n mGlobalVariables.put(varName, value);\n }\n refreshGlobalBindings();\n }",
"public SparqlResult runQuery(String endpoint, String query) {\n return SparqlClient.execute(endpoint, query, username, password);\n }",
"@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 void acceptsUrl(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_U, OPT_URL), \"bootstrap url\")\n .withRequiredArg()\n .describedAs(\"url\")\n .ofType(String.class);\n }",
"private static long scanForLocSig(FileChannel channel) throws IOException {\n\n channel.position(0);\n\n ByteBuffer bb = getByteBuffer(CHUNK_SIZE);\n long end = channel.size();\n while (channel.position() <= end) {\n\n read(bb, channel);\n\n int bufferPos = 0;\n while (bufferPos <= bb.limit() - SIG_PATTERN_LENGTH) {\n\n // Following is based on the Boyer Moore algorithm but simplified to reflect\n // a) the size of the pattern is static\n // b) the pattern is static and has no repeating bytes\n\n int patternPos;\n for (patternPos = SIG_PATTERN_LENGTH - 1;\n patternPos >= 0 && LOCSIG_PATTERN[patternPos] == bb.get(bufferPos + patternPos);\n --patternPos) {\n // empty loop while bytes match\n }\n\n // Outer switch gives same results as checking the \"good suffix array\" in the Boyer Moore algorithm\n switch (patternPos) {\n case -1: {\n // Pattern matched. Confirm is this is the start of a valid local file record\n long startLocRecord = channel.position() - bb.limit() + bufferPos;\n long currentPos = channel.position();\n if (validateLocalFileRecord(channel, startLocRecord, -1)) {\n return startLocRecord;\n }\n // Restore position in case it shifted\n channel.position(currentPos);\n\n // wasn't a valid local file record; continue scan\n bufferPos += 4;\n break;\n }\n case 3: {\n // No bytes matched; the common case.\n // With our pattern, this is the only case where the Boyer Moore algorithm's \"bad char array\" may\n // produce a shift greater than the \"good suffix array\" (which would shift 1 byte)\n int idx = bb.get(bufferPos + patternPos) - Byte.MIN_VALUE;\n bufferPos += LOC_BAD_BYTE_SKIP[idx];\n break;\n }\n default:\n // 1 or more bytes matched\n bufferPos += 4;\n }\n }\n }\n\n return -1;\n }"
] |
Adds the provided map of key-value pairs as a new row in the table represented by this DataSet.
@param map the key (column-name), value pairs to add as a new row
@throws SQLException if a database error occurs | [
"public void add(Map<String, Object> map) throws SQLException {\n if (withinDataSetBatch) {\n if (batchData.size() == 0) {\n batchKeys = map.keySet();\n } else {\n if (!map.keySet().equals(batchKeys)) {\n throw new IllegalArgumentException(\"Inconsistent keys found for batch add!\");\n }\n }\n batchData.add(map);\n return;\n }\n int answer = executeUpdate(buildListQuery(map), new ArrayList<Object>(map.values()));\n if (answer != 1) {\n LOG.warning(\"Should have updated 1 row not \" + answer + \" when trying to add: \" + map);\n }\n }"
] | [
"public Iterator getAllExtentClasses()\r\n {\r\n ArrayList subTypes = new ArrayList();\r\n\r\n subTypes.addAll(_extents);\r\n\r\n for (int idx = 0; idx < subTypes.size(); idx++)\r\n {\r\n ClassDescriptorDef curClassDef = (ClassDescriptorDef)subTypes.get(idx);\r\n\r\n for (Iterator it = curClassDef.getExtentClasses(); it.hasNext();)\r\n {\r\n ClassDescriptorDef curSubTypeDef = (ClassDescriptorDef)it.next();\r\n\r\n if (!subTypes.contains(curSubTypeDef))\r\n {\r\n subTypes.add(curSubTypeDef);\r\n }\r\n }\r\n }\r\n return subTypes.iterator();\r\n }",
"public void setIsSeries(Boolean isSeries) {\r\n\r\n if (null != isSeries) {\r\n final boolean series = isSeries.booleanValue();\r\n if ((null != m_model.getParentSeriesId()) && series) {\r\n m_removeSeriesBindingConfirmDialog.show(new Command() {\r\n\r\n public void execute() {\r\n\r\n m_model.setParentSeriesId(null);\r\n setPattern(PatternType.DAILY.toString());\r\n\r\n }\r\n });\r\n } else {\r\n setPattern(series ? PatternType.DAILY.toString() : PatternType.NONE.toString());\r\n }\r\n }\r\n }",
"public boolean isServerAvailable(){\n final Client client = getClient();\n final ClientResponse response = client.resource(serverURL).get(ClientResponse.class);\n\n if(ClientResponse.Status.OK.getStatusCode() == response.getStatus()){\n return true;\n }\n\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, \"Failed to reach the targeted Grapes server\", response.getStatus()));\n }\n client.destroy();\n\n return false;\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<EthiopicDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<EthiopicDate>) super.localDateTime(temporal);\n }",
"public void setCustomRequest(int pathId, String customRequest, String clientUUID) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n int profileId = EditService.getProfileIdFromPathID(pathId);\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_REQUEST_RESPONSE +\n \" SET \" + Constants.REQUEST_RESPONSE_CUSTOM_REQUEST + \"= ?\" +\n \" WHERE \" + Constants.GENERIC_PROFILE_ID + \"= ?\" +\n \" AND \" + Constants.GENERIC_CLIENT_UUID + \"= ?\" +\n \" AND \" + Constants.REQUEST_RESPONSE_PATH_ID + \"= ?\"\n );\n statement.setString(1, customRequest);\n statement.setInt(2, profileId);\n statement.setString(3, clientUUID);\n statement.setInt(4, pathId);\n statement.executeUpdate();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }",
"private Object getConstantValue(FieldType type, byte[] block)\n {\n Object value;\n DataType dataType = type.getDataType();\n\n if (dataType == null)\n {\n value = null;\n }\n else\n {\n switch (dataType)\n {\n case DURATION:\n {\n value = MPPUtility.getAdjustedDuration(m_properties, MPPUtility.getInt(block, getValueOffset()), MPPUtility.getDurationTimeUnits(MPPUtility.getShort(block, getTimeUnitsOffset())));\n break;\n }\n\n case NUMERIC:\n {\n value = Double.valueOf(MPPUtility.getDouble(block, getValueOffset()));\n break;\n }\n\n case PERCENTAGE:\n {\n value = Double.valueOf(MPPUtility.getShort(block, getValueOffset()));\n break;\n }\n\n case CURRENCY:\n {\n value = Double.valueOf(MPPUtility.getDouble(block, getValueOffset()) / 100);\n break;\n }\n\n case STRING:\n {\n int textOffset = getTextOffset(block);\n value = MPPUtility.getUnicodeString(m_criteriaData, m_dataOffset + m_criteriaTextStart + textOffset);\n break;\n }\n\n case BOOLEAN:\n {\n int intValue = MPPUtility.getShort(block, getValueOffset());\n value = (intValue == 1 ? Boolean.TRUE : Boolean.FALSE);\n break;\n }\n\n case DATE:\n {\n value = MPPUtility.getTimestamp(block, getValueOffset());\n break;\n }\n\n default:\n {\n value = null;\n break;\n }\n }\n }\n\n return value;\n }",
"public final Object getValue(final String id, final String property) {\n final CriteriaBuilder builder = getSession().getCriteriaBuilder();\n final CriteriaQuery<Object> criteria = builder.createQuery(Object.class);\n final Root<PrintJobStatusExtImpl> root = criteria.from(PrintJobStatusExtImpl.class);\n criteria.select(root.get(property));\n criteria.where(builder.equal(root.get(\"referenceId\"), id));\n return getSession().createQuery(criteria).uniqueResult();\n }",
"public String getCanonicalTypeName(Object object) {\n ensureNotNull(\"object\", object);\n\n for (TypeDetector typeDetector : typeDetectors) {\n if (typeDetector.canHandle(object)) {\n return typeDetector.detectType(object);\n }\n }\n\n throw LOG.unableToDetectCanonicalType(object);\n }",
"private static ClassLoader getParentCl()\n {\n try\n {\n Method m = ClassLoader.class.getMethod(\"getPlatformClassLoader\");\n return (ClassLoader) m.invoke(null);\n }\n catch (NoSuchMethodException e)\n {\n // Java < 9, just use the bootstrap CL.\n return null;\n }\n catch (Exception e)\n {\n throw new JqmInitError(\"Could not fetch Platform Class Loader\", e);\n }\n }"
] |
Attempts to revert the working copy. In case of failure it just logs the error. | [
"public void safeRevertWorkingCopy() {\n try {\n revertWorkingCopy();\n } catch (Exception e) {\n debuggingLogger.log(Level.FINE, \"Failed to revert working copy\", e);\n log(\"Failed to revert working copy: \" + e.getLocalizedMessage());\n Throwable cause = e.getCause();\n if (!(cause instanceof SVNException)) {\n return;\n }\n SVNException svnException = (SVNException) cause;\n if (svnException.getErrorMessage().getErrorCode() == SVNErrorCode.WC_LOCKED) {\n // work space locked attempt cleanup and try to revert again\n try {\n cleanupWorkingCopy();\n } catch (Exception unlockException) {\n debuggingLogger.log(Level.FINE, \"Failed to cleanup working copy\", e);\n log(\"Failed to cleanup working copy: \" + e.getLocalizedMessage());\n return;\n }\n\n try {\n revertWorkingCopy();\n } catch (Exception revertException) {\n log(\"Failed to revert working copy on the 2nd attempt: \" + e.getLocalizedMessage());\n }\n }\n }\n }"
] | [
"public static base_response delete(nitro_service client, String fipskeyname) throws Exception {\n\t\tsslfipskey deleteresource = new sslfipskey();\n\t\tdeleteresource.fipskeyname = fipskeyname;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"private void throwOrWarnAboutDescriptorProblem(String message) {\n if (validateDescriptions) {\n throw new IllegalArgumentException(message);\n }\n ControllerLogger.ROOT_LOGGER.warn(message);\n }",
"public static int count(CharSequence self, CharSequence text) {\n int answer = 0;\n for (int idx = 0; true; idx++) {\n idx = self.toString().indexOf(text.toString(), idx);\n // break once idx goes to -1 or for case of empty string once\n // we get to the end to avoid JDK library bug (see GROOVY-5858)\n if (idx < answer) break;\n ++answer;\n }\n return answer;\n }",
"private GraphicsDocument createLabelDocument(StringWriter writer, LabelStyleInfo labelStyleInfo)\n\t\t\tthrows RenderException {\n\n\t\tif (TileMetadata.PARAM_SVG_RENDERER.equalsIgnoreCase(renderer)) {\n\t\t\tDefaultSvgDocument document = new DefaultSvgDocument(writer, false);\n\t\t\tdocument.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS);\n\t\t\tdocument.registerWriter(InternalTileImpl.class, new SvgLabelTileWriter(getTransformer(), labelStyleInfo,\n\t\t\t\t\tgeoService, textService));\n\t\t\treturn document;\n\t\t} else if (TileMetadata.PARAM_VML_RENDERER.equalsIgnoreCase(renderer)) {\n\t\t\tDefaultVmlDocument document = new DefaultVmlDocument(writer);\n\t\t\tint coordWidth = tile.getScreenWidth();\n\t\t\tint coordHeight = tile.getScreenHeight();\n\t\t\tdocument.registerWriter(InternalFeatureImpl.class, new VmlFeatureWriter(getTransformer(), coordWidth,\n\t\t\t\t\tcoordHeight));\n\t\t\tdocument.registerWriter(InternalTileImpl.class, new VmlLabelTileWriter(coordWidth, coordHeight,\n\t\t\t\t\tgetTransformer(), labelStyleInfo, geoService, textService));\n\t\t\tdocument.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS);\n\t\t\treturn document;\n\t\t} else {\n\t\t\tthrow new RenderException(ExceptionCode.RENDERER_TYPE_NOT_SUPPORTED, renderer);\n\t\t}\n\t}",
"protected static void statistics(int from, int to) {\r\n\t// check that primes contain no accidental errors\r\n\tfor (int i=0; i<primeCapacities.length-1; i++) {\r\n\t\tif (primeCapacities[i] >= primeCapacities[i+1]) throw new RuntimeException(\"primes are unsorted or contain duplicates; detected at \"+i+\"@\"+primeCapacities[i]);\r\n\t}\r\n\t\r\n\tdouble accDeviation = 0.0;\r\n\tdouble maxDeviation = - 1.0;\r\n\r\n\tfor (int i=from; i<=to; i++) {\r\n\t\tint primeCapacity = nextPrime(i);\r\n\t\t//System.out.println(primeCapacity);\r\n\t\tdouble deviation = (primeCapacity - i) / (double)i;\r\n\t\t\r\n\t\tif (deviation > maxDeviation) {\r\n\t\t\tmaxDeviation = deviation;\r\n\t\t\tSystem.out.println(\"new maxdev @\"+i+\"@dev=\"+maxDeviation);\r\n\t\t}\r\n\r\n\t\taccDeviation += deviation;\r\n\t}\r\n\tlong width = 1 + (long)to - (long)from;\r\n\t\r\n\tdouble meanDeviation = accDeviation/width;\r\n\tSystem.out.println(\"Statistics for [\"+ from + \",\"+to+\"] are as follows\");\r\n\tSystem.out.println(\"meanDeviation = \"+(float)meanDeviation*100+\" %\");\r\n\tSystem.out.println(\"maxDeviation = \"+(float)maxDeviation*100+\" %\");\r\n}",
"@UiThread\n protected void parentExpandedFromViewHolder(int flatParentPosition) {\n ExpandableWrapper<P, C> parentWrapper = mFlatItemList.get(flatParentPosition);\n updateExpandedParent(parentWrapper, flatParentPosition, true);\n }",
"public static FullTypeSignature getTypeSignature(Class<?> clazz, Class<?>[] typeArgs) {\n\t\tClassTypeSignature rawClassTypeSignature = (ClassTypeSignature) javaTypeToTypeSignature\n\t\t\t\t.getTypeSignature(clazz);\n\t\tTypeArgSignature[] typeArgSignatures = new TypeArgSignature[typeArgs.length];\n\t\tfor (int i = 0; i < typeArgs.length; i++) {\n\t\t\ttypeArgSignatures[i] = new TypeArgSignature(\n\t\t\t\t\tTypeArgSignature.NO_WILDCARD,\n\t\t\t\t\t(FieldTypeSignature) javaTypeToTypeSignature\n\t\t\t\t\t\t\t.getTypeSignature(typeArgs[i]));\n\t\t}\n\t\tClassTypeSignature classTypeSignature = new ClassTypeSignature(\n\t\t\t\trawClassTypeSignature.getBinaryName(), typeArgSignatures,\n\t\t\t\trawClassTypeSignature.getOwnerTypeSignature());\n\n\t\treturn classTypeSignature;\n\t}",
"public BoxComment.Info reply(String message) {\n JsonObject itemJSON = new JsonObject();\n itemJSON.add(\"type\", \"comment\");\n itemJSON.add(\"id\", this.getID());\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"item\", itemJSON);\n if (BoxComment.messageContainsMention(message)) {\n requestJSON.add(\"tagged_message\", message);\n } else {\n requestJSON.add(\"message\", message);\n }\n\n URL url = ADD_COMMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxComment addedComment = new BoxComment(this.getAPI(), responseJSON.get(\"id\").asString());\n return addedComment.new Info(responseJSON);\n }",
"public static ComplexNumber Subtract(ComplexNumber z1, ComplexNumber z2) {\r\n return new ComplexNumber(z1.real - z2.real, z1.imaginary - z2.imaginary);\r\n }"
] |
Use this API to rename a responderpolicy resource. | [
"public static base_response rename(nitro_service client, responderpolicy resource, String new_name) throws Exception {\n\t\tresponderpolicy renameresource = new responderpolicy();\n\t\trenameresource.name = resource.name;\n\t\treturn renameresource.rename_resource(client,new_name);\n\t}"
] | [
"@Override\n public void begin(String namespace, String name, Attributes attributes) throws Exception {\n\n // not now: 6.0.0\n // digester.setLogger(CmsLog.getLog(digester.getClass()));\n\n // Push an array to capture the parameter values if necessary\n if (m_paramCount > 0) {\n Object[] parameters = new Object[m_paramCount];\n for (int i = 0; i < parameters.length; i++) {\n parameters[i] = null;\n }\n getDigester().pushParams(parameters);\n }\n }",
"public static Object setProperty( String key, String value ) {\n return prp.setProperty( key, value );\n }",
"public void commandLoop() throws IOException {\n for (Object handler : allHandlers) {\n if (handler instanceof ShellManageable) {\n ((ShellManageable)handler).cliEnterLoop();\n }\n }\n output.output(appName, outputConverter);\n String command = \"\";\n while (true) {\n try {\n command = input.readCommand(path);\n if (command.trim().equals(\"exit\")) {\n if (lineProcessor == null)\n break;\n else {\n path = savedPath;\n lineProcessor = null;\n }\n }\n\n processLine(command);\n } catch (TokenException te) {\n lastException = te;\n output.outputException(command, te);\n } catch (CLIException clie) {\n lastException = clie;\n if (!command.trim().equals(\"exit\")) {\n output.outputException(clie);\n }\n }\n }\n for (Object handler : allHandlers) {\n if (handler instanceof ShellManageable) {\n ((ShellManageable)handler).cliLeaveLoop();\n }\n }\n }",
"public static RgbaColor fromHex(String hex) {\n if (hex.length() == 0 || hex.charAt(0) != '#') return getDefaultColor();\n\n // #rgb\n if (hex.length() == 4) {\n\n return new RgbaColor(parseHex(hex, 1, 2),\n parseHex(hex, 2, 3),\n parseHex(hex, 3, 4));\n\n }\n // #rrggbb\n else if (hex.length() == 7) {\n\n return new RgbaColor(parseHex(hex, 1, 3),\n parseHex(hex, 3, 5),\n parseHex(hex, 5, 7));\n\n }\n else {\n return getDefaultColor();\n }\n }",
"public static Object parsePrimitive(\n final String fieldName, final PrimitiveAttribute<?> pAtt, final PObject requestData) {\n Class<?> valueClass = pAtt.getValueClass();\n Object value;\n try {\n value = parseValue(false, new String[0], valueClass, fieldName, requestData);\n } catch (UnsupportedTypeException e) {\n String type = e.type.getName();\n if (e.type.isArray()) {\n type = e.type.getComponentType().getName() + \"[]\";\n }\n throw new RuntimeException(\n \"The type '\" + type + \"' is not a supported type when parsing json. \" +\n \"See documentation for supported types.\\n\\nUnsupported type found in attribute \" +\n fieldName\n + \"\\n\\nTo support more types add the type to \" +\n \"parseValue and parseArrayValue in this class and add a test to the test class\",\n e);\n }\n pAtt.validateValue(value);\n\n return value;\n }",
"public static boolean streamHasText(InputStream in, String text) {\n final byte[] readBuffer = new byte[8192];\n\n StringBuffer sb = new StringBuffer();\n try {\n if (in.available() > 0) {\n int bytesRead = 0;\n while ((bytesRead = in.read(readBuffer)) != -1) {\n sb.append(new String(readBuffer, 0, bytesRead));\n\n if (sb.toString().contains(text)) {\n sb = null;\n return true;\n }\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n in.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n return false;\n }",
"public void setWorkConnection(CmsSetupDb db) {\n\n db.setConnection(\n m_setupBean.getDbDriver(),\n m_setupBean.getDbWorkConStr(),\n m_setupBean.getDbConStrParams(),\n m_setupBean.getDbWorkUser(),\n m_setupBean.getDbWorkPwd());\n }",
"public void close() throws IOException {\n\t\tSystem.out.println(\"Serialized \"\n\t\t\t\t+ this.jsonSerializer.getEntityDocumentCount()\n\t\t\t\t+ \" item documents to JSON file \" + OUTPUT_FILE_NAME + \".\");\n\t\tthis.jsonSerializer.close();\n\t}",
"@Override\n\tpublic void visit(Rule rule) {\n\t\tRule copy = null;\n\t\tFilter filterCopy = null;\n\n\t\tif (rule.getFilter() != null) {\n\t\t\tFilter filter = rule.getFilter();\n\t\t\tfilterCopy = copy(filter);\n\t\t}\n\n\t\tList<Symbolizer> symsCopy = new ArrayList<Symbolizer>();\n\t\tfor (Symbolizer sym : rule.symbolizers()) {\n\t\t\tif (!skipSymbolizer(sym)) {\n\t\t\t\tSymbolizer symCopy = copy(sym);\n\t\t\t\tsymsCopy.add(symCopy);\n\t\t\t}\n\t\t}\n\n\t\tGraphic[] legendCopy = rule.getLegendGraphic();\n\t\tfor (int i = 0; i < legendCopy.length; i++) {\n\t\t\tlegendCopy[i] = copy(legendCopy[i]);\n\t\t}\n\n\t\tDescription descCopy = rule.getDescription();\n\t\tdescCopy = copy(descCopy);\n\n\t\tcopy = sf.createRule();\n\t\tcopy.symbolizers().addAll(symsCopy);\n\t\tcopy.setDescription(descCopy);\n\t\tcopy.setLegendGraphic(legendCopy);\n\t\tcopy.setName(rule.getName());\n\t\tcopy.setFilter(filterCopy);\n\t\tcopy.setElseFilter(rule.isElseFilter());\n\t\tcopy.setMaxScaleDenominator(rule.getMaxScaleDenominator());\n\t\tcopy.setMinScaleDenominator(rule.getMinScaleDenominator());\n\n\t\tif (STRICT && !copy.equals(rule)) {\n\t\t\tthrow new IllegalStateException(\n\t\t\t\t\t\"Was unable to duplicate provided Rule:\" + rule);\n\t\t}\n\t\tpages.push(copy);\n\t}"
] |
Copy a path recursively.
@param source a Path pointing to a file or a directory that must exist
@param target a Path pointing to a directory where the contents will be copied.
@param overwrite overwrite existing files - if set to false fails if the target file already exists.
@throws IOException | [
"public static void copyRecursively(final Path source, final Path target, boolean overwrite) throws IOException {\n final CopyOption[] options;\n if (overwrite) {\n options = new CopyOption[]{StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING};\n } else {\n options = new CopyOption[]{StandardCopyOption.COPY_ATTRIBUTES};\n }\n Files.walkFileTree(source, new FileVisitor<Path>() {\n @Override\n public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {\n Files.copy(dir, target.resolve(source.relativize(dir)), options);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n Files.copy(file, target.resolve(source.relativize(file)), options);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {\n DeploymentRepositoryLogger.ROOT_LOGGER.cannotCopyFile(exc, file);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {\n return FileVisitResult.CONTINUE;\n }\n });\n }"
] | [
"private void processCurrency(Row row)\n {\n String currencyName = row.getString(\"curr_short_name\");\n DecimalFormatSymbols symbols = new DecimalFormatSymbols();\n symbols.setDecimalSeparator(row.getString(\"decimal_symbol\").charAt(0));\n symbols.setGroupingSeparator(row.getString(\"digit_group_symbol\").charAt(0));\n DecimalFormat nf = new DecimalFormat();\n nf.setDecimalFormatSymbols(symbols);\n nf.applyPattern(\"#.#\");\n m_currencyMap.put(currencyName, nf);\n\n if (currencyName.equalsIgnoreCase(m_defaultCurrencyName))\n {\n m_numberFormat = nf;\n m_defaultCurrencyData = row;\n }\n }",
"private Component createMainComponent() throws IOException, CmsException {\n\n VerticalLayout mainComponent = new VerticalLayout();\n mainComponent.setSizeFull();\n mainComponent.addStyleName(\"o-message-bundle-editor\");\n m_table = createTable();\n Panel navigator = new Panel();\n navigator.setSizeFull();\n navigator.setContent(m_table);\n navigator.addActionHandler(new CmsMessageBundleEditorTypes.TableKeyboardHandler(m_table));\n navigator.addStyleName(\"v-panel-borderless\");\n\n mainComponent.addComponent(m_options.getOptionsComponent());\n mainComponent.addComponent(navigator);\n mainComponent.setExpandRatio(navigator, 1f);\n m_options.updateShownOptions(m_model.hasMasterMode(), m_model.canAddKeys());\n return mainComponent;\n }",
"public static void endThreads(String check){\r\n //(error check)\r\n if(currentThread != -1L){\r\n throw new IllegalStateException(\"endThreads() called, but thread \" + currentThread + \" has not finished (exception in thread?)\");\r\n }\r\n //(end threaded environment)\r\n assert !control.isHeldByCurrentThread();\r\n isThreaded = false;\r\n //(write remaining threads)\r\n boolean cleanPass = false;\r\n while(!cleanPass){\r\n cleanPass = true;\r\n for(long thread : threadedLogQueue.keySet()){\r\n assert currentThread < 0L;\r\n if(threadedLogQueue.get(thread) != null && !threadedLogQueue.get(thread).isEmpty()){\r\n //(mark queue as unclean)\r\n cleanPass = false;\r\n //(variables)\r\n Queue<Runnable> backlog = threadedLogQueue.get(thread);\r\n currentThread = thread;\r\n //(clear buffer)\r\n while(currentThread >= 0){\r\n if(currentThread != thread){ throw new IllegalStateException(\"Redwood control shifted away from flushing thread\"); }\r\n if(backlog.isEmpty()){ throw new IllegalStateException(\"Forgot to call finishThread() on thread \" + currentThread); }\r\n assert !control.isHeldByCurrentThread();\r\n backlog.poll().run();\r\n }\r\n //(unregister thread)\r\n threadsWaiting.remove(thread);\r\n }\r\n }\r\n }\r\n while(threadsWaiting.size() > 0){\r\n assert currentThread < 0L;\r\n assert control.tryLock();\r\n assert !threadsWaiting.isEmpty();\r\n control.lock();\r\n attemptThreadControlThreadsafe(-1);\r\n control.unlock();\r\n }\r\n //(clean up)\r\n for(long threadId : threadedLogQueue.keySet()){\r\n assert threadedLogQueue.get(threadId).isEmpty();\r\n }\r\n assert threadsWaiting.isEmpty();\r\n assert currentThread == -1L;\r\n endTrack(\"Threads( \"+check+\" )\");\r\n }",
"public String getFormattedParentValue()\n {\n String result = null;\n if (m_elements.size() > 2)\n {\n result = joinElements(m_elements.size() - 2);\n }\n return result;\n }",
"public Set<BsonValue> getPausedDocumentIds(final MongoNamespace namespace) {\n this.waitUntilInitialized();\n\n try {\n ongoingOperationsGroup.enter();\n final Set<BsonValue> pausedDocumentIds = new HashSet<>();\n\n for (final CoreDocumentSynchronizationConfig config :\n this.syncConfig.getSynchronizedDocuments(namespace)) {\n if (config.isPaused()) {\n pausedDocumentIds.add(config.getDocumentId());\n }\n }\n\n return pausedDocumentIds;\n } finally {\n ongoingOperationsGroup.exit();\n }\n }",
"public ItemRequest<Project> findById(String project) {\n \n String path = String.format(\"/projects/%s\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"GET\");\n }",
"public int getIndexFromOffset(int offset)\n {\n int result = -1;\n\n for (int loop = 0; loop < m_offset.length; loop++)\n {\n if (m_offset[loop] == offset)\n {\n result = loop;\n break;\n }\n }\n\n return (result);\n }",
"public Long getLong(String fieldName) {\n\t\ttry {\n\t\t\treturn hasValue(fieldName) ? Long.valueOf(String.valueOf(resultMap.get(fieldName))) : null;\n\t\t} catch (NumberFormatException e) {\n\t\t\tthrow new FqlException(\"Field '\" + fieldName +\"' is not a number.\", e);\n\t\t}\n\t}",
"public PlacesList<Place> placesForUser(int placeType, String woeId, String placeId, String threshold, Date minUploadDate, Date maxUploadDate,\r\n Date minTakenDate, Date maxTakenDate) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n PlacesList<Place> placesList = new PlacesList<Place>();\r\n parameters.put(\"method\", METHOD_PLACES_FOR_USER);\r\n\r\n parameters.put(\"place_type\", intPlaceTypeToString(placeType));\r\n if (placeId != null) {\r\n parameters.put(\"place_id\", placeId);\r\n }\r\n if (woeId != null) {\r\n parameters.put(\"woe_id\", woeId);\r\n }\r\n if (threshold != null) {\r\n parameters.put(\"threshold\", threshold);\r\n }\r\n if (minUploadDate != null) {\r\n parameters.put(\"min_upload_date\", Long.toString(minUploadDate.getTime() / 1000L));\r\n }\r\n if (maxUploadDate != null) {\r\n parameters.put(\"max_upload_date\", Long.toString(maxUploadDate.getTime() / 1000L));\r\n }\r\n if (minTakenDate != null) {\r\n parameters.put(\"min_taken_date\", ((DateFormat) SearchParameters.MYSQL_DATE_FORMATS.get()).format(minTakenDate));\r\n }\r\n if (maxTakenDate != null) {\r\n parameters.put(\"max_taken_date\", ((DateFormat) SearchParameters.MYSQL_DATE_FORMATS.get()).format(maxTakenDate));\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element placesElement = response.getPayload();\r\n NodeList placesNodes = placesElement.getElementsByTagName(\"place\");\r\n placesList.setPage(\"1\");\r\n placesList.setPages(\"1\");\r\n placesList.setPerPage(\"\" + placesNodes.getLength());\r\n placesList.setTotal(\"\" + placesNodes.getLength());\r\n for (int i = 0; i < placesNodes.getLength(); i++) {\r\n Element placeElement = (Element) placesNodes.item(i);\r\n placesList.add(parsePlace(placeElement));\r\n }\r\n return placesList;\r\n }"
] |
Create an info object from a uri and the http method object.
@param uri the uri
@param method the method | [
"public static MatchInfo fromUri(final URI uri, final HttpMethod method) {\n int newPort = uri.getPort();\n if (newPort < 0) {\n try {\n newPort = uri.toURL().getDefaultPort();\n } catch (MalformedURLException | IllegalArgumentException e) {\n newPort = ANY_PORT;\n }\n }\n\n return new MatchInfo(uri.getScheme(), uri.getHost(), newPort, uri.getPath(), uri.getQuery(),\n uri.getFragment(), ANY_REALM, method);\n }"
] | [
"public static String get(MessageKey key) {\n return data.getProperty(key.toString(), key.toString());\n }",
"public static String format(String pattern, Object... arguments) {\n String msg = pattern;\n if (arguments != null) {\n for (int index = 0; index < arguments.length; index++) {\n msg = msg.replaceAll(\"\\\\{\" + (index + 1) + \"\\\\}\", String.valueOf(arguments[index]));\n }\n }\n return msg;\n }",
"public String convertToReadableDate(Holiday holiday) {\n DateTimeFormatter parser = ISODateTimeFormat.date();\n\n if (holiday.isInDateForm()) {\n String month = Integer.toString(holiday.getMonth()).length() < 2\n ? \"0\" + holiday.getMonth() : Integer.toString(holiday.getMonth());\n String day = Integer.toString(holiday.getDayOfMonth()).length() < 2\n ? \"0\" + holiday.getDayOfMonth() : Integer.toString(holiday.getDayOfMonth());\n return holiday.getYear() + \"-\" + month + \"-\" + day;\n } else {\n /*\n * 5 denotes the final occurrence of the day in the month. Need to find actual\n * number of occurrences\n */\n if (holiday.getOccurrence() == 5) {\n holiday.setOccurrence(numOccurrences(holiday.getYear(), holiday.getMonth(),\n holiday.getDayOfWeek()));\n }\n\n DateTime date = parser.parseDateTime(holiday.getYear() + \"-\"\n + holiday.getMonth() + \"-\" + \"01\");\n Calendar calendar = Calendar.getInstance();\n calendar.setTime(date.toDate());\n int count = 0;\n\n while (count < holiday.getOccurrence()) {\n if (calendar.get(Calendar.DAY_OF_WEEK) == holiday.getDayOfWeek()) {\n count++;\n if (count == holiday.getOccurrence()) {\n break;\n }\n }\n date = date.plusDays(1);\n calendar.setTime(date.toDate());\n }\n return date.toString().substring(0, 10);\n }\n }",
"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 RelationType getRelationType(Integer gpType)\n {\n RelationType result = null;\n if (gpType != null)\n {\n int index = NumberHelper.getInt(gpType);\n if (index > 0 && index < RELATION.length)\n {\n result = RELATION[index];\n }\n }\n\n if (result == null)\n {\n result = RelationType.FINISH_START;\n }\n\n return result;\n }",
"public static Shell createSubshell(String pathElement, Shell parent, String appName, Object mainHandler,\n MultiMap<String, Object> auxHandlers) {\n\n List<String> newPath = new ArrayList<String>(parent.getPath());\n newPath.add(pathElement);\n\n Shell subshell = new Shell(parent.getSettings().createWithAddedAuxHandlers(auxHandlers),\n new CommandTable(parent.getCommandTable().getNamer()), newPath);\n\n subshell.setAppName(appName);\n subshell.addMainHandler(subshell, \"!\");\n subshell.addMainHandler(new HelpCommandHandler(), \"?\");\n\n subshell.addMainHandler(mainHandler, \"\");\n return subshell;\n }",
"public WaveformDetail requestWaveformDetailFrom(final DataReference dataReference) {\n ensureRunning();\n for (WaveformDetail cached : detailHotCache.values()) {\n if (cached.dataReference.equals(dataReference)) { // Found a hot cue hit, use it.\n return cached;\n }\n }\n return requestDetailInternal(dataReference, false);\n }",
"public static appfwprofile_denyurl_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_denyurl_binding obj = new appfwprofile_denyurl_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_denyurl_binding response[] = (appfwprofile_denyurl_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public Widget findChildByName(final String name) {\n final List<Widget> groups = new ArrayList<>();\n groups.add(this);\n\n return findChildByNameInAllGroups(name, groups);\n }"
] |
format with lazy-eval | [
"public static Object formatL(final String template, final Object... args) {\n return new Object() {\n @Override\n public String toString() {\n return format(template, args);\n }\n };\n }"
] | [
"public static authenticationlocalpolicy_authenticationvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationlocalpolicy_authenticationvserver_binding obj = new authenticationlocalpolicy_authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationlocalpolicy_authenticationvserver_binding response[] = (authenticationlocalpolicy_authenticationvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static 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 }",
"public Weld addBeanDefiningAnnotations(Class<? extends Annotation>... annotations) {\n for (Class<? extends Annotation> annotation : annotations) {\n this.extendedBeanDefiningAnnotations.add(annotation);\n }\n return this;\n }",
"public Optional<URL> getRoute() {\n Optional<Route> optionalRoute = getClient().routes().inNamespace(namespace)\n .list().getItems()\n .stream()\n .findFirst();\n\n return optionalRoute\n .map(OpenShiftRouteLocator::createUrlFromRoute);\n }",
"public Set<Action.ActionEffect> getActionEffects() {\n switch(getImpact()) {\n case CLASSLOADING:\n case WRITE:\n return WRITES;\n case READ_ONLY:\n return READS;\n default:\n throw new IllegalStateException();\n }\n\n }",
"public Excerpt typeParameters() {\n if (getTypeParameters().isEmpty()) {\n return Excerpts.EMPTY;\n } else {\n return Excerpts.add(\"<%s>\", Excerpts.join(\", \", getTypeParameters()));\n }\n }",
"public Metadata createMetadata(String typeName, Metadata metadata) {\n String scope = Metadata.scopeBasedOnType(typeName);\n return this.createMetadata(typeName, scope, metadata);\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 }",
"void pumpEvents(InputStream eventStream) {\n try {\n Deserializer deserializer = new Deserializer(eventStream, refLoader);\n\n IEvent event = null;\n while ((event = deserializer.deserialize()) != null) {\n switch (event.getType()) {\n case APPEND_STDERR:\n case APPEND_STDOUT:\n // Ignore these two on activity heartbeats. GH-117\n break;\n default:\n lastActivity = System.currentTimeMillis();\n break;\n }\n\n try {\n switch (event.getType()) {\n case QUIT:\n eventBus.post(event);\n return;\n\n case IDLE:\n eventBus.post(new SlaveIdle(stdinWriter));\n break;\n\n case BOOTSTRAP:\n clientCharset = Charset.forName(((BootstrapEvent) event).getDefaultCharsetName());\n stdinWriter = new OutputStreamWriter(stdin, clientCharset);\n eventBus.post(event);\n break;\n\n case APPEND_STDERR:\n case APPEND_STDOUT:\n assert streamsBuffer.getFilePointer() == streamsBuffer.length();\n final long bufferStart = streamsBuffer.getFilePointer();\n IStreamEvent streamEvent = (IStreamEvent) event;\n streamEvent.copyTo(streamsBufferWrapper);\n final long bufferEnd = streamsBuffer.getFilePointer();\n\n event = new OnDiskStreamEvent(event.getType(), streamsBuffer, bufferStart, bufferEnd);\n eventBus.post(event);\n break;\n \n default:\n eventBus.post(event);\n }\n } catch (Throwable t) {\n warnStream.println(\"Event bus dispatch error: \" + t.toString());\n t.printStackTrace(warnStream);\n }\n }\n lastActivity = null;\n } catch (Throwable e) {\n if (!stopping) {\n warnStream.println(\"Event stream error: \" + e.toString());\n e.printStackTrace(warnStream);\n }\n }\n }"
] |
Computes the cross product of v1 and v2 and places the result in this
vector.
@param v1
left-hand vector
@param v2
right-hand vector | [
"public void cross(Vector3d v1, Vector3d v2) {\n double tmpx = v1.y * v2.z - v1.z * v2.y;\n double tmpy = v1.z * v2.x - v1.x * v2.z;\n double tmpz = v1.x * v2.y - v1.y * v2.x;\n\n x = tmpx;\n y = tmpy;\n z = tmpz;\n }"
] | [
"protected ViewPort load() {\n resize = Window.addResizeHandler(event -> {\n execute(event.getWidth(), event.getHeight());\n });\n\n execute(window().width(), (int)window().height());\n return viewPort;\n }",
"private String getActivityID(Task task)\n {\n String result = null;\n if (m_activityIDField != null)\n {\n Object value = task.getCachedValue(m_activityIDField);\n if (value != null)\n {\n result = value.toString();\n }\n }\n return result;\n }",
"public static final String printExtendedAttributeCurrency(Number value)\n {\n return (value == null ? null : NUMBER_FORMAT.get().format(value.doubleValue() * 100));\n }",
"private Filter getFilter(String layerFilter, String[] featureIds) throws GeomajasException {\n\t\tFilter filter = null;\n\t\tif (null != layerFilter) {\n\t\t\tfilter = filterService.parseFilter(layerFilter);\n\t\t}\n\t\tif (null != featureIds) {\n\t\t\tFilter fidFilter = filterService.createFidFilter(featureIds);\n\t\t\tif (null == filter) {\n\t\t\t\tfilter = fidFilter;\n\t\t\t} else {\n\t\t\t\tfilter = filterService.createAndFilter(filter, fidFilter);\n\t\t\t}\n\t\t}\n\t\treturn filter;\n\t}",
"public static boolean isFinalVariable(DeclarationExpression declarationExpression, SourceCode sourceCode) {\r\n if (isFromGeneratedSourceCode(declarationExpression)) {\r\n return false;\r\n }\r\n List<Expression> variableExpressions = getVariableExpressions(declarationExpression);\r\n if (!variableExpressions.isEmpty()) {\r\n Expression variableExpression = variableExpressions.get(0);\r\n int startOfDeclaration = declarationExpression.getColumnNumber();\r\n int startOfVariableName = variableExpression.getColumnNumber();\r\n int sourceLineNumber = findFirstNonAnnotationLine(declarationExpression, sourceCode);\r\n String sourceLine = sourceCode.getLines().get(sourceLineNumber-1);\r\n\r\n String modifiers = (startOfDeclaration >= 0 && startOfVariableName >= 0 && sourceLine.length() >= startOfVariableName) ?\r\n sourceLine.substring(startOfDeclaration - 1, startOfVariableName - 1) : \"\";\r\n return modifiers.contains(\"final\");\r\n }\r\n return false;\r\n }",
"public static java.util.Date toDateTime(Object value) throws ParseException {\n if (value == null) {\n return null;\n }\n if (value instanceof java.util.Date) {\n return (java.util.Date) value;\n }\n if (value instanceof String) {\n if (\"\".equals((String) value)) {\n return null;\n }\n return IN_DATETIME_FORMAT.parse((String) value);\n }\n\n return IN_DATETIME_FORMAT.parse(value.toString());\n }",
"private void recordBackupSet(File backupDir) throws IOException {\n String[] filesInEnv = env.getHome().list();\n SimpleDateFormat format = new SimpleDateFormat(\"yyyy_MM_dd_kk_mm_ss\");\n String recordFileName = \"backupset-\" + format.format(new Date());\n File recordFile = new File(backupDir, recordFileName);\n if(recordFile.exists()) {\n recordFile.renameTo(new File(backupDir, recordFileName + \".old\"));\n }\n\n PrintStream backupRecord = new PrintStream(new FileOutputStream(recordFile));\n backupRecord.println(\"Lastfile:\" + Long.toHexString(backupHelper.getLastFileInBackupSet()));\n if(filesInEnv != null) {\n for(String file: filesInEnv) {\n if(file.endsWith(BDB_EXT))\n backupRecord.println(file);\n }\n }\n backupRecord.close();\n }",
"@SuppressWarnings(\"unchecked\")\n private static Object resolveConflictWithResolver(\n final ConflictHandler conflictResolver,\n final BsonValue documentId,\n final ChangeEvent localEvent,\n final ChangeEvent remoteEvent\n ) {\n return conflictResolver.resolveConflict(\n documentId,\n localEvent,\n remoteEvent);\n }",
"public static boolean isInSubDirectory(File dir, File file)\n {\n if (file == null)\n return false;\n\n if (file.equals(dir))\n return true;\n\n return isInSubDirectory(dir, file.getParentFile());\n }"
] |
From v3_epoly.js, calculates the distance between this LatLong point and
another.
@param end The end point to calculate the distance to.
@return The distance, in metres, to the end point. | [
"public double distanceFrom(LatLong end) {\n\n double dLat = (end.getLatitude() - getLatitude()) * Math.PI / 180;\n double dLon = (end.getLongitude() - getLongitude()) * Math.PI / 180;\n\n double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)\n + Math.cos(getLatitude() * Math.PI / 180)\n * Math.cos(end.getLatitude() * Math.PI / 180)\n * Math.sin(dLon / 2) * Math.sin(dLon / 2);\n\n double c = 2.0 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n double d = EarthRadiusMeters * c;\n return d;\n }"
] | [
"public static dospolicy[] get(nitro_service service) throws Exception{\n\t\tdospolicy obj = new dospolicy();\n\t\tdospolicy[] response = (dospolicy[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void performPermissionCheck(CmsObject cms) throws CmsPermissionViolationException {\n\n if (cms.getRequestContext().getCurrentUser().isGuestUser()) {\n throw new CmsPermissionViolationException(null);\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 boolean detectTierRichCss() {\r\n\r\n boolean result = false;\r\n //The following devices are explicitly ok.\r\n //Note: 'High' BlackBerry devices ONLY\r\n if (detectMobileQuick()) {\r\n\r\n //Exclude iPhone Tier and e-Ink Kindle devices.\r\n if (!detectTierIphone() && !detectKindle()) {\r\n\r\n //The following devices are explicitly ok.\r\n //Note: 'High' BlackBerry devices ONLY\r\n //Older Windows 'Mobile' isn't good enough for iPhone Tier.\r\n if (detectWebkit()\r\n || detectS60OssBrowser()\r\n || detectBlackBerryHigh()\r\n || detectWindowsMobile()\r\n || (userAgent.indexOf(engineTelecaQ) != -1)) {\r\n result = true;\r\n } // if detectWebkit()\r\n } //if !detectTierIphone()\r\n } //if detectMobileQuick()\r\n return result;\r\n }",
"@Override\n public PersistentResourceXMLDescription getParserDescription() {\n return PersistentResourceXMLDescription.builder(ElytronExtension.SUBSYSTEM_PATH, getNameSpace())\n .addAttribute(ElytronDefinition.DEFAULT_AUTHENTICATION_CONTEXT)\n .addAttribute(ElytronDefinition.INITIAL_PROVIDERS)\n .addAttribute(ElytronDefinition.FINAL_PROVIDERS)\n .addAttribute(ElytronDefinition.DISALLOWED_PROVIDERS)\n .addAttribute(ElytronDefinition.SECURITY_PROPERTIES, new AttributeParsers.PropertiesParser(null, SECURITY_PROPERTY, true), new AttributeMarshallers.PropertiesAttributeMarshaller(null, SECURITY_PROPERTY, true))\n .addChild(getAuthenticationClientParser())\n .addChild(getProviderParser())\n .addChild(getAuditLoggingParser())\n .addChild(getDomainParser())\n .addChild(getRealmParser())\n .addChild(getCredentialSecurityFactoryParser())\n .addChild(getMapperParser())\n .addChild(getHttpParser())\n .addChild(getSaslParser())\n .addChild(getTlsParser())\n .addChild(decorator(CREDENTIAL_STORES).addChild(new CredentialStoreParser().parser))\n .addChild(getDirContextParser())\n .addChild(getPolicyParser())\n .build();\n }",
"protected float getStartingOffset(final float totalSize) {\n final float axisSize = getViewPortSize(getOrientationAxis());\n float startingOffset = 0;\n\n switch (getGravityInternal()) {\n case LEFT:\n case FILL:\n case TOP:\n case FRONT:\n startingOffset = -axisSize / 2;\n break;\n case RIGHT:\n case BOTTOM:\n case BACK:\n startingOffset = (axisSize / 2 - totalSize);\n break;\n case CENTER:\n startingOffset = -totalSize / 2;\n break;\n default:\n Log.w(TAG, \"Cannot calculate starting offset: \" +\n \"gravity %s is not supported!\", mGravity);\n break;\n\n }\n\n Log.d(LAYOUT, TAG, \"getStartingOffset(): totalSize: %5.4f, dimension: %5.4f, startingOffset: %5.4f\",\n totalSize, axisSize, startingOffset);\n\n return startingOffset;\n }",
"public static dnspolicy_dnspolicylabel_binding[] get(nitro_service service, String name) throws Exception{\n\t\tdnspolicy_dnspolicylabel_binding obj = new dnspolicy_dnspolicylabel_binding();\n\t\tobj.set_name(name);\n\t\tdnspolicy_dnspolicylabel_binding response[] = (dnspolicy_dnspolicylabel_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"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 String objectToString(T object) {\n\t\tStringBuilder sb = new StringBuilder(64);\n\t\tsb.append(object.getClass().getSimpleName());\n\t\tfor (FieldType fieldType : fieldTypes) {\n\t\t\tsb.append(' ').append(fieldType.getColumnName()).append('=');\n\t\t\ttry {\n\t\t\t\tsb.append(fieldType.extractJavaFieldValue(object));\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow new IllegalStateException(\"Could not generate toString of field \" + fieldType, e);\n\t\t\t}\n\t\t}\n\t\treturn sb.toString();\n\t}"
] |
Print work units.
@param value TimeUnit instance
@return work units value | [
"public static final BigInteger printWorkUnits(TimeUnit value)\n {\n int result;\n\n if (value == null)\n {\n value = TimeUnit.HOURS;\n }\n\n switch (value)\n {\n case MINUTES:\n {\n result = 1;\n break;\n }\n\n case DAYS:\n {\n result = 3;\n break;\n }\n\n case WEEKS:\n {\n result = 4;\n break;\n }\n\n case MONTHS:\n {\n result = 5;\n break;\n }\n\n case YEARS:\n {\n result = 7;\n break;\n }\n\n default:\n case HOURS:\n {\n result = 2;\n break;\n }\n }\n\n return (BigInteger.valueOf(result));\n }"
] | [
"public void filterUnsafeOrUnnecessaryRequest(\n Map<String, NodeReqResponse> nodeDataMapValidSource,\n Map<String, NodeReqResponse> nodeDataMapValidSafe) {\n\n for (Entry<String, NodeReqResponse> entry : nodeDataMapValidSource\n .entrySet()) {\n\n String hostName = entry.getKey();\n NodeReqResponse nrr = entry.getValue();\n\n Map<String, String> map = nrr.getRequestParameters();\n\n /**\n * 20130507: will generally apply to all requests: if have this\n * field and this field is false\n */\n if (map.containsKey(PcConstants.NODE_REQUEST_WILL_EXECUTE)) {\n Boolean willExecute = Boolean.parseBoolean(map\n .get(PcConstants.NODE_REQUEST_WILL_EXECUTE));\n\n if (!willExecute) {\n logger.info(\"NOT_EXECUTE_COMMAND \" + \" on target: \"\n + hostName + \" at \"\n + PcDateUtils.getNowDateTimeStrStandard());\n continue;\n }\n }\n\n // now safely to add this node in.\n nodeDataMapValidSafe.put(hostName, nrr);\n }// end for loop\n\n }",
"protected PrintResult withOpenOutputStream(final PrintAction function) throws Exception {\n final File reportFile = getReportFile();\n final Processor.ExecutionContext executionContext;\n try (FileOutputStream out = new FileOutputStream(reportFile);\n BufferedOutputStream bout = new BufferedOutputStream(out)) {\n executionContext = function.run(bout);\n }\n return new PrintResult(reportFile.length(), executionContext);\n }",
"public void put(String key, String value) {\n synchronized (this.cache) {\n this.cache.put(key, value);\n }\n }",
"static ReadMasterDomainModelUtil readMasterDomainResourcesForInitialConnect(final Transformers transformers,\n final Transformers.TransformationInputs transformationInputs,\n final Transformers.ResourceIgnoredTransformationRegistry ignoredTransformationRegistry,\n final Resource domainRoot) throws OperationFailedException {\n\n Resource transformedResource = transformers.transformRootResource(transformationInputs, domainRoot, ignoredTransformationRegistry);\n ReadMasterDomainModelUtil util = new ReadMasterDomainModelUtil();\n util.describedResources = util.describeAsNodeList(PathAddress.EMPTY_ADDRESS, transformedResource, false);\n return util;\n }",
"public BoxFile.Info restoreFile(String fileID, String newName, String newParentID) {\n JsonObject requestJSON = new JsonObject();\n\n if (newName != null) {\n requestJSON.add(\"name\", newName);\n }\n\n if (newParentID != null) {\n JsonObject parent = new JsonObject();\n parent.add(\"id\", newParentID);\n requestJSON.add(\"parent\", parent);\n }\n\n URL url = RESTORE_FILE_URL_TEMPLATE.build(this.api.getBaseURL(), fileID);\n BoxJSONRequest request = new BoxJSONRequest(this.api, url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxFile restoredFile = new BoxFile(this.api, responseJSON.get(\"id\").asString());\n return restoredFile.new Info(responseJSON);\n }",
"public static AnnotationNode getAnnotation(AnnotatedNode node, String name) {\r\n List<AnnotationNode> annotations = node.getAnnotations();\r\n for (AnnotationNode annot : annotations) {\r\n if (annot.getClassNode().getName().equals(name)) {\r\n return annot;\r\n }\r\n }\r\n return null;\r\n }",
"public ItemRequest<CustomField> findById(String customField) {\n \n String path = String.format(\"/custom_fields/%s\", customField);\n return new ItemRequest<CustomField>(this, CustomField.class, path, \"GET\");\n }",
"public String getHostAddress() {\n if( addr instanceof NbtAddress ) {\n return ((NbtAddress)addr).getHostAddress();\n }\n return ((InetAddress)addr).getHostAddress();\n }",
"protected void appendFacetOption(StringBuffer query, final String name, final String value) {\n\n query.append(\" facet.\").append(name).append(\"=\").append(value);\n }"
] |
Generate the global CSS style for the whole document.
@return the CSS code used in the generated document header | [
"protected String createGlobalStyle()\n {\n StringBuilder ret = new StringBuilder();\n ret.append(createFontFaces());\n ret.append(\"\\n\");\n ret.append(defaultStyle);\n return ret.toString();\n }"
] | [
"private void writeAllEnvelopes(boolean reuse)\r\n {\r\n // perform remove of m:n indirection table entries first\r\n performM2NUnlinkEntries();\r\n\r\n Iterator iter;\r\n // using clone to avoid ConcurentModificationException\r\n iter = ((List) mvOrderOfIds.clone()).iterator();\r\n while(iter.hasNext())\r\n {\r\n ObjectEnvelope mod = (ObjectEnvelope) mhtObjectEnvelopes.get(iter.next());\r\n boolean insert = false;\r\n if(needsCommit)\r\n {\r\n insert = mod.needsInsert();\r\n mod.getModificationState().commit(mod);\r\n if(reuse && insert)\r\n {\r\n getTransaction().doSingleLock(mod.getClassDescriptor(), mod.getObject(), mod.getIdentity(), Transaction.WRITE);\r\n }\r\n }\r\n /*\r\n arminw: important to call this cleanup method for each registered\r\n ObjectEnvelope, because this method will e.g. remove proxy listener\r\n objects for registered objects.\r\n */\r\n mod.cleanup(reuse, insert);\r\n }\r\n // add m:n indirection table entries\r\n performM2NLinkEntries();\r\n }",
"public SerialMessage setValueMessage(int level) {\r\n\t\tlogger.debug(\"Creating new message for application command BASIC_SET for node {}\", this.getNode().getNodeId());\r\n\t\tSerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.SendData, SerialMessagePriority.Set);\r\n \tbyte[] newPayload = { \t(byte) this.getNode().getNodeId(), \r\n \t\t\t\t\t\t\t3, \r\n\t\t\t\t\t\t\t\t(byte) getCommandClass().getKey(), \r\n\t\t\t\t\t\t\t\t(byte) BASIC_SET,\r\n\t\t\t\t\t\t\t\t(byte) level\r\n\t\t\t\t\t\t\t\t};\r\n \tresult.setMessagePayload(newPayload);\r\n \treturn result;\t\t\r\n\t}",
"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 }",
"public static ModelNode createBootUpdates(final String serverName, final ModelNode domainModel, final ModelNode hostModel,\n final DomainController domainController, final ExpressionResolver expressionResolver) {\n final ManagedServerOperationsFactory factory = new ManagedServerOperationsFactory(serverName, domainModel,\n hostModel, domainController, expressionResolver);\n\n\n return factory.getBootUpdates();\n }",
"public Object putNodeMetaData(Object key, Object value) {\n if (key == null) throw new GroovyBugError(\"Tried to set meta data with null key on \" + this + \".\");\n if (metaDataMap == null) {\n metaDataMap = new ListHashMap();\n }\n return metaDataMap.put(key, value);\n }",
"protected StreamRequestHandlerState determineRequestHandlerState(String itemTag) {\n\n if (keyIterator.hasNext() && !fetchedEnoughForAllPartitions()) {\n return StreamRequestHandlerState.WRITING;\n } else {\n logger.info(\"Finished fetch \" + itemTag + \" for store '\" + storageEngine.getName()\n + \"' with partitions \" + partitionIds);\n progressInfoMessage(\"Fetch \" + itemTag + \" (end of scan)\");\n\n return StreamRequestHandlerState.COMPLETE;\n }\n }",
"public static aaauser_binding get(nitro_service service, String username) throws Exception{\n\t\taaauser_binding obj = new aaauser_binding();\n\t\tobj.set_username(username);\n\t\taaauser_binding response = (aaauser_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private void writeProjectExtendedAttributes(Project project)\n {\n Project.ExtendedAttributes attributes = m_factory.createProjectExtendedAttributes();\n project.setExtendedAttributes(attributes);\n List<Project.ExtendedAttributes.ExtendedAttribute> list = attributes.getExtendedAttribute();\n\n Set<FieldType> customFields = new HashSet<FieldType>();\n for (CustomField customField : m_projectFile.getCustomFields())\n {\n FieldType fieldType = customField.getFieldType();\n if (fieldType != null)\n {\n customFields.add(fieldType);\n }\n }\n\n customFields.addAll(m_extendedAttributesInUse);\n \n List<FieldType> customFieldsList = new ArrayList<FieldType>();\n customFieldsList.addAll(customFields);\n \n\n // Sort to ensure consistent order in file\n final CustomFieldContainer customFieldContainer = m_projectFile.getCustomFields();\n Collections.sort(customFieldsList, new Comparator<FieldType>()\n {\n @Override public int compare(FieldType o1, FieldType o2)\n {\n CustomField customField1 = customFieldContainer.getCustomField(o1);\n CustomField customField2 = customFieldContainer.getCustomField(o2);\n String name1 = o1.getClass().getSimpleName() + \".\" + o1.getName() + \" \" + customField1.getAlias();\n String name2 = o2.getClass().getSimpleName() + \".\" + o2.getName() + \" \" + customField2.getAlias();\n return name1.compareTo(name2);\n }\n });\n\n for (FieldType fieldType : customFieldsList)\n {\n Project.ExtendedAttributes.ExtendedAttribute attribute = m_factory.createProjectExtendedAttributesExtendedAttribute();\n list.add(attribute);\n attribute.setFieldID(String.valueOf(FieldTypeHelper.getFieldID(fieldType)));\n attribute.setFieldName(fieldType.getName());\n\n CustomField customField = customFieldContainer.getCustomField(fieldType);\n attribute.setAlias(customField.getAlias());\n }\n }",
"public void filterUnsafeOrUnnecessaryRequest(\n Map<String, NodeReqResponse> nodeDataMapValidSource,\n Map<String, NodeReqResponse> nodeDataMapValidSafe) {\n\n for (Entry<String, NodeReqResponse> entry : nodeDataMapValidSource\n .entrySet()) {\n\n String hostName = entry.getKey();\n NodeReqResponse nrr = entry.getValue();\n\n Map<String, String> map = nrr.getRequestParameters();\n\n /**\n * 20130507: will generally apply to all requests: if have this\n * field and this field is false\n */\n if (map.containsKey(PcConstants.NODE_REQUEST_WILL_EXECUTE)) {\n Boolean willExecute = Boolean.parseBoolean(map\n .get(PcConstants.NODE_REQUEST_WILL_EXECUTE));\n\n if (!willExecute) {\n logger.info(\"NOT_EXECUTE_COMMAND \" + \" on target: \"\n + hostName + \" at \"\n + PcDateUtils.getNowDateTimeStrStandard());\n continue;\n }\n }\n\n // now safely to add this node in.\n nodeDataMapValidSafe.put(hostName, nrr);\n }// end for loop\n\n }"
] |
Returns the required gallery open parameters.
@param cms an initialized instance of a CmsObject
@param messages the dialog messages
@param param the widget parameter to generate the widget for
@param resource the resource being edited
@param hashId the field id hash
@return the gallery open parameters | [
"protected Map<String, String> getGalleryOpenParams(\n CmsObject cms,\n CmsMessages messages,\n I_CmsWidgetParameter param,\n String resource,\n long hashId) {\n\n Map<String, String> result = new HashMap<String, String>();\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_MODE, A_CmsAjaxGallery.MODE_WIDGET);\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_STORAGE_PREFIX, getGalleryStoragePrefix());\n result.put(I_CmsGalleryProviderConstants.CONFIG_RESOURCE_TYPES, getGalleryTypes());\n if (param.getId() != null) {\n result.put(I_CmsGalleryProviderConstants.KEY_FIELD_ID, param.getId());\n // use javascript to read the current field value\n result.put(\n I_CmsGalleryProviderConstants.CONFIG_CURRENT_ELEMENT,\n \"'+document.getElementById('\" + param.getId() + \"').getAttribute('value')+'\");\n }\n result.put(I_CmsGalleryProviderConstants.KEY_HASH_ID, \"\" + hashId);\n // the edited resource\n if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(resource)) {\n result.put(I_CmsGalleryProviderConstants.CONFIG_REFERENCE_PATH, resource);\n }\n // the start up gallery path\n CmsGalleryWidgetConfiguration configuration = getWidgetConfiguration(cms, messages, param);\n if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(configuration.getStartup())) {\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_PATH, configuration.getStartup());\n }\n // set gallery types if available\n if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(configuration.getGalleryTypes())) {\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_TYPES, configuration.getGalleryTypes());\n }\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_NAME, getGalleryName());\n return result;\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 }",
"public static void initialize(BeanManagerImpl deploymentManager, ServiceRegistry deploymentServices) {\n Container instance = new Container(RegistrySingletonProvider.STATIC_INSTANCE, deploymentManager, deploymentServices);\n Container.instance.set(RegistrySingletonProvider.STATIC_INSTANCE, instance);\n }",
"public static base_response update(nitro_service client, inatparam resource) throws Exception {\n\t\tinatparam updateresource = new inatparam();\n\t\tupdateresource.nat46v6prefix = resource.nat46v6prefix;\n\t\tupdateresource.nat46ignoretos = resource.nat46ignoretos;\n\t\tupdateresource.nat46zerochecksum = resource.nat46zerochecksum;\n\t\tupdateresource.nat46v6mtu = resource.nat46v6mtu;\n\t\tupdateresource.nat46fragheader = resource.nat46fragheader;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public void writeObject(Object o, GraphicsDocument document, boolean asChild) throws RenderException {\n\t\tdocument.writeElement(\"vml:shape\", asChild);\n\t\tPoint p = (Point) o;\n\t\tString adj = document.getFormatter().format(p.getX()) + \",\"\n\t\t\t\t+ document.getFormatter().format(p.getY());\n\t\tdocument.writeAttribute(\"adj\", adj);\n\t}",
"public void growMaxColumns( int desiredColumns , boolean preserveValue ) {\n if( col_idx.length < desiredColumns+1 ) {\n int[] c = new int[ desiredColumns+1 ];\n if( preserveValue )\n System.arraycopy(col_idx,0,c,0,col_idx.length);\n col_idx = c;\n }\n }",
"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 }",
"public Response remove(String id, String rev) {\r\n assertNotEmpty(id, \"id\");\r\n assertNotEmpty(id, \"rev\");\r\n return db.remove(ensureDesignPrefix(id), rev);\r\n\r\n }",
"@Override\n public PmdRuleSet create() {\n final SAXBuilder parser = new SAXBuilder();\n final Document dom;\n try {\n dom = parser.build(source);\n } catch (JDOMException | IOException e) {\n if (messages != null) {\n messages.addErrorText(INVALID_INPUT + \" : \" + e.getMessage());\n }\n LOG.error(INVALID_INPUT, e);\n return new PmdRuleSet();\n }\n\n final Element eltResultset = dom.getRootElement();\n final Namespace namespace = eltResultset.getNamespace();\n final PmdRuleSet result = new PmdRuleSet();\n\n final String name = eltResultset.getAttributeValue(\"name\");\n final Element descriptionElement = getChild(eltResultset, namespace);\n\n result.setName(name);\n\n if (descriptionElement != null) {\n result.setDescription(descriptionElement.getValue());\n }\n\n for (Element eltRule : getChildren(eltResultset, \"rule\", namespace)) {\n PmdRule pmdRule = new PmdRule(eltRule.getAttributeValue(\"ref\"));\n pmdRule.setClazz(eltRule.getAttributeValue(\"class\"));\n pmdRule.setName(eltRule.getAttributeValue(\"name\"));\n pmdRule.setMessage(eltRule.getAttributeValue(\"message\"));\n parsePmdPriority(eltRule, pmdRule, namespace);\n parsePmdProperties(eltRule, pmdRule, namespace);\n result.addRule(pmdRule);\n }\n return result;\n }",
"public boolean equivalent(Element otherElement, boolean logging) {\n\t\tif (eventable.getElement().equals(otherElement)) {\n\t\t\tif (logging) {\n\t\t\t\tLOGGER.info(\"Element equal\");\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tif (eventable.getElement().equalAttributes(otherElement)) {\n\t\t\tif (logging) {\n\t\t\t\tLOGGER.info(\"Element attributes equal\");\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tif (eventable.getElement().equalId(otherElement)) {\n\t\t\tif (logging) {\n\t\t\t\tLOGGER.info(\"Element ID equal\");\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tif (!eventable.getElement().getText().equals(\"\")\n\t\t\t\t&& eventable.getElement().equalText(otherElement)) {\n\n\t\t\tif (logging) {\n\t\t\t\tLOGGER.info(\"Element text equal\");\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}"
] |
Computes the MD5 value of the input stream
@param input
@return
@throws IOException
@throws IllegalStateException | [
"public static String md5sum(InputStream input) throws IOException {\r\n InputStream in = new BufferedInputStream(input);\r\n try {\r\n MessageDigest digest = java.security.MessageDigest.getInstance(\"MD5\");\r\n DigestInputStream digestInputStream = new DigestInputStream(in, digest);\r\n while(digestInputStream.read() >= 0) {\r\n }\r\n OutputStream md5out = new ByteArrayOutputStream();\r\n md5out.write(digest.digest());\r\n return md5out.toString();\r\n }\r\n catch(NoSuchAlgorithmException e) {\r\n throw new IllegalStateException(\"MD5 algorithm is not available: \" + e.getMessage());\r\n }\r\n finally {\r\n in.close();\r\n }\r\n }"
] | [
"public void addGroupBy(String[] fieldNames)\r\n {\r\n for (int i = 0; i < fieldNames.length; i++)\r\n {\r\n addGroupBy(fieldNames[i]);\r\n }\r\n }",
"private void readLSD() {\n // Logical screen size.\n header.width = readShort();\n header.height = readShort();\n // Packed fields\n int packed = read();\n // 1 : global color table flag.\n header.gctFlag = (packed & 0x80) != 0;\n // 2-4 : color resolution.\n // 5 : gct sort flag.\n // 6-8 : gct size.\n header.gctSize = 2 << (packed & 7);\n // Background color index.\n header.bgIndex = read();\n // Pixel aspect ratio\n header.pixelAspect = read();\n }",
"public static nslimitidentifier_stats get(nitro_service service, String name) throws Exception{\n\t\tnslimitidentifier_stats obj = new nslimitidentifier_stats();\n\t\tobj.set_name(name);\n\t\tnslimitidentifier_stats response = (nslimitidentifier_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"public void removeValue(T value, boolean reload) {\n int idx = getIndex(value);\n if (idx >= 0) {\n removeItemInternal(idx, reload);\n }\n }",
"public static void load(File file)\n {\n try(FileInputStream inputStream = new FileInputStream(file))\n {\n LineIterator it = IOUtils.lineIterator(inputStream, \"UTF-8\");\n while (it.hasNext())\n {\n String line = it.next();\n if (!line.startsWith(\"#\") && !line.trim().isEmpty())\n {\n add(line);\n }\n }\n }\n catch (Exception e)\n {\n throw new WindupException(\"Failed loading archive ignore patterns from [\" + file.toString() + \"]\", e);\n }\n }",
"private static String clearPath(String path) {\n try {\n ExpressionBaseState state = new ExpressionBaseState(\"EXPR\", true, false);\n if (Util.isWindows()) {\n // to not require escaping FS name separator\n state.setDefaultHandler(WordCharacterHandler.IGNORE_LB_ESCAPE_OFF);\n } else {\n state.setDefaultHandler(WordCharacterHandler.IGNORE_LB_ESCAPE_ON);\n }\n // Remove escaping characters\n path = ArgumentWithValue.resolveValue(path, state);\n } catch (CommandFormatException ex) {\n // XXX OK, continue translation\n }\n // Remove quote to retrieve candidates.\n if (path.startsWith(\"\\\"\")) {\n path = path.substring(1);\n }\n // Could be an escaped \" character. We don't take into account this corner case.\n // concider it the end of the quoted part.\n if (path.endsWith(\"\\\"\")) {\n path = path.substring(0, path.length() - 1);\n }\n return path;\n }",
"public static byte[] synchronizeSlaveHostController(ModelNode operation, final PathAddress address, HostFileRepository fileRepository, ContentRepository contentRepository, boolean backup, byte[] oldHash) {\n ModelNode operationContentItem = operation.get(DeploymentAttributes.CONTENT_RESOURCE_ALL.getName()).get(0);\n byte[] newHash = operationContentItem.require(CONTENT_HASH.getName()).asBytes();\n if (needRemoteContent(fileRepository, contentRepository, backup, oldHash)) { // backup DC needs to pull the content\n fileRepository.getDeploymentFiles(ModelContentReference.fromModelAddress(address, newHash));\n }\n return newHash;\n }",
"public static CombinedInterceptorAndDecoratorStackMethodHandler peekIfNotEmpty() {\n Stack stack = interceptionContexts.get();\n if (stack == null) {\n return null;\n }\n return stack.peek();\n }",
"private void parseMacro( TokenList tokens , Sequence sequence ) {\n Macro macro = new Macro();\n\n TokenList.Token t = tokens.getFirst().next;\n\n if( t.word == null ) {\n throw new ParseError(\"Expected the macro's name after \"+tokens.getFirst().word);\n }\n List<TokenList.Token> variableTokens = new ArrayList<TokenList.Token>();\n\n macro.name = t.word;\n t = t.next;\n t = parseMacroInput(variableTokens, t);\n for( TokenList.Token a : variableTokens ) {\n if( a.word == null) throw new ParseError(\"expected word in macro header\");\n macro.inputs.add(a.word);\n }\n t = t.next;\n if( t == null || t.getSymbol() != Symbol.ASSIGN)\n throw new ParseError(\"Expected assignment\");\n t = t.next;\n macro.tokens = new TokenList(t,tokens.last);\n\n sequence.addOperation(macro.createOperation(macros));\n }"
] |
Removes bean from scope.
@param name bean name
@return previous value | [
"public Object remove(String name) {\n\t\tThreadScopeContext context = ThreadScopeContextHolder.getContext();\n\t\treturn context.remove(name);\n\t}"
] | [
"public Where<T, ID> rawComparison(String columnName, String rawOperator, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value, rawOperator));\n\t\treturn this;\n\t}",
"BsonDocument getNextVersion() {\n if (!this.hasVersion() || this.getVersionDoc() == null) {\n return getFreshVersionDocument();\n }\n final BsonDocument nextVersion = BsonUtils.copyOfDocument(this.getVersionDoc());\n nextVersion.put(\n Fields.VERSION_COUNTER_FIELD,\n new BsonInt64(this.getVersion().getVersionCounter() + 1));\n return nextVersion;\n }",
"@Override\n\tpublic T next() {\n\t\tSQLException sqlException = null;\n\t\ttry {\n\t\t\tT result = nextThrow();\n\t\t\tif (result != null) {\n\t\t\t\treturn result;\n\t\t\t}\n\t\t} catch (SQLException e) {\n\t\t\tsqlException = e;\n\t\t}\n\t\t// we have to throw if there is no next or on a SQLException\n\t\tlast = null;\n\t\tcloseQuietly();\n\t\tthrow new IllegalStateException(\"Could not get next result for \" + dataClass, sqlException);\n\t}",
"public String readSnippet(String name) {\n\n String path = CmsStringUtil.joinPaths(\n m_context.getSetupBean().getWebAppRfsPath(),\n CmsSetupBean.FOLDER_SETUP,\n \"html\",\n name);\n try (InputStream stream = new FileInputStream(path)) {\n byte[] data = CmsFileUtil.readFully(stream, false);\n String result = new String(data, \"UTF-8\");\n return result;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }",
"private static void checkPreconditions(final long min, final long max) {\n\t\tif( max < min ) {\n\t\t\tthrow new IllegalArgumentException(String.format(\"max (%d) should not be < min (%d)\", max, min));\n\t\t}\n\t}",
"protected ValueContainer[] getKeyValues(PersistenceBroker broker, ClassDescriptor cld, Object obj) throws PersistenceBrokerException\r\n {\r\n return broker.serviceBrokerHelper().getKeyValues(cld, obj);\r\n }",
"public T update(T entity) throws RowNotFoundException, OptimisticLockException {\n\n if (!hasPrimaryKey(entity)) {\n throw new RuntimeException(String.format(\"Tried to update entity of type %s without a primary key\", entity\n .getClass().getSimpleName()));\n }\n\n UpdateCreator update = new UpdateCreator(table);\n\n update.whereEquals(idColumn.getColumnName(), getPrimaryKey(entity));\n\n if (versionColumn != null) {\n update.set(versionColumn.getColumnName() + \" = \" + versionColumn.getColumnName() + \" + 1\");\n update.whereEquals(versionColumn.getColumnName(), getVersion(entity));\n }\n\n for (Column column : columns) {\n if (!column.isReadOnly()) {\n update.setValue(column.getColumnName(), getFieldValueAsColumn(entity, column));\n }\n }\n\n int rows = new JdbcTemplate(ormConfig.getDataSource()).update(update);\n\n if (rows == 1) {\n\n if (versionColumn != null) {\n ReflectionUtils.setFieldValue(entity, versionColumn.getFieldName(), getVersion(entity) + 1);\n }\n\n return entity;\n\n } else if (rows > 1) {\n\n throw new RuntimeException(\n String.format(\"Updating table %s with id %s updated %d rows. There must be a mapping problem. Is column %s really the primary key?\",\n table, getPrimaryKey(entity), rows, idColumn));\n\n } else {\n\n //\n // Updated zero rows. This could be because our ID is wrong, or\n // because our object is out-of date. Let's try querying just by ID.\n //\n\n SelectCreator selectById = new SelectCreator()\n .column(\"count(*)\")\n .from(table)\n .whereEquals(idColumn.getColumnName(), getPrimaryKey(entity));\n\n rows = new JdbcTemplate(ormConfig.getDataSource()).query(selectById, new ResultSetExtractor<Integer>() {\n @Override\n public Integer extractData(ResultSet rs) throws SQLException, DataAccessException {\n rs.next();\n return rs.getInt(1);\n }\n });\n\n if (rows == 0) {\n throw new RowNotFoundException(table, getPrimaryKey(entity));\n } else {\n throw new OptimisticLockException(table, getPrimaryKey(entity));\n }\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 void addAuthentication(HttpHost host, Credentials credentials,\n AuthScheme authScheme, HttpClientContext context) {\n AuthCache authCache = context.getAuthCache();\n if (authCache == null) {\n authCache = new BasicAuthCache();\n context.setAuthCache(authCache);\n }\n \n CredentialsProvider credsProvider = context.getCredentialsProvider();\n if (credsProvider == null) {\n credsProvider = new BasicCredentialsProvider();\n context.setCredentialsProvider(credsProvider);\n }\n \n credsProvider.setCredentials(new AuthScope(host), credentials);\n \n if (authScheme != null) {\n authCache.put(host, authScheme);\n }\n }"
] |
Retrieves a constant value.
@param type field type
@param block criteria data block
@return constant value | [
"private Object getConstantValue(FieldType type, byte[] block)\n {\n Object value;\n DataType dataType = type.getDataType();\n\n if (dataType == null)\n {\n value = null;\n }\n else\n {\n switch (dataType)\n {\n case DURATION:\n {\n value = MPPUtility.getAdjustedDuration(m_properties, MPPUtility.getInt(block, getValueOffset()), MPPUtility.getDurationTimeUnits(MPPUtility.getShort(block, getTimeUnitsOffset())));\n break;\n }\n\n case NUMERIC:\n {\n value = Double.valueOf(MPPUtility.getDouble(block, getValueOffset()));\n break;\n }\n\n case PERCENTAGE:\n {\n value = Double.valueOf(MPPUtility.getShort(block, getValueOffset()));\n break;\n }\n\n case CURRENCY:\n {\n value = Double.valueOf(MPPUtility.getDouble(block, getValueOffset()) / 100);\n break;\n }\n\n case STRING:\n {\n int textOffset = getTextOffset(block);\n value = MPPUtility.getUnicodeString(m_criteriaData, m_dataOffset + m_criteriaTextStart + textOffset);\n break;\n }\n\n case BOOLEAN:\n {\n int intValue = MPPUtility.getShort(block, getValueOffset());\n value = (intValue == 1 ? Boolean.TRUE : Boolean.FALSE);\n break;\n }\n\n case DATE:\n {\n value = MPPUtility.getTimestamp(block, getValueOffset());\n break;\n }\n\n default:\n {\n value = null;\n break;\n }\n }\n }\n\n return value;\n }"
] | [
"public static 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 }",
"public static String parseString(String value)\n {\n if (value != null)\n {\n // Strip angle brackets if present\n if (!value.isEmpty() && value.charAt(0) == '<')\n {\n value = value.substring(1, value.length() - 1);\n }\n\n // Strip quotes if present\n if (!value.isEmpty() && value.charAt(0) == '\"')\n {\n value = value.substring(1, value.length() - 1);\n }\n }\n return value;\n }",
"public int createPartitions(String topic, int partitionNum, boolean enlarge) throws IOException {\n KV<Receive, ErrorMapping> response = send(new CreaterRequest(topic, partitionNum, enlarge));\n return Utils.deserializeIntArray(response.k.buffer())[0];\n }",
"public static double blackScholesDigitalOptionDelta(\n\t\t\tdouble initialStockValue,\n\t\t\tdouble riskFreeRate,\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike)\n\t{\n\t\tif(optionStrike <= 0.0 || optionMaturity <= 0.0)\n\t\t{\n\t\t\t// The Black-Scholes model does not consider it being an option\n\t\t\treturn 0.0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Calculate delta\n\t\t\tdouble dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));\n\t\t\tdouble dMinus = dPlus - volatility * Math.sqrt(optionMaturity);\n\n\t\t\tdouble delta = Math.exp(-0.5*dMinus*dMinus) / (Math.sqrt(2.0 * Math.PI * optionMaturity) * initialStockValue * volatility);\n\n\t\t\treturn delta;\n\t\t}\n\t}",
"public Optional<URL> getServiceUrl() {\n Optional<Service> optionalService = client.services().inNamespace(namespace)\n .list().getItems()\n .stream()\n .findFirst();\n\n return optionalService\n .map(this::createUrlForService)\n .orElse(Optional.empty());\n }",
"public static appfwpolicylabel_binding get(nitro_service service, String labelname) throws Exception{\n\t\tappfwpolicylabel_binding obj = new appfwpolicylabel_binding();\n\t\tobj.set_labelname(labelname);\n\t\tappfwpolicylabel_binding response = (appfwpolicylabel_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private void writeCostRateTables(Project.Resources.Resource xml, Resource mpx)\n {\n //Rates rates = m_factory.createProjectResourcesResourceRates();\n //xml.setRates(rates);\n //List<Project.Resources.Resource.Rates.Rate> ratesList = rates.getRate();\n\n List<Project.Resources.Resource.Rates.Rate> ratesList = null;\n\n for (int tableIndex = 0; tableIndex < 5; tableIndex++)\n {\n CostRateTable table = mpx.getCostRateTable(tableIndex);\n if (table != null)\n {\n Date from = DateHelper.FIRST_DATE;\n for (CostRateTableEntry entry : table)\n {\n if (costRateTableWriteRequired(entry, from))\n {\n if (ratesList == null)\n {\n Rates rates = m_factory.createProjectResourcesResourceRates();\n xml.setRates(rates);\n ratesList = rates.getRate();\n }\n\n Project.Resources.Resource.Rates.Rate rate = m_factory.createProjectResourcesResourceRatesRate();\n ratesList.add(rate);\n\n rate.setCostPerUse(DatatypeConverter.printCurrency(entry.getCostPerUse()));\n rate.setOvertimeRate(DatatypeConverter.printRate(entry.getOvertimeRate()));\n rate.setOvertimeRateFormat(DatatypeConverter.printTimeUnit(entry.getOvertimeRateFormat()));\n rate.setRatesFrom(from);\n from = entry.getEndDate();\n rate.setRatesTo(from);\n rate.setRateTable(BigInteger.valueOf(tableIndex));\n rate.setStandardRate(DatatypeConverter.printRate(entry.getStandardRate()));\n rate.setStandardRateFormat(DatatypeConverter.printTimeUnit(entry.getStandardRateFormat()));\n }\n }\n }\n }\n }",
"public Pair<int[][][], int[]> documentToDataAndLabels(List<IN> document) {\r\n\r\n int docSize = document.size();\r\n // first index is position in the document also the index of the\r\n // clique/factor table\r\n // second index is the number of elements in the clique/window these\r\n // features are for (starting with last element)\r\n // third index is position of the feature in the array that holds them\r\n // element in data[j][k][m] is the index of the mth feature occurring in\r\n // position k of the jth clique\r\n int[][][] data = new int[docSize][windowSize][];\r\n // index is the position in the document\r\n // element in labels[j] is the index of the correct label (if it exists) at\r\n // position j of document\r\n int[] labels = new int[docSize];\r\n\r\n if (flags.useReverse) {\r\n Collections.reverse(document);\r\n }\r\n\r\n // System.err.println(\"docSize:\"+docSize);\r\n for (int j = 0; j < docSize; j++) {\r\n CRFDatum<List<String>, CRFLabel> d = makeDatum(document, j, featureFactory);\r\n\r\n List<List<String>> features = d.asFeatures();\r\n for (int k = 0, fSize = features.size(); k < fSize; k++) {\r\n Collection<String> cliqueFeatures = features.get(k);\r\n data[j][k] = new int[cliqueFeatures.size()];\r\n int m = 0;\r\n for (String feature : cliqueFeatures) {\r\n int index = featureIndex.indexOf(feature);\r\n if (index >= 0) {\r\n data[j][k][m] = index;\r\n m++;\r\n } else {\r\n // this is where we end up when we do feature threshold cutoffs\r\n }\r\n }\r\n // Reduce memory use when some features were cut out by threshold\r\n if (m < data[j][k].length) {\r\n int[] f = new int[m];\r\n System.arraycopy(data[j][k], 0, f, 0, m);\r\n data[j][k] = f;\r\n }\r\n }\r\n\r\n IN wi = document.get(j);\r\n labels[j] = classIndex.indexOf(wi.get(AnswerAnnotation.class));\r\n }\r\n\r\n if (flags.useReverse) {\r\n Collections.reverse(document);\r\n }\r\n\r\n // System.err.println(\"numClasses: \"+classIndex.size()+\" \"+classIndex);\r\n // System.err.println(\"numDocuments: 1\");\r\n // System.err.println(\"numDatums: \"+data.length);\r\n // System.err.println(\"numFeatures: \"+featureIndex.size());\r\n\r\n return new Pair<int[][][], int[]>(data, labels);\r\n }",
"public void makePickable(GVRSceneObject sceneObject) {\n try {\n GVRMeshCollider collider = new GVRMeshCollider(sceneObject.getGVRContext(), false);\n sceneObject.attachComponent(collider);\n } catch (Exception e) {\n // Possible that some objects (X3D panel nodes) are without mesh\n Log.e(Log.SUBSYSTEM.INPUT, TAG, \"makePickable(): possible that some objects (X3D panel nodes) are without mesh!\");\n }\n }"
] |
Imports a file via assimp without post processing.
@param filename the file to import
@return the loaded scene
@throws IOException if an error occurs | [
"public static AiScene importFile(String filename) throws IOException {\n \n return importFile(filename, EnumSet.noneOf(AiPostProcessSteps.class));\n }"
] | [
"void lockInterruptibly(final Integer permit) throws InterruptedException {\n if (permit == null) {\n throw new IllegalArgumentException();\n }\n sync.acquireInterruptibly(permit);\n }",
"public static <T> List<T> sortWith(Iterable<T> iterable, Comparator<? super T> comparator) {\n\t\treturn ListExtensions.sortInplace(Lists.newArrayList(iterable), comparator);\n\t}",
"int acquireTransaction(@NotNull final Thread thread) {\n try (CriticalSection ignored = criticalSection.enter()) {\n final int currentThreadPermits = getThreadPermitsToAcquire(thread);\n waitForPermits(thread, currentThreadPermits > 0 ? nestedQueue : regularQueue, 1, currentThreadPermits);\n }\n return 1;\n }",
"private boolean isRedeployAfterRemoval(ModelNode operation) {\n return operation.hasDefined(DEPLOYMENT_OVERLAY_LINK_REMOVAL) &&\n operation.get(DEPLOYMENT_OVERLAY_LINK_REMOVAL).asBoolean();\n }",
"@Nonnull\n\tprivate static Properties findDefaultProperties() {\n\t\tfinal InputStream in = SourceCodeFormatter.class.getClassLoader().getResourceAsStream(DEFAULT_PROPERTIES_PATH);\n\t\tfinal Properties p = new Properties();\n\t\ttry {\n\t\t\tp.load(in);\n\t\t} catch (final IOException e) {\n\t\t\tthrow new RuntimeException(String.format(\"Can not load resource %s\", DEFAULT_PROPERTIES_PATH));\n\t\t}\n\t\treturn p;\n\t}",
"public static boolean isExclusivelyKnownArchive(GraphRewrite event, String filePath)\n {\n String extension = StringUtils.substringAfterLast(filePath, \".\");\n\n if (!StringUtils.equalsIgnoreCase(extension, \"jar\"))\n return false;\n\n ZipFile archive;\n try\n {\n archive = new ZipFile(filePath);\n } catch (IOException e)\n {\n return false;\n }\n\n WindupJavaConfigurationService javaConfigurationService = new WindupJavaConfigurationService(event.getGraphContext());\n WindupJavaConfigurationModel javaConfigurationModel = WindupJavaConfigurationService.getJavaConfigurationModel(event.getGraphContext());\n\n // indicates that the user did specify some packages to scan explicitly (as opposed to scanning everything)\n boolean customerPackagesSpecified = javaConfigurationModel.getScanJavaPackages().iterator().hasNext();\n\n // this should only be true if:\n // 1) the package does not contain *any* customer packages.\n // 2) the package contains \"known\" vendor packages.\n boolean exclusivelyKnown = false;\n\n String organization = null;\n Enumeration<?> e = archive.entries();\n\n // go through all entries...\n ZipEntry entry;\n while (e.hasMoreElements())\n {\n entry = (ZipEntry) e.nextElement();\n String entryName = entry.getName();\n\n if (entry.isDirectory() || !StringUtils.endsWith(entryName, \".class\"))\n continue;\n\n String classname = PathUtil.classFilePathToClassname(entryName);\n // if the package isn't current \"known\", try to match against known packages for this entry.\n if (!exclusivelyKnown)\n {\n organization = getOrganizationForPackage(event, classname);\n if (organization != null)\n {\n exclusivelyKnown = true;\n } else\n {\n // we couldn't find a package definitively, so ignore the archive\n exclusivelyKnown = false;\n break;\n }\n }\n\n // If the user specified package names and this is in those package names, then scan it anyway\n if (customerPackagesSpecified && javaConfigurationService.shouldScanPackage(classname))\n {\n return false;\n }\n }\n\n if (exclusivelyKnown)\n LOG.info(\"Known Package: \" + archive.getName() + \"; Organization: \" + organization);\n\n // Return the evaluated exclusively known value.\n return exclusivelyKnown;\n }",
"public void addGroupBy(String[] fieldNames)\r\n {\r\n for (int i = 0; i < fieldNames.length; i++)\r\n {\r\n addGroupBy(fieldNames[i]);\r\n }\r\n }",
"public Map<String, Object> getValues(double evaluationTime, MonteCarloSimulationInterface model) throws CalculationException\n\t{\n\t\tRandomVariableInterface values = getValue(evaluationTime, model);\n\n\t\tif(values == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// Sum up values on path\n\t\tdouble value = values.getAverage();\n\t\tdouble error = values.getStandardError();\n\n\t\tMap<String, Object> results = new HashMap<String, Object>();\n\t\tresults.put(\"value\", value);\n\t\tresults.put(\"error\", error);\n\n\t\treturn results;\n\t}",
"@Deprecated\n public void parseAndSetParameter(String value, ModelNode operation, XMLStreamReader reader) throws XMLStreamException {\n //we use manual parsing here, and not #getParser().. to preserve backward compatibility.\n if (value != null) {\n for (String element : value.split(\",\")) {\n parseAndAddParameterElement(element.trim(), operation, reader);\n }\n }\n }"
] |
Write the criteria elements, extracting the information of the sub-model.
@param writer the xml stream writer
@param subModel the interface model
@param nested whether it the criteria elements are nested as part of <not /> or <any />
@throws XMLStreamException | [
"private void writeInterfaceCriteria(final XMLExtendedStreamWriter writer, final ModelNode subModel, final boolean nested) throws XMLStreamException {\n for (final Property property : subModel.asPropertyList()) {\n if (property.getValue().isDefined()) {\n writeInterfaceCriteria(writer, property, nested);\n }\n }\n }"
] | [
"public IndexDef getIndex(String name)\r\n {\r\n String realName = (name == null ? \"\" : name);\r\n IndexDef def = null;\r\n\r\n for (Iterator it = getIndices(); it.hasNext();)\r\n {\r\n def = (IndexDef)it.next();\r\n if (def.getName().equals(realName))\r\n {\r\n return def;\r\n }\r\n }\r\n return null;\r\n }",
"private void debugLogEnd(String operationType,\n Long OriginTimeInMs,\n Long RequestStartTimeInMs,\n Long ResponseReceivedTimeInMs,\n String keyString,\n int numVectorClockEntries) {\n long durationInMs = ResponseReceivedTimeInMs - RequestStartTimeInMs;\n logger.debug(\"Received a response from voldemort server for Operation Type: \"\n + operationType\n + \" , For key(s): \"\n + keyString\n + \" , Store: \"\n + this.storeName\n + \" , Origin time of request (in ms): \"\n + OriginTimeInMs\n + \" , Response received at time (in ms): \"\n + ResponseReceivedTimeInMs\n + \" . Request sent at(in ms): \"\n + RequestStartTimeInMs\n + \" , Num vector clock entries: \"\n + numVectorClockEntries\n + \" , Duration from CoordinatorFatClient back to CoordinatorFatClient(in ms): \"\n + durationInMs);\n }",
"public int length() {\n int length = 1 + 2 + deviceToken.length + 2 + payload.length;\n final int marshalledLength = marshall().length;\n assert marshalledLength == length;\n return length;\n }",
"public int getTotalCreatedConnections(){\r\n\t\tint total=0;\r\n\t\tfor (int i=0; i < this.partitionCount && this.partitions[i] != null; i++){\r\n\t\t\ttotal+=this.partitions[i].getCreatedConnections();\r\n\t\t}\r\n\t\treturn total;\r\n\t}",
"private void initExceptionsPanel() {\n\n m_exceptionsPanel.setLegend(Messages.get().key(Messages.GUI_SERIALDATE_PANEL_EXCEPTIONS_0));\n m_exceptionsPanel.addCloseHandler(this);\n m_exceptionsPanel.setVisible(false);\n }",
"public static aaaparameter get(nitro_service service) throws Exception{\n\t\taaaparameter obj = new aaaparameter();\n\t\taaaparameter[] response = (aaaparameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public static Variable deserialize(String s,\n VariableType variableType) {\n return deserialize(s,\n variableType,\n null);\n }",
"@Override\n public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {\n\n final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();\n List<ResourceRoot> resourceRoots = DeploymentUtils.allResourceRoots(deploymentUnit);\n for (ResourceRoot resourceRoot : resourceRoots) {\n if (IgnoreMetaInfMarker.isIgnoreMetaInf(resourceRoot)) {\n continue;\n }\n Manifest manifest = getManifest(resourceRoot);\n if (manifest != null)\n resourceRoot.putAttachment(Attachments.MANIFEST, manifest);\n }\n }",
"public static int[] longestWord(LinkedList<AT_Row> rows, int colNumbers){\r\n\t\tif(rows==null){\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\tif(rows.size()==0){\r\n\t\t\treturn new int[0];\r\n\t\t}\r\n\r\n\t\tint[] ret = new int[colNumbers];\r\n\r\n\t\tfor(AT_Row row : rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT) {\r\n\t\t\t\tLinkedList<AT_Cell> cells = row.getCells();\r\n\r\n\t\t\t\tfor(int i=0; i<cells.size(); i++) {\r\n\t\t\t\t\tif(cells.get(i).getContent()!=null){\r\n\t\t\t\t\t\tString[] ar = StringUtils.split(Object_To_StrBuilder.convert(cells.get(i).getContent()).toString());\r\n\t\t\t\t\t\tfor(int k=0; k<ar.length; k++){\r\n\t\t\t\t\t\t\tint count = ar[k].length() + cells.get(i).getContext().getPaddingLeft() + cells.get(i).getContext().getPaddingRight();\r\n\t\t\t\t\t\t\tif(count>ret[i]){\r\n\t\t\t\t\t\t\t\tret[i] = count;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn ret;\r\n\t}"
] |
Remove an read lock. | [
"public boolean removeReader(Object key, Object resourceId)\r\n {\r\n boolean result = false;\r\n ObjectLocks objectLocks = null;\r\n synchronized(locktable)\r\n {\r\n objectLocks = (ObjectLocks) locktable.get(resourceId);\r\n if(objectLocks != null)\r\n {\r\n /**\r\n * MBAIRD, last one out, close the door and turn off the lights.\r\n * if no locks (readers or writers) exist for this object, let's remove\r\n * it from the locktable.\r\n */\r\n Map readers = objectLocks.getReaders();\r\n result = readers.remove(key) != null;\r\n if((objectLocks.getWriter() == null) && (readers.size() == 0))\r\n {\r\n locktable.remove(resourceId);\r\n }\r\n }\r\n }\r\n return result;\r\n }"
] | [
"public static nspbr6 get(nitro_service service, String name) throws Exception{\n\t\tnspbr6 obj = new nspbr6();\n\t\tobj.set_name(name);\n\t\tnspbr6 response = (nspbr6) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static BuildRetention createBuildRetention(Run build, boolean discardOldArtifacts) {\n BuildRetention buildRetention = new BuildRetention(discardOldArtifacts);\n LogRotator rotator = null;\n BuildDiscarder buildDiscarder = build.getParent().getBuildDiscarder();\n if (buildDiscarder != null && buildDiscarder instanceof LogRotator) {\n rotator = (LogRotator) buildDiscarder;\n }\n if (rotator == null) {\n return buildRetention;\n }\n if (rotator.getNumToKeep() > -1) {\n buildRetention.setCount(rotator.getNumToKeep());\n }\n if (rotator.getDaysToKeep() > -1) {\n Calendar calendar = Calendar.getInstance();\n calendar.add(Calendar.DAY_OF_YEAR, -rotator.getDaysToKeep());\n buildRetention.setMinimumBuildDate(new Date(calendar.getTimeInMillis()));\n }\n List<String> notToBeDeleted = ExtractorUtils.getBuildNumbersNotToBeDeleted(build);\n buildRetention.setBuildNumbersNotToBeDiscarded(notToBeDeleted);\n return buildRetention;\n }",
"public URL buildWithQuery(String base, String queryString, Object... values) {\n String urlString = String.format(base + this.template, values) + queryString;\n URL url = null;\n try {\n url = new URL(urlString);\n } catch (MalformedURLException e) {\n assert false : \"An invalid URL template indicates a bug in the SDK.\";\n }\n\n return url;\n }",
"public static void directoryCheck(String dir) throws IOException {\n\t\tfinal File file = new File(dir);\n\n\t\tif (!file.exists()) {\n\t\t\tFileUtils.forceMkdir(file);\n\t\t}\n\t}",
"ValidationResult isRestrictedEventName(String name) {\n ValidationResult error = new ValidationResult();\n if (name == null) {\n error.setErrorCode(510);\n error.setErrorDesc(\"Event Name is null\");\n return error;\n }\n for (String x : restrictedNames)\n if (name.equalsIgnoreCase(x)) {\n // The event name is restricted\n\n error.setErrorCode(513);\n error.setErrorDesc(name + \" is a restricted event name. Last event aborted.\");\n Logger.v(name + \" is a restricted system event name. Last event aborted.\");\n return error;\n }\n return error;\n }",
"private void processColumns()\n {\n int fieldID = MPPUtility.getInt(m_data, m_headerOffset);\n m_headerOffset += 4;\n\n m_dataOffset = MPPUtility.getInt(m_data, m_headerOffset);\n m_headerOffset += 4;\n\n FieldType type = FieldTypeHelper.getInstance(fieldID);\n if (type.getDataType() != null)\n {\n processKnownType(type);\n }\n }",
"public static URL buildUrl(String scheme, String host, int port, String path, Map<String, String> parameters) throws MalformedURLException {\r\n checkSchemeAndPort(scheme, port);\r\n StringBuilder buffer = new StringBuilder();\r\n if (!host.startsWith(scheme + \"://\")) {\r\n buffer.append(scheme).append(\"://\");\r\n }\r\n buffer.append(host);\r\n if (port > 0) {\r\n buffer.append(':');\r\n buffer.append(port);\r\n }\r\n if (path == null) {\r\n path = \"/\";\r\n }\r\n buffer.append(path);\r\n\r\n if (!parameters.isEmpty()) {\r\n buffer.append('?');\r\n }\r\n int size = parameters.size();\r\n for (Map.Entry<String, String> entry : parameters.entrySet()) {\r\n buffer.append(entry.getKey());\r\n buffer.append('=');\r\n Object value = entry.getValue();\r\n if (value != null) {\r\n String string = value.toString();\r\n try {\r\n string = URLEncoder.encode(string, UTF8);\r\n } catch (UnsupportedEncodingException e) {\r\n // Should never happen, but just in case\r\n }\r\n buffer.append(string);\r\n }\r\n if (--size != 0) {\r\n buffer.append('&');\r\n }\r\n }\r\n\r\n /*\r\n * RequestContext requestContext = RequestContext.getRequestContext(); Auth auth = requestContext.getAuth(); if (auth != null &&\r\n * !ignoreMethod(getMethod(parameters))) { buffer.append(\"&api_sig=\"); buffer.append(AuthUtilities.getSignature(sharedSecret, parameters)); }\r\n */\r\n\r\n return new URL(buffer.toString());\r\n }",
"public synchronized void submitOperation(int requestId, AsyncOperation operation) {\n if(this.operations.containsKey(requestId))\n throw new VoldemortException(\"Request \" + requestId\n + \" already submitted to the system\");\n\n this.operations.put(requestId, operation);\n scheduler.scheduleNow(operation);\n logger.debug(\"Handling async operation \" + requestId);\n }",
"public ServerGroup addServerGroup(String groupName) {\n ServerGroup group = new ServerGroup();\n\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"name\", groupName),\n new BasicNameValuePair(\"profileIdentifier\", this._profileName)\n };\n try {\n JSONObject response = new JSONObject(doPost(BASE_SERVERGROUP, params));\n group = getServerGroupFromJSON(response);\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n return group;\n }"
] |
if you want to parse an argument, you need a converter from String to Object
@param commandLineOption specification of the command line options
@param converter how to convert your String value to a castable Object | [
"public ConfigOptionBuilder setCommandLineOptionWithArgument( CommandLineOption commandLineOption, StringConverter converter ) {\n co.setCommandLineOption( commandLineOption );\n return setStringConverter( converter );\n }"
] | [
"public static Diagram parseJson(JSONObject json,\n Boolean keepGlossaryLink) throws JSONException {\n ArrayList<Shape> shapes = new ArrayList<Shape>();\n HashMap<String, JSONObject> flatJSON = flatRessources(json);\n for (String resourceId : flatJSON.keySet()) {\n parseRessource(shapes,\n flatJSON,\n resourceId,\n keepGlossaryLink);\n }\n String id = \"canvas\";\n\n if (json.has(\"resourceId\")) {\n id = json.getString(\"resourceId\");\n shapes.remove(new Shape(id));\n }\n ;\n Diagram diagram = new Diagram(id);\n\n // remove Diagram\n // (Diagram)getShapeWithId(json.getString(\"resourceId\"), shapes);\n parseStencilSet(json,\n diagram);\n parseSsextensions(json,\n diagram);\n parseStencil(json,\n diagram);\n parseProperties(json,\n diagram,\n keepGlossaryLink);\n parseChildShapes(shapes,\n json,\n diagram);\n parseBounds(json,\n diagram);\n diagram.setShapes(shapes);\n return diagram;\n }",
"public List<String> filterAddonResources(Addon addon, Predicate<String> filter)\n {\n List<String> discoveredFileNames = new ArrayList<>();\n List<File> addonResources = addon.getRepository().getAddonResources(addon.getId());\n for (File addonFile : addonResources)\n {\n if (addonFile.isDirectory())\n handleDirectory(filter, addonFile, discoveredFileNames);\n else\n handleArchiveByFile(filter, addonFile, discoveredFileNames);\n }\n return discoveredFileNames;\n }",
"public synchronized int get(byte[] dst, int off, int len) {\n if (available == 0) {\n return 0;\n }\n\n // limit is last index to read + 1\n int limit = idxGet < idxPut ? idxPut : capacity;\n int count = Math.min(limit - idxGet, len);\n System.arraycopy(buffer, idxGet, dst, off, count);\n idxGet += count;\n\n if (idxGet == capacity) {\n // Array end reached, check if we have more\n int count2 = Math.min(len - count, idxPut);\n if (count2 > 0) {\n System.arraycopy(buffer, 0, dst, off + count, count2);\n idxGet = count2;\n count += count2;\n } else {\n idxGet = 0;\n }\n }\n available -= count;\n return count;\n }",
"public synchronized void stop() throws DatastoreEmulatorException {\n // We intentionally don't check the internal state. If people want to try and stop the server\n // multiple times that's fine.\n stopEmulatorInternal();\n if (state != State.STOPPED) {\n state = State.STOPPED;\n if (projectDirectory != null) {\n try {\n Process process =\n new ProcessBuilder(\"rm\", \"-r\", projectDirectory.getAbsolutePath()).start();\n if (process.waitFor() != 0) {\n throw new IOException(\n \"Temporary project directory deletion exited with \" + process.exitValue());\n }\n } catch (IOException e) {\n throw new IllegalStateException(\"Could not delete temporary project directory\", e);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n throw new IllegalStateException(\"Could not delete temporary project directory\", e);\n }\n }\n }\n }",
"public static <T> T callConstructor(Class<T> klass, Object[] args) {\n Class<?>[] klasses = new Class[args.length];\n for(int i = 0; i < args.length; i++)\n klasses[i] = args[i].getClass();\n return callConstructor(klass, klasses, args);\n }",
"static Type getRawType(Type genericType, Map<TypeVariable, Type> typeVariableMap) {\n\t\tType resolvedType = genericType;\n\t\tif (genericType instanceof TypeVariable) {\n\t\t\tTypeVariable tv = (TypeVariable) genericType;\n\t\t\tresolvedType = typeVariableMap.get(tv);\n\t\t\tif (resolvedType == null) {\n\t\t\t\tresolvedType = extractBoundForTypeVariable(tv);\n\t\t\t}\n\t\t}\n\t\tif (resolvedType instanceof ParameterizedType) {\n\t\t\treturn ((ParameterizedType) resolvedType).getRawType();\n\t\t}\n\t\telse {\n\t\t\treturn resolvedType;\n\t\t}\n\t}",
"public Integer next() {\n\t\tfor(int i = currentIndex; i < t.size(); i++){\n\t\t\tif(i+timelag>=t.size()){\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif((t.get(i) != null) && (t.get(i+timelag) != null)){\n\t\t\t\tif(overlap){\n\t\t\t\t\tcurrentIndex = i+1;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tcurrentIndex = i+timelag;\n\t\t\t\t}\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn null;\n\t}",
"public static String join(int[] array, String separator) {\n if (array != null) {\n StringBuilder buf = new StringBuilder(Math.max(16, (separator.length() + 1) * array.length));\n char singleChar = separator.length() == 1 ? separator.charAt(0) : 0;\n for (int i = 0; i < array.length; i++) {\n if (i != 0) {\n if (singleChar != 0) {\n // More efficient\n buf.append(singleChar);\n } else {\n buf.append(separator);\n }\n }\n buf.append(array[i]);\n }\n return buf.toString();\n } else {\n return \"\";\n }\n }",
"private void copy(InputStream input, OutputStream output) throws IOException {\n try {\n byte[] buffer = new byte[BUFFER_SIZE];\n int bytesRead = input.read(buffer);\n while (bytesRead != -1) {\n output.write(buffer, 0, bytesRead);\n bytesRead = input.read(buffer);\n }\n } finally {\n input.close();\n output.close();\n }\n }"
] |
Use this API to fetch tmtrafficpolicy_lbvserver_binding resources of given name . | [
"public static tmtrafficpolicy_lbvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\ttmtrafficpolicy_lbvserver_binding obj = new tmtrafficpolicy_lbvserver_binding();\n\t\tobj.set_name(name);\n\t\ttmtrafficpolicy_lbvserver_binding response[] = (tmtrafficpolicy_lbvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"public static base_responses enable(nitro_service client, String trapname[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (trapname != null && trapname.length > 0) {\n\t\t\tsnmpalarm enableresources[] = new snmpalarm[trapname.length];\n\t\t\tfor (int i=0;i<trapname.length;i++){\n\t\t\t\tenableresources[i] = new snmpalarm();\n\t\t\t\tenableresources[i].trapname = trapname[i];\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, enableresources,\"enable\");\n\t\t}\n\t\treturn result;\n\t}",
"@Deprecated\r\n private InputStream getImageAsStream(String suffix) throws IOException {\r\n StringBuffer buffer = getBaseImageUrl();\r\n buffer.append(suffix);\r\n return _getImageAsStream(buffer.toString());\r\n }",
"private void ensureConversion(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n // we issue a warning if we encounter a field with a java.util.Date java type without a conversion\r\n if (\"java.util.Date\".equals(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JAVA_TYPE)) &&\r\n !fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_CONVERSION))\r\n {\r\n LogHelper.warn(true,\r\n FieldDescriptorConstraints.class,\r\n \"ensureConversion\",\r\n \"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\r\n \" of type java.util.Date is directly mapped to jdbc-type \"+\r\n fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE)+\r\n \". However, most JDBC drivers can't handle java.util.Date directly so you might want to \"+\r\n \" use a conversion for converting it to a JDBC datatype like TIMESTAMP.\");\r\n }\r\n\r\n String conversionClass = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_CONVERSION);\r\n\r\n if (((conversionClass == null) || (conversionClass.length() == 0)) &&\r\n fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_CONVERSION) &&\r\n fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_JDBC_TYPE).equals(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE)))\r\n {\r\n conversionClass = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_CONVERSION);\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_CONVERSION, conversionClass);\r\n }\r\n // now checking\r\n if (CHECKLEVEL_STRICT.equals(checkLevel) && (conversionClass != null) && (conversionClass.length() > 0))\r\n {\r\n InheritanceHelper helper = new InheritanceHelper();\r\n\r\n try\r\n {\r\n if (!helper.isSameOrSubTypeOf(conversionClass, CONVERSION_INTERFACE))\r\n {\r\n throw new ConstraintException(\"The conversion class specified for field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" does not implement the necessary interface \"+CONVERSION_INTERFACE);\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"The class \"+ex.getMessage()+\" hasn't been found on the classpath while checking the conversion class specified for field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName());\r\n }\r\n }\r\n}",
"public void setColorRange(int firstIndex, int lastIndex, int color) {\n\t\tfor (int i = firstIndex; i <= lastIndex; i++)\n\t\t\tmap[i] = color;\n\t}",
"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 static base_responses enable(nitro_service client, Long clid[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (clid != null && clid.length > 0) {\n\t\t\tclusterinstance enableresources[] = new clusterinstance[clid.length];\n\t\t\tfor (int i=0;i<clid.length;i++){\n\t\t\t\tenableresources[i] = new clusterinstance();\n\t\t\t\tenableresources[i].clid = clid[i];\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, enableresources,\"enable\");\n\t\t}\n\t\treturn result;\n\t}",
"public void validateOperations(final List<ModelNode> operations) {\n if (operations == null) {\n return;\n }\n\n for (ModelNode operation : operations) {\n try {\n validateOperation(operation);\n } catch (RuntimeException e) {\n if (exitOnError) {\n throw e;\n } else {\n System.out.println(\"---- Operation validation error:\");\n System.out.println(e.getMessage());\n }\n\n }\n }\n }",
"protected void checkVariableName(GraphRewrite event, EvaluationContext context)\n {\n if (variableName == null)\n {\n setVariableName(Iteration.getPayloadVariableName(event, context));\n }\n }",
"public String getResourcePath()\n {\n switch (resourceType)\n {\n case ANDROID_ASSETS: return assetPath;\n\n case ANDROID_RESOURCE: return resourceFilePath;\n\n case LINUX_FILESYSTEM: return filePath;\n\n case NETWORK: return url.getPath();\n\n case INPUT_STREAM: return inputStreamName;\n\n default: return null;\n }\n }"
] |
Gets the property and casts to the appropriate type
@param <T>
@param key The property name
@param type The property type
@return The value of the property | [
"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 }"
] | [
"public static void acceptsZone(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_Z, OPT_ZONE), \"zone id\")\n .withRequiredArg()\n .describedAs(\"zone-id\")\n .ofType(Integer.class);\n }",
"public static KnowledgeBuilderConfiguration newKnowledgeBuilderConfiguration(Properties properties,\n ClassLoader... classLoaders) {\n return FactoryServiceHolder.factoryService.newKnowledgeBuilderConfiguration( properties, classLoaders );\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 ResultAction getFailedResultAction(Throwable cause) {\n if (currentStage == Stage.MODEL || cancelled || isRollbackOnRuntimeFailure() || isRollbackOnly()\n || (cause != null && !(cause instanceof OperationFailedException))) {\n return ResultAction.ROLLBACK;\n }\n return ResultAction.KEEP;\n }",
"public static <K,V> Map<K,V> minus(Map<K,V> self, Map removeMe) {\n final Map<K,V> ansMap = createSimilarMap(self);\n ansMap.putAll(self);\n if (removeMe != null && removeMe.size() > 0) {\n for (Map.Entry<K, V> e1 : self.entrySet()) {\n for (Object e2 : removeMe.entrySet()) {\n if (DefaultTypeTransformation.compareEqual(e1, e2)) {\n ansMap.remove(e1.getKey());\n }\n }\n }\n }\n return ansMap;\n }",
"private void initEditorStates() {\n\n m_editorState = new HashMap<CmsMessageBundleEditorTypes.EditMode, EditorState>();\n List<TableProperty> cols = null;\n switch (m_bundleType) {\n case PROPERTY:\n case XML:\n if (hasDescriptor()) { // bundle descriptor is present, keys are not editable in default mode, maybe master mode is available\n m_editorState.put(CmsMessageBundleEditorTypes.EditMode.DEFAULT, getDefaultState());\n if (hasMasterMode()) { // the bundle descriptor is editable\n m_editorState.put(CmsMessageBundleEditorTypes.EditMode.MASTER, getMasterState());\n }\n } else { // no bundle descriptor given - implies no master mode\n cols = new ArrayList<TableProperty>(1);\n cols.add(TableProperty.KEY);\n cols.add(TableProperty.TRANSLATION);\n m_editorState.put(CmsMessageBundleEditorTypes.EditMode.DEFAULT, new EditorState(cols, true));\n }\n break;\n case DESCRIPTOR:\n cols = new ArrayList<TableProperty>(3);\n cols.add(TableProperty.KEY);\n cols.add(TableProperty.DESCRIPTION);\n cols.add(TableProperty.DEFAULT);\n m_editorState.put(CmsMessageBundleEditorTypes.EditMode.DEFAULT, new EditorState(cols, true));\n break;\n default:\n throw new IllegalArgumentException();\n }\n\n }",
"private boolean isSingleMultiDay() {\n\n long duration = getEnd().getTime() - getStart().getTime();\n if (duration > I_CmsSerialDateValue.DAY_IN_MILLIS) {\n return true;\n }\n if (isWholeDay() && (duration <= I_CmsSerialDateValue.DAY_IN_MILLIS)) {\n return false;\n }\n Calendar start = new GregorianCalendar();\n start.setTime(getStart());\n Calendar end = new GregorianCalendar();\n end.setTime(getEnd());\n if (start.get(Calendar.DAY_OF_MONTH) == end.get(Calendar.DAY_OF_MONTH)) {\n return false;\n }\n return 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 static void parseChildShapes(ArrayList<Shape> shapes,\n JSONObject modelJSON,\n Shape current) throws JSONException {\n if (modelJSON.has(\"childShapes\")) {\n ArrayList<Shape> childShapes = new ArrayList<Shape>();\n\n JSONArray childShapeObject = modelJSON.getJSONArray(\"childShapes\");\n for (int i = 0; i < childShapeObject.length(); i++) {\n childShapes.add(getShapeWithId(childShapeObject.getJSONObject(i).getString(\"resourceId\"),\n shapes));\n }\n if (childShapes.size() > 0) {\n for (Shape each : childShapes) {\n each.setParent(current);\n }\n current.setChildShapes(childShapes);\n }\n ;\n }\n }"
] |
Release the broker instance. | [
"protected synchronized void releaseBroker(PersistenceBroker broker)\r\n {\r\n /*\r\n arminw:\r\n only close the broker instance if we get\r\n it from the PBF, do nothing if we obtain it from\r\n PBThreadMapping\r\n */\r\n if (broker != null && _needsClose)\r\n {\r\n _needsClose = false;\r\n broker.close();\r\n }\r\n }"
] | [
"public T addModule(final String moduleName, final String slot, final byte[] newHash) {\n final ContentItem item = createModuleItem(moduleName, slot, newHash);\n addContentModification(createContentModification(item, ModificationType.ADD, NO_CONTENT));\n return returnThis();\n }",
"public void evictCache(String key) {\n H.Session sess = session();\n if (null != sess) {\n sess.evict(key);\n } else {\n app().cache().evict(key);\n }\n }",
"public static nslimitselector[] get(nitro_service service) throws Exception{\n\t\tnslimitselector obj = new nslimitselector();\n\t\tnslimitselector[] response = (nslimitselector[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void notifyIfStopped() {\n if (isAcceptingNewJobs() || !this.runningTasksFutures.isEmpty()) {\n return;\n }\n final File stoppedFile = new File(this.workingDirectories.getWorking(), \"stopped\");\n try {\n LOGGER.info(\"The print has finished processing jobs and can now stop\");\n stoppedFile.createNewFile();\n } catch (IOException e) {\n LOGGER.warn(\"Cannot create the {} file\", stoppedFile, e);\n }\n }",
"public static boolean setCustomRequestForDefaultProfile(String pathName, String customData) {\n try {\n return setCustomForDefaultProfile(pathName, false, customData);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }",
"private void configureConfigurationSelector() {\n\n if (m_checkinBean.getConfigurations().size() < 2) {\n // Do not show the configuration selection at all.\n removeComponent(m_configurationSelectionPanel);\n } else {\n for (CmsGitConfiguration configuration : m_checkinBean.getConfigurations()) {\n m_configurationSelector.addItem(configuration);\n m_configurationSelector.setItemCaption(configuration, configuration.getName());\n }\n m_configurationSelector.setNullSelectionAllowed(false);\n m_configurationSelector.setNewItemsAllowed(false);\n m_configurationSelector.setWidth(\"350px\");\n m_configurationSelector.select(m_checkinBean.getCurrentConfiguration());\n\n // There is really a choice between configurations\n m_configurationSelector.addValueChangeListener(new ValueChangeListener() {\n\n private static final long serialVersionUID = 1L;\n\n @SuppressWarnings(\"synthetic-access\")\n public void valueChange(ValueChangeEvent event) {\n\n updateForNewConfiguration((CmsGitConfiguration)event.getProperty().getValue());\n restoreFieldsFromUserInfo();\n\n }\n });\n }\n }",
"boolean openStream() throws InterruptedException, IOException {\n logger.info(\"stream START\");\n final boolean isOpen;\n final Set<BsonValue> idsToWatch = nsConfig.getSynchronizedDocumentIds();\n\n if (!networkMonitor.isConnected()) {\n logger.info(\"stream END - Network disconnected\");\n return false;\n }\n\n if (idsToWatch.isEmpty()) {\n logger.info(\"stream END - No synchronized documents\");\n return false;\n }\n\n nsLock.writeLock().lockInterruptibly();\n try {\n if (!authMonitor.isLoggedIn()) {\n logger.info(\"stream END - Logged out\");\n return false;\n }\n\n final Document args = new Document();\n args.put(\"database\", namespace.getDatabaseName());\n args.put(\"collection\", namespace.getCollectionName());\n args.put(\"ids\", idsToWatch);\n\n currentStream =\n service.streamFunction(\n \"watch\",\n Collections.singletonList(args),\n ResultDecoders.changeEventDecoder(BSON_DOCUMENT_CODEC));\n\n if (currentStream != null && currentStream.isOpen()) {\n this.nsConfig.setStale(true);\n isOpen = true;\n } else {\n isOpen = false;\n }\n } finally {\n nsLock.writeLock().unlock();\n }\n return isOpen;\n }",
"public String format() {\r\n if (getName().equals(\"*\")) {\r\n return \"*\";\r\n }\r\n else {\r\n StringBuilder sb = new StringBuilder();\r\n if (isWeak()) {\r\n sb.append(\"W/\");\r\n }\r\n return sb.append('\"').append(getName()).append('\"').toString();\r\n }\r\n }",
"public static CmsResourceTypeStatResultList init(CmsResourceTypeStatResultList resList) {\n\n if (resList == null) {\n return new CmsResourceTypeStatResultList();\n }\n\n resList.deleteOld();\n return resList;\n }"
] |
Adds a corporate groupId to an organization
@param organizationId String
@param corporateGroupId String | [
"public void addCorporateGroupId(final String organizationId, final String corporateGroupId) {\n final DbOrganization dbOrganization = getOrganization(organizationId);\n\n if(!dbOrganization.getCorporateGroupIdPrefixes().contains(corporateGroupId)){\n dbOrganization.getCorporateGroupIdPrefixes().add(corporateGroupId);\n repositoryHandler.store(dbOrganization);\n }\n\n repositoryHandler.addModulesOrganization(corporateGroupId, dbOrganization);\n }"
] | [
"public void setPermissions(Permissions permissions) {\n if (this.permissions == permissions) {\n return;\n }\n\n this.removeChildObject(\"permissions\");\n this.permissions = permissions;\n this.addChildObject(\"permissions\", permissions);\n }",
"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 WebSocketContext sendToTagged(String message, String tag) {\n return sendToTagged(message, tag, false);\n }",
"protected Object doInvoke(Object proxy, Method methodToBeInvoked, Object[] args)\r\n\t\tthrows Throwable\r\n\t{\r\n\t\tMethod m =\r\n\t\t\tgetRealSubject().getClass().getMethod(\r\n\t\t\t\tmethodToBeInvoked.getName(),\r\n\t\t\t\tmethodToBeInvoked.getParameterTypes());\r\n\t\treturn m.invoke(getRealSubject(), args);\r\n\t}",
"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 JmsDestinationType getTypeFromClass(String aClass)\n {\n if (StringUtils.equals(aClass, \"javax.jms.Queue\") || StringUtils.equals(aClass, \"javax.jms.QueueConnectionFactory\"))\n {\n return JmsDestinationType.QUEUE;\n }\n else if (StringUtils.equals(aClass, \"javax.jms.Topic\") || StringUtils.equals(aClass, \"javax.jms.TopicConnectionFactory\"))\n {\n return JmsDestinationType.TOPIC;\n }\n else\n {\n return null;\n }\n }",
"private static CmsUUID toUuid(String uuid) {\n\n if (\"null\".equals(uuid) || CmsStringUtil.isEmpty(uuid)) {\n return null;\n }\n return new CmsUUID(uuid);\n\n }",
"public static authenticationradiuspolicy_authenticationvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationradiuspolicy_authenticationvserver_binding obj = new authenticationradiuspolicy_authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationradiuspolicy_authenticationvserver_binding response[] = (authenticationradiuspolicy_authenticationvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public Duration getStartVariance()\n {\n Duration variance = (Duration) getCachedValue(AssignmentField.START_VARIANCE);\n if (variance == null)\n {\n TimeUnit format = getParentFile().getProjectProperties().getDefaultDurationUnits();\n variance = DateHelper.getVariance(getTask(), getBaselineStart(), getStart(), format);\n set(AssignmentField.START_VARIANCE, variance);\n }\n return (variance);\n }"
] |
Retrieve and validate the timestamp value from the REST request.
"X_VOLD_REQUEST_ORIGIN_TIME_MS" is timestamp header
TODO REST-Server 1. Change Time stamp header to a better name.
@return true if present, false if missing | [
"protected boolean hasTimeStampHeader() {\n String originTime = request.getHeader(RestMessageHeaders.X_VOLD_REQUEST_ORIGIN_TIME_MS);\n boolean result = false;\n if(originTime != null) {\n try {\n // TODO: remove the originTime field from request header,\n // because coordinator should not accept the request origin time\n // from the client.. In this commit, we only changed\n // \"this.parsedRequestOriginTimeInMs\" from\n // \"Long.parseLong(originTime)\" to current system time,\n // The reason that we did not remove the field from request\n // header right now, is because this commit is a quick fix for\n // internal performance test to be available as soon as\n // possible.\n\n this.parsedRequestOriginTimeInMs = System.currentTimeMillis();\n if(this.parsedRequestOriginTimeInMs < 0) {\n RestErrorHandler.writeErrorResponse(messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Origin time cannot be negative \");\n\n } else {\n result = true;\n }\n } catch(NumberFormatException nfe) {\n logger.error(\"Exception when validating request. Incorrect origin time parameter. Cannot parse this to long: \"\n + originTime,\n nfe);\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Incorrect origin time parameter. Cannot parse this to long: \"\n + originTime);\n }\n } else {\n logger.error(\"Error when validating request. Missing origin time parameter.\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Missing origin time parameter.\");\n }\n return result;\n }"
] | [
"public <T> T decodeSignedRequest(String signedRequest, Class<T> type) throws SignedRequestException {\n\t\tString[] split = signedRequest.split(\"\\\\.\");\n\t\tString encodedSignature = split[0];\n\t\tString payload = split[1];\t\t\n\t\tString decoded = base64DecodeToString(payload);\t\t\n\t\tbyte[] signature = base64DecodeToBytes(encodedSignature);\n\t\ttry {\n\t\t\tT data = objectMapper.readValue(decoded, type);\t\t\t\n\t\t\tString algorithm = objectMapper.readTree(decoded).get(\"algorithm\").textValue();\n\t\t\tif (algorithm == null || !algorithm.equals(\"HMAC-SHA256\")) {\n\t\t\t\tthrow new SignedRequestException(\"Unknown encryption algorithm: \" + algorithm);\n\t\t\t}\t\t\t\n\t\t\tbyte[] expectedSignature = encrypt(payload, secret);\n\t\t\tif (!Arrays.equals(expectedSignature, signature)) {\n\t\t\t\tthrow new SignedRequestException(\"Invalid signature.\");\n\t\t\t}\t\t\t\n\t\t\treturn data;\n\t\t} catch (IOException e) {\n\t\t\tthrow new SignedRequestException(\"Error parsing payload.\", e);\n\t\t}\n\t}",
"public void setProxyClass(Class newProxyClass)\r\n {\r\n proxyClass = newProxyClass;\r\n if (proxyClass == null)\r\n {\r\n setProxyClassName(null);\r\n }\r\n else\r\n {\r\n proxyClassName = proxyClass.getName();\r\n }\r\n }",
"public float getSphereBound(float[] sphere)\n {\n if ((sphere == null) || (sphere.length != 4) ||\n ((NativeVertexBuffer.getBoundingVolume(getNative(), sphere)) < 0))\n {\n throw new IllegalArgumentException(\"Cannot copy sphere bound into array provided\");\n }\n return sphere[0];\n }",
"public TaskMode getTaskMode()\n {\n return BooleanHelper.getBoolean((Boolean) getCachedValue(TaskField.TASK_MODE)) ? TaskMode.MANUALLY_SCHEDULED : TaskMode.AUTO_SCHEDULED;\n }",
"private static int tribus(int version, int a, int b, int c) {\n if (version < 10) {\n return a;\n } else if (version >= 10 && version <= 26) {\n return b;\n } else {\n return c;\n }\n }",
"private String getRelativePomPath(MavenModule mavenModule, MavenModuleSetBuild mavenBuild) {\n String relativePath = mavenModule.getRelativePath();\n if (StringUtils.isBlank(relativePath)) {\n return POM_NAME;\n }\n\n // If this is the root module, return the root pom path.\n if (mavenModule.getModuleName().toString().\n equals(mavenBuild.getProject().getRootModule().getModuleName().toString())) {\n return mavenBuild.getProject().getRootPOM(null);\n }\n\n // to remove the project folder name if exists\n // keeps only the name of the module\n String modulePath = relativePath.substring(relativePath.indexOf(\"/\") + 1);\n for (String moduleName : mavenModules) {\n if (moduleName.contains(modulePath)) {\n return createPomPath(relativePath, moduleName);\n }\n }\n\n // In case this module is not in the parent pom\n return relativePath + \"/\" + POM_NAME;\n }",
"public Map<String,Object> getAttributeValues()\n throws AttributeNotFoundException, InstanceNotFoundException, ReflectionException {\n\n HashSet<String> attributeSet = new HashSet<String>();\n\n for (MBeanAttributeInfo attributeInfo : mBeanInfo.getAttributes()) {\n attributeSet.add(attributeInfo.getName());\n }\n\n AttributeList attributeList =\n mBeanServer.getAttributes(objectName, attributeSet.toArray(new String[attributeSet.size()]));\n\n Map<String, Object> attributeValueMap = new TreeMap<String, Object>();\n for (Attribute attribute : attributeList.asList()) {\n attributeValueMap.put(attribute.getName(), sanitizer.escapeValue(attribute.getValue()));\n }\n\n return attributeValueMap;\n }",
"private void addTransformInterceptors(List<Interceptor<?>> inInterceptors,\n List<Interceptor<?>> outInterceptors,\n boolean newClient) {\n \n // The old service expects the Customer data be qualified with\n // the 'http://customer/v1' namespace.\n \n // The new service expects the Customer data be qualified with\n // the 'http://customer/v2' namespace.\n \n // If it is an old client talking to the new service then:\n // - the out transformation interceptor is configured for \n // 'http://customer/v1' qualified data be transformed into\n // 'http://customer/v2' qualified data.\n // - the in transformation interceptor is configured for \n // 'http://customer/v2' qualified response data be transformed into\n // 'http://customer/v1' qualified data.\n \n // If it is a new client talking to the old service then:\n // - the out transformation interceptor is configured for \n // 'http://customer/v2' qualified data be transformed into\n // 'http://customer/v1' qualified data.\n // - the in transformation interceptor is configured for \n // 'http://customer/v1' qualified response data be transformed into\n // 'http://customer/v2' qualified data.\n // - new Customer type also introduces a briefDescription property\n // which needs to be dropped for the old service validation to succeed\n \n \n // this configuration can be provided externally\n \n Map<String, String> newToOldTransformMap = new HashMap<String, String>();\n newToOldTransformMap.put(\"{http://customer/v2}*\", \"{http://customer/v1}*\");\n Map<String, String> oldToNewTransformMap = \n Collections.singletonMap(\"{http://customer/v1}*\", \"{http://customer/v2}*\");\n \n TransformOutInterceptor outTransform = new TransformOutInterceptor();\n outTransform.setOutTransformElements(newClient ? newToOldTransformMap \n : oldToNewTransformMap);\n \n if (newClient) {\n newToOldTransformMap.put(\"{http://customer/v2}briefDescription\", \"\");\n //outTransform.setOutDropElements(\n // Collections.singletonList(\"{http://customer/v2}briefDescription\")); \n }\n \n TransformInInterceptor inTransform = new TransformInInterceptor();\n inTransform.setInTransformElements(newClient ? oldToNewTransformMap \n : newToOldTransformMap);\n\n inInterceptors.add(inTransform);\n outInterceptors.add(outTransform);\n \n \n }",
"@Nonnull\n public BiMap<String, String> getInputMapper() {\n final BiMap<String, String> inputMapper = this.processor.getInputMapperBiMap();\n if (inputMapper == null) {\n return HashBiMap.create();\n }\n return inputMapper;\n }"
] |
Verify that the given queues are all valid.
@param queues the given queues | [
"protected static void checkQueues(final Iterable<String> queues) {\n if (queues == null) {\n throw new IllegalArgumentException(\"queues must not be null\");\n }\n for (final String queue : queues) {\n if (queue == null || \"\".equals(queue)) {\n throw new IllegalArgumentException(\"queues' members must not be null: \" + queues);\n }\n }\n }"
] | [
"@RequestMapping(value = \"api/edit/server\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getjqRedirects(Model model,\n @RequestParam(value = \"profileId\", required = false) Integer profileId,\n @RequestParam(value = \"clientUUID\", required = true) String clientUUID,\n @RequestParam(value = \"profileIdentifier\", required = false) String profileIdentifier) throws Exception {\n if (profileId == null && profileIdentifier == null) {\n throw new Exception(\"profileId required\");\n }\n if (profileId == null) {\n profileId = ProfileService.getInstance().getIdFromName(profileIdentifier);\n }\n int clientId = ClientService.getInstance().findClient(clientUUID, profileId).getId();\n\n HashMap<String, Object> returnJson = Utils.getJQGridJSON(ServerRedirectService.getInstance().tableServers(clientId), \"servers\");\n returnJson.put(\"hostEditor\", Client.isAvailable());\n return returnJson;\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<BritishCutoverDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<BritishCutoverDate>) super.zonedDateTime(temporal);\n }",
"private void updateSortedServices() {\n List<T> copiedList = new ArrayList<T>(serviceMap.values());\n sortedServices = Collections.unmodifiableList(copiedList);\n if (changeListener != null) {\n changeListener.changed();\n }\n }",
"public Object materializeObject(ClassDescriptor cld, Identity oid)\r\n throws PersistenceBrokerException\r\n {\r\n final StatementManagerIF sm = broker.serviceStatementManager();\r\n final SelectStatement sql = broker.serviceSqlGenerator().getPreparedSelectByPkStatement(cld);\r\n Object result = null;\r\n PreparedStatement stmt = null;\r\n ResultSet rs = null;\r\n try\r\n {\r\n stmt = sm.getSelectByPKStatement(cld);\r\n if (stmt == null)\r\n {\r\n logger.error(\"getSelectByPKStatement returned a null statement\");\r\n throw new PersistenceBrokerException(\"getSelectByPKStatement returned a null statement\");\r\n }\r\n /*\r\n arminw: currently a select by PK could never be a stored procedure,\r\n thus we can always set 'false'. Is this correct??\r\n */\r\n sm.bindSelect(stmt, oid, cld, false);\r\n rs = stmt.executeQuery();\r\n // data available read object, else return null\r\n ResultSetAndStatement rs_stmt = new ResultSetAndStatement(broker.serviceStatementManager(), stmt, rs, sql);\r\n if (rs.next())\r\n {\r\n Map row = new HashMap();\r\n cld.getRowReader().readObjectArrayFrom(rs_stmt, row);\r\n result = cld.getRowReader().readObjectFrom(row);\r\n }\r\n // close resources\r\n rs_stmt.close();\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n // release resources on exception\r\n sm.closeResources(stmt, rs);\r\n logger.error(\"PersistenceBrokerException during the execution of materializeObject: \" + e.getMessage(), e);\r\n throw e;\r\n }\r\n catch (SQLException e)\r\n {\r\n // release resources on exception\r\n sm.closeResources(stmt, rs);\r\n throw ExceptionHelper.generateException(e, sql.getStatement(), cld, logger, null);\r\n }\r\n return result;\r\n }",
"@SuppressWarnings(\"WeakerAccess\")\n public String formatCueCountdown() {\n int count = getCueCountdown();\n\n if (count == 511) {\n return \"--.-\";\n }\n\n if ((count >= 1) && (count <= 256)) {\n int bars = (count - 1) / 4;\n int beats = ((count - 1) % 4) + 1;\n return String.format(\"%02d.%d\", bars, beats);\n }\n\n if (count == 0) {\n return \"00.0\";\n }\n\n return \"??.?\";\n }",
"@Override\n public CopticDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }",
"protected static PatchElement createPatchElement(final PatchEntry entry, String patchId, final List<ContentModification> modifications) {\n final PatchElement patchElement = entry.element;\n final PatchElementImpl element = new PatchElementImpl(patchId);\n element.setProvider(patchElement.getProvider());\n // Add all the rollback actions\n element.getModifications().addAll(modifications);\n element.setDescription(patchElement.getDescription());\n return element;\n }",
"public GroovyFieldDoc[] enumConstants() {\n Collections.sort(enumConstants);\n return enumConstants.toArray(new GroovyFieldDoc[enumConstants.size()]);\n }",
"protected void restoreAutoCommitState()\r\n {\r\n try\r\n {\r\n if(!broker.isManaged())\r\n {\r\n if (jcd.getUseAutoCommit() == JdbcConnectionDescriptor.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE\r\n && originalAutoCommitState == true && con != null && !con.isClosed())\r\n {\r\n platform.changeAutoCommitState(jcd, con, true);\r\n }\r\n }\r\n else\r\n {\r\n if(log.isDebugEnabled()) log.debug(\r\n \"Found managed environment setting in PB, will skip Platform.changeAutoCommitState(...) call\");\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n // should never be reached\r\n throw new OJBRuntimeException(\"Restore of connection autocommit state failed\", e);\r\n }\r\n }"
] |
Set the active view.
If the mdActiveIndicator attribute is set, this View will have the indicator drawn next to it.
@param v The active view.
@param position Optional position, usually used with ListView. v.setTag(R.id.mdActiveViewPosition, position)
must be called first. | [
"public void setActiveView(View v, int position) {\n final View oldView = mActiveView;\n mActiveView = v;\n mActivePosition = position;\n\n if (mAllowIndicatorAnimation && oldView != null) {\n startAnimatingIndicator();\n }\n\n invalidate();\n }"
] | [
"public static String getOperationName(final ModelNode op) {\n if (op.hasDefined(OP)) {\n return op.get(OP).asString();\n }\n throw ControllerClientLogger.ROOT_LOGGER.operationNameNotFound();\n }",
"public double getProgressFromResponse(ResponseOnSingeRequest myResponse) {\n\n double progress = 0.0;\n try {\n\n if (myResponse == null || myResponse.isFailObtainResponse()) {\n return progress;\n }\n\n String responseBody = myResponse.getResponseBody();\n Pattern regex = Pattern.compile(progressRegex);\n Matcher matcher = regex.matcher(responseBody);\n if (matcher.matches()) {\n String progressStr = matcher.group(1);\n progress = Double.parseDouble(progressStr);\n }\n\n } catch (Exception t) {\n logger.error(\"fail \" + t);\n\n }\n\n return progress;\n }",
"protected void appendWhereClause(StringBuffer stmt, Object[] columns)\r\n {\r\n stmt.append(\" WHERE \");\r\n\r\n for (int i = 0; i < columns.length; i++)\r\n {\r\n if (i > 0)\r\n {\r\n stmt.append(\" AND \");\r\n }\r\n stmt.append(columns[i]);\r\n stmt.append(\"=?\");\r\n }\r\n }",
"public Collection<Method> getAllMethods(String name) {\n final Map<ParamList, Map<Class<?>, Method>> nameMap = methods.get(name);\n if (nameMap == null) {\n return Collections.emptySet();\n }\n final Collection<Method> methods = new ArrayList<Method>();\n for (Map<Class<?>, Method> map : nameMap.values()) {\n methods.addAll(map.values());\n }\n return methods;\n }",
"synchronized void removeUserProfile(String id) {\n\n if (id == null) return;\n final String tableName = Table.USER_PROFILES.getName();\n try {\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n db.delete(tableName, \"_id = ?\", new String[]{id});\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Error removing user profile from \" + tableName + \" Recreating DB\");\n dbHelper.deleteDatabase();\n } finally {\n dbHelper.close();\n }\n }",
"public void setScriptText(String scriptText, String language)\n {\n GVRScriptFile newScript = new GVRJavascriptScriptFile(getGVRContext(), scriptText);\n mLanguage = GVRScriptManager.LANG_JAVASCRIPT;\n setScriptFile(newScript);\n }",
"public boolean contains(String id) {\n assertNotEmpty(id, \"id\");\n InputStream response = null;\n try {\n response = couchDbClient.head(new DatabaseURIHelper(dbUri).documentUri(id));\n } catch (NoDocumentException e) {\n return false;\n } finally {\n close(response);\n }\n return true;\n }",
"public int getIndexMin() {\n int indexMin = 0;\n double min = getEigenvalue(0).getMagnitude2();\n\n final int N = getNumberOfEigenvalues();\n for( int i = 1; i < N; i++ ) {\n double m = getEigenvalue(i).getMagnitude2();\n if( m < min ) {\n min = m;\n indexMin = i;\n }\n }\n\n return indexMin;\n }",
"protected TextBox createTextBox(BlockBox contblock, Text n)\n {\n TextBox text = new TextBox(n, (Graphics2D) contblock.getGraphics().create(), contblock.getVisualContext().create());\n text.setOrder(next_order++);\n text.setContainingBlockBox(contblock);\n text.setClipBlock(contblock);\n text.setViewport(viewport);\n text.setBase(baseurl);\n return text;\n }"
] |
Add a module to a module tree
@param module
@param tree | [
"private void addModuleToTree(final DbModule module, final TreeNode tree) {\n final TreeNode subTree = new TreeNode();\n subTree.setName(module.getName());\n tree.addChild(subTree);\n\n // Add SubsubModules\n for (final DbModule subsubmodule : module.getSubmodules()) {\n addModuleToTree(subsubmodule, subTree);\n }\n }"
] | [
"public void addLicense(final String gavc, final String licenseId) {\n final DbArtifact dbArtifact = getArtifact(gavc);\n\n // Try to find an existing license that match the new one\n final LicenseHandler licenseHandler = new LicenseHandler(repositoryHandler);\n final DbLicense license = licenseHandler.resolve(licenseId);\n\n // If there is no existing license that match this one let's use the provided value but\n // only if the artifact has no license yet. Otherwise it could mean that users has already\n // identify the license manually.\n if(license == null){\n if(dbArtifact.getLicenses().isEmpty()){\n LOG.warn(\"Add reference to a non existing license called \" + licenseId + \" in artifact \" + dbArtifact.getGavc());\n repositoryHandler.addLicenseToArtifact(dbArtifact, licenseId);\n }\n }\n // Add only if the license is not already referenced\n else if(!dbArtifact.getLicenses().contains(license.getName())){\n repositoryHandler.addLicenseToArtifact(dbArtifact, license.getName());\n }\n }",
"public static DMatrixRMaj convert(DMatrixRBlock src , DMatrixRMaj dst )\n {\n return ConvertDMatrixStruct.convert(src,dst);\n }",
"private Duration assignmentDuration(Task task, Duration work)\n {\n Duration result = work;\n\n if (result != null)\n {\n if (result.getUnits() == TimeUnit.PERCENT)\n {\n Duration taskWork = task.getWork();\n if (taskWork != null)\n {\n result = Duration.getInstance(taskWork.getDuration() * result.getDuration(), taskWork.getUnits());\n }\n }\n }\n return result;\n }",
"protected void switchTab() {\n\n Component tab = m_tab.getSelectedTab();\n int pos = m_tab.getTabPosition(m_tab.getTab(tab));\n if (m_isWebOU) {\n if (pos == 0) {\n pos = 1;\n }\n }\n m_tab.setSelectedTab(pos + 1);\n }",
"public void setCloseConnectionWatchTimeout(long closeConnectionWatchTimeout, TimeUnit timeUnit) {\n\t\tthis.closeConnectionWatchTimeoutInMs = TimeUnit.MILLISECONDS.convert(closeConnectionWatchTimeout, timeUnit);\n\t}",
"private static MenuDrawer createMenuDrawer(Activity activity, int dragMode, Position position, Type type) {\n MenuDrawer drawer;\n\n if (type == Type.STATIC) {\n drawer = new StaticDrawer(activity);\n\n } else if (type == Type.OVERLAY) {\n drawer = new OverlayDrawer(activity, dragMode);\n if (position == Position.LEFT || position == Position.START) {\n drawer.setupUpIndicator(activity);\n }\n\n } else {\n drawer = new SlidingDrawer(activity, dragMode);\n if (position == Position.LEFT || position == Position.START) {\n drawer.setupUpIndicator(activity);\n }\n }\n\n drawer.mDragMode = dragMode;\n drawer.setPosition(position);\n\n return drawer;\n }",
"public void addConverter(int index, IConverter converter) {\r\n\t\tconverterList.add(index, converter);\r\n\t\tif (converter instanceof IContainerConverter) {\r\n\t\t\tIContainerConverter containerConverter = (IContainerConverter) converter;\r\n\t\t\tif (containerConverter.getElementConverter() == null) {\r\n\t\t\t\tcontainerConverter.setElementConverter(elementConverter);\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"public Info getInfo() {\n BoxAPIConnection api = this.getAPI();\n URL url = COLLABORATION_URL_TEMPLATE.build(api.getBaseURL(), this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n return new Info(jsonObject);\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<Symmetry454Date> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<Symmetry454Date>) super.zonedDateTime(temporal);\n }"
] |
One of the two main methods in this class. Creates a RendererViewHolder instance with a
Renderer inside ready to be used. The RendererBuilder to create a RendererViewHolder using the
information given as parameter.
@param viewGroup used to create the ViewHolder.
@param viewType associated to the renderer.
@return ViewHolder extension with the Renderer it has to use inside. | [
"@Override public RendererViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {\n rendererBuilder.withParent(viewGroup);\n rendererBuilder.withLayoutInflater(LayoutInflater.from(viewGroup.getContext()));\n rendererBuilder.withViewType(viewType);\n RendererViewHolder viewHolder = rendererBuilder.buildRendererViewHolder();\n if (viewHolder == null) {\n throw new NullRendererBuiltException(\"RendererBuilder have to return a not null viewHolder\");\n }\n return viewHolder;\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 base_responses add(nitro_service client, sslcertkey resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslcertkey addresources[] = new sslcertkey[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new sslcertkey();\n\t\t\t\taddresources[i].certkey = resources[i].certkey;\n\t\t\t\taddresources[i].cert = resources[i].cert;\n\t\t\t\taddresources[i].key = resources[i].key;\n\t\t\t\taddresources[i].password = resources[i].password;\n\t\t\t\taddresources[i].fipskey = resources[i].fipskey;\n\t\t\t\taddresources[i].inform = resources[i].inform;\n\t\t\t\taddresources[i].passplain = resources[i].passplain;\n\t\t\t\taddresources[i].expirymonitor = resources[i].expirymonitor;\n\t\t\t\taddresources[i].notificationperiod = resources[i].notificationperiod;\n\t\t\t\taddresources[i].bundle = resources[i].bundle;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"private void appendJoin(StringBuffer where, StringBuffer buf, Join join)\r\n {\r\n buf.append(\",\");\r\n appendTableWithJoins(join.right, where, buf);\r\n if (where.length() > 0)\r\n {\r\n where.append(\" AND \");\r\n }\r\n join.appendJoinEqualities(where);\r\n }",
"public static Integer parseInteger(String value) throws ParseException\n {\n Integer result = null;\n\n if (value.length() > 0 && value.indexOf(' ') == -1)\n {\n if (value.indexOf('.') == -1)\n {\n result = Integer.valueOf(value);\n }\n else\n {\n Number n = DatatypeConverter.parseDouble(value);\n result = Integer.valueOf(n.intValue());\n }\n }\n\n return result;\n }",
"final public void addOffset(Integer start, Integer end) {\n if (tokenOffset == null) {\n setOffset(start, end);\n } else if ((start == null) || (end == null)) {\n // do nothing\n } else if (start > end) {\n throw new IllegalArgumentException(\"Start offset after end offset\");\n } else {\n tokenOffset.add(start, end);\n }\n }",
"public static rnatip_stats[] get(nitro_service service, options option) throws Exception{\n\t\trnatip_stats obj = new rnatip_stats();\n\t\trnatip_stats[] response = (rnatip_stats[])obj.stat_resources(service,option);\n\t\treturn response;\n\t}",
"public static servicegroup_lbmonitor_binding[] get(nitro_service service, String servicegroupname) throws Exception{\n\t\tservicegroup_lbmonitor_binding obj = new servicegroup_lbmonitor_binding();\n\t\tobj.set_servicegroupname(servicegroupname);\n\t\tservicegroup_lbmonitor_binding response[] = (servicegroup_lbmonitor_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"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 Face createTriangle(Vertex v0, Vertex v1, Vertex v2, double minArea) {\n Face face = new Face();\n HalfEdge he0 = new HalfEdge(v0, face);\n HalfEdge he1 = new HalfEdge(v1, face);\n HalfEdge he2 = new HalfEdge(v2, face);\n\n he0.prev = he2;\n he0.next = he1;\n he1.prev = he0;\n he1.next = he2;\n he2.prev = he1;\n he2.next = he0;\n\n face.he0 = he0;\n\n // compute the normal and offset\n face.computeNormalAndCentroid(minArea);\n return face;\n }"
] |
Enables or disabled shadow casting for a spot light.
Enabling shadows attaches a GVRShadowMap component to the
GVRSceneObject which owns the light and provides the
component with an perspective camera for shadow casting.
@param enableFlag true to enable shadow casting, false to disable | [
"public void setCastShadow(boolean enableFlag)\n {\n GVRSceneObject owner = getOwnerObject();\n\n if (owner != null)\n {\n GVRShadowMap shadowMap = (GVRShadowMap) getComponent(GVRRenderTarget.getComponentType());\n if (enableFlag)\n {\n if (shadowMap != null)\n {\n shadowMap.setEnable(true);\n }\n else\n {\n float angle = (float) Math.acos(getFloat(\"outer_cone_angle\")) * 2.0f;\n GVRCamera shadowCam = GVRShadowMap.makePerspShadowCamera(getGVRContext().getMainScene().getMainCameraRig().getCenterCamera(), angle);\n shadowMap = new GVRShadowMap(getGVRContext(), shadowCam);\n owner.attachComponent(shadowMap);\n }\n mChanged.set(true);\n }\n else if (shadowMap != null)\n {\n shadowMap.setEnable(false);\n }\n }\n mCastShadow = enableFlag;\n }"
] | [
"public static Collection<Info> getPendingCollaborations(BoxAPIConnection api) {\n URL url = PENDING_COLLABORATIONS_URL.build(api.getBaseURL());\n\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int entriesCount = responseJSON.get(\"total_count\").asInt();\n Collection<BoxCollaboration.Info> collaborations = new ArrayList<BoxCollaboration.Info>(entriesCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue entry : entries) {\n JsonObject entryObject = entry.asObject();\n BoxCollaboration collaboration = new BoxCollaboration(api, entryObject.get(\"id\").asString());\n BoxCollaboration.Info info = collaboration.new Info(entryObject);\n collaborations.add(info);\n }\n\n return collaborations;\n }",
"public static base_response update(nitro_service client, gslbservice resource) throws Exception {\n\t\tgslbservice updateresource = new gslbservice();\n\t\tupdateresource.servicename = resource.servicename;\n\t\tupdateresource.ipaddress = resource.ipaddress;\n\t\tupdateresource.publicip = resource.publicip;\n\t\tupdateresource.publicport = resource.publicport;\n\t\tupdateresource.cip = resource.cip;\n\t\tupdateresource.cipheader = resource.cipheader;\n\t\tupdateresource.sitepersistence = resource.sitepersistence;\n\t\tupdateresource.siteprefix = resource.siteprefix;\n\t\tupdateresource.maxclient = resource.maxclient;\n\t\tupdateresource.healthmonitor = resource.healthmonitor;\n\t\tupdateresource.maxbandwidth = resource.maxbandwidth;\n\t\tupdateresource.downstateflush = resource.downstateflush;\n\t\tupdateresource.maxaaausers = resource.maxaaausers;\n\t\tupdateresource.viewname = resource.viewname;\n\t\tupdateresource.viewip = resource.viewip;\n\t\tupdateresource.monthreshold = resource.monthreshold;\n\t\tupdateresource.weight = resource.weight;\n\t\tupdateresource.monitor_name_svc = resource.monitor_name_svc;\n\t\tupdateresource.hashid = resource.hashid;\n\t\tupdateresource.comment = resource.comment;\n\t\tupdateresource.appflowlog = resource.appflowlog;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public 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 }",
"public static base_response unset(nitro_service client, aaaparameter resource, String[] args) throws Exception{\n\t\taaaparameter unsetresource = new aaaparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"protected String getExecutableJar() throws IOException {\n Manifest manifest = new Manifest();\n manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, \"1.0\");\n manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, MAIN);\n manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, getClasspath());\n\n Path jar = createTempDirectory(\"exec\").resolve(\"generate.jar\");\n try (JarOutputStream output = new JarOutputStream(Files.newOutputStream(jar), manifest)) {\n output.putNextEntry(new JarEntry(\"allure.properties\"));\n Path allureConfig = PROPERTIES.getAllureConfig();\n if (Files.exists(allureConfig)) {\n byte[] bytes = Files.readAllBytes(allureConfig);\n output.write(bytes);\n }\n output.closeEntry();\n }\n\n return jar.toAbsolutePath().toString();\n }",
"public Response remove(DesignDocument designDocument) {\r\n assertNotEmpty(designDocument, \"DesignDocument\");\r\n ensureDesignPrefixObject(designDocument);\r\n return db.remove(designDocument);\r\n }",
"public void processDefaultCurrency(Row row)\n {\n ProjectProperties properties = m_project.getProjectProperties();\n properties.setCurrencySymbol(row.getString(\"curr_symbol\"));\n properties.setSymbolPosition(CURRENCY_SYMBOL_POSITION_MAP.get(row.getString(\"pos_curr_fmt_type\")));\n properties.setCurrencyDigits(row.getInteger(\"decimal_digit_cnt\"));\n properties.setThousandsSeparator(row.getString(\"digit_group_symbol\").charAt(0));\n properties.setDecimalSeparator(row.getString(\"decimal_symbol\").charAt(0));\n }",
"protected void appendSQLClause(SelectionCriteria c, StringBuffer buf)\r\n {\r\n // BRJ : handle SqlCriteria\r\n if (c instanceof SqlCriteria)\r\n {\r\n buf.append(c.getAttribute());\r\n return;\r\n }\r\n \r\n // BRJ : criteria attribute is a query\r\n if (c.getAttribute() instanceof Query)\r\n {\r\n Query q = (Query) c.getAttribute();\r\n buf.append(\"(\");\r\n buf.append(getSubQuerySQL(q));\r\n buf.append(\")\");\r\n buf.append(c.getClause());\r\n appendParameter(c.getValue(), buf);\r\n return;\r\n }\r\n\r\n\t\tAttributeInfo attrInfo = getAttributeInfo((String) c.getAttribute(), false, c.getUserAlias(), c.getPathClasses());\r\n TableAlias alias = attrInfo.tableAlias;\r\n\r\n if (alias != null)\r\n {\r\n boolean hasExtents = alias.hasExtents();\r\n\r\n if (hasExtents)\r\n {\r\n // BRJ : surround with braces if alias has extents\r\n buf.append(\"(\");\r\n appendCriteria(alias, attrInfo.pathInfo, c, buf);\r\n\r\n c.setNumberOfExtentsToBind(alias.extents.size());\r\n Iterator iter = alias.iterateExtents();\r\n while (iter.hasNext())\r\n {\r\n TableAlias tableAlias = (TableAlias) iter.next();\r\n buf.append(\" OR \");\r\n appendCriteria(tableAlias, attrInfo.pathInfo, c, buf);\r\n }\r\n buf.append(\")\");\r\n }\r\n else\r\n {\r\n // no extents\r\n appendCriteria(alias, attrInfo.pathInfo, c, buf);\r\n }\r\n }\r\n else\r\n {\r\n // alias null\r\n appendCriteria(alias, attrInfo.pathInfo, c, buf);\r\n }\r\n\r\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 }"
] |
Checks if provided class package is on the exclude list
@param classPackageName
name of class package
@return false if class package is on the {@link #excludePackages} list | [
"protected boolean checkExcludePackages(String classPackageName) {\n\t\tif (excludePackages != null && excludePackages.length > 0) {\n\t\t\tWildcardHelper wildcardHelper = new WildcardHelper();\n\n\t\t\t// we really don't care about the results, just the boolean\n\t\t\tMap<String, String> matchMap = new HashMap<String, String>();\n\n\t\t\tfor (String packageExclude : excludePackages) {\n\t\t\t\tint[] packagePattern = wildcardHelper.compilePattern(packageExclude);\n\t\t\t\tif (wildcardHelper.match(matchMap, classPackageName, packagePattern)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}"
] | [
"public boolean clearParameters() {\n this.query = null;\n this.fields = null;\n this.scope = null;\n this.fileExtensions = null;\n this.createdRange = null;\n this.updatedRange = null;\n this.sizeRange = null;\n this.ownerUserIds = null;\n this.ancestorFolderIds = null;\n this.contentTypes = null;\n this.type = null;\n this.trashContent = null;\n this.metadataFilter = null;\n this.sort = null;\n this.direction = null;\n return true;\n }",
"public static List<Number> findIndexValues(Object self, Number startIndex, Closure closure) {\n List<Number> result = new ArrayList<Number>();\n long count = 0;\n long startCount = startIndex.longValue();\n BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);\n for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); count++) {\n Object value = iter.next();\n if (count < startCount) {\n continue;\n }\n if (bcw.call(value)) {\n result.add(count);\n }\n }\n return result;\n }",
"List<MwDumpFile> findDumpsOnline(DumpContentType dumpContentType) {\n\t\tList<String> dumpFileDates = findDumpDatesOnline(dumpContentType);\n\n\t\tList<MwDumpFile> result = new ArrayList<>();\n\n\t\tfor (String dateStamp : dumpFileDates) {\n\t\t\tif (dumpContentType == DumpContentType.DAILY) {\n\t\t\t\tresult.add(new WmfOnlineDailyDumpFile(dateStamp,\n\t\t\t\t\t\tthis.projectName, this.webResourceFetcher,\n\t\t\t\t\t\tthis.dumpfileDirectoryManager));\n\t\t\t} else if (dumpContentType == DumpContentType.JSON) {\n\t\t\t\tresult.add(new JsonOnlineDumpFile(dateStamp, this.projectName,\n\t\t\t\t\t\tthis.webResourceFetcher, this.dumpfileDirectoryManager));\n\t\t\t} else {\n\t\t\t\tresult.add(new WmfOnlineStandardDumpFile(dateStamp,\n\t\t\t\t\t\tthis.projectName, this.webResourceFetcher,\n\t\t\t\t\t\tthis.dumpfileDirectoryManager, dumpContentType));\n\t\t\t}\n\t\t}\n\n\t\tlogger.info(\"Found \" + result.size() + \" online dumps of type \"\n\t\t\t\t+ dumpContentType + \": \" + result);\n\n\t\treturn result;\n\t}",
"public static int scanright(Color color, int height, int width, int col, PixelsExtractor f, int tolerance) {\n if (col == width || !PixelTools.colorMatches(color, tolerance, f.apply(new Area(col, 0, 1, height))))\n return col;\n else\n return scanright(color, height, width, col + 1, f, tolerance);\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 LuaScript endScriptReturn(LuaValue value, LuaScriptConfig config) {\n add(new LuaAstReturnStatement(argument(value)));\n String scriptText = buildScriptText();\n return new BasicLuaScript(scriptText, config);\n }",
"public synchronized void becomeTempoMaster() throws IOException {\n logger.debug(\"Trying to become master.\");\n if (!isSendingStatus()) {\n throw new IllegalStateException(\"Must be sending status updates to become the tempo master.\");\n }\n\n // Is there someone we need to ask to yield to us?\n final DeviceUpdate currentMaster = getTempoMaster();\n if (currentMaster != null) {\n // Send the yield request; we will become master when we get a successful response.\n byte[] payload = new byte[MASTER_HANDOFF_REQUEST_PAYLOAD.length];\n System.arraycopy(MASTER_HANDOFF_REQUEST_PAYLOAD, 0, payload, 0, MASTER_HANDOFF_REQUEST_PAYLOAD.length);\n payload[2] = getDeviceNumber();\n payload[8] = getDeviceNumber();\n if (logger.isDebugEnabled()) {\n logger.debug(\"Sending master yield request to player \" + currentMaster);\n }\n requestingMasterRoleFromPlayer.set(currentMaster.deviceNumber);\n assembleAndSendPacket(Util.PacketType.MASTER_HANDOFF_REQUEST, payload, currentMaster.address, BeatFinder.BEAT_PORT);\n } else if (!master.get()) {\n // There is no other master, we can just become it immediately.\n requestingMasterRoleFromPlayer.set(0);\n setMasterTempo(getTempo());\n master.set(true);\n }\n }",
"public OpenShiftAssistantTemplate parameter(String name, String value) {\n parameterValues.put(name, value);\n return this;\n }",
"private void writeClassData() {\n\t\ttry (PrintStream out = new PrintStream(openResultFileOuputStream(\n\t\t\t\tresultDirectory, \"classes.json\"))) {\n\t\t\tout.println(\"{\");\n\n\t\t\t// Add direct subclass information:\n\t\t\tfor (Entry<Integer, ClassRecord> classEntry : this.classRecords\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tif (classEntry.getValue().subclassCount == 0\n\t\t\t\t\t\t&& classEntry.getValue().itemCount == 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfor (Integer superClass : classEntry.getValue().directSuperClasses) {\n\t\t\t\t\tthis.classRecords.get(superClass).nonemptyDirectSubclasses\n\t\t\t\t\t\t\t.add(classEntry.getKey().toString());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tint count = 0;\n\t\t\tint countNoLabel = 0;\n\t\t\tfor (Entry<Integer, ClassRecord> classEntry : this.classRecords\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tif (classEntry.getValue().subclassCount == 0\n\t\t\t\t\t\t&& classEntry.getValue().itemCount == 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (classEntry.getValue().label == null) {\n\t\t\t\t\tcountNoLabel++;\n\t\t\t\t}\n\n\t\t\t\tif (count > 0) {\n\t\t\t\t\tout.println(\",\");\n\t\t\t\t}\n\t\t\t\tout.print(\"\\\"\" + classEntry.getKey() + \"\\\":\");\n\t\t\t\tmapper.writeValue(out, classEntry.getValue());\n\t\t\t\tcount++;\n\t\t\t}\n\t\t\tout.println(\"\\n}\");\n\n\t\t\tSystem.out.println(\" Serialized information for \" + count\n\t\t\t\t\t+ \" class items.\");\n\t\t\tSystem.out.println(\" -- class items with missing label: \"\n\t\t\t\t\t+ countNoLabel);\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}"
] |
Tests whether a Row name occurs more than once in the list of rows
@param name
@return | [
"public boolean isDuplicateName(String name) {\n if (name == null || name.trim().isEmpty()) {\n return false;\n }\n List<AssignmentRow> as = view.getAssignmentRows();\n if (as != null && !as.isEmpty()) {\n int nameCount = 0;\n for (AssignmentRow row : as) {\n if (name.trim().compareTo(row.getName()) == 0) {\n nameCount++;\n if (nameCount > 1) {\n return true;\n }\n }\n }\n }\n return false;\n }"
] | [
"public Map<Integer, String> listProjects(InputStream is) throws MPXJException\n {\n try\n {\n m_tables = new HashMap<String, List<Row>>();\n processFile(is);\n\n Map<Integer, String> result = new HashMap<Integer, String>();\n\n List<Row> rows = getRows(\"project\", null, null);\n for (Row row : rows)\n {\n Integer id = row.getInteger(\"proj_id\");\n String name = row.getString(\"proj_short_name\");\n result.put(id, name);\n }\n\n return result;\n }\n\n finally\n {\n m_tables = null;\n m_currentTable = null;\n m_currentFieldNames = null;\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 }",
"public static <E extends Style.HasCssName, F extends Enum<? extends Style.HasCssName>> void addUniqueEnumStyleName(final UIObject uiObject,\n final Class<F> enumClass,\n final E style) {\n removeEnumStyleNames(uiObject, enumClass);\n addEnumStyleName(uiObject, style);\n }",
"public double estimateExcludedVolumeFraction(){\n\t\t//Calculate volume/area of the of the scene without obstacles\n\t\tif(recalculateVolumeFraction){\n\t\t\tCentralRandomNumberGenerator r = CentralRandomNumberGenerator.getInstance();\n\t\t\tboolean firstRandomDraw = false;\n\t\t\tif(randomNumbers==null){\n\t\t\t\trandomNumbers = new double[nRandPoints*dimension];\n\t\t\t\tfirstRandomDraw = true;\n\t\t\t}\n\t\t\tint countCollision = 0;\n\t\t\tfor(int i = 0; i< nRandPoints; i++){\n\t\t\t\tdouble[] pos = new double[dimension];\n\t\t\t\tfor(int j = 0; j < dimension; j++){\n\t\t\t\t\tif(firstRandomDraw){\n\t\t\t\t\t\trandomNumbers[i*dimension + j] = r.nextDouble();\n\t\t\t\t\t}\n\t\t\t\t\tpos[j] = randomNumbers[i*dimension + j]*size[j];\n\t\t\t\t}\n\t\t\t\tif(checkCollision(pos)){\n\t\t\t\t\tcountCollision++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfraction = countCollision*1.0/nRandPoints;\n\t\t\trecalculateVolumeFraction = false;\n\t\t}\n\t\treturn fraction;\n\t}",
"public static void registerOgmExternalizers(GlobalConfiguration globalCfg) {\n\t\tMap<Integer, AdvancedExternalizer<?>> externalizerMap = globalCfg.serialization().advancedExternalizers();\n\t\texternalizerMap.putAll( ogmExternalizers );\n\t}",
"@Override\n public Object put(List<Map.Entry> batch) throws InterruptedException {\n if (initializeClusterSource()) {\n return clusterSource.put(batch);\n }\n return null;\n }",
"protected void\t\tcalcWorld(Bone bone, int parentId)\n {\n getWorldMatrix(parentId, mTempMtxB); // WorldMatrix (parent) TempMtxB\n mTempMtxB.mul(bone.LocalMatrix); // WorldMatrix = WorldMatrix(parent) * LocalMatrix\n bone.WorldMatrix.set(mTempMtxB);\n }",
"public void addIn(Object attribute, Query subQuery)\r\n {\r\n // PAW\r\n\t\t// addSelectionCriteria(ValueCriteria.buildInCriteria(attribute, subQuery, getAlias()));\r\n\t\taddSelectionCriteria(ValueCriteria.buildInCriteria(attribute, subQuery, getUserAlias(attribute)));\r\n }",
"public List<MapRow> readBlocks(Class<? extends BlockReader> readerClass) throws IOException\n {\n BlockReader reader;\n\n try\n {\n reader = readerClass.getConstructor(StreamReader.class).newInstance(this);\n }\n catch (Exception ex)\n {\n throw new RuntimeException(ex);\n }\n\n return reader.read();\n }"
] |
Read a field into our table configuration for field=value line. | [
"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}"
] | [
"@Override\n public double get( int row , int col ) {\n if( col < 0 || col >= numCols || row < 0 || row >= numRows ) {\n throw new IllegalArgumentException(\"Specified element is out of bounds: \"+row+\" \"+col);\n }\n\n return data[ row * numCols + col ];\n }",
"private void changeClusterAndStores(String clusterKey,\n final Cluster cluster,\n String storesKey,\n final List<StoreDefinition> storeDefs) {\n metadataStore.writeLock.lock();\n try {\n VectorClock updatedVectorClock = ((VectorClock) metadataStore.get(clusterKey, null)\n .get(0)\n .getVersion()).incremented(metadataStore.getNodeId(),\n System.currentTimeMillis());\n metadataStore.put(clusterKey, Versioned.value((Object) cluster, updatedVectorClock));\n\n // now put new stores\n updatedVectorClock = ((VectorClock) metadataStore.get(storesKey, null)\n .get(0)\n .getVersion()).incremented(metadataStore.getNodeId(),\n System.currentTimeMillis());\n metadataStore.put(storesKey, Versioned.value((Object) storeDefs, updatedVectorClock));\n\n } catch(Exception e) {\n logger.info(\"Error while changing cluster to \" + cluster + \"for key \" + clusterKey);\n throw new VoldemortException(e);\n } finally {\n metadataStore.writeLock.unlock();\n }\n }",
"public Collection<Blog> getList() throws FlickrException {\r\n List<Blog> blogs = new ArrayList<Blog>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIST);\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element blogsElement = response.getPayload();\r\n NodeList blogNodes = blogsElement.getElementsByTagName(\"blog\");\r\n for (int i = 0; i < blogNodes.getLength(); i++) {\r\n Element blogElement = (Element) blogNodes.item(i);\r\n Blog blog = new Blog();\r\n blog.setId(blogElement.getAttribute(\"id\"));\r\n blog.setName(blogElement.getAttribute(\"name\"));\r\n blog.setNeedPassword(\"1\".equals(blogElement.getAttribute(\"needspassword\")));\r\n blog.setUrl(blogElement.getAttribute(\"url\"));\r\n blogs.add(blog);\r\n }\r\n return blogs;\r\n }",
"public static int countTrue(BMatrixRMaj A) {\n int total = 0;\n\n int N = A.getNumElements();\n\n for (int i = 0; i < N; i++) {\n if( A.data[i] )\n total++;\n }\n\n return total;\n }",
"public Object materializeObject(ClassDescriptor cld, Identity oid)\r\n throws PersistenceBrokerException\r\n {\r\n final StatementManagerIF sm = broker.serviceStatementManager();\r\n final SelectStatement sql = broker.serviceSqlGenerator().getPreparedSelectByPkStatement(cld);\r\n Object result = null;\r\n PreparedStatement stmt = null;\r\n ResultSet rs = null;\r\n try\r\n {\r\n stmt = sm.getSelectByPKStatement(cld);\r\n if (stmt == null)\r\n {\r\n logger.error(\"getSelectByPKStatement returned a null statement\");\r\n throw new PersistenceBrokerException(\"getSelectByPKStatement returned a null statement\");\r\n }\r\n /*\r\n arminw: currently a select by PK could never be a stored procedure,\r\n thus we can always set 'false'. Is this correct??\r\n */\r\n sm.bindSelect(stmt, oid, cld, false);\r\n rs = stmt.executeQuery();\r\n // data available read object, else return null\r\n ResultSetAndStatement rs_stmt = new ResultSetAndStatement(broker.serviceStatementManager(), stmt, rs, sql);\r\n if (rs.next())\r\n {\r\n Map row = new HashMap();\r\n cld.getRowReader().readObjectArrayFrom(rs_stmt, row);\r\n result = cld.getRowReader().readObjectFrom(row);\r\n }\r\n // close resources\r\n rs_stmt.close();\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n // release resources on exception\r\n sm.closeResources(stmt, rs);\r\n logger.error(\"PersistenceBrokerException during the execution of materializeObject: \" + e.getMessage(), e);\r\n throw e;\r\n }\r\n catch (SQLException e)\r\n {\r\n // release resources on exception\r\n sm.closeResources(stmt, rs);\r\n throw ExceptionHelper.generateException(e, sql.getStatement(), cld, logger, null);\r\n }\r\n return result;\r\n }",
"private static Iterable<BoxUser.Info> getUsersInfoForType(final BoxAPIConnection api,\n final String filterTerm, final String userType, final String externalAppUserId, final String... fields) {\n return new Iterable<BoxUser.Info>() {\n public Iterator<BoxUser.Info> iterator() {\n QueryStringBuilder builder = new QueryStringBuilder();\n if (filterTerm != null) {\n builder.appendParam(\"filter_term\", filterTerm);\n }\n if (userType != null) {\n builder.appendParam(\"user_type\", userType);\n }\n if (externalAppUserId != null) {\n builder.appendParam(\"external_app_user_id\", externalAppUserId);\n }\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields);\n }\n URL url = USERS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString());\n return new BoxUserIterator(api, url);\n }\n };\n }",
"public static final Integer getInteger(String value)\n {\n Integer result;\n\n try\n {\n result = Integer.valueOf(Integer.parseInt(value));\n }\n\n catch (Exception ex)\n {\n result = null;\n }\n\n return (result);\n }",
"public void setFromJSON(Context context, JSONObject properties) {\n String backgroundResStr = optString(properties, Properties.background);\n if (backgroundResStr != null && !backgroundResStr.isEmpty()) {\n final int backgroundResId = getId(context, backgroundResStr, \"drawable\");\n setBackGround(context.getResources().getDrawable(backgroundResId, null));\n }\n\n setBackgroundColor(getJSONColor(properties, Properties.background_color, getBackgroundColor()));\n setGravity(optInt(properties, TextContainer.Properties.gravity, getGravity()));\n setRefreshFrequency(optEnum(properties, Properties.refresh_freq, getRefreshFrequency()));\n setTextColor(getJSONColor(properties, Properties.text_color, getTextColor()));\n setText(optString(properties, Properties.text, (String) getText()));\n setTextSize(optFloat(properties, Properties.text_size, getTextSize()));\n\n final JSONObject typefaceJson = optJSONObject(properties, Properties.typeface);\n\n if (typefaceJson != null) {\n try {\n Typeface typeface = WidgetLib.getTypefaceManager().getTypeface(typefaceJson);\n setTypeface(typeface);\n } catch (Throwable e) {\n Log.e(TAG, e, \"Couldn't set typeface from properties: %s\", typefaceJson);\n }\n }\n }",
"public 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 }"
] |
Randomly shuffle partitions between nodes within every zone.
@param nextCandidateCluster cluster object.
@param randomSwapAttempts See RebalanceCLI.
@param randomSwapSuccesses See RebalanceCLI.
@param randomSwapZoneIds The set of zoneIds to consider. Each zone is done
independently.
@param storeDefs List of store definitions
@return updated cluster | [
"public static Cluster randomShufflePartitions(final Cluster nextCandidateCluster,\n final int randomSwapAttempts,\n final int randomSwapSuccesses,\n final List<Integer> randomSwapZoneIds,\n List<StoreDefinition> storeDefs) {\n List<Integer> zoneIds = null;\n if(randomSwapZoneIds.isEmpty()) {\n zoneIds = new ArrayList<Integer>(nextCandidateCluster.getZoneIds());\n } else {\n zoneIds = new ArrayList<Integer>(randomSwapZoneIds);\n }\n\n List<Integer> nodeIds = new ArrayList<Integer>();\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n double currentUtility = new PartitionBalance(returnCluster, storeDefs).getUtility();\n\n int successes = 0;\n for(int i = 0; i < randomSwapAttempts; i++) {\n\n // Iterate over zone ids to decide which node ids to include for\n // intra-zone swapping.\n // In future, if there is a need to support inter-zone swapping,\n // then just remove the\n // zone specific logic that populates nodeIdSet and add all nodes\n // from across all zones.\n\n int zoneIdOffset = i % zoneIds.size();\n\n Set<Integer> nodeIdSet = nextCandidateCluster.getNodeIdsInZone(zoneIds.get(zoneIdOffset));\n nodeIds = new ArrayList<Integer>(nodeIdSet);\n\n Collections.shuffle(zoneIds, new Random(System.currentTimeMillis()));\n Cluster shuffleResults = swapRandomPartitionsAmongNodes(returnCluster, nodeIds);\n\n double nextUtility = new PartitionBalance(shuffleResults, storeDefs).getUtility();\n if(nextUtility < currentUtility) {\n System.out.println(\"Swap improved max-min ratio: \" + currentUtility + \" -> \"\n + nextUtility + \" (improvement \" + successes\n + \" on swap attempt \" + i + \")\");\n successes++;\n returnCluster = shuffleResults;\n currentUtility = nextUtility;\n }\n if(successes >= randomSwapSuccesses) {\n // Enough successes, move on.\n break;\n }\n }\n return returnCluster;\n }"
] | [
"public static <T> OptionalValue<T> ofNullable(T value) {\n return new GenericOptionalValue<T>(RUNTIME_SOURCE, DEFAULT_KEY, value);\n }",
"public String addDependency(FunctionalTaskItem dependencyTaskItem) {\n IndexableTaskItem dependency = IndexableTaskItem.create(dependencyTaskItem);\n this.addDependency(dependency);\n return dependency.key();\n }",
"public SingleProfileBackup getProfileBackupData(int profileID, String clientUUID) throws Exception {\n SingleProfileBackup singleProfileBackup = new SingleProfileBackup();\n List<PathOverride> enabledPaths = new ArrayList<>();\n\n List<EndpointOverride> paths = PathOverrideService.getInstance().getPaths(profileID, clientUUID, null);\n for (EndpointOverride override : paths) {\n if (override.getRequestEnabled() || override.getResponseEnabled()) {\n PathOverride pathOverride = new PathOverride();\n pathOverride.setPathName(override.getPathName());\n if (override.getRequestEnabled()) {\n pathOverride.setRequestEnabled(true);\n }\n if (override.getResponseEnabled()) {\n pathOverride.setResponseEnabled(true);\n }\n\n pathOverride.setEnabledEndpoints(override.getEnabledEndpoints());\n enabledPaths.add(pathOverride);\n }\n }\n singleProfileBackup.setEnabledPaths(enabledPaths);\n\n Client backupClient = ClientService.getInstance().findClient(clientUUID, profileID);\n ServerGroup activeServerGroup = ServerRedirectService.getInstance().getServerGroup(backupClient.getActiveServerGroup(), profileID);\n singleProfileBackup.setActiveServerGroup(activeServerGroup);\n\n return singleProfileBackup;\n }",
"public float getSize(final Axis axis) {\n float size = 0;\n if (mViewPort != null && mViewPort.isClippingEnabled(axis)) {\n size = mViewPort.get(axis);\n } else if (mContainer != null) {\n size = getSizeImpl(axis);\n }\n return size;\n }",
"public <T> T eval(ELVars vars, String el, Class<T> returnType) throws ELEvalException {\n Utils.checkNotNull(vars, \"vars\");\n Utils.checkNotNull(el, \"expression\");\n Utils.checkNotNull(returnType, \"returnType\");\n VARIABLES_IN_SCOPE_TL.set(vars);\n try {\n return evaluate(vars, el, returnType);\n } finally {\n VARIABLES_IN_SCOPE_TL.set(null);\n }\n }",
"public boolean contains(Date date)\n {\n boolean result = false;\n\n if (date != null)\n {\n result = (DateHelper.compare(getFromDate(), getToDate(), date) == 0);\n }\n\n return (result);\n }",
"@Override\n public boolean commit() {\n final CoreRemoteMongoCollection<DocumentT> collection = getCollection();\n final List<WriteModel<DocumentT>> writeModels = getBulkWriteModels();\n\n // define success as any one operation succeeding for now\n boolean success = true;\n for (final WriteModel<DocumentT> write : writeModels) {\n if (write instanceof ReplaceOneModel) {\n final ReplaceOneModel<DocumentT> replaceModel = ((ReplaceOneModel) write);\n final RemoteUpdateResult result =\n collection.updateOne(replaceModel.getFilter(), (Bson) replaceModel.getReplacement());\n success = success\n && (result != null && result.getModifiedCount() == result.getMatchedCount());\n } else if (write instanceof UpdateOneModel) {\n final UpdateOneModel<DocumentT> updateModel = ((UpdateOneModel) write);\n final RemoteUpdateResult result =\n collection.updateOne(updateModel.getFilter(), updateModel.getUpdate());\n success = success\n && (result != null && result.getModifiedCount() == result.getMatchedCount());\n } else if (write instanceof UpdateManyModel) {\n final UpdateManyModel<DocumentT> updateModel = ((UpdateManyModel) write);\n final RemoteUpdateResult result =\n collection.updateMany(updateModel.getFilter(), updateModel.getUpdate());\n success = success\n && (result != null && result.getModifiedCount() == result.getMatchedCount());\n }\n }\n return success;\n }",
"public void cleanup() {\n synchronized (_sslMap) {\n for (SslRelayOdo relay : _sslMap.values()) {\n if (relay.getHttpServer() != null && relay.isStarted()) {\n relay.getHttpServer().removeListener(relay);\n }\n }\n\n sslRelays.clear();\n }\n }",
"public void localBegin()\r\n {\r\n if (this.isInLocalTransaction)\r\n {\r\n throw new TransactionInProgressException(\"Connection is already in transaction\");\r\n }\r\n Connection connection = null;\r\n try\r\n {\r\n connection = this.getConnection();\r\n }\r\n catch (LookupException e)\r\n {\r\n /**\r\n * must throw to notify user that we couldn't start a connection\r\n */\r\n throw new PersistenceBrokerException(\"Can't lookup a connection\", e);\r\n }\r\n if (log.isDebugEnabled()) log.debug(\"localBegin was called for con \" + connection);\r\n // change autoCommit state only if we are not in a managed environment\r\n // and it is enabled by user\r\n if(!broker.isManaged())\r\n {\r\n if (jcd.getUseAutoCommit() == JdbcConnectionDescriptor.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE)\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"Try to change autoCommit state to 'false'\");\r\n platform.changeAutoCommitState(jcd, connection, false);\r\n }\r\n }\r\n else\r\n {\r\n if(log.isDebugEnabled()) log.debug(\r\n \"Found managed environment setting in PB, will skip Platform.changeAutoCommitState(...) call\");\r\n }\r\n this.isInLocalTransaction = true;\r\n }"
] |
Retrieve the correct calendar for a resource.
@param calendarID calendar ID
@return calendar for resource | [
"private ProjectCalendar getResourceCalendar(Integer calendarID)\n {\n ProjectCalendar result = null;\n if (calendarID != null)\n {\n ProjectCalendar calendar = m_calMap.get(calendarID);\n if (calendar != null)\n {\n //\n // If the resource is linked to a base calendar, derive\n // a default calendar from the base calendar.\n //\n if (!calendar.isDerived())\n {\n ProjectCalendar resourceCalendar = m_project.addCalendar();\n resourceCalendar.setParent(calendar);\n resourceCalendar.setWorkingDay(Day.MONDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.TUESDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.WEDNESDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.THURSDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.FRIDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.SATURDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.SUNDAY, DayType.DEFAULT);\n result = resourceCalendar;\n }\n else\n {\n //\n // Primavera seems to allow a calendar to be shared between resources\n // whereas in the MS Project model there is a one-to-one\n // relationship. If we find a shared calendar, take a copy of it\n //\n if (calendar.getResource() == null)\n {\n result = calendar;\n }\n else\n {\n ProjectCalendar copy = m_project.addCalendar();\n copy.copy(calendar);\n result = copy;\n }\n }\n }\n }\n\n return result;\n }"
] | [
"private boolean findAndSetManifestFromArtifactory(ArtifactoryServer server, ArtifactoryDependenciesClient dependenciesClient, TaskListener listener) throws IOException {\n String candidateImagePath = DockerUtils.getImagePath(imageTag);\n String manifestPath;\n\n // Try to get manifest, assuming reverse proxy\n manifestPath = StringUtils.join(new String[]{server.getUrl(), targetRepo, candidateImagePath, \"manifest.json\"}, \"/\");\n if (checkAndSetManifestAndImagePathCandidates(manifestPath, candidateImagePath, dependenciesClient, listener)) {\n return true;\n }\n\n // Try to get manifest, assuming proxy-less\n candidateImagePath = candidateImagePath.substring(candidateImagePath.indexOf(\"/\") + 1);\n manifestPath = StringUtils.join(new String[]{server.getUrl(), targetRepo, candidateImagePath, \"manifest.json\"}, \"/\");\n if (checkAndSetManifestAndImagePathCandidates(manifestPath, candidateImagePath, dependenciesClient, listener)) {\n return true;\n }\n\n // Couldn't find correct manifest\n listener.getLogger().println(\"Could not find corresponding manifest.json file in Artifactory.\");\n return false;\n }",
"public static double Sin(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 double sign = 1;\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 += sign * (mult / fact);\r\n sign *= -1;\r\n }\r\n\r\n return result;\r\n }\r\n }",
"public static <T, X> ObserverMethodImpl<T, X> create(EnhancedAnnotatedMethod<T, ? super X> method, RIBean<X> declaringBean, BeanManagerImpl manager, boolean isAsync) {\n if (declaringBean instanceof ExtensionBean) {\n return new ExtensionObserverMethodImpl<T, X>(method, declaringBean, manager, isAsync);\n }\n return new ObserverMethodImpl<T, X>(method, declaringBean, manager, isAsync);\n }",
"public static snmpalarm[] get(nitro_service service, String trapname[]) throws Exception{\n\t\tif (trapname !=null && trapname.length>0) {\n\t\t\tsnmpalarm response[] = new snmpalarm[trapname.length];\n\t\t\tsnmpalarm obj[] = new snmpalarm[trapname.length];\n\t\t\tfor (int i=0;i<trapname.length;i++) {\n\t\t\t\tobj[i] = new snmpalarm();\n\t\t\t\tobj[i].set_trapname(trapname[i]);\n\t\t\t\tresponse[i] = (snmpalarm) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}",
"public static Method getBridgeMethodTarget(Method someMethod) {\n TraitBridge annotation = someMethod.getAnnotation(TraitBridge.class);\n if (annotation==null) {\n return null;\n }\n Class aClass = annotation.traitClass();\n String desc = annotation.desc();\n for (Method method : aClass.getDeclaredMethods()) {\n String methodDescriptor = BytecodeHelper.getMethodDescriptor(method.getReturnType(), method.getParameterTypes());\n if (desc.equals(methodDescriptor)) {\n return method;\n }\n }\n return null;\n }",
"public static long decodeLong(byte[] ba, int offset) {\n return ((((long) ba[offset + 0] << 56) + ((long) (ba[offset + 1] & 255) << 48)\n + ((long) (ba[offset + 2] & 255) << 40) + ((long) (ba[offset + 3] & 255) << 32)\n + ((long) (ba[offset + 4] & 255) << 24) + ((ba[offset + 5] & 255) << 16)\n + ((ba[offset + 6] & 255) << 8) + ((ba[offset + 7] & 255) << 0)));\n }",
"private void setRequestProps(WbGetEntitiesActionData properties) {\n\t\tStringBuilder builder = new StringBuilder();\n\t\tbuilder.append(\"info|datatype\");\n\t\tif (!this.filter.excludeAllLanguages()) {\n\t\t\tbuilder.append(\"|labels|aliases|descriptions\");\n\t\t}\n\t\tif (!this.filter.excludeAllProperties()) {\n\t\t\tbuilder.append(\"|claims\");\n\t\t}\n\t\tif (!this.filter.excludeAllSiteLinks()) {\n\t\t\tbuilder.append(\"|sitelinks\");\n\t\t}\n\n\t\tproperties.props = builder.toString();\n\t}",
"private void deriveProjectCalendar()\n {\n //\n // Count the number of times each calendar is used\n //\n Map<ProjectCalendar, Integer> map = new HashMap<ProjectCalendar, Integer>();\n for (Task task : m_project.getTasks())\n {\n ProjectCalendar calendar = task.getCalendar();\n Integer count = map.get(calendar);\n if (count == null)\n {\n count = Integer.valueOf(1);\n }\n else\n {\n count = Integer.valueOf(count.intValue() + 1);\n }\n map.put(calendar, count);\n }\n\n //\n // Find the most frequently used calendar\n //\n int maxCount = 0;\n ProjectCalendar defaultCalendar = null;\n\n for (Entry<ProjectCalendar, Integer> entry : map.entrySet())\n {\n if (entry.getValue().intValue() > maxCount)\n {\n maxCount = entry.getValue().intValue();\n defaultCalendar = entry.getKey();\n }\n }\n\n //\n // Set the default calendar for the project\n // and remove it's use as a task-specific calendar.\n //\n if (defaultCalendar != null)\n {\n m_project.setDefaultCalendar(defaultCalendar);\n for (Task task : m_project.getTasks())\n {\n if (task.getCalendar() == defaultCalendar)\n {\n task.setCalendar(null);\n }\n }\n }\n }",
"private List<Object> convertType(DataType type, byte[] data)\n {\n List<Object> result = new ArrayList<Object>();\n int index = 0;\n\n while (index < data.length)\n {\n switch (type)\n {\n case STRING:\n {\n String value = MPPUtility.getUnicodeString(data, index);\n result.add(value);\n index += ((value.length() + 1) * 2);\n break;\n }\n\n case CURRENCY:\n {\n Double value = Double.valueOf(MPPUtility.getDouble(data, index) / 100);\n result.add(value);\n index += 8;\n break;\n }\n\n case NUMERIC:\n {\n Double value = Double.valueOf(MPPUtility.getDouble(data, index));\n result.add(value);\n index += 8;\n break;\n }\n\n case DATE:\n {\n Date value = MPPUtility.getTimestamp(data, index);\n result.add(value);\n index += 4;\n break;\n\n }\n\n case DURATION:\n {\n TimeUnit units = MPPUtility.getDurationTimeUnits(MPPUtility.getShort(data, index + 4), m_properties.getDefaultDurationUnits());\n Duration value = MPPUtility.getAdjustedDuration(m_properties, MPPUtility.getInt(data, index), units);\n result.add(value);\n index += 6;\n break;\n }\n\n case BOOLEAN:\n {\n Boolean value = Boolean.valueOf(MPPUtility.getShort(data, index) == 1);\n result.add(value);\n index += 2;\n break;\n }\n\n default:\n {\n index = data.length;\n break;\n }\n }\n }\n\n return result;\n }"
] |
Assign an ID value to this field. | [
"public Object assignIdValue(ConnectionSource connectionSource, Object data, Number val, ObjectCache objectCache)\n\t\t\tthrows SQLException {\n\t\tObject idVal = dataPersister.convertIdNumber(val);\n\t\tif (idVal == null) {\n\t\t\tthrow new SQLException(\"Invalid class \" + dataPersister + \" for sequence-id \" + this);\n\t\t} else {\n\t\t\tassignField(connectionSource, data, idVal, false, objectCache);\n\t\t\treturn idVal;\n\t\t}\n\t}"
] | [
"public static base_response add(nitro_service client, snmpuser resource) throws Exception {\n\t\tsnmpuser addresource = new snmpuser();\n\t\taddresource.name = resource.name;\n\t\taddresource.group = resource.group;\n\t\taddresource.authtype = resource.authtype;\n\t\taddresource.authpasswd = resource.authpasswd;\n\t\taddresource.privtype = resource.privtype;\n\t\taddresource.privpasswd = resource.privpasswd;\n\t\treturn addresource.add_resource(client);\n\t}",
"protected static void appendHandler(LogRecordHandler parent, LogRecordHandler child){\r\n RecordHandlerTree p = handlers.find(parent);\r\n if(p != null){\r\n p.addChild(child);\r\n } else {\r\n throw new IllegalArgumentException(\"No such parent handler: \" + parent);\r\n }\r\n }",
"public void mergeSubsystem(final GlobalTransformerRegistry registry, String subsystemName, ModelVersion version) {\n final PathElement element = PathElement.pathElement(SUBSYSTEM, subsystemName);\n registry.mergeSubtree(this, PathAddress.EMPTY_ADDRESS.append(element), version);\n }",
"public Metadata getMetadata(String templateName) {\n String scope = Metadata.scopeBasedOnType(templateName);\n return this.getMetadata(templateName, scope);\n }",
"protected BufferedImage fetchImage(\n @Nonnull final ClientHttpRequest request, @Nonnull final MapfishMapContext transformer)\n throws IOException {\n final String baseMetricName = getClass().getName() + \".read.\" +\n StatsUtils.quotePart(request.getURI().getHost());\n final Timer.Context timerDownload = this.registry.timer(baseMetricName).time();\n try (ClientHttpResponse httpResponse = request.execute()) {\n if (httpResponse.getStatusCode() != HttpStatus.OK) {\n final String message = String.format(\n \"Invalid status code for %s (%d!=%d). The response was: '%s'\",\n request.getURI(), httpResponse.getStatusCode().value(),\n HttpStatus.OK.value(), httpResponse.getStatusText());\n this.registry.counter(baseMetricName + \".error\").inc();\n if (getFailOnError()) {\n throw new RuntimeException(message);\n } else {\n LOGGER.info(message);\n return createErrorImage(transformer.getPaintArea());\n }\n }\n\n final List<String> contentType = httpResponse.getHeaders().get(\"Content-Type\");\n if (contentType == null || contentType.size() != 1) {\n LOGGER.debug(\"The image {} didn't return a valid content type header.\",\n request.getURI());\n } else if (!contentType.get(0).startsWith(\"image/\")) {\n final byte[] data;\n try (InputStream body = httpResponse.getBody()) {\n data = IOUtils.toByteArray(body);\n }\n LOGGER.debug(\"We get a wrong image for {}, content type: {}\\nresult:\\n{}\",\n request.getURI(), contentType.get(0),\n new String(data, StandardCharsets.UTF_8));\n this.registry.counter(baseMetricName + \".error\").inc();\n return createErrorImage(transformer.getPaintArea());\n }\n\n final BufferedImage image = ImageIO.read(httpResponse.getBody());\n if (image == null) {\n LOGGER.warn(\"Cannot read image from %a\", request.getURI());\n this.registry.counter(baseMetricName + \".error\").inc();\n if (getFailOnError()) {\n throw new RuntimeException(\"Cannot read image from \" + request.getURI());\n } else {\n return createErrorImage(transformer.getPaintArea());\n }\n }\n timerDownload.stop();\n return image;\n } catch (Throwable e) {\n this.registry.counter(baseMetricName + \".error\").inc();\n throw e;\n }\n }",
"private String jsonifyData(Map<String, ? extends Object> data) {\n JSONObject jsonData = new JSONObject(data);\n\n return jsonData.toString();\n }",
"boolean advance() {\n if (header.frameCount <= 0) {\n return false;\n }\n\n if(framePointer == getFrameCount() - 1) {\n loopIndex++;\n }\n\n if(header.loopCount != LOOP_FOREVER && loopIndex > header.loopCount) {\n return false;\n }\n\n framePointer = (framePointer + 1) % header.frameCount;\n return true;\n }",
"public static dnstxtrec get(nitro_service service, String domain) throws Exception{\n\t\tdnstxtrec obj = new dnstxtrec();\n\t\tobj.set_domain(domain);\n\t\tdnstxtrec response = (dnstxtrec) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public ParallelTaskBuilder prepareHttpHead(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.getHttpMeta().setHttpMethod(HttpMethod.HEAD);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\n }"
] |
Load the entity activating the persistence context execution boundaries
@param session the session
@param qp the query parameters
@param ogmLoadingContext the loading context
@param returnProxies when {@code true}, get an existing proxy for each collection element (if there is one)
@return the result of the query | [
"private List<Object> doQueryAndInitializeNonLazyCollections(\n\t\t\tSharedSessionContractImplementor session,\n\t\t\tQueryParameters qp,\n\t\t\tOgmLoadingContext ogmLoadingContext,\n\t\t\tboolean returnProxies) {\n\n\n\t\t//TODO handles the read only\n\t\tfinal PersistenceContext persistenceContext = session.getPersistenceContext();\n\t\tboolean defaultReadOnlyOrig = persistenceContext.isDefaultReadOnly();\n\t\tpersistenceContext.beforeLoad();\n\t\tList<Object> result;\n\t\ttry {\n\t\t\ttry {\n\t\t\t\tresult = doQuery(\n\t\t\t\t\t\tsession,\n\t\t\t\t\t\tqp,\n\t\t\t\t\t\togmLoadingContext,\n\t\t\t\t\t\treturnProxies\n\t\t\t\t);\n\t\t\t}\n\t\t\tfinally {\n\t\t\t\tpersistenceContext.afterLoad();\n\t\t\t}\n\t\t\tpersistenceContext.initializeNonLazyCollections();\n\t\t}\n\t\tfinally {\n\t\t\t// Restore the original default\n\t\t\tpersistenceContext.setDefaultReadOnly( defaultReadOnlyOrig );\n\t\t}\n\n\t\tlog.debug( \"done entity load\" );\n\t\treturn result;\n\t}"
] | [
"public void add(Vector3d v1, Vector3d v2) {\n x = v1.x + v2.x;\n y = v1.y + v2.y;\n z = v1.z + v2.z;\n }",
"public static tmglobal_tmsessionpolicy_binding[] get(nitro_service service) throws Exception{\n\t\ttmglobal_tmsessionpolicy_binding obj = new tmglobal_tmsessionpolicy_binding();\n\t\ttmglobal_tmsessionpolicy_binding response[] = (tmglobal_tmsessionpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private WeekDay readWeekDay(JSONValue val) throws IllegalArgumentException {\n\n String str = readOptionalString(val);\n if (null != str) {\n return WeekDay.valueOf(str);\n }\n throw new IllegalArgumentException();\n }",
"public void updateInfo(BoxTermsOfServiceUserStatus.Info info) {\n URL url = TERMS_OF_SERVICE_USER_STATUSES_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"PUT\");\n request.setBody(info.getPendingChanges());\n\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n info.update(responseJSON);\n }",
"@SuppressWarnings(\"checkstyle:illegalcatch\")\n private boolean sendMessage(final byte[] messageToSend) {\n try {\n connectionPool.execute(new PooledObjectConsumer<TcpConnection>() {\n @Override\n public void accept(final TcpConnection tcpConnection) throws IOException {\n tcpConnection.write(messageToSend);\n }\n });\n } catch (final Exception e) {\n addError(String.format(\"Error sending message via tcp://%s:%s\",\n getGraylogHost(), getGraylogPort()), e);\n\n return false;\n }\n\n return true;\n }",
"static void prepareTasks(final IdentityPatchContext.PatchEntry entry, final IdentityPatchContext context, final List<PreparedTask> tasks, final List<ContentItem> conflicts) throws PatchingException {\n for (final PatchingTasks.ContentTaskDefinition definition : entry.getTaskDefinitions()) {\n final PatchingTask task = createTask(definition, context, entry);\n if(!task.isRelevant(entry)) {\n continue;\n }\n try {\n // backup and validate content\n if (!task.prepare(entry) || definition.hasConflicts()) {\n // Unless it a content item was manually ignored (or excluded)\n final ContentItem item = task.getContentItem();\n if (!context.isIgnored(item)) {\n conflicts.add(item);\n }\n }\n tasks.add(new PreparedTask(task, entry));\n } catch (IOException e) {\n throw new PatchingException(e);\n }\n }\n }",
"private boolean keyAlreadyExists(String newKey) {\n\n Collection<?> itemIds = m_table.getItemIds();\n for (Object itemId : itemIds) {\n if (m_table.getItem(itemId).getItemProperty(TableProperty.KEY).getValue().equals(newKey)) {\n return true;\n }\n }\n return false;\n }",
"public static scpolicy_stats get(nitro_service service, String name) throws Exception{\n\t\tscpolicy_stats obj = new scpolicy_stats();\n\t\tobj.set_name(name);\n\t\tscpolicy_stats response = (scpolicy_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"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 }"
] |
Add the value to list of values to be used as part of the
evaluation of this indicator.
@param index position in the list
@param value evaluation value | [
"public void setRightValue(int index, Object value)\n {\n m_definedRightValues[index] = value;\n\n if (value instanceof FieldType)\n {\n m_symbolicValues = true;\n }\n else\n {\n if (value instanceof Duration)\n {\n if (((Duration) value).getUnits() != TimeUnit.HOURS)\n {\n value = ((Duration) value).convertUnits(TimeUnit.HOURS, m_properties);\n }\n }\n }\n\n m_workingRightValues[index] = value;\n }"
] | [
"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 }",
"void updateFromResponseOnDeletePost(Response<ResponseBody> response) throws IOException {\n this.withResponse(response);\n String responseContent = null;\n if (response.body() != null) {\n responseContent = response.body().string();\n response.body().close();\n }\n this.withResource(serializerAdapter.<T>deserialize(responseContent, resourceType));\n withStatus(AzureAsyncOperation.SUCCESS_STATUS, response.code());\n }",
"private 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 }",
"static synchronized void clearLogContext() {\n final LogContext embeddedLogContext = Holder.LOG_CONTEXT;\n // Remove the configurator and clear the log context\n final Configurator configurator = embeddedLogContext.getLogger(\"\").detach(Configurator.ATTACHMENT_KEY);\n // If this was a PropertyConfigurator we can use the LogContextConfiguration API to tear down the LogContext\n if (configurator instanceof PropertyConfigurator) {\n final LogContextConfiguration logContextConfiguration = ((PropertyConfigurator) configurator).getLogContextConfiguration();\n clearLogContext(logContextConfiguration);\n } else if (configurator instanceof LogContextConfiguration) {\n clearLogContext((LogContextConfiguration) configurator);\n } else {\n // Remove all the handlers and close them as well as reset the loggers\n final List<String> loggerNames = Collections.list(embeddedLogContext.getLoggerNames());\n for (String name : loggerNames) {\n final Logger logger = embeddedLogContext.getLoggerIfExists(name);\n if (logger != null) {\n final Handler[] handlers = logger.clearHandlers();\n if (handlers != null) {\n for (Handler handler : handlers) {\n handler.close();\n }\n }\n logger.setFilter(null);\n logger.setUseParentFilters(false);\n logger.setUseParentHandlers(true);\n logger.setLevel(Level.INFO);\n }\n }\n }\n }",
"@JmxOperation\n public String stopAsyncOperation(int requestId) {\n try {\n stopOperation(requestId);\n } catch(VoldemortException e) {\n return e.getMessage();\n }\n\n return \"Stopping operation \" + requestId;\n }",
"public static void addLazyDefinitions(SourceBuilder code) {\n Set<Declaration> defined = new HashSet<>();\n\n // Definitions may lazily declare new names; ensure we add them all\n List<Declaration> declarations =\n code.scope().keysOfType(Declaration.class).stream().sorted().collect(toList());\n while (!defined.containsAll(declarations)) {\n for (Declaration declaration : declarations) {\n if (defined.add(declaration)) {\n code.add(code.scope().get(declaration).definition);\n }\n }\n declarations = code.scope().keysOfType(Declaration.class).stream().sorted().collect(toList());\n }\n }",
"private void initManagementPart() {\n\n m_manageExceptionsButton.setText(Messages.get().key(Messages.GUI_SERIALDATE_BUTTON_MANAGE_EXCEPTIONS_0));\n m_manageExceptionsButton.getElement().getStyle().setFloat(Style.Float.RIGHT);\n }",
"public static appfwwsdl get(nitro_service service) throws Exception{\n\t\tappfwwsdl obj = new appfwwsdl();\n\t\tappfwwsdl[] response = (appfwwsdl[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public void reverse() {\n for (int i = 0, size = mTransitionControls.size(); i < size; i++) {\n mTransitionControls.get(i).reverse();\n }\n }"
] |
Overridden to add transform. | [
"@Override\n\tpublic void visit(FeatureTypeStyle fts) {\n\n\t\tFeatureTypeStyle copy = new FeatureTypeStyleImpl(\n\t\t\t\t(FeatureTypeStyleImpl) fts);\n\t\tRule[] rules = fts.getRules();\n\t\tint length = rules.length;\n\t\tRule[] rulesCopy = new Rule[length];\n\t\tfor (int i = 0; i < length; i++) {\n\t\t\tif (rules[i] != null) {\n\t\t\t\trules[i].accept(this);\n\t\t\t\trulesCopy[i] = (Rule) pages.pop();\n\t\t\t}\n\t\t}\n\t\tcopy.setRules(rulesCopy);\n\t\tif (fts.getTransformation() != null) {\n\t\t\tcopy.setTransformation(copy(fts.getTransformation()));\n\t\t}\n\t\tif (STRICT && !copy.equals(fts)) {\n\t\t\tthrow new IllegalStateException(\n\t\t\t\t\t\"Was unable to duplicate provided FeatureTypeStyle:\" + fts);\n\t\t}\n\t\tpages.push(copy);\n\t}"
] | [
"@JsonProperty(\"labels\")\n @JsonInclude(Include.NON_EMPTY)\n public Map<String, TermImpl> getLabelUpdates() {\n \treturn getMonolingualUpdatedValues(newLabels);\n }",
"public void _solveVectorInternal( double []vv )\n {\n // Solve L*Y = B\n int ii = 0;\n\n for( int i = 0; i < n; i++ ) {\n int ip = indx[i];\n double sum = vv[ip];\n vv[ip] = vv[i];\n if( ii != 0 ) {\n// for( int j = ii-1; j < i; j++ )\n// sum -= dataLU[i* n +j]*vv[j];\n int index = i*n + ii-1;\n for( int j = ii-1; j < i; j++ )\n sum -= dataLU[index++]*vv[j];\n } else if( sum != 0.0 ) {\n ii=i+1;\n }\n vv[i] = sum;\n }\n\n // Solve U*X = Y;\n TriangularSolver_DDRM.solveU(dataLU,vv,n);\n }",
"private void deliverMediaDetailsUpdate(final MediaDetails details) {\n for (MediaDetailsListener listener : getMediaDetailsListeners()) {\n try {\n listener.detailsAvailable(details);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering media details response to listener\", t);\n }\n }\n }",
"@SuppressWarnings(\"unchecked\")\n\tpublic Map<String, ?> decodeSignedRequest(String signedRequest) throws SignedRequestException {\n\t\treturn decodeSignedRequest(signedRequest, Map.class);\n\t}",
"private List<ExpandableWrapper<P, C>> generateFlattenedParentChildList(List<P> parentList) {\n List<ExpandableWrapper<P, C>> flatItemList = new ArrayList<>();\n\n int parentCount = parentList.size();\n for (int i = 0; i < parentCount; i++) {\n P parent = parentList.get(i);\n generateParentWrapper(flatItemList, parent, parent.isInitiallyExpanded());\n }\n\n return flatItemList;\n }",
"private void readLeafTasks(Task parent, Integer id)\n {\n Integer currentID = id;\n Table table = getTable(\"A1TAB\");\n while (currentID.intValue() != 0)\n {\n if (m_projectFile.getTaskByUniqueID(currentID) == null)\n {\n readTask(parent, currentID);\n }\n currentID = table.find(currentID).getInteger(\"NEXT_TASK_ID\");\n }\n }",
"public AT_Row setPaddingLeftChar(Character paddingLeftChar) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingLeftChar(paddingLeftChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public static double huntKennedyCMSOptionValue(\n\t\t\tdouble forwardSwaprate,\n\t\t\tdouble volatility,\n\t\t\tdouble swapAnnuity,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble swapMaturity,\n\t\t\tdouble payoffUnit,\n\t\t\tdouble optionStrike)\n\t{\n\t\tdouble a = 1.0/swapMaturity;\n\t\tdouble b = (payoffUnit / swapAnnuity - a) / forwardSwaprate;\n\t\tdouble convexityAdjustment = Math.exp(volatility*volatility*optionMaturity);\n\n\t\tdouble valueUnadjusted\t= blackModelSwaptionValue(forwardSwaprate, volatility, optionMaturity, optionStrike, swapAnnuity);\n\t\tdouble valueAdjusted\t= blackModelSwaptionValue(forwardSwaprate * convexityAdjustment, volatility, optionMaturity, optionStrike, swapAnnuity);\n\n\t\treturn a * valueUnadjusted + b * forwardSwaprate * valueAdjusted;\n\t}",
"private int[] getPrimaryCodewords() {\r\n\r\n assert mode == 2 || mode == 3;\r\n\r\n if (primaryData.length() != 15) {\r\n throw new OkapiException(\"Invalid Primary String\");\r\n }\r\n\r\n for (int i = 9; i < 15; i++) { /* check that country code and service are numeric */\r\n if (primaryData.charAt(i) < '0' || primaryData.charAt(i) > '9') {\r\n throw new OkapiException(\"Invalid Primary String\");\r\n }\r\n }\r\n\r\n String postcode;\r\n if (mode == 2) {\r\n postcode = primaryData.substring(0, 9);\r\n int index = postcode.indexOf(' ');\r\n if (index != -1) {\r\n postcode = postcode.substring(0, index);\r\n }\r\n } else {\r\n // if (mode == 3)\r\n postcode = primaryData.substring(0, 6);\r\n }\r\n\r\n int country = Integer.parseInt(primaryData.substring(9, 12));\r\n int service = Integer.parseInt(primaryData.substring(12, 15));\r\n\r\n if (debug) {\r\n System.out.println(\"Using mode \" + mode);\r\n System.out.println(\" Postcode: \" + postcode);\r\n System.out.println(\" Country Code: \" + country);\r\n System.out.println(\" Service: \" + service);\r\n }\r\n\r\n if (mode == 2) {\r\n return getMode2PrimaryCodewords(postcode, country, service);\r\n } else { // mode == 3\r\n return getMode3PrimaryCodewords(postcode, country, service);\r\n }\r\n }"
] |
Checks if maintenance mode is enabled for the given app
@param appName See {@link #listApps} for a list of apps that can be used.
@return true if maintenance mode is enabled | [
"public boolean isMaintenanceModeEnabled(String appName) {\n App app = connection.execute(new AppInfo(appName), apiKey);\n return app.isMaintenance();\n }"
] | [
"public void setAngularLowerLimits(float limitX, float limitY, float limitZ) {\n Native3DGenericConstraint.setAngularLowerLimits(getNative(), limitX, limitY, limitZ);\n }",
"private void processFile(InputStream is) throws MPXJException\n {\n int line = 1;\n\n try\n {\n //\n // Test the header and extract the separator. If this is successful,\n // we reset the stream back as far as we can. The design of the\n // BufferedInputStream class means that we can't get back to character\n // zero, so the first record we will read will get \"RMHDR\" rather than\n // \"ERMHDR\" in the first field position.\n //\n BufferedInputStream bis = new BufferedInputStream(is);\n byte[] data = new byte[6];\n data[0] = (byte) bis.read();\n bis.mark(1024);\n bis.read(data, 1, 5);\n\n if (!new String(data).equals(\"ERMHDR\"))\n {\n throw new MPXJException(MPXJException.INVALID_FILE);\n }\n\n bis.reset();\n\n InputStreamReader reader = new InputStreamReader(bis, getCharset());\n Tokenizer tk = new ReaderTokenizer(reader);\n tk.setDelimiter('\\t');\n List<String> record = new ArrayList<String>();\n\n while (tk.getType() != Tokenizer.TT_EOF)\n {\n readRecord(tk, record);\n if (!record.isEmpty())\n {\n if (processRecord(record))\n {\n break;\n }\n }\n ++line;\n }\n }\n\n catch (Exception ex)\n {\n throw new MPXJException(MPXJException.READ_ERROR + \" (failed at line \" + line + \")\", ex);\n }\n }",
"public static base_response delete(nitro_service client) throws Exception {\n\t\tlocationfile deleteresource = new locationfile();\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"void register(long mjDay, int leapAdjustment) {\n if (leapAdjustment != -1 && leapAdjustment != 1) {\n throw new IllegalArgumentException(\"Leap adjustment must be -1 or 1\");\n }\n Data data = dataRef.get();\n int pos = Arrays.binarySearch(data.dates, mjDay);\n int currentAdj = pos > 0 ? data.offsets[pos] - data.offsets[pos - 1] : 0;\n if (currentAdj == leapAdjustment) {\n return; // matches previous definition\n }\n if (mjDay <= data.dates[data.dates.length - 1]) {\n throw new IllegalArgumentException(\"Date must be after the last configured leap second date\");\n }\n long[] dates = Arrays.copyOf(data.dates, data.dates.length + 1);\n int[] offsets = Arrays.copyOf(data.offsets, data.offsets.length + 1);\n long[] taiSeconds = Arrays.copyOf(data.taiSeconds, data.taiSeconds.length + 1);\n int offset = offsets[offsets.length - 2] + leapAdjustment;\n dates[dates.length - 1] = mjDay;\n offsets[offsets.length - 1] = offset;\n taiSeconds[taiSeconds.length - 1] = tai(mjDay, offset);\n Data newData = new Data(dates, offsets, taiSeconds);\n if (dataRef.compareAndSet(data, newData) == false) {\n throw new ConcurrentModificationException(\"Unable to update leap second rules as they have already been updated\");\n }\n }",
"public Object invokeMethod(String name, Object args) {\n Object val = null;\n if (args != null && Object[].class.isAssignableFrom(args.getClass())) {\n Object[] arr = (Object[]) args;\n\n if (arr.length == 1) {\n val = arr[0];\n } else if (arr.length == 2 && arr[0] instanceof Collection && arr[1] instanceof Closure) {\n Closure<?> closure = (Closure<?>) arr[1];\n Iterator<?> iterator = ((Collection) arr[0]).iterator();\n List<Object> list = new ArrayList<Object>();\n while (iterator.hasNext()) {\n list.add(curryDelegateAndGetContent(closure, iterator.next()));\n }\n val = list;\n } else {\n val = Arrays.asList(arr);\n }\n }\n content.put(name, val);\n\n return val;\n }",
"public static void setPropertySafely(Marshaller marshaller, String name, Object value) {\n try {\n marshaller.setProperty(name, value);\n } catch (PropertyException e) {\n LOGGER.warn(String.format(\"Can't set \\\"%s\\\" property to given marshaller\", name), e);\n }\n }",
"public static void log(String label, byte[] data)\n {\n if (LOG != null)\n {\n LOG.write(label);\n LOG.write(\": \");\n LOG.println(ByteArrayHelper.hexdump(data, true));\n LOG.flush();\n }\n }",
"public void forAllTables(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _torqueModel.getTables(); it.hasNext(); )\r\n {\r\n _curTableDef = (TableDef)it.next();\r\n generate(template);\r\n }\r\n _curTableDef = null;\r\n }",
"public static spilloverpolicy_stats[] get(nitro_service service) throws Exception{\n\t\tspilloverpolicy_stats obj = new spilloverpolicy_stats();\n\t\tspilloverpolicy_stats[] response = (spilloverpolicy_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}"
] |
Put a new value in map.
@param key id of the value for looking up.
@param value the value. | [
"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 }"
] | [
"@Override\n public EthiopicDate date(Era era, int yearOfEra, int month, int dayOfMonth) {\n return date(prolepticYear(era, yearOfEra), month, dayOfMonth);\n }",
"public static double J0(double x) {\r\n double ax;\r\n\r\n if ((ax = Math.abs(x)) < 8.0) {\r\n double y = x * x;\r\n double ans1 = 57568490574.0 + y * (-13362590354.0 + y * (651619640.7\r\n + y * (-11214424.18 + y * (77392.33017 + y * (-184.9052456)))));\r\n double ans2 = 57568490411.0 + y * (1029532985.0 + y * (9494680.718\r\n + y * (59272.64853 + y * (267.8532712 + y * 1.0))));\r\n\r\n return ans1 / ans2;\r\n } else {\r\n double z = 8.0 / ax;\r\n double y = z * z;\r\n double xx = ax - 0.785398164;\r\n double ans1 = 1.0 + y * (-0.1098628627e-2 + y * (0.2734510407e-4\r\n + y * (-0.2073370639e-5 + y * 0.2093887211e-6)));\r\n double ans2 = -0.1562499995e-1 + y * (0.1430488765e-3\r\n + y * (-0.6911147651e-5 + y * (0.7621095161e-6\r\n - y * 0.934935152e-7)));\r\n\r\n return Math.sqrt(0.636619772 / ax) *\r\n (Math.cos(xx) * ans1 - z * Math.sin(xx) * ans2);\r\n }\r\n }",
"public int[] executeBatch(PreparedStatement stmt) throws PlatformException\r\n {\r\n // Check for Oracle batching support\r\n final Method methodSendBatch = (Method) m_batchStatementsInProgress.remove(stmt);\r\n final boolean statementBatchingSupported = methodSendBatch != null;\r\n\r\n int[] retval = null;\r\n if (statementBatchingSupported)\r\n {\r\n try\r\n {\r\n // sendBatch() returns total row count as an Integer\r\n methodSendBatch.invoke(stmt, null);\r\n }\r\n catch (Exception e)\r\n {\r\n throw new PlatformException(e.getLocalizedMessage(), e);\r\n }\r\n }\r\n else\r\n {\r\n retval = super.executeBatch(stmt);\r\n }\r\n return retval;\r\n }",
"@SuppressWarnings(\"unchecked\")\n public Map<String, Field> getValueAsMap() {\n return (Map<String, Field>) type.convert(getValue(), Type.MAP);\n }",
"public Where<T, ID> in(String columnName, Iterable<?> objects) throws SQLException {\n\t\taddClause(new In(columnName, findColumnFieldType(columnName), objects, true));\n\t\treturn this;\n\t}",
"public void remove(Identity oid)\r\n {\r\n //processQueue();\r\n if(oid != null)\r\n {\r\n removeTracedIdentity(oid);\r\n objectTable.remove(buildKey(oid));\r\n if(log.isDebugEnabled()) log.debug(\"Remove object \" + oid);\r\n }\r\n }",
"public RgbaColor opacify(float amount) {\n return new RgbaColor(r, g, b, alphaCheck(a + amount));\n }",
"public static String resolveDataSourceTypeFromDialect(String dialect)\n {\n if (StringUtils.contains(dialect, \"Oracle\"))\n {\n return \"Oracle\";\n }\n else if (StringUtils.contains(dialect, \"MySQL\"))\n {\n return \"MySQL\";\n }\n else if (StringUtils.contains(dialect, \"DB2390Dialect\"))\n {\n return \"DB2/390\";\n }\n else if (StringUtils.contains(dialect, \"DB2400Dialect\"))\n {\n return \"DB2/400\";\n }\n else if (StringUtils.contains(dialect, \"DB2\"))\n {\n return \"DB2\";\n }\n else if (StringUtils.contains(dialect, \"Ingres\"))\n {\n return \"Ingres\";\n }\n else if (StringUtils.contains(dialect, \"Derby\"))\n {\n return \"Derby\";\n }\n else if (StringUtils.contains(dialect, \"Pointbase\"))\n {\n return \"Pointbase\";\n }\n else if (StringUtils.contains(dialect, \"Postgres\"))\n {\n return \"Postgres\";\n }\n else if (StringUtils.contains(dialect, \"SQLServer\"))\n {\n return \"SQLServer\";\n }\n else if (StringUtils.contains(dialect, \"Sybase\"))\n {\n return \"Sybase\";\n }\n else if (StringUtils.contains(dialect, \"HSQLDialect\"))\n {\n return \"HyperSQL\";\n }\n else if (StringUtils.contains(dialect, \"H2Dialect\"))\n {\n return \"H2\";\n }\n \n return dialect;\n\n }",
"private void setRecordNumber(LinkedList<String> list)\n {\n try\n {\n String number = list.remove(0);\n m_recordNumber = Integer.valueOf(number);\n }\n catch (NumberFormatException ex)\n {\n // Malformed MPX file: the record number isn't a valid integer\n // Catch the exception here, leaving m_recordNumber as null\n // so we will skip this record entirely.\n }\n }"
] |
Creates the JSON serialized form of the accessory for use over the Homekit Accessory Protocol.
@param instanceId the static id of the accessory.
@return a future that will complete with the JSON builder for the object. | [
"protected CompletableFuture<JsonObjectBuilder> makeBuilder(int instanceId) {\n CompletableFuture<T> futureValue = getValue();\n\n if (futureValue == null) {\n logger.error(\"Could not retrieve value \" + this.getClass().getName());\n return null;\n }\n\n return futureValue\n .exceptionally(\n t -> {\n logger.error(\"Could not retrieve value \" + this.getClass().getName(), t);\n return null;\n })\n .thenApply(\n value -> {\n JsonArrayBuilder perms = Json.createArrayBuilder();\n if (isWritable) {\n perms.add(\"pw\");\n }\n if (isReadable) {\n perms.add(\"pr\");\n }\n if (isEventable) {\n perms.add(\"ev\");\n }\n JsonObjectBuilder builder =\n Json.createObjectBuilder()\n .add(\"iid\", instanceId)\n .add(\"type\", shortType)\n .add(\"perms\", perms.build())\n .add(\"format\", format)\n .add(\"ev\", false)\n .add(\"description\", description);\n setJsonValue(builder, value);\n return builder;\n });\n }"
] | [
"public ListenableFuture<Connection> getAsyncConnection(){\r\n\r\n\t\treturn this.asyncExecutor.submit(new Callable<Connection>() {\r\n\r\n\t\t\tpublic Connection call() throws Exception {\r\n\t\t\t\treturn getConnection();\r\n\t\t\t}});\r\n\t}",
"private void renameReadOnlyV2Files(int masterPartitionId, int correctReplicaType) {\n for (int replica = 0; replica < routingStrategy.getNumReplicas(); replica++) {\n if (replica != correctReplicaType) {\n int chunkId = 0;\n while (true) {\n String fileName = Integer.toString(masterPartitionId) + \"_\"\n + Integer.toString(replica) + \"_\"\n + Integer.toString(chunkId);\n File index = getIndexFile(fileName);\n File data = getDataFile(fileName);\n\n if(index.exists() && data.exists()) {\n // We found files with the \"wrong\" replica type, so let's rename them\n\n String correctFileName = Integer.toString(masterPartitionId) + \"_\"\n + Integer.toString(correctReplicaType) + \"_\"\n + Integer.toString(chunkId);\n File indexWithCorrectReplicaType = getIndexFile(correctFileName);\n File dataWithCorrectReplicaType = getDataFile(correctFileName);\n\n Utils.move(index, indexWithCorrectReplicaType);\n Utils.move(data, dataWithCorrectReplicaType);\n\n // Maybe change this to DEBUG?\n logger.info(\"Renamed files with wrong replica type: \"\n + index.getAbsolutePath() + \"|data -> \"\n + indexWithCorrectReplicaType.getName() + \"|data\");\n } else if(index.exists() ^ data.exists()) {\n throw new VoldemortException(\"One of the following does not exist: \"\n + index.toString()\n + \" or \"\n + data.toString() + \".\");\n } else {\n // The files don't exist, or we've gone over all available chunks,\n // so let's move on.\n break;\n }\n chunkId++;\n }\n }\n }\n }",
"public int createLogs(String topic, final int partitions, final boolean forceEnlarge) {\n TopicNameValidator.validate(topic);\n synchronized (logCreationLock) {\n final int configPartitions = getPartition(topic);\n if (configPartitions >= partitions || !forceEnlarge) {\n return configPartitions;\n }\n topicPartitionsMap.put(topic, partitions);\n if (config.getEnableZookeeper()) {\n if (getLogPool(topic, 0) != null) {//created already\n topicRegisterTasks.add(new TopicTask(TopicTask.TaskType.ENLARGE, topic));\n } else {\n topicRegisterTasks.add(new TopicTask(TopicTask.TaskType.CREATE, topic));\n }\n }\n return partitions;\n }\n }",
"public static base_response update(nitro_service client, sslcertkey resource) throws Exception {\n\t\tsslcertkey updateresource = new sslcertkey();\n\t\tupdateresource.certkey = resource.certkey;\n\t\tupdateresource.expirymonitor = resource.expirymonitor;\n\t\tupdateresource.notificationperiod = resource.notificationperiod;\n\t\treturn updateresource.update_resource(client);\n\t}",
"private static JSONArray parseDockers(ArrayList<Point> dockers) throws JSONException {\n if (dockers != null) {\n JSONArray dockersArray = new JSONArray();\n\n for (Point docker : dockers) {\n JSONObject dockerObject = new JSONObject();\n\n dockerObject.put(\"x\",\n docker.getX().doubleValue());\n dockerObject.put(\"y\",\n docker.getY().doubleValue());\n\n dockersArray.put(dockerObject);\n }\n\n return dockersArray;\n }\n\n return new JSONArray();\n }",
"@Override\n public void put(ByteArray keyBytes, Versioned<byte[]> valueBytes, byte[] transforms)\n throws VoldemortException {\n // acquire write lock\n writeLock.lock();\n try {\n String key = ByteUtils.getString(keyBytes.get(), \"UTF-8\");\n Versioned<String> value = new Versioned<String>(ByteUtils.getString(valueBytes.getValue(),\n \"UTF-8\"),\n valueBytes.getVersion());\n\n Versioned<Object> valueObject = convertStringToObject(key, value);\n\n this.put(key, valueObject);\n } finally {\n writeLock.unlock();\n }\n }",
"public static void mark(DeploymentUnit unit) {\n unit = DeploymentUtils.getTopDeploymentUnit(unit);\n unit.putAttachment(MARKER, Boolean.TRUE);\n }",
"public Number getPercentageWorkComplete()\n {\n Number pct = (Number) getCachedValue(AssignmentField.PERCENT_WORK_COMPLETE);\n if (pct == null)\n {\n Duration actualWork = getActualWork();\n Duration work = getWork();\n if (actualWork != null && work != null && work.getDuration() != 0)\n {\n pct = Double.valueOf((actualWork.getDuration() * 100) / work.convertUnits(actualWork.getUnits(), getParentFile().getProjectProperties()).getDuration());\n set(AssignmentField.PERCENT_WORK_COMPLETE, pct);\n }\n }\n return pct;\n }",
"public void addIterator(OJBIterator iterator)\r\n {\r\n /**\r\n * only add iterators that are not null and non-empty.\r\n */\r\n if (iterator != null)\r\n {\r\n if (iterator.hasNext())\r\n {\r\n setNextIterator();\r\n m_rsIterators.add(iterator);\r\n }\r\n }\r\n }"
] |
Return the TransactionManager of the external app | [
"private TransactionManager getTransactionManager()\r\n {\r\n TransactionManager retval = null;\r\n try\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"getTransactionManager called\");\r\n retval = TransactionManagerFactoryFactory.instance().getTransactionManager();\r\n }\r\n catch (TransactionManagerFactoryException e)\r\n {\r\n log.warn(\"Exception trying to obtain TransactionManager from Factory\", e);\r\n e.printStackTrace();\r\n }\r\n return retval;\r\n }"
] | [
"public PhotoList<Photo> getClusterPhotos(String tag, String clusterId) throws FlickrException {\n\n PhotoList<Photo> photos = new PhotoList<Photo>();\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_CLUSTER_PHOTOS);\n\n parameters.put(\"tag\", tag);\n parameters.put(\"cluster_id\", clusterId);\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 photosElement = response.getPayload();\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\n photos.setPage(\"1\");\n photos.setPages(\"1\");\n photos.setPerPage(\"\" + photoNodes.getLength());\n photos.setTotal(\"\" + photoNodes.getLength());\n for (int i = 0; i < photoNodes.getLength(); i++) {\n Element photoElement = (Element) photoNodes.item(i);\n photos.add(PhotoUtils.createPhoto(photoElement));\n }\n return photos;\n }",
"public void forAllIndexDescriptorDefinitions(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _curClassDef.getIndexDescriptors(); it.hasNext(); )\r\n {\r\n _curIndexDescriptorDef = (IndexDescriptorDef)it.next();\r\n generate(template);\r\n }\r\n _curIndexDescriptorDef = null;\r\n }",
"public void getElevationAlongPath(PathElevationRequest req, ElevationServiceCallback callback) {\n \n this.callback = callback;\n \n JSObject doc = (JSObject) getJSObject().eval(\"document\");\n doc.setMember(getVariableName(), this);\n \n StringBuilder r = new StringBuilder(getVariableName())\n .append(\".\")\n .append(\"getElevationAlongPath(\")\n .append(req.getVariableName())\n .append(\", \")\n .append(\"function(results, status) {document.\")\n .append(getVariableName())\n .append(\".processResponse(results, status);});\");\n \n getJSObject().eval(r.toString());\n \n }",
"@Pure\n\tpublic static <K, V> Pair<K, V> of(K k, V v) {\n\t\treturn new Pair<K, V>(k, v);\n\t}",
"public void registerComponent(java.awt.Component c)\r\n {\r\n unregisterComponent(c);\r\n if (recognizerAbstractClass == null)\r\n {\r\n hmDragGestureRecognizers.put(c, \r\n dragSource.createDefaultDragGestureRecognizer(c, \r\n dragWorker.getAcceptableActions(c), dgListener)\r\n );\r\n }\r\n else\r\n {\r\n hmDragGestureRecognizers.put(c, \r\n dragSource.createDragGestureRecognizer (recognizerAbstractClass,\r\n c, dragWorker.getAcceptableActions(c), dgListener)\r\n );\r\n }\r\n }",
"public static boolean sameNetwork(int prefixLength, InetAddress address1, InetAddress address2) {\n if (logger.isDebugEnabled()) {\n logger.debug(\"Comparing address \" + address1.getHostAddress() + \" with \" + address2.getHostAddress() + \", prefixLength=\" + prefixLength);\n }\n long prefixMask = 0xffffffffL & (-1 << (32 - prefixLength));\n return (addressToLong(address1) & prefixMask) == (addressToLong(address2) & prefixMask);\n }",
"public static Thread addShutdownHook(final Process process) {\n final Thread thread = new Thread(new Runnable() {\n @Override\n public void run() {\n if (process != null) {\n process.destroy();\n try {\n process.waitFor();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n }\n }\n });\n thread.setDaemon(true);\n Runtime.getRuntime().addShutdownHook(thread);\n return thread;\n }",
"public static <T> T buildInstanceForMap(Class<T> clazz, Map<String, Object> values)\n throws InstantiationException, IllegalAccessException, IntrospectionException,\n IllegalArgumentException, InvocationTargetException {\n return buildInstanceForMap(clazz, values, new MyDefaultReflectionDifferenceHandler());\n }",
"public static appflowpolicy_appflowpolicylabel_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappflowpolicy_appflowpolicylabel_binding obj = new appflowpolicy_appflowpolicylabel_binding();\n\t\tobj.set_name(name);\n\t\tappflowpolicy_appflowpolicylabel_binding response[] = (appflowpolicy_appflowpolicylabel_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Check the given resource back into the pool
@param key The key for the resource
@param resource The resource | [
"@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 }"
] | [
"public CoordinatorConfig setBootstrapURLs(List<String> bootstrapUrls) {\n this.bootstrapURLs = Utils.notNull(bootstrapUrls);\n if(this.bootstrapURLs.size() <= 0)\n throw new IllegalArgumentException(\"Must provide at least one bootstrap URL.\");\n return this;\n }",
"@Override\n public Response doRequest(final StitchRequest stitchReq) {\n initAppMetadata(clientAppId);\n\n return super.doRequestUrl(stitchReq, getHostname());\n }",
"public void setFrustum(Matrix4f projMatrix)\n {\n if (projMatrix != null)\n {\n if (mProjMatrix == null)\n {\n mProjMatrix = new float[16];\n }\n mProjMatrix = projMatrix.get(mProjMatrix, 0);\n mScene.setPickVisible(false);\n if (mCuller != null)\n {\n mCuller.set(projMatrix);\n }\n else\n {\n mCuller = new FrustumIntersection(projMatrix);\n }\n }\n mProjection = projMatrix;\n }",
"private void addDownloadButton(final CmsLogFileView view) {\n\n Button button = CmsToolBar.createButton(\n FontOpenCms.DOWNLOAD,\n CmsVaadinUtils.getMessageText(Messages.GUI_LOGFILE_DOWNLOAD_0));\n button.addClickListener(new ClickListener() {\n\n private static final long serialVersionUID = 1L;\n\n public void buttonClick(ClickEvent event) {\n\n Window window = CmsBasicDialog.prepareWindow(CmsBasicDialog.DialogWidth.wide);\n window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_LOGFILE_DOWNLOAD_0));\n window.setContent(new CmsLogDownloadDialog(window, view.getCurrentFile()));\n A_CmsUI.get().addWindow(window);\n }\n });\n m_uiContext.addToolbarButton(button);\n }",
"private void initializeLogging() {\n\t\t// Since logging is static, make sure this is done only once even if\n\t\t// multiple clients are created (e.g., during tests)\n\t\tif (consoleAppender != null) {\n\t\t\treturn;\n\t\t}\n\n\t\tconsoleAppender = new ConsoleAppender();\n\t\tconsoleAppender.setLayout(new PatternLayout(LOG_PATTERN));\n\t\tconsoleAppender.setThreshold(Level.INFO);\n\t\tLevelRangeFilter filter = new LevelRangeFilter();\n\t\tfilter.setLevelMin(Level.TRACE);\n\t\tfilter.setLevelMax(Level.INFO);\n\t\tconsoleAppender.addFilter(filter);\n\t\tconsoleAppender.activateOptions();\n\t\torg.apache.log4j.Logger.getRootLogger().addAppender(consoleAppender);\n\n\t\terrorAppender = new ConsoleAppender();\n\t\terrorAppender.setLayout(new PatternLayout(LOG_PATTERN));\n\t\terrorAppender.setThreshold(Level.WARN);\n\t\terrorAppender.setTarget(ConsoleAppender.SYSTEM_ERR);\n\t\terrorAppender.activateOptions();\n\t\torg.apache.log4j.Logger.getRootLogger().addAppender(errorAppender);\n\t}",
"private CompiledStatement assignStatementArguments(CompiledStatement stmt) throws SQLException {\n\t\tboolean ok = false;\n\t\ttry {\n\t\t\tif (limit != null) {\n\t\t\t\t// we use this if SQL statement LIMITs are not supported by this database type\n\t\t\t\tstmt.setMaxRows(limit.intValue());\n\t\t\t}\n\t\t\t// set any arguments if we are logging our object\n\t\t\tObject[] argValues = null;\n\t\t\tif (logger.isLevelEnabled(Level.TRACE) && argHolders.length > 0) {\n\t\t\t\targValues = new Object[argHolders.length];\n\t\t\t}\n\t\t\tfor (int i = 0; i < argHolders.length; i++) {\n\t\t\t\tObject argValue = argHolders[i].getSqlArgValue();\n\t\t\t\tFieldType fieldType = argFieldTypes[i];\n\t\t\t\tSqlType sqlType;\n\t\t\t\tif (fieldType == null) {\n\t\t\t\t\tsqlType = argHolders[i].getSqlType();\n\t\t\t\t} else {\n\t\t\t\t\tsqlType = fieldType.getSqlType();\n\t\t\t\t}\n\t\t\t\tstmt.setObject(i, argValue, sqlType);\n\t\t\t\tif (argValues != null) {\n\t\t\t\t\targValues[i] = argValue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tlogger.debug(\"prepared statement '{}' with {} args\", statement, argHolders.length);\n\t\t\tif (argValues != null) {\n\t\t\t\t// need to do the (Object) cast to force args to be a single object\n\t\t\t\tlogger.trace(\"prepared statement arguments: {}\", (Object) argValues);\n\t\t\t}\n\t\t\tok = true;\n\t\t\treturn stmt;\n\t\t} finally {\n\t\t\tif (!ok) {\n\t\t\t\tIOUtils.closeThrowSqlException(stmt, \"statement\");\n\t\t\t}\n\t\t}\n\t}",
"public static AnnotationNode getAnnotation(AnnotatedNode node, String name) {\r\n List<AnnotationNode> annotations = node.getAnnotations();\r\n for (AnnotationNode annot : annotations) {\r\n if (annot.getClassNode().getName().equals(name)) {\r\n return annot;\r\n }\r\n }\r\n return null;\r\n }",
"static String replaceCheckDigit(final String iban, final String checkDigit) {\n return getCountryCode(iban) + checkDigit + getBban(iban);\n }",
"public static base_response unset(nitro_service client, snmpmanager resource, String[] args) throws Exception{\n\t\tsnmpmanager unsetresource = new snmpmanager();\n\t\tunsetresource.ipaddress = resource.ipaddress;\n\t\tunsetresource.netmask = resource.netmask;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}"
] |
This method retrieves a double value from a String instance.
It returns zero by default if a null value or an empty string is supplied.
@param value string representation of a double
@return double value | [
"public static final double getDouble(String value)\n {\n return (value == null || value.length() == 0 ? 0 : Double.parseDouble(value));\n }"
] | [
"public synchronized void stop() {\n if (isRunning()) {\n running.set(false);\n DeviceFinder.getInstance().removeDeviceAnnouncementListener(announcementListener);\n dbServerPorts.clear();\n for (Client client : openClients.values()) {\n try {\n client.close();\n } catch (Exception e) {\n logger.warn(\"Problem closing \" + client + \" when stopping\", e);\n }\n }\n openClients.clear();\n useCounts.clear();\n deliverLifecycleAnnouncement(logger, false);\n }\n }",
"public static List<DatabaseTableConfig<?>> loadDatabaseConfigFromReader(BufferedReader reader) throws SQLException {\n\t\tList<DatabaseTableConfig<?>> list = new ArrayList<DatabaseTableConfig<?>>();\n\t\twhile (true) {\n\t\t\tDatabaseTableConfig<?> config = DatabaseTableConfigLoader.fromReader(reader);\n\t\t\tif (config == null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tlist.add(config);\n\t\t}\n\t\treturn list;\n\t}",
"public static final void decodeBuffer(byte[] data, byte encryptionCode)\n {\n for (int i = 0; i < data.length; i++)\n {\n data[i] = (byte) (data[i] ^ encryptionCode);\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 }",
"private void handleSendDataResponse(SerialMessage incomingMessage) {\n\t\tlogger.trace(\"Handle Message Send Data Response\");\n\t\tif(incomingMessage.getMessageBuffer()[2] != 0x00)\n\t\t\tlogger.debug(\"Sent Data successfully placed on stack.\");\n\t\telse\n\t\t\tlogger.error(\"Sent Data was not placed on stack due to error.\");\n\t}",
"private static List<Node> difference(List<Node> listA, List<Node> listB) {\n if(listA != null && listB != null)\n listA.removeAll(listB);\n return listA;\n }",
"public static cmppolicylabel_stats get(nitro_service service, String labelname) throws Exception{\n\t\tcmppolicylabel_stats obj = new cmppolicylabel_stats();\n\t\tobj.set_labelname(labelname);\n\t\tcmppolicylabel_stats response = (cmppolicylabel_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"public static Tuple2<Double, Double> getRandomGeographicalLocation() {\r\n return new Tuple2<>(\r\n (double) (RandomHelper.randWithConfiguredSeed().nextInt(999) + 1) / 100,\r\n (double) (RandomHelper.randWithConfiguredSeed().nextInt(999) + 1) / 100);\r\n }",
"public T removeModule(final String moduleName, final String slot, final byte[] existingHash) {\n final ContentItem item = createModuleItem(moduleName, slot, NO_CONTENT);\n addContentModification(createContentModification(item, ModificationType.REMOVE, existingHash));\n return returnThis();\n }"
] |
Helper method used to peel off spurious wrappings of DateTimeException
@param e DateTimeException to peel
@return DateTimeException that does not have another DateTimeException as its cause. | [
"protected DateTimeException _peelDTE(DateTimeException e) {\n while (true) {\n Throwable t = e.getCause();\n if (t != null && t instanceof DateTimeException) {\n e = (DateTimeException) t;\n continue;\n }\n break;\n }\n return e;\n }"
] | [
"public static vpath get(nitro_service service, String name) throws Exception{\n\t\tvpath obj = new vpath();\n\t\tobj.set_name(name);\n\t\tvpath response = (vpath) obj.get_resource(service);\n\t\treturn response;\n\t}",
"@Override\n protected void initBuilderSpecific() throws Exception {\n reset();\n FilePath workspace = getModuleRoot(EnvVars.masterEnvVars);\n FilePath gradlePropertiesPath = new FilePath(workspace, \"gradle.properties\");\n if (releaseProps == null) {\n releaseProps = PropertyUtils.getModulesPropertiesFromPropFile(gradlePropertiesPath, getReleaseProperties());\n }\n if (nextIntegProps == null) {\n nextIntegProps =\n PropertyUtils.getModulesPropertiesFromPropFile(gradlePropertiesPath, getNextIntegProperties());\n }\n }",
"void setParent(ProjectCalendarWeek parent)\n {\n m_parent = parent;\n\n for (int loop = 0; loop < m_days.length; loop++)\n {\n if (m_days[loop] == null)\n {\n m_days[loop] = DayType.DEFAULT;\n }\n }\n }",
"public void add(K key, V value) {\r\n if (treatCollectionsAsImmutable) {\r\n Collection<V> newC = cf.newCollection();\r\n Collection<V> c = map.get(key);\r\n if (c != null) {\r\n newC.addAll(c);\r\n }\r\n newC.add(value);\r\n map.put(key, newC); // replacing the old collection\r\n } else {\r\n Collection<V> c = map.get(key);\r\n if (c == null) {\r\n c = cf.newCollection();\r\n map.put(key, c);\r\n }\r\n c.add(value); // modifying the old collection\r\n }\r\n }",
"String buildProjectEndpoint(DatastoreOptions options) {\n if (options.getProjectEndpoint() != null) {\n return options.getProjectEndpoint();\n }\n // DatastoreOptions ensures either project endpoint or project ID is set.\n String projectId = checkNotNull(options.getProjectId());\n if (options.getHost() != null) {\n return validateUrl(String.format(\"https://%s/%s/projects/%s\",\n options.getHost(), VERSION, projectId));\n } else if (options.getLocalHost() != null) {\n return validateUrl(String.format(\"http://%s/%s/projects/%s\",\n options.getLocalHost(), VERSION, projectId));\n }\n return validateUrl(String.format(\"%s/%s/projects/%s\",\n DEFAULT_HOST, VERSION, projectId));\n }",
"public static gslbvserver_spilloverpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tgslbvserver_spilloverpolicy_binding obj = new gslbvserver_spilloverpolicy_binding();\n\t\tobj.set_name(name);\n\t\tgslbvserver_spilloverpolicy_binding response[] = (gslbvserver_spilloverpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static streamidentifier_stats get(nitro_service service, String name) throws Exception{\n\t\tstreamidentifier_stats obj = new streamidentifier_stats();\n\t\tobj.set_name(name);\n\t\tstreamidentifier_stats response = (streamidentifier_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"public static double HighAccuracyComplemented(double x) {\n double[] R =\n {\n 1.25331413731550025, 0.421369229288054473, 0.236652382913560671,\n 0.162377660896867462, 0.123131963257932296, 0.0990285964717319214,\n 0.0827662865013691773, 0.0710695805388521071, 0.0622586659950261958\n };\n\n int j = (int) (0.5 * (Math.abs(x) + 1));\n\n double a = R[j];\n double z = 2 * j;\n double b = a * z - 1;\n\n double h = Math.abs(x) - z;\n double q = h * h;\n double pwr = 1;\n\n double sum = a + h * b;\n double term = a;\n\n\n for (int i = 2; sum != term; i += 2) {\n term = sum;\n\n a = (a + z * b) / (i);\n b = (b + z * a) / (i + 1);\n pwr *= q;\n\n sum = term + pwr * (a + h * b);\n }\n\n sum *= Math.exp(-0.5 * (x * x) - 0.5 * Constants.Log2PI);\n\n return (x >= 0) ? sum : (1.0 - sum);\n }",
"public static nsrpcnode get(nitro_service service, String ipaddress) throws Exception{\n\t\tnsrpcnode obj = new nsrpcnode();\n\t\tobj.set_ipaddress(ipaddress);\n\t\tnsrpcnode response = (nsrpcnode) obj.get_resource(service);\n\t\treturn response;\n\t}"
] |
Magnitude of complex number.
@param z Complex number.
@return Magnitude of complex number. | [
"public static double Magnitude(ComplexNumber z) {\r\n return Math.sqrt(z.real * z.real + z.imaginary * z.imaginary);\r\n }"
] | [
"public static void addActionsTo(\n SourceBuilder code,\n Set<MergeAction> mergeActions,\n boolean forBuilder) {\n SetMultimap<String, String> nounsByVerb = TreeMultimap.create();\n mergeActions.forEach(mergeAction -> {\n if (forBuilder || !mergeAction.builderOnly) {\n nounsByVerb.put(mergeAction.verb, mergeAction.noun);\n }\n });\n List<String> verbs = ImmutableList.copyOf(nounsByVerb.keySet());\n String lastVerb = getLast(verbs, null);\n for (String verb : nounsByVerb.keySet()) {\n code.add(\", %s%s\", (verbs.size() > 1 && verb.equals(lastVerb)) ? \"and \" : \"\", verb);\n List<String> nouns = ImmutableList.copyOf(nounsByVerb.get(verb));\n for (int i = 0; i < nouns.size(); ++i) {\n String separator = (i == 0) ? \"\" : (i == nouns.size() - 1) ? \" and\" : \",\";\n code.add(\"%s %s\", separator, nouns.get(i));\n }\n }\n }",
"protected void processProjectListItem(Map<Integer, String> result, Row row)\n {\n Integer id = row.getInteger(\"PROJ_ID\");\n String name = row.getString(\"PROJ_NAME\");\n result.put(id, name);\n }",
"public Object remove(Object key)\r\n {\r\n if (key == null) return null;\r\n purge();\r\n int hash = hashCode(key);\r\n int index = indexFor(hash);\r\n Entry previous = null;\r\n Entry entry = table[index];\r\n while (entry != null)\r\n {\r\n if ((hash == entry.hash) && equals(key, entry.getKey()))\r\n {\r\n if (previous == null)\r\n table[index] = entry.next;\r\n else\r\n previous.next = entry.next;\r\n this.size--;\r\n modCount++;\r\n return entry.getValue();\r\n }\r\n previous = entry;\r\n entry = entry.next;\r\n }\r\n return null;\r\n }",
"public JsonTypeDefinition projectionType(String... properties) {\n if(this.getType() instanceof Map<?, ?>) {\n Map<?, ?> type = (Map<?, ?>) getType();\n Arrays.sort(properties);\n Map<String, Object> newType = new LinkedHashMap<String, Object>();\n for(String prop: properties)\n newType.put(prop, type.get(prop));\n return new JsonTypeDefinition(newType);\n } else {\n throw new IllegalArgumentException(\"Cannot take the projection of a type that is not a Map.\");\n }\n }",
"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 }",
"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 void checkReferenceForeignkeys(ModelDef modelDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n ClassDescriptorDef classDef;\r\n ReferenceDescriptorDef refDef;\r\n\r\n for (Iterator it = modelDef.getClasses(); it.hasNext();)\r\n {\r\n classDef = (ClassDescriptorDef)it.next();\r\n for (Iterator refIt = classDef.getReferences(); refIt.hasNext();)\r\n {\r\n refDef = (ReferenceDescriptorDef)refIt.next();\r\n if (!refDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))\r\n {\r\n checkReferenceForeignkeys(modelDef, refDef);\r\n }\r\n }\r\n }\r\n }",
"public void printAnswers(List<CoreLabel> doc, PrintWriter out) {\r\n // boolean tagsMerged = flags.mergeTags;\r\n // boolean useHead = flags.splitOnHead;\r\n\r\n if ( ! \"iob1\".equalsIgnoreCase(flags.entitySubclassification)) {\r\n deEndify(doc);\r\n }\r\n\r\n for (CoreLabel fl : doc) {\r\n String word = fl.word();\r\n if (word == BOUNDARY) { // Using == is okay, because it is set to constant\r\n out.println();\r\n } else {\r\n String gold = fl.get(OriginalAnswerAnnotation.class);\r\n if(gold == null) gold = \"\";\r\n String guess = fl.get(AnswerAnnotation.class);\r\n // System.err.println(fl.word() + \"\\t\" + fl.get(AnswerAnnotation.class) + \"\\t\" + fl.get(AnswerAnnotation.class));\r\n String pos = fl.tag();\r\n String chunk = (fl.get(ChunkAnnotation.class) == null ? \"\" : fl.get(ChunkAnnotation.class));\r\n out.println(fl.word() + '\\t' + pos + '\\t' + chunk + '\\t' +\r\n gold + '\\t' + guess);\r\n }\r\n }\r\n }",
"public static void parse(Reader src, StatementHandler handler)\n throws IOException {\n new NTriplesParser(src, handler).parse();\n }"
] |
Deletes an individual alias
@param alias
the alias to delete | [
"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 base_response delete(nitro_service client, String servicename) throws Exception {\n\t\tgslbservice deleteresource = new gslbservice();\n\t\tdeleteresource.servicename = servicename;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"public List<ServerRedirect> tableServers(int clientId) {\n List<ServerRedirect> servers = new ArrayList<>();\n\n try {\n Client client = ClientService.getInstance().getClient(clientId);\n servers = tableServers(client.getProfile().getId(), client.getActiveServerGroup());\n } catch (SQLException e) {\n e.printStackTrace();\n } catch (Exception e) {\n e.printStackTrace();\n }\n return servers;\n }",
"public synchronized void becomeTempoMaster() throws IOException {\n logger.debug(\"Trying to become master.\");\n if (!isSendingStatus()) {\n throw new IllegalStateException(\"Must be sending status updates to become the tempo master.\");\n }\n\n // Is there someone we need to ask to yield to us?\n final DeviceUpdate currentMaster = getTempoMaster();\n if (currentMaster != null) {\n // Send the yield request; we will become master when we get a successful response.\n byte[] payload = new byte[MASTER_HANDOFF_REQUEST_PAYLOAD.length];\n System.arraycopy(MASTER_HANDOFF_REQUEST_PAYLOAD, 0, payload, 0, MASTER_HANDOFF_REQUEST_PAYLOAD.length);\n payload[2] = getDeviceNumber();\n payload[8] = getDeviceNumber();\n if (logger.isDebugEnabled()) {\n logger.debug(\"Sending master yield request to player \" + currentMaster);\n }\n requestingMasterRoleFromPlayer.set(currentMaster.deviceNumber);\n assembleAndSendPacket(Util.PacketType.MASTER_HANDOFF_REQUEST, payload, currentMaster.address, BeatFinder.BEAT_PORT);\n } else if (!master.get()) {\n // There is no other master, we can just become it immediately.\n requestingMasterRoleFromPlayer.set(0);\n setMasterTempo(getTempo());\n master.set(true);\n }\n }",
"public synchronized void start() throws SocketException {\n if (!isRunning()) {\n DeviceFinder.getInstance().addLifecycleListener(lifecycleListener);\n DeviceFinder.getInstance().addDeviceAnnouncementListener(announcementListener);\n DeviceFinder.getInstance().start();\n for (DeviceAnnouncement device: DeviceFinder.getInstance().getCurrentDevices()) {\n requestPlayerDBServerPort(device);\n }\n\n new Thread(null, new Runnable() {\n @Override\n public void run() {\n while (isRunning()) {\n try {\n Thread.sleep(500);\n } catch (InterruptedException e) {\n logger.warn(\"Interrupted sleeping to close idle dbserver clients\");\n }\n closeIdleClients();\n }\n logger.info(\"Idle dbserver client closer shutting down.\");\n }\n }, \"Idle dbserver client closer\").start();\n\n running.set(true);\n deliverLifecycleAnnouncement(logger, true);\n }\n }",
"public void setScriptText(String scriptText, String language)\n {\n GVRScriptFile newScript = new GVRJavascriptScriptFile(getGVRContext(), scriptText);\n mLanguage = GVRScriptManager.LANG_JAVASCRIPT;\n setScriptFile(newScript);\n }",
"private void deleteDir(File dir)\r\n {\r\n if (dir.exists() && dir.isDirectory())\r\n {\r\n File[] files = dir.listFiles();\r\n\r\n for (int idx = 0; idx < files.length; idx++)\r\n {\r\n if (!files[idx].exists())\r\n {\r\n continue;\r\n }\r\n if (files[idx].isDirectory())\r\n {\r\n deleteDir(files[idx]);\r\n }\r\n else\r\n {\r\n files[idx].delete();\r\n }\r\n }\r\n dir.delete();\r\n }\r\n }",
"private Properties mapToProperties(Map<String, String> map) {\r\n\t\t Properties p = new Properties();\r\n\t\t for (Map.Entry<String,String> entry : map.entrySet()) {\r\n\t\t p.put(entry.getKey(), entry.getValue());\r\n\t\t }\r\n\t\t return p;\r\n\t\t }",
"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 int compare(Object objA, Object objB)\r\n {\r\n String idAStr = ((FieldDescriptorDef)_fields.get(objA)).getProperty(\"id\");\r\n String idBStr = ((FieldDescriptorDef)_fields.get(objB)).getProperty(\"id\");\r\n int idA;\r\n int idB;\r\n\r\n try\r\n {\r\n idA = Integer.parseInt(idAStr);\r\n }\r\n catch (Exception ex)\r\n {\r\n return 1;\r\n }\r\n try\r\n {\r\n idB = Integer.parseInt(idBStr);\r\n }\r\n catch (Exception ex)\r\n {\r\n return -1;\r\n }\r\n return idA < idB ? -1 : (idA > idB ? 1 : 0);\r\n }"
] |
Get the items for the key.
@param key
@return the items for the given key | [
"public Value get(Object key) {\n /* If the length is under and we are asking for the key, then just look for the key. Don't build the map. */\n if (map == null && items.length < 20) {\n for (Object item : items) {\n MapItemValue miv = (MapItemValue) item;\n if (key.equals(miv.name.toValue())) {\n return miv.value;\n }\n }\n return null;\n } else {\n if (map == null) buildIfNeededMap();\n return map.get(key);\n }\n }"
] | [
"private void readResources(Project project, HashMap<BigInteger, ProjectCalendar> calendarMap)\n {\n Project.Resources resources = project.getResources();\n if (resources != null)\n {\n for (Project.Resources.Resource resource : resources.getResource())\n {\n readResource(resource, calendarMap);\n }\n }\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 String read(int numBytes) throws IOException {\n Preconditions.checkArgument(numBytes >= 0);\n Preconditions.checkArgument(numBytes <= MAX_ALLOWABLE_BUFFER_SIZE);\n int numBytesRemaining = numBytes;\n // first read whatever we need from our buffer\n if (!isReadBufferEmpty()) {\n int length = Math.min(end - offset, numBytesRemaining);\n copyToStrBuffer(buffer, offset, length);\n offset += length;\n numBytesRemaining -= length;\n }\n\n // next read the remaining chars directly into our strBuffer\n if (numBytesRemaining > 0) {\n readAmountToStrBuffer(numBytesRemaining);\n }\n\n if (strBufferIndex > 0 && strBuffer[strBufferIndex - 1] != LF) {\n // the last byte doesn't correspond to lf\n return readLine(false);\n }\n\n int strBufferLength = strBufferIndex;\n strBufferIndex = 0;\n return new String(strBuffer, 0, strBufferLength, charset);\n }",
"private boolean replaceValues(Locale locale) {\n\n try {\n SortedProperties localization = getLocalization(locale);\n if (hasDescriptor()) {\n for (Object itemId : m_container.getItemIds()) {\n Item item = m_container.getItem(itemId);\n String key = item.getItemProperty(TableProperty.KEY).getValue().toString();\n Object value = localization.get(key);\n item.getItemProperty(TableProperty.TRANSLATION).setValue(null == value ? \"\" : value);\n }\n } else {\n m_container.removeAllItems();\n Set<Object> keyset = m_keyset.getKeySet();\n for (Object key : keyset) {\n Object itemId = m_container.addItem();\n Item item = m_container.getItem(itemId);\n item.getItemProperty(TableProperty.KEY).setValue(key);\n Object value = localization.get(key);\n item.getItemProperty(TableProperty.TRANSLATION).setValue(null == value ? \"\" : value);\n }\n if (m_container.getItemIds().isEmpty()) {\n m_container.addItem();\n }\n }\n return true;\n } catch (IOException | CmsException e) {\n // The problem should typically be a problem with locking or reading the file containing the translation.\n // This should be reported in the editor, if false is returned here.\n return false;\n }\n }",
"public <X> X invokeOnInstance(Object instance, Object... parameters) throws IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {\n final Map<Class<?>, Method> methods = this.methods;\n Method method = methods.get(instance.getClass());\n if (method == null) {\n // the same method may be written to the map twice, but that is ok\n // lookupMethod is very slow\n Method delegate = annotatedMethod.getJavaMember();\n method = SecurityActions.lookupMethod(instance.getClass(), delegate.getName(), delegate.getParameterTypes());\n SecurityActions.ensureAccessible(method);\n synchronized (this) {\n final Map<Class<?>, Method> newMethods = new HashMap<Class<?>, Method>(methods);\n newMethods.put(instance.getClass(), method);\n this.methods = WeldCollections.immutableMapView(newMethods);\n }\n }\n return cast(method.invoke(instance, parameters));\n }",
"public ParallelTaskBuilder setReplaceVarMapToSingleTarget(\n List<StrStrMap> replacementVarMapList, String uniformTargetHost) {\n\n if (Strings.isNullOrEmpty(uniformTargetHost)) {\n logger.error(\"uniform target host is empty or null. skil setting.\");\n return this;\n }\n this.replacementVarMapNodeSpecific.clear();\n this.targetHosts.clear();\n int i = 0;\n for (StrStrMap ssm : replacementVarMapList) {\n if (ssm == null)\n continue;\n String hostName = PcConstants.API_PREFIX + i;\n ssm.addPair(PcConstants.UNIFORM_TARGET_HOST_VAR, uniformTargetHost);\n replacementVarMapNodeSpecific.put(hostName, ssm);\n targetHosts.add(hostName);\n ++i;\n }\n this.requestReplacementType = RequestReplacementType.TARGET_HOST_SPECIFIC_VAR_REPLACEMENT;\n logger.info(\n \"Set requestReplacementType as {} for single target. Will disable the set target hosts.\"\n + \"Also Simulated \"\n + \"Now Already set targetHost list with size {}. \\nPLEASE NOT TO SET TARGET HOSTS AGAIN WITH THIS API.\",\n requestReplacementType.toString(), targetHosts.size());\n\n return this;\n }",
"private PlayState1 findPlayState1() {\n PlayState1 result = PLAY_STATE_1_MAP.get(packetBytes[123]);\n if (result == null) {\n return PlayState1.UNKNOWN;\n }\n return result;\n }",
"private void processWorkPattern(ProjectCalendarWeek week, Integer workPatternID, Map<Integer, Row> workPatternMap, Map<Integer, List<Row>> timeEntryMap, Map<Integer, DayType> exceptionTypeMap)\n {\n Row workPatternRow = workPatternMap.get(workPatternID);\n if (workPatternRow != null)\n {\n week.setName(workPatternRow.getString(\"NAMN\"));\n\n List<Row> timeEntryRows = timeEntryMap.get(workPatternID);\n if (timeEntryRows != null)\n {\n long lastEndTime = Long.MIN_VALUE;\n Day currentDay = Day.SUNDAY;\n ProjectCalendarHours hours = week.addCalendarHours(currentDay);\n Arrays.fill(week.getDays(), DayType.NON_WORKING);\n\n for (Row row : timeEntryRows)\n {\n Date startTime = row.getDate(\"START_TIME\");\n Date endTime = row.getDate(\"END_TIME\");\n if (startTime == null)\n {\n startTime = DateHelper.getDayStartDate(new Date(0));\n }\n\n if (endTime == null)\n {\n endTime = DateHelper.getDayEndDate(new Date(0));\n }\n\n if (startTime.getTime() > endTime.getTime())\n {\n endTime = DateHelper.addDays(endTime, 1);\n }\n\n if (startTime.getTime() < lastEndTime)\n {\n currentDay = currentDay.getNextDay();\n hours = week.addCalendarHours(currentDay);\n }\n\n DayType type = exceptionTypeMap.get(row.getInteger(\"EXCEPTIOP\"));\n if (type == DayType.WORKING)\n {\n hours.addRange(new DateRange(startTime, endTime));\n week.setWorkingDay(currentDay, DayType.WORKING);\n }\n\n lastEndTime = endTime.getTime();\n }\n }\n }\n }",
"@Override\n public void stop()\n {\n synchronized (killHook)\n {\n jqmlogger.info(\"JQM engine \" + this.node.getName() + \" has received a stop order\");\n\n // Kill hook should be removed\n try\n {\n if (!Runtime.getRuntime().removeShutdownHook(killHook))\n {\n jqmlogger.error(\"The engine could not unregister its shutdown hook\");\n }\n }\n catch (IllegalStateException e)\n {\n // This happens if the stop sequence is initiated by the shutdown hook itself.\n jqmlogger.info(\"Stop order is due to an admin operation (KILL/INT)\");\n }\n }\n\n // Stop pollers\n int pollerCount = pollers.size();\n for (QueuePoller p : pollers.values())\n {\n p.stop();\n }\n\n // Scheduler\n this.scheduler.stop();\n\n // Jetty is closed automatically when all pollers are down\n\n // Wait for the end of the world\n if (pollerCount > 0)\n {\n try\n {\n this.ended.acquire();\n }\n catch (InterruptedException e)\n {\n jqmlogger.error(\"interrupted\", e);\n }\n }\n\n // Send a KILL signal to remaining job instances, and wait some more.\n if (this.getCurrentlyRunningJobCount() > 0)\n {\n this.runningJobInstanceManager.killAll();\n try\n {\n Thread.sleep(10000);\n }\n catch (InterruptedException e)\n {\n jqmlogger.error(\"interrupted\", e);\n }\n }\n\n jqmlogger.debug(\"Stop order was correctly handled. Engine for node \" + this.node.getName() + \" has stopped.\");\n }"
] |
Read an element which contains only a single list attribute of a given
type, returning it as an array.
@param reader the reader
@param attributeName the attribute name, usually "value"
@param type the value type class
@param <T> the value type
@return the value list as an array
@throws javax.xml.stream.XMLStreamException if an error occurs or if the
element does not contain the specified attribute, contains other
attributes, or contains child elements. | [
"@SuppressWarnings({ \"unchecked\" })\n public static <T> T[] readArrayAttributeElement(final XMLExtendedStreamReader reader, final String attributeName,\n final Class<T> type) throws XMLStreamException {\n final List<T> list = readListAttributeElement(reader, attributeName, type);\n return list.toArray((T[]) Array.newInstance(type, list.size()));\n }"
] | [
"private void addArrayMethods(List<MethodNode> methods, ClassNode receiver, String name, ClassNode[] args) {\n if (args.length!=1) return;\n if (!receiver.isArray()) return;\n if (!isIntCategory(getUnwrapper(args[0]))) return;\n if (\"getAt\".equals(name)) {\n MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC, receiver.getComponentType(), new Parameter[]{new Parameter(args[0],\"arg\")}, null, null);\n node.setDeclaringClass(receiver.redirect());\n methods.add(node);\n } else if (\"setAt\".equals(name)) {\n MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC, VOID_TYPE, new Parameter[]{new Parameter(args[0],\"arg\")}, null, null);\n node.setDeclaringClass(receiver.redirect());\n methods.add(node);\n }\n }",
"private void checkReadonlyAccessForNativePKs(FieldDescriptorDef fieldDef, String checkLevel)\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n String access = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_ACCESS);\r\n String autoInc = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_AUTOINCREMENT);\r\n\r\n if (\"database\".equals(autoInc) && !\"readonly\".equals(access))\r\n {\r\n LogHelper.warn(true,\r\n FieldDescriptorConstraints.class,\r\n \"checkAccess\",\r\n \"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" is set to database auto-increment. Therefore the field's access is set to 'readonly'.\");\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_ACCESS, \"readonly\");\r\n }\r\n }",
"public void edit(Note note) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT);\r\n\r\n parameters.put(\"note_id\", note.getId());\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 }",
"public static base_response delete(nitro_service client, String Dnssuffix) throws Exception {\n\t\tdnssuffix deleteresource = new dnssuffix();\n\t\tdeleteresource.Dnssuffix = Dnssuffix;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"private void addClasses(XMLStreamWriter writer, File jarFile, boolean mapClassMethods) throws IOException, ClassNotFoundException, XMLStreamException, IntrospectionException\n {\n ClassLoader currentThreadClassLoader = Thread.currentThread().getContextClassLoader();\n\n URLClassLoader loader = new URLClassLoader(new URL[]\n {\n jarFile.toURI().toURL()\n }, currentThreadClassLoader);\n\n JarFile jar = new JarFile(jarFile);\n Enumeration<JarEntry> enumeration = jar.entries();\n while (enumeration.hasMoreElements())\n {\n JarEntry jarEntry = enumeration.nextElement();\n if (!jarEntry.isDirectory() && jarEntry.getName().endsWith(\".class\"))\n {\n addClass(loader, jarEntry, writer, mapClassMethods);\n }\n }\n jar.close();\n }",
"public static <T> T load(String resourcePath, BeanSpec spec) {\n return load(resourcePath, spec, false);\n }",
"@SuppressWarnings(\"unchecked\")\n public final FluentModelImplT withTag(String key, String value) {\n if (this.inner().getTags() == null) {\n this.inner().withTags(new HashMap<String, String>());\n }\n this.inner().getTags().put(key, value);\n return (FluentModelImplT) this;\n }",
"private void setProperties(Properties properties) {\n Props props = new Props(properties);\n if(props.containsKey(BOOTSTRAP_URLS_PROPERTY)) {\n setBootstrapURLs(props.getList(BOOTSTRAP_URLS_PROPERTY));\n }\n\n if(props.containsKey(FAT_CLIENTS_CONFIG_SOURCE)) {\n setFatClientConfigSource(StoreClientConfigSource.get(props.getString(FAT_CLIENTS_CONFIG_SOURCE)));\n }\n\n if(props.containsKey(FAT_CLIENTS_CONFIG_FILE_PATH_PROPERTY)) {\n setFatClientConfigPath(props.getString(FAT_CLIENTS_CONFIG_FILE_PATH_PROPERTY));\n }\n\n if(props.containsKey(METADATA_CHECK_INTERVAL_IN_MS)) {\n setMetadataCheckIntervalInMs(props.getInt(METADATA_CHECK_INTERVAL_IN_MS));\n }\n\n if(props.containsKey(NETTY_SERVER_PORT)) {\n setServerPort(props.getInt(NETTY_SERVER_PORT));\n }\n\n if(props.containsKey(NETTY_SERVER_BACKLOG)) {\n setNettyServerBacklog(props.getInt(NETTY_SERVER_BACKLOG));\n }\n\n if(props.containsKey(COORDINATOR_CORE_THREADS)) {\n setCoordinatorCoreThreads(props.getInt(COORDINATOR_CORE_THREADS));\n }\n\n if(props.containsKey(COORDINATOR_MAX_THREADS)) {\n setCoordinatorMaxThreads(props.getInt(COORDINATOR_MAX_THREADS));\n }\n\n if(props.containsKey(COORDINATOR_QUEUED_REQUESTS)) {\n setCoordinatorQueuedRequestsSize(props.getInt(COORDINATOR_QUEUED_REQUESTS));\n }\n\n if(props.containsKey(HTTP_MESSAGE_DECODER_MAX_INITIAL_LINE_LENGTH)) {\n setHttpMessageDecoderMaxInitialLength(props.getInt(HTTP_MESSAGE_DECODER_MAX_INITIAL_LINE_LENGTH));\n }\n\n if(props.containsKey(HTTP_MESSAGE_DECODER_MAX_HEADER_SIZE)) {\n setHttpMessageDecoderMaxHeaderSize(props.getInt(HTTP_MESSAGE_DECODER_MAX_HEADER_SIZE));\n }\n\n if(props.containsKey(HTTP_MESSAGE_DECODER_MAX_CHUNK_SIZE)) {\n setHttpMessageDecoderMaxChunkSize(props.getInt(HTTP_MESSAGE_DECODER_MAX_CHUNK_SIZE));\n }\n\n if(props.containsKey(ADMIN_ENABLE)) {\n setAdminServiceEnabled(props.getBoolean(ADMIN_ENABLE));\n }\n\n if(props.containsKey(ADMIN_PORT)) {\n setAdminPort(props.getInt(ADMIN_PORT));\n }\n\n }",
"public int addKey(String key) {\n JdkUtils.requireNonNull(key);\n int nextIndex = keys.size();\n final Integer mapIndex = JdkUtils.putIfAbsent(keys, key, nextIndex);\n return mapIndex == null ? nextIndex : mapIndex;\n }"
] |
Returns the total number of times the app has been launched
@return Total number of app launches in int | [
"@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 }"
] | [
"public static base_response apply(nitro_service client) throws Exception {\n\t\tnspbr6 applyresource = new nspbr6();\n\t\treturn applyresource.perform_operation(client,\"apply\");\n\t}",
"public void subscriptionRequestReceived(SubscriptionRequest sr) throws SubscriptionException {\n\n LOG.info(\"Subscriber -> (Hub), new subscription request received.\", sr.getCallback());\n\n try {\n\n verifySubscriberRequestedSubscription(sr);\n\n if (\"subscribe\".equals(sr.getMode())) {\n LOG.info(\"Adding callback {} to the topic {}\", sr.getCallback(), sr.getTopic());\n addCallbackToTopic(sr.getCallback(), sr.getTopic());\n } else if (\"unsubscribe\".equals(sr.getMode())) {\n LOG.info(\"Removing callback {} from the topic {}\", sr.getCallback(), sr.getTopic());\n removeCallbackToTopic(sr.getCallback(), sr.getTopic());\n }\n\n } catch (Exception e) {\n throw new SubscriptionException(e);\n }\n\n }",
"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 }",
"public InetSocketAddress getMulticastSocketAddress() {\n if (multicastAddress == null) {\n throw MESSAGES.noMulticastBinding(name);\n }\n return new InetSocketAddress(multicastAddress, multicastPort);\n }",
"public static appfwwsdl get(nitro_service service, String name) throws Exception{\n\t\tappfwwsdl obj = new appfwwsdl();\n\t\tobj.set_name(name);\n\t\tappfwwsdl response = (appfwwsdl) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private void unregisterAllServlets() {\n\n for (String endpoint : registeredServlets) {\n registeredServlets.remove(endpoint);\n web.unregister(endpoint);\n LOG.info(\"endpoint {} unregistered\", endpoint);\n }\n\n }",
"public static base_responses add(nitro_service client, dnsaaaarec resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdnsaaaarec addresources[] = new dnsaaaarec[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dnsaaaarec();\n\t\t\t\taddresources[i].hostname = resources[i].hostname;\n\t\t\t\taddresources[i].ipv6address = resources[i].ipv6address;\n\t\t\t\taddresources[i].ttl = resources[i].ttl;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"public File getBootFile() {\n if (bootFile == null) {\n synchronized (this) {\n if (bootFile == null) {\n if (bootFileReset) {\n //Reset the done bootup and the sequence, so that the old file we are reloading from\n // overwrites the main file on successful boot, and history is reset as when booting new\n doneBootup.set(false);\n sequence.set(0);\n }\n // If it's a reload with no new boot file name and we're persisting our config, we boot from mainFile,\n // as that's where we persist\n if (bootFileReset && !interactionPolicy.isReadOnly() && newReloadBootFileName == null) {\n // we boot from mainFile\n bootFile = mainFile;\n } else {\n // It's either first boot, or a reload where we're not persisting our config or with a new boot file.\n // So we need to figure out which file we're meant to boot from\n\n String bootFileName = this.bootFileName;\n if (newReloadBootFileName != null) {\n //A non-null new boot file on reload takes precedence over the reloadUsingLast functionality\n //A new boot file was specified. Use that and reset the new name to null\n bootFileName = newReloadBootFileName;\n newReloadBootFileName = null;\n } else if (interactionPolicy.isReadOnly() && reloadUsingLast) {\n //If we were reloaded, and it is not a persistent configuration we want to use the last from the history\n bootFileName = LAST;\n }\n boolean usingRawFile = bootFileName.equals(rawFileName);\n if (usingRawFile) {\n bootFile = mainFile;\n } else {\n bootFile = determineBootFile(configurationDir, bootFileName);\n try {\n bootFile = bootFile.getCanonicalFile();\n } catch (IOException ioe) {\n throw ControllerLogger.ROOT_LOGGER.canonicalBootFileNotFound(ioe, bootFile);\n }\n }\n\n\n if (!bootFile.exists()) {\n if (!usingRawFile) { // TODO there's no reason usingRawFile should be an exception,\n // but the test infrastructure stuff is built around an assumption\n // that ConfigurationFile doesn't fail if test files are not\n // in the normal spot\n if (bootFileReset || interactionPolicy.isRequireExisting()) {\n throw ControllerLogger.ROOT_LOGGER.fileNotFound(bootFile.getAbsolutePath());\n }\n }\n // Create it for the NEW and DISCARD cases\n if (!bootFileReset && !interactionPolicy.isRequireExisting()) {\n createBootFile(bootFile);\n }\n } else if (!bootFileReset) {\n if (interactionPolicy.isRejectExisting() && bootFile.length() > 0) {\n throw ControllerLogger.ROOT_LOGGER.rejectEmptyConfig(bootFile.getAbsolutePath());\n } else if (interactionPolicy.isRemoveExisting() && bootFile.length() > 0) {\n if (!bootFile.delete()) {\n throw ControllerLogger.ROOT_LOGGER.cannotDelete(bootFile.getAbsoluteFile());\n }\n createBootFile(bootFile);\n }\n } // else after first boot we want the file to exist\n }\n }\n }\n }\n return bootFile;\n }",
"public void updateInfo(Info info) {\n BoxAPIConnection api = this.getAPI();\n URL url = COLLABORATION_URL_TEMPLATE.build(api.getBaseURL(), this.getID());\n\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"PUT\");\n request.setBody(info.getPendingChanges());\n BoxAPIResponse boxAPIResponse = request.send();\n\n if (boxAPIResponse instanceof BoxJSONResponse) {\n BoxJSONResponse response = (BoxJSONResponse) boxAPIResponse;\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n info.update(jsonObject);\n }\n }"
] |
Given a rebalance-task info, convert it into the protobuf equivalent
@param stealInfo Rebalance task info
@return Protobuf equivalent of the same | [
"public static RebalanceTaskInfoMap encodeRebalanceTaskInfoMap(RebalanceTaskInfo stealInfo) {\n return RebalanceTaskInfoMap.newBuilder()\n .setStealerId(stealInfo.getStealerId())\n .setDonorId(stealInfo.getDonorId())\n .addAllPerStorePartitionIds(ProtoUtils.encodeStoreToPartitionsTuple(stealInfo.getStoreToPartitionIds()))\n .setInitialCluster(new ClusterMapper().writeCluster(stealInfo.getInitialCluster()))\n .build();\n }"
] | [
"public static List<Number> findIndexValues(Object self, Number startIndex, Closure closure) {\n List<Number> result = new ArrayList<Number>();\n long count = 0;\n long startCount = startIndex.longValue();\n BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);\n for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); count++) {\n Object value = iter.next();\n if (count < startCount) {\n continue;\n }\n if (bcw.call(value)) {\n result.add(count);\n }\n }\n return result;\n }",
"private void writeCalendarHours(ProjectCalendar parentCalendar, ProjectCalendarHours record) throws IOException\n {\n m_buffer.setLength(0);\n\n int recordNumber;\n\n if (!parentCalendar.isDerived())\n {\n recordNumber = MPXConstants.BASE_CALENDAR_HOURS_RECORD_NUMBER;\n }\n else\n {\n recordNumber = MPXConstants.RESOURCE_CALENDAR_HOURS_RECORD_NUMBER;\n }\n\n DateRange range1 = record.getRange(0);\n if (range1 == null)\n {\n range1 = DateRange.EMPTY_RANGE;\n }\n\n DateRange range2 = record.getRange(1);\n if (range2 == null)\n {\n range2 = DateRange.EMPTY_RANGE;\n }\n\n DateRange range3 = record.getRange(2);\n if (range3 == null)\n {\n range3 = DateRange.EMPTY_RANGE;\n }\n\n m_buffer.append(recordNumber);\n m_buffer.append(m_delimiter);\n m_buffer.append(format(record.getDay()));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatTime(range1.getStart())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatTime(range1.getEnd())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatTime(range2.getStart())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatTime(range2.getEnd())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatTime(range3.getStart())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatTime(range3.getEnd())));\n stripTrailingDelimiters(m_buffer);\n m_buffer.append(MPXConstants.EOL);\n\n m_writer.write(m_buffer.toString());\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 }",
"public static String changeFirstLetterToLowerCase(String word) {\n char[] letras = word.toCharArray();\n char a = letras[0];\n letras[0] = Character.toLowerCase(a);\n return new String(letras);\n }",
"public Object getObjectByIdentity(Identity id)\r\n throws PersistenceBrokerException\r\n {\r\n checkOpen();\r\n ObjectEnvelope envelope = objectEnvelopeTable.getByIdentity(id);\r\n if (envelope != null)\r\n {\r\n return (envelope.needsDelete() ? null : envelope.getObject());\r\n }\r\n else\r\n {\r\n return getBroker().getObjectByIdentity(id);\r\n }\r\n }",
"protected I_CmsSearchConfigurationSortOption parseSortOption(JSONObject json) {\n\n try {\n String solrValue = json.getString(JSON_KEY_SORTOPTION_SOLRVALUE);\n String paramValue = parseOptionalStringValue(json, JSON_KEY_SORTOPTION_PARAMVALUE);\n paramValue = (paramValue == null) ? solrValue : paramValue;\n String label = parseOptionalStringValue(json, JSON_KEY_SORTOPTION_LABEL);\n label = (label == null) ? paramValue : label;\n return new CmsSearchConfigurationSortOption(label, paramValue, solrValue);\n } catch (JSONException e) {\n LOG.error(\n Messages.get().getBundle().key(Messages.ERR_SORT_OPTION_NOT_PARSABLE_1, JSON_KEY_SORTOPTION_SOLRVALUE),\n e);\n return null;\n }\n }",
"public void parseVersion( String version )\n {\n DefaultVersioning artifactVersion = new DefaultVersioning( version );\n\n getLog().debug( \"Parsed Version\" );\n getLog().debug( \" major: \" + artifactVersion.getMajor() );\n getLog().debug( \" minor: \" + artifactVersion.getMinor() );\n getLog().debug( \" incremental: \" + artifactVersion.getPatch() );\n getLog().debug( \" buildnumber: \" + artifactVersion.getBuildNumber() );\n getLog().debug( \" qualifier: \" + artifactVersion.getQualifier() );\n\n defineVersionProperty( \"majorVersion\", artifactVersion.getMajor() );\n defineVersionProperty( \"minorVersion\", artifactVersion.getMinor() );\n defineVersionProperty( \"incrementalVersion\", artifactVersion.getPatch() );\n defineVersionProperty( \"buildNumber\", artifactVersion.getBuildNumber() );\n\n defineVersionProperty( \"nextMajorVersion\", artifactVersion.getMajor() + 1 );\n defineVersionProperty( \"nextMinorVersion\", artifactVersion.getMinor() + 1 );\n defineVersionProperty( \"nextIncrementalVersion\", artifactVersion.getPatch() + 1 );\n defineVersionProperty( \"nextBuildNumber\", artifactVersion.getBuildNumber() + 1 );\n\n defineFormattedVersionProperty( \"majorVersion\", String.format( formatMajor, artifactVersion.getMajor() ) );\n defineFormattedVersionProperty( \"minorVersion\", String.format( formatMinor, artifactVersion.getMinor() ) );\n defineFormattedVersionProperty( \"incrementalVersion\", String.format( formatIncremental, artifactVersion.getPatch() ) );\n defineFormattedVersionProperty( \"buildNumber\", String.format( formatBuildNumber, artifactVersion.getBuildNumber() ));\n\n defineFormattedVersionProperty( \"nextMajorVersion\", String.format( formatMajor, artifactVersion.getMajor() + 1 ));\n defineFormattedVersionProperty( \"nextMinorVersion\", String.format( formatMinor, artifactVersion.getMinor() + 1 ));\n defineFormattedVersionProperty( \"nextIncrementalVersion\", String.format( formatIncremental, artifactVersion.getPatch() + 1 ));\n defineFormattedVersionProperty( \"nextBuildNumber\", String.format( formatBuildNumber, artifactVersion.getBuildNumber() + 1 ));\n \n String osgi = artifactVersion.getAsOSGiVersion();\n\n String qualifier = artifactVersion.getQualifier();\n String qualifierQuestion = \"\";\n if ( qualifier == null )\n {\n qualifier = \"\";\n } else {\n qualifierQuestion = qualifierPrefix;\n }\n\n defineVersionProperty( \"qualifier\", qualifier );\n defineVersionProperty( \"qualifier?\", qualifierQuestion + qualifier );\n\n defineVersionProperty( \"osgiVersion\", osgi );\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 }",
"@Override\n public final double getDouble(final String key) {\n Double result = optDouble(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }"
] |
Generate an ordered set of column definitions from an ordered set of column names.
@param columns column definitions
@param order column names
@return ordered set of column definitions | [
"private ColumnDefinition[] columnDefinitions(ColumnDefinition[] columns, String[] order)\n {\n Map<String, ColumnDefinition> map = makeColumnMap(columns);\n ColumnDefinition[] result = new ColumnDefinition[order.length];\n for (int index = 0; index < order.length; index++)\n {\n result[index] = map.get(order[index]);\n }\n return result;\n }"
] | [
"public void printInferredRelations(ClassDoc c) {\n\t// check if the source is excluded from inference\n\tif (hidden(c))\n\t return;\n\n\tOptions opt = optionProvider.getOptionsFor(c);\n\n\tfor (FieldDoc field : c.fields(false)) {\n\t if(hidden(field))\n\t\tcontinue;\n\t // skip statics\n\t if(field.isStatic())\n\t\tcontinue;\n\t // skip primitives\n\t FieldRelationInfo fri = getFieldRelationInfo(field);\n\t if (fri == null)\n\t\tcontinue;\n\t // check if the destination is excluded from inference\n\t if (hidden(fri.cd))\n\t\tcontinue;\n\n\t // if source and dest are not already linked, add a dependency\n\t RelationPattern rp = getClassInfo(c, true).getRelation(fri.cd.toString());\n\t if (rp == null) {\n\t\tString destAdornment = fri.multiple ? \"*\" : \"\";\n\t\trelation(opt, opt.inferRelationshipType, c, fri.cd, \"\", \"\", destAdornment);\n }\n\t}\n }",
"protected long buildNextSequence(PersistenceBroker broker, ClassDescriptor cld, String sequenceName)\r\n throws LookupException, SQLException, PlatformException\r\n {\r\n CallableStatement cs = null;\r\n try\r\n {\r\n Connection con = broker.serviceConnectionManager().getConnection();\r\n cs = getPlatform().prepareNextValProcedureStatement(con, PROCEDURE_NAME, sequenceName);\r\n cs.executeUpdate();\r\n return cs.getLong(1);\r\n }\r\n finally\r\n {\r\n try\r\n {\r\n if (cs != null)\r\n cs.close();\r\n }\r\n catch (SQLException ignore)\r\n {\r\n // ignore it\r\n }\r\n }\r\n }",
"public static final TimeUnit getTimeUnit(int value)\n {\n TimeUnit result = null;\n\n switch (value)\n {\n case 1:\n {\n // Appears to mean \"use the document format\"\n result = TimeUnit.ELAPSED_DAYS;\n break;\n }\n\n case 2:\n {\n result = TimeUnit.HOURS;\n break;\n }\n\n case 4:\n {\n result = TimeUnit.DAYS;\n break;\n }\n\n case 6:\n {\n result = TimeUnit.WEEKS;\n break;\n }\n\n case 8:\n case 10:\n {\n result = TimeUnit.MONTHS;\n break;\n }\n\n case 12:\n {\n result = TimeUnit.YEARS;\n break;\n }\n\n default:\n {\n break;\n }\n }\n\n return result;\n }",
"private void readHours(ProjectCalendar calendar, Day day, Integer hours)\n {\n int value = hours.intValue();\n int startHour = 0;\n ProjectCalendarHours calendarHours = null;\n\n Calendar cal = DateHelper.popCalendar();\n cal.set(Calendar.HOUR_OF_DAY, 0);\n cal.set(Calendar.MINUTE, 0);\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MILLISECOND, 0);\n\n calendar.setWorkingDay(day, false);\n\n while (value != 0)\n {\n // Move forward until we find a working hour\n while (startHour < 24 && (value & 0x1) == 0)\n {\n value = value >> 1;\n ++startHour;\n }\n\n // No more working hours, bail out\n if (startHour >= 24)\n {\n break;\n }\n\n // Move forward until we find the end of the working hours\n int endHour = startHour;\n while (endHour < 24 && (value & 0x1) != 0)\n {\n value = value >> 1;\n ++endHour;\n }\n\n cal.set(Calendar.HOUR_OF_DAY, startHour);\n Date startDate = cal.getTime();\n cal.set(Calendar.HOUR_OF_DAY, endHour);\n Date endDate = cal.getTime();\n\n if (calendarHours == null)\n {\n calendarHours = calendar.addCalendarHours(day);\n calendar.setWorkingDay(day, true);\n }\n calendarHours.addRange(new DateRange(startDate, endDate));\n startHour = endHour;\n }\n \n DateHelper.pushCalendar(cal);\n }",
"public void updateLockingValues(Object obj) throws PersistenceBrokerException\r\n {\r\n FieldDescriptor[] fields = getLockingFields();\r\n for (int i = 0; i < fields.length; i++)\r\n {\r\n FieldDescriptor fmd = fields[i];\r\n if (fmd.isUpdateLock())\r\n {\r\n PersistentField f = fmd.getPersistentField();\r\n Object cv = f.get(obj);\r\n // int\r\n if ((f.getType() == int.class) || (f.getType() == Integer.class))\r\n {\r\n int newCv = 0;\r\n if (cv != null)\r\n {\r\n newCv = ((Number) cv).intValue();\r\n }\r\n newCv++;\r\n f.set(obj, new Integer(newCv));\r\n }\r\n // long\r\n else if ((f.getType() == long.class) || (f.getType() == Long.class))\r\n {\r\n long newCv = 0;\r\n if (cv != null)\r\n {\r\n newCv = ((Number) cv).longValue();\r\n }\r\n newCv++;\r\n f.set(obj, new Long(newCv));\r\n }\r\n // Timestamp\r\n else if (f.getType() == Timestamp.class)\r\n {\r\n long newCv = System.currentTimeMillis();\r\n f.set(obj, new Timestamp(newCv));\r\n }\r\n }\r\n }\r\n }",
"public void appendImmediate(Object object, String indentation) {\n\t\tfor (int i = segments.size() - 1; i >= 0; i--) {\n\t\t\tString segment = segments.get(i);\n\t\t\tfor (int j = 0; j < segment.length(); j++) {\n\t\t\t\tif (!WhitespaceMatcher.isWhitespace(segment.charAt(j))) {\n\t\t\t\t\tappend(object, indentation, i + 1);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tappend(object, indentation, 0);\n\t}",
"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 String[] parseMFString(String mfString) {\n Vector<String> strings = new Vector<String>();\n\n StringReader sr = new StringReader(mfString);\n StreamTokenizer st = new StreamTokenizer(sr);\n st.quoteChar('\"');\n st.quoteChar('\\'');\n String[] mfStrings = null;\n\n int tokenType;\n try {\n while ((tokenType = st.nextToken()) != StreamTokenizer.TT_EOF) {\n\n strings.add(st.sval);\n\n }\n } catch (IOException e) {\n\n Log.d(TAG, \"String parsing Error: \" + e);\n\n e.printStackTrace();\n }\n mfStrings = new String[strings.size()];\n for (int i = 0; i < strings.size(); i++) {\n mfStrings[i] = strings.get(i);\n }\n return mfStrings;\n }",
"public static Object newInstance(String className, Class type, Object arg) throws InstantiationException,\r\n IllegalAccessException,\r\n IllegalArgumentException,\r\n InvocationTargetException,\r\n NoSuchMethodException,\r\n SecurityException,\r\n ClassNotFoundException\r\n {\r\n return newInstance(className, new Class[]{type}, new Object[]{arg});\r\n }"
] |
Notifies that multiple content items are inserted.
@param positionStart the position.
@param itemCount the item count. | [
"public final void notifyContentItemRangeInserted(int positionStart, int itemCount) {\n int newHeaderItemCount = getHeaderItemCount();\n int newContentItemCount = getContentItemCount();\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > newContentItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for content items [0 - \"\n + (newContentItemCount - 1) + \"].\");\n }\n notifyItemRangeInserted(positionStart + newHeaderItemCount, itemCount);\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 }",
"public Date[] getDates()\n {\n int frequency = NumberHelper.getInt(m_frequency);\n if (frequency < 1)\n {\n frequency = 1;\n }\n\n Calendar calendar = DateHelper.popCalendar(m_startDate);\n List<Date> dates = new ArrayList<Date>();\n\n switch (m_recurrenceType)\n {\n case DAILY:\n {\n getDailyDates(calendar, frequency, dates);\n break;\n }\n\n case WEEKLY:\n {\n getWeeklyDates(calendar, frequency, dates);\n break;\n }\n\n case MONTHLY:\n {\n getMonthlyDates(calendar, frequency, dates);\n break;\n }\n\n case YEARLY:\n {\n getYearlyDates(calendar, dates);\n break;\n }\n }\n\n DateHelper.pushCalendar(calendar);\n \n return dates.toArray(new Date[dates.size()]);\n }",
"public JSONObject toJSON() {\n try {\n return new JSONObject(properties).putOpt(\"name\", getName());\n } catch (JSONException e) {\n e.printStackTrace();\n Log.e(TAG, e, \"toJSON()\");\n throw new RuntimeAssertion(\"NodeEntry.toJSON() failed for '%s'\", this);\n }\n }",
"public int compare(Object objA, Object objB)\r\n {\r\n String idAStr = _table.getColumn((String)objA).getProperty(\"id\");\r\n String idBStr = _table.getColumn((String)objB).getProperty(\"id\");\r\n int idA;\r\n int idB;\r\n\r\n try {\r\n idA = Integer.parseInt(idAStr);\r\n }\r\n catch (Exception ex) {\r\n return 1;\r\n }\r\n try {\r\n idB = Integer.parseInt(idBStr);\r\n }\r\n catch (Exception ex) {\r\n return -1;\r\n }\r\n return idA < idB ? -1 : (idA > idB ? 1 : 0);\r\n }",
"public static ServiceController<InstallationManager> installService(ServiceTarget serviceTarget) {\n final InstallationManagerService service = new InstallationManagerService();\n return serviceTarget.addService(InstallationManagerService.NAME, service)\n .addDependency(JBOSS_PRODUCT_CONFIG_SERVICE, ProductConfig.class, service.productConfig)\n .setInitialMode(ServiceController.Mode.ACTIVE)\n .install();\n }",
"@Override\n public void perform(GraphRewrite event, EvaluationContext context)\n {\n checkVariableName(event, context);\n WindupVertexFrame payload = resolveVariable(event, getVariableName());\n if (payload instanceof FileReferenceModel)\n {\n FileModel file = ((FileReferenceModel) payload).getFile();\n perform(event, context, (XmlFileModel) file);\n }\n else\n {\n super.perform(event, context);\n }\n\n }",
"public void edit(Note note) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT);\r\n\r\n parameters.put(\"note_id\", note.getId());\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 }",
"private void readAssignments(Project plannerProject)\n {\n Allocations allocations = plannerProject.getAllocations();\n List<Allocation> allocationList = allocations.getAllocation();\n Set<Task> tasksWithAssignments = new HashSet<Task>();\n\n for (Allocation allocation : allocationList)\n {\n Integer taskID = getInteger(allocation.getTaskId());\n Integer resourceID = getInteger(allocation.getResourceId());\n Integer units = getInteger(allocation.getUnits());\n\n Task task = m_projectFile.getTaskByUniqueID(taskID);\n Resource resource = m_projectFile.getResourceByUniqueID(resourceID);\n\n if (task != null && resource != null)\n {\n Duration work = task.getWork();\n int percentComplete = NumberHelper.getInt(task.getPercentageComplete());\n\n ResourceAssignment assignment = task.addResourceAssignment(resource);\n assignment.setUnits(units);\n assignment.setWork(work);\n\n if (percentComplete != 0)\n {\n Duration actualWork = Duration.getInstance((work.getDuration() * percentComplete) / 100, work.getUnits());\n assignment.setActualWork(actualWork);\n assignment.setRemainingWork(Duration.getInstance(work.getDuration() - actualWork.getDuration(), work.getUnits()));\n }\n else\n {\n assignment.setRemainingWork(work);\n }\n\n assignment.setStart(task.getStart());\n assignment.setFinish(task.getFinish());\n\n tasksWithAssignments.add(task);\n\n m_eventManager.fireAssignmentReadEvent(assignment);\n }\n }\n\n //\n // Adjust work per assignment for tasks with multiple assignments\n //\n for (Task task : tasksWithAssignments)\n {\n List<ResourceAssignment> assignments = task.getResourceAssignments();\n if (assignments.size() > 1)\n {\n double maxUnits = 0;\n for (ResourceAssignment assignment : assignments)\n {\n maxUnits += assignment.getUnits().doubleValue();\n }\n\n for (ResourceAssignment assignment : assignments)\n {\n Duration work = assignment.getWork();\n double factor = assignment.getUnits().doubleValue() / maxUnits;\n\n work = Duration.getInstance(work.getDuration() * factor, work.getUnits());\n assignment.setWork(work);\n Duration actualWork = assignment.getActualWork();\n if (actualWork != null)\n {\n actualWork = Duration.getInstance(actualWork.getDuration() * factor, actualWork.getUnits());\n assignment.setActualWork(actualWork);\n }\n\n Duration remainingWork = assignment.getRemainingWork();\n if (remainingWork != null)\n {\n remainingWork = Duration.getInstance(remainingWork.getDuration() * factor, remainingWork.getUnits());\n assignment.setRemainingWork(remainingWork);\n }\n }\n }\n }\n }",
"public static double elementMax( DMatrixSparseCSC A ) {\n if( A.nz_length == 0)\n return 0;\n\n // if every element is assigned a value then the first element can be a max.\n // Otherwise zero needs to be considered\n double max = A.isFull() ? A.nz_values[0] : 0;\n for(int i = 0; i < A.nz_length; i++ ) {\n double val = A.nz_values[i];\n if( val > max ) {\n max = val;\n }\n }\n\n return max;\n }"
] |
Provides a type-specific Meta class for the given TinyType.
@param <T> the TinyType class type
@param candidate the TinyType class to obtain a Meta for
@return a Meta implementation suitable for the candidate
@throws IllegalArgumentException for null or a non-TinyType | [
"public static <T> MetaTinyType<T> metaFor(Class<?> candidate) {\n for (MetaTinyType meta : metas) {\n if (meta.isMetaOf(candidate)) {\n return meta;\n }\n }\n throw new IllegalArgumentException(String.format(\"not a tinytype: %s\", candidate == null ? \"null\" : candidate.getCanonicalName()));\n }"
] | [
"public static String buildDynamicCapabilityName(String baseName, String dynamicNameElement) {\n return buildDynamicCapabilityName(baseName, new String[]{dynamicNameElement});\n }",
"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 int refresh(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException {\n\t\tif (mappedRefresh == null) {\n\t\t\tmappedRefresh = MappedRefresh.build(dao, tableInfo);\n\t\t}\n\t\treturn mappedRefresh.executeRefresh(databaseConnection, data, objectCache);\n\t}",
"public static Comparator getComparator()\r\n {\r\n return new Comparator()\r\n {\r\n public int compare(Object o1, Object o2)\r\n {\r\n FieldDescriptor fmd1 = (FieldDescriptor) o1;\r\n FieldDescriptor fmd2 = (FieldDescriptor) o2;\r\n if (fmd1.getColNo() < fmd2.getColNo())\r\n {\r\n return -1;\r\n }\r\n else if (fmd1.getColNo() > fmd2.getColNo())\r\n {\r\n return 1;\r\n }\r\n else\r\n {\r\n return 0;\r\n }\r\n }\r\n };\r\n }",
"public static<T> SessionVar<T> vendSessionVar(Callable<T> defFunc) {\n\treturn (new VarsJBridge()).vendSessionVar(defFunc, new Exception());\n }",
"public static void deleteRecursively(final Path path) throws IOException {\n DeploymentRepositoryLogger.ROOT_LOGGER.debugf(\"Deleting %s recursively\", path);\n if (Files.exists(path)) {\n Files.walkFileTree(path, new FileVisitor<Path>() {\n @Override\n public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n Files.delete(file);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {\n DeploymentRepositoryLogger.ROOT_LOGGER.cannotDeleteFile(exc, path);\n throw exc;\n }\n\n @Override\n public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {\n Files.delete(dir);\n return FileVisitResult.CONTINUE;\n }\n });\n }\n }",
"public void add(String photoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ADD);\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"public void updateShownOptions(boolean showModeSwitch, boolean showAddKeyOption) {\n\n if (showModeSwitch != m_showModeSwitch) {\n m_upperLeftComponent.removeAllComponents();\n m_upperLeftComponent.addComponent(m_languageSwitch);\n if (showModeSwitch) {\n m_upperLeftComponent.addComponent(m_modeSwitch);\n }\n m_upperLeftComponent.addComponent(m_filePathLabel);\n m_showModeSwitch = showModeSwitch;\n }\n if (showAddKeyOption != m_showAddKeyOption) {\n if (showAddKeyOption) {\n m_optionsComponent.addComponent(m_lowerLeftComponent, 0, 1);\n m_optionsComponent.addComponent(m_lowerRightComponent, 1, 1);\n } else {\n m_optionsComponent.removeComponent(0, 1);\n m_optionsComponent.removeComponent(1, 1);\n }\n m_showAddKeyOption = showAddKeyOption;\n }\n }",
"public void renumberUniqueIDs()\n {\n int uid = firstUniqueID();\n for (T entity : this)\n {\n entity.setUniqueID(Integer.valueOf(uid++));\n }\n }"
] |
Set the color at "index" to "color". Entries are interpolated linearly from
the existing entries at "firstIndex" and "lastIndex" to the new entry.
firstIndex < index < lastIndex must hold.
@param index the position to set
@param firstIndex the position of the first color from which to interpolate
@param lastIndex the position of the second color from which to interpolate
@param color the color to set | [
"public void setColorInterpolated(int index, int firstIndex, int lastIndex, int color) {\n\t\tint firstColor = map[firstIndex];\n\t\tint lastColor = map[lastIndex];\n\t\tfor (int i = firstIndex; i <= index; i++)\n\t\t\tmap[i] = ImageMath.mixColors((float)(i-firstIndex)/(index-firstIndex), firstColor, color);\n\t\tfor (int i = index; i < lastIndex; i++)\n\t\t\tmap[i] = ImageMath.mixColors((float)(i-index)/(lastIndex-index), color, lastColor);\n\t}"
] | [
"private void updateBeatGrid(TrackMetadataUpdate update, BeatGrid beatGrid) {\n hotCache.put(DeckReference.getDeckReference(update.player, 0), beatGrid); // Main deck\n if (update.metadata.getCueList() != null) { // Update the cache with any hot cues in this track as well\n for (CueList.Entry entry : update.metadata.getCueList().entries) {\n if (entry.hotCueNumber != 0) {\n hotCache.put(DeckReference.getDeckReference(update.player, entry.hotCueNumber), beatGrid);\n }\n }\n }\n deliverBeatGridUpdate(update.player, beatGrid);\n }",
"public static List<Object> filterMapToList(final Map<String, ?> map, final String[] nameMapping) {\n\t\tif( map == null ) {\n\t\t\tthrow new NullPointerException(\"map 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}\n\t\t\n\t\tfinal List<Object> result = new ArrayList<Object>(nameMapping.length);\n\t\tfor( final String key : nameMapping ) {\n\t\t\tresult.add(map.get(key));\n\t\t}\n\t\treturn result;\n\t}",
"public void addConverter(int index, IConverter converter) {\r\n\t\tconverterList.add(index, converter);\r\n\t\tif (converter instanceof IContainerConverter) {\r\n\t\t\tIContainerConverter containerConverter = (IContainerConverter) converter;\r\n\t\t\tif (containerConverter.getElementConverter() == null) {\r\n\t\t\t\tcontainerConverter.setElementConverter(elementConverter);\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"public long removeAll(final String... members) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.srem(getKey(), members);\n }\n });\n }",
"public <T> QueryResult<T> query(String partitionKey, String query, final Class<T> classOfT) {\n URI uri = new DatabaseURIHelper(db.getDBUri()).partition(partitionKey).path(\"_find\").build();\n return this.query(uri, query, classOfT);\n }",
"private static void addRedeployOperationStep(final CompositeOperationBuilder builder, final DeploymentDescription deployment) {\n final String deploymentName = deployment.getName();\n final Set<String> serverGroups = deployment.getServerGroups();\n if (serverGroups.isEmpty()) {\n builder.addStep(createOperation(DEPLOYMENT_REDEPLOY_OPERATION, createAddress(DEPLOYMENT, deploymentName)));\n } else {\n for (String serverGroup : serverGroups) {\n builder.addStep(createOperation(DEPLOYMENT_REDEPLOY_OPERATION, createAddress(SERVER_GROUP, serverGroup, DEPLOYMENT, deploymentName)));\n }\n }\n }",
"public static boolean changeHost(String hostName,\n boolean enable,\n boolean disable,\n boolean remove,\n boolean isEnabled,\n boolean exists) throws Exception {\n\n // Open the file that is the first\n // command line parameter\n File hostsFile = new File(\"/etc/hosts\");\n FileInputStream fstream = new FileInputStream(\"/etc/hosts\");\n\n File outFile = null;\n BufferedWriter bw = null;\n // only do file output for destructive operations\n if (!exists && !isEnabled) {\n outFile = File.createTempFile(\"HostsEdit\", \".tmp\");\n bw = new BufferedWriter(new FileWriter(outFile));\n System.out.println(\"File name: \" + outFile.getPath());\n }\n\n // Get the object of DataInputStream\n DataInputStream in = new DataInputStream(fstream);\n BufferedReader br = new BufferedReader(new InputStreamReader(in));\n String strLine;\n boolean foundHost = false;\n boolean hostEnabled = false;\n\n\t\t/*\n * Group 1 - possible commented out host entry\n\t\t * Group 2 - destination address\n\t\t * Group 3 - host name\n\t\t * Group 4 - everything else\n\t\t */\n Pattern pattern = Pattern.compile(\"\\\\s*(#?)\\\\s*([^\\\\s]+)\\\\s*([^\\\\s]+)(.*)\");\n while ((strLine = br.readLine()) != null) {\n\n Matcher matcher = pattern.matcher(strLine);\n\n // if there is a match to the pattern and the host name is the same as the one we want to set\n if (matcher.find() &&\n matcher.group(3).toLowerCase().compareTo(hostName.toLowerCase()) == 0) {\n foundHost = true;\n if (remove) {\n // skip this line altogether\n continue;\n } else if (enable) {\n // we will disregard group 2 and just set it to 127.0.0.1\n if (!exists && !isEnabled)\n bw.write(\"127.0.0.1 \" + matcher.group(3) + matcher.group(4));\n } else if (disable) {\n if (!exists && !isEnabled)\n bw.write(\"# \" + matcher.group(2) + \" \" + matcher.group(3) + matcher.group(4));\n } else if (isEnabled && matcher.group(1).compareTo(\"\") == 0) {\n // host exists and there is no # before it\n hostEnabled = true;\n }\n } else {\n // just write the line back out\n if (!exists && !isEnabled)\n bw.write(strLine);\n }\n\n if (!exists && !isEnabled)\n bw.write('\\n');\n }\n\n // if we didn't find the host in the file but need to enable it\n if (!foundHost && enable) {\n // write a new host entry\n if (!exists && !isEnabled)\n bw.write(\"127.0.0.1 \" + hostName + '\\n');\n }\n // Close the input stream\n in.close();\n\n if (!exists && !isEnabled) {\n bw.close();\n outFile.renameTo(hostsFile);\n }\n\n // return false if the host wasn't found\n if (exists && !foundHost)\n return false;\n\n // return false if the host wasn't enabled\n if (isEnabled && !hostEnabled)\n return false;\n\n return true;\n }",
"public void process(ProjectProperties properties, FilterContainer filters, FixedData fixedData, Var2Data varData)\n {\n int filterCount = fixedData.getItemCount();\n boolean[] criteriaType = new boolean[2];\n CriteriaReader criteriaReader = getCriteriaReader();\n\n for (int filterLoop = 0; filterLoop < filterCount; filterLoop++)\n {\n byte[] filterFixedData = fixedData.getByteArrayValue(filterLoop);\n if (filterFixedData == null || filterFixedData.length < 4)\n {\n continue;\n }\n\n Filter filter = new Filter();\n filter.setID(Integer.valueOf(MPPUtility.getInt(filterFixedData, 0)));\n filter.setName(MPPUtility.removeAmpersands(MPPUtility.getUnicodeString(filterFixedData, 4)));\n byte[] filterVarData = varData.getByteArray(filter.getID(), getVarDataType());\n if (filterVarData == null)\n {\n continue;\n }\n\n //System.out.println(ByteArrayHelper.hexdump(filterVarData, true, 16, \"\"));\n List<GenericCriteriaPrompt> prompts = new LinkedList<GenericCriteriaPrompt>();\n\n filter.setShowRelatedSummaryRows(MPPUtility.getByte(filterVarData, 4) != 0);\n filter.setCriteria(criteriaReader.process(properties, filterVarData, 0, -1, prompts, null, criteriaType));\n\n filter.setIsTaskFilter(criteriaType[0]);\n filter.setIsResourceFilter(criteriaType[1]);\n filter.setPrompts(prompts);\n\n filters.addFilter(filter);\n //System.out.println(filter);\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 }"
] |
Retrieve and validate vector clock value from the REST request.
"X_VOLD_VECTOR_CLOCK" is the vector clock header.
@return true if present, false if missing | [
"protected boolean hasVectorClock(boolean isVectorClockOptional) {\n boolean result = false;\n\n String vectorClockHeader = this.request.getHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK);\n if(vectorClockHeader != null) {\n ObjectMapper mapper = new ObjectMapper();\n try {\n VectorClockWrapper vcWrapper = mapper.readValue(vectorClockHeader,\n VectorClockWrapper.class);\n this.parsedVectorClock = new VectorClock(vcWrapper.getVersions(),\n vcWrapper.getTimestamp());\n result = true;\n } catch(Exception e) {\n logger.error(\"Exception while parsing and constructing vector clock\", e);\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Invalid Vector Clock\");\n }\n } else if(!isVectorClockOptional) {\n logger.error(\"Error when validating request. Missing Vector Clock\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Missing Vector Clock\");\n } else {\n result = true;\n }\n\n return result;\n }"
] | [
"public JsonNode wbSetLabel(String id, String site, String title,\n\t\t\tString newEntity, String language, String value,\n\t\t\tboolean bot, long baserevid, String summary)\n\t\t\t\t\tthrows IOException, MediaWikiApiErrorException {\n\t\tValidate.notNull(language,\n\t\t\t\t\"Language parameter cannot be null when setting a label\");\n\t\t\n\t\tMap<String, String> parameters = new HashMap<String, String>();\n\t\tparameters.put(\"language\", language);\n\t\tif (value != null) {\n\t\t\tparameters.put(\"value\", value);\n\t\t}\n\t\t\n\t\tJsonNode response = performAPIAction(\"wbsetlabel\", id, site, title, newEntity,\n\t\t\t\tparameters, summary, baserevid, bot);\n\t\treturn response;\n\t}",
"public static <T> boolean addAll(Collection<T> target, Iterator<? extends T> iterator) {\n Preconditions.checkArgumentNotNull(target, \"target\");\n boolean modified = false;\n while (iterator.hasNext()) {\n modified |= target.add(iterator.next());\n }\n return modified;\n }",
"private static void displayAvailableFilters(ProjectFile project)\n {\n System.out.println(\"Unknown filter name supplied.\");\n System.out.println(\"Available task filters:\");\n for (Filter filter : project.getFilters().getTaskFilters())\n {\n System.out.println(\" \" + filter.getName());\n }\n\n System.out.println(\"Available resource filters:\");\n for (Filter filter : project.getFilters().getResourceFilters())\n {\n System.out.println(\" \" + filter.getName());\n }\n\n }",
"private void checkAndAddLengths(final int... requiredLengths) {\n\t\tfor( final int length : requiredLengths ) {\n\t\t\tif( length < 0 ) {\n\t\t\t\tthrow new IllegalArgumentException(String.format(\"required length cannot be negative but was %d\",\n\t\t\t\t\tlength));\n\t\t\t}\n\t\t\tthis.requiredLengths.add(length);\n\t\t}\n\t}",
"@Override\n\tpublic String toCanonicalString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = stringCache.canonicalString) == null) {\n\t\t\tstringCache.canonicalString = result = toNormalizedString(IPv6StringCache.canonicalParams);\n\t\t}\n\t\treturn result;\n\t}",
"public ThumborUrlBuilder resize(int width, int height) {\n if (width < 0 && width != ORIGINAL_SIZE) {\n throw new IllegalArgumentException(\"Width must be a positive number.\");\n }\n if (height < 0 && height != ORIGINAL_SIZE) {\n throw new IllegalArgumentException(\"Height must be a positive number.\");\n }\n if (width == 0 && height == 0) {\n throw new IllegalArgumentException(\"Both width and height must not be zero.\");\n }\n hasResize = true;\n resizeWidth = width;\n resizeHeight = height;\n return this;\n }",
"private void addAssignments(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (ResourceAssignment assignment : file.getResourceAssignments())\n {\n final ResourceAssignment a = assignment;\n MpxjTreeNode childNode = new MpxjTreeNode(a)\n {\n @Override public String toString()\n {\n Resource resource = a.getResource();\n String resourceName = resource == null ? \"(unknown resource)\" : resource.getName();\n Task task = a.getTask();\n String taskName = task == null ? \"(unknown task)\" : task.getName();\n return resourceName + \"->\" + taskName;\n }\n };\n parentNode.add(childNode);\n }\n }",
"public static float smoothStep(float a, float b, float x) {\n\t\tif (x < a)\n\t\t\treturn 0;\n\t\tif (x >= b)\n\t\t\treturn 1;\n\t\tx = (x - a) / (b - a);\n\t\treturn x*x * (3 - 2*x);\n\t}",
"public static clusternodegroup get(nitro_service service, String name) throws Exception{\n\t\tclusternodegroup obj = new clusternodegroup();\n\t\tobj.set_name(name);\n\t\tclusternodegroup response = (clusternodegroup) obj.get_resource(service);\n\t\treturn response;\n\t}"
] |
called per frame of animation to update the camera position | [
"public void updateAnimation()\n {\n Date time = new Date();\n long currentTime = time.getTime() - this.beginAnimation;\n if (currentTime > animationTime)\n {\n this.currentQuaternion.set(endQuaternion);\n for (int i = 0; i < 3; i++)\n {\n\n this.currentPos[i] = this.endPos[i];\n }\n this.animate = false;\n }\n\n else\n {\n float t = (float) currentTime / animationTime;\n this.currentQuaternion = this.beginQuaternion.slerp(this.endQuaternion,\n t);\n for (int i = 0; i < 3; i++)\n {\n this.currentPos[i] = this.beginPos[i] + totalTranslation[i] * t;\n }\n\n }\n }"
] | [
"public LuaScriptBlock endBlockReturn(LuaValue value) {\n add(new LuaAstReturnStatement(argument(value)));\n return new LuaScriptBlock(script);\n }",
"protected void doSplitTokenImpl(Token token, ITokenAcceptor result) {\n\t\tString text = token.getText();\n\t\tint indentation = computeIndentation(text);\n\t\tif (indentation == -1 || indentation == currentIndentation) {\n\t\t\t// no change of indentation level detected simply process the token\n\t\t\tresult.accept(token);\n\t\t} else if (indentation > currentIndentation) {\n\t\t\t// indentation level increased\n\t\t\tsplitIntoBeginToken(token, indentation, result);\n\t\t} else if (indentation < currentIndentation) {\n\t\t\t// indentation level decreased\n\t\t\tint charCount = computeIndentationRelevantCharCount(text);\n\t\t\tif (charCount > 0) {\n\t\t\t\t// emit whitespace including newline\n\t\t\t\tsplitWithText(token, text.substring(0, charCount), result);\t\n\t\t\t}\n\t\t\t// emit end tokens at the beginning of the line\n\t\t\tdecreaseIndentation(indentation, result);\n\t\t\tif (charCount != text.length()) {\n\t\t\t\thandleRemainingText(token, text.substring(charCount), indentation, result);\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new IllegalStateException(String.valueOf(indentation));\n\t\t}\n\t}",
"public Where<T, ID> not() {\n\t\t/*\n\t\t * Special circumstance here when we have a needs future with a not. Something like and().not().like(...). In\n\t\t * this case we satisfy the and()'s future as the not() but the not() becomes the new needs-future.\n\t\t */\n\t\tNot not = new Not();\n\t\taddClause(not);\n\t\taddNeedsFuture(not);\n\t\treturn this;\n\t}",
"public DefaultStreamingEndpoint languages(List<String> languages) {\n addPostParameter(Constants.LANGUAGE_PARAM, Joiner.on(',').join(languages));\n return this;\n }",
"public void deleteFile(String fileID) {\n URL url = FILE_INFO_URL_TEMPLATE.build(this.api.getBaseURL(), fileID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"DELETE\");\n BoxAPIResponse response = request.send();\n response.disconnect();\n }",
"public static void extract( DMatrixRMaj src,\n int rows[] , int rowsSize ,\n int cols[] , int colsSize , DMatrixRMaj dst ) {\n if( rowsSize != dst.numRows || colsSize != dst.numCols )\n throw new MatrixDimensionException(\"Unexpected number of rows and/or columns in dst matrix\");\n\n int indexDst = 0;\n for (int i = 0; i < rowsSize; i++) {\n int indexSrcRow = src.numCols*rows[i];\n for (int j = 0; j < colsSize; j++) {\n dst.data[indexDst++] = src.data[indexSrcRow + cols[j]];\n }\n }\n }",
"public static boolean isSameStructure(DMatrixSparseCSC a , DMatrixSparseCSC b) {\n if( a.numRows == b.numRows && a.numCols == b.numCols && a.nz_length == b.nz_length) {\n for (int i = 0; i <= a.numCols; i++) {\n if( a.col_idx[i] != b.col_idx[i] )\n return false;\n }\n for (int i = 0; i < a.nz_length; i++) {\n if( a.nz_rows[i] != b.nz_rows[i] )\n return false;\n }\n return true;\n }\n return false;\n }",
"public Number getUnits(int field) throws MPXJException\n {\n Number result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n try\n {\n result = Double.valueOf(m_formats.getUnitsDecimalFormat().parse(m_fields[field]).doubleValue() * 100);\n }\n\n catch (ParseException ex)\n {\n throw new MPXJException(\"Failed to parse units\", ex);\n }\n }\n else\n {\n result = null;\n }\n\n return (result);\n }",
"@RequestMapping(value = \"/api/plugins\", method = RequestMethod.POST)\n public\n @ResponseBody\n HashMap<String, Object> addPluginPath(Model model, Plugin add) throws Exception {\n PluginManager.getInstance().addPluginPath(add.getPath());\n\n return pluginInformation();\n }"
] |
Given a year, month, and day, find the number of occurrences of that day in the month
@param year the year
@param month the month
@param day the day
@return the number of occurrences of the day in the month | [
"public int numOccurrences(int year, int month, int day) {\n DateTimeFormatter parser = ISODateTimeFormat.date();\n DateTime date = parser.parseDateTime(year + \"-\" + month + \"-\" + \"01\");\n Calendar cal = Calendar.getInstance();\n cal.setTime(date.toDate());\n GregorianChronology calendar = GregorianChronology.getInstance();\n DateTimeField field = calendar.dayOfMonth();\n\n int days = 0;\n int count = 0;\n int num = field.getMaximumValue(new LocalDate(year, month, day, calendar));\n while (days < num) {\n if (cal.get(Calendar.DAY_OF_WEEK) == day) {\n count++;\n }\n date = date.plusDays(1);\n cal.setTime(date.toDate());\n\n days++;\n }\n return count;\n }"
] | [
"public static PredicateExpression all(Object... rhs) {\n PredicateExpression ex = new PredicateExpression( \"$all\", rhs);\n if (rhs.length == 1) {\n ex.single = true;\n }\n return ex;\n }",
"public T modifyFile(final String name, final List<String> path, final byte[] existingHash, final byte[] newHash, final boolean isDirectory) {\n return modifyFile(name, path, existingHash, newHash, isDirectory, null);\n }",
"private List<AssignmentField> getAllAssignmentExtendedAttributes()\n {\n ArrayList<AssignmentField> result = new ArrayList<AssignmentField>();\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_COST));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_DATE));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_DURATION));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_COST));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_DATE));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_DURATION));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_FLAG));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_NUMBER));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_RESOURCE_MULTI_VALUE));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_RESOURCE_OUTLINE_CODE));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_TEXT));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_FINISH));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_FLAG));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_NUMBER));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_START));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_TEXT));\n return result;\n }",
"private static void addRedeployOperationStep(final CompositeOperationBuilder builder, final DeploymentDescription deployment) {\n final String deploymentName = deployment.getName();\n final Set<String> serverGroups = deployment.getServerGroups();\n if (serverGroups.isEmpty()) {\n builder.addStep(createOperation(DEPLOYMENT_REDEPLOY_OPERATION, createAddress(DEPLOYMENT, deploymentName)));\n } else {\n for (String serverGroup : serverGroups) {\n builder.addStep(createOperation(DEPLOYMENT_REDEPLOY_OPERATION, createAddress(SERVER_GROUP, serverGroup, DEPLOYMENT, deploymentName)));\n }\n }\n }",
"public String getString(Integer offset)\n {\n String result = null;\n\n if (offset != null)\n {\n byte[] value = m_map.get(offset);\n if (value != null)\n {\n result = MPPUtility.getString(value, 0);\n }\n }\n\n return (result);\n }",
"public static boolean zipFolder(File folder, String fileName){\n\t\tboolean success = false;\n\t\tif(!folder.isDirectory()){\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tif(fileName == null){\n\t\t\tfileName = folder.getAbsolutePath()+ZIP_EXT;\n\t\t}\n\t\t\n\t\tZipArchiveOutputStream zipOutput = null;\n\t\ttry {\n\t\t\tzipOutput = new ZipArchiveOutputStream(new File(fileName));\n\t\t\t\n\t\t\tsuccess = addFolderContentToZip(folder,zipOutput,\"\");\n\n\t\t\tzipOutput.close();\n\t\t\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t\treturn false;\n\t\t}\n\t\tfinally{\n\t\t\ttry {\n\t\t\t\tif(zipOutput != null){\n\t\t\t\t\tzipOutput.close();\n\t\t\t\t}\n\t\t\t} catch (IOException e) {}\n\t\t}\n\t\treturn success;\n\t}",
"public void process() {\n // are we ready to process yet, or have we had an error, and are\n // waiting a bit longer in the hope that it will resolve itself?\n if (error_skips > 0) {\n error_skips--;\n return;\n }\n \n try {\n if (logger != null)\n logger.debug(\"Starting processing\");\n status = \"Processing\";\n lastCheck = System.currentTimeMillis();\n\n // FIXME: how to break off processing if we don't want to keep going?\n processor.deduplicate(batch_size);\n\n status = \"Sleeping\";\n if (logger != null)\n logger.debug(\"Finished processing\");\n } catch (Throwable e) {\n status = \"Thread blocked on error: \" + e;\n if (logger != null)\n logger.error(\"Error in processing; waiting\", e);\n error_skips = error_factor;\n }\n }",
"public ThumborUrlBuilder buildImage(String image) {\n if (image == null || image.length() == 0) {\n throw new IllegalArgumentException(\"Image must not be blank.\");\n }\n return new ThumborUrlBuilder(host, key, image);\n }",
"@Deprecated\r\n public static URL buildUrl(String host, int port, String path, Map<String, String> parameters) throws MalformedURLException {\r\n return buildUrl(\"http\", port, path, parameters);\r\n }"
] |
Create a collection object of the given collection type. If none has been given,
OJB uses RemovalAwareList, RemovalAwareSet, or RemovalAwareCollection depending
on the field type.
@param desc The collection descriptor
@param collectionClass The collection class specified in the collection-descriptor
@return The collection object | [
"protected ManageableCollection createCollection(CollectionDescriptor desc, Class collectionClass)\r\n {\r\n Class fieldType = desc.getPersistentField().getType();\r\n ManageableCollection col;\r\n\r\n if (collectionClass == null)\r\n {\r\n if (ManageableCollection.class.isAssignableFrom(fieldType))\r\n {\r\n try\r\n {\r\n col = (ManageableCollection)fieldType.newInstance();\r\n }\r\n catch (Exception e)\r\n {\r\n throw new OJBRuntimeException(\"Cannot instantiate the default collection type \"+fieldType.getName()+\" of collection \"+desc.getAttributeName()+\" in type \"+desc.getClassDescriptor().getClassNameOfObject());\r\n }\r\n }\r\n else if (fieldType.isAssignableFrom(RemovalAwareCollection.class))\r\n {\r\n col = new RemovalAwareCollection();\r\n }\r\n else if (fieldType.isAssignableFrom(RemovalAwareList.class))\r\n {\r\n col = new RemovalAwareList();\r\n }\r\n else if (fieldType.isAssignableFrom(RemovalAwareSet.class))\r\n {\r\n col = new RemovalAwareSet();\r\n }\r\n else\r\n {\r\n throw new MetadataException(\"Cannot determine a default collection type for collection \"+desc.getAttributeName()+\" in type \"+desc.getClassDescriptor().getClassNameOfObject());\r\n }\r\n }\r\n else\r\n {\r\n try\r\n {\r\n col = (ManageableCollection)collectionClass.newInstance();\r\n }\r\n catch (Exception e)\r\n {\r\n throw new OJBRuntimeException(\"Cannot instantiate the collection class \"+collectionClass.getName()+\" of collection \"+desc.getAttributeName()+\" in type \"+desc.getClassDescriptor().getClassNameOfObject());\r\n }\r\n }\r\n return col;\r\n }"
] | [
"@CheckReturnValue\n private LocalSyncWriteModelContainer resolveConflict(\n final NamespaceSynchronizationConfig nsConfig,\n final CoreDocumentSynchronizationConfig docConfig,\n final ChangeEvent<BsonDocument> remoteEvent\n ) {\n return resolveConflict(nsConfig, docConfig, docConfig.getLastUncommittedChangeEvent(),\n remoteEvent);\n }",
"private void setFileNotWorldReadablePermissions(File file) {\n file.setReadable(false, false);\n file.setWritable(false, false);\n file.setExecutable(false, false);\n file.setReadable(true, true);\n file.setWritable(true, true);\n }",
"protected boolean check(String value, String regex) {\n\t\tPattern pattern = Pattern.compile(regex);\n\t\treturn pattern.matcher(value).matches();\n\t}",
"private void add(int field)\n {\n if (field < m_flags.length)\n {\n if (m_flags[field] == false)\n {\n m_flags[field] = true;\n m_fields[m_count] = field;\n ++m_count;\n }\n }\n }",
"protected String getExtraSolrParams() {\n\n try {\n return m_configObject.getString(JSON_KEY_EXTRASOLRPARAMS);\n } catch (JSONException e) {\n if (null == m_baseConfig) {\n if (LOG.isInfoEnabled()) {\n LOG.info(Messages.get().getBundle().key(Messages.LOG_NO_EXTRA_PARAMETERS_0), e);\n }\n return \"\";\n } else {\n return m_baseConfig.getGeneralConfig().getExtraSolrParams();\n }\n }\n }",
"@Override\n public EthiopicDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }",
"public static csvserver_cmppolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_cmppolicy_binding obj = new csvserver_cmppolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_cmppolicy_binding response[] = (csvserver_cmppolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public InputStream getStream(String url, RasterLayer layer) throws IOException {\n\t\tif (layer instanceof ProxyLayerSupport) {\n\t\t\tProxyLayerSupport proxyLayer = (ProxyLayerSupport) layer;\n\t\t\tif (proxyLayer.isUseCache() && null != cacheManagerService) {\n\t\t\t\tObject cachedObject = cacheManagerService.get(proxyLayer, CacheCategory.RASTER, url);\n\t\t\t\tif (null != cachedObject) {\n\t\t\t\t\ttestRecorder.record(TEST_RECORDER_GROUP, TEST_RECORDER_GET_FROM_CACHE);\n\t\t\t\t\treturn new ByteArrayInputStream((byte[]) cachedObject);\n\t\t\t\t} else {\n\t\t\t\t\ttestRecorder.record(TEST_RECORDER_GROUP, TEST_RECORDER_PUT_IN_CACHE);\n\t\t\t\t\tInputStream stream = super.getStream(url, proxyLayer);\n\t\t\t\t\tByteArrayOutputStream os = new ByteArrayOutputStream();\n\t\t\t\t\tint b;\n\t\t\t\t\twhile ((b = stream.read()) >= 0) {\n\t\t\t\t\t\tos.write(b);\n\t\t\t\t\t}\n\t\t\t\t\tcacheManagerService.put(proxyLayer, CacheCategory.RASTER, url, os.toByteArray(),\n\t\t\t\t\t\t\tgetLayerEnvelope(proxyLayer));\n\t\t\t\t\treturn new ByteArrayInputStream((byte[]) os.toByteArray());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn super.getStream(url, layer);\n\t}",
"@Override\n\tpublic RandomVariable getValue(double evaluationTime, AssetModelMonteCarloSimulationModel model) throws CalculationException {\n\t\tif(exerciseMethod == ExerciseMethod.UPPER_BOUND_METHOD) {\n\t\t\t// Find optimal lambda\n\t\t\tGoldenSectionSearch optimizer = new GoldenSectionSearch(-1.0, 1.0);\n\t\t\twhile(!optimizer.isDone()) {\n\t\t\t\tdouble lambda = optimizer.getNextPoint();\n\t\t\t\tdouble value = this.getValues(evaluationTime, model, lambda).getAverage();\n\t\t\t\toptimizer.setValue(value);\n\t\t\t}\n\t\t\treturn getValues(evaluationTime, model, optimizer.getBestPoint());\n\t\t}\n\t\telse {\n\t\t\treturn getValues(evaluationTime, model, 0.0);\n\t\t}\n\t}"
] |
Print the class's operations m | [
"private boolean operations(Options opt, MethodDoc m[]) {\n\tboolean printed = false;\n\tfor (MethodDoc md : m) {\n\t if (hidden(md))\n\t\tcontinue;\n\t // Filter-out static initializer method\n\t if (md.name().equals(\"<clinit>\") && md.isStatic() && md.isPackagePrivate())\n\t\tcontinue;\n\t stereotype(opt, md, Align.LEFT);\n\t String op = visibility(opt, md) + md.name() + //\n\t\t (opt.showType ? \"(\" + parameter(opt, md.parameters()) + \")\" + typeAnnotation(opt, md.returnType())\n\t\t\t : \"()\");\n\t tableLine(Align.LEFT, (md.isAbstract() ? Font.ABSTRACT : Font.NORMAL).wrap(opt, op));\n\t printed = true;\n\n\t tagvalue(opt, md);\n\t}\n\treturn printed;\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 }",
"protected void updateLabelActiveStyle() {\n if (this.valueBoxBase.getText() != null && !this.valueBoxBase.getText().isEmpty()) {\n label.addStyleName(CssName.ACTIVE);\n } else {\n label.removeStyleName(CssName.ACTIVE);\n }\n }",
"private void logShort(CharSequence message, boolean trim) throws IOException {\n int length = message.length();\n if (trim) {\n while (length > 0 && Character.isWhitespace(message.charAt(length - 1))) {\n length--;\n }\n }\n\n char [] chars = new char [length + 1];\n for (int i = 0; i < length; i++) {\n chars[i] = message.charAt(i);\n }\n chars[length] = '\\n';\n\n output.write(chars);\n }",
"public static void addItemsHandled(String handledItemsType, int handledItemsNumber) {\n \tJobLogger jobLogger = (JobLogger) getInstance();\n if (jobLogger == null) {\n return;\n }\n\n jobLogger.addItemsHandledInstance(handledItemsType, handledItemsNumber);\n }",
"public Object getObjectByIdentity(Identity id)\r\n throws PersistenceBrokerException\r\n {\r\n checkOpen();\r\n ObjectEnvelope envelope = objectEnvelopeTable.getByIdentity(id);\r\n if (envelope != null)\r\n {\r\n return (envelope.needsDelete() ? null : envelope.getObject());\r\n }\r\n else\r\n {\r\n return getBroker().getObjectByIdentity(id);\r\n }\r\n }",
"protected DateTimeException _peelDTE(DateTimeException e) {\n while (true) {\n Throwable t = e.getCause();\n if (t != null && t instanceof DateTimeException) {\n e = (DateTimeException) t;\n continue;\n }\n break;\n }\n return e;\n }",
"public synchronized void abortTransaction() throws TransactionNotInProgressException\n {\n if(isInTransaction())\n {\n fireBrokerEvent(BEFORE_ROLLBACK_EVENT);\n setInTransaction(false);\n clearRegistrationLists();\n referencesBroker.removePrefetchingListeners();\n /*\n arminw:\n check if we in local tx, before do local rollback\n Necessary, because ConnectionManager may do a rollback by itself\n or in managed environments the used connection is already be closed\n */\n if(connectionManager.isInLocalTransaction()) this.connectionManager.localRollback();\n fireBrokerEvent(AFTER_ROLLBACK_EVENT);\n }\n }",
"public ItemRequest<Workspace> addUser(String workspace) {\n \n String path = String.format(\"/workspaces/%s/addUser\", workspace);\n return new ItemRequest<Workspace>(this, Workspace.class, path, \"POST\");\n }",
"public static void removeFromList(List<String> list, String value) {\n int foundIndex = -1;\n int i = 0;\n for (String id : list) {\n if (id.equalsIgnoreCase(value)) {\n foundIndex = i;\n break;\n }\n i++;\n }\n if (foundIndex != -1) {\n list.remove(foundIndex);\n }\n }"
] |
Subtracts vector v1 from v2 and places the result in this vector.
@param v1
left-hand vector
@param v2
right-hand vector | [
"public void sub(Vector3d v1, Vector3d v2) {\n x = v1.x - v2.x;\n y = v1.y - v2.y;\n z = v1.z - v2.z;\n }"
] | [
"public void logAttributeWarning(PathAddress address, String message, Set<String> attributes) {\n messageQueue.add(new AttributeLogEntry(address, null, message, attributes));\n }",
"public static URL getKubernetesConfigurationUrl(Map<String, String> map) throws MalformedURLException {\n if (Strings.isNotNullOrEmpty(Utils.getSystemPropertyOrEnvVar(ENVIRONMENT_CONFIG_URL, \"\"))) {\n return new URL(Utils.getSystemPropertyOrEnvVar(ENVIRONMENT_CONFIG_URL, \"\"));\n } else if (Strings.isNotNullOrEmpty(Utils.getSystemPropertyOrEnvVar(ENVIRONMENT_CONFIG_RESOURCE_NAME, \"\"))) {\n String resourceName = Utils.getSystemPropertyOrEnvVar(ENVIRONMENT_CONFIG_RESOURCE_NAME, \"\");\n return findConfigResource(resourceName);\n } else if (map.containsKey(ENVIRONMENT_CONFIG_URL)) {\n return new URL(map.get(ENVIRONMENT_CONFIG_URL));\n } else if (map.containsKey(ENVIRONMENT_CONFIG_RESOURCE_NAME)) {\n String resourceName = map.get(ENVIRONMENT_CONFIG_RESOURCE_NAME);\n return findConfigResource(resourceName);\n } else {\n // Let the resource locator find the resource\n return null;\n }\n }",
"public ProteusApplication setServerConfigurationFunction(Function<Undertow.Builder, Undertow.Builder> serverConfigurationFunction)\n {\n this.serverConfigurationFunction = serverConfigurationFunction;\n return this;\n }",
"@Deprecated\r\n public Category browse(String catId) throws FlickrException {\r\n List<Subcategory> subcategories = new ArrayList<Subcategory>();\r\n List<Group> groups = new ArrayList<Group>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_BROWSE);\r\n\r\n if (catId != null) {\r\n parameters.put(\"cat_id\", catId);\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element categoryElement = response.getPayload();\r\n\r\n Category category = new Category();\r\n category.setName(categoryElement.getAttribute(\"name\"));\r\n category.setPath(categoryElement.getAttribute(\"path\"));\r\n category.setPathIds(categoryElement.getAttribute(\"pathids\"));\r\n\r\n NodeList subcatNodes = categoryElement.getElementsByTagName(\"subcat\");\r\n for (int i = 0; i < subcatNodes.getLength(); i++) {\r\n Element node = (Element) subcatNodes.item(i);\r\n Subcategory subcategory = new Subcategory();\r\n subcategory.setId(Integer.parseInt(node.getAttribute(\"id\")));\r\n subcategory.setName(node.getAttribute(\"name\"));\r\n subcategory.setCount(Integer.parseInt(node.getAttribute(\"count\")));\r\n\r\n subcategories.add(subcategory);\r\n }\r\n\r\n NodeList groupNodes = categoryElement.getElementsByTagName(\"group\");\r\n for (int i = 0; i < groupNodes.getLength(); i++) {\r\n Element node = (Element) groupNodes.item(i);\r\n Group group = new Group();\r\n group.setId(node.getAttribute(\"nsid\"));\r\n group.setName(node.getAttribute(\"name\"));\r\n group.setMembers(node.getAttribute(\"members\"));\r\n\r\n groups.add(group);\r\n }\r\n\r\n category.setGroups(groups);\r\n category.setSubcategories(subcategories);\r\n\r\n return category;\r\n }",
"protected void validateResultsDirectories() {\n for (String result : results) {\n if (Files.notExists(Paths.get(result))) {\n throw new AllureCommandException(String.format(\"Report directory <%s> not found.\", result));\n }\n }\n }",
"private List<Map<Class<? extends Annotation>, ParameterInfo<?>>> createParametersInfos(Method method) {\n if (method.getParameterTypes().length <= 2) {\n return Collections.emptyList();\n }\n\n List<Map<Class<? extends Annotation>, ParameterInfo<?>>> result = new ArrayList<>();\n Type[] parameterTypes = method.getGenericParameterTypes();\n Annotation[][] parameterAnnotations = method.getParameterAnnotations();\n\n for (int i = 2; i < parameterAnnotations.length; i++) {\n Annotation[] annotations = parameterAnnotations[i];\n Map<Class<? extends Annotation>, ParameterInfo<?>> paramAnnotations = new IdentityHashMap<>();\n\n for (Annotation annotation : annotations) {\n Class<? extends Annotation> annotationType = annotation.annotationType();\n ParameterInfo<?> parameterInfo;\n\n if (PathParam.class.isAssignableFrom(annotationType)) {\n parameterInfo = ParameterInfo.create(annotation,\n ParamConvertUtils.createPathParamConverter(parameterTypes[i]));\n } else if (QueryParam.class.isAssignableFrom(annotationType)) {\n parameterInfo = ParameterInfo.create(annotation,\n ParamConvertUtils.createQueryParamConverter(parameterTypes[i]));\n } else if (HeaderParam.class.isAssignableFrom(annotationType)) {\n parameterInfo = ParameterInfo.create(annotation,\n ParamConvertUtils.createHeaderParamConverter(parameterTypes[i]));\n } else {\n parameterInfo = ParameterInfo.create(annotation, null);\n }\n\n paramAnnotations.put(annotationType, parameterInfo);\n }\n\n // Must have either @PathParam, @QueryParam or @HeaderParam, but not two or more.\n int presence = 0;\n for (Class<? extends Annotation> annotationClass : paramAnnotations.keySet()) {\n if (SUPPORTED_PARAM_ANNOTATIONS.contains(annotationClass)) {\n presence++;\n }\n }\n if (presence != 1) {\n throw new IllegalArgumentException(\n String.format(\"Must have exactly one annotation from %s for parameter %d in method %s\",\n SUPPORTED_PARAM_ANNOTATIONS, i, method));\n }\n\n result.add(Collections.unmodifiableMap(paramAnnotations));\n }\n\n return Collections.unmodifiableList(result);\n }",
"private InputStream runSparqlQuery(String query) throws IOException {\n\t\ttry {\n\t\t\tString queryString = \"query=\" + URLEncoder.encode(query, \"UTF-8\")\n\t\t\t\t\t+ \"&format=json\";\n\t\t\tURL url = new URL(\"https://query.wikidata.org/sparql?\"\n\t\t\t\t\t+ queryString);\n\t\t\tHttpURLConnection connection = (HttpURLConnection) url\n\t\t\t\t\t.openConnection();\n\t\t\tconnection.setRequestMethod(\"GET\");\n\n\t\t\treturn connection.getInputStream();\n\t\t} catch (UnsupportedEncodingException | MalformedURLException e) {\n\t\t\tthrow new RuntimeException(e.getMessage(), e);\n\t\t}\n\t}",
"public int getShort(Integer id, Integer type)\n {\n int result = 0;\n\n Integer offset = m_meta.getOffset(id, type);\n\n if (offset != null)\n {\n byte[] value = m_map.get(offset);\n\n if (value != null && value.length >= 2)\n {\n result = MPPUtility.getShort(value, 0);\n }\n }\n\n return (result);\n }",
"private static Map<String, List<String>> getOrCreateProtocolHeader(\n Message message) {\n Map<String, List<String>> headers = CastUtils.cast((Map<?, ?>) message\n .get(Message.PROTOCOL_HEADERS));\n if (headers == null) {\n headers = new HashMap<String, List<String>>();\n message.put(Message.PROTOCOL_HEADERS, headers);\n }\n return headers;\n }"
] |
Add roles for given role parent item.
@param ouItem group parent item | [
"private void addChildrenForRolesNode(String ouItem) {\n\n try {\n List<CmsRole> roles = OpenCms.getRoleManager().getRoles(m_cms, ouItem.substring(1), false);\n CmsRole.applySystemRoleOrder(roles);\n for (CmsRole role : roles) {\n String roleId = ouItem + \"/\" + role.getId();\n Item roleItem = m_treeContainer.addItem(roleId);\n if (roleItem == null) {\n roleItem = getItem(roleId);\n }\n roleItem.getItemProperty(PROP_NAME).setValue(getIconCaptionHTML(role, CmsOuTreeType.ROLE));\n roleItem.getItemProperty(PROP_TYPE).setValue(CmsOuTreeType.ROLE);\n setChildrenAllowed(roleId, false);\n m_treeContainer.setParent(roleId, ouItem);\n }\n } catch (CmsException e) {\n LOG.error(\"Can not read group\", e);\n }\n }"
] | [
"public static vpnvserver_vpnnexthopserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_vpnnexthopserver_binding obj = new vpnvserver_vpnnexthopserver_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_vpnnexthopserver_binding response[] = (vpnvserver_vpnnexthopserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public HashMap<String, Object> getFirstResult(String query)\n throws Exception {\n HashMap<String, Object> result = null;\n\n Statement queryStatement = null;\n ResultSet results = null;\n try (Connection sqlConnection = getConnection()) {\n queryStatement = sqlConnection.createStatement();\n results = queryStatement.executeQuery(query);\n if (results.next()) {\n result = new HashMap<>();\n String[] columns = getColumnNames(results.getMetaData());\n\n for (String column : columns) {\n result.put(column, results.getObject(column));\n }\n }\n } catch (Exception e) {\n\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return result;\n }",
"public synchronized void jumpToBeat(int beat) {\n\n if (beat < 1) {\n beat = 1;\n } else {\n beat = wrapBeat(beat);\n }\n\n if (playing.get()) {\n metronome.jumpToBeat(beat);\n } else {\n whereStopped.set(metronome.getSnapshot(metronome.getTimeOfBeat(beat)));\n }\n }",
"public <T extends CanvasWriter> T getWriter(Class<T> type, OauthToken oauthToken) {\n return getWriter(type, oauthToken, false);\n }",
"private Level getLogLevel() {\n return isQuiet() ? Level.OFF : isVerbose() ? Level.DEBUG : Level.INFO;\n }",
"@Override\n\tpublic ClosableIterator<Tuple> callStoredProcedure(String storedProcedureName, ProcedureQueryParameters params, TupleContext tupleContext) {\n\t\tvalidate( params );\n\t\tStringBuilder commandLine = createCallStoreProcedureCommand( storedProcedureName, params );\n\t\tDocument result = callStoredProcedure( commandLine );\n\t\tObject resultValue = result.get( \"retval\" );\n\t\tList<Tuple> resultTuples = extractTuples( storedProcedureName, resultValue );\n\t\treturn CollectionHelper.newClosableIterator( resultTuples );\n\t}",
"@Override\n public final Map<String, OperationEntry> getOperationDescriptions(final PathAddress address, boolean inherited) {\n\n if (parent != null) {\n RootInvocation ri = getRootInvocation();\n return ri.root.getOperationDescriptions(ri.pathAddress.append(address), inherited);\n }\n // else we are the root\n Map<String, OperationEntry> providers = new TreeMap<String, OperationEntry>();\n getOperationDescriptions(address.iterator(), providers, inherited);\n return providers;\n }",
"public Triple<EObject, EReference, INode> decode(Resource res, String uriFragment) {\n\t\tif (isUseIndexFragment(res)) {\n\t\t\treturn getLazyProxyInformation(res, uriFragment);\n\t\t}\n\t\tList<String> split = Strings.split(uriFragment, SEP);\n\t\tEObject source = resolveShortFragment(res, split.get(1));\n\t\tEReference ref = fromShortExternalForm(source.eClass(), split.get(2));\n\t\tINode compositeNode = NodeModelUtils.getNode(source);\n\t\tif (compositeNode==null)\n\t\t\tthrow new IllegalStateException(\"Couldn't resolve lazy link, because no node model is attached.\");\n\t\tINode textNode = getNode(compositeNode, split.get(3));\n\t\treturn Tuples.create(source, ref, textNode);\n\t}",
"public static Map<String, List<String>> getResponseHeaders(String stringUrl) throws IOException {\n return getResponseHeaders(stringUrl, true);\n }"
] |
get string from post stream
@param is
@param encoding
@return | [
"public static String getPostString(InputStream is, String encoding) {\n try {\n StringWriter sw = new StringWriter();\n IOUtils.copy(is, sw, encoding);\n\n return sw.toString();\n } catch (IOException e) {\n // no op\n return null;\n } finally {\n IOUtils.closeQuietly(is);\n }\n }"
] | [
"private Storepoint getCurrentStorepoint(Project phoenixProject)\n {\n List<Storepoint> storepoints = phoenixProject.getStorepoints().getStorepoint();\n Collections.sort(storepoints, new Comparator<Storepoint>()\n {\n @Override public int compare(Storepoint o1, Storepoint o2)\n {\n return DateHelper.compare(o2.getCreationTime(), o1.getCreationTime());\n }\n });\n return storepoints.get(0);\n }",
"public static gslbservice[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tgslbservice obj = new gslbservice();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tgslbservice[] response = (gslbservice[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}",
"public static int cudnnPoolingForward(\n cudnnHandle handle, \n cudnnPoolingDescriptor poolingDesc, \n Pointer alpha, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor yDesc, \n Pointer y)\n {\n return checkResult(cudnnPoolingForwardNative(handle, poolingDesc, alpha, xDesc, x, beta, yDesc, y));\n }",
"public void ifHasMemberWithTag(String template, Properties attributes) throws XDocletException\r\n {\r\n ArrayList allMemberNames = new ArrayList();\r\n HashMap allMembers = new HashMap();\r\n boolean hasTag = false;\r\n\r\n addMembers(allMemberNames, allMembers, getCurrentClass(), null, null, null);\r\n for (Iterator it = allMemberNames.iterator(); it.hasNext(); ) {\r\n XMember member = (XMember) allMembers.get(it.next());\r\n\r\n if (member instanceof XField) {\r\n setCurrentField((XField)member);\r\n if (hasTag(attributes, FOR_FIELD)) {\r\n hasTag = true;\r\n }\r\n setCurrentField(null);\r\n }\r\n else if (member instanceof XMethod) {\r\n setCurrentMethod((XMethod)member);\r\n if (hasTag(attributes, FOR_METHOD)) {\r\n hasTag = true;\r\n }\r\n setCurrentMethod(null);\r\n }\r\n if (hasTag) {\r\n generate(template);\r\n break;\r\n }\r\n }\r\n }",
"private boolean isAllNumeric(TokenStream stream) {\n List<Token> tokens = ((NattyTokenSource) stream.getTokenSource()).getTokens();\n for(Token token:tokens) {\n try {\n Integer.parseInt(token.getText());\n } catch(NumberFormatException e) {\n return false;\n }\n }\n return true;\n }",
"public static CharSequence getAt(CharSequence text, Range range) {\n RangeInfo info = subListBorders(text.length(), range);\n CharSequence sequence = text.subSequence(info.from, info.to);\n return info.reverse ? reverse(sequence) : sequence;\n }",
"public String getName() {\n if (name == null && securityIdentity != null) {\n name = securityIdentity.getPrincipal().getName();\n }\n\n return name;\n }",
"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 final void reset()\n {\n for (int i = 0; i < combinationIndices.length; i++)\n {\n combinationIndices[i] = i;\n }\n remainingCombinations = totalCombinations;\n }"
] |
Get the collection of configured blogs for the calling user.
@return The Collection of configured blogs | [
"public Collection<Blog> getList() throws FlickrException {\r\n List<Blog> blogs = new ArrayList<Blog>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIST);\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element blogsElement = response.getPayload();\r\n NodeList blogNodes = blogsElement.getElementsByTagName(\"blog\");\r\n for (int i = 0; i < blogNodes.getLength(); i++) {\r\n Element blogElement = (Element) blogNodes.item(i);\r\n Blog blog = new Blog();\r\n blog.setId(blogElement.getAttribute(\"id\"));\r\n blog.setName(blogElement.getAttribute(\"name\"));\r\n blog.setNeedPassword(\"1\".equals(blogElement.getAttribute(\"needspassword\")));\r\n blog.setUrl(blogElement.getAttribute(\"url\"));\r\n blogs.add(blog);\r\n }\r\n return blogs;\r\n }"
] | [
"public String getString(Integer id, Integer type)\n {\n return (getString(m_meta.getOffset(id, type)));\n }",
"private void sendEvents(final List<Event> events) {\n if (null != handlers) {\n for (EventHandler current : handlers) {\n for (Event event : events) {\n current.handleEvent(event);\n }\n }\n }\n\n LOG.info(\"Put events(\" + events.size() + \") to Monitoring Server.\");\n\n try {\n if (sendToEventadmin) {\n EventAdminPublisher.publish(events);\n } else {\n monitoringServiceClient.putEvents(events);\n }\n } catch (MonitoringException e) {\n throw e;\n } catch (Exception e) {\n throw new MonitoringException(\"002\",\n \"Unknown error while execute put events to Monitoring Server\", e);\n }\n\n }",
"public static <T> T assertNotNull(T value, String message) {\n if (value == null)\n throw new IllegalStateException(message);\n return value;\n }",
"public static sslcertkey[] get(nitro_service service, String certkey[]) throws Exception{\n\t\tif (certkey !=null && certkey.length>0) {\n\t\t\tsslcertkey response[] = new sslcertkey[certkey.length];\n\t\t\tsslcertkey obj[] = new sslcertkey[certkey.length];\n\t\t\tfor (int i=0;i<certkey.length;i++) {\n\t\t\t\tobj[i] = new sslcertkey();\n\t\t\t\tobj[i].set_certkey(certkey[i]);\n\t\t\t\tresponse[i] = (sslcertkey) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}",
"public static Object getObjectFromColumn(ResultSet rs, Integer jdbcType, int columnId)\r\n throws SQLException\r\n {\r\n return getObjectFromColumn(rs, null, jdbcType, null, columnId);\r\n }",
"protected void setupRegistration() {\n if (isServiceWorkerSupported()) {\n Navigator.serviceWorker.register(getResource()).then(object -> {\n logger.info(\"Service worker has been successfully registered\");\n registration = (ServiceWorkerRegistration) object;\n\n onRegistered(new ServiceEvent(), registration);\n\n // Observe service worker lifecycle\n observeLifecycle(registration);\n\n // Setup Service Worker events events\n setupOnControllerChangeEvent();\n setupOnMessageEvent();\n setupOnErrorEvent();\n return null;\n }, error -> {\n logger.info(\"ServiceWorker registration failed: \" + error);\n return null;\n });\n } else {\n logger.info(\"Service worker is not supported by this browser.\");\n }\n }",
"public static final Date getTime(byte[] data, int offset)\n {\n int time = getShort(data, offset) / 10;\n Calendar cal = DateHelper.popCalendar(EPOCH_DATE);\n cal.set(Calendar.HOUR_OF_DAY, (time / 60));\n cal.set(Calendar.MINUTE, (time % 60));\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MILLISECOND, 0);\n DateHelper.pushCalendar(cal);\n return (cal.getTime());\n }",
"public Object remove(String name) {\n\t\tThreadScopeContext context = ThreadScopeContextHolder.getContext();\n\t\treturn context.remove(name);\n\t}",
"public Release rollback(String appName, String releaseUuid) {\n return connection.execute(new Rollback(appName, releaseUuid), apiKey);\n }"
] |
Converts B and X into block matrices and calls the block matrix solve routine.
@param B A matrix ℜ <sup>m × p</sup>. Not modified.
@param X A matrix ℜ <sup>n × p</sup>, where the solution is written to. Modified. | [
"@Override\n public void solve(DMatrixRMaj B, DMatrixRMaj X) {\n X.reshape(blockA.numCols,B.numCols);\n blockB.reshape(B.numRows,B.numCols,false);\n blockX.reshape(X.numRows,X.numCols,false);\n MatrixOps_DDRB.convert(B,blockB);\n\n alg.solve(blockB,blockX);\n\n MatrixOps_DDRB.convert(blockX,X);\n }"
] | [
"private String getCurrencyFormat(CurrencySymbolPosition position)\n {\n String result;\n\n switch (position)\n {\n case AFTER:\n {\n result = \"1.1#\";\n break;\n }\n\n case AFTER_WITH_SPACE:\n {\n result = \"1.1 #\";\n break;\n }\n\n case BEFORE_WITH_SPACE:\n {\n result = \"# 1.1\";\n break;\n }\n\n default:\n case BEFORE:\n {\n result = \"#1.1\";\n break;\n }\n }\n\n return result;\n }",
"private static int abs(int a) {\n if(a >= 0)\n return a;\n else if(a != Integer.MIN_VALUE)\n return -a;\n return Integer.MAX_VALUE;\n }",
"public static File guessKeyRingFile() throws FileNotFoundException {\n final Collection<String> possibleLocations = getKnownPGPSecureRingLocations();\n for (final String location : possibleLocations) {\n final File candidate = new File(location);\n if (candidate.exists()) {\n return candidate;\n }\n }\n final StringBuilder message = new StringBuilder(\"Could not locate secure keyring, locations tried: \");\n final Iterator<String> it = possibleLocations.iterator();\n while (it.hasNext()) {\n message.append(it.next());\n if (it.hasNext()) {\n message.append(\", \");\n }\n }\n throw new FileNotFoundException(message.toString());\n }",
"public String urlEncode(String s) {\n if (s == null || s.isEmpty()) {\n return s;\n }\n\n return URL.encodeQueryString(s);\n }",
"public void drawImage(Image img, Rectangle rect, Rectangle clipRect) {\n\t\tdrawImage(img, rect, clipRect, 1);\n\t}",
"private Calendar cleanHistCalendar(Calendar cal) {\n cal.set(Calendar.MILLISECOND, 0);\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MINUTE, 0);\n cal.set(Calendar.HOUR, 0);\n return cal;\n }",
"protected long getUniqueLong(FieldDescriptor field) throws SequenceManagerException\r\n {\r\n boolean needsCommit = false;\r\n long result = 0;\r\n /*\r\n arminw:\r\n use the associated broker instance, check if broker was in tx or\r\n we need to commit used connection.\r\n */\r\n PersistenceBroker targetBroker = getBrokerForClass();\r\n if(!targetBroker.isInTransaction())\r\n {\r\n targetBroker.beginTransaction();\r\n needsCommit = true;\r\n }\r\n try\r\n {\r\n // lookup sequence name\r\n String sequenceName = calculateSequenceName(field);\r\n try\r\n {\r\n result = buildNextSequence(targetBroker, field.getClassDescriptor(), sequenceName);\r\n /*\r\n if 0 was returned we assume that the stored procedure\r\n did not work properly.\r\n */\r\n if (result == 0)\r\n {\r\n throw new SequenceManagerException(\"No incremented value retrieved\");\r\n }\r\n }\r\n catch (Exception e)\r\n {\r\n // maybe the sequence was not created\r\n log.info(\"Could not grab next key, message was \" + e.getMessage() +\r\n \" - try to write a new sequence entry to database\");\r\n try\r\n {\r\n // on create, make sure to get the max key for the table first\r\n long maxKey = SequenceManagerHelper.getMaxForExtent(targetBroker, field);\r\n createSequence(targetBroker, field, sequenceName, maxKey);\r\n }\r\n catch (Exception e1)\r\n {\r\n String eol = SystemUtils.LINE_SEPARATOR;\r\n throw new SequenceManagerException(eol + \"Could not grab next id, failed with \" + eol +\r\n e.getMessage() + eol + \"Creation of new sequence failed with \" +\r\n eol + e1.getMessage() + eol, e1);\r\n }\r\n try\r\n {\r\n result = buildNextSequence(targetBroker, field.getClassDescriptor(), sequenceName);\r\n }\r\n catch (Exception e1)\r\n {\r\n throw new SequenceManagerException(\"Could not grab next id although a sequence seems to exist\", e);\r\n }\r\n }\r\n }\r\n finally\r\n {\r\n if(targetBroker != null && needsCommit)\r\n {\r\n targetBroker.commitTransaction();\r\n }\r\n }\r\n return result;\r\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 }",
"private FilePath copyClassWorldsFile(FilePath ws, URL resource) {\n try {\n FilePath remoteClassworlds =\n ws.createTextTempFile(\"classworlds\", \"conf\", \"\");\n remoteClassworlds.copyFrom(resource);\n return remoteClassworlds;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }"
] |
Make a composite filter from the given sub-filters using AND to combine filters. | [
"public static Filter.Builder makeAndFilter(Iterable<Filter> subfilters) {\n return Filter.newBuilder()\n .setCompositeFilter(CompositeFilter.newBuilder()\n .addAllFilters(subfilters)\n .setOp(CompositeFilter.Operator.AND));\n }"
] | [
"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 boolean hasAnnotation(Method method, Class<? extends Annotation> annotation) {\n return !searchForAnnotation(method, annotation).isEmpty();\n }",
"public final void notifyContentItemRemoved(int position) {\n if (position < 0 || position >= contentItemCount) {\n throw new IndexOutOfBoundsException(\"The given position \" + position\n + \" is not within the position bounds for content items [0 - \"\n + (contentItemCount - 1) + \"].\");\n }\n notifyItemRemoved(position + headerItemCount);\n }",
"public static appqoepolicy[] get(nitro_service service) throws Exception{\n\t\tappqoepolicy obj = new appqoepolicy();\n\t\tappqoepolicy[] response = (appqoepolicy[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"private String searchForPersistentSubType(XClass type)\r\n {\r\n ArrayList queue = new ArrayList();\r\n XClass subType;\r\n\r\n queue.add(type);\r\n while (!queue.isEmpty())\r\n {\r\n subType = (XClass)queue.get(0);\r\n queue.remove(0);\r\n if (_model.hasClass(subType.getQualifiedName()))\r\n {\r\n return subType.getQualifiedName();\r\n }\r\n addDirectSubTypes(subType, queue);\r\n }\r\n return null;\r\n }",
"static Project convert(\n String name, com.linecorp.centraldogma.server.storage.project.Project project) {\n return new Project(name);\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 }",
"protected void\t\tcalcWorld(Bone bone, int parentId)\n {\n getWorldMatrix(parentId, mTempMtxB); // WorldMatrix (parent) TempMtxB\n mTempMtxB.mul(bone.LocalMatrix); // WorldMatrix = WorldMatrix(parent) * LocalMatrix\n bone.WorldMatrix.set(mTempMtxB);\n }",
"public String convert(BufferedImage image, boolean favicon) {\n // Reset statistics before anything\n statsArray = new int[12];\n // Begin the timer\n dStart = System.nanoTime();\n // Scale the image\n image = scale(image, favicon);\n // The +1 is for the newline characters\n StringBuilder sb = new StringBuilder((image.getWidth() + 1) * image.getHeight());\n\n for (int y = 0; y < image.getHeight(); y++) {\n // At the end of each line, add a newline character\n if (sb.length() != 0) sb.append(\"\\n\");\n for (int x = 0; x < image.getWidth(); x++) {\n //\n Color pixelColor = new Color(image.getRGB(x, y), true);\n int alpha = pixelColor.getAlpha();\n boolean isTransient = alpha < 0.1;\n double gValue = isTransient ? 250 : ((double) pixelColor.getRed() * 0.2989 + (double) pixelColor.getBlue() * 0.5870 + (double) pixelColor.getGreen() * 0.1140) / ((double)alpha / (double)250);\n final char s = gValue < 130 ? darkGrayScaleMap(gValue) : lightGrayScaleMap(gValue);\n sb.append(s);\n }\n }\n imgArray = sb.toString().toCharArray();\n dEnd = System.nanoTime();\n return sb.toString();\n }"
] |
Increases the maximum size of the data array so that it can store sparse data up to 'length'. The class
parameter nz_length is not modified by this function call.
@param arrayLength Desired maximum length of sparse data
@param preserveValue If true the old values will be copied into the new arrays. If false that step will be skipped. | [
"public void growMaxLength( int arrayLength , boolean preserveValue ) {\n if( arrayLength < 0 )\n throw new IllegalArgumentException(\"Negative array length. Overflow?\");\n // see if multiplying numRows*numCols will cause an overflow. If it won't then pick the smaller of the two\n if( numRows != 0 && numCols <= Integer.MAX_VALUE / numRows ) {\n // save the user from themselves\n arrayLength = Math.min(numRows*numCols, arrayLength);\n }\n if( nz_values == null || arrayLength > this.nz_values.length ) {\n double[] data = new double[ arrayLength ];\n int[] row_idx = new int[ arrayLength ];\n\n if( preserveValue ) {\n if( nz_values == null )\n throw new IllegalArgumentException(\"Can't preserve values when uninitialized\");\n System.arraycopy(this.nz_values, 0, data, 0, this.nz_length);\n System.arraycopy(this.nz_rows, 0, row_idx, 0, this.nz_length);\n }\n\n this.nz_values = data;\n this.nz_rows = row_idx;\n }\n }"
] | [
"private boolean canSuccessorProceed() {\n\n if (predecessor != null && !predecessor.canSuccessorProceed()) {\n return false;\n }\n\n synchronized (this) {\n while (responseCount < groups.size()) {\n try {\n wait();\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n return false;\n }\n }\n return !failed;\n }\n }",
"public static <T> ManagedBean<T> of(BeanAttributes<T> attributes, EnhancedAnnotatedType<T> clazz, BeanManagerImpl beanManager) {\n return new ManagedBean<T>(attributes, clazz, createId(attributes, clazz), beanManager);\n }",
"public static DatagramPacket buildPacket(PacketType type, ByteBuffer deviceName, ByteBuffer payload) {\n ByteBuffer content = ByteBuffer.allocate(0x1f + payload.remaining());\n content.put(getMagicHeader());\n content.put(type.protocolValue);\n content.put(deviceName);\n content.put(payload);\n return new DatagramPacket(content.array(), content.capacity());\n }",
"public PhotoList<Photo> getClusterPhotos(String tag, String clusterId) throws FlickrException {\n\n PhotoList<Photo> photos = new PhotoList<Photo>();\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_CLUSTER_PHOTOS);\n\n parameters.put(\"tag\", tag);\n parameters.put(\"cluster_id\", clusterId);\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 photosElement = response.getPayload();\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\n photos.setPage(\"1\");\n photos.setPages(\"1\");\n photos.setPerPage(\"\" + photoNodes.getLength());\n photos.setTotal(\"\" + photoNodes.getLength());\n for (int i = 0; i < photoNodes.getLength(); i++) {\n Element photoElement = (Element) photoNodes.item(i);\n photos.add(PhotoUtils.createPhoto(photoElement));\n }\n return photos;\n }",
"public Operation.Info create( char op , Variable input ) {\n switch( op ) {\n case '\\'':\n return Operation.transpose(input, managerTemp);\n\n default:\n throw new RuntimeException(\"Unknown operation \" + op);\n }\n }",
"static void onActivityCreated(Activity activity) {\n // make sure we have at least the default instance created here.\n if (instances == null) {\n CleverTapAPI.createInstanceIfAvailable(activity, null);\n }\n\n if (instances == null) {\n Logger.v(\"Instances is null in onActivityCreated!\");\n return;\n }\n\n boolean alreadyProcessedByCleverTap = false;\n Bundle notification = null;\n Uri deepLink = null;\n String _accountId = null;\n\n // check for launch deep link\n try {\n Intent intent = activity.getIntent();\n deepLink = intent.getData();\n if (deepLink != null) {\n Bundle queryArgs = UriHelper.getAllKeyValuePairs(deepLink.toString(), true);\n _accountId = queryArgs.getString(Constants.WZRK_ACCT_ID_KEY);\n }\n } catch (Throwable t) {\n // Ignore\n }\n\n // check for launch via notification click\n try {\n notification = activity.getIntent().getExtras();\n if (notification != null && !notification.isEmpty()) {\n try {\n alreadyProcessedByCleverTap = (notification.containsKey(Constants.WZRK_FROM_KEY) && Constants.WZRK_FROM.equals(notification.get(Constants.WZRK_FROM_KEY)));\n if (alreadyProcessedByCleverTap){\n Logger.v(\"ActivityLifecycleCallback: Notification Clicked already processed for \"+ notification.toString() +\", dropping duplicate.\");\n }\n if (notification.containsKey(Constants.WZRK_ACCT_ID_KEY)) {\n _accountId = (String) notification.get(Constants.WZRK_ACCT_ID_KEY);\n }\n } catch (Throwable t) {\n // no-op\n }\n }\n } catch (Throwable t) {\n // Ignore\n }\n\n if (alreadyProcessedByCleverTap && deepLink == null) return;\n\n for (String accountId: CleverTapAPI.instances.keySet()) {\n CleverTapAPI instance = CleverTapAPI.instances.get(accountId);\n\n boolean shouldProcess = false;\n if (instance != null) {\n shouldProcess = (_accountId == null && instance.config.isDefaultInstance()) || instance.getAccountId().equals(_accountId);\n }\n\n if (shouldProcess) {\n if (notification != null && !notification.isEmpty() && notification.containsKey(Constants.NOTIFICATION_TAG)) {\n instance.pushNotificationClickedEvent(notification);\n }\n\n if (deepLink != null) {\n try {\n instance.pushDeepLink(deepLink);\n } catch (Throwable t) {\n // no-op\n }\n }\n break;\n }\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 static <K, V> QueuedKeyedResourcePool<K, V> create(ResourceFactory<K, V> factory,\n ResourcePoolConfig config) {\n return new QueuedKeyedResourcePool<K, V>(factory, config);\n }",
"public long removeRangeByLex(final LexRange lexRange) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.zremrangeByLex(getKey(), lexRange.from(), lexRange.to());\n }\n });\n }"
] |
Get the original image URL.
@return The original image URL | [
"public String getOriginalUrl() throws FlickrException {\r\n if (originalSize == null) {\r\n if (originalFormat != null) {\r\n return getOriginalBaseImageUrl() + \"_o.\" + originalFormat;\r\n }\r\n return getOriginalBaseImageUrl() + DEFAULT_ORIGINAL_IMAGE_SUFFIX;\r\n } else {\r\n return originalSize.getSource();\r\n }\r\n }"
] | [
"public List<Message> requestArtistMenuFrom(final SlotReference slotReference, final int sortOrder)\n throws Exception {\n\n ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {\n @Override\n public List<Message> useClient(Client client) throws Exception {\n if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) {\n try {\n logger.debug(\"Requesting Artist menu.\");\n Message response = client.menuRequest(Message.KnownType.ARTIST_MENU_REQ, Message.MenuIdentifier.MAIN_MENU, slotReference.slot,\n new NumberField(sortOrder));\n return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response);\n } finally {\n client.unlockForMenuOperations();\n }\n } else {\n throw new TimeoutException(\"Unable to lock player for menu operations.\");\n }\n }\n };\n\n return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, \"requesting artist menu\");\n }",
"public Object putNodeMetaData(Object key, Object value) {\n if (key == null) throw new GroovyBugError(\"Tried to set meta data with null key on \" + this + \".\");\n if (metaDataMap == null) {\n metaDataMap = new ListHashMap();\n }\n return metaDataMap.put(key, value);\n }",
"protected final String computeId(\n final ITemplateContext context,\n final IProcessableElementTag tag,\n final String name, final boolean sequence) {\n\n String id = tag.getAttributeValue(this.idAttributeDefinition.getAttributeName());\n if (!org.thymeleaf.util.StringUtils.isEmptyOrWhitespace(id)) {\n return (StringUtils.hasText(id) ? id : null);\n }\n\n id = FieldUtils.idFromName(name);\n if (sequence) {\n final Integer count = context.getIdentifierSequences().getAndIncrementIDSeq(id);\n return id + count.toString();\n }\n return id;\n\n }",
"public void startup() throws InterruptedException {\n final int maxCacheConnectionPerThread = serverConfig.getMaxConnections() / processors.length;\n logger.debug(\"start {} Processor threads\",processors.length);\n for (int i = 0; i < processors.length; i++) {\n processors[i] = new Processor(handlerFactory, stats, maxRequestSize, maxCacheConnectionPerThread);\n Utils.newThread(\"jafka-processor-\" + i, processors[i], false).start();\n }\n Utils.newThread(\"jafka-acceptor\", acceptor, false).start();\n acceptor.awaitStartup();\n }",
"public void ifPropertyValueEquals(String template, Properties attributes) throws XDocletException\r\n {\r\n String value = getPropertyValue(attributes.getProperty(ATTRIBUTE_LEVEL), attributes.getProperty(ATTRIBUTE_NAME));\r\n String expected = attributes.getProperty(ATTRIBUTE_VALUE);\r\n\r\n if (value == null)\r\n {\r\n value = attributes.getProperty(ATTRIBUTE_DEFAULT);\r\n }\r\n if (expected.equals(value))\r\n {\r\n generate(template);\r\n }\r\n }",
"public final Set<String> getOutputFormatsNames() {\n SortedSet<String> formats = new TreeSet<>();\n for (String formatBeanName: this.outputFormat.keySet()) {\n int endingIndex = formatBeanName.indexOf(MAP_OUTPUT_FORMAT_BEAN_NAME_ENDING);\n if (endingIndex < 0) {\n endingIndex = formatBeanName.indexOf(OUTPUT_FORMAT_BEAN_NAME_ENDING);\n }\n formats.add(formatBeanName.substring(0, endingIndex));\n }\n return formats;\n }",
"public List<Release> listReleases(String appName) {\n return connection.execute(new ReleaseList(appName), apiKey);\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 void generateReport(List<XmlSuite> xmlSuites,\n List<ISuite> suites,\n String outputDirectoryName)\n {\n removeEmptyDirectories(new File(outputDirectoryName));\n \n boolean useFrames = System.getProperty(FRAMES_PROPERTY, \"true\").equals(\"true\");\n boolean onlyFailures = System.getProperty(ONLY_FAILURES_PROPERTY, \"false\").equals(\"true\");\n\n File outputDirectory = new File(outputDirectoryName, REPORT_DIRECTORY);\n outputDirectory.mkdirs();\n\n try\n {\n if (useFrames)\n {\n createFrameset(outputDirectory);\n }\n createOverview(suites, outputDirectory, !useFrames, onlyFailures);\n createSuiteList(suites, outputDirectory, onlyFailures);\n createGroups(suites, outputDirectory);\n createResults(suites, outputDirectory, onlyFailures);\n createLog(outputDirectory, onlyFailures);\n copyResources(outputDirectory);\n }\n catch (Exception ex)\n {\n throw new ReportNGException(\"Failed generating HTML report.\", ex);\n }\n }"
] |
Fills the Boyer Moore "bad character array" for the given pattern | [
"private static void computeBadByteSkipArray(byte[] pattern, int[] badByteArray) {\n for (int a = 0; a < ALPHABET_SIZE; a++) {\n badByteArray[a] = pattern.length;\n }\n\n for (int j = 0; j < pattern.length - 1; j++) {\n badByteArray[pattern[j] - Byte.MIN_VALUE] = pattern.length - j - 1;\n }\n }"
] | [
"public static void setPropertySafely(Marshaller marshaller, String name, Object value) {\n try {\n marshaller.setProperty(name, value);\n } catch (PropertyException e) {\n LOGGER.warn(String.format(\"Can't set \\\"%s\\\" property to given marshaller\", name), e);\n }\n }",
"public double Function1D(double x) {\n double frequency = initFrequency;\n double amplitude = initAmplitude;\n double sum = 0;\n\n // octaves\n for (int i = 0; i < octaves; i++) {\n sum += SmoothedNoise(x * frequency) * amplitude;\n\n frequency *= 2;\n amplitude *= persistence;\n }\n return sum;\n }",
"public static ServiceController<DeploymentScanner> addService(final OperationContext context, final PathAddress resourceAddress, final String relativeTo, final String path,\n final int scanInterval, TimeUnit unit, final boolean autoDeployZip,\n final boolean autoDeployExploded, final boolean autoDeployXml, final boolean scanEnabled, final long deploymentTimeout, boolean rollbackOnRuntimeFailure,\n final FileSystemDeploymentService bootTimeService, final ScheduledExecutorService scheduledExecutorService) {\n final DeploymentScannerService service = new DeploymentScannerService(resourceAddress, relativeTo, path, scanInterval, unit, autoDeployZip,\n autoDeployExploded, autoDeployXml, scanEnabled, deploymentTimeout, rollbackOnRuntimeFailure, bootTimeService);\n final ServiceName serviceName = getServiceName(resourceAddress.getLastElement().getValue());\n service.scheduledExecutorValue.inject(scheduledExecutorService);\n final ServiceBuilder<DeploymentScanner> sb = context.getServiceTarget().addService(serviceName, service);\n sb.addDependency(context.getCapabilityServiceName(PATH_MANAGER_CAPABILITY, PathManager.class), PathManager.class, service.pathManagerValue);\n sb.addDependency(context.getCapabilityServiceName(\"org.wildfly.management.notification-handler-registry\", null),\n NotificationHandlerRegistry.class, service.notificationRegistryValue);\n sb.addDependency(context.getCapabilityServiceName(\"org.wildfly.management.model-controller-client-factory\", null),\n ModelControllerClientFactory.class, service.clientFactoryValue);\n sb.requires(org.jboss.as.server.deployment.Services.JBOSS_DEPLOYMENT_CHAINS);\n sb.addDependency(ControlledProcessStateService.SERVICE_NAME, ControlledProcessStateService.class, service.controlledProcessStateServiceValue);\n return sb.install();\n }",
"public static String getParentDirectory(String filePath) throws IllegalArgumentException {\n if (Pattern.matches(sPatternUrl, filePath))\n return getURLParentDirectory(filePath);\n\n return new File(filePath).getParent();\n }",
"public static TaskField getMpxjField(int value)\n {\n TaskField result = null;\n\n if (value >= 0 && value < MPX_MPXJ_ARRAY.length)\n {\n result = MPX_MPXJ_ARRAY[value];\n }\n\n return (result);\n }",
"protected static Map<Double, Double> doQuantization(double max,\n double min,\n double[] values)\n {\n double range = max - min;\n int noIntervals = 20;\n double intervalSize = range / noIntervals;\n int[] intervals = new int[noIntervals];\n for (double value : values)\n {\n int interval = Math.min(noIntervals - 1,\n (int) Math.floor((value - min) / intervalSize));\n assert interval >= 0 && interval < noIntervals : \"Invalid interval: \" + interval;\n ++intervals[interval];\n }\n Map<Double, Double> discretisedValues = new HashMap<Double, Double>();\n for (int i = 0; i < intervals.length; i++)\n {\n // Correct the value to take into account the size of the interval.\n double value = (1 / intervalSize) * (double) intervals[i];\n discretisedValues.put(min + ((i + 0.5) * intervalSize), value);\n }\n return discretisedValues;\n }",
"public void recordGetAllTime(long timeNS,\n int requested,\n int returned,\n long totalValueBytes,\n long totalKeyBytes) {\n recordTime(Tracked.GET_ALL,\n timeNS,\n requested - returned,\n totalValueBytes,\n totalKeyBytes,\n requested);\n }",
"public Info changeMessage(String newMessage) {\n Info newInfo = new Info();\n newInfo.setMessage(newMessage);\n\n URL url = COMMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"PUT\");\n request.setBody(newInfo.getPendingChanges());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonResponse = JsonObject.readFrom(response.getJSON());\n\n return new Info(jsonResponse);\n }",
"@Deprecated\n\tpublic static ScheduleInterface createScheduleFromConventions(\n\t\t\tLocalDate referenceDate,\n\t\t\tLocalDate startDate,\n\t\t\tString frequency,\n\t\t\tdouble maturity,\n\t\t\tString daycountConvention,\n\t\t\tString shortPeriodConvention\n\t\t\t)\n\t{\n\t\treturn createScheduleFromConventions(\n\t\t\t\treferenceDate,\n\t\t\t\tstartDate,\n\t\t\t\tfrequency,\n\t\t\t\tmaturity,\n\t\t\t\tdaycountConvention,\n\t\t\t\tshortPeriodConvention,\n\t\t\t\t\"UNADJUSTED\",\n\t\t\t\tnew BusinessdayCalendarAny(),\n\t\t\t\t0, 0);\n\t}"
] |
Sets number of pages. If the index of currently selected page is bigger than the total number
of pages, first page will be selected instead.
@return difference between the previous number of pages and new one. Negative value is
returned if new number of pages is less then it was before. | [
"public int setPageCount(final int num) {\n int diff = num - getCheckableCount();\n if (diff > 0) {\n addIndicatorChildren(diff);\n } else if (diff < 0) {\n removeIndicatorChildren(-diff);\n }\n if (mCurrentPage >=num ) {\n mCurrentPage = 0;\n }\n setCurrentPage(mCurrentPage);\n return diff;\n }"
] | [
"public static void validateObserverMethod(ObserverMethod<?> observerMethod, BeanManager beanManager, ObserverMethod<?> originalObserverMethod) {\n Set<Annotation> qualifiers = observerMethod.getObservedQualifiers();\n if (observerMethod.getBeanClass() == null) {\n throw EventLogger.LOG.observerMethodsMethodReturnsNull(\"getBeanClass\", observerMethod);\n }\n if (observerMethod.getObservedType() == null) {\n throw EventLogger.LOG.observerMethodsMethodReturnsNull(\"getObservedType\", observerMethod);\n }\n Bindings.validateQualifiers(qualifiers, beanManager, observerMethod, \"ObserverMethod.getObservedQualifiers\");\n if (observerMethod.getReception() == null) {\n throw EventLogger.LOG.observerMethodsMethodReturnsNull(\"getReception\", observerMethod);\n }\n if (observerMethod.getTransactionPhase() == null) {\n throw EventLogger.LOG.observerMethodsMethodReturnsNull(\"getTransactionPhase\", observerMethod);\n }\n if (originalObserverMethod != null && (!observerMethod.getBeanClass().equals(originalObserverMethod.getBeanClass()))) {\n throw EventLogger.LOG.beanClassMismatch(originalObserverMethod, observerMethod);\n }\n if (!(observerMethod instanceof SyntheticObserverMethod) && !hasNotifyOverriden(observerMethod.getClass(), observerMethod)) {\n throw EventLogger.LOG.notifyMethodNotImplemented(observerMethod);\n }\n }",
"public 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 }",
"boolean undoChanges() {\n final State state = stateUpdater.getAndSet(this, State.ROLLBACK_ONLY);\n if (state == State.COMPLETED || state == State.ROLLBACK_ONLY) {\n // Was actually completed already\n return false;\n }\n PatchingTaskContext.Mode currentMode = this.mode;\n mode = PatchingTaskContext.Mode.UNDO;\n final PatchContentLoader loader = PatchContentLoader.create(miscBackup, null, null);\n // Undo changes for the identity\n undoChanges(identityEntry, loader);\n // TODO maybe check if we need to do something for the layers too !?\n if (state == State.INVALIDATE || currentMode == PatchingTaskContext.Mode.ROLLBACK) {\n // For apply the state needs to be invalidate\n // For rollback the files are invalidated as part of the tasks\n final PatchingTaskContext.Mode mode = currentMode == PatchingTaskContext.Mode.APPLY ? PatchingTaskContext.Mode.ROLLBACK : PatchingTaskContext.Mode.APPLY;\n for (final File file : moduleInvalidations) {\n try {\n PatchModuleInvalidationUtils.processFile(this, file, mode);\n } catch (Exception e) {\n PatchLogger.ROOT_LOGGER.debugf(e, \"failed to restore state for %s\", file);\n }\n }\n if(!modulesToReenable.isEmpty()) {\n for (final File file : modulesToReenable) {\n try {\n PatchModuleInvalidationUtils.processFile(this, file, PatchingTaskContext.Mode.APPLY);\n } catch (Exception e) {\n PatchLogger.ROOT_LOGGER.debugf(e, \"failed to restore state for %s\", file);\n }\n }\n }\n if(!modulesToDisable.isEmpty()) {\n for (final File file : modulesToDisable) {\n try {\n PatchModuleInvalidationUtils.processFile(this, file, PatchingTaskContext.Mode.ROLLBACK);\n } catch (Exception e) {\n PatchLogger.ROOT_LOGGER.debugf(e, \"failed to restore state for %s\", file);\n }\n }\n }\n }\n return true;\n }",
"@Override\n public final boolean getBool(final int i) {\n try {\n return this.array.getBoolean(i);\n } catch (JSONException e) {\n throw new ObjectMissingException(this, \"[\" + i + \"]\");\n }\n }",
"public static clusterinstance get(nitro_service service, Long clid) throws Exception{\n\t\tclusterinstance obj = new clusterinstance();\n\t\tobj.set_clid(clid);\n\t\tclusterinstance response = (clusterinstance) obj.get_resource(service);\n\t\treturn response;\n\t}",
"static GVRPerspectiveCamera makePerspShadowCamera(GVRPerspectiveCamera centerCam, float coneAngle)\n {\n GVRPerspectiveCamera camera = new GVRPerspectiveCamera(centerCam.getGVRContext());\n float near = centerCam.getNearClippingDistance();\n float far = centerCam.getFarClippingDistance();\n\n camera.setNearClippingDistance(near);\n camera.setFarClippingDistance(far);\n camera.setFovY((float) Math.toDegrees(coneAngle));\n camera.setAspectRatio(1.0f);\n return camera;\n }",
"@SuppressWarnings({\"WeakerAccess\"})\n protected void initDeviceID() {\n getDeviceCachedInfo(); // put this here to avoid running on main thread\n\n // generate a provisional while we do the rest async\n generateProvisionalGUID();\n // grab and cache the googleAdID in any event if available\n // if we already have a deviceID we won't user ad id as the guid\n cacheGoogleAdID();\n\n // if we already have a device ID use it and just notify\n // otherwise generate one, either from ad id if available or the provisional\n String deviceID = getDeviceID();\n if (deviceID == null || deviceID.trim().length() <= 2) {\n generateDeviceID();\n }\n\n }",
"public void remove(IConverter converter, Object sourceObject,\n\t\t\tTypeReference<?> destinationType) {\n\t\tconvertedObjects.remove(new ConvertedObjectsKey(converter,\n\t\t\t\tsourceObject, destinationType));\n\t}",
"public ApnsServiceBuilder withDelegate(ApnsDelegate delegate) {\n this.delegate = delegate == null ? ApnsDelegate.EMPTY : delegate;\n return this;\n }"
] |
Formats a logging event to a writer.
@param event
logging event to be formatted. | [
"public String format(final LoggingEvent event) {\n\t\tfinal StringBuffer buf = new StringBuffer();\n\t\tfor (PatternConverter c = head; c != null; c = c.next) {\n\t\t\tc.format(buf, event);\n\t\t}\n\t\treturn buf.toString();\n\t}"
] | [
"private ModelNode resolveSubsystems(final List<ModelNode> extensions) {\n\n HostControllerLogger.ROOT_LOGGER.debug(\"Applying extensions provided by master\");\n final ModelNode result = operationExecutor.installSlaveExtensions(extensions);\n if (!SUCCESS.equals(result.get(OUTCOME).asString())) {\n throw HostControllerLogger.ROOT_LOGGER.failedToAddExtensions(result.get(FAILURE_DESCRIPTION));\n }\n final ModelNode subsystems = new ModelNode();\n for (final ModelNode extension : extensions) {\n extensionRegistry.recordSubsystemVersions(extension.asString(), subsystems);\n }\n return subsystems;\n }",
"static boolean uninstall() {\n boolean uninstalled = false;\n synchronized (lock) {\n if (locationCollectionClient != null) {\n locationCollectionClient.locationEngineController.onDestroy();\n locationCollectionClient.settingsChangeHandlerThread.quit();\n locationCollectionClient.sharedPreferences.unregisterOnSharedPreferenceChangeListener(locationCollectionClient);\n locationCollectionClient = null;\n uninstalled = true;\n }\n }\n return uninstalled;\n }",
"public Object get(int dataSet) throws SerializationException {\r\n\t\tObject result = null;\r\n\t\tfor (Iterator<DataSet> i = dataSets.iterator(); i.hasNext();) {\r\n\t\t\tDataSet ds = i.next();\r\n\t\t\tDataSetInfo info = ds.getInfo();\r\n\t\t\tif (info.getDataSetNumber() == dataSet) {\r\n\t\t\t\tresult = getData(ds);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn result;\r\n\t}",
"public TokenList extractSubList( Token begin , Token end ) {\n if( begin == end ) {\n remove(begin);\n return new TokenList(begin,begin);\n } else {\n if( first == begin ) {\n first = end.next;\n }\n if( last == end ) {\n last = begin.previous;\n }\n if( begin.previous != null ) {\n begin.previous.next = end.next;\n }\n if( end.next != null ) {\n end.next.previous = begin.previous;\n }\n begin.previous = null;\n end.next = null;\n\n TokenList ret = new TokenList(begin,end);\n size -= ret.size();\n return ret;\n }\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 String toIPTC(SubjectReferenceSystem srs) {\r\n\t\tStringBuffer b = new StringBuffer();\r\n\t\tb.append(\"IPTC:\");\r\n\t\tb.append(getNumber());\r\n\t\tb.append(\":\");\r\n\t\tif (getNumber().endsWith(\"000000\")) {\r\n\t\t\tb.append(toIPTCHelper(srs.getName(this)));\r\n\t\t\tb.append(\"::\");\r\n\t\t} else if (getNumber().endsWith(\"000\")) {\r\n\t\t\tb.append(toIPTCHelper(srs.getName(srs.get(getNumber().substring(0, 2) + \"000000\"))));\r\n\t\t\tb.append(\":\");\r\n\t\t\tb.append(toIPTCHelper(srs.getName(this)));\r\n\t\t\tb.append(\":\");\r\n\t\t} else {\r\n\t\t\tb.append(toIPTCHelper(srs.getName(srs.get(getNumber().substring(0, 2) + \"000000\"))));\r\n\t\t\tb.append(\":\");\r\n\t\t\tb.append(toIPTCHelper(srs.getName(srs.get(getNumber().substring(0, 5) + \"000\"))));\r\n\t\t\tb.append(\":\");\r\n\t\t\tb.append(toIPTCHelper(srs.getName(this)));\r\n\t\t}\r\n\t\treturn b.toString();\r\n\t}",
"public ParallelTaskBuilder prepareHttpDelete(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n\n cb.getHttpMeta().setHttpMethod(HttpMethod.DELETE);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\n }",
"private void setRawDirection(SwipyRefreshLayoutDirection direction) {\n if (mDirection == direction) {\n return;\n }\n\n mDirection = direction;\n switch (mDirection) {\n case BOTTOM:\n mCurrentTargetOffsetTop = mOriginalOffsetTop = getMeasuredHeight();\n break;\n case TOP:\n default:\n mCurrentTargetOffsetTop = mOriginalOffsetTop = -mCircleView.getMeasuredHeight();\n break;\n }\n }",
"public static Collection<Field> getAllAttributes(final Class<?> classToInspect) {\n Set<Field> allFields = new HashSet<>();\n getAllAttributes(classToInspect, allFields, Function.identity(), field -> true);\n return allFields;\n }"
] |
Declares the internal data structures so that it can process matrices up to the specified size.
@param maxRows
@param maxCols | [
"public void declareInternalData(int maxRows, int maxCols) {\n this.maxRows = maxRows;\n this.maxCols = maxCols;\n\n U_tran = new DMatrixRMaj(maxRows,maxRows);\n Qm = new DMatrixRMaj(maxRows,maxRows);\n\n r_row = new double[ maxCols ];\n }"
] | [
"public <T> T invokeWithClientSession(int targetPlayer, ClientTask<T> task, String description)\n throws Exception {\n if (!isRunning()) {\n throw new IllegalStateException(\"ConnectionManager is not running, aborting \" + description);\n }\n\n final Client client = allocateClient(targetPlayer, description);\n try {\n return task.useClient(client);\n } finally {\n freeClient(client);\n }\n }",
"public static base_responses update(nitro_service client, responderpolicy resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tresponderpolicy updateresources[] = new responderpolicy[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new responderpolicy();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].rule = resources[i].rule;\n\t\t\t\tupdateresources[i].action = resources[i].action;\n\t\t\t\tupdateresources[i].undefaction = resources[i].undefaction;\n\t\t\t\tupdateresources[i].comment = resources[i].comment;\n\t\t\t\tupdateresources[i].logaction = resources[i].logaction;\n\t\t\t\tupdateresources[i].appflowaction = resources[i].appflowaction;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public static String[] sortStringArray(String[] array) {\n if (isEmpty(array)) {\n return new String[0];\n }\n Arrays.sort(array);\n return array;\n }",
"public static base_response delete(nitro_service client, String network) throws Exception {\n\t\troute6 deleteresource = new route6();\n\t\tdeleteresource.network = network;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"private FieldDescriptor getFldFromJoin(TableAlias aTableAlias, String aColName)\r\n {\r\n FieldDescriptor fld = null;\r\n\r\n // Search Join Structure for attribute\r\n if (aTableAlias.joins != null)\r\n {\r\n Iterator itr = aTableAlias.joins.iterator();\r\n while (itr.hasNext())\r\n {\r\n Join join = (Join) itr.next();\r\n ClassDescriptor cld = join.right.cld;\r\n\r\n if (cld != null)\r\n {\r\n fld = cld.getFieldDescriptorByName(aColName);\r\n if (fld != null)\r\n {\r\n break;\r\n }\r\n\r\n }\r\n }\r\n }\r\n return fld;\r\n }",
"public static Artifact withVersion(Version v)\n {\n Artifact artifact = new Artifact();\n artifact.version = v;\n return artifact;\n }",
"protected void\t\tcalcWorld(Bone bone, int parentId)\n {\n getWorldMatrix(parentId, mTempMtxB); // WorldMatrix (parent) TempMtxB\n mTempMtxB.mul(bone.LocalMatrix); // WorldMatrix = WorldMatrix(parent) * LocalMatrix\n bone.WorldMatrix.set(mTempMtxB);\n }",
"ValidationResult cleanObjectKey(String name) {\n ValidationResult vr = new ValidationResult();\n name = name.trim();\n for (String x : objectKeyCharsNotAllowed)\n name = name.replace(x, \"\");\n\n if (name.length() > Constants.MAX_KEY_LENGTH) {\n name = name.substring(0, Constants.MAX_KEY_LENGTH-1);\n vr.setErrorDesc(name.trim() + \"... exceeds the limit of \"+ Constants.MAX_KEY_LENGTH + \" characters. Trimmed\");\n vr.setErrorCode(520);\n }\n\n vr.setObject(name.trim());\n\n return vr;\n }",
"public boolean contains(Color color) {\n return exists(p -> p.toInt() == color.toPixel().toInt());\n }"
] |
Adds the class descriptor to this model.
@param classDef The class descriptor
@return The class descriptor or <code>null</code> if there is no such class in this model | [
"public void addClass(ClassDescriptorDef classDef)\r\n {\r\n classDef.setOwner(this);\r\n // Regardless of the format of the class name, we're using the fully qualified format\r\n // This is safe because of the package & class naming constraints of the Java language\r\n _classDefs.put(classDef.getQualifiedName(), classDef);\r\n }"
] | [
"private Set<Artifact> findThriftDependencies() throws IOException, MojoExecutionException {\n Set<Artifact> thriftDependencies = new HashSet<Artifact>();\n\n Set<Artifact> deps = new HashSet<Artifact>();\n deps.addAll(project.getArtifacts());\n deps.addAll(project.getDependencyArtifacts());\n\n Map<String, Artifact> depsMap = new HashMap<String, Artifact>();\n for (Artifact dep : deps) {\n depsMap.put(dep.getId(), dep);\n }\n\n for (Artifact artifact : deps) {\n // This artifact has an idl classifier.\n if (isIdlCalssifier(artifact, classifier)) {\n thriftDependencies.add(artifact);\n } else {\n if (isDepOfIdlArtifact(artifact, depsMap)) {\n // Fetch idl artifact for dependency of an idl artifact.\n try {\n Artifact idlArtifact = MavenScroogeCompilerUtil.getIdlArtifact(\n artifact,\n artifactFactory,\n artifactResolver,\n localRepository,\n remoteArtifactRepositories,\n classifier);\n thriftDependencies.add(idlArtifact);\n } catch (MojoExecutionException e) {\n /* Do nothing as this artifact is not an idl artifact\n binary jars may have dependency on thrift lib etc.\n */\n getLog().debug(\"Could not fetch idl jar for \" + artifact);\n }\n }\n }\n }\n return thriftDependencies;\n }",
"public static sslaction[] get(nitro_service service) throws Exception{\n\t\tsslaction obj = new sslaction();\n\t\tsslaction[] response = (sslaction[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"private String fixSpecials(final String inString) {\n\t\tStringBuilder tmp = new StringBuilder();\n\n\t\tfor (int i = 0; i < inString.length(); i++) {\n\t\t\tchar chr = inString.charAt(i);\n\n\t\t\tif (isSpecial(chr)) {\n\t\t\t\ttmp.append(this.escape);\n\t\t\t\ttmp.append(chr);\n\t\t\t} else {\n\t\t\t\ttmp.append(chr);\n\t\t\t}\n\t\t}\n\n\t\treturn tmp.toString();\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}",
"private void writeProjectProperties()\n {\n ProjectProperties properties = m_projectFile.getProjectProperties();\n\n m_plannerProject.setCompany(properties.getCompany());\n m_plannerProject.setManager(properties.getManager());\n m_plannerProject.setName(getString(properties.getName()));\n m_plannerProject.setProjectStart(getDateTime(properties.getStartDate()));\n m_plannerProject.setCalendar(getIntegerString(m_projectFile.getDefaultCalendar().getUniqueID()));\n m_plannerProject.setMrprojectVersion(\"2\");\n }",
"public void add(ResourceCollection rc) {\n if (rc instanceof FileSet) {\n FileSet fs = (FileSet) rc;\n fs.setProject(getProject());\n }\n resources.add(rc);\n }",
"public Matrix4f getFinalTransformMatrix()\n {\n final FloatBuffer fb = ByteBuffer.allocateDirect(4*4*4).order(ByteOrder.nativeOrder()).asFloatBuffer();\n NativeBone.getFinalTransformMatrix(getNative(), fb);\n return new Matrix4f(fb);\n }",
"public static LBuffer loadFrom(File file) throws IOException {\n FileChannel fin = new FileInputStream(file).getChannel();\n long fileSize = fin.size();\n if (fileSize > Integer.MAX_VALUE)\n throw new IllegalArgumentException(\"Cannot load from file more than 2GB: \" + file);\n LBuffer b = new LBuffer((int) fileSize);\n long pos = 0L;\n WritableChannelWrap ch = new WritableChannelWrap(b);\n while (pos < fileSize) {\n pos += fin.transferTo(0, fileSize, ch);\n }\n return b;\n }",
"private void deliverOnAirUpdate(Set<Integer> audibleChannels) {\n for (final OnAirListener listener : getOnAirListeners()) {\n try {\n listener.channelsOnAir(audibleChannels);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering channels on-air update to listener\", t);\n }\n }\n }"
] |
Converts days of the week into a bit field.
@param data recurring data
@return bit field | [
"private BigInteger getDaysOfTheWeek(RecurringData data)\n {\n int value = 0;\n for (Day day : Day.values())\n {\n if (data.getWeeklyDay(day))\n {\n value = value | DAY_MASKS[day.getValue()];\n }\n }\n return BigInteger.valueOf(value);\n }"
] | [
"public JsonNode wbSetAliases(String id, String site, String title,\n\t\t\tString newEntity, String language, List<String> add,\n\t\t\tList<String> remove, List<String> set,\n\t\t\tboolean bot, long baserevid, String summary)\n\t\t\t\t\tthrows IOException, MediaWikiApiErrorException {\n\t\tValidate.notNull(language,\n\t\t\t\t\"Language parameter cannot be null when setting aliases\");\n\t\t\n\t\tMap<String, String> parameters = new HashMap<String, String>();\n\t\tparameters.put(\"language\", language);\n\t\tif (set != null) {\n\t\t\tif (add != null || remove != null) {\n\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\"Cannot use parameters \\\"add\\\" or \\\"remove\\\" when using \\\"set\\\" to edit aliases\");\n\t\t\t}\n\t\t\tparameters.put(\"set\", ApiConnection.implodeObjects(set));\n\t\t}\n\t\tif (add != null) {\n\t\t\tparameters.put(\"add\", ApiConnection.implodeObjects(add));\n\t\t}\n\t\tif (remove != null) {\n\t\t\tparameters.put(\"remove\", ApiConnection.implodeObjects(remove));\n\t\t}\n\t\t\n\t\tJsonNode response = performAPIAction(\"wbsetaliases\", id, site, title, newEntity, parameters, summary, baserevid, bot);\n\t\treturn response;\n\t}",
"private void parseMacro( TokenList tokens , Sequence sequence ) {\n Macro macro = new Macro();\n\n TokenList.Token t = tokens.getFirst().next;\n\n if( t.word == null ) {\n throw new ParseError(\"Expected the macro's name after \"+tokens.getFirst().word);\n }\n List<TokenList.Token> variableTokens = new ArrayList<TokenList.Token>();\n\n macro.name = t.word;\n t = t.next;\n t = parseMacroInput(variableTokens, t);\n for( TokenList.Token a : variableTokens ) {\n if( a.word == null) throw new ParseError(\"expected word in macro header\");\n macro.inputs.add(a.word);\n }\n t = t.next;\n if( t == null || t.getSymbol() != Symbol.ASSIGN)\n throw new ParseError(\"Expected assignment\");\n t = t.next;\n macro.tokens = new TokenList(t,tokens.last);\n\n sequence.addOperation(macro.createOperation(macros));\n }",
"static List<List<String>> handleNewLines( List<List<String>> tableModel ) {\n List<List<String>> result = Lists.newArrayListWithExpectedSize( tableModel.size() );\n\n for( List<String> row : tableModel ) {\n if( hasNewline( row ) ) {\n result.addAll( splitRow( row ) );\n } else {\n result.add( row );\n }\n }\n\n return result;\n }",
"public static Dimension dimensionsToFit(Dimension target, Dimension source) {\n\n // if target width/height is zero then we have no preference for that, so set it to the original value,\n // since it cannot be any larger\n int maxWidth;\n if (target.getX() == 0) {\n maxWidth = source.getX();\n } else {\n maxWidth = target.getX();\n }\n\n int maxHeight;\n if (target.getY() == 0) {\n maxHeight = source.getY();\n } else {\n maxHeight = target.getY();\n }\n\n double wscale = maxWidth / (double) source.getX();\n double hscale = maxHeight / (double) source.getY();\n\n if (wscale < hscale)\n return new Dimension((int) (source.getX() * wscale), (int) (source.getY() * wscale));\n else\n return new Dimension((int) (source.getX() * hscale), (int) (source.getY() * hscale));\n }",
"@Override\n public void setDraggable(Element elem, String draggable) {\n super.setDraggable(elem, draggable);\n if (\"true\".equals(draggable)) {\n elem.getStyle().setProperty(\"webkitUserDrag\", \"element\");\n } else {\n elem.getStyle().clearProperty(\"webkitUserDrag\");\n }\n }",
"public static int secondsDiff(Date earlierDate, Date laterDate) {\n if (earlierDate == null || laterDate == null) {\n return 0;\n }\n\n return (int) ((laterDate.getTime() / SECOND_MILLIS) - (earlierDate.getTime() / SECOND_MILLIS));\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 }",
"public static String encodeQuery(String query, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(query, encoding, HierarchicalUriComponents.Type.QUERY);\n\t}",
"public Info changeMessage(String newMessage) {\n Info newInfo = new Info();\n newInfo.setMessage(newMessage);\n\n URL url = COMMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"PUT\");\n request.setBody(newInfo.getPendingChanges());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonResponse = JsonObject.readFrom(response.getJSON());\n\n return new Info(jsonResponse);\n }"
] |
Returns the screen height in pixels
@param context is the context to get the resources
@return the screen height in pixels | [
"public static int getScreenHeight(Context context) {\n DisplayMetrics metrics = context.getResources().getDisplayMetrics();\n return metrics.heightPixels;\n }"
] | [
"public void errorFuture(UUID taskId, Exception e) {\n DistributedFuture<GROUP, Serializable> future = remove(taskId);\n if(future != null) {\n future.setException(e);\n }\n }",
"public void setObjectForStatement(PreparedStatement ps, int index,\r\n Object value, int sqlType) throws SQLException\r\n {\r\n if (sqlType == Types.TINYINT)\r\n {\r\n ps.setByte(index, ((Byte) value).byteValue());\r\n }\r\n else\r\n {\r\n super.setObjectForStatement(ps, index, value, sqlType);\r\n }\r\n }",
"int getItemViewType(T content) {\n Class prototypeClass = getPrototypeClass(content);\n validatePrototypeClass(prototypeClass);\n return getItemViewType(prototypeClass);\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 }",
"public void sendLoadTrackCommand(int targetPlayer, int rekordboxId,\n int sourcePlayer, CdjStatus.TrackSourceSlot sourceSlot, CdjStatus.TrackType sourceType)\n throws IOException {\n final DeviceUpdate update = getLatestStatusFor(targetPlayer);\n if (update == null) {\n throw new IllegalArgumentException(\"Device \" + targetPlayer + \" not found on network.\");\n }\n sendLoadTrackCommand(update, rekordboxId, sourcePlayer, sourceSlot, sourceType);\n }",
"@SuppressWarnings(\"unchecked\")\n protected void addPostRunDependent(Executable<? extends Indexable> executable) {\n TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) executable;\n this.addPostRunDependent(dependency);\n }",
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void setOffline(boolean value){\n offline = value;\n if (offline) {\n getConfigLogger().debug(getAccountId(), \"CleverTap Instance has been set to offline, won't send events queue\");\n } else {\n getConfigLogger().debug(getAccountId(), \"CleverTap Instance has been set to online, sending events queue\");\n flush();\n }\n }",
"private String getDateTimeString(Date value)\n {\n String result = null;\n if (value != null)\n {\n Calendar cal = DateHelper.popCalendar(value);\n StringBuilder sb = new StringBuilder(16);\n sb.append(m_fourDigitFormat.format(cal.get(Calendar.YEAR)));\n sb.append(m_twoDigitFormat.format(cal.get(Calendar.MONTH) + 1));\n sb.append(m_twoDigitFormat.format(cal.get(Calendar.DAY_OF_MONTH)));\n sb.append('T');\n sb.append(m_twoDigitFormat.format(cal.get(Calendar.HOUR_OF_DAY)));\n sb.append(m_twoDigitFormat.format(cal.get(Calendar.MINUTE)));\n sb.append(m_twoDigitFormat.format(cal.get(Calendar.SECOND)));\n sb.append('Z');\n result = sb.toString();\n DateHelper.pushCalendar(cal);\n }\n return result;\n }",
"public static final void setSize(UIObject o, Rect size) {\n o.setPixelSize(size.w, size.h);\n\n }"
] |
Adds an artifact to the module.
<P>
INFO: If the module is promoted, all added artifacts will be promoted.
@param artifact Artifact | [
"public void addArtifact(final Artifact artifact) {\n if (!artifacts.contains(artifact)) {\n if (promoted) {\n artifact.setPromoted(promoted);\n }\n\n artifacts.add(artifact);\n }\n }"
] | [
"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 final PJsonArray optJSONArray(final String key, final PJsonArray defaultValue) {\n PJsonArray result = optJSONArray(key);\n return result != null ? result : defaultValue;\n }",
"private InputStream connect(String url) throws IOException {\n\t\tURLConnection conn = new URL(URL_BASE + url).openConnection();\n\t\tconn.setConnectTimeout(CONNECT_TIMEOUT);\n\t\tconn.setReadTimeout(READ_TIMEOUT);\n\t\tconn.setRequestProperty(\"User-Agent\", USER_AGENT);\n\t\treturn conn.getInputStream();\n\t}",
"private void writeIntegerField(String fieldName, Object value) throws IOException\n {\n int val = ((Number) value).intValue();\n if (val != 0)\n {\n m_writer.writeNameValuePair(fieldName, val);\n }\n }",
"public boolean setMethodArguments(String pathName, String methodName, Integer ordinal, Object... arguments) {\n try {\n BasicNameValuePair[] params = new BasicNameValuePair[arguments.length + 2];\n int x = 0;\n for (Object argument : arguments) {\n params[x] = new BasicNameValuePair(\"arguments[]\", argument.toString());\n x++;\n }\n params[x] = new BasicNameValuePair(\"profileIdentifier\", this._profileName);\n params[x + 1] = new BasicNameValuePair(\"ordinal\", ordinal.toString());\n\n JSONObject response = new JSONObject(doPost(BASE_PATH + uriEncode(pathName) + \"/\" + methodName, params));\n\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return false;\n }",
"public double Function1D(double x) {\n double frequency = initFrequency;\n double amplitude = initAmplitude;\n double sum = 0;\n\n // octaves\n for (int i = 0; i < octaves; i++) {\n sum += SmoothedNoise(x * frequency) * amplitude;\n\n frequency *= 2;\n amplitude *= persistence;\n }\n return sum;\n }",
"private boolean includeDocument(ItemDocument itemDocument) {\n\t\tfor (StatementGroup sg : itemDocument.getStatementGroups()) {\n\t\t\t// \"P19\" is \"place of birth\" on Wikidata\n\t\t\tif (!\"P19\".equals(sg.getProperty().getId())) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (Statement s : sg) {\n\t\t\t\tif (s.getMainSnak() instanceof ValueSnak) {\n\t\t\t\t\tValue v = s.getValue();\n\t\t\t\t\t// \"Q1731\" is \"Dresden\" on Wikidata\n\t\t\t\t\tif (v instanceof ItemIdValue\n\t\t\t\t\t\t\t&& \"Q1731\".equals(((ItemIdValue) v).getId())) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"public static base_response add(nitro_service client, ipset resource) throws Exception {\n\t\tipset addresource = new ipset();\n\t\taddresource.name = resource.name;\n\t\taddresource.td = resource.td;\n\t\treturn addresource.add_resource(client);\n\t}",
"private String stripLineBreaks(String text, String replacement)\n {\n if (text.indexOf('\\r') != -1 || text.indexOf('\\n') != -1)\n {\n StringBuilder sb = new StringBuilder(text);\n\n int index;\n\n while ((index = sb.indexOf(\"\\r\\n\")) != -1)\n {\n sb.replace(index, index + 2, replacement);\n }\n\n while ((index = sb.indexOf(\"\\n\\r\")) != -1)\n {\n sb.replace(index, index + 2, replacement);\n }\n\n while ((index = sb.indexOf(\"\\r\")) != -1)\n {\n sb.replace(index, index + 1, replacement);\n }\n\n while ((index = sb.indexOf(\"\\n\")) != -1)\n {\n sb.replace(index, index + 1, replacement);\n }\n\n text = sb.toString();\n }\n\n return (text);\n }"
] |
Use this API to renumber nspbr6 resources. | [
"public static base_responses renumber(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 renumberresources[] = new nspbr6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\trenumberresources[i] = new nspbr6();\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, renumberresources,\"renumber\");\n\t\t}\n\t\treturn result;\n\t}"
] | [
"public Object newInstance(String resource) {\n try {\n String name = resource.startsWith(\"/\") ? resource : \"/\" + resource;\n File file = new File(this.getClass().getResource(name).toURI());\n return newInstance(classLoader.parseClass(new GroovyCodeSource(file), true));\n } catch (Exception e) {\n throw new GroovyClassInstantiationFailed(classLoader, resource, e);\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 static Face createTriangle(Vertex v0, Vertex v1, Vertex v2, double minArea) {\n Face face = new Face();\n HalfEdge he0 = new HalfEdge(v0, face);\n HalfEdge he1 = new HalfEdge(v1, face);\n HalfEdge he2 = new HalfEdge(v2, face);\n\n he0.prev = he2;\n he0.next = he1;\n he1.prev = he0;\n he1.next = he2;\n he2.prev = he1;\n he2.next = he0;\n\n face.he0 = he0;\n\n // compute the normal and offset\n face.computeNormalAndCentroid(minArea);\n return face;\n }",
"public void forAllIndexDescriptorDefinitions(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _curClassDef.getIndexDescriptors(); it.hasNext(); )\r\n {\r\n _curIndexDescriptorDef = (IndexDescriptorDef)it.next();\r\n generate(template);\r\n }\r\n _curIndexDescriptorDef = null;\r\n }",
"public void setEnd(Date endDate) {\n\n if ((null == endDate) || getStart().after(endDate)) {\n m_explicitEnd = null;\n } else {\n m_explicitEnd = endDate;\n }\n }",
"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 double[] getMoneynessAsOffsets() {\r\n\t\tDoubleStream moneyness = getGridNodesPerMoneyness().keySet().stream().mapToDouble(Integer::doubleValue);\r\n\t\tif(quotingConvention == QuotingConvention.PAYERVOLATILITYLOGNORMAL) {\r\n\t\t\tmoneyness = moneyness.map(new DoubleUnaryOperator() {\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic double applyAsDouble(double x) {\r\n\t\t\t\t\treturn x * 0.01;\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t} else if(quotingConvention == QuotingConvention.RECEIVERPRICE) {\r\n\t\t\tmoneyness = moneyness.map(new DoubleUnaryOperator() {\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic double applyAsDouble(double x) {\r\n\t\t\t\t\treturn - x * 0.0001;\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t} else {\r\n\t\t\tmoneyness = moneyness.map(new DoubleUnaryOperator() {\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic double applyAsDouble(double x) {\r\n\t\t\t\t\treturn x * 0.0001;\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t}\r\n\t\treturn moneyness.toArray();\r\n\t}",
"private void throwExceptionIfSafetyRestrictionsAreViolated(CmsObject cms, CmsSolrQuery query, boolean isSpell)\r\n throws CmsSearchException {\r\n\r\n if (!isDebug(cms, query)) {\r\n if (isSpell) {\r\n if (m_handlerSpellDisabled) {\r\n throw new CmsSearchException(Messages.get().container(Messages.GUI_HANDLER_REQUEST_NOT_ALLOWED_0));\r\n }\r\n } else {\r\n if (m_handlerSelectDisabled) {\r\n throw new CmsSearchException(Messages.get().container(Messages.GUI_HANDLER_REQUEST_NOT_ALLOWED_0));\r\n }\r\n int start = null != query.getStart() ? query.getStart().intValue() : 0;\r\n int rows = null != query.getRows() ? query.getRows().intValue() : CmsSolrQuery.DEFAULT_ROWS.intValue();\r\n if ((m_handlerMaxAllowedResultsAtAll >= 0) && ((rows + start) > m_handlerMaxAllowedResultsAtAll)) {\r\n throw new CmsSearchException(\r\n Messages.get().container(\r\n Messages.GUI_HANDLER_TOO_MANY_RESULTS_REQUESTED_AT_ALL_2,\r\n Integer.valueOf(m_handlerMaxAllowedResultsAtAll),\r\n Integer.valueOf(rows + start)));\r\n }\r\n if ((m_handlerMaxAllowedResultsPerPage >= 0) && (rows > m_handlerMaxAllowedResultsPerPage)) {\r\n throw new CmsSearchException(\r\n Messages.get().container(\r\n Messages.GUI_HANDLER_TOO_MANY_RESULTS_REQUESTED_PER_PAGE_2,\r\n Integer.valueOf(m_handlerMaxAllowedResultsPerPage),\r\n Integer.valueOf(rows)));\r\n }\r\n if ((null != m_handlerAllowedFields) && (Stream.of(m_handlerAllowedFields).anyMatch(x -> true))) {\r\n if (query.getFields().equals(CmsSolrQuery.ALL_RETURN_FIELDS)) {\r\n query.setFields(m_handlerAllowedFields);\r\n } else {\r\n for (String requestedField : query.getFields().split(\",\")) {\r\n if (Stream.of(m_handlerAllowedFields).noneMatch(\r\n allowedField -> allowedField.equals(requestedField))) {\r\n throw new CmsSearchException(\r\n Messages.get().container(\r\n Messages.GUI_HANDLER_REQUESTED_FIELD_NOT_ALLOWED_2,\r\n requestedField,\r\n Stream.of(m_handlerAllowedFields).reduce(\"\", (a, b) -> a + \",\" + b)));\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }",
"private String[] getFksToThisClass()\r\n {\r\n String indTable = getCollectionDescriptor().getIndirectionTable();\r\n String[] fks = getCollectionDescriptor().getFksToThisClass();\r\n String[] result = new String[fks.length];\r\n\r\n for (int i = 0; i < result.length; i++)\r\n {\r\n result[i] = indTable + \".\" + fks[i];\r\n }\r\n\r\n return result;\r\n }"
] |
Pretty-print the object. | [
"@Override\n public void prettyPrint(StringBuffer sb, int indent)\n {\n sb.append(Log.getSpaces(indent));\n sb.append(GVRBone.class.getSimpleName());\n sb.append(\" [name=\" + getName() + \", boneId=\" + getBoneId()\n + \", offsetMatrix=\" + getOffsetMatrix()\n + \", finalTransformMatrix=\" + getFinalTransformMatrix() // crashes debugger\n + \"]\");\n sb.append(System.lineSeparator());\n }"
] | [
"protected void processDurationField(Row row)\n {\n processField(row, \"DUR_FIELD_ID\", \"DUR_REF_UID\", MPDUtility.getAdjustedDuration(m_project, row.getInt(\"DUR_VALUE\"), MPDUtility.getDurationTimeUnits(row.getInt(\"DUR_FMT\"))));\n }",
"void close(Supplier<CentralDogmaException> failureCauseSupplier) {\n requireNonNull(failureCauseSupplier, \"failureCauseSupplier\");\n if (closePending.compareAndSet(null, failureCauseSupplier)) {\n repositoryWorker.execute(() -> {\n rwLock.writeLock().lock();\n try {\n if (commitIdDatabase != null) {\n try {\n commitIdDatabase.close();\n } catch (Exception e) {\n logger.warn(\"Failed to close a commitId database:\", e);\n }\n }\n\n if (jGitRepository != null) {\n try {\n jGitRepository.close();\n } catch (Exception e) {\n logger.warn(\"Failed to close a Git repository: {}\",\n jGitRepository.getDirectory(), e);\n }\n }\n } finally {\n rwLock.writeLock().unlock();\n commitWatchers.close(failureCauseSupplier);\n closeFuture.complete(null);\n }\n });\n }\n\n closeFuture.join();\n }",
"public long remove(final String... fields) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.hdel(getKey(), fields);\n }\n });\n }",
"private void readResources()\n {\n for (MapRow row : getTable(\"RTAB\"))\n {\n Resource resource = m_projectFile.addResource();\n setFields(RESOURCE_FIELDS, row, resource);\n m_eventManager.fireResourceReadEvent(resource);\n // TODO: Correctly handle calendar\n }\n }",
"public boolean setCustomResponse(String pathValue, String requestType, String customData) {\n try {\n JSONObject path = getPathFromEndpoint(pathValue, requestType);\n if (path == null) {\n String pathName = pathValue;\n createPath(pathName, pathValue, requestType);\n path = getPathFromEndpoint(pathValue, requestType);\n }\n String pathId = path.getString(\"pathId\");\n resetResponseOverride(pathId);\n setCustomResponse(pathId, customData);\n return toggleResponseOverride(pathId, true);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }",
"public final static void appendDecEntity(final StringBuilder out, final char value)\n {\n out.append(\"&#\");\n out.append((int)value);\n out.append(';');\n }",
"public void setIsSeries(Boolean isSeries) {\r\n\r\n if (null != isSeries) {\r\n final boolean series = isSeries.booleanValue();\r\n if ((null != m_model.getParentSeriesId()) && series) {\r\n m_removeSeriesBindingConfirmDialog.show(new Command() {\r\n\r\n public void execute() {\r\n\r\n m_model.setParentSeriesId(null);\r\n setPattern(PatternType.DAILY.toString());\r\n\r\n }\r\n });\r\n } else {\r\n setPattern(series ? PatternType.DAILY.toString() : PatternType.NONE.toString());\r\n }\r\n }\r\n }",
"private String toPath(String name, IconSize size) {\n\n return CmsStringUtil.joinPaths(CmsWorkplace.getSkinUri(), ICON_FOLDER, \"\" + name.hashCode()) + size.getSuffix();\n }",
"private void allRelation(Options opt, RelationType rt, ClassDoc from) {\n\tString tagname = rt.lower;\n\tfor (Tag tag : from.tags(tagname)) {\n\t String t[] = tokenize(tag.text()); // l-src label l-dst target\n\t t = t.length == 1 ? new String[] { \"-\", \"-\", \"-\", t[0] } : t; // Shorthand\n\t if (t.length != 4) {\n\t\tSystem.err.println(\"Error in \" + from + \"\\n\" + tagname + \" expects four fields (l-src label l-dst target): \" + tag.text());\n\t\treturn;\n\t }\n\t ClassDoc to = from.findClass(t[3]);\n\t if (to != null) {\n\t\tif(hidden(to))\n\t\t continue;\n\t\trelation(opt, rt, from, to, t[0], t[1], t[2]);\n\t } else {\n\t\tif(hidden(t[3]))\n\t\t continue;\n\t\trelation(opt, rt, from, from.toString(), to, t[3], t[0], t[1], t[2]);\n\t }\n\t}\n }"
] |
Is the user password reset?
@param user User to check
@return boolean | [
"boolean isUserPasswordReset(CmsUser user) {\n\n if (USER_PASSWORD_STATUS.containsKey(user.getId())) { //Check if user was checked before\n if (!USER_PASSWORD_STATUS.get(user.getId()).booleanValue()) { // was false before, false->true is never done without changing map\n return false;\n }\n if (m_checkedUserPasswordReset.contains(user.getId())) { //was true before, true->false happens when user resets password. Only check one time per table load.\n return true; //Set gets flushed on reloading table\n }\n }\n CmsUser currentUser = user;\n if (user.getAdditionalInfo().size() < 3) {\n\n try {\n currentUser = m_cms.readUser(user.getId());\n } catch (CmsException e) {\n LOG.error(\"Can not read user\", e);\n }\n }\n if (currentUser.getAdditionalInfo(CmsUserSettings.ADDITIONAL_INFO_PASSWORD_RESET) != null) {\n USER_PASSWORD_STATUS.put(currentUser.getId(), new Boolean(true));\n m_checkedUserPasswordReset.add(currentUser.getId());\n return true;\n }\n USER_PASSWORD_STATUS.put(currentUser.getId(), new Boolean(false));\n return false;\n }"
] | [
"private void processCalendarData(List<ProjectCalendar> calendars) throws SQLException\n {\n for (ProjectCalendar calendar : calendars)\n {\n processCalendarData(calendar, getRows(\"SELECT * FROM MSP_CALENDAR_DATA WHERE PROJ_ID=? AND CAL_UID=?\", m_projectID, calendar.getUniqueID()));\n }\n }",
"public static void doExtendTraits(final ClassNode cNode, final SourceUnit unit, final CompilationUnit cu) {\n if (cNode.isInterface()) return;\n boolean isItselfTrait = Traits.isTrait(cNode);\n SuperCallTraitTransformer superCallTransformer = new SuperCallTraitTransformer(unit);\n if (isItselfTrait) {\n checkTraitAllowed(cNode, unit);\n return;\n }\n if (!cNode.getNameWithoutPackage().endsWith(Traits.TRAIT_HELPER)) {\n List<ClassNode> traits = findTraits(cNode);\n for (ClassNode trait : traits) {\n TraitHelpersTuple helpers = Traits.findHelpers(trait);\n applyTrait(trait, cNode, helpers);\n superCallTransformer.visitClass(cNode);\n if (unit!=null) {\n ASTTransformationCollectorCodeVisitor collector = new ASTTransformationCollectorCodeVisitor(unit, cu.getTransformLoader());\n collector.visitClass(cNode);\n }\n }\n }\n }",
"public static List<StoreDefinition> filterStores(List<StoreDefinition> storeDefs,\n final boolean isReadOnly) {\n List<StoreDefinition> filteredStores = Lists.newArrayList();\n for(StoreDefinition storeDef: storeDefs) {\n if(storeDef.getType().equals(ReadOnlyStorageConfiguration.TYPE_NAME) == isReadOnly) {\n filteredStores.add(storeDef);\n }\n }\n return filteredStores;\n }",
"public void trace(Throwable throwable, String msg, Object[] argArray) {\n\t\tlogIfEnabled(Level.TRACE, throwable, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, argArray);\n\t}",
"public static base_responses update(nitro_service client, dospolicy resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdospolicy updateresources[] = new dospolicy[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new dospolicy();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].qdepth = resources[i].qdepth;\n\t\t\t\tupdateresources[i].cltdetectrate = resources[i].cltdetectrate;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public void value2x2( double a11 , double a12, double a21 , double a22 )\n {\n // apply a rotators such that th a11 and a22 elements are the same\n double c,s;\n\n if( a12 + a21 == 0 ) { // is this pointless since\n c = s = 1.0 / Math.sqrt(2);\n } else {\n double aa = (a11-a22);\n double bb = (a12+a21);\n\n double t_hat = aa/bb;\n double t = t_hat/(1.0 + Math.sqrt(1.0+t_hat*t_hat));\n\n c = 1.0/ Math.sqrt(1.0+t*t);\n s = c*t;\n }\n\n double c2 = c*c;\n double s2 = s*s;\n double cs = c*s;\n\n double b11 = c2*a11 + s2*a22 - cs*(a12+a21);\n double b12 = c2*a12 - s2*a21 + cs*(a11-a22);\n double b21 = c2*a21 - s2*a12 + cs*(a11-a22);\n// double b22 = c2*a22 + s2*a11 + cs*(a12+a21);\n\n // apply second rotator to make A upper triangular if real eigenvalues\n if( b21*b12 >= 0 ) {\n if( b12 == 0 ) {\n c = 0;\n s = 1;\n } else {\n s = Math.sqrt(b21/(b12+b21));\n c = Math.sqrt(b12/(b12+b21));\n }\n\n// c2 = b12;//c*c;\n// s2 = b21;//s*s;\n cs = c*s;\n\n a11 = b11 - cs*(b12 + b21);\n// a12 = c2*b12 - s2*b21;\n// a21 = c2*b21 - s2*b12;\n a22 = b11 + cs*(b12 + b21);\n\n value0.real = a11;\n value1.real = a22;\n\n value0.imaginary = value1.imaginary = 0;\n\n } else {\n value0.real = value1.real = b11;\n value0.imaginary = Math.sqrt(-b21*b12);\n value1.imaginary = -value0.imaginary;\n }\n }",
"public void init(final MultivaluedMap<String, String> queryParameters) {\n final String scopeCompileParam = queryParameters.getFirst(ServerAPI.SCOPE_COMPILE_PARAM);\n if(scopeCompileParam != null){\n this.scopeComp = Boolean.valueOf(scopeCompileParam);\n }\n final String scopeProvidedParam = queryParameters.getFirst(ServerAPI.SCOPE_PROVIDED_PARAM);\n if(scopeProvidedParam != null){\n this.scopePro = Boolean.valueOf(scopeProvidedParam);\n }\n final String scopeRuntimeParam = queryParameters.getFirst(ServerAPI.SCOPE_RUNTIME_PARAM);\n if(scopeRuntimeParam != null){\n this.scopeRun = Boolean.valueOf(scopeRuntimeParam);\n }\n final String scopeTestParam = queryParameters.getFirst(ServerAPI.SCOPE_TEST_PARAM);\n if(scopeTestParam != null){\n this.scopeTest = Boolean.valueOf(scopeTestParam);\n }\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 }",
"public static DeploymentUnit getTopDeploymentUnit(DeploymentUnit unit) {\n Assert.checkNotNullParam(\"unit\", unit);\n\n DeploymentUnit parent = unit.getParent();\n while (parent != null) {\n unit = parent;\n parent = unit.getParent();\n }\n return unit;\n }"
] |
Sets whether an individual list value is selected.
@param value the value of the item to be selected or unselected
@param selected <code>true</code> to select the item | [
"public void setValueSelected(T value, boolean selected) {\n int idx = getIndex(value);\n if (idx >= 0) {\n setItemSelectedInternal(idx, selected);\n }\n }"
] | [
"public void addColumnPair(String localColumn, String remoteColumn)\r\n {\r\n if (!_localColumns.contains(localColumn))\r\n { \r\n _localColumns.add(localColumn);\r\n }\r\n if (!_remoteColumns.contains(remoteColumn))\r\n { \r\n _remoteColumns.add(remoteColumn);\r\n }\r\n }",
"public float[] getFloatArray(String attributeName)\n {\n float[] array = NativeVertexBuffer.getFloatArray(getNative(), attributeName);\n if (array == null)\n {\n throw new IllegalArgumentException(\"Attribute name \" + attributeName + \" cannot be accessed\");\n }\n return array;\n }",
"public void setIssueTrackerInfo(BuildInfoBuilder builder) {\n Issues issues = new Issues();\n issues.setAggregateBuildIssues(aggregateBuildIssues);\n issues.setAggregationBuildStatus(aggregationBuildStatus);\n issues.setTracker(new IssueTracker(\"JIRA\", issueTrackerVersion));\n Set<Issue> affectedIssuesSet = IssuesTrackerUtils.getAffectedIssuesSet(affectedIssues);\n if (!affectedIssuesSet.isEmpty()) {\n issues.setAffectedIssues(affectedIssuesSet);\n }\n builder.issues(issues);\n }",
"public void setHeaders(final Set<String> names) {\n // transform to lower-case because header names should be case-insensitive\n Set<String> lowerCaseNames = new HashSet<>();\n for (String name: names) {\n lowerCaseNames.add(name.toLowerCase());\n }\n this.headerNames = lowerCaseNames;\n }",
"static WeldContainer startInitialization(String id, Deployment deployment, Bootstrap bootstrap) {\n if (SINGLETON.isSet(id)) {\n throw WeldSELogger.LOG.weldContainerAlreadyRunning(id);\n }\n WeldContainer weldContainer = new WeldContainer(id, deployment, bootstrap);\n SINGLETON.set(id, weldContainer);\n RUNNING_CONTAINER_IDS.add(id);\n return weldContainer;\n }",
"public boolean isEmbeddedProperty(String targetTypeName, List<String> namesWithoutAlias) {\n\t\tOgmEntityPersister persister = getPersister( targetTypeName );\n\t\tType propertyType = persister.getPropertyType( namesWithoutAlias.get( 0 ) );\n\t\tif ( propertyType.isComponentType() ) {\n\t\t\t// Embedded\n\t\t\treturn true;\n\t\t}\n\t\telse if ( propertyType.isAssociationType() ) {\n\t\t\tJoinable associatedJoinable = ( (AssociationType) propertyType ).getAssociatedJoinable( persister.getFactory() );\n\t\t\tif ( associatedJoinable.isCollection() ) {\n\t\t\t\tOgmCollectionPersister collectionPersister = (OgmCollectionPersister) associatedJoinable;\n\t\t\t\treturn collectionPersister.getType().isComponentType();\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"synchronized int storeObject(JSONObject obj, Table table) {\n if (!this.belowMemThreshold()) {\n Logger.v(\"There is not enough space left on the device to store data, data discarded\");\n return DB_OUT_OF_MEMORY_ERROR;\n }\n\n final String tableName = table.getName();\n\n Cursor cursor = null;\n int count = DB_UPDATE_ERROR;\n\n //noinspection TryFinallyCanBeTryWithResources\n try {\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n\n final ContentValues cv = new ContentValues();\n cv.put(KEY_DATA, obj.toString());\n cv.put(KEY_CREATED_AT, System.currentTimeMillis());\n db.insert(tableName, null, cv);\n cursor = db.rawQuery(\"SELECT COUNT(*) FROM \" + tableName, null);\n cursor.moveToFirst();\n count = cursor.getInt(0);\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Error adding data to table \" + tableName + \" Recreating DB\");\n\n if (cursor != null) {\n cursor.close();\n cursor = null;\n }\n dbHelper.deleteDatabase();\n } finally {\n if (cursor != null) {\n cursor.close();\n }\n dbHelper.close();\n }\n return count;\n }",
"public RedwoodConfiguration stdout(){\r\n LogRecordHandler visibility = new VisibilityHandler();\r\n LogRecordHandler console = Redwood.ConsoleHandler.out();\r\n return this\r\n .rootHandler(visibility)\r\n .handler(visibility, console);\r\n }",
"public static authenticationtacacspolicy_systemglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationtacacspolicy_systemglobal_binding obj = new authenticationtacacspolicy_systemglobal_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationtacacspolicy_systemglobal_binding response[] = (authenticationtacacspolicy_systemglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Unlinks a set of dependencies from this task.
@param task The task to remove dependencies from.
@return Request object | [
"public ItemRequest<Task> removeDependencies(String task) {\n \n String path = String.format(\"/tasks/%s/removeDependencies\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }"
] | [
"public Deployment setServerGroups(final Collection<String> serverGroups) {\n this.serverGroups.clear();\n this.serverGroups.addAll(serverGroups);\n return this;\n }",
"public void checkpoint(ObjectEnvelope mod)\r\n throws org.apache.ojb.broker.PersistenceBrokerException\r\n {\r\n mod.doUpdate();\r\n }",
"public final void reset()\n {\n for (int i = 0; i < combinationIndices.length; i++)\n {\n combinationIndices[i] = i;\n }\n remainingCombinations = totalCombinations;\n }",
"public String getCanonicalTypeName(Object object) {\n ensureNotNull(\"object\", object);\n\n for (TypeDetector typeDetector : typeDetectors) {\n if (typeDetector.canHandle(object)) {\n return typeDetector.detectType(object);\n }\n }\n\n throw LOG.unableToDetectCanonicalType(object);\n }",
"public static long readUnsignedInt(byte[] bytes, int offset) {\n return (((bytes[offset + 0] & 0xffL) << 24) | ((bytes[offset + 1] & 0xffL) << 16)\n | ((bytes[offset + 2] & 0xffL) << 8) | (bytes[offset + 3] & 0xffL));\n }",
"public static dnsaaaarec[] get(nitro_service service, dnsaaaarec_args args) throws Exception{\n\t\tdnsaaaarec obj = new dnsaaaarec();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tdnsaaaarec[] response = (dnsaaaarec[])obj.get_resources(service, option);\n\t\treturn response;\n\t}",
"public void process(String inputFile, String outputFile) throws Exception\n {\n System.out.println(\"Reading input file started.\");\n long start = System.currentTimeMillis();\n ProjectFile projectFile = readFile(inputFile);\n long elapsed = System.currentTimeMillis() - start;\n System.out.println(\"Reading input file completed in \" + elapsed + \"ms.\");\n\n System.out.println(\"Writing output file started.\");\n start = System.currentTimeMillis();\n ProjectWriter writer = ProjectWriterUtility.getProjectWriter(outputFile);\n writer.write(projectFile, outputFile);\n elapsed = System.currentTimeMillis() - start;\n System.out.println(\"Writing output completed in \" + elapsed + \"ms.\");\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 String text() {\n String previousText = null;\n StringBuilder buffer = null;\n for (Object child : this) {\n String text = null;\n if (child instanceof String) {\n text = (String) child;\n } else if (child instanceof Node) {\n text = ((Node) child).text();\n }\n if (text != null) {\n if (previousText == null) {\n previousText = text;\n } else {\n if (buffer == null) {\n buffer = new StringBuilder();\n buffer.append(previousText);\n }\n buffer.append(text);\n }\n }\n }\n if (buffer != null) {\n return buffer.toString();\n }\n if (previousText != null) {\n return previousText;\n }\n return \"\";\n }"
] |
Notifies that multiple footer items are removed.
@param positionStart the position.
@param itemCount the item count. | [
"public final void notifyFooterItemRangeRemoved(int positionStart, int itemCount) {\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > footerItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for footer items [0 - \"\n + (footerItemCount - 1) + \"].\");\n }\n notifyItemRangeRemoved(positionStart + headerItemCount + contentItemCount, itemCount);\n }"
] | [
"private void logOriginalRequestHistory(String requestType,\n HttpServletRequest request, History history) {\n logger.info(\"Storing original request history\");\n history.setRequestType(requestType);\n history.setOriginalRequestHeaders(HttpUtilities.getHeaders(request));\n history.setOriginalRequestURL(request.getRequestURL().toString());\n history.setOriginalRequestParams(request.getQueryString() == null ? \"\" : request.getQueryString());\n logger.info(\"Done storing\");\n }",
"public DescriptorRepository readDescriptorRepository(String fileName)\r\n {\r\n try\r\n {\r\n RepositoryPersistor persistor = new RepositoryPersistor();\r\n return persistor.readDescriptorRepository(fileName);\r\n }\r\n catch (Exception e)\r\n {\r\n throw new MetadataException(\"Can not read repository \" + fileName, e);\r\n }\r\n }",
"public void resize(int w, int h) {\n\n // using the new approach of Java 2D API\n BufferedImage buf = new BufferedImage(w, h, image.getType());\n Graphics2D g2d = (Graphics2D) buf.getGraphics();\n g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);\n g2d.drawImage(image, 0, 0, w, h, null);\n g2d.dispose();\n image = buf;\n width = w;\n height = h;\n updateColorArray();\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 }",
"public URI build() {\n try {\n String uriString = String.format(\"%s%s\", baseUri.toASCIIString(),\n (path.isEmpty() ? \"\" : path));\n if(qParams != null && qParams.size() > 0) {\n //Add queries together if both exist\n if(!completeQuery.isEmpty()) {\n uriString = String.format(\"%s?%s&%s\", uriString,\n getJoinedQuery(qParams.getParams()),\n completeQuery);\n } else {\n uriString = String.format(\"%s?%s\", uriString,\n getJoinedQuery(qParams.getParams()));\n }\n } else if(!completeQuery.isEmpty()) {\n uriString = String.format(\"%s?%s\", uriString, completeQuery);\n }\n\n return new URI(uriString);\n } catch (URISyntaxException e) {\n throw new IllegalArgumentException(e);\n }\n }",
"public void writeStartObject(String name) throws IOException\n {\n writeComma();\n writeNewLineIndent();\n\n if (name != null)\n {\n writeName(name);\n writeNewLineIndent();\n }\n\n m_writer.write(\"{\");\n increaseIndent();\n }",
"@SafeVarargs\n public static <T> Set<T> create(final T... values) {\n Set<T> result = new HashSet<>(values.length);\n Collections.addAll(result, values);\n return result;\n }",
"public static AnalysisResult fakeSuccess() {\n return new AnalysisResult(null, new Extensions(Collections.emptyMap(), Collections.emptyMap(),\n Collections.emptyMap(), Collections.emptyMap()));\n }",
"List<Message> getFullTrackList(final CdjStatus.TrackSourceSlot slot, final Client client, final int sortOrder)\n throws IOException, InterruptedException, TimeoutException {\n // Send the metadata menu request\n if (client.tryLockingForMenuOperations(MENU_TIMEOUT, TimeUnit.SECONDS)) {\n try {\n Message response = client.menuRequest(Message.KnownType.TRACK_MENU_REQ, Message.MenuIdentifier.MAIN_MENU, slot,\n new NumberField(sortOrder));\n final long count = response.getMenuResultsCount();\n if (count == Message.NO_MENU_RESULTS_AVAILABLE || count == 0) {\n return Collections.emptyList();\n }\n\n // Gather all the metadata menu items\n return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slot, CdjStatus.TrackType.REKORDBOX, response);\n }\n finally {\n client.unlockForMenuOperations();\n }\n } else {\n throw new TimeoutException(\"Unable to lock the player for menu operations\");\n }\n }"
] |
Creates a cube with each face as a separate mesh using a different texture.
The meshes will share a common vertex array but will have separate index buffers.
@param gvrContext context to use for creating cube
@param facingOut true for outward normals, false for inward normals
@param vertexDesc string describing which vertex components are desired
@param textureList list of 6 textures, one for each face | [
"private void createSimpleCubeSixMeshes(GVRContext gvrContext,\n boolean facingOut, String vertexDesc, ArrayList<GVRTexture> textureList)\n {\n GVRSceneObject[] children = new GVRSceneObject[6];\n GVRMesh[] meshes = new GVRMesh[6];\n GVRVertexBuffer vbuf = new GVRVertexBuffer(gvrContext, vertexDesc, SIMPLE_VERTICES.length / 3);\n\n if (facingOut)\n {\n vbuf.setFloatArray(\"a_position\", SIMPLE_VERTICES, 3, 0);\n vbuf.setFloatArray(\"a_normal\", SIMPLE_OUTWARD_NORMALS, 3, 0);\n vbuf.setFloatArray(\"a_texcoord\", SIMPLE_OUTWARD_TEXCOORDS, 2, 0);\n meshes[0] = createMesh(vbuf, SIMPLE_OUTWARD_FRONT_INDICES);\n meshes[1] = createMesh(vbuf, SIMPLE_OUTWARD_RIGHT_INDICES);\n meshes[2] = createMesh(vbuf, SIMPLE_OUTWARD_BACK_INDICES);\n meshes[3] = createMesh(vbuf, SIMPLE_OUTWARD_LEFT_INDICES);\n meshes[4] = createMesh(vbuf, SIMPLE_OUTWARD_TOP_INDICES);\n meshes[5] = createMesh(vbuf, SIMPLE_OUTWARD_BOTTOM_INDICES);\n }\n else\n {\n vbuf.setFloatArray(\"a_position\", SIMPLE_VERTICES, 3, 0);\n vbuf.setFloatArray(\"a_normal\", SIMPLE_INWARD_NORMALS, 3, 0);\n vbuf.setFloatArray(\"a_texcoord\", SIMPLE_INWARD_TEXCOORDS, 2, 0);\n meshes[0] = createMesh(vbuf, SIMPLE_INWARD_FRONT_INDICES);\n meshes[1] = createMesh(vbuf, SIMPLE_INWARD_RIGHT_INDICES);\n meshes[2] = createMesh(vbuf, SIMPLE_INWARD_BACK_INDICES);\n meshes[3] = createMesh(vbuf, SIMPLE_INWARD_LEFT_INDICES);\n meshes[4] = createMesh(vbuf, SIMPLE_INWARD_TOP_INDICES);\n meshes[5] = createMesh(vbuf, SIMPLE_INWARD_BOTTOM_INDICES);\n }\n\n for (int i = 0; i < 6; i++)\n {\n children[i] = new GVRSceneObject(gvrContext, meshes[i], textureList.get(i));\n addChildObject(children[i]);\n }\n\n // attached an empty renderData for parent object, so that we can set some common properties\n GVRRenderData renderData = new GVRRenderData(gvrContext);\n attachRenderData(renderData);\n }"
] | [
"public String getHostName() {\n if( addr instanceof NbtAddress ) {\n return ((NbtAddress)addr).getHostName();\n }\n return ((InetAddress)addr).getHostName();\n }",
"@SuppressWarnings(\"deprecation\")\n\tpublic static boolean isTimeInRange(java.sql.Time start, java.sql.Time end, java.util.Date d) {\n d = new java.sql.Time(d.getHours(), d.getMinutes(), d.getSeconds());\n\n if (start == null || end == null) {\n return false;\n }\n\n if (start.before(end) && (!(d.after(start) && d.before(end)))) {\n return false;\n }\n\n if (end.before(start) && (!(d.after(end) || d.before(start)))) {\n return false;\n }\n return true;\n }",
"public void setAcquireRetryDelay(long acquireRetryDelay, TimeUnit timeUnit) {\n\t\tthis.acquireRetryDelayInMs = TimeUnit.MILLISECONDS.convert(acquireRetryDelay, timeUnit);\n\t}",
"@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 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}",
"private void checkModifications(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 HashMap features = new HashMap();\r\n FeatureDescriptorDef def;\r\n\r\n for (Iterator it = classDef.getFields(); it.hasNext();)\r\n {\r\n def = (FeatureDescriptorDef)it.next();\r\n features.put(def.getName(), def);\r\n }\r\n for (Iterator it = classDef.getReferences(); it.hasNext();)\r\n {\r\n def = (FeatureDescriptorDef)it.next();\r\n features.put(def.getName(), def);\r\n }\r\n for (Iterator it = classDef.getCollections(); it.hasNext();)\r\n {\r\n def = (FeatureDescriptorDef)it.next();\r\n features.put(def.getName(), def);\r\n }\r\n\r\n // now checking the modifications\r\n Properties mods;\r\n String modName;\r\n String propName;\r\n\r\n for (Iterator it = classDef.getModificationNames(); it.hasNext();)\r\n {\r\n modName = (String)it.next();\r\n if (!features.containsKey(modName))\r\n {\r\n throw new ConstraintException(\"Class \"+classDef.getName()+\" contains a modification for an unknown feature \"+modName);\r\n }\r\n def = (FeatureDescriptorDef)features.get(modName);\r\n if (def.getOriginal() == null)\r\n {\r\n throw new ConstraintException(\"Class \"+classDef.getName()+\" contains a modification for a feature \"+modName+\" that is not inherited but defined in the same class\");\r\n }\r\n // checking modification\r\n mods = classDef.getModification(modName);\r\n for (Iterator propIt = mods.keySet().iterator(); propIt.hasNext();)\r\n {\r\n propName = (String)propIt.next();\r\n if (!PropertyHelper.isPropertyAllowed(def.getClass(), propName))\r\n {\r\n throw new ConstraintException(\"The modification of attribute \"+propName+\" in class \"+classDef.getName()+\" is not applicable to the feature \"+modName);\r\n }\r\n }\r\n }\r\n }",
"public void updateRequestByAddingReplaceVarPair(\n ParallelTask task, String replaceVarKey, String replaceVarValue) {\n\n Map<String, NodeReqResponse> taskResult = task.getParallelTaskResult();\n\n for (Entry<String, NodeReqResponse> entry : taskResult.entrySet()) {\n NodeReqResponse nodeReqResponse = entry.getValue();\n\n nodeReqResponse.getRequestParameters()\n .put(PcConstants.NODE_REQUEST_PREFIX_REPLACE_VAR\n + replaceVarKey, replaceVarValue);\n nodeReqResponse.getRequestParameters().put(\n PcConstants.NODE_REQUEST_WILL_EXECUTE,\n Boolean.toString(true));\n\n }// end for loop\n\n }",
"public static base_response update(nitro_service client, onlinkipv6prefix resource) throws Exception {\n\t\tonlinkipv6prefix updateresource = new onlinkipv6prefix();\n\t\tupdateresource.ipv6prefix = resource.ipv6prefix;\n\t\tupdateresource.onlinkprefix = resource.onlinkprefix;\n\t\tupdateresource.autonomusprefix = resource.autonomusprefix;\n\t\tupdateresource.depricateprefix = resource.depricateprefix;\n\t\tupdateresource.decrementprefixlifetimes = resource.decrementprefixlifetimes;\n\t\tupdateresource.prefixvalidelifetime = resource.prefixvalidelifetime;\n\t\tupdateresource.prefixpreferredlifetime = resource.prefixpreferredlifetime;\n\t\treturn updateresource.update_resource(client);\n\t}",
"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 }"
] |
Modify a misc file.
@param name the file name
@param path the relative path
@param existingHash the existing hash
@param newHash the new hash of the modified content
@param isDirectory whether the file is a directory or not
@return the builder | [
"public T modifyFile(final String name, final List<String> path, final byte[] existingHash, final byte[] newHash, final boolean isDirectory) {\n return modifyFile(name, path, existingHash, newHash, isDirectory, null);\n }"
] | [
"protected Violation createViolationForImport(SourceCode sourceCode, ImportNode importNode, String message) {\n Map importInfo = ImportUtil.sourceLineAndNumberForImport(sourceCode, importNode);\n Violation violation = new Violation();\n violation.setRule(this);\n violation.setSourceLine((String) importInfo.get(\"sourceLine\"));\n violation.setLineNumber((Integer) importInfo.get(\"lineNumber\"));\n violation.setMessage(message);\n return violation;\n }",
"@Deprecated\n public static TraceContextHolder wrap(TraceContext traceContext) {\n return (traceContext != null) ? new TraceContextHolder(traceContext) : TraceContextHolder.EMPTY;\n }",
"@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients/{clientUUID}\", method = RequestMethod.POST)\n public\n @ResponseBody\n HashMap<String, Object> updateClient(Model model,\n @PathVariable(\"profileIdentifier\") String profileIdentifier,\n @PathVariable(\"clientUUID\") String clientUUID,\n @RequestParam(required = false) Boolean active,\n @RequestParam(required = false) String friendlyName,\n @RequestParam(required = false) Boolean reset) throws Exception {\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n\n if (active != null) {\n logger.info(\"Active: {}\", active);\n clientService.updateActive(profileId, clientUUID, active);\n }\n\n if (friendlyName != null) {\n clientService.setFriendlyName(profileId, clientUUID, friendlyName);\n }\n\n if (reset != null && reset) {\n clientService.reset(profileId, clientUUID);\n }\n\n HashMap<String, Object> valueHash = new HashMap<String, Object>();\n valueHash.put(\"client\", clientService.findClient(clientUUID, profileId));\n return valueHash;\n }",
"public void setRotation(String rotation) {\r\n if (rotation != null) {\r\n try {\r\n setRotation(Integer.parseInt(rotation));\r\n } catch (NumberFormatException e) {\r\n setRotation(-1);\r\n }\r\n }\r\n }",
"public void retrieveReference(Object pInstance, String pAttributeName) throws PersistenceBrokerException\n {\n if (logger.isDebugEnabled())\n {\n \tlogger.debug(\"Retrieving reference named [\"+pAttributeName+\"] on object of type [\"+\n \t pInstance.getClass().getName()+\"]\");\n }\n ClassDescriptor cld = getClassDescriptor(pInstance.getClass());\n CollectionDescriptor cod = cld.getCollectionDescriptorByName(pAttributeName);\n getInternalCache().enableMaterializationCache();\n // to avoid problems with circular references, locally cache the current object instance\n Identity oid = serviceIdentity().buildIdentity(pInstance);\n boolean needLocalRemove = false;\n if(getInternalCache().doLocalLookup(oid) == null)\n {\n getInternalCache().doInternalCache(oid, pInstance, MaterializationCache.TYPE_TEMP);\n needLocalRemove = true;\n }\n try\n {\n if (cod != null)\n {\n referencesBroker.retrieveCollection(pInstance, cld, cod, true);\n }\n else\n {\n ObjectReferenceDescriptor ord = cld.getObjectReferenceDescriptorByName(pAttributeName);\n if (ord != null)\n {\n referencesBroker.retrieveReference(pInstance, cld, ord, true);\n }\n else\n {\n throw new PersistenceBrokerException(\"did not find attribute \" + pAttributeName +\n \" for class \" + pInstance.getClass().getName());\n }\n }\n // do locally remove the object to avoid problems with object state detection (insert/update),\n // because objects found in the cache detected as 'old' means 'update'\n if(needLocalRemove) getInternalCache().doLocalRemove(oid);\n getInternalCache().disableMaterializationCache();\n }\n catch(RuntimeException e)\n {\n getInternalCache().doLocalClear();\n throw e;\n }\n }",
"public static lbmonitor_binding[] get(nitro_service service, String monitorname[]) throws Exception{\n\t\tif (monitorname !=null && monitorname.length>0) {\n\t\t\tlbmonitor_binding response[] = new lbmonitor_binding[monitorname.length];\n\t\t\tlbmonitor_binding obj[] = new lbmonitor_binding[monitorname.length];\n\t\t\tfor (int i=0;i<monitorname.length;i++) {\n\t\t\t\tobj[i] = new lbmonitor_binding();\n\t\t\t\tobj[i].set_monitorname(monitorname[i]);\n\t\t\t\tresponse[i] = (lbmonitor_binding) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}",
"protected TransformationDescription buildDefault(final DiscardPolicy discardPolicy, boolean inherited, final AttributeTransformationDescriptionBuilderImpl.AttributeTransformationDescriptionBuilderRegistry registry, List<String> discardedOperations) {\n // Build attribute rules\n final Map<String, AttributeTransformationDescription> attributes = registry.buildAttributes();\n // Create operation transformers\n final Map<String, OperationTransformer> operations = buildOperationTransformers(registry);\n // Process children\n final List<TransformationDescription> children = buildChildren();\n\n if (discardPolicy == DiscardPolicy.NEVER) {\n // TODO override more global operations?\n if(! operations.containsKey(ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION)) {\n operations.put(ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION, OperationTransformationRules.createWriteOperation(attributes));\n }\n if(! operations.containsKey(ModelDescriptionConstants.UNDEFINE_ATTRIBUTE_OPERATION)) {\n operations.put(ModelDescriptionConstants.UNDEFINE_ATTRIBUTE_OPERATION, OperationTransformationRules.createUndefinedOperation(attributes));\n }\n }\n // Create the description\n Set<String> discarded = new HashSet<>();\n discarded.addAll(discardedOperations);\n return new TransformingDescription(pathElement, pathAddressTransformer, discardPolicy, inherited,\n resourceTransformer, attributes, operations, children, discarded, dynamicDiscardPolicy);\n }",
"public DesignDocument get(String id, String rev) {\r\n assertNotEmpty(id, \"id\");\r\n assertNotEmpty(id, \"rev\");\r\n return db.find(DesignDocument.class, ensureDesignPrefix(id), rev);\r\n }",
"public void fireCalendarReadEvent(ProjectCalendar calendar)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.calendarRead(calendar);\n }\n }\n }"
] |
Queues a Runnable to be run on the main thread on the next iteration of
the messaging loop. This is handy when code running on the main thread
needs to run something else on the main thread, but only after the
current code has finished executing.
@param r
The {@link Runnable} to run on the main thread.
@return Returns {@code true} if the Runnable was successfully placed in
the Looper's message queue. | [
"public boolean runOnMainThreadNext(Runnable r) {\n assert handler != null;\n\n if (!sanityCheck(\"runOnMainThreadNext \" + r)) {\n return false;\n }\n return handler.post(r);\n }"
] | [
"public void remove(RowKey key) {\n\t\tcurrentState.put( key, new AssociationOperation( key, null, REMOVE ) );\n\t}",
"@Override\n\tpublic Iterator<? extends IPAddressSeqRange> prefixIterator(int prefixLength) {\n\t\tif(!isMultiple()) {\n\t\t\treturn new Iterator<IPAddressSeqRange>() {\n\t\t\t\tIPAddressSeqRange orig = IPAddressSeqRange.this;\n\n\t\t\t\t@Override\n\t\t\t\tpublic boolean hasNext() {\n\t\t\t\t\treturn orig != null;\n\t\t\t\t}\n\n\t\t\t @Override\n\t\t\t\tpublic IPAddressSeqRange next() {\n\t\t\t \tif(orig == null) {\n\t\t\t \t\tthrow new NoSuchElementException();\n\t\t\t \t}\n\t\t\t \tIPAddressSeqRange result = orig;\n\t\t\t \torig = null;\n\t\t\t \treturn result;\n\t\t\t }\n\t\t\t\n\t\t\t @Override\n\t\t\t\tpublic void remove() {\n\t\t\t \tthrow new UnsupportedOperationException();\n\t\t\t }\n\t\t\t};\n\t\t}\n\t\treturn new Iterator<IPAddressSeqRange>() {\n\t\t\tIterator<? extends IPAddress> prefixBlockIterator = prefixBlockIterator(prefixLength);\n\t\t\tprivate boolean first = true;\n\n\t\t\t@Override\n\t\t\tpublic boolean hasNext() {\n\t\t\t\treturn prefixBlockIterator.hasNext();\n\t\t\t}\n\n\t\t @Override\n\t\t\tpublic IPAddressSeqRange next() {\n\t\t \tIPAddress next = prefixBlockIterator.next();\n\t\t \tif(first) {\n\t\t \t\tfirst = false;\n\t\t \t\t// next is a prefix block\n\t\t \t\tIPAddress lower = getLower();\n\t\t \t\tif(hasNext()) {\n\t\t\t \t\tif(!lower.includesZeroHost(prefixLength)) {\n\t\t\t \t\t\treturn create(lower, next.getUpper());\n\t\t\t \t\t}\n\t\t \t\t} else {\n\t\t \t\t\tIPAddress upper = getUpper();\n\t\t \t\t\tif(!lower.includesZeroHost(prefixLength) || !upper.includesMaxHost(prefixLength)) {\n\t\t \t\t\t\treturn create(lower, upper);\n\t\t \t\t\t}\n\t\t \t\t}\n\t\t \t} else if(!hasNext()) {\n\t\t \t\tIPAddress upper = getUpper();\n\t\t \t\tif(!upper.includesMaxHost(prefixLength)) {\n\t\t \t\t\treturn create(next.getLower(), upper);\n\t\t \t\t}\n\t\t \t}\n\t\t \treturn next.toSequentialRange();\n\t\t }\n\t\t\n\t\t @Override\n\t\t\tpublic void remove() {\n\t\t \tthrow new UnsupportedOperationException();\n\t\t }\n\t\t};\n\t}",
"public void saveFile(File file, String type)\n {\n try\n {\n Class<? extends ProjectWriter> fileClass = WRITER_MAP.get(type);\n if (fileClass == null)\n {\n throw new IllegalArgumentException(\"Cannot write files of type: \" + type);\n }\n\n ProjectWriter writer = fileClass.newInstance();\n writer.write(m_projectFile, file);\n }\n\n catch (Exception ex)\n {\n throw new RuntimeException(ex);\n }\n }",
"public <S extends AddressSegment> void getSplitSegments(S segs[], int index, AddressSegmentCreator<S> creator) {\r\n\t\tif(!isMultiple()) {\r\n\t\t\tint bitSizeSplit = IPv6Address.BITS_PER_SEGMENT >>> 1;\r\n\t\t\tInteger myPrefix = getSegmentPrefixLength();\r\n\t\t\tInteger highPrefixBits = getSplitSegmentPrefix(bitSizeSplit, myPrefix, 0);\r\n\t\t\tInteger lowPrefixBits = getSplitSegmentPrefix(bitSizeSplit, myPrefix, 1);\r\n\t\t\tif(index >= 0 && index < segs.length) {\r\n\t\t\t\tsegs[index] = creator.createSegment(highByte(), highPrefixBits);\r\n\t\t\t}\r\n\t\t\tif(++index >= 0 && index < segs.length) {\r\n\t\t\t\tsegs[index] = creator.createSegment(lowByte(), lowPrefixBits);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tgetSplitSegmentsMultiple(segs, index, creator);\r\n\t\t}\r\n\t}",
"public AT_Row setPaddingRightChar(Character paddingRightChar) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingRightChar(paddingRightChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"@Override\n public InternationalFixedDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }",
"public AT_Row setTextAlignment(TextAlignment textAlignment){\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setTextAlignment(textAlignment);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public static List<String> getStoreNames(List<StoreDefinition> list, boolean ignoreViews) {\n List<String> storeNameSet = new ArrayList<String>();\n for(StoreDefinition def: list)\n if(!def.isView() || !ignoreViews)\n storeNameSet.add(def.getName());\n return storeNameSet;\n }",
"private List<Row> createTimeEntryRowList(String shiftData) throws ParseException\n {\n List<Row> list = new ArrayList<Row>();\n String[] shifts = shiftData.split(\",|:\");\n int index = 1;\n while (index < shifts.length)\n {\n index += 2;\n int entryCount = Integer.parseInt(shifts[index]);\n index++;\n\n for (int entryIndex = 0; entryIndex < entryCount; entryIndex++)\n {\n Integer exceptionTypeID = Integer.valueOf(shifts[index + 0]);\n Date startTime = DatatypeConverter.parseBasicTime(shifts[index + 1]);\n Date endTime = DatatypeConverter.parseBasicTime(shifts[index + 2]);\n\n Map<String, Object> map = new HashMap<String, Object>();\n map.put(\"START_TIME\", startTime);\n map.put(\"END_TIME\", endTime);\n map.put(\"EXCEPTIOP\", exceptionTypeID);\n\n list.add(new MapRow(map));\n\n index += 3;\n }\n }\n\n return list;\n }"
] |
Gets the task from in progress map.
@param jobId
the job id
@return the task from in progress map | [
"public ParallelTask getTaskFromInProgressMap(String jobId) {\n if (!inprogressTaskMap.containsKey(jobId))\n return null;\n return inprogressTaskMap.get(jobId);\n }"
] | [
"public void setShortVec(char[] data)\n {\n if (data == null)\n {\n throw new IllegalArgumentException(\"Input data for indices cannot be null\");\n }\n if (getIndexSize() != 2)\n {\n throw new UnsupportedOperationException(\"Cannot update integer indices with char array\");\n }\n if (!NativeIndexBuffer.setShortArray(getNative(), data))\n {\n throw new UnsupportedOperationException(\"Input array is wrong size\");\n }\n }",
"static String[] tokenize(String str) {\n char sep = '.';\n int start = 0;\n int len = str.length();\n int count = 0;\n for (int pos = 0; pos < len; pos++) {\n if (str.charAt(pos) == sep) {\n if (pos != start) {\n count++;\n }\n start = pos + 1;\n }\n }\n if (len != start) {\n count++;\n }\n String[] l = new String[count];\n\n count = 0;\n start = 0;\n for (int pos = 0; pos < len; pos++) {\n if (str.charAt(pos) == sep) {\n if (pos != start) {\n String tok = str.substring(start, pos);\n l[count++] = tok;\n }\n start = pos + 1;\n }\n }\n if (len != start) {\n String tok = str.substring(start);\n l[count/* ++ */] = tok;\n }\n return l;\n }",
"private void readResource(net.sf.mpxj.ganttproject.schema.Resource gpResource)\n {\n Resource mpxjResource = m_projectFile.addResource();\n mpxjResource.setUniqueID(Integer.valueOf(NumberHelper.getInt(gpResource.getId()) + 1));\n mpxjResource.setName(gpResource.getName());\n mpxjResource.setEmailAddress(gpResource.getContacts());\n mpxjResource.setText(1, gpResource.getPhone());\n mpxjResource.setGroup(m_roleDefinitions.get(gpResource.getFunction()));\n\n net.sf.mpxj.ganttproject.schema.Rate gpRate = gpResource.getRate();\n if (gpRate != null)\n {\n mpxjResource.setStandardRate(new Rate(gpRate.getValueAttribute(), TimeUnit.DAYS));\n }\n readResourceCustomFields(gpResource, mpxjResource);\n m_eventManager.fireResourceReadEvent(mpxjResource);\n }",
"public WebSocketContext sendJsonToUser(Object data, String username) {\n return sendToTagged(JSON.toJSONString(data), username);\n }",
"protected Object[] idsOf(final List<?> idsOrValues) {\n // convert list to array that we can mutate\n final Object[] ids = idsOrValues.toArray();\n\n // mutate array to contain only non-empty ids\n int length = 0;\n for (int i = 0; i < ids.length;) {\n final Object p = ids[i++];\n if (p instanceof HasId) {\n // only use values with ids that are non-empty\n final String id = ((HasId) p).getId();\n if (!StringUtils.isEmpty(id)) {\n ids[length++] = id;\n }\n } else if (p instanceof String) {\n // only use ids that are non-empty\n final String id = p.toString();\n if (!StringUtils.isEmpty(id)) {\n ids[length++] = id;\n }\n } else if (p != null) {\n throw new StoreException(\"Invalid id or value of type \" + p);\n }\n }\n\n // no ids in array\n if (length == 0) {\n return null;\n }\n\n // some ids in array\n if (length != ids.length) {\n final Object[] tmp = new Object[length];\n System.arraycopy(ids, 0, tmp, 0, length);\n return tmp;\n }\n\n // array was full\n return ids;\n }",
"public static long bytesToNumber(byte[] buffer, int start, int length) {\n long result = 0;\n for (int index = start; index < start + length; index++) {\n result = (result << 8) + unsign(buffer[index]);\n }\n return result;\n }",
"public static boolean isAvroSchema(String serializerName) {\n if(serializerName.equals(AVRO_GENERIC_VERSIONED_TYPE_NAME)\n || serializerName.equals(AVRO_GENERIC_TYPE_NAME)\n || serializerName.equals(AVRO_REFLECTIVE_TYPE_NAME)\n || serializerName.equals(AVRO_SPECIFIC_TYPE_NAME)) {\n return true;\n } else {\n return false;\n }\n }",
"protected void checkVariableName(GraphRewrite event, EvaluationContext context)\n {\n if (getInputVariablesName() == null)\n {\n setInputVariablesName(Iteration.getPayloadVariableName(event, context));\n }\n }",
"private void parseUsersAuthentication(final XMLExtendedStreamReader reader,\n final ModelNode realmAddress, final List<ModelNode> list)\n throws XMLStreamException {\n final ModelNode usersAddress = realmAddress.clone().add(AUTHENTICATION, USERS);\n list.add(Util.getEmptyOperation(ADD, usersAddress));\n\n while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {\n requireNamespace(reader, namespace);\n final Element element = Element.forName(reader.getLocalName());\n switch (element) {\n case USER: {\n parseUser(reader, usersAddress, list);\n break;\n }\n default: {\n throw unexpectedElement(reader);\n }\n }\n }\n }"
] |
Initializes module enablement.
@see ModuleEnablement | [
"public void createEnablement() {\n GlobalEnablementBuilder builder = beanManager.getServices().get(GlobalEnablementBuilder.class);\n ModuleEnablement enablement = builder.createModuleEnablement(this);\n beanManager.setEnabled(enablement);\n\n if (BootstrapLogger.LOG.isDebugEnabled()) {\n BootstrapLogger.LOG.enabledAlternatives(this.beanManager, WeldCollections.toMultiRowString(enablement.getAllAlternatives()));\n BootstrapLogger.LOG.enabledDecorators(this.beanManager, WeldCollections.toMultiRowString(enablement.getDecorators()));\n BootstrapLogger.LOG.enabledInterceptors(this.beanManager, WeldCollections.toMultiRowString(enablement.getInterceptors()));\n }\n }"
] | [
"@SuppressWarnings(\"boxing\")\r\n public OAuth1Token getAccessToken(OAuth1RequestToken oAuthRequestToken, String verifier) {\r\n OAuth10aService service = new ServiceBuilder(apiKey)\r\n .apiSecret(sharedSecret)\r\n .build(FlickrApi.instance());\r\n\r\n // Flickr seems to return invalid token sometimes so retry a few times.\r\n // See http://www.flickr.com/groups/api/discuss/72157628028927244/\r\n OAuth1Token accessToken = null;\r\n boolean success = false;\r\n for (int i = 0; i < maxGetTokenRetries && !success; i++) {\r\n try {\r\n accessToken = service.getAccessToken(oAuthRequestToken, verifier);\r\n success = true;\r\n } catch (OAuthException | IOException | InterruptedException | ExecutionException e) {\r\n if (i == maxGetTokenRetries - 1) {\r\n logger.error(String.format(\"OAuthService.getAccessToken failing after %d tries, re-throwing exception\", i), e);\r\n throw new FlickrRuntimeException(e);\r\n } else {\r\n logger.warn(String.format(\"OAuthService.getAccessToken failed, try number %d: %s\", i, e.getMessage()));\r\n try {\r\n Thread.sleep(500);\r\n } catch (InterruptedException ie) {\r\n // Do nothing\r\n }\r\n }\r\n }\r\n }\r\n\r\n return accessToken;\r\n }",
"public <T extends CanvasWriter> T getWriter(Class<T> type, OauthToken oauthToken, Boolean serializeNulls) {\n LOG.debug(\"Factory call to instantiate class: \" + type.getName());\n RestClient restClient = new RefreshingRestClient();\n\n @SuppressWarnings(\"unchecked\")\n Class<T> concreteClass = (Class<T>) writerMap.get(type);\n\n if (concreteClass == null) {\n throw new UnsupportedOperationException(\"No implementation for requested interface found: \" + type.getName());\n }\n\n LOG.debug(\"got writer class: \" + concreteClass);\n try {\n Constructor<T> constructor = concreteClass.getConstructor(String.class, Integer.class, OauthToken.class,\n RestClient.class, Integer.TYPE, Integer.TYPE, Integer.class, Boolean.class);\n return constructor.newInstance(canvasBaseUrl, CANVAS_API_VERSION, oauthToken, restClient,\n connectTimeout, readTimeout, null, serializeNulls);\n } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) {\n throw new UnsupportedOperationException(\"Unknown error instantiating the concrete API class: \" + type.getName(), e);\n }\n }",
"private void createTasks(ChildTaskContainer parent, String parentName, List<Row> rows)\n {\n for (Row row : rows)\n {\n boolean rowIsBar = (row.getInteger(\"BARID\") != null);\n\n //\n // Don't export hammock tasks.\n //\n if (rowIsBar && row.getChildRows().isEmpty())\n {\n continue;\n }\n\n Task task = parent.addTask();\n\n //\n // Do we have a bar, task, or milestone?\n //\n if (rowIsBar)\n {\n //\n // If the bar only has one child task, we skip it and add the task directly\n //\n if (skipBar(row))\n {\n populateLeaf(row.getString(\"NAMH\"), row.getChildRows().get(0), task);\n }\n else\n {\n populateBar(row, task);\n createTasks(task, task.getName(), row.getChildRows());\n }\n }\n else\n {\n populateLeaf(parentName, row, task);\n }\n\n m_eventManager.fireTaskReadEvent(task);\n }\n }",
"private void 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 static base_response export(nitro_service client, application resource) throws Exception {\n\t\tapplication exportresource = new application();\n\t\texportresource.appname = resource.appname;\n\t\texportresource.apptemplatefilename = resource.apptemplatefilename;\n\t\texportresource.deploymentfilename = resource.deploymentfilename;\n\t\treturn exportresource.perform_operation(client,\"export\");\n\t}",
"private Integer getFrequency(Project.Calendars.Calendar.Exceptions.Exception exception)\n {\n Integer period = NumberHelper.getInteger(exception.getPeriod());\n if (period == null)\n {\n period = Integer.valueOf(1);\n }\n return period;\n }",
"private void copyToStrBuffer(byte[] buffer, int offset, int length) {\n Preconditions.checkArgument(length >= 0);\n if (strBuffer.length - strBufferIndex < length) {\n // cannot fit, expanding buffer\n expandStrBuffer(length);\n }\n System.arraycopy(\n buffer, offset, strBuffer, strBufferIndex, Math.min(length, MAX_ALLOWABLE_BUFFER_SIZE - strBufferIndex));\n strBufferIndex += length;\n }",
"public boolean removeCustomResponse(String pathValue, String requestType) {\n try {\n JSONObject path = getPathFromEndpoint(pathValue, requestType);\n if (path == null) {\n return false;\n }\n String pathId = path.getString(\"pathId\");\n return resetResponseOverride(pathId);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }",
"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 }"
] |
Apply the matching client UUID for the request
@param httpServletRequest
@param history | [
"private void processClientId(HttpServletRequest httpServletRequest, History history) {\n // get the client id from the request header if applicable.. otherwise set to default\n // also set the client uuid in the history object\n if (httpServletRequest.getHeader(Constants.PROFILE_CLIENT_HEADER_NAME) != null &&\n !httpServletRequest.getHeader(Constants.PROFILE_CLIENT_HEADER_NAME).equals(\"\")) {\n history.setClientUUID(httpServletRequest.getHeader(Constants.PROFILE_CLIENT_HEADER_NAME));\n } else {\n history.setClientUUID(Constants.PROFILE_CLIENT_DEFAULT_ID);\n }\n logger.info(\"Client UUID is: {}\", history.getClientUUID());\n }"
] | [
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public static void changeCredentials(String accountID, String token, String region) {\n if(defaultConfig != null){\n Logger.i(\"CleverTap SDK already initialized with accountID:\"+defaultConfig.getAccountId()\n +\" and token:\"+defaultConfig.getAccountToken()+\". Cannot change credentials to \"\n + accountID + \" and \" + token);\n return;\n }\n\n ManifestInfo.changeCredentials(accountID,token,region);\n }",
"public Replication targetOauth(String consumerSecret, String consumerKey, String tokenSecret,\n String token) {\n targetOauth = new JsonObject();\n this.consumerSecret = consumerSecret;\n this.consumerKey = consumerKey;\n this.tokenSecret = tokenSecret;\n this.token = token;\n return this;\n }",
"public static base_responses update(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 updateresources[] = new autoscaleaction[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new autoscaleaction();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].profilename = resources[i].profilename;\n\t\t\t\tupdateresources[i].parameters = resources[i].parameters;\n\t\t\t\tupdateresources[i].vmdestroygraceperiod = resources[i].vmdestroygraceperiod;\n\t\t\t\tupdateresources[i].quiettime = resources[i].quiettime;\n\t\t\t\tupdateresources[i].vserver = resources[i].vserver;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public SslHandler create(ByteBufAllocator bufferAllocator) {\n SSLEngine engine = sslContext.newEngine(bufferAllocator);\n engine.setNeedClientAuth(needClientAuth);\n engine.setUseClientMode(false);\n return new SslHandler(engine);\n }",
"public void setGlobal(int pathId, Boolean global) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + Constants.PATH_PROFILE_GLOBAL + \" = ? \" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setBoolean(1, global);\n statement.setInt(2, pathId);\n statement.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }",
"public MaterialSection getSectionByTitle(String title) {\n\n for(MaterialSection section : sectionList) {\n if(section.getTitle().equals(title)) {\n return section;\n }\n }\n\n for(MaterialSection section : bottomSectionList) {\n if(section.getTitle().equals(title))\n return section;\n }\n\n return null;\n }",
"public String convertFromJavaString(String string, boolean useUnicode) {\n\t\tint firstEscapeSequence = string.indexOf('\\\\');\n\t\tif (firstEscapeSequence == -1) {\n\t\t\treturn string;\n\t\t}\n\t\tint length = string.length();\n\t\tStringBuilder result = new StringBuilder(length);\n\t\tappendRegion(string, 0, firstEscapeSequence, result);\n\t\treturn convertFromJavaString(string, useUnicode, firstEscapeSequence, result);\n\t}",
"private TimeUnit getFormat(int format)\n {\n TimeUnit result;\n if (format == 0xFFFF)\n {\n result = TimeUnit.HOURS;\n }\n else\n {\n result = MPPUtility.getWorkTimeUnits(format);\n }\n return result;\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 }"
] |
Takes an object and converts it to a string.
@param mapper the object mapper
@param object the object to convert
@return json string | [
"public static String stringify(ObjectMapper mapper, Object object) {\n try {\n return mapper.writeValueAsString(object);\n } catch (JsonProcessingException e) {\n throw new IllegalArgumentException(e);\n }\n }"
] | [
"public static Expression type(String lhs, Type rhs) {\n return new Expression(lhs, \"$type\", rhs.toString());\n }",
"public static base_response update(nitro_service client, lbsipparameters resource) throws Exception {\n\t\tlbsipparameters updateresource = new lbsipparameters();\n\t\tupdateresource.rnatsrcport = resource.rnatsrcport;\n\t\tupdateresource.rnatdstport = resource.rnatdstport;\n\t\tupdateresource.retrydur = resource.retrydur;\n\t\tupdateresource.addrportvip = resource.addrportvip;\n\t\tupdateresource.sip503ratethreshold = resource.sip503ratethreshold;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public static auditnslogpolicy_systemglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditnslogpolicy_systemglobal_binding obj = new auditnslogpolicy_systemglobal_binding();\n\t\tobj.set_name(name);\n\t\tauditnslogpolicy_systemglobal_binding response[] = (auditnslogpolicy_systemglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static snmpalarm get(nitro_service service, String trapname) throws Exception{\n\t\tsnmpalarm obj = new snmpalarm();\n\t\tobj.set_trapname(trapname);\n\t\tsnmpalarm response = (snmpalarm) obj.get_resource(service);\n\t\treturn response;\n\t}",
"okhttp3.Response delete(String url, Map<String, Object> params)\n throws RequestException, LocalOperationException {\n okhttp3.Request request = new okhttp3.Request.Builder()\n .url(getFullUrl(url))\n .delete(getBody(toPayload(params), null))\n .addHeader(\"Transloadit-Client\", version)\n .build();\n\n try {\n return httpClient.newCall(request).execute();\n } catch (IOException e) {\n throw new RequestException(e);\n }\n }",
"public static Enum castToEnum(Object object, Class<? extends Enum> type) {\n if (object==null) return null;\n if (type.isInstance(object)) return (Enum) object;\n if (object instanceof String || object instanceof GString) {\n return Enum.valueOf(type, object.toString());\n }\n throw new GroovyCastException(object, type);\n }",
"public static nsacl6_stats get(nitro_service service, String acl6name) throws Exception{\n\t\tnsacl6_stats obj = new nsacl6_stats();\n\t\tobj.set_acl6name(acl6name);\n\t\tnsacl6_stats response = (nsacl6_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"public Object copy(Object obj, PersistenceBroker broker)\r\n\t\t\tthrows ObjectCopyException\r\n\t{\r\n\t\tif (obj instanceof OjbCloneable)\r\n\t\t{\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\treturn ((OjbCloneable) obj).ojbClone();\r\n\t\t\t}\r\n\t\t\tcatch (Exception e)\r\n\t\t\t{\r\n\t\t\t\tthrow new ObjectCopyException(e);\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tthrow new ObjectCopyException(\"Object must implement OjbCloneable in order to use the\"\r\n\t\t\t\t\t\t\t\t\t\t + \" CloneableObjectCopyStrategy\");\r\n\t\t}\r\n\t}",
"public <T> Method getSetMethod(final Object object, final String fieldName, final Class<?> argumentType) {\n\t\tif( object == null ) {\n\t\t\tthrow new NullPointerException(\"object should not be null\");\n\t\t} else if( fieldName == null ) {\n\t\t\tthrow new NullPointerException(\"fieldName should not be null\");\n\t\t} else if( argumentType == null ) {\n\t\t\tthrow new NullPointerException(\"argumentType should not be null\");\n\t\t}\n\t\t\n\t\tMethod method = setMethodsCache.get(object.getClass(), argumentType, fieldName);\n\t\tif( method == null ) {\n\t\t\tmethod = ReflectionUtils.findSetter(object, fieldName, argumentType);\n\t\t\tsetMethodsCache.set(object.getClass(), argumentType, fieldName, method);\n\t\t}\n\t\treturn method;\n\t}"
] |
Creates a converter function that converts value using a constructor that accepts a single String argument.
@return A converter function or {@code null} if the given type doesn't have a public constructor that accepts
a single String argument. | [
"private static Converter<List<String>, Object> createStringConstructorConverter(Class<?> resultClass) {\n try {\n final Constructor<?> constructor = resultClass.getConstructor(String.class);\n return new BasicConverter(defaultValue(resultClass)) {\n @Override\n protected Object convert(String value) throws Exception {\n return constructor.newInstance(value);\n }\n };\n } catch (Exception e) {\n return null;\n }\n }"
] | [
"public static StringBuffer leftShift(String self, Object value) {\n return new StringBuffer(self).append(value);\n }",
"private void parseLdapAuthorization_1_5(final XMLExtendedStreamReader reader,\n final ModelNode realmAddress, final List<ModelNode> list) throws XMLStreamException {\n ModelNode addr = realmAddress.clone().add(AUTHORIZATION, LDAP);\n ModelNode ldapAuthorization = Util.getEmptyOperation(ADD, addr);\n\n list.add(ldapAuthorization);\n\n Set<Attribute> required = EnumSet.of(Attribute.CONNECTION);\n final int count = reader.getAttributeCount();\n for (int i = 0; i < count; i++) {\n final String value = reader.getAttributeValue(i);\n if (!isNoNamespaceAttribute(reader, i)) {\n throw unexpectedAttribute(reader, i);\n } else {\n final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));\n required.remove(attribute);\n switch (attribute) {\n case CONNECTION: {\n LdapAuthorizationResourceDefinition.CONNECTION.parseAndSetParameter(value, ldapAuthorization, reader);\n break;\n }\n default: {\n throw unexpectedAttribute(reader, i);\n }\n }\n }\n }\n\n if (required.isEmpty() == false) {\n throw missingRequired(reader, required);\n }\n\n Set<Element> foundElements = new HashSet<Element>();\n while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {\n requireNamespace(reader, namespace);\n final Element element = Element.forName(reader.getLocalName());\n if (foundElements.add(element) == false) {\n throw unexpectedElement(reader); // Only one of each allowed.\n }\n switch (element) {\n case USERNAME_TO_DN: {\n switch (namespace.getMajorVersion()) {\n case 1: // 1.5 up to but not including 2.0\n parseUsernameToDn_1_5(reader, addr, list);\n break;\n default: // 2.0 and onwards\n parseUsernameToDn_2_0(reader, addr, list);\n break;\n }\n\n break;\n }\n case GROUP_SEARCH: {\n switch (namespace) {\n case DOMAIN_1_5:\n case DOMAIN_1_6:\n parseGroupSearch_1_5(reader, addr, list);\n break;\n default:\n parseGroupSearch_1_7_and_2_0(reader, addr, list);\n break;\n }\n break;\n }\n default: {\n throw unexpectedElement(reader);\n }\n }\n }\n }",
"public void process()\n {\n if (m_data != null)\n {\n int index = 0;\n int offset = 0;\n // First the length (repeated twice)\n int length = MPPUtility.getInt(m_data, offset);\n offset += 8;\n // Then the number of custom columns\n int numberOfAliases = MPPUtility.getInt(m_data, offset);\n offset += 4;\n\n // Then the aliases themselves\n while (index < numberOfAliases && offset < length)\n {\n // Each item consists of the Field ID (2 bytes), 40 0B marker (2 bytes), and the\n // offset to the string (4 bytes)\n\n // Get the Field ID\n int fieldID = MPPUtility.getInt(m_data, offset);\n offset += 4;\n // Get the alias offset (offset + 4 for some reason).\n int aliasOffset = MPPUtility.getInt(m_data, offset) + 4;\n offset += 4;\n // Read the alias itself\n if (aliasOffset < m_data.length)\n {\n String alias = MPPUtility.getUnicodeString(m_data, aliasOffset);\n m_fields.getCustomField(FieldTypeHelper.getInstance(fieldID)).setAlias(alias);\n }\n index++;\n }\n }\n }",
"private void processQueue()\r\n {\r\n CacheEntry sv;\r\n while((sv = (CacheEntry) queue.poll()) != null)\r\n {\r\n sessionCache.remove(sv.oid);\r\n }\r\n }",
"public void addEvent(Event event) {\n if(event == null)\n throw new IllegalStateException(\"event must be non-null\");\n\n if(logger.isTraceEnabled())\n logger.trace(\"Adding event \" + event);\n\n eventQueue.add(event);\n }",
"private boolean initCheckTypeModifiers() {\n\n Class<?> classInfoclass = Reflections.loadClass(CLASSINFO_CLASS_NAME, new ClassLoaderResourceLoader(classFileServices.getClass().getClassLoader()));\n if (classInfoclass != null) {\n try {\n Method setFlags = AccessController.doPrivileged(GetDeclaredMethodAction.of(classInfoclass, \"setFlags\", short.class));\n return setFlags != null;\n } catch (Exception exceptionIgnored) {\n BootstrapLogger.LOG.usingOldJandexVersion();\n return false;\n }\n } else {\n return true;\n }\n }",
"protected Connection newConnectionFromDriverManager(JdbcConnectionDescriptor jcd)\r\n throws LookupException\r\n {\r\n Connection retval = null;\r\n // use JDBC DriverManager\r\n final String driver = jcd.getDriver();\r\n final String url = getDbURL(jcd);\r\n try\r\n {\r\n // loads the driver - NB call to newInstance() added to force initialisation\r\n ClassHelper.getClass(driver, true);\r\n final String user = jcd.getUserName();\r\n final String password = jcd.getPassWord();\r\n final Properties properties = getJdbcProperties(jcd, user, password);\r\n if (properties.isEmpty())\r\n {\r\n if (user == null)\r\n {\r\n retval = DriverManager.getConnection(url);\r\n }\r\n else\r\n {\r\n retval = DriverManager.getConnection(url, user, password);\r\n }\r\n }\r\n else\r\n {\r\n retval = DriverManager.getConnection(url, properties);\r\n }\r\n }\r\n catch (SQLException sqlEx)\r\n {\r\n log.error(\"Error getting Connection from DriverManager with url (\" + url + \") and driver (\" + driver + \")\", sqlEx);\r\n throw new LookupException(\"Error getting Connection from DriverManager with url (\" + url + \") and driver (\" + driver + \")\", sqlEx);\r\n }\r\n catch (ClassNotFoundException cnfEx)\r\n {\r\n log.error(cnfEx);\r\n throw new LookupException(\"A class was not found\", cnfEx);\r\n }\r\n catch (Exception e)\r\n {\r\n log.error(\"Instantiation of jdbc driver failed\", e);\r\n throw new LookupException(\"Instantiation of jdbc driver failed\", e);\r\n }\r\n // initialize connection\r\n initializeJdbcConnection(retval, jcd);\r\n if(log.isDebugEnabled()) log.debug(\"Create new connection using DriverManager: \"+retval);\r\n return retval;\r\n }",
"public static int cudnnGetReductionIndicesSize(\n cudnnHandle handle, \n cudnnReduceTensorDescriptor reduceTensorDesc, \n cudnnTensorDescriptor aDesc, \n cudnnTensorDescriptor cDesc, \n long[] sizeInBytes)\n {\n return checkResult(cudnnGetReductionIndicesSizeNative(handle, reduceTensorDesc, aDesc, cDesc, sizeInBytes));\n }",
"public boolean doSyncPass() {\n if (!this.isConfigured || !syncLock.tryLock()) {\n return false;\n }\n try {\n if (logicalT == Long.MAX_VALUE) {\n if (logger.isInfoEnabled()) {\n logger.info(\"reached max logical time; resetting back to 0\");\n }\n logicalT = 0;\n }\n logicalT++;\n\n if (logger.isInfoEnabled()) {\n logger.info(String.format(\n Locale.US,\n \"t='%d': doSyncPass START\",\n logicalT));\n }\n if (networkMonitor == null || !networkMonitor.isConnected()) {\n if (logger.isInfoEnabled()) {\n logger.info(String.format(\n Locale.US,\n \"t='%d': doSyncPass END - Network disconnected\",\n logicalT));\n }\n return false;\n }\n if (authMonitor == null || !authMonitor.tryIsLoggedIn()) {\n if (logger.isInfoEnabled()) {\n logger.info(String.format(\n Locale.US,\n \"t='%d': doSyncPass END - Logged out\",\n logicalT));\n }\n return false;\n }\n\n syncRemoteToLocal();\n syncLocalToRemote();\n\n if (logger.isInfoEnabled()) {\n logger.info(String.format(\n Locale.US,\n \"t='%d': doSyncPass END\",\n logicalT));\n }\n } catch (InterruptedException e) {\n if (logger.isInfoEnabled()) {\n logger.info(String.format(\n Locale.US,\n \"t='%d': doSyncPass INTERRUPTED\",\n logicalT));\n }\n return false;\n } finally {\n syncLock.unlock();\n }\n return true;\n }"
] |
Process calendar hours.
@param calendar parent calendar
@param row calendar hours data
@param dayIndex day index | [
"private void processCalendarHours(ProjectCalendar calendar, Row row, int dayIndex)\n {\n Day day = Day.getInstance(dayIndex);\n boolean working = row.getInt(\"CD_WORKING\") != 0;\n calendar.setWorkingDay(day, working);\n if (working == true)\n {\n ProjectCalendarHours hours = calendar.addCalendarHours(day);\n\n Date start = row.getDate(\"CD_FROM_TIME1\");\n Date end = row.getDate(\"CD_TO_TIME1\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME2\");\n end = row.getDate(\"CD_TO_TIME2\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME3\");\n end = row.getDate(\"CD_TO_TIME3\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME4\");\n end = row.getDate(\"CD_TO_TIME4\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME5\");\n end = row.getDate(\"CD_TO_TIME5\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n }\n }"
] | [
"void fileWritten() throws ConfigurationPersistenceException {\n if (!doneBootup.get() || interactionPolicy.isReadOnly()) {\n return;\n }\n try {\n FilePersistenceUtils.copyFile(mainFile, lastFile);\n } catch (IOException e) {\n throw ControllerLogger.ROOT_LOGGER.failedToBackup(e, mainFile);\n }\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 }",
"public static clusterinstance_binding get(nitro_service service, Long clid) throws Exception{\n\t\tclusterinstance_binding obj = new clusterinstance_binding();\n\t\tobj.set_clid(clid);\n\t\tclusterinstance_binding response = (clusterinstance_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public RandomVariableInterface[] getBasisFunctions(double exerciseDate, LIBORModelMonteCarloSimulationInterface model) throws CalculationException {\n\n\t\tArrayList<RandomVariableInterface> basisFunctions = new ArrayList<RandomVariableInterface>();\n\n\t\tRandomVariableInterface basisFunction;\n\n\t\t// Constant\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tbasisFunctions.add(basisFunction);\n\n\t\t// LIBORs\n\t\tint liborPeriodIndex, liborPeriodIndexEnd;\n\t\tRandomVariableInterface rate;\n\n\t\t// 1 Period\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tliborPeriodIndex = model.getLiborPeriodIndex(exerciseDate);\n\t\tif(liborPeriodIndex < 0) {\n\t\t\tliborPeriodIndex = -liborPeriodIndex-1;\n\t\t}\n\t\tliborPeriodIndexEnd = liborPeriodIndex+1;\n\t\tdouble periodLength1 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex);\n\n\t\trate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd));\n\t\tbasisFunction = basisFunction.discount(rate, periodLength1);\n\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\tbasisFunction = basisFunction.discount(rate, periodLength1);\n\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t// n/2 Period\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tliborPeriodIndex = model.getLiborPeriodIndex(exerciseDate);\n\t\tif(liborPeriodIndex < 0) {\n\t\t\tliborPeriodIndex = -liborPeriodIndex-1;\n\t\t}\n\t\tliborPeriodIndexEnd = (liborPeriodIndex + model.getNumberOfLibors())/2;\n\n\t\tdouble periodLength2 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex);\n\n\t\tif(periodLength2 != periodLength1) {\n\t\t\trate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd));\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength2);\n\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength2);\n\t\t\t//\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength2);\n\t\t\t//\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\t\t}\n\n\n\t\t// n Period\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tliborPeriodIndex = model.getLiborPeriodIndex(exerciseDate);\n\t\tif(liborPeriodIndex < 0) {\n\t\t\tliborPeriodIndex = -liborPeriodIndex-1;\n\t\t}\n\t\tliborPeriodIndexEnd = model.getNumberOfLibors();\n\t\tdouble periodLength3 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex);\n\n\t\tif(periodLength3 != periodLength1 && periodLength3 != periodLength2) {\n\t\t\trate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd));\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength3);\n\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength3);\n\t\t\t//\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\t\t}\n\n\t\treturn basisFunctions.toArray(new RandomVariableInterface[0]);\n\t}",
"public static base_response unset(nitro_service client, rnatparam resource, String[] args) throws Exception{\n\t\trnatparam unsetresource = new rnatparam();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"private void handleUpdate(final int player) {\n final TrackMetadata metadata = MetadataFinder.getInstance().getLatestMetadataFor(player);\n final WaveformDetail waveformDetail = WaveformFinder.getInstance().getLatestDetailFor(player);\n final BeatGrid beatGrid = BeatGridFinder.getInstance().getLatestBeatGridFor(player);\n if (metadata != null && waveformDetail != null && beatGrid != null) {\n final String signature = computeTrackSignature(metadata.getTitle(), metadata.getArtist(),\n metadata.getDuration(), waveformDetail, beatGrid);\n if (signature != null) {\n signatures.put(player, signature);\n deliverSignatureUpdate(player, signature);\n }\n }\n }",
"public Date toDate(Object date) {\n\n Date d = null;\n if (null != date) {\n if (date instanceof Date) {\n d = (Date)date;\n } else if (date instanceof Long) {\n d = new Date(((Long)date).longValue());\n } else {\n try {\n long l = Long.parseLong(date.toString());\n d = new Date(l);\n } catch (Exception e) {\n // do nothing, just let d remain null\n }\n }\n }\n return d;\n }",
"public static wisite_farmname_binding[] get(nitro_service service, String sitepath) throws Exception{\n\t\twisite_farmname_binding obj = new wisite_farmname_binding();\n\t\tobj.set_sitepath(sitepath);\n\t\twisite_farmname_binding response[] = (wisite_farmname_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public BoxTaskAssignment.Info addAssignment(BoxUser assignTo) {\n JsonObject taskJSON = new JsonObject();\n taskJSON.add(\"type\", \"task\");\n taskJSON.add(\"id\", this.getID());\n\n JsonObject assignToJSON = new JsonObject();\n assignToJSON.add(\"id\", assignTo.getID());\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"task\", taskJSON);\n requestJSON.add(\"assign_to\", assignToJSON);\n\n URL url = ADD_TASK_ASSIGNMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxTaskAssignment addedAssignment = new BoxTaskAssignment(this.getAPI(), responseJSON.get(\"id\").asString());\n return addedAssignment.new Info(responseJSON);\n }"
] |
Processes and computes column counts of A
@param A (Input) Upper triangular matrix
@param parent (Input) Elimination tree.
@param post (Input) Post order permutation of elimination tree. See {@link TriangularSolver_DSCC#postorder}
@param counts (Output) Storage for column counts. | [
"public void process(DMatrixSparseCSC A , int parent[], int post[], int counts[] ) {\n if( counts.length < A.numCols )\n throw new IllegalArgumentException(\"counts must be at least of length A.numCols\");\n\n initialize(A);\n\n int delta[] = counts;\n findFirstDescendant(parent, post, delta);\n\n if( ata ) {\n init_ata(post);\n }\n for (int i = 0; i < n; i++)\n w[ancestor+i] = i;\n\n int[] ATp = At.col_idx; int []ATi = At.nz_rows;\n\n for (int k = 0; k < n; k++) {\n int j = post[k];\n if( parent[j] != -1 )\n delta[parent[j]]--; // j is not a root\n for (int J = HEAD(k,j); J != -1; J = NEXT(J)) {\n for (int p = ATp[J]; p < ATp[J+1]; p++) {\n int i = ATi[p];\n int q = isLeaf(i,j);\n if( jleaf >= 1)\n delta[j]++;\n if( jleaf == 2 )\n delta[q]--;\n }\n }\n if( parent[j] != -1 )\n w[ancestor+j] = parent[j];\n }\n\n // sum up delta's of each child\n for ( int j = 0; j < n; j++) {\n if( parent[j] != -1)\n counts[parent[j]] += counts[j];\n }\n }"
] | [
"public void start() {\n syncLock.lock();\n try {\n if (!this.isConfigured) {\n return;\n }\n instanceChangeStreamListener.stop();\n if (listenersEnabled) {\n instanceChangeStreamListener.start();\n }\n\n if (syncThread == null) {\n syncThread = new Thread(\n new DataSynchronizerRunner(\n new WeakReference<>(this),\n networkMonitor,\n logger\n ),\n \"dataSynchronizerRunnerThread\"\n );\n }\n if (syncThreadEnabled && !isRunning) {\n syncThread.start();\n isRunning = true;\n }\n } finally {\n syncLock.unlock();\n }\n }",
"public static MapBounds adjustBoundsToScaleAndMapSize(\n final GenericMapAttributeValues mapValues,\n final Rectangle paintArea,\n final MapBounds bounds,\n final double dpi) {\n MapBounds newBounds = bounds;\n if (mapValues.isUseNearestScale()) {\n newBounds = newBounds.adjustBoundsToNearestScale(\n mapValues.getZoomLevels(),\n mapValues.getZoomSnapTolerance(),\n mapValues.getZoomLevelSnapStrategy(),\n mapValues.getZoomSnapGeodetic(),\n paintArea, dpi);\n }\n\n newBounds = new BBoxMapBounds(newBounds.toReferencedEnvelope(paintArea));\n\n if (mapValues.isUseAdjustBounds()) {\n newBounds = newBounds.adjustedEnvelope(paintArea);\n }\n return newBounds;\n }",
"public static String getGalleryNotFoundKey(String gallery) {\n\n StringBuffer sb = new StringBuffer(ERROR_REASON_NO_PREFIX);\n sb.append(gallery.toUpperCase());\n sb.append(GUI_TITLE_POSTFIX);\n return sb.toString();\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 base_response unset(nitro_service client, sslservice resource, String[] args) throws Exception{\n\t\tsslservice unsetresource = new sslservice();\n\t\tunsetresource.servicename = resource.servicename;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public static String extractFromResourceId(String id, String identifier) {\n if (id == null || identifier == null) {\n return id;\n }\n Pattern pattern = Pattern.compile(identifier + \"/[-\\\\w._]+\");\n Matcher matcher = pattern.matcher(id);\n if (matcher.find()) {\n return matcher.group().split(\"/\")[1];\n } else {\n return null;\n }\n }",
"public double Function1D(double x) {\n return Math.exp(x * x / (-2 * sqrSigma)) / (Math.sqrt(2 * Math.PI) * sigma);\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 }",
"public static base_responses delete(nitro_service client, nsip6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsip6 deleteresources[] = new nsip6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new nsip6();\n\t\t\t\tdeleteresources[i].ipv6address = resources[i].ipv6address;\n\t\t\t\tdeleteresources[i].td = resources[i].td;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}"
] |
Remove colProxy from list of pending collections and
register its contents with the transaction. | [
"public void afterLoading(CollectionProxyDefaultImpl colProxy)\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"loading a proxied collection a collection: \" + colProxy);\r\n Collection data = colProxy.getData();\r\n for (Iterator iterator = data.iterator(); iterator.hasNext();)\r\n {\r\n Object o = iterator.next();\r\n if(!isOpen())\r\n {\r\n log.error(\"Collection proxy materialization outside of a running tx, obj=\" + o);\r\n try{throw new Exception(\"Collection proxy materialization outside of a running tx, obj=\" + o);}\r\n catch(Exception e)\r\n {e.printStackTrace();}\r\n }\r\n else\r\n {\r\n Identity oid = getBroker().serviceIdentity().buildIdentity(o);\r\n ClassDescriptor cld = getBroker().getClassDescriptor(ProxyHelper.getRealClass(o));\r\n RuntimeObject rt = new RuntimeObject(o, oid, cld, false, ProxyHelper.isProxy(o));\r\n lockAndRegister(rt, Transaction.READ, isImplicitLocking(), getRegistrationList());\r\n }\r\n }\r\n unregisterFromCollectionProxy(colProxy);\r\n }"
] | [
"public double distanceSquared(Vector3d v) {\n double dx = x - v.x;\n double dy = y - v.y;\n double dz = z - v.z;\n\n return dx * dx + dy * dy + dz * dz;\n }",
"private static OriginatorType mapOriginator(Originator originator) {\n if (originator == null) {\n return null;\n }\n OriginatorType origType = new OriginatorType();\n origType.setProcessId(originator.getProcessId());\n origType.setIp(originator.getIp());\n origType.setHostname(originator.getHostname());\n origType.setCustomId(originator.getCustomId());\n origType.setPrincipal(originator.getPrincipal());\n return origType;\n }",
"private void deleteDir(File dir)\r\n {\r\n if (dir.exists() && dir.isDirectory())\r\n {\r\n File[] files = dir.listFiles();\r\n\r\n for (int idx = 0; idx < files.length; idx++)\r\n {\r\n if (!files[idx].exists())\r\n {\r\n continue;\r\n }\r\n if (files[idx].isDirectory())\r\n {\r\n deleteDir(files[idx]);\r\n }\r\n else\r\n {\r\n files[idx].delete();\r\n }\r\n }\r\n dir.delete();\r\n }\r\n }",
"protected void writeBody(HttpURLConnection connection, ProgressListener listener) {\n if (this.body == null) {\n return;\n }\n\n connection.setDoOutput(true);\n try {\n OutputStream output = connection.getOutputStream();\n if (listener != null) {\n output = new ProgressOutputStream(output, listener, this.bodyLength);\n }\n int b = this.body.read();\n while (b != -1) {\n output.write(b);\n b = this.body.read();\n }\n output.close();\n } catch (IOException e) {\n throw new BoxAPIException(\"Couldn't connect to the Box API due to a network error.\", e);\n }\n }",
"private ReferenceDescriptorDef usedByReference(ModelDef modelDef, FieldDescriptorDef fieldDef)\r\n {\r\n String ownerClassName = ((ClassDescriptorDef)fieldDef.getOwner()).getQualifiedName();\r\n ClassDescriptorDef classDef;\r\n ReferenceDescriptorDef refDef;\r\n String targetClassName;\r\n\r\n // only relevant for primarykey fields\r\n if (PropertyHelper.toBoolean(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_PRIMARYKEY), false))\r\n {\r\n for (Iterator classIt = modelDef.getClasses(); classIt.hasNext();)\r\n {\r\n classDef = (ClassDescriptorDef)classIt.next();\r\n for (Iterator refIt = classDef.getReferences(); refIt.hasNext();)\r\n {\r\n refDef = (ReferenceDescriptorDef)refIt.next();\r\n targetClassName = refDef.getProperty(PropertyHelper.OJB_PROPERTY_CLASS_REF).replace('$', '.');\r\n if (ownerClassName.equals(targetClassName))\r\n {\r\n // the field is a primary key of the class referenced by this reference descriptor\r\n return refDef;\r\n }\r\n }\r\n }\r\n }\r\n return null;\r\n }",
"public int getIndexByDate(Date date)\n {\n int result = -1;\n int index = 0;\n\n for (CostRateTableEntry entry : this)\n {\n if (DateHelper.compare(date, entry.getEndDate()) < 0)\n {\n result = index;\n break;\n }\n ++index;\n }\n\n return result;\n }",
"private void unmarshalDescriptor() throws CmsXmlException, CmsException {\n\n if (null != m_desc) {\n\n // unmarshal descriptor\n m_descContent = CmsXmlContentFactory.unmarshal(m_cms, m_cms.readFile(m_desc));\n\n // configure messages if wanted\n CmsProperty bundleProp = m_cms.readPropertyObject(m_desc, PROPERTY_BUNDLE_DESCRIPTOR_LOCALIZATION, true);\n if (!(bundleProp.isNullProperty() || bundleProp.getValue().trim().isEmpty())) {\n m_configuredBundle = bundleProp.getValue();\n }\n }\n\n }",
"protected void setBeanStore(BoundBeanStore beanStore) {\n if (beanStore == null) {\n this.beanStore.remove();\n } else {\n this.beanStore.set(beanStore);\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 }"
] |
Producers returned from this method are not validated. Internal use only. | [
"@Override\n public <T> Producer<T> createProducer(final Bean<X> declaringBean, final Bean<T> bean, DisposalMethod<X, T> disposalMethod) {\n EnhancedAnnotatedField<T, X> enhancedField = getManager().getServices().get(MemberTransformer.class).loadEnhancedMember(field, getManager().getId());\n return new ProducerFieldProducer<X, T>(enhancedField, disposalMethod) {\n\n @Override\n public AnnotatedField<X> getAnnotated() {\n return field;\n }\n\n @Override\n public BeanManagerImpl getBeanManager() {\n return getManager();\n }\n\n @Override\n public Bean<X> getDeclaringBean() {\n return declaringBean;\n }\n\n @Override\n public Bean<T> getBean() {\n return bean;\n }\n };\n }"
] | [
"protected void threadWatch(final ConnectionHandle c) {\r\n\t\tthis.threadFinalizableRefs.put(c, new FinalizableWeakReference<Thread>(Thread.currentThread(), this.finalizableRefQueue) {\r\n\t\t\tpublic void finalizeReferent() {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tif (!CachedConnectionStrategy.this.pool.poolShuttingDown){\r\n\t\t\t\t\t\t\tlogger.debug(\"Monitored thread is dead, closing off allocated connection.\");\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tc.internalClose();\r\n\t\t\t\t\t} catch (SQLException e) {\r\n\t\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t\t}\r\n\t\t\t\t\tCachedConnectionStrategy.this.threadFinalizableRefs.remove(c);\r\n\t\t\t}\r\n\t\t});\r\n\t}",
"public void updateSchema(String migrationPath) {\n try {\n logger.info(\"Updating schema... \");\n int current_version = 0;\n\n // first check the current schema version\n HashMap<String, Object> configuration = getFirstResult(\"SELECT * FROM \" + Constants.DB_TABLE_CONFIGURATION +\n \" WHERE \" + Constants.DB_TABLE_CONFIGURATION_NAME + \" = \\'\" + Constants.DB_TABLE_CONFIGURATION_DATABASE_VERSION + \"\\'\");\n\n if (configuration == null) {\n logger.info(\"Creating configuration table..\");\n // create configuration table\n executeUpdate(\"CREATE TABLE \"\n + Constants.DB_TABLE_CONFIGURATION\n + \" (\" + Constants.GENERIC_ID + \" INTEGER IDENTITY,\"\n + Constants.DB_TABLE_CONFIGURATION_NAME + \" VARCHAR(256),\"\n + Constants.DB_TABLE_CONFIGURATION_VALUE + \" VARCHAR(1024));\");\n\n executeUpdate(\"INSERT INTO \" + Constants.DB_TABLE_CONFIGURATION\n + \"(\" + Constants.DB_TABLE_CONFIGURATION_NAME + \",\" + Constants.DB_TABLE_CONFIGURATION_VALUE + \")\"\n + \" VALUES (\\'\"\n + Constants.DB_TABLE_CONFIGURATION_DATABASE_VERSION\n + \"\\', '0');\");\n } else {\n logger.info(\"Getting current schema version..\");\n // get current version\n current_version = new Integer(configuration.get(\"VALUE\").toString());\n logger.info(\"Current schema version is {}\", current_version);\n }\n\n // loop through until we get up to the right schema version\n while (current_version < Constants.DB_CURRENT_SCHEMA_VERSION) {\n current_version++;\n\n // look for a schema file for this version\n logger.info(\"Updating to schema version {}\", current_version);\n String currentFile = migrationPath + \"/schema.\"\n + current_version;\n Resource migFile = new ClassPathResource(currentFile);\n BufferedReader in = new BufferedReader(new InputStreamReader(\n migFile.getInputStream()));\n\n String str;\n while ((str = in.readLine()) != null) {\n // execute each line\n if (str.length() > 0) {\n executeUpdate(str);\n }\n }\n in.close();\n }\n\n // update the configuration table with the correct version\n executeUpdate(\"UPDATE \" + Constants.DB_TABLE_CONFIGURATION\n + \" SET \" + Constants.DB_TABLE_CONFIGURATION_VALUE + \"='\" + current_version\n + \"' WHERE \" + Constants.DB_TABLE_CONFIGURATION_NAME + \"='\"\n + Constants.DB_TABLE_CONFIGURATION_DATABASE_VERSION + \"';\");\n } catch (Exception e) {\n logger.info(\"Error in executeUpdate\");\n e.printStackTrace();\n }\n }",
"protected void setBeanDeploymentArchivesAccessibility() {\n for (WeldBeanDeploymentArchive beanDeploymentArchive : beanDeploymentArchives) {\n Set<WeldBeanDeploymentArchive> accessibleArchives = new HashSet<>();\n for (WeldBeanDeploymentArchive candidate : beanDeploymentArchives) {\n if (candidate.equals(beanDeploymentArchive)) {\n continue;\n }\n accessibleArchives.add(candidate);\n }\n beanDeploymentArchive.setAccessibleBeanDeploymentArchives(accessibleArchives);\n }\n }",
"public static void sendEvent(Context context, Parcelable event) {\n Intent intent = new Intent(EventManager.ACTION_ACCESSORY_EVENT);\n intent.putExtra(EventManager.EXTRA_EVENT, event);\n context.sendBroadcast(intent);\n }",
"public Collection<License> getInfo() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_INFO);\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 List<License> licenses = new ArrayList<License>();\r\n Element licensesElement = response.getPayload();\r\n NodeList licenseElements = licensesElement.getElementsByTagName(\"license\");\r\n for (int i = 0; i < licenseElements.getLength(); i++) {\r\n Element licenseElement = (Element) licenseElements.item(i);\r\n License license = new License();\r\n license.setId(licenseElement.getAttribute(\"id\"));\r\n license.setName(licenseElement.getAttribute(\"name\"));\r\n license.setUrl(licenseElement.getAttribute(\"url\"));\r\n licenses.add(license);\r\n }\r\n return licenses;\r\n }",
"public void clipTile(InternalTile tile, double scale, Coordinate panOrigin) throws GeomajasException {\n\t\tlog.debug(\"clipTile before {}\", tile);\n\t\tList<InternalFeature> orgFeatures = tile.getFeatures();\n\t\ttile.setFeatures(new ArrayList<InternalFeature>());\n\t\tGeometry maxScreenBbox = null; // The tile's maximum bounds in screen space. Used for clipping.\n\t\tfor (InternalFeature feature : orgFeatures) {\n\t\t\t// clip feature if necessary\n\t\t\tif (exceedsScreenDimensions(feature, scale)) {\n\t\t\t\tlog.debug(\"feature {} exceeds screen dimensions\", feature);\n\t\t\t\tInternalFeatureImpl vectorFeature = (InternalFeatureImpl) feature.clone();\n\t\t\t\ttile.setClipped(true);\n\t\t\t\tvectorFeature.setClipped(true);\n\t\t\t\tif (null == maxScreenBbox) {\n\t\t\t\t\tmaxScreenBbox = JTS.toGeometry(getMaxScreenEnvelope(tile, panOrigin));\n\t\t\t\t}\n\t\t\t\tGeometry clipped = maxScreenBbox.intersection(feature.getGeometry());\n\t\t\t\tvectorFeature.setClippedGeometry(clipped);\n\t\t\t\ttile.addFeature(vectorFeature);\n\t\t\t} else {\n\t\t\t\ttile.addFeature(feature);\n\t\t\t}\n\t\t}\n\t\tlog.debug(\"clipTile after {}\", tile);\n\t}",
"public void createNewFile() throws SmbException {\n if( getUncPath0().length() == 1 ) {\n throw new SmbException( \"Invalid operation for workgroups, servers, or shares\" );\n }\n close( open0( O_RDWR | O_CREAT | O_EXCL, 0, ATTR_NORMAL, 0 ), 0L );\n }",
"public static TransactionalProtocolClient.Operation wrap(final ModelNode operation, final OperationMessageHandler messageHandler, final OperationAttachments attachments) {\n return new TransactionalOperationImpl(operation, messageHandler, attachments);\n }",
"public AddonChange addAddon(String appName, String addonName) {\n return connection.execute(new AddonInstall(appName, addonName), apiKey);\n }"
] |
Use this API to delete nsacl6 of given name. | [
"public static base_response delete(nitro_service client, String acl6name) throws Exception {\n\t\tnsacl6 deleteresource = new nsacl6();\n\t\tdeleteresource.acl6name = acl6name;\n\t\treturn deleteresource.delete_resource(client);\n\t}"
] | [
"okhttp3.Response get(String url, Map<String, Object> params)\n throws RequestException, LocalOperationException {\n\n String fullUrl = getFullUrl(url);\n okhttp3.Request request = new okhttp3.Request.Builder()\n .url(addUrlParams(fullUrl, toPayload(params)))\n .addHeader(\"Transloadit-Client\", version)\n .build();\n\n try {\n return httpClient.newCall(request).execute();\n } catch (IOException e) {\n throw new RequestException(e);\n }\n }",
"public PlanarImage toDirectColorModel(RenderedImage img) {\n\t\tBufferedImage dest = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);\n\t\tBufferedImage source = new BufferedImage(img.getColorModel(), (WritableRaster) img.getData(), img\n\t\t\t\t.getColorModel().isAlphaPremultiplied(), null);\n\t\tColorConvertOp op = new ColorConvertOp(null);\n\t\top.filter(source, dest);\n\t\treturn PlanarImage.wrapRenderedImage(dest);\n\t}",
"public static base_response disable(nitro_service client, String trapname) throws Exception {\n\t\tsnmpalarm disableresource = new snmpalarm();\n\t\tdisableresource.trapname = trapname;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}",
"public Collection<Service> getServices() throws FlickrException {\r\n List<Service> list = new ArrayList<Service>();\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_SERVICES);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element servicesElement = response.getPayload();\r\n NodeList serviceNodes = servicesElement.getElementsByTagName(\"service\");\r\n for (int i = 0; i < serviceNodes.getLength(); i++) {\r\n Element serviceElement = (Element) serviceNodes.item(i);\r\n Service srv = new Service();\r\n srv.setId(serviceElement.getAttribute(\"id\"));\r\n srv.setName(XMLUtilities.getValue(serviceElement));\r\n list.add(srv);\r\n }\r\n return list;\r\n }",
"CapabilityRegistry createShadowCopy() {\n CapabilityRegistry result = new CapabilityRegistry(forServer, this);\n readLock.lock();\n try {\n try {\n result.writeLock.lock();\n copy(this, result);\n } finally {\n result.writeLock.unlock();\n }\n } finally {\n readLock.unlock();\n }\n return result;\n }",
"public static int cudnnPoolingBackward(\n cudnnHandle handle, \n cudnnPoolingDescriptor poolingDesc, \n Pointer alpha, \n cudnnTensorDescriptor yDesc, \n Pointer y, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor dxDesc, \n Pointer dx)\n {\n return checkResult(cudnnPoolingBackwardNative(handle, poolingDesc, alpha, yDesc, y, dyDesc, dy, xDesc, x, beta, dxDesc, dx));\n }",
"public static MetadataTemplate updateMetadataTemplate(BoxAPIConnection api, String scope, String template,\n List<FieldOperation> fieldOperations) {\n\n JsonArray array = new JsonArray();\n\n for (FieldOperation fieldOperation : fieldOperations) {\n JsonObject jsonObject = getFieldOperationJsonObject(fieldOperation);\n array.add(jsonObject);\n }\n\n QueryStringBuilder builder = new QueryStringBuilder();\n URL url = METADATA_TEMPLATE_URL_TEMPLATE.build(api.getBaseURL(), scope, template);\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"PUT\");\n request.setBody(array.toString());\n\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJson = JsonObject.readFrom(response.getJSON());\n\n return new MetadataTemplate(responseJson);\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 }",
"protected void associateBatched(Collection owners, Collection children)\r\n {\r\n CollectionDescriptor cds = getCollectionDescriptor();\r\n PersistentField field = cds.getPersistentField();\r\n PersistenceBroker pb = getBroker();\r\n Class ownerTopLevelClass = pb.getTopLevelClass(getOwnerClassDescriptor().getClassOfObject());\r\n Class collectionClass = cds.getCollectionClass(); // this collection type will be used:\r\n HashMap ownerIdsToLists = new HashMap(owners.size());\r\n\r\n IdentityFactory identityFactory = pb.serviceIdentity();\r\n // initialize the owner list map\r\n for (Iterator it = owners.iterator(); it.hasNext();)\r\n {\r\n Object owner = it.next();\r\n ownerIdsToLists.put(identityFactory.buildIdentity(getOwnerClassDescriptor(), owner), new ArrayList());\r\n }\r\n\r\n // build the children lists for the owners\r\n for (Iterator it = children.iterator(); it.hasNext();)\r\n {\r\n Object child = it.next();\r\n // BRJ: use cld for real class, relatedObject could be Proxy\r\n ClassDescriptor cld = getDescriptorRepository().getDescriptorFor(ProxyHelper.getRealClass(child));\r\n\r\n Object[] fkValues = cds.getForeignKeyValues(child, cld);\r\n Identity ownerId = identityFactory.buildIdentity(null, ownerTopLevelClass, fkValues);\r\n List list = (List) ownerIdsToLists.get(ownerId);\r\n if (list != null)\r\n {\r\n list.add(child);\r\n }\r\n }\r\n\r\n // connect children list to owners\r\n for (Iterator it = owners.iterator(); it.hasNext();)\r\n {\r\n Object result;\r\n Object owner = it.next();\r\n Identity ownerId = identityFactory.buildIdentity(owner);\r\n List list = (List) ownerIdsToLists.get(ownerId);\r\n\r\n if ((collectionClass == null) && field.getType().isArray())\r\n {\r\n int length = list.size();\r\n Class itemtype = field.getType().getComponentType();\r\n result = Array.newInstance(itemtype, length);\r\n for (int j = 0; j < length; j++)\r\n {\r\n Array.set(result, j, list.get(j));\r\n }\r\n }\r\n else\r\n {\r\n ManageableCollection col = createCollection(cds, collectionClass);\r\n for (Iterator it2 = list.iterator(); it2.hasNext();)\r\n {\r\n col.ojbAdd(it2.next());\r\n }\r\n result = col;\r\n }\r\n\r\n Object value = field.get(owner);\r\n if ((value instanceof CollectionProxyDefaultImpl) && (result instanceof Collection))\r\n {\r\n ((CollectionProxyDefaultImpl) value).setData((Collection) result);\r\n }\r\n else\r\n {\r\n field.set(owner, result);\r\n }\r\n }\r\n }"
] |
Checks if the given operator code is a valid one.
@param operatorCode an operator code to evaluate
@throws IllegalStateException if operatorCode is not a known operator code. | [
"public static void checkOperatorIsValid(int operatorCode) {\n switch (operatorCode) {\n case OPERATOR_LT:\n case OPERATOR_LE:\n case OPERATOR_EQ:\n case OPERATOR_NE:\n case OPERATOR_GE:\n case OPERATOR_GT:\n case OPERATOR_UNKNOWN:\n return;\n default:\n throw new IllegalStateException(String.format(Locale.US, ERROR_INVALID_CODE, operatorCode));\n }\n }"
] | [
"private Cluster expandCluster(final Cluster cluster,\n final Point2D point,\n final List<Point2D> neighbors,\n final KDTree<Point2D> points,\n final Map<Point2D, PointStatus> visited) {\n cluster.addPoint(point);\n visited.put(point, PointStatus.PART_OF_CLUSTER);\n\n List<Point2D> seeds = new ArrayList<Point2D>(neighbors);\n int index = 0;\n while (index < seeds.size()) {\n Point2D current = seeds.get(index);\n PointStatus pStatus = visited.get(current);\n // only check non-visited points\n if (pStatus == null) {\n final List<Point2D> currentNeighbors = getNeighbors(current, points);\n if (currentNeighbors.size() >= minPoints) {\n seeds = merge(seeds, currentNeighbors);\n }\n }\n\n if (pStatus != PointStatus.PART_OF_CLUSTER) {\n visited.put(current, PointStatus.PART_OF_CLUSTER);\n cluster.addPoint(current);\n }\n\n index++;\n }\n return cluster;\n }",
"private static CallSite realBootstrap(Lookup caller, String name, int callID, MethodType type, boolean safe, boolean thisCall, boolean spreadCall) {\n // since indy does not give us the runtime types\n // we produce first a dummy call site, which then changes the target to one,\n // that does the method selection including the the direct call to the \n // real method.\n MutableCallSite mc = new MutableCallSite(type);\n MethodHandle mh = makeFallBack(mc,caller.lookupClass(),name,callID,type,safe,thisCall,spreadCall);\n mc.setTarget(mh);\n return mc;\n }",
"public static boolean isConstantVal(DMatrixRMaj mat , double val , double tol )\n {\n // see if the result is an identity matrix\n int index = 0;\n for( int i = 0; i < mat.numRows; i++ ) {\n for( int j = 0; j < mat.numCols; j++ ) {\n if( !(Math.abs(mat.get(index++)-val) <= tol) )\n return false;\n\n }\n }\n\n return true;\n }",
"private static CmsUUID toUuid(String uuid) {\n\n if (\"null\".equals(uuid) || CmsStringUtil.isEmpty(uuid)) {\n return null;\n }\n return new CmsUUID(uuid);\n\n }",
"public void run(Configuration configuration, InjectableStepsFactory stepsFactory, Story story, MetaFilter filter,\n State beforeStories) throws Throwable {\n RunContext context = new RunContext(configuration, stepsFactory, story.getPath(), filter);\n if (beforeStories != null) {\n context.stateIs(beforeStories);\n }\n Map<String, String> storyParameters = new HashMap<>();\n run(context, story, storyParameters);\n }",
"public Object doGetObjectByIdentity(Identity id) throws PersistenceBrokerException\n {\n if (logger.isDebugEnabled()) logger.debug(\"getObjectByIdentity \" + id);\n\n // check if object is present in ObjectCache:\n Object obj = objectCache.lookup(id);\n // only perform a db lookup if necessary (object not cached yet)\n if (obj == null)\n {\n obj = getDBObject(id);\n }\n else\n {\n ClassDescriptor cld = getClassDescriptor(obj.getClass());\n // if specified in the ClassDescriptor the instance must be refreshed\n if (cld.isAlwaysRefresh())\n {\n refreshInstance(obj, id, cld);\n }\n // now refresh all references\n checkRefreshRelationships(obj, id, cld);\n }\n\n // Invoke events on PersistenceBrokerAware instances and listeners\n AFTER_LOOKUP_EVENT.setTarget(obj);\n fireBrokerEvent(AFTER_LOOKUP_EVENT);\n AFTER_LOOKUP_EVENT.setTarget(null);\n\n //logger.info(\"RETRIEVING object \" + obj);\n return obj;\n }",
"protected float getSizeArcLength(float angle) {\n if (mRadius <= 0) {\n throw new IllegalArgumentException(\"mRadius is not specified!\");\n }\n return angle == Float.MAX_VALUE ? Float.MAX_VALUE :\n LayoutHelpers.lengthOfArc(angle, mRadius);\n }",
"public final static String process(final File file, final boolean safeMode) throws IOException\n {\n return process(file, Configuration.builder().setSafeMode(safeMode).build());\n }",
"public Collection<BoxGroupMembership.Info> getMemberships() {\n BoxAPIConnection api = this.getAPI();\n URL url = USER_MEMBERSHIPS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int entriesCount = responseJSON.get(\"total_count\").asInt();\n Collection<BoxGroupMembership.Info> memberships = new ArrayList<BoxGroupMembership.Info>(entriesCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue entry : entries) {\n JsonObject entryObject = entry.asObject();\n BoxGroupMembership membership = new BoxGroupMembership(api, entryObject.get(\"id\").asString());\n BoxGroupMembership.Info info = membership.new Info(entryObject);\n memberships.add(info);\n }\n\n return memberships;\n }"
] |
Execute a server task.
@param listener the transactional server listener
@param task the server task
@return time to wait in ms for a response from the server, or {@code -1} if the task execution failed locally | [
"public int executeTask(final TransactionalProtocolClient.TransactionalOperationListener<ServerOperation> listener, final ServerUpdateTask task) {\n try {\n return execute(listener, task.getServerIdentity(), task.getOperation());\n } catch (OperationFailedException e) {\n // Handle failures operation transformation failures\n final ServerIdentity identity = task.getServerIdentity();\n final ServerOperation serverOperation = new ServerOperation(identity, task.getOperation(), null, null, OperationResultTransformer.ORIGINAL_RESULT);\n final TransactionalProtocolClient.PreparedOperation<ServerOperation> result = BlockingQueueOperationListener.FailedOperation.create(serverOperation, e);\n listener.operationPrepared(result);\n recordExecutedRequest(new ExecutedServerRequest(identity, result.getFinalResult(), OperationResultTransformer.ORIGINAL_RESULT));\n return 1; // 1 ms timeout since there is no reason to wait for the locally stored result\n }\n\n }"
] | [
"public void cache(String key, Object obj) {\n H.Session sess = session();\n if (null != sess) {\n sess.cache(key, obj);\n } else {\n app().cache().put(key, obj);\n }\n }",
"public int getVersion() {\n ResultSet resultSet = session.execute(format(VERSION_QUERY, getTableName()));\n Row result = resultSet.one();\n if (result == null) {\n return 0;\n }\n return result.getInt(0);\n }",
"public static long hash(final BsonDocument doc) {\n if (doc == null) {\n return 0L;\n }\n\n final byte[] docBytes = toBytes(doc);\n long hashValue = FNV_64BIT_OFFSET_BASIS;\n\n for (int offset = 0; offset < docBytes.length; offset++) {\n hashValue ^= (0xFF & docBytes[offset]);\n hashValue *= FNV_64BIT_PRIME;\n }\n\n return hashValue;\n }",
"public void emitEvent(\n final NamespaceSynchronizationConfig nsConfig,\n final ChangeEvent<BsonDocument> event) {\n listenersLock.lock();\n try {\n if (nsConfig.getNamespaceListenerConfig() == null) {\n return;\n }\n final NamespaceListenerConfig namespaceListener =\n nsConfig.getNamespaceListenerConfig();\n eventDispatcher.dispatch(() -> {\n try {\n if (namespaceListener.getEventListener() != null) {\n namespaceListener.getEventListener().onEvent(\n BsonUtils.getDocumentId(event.getDocumentKey()),\n ChangeEvents.transformChangeEventForUser(\n event, namespaceListener.getDocumentCodec()));\n }\n } catch (final Exception ex) {\n logger.error(String.format(\n Locale.US,\n \"emitEvent ns=%s documentId=%s emit exception: %s\",\n event.getNamespace(),\n BsonUtils.getDocumentId(event.getDocumentKey()),\n ex), ex);\n }\n return null;\n });\n } finally {\n listenersLock.unlock();\n }\n }",
"private EnabledEndpoint getPartialEnabledEndpointFromResultset(ResultSet result) throws Exception {\n EnabledEndpoint endpoint = new EnabledEndpoint();\n endpoint.setId(result.getInt(Constants.GENERIC_ID));\n endpoint.setPathId(result.getInt(Constants.ENABLED_OVERRIDES_PATH_ID));\n endpoint.setOverrideId(result.getInt(Constants.ENABLED_OVERRIDES_OVERRIDE_ID));\n endpoint.setPriority(result.getInt(Constants.ENABLED_OVERRIDES_PRIORITY));\n endpoint.setRepeatNumber(result.getInt(Constants.ENABLED_OVERRIDES_REPEAT_NUMBER));\n endpoint.setResponseCode(result.getString(Constants.ENABLED_OVERRIDES_RESPONSE_CODE));\n\n ArrayList<Object> args = new ArrayList<Object>();\n try {\n JSONArray arr = new JSONArray(result.getString(Constants.ENABLED_OVERRIDES_ARGUMENTS));\n for (int x = 0; x < arr.length(); x++) {\n args.add(arr.get(x));\n }\n } catch (Exception e) {\n // ignore it.. this means the entry was null/corrupt\n }\n\n endpoint.setArguments(args.toArray(new Object[0]));\n\n return endpoint;\n }",
"public static int ptb2Text(Reader ptbText, Writer w) throws IOException {\r\n int numTokens = 0;\r\n PTB2TextLexer lexer = new PTB2TextLexer(ptbText);\r\n for (String token; (token = lexer.next()) != null; ) {\r\n numTokens++;\r\n w.write(token);\r\n }\r\n return numTokens;\r\n }",
"public 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 validateArguments() throws BuildException {\n Path tempDir = getTempDir();\n\n if (tempDir == null) {\n throw new BuildException(\"Temporary directory cannot be null.\");\n }\n \n if (Files.exists(tempDir)) {\n if (!Files.isDirectory(tempDir)) {\n throw new BuildException(\"Temporary directory is not a folder: \" + tempDir.toAbsolutePath());\n }\n } else {\n try {\n Files.createDirectories(tempDir);\n } catch (IOException e) {\n throw new BuildException(\"Failed to create temporary folder: \" + tempDir, e);\n }\n }\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 }"
] |
Set up arguments for each FieldDescriptor in an array. | [
"protected void addArguments(FieldDescriptor field[])\r\n {\r\n for (int i = 0; i < field.length; i++)\r\n {\r\n ArgumentDescriptor arg = new ArgumentDescriptor(this);\r\n arg.setValue(field[i].getAttributeName(), false);\r\n this.addArgument(arg);\r\n }\r\n }"
] | [
"public static <T extends Spin<?>> T S(Object input, DataFormat<T> format) {\n return SpinFactory.INSTANCE.createSpin(input, format);\n }",
"public static tunnelip_stats[] get(nitro_service service) throws Exception{\n\t\ttunnelip_stats obj = new tunnelip_stats();\n\t\ttunnelip_stats[] response = (tunnelip_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}",
"public static void copyRecursively(final Path source, final Path target, boolean overwrite) throws IOException {\n final CopyOption[] options;\n if (overwrite) {\n options = new CopyOption[]{StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING};\n } else {\n options = new CopyOption[]{StandardCopyOption.COPY_ATTRIBUTES};\n }\n Files.walkFileTree(source, new FileVisitor<Path>() {\n @Override\n public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {\n Files.copy(dir, target.resolve(source.relativize(dir)), options);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n Files.copy(file, target.resolve(source.relativize(file)), options);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {\n DeploymentRepositoryLogger.ROOT_LOGGER.cannotCopyFile(exc, file);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {\n return FileVisitResult.CONTINUE;\n }\n });\n }",
"public static Iterable<BoxCollection.Info> getAllCollections(final BoxAPIConnection api) {\n return new Iterable<BoxCollection.Info>() {\n public Iterator<BoxCollection.Info> iterator() {\n URL url = GET_COLLECTIONS_URL_TEMPLATE.build(api.getBaseURL());\n return new BoxCollectionIterator(api, url);\n }\n };\n }",
"public static void generateOutputFile(Random rng,\n File outputFile) throws IOException\n {\n DataOutputStream dataOutput = null;\n try\n {\n dataOutput = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outputFile)));\n for (int i = 0; i < INT_COUNT; i++)\n {\n dataOutput.writeInt(rng.nextInt());\n }\n dataOutput.flush();\n }\n finally\n {\n if (dataOutput != null)\n {\n dataOutput.close();\n }\n }\n }",
"public void initialize() {\n\t\tthis.enqueue(new SerialMessage(SerialMessage.SerialMessageClass.GetVersion, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.GetVersion, SerialMessage.SerialMessagePriority.High));\n\t\tthis.enqueue(new SerialMessage(SerialMessage.SerialMessageClass.MemoryGetId, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.MemoryGetId, SerialMessage.SerialMessagePriority.High));\n\t\tthis.enqueue(new SerialMessage(SerialMessage.SerialMessageClass.SerialApiGetCapabilities, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.SerialApiGetCapabilities, SerialMessage.SerialMessagePriority.High));\n\t}",
"public static nd6ravariables[] get(nitro_service service, options option) throws Exception{\n\t\tnd6ravariables obj = new nd6ravariables();\n\t\tnd6ravariables[] response = (nd6ravariables[])obj.get_resources(service,option);\n\t\treturn response;\n\t}",
"public static Path createTempDirectory(Path dir, String prefix) throws IOException {\n try {\n return Files.createTempDirectory(dir, prefix);\n } catch (UnsupportedOperationException ex) {\n }\n return Files.createTempDirectory(dir, prefix);\n }",
"private int deleteSegments(Log log, List<LogSegment> segments) {\n int total = 0;\n for (LogSegment segment : segments) {\n boolean deleted = false;\n try {\n try {\n segment.getMessageSet().close();\n } catch (IOException e) {\n logger.warn(e.getMessage(), e);\n }\n if (!segment.getFile().delete()) {\n deleted = true;\n } else {\n total += 1;\n }\n } finally {\n logger.warn(String.format(\"DELETE_LOG[%s] %s => %s\", log.name, segment.getFile().getAbsolutePath(),\n deleted));\n }\n }\n return total;\n }"
] |
Finish initializing.
@throws GeomajasException oops | [
"@PostConstruct\n\tprotected void checkPluginDependencies() throws GeomajasException {\n\t\tif (\"true\".equals(System.getProperty(\"skipPluginDependencyCheck\"))) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (null == declaredPlugins) {\n\t\t\treturn;\n\t\t}\n\n\t\t// start by going through all plug-ins to build a map of versions for plug-in keys\n\t\t// includes verification that each key is only used once\n\t\tMap<String, String> versions = new HashMap<String, String>();\n\t\tfor (PluginInfo plugin : declaredPlugins.values()) {\n\t\t\tString name = plugin.getVersion().getName();\n\t\t\tString version = plugin.getVersion().getVersion();\n\t\t\t// check for multiple plugin with same name but different versions (duplicates allowed for jar+source dep)\n\t\t\tif (null != version) {\n\t\t\t\tString otherVersion = versions.get(name);\n\t\t\t\tif (null != otherVersion) {\n\t\t\t\t\tif (!version.startsWith(EXPR_START)) {\n\t\t\t\t\t\tif (!otherVersion.startsWith(EXPR_START) && !otherVersion.equals(version)) {\n\t\t\t\t\t\t\tthrow new GeomajasException(ExceptionCode.DEPENDENCY_CHECK_INVALID_DUPLICATE,\n\t\t\t\t\t\t\t\t\tname, version, versions.get(name));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tversions.put(name, version);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tversions.put(name, version);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Check dependencies\n\t\tStringBuilder message = new StringBuilder();\n\t\tString backendVersion = versions.get(\"Geomajas\");\n\t\tfor (PluginInfo plugin : declaredPlugins.values()) {\n\t\t\tString name = plugin.getVersion().getName();\n\t\t\tmessage.append(checkVersion(name, \"Geomajas back-end\", plugin.getBackendVersion(), backendVersion));\n\t\t\tList<PluginVersionInfo> dependencies = plugin.getDependencies();\n\t\t\tif (null != dependencies) {\n\t\t\t\tfor (PluginVersionInfo dependency : plugin.getDependencies()) {\n\t\t\t\t\tString depName = dependency.getName();\n\t\t\t\t\tmessage.append(checkVersion(name, depName, dependency.getVersion(), versions.get(depName)));\n\t\t\t\t}\n\t\t\t}\n\t\t\tdependencies = plugin.getOptionalDependencies();\n\t\t\tif (null != dependencies) {\n\t\t\t\tfor (PluginVersionInfo dependency : dependencies) {\n\t\t\t\t\tString depName = dependency.getName();\n\t\t\t\t\tString availableVersion = versions.get(depName);\n\t\t\t\t\tif (null != availableVersion) {\n\t\t\t\t\t\tmessage.append(checkVersion(name, depName, dependency.getVersion(), versions.get(depName)));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (message.length() > 0) {\n\t\t\tthrow new GeomajasException(ExceptionCode.DEPENDENCY_CHECK_FAILED, message.toString());\n\t\t}\n\n\t\trecorder.record(GROUP, VALUE);\n\t}"
] | [
"public void setTimeWarp(String l) {\n\n long warp = CmsContextInfo.CURRENT_TIME;\n try {\n warp = Long.parseLong(l);\n } catch (NumberFormatException e) {\n // if parsing the time warp fails, it will be set to -1 (i.e. disabled)\n }\n m_settings.setTimeWarp(warp);\n }",
"@SuppressWarnings(\"unchecked\")\n public static <T> AttachmentKey<T> create(final Class<? super T> valueClass) {\n return new SimpleAttachmentKey(valueClass);\n }",
"public static <T, U extends Closeable> T withCloseable(U self, @ClosureParams(value=FirstParam.class) Closure<T> action) throws IOException {\n try {\n T result = action.call(self);\n\n Closeable temp = self;\n self = null;\n temp.close();\n\n return result;\n } finally {\n DefaultGroovyMethodsSupport.closeWithWarning(self);\n }\n }",
"private void beginInternTransaction()\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"beginInternTransaction was called\");\r\n J2EETransactionImpl tx = (J2EETransactionImpl) super.currentTransaction();\r\n if (tx == null) tx = newInternTransaction();\r\n if (!tx.isOpen())\r\n {\r\n // start the transaction\r\n tx.begin();\r\n tx.setInExternTransaction(true);\r\n }\r\n }",
"public ModelNode getDeploymentSubsystemModel(final String subsystemName) {\n assert subsystemName != null : \"The subsystemName cannot be null\";\n return getDeploymentSubModel(subsystemName, PathAddress.EMPTY_ADDRESS, null, deploymentUnit);\n }",
"public static base_response add(nitro_service client, snmpmanager resource) throws Exception {\n\t\tsnmpmanager addresource = new snmpmanager();\n\t\taddresource.ipaddress = resource.ipaddress;\n\t\taddresource.netmask = resource.netmask;\n\t\taddresource.domainresolveretry = resource.domainresolveretry;\n\t\treturn addresource.add_resource(client);\n\t}",
"public void transformPose(Matrix4f trans)\n {\n Bone bone = mBones[0];\n\n bone.LocalMatrix.set(trans);\n bone.WorldMatrix.set(trans);\n bone.Changed = WORLD_POS | WORLD_ROT;\n mNeedSync = true;\n sync();\n }",
"public void writeReferences() throws RDFHandlerException {\n\t\tIterator<Reference> referenceIterator = this.referenceQueue.iterator();\n\t\tfor (Resource resource : this.referenceSubjectQueue) {\n\t\t\tfinal Reference reference = referenceIterator.next();\n\t\t\tif (this.declaredReferences.add(resource)) {\n\t\t\t\twriteReference(reference, resource);\n\t\t\t}\n\t\t}\n\t\tthis.referenceSubjectQueue.clear();\n\t\tthis.referenceQueue.clear();\n\n\t\tthis.snakRdfConverter.writeAuxiliaryTriples();\n\t}",
"private String mountPath(CdjStatus.TrackSourceSlot slot) {\n switch (slot) {\n case SD_SLOT: return \"/B/\";\n case USB_SLOT: return \"/C/\";\n }\n throw new IllegalArgumentException(\"Don't know how to NFS mount filesystem for slot \" + slot);\n }"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.