query
stringlengths
7
3.3k
positive
sequencelengths
1
1
negative
sequencelengths
9
9
Use this API to fetch all the linkset resources that are configured on netscaler.
[ "public static linkset[] get(nitro_service service) throws Exception{\n\t\tlinkset obj = new linkset();\n\t\tlinkset[] response = (linkset[])obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "public int getIgnoredCount() {\n int count = 0;\n for (AggregatedTestResultEvent t : getTests()) {\n if (t.getStatus() == TestStatus.IGNORED ||\n t.getStatus() == TestStatus.IGNORED_ASSUMPTION) {\n count++;\n }\n }\n return count;\n }", "public static List<int[]> createList( int N )\n {\n int data[] = new int[ N ];\n for( int i = 0; i < data.length; i++ ) {\n data[i] = -1;\n }\n\n List<int[]> ret = new ArrayList<int[]>();\n\n createList(data,0,-1,ret);\n\n return ret;\n }", "protected boolean exportWithMinimalMetaData(String path) {\n\n String checkPath = path.startsWith(\"/\") ? path + \"/\" : \"/\" + path + \"/\";\n for (String p : m_parameters.getResourcesToExportWithMetaData()) {\n if (checkPath.startsWith(p)) {\n return false;\n }\n }\n return true;\n }", "private Collection getOwnerObjects()\r\n {\r\n Collection owners = new Vector();\r\n while (hasNext())\r\n {\r\n owners.add(next());\r\n }\r\n return owners;\r\n }", "public SerialMessage getMultiChannelCapabilityGetMessage(ZWaveEndpoint endpoint) {\r\n\t\tlogger.debug(\"Creating new message for application command MULTI_CHANNEL_CAPABILITY_GET for node {} and endpoint {}\", this.getNode().getNodeId(), endpoint.getEndpointId());\r\n\t\tSerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get);\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) MULTI_CHANNEL_CAPABILITY_GET,\r\n\t\t\t\t\t\t\t\t(byte) endpoint.getEndpointId() };\r\n \tresult.setMessagePayload(newPayload);\r\n \treturn result;\r\n\t}", "public static String eachMatch(String self, String regex, @ClosureParams(value=FromString.class, options={\"List<String>\",\"String[]\"}) Closure closure) {\n return eachMatch(self, Pattern.compile(regex), closure);\n }", "protected boolean intersect(GVRSceneObject.BoundingVolume bv1, GVRSceneObject.BoundingVolume bv2)\n {\n return (bv1.maxCorner.x >= bv2.minCorner.x) &&\n (bv1.maxCorner.y >= bv2.minCorner.y) &&\n (bv1.maxCorner.z >= bv2.minCorner.z) &&\n (bv1.minCorner.x <= bv2.maxCorner.x) &&\n (bv1.minCorner.y <= bv2.maxCorner.y) &&\n (bv1.minCorner.z <= bv2.maxCorner.z);\n }", "@SuppressWarnings(\"unchecked\")\n private static synchronized Map<String, Boolean> getCache(GraphRewrite event)\n {\n Map<String, Boolean> result = (Map<String, Boolean>)event.getRewriteContext().get(ClassificationServiceCache.class);\n if (result == null)\n {\n result = Collections.synchronizedMap(new LRUMap(30000));\n event.getRewriteContext().put(ClassificationServiceCache.class, result);\n }\n return result;\n }", "@Deprecated\r\n public Location resolvePlaceURL(String flickrPlacesUrl) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_RESOLVE_PLACE_URL);\r\n\r\n parameters.put(\"url\", flickrPlacesUrl);\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 locationElement = response.getPayload();\r\n return parseLocation(locationElement);\r\n }" ]
Sets the set of language filters based on the given string. @param filters comma-separates list of language codes, or "-" to filter all languages
[ "private void setLanguageFilters(String filters) {\n\t\tthis.filterLanguages = new HashSet<>();\n\t\tif (!\"-\".equals(filters)) {\n\t\t\tCollections.addAll(this.filterLanguages, filters.split(\",\"));\n\t\t}\n\t}" ]
[ "public final void end() {\n final Thread thread = threadRef;\n if (thread != null) {\n thread.interrupt();\n try {\n thread.join();\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n }\n this.threadRef = null;\n }", "private void updateImageInfo() {\n\n String crop = getCrop();\n String point = getPoint();\n m_imageInfoDisplay.fillContent(m_info, crop, point);\n }", "public static int Hamming(String first, String second) {\n\n if (first.length() != second.length())\n throw new IllegalArgumentException(\"The size of string must be the same.\");\n\n int diff = 0;\n for (int i = 0; i < first.length(); i++)\n if (first.charAt(i) != second.charAt(i))\n diff++;\n return diff;\n }", "private void readFieldAlias(Project.ExtendedAttributes.ExtendedAttribute attribute)\n {\n String alias = attribute.getAlias();\n if (alias != null && alias.length() != 0)\n {\n FieldType field = FieldTypeHelper.getInstance(Integer.parseInt(attribute.getFieldID()));\n m_projectFile.getCustomFields().getCustomField(field).setAlias(attribute.getAlias());\n }\n }", "public static boolean ensureJedisConnection(final Jedis jedis) {\n final boolean jedisOK = testJedisConnection(jedis);\n if (!jedisOK) {\n try {\n jedis.quit();\n } catch (Exception e) {\n } // Ignore\n try {\n jedis.disconnect();\n } catch (Exception e) {\n } // Ignore\n jedis.connect();\n }\n return jedisOK;\n }", "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 }", "@SuppressWarnings(\"unchecked\")\n public <T> T getOptionValue(String name)\n {\n return (T) configurationOptions.get(name);\n }", "protected long getRevisionIdFromResponse(JsonNode response) throws JsonMappingException {\n\t\tif(response == null) {\n\t\t\tthrow new JsonMappingException(\"API response is null\");\n\t\t}\n\t\tJsonNode entity = null;\n\t\tif(response.has(\"entity\")) {\n\t\t\tentity = response.path(\"entity\");\n\t\t} else if(response.has(\"pageinfo\")) {\n\t\t\tentity = response.path(\"pageinfo\");\n\t\t} \n\t\tif(entity != null && entity.has(\"lastrevid\")) {\n\t\t\treturn entity.path(\"lastrevid\").asLong();\n\t\t}\n\t\tthrow new JsonMappingException(\"The last revision id could not be found in API response\");\n\t}", "public static DMatrixRMaj nullspaceQR( DMatrixRMaj A , int totalSingular ) {\n SolveNullSpaceQR_DDRM solver = new SolveNullSpaceQR_DDRM();\n\n DMatrixRMaj nullspace = new DMatrixRMaj(1,1);\n\n if( !solver.process(A,totalSingular,nullspace))\n throw new RuntimeException(\"Solver failed. try SVD based method instead?\");\n\n return nullspace;\n }" ]
Writes the details of a recurring exception. @param mpxjException source MPXJ calendar exception @param xmlException target MSPDI exception
[ "private void populateRecurringException(ProjectCalendarException mpxjException, Exceptions.Exception xmlException)\n {\n RecurringData data = mpxjException.getRecurring();\n xmlException.setEnteredByOccurrences(Boolean.TRUE);\n xmlException.setOccurrences(NumberHelper.getBigInteger(data.getOccurrences()));\n\n switch (data.getRecurrenceType())\n {\n case DAILY:\n {\n xmlException.setType(BigInteger.valueOf(7));\n xmlException.setPeriod(NumberHelper.getBigInteger(data.getFrequency()));\n break;\n }\n\n case WEEKLY:\n {\n xmlException.setType(BigInteger.valueOf(6));\n xmlException.setPeriod(NumberHelper.getBigInteger(data.getFrequency()));\n xmlException.setDaysOfWeek(getDaysOfTheWeek(data));\n break;\n }\n\n case MONTHLY:\n {\n xmlException.setPeriod(NumberHelper.getBigInteger(data.getFrequency()));\n if (data.getRelative())\n {\n xmlException.setType(BigInteger.valueOf(5));\n xmlException.setMonthItem(BigInteger.valueOf(data.getDayOfWeek().getValue() + 2));\n xmlException.setMonthPosition(BigInteger.valueOf(NumberHelper.getInt(data.getDayNumber()) - 1));\n }\n else\n {\n xmlException.setType(BigInteger.valueOf(4));\n xmlException.setMonthDay(NumberHelper.getBigInteger(data.getDayNumber()));\n }\n break;\n }\n\n case YEARLY:\n {\n xmlException.setMonth(BigInteger.valueOf(NumberHelper.getInt(data.getMonthNumber()) - 1));\n if (data.getRelative())\n {\n xmlException.setType(BigInteger.valueOf(3));\n xmlException.setMonthItem(BigInteger.valueOf(data.getDayOfWeek().getValue() + 2));\n xmlException.setMonthPosition(BigInteger.valueOf(NumberHelper.getInt(data.getDayNumber()) - 1));\n }\n else\n {\n xmlException.setType(BigInteger.valueOf(2));\n xmlException.setMonthDay(NumberHelper.getBigInteger(data.getDayNumber()));\n }\n }\n }\n }" ]
[ "Response delete(URI uri) {\n HttpConnection connection = Http.DELETE(uri);\n return executeToResponse(connection);\n }", "private org.apache.tools.ant.types.Path resolveFiles(org.apache.tools.ant.types.Path path) {\n org.apache.tools.ant.types.Path cloned = new org.apache.tools.ant.types.Path(getProject());\n for (String location : path.list()) {\n cloned.createPathElement().setLocation(new File(location));\n }\n return cloned;\n }", "public void addProducer(Broker broker) {\n Properties props = new Properties();\n props.put(\"host\", broker.host);\n props.put(\"port\", \"\" + broker.port);\n props.putAll(config.getProperties());\n if (sync) {\n SyncProducer producer = new SyncProducer(new SyncProducerConfig(props));\n logger.info(\"Creating sync producer for broker id = \" + broker.id + \" at \" + broker.host + \":\" + broker.port);\n syncProducers.put(broker.id, producer);\n } else {\n AsyncProducer<V> producer = new AsyncProducer<V>(new AsyncProducerConfig(props),//\n new SyncProducer(new SyncProducerConfig(props)),//\n serializer,//\n eventHandler,//\n config.getEventHandlerProperties(),//\n this.callbackHandler, //\n config.getCbkHandlerProperties());\n producer.start();\n logger.info(\"Creating async producer for broker id = \" + broker.id + \" at \" + broker.host + \":\" + broker.port);\n asyncProducers.put(broker.id, producer);\n }\n }", "public static int hash(int input)\n {\n int k1 = mixK1(input);\n int h1 = mixH1(DEFAULT_SEED, k1);\n\n return fmix(h1, SizeOf.SIZE_OF_INT);\n }", "public static boolean validate(Statement stmt) {\n try {\n Connection conn = stmt.getConnection();\n if (conn == null)\n return false;\n\n if (!conn.isClosed() && conn.isValid(10))\n return true;\n\n stmt.close();\n conn.close();\n } catch (SQLException e) {\n // this may well fail. that doesn't matter. we're just making an\n // attempt to clean up, and if we can't, that's just too bad.\n }\n return false;\n }", "private TableAlias getTableAliasForPath(String aPath, String aUserAlias, List hintClasses)\r\n {\r\n if (aUserAlias == null)\r\n {\r\n return getTableAliasForPath(aPath, hintClasses);\r\n }\r\n else\r\n {\r\n\t\t\treturn getTableAliasForPath(aUserAlias + ALIAS_SEPARATOR + aPath, hintClasses);\r\n }\r\n }", "public ModelNode buildRequest() throws OperationFormatException {\n\n ModelNode address = request.get(Util.ADDRESS);\n if(prefix.isEmpty()) {\n address.setEmptyList();\n } else {\n Iterator<Node> iterator = prefix.iterator();\n while (iterator.hasNext()) {\n OperationRequestAddress.Node node = iterator.next();\n if (node.getName() != null) {\n address.add(node.getType(), node.getName());\n } else if (iterator.hasNext()) {\n throw new OperationFormatException(\n \"The node name is not specified for type '\"\n + node.getType() + \"'\");\n }\n }\n }\n\n if(!request.hasDefined(Util.OPERATION)) {\n throw new OperationFormatException(\"The operation name is missing or the format of the operation request is wrong.\");\n }\n\n return request;\n }", "private void deliverCacheUpdate(SlotReference slot, MetadataCache cache) {\n for (final MetadataCacheListener listener : getCacheListeners()) {\n try {\n if (cache == null) {\n listener.cacheDetached(slot);\n } else {\n listener.cacheAttached(slot, cache);\n }\n } catch (Throwable t) {\n logger.warn(\"Problem delivering metadata cache update to listener\", t);\n }\n }\n }", "private void readUDFTypes(FieldContainer mpxj, List<UDFAssignmentType> udfs)\n {\n for (UDFAssignmentType udf : udfs)\n {\n FieldType fieldType = m_fieldTypeMap.get(Integer.valueOf(udf.getTypeObjectId()));\n if (fieldType != null)\n {\n mpxj.set(fieldType, getUdfValue(udf));\n }\n }\n }" ]
Map the EventType. @param eventType the event type @return the event
[ "public static Event map(EventType eventType) {\n Event event = new Event();\n event.setEventType(mapEventTypeEnum(eventType.getEventType()));\n Date date = (eventType.getTimestamp() == null)\n ? new Date() : eventType.getTimestamp().toGregorianCalendar().getTime();\n event.setTimestamp(date);\n event.setOriginator(mapOriginatorType(eventType.getOriginator()));\n MessageInfo messageInfo = mapMessageInfo(eventType.getMessageInfo());\n event.setMessageInfo(messageInfo);\n String content = mapContent(eventType.getContent());\n event.setContent(content);\n event.getCustomInfo().clear();\n event.getCustomInfo().putAll(mapCustomInfo(eventType.getCustomInfo()));\n return event;\n }" ]
[ "public RandomVariable[]\tgetParameter() {\n\t\tdouble[] parameterAsDouble = this.getParameterAsDouble();\n\t\tRandomVariable[] parameter = new RandomVariable[parameterAsDouble.length];\n\t\tfor(int i=0; i<parameter.length; i++) {\n\t\t\tparameter[i] = new Scalar(parameterAsDouble[i]);\n\t\t}\n\t\treturn parameter;\n\t}", "public Duration getWork(Date date, TimeUnit format)\n {\n ProjectCalendarDateRanges ranges = getRanges(date, null, null);\n long time = getTotalTime(ranges);\n return convertFormat(time, format);\n }", "public void pause()\n {\n if (mAudioListener != null)\n {\n int sourceId = getSourceId();\n if (sourceId != GvrAudioEngine.INVALID_ID)\n {\n mAudioListener.getAudioEngine().pauseSound(sourceId);\n }\n }\n }", "private void addDirectSubTypes(XClass type, ArrayList subTypes)\r\n {\r\n if (type.isInterface())\r\n {\r\n if (type.getExtendingInterfaces() != null)\r\n {\r\n subTypes.addAll(type.getExtendingInterfaces());\r\n }\r\n // we have to traverse the implementing classes as these array contains all classes that\r\n // implement the interface, not only those who have an \"implement\" declaration\r\n // note that for whatever reason the declared interfaces are not exported via the XClass interface\r\n // so we have to get them via the underlying class which is hopefully a subclass of AbstractClass\r\n if (type.getImplementingClasses() != null)\r\n {\r\n Collection declaredInterfaces = null;\r\n XClass subType;\r\n\r\n for (Iterator it = type.getImplementingClasses().iterator(); it.hasNext(); )\r\n {\r\n subType = (XClass)it.next();\r\n if (subType instanceof AbstractClass)\r\n {\r\n declaredInterfaces = ((AbstractClass)subType).getDeclaredInterfaces();\r\n if ((declaredInterfaces != null) && declaredInterfaces.contains(type))\r\n {\r\n subTypes.add(subType);\r\n }\r\n }\r\n else\r\n {\r\n // Otherwise we have to live with the bug\r\n subTypes.add(subType);\r\n }\r\n }\r\n }\r\n }\r\n else\r\n {\r\n subTypes.addAll(type.getDirectSubclasses());\r\n }\r\n }", "public void calculateSize(PdfContext context) {\n\t\tfloat width = 0;\n\t\tfloat height = 0;\n\t\tfor (PrintComponent<?> child : children) {\n\t\t\tchild.calculateSize(context);\n\t\t\tfloat cw = child.getBounds().getWidth() + 2 * child.getConstraint().getMarginX();\n\t\t\tfloat ch = child.getBounds().getHeight() + 2 * child.getConstraint().getMarginY();\n\t\t\tswitch (getConstraint().getFlowDirection()) {\n\t\t\t\tcase LayoutConstraint.FLOW_NONE:\n\t\t\t\t\twidth = Math.max(width, cw);\n\t\t\t\t\theight = Math.max(height, ch);\n\t\t\t\t\tbreak;\n\t\t\t\tcase LayoutConstraint.FLOW_X:\n\t\t\t\t\twidth += cw;\n\t\t\t\t\theight = Math.max(height, ch);\n\t\t\t\t\tbreak;\n\t\t\t\tcase LayoutConstraint.FLOW_Y:\n\t\t\t\t\twidth = Math.max(width, cw);\n\t\t\t\t\theight += ch;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new IllegalStateException(\"Unknown flow direction \" + getConstraint().getFlowDirection());\n\t\t\t}\n\t\t}\n\t\tif (getConstraint().getWidth() != 0) {\n\t\t\twidth = getConstraint().getWidth();\n\t\t}\n\t\tif (getConstraint().getHeight() != 0) {\n\t\t\theight = getConstraint().getHeight();\n\t\t}\n\t\tsetBounds(new Rectangle(0, 0, width, height));\n\t}", "public void deleteInactiveContent() throws PatchingException {\n List<File> dirs = getInactiveHistory();\n if (!dirs.isEmpty()) {\n for (File dir : dirs) {\n deleteDir(dir, ALL);\n }\n }\n dirs = getInactiveOverlays();\n if (!dirs.isEmpty()) {\n for (File dir : dirs) {\n deleteDir(dir, ALL);\n }\n }\n }", "public ConverterServerBuilder baseUri(String baseUri) {\n checkNotNull(baseUri);\n this.baseUri = URI.create(baseUri);\n return this;\n }", "<P extends PatchingArtifact.ArtifactState, S extends PatchingArtifact.ArtifactState> PatchingArtifactStateHandler<S> getHandlerForArtifact(PatchingArtifact<P, S> artifact) {\n return handlers.get(artifact);\n }", "private void getDailyDates(Calendar calendar, int frequency, List<Date> dates)\n {\n while (moreDates(calendar, dates))\n {\n dates.add(calendar.getTime());\n calendar.add(Calendar.DAY_OF_YEAR, frequency);\n }\n }" ]
Creates a quad consisting of two triangles, with the specified width and height. @param gvrContext current {@link GVRContext} @param width the quad's width @param height the quad's height @return A 2D, rectangular mesh with four vertices and two triangles
[ "public static GVRMesh createQuad(GVRContext gvrContext, float width, float height) {\n GVRMesh mesh = new GVRMesh(gvrContext);\n\n float[] vertices = { width * -0.5f, height * 0.5f, 0.0f, width * -0.5f,\n height * -0.5f, 0.0f, width * 0.5f, height * 0.5f, 0.0f,\n width * 0.5f, height * -0.5f, 0.0f };\n mesh.setVertices(vertices);\n\n final float[] normals = { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,\n 0.0f, 1.0f, 0.0f, 0.0f, 1.0f };\n mesh.setNormals(normals);\n\n final float[] texCoords = { 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f,\n 1.0f };\n mesh.setTexCoords(texCoords);\n\n char[] triangles = { 0, 1, 2, 1, 3, 2 };\n mesh.setIndices(triangles);\n\n return mesh;\n }" ]
[ "static ChangeEvent<BsonDocument> changeEventForLocalUpdate(\n final MongoNamespace namespace,\n final BsonValue documentId,\n final UpdateDescription update,\n final BsonDocument fullDocumentAfterUpdate,\n final boolean writePending\n ) {\n return new ChangeEvent<>(\n new BsonDocument(),\n OperationType.UPDATE,\n fullDocumentAfterUpdate,\n namespace,\n new BsonDocument(\"_id\", documentId),\n update,\n writePending);\n }", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public int getCount(String event) {\n EventDetail eventDetail = getLocalDataStore().getEventDetail(event);\n if (eventDetail != null) return eventDetail.getCount();\n\n return -1;\n }", "public static route6[] get(nitro_service service) throws Exception{\n\t\troute6 obj = new route6();\n\t\troute6[] response = (route6[])obj.get_resources(service);\n\t\treturn response;\n\t}", "private void printSuggestion( String arg, List<ConfigOption> co ) {\n List<ConfigOption> sortedList = new ArrayList<ConfigOption>( co );\n Collections.sort( sortedList, new ConfigOptionLevenshteinDistance( arg ) );\n System.err.println( \"Parse error for argument \\\"\" + arg + \"\\\", did you mean \" + sortedList.get( 0 ).getCommandLineOption()\n .showFlagInfo() + \"? Ignoring for now.\" );\n\n }", "public 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 String getXmlFormatted(Map<String, String> dataMap) {\r\n StringBuilder sb = new StringBuilder();\r\n for (String var : outTemplate) {\r\n sb.append(appendXmlStartTag(var));\r\n sb.append(dataMap.get(var));\r\n sb.append(appendXmlEndingTag(var));\r\n }\r\n return sb.toString();\r\n }", "public static Variable upcastToGeneratedBuilder(\n SourceBuilder code, Datatype datatype, String builder) {\n return code.scope().computeIfAbsent(Declaration.UPCAST, () -> {\n Variable base = new Variable(\"base\");\n code.addLine(UPCAST_COMMENT)\n .addLine(\"%s %s = %s;\", datatype.getGeneratedBuilder(), base, builder);\n return base;\n });\n }", "public List<String> getServiceImplementations(String serviceTypeName) {\n final List<String> strings = services.get(serviceTypeName);\n return strings == null ? Collections.<String>emptyList() : Collections.unmodifiableList(strings);\n }", "private final void replyErrors(final String errorMessage,\n final String stackTrace, final String statusCode,\n final int statusCodeInt) {\n reply(true, errorMessage, stackTrace, statusCode, statusCodeInt,\n PcConstants.NA, null);\n\n }" ]
a small static helper class to get the color from the colorHolder @param colorHolder @param ctx @return
[ "public static int color(ColorHolder colorHolder, Context ctx) {\n if (colorHolder == null) {\n return 0;\n } else {\n return colorHolder.color(ctx);\n }\n }" ]
[ "protected String statusMsg(final String queue, final Job job) throws IOException {\n final WorkerStatus status = new WorkerStatus();\n status.setRunAt(new Date());\n status.setQueue(queue);\n status.setPayload(job);\n return ObjectMapperFactory.get().writeValueAsString(status);\n }", "public void collectVariables(EnvVars env, Run build, TaskListener listener) {\n EnvVars buildParameters = Utils.extractBuildParameters(build, listener);\n if (buildParameters != null) {\n env.putAll(buildParameters);\n }\n addAllWithFilter(envVars, env, filter.getPatternFilter());\n Map<String, String> sysEnv = new HashMap<>();\n Properties systemProperties = System.getProperties();\n Enumeration<?> enumeration = systemProperties.propertyNames();\n while (enumeration.hasMoreElements()) {\n String propertyKey = (String) enumeration.nextElement();\n sysEnv.put(propertyKey, systemProperties.getProperty(propertyKey));\n }\n addAllWithFilter(sysVars, sysEnv, filter.getPatternFilter());\n }", "public List<Action> getRootActions() {\n\t\tfinal List<Action> rootActions = srcUpdTrees.stream().map(t -> originalActionsSrc.get(t))\n\t\t\t\t.collect(Collectors.toList());\n\n\t\trootActions.addAll(srcDelTrees.stream() //\n\t\t\t\t.filter(t -> !srcDelTrees.contains(t.getParent()) && !srcUpdTrees.contains(t.getParent())) //\n\t\t\t\t.map(t -> originalActionsSrc.get(t)) //\n\t\t\t\t.collect(Collectors.toList()));\n\n\t\trootActions.addAll(dstAddTrees.stream() //\n\t\t\t\t.filter(t -> !dstAddTrees.contains(t.getParent()) && !dstUpdTrees.contains(t.getParent())) //\n\t\t\t\t.map(t -> originalActionsDst.get(t)) //\n\t\t\t\t.collect(Collectors.toList()));\n\n\t\trootActions.addAll(dstMvTrees.stream() //\n\t\t\t\t.filter(t -> !dstMvTrees.contains(t.getParent())) //\n\t\t\t\t.map(t -> originalActionsDst.get(t)) //\n\t\t\t\t.collect(Collectors.toList()));\n\n\t\trootActions.removeAll(Collections.singleton(null));\n\t\treturn rootActions;\n\t}", "protected static Connection memorize(final Connection target, final ConnectionHandle connectionHandle) {\n\n\t\treturn (Connection) Proxy.newProxyInstance(\n\t\t\t\tConnectionProxy.class.getClassLoader(),\n\t\t\t\tnew Class[] {ConnectionProxy.class},\n\t\t\t\tnew MemorizeTransactionProxy(target, connectionHandle));\n\t}", "public static void fillProcessorAttributes(\n final List<Processor> processors,\n final Map<String, Attribute> initialAttributes) {\n Map<String, Attribute> currentAttributes = new HashMap<>(initialAttributes);\n for (Processor processor: processors) {\n if (processor instanceof RequireAttributes) {\n for (ProcessorDependencyGraphFactory.InputValue inputValue:\n ProcessorDependencyGraphFactory.getInputs(processor)) {\n if (inputValue.type == Values.class) {\n if (processor instanceof CustomDependencies) {\n for (String attributeName: ((CustomDependencies) processor).getDependencies()) {\n Attribute attribute = currentAttributes.get(attributeName);\n if (attribute != null) {\n ((RequireAttributes) processor).setAttribute(\n attributeName, currentAttributes.get(attributeName));\n }\n }\n\n } else {\n for (Map.Entry<String, Attribute> attribute: currentAttributes.entrySet()) {\n ((RequireAttributes) processor).setAttribute(\n attribute.getKey(), attribute.getValue());\n }\n }\n } else {\n try {\n ((RequireAttributes) processor).setAttribute(\n inputValue.internalName,\n currentAttributes.get(inputValue.name));\n } catch (ClassCastException e) {\n throw new IllegalArgumentException(String.format(\"The processor '%s' requires \" +\n \"the attribute '%s' \" +\n \"(%s) but he has the \" +\n \"wrong type:\\n%s\",\n processor, inputValue.name,\n inputValue.internalName,\n e.getMessage()), e);\n }\n }\n }\n }\n if (processor instanceof ProvideAttributes) {\n Map<String, Attribute> newAttributes = ((ProvideAttributes) processor).getAttributes();\n for (ProcessorDependencyGraphFactory.OutputValue ouputValue:\n ProcessorDependencyGraphFactory.getOutputValues(processor)) {\n currentAttributes.put(\n ouputValue.name, newAttributes.get(ouputValue.internalName));\n }\n }\n }\n }", "private Method getPropertySourceMethod(Object sourceObject,\r\n\t\t\tObject destinationObject, String destinationProperty) {\r\n\t\tBeanToBeanMapping beanToBeanMapping = beanToBeanMappings.get(ClassPair\r\n\t\t\t\t.get(sourceObject.getClass(), destinationObject\r\n\t\t\t\t\t\t.getClass()));\r\n\t\tString sourceProperty = null;\r\n\t\tif (beanToBeanMapping != null) {\r\n\t\t\tsourceProperty = beanToBeanMapping\r\n\t\t\t\t\t.getSourceProperty(destinationProperty);\r\n\t\t}\r\n\t\tif (sourceProperty == null) {\r\n\t\t\tsourceProperty = destinationProperty;\r\n\t\t}\r\n\r\n\t\treturn BeanUtils.getGetterPropertyMethod(sourceObject.getClass(),\r\n\t\t\t\tsourceProperty);\r\n\t}", "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 }", "private static long createLongSeed(byte[] seed)\n {\n if (seed == null || seed.length != SEED_SIZE_BYTES)\n {\n throw new IllegalArgumentException(\"Java RNG requires a 64-bit (8-byte) seed.\");\n }\n return BinaryUtils.convertBytesToLong(seed, 0);\n }", "@PostConstruct\n public void init() {\n //init Bus and LifeCycle listeners\n if (bus != null && sendLifecycleEvent ) {\n ServerLifeCycleManager slcm = bus.getExtension(ServerLifeCycleManager.class);\n if (null != slcm) {\n ServiceListenerImpl svrListener = new ServiceListenerImpl();\n svrListener.setSendLifecycleEvent(sendLifecycleEvent);\n svrListener.setQueue(queue);\n svrListener.setMonitoringServiceClient(monitoringServiceClient);\n slcm.registerListener(svrListener);\n }\n\n ClientLifeCycleManager clcm = bus.getExtension(ClientLifeCycleManager.class);\n if (null != clcm) {\n ClientListenerImpl cltListener = new ClientListenerImpl();\n cltListener.setSendLifecycleEvent(sendLifecycleEvent);\n cltListener.setQueue(queue);\n cltListener.setMonitoringServiceClient(monitoringServiceClient);\n clcm.registerListener(cltListener);\n }\n }\n\n if(executorQueueSize == 0) {\r\n \texecutor = Executors.newFixedThreadPool(this.executorPoolSize);\n }else{\r\n executor = new ThreadPoolExecutor(executorPoolSize, executorPoolSize, 0, TimeUnit.SECONDS, \r\n \t\tnew LinkedBlockingQueue<Runnable>(executorQueueSize), Executors.defaultThreadFactory(), \r\n \t\t\tnew RejectedExecutionHandlerImpl());\r\n }\r\n\n scheduler = new Timer();\n scheduler.scheduleAtFixedRate(new TimerTask() {\n public void run() {\n sendEventsFromQueue();\n }\n }, 0, getDefaultInterval());\n }" ]
This loads plugin file information into a hash for lazy loading later on @param pluginDirectory path of plugin @throws Exception exception
[ "public void identifyClasses(final String pluginDirectory) throws Exception {\n methodInformation.clear();\n jarInformation.clear();\n try {\n new FileTraversal() {\n public void onDirectory(final File d) {\n }\n\n public void onFile(final File f) {\n try {\n // loads class files\n if (f.getName().endsWith(\".class\")) {\n // get the class name for this path\n String className = f.getAbsolutePath();\n className = className.replace(pluginDirectory, \"\");\n className = getClassNameFromPath(className);\n\n logger.info(\"Storing plugin information: {}, {}\", className,\n f.getName());\n\n ClassInformation classInfo = new ClassInformation();\n classInfo.pluginPath = pluginDirectory;\n classInformation.put(className, classInfo);\n } else if (f.getName().endsWith(\".jar\")) {\n // loads JAR packages\n // open up jar and discover files\n // look for anything with /proxy/ in it\n // this may discover things we don't need but that is OK\n try {\n jarInformation.add(f.getAbsolutePath());\n JarFile jarFile = new JarFile(f);\n Enumeration<?> enumer = jarFile.entries();\n\n // Use the Plugin-Name manifest entry to match with the provided pluginName\n String pluginPackageName = jarFile.getManifest().getMainAttributes().getValue(\"plugin-package\");\n if (pluginPackageName == null) {\n return;\n }\n\n while (enumer.hasMoreElements()) {\n Object element = enumer.nextElement();\n String elementName = element.toString();\n\n if (!elementName.endsWith(\".class\")) {\n continue;\n }\n\n String className = getClassNameFromPath(elementName);\n if (className.contains(pluginPackageName)) {\n logger.info(\"Storing plugin information: {}, {}\", className,\n f.getAbsolutePath());\n\n ClassInformation classInfo = new ClassInformation();\n classInfo.pluginPath = f.getAbsolutePath();\n classInformation.put(className, classInfo);\n }\n }\n } catch (Exception e) {\n\n }\n }\n } catch (Exception e) {\n logger.warn(\"Exception caught: {}, {}\", e.getMessage(), e.getCause());\n }\n }\n }.traverse(new File(pluginDirectory));\n } catch (IOException e) {\n throw new Exception(\"Could not identify all plugins: \" + e.getMessage());\n }\n }" ]
[ "@SuppressWarnings(\"unchecked\")\n public Set<RateType> getRateTypes() {\n Set<RateType> result = get(KEY_RATE_TYPES, Set.class);\n if (result == null) {\n return Collections.emptySet();\n }\n return result;\n }", "public static TxInfo getTransactionInfo(Environment env, Bytes prow, Column pcol, long startTs) {\n // TODO ensure primary is visible\n\n IteratorSetting is = new IteratorSetting(10, RollbackCheckIterator.class);\n RollbackCheckIterator.setLocktime(is, startTs);\n\n Entry<Key, Value> entry = ColumnUtil.checkColumn(env, is, prow, pcol);\n\n TxInfo txInfo = new TxInfo();\n\n if (entry == null) {\n txInfo.status = TxStatus.UNKNOWN;\n return txInfo;\n }\n\n ColumnType colType = ColumnType.from(entry.getKey());\n long ts = entry.getKey().getTimestamp() & ColumnConstants.TIMESTAMP_MASK;\n\n switch (colType) {\n case LOCK: {\n if (ts == startTs) {\n txInfo.status = TxStatus.LOCKED;\n txInfo.lockValue = entry.getValue().get();\n } else {\n txInfo.status = TxStatus.UNKNOWN; // locked by another tx\n }\n break;\n }\n case DEL_LOCK: {\n DelLockValue dlv = new DelLockValue(entry.getValue().get());\n\n if (ts != startTs) {\n // expect this to always be false, must be a bug in the iterator\n throw new IllegalStateException(prow + \" \" + pcol + \" (\" + ts + \" != \" + startTs + \") \");\n }\n\n if (dlv.isRollback()) {\n txInfo.status = TxStatus.ROLLED_BACK;\n } else {\n txInfo.status = TxStatus.COMMITTED;\n txInfo.commitTs = dlv.getCommitTimestamp();\n }\n break;\n }\n case WRITE: {\n long timePtr = WriteValue.getTimestamp(entry.getValue().get());\n\n if (timePtr != startTs) {\n // expect this to always be false, must be a bug in the iterator\n throw new IllegalStateException(\n prow + \" \" + pcol + \" (\" + timePtr + \" != \" + startTs + \") \");\n }\n\n txInfo.status = TxStatus.COMMITTED;\n txInfo.commitTs = ts;\n break;\n }\n default:\n throw new IllegalStateException(\"unexpected col type returned \" + colType);\n }\n\n return txInfo;\n }", "@SuppressWarnings(\"unchecked\")\n public static <T> T getJlsDefaultValue(Class<T> type) {\n if(!type.isPrimitive()) {\n return null;\n }\n return (T) JLS_PRIMITIVE_DEFAULT_VALUES.get(type);\n }", "public void bind(T service, Map<String, Object> props) {\n synchronized (serviceMap) {\n serviceMap.put(ServiceUtil.getComparableForServiceRanking(props), service);\n updateSortedServices();\n }\n }", "@PostConstruct\n\tprotected void postConstruct() {\n\t\tif (null == authenticationServices) {\n\t\t\tauthenticationServices = new ArrayList<AuthenticationService>();\n\t\t}\n\t\tif (!excludeDefault) {\n\t\t\tauthenticationServices.add(staticAuthenticationService);\n\t\t}\n\t}", "protected String createName() {\n final StringBuilder buf = new StringBuilder(128);\n try {\n buf.append(InetAddress.getLocalHost().getHostName()).append(COLON)\n .append(ManagementFactory.getRuntimeMXBean().getName().split(\"@\")[0]) // PID\n .append('-').append(this.workerId).append(COLON).append(JAVA_DYNAMIC_QUEUES);\n for (final String queueName : this.queueNames) {\n buf.append(',').append(queueName);\n }\n } catch (UnknownHostException uhe) {\n throw new RuntimeException(uhe);\n }\n return buf.toString();\n }", "public static String getPropertyName(String name) {\n if(name != null && (name.startsWith(\"get\") || name.startsWith(\"set\"))) {\n StringBuilder b = new StringBuilder(name);\n b.delete(0, 3);\n b.setCharAt(0, Character.toLowerCase(b.charAt(0)));\n return b.toString();\n } else {\n return name;\n }\n }", "private boolean parseRemoteDomainControllerAttributes_1_5(final XMLExtendedStreamReader reader, final ModelNode address,\n final List<ModelNode> list, boolean allowDiscoveryOptions) throws XMLStreamException {\n\n final ModelNode update = new ModelNode();\n update.get(OP_ADDR).set(address);\n update.get(OP).set(RemoteDomainControllerAddHandler.OPERATION_NAME);\n\n // Handle attributes\n AdminOnlyDomainConfigPolicy adminOnlyPolicy = AdminOnlyDomainConfigPolicy.DEFAULT;\n boolean requireDiscoveryOptions = false;\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 switch (attribute) {\n case HOST: {\n DomainControllerWriteAttributeHandler.HOST.parseAndSetParameter(value, update, reader);\n break;\n }\n case PORT: {\n DomainControllerWriteAttributeHandler.PORT.parseAndSetParameter(value, update, reader);\n break;\n }\n case SECURITY_REALM: {\n DomainControllerWriteAttributeHandler.SECURITY_REALM.parseAndSetParameter(value, update, reader);\n break;\n }\n case USERNAME: {\n DomainControllerWriteAttributeHandler.USERNAME.parseAndSetParameter(value, update, reader);\n break;\n }\n case ADMIN_ONLY_POLICY: {\n DomainControllerWriteAttributeHandler.ADMIN_ONLY_POLICY.parseAndSetParameter(value, update, reader);\n ModelNode nodeValue = update.get(DomainControllerWriteAttributeHandler.ADMIN_ONLY_POLICY.getName());\n if (nodeValue.getType() != ModelType.EXPRESSION) {\n adminOnlyPolicy = AdminOnlyDomainConfigPolicy.getPolicy(nodeValue.asString());\n }\n break;\n }\n default:\n throw unexpectedAttribute(reader, i);\n }\n }\n }\n\n if (!update.hasDefined(DomainControllerWriteAttributeHandler.HOST.getName())) {\n if (allowDiscoveryOptions) {\n requireDiscoveryOptions = isRequireDiscoveryOptions(adminOnlyPolicy);\n } else {\n throw ParseUtils.missingRequired(reader, Collections.singleton(Attribute.HOST.getLocalName()));\n }\n }\n if (!update.hasDefined(DomainControllerWriteAttributeHandler.PORT.getName())) {\n if (allowDiscoveryOptions) {\n requireDiscoveryOptions = requireDiscoveryOptions || isRequireDiscoveryOptions(adminOnlyPolicy);\n } else {\n throw ParseUtils.missingRequired(reader, Collections.singleton(Attribute.PORT.getLocalName()));\n }\n }\n\n list.add(update);\n return requireDiscoveryOptions;\n }", "@PostConstruct\n public final void init() throws URISyntaxException {\n final String address = getConfig(ADDRESS, null);\n if (address != null) {\n final URI uri = new URI(\"udp://\" + address);\n final String prefix = getConfig(PREFIX, \"mapfish-print\").replace(\"%h\", getHostname());\n final int period = Integer.parseInt(getConfig(PERIOD, \"10\"));\n LOGGER.info(\"Starting a StatsD reporter targeting {} with prefix {} and period {}s\",\n uri, prefix, period);\n this.reporter = StatsDReporter.forRegistry(this.metricRegistry)\n .prefixedWith(prefix)\n .build(uri.getHost(), uri.getPort());\n this.reporter.start(period, TimeUnit.SECONDS);\n }\n }" ]
absolute for advancedJDBCSupport @param row
[ "private boolean absoluteAdvanced(int row)\r\n {\r\n boolean retval = false;\r\n \r\n try\r\n {\r\n if (getRsAndStmt().m_rs != null)\r\n {\r\n if (row == 0)\r\n {\r\n getRsAndStmt().m_rs.beforeFirst();\r\n }\r\n else\r\n {\r\n retval = getRsAndStmt().m_rs.absolute(row); \r\n }\r\n m_current_row = row;\r\n setHasCalledCheck(false);\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n advancedJDBCSupport = false;\r\n }\r\n return retval;\r\n }" ]
[ "public void removeOverride(int overrideId, int pathId, Integer ordinal, String clientUUID) {\n // TODO: reorder priorities after removal\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n int enabledId = getEnabledEndpoint(pathId, overrideId, ordinal, clientUUID).getId();\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, enabledId);\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 D createAndRegisterDeclaration(Map<String, Object> metadata) {\n D declaration;\n if (klass.equals(ImportDeclaration.class)) {\n declaration = (D) ImportDeclarationBuilder.fromMetadata(metadata).build();\n } else if (klass.equals(ExportDeclaration.class)) {\n declaration = (D) ExportDeclarationBuilder.fromMetadata(metadata).build();\n } else {\n throw new IllegalStateException(\"\");\n }\n declarationRegistrationManager.registerDeclaration(declaration);\n return declaration;\n }", "public static ComplexNumber Multiply(ComplexNumber z1, ComplexNumber z2) {\r\n double z1R = z1.real, z1I = z1.imaginary;\r\n double z2R = z2.real, z2I = z2.imaginary;\r\n\r\n return new ComplexNumber(z1R * z2R - z1I * z2I, z1R * z2I + z1I * z2R);\r\n }", "private List<Event> filterEvents(List<Event> events) {\n List<Event> filteredEvents = new ArrayList<Event>();\n for (Event event : events) {\n if (!filter(event)) {\n filteredEvents.add(event);\n }\n }\n return filteredEvents;\n }", "public static Map<String, StoreDefinition> getSystemStoreDefMap() {\n Map<String, StoreDefinition> sysStoreDefMap = Maps.newHashMap();\n List<StoreDefinition> storesDefs = SystemStoreConstants.getAllSystemStoreDefs();\n for(StoreDefinition def: storesDefs) {\n sysStoreDefMap.put(def.getName(), def);\n }\n return sysStoreDefMap;\n }", "public static List<Integer> getStolenPrimaryPartitions(final Cluster currentCluster,\n final Cluster finalCluster,\n final int stealNodeId) {\n List<Integer> finalList = new ArrayList<Integer>(finalCluster.getNodeById(stealNodeId)\n .getPartitionIds());\n\n List<Integer> currentList = new ArrayList<Integer>();\n if(currentCluster.hasNodeWithId(stealNodeId)) {\n currentList = currentCluster.getNodeById(stealNodeId).getPartitionIds();\n } else {\n if(logger.isDebugEnabled()) {\n logger.debug(\"Current cluster does not contain stealer node (cluster : [[[\"\n + currentCluster + \"]]], node id \" + stealNodeId + \")\");\n }\n }\n finalList.removeAll(currentList);\n\n return finalList;\n }", "@Override\n public void onLoadFinished(final Loader<SortedList<T>> loader,\n final SortedList<T> data) {\n isLoading = false;\n mCheckedItems.clear();\n mCheckedVisibleViewHolders.clear();\n mFiles = data;\n mAdapter.setList(data);\n if (mCurrentDirView != null) {\n mCurrentDirView.setText(getFullPath(mCurrentPath));\n }\n // Stop loading now to avoid a refresh clearing the user's selections\n getLoaderManager().destroyLoader( 0 );\n }", "private String getActivityStatus(Task mpxj)\n {\n String result;\n if (mpxj.getActualStart() == null)\n {\n result = \"Not Started\";\n }\n else\n {\n if (mpxj.getActualFinish() == null)\n {\n result = \"In Progress\";\n }\n else\n {\n result = \"Completed\";\n }\n }\n return result;\n }", "public static double[] getTileLayerSize(TileCode code, Envelope maxExtent, double scale) {\n\t\tdouble div = Math.pow(2, code.getTileLevel());\n\t\tdouble tileWidth = Math.ceil((scale * maxExtent.getWidth()) / div) / scale;\n\t\tdouble tileHeight = Math.ceil((scale * maxExtent.getHeight()) / div) / scale;\n\t\treturn new double[] { tileWidth, tileHeight };\n\t}" ]
Retrieve a child record by name. @param key child record name @return child record
[ "public Record getChild(String key)\n {\n Record result = null;\n if (key != null)\n {\n for (Record record : m_records)\n {\n if (key.equals(record.getField()))\n {\n result = record;\n break;\n }\n }\n }\n return result;\n }" ]
[ "public void useNewSOAPServiceWithOldClient() throws Exception {\n \n URL wsdlURL = getClass().getResource(\"/CustomerServiceNew.wsdl\");\n com.example.customerservice.CustomerServiceService service = \n new com.example.customerservice.CustomerServiceService(wsdlURL);\n \n com.example.customerservice.CustomerService customerService = \n service.getCustomerServicePort();\n\n // The outgoing new Customer data needs to be transformed for \n // the old service to understand it and the response from the old service\n // needs to be transformed for this new client to understand it.\n Client client = ClientProxy.getClient(customerService);\n addTransformInterceptors(client.getInInterceptors(),\n client.getOutInterceptors(),\n false);\n \n System.out.println(\"Using new SOAP CustomerService with old client\");\n \n customer.v1.Customer customer = createOldCustomer(\"Barry Old to New SOAP\");\n customerService.updateCustomer(customer);\n customer = customerService.getCustomerByName(\"Barry Old to New SOAP\");\n printOldCustomerDetails(customer);\n }", "public static Iterable<String> toHexStrings(Iterable<ByteArray> arrays) {\n ArrayList<String> ret = new ArrayList<String>();\n for(ByteArray array: arrays)\n ret.add(ByteUtils.toHexString(array.get()));\n return ret;\n }", "public static String getVersionString() {\n\t\tString versionString = \"UNKNOWN\";\n\t\tProperties propeties = getProperites();\n\t\tif(propeties != null) {\n\t\t\tversionString = propeties.getProperty(\"finmath-lib.version\");\n\t\t}\n\t\treturn versionString;\n\t}", "public static csparameter get(nitro_service service) throws Exception{\n\t\tcsparameter obj = new csparameter();\n\t\tcsparameter[] response = (csparameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public void BuildInteractiveObjectFromAnchor(Sensor anchorSensor, String anchorDestination) {\n InteractiveObject interactiveObject = new InteractiveObject();\n interactiveObject.setSensor(anchorSensor, anchorDestination);\n interactiveObjects.add(interactiveObject);\n }", "private void initPixelsArray(BufferedImage image) {\n int width = image.getWidth();\n int height = image.getHeight();\n pixels = new int[width * height];\n image.getRGB(0, 0, width, height, pixels, 0, width);\n\n }", "public void addFkToThisClass(String column)\r\n {\r\n if (fksToThisClass == null)\r\n {\r\n fksToThisClass = new Vector();\r\n }\r\n fksToThisClass.add(column);\r\n fksToThisClassAry = null;\r\n }", "public static PacketType validateHeader(DatagramPacket packet, int port) {\n byte[] data = packet.getData();\n\n if (data.length < PACKET_TYPE_OFFSET) {\n logger.warn(\"Packet is too short to be a Pro DJ Link packet; must be at least \" + PACKET_TYPE_OFFSET +\n \" bytes long, was only \" + data.length + \".\");\n return null;\n }\n\n if (!getMagicHeader().equals(ByteBuffer.wrap(data, 0, MAGIC_HEADER.length))) {\n logger.warn(\"Packet did not have correct nine-byte header for the Pro DJ Link protocol.\");\n return null;\n }\n\n final Map<Byte, PacketType> portMap = PACKET_TYPE_MAP.get(port);\n if (portMap == null) {\n logger.warn(\"Do not know any Pro DJ Link packets that are received on port \" + port + \".\");\n return null;\n }\n\n final PacketType result = portMap.get(data[PACKET_TYPE_OFFSET]);\n if (result == null) {\n logger.warn(\"Do not know any Pro DJ Link packets received on port \" + port + \" with type \" +\n String.format(\"0x%02x\", data[PACKET_TYPE_OFFSET]) + \".\");\n }\n\n return result;\n }", "public void purge(String cacheKey) {\n try {\n if (useMemoryCache) {\n if (memoryCache != null) {\n memoryCache.remove(cacheKey);\n }\n }\n\n if (useDiskCache) {\n if (diskLruCache != null) {\n diskLruCache.remove(cacheKey);\n }\n }\n } catch (Exception e) {\n Log.w(TAG, \"Could not remove entry in cache purge\", e);\n }\n }" ]
Start component timer for current instance @param type - of component
[ "public static void startTimer(final String type) {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return;\n }\n\n instance.components.putIfAbsent(type, new Component(type));\n instance.components.get(type).startTimer();\n }" ]
[ "public static vridparam get(nitro_service service) throws Exception{\n\t\tvridparam obj = new vridparam();\n\t\tvridparam[] response = (vridparam[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public static IntRange GetRange( int[] values, double percent ){\n int total = 0, n = values.length;\n\n // for all values\n for ( int i = 0; i < n; i++ )\n {\n // accumalate total\n total += values[i];\n }\n\n int min, max, hits;\n int h = (int) ( total * ( percent + ( 1 - percent ) / 2 ) );\n\n // get range min value\n for ( min = 0, hits = total; min < n; min++ )\n {\n hits -= values[min];\n if ( hits < h )\n break;\n }\n // get range max value\n for ( max = n - 1, hits = total; max >= 0; max-- )\n {\n hits -= values[max];\n if ( hits < h )\n break;\n }\n return new IntRange( min, max );\n }", "private int getResourceCode(String field) throws MPXJException\n {\n Integer result = m_resourceNumbers.get(field);\n\n if (result == null)\n {\n throw new MPXJException(MPXJException.INVALID_RESOURCE_FIELD_NAME + \" \" + field);\n }\n\n return (result.intValue());\n }", "@Pure\n\tpublic static <P1, P2, P3, P4, P5> Procedure4<P2, P3, P4, P5> curry(final Procedure5<? super P1, ? super P2, ? super P3, ? super P4, ? super P5> procedure,\n\t\t\tfinal P1 argument) {\n\t\tif (procedure == null)\n\t\t\tthrow new NullPointerException(\"procedure\");\n\t\treturn new Procedure4<P2, P3, P4, P5>() {\n\t\t\t@Override\n\t\t\tpublic void apply(P2 p2, P3 p3, P4 p4, P5 p5) {\n\t\t\t\tprocedure.apply(argument, p2, p3, p4, p5);\n\t\t\t}\n\t\t};\n\t}", "public CmsJspInstanceDateBean getToInstanceDate() {\n\n if (m_instanceDate == null) {\n m_instanceDate = new CmsJspInstanceDateBean(getToDate(), m_cms.getRequestContext().getLocale());\n }\n return m_instanceDate;\n }", "public void addImportedPackages(String... importedPackages) {\n\t\tString oldBundles = mainAttributes.get(IMPORT_PACKAGE);\n\t\tif (oldBundles == null)\n\t\t\toldBundles = \"\";\n\t\tBundleList oldResultList = BundleList.fromInput(oldBundles, newline);\n\t\tBundleList resultList = BundleList.fromInput(oldBundles, newline);\n\t\tfor (String bundle : importedPackages)\n\t\t\tresultList.mergeInto(Bundle.fromInput(bundle));\n\t\tString result = resultList.toString();\n\t\tboolean changed = !oldResultList.toString().equals(result);\n\t\tmodified |= changed;\n\t\tif (changed)\n\t\t\tmainAttributes.put(IMPORT_PACKAGE, result);\n\t}", "public void ojbAdd(Object anObject)\r\n {\r\n DSetEntry entry = prepareEntry(anObject);\r\n entry.setPosition(elements.size());\r\n elements.add(entry);\r\n }", "public static ComplexNumber Divide(ComplexNumber z1, ComplexNumber z2) {\r\n\r\n ComplexNumber conj = ComplexNumber.Conjugate(z2);\r\n\r\n double a = z1.real * conj.real + ((z1.imaginary * conj.imaginary) * -1);\r\n double b = z1.real * conj.imaginary + (z1.imaginary * conj.real);\r\n\r\n double c = z2.real * conj.real + ((z2.imaginary * conj.imaginary) * -1);\r\n\r\n return new ComplexNumber(a / c, b / c);\r\n }", "private void processPredecessors(Gantt gantt)\n {\n for (Gantt.Tasks.Task ganttTask : gantt.getTasks().getTask())\n {\n String predecessors = ganttTask.getP();\n if (predecessors != null && !predecessors.isEmpty())\n {\n String wbs = ganttTask.getID();\n Task task = m_taskMap.get(wbs);\n for (String predecessor : predecessors.split(\";\"))\n {\n Task predecessorTask = m_projectFile.getTaskByID(Integer.valueOf(predecessor));\n task.addPredecessor(predecessorTask, RelationType.FINISH_START, ganttTask.getL());\n }\n }\n }\n }" ]
This method is called when the locale of the parent file is updated. It resets the locale specific date attributes to the default values for the new locale. @param locale new locale
[ "public void setLocale(Locale locale)\n {\n List<SimpleDateFormat> formats = new ArrayList<SimpleDateFormat>();\n for (SimpleDateFormat format : m_formats)\n {\n formats.add(new SimpleDateFormat(format.toPattern(), locale));\n }\n\n m_formats = formats.toArray(new SimpleDateFormat[formats.size()]);\n }" ]
[ "private static BsonDocument withNewVersion(\n final BsonDocument document,\n final BsonDocument newVersion\n ) {\n final BsonDocument newDocument = BsonUtils.copyOfDocument(document);\n newDocument.put(DOCUMENT_VERSION_FIELD, newVersion);\n return newDocument;\n }", "public static ModelNode determineHostAddress(final ModelControllerClient client) throws IOException, OperationExecutionException {\n final ModelNode op = Operations.createReadAttributeOperation(EMPTY_ADDRESS, \"local-host-name\");\n ModelNode response = client.execute(op);\n if (Operations.isSuccessfulOutcome(response)) {\n return DeploymentOperations.createAddress(\"host\", Operations.readResult(response).asString());\n }\n throw new OperationExecutionException(op, response);\n }", "public double mean() {\n double total = 0;\n\n final int N = getNumElements();\n for( int i = 0; i < N; i++ ) {\n total += get(i);\n }\n\n return total/N;\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 static ProctorLoadResult verify(\n @Nonnull final TestMatrixArtifact testMatrix,\n final String matrixSource,\n @Nonnull final Map<String, TestSpecification> requiredTests,\n @Nonnull final FunctionMapper functionMapper,\n final ProvidedContext providedContext,\n @Nonnull final Set<String> dynamicTests\n ) {\n final ProctorLoadResult.Builder resultBuilder = ProctorLoadResult.newBuilder();\n\n final Map<String, Map<Integer, String>> allTestsKnownBuckets = Maps.newHashMapWithExpectedSize(requiredTests.size());\n for (final Entry<String, TestSpecification> entry : requiredTests.entrySet()) {\n final Map<Integer, String> bucketValueToName = Maps.newHashMap();\n for (final Entry<String, Integer> bucket : entry.getValue().getBuckets().entrySet()) {\n bucketValueToName.put(bucket.getValue(), bucket.getKey());\n }\n allTestsKnownBuckets.put(entry.getKey(), bucketValueToName);\n }\n\n final Map<String, ConsumableTestDefinition> definedTests = testMatrix.getTests();\n final SetView<String> missingTests = Sets.difference(requiredTests.keySet(), definedTests.keySet());\n resultBuilder.recordAllMissing(missingTests);\n for (final Entry<String, ConsumableTestDefinition> entry : definedTests.entrySet()) {\n final String testName = entry.getKey();\n\n final Map<Integer, String> knownBuckets;\n final TestSpecification specification;\n final boolean isRequired;\n if (allTestsKnownBuckets.containsKey(testName)) {\n // required in specification\n isRequired = true;\n knownBuckets = allTestsKnownBuckets.remove(testName);\n specification = requiredTests.get(testName);\n } else if (dynamicTests.contains(testName)) {\n // resolved by dynamic filter\n isRequired = false;\n knownBuckets = Collections.emptyMap();\n specification = new TestSpecification();\n } else {\n // we don't care about this test\n continue;\n }\n\n final ConsumableTestDefinition testDefinition = entry.getValue();\n\n try {\n verifyTest(testName, testDefinition, specification, knownBuckets, matrixSource, functionMapper, providedContext);\n\n } catch (IncompatibleTestMatrixException e) {\n if (isRequired) {\n LOGGER.error(String.format(\"Unable to load test matrix for a required test %s\", testName), e);\n resultBuilder.recordError(testName, e);\n } else {\n LOGGER.info(String.format(\"Unable to load test matrix for a dynamic test %s\", testName), e);\n resultBuilder.recordIncompatibleDynamicTest(testName, e);\n }\n }\n }\n\n // TODO mjs - is this check additive?\n resultBuilder.recordAllMissing(allTestsKnownBuckets.keySet());\n\n resultBuilder.recordVerifiedRules(providedContext.shouldEvaluate());\n\n final ProctorLoadResult loadResult = resultBuilder.build();\n\n return loadResult;\n }", "public static long count(nitro_service service, String certkey) throws Exception{\n\t\tsslcertkey_crldistribution_binding obj = new sslcertkey_crldistribution_binding();\n\t\tobj.set_certkey(certkey);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tsslcertkey_crldistribution_binding response[] = (sslcertkey_crldistribution_binding[]) obj.get_resources(service,option);\n\t\tif (response != null) {\n\t\t\treturn response[0].__count;\n\t\t}\n\t\treturn 0;\n\t}", "public static InstalledIdentity load(final File jbossHome, final ProductConfig productConfig, final File... repoRoots) throws IOException {\n final InstalledImage installedImage = installedImage(jbossHome);\n return load(installedImage, productConfig, Arrays.<File>asList(repoRoots), Collections.<File>emptyList());\n }", "private void harvestReturnValues(\r\n ProcedureDescriptor proc,\r\n Object obj,\r\n PreparedStatement stmt)\r\n throws PersistenceBrokerSQLException\r\n {\r\n // If the procedure descriptor is null or has no return values or\r\n // if the statement is not a callable statment, then we're done.\r\n if ((proc == null) || (!proc.hasReturnValues()))\r\n {\r\n return;\r\n }\r\n\r\n // Set up the callable statement\r\n CallableStatement callable = (CallableStatement) stmt;\r\n\r\n // This is the index that we'll use to harvest the return value(s).\r\n int index = 0;\r\n\r\n // If the proc has a return value, then try to harvest it.\r\n if (proc.hasReturnValue())\r\n {\r\n\r\n // Increment the index\r\n index++;\r\n\r\n // Harvest the value.\r\n this.harvestReturnValue(obj, callable, proc.getReturnValueFieldRef(), index);\r\n }\r\n\r\n // Check each argument. If it's returned by the procedure,\r\n // then harvest the value.\r\n Iterator iter = proc.getArguments().iterator();\r\n while (iter.hasNext())\r\n {\r\n index++;\r\n ArgumentDescriptor arg = (ArgumentDescriptor) iter.next();\r\n if (arg.getIsReturnedByProcedure())\r\n {\r\n this.harvestReturnValue(obj, callable, arg.getFieldRef(), index);\r\n }\r\n }\r\n }", "public static base_responses update(nitro_service client, clusterinstance resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tclusterinstance updateresources[] = new clusterinstance[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new clusterinstance();\n\t\t\t\tupdateresources[i].clid = resources[i].clid;\n\t\t\t\tupdateresources[i].deadinterval = resources[i].deadinterval;\n\t\t\t\tupdateresources[i].hellointerval = resources[i].hellointerval;\n\t\t\t\tupdateresources[i].preemption = resources[i].preemption;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}" ]
Curries a procedure that takes five arguments. @param procedure the original procedure. May not be <code>null</code>. @param argument the fixed first argument of {@code procedure}. @return a procedure that takes four arguments. Never <code>null</code>.
[ "@Pure\n\tpublic static <P1, P2, P3, P4, P5> Procedure4<P2, P3, P4, P5> curry(final Procedure5<? super P1, ? super P2, ? super P3, ? super P4, ? super P5> procedure,\n\t\t\tfinal P1 argument) {\n\t\tif (procedure == null)\n\t\t\tthrow new NullPointerException(\"procedure\");\n\t\treturn new Procedure4<P2, P3, P4, P5>() {\n\t\t\t@Override\n\t\t\tpublic void apply(P2 p2, P3 p3, P4 p4, P5 p5) {\n\t\t\t\tprocedure.apply(argument, p2, p3, p4, p5);\n\t\t\t}\n\t\t};\n\t}" ]
[ "private void validateSameDay(ProjectCalendar calendar, LinkedList<TimephasedWork> list)\n {\n for (TimephasedWork assignment : list)\n {\n Date assignmentStart = assignment.getStart();\n Date calendarStartTime = calendar.getStartTime(assignmentStart);\n Date assignmentStartTime = DateHelper.getCanonicalTime(assignmentStart);\n Date assignmentFinish = assignment.getFinish();\n Date calendarFinishTime = calendar.getFinishTime(assignmentFinish);\n Date assignmentFinishTime = DateHelper.getCanonicalTime(assignmentFinish);\n double totalWork = assignment.getTotalAmount().getDuration();\n\n if (assignmentStartTime != null && calendarStartTime != null)\n {\n if ((totalWork == 0 && assignmentStartTime.getTime() != calendarStartTime.getTime()) || (assignmentStartTime.getTime() < calendarStartTime.getTime()))\n {\n assignmentStart = DateHelper.setTime(assignmentStart, calendarStartTime);\n assignment.setStart(assignmentStart);\n }\n }\n\n if (assignmentFinishTime != null && calendarFinishTime != null)\n {\n if ((totalWork == 0 && assignmentFinishTime.getTime() != calendarFinishTime.getTime()) || (assignmentFinishTime.getTime() > calendarFinishTime.getTime()))\n {\n assignmentFinish = DateHelper.setTime(assignmentFinish, calendarFinishTime);\n assignment.setFinish(assignmentFinish);\n }\n }\n }\n }", "public static <T> T createObject(final Class<T> clazz, final Object[] args, final Map<String,Object> vars) \n throws NoSuchConstructorException, AmbiguousConstructorException, ReflectiveOperationException {\n return invokeSetters(findConstructor(clazz, args).newInstance(args), vars);\n }", "public void readData(BufferedReader in) throws IOException {\r\n String line, value;\r\n // skip old variables if still present\r\n lexOptions.readData(in);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n try {\r\n tlpParams = (TreebankLangParserParams) Class.forName(value).newInstance();\r\n } catch (Exception e) {\r\n IOException ioe = new IOException(\"Problem instantiating parserParams: \" + line);\r\n ioe.initCause(e);\r\n throw ioe;\r\n }\r\n line = in.readLine();\r\n // ensure backwards compatibility\r\n if (line.matches(\"^forceCNF.*\")) {\r\n value = line.substring(line.indexOf(' ') + 1);\r\n forceCNF = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n }\r\n value = line.substring(line.indexOf(' ') + 1);\r\n doPCFG = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n doDep = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n freeDependencies = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n directional = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n genStop = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n distance = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n coarseDistance = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n dcTags = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n if ( ! line.matches(\"^nPrune.*\")) {\r\n throw new RuntimeException(\"Expected nPrune, found: \" + line);\r\n }\r\n value = line.substring(line.indexOf(' ') + 1);\r\n nodePrune = Boolean.parseBoolean(value);\r\n line = in.readLine(); // get rid of last line\r\n if (line.length() != 0) {\r\n throw new RuntimeException(\"Expected blank line, found: \" + line);\r\n }\r\n }", "@Pure\n\tpublic static <P1, P2, P3, RESULT> Function2<P2, P3, RESULT> curry(final Function3<? super P1, ? super P2, ? super P3, ? extends RESULT> function,\n\t\t\tfinal P1 argument) {\n\t\tif (function == null)\n\t\t\tthrow new NullPointerException(\"function\");\n\t\treturn new Function2<P2, P3, RESULT>() {\n\t\t\t@Override\n\t\t\tpublic RESULT apply(P2 p2, P3 p3) {\n\t\t\t\treturn function.apply(argument, p2, p3);\n\t\t\t}\n\t\t};\n\t}", "public static Map<String, Object> with(Object... params) {\n Map<String, Object> map = new HashMap<>();\n for (int i = 0; i < params.length; i++) {\n map.put(String.valueOf(i), params[i]);\n }\n return map;\n }", "public static final Bytes of(ByteBuffer bb) {\n Objects.requireNonNull(bb);\n if (bb.remaining() == 0) {\n return EMPTY;\n }\n byte[] data;\n if (bb.hasArray()) {\n data = Arrays.copyOfRange(bb.array(), bb.position() + bb.arrayOffset(),\n bb.limit() + bb.arrayOffset());\n } else {\n data = new byte[bb.remaining()];\n // duplicate so that it does not change position\n bb.duplicate().get(data);\n }\n return new Bytes(data);\n }", "public double distance(Vector3d v) {\n double dx = x - v.x;\n double dy = y - v.y;\n double dz = z - v.z;\n\n return Math.sqrt(dx * dx + dy * dy + dz * dz);\n }", "void reset()\n {\n if (!hasStopped)\n {\n throw new IllegalStateException(\"cannot reset a non stopped queue poller\");\n }\n hasStopped = false;\n run = true;\n lastLoop = null;\n loop = new Semaphore(0);\n }", "public static base_response delete(nitro_service client, nsip6 resource) throws Exception {\n\t\tnsip6 deleteresource = new nsip6();\n\t\tdeleteresource.ipv6address = resource.ipv6address;\n\t\tdeleteresource.td = resource.td;\n\t\treturn deleteresource.delete_resource(client);\n\t}" ]
Set the main attribute "Bundle-Activator" to the given value. @param bundleActivator The new value
[ "public void setBundleActivator(String bundleActivator) {\n\t\tString old = mainAttributes.get(BUNDLE_ACTIVATOR);\n\t\tif (!bundleActivator.equals(old)) {\n\t\t\tthis.mainAttributes.put(BUNDLE_ACTIVATOR, bundleActivator);\n\t\t\tthis.modified = true;\n\t\t\tthis.bundleActivator = bundleActivator;\n\t\t}\n\t}" ]
[ "public boolean projectExists(String name) throws IllegalArgumentException {\n if (name == null || name.isEmpty()) {\n throw new IllegalArgumentException(\"Project name cannot be empty\");\n }\n return listProjects().stream()\n .map(p -> p.getMetadata().getName())\n .anyMatch(Predicate.isEqual(name));\n }", "public void useSimpleProxy() {\n String webAppAddress = \"http://localhost:\" + port + \"/services/personservice\";\n PersonService proxy = JAXRSClientFactory.create(webAppAddress, PersonService.class);\n\n new PersonServiceProxyClient(proxy).useService();\n }", "private static int getBinaryLength(int version, QrMode[] inputModeUnoptimized, int[] inputData, boolean gs1, int eciMode) {\n\n int i, j;\n QrMode currentMode;\n int inputLength = inputModeUnoptimized.length;\n int count = 0;\n int alphaLength;\n int percent = 0;\n\n // ZINT NOTE: in Zint, this call modifies the input mode array directly; here, we leave\n // the original array alone so that subsequent binary length checks don't irrevocably\n // optimize the mode array for the wrong QR Code version\n QrMode[] inputMode = applyOptimisation(version, inputModeUnoptimized);\n\n currentMode = QrMode.NULL;\n\n if (gs1) {\n count += 4;\n }\n\n if (eciMode != 3) {\n count += 12;\n }\n\n for (i = 0; i < inputLength; i++) {\n if (inputMode[i] != currentMode) {\n count += 4;\n switch (inputMode[i]) {\n case KANJI:\n count += tribus(version, 8, 10, 12);\n count += (blockLength(i, inputMode) * 13);\n break;\n case BINARY:\n count += tribus(version, 8, 16, 16);\n for (j = i; j < (i + blockLength(i, inputMode)); j++) {\n if (inputData[j] > 0xff) {\n count += 16;\n } else {\n count += 8;\n }\n }\n break;\n case ALPHANUM:\n count += tribus(version, 9, 11, 13);\n alphaLength = blockLength(i, inputMode);\n // In alphanumeric mode % becomes %%\n if (gs1) {\n for (j = i; j < (i + alphaLength); j++) { // TODO: need to do this only if in GS1 mode? or is the other code wrong? https://sourceforge.net/p/zint/tickets/104/#227b\n if (inputData[j] == '%') {\n percent++;\n }\n }\n }\n alphaLength += percent;\n switch (alphaLength % 2) {\n case 0:\n count += (alphaLength / 2) * 11;\n break;\n case 1:\n count += ((alphaLength - 1) / 2) * 11;\n count += 6;\n break;\n }\n break;\n case NUMERIC:\n count += tribus(version, 10, 12, 14);\n switch (blockLength(i, inputMode) % 3) {\n case 0:\n count += (blockLength(i, inputMode) / 3) * 10;\n break;\n case 1:\n count += ((blockLength(i, inputMode) - 1) / 3) * 10;\n count += 4;\n break;\n case 2:\n count += ((blockLength(i, inputMode) - 2) / 3) * 10;\n count += 7;\n break;\n }\n break;\n }\n currentMode = inputMode[i];\n }\n }\n\n return count;\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 Set<String> getStoreNamesSet(List<StoreDefinition> storeDefList) {\n HashSet<String> storeSet = new HashSet<String>();\n for(StoreDefinition def: storeDefList) {\n storeSet.add(def.getName());\n }\n return storeSet;\n }", "public void addAttribute(String attributeName, String attributeValue)\r\n {\r\n if (attributeName != null && attributeName.startsWith(JDBC_PROPERTY_NAME_PREFIX))\r\n {\r\n final String jdbcPropertyName = attributeName.substring(JDBC_PROPERTY_NAME_LENGTH);\r\n jdbcProperties.setProperty(jdbcPropertyName, attributeValue);\r\n }\r\n else if (attributeName != null && attributeName.startsWith(DBCP_PROPERTY_NAME_PREFIX))\r\n {\r\n final String dbcpPropertyName = attributeName.substring(DBCP_PROPERTY_NAME_LENGTH);\r\n dbcpProperties.setProperty(dbcpPropertyName, attributeValue);\r\n }\r\n else\r\n {\r\n super.addAttribute(attributeName, attributeValue);\r\n }\r\n }", "public static snmpmanager[] get(nitro_service service) throws Exception{\n\t\tsnmpmanager obj = new snmpmanager();\n\t\tsnmpmanager[] response = (snmpmanager[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public UpdateBuilder<T, ID> updateColumnExpression(String columnName, String expression) throws SQLException {\n\t\tFieldType fieldType = verifyColumnName(columnName);\n\t\tif (fieldType.isForeignCollection()) {\n\t\t\tthrow new SQLException(\"Can't update foreign colletion field: \" + columnName);\n\t\t}\n\t\taddUpdateColumnToList(columnName, new SetExpression(columnName, fieldType, expression));\n\t\treturn this;\n\t}", "public List<String> getListAttribute(String section, String name) {\n return split(getAttribute(section, name));\n }" ]
Returns the Map value of the field. @return the Map value of the field. It returns a reference of the value both for <code>MAP</code> and <code>LIST_MAP</code>. @throws IllegalArgumentException if the value cannot be converted to Map.
[ "@SuppressWarnings(\"unchecked\")\n public Map<String, Field> getValueAsMap() {\n return (Map<String, Field>) type.convert(getValue(), Type.MAP);\n }" ]
[ "String getQuery(String key)\n {\n String res = this.adapter.getSqlText(key);\n if (res == null)\n {\n throw new DatabaseException(\"Query \" + key + \" does not exist\");\n }\n return res;\n }", "public MBeanOperationInfo getOperationInfo(String operationName)\n throws OperationNotFoundException, UnsupportedEncodingException {\n\n String decodedOperationName = sanitizer.urlDecode(operationName, encoding);\n Map<String, MBeanOperationInfo> operationMap = getOperationMetadata();\n if (operationMap.containsKey(decodedOperationName)) {\n return operationMap.get(decodedOperationName);\n }\n throw new OperationNotFoundException(\"Could not find operation \" + operationName + \" on MBean \" +\n objectName.getCanonicalName());\n }", "public static BoxRetentionPolicyAssignment.Info createAssignmentToMetadata(BoxAPIConnection api,\r\n String policyID,\r\n String templateID,\r\n MetadataFieldFilter... filter) {\r\n JsonObject assignTo = new JsonObject().add(\"type\", TYPE_METADATA).add(\"id\", templateID);\r\n JsonArray filters = null;\r\n if (filter.length > 0) {\r\n filters = new JsonArray();\r\n for (MetadataFieldFilter f : filter) {\r\n filters.add(f.getJsonObject());\r\n }\r\n }\r\n return createAssignment(api, policyID, assignTo, filters);\r\n }", "public String getRelativePath() {\n final StringBuilder builder = new StringBuilder();\n for(final String p : path) {\n builder.append(p).append(\"/\");\n }\n builder.append(getName());\n return builder.toString();\n }", "public String getProfileIdFromClientId(int id) {\n return (String) sqlService.getFromTable(Constants.CLIENT_PROFILE_ID, Constants.GENERIC_ID, id, Constants.DB_TABLE_CLIENT);\n }", "public ExecutorLoadBalancingConfig<GROUP> useLoadBalancedEnumOrdinalPrioritizer(Class<GROUP> groupClass) {\n if(!groupClass.isEnum()) {\n throw new IllegalArgumentException(\"The group class \"+groupClass+\" is not an enum\");\n }\n groupPrioritizer = new LoadBalancedPriorityPrioritizer<GROUP>(new EnumOrdinalPrioritizer<GROUP>());\n return this;\n }", "public static void addTTLIndex(DBCollection collection, String field, int ttl) {\n if (ttl <= 0) {\n throw new IllegalArgumentException(\"TTL must be positive\");\n }\n collection.createIndex(new BasicDBObject(field, 1), new BasicDBObject(\"expireAfterSeconds\", ttl));\n }", "public void extractFieldTypes(DatabaseType databaseType) throws SQLException {\n\t\tif (fieldTypes == null) {\n\t\t\tif (fieldConfigs == null) {\n\t\t\t\tfieldTypes = extractFieldTypes(databaseType, dataClass, tableName);\n\t\t\t} else {\n\t\t\t\tfieldTypes = convertFieldConfigs(databaseType, tableName, fieldConfigs);\n\t\t\t}\n\t\t}\n\t}", "public void setFrustum(float fovy, float aspect, float znear, float zfar)\n {\n Matrix4f projMatrix = new Matrix4f();\n projMatrix.perspective((float) Math.toRadians(fovy), aspect, znear, zfar);\n setFrustum(projMatrix);\n }" ]
Put a new resource description into the index, or remove one if the delta has no new description. A delta for a particular URI may be registered more than once; overwriting any earlier registration. @param delta The resource change. @since 2.9
[ "public void register(Delta delta) {\n\t\tfinal IResourceDescription newDesc = delta.getNew();\n\t\tif (newDesc == null) {\n\t\t\tremoveDescription(delta.getUri());\n\t\t} else {\n\t\t\taddDescription(delta.getUri(), newDesc);\n\t\t}\n\t}" ]
[ "public static clusternodegroup_binding get(nitro_service service, String name) throws Exception{\n\t\tclusternodegroup_binding obj = new clusternodegroup_binding();\n\t\tobj.set_name(name);\n\t\tclusternodegroup_binding response = (clusternodegroup_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static XMLStreamException unexpectedEndElement(final XMLExtendedStreamReader reader) {\n return ControllerLogger.ROOT_LOGGER.unexpectedEndElement(reader.getName(), reader.getLocation());\n }", "public static Object toObject(Class<?> clazz, Object value) throws ParseException {\n if (value == null) {\n return null;\n }\n if (clazz == null) {\n return value;\n }\n\n if (java.sql.Date.class.isAssignableFrom(clazz)) {\n return toDate(value);\n }\n if (java.sql.Time.class.isAssignableFrom(clazz)) {\n return toTime(value);\n }\n if (java.sql.Timestamp.class.isAssignableFrom(clazz)) {\n return toTimestamp(value);\n }\n if (java.util.Date.class.isAssignableFrom(clazz)) {\n return toDateTime(value);\n }\n\n return value;\n }", "public static MBeanServerConnection getMBeanServerConnection(Process p, boolean startAgent) {\n try {\n final JMXServiceURL serviceURL = getLocalConnectorAddress(p, startAgent);\n final JMXConnector connector = JMXConnectorFactory.connect(serviceURL);\n final MBeanServerConnection mbsc = connector.getMBeanServerConnection();\n return mbsc;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }", "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 }", "public Path getTransformedXSLTPath(FileModel payload)\n {\n ReportService reportService = new ReportService(getGraphContext());\n Path outputPath = reportService.getReportDirectory();\n outputPath = outputPath.resolve(this.getRelativeTransformedXSLTPath(payload));\n if (!Files.isDirectory(outputPath))\n {\n try\n {\n Files.createDirectories(outputPath);\n }\n catch (IOException e)\n {\n throw new WindupException(\"Failed to create output directory at: \" + outputPath + \" due to: \"\n + e.getMessage(), e);\n }\n }\n return outputPath;\n }", "public PortComponentMetaData getPortComponentByWsdlPort(String name)\n {\n ArrayList<String> pcNames = new ArrayList<String>();\n for (PortComponentMetaData pc : portComponents)\n {\n String wsdlPortName = pc.getWsdlPort().getLocalPart();\n if (wsdlPortName.equals(name))\n return pc;\n\n pcNames.add(wsdlPortName);\n }\n\n Loggers.METADATA_LOGGER.cannotGetPortComponentName(name, pcNames);\n return null;\n }", "public void setMaintenanceMode(String appName, boolean enable) {\n connection.execute(new AppUpdate(appName, enable), apiKey);\n }", "public OperationTransformerRegistry resolveServer(final ModelVersion mgmtVersion, final ModelNode subsystems) {\n return resolveServer(mgmtVersion, resolveVersions(subsystems));\n }" ]
Should be called after all columns have been created @param headerStyle @param totalStyle @param totalHeaderStyle @return
[ "public CrosstabBuilder setColumnStyles(Style headerStyle, Style totalStyle, Style totalHeaderStyle) {\r\n\t\tcrosstab.setColumnHeaderStyle(headerStyle);\r\n\t\tcrosstab.setColumnTotalheaderStyle(totalHeaderStyle);\r\n\t\tcrosstab.setColumnTotalStyle(totalStyle);\r\n\t\treturn this;\r\n\t}" ]
[ "public void addComparator(Comparator<T> comparator, boolean ascending) {\n\t\tthis.comparators.add(new InvertibleComparator<T>(comparator, ascending));\n\t}", "private String computeMorse(BytesRef term) {\n StringBuilder stringBuilder = new StringBuilder();\n int i = term.offset + prefixOffset;\n for (; i < term.length; i++) {\n if (ALPHABET_MORSE.containsKey(term.bytes[i])) {\n stringBuilder.append(ALPHABET_MORSE.get(term.bytes[i]) + \" \");\n } else if(term.bytes[i]!=0x00){\n return null;\n } else {\n break;\n }\n }\n return stringBuilder.toString();\n }", "private void writeResources()\n {\n Resources resources = m_factory.createResources();\n m_plannerProject.setResources(resources);\n List<net.sf.mpxj.planner.schema.Resource> resourceList = resources.getResource();\n for (Resource mpxjResource : m_projectFile.getResources())\n {\n net.sf.mpxj.planner.schema.Resource plannerResource = m_factory.createResource();\n resourceList.add(plannerResource);\n writeResource(mpxjResource, plannerResource);\n }\n }", "public boolean isWorkingDate(Date date)\n {\n Calendar cal = DateHelper.popCalendar(date);\n Day day = Day.getInstance(cal.get(Calendar.DAY_OF_WEEK));\n DateHelper.pushCalendar(cal);\n return isWorkingDate(date, day);\n }", "public Pair<int[][][][], int[][]> documentsToDataAndLabels(Collection<List<IN>> documents) {\r\n\r\n // first index is the number of the document\r\n // second index is position in the document also the index of the\r\n // clique/factor table\r\n // third index is the number of elements in the clique/window these features\r\n // are for (starting with last element)\r\n // fourth index is position of the feature in the array that holds them\r\n // element in data[i][j][k][m] is the index of the mth feature occurring in\r\n // position k of the jth clique of the ith document\r\n // int[][][][] data = new int[documentsSize][][][];\r\n List<int[][][]> data = new ArrayList<int[][][]>();\r\n\r\n // first index is the number of the document\r\n // second index is the position in the document\r\n // element in labels[i][j] is the index of the correct label (if it exists)\r\n // at position j in document i\r\n // int[][] labels = new int[documentsSize][];\r\n List<int[]> labels = new ArrayList<int[]>();\r\n\r\n int numDatums = 0;\r\n\r\n for (List<IN> doc : documents) {\r\n Pair<int[][][], int[]> docPair = documentToDataAndLabels(doc);\r\n data.add(docPair.first());\r\n labels.add(docPair.second());\r\n numDatums += doc.size();\r\n }\r\n\r\n System.err.println(\"numClasses: \" + classIndex.size() + ' ' + classIndex);\r\n System.err.println(\"numDocuments: \" + data.size());\r\n System.err.println(\"numDatums: \" + numDatums);\r\n System.err.println(\"numFeatures: \" + featureIndex.size());\r\n printFeatures();\r\n\r\n int[][][][] dataA = new int[0][][][];\r\n int[][] labelsA = new int[0][];\r\n\r\n return new Pair<int[][][][], int[][]>(data.toArray(dataA), labels.toArray(labelsA));\r\n }", "public static double blackScholesDigitalOptionVega(\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 vega\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 vega = - Math.exp(-riskFreeRate * optionMaturity) * Math.exp(-0.5*dMinus*dMinus) / Math.sqrt(2.0 * Math.PI) * dPlus / volatility;\n\n\t\t\treturn vega;\n\t\t}\n\t}", "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 }", "static void init() {// NOPMD\n\n\t\tdetermineIfNTEventLogIsSupported();\n\n\t\tURL resource = null;\n\n\t\tfinal String configurationOptionStr = OptionConverter.getSystemProperty(DEFAULT_CONFIGURATION_KEY, null);\n\n\t\tif (configurationOptionStr != null) {\n\t\t\ttry {\n\t\t\t\tresource = new URL(configurationOptionStr);\n\t\t\t} catch (MalformedURLException ex) {\n\t\t\t\t// so, resource is not a URL:\n\t\t\t\t// attempt to get the resource from the class path\n\t\t\t\tresource = Loader.getResource(configurationOptionStr);\n\t\t\t}\n\t\t}\n\t\tif (resource == null) {\n\t\t\tresource = Loader.getResource(DEFAULT_CONFIGURATION_FILE); // NOPMD\n\t\t}\n\n\t\tif (resource == null) {\n\t\t\tSystem.err.println(\"[FoundationLogger] Can not find resource: \" + DEFAULT_CONFIGURATION_FILE); // NOPMD\n\t\t\tthrow new FoundationIOException(\"Can not find resource: \" + DEFAULT_CONFIGURATION_FILE); // NOPMD\n\t\t}\n\n\t\t// update the log manager to use the Foundation repository.\n\t\tfinal RepositorySelector foundationRepositorySelector = new FoundationRepositorySelector(FoundationLogFactory.foundationLogHierarchy);\n\t\tLogManager.setRepositorySelector(foundationRepositorySelector, null);\n\n\t\t// set logger to info so we always want to see these logs even if root\n\t\t// is set to ERROR.\n\t\tfinal Logger logger = getLogger(FoundationLogger.class);\n\n\t\tfinal String logPropFile = resource.getPath();\n\t\tlog4jConfigProps = getLogProperties(resource);\n\t\t\n\t\t// select and configure again so the loggers are created with the right\n\t\t// level after the repository selector was updated.\n\t\tOptionConverter.selectAndConfigure(resource, null, FoundationLogFactory.foundationLogHierarchy);\n\n\t\t// start watching for property changes\n\t\tsetUpPropFileReloading(logger, logPropFile, log4jConfigProps);\n\n\t\t// add syslog appender or windows event viewer appender\n//\t\tsetupOSSystemLog(logger, log4jConfigProps);\n\n\t\t// parseMarkerPatterns(log4jConfigProps);\n\t\t// parseMarkerPurePattern(log4jConfigProps);\n//\t\tudpateMarkerStructuredLogOverrideMap(logger);\n\n AbstractFoundationLoggingMarker.init();\n\n\t\tupdateSniffingLoggersLevel(logger);\n\n setupJULSupport(resource);\n\n }", "protected <C> C convert(Object object, Class<C> targetClass) {\n return this.mapper.convertValue(object, targetClass);\n }" ]
Creates an option to deploy existing content to the runtime for each deployment @param deployments a set of deployments to deploy @return the deploy operation
[ "public static Operation createDeployOperation(final Set<DeploymentDescription> deployments) {\n Assertions.requiresNotNullOrNotEmptyParameter(\"deployments\", deployments);\n final CompositeOperationBuilder builder = CompositeOperationBuilder.create(true);\n for (DeploymentDescription deployment : deployments) {\n addDeployOperationStep(builder, deployment);\n }\n return builder.build();\n }" ]
[ "protected boolean isStoredProcedure(String sql)\r\n {\r\n /*\r\n Stored procedures start with\r\n {?= call <procedure-name>[<arg1>,<arg2>, ...]}\r\n or\r\n {call <procedure-name>[<arg1>,<arg2>, ...]}\r\n but also statements with white space like\r\n { ?= call <procedure-name>[<arg1>,<arg2>, ...]}\r\n are possible.\r\n */\r\n int k = 0, i = 0;\r\n char c;\r\n while(k < 3 && i < sql.length())\r\n {\r\n c = sql.charAt(i);\r\n if(c != ' ')\r\n {\r\n switch (k)\r\n {\r\n case 0:\r\n if(c != '{') return false;\r\n break;\r\n case 1:\r\n if(c != '?' && c != 'c') return false;\r\n break;\r\n case 2:\r\n if(c != '=' && c != 'a') return false;\r\n break;\r\n }\r\n k++;\r\n }\r\n i++;\r\n }\r\n return true;\r\n }", "public static base_response delete(nitro_service client, dnsaaaarec resource) throws Exception {\n\t\tdnsaaaarec deleteresource = new dnsaaaarec();\n\t\tdeleteresource.hostname = resource.hostname;\n\t\tdeleteresource.ipv6address = resource.ipv6address;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public static void addIndex(DBCollection collection, String field, boolean asc, boolean background) {\n int dir = (asc) ? 1 : -1;\n collection.createIndex(new BasicDBObject(field, dir), new BasicDBObject(\"background\", background));\n }", "public void close() throws IOException {\n final ManagedBinding binding = this.socketBindingManager.getNamedRegistry().getManagedBinding(this.name);\n if (binding == null) {\n return;\n }\n binding.close();\n }", "protected <T> T getDatamodelObjectFromResponse(JsonNode response, List<String> path, Class<T> targetClass) throws JsonProcessingException {\n\t\tif(response == null) {\n\t\t\tthrow new JsonMappingException(\"The API response is null\");\n\t\t}\n\t\tJsonNode currentNode = response;\n\t\tfor(String field : path) {\n\t\t\tif (!currentNode.has(field)) {\n\t\t\t\tthrow new JsonMappingException(\"Field '\"+field+\"' not found in API response.\");\n\t\t\t}\n\t\t\tcurrentNode = currentNode.path(field);\n\t\t}\n\t\treturn mapper.treeToValue(currentNode, targetClass);\n\t}", "public static java.sql.Time getTime(Object value) {\n try {\n return toTime(value);\n } catch (ParseException pe) {\n pe.printStackTrace();\n return null;\n }\n }", "public ReferenceBuilder withPropertyValue(PropertyIdValue propertyIdValue,\n\t\t\tValue value) {\n\t\tgetSnakList(propertyIdValue).add(\n\t\t\t\tfactory.getValueSnak(propertyIdValue, value));\n\t\treturn getThis();\n\t}", "public void logException(Level level) {\n if (!LOG.isLoggable(level)) {\n return;\n }\n final StringBuilder builder = new StringBuilder();\n builder.append(\"\\n----------------------------------------------------\");\n builder.append(\"\\nMonitoringException\");\n builder.append(\"\\n----------------------------------------------------\");\n builder.append(\"\\nCode: \").append(code);\n builder.append(\"\\nMessage: \").append(message);\n builder.append(\"\\n----------------------------------------------------\");\n if (events != null) {\n for (Event event : events) {\n builder.append(\"\\nEvent:\");\n if (event.getMessageInfo() != null) {\n builder.append(\"\\nMessage id: \").append(event.getMessageInfo().getMessageId());\n builder.append(\"\\nFlow id: \").append(event.getMessageInfo().getFlowId());\n builder.append(\"\\n----------------------------------------------------\");\n } else {\n builder.append(\"\\nNo message id and no flow id\");\n }\n }\n }\n builder.append(\"\\n----------------------------------------------------\\n\");\n LOG.log(level, builder.toString(), this);\n }", "public static Object readObject(File file) throws IOException,\n ClassNotFoundException {\n FileInputStream fileIn = new FileInputStream(file);\n ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(fileIn));\n try {\n return in.readObject();\n } finally {\n IoUtils.safeClose(in);\n }\n }" ]
Send JSON representation of given data object to all connections connected to given URL @param data the data object @param url the url
[ "public void sendJsonToUrl(Object data, String url) {\n sendToUrl(JSON.toJSONString(data), url);\n }" ]
[ "public static Double checkLongitude(String name, Double longitude) {\n if (longitude == null) {\n throw new IndexException(\"{} required\", name);\n } else if (longitude < MIN_LONGITUDE || longitude > MAX_LONGITUDE) {\n throw new IndexException(\"{} must be in range [{}, {}], but found {}\",\n name,\n MIN_LONGITUDE,\n MAX_LONGITUDE,\n longitude);\n }\n return longitude;\n }", "protected byte[] readByteArray(InputStream is, int size) throws IOException\n {\n byte[] buffer = new byte[size];\n if (is.read(buffer) != buffer.length)\n {\n throw new EOFException();\n }\n return (buffer);\n }", "public void retrieveCollections(Object newObj, ClassDescriptor cld, boolean forced) throws PersistenceBrokerException\r\n {\r\n doRetrieveCollections(newObj, cld, forced, false);\r\n }", "private void writeClassData() {\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(\"classes.csv\"))) {\n\n\t\t\tout.println(\"Id\" + \",Label\" + \",Description\" + \",URL\" + \",Image\"\n\t\t\t\t\t+ \",Number of direct instances\"\n\t\t\t\t\t+ \",Number of direct subclasses\" + \",Direct superclasses\"\n\t\t\t\t\t+ \",All superclasses\" + \",Related properties\");\n\n\t\t\tList<Entry<EntityIdValue, ClassRecord>> list = new ArrayList<>(\n\t\t\t\t\tthis.classRecords.entrySet());\n\t\t\tCollections.sort(list, new ClassUsageRecordComparator());\n\t\t\tfor (Entry<EntityIdValue, ClassRecord> entry : list) {\n\t\t\t\tif (entry.getValue().itemCount > 0\n\t\t\t\t\t\t|| entry.getValue().subclassCount > 0) {\n\t\t\t\t\tprintClassRecord(out, entry.getValue(), entry.getKey());\n\t\t\t\t}\n\t\t\t}\n\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}", "private List<Row> getRows(String sql) throws SQLException\n {\n allocateConnection();\n\n try\n {\n List<Row> result = new LinkedList<Row>();\n\n m_ps = m_connection.prepareStatement(sql);\n m_rs = m_ps.executeQuery();\n populateMetaData();\n while (m_rs.next())\n {\n result.add(new MpdResultSetRow(m_rs, m_meta));\n }\n\n return (result);\n }\n\n finally\n {\n releaseConnection();\n }\n }", "public static void writeFlowId(Message message, String flowId) {\n Map<String, List<String>> headers = getOrCreateProtocolHeader(message);\n headers.put(FLOWID_HTTP_HEADER_NAME, Collections.singletonList(flowId));\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"HTTP header '\" + FLOWID_HTTP_HEADER_NAME + \"' set to: \" + flowId);\n }\n }", "public Path getTransformedXSLTPath(FileModel payload)\n {\n ReportService reportService = new ReportService(getGraphContext());\n Path outputPath = reportService.getReportDirectory();\n outputPath = outputPath.resolve(this.getRelativeTransformedXSLTPath(payload));\n if (!Files.isDirectory(outputPath))\n {\n try\n {\n Files.createDirectories(outputPath);\n }\n catch (IOException e)\n {\n throw new WindupException(\"Failed to create output directory at: \" + outputPath + \" due to: \"\n + e.getMessage(), e);\n }\n }\n return outputPath;\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 Object getProperty(Object object) {\n return java.lang.reflect.Array.getLength(object);\n }" ]
This method sends the same message to many agents. @param agent_name The id of the agents that receive the message @param msgtype @param message_content The content of the message @param connector The connector to get the external access
[ "public void sendMessageToAgents(String[] agent_name, String msgtype,\n Object message_content, Connector connector) {\n HashMap<String, Object> hm = new HashMap<String, Object>();\n hm.put(\"performative\", msgtype);\n hm.put(SFipa.CONTENT, message_content);\n IComponentIdentifier[] ici = new IComponentIdentifier[agent_name.length];\n for (int i = 0; i < agent_name.length; i++) {\n ici[i] = (IComponentIdentifier) connector.getAgentID(agent_name[i]);\n }\n ((IMessageService) connector.getMessageService()).deliverMessage(hm,\n \"fipa\", ici);\n }" ]
[ "protected <T, A> ActiveOperation<T, A> getActiveOperation(final Integer id) {\n //noinspection unchecked\n return (ActiveOperation<T, A>) activeRequests.get(id);\n }", "private void getAllDependents(Set<PathEntry> result, String name) {\n Set<String> depNames = dependenctRelativePaths.get(name);\n if (depNames == null) {\n return;\n }\n for (String dep : depNames) {\n PathEntry entry = pathEntries.get(dep);\n if (entry != null) {\n result.add(entry);\n getAllDependents(result, dep);\n }\n }\n }", "public static base_response reset(nitro_service client, Interface resource) throws Exception {\n\t\tInterface resetresource = new Interface();\n\t\tresetresource.id = resource.id;\n\t\treturn resetresource.perform_operation(client,\"reset\");\n\t}", "public static void readAndCheckVersion(ObjectInput input, int supportedVersion, Class<?> externalizedType) throws IOException {\n\t\tint version = input.readInt();\n\n\t\tif ( version != supportedVersion ) {\n\t\t\tthrow LOG.unexpectedKeyVersion( externalizedType, version, supportedVersion );\n\t\t}\n\t}", "public void close() {\n Closer.closeQuietly(acceptor);\n for (Processor processor : processors) {\n Closer.closeQuietly(processor);\n }\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 }", "private static JsonArray toJsonArray(Collection<String> values) {\n JsonArray array = new JsonArray();\n for (String value : values) {\n array.add(value);\n }\n return array;\n\n }", "public ModelNode toModelNode() {\n final ModelNode node = new ModelNode().setEmptyList();\n for (PathElement element : pathAddressList) {\n final String value;\n if (element.isMultiTarget() && !element.isWildcard()) {\n value = '[' + element.getValue() + ']';\n } else {\n value = element.getValue();\n }\n node.add(element.getKey(), value);\n }\n return node;\n }", "public void classifyAndWriteViterbiSearchGraph(String testFile, String searchGraphPrefix, DocumentReaderAndWriter<IN> readerAndWriter) throws IOException {\r\n Timing timer = new Timing();\r\n ObjectBank<List<IN>> documents =\r\n makeObjectBankFromFile(testFile, readerAndWriter);\r\n int numWords = 0;\r\n int numSentences = 0;\r\n\r\n for (List<IN> doc : documents) {\r\n DFSA<String, Integer> tagLattice = getViterbiSearchGraph(doc, AnswerAnnotation.class);\r\n numWords += doc.size();\r\n PrintWriter latticeWriter = new PrintWriter(new FileOutputStream(searchGraphPrefix + '.' + numSentences\r\n + \".wlattice\"));\r\n PrintWriter vsgWriter = new PrintWriter(new FileOutputStream(searchGraphPrefix + '.' + numSentences + \".lattice\"));\r\n if (readerAndWriter instanceof LatticeWriter)\r\n ((LatticeWriter) readerAndWriter).printLattice(tagLattice, doc, latticeWriter);\r\n tagLattice.printAttFsmFormat(vsgWriter);\r\n latticeWriter.close();\r\n vsgWriter.close();\r\n numSentences++;\r\n }\r\n\r\n long millis = timer.stop();\r\n double wordspersec = numWords / (((double) millis) / 1000);\r\n NumberFormat nf = new DecimalFormat(\"0.00\"); // easier way!\r\n System.err.println(this.getClass().getName() + \" tagged \" + numWords + \" words in \" + numSentences\r\n + \" documents at \" + nf.format(wordspersec) + \" words per second.\");\r\n }" ]
Restore backup data @param fileData - json file with restore data @return @throws Exception
[ "@RequestMapping(value = \"/api/backup\", method = RequestMethod.POST)\n public\n @ResponseBody\n Backup processBackup(@RequestParam(\"fileData\") MultipartFile fileData) throws Exception {\n // Method taken from: http://spring.io/guides/gs/uploading-files/\n if (!fileData.isEmpty()) {\n try {\n byte[] bytes = fileData.getBytes();\n BufferedOutputStream stream =\n new BufferedOutputStream(new FileOutputStream(new File(\"backup-uploaded.json\")));\n stream.write(bytes);\n stream.close();\n\n } catch (Exception e) {\n }\n }\n File f = new File(\"backup-uploaded.json\");\n BackupService.getInstance().restoreBackupData(new FileInputStream(f));\n return BackupService.getInstance().getBackupData();\n }" ]
[ "public static String createQuotedConstant(String str) {\n if (str == null || str.isEmpty()) {\n return str;\n }\n try {\n Double.parseDouble(str);\n } catch (NumberFormatException nfe) {\n return \"\\\"\" + str + \"\\\"\";\n }\n return str;\n }", "public static <X, T> ProducerField<X, T> of(BeanAttributes<T> attributes, EnhancedAnnotatedField<T, ? super X> field, AbstractClassBean<X> declaringBean, DisposalMethod<X, ?> disposalMethod, BeanManagerImpl beanManager, ServiceRegistry services) {\n return new ProducerField<X, T>(attributes, field, declaringBean, disposalMethod, beanManager, services);\n }", "public static authenticationvserver_stats[] get(nitro_service service) throws Exception{\n\t\tauthenticationvserver_stats obj = new authenticationvserver_stats();\n\t\tauthenticationvserver_stats[] response = (authenticationvserver_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}", "Map<String, EntityDocument> getEntityDocumentMap(int numOfEntities,\n\t\t\tWbGetEntitiesActionData properties)\n\t\t\tthrows MediaWikiApiErrorException, IOException {\n\t\tif (numOfEntities == 0) {\n\t\t\treturn Collections.emptyMap();\n\t\t}\n\t\tconfigureProperties(properties);\n\t\treturn this.wbGetEntitiesAction.wbGetEntities(properties);\n\t}", "@SuppressWarnings({\"unchecked\", \"WeakerAccess\"})\n public static <T> List<T> readListAttributeElement(final XMLExtendedStreamReader reader, final String attributeName,\n final Class<T> type) throws XMLStreamException {\n requireSingleAttribute(reader, attributeName);\n // todo: fix this when this method signature is corrected\n final List<T> value = (List<T>) reader.getListAttributeValue(0, type);\n requireNoContent(reader);\n return value;\n }", "private Map<StandardMethod, UnderrideLevel> findUnderriddenMethods(\n Iterable<ExecutableElement> methods) {\n Map<StandardMethod, ExecutableElement> standardMethods = new LinkedHashMap<>();\n for (ExecutableElement method : methods) {\n Optional<StandardMethod> standardMethod = maybeStandardMethod(method);\n if (standardMethod.isPresent() && isUnderride(method)) {\n standardMethods.put(standardMethod.get(), method);\n }\n }\n if (standardMethods.containsKey(StandardMethod.EQUALS)\n != standardMethods.containsKey(StandardMethod.HASH_CODE)) {\n ExecutableElement underriddenMethod = standardMethods.containsKey(StandardMethod.EQUALS)\n ? standardMethods.get(StandardMethod.EQUALS)\n : standardMethods.get(StandardMethod.HASH_CODE);\n messager.printMessage(ERROR,\n \"hashCode and equals must be implemented together on FreeBuilder types\",\n underriddenMethod);\n }\n ImmutableMap.Builder<StandardMethod, UnderrideLevel> result = ImmutableMap.builder();\n for (StandardMethod standardMethod : standardMethods.keySet()) {\n if (standardMethods.get(standardMethod).getModifiers().contains(Modifier.FINAL)) {\n result.put(standardMethod, UnderrideLevel.FINAL);\n } else {\n result.put(standardMethod, UnderrideLevel.OVERRIDEABLE);\n }\n }\n return result.build();\n }", "private void readResourceExtendedAttributes(Project.Resources.Resource xml, Resource mpx)\n {\n for (Project.Resources.Resource.ExtendedAttribute attrib : xml.getExtendedAttribute())\n {\n int xmlFieldID = Integer.parseInt(attrib.getFieldID()) & 0x0000FFFF;\n ResourceField mpxFieldID = MPPResourceField.getInstance(xmlFieldID);\n TimeUnit durationFormat = DatatypeConverter.parseDurationTimeUnits(attrib.getDurationFormat(), null);\n DatatypeConverter.parseExtendedAttribute(m_projectFile, mpx, attrib.getValue(), mpxFieldID, durationFormat);\n }\n }", "public static ModelMBeanOperationInfo[] extractOperationInfo(Object object) {\n ArrayList<ModelMBeanOperationInfo> infos = new ArrayList<ModelMBeanOperationInfo>();\n for(Method m: object.getClass().getMethods()) {\n JmxOperation jmxOperation = m.getAnnotation(JmxOperation.class);\n JmxGetter jmxGetter = m.getAnnotation(JmxGetter.class);\n JmxSetter jmxSetter = m.getAnnotation(JmxSetter.class);\n if(jmxOperation != null || jmxGetter != null || jmxSetter != null) {\n String description = \"\";\n int visibility = 1;\n int impact = MBeanOperationInfo.UNKNOWN;\n if(jmxOperation != null) {\n description = jmxOperation.description();\n impact = jmxOperation.impact();\n } else if(jmxGetter != null) {\n description = jmxGetter.description();\n impact = MBeanOperationInfo.INFO;\n visibility = 4;\n } else if(jmxSetter != null) {\n description = jmxSetter.description();\n impact = MBeanOperationInfo.ACTION;\n visibility = 4;\n }\n ModelMBeanOperationInfo info = new ModelMBeanOperationInfo(m.getName(),\n description,\n extractParameterInfo(m),\n m.getReturnType()\n .getName(), impact);\n info.getDescriptor().setField(\"visibility\", Integer.toString(visibility));\n infos.add(info);\n }\n }\n\n return infos.toArray(new ModelMBeanOperationInfo[infos.size()]);\n }", "@Override\n public void close() throws VoldemortException {\n logger.debug(\"Close called for read-only store.\");\n this.fileModificationLock.writeLock().lock();\n\n try {\n if(isOpen) {\n this.isOpen = false;\n fileSet.close();\n } else {\n logger.debug(\"Attempt to close already closed store \" + getName());\n }\n } finally {\n this.fileModificationLock.writeLock().unlock();\n }\n }" ]
Modify a module. @param moduleName the module name @param slot the module slot @param existingHash the existing hash @param newHash the new hash of the modified content @return the builder
[ "public T modifyModule(final String moduleName, final String slot, final byte[] existingHash, final byte[] newHash) {\n final ContentItem item = createModuleItem(moduleName, slot, newHash);\n addContentModification(createContentModification(item, ModificationType.MODIFY, existingHash));\n return returnThis();\n }" ]
[ "public static void acceptsZone(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_Z, OPT_ZONE), \"zone id\")\n .withRequiredArg()\n .describedAs(\"zone-id\")\n .ofType(Integer.class);\n }", "private static String quoteSort(Sort[] sort) {\n LinkedList<String> sorts = new LinkedList<String>();\n for (Sort pair : sort) {\n sorts.add(String.format(\"{%s: %s}\", Helpers.quote(pair.getName()), Helpers.quote(pair.getOrder().toString())));\n }\n return sorts.toString();\n }", "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 }", "private static void listResourceNotes(ProjectFile file)\n {\n for (Resource resource : file.getResources())\n {\n String notes = resource.getNotes();\n\n if (notes.length() != 0)\n {\n System.out.println(\"Notes for \" + resource.getName() + \": \" + notes);\n }\n }\n\n System.out.println();\n }", "protected void createSetterMethod(ClassNode declaringClass, PropertyNode propertyNode, String setterName, Statement setterBlock) {\r\n MethodNode setter = new MethodNode(\r\n setterName,\r\n propertyNode.getModifiers(),\r\n ClassHelper.VOID_TYPE,\r\n params(param(propertyNode.getType(), \"value\")),\r\n ClassNode.EMPTY_ARRAY,\r\n setterBlock);\r\n setter.setSynthetic(true);\r\n // add it to the class\r\n declaringClass.addMethod(setter);\r\n }", "public void transform(String name, String transform) throws Exception {\n\n File configFile = new File(m_configDir, name);\n File transformFile = new File(m_xsltDir, transform);\n try (InputStream stream = new FileInputStream(transformFile)) {\n StreamSource source = new StreamSource(stream);\n transform(configFile, source);\n }\n }", "public static base_responses add(nitro_service client, cmppolicylabel resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcmppolicylabel addresources[] = new cmppolicylabel[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new cmppolicylabel();\n\t\t\t\taddresources[i].labelname = resources[i].labelname;\n\t\t\t\taddresources[i].type = resources[i].type;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public static <T> List<T> copyOf(T[] elements) {\n Preconditions.checkNotNull(elements);\n return ofInternal(elements.clone());\n }", "public static base_response update(nitro_service client, autoscaleprofile resource) throws Exception {\n\t\tautoscaleprofile updateresource = new autoscaleprofile();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.url = resource.url;\n\t\tupdateresource.apikey = resource.apikey;\n\t\tupdateresource.sharedsecret = resource.sharedsecret;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
Starts recursive insert on all insert objects object graph
[ "private void cascadeMarkedForInsert()\r\n {\r\n // This list was used to avoid endless recursion on circular references\r\n List alreadyPrepared = new ArrayList();\r\n for(int i = 0; i < markedForInsertList.size(); i++)\r\n {\r\n ObjectEnvelope mod = (ObjectEnvelope) markedForInsertList.get(i);\r\n // only if a new object was found we cascade to register the dependent objects\r\n if(mod.needsInsert())\r\n {\r\n cascadeInsertFor(mod, alreadyPrepared);\r\n alreadyPrepared.clear();\r\n }\r\n }\r\n markedForInsertList.clear();\r\n }" ]
[ "private File makeDestFile(URL src) {\n if (dest == null) {\n throw new IllegalArgumentException(\"Please provide a download destination\");\n }\n\n File destFile = dest;\n if (destFile.isDirectory()) {\n //guess name from URL\n String name = src.toString();\n if (name.endsWith(\"/\")) {\n name = name.substring(0, name.length() - 1);\n }\n name = name.substring(name.lastIndexOf('/') + 1);\n destFile = new File(dest, name);\n } else {\n //create destination directory\n File parent = destFile.getParentFile();\n if (parent != null) {\n parent.mkdirs();\n }\n }\n return destFile;\n }", "private void readAssignment(Resource resource, Assignment assignment)\n {\n Task task = m_activityMap.get(assignment.getActivity());\n if (task != null)\n {\n task.addResourceAssignment(resource);\n }\n }", "public Response getBill(int month, int year)\n throws RequestException, LocalOperationException {\n Request request = new Request(this);\n return new Response(request.get(\"/bill/\" + year + String.format(\"-%02d\", month)));\n }", "private StitchUserT doLogin(final StitchCredential credential, final boolean asLinkRequest) {\n final Response response = doLoginRequest(credential, asLinkRequest);\n\n final StitchUserT previousUser = activeUser;\n final StitchUserT user = processLoginResponse(credential, response, asLinkRequest);\n\n if (asLinkRequest) {\n onUserLinked(user);\n } else {\n onUserLoggedIn(user);\n onActiveUserChanged(activeUser, previousUser);\n }\n\n return user;\n }", "public int getBoneIndex(GVRSceneObject bone)\n {\n for (int i = 0; i < getNumBones(); ++i)\n if (mBones[i] == bone)\n return i;\n return -1;\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 void bind(Object object, String name)\r\n throws ObjectNameNotUniqueException\r\n {\r\n /**\r\n * Is DB open? ODMG 3.0 says it has to be to call bind.\r\n */\r\n if (!this.isOpen())\r\n {\r\n throw new DatabaseClosedException(\"Database is not open. Must have an open DB to call bind.\");\r\n }\r\n /**\r\n * Is Tx open? ODMG 3.0 says it has to be to call bind.\r\n */\r\n TransactionImpl tx = getTransaction();\r\n if (tx == null || !tx.isOpen())\r\n {\r\n throw new TransactionNotInProgressException(\"Tx is not open. Must have an open TX to call bind.\");\r\n }\r\n\r\n tx.getNamedRootsMap().bind(object, name);\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 static sslpolicylabel get(nitro_service service, String labelname) throws Exception{\n\t\tsslpolicylabel obj = new sslpolicylabel();\n\t\tobj.set_labelname(labelname);\n\t\tsslpolicylabel response = (sslpolicylabel) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
Calculate the highlight color. Saturate at 0xff to make sure that high values don't result in aliasing. @param _Slice The Slice which will be highlighted.
[ "private void highlightSlice(PieModel _Slice) {\n\n int color = _Slice.getColor();\n _Slice.setHighlightedColor(Color.argb(\n 0xff,\n Math.min((int) (mHighlightStrength * (float) Color.red(color)), 0xff),\n Math.min((int) (mHighlightStrength * (float) Color.green(color)), 0xff),\n Math.min((int) (mHighlightStrength * (float) Color.blue(color)), 0xff)\n ));\n }" ]
[ "public void add(ServiceReference<D> declarationSRef) {\n D declaration = getDeclaration(declarationSRef);\n boolean matchFilter = declarationFilter.matches(declaration.getMetadata());\n declarations.put(declarationSRef, matchFilter);\n }", "private Component createAddKeyButton() {\n\n // the \"+\" button\n Button addKeyButton = new Button();\n addKeyButton.addStyleName(\"icon-only\");\n addKeyButton.addStyleName(\"borderless-colored\");\n addKeyButton.setDescription(m_messages.key(Messages.GUI_ADD_KEY_0));\n addKeyButton.setIcon(FontOpenCms.CIRCLE_PLUS, m_messages.key(Messages.GUI_ADD_KEY_0));\n addKeyButton.addClickListener(new ClickListener() {\n\n private static final long serialVersionUID = 1L;\n\n public void buttonClick(ClickEvent event) {\n\n handleAddKey();\n\n }\n });\n return addKeyButton;\n }", "private static String getHostname() {\n if (Hostname == null) {\n try {\n Hostname = InetAddress.getLocalHost().getHostName();\n } catch (Exception e) {\n Hostname = \"default\";\n LOGGER.warn(\"Can not get current hostname\", e);\n }\n }\n return Hostname;\n }", "@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public void registerFilters(List<AlgoliaFilter> filters) {\n for (final AlgoliaFilter filter : filters) {\n searcher.addFacet(filter.getAttribute());\n }\n }", "public 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 }", "public float getChildSize(final int dataIndex, final Axis axis) {\n float size = 0;\n Widget child = mContainer.get(dataIndex);\n if (child != null) {\n switch (axis) {\n case X:\n size = child.getLayoutWidth();\n break;\n case Y:\n size = child.getLayoutHeight();\n break;\n case Z:\n size = child.getLayoutDepth();\n break;\n default:\n throw new RuntimeAssertion(\"Bad axis specified: %s\", axis);\n }\n }\n return size;\n }", "private void adjustOptionsColumn(\n CmsMessageBundleEditorTypes.EditMode oldMode,\n CmsMessageBundleEditorTypes.EditMode newMode) {\n\n if (m_model.isShowOptionsColumn(oldMode) != m_model.isShowOptionsColumn(newMode)) {\n m_table.removeGeneratedColumn(TableProperty.OPTIONS);\n if (m_model.isShowOptionsColumn(newMode)) {\n // Don't know why exactly setting the filter field invisible is necessary here,\n // it should be already set invisible - but apparently not setting it invisible again\n // will result in the field being visible.\n m_table.setFilterFieldVisible(TableProperty.OPTIONS, false);\n m_table.addGeneratedColumn(TableProperty.OPTIONS, m_optionsColumn);\n }\n }\n }", "public static int cudnnGetActivationDescriptor(\n cudnnActivationDescriptor activationDesc, \n int[] mode, \n int[] reluNanOpt, \n double[] coef)/** ceiling for clipped RELU, alpha for ELU */\n {\n return checkResult(cudnnGetActivationDescriptorNative(activationDesc, mode, reluNanOpt, coef));\n }", "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 }" ]
Uninstall current location collection client. @return true if uninstall was successful
[ "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 void logAttributeWarning(PathAddress address, ModelNode operation, String message, Set<String> attributes) {\n messageQueue.add(new AttributeLogEntry(address, operation, message, attributes));\n }", "static void rethrowIrrecoverableConnectionFailures(IOException e) throws SlaveRegistrationException {\n Throwable cause = e;\n while ((cause = cause.getCause()) != null) {\n if (cause instanceof SaslException) {\n throw HostControllerLogger.ROOT_LOGGER.authenticationFailureUnableToConnect(cause);\n } else if (cause instanceof SSLHandshakeException) {\n throw HostControllerLogger.ROOT_LOGGER.sslFailureUnableToConnect(cause);\n } else if (cause instanceof SlaveRegistrationException) {\n throw (SlaveRegistrationException) cause;\n }\n }\n }", "public void addFkToThisClass(String column)\r\n {\r\n if (fksToThisClass == null)\r\n {\r\n fksToThisClass = new Vector();\r\n }\r\n fksToThisClass.add(column);\r\n fksToThisClassAry = null;\r\n }", "public static Command newInsertElements(Collection objects, String outIdentifier, boolean returnObject, String entryPoint) {\n return getCommandFactoryProvider().newInsertElements( objects, outIdentifier, returnObject, entryPoint );\n }", "@Override\n\tpublic String toFullString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = stringCache.fullString) == null) {\n\t\t\tstringCache.fullString = result = toNormalizedString(IPv4StringCache.fullParams);\n\t\t}\n\t\treturn result;\n\t}", "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 F resolve(R resolvable, boolean cache) {\n R wrappedResolvable = wrap(resolvable);\n if (cache) {\n return resolved.getValue(wrappedResolvable);\n } else {\n return resolverFunction.apply(wrappedResolvable);\n }\n }", "private void enforceSrid(Object feature) throws LayerException {\n\t\tGeometry geom = getFeatureModel().getGeometry(feature);\n\t\tif (null != geom) {\n\t\t\tgeom.setSRID(srid);\n\t\t\tgetFeatureModel().setGeometry(feature, geom);\n\t\t}\n\t}", "public Map<String, String> getMapAttribute(String name, String defaultValue) {\n return mapSplit(getAttribute(name), defaultValue);\n }" ]
Creates a resource key with given id for bundle specified by given class. @param clazz the class owning the bundle. @param id value identifier @return the resource key
[ "public static ResourceKey key(Class<?> clazz, String id) {\n return new ResourceKey(clazz.getName(), id);\n }" ]
[ "private <T> List<Class<?>> filter(List<Class<?>> enabledClasses, List<Class<?>> globallyEnabledClasses, LogMessageCallback logMessageCallback,\n BeanDeployment deployment) {\n for (Iterator<Class<?>> iterator = enabledClasses.iterator(); iterator.hasNext(); ) {\n Class<?> enabledClass = iterator.next();\n if (globallyEnabledClasses.contains(enabledClass)) {\n logMessageCallback.log(enabledClass, deployment.getBeanDeploymentArchive().getId());\n iterator.remove();\n }\n }\n return enabledClasses;\n }", "protected Integer getCorrectIndex(Integer index) {\n Integer size = jsonNode.size();\n Integer newIndex = index;\n\n // reverse walking through the array\n if(index < 0) {\n newIndex = size + index;\n }\n\n // the negative index would be greater than the size a second time!\n if(newIndex < 0) {\n throw LOG.indexOutOfBounds(index, size);\n }\n\n // the index is greater as the actual size\n if(index > size) {\n throw LOG.indexOutOfBounds(index, size);\n }\n\n return newIndex;\n }", "public void ojbAdd(Object anObject)\r\n {\r\n DSetEntry entry = prepareEntry(anObject);\r\n entry.setPosition(elements.size());\r\n elements.add(entry);\r\n }", "synchronized long storeUserProfile(String id, JSONObject obj) {\n\n if (id == null) return DB_UPDATE_ERROR;\n\n if (!this.belowMemThreshold()) {\n getConfigLogger().verbose(\"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.USER_PROFILES.getName();\n\n long ret = DB_UPDATE_ERROR;\n\n try {\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n final ContentValues cv = new ContentValues();\n cv.put(KEY_DATA, obj.toString());\n cv.put(\"_id\", id);\n ret = db.insertWithOnConflict(tableName, null, cv, SQLiteDatabase.CONFLICT_REPLACE);\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Error adding data to table \" + tableName + \" Recreating DB\");\n dbHelper.deleteDatabase();\n } finally {\n dbHelper.close();\n }\n return ret;\n }", "public static Bitmap flip(Bitmap src) {\n Matrix m = new Matrix();\n m.preScale(-1, 1);\n return Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), m, false);\n }", "public void fireRelationWrittenEvent(Relation relation)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.relationWritten(relation);\n }\n }\n }", "private static void waitUntilFinished(FluoConfiguration config) {\n try (Environment env = new Environment(config)) {\n List<TableRange> ranges = getRanges(env);\n\n outer: while (true) {\n long ts1 = env.getSharedResources().getOracleClient().getStamp().getTxTimestamp();\n for (TableRange range : ranges) {\n boolean sawNotifications = waitTillNoNotifications(env, range);\n if (sawNotifications) {\n ranges = getRanges(env);\n // This range had notifications. Processing those notifications may have created\n // notifications in previously scanned ranges, so start over.\n continue outer;\n }\n }\n long ts2 = env.getSharedResources().getOracleClient().getStamp().getTxTimestamp();\n\n // Check to ensure the Oracle issued no timestamps during the scan for notifications.\n if (ts2 - ts1 == 1) {\n break;\n }\n }\n } catch (Exception e) {\n log.error(\"An exception was thrown -\", e);\n System.exit(-1);\n }\n }", "public PeriodicEvent runEvery(Runnable task, float delay, float period,\n int repetitions) {\n if (repetitions < 1) {\n return null;\n } else if (repetitions == 1) {\n // Better to burn a handful of CPU cycles than to churn memory by\n // creating a new callback\n return runAfter(task, delay);\n } else {\n return runEvery(task, delay, period, new RunFor(repetitions));\n }\n }", "public static Result generate(@Nonnull final String code, @Nonnull final ImmutableSettings settings) {\n\t\tCheck.notNull(code, \"code\");\n\t\tfinal ImmutableSettings.Builder settingsBuilder = new ImmutableSettings.Builder(Check.notNull(settings, \"settings\"));\n\n\t\tfinal InterfaceAnalysis analysis = InterfaceAnalyzer.analyze(code);\n\t\tfinal Clazz clazz = scaffoldClazz(analysis, settings);\n\n\t\t// immutable settings\n\t\tsettingsBuilder.fields(clazz.getFields());\n\t\tsettingsBuilder.immutableName(clazz.getName());\n\t\tsettingsBuilder.imports(clazz.getImports());\n\t\tfinal Interface definition = new Interface(new Type(clazz.getPackage(), analysis.getInterfaceName(), GenericDeclaration.UNDEFINED));\n\t\tsettingsBuilder.mainInterface(definition);\n\t\tsettingsBuilder.interfaces(clazz.getInterfaces());\n\t\tsettingsBuilder.packageDeclaration(clazz.getPackage());\n\n\t\tfinal String implementationCode = SourceCodeFormatter.format(ImmutableObjectRenderer.toString(clazz, settingsBuilder.build()));\n\t\tfinal String testCode = SourceCodeFormatter.format(ImmutableObjectTestRenderer.toString(clazz, settingsBuilder.build()));\n\t\treturn new Result(implementationCode, testCode);\n\t}" ]
Increment the version info associated with the given node @param node The node
[ "public void incrementVersion(int node, long time) {\n if(node < 0 || node > Short.MAX_VALUE)\n throw new IllegalArgumentException(node\n + \" is outside the acceptable range of node ids.\");\n\n this.timestamp = time;\n\n Long version = versionMap.get((short) node);\n if(version == null) {\n version = 1L;\n } else {\n version = version + 1L;\n }\n\n versionMap.put((short) node, version);\n if(versionMap.size() >= MAX_NUMBER_OF_VERSIONS) {\n throw new IllegalStateException(\"Vector clock is full!\");\n }\n\n }" ]
[ "public static FormValidation validateArtifactoryCombinationFilter(String value)\n throws IOException, InterruptedException {\n String url = Util.fixEmptyAndTrim(value);\n if (url == null)\n return FormValidation.error(\"Mandatory field - You don`t have any deploy matches\");\n\n return FormValidation.ok();\n }", "private static boolean mayBeIPv6Address(String input) {\n if (input == null) {\n return false;\n }\n\n boolean result = false;\n int colonsCounter = 0;\n int length = input.length();\n for (int i = 0; i < length; i++) {\n char c = input.charAt(i);\n if (c == '.' || c == '%') {\n // IPv4 in IPv6 or Zone ID detected, end of checking.\n break;\n }\n if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')\n || (c >= 'A' && c <= 'F') || c == ':')) {\n return false;\n } else if (c == ':') {\n colonsCounter++;\n }\n }\n if (colonsCounter >= 2) {\n result = true;\n }\n return result;\n }", "public static int compare(double a, double b, double delta) {\n if (equals(a, b, delta)) {\n return 0;\n }\n return Double.compare(a, b);\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 Optional<SoyMsgBundle> resolve(final Optional<Locale> locale) throws IOException {\n if (!locale.isPresent()) {\n return Optional.absent();\n }\n\n synchronized (msgBundles) {\n SoyMsgBundle soyMsgBundle = null;\n if (isHotReloadModeOff()) {\n soyMsgBundle = msgBundles.get(locale.get());\n }\n if (soyMsgBundle == null) {\n soyMsgBundle = createSoyMsgBundle(locale.get());\n if (soyMsgBundle == null) {\n soyMsgBundle = createSoyMsgBundle(new Locale(locale.get().getLanguage()));\n }\n\n if (soyMsgBundle == null && fallbackToEnglish) {\n soyMsgBundle = createSoyMsgBundle(Locale.ENGLISH);\n }\n\n if (soyMsgBundle == null) {\n return Optional.absent();\n }\n\n if (isHotReloadModeOff()) {\n msgBundles.put(locale.get(), soyMsgBundle);\n }\n }\n\n return Optional.fromNullable(soyMsgBundle);\n }\n }", "public static void resize(GVRMesh mesh, float size) {\n float dim[] = getBoundingSize(mesh);\n float maxsize = 0.0f;\n\n if (dim[0] > maxsize) maxsize = dim[0];\n if (dim[1] > maxsize) maxsize = dim[1];\n if (dim[2] > maxsize) maxsize = dim[2];\n\n scale(mesh, size / maxsize);\n }", "public static void show(DMatrixD1 A , String title ) {\n JFrame frame = new JFrame(title);\n\n int width = 300;\n int height = 300;\n\n if( A.numRows > A.numCols) {\n width = width*A.numCols/A.numRows;\n } else {\n height = height*A.numRows/A.numCols;\n }\n\n DMatrixComponent panel = new DMatrixComponent(width,height);\n panel.setMatrix(A);\n\n frame.add(panel, BorderLayout.CENTER);\n\n frame.pack();\n frame.setVisible(true);\n\n }", "public void writeTo(DataOutput outstream) throws Exception {\n S3Util.writeString(host, outstream);\n outstream.writeInt(port);\n S3Util.writeString(protocol, outstream);\n }", "public NamespacesList<Value> getValues(String namespace, String predicate, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n NamespacesList<Value> valuesList = new NamespacesList<Value>();\r\n parameters.put(\"method\", METHOD_GET_VALUES);\r\n\r\n if (namespace != null) {\r\n parameters.put(\"namespace\", namespace);\r\n }\r\n if (predicate != null) {\r\n parameters.put(\"predicate\", predicate);\r\n }\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element nsElement = response.getPayload();\r\n NodeList nsNodes = nsElement.getElementsByTagName(\"value\");\r\n valuesList.setPage(nsElement.getAttribute(\"page\"));\r\n valuesList.setPages(nsElement.getAttribute(\"pages\"));\r\n valuesList.setPerPage(nsElement.getAttribute(\"perPage\"));\r\n valuesList.setTotal(\"\" + nsNodes.getLength());\r\n for (int i = 0; i < nsNodes.getLength(); i++) {\r\n Element element = (Element) nsNodes.item(i);\r\n Value value = parseValue(element);\r\n value.setNamespace(namespace);\r\n value.setPredicate(predicate);\r\n valuesList.add(value);\r\n }\r\n return valuesList;\r\n }" ]
Method to read our client's plain text @param file_name @return the filereader to translate client's plain text into our files @throws BeastException if any problem is found whit the file
[ "protected static BufferedReader createFileReader(String file_name)\n throws BeastException {\n try {\n return new BufferedReader(new FileReader(file_name));\n } catch (FileNotFoundException e) {\n Logger logger = Logger.getLogger(MASReader.class.getName());\n logger.severe(\"ERROR: \" + e.toString());\n throw new BeastException(\"ERROR: \" + e.toString(), e);\n }\n }" ]
[ "public static void writeErrorResponse(MessageEvent messageEvent,\n HttpResponseStatus status,\n String message) {\n\n // Create the Response object\n HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);\n response.setHeader(CONTENT_TYPE, \"text/plain; charset=UTF-8\");\n response.setContent(ChannelBuffers.copiedBuffer(\"Failure: \" + status.toString() + \". \"\n + message + \"\\r\\n\", CharsetUtil.UTF_8));\n response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());\n\n // Write the response to the Netty Channel\n messageEvent.getChannel().write(response);\n }", "public CmsJspInstanceDateBean getToInstanceDate() {\n\n if (m_instanceDate == null) {\n m_instanceDate = new CmsJspInstanceDateBean(getToDate(), m_cms.getRequestContext().getLocale());\n }\n return m_instanceDate;\n }", "public boolean rename(final File from, final File to) {\n boolean renamed = false;\n if (this.isWriteable(from)) {\n renamed = from.renameTo(to);\n } else {\n LogLog.debug(from + \" is not writeable for rename (retrying)\");\n }\n if (!renamed) {\n from.renameTo(to);\n renamed = (!from.exists());\n }\n return renamed;\n }", "public List<GanttDesignerRemark.Task> getTask()\n {\n if (task == null)\n {\n task = new ArrayList<GanttDesignerRemark.Task>();\n }\n return this.task;\n }", "public ObjectReferenceDescriptor getObjectReferenceDescriptorByName(String name)\r\n {\r\n ObjectReferenceDescriptor ord = (ObjectReferenceDescriptor)\r\n getObjectReferenceDescriptorsNameMap().get(name);\r\n\r\n //\r\n // BRJ: if the ReferenceDescriptor is not found\r\n // look in the ClassDescriptor referenced by 'super' for it\r\n //\r\n if (ord == null)\r\n {\r\n ClassDescriptor superCld = getSuperClassDescriptor();\r\n if (superCld != null)\r\n {\r\n ord = superCld.getObjectReferenceDescriptorByName(name);\r\n }\r\n }\r\n return ord;\r\n }", "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 }", "public void set(int i, double value) {\n switch (i) {\n case 0: {\n x = value;\n break;\n }\n case 1: {\n y = value;\n break;\n }\n case 2: {\n z = value;\n break;\n }\n default: {\n throw new ArrayIndexOutOfBoundsException(i);\n }\n }\n }", "public static sslglobal_sslpolicy_binding[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tsslglobal_sslpolicy_binding obj = new sslglobal_sslpolicy_binding();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tsslglobal_sslpolicy_binding[] response = (sslglobal_sslpolicy_binding[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}", "public static String getPublicIPAddress() throws Exception {\n final String IPV4_REGEX = \"\\\\A(25[0-5]|2[0-4]\\\\d|[0-1]?\\\\d?\\\\d)(\\\\.(25[0-5]|2[0-4]\\\\d|[0-1]?\\\\d?\\\\d)){3}\\\\z\";\n\n String ipAddr = null;\n Enumeration e = NetworkInterface.getNetworkInterfaces();\n while (e.hasMoreElements()) {\n NetworkInterface n = (NetworkInterface) e.nextElement();\n Enumeration ee = n.getInetAddresses();\n while (ee.hasMoreElements()) {\n InetAddress i = (InetAddress) ee.nextElement();\n\n // Pick the first non loop back address\n if ((!i.isLoopbackAddress() && i.isSiteLocalAddress()) ||\n i.getHostAddress().matches(IPV4_REGEX)) {\n ipAddr = i.getHostAddress();\n break;\n }\n }\n if (ipAddr != null) {\n break;\n }\n }\n\n return ipAddr;\n }" ]
Finds an entity given its primary key. @throws RowNotFoundException If no such object was found. @throws TooManyRowsException If more that one object was returned for the given ID.
[ "public T findById(Object id) throws RowNotFoundException, TooManyRowsException {\n return findWhere(eq(idColumn.getColumnName(), id)).getSingleResult();\n }" ]
[ "public int count(String key) {\n ConcurrentMap<WebSocketConnection, WebSocketConnection> bag = registry.get(key);\n return null == bag ? 0 : bag.size();\n }", "public Map<String, String> resolve(Map<String, String> config) {\n config = resolveSystemEnvironmentVariables(config);\n config = resolveSystemDefaultSetup(config);\n config = resolveDockerInsideDocker(config);\n config = resolveDownloadDockerMachine(config);\n config = resolveAutoStartDockerMachine(config);\n config = resolveDefaultDockerMachine(config);\n config = resolveServerUriByOperativeSystem(config);\n config = resolveServerIp(config);\n config = resolveTlsVerification(config);\n return config;\n }", "private void addArrayMethods(List<MethodNode> methods, ClassNode receiver, String name, ClassNode[] args) {\n if (args.length!=1) return;\n if (!receiver.isArray()) return;\n if (!isIntCategory(getUnwrapper(args[0]))) return;\n if (\"getAt\".equals(name)) {\n MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC, receiver.getComponentType(), new Parameter[]{new Parameter(args[0],\"arg\")}, null, null);\n node.setDeclaringClass(receiver.redirect());\n methods.add(node);\n } else if (\"setAt\".equals(name)) {\n MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC, VOID_TYPE, new Parameter[]{new Parameter(args[0],\"arg\")}, null, null);\n node.setDeclaringClass(receiver.redirect());\n methods.add(node);\n }\n }", "public static base_response unset(nitro_service client, lbsipparameters resource, String[] args) throws Exception{\n\t\tlbsipparameters unsetresource = new lbsipparameters();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public GVRMesh findMesh(GVRSceneObject model)\n {\n class MeshFinder implements GVRSceneObject.ComponentVisitor\n {\n private GVRMesh meshFound = null;\n public GVRMesh getMesh() { return meshFound; }\n public boolean visit(GVRComponent comp)\n {\n GVRRenderData rdata = (GVRRenderData) comp;\n meshFound = rdata.getMesh();\n return (meshFound == null);\n }\n };\n MeshFinder findMesh = new MeshFinder();\n model.forAllComponents(findMesh, GVRRenderData.getComponentType());\n return findMesh.getMesh();\n }", "public void setAccordion(boolean accordion) {\n getElement().setAttribute(\"data-collapsible\", accordion ? CssName.ACCORDION : CssName.EXPANDABLE);\n reload();\n }", "public void load(List<E> result) {\n ++pageCount;\n if (this.result == null || this.result.isEmpty()) {\n this.result = result;\n } else {\n this.result.addAll(result);\n }\n }", "private List<Row> createWorkPatternAssignmentRowList(String workPatterns) throws ParseException\n {\n List<Row> list = new ArrayList<Row>();\n String[] patterns = workPatterns.split(\",|:\");\n int index = 1;\n while (index < patterns.length)\n {\n Integer workPattern = Integer.valueOf(patterns[index + 1]);\n Date startDate = DatatypeConverter.parseBasicTimestamp(patterns[index + 3]);\n Date endDate = DatatypeConverter.parseBasicTimestamp(patterns[index + 4]);\n\n Map<String, Object> map = new HashMap<String, Object>();\n map.put(\"WORK_PATTERN\", workPattern);\n map.put(\"START_DATE\", startDate);\n map.put(\"END_DATE\", endDate);\n\n list.add(new MapRow(map));\n\n index += 5;\n }\n\n return list;\n }", "public static String replaceErrorMsg(String origMsg) {\n\n String replaceMsg = origMsg;\n for (ERROR_TYPE errorType : ERROR_TYPE.values()) {\n\n if (origMsg == null) {\n replaceMsg = PcConstants.NA;\n return replaceMsg;\n }\n\n if (origMsg.contains(errorMapOrig.get(errorType))) {\n replaceMsg = errorMapReplace.get(errorType);\n break;\n }\n\n }\n\n return replaceMsg;\n\n }" ]
Returns an array of all the singular values
[ "public double[] getSingularValues() {\n double ret[] = new double[W.numCols()];\n\n for (int i = 0; i < ret.length; i++) {\n ret[i] = getSingleValue(i);\n }\n return ret;\n }" ]
[ "public static ModelNode createListDeploymentsOperation() {\n final ModelNode op = createOperation(READ_CHILDREN_NAMES);\n op.get(CHILD_TYPE).set(DEPLOYMENT);\n return op;\n }", "public static void copy(byte[] in, OutputStream out) throws IOException {\n\t\tAssert.notNull(in, \"No input byte array specified\");\n\t\tAssert.notNull(out, \"No OutputStream specified\");\n\t\tout.write(in);\n\t}", "protected final <T> StyleSupplier<T> createStyleSupplier(\n final Template template,\n final String styleRef) {\n return new StyleSupplier<T>() {\n @Override\n public Style load(\n final MfClientHttpRequestFactory requestFactory,\n final T featureSource) {\n final StyleParser parser = AbstractGridCoverageLayerPlugin.this.styleParser;\n return OptionalUtils.or(\n () -> template.getStyle(styleRef),\n () -> parser.loadStyle(template.getConfiguration(), requestFactory, styleRef))\n .orElse(template.getConfiguration().getDefaultStyle(NAME));\n }\n };\n }", "public static <T extends Annotation> List<T> searchForAnnotation(Method method, Class<T> annotation) {\n if (method == null) {\n return Lists.newArrayList();\n }\n return searchClasses(method, annotation, method.getDeclaringClass());\n }", "@NonNull\n public static String placeholders(final int numberOfPlaceholders) {\n if (numberOfPlaceholders == 1) {\n return \"?\"; // fffast\n } else if (numberOfPlaceholders == 0) {\n return \"\";\n } else if (numberOfPlaceholders < 0) {\n throw new IllegalArgumentException(\"numberOfPlaceholders must be >= 0, but was = \" + numberOfPlaceholders);\n }\n\n final StringBuilder stringBuilder = new StringBuilder((numberOfPlaceholders * 2) - 1);\n\n for (int i = 0; i < numberOfPlaceholders; i++) {\n stringBuilder.append('?');\n\n if (i != numberOfPlaceholders - 1) {\n stringBuilder.append(',');\n }\n }\n\n return stringBuilder.toString();\n }", "public boolean isMaskCompatibleWithRange(int maskValue, Integer segmentPrefixLength) throws PrefixLenException {\r\n\t\tif(!isMultiple()) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\treturn super.isMaskCompatibleWithRange(maskValue, segmentPrefixLength, getNetwork().getPrefixConfiguration().allPrefixedAddressesAreSubnets());\r\n\t}", "public PhotoList<Photo> getPublicPhotos(String userId, Set<String> extras, int perPage, int page) throws FlickrException {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PUBLIC_PHOTOS);\r\n\r\n parameters.put(\"user_id\", userId);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n\r\n if (extras != null) {\r\n parameters.put(Extras.KEY_EXTRAS, StringUtilities.join(extras, \",\"));\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n photos.setPage(photosElement.getAttribute(\"page\"));\r\n photos.setPages(photosElement.getAttribute(\"pages\"));\r\n photos.setPerPage(photosElement.getAttribute(\"perpage\"));\r\n photos.setTotal(photosElement.getAttribute(\"total\"));\r\n\r\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element photoElement = (Element) photoNodes.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement));\r\n }\r\n return photos;\r\n }", "@Override\n public void process(TestCaseResult context) {\n context.getParameters().add(new Parameter()\n .withName(getName())\n .withValue(getValue())\n .withKind(ParameterKind.valueOf(getKind()))\n );\n }", "public static base_response update(nitro_service client, bridgetable resource) throws Exception {\n\t\tbridgetable updateresource = new bridgetable();\n\t\tupdateresource.bridgeage = resource.bridgeage;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
Read custom fields for a GanttProject resource. @param gpResource GanttProject resource @param mpxjResource MPXJ Resource instance
[ "private void readResourceCustomFields(net.sf.mpxj.ganttproject.schema.Resource gpResource, Resource mpxjResource)\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_resourcePropertyDefinitions.values())\n {\n customFields.put(definition.getFirst(), definition.getSecond());\n }\n\n //\n // Update with custom field actual values\n //\n for (CustomResourceProperty property : gpResource.getCustomProperty())\n {\n Pair<FieldType, String> definition = m_resourcePropertyDefinitions.get(property.getDefinitionId());\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_localeDateFormat.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 mpxjResource.set(item.getKey(), item.getValue());\n }\n }\n }" ]
[ "@Override\n public final synchronized void stopService(long millis) {\n running = false;\n try {\n if (keepRunning) {\n keepRunning = false;\n interrupt();\n quit();\n if (0L == millis) {\n join();\n } else {\n join(millis);\n }\n }\n } catch (InterruptedException e) {\n //its possible that the thread exits between the lines keepRunning=false and interrupt above\n log.warn(\"Got interrupted while stopping {}\", this, e);\n\n Thread.currentThread().interrupt();\n }\n }", "public static Date max(Date d1, Date d2)\n {\n Date result;\n if (d1 == null)\n {\n result = d2;\n }\n else\n if (d2 == null)\n {\n result = d1;\n }\n else\n {\n result = (d1.compareTo(d2) > 0) ? d1 : d2;\n }\n return result;\n }", "public static boolean setCustomResponseForDefaultClient(String profileName, String pathName, String customData) {\n try {\n return setCustomForDefaultClient(profileName, pathName, true, customData);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\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}", "public final void setExceptions(SortedSet<Date> dates) {\n\n m_exceptions.clear();\n if (null != dates) {\n m_exceptions.addAll(dates);\n }\n\n }", "private void afterBatch(BatchBackend backend) {\n\t\tIndexedTypeSet targetedTypes = searchFactoryImplementor.getIndexedTypesPolymorphic( rootIndexedTypes );\n\t\tif ( this.optimizeAtEnd ) {\n\t\t\tbackend.optimize( targetedTypes );\n\t\t}\n\t\tbackend.flush( targetedTypes );\n\t}", "public static VectorClock makeClock(Set<Integer> serverIds, long clockValue, long timestamp) {\n List<ClockEntry> clockEntries = new ArrayList<ClockEntry>(serverIds.size());\n for(Integer serverId: serverIds) {\n clockEntries.add(new ClockEntry(serverId.shortValue(), clockValue));\n }\n return new VectorClock(clockEntries, timestamp);\n }", "private void fillWeekPanel() {\r\n\r\n addCheckBox(WeekOfMonth.FIRST.toString(), Messages.GUI_SERIALDATE_WEEKDAYNUMBER_1_0);\r\n addCheckBox(WeekOfMonth.SECOND.toString(), Messages.GUI_SERIALDATE_WEEKDAYNUMBER_2_0);\r\n addCheckBox(WeekOfMonth.THIRD.toString(), Messages.GUI_SERIALDATE_WEEKDAYNUMBER_3_0);\r\n addCheckBox(WeekOfMonth.FOURTH.toString(), Messages.GUI_SERIALDATE_WEEKDAYNUMBER_4_0);\r\n addCheckBox(WeekOfMonth.LAST.toString(), Messages.GUI_SERIALDATE_WEEKDAYNUMBER_5_0);\r\n }", "private <A extends Annotation> AnnotationConverter<A> getConverter(Annotation annotation) {\n\t\tMappingOption mappingOption = annotation.annotationType().getAnnotation( MappingOption.class );\n\t\tif ( mappingOption == null ) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// wrong type would be a programming error of the annotation developer\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tClass<? extends AnnotationConverter<A>> converterClass = (Class<? extends AnnotationConverter<A>>) mappingOption.value();\n\n\t\ttry {\n\t\t\treturn converterClass.newInstance();\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tthrow log.cannotConvertAnnotation( converterClass, e );\n\t\t}\n\t}" ]
Returns flag whose value indicates if the string is null, empty or only contains whitespace characters @param s a string @return true if the string is null, empty or only contains whitespace characters
[ "static boolean isEmptyWhitespace(@Nullable final String s) {\n if (s == null) {\n return true;\n }\n return CharMatcher.WHITESPACE.matchesAllOf(s);\n }" ]
[ "public RandomVariable[] getBasisFunctions(double fixingDate, LIBORModelMonteCarloSimulationModel model) throws CalculationException {\n\n\t\tArrayList<RandomVariable> basisFunctions = new ArrayList<>();\n\n\t\t// Constant\n\t\tRandomVariable basisFunction = new RandomVariableFromDoubleArray(1.0);//.getRandomVariableForConstant(1.0);\n\t\tbasisFunctions.add(basisFunction);\n\n\t\tint fixingDateIndex = Arrays.binarySearch(fixingDates, fixingDate);\n\t\tif(fixingDateIndex < 0) {\n\t\t\tfixingDateIndex = -fixingDateIndex;\n\t\t}\n\t\tif(fixingDateIndex >= fixingDates.length) {\n\t\t\tfixingDateIndex = fixingDates.length-1;\n\t\t}\n\n\t\t// forward rate to the next period\n\t\tRandomVariable rateShort = model.getLIBOR(fixingDate, fixingDate, paymentDates[fixingDateIndex]);\n\t\tRandomVariable discountShort = rateShort.mult(paymentDates[fixingDateIndex]-fixingDate).add(1.0).invert();\n\t\tbasisFunctions.add(discountShort);\n\t\tbasisFunctions.add(discountShort.pow(2.0));\n\t\t//\t\tbasisFunctions.add(rateShort.pow(3.0));\n\n\t\t// forward rate to the end of the product\n\t\tRandomVariable rateLong = model.getLIBOR(fixingDate, fixingDates[fixingDateIndex], paymentDates[paymentDates.length-1]);\n\t\tRandomVariable discountLong = rateLong.mult(paymentDates[paymentDates.length-1]-fixingDates[fixingDateIndex]).add(1.0).invert();\n\t\tbasisFunctions.add(discountLong);\n\t\tbasisFunctions.add(discountLong.pow(2.0));\n\t\t//\t\tbasisFunctions.add(rateLong.pow(3.0));\n\n\t\t// Numeraire\n\t\tRandomVariable numeraire = model.getNumeraire(fixingDate).invert();\n\t\tbasisFunctions.add(numeraire);\n\t\t//\t\tbasisFunctions.add(numeraire.pow(2.0));\n\t\t//\t\tbasisFunctions.add(numeraire.pow(3.0));\n\n\t\treturn basisFunctions.toArray(new RandomVariable[basisFunctions.size()]);\n\t}", "public CollectionRequest<Tag> findByWorkspace(String workspace) {\n \n String path = String.format(\"/workspaces/%s/tags\", workspace);\n return new CollectionRequest<Tag>(this, Tag.class, path, \"GET\");\n }", "public static final BigInteger getBigInteger(Number value)\n {\n BigInteger result = null;\n if (value != null)\n {\n if (value instanceof BigInteger)\n {\n result = (BigInteger) value;\n }\n else\n {\n result = BigInteger.valueOf(Math.round(value.doubleValue()));\n }\n }\n return (result);\n }", "@Override\n public boolean decompose( ZMatrixRMaj A )\n {\n if( A.numRows != A.numCols )\n throw new IllegalArgumentException(\"A must be square.\");\n if( A.numRows <= 0 )\n return false;\n\n QH = A;\n\n N = A.numCols;\n\n if( b.length < N*2 ) {\n b = new double[ N*2 ];\n gammas = new double[ N ];\n u = new double[ N*2 ];\n }\n return _decompose();\n }", "public static void validateExternalizersPresent(EmbeddedCacheManager externalCacheManager) {\n\t\tMap<Integer, AdvancedExternalizer<?>> externalizerMap = externalCacheManager\n\t\t\t\t.getCacheManagerConfiguration()\n\t\t\t\t.serialization()\n\t\t\t\t.advancedExternalizers();\n\t\tfor ( AdvancedExternalizer<?> ogmExternalizer : ogmExternalizers.values() ) {\n\t\t\tfinal Integer externalizerId = ogmExternalizer.getId();\n\t\t\tAdvancedExternalizer<?> registeredExternalizer = externalizerMap.get( externalizerId );\n\t\t\tif ( registeredExternalizer == null ) {\n\t\t\t\tthrow log.externalizersNotRegistered( externalizerId, ogmExternalizer.getClass() );\n\t\t\t}\n\t\t\telse if ( !registeredExternalizer.getClass().equals( ogmExternalizer ) ) {\n\t\t\t\tif ( registeredExternalizer.getClass().toString().equals( ogmExternalizer.getClass().toString() ) ) {\n\t\t\t\t\t// same class name, yet different Class definition!\n\t\t\t\t\tthrow log.registeredExternalizerNotLoadedFromOGMClassloader( registeredExternalizer.getClass() );\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow log.externalizerIdNotMatchingType( externalizerId, registeredExternalizer, ogmExternalizer );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "public AsciiTable setPaddingTopChar(Character paddingTopChar) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingTopChar(paddingTopChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "private boolean isNullOrEmpty(Object paramValue) {\n boolean isNullOrEmpty = false;\n if (paramValue == null) {\n isNullOrEmpty = true;\n }\n if (paramValue instanceof String) {\n if (((String) paramValue).trim().equalsIgnoreCase(\"\")) {\n isNullOrEmpty = true;\n }\n } else if (paramValue instanceof List) {\n return ((List) paramValue).isEmpty();\n }\n return isNullOrEmpty;\n }", "@Override\n public EventStream doStreamRequest(final StitchRequest stitchReq) {\n initAppMetadata(clientAppId);\n\n return super.doStreamRequestUrl(stitchReq, getHostname());\n }", "public static base_response unset(nitro_service client, snmpalarm resource, String[] args) throws Exception{\n\t\tsnmpalarm unsetresource = new snmpalarm();\n\t\tunsetresource.trapname = resource.trapname;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}" ]
Creates or returns the instance of the helper class. @param inputSpecification the input specification. @param formFillMode if random data should be used on the input fields. @return The singleton instance.
[ "public static synchronized FormInputValueHelper getInstance(\n\t\t\tInputSpecification inputSpecification, FormFillMode formFillMode) {\n\t\tif (instance == null)\n\t\t\tinstance = new FormInputValueHelper(inputSpecification,\n\t\t\t\t\tformFillMode);\n\t\treturn instance;\n\t}" ]
[ "@Nullable\n public static LocationEngineResult extractResult(Intent intent) {\n LocationEngineResult result = null;\n if (isOnClasspath(GOOGLE_PLAY_LOCATION_RESULT)) {\n result = extractGooglePlayResult(intent);\n }\n return result == null ? extractAndroidResult(intent) : result;\n }", "public JSONObject marshal(final AccessAssertion assertion) {\n final JSONObject jsonObject = assertion.marshal();\n if (jsonObject.has(JSON_CLASS_NAME)) {\n throw new AssertionError(\"The toJson method in AccessAssertion: '\" + assertion.getClass() +\n \"' defined a JSON field \" + JSON_CLASS_NAME +\n \" which is a reserved keyword and is not permitted to be used \" +\n \"in toJSON method\");\n }\n try {\n jsonObject.put(JSON_CLASS_NAME, assertion.getClass().getName());\n } catch (JSONException e) {\n throw new RuntimeException(e);\n }\n\n return jsonObject;\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 }", "private synchronized void finishTransition(final InternalState current, final InternalState next) {\n internalSetState(getTransitionTask(next), current, next);\n transition();\n }", "public static String getHeaders(HttpServletRequest request) {\n String headerString = \"\";\n Enumeration<String> headerNames = request.getHeaderNames();\n\n while (headerNames.hasMoreElements()) {\n String name = headerNames.nextElement();\n if (name.equals(Constants.ODO_PROXY_HEADER)) {\n // skip.. don't want to log this\n continue;\n }\n\n if (headerString.length() != 0) {\n headerString += \"\\n\";\n }\n\n headerString += name + \": \" + request.getHeader(name);\n }\n\n return headerString;\n }", "public void setNearClippingDistance(float near) {\n if(leftCamera instanceof GVRCameraClippingDistanceInterface &&\n centerCamera instanceof GVRCameraClippingDistanceInterface &&\n rightCamera instanceof GVRCameraClippingDistanceInterface) {\n ((GVRCameraClippingDistanceInterface)leftCamera).setNearClippingDistance(near);\n centerCamera.setNearClippingDistance(near);\n ((GVRCameraClippingDistanceInterface)rightCamera).setNearClippingDistance(near);\n }\n }", "private void verifiedCopyFile(File sourceFile, File destFile) throws IOException {\n if(!destFile.exists()) {\n destFile.createNewFile();\n }\n\n FileInputStream source = null;\n FileOutputStream destination = null;\n LogVerificationInputStream verifyStream = null;\n try {\n source = new FileInputStream(sourceFile);\n destination = new FileOutputStream(destFile);\n verifyStream = new LogVerificationInputStream(env, source, sourceFile.getName());\n\n final byte[] buf = new byte[LOGVERIFY_BUFSIZE];\n\n while(true) {\n final int len = verifyStream.read(buf);\n if(len < 0) {\n break;\n }\n destination.write(buf, 0, len);\n }\n\n } finally {\n if(verifyStream != null) {\n verifyStream.close();\n }\n if(destination != null) {\n destination.close();\n }\n }\n }", "public IExternalAccess getAgentsExternalAccess(String agent_name) {\n\n return cmsService.getExternalAccess(getAgentID(agent_name)).get(\n new ThreadSuspendable());\n }", "public static Resource getSetupPage(I_SetupUiContext context, String name) {\n\n String path = CmsStringUtil.joinPaths(context.getSetupBean().getContextPath(), CmsSetupBean.FOLDER_SETUP, name);\n Resource resource = new ExternalResource(path);\n return resource;\n }" ]
Use this API to fetch sslaction resource of given name .
[ "public static sslaction get(nitro_service service, String name) throws Exception{\n\t\tsslaction obj = new sslaction();\n\t\tobj.set_name(name);\n\t\tsslaction response = (sslaction) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
[ "public String[] getNormalizedLabels() {\n\t\tif(isValid()) {\n\t\t\treturn parsedHost.getNormalizedLabels();\n\t\t}\n\t\tif(host.length() == 0) {\n\t\t\treturn new String[0];\n\t\t}\n\t\treturn new String[] {host};\n\t}", "private void readResourceCustomPropertyDefinitions(Resources gpResources)\n {\n CustomField field = m_projectFile.getCustomFields().getCustomField(ResourceField.TEXT1);\n field.setAlias(\"Phone\");\n\n for (CustomPropertyDefinition definition : gpResources.getCustomPropertyDefinition())\n {\n //\n // Find the next available field of the correct type.\n //\n String type = definition.getType();\n FieldType fieldType = RESOURCE_PROPERTY_TYPES.get(type).getField();\n\n //\n // If we have run out of fields of the right type, try using a text field.\n //\n if (fieldType == null)\n {\n fieldType = RESOURCE_PROPERTY_TYPES.get(\"text\").getField();\n }\n\n //\n // If we actually have a field available, set the alias to match\n // the name used in GanttProject.\n //\n if (fieldType != null)\n {\n field = m_projectFile.getCustomFields().getCustomField(fieldType);\n field.setAlias(definition.getName());\n String defaultValue = definition.getDefaultValue();\n if (defaultValue != null && defaultValue.isEmpty())\n {\n defaultValue = null;\n }\n m_resourcePropertyDefinitions.put(definition.getId(), new Pair<FieldType, String>(fieldType, defaultValue));\n }\n }\n }", "private void setNsid() throws FlickrException {\n\n if (username != null && !username.equals(\"\")) {\n Auth auth = null;\n if (authStore != null) {\n auth = authStore.retrieve(username); // assuming FileAuthStore is enhanced else need to\n // keep in user-level files.\n\n if (auth != null) {\n nsid = auth.getUser().getId();\n }\n }\n if (auth != null)\n return;\n\n Auth[] allAuths = authStore.retrieveAll();\n for (int i = 0; i < allAuths.length; i++) {\n if (username.equals(allAuths[i].getUser().getUsername())) {\n nsid = allAuths[i].getUser().getId();\n return;\n }\n }\n\n // For this to work: REST.java or PeopleInterface needs to change to pass apiKey\n // as the parameter to the call which is not authenticated.\n\n // Get nsid using flickr.people.findByUsername\n PeopleInterface peopleInterf = flickr.getPeopleInterface();\n User u = peopleInterf.findByUsername(username);\n if (u != null) {\n nsid = u.getId();\n }\n }\n }", "public EventBus emit(EventObject event, Object... args) {\n return _emitWithOnceBus(eventContext(event, args));\n }", "private boolean findBinding(Injector injector, Class<?> type) {\n boolean found = false;\n for (Key<?> key : injector.getBindings().keySet()) {\n if (key.getTypeLiteral().getRawType().equals(type)) {\n found = true;\n break;\n }\n }\n if (!found && injector.getParent() != null) {\n return findBinding(injector.getParent(), type);\n }\n\n return found;\n }", "private int getFlagResource(Country country) {\n return getContext().getResources().getIdentifier(\"country_\" + country.getIso().toLowerCase(), \"drawable\", getContext().getPackageName());\n }", "private void checkForCycles(DefaultDirectedWeightedGraph<RuleProvider, DefaultEdge> graph)\n {\n CycleDetector<RuleProvider, DefaultEdge> cycleDetector = new CycleDetector<>(graph);\n\n if (cycleDetector.detectCycles())\n {\n // if we have cycles, then try to throw an exception with some usable data\n Set<RuleProvider> cycles = cycleDetector.findCycles();\n StringBuilder errorSB = new StringBuilder();\n for (RuleProvider cycle : cycles)\n {\n errorSB.append(\"Found dependency cycle involving: \" + cycle.getMetadata().getID()).append(System.lineSeparator());\n Set<RuleProvider> subCycleSet = cycleDetector.findCyclesContainingVertex(cycle);\n for (RuleProvider subCycle : subCycleSet)\n {\n errorSB.append(\"\\tSubcycle: \" + subCycle.getMetadata().getID()).append(System.lineSeparator());\n }\n }\n throw new RuntimeException(\"Dependency cycles detected: \" + errorSB.toString());\n }\n }", "private String getTaskField(int key)\n {\n String result = null;\n\n if ((key > 0) && (key < m_taskNames.length))\n {\n result = m_taskNames[key];\n }\n\n return (result);\n }", "public static URL classFileUrl(Class<?> clazz) throws IOException {\n ClassLoader cl = clazz.getClassLoader();\n if (cl == null) {\n cl = ClassLoader.getSystemClassLoader();\n }\n URL res = cl.getResource(clazz.getName().replace('.', '/') + \".class\");\n if (res == null) {\n throw new IllegalArgumentException(\"Unable to locate class file for \" + clazz);\n }\n return res;\n }" ]
Detach a connection from a key. @param key the key @param connection the connection
[ "public void signOff(String key, WebSocketConnection connection) {\n ConcurrentMap<WebSocketConnection, WebSocketConnection> connections = registry.get(key);\n if (null == connections) {\n return;\n }\n connections.remove(connection);\n }" ]
[ "public static String get(Properties props, String name, String defval) {\n String value = props.getProperty(name);\n if (value == null)\n value = defval;\n return value;\n }", "public static final Date getTime(InputStream is) throws IOException\n {\n int timeValue = getInt(is);\n timeValue -= 86400;\n timeValue /= 60;\n return DateHelper.getTimeFromMinutesPastMidnight(Integer.valueOf(timeValue));\n }", "private String getApiKey(CmsObject cms, String sitePath) throws CmsException {\n\n String res = cms.readPropertyObject(\n sitePath,\n CmsPropertyDefinition.PROPERTY_GOOGLE_API_KEY_WORKPLACE,\n true).getValue();\n\n if (CmsStringUtil.isEmptyOrWhitespaceOnly(res)) {\n res = cms.readPropertyObject(sitePath, CmsPropertyDefinition.PROPERTY_GOOGLE_API_KEY, true).getValue();\n }\n return res;\n\n }", "public static base_response unset(nitro_service client, lbsipparameters resource, String[] args) throws Exception{\n\t\tlbsipparameters unsetresource = new lbsipparameters();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "static ChangeEvent<BsonDocument> changeEventForLocalReplace(\n final MongoNamespace namespace,\n final BsonValue documentId,\n final BsonDocument document,\n final boolean writePending\n ) {\n return new ChangeEvent<>(\n new BsonDocument(),\n OperationType.REPLACE,\n document,\n namespace,\n new BsonDocument(\"_id\", documentId),\n null,\n writePending);\n }", "public static String getButtonName(String gallery) {\n\n StringBuffer sb = new StringBuffer(GUI_BUTTON_PREF);\n sb.append(gallery.toUpperCase());\n sb.append(GUI_BUTTON_SUF);\n return sb.toString();\n }", "public static systemuser get(nitro_service service, String username) throws Exception{\n\t\tsystemuser obj = new systemuser();\n\t\tobj.set_username(username);\n\t\tsystemuser response = (systemuser) obj.get_resource(service);\n\t\treturn response;\n\t}", "public ParallelTaskBuilder setTargetHostsFromJsonPath(String jsonPath,\n String sourcePath, HostsSourceType sourceType)\n throws TargetHostsLoadException {\n\n this.targetHosts = targetHostBuilder.setTargetHostsFromJsonPath(jsonPath, sourcePath,\n sourceType);\n return this;\n\n }", "public static ClassLoader overrideThreadContextClassLoader(ClassLoader classLoaderToUse) {\n\t\tThread currentThread = Thread.currentThread();\n\t\tClassLoader threadContextClassLoader = currentThread.getContextClassLoader();\n\t\tif (classLoaderToUse != null && !classLoaderToUse.equals(threadContextClassLoader)) {\n\t\t\tcurrentThread.setContextClassLoader(classLoaderToUse);\n\t\t\treturn threadContextClassLoader;\n\t\t}\n\t\telse {\n\t\t\treturn null;\n\t\t}\n\t}" ]
Removes any child object that has the given name by performing case-sensitive search. @param name name of scene object to be removed. @return number of removed objects, 0 if none was found.
[ "public int removeChildObjectsByName(final String name) {\n int removed = 0;\n\n if (null != name && !name.isEmpty()) {\n removed = removeChildObjectsByNameImpl(name);\n }\n\n return removed;\n }" ]
[ "@Override\n public List<Integer> getReplicatingPartitionList(int index) {\n List<Node> preferenceNodesList = new ArrayList<Node>(getNumReplicas());\n List<Integer> replicationPartitionsList = new ArrayList<Integer>(getNumReplicas());\n\n // Copy Zone based Replication Factor\n HashMap<Integer, Integer> requiredRepFactor = new HashMap<Integer, Integer>();\n requiredRepFactor.putAll(zoneReplicationFactor);\n\n // Cross-check if individual zone replication factor equals global\n int sum = 0;\n for(Integer zoneRepFactor: requiredRepFactor.values()) {\n sum += zoneRepFactor;\n }\n\n if(sum != getNumReplicas())\n throw new IllegalArgumentException(\"Number of zone replicas is not equal to the total replication factor\");\n\n if(getPartitionToNode().length == 0) {\n return new ArrayList<Integer>(0);\n }\n\n for(int i = 0; i < getPartitionToNode().length; i++) {\n // add this one if we haven't already, and it can satisfy some zone\n // replicationFactor\n Node currentNode = getNodeByPartition(index);\n if(!preferenceNodesList.contains(currentNode)) {\n preferenceNodesList.add(currentNode);\n if(checkZoneRequirement(requiredRepFactor, currentNode.getZoneId()))\n replicationPartitionsList.add(index);\n }\n\n // if we have enough, go home\n if(replicationPartitionsList.size() >= getNumReplicas())\n return replicationPartitionsList;\n // move to next clockwise slot on the ring\n index = (index + 1) % getPartitionToNode().length;\n }\n\n // we don't have enough, but that may be okay\n return replicationPartitionsList;\n }", "@Pure\n\tpublic static <K, V> Map<K, V> operator_minus(Map<K, V> left, final Map<? extends K, ? extends V> right) {\n\t\treturn Maps.filterEntries(left, new Predicate<Entry<K, V>>() {\n\t\t\t@Override\n\t\t\tpublic boolean apply(Entry<K, V> input) {\n\t\t\t\tfinal V value = right.get(input.getKey());\n\t\t\t\tif (value == null) {\n\t\t\t\t\treturn input.getValue() == null && right.containsKey(input.getKey());\n\t\t\t\t}\n\t\t\t\treturn !Objects.equal(input.getValue(), value);\n\t\t\t}\n\t\t});\n\t}", "public void setTileUrls(List<String> tileUrls) {\n\t\tthis.tileUrls = tileUrls;\n\t\tif (null != urlStrategy) {\n\t\t\turlStrategy.setUrls(tileUrls);\n\t\t}\n\t}", "protected float[] transformPosition(float x, float y)\n {\n Point2D.Float point = super.transformedPoint(x, y);\n AffineTransform pageTransform = createCurrentPageTransformation();\n Point2D.Float transformedPoint = (Point2D.Float) pageTransform.transform(point, null);\n\n return new float[]{(float) transformedPoint.getX(), (float) transformedPoint.getY()};\n }", "public String haikunate() {\n if (tokenHex) {\n tokenChars = \"0123456789abcdef\";\n }\n\n String adjective = randomString(adjectives);\n String noun = randomString(nouns);\n\n StringBuilder token = new StringBuilder();\n if (tokenChars != null && tokenChars.length() > 0) {\n for (int i = 0; i < tokenLength; i++) {\n token.append(tokenChars.charAt(random.nextInt(tokenChars.length())));\n }\n }\n\n return Stream.of(adjective, noun, token.toString())\n .filter(s -> s != null && !s.isEmpty())\n .collect(joining(delimiter));\n }", "private StepFormatter.Formatting<?, ?> getFormatting( Annotation[] annotations, Set<Class<?>> visitedTypes,\n Annotation originalAnnotation, String parameterName ) {\n List<StepFormatter.Formatting<?, ?>> foundFormatting = Lists.newArrayList();\n Table tableAnnotation = null;\n for( Annotation annotation : annotations ) {\n try {\n if( annotation instanceof Format ) {\n Format arg = (Format) annotation;\n foundFormatting.add( new StepFormatter.ArgumentFormatting( ReflectionUtil.newInstance( arg.value() ), arg.args() ) );\n } else if( annotation instanceof Table ) {\n tableAnnotation = (Table) annotation;\n } else if( annotation instanceof AnnotationFormat ) {\n AnnotationFormat arg = (AnnotationFormat) annotation;\n foundFormatting.add( new StepFormatter.ArgumentFormatting(\n new StepFormatter.AnnotationBasedFormatter( arg.value().newInstance(), originalAnnotation ) ) );\n } else {\n Class<? extends Annotation> annotationType = annotation.annotationType();\n if( !visitedTypes.contains( annotationType ) ) {\n visitedTypes.add( annotationType );\n StepFormatter.Formatting<?, ?> formatting = getFormatting( annotationType.getAnnotations(), visitedTypes,\n annotation, parameterName );\n if( formatting != null ) {\n foundFormatting.add( formatting );\n }\n }\n }\n } catch( Exception e ) {\n throw Throwables.propagate( e );\n }\n }\n\n if( foundFormatting.size() > 1 ) {\n Formatting<?, ?> innerFormatting = Iterables.getLast( foundFormatting );\n foundFormatting.remove( innerFormatting );\n\n ChainedFormatting<?> chainedFormatting = new StepFormatter.ChainedFormatting<Object>( (ObjectFormatter<Object>) innerFormatting );\n for( StepFormatter.Formatting<?, ?> formatting : Lists.reverse( foundFormatting ) ) {\n chainedFormatting.addFormatting( (StepFormatter.Formatting<?, String>) formatting );\n }\n\n foundFormatting.clear();\n foundFormatting.add( chainedFormatting );\n }\n\n if( tableAnnotation != null ) {\n ObjectFormatter<?> objectFormatter = foundFormatting.isEmpty()\n ? DefaultFormatter.INSTANCE\n : foundFormatting.get( 0 );\n return getTableFormatting( annotations, parameterName, tableAnnotation, objectFormatter );\n }\n\n if( foundFormatting.isEmpty() ) {\n return null;\n }\n\n return foundFormatting.get( 0 );\n }", "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 static Map<String, Object> introspect(Object obj) throws IntrospectionException, InvocationTargetException, IllegalAccessException {\n\t\tMap<String, Object> result = new HashMap<>();\n\t\tBeanInfo info = Introspector.getBeanInfo( obj.getClass() );\n\t\tfor ( PropertyDescriptor pd : info.getPropertyDescriptors() ) {\n\t\t\tMethod reader = pd.getReadMethod();\n\t\t\tString name = pd.getName();\n\t\t\tif ( reader != null && !\"class\".equals( name ) ) {\n\t\t\t\tresult.put( name, reader.invoke( obj ) );\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}", "private static Point getScreenSize(Context context, Point p) {\n if (p == null) {\n p = new Point();\n }\n WindowManager windowManager = (WindowManager) context\n .getSystemService(Context.WINDOW_SERVICE);\n Display display = windowManager.getDefaultDisplay();\n display.getSize(p);\n return p;\n }" ]
Initialize the service with a context @param context the servlet context to initialize the profile.
[ "public void init(ServletContext context) {\n if (profiles != null) {\n for (IDiagramProfile profile : profiles) {\n profile.init(context);\n _registry.put(profile.getName(),\n profile);\n }\n }\n }" ]
[ "public static String getDefaultJdbcTypeFor(String javaType)\r\n {\r\n return _jdbcMappings.containsKey(javaType) ? (String)_jdbcMappings.get(javaType) : JDBC_DEFAULT_TYPE;\r\n }", "public static void addService(final ServiceTarget serviceTarget, final Bootstrap.Configuration configuration,\n final ControlledProcessState processState, final BootstrapListener bootstrapListener,\n final RunningModeControl runningModeControl, final AbstractVaultReader vaultReader, final ManagedAuditLogger auditLogger,\n final DelegatingConfigurableAuthorizer authorizer, final ManagementSecurityIdentitySupplier securityIdentitySupplier,\n final SuspendController suspendController) {\n\n // Install Executor services\n final ThreadGroup threadGroup = new ThreadGroup(\"ServerService ThreadGroup\");\n final String namePattern = \"ServerService Thread Pool -- %t\";\n final ThreadFactory threadFactory = doPrivileged(new PrivilegedAction<ThreadFactory>() {\n public ThreadFactory run() {\n return new JBossThreadFactory(threadGroup, Boolean.FALSE, null, namePattern, null, null);\n }\n });\n\n // TODO determine why QueuelessThreadPoolService makes boot take > 35 secs\n// final QueuelessThreadPoolService serverExecutorService = new QueuelessThreadPoolService(Integer.MAX_VALUE, false, new TimeSpec(TimeUnit.SECONDS, 5));\n// serverExecutorService.getThreadFactoryInjector().inject(threadFactory);\n final boolean forDomain = ProcessType.DOMAIN_SERVER == getProcessType(configuration.getServerEnvironment());\n final ServerExecutorService serverExecutorService = new ServerExecutorService(threadFactory, forDomain);\n serviceTarget.addService(MANAGEMENT_EXECUTOR, serverExecutorService)\n .addAliases(Services.JBOSS_SERVER_EXECUTOR, ManagementRemotingServices.SHUTDOWN_EXECUTOR_NAME) // Use this executor for mgmt shutdown for now\n .install();\n final ServerScheduledExecutorService serverScheduledExecutorService = new ServerScheduledExecutorService(threadFactory);\n serviceTarget.addService(JBOSS_SERVER_SCHEDULED_EXECUTOR, serverScheduledExecutorService)\n .addAliases(JBOSS_SERVER_SCHEDULED_EXECUTOR)\n .addDependency(MANAGEMENT_EXECUTOR, ExecutorService.class, serverScheduledExecutorService.executorInjector)\n .install();\n\n final CapabilityRegistry capabilityRegistry = configuration.getCapabilityRegistry();\n ServerService service = new ServerService(configuration, processState, null, bootstrapListener, new ServerDelegatingResourceDefinition(),\n runningModeControl, vaultReader, auditLogger, authorizer, securityIdentitySupplier, capabilityRegistry, suspendController);\n\n ExternalManagementRequestExecutor.install(serviceTarget, threadGroup, EXECUTOR_CAPABILITY.getCapabilityServiceName(), service.getStabilityMonitor());\n\n ServiceBuilder<?> serviceBuilder = serviceTarget.addService(Services.JBOSS_SERVER_CONTROLLER, service);\n serviceBuilder.addDependency(DeploymentMountProvider.SERVICE_NAME,DeploymentMountProvider.class, service.injectedDeploymentRepository);\n serviceBuilder.addDependency(ContentRepository.SERVICE_NAME, ContentRepository.class, service.injectedContentRepository);\n serviceBuilder.addDependency(Services.JBOSS_SERVICE_MODULE_LOADER, ServiceModuleLoader.class, service.injectedModuleLoader);\n serviceBuilder.addDependency(Services.JBOSS_EXTERNAL_MODULE_SERVICE, ExternalModuleService.class,\n service.injectedExternalModuleService);\n serviceBuilder.addDependency(PATH_MANAGER_CAPABILITY.getCapabilityServiceName(), PathManager.class, service.injectedPathManagerService);\n if (configuration.getServerEnvironment().isAllowModelControllerExecutor()) {\n serviceBuilder.addDependency(MANAGEMENT_EXECUTOR, ExecutorService.class, service.getExecutorServiceInjector());\n }\n if (configuration.getServerEnvironment().getLaunchType() == ServerEnvironment.LaunchType.DOMAIN) {\n serviceBuilder.addDependency(HostControllerConnectionService.SERVICE_NAME, ControllerInstabilityListener.class,\n service.getContainerInstabilityInjector());\n }\n\n serviceBuilder.install();\n }", "public boolean detectBlackBerryHigh() {\r\n\r\n //Disambiguate for BlackBerry OS 6 or 7 (WebKit) browser\r\n if (detectBlackBerryWebKit()) {\r\n return false;\r\n }\r\n if (detectBlackBerry()) {\r\n if (detectBlackBerryTouch()\r\n || (userAgent.indexOf(deviceBBBold) != -1)\r\n || (userAgent.indexOf(deviceBBTour) != -1)\r\n || (userAgent.indexOf(deviceBBCurve) != -1)) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n } else {\r\n return false;\r\n }\r\n }", "public static ModelNode determineHostAddress(final ModelControllerClient client) throws IOException, OperationExecutionException {\n final ModelNode op = Operations.createReadAttributeOperation(EMPTY_ADDRESS, \"local-host-name\");\n ModelNode response = client.execute(op);\n if (Operations.isSuccessfulOutcome(response)) {\n return DeploymentOperations.createAddress(\"host\", Operations.readResult(response).asString());\n }\n throw new OperationExecutionException(op, response);\n }", "protected byte[] readByteArray(InputStream is, int size) throws IOException\n {\n byte[] buffer = new byte[size];\n if (is.read(buffer) != buffer.length)\n {\n throw new EOFException();\n }\n return (buffer);\n }", "public RemoteMongoCollection<Document> getCollection(final String collectionName) {\n return new RemoteMongoCollectionImpl<>(proxy.getCollection(collectionName), dispatcher);\n }", "public static void showChannels(Object... channels){\r\n // TODO this could share more code with the other show/hide(Only)Channels methods\r\n for(LogRecordHandler handler : handlers){\r\n if(handler instanceof VisibilityHandler){\r\n VisibilityHandler visHandler = (VisibilityHandler) handler;\r\n for (Object channel : channels) {\r\n visHandler.alsoShow(channel);\r\n }\r\n }\r\n }\r\n }", "public static base_response delete(nitro_service client, String selectorname) throws Exception {\n\t\tcacheselector deleteresource = new cacheselector();\n\t\tdeleteresource.selectorname = selectorname;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "protected boolean hasContentType() {\n\n boolean result = false;\n if(this.request.getHeader(RestMessageHeaders.CONTENT_TYPE) != null) {\n result = true;\n } else {\n logger.error(\"Error when validating put request. Missing Content-Type header.\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Missing Content-Type header\");\n }\n return result;\n }" ]
Called recursively to renumber child task IDs. @param parentTask parent task instance @param currentID current task ID @return updated current task ID
[ "private int synchroizeTaskIDToHierarchy(Task parentTask, int currentID)\n {\n for (Task task : parentTask.getChildTasks())\n {\n task.setID(Integer.valueOf(currentID++));\n add(task);\n currentID = synchroizeTaskIDToHierarchy(task, currentID);\n }\n return currentID;\n }" ]
[ "private Options getOptions() {\n\t\tOptions options = new Options();\n\t\toptions.addOption(\"h\", HELP, false, \"print this message\");\n\t\toptions.addOption(VERSION, false, \"print the version information and exit\");\n\n\t\toptions.addOption(\"b\", BROWSER, true,\n\t\t \"browser type: \" + availableBrowsers() + \". Default is Firefox\");\n\n\t\toptions.addOption(BROWSER_REMOTE_URL, true,\n\t\t \"The remote url if you have configured a remote browser\");\n\n\t\toptions.addOption(\"d\", DEPTH, true, \"crawl depth level. Default is 2\");\n\n\t\toptions.addOption(\"s\", MAXSTATES, true,\n\t\t \"max number of states to crawl. Default is 0 (unlimited)\");\n\n\t\toptions.addOption(\"p\", PARALLEL, true,\n\t\t \"Number of browsers to use for crawling. Default is 1\");\n\t\toptions.addOption(\"o\", OVERRIDE, false, \"Override the output directory if non-empty\");\n\n\t\toptions.addOption(\"a\", CRAWL_HIDDEN_ANCHORS, false,\n\t\t \"Crawl anchors even if they are not visible in the browser.\");\n\n\t\toptions.addOption(\"t\", TIME_OUT, true,\n\t\t \"Specify the maximum crawl time in minutes\");\n\n\t\toptions.addOption(CLICK, true,\n\t\t \"a comma separated list of HTML tags that should be clicked. Default is A and BUTTON\");\n\n\t\toptions.addOption(WAIT_AFTER_EVENT, true,\n\t\t \"the time to wait after an event has been fired in milliseconds. Default is \"\n\t\t + CrawlRules.DEFAULT_WAIT_AFTER_EVENT);\n\n\t\toptions.addOption(WAIT_AFTER_RELOAD, true,\n\t\t \"the time to wait after an URL has been loaded in milliseconds. Default is \"\n\t\t + CrawlRules.DEFAULT_WAIT_AFTER_RELOAD);\n\n\t\toptions.addOption(\"v\", VERBOSE, false, \"Be extra verbose\");\n\t\toptions.addOption(LOG_FILE, true, \"Log to this file instead of the console\");\n\n\t\treturn options;\n\t}", "public Metadata replace(String path, String value) {\n this.values.set(this.pathToProperty(path), value);\n this.addOp(\"replace\", path, value);\n return this;\n }", "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 static Boolean assertFalse(Boolean value, String message) {\n if (Boolean.valueOf(value))\n throw new IllegalArgumentException(message);\n return value;\n }", "public Integer getInteger(String fieldName) {\n\t\ttry {\n\t\t\treturn hasValue(fieldName) ? Integer.valueOf(String.valueOf(resultMap.get(fieldName))) : null;\n\t\t} catch (NumberFormatException e) {\n\t\t\tthrow new FqlException(\"Field '\" + fieldName +\"' is not a number.\", e);\n\t\t}\n\t}", "public static base_responses update(nitro_service client, sslcertkey resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslcertkey updateresources[] = new sslcertkey[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new sslcertkey();\n\t\t\t\tupdateresources[i].certkey = resources[i].certkey;\n\t\t\t\tupdateresources[i].expirymonitor = resources[i].expirymonitor;\n\t\t\t\tupdateresources[i].notificationperiod = resources[i].notificationperiod;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "private void initPixelsArray(BufferedImage image) {\n int width = image.getWidth();\n int height = image.getHeight();\n pixels = new int[width * height];\n image.getRGB(0, 0, width, height, pixels, 0, width);\n\n }", "protected void removeInvalidChildren() {\n\n if (getLoadState() == LoadState.LOADED) {\n List<CmsSitemapTreeItem> toDelete = new ArrayList<CmsSitemapTreeItem>();\n for (int i = 0; i < getChildCount(); i++) {\n CmsSitemapTreeItem item = (CmsSitemapTreeItem)getChild(i);\n CmsUUID id = item.getEntryId();\n if ((id != null) && (CmsSitemapView.getInstance().getController().getEntryById(id) == null)) {\n toDelete.add(item);\n }\n }\n for (CmsSitemapTreeItem deleteItem : toDelete) {\n m_children.removeItem(deleteItem);\n }\n }\n }", "public static ProtocolConnectionManager create(final Connection connection, final ConnectionOpenHandler openHandler) {\n return create(new EstablishedConnection(connection, openHandler));\n }" ]
Retrieves the index of a cost rate table entry active on a given date. @param date target date @return cost rate table entry index
[ "private int getCostRateTableEntryIndex(Date date)\n {\n int result = -1;\n\n CostRateTable table = getCostRateTable();\n if (table != null)\n {\n if (table.size() == 1)\n {\n result = 0;\n }\n else\n {\n result = table.getIndexByDate(date);\n }\n }\n\n return result;\n }" ]
[ "public static File copyResourceToLocalFile(String sourceResource, String destFileName) throws Exception {\n try {\n Resource keystoreFile = new ClassPathResource(sourceResource);\n InputStream in = keystoreFile.getInputStream();\n\n File outKeyStoreFile = new File(destFileName);\n FileOutputStream fop = new FileOutputStream(outKeyStoreFile);\n byte[] buf = new byte[512];\n int num;\n while ((num = in.read(buf)) != -1) {\n fop.write(buf, 0, num);\n }\n fop.flush();\n fop.close();\n in.close();\n return outKeyStoreFile;\n } catch (IOException ioe) {\n throw new Exception(\"Could not copy keystore file: \" + ioe.getMessage());\n }\n }", "protected void processOutlineCodeField(Integer entityID, Row row)\n {\n processField(row, \"OC_FIELD_ID\", entityID, row.getString(\"OC_NAME\"));\n }", "public float getMetallic()\n {\n Property p = getProperty(PropertyKey.METALLIC.m_key);\n\n if (null == p || null == p.getData())\n {\n throw new IllegalArgumentException(\"Metallic property not found\");\n }\n Object rawValue = p.getData();\n if (rawValue instanceof java.nio.ByteBuffer)\n {\n java.nio.FloatBuffer fbuf = ((java.nio.ByteBuffer) rawValue).asFloatBuffer();\n return fbuf.get();\n }\n else\n {\n return (Float) rawValue;\n }\n }", "public ParallelTaskBuilder setReplacementVarMapNodeSpecific(\n Map<String, StrStrMap> replacementVarMapNodeSpecific) {\n this.replacementVarMapNodeSpecific.clear();\n this.replacementVarMapNodeSpecific\n .putAll(replacementVarMapNodeSpecific);\n\n this.requestReplacementType = RequestReplacementType.TARGET_HOST_SPECIFIC_VAR_REPLACEMENT;\n logger.info(\"Set requestReplacementType as {}\"\n + requestReplacementType.toString());\n return this;\n }", "public void bind(T service, Map<String, Object> props) {\n synchronized (serviceMap) {\n serviceMap.put(ServiceUtil.getComparableForServiceRanking(props), service);\n updateSortedServices();\n }\n }", "public static Boolean askConfirm(Boolean confirm, String opDesc) throws IOException {\n if(confirm) {\n System.out.println(\"Confirmed \" + opDesc + \" in command-line.\");\n return true;\n } else {\n System.out.println(\"Are you sure you want to \" + opDesc + \"? (yes/no)\");\n BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));\n String text = buffer.readLine().toLowerCase(Locale.ENGLISH);\n boolean go = text.equals(\"yes\") || text.equals(\"y\");\n if (!go) {\n System.out.println(\"Did not confirm; \" + opDesc + \" aborted.\");\n }\n return go;\n }\n }", "public static void assertValidMetadata(ByteArray key,\n RoutingStrategy routingStrategy,\n Node currentNode) {\n List<Node> nodes = routingStrategy.routeRequest(key.get());\n for(Node node: nodes) {\n if(node.getId() == currentNode.getId()) {\n return;\n }\n }\n\n throw new InvalidMetadataException(\"Client accessing key belonging to partitions \"\n + routingStrategy.getPartitionList(key.get())\n + \" not present at \" + currentNode);\n }", "public String stripUnnecessaryComments(String javaContent, AntlrOptions options) {\n\t\tif (!options.isOptimizeCodeQuality()) {\n\t\t\treturn javaContent;\n\t\t}\n\t\tjavaContent = stripMachineDependentPaths(javaContent);\n\t\tif (options.isStripAllComments()) {\n\t\t\tjavaContent = stripAllComments(javaContent);\n\t\t}\n\t\treturn javaContent;\n\t}", "private void populateBar(Row row, Task task)\n {\n Integer calendarID = row.getInteger(\"CALENDAU\");\n ProjectCalendar calendar = m_project.getCalendarByUniqueID(calendarID);\n\n //PROJID\n task.setUniqueID(row.getInteger(\"BARID\"));\n task.setStart(row.getDate(\"STARV\"));\n task.setFinish(row.getDate(\"ENF\"));\n //NATURAL_ORDER\n //SPARI_INTEGER\n task.setName(row.getString(\"NAMH\"));\n //EXPANDED_TASK\n //PRIORITY\n //UNSCHEDULABLE\n //MARK_FOR_HIDING\n //TASKS_MAY_OVERLAP\n //SUBPROJECT_ID\n //ALT_ID\n //LAST_EDITED_DATE\n //LAST_EDITED_BY\n //Proc_Approve\n //Proc_Design_info\n //Proc_Proc_Dur\n //Proc_Procurement\n //Proc_SC_design\n //Proc_Select_SC\n //Proc_Tender\n //QA Checked\n //Related_Documents\n task.setCalendar(calendar);\n }" ]
Set the inner angle of the spotlight cone in degrees. Beyond the outer cone angle there is no illumination. The underlying uniform "outer_cone_angle" is the cosine of this input angle. If the inner cone angle is larger than the outer cone angle there will be unexpected results. @see #setInnerConeAngle(float) @see #getOuterConeAngle()
[ "public void setOuterConeAngle(float angle)\n {\n setFloat(\"outer_cone_angle\", (float) Math.cos(Math.toRadians(angle)));\n mChanged.set(true);\n }" ]
[ "public void createLinks(ServiceReference<S> declarationBinderRef) {\n for (D declaration : linkerManagement.getMatchedDeclaration()) {\n if (linkerManagement.canBeLinked(declaration, declarationBinderRef)) {\n linkerManagement.link(declaration, declarationBinderRef);\n }\n }\n }", "protected void setRandom(double lower, double upper, Random generator) {\n double range = upper - lower;\n\n x = generator.nextDouble() * range + lower;\n y = generator.nextDouble() * range + lower;\n z = generator.nextDouble() * range + lower;\n }", "public Collection<DataSource> getDataSources(int groupno) {\n if (groupno == 1)\n return group1;\n else if (groupno == 2)\n return group2;\n else\n throw new DukeConfigException(\"Invalid group number: \" + groupno);\n }", "public ItemRequest<Section> delete(String section) {\n \n String path = String.format(\"/sections/%s\", section);\n return new ItemRequest<Section>(this, Section.class, path, \"DELETE\");\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}", "public static sslocspresponder[] get(nitro_service service) throws Exception{\n\t\tsslocspresponder obj = new sslocspresponder();\n\t\tsslocspresponder[] response = (sslocspresponder[])obj.get_resources(service);\n\t\treturn response;\n\t}", "private PersistenceBrokerException createException(final Exception ex, String message, final Object objectToIdentify, Class topLevelClass, Class realClass, Object[] pks)\r\n {\r\n final String eol = SystemUtils.LINE_SEPARATOR;\r\n StringBuffer msg = new StringBuffer();\r\n if(message == null)\r\n {\r\n msg.append(\"Unexpected error: \");\r\n }\r\n else\r\n {\r\n msg.append(message).append(\" :\");\r\n }\r\n if(topLevelClass != null) msg.append(eol).append(\"objectTopLevelClass=\").append(topLevelClass.getName());\r\n if(realClass != null) msg.append(eol).append(\"objectRealClass=\").append(realClass.getName());\r\n if(pks != null) msg.append(eol).append(\"pkValues=\").append(ArrayUtils.toString(pks));\r\n if(objectToIdentify != null) msg.append(eol).append(\"object to identify: \").append(objectToIdentify);\r\n if(ex != null)\r\n {\r\n // add causing stack trace\r\n Throwable rootCause = ExceptionUtils.getRootCause(ex);\r\n if(rootCause != null)\r\n {\r\n msg.append(eol).append(\"The root stack trace is --> \");\r\n String rootStack = ExceptionUtils.getStackTrace(rootCause);\r\n msg.append(eol).append(rootStack);\r\n }\r\n\r\n return new PersistenceBrokerException(msg.toString(), ex);\r\n }\r\n else\r\n {\r\n return new PersistenceBrokerException(msg.toString());\r\n }\r\n }", "private void recurseAndAddFiles(GraphRewrite event, EvaluationContext context,\n Path tempFolder,\n FileService fileService, ArchiveModel archiveModel,\n FileModel parentFileModel, boolean subArchivesOnly)\n {\n checkCancelled(event);\n\n int numberAdded = 0;\n\n FileFilter filter = TrueFileFilter.TRUE;\n if (archiveModel instanceof IdentifiedArchiveModel)\n {\n filter = new IdentifiedArchiveFileFilter(archiveModel);\n }\n\n File fileReference;\n if (parentFileModel instanceof ArchiveModel)\n fileReference = new File(((ArchiveModel) parentFileModel).getUnzippedDirectory());\n else\n fileReference = parentFileModel.asFile();\n\n WindupJavaConfigurationService windupJavaConfigurationService = new WindupJavaConfigurationService(event.getGraphContext());\n File[] subFiles = fileReference.listFiles();\n if (subFiles == null)\n return;\n\n for (File subFile : subFiles)\n {\n if (!filter.accept(subFile))\n continue;\n\n if (subArchivesOnly && !ZipUtil.endsWithZipExtension(subFile.getAbsolutePath()))\n continue;\n\n FileModel subFileModel = fileService.createByFilePath(parentFileModel, subFile.getAbsolutePath());\n\n // check if this file should be ignored\n if (windupJavaConfigurationService.checkIfIgnored(event, subFileModel))\n continue;\n\n numberAdded++;\n if (numberAdded % 250 == 0)\n event.getGraphContext().commit();\n\n if (subFile.isFile() && ZipUtil.endsWithZipExtension(subFileModel.getFilePath()))\n {\n File newZipFile = subFileModel.asFile();\n ArchiveModel newArchiveModel = GraphService.addTypeToModel(event.getGraphContext(), subFileModel, ArchiveModel.class);\n newArchiveModel.setParentArchive(archiveModel);\n newArchiveModel.setArchiveName(newZipFile.getName());\n\n /*\n * New archive must be reloaded in case the archive should be ignored\n */\n newArchiveModel = GraphService.refresh(event.getGraphContext(), newArchiveModel);\n\n ArchiveModel canonicalArchiveModel = null;\n for (FileModel otherMatches : fileService.findAllByProperty(FileModel.SHA1_HASH, newArchiveModel.getSHA1Hash()))\n {\n if (otherMatches instanceof ArchiveModel && !otherMatches.equals(newArchiveModel) && !(otherMatches instanceof DuplicateArchiveModel))\n {\n canonicalArchiveModel = (ArchiveModel)otherMatches;\n break;\n }\n }\n\n if (canonicalArchiveModel != null)\n {\n // handle as duplicate\n DuplicateArchiveModel duplicateArchive = GraphService.addTypeToModel(event.getGraphContext(), newArchiveModel, DuplicateArchiveModel.class);\n duplicateArchive.setCanonicalArchive(canonicalArchiveModel);\n\n // create dupes for child archives\n unzipToTempDirectory(event, context, tempFolder, newZipFile, duplicateArchive, true);\n } else\n {\n unzipToTempDirectory(event, context, tempFolder, newZipFile, newArchiveModel, false);\n }\n } else if (subFile.isDirectory())\n {\n recurseAndAddFiles(event, context, tempFolder, fileService, archiveModel, subFileModel, false);\n }\n }\n }", "public static void setFlag(Activity activity, final int bits, boolean on) {\n Window win = activity.getWindow();\n WindowManager.LayoutParams winParams = win.getAttributes();\n if (on) {\n winParams.flags |= bits;\n } else {\n winParams.flags &= ~bits;\n }\n win.setAttributes(winParams);\n }" ]
If the user has not specified a project ID, this method retrieves the ID of the first project in the file.
[ "private void processProjectID()\n {\n if (m_projectID == null)\n {\n List<Row> rows = getRows(\"project\", null, null);\n if (!rows.isEmpty())\n {\n Row row = rows.get(0);\n m_projectID = row.getInteger(\"proj_id\");\n }\n }\n }" ]
[ "private void checkAndAddForbiddenStrings(final List<String> forbiddenSubStrings) {\n\t\tfor( String forbidden : forbiddenSubStrings ) {\n\t\t\tif( forbidden == null ) {\n\t\t\t\tthrow new NullPointerException(\"forbidden substring should not be null\");\n\t\t\t}\n\t\t\tthis.forbiddenSubStrings.add(forbidden);\n\t\t}\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 AiScene importFile(String filename) throws IOException {\n \n return importFile(filename, EnumSet.noneOf(AiPostProcessSteps.class));\n }", "public T removeFile(final String name, final List<String> path, final byte[] existingHash, final boolean isDirectory) {\n return removeFile(name, path, existingHash, isDirectory, null);\n }", "public boolean detectTierIphone() {\r\n\r\n if (detectIphoneOrIpod()\r\n || detectAndroidPhone()\r\n || detectWindowsPhone()\r\n || detectBlackBerry10Phone()\r\n || (detectBlackBerryWebKit() && detectBlackBerryTouch())\r\n || detectPalmWebOS()\r\n || detectBada()\r\n || detectTizen()\r\n || detectFirefoxOSPhone()\r\n || detectSailfishPhone()\r\n || detectUbuntuPhone()\r\n || detectGamingHandheld()) {\r\n return true;\r\n }\r\n return false;\r\n }", "public static int cudnnReduceTensor(\n cudnnHandle handle, \n cudnnReduceTensorDescriptor reduceTensorDesc, \n Pointer indices, \n long indicesSizeInBytes, \n Pointer workspace, \n long workspaceSizeInBytes, \n Pointer alpha, \n cudnnTensorDescriptor aDesc, \n Pointer A, \n Pointer beta, \n cudnnTensorDescriptor cDesc, \n Pointer C)\n {\n return checkResult(cudnnReduceTensorNative(handle, reduceTensorDesc, indices, indicesSizeInBytes, workspace, workspaceSizeInBytes, alpha, aDesc, A, beta, cDesc, C));\n }", "@Override\n\tpublic void clear() {\n\t\tif (dao == null) {\n\t\t\treturn;\n\t\t}\n\t\tCloseableIterator<T> iterator = closeableIterator();\n\t\ttry {\n\t\t\twhile (iterator.hasNext()) {\n\t\t\t\titerator.next();\n\t\t\t\titerator.remove();\n\t\t\t}\n\t\t} finally {\n\t\t\tIOUtils.closeQuietly(iterator);\n\t\t}\n\t}", "private boolean isWorkingDay(ProjectCalendar mpxjCalendar, Day day)\n {\n boolean result = false;\n net.sf.mpxj.DayType type = mpxjCalendar.getWorkingDay(day);\n if (type == null)\n {\n type = net.sf.mpxj.DayType.DEFAULT;\n }\n\n switch (type)\n {\n case WORKING:\n {\n result = true;\n break;\n }\n\n case NON_WORKING:\n {\n result = false;\n break;\n }\n\n case DEFAULT:\n {\n if (mpxjCalendar.getParent() == null)\n {\n result = false;\n }\n else\n {\n result = isWorkingDay(mpxjCalendar.getParent(), day);\n }\n break;\n }\n }\n\n return (result);\n }", "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 }" ]
judge if an point in the area or not @param point @param area @param offsetRatio @return
[ "public static boolean inArea(Point point, Rect area, float offsetRatio) {\n int offset = (int) (area.width() * offsetRatio);\n return point.x >= area.left - offset && point.x <= area.right + offset &&\n point.y >= area.top - offset && point.y <= area.bottom + offset;\n }" ]
[ "public List<TableProperty> getEditableColumns(CmsMessageBundleEditorTypes.EditMode mode) {\n\n return m_editorState.get(mode).getEditableColumns();\n }", "public void clearHistory(int profileId, String clientUUID) {\n PreparedStatement query = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n String sqlQuery = \"DELETE FROM \" + Constants.DB_TABLE_HISTORY + \" \";\n\n // see if profileId is null or not (-1)\n if (profileId != -1) {\n sqlQuery += \"WHERE \" + Constants.GENERIC_PROFILE_ID + \"=\" + profileId;\n }\n\n // see if clientUUID is null or not\n if (clientUUID != null && clientUUID.compareTo(\"\") != 0) {\n sqlQuery += \" AND \" + Constants.GENERIC_CLIENT_UUID + \"='\" + clientUUID + \"'\";\n }\n\n sqlQuery += \";\";\n\n logger.info(\"Query: {}\", sqlQuery);\n query = sqlConnection.prepareStatement(sqlQuery);\n query.executeUpdate();\n } catch (Exception e) {\n } finally {\n try {\n if (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n }", "public void setInvalidValues(final Set<String> invalidValues,\n final boolean isCaseSensitive,\n final String invalidValueErrorMessage) {\n if (isCaseSensitive) {\n this.invalidValues = invalidValues;\n } else {\n this.invalidValues = new HashSet<String>();\n for (String value : invalidValues) {\n this.invalidValues.add(value.toLowerCase());\n }\n }\n this.isCaseSensitive = isCaseSensitive;\n this.invalidValueErrorMessage = invalidValueErrorMessage;\n }", "static BsonDocument getVersionedFilter(\n @Nonnull final BsonValue documentId,\n @Nullable final BsonValue version\n ) {\n final BsonDocument filter = new BsonDocument(\"_id\", documentId);\n if (version == null) {\n filter.put(DOCUMENT_VERSION_FIELD, new BsonDocument(\"$exists\", BsonBoolean.FALSE));\n } else {\n filter.put(DOCUMENT_VERSION_FIELD, version);\n }\n return filter;\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 }", "private SearchableItem buildSearchableItem(Message menuItem) {\n return new SearchableItem((int) ((NumberField) menuItem.arguments.get(1)).getValue(),\n ((StringField) menuItem.arguments.get(3)).getValue());\n }", "public static void doBatchEnqueue(final Jedis jedis, final String namespace, final String queue, final List<String> jobJsons) {\n Pipeline pipelined = jedis.pipelined();\n pipelined.sadd(JesqueUtils.createKey(namespace, QUEUES), queue);\n for (String jobJson : jobJsons) {\n pipelined.rpush(JesqueUtils.createKey(namespace, QUEUE, queue), jobJson);\n }\n pipelined.sync();\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 mergeSameCost(LinkedList<TimephasedCost> list)\n {\n LinkedList<TimephasedCost> result = new LinkedList<TimephasedCost>();\n\n TimephasedCost previousAssignment = null;\n for (TimephasedCost assignment : list)\n {\n if (previousAssignment == null)\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n result.add(assignment);\n }\n else\n {\n Number previousAssignmentCost = previousAssignment.getAmountPerDay();\n Number assignmentCost = assignment.getTotalAmount();\n\n if (NumberHelper.equals(previousAssignmentCost.doubleValue(), assignmentCost.doubleValue(), 0.01))\n {\n Date assignmentStart = previousAssignment.getStart();\n Date assignmentFinish = assignment.getFinish();\n double total = previousAssignment.getTotalAmount().doubleValue();\n total += assignmentCost.doubleValue();\n\n TimephasedCost merged = new TimephasedCost();\n merged.setStart(assignmentStart);\n merged.setFinish(assignmentFinish);\n merged.setAmountPerDay(assignmentCost);\n merged.setTotalAmount(Double.valueOf(total));\n\n result.removeLast();\n assignment = merged;\n }\n else\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n }\n result.add(assignment);\n }\n\n previousAssignment = assignment;\n }\n\n list.clear();\n list.addAll(result);\n }" ]
2-D Integer array to double array. @param array Integer array. @return Double array.
[ "public static double[][] toDouble(int[][] array) {\n double[][] n = new double[array.length][array[0].length];\n for (int i = 0; i < array.length; i++) {\n for (int j = 0; j < array[0].length; j++) {\n n[i][j] = (double) array[i][j];\n }\n }\n return n;\n }" ]
[ "public Number getCostVariance()\n {\n Number variance = (Number) getCachedValue(TaskField.COST_VARIANCE);\n if (variance == null)\n {\n Number cost = getCost();\n Number baselineCost = getBaselineCost();\n if (cost != null && baselineCost != null)\n {\n variance = NumberHelper.getDouble(cost.doubleValue() - baselineCost.doubleValue());\n set(TaskField.COST_VARIANCE, variance);\n }\n }\n return (variance);\n }", "private void createStringMappings(MtasTokenIdFactory mtasTokenIdFactory,\n Level level, String stringValue, int offsetStart, int offsetEnd,\n int position) throws IOException {\n // System.out.println(\"createStringMappings string \");\n String[] stringValues = MtasPennTreebankReader.createStrings(stringValue,\n Pattern.quote(STRING_SPLITTER));\n if (stringValues.length > 0 && !stringValues[0].trim().isEmpty()) {\n MtasToken token = new MtasTokenString(mtasTokenIdFactory.createTokenId(),\n \"t\", filterString(stringValues[0].trim()), position);\n token.setOffset(offsetStart, offsetEnd);\n tokenCollection.add(token);\n level.tokens.add(token);\n }\n if (stringValues.length > 1 && !stringValues[1].trim().isEmpty()) {\n MtasToken token = new MtasTokenString(mtasTokenIdFactory.createTokenId(),\n \"lemma\", filterString(stringValues[1].trim()), position);\n token.setOffset(offsetStart, offsetEnd);\n tokenCollection.add(token);\n level.tokens.add(token);\n }\n }", "private ModelNode resolveExpressionStringRecursively(final String expressionString, final boolean ignoreDMRResolutionFailure,\n final boolean initial) throws OperationFailedException {\n ParseAndResolveResult resolved = parseAndResolve(expressionString, ignoreDMRResolutionFailure);\n if (resolved.recursive) {\n // Some part of expressionString resolved into a different expression.\n // So, start over, ignoring failures. Ignore failures because we don't require\n // that expressions must not resolve to something that *looks like* an expression but isn't\n return resolveExpressionStringRecursively(resolved.result, true, false);\n } else if (resolved.modified) {\n // Typical case\n return new ModelNode(resolved.result);\n } else if (initial && EXPRESSION_PATTERN.matcher(expressionString).matches()) {\n // We should only get an unmodified expression string back if there was a resolution\n // failure that we ignored.\n assert ignoreDMRResolutionFailure;\n // expressionString came from a node of type expression, so since we did nothing send it back in the same type\n return new ModelNode(new ValueExpression(expressionString));\n } else {\n // The string wasn't really an expression. Two possible cases:\n // 1) if initial == true, someone created a expression node with a non-expression string, which is legal\n // 2) if initial == false, we resolved from an ModelType.EXPRESSION to a string that looked like an\n // expression but can't be resolved. We don't require that expressions must not resolve to something that\n // *looks like* an expression but isn't, so we'll just treat this as a string\n return new ModelNode(expressionString);\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 }", "private void solveInternalL() {\n // This takes advantage of the diagonal elements always being real numbers\n\n // solve L*y=b storing y in x\n TriangularSolver_ZDRM.solveL_diagReal(t, vv, n);\n\n // solve L^T*x=y\n TriangularSolver_ZDRM.solveConjTranL_diagReal(t, vv, n);\n }", "public void removeChildTask(Task child)\n {\n if (m_children.remove(child))\n {\n child.m_parent = null;\n }\n setSummary(!m_children.isEmpty());\n }", "public static final BigInteger printDay(Day day)\n {\n return (day == null ? null : BigInteger.valueOf(day.getValue() - 1));\n }", "public static <T> NewSessionBean<T> of(BeanAttributes<T> attributes, InternalEjbDescriptor<T> ejbDescriptor, BeanManagerImpl beanManager) {\n EnhancedAnnotatedType<T> type = beanManager.getServices().get(ClassTransformer.class).getEnhancedAnnotatedType(ejbDescriptor.getBeanClass(), beanManager.getId());\n return new NewSessionBean<T>(attributes, type, ejbDescriptor, new StringBeanIdentifier(SessionBeans.createIdentifierForNew(ejbDescriptor)), beanManager);\n }", "private static boolean containsObject(Object searchFor, Object[] searchIn)\r\n {\r\n for (int i = 0; i < searchIn.length; i++)\r\n {\r\n if (searchFor == searchIn[i])\r\n {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }" ]
build an Authentication. Types: <ul> <li>plain:jafka</li> <li>md5:77be29f6d71ec4e310766ddf881ae6a0</li> <li>crc32:1725717671</li> </ul> @param crypt password style @return an authentication @throws IllegalArgumentException password error
[ "public static Authentication build(String crypt) throws IllegalArgumentException {\n if(crypt == null) {\n return new PlainAuth(null);\n }\n String[] value = crypt.split(\":\");\n \n if(value.length == 2 ) {\n String type = value[0].trim();\n String password = value[1].trim();\n if(password!=null&&password.length()>0) {\n if(\"plain\".equals(type)) {\n return new PlainAuth(password);\n }\n if(\"md5\".equals(type)) {\n return new Md5Auth(password);\n }\n if(\"crc32\".equals(type)) {\n return new Crc32Auth(Long.parseLong(password));\n }\n }\n }\n throw new IllegalArgumentException(\"error password: \"+crypt);\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 List<T> parseList(JsonParser jsonParser) throws IOException {\n List<T> list = new ArrayList<>();\n if (jsonParser.getCurrentToken() == JsonToken.START_ARRAY) {\n while (jsonParser.nextToken() != JsonToken.END_ARRAY) {\n list.add(parse(jsonParser));\n }\n }\n return list;\n }", "public static base_response add(nitro_service client, responderpolicy resource) throws Exception {\n\t\tresponderpolicy addresource = new responderpolicy();\n\t\taddresource.name = resource.name;\n\t\taddresource.rule = resource.rule;\n\t\taddresource.action = resource.action;\n\t\taddresource.undefaction = resource.undefaction;\n\t\taddresource.comment = resource.comment;\n\t\taddresource.logaction = resource.logaction;\n\t\taddresource.appflowaction = resource.appflowaction;\n\t\treturn addresource.add_resource(client);\n\t}", "public static TxInfo getTransactionInfo(Environment env, Bytes prow, Column pcol, long startTs) {\n // TODO ensure primary is visible\n\n IteratorSetting is = new IteratorSetting(10, RollbackCheckIterator.class);\n RollbackCheckIterator.setLocktime(is, startTs);\n\n Entry<Key, Value> entry = ColumnUtil.checkColumn(env, is, prow, pcol);\n\n TxInfo txInfo = new TxInfo();\n\n if (entry == null) {\n txInfo.status = TxStatus.UNKNOWN;\n return txInfo;\n }\n\n ColumnType colType = ColumnType.from(entry.getKey());\n long ts = entry.getKey().getTimestamp() & ColumnConstants.TIMESTAMP_MASK;\n\n switch (colType) {\n case LOCK: {\n if (ts == startTs) {\n txInfo.status = TxStatus.LOCKED;\n txInfo.lockValue = entry.getValue().get();\n } else {\n txInfo.status = TxStatus.UNKNOWN; // locked by another tx\n }\n break;\n }\n case DEL_LOCK: {\n DelLockValue dlv = new DelLockValue(entry.getValue().get());\n\n if (ts != startTs) {\n // expect this to always be false, must be a bug in the iterator\n throw new IllegalStateException(prow + \" \" + pcol + \" (\" + ts + \" != \" + startTs + \") \");\n }\n\n if (dlv.isRollback()) {\n txInfo.status = TxStatus.ROLLED_BACK;\n } else {\n txInfo.status = TxStatus.COMMITTED;\n txInfo.commitTs = dlv.getCommitTimestamp();\n }\n break;\n }\n case WRITE: {\n long timePtr = WriteValue.getTimestamp(entry.getValue().get());\n\n if (timePtr != startTs) {\n // expect this to always be false, must be a bug in the iterator\n throw new IllegalStateException(\n prow + \" \" + pcol + \" (\" + timePtr + \" != \" + startTs + \") \");\n }\n\n txInfo.status = TxStatus.COMMITTED;\n txInfo.commitTs = ts;\n break;\n }\n default:\n throw new IllegalStateException(\"unexpected col type returned \" + colType);\n }\n\n return txInfo;\n }", "public static base_responses update(nitro_service client, nsacl6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsacl6 updateresources[] = new nsacl6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nsacl6();\n\t\t\t\tupdateresources[i].acl6name = resources[i].acl6name;\n\t\t\t\tupdateresources[i].aclaction = resources[i].aclaction;\n\t\t\t\tupdateresources[i].srcipv6 = resources[i].srcipv6;\n\t\t\t\tupdateresources[i].srcipop = resources[i].srcipop;\n\t\t\t\tupdateresources[i].srcipv6val = resources[i].srcipv6val;\n\t\t\t\tupdateresources[i].srcport = resources[i].srcport;\n\t\t\t\tupdateresources[i].srcportop = resources[i].srcportop;\n\t\t\t\tupdateresources[i].srcportval = resources[i].srcportval;\n\t\t\t\tupdateresources[i].destipv6 = resources[i].destipv6;\n\t\t\t\tupdateresources[i].destipop = resources[i].destipop;\n\t\t\t\tupdateresources[i].destipv6val = resources[i].destipv6val;\n\t\t\t\tupdateresources[i].destport = resources[i].destport;\n\t\t\t\tupdateresources[i].destportop = resources[i].destportop;\n\t\t\t\tupdateresources[i].destportval = resources[i].destportval;\n\t\t\t\tupdateresources[i].srcmac = resources[i].srcmac;\n\t\t\t\tupdateresources[i].protocol = resources[i].protocol;\n\t\t\t\tupdateresources[i].protocolnumber = resources[i].protocolnumber;\n\t\t\t\tupdateresources[i].icmptype = resources[i].icmptype;\n\t\t\t\tupdateresources[i].icmpcode = resources[i].icmpcode;\n\t\t\t\tupdateresources[i].vlan = resources[i].vlan;\n\t\t\t\tupdateresources[i].Interface = resources[i].Interface;\n\t\t\t\tupdateresources[i].priority = resources[i].priority;\n\t\t\t\tupdateresources[i].established = resources[i].established;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "protected boolean isPrefixBlock(long divisionValue, long upperValue, int divisionPrefixLen) {\n\t\tif(divisionPrefixLen == 0) {\n\t\t\treturn divisionValue == 0 && upperValue == getMaxValue();\n\t\t}\n\t\tlong ones = ~0L;\n\t\tlong divisionBitMask = ~(ones << getBitCount());\n\t\tlong divisionPrefixMask = ones << (getBitCount() - divisionPrefixLen);\n\t\tlong divisionNonPrefixMask = ~divisionPrefixMask;\n\t\treturn testRange(divisionValue,\n\t\t\t\tupperValue,\n\t\t\t\tupperValue,\n\t\t\t\tdivisionPrefixMask & divisionBitMask,\n\t\t\t\tdivisionNonPrefixMask);\n\t}", "public Stamp allocateTimestamp() {\n\n synchronized (this) {\n Preconditions.checkState(!closed, \"tracker closed \");\n\n if (node == null) {\n Preconditions.checkState(allocationsInProgress == 0,\n \"expected allocationsInProgress == 0 when node == null\");\n Preconditions.checkState(!updatingZk, \"unexpected concurrent ZK update\");\n\n createZkNode(getTimestamp().getTxTimestamp());\n }\n\n allocationsInProgress++;\n }\n\n try {\n Stamp ts = getTimestamp();\n\n synchronized (this) {\n timestamps.add(ts.getTxTimestamp());\n }\n\n return ts;\n } catch (RuntimeException re) {\n synchronized (this) {\n allocationsInProgress--;\n }\n throw re;\n }\n }", "public 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 }", "private static void listHierarchy(ProjectFile file)\n {\n for (Task task : file.getChildTasks())\n {\n System.out.println(\"Task: \" + task.getName() + \"\\t\" + task.getStart() + \"\\t\" + task.getFinish());\n listHierarchy(task, \" \");\n }\n\n System.out.println();\n }" ]
Write the domain controller's data to an output stream. @param outstream the output stream @throws Exception
[ "public void writeTo(DataOutput outstream) throws Exception {\n S3Util.writeString(host, outstream);\n outstream.writeInt(port);\n S3Util.writeString(protocol, outstream);\n }" ]
[ "public static Object instantiate(Constructor constructor) throws InstantiationException\r\n {\r\n if(constructor == null)\r\n {\r\n throw new ClassNotPersistenceCapableException(\r\n \"A zero argument constructor was not provided!\");\r\n }\r\n\r\n Object result = null;\r\n try\r\n {\r\n result = constructor.newInstance(NO_ARGS);\r\n }\r\n catch(InstantiationException e)\r\n {\r\n throw e;\r\n }\r\n catch(Exception e)\r\n {\r\n throw new ClassNotPersistenceCapableException(\"Can't instantiate class '\"\r\n + (constructor != null ? constructor.getDeclaringClass().getName() : \"null\")\r\n + \"' with given constructor: \" + e.getMessage(), e);\r\n }\r\n return result;\r\n }", "@Override\n public final long optLong(final String key, final long defaultValue) {\n Long result = optLong(key);\n return result == null ? defaultValue : result;\n }", "public static base_responses delete(nitro_service client, String ciphergroupname[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (ciphergroupname != null && ciphergroupname.length > 0) {\n\t\t\tsslcipher deleteresources[] = new sslcipher[ciphergroupname.length];\n\t\t\tfor (int i=0;i<ciphergroupname.length;i++){\n\t\t\t\tdeleteresources[i] = new sslcipher();\n\t\t\t\tdeleteresources[i].ciphergroupname = ciphergroupname[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "protected void processAliases(List<MonolingualTextValue> addAliases, List<MonolingualTextValue> deleteAliases) {\n for(MonolingualTextValue val : addAliases) {\n addAlias(val);\n }\n for(MonolingualTextValue val : deleteAliases) {\n deleteAlias(val);\n }\n }", "private int findIndexForName(String[] fieldNames, String searchName)\r\n {\r\n for(int i = 0; i < fieldNames.length; i++)\r\n {\r\n if(searchName.equals(fieldNames[i]))\r\n {\r\n return i;\r\n }\r\n }\r\n throw new PersistenceBrokerException(\"Can't find field name '\" + searchName +\r\n \"' in given array of field names\");\r\n }", "public static Observable<Void> mapToVoid(Observable<?> fromObservable) {\n if (fromObservable != null) {\n return fromObservable.subscribeOn(Schedulers.io())\n .map(new RXMapper<Void>());\n } else {\n return Observable.empty();\n }\n }", "public boolean getOverAllocated()\n {\n Boolean overallocated = (Boolean) getCachedValue(ResourceField.OVERALLOCATED);\n if (overallocated == null)\n {\n Number peakUnits = getPeakUnits();\n Number maxUnits = getMaxUnits();\n overallocated = Boolean.valueOf(NumberHelper.getDouble(peakUnits) > NumberHelper.getDouble(maxUnits));\n set(ResourceField.OVERALLOCATED, overallocated);\n }\n return (overallocated.booleanValue());\n }", "public AT_Context setFrameLeftRightMargin(int frameLeft, int frameRight){\r\n\t\tif(frameRight>-1 && frameLeft>-1){\r\n\t\t\tthis.frameLeftMargin = frameLeft;\r\n\t\t\tthis.frameRightMargin = frameRight;\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "private void removeObsoleteElements(List<String> names,\n Map<String, View> sharedElements,\n List<String> elementsToRemove) {\n if (elementsToRemove.size() > 0) {\n names.removeAll(elementsToRemove);\n for (String elementToRemove : elementsToRemove) {\n sharedElements.remove(elementToRemove);\n }\n }\n }" ]
multi-field string
[ "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 Organization unserializeOrganization(final String organization) throws IOException {\n final ObjectMapper mapper = new ObjectMapper();\n mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);\n return mapper.readValue(organization, Organization.class);\n }", "public static MarvinImage rgbToBinary(MarvinImage img, int threshold) {\n MarvinImage resultImage = new MarvinImage(img.getWidth(), img.getHeight(), MarvinImage.COLOR_MODEL_BINARY);\n\n for (int y = 0; y < img.getHeight(); y++) {\n for (int x = 0; x < img.getWidth(); x++) {\n int gray = (int) ((img.getIntComponent0(x, y) * 0.3) + (img.getIntComponent1(x, y) * 0.59) + (img.getIntComponent2(x, y) * 0.11));\n\n if (gray <= threshold) {\n resultImage.setBinaryColor(x, y, true);\n } else {\n resultImage.setBinaryColor(x, y, false);\n }\n }\n }\n return resultImage;\n }", "public void setEnable(boolean flag)\n {\n if (mEnabled == flag)\n {\n return;\n }\n mEnabled = flag;\n if (flag)\n {\n mContext.registerDrawFrameListener(this);\n mContext.getApplication().getEventReceiver().addListener(this);\n mAudioEngine.resume();\n }\n else\n {\n mContext.unregisterDrawFrameListener(this);\n mContext.getApplication().getEventReceiver().removeListener(this);\n mAudioEngine.pause();\n }\n }", "public TFuture<JsonResponse<AdvertiseResponse>> advertise() {\n\n final AdvertiseRequest advertiseRequest = new AdvertiseRequest();\n advertiseRequest.addService(service, 0);\n\n // TODO: options for hard fail, retries etc.\n final JsonRequest<AdvertiseRequest> request = new JsonRequest.Builder<AdvertiseRequest>(\n HYPERBAHN_SERVICE_NAME,\n HYPERBAHN_ADVERTISE_ENDPOINT\n )\n .setBody(advertiseRequest)\n .setTimeout(REQUEST_TIMEOUT)\n .setRetryLimit(4)\n .build();\n\n final TFuture<JsonResponse<AdvertiseResponse>> future = hyperbahnChannel.send(request);\n future.addCallback(new TFutureCallback<JsonResponse<AdvertiseResponse>>() {\n @Override\n public void onResponse(JsonResponse<AdvertiseResponse> response) {\n if (response.isError()) {\n logger.error(\"Failed to advertise to Hyperbahn: {} - {}\",\n response.getError().getErrorType(),\n response.getError().getMessage());\n }\n\n if (destroyed.get()) {\n return;\n }\n\n scheduleAdvertise();\n }\n });\n\n return future;\n }", "public static void extract( DMatrix src,\n int srcY0, int srcY1,\n int srcX0, int srcX1,\n DMatrix dst ) {\n ((ReshapeMatrix)dst).reshape(srcY1-srcY0,srcX1-srcX0);\n extract(src,srcY0,srcY1,srcX0,srcX1,dst,0,0);\n }", "private void expireDevices() {\n long now = System.currentTimeMillis();\n // Make a copy so we don't have to worry about concurrent modification.\n Map<InetAddress, DeviceAnnouncement> copy = new HashMap<InetAddress, DeviceAnnouncement>(devices);\n for (Map.Entry<InetAddress, DeviceAnnouncement> entry : copy.entrySet()) {\n if (now - entry.getValue().getTimestamp() > MAXIMUM_AGE) {\n devices.remove(entry.getKey());\n deliverLostAnnouncement(entry.getValue());\n }\n }\n if (devices.isEmpty()) {\n firstDeviceTime.set(0); // We have lost contact with the Pro DJ Link network, so start over with next device.\n }\n }", "public String getTextForExpression(DJGroup group, DJGroup childGroup, String type) {\n\t\treturn \"new Double( $V{\" + getReportName() + \"_\" + getGroupVariableName(childGroup) + \"}.doubleValue() / $V{\" + getReportName() + \"_\" + getGroupVariableName(type,group.getColumnToGroupBy().getColumnProperty().getProperty()) + \"}.doubleValue())\";\n\t}", "private static List<Path> expandMultiAppInputDirs(List<Path> input)\n {\n List<Path> expanded = new LinkedList<>();\n for (Path path : input)\n {\n if (Files.isRegularFile(path))\n {\n expanded.add(path);\n continue;\n }\n if (!Files.isDirectory(path))\n {\n String pathString = (path == null) ? \"\" : path.toString(); \n log.warning(\"Neither a file or directory found in input: \" + pathString);\n continue;\n }\n\n try\n {\n try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path))\n {\n for (Path subpath : directoryStream)\n {\n\n if (isJavaArchive(subpath))\n {\n expanded.add(subpath);\n }\n }\n }\n }\n catch (IOException e)\n {\n throw new WindupException(\"Failed to read directory contents of: \" + path);\n }\n }\n return expanded;\n }", "private boolean findBinding(Injector injector, Class<?> type) {\n boolean found = false;\n for (Key<?> key : injector.getBindings().keySet()) {\n if (key.getTypeLiteral().getRawType().equals(type)) {\n found = true;\n break;\n }\n }\n if (!found && injector.getParent() != null) {\n return findBinding(injector.getParent(), type);\n }\n\n return found;\n }" ]
Convert a document List into arrays storing the data features and labels. @param document Training documents @return A Pair, where the first element is an int[][][] representing the data and the second element is an int[] representing the labels
[ "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 static <T extends Annotation> List<T> searchForAnnotation(Method method, Class<T> annotation) {\n if (method == null) {\n return Lists.newArrayList();\n }\n return searchClasses(method, annotation, method.getDeclaringClass());\n }", "public static Class<?> resolvePrimitiveIfNecessary(Class<?> clazz) {\n\t\tAssert.notNull(clazz, \"Class must not be null\");\n\t\treturn (clazz.isPrimitive() && clazz != void.class? primitiveTypeToWrapperMap.get(clazz) : clazz);\n\t}", "private void processRequestHeaderOverrides(HttpMethod httpMethodProxyRequest) throws Exception {\n RequestInformation requestInfo = requestInformation.get();\n for (EndpointOverride selectedPath : requestInfo.selectedRequestPaths) {\n List<EnabledEndpoint> points = selectedPath.getEnabledEndpoints();\n for (EnabledEndpoint endpoint : points) {\n if (endpoint.getOverrideId() == Constants.PLUGIN_REQUEST_HEADER_OVERRIDE_ADD) {\n httpMethodProxyRequest.addRequestHeader(endpoint.getArguments()[0].toString(),\n endpoint.getArguments()[1].toString());\n requestInfo.modified = true;\n } else if (endpoint.getOverrideId() == Constants.PLUGIN_REQUEST_HEADER_OVERRIDE_REMOVE) {\n httpMethodProxyRequest.removeRequestHeader(endpoint.getArguments()[0].toString());\n requestInfo.modified = true;\n }\n }\n }\n }", "public boolean rename(final File from, final File to) {\n boolean renamed = false;\n if (this.isWriteable(from)) {\n renamed = from.renameTo(to);\n } else {\n LogLog.debug(from + \" is not writeable for rename (retrying)\");\n }\n if (!renamed) {\n from.renameTo(to);\n renamed = (!from.exists());\n }\n return renamed;\n }", "public static wisite_binding[] get(nitro_service service, String sitepath[]) throws Exception{\n\t\tif (sitepath !=null && sitepath.length>0) {\n\t\t\twisite_binding response[] = new wisite_binding[sitepath.length];\n\t\t\twisite_binding obj[] = new wisite_binding[sitepath.length];\n\t\t\tfor (int i=0;i<sitepath.length;i++) {\n\t\t\t\tobj[i] = new wisite_binding();\n\t\t\t\tobj[i].set_sitepath(sitepath[i]);\n\t\t\t\tresponse[i] = (wisite_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 static void checkChannels(final Iterable<String> channels) {\n if (channels == null) {\n throw new IllegalArgumentException(\"channels must not be null\");\n }\n for (final String channel : channels) {\n if (channel == null || \"\".equals(channel)) {\n throw new IllegalArgumentException(\"channels' members must not be null: \" + channels);\n }\n }\n }", "public static java.sql.Timestamp getTimestamp(Object value) {\n try {\n return toTimestamp(value);\n } catch (ParseException pe) {\n pe.printStackTrace();\n return null;\n }\n }", "@SuppressWarnings(\"unchecked\")\n private void addPrivateFieldsAccessors(ClassNode node) {\n Set<ASTNode> accessedFields = (Set<ASTNode>) node.getNodeMetaData(StaticTypesMarker.PV_FIELDS_ACCESS);\n if (accessedFields==null) return;\n Map<String, MethodNode> privateConstantAccessors = (Map<String, MethodNode>) node.getNodeMetaData(PRIVATE_FIELDS_ACCESSORS);\n if (privateConstantAccessors!=null) {\n // already added\n return;\n }\n int acc = -1;\n privateConstantAccessors = new HashMap<String, MethodNode>();\n final int access = Opcodes.ACC_STATIC | Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC;\n for (FieldNode fieldNode : node.getFields()) {\n if (accessedFields.contains(fieldNode)) {\n\n acc++;\n Parameter param = new Parameter(node.getPlainNodeReference(), \"$that\");\n Expression receiver = fieldNode.isStatic()?new ClassExpression(node):new VariableExpression(param);\n Statement stmt = new ExpressionStatement(new PropertyExpression(\n receiver,\n fieldNode.getName()\n ));\n MethodNode accessor = node.addMethod(\"pfaccess$\"+acc, access, fieldNode.getOriginType(), new Parameter[]{param}, ClassNode.EMPTY_ARRAY, stmt);\n privateConstantAccessors.put(fieldNode.getName(), accessor);\n }\n }\n node.setNodeMetaData(PRIVATE_FIELDS_ACCESSORS, privateConstantAccessors);\n }", "protected boolean prepareClose() {\n synchronized (lock) {\n final State state = this.state;\n if (state == State.OPEN) {\n this.state = State.CLOSING;\n lock.notifyAll();\n return true;\n }\n }\n return false;\n }" ]
A specific, existing custom field can be deleted by making a DELETE request on the URL for that custom field. Returns an empty data record. @param customField Globally unique identifier for the custom field. @return Request object
[ "public ItemRequest<CustomField> delete(String customField) {\n \n String path = String.format(\"/custom_fields/%s\", customField);\n return new ItemRequest<CustomField>(this, CustomField.class, path, \"DELETE\");\n }" ]
[ "@RequestMapping(value = \"api/edit/disable\", method = RequestMethod.POST)\n public\n @ResponseBody\n String disableResponses(Model model, int path_id, @RequestParam(defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) throws Exception {\n OverrideService.getInstance().disableAllOverrides(path_id, clientUUID);\n //TODO also need to disable custom override if there is one of those\n editService.removeCustomOverride(path_id, clientUUID);\n\n return null;\n }", "public static final double round(double value, double precision)\n {\n precision = Math.pow(10, precision);\n return Math.round(value * precision) / precision;\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 Duration getWorkVariance()\n {\n Duration variance = (Duration) getCachedValue(ResourceField.WORK_VARIANCE);\n if (variance == null)\n {\n Duration work = getWork();\n Duration baselineWork = getBaselineWork();\n if (work != null && baselineWork != null)\n {\n variance = Duration.getInstance(work.getDuration() - baselineWork.convertUnits(work.getUnits(), getParentFile().getProjectProperties()).getDuration(), work.getUnits());\n set(ResourceField.WORK_VARIANCE, variance);\n }\n }\n return (variance);\n }", "public void validateUniqueIDsForMicrosoftProject()\n {\n if (!isEmpty())\n {\n for (T entity : this)\n {\n if (NumberHelper.getInt(entity.getUniqueID()) > MS_PROJECT_MAX_UNIQUE_ID)\n {\n renumberUniqueIDs();\n break;\n }\n }\n }\n }", "protected String addDependency(FunctionalTaskItem dependency) {\n Objects.requireNonNull(dependency);\n return this.taskGroup().addDependency(dependency);\n }", "private static boolean checkModifiers(Class<? extends AbstractPlugin> pluginClass) {\n int modifiers = pluginClass.getModifiers();\n return !Modifier.isAbstract(modifiers) &&\n !Modifier.isInterface(modifiers) &&\n !Modifier.isPrivate(modifiers);\n }", "public static Collection<CurrencyUnit> getCurrencies(String... providers) {\n return Optional.ofNullable(MONETARY_CURRENCIES_SINGLETON_SPI()).orElseThrow(\n () -> new MonetaryException(\"No MonetaryCurrenciesSingletonSpi loaded, check your system setup.\"))\n .getCurrencies(providers);\n }", "public void deleteComment(String commentId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_DELETE_COMMENT);\r\n\r\n parameters.put(\"comment_id\", commentId);\r\n\r\n // Note: This method requires an HTTP POST request.\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n // This method has no specific response - It returns an empty\r\n // sucess response if it completes without error.\r\n }" ]
Print duration in tenths of minutes. @param duration Duration instance @return duration in tenths of minutes
[ "public static final BigInteger printDurationInIntegerTenthsOfMinutes(Duration duration)\n {\n BigInteger result = null;\n\n if (duration != null && duration.getDuration() != 0)\n {\n result = BigInteger.valueOf((long) printDurationFractionsOfMinutes(duration, 10));\n }\n\n return result;\n }" ]
[ "private void set(FieldType field, boolean value)\n {\n set(field, (value ? Boolean.TRUE : Boolean.FALSE));\n }", "public ParallelTaskBuilder preparePing() {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.setProtocol(RequestProtocol.PING);\n return cb;\n }", "public synchronized X509Certificate getMappedCertificate(final X509Certificate cert)\n\tthrows CertificateEncodingException,\n\tInvalidKeyException,\n\tCertificateException,\n\tCertificateNotYetValidException,\n\tNoSuchAlgorithmException,\n\tNoSuchProviderException,\n\tSignatureException,\n\tKeyStoreException,\n\tUnrecoverableKeyException\n\t{\n\n\t\tString thumbprint = ThumbprintUtil.getThumbprint(cert);\n\n\t\tString mappedCertThumbprint = _certMap.get(thumbprint);\n\n\t\tif(mappedCertThumbprint == null)\n\t\t{\n\n\t\t\t// Check if we've already mapped this public key from a KeyValue\n\t\t\tPublicKey mappedPk = getMappedPublicKey(cert.getPublicKey());\n\t\t\tPrivateKey privKey;\n\n\t\t\tif(mappedPk == null)\n\t\t\t{\n\t\t\t\tPublicKey pk = cert.getPublicKey();\n\n\t\t\t\tString algo = pk.getAlgorithm();\n\n\t\t\t\tKeyPair kp;\n\n\t\t\t\tif(algo.equals(\"RSA\")) {\n\t\t\t\t\tkp = getRSAKeyPair();\n\t\t\t\t}\n\t\t\t\telse if(algo.equals(\"DSA\")) {\n\t\t\t\t\tkp = getDSAKeyPair();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tthrow new InvalidKeyException(\"Key algorithm \" + algo + \" not supported.\");\n\t\t\t\t}\n\t\t\t\tmappedPk = kp.getPublic();\n\t\t\t\tprivKey = kp.getPrivate();\n\n\t\t\t\tmapPublicKeys(cert.getPublicKey(), mappedPk);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tprivKey = getPrivateKey(mappedPk);\n\t\t\t}\n\n\n\t\t\tX509Certificate replacementCert =\n\t\t\t\tCertificateCreator.mitmDuplicateCertificate(\n\t\t\t\t\t\tcert,\n\t\t\t\t\t\tmappedPk,\n\t\t\t\t\t\tgetSigningCert(),\n\t\t\t\t\t\tgetSigningPrivateKey());\n\n\t\t\taddCertAndPrivateKey(null, replacementCert, privKey);\n\n\t\t\tmappedCertThumbprint = ThumbprintUtil.getThumbprint(replacementCert);\n\n\t\t\t_certMap.put(thumbprint, mappedCertThumbprint);\n\t\t\t_certMap.put(mappedCertThumbprint, thumbprint);\n\t\t\t_subjectMap.put(replacementCert.getSubjectX500Principal().getName(), thumbprint);\n\n\t\t\tif(persistImmediately) {\n\t\t\t\tpersist();\n\t\t\t}\n\t\t\treturn replacementCert;\n\t\t}\n return getCertificateByAlias(mappedCertThumbprint);\n\n\t}", "public T addBundle(final String moduleName, final String slot, final byte[] newHash) {\n final ContentItem item = createBundleItem(moduleName, slot, newHash);\n addContentModification(createContentModification(item, ModificationType.ADD, NO_CONTENT));\n return returnThis();\n }", "List<CmsResource> getBundleResources() {\n\n List<CmsResource> resources = new ArrayList<>(m_bundleFiles.values());\n if (m_desc != null) {\n resources.add(m_desc);\n }\n return resources;\n\n }", "public ParallelTaskBuilder prepareHttpPost(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.getHttpMeta().setHttpMethod(HttpMethod.POST);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\n }", "public static String frame(String imageUrl) {\n if (imageUrl == null || imageUrl.length() == 0) {\n throw new IllegalArgumentException(\"Image URL must not be blank.\");\n }\n return FILTER_FRAME + \"(\" + imageUrl + \")\";\n }", "private ModelNode resolveExpressionsRecursively(final ModelNode node) throws OperationFailedException {\n if (!node.isDefined()) {\n return node;\n }\n\n ModelType type = node.getType();\n ModelNode resolved;\n if (type == ModelType.EXPRESSION) {\n resolved = resolveExpressionStringRecursively(node.asExpression().getExpressionString(), lenient, true);\n } else if (type == ModelType.OBJECT) {\n resolved = node.clone();\n for (Property prop : resolved.asPropertyList()) {\n resolved.get(prop.getName()).set(resolveExpressionsRecursively(prop.getValue()));\n }\n } else if (type == ModelType.LIST) {\n resolved = node.clone();\n ModelNode list = new ModelNode();\n list.setEmptyList();\n for (ModelNode current : resolved.asList()) {\n list.add(resolveExpressionsRecursively(current));\n }\n resolved = list;\n } else if (type == ModelType.PROPERTY) {\n resolved = node.clone();\n resolved.set(resolved.asProperty().getName(), resolveExpressionsRecursively(resolved.asProperty().getValue()));\n } else {\n resolved = node;\n }\n\n return resolved;\n }", "public static base_response update(nitro_service client, cacheselector resource) throws Exception {\n\t\tcacheselector updateresource = new cacheselector();\n\t\tupdateresource.selectorname = resource.selectorname;\n\t\tupdateresource.rule = resource.rule;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
Returns all the retention policies. @param api the API connection to be used by the resource. @param fields the fields to retrieve. @return an iterable with all the retention policies.
[ "public static Iterable<BoxRetentionPolicy.Info> getAll(final BoxAPIConnection api, String ... fields) {\r\n return getAll(null, null, null, DEFAULT_LIMIT, api, fields);\r\n }" ]
[ "public static void append(File file, Object text, String charset) throws IOException {\n Writer writer = null;\n try {\n FileOutputStream out = new FileOutputStream(file, true);\n if (!file.exists()) {\n writeUTF16BomIfRequired(charset, out);\n }\n writer = new OutputStreamWriter(out, charset);\n InvokerHelper.write(writer, text);\n writer.flush();\n\n Writer temp = writer;\n writer = null;\n temp.close();\n } finally {\n closeWithWarning(writer);\n }\n }", "public static int randomIntBetween(int min, int max) {\n Random rand = new Random();\n return rand.nextInt((max - min) + 1) + min;\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}", "@Override\n public HandlerRegistration addChangeHandler(final ChangeHandler handler) {\n return getRangeInputElement().addDomHandler(handler, ChangeEvent.getType());\n }", "public Character getCharacter(int field)\n {\n Character result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n result = Character.valueOf(m_fields[field].charAt(0));\n }\n else\n {\n result = null;\n }\n\n return (result);\n }", "public static Thread newThread(String name, Runnable runnable, boolean daemon) {\n Thread thread = new Thread(runnable, name);\n thread.setDaemon(daemon);\n return thread;\n }", "public void fillRect(int x, int y, int w, int h, Color c) {\n int color = c.getRGB();\n for (int i = x; i < x + w; i++) {\n for (int j = y; j < y + h; j++) {\n setIntColor(i, j, color);\n }\n }\n }", "void initialize(DMatrixSparseCSC A) {\n m = A.numRows;\n n = A.numCols;\n int s = 4*n + (ata ? (n+m+1) : 0);\n\n gw.reshape(s);\n w = gw.data;\n\n // compute the transpose of A\n At.reshape(A.numCols,A.numRows,A.nz_length);\n CommonOps_DSCC.transpose(A,At,gw);\n\n // initialize w\n Arrays.fill(w,0,s,-1); // assign all values in workspace to -1\n\n ancestor = 0;\n maxfirst = n;\n prevleaf = 2*n;\n first = 3*n;\n }", "public static boolean removeDefaultCustomResponse(String pathValue, String requestType) {\n try {\n JSONObject profile = getDefaultProfile();\n String profileName = profile.getString(\"name\");\n PathValueClient client = new PathValueClient(profileName, false);\n return client.removeCustomResponse(pathValue, requestType);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }" ]
Answer the primary key query to retrieve an Object @param oid the Identity of the Object to retrieve @return The resulting query
[ "public Query getPKQuery(Identity oid)\r\n {\r\n Object[] values = oid.getPrimaryKeyValues();\r\n ClassDescriptor cld = pb.getClassDescriptor(oid.getObjectsTopLevelClass());\r\n FieldDescriptor[] fields = cld.getPkFields();\r\n Criteria criteria = new Criteria();\r\n\r\n for (int i = 0; i < fields.length; i++)\r\n {\r\n FieldDescriptor fld = fields[i];\r\n criteria.addEqualTo(fld.getAttributeName(), values[i]);\r\n }\r\n return QueryFactory.newQuery(cld.getClassOfObject(), criteria);\r\n }" ]
[ "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 }", "public static void pullImage(String imageTag, String username, String password, String host) throws IOException {\n final AuthConfig authConfig = new AuthConfig();\n authConfig.withUsername(username);\n authConfig.withPassword(password);\n\n DockerClient dockerClient = null;\n try {\n dockerClient = getDockerClient(host);\n dockerClient.pullImageCmd(imageTag).withAuthConfig(authConfig).exec(new PullImageResultCallback()).awaitSuccess();\n } finally {\n closeQuietly(dockerClient);\n }\n }", "public static List<String> getChildrenParentMayNotExist(ZkClient zkClient, String path) {\n try {\n return zkClient.getChildren(path);\n } catch (ZkNoNodeException e) {\n return null;\n }\n }", "private void appendBetweenCriteria(TableAlias alias, PathInfo pathInfo, BetweenCriteria c, StringBuffer buf)\r\n {\r\n appendColName(alias, pathInfo, c.isTranslateAttribute(), buf);\r\n buf.append(c.getClause());\r\n appendParameter(c.getValue(), buf);\r\n buf.append(\" AND \");\r\n appendParameter(c.getValue2(), buf);\r\n }", "public static Long getSize(final File file){\n if ( file!=null && file.exists() ){\n return file.length();\n }\n return null;\n }", "public static dnsview[] get(nitro_service service) throws Exception{\n\t\tdnsview obj = new dnsview();\n\t\tdnsview[] response = (dnsview[])obj.get_resources(service);\n\t\treturn response;\n\t}", "private JSONObject getJsonFormattedSpellcheckResult(CmsSpellcheckingRequest request) {\n\n final JSONObject response = new JSONObject();\n\n try {\n if (null != request.m_id) {\n response.put(JSON_ID, request.m_id);\n }\n\n response.put(JSON_RESULT, request.m_wordSuggestions);\n\n } catch (Exception e) {\n try {\n response.put(JSON_ERROR, true);\n LOG.debug(\"Error while assembling spellcheck response in JSON format.\", e);\n } catch (JSONException ex) {\n LOG.debug(\"Error while assembling spellcheck response in JSON format.\", ex);\n }\n }\n\n return response;\n }", "public void registerCollectionSizeGauge(\n\t\t\tCollectionSizeGauge collectionSizeGauge) {\n\t\tString name = createMetricName(LocalTaskExecutorService.class,\n\t\t\t\t\"queue-size\");\n\t\tmetrics.register(name, collectionSizeGauge);\n\t}", "public static base_response update(nitro_service client, cmpparameter resource) throws Exception {\n\t\tcmpparameter updateresource = new cmpparameter();\n\t\tupdateresource.cmplevel = resource.cmplevel;\n\t\tupdateresource.quantumsize = resource.quantumsize;\n\t\tupdateresource.servercmp = resource.servercmp;\n\t\tupdateresource.heurexpiry = resource.heurexpiry;\n\t\tupdateresource.heurexpirythres = resource.heurexpirythres;\n\t\tupdateresource.heurexpiryhistwt = resource.heurexpiryhistwt;\n\t\tupdateresource.minressize = resource.minressize;\n\t\tupdateresource.cmpbypasspct = resource.cmpbypasspct;\n\t\tupdateresource.cmponpush = resource.cmponpush;\n\t\tupdateresource.policytype = resource.policytype;\n\t\tupdateresource.addvaryheader = resource.addvaryheader;\n\t\tupdateresource.externalcache = resource.externalcache;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
Return an artifact regarding its gavc @param gavc String @return DbArtifact
[ "public DbArtifact getArtifact(final String gavc) {\n final DbArtifact artifact = repositoryHandler.getArtifact(gavc);\n\n if(artifact == null){\n throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)\n .entity(\"Artifact \" + gavc + \" does not exist.\").build());\n }\n\n return artifact;\n }" ]
[ "public static hanode_routemonitor6_binding[] get(nitro_service service, Long id) throws Exception{\n\t\thanode_routemonitor6_binding obj = new hanode_routemonitor6_binding();\n\t\tobj.set_id(id);\n\t\thanode_routemonitor6_binding response[] = (hanode_routemonitor6_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "@VisibleForTesting\n @Nullable\n protected LineSymbolizer createLineSymbolizer(final PJsonObject styleJson) {\n final Stroke stroke = createStroke(styleJson, true);\n if (stroke == null) {\n return null;\n } else {\n return this.styleBuilder.createLineSymbolizer(stroke);\n }\n }", "protected Model createFlattenedPom( File pomFile )\n throws MojoExecutionException, MojoFailureException\n {\n\n ModelBuildingRequest buildingRequest = createModelBuildingRequest( pomFile );\n Model effectivePom = createEffectivePom( buildingRequest, isEmbedBuildProfileDependencies(), this.flattenMode );\n\n Model flattenedPom = new Model();\n\n // keep original encoding (we could also normalize to UTF-8 here)\n String modelEncoding = effectivePom.getModelEncoding();\n if ( StringUtils.isEmpty( modelEncoding ) )\n {\n modelEncoding = \"UTF-8\";\n }\n flattenedPom.setModelEncoding( modelEncoding );\n\n Model cleanPom = createCleanPom( effectivePom );\n\n FlattenDescriptor descriptor = getFlattenDescriptor();\n Model originalPom = this.project.getOriginalModel();\n Model resolvedPom = this.project.getModel();\n Model interpolatedPom = createResolvedPom( buildingRequest );\n\n // copy the configured additional POM elements...\n\n for ( PomProperty<?> property : PomProperty.getPomProperties() )\n {\n if ( property.isElement() )\n {\n Model sourceModel = getSourceModel( descriptor, property, effectivePom, originalPom, resolvedPom,\n interpolatedPom, cleanPom );\n if ( sourceModel == null )\n {\n if ( property.isRequired() )\n {\n throw new MojoFailureException( \"Property \" + property.getName()\n + \" is required and can not be removed!\" );\n }\n }\n else\n {\n property.copy( sourceModel, flattenedPom );\n }\n }\n }\n\n return flattenedPom;\n }", "public synchronized void stopDebugServer() {\n if (mDebugServer == null) {\n Log.e(TAG, \"Debug server is not running.\");\n return;\n }\n\n mDebugServer.shutdown();\n mDebugServer = null;\n }", "public void writeOutput(DataPipe cr) {\n String[] nextLine = new String[cr.getDataMap().entrySet().size()];\n\n int count = 0;\n for (Map.Entry<String, String> entry : cr.getDataMap().entrySet()) {\n nextLine[count] = entry.getValue();\n count++;\n }\n\n csvFile.writeNext(nextLine);\n }", "public Bundler put(String key, CharSequence[] value) {\n delegate.putCharSequenceArray(key, value);\n return this;\n }", "public void enableCustomResponse(String custom, int path_id, String client_uuid) throws Exception {\n\n updateRequestResponseTables(\"custom_response\", custom, getProfileIdFromPathID(path_id), client_uuid, path_id);\n }", "public Range<Dyno> listDynos(String appName) {\n return connection.execute(new DynoList(appName), apiKey);\n }", "public void forAllIndices(String template, Properties attributes) throws XDocletException\r\n {\r\n boolean processUnique = TypeConversionUtil.stringToBoolean(attributes.getProperty(ATTRIBUTE_UNIQUE), false);\r\n\r\n // first the default index\r\n _curIndexDef = _curTableDef.getIndex(null);\r\n if ((_curIndexDef != null) && (processUnique == _curIndexDef.isUnique()))\r\n {\r\n generate(template);\r\n }\r\n for (Iterator it = _curTableDef.getIndices(); it.hasNext(); )\r\n {\r\n _curIndexDef = (IndexDef)it.next();\r\n if (!_curIndexDef.isDefault() && (processUnique == _curIndexDef.isUnique()))\r\n { \r\n generate(template);\r\n }\r\n }\r\n _curIndexDef = null;\r\n }" ]
First close the connection. Then reply. @param response the response @param error the error @param errorMessage the error message @param stackTrace the stack trace @param statusCode the status code @param statusCodeInt the status code int
[ "private void reply(final String response, final boolean error,\n final String errorMessage, final String stackTrace,\n final String statusCode, final int statusCodeInt) {\n\n \n if (!sentReply) {\n \n //must update sentReply first to avoid duplicated msg.\n sentReply = true;\n // Close the connection. Make sure the close operation ends because\n // all I/O operations are asynchronous in Netty.\n if(channel!=null && channel.isOpen())\n channel.close().awaitUninterruptibly();\n final ResponseOnSingeRequest res = new ResponseOnSingeRequest(\n response, error, errorMessage, stackTrace, statusCode,\n statusCodeInt, PcDateUtils.getNowDateTimeStrStandard(), null);\n if (!getContext().system().deadLetters().equals(sender)) {\n sender.tell(res, getSelf());\n }\n if (getContext() != null) {\n getContext().stop(getSelf());\n }\n }\n\n }" ]
[ "public static base_response unset(nitro_service client, ntpserver resource, String[] args) throws Exception{\n\t\tntpserver unsetresource = new ntpserver();\n\t\tunsetresource.serverip = resource.serverip;\n\t\tunsetresource.servername = resource.servername;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "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}", "public void setPublishQueueShutdowntime(String publishQueueShutdowntime) {\n\n if (m_frozen) {\n throw new CmsRuntimeException(Messages.get().container(Messages.ERR_CONFIG_FROZEN_0));\n }\n m_publishQueueShutdowntime = Integer.parseInt(publishQueueShutdowntime);\n }", "public void addForeignKeyField(String newField)\r\n {\r\n if (m_ForeignKeyFields == null)\r\n {\r\n m_ForeignKeyFields = new Vector();\r\n }\r\n m_ForeignKeyFields.add(newField);\r\n }", "public static Class<?> resolveTypeArgument(Class<?> clazz, Class<?> genericIfc) {\n\t\tClass<?>[] typeArgs = resolveTypeArguments(clazz, genericIfc);\n\t\tif (typeArgs == null) {\n\t\t\treturn null;\n\t\t}\n\t\tif (typeArgs.length != 1) {\n\t\t\tthrow new IllegalArgumentException(\"Expected 1 type argument on generic interface [\" +\n\t\t\t\t\tgenericIfc.getName() + \"] but found \" + typeArgs.length);\n\t\t}\n\t\treturn typeArgs[0];\n\t}", "public void addFilter(Filter filter)\n {\n if (filter.isTaskFilter())\n {\n m_taskFilters.add(filter);\n }\n\n if (filter.isResourceFilter())\n {\n m_resourceFilters.add(filter);\n }\n\n m_filtersByName.put(filter.getName(), filter);\n m_filtersByID.put(filter.getID(), filter);\n }", "private Task findChildTaskByUUID(ChildTaskContainer parent, UUID uuid)\n {\n Task result = null;\n\n for (Task task : parent.getChildTasks())\n {\n if (uuid.equals(task.getGUID()))\n {\n result = task;\n break;\n }\n }\n\n return result;\n }", "public Weld addExtension(Extension extension) {\n extensions.add(new MetadataImpl<Extension>(extension, SYNTHETIC_LOCATION_PREFIX + extension.getClass().getName()));\n return this;\n }", "PathAddress toPathAddress(final ObjectName name) {\n return ObjectNameAddressUtil.toPathAddress(rootObjectInstance.getObjectName(), getRootResourceAndRegistration().getRegistration(), name);\n }" ]
returns a collection of Reader LockEntries for object obj. If no LockEntries could be found an empty Vector is returned.
[ "public Collection getReaders(Object obj)\r\n {\r\n \tcheckTimedOutLocks();\r\n Identity oid = new Identity(obj,getBroker());\r\n return getReaders(oid);\r\n }" ]
[ "public Class<? extends MonetaryAmount> getAmountType() {\n Class<?> clazz = get(AMOUNT_TYPE, Class.class);\n return clazz.asSubclass(MonetaryAmount.class);\n }", "public static <E> Collection<E> collectify(ObjectMapper mapper, Object source, Class<? extends Collection> targetCollectionType, Class<E> targetElementType) {\n CollectionType collectionType = mapper.getTypeFactory().constructCollectionType(targetCollectionType, targetElementType);\n return objectify(mapper, convertToCollection(source), collectionType);\n }", "public static PropertyResourceBundle getBundle(String baseName, Locale locale) throws UnsupportedEncodingException, IOException{\n\t\tInputStream is = UTF8PropertyResourceBundle.class.getResourceAsStream(\"/\"+baseName + \"_\"+locale.toString()+PROPERTIES_EXT);\n\t\tif(is != null){\n\t\t\treturn new PropertyResourceBundle(new InputStreamReader(is, \"UTF-8\"));\n\t\t}\n\t\treturn null;\n\t}", "public void addAll(int index, T... items) {\n List<T> collection = Arrays.asList(items);\n synchronized (mLock) {\n if (mOriginalValues != null) {\n mOriginalValues.addAll(index, collection);\n } else {\n mObjects.addAll(index, collection);\n }\n }\n if (mNotifyOnChange) notifyDataSetChanged();\n }", "public void clear() {\n List<Widget> children = getChildren();\n Log.d(TAG, \"clear(%s): removing %d children\", getName(), children.size());\n for (Widget child : children) {\n removeChild(child, true);\n }\n requestLayout();\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 static String toJson(Date date) {\n if (date == null) {\n return NULL_VALUE;\n }\n\n CharBuf buffer = CharBuf.create(26);\n writeDate(date, buffer);\n\n return buffer.toString();\n }", "public static String getSimpleClassName(String className) {\n\t\t// get the last part of the class name\n\t\tString[] parts = className.split(\"\\\\.\");\n\t\tif (parts.length <= 1) {\n\t\t\treturn className;\n\t\t} else {\n\t\t\treturn parts[parts.length - 1];\n\t\t}\n\t}", "public static vlan_nsip_binding[] get(nitro_service service, Long id) throws Exception{\n\t\tvlan_nsip_binding obj = new vlan_nsip_binding();\n\t\tobj.set_id(id);\n\t\tvlan_nsip_binding response[] = (vlan_nsip_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
IS NULL predicate @param value the value for which to check @return a {@link LuaCondition} instance
[ "public static LuaCondition isNull(LuaValue value) {\n LuaAstExpression expression;\n if (value instanceof LuaLocal) {\n expression = new LuaAstLocal(((LuaLocal) value).getName());\n } else {\n throw new IllegalArgumentException(\"Unexpected value type: \" + value.getClass().getName());\n }\n return new LuaCondition(new LuaAstNot(expression));\n }" ]
[ "public static void addHeaders(BoundRequestBuilder builder,\n Map<String, String> headerMap) {\n for (Entry<String, String> entry : headerMap.entrySet()) {\n String name = entry.getKey();\n String value = entry.getValue();\n builder.addHeader(name, value);\n }\n\n }", "@SuppressWarnings(\"unchecked\") public static TimeUnit getInstance(String units, Locale locale) throws MPXJException\n {\n Map<String, Integer> map = LocaleData.getMap(locale, LocaleData.TIME_UNITS_MAP);\n Integer result = map.get(units.toLowerCase());\n if (result == null)\n {\n throw new MPXJException(MPXJException.INVALID_TIME_UNIT + \" \" + units);\n }\n return (TimeUnit.getInstance(result.intValue()));\n }", "public EventBus emitAsync(String event, Object... args) {\n return _emitWithOnceBus(eventContextAsync(event, args));\n }", "protected void init(String configString, I_CmsSearchConfiguration baseConfig) throws JSONException {\n\n m_configObject = new JSONObject(configString);\n m_baseConfig = baseConfig;\n }", "public static double[] computeSeasonalAdjustments(double[] realizedCPIValues, int lastMonth, int numberOfYearsToAverage) {\n\n\t\t/*\n\t\t * Cacluate average log returns\n\t\t */\n\t\tdouble[] averageLogReturn = new double[12];\n\t\tArrays.fill(averageLogReturn, 0.0);\n\t\tfor(int arrayIndex = 0; arrayIndex < 12*numberOfYearsToAverage; arrayIndex++){\n\n\t\t\tint month = (((((lastMonth-1 - arrayIndex) % 12) + 12) % 12));\n\n\t\t\tdouble logReturn = Math.log(realizedCPIValues[realizedCPIValues.length - 1 - arrayIndex] / realizedCPIValues[realizedCPIValues.length - 2 - arrayIndex]);\n\t\t\taverageLogReturn[month] += logReturn/numberOfYearsToAverage;\n\t\t}\n\n\t\t/*\n\t\t * Normalize\n\t\t */\n\t\tdouble sum = 0.0;\n\t\tfor(int index = 0; index < averageLogReturn.length; index++){\n\t\t\tsum += averageLogReturn[index];\n\t\t}\n\t\tdouble averageSeasonal = sum / averageLogReturn.length;\n\n\t\tdouble[] seasonalAdjustments = new double[averageLogReturn.length];\n\t\tfor(int index = 0; index < seasonalAdjustments.length; index++){\n\t\t\tseasonalAdjustments[index] = averageLogReturn[index] - averageSeasonal;\n\t\t}\n\n\t\t// Annualize seasonal adjustments\n\t\tfor(int index = 0; index < seasonalAdjustments.length; index++){\n\t\t\tseasonalAdjustments[index] = seasonalAdjustments[index] * 12;\n\t\t}\n\n\t\treturn seasonalAdjustments;\n\t}", "public boolean getBoolean(FastTrackField type)\n {\n boolean result = false;\n Object value = getObject(type);\n if (value != null)\n {\n result = BooleanHelper.getBoolean((Boolean) value);\n }\n return result;\n }", "public float getTangentY(int vertex) {\n if (!hasTangentsAndBitangents()) {\n throw new IllegalStateException(\"mesh has no bitangents\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_tangents.getFloat((vertex * 3 + 1) * SIZEOF_FLOAT);\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 }", "protected void appendTableWithJoins(TableAlias alias, StringBuffer where, StringBuffer buf)\r\n {\r\n int stmtFromPos = 0;\r\n byte joinSyntax = getJoinSyntaxType();\r\n\r\n if (joinSyntax == SQL92_JOIN_SYNTAX)\r\n {\r\n stmtFromPos = buf.length(); // store position of join (by: Terry Dexter)\r\n }\r\n\r\n if (alias == getRoot())\r\n {\r\n // BRJ: also add indirection table to FROM-clause for MtoNQuery \r\n if (getQuery() instanceof MtoNQuery)\r\n {\r\n MtoNQuery mnQuery = (MtoNQuery)m_query; \r\n buf.append(getTableAliasForPath(mnQuery.getIndirectionTable(), null).getTableAndAlias());\r\n buf.append(\", \");\r\n } \r\n buf.append(alias.getTableAndAlias());\r\n }\r\n else if (joinSyntax != SQL92_NOPAREN_JOIN_SYNTAX)\r\n {\r\n buf.append(alias.getTableAndAlias());\r\n }\r\n\r\n if (!alias.hasJoins())\r\n {\r\n return;\r\n }\r\n\r\n for (Iterator it = alias.iterateJoins(); it.hasNext();)\r\n {\r\n Join join = (Join) it.next();\r\n\r\n if (joinSyntax == SQL92_JOIN_SYNTAX)\r\n {\r\n appendJoinSQL92(join, where, buf);\r\n if (it.hasNext())\r\n {\r\n buf.insert(stmtFromPos, \"(\");\r\n buf.append(\")\");\r\n }\r\n }\r\n else if (joinSyntax == SQL92_NOPAREN_JOIN_SYNTAX)\r\n {\r\n appendJoinSQL92NoParen(join, where, buf);\r\n }\r\n else\r\n {\r\n appendJoin(where, buf, join);\r\n }\r\n\r\n }\r\n }" ]
Draw text in the center of the specified box. @param text text @param font font @param box box to put text int @param fontColor colour
[ "public void drawText(String text, Font font, Rectangle box, Color fontColor) {\n\t\ttemplate.saveState();\n\t\t// get the font\n\t\tDefaultFontMapper mapper = new DefaultFontMapper();\n\t\tBaseFont bf = mapper.awtToPdf(font);\n\t\ttemplate.setFontAndSize(bf, font.getSize());\n\n\t\t// calculate descent\n\t\tfloat descent = 0;\n\t\tif (text != null) {\n\t\t\tdescent = bf.getDescentPoint(text, font.getSize());\n\t\t}\n\n\t\t// calculate the fitting size\n\t\tRectangle fit = getTextSize(text, font);\n\n\t\t// draw text if necessary\n\t\ttemplate.setColorFill(fontColor);\n\t\ttemplate.beginText();\n\t\ttemplate.showTextAligned(PdfContentByte.ALIGN_LEFT, text, origX + box.getLeft() + 0.5f\n\t\t\t\t* (box.getWidth() - fit.getWidth()), origY + box.getBottom() + 0.5f\n\t\t\t\t* (box.getHeight() - fit.getHeight()) - descent, 0);\n\t\ttemplate.endText();\n\t\ttemplate.restoreState();\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 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 static final Integer parseMinutesFromHours(String value)\n {\n Integer result = null;\n if (value != null)\n {\n result = Integer.valueOf(Integer.parseInt(value) * 60);\n }\n return result;\n }", "public static dnstxtrec[] get(nitro_service service, dnstxtrec_args args) throws Exception{\n\t\tdnstxtrec obj = new dnstxtrec();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tdnstxtrec[] response = (dnstxtrec[])obj.get_resources(service, option);\n\t\treturn response;\n\t}", "public int compare(final Version other) throws IncomparableException{\n\t\t// Cannot compare branch versions and others \n\t\tif(!isBranch().equals(other.isBranch())){\n\t\t\tthrow new IncomparableException();\n\t\t}\n\t\t\n\t\t// Compare digits\n\t\tfinal int minDigitSize = getDigitsSize() < other.getDigitsSize()? getDigitsSize(): other.getDigitsSize();\n\t\t\n\t\tfor(int i = 0; i < minDigitSize ; i++){\n\t\t\tif(!getDigit(i).equals(other.getDigit(i))){\n\t\t\t\treturn getDigit(i).compareTo(other.getDigit(i));\n\t\t\t}\n\t\t}\n\t\t\n\t\t// If not the same number of digits and the first digits are equals, the longest is the newer\n\t\tif(!getDigitsSize().equals(other.getDigitsSize())){\n\t\t\treturn getDigitsSize() > other.getDigitsSize()? 1: -1;\n\t\t}\n\n if(isBranch() && !getBranchId().equals(other.getBranchId())){\n\t\t\treturn getBranchId().compareTo(other.getBranchId());\n\t\t}\n\t\t\n\t\t// if the digits are the same, a snapshot is newer than a release\n\t\tif(isSnapshot() && other.isRelease()){\n\t\t\treturn 1;\n\t\t}\n\t\t\n\t\tif(isRelease() && other.isSnapshot()){\n\t\t\treturn -1;\n\t\t}\n\t\t\n\t\t// if both versions are releases, compare the releaseID\n\t\tif(isRelease() && other.isRelease()){\n\t\t\treturn getReleaseId().compareTo(other.getReleaseId());\n\t\t}\n\t\t\n\t\treturn 0;\n\t}", "public QueryBuilder useIndex(String designDocument, String indexName) {\n useIndex = new String[]{designDocument, indexName};\n return this;\n }", "public static final Bytes of(ByteBuffer bb) {\n Objects.requireNonNull(bb);\n if (bb.remaining() == 0) {\n return EMPTY;\n }\n byte[] data;\n if (bb.hasArray()) {\n data = Arrays.copyOfRange(bb.array(), bb.position() + bb.arrayOffset(),\n bb.limit() + bb.arrayOffset());\n } else {\n data = new byte[bb.remaining()];\n // duplicate so that it does not change position\n bb.duplicate().get(data);\n }\n return new Bytes(data);\n }", "private static void defineField(Map<String, FieldType> container, String name, FieldType type, String alias)\n {\n container.put(name, type);\n if (alias != null)\n {\n ALIASES.put(type, alias);\n }\n }", "private void init()\n {\n style = new BoxStyle(UNIT);\n textLine = new StringBuilder();\n textMetrics = null;\n graphicsPath = new Vector<PathSegment>();\n startPage = 0;\n endPage = Integer.MAX_VALUE;\n fontTable = new FontTable();\n }" ]
A specific, existing custom field can be updated by making a PUT request on the URL for that custom field. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged When using this method, it is best to specify only those fields you wish to change, or else you may overwrite changes made by another user since you last retrieved the custom field. A custom field's `type` cannot be updated. An enum custom field's `enum_options` cannot be updated with this endpoint. Instead see "Work With Enum Options" for information on how to update `enum_options`. Returns the complete updated custom field record. @param customField Globally unique identifier for the custom field. @return Request object
[ "public ItemRequest<CustomField> update(String customField) {\n \n String path = String.format(\"/custom_fields/%s\", customField);\n return new ItemRequest<CustomField>(this, CustomField.class, path, \"PUT\");\n }" ]
[ "public void increasePriority(int overrideId, int ordinal, int pathId, String clientUUID) {\n logger.info(\"Increase priority\");\n\n int origPriority = -1;\n int newPriority = -1;\n int origId = 0;\n int newId = 0;\n\n PreparedStatement statement = null;\n ResultSet results = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n results = null;\n statement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \" = ?\" +\n \" AND \" + Constants.GENERIC_CLIENT_UUID + \" = ?\" +\n \" ORDER BY \" + Constants.ENABLED_OVERRIDES_PRIORITY\n );\n statement.setInt(1, pathId);\n statement.setString(2, clientUUID);\n results = statement.executeQuery();\n\n int ordinalCount = 0;\n while (results.next()) {\n if (results.getInt(Constants.ENABLED_OVERRIDES_OVERRIDE_ID) == overrideId) {\n ordinalCount++;\n if (ordinalCount == ordinal) {\n origPriority = results.getInt(Constants.ENABLED_OVERRIDES_PRIORITY);\n origId = results.getInt(Constants.GENERIC_ID);\n break;\n }\n }\n newPriority = results.getInt(Constants.ENABLED_OVERRIDES_PRIORITY);\n newId = results.getInt(Constants.GENERIC_ID);\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n // update priorities\n if (origPriority != -1 && newPriority != -1) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" SET \" + Constants.ENABLED_OVERRIDES_PRIORITY + \"=?\" +\n \" WHERE \" + Constants.GENERIC_ID + \"=?\"\n );\n statement.setInt(1, origPriority);\n statement.setInt(2, newId);\n statement.executeUpdate();\n statement.close();\n\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" SET \" + Constants.ENABLED_OVERRIDES_PRIORITY + \"=?\" +\n \" WHERE \" + Constants.GENERIC_ID + \"=?\"\n );\n statement.setInt(1, newPriority);\n statement.setInt(2, origId);\n statement.executeUpdate();\n }\n } catch (Exception e) {\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "private static void renderFreemarkerTemplate(Path templatePath, Map vars, Path outputPath)\n throws IOException, TemplateException\n {\n if(templatePath == null)\n throw new WindupException(\"templatePath is null\");\n\n freemarker.template.Configuration freemarkerConfig = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_26);\n DefaultObjectWrapperBuilder objectWrapperBuilder = new DefaultObjectWrapperBuilder(freemarker.template.Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);\n objectWrapperBuilder.setUseAdaptersForContainers(true);\n objectWrapperBuilder.setIterableSupport(true);\n freemarkerConfig.setObjectWrapper(objectWrapperBuilder.build());\n freemarkerConfig.setTemplateLoader(new FurnaceFreeMarkerTemplateLoader());\n Template template = freemarkerConfig.getTemplate(templatePath.toString().replace('\\\\', '/'));\n try (FileWriter fw = new FileWriter(outputPath.toFile()))\n {\n template.process(vars, fw);\n }\n }", "private void writeResources()\n {\n for (Resource resource : m_projectFile.getResources())\n {\n if (resource.getUniqueID().intValue() != 0)\n {\n writeResource(resource);\n }\n }\n }", "public void insertAfter(Token before, TokenList list ) {\n Token after = before.next;\n\n before.next = list.first;\n list.first.previous = before;\n if( after == null ) {\n last = list.last;\n } else {\n after.previous = list.last;\n list.last.next = after;\n }\n size += list.size;\n }", "public static base_response clear(nitro_service client, route6 resource) throws Exception {\n\t\troute6 clearresource = new route6();\n\t\tclearresource.routetype = resource.routetype;\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}", "@SuppressWarnings(\"unchecked\")\n protected Class<? extends Annotation> annotationTypeForName(String name) {\n try {\n return (Class<? extends Annotation>) resourceLoader.classForName(name);\n } catch (ResourceLoadingException cnfe) {\n return DUMMY_ANNOTATION;\n }\n }", "public static String decodeUrl(String stringToDecode) {\n try {\n return URLDecoder.decode(stringToDecode, \"UTF-8\");\n } catch (UnsupportedEncodingException e1) {\n throw new RuntimeException(e1);\n }\n }", "public static ResourceKey key(Class<?> clazz, Enum<?> value) {\n return new ResourceKey(clazz.getName(), value.name());\n }", "public boolean isWorkingDate(Date date)\n {\n Calendar cal = DateHelper.popCalendar(date);\n Day day = Day.getInstance(cal.get(Calendar.DAY_OF_WEEK));\n DateHelper.pushCalendar(cal);\n return isWorkingDate(date, day);\n }" ]
Default implementation returns unmodified original Query @see org.apache.ojb.broker.accesslayer.QueryCustomizer#customizeQuery
[ "public Query customizeQuery(Object anObject, PersistenceBroker aBroker, CollectionDescriptor aCod, QueryByCriteria aQuery)\r\n {\r\n return aQuery;\r\n }" ]
[ "AlbumArt getArtwork(int artworkId, SlotReference slot, CdjStatus.TrackType trackType, Client client)\n throws IOException {\n\n // Send the artwork request\n Message response = client.simpleRequest(Message.KnownType.ALBUM_ART_REQ, Message.KnownType.ALBUM_ART,\n client.buildRMST(Message.MenuIdentifier.DATA, slot.slot, trackType), new NumberField((long)artworkId));\n\n // Create an image from the response bytes\n return new AlbumArt(new DataReference(slot, artworkId), ((BinaryField)response.arguments.get(3)).getValue());\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 }", "protected final void setDerivedEndType() {\n\n m_endType = getPatternType().equals(PatternType.NONE) || getPatternType().equals(PatternType.INDIVIDUAL)\n ? EndType.SINGLE\n : null != getSeriesEndDate() ? EndType.DATE : EndType.TIMES;\n }", "public static base_response unset(nitro_service client, inatparam resource, String[] args) throws Exception{\n\t\tinatparam unsetresource = new inatparam();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public static base_response add(nitro_service client, spilloverpolicy resource) throws Exception {\n\t\tspilloverpolicy addresource = new spilloverpolicy();\n\t\taddresource.name = resource.name;\n\t\taddresource.rule = resource.rule;\n\t\taddresource.action = resource.action;\n\t\taddresource.comment = resource.comment;\n\t\treturn addresource.add_resource(client);\n\t}", "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 setCloseConnectionWatchTimeout(long closeConnectionWatchTimeout, TimeUnit timeUnit) {\n\t\tthis.closeConnectionWatchTimeoutInMs = TimeUnit.MILLISECONDS.convert(closeConnectionWatchTimeout, timeUnit);\n\t}", "protected void maybeSignalForMoreConnections(ConnectionPartition connectionPartition) {\r\n\r\n\t\tif (!connectionPartition.isUnableToCreateMoreTransactions() \r\n\t\t\t\t&& !this.poolShuttingDown &&\r\n\t\t\t\tconnectionPartition.getAvailableConnections()*100/connectionPartition.getMaxConnections() <= this.poolAvailabilityThreshold){\r\n\t\t\tconnectionPartition.getPoolWatchThreadSignalQueue().offer(new Object()); // item being pushed is not important.\r\n\t\t}\r\n\t}", "public AsciiTable setHtmlElementTranslator(HtmlElementTranslator htmlElementTranslator) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setHtmlElementTranslator(htmlElementTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}" ]
Compares two annotated parameters and returns true if they are equal
[ "public static boolean compareAnnotatedParameters(AnnotatedParameter<?> p1, AnnotatedParameter<?> p2) {\n return compareAnnotatedCallable(p1.getDeclaringCallable(), p2.getDeclaringCallable()) && p1.getPosition() == p2.getPosition() && compareAnnotated(p1, p2);\n }" ]
[ "private void readTask(ChildTaskContainer mpxjParent, net.sf.mpxj.ganttproject.schema.Task gpTask)\n {\n Task mpxjTask = mpxjParent.addTask();\n mpxjTask.setUniqueID(Integer.valueOf(NumberHelper.getInt(gpTask.getId()) + 1));\n mpxjTask.setName(gpTask.getName());\n mpxjTask.setPercentageComplete(gpTask.getComplete());\n mpxjTask.setPriority(getPriority(gpTask.getPriority()));\n mpxjTask.setHyperlink(gpTask.getWebLink());\n\n Duration duration = Duration.getInstance(NumberHelper.getDouble(gpTask.getDuration()), TimeUnit.DAYS);\n mpxjTask.setDuration(duration);\n\n if (duration.getDuration() == 0)\n {\n mpxjTask.setMilestone(true);\n }\n else\n {\n mpxjTask.setStart(gpTask.getStart());\n mpxjTask.setFinish(m_mpxjCalendar.getDate(gpTask.getStart(), mpxjTask.getDuration(), false));\n }\n\n mpxjTask.setConstraintDate(gpTask.getThirdDate());\n if (mpxjTask.getConstraintDate() != null)\n {\n // TODO: you don't appear to be able to change this setting in GanttProject\n // task.getThirdDateConstraint()\n mpxjTask.setConstraintType(ConstraintType.START_NO_EARLIER_THAN);\n }\n\n readTaskCustomFields(gpTask, mpxjTask);\n\n m_eventManager.fireTaskReadEvent(mpxjTask);\n\n // TODO: read custom values\n\n //\n // Process child tasks\n //\n for (net.sf.mpxj.ganttproject.schema.Task childTask : gpTask.getTask())\n {\n readTask(mpxjTask, childTask);\n }\n }", "public void setVec4(String key, float x, float y, float z, float w)\n {\n checkKeyIsUniform(key);\n NativeLight.setVec4(getNative(), key, x, y, z, w);\n }", "public ApnsServiceBuilder withDelegate(ApnsDelegate delegate) {\n this.delegate = delegate == null ? ApnsDelegate.EMPTY : delegate;\n return this;\n }", "public void updateDownLoadUrl(final String gavc, final String downLoadUrl) {\n final DbArtifact artifact = getArtifact(gavc);\n repositoryHandler.updateDownloadUrl(artifact, downLoadUrl);\n }", "public static Boolean assertFalse(Boolean value, String message) {\n if (Boolean.valueOf(value))\n throw new IllegalStateException(message);\n return value;\n }", "public static XMLGregorianCalendar convertDate(Date date) {\n if (date == null) {\n return null;\n }\n\n GregorianCalendar gc = new GregorianCalendar();\n gc.setTimeInMillis(date.getTime());\n\n try {\n return getDatatypeFactory().newXMLGregorianCalendar(gc);\r\n } catch (DatatypeConfigurationException ex) {\n return null;\n }\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 }", "private void setAnimationProgress(float progress) {\n if (isAlphaUsedForScale()) {\n setColorViewAlpha((int) (progress * MAX_ALPHA));\n } else {\n ViewCompat.setScaleX(mCircleView, progress);\n ViewCompat.setScaleY(mCircleView, progress);\n }\n }", "@Override\n public View getView(int position, View convertView, ViewGroup parent) {\n if (position == super.getCount() && isEnableRefreshing()) {\n return (mFooter);\n }\n return (super.getView(position, convertView, parent));\n }" ]
static expansion helpers
[ "static String expandUriComponent(String source, UriTemplateVariables uriVariables) {\n\t\tif (source == null) {\n\t\t\treturn null;\n\t\t}\n\t\tif (source.indexOf('{') == -1) {\n\t\t\treturn source;\n\t\t}\n\t\tMatcher matcher = NAMES_PATTERN.matcher(source);\n\t\tStringBuffer sb = new StringBuffer();\n\t\twhile (matcher.find()) {\n\t\t\tString match = matcher.group(1);\n\t\t\tString variableName = getVariableName(match);\n\t\t\tObject variableValue = uriVariables.getValue(variableName);\n\t\t\tif (UriTemplateVariables.SKIP_VALUE.equals(variableValue)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tString variableValueString = getVariableValueAsString(variableValue);\n\t\t\tString replacement = Matcher.quoteReplacement(variableValueString);\n\t\t\tmatcher.appendReplacement(sb, replacement);\n\t\t}\n\t\tmatcher.appendTail(sb);\n\t\treturn sb.toString();\n\t}" ]
[ "private static EndpointReferenceType createEPR(String address, SLProperties props) {\n EndpointReferenceType epr = WSAEndpointReferenceUtils.getEndpointReference(address);\n if (props != null) {\n addProperties(epr, props);\n }\n return epr;\n }", "private Collection<? extends ResourceRoot> handleClassPathItems(final DeploymentUnit deploymentUnit) {\n final Set<ResourceRoot> additionalRoots = new HashSet<ResourceRoot>();\n final ArrayDeque<ResourceRoot> toProcess = new ArrayDeque<ResourceRoot>();\n final List<ResourceRoot> resourceRoots = DeploymentUtils.allResourceRoots(deploymentUnit);\n toProcess.addAll(resourceRoots);\n final Set<ResourceRoot> processed = new HashSet<ResourceRoot>(resourceRoots);\n\n while (!toProcess.isEmpty()) {\n final ResourceRoot root = toProcess.pop();\n final List<ResourceRoot> classPathRoots = root.getAttachmentList(Attachments.CLASS_PATH_RESOURCE_ROOTS);\n for(ResourceRoot cpRoot : classPathRoots) {\n if(!processed.contains(cpRoot)) {\n additionalRoots.add(cpRoot);\n toProcess.add(cpRoot);\n processed.add(cpRoot);\n }\n }\n }\n return additionalRoots;\n }", "public static DMatrixRMaj insideSpan(DMatrixRMaj[] span , double min , double max , Random rand ) {\n DMatrixRMaj A = new DMatrixRMaj(span.length,1);\n\n DMatrixRMaj B = new DMatrixRMaj(span[0].getNumElements(),1);\n\n for( int i = 0; i < span.length; i++ ) {\n B.set(span[i]);\n double val = rand.nextDouble()*(max-min)+min;\n CommonOps_DDRM.scale(val,B);\n\n CommonOps_DDRM.add(A,B,A);\n\n }\n\n return A;\n }", "@Override\r\n public String replace(File file, String flickrId, boolean async) throws FlickrException {\r\n Payload payload = new Payload(file, flickrId);\r\n return sendReplaceRequest(async, payload);\r\n }", "public static base_responses update(nitro_service client, onlinkipv6prefix resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tonlinkipv6prefix updateresources[] = new onlinkipv6prefix[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new onlinkipv6prefix();\n\t\t\t\tupdateresources[i].ipv6prefix = resources[i].ipv6prefix;\n\t\t\t\tupdateresources[i].onlinkprefix = resources[i].onlinkprefix;\n\t\t\t\tupdateresources[i].autonomusprefix = resources[i].autonomusprefix;\n\t\t\t\tupdateresources[i].depricateprefix = resources[i].depricateprefix;\n\t\t\t\tupdateresources[i].decrementprefixlifetimes = resources[i].decrementprefixlifetimes;\n\t\t\t\tupdateresources[i].prefixvalidelifetime = resources[i].prefixvalidelifetime;\n\t\t\t\tupdateresources[i].prefixpreferredlifetime = resources[i].prefixpreferredlifetime;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "public static FileOutputStream openResultFileOuputStream(\n\t\t\tPath resultDirectory, String filename) throws IOException {\n\t\tPath filePath = resultDirectory.resolve(filename);\n\t\treturn new FileOutputStream(filePath.toFile());\n\t}", "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 }", "private Set<Annotation> getFieldAnnotations(final Class<?> clazz)\n\t{\n\t\ttry\n\t\t{\n\t\t\treturn new LinkedHashSet<Annotation>(asList(clazz.getDeclaredField(propertyName).getAnnotations()));\n\t\t}\n\t\tcatch (final NoSuchFieldException e)\n\t\t{\n\t\t\tif (clazz.getSuperclass() != null)\n\t\t\t{\n\t\t\t\treturn getFieldAnnotations(clazz.getSuperclass());\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tlogger.debug(\"Cannot find propertyName: {}, declaring class: {}\", propertyName, clazz);\n\t\t\t\treturn new LinkedHashSet<Annotation>(0);\n\t\t\t}\n\t\t}\n\t}", "public void addChildTask(Task child)\n {\n child.m_parent = this;\n m_children.add(child);\n setSummary(true);\n\n if (getParentFile().getProjectConfig().getAutoOutlineLevel() == true)\n {\n child.setOutlineLevel(Integer.valueOf(NumberHelper.getInt(getOutlineLevel()) + 1));\n }\n }" ]
Returns the value of the identified field as a Date. Time fields returned from an FQL query are expressed in terms of seconds since midnight, January 1, 1970 UTC. @param fieldName the name of the field @return the value of the field as a Date @throws FqlException if the field's value cannot be expressed as a long value from which a Date object can be constructed.
[ "public Date getTime(String fieldName) {\n\t\ttry {\n\t\t\tif (hasValue(fieldName)) {\n\t\t\t\treturn new Date(Long.valueOf(String.valueOf(resultMap.get(fieldName))) * 1000);\n\t\t\t} else {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t} catch (NumberFormatException e) {\n\t\t\tthrow new FqlException(\"Field '\" + fieldName +\"' is not a time.\", e);\n\t\t}\n\t}" ]
[ "public CollectionRequest<Task> stories(String task) {\n \n String path = String.format(\"/tasks/%s/stories\", task);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }", "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 }", "@Override\n public void setActive(boolean active) {\n this.active = active;\n\n if (parent != null) {\n fireCollapsibleHandler();\n removeStyleName(CssName.ACTIVE);\n if (header != null) {\n header.removeStyleName(CssName.ACTIVE);\n }\n if (active) {\n if (parent != null && parent.isAccordion()) {\n parent.clearActive();\n }\n addStyleName(CssName.ACTIVE);\n\n if (header != null) {\n header.addStyleName(CssName.ACTIVE);\n }\n }\n\n if (body != null) {\n body.setDisplay(active ? Display.BLOCK : Display.NONE);\n }\n } else {\n GWT.log(\"Please make sure that the Collapsible parent is attached or existed.\", new IllegalStateException());\n }\n }", "@NonNull\n public static String placeholders(final int numberOfPlaceholders) {\n if (numberOfPlaceholders == 1) {\n return \"?\"; // fffast\n } else if (numberOfPlaceholders == 0) {\n return \"\";\n } else if (numberOfPlaceholders < 0) {\n throw new IllegalArgumentException(\"numberOfPlaceholders must be >= 0, but was = \" + numberOfPlaceholders);\n }\n\n final StringBuilder stringBuilder = new StringBuilder((numberOfPlaceholders * 2) - 1);\n\n for (int i = 0; i < numberOfPlaceholders; i++) {\n stringBuilder.append('?');\n\n if (i != numberOfPlaceholders - 1) {\n stringBuilder.append(',');\n }\n }\n\n return stringBuilder.toString();\n }", "public double multi8p(int x, int y, double masc) {\n int aR = getIntComponent0(x - 1, y - 1);\n int bR = getIntComponent0(x - 1, y);\n int cR = getIntComponent0(x - 1, y + 1);\n int aG = getIntComponent1(x - 1, y - 1);\n int bG = getIntComponent1(x - 1, y);\n int cG = getIntComponent1(x - 1, y + 1);\n int aB = getIntComponent1(x - 1, y - 1);\n int bB = getIntComponent1(x - 1, y);\n int cB = getIntComponent1(x - 1, y + 1);\n\n\n int dR = getIntComponent0(x, y - 1);\n int eR = getIntComponent0(x, y);\n int fR = getIntComponent0(x, y + 1);\n int dG = getIntComponent1(x, y - 1);\n int eG = getIntComponent1(x, y);\n int fG = getIntComponent1(x, y + 1);\n int dB = getIntComponent1(x, y - 1);\n int eB = getIntComponent1(x, y);\n int fB = getIntComponent1(x, y + 1);\n\n\n int gR = getIntComponent0(x + 1, y - 1);\n int hR = getIntComponent0(x + 1, y);\n int iR = getIntComponent0(x + 1, y + 1);\n int gG = getIntComponent1(x + 1, y - 1);\n int hG = getIntComponent1(x + 1, y);\n int iG = getIntComponent1(x + 1, y + 1);\n int gB = getIntComponent1(x + 1, y - 1);\n int hB = getIntComponent1(x + 1, y);\n int iB = getIntComponent1(x + 1, y + 1);\n\n double rgb = 0;\n\n rgb = ((aR * masc) + (bR * masc) + (cR * masc) +\n (dR * masc) + (eR * masc) + (fR * masc) +\n (gR * masc) + (hR * masc) + (iR * masc));\n\n return (rgb);\n\n }", "public static base_response kill(nitro_service client, systemsession resource) throws Exception {\n\t\tsystemsession killresource = new systemsession();\n\t\tkillresource.sid = resource.sid;\n\t\tkillresource.all = resource.all;\n\t\treturn killresource.perform_operation(client,\"kill\");\n\t}", "protected I_CmsSearchConfigurationFacetField parseFieldFacet(JSONObject fieldFacetObject) {\n\n try {\n String field = fieldFacetObject.getString(JSON_KEY_FACET_FIELD);\n String name = parseOptionalStringValue(fieldFacetObject, JSON_KEY_FACET_NAME);\n String label = parseOptionalStringValue(fieldFacetObject, JSON_KEY_FACET_LABEL);\n Integer minCount = parseOptionalIntValue(fieldFacetObject, JSON_KEY_FACET_MINCOUNT);\n Integer limit = parseOptionalIntValue(fieldFacetObject, JSON_KEY_FACET_LIMIT);\n String prefix = parseOptionalStringValue(fieldFacetObject, JSON_KEY_FACET_PREFIX);\n String sorder = parseOptionalStringValue(fieldFacetObject, JSON_KEY_FACET_ORDER);\n I_CmsSearchConfigurationFacet.SortOrder order;\n try {\n order = I_CmsSearchConfigurationFacet.SortOrder.valueOf(sorder);\n } catch (Exception e) {\n order = null;\n }\n String filterQueryModifier = parseOptionalStringValue(fieldFacetObject, JSON_KEY_FACET_FILTERQUERYMODIFIER);\n Boolean isAndFacet = parseOptionalBooleanValue(fieldFacetObject, JSON_KEY_FACET_ISANDFACET);\n List<String> preselection = parseOptionalStringValues(fieldFacetObject, JSON_KEY_FACET_PRESELECTION);\n Boolean ignoreFilterAllFacetFilters = parseOptionalBooleanValue(\n fieldFacetObject,\n JSON_KEY_FACET_IGNOREALLFACETFILTERS);\n return new CmsSearchConfigurationFacetField(\n field,\n name,\n minCount,\n limit,\n prefix,\n label,\n order,\n filterQueryModifier,\n isAndFacet,\n preselection,\n ignoreFilterAllFacetFilters);\n } catch (JSONException e) {\n LOG.error(\n Messages.get().getBundle().key(Messages.ERR_FIELD_FACET_MANDATORY_KEY_MISSING_1, JSON_KEY_FACET_FIELD),\n e);\n return null;\n }\n }", "public ItemRequest<Project> addMembers(String project) {\n \n String path = String.format(\"/projects/%s/addMembers\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\n }", "private String filterAttributes(String html) {\n\t\tString filteredHtml = html;\n\t\tfor (String attribute : this.filterAttributes) {\n\t\t\tString regex = \"\\\\s\" + attribute + \"=\\\"[^\\\"]*\\\"\";\n\t\t\tPattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);\n\t\t\tMatcher m = p.matcher(html);\n\t\t\tfilteredHtml = m.replaceAll(\"\");\n\t\t}\n\t\treturn filteredHtml;\n\t}" ]
Splits the given string.
[ "public List<String> split(String s) {\n\n List<String> result = new ArrayList<String>();\n\n if (s == null) {\n return result;\n }\n\n boolean seenEscape = false;\n\n // Used to detect if the last char was a separator,\n // in which case we append an empty string\n boolean seenSeparator = false;\n\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < s.length(); i++) {\n seenSeparator = false;\n char c = s.charAt(i);\n if (seenEscape) {\n if (c == escapeChar || c == separator) {\n sb.append(c);\n } else {\n sb.append(escapeChar).append(c);\n }\n seenEscape = false;\n } else {\n if (c == escapeChar) {\n seenEscape = true;\n } else if (c == separator) {\n if (sb.length() == 0 && convertEmptyToNull) {\n result.add(null);\n } else {\n result.add(sb.toString());\n }\n sb.setLength(0);\n seenSeparator = true;\n } else {\n sb.append(c);\n }\n }\n }\n\n // Clean up\n if (seenEscape) {\n sb.append(escapeChar);\n }\n\n if (sb.length() > 0 || seenSeparator) {\n\n if (sb.length() == 0 && convertEmptyToNull) {\n result.add(null);\n } else {\n result.add(sb.toString());\n }\n\n }\n\n return result;\n }" ]
[ "public BlockHeader read(byte[] buffer, int offset, int postHeaderSkipBytes)\n {\n m_offset = offset;\n\n System.arraycopy(buffer, m_offset, m_header, 0, 8);\n m_offset += 8;\n\n int nameLength = FastTrackUtility.getInt(buffer, m_offset);\n m_offset += 4;\n\n if (nameLength < 1 || nameLength > 255)\n {\n throw new UnexpectedStructureException();\n }\n\n m_name = new String(buffer, m_offset, nameLength, CharsetHelper.UTF16LE);\n m_offset += nameLength;\n\n m_columnType = FastTrackUtility.getShort(buffer, m_offset);\n m_offset += 2;\n\n m_flags = FastTrackUtility.getShort(buffer, m_offset);\n m_offset += 2;\n\n m_skip = new byte[postHeaderSkipBytes];\n System.arraycopy(buffer, m_offset, m_skip, 0, postHeaderSkipBytes);\n m_offset += postHeaderSkipBytes;\n\n return this;\n }", "public static boolean isArray(Type type) {\n return (type instanceof GenericArrayType) || (type instanceof Class<?> && ((Class<?>) type).isArray());\n }", "public static void dumpClusters(Cluster currentCluster,\n Cluster finalCluster,\n String outputDirName) {\n dumpClusters(currentCluster, finalCluster, outputDirName, \"\");\n }", "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 }", "private void ensureReferencedPKs(ModelDef modelDef, ReferenceDescriptorDef refDef) throws ConstraintException\r\n {\r\n String targetClassName = refDef.getProperty(PropertyHelper.OJB_PROPERTY_CLASS_REF);\r\n ClassDescriptorDef targetClassDef = modelDef.getClass(targetClassName);\r\n\r\n ensurePKsFromHierarchy(targetClassDef);\r\n }", "private void processCalendarDays(ProjectCalendar calendar, Record root)\n {\n // Retrieve working hours ...\n Record daysOfWeek = root.getChild(\"DaysOfWeek\");\n if (daysOfWeek != null)\n {\n for (Record dayRecord : daysOfWeek.getChildren())\n {\n processCalendarHours(calendar, dayRecord);\n }\n }\n }", "public static void endTrack(final String title){\r\n if(isClosed){ return; }\r\n //--Make Task\r\n final long timestamp = System.currentTimeMillis();\r\n Runnable endTrack = new Runnable(){\r\n public void run(){\r\n assert !isThreaded || control.isHeldByCurrentThread();\r\n //(check name match)\r\n String expected = titleStack.pop();\r\n if(!expected.equalsIgnoreCase(title)){\r\n throw new IllegalArgumentException(\"Track names do not match: expected: \" + expected + \" found: \" + title);\r\n }\r\n //(decrement depth)\r\n depth -= 1;\r\n //(send signal)\r\n handlers.process(null, MessageType.END_TRACK, depth, timestamp);\r\n assert !isThreaded || control.isHeldByCurrentThread();\r\n }\r\n };\r\n //--Run Task\r\n if(isThreaded){\r\n //(case: multithreaded)\r\n long threadId = Thread.currentThread().getId();\r\n attemptThreadControl( threadId, endTrack );\r\n } else {\r\n //(case: no threading)\r\n endTrack.run();\r\n }\r\n }", "private boolean shouldWrapMethodCall(String methodName) {\n if (methodList == null) {\n return true; // Wrap all by default\n }\n\n if (methodList.contains(methodName)) {\n return true; //Wrap a specific method\n }\n\n // If I get to this point, I should not wrap the call.\n return false;\n }", "public double[][] getU() {\n double[][] X = new double[n][n];\n double[][] U = X;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n if (i <= j) {\n U[i][j] = LU[i][j];\n } else {\n U[i][j] = 0.0;\n }\n }\n }\n return X;\n }" ]
allow extension only for testing
[ "@Override\n public ConfigurableRequest createRequest(\n @Nonnull final URI uri,\n @Nonnull final HttpMethod httpMethod) throws IOException {\n HttpRequestBase httpRequest = (HttpRequestBase) createHttpUriRequest(httpMethod, uri);\n return new Request(getHttpClient(), httpRequest, createHttpContext(httpMethod, uri));\n }" ]
[ "private String toRfsName(String name, IconSize size) {\n\n return CmsStringUtil.joinPaths(m_cache.getRepositoryPath(), \"\" + name.hashCode()) + size.getSuffix();\n }", "public static vpntrafficpolicy_vpnglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpntrafficpolicy_vpnglobal_binding obj = new vpntrafficpolicy_vpnglobal_binding();\n\t\tobj.set_name(name);\n\t\tvpntrafficpolicy_vpnglobal_binding response[] = (vpntrafficpolicy_vpnglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public String registerHandler(GFXEventHandler handler) {\n String uuid = UUID.randomUUID().toString();\n handlers.put(uuid, handler);\n return uuid;\n }", "public static void processEntitiesFromWikidataDump(\n\t\t\tEntityDocumentProcessor entityDocumentProcessor) {\n\n\t\t// Controller object for processing dumps:\n\t\tDumpProcessingController dumpProcessingController = new DumpProcessingController(\n\t\t\t\t\"wikidatawiki\");\n\t\tdumpProcessingController.setOfflineMode(OFFLINE_MODE);\n\n\t\t// // Optional: Use another download directory:\n\t\t// dumpProcessingController.setDownloadDirectory(System.getProperty(\"user.dir\"));\n\n\t\t// Should we process historic revisions or only current ones?\n\t\tboolean onlyCurrentRevisions;\n\t\tswitch (DUMP_FILE_MODE) {\n\t\tcase ALL_REVS:\n\t\tcase ALL_REVS_WITH_DAILIES:\n\t\t\tonlyCurrentRevisions = false;\n\t\t\tbreak;\n\t\tcase CURRENT_REVS:\n\t\tcase CURRENT_REVS_WITH_DAILIES:\n\t\tcase JSON:\n\t\tcase JUST_ONE_DAILY_FOR_TEST:\n\t\tdefault:\n\t\t\tonlyCurrentRevisions = true;\n\t\t}\n\n\t\t// Subscribe to the most recent entity documents of type wikibase item:\n\t\tdumpProcessingController.registerEntityDocumentProcessor(\n\t\t\t\tentityDocumentProcessor, null, onlyCurrentRevisions);\n\n\t\t// Also add a timer that reports some basic progress information:\n\t\tEntityTimerProcessor entityTimerProcessor = new EntityTimerProcessor(\n\t\t\t\tTIMEOUT_SEC);\n\t\tdumpProcessingController.registerEntityDocumentProcessor(\n\t\t\t\tentityTimerProcessor, null, onlyCurrentRevisions);\n\n\t\tMwDumpFile dumpFile = null;\n\t\ttry {\n\t\t\t// Start processing (may trigger downloads where needed):\n\t\t\tswitch (DUMP_FILE_MODE) {\n\t\t\tcase ALL_REVS:\n\t\t\tcase CURRENT_REVS:\n\t\t\t\tdumpFile = dumpProcessingController\n\t\t\t\t\t\t.getMostRecentDump(DumpContentType.FULL);\n\t\t\t\tbreak;\n\t\t\tcase ALL_REVS_WITH_DAILIES:\n\t\t\tcase CURRENT_REVS_WITH_DAILIES:\n\t\t\t\tMwDumpFile fullDumpFile = dumpProcessingController\n\t\t\t\t\t\t.getMostRecentDump(DumpContentType.FULL);\n\t\t\t\tMwDumpFile incrDumpFile = dumpProcessingController\n\t\t\t\t\t\t.getMostRecentDump(DumpContentType.DAILY);\n\t\t\t\tlastDumpFileName = fullDumpFile.getProjectName() + \"-\"\n\t\t\t\t\t\t+ incrDumpFile.getDateStamp() + \".\"\n\t\t\t\t\t\t+ fullDumpFile.getDateStamp();\n\t\t\t\tdumpProcessingController.processAllRecentRevisionDumps();\n\t\t\t\tbreak;\n\t\t\tcase JSON:\n\t\t\t\tdumpFile = dumpProcessingController\n\t\t\t\t\t\t.getMostRecentDump(DumpContentType.JSON);\n\t\t\t\tbreak;\n\t\t\tcase JUST_ONE_DAILY_FOR_TEST:\n\t\t\t\tdumpFile = dumpProcessingController\n\t\t\t\t\t\t.getMostRecentDump(DumpContentType.DAILY);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new RuntimeException(\"Unsupported dump processing type \"\n\t\t\t\t\t\t+ DUMP_FILE_MODE);\n\t\t\t}\n\n\t\t\tif (dumpFile != null) {\n\t\t\t\tlastDumpFileName = dumpFile.getProjectName() + \"-\"\n\t\t\t\t\t\t+ dumpFile.getDateStamp();\n\t\t\t\tdumpProcessingController.processDump(dumpFile);\n\t\t\t}\n\t\t} catch (TimeoutException e) {\n\t\t\t// The timer caused a time out. Continue and finish normally.\n\t\t}\n\n\t\t// Print final timer results:\n\t\tentityTimerProcessor.close();\n\t}", "public void beforeClose(PBStateEvent event)\r\n {\r\n /*\r\n arminw:\r\n this is a workaround for use in managed environments. When a PB instance is used\r\n within a container a PB.close call is done when leave the container method. This close\r\n the PB handle (but the real instance is still in use) and the PB listener are notified.\r\n But the JTA tx was not committed at\r\n this point in time and the session cache should not be cleared, because the updated/new\r\n objects will be pushed to the real cache on commit call (if we clear, nothing to push).\r\n So we check if the real broker is in a local tx (in this case we are in a JTA tx and the handle\r\n is closed), if true we don't reset the session cache.\r\n */\r\n if(!broker.isInTransaction())\r\n {\r\n if(log.isDebugEnabled()) log.debug(\"Clearing the session cache\");\r\n resetSessionCache();\r\n }\r\n }", "private void store(final PrintJobStatus printJobStatus) throws JSONException {\n JSONObject metadata = new JSONObject();\n metadata.put(JSON_REQUEST_DATA, printJobStatus.getEntry().getRequestData().getInternalObj());\n metadata.put(JSON_STATUS, printJobStatus.getStatus().toString());\n metadata.put(JSON_START_DATE, printJobStatus.getStartTime());\n metadata.put(JSON_REQUEST_COUNT, printJobStatus.getRequestCount());\n if (printJobStatus.getCompletionDate() != null) {\n metadata.put(JSON_COMPLETION_DATE, printJobStatus.getCompletionTime());\n }\n metadata.put(JSON_ACCESS_ASSERTION, this.assertionPersister.marshal(printJobStatus.getAccess()));\n if (printJobStatus.getError() != null) {\n metadata.put(JSON_ERROR, printJobStatus.getError());\n }\n if (printJobStatus.getResult() != null) {\n metadata.put(JSON_REPORT_URI, printJobStatus.getResult().getReportURIString());\n metadata.put(JSON_FILENAME, printJobStatus.getResult().getFileName());\n metadata.put(JSON_FILE_EXT, printJobStatus.getResult().getFileExtension());\n metadata.put(JSON_MIME_TYPE, printJobStatus.getResult().getMimeType());\n }\n this.registry.put(RESULT_METADATA + printJobStatus.getReferenceId(), metadata);\n }", "@Nullable\n @VisibleForTesting\n protected PolygonSymbolizer createPolygonSymbolizer(final PJsonObject styleJson) {\n if (this.allowNullSymbolizer && !styleJson.has(JSON_FILL_COLOR)) {\n return null;\n }\n\n final PolygonSymbolizer symbolizer = this.styleBuilder.createPolygonSymbolizer();\n symbolizer.setFill(createFill(styleJson));\n\n symbolizer.setStroke(createStroke(styleJson, false));\n\n return symbolizer;\n }", "public Object remove(String name) {\n\t\tBean bean = beans.get(name);\n\t\tif (null != bean) {\n\t\t\tbeans.remove(name);\n\t\t\tbean.destructionCallback.run();\n\t\t\treturn bean.object;\n\t\t}\n\t\treturn null;\n\t}", "public List<NodeInfo> getNodes() {\n final URI uri = uriWithPath(\"./nodes/\");\n return Arrays.asList(this.rt.getForObject(uri, NodeInfo[].class));\n }" ]
Get a list of people in a given photo. @param photoId @throws FlickrException
[ "public PersonTagList<PersonTag> getList(String photoId) throws FlickrException {\r\n\r\n // Delegating this to photos.people.PeopleInterface - Naming standard would be to use PeopleInterface but having 2 the same name can cause issues\r\n com.flickr4java.flickr.photos.people.PeopleInterface pi = new com.flickr4java.flickr.photos.people.PeopleInterface(apiKey, sharedSecret, transportAPI);\r\n return pi.getList(photoId);\r\n }" ]
[ "static int createDeliverable(String path, String originalFileName, String fileFamily, Integer jobId, DbConn cnx)\n {\n QueryResult qr = cnx.runUpdate(\"deliverable_insert\", fileFamily, path, jobId, originalFileName, UUID.randomUUID().toString());\n return qr.getGeneratedId();\n }", "@Nullable\n public ByteIterable get2(@NotNull final Transaction txn, @NotNull final ByteIterable second) {\n return this.second.get(txn, second);\n }", "private double goldenMean(double a, double b) {\r\n if (geometric) {\r\n return a * Math.pow(b / a, GOLDEN_SECTION);\r\n } else {\r\n return a + (b - a) * GOLDEN_SECTION;\r\n }\r\n }", "@Override\n public void start(String[] arguments) {\n boolean notStarted = !started.getAndSet(true);\n if (notStarted) {\n start(new MultiInstanceWorkloadStrategy(factory, name, arguments, endpointRegistry, execService));\n }\n }", "public static Integer getDurationValue(ProjectProperties properties, Duration duration)\n {\n Integer result;\n if (duration == null)\n {\n result = null;\n }\n else\n {\n if (duration.getUnits() != TimeUnit.MINUTES)\n {\n duration = duration.convertUnits(TimeUnit.MINUTES, properties);\n }\n result = Integer.valueOf((int) duration.getDuration());\n }\n return (result);\n }", "public static base_response unset(nitro_service client, csparameter resource, String[] args) throws Exception{\n\t\tcsparameter unsetresource = new csparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "protected boolean waitForJobs() throws InterruptedException {\n final Pair<Long, Job> peekPair;\n try (Guard ignored = timeQueue.lock()) {\n peekPair = timeQueue.peekPair();\n }\n if (peekPair == null) {\n awake.acquire();\n return true;\n }\n final long timeout = Long.MAX_VALUE - peekPair.getFirst() - System.currentTimeMillis();\n if (timeout < 0) {\n return false;\n }\n return awake.tryAcquire(timeout, TimeUnit.MILLISECONDS);\n }", "protected OJBIterator getIteratorFromQuery(Query query, ClassDescriptor cld) throws PersistenceBrokerException\n {\n RsIteratorFactory factory = RsIteratorFactoryImpl.getInstance();\n OJBIterator result = getRsIteratorFromQuery(query, cld, factory);\n\n if (query.usePaging())\n {\n result = new PagingIterator(result, query.getStartAtIndex(), query.getEndAtIndex());\n }\n return result;\n }", "static EntityIdValue fromId(String id, String siteIri) {\n\t\tswitch (guessEntityTypeFromId(id)) {\n\t\t\tcase EntityIdValueImpl.JSON_ENTITY_TYPE_ITEM:\n\t\t\t\treturn new ItemIdValueImpl(id, siteIri);\n\t\t\tcase EntityIdValueImpl.JSON_ENTITY_TYPE_PROPERTY:\n\t\t\t\treturn new PropertyIdValueImpl(id, siteIri);\n\t\t\tcase EntityIdValueImpl.JSON_ENTITY_TYPE_LEXEME:\n\t\t\t\treturn new LexemeIdValueImpl(id, siteIri);\n\t\t\tcase EntityIdValueImpl.JSON_ENTITY_TYPE_FORM:\n\t\t\t\treturn new FormIdValueImpl(id, siteIri);\n\t\t\tcase EntityIdValueImpl.JSON_ENTITY_TYPE_SENSE:\n\t\t\t\treturn new SenseIdValueImpl(id, siteIri);\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalArgumentException(\"Entity id \\\"\" + id + \"\\\" is not supported.\");\n\t\t}\n\t}" ]
Sets the bottom padding character for all cells in the row. @param paddingBottomChar new padding character, ignored if null @return this to allow chaining
[ "public AT_Row setPaddingBottomChar(Character paddingBottomChar) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingBottomChar(paddingBottomChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}" ]
[ "public static bridgegroup_vlan_binding[] get(nitro_service service, Long id) throws Exception{\n\t\tbridgegroup_vlan_binding obj = new bridgegroup_vlan_binding();\n\t\tobj.set_id(id);\n\t\tbridgegroup_vlan_binding response[] = (bridgegroup_vlan_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static String keyVersionToString(ByteArray key,\n Map<Value, Set<ClusterNode>> versionMap,\n String storeName,\n Integer partitionId) {\n StringBuilder record = new StringBuilder();\n for (Map.Entry<Value, Set<ClusterNode>> versionSet : versionMap.entrySet()) {\n Value value = versionSet.getKey();\n Set<ClusterNode> nodeSet = versionSet.getValue();\n\n record.append(\"BAD_KEY,\");\n record.append(storeName + \",\");\n record.append(partitionId + \",\");\n record.append(ByteUtils.toHexString(key.get()) + \",\");\n record.append(nodeSet.toString().replace(\", \", \";\") + \",\");\n record.append(value.toString());\n }\n return record.toString();\n }", "private static LblTree createTree(TreeWalker walker) {\n\t\tNode parent = walker.getCurrentNode();\n\t\tLblTree node = new LblTree(parent.getNodeName(), -1); // treeID = -1\n\t\tfor (Node n = walker.firstChild(); n != null; n = walker.nextSibling()) {\n\t\t\tnode.add(createTree(walker));\n\t\t}\n\t\twalker.setCurrentNode(parent);\n\t\treturn node;\n\t}", "public Script[] getScripts(Integer type) {\n ArrayList<Script> returnData = new ArrayList<>();\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = SQLService.getInstance().getConnection()) {\n\n statement = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_SCRIPT +\n \" ORDER BY \" + Constants.GENERIC_ID);\n if (type != null) {\n statement = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_SCRIPT +\n \" WHERE \" + Constants.SCRIPT_TYPE + \"= ?\" +\n \" ORDER BY \" + Constants.GENERIC_ID);\n statement.setInt(1, type);\n }\n\n logger.info(\"Query: {}\", statement);\n\n results = statement.executeQuery();\n while (results.next()) {\n returnData.add(scriptFromSQLResult(results));\n }\n } catch (Exception e) {\n\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return returnData.toArray(new Script[0]);\n }", "@Override\n public String printHelp() {\n List<CommandLineParser<CI>> parsers = getChildParsers();\n if (parsers != null && parsers.size() > 0) {\n StringBuilder sb = new StringBuilder();\n sb.append(processedCommand.printHelp(helpNames()))\n .append(Config.getLineSeparator())\n .append(processedCommand.name())\n .append(\" commands:\")\n .append(Config.getLineSeparator());\n\n int maxLength = 0;\n\n for (CommandLineParser child : parsers) {\n int length = child.getProcessedCommand().name().length();\n if (length > maxLength) {\n maxLength = length;\n }\n }\n\n for (CommandLineParser child : parsers) {\n sb.append(child.getFormattedCommand(4, maxLength + 2))\n .append(Config.getLineSeparator());\n }\n\n return sb.toString();\n }\n else\n return processedCommand.printHelp(helpNames());\n }", "public String addressPath() {\n if (isLeaf) {\n ManagementModelNode parent = (ManagementModelNode)getParent();\n return parent.addressPath();\n }\n\n StringBuilder builder = new StringBuilder();\n for (Object pathElement : getUserObjectPath()) {\n UserObject userObj = (UserObject)pathElement;\n if (userObj.isRoot()) { // don't want to escape root\n builder.append(userObj.getName());\n continue;\n }\n\n builder.append(userObj.getName());\n builder.append(\"=\");\n builder.append(userObj.getEscapedValue());\n builder.append(\"/\");\n }\n\n return builder.toString();\n }", "public static final String vertexAsString(Vertex vertex, int depth, String withEdgesOfLabel)\n {\n StringBuilder sb = new StringBuilder();\n vertexAsString(vertex, depth, withEdgesOfLabel, sb, 0, new HashSet<>());\n return sb.toString();\n }", "public int evaluate(FieldContainer container)\n {\n //\n // First step - determine the list of criteria we are should use\n //\n List<GraphicalIndicatorCriteria> criteria;\n if (container instanceof Task)\n {\n Task task = (Task) container;\n if (NumberHelper.getInt(task.getUniqueID()) == 0)\n {\n if (m_projectSummaryInheritsFromSummaryRows == false)\n {\n criteria = m_projectSummaryCriteria;\n }\n else\n {\n if (m_summaryRowsInheritFromNonSummaryRows == false)\n {\n criteria = m_summaryRowCriteria;\n }\n else\n {\n criteria = m_nonSummaryRowCriteria;\n }\n }\n }\n else\n {\n if (task.getSummary() == true)\n {\n if (m_summaryRowsInheritFromNonSummaryRows == false)\n {\n criteria = m_summaryRowCriteria;\n }\n else\n {\n criteria = m_nonSummaryRowCriteria;\n }\n }\n else\n {\n criteria = m_nonSummaryRowCriteria;\n }\n }\n }\n else\n {\n // It is possible to have a resource summary row, but at the moment\n // I can't see how you can determine this.\n criteria = m_nonSummaryRowCriteria;\n }\n\n //\n // Now we have the criteria, evaluate each one until we get a result\n //\n int result = -1;\n for (GraphicalIndicatorCriteria gic : criteria)\n {\n result = gic.evaluate(container);\n if (result != -1)\n {\n break;\n }\n }\n\n //\n // If we still don't have a result at the end, return the\n // default value, which is 0\n //\n if (result == -1)\n {\n result = 0;\n }\n\n return (result);\n }", "protected String buildErrorSetMsg(Object obj, Object value, Field aField)\r\n {\r\n String eol = SystemUtils.LINE_SEPARATOR;\r\n StringBuffer buf = new StringBuffer();\r\n buf\r\n .append(eol + \"[try to set 'object value' in 'target object'\")\r\n .append(eol + \"target obj class: \" + (obj != null ? obj.getClass().getName() : null))\r\n .append(eol + \"target field name: \" + (aField != null ? aField.getName() : null))\r\n .append(eol + \"target field type: \" + (aField != null ? aField.getType() : null))\r\n .append(eol + \"target field declared in: \" + (aField != null ? aField.getDeclaringClass().getName() : null))\r\n .append(eol + \"object value class: \" + (value != null ? value.getClass().getName() : null))\r\n .append(eol + \"object value: \" + (value != null ? value : null))\r\n .append(eol + \"]\");\r\n return buf.toString();\r\n }" ]
Emit a event object with parameters and force all listeners to be called asynchronously. @param event the target event @param args the arguments passed in @see #emit(EventObject, Object...)
[ "public EventBus emitAsync(EventObject event, Object... args) {\n return _emitWithOnceBus(eventContextAsync(event, args));\n }" ]
[ "public void setParent(ProjectCalendar calendar)\n {\n // I've seen a malformed MSPDI file which sets the parent calendar to itself.\n // Silently ignore this here.\n if (calendar != this)\n {\n if (getParent() != null)\n {\n getParent().removeDerivedCalendar(this);\n }\n\n super.setParent(calendar);\n\n if (calendar != null)\n {\n calendar.addDerivedCalendar(this);\n }\n clearWorkingDateCache();\n }\n }", "private List<UDFAssignmentType> writeUDFType(FieldTypeClass type, FieldContainer mpxj)\n {\n List<UDFAssignmentType> out = new ArrayList<UDFAssignmentType>();\n for (CustomField cf : m_sortedCustomFieldsList)\n {\n FieldType fieldType = cf.getFieldType();\n if (fieldType != null && type == fieldType.getFieldTypeClass())\n {\n Object value = mpxj.getCachedValue(fieldType);\n if (FieldTypeHelper.valueIsNotDefault(fieldType, value))\n {\n UDFAssignmentType udf = m_factory.createUDFAssignmentType();\n udf.setTypeObjectId(FieldTypeHelper.getFieldID(fieldType));\n setUserFieldValue(udf, fieldType.getDataType(), value);\n out.add(udf);\n }\n }\n }\n return out;\n }", "protected List<File> getRecursiveThriftFiles(MavenProject project, String outputDirectory) throws IOException {\n return getRecursiveThriftFiles(project, outputDirectory, new ArrayList<File>());\n }", "public final TagConfiguration.Builder configureTag( Class<? extends Annotation> tagAnnotation ) {\n TagConfiguration configuration = new TagConfiguration( tagAnnotation );\n tagConfigurations.put( tagAnnotation, configuration );\n return new TagConfiguration.Builder( configuration );\n }", "public boolean removeChildObjectByName(final String name) {\n if (null != name && !name.isEmpty()) {\n GVRSceneObject found = null;\n for (GVRSceneObject child : mChildren) {\n GVRSceneObject object = child.getSceneObjectByName(name);\n if (object != null) {\n found = object;\n break;\n }\n }\n if (found != null) {\n removeChildObject(found);\n return true;\n }\n }\n return false;\n }", "public void setBorderWidth(int borderWidth) {\n\t\tthis.borderWidth = borderWidth;\n\t\tif(paintBorder != null)\n\t\t\tpaintBorder.setStrokeWidth(borderWidth);\n\t\trequestLayout();\n\t\tinvalidate();\n\t}", "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 }", "@Override\n public void solve(DMatrixRMaj B, DMatrixRMaj X) {\n blockB.reshape(B.numRows,B.numCols,false);\n MatrixOps_DDRB.convert(B,blockB);\n\n // since overwrite B is true X does not need to be passed in\n alg.solve(blockB,null);\n\n MatrixOps_DDRB.convert(blockB,X);\n }", "public synchronized void setDeviceName(String name) {\n if (name.getBytes().length > DEVICE_NAME_LENGTH) {\n throw new IllegalArgumentException(\"name cannot be more than \" + DEVICE_NAME_LENGTH + \" bytes long\");\n }\n Arrays.fill(announcementBytes, DEVICE_NAME_OFFSET, DEVICE_NAME_LENGTH, (byte)0);\n System.arraycopy(name.getBytes(), 0, announcementBytes, DEVICE_NAME_OFFSET, name.getBytes().length);\n }" ]
Convert this update description to an update document. @return an update document with the appropriate $set and $unset documents.
[ "public BsonDocument toUpdateDocument() {\n final List<BsonElement> unsets = new ArrayList<>();\n for (final String removedField : this.removedFields) {\n unsets.add(new BsonElement(removedField, new BsonBoolean(true)));\n }\n final BsonDocument updateDocument = new BsonDocument();\n\n if (this.updatedFields.size() > 0) {\n updateDocument.append(\"$set\", this.updatedFields);\n }\n\n if (unsets.size() > 0) {\n updateDocument.append(\"$unset\", new BsonDocument(unsets));\n }\n\n return updateDocument;\n }" ]
[ "public void updateInfo(BoxWebLink.Info info) {\n URL url = WEB_LINK_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"PUT\");\n request.setBody(info.getPendingChanges());\n String body = info.getPendingChanges();\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n info.update(jsonObject);\n }", "public static String getTabularData(String[] labels, String[][] data, int padding) {\n int[] size = new int[labels.length];\n \n for (int i = 0; i < labels.length; i++) {\n size[i] = labels[i].length() + padding;\n }\n \n for (String[] row : data) {\n for (int i = 0; i < labels.length; i++) {\n if (row[i].length() >= size[i]) {\n size[i] = row[i].length() + padding;\n }\n }\n }\n \n StringBuffer tabularData = new StringBuffer();\n \n for (int i = 0; i < labels.length; i++) {\n tabularData.append(labels[i]);\n tabularData.append(fill(' ', size[i] - labels[i].length()));\n }\n \n tabularData.append(\"\\n\");\n \n for (int i = 0; i < labels.length; i++) {\n tabularData.append(fill('=', size[i] - 1)).append(\" \");\n }\n \n tabularData.append(\"\\n\");\n \n \n for (String[] row : data) {\n for (int i = 0; i < labels.length; i++) {\n tabularData.append(row[i]);\n tabularData.append(fill(' ', size[i] - row[i].length()));\n }\n \n tabularData.append(\"\\n\");\n }\n \n return tabularData.toString();\n }", "@Override\n public ActivityInterface getActivityInterface() {\n if (activityInterface == null) {\n activityInterface = new ActivityInterface(apiKey, sharedSecret, transport);\n }\n return activityInterface;\n }", "public static Node addPartitionsToNode(final Node node, final Set<Integer> donatedPartitions) {\n List<Integer> deepCopy = new ArrayList<Integer>(node.getPartitionIds());\n deepCopy.addAll(donatedPartitions);\n Collections.sort(deepCopy);\n return updateNode(node, deepCopy);\n }", "public static boolean isConstant(Expression expression, Object expected) {\r\n return expression instanceof ConstantExpression && expected.equals(((ConstantExpression) expression).getValue());\r\n }", "public synchronized Set<RegistrationPoint> getRegistrationPoints() {\n Set<RegistrationPoint> result = new HashSet<>();\n for (List<RegistrationPoint> registrationPoints : registrationPoints.values()) {\n result.addAll(registrationPoints);\n }\n return Collections.unmodifiableSet(result);\n }", "public static void validate(final ArtifactQuery artifactQuery) {\n final Pattern invalidChars = Pattern.compile(\"[^A-Fa-f0-9]\");\n if(artifactQuery.getUser() == null ||\n \t\tartifactQuery.getUser().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [user] missing\")\n .build());\n }\n if( artifactQuery.getStage() != 0 && artifactQuery.getStage() !=1 ){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Invalid [stage] value (supported 0 | 1)\")\n .build());\n }\n if(artifactQuery.getName() == null ||\n \t\tartifactQuery.getName().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [name] missing, it should be the file name\")\n .build());\n }\n if(artifactQuery.getSha256() == null ||\n artifactQuery.getSha256().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [sha256] missing\")\n .build());\n }\n if(artifactQuery.getSha256().length() < 64 || invalidChars.matcher(artifactQuery.getSha256()).find()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Invalid file checksum value\")\n .build());\n }\n if(artifactQuery.getType() == null ||\n \t\tartifactQuery.getType().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [type] missing\")\n .build());\n }\n }", "public void open(File versionDir) {\n /* acquire modification lock */\n fileModificationLock.writeLock().lock();\n try {\n /* check that the store is currently closed */\n if(isOpen)\n throw new IllegalStateException(\"Attempt to open already open store.\");\n\n // Find version directory from symbolic link or max version id\n if(versionDir == null) {\n versionDir = ReadOnlyUtils.getCurrentVersion(storeDir);\n\n if(versionDir == null)\n versionDir = new File(storeDir, \"version-0\");\n }\n\n // Set the max version id\n long versionId = ReadOnlyUtils.getVersionId(versionDir);\n if(versionId == -1) {\n throw new VoldemortException(\"Unable to parse id from version directory \"\n + versionDir.getAbsolutePath());\n }\n Utils.mkdirs(versionDir);\n\n // Validate symbolic link, and create it if it doesn't already exist\n Utils.symlink(versionDir.getAbsolutePath(), storeDir.getAbsolutePath() + File.separator + \"latest\");\n this.fileSet = new ChunkedFileSet(versionDir, routingStrategy, nodeId, maxValueBufferAllocationSize);\n storeVersionManager.syncInternalStateFromFileSystem(false);\n this.lastSwapped = System.currentTimeMillis();\n this.isOpen = true;\n } catch(IOException e) {\n logger.error(\"Error in opening store\", e);\n } finally {\n fileModificationLock.writeLock().unlock();\n }\n }", "public DiscreteInterval plus(DiscreteInterval other) {\n return new DiscreteInterval(this.min + other.min, this.max + other.max);\n }" ]
Returns the number of rows within this association. @return the number of rows within this association
[ "public int size() {\n\t\tint size = cleared ? 0 : snapshot.size();\n\t\tfor ( Map.Entry<RowKey,AssociationOperation> op : currentState.entrySet() ) {\n\t\t\tswitch ( op.getValue().getType() ) {\n\t\t\t\tcase PUT:\n\t\t\t\t\tif ( cleared || !snapshot.containsKey( op.getKey() ) ) {\n\t\t\t\t\t\tsize++;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase REMOVE:\n\t\t\t\t\tif ( !cleared && snapshot.containsKey( op.getKey() ) ) {\n\t\t\t\t\t\tsize--;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn size;\n\t}" ]
[ "protected void addAlias(MonolingualTextValue alias) {\n String lang = alias.getLanguageCode();\n AliasesWithUpdate currentAliasesUpdate = newAliases.get(lang);\n \n NameWithUpdate currentLabel = newLabels.get(lang);\n // If there isn't any label for that language, put the alias there\n if (currentLabel == null) {\n newLabels.put(lang, new NameWithUpdate(alias, true));\n // If the new alias is equal to the current label, skip it\n } else if (!currentLabel.value.equals(alias)) {\n \tif (currentAliasesUpdate == null) {\n \t\tcurrentAliasesUpdate = new AliasesWithUpdate(new ArrayList<MonolingualTextValue>(), true);\n \t}\n \tList<MonolingualTextValue> currentAliases = currentAliasesUpdate.aliases;\n \tif(!currentAliases.contains(alias)) {\n \t\tcurrentAliases.add(alias);\n \t\tcurrentAliasesUpdate.added.add(alias);\n \t\tcurrentAliasesUpdate.write = true;\n \t}\n \tnewAliases.put(lang, currentAliasesUpdate);\n }\n }", "private SynchroTable readTableHeader(byte[] header)\n {\n SynchroTable result = null;\n String tableName = DatatypeConverter.getSimpleString(header, 0);\n if (!tableName.isEmpty())\n {\n int offset = DatatypeConverter.getInt(header, 40);\n result = new SynchroTable(tableName, offset);\n }\n return result;\n }", "public static Timer getNamedTimer(String timerName, int todoFlags) {\n\t\treturn getNamedTimer(timerName, todoFlags, Thread.currentThread()\n\t\t\t\t.getId());\n\t}", "public Set<String> getTags() {\r\n Set<String> tags = new HashSet<String>(classIndex.objectsList());\r\n tags.remove(flags.backgroundSymbol);\r\n return tags;\r\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}", "private Iterable<BoxRetentionPolicyAssignment.Info> getAssignments(String type, int limit, String ... fields) {\r\n QueryStringBuilder queryString = new QueryStringBuilder();\r\n if (type != null) {\r\n queryString.appendParam(\"type\", type);\r\n }\r\n if (fields.length > 0) {\r\n queryString.appendParam(\"fields\", fields);\r\n }\r\n URL url = ASSIGNMENTS_URL_TEMPLATE.buildWithQuery(getAPI().getBaseURL(), queryString.toString(), getID());\r\n return new BoxResourceIterable<BoxRetentionPolicyAssignment.Info>(getAPI(), url, limit) {\r\n\r\n @Override\r\n protected BoxRetentionPolicyAssignment.Info factory(JsonObject jsonObject) {\r\n BoxRetentionPolicyAssignment assignment\r\n = new BoxRetentionPolicyAssignment(getAPI(), jsonObject.get(\"id\").asString());\r\n return assignment.new Info(jsonObject);\r\n }\r\n\r\n };\r\n }", "public static responderpolicy[] get(nitro_service service) throws Exception{\n\t\tresponderpolicy obj = new responderpolicy();\n\t\tresponderpolicy[] response = (responderpolicy[])obj.get_resources(service);\n\t\treturn response;\n\t}", "private Map<Integer, List<Row>> createExceptionAssignmentMap(List<Row> rows)\n {\n Map<Integer, List<Row>> map = new HashMap<Integer, List<Row>>();\n for (Row row : rows)\n {\n Integer calendarID = row.getInteger(\"ID\");\n String exceptions = row.getString(\"EXCEPTIONS\");\n map.put(calendarID, createExceptionAssignmentRowList(exceptions));\n }\n return map;\n }", "public void set(final Argument argument) {\n if (argument != null) {\n map.put(argument.getKey(), Collections.singleton(argument));\n }\n }" ]
List the addons already added to an app. @param appName new of the app @return a list of add-ons
[ "public List<Addon> listAppAddons(String appName) {\n return connection.execute(new AppAddonsList(appName), apiKey);\n }" ]
[ "@Override\n public final long getLong(final String key) {\n Long result = optLong(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }", "public PropertiesEnvelope createUserProperties(String userId, AppProperties properties, String aid) throws ApiException {\n ApiResponse<PropertiesEnvelope> resp = createUserPropertiesWithHttpInfo(userId, properties, aid);\n return resp.getData();\n }", "@Override\n public <K, V> StoreClient<K, V> getStoreClient(final String storeName,\n final InconsistencyResolver<Versioned<V>> resolver) {\n // wrap it in LazyStoreClient here so any direct calls to this method\n // returns a lazy client\n return new LazyStoreClient<K, V>(new Callable<StoreClient<K, V>>() {\n\n @Override\n public StoreClient<K, V> call() throws Exception {\n Store<K, V, Object> clientStore = getRawStore(storeName, resolver);\n return new RESTClient<K, V>(storeName, clientStore);\n }\n }, true);\n }", "public String getResourceFilename() {\n switch (resourceType) {\n case ANDROID_ASSETS:\n return assetPath\n .substring(assetPath.lastIndexOf(File.separator) + 1);\n\n case ANDROID_RESOURCE:\n return resourceFilePath.substring(\n resourceFilePath.lastIndexOf(File.separator) + 1);\n\n case LINUX_FILESYSTEM:\n return filePath.substring(filePath.lastIndexOf(File.separator) + 1);\n\n case NETWORK:\n return url.getPath().substring(url.getPath().lastIndexOf(\"/\") + 1);\n\n case INPUT_STREAM:\n return inputStreamName;\n\n default:\n return null;\n }\n }", "private void populateAnnotations(Collection<Annotation> annotations) {\n for (Annotation each : annotations) {\n this.annotations.put(each.annotationType(), each);\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 addProperty(String name, String... values) {\n List<String> valueList = new ArrayList<String>();\n for (String value : values) {\n valueList.add(value.trim());\n }\n properties.put(name.trim(), valueList);\n }", "public AlbumArt requestArtworkFrom(final DataReference artReference, final CdjStatus.TrackType trackType) {\n ensureRunning();\n AlbumArt artwork = findArtInMemoryCaches(artReference); // First check the in-memory artwork caches.\n if (artwork == null) {\n artwork = requestArtworkInternal(artReference, trackType, false);\n }\n return artwork;\n }", "public Project dependsOnArtifact(Artifact artifact)\n {\n Project project = new Project();\n project.setArtifact(artifact); \n project.setInputVariablesName(inputVarName);\n return project;\n }" ]
create a path structure representing the object graph
[ "private Path getPath(PropertyWriter writer, JsonStreamContext sc) {\n LinkedList<PathElement> elements = new LinkedList<>();\n\n if (sc != null) {\n elements.add(new PathElement(writer.getName(), sc.getCurrentValue()));\n sc = sc.getParent();\n }\n\n while (sc != null) {\n if (sc.getCurrentName() != null && sc.getCurrentValue() != null) {\n elements.addFirst(new PathElement(sc.getCurrentName(), sc.getCurrentValue()));\n }\n sc = sc.getParent();\n }\n\n return new Path(elements);\n }" ]
[ "public static snmpalarm[] get(nitro_service service) throws Exception{\n\t\tsnmpalarm obj = new snmpalarm();\n\t\tsnmpalarm[] response = (snmpalarm[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public void setTabs(ArrayList<String>tabs) {\n if (tabs == null || tabs.size() <= 0) return;\n\n if (platformSupportsTabs) {\n ArrayList<String> toAdd;\n if (tabs.size() > MAX_TABS) {\n toAdd = new ArrayList<>(tabs.subList(0, MAX_TABS));\n } else {\n toAdd = tabs;\n }\n this.tabs = toAdd.toArray(new String[0]);\n } else {\n Logger.d(\"Please upgrade com.android.support:design library to v28.0.0 to enable Tabs for App Inbox, dropping Tabs\");\n }\n }", "public static HikariConfig createHikariConfig(CmsParameterConfiguration config, String key) {\n\n Map<String, String> poolMap = Maps.newHashMap();\n for (Map.Entry<String, String> entry : config.entrySet()) {\n String suffix = getPropertyRelativeSuffix(KEY_DATABASE_POOL + \".\" + key, entry.getKey());\n if ((suffix != null) && !CmsStringUtil.isEmptyOrWhitespaceOnly(entry.getValue())) {\n String value = entry.getValue().trim();\n poolMap.put(suffix, value);\n }\n }\n\n // these are for backwards compatibility , all other properties not of the form db.pool.poolname.v11..... are ignored\n String jdbcUrl = poolMap.get(KEY_JDBC_URL);\n String params = poolMap.get(KEY_JDBC_URL_PARAMS);\n String driver = poolMap.get(KEY_JDBC_DRIVER);\n String user = poolMap.get(KEY_USERNAME);\n String password = poolMap.get(KEY_PASSWORD);\n String poolName = OPENCMS_URL_PREFIX + key;\n\n if ((params != null) && (jdbcUrl != null)) {\n jdbcUrl += params;\n }\n\n Properties hikariProps = new Properties();\n\n if (jdbcUrl != null) {\n hikariProps.put(\"jdbcUrl\", jdbcUrl);\n }\n if (driver != null) {\n hikariProps.put(\"driverClassName\", driver);\n }\n if (user != null) {\n user = OpenCms.getCredentialsResolver().resolveCredential(I_CmsCredentialsResolver.DB_USER, user);\n hikariProps.put(\"username\", user);\n }\n if (password != null) {\n password = OpenCms.getCredentialsResolver().resolveCredential(\n I_CmsCredentialsResolver.DB_PASSWORD,\n password);\n hikariProps.put(\"password\", password);\n }\n\n hikariProps.put(\"maximumPoolSize\", \"30\");\n\n // Properties of the form db.pool.poolname.v11.<foo> are directly passed to HikariCP as <foo>\n for (Map.Entry<String, String> entry : poolMap.entrySet()) {\n String suffix = getPropertyRelativeSuffix(\"v11\", entry.getKey());\n if (suffix != null) {\n hikariProps.put(suffix, entry.getValue());\n }\n }\n\n String configuredTestQuery = (String)(hikariProps.get(\"connectionTestQuery\"));\n String testQueryForDriver = testQueries.get(driver);\n if ((testQueryForDriver != null) && CmsStringUtil.isEmptyOrWhitespaceOnly(configuredTestQuery)) {\n hikariProps.put(\"connectionTestQuery\", testQueryForDriver);\n }\n hikariProps.put(\"registerMbeans\", \"true\");\n HikariConfig result = new HikariConfig(hikariProps);\n\n result.setPoolName(poolName.replace(\":\", \"_\"));\n return result;\n }", "public void setRegistrationConfig(RegistrationConfig registrationConfig) {\n this.registrationConfig = registrationConfig;\n\n if (registrationConfig.getDefaultConfig()!=null) {\n for (String key : registrationConfig.getDefaultConfig().keySet()) {\n dynamicConfig.put(key, registrationConfig.getDefaultConfig().get(key));\n }\n }\n }", "private void sendCloseMessage() {\n\n this.lock(() -> {\n\n TcpChannelHub.this.writeMetaDataForKnownTID(0, outWire, null, 0);\n\n TcpChannelHub.this.outWire.writeDocument(false, w ->\n w.writeEventName(EventId.onClientClosing).text(\"\"));\n\n }, TryLock.LOCK);\n\n // wait up to 1 seconds to receive an close request acknowledgment from the server\n try {\n final boolean await = receivedClosedAcknowledgement.await(1, TimeUnit.SECONDS);\n if (!await)\n if (Jvm.isDebugEnabled(getClass()))\n Jvm.debug().on(getClass(), \"SERVER IGNORED CLOSE REQUEST: shutting down the client anyway as the \" +\n \"server did not respond to the close() request.\");\n } catch (InterruptedException ignore) {\n Thread.currentThread().interrupt();\n }\n }", "public static String encodeAuthority(String authority, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(authority, encoding, HierarchicalUriComponents.Type.AUTHORITY);\n\t}", "public String getHeaderField(String fieldName) {\n // headers map is null for all regular response calls except when made as a batch request\n if (this.headers == null) {\n if (this.connection != null) {\n return this.connection.getHeaderField(fieldName);\n } else {\n return null;\n }\n } else {\n return this.headers.get(fieldName);\n }\n }", "@SuppressWarnings(\"unchecked\")\n public LinkedHashMap<String, Field> getValueAsListMap() {\n return (LinkedHashMap<String, Field>) type.convert(getValue(), Type.LIST_MAP);\n }", "public ForeignkeyDef getForeignkey(String name, String tableName)\r\n {\r\n String realName = (name == null ? \"\" : name);\r\n ForeignkeyDef def = null;\r\n\r\n for (Iterator it = getForeignkeys(); it.hasNext();)\r\n {\r\n def = (ForeignkeyDef)it.next();\r\n if (realName.equals(def.getName()) &&\r\n def.getTableName().equals(tableName))\r\n {\r\n return def;\r\n }\r\n }\r\n return null;\r\n }" ]
Calculate start dates for a yearly relative recurrence. @param calendar current date @param dates array of start dates
[ "private void getYearlyRelativeDates(Calendar calendar, List<Date> dates)\n {\n long startDate = calendar.getTimeInMillis();\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n calendar.set(Calendar.MONTH, NumberHelper.getInt(m_monthNumber) - 1);\n\n int dayNumber = NumberHelper.getInt(m_dayNumber);\n while (moreDates(calendar, dates))\n {\n if (dayNumber > 4)\n {\n setCalendarToLastRelativeDay(calendar);\n }\n else\n {\n setCalendarToOrdinalRelativeDay(calendar, dayNumber);\n }\n\n if (calendar.getTimeInMillis() > startDate)\n {\n dates.add(calendar.getTime());\n if (!moreDates(calendar, dates))\n {\n break;\n }\n }\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n calendar.add(Calendar.YEAR, 1);\n }\n }" ]
[ "@Deprecated\r\n public void setViews(String views) {\r\n if (views != null) {\r\n try {\r\n setViews(Integer.parseInt(views));\r\n } catch (NumberFormatException e) {\r\n setViews(-1);\r\n }\r\n }\r\n }", "public static AbstractBuild<?, ?> getRootBuild(AbstractBuild<?, ?> currentBuild) {\n AbstractBuild<?, ?> rootBuild = null;\n AbstractBuild<?, ?> parentBuild = getUpstreamBuild(currentBuild);\n while (parentBuild != null) {\n if (isPassIdentifiedDownstream(parentBuild)) {\n rootBuild = parentBuild;\n }\n parentBuild = getUpstreamBuild(parentBuild);\n }\n if (rootBuild == null && isPassIdentifiedDownstream(currentBuild)) {\n return currentBuild;\n }\n return rootBuild;\n }", "public static String readCorrelationId(Message message) {\n if (!(message instanceof SoapMessage)) {\n return null;\n }\n String correlationId = null;\n Header hdCorrelationId = ((SoapMessage) message).getHeader(CORRELATION_ID_QNAME);\n if (hdCorrelationId != null) {\n if (hdCorrelationId.getObject() instanceof String) {\n correlationId = (String) hdCorrelationId.getObject();\n } else if (hdCorrelationId.getObject() instanceof Node) {\n Node headerNode = (Node) hdCorrelationId.getObject();\n correlationId = headerNode.getTextContent();\n } else {\n LOG.warning(\"Found CorrelationId soap header but value is not a String or a Node! Value: \"\n + hdCorrelationId.getObject().toString());\n }\n }\n return correlationId;\n }", "private <T> MongoCollection<T> getLocalCollection(\n final MongoNamespace namespace,\n final Class<T> resultClass,\n final CodecRegistry codecRegistry\n ) {\n return localClient\n .getDatabase(String.format(\"sync_user_%s\", namespace.getDatabaseName()))\n .getCollection(namespace.getCollectionName(), resultClass)\n .withCodecRegistry(codecRegistry);\n }", "private File getDisabledMarkerFile(long version) throws PersistenceFailureException {\n File[] versionDirArray = ReadOnlyUtils.getVersionDirs(rootDir, version, version);\n if (versionDirArray.length == 0) {\n throw new PersistenceFailureException(\"getDisabledMarkerFile did not find the requested version directory\" +\n \" on disk. Version: \" + version + \", rootDir: \" + rootDir);\n }\n File disabledMarkerFile = new File(versionDirArray[0], DISABLED_MARKER_NAME);\n return disabledMarkerFile;\n }", "protected NodeData createRectangleStyle(float x, float y, float width, float height, boolean stroke, boolean fill)\n {\n float lineWidth = transformLength((float) getGraphicsState().getLineWidth());\n float lw = (lineWidth < 1f) ? 1f : lineWidth;\n float wcor = stroke ? lw : 0.0f;\n \n NodeData ret = CSSFactory.createNodeData();\n TermFactory tf = CSSFactory.getTermFactory();\n ret.push(createDeclaration(\"position\", tf.createIdent(\"absolute\")));\n ret.push(createDeclaration(\"left\", tf.createLength(x, unit)));\n ret.push(createDeclaration(\"top\", tf.createLength(y, unit)));\n ret.push(createDeclaration(\"width\", tf.createLength(width - wcor, unit)));\n ret.push(createDeclaration(\"height\", tf.createLength(height - wcor, unit)));\n \n if (stroke)\n {\n ret.push(createDeclaration(\"border-width\", tf.createLength(lw, unit)));\n ret.push(createDeclaration(\"border-style\", tf.createIdent(\"solid\")));\n String color = colorString(getGraphicsState().getStrokingColor());\n ret.push(createDeclaration(\"border-color\", tf.createColor(color)));\n }\n \n if (fill)\n {\n String color = colorString(getGraphicsState().getNonStrokingColor());\n if (color != null)\n ret.push(createDeclaration(\"background-color\", tf.createColor(color)));\n }\n\n return ret;\n }", "private static String loadUA(ClassLoader loader, String filename){\n String ua = \"cloudant-http\";\n String version = \"unknown\";\n final InputStream propStream = loader.getResourceAsStream(filename);\n final Properties properties = new Properties();\n try {\n if (propStream != null) {\n try {\n properties.load(propStream);\n } finally {\n propStream.close();\n }\n }\n ua = properties.getProperty(\"user.agent.name\", ua);\n version = properties.getProperty(\"user.agent.version\", version);\n } catch (IOException e) {\n // Swallow exception and use default values.\n }\n\n return String.format(Locale.ENGLISH, \"%s/%s\", ua,version);\n }", "private synchronized static Cluster getCluster(URI baseUrl, String[] personalities) throws IOException\n {\n final Entry<URI, Set<String>> key = Maps.immutableEntry(baseUrl, (Set<String>)ImmutableSet.copyOf(personalities));\n\n Cluster result = CLUSTERS.get(key);\n if (result != null) {\n return result;\n }\n\n result = new Cluster(EmbeddedPostgreSQL.start());\n\n final DBI dbi = new DBI(result.getPg().getTemplateDatabase());\n final Migratory migratory = new Migratory(new MigratoryConfig() {}, dbi, dbi);\n migratory.addLocator(new DatabasePreparerLocator(migratory, baseUrl));\n\n final MigrationPlan plan = new MigrationPlan();\n int priority = 100;\n\n for (final String personality : personalities) {\n plan.addMigration(personality, Integer.MAX_VALUE, priority--);\n }\n\n migratory.dbMigrate(plan);\n\n result.start();\n\n CLUSTERS.put(key, result);\n return result;\n }", "private List<Entity> runQuery(Query query) throws DatastoreException {\n RunQueryRequest.Builder request = RunQueryRequest.newBuilder();\n request.setQuery(query);\n RunQueryResponse response = datastore.runQuery(request.build());\n\n if (response.getBatch().getMoreResults() == QueryResultBatch.MoreResultsType.NOT_FINISHED) {\n System.err.println(\"WARNING: partial results\\n\");\n }\n List<EntityResult> results = response.getBatch().getEntityResultsList();\n List<Entity> entities = new ArrayList<Entity>(results.size());\n for (EntityResult result : results) {\n entities.add(result.getEntity());\n }\n return entities;\n }" ]
Write a map field to the JSON file. @param fieldName field name @param value field value
[ "private void writeMap(String fieldName, Object value) throws IOException\n {\n @SuppressWarnings(\"unchecked\")\n Map<String, Object> map = (Map<String, Object>) value;\n m_writer.writeStartObject(fieldName);\n for (Map.Entry<String, Object> entry : map.entrySet())\n {\n Object entryValue = entry.getValue();\n if (entryValue != null)\n {\n DataType type = TYPE_MAP.get(entryValue.getClass().getName());\n if (type == null)\n {\n type = DataType.STRING;\n entryValue = entryValue.toString();\n }\n writeField(entry.getKey(), type, entryValue);\n }\n }\n m_writer.writeEndObject();\n }" ]
[ "private static boolean implementsMethod(ClassNode classNode, String methodName, Class[] argTypes) {\r\n List methods = classNode.getMethods();\r\n if (argTypes == null || argTypes.length ==0) {\r\n for (Iterator i = methods.iterator(); i.hasNext();) {\r\n MethodNode mn = (MethodNode) i.next();\r\n boolean methodMatch = mn.getName().equals(methodName);\r\n if(methodMatch)return true;\r\n // TODO Implement further parameter analysis\r\n }\r\n }\r\n return false;\r\n }", "public RendererBuilder<T> withPrototype(Renderer<? extends T> renderer) {\n if (renderer == null) {\n throw new NeedsPrototypesException(\n \"RendererBuilder can't use a null Renderer<T> instance as prototype\");\n }\n this.prototypes.add(renderer);\n return this;\n }", "public Bundler put(String key, Parcelable[] value) {\n delegate.putParcelableArray(key, value);\n return this;\n }", "public T copy() {\n T ret = createLike();\n ret.getMatrix().set(this.getMatrix());\n return ret;\n }", "public List<String> invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {\n MavenProject mavenProject = getMavenProject(f.getAbsolutePath());\n return mavenProject.getModel().getModules();\n }", "protected Class getClassCacheEntry(String name) {\n if (name == null) return null;\n synchronized (classCache) {\n return classCache.get(name);\n }\n }", "public static ConsistencyLevel determineConsistency(Map<Value, Set<ClusterNode>> versionNodeSetMap,\n int replicationFactor) {\n boolean fullyConsistent = true;\n Value latestVersion = null;\n for (Map.Entry<Value, Set<ClusterNode>> versionNodeSetEntry : versionNodeSetMap.entrySet()) {\n Value value = versionNodeSetEntry.getKey();\n if (latestVersion == null) {\n latestVersion = value;\n } else if (value.isTimeStampLaterThan(latestVersion)) {\n latestVersion = value;\n }\n Set<ClusterNode> nodeSet = versionNodeSetEntry.getValue();\n fullyConsistent = fullyConsistent && (nodeSet.size() == replicationFactor);\n }\n if (fullyConsistent) {\n return ConsistencyLevel.FULL;\n } else {\n // latest write consistent, effectively consistent\n if (latestVersion != null && versionNodeSetMap.get(latestVersion).size() == replicationFactor) {\n return ConsistencyLevel.LATEST_CONSISTENT;\n }\n // all other states inconsistent\n return ConsistencyLevel.INCONSISTENT;\n }\n }", "public boolean containsIteratorForTable(String aTable)\r\n {\r\n boolean result = false;\r\n\r\n if (m_rsIterators != null)\r\n {\r\n for (int i = 0; i < m_rsIterators.size(); i++)\r\n {\r\n OJBIterator it = (OJBIterator) m_rsIterators.get(i);\r\n if (it instanceof RsIterator)\r\n {\r\n if (((RsIterator) it).getClassDescriptor().getFullTableName().equals(aTable))\r\n {\r\n result = true;\r\n break;\r\n }\r\n }\r\n else if (it instanceof ChainingIterator)\r\n {\r\n result = ((ChainingIterator) it).containsIteratorForTable(aTable);\r\n }\r\n }\r\n }\r\n\r\n return result;\r\n }", "public static <K, V> HashMap<K, V> newEmptyHashMap(Iterable<?> iterable) {\n if(iterable instanceof Collection<?>)\n return Maps.newHashMapWithExpectedSize(((Collection<?>) iterable).size());\n return Maps.newHashMap();\n }" ]
Adds a materialization listener. @param listener The listener to add
[ "public synchronized void addListener(MaterializationListener listener)\r\n\t{\r\n\t\tif (_listeners == null)\r\n\t\t{\r\n\t\t\t_listeners = new ArrayList();\r\n\t\t}\r\n\t\t// add listener only once\r\n\t\tif (!_listeners.contains(listener))\r\n\t\t{\r\n\t\t\t_listeners.add(listener);\r\n\t\t}\r\n\t}" ]
[ "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 }", "public final void setConfigurationFiles(final Map<String, String> configurationFiles)\n throws URISyntaxException {\n this.configurationFiles.clear();\n this.configurationFileLastModifiedTimes.clear();\n for (Map.Entry<String, String> entry: configurationFiles.entrySet()) {\n if (!entry.getValue().contains(\":/\")) {\n // assume is a file\n this.configurationFiles.put(entry.getKey(), new File(entry.getValue()).toURI());\n } else {\n this.configurationFiles.put(entry.getKey(), new URI(entry.getValue()));\n }\n }\n\n if (this.configFileLoader != null) {\n this.validateConfigurationFiles();\n }\n }", "final void dispatchToAppender(final String message) {\n // dispatch a copy, since events should be treated as being immutable\n final FoundationFileRollingAppender appender = this.getSource();\n if (appender != null) {\n appender.append(new FileRollEvent(this, message));\n }\n }", "@Override\n public boolean postExecute(MavenBuildProxy build, MavenProject pom, MojoInfo mojo, BuildListener listener,\n Throwable error) {\n //listener.getLogger().println(\"[MavenDependenciesRecorder] mojo: \" + mojo.getClass() + \":\" + mojo.getGoal());\n //listener.getLogger().println(\"[MavenDependenciesRecorder] dependencies: \" + pom.getArtifacts());\n recordMavenDependencies(pom.getArtifacts());\n return true;\n }", "private boolean pathMatches(Path path, SquigglyContext context) {\n List<SquigglyNode> nodes = context.getNodes();\n Set<String> viewStack = null;\n SquigglyNode viewNode = null;\n\n int pathSize = path.getElements().size();\n int lastIdx = pathSize - 1;\n\n for (int i = 0; i < pathSize; i++) {\n PathElement element = path.getElements().get(i);\n\n if (viewNode != null && !viewNode.isSquiggly()) {\n Class beanClass = element.getBeanClass();\n\n if (beanClass != null && !Map.class.isAssignableFrom(beanClass)) {\n Set<String> propertyNames = getPropertyNamesFromViewStack(element, viewStack);\n\n if (!propertyNames.contains(element.getName())) {\n return false;\n }\n }\n\n } else if (nodes.isEmpty()) {\n return false;\n } else {\n\n SquigglyNode match = findBestSimpleNode(element, nodes);\n\n if (match == null) {\n match = findBestViewNode(element, nodes);\n\n if (match != null) {\n viewNode = match;\n viewStack = addToViewStack(viewStack, viewNode);\n }\n } else if (match.isAnyShallow()) {\n viewNode = match;\n } else if (match.isAnyDeep()) {\n return true;\n }\n\n if (match == null) {\n if (isJsonUnwrapped(element)) {\n continue;\n }\n\n return false;\n }\n\n if (match.isNegated()) {\n return false;\n }\n\n nodes = match.getChildren();\n\n if (i < lastIdx && nodes.isEmpty() && !match.isEmptyNested() && SquigglyConfig.isFilterImplicitlyIncludeBaseFields()) {\n nodes = BASE_VIEW_NODES;\n }\n }\n }\n\n return true;\n }", "@Override protected Class getPrototypeClass(Video content) {\n Class prototypeClass;\n if (content.isFavorite()) {\n prototypeClass = FavoriteVideoRenderer.class;\n } else if (content.isLive()) {\n prototypeClass = LiveVideoRenderer.class;\n } else {\n prototypeClass = LikeVideoRenderer.class;\n }\n return prototypeClass;\n }", "public void addSite(String siteKey) {\n\t\tValueMap gv = new ValueMap(siteKey);\n\t\tif (!this.valueMaps.contains(gv)) {\n\t\t\tthis.valueMaps.add(gv);\n\t\t}\n\t}", "public String getElementId() {\r\n\t\tfor (Entry<String, String> attribute : attributes.entrySet()) {\r\n\t\t\tif (attribute.getKey().equalsIgnoreCase(\"id\")) {\r\n\t\t\t\treturn attribute.getValue();\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn null;\r\n\t}", "public static int optionLength(String option) {\n if(matchOption(option, \"qualify\", true) ||\n matchOption(option, \"qualifyGenerics\", true) ||\n matchOption(option, \"hideGenerics\", true) ||\n matchOption(option, \"horizontal\", true) ||\n matchOption(option, \"all\") ||\n matchOption(option, \"attributes\", true) ||\n matchOption(option, \"enumconstants\", true) ||\n matchOption(option, \"operations\", true) ||\n matchOption(option, \"enumerations\", true) ||\n matchOption(option, \"constructors\", true) ||\n matchOption(option, \"visibility\", true) ||\n matchOption(option, \"types\", true) ||\n matchOption(option, \"autosize\", true) ||\n matchOption(option, \"commentname\", true) ||\n matchOption(option, \"nodefontabstractitalic\", true) ||\n matchOption(option, \"postfixpackage\", true) ||\n matchOption(option, \"noguillemot\", true) ||\n matchOption(option, \"views\", true) ||\n matchOption(option, \"inferrel\", true) ||\n matchOption(option, \"useimports\", true) ||\n matchOption(option, \"collapsible\", true) ||\n matchOption(option, \"inferdep\", true) ||\n matchOption(option, \"inferdepinpackage\", true) ||\n matchOption(option, \"hideprivateinner\", true) ||\n matchOption(option, \"compact\", true))\n\n return 1;\n else if(matchOption(option, \"nodefillcolor\") ||\n matchOption(option, \"nodefontcolor\") ||\n matchOption(option, \"nodefontsize\") ||\n matchOption(option, \"nodefontname\") ||\n matchOption(option, \"nodefontclasssize\") ||\n matchOption(option, \"nodefontclassname\") ||\n matchOption(option, \"nodefonttagsize\") ||\n matchOption(option, \"nodefonttagname\") ||\n matchOption(option, \"nodefontpackagesize\") ||\n matchOption(option, \"nodefontpackagename\") ||\n matchOption(option, \"edgefontcolor\") ||\n matchOption(option, \"edgecolor\") ||\n matchOption(option, \"edgefontsize\") ||\n matchOption(option, \"edgefontname\") ||\n matchOption(option, \"shape\") ||\n matchOption(option, \"output\") ||\n matchOption(option, \"outputencoding\") ||\n matchOption(option, \"bgcolor\") ||\n matchOption(option, \"hide\") ||\n matchOption(option, \"include\") ||\n matchOption(option, \"apidocroot\") ||\n matchOption(option, \"apidocmap\") ||\n matchOption(option, \"d\") ||\n matchOption(option, \"view\") ||\n matchOption(option, \"inferreltype\") ||\n matchOption(option, \"inferdepvis\") ||\n matchOption(option, \"collpackages\") ||\n matchOption(option, \"nodesep\") ||\n matchOption(option, \"ranksep\") ||\n matchOption(option, \"dotexecutable\") ||\n matchOption(option, \"link\"))\n return 2;\n else if(matchOption(option, \"contextPattern\") ||\n matchOption(option, \"linkoffline\"))\n return 3;\n else\n return 0;\n }" ]
Load resource content from given path into variable with type specified by `spec`. @param resourcePath the resource path @param spec {@link BeanSpec} specifies the return value type @return the resource content in a specified type or `null` if resource not found @throws UnexpectedException if return value type not supported
[ "public static <T> T load(String resourcePath, BeanSpec spec) {\n return load(resourcePath, spec, false);\n }" ]
[ "String calculateDisplayTimestamp(long time){\n long now = System.currentTimeMillis()/1000;\n long diff = now-time;\n if(diff < 60){\n return \"Just Now\";\n }else if(diff > 60 && diff < 59*60){\n return (diff/(60)) + \" mins ago\";\n }else if(diff > 59*60 && diff < 23*59*60 ){\n return diff/(60*60) > 1 ? diff/(60*60) + \" hours ago\" : diff/(60*60) + \" hour ago\";\n }else if(diff > 24*60*60 && diff < 48*60*60){\n return \"Yesterday\";\n }else {\n @SuppressLint(\"SimpleDateFormat\")\n SimpleDateFormat sdf = new SimpleDateFormat(\"dd MMM\");\n return sdf.format(new Date(time));\n }\n }", "private void removeGroupIdFromTablePaths(int groupIdToRemove) {\n PreparedStatement queryStatement = null;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_PATH);\n results = queryStatement.executeQuery();\n // this is a hashamp from a pathId to the string of groups\n HashMap<Integer, String> idToGroups = new HashMap<Integer, String>();\n while (results.next()) {\n int pathId = results.getInt(Constants.GENERIC_ID);\n String stringGroupIds = results.getString(Constants.PATH_PROFILE_GROUP_IDS);\n int[] groupIds = Utils.arrayFromStringOfIntegers(stringGroupIds);\n String newGroupIds = \"\";\n for (int i = 0; i < groupIds.length; i++) {\n if (groupIds[i] != groupIdToRemove) {\n newGroupIds += (groupIds[i] + \",\");\n }\n }\n idToGroups.put(pathId, newGroupIds);\n }\n\n // now i want to go though the hashmap and for each pathId, add\n // update the newGroupIds\n for (Map.Entry<Integer, String> entry : idToGroups.entrySet()) {\n Integer pathId = entry.getKey();\n String newGroupIds = entry.getValue();\n\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH\n + \" SET \" + Constants.PATH_PROFILE_GROUP_IDS + \" = ? \"\n + \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, newGroupIds);\n statement.setInt(2, pathId);\n statement.executeUpdate();\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "public static List<String> toList(CharSequence self) {\n String s = self.toString();\n int size = s.length();\n List<String> answer = new ArrayList<String>(size);\n for (int i = 0; i < size; i++) {\n answer.add(s.substring(i, i + 1));\n }\n return answer;\n }", "private void sort()\n {\n DefaultDirectedWeightedGraph<RuleProvider, DefaultEdge> graph = new DefaultDirectedWeightedGraph<>(\n DefaultEdge.class);\n\n for (RuleProvider provider : providers)\n {\n graph.addVertex(provider);\n }\n\n addProviderRelationships(graph);\n\n checkForCycles(graph);\n\n List<RuleProvider> result = new ArrayList<>(this.providers.size());\n TopologicalOrderIterator<RuleProvider, DefaultEdge> iterator = new TopologicalOrderIterator<>(graph);\n while (iterator.hasNext())\n {\n RuleProvider provider = iterator.next();\n result.add(provider);\n }\n\n this.providers = Collections.unmodifiableList(result);\n\n int index = 0;\n for (RuleProvider provider : this.providers)\n {\n if (provider instanceof AbstractRuleProvider)\n ((AbstractRuleProvider) provider).setExecutionIndex(index++);\n }\n }", "public static boolean reconnect(final Jedis jedis, final int reconAttempts, final long reconnectSleepTime) {\n int i = 1;\n do {\n try {\n jedis.disconnect();\n try {\n Thread.sleep(reconnectSleepTime);\n } catch (Exception e2) {\n }\n jedis.connect();\n } catch (JedisConnectionException jce) {\n } // Ignore bad connection attempts\n catch (Exception e3) {\n LOG.error(\"Unknown Exception while trying to reconnect to Redis\", e3);\n }\n } while (++i <= reconAttempts && !testJedisConnection(jedis));\n return testJedisConnection(jedis);\n }", "public static HashMap<String, String> getParameters(String query) {\n HashMap<String, String> params = new HashMap<String, String>();\n if (query == null || query.length() == 0) {\n return params;\n }\n\n String[] splitQuery = query.split(\"&\");\n for (String splitItem : splitQuery) {\n String[] items = splitItem.split(\"=\");\n\n if (items.length == 1) {\n params.put(items[0], \"\");\n } else {\n params.put(items[0], items[1]);\n }\n }\n\n return params;\n }", "@Override\n public View getView(int position, View convertView, ViewGroup parent) {\n if (position == super.getCount() && isEnableRefreshing()) {\n return (mFooter);\n }\n return (super.getView(position, convertView, parent));\n }", "public static authenticationradiuspolicy_vpnvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationradiuspolicy_vpnvserver_binding obj = new authenticationradiuspolicy_vpnvserver_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationradiuspolicy_vpnvserver_binding response[] = (authenticationradiuspolicy_vpnvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static String rset(String input, int width)\n {\n String result; // result to return\n StringBuilder pad = new StringBuilder();\n if (input == null)\n {\n for (int i = 0; i < width - 1; i++)\n {\n pad.append(' '); // put blanks into buffer\n }\n result = \" \" + pad; // one short to use + overload\n }\n else\n {\n if (input.length() >= width)\n {\n result = input.substring(0, width); // when input is too long, truncate\n }\n else\n {\n int padLength = width - input.length(); // number of blanks to add\n for (int i = 0; i < padLength; i++)\n {\n pad.append(' '); // actually put blanks into buffer\n }\n result = pad + input; // concatenate\n }\n }\n return result;\n }" ]
Restarts a single dyno @param appName See {@link #listApps} for a list of apps that can be used. @param dynoId the unique identifier of the dyno to restart
[ "public void restartDyno(String appName, String dynoId) {\n connection.execute(new DynoRestart(appName, dynoId), apiKey);\n }" ]
[ "private boolean isDescriptorProperty(Object property) {\n\n return (getBundleType().equals(BundleType.DESCRIPTOR)\n || (hasDescriptor()\n && (property.equals(TableProperty.KEY)\n || property.equals(TableProperty.DEFAULT)\n || property.equals(TableProperty.DESCRIPTION))));\n }", "public static vpnclientlessaccesspolicy_binding get(nitro_service service, String name) throws Exception{\n\t\tvpnclientlessaccesspolicy_binding obj = new vpnclientlessaccesspolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnclientlessaccesspolicy_binding response = (vpnclientlessaccesspolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static <ResultT> PollingState<ResultT> createFromJSONString(String serializedPollingState) {\n ObjectMapper mapper = initMapper(new ObjectMapper());\n PollingState<ResultT> pollingState;\n try {\n pollingState = mapper.readValue(serializedPollingState, PollingState.class);\n } catch (IOException exception) {\n throw new RuntimeException(exception);\n }\n return pollingState;\n }", "public static base_responses expire(nitro_service client, cachecontentgroup resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcachecontentgroup expireresources[] = new cachecontentgroup[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\texpireresources[i] = new cachecontentgroup();\n\t\t\t\texpireresources[i].name = resources[i].name;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, expireresources,\"expire\");\n\t\t}\n\t\treturn result;\n\t}", "private String getCacheFormatEntry() throws IOException {\n ZipEntry zipEntry = zipFile.getEntry(CACHE_FORMAT_ENTRY);\n InputStream is = zipFile.getInputStream(zipEntry);\n try {\n Scanner s = new Scanner(is, \"UTF-8\").useDelimiter(\"\\\\A\");\n String tag = null;\n if (s.hasNext()) tag = s.next();\n return tag;\n } finally {\n is.close();\n }\n }", "private RandomVariable getShortRate(int timeIndex) throws CalculationException {\n\t\tdouble time = getProcess().getTime(timeIndex);\n\t\tdouble timePrev = timeIndex > 0 ? getProcess().getTime(timeIndex-1) : time;\n\t\tdouble timeNext = getProcess().getTime(timeIndex+1);\n\n\t\tRandomVariable zeroRate = getZeroRateFromForwardCurve(time); //getDiscountFactorFromForwardCurve(time).div(getDiscountFactorFromForwardCurve(timeNext)).log().div(timeNext-time);\n\n\t\tRandomVariable alpha = getDV(0, time);\n\n\t\tRandomVariable value = getProcess().getProcessValue(timeIndex, 0);\n\t\tvalue = value.add(alpha);\n\t\t//\t\tvalue = value.sub(Math.log(value.exp().getAverage()));\n\n\t\tvalue = value.add(zeroRate);\n\n\t\treturn value;\n\t}", "@Nullable\n public StitchUserT getUser() {\n authLock.readLock().lock();\n try {\n return activeUser;\n } finally {\n authLock.readLock().unlock();\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}", "public static DMatrixRMaj copyTriangle(DMatrixRMaj src , DMatrixRMaj dst , boolean upper ) {\n if( dst == null ) {\n dst = new DMatrixRMaj(src.numRows,src.numCols);\n } else if( src.numRows != dst.numRows || src.numCols != dst.numCols ) {\n throw new IllegalArgumentException(\"src and dst must have the same dimensions.\");\n }\n\n if( upper ) {\n int N = Math.min(src.numRows,src.numCols);\n for( int i = 0; i < N; i++ ) {\n int index = i*src.numCols+i;\n System.arraycopy(src.data,index,dst.data,index,src.numCols-i);\n }\n } else {\n for( int i = 0; i < src.numRows; i++ ) {\n int length = Math.min(i+1,src.numCols);\n int index = i*src.numCols;\n System.arraycopy(src.data,index,dst.data,index,length);\n }\n }\n\n return dst;\n }" ]
Computes the p=1 norm. If A is a matrix then the induced norm is computed. @param A Matrix or vector. @return The norm.
[ "public static double normP1( DMatrixRMaj A ) {\n if( MatrixFeatures_DDRM.isVector(A)) {\n return CommonOps_DDRM.elementSumAbs(A);\n } else {\n return inducedP1(A);\n }\n }" ]
[ "private String getRowLineBuf(int colCount, List<Integer> colMaxLenList, String[][] data) {\n\t\t\n\t\tS.Buffer rowBuilder = S.buffer();\n\t\tint colWidth;\n\t\t\n\t\tfor (int i = 0 ; i < colCount ; i ++) {\n\t\t\t\n\t\t\tcolWidth = colMaxLenList.get(i) + 3;\n\t\t\t\n\t\t\tfor (int j = 0; j < colWidth ; j ++) {\n\t\t\t\tif (j==0) {\n\t\t\t\t\trowBuilder.append(\"+\");\n\t\t\t\t} else if ((i+1 == colCount && j+1 == colWidth)) {//for last column close the border\n\t\t\t\t\trowBuilder.append(\"-+\");\n\t\t\t\t} else {\n\t\t\t\t\trowBuilder.append(\"-\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn rowBuilder.append(\"\\n\").toString();\n\t}", "public static void acceptsHex(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_X, OPT_HEX), \"fetch key/entry by key value of hex type\")\n .withRequiredArg()\n .describedAs(\"key-list\")\n .withValuesSeparatedBy(',')\n .ofType(String.class);\n }", "public RandomVariable[] getBasisFunctions(double fixingDate, LIBORModelMonteCarloSimulationModel model) throws CalculationException {\n\n\t\tArrayList<RandomVariable> basisFunctions = new ArrayList<>();\n\n\t\t// Constant\n\t\tRandomVariable basisFunction = new RandomVariableFromDoubleArray(1.0);//.getRandomVariableForConstant(1.0);\n\t\tbasisFunctions.add(basisFunction);\n\n\t\tint fixingDateIndex = Arrays.binarySearch(fixingDates, fixingDate);\n\t\tif(fixingDateIndex < 0) {\n\t\t\tfixingDateIndex = -fixingDateIndex;\n\t\t}\n\t\tif(fixingDateIndex >= fixingDates.length) {\n\t\t\tfixingDateIndex = fixingDates.length-1;\n\t\t}\n\n\t\t// forward rate to the next period\n\t\tRandomVariable rateShort = model.getLIBOR(fixingDate, fixingDate, paymentDates[fixingDateIndex]);\n\t\tRandomVariable discountShort = rateShort.mult(paymentDates[fixingDateIndex]-fixingDate).add(1.0).invert();\n\t\tbasisFunctions.add(discountShort);\n\t\tbasisFunctions.add(discountShort.pow(2.0));\n\t\t//\t\tbasisFunctions.add(rateShort.pow(3.0));\n\n\t\t// forward rate to the end of the product\n\t\tRandomVariable rateLong = model.getLIBOR(fixingDate, fixingDates[fixingDateIndex], paymentDates[paymentDates.length-1]);\n\t\tRandomVariable discountLong = rateLong.mult(paymentDates[paymentDates.length-1]-fixingDates[fixingDateIndex]).add(1.0).invert();\n\t\tbasisFunctions.add(discountLong);\n\t\tbasisFunctions.add(discountLong.pow(2.0));\n\t\t//\t\tbasisFunctions.add(rateLong.pow(3.0));\n\n\t\t// Numeraire\n\t\tRandomVariable numeraire = model.getNumeraire(fixingDate).invert();\n\t\tbasisFunctions.add(numeraire);\n\t\t//\t\tbasisFunctions.add(numeraire.pow(2.0));\n\t\t//\t\tbasisFunctions.add(numeraire.pow(3.0));\n\n\t\treturn basisFunctions.toArray(new RandomVariable[basisFunctions.size()]);\n\t}", "private void writeAssignments() throws IOException\n {\n writeAttributeTypes(\"assignment_types\", AssignmentField.values());\n\n m_writer.writeStartList(\"assignments\");\n for (ResourceAssignment assignment : m_projectFile.getResourceAssignments())\n {\n writeFields(null, assignment, AssignmentField.values());\n }\n m_writer.writeEndList();\n\n }", "private Number calculateDurationPercentComplete(Row row)\n {\n double result = 0;\n double targetDuration = row.getDuration(\"target_drtn_hr_cnt\").getDuration();\n double remainingDuration = row.getDuration(\"remain_drtn_hr_cnt\").getDuration();\n\n if (targetDuration == 0)\n {\n if (remainingDuration == 0)\n {\n if (\"TK_Complete\".equals(row.getString(\"status_code\")))\n {\n result = 100;\n }\n }\n }\n else\n {\n if (remainingDuration < targetDuration)\n {\n result = ((targetDuration - remainingDuration) * 100) / targetDuration;\n }\n }\n\n return NumberHelper.getDouble(result);\n }", "public void enable(ConduitSelectorHolder conduitSelectorHolder, SLPropertiesMatcher matcher,\n String selectionStrategy) {\n LocatorTargetSelector selector = new LocatorTargetSelector();\n selector.setEndpoint(conduitSelectorHolder.getConduitSelector().getEndpoint());\n\n String actualStrategy = selectionStrategy != null ? selectionStrategy : defaultLocatorSelectionStrategy;\n \n LocatorSelectionStrategy locatorSelectionStrategy = getLocatorSelectionStrategy(actualStrategy);\n locatorSelectionStrategy.setServiceLocator(locatorClient);\n if (matcher != null) {\n locatorSelectionStrategy.setMatcher(matcher);\n }\n selector.setLocatorSelectionStrategy(locatorSelectionStrategy);\n\n if (LOG.isLoggable(Level.INFO)) {\n LOG.log(Level.INFO, \"Client enabled with strategy \"\n + locatorSelectionStrategy.getClass().getName() + \".\");\n }\n conduitSelectorHolder.setConduitSelector(selector);\n\n if (LOG.isLoggable(Level.FINE)) {\n LOG.log(Level.FINE, \"Successfully enabled client \" + conduitSelectorHolder\n + \" for the service locator\");\n }\n }", "private void primeCache() {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (Map.Entry<DeckReference, TrackMetadata> entry : MetadataFinder.getInstance().getLoadedTracks().entrySet()) {\n if (entry.getKey().hotCue == 0) { // The track is currently loaded in a main player deck\n handleUpdate(new TrackMetadataUpdate(entry.getKey().player, entry.getValue()));\n }\n }\n }\n });\n }", "public void load(IAssetEvents handler)\n {\n GVRAssetLoader loader = getGVRContext().getAssetLoader();\n\n if (mReplaceScene)\n {\n loader.loadScene(getOwnerObject(), mVolume, mImportSettings, getGVRContext().getMainScene(), handler);\n }\n else\n {\n loader.loadModel(mVolume, getOwnerObject(), mImportSettings, true, handler);\n }\n }", "public void postArtifact(final Artifact artifact, final String user, final String password) throws GrapesCommunicationException, AuthenticationException {\n final Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.artifactResourcePath());\n final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, artifact);\n\n client.destroy();\n if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){\n final String message = \"Failed to POST artifact\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n }" ]
If there is an unprocessed change event for a particular document ID, fetch it from the appropriate namespace change stream listener, and remove it. By reading the event here, we are assuming it will be processed by the consumer. @return the latest unprocessed change event for the given document ID and namespace, or null if none exists.
[ "public @Nullable ChangeEvent<BsonDocument> getUnprocessedEventForDocumentId(\n final MongoNamespace namespace,\n final BsonValue documentId\n ) {\n this.instanceLock.readLock().lock();\n final NamespaceChangeStreamListener streamer;\n try {\n streamer = nsStreamers.get(namespace);\n } finally {\n this.instanceLock.readLock().unlock();\n }\n\n if (streamer == null) {\n return null;\n }\n\n return streamer.getUnprocessedEventForDocumentId(documentId);\n }" ]
[ "@Override public void render() {\n Video video = getContent();\n renderThumbnail(video);\n renderTitle(video);\n renderMarker(video);\n renderLabel();\n }", "public static synchronized FormInputValueHelper getInstance(\n\t\t\tInputSpecification inputSpecification, FormFillMode formFillMode) {\n\t\tif (instance == null)\n\t\t\tinstance = new FormInputValueHelper(inputSpecification,\n\t\t\t\t\tformFillMode);\n\t\treturn instance;\n\t}", "public <T extends Widget & Checkable> List<T> getCheckedWidgets() {\n List<T> checked = new ArrayList<>();\n\n for (Widget c : getChildren()) {\n if (c instanceof Checkable && ((Checkable) c).isChecked()) {\n checked.add((T) c);\n }\n }\n\n return checked;\n }", "public boolean hasSameConfiguration(BoneCPConfig that){\n\t\tif ( that != null && Objects.equal(this.acquireIncrement, that.getAcquireIncrement())\n\t\t\t\t&& Objects.equal(this.acquireRetryDelayInMs, that.getAcquireRetryDelayInMs())\n\t\t\t\t&& Objects.equal(this.closeConnectionWatch, that.isCloseConnectionWatch())\n\t\t\t\t&& Objects.equal(this.logStatementsEnabled, that.isLogStatementsEnabled())\n\t\t\t\t&& Objects.equal(this.connectionHook, that.getConnectionHook())\n\t\t\t\t&& Objects.equal(this.connectionTestStatement, that.getConnectionTestStatement())\n\t\t\t\t&& Objects.equal(this.idleConnectionTestPeriodInSeconds, that.getIdleConnectionTestPeriod(TimeUnit.SECONDS))\n\t\t\t\t&& Objects.equal(this.idleMaxAgeInSeconds, that.getIdleMaxAge(TimeUnit.SECONDS))\n\t\t\t\t&& Objects.equal(this.initSQL, that.getInitSQL())\n\t\t\t\t&& Objects.equal(this.jdbcUrl, that.getJdbcUrl())\n\t\t\t\t&& Objects.equal(this.maxConnectionsPerPartition, that.getMaxConnectionsPerPartition())\n\t\t\t\t&& Objects.equal(this.minConnectionsPerPartition, that.getMinConnectionsPerPartition())\n\t\t\t\t&& Objects.equal(this.partitionCount, that.getPartitionCount())\n\t\t\t\t&& Objects.equal(this.releaseHelperThreads, that.getReleaseHelperThreads())\n\t\t\t\t&& Objects.equal(this.statementsCacheSize, that.getStatementsCacheSize())\n\t\t\t\t&& Objects.equal(this.username, that.getUsername())\n\t\t\t\t&& Objects.equal(this.password, that.getPassword())\n\t\t\t\t&& Objects.equal(this.lazyInit, that.isLazyInit())\n\t\t\t\t&& Objects.equal(this.transactionRecoveryEnabled, that.isTransactionRecoveryEnabled())\n\t\t\t\t&& Objects.equal(this.acquireRetryAttempts, that.getAcquireRetryAttempts())\n\t\t\t\t&& Objects.equal(this.statementReleaseHelperThreads, that.getStatementReleaseHelperThreads())\n\t\t\t\t&& Objects.equal(this.closeConnectionWatchTimeoutInMs, that.getCloseConnectionWatchTimeout())\n\t\t\t\t&& Objects.equal(this.connectionTimeoutInMs, that.getConnectionTimeoutInMs())\n\t\t\t\t&& Objects.equal(this.datasourceBean, that.getDatasourceBean())\n\t\t\t\t&& Objects.equal(this.getQueryExecuteTimeLimitInMs(), that.getQueryExecuteTimeLimitInMs())\n\t\t\t\t&& Objects.equal(this.poolAvailabilityThreshold, that.getPoolAvailabilityThreshold())\n\t\t\t\t&& Objects.equal(this.poolName, that.getPoolName())\n\t\t\t\t&& Objects.equal(this.disableConnectionTracking, that.isDisableConnectionTracking())\n\n\t\t\t\t){\n\t\t\treturn true;\n\t\t} \n\n\t\treturn false;\n\t}", "public static <T> void addAll(Collection<T> collection, Iterable<? extends T> items) {\r\n for (T item : items) {\r\n collection.add(item);\r\n }\r\n }", "public CollectionRequest<Task> projects(String task) {\n \n String path = String.format(\"/tasks/%s/projects\", task);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }", "private void setSiteFilters(String filters) {\n\t\tthis.filterSites = new HashSet<>();\n\t\tif (!\"-\".equals(filters)) {\n\t\t\tCollections.addAll(this.filterSites, filters.split(\",\"));\n\t\t}\n\t}", "public final void setWeekDay(WeekDay weekDay) {\n\n SortedSet<WeekDay> wds = new TreeSet<>();\n if (null != weekDay) {\n wds.add(weekDay);\n }\n setWeekDays(wds);\n\n }", "private void sortFields()\r\n {\r\n HashMap fields = new HashMap();\r\n ArrayList fieldsWithId = new ArrayList();\r\n ArrayList fieldsWithoutId = new ArrayList();\r\n FieldDescriptorDef fieldDef;\r\n\r\n for (Iterator it = getFields(); it.hasNext(); )\r\n {\r\n fieldDef = (FieldDescriptorDef)it.next();\r\n fields.put(fieldDef.getName(), fieldDef);\r\n if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_ID))\r\n {\r\n fieldsWithId.add(fieldDef.getName());\r\n }\r\n else\r\n {\r\n fieldsWithoutId.add(fieldDef.getName());\r\n }\r\n }\r\n\r\n Collections.sort(fieldsWithId, new FieldWithIdComparator(fields));\r\n\r\n ArrayList result = new ArrayList();\r\n\r\n for (Iterator it = fieldsWithId.iterator(); it.hasNext();)\r\n {\r\n result.add(getField((String)it.next()));\r\n }\r\n for (Iterator it = fieldsWithoutId.iterator(); it.hasNext();)\r\n {\r\n result.add(getField((String)it.next()));\r\n }\r\n\r\n _fields = result;\r\n }" ]
Add a new value to the array map. @param key The key under which to store the value. <b>Must not be null.</b> If this key already exists in the array, its value will be replaced. @param value The value to store for the given key. @return Returns the old value that was stored for the given key, or null if there was no such key.
[ "public V put(K key, V value) {\n final int hash;\n int index;\n if (key == null) {\n hash = 0;\n index = indexOfNull();\n } else {\n hash = key.hashCode();\n index = indexOf(key, hash);\n }\n if (index >= 0) {\n index = (index<<1) + 1;\n final V old = (V)mArray[index];\n mArray[index] = value;\n return old;\n }\n\n index = ~index;\n if (mSize >= mHashes.length) {\n final int n = mSize >= (BASE_SIZE*2) ? (mSize+(mSize>>1))\n : (mSize >= BASE_SIZE ? (BASE_SIZE*2) : BASE_SIZE);\n\n final int[] ohashes = mHashes;\n final Object[] oarray = mArray;\n allocArrays(n);\n\n if (mHashes.length > 0) {\n System.arraycopy(ohashes, 0, mHashes, 0, ohashes.length);\n System.arraycopy(oarray, 0, mArray, 0, oarray.length);\n }\n\n freeArrays(ohashes, oarray, mSize);\n }\n\n if (index < mSize) {\n System.arraycopy(mHashes, index, mHashes, index + 1, mSize - index);\n System.arraycopy(mArray, index << 1, mArray, (index + 1) << 1, (mSize - index) << 1);\n }\n\n mHashes[index] = hash;\n mArray[index<<1] = key;\n mArray[(index<<1)+1] = value;\n mSize++;\n return null;\n }" ]
[ "public static <OutT, InT> PagedList<OutT> toPagedList(List<InT> list, final Func1<InT, OutT> mapper) {\n PageImpl<InT> page = new PageImpl<>();\n page.setItems(list);\n page.setNextPageLink(null);\n PagedList<InT> pagedList = new PagedList<InT>(page) {\n @Override\n public Page<InT> nextPage(String nextPageLink) {\n return null;\n }\n };\n PagedListConverter<InT, OutT> converter = new PagedListConverter<InT, OutT>() {\n @Override\n public Observable<OutT> typeConvertAsync(InT inner) {\n return Observable.just(mapper.call(inner));\n }\n };\n return converter.convert(pagedList);\n }", "public IPv4Address getEmbeddedIPv4Address(int byteIndex) {\n\t\tif(byteIndex == IPv6Address.MIXED_ORIGINAL_SEGMENT_COUNT * IPv6Address.BYTES_PER_SEGMENT) {\n\t\t\treturn getEmbeddedIPv4Address();\n\t\t}\n\t\tIPv4AddressCreator creator = getIPv4Network().getAddressCreator();\n\t\treturn creator.createAddress(getSection().getEmbeddedIPv4AddressSection(byteIndex, byteIndex + IPv4Address.BYTE_COUNT)); /* address creation */\n\t}", "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}", "private String getName(CommandContext ctx, boolean failInBatch) throws CommandLineException {\n final ParsedCommandLine args = ctx.getParsedCommandLine();\n final String name = this.name.getValue(args, true);\n if (name == null) {\n throw new CommandFormatException(this.name + \" is missing value.\");\n }\n if (!ctx.isBatchMode() || failInBatch) {\n if (!Util.isValidPath(ctx.getModelControllerClient(), Util.DEPLOYMENT_OVERLAY, name)) {\n throw new CommandFormatException(\"Deployment overlay \" + name + \" does not exist.\");\n }\n }\n return name;\n }", "private String type(Options opt, Type t, boolean generics) {\n\treturn ((generics ? opt.showQualifiedGenerics : opt.showQualified) ? //\n\t\tt.qualifiedTypeName() : t.typeName()) //\n\t\t+ (opt.hideGenerics ? \"\" : typeParameters(opt, t.asParameterizedType()));\n }", "public String[] getMethods(String pluginClass) throws Exception {\n ArrayList<String> methodNames = new ArrayList<String>();\n\n Method[] methods = getClass(pluginClass).getDeclaredMethods();\n for (Method method : methods) {\n logger.info(\"Checking {}\", method.getName());\n\n com.groupon.odo.proxylib.models.Method methodInfo = this.getMethod(pluginClass, method.getName());\n if (methodInfo == null) {\n continue;\n }\n\n // check annotations\n Boolean matchesAnnotation = false;\n if (methodInfo.getMethodType().endsWith(Constants.PLUGIN_RESPONSE_OVERRIDE_CLASS) ||\n methodInfo.getMethodType().endsWith(Constants.PLUGIN_RESPONSE_OVERRIDE_V2_CLASS)) {\n matchesAnnotation = true;\n }\n\n if (!methodNames.contains(method.getName()) && matchesAnnotation) {\n methodNames.add(method.getName());\n }\n }\n\n return methodNames.toArray(new String[0]);\n }", "@Override\n public GroupDiscussInterface getDiscussionInterface() {\n if (discussionInterface == null) {\n discussionInterface = new GroupDiscussInterface(apiKey, sharedSecret, transport);\n }\n return discussionInterface;\n }", "public ItemRequest<Task> findById(String task) {\n \n String path = String.format(\"/tasks/%s\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"GET\");\n }", "public static void checkDirectory(File directory) {\n if (!(directory.exists() || directory.mkdirs())) {\n throw new ReportGenerationException(\n String.format(\"Can't create data directory <%s>\", directory.getAbsolutePath())\n );\n }\n }" ]
Adds a new Matrix variable. If one already has the same name it is written over. While more verbose for multiple variables, this function doesn't require new memory be declared each time it's called. @param variable Matrix which is to be assigned to name @param name The name of the variable
[ "public void alias(DMatrixRMaj variable , String name ) {\n if( isReserved(name))\n throw new RuntimeException(\"Reserved word or contains a reserved character\");\n VariableMatrix old = (VariableMatrix)variables.get(name);\n if( old == null ) {\n variables.put(name, new VariableMatrix(variable));\n }else {\n old.matrix = variable;\n }\n }" ]
[ "public void lock(Object obj, int lockMode) throws LockNotGrantedException\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"lock object was called on tx \" + this + \", object is \" + obj.toString());\r\n checkOpen();\r\n RuntimeObject rtObject = new RuntimeObject(obj, this);\r\n lockAndRegister(rtObject, lockMode, isImplicitLocking(), getRegistrationList());\r\n// if(isImplicitLocking()) moveToLastInOrderList(rtObject.getIdentity());\r\n }", "private static Point getScreenSize(Context context, Point p) {\n if (p == null) {\n p = new Point();\n }\n WindowManager windowManager = (WindowManager) context\n .getSystemService(Context.WINDOW_SERVICE);\n Display display = windowManager.getDefaultDisplay();\n display.getSize(p);\n return p;\n }", "private void initialize(Handler callbackHandler, int threadPoolSize) {\n\t\tmDownloadDispatchers = new DownloadDispatcher[threadPoolSize];\n\t\tmDelivery = new CallBackDelivery(callbackHandler);\n\t}", "public FastReportBuilder addBarcodeColumn(String title, String property,String className, int barcodeType,boolean showText, int width, boolean fixedWidth,ImageScaleMode imageScaleMode, Style style) throws ColumnBuilderException, ClassNotFoundException {\n\t\tAbstractColumn column = ColumnBuilder.getNew()\n\t\t.setColumnProperty(property, className)\n\t\t.setWidth(width)\n\t\t.setTitle(title)\n\t\t.setFixedWidth(fixedWidth)\n\t\t.setColumnType(ColumnBuilder.COLUMN_TYPE_BARCODE)\n\t\t.setStyle(style)\n\t\t.setBarcodeType(barcodeType)\n\t\t.setShowText(showText)\n\t\t.build();\n\n\t\tif (style == null)\n\t\t\tguessStyle(className, column);\n\n\t\taddColumn(column);\n\n\t\treturn this;\n\t}", "private ModelNode createCPUNode() throws OperationFailedException {\n ModelNode cpu = new ModelNode().setEmptyObject();\n cpu.get(ARCH).set(getProperty(\"os.arch\"));\n cpu.get(AVAILABLE_PROCESSORS).set(ProcessorInfo.availableProcessors());\n return cpu;\n }", "public static Optional<Variable> freshBuilder(SourceBuilder code, Datatype datatype) {\n if (!datatype.getBuilderFactory().isPresent()) {\n return Optional.empty();\n }\n return Optional.of(code.scope().computeIfAbsent(Declaration.FRESH_BUILDER, () -> {\n Variable defaults = new Variable(\"defaults\");\n code.addLine(\"%s %s = %s;\",\n datatype.getGeneratedBuilder(),\n defaults,\n datatype.getBuilderFactory().get()\n .newBuilder(datatype.getBuilder(), TypeInference.INFERRED_TYPES));\n return defaults;\n }));\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}", "private static <T, ID> MappedDeleteCollection<T, ID> build(Dao<T, ID> dao, TableInfo<T, ID> tableInfo, int dataSize)\n\t\t\tthrows SQLException {\n\t\tFieldType idField = tableInfo.getIdField();\n\t\tif (idField == null) {\n\t\t\tthrow new SQLException(\n\t\t\t\t\t\"Cannot delete \" + tableInfo.getDataClass() + \" because it doesn't have an id field defined\");\n\t\t}\n\t\tStringBuilder sb = new StringBuilder(128);\n\t\tDatabaseType databaseType = dao.getConnectionSource().getDatabaseType();\n\t\tappendTableName(databaseType, sb, \"DELETE FROM \", tableInfo.getTableName());\n\t\tFieldType[] argFieldTypes = new FieldType[dataSize];\n\t\tappendWhereIds(databaseType, idField, sb, dataSize, argFieldTypes);\n\t\treturn new MappedDeleteCollection<T, ID>(dao, tableInfo, sb.toString(), argFieldTypes);\n\t}", "private void addGroups(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (Group group : file.getGroups())\n {\n final Group g = group;\n MpxjTreeNode childNode = new MpxjTreeNode(group)\n {\n @Override public String toString()\n {\n return g.getName();\n }\n };\n parentNode.add(childNode);\n }\n }" ]
Given counters of true positives, false positives, and false negatives, prints out precision, recall, and f1 for each key.
[ "public static void printResults(Counter<String> entityTP, Counter<String> entityFP,\r\n Counter<String> entityFN) {\r\n Set<String> entities = new TreeSet<String>();\r\n entities.addAll(entityTP.keySet());\r\n entities.addAll(entityFP.keySet());\r\n entities.addAll(entityFN.keySet());\r\n boolean printedHeader = false;\r\n for (String entity : entities) {\r\n double tp = entityTP.getCount(entity);\r\n double fp = entityFP.getCount(entity);\r\n double fn = entityFN.getCount(entity);\r\n printedHeader = printPRLine(entity, tp, fp, fn, printedHeader);\r\n }\r\n double tp = entityTP.totalCount();\r\n double fp = entityFP.totalCount();\r\n double fn = entityFN.totalCount();\r\n printedHeader = printPRLine(\"Totals\", tp, fp, fn, printedHeader);\r\n }" ]
[ "static void processServerConfig(final Resource root, final RequiredConfigurationHolder requiredConfigurationHolder, final IgnoredNonAffectedServerGroupsUtil.ServerConfigInfo serverConfig, final ExtensionRegistry extensionRegistry) {\n\n final Set<String> serverGroups = requiredConfigurationHolder.serverGroups;\n final Set<String> socketBindings = requiredConfigurationHolder.socketBindings;\n\n String sbg = serverConfig.getSocketBindingGroup();\n if (sbg != null && !socketBindings.contains(sbg)) {\n processSocketBindingGroup(root, sbg, requiredConfigurationHolder);\n }\n\n final String groupName = serverConfig.getServerGroup();\n final PathElement groupElement = PathElement.pathElement(SERVER_GROUP, groupName);\n // Also check the root, since this also gets executed on the slave which may not have the server-group configured yet\n if (!serverGroups.contains(groupName) && root.hasChild(groupElement)) {\n\n final Resource serverGroup = root.getChild(groupElement);\n final ModelNode groupModel = serverGroup.getModel();\n serverGroups.add(groupName);\n\n // Include the socket binding groups\n if (groupModel.hasDefined(SOCKET_BINDING_GROUP)) {\n final String socketBindingGroup = groupModel.get(SOCKET_BINDING_GROUP).asString();\n processSocketBindingGroup(root, socketBindingGroup, requiredConfigurationHolder);\n }\n\n final String profileName = groupModel.get(PROFILE).asString();\n processProfile(root, profileName, requiredConfigurationHolder, extensionRegistry);\n }\n }", "private boolean checkZoneRequirement(HashMap<Integer, Integer> requiredRepFactor, int zoneId) {\n if(requiredRepFactor.containsKey(zoneId)) {\n if(requiredRepFactor.get(zoneId) == 0) {\n return false;\n } else {\n requiredRepFactor.put(zoneId, requiredRepFactor.get(zoneId) - 1);\n return true;\n }\n }\n return false;\n\n }", "public static <E, V> ServiceFuture<List<E>> fromHeaderPageResponse(Observable<ServiceResponseWithHeaders<Page<E>, V>> first, final Func1<String, Observable<ServiceResponseWithHeaders<Page<E>, V>>> next, final ListOperationCallback<E> callback) {\n final AzureServiceFuture<List<E>> serviceCall = new AzureServiceFuture<>();\n final PagingSubscriber<E> subscriber = new PagingSubscriber<>(serviceCall, new Func1<String, Observable<ServiceResponse<Page<E>>>>() {\n @Override\n public Observable<ServiceResponse<Page<E>>> call(String s) {\n return next.call(s)\n .map(new Func1<ServiceResponseWithHeaders<Page<E>, V>, ServiceResponse<Page<E>>>() {\n @Override\n public ServiceResponse<Page<E>> call(ServiceResponseWithHeaders<Page<E>, V> pageVServiceResponseWithHeaders) {\n return pageVServiceResponseWithHeaders;\n }\n });\n }\n }, callback);\n serviceCall.setSubscription(first\n .single()\n .subscribe(subscriber));\n return serviceCall;\n }", "public String toText() {\n StringBuilder sb = new StringBuilder();\n if (!description.isEmpty()) {\n sb.append(description.toText());\n sb.append(EOL);\n }\n if (!blockTags.isEmpty()) {\n sb.append(EOL);\n }\n for (JavadocBlockTag tag : blockTags) {\n sb.append(tag.toText()).append(EOL);\n }\n return sb.toString();\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<Symmetry010Date> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<Symmetry010Date>) super.zonedDateTime(temporal);\n }", "public void remove(Identity oid)\r\n {\r\n try\r\n {\r\n jcsCache.remove(oid.toString());\r\n }\r\n catch (CacheException e)\r\n {\r\n throw new RuntimeCacheException(e.getMessage());\r\n }\r\n }", "private synchronized Response doAuthenticatedRequest(\n final StitchAuthRequest stitchReq,\n final AuthInfo authInfo\n ) {\n try {\n return requestClient.doRequest(prepareAuthRequest(stitchReq, authInfo));\n } catch (final StitchServiceException ex) {\n return handleAuthFailure(ex, stitchReq);\n }\n }", "public static void addLoadInstruction(CodeAttribute code, String type, int variable) {\n char tp = type.charAt(0);\n if (tp != 'L' && tp != '[') {\n // we have a primitive type\n switch (tp) {\n case 'J':\n code.lload(variable);\n break;\n case 'D':\n code.dload(variable);\n break;\n case 'F':\n code.fload(variable);\n break;\n default:\n code.iload(variable);\n }\n } else {\n code.aload(variable);\n }\n }", "public GeoPermissions getPerms(String photoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PERMS);\r\n parameters.put(\"photo_id\", photoId);\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 // response:\r\n // <perms id=\"240935723\" ispublic=\"1\" iscontact=\"0\" isfriend=\"0\" isfamily=\"0\"/>\r\n GeoPermissions perms = new GeoPermissions();\r\n Element permsElement = response.getPayload();\r\n perms.setPublic(\"1\".equals(permsElement.getAttribute(\"ispublic\")));\r\n perms.setContact(\"1\".equals(permsElement.getAttribute(\"iscontact\")));\r\n perms.setFriend(\"1\".equals(permsElement.getAttribute(\"isfriend\")));\r\n perms.setFamily(\"1\".equals(permsElement.getAttribute(\"isfamily\")));\r\n perms.setId(permsElement.getAttribute(\"id\"));\r\n // I ignore the id attribute. should be the same as the given\r\n // photo id.\r\n return perms;\r\n }" ]
Links the two field names into a single left.right field name. If the left field is empty, right is returned @param left one field name @param right the other field name @return left.right or right if left is an empty string
[ "public static String flatten(String left, String right) {\n\t\treturn left == null || left.isEmpty() ? right : left + \".\" + right;\n\t}" ]
[ "public String getShortMessage(Locale locale) {\n\t\tString message;\n\t\tmessage = translate(Integer.toString(exceptionCode), locale);\n\t\tif (message != null && msgParameters != null && msgParameters.length > 0) {\n\t\t\tfor (int i = 0; i < msgParameters.length; i++) {\n\t\t\t\tboolean isIncluded = false;\n\t\t\t\tString needTranslationParam = \"$${\" + i + \"}\";\n\t\t\t\tif (message.contains(needTranslationParam)) {\n\t\t\t\t\tString translation = translate(msgParameters[i], locale);\n\t\t\t\t\tif (null == translation && null != msgParameters[i]) {\n\t\t\t\t\t\ttranslation = msgParameters[i].toString();\n\t\t\t\t\t}\n\t\t\t\t\tif (null == translation) {\n\t\t\t\t\t\ttranslation = \"[null]\";\n\t\t\t\t\t}\n\t\t\t\t\tmessage = message.replace(needTranslationParam, translation);\n\t\t\t\t\tisIncluded = true;\n\t\t\t\t}\n\t\t\t\tString verbatimParam = \"${\" + i + \"}\";\n\t\t\t\tString rs = null == msgParameters[i] ? \"[null]\" : msgParameters[i].toString();\n\t\t\t\tif (message.contains(verbatimParam)) {\n\t\t\t\t\tmessage = message.replace(verbatimParam, rs);\n\t\t\t\t\tisIncluded = true;\n\t\t\t\t}\n\t\t\t\tif (!isIncluded) {\n\t\t\t\t\tmessage = message + \" (\" + rs + \")\"; // NOSONAR replace/contains makes StringBuilder use difficult\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn message;\n\t}", "@Override\n public final int getInt(final String key) {\n Integer result = optInt(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }", "private RawGcsCreationToken put(final GcsRestCreationToken token, ByteBuffer chunk,\n final boolean isFinalChunk, long timeoutMillis) throws IOException {\n final int length = chunk.remaining();\n HTTPRequest req = createPutRequest(token, chunk, isFinalChunk, timeoutMillis, length);\n HTTPRequestInfo info = new HTTPRequestInfo(req);\n HTTPResponse response;\n try {\n response = urlfetch.fetch(req);\n } catch (IOException e) {\n throw createIOException(info, e);\n }\n return handlePutResponse(token, isFinalChunk, length, info, response);\n }", "public ItemRequest<Attachment> createOnTask(String task, InputStream fileContent, String fileName, String fileType) {\n MultipartContent.Part part = new MultipartContent.Part()\n .setContent(new InputStreamContent(fileType, fileContent))\n .setHeaders(new HttpHeaders().set(\n \"Content-Disposition\",\n String.format(\"form-data; name=\\\"file\\\"; filename=\\\"%s\\\"\", fileName) // TODO: escape fileName?\n ));\n MultipartContent content = new MultipartContent()\n .setMediaType(new HttpMediaType(\"multipart/form-data\").setParameter(\"boundary\", UUID.randomUUID().toString()))\n .addPart(part);\n\n String path = String.format(\"/tasks/%s/attachments\", task);\n return new ItemRequest<Attachment>(this, Attachment.class, path, \"POST\")\n .data(content);\n }", "private void instanceAlreadyLoaded(\n\t\tfinal Tuple resultset,\n\t\tfinal int i,\n\t\t\t//TODO create an interface for this usage\n\t\tfinal OgmEntityPersister persister,\n\t\tfinal org.hibernate.engine.spi.EntityKey key,\n\t\tfinal Object object,\n\t\tfinal LockMode lockMode,\n\t\tfinal SharedSessionContractImplementor session)\n\tthrows HibernateException {\n\t\tif ( !persister.isInstance( object ) ) {\n\t\t\tthrow new WrongClassException(\n\t\t\t\t\t\"loaded object was of wrong class \" + object.getClass(),\n\t\t\t\t\tkey.getIdentifier(),\n\t\t\t\t\tpersister.getEntityName()\n\t\t\t\t);\n\t\t}\n\n\t\tif ( LockMode.NONE != lockMode && upgradeLocks() ) { // no point doing this if NONE was requested\n\n\t\t\tfinal boolean isVersionCheckNeeded = persister.isVersioned() &&\n\t\t\t\t\tsession.getPersistenceContext().getEntry( object )\n\t\t\t\t\t\t\t.getLockMode().lessThan( lockMode );\n\t\t\t// we don't need to worry about existing version being uninitialized\n\t\t\t// because this block isn't called by a re-entrant load (re-entrant\n\t\t\t// loads _always_ have lock mode NONE)\n\t\t\tif ( isVersionCheckNeeded ) {\n\t\t\t\t//we only check the version when _upgrading_ lock modes\n\t\t\t\tObject oldVersion = session.getPersistenceContext().getEntry( object ).getVersion();\n\t\t\t\tpersister.checkVersionAndRaiseSOSE( key.getIdentifier(), oldVersion, session, resultset );\n\t\t\t\t//we need to upgrade the lock mode to the mode requested\n\t\t\t\tsession.getPersistenceContext().getEntry( object )\n\t\t\t\t\t\t.setLockMode( lockMode );\n\t\t\t}\n\t\t}\n\t}", "public void unlink(Object obj, ObjectReferenceDescriptor ord, boolean insert)\r\n {\r\n linkOrUnlink(false, obj, ord, insert);\r\n }", "public PeriodicEvent runEvery(Runnable task, float delay, float period,\n KeepRunning callback) {\n validateDelay(delay);\n validatePeriod(period);\n return new Event(task, delay, period, callback);\n }", "@SuppressWarnings(\"deprecation\")\n public BUILDER setAllowedValues(String ... allowedValues) {\n assert allowedValues!= null;\n this.allowedValues = new ModelNode[allowedValues.length];\n for (int i = 0; i < allowedValues.length; i++) {\n this.allowedValues[i] = new ModelNode(allowedValues[i]);\n }\n return (BUILDER) this;\n }", "protected void postProcessing()\n {\n //\n // Update the internal structure. We'll take this opportunity to\n // generate outline numbers for the tasks as they don't appear to\n // be present in the MPP file.\n //\n ProjectConfig config = m_project.getProjectConfig();\n config.setAutoWBS(m_autoWBS);\n config.setAutoOutlineNumber(true);\n m_project.updateStructure();\n config.setAutoOutlineNumber(false);\n\n //\n // Perform post-processing to set the summary flag\n //\n for (Task task : m_project.getTasks())\n {\n task.setSummary(task.hasChildTasks());\n }\n\n //\n // Ensure that the unique ID counters are correct\n //\n config.updateUniqueCounters();\n }" ]
Load assertion from the provided json or throw exception if not possible. @param encodedAssertion the assertion as it was encoded in JSON.
[ "public AccessAssertion unmarshal(final JSONObject encodedAssertion) {\n final String className;\n try {\n className = encodedAssertion.getString(JSON_CLASS_NAME);\n final Class<?> assertionClass =\n Thread.currentThread().getContextClassLoader().loadClass(className);\n final AccessAssertion assertion =\n (AccessAssertion) this.applicationContext.getBean(assertionClass);\n assertion.unmarshal(encodedAssertion);\n\n return assertion;\n } catch (JSONException | ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n }" ]
[ "public static Map<String, String> getContentMap(File file, String separator) throws IOException {\n List<String> content = getContentLines(file);\n Map<String, String> map = new LinkedHashMap<String, String>();\n \n for (String line : content) {\n String[] spl = line.split(separator);\n if (line.trim().length() > 0) {\n map.put(spl[0], (spl.length > 1 ? spl[1] : \"\"));\n }\n }\n \n return map;\n }", "public boolean evaluate(Object feature) {\n\t\t// Checks to ensure that the attribute has been set\n\t\tif (attribute == null) {\n\t\t\treturn false;\n\t\t}\n\t\t// Note that this converts the attribute to a string\n\t\t// for comparison. Unlike the math or geometry filters, which\n\t\t// require specific types to function correctly, this filter\n\t\t// using the mandatory string representation in Java\n\t\t// Of course, this does not guarantee a meaningful result, but it\n\t\t// does guarantee a valid result.\n\t\t// LOGGER.finest(\"pattern: \" + pattern);\n\t\t// LOGGER.finest(\"string: \" + attribute.getValue(feature));\n\t\t// return attribute.getValue(feature).toString().matches(pattern);\n\t\tObject value = attribute.evaluate(feature);\n\n\t\tif (null == value) {\n\t\t\treturn false;\n\t\t}\n\n\t\tMatcher matcher = getMatcher();\n\t\tmatcher.reset(value.toString());\n\n\t\treturn matcher.matches();\n\t}", "public static base_responses enable(nitro_service client, String id[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (id != null && id.length > 0) {\n\t\t\tInterface enableresources[] = new Interface[id.length];\n\t\t\tfor (int i=0;i<id.length;i++){\n\t\t\t\tenableresources[i] = new Interface();\n\t\t\t\tenableresources[i].id = id[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}", "private Profile getProfileFromResultSet(ResultSet result) throws Exception {\n Profile profile = new Profile();\n profile.setId(result.getInt(Constants.GENERIC_ID));\n Clob clobProfileName = result.getClob(Constants.PROFILE_PROFILE_NAME);\n String profileName = clobProfileName.getSubString(1, (int) clobProfileName.length());\n profile.setName(profileName);\n return profile;\n }", "private boolean containsValue(StatementGroup statementGroup, Value value) {\n\t\tfor (Statement s : statementGroup) {\n\t\t\tif (value.equals(s.getValue())) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}", "private static QName getServiceName(Server server) {\n QName serviceName;\n String bindingId = getBindingId(server);\n EndpointInfo eInfo = server.getEndpoint().getEndpointInfo();\n \n if (JAXRS_BINDING_ID.equals(bindingId)) {\n serviceName = eInfo.getName();\n } else {\n ServiceInfo serviceInfo = eInfo.getService();\n serviceName = serviceInfo.getName();\n }\n return serviceName;\n }", "private Profile getProfileFromResultSet(ResultSet result) throws Exception {\n Profile profile = new Profile();\n profile.setId(result.getInt(Constants.GENERIC_ID));\n Clob clobProfileName = result.getClob(Constants.PROFILE_PROFILE_NAME);\n String profileName = clobProfileName.getSubString(1, (int) clobProfileName.length());\n profile.setName(profileName);\n return profile;\n }", "public static byte[] copy(byte[] array, int from, int to) {\n if(to - from < 0) {\n return new byte[0];\n } else {\n byte[] a = new byte[to - from];\n System.arraycopy(array, from, a, 0, to - from);\n return a;\n }\n }", "protected void createSequence(PersistenceBroker broker, FieldDescriptor field,\r\n String sequenceName, long maxKey) throws Exception\r\n {\r\n Statement stmt = null;\r\n try\r\n {\r\n stmt = broker.serviceStatementManager().getGenericStatement(field.getClassDescriptor(), Query.NOT_SCROLLABLE);\r\n stmt.execute(sp_createSequenceQuery(sequenceName, maxKey));\r\n }\r\n catch (Exception e)\r\n {\r\n log.error(e);\r\n throw new SequenceManagerException(\"Could not create new row in \"+SEQ_TABLE_NAME+\" table - TABLENAME=\" +\r\n sequenceName + \" field=\" + field.getColumnName(), e);\r\n }\r\n finally\r\n {\r\n try\r\n {\r\n if (stmt != null) stmt.close();\r\n }\r\n catch (SQLException sqle)\r\n {\r\n if(log.isDebugEnabled())\r\n log.debug(\"Threw SQLException while in createSequence and closing stmt\", sqle);\r\n // ignore it\r\n }\r\n }\r\n }" ]
Sets the path name for this ID @param pathId ID of path @param pathName Name of path
[ "public void setName(int pathId, String pathName) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + Constants.PATH_PROFILE_PATHNAME + \" = ?\" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, pathName);\n statement.setInt(2, pathId);\n statement.executeUpdate();\n statement.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }" ]
[ "public void setAngularLowerLimits(float limitX, float limitY, float limitZ) {\n Native3DGenericConstraint.setAngularLowerLimits(getNative(), limitX, limitY, limitZ);\n }", "public void removeLinks(ServiceReference<S> declarationBinderRef) {\n for (D declaration : linkerManagement.getMatchedDeclaration()) {\n if (declaration.getStatus().getServiceReferencesBounded().contains(declarationBinderRef)) {\n linkerManagement.unlink(declaration, declarationBinderRef);\n }\n }\n }", "public void addTags(String photoId, String[] tags) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ADD_TAGS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"tags\", StringUtilities.join(tags, \" \", true));\r\n\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }", "public void addProcedure(ProcedureDef procDef)\r\n {\r\n procDef.setOwner(this);\r\n _procedures.put(procDef.getName(), procDef);\r\n }", "public static int cudnnRestoreDropoutDescriptor(\n cudnnDropoutDescriptor dropoutDesc, \n cudnnHandle handle, \n float dropout, \n Pointer states, \n long stateSizeInBytes, \n long seed)\n {\n return checkResult(cudnnRestoreDropoutDescriptorNative(dropoutDesc, handle, dropout, states, stateSizeInBytes, seed));\n }", "public Constructor getZeroArgumentConstructor()\r\n {\r\n if (zeroArgumentConstructor == null && !alreadyLookedupZeroArguments)\r\n {\r\n try\r\n {\r\n zeroArgumentConstructor = getClassOfObject().getConstructor(NO_PARAMS);\r\n }\r\n catch (NoSuchMethodException e)\r\n {\r\n //no public zero argument constructor available let's try for a private/protected one\r\n try\r\n {\r\n zeroArgumentConstructor = getClassOfObject().getDeclaredConstructor(NO_PARAMS);\r\n\r\n //we found one, now let's make it accessible\r\n zeroArgumentConstructor.setAccessible(true);\r\n }\r\n catch (NoSuchMethodException e2)\r\n {\r\n //out of options, log the fact and let the method return null\r\n LoggerFactory.getDefaultLogger().warn(\r\n this.getClass().getName()\r\n + \": \"\r\n + \"No zero argument constructor defined for \"\r\n + this.getClassOfObject());\r\n }\r\n }\r\n\r\n alreadyLookedupZeroArguments = true;\r\n }\r\n\r\n return zeroArgumentConstructor;\r\n }", "public static appflowpolicylabel[] get(nitro_service service) throws Exception{\n\t\tappflowpolicylabel obj = new appflowpolicylabel();\n\t\tappflowpolicylabel[] response = (appflowpolicylabel[])obj.get_resources(service);\n\t\treturn response;\n\t}", "protected Map<String, TermImpl> getMonolingualUpdatedValues(Map<String, NameWithUpdate> updates) {\n \tMap<String, TermImpl> updatedValues = new HashMap<>();\n \tfor(NameWithUpdate update : updates.values()) {\n if (!update.write) {\n continue;\n }\n updatedValues.put(update.value.getLanguageCode(), monolingualToJackson(update.value));\n \t}\n \treturn updatedValues;\n }", "public static String nameFromOffset(long offset) {\n NumberFormat nf = NumberFormat.getInstance();\n nf.setMinimumIntegerDigits(20);\n nf.setMaximumFractionDigits(0);\n nf.setGroupingUsed(false);\n return nf.format(offset) + Log.FileSuffix;\n }" ]
Returns an java object read from the specified ResultSet column.
[ "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 }" ]
[ "public String getOriginalValue(ParsedCommandLine parsedLine, boolean required) throws CommandFormatException {\n String value = null;\n if(parsedLine.hasProperties()) {\n if(index >= 0) {\n List<String> others = parsedLine.getOtherProperties();\n if(others.size() > index) {\n return others.get(index);\n }\n }\n\n value = parsedLine.getPropertyValue(fullName);\n if(value == null && shortName != null) {\n value = parsedLine.getPropertyValue(shortName);\n }\n }\n\n if(required && value == null && !isPresent(parsedLine)) {\n StringBuilder buf = new StringBuilder();\n buf.append(\"Required argument \");\n buf.append('\\'').append(fullName).append('\\'');\n buf.append(\" is missing.\");\n throw new CommandFormatException(buf.toString());\n }\n return value;\n }", "public synchronized void init() {\n channelFactory = new NioClientSocketChannelFactory(\n Executors.newCachedThreadPool(),\n Executors.newCachedThreadPool());\n\n datagramChannelFactory = new NioDatagramChannelFactory(\n Executors.newCachedThreadPool());\n\n timer = new HashedWheelTimer();\n }", "private HashMap<String, StoreDefinition> makeStoreDefinitionMap(List<StoreDefinition> storeDefs) {\n HashMap<String, StoreDefinition> storeDefMap = new HashMap<String, StoreDefinition>();\n for(StoreDefinition storeDef: storeDefs)\n storeDefMap.put(storeDef.getName(), storeDef);\n return storeDefMap;\n }", "void writeNoValueRestriction(RdfWriter rdfWriter, String propertyUri,\n\t\t\tString rangeUri, String subject) throws RDFHandlerException {\n\n\t\tResource bnodeSome = rdfWriter.getFreshBNode();\n\t\trdfWriter.writeTripleValueObject(subject, RdfWriter.RDF_TYPE,\n\t\t\t\tRdfWriter.OWL_CLASS);\n\t\trdfWriter.writeTripleValueObject(subject, RdfWriter.OWL_COMPLEMENT_OF,\n\t\t\t\tbnodeSome);\n\t\trdfWriter.writeTripleValueObject(bnodeSome, RdfWriter.RDF_TYPE,\n\t\t\t\tRdfWriter.OWL_RESTRICTION);\n\t\trdfWriter.writeTripleUriObject(bnodeSome, RdfWriter.OWL_ON_PROPERTY,\n\t\t\t\tpropertyUri);\n\t\trdfWriter.writeTripleUriObject(bnodeSome,\n\t\t\t\tRdfWriter.OWL_SOME_VALUES_FROM, rangeUri);\n\t}", "private void initDefaultScopeType(EnhancedAnnotation<T> annotatedAnnotation) {\n Set<Annotation> scopeTypes = new HashSet<Annotation>();\n scopeTypes.addAll(annotatedAnnotation.getMetaAnnotations(Scope.class));\n scopeTypes.addAll(annotatedAnnotation.getMetaAnnotations(NormalScope.class));\n if (scopeTypes.size() > 1) {\n throw MetadataLogger.LOG.multipleScopes(annotatedAnnotation);\n } else if (scopeTypes.size() == 1) {\n this.defaultScopeType = scopeTypes.iterator().next();\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 }", "private boolean isClockwise(Point center, Point a, Point b) {\n double cross = (a.x - center.x) * (b.y - center.y) - (b.x - center.x) * (a.y - center.y);\n return cross > 0;\n }", "public static String replaceFullRequestContent(\n String requestContentTemplate, String replacementString) {\n return (requestContentTemplate.replace(\n PcConstants.COMMAND_VAR_DEFAULT_REQUEST_CONTENT,\n replacementString));\n }", "public BoxFileUploadSession.Info createUploadSession(long fileSize) {\n URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL(), this.getID());\n\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n request.addHeader(\"Content-Type\", \"application/json\");\n\n JsonObject body = new JsonObject();\n body.add(\"file_size\", fileSize);\n request.setBody(body.toString());\n\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n String sessionId = jsonObject.get(\"id\").asString();\n BoxFileUploadSession session = new BoxFileUploadSession(this.getAPI(), sessionId);\n return session.new Info(jsonObject);\n }" ]
Print a percent complete value. @param value Double instance @return percent complete value
[ "public static final String printPercent(Double value)\n {\n return value == null ? null : Double.toString(value.doubleValue() / 100.0);\n }" ]
[ "@Override\n public void run()\n {\n try {\n startBarrier.await();\n\n int idleCount = 0;\n while (!isRunning.compareAndSet(idleCount > lingerIterations && pidToProcessMap.isEmpty(), false)) {\n idleCount = (!shutdown && process()) ? 0 : (idleCount + 1);\n }\n }\n catch (Exception e) {\n // TODO: how to handle this error?\n isRunning.set(false);\n }\n }", "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 }", "List<String> getWarnings(JsonNode root) {\n\t\tArrayList<String> warnings = new ArrayList<>();\n\n\t\tif (root.has(\"warnings\")) {\n\t\t\tJsonNode warningNode = root.path(\"warnings\");\n\t\t\tIterator<Map.Entry<String, JsonNode>> moduleIterator = warningNode\n\t\t\t\t\t.fields();\n\t\t\twhile (moduleIterator.hasNext()) {\n\t\t\t\tMap.Entry<String, JsonNode> moduleNode = moduleIterator.next();\n\t\t\t\tIterator<JsonNode> moduleOutputIterator = moduleNode.getValue()\n\t\t\t\t\t\t.elements();\n\t\t\t\twhile (moduleOutputIterator.hasNext()) {\n\t\t\t\t\tJsonNode moduleOutputNode = moduleOutputIterator.next();\n\t\t\t\t\tif (moduleOutputNode.isTextual()) {\n\t\t\t\t\t\twarnings.add(\"[\" + moduleNode.getKey() + \"]: \"\n\t\t\t\t\t\t\t\t+ moduleOutputNode.textValue());\n\t\t\t\t\t} else if (moduleOutputNode.isArray()) {\n\t\t\t\t\t\tIterator<JsonNode> messageIterator = moduleOutputNode\n\t\t\t\t\t\t\t\t.elements();\n\t\t\t\t\t\twhile (messageIterator.hasNext()) {\n\t\t\t\t\t\t\tJsonNode messageNode = messageIterator.next();\n\t\t\t\t\t\t\twarnings.add(\"[\"\n\t\t\t\t\t\t\t\t\t+ moduleNode.getKey()\n\t\t\t\t\t\t\t\t\t+ \"]: \"\n\t\t\t\t\t\t\t\t\t+ messageNode.path(\"html\").path(\"*\")\n\t\t\t\t\t\t\t\t\t\t\t.asText(messageNode.toString()));\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\twarnings.add(\"[\"\n\t\t\t\t\t\t\t\t+ moduleNode.getKey()\n\t\t\t\t\t\t\t\t+ \"]: \"\n\t\t\t\t\t\t\t\t+ \"Warning was not understood. Please report this to Wikidata Toolkit. JSON source: \"\n\t\t\t\t\t\t\t\t+ moduleOutputNode.toString());\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t\treturn warnings;\n\t}", "@Override\n protected <T> CompletableFuture<T> doExecute(Command<T> command) throws Exception {\n final CompletableFuture<T> future = new CompletableFuture<>();\n executor.execute(() -> {\n try {\n future.complete(blockingExecute(command));\n } catch (Throwable t) {\n future.completeExceptionally(t);\n }\n });\n return future;\n }", "@SuppressWarnings(\"unchecked\")\n public static <T> void defaultHandleContextMenuForMultiselect(\n Table table,\n CmsContextMenu menu,\n ItemClickEvent event,\n List<I_CmsSimpleContextMenuEntry<Collection<T>>> entries) {\n\n if (!event.isCtrlKey() && !event.isShiftKey()) {\n if (event.getButton().equals(MouseButton.RIGHT)) {\n Collection<T> oldValue = ((Collection<T>)table.getValue());\n if (oldValue.isEmpty() || !oldValue.contains(event.getItemId())) {\n table.setValue(new HashSet<Object>(Arrays.asList(event.getItemId())));\n }\n Collection<T> selection = (Collection<T>)table.getValue();\n menu.setEntries(entries, selection);\n menu.openForTable(event, table);\n }\n }\n\n }", "public List<Widget> getAllViews() {\n List<Widget> views = new ArrayList<>();\n for (Widget child: mContent.getChildren()) {\n Widget item = ((ListItemHostWidget) child).getGuest();\n if (item != null) {\n views.add(item);\n }\n }\n return views;\n }", "static void logConnectionException(URI uri, DiscoveryOption discoveryOption, boolean moreOptions, Exception e) {\n if (uri == null) {\n HostControllerLogger.ROOT_LOGGER.failedDiscoveringMaster(discoveryOption, e);\n } else {\n HostControllerLogger.ROOT_LOGGER.cannotConnect(uri, e);\n }\n if (!moreOptions) {\n // All discovery options have been exhausted\n HostControllerLogger.ROOT_LOGGER.noDiscoveryOptionsLeft();\n }\n }", "public void setHeader(String header) {\n headerLabel.getElement().setInnerSafeHtml(SafeHtmlUtils.fromString(header));\n addStyleName(CssName.WITH_HEADER);\n ListItem item = new ListItem(headerLabel);\n UiHelper.addMousePressedHandlers(item);\n item.setStyleName(CssName.COLLECTION_HEADER);\n insert(item, 0);\n }", "public T withLabel(String text, String languageCode) {\n\t\twithLabel(factory.getMonolingualTextValue(text, languageCode));\n\t\treturn getThis();\n\t}" ]
Retrieves the members of the type and of its super types. @param memberNames Will receive the names of the members (for sorting) @param members Will receive the members @param type The type to process @param tagName An optional tag for filtering the types @param paramName The feature to be added to the MembersInclSupertypes attribute @param paramValue The feature to be added to the MembersInclSupertypes attribute @throws XDocletException If an error occurs
[ "private void addMembersInclSupertypes(Collection memberNames, HashMap members, XClass type, String tagName, String paramName, String paramValue) throws XDocletException\r\n {\r\n addMembers(memberNames, members, type, tagName, paramName, paramValue);\r\n if (type.getInterfaces() != null) {\r\n for (Iterator it = type.getInterfaces().iterator(); it.hasNext(); ) {\r\n addMembersInclSupertypes(memberNames, members, (XClass)it.next(), tagName, paramName, paramValue);\r\n }\r\n }\r\n if (!type.isInterface() && (type.getSuperclass() != null)) {\r\n addMembersInclSupertypes(memberNames, members, type.getSuperclass(), tagName, paramName, paramValue);\r\n }\r\n }" ]
[ "public static base_response unset(nitro_service client, nsdiameter resource, String[] args) throws Exception{\n\t\tnsdiameter unsetresource = new nsdiameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "int getDelay(int n) {\n int delay = -1;\n if ((n >= 0) && (n < header.frameCount)) {\n delay = header.frames.get(n).delay;\n }\n return delay;\n }", "private void recordTime(Tracked op,\n long timeNS,\n long numEmptyResponses,\n long valueSize,\n long keySize,\n long getAllAggregateRequests) {\n counters.get(op).addRequest(timeNS,\n numEmptyResponses,\n valueSize,\n keySize,\n getAllAggregateRequests);\n\n if (logger.isTraceEnabled() && !storeName.contains(\"aggregate\") && !storeName.contains(\"voldsys$\"))\n logger.trace(\"Store '\" + storeName + \"' logged a \" + op.toString() + \" request taking \" +\n ((double) timeNS / voldemort.utils.Time.NS_PER_MS) + \" ms\");\n }", "public static Collection<String> getFormatProviderNames() {\n Collection<String> providers = Optional.ofNullable(getMonetaryFormatsSpi()).orElseThrow(\n () -> new MonetaryException(\n \"No MonetaryFormatsSingletonSpi loaded, query functionality is not available.\"))\n .getProviderNames();\n if (Objects.isNull(providers)) {\n Logger.getLogger(MonetaryFormats.class.getName()).warning(\n \"No supported rate/conversion providers returned by SPI: \" +\n getMonetaryFormatsSpi().getClass().getName());\n return Collections.emptySet();\n }\n return providers;\n }", "public void removeFilter(String filterName)\n {\n Filter filter = getFilterByName(filterName);\n if (filter != null)\n {\n if (filter.isTaskFilter())\n {\n m_taskFilters.remove(filter);\n }\n\n if (filter.isResourceFilter())\n {\n m_resourceFilters.remove(filter);\n }\n m_filtersByName.remove(filterName);\n m_filtersByID.remove(filter.getID());\n }\n }", "@Override\n public void map(GenericData.Record record,\n AvroCollector<Pair<ByteBuffer, ByteBuffer>> collector,\n Reporter reporter) throws IOException {\n\n byte[] keyBytes = null;\n byte[] valBytes = null;\n Object keyRecord = null;\n Object valRecord = null;\n try {\n keyRecord = record.get(keyField);\n valRecord = record.get(valField);\n keyBytes = keySerializer.toBytes(keyRecord);\n valBytes = valueSerializer.toBytes(valRecord);\n\n this.collectorWrapper.setCollector(collector);\n this.mapper.map(keyBytes, valBytes, this.collectorWrapper);\n\n recordCounter++;\n } catch (OutOfMemoryError oom) {\n logger.error(oomErrorMessage(reporter));\n if (keyBytes == null) {\n logger.error(\"keyRecord caused OOM!\");\n } else {\n logger.error(\"keyRecord: \" + keyRecord);\n logger.error(\"valRecord: \" + (valBytes == null ? \"caused OOM\" : valRecord));\n }\n throw new VoldemortException(oomErrorMessage(reporter), oom);\n }\n }", "protected static void checkChannels(final Iterable<String> channels) {\n if (channels == null) {\n throw new IllegalArgumentException(\"channels must not be null\");\n }\n for (final String channel : channels) {\n if (channel == null || \"\".equals(channel)) {\n throw new IllegalArgumentException(\"channels' members must not be null: \" + channels);\n }\n }\n }", "public boolean isObjectsFieldValueDefault(Object object) throws SQLException {\n\t\tObject fieldValue = extractJavaFieldValue(object);\n\t\treturn isFieldValueDefault(fieldValue);\n\t}", "private Object instanceNotYetLoaded(\n\t\tfinal Tuple resultset,\n\t\tfinal int i,\n\t\tfinal Loadable persister,\n\t\tfinal String rowIdAlias,\n\t\tfinal org.hibernate.engine.spi.EntityKey key,\n\t\tfinal LockMode lockMode,\n\t\tfinal org.hibernate.engine.spi.EntityKey optionalObjectKey,\n\t\tfinal Object optionalObject,\n\t\tfinal List hydratedObjects,\n\t\tfinal SharedSessionContractImplementor session)\n\tthrows HibernateException {\n\t\tfinal String instanceClass = getInstanceClass(\n\t\t\t\tresultset,\n\t\t\t\ti,\n\t\t\t\tpersister,\n\t\t\t\tkey.getIdentifier(),\n\t\t\t\tsession\n\t\t\t);\n\n\t\tfinal Object object;\n\t\tif ( optionalObjectKey != null && key.equals( optionalObjectKey ) ) {\n\t\t\t//its the given optional object\n\t\t\tobject = optionalObject;\n\t\t}\n\t\telse {\n\t\t\t// instantiate a new instance\n\t\t\tobject = session.instantiate( instanceClass, key.getIdentifier() );\n\t\t}\n\n\t\t//need to hydrate it.\n\n\t\t// grab its state from the ResultSet and keep it in the Session\n\t\t// (but don't yet initialize the object itself)\n\t\t// note that we acquire LockMode.READ even if it was not requested\n\t\tLockMode acquiredLockMode = lockMode == LockMode.NONE ? LockMode.READ : lockMode;\n\t\tloadFromResultSet(\n\t\t\t\tresultset,\n\t\t\t\ti,\n\t\t\t\tobject,\n\t\t\t\tinstanceClass,\n\t\t\t\tkey,\n\t\t\t\trowIdAlias,\n\t\t\t\tacquiredLockMode,\n\t\t\t\tpersister,\n\t\t\t\tsession\n\t\t\t);\n\n\t\t//materialize associations (and initialize the object) later\n\t\thydratedObjects.add( object );\n\n\t\treturn object;\n\t}" ]
Updates the existing cluster such that we remove partitions mentioned from the stealer node and add them to the donor node @param currentCluster Existing cluster metadata. Both stealer and donor node should already exist in this metadata @param stealerNodeId Id of node for which we are stealing the partitions @param donatedPartitions List of partitions we are moving @return Updated cluster metadata
[ "public static Cluster createUpdatedCluster(Cluster currentCluster,\n int stealerNodeId,\n List<Integer> donatedPartitions) {\n Cluster updatedCluster = Cluster.cloneCluster(currentCluster);\n // Go over every donated partition one by one\n for(int donatedPartition: donatedPartitions) {\n\n // Gets the donor Node that owns this donated partition\n Node donorNode = updatedCluster.getNodeForPartitionId(donatedPartition);\n Node stealerNode = updatedCluster.getNodeById(stealerNodeId);\n\n if(donorNode == stealerNode) {\n // Moving to the same location = No-op\n continue;\n }\n\n // Update the list of partitions for this node\n donorNode = removePartitionFromNode(donorNode, donatedPartition);\n stealerNode = addPartitionToNode(stealerNode, donatedPartition);\n\n // Sort the nodes\n updatedCluster = updateCluster(updatedCluster,\n Lists.newArrayList(donorNode, stealerNode));\n\n }\n\n return updatedCluster;\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 }", "@Override\n public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {\n final ServletRequest r1 = request;\n chain.doFilter(request, new HttpServletResponseWrapper((HttpServletResponse) response) {\n @SuppressWarnings(\"unchecked\")\n public void setHeader(String name, String value) {\n ArrayList<String> headersToRemove = new ArrayList<String>();\n \n if (r1.getAttribute(\"com.groupon.odo.removeHeaders\") != null)\n headersToRemove = (ArrayList<String>) r1.getAttribute(\"com.groupon.odo.removeHeaders\");\n\n boolean removeHeader = false;\n // need to loop through removeHeaders to make things case insensitive\n for (String headerToRemove : headersToRemove) {\n if (headerToRemove.toLowerCase().equals(name.toLowerCase())) {\n removeHeader = true;\n break;\n }\n }\n\n if (! removeHeader) {\n super.setHeader(name, value);\n }\n }\n });\n }", "public static base_responses reset(nitro_service client, Interface resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tInterface resetresources[] = new Interface[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tresetresources[i] = new Interface();\n\t\t\t\tresetresources[i].id = resources[i].id;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, resetresources,\"reset\");\n\t\t}\n\t\treturn result;\n\t}", "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 float conditionalLogProb(int[] given, int of) {\r\n if (given.length != windowSize - 1) {\r\n System.err.println(\"error computing conditional log prob\");\r\n System.exit(0);\r\n }\r\n int[] label = indicesFront(given);\r\n float[] masses = new float[label.length];\r\n for (int i = 0; i < masses.length; i++) {\r\n masses[i] = table[label[i]];\r\n }\r\n float z = ArrayMath.logSum(masses);\r\n\r\n return table[indexOf(given, of)] - z;\r\n }", "public Photo getListPhoto(String photoId) throws FlickrException {\n\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_LIST_PHOTO);\n\n parameters.put(\"photo_id\", photoId);\n\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\n if (response.isError()) {\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\n }\n\n Element photoElement = response.getPayload();\n Photo photo = new Photo();\n photo.setId(photoElement.getAttribute(\"id\"));\n\n List<Tag> tags = new ArrayList<Tag>();\n Element tagsElement = (Element) photoElement.getElementsByTagName(\"tags\").item(0);\n NodeList tagElements = tagsElement.getElementsByTagName(\"tag\");\n for (int i = 0; i < tagElements.getLength(); i++) {\n Element tagElement = (Element) tagElements.item(i);\n Tag tag = new Tag();\n tag.setId(tagElement.getAttribute(\"id\"));\n tag.setAuthor(tagElement.getAttribute(\"author\"));\n tag.setAuthorName(tagElement.getAttribute(\"authorname\"));\n tag.setRaw(tagElement.getAttribute(\"raw\"));\n tag.setValue(((Text) tagElement.getFirstChild()).getData());\n tags.add(tag);\n }\n photo.setTags(tags);\n return photo;\n }", "private void processCalendars() throws IOException\n {\n CalendarReader reader = new CalendarReader(m_data.getTableData(\"Calendars\"));\n reader.read();\n\n for (MapRow row : reader.getRows())\n {\n processCalendar(row);\n }\n\n m_project.setDefaultCalendar(m_calendarMap.get(reader.getDefaultCalendarUUID()));\n }", "public List<Release> listReleases(String appName) {\n return connection.execute(new ReleaseList(appName), apiKey);\n }", "public static cachepolicylabel_binding get(nitro_service service, String labelname) throws Exception{\n\t\tcachepolicylabel_binding obj = new cachepolicylabel_binding();\n\t\tobj.set_labelname(labelname);\n\t\tcachepolicylabel_binding response = (cachepolicylabel_binding) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
Checks to see if the token is in the list of allowed character operations. Used to apply order of operations @param token Token being checked @param ops List of allowed character operations @return true for it being in the list and false for it not being in the list
[ "protected static boolean isTargetOp( TokenList.Token token , Symbol[] ops ) {\n Symbol c = token.symbol;\n for (int i = 0; i < ops.length; i++) {\n if( c == ops[i])\n return true;\n }\n return false;\n }" ]
[ "public static void count() {\n long duration = SystemClock.uptimeMillis() - startTime;\n float avgFPS = sumFrames / (duration / 1000f);\n\n Log.v(\"FPSCounter\",\n \"total frames = %d, total elapsed time = %d ms, average fps = %f\",\n sumFrames, duration, avgFPS);\n }", "public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {\n final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();\n for (ResourceRoot resourceRoot : DeploymentUtils.allResourceRoots(deploymentUnit)) {\n ResourceRootIndexer.indexResourceRoot(resourceRoot);\n }\n }", "private static JSONObject parseStencilSet(StencilSet stencilSet) throws JSONException {\n if (stencilSet != null) {\n JSONObject stencilSetObject = new JSONObject();\n\n stencilSetObject.put(\"url\",\n stencilSet.getUrl().toString());\n stencilSetObject.put(\"namespace\",\n stencilSet.getNamespace().toString());\n\n return stencilSetObject;\n }\n\n return new JSONObject();\n }", "public static Region fromName(String name) {\n if (name == null) {\n return null;\n }\n\n Region region = VALUES_BY_NAME.get(name.toLowerCase().replace(\" \", \"\"));\n if (region != null) {\n return region;\n } else {\n return Region.create(name.toLowerCase().replace(\" \", \"\"), name);\n }\n }", "public InetSocketAddress getMulticastSocketAddress() {\n if (multicastAddress == null) {\n throw MESSAGES.noMulticastBinding(name);\n }\n return new InetSocketAddress(multicastAddress, multicastPort);\n }", "public static<A, B, Z> Function2<A, B, Z> lift(Func2<A, B, Z> f) {\n\treturn bridge.lift(f);\n }", "private ReferenceDescriptorDef cloneReference(ReferenceDescriptorDef refDef, String prefix)\r\n {\r\n ReferenceDescriptorDef copyRefDef = new ReferenceDescriptorDef(refDef, prefix);\r\n\r\n copyRefDef.setOwner(this);\r\n // we remove properties that are only relevant to the class the features are declared in\r\n copyRefDef.setProperty(PropertyHelper.OJB_PROPERTY_IGNORE, null);\r\n \r\n Properties mod = getModification(copyRefDef.getName());\r\n\r\n if (mod != null)\r\n {\r\n if (!PropertyHelper.toBoolean(mod.getProperty(PropertyHelper.OJB_PROPERTY_IGNORE), false) &&\r\n hasFeature(copyRefDef.getName()))\r\n {\r\n LogHelper.warn(true,\r\n ClassDescriptorDef.class,\r\n \"process\",\r\n \"Class \"+getName()+\" has a feature that has the same name as its included reference \"+\r\n copyRefDef.getName()+\" from class \"+refDef.getOwner().getName()); \r\n }\r\n copyRefDef.applyModifications(mod);\r\n }\r\n return copyRefDef;\r\n }", "public Release getReleaseInfo(String appName, String releaseName) {\n return connection.execute(new ReleaseInfo(appName, releaseName), apiKey);\n }", "public Node insertEntity(GraphDatabaseService executionEngine, Object[] columnValues) {\n\t\tMap<String, Object> params = params( columnValues );\n\t\tResult result = executionEngine.execute( getCreateEntityQuery(), params );\n\t\treturn singleResult( result );\n\t}" ]
Attempt to reconnect to Redis. @param jedis the connection to Redis @param reconAttempts number of times to attempt to reconnect before giving up @param reconnectSleepTime time in milliseconds to wait between attempts @return true if reconnection was successful
[ "public static boolean reconnect(final Jedis jedis, final int reconAttempts, final long reconnectSleepTime) {\n int i = 1;\n do {\n try {\n jedis.disconnect();\n try {\n Thread.sleep(reconnectSleepTime);\n } catch (Exception e2) {\n }\n jedis.connect();\n } catch (JedisConnectionException jce) {\n } // Ignore bad connection attempts\n catch (Exception e3) {\n LOG.error(\"Unknown Exception while trying to reconnect to Redis\", e3);\n }\n } while (++i <= reconAttempts && !testJedisConnection(jedis));\n return testJedisConnection(jedis);\n }" ]
[ "public Map<String, CmsCategory> getReadCategory() {\n\n if (null == m_categories) {\n m_categories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n public Object transform(Object categoryPath) {\n\n try {\n CmsCategoryService catService = CmsCategoryService.getInstance();\n return catService.localizeCategory(\n m_cms,\n catService.readCategory(m_cms, (String)categoryPath, getRequestContext().getUri()),\n m_cms.getRequestContext().getLocale());\n } catch (CmsException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n return null;\n }\n }\n\n });\n }\n return m_categories;\n }", "private void printStatistics(UsageStatistics usageStatistics,\n\t\t\tString entityLabel) {\n\t\tSystem.out.println(\"Processed \" + usageStatistics.count + \" \"\n\t\t\t\t+ entityLabel + \":\");\n\t\tSystem.out.println(\" * Labels: \" + usageStatistics.countLabels\n\t\t\t\t+ \", descriptions: \" + usageStatistics.countDescriptions\n\t\t\t\t+ \", aliases: \" + usageStatistics.countAliases);\n\t\tSystem.out.println(\" * Statements: \" + usageStatistics.countStatements\n\t\t\t\t+ \", with references: \"\n\t\t\t\t+ usageStatistics.countReferencedStatements);\n\t}", "private void stopAllServersAndRemoveCamelContext(CamelContext camelContext) {\n log.debug(\"Stopping all servers associated with {}\", camelContext);\n List<SingleBusLocatorRegistrar> registrars = locatorRegistrar.getAllRegistars(camelContext);\n registrars.forEach(registrar -> registrar.stopAllServersAndRemoveCamelContext());\n }", "public static void invert( final int blockLength ,\n final boolean upper ,\n final DSubmatrixD1 T ,\n final DSubmatrixD1 T_inv ,\n final double temp[] )\n {\n if( upper )\n throw new IllegalArgumentException(\"Upper triangular matrices not supported yet\");\n\n if( temp.length < blockLength*blockLength )\n throw new IllegalArgumentException(\"Temp must be at least blockLength*blockLength long.\");\n\n if( T.row0 != T_inv.row0 || T.row1 != T_inv.row1 || T.col0 != T_inv.col0 || T.col1 != T_inv.col1)\n throw new IllegalArgumentException(\"T and T_inv must be at the same elements in the matrix\");\n\n final int M = T.row1-T.row0;\n\n final double dataT[] = T.original.data;\n final double dataX[] = T_inv.original.data;\n\n final int offsetT = T.row0*T.original.numCols+M*T.col0;\n\n for( int i = 0; i < M; i += blockLength ) {\n int heightT = Math.min(T.row1-(i+T.row0),blockLength);\n\n int indexII = offsetT + T.original.numCols*(i+T.row0) + heightT*(i+T.col0);\n\n for( int j = 0; j < i; j += blockLength ) {\n int widthX = Math.min(T.col1-(j+T.col0),blockLength);\n\n for( int w = 0; w < temp.length; w++ ) {\n temp[w] = 0;\n }\n\n for( int k = j; k < i; k += blockLength ) {\n int widthT = Math.min(T.col1-(k+T.col0),blockLength);\n\n int indexL = offsetT + T.original.numCols*(i+T.row0) + heightT*(k+T.col0);\n int indexX = offsetT + T.original.numCols*(k+T.row0) + widthT*(j+T.col0);\n\n blockMultMinus(dataT,dataX,temp,indexL,indexX,0,heightT,widthT,widthX);\n }\n\n int indexX = offsetT + T.original.numCols*(i+T.row0) + heightT*(j+T.col0);\n\n InnerTriangularSolver_DDRB.solveL(dataT,temp,heightT,widthX,heightT,indexII,0);\n System.arraycopy(temp,0,dataX,indexX,widthX*heightT);\n }\n InnerTriangularSolver_DDRB.invertLower(dataT,dataX,heightT,indexII,indexII);\n }\n }", "private boolean computeUWV() {\n bidiag.getDiagonal(diag,off);\n qralg.setMatrix(numRowsT,numColsT,diag,off);\n\n// long pointA = System.currentTimeMillis();\n // compute U and V matrices\n if( computeU )\n Ut = bidiag.getU(Ut,true,compact);\n if( computeV )\n Vt = bidiag.getV(Vt,true,compact);\n\n qralg.setFastValues(false);\n if( computeU )\n qralg.setUt(Ut);\n else\n qralg.setUt(null);\n if( computeV )\n qralg.setVt(Vt);\n else\n qralg.setVt(null);\n\n// long pointB = System.currentTimeMillis();\n\n boolean ret = !qralg.process();\n\n// long pointC = System.currentTimeMillis();\n// System.out.println(\" compute UV \"+(pointB-pointA)+\" QR = \"+(pointC-pointB));\n\n return ret;\n }", "public ItemRequest<Task> dependencies(String task) {\n \n String path = String.format(\"/tasks/%s/dependencies\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"GET\");\n }", "public InputStream call(String methodName, MessageLite request) throws DatastoreException {\n logger.fine(\"remote datastore call \" + methodName);\n\n long startTime = System.currentTimeMillis();\n try {\n HttpResponse httpResponse;\n try {\n rpcCount.incrementAndGet();\n ProtoHttpContent payload = new ProtoHttpContent(request);\n HttpRequest httpRequest = client.buildPostRequest(resolveURL(methodName), payload);\n httpRequest.getHeaders().put(API_FORMAT_VERSION_HEADER, API_FORMAT_VERSION);\n // Don't throw an HTTPResponseException on error. It converts the response to a String and\n // throws away the original, whereas we need the raw bytes to parse it as a proto.\n httpRequest.setThrowExceptionOnExecuteError(false);\n // Datastore requests typically time out after 60s; set the read timeout to slightly longer\n // than that by default (can be overridden via the HttpRequestInitializer).\n httpRequest.setReadTimeout(65 * 1000);\n if (initializer != null) {\n initializer.initialize(httpRequest);\n }\n httpResponse = httpRequest.execute();\n if (!httpResponse.isSuccessStatusCode()) {\n try (InputStream content = GzipFixingInputStream.maybeWrap(httpResponse.getContent())) {\n throw makeException(url, methodName, content,\n httpResponse.getContentType(), httpResponse.getContentCharset(), null,\n httpResponse.getStatusCode());\n }\n }\n return GzipFixingInputStream.maybeWrap(httpResponse.getContent());\n } catch (SocketTimeoutException e) {\n throw makeException(url, methodName, Code.DEADLINE_EXCEEDED, \"Deadline exceeded\", e);\n } catch (IOException e) {\n throw makeException(url, methodName, Code.UNAVAILABLE, \"I/O error\", e);\n }\n } finally {\n long elapsedTime = System.currentTimeMillis() - startTime;\n logger.fine(\"remote datastore call \" + methodName + \" took \" + elapsedTime + \" ms\");\n }\n }", "private void handleArchiveByFile(Predicate<String> filter, File archive, List<String> discoveredFiles)\n {\n try\n {\n try (ZipFile zip = new ZipFile(archive))\n {\n Enumeration<? extends ZipEntry> entries = zip.entries();\n \n while (entries.hasMoreElements())\n {\n ZipEntry entry = entries.nextElement();\n String name = entry.getName();\n if (filter.accept(name))\n discoveredFiles.add(name);\n }\n }\n }\n catch (IOException e)\n {\n throw new RuntimeException(\"Error handling file \" + archive, e);\n }\n }", "public boolean hasCachedValue(Key key) {\n\t\ttry {\n\t\t\treadLock.lock();\n\t\t\treturn content.containsKey(key);\n\t\t} finally {\n\t\t\treadLock.unlock();\n\t\t}\n\t}" ]
Test for convergence by seeing if the element with the largest change is smaller than the tolerance. In some test cases it alternated between the + and - values of the eigen vector. When this happens it seems to have "converged" to a non-dominant eigen vector. At least in the case I looked at. I haven't devoted a lot of time into this issue...
[ "private boolean checkConverged(DMatrixRMaj A) {\n double worst = 0;\n double worst2 = 0;\n for( int j = 0; j < A.numRows; j++ ) {\n double val = Math.abs(q2.data[j] - q0.data[j]);\n if( val > worst ) worst = val;\n val = Math.abs(q2.data[j] + q0.data[j]);\n if( val > worst2 ) worst2 = val;\n }\n\n // swap vectors\n DMatrixRMaj temp = q0;\n q0 = q2;\n q2 = temp;\n\n if( worst < tol )\n return true;\n else if( worst2 < tol )\n return true;\n else\n return false;\n }" ]
[ "private <T> CoreRemoteMongoCollection<T> getRemoteCollection(\n final MongoNamespace namespace,\n final Class<T> resultClass\n ) {\n return remoteClient\n .getDatabase(namespace.getDatabaseName())\n .getCollection(namespace.getCollectionName(), resultClass);\n }", "public static base_response unset(nitro_service client, csparameter resource, String[] args) throws Exception{\n\t\tcsparameter unsetresource = new csparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public void setSize(ButtonSize size) {\n if (this.size != null) {\n removeStyleName(this.size.getCssName());\n }\n this.size = size;\n\n if (size != null) {\n addStyleName(size.getCssName());\n }\n }", "public void fireAssignmentReadEvent(ResourceAssignment resourceAssignment)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.assignmentRead(resourceAssignment);\n }\n }\n }", "private GVRCursorController getUniqueControllerId(int deviceId) {\n GVRCursorController controller = controllerIds.get(deviceId);\n if (controller != null) {\n return controller;\n }\n return null;\n }", "private void cleanupDestination(DownloadRequest request, boolean forceClean) {\n if (!request.isResumable() || forceClean) {\n Log.d(\"cleanupDestination() deleting \" + request.getDestinationURI().getPath());\n File destinationFile = new File(request.getDestinationURI().getPath());\n if (destinationFile.exists()) {\n destinationFile.delete();\n }\n }\n }", "protected Patch createProcessedPatch(final Patch original) {\n\n // Process elements\n final List<PatchElement> elements = new ArrayList<PatchElement>();\n // Process layers\n for (final PatchEntry entry : getLayers()) {\n final PatchElement element = createPatchElement(entry, entry.element.getId(), entry.modifications);\n elements.add(element);\n }\n // Process add-ons\n for (final PatchEntry entry : getAddOns()) {\n final PatchElement element = createPatchElement(entry, entry.element.getId(), entry.modifications);\n elements.add(element);\n }\n\n // Swap the patch element modifications, keep the identity ones since we don't need to fix the misc modifications\n return new PatchImpl(original.getPatchId(), original.getDescription(), original.getLink(), original.getIdentity(), elements, identityEntry.modifications);\n }", "public Set<S> getMatchedDeclarationBinder() {\n Set<S> bindedSet = new HashSet<S>();\n for (Map.Entry<ServiceReference<S>, BinderDescriptor> e : declarationBinders.entrySet()) {\n if (e.getValue().match) {\n bindedSet.add(getDeclarationBinder(e.getKey()));\n }\n }\n return bindedSet;\n }", "public static ModelNode determineHostAddress(final ModelControllerClient client) throws IOException, OperationExecutionException {\n final ModelNode op = Operations.createReadAttributeOperation(EMPTY_ADDRESS, \"local-host-name\");\n ModelNode response = client.execute(op);\n if (Operations.isSuccessfulOutcome(response)) {\n return DeploymentOperations.createAddress(\"host\", Operations.readResult(response).asString());\n }\n throw new OperationExecutionException(op, response);\n }" ]
This method returns the value of the product using a Black-Scholes model for the swap rate with the Hunt-Kennedy convexity adjustment. The model is determined by a discount factor curve and a swap rate volatility. @param forwardCurve The forward curve from which the swap rate is calculated. The discount curve, associated with this forward curve is used for discounting this option. @param swaprateVolatility The volatility of the log-swaprate. @return Value of this product
[ "public double getValue(ForwardCurve forwardCurve, double swaprateVolatility) {\n\t\tdouble[] swapTenor = new double[fixingDates.length+1];\n\t\tSystem.arraycopy(fixingDates, 0, swapTenor, 0, fixingDates.length);\n\t\tswapTenor[swapTenor.length-1] = paymentDates[paymentDates.length-1];\n\n\t\tTimeDiscretization fixTenor\t= new TimeDiscretizationFromArray(swapTenor);\n\t\tTimeDiscretization floatTenor\t= new TimeDiscretizationFromArray(swapTenor);\n\t\tdouble forwardSwapRate = Swap.getForwardSwapRate(fixTenor, floatTenor, forwardCurve);\n\t\tdouble swapAnnuity = SwapAnnuity.getSwapAnnuity(fixTenor, forwardCurve);\n\t\tdouble payoffUnit = SwapAnnuity.getSwapAnnuity(new TimeDiscretizationFromArray(swapTenor[0], swapTenor[1]), forwardCurve) / (swapTenor[1] - swapTenor[0]);\n\t\treturn AnalyticFormulas.huntKennedyCMSOptionValue(forwardSwapRate, swaprateVolatility, swapAnnuity, exerciseDate, swapTenor[swapTenor.length-1]-swapTenor[0], payoffUnit, strike) * (swapTenor[1] - swapTenor[0]);\n\t}" ]
[ "public static base_response unset(nitro_service client, nsspparams resource, String[] args) throws Exception{\n\t\tnsspparams unsetresource = new nsspparams();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public static <A extends Annotation> EnhancedAnnotation<A> create(SlimAnnotatedType<A> annotatedType, ClassTransformer classTransformer) {\n\n Class<A> annotationType = annotatedType.getJavaClass();\n\n Map<Class<? extends Annotation>, Annotation> annotationMap = new HashMap<Class<? extends Annotation>, Annotation>();\n annotationMap.putAll(buildAnnotationMap(annotatedType.getAnnotations()));\n annotationMap.putAll(buildAnnotationMap(classTransformer.getTypeStore().get(annotationType)));\n // Annotations and declared annotations are the same for annotation type\n return new EnhancedAnnotationImpl<A>(annotatedType, annotationMap, annotationMap, classTransformer);\n }", "private JsonArray formatBoxMetadataFilterRequest() {\n JsonArray boxMetadataFilterRequestArray = new JsonArray();\n\n JsonObject boxMetadataFilter = new JsonObject()\n .add(\"templateKey\", this.metadataFilter.getTemplateKey())\n .add(\"scope\", this.metadataFilter.getScope())\n .add(\"filters\", this.metadataFilter.getFiltersList());\n boxMetadataFilterRequestArray.add(boxMetadataFilter);\n\n return boxMetadataFilterRequestArray;\n }", "private void processCustomValueLists() throws IOException\n {\n CustomFieldValueReader9 reader = new CustomFieldValueReader9(m_projectDir, m_file.getProjectProperties(), m_projectProps, m_file.getCustomFields());\n reader.process();\n }", "@Pure\n\t@Inline(value = \"$3.union($1, $4.singletonMap($2.getKey(), $2.getValue()))\",\n\t\t\timported = { MapExtensions.class, Collections.class })\n\tpublic static <K, V> Map<K, V> operator_plus(Map<K, V> left, final Pair<? extends K, ? extends V> right) {\n\t\treturn union(left, Collections.singletonMap(right.getKey(), right.getValue()));\n\t}", "public final void setColorPreferred(boolean preferColor) {\n if (this.preferColor.compareAndSet(!preferColor, preferColor) && isRunning()) {\n stop();\n try {\n start();\n } catch (Exception e) {\n logger.error(\"Unexplained exception restarting; we had been running already!\", e);\n }\n }\n }", "@Override\n\tpublic Iterator<? extends IPAddressSeqRange> prefixIterator(int prefixLength) {\n\t\tif(!isMultiple()) {\n\t\t\treturn new Iterator<IPAddressSeqRange>() {\n\t\t\t\tIPAddressSeqRange orig = IPAddressSeqRange.this;\n\n\t\t\t\t@Override\n\t\t\t\tpublic boolean hasNext() {\n\t\t\t\t\treturn orig != null;\n\t\t\t\t}\n\n\t\t\t @Override\n\t\t\t\tpublic IPAddressSeqRange next() {\n\t\t\t \tif(orig == null) {\n\t\t\t \t\tthrow new NoSuchElementException();\n\t\t\t \t}\n\t\t\t \tIPAddressSeqRange result = orig;\n\t\t\t \torig = null;\n\t\t\t \treturn result;\n\t\t\t }\n\t\t\t\n\t\t\t @Override\n\t\t\t\tpublic void remove() {\n\t\t\t \tthrow new UnsupportedOperationException();\n\t\t\t }\n\t\t\t};\n\t\t}\n\t\treturn new Iterator<IPAddressSeqRange>() {\n\t\t\tIterator<? extends IPAddress> prefixBlockIterator = prefixBlockIterator(prefixLength);\n\t\t\tprivate boolean first = true;\n\n\t\t\t@Override\n\t\t\tpublic boolean hasNext() {\n\t\t\t\treturn prefixBlockIterator.hasNext();\n\t\t\t}\n\n\t\t @Override\n\t\t\tpublic IPAddressSeqRange next() {\n\t\t \tIPAddress next = prefixBlockIterator.next();\n\t\t \tif(first) {\n\t\t \t\tfirst = false;\n\t\t \t\t// next is a prefix block\n\t\t \t\tIPAddress lower = getLower();\n\t\t \t\tif(hasNext()) {\n\t\t\t \t\tif(!lower.includesZeroHost(prefixLength)) {\n\t\t\t \t\t\treturn create(lower, next.getUpper());\n\t\t\t \t\t}\n\t\t \t\t} else {\n\t\t \t\t\tIPAddress upper = getUpper();\n\t\t \t\t\tif(!lower.includesZeroHost(prefixLength) || !upper.includesMaxHost(prefixLength)) {\n\t\t \t\t\t\treturn create(lower, upper);\n\t\t \t\t\t}\n\t\t \t\t}\n\t\t \t} else if(!hasNext()) {\n\t\t \t\tIPAddress upper = getUpper();\n\t\t \t\tif(!upper.includesMaxHost(prefixLength)) {\n\t\t \t\t\treturn create(next.getLower(), upper);\n\t\t \t\t}\n\t\t \t}\n\t\t \treturn next.toSequentialRange();\n\t\t }\n\t\t\n\t\t @Override\n\t\t\tpublic void remove() {\n\t\t \tthrow new UnsupportedOperationException();\n\t\t }\n\t\t};\n\t}", "private static Originator mapOriginatorType(OriginatorType originatorType) {\n Originator originator = new Originator();\n if (originatorType != null) {\n originator.setCustomId(originatorType.getCustomId());\n originator.setHostname(originatorType.getHostname());\n originator.setIp(originatorType.getIp());\n originator.setProcessId(originatorType.getProcessId());\n originator.setPrincipal(originatorType.getPrincipal());\n }\n return originator;\n }", "protected static String getTimePrecisionString(byte precision) {\n\t\tswitch (precision) {\n\t\tcase TimeValue.PREC_SECOND:\n\t\t\treturn \"sec\";\n\t\tcase TimeValue.PREC_MINUTE:\n\t\t\treturn \"min\";\n\t\tcase TimeValue.PREC_HOUR:\n\t\t\treturn \"hour\";\n\t\tcase TimeValue.PREC_DAY:\n\t\t\treturn \"day\";\n\t\tcase TimeValue.PREC_MONTH:\n\t\t\treturn \"month\";\n\t\tcase TimeValue.PREC_YEAR:\n\t\t\treturn \"year\";\n\t\tcase TimeValue.PREC_DECADE:\n\t\t\treturn \"decade\";\n\t\tcase TimeValue.PREC_100Y:\n\t\t\treturn \"100 years\";\n\t\tcase TimeValue.PREC_1KY:\n\t\t\treturn \"1000 years\";\n\t\tcase TimeValue.PREC_10KY:\n\t\t\treturn \"10K years\";\n\t\tcase TimeValue.PREC_100KY:\n\t\t\treturn \"100K years\";\n\t\tcase TimeValue.PREC_1MY:\n\t\t\treturn \"1 million years\";\n\t\tcase TimeValue.PREC_10MY:\n\t\t\treturn \"10 million years\";\n\t\tcase TimeValue.PREC_100MY:\n\t\t\treturn \"100 million years\";\n\t\tcase TimeValue.PREC_1GY:\n\t\t\treturn \"1000 million years\";\n\t\tdefault:\n\t\t\treturn \"Unsupported precision \" + precision;\n\t\t}\n\t}" ]
Hide the following channels. @param channels The names of the channels to hide. @return this
[ "public RedwoodConfiguration hideChannels(final Object[] channels){\r\n tasks.add(new Runnable() { public void run() { Redwood.hideChannels(channels); } });\r\n return this;\r\n }" ]
[ "private void processEncodedPayload() throws IOException {\n if (!readPayload) {\n payloadSpanCollector.reset();\n collect(payloadSpanCollector);\n Collection<byte[]> originalPayloadCollection = payloadSpanCollector\n .getPayloads();\n if (originalPayloadCollection.iterator().hasNext()) {\n byte[] payload = originalPayloadCollection.iterator().next();\n if (payload == null) {\n throw new IOException(\"no payload\");\n }\n MtasPayloadDecoder payloadDecoder = new MtasPayloadDecoder();\n payloadDecoder.init(startPosition(), payload);\n mtasPosition = payloadDecoder.getMtasPosition();\n } else {\n throw new IOException(\"no payload\");\n }\n }\n }", "public static String fromClassPath() {\n Set<String> versions = new HashSet<>();\n try {\n ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n Enumeration<URL> manifests = classLoader.getResources(\"META-INF/MANIFEST.MF\");\n\n while (manifests.hasMoreElements()) {\n URL manifestURL = manifests.nextElement();\n try (InputStream is = manifestURL.openStream()) {\n Manifest manifest = new Manifest();\n manifest.read(is);\n\n Attributes buildInfo = manifest.getAttributes(\"Build-Info\");\n if (buildInfo != null) {\n if (buildInfo.getValue(\"Selenium-Version\") != null) {\n versions.add(buildInfo.getValue(\"Selenium-Version\"));\n } else {\n // might be in build-info part\n if (manifest.getEntries() != null) {\n if (manifest.getEntries().containsKey(\"Build-Info\")) {\n final Attributes attributes = manifest.getEntries().get(\"Build-Info\");\n\n if (attributes.getValue(\"Selenium-Version\") != null) {\n versions.add(attributes.getValue(\"Selenium-Version\"));\n }\n }\n }\n }\n }\n }\n }\n } catch (Exception e) {\n logger.log(Level.WARNING,\n \"Exception {0} occurred while resolving selenium version and latest image is going to be used.\",\n e.getMessage());\n return SELENIUM_VERSION;\n }\n\n if (versions.isEmpty()) {\n logger.log(Level.INFO, \"No version of Selenium found in classpath. Using latest image.\");\n return SELENIUM_VERSION;\n }\n\n String foundVersion = versions.iterator().next();\n if (versions.size() > 1) {\n logger.log(Level.WARNING, \"Multiple versions of Selenium found in classpath. Using the first one found {0}.\",\n foundVersion);\n }\n\n return foundVersion;\n }", "public static auditsyslogpolicy_lbvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditsyslogpolicy_lbvserver_binding obj = new auditsyslogpolicy_lbvserver_binding();\n\t\tobj.set_name(name);\n\t\tauditsyslogpolicy_lbvserver_binding response[] = (auditsyslogpolicy_lbvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public int count(String key) {\n ConcurrentMap<WebSocketConnection, WebSocketConnection> bag = registry.get(key);\n return null == bag ? 0 : bag.size();\n }", "public void linkMtoN(Object obj, CollectionDescriptor cod, boolean insert)\n {\n Object referencedObjects = cod.getPersistentField().get(obj);\n storeAndLinkMtoN(true, obj, cod, referencedObjects, insert);\n }", "private static JsonArray getJsonArray(List<String> keys) {\n JsonArray array = new JsonArray();\n for (String key : keys) {\n array.add(key);\n }\n\n return array;\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}", "public static String decodeUrlIso(String stringToDecode) {\n try {\n return URLDecoder.decode(stringToDecode, \"ISO-8859-1\");\n } catch (UnsupportedEncodingException e1) {\n throw new RuntimeException(e1);\n }\n }", "protected void destroy() {\n ContextLogger.LOG.contextCleared(this);\n final BeanStore beanStore = getBeanStore();\n if (beanStore == null) {\n throw ContextLogger.LOG.noBeanStoreAvailable(this);\n }\n for (BeanIdentifier id : beanStore) {\n destroyContextualInstance(beanStore.get(id));\n }\n beanStore.clear();\n }" ]
Process events in the order as they were received. <p/> The overall time to process the events must be within the bounds of the timeout or an {@link InsufficientOperationalNodesException} will be thrown.
[ "public void execute() {\n try {\n while(true) {\n Event event = null;\n\n try {\n event = eventQueue.poll(timeout, unit);\n } catch(InterruptedException e) {\n throw new InsufficientOperationalNodesException(operation.getSimpleName()\n + \" operation interrupted!\", e);\n }\n\n if(event == null)\n throw new VoldemortException(operation.getSimpleName()\n + \" returned a null event\");\n\n if(event.equals(Event.ERROR)) {\n if(logger.isTraceEnabled())\n logger.trace(operation.getSimpleName()\n + \" request, events complete due to error\");\n\n break;\n } else if(event.equals(Event.COMPLETED)) {\n if(logger.isTraceEnabled())\n logger.trace(operation.getSimpleName() + \" request, events complete\");\n\n break;\n }\n\n Action action = eventActions.get(event);\n\n if(action == null)\n throw new IllegalStateException(\"action was null for event \" + event);\n\n if(logger.isTraceEnabled())\n logger.trace(operation.getSimpleName() + \" request, action \"\n + action.getClass().getSimpleName() + \" to handle \" + event\n + \" event\");\n\n action.execute(this);\n }\n } finally {\n finished = true;\n }\n }" ]
[ "public List<Release> listReleases(String appName) {\n return connection.execute(new ReleaseList(appName), apiKey);\n }", "private void init() {\n validatePreSignedUrls();\n\n try {\n conn = new AWSAuthConnection(access_key, secret_access_key);\n // Determine the bucket name if prefix is set or if pre-signed URLs are being used\n if (prefix != null && prefix.length() > 0) {\n ListAllMyBucketsResponse bucket_list = conn.listAllMyBuckets(null);\n List buckets = bucket_list.entries;\n if (buckets != null) {\n boolean found = false;\n for (Object tmp : buckets) {\n if (tmp instanceof Bucket) {\n Bucket bucket = (Bucket) tmp;\n if (bucket.name.startsWith(prefix)) {\n location = bucket.name;\n found = true;\n }\n }\n }\n if (!found) {\n location = prefix + \"-\" + java.util.UUID.randomUUID().toString();\n }\n }\n }\n if (usingPreSignedUrls()) {\n PreSignedUrlParser parsedPut = new PreSignedUrlParser(pre_signed_put_url);\n location = parsedPut.getBucket();\n }\n if (!conn.checkBucketExists(location)) {\n conn.createBucket(location, AWSAuthConnection.LOCATION_DEFAULT, null).connection.getResponseMessage();\n }\n } catch (Exception e) {\n throw HostControllerLogger.ROOT_LOGGER.cannotAccessS3Bucket(location, e.getLocalizedMessage());\n }\n }", "protected RendererViewHolder buildRendererViewHolder() {\n validateAttributesToCreateANewRendererViewHolder();\n\n Renderer renderer = getPrototypeByIndex(viewType).copy();\n renderer.onCreate(null, layoutInflater, parent);\n return new RendererViewHolder(renderer);\n }", "public void setValue(int numStrings, String[] newValues) {\n value.clear();\n if (numStrings == newValues.length) {\n for (int i = 0; i < newValues.length; i++) {\n value.add(newValues[i]);\n }\n }\n else {\n Log.e(TAG, \"X3D MFString setValue() numStrings not equal total newValues\");\n }\n }", "public final void setWeekDay(WeekDay weekDay) {\n\n SortedSet<WeekDay> wds = new TreeSet<>();\n if (null != weekDay) {\n wds.add(weekDay);\n }\n setWeekDays(wds);\n\n }", "public ItemRequest<CustomField> delete(String customField) {\n \n String path = String.format(\"/custom_fields/%s\", customField);\n return new ItemRequest<CustomField>(this, CustomField.class, path, \"DELETE\");\n }", "public List<Object> getAll(int dataSet) throws SerializationException {\r\n\t\tList<Object> result = new ArrayList<Object>();\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.add(getData(ds));\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn result;\r\n\t}", "public static <T> Class<T> loadClass(String className, ResourceLoader resourceLoader) {\n try {\n return cast(resourceLoader.classForName(className));\n } catch (ResourceLoadingException e) {\n return null;\n } catch (SecurityException e) {\n return null;\n }\n }", "private Properties parseFile(File file) throws InvalidDeclarationFileException {\n Properties properties = new Properties();\n InputStream is = null;\n try {\n is = new FileInputStream(file);\n properties.load(is);\n } catch (Exception e) {\n throw new InvalidDeclarationFileException(String.format(\"Error reading declaration file %s\", file.getAbsoluteFile()), e);\n } finally {\n if (is != null) {\n try {\n is.close();\n } catch (IOException e) {\n LOG.error(\"IOException thrown while trying to close the declaration file.\", e);\n }\n }\n }\n\n if (!properties.containsKey(Constants.ID)) {\n throw new InvalidDeclarationFileException(String.format(\"File %s is not a correct declaration, needs to contains an id property\", file.getAbsoluteFile()));\n }\n return properties;\n }" ]
Verifies that the connection is still alive. Returns true if it is, false if it is not. If the connection is broken we try closing everything, too, so that the caller need only open a new connection.
[ "public static boolean validate(Statement stmt) {\n try {\n Connection conn = stmt.getConnection();\n if (conn == null)\n return false;\n\n if (!conn.isClosed() && conn.isValid(10))\n return true;\n\n stmt.close();\n conn.close();\n } catch (SQLException e) {\n // this may well fail. that doesn't matter. we're just making an\n // attempt to clean up, and if we can't, that's just too bad.\n }\n return false;\n }" ]
[ "public static float[] toFloat(int[] array) {\n float[] n = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n n[i] = (float) array[i];\n }\n return n;\n }", "public static vpnglobal_vpnnexthopserver_binding[] get(nitro_service service) throws Exception{\n\t\tvpnglobal_vpnnexthopserver_binding obj = new vpnglobal_vpnnexthopserver_binding();\n\t\tvpnglobal_vpnnexthopserver_binding response[] = (vpnglobal_vpnnexthopserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void setSeriesEndDate(Date date) {\r\n\r\n if (!Objects.equals(m_model.getSeriesEndDate(), date)) {\r\n m_model.setSeriesEndDate(date);\r\n valueChanged();\r\n }\r\n\r\n }", "public static final BigDecimal printCurrency(Number value)\n {\n return (value == null || value.doubleValue() == 0 ? null : new BigDecimal(value.doubleValue() * 100));\n }", "public int getMinutesPerDay()\n {\n return m_minutesPerDay == null ? NumberHelper.getInt(getParentFile().getProjectProperties().getMinutesPerDay()) : m_minutesPerDay.intValue();\n }", "public static lbsipparameters get(nitro_service service) throws Exception{\n\t\tlbsipparameters obj = new lbsipparameters();\n\t\tlbsipparameters[] response = (lbsipparameters[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public void sendSyncModeCommand(int deviceNumber, boolean synced) throws IOException {\n final DeviceUpdate update = getLatestStatusFor(deviceNumber);\n if (update == null) {\n throw new IllegalArgumentException(\"Device \" + deviceNumber + \" not found on network.\");\n }\n sendSyncModeCommand(update, synced);\n }", "protected void setWhenNoDataBand() {\n log.debug(\"setting up WHEN NO DATA band\");\n String whenNoDataText = getReport().getWhenNoDataText();\n Style style = getReport().getWhenNoDataStyle();\n if (whenNoDataText == null || \"\".equals(whenNoDataText))\n return;\n JRDesignBand band = new JRDesignBand();\n getDesign().setNoData(band);\n\n JRDesignTextField text = new JRDesignTextField();\n JRDesignExpression expression = ExpressionUtils.createStringExpression(\"\\\"\" + whenNoDataText + \"\\\"\");\n text.setExpression(expression);\n\n if (style == null) {\n style = getReport().getOptions().getDefaultDetailStyle();\n }\n\n if (getReport().isWhenNoDataShowTitle()) {\n LayoutUtils.copyBandElements(band, getDesign().getTitle());\n LayoutUtils.copyBandElements(band, getDesign().getPageHeader());\n }\n if (getReport().isWhenNoDataShowColumnHeader())\n LayoutUtils.copyBandElements(band, getDesign().getColumnHeader());\n\n int offset = LayoutUtils.findVerticalOffset(band);\n text.setY(offset);\n applyStyleToElement(style, text);\n text.setWidth(getReport().getOptions().getPrintableWidth());\n text.setHeight(50);\n band.addElement(text);\n log.debug(\"OK setting up WHEN NO DATA band\");\n\n }", "@Override\n public Object[] getAgentPlans(String agent_name, Connector connector) {\n // Not supported in JADE\n connector.getLogger().warning(\"Non suported method for Jade Platform. There is no plans in Jade platform.\");\n throw new java.lang.UnsupportedOperationException(\"Non suported method for Jade Platform. There is no extra properties.\");\n }" ]
Use this API to delete route6.
[ "public static base_response delete(nitro_service client, route6 resource) throws Exception {\n\t\troute6 deleteresource = new route6();\n\t\tdeleteresource.network = resource.network;\n\t\tdeleteresource.gateway = resource.gateway;\n\t\tdeleteresource.vlan = resource.vlan;\n\t\tdeleteresource.td = resource.td;\n\t\treturn deleteresource.delete_resource(client);\n\t}" ]
[ "protected boolean isItemAccepted(byte[] key) {\n boolean entryAccepted = false;\n if (!fetchOrphaned) {\n if (isKeyNeeded(key)) {\n entryAccepted = true;\n }\n } else {\n if (!StoreRoutingPlan.checkKeyBelongsToNode(key, nodeId, initialCluster, storeDef)) {\n entryAccepted = true;\n }\n }\n return entryAccepted;\n }", "public static String changeFileNameSuffixTo(String filename, String suffix) {\n\n int dotPos = filename.lastIndexOf('.');\n if (dotPos != -1) {\n return filename.substring(0, dotPos + 1) + suffix;\n } else {\n // the string has no suffix\n return filename;\n }\n }", "@SafeVarargs\n private final <T> Set<T> join(Set<T>... sets)\n {\n Set<T> result = new HashSet<>();\n if (sets == null)\n return result;\n\n for (Set<T> set : sets)\n {\n if (set != null)\n result.addAll(set);\n }\n return result;\n }", "protected Object[] getFieldObjects(Object data) throws SQLException {\n\t\tObject[] objects = new Object[argFieldTypes.length];\n\t\tfor (int i = 0; i < argFieldTypes.length; i++) {\n\t\t\tFieldType fieldType = argFieldTypes[i];\n\t\t\tif (fieldType.isAllowGeneratedIdInsert()) {\n\t\t\t\tobjects[i] = fieldType.getFieldValueIfNotDefault(data);\n\t\t\t} else {\n\t\t\t\tobjects[i] = fieldType.extractJavaFieldToSqlArgValue(data);\n\t\t\t}\n\t\t\tif (objects[i] == null) {\n\t\t\t\t// NOTE: the default value could be null as well\n\t\t\t\tobjects[i] = fieldType.getDefaultValue();\n\t\t\t}\n\t\t}\n\t\treturn objects;\n\t}", "private int calcItemWidth(RecyclerView rvCategories) {\n if (itemWidth == null || itemWidth == 0) {\n for (int i = 0; i < rvCategories.getChildCount(); i++) {\n itemWidth = rvCategories.getChildAt(i).getWidth();\n if (itemWidth != 0) {\n break;\n }\n }\n }\n // in case of call before view was created\n if (itemWidth == null) {\n itemWidth = 0;\n }\n return itemWidth;\n }", "private List<Row> buildRowHierarchy(List<Row> bars, List<Row> expandedTasks, List<Row> tasks, List<Row> milestones)\n {\n //\n // Create a list of leaf nodes by merging the task and milestone lists\n //\n List<Row> leaves = new ArrayList<Row>();\n leaves.addAll(tasks);\n leaves.addAll(milestones);\n\n //\n // Sort the bars and the leaves\n //\n Collections.sort(bars, BAR_COMPARATOR);\n Collections.sort(leaves, LEAF_COMPARATOR);\n\n //\n // Map bar IDs to bars\n //\n Map<Integer, Row> barIdToBarMap = new HashMap<Integer, Row>();\n for (Row bar : bars)\n {\n barIdToBarMap.put(bar.getInteger(\"BARID\"), bar);\n }\n\n //\n // Merge expanded task attributes with parent bars\n // and create an expanded task ID to bar map.\n //\n Map<Integer, Row> expandedTaskIdToBarMap = new HashMap<Integer, Row>();\n for (Row expandedTask : expandedTasks)\n {\n Row bar = barIdToBarMap.get(expandedTask.getInteger(\"BAR\"));\n bar.merge(expandedTask, \"_\");\n Integer expandedTaskID = bar.getInteger(\"_EXPANDED_TASKID\");\n expandedTaskIdToBarMap.put(expandedTaskID, bar);\n }\n\n //\n // Build the hierarchy\n //\n List<Row> parentBars = new ArrayList<Row>();\n for (Row bar : bars)\n {\n Integer expandedTaskID = bar.getInteger(\"EXPANDED_TASK\");\n Row parentBar = expandedTaskIdToBarMap.get(expandedTaskID);\n if (parentBar == null)\n {\n parentBars.add(bar);\n }\n else\n {\n parentBar.addChild(bar);\n }\n }\n\n //\n // Attach the leaves\n //\n for (Row leaf : leaves)\n {\n Integer barID = leaf.getInteger(\"BAR\");\n Row bar = barIdToBarMap.get(barID);\n bar.addChild(leaf);\n }\n\n //\n // Prune any \"displaced items\" from the top level.\n // We're using a heuristic here as this is the only thing I\n // can see which differs between bars that we want to include\n // and bars that we want to exclude.\n //\n Iterator<Row> iter = parentBars.iterator();\n while (iter.hasNext())\n {\n Row bar = iter.next();\n String barName = bar.getString(\"NAMH\");\n if (barName == null || barName.isEmpty() || barName.equals(\"Displaced Items\"))\n {\n iter.remove();\n }\n }\n\n //\n // If we only have a single top level node (effectively a summary task) prune that too.\n //\n if (parentBars.size() == 1)\n {\n parentBars = parentBars.get(0).getChildRows();\n }\n\n return parentBars;\n }", "protected LayoutManager getLayOutManagerObj(ActionInvocation _invocation) {\n\t\tif (layoutManager == null || \"\".equals(layoutManager)){\n\t\t\tLOG.warn(\"No valid LayoutManager, using ClassicLayoutManager\");\n\t\t\treturn new ClassicLayoutManager();\n\t\t}\n\n\t\tObject los = conditionalParse(layoutManager, _invocation);\n\n\t\tif (los instanceof LayoutManager){\n\t\t\treturn (LayoutManager) los;\n\t\t}\n\n\t\tLayoutManager lo = null;\n\t\tif (los instanceof String){\n\t\t\tif (LAYOUT_CLASSIC.equalsIgnoreCase((String) los))\n\t\t\t\tlo = new ClassicLayoutManager();\n\t\t\telse if (LAYOUT_LIST.equalsIgnoreCase((String) los))\n\t\t\t\tlo = new ListLayoutManager();\n\t\t\telse {\n\t\t\t\ttry {\n\t\t\t\t\tlo = (LayoutManager) Class.forName((String) los).newInstance();\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tLOG.warn(\"No valid LayoutManager: \" + e.getMessage(),e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn lo;\n\t}", "@ArgumentsChecked\n\t@Throws(IllegalNullArgumentException.class)\n\tpublic static int checkLong(@Nonnull final Number number) {\n\t\tCheck.notNull(number, \"number\");\n\t\tif (!isInLongRange(number)) {\n\t\t\tthrow new IllegalNumberRangeException(number.toString(), LONG_MIN, LONG_MAX);\n\t\t}\n\n\t\treturn number.intValue();\n\t}", "private int bindStatementValue(PreparedStatement stmt, int index, Object attributeOrQuery, Object value, ClassDescriptor cld)\r\n throws SQLException\r\n {\r\n FieldDescriptor fld = null;\r\n // if value is a subQuery bind it\r\n if (value instanceof Query)\r\n {\r\n Query subQuery = (Query) value;\r\n return bindStatement(stmt, subQuery, cld.getRepository().getDescriptorFor(subQuery.getSearchClass()), index);\r\n }\r\n\r\n // if attribute is a subQuery bind it\r\n if (attributeOrQuery instanceof Query)\r\n {\r\n Query subQuery = (Query) attributeOrQuery;\r\n bindStatement(stmt, subQuery, cld.getRepository().getDescriptorFor(subQuery.getSearchClass()), index);\r\n }\r\n else\r\n {\r\n fld = cld.getFieldDescriptorForPath((String) attributeOrQuery);\r\n }\r\n\r\n if (fld != null)\r\n {\r\n // BRJ: use field conversions and platform\r\n if (value != null)\r\n {\r\n m_platform.setObjectForStatement(stmt, index, fld.getFieldConversion().javaToSql(value), fld.getJdbcType().getType());\r\n }\r\n else\r\n {\r\n m_platform.setNullForStatement(stmt, index, fld.getJdbcType().getType());\r\n }\r\n }\r\n else\r\n {\r\n if (value != null)\r\n {\r\n stmt.setObject(index, value);\r\n }\r\n else\r\n {\r\n stmt.setNull(index, Types.NULL);\r\n }\r\n }\r\n\r\n return ++index; // increment before return\r\n }" ]
Returns the position for a given number of occurrences or NOT_FOUND if this value is not found. @param nOccurrence number of occurrences @return the position for a given number of occurrences or NOT_FOUND if this value is not found
[ "public long findPosition(long nOccurrence) {\n\t\tupdateCount();\n\t\tif (nOccurrence <= 0) {\n\t\t\treturn RankedBitVector.NOT_FOUND;\n\t\t}\n\t\tint findPos = (int) (nOccurrence / this.blockSize);\n\t\tif (findPos < this.positionArray.length) {\n\t\t\tlong pos0 = this.positionArray[findPos];\n\t\t\tlong leftOccurrences = nOccurrence - (findPos * this.blockSize);\n\t\t\tif (leftOccurrences == 0) {\n\t\t\t\treturn pos0;\n\t\t\t}\n\t\t\tfor (long index = pos0 + 1; index < this.bitVector.size(); index++) {\n\t\t\t\tif (this.bitVector.getBit(index) == this.bit) {\n\t\t\t\t\tleftOccurrences--;\n\t\t\t\t}\n\t\t\t\tif (leftOccurrences == 0) {\n\t\t\t\t\treturn index;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn RankedBitVector.NOT_FOUND;\n\t}" ]
[ "public static void validateClusterZonesSame(final Cluster lhs, final Cluster rhs) {\n Set<Zone> lhsSet = new HashSet<Zone>(lhs.getZones());\n Set<Zone> rhsSet = new HashSet<Zone>(rhs.getZones());\n if(!lhsSet.equals(rhsSet))\n throw new VoldemortException(\"Zones are not the same [ lhs cluster zones (\"\n + lhs.getZones() + \") not equal to rhs cluster zones (\"\n + rhs.getZones() + \") ]\");\n }", "public void signOff(WebSocketConnection connection) {\n for (ConcurrentMap<WebSocketConnection, WebSocketConnection> connections : registry.values()) {\n connections.remove(connection);\n }\n }", "public static DMatrixRMaj diagonal(int numRows , int numCols , double min , double max , Random rand ) {\n if( max < min )\n throw new IllegalArgumentException(\"The max must be >= the min\");\n\n DMatrixRMaj ret = new DMatrixRMaj(numRows,numCols);\n\n int N = Math.min(numRows,numCols);\n\n double r = max-min;\n\n for( int i = 0; i < N; i++ ) {\n ret.set(i,i, rand.nextDouble()*r+min);\n }\n\n return ret;\n }", "public static ProctorLoadResult verifyWithoutSpecification(@Nonnull final TestMatrixArtifact testMatrix,\n final String matrixSource) {\n final ProctorLoadResult.Builder resultBuilder = ProctorLoadResult.newBuilder();\n\n for (final Entry<String, ConsumableTestDefinition> entry : testMatrix.getTests().entrySet()) {\n final String testName = entry.getKey();\n final ConsumableTestDefinition testDefinition = entry.getValue();\n\n try {\n verifyInternallyConsistentDefinition(testName, matrixSource, testDefinition);\n } catch (IncompatibleTestMatrixException e) {\n LOGGER.info(String.format(\"Unable to load test matrix for %s\", testName), e);\n resultBuilder.recordError(testName, e);\n }\n }\n return resultBuilder.build();\n }", "public static base_responses reset(nitro_service client, appfwlearningdata resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tappfwlearningdata resetresources[] = new appfwlearningdata[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tresetresources[i] = new appfwlearningdata();\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, resetresources,\"reset\");\n\t\t}\n\t\treturn result;\n\t}", "public static MediaType nonBinary( MediaType.Type type, String subType, Charset charSet ) {\n ApiUtil.notNull( charSet, \"charset must not be null\" );\n return new MediaType( type, subType, charSet );\n }", "@Override public void setModel(TableModel model)\n {\n super.setModel(model);\n int columns = model.getColumnCount();\n TableColumnModel tableColumnModel = getColumnModel();\n for (int index = 0; index < columns; index++)\n {\n tableColumnModel.getColumn(index).setPreferredWidth(m_columnWidth);\n }\n }", "public void delete(boolean notifyUser, boolean force) {\n String queryString = new QueryStringBuilder()\n .appendParam(\"notify\", String.valueOf(notifyUser))\n .appendParam(\"force\", String.valueOf(force))\n .toString();\n\n URL url = USER_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"DELETE\");\n BoxAPIResponse response = request.send();\n response.disconnect();\n }", "public void setSourceUrl(String newUrl, int id) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_SERVERS +\n \" SET \" + Constants.SERVER_REDIRECT_SRC_URL + \" = ?\" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, newUrl);\n statement.setInt(2, id);\n statement.executeUpdate();\n statement.close();\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 }" ]
Creates the button for converting an XML bundle in a property bundle. @return the created button.
[ "private Component createConvertToPropertyBundleButton() {\n\n Button addDescriptorButton = CmsToolBar.createButton(\n FontOpenCms.SETTINGS,\n m_messages.key(Messages.GUI_CONVERT_TO_PROPERTY_BUNDLE_0));\n\n addDescriptorButton.setDisableOnClick(true);\n\n addDescriptorButton.addClickListener(new ClickListener() {\n\n private static final long serialVersionUID = 1L;\n\n public void buttonClick(ClickEvent event) {\n\n try {\n m_model.saveAsPropertyBundle();\n Notification.show(\"Conversion successful.\");\n } catch (CmsException | IOException e) {\n CmsVaadinUtils.showAlert(\"Conversion failed\", e.getLocalizedMessage(), null);\n }\n }\n });\n addDescriptorButton.setDisableOnClick(true);\n return addDescriptorButton;\n }" ]
[ "public static base_response add(nitro_service client, vpnclientlessaccesspolicy resource) throws Exception {\n\t\tvpnclientlessaccesspolicy addresource = new vpnclientlessaccesspolicy();\n\t\taddresource.name = resource.name;\n\t\taddresource.rule = resource.rule;\n\t\taddresource.profilename = resource.profilename;\n\t\treturn addresource.add_resource(client);\n\t}", "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 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 }", "public Response getTemplate(String id) throws RequestException, LocalOperationException {\n Request request = new Request(this);\n return new Response(request.get(\"/templates/\" + id));\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 }", "private static void firstDotConstellation(int[] dollarPositions, int[] dotPositions, int nestingLevel) {\n int i = 0;\n int unassigned = dotPositions.length - nestingLevel;\n\n for (; i < unassigned; ++i) {\n dotPositions[i] = -1;\n }\n\n for (; i < dotPositions.length; ++i) {\n dotPositions[i] = dollarPositions[i];\n }\n }", "public float get(Layout.Axis axis) {\n switch (axis) {\n case X:\n return x;\n case Y:\n return y;\n case Z:\n return z;\n default:\n throw new RuntimeAssertion(\"Bad axis specified: %s\", axis);\n }\n }", "public ServerSetup[] build(Properties properties) {\n List<ServerSetup> serverSetups = new ArrayList<>();\n\n String hostname = properties.getProperty(\"greenmail.hostname\", ServerSetup.getLocalHostAddress());\n long serverStartupTimeout =\n Long.parseLong(properties.getProperty(\"greenmail.startup.timeout\", \"-1\"));\n\n // Default setups\n addDefaultSetups(hostname, properties, serverSetups);\n\n // Default setups for test\n addTestSetups(hostname, properties, serverSetups);\n\n // Default setups\n for (String protocol : ServerSetup.PROTOCOLS) {\n addSetup(hostname, protocol, properties, serverSetups);\n }\n\n for (ServerSetup setup : serverSetups) {\n if (properties.containsKey(GREENMAIL_VERBOSE)) {\n setup.setVerbose(true);\n }\n if (serverStartupTimeout >= 0L) {\n setup.setServerStartupTimeout(serverStartupTimeout);\n }\n }\n\n return serverSetups.toArray(new ServerSetup[serverSetups.size()]);\n }", "private void setExceptions(ProjectCalendar mpxjCalendar, Calendars gpCalendar)\n {\n List<net.sf.mpxj.ganttproject.schema.Date> dates = gpCalendar.getDate();\n for (net.sf.mpxj.ganttproject.schema.Date date : dates)\n {\n addException(mpxjCalendar, date);\n }\n }" ]
Add the set of partitions to the node provided @param node The node to which we'll add the partitions @param donatedPartitions The list of partitions to add @return The new node with the new partitions
[ "public static Node addPartitionsToNode(final Node node, final Set<Integer> donatedPartitions) {\n List<Integer> deepCopy = new ArrayList<Integer>(node.getPartitionIds());\n deepCopy.addAll(donatedPartitions);\n Collections.sort(deepCopy);\n return updateNode(node, deepCopy);\n }" ]
[ "public void waitForAsyncFlush() {\n long numAdded = asyncBatchesAdded.get();\n\n synchronized (this) {\n while (numAdded > asyncBatchesProcessed) {\n try {\n wait();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n }\n }\n }", "private void ensureColumn(FieldDescriptorDef fieldDef, String checkLevel)\r\n {\r\n if (!fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_COLUMN))\r\n {\r\n String javaname = fieldDef.getName();\r\n\r\n if (fieldDef.isNested())\r\n { \r\n int pos = javaname.indexOf(\"::\");\r\n\r\n // we convert nested names ('_' for '::')\r\n if (pos > 0)\r\n {\r\n StringBuffer newJavaname = new StringBuffer(javaname.substring(0, pos));\r\n int lastPos = pos + 2;\r\n\r\n do\r\n {\r\n pos = javaname.indexOf(\"::\", lastPos);\r\n newJavaname.append(\"_\");\r\n if (pos > 0)\r\n { \r\n newJavaname.append(javaname.substring(lastPos, pos));\r\n lastPos = pos + 2;\r\n }\r\n else\r\n {\r\n newJavaname.append(javaname.substring(lastPos));\r\n }\r\n }\r\n while (pos > 0);\r\n javaname = newJavaname.toString();\r\n }\r\n }\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_COLUMN, javaname);\r\n }\r\n }", "public boolean existsElement(String predicate) throws org.odmg.QueryInvalidException\r\n {\r\n DList results = (DList) this.query(predicate);\r\n if (results == null || results.size() == 0)\r\n return false;\r\n else\r\n return true;\r\n }", "private TypeArgSignature getTypeArgSignature(Type type) {\r\n\t\tif (type instanceof WildcardType) {\r\n\t\t\tWildcardType wildcardType = (WildcardType) type;\r\n\t\t\tType lowerBound = wildcardType.getLowerBounds().length == 0 ? null\r\n\t\t\t\t\t: wildcardType.getLowerBounds()[0];\r\n\t\t\tType upperBound = wildcardType.getUpperBounds().length == 0 ? null\r\n\t\t\t\t\t: wildcardType.getUpperBounds()[0];\r\n\r\n\t\t\tif (lowerBound == null && Object.class.equals(upperBound)) {\r\n\t\t\t\treturn new TypeArgSignature(\r\n\t\t\t\t\t\tTypeArgSignature.UNBOUNDED_WILDCARD,\r\n\t\t\t\t\t\t(FieldTypeSignature) getFullTypeSignature(upperBound));\r\n\t\t\t} else if (lowerBound == null && upperBound != null) {\r\n\t\t\t\treturn new TypeArgSignature(\r\n\t\t\t\t\t\tTypeArgSignature.UPPERBOUND_WILDCARD,\r\n\t\t\t\t\t\t(FieldTypeSignature) getFullTypeSignature(upperBound));\r\n\t\t\t} else if (lowerBound != null) {\r\n\t\t\t\treturn new TypeArgSignature(\r\n\t\t\t\t\t\tTypeArgSignature.LOWERBOUND_WILDCARD,\r\n\t\t\t\t\t\t(FieldTypeSignature) getFullTypeSignature(lowerBound));\r\n\t\t\t} else {\r\n\t\t\t\tthrow new RuntimeException(\"Invalid type\");\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\treturn new TypeArgSignature(TypeArgSignature.NO_WILDCARD,\r\n\t\t\t\t\t(FieldTypeSignature) getFullTypeSignature(type));\r\n\t\t}\r\n\t}", "public void bindScriptBundleToScene(GVRScriptBundle scriptBundle, GVRScene scene) throws IOException, GVRScriptException {\n for (GVRSceneObject sceneObject : scene.getSceneObjects()) {\n bindBundleToSceneObject(scriptBundle, sceneObject);\n }\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 static Project dependsOnArtifact(Artifact artifact)\n {\n Project project = new Project();\n project.artifact = artifact;\n return project;\n }", "private Logger createLoggerInstance(String loggerName) throws Exception\r\n {\r\n Class loggerClass = getConfiguration().getLoggerClass();\r\n Logger log = (Logger) ClassHelper.newInstance(loggerClass, String.class, loggerName);\r\n log.configure(getConfiguration());\r\n return log;\r\n }", "private void getMonthlyAbsoluteDates(Calendar calendar, int frequency, List<Date> dates)\n {\n int currentDayNumber = calendar.get(Calendar.DAY_OF_MONTH);\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n int requiredDayNumber = NumberHelper.getInt(m_dayNumber);\n if (requiredDayNumber < currentDayNumber)\n {\n calendar.add(Calendar.MONTH, 1);\n }\n\n while (moreDates(calendar, dates))\n {\n int useDayNumber = requiredDayNumber;\n int maxDayNumber = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);\n if (useDayNumber > maxDayNumber)\n {\n useDayNumber = maxDayNumber;\n }\n calendar.set(Calendar.DAY_OF_MONTH, useDayNumber);\n dates.add(calendar.getTime());\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n calendar.add(Calendar.MONTH, frequency);\n }\n }" ]
Use this API to add transformpolicy.
[ "public static base_response add(nitro_service client, transformpolicy resource) throws Exception {\n\t\ttransformpolicy addresource = new transformpolicy();\n\t\taddresource.name = resource.name;\n\t\taddresource.rule = resource.rule;\n\t\taddresource.profilename = resource.profilename;\n\t\taddresource.comment = resource.comment;\n\t\taddresource.logaction = resource.logaction;\n\t\treturn addresource.add_resource(client);\n\t}" ]
[ "public List<Object> stepsInstances(List<CandidateSteps> candidateSteps) {\n List<Object> instances = new ArrayList<>();\n for (CandidateSteps steps : candidateSteps) {\n if (steps instanceof Steps) {\n instances.add(((Steps) steps).instance());\n }\n }\n return instances;\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}", "public void unregisterComponent(java.awt.Component c)\r\n {\r\n java.awt.dnd.DragGestureRecognizer recognizer = \r\n (java.awt.dnd.DragGestureRecognizer)this.hmDragGestureRecognizers.remove(c);\r\n if (recognizer != null)\r\n recognizer.setComponent(null);\r\n }", "public int expect(String pattern) throws MalformedPatternException, Exception {\n logger.trace(\"Searching for '\" + pattern + \"' in the reader stream\");\n return expect(pattern, null);\n }", "private void writeCompressedTexts(File dir, HashMap contents) throws IOException\r\n {\r\n String filename;\r\n\r\n for (Iterator nameIt = contents.keySet().iterator(); nameIt.hasNext();)\r\n {\r\n filename = (String)nameIt.next();\r\n writeCompressedText(new File(dir, filename), (byte[])contents.get(filename));\r\n }\r\n }", "void scan() {\n if (acquireScanLock()) {\n boolean scheduleRescan = false;\n try {\n scheduleRescan = scan(false, deploymentOperations);\n } finally {\n try {\n if (scheduleRescan) {\n synchronized (this) {\n if (scanEnabled) {\n rescanIncompleteTask = scheduledExecutor.schedule(scanRunnable, 200, TimeUnit.MILLISECONDS);\n }\n }\n }\n } finally {\n releaseScanLock();\n }\n }\n }\n }", "private void handleFailedSendDataRequest(SerialMessage originalMessage) {\n\t\tZWaveNode node = this.getNode(originalMessage.getMessageNode());\n\t\t\n\t\tif (node.getNodeStage() == NodeStage.NODEBUILDINFO_DEAD)\n\t\t\treturn;\n\t\t\n\t\tif (!node.isListening() && originalMessage.getPriority() != SerialMessage.SerialMessagePriority.Low) {\n\t\t\tZWaveWakeUpCommandClass wakeUpCommandClass = (ZWaveWakeUpCommandClass)node.getCommandClass(ZWaveCommandClass.CommandClass.WAKE_UP);\n\t\t\t\n\t\t\tif (wakeUpCommandClass != null) {\n\t\t\t\twakeUpCommandClass.setAwake(false);\n\t\t\t\twakeUpCommandClass.putInWakeUpQueue(originalMessage); //it's a battery operated device, place in wake-up queue.\n\t\t\t\treturn;\n\t\t\t}\n\t\t} else if (!node.isListening() && originalMessage.getPriority() == SerialMessage.SerialMessagePriority.Low)\n\t\t\treturn;\n\t\t\n\t\tnode.incrementResendCount();\n\t\t\n\t\tlogger.error(\"Got an error while sending data to node {}. Resending message.\", node.getNodeId());\n\t\tthis.sendData(originalMessage);\n\t}", "public IPv6Address toLinkLocalIPv6() {\r\n\t\tIPv6AddressNetwork network = getIPv6Network();\r\n\t\tIPv6AddressSection linkLocalPrefix = network.getLinkLocalPrefix();\r\n\t\tIPv6AddressCreator creator = network.getAddressCreator();\r\n\t\treturn creator.createAddress(linkLocalPrefix.append(toEUI64IPv6()));\r\n\t}", "public void sendMessageToAgents(String[] agent_name, String msgtype,\n Object message_content, Connector connector) {\n HashMap<String, Object> hm = new HashMap<String, Object>();\n hm.put(\"performative\", msgtype);\n hm.put(SFipa.CONTENT, message_content);\n IComponentIdentifier[] ici = new IComponentIdentifier[agent_name.length];\n for (int i = 0; i < agent_name.length; i++) {\n ici[i] = (IComponentIdentifier) connector.getAgentID(agent_name[i]);\n }\n ((IMessageService) connector.getMessageService()).deliverMessage(hm,\n \"fipa\", ici);\n }" ]
Tries to stop the JLAN server and return after it is stopped, but will also return if the thread hasn't stopped after MAX_SHUTDOWN_WAIT_MILLIS.
[ "public synchronized void stop() {\r\n\r\n if (m_thread != null) {\r\n long timeBeforeShutdownWasCalled = System.currentTimeMillis();\r\n JLANServer.shutdownServer(new String[] {});\r\n while (m_thread.isAlive()\r\n && ((System.currentTimeMillis() - timeBeforeShutdownWasCalled) < MAX_SHUTDOWN_WAIT_MILLIS)) {\r\n try {\r\n Thread.sleep(500);\r\n } catch (InterruptedException e) {\r\n // ignore\r\n }\r\n }\r\n }\r\n\r\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}", "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 }", "private static JSONObject parseBounds(Bounds bounds) throws JSONException {\n if (bounds != null) {\n JSONObject boundsObject = new JSONObject();\n JSONObject lowerRight = new JSONObject();\n JSONObject upperLeft = new JSONObject();\n\n lowerRight.put(\"x\",\n bounds.getLowerRight().getX().doubleValue());\n lowerRight.put(\"y\",\n bounds.getLowerRight().getY().doubleValue());\n\n upperLeft.put(\"x\",\n bounds.getUpperLeft().getX().doubleValue());\n upperLeft.put(\"y\",\n bounds.getUpperLeft().getY().doubleValue());\n\n boundsObject.put(\"lowerRight\",\n lowerRight);\n boundsObject.put(\"upperLeft\",\n upperLeft);\n\n return boundsObject;\n }\n\n return new JSONObject();\n }", "private Double getDuration(Duration duration)\n {\n Double result;\n if (duration == null)\n {\n result = null;\n }\n else\n {\n if (duration.getUnits() != TimeUnit.HOURS)\n {\n duration = duration.convertUnits(TimeUnit.HOURS, m_projectFile.getProjectProperties());\n }\n\n result = Double.valueOf(duration.getDuration());\n }\n return result;\n }", "private void populateCurrencySettings(Record record, ProjectProperties properties)\n {\n properties.setCurrencySymbol(record.getString(0));\n properties.setSymbolPosition(record.getCurrencySymbolPosition(1));\n properties.setCurrencyDigits(record.getInteger(2));\n\n Character c = record.getCharacter(3);\n if (c != null)\n {\n properties.setThousandsSeparator(c.charValue());\n }\n\n c = record.getCharacter(4);\n if (c != null)\n {\n properties.setDecimalSeparator(c.charValue());\n }\n }", "private void enforceSrid(Object feature) throws LayerException {\n\t\tGeometry geom = getFeatureModel().getGeometry(feature);\n\t\tif (null != geom) {\n\t\t\tgeom.setSRID(srid);\n\t\t\tgetFeatureModel().setGeometry(feature, geom);\n\t\t}\n\t}", "private void WebPageCloseOnClick(GVRViewSceneObject gvrWebViewSceneObject, GVRSceneObject gvrSceneObjectAnchor, String url) {\n final String urlFinal = url;\n\n webPagePlusUISceneObject = new GVRSceneObject(gvrContext);\n webPagePlusUISceneObject.getTransform().setPosition(webPagePlusUIPosition[0], webPagePlusUIPosition[1], webPagePlusUIPosition[2]);\n\n GVRScene mainScene = gvrContext.getMainScene();\n\n Sensor webPageSensor = new Sensor(urlFinal, Sensor.Type.TOUCH, gvrWebViewSceneObject, true);\n final GVRSceneObject gvrSceneObjectAnchorFinal = gvrSceneObjectAnchor;\n final GVRSceneObject gvrWebViewSceneObjectFinal = gvrWebViewSceneObject;\n final GVRSceneObject webPagePlusUISceneObjectFinal = webPagePlusUISceneObject;\n\n webPagePlusUISceneObjectFinal.addChildObject(gvrWebViewSceneObjectFinal);\n gvrSceneObjectAnchorFinal.addChildObject(webPagePlusUISceneObjectFinal);\n\n\n webPageSensor.addISensorEvents(new ISensorEvents() {\n boolean uiObjectIsActive = false;\n boolean clickDown = true;\n\n @Override\n public void onSensorEvent(SensorEvent event) {\n if (event.isActive()) {\n clickDown = !clickDown;\n if (clickDown) {\n // Delete the WebView page\n gvrSceneObjectAnchorFinal.removeChildObject(webPagePlusUISceneObjectFinal);\n webPageActive = false;\n webPagePlusUISceneObject = null;\n webPageClosed = true; // Make sure click up doesn't open web page behind it\n }\n }\n }\n });\n }", "@Override\n\tpublic ProxyAuthenticationMethod getMethod() {\n\t\tswitch (authenticationMethod) {\n\t\tcase BASIC:\n\t\t\treturn ProxyAuthenticationMethod.BASIC;\n\t\tcase DIGEST:\n\t\t\treturn ProxyAuthenticationMethod.DIGEST;\n\t\tcase URL:\n\t\t\treturn ProxyAuthenticationMethod.URL;\n\t\tdefault:\n\t\t\treturn null;\n\t\t}\n\t}", "public static FormValidation validateArtifactoryCombinationFilter(String value)\n throws IOException, InterruptedException {\n String url = Util.fixEmptyAndTrim(value);\n if (url == null)\n return FormValidation.error(\"Mandatory field - You don`t have any deploy matches\");\n\n return FormValidation.ok();\n }" ]
Log original incoming request @param requestType @param request @param history
[ "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 }" ]
[ "private void readFieldAlias(Project.ExtendedAttributes.ExtendedAttribute attribute)\n {\n String alias = attribute.getAlias();\n if (alias != null && alias.length() != 0)\n {\n FieldType field = FieldTypeHelper.getInstance(Integer.parseInt(attribute.getFieldID()));\n m_projectFile.getCustomFields().getCustomField(field).setAlias(attribute.getAlias());\n }\n }", "public static <T> T invokeSetters(final T instance, final Map<String,Object> vars) \n throws ReflectiveOperationException {\n if (instance != null && vars != null) {\n final Class<?> clazz = instance.getClass();\n final Method[] methods = clazz.getMethods();\n for (final Entry<String,Object> entry : vars.entrySet()) {\n final String methodName = \"set\" + entry.getKey().substring(0, 1).toUpperCase(Locale.US) \n + entry.getKey().substring(1);\n boolean found = false;\n for (final Method method : methods) {\n if (methodName.equals(method.getName()) && method.getParameterTypes().length == 1) {\n method.invoke(instance, entry.getValue());\n found = true;\n break;\n }\n }\n if (!found) {\n throw new NoSuchMethodException(\"Expected setter named '\" + methodName \n + \"' for var '\" + entry.getKey() + \"'\");\n }\n }\n }\n return instance;\n }", "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 aaapreauthenticationpolicy_aaaglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\taaapreauthenticationpolicy_aaaglobal_binding obj = new aaapreauthenticationpolicy_aaaglobal_binding();\n\t\tobj.set_name(name);\n\t\taaapreauthenticationpolicy_aaaglobal_binding response[] = (aaapreauthenticationpolicy_aaaglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static String formatDateRange(Context context, ReadablePartial start, ReadablePartial end, int flags) {\n return formatDateRange(context, toMillis(start), toMillis(end), flags);\n }", "private void setPropertyFilters(String filters) {\n\t\tthis.filterProperties = new HashSet<>();\n\t\tif (!\"-\".equals(filters)) {\n\t\t\tfor (String pid : filters.split(\",\")) {\n\t\t\t\tthis.filterProperties.add(Datamodel\n\t\t\t\t\t\t.makeWikidataPropertyIdValue(pid));\n\t\t\t}\n\t\t}\n\t}", "public static String nextWord(String string) {\n int index = 0;\n while (index < string.length() && !Character.isWhitespace(string.charAt(index))) {\n index++;\n }\n return string.substring(0, index);\n }", "private void initXmlBundle() throws CmsException {\n\n CmsFile file = m_cms.readFile(m_resource);\n m_bundleFiles.put(null, m_resource);\n m_xmlBundle = CmsXmlContentFactory.unmarshal(m_cms, file);\n initKeySetForXmlBundle();\n\n }", "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 }" ]