query
stringlengths 7
3.3k
| positive
sequencelengths 1
1
| negative
sequencelengths 9
9
|
---|---|---|
Get the metadata of all tracks currently loaded in any player, either on the play deck, or in a hot cue.
@return the track information reported by all current players, including any tracks loaded in their hot cue slots
@throws IllegalStateException if the MetadataFinder is not running | [
"public Map<DeckReference, TrackMetadata> getLoadedTracks() {\n ensureRunning();\n // Make a copy so callers get an immutable snapshot of the current state.\n return Collections.unmodifiableMap(new HashMap<DeckReference, TrackMetadata>(hotCache));\n }"
] | [
"private boolean operations(Options opt, ConstructorDoc m[]) {\n\tboolean printed = false;\n\tfor (ConstructorDoc cd : m) {\n\t if (hidden(cd))\n\t\tcontinue;\n\t stereotype(opt, cd, Align.LEFT);\n\t String cs = visibility(opt, cd) + cd.name() //\n\t\t + (opt.showType ? \"(\" + parameter(opt, cd.parameters()) + \")\" : \"()\");\n\t tableLine(Align.LEFT, cs);\n\t tagvalue(opt, cd);\n\t printed = true;\n\t}\n\treturn printed;\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}",
"@JsonProperty(\"paging\")\n void paging(String paging) {\n builder.paging(IndexPagingState.fromByteBuffer(ByteBufferUtils.byteBuffer(paging)));\n }",
"public void setDateAttribute(String name, Date value) {\n\t\tensureAttributes();\n\t\tAttribute attribute = new DateAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetAllAttributes().put(name, attribute);\n\t}",
"protected static String createDotStoryName(String scenarioName) {\n String[] words = scenarioName.trim().split(\" \");\n String result = \"\";\n for (int i = 0; i < words.length; i++) {\n String word1 = words[i];\n String word2 = word1.toLowerCase();\n if (!word1.equals(word2)) {\n String finalWord = \"\";\n for (int j = 0; j < word1.length(); j++) {\n if (i != 0) {\n char c = word1.charAt(j);\n if (Character.isUpperCase(c)) {\n if (j==0) {\n finalWord += Character.toLowerCase(c);\n } else {\n finalWord += \"_\" + Character.toLowerCase(c); \n }\n } else {\n finalWord += c;\n }\n } else {\n finalWord = word2;\n break;\n }\n }\n\n result += finalWord;\n } else {\n result += word2;\n }\n // I don't add the '_' to the last word.\n if (!(i == words.length - 1))\n result += \"_\";\n }\n return result;\n }",
"protected void handleParentheses( TokenList tokens, Sequence sequence ) {\n // have a list to handle embedded parentheses, e.g. (((((a)))))\n List<TokenList.Token> left = new ArrayList<TokenList.Token>();\n\n // find all of them\n TokenList.Token t = tokens.first;\n while( t != null ) {\n TokenList.Token next = t.next;\n if( t.getType() == Type.SYMBOL ) {\n if( t.getSymbol() == Symbol.PAREN_LEFT )\n left.add(t);\n else if( t.getSymbol() == Symbol.PAREN_RIGHT ) {\n if( left.isEmpty() )\n throw new ParseError(\") found with no matching (\");\n\n TokenList.Token a = left.remove(left.size()-1);\n\n // remember the element before so the new one can be inserted afterwards\n TokenList.Token before = a.previous;\n\n TokenList sublist = tokens.extractSubList(a,t);\n // remove parentheses\n sublist.remove(sublist.first);\n sublist.remove(sublist.last);\n\n // if its a function before () then the () indicates its an input to a function\n if( before != null && before.getType() == Type.FUNCTION ) {\n List<TokenList.Token> inputs = parseParameterCommaBlock(sublist, sequence);\n if (inputs.isEmpty())\n throw new ParseError(\"Empty function input parameters\");\n else {\n createFunction(before, inputs, tokens, sequence);\n }\n } else if( before != null && before.getType() == Type.VARIABLE &&\n before.getVariable().getType() == VariableType.MATRIX ) {\n // if it's a variable then that says it's a sub-matrix\n TokenList.Token extract = parseSubmatrixToExtract(before,sublist, sequence);\n // put in the extract operation\n tokens.insert(before,extract);\n tokens.remove(before);\n } else {\n // if null then it was empty inside\n TokenList.Token output = parseBlockNoParentheses(sublist,sequence, false);\n if (output != null)\n tokens.insert(before, output);\n }\n }\n }\n t = next;\n }\n\n if( !left.isEmpty())\n throw new ParseError(\"Dangling ( parentheses\");\n }",
"public void put(@NotNull final PersistentStoreTransaction txn,\n final long localId,\n @NotNull final ByteIterable value,\n @Nullable final ByteIterable oldValue,\n final int propertyId,\n @NotNull final ComparableValueType type) {\n final Store valueIdx = getOrCreateValueIndex(txn, propertyId);\n final ByteIterable key = PropertyKey.propertyKeyToEntry(new PropertyKey(localId, propertyId));\n final Transaction envTxn = txn.getEnvironmentTransaction();\n primaryStore.put(envTxn, key, value);\n final ByteIterable secondaryValue = LongBinding.longToCompressedEntry(localId);\n boolean success;\n if (oldValue == null) {\n success = allPropsIndex.put(envTxn, IntegerBinding.intToCompressedEntry(propertyId), secondaryValue);\n } else {\n success = deleteFromStore(envTxn, valueIdx, secondaryValue, createSecondaryKeys(store.getPropertyTypes(), oldValue, type));\n }\n if (success) {\n for (final ByteIterable secondaryKey : createSecondaryKeys(store.getPropertyTypes(), value, type)) {\n valueIdx.put(envTxn, secondaryKey, secondaryValue);\n }\n }\n checkStatus(success, \"Failed to put\");\n }",
"@Override\n\tpublic BigInteger getCount() {\n\t\tBigInteger cached = cachedCount;\n\t\tif(cached == null) {\n\t\t\tcachedCount = cached = getCountImpl();\n\t\t}\n\t\treturn cached;\n\t}",
"private void writeCalendar(ProjectCalendar record) throws IOException\n {\n //\n // Test used to ensure that we don't write the default calendar used for the \"Unassigned\" resource\n //\n if (record.getParent() == null || record.getResource() != null)\n {\n m_buffer.setLength(0);\n\n if (record.getParent() == null)\n {\n m_buffer.append(MPXConstants.BASE_CALENDAR_RECORD_NUMBER);\n m_buffer.append(m_delimiter);\n if (record.getName() != null)\n {\n m_buffer.append(record.getName());\n }\n }\n else\n {\n m_buffer.append(MPXConstants.RESOURCE_CALENDAR_RECORD_NUMBER);\n m_buffer.append(m_delimiter);\n m_buffer.append(record.getParent().getName());\n }\n\n for (DayType day : record.getDays())\n {\n if (day == null)\n {\n day = DayType.DEFAULT;\n }\n m_buffer.append(m_delimiter);\n m_buffer.append(day.getValue());\n }\n\n m_buffer.append(MPXConstants.EOL);\n m_writer.write(m_buffer.toString());\n\n ProjectCalendarHours[] hours = record.getHours();\n for (int loop = 0; loop < hours.length; loop++)\n {\n if (hours[loop] != null)\n {\n writeCalendarHours(record, hours[loop]);\n }\n }\n\n if (!record.getCalendarExceptions().isEmpty())\n {\n //\n // A quirk of MS Project is that these exceptions must be\n // in date order in the file, otherwise they are ignored.\n // The getCalendarExceptions method now guarantees that\n // the exceptions list is sorted when retrieved.\n //\n for (ProjectCalendarException ex : record.getCalendarExceptions())\n {\n writeCalendarException(record, ex);\n }\n }\n\n m_eventManager.fireCalendarWrittenEvent(record);\n }\n }"
] |
Deletes all steps of scenario cases where a data table
is generated to reduce the size of the data file.
In this case only the steps of the first scenario case are actually needed. | [
"private void deleteUnusedCaseSteps( ReportModel model ) {\n\n for( ScenarioModel scenarioModel : model.getScenarios() ) {\n if( scenarioModel.isCasesAsTable() && !hasAttachment( scenarioModel ) ) {\n List<ScenarioCaseModel> cases = scenarioModel.getScenarioCases();\n for( int i = 1; i < cases.size(); i++ ) {\n ScenarioCaseModel caseModel = cases.get( i );\n caseModel.setSteps( Collections.<StepModel>emptyList() );\n }\n }\n }\n }"
] | [
"public synchronized ModelNode doCommand(String command) throws CommandFormatException, IOException {\n ModelNode request = cmdCtx.buildRequest(command);\n return execute(request, isSlowCommand(command)).getResponseNode();\n }",
"public static lbmonitor_binding[] get(nitro_service service, String monitorname[]) throws Exception{\n\t\tif (monitorname !=null && monitorname.length>0) {\n\t\t\tlbmonitor_binding response[] = new lbmonitor_binding[monitorname.length];\n\t\t\tlbmonitor_binding obj[] = new lbmonitor_binding[monitorname.length];\n\t\t\tfor (int i=0;i<monitorname.length;i++) {\n\t\t\t\tobj[i] = new lbmonitor_binding();\n\t\t\t\tobj[i].set_monitorname(monitorname[i]);\n\t\t\t\tresponse[i] = (lbmonitor_binding) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}",
"public void convertToDense() {\n switch ( mat.getType() ) {\n case DSCC: {\n DMatrix m = new DMatrixRMaj(mat.getNumRows(), mat.getNumCols());\n ConvertDMatrixStruct.convert((DMatrix) mat, m);\n setMatrix(m);\n } break;\n case FSCC: {\n FMatrix m = new FMatrixRMaj(mat.getNumRows(), mat.getNumCols());\n ConvertFMatrixStruct.convert((FMatrix) mat, m);\n setMatrix(m);\n } break;\n case DDRM:\n case FDRM:\n case ZDRM:\n case CDRM:\n break;\n default:\n throw new RuntimeException(\"Not a sparse matrix!\");\n }\n }",
"public static void applyWsdlExtensions(Bus bus) {\n\n ExtensionRegistry registry = bus.getExtension(WSDLManager.class).getExtensionRegistry();\n\n try {\n\n JAXBExtensionHelper.addExtensions(registry,\n javax.wsdl.Definition.class,\n org.talend.esb.mep.requestcallback.impl.wsdl.PLType.class);\n\n JAXBExtensionHelper.addExtensions(registry,\n javax.wsdl.Binding.class,\n org.talend.esb.mep.requestcallback.impl.wsdl.CallbackExtension.class);\n\n } catch (JAXBException e) {\n throw new RuntimeException(\"Failed to add WSDL JAXB extensions\", e);\n }\n }",
"public static base_response add(nitro_service client, systemuser resource) throws Exception {\n\t\tsystemuser addresource = new systemuser();\n\t\taddresource.username = resource.username;\n\t\taddresource.password = resource.password;\n\t\taddresource.externalauth = resource.externalauth;\n\t\taddresource.promptstring = resource.promptstring;\n\t\taddresource.timeout = resource.timeout;\n\t\treturn addresource.add_resource(client);\n\t}",
"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 }",
"protected int adjustIndex(Widget child, int beforeIndex) {\n\n checkIndexBoundsForInsertion(beforeIndex);\n\n // Check to see if this widget is already a direct child.\n if (child.getParent() == this) {\n // If the Widget's previous position was left of the desired new position\n // shift the desired position left to reflect the removal\n int idx = getWidgetIndex(child);\n if (idx < beforeIndex) {\n beforeIndex--;\n }\n }\n\n return beforeIndex;\n }",
"public static void munlock(Pointer addr, long len) {\n\n if(Delegate.munlock(addr, new NativeLong(len)) != 0) {\n if(logger.isDebugEnabled())\n logger.debug(\"munlocking failed with errno:\" + errno.strerror());\n } else {\n if(logger.isDebugEnabled())\n logger.debug(\"munlocking region\");\n }\n }",
"private ProjectFile handleOleCompoundDocument(InputStream stream) throws Exception\n {\n POIFSFileSystem fs = new POIFSFileSystem(POIFSFileSystem.createNonClosingInputStream(stream));\n String fileFormat = MPPReader.getFileFormat(fs);\n if (fileFormat != null && fileFormat.startsWith(\"MSProject\"))\n {\n MPPReader reader = new MPPReader();\n addListeners(reader);\n return reader.read(fs);\n }\n return null;\n }"
] |
Retrieve the index of the table entry valid for the supplied date.
@param date required date
@return cost rate table entry index | [
"public int getIndexByDate(Date date)\n {\n int result = -1;\n int index = 0;\n\n for (CostRateTableEntry entry : this)\n {\n if (DateHelper.compare(date, entry.getEndDate()) < 0)\n {\n result = index;\n break;\n }\n ++index;\n }\n\n return result;\n }"
] | [
"private static void updateJar(final File file, final byte[] searchPattern, final int[] badSkipBytes, final int newSig, final int endSig) throws IOException {\n final RandomAccessFile raf = new RandomAccessFile(file, \"rw\");\n try {\n final FileChannel channel = raf.getChannel();\n try {\n long pos = channel.size() - ENDLEN;\n final ScanContext context;\n if (newSig == CRIPPLED_ENDSIG) {\n context = new ScanContext(GOOD_ENDSIG_PATTERN, CRIPPLED_ENDSIG_PATTERN);\n } else if (newSig == GOOD_ENDSIG) {\n context = new ScanContext(CRIPPLED_ENDSIG_PATTERN, GOOD_ENDSIG_PATTERN);\n } else {\n context = null;\n }\n\n if (!validateEndRecord(file, channel, pos, endSig)) {\n pos = scanForEndSig(file, channel, context);\n }\n if (pos == -1) {\n if (context.state == State.NOT_FOUND) {\n // Don't fail patching if we cannot validate a valid zip\n PatchLogger.ROOT_LOGGER.cannotInvalidateZip(file.getAbsolutePath());\n }\n return;\n }\n // Update the central directory record\n channel.position(pos);\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(ByteOrder.LITTLE_ENDIAN);\n buffer.putInt(newSig);\n buffer.flip();\n while (buffer.hasRemaining()) {\n channel.write(buffer);\n }\n } finally {\n safeClose(channel);\n }\n } finally {\n safeClose(raf);\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 }",
"private static String formatDirName(final String prefix, final String suffix) {\n // Replace all invalid characters with '-'\n final CharMatcher invalidCharacters = VALID_SUFFIX_CHARS.negate();\n return String.format(\"%s-%s\", prefix, invalidCharacters.trimAndCollapseFrom(suffix.toLowerCase(), '-'));\n }",
"public void reportCompletion(NodeT completed) {\n completed.setPreparer(true);\n String dependency = completed.key();\n for (String dependentKey : nodeTable.get(dependency).dependentKeys()) {\n DAGNode<DataT, NodeT> dependent = nodeTable.get(dependentKey);\n dependent.lock().lock();\n try {\n dependent.onSuccessfulResolution(dependency);\n if (dependent.hasAllResolved()) {\n queue.add(dependent.key());\n }\n } finally {\n dependent.lock().unlock();\n }\n }\n }",
"public static ServiceFuture<Void> fromBody(final Completable completable, final ServiceCallback<Void> callback) {\n final ServiceFuture<Void> serviceFuture = new ServiceFuture<>();\n completable.subscribe(new Action0() {\n Void value = null;\n @Override\n public void call() {\n if (callback != null) {\n callback.success(value);\n }\n serviceFuture.set(value);\n }\n }, new Action1<Throwable>() {\n @Override\n public void call(Throwable throwable) {\n if (callback != null) {\n callback.failure(throwable);\n }\n serviceFuture.setException(throwable);\n }\n });\n return serviceFuture;\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 getMemberName() throws XDocletException\r\n {\r\n if (getCurrentField() != null) {\r\n return getCurrentField().getName();\r\n }\r\n else if (getCurrentMethod() != null) {\r\n return MethodTagsHandler.getPropertyNameFor(getCurrentMethod());\r\n }\r\n else {\r\n return null;\r\n }\r\n }",
"@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients\", method = RequestMethod.POST)\n public\n @ResponseBody\n HashMap<String, Object> addClient(Model model,\n @PathVariable(\"profileIdentifier\") String profileIdentifier,\n @RequestParam(required = false) String friendlyName) throws Exception {\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n\n // make sure client with this name does not already exist\n if (null != clientService.findClientFromFriendlyName(profileId, friendlyName)) {\n \tthrow new Exception(\"Cannot add client. Friendly name already in use.\");\n }\n \n Client client = clientService.add(profileId);\n\n // set friendly name if it was specified\n if (friendlyName != null) {\n clientService.setFriendlyName(profileId, client.getUUID(), friendlyName);\n client.setFriendlyName(friendlyName);\n }\n\n HashMap<String, Object> valueHash = new HashMap<String, Object>();\n valueHash.put(\"client\", client);\n return valueHash;\n }",
"protected Object buildOrRefreshObject(Map row, ClassDescriptor targetClassDescriptor, Object targetObject)\r\n {\r\n Object result = targetObject;\r\n FieldDescriptor fmd;\r\n FieldDescriptor[] fields = targetClassDescriptor.getFieldDescriptor(true);\r\n\r\n if(targetObject == null)\r\n {\r\n // 1. create new object instance if needed\r\n result = ClassHelper.buildNewObjectInstance(targetClassDescriptor);\r\n }\r\n\r\n // 2. fill all scalar attributes of the new object\r\n for (int i = 0; i < fields.length; i++)\r\n {\r\n fmd = fields[i];\r\n fmd.getPersistentField().set(result, row.get(fmd.getColumnName()));\r\n }\r\n\r\n if(targetObject == null)\r\n {\r\n // 3. for new build objects, invoke the initialization method for the class if one is provided\r\n Method initializationMethod = targetClassDescriptor.getInitializationMethod();\r\n if (initializationMethod != null)\r\n {\r\n try\r\n {\r\n initializationMethod.invoke(result, NO_ARGS);\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new PersistenceBrokerException(\"Unable to invoke initialization method:\" + initializationMethod.getName() + \" for class:\" + m_cld.getClassOfObject(), ex);\r\n }\r\n }\r\n }\r\n return result;\r\n }"
] |
Return a list of unique namespaces, optionally limited by a given predicate, in alphabetical order.
This method does not require authentication.
@param predicate
@param perPage
@param page
@return NamespacesList
@throws FlickrException | [
"public NamespacesList<Namespace> getNamespaces(String predicate, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n NamespacesList<Namespace> nsList = new NamespacesList<Namespace>();\r\n parameters.put(\"method\", METHOD_GET_NAMESPACES);\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(\"namespace\");\r\n nsList.setPage(\"1\");\r\n nsList.setPages(\"1\");\r\n nsList.setPerPage(\"\" + nsNodes.getLength());\r\n nsList.setTotal(\"\" + nsNodes.getLength());\r\n for (int i = 0; i < nsNodes.getLength(); i++) {\r\n Element element = (Element) nsNodes.item(i);\r\n nsList.add(parseNamespace(element));\r\n }\r\n return nsList;\r\n }"
] | [
"public void setEndTime(final Date date) {\r\n\r\n if (!Objects.equals(m_model.getEnd(), date)) {\r\n m_model.setEnd(date);\r\n valueChanged();\r\n }\r\n\r\n }",
"public static sslpolicy_lbvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tsslpolicy_lbvserver_binding obj = new sslpolicy_lbvserver_binding();\n\t\tobj.set_name(name);\n\t\tsslpolicy_lbvserver_binding response[] = (sslpolicy_lbvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public ForeignkeyDef getForeignkey(String name, String tableName)\r\n {\r\n String realName = (name == null ? \"\" : name);\r\n ForeignkeyDef def = null;\r\n\r\n for (Iterator it = getForeignkeys(); it.hasNext();)\r\n {\r\n def = (ForeignkeyDef)it.next();\r\n if (realName.equals(def.getName()) &&\r\n def.getTableName().equals(tableName))\r\n {\r\n return def;\r\n }\r\n }\r\n return null;\r\n }",
"public ItemRequest<Task> removeFollowers(String task) {\n \n String path = String.format(\"/tasks/%s/removeFollowers\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }",
"public static String formatConnectionEstablishmentMessage(final String connectionName, final String host, final String connectionReason) {\n\t\treturn CON_ESTABLISHMENT_FORMAT.format(new Object[] { connectionName, host, connectionReason });\n\t}",
"public void append(Object object, String indentation) {\n\t\tappend(object, indentation, segments.size());\n\t}",
"public void setDateMax(Date dateMax) {\n this.dateMax = dateMax;\n\n if (isAttached() && dateMax != null) {\n getPicker().set(\"max\", JsDate.create((double) dateMax.getTime()));\n }\n }",
"private synchronized Class<?> getClass(String className) throws Exception {\n // see if we need to invalidate the class\n ClassInformation classInfo = classInformation.get(className);\n File classFile = new File(classInfo.pluginPath);\n if (classFile.lastModified() > classInfo.lastModified) {\n logger.info(\"Class {} has been modified, reloading\", className);\n logger.info(\"Thread ID: {}\", Thread.currentThread().getId());\n classInfo.loaded = false;\n classInformation.put(className, classInfo);\n\n // also cleanup anything in methodInformation with this className so it gets reloaded\n Iterator<Map.Entry<String, com.groupon.odo.proxylib.models.Method>> iter = methodInformation.entrySet().iterator();\n while (iter.hasNext()) {\n Map.Entry<String, com.groupon.odo.proxylib.models.Method> entry = iter.next();\n if (entry.getKey().startsWith(className)) {\n iter.remove();\n }\n }\n }\n\n if (!classInfo.loaded) {\n loadClass(className);\n }\n\n return classInfo.loadedClass;\n }",
"public static String digestToFileName(String digest) {\n if (StringUtils.startsWith(digest, \"sha1\")) {\n return \"manifest.json\";\n }\n return getShaVersion(digest) + \"__\" + getShaValue(digest);\n }"
] |
Use this API to fetch the statistics of all appfwpolicy_stats resources that are configured on netscaler. | [
"public static appfwpolicy_stats[] get(nitro_service service) throws Exception{\n\t\tappfwpolicy_stats obj = new appfwpolicy_stats();\n\t\tappfwpolicy_stats[] response = (appfwpolicy_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}"
] | [
"private void writeTaskExtendedAttributes(Project.Tasks.Task xml, Task mpx)\n {\n Project.Tasks.Task.ExtendedAttribute attrib;\n List<Project.Tasks.Task.ExtendedAttribute> extendedAttributes = xml.getExtendedAttribute();\n\n for (TaskField mpxFieldID : getAllTaskExtendedAttributes())\n {\n Object value = mpx.getCachedValue(mpxFieldID);\n\n if (FieldTypeHelper.valueIsNotDefault(mpxFieldID, value))\n {\n m_extendedAttributesInUse.add(mpxFieldID);\n\n Integer xmlFieldID = Integer.valueOf(MPPTaskField.getID(mpxFieldID) | MPPTaskField.TASK_FIELD_BASE);\n\n attrib = m_factory.createProjectTasksTaskExtendedAttribute();\n extendedAttributes.add(attrib);\n attrib.setFieldID(xmlFieldID.toString());\n attrib.setValue(DatatypeConverter.printExtendedAttribute(this, value, mpxFieldID.getDataType()));\n attrib.setDurationFormat(printExtendedAttributeDurationFormat(value));\n }\n }\n }",
"public void writeOutput(DataPipe cr) {\n try {\n context.write(NullWritable.get(), new Text(cr.getPipeDelimited(outTemplate)));\n } catch (Exception e) {\n throw new RuntimeException(\"Exception occurred while writing to Context\", e);\n }\n }",
"public static base_responses clear(nitro_service client, route6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\troute6 clearresources[] = new route6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tclearresources[i] = new route6();\n\t\t\t\tclearresources[i].routetype = resources[i].routetype;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, clearresources,\"clear\");\n\t\t}\n\t\treturn result;\n\t}",
"public void destroy() throws Exception {\n if (_clientId == null) {\n return;\n }\n\n // delete the clientId here\n String uri = BASE_PROFILE + uriEncode(_profileName) + \"/\" + BASE_CLIENTS + \"/\" + _clientId;\n try {\n doDelete(uri, null);\n } catch (Exception e) {\n // some sort of error\n throw new Exception(\"Could not delete a proxy client\");\n }\n }",
"@Override\n public HandlerRegistration addSearchNoResultHandler(final SearchNoResultEvent.SearchNoResultHandler handler) {\n return addHandler(handler, SearchNoResultEvent.TYPE);\n }",
"private Class<?> beanType(String name) {\n\t\tClass<?> type = context.getType(name);\n\t\tif (ClassUtils.isCglibProxyClass(type)) {\n\t\t\treturn AopProxyUtils.ultimateTargetClass(context.getBean(name));\n\t\t}\n\t\treturn type;\n\t}",
"private String extractAndConvertTaskType(Task task)\n {\n String activityType = (String) task.getCachedValue(m_activityTypeField);\n if (activityType == null)\n {\n activityType = \"Resource Dependent\";\n }\n else\n {\n if (ACTIVITY_TYPE_MAP.containsKey(activityType))\n {\n activityType = ACTIVITY_TYPE_MAP.get(activityType);\n }\n }\n return activityType;\n }",
"public Diff compare(CtElement left, CtElement right) {\n\t\tfinal SpoonGumTreeBuilder scanner = new SpoonGumTreeBuilder();\n\t\treturn new DiffImpl(scanner.getTreeContext(), scanner.getTree(left), scanner.getTree(right));\n\t}",
"public static boolean isTemplatePath(String string) {\n int sz = string.length();\n if (sz == 0) {\n return true;\n }\n for (int i = 0; i < sz; ++i) {\n char c = string.charAt(i);\n switch (c) {\n case ' ':\n case '\\t':\n case '\\b':\n case '<':\n case '>':\n case '(':\n case ')':\n case '[':\n case ']':\n case '{':\n case '}':\n case '!':\n case '@':\n case '#':\n case '*':\n case '?':\n case '%':\n case '|':\n case ',':\n case ':':\n case ';':\n case '^':\n case '&':\n return false;\n }\n }\n return true;\n }"
] |
Returns the master mode's editor state for editing a bundle with descriptor.
@return the master mode's editor state for editing a bundle with descriptor. | [
"private EditorState getMasterState() {\n\n List<TableProperty> cols = new ArrayList<TableProperty>(4);\n cols.add(TableProperty.KEY);\n cols.add(TableProperty.DESCRIPTION);\n cols.add(TableProperty.DEFAULT);\n cols.add(TableProperty.TRANSLATION);\n return new EditorState(cols, true);\n }"
] | [
"public static void configureProtocolHandler() {\n final String pkgs = System.getProperty(\"java.protocol.handler.pkgs\");\n String newValue = \"org.mapfish.print.url\";\n if (pkgs != null && !pkgs.contains(newValue)) {\n newValue = newValue + \"|\" + pkgs;\n } else if (pkgs != null) {\n newValue = pkgs;\n }\n System.setProperty(\"java.protocol.handler.pkgs\", newValue);\n }",
"public static boolean bidiagOuterBlocks( final int blockLength ,\n final DSubmatrixD1 A ,\n final double gammasU[],\n final double gammasV[])\n {\n// System.out.println(\"---------- Orig\");\n// A.original.print();\n\n int width = Math.min(blockLength,A.col1-A.col0);\n int height = Math.min(blockLength,A.row1-A.row0);\n\n int min = Math.min(width,height);\n\n for( int i = 0; i < min; i++ ) {\n //--- Apply reflector to the column\n\n // compute the householder vector\n if (!computeHouseHolderCol(blockLength, A, gammasU, i))\n return false;\n\n // apply to rest of the columns in the column block\n rank1UpdateMultR_Col(blockLength,A,i,gammasU[A.col0+i]);\n\n // apply to the top row block\n rank1UpdateMultR_TopRow(blockLength,A,i,gammasU[A.col0+i]);\n\n System.out.println(\"After column stuff\");\n A.original.print();\n\n //-- Apply reflector to the row\n if(!computeHouseHolderRow(blockLength,A,gammasV,i))\n return false;\n \n // apply to rest of the rows in the row block\n rank1UpdateMultL_Row(blockLength,A,i,i+1,gammasV[A.row0+i]);\n\n System.out.println(\"After update row\");\n A.original.print();\n\n // apply to the left column block\n // TODO THIS WON'T WORK!!!!!!!!!!!!!\n // Needs the whole matrix to have been updated by the left reflector to compute the correct solution\n// rank1UpdateMultL_LeftCol(blockLength,A,i,i+1,gammasV[A.row0+i]);\n\n System.out.println(\"After row stuff\");\n A.original.print();\n }\n\n return true;\n }",
"@Modified(id = \"exporterServices\")\n void modifiedExporterService(ServiceReference<ExporterService> serviceReference) {\n try {\n exportersManager.modified(serviceReference);\n } catch (InvalidFilterException invalidFilterException) {\n LOG.error(\"The ServiceProperty \\\"\" + TARGET_FILTER_PROPERTY + \"\\\" of the ExporterService \"\n + bundleContext.getService(serviceReference) + \" doesn't provides a valid Filter.\"\n + \" To be used, it must provides a correct \\\"\" + TARGET_FILTER_PROPERTY + \"\\\" ServiceProperty.\",\n invalidFilterException\n );\n exportersManager.removeLinks(serviceReference);\n return;\n }\n if (exportersManager.matched(serviceReference)) {\n exportersManager.updateLinks(serviceReference);\n } else {\n exportersManager.removeLinks(serviceReference);\n }\n }",
"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 }",
"static boolean isOnClasspath(String className) {\n boolean isOnClassPath = true;\n try {\n Class.forName(className);\n } catch (ClassNotFoundException exception) {\n isOnClassPath = false;\n }\n return isOnClassPath;\n }",
"@Override public Object instantiateItem(ViewGroup parent, int position) {\n T content = getItem(position);\n rendererBuilder.withContent(content);\n rendererBuilder.withParent(parent);\n rendererBuilder.withLayoutInflater(LayoutInflater.from(parent.getContext()));\n Renderer<T> renderer = rendererBuilder.build();\n if (renderer == null) {\n throw new NullRendererBuiltException(\"RendererBuilder have to return a not null Renderer\");\n }\n updateRendererExtraValues(content, renderer, position);\n renderer.render();\n View view = renderer.getRootView();\n parent.addView(view);\n return view;\n }",
"protected <T> Request doInvoke(ResponseReader responseReader,\n String methodName, RpcStatsContext statsContext, String requestData,\n AsyncCallback<T> callback) {\n\n RequestBuilder rb = doPrepareRequestBuilderImpl(responseReader, methodName,\n statsContext, requestData, callback);\n\n try {\n return rb.send();\n } catch (RequestException ex) {\n InvocationException iex = new InvocationException(\n \"Unable to initiate the asynchronous service invocation (\" +\n methodName + \") -- check the network connection\",\n ex);\n callback.onFailure(iex);\n } finally {\n if (statsContext.isStatsAvailable()) {\n statsContext.stats(statsContext.bytesStat(methodName,\n requestData.length(), \"requestSent\"));\n }\n }\n return null;\n }",
"private void addDependencyToGraph(final DbDependency dependency, final AbstractGraph graph, final int depth, final String parentId) {\n // In that case of Axway artifact we will add a module to the graph\n if (filters.getCorporateFilter().filter(dependency)) {\n final DbModule dbTarget = repoHandler.getModuleOf(dependency.getTarget());\n\n // if there is no module, add the artifact to the graph\n if(dbTarget == null){\n LOG.error(\"Got missing reference: \" + dependency.getTarget());\n final DbArtifact dbArtifact = DataUtils.createDbArtifact(dependency.getTarget());\n final String targetElementId = graph.getId(dbArtifact);\n graph.addElement(targetElementId, dbArtifact.getVersion(), false);\n graph.addDependency(parentId, targetElementId, dependency.getScope());\n return;\n }\n\n // Add the element to the graph\n addModuleToGraph(dbTarget, graph, depth + 1);\n\n //Add the dependency to the graph\n final String moduleElementId = graph.getId(dbTarget);\n graph.addDependency(parentId, moduleElementId, dependency.getScope());\n }\n // In case a third-party we will add an artifact\n else {\n final DbArtifact dbTarget = repoHandler.getArtifact(dependency.getTarget());\n if(dbTarget == null){\n LOG.error(\"Got missing artifact: \" + dependency.getTarget());\n return;\n }\n\n if(!graph.isTreated(graph.getId(dbTarget))){\n final ModelMapper modelMapper = new ModelMapper(repoHandler);\n final Artifact target = modelMapper.getArtifact(dbTarget);\n final String targetElementId = graph.getId(target);\n graph.addElement(targetElementId, target.getVersion(), false);\n graph.addDependency(parentId, targetElementId, dependency.getScope());\n }\n }\n }",
"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 }"
] |
Returns requested content types or default content type if none found.
@return Requested content types or default content type if none found. | [
"@Override\n\tpublic List<String> contentTypes() {\n\t\tList<String> contentTypes = null;\n\t\tfinal HttpServletRequest request = getHttpRequest();\n\n\t\tif (favorParameterOverAcceptHeader) {\n\t\t\tcontentTypes = getFavoredParameterValueAsList(request);\n\t\t} else {\n\t\t\tcontentTypes = getAcceptHeaderValues(request);\n\t\t}\n\n\t\tif (isEmpty(contentTypes)) {\n\t\t\tlogger.debug(\"Setting content types to default: {}.\", DEFAULT_SUPPORTED_CONTENT_TYPES);\n\n\t\t\tcontentTypes = DEFAULT_SUPPORTED_CONTENT_TYPES;\n\t\t}\n\n\t\treturn unmodifiableList(contentTypes);\n\t}"
] | [
"public void fireCalendarWrittenEvent(ProjectCalendar calendar)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.calendarWritten(calendar);\n }\n }\n }",
"public static final String printTime(Date value)\n {\n return (value == null ? null : TIME_FORMAT.get().format(value));\n }",
"private void registerInterceptor(Node source,\n String beanName,\n BeanDefinitionRegistry registry) {\n List<String> methodList = buildMethodList(source);\n\n BeanDefinitionBuilder initializer =\n BeanDefinitionBuilder.rootBeanDefinition(SingleServiceWrapperInterceptor.class);\n initializer.addPropertyValue(\"methods\", methodList);\n\n String perfMonitorName = beanName + \"PerformanceMonitor\";\n initializer.addPropertyReference(\"serviceWrapper\", perfMonitorName);\n\n String interceptorName = beanName + \"PerformanceMonitorInterceptor\";\n registry.registerBeanDefinition(interceptorName, initializer.getBeanDefinition());\n }",
"public static linkset[] get(nitro_service service) throws Exception{\n\t\tlinkset obj = new linkset();\n\t\tlinkset[] response = (linkset[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"private EndpointOverride getEndpointOverrideFromResultSet(ResultSet results) throws Exception {\n EndpointOverride endpoint = new EndpointOverride();\n endpoint.setPathId(results.getInt(Constants.GENERIC_ID));\n endpoint.setPath(results.getString(Constants.PATH_PROFILE_ACTUAL_PATH));\n endpoint.setBodyFilter(results.getString(Constants.PATH_PROFILE_BODY_FILTER));\n endpoint.setPathName(results.getString(Constants.PATH_PROFILE_PATHNAME));\n endpoint.setContentType(results.getString(Constants.PATH_PROFILE_CONTENT_TYPE));\n endpoint.setRequestType(results.getInt(Constants.PATH_PROFILE_REQUEST_TYPE));\n endpoint.setRepeatNumber(results.getInt(Constants.REQUEST_RESPONSE_REPEAT_NUMBER));\n endpoint.setGroupIds(results.getString(Constants.PATH_PROFILE_GROUP_IDS));\n endpoint.setRequestEnabled(results.getBoolean(Constants.REQUEST_RESPONSE_REQUEST_ENABLED));\n endpoint.setResponseEnabled(results.getBoolean(Constants.REQUEST_RESPONSE_RESPONSE_ENABLED));\n endpoint.setClientUUID(results.getString(Constants.GENERIC_CLIENT_UUID));\n endpoint.setProfileId(results.getInt(Constants.GENERIC_PROFILE_ID));\n endpoint.setGlobal(results.getBoolean(Constants.PATH_PROFILE_GLOBAL));\n return endpoint;\n }",
"public static String implodeObjects(Iterable<?> objects) {\n\t\tStringBuilder builder = new StringBuilder();\n\t\tboolean first = true;\n\t\tfor (Object o : objects) {\n\t\t\tif (first) {\n\t\t\t\tfirst = false;\n\t\t\t} else {\n\t\t\t\tbuilder.append(\"|\");\n\t\t\t}\n\t\t\tbuilder.append(o.toString());\n\t\t}\n\t\treturn builder.toString();\n\t}",
"public static <T> T splitEachLine(InputStream stream, String regex, String charset, @ClosureParams(value=FromString.class,options=\"List<String>\") Closure<T> closure) throws IOException {\n return splitEachLine(new BufferedReader(new InputStreamReader(stream, charset)), regex, closure);\n }",
"public GeoPolygon addHoles(List<List<GeoPoint>> holes) {\n\t\tContracts.assertNotNull( holes, \"holes\" );\n\t\tthis.rings.addAll( holes );\n\t\treturn this;\n\t}",
"public static <T> List<T> flatten(Collection<List<T>> nestedList) {\r\n List<T> result = new ArrayList<T>();\r\n for (List<T> list : nestedList) {\r\n result.addAll(list);\r\n }\r\n return result;\r\n }"
] |
Send a request to another handler internal to the server, getting back the response body and response code.
@param request request to send to another handler.
@return {@link InternalHttpResponse} containing the response code and body. | [
"protected InternalHttpResponse sendInternalRequest(HttpRequest request) {\n InternalHttpResponder responder = new InternalHttpResponder();\n httpResourceHandler.handle(request, responder);\n return responder.getResponse();\n }"
] | [
"@Override public void process(MPPReader reader, ProjectFile file, DirectoryEntry root) throws MPXJException, IOException\n {\n try\n {\n populateMemberData(reader, file, root);\n processProjectProperties();\n\n if (!reader.getReadPropertiesOnly())\n {\n processSubProjectData();\n processGraphicalIndicators();\n processCustomValueLists();\n processCalendarData();\n processResourceData();\n processTaskData();\n processConstraintData();\n processAssignmentData();\n postProcessTasks();\n\n if (reader.getReadPresentationData())\n {\n processViewPropertyData();\n processTableData();\n processViewData();\n processFilterData();\n processGroupData();\n processSavedViewState();\n }\n }\n }\n\n finally\n {\n clearMemberData();\n }\n }",
"public void updateEmbeddedColumn(GraphDatabaseService executionEngine, Object[] keyValues, String embeddedColumn, Object value) {\n\t\tString query = getUpdateEmbeddedColumnQuery( keyValues, embeddedColumn );\n\t\tMap<String, Object> params = params( ArrayHelper.concat( keyValues, value, value ) );\n\t\texecutionEngine.execute( query, params );\n\t}",
"void recordPreparedOperation(final TransactionalProtocolClient.PreparedOperation<ServerTaskExecutor.ServerOperation> preparedOperation) {\n recordPreparedTask(new ServerTaskExecutor.ServerPreparedResponse(preparedOperation));\n }",
"private static boolean validateEndRecord(File file, FileChannel channel, long startEndRecord, long endSig) throws IOException {\n\n try {\n channel.position(startEndRecord);\n\n final ByteBuffer endDirHeader = getByteBuffer(ENDLEN);\n read(endDirHeader, channel);\n if (endDirHeader.limit() < ENDLEN) {\n // Couldn't read the full end of central directory record header\n return false;\n } else if (getUnsignedInt(endDirHeader, 0) != endSig) {\n return false;\n }\n\n long pos = getUnsignedInt(endDirHeader, END_CENSTART);\n // TODO deal with Zip64\n if (pos == ZIP64_MARKER) {\n return false;\n }\n\n ByteBuffer cdfhBuffer = getByteBuffer(CENLEN);\n read(cdfhBuffer, channel, pos);\n long header = getUnsignedInt(cdfhBuffer, 0);\n if (header == CENSIG) {\n long firstLoc = getUnsignedInt(cdfhBuffer, CEN_LOC_OFFSET);\n long firstSize = getUnsignedInt(cdfhBuffer, CENSIZ);\n if (firstLoc == 0) {\n // normal case -- first bytes are the first local file\n if (!validateLocalFileRecord(channel, 0, firstSize)) {\n return false;\n }\n } else {\n // confirm that firstLoc is indeed the first local file\n long fileFirstLoc = scanForLocSig(channel);\n if (firstLoc != fileFirstLoc) {\n if (fileFirstLoc == 0) {\n return false;\n } else {\n // scanForLocSig() found a LOCSIG, but not at position zero and not\n // at the expected position.\n // With a file like this, we can't tell if we're in a nested zip\n // or we're in an outer zip and had the bad luck to find random bytes\n // that look like LOCSIG.\n return false;\n }\n }\n }\n\n // At this point, endDirHeader points to the correct end of central dir record.\n // Just need to validate the record is complete, including any comment\n int commentLen = getUnsignedShort(endDirHeader, END_COMMENTLEN);\n long commentEnd = startEndRecord + ENDLEN + commentLen;\n return commentEnd <= channel.size();\n }\n\n return false;\n } catch (EOFException eof) {\n // pos or firstLoc weren't really positions and moved us to an invalid location\n return false;\n }\n }",
"public static void setBackgroundDrawable(View view, Drawable drawable) {\n if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {\n view.setBackgroundDrawable(drawable);\n } else {\n view.setBackground(drawable);\n }\n }",
"boolean undoChanges() {\n final State state = stateUpdater.getAndSet(this, State.ROLLBACK_ONLY);\n if (state == State.COMPLETED || state == State.ROLLBACK_ONLY) {\n // Was actually completed already\n return false;\n }\n PatchingTaskContext.Mode currentMode = this.mode;\n mode = PatchingTaskContext.Mode.UNDO;\n final PatchContentLoader loader = PatchContentLoader.create(miscBackup, null, null);\n // Undo changes for the identity\n undoChanges(identityEntry, loader);\n // TODO maybe check if we need to do something for the layers too !?\n if (state == State.INVALIDATE || currentMode == PatchingTaskContext.Mode.ROLLBACK) {\n // For apply the state needs to be invalidate\n // For rollback the files are invalidated as part of the tasks\n final PatchingTaskContext.Mode mode = currentMode == PatchingTaskContext.Mode.APPLY ? PatchingTaskContext.Mode.ROLLBACK : PatchingTaskContext.Mode.APPLY;\n for (final File file : moduleInvalidations) {\n try {\n PatchModuleInvalidationUtils.processFile(this, file, mode);\n } catch (Exception e) {\n PatchLogger.ROOT_LOGGER.debugf(e, \"failed to restore state for %s\", file);\n }\n }\n if(!modulesToReenable.isEmpty()) {\n for (final File file : modulesToReenable) {\n try {\n PatchModuleInvalidationUtils.processFile(this, file, PatchingTaskContext.Mode.APPLY);\n } catch (Exception e) {\n PatchLogger.ROOT_LOGGER.debugf(e, \"failed to restore state for %s\", file);\n }\n }\n }\n if(!modulesToDisable.isEmpty()) {\n for (final File file : modulesToDisable) {\n try {\n PatchModuleInvalidationUtils.processFile(this, file, PatchingTaskContext.Mode.ROLLBACK);\n } catch (Exception e) {\n PatchLogger.ROOT_LOGGER.debugf(e, \"failed to restore state for %s\", file);\n }\n }\n }\n }\n return true;\n }",
"public PatchingResult rollbackLast(final ContentVerificationPolicy contentPolicy, final boolean resetConfiguration, InstallationManager.InstallationModification modification) throws PatchingException {\n\n // Determine the patch id to rollback\n String patchId;\n final List<String> oneOffs = modification.getPatchIDs();\n if (oneOffs.isEmpty()) {\n patchId = modification.getCumulativePatchID();\n if (patchId == null || Constants.NOT_PATCHED.equals(patchId)) {\n throw PatchLogger.ROOT_LOGGER.noPatchesApplied();\n }\n } else {\n patchId = oneOffs.get(0);//oneOffs.get(oneOffs.size() - 1);\n }\n return rollbackPatch(patchId, contentPolicy, false, resetConfiguration, modification);\n }",
"public static String getParentId(String digest, String host) throws IOException {\n DockerClient dockerClient = null;\n try {\n dockerClient = getDockerClient(host);\n return dockerClient.inspectImageCmd(digest).exec().getParent();\n } finally {\n closeQuietly(dockerClient);\n }\n }",
"public static <T> void callInitializers(T instance, CreationalContext<T> creationalContext, BeanManagerImpl manager,\n Iterable<? extends MethodInjectionPoint<?, ?>> initializerMethods) {\n for (MethodInjectionPoint<?, ?> initializer : initializerMethods) {\n initializer.invoke(instance, null, manager, creationalContext, CreationException.class);\n }\n }"
] |
For use on a slave HC to get all the server groups used by the host
@param hostResource the host resource
@return the server configs on this host | [
"public Set<ServerConfigInfo> getServerConfigsOnSlave(Resource hostResource){\n Set<ServerConfigInfo> groups = new HashSet<>();\n for (ResourceEntry entry : hostResource.getChildren(SERVER_CONFIG)) {\n groups.add(new ServerConfigInfoImpl(entry.getModel()));\n }\n return groups;\n }"
] | [
"public static double Y(int n, double x) {\r\n double by, bym, byp, tox;\r\n\r\n if (n == 0) return Y0(x);\r\n if (n == 1) return Y(x);\r\n\r\n tox = 2.0 / x;\r\n by = Y(x);\r\n bym = Y0(x);\r\n for (int j = 1; j < n; j++) {\r\n byp = j * tox * by - bym;\r\n bym = by;\r\n by = byp;\r\n }\r\n return by;\r\n }",
"public static LBuffer loadFrom(File file) throws IOException {\n FileChannel fin = new FileInputStream(file).getChannel();\n long fileSize = fin.size();\n if (fileSize > Integer.MAX_VALUE)\n throw new IllegalArgumentException(\"Cannot load from file more than 2GB: \" + file);\n LBuffer b = new LBuffer((int) fileSize);\n long pos = 0L;\n WritableChannelWrap ch = new WritableChannelWrap(b);\n while (pos < fileSize) {\n pos += fin.transferTo(0, fileSize, ch);\n }\n return b;\n }",
"private LoginContext getClientLoginContext() throws LoginException {\n Configuration config = new Configuration() {\n @Override\n public AppConfigurationEntry[] getAppConfigurationEntry(String name) {\n Map<String, String> options = new HashMap<String, String>();\n options.put(\"multi-threaded\", \"true\");\n options.put(\"restore-login-identity\", \"true\");\n\n AppConfigurationEntry clmEntry = new AppConfigurationEntry(ClientLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, options);\n return new AppConfigurationEntry[] { clmEntry };\n }\n };\n return getLoginContext(config);\n }",
"public boolean computeDirect( DMatrixRMaj A ) {\n\n initPower(A);\n\n boolean converged = false;\n\n for( int i = 0; i < maxIterations && !converged; i++ ) {\n// q0.print();\n \n CommonOps_DDRM.mult(A,q0,q1);\n double s = NormOps_DDRM.normPInf(q1);\n CommonOps_DDRM.divide(q1,s,q2);\n\n converged = checkConverged(A);\n }\n\n return converged;\n }",
"private void readAssignments(Project plannerProject)\n {\n Allocations allocations = plannerProject.getAllocations();\n List<Allocation> allocationList = allocations.getAllocation();\n Set<Task> tasksWithAssignments = new HashSet<Task>();\n\n for (Allocation allocation : allocationList)\n {\n Integer taskID = getInteger(allocation.getTaskId());\n Integer resourceID = getInteger(allocation.getResourceId());\n Integer units = getInteger(allocation.getUnits());\n\n Task task = m_projectFile.getTaskByUniqueID(taskID);\n Resource resource = m_projectFile.getResourceByUniqueID(resourceID);\n\n if (task != null && resource != null)\n {\n Duration work = task.getWork();\n int percentComplete = NumberHelper.getInt(task.getPercentageComplete());\n\n ResourceAssignment assignment = task.addResourceAssignment(resource);\n assignment.setUnits(units);\n assignment.setWork(work);\n\n if (percentComplete != 0)\n {\n Duration actualWork = Duration.getInstance((work.getDuration() * percentComplete) / 100, work.getUnits());\n assignment.setActualWork(actualWork);\n assignment.setRemainingWork(Duration.getInstance(work.getDuration() - actualWork.getDuration(), work.getUnits()));\n }\n else\n {\n assignment.setRemainingWork(work);\n }\n\n assignment.setStart(task.getStart());\n assignment.setFinish(task.getFinish());\n\n tasksWithAssignments.add(task);\n\n m_eventManager.fireAssignmentReadEvent(assignment);\n }\n }\n\n //\n // Adjust work per assignment for tasks with multiple assignments\n //\n for (Task task : tasksWithAssignments)\n {\n List<ResourceAssignment> assignments = task.getResourceAssignments();\n if (assignments.size() > 1)\n {\n double maxUnits = 0;\n for (ResourceAssignment assignment : assignments)\n {\n maxUnits += assignment.getUnits().doubleValue();\n }\n\n for (ResourceAssignment assignment : assignments)\n {\n Duration work = assignment.getWork();\n double factor = assignment.getUnits().doubleValue() / maxUnits;\n\n work = Duration.getInstance(work.getDuration() * factor, work.getUnits());\n assignment.setWork(work);\n Duration actualWork = assignment.getActualWork();\n if (actualWork != null)\n {\n actualWork = Duration.getInstance(actualWork.getDuration() * factor, actualWork.getUnits());\n assignment.setActualWork(actualWork);\n }\n\n Duration remainingWork = assignment.getRemainingWork();\n if (remainingWork != null)\n {\n remainingWork = Duration.getInstance(remainingWork.getDuration() * factor, remainingWork.getUnits());\n assignment.setRemainingWork(remainingWork);\n }\n }\n }\n }\n }",
"@Pure\n\tpublic static <P1, P2> Procedure1<P2> curry(final Procedure2<? super P1, ? super P2> procedure, final P1 argument) {\n\t\tif (procedure == null)\n\t\t\tthrow new NullPointerException(\"procedure\");\n\t\treturn new Procedure1<P2>() {\n\t\t\t@Override\n\t\t\tpublic void apply(P2 p) {\n\t\t\t\tprocedure.apply(argument, p);\n\t\t\t}\n\t\t};\n\t}",
"@Override public void onBindViewHolder(RendererViewHolder viewHolder, int position) {\n T content = getItem(position);\n Renderer<T> renderer = viewHolder.getRenderer();\n if (renderer == null) {\n throw new NullRendererBuiltException(\"RendererBuilder have to return a not null renderer\");\n }\n renderer.setContent(content);\n updateRendererExtraValues(content, renderer, position);\n renderer.render();\n }",
"public static Iterable<BoxRetentionPolicy.Info> getAll(\r\n String name, String type, String userID, int limit, final BoxAPIConnection api, String ... fields) {\r\n QueryStringBuilder queryString = new QueryStringBuilder();\r\n if (name != null) {\r\n queryString.appendParam(\"policy_name\", name);\r\n }\r\n if (type != null) {\r\n queryString.appendParam(\"policy_type\", type);\r\n }\r\n if (userID != null) {\r\n queryString.appendParam(\"created_by_user_id\", userID);\r\n }\r\n if (fields.length > 0) {\r\n queryString.appendParam(\"fields\", fields);\r\n }\r\n URL url = RETENTION_POLICIES_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), queryString.toString());\r\n return new BoxResourceIterable<BoxRetentionPolicy.Info>(api, url, limit) {\r\n\r\n @Override\r\n protected BoxRetentionPolicy.Info factory(JsonObject jsonObject) {\r\n BoxRetentionPolicy policy = new BoxRetentionPolicy(api, jsonObject.get(\"id\").asString());\r\n return policy.new Info(jsonObject);\r\n }\r\n\r\n };\r\n }",
"public boolean classifyDocumentStdin(DocumentReaderAndWriter<IN> readerWriter)\r\n throws IOException\r\n {\r\n BufferedReader is = new BufferedReader(new InputStreamReader(System.in, flags.inputEncoding));\r\n String line;\r\n String text = \"\";\r\n String eol = \"\\n\";\r\n String sentence = \"<s>\";\r\n int blankLines = 0;\r\n while ((line = is.readLine()) != null) {\r\n if (line.trim().equals(\"\")) {\r\n \t ++blankLines;\r\n \t if (blankLines > 3) {\r\n \t\t return false;\r\n \t } else if (blankLines > 2) {\r\n\t\t\t ObjectBank<List<IN>> documents = makeObjectBankFromString(text, readerWriter);\r\n\t \t classifyAndWriteAnswers(documents, readerWriter);\r\n \t\t text = \"\";\r\n \t } else {\r\n \t\t text += sentence + eol;\r\n \t }\r\n } else {\r\n \t text += line + eol;\r\n \t blankLines = 0;\r\n }\r\n }\r\n // Classify last document before input stream end\r\n if (text.trim() != \"\") {\r\n ObjectBank<List<IN>> documents = makeObjectBankFromString(text, readerWriter);\r\n \t classifyAndWriteAnswers(documents, readerWriter);\r\n }\r\n return (line == null); // reached eol\r\n }"
] |
Determines whether the boolean value of the given string value.
@param value The value
@param defaultValue The boolean value to use if the string value is neither 'true' nor 'false'
@return The boolean value of the string | [
"public static boolean toBoolean(String value, boolean defaultValue)\r\n {\r\n return \"true\".equals(value) ? true : (\"false\".equals(value) ? false : defaultValue);\r\n }"
] | [
"public ModelNode buildExecutableRequest(CommandContext ctx) throws Exception {\n try {\n for (FailureDescProvider h : providers) {\n effectiveProviders.add(h);\n }\n // In case some key-store needs to be persisted\n for (String ks : ksToStore) {\n composite.get(Util.STEPS).add(ElytronUtil.storeKeyStore(ctx, ks));\n effectiveProviders.add(new FailureDescProvider() {\n @Override\n public String stepFailedDescription() {\n return \"Storing the key-store \" + ksToStore;\n }\n });\n }\n // Final steps\n for (int i = 0; i < finalSteps.size(); i++) {\n composite.get(Util.STEPS).add(finalSteps.get(i));\n effectiveProviders.add(finalProviders.get(i));\n }\n return composite;\n } catch (Exception ex) {\n try {\n failureOccured(ctx, null);\n } catch (Exception ex2) {\n ex.addSuppressed(ex2);\n }\n throw ex;\n }\n }",
"public DynamicReportBuilder addStyle(Style style) throws DJBuilderException {\n if (style.getName() == null) {\n throw new DJBuilderException(\"Invalid style. The style must have a name\");\n }\n\n report.addStyle(style);\n\n return this;\n }",
"@SuppressWarnings(\"rawtypes\")\n\tprivate MailInboundChannelAdapterSpec getImapFlowBuilder(URLName urlName) {\n\t\treturn Mail.imapInboundAdapter(urlName.toString())\n\t\t\t\t.shouldMarkMessagesAsRead(this.properties.isMarkAsRead());\n\t}",
"public ILog getOrCreateLog(String topic, int partition) throws IOException {\n final int configPartitionNumber = getPartition(topic);\n if (partition >= configPartitionNumber) {\n throw new IOException(\"partition is bigger than the number of configuration: \" + configPartitionNumber);\n }\n boolean hasNewTopic = false;\n Pool<Integer, Log> parts = getLogPool(topic, partition);\n if (parts == null) {\n Pool<Integer, Log> found = logs.putIfNotExists(topic, new Pool<Integer, Log>());\n if (found == null) {\n hasNewTopic = true;\n }\n parts = logs.get(topic);\n }\n //\n Log log = parts.get(partition);\n if (log == null) {\n log = createLog(topic, partition);\n Log found = parts.putIfNotExists(partition, log);\n if (found != null) {\n Closer.closeQuietly(log, logger);\n log = found;\n } else {\n logger.info(format(\"Created log for [%s-%d], now create other logs if necessary\", topic, partition));\n final int configPartitions = getPartition(topic);\n for (int i = 0; i < configPartitions; i++) {\n getOrCreateLog(topic, i);\n }\n }\n }\n if (hasNewTopic && config.getEnableZookeeper()) {\n topicRegisterTasks.add(new TopicTask(TopicTask.TaskType.CREATE, topic));\n }\n return log;\n }",
"public static base_response add(nitro_service client, systemuser resource) throws Exception {\n\t\tsystemuser addresource = new systemuser();\n\t\taddresource.username = resource.username;\n\t\taddresource.password = resource.password;\n\t\taddresource.externalauth = resource.externalauth;\n\t\taddresource.promptstring = resource.promptstring;\n\t\taddresource.timeout = resource.timeout;\n\t\treturn addresource.add_resource(client);\n\t}",
"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 }",
"public static void unzip(Path zip, Path target) throws IOException {\n try (final ZipFile zipFile = new ZipFile(zip.toFile())){\n unzip(zipFile, target);\n }\n }",
"private static EndpointReferenceType createEPR(Server server, String address, SLProperties props) {\n EndpointReferenceType sourceEPR = server.getEndpoint().getEndpointInfo().getTarget();\n EndpointReferenceType targetEPR = WSAEndpointReferenceUtils.duplicate(sourceEPR);\n WSAEndpointReferenceUtils.setAddress(targetEPR, address);\n\n if (props != null) {\n addProperties(targetEPR, props);\n }\n return targetEPR;\n }",
"public static PredicateExpression nin(Object... rhs) {\n PredicateExpression ex = new PredicateExpression(\"$nin\", rhs);\n if (rhs.length == 1) {\n ex.single = true;\n }\n return ex;\n }"
] |
Gets whether the given server can be updated.
@param server the id of the server. Cannot be <code>null</code>
@return <code>true</code> if the server can be updated; <code>false</code>
if the update should be cancelled
@throws IllegalStateException if this policy is not expecting a request
to update the given server | [
"public boolean canUpdateServer(ServerIdentity server) {\n if (!serverGroupName.equals(server.getServerGroupName()) || !servers.contains(server)) {\n throw DomainControllerLogger.HOST_CONTROLLER_LOGGER.unknownServer(server);\n }\n\n if (!parent.canChildProceed())\n return false;\n\n synchronized (this) {\n return failureCount <= maxFailed;\n }\n }"
] | [
"public Triple<Double, Integer, Integer> getAccuracyInfo()\r\n {\r\n int totalCorrect = tokensCorrect;\r\n int totalWrong = tokensCount - tokensCorrect;\r\n return new Triple<Double, Integer, Integer>((((double) totalCorrect) / tokensCount),\r\n totalCorrect, totalWrong);\r\n }",
"public RgbaColor adjustHue(float degrees) {\n float[] HSL = convertToHsl();\n HSL[0] = hueCheck(HSL[0] + degrees); // ensure [0-360)\n return RgbaColor.fromHsl(HSL);\n }",
"private boolean containsCollectionAndMapsToDifferentTable(CollectionDescriptorDef origCollDef, TableDef origTableDef, ClassDescriptorDef classDef)\r\n {\r\n if (classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, true) &&\r\n !origTableDef.getName().equals(classDef.getProperty(PropertyHelper.OJB_PROPERTY_TABLE)))\r\n {\r\n CollectionDescriptorDef curCollDef = classDef.getCollection(origCollDef.getName());\r\n\r\n if ((curCollDef != null) &&\r\n !curCollDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))\r\n {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }",
"private void processQueue()\r\n {\r\n CacheEntry sv;\r\n while((sv = (CacheEntry) queue.poll()) != null)\r\n {\r\n sessionCache.remove(sv.oid);\r\n }\r\n }",
"public static double Correlation(double[] p, double[] q) {\n\n double x = 0;\n double y = 0;\n\n for (int i = 0; i < p.length; i++) {\n x += -p[i];\n y += -q[i];\n }\n\n x /= p.length;\n y /= q.length;\n\n double num = 0;\n double den1 = 0;\n double den2 = 0;\n for (int i = 0; i < p.length; i++) {\n num += (p[i] + x) * (q[i] + y);\n\n den1 += Math.abs(Math.pow(p[i] + x, 2));\n den2 += Math.abs(Math.pow(q[i] + x, 2));\n }\n\n return 1 - (num / (Math.sqrt(den1) * Math.sqrt(den2)));\n\n }",
"public AbstractGraph getModuleGraph(final String moduleId) {\n final ModuleHandler moduleHandler = new ModuleHandler(repoHandler);\n final DbModule module = moduleHandler.getModule(moduleId);\n final DbOrganization organization = moduleHandler.getOrganization(module);\n\n filters.setCorporateFilter(new CorporateFilter(organization));\n\n final AbstractGraph graph = new ModuleGraph();\n addModuleToGraph(module, graph, 0);\n\n return graph;\n }",
"private <T> void requestAsync(ClientRequest<T> delegate,\n NonblockingStoreCallback callback,\n long timeoutMs,\n String operationName) {\n pool.submitAsync(this.destination, delegate, callback, timeoutMs, operationName);\n }",
"public void displayUseCases()\r\n {\r\n System.out.println();\r\n for (int i = 0; i < useCases.size(); i++)\r\n {\r\n System.out.println(\"[\" + i + \"] \" + ((UseCase) useCases.get(i)).getDescription());\r\n }\r\n }",
"public void writeStartList(String name) throws IOException\n {\n writeComma();\n writeNewLineIndent();\n writeName(name);\n writeNewLineIndent();\n m_writer.write(\"[\");\n increaseIndent();\n }"
] |
Gets the value of the project property.
<p>
This accessor method returns a reference to the live list,
not a snapshot. Therefore any modification you make to the
returned list will be present inside the JAXB object.
This is why there is not a <CODE>set</CODE> method for the project property.
<p>
For example, to add a new item, do as follows:
<pre>
getProject().add(newItem);
</pre>
<p>
Objects of the following type(s) are allowed in the list
{@link ProjectListType.Project } | [
"public List<ProjectListType.Project> getProject()\n {\n if (project == null)\n {\n project = new ArrayList<ProjectListType.Project>();\n }\n return this.project;\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 static int findNext(boolean reverse, int pos) {\n boolean backwards = IS_BACKWARDS_CHECKBOX.isSelected();\n backwards = backwards ? !reverse : reverse;\n\n String pattern = (String) FIND_FIELD.getSelectedItem();\n if (pattern != null && pattern.length() > 0) {\n try {\n Document doc = textComponent.getDocument();\n doc.getText(0, doc.getLength(), SEGMENT);\n }\n catch (Exception e) {\n // should NEVER reach here\n e.printStackTrace();\n }\n\n pos += textComponent.getSelectedText() == null ?\n (backwards ? -1 : 1) : 0;\n\n char first = backwards ?\n pattern.charAt(pattern.length() - 1) : pattern.charAt(0);\n char oppFirst = Character.isUpperCase(first) ?\n Character.toLowerCase(first) : Character.toUpperCase(first);\n int start = pos;\n boolean wrapped = WRAP_SEARCH_CHECKBOX.isSelected();\n int end = backwards ? 0 : SEGMENT.getEndIndex();\n pos += backwards ? -1 : 1;\n\n int length = textComponent.getDocument().getLength();\n if (pos > length) {\n pos = wrapped ? 0 : length;\n }\n\n boolean found = false;\n while (!found && (backwards ? pos > end : pos < end)) {\n found = !MATCH_CASE_CHECKBOX.isSelected() && SEGMENT.array[pos] == oppFirst;\n found = found ? found : SEGMENT.array[pos] == first;\n\n if (found) {\n pos += backwards ? -(pattern.length() - 1) : 0;\n for (int i = 0; found && i < pattern.length(); i++) {\n char c = pattern.charAt(i);\n found = SEGMENT.array[pos + i] == c;\n if (!MATCH_CASE_CHECKBOX.isSelected() && !found) {\n c = Character.isUpperCase(c) ?\n Character.toLowerCase(c) :\n Character.toUpperCase(c);\n found = SEGMENT.array[pos + i] == c;\n }\n }\n }\n\n if (!found) {\n pos += backwards ? -1 : 1;\n\n if (pos == end && wrapped) {\n pos = backwards ? SEGMENT.getEndIndex() : 0;\n end = start;\n wrapped = false;\n }\n }\n }\n pos = found ? pos : -1;\n }\n\n return pos;\n }",
"public static base_response unset(nitro_service client, nsacl6 resource, String[] args) throws Exception{\n\t\tnsacl6 unsetresource = new nsacl6();\n\t\tunsetresource.acl6name = resource.acl6name;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public static String readFileContentToString(String filePath)\n throws IOException {\n String content = \"\";\n content = Files.toString(new File(filePath), Charsets.UTF_8);\n return content;\n }",
"private Path getTempDir() {\n if (this.tempDir == null) {\n if (this.dir != null) {\n this.tempDir = dir;\n } else {\n this.tempDir = getProject().getBaseDir().toPath();\n }\n }\n return tempDir;\n }",
"public void setPath(int pathId, String path) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + Constants.PATH_PROFILE_ACTUAL_PATH + \" = ? \" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, path);\n statement.setInt(2, pathId);\n statement.executeUpdate();\n statement.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }",
"@RequestMapping(value = \"api/servergroup\", method = RequestMethod.POST)\n public\n @ResponseBody\n ServerGroup createServerGroup(Model model,\n @RequestParam(value = \"name\") String name,\n @RequestParam(value = \"profileId\", required = false) Integer profileId,\n @RequestParam(value = \"profileIdentifier\", required = false) String profileIdentifier) throws Exception {\n if (profileId == null && profileIdentifier == null) {\n throw new Exception(\"profileId required\");\n }\n if (profileId == null) {\n profileId = ProfileService.getInstance().getIdFromName(profileIdentifier);\n }\n int groupId = ServerRedirectService.getInstance().addServerGroup(name, profileId);\n return ServerRedirectService.getInstance().getServerGroup(groupId, profileId);\n }",
"public static void convert(DMatrixD1 input , ZMatrixD1 output ) {\n if( input.numCols != output.numCols || input.numRows != output.numRows ) {\n throw new IllegalArgumentException(\"The matrices are not all the same dimension.\");\n }\n\n Arrays.fill(output.data, 0, output.getDataLength(), 0);\n\n final int length = output.getDataLength();\n\n for( int i = 0; i < length; i += 2 ) {\n output.data[i] = input.data[i/2];\n }\n }",
"public static sslcipher_individualcipher_binding[] get_filtered(nitro_service service, String ciphergroupname, filtervalue[] filter) throws Exception{\n\t\tsslcipher_individualcipher_binding obj = new sslcipher_individualcipher_binding();\n\t\tobj.set_ciphergroupname(ciphergroupname);\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tsslcipher_individualcipher_binding[] response = (sslcipher_individualcipher_binding[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}"
] |
Use this API to delete nssimpleacl. | [
"public static base_response delete(nitro_service client, nssimpleacl resource) throws Exception {\n\t\tnssimpleacl deleteresource = new nssimpleacl();\n\t\tdeleteresource.aclname = resource.aclname;\n\t\treturn deleteresource.delete_resource(client);\n\t}"
] | [
"public static String getModuleVersion(final String moduleId) {\n final int splitter = moduleId.lastIndexOf(':');\n if(splitter == -1){\n return moduleId;\n }\n return moduleId.substring(splitter+1);\n }",
"public static NodeList evaluateXpathExpression(Document dom, String xpathExpr)\n\t\t\tthrows XPathExpressionException {\n\t\tXPathFactory factory = XPathFactory.newInstance();\n\t\tXPath xpath = factory.newXPath();\n\t\tXPathExpression expr = xpath.compile(xpathExpr);\n\t\tObject result = expr.evaluate(dom, XPathConstants.NODESET);\n\t\treturn (NodeList) result;\n\t}",
"private static double threePointsAngle(Point vertex, Point A, Point B) {\n double b = pointsDistance(vertex, A);\n double c = pointsDistance(A, B);\n double a = pointsDistance(B, vertex);\n\n return Math.toDegrees(Math.acos((a * a + b * b - c * c) / (2 * a * b)));\n\n }",
"public void setVariable(String name, Object value) {\n if (variables == null)\n variables = new LinkedHashMap();\n variables.put(name, value);\n }",
"public String[] getAttributeNames()\r\n {\r\n Set keys = (attributeMap == null ? new HashSet() : attributeMap.keySet());\r\n String[] result = new String[keys.size()];\r\n\r\n keys.toArray(result);\r\n return result;\r\n }",
"private void checkAnonymous(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n String access = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_ACCESS);\r\n\r\n if (!\"anonymous\".equals(access))\r\n {\r\n throw new ConstraintException(\"The access property of the field \"+fieldDef.getName()+\" defined in class \"+fieldDef.getOwner().getName()+\" cannot be changed\");\r\n }\r\n\r\n if ((fieldDef.getName() == null) || (fieldDef.getName().length() == 0))\r\n {\r\n throw new ConstraintException(\"An anonymous field defined in class \"+fieldDef.getOwner().getName()+\" has no name\");\r\n }\r\n }",
"List<CmsFavoriteEntry> getEntries() {\n\n List<CmsFavoriteEntry> result = new ArrayList<>();\n for (I_CmsEditableGroupRow row : m_group.getRows()) {\n CmsFavoriteEntry entry = ((CmsFavInfo)row).getEntry();\n result.add(entry);\n }\n return result;\n }",
"public VideoCollection generate(final int videoCount) {\n List<Video> videos = new LinkedList<Video>();\n for (int i = 0; i < videoCount; i++) {\n Video video = generateRandomVideo();\n videos.add(video);\n }\n return new VideoCollection(videos);\n }",
"public void performImplicitSingleStep(double scale , double lambda , boolean byAngle) {\n createBulge(x1,lambda,scale,byAngle);\n\n for( int i = x1; i < x2-1 && bulge != 0.0; i++ ) {\n removeBulgeLeft(i,true);\n if( bulge == 0 )\n break;\n removeBulgeRight(i);\n }\n\n if( bulge != 0 )\n removeBulgeLeft(x2-1,false);\n\n incrementSteps();\n }"
] |
Generic string joining function.
@param strings Strings to be joined
@param fixCase does it need to fix word case
@param withChar char to join strings with.
@return joined-string | [
"public static String joinStrings(List<String> strings, boolean fixCase, char withChar) {\n if (strings == null || strings.size() == 0) {\n return \"\";\n }\n StringBuilder result = null;\n for (String s : strings) {\n if (fixCase) {\n s = fixCase(s);\n }\n if (result == null) {\n result = new StringBuilder(s);\n } else {\n result.append(withChar);\n result.append(s);\n }\n }\n return result.toString();\n }"
] | [
"private Charset getCharset()\n {\n Charset result = m_charset;\n if (result == null)\n {\n // We default to CP1252 as this seems to be the most common encoding\n result = m_encoding == null ? CharsetHelper.CP1252 : Charset.forName(m_encoding);\n }\n return result;\n }",
"protected String generateCacheKey(\n CmsObject cms,\n String targetSiteRoot,\n String detailPagePart,\n String absoluteLink) {\n\n return cms.getRequestContext().getSiteRoot() + \":\" + targetSiteRoot + \":\" + detailPagePart + absoluteLink;\n }",
"public static GraphTraversal<Vertex, Vertex> addPipeFor(GraphTraversal<Vertex, Vertex> pipeline,\n Class<? extends WindupVertexFrame> clazz)\n {\n pipeline.has(WindupVertexFrame.TYPE_PROP, GraphTypeManager.getTypeValue(clazz));\n return pipeline;\n }",
"public QueryBuilder<T, ID> orderByRaw(String rawSql) {\n\t\taddOrderBy(new OrderBy(rawSql, (ArgumentHolder[]) null));\n\t\treturn this;\n\t}",
"public void writeTo(IIMWriter writer) throws IOException {\r\n\t\tfinal boolean doLog = log != null;\r\n\t\tfor (Iterator<DataSet> i = dataSets.iterator(); i.hasNext();) {\r\n\t\t\tDataSet ds = i.next();\r\n\t\t\twriter.write(ds);\r\n\t\t\tif (doLog) {\r\n\t\t\t\tlog.debug(\"Wrote data set \" + ds);\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"private void populateCalendarException(Record record, ProjectCalendar calendar) throws MPXJException\n {\n Date fromDate = record.getDate(0);\n Date toDate = record.getDate(1);\n boolean working = record.getNumericBoolean(2);\n\n // I have found an example MPX file where a single day exception is expressed with just the start date set.\n // If we find this for we assume that the end date is the same as the start date.\n if (fromDate != null && toDate == null)\n {\n toDate = fromDate;\n }\n\n ProjectCalendarException exception = calendar.addCalendarException(fromDate, toDate);\n if (working)\n {\n addExceptionRange(exception, record.getTime(3), record.getTime(4));\n addExceptionRange(exception, record.getTime(5), record.getTime(6));\n addExceptionRange(exception, record.getTime(7), record.getTime(8));\n }\n }",
"public int scrollToPage(int pageNumber) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"scrollToPage pageNumber = %d mPageCount = %d\",\n pageNumber, mPageCount);\n\n if (mSupportScrollByPage &&\n (mScrollOver || (pageNumber >= 0 && pageNumber <= mPageCount - 1))) {\n scrollToItem(getFirstItemIndexOnPage(pageNumber));\n } else {\n Log.w(TAG, \"Pagination is not enabled!\");\n }\n return mCurrentItemIndex;\n\t}",
"private void calculateMenuItemPosition() {\n\n float itemRadius = (expandedRadius + collapsedRadius) / 2, f;\n RectF area = new RectF(\n center.x - itemRadius,\n center.y - itemRadius,\n center.x + itemRadius,\n center.y + itemRadius);\n Path path = new Path();\n path.addArc(area, (float) fromAngle, (float) (toAngle - fromAngle));\n PathMeasure measure = new PathMeasure(path, false);\n float len = measure.getLength();\n int divisor = getChildCount();\n float divider = len / divisor;\n\n for (int i = 0; i < getChildCount(); i++) {\n float[] coords = new float[2];\n measure.getPosTan(i * divider + divider * .5f, coords, null);\n FilterMenu.Item item = (FilterMenu.Item) getChildAt(i).getTag();\n item.setX((int) coords[0] - item.getView().getMeasuredWidth() / 2);\n item.setY((int) coords[1] - item.getView().getMeasuredHeight() / 2);\n }\n }",
"void forcedUndeployScan() {\n\n if (acquireScanLock()) {\n try {\n ROOT_LOGGER.tracef(\"Performing a post-boot forced undeploy scan for scan directory %s\", deploymentDir.getAbsolutePath());\n ScanContext scanContext = new ScanContext(deploymentOperations);\n\n // Add remove actions to the plan for anything we count as\n // deployed that we didn't find on the scan\n for (Map.Entry<String, DeploymentMarker> missing : scanContext.toRemove.entrySet()) {\n // remove successful deployment and left will be removed\n if (scanContext.registeredDeployments.containsKey(missing.getKey())) {\n scanContext.registeredDeployments.remove(missing.getKey());\n }\n }\n Set<String> scannedDeployments = new HashSet<String>(scanContext.registeredDeployments.keySet());\n scannedDeployments.removeAll(scanContext.persistentDeployments);\n\n List<ScannerTask> scannerTasks = scanContext.scannerTasks;\n for (String toUndeploy : scannedDeployments) {\n scannerTasks.add(new UndeployTask(toUndeploy, deploymentDir, scanContext.scanStartTime, true));\n }\n try {\n executeScannerTasks(scannerTasks, deploymentOperations, true);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n\n ROOT_LOGGER.tracef(\"Forced undeploy scan complete\");\n } catch (Exception e) {\n ROOT_LOGGER.scanException(e, deploymentDir.getAbsolutePath());\n } finally {\n releaseScanLock();\n }\n }\n }"
] |
Adds an option to the JVM arguments to enable JMX connection
@param jvmArgs the JVM args
@return a new list of JVM args | [
"public static List<String> enableJMX(List<String> jvmArgs) {\n final String arg = \"-D\" + OPT_JMX_REMOTE;\n if (jvmArgs.contains(arg))\n return jvmArgs;\n final List<String> cmdLine2 = new ArrayList<>(jvmArgs);\n cmdLine2.add(arg);\n return cmdLine2;\n }"
] | [
"public boolean measureAll(List<Widget> measuredChildren) {\n boolean changed = false;\n for (int i = 0; i < mContainer.size(); ++i) {\n\n if (!isChildMeasured(i)) {\n Widget child = measureChild(i, false);\n if (child != null) {\n if (measuredChildren != null) {\n measuredChildren.add(child);\n }\n changed = true;\n }\n }\n }\n if (changed) {\n postMeasurement();\n }\n return changed;\n }",
"private long getEndTime(ISuite suite, IInvokedMethod method)\n {\n // Find the latest end time for all tests in the suite.\n for (Map.Entry<String, ISuiteResult> entry : suite.getResults().entrySet())\n {\n ITestContext testContext = entry.getValue().getTestContext();\n for (ITestNGMethod m : testContext.getAllTestMethods())\n {\n if (method == m)\n {\n return testContext.getEndDate().getTime();\n }\n }\n // If we can't find a matching test method it must be a configuration method.\n for (ITestNGMethod m : testContext.getPassedConfigurations().getAllMethods())\n {\n if (method == m)\n {\n return testContext.getEndDate().getTime();\n }\n }\n for (ITestNGMethod m : testContext.getFailedConfigurations().getAllMethods())\n {\n if (method == m)\n {\n return testContext.getEndDate().getTime();\n }\n }\n }\n throw new IllegalStateException(\"Could not find matching end time.\");\n }",
"@Override\n protected void updateState(final String name, final InstallationModificationImpl modification, final InstallationModificationImpl.InstallationState state) {\n final PatchableTarget.TargetInfo identityInfo = modification.getModifiedState();\n this.identity = new Identity() {\n @Override\n public String getVersion() {\n return modification.getVersion();\n }\n\n @Override\n public String getName() {\n return name;\n }\n\n @Override\n public TargetInfo loadTargetInfo() throws IOException {\n return identityInfo;\n }\n\n @Override\n public DirectoryStructure getDirectoryStructure() {\n return modification.getDirectoryStructure();\n }\n };\n\n this.allPatches = Collections.unmodifiableList(modification.getAllPatches());\n this.layers.clear();\n for (final Map.Entry<String, MutableTargetImpl> entry : state.getLayers().entrySet()) {\n final String layerName = entry.getKey();\n final MutableTargetImpl target = entry.getValue();\n putLayer(layerName, new LayerInfo(layerName, target.getModifiedState(), target.getDirectoryStructure()));\n }\n this.addOns.clear();\n for (final Map.Entry<String, MutableTargetImpl> entry : state.getAddOns().entrySet()) {\n final String addOnName = entry.getKey();\n final MutableTargetImpl target = entry.getValue();\n putAddOn(addOnName, new LayerInfo(addOnName, target.getModifiedState(), target.getDirectoryStructure()));\n }\n }",
"protected boolean check(String id, List<String> includes) {\n\t\tif (null != includes) {\n\t\t\tfor (String check : includes) {\n\t\t\t\tif (check(id, check)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"public static csvserver_appflowpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_appflowpolicy_binding obj = new csvserver_appflowpolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_appflowpolicy_binding response[] = (csvserver_appflowpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public AsciiTable setCharTranslator(CharacterTranslator charTranslator) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setCharTranslator(charTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"@Override\n public boolean isTempoMaster() {\n DeviceUpdate master = VirtualCdj.getInstance().getTempoMaster();\n return (master != null) && master.getAddress().equals(address);\n }",
"private int combineSubsetBlocks(Mode[] mode_type, int[] mode_length, int index_point) {\n /* bring together same type blocks */\n if (index_point > 1) {\n for (int i = 1; i < index_point; i++) {\n if (mode_type[i - 1] == mode_type[i]) {\n /* bring together */\n mode_length[i - 1] = mode_length[i - 1] + mode_length[i];\n /* decrease the list */\n for (int j = i + 1; j < index_point; j++) {\n mode_length[j - 1] = mode_length[j];\n mode_type[j - 1] = mode_type[j];\n }\n index_point--;\n i--;\n }\n }\n }\n return index_point;\n }",
"public static void acceptsJson(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_J, OPT_JSON),\n \"fetch key/entry by key value of json type\")\n .withRequiredArg()\n .describedAs(\"key-list\")\n .withValuesSeparatedBy(',')\n .ofType(String.class);\n }"
] |
Get a value from a date metadata field.
@param path the key path in the metadata object. Must be prefixed with a "/".
@return the metadata value as a Date.
@throws ParseException when the value cannot be parsed as a valid date | [
"public Date getDate(String path) throws ParseException {\n return BoxDateFormat.parse(this.getValue(path).asString());\n }"
] | [
"public Collection<Size> getSizes(String photoId, boolean sign) throws FlickrException {\r\n SizeList<Size> sizes = new SizeList<Size>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_SIZES);\r\n\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 Element sizesElement = response.getPayload();\r\n sizes.setIsCanBlog(\"1\".equals(sizesElement.getAttribute(\"canblog\")));\r\n sizes.setIsCanDownload(\"1\".equals(sizesElement.getAttribute(\"candownload\")));\r\n sizes.setIsCanPrint(\"1\".equals(sizesElement.getAttribute(\"canprint\")));\r\n NodeList sizeNodes = sizesElement.getElementsByTagName(\"size\");\r\n for (int i = 0; i < sizeNodes.getLength(); i++) {\r\n Element sizeElement = (Element) sizeNodes.item(i);\r\n Size size = new Size();\r\n size.setLabel(sizeElement.getAttribute(\"label\"));\r\n size.setWidth(sizeElement.getAttribute(\"width\"));\r\n size.setHeight(sizeElement.getAttribute(\"height\"));\r\n size.setSource(sizeElement.getAttribute(\"source\"));\r\n size.setUrl(sizeElement.getAttribute(\"url\"));\r\n size.setMedia(sizeElement.getAttribute(\"media\"));\r\n sizes.add(size);\r\n }\r\n return sizes;\r\n }",
"public void clear() {\n\t\tfor (Bean bean : beans.values()) {\n\t\t\tif (null != bean.destructionCallback) {\n\t\t\t\tbean.destructionCallback.run();\n\t\t\t}\n\t\t}\n\t\tbeans.clear();\n\t}",
"public void callFunction(\n final String name,\n final List<?> args,\n final @Nullable Long requestTimeout) {\n this.functionService.callFunction(name, args, requestTimeout);\n }",
"public TreeNode getModuleTree(final String moduleId) {\n final ModuleHandler moduleHandler = new ModuleHandler(repoHandler);\n final DbModule module = moduleHandler.getModule(moduleId);\n\n final TreeNode tree = new TreeNode();\n tree.setName(module.getName());\n\n // Add submodules\n for (final DbModule submodule : module.getSubmodules()) {\n addModuleToTree(submodule, tree);\n }\n\n return tree;\n }",
"private ColumnDef addColumnFor(FieldDescriptorDef fieldDef, TableDef tableDef)\r\n {\r\n String name = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN);\r\n ColumnDef columnDef = tableDef.getColumn(name);\r\n\r\n if (columnDef == null)\r\n {\r\n columnDef = new ColumnDef(name);\r\n tableDef.addColumn(columnDef);\r\n }\r\n if (!fieldDef.isNested())\r\n { \r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_JAVANAME, fieldDef.getName());\r\n }\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_TYPE, fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_ID, fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_ID));\r\n if (fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_PRIMARYKEY, false))\r\n {\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_PRIMARYKEY, \"true\");\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_REQUIRED, \"true\");\r\n }\r\n else if (!fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_NULLABLE, true))\r\n {\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_REQUIRED, \"true\");\r\n }\r\n if (\"database\".equals(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_AUTOINCREMENT)))\r\n {\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_AUTOINCREMENT, \"true\");\r\n }\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_SIZE, fieldDef.getSizeConstraint());\r\n if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_DOCUMENTATION))\r\n {\r\n columnDef.setProperty(PropertyHelper.OJB_PROPERTY_DOCUMENTATION,\r\n fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_DOCUMENTATION));\r\n }\r\n if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_COLUMN_DOCUMENTATION))\r\n {\r\n columnDef.setProperty(PropertyHelper.OJB_PROPERTY_COLUMN_DOCUMENTATION,\r\n fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN_DOCUMENTATION));\r\n }\r\n return columnDef;\r\n }",
"public ProjectCalendarHours addCalendarHours(Day day)\n {\n ProjectCalendarHours bch = new ProjectCalendarHours(this);\n bch.setDay(day);\n m_hours[day.getValue() - 1] = bch;\n return (bch);\n }",
"public void resolveLazyCrossReferences(final CancelIndicator mon) {\n\t\tfinal CancelIndicator monitor = mon == null ? CancelIndicator.NullImpl : mon;\n\t\tTreeIterator<Object> iterator = EcoreUtil.getAllContents(this, true);\n\t\twhile (iterator.hasNext()) {\n\t\t\toperationCanceledManager.checkCanceled(monitor);\n\t\t\tInternalEObject source = (InternalEObject) iterator.next();\n\t\t\tEStructuralFeature[] eStructuralFeatures = ((EClassImpl.FeatureSubsetSupplier) source.eClass()\n\t\t\t\t\t.getEAllStructuralFeatures()).crossReferences();\n\t\t\tif (eStructuralFeatures != null) {\n\t\t\t\tfor (EStructuralFeature crossRef : eStructuralFeatures) {\n\t\t\t\t\toperationCanceledManager.checkCanceled(monitor);\n\t\t\t\t\tresolveLazyCrossReference(source, crossRef);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"public StitchObjectMapper withCodecRegistry(final CodecRegistry codecRegistry) {\n // We can't detect if their codecRegistry has any duplicate providers. There's also a chance\n // that putting ours first may prevent decoding of some of their classes if for example they\n // have their own way of decoding an Integer.\n final CodecRegistry newReg =\n CodecRegistries.fromRegistries(BsonUtils.DEFAULT_CODEC_REGISTRY, codecRegistry);\n return new StitchObjectMapper(this, newReg);\n }",
"public static boolean isBadXmlCharacter(char c) {\n boolean cDataCharacter = c < '\\u0020' && c != '\\t' && c != '\\r' && c != '\\n';\n cDataCharacter |= (c >= '\\uD800' && c < '\\uE000');\n cDataCharacter |= (c == '\\uFFFE' || c == '\\uFFFF');\n return cDataCharacter;\n }"
] |
Boyer Moore scan that proceeds backwards from the end of the file looking for ENDSIG
@throws NonScannableZipException | [
"private static boolean scanForEndSig(File file, FileChannel channel) throws IOException, NonScannableZipException {\n\n // TODO Consider just reading in MAX_REVERSE_SCAN bytes -- increased peak memory cost but less complex\n\n ByteBuffer bb = getByteBuffer(CHUNK_SIZE);\n long start = channel.size();\n long end = Math.max(0, start - MAX_REVERSE_SCAN);\n long channelPos = Math.max(0, start - CHUNK_SIZE);\n long lastChannelPos = channelPos;\n boolean firstRead = true;\n while (lastChannelPos >= end) {\n\n read(bb, channel, channelPos);\n\n int actualRead = bb.limit();\n if (firstRead) {\n long expectedRead = Math.min(CHUNK_SIZE, start);\n if (actualRead > expectedRead) {\n // File is still growing\n return false;\n }\n firstRead = false;\n }\n\n int bufferPos = actualRead -1;\n while (bufferPos >= SIG_PATTERN_LENGTH) {\n\n // Following is based on the Boyer Moore algorithm but simplified to reflect\n // a) the pattern is static\n // b) the pattern has no repeating bytes\n\n int patternPos;\n for (patternPos = SIG_PATTERN_LENGTH - 1;\n patternPos >= 0 && ENDSIG_PATTERN[patternPos] == bb.get(bufferPos - patternPos);\n --patternPos) {\n // empty loop while bytes match\n }\n\n // 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 end of central dir record\n long startEndRecord = channelPos + bufferPos - SIG_PATTERN_LENGTH + 1;\n if (validateEndRecord(file, channel, startEndRecord)) {\n return true;\n }\n // wasn't a valid end 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 -= END_BAD_BYTE_SKIP[idx];\n break;\n }\n default:\n // 1 or more bytes matched\n bufferPos -= 4;\n }\n }\n\n // Move back a full chunk. If we didn't read a full chunk, that's ok,\n // it means we read all data and the outer while loop will terminate\n if (channelPos <= bufferPos) {\n break;\n }\n lastChannelPos = channelPos;\n channelPos -= Math.min(channelPos - bufferPos, CHUNK_SIZE - bufferPos);\n }\n\n return false;\n }"
] | [
"public void setRequestType(int pathId, Integer requestType) {\n if (requestType == null) {\n requestType = Constants.REQUEST_TYPE_GET;\n }\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + Constants.PATH_PROFILE_REQUEST_TYPE + \" = ?\" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, requestType);\n statement.setInt(2, pathId);\n statement.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }",
"public static double SymmetricChiSquareDivergence(double[] p, double[] q) {\n double r = 0;\n for (int i = 0; i < p.length; i++) {\n double den = p[i] * q[i];\n if (den != 0) {\n double p1 = p[i] - q[i];\n double p2 = p[i] + q[i];\n r += (p1 * p1 * p2) / den;\n }\n }\n\n return r;\n }",
"public static vpnglobal_auditnslogpolicy_binding[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tvpnglobal_auditnslogpolicy_binding obj = new vpnglobal_auditnslogpolicy_binding();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tvpnglobal_auditnslogpolicy_binding[] response = (vpnglobal_auditnslogpolicy_binding[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}",
"private void deliverMasterYieldCommand(int toPlayer) {\n for (final MasterHandoffListener listener : getMasterHandoffListeners()) {\n try {\n listener.yieldMasterTo(toPlayer);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering master yield command to listener\", t);\n }\n }\n }",
"public void storeIfNew(final DbArtifact fromClient) {\n final DbArtifact existing = repositoryHandler.getArtifact(fromClient.getGavc());\n\n if(existing != null){\n existing.setLicenses(fromClient.getLicenses());\n store(existing);\n }\n\n if(existing == null){\n\t store(fromClient);\n }\n }",
"private Renderer getPrototypeByIndex(final int prototypeIndex) {\n Renderer prototypeSelected = null;\n int i = 0;\n for (Renderer prototype : prototypes) {\n if (i == prototypeIndex) {\n prototypeSelected = prototype;\n }\n i++;\n }\n return prototypeSelected;\n }",
"public static String[] removeDuplicateStrings(String[] array) {\n if (isEmpty(array)) {\n return array;\n }\n Set<String> set = new TreeSet<String>();\n Collections.addAll(set, array);\n return toStringArray(set);\n }",
"public Build createBuild(String appName, Build build) {\n return connection.execute(new BuildCreate(appName, build), apiKey);\n }",
"public String calculateCacheKey(String sql, int[] columnIndexes) {\r\n\t\tStringBuilder tmp = new StringBuilder(sql.length()+4);\r\n\t\ttmp.append(sql);\r\n\t\tfor (int i=0; i < columnIndexes.length; i++){\r\n\t\t\ttmp.append(columnIndexes[i]);\r\n\t\t\ttmp.append(\"CI,\");\r\n\t\t}\r\n\t\treturn tmp.toString();\r\n\t}"
] |
Updates the Q matrix to take inaccount the row that was removed by only multiplying e
lements that need to be. There is still some room for improvement here...
@param rowIndex | [
"private void updateRemoveQ( int rowIndex ) {\n Qm.set(Q);\n Q.reshape(m_m,m_m, false);\n\n for( int i = 0; i < rowIndex; i++ ) {\n for( int j = 1; j < m; j++ ) {\n double sum = 0;\n for( int k = 0; k < m; k++ ) {\n sum += Qm.data[i*m+k]* U_tran.data[j*m+k];\n }\n Q.data[i*m_m+j-1] = sum;\n }\n }\n\n for( int i = rowIndex+1; i < m; i++ ) {\n for( int j = 1; j < m; j++ ) {\n double sum = 0;\n for( int k = 0; k < m; k++ ) {\n sum += Qm.data[i*m+k]* U_tran.data[j*m+k];\n }\n Q.data[(i-1)*m_m+j-1] = sum;\n }\n }\n }"
] | [
"protected List<I_CmsSearchConfigurationSortOption> getSortOptions() {\n\n List<I_CmsSearchConfigurationSortOption> options = new LinkedList<I_CmsSearchConfigurationSortOption>();\n try {\n JSONArray sortOptions = m_configObject.getJSONArray(JSON_KEY_SORTOPTIONS);\n for (int i = 0; i < sortOptions.length(); i++) {\n I_CmsSearchConfigurationSortOption option = parseSortOption(sortOptions.getJSONObject(i));\n if (option != null) {\n options.add(option);\n }\n }\n } catch (JSONException e) {\n if (null == m_baseConfig) {\n if (LOG.isInfoEnabled()) {\n LOG.info(Messages.get().getBundle().key(Messages.LOG_NO_SORT_CONFIG_0), e);\n }\n } else {\n options = m_baseConfig.getSortConfig().getSortOptions();\n }\n }\n return options;\n }",
"public void start(GVRAccessibilitySpeechListener speechListener) {\n mTts.setSpeechListener(speechListener);\n mTts.getSpeechRecognizer().startListening(mTts.getSpeechRecognizerIntent());\n }",
"@SuppressWarnings(\"unchecked\")\r\n\tpublic List<Difference> compare() {\r\n\t\tDiff diff = new Diff(this.controlDOM, this.testDOM);\r\n\t\tDetailedDiff detDiff = new DetailedDiff(diff);\r\n\t\treturn detDiff.getAllDifferences();\r\n\t}",
"@Override\n public void onNewState(CrawlerContext context, StateVertex vertex) {\n LOG.debug(\"onNewState\");\n StateBuilder state = outModelCache.addStateIfAbsent(vertex);\n visitedStates.putIfAbsent(state.getName(), vertex);\n\n saveScreenshot(context.getBrowser(), state.getName(), vertex);\n\n outputBuilder.persistDom(state.getName(), context.getBrowser().getUnStrippedDom());\n }",
"protected ServiceName serviceName(final String name) {\n return baseServiceName != null ? baseServiceName.append(name) : null;\n }",
"protected void runScript(File script) {\n if (!script.exists()) {\n JOptionPane.showMessageDialog(cliGuiCtx.getMainPanel(), script.getAbsolutePath() + \" does not exist.\",\n \"Unable to run script.\", JOptionPane.ERROR_MESSAGE);\n return;\n }\n\n int choice = JOptionPane.showConfirmDialog(cliGuiCtx.getMainPanel(), \"Run CLI script \" + script.getName() + \"?\",\n \"Confirm run script\", JOptionPane.YES_NO_OPTION);\n if (choice != JOptionPane.YES_OPTION) return;\n\n menu.addScript(script);\n\n cliGuiCtx.getTabs().setSelectedIndex(1); // set to Output tab to view the output\n output.post(\"\\n\");\n\n SwingWorker scriptRunner = new ScriptRunner(script);\n scriptRunner.execute();\n }",
"public List<String> getArtifactVersions(final String gavc) {\n final DbArtifact artifact = getArtifact(gavc);\n return repositoryHandler.getArtifactVersions(artifact);\n }",
"public static base_response delete(nitro_service client, String ciphergroupname) throws Exception {\n\t\tsslcipher deleteresource = new sslcipher();\n\t\tdeleteresource.ciphergroupname = ciphergroupname;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"public static Chart getMSDLineWithFreeModelChart(Trajectory t, int lagMin,\n\t\t\tint lagMax, double timelag, double diffusionCoefficient, double intercept) {\n\n\t\tdouble[] xData = new double[lagMax - lagMin + 1];\n\t\tdouble[] yData = new double[lagMax - lagMin + 1];\n\t\tdouble[] modelData = new double[lagMax - lagMin + 1];\n\t\tMeanSquaredDisplacmentFeature msdeval = new MeanSquaredDisplacmentFeature(\n\t\t\t\tt, lagMin);\n\t\tmsdeval.setTrajectory(t);\n\t\tmsdeval.setTimelag(lagMin);\n\t\tfor (int i = lagMin; i < lagMax + 1; i++) {\n\t\t\tmsdeval.setTimelag(i);\n\t\t\tdouble msdhelp = msdeval.evaluate()[0];\n\t\t\txData[i - lagMin] = i;\n\t\t\tyData[i - lagMin] = msdhelp;\n\t\t\tmodelData[i - lagMin] = intercept + 4*diffusionCoefficient*(i*timelag);//4 * D * Math.pow(i * timelag, a);\n\t\t}\n\n\t\t// Create Chart\n\t\tChart chart = QuickChart.getChart(\"MSD Line\", \"LAG\", \"MSD\", \"MSD\",\n\t\t\t\txData, yData);\n\t\tchart.addSeries(\"y=4*D*t + a\", xData, modelData);\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}"
] |
Specifies the object id associated with a user assigned managed service identity
resource that should be used to retrieve the access token.
@param objectId Object ID of the identity to use when authenticating to Azure AD.
@return MSICredentials | [
"@Beta\n public MSICredentials withObjectId(String objectId) {\n this.objectId = objectId;\n this.clientId = null;\n this.identityId = null;\n return this;\n }"
] | [
"private static IndexOptions prepareOptions(MongoDBIndexType indexType, Document options, String indexName, boolean unique) {\n\t\tIndexOptions indexOptions = new IndexOptions();\n\t\tindexOptions.name( indexName ).unique( unique ).background( options.getBoolean( \"background\" , false ) );\n\n\t\tif ( unique ) {\n\t\t\t// MongoDB only allows one null value per unique index which is not in line with what we usually consider\n\t\t\t// as the definition of a unique constraint. Thus, we mark the index as sparse to only index values\n\t\t\t// defined and avoid this issue. We do this only if a partialFilterExpression has not been defined\n\t\t\t// as partialFilterExpression and sparse are exclusive.\n\t\t\tindexOptions.sparse( !options.containsKey( \"partialFilterExpression\" ) );\n\t\t}\n\t\telse if ( options.containsKey( \"partialFilterExpression\" ) ) {\n\t\t\tindexOptions.partialFilterExpression( (Bson) options.get( \"partialFilterExpression\" ) );\n\t\t}\n\t\tif ( options.containsKey( \"expireAfterSeconds\" ) ) {\n\t\t\t//@todo is it correct?\n\t\t\tindexOptions.expireAfter( options.getInteger( \"expireAfterSeconds\" ).longValue() , TimeUnit.SECONDS );\n\n\t\t}\n\n\t\tif ( MongoDBIndexType.TEXT.equals( indexType ) ) {\n\t\t\t// text is an option we take into account to mark an index as a full text index as we cannot put \"text\" as\n\t\t\t// the order like MongoDB as ORM explicitly checks that the order is either asc or desc.\n\t\t\t// we remove the option from the Document so that we don't pass it to MongoDB\n\t\t\tif ( options.containsKey( \"default_language\" ) ) {\n\t\t\t\tindexOptions.defaultLanguage( options.getString( \"default_language\" ) );\n\t\t\t}\n\t\t\tif ( options.containsKey( \"weights\" ) ) {\n\t\t\t\tindexOptions.weights( (Bson) options.get( \"weights\" ) );\n\t\t\t}\n\n\t\t\toptions.remove( \"text\" );\n\t\t}\n\t\treturn indexOptions;\n\t}",
"public static <T> void callInitializers(T instance, CreationalContext<T> creationalContext, BeanManagerImpl manager,\n Iterable<? extends MethodInjectionPoint<?, ?>> initializerMethods) {\n for (MethodInjectionPoint<?, ?> initializer : initializerMethods) {\n initializer.invoke(instance, null, manager, creationalContext, CreationException.class);\n }\n }",
"private int decode(Huffman h) throws IOException\n {\n int len; /* current number of bits in code */\n int code; /* len bits being decoded */\n int first; /* first code of length len */\n int count; /* number of codes of length len */\n int index; /* index of first code of length len in symbol table */\n int bitbuf; /* bits from stream */\n int left; /* bits left in next or left to process */\n //short *next; /* next number of codes */\n\n bitbuf = m_bitbuf;\n left = m_bitcnt;\n code = first = index = 0;\n len = 1;\n int nextIndex = 1; // next = h->count + 1;\n while (true)\n {\n while (left-- != 0)\n {\n code |= (bitbuf & 1) ^ 1; /* invert code */\n bitbuf >>= 1;\n //count = *next++;\n count = h.m_count[nextIndex++];\n if (code < first + count)\n { /* if length len, return symbol */\n m_bitbuf = bitbuf;\n m_bitcnt = (m_bitcnt - len) & 7;\n return h.m_symbol[index + (code - first)];\n }\n index += count; /* else update for next length */\n first += count;\n first <<= 1;\n code <<= 1;\n len++;\n }\n left = (MAXBITS + 1) - len;\n if (left == 0)\n {\n break;\n }\n if (m_left == 0)\n {\n m_in = m_input.read();\n m_left = m_in == -1 ? 0 : 1;\n if (m_left == 0)\n {\n throw new IOException(\"out of input\"); /* out of input */\n }\n }\n bitbuf = m_in;\n m_left--;\n if (left > 8)\n {\n left = 8;\n }\n }\n return -9; /* ran out of codes */\n }",
"private void ensureNext() {\n // Check if the current scan result has more keys (i.e. the index did not reach the end of the result list)\n if (resultIndex < scanResult.getResult().size()) {\n return;\n }\n // Since the current scan result was fully iterated,\n // if there is another cursor scan it and ensure next key (recursively)\n if (!FIRST_CURSOR.equals(scanResult.getStringCursor())) {\n scanResult = scan(scanResult.getStringCursor(), scanParams);\n resultIndex = 0;\n ensureNext();\n }\n }",
"public Set<ServerConfigInfo> getServerConfigsOnSlave(Resource hostResource){\n Set<ServerConfigInfo> groups = new HashSet<>();\n for (ResourceEntry entry : hostResource.getChildren(SERVER_CONFIG)) {\n groups.add(new ServerConfigInfoImpl(entry.getModel()));\n }\n return groups;\n }",
"@SafeVarargs\n public static <T> Set<T> of(T... elements) {\n Preconditions.checkNotNull(elements);\n return ImmutableSet.<T> builder().addAll(elements).build();\n }",
"private String getIndirectionTableColName(TableAlias mnAlias, String path)\r\n {\r\n int dotIdx = path.lastIndexOf(\".\");\r\n String column = path.substring(dotIdx);\r\n return mnAlias.alias + column;\r\n }",
"@UiThread\n public int getParentAdapterPosition() {\n int flatPosition = getAdapterPosition();\n if (mExpandableAdapter == null || flatPosition == RecyclerView.NO_POSITION) {\n return RecyclerView.NO_POSITION;\n }\n\n return mExpandableAdapter.getNearestParentPosition(flatPosition);\n }",
"public String getDefaultTableName()\r\n {\r\n String name = getName();\r\n int lastDotPos = name.lastIndexOf('.');\r\n int lastDollarPos = name.lastIndexOf('$');\r\n\r\n return lastDollarPos > lastDotPos ? name.substring(lastDollarPos + 1) : name.substring(lastDotPos + 1);\r\n }"
] |
Performs an efficient update of each columns' norm | [
"protected void updateNorms( int j ) {\n boolean foundNegative = false;\n for( int col = j; col < numCols; col++ ) {\n double e = dataQR[col][j-1];\n double v = normsCol[col] -= e*e;\n\n if( v < 0 ) {\n foundNegative = true;\n break;\n }\n }\n\n // if a negative sum has been found then clearly too much precision has been lost\n // and it should recompute the column norms from scratch\n if( foundNegative ) {\n for( int col = j; col < numCols; col++ ) {\n double u[] = dataQR[col];\n double actual = 0;\n for( int i=j; i < numRows; i++ ) {\n double v = u[i];\n actual += v*v;\n }\n normsCol[col] = actual;\n }\n }\n }"
] | [
"public void download(OutputStream output, ProgressListener listener) {\n URL url = CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.fileID, this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxAPIResponse response = request.send();\n InputStream input = response.getBody(listener);\n\n long totalRead = 0;\n byte[] buffer = new byte[BUFFER_SIZE];\n try {\n int n = input.read(buffer);\n totalRead += n;\n while (n != -1) {\n output.write(buffer, 0, n);\n n = input.read(buffer);\n totalRead += n;\n }\n } catch (IOException e) {\n throw new BoxAPIException(\"Couldn't connect to the Box API due to a network error.\", e);\n }\n\n response.disconnect();\n }",
"private <T> T request(ClientRequest<T> delegate, String operationName) {\n long startTimeMs = -1;\n long startTimeNs = -1;\n\n if(logger.isDebugEnabled()) {\n startTimeMs = System.currentTimeMillis();\n }\n ClientRequestExecutor clientRequestExecutor = pool.checkout(destination);\n String debugMsgStr = \"\";\n\n startTimeNs = System.nanoTime();\n\n BlockingClientRequest<T> blockingClientRequest = null;\n try {\n blockingClientRequest = new BlockingClientRequest<T>(delegate, timeoutMs);\n clientRequestExecutor.addClientRequest(blockingClientRequest,\n timeoutMs,\n System.nanoTime() - startTimeNs);\n\n boolean awaitResult = blockingClientRequest.await();\n\n if(awaitResult == false) {\n blockingClientRequest.timeOut();\n }\n\n if(logger.isDebugEnabled())\n debugMsgStr += \"success\";\n\n return blockingClientRequest.getResult();\n } catch(InterruptedException e) {\n\n if(logger.isDebugEnabled())\n debugMsgStr += \"unreachable: \" + e.getMessage();\n\n throw new UnreachableStoreException(\"Failure in \" + operationName + \" on \"\n + destination + \": \" + e.getMessage(), e);\n } catch(UnreachableStoreException e) {\n clientRequestExecutor.close();\n\n if(logger.isDebugEnabled())\n debugMsgStr += \"failure: \" + e.getMessage();\n\n throw new UnreachableStoreException(\"Failure in \" + operationName + \" on \"\n + destination + \": \" + e.getMessage(), e.getCause());\n } finally {\n if(blockingClientRequest != null && !blockingClientRequest.isComplete()) {\n // close the executor if we timed out\n clientRequestExecutor.close();\n }\n // Record operation time\n long opTimeNs = Utils.elapsedTimeNs(startTimeNs, System.nanoTime());\n if(stats != null) {\n stats.recordSyncOpTimeNs(destination, opTimeNs);\n }\n if(logger.isDebugEnabled()) {\n logger.debug(\"Sync request end, type: \"\n + operationName\n + \" requestRef: \"\n + System.identityHashCode(delegate)\n + \" totalTimeNs: \"\n + opTimeNs\n + \" start time: \"\n + startTimeMs\n + \" end time: \"\n + System.currentTimeMillis()\n + \" client:\"\n + clientRequestExecutor.getSocketChannel().socket().getLocalAddress()\n + \":\"\n + clientRequestExecutor.getSocketChannel().socket().getLocalPort()\n + \" server: \"\n + clientRequestExecutor.getSocketChannel()\n .socket()\n .getRemoteSocketAddress() + \" outcome: \"\n + debugMsgStr);\n }\n\n pool.checkin(destination, clientRequestExecutor);\n }\n }",
"public static void configureProtocolHandler() {\n final String pkgs = System.getProperty(\"java.protocol.handler.pkgs\");\n String newValue = \"org.mapfish.print.url\";\n if (pkgs != null && !pkgs.contains(newValue)) {\n newValue = newValue + \"|\" + pkgs;\n } else if (pkgs != null) {\n newValue = pkgs;\n }\n System.setProperty(\"java.protocol.handler.pkgs\", newValue);\n }",
"protected List<CmsUUID> undelete() throws CmsException {\n\n List<CmsUUID> modifiedResources = new ArrayList<CmsUUID>();\n CmsObject cms = m_context.getCms();\n for (CmsResource resource : m_context.getResources()) {\n CmsLockActionRecord actionRecord = null;\n try {\n actionRecord = CmsLockUtil.ensureLock(m_context.getCms(), resource);\n cms.undeleteResource(cms.getSitePath(resource), true);\n modifiedResources.add(resource.getStructureId());\n } finally {\n if ((actionRecord != null) && (actionRecord.getChange() == LockChange.locked)) {\n\n try {\n cms.unlockResource(resource);\n } catch (CmsLockException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n }\n }\n }\n }\n return modifiedResources;\n }",
"public void setWorkingDay(Day day, DayType working)\n {\n DayType value;\n\n if (working == null)\n {\n if (isDerived())\n {\n value = DayType.DEFAULT;\n }\n else\n {\n value = DayType.WORKING;\n }\n }\n else\n {\n value = working;\n }\n\n m_days[day.getValue() - 1] = value;\n }",
"public static boolean requiresReload(final Set<Flag> flags) {\n return flags.contains(Flag.RESTART_ALL_SERVICES) || flags.contains(Flag.RESTART_RESOURCE_SERVICES);\n }",
"public int sum() {\n int total = 0;\n int N = getNumElements();\n for (int i = 0; i < N; i++) {\n if( data[i] )\n total += 1;\n }\n return total;\n }",
"private void removeAllBroadcasts(Set<String> sessionIds) {\n\n if (sessionIds == null) {\n for (CmsSessionInfo info : OpenCms.getSessionManager().getSessionInfos()) {\n OpenCms.getSessionManager().getBroadcastQueue(info.getSessionId().getStringValue()).clear();\n }\n return;\n }\n for (String sessionId : sessionIds) {\n OpenCms.getSessionManager().getBroadcastQueue(sessionId).clear();\n }\n }",
"public static final BigInteger printDay(Day day)\n {\n return (day == null ? null : BigInteger.valueOf(day.getValue() - 1));\n }"
] |
Retrieves the amount of work on a given day, and
returns it in the specified format.
@param date target date
@param format required format
@return work duration | [
"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 }"
] | [
"private String joinElements(int length)\n {\n StringBuilder sb = new StringBuilder();\n for (int index = 0; index < length; index++)\n {\n sb.append(m_elements.get(index));\n }\n return sb.toString();\n }",
"private long interpolateTimeFromUpdate(TrackPositionUpdate lastTrackUpdate, CdjStatus newDeviceUpdate,\n BeatGrid beatGrid) {\n final int beatNumber = newDeviceUpdate.getBeatNumber();\n final boolean noLongerPlaying = !newDeviceUpdate.isPlaying();\n\n // If we have just stopped, see if we are near a cue (assuming that information is available), and if so,\n // the best assumption is that the DJ jumped to that cue.\n if (lastTrackUpdate.playing && noLongerPlaying) {\n final CueList.Entry jumpedTo = findAdjacentCue(newDeviceUpdate, beatGrid);\n if (jumpedTo != null) return jumpedTo.cueTime;\n }\n\n // Handle the special case where we were not playing either in the previous or current update, but the DJ\n // might have jumped to a different place in the track.\n if (!lastTrackUpdate.playing) {\n if (lastTrackUpdate.beatNumber == beatNumber && noLongerPlaying) { // Haven't moved\n return lastTrackUpdate.milliseconds;\n } else {\n if (noLongerPlaying) { // Have jumped without playing.\n if (beatNumber < 0) {\n return -1; // We don't know the position any more; weird to get into this state and still have a grid?\n }\n // As a heuristic, assume we are right before the beat?\n return timeOfBeat(beatGrid, beatNumber, newDeviceUpdate);\n }\n }\n }\n\n // One way or another, we are now playing.\n long elapsedMillis = (newDeviceUpdate.getTimestamp() - lastTrackUpdate.timestamp) / 1000000;\n long moved = Math.round(lastTrackUpdate.pitch * elapsedMillis);\n long interpolated = (lastTrackUpdate.reverse)?\n (lastTrackUpdate.milliseconds - moved) : lastTrackUpdate.milliseconds + moved;\n if (Math.abs(beatGrid.findBeatAtTime(interpolated) - beatNumber) < 2) {\n return interpolated; // Our calculations still look plausible\n }\n // The player has jumped or drifted somewhere unexpected, correct.\n if (newDeviceUpdate.isPlayingForwards()) {\n return timeOfBeat(beatGrid, beatNumber, newDeviceUpdate);\n } else {\n return beatGrid.getTimeWithinTrack(Math.min(beatNumber + 1, beatGrid.beatCount));\n }\n }",
"public boolean hasUniqueLongOption(String optionName) {\n if(hasLongOption(optionName)) {\n for(ProcessedOption o : getOptions()) {\n if(o.name().startsWith(optionName) && !o.name().equals(optionName))\n return false;\n }\n return true;\n }\n return false;\n }",
"@SuppressWarnings(\"deprecation\")\n\tpublic static boolean dateTimeEquals(java.util.Date d1, java.util.Date d2) {\n if (d1 == null || d2 == null) {\n return false;\n }\n\n return d1.getDate() == d2.getDate()\n && d1.getMonth() == d2.getMonth()\n && d1.getYear() == d2.getYear()\n && d1.getHours() == d2.getHours()\n && d1.getMinutes() == d2.getMinutes()\n && d1.getSeconds() == d2.getSeconds();\n }",
"private void userInfoInit() {\n\t\tboolean first = true;\n\t\tuserId = null;\n\t\tuserLocale = null;\n\t\tuserName = null;\n\t\tuserOrganization = null;\n\t\tuserDivision = null;\n\t\tif (null != authentications) {\n\t\t\tfor (Authentication auth : authentications) {\n\t\t\t\tuserId = combine(userId, auth.getUserId());\n\t\t\t\tuserName = combine(userName, auth.getUserName());\n\t\t\t\tif (first) {\n\t\t\t\t\tuserLocale = auth.getUserLocale();\n\t\t\t\t\tfirst = false;\n\t\t\t\t} else {\n\t\t\t\t\tif (null != auth.getUserLocale() &&\n\t\t\t\t\t\t\t(null == userLocale || !userLocale.equals(auth.getUserLocale()))) {\n\t\t\t\t\t\tuserLocale = null;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tuserOrganization = combine(userOrganization, auth.getUserOrganization());\n\t\t\t\tuserDivision = combine(userDivision, auth.getUserDivision());\n\t\t\t}\n\t\t}\n\n\t\t// now calculate the \"id\" for this context, this should be independent of the data order, so sort\n\t\tMap<String, List<String>> idParts = new HashMap<String, List<String>>();\n\t\tif (null != authentications) {\n\t\t\tfor (Authentication auth : authentications) {\n\t\t\t\tList<String> auths = new ArrayList<String>();\n\t\t\t\tfor (BaseAuthorization ba : auth.getAuthorizations()) {\n\t\t\t\t\tauths.add(ba.getId());\n\t\t\t\t}\n\t\t\t\tCollections.sort(auths);\n\t\t\t\tidParts.put(auth.getSecurityServiceId(), auths);\n\t\t\t}\n\t\t}\n\t\tStringBuilder sb = new StringBuilder();\n\t\tList<String> sortedKeys = new ArrayList<String>(idParts.keySet());\n\t\tCollections.sort(sortedKeys);\n\t\tfor (String key : sortedKeys) {\n\t\t\tif (sb.length() > 0) {\n\t\t\t\tsb.append('|');\n\t\t\t}\n\t\t\tList<String> auths = idParts.get(key);\n\t\t\tfirst = true;\n\t\t\tfor (String ak : auths) {\n\t\t\t\tif (first) {\n\t\t\t\t\tfirst = false;\n\t\t\t\t} else {\n\t\t\t\t\tsb.append('|');\n\t\t\t\t}\n\t\t\t\tsb.append(ak);\n\t\t\t}\n\t\t\tsb.append('@');\n\t\t\tsb.append(key);\n\t\t}\n\t\tid = sb.toString();\n\t}",
"public void setEveryWorkingDay(final boolean isEveryWorkingDay) {\n\n if (m_model.isEveryWorkingDay() != isEveryWorkingDay) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setEveryWorkingDay(Boolean.valueOf(isEveryWorkingDay));\n m_model.setInterval(getPatternDefaultValues().getInterval());\n onValueChange();\n }\n });\n }\n }",
"public static SimpleMatrix diag( Class type, double ...vals ) {\n SimpleMatrix M = new SimpleMatrix(vals.length,vals.length,type);\n for (int i = 0; i < vals.length; i++) {\n M.set(i,i,vals[i]);\n }\n return M;\n }",
"public static <X, Y> Pair<X, Y> makePair(X x, Y y) {\r\n return new Pair<X, Y>(x, y);\r\n }",
"public List<String> getArtifactVersions(final String gavc) {\n final DbArtifact artifact = getArtifact(gavc);\n return repositoryHandler.getArtifactVersions(artifact);\n }"
] |
Reads the categories assigned to a resource.
@return map from the resource path (root path) to the assigned categories | [
"public Map<String, CmsJspCategoryAccessBean> getReadResourceCategories() {\n\n if (null == m_resourceCategories) {\n m_resourceCategories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n public Object transform(Object resourceName) {\n\n try {\n CmsResource resource = m_cms.readResource(\n getRequestContext().removeSiteRoot((String)resourceName));\n return new CmsJspCategoryAccessBean(m_cms, resource);\n } catch (CmsException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n return null;\n }\n }\n });\n }\n return m_resourceCategories;\n }"
] | [
"public void addColumnPair(String localColumn, String remoteColumn)\r\n {\r\n if (!_localColumns.contains(localColumn))\r\n { \r\n _localColumns.add(localColumn);\r\n }\r\n if (!_remoteColumns.contains(remoteColumn))\r\n { \r\n _remoteColumns.add(remoteColumn);\r\n }\r\n }",
"public void setTexCoord(String texName, String texCoordAttr, String shaderVarName)\n {\n synchronized (textures)\n {\n GVRTexture tex = textures.get(texName);\n\n if (tex != null)\n {\n tex.setTexCoord(texCoordAttr, shaderVarName);\n }\n else\n {\n throw new UnsupportedOperationException(\"Texture must be set before updating texture coordinate information\");\n }\n }\n }",
"public static final UUID parseUUID(String value)\n {\n return value == null || value.isEmpty() ? null : UUID.fromString(value);\n }",
"public static int getSystemPort(String portIdentifier) {\n int defaultPort = 0;\n\n if (portIdentifier.compareTo(Constants.SYS_API_PORT) == 0) {\n defaultPort = Constants.DEFAULT_API_PORT;\n } else if (portIdentifier.compareTo(Constants.SYS_DB_PORT) == 0) {\n defaultPort = Constants.DEFAULT_DB_PORT;\n } else if (portIdentifier.compareTo(Constants.SYS_FWD_PORT) == 0) {\n defaultPort = Constants.DEFAULT_FWD_PORT;\n } else if (portIdentifier.compareTo(Constants.SYS_HTTP_PORT) == 0) {\n defaultPort = Constants.DEFAULT_HTTP_PORT;\n } else if (portIdentifier.compareTo(Constants.SYS_HTTPS_PORT) == 0) {\n defaultPort = Constants.DEFAULT_HTTPS_PORT;\n } else {\n return defaultPort;\n }\n\n String portStr = System.getenv(portIdentifier);\n return (portStr == null || portStr.isEmpty()) ? defaultPort : Integer.valueOf(portStr);\n }",
"private void writeAllEnvelopes(boolean reuse)\r\n {\r\n // perform remove of m:n indirection table entries first\r\n performM2NUnlinkEntries();\r\n\r\n Iterator iter;\r\n // using clone to avoid ConcurentModificationException\r\n iter = ((List) mvOrderOfIds.clone()).iterator();\r\n while(iter.hasNext())\r\n {\r\n ObjectEnvelope mod = (ObjectEnvelope) mhtObjectEnvelopes.get(iter.next());\r\n boolean insert = false;\r\n if(needsCommit)\r\n {\r\n insert = mod.needsInsert();\r\n mod.getModificationState().commit(mod);\r\n if(reuse && insert)\r\n {\r\n getTransaction().doSingleLock(mod.getClassDescriptor(), mod.getObject(), mod.getIdentity(), Transaction.WRITE);\r\n }\r\n }\r\n /*\r\n arminw: important to call this cleanup method for each registered\r\n ObjectEnvelope, because this method will e.g. remove proxy listener\r\n objects for registered objects.\r\n */\r\n mod.cleanup(reuse, insert);\r\n }\r\n // add m:n indirection table entries\r\n performM2NLinkEntries();\r\n }",
"public static String objectToColumnString(Object object, String delimiter, String[] fieldNames)\r\n throws IllegalAccessException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException\r\n {\r\n StringBuilder sb = new StringBuilder();\r\n for (int i = 0; i < fieldNames.length; i++) {\r\n if (sb.length() > 0) {\r\n sb.append(delimiter);\r\n }\r\n try {\r\n Field field = object.getClass().getDeclaredField(fieldNames[i]);\r\n sb.append(field.get(object)) ;\r\n } catch (IllegalAccessException ex) {\r\n Method method = object.getClass().getDeclaredMethod(\"get\" + StringUtils.capitalize(fieldNames[i]));\r\n sb.append(method.invoke(object));\r\n }\r\n }\r\n return sb.toString();\r\n }",
"static DocumentVersionInfo getRemoteVersionInfo(final BsonDocument remoteDocument) {\n final BsonDocument version = getDocumentVersionDoc(remoteDocument);\n return new DocumentVersionInfo(\n version,\n remoteDocument != null\n ? BsonUtils.getDocumentId(remoteDocument) : null\n );\n }",
"public static Drawable decideIcon(ImageHolder imageHolder, Context ctx, int iconColor, boolean tint) {\n if (imageHolder == null) {\n return null;\n } else {\n return imageHolder.decideIcon(ctx, iconColor, tint);\n }\n }",
"public static ResourceKey key(Class<?> clazz, Enum<?> value) {\n return new ResourceKey(clazz.getName(), value.name());\n }"
] |
Create a mapping from entity names to entity ID values. | [
"private void populateEntityMap() throws SQLException\n {\n for (Row row : getRows(\"select * from z_primarykey\"))\n {\n m_entityMap.put(row.getString(\"Z_NAME\"), row.getInteger(\"Z_ENT\"));\n }\n }"
] | [
"public static <T> Set<T> asSet(T[] o) {\r\n return new HashSet<T>(Arrays.asList(o));\r\n }",
"public static boolean changeHost(String hostName,\n boolean enable,\n boolean disable,\n boolean remove,\n boolean isEnabled,\n boolean exists) throws Exception {\n\n // Open the file that is the first\n // command line parameter\n File hostsFile = new File(\"/etc/hosts\");\n FileInputStream fstream = new FileInputStream(\"/etc/hosts\");\n\n File outFile = null;\n BufferedWriter bw = null;\n // only do file output for destructive operations\n if (!exists && !isEnabled) {\n outFile = File.createTempFile(\"HostsEdit\", \".tmp\");\n bw = new BufferedWriter(new FileWriter(outFile));\n System.out.println(\"File name: \" + outFile.getPath());\n }\n\n // Get the object of DataInputStream\n DataInputStream in = new DataInputStream(fstream);\n BufferedReader br = new BufferedReader(new InputStreamReader(in));\n String strLine;\n boolean foundHost = false;\n boolean hostEnabled = false;\n\n\t\t/*\n * Group 1 - possible commented out host entry\n\t\t * Group 2 - destination address\n\t\t * Group 3 - host name\n\t\t * Group 4 - everything else\n\t\t */\n Pattern pattern = Pattern.compile(\"\\\\s*(#?)\\\\s*([^\\\\s]+)\\\\s*([^\\\\s]+)(.*)\");\n while ((strLine = br.readLine()) != null) {\n\n Matcher matcher = pattern.matcher(strLine);\n\n // if there is a match to the pattern and the host name is the same as the one we want to set\n if (matcher.find() &&\n matcher.group(3).toLowerCase().compareTo(hostName.toLowerCase()) == 0) {\n foundHost = true;\n if (remove) {\n // skip this line altogether\n continue;\n } else if (enable) {\n // we will disregard group 2 and just set it to 127.0.0.1\n if (!exists && !isEnabled)\n bw.write(\"127.0.0.1 \" + matcher.group(3) + matcher.group(4));\n } else if (disable) {\n if (!exists && !isEnabled)\n bw.write(\"# \" + matcher.group(2) + \" \" + matcher.group(3) + matcher.group(4));\n } else if (isEnabled && matcher.group(1).compareTo(\"\") == 0) {\n // host exists and there is no # before it\n hostEnabled = true;\n }\n } else {\n // just write the line back out\n if (!exists && !isEnabled)\n bw.write(strLine);\n }\n\n if (!exists && !isEnabled)\n bw.write('\\n');\n }\n\n // if we didn't find the host in the file but need to enable it\n if (!foundHost && enable) {\n // write a new host entry\n if (!exists && !isEnabled)\n bw.write(\"127.0.0.1 \" + hostName + '\\n');\n }\n // Close the input stream\n in.close();\n\n if (!exists && !isEnabled) {\n bw.close();\n outFile.renameTo(hostsFile);\n }\n\n // return false if the host wasn't found\n if (exists && !foundHost)\n return false;\n\n // return false if the host wasn't enabled\n if (isEnabled && !hostEnabled)\n return false;\n\n return true;\n }",
"public List<TimephasedWork> getCompleteWork(ProjectCalendar calendar, ResourceAssignment resourceAssignment, byte[] data)\n {\n LinkedList<TimephasedWork> list = new LinkedList<TimephasedWork>();\n\n if (calendar != null && data != null && data.length > 2 && MPPUtility.getShort(data, 0) > 0)\n {\n Date startDate = resourceAssignment.getStart();\n double finishTime = MPPUtility.getInt(data, 24);\n\n int blockCount = MPPUtility.getShort(data, 0);\n double previousCumulativeWork = 0;\n TimephasedWork previousAssignment = null;\n\n int index = 32;\n int currentBlock = 0;\n while (currentBlock < blockCount && index + 20 <= data.length)\n {\n double time = MPPUtility.getInt(data, index + 0);\n\n // If the start of this block is before the start of the assignment, or after the end of the assignment\n // the values don't make sense, so we'll just set the start of this block to be the start of the assignment.\n // This deals with an issue where odd timephased data like this was causing an MPP file to be read\n // extremely slowly.\n if (time < 0 || time > finishTime)\n {\n time = 0;\n }\n else\n {\n time /= 80;\n }\n Duration startWork = Duration.getInstance(time, TimeUnit.MINUTES);\n\n double currentCumulativeWork = (long) MPPUtility.getDouble(data, index + 4);\n double assignmentDuration = currentCumulativeWork - previousCumulativeWork;\n previousCumulativeWork = currentCumulativeWork;\n assignmentDuration /= 1000;\n Duration totalWork = Duration.getInstance(assignmentDuration, TimeUnit.MINUTES);\n time = (long) MPPUtility.getDouble(data, index + 12);\n time /= 125;\n time *= 6;\n Duration workPerDay = Duration.getInstance(time, TimeUnit.MINUTES);\n\n Date start;\n if (startWork.getDuration() == 0)\n {\n start = startDate;\n }\n else\n {\n start = calendar.getDate(startDate, startWork, true);\n }\n\n TimephasedWork assignment = new TimephasedWork();\n assignment.setStart(start);\n assignment.setAmountPerDay(workPerDay);\n assignment.setTotalAmount(totalWork);\n\n if (previousAssignment != null)\n {\n Date finish = calendar.getDate(startDate, startWork, false);\n previousAssignment.setFinish(finish);\n if (previousAssignment.getStart().getTime() == previousAssignment.getFinish().getTime())\n {\n list.removeLast();\n }\n }\n\n list.add(assignment);\n previousAssignment = assignment;\n\n index += 20;\n ++currentBlock;\n }\n\n if (previousAssignment != null)\n {\n Duration finishWork = Duration.getInstance(finishTime / 80, TimeUnit.MINUTES);\n Date finish = calendar.getDate(startDate, finishWork, false);\n previousAssignment.setFinish(finish);\n if (previousAssignment.getStart().getTime() == previousAssignment.getFinish().getTime())\n {\n list.removeLast();\n }\n }\n }\n\n return list;\n }",
"private void purgeDeadJobInstances(DbConn cnx, Node node)\n {\n for (JobInstance ji : JobInstance.select(cnx, \"ji_select_by_node\", node.getId()))\n {\n try\n {\n cnx.runSelectSingle(\"history_select_state_by_id\", String.class, ji.getId());\n }\n catch (NoResultException e)\n {\n History.create(cnx, ji, State.CRASHED, Calendar.getInstance());\n Message.create(cnx,\n \"Job was supposed to be running at server startup - usually means it was killed along a server by an admin or a crash\",\n ji.getId());\n }\n\n cnx.runUpdate(\"ji_delete_by_id\", ji.getId());\n }\n cnx.commit();\n }",
"public void stop(int waitMillis) throws InterruptedException {\n try {\n if (!isDone()) {\n setExitStatus(new Event(EventType.STOPPED_BY_USER, String.format(\"Stopped by user: waiting for %d ms\", waitMillis)));\n }\n if (!waitForFinish(waitMillis)) {\n logger.warn(\"{} Client thread failed to finish in {} millis\", name, waitMillis);\n }\n } finally {\n rateTracker.shutdown();\n }\n }",
"@Override\n public DMatrixRMaj getA() {\n if( A.data.length < numRows*numCols ) {\n A = new DMatrixRMaj(numRows,numCols);\n }\n A.reshape(numRows,numCols, false);\n CommonOps_DDRM.mult(Q,R,A);\n\n return A;\n }",
"public BlurBuilder contrast(float contrast) {\n data.preProcessors.add(new ContrastProcessor(data.contextWrapper.getRenderScript(), Math.max(Math.min(1500.f, contrast), -1500.f)));\n return this;\n }",
"public static boolean isBadXmlCharacter(char c) {\n boolean cDataCharacter = c < '\\u0020' && c != '\\t' && c != '\\r' && c != '\\n';\n cDataCharacter |= (c >= '\\uD800' && c < '\\uE000');\n cDataCharacter |= (c == '\\uFFFE' || c == '\\uFFFF');\n return cDataCharacter;\n }",
"public static Collection<Info> getPendingCollaborations(BoxAPIConnection api) {\n URL url = PENDING_COLLABORATIONS_URL.build(api.getBaseURL());\n\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int entriesCount = responseJSON.get(\"total_count\").asInt();\n Collection<BoxCollaboration.Info> collaborations = new ArrayList<BoxCollaboration.Info>(entriesCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue entry : entries) {\n JsonObject entryObject = entry.asObject();\n BoxCollaboration collaboration = new BoxCollaboration(api, entryObject.get(\"id\").asString());\n BoxCollaboration.Info info = collaboration.new Info(entryObject);\n collaborations.add(info);\n }\n\n return collaborations;\n }"
] |
Computes the d and H parameters.
d = J'*(f(x)-y) <--- that's also the gradient
H = J'*J | [
"private void computeGradientAndHessian(DMatrixRMaj param )\n {\n // residuals = f(x) - y\n function.compute(param, residuals);\n\n computeNumericalJacobian(param,jacobian);\n\n CommonOps_DDRM.multTransA(jacobian, residuals, g);\n CommonOps_DDRM.multTransA(jacobian, jacobian, H);\n\n CommonOps_DDRM.extractDiag(H,Hdiag);\n }"
] | [
"public String prepareStatementString() throws SQLException {\n\t\tList<ArgumentHolder> argList = new ArrayList<ArgumentHolder>();\n\t\treturn buildStatementString(argList);\n\t}",
"public Where<T, ID> gt(String columnName, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,\n\t\t\t\tSimpleComparison.GREATER_THAN_OPERATION));\n\t\treturn this;\n\t}",
"public void send(ProducerPoolData<V> ppd) {\n if (logger.isDebugEnabled()) {\n logger.debug(\"send message: \" + ppd);\n }\n if (sync) {\n Message[] messages = new Message[ppd.data.size()];\n int index = 0;\n for (V v : ppd.data) {\n messages[index] = serializer.toMessage(v);\n index++;\n }\n ByteBufferMessageSet bbms = new ByteBufferMessageSet(config.getCompressionCodec(), messages);\n ProducerRequest request = new ProducerRequest(ppd.topic, ppd.partition.partId, bbms);\n SyncProducer producer = syncProducers.get(ppd.partition.brokerId);\n if (producer == null) {\n throw new UnavailableProducerException(\"Producer pool has not been initialized correctly. \" + \"Sync Producer for broker \"\n + ppd.partition.brokerId + \" does not exist in the pool\");\n }\n producer.send(request.topic, request.partition, request.messages);\n } else {\n AsyncProducer<V> asyncProducer = asyncProducers.get(ppd.partition.brokerId);\n for (V v : ppd.data) {\n asyncProducer.send(ppd.topic, v, ppd.partition.partId);\n }\n }\n }",
"protected String addDependency(TaskGroup.HasTaskGroup dependency) {\n Objects.requireNonNull(dependency);\n this.taskGroup().addDependencyTaskGroup(dependency.taskGroup());\n return dependency.taskGroup().key();\n }",
"private void cascadeInsertFor(ObjectEnvelope mod, List alreadyPrepared)\r\n {\r\n // avoid endless recursion, so use List for registration\r\n if(alreadyPrepared.contains(mod.getIdentity())) return;\r\n alreadyPrepared.add(mod.getIdentity());\r\n\r\n ClassDescriptor cld = getTransaction().getBroker().getClassDescriptor(mod.getObject().getClass());\r\n\r\n List refs = cld.getObjectReferenceDescriptors(true);\r\n cascadeInsertSingleReferences(mod, refs, alreadyPrepared);\r\n\r\n List colls = cld.getCollectionDescriptors(true);\r\n cascadeInsertCollectionReferences(mod, colls, alreadyPrepared);\r\n }",
"private boolean matchesFingerprint(byte[] buffer, Pattern fingerprint)\n {\n return fingerprint.matcher(m_charset == null ? new String(buffer) : new String(buffer, m_charset)).matches();\n }",
"public void updateGroupName(String newGroupName, int id) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_GROUPS +\n \" SET \" + Constants.GROUPS_GROUP_NAME + \" = ? \" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, newGroupName);\n statement.setInt(2, id);\n statement.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }",
"private void populateResourceAssignmentWorkgroupFields(Record record, ResourceAssignmentWorkgroupFields workgroup) throws MPXJException\n {\n workgroup.setMessageUniqueID(record.getString(0));\n workgroup.setConfirmed(NumberHelper.getInt(record.getInteger(1)) == 1);\n workgroup.setResponsePending(NumberHelper.getInt(record.getInteger(1)) == 1);\n workgroup.setUpdateStart(record.getDateTime(3));\n workgroup.setUpdateFinish(record.getDateTime(4));\n workgroup.setScheduleID(record.getString(5));\n }",
"public static servicegroupbindings get(nitro_service service, String servicegroupname) throws Exception{\n\t\tservicegroupbindings obj = new servicegroupbindings();\n\t\tobj.set_servicegroupname(servicegroupname);\n\t\tservicegroupbindings response = (servicegroupbindings) obj.get_resource(service);\n\t\treturn response;\n\t}"
] |
Use this API to fetch statistics of appfwpolicy_stats resource of given name . | [
"public static appfwpolicy_stats get(nitro_service service, String name) throws Exception{\n\t\tappfwpolicy_stats obj = new appfwpolicy_stats();\n\t\tobj.set_name(name);\n\t\tappfwpolicy_stats response = (appfwpolicy_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}"
] | [
"private void printKeySet() {\r\n Set<?> keys = keySet();\r\n System.out.println(\"printing keyset:\");\r\n for (Object o: keys) {\r\n //System.out.println(Arrays.asList((Object[]) i.next()));\r\n System.out.println(o);\r\n }\r\n }",
"public Photoset create(String title, String description, String primaryPhotoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_CREATE);\r\n\r\n parameters.put(\"title\", title);\r\n parameters.put(\"description\", description);\r\n parameters.put(\"primary_photo_id\", primaryPhotoId);\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosetElement = response.getPayload();\r\n Photoset photoset = new Photoset();\r\n photoset.setId(photosetElement.getAttribute(\"id\"));\r\n photoset.setUrl(photosetElement.getAttribute(\"url\"));\r\n return photoset;\r\n }",
"private List<AssignmentField> getAllAssignmentExtendedAttributes()\n {\n ArrayList<AssignmentField> result = new ArrayList<AssignmentField>();\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_COST));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_DATE));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_DURATION));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_COST));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_DATE));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_DURATION));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_FLAG));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_NUMBER));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_RESOURCE_MULTI_VALUE));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_RESOURCE_OUTLINE_CODE));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_TEXT));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_FINISH));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_FLAG));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_NUMBER));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_START));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_TEXT));\n return result;\n }",
"public PBKey getPBKey()\r\n {\r\n if (pbKey == null)\r\n {\r\n this.pbKey = new PBKey(this.getJcdAlias(), this.getUserName(), this.getPassWord());\r\n }\r\n return pbKey;\r\n }",
"public ItemRequest<Project> update(String project) {\n \n String path = String.format(\"/projects/%s\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"PUT\");\n }",
"public static BoxRetentionPolicyAssignment.Info createAssignmentToFolder(BoxAPIConnection api, String policyID,\r\n String folderID) {\r\n return createAssignment(api, policyID, new JsonObject().add(\"type\", TYPE_FOLDER).add(\"id\", folderID), null);\r\n }",
"public static void scanClassPathForFormattingAnnotations() {\n\n\t\tExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);\n\n\t\t// scan classpath and filter out classes that don't begin with \"com.nds\"\n\t\tReflections reflections = new Reflections(\"com.nds\",\"com.cisco\");\n\n\t\tSet<Class<?>> annotated = reflections.getTypesAnnotatedWith(DefaultFormat.class);\n\n// Reflections ciscoReflections = new Reflections(\"com.cisco\");\n//\n// annotated.addAll(ciscoReflections.getTypesAnnotatedWith(DefaultFormat.class));\n\n\t\tfor (Class<?> markerClass : annotated) {\n\n\t\t\t// if the marker class is indeed implementing FoundationLoggingMarker\n\t\t\t// interface\n\t\t\tif (FoundationLoggingMarker.class.isAssignableFrom(markerClass)) {\n\n\t\t\t\tfinal Class<? extends FoundationLoggingMarker> clazz = (Class<? extends FoundationLoggingMarker>) markerClass;\n\n\t\t\t\texecutorService.execute(new Runnable() {\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void run() {\n\n\t\t\t\t\t\tif (markersMap.get(clazz) == null) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t// generate formatter class for this marker\n\t\t\t\t\t\t\t\t// class\n\t\t\t\t\t\t\t\tgenerateAndUpdateFormatterInMap(clazz);\n\t\t\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t\t\tLOGGER.trace(\"problem generating formatter class from static scan method. error is: \" + e.toString());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t} else {// if marker class does not implement FoundationLoggingMarker\n\t\t\t\t\t// interface, log ERROR\n\n\t\t\t\t// verify the LOGGER was initialized. It might not be as this\n\t\t\t\t// Method is called in a static block\n\t\t\t\tif (LOGGER == null) {\n\t\t\t\t\tLOGGER = LoggerFactory.getLogger(AbstractFoundationLoggingMarker.class);\n\t\t\t\t}\n\t\t\t\tLOGGER.error(\"Formatter annotations should only appear on foundationLoggingMarker implementations\");\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\tTimeUnit.SECONDS.sleep(30);\n\t\t} catch (InterruptedException e) {\n\t\t\tLOGGER.trace(e.toString(), e);\n\t\t}\n\t\texecutorService.shutdown();\n\t\t// try {\n\t\t// executorService.awaitTermination(15, TimeUnit.SECONDS);\n\t\t// } catch (InterruptedException e) {\n\t\t// LOGGER.error(\"creation of formatters has been interrupted\");\n\t\t// }\n\t}",
"protected boolean boot(List<ModelNode> bootOperations, boolean rollbackOnRuntimeFailure) throws ConfigurationPersistenceException {\n return boot(bootOperations, rollbackOnRuntimeFailure, false, ModelControllerImpl.getMutableRootResourceRegistrationProvider());\n }",
"@SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n public List<HazeltaskTask<G>> shutdownNow() {\n\t return (List<HazeltaskTask<G>>) (List) localExecutorPool.shutdownNow();\n\t}"
] |
Get content of a file as a Map<String, String>, using separator to split values
@param file File to get content
@param separator The separator
@return The map with the values
@throws IOException I/O Error | [
"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 }"
] | [
"@Override\n public boolean accept(File file) {\n //All directories are added in the least that can be read by the Application\n if (file.isDirectory()&&file.canRead())\n { return true;\n }\n else if(properties.selection_type==DialogConfigs.DIR_SELECT)\n { /* True for files, If the selection type is Directory type, ie.\n * Only directory has to be selected from the list, then all files are\n * ignored.\n */\n return false;\n }\n else\n { /* Check whether name of the file ends with the extension. Added if it\n * does.\n */\n String name = file.getName().toLowerCase(Locale.getDefault());\n for (String ext : validExtensions) {\n if (name.endsWith(ext)) {\n return true;\n }\n }\n }\n return false;\n }",
"public void fireCalendarReadEvent(ProjectCalendar calendar)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.calendarRead(calendar);\n }\n }\n }",
"public List<String> getArtifactVersions(final String gavc) {\n final DbArtifact artifact = getArtifact(gavc);\n return repositoryHandler.getArtifactVersions(artifact);\n }",
"public String buildRadio(String propName) throws CmsException {\n\n String propVal = readProperty(propName);\n StringBuffer result = new StringBuffer(\"<table border=\\\"0\\\"><tr>\");\n result.append(\"<td><input type=\\\"radio\\\" value=\\\"true\\\" onClick=\\\"checkNoIntern()\\\" name=\\\"\").append(\n propName).append(\"\\\" \").append(Boolean.valueOf(propVal).booleanValue() ? \"checked=\\\"checked\\\"\" : \"\").append(\n \"/></td><td id=\\\"tablelabel\\\">\").append(key(Messages.GUI_LABEL_TRUE_0)).append(\"</td>\");\n result.append(\"<td><input type=\\\"radio\\\" value=\\\"false\\\" onClick=\\\"checkNoIntern()\\\" name=\\\"\").append(\n propName).append(\"\\\" \").append(Boolean.valueOf(propVal).booleanValue() ? \"\" : \"checked=\\\"checked\\\"\").append(\n \"/></td><td id=\\\"tablelabel\\\">\").append(key(Messages.GUI_LABEL_FALSE_0)).append(\"</td>\");\n result.append(\"<td><input type=\\\"radio\\\" value=\\\"\\\" onClick=\\\"checkNoIntern()\\\" name=\\\"\").append(\n propName).append(\"\\\" \").append(CmsStringUtil.isEmpty(propVal) ? \"checked=\\\"checked\\\"\" : \"\").append(\n \"/></td><td id=\\\"tablelabel\\\">\").append(getPropertyInheritanceInfo(propName)).append(\n \"</td></tr></table>\");\n return result.toString();\n }",
"public final int deleteOld(final long checkTimeThreshold) {\n final CriteriaBuilder builder = getSession().getCriteriaBuilder();\n final CriteriaDelete<PrintJobStatusExtImpl> delete =\n builder.createCriteriaDelete(PrintJobStatusExtImpl.class);\n final Root<PrintJobStatusExtImpl> root = delete.from(PrintJobStatusExtImpl.class);\n delete.where(builder.and(builder.isNotNull(root.get(\"lastCheckTime\")),\n builder.lessThan(root.get(\"lastCheckTime\"), checkTimeThreshold)));\n return getSession().createQuery(delete).executeUpdate();\n }",
"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 FormInput inputField(InputType type, Identification identification) {\r\n\t\tFormInput input = new FormInput(type, identification);\r\n\t\tthis.formInputs.add(input);\r\n\t\treturn input;\r\n\t}",
"public void setAcquireRetryDelay(long acquireRetryDelay, TimeUnit timeUnit) {\n\t\tthis.acquireRetryDelayInMs = TimeUnit.MILLISECONDS.convert(acquireRetryDelay, timeUnit);\n\t}",
"public static boolean isTypeManagedBeanOrDecoratorOrInterceptor(AnnotatedType<?> annotatedType) {\n Class<?> javaClass = annotatedType.getJavaClass();\n return !javaClass.isEnum() && !Extension.class.isAssignableFrom(javaClass)\n && Reflections.isTopLevelOrStaticNestedClass(javaClass) && !Reflections.isParameterizedTypeWithWildcard(javaClass)\n && hasSimpleCdiConstructor(annotatedType);\n }"
] |
Get the sub registry for the servers.
@param range the version range
@return the sub registry | [
"public TransformersSubRegistration getServerRegistration(final ModelVersionRange range) {\n final PathAddress address = PathAddress.EMPTY_ADDRESS.append(HOST, SERVER);\n return new TransformersSubRegistrationImpl(range, domain, address);\n }"
] | [
"private void stripCommas(TokenList tokens) {\n TokenList.Token t = tokens.getFirst();\n\n while( t != null ) {\n TokenList.Token next = t.next;\n if( t.getSymbol() == Symbol.COMMA ) {\n tokens.remove(t);\n }\n t = next;\n }\n }",
"private void readRelationships()\n {\n for (MapRow row : m_tables.get(\"REL\"))\n {\n Task predecessor = m_activityMap.get(row.getString(\"PREDECESSOR_ACTIVITY_ID\"));\n Task successor = m_activityMap.get(row.getString(\"SUCCESSOR_ACTIVITY_ID\"));\n if (predecessor != null && successor != null)\n {\n Duration lag = row.getDuration(\"LAG_VALUE\");\n RelationType type = row.getRelationType(\"LAG_TYPE\");\n\n successor.addPredecessor(predecessor, type, lag);\n }\n }\n }",
"public static double distance(double lat1, double lon1,\n double lat2, double lon2) {\n double dLat = Math.toRadians(lat2-lat1);\n double dLon = Math.toRadians(lon2-lon1);\n lat1 = Math.toRadians(lat1);\n lat2 = Math.toRadians(lat2);\n\n double a = Math.sin(dLat/2) * Math.sin(dLat/2) +\n Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); \n double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); \n return R * c;\n }",
"private static <T> Set<Type> getSessionBeanTypes(EnhancedAnnotated<T, ?> annotated, EjbDescriptor<T> ejbDescriptor) {\n ImmutableSet.Builder<Type> types = ImmutableSet.builder();\n // session beans\n Map<Class<?>, Type> typeMap = new LinkedHashMap<Class<?>, Type>();\n HierarchyDiscovery beanClassDiscovery = HierarchyDiscovery.forNormalizedType(ejbDescriptor.getBeanClass());\n for (BusinessInterfaceDescriptor<?> businessInterfaceDescriptor : ejbDescriptor.getLocalBusinessInterfaces()) {\n // first we need to resolve the local interface\n Type resolvedLocalInterface = beanClassDiscovery.resolveType(Types.getCanonicalType(businessInterfaceDescriptor.getInterface()));\n SessionBeanHierarchyDiscovery interfaceDiscovery = new SessionBeanHierarchyDiscovery(resolvedLocalInterface);\n if (beanClassDiscovery.getTypeMap().containsKey(businessInterfaceDescriptor.getInterface())) {\n // WELD-1675 Only add types also included in Annotated.getTypeClosure()\n for (Entry<Class<?>, Type> entry : interfaceDiscovery.getTypeMap().entrySet()) {\n if (annotated.getTypeClosure().contains(entry.getValue())) {\n typeMap.put(entry.getKey(), entry.getValue());\n }\n }\n } else {\n // Session bean class does not implement the business interface and @javax.ejb.Local applied to the session bean class\n typeMap.putAll(interfaceDiscovery.getTypeMap());\n }\n }\n if (annotated.isAnnotationPresent(Typed.class)) {\n types.addAll(Beans.getTypedTypes(typeMap, annotated.getJavaClass(), annotated.getAnnotation(Typed.class)));\n } else {\n typeMap.put(Object.class, Object.class);\n types.addAll(typeMap.values());\n }\n return Beans.getLegalBeanTypes(types.build(), annotated);\n }",
"public static Map<String, String> parseProperties(String s) {\n\t\tMap<String, String> properties = new HashMap<String, String>();\n\t\tif (!StringUtils.isEmpty(s)) {\n\t\t\tMatcher matcher = PROPERTIES_PATTERN.matcher(s);\n\t\t\tint start = 0;\n\t\t\twhile (matcher.find()) {\n\t\t\t\taddKeyValuePairAsProperty(s.substring(start, matcher.start()), properties);\n\t\t\t\tstart = matcher.start() + 1;\n\t\t\t}\n\t\t\taddKeyValuePairAsProperty(s.substring(start), properties);\n\t\t}\n\t\treturn properties;\n\t}",
"private String getStringPredicate(String fieldName, List<String> filterValues, List<Object> prms)\n {\n if (filterValues != null && !filterValues.isEmpty())\n {\n String res = \"\";\n for (String filterValue : filterValues)\n {\n if (filterValue == null)\n {\n continue;\n }\n if (!filterValue.isEmpty())\n {\n prms.add(filterValue);\n if (filterValue.contains(\"%\"))\n {\n res += String.format(\"(%s LIKE ?) OR \", fieldName);\n }\n else\n {\n res += String.format(\"(%s = ?) OR \", fieldName);\n }\n }\n else\n {\n res += String.format(\"(%s IS NULL OR %s = '') OR \", fieldName, fieldName);\n }\n }\n if (!res.isEmpty())\n {\n res = \"AND (\" + res.substring(0, res.length() - 4) + \") \";\n return res;\n }\n }\n return \"\";\n }",
"public IGoal[] getAgentGoals(final String agent_name, Connector connector) {\n ((IExternalAccess) connector.getAgentsExternalAccess(agent_name))\n .scheduleStep(new IComponentStep<Plan>() {\n\n public IFuture<Plan> execute(IInternalAccess ia) {\n IBDIInternalAccess bia = (IBDIInternalAccess) ia;\n\n goals = bia.getGoalbase().getGoals();\n return null;\n }\n }).get(new ThreadSuspendable());\n\n return goals;\n }",
"public Collection<Group> getPublicGroups(String userId) throws FlickrException {\r\n List<Group> groups = new ArrayList<Group>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PUBLIC_GROUPS);\r\n\r\n parameters.put(\"user_id\", userId);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element groupsElement = response.getPayload();\r\n NodeList groupNodes = groupsElement.getElementsByTagName(\"group\");\r\n for (int i = 0; i < groupNodes.getLength(); i++) {\r\n Element groupElement = (Element) groupNodes.item(i);\r\n Group group = new Group();\r\n group.setId(groupElement.getAttribute(\"nsid\"));\r\n group.setName(groupElement.getAttribute(\"name\"));\r\n group.setAdmin(\"1\".equals(groupElement.getAttribute(\"admin\")));\r\n group.setEighteenPlus(groupElement.getAttribute(\"eighteenplus\").equals(\"0\") ? false : true);\r\n groups.add(group);\r\n }\r\n return groups;\r\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 }"
] |
Returns the orthogonal V matrix.
@param V If not null then the results will be stored here. Otherwise a new matrix will be created.
@return The extracted Q matrix. | [
"@Override\n public DMatrixRMaj getV(DMatrixRMaj V , boolean transpose , boolean compact ) {\n V = handleV(V, transpose, compact,m,n,min);\n CommonOps_DDRM.setIdentity(V);\n\n// UBV.print();\n\n // todo the very first multiplication can be avoided by setting to the rank1update output\n for( int j = min-1; j >= 0; j-- ) {\n u[j+1] = 1;\n for( int i = j+2; i < n; i++ ) {\n u[i] = UBV.get(j,i);\n }\n if( transpose )\n QrHelperFunctions_DDRM.rank1UpdateMultL(V, u, gammasV[j], j + 1, j + 1, n);\n else\n QrHelperFunctions_DDRM.rank1UpdateMultR(V, u, gammasV[j], j + 1, j + 1, n, this.b);\n }\n\n return V;\n }"
] | [
"private CmsFavInfo createFavInfo(CmsFavoriteEntry entry) throws CmsException {\n\n String title = \"\";\n String subtitle = \"\";\n CmsFavInfo result = new CmsFavInfo(entry);\n CmsObject cms = A_CmsUI.getCmsObject();\n String project = getProject(cms, entry);\n String site = getSite(cms, entry);\n try {\n CmsUUID idToLoad = entry.getDetailId() != null ? entry.getDetailId() : entry.getStructureId();\n CmsResource resource = cms.readResource(idToLoad, CmsResourceFilter.IGNORE_EXPIRATION.addRequireVisible());\n CmsResourceUtil resutil = new CmsResourceUtil(cms, resource);\n switch (entry.getType()) {\n case explorerFolder:\n title = CmsStringUtil.isEmpty(resutil.getTitle())\n ? CmsResource.getName(resource.getRootPath())\n : resutil.getTitle();\n break;\n case page:\n title = resutil.getTitle();\n break;\n }\n subtitle = resource.getRootPath();\n CmsResourceIcon icon = result.getResourceIcon();\n icon.initContent(resutil, CmsResource.STATE_UNCHANGED, false, false);\n } catch (CmsException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n }\n result.getTopLine().setValue(title);\n result.getBottomLine().setValue(subtitle);\n result.getProjectLabel().setValue(project);\n result.getSiteLabel().setValue(site);\n\n return result;\n\n }",
"protected final void setDefaultValue() {\n\n m_start = null;\n m_end = null;\n m_patterntype = PatternType.NONE;\n m_dayOfMonth = 0;\n m_exceptions.clear();\n m_individualDates.clear();\n m_interval = 0;\n m_isEveryWorkingDay = false;\n m_isWholeDay = false;\n m_month = Month.JANUARY;\n m_seriesEndDate = null;\n m_seriesOccurrences = 0;\n m_weekDays.clear();\n m_weeksOfMonth.clear();\n m_endType = EndType.SINGLE;\n m_parentSeriesId = null;\n }",
"public void addEmailStats(final InternetAddress[] recipients, final boolean storageUsed) {\n this.storageUsed = storageUsed;\n for (InternetAddress recipient: recipients) {\n emailDests.add(recipient.getAddress());\n }\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 }",
"public void setWorkingDay(Day day, boolean working)\n {\n setWorkingDay(day, (working ? DayType.WORKING : DayType.NON_WORKING));\n }",
"protected AbsoluteURI getGeneratedLocation(PersistedTrace trace) {\n\t\tAbsoluteURI path = trace.getPath();\n\t\tString fileName = traceFileNameProvider.getJavaFromTrace(path.getURI().toString());\n\t\treturn new AbsoluteURI(fileName);\n\t}",
"final public Boolean checkRealOffset() {\n if ((tokenRealOffset == null) || !provideRealOffset) {\n return false;\n } else if (tokenOffset == null) {\n return true;\n } else if (tokenOffset.getStart() == tokenRealOffset.getStart()\n && tokenOffset.getEnd() == tokenRealOffset.getEnd()) {\n return false;\n } else {\n return true;\n }\n }",
"public final static String process(final File file, final Configuration configuration) throws IOException\n {\n final FileInputStream input = new FileInputStream(file);\n final String ret = process(input, configuration);\n input.close();\n return ret;\n }",
"public static final String hexdump(byte[] buffer, int offset, int length, boolean ascii, int columns, String prefix)\n {\n StringBuilder sb = new StringBuilder();\n if (buffer != null)\n {\n int index = offset;\n DecimalFormat df = new DecimalFormat(\"00000\");\n\n while (index < (offset + length))\n {\n if (index + columns > (offset + length))\n {\n columns = (offset + length) - index;\n }\n\n sb.append(prefix);\n sb.append(df.format(index - offset));\n sb.append(\":\");\n sb.append(hexdump(buffer, index, columns, ascii));\n sb.append('\\n');\n\n index += columns;\n }\n }\n\n return (sb.toString());\n }"
] |
Read all task relationships from a GanttProject.
@param gpProject GanttProject project | [
"private void readRelationships(Project gpProject)\n {\n for (net.sf.mpxj.ganttproject.schema.Task gpTask : gpProject.getTasks().getTask())\n {\n readRelationships(gpTask);\n }\n }"
] | [
"protected AbsoluteURI getGeneratedLocation(PersistedTrace trace) {\n\t\tAbsoluteURI path = trace.getPath();\n\t\tString fileName = traceFileNameProvider.getJavaFromTrace(path.getURI().toString());\n\t\treturn new AbsoluteURI(fileName);\n\t}",
"protected <T, A> ActiveOperation<T, A> removeActiveOperation(Integer id) {\n final ActiveOperation<T, A> removed = removeUnderLock(id);\n if(removed != null) {\n for(final Map.Entry<Integer, ActiveRequest<?, ?>> requestEntry : requests.entrySet()) {\n final ActiveRequest<?, ?> request = requestEntry.getValue();\n if(request.context == removed) {\n requests.remove(requestEntry.getKey());\n }\n }\n }\n return removed;\n }",
"private InputStream runSparqlQuery(String query) throws IOException {\n\t\ttry {\n\t\t\tString queryString = \"query=\" + URLEncoder.encode(query, \"UTF-8\")\n\t\t\t\t\t+ \"&format=json\";\n\t\t\tURL url = new URL(\"https://query.wikidata.org/sparql?\"\n\t\t\t\t\t+ queryString);\n\t\t\tHttpURLConnection connection = (HttpURLConnection) url\n\t\t\t\t\t.openConnection();\n\t\t\tconnection.setRequestMethod(\"GET\");\n\n\t\t\treturn connection.getInputStream();\n\t\t} catch (UnsupportedEncodingException | MalformedURLException e) {\n\t\t\tthrow new RuntimeException(e.getMessage(), e);\n\t\t}\n\t}",
"@SuppressWarnings(\"WeakerAccess\")\n public int segmentHeight(final int segment, final boolean front) {\n final ByteBuffer bytes = getData();\n if (isColor) {\n final int base = segment * 6;\n final int frontHeight = Util.unsign(bytes.get(base + 5));\n if (front) {\n return frontHeight;\n } else {\n return Math.max(frontHeight, Math.max(Util.unsign(bytes.get(base + 3)), Util.unsign(bytes.get(base + 4))));\n }\n } else {\n return getData().get(segment * 2) & 0x1f;\n }\n }",
"public void clearHandlers() {\r\n\r\n for (Map<String, CmsAttributeHandler> handlers : m_handlers) {\r\n for (CmsAttributeHandler handler : handlers.values()) {\r\n handler.clearHandlers();\r\n }\r\n handlers.clear();\r\n }\r\n m_handlers.clear();\r\n m_handlers.add(new HashMap<String, CmsAttributeHandler>());\r\n m_handlerById.clear();\r\n }",
"@Override\n\tpublic double getDiscountFactor(AnalyticModelInterface model, double maturity)\n\t{\n\t\t// Change time scale\n\t\tmaturity *= timeScaling;\n\n\t\tdouble beta1\t= parameter[0];\n\t\tdouble beta2\t= parameter[1];\n\t\tdouble beta3\t= parameter[2];\n\t\tdouble beta4\t= parameter[3];\n\t\tdouble tau1\t\t= parameter[4];\n\t\tdouble tau2\t\t= parameter[5];\n\n\t\tdouble x1 = tau1 > 0 ? FastMath.exp(-maturity/tau1) : 0.0;\n\t\tdouble x2 = tau2 > 0 ? FastMath.exp(-maturity/tau2) : 0.0;\n\n\t\tdouble y1 = tau1 > 0 ? (maturity > 0.0 ? (1.0-x1)/maturity*tau1 : 1.0) : 0.0;\n\t\tdouble y2 = tau2 > 0 ? (maturity > 0.0 ? (1.0-x2)/maturity*tau2 : 1.0) : 0.0;\n\n\t\tdouble zeroRate = beta1 + beta2 * y1 + beta3 * (y1-x1) + beta4 * (y2-x2);\n\n\t\treturn Math.exp(- zeroRate * maturity);\n\t}",
"public void setDuration(float start, float end)\n {\n for (GVRAnimation anim : mAnimations)\n {\n anim.setDuration(start,end);\n }\n }",
"public Stats getCollectionStats(String collectionId, Date date) throws FlickrException {\n return getStats(METHOD_GET_COLLECTION_STATS, \"collection_id\", collectionId, date);\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}"
] |
Processes the template for all columns of the current table index.
@param template The template
@param attributes The attributes of the tag
@exception XDocletException if an error occurs
@doc.tag type="block" | [
"public void forAllIndexColumns(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _curIndexDef.getColumns(); it.hasNext(); )\r\n {\r\n _curColumnDef = _curTableDef.getColumn((String)it.next());\r\n generate(template);\r\n }\r\n _curColumnDef = null;\r\n }"
] | [
"private void processTasks() throws SQLException\n {\n //\n // Yes... we could probably read this in one query in the right order\n // using a CTE... but life's too short.\n //\n List<Row> rows = getRows(\"select * from zscheduleitem where zproject=? and zparentactivity_ is null and z_ent=? order by zorderinparentactivity\", m_projectID, m_entityMap.get(\"Activity\"));\n for (Row row : rows)\n {\n Task task = m_project.addTask();\n populateTask(row, task);\n processChildTasks(task);\n }\n }",
"private void setQR(DMatrixRMaj Q , DMatrixRMaj R , int growRows ) {\n if( Q.numRows != Q.numCols ) {\n throw new IllegalArgumentException(\"Q should be square.\");\n }\n\n this.Q = Q;\n this.R = R;\n\n m = Q.numRows;\n n = R.numCols;\n\n if( m+growRows > maxRows || n > maxCols ) {\n if( autoGrow ) {\n declareInternalData(m+growRows,n);\n } else {\n throw new IllegalArgumentException(\"Autogrow has been set to false and the maximum number of rows\" +\n \" or columns has been exceeded.\");\n }\n }\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 }",
"public static AppDescriptor deserializeFrom(byte[] bytes) {\n try {\n ByteArrayInputStream bais = new ByteArrayInputStream(bytes);\n ObjectInputStream ois = new ObjectInputStream(bais);\n return (AppDescriptor) ois.readObject();\n } catch (IOException e) {\n throw E.ioException(e);\n } catch (ClassNotFoundException e) {\n throw E.unexpected(e);\n }\n }",
"public static Integer convertOverrideIdentifier(String overrideIdentifier) throws Exception {\n Integer overrideId = -1;\n\n try {\n // there is an issue with parseInt where it does not parse negative values correctly\n boolean isNegative = false;\n if (overrideIdentifier.startsWith(\"-\")) {\n isNegative = true;\n overrideIdentifier = overrideIdentifier.substring(1);\n }\n overrideId = Integer.parseInt(overrideIdentifier);\n\n if (isNegative) {\n overrideId = 0 - overrideId;\n }\n } catch (NumberFormatException ne) {\n // this is OK.. just means it's not a #\n\n // split into two parts\n String className = null;\n String methodName = null;\n int lastDot = overrideIdentifier.lastIndexOf(\".\");\n className = overrideIdentifier.substring(0, lastDot);\n methodName = overrideIdentifier.substring(lastDot + 1);\n\n overrideId = OverrideService.getInstance().getOverrideIdForMethod(className, methodName);\n }\n\n return overrideId;\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 final void setHost(final String host) throws UnknownHostException {\n this.host = host;\n final InetAddress[] inetAddresses = InetAddress.getAllByName(host);\n\n for (InetAddress address: inetAddresses) {\n final AddressHostMatcher matcher = new AddressHostMatcher();\n matcher.setIp(address.getHostAddress());\n this.matchersForHost.add(matcher);\n }\n }",
"@Override\n public void populateObject(ProcessedCommand<Command<CI>, CI> processedCommand, InvocationProviders invocationProviders,\n AeshContext aeshContext, CommandLineParser.Mode mode)\n throws CommandLineParserException, OptionValidatorException {\n if(processedCommand.parserExceptions().size() > 0 && mode == CommandLineParser.Mode.VALIDATE)\n throw processedCommand.parserExceptions().get(0);\n for(ProcessedOption option : processedCommand.getOptions()) {\n if(option.getValues() != null && option.getValues().size() > 0)\n option.injectValueIntoField(getObject(), invocationProviders, aeshContext,\n mode == CommandLineParser.Mode.VALIDATE );\n else if(option.getDefaultValues().size() > 0) {\n option.injectValueIntoField(getObject(), invocationProviders, aeshContext,\n mode == CommandLineParser.Mode.VALIDATE);\n }\n else if(option.getOptionType().equals(OptionType.GROUP) && option.getProperties().size() > 0)\n option.injectValueIntoField(getObject(), invocationProviders, aeshContext,\n mode == CommandLineParser.Mode.VALIDATE);\n else\n resetField(getObject(), option.getFieldName(), option.hasValue());\n }\n //arguments\n if(processedCommand.getArguments() != null &&\n (processedCommand.getArguments().getValues().size() > 0 || processedCommand.getArguments().getDefaultValues().size() > 0))\n processedCommand.getArguments().injectValueIntoField(getObject(), invocationProviders, aeshContext,\n mode == CommandLineParser.Mode.VALIDATE);\n else if(processedCommand.getArguments() != null)\n resetField(getObject(), processedCommand.getArguments().getFieldName(), true);\n //argument\n if(processedCommand.getArgument() != null &&\n (processedCommand.getArgument().getValues().size() > 0 || processedCommand.getArgument().getDefaultValues().size() > 0))\n processedCommand.getArgument().injectValueIntoField(getObject(), invocationProviders, aeshContext,\n mode == CommandLineParser.Mode.VALIDATE);\n else if(processedCommand.getArgument() != null)\n resetField(getObject(), processedCommand.getArgument().getFieldName(), true);\n }",
"public void moveDown(I_CmsEditableGroupRow row) {\n\n int index = m_container.getComponentIndex(row);\n if ((index >= 0) && (index < (m_container.getComponentCount() - 1))) {\n m_container.removeComponent(row);\n m_container.addComponent(row, index + 1);\n }\n updateButtonBars();\n }"
] |
Sets the fieldConversion.
@param fieldConversionClassName The fieldConversion to set | [
"public void setFieldConversionClassName(String fieldConversionClassName)\r\n {\r\n try\r\n {\r\n this.fieldConversion = (FieldConversion) ClassHelper.newInstance(fieldConversionClassName);\r\n }\r\n catch (Exception e)\r\n {\r\n throw new MetadataException(\r\n \"Could not instantiate FieldConversion class using default constructor\", e);\r\n }\r\n }"
] | [
"public Collection<SerialMessage> initialize() {\r\n\t\tArrayList<SerialMessage> result = new ArrayList<SerialMessage>();\r\n\t\t\r\n\t\tif (this.getNode().getManufacturer() == 0x010F && this.getNode().getDeviceType() == 0x0501) {\r\n\t\t\t\tlogger.warn(\"Detected Fibaro FGBS001 Universal Sensor - this device fails to respond to SENSOR_ALARM_GET and SENSOR_ALARM_SUPPORTED_GET.\");\r\n\t\t\t\treturn result;\r\n\t\t}\r\n\t\t\r\n\t\tresult.add(this.getSupportedMessage());\r\n\t\treturn result;\r\n\t}",
"public void setPerms(String photoId, Permissions permissions) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SET_PERMS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"is_public\", permissions.isPublicFlag() ? \"1\" : \"0\");\r\n parameters.put(\"is_friend\", permissions.isFriendFlag() ? \"1\" : \"0\");\r\n parameters.put(\"is_family\", permissions.isFamilyFlag() ? \"1\" : \"0\");\r\n parameters.put(\"perm_comment\", Integer.toString(permissions.getComment()));\r\n parameters.put(\"perm_addmeta\", Integer.toString(permissions.getAddmeta()));\r\n\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"public Pair<int[][][], int[]> documentToDataAndLabels(List<IN> document) {\r\n\r\n int docSize = document.size();\r\n // first index is position in the document also the index of the\r\n // clique/factor table\r\n // second index is the number of elements in the clique/window these\r\n // features are for (starting with last element)\r\n // third index is position of the feature in the array that holds them\r\n // element in data[j][k][m] is the index of the mth feature occurring in\r\n // position k of the jth clique\r\n int[][][] data = new int[docSize][windowSize][];\r\n // index is the position in the document\r\n // element in labels[j] is the index of the correct label (if it exists) at\r\n // position j of document\r\n int[] labels = new int[docSize];\r\n\r\n if (flags.useReverse) {\r\n Collections.reverse(document);\r\n }\r\n\r\n // System.err.println(\"docSize:\"+docSize);\r\n for (int j = 0; j < docSize; j++) {\r\n CRFDatum<List<String>, CRFLabel> d = makeDatum(document, j, featureFactory);\r\n\r\n List<List<String>> features = d.asFeatures();\r\n for (int k = 0, fSize = features.size(); k < fSize; k++) {\r\n Collection<String> cliqueFeatures = features.get(k);\r\n data[j][k] = new int[cliqueFeatures.size()];\r\n int m = 0;\r\n for (String feature : cliqueFeatures) {\r\n int index = featureIndex.indexOf(feature);\r\n if (index >= 0) {\r\n data[j][k][m] = index;\r\n m++;\r\n } else {\r\n // this is where we end up when we do feature threshold cutoffs\r\n }\r\n }\r\n // Reduce memory use when some features were cut out by threshold\r\n if (m < data[j][k].length) {\r\n int[] f = new int[m];\r\n System.arraycopy(data[j][k], 0, f, 0, m);\r\n data[j][k] = f;\r\n }\r\n }\r\n\r\n IN wi = document.get(j);\r\n labels[j] = classIndex.indexOf(wi.get(AnswerAnnotation.class));\r\n }\r\n\r\n if (flags.useReverse) {\r\n Collections.reverse(document);\r\n }\r\n\r\n // System.err.println(\"numClasses: \"+classIndex.size()+\" \"+classIndex);\r\n // System.err.println(\"numDocuments: 1\");\r\n // System.err.println(\"numDatums: \"+data.length);\r\n // System.err.println(\"numFeatures: \"+featureIndex.size());\r\n\r\n return new Pair<int[][][], int[]>(data, labels);\r\n }",
"public void actionPerformed(java.awt.event.ActionEvent actionEvent)\r\n {\r\n new Thread()\r\n {\r\n public void run()\r\n {\r\n final java.sql.Connection conn = new JDlgDBConnection(containingFrame, false).showAndReturnConnection();\r\n if (conn != null)\r\n {\r\n javax.swing.SwingUtilities.invokeLater(new Runnable()\r\n {\r\n public void run()\r\n {\r\n JIFrmDatabase frm = new JIFrmDatabase(conn);\r\n containingFrame.getContentPane().add(frm);\r\n frm.setVisible(true);\r\n }\r\n });\r\n }\r\n }\r\n }.start();\r\n }",
"private EditorState getDefaultState() {\n\n List<TableProperty> cols = new ArrayList<TableProperty>(1);\n cols.add(TableProperty.TRANSLATION);\n\n return new EditorState(cols, false);\n }",
"public Path relativize(Path other) {\n\t\tif (other.isAbsolute() != isAbsolute())\n\t\t\tthrow new IllegalArgumentException(\"This path and the given path are not both absolute or both relative: \" + toString() + \" | \" + other.toString());\n\t\tif (startsWith(other)) {\n\t\t\treturn internalRelativize(this, other);\n\t\t} else if (other.startsWith(this)) {\n\t\t\treturn internalRelativize(other, this);\n\t\t}\n\t\treturn null;\n\t}",
"public RandomVariableInterface[] getBasisFunctions(double exerciseDate, LIBORModelMonteCarloSimulationInterface model) throws CalculationException {\n\n\t\tArrayList<RandomVariableInterface> basisFunctions = new ArrayList<RandomVariableInterface>();\n\n\t\tRandomVariableInterface basisFunction;\n\n\t\t// Constant\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tbasisFunctions.add(basisFunction);\n\n\t\t// LIBORs\n\t\tint liborPeriodIndex, liborPeriodIndexEnd;\n\t\tRandomVariableInterface rate;\n\n\t\t// 1 Period\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tliborPeriodIndex = model.getLiborPeriodIndex(exerciseDate);\n\t\tif(liborPeriodIndex < 0) {\n\t\t\tliborPeriodIndex = -liborPeriodIndex-1;\n\t\t}\n\t\tliborPeriodIndexEnd = liborPeriodIndex+1;\n\t\tdouble periodLength1 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex);\n\n\t\trate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd));\n\t\tbasisFunction = basisFunction.discount(rate, periodLength1);\n\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\tbasisFunction = basisFunction.discount(rate, periodLength1);\n\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t// n/2 Period\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tliborPeriodIndex = model.getLiborPeriodIndex(exerciseDate);\n\t\tif(liborPeriodIndex < 0) {\n\t\t\tliborPeriodIndex = -liborPeriodIndex-1;\n\t\t}\n\t\tliborPeriodIndexEnd = (liborPeriodIndex + model.getNumberOfLibors())/2;\n\n\t\tdouble periodLength2 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex);\n\n\t\tif(periodLength2 != periodLength1) {\n\t\t\trate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd));\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength2);\n\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength2);\n\t\t\t//\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength2);\n\t\t\t//\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\t\t}\n\n\n\t\t// n Period\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tliborPeriodIndex = model.getLiborPeriodIndex(exerciseDate);\n\t\tif(liborPeriodIndex < 0) {\n\t\t\tliborPeriodIndex = -liborPeriodIndex-1;\n\t\t}\n\t\tliborPeriodIndexEnd = model.getNumberOfLibors();\n\t\tdouble periodLength3 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex);\n\n\t\tif(periodLength3 != periodLength1 && periodLength3 != periodLength2) {\n\t\t\trate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd));\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength3);\n\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength3);\n\t\t\t//\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\t\t}\n\n\t\treturn basisFunctions.toArray(new RandomVariableInterface[0]);\n\t}",
"public static base_responses disable(nitro_service client, Long clid[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (clid != null && clid.length > 0) {\n\t\t\tclusterinstance disableresources[] = new clusterinstance[clid.length];\n\t\t\tfor (int i=0;i<clid.length;i++){\n\t\t\t\tdisableresources[i] = new clusterinstance();\n\t\t\t\tdisableresources[i].clid = clid[i];\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, disableresources,\"disable\");\n\t\t}\n\t\treturn result;\n\t}",
"private List<I_CmsSearchFieldMapping> getMappings() {\n\n CmsSearchManager manager = OpenCms.getSearchManager();\n I_CmsSearchFieldConfiguration fieldConfig = manager.getFieldConfiguration(getParamFieldconfiguration());\n CmsLuceneField field;\n List<I_CmsSearchFieldMapping> result = null;\n Iterator<CmsSearchField> itFields;\n if (fieldConfig != null) {\n itFields = fieldConfig.getFields().iterator();\n while (itFields.hasNext()) {\n field = (CmsLuceneField)itFields.next();\n if (field.getName().equals(getParamField())) {\n result = field.getMappings();\n }\n }\n } else {\n result = Collections.emptyList();\n if (LOG.isErrorEnabled()) {\n LOG.error(\n Messages.get().getBundle().key(\n Messages.ERR_SEARCHINDEX_EDIT_MISSING_PARAM_1,\n A_CmsFieldConfigurationDialog.PARAM_FIELDCONFIGURATION));\n }\n }\n return result;\n }"
] |
Return the list of corporate GroupId prefix configured for an organization.
@param organizationId String Organization name
@return Response A list of corporate groupId prefix in HTML or JSON | [
"@GET\n @Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON})\n @Path(\"/{name}\" + ServerAPI.GET_CORPORATE_GROUPIDS)\n public Response getCorporateGroupIdPrefix(@PathParam(\"name\") final String organizationId){\n LOG.info(\"Got a get corporate groupId prefix request for organization \" + organizationId +\".\");\n\n final ListView view = new ListView(\"Organization \" + organizationId, \"Corporate GroupId Prefix\");\n final List<String> corporateGroupIds = getOrganizationHandler().getCorporateGroupIds(organizationId);\n view.addAll(corporateGroupIds);\n\n return Response.ok(view).build();\n }"
] | [
"private void writeResource(Resource mpxjResource, net.sf.mpxj.planner.schema.Resource plannerResource)\n {\n ProjectCalendar resourceCalendar = mpxjResource.getResourceCalendar();\n if (resourceCalendar != null)\n {\n plannerResource.setCalendar(getIntegerString(resourceCalendar.getUniqueID()));\n }\n\n plannerResource.setEmail(mpxjResource.getEmailAddress());\n plannerResource.setId(getIntegerString(mpxjResource.getUniqueID()));\n plannerResource.setName(getString(mpxjResource.getName()));\n plannerResource.setNote(mpxjResource.getNotes());\n plannerResource.setShortName(mpxjResource.getInitials());\n plannerResource.setType(mpxjResource.getType() == ResourceType.MATERIAL ? \"2\" : \"1\");\n //plannerResource.setStdRate();\n //plannerResource.setOvtRate();\n plannerResource.setUnits(\"0\");\n //plannerResource.setProperties();\n m_eventManager.fireResourceWrittenEvent(mpxjResource);\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 }",
"@SuppressWarnings(\"serial\")\n private Component createCloseButton() {\n\n Button closeBtn = CmsToolBar.createButton(\n FontOpenCms.CIRCLE_INV_CANCEL,\n m_messages.key(Messages.GUI_BUTTON_CANCEL_0));\n closeBtn.addClickListener(new ClickListener() {\n\n public void buttonClick(ClickEvent event) {\n\n closeAction();\n }\n\n });\n return closeBtn;\n }",
"void killAll()\n {\n for (RjiRegistration reg : this.instancesById.values().toArray(new RjiRegistration[] {}))\n {\n reg.rji.handleInstruction(Instruction.KILL);\n }\n }",
"public static appfwpolicylabel_stats get(nitro_service service, String labelname) throws Exception{\n\t\tappfwpolicylabel_stats obj = new appfwpolicylabel_stats();\n\t\tobj.set_labelname(labelname);\n\t\tappfwpolicylabel_stats response = (appfwpolicylabel_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"public void handle(HttpRequest request, HttpResponder responder) {\n if (urlRewriter != null) {\n try {\n request.setUri(URI.create(request.uri()).normalize().toString());\n if (!urlRewriter.rewrite(request, responder)) {\n return;\n }\n } catch (Throwable t) {\n responder.sendString(HttpResponseStatus.INTERNAL_SERVER_ERROR,\n String.format(\"Caught exception processing request. Reason: %s\",\n t.getMessage()));\n LOG.error(\"Exception thrown during rewriting of uri {}\", request.uri(), t);\n return;\n }\n }\n\n try {\n String path = URI.create(request.uri()).normalize().getPath();\n\n List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>> routableDestinations\n = patternRouter.getDestinations(path);\n\n PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel> matchedDestination =\n getMatchedDestination(routableDestinations, request.method(), path);\n\n if (matchedDestination != null) {\n //Found a httpresource route to it.\n HttpResourceModel httpResourceModel = matchedDestination.getDestination();\n\n // Call preCall method of handler hooks.\n boolean terminated = false;\n HandlerInfo info = new HandlerInfo(httpResourceModel.getMethod().getDeclaringClass().getName(),\n httpResourceModel.getMethod().getName());\n for (HandlerHook hook : handlerHooks) {\n if (!hook.preCall(request, responder, info)) {\n // Terminate further request processing if preCall returns false.\n terminated = true;\n break;\n }\n }\n\n // Call httpresource method\n if (!terminated) {\n // Wrap responder to make post hook calls.\n responder = new WrappedHttpResponder(responder, handlerHooks, request, info);\n if (httpResourceModel.handle(request, responder, matchedDestination.getGroupNameValues()).isStreaming()) {\n responder.sendString(HttpResponseStatus.METHOD_NOT_ALLOWED,\n String.format(\"Body Consumer not supported for internalHttpResponder: %s\",\n request.uri()));\n }\n }\n } else if (routableDestinations.size() > 0) {\n //Found a matching resource but could not find the right HttpMethod so return 405\n responder.sendString(HttpResponseStatus.METHOD_NOT_ALLOWED,\n String.format(\"Problem accessing: %s. Reason: Method Not Allowed\", request.uri()));\n } else {\n responder.sendString(HttpResponseStatus.NOT_FOUND, String.format(\"Problem accessing: %s. Reason: Not Found\",\n request.uri()));\n }\n } catch (Throwable t) {\n responder.sendString(HttpResponseStatus.INTERNAL_SERVER_ERROR,\n String.format(\"Caught exception processing request. Reason: %s\", t.getMessage()));\n LOG.error(\"Exception thrown during request processing for uri {}\", request.uri(), t);\n }\n }",
"private 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 }",
"private SpellCheckResponse performSpellcheckQuery(CmsSpellcheckingRequest request) {\n\n if ((null == request) || !request.isInitialized()) {\n return null;\n }\n\n final String[] wordsToCheck = request.m_wordsToCheck;\n\n final ModifiableSolrParams params = new ModifiableSolrParams();\n params.set(\"spellcheck\", \"true\");\n params.set(\"spellcheck.dictionary\", request.m_dictionaryToUse);\n params.set(\"spellcheck.extendedResults\", \"true\");\n\n // Build one string from array of words and use it as query.\n final StringBuilder builder = new StringBuilder();\n for (int i = 0; i < wordsToCheck.length; i++) {\n builder.append(wordsToCheck[i] + \" \");\n }\n\n params.set(\"spellcheck.q\", builder.toString());\n\n final SolrQuery query = new SolrQuery();\n query.setRequestHandler(\"/spell\");\n query.add(params);\n\n try {\n QueryResponse qres = m_solrClient.query(query);\n return qres.getSpellCheckResponse();\n } catch (Exception e) {\n LOG.debug(\"Exception while performing spellcheck query...\", e);\n }\n\n return null;\n }",
"public Where<T, ID> raw(String rawStatement, ArgumentHolder... args) {\n\t\tfor (ArgumentHolder arg : args) {\n\t\t\tString columnName = arg.getColumnName();\n\t\t\tif (columnName == null) {\n\t\t\t\tif (arg.getSqlType() == null) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"Either the column name or SqlType must be set on each argument\");\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\targ.setMetaInfo(findColumnFieldType(columnName));\n\t\t\t}\n\t\t}\n\t\taddClause(new Raw(rawStatement, args));\n\t\treturn this;\n\t}"
] |
Returns a string to resolve apostrophe issue in xpath
@param text
@return the apostrophe resolved xpath value string | [
"protected String escapeApostrophes(String text) {\r\n\t\tString resultString;\r\n\t\tif (text.contains(\"'\")) {\r\n\t\t\tStringBuilder stringBuilder = new StringBuilder();\r\n\t\t\tstringBuilder.append(\"concat('\");\r\n\t\t\tstringBuilder.append(text.replace(\"'\", \"',\\\"'\\\",'\"));\r\n\t\t\tstringBuilder.append(\"')\");\r\n\t\t\tresultString = stringBuilder.toString();\r\n\t\t} else {\r\n\t\t\tresultString = \"'\" + text + \"'\";\r\n\t\t}\r\n\t\treturn resultString;\r\n\t}"
] | [
"public VALUE put(KEY key, VALUE object) {\n CacheEntry<VALUE> entry;\n if (referenceType == ReferenceType.WEAK) {\n entry = new CacheEntry<>(new WeakReference<>(object), null);\n } else if (referenceType == ReferenceType.SOFT) {\n entry = new CacheEntry<>(new SoftReference<>(object), null);\n } else {\n entry = new CacheEntry<>(null, object);\n }\n\n countPutCountSinceEviction++;\n countPut++;\n if (isExpiring && nextCleanUpTimestamp == 0) {\n nextCleanUpTimestamp = System.currentTimeMillis() + expirationMillis + 1;\n }\n\n CacheEntry<VALUE> oldEntry;\n synchronized (this) {\n if (values.size() >= maxSize) {\n evictToTargetSize(maxSize - 1);\n }\n oldEntry = values.put(key, entry);\n }\n return getValueForRemoved(oldEntry);\n }",
"public static Configuration getDefaultFreemarkerConfiguration()\n {\n freemarker.template.Configuration configuration = new freemarker.template.Configuration(Configuration.VERSION_2_3_26);\n DefaultObjectWrapperBuilder objectWrapperBuilder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_26);\n objectWrapperBuilder.setUseAdaptersForContainers(true);\n objectWrapperBuilder.setIterableSupport(true);\n configuration.setObjectWrapper(objectWrapperBuilder.build());\n configuration.setAPIBuiltinEnabled(true);\n\n configuration.setTemplateLoader(new FurnaceFreeMarkerTemplateLoader());\n configuration.setTemplateUpdateDelayMilliseconds(3600);\n return configuration;\n }",
"private 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 void setBoneName(int boneindex, String bonename)\n {\n mBoneNames[boneindex] = bonename;\n NativeSkeleton.setBoneName(getNative(), boneindex, bonename);\n }",
"public List<String> asList() {\n final List<String> result = new ArrayList<>();\n for (Collection<Argument> args : map.values()) {\n for (Argument arg : args) {\n result.add(arg.asCommandLineArgument());\n }\n }\n return result;\n }",
"protected void processLabels(List<MonolingualTextValue> labels) {\n for(MonolingualTextValue label : labels) {\n \tString lang = label.getLanguageCode();\n \tNameWithUpdate currentValue = newLabels.get(lang);\n \tif (currentValue == null || !currentValue.value.equals(label)) {\n\t newLabels.put(lang,\n\t new NameWithUpdate(label, true));\n\t \n\t // Delete any alias that matches the new label\n\t AliasesWithUpdate currentAliases = newAliases.get(lang);\n\t if (currentAliases != null && currentAliases.aliases.contains(label)) {\n\t \tdeleteAlias(label);\n\t }\n \t}\n }\n \n }",
"private GenericCriteriaPrompt getPromptValue(FieldType field, byte[] block)\n {\n int textOffset = getPromptOffset(block);\n String value = MPPUtility.getUnicodeString(m_criteriaData, m_criteriaTextStart + textOffset);\n GenericCriteriaPrompt prompt = new GenericCriteriaPrompt(field.getDataType(), value);\n if (m_prompts != null)\n {\n m_prompts.add(prompt);\n }\n return prompt;\n }",
"protected EntityKey getEntityKey(Tuple tuple, AssociatedEntityKeyMetadata associatedEntityKeyMetadata) {\n\t\tObject[] columnValues = new Object[ associatedEntityKeyMetadata.getAssociationKeyColumns().length];\n\t\tint i = 0;\n\n\t\tfor ( String associationKeyColumn : associatedEntityKeyMetadata.getAssociationKeyColumns() ) {\n\t\t\tcolumnValues[i] = tuple.get( associationKeyColumn );\n\t\t\ti++;\n\t\t}\n\n\t\treturn new EntityKey( associatedEntityKeyMetadata.getEntityKeyMetadata(), columnValues );\n\t}",
"@RequestMapping(value = \"api/edit/disableAll\", method = RequestMethod.POST)\n public\n @ResponseBody\n String disableAll(Model model, int profileID,\n @RequestParam(defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) {\n editService.disableAll(profileID, clientUUID);\n return null;\n }"
] |
Ends interception context if it was previously stated. This is indicated by a local variable with index 0. | [
"void endIfStarted(CodeAttribute b, ClassMethod method) {\n b.aload(getLocalVariableIndex(0));\n b.dup();\n final BranchEnd ifnotnull = b.ifnull();\n b.checkcast(Stack.class);\n b.invokevirtual(Stack.class.getName(), END_INTERCEPTOR_CONTEXT_METHOD_NAME, EMPTY_PARENTHESES + VOID_CLASS_DESCRIPTOR);\n BranchEnd ifnull = b.gotoInstruction();\n b.branchEnd(ifnotnull);\n b.pop(); // remove null Stack\n b.branchEnd(ifnull);\n }"
] | [
"public void addJobType(final String jobName, final Class<?> jobType) {\n checkJobType(jobName, jobType);\n this.jobTypes.put(jobName, jobType);\n }",
"public Duration getWork(FastTrackField type)\n {\n Double value = (Double) getObject(type);\n return value == null ? null : Duration.getInstance(value.doubleValue(), m_table.getWorkTimeUnit());\n }",
"public void removeNodeMetaData(Object key) {\n if (key==null) throw new GroovyBugError(\"Tried to remove meta data with null key \"+this+\".\");\n if (metaDataMap == null) {\n return;\n }\n metaDataMap.remove(key);\n }",
"public void initialize(BinaryPackageControlFile packageControlFile) {\n set(\"Binary\", packageControlFile.get(\"Package\"));\n set(\"Source\", Utils.defaultString(packageControlFile.get(\"Source\"), packageControlFile.get(\"Package\")));\n set(\"Architecture\", packageControlFile.get(\"Architecture\"));\n set(\"Version\", packageControlFile.get(\"Version\"));\n set(\"Maintainer\", packageControlFile.get(\"Maintainer\"));\n set(\"Changed-By\", packageControlFile.get(\"Maintainer\"));\n set(\"Distribution\", packageControlFile.get(\"Distribution\"));\n\n for (Entry<String, String> entry : packageControlFile.getUserDefinedFields().entrySet()) {\n set(entry.getKey(), entry.getValue());\n }\n\n StringBuilder description = new StringBuilder();\n description.append(packageControlFile.get(\"Package\"));\n if (packageControlFile.get(\"Description\") != null) {\n description.append(\" - \");\n description.append(packageControlFile.getShortDescription());\n }\n set(\"Description\", description.toString());\n }",
"public static String getStatusForItem(Long lastActivity) {\n\n if (lastActivity.longValue() < CmsSessionsTable.INACTIVE_LIMIT) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_MESSAGES_BROADCAST_COLS_STATUS_ACTIVE_0);\n }\n return CmsVaadinUtils.getMessageText(Messages.GUI_MESSAGES_BROADCAST_COLS_STATUS_INACTIVE_0);\n }",
"public <U> CoreRemoteMongoIterable<U> map(final Function<ResultT, U> mapper) {\n return new CoreRemoteMappingIterable<>(this, mapper);\n }",
"public static String findReplacement(final String variableName, final Date date) {\n if (variableName.equalsIgnoreCase(\"date\")) {\n return cleanUpName(DateFormat.getDateInstance().format(date));\n } else if (variableName.equalsIgnoreCase(\"datetime\")) {\n return cleanUpName(DateFormat.getDateTimeInstance().format(date));\n } else if (variableName.equalsIgnoreCase(\"time\")) {\n return cleanUpName(DateFormat.getTimeInstance().format(date));\n } else {\n try {\n return new SimpleDateFormat(variableName).format(date);\n } catch (Exception e) {\n LOGGER.error(\"Unable to format timestamp according to pattern: {}\", variableName, e);\n return \"${\" + variableName + \"}\";\n }\n }\n }",
"protected void appendWhereClause(FieldDescriptor[] fields, StringBuffer stmt) throws PersistenceBrokerException\r\n {\r\n stmt.append(\" WHERE \");\r\n\r\n for(int i = 0; i < fields.length; i++)\r\n {\r\n FieldDescriptor fmd = fields[i];\r\n\r\n stmt.append(fmd.getColumnName());\r\n stmt.append(\" = ? \");\r\n if(i < fields.length - 1)\r\n {\r\n stmt.append(\" AND \");\r\n }\r\n }\r\n }",
"SimpleJsonEncoder appendToJSONUnquoted(final String key, final Object value) {\n if (closed) {\n throw new IllegalStateException(\"Encoder already closed\");\n }\n if (value != null) {\n appendKey(key);\n sb.append(value);\n }\n return this;\n }"
] |
Creates the operation to add a resource.
@param address the address of the operation to add.
@param properties the properties to set for the resource.
@return the operation. | [
"private ModelNode buildAddOperation(final ModelNode address, final Map<String, String> properties) {\n final ModelNode op = ServerOperations.createAddOperation(address);\n for (Map.Entry<String, String> prop : properties.entrySet()) {\n final String[] props = prop.getKey().split(\",\");\n if (props.length == 0) {\n throw new RuntimeException(\"Invalid property \" + prop);\n }\n ModelNode node = op;\n for (int i = 0; i < props.length - 1; ++i) {\n node = node.get(props[i]);\n }\n final String value = prop.getValue() == null ? \"\" : prop.getValue();\n if (value.startsWith(\"!!\")) {\n handleDmrString(node, props[props.length - 1], value);\n } else {\n node.get(props[props.length - 1]).set(value);\n }\n }\n return op;\n }"
] | [
"public static URI setQueryParams(final URI initialUri, final Multimap<String, String> queryParams) {\n StringBuilder queryString = new StringBuilder();\n for (Map.Entry<String, String> entry: queryParams.entries()) {\n if (queryString.length() > 0) {\n queryString.append(\"&\");\n }\n queryString.append(entry.getKey()).append(\"=\").append(entry.getValue());\n }\n try {\n if (initialUri.getHost() == null && initialUri.getAuthority() != null) {\n return new URI(initialUri.getScheme(), initialUri.getAuthority(), initialUri.getPath(),\n queryString.toString(),\n initialUri.getFragment());\n } else {\n return new URI(initialUri.getScheme(), initialUri.getUserInfo(), initialUri.getHost(),\n initialUri.getPort(),\n initialUri.getPath(),\n queryString.toString(), initialUri.getFragment());\n }\n } catch (URISyntaxException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }",
"@Override\n public FileModel resolvePayload(GraphRewrite event, EvaluationContext context, WindupVertexFrame payload)\n {\n checkVariableName(event, context);\n if (payload instanceof FileReferenceModel)\n {\n return ((FileReferenceModel) payload).getFile();\n }\n if (payload instanceof FileModel)\n {\n return (FileModel) payload;\n }\n return null;\n }",
"public static callhome get(nitro_service service) throws Exception{\n\t\tcallhome obj = new callhome();\n\t\tcallhome[] response = (callhome[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"protected static CallableStatement memorize(final CallableStatement target, final ConnectionHandle connectionHandle) {\n\t\treturn (CallableStatement) Proxy.newProxyInstance(\n\t\t\t\tCallableStatementProxy.class.getClassLoader(),\n\t\t\t\tnew Class[] {CallableStatementProxy.class},\n\t\t\t\tnew MemorizeTransactionProxy(target, connectionHandle));\n\t}",
"public float getTexCoordU(int vertex, int coords) {\n if (!hasTexCoords(coords)) {\n throw new IllegalStateException(\n \"mesh has no texture coordinate set \" + coords);\n }\n \n checkVertexIndexBounds(vertex);\n /* bound checks for coords are done by java for us */\n \n return m_texcoords[coords].getFloat(\n vertex * m_numUVComponents[coords] * SIZEOF_FLOAT);\n }",
"public MetaClassRegistryChangeEventListener[] getMetaClassRegistryChangeEventListeners() {\n synchronized (changeListenerList) {\n ArrayList<MetaClassRegistryChangeEventListener> ret =\n new ArrayList<MetaClassRegistryChangeEventListener>(changeListenerList.size()+nonRemoveableChangeListenerList.size());\n ret.addAll(nonRemoveableChangeListenerList);\n ret.addAll(changeListenerList);\n return ret.toArray(new MetaClassRegistryChangeEventListener[ret.size()]);\n }\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<DiscordianDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<DiscordianDate>) super.zonedDateTime(temporal);\n }",
"void updateFromResponseOnPutPatch(Response<ResponseBody> response) throws CloudException, IOException {\n String responseContent = null;\n if (response.body() != null) {\n responseContent = response.body().string();\n response.body().close();\n }\n\n if (responseContent == null || responseContent.isEmpty()) {\n throw new CloudException(\"polling response does not contain a valid body\", response);\n }\n\n PollingResource resource = serializerAdapter.deserialize(responseContent, PollingResource.class);\n final int statusCode = response.code();\n if (resource != null && resource.properties != null && resource.properties.provisioningState != null) {\n this.withStatus(resource.properties.provisioningState, statusCode);\n } else {\n this.withStatus(AzureAsyncOperation.SUCCESS_STATUS, statusCode);\n }\n\n CloudError error = new CloudError();\n this.withErrorBody(error);\n error.withCode(this.status());\n error.withMessage(\"Long running operation failed\");\n this.withResponse(response);\n this.withResource(serializerAdapter.<T>deserialize(responseContent, resourceType));\n }",
"public static void writeFlowId(Message message, String flowId) {\n if (!(message instanceof SoapMessage)) {\n return;\n }\n SoapMessage soapMessage = (SoapMessage)message;\n Header hdFlowId = soapMessage.getHeader(FLOW_ID_QNAME);\n if (hdFlowId != null) {\n LOG.warning(\"FlowId already existing in soap header, need not to write FlowId header.\");\n return;\n }\n\n try {\n soapMessage.getHeaders().add(\n new Header(FLOW_ID_QNAME, flowId, new JAXBDataBinding(String.class)));\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Stored flowId '\" + flowId + \"' in soap header: \" + FLOW_ID_QNAME);\n }\n } catch (JAXBException e) {\n LOG.log(Level.SEVERE, \"Couldn't create flowId header.\", e);\n }\n\n }"
] |
Disposes resources created to service this connection context | [
"@PreDestroy\n public final void dispose() {\n getConnectionPool().ifPresent(PoolResources::dispose);\n getThreadPool().dispose();\n\n try {\n ObjectName name = getByteBufAllocatorObjectName();\n\n if (ManagementFactory.getPlatformMBeanServer().isRegistered(name)) {\n ManagementFactory.getPlatformMBeanServer().unregisterMBean(name);\n }\n } catch (JMException e) {\n this.logger.error(\"Unable to register ByteBufAllocator MBean\", e);\n }\n }"
] | [
"public static void redeployLinksAndTransformOperation(OperationContext context, ModelNode removeOperation, PathAddress deploymentsRootAddress, Set<String> runtimeNames) throws OperationFailedException {\n Set<String> deploymentNames = listDeployments(context.readResourceFromRoot(deploymentsRootAddress), runtimeNames);\n Operations.CompositeOperationBuilder opBuilder = Operations.CompositeOperationBuilder.create();\n if (deploymentNames.isEmpty()) {\n for (String s : runtimeNames) {\n ServerLogger.ROOT_LOGGER.debugf(\"We haven't found any deployment for %s in server-group %s\", s, deploymentsRootAddress.getLastElement().getValue());\n }\n }\n if(removeOperation != null) {\n opBuilder.addStep(removeOperation);\n }\n for (String deploymentName : deploymentNames) {\n opBuilder.addStep(addRedeployStep(deploymentsRootAddress.append(DEPLOYMENT, deploymentName)));\n }\n List<DomainOperationTransmuter> transformers = context.getAttachment(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS);\n if (transformers == null) {\n context.attach(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS, transformers = new ArrayList<>());\n }\n final ModelNode slave = opBuilder.build().getOperation();\n transformers.add(new OverlayOperationTransmuter(slave, context.getCurrentAddress()));\n }",
"public static <T> void setBeanInstance(String contextId, T proxy, BeanInstance beanInstance, Bean<?> bean) {\n if (proxy instanceof ProxyObject) {\n ProxyObject proxyView = (ProxyObject) proxy;\n proxyView.weld_setHandler(new ProxyMethodHandler(contextId, beanInstance, bean));\n }\n }",
"@Override\n\tprotected void doProcessQueuedOps(PersistentCollection collection, Serializable key, int nextIndex, SharedSessionContractImplementor session)\n\t\t\tthrows HibernateException {\n\t\t// nothing to do\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 }",
"public void checkpoint(ObjectEnvelope mod)\r\n throws org.apache.ojb.broker.PersistenceBrokerException\r\n {\r\n mod.doUpdate();\r\n }",
"private String getIndirectionTableColName(TableAlias mnAlias, String path)\r\n {\r\n int dotIdx = path.lastIndexOf(\".\");\r\n String column = path.substring(dotIdx);\r\n return mnAlias.alias + column;\r\n }",
"public void createProposals(final Collection<ContentAssistContext> contexts, final IIdeContentProposalAcceptor acceptor) {\n Iterable<ContentAssistContext> _filteredContexts = this.getFilteredContexts(contexts);\n for (final ContentAssistContext context : _filteredContexts) {\n ImmutableList<AbstractElement> _firstSetGrammarElements = context.getFirstSetGrammarElements();\n for (final AbstractElement element : _firstSetGrammarElements) {\n {\n boolean _canAcceptMoreProposals = acceptor.canAcceptMoreProposals();\n boolean _not = (!_canAcceptMoreProposals);\n if (_not) {\n return;\n }\n this.createProposals(element, context, acceptor);\n }\n }\n }\n }",
"public static void append(File file, Writer writer, String charset) throws IOException {\n appendBuffered(file, writer, charset);\n }",
"protected boolean setChannel(final Channel newChannel) {\n if(newChannel == null) {\n return false;\n }\n synchronized (lock) {\n if(state != State.OPEN || channel != null) {\n return false;\n }\n this.channel = newChannel;\n this.channel.addCloseHandler(new CloseHandler<Channel>() {\n @Override\n public void handleClose(final Channel closed, final IOException exception) {\n synchronized (lock) {\n if(FutureManagementChannel.this.channel == closed) {\n FutureManagementChannel.this.channel = null;\n }\n lock.notifyAll();\n }\n }\n });\n lock.notifyAll();\n return true;\n }\n }"
] |
Setter for the file format.
@param fileFormat File format the configuration file is in. | [
"public void setFileFormat(String fileFormat) {\n\n if (fileFormat.toUpperCase().equals(FileFormat.JSON.toString())) {\n m_fileFormat = FileFormat.JSON;\n }\n }"
] | [
"public static final CurrencySymbolPosition parseCurrencySymbolPosition(String value)\n {\n CurrencySymbolPosition result = MAP_TO_CURRENCY_SYMBOL_POSITION.get(value);\n result = result == null ? CurrencySymbolPosition.BEFORE_WITH_SPACE : result;\n return result;\n }",
"@Override\n public Integer getMasterPartition(byte[] key) {\n return abs(hash.hash(key)) % (Math.max(1, this.partitionToNode.length));\n }",
"public boolean isAlive(Connection conn)\r\n {\r\n try\r\n {\r\n return con != null ? !con.isClosed() : false;\r\n }\r\n catch (SQLException e)\r\n {\r\n log.error(\"IsAlive check failed, running connection was invalid!!\", e);\r\n return false;\r\n }\r\n }",
"public boolean checkRead(TransactionImpl tx, Object obj)\r\n {\r\n if (hasReadLock(tx, obj))\r\n {\r\n return true;\r\n }\r\n LockEntry writer = getWriter(obj);\r\n if (writer.isOwnedBy(tx))\r\n {\r\n return true;\r\n }\r\n return false;\r\n }",
"@SuppressWarnings(\"SameParameterValue\")\n private byte[] readResponseWithExpectedSize(InputStream is, int size, String description) throws IOException {\n byte[] result = receiveBytes(is);\n if (result.length != size) {\n logger.warn(\"Expected \" + size + \" bytes while reading \" + description + \" response, received \" + result.length);\n }\n return result;\n }",
"public static <T extends WindupVertexFrame> T addTypeToModel(GraphContext graphContext, WindupVertexFrame frame, Class<T> type)\n {\n Vertex vertex = frame.getElement();\n graphContext.getGraphTypeManager().addTypeToElement(type, vertex);\n return graphContext.getFramed().frameElement(vertex, type);\n }",
"public static Dimension rectangleDoubleToDimension(final Rectangle2D.Double rectangle) {\n return new Dimension(\n (int) Math.round(rectangle.width),\n (int) Math.round(rectangle.height));\n }",
"protected void eciProcess() {\n\n EciMode eci = EciMode.of(content, \"ISO8859_1\", 3)\n .or(content, \"ISO8859_2\", 4)\n .or(content, \"ISO8859_3\", 5)\n .or(content, \"ISO8859_4\", 6)\n .or(content, \"ISO8859_5\", 7)\n .or(content, \"ISO8859_6\", 8)\n .or(content, \"ISO8859_7\", 9)\n .or(content, \"ISO8859_8\", 10)\n .or(content, \"ISO8859_9\", 11)\n .or(content, \"ISO8859_10\", 12)\n .or(content, \"ISO8859_11\", 13)\n .or(content, \"ISO8859_13\", 15)\n .or(content, \"ISO8859_14\", 16)\n .or(content, \"ISO8859_15\", 17)\n .or(content, \"ISO8859_16\", 18)\n .or(content, \"Windows_1250\", 21)\n .or(content, \"Windows_1251\", 22)\n .or(content, \"Windows_1252\", 23)\n .or(content, \"Windows_1256\", 24)\n .or(content, \"SJIS\", 20)\n .or(content, \"UTF8\", 26);\n\n if (EciMode.NONE.equals(eci)) {\n throw new OkapiException(\"Unable to determine ECI mode.\");\n }\n\n eciMode = eci.mode;\n inputData = toBytes(content, eci.charset);\n\n encodeInfo += \"ECI Mode: \" + eci.mode + \"\\n\";\n encodeInfo += \"ECI Charset: \" + eci.charset.name() + \"\\n\";\n }",
"public void beforeCompletion()\r\n {\r\n // avoid redundant calls\r\n if(beforeCompletionCall) return;\r\n\r\n log.info(\"Method beforeCompletion was called\");\r\n int status = Status.STATUS_UNKNOWN;\r\n try\r\n {\r\n JTATxManager mgr = (JTATxManager) getImplementation().getTxManager();\r\n status = mgr.getJTATransaction().getStatus();\r\n // ensure proper work, check all possible status\r\n // normally only check for 'STATUS_MARKED_ROLLBACK' is necessary\r\n if(status == Status.STATUS_MARKED_ROLLBACK\r\n || status == Status.STATUS_ROLLEDBACK\r\n || status == Status.STATUS_ROLLING_BACK\r\n || status == Status.STATUS_UNKNOWN\r\n || status == Status.STATUS_NO_TRANSACTION)\r\n {\r\n log.error(\"Synchronization#beforeCompletion: Can't prepare for commit, because tx status was \"\r\n + TxUtil.getStatusString(status) + \". Do internal cleanup only.\");\r\n }\r\n else\r\n {\r\n if(log.isDebugEnabled())\r\n {\r\n log.debug(\"Synchronization#beforeCompletion: Prepare for commit\");\r\n }\r\n // write objects to database\r\n prepareCommit();\r\n }\r\n }\r\n catch(Exception e)\r\n {\r\n log.error(\"Synchronization#beforeCompletion: Error while prepare for commit\", e);\r\n if(e instanceof LockNotGrantedException)\r\n {\r\n throw (LockNotGrantedException) e;\r\n }\r\n else if(e instanceof TransactionAbortedException)\r\n {\r\n throw (TransactionAbortedException) e;\r\n }\r\n else if(e instanceof ODMGRuntimeException)\r\n {\r\n throw (ODMGRuntimeException) e;\r\n }\r\n else\r\n { \r\n throw new ODMGRuntimeException(\"Method beforeCompletion() fails, status of JTA-tx was \"\r\n + TxUtil.getStatusString(status) + \", message: \" + e.getMessage());\r\n }\r\n\r\n }\r\n finally\r\n {\r\n beforeCompletionCall = true;\r\n setInExternTransaction(false);\r\n internalCleanup();\r\n }\r\n }"
] |
Checks if a given number is in the range of a float.
@param number
a number which should be in the range of a float (positive or negative)
@see java.lang.Float#MIN_VALUE
@see java.lang.Float#MAX_VALUE
@return number as a float | [
"@ArgumentsChecked\n\t@Throws(IllegalNullArgumentException.class)\n\tpublic static float checkFloat(@Nonnull final Number number) {\n\t\tCheck.notNull(number, \"number\");\n\t\tif (!isInFloatRange(number)) {\n\t\t\tthrow new IllegalNumberRangeException(number.toString(), FLOAT_MIN, FLOAT_MAX);\n\t\t}\n\n\t\treturn number.floatValue();\n\t}"
] | [
"public static int allParametersAndArgumentsMatch(Parameter[] params, ClassNode[] args) {\n if (params==null) {\n params = Parameter.EMPTY_ARRAY;\n }\n int dist = 0;\n if (args.length<params.length) return -1;\n // we already know the lengths are equal\n for (int i = 0; i < params.length; i++) {\n ClassNode paramType = params[i].getType();\n ClassNode argType = args[i];\n if (!isAssignableTo(argType, paramType)) return -1;\n else {\n if (!paramType.equals(argType)) dist+=getDistance(argType, paramType);\n }\n }\n return dist;\n }",
"public static java.sql.Time rollTime(java.util.Date startDate, int period, int amount) {\n GregorianCalendar gc = new GregorianCalendar();\n gc.setTime(startDate);\n gc.add(period, amount);\n return new java.sql.Time(gc.getTime().getTime());\n }",
"private void deliverWaveformPreviewUpdate(final int player, final WaveformPreview preview) {\n final Set<WaveformListener> listeners = getWaveformListeners();\n if (!listeners.isEmpty()) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n final WaveformPreviewUpdate update = new WaveformPreviewUpdate(player, preview);\n for (final WaveformListener listener : listeners) {\n try {\n listener.previewChanged(update);\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering waveform preview update to listener\", t);\n }\n }\n }\n });\n }\n }",
"public static Broker createBroker(int id, String brokerInfoString) {\n String[] brokerInfo = brokerInfoString.split(\":\");\n String creator = brokerInfo[0].replace('#', ':');\n String hostname = brokerInfo[1].replace('#', ':');\n String port = brokerInfo[2];\n boolean autocreated = Boolean.valueOf(brokerInfo.length > 3 ? brokerInfo[3] : \"true\");\n return new Broker(id, creator, hostname, Integer.parseInt(port), autocreated);\n }",
"public static String makeHTMLTable(String[][] table, String[] rowLabels, String[] colLabels) {\r\n StringBuilder buff = new StringBuilder();\r\n buff.append(\"<table class=\\\"auto\\\" border=\\\"1\\\" cellspacing=\\\"0\\\">\\n\");\r\n // top row\r\n buff.append(\"<tr>\\n\");\r\n buff.append(\"<td></td>\\n\"); // the top left cell\r\n for (int j = 0; j < table[0].length; j++) { // assume table is a rectangular matrix\r\n buff.append(\"<td class=\\\"label\\\">\").append(colLabels[j]).append(\"</td>\\n\");\r\n }\r\n buff.append(\"</tr>\\n\");\r\n // all other rows\r\n for (int i = 0; i < table.length; i++) {\r\n // one row\r\n buff.append(\"<tr>\\n\");\r\n buff.append(\"<td class=\\\"label\\\">\").append(rowLabels[i]).append(\"</td>\\n\");\r\n for (int j = 0; j < table[i].length; j++) {\r\n buff.append(\"<td class=\\\"data\\\">\");\r\n buff.append(((table[i][j] != null) ? table[i][j] : \"\"));\r\n buff.append(\"</td>\\n\");\r\n }\r\n buff.append(\"</tr>\\n\");\r\n }\r\n buff.append(\"</table>\");\r\n return buff.toString();\r\n }",
"private AlbumArt requestArtworkInternal(final DataReference artReference, final CdjStatus.TrackType trackType,\n final boolean failIfPassive) {\n\n // First check if we are using cached data for this slot.\n MetadataCache cache = MetadataFinder.getInstance().getMetadataCache(SlotReference.getSlotReference(artReference));\n if (cache != null) {\n final AlbumArt result = cache.getAlbumArt(null, artReference);\n if (result != null) {\n artCache.put(artReference, result);\n }\n return result;\n }\n\n // Then see if any registered metadata providers can offer it for us.\n final MediaDetails sourceDetails = MetadataFinder.getInstance().getMediaDetailsFor(artReference.getSlotReference());\n if (sourceDetails != null) {\n final AlbumArt provided = MetadataFinder.getInstance().allMetadataProviders.getAlbumArt(sourceDetails, artReference);\n if (provided != null) {\n return provided;\n }\n }\n\n // At this point, unless we are allowed to actively request the data, we are done. We can always actively\n // request tracks from rekordbox.\n if (MetadataFinder.getInstance().isPassive() && failIfPassive && artReference.slot != CdjStatus.TrackSourceSlot.COLLECTION) {\n return null;\n }\n\n // We have to actually request the art using the dbserver protocol.\n ConnectionManager.ClientTask<AlbumArt> task = new ConnectionManager.ClientTask<AlbumArt>() {\n @Override\n public AlbumArt useClient(Client client) throws Exception {\n return getArtwork(artReference.rekordboxId, SlotReference.getSlotReference(artReference), trackType, client);\n }\n };\n\n try {\n AlbumArt artwork = ConnectionManager.getInstance().invokeWithClientSession(artReference.player, task, \"requesting artwork\");\n if (artwork != null) { // Our cache file load or network request succeeded, so add to the level 2 cache.\n artCache.put(artReference, artwork);\n }\n return artwork;\n } catch (Exception e) {\n logger.error(\"Problem requesting album art, returning null\", e);\n }\n return null;\n }",
"public final Template getTemplate(final String name) {\n final Template template = this.templates.get(name);\n if (template != null) {\n this.accessAssertion.assertAccess(\"Configuration\", this);\n template.assertAccessible(name);\n } else {\n throw new IllegalArgumentException(String.format(\"Template '%s' does not exist. Options are: \" +\n \"%s\", name, this.templates.keySet()));\n }\n return template;\n }",
"public static List<DatabaseTableConfig<?>> loadDatabaseConfigFromReader(BufferedReader reader) throws SQLException {\n\t\tList<DatabaseTableConfig<?>> list = new ArrayList<DatabaseTableConfig<?>>();\n\t\twhile (true) {\n\t\t\tDatabaseTableConfig<?> config = DatabaseTableConfigLoader.fromReader(reader);\n\t\t\tif (config == null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tlist.add(config);\n\t\t}\n\t\treturn list;\n\t}",
"public void sendMessageToAgentsWithExtraProperties(String[] agent_name,\n String msgtype, Object message_content,\n ArrayList<Object> properties, Connector connector) {\n HashMap<String, Object> hm = new HashMap<String, Object>();\n hm.put(\"performative\", msgtype);\n hm.put(SFipa.CONTENT, message_content);\n\n for (Object property : properties) {\n // Logger logger = Logger.getLogger(\"JadexMessenger\");\n // logger.info(\"Sending message with extra property: \"+property.get(0)+\", with value \"+property.get(1));\n hm.put((String) ((Tuple) property).get(0), ((Tuple) property).get(1));\n }\n\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 }"
] |
Read calendar data. | [
"private void processCalendars() throws Exception\n {\n List<Row> rows = getRows(\"select * from zcalendar where zproject=?\", m_projectID);\n for (Row row : rows)\n {\n ProjectCalendar calendar = m_project.addCalendar();\n calendar.setUniqueID(row.getInteger(\"Z_PK\"));\n calendar.setName(row.getString(\"ZTITLE\"));\n processDays(calendar);\n processExceptions(calendar);\n m_eventManager.fireCalendarReadEvent(calendar);\n }\n }"
] | [
"public static void stopService() {\n DaemonStarter.currentPhase.set(LifecyclePhase.STOPPING);\n final CountDownLatch cdl = new CountDownLatch(1);\n Executors.newSingleThreadExecutor().execute(() -> {\n DaemonStarter.getLifecycleListener().stopping();\n DaemonStarter.daemon.stop();\n cdl.countDown();\n });\n\n try {\n int timeout = DaemonStarter.lifecycleListener.get().getShutdownTimeoutSeconds();\n if (!cdl.await(timeout, TimeUnit.SECONDS)) {\n DaemonStarter.rlog.error(\"Failed to stop gracefully\");\n DaemonStarter.abortSystem();\n }\n } catch (InterruptedException e) {\n DaemonStarter.rlog.error(\"Failure awaiting stop\", e);\n Thread.currentThread().interrupt();\n }\n\n }",
"private void queryDatabaseMetaData()\n {\n ResultSet rs = null;\n\n try\n {\n Set<String> tables = new HashSet<String>();\n DatabaseMetaData dmd = m_connection.getMetaData();\n rs = dmd.getTables(null, null, null, null);\n while (rs.next())\n {\n tables.add(rs.getString(\"TABLE_NAME\"));\n }\n\n m_hasResourceBaselines = tables.contains(\"MSP_RESOURCE_BASELINES\");\n m_hasTaskBaselines = tables.contains(\"MSP_TASK_BASELINES\");\n m_hasAssignmentBaselines = tables.contains(\"MSP_ASSIGNMENT_BASELINES\");\n }\n\n catch (Exception ex)\n {\n // Ignore errors when reading meta data\n }\n\n finally\n {\n if (rs != null)\n {\n try\n {\n rs.close();\n }\n\n catch (SQLException ex)\n {\n // Ignore errors when closing result set\n }\n rs = null;\n }\n }\n }",
"public CollectionRequest<Team> users(String team) {\n \n String path = String.format(\"/teams/%s/users\", team);\n return new CollectionRequest<Team>(this, Team.class, path, \"GET\");\n }",
"public boolean checkContains(String uri, String[] patterns) {\n\t\tfor (String pattern : patterns) {\n\t\t\tif (pattern.length() > 0) {\n\t\t\t\tif (uri.contains(pattern)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"public LuaScript endScript(LuaScriptConfig config) {\n if (!endsWithReturnStatement()) {\n add(new LuaAstReturnStatement());\n }\n String scriptText = buildScriptText();\n return new BasicLuaScript(scriptText, config);\n }",
"public String getBaselineDurationText()\n {\n Object result = getCachedValue(TaskField.BASELINE_DURATION);\n if (result == null)\n {\n result = getCachedValue(TaskField.BASELINE_ESTIMATED_DURATION);\n }\n\n if (!(result instanceof String))\n {\n result = null;\n }\n return (String) result;\n }",
"private List<AssignmentField> getAllAssignmentExtendedAttributes()\n {\n ArrayList<AssignmentField> result = new ArrayList<AssignmentField>();\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_COST));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_DATE));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_DURATION));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_COST));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_DATE));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_DURATION));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_FLAG));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_NUMBER));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_RESOURCE_MULTI_VALUE));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_RESOURCE_OUTLINE_CODE));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_TEXT));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_FINISH));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_FLAG));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_NUMBER));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_START));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_TEXT));\n return result;\n }",
"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 }",
"protected AbstractColumn buildSimpleImageColumn() {\n\t\tImageColumn column = new ImageColumn();\n\t\tpopulateCommonAttributes(column);\n\t\tpopulateExpressionAttributes(column);\n\t\t\n\t\tcolumn.setExpression(customExpression);\n\t\tcolumn.setExpressionToGroupBy(customExpressionToGroupBy);\n\t\tcolumn.setExpressionForCalculation(customExpressionForCalculation);\n\t\t\n\t\tcolumn.setScaleMode(imageScaleMode);\n\t\treturn column;\n\t}"
] |
Wait to shutdown service
@param executorService Executor service to shutdown
@param timeOutSec Time we wait for | [
"public static void executorShutDown(ExecutorService executorService, long timeOutSec) {\n try {\n executorService.shutdown();\n executorService.awaitTermination(timeOutSec, TimeUnit.SECONDS);\n } catch(Exception e) {\n logger.warn(\"Error while stoping executor service.\", e);\n }\n }"
] | [
"public SourceBuilder addLine(String fmt, Object... args) {\n add(fmt, args);\n source.append(LINE_SEPARATOR);\n return this;\n }",
"public ParallelTaskBuilder setTargetHostsFromLineByLineText(\n String sourcePath, HostsSourceType sourceType)\n throws TargetHostsLoadException {\n\n this.targetHosts = targetHostBuilder.setTargetHostsFromLineByLineText(sourcePath,\n sourceType);\n return this;\n }",
"private void processGraphicalIndicators()\n {\n GraphicalIndicatorReader graphicalIndicatorReader = new GraphicalIndicatorReader();\n graphicalIndicatorReader.process(m_file.getCustomFields(), m_file.getProjectProperties(), m_projectProps);\n }",
"public void copyNodeMetaData(ASTNode other) {\n if (other.metaDataMap == null) {\n return;\n }\n if (metaDataMap == null) {\n metaDataMap = new ListHashMap();\n }\n metaDataMap.putAll(other.metaDataMap);\n }",
"public static Type[] getActualTypeArguments(Class<?> clazz) {\n Type type = Types.getCanonicalType(clazz);\n if (type instanceof ParameterizedType) {\n return ((ParameterizedType) type).getActualTypeArguments();\n } else {\n return EMPTY_TYPES;\n }\n }",
"public static ForwardCurveInterpolation createForwardCurveFromMonteCarloLiborModel(String name, LIBORModelMonteCarloSimulationModel model, double startTime) throws CalculationException{\n\n\t\tint timeIndex\t= model.getTimeIndex(startTime);\n\t\t// Get all Libors at timeIndex which are not yet fixed (others null) and times for the timeDiscretizationFromArray of the curves\n\t\tArrayList<RandomVariable> liborsAtTimeIndex = new ArrayList<>();\n\t\tint firstLiborIndex = model.getLiborPeriodDiscretization().getTimeIndexNearestGreaterOrEqual(startTime);\n\t\tdouble firstLiborTime = model.getLiborPeriodDiscretization().getTime(firstLiborIndex);\n\t\tif(firstLiborTime>startTime) {\n\t\t\tliborsAtTimeIndex.add(model.getLIBOR(startTime, startTime, firstLiborTime));\n\t\t}\n\t\t// Vector of times for the forward curve\n\t\tdouble[] times = new double[firstLiborTime==startTime ? (model.getNumberOfLibors()-firstLiborIndex) : (model.getNumberOfLibors()-firstLiborIndex+1)];\n\t\ttimes[0]=0;\n\t\tint indexOffset = firstLiborTime==startTime ? 0 : 1;\n\t\tfor(int i=firstLiborIndex;i<model.getNumberOfLibors();i++) {\n\t\t\tliborsAtTimeIndex.add(model.getLIBOR(timeIndex,i));\n\t\t\ttimes[i-firstLiborIndex+indexOffset]=model.getLiborPeriodDiscretization().getTime(i)-startTime;\n\t\t}\n\n\t\tRandomVariable[] libors = liborsAtTimeIndex.toArray(new RandomVariable[liborsAtTimeIndex.size()]);\n\t\treturn ForwardCurveInterpolation.createForwardCurveFromForwards(name, times, libors, model.getLiborPeriodDiscretization().getTimeStep(firstLiborIndex));\n\n\t}",
"public QueryBuilder<T, ID> join(QueryBuilder<?, ?> joinedQueryBuilder) throws SQLException {\n\t\taddJoinInfo(JoinType.INNER, null, null, joinedQueryBuilder, JoinWhereOperation.AND);\n\t\treturn this;\n\t}",
"public static int getBytesToken(ParsingContext ctx) {\n String input = ctx.getInput().substring(ctx.getLocation());\n int tokenOffset = 0;\n int i = 0;\n char[] inputChars = input.toCharArray();\n for (; i < input.length(); i += 1) {\n char c = inputChars[i];\n if (c == ' ') {\n continue;\n }\n if (c != BYTES_TOKEN_CHARS[tokenOffset]) {\n return -1;\n } else {\n tokenOffset += 1;\n if (tokenOffset == BYTES_TOKEN_CHARS.length) {\n // Found the token.\n return i;\n }\n }\n }\n return -1;\n }",
"private boolean findAndSetManifestFromArtifactory(ArtifactoryServer server, ArtifactoryDependenciesClient dependenciesClient, TaskListener listener) throws IOException {\n String candidateImagePath = DockerUtils.getImagePath(imageTag);\n String manifestPath;\n\n // Try to get manifest, assuming reverse proxy\n manifestPath = StringUtils.join(new String[]{server.getUrl(), targetRepo, candidateImagePath, \"manifest.json\"}, \"/\");\n if (checkAndSetManifestAndImagePathCandidates(manifestPath, candidateImagePath, dependenciesClient, listener)) {\n return true;\n }\n\n // Try to get manifest, assuming proxy-less\n candidateImagePath = candidateImagePath.substring(candidateImagePath.indexOf(\"/\") + 1);\n manifestPath = StringUtils.join(new String[]{server.getUrl(), targetRepo, candidateImagePath, \"manifest.json\"}, \"/\");\n if (checkAndSetManifestAndImagePathCandidates(manifestPath, candidateImagePath, dependenciesClient, listener)) {\n return true;\n }\n\n // Couldn't find correct manifest\n listener.getLogger().println(\"Could not find corresponding manifest.json file in Artifactory.\");\n return false;\n }"
] |
Get an active operation.
@param header the request header
@return the active operation, {@code null} if if there is no registered operation | [
"protected <T, A> ActiveOperation<T, A> getActiveOperation(final ManagementRequestHeader header) {\n return getActiveOperation(header.getBatchId());\n }"
] | [
"@SuppressWarnings(\"unchecked\")\n\tstatic void logToFile(String filename) {\n\t\tLogger rootLogger = (Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);\n\n\t\tFileAppender<ILoggingEvent> fileappender = new FileAppender<>();\n\t\tfileappender.setContext(rootLogger.getLoggerContext());\n\t\tfileappender.setFile(filename);\n\t\tfileappender.setName(\"FILE\");\n\n\t\tConsoleAppender<?> console = (ConsoleAppender<?>) rootLogger.getAppender(\"STDOUT\");\n\t\tfileappender.setEncoder((Encoder<ILoggingEvent>) console.getEncoder());\n\n\t\tfileappender.start();\n\n\t\trootLogger.addAppender(fileappender);\n\n\t\tconsole.stop();\n\t}",
"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 static double elementSum( DMatrixSparseCSC A ) {\n if( A.nz_length == 0)\n return 0;\n\n double sum = 0;\n for(int i = 0; i < A.nz_length; i++ ) {\n sum += A.nz_values[i];\n }\n\n return sum;\n }",
"public String build() {\n if (!root.containsKey(\"mdm\")) {\n insertCustomAlert();\n root.put(\"aps\", aps);\n }\n try {\n return mapper.writeValueAsString(root);\n } catch (final Exception e) {\n throw new RuntimeException(e);\n }\n }",
"protected Object buildOrRefreshObject(Map row, ClassDescriptor targetClassDescriptor, Object targetObject)\r\n {\r\n Object result = targetObject;\r\n FieldDescriptor fmd;\r\n FieldDescriptor[] fields = targetClassDescriptor.getFieldDescriptor(true);\r\n\r\n if(targetObject == null)\r\n {\r\n // 1. create new object instance if needed\r\n result = ClassHelper.buildNewObjectInstance(targetClassDescriptor);\r\n }\r\n\r\n // 2. fill all scalar attributes of the new object\r\n for (int i = 0; i < fields.length; i++)\r\n {\r\n fmd = fields[i];\r\n fmd.getPersistentField().set(result, row.get(fmd.getColumnName()));\r\n }\r\n\r\n if(targetObject == null)\r\n {\r\n // 3. for new build objects, invoke the initialization method for the class if one is provided\r\n Method initializationMethod = targetClassDescriptor.getInitializationMethod();\r\n if (initializationMethod != null)\r\n {\r\n try\r\n {\r\n initializationMethod.invoke(result, NO_ARGS);\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new PersistenceBrokerException(\"Unable to invoke initialization method:\" + initializationMethod.getName() + \" for class:\" + m_cld.getClassOfObject(), ex);\r\n }\r\n }\r\n }\r\n return result;\r\n }",
"private static StackTraceElement getStackTrace() {\r\n StackTraceElement[] stack = Thread.currentThread().getStackTrace();\r\n\r\n int i = 2; // we can skip the first two (first is getStackTrace(), second is this method)\r\n while (i < stack.length) {\r\n boolean isLoggingClass = false;\r\n for (String loggingClass : loggingClasses) {\r\n String className = stack[i].getClassName();\r\n if (className.startsWith(loggingClass)) {\r\n isLoggingClass = true;\r\n break;\r\n }\r\n }\r\n if (!isLoggingClass) {\r\n break;\r\n }\r\n\r\n i += 1;\r\n }\r\n\r\n // if we didn't find anything, keep last element (probably shouldn't happen, but could if people add too many logging classes)\r\n if (i >= stack.length) {\r\n i = stack.length - 1;\r\n }\r\n return stack[i];\r\n }",
"@Override\n public AccountingDate date(int prolepticYear, int month, int dayOfMonth) {\n return AccountingDate.of(this, prolepticYear, month, dayOfMonth);\n }",
"public static String toPrettyJson(Object o) {\n\t\ttry {\n\t\t\treturn MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(o);\n\t\t} catch (JsonProcessingException e) {\n\t\t\tLoggerFactory\n\t\t\t .getLogger(Serializer.class)\n\t\t\t .error(\"Could not serialize the object. This will be ignored and the error will be written instead. Object was {}\",\n\t\t\t o, e);\n\t\t\treturn \"\\\"\" + e.getMessage() + \"\\\"\";\n\t\t}\n\t}",
"public QueryBuilder<T, ID> orderBy(String columnName, boolean ascending) {\n\t\tFieldType fieldType = verifyColumnName(columnName);\n\t\tif (fieldType.isForeignCollection()) {\n\t\t\tthrow new IllegalArgumentException(\"Can't orderBy foreign collection field: \" + columnName);\n\t\t}\n\t\taddOrderBy(new OrderBy(columnName, ascending));\n\t\treturn this;\n\t}"
] |
Returns the proxies real subject. The subject will be materialized if
necessary.
@return The subject | [
"public Object getRealSubject() throws PersistenceBrokerException\r\n\t{\r\n\t\tif (_realSubject == null)\r\n\t\t{\r\n\t\t\tbeforeMaterialization();\r\n\t\t\t_realSubject = materializeSubject();\r\n\t\t\tafterMaterialization();\r\n\t\t}\r\n\t\treturn _realSubject;\r\n\t}"
] | [
"public void checkpoint(ObjectEnvelope mod)\r\n throws org.apache.ojb.broker.PersistenceBrokerException\r\n {\r\n mod.doUpdate();\r\n }",
"public static FullTypeSignature getTypeSignature(Class<?> clazz, Class<?>[] typeArgs) {\n\t\tClassTypeSignature rawClassTypeSignature = (ClassTypeSignature) javaTypeToTypeSignature\n\t\t\t\t.getTypeSignature(clazz);\n\t\tTypeArgSignature[] typeArgSignatures = new TypeArgSignature[typeArgs.length];\n\t\tfor (int i = 0; i < typeArgs.length; i++) {\n\t\t\ttypeArgSignatures[i] = new TypeArgSignature(\n\t\t\t\t\tTypeArgSignature.NO_WILDCARD,\n\t\t\t\t\t(FieldTypeSignature) javaTypeToTypeSignature\n\t\t\t\t\t\t\t.getTypeSignature(typeArgs[i]));\n\t\t}\n\t\tClassTypeSignature classTypeSignature = new ClassTypeSignature(\n\t\t\t\trawClassTypeSignature.getBinaryName(), typeArgSignatures,\n\t\t\t\trawClassTypeSignature.getOwnerTypeSignature());\n\n\t\treturn classTypeSignature;\n\t}",
"public boolean fling(float velocityX, float velocityY, float velocityZ) {\n boolean scrolled = true;\n float viewportX = mScrollable.getViewPortWidth();\n if (Float.isNaN(viewportX)) {\n viewportX = 0;\n }\n float maxX = Math.min(MAX_SCROLLING_DISTANCE,\n viewportX * MAX_VIEWPORT_LENGTHS);\n\n float viewportY = mScrollable.getViewPortHeight();\n if (Float.isNaN(viewportY)) {\n viewportY = 0;\n }\n float maxY = Math.min(MAX_SCROLLING_DISTANCE,\n viewportY * MAX_VIEWPORT_LENGTHS);\n\n float xOffset = (maxX * velocityX)/VELOCITY_MAX;\n float yOffset = (maxY * velocityY)/VELOCITY_MAX;\n\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"fling() velocity = [%f, %f, %f] offset = [%f, %f]\",\n velocityX, velocityY, velocityZ,\n xOffset, yOffset);\n\n if (equal(xOffset, 0)) {\n xOffset = Float.NaN;\n }\n\n if (equal(yOffset, 0)) {\n yOffset = Float.NaN;\n }\n\n// TODO: Think about Z-scrolling\n mScrollable.scrollByOffset(xOffset, yOffset, Float.NaN, mInternalScrollListener);\n\n return scrolled;\n }",
"public int getInt(Integer type)\n {\n int result = 0;\n\n byte[] item = m_map.get(type);\n if (item != null)\n {\n result = MPPUtility.getInt(item, 0);\n }\n\n return (result);\n }",
"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}",
"public int blast(InputStream input, OutputStream output) throws IOException\n {\n m_input = input;\n m_output = output;\n\n int lit; /* true if literals are coded */\n int dict; /* log2(dictionary size) - 6 */\n int symbol; /* decoded symbol, extra bits for distance */\n int len; /* length for copy */\n int dist; /* distance for copy */\n int copy; /* copy counter */\n //unsigned char *from, *to; /* copy pointers */\n\n /* read header */\n lit = bits(8);\n if (lit > 1)\n {\n return -1;\n }\n dict = bits(8);\n if (dict < 4 || dict > 6)\n {\n return -2;\n }\n\n /* decode literals and length/distance pairs */\n do\n {\n if (bits(1) != 0)\n {\n /* get length */\n symbol = decode(LENCODE);\n len = BASE[symbol] + bits(EXTRA[symbol]);\n if (len == 519)\n {\n break; /* end code */\n }\n\n /* get distance */\n symbol = len == 2 ? 2 : dict;\n dist = decode(DISTCODE) << symbol;\n dist += bits(symbol);\n dist++;\n if (m_first != 0 && dist > m_next)\n {\n return -3; /* distance too far back */\n }\n\n /* copy length bytes from distance bytes back */\n do\n {\n //to = m_out + m_next;\n int to = m_next;\n int from = to - dist;\n copy = MAXWIN;\n if (m_next < dist)\n {\n from += copy;\n copy = dist;\n }\n copy -= m_next;\n if (copy > len)\n {\n copy = len;\n }\n len -= copy;\n m_next += copy;\n do\n {\n //*to++ = *from++;\n m_out[to++] = m_out[from++];\n }\n while (--copy != 0);\n if (m_next == MAXWIN)\n {\n //if (s->outfun(s->outhow, s->out, s->next)) return 1;\n m_output.write(m_out, 0, m_next);\n m_next = 0;\n m_first = 0;\n }\n }\n while (len != 0);\n }\n else\n {\n /* get literal and write it */\n symbol = lit != 0 ? decode(LITCODE) : bits(8);\n m_out[m_next++] = (byte) symbol;\n if (m_next == MAXWIN)\n {\n //if (s->outfun(s->outhow, s->out, s->next)) return 1;\n m_output.write(m_out, 0, m_next);\n m_next = 0;\n m_first = 0;\n }\n }\n }\n while (true);\n\n if (m_next != 0)\n {\n m_output.write(m_out, 0, m_next);\n }\n\n return 0;\n }",
"public static Timer getNamedTimer(String timerName, int todoFlags,\n\t\t\tlong threadId) {\n\t\tTimer key = new Timer(timerName, todoFlags, threadId);\n\t\tregisteredTimers.putIfAbsent(key, key);\n\t\treturn registeredTimers.get(key);\n\t}",
"private void revisitMessages(Definitions def) {\n List<RootElement> rootElements = def.getRootElements();\n List<ItemDefinition> toAddDefinitions = new ArrayList<ItemDefinition>();\n for (RootElement root : rootElements) {\n if (root instanceof Message) {\n if (!existsMessageItemDefinition(rootElements,\n root.getId())) {\n ItemDefinition itemdef = Bpmn2Factory.eINSTANCE.createItemDefinition();\n itemdef.setId(root.getId() + \"Type\");\n toAddDefinitions.add(itemdef);\n ((Message) root).setItemRef(itemdef);\n }\n }\n }\n for (ItemDefinition id : toAddDefinitions) {\n def.getRootElements().add(id);\n }\n }",
"private static TimeUnit getDurationUnits(Integer value)\n {\n TimeUnit result = null;\n\n if (value != null)\n {\n int index = value.intValue();\n if (index >= 0 && index < DURATION_UNITS.length)\n {\n result = DURATION_UNITS[index];\n }\n }\n\n if (result == null)\n {\n result = TimeUnit.DAYS;\n }\n\n return (result);\n }"
] |
Sets the delegate of the service, that gets notified of the
status of message delivery.
Note: This option has no effect when using non-blocking
connections. | [
"public ApnsServiceBuilder withDelegate(ApnsDelegate delegate) {\n this.delegate = delegate == null ? ApnsDelegate.EMPTY : delegate;\n return this;\n }"
] | [
"public boolean checkWrite(TransactionImpl tx, Object obj)\r\n {\r\n LockEntry writer = getWriter(obj);\r\n if (writer == null)\r\n return false;\r\n else if (writer.isOwnedBy(tx))\r\n return true;\r\n else\r\n return false;\r\n }",
"public DateRange getRange(int index)\n {\n DateRange result;\n\n if (index >= 0 && index < m_ranges.size())\n {\n result = m_ranges.get(index);\n }\n else\n {\n result = DateRange.EMPTY_RANGE;\n }\n\n return (result);\n }",
"private List<org.jfrog.hudson.pipeline.types.File> getBuildFilesList(Stream<? extends BaseBuildFileBean> buildFilesStream) {\n return buildFilesStream\n .filter(buildFile -> StringUtils.isNotBlank(buildFile.getLocalPath()))\n .filter(buildFile -> StringUtils.isNotBlank(buildFile.getRemotePath()))\n .map(org.jfrog.hudson.pipeline.types.File::new)\n .distinct()\n .collect(Collectors.toList());\n }",
"private void emitSuiteStart(Description description, long startTimestamp) throws IOException {\n String suiteName = description.getDisplayName();\n if (useSimpleNames) {\n if (suiteName.lastIndexOf('.') >= 0) {\n suiteName = suiteName.substring(suiteName.lastIndexOf('.') + 1);\n }\n }\n logShort(shortTimestamp(startTimestamp) +\n \"Suite: \" +\n FormattingUtils.padTo(maxClassNameColumns, suiteName, \"[...]\"));\n }",
"private void setProperties(Properties properties) {\n Props props = new Props(properties);\n if(props.containsKey(BOOTSTRAP_URLS_PROPERTY)) {\n setBootstrapURLs(props.getList(BOOTSTRAP_URLS_PROPERTY));\n }\n\n if(props.containsKey(FAT_CLIENTS_CONFIG_SOURCE)) {\n setFatClientConfigSource(StoreClientConfigSource.get(props.getString(FAT_CLIENTS_CONFIG_SOURCE)));\n }\n\n if(props.containsKey(FAT_CLIENTS_CONFIG_FILE_PATH_PROPERTY)) {\n setFatClientConfigPath(props.getString(FAT_CLIENTS_CONFIG_FILE_PATH_PROPERTY));\n }\n\n if(props.containsKey(METADATA_CHECK_INTERVAL_IN_MS)) {\n setMetadataCheckIntervalInMs(props.getInt(METADATA_CHECK_INTERVAL_IN_MS));\n }\n\n if(props.containsKey(NETTY_SERVER_PORT)) {\n setServerPort(props.getInt(NETTY_SERVER_PORT));\n }\n\n if(props.containsKey(NETTY_SERVER_BACKLOG)) {\n setNettyServerBacklog(props.getInt(NETTY_SERVER_BACKLOG));\n }\n\n if(props.containsKey(COORDINATOR_CORE_THREADS)) {\n setCoordinatorCoreThreads(props.getInt(COORDINATOR_CORE_THREADS));\n }\n\n if(props.containsKey(COORDINATOR_MAX_THREADS)) {\n setCoordinatorMaxThreads(props.getInt(COORDINATOR_MAX_THREADS));\n }\n\n if(props.containsKey(COORDINATOR_QUEUED_REQUESTS)) {\n setCoordinatorQueuedRequestsSize(props.getInt(COORDINATOR_QUEUED_REQUESTS));\n }\n\n if(props.containsKey(HTTP_MESSAGE_DECODER_MAX_INITIAL_LINE_LENGTH)) {\n setHttpMessageDecoderMaxInitialLength(props.getInt(HTTP_MESSAGE_DECODER_MAX_INITIAL_LINE_LENGTH));\n }\n\n if(props.containsKey(HTTP_MESSAGE_DECODER_MAX_HEADER_SIZE)) {\n setHttpMessageDecoderMaxHeaderSize(props.getInt(HTTP_MESSAGE_DECODER_MAX_HEADER_SIZE));\n }\n\n if(props.containsKey(HTTP_MESSAGE_DECODER_MAX_CHUNK_SIZE)) {\n setHttpMessageDecoderMaxChunkSize(props.getInt(HTTP_MESSAGE_DECODER_MAX_CHUNK_SIZE));\n }\n\n if(props.containsKey(ADMIN_ENABLE)) {\n setAdminServiceEnabled(props.getBoolean(ADMIN_ENABLE));\n }\n\n if(props.containsKey(ADMIN_PORT)) {\n setAdminPort(props.getInt(ADMIN_PORT));\n }\n\n }",
"public static Date getTime(int hour, int minutes)\n {\n Calendar cal = popCalendar();\n cal.set(Calendar.HOUR_OF_DAY, hour);\n cal.set(Calendar.MINUTE, minutes);\n cal.set(Calendar.SECOND, 0);\n Date result = cal.getTime();\n pushCalendar(cal);\n return result;\n }",
"public <X> Set<DisposalMethod<X, ?>> resolveDisposalBeans(Set<Type> types, Set<Annotation> qualifiers, AbstractClassBean<X> declaringBean) {\n // We can always cache as this is only ever called by Weld where we avoid non-static inner classes for annotation literals\n Set<DisposalMethod<X, ?>> beans = cast(disposalMethodResolver.resolve(new ResolvableBuilder(manager).addTypes(types).addQualifiers(qualifiers).setDeclaringBean(declaringBean).create(), true));\n resolvedDisposalBeans.addAll(beans);\n return Collections.unmodifiableSet(beans);\n }",
"public static double Exp(double x, int nTerms) {\r\n if (nTerms < 2) return 1 + x;\r\n if (nTerms == 2) {\r\n return 1 + x + (x * x) / 2;\r\n } else {\r\n\r\n double mult = x * x;\r\n double fact = 2;\r\n double result = 1 + x + mult / fact;\r\n for (int i = 3; i <= nTerms; i++) {\r\n mult *= x;\r\n fact *= i;\r\n result += mult / fact;\r\n }\r\n\r\n return result;\r\n }\r\n }",
"public ConnectionInfo getConnection(String name) {\n final URI uri = uriWithPath(\"./connections/\" + encodePathSegment(name));\n return this.rt.getForObject(uri, ConnectionInfo.class);\n }"
] |
Get the account knowing his position
@param position the position of the account (it can change at runtime!)
@return the account | [
"public MaterialAccount getAccountAtCurrentPosition(int position) {\n\n if (position < 0 || position >= accountManager.size())\n throw new RuntimeException(\"Account Index Overflow\");\n\n return findAccountNumber(position);\n }"
] | [
"@Deprecated\n public void parseAndSetParameter(String value, ModelNode operation, XMLStreamReader reader) throws XMLStreamException {\n //we use manual parsing here, and not #getParser().. to preserve backward compatibility.\n if (value != null) {\n for (String element : value.split(\",\")) {\n parseAndAddParameterElement(element.trim(), operation, reader);\n }\n }\n }",
"public void handleChannelClosed(final Channel closed, final IOException e) {\n for(final ActiveOperationImpl<?, ?> activeOperation : activeRequests.values()) {\n if (activeOperation.getChannel() == closed) {\n // Only call cancel, to also interrupt still active threads\n activeOperation.getResultHandler().cancel();\n }\n }\n }",
"public GVRTexture getSplashTexture(GVRContext gvrContext) {\n Bitmap bitmap = BitmapFactory.decodeResource( //\n gvrContext.getContext().getResources(), //\n R.drawable.__default_splash_screen__);\n GVRTexture tex = new GVRTexture(gvrContext);\n tex.setImage(new GVRBitmapImage(gvrContext, bitmap));\n return tex;\n }",
"protected void onEditTitleTextBox(TextBox box) {\n\n if (m_titleEditHandler != null) {\n m_titleEditHandler.handleEdit(m_title, box);\n return;\n }\n\n String text = box.getText();\n box.removeFromParent();\n m_title.setText(text);\n m_title.setVisible(true);\n\n }",
"protected void appendWhereClause(FieldDescriptor[] fields, StringBuffer stmt) throws PersistenceBrokerException\r\n {\r\n stmt.append(\" WHERE \");\r\n\r\n for(int i = 0; i < fields.length; i++)\r\n {\r\n FieldDescriptor fmd = fields[i];\r\n\r\n stmt.append(fmd.getColumnName());\r\n stmt.append(\" = ? \");\r\n if(i < fields.length - 1)\r\n {\r\n stmt.append(\" AND \");\r\n }\r\n }\r\n }",
"public void releaseDbResources()\r\n {\r\n Iterator it = m_rsIterators.iterator();\r\n while (it.hasNext())\r\n {\r\n ((OJBIterator) it.next()).releaseDbResources();\r\n }\r\n }",
"private GregorianCalendar getLastReleventDate(GregorianCalendar currentDate) {\n\t\tint age=this.getProperties().getMaxFileAge();\n\t\tGregorianCalendar result=new GregorianCalendar(currentDate.get(Calendar.YEAR),currentDate.get(Calendar.MONTH),currentDate.get(Calendar.DAY_OF_MONTH));\n\t\tresult.add(Calendar.DAY_OF_MONTH, -age);\n\t\treturn result;\n\t}",
"private AlbumArt findArtInMemoryCaches(DataReference artReference) {\n // First see if we can find the new track in the hot cache as a hot cue\n for (AlbumArt cached : hotCache.values()) {\n if (cached.artReference.equals(artReference)) { // Found a hot cue hit, use it.\n return cached;\n }\n }\n\n // Not in the hot cache, see if it is in our LRU cache\n return artCache.get(artReference);\n }",
"MongoCollection<BsonDocument> getLocalCollection(final MongoNamespace namespace) {\n return getLocalCollection(\n namespace,\n BsonDocument.class,\n MongoClientSettings.getDefaultCodecRegistry());\n }"
] |
2-D Complex Gabor function.
@param x X axis coordinate.
@param y Y axis coordinate.
@param wavelength Wavelength.
@param orientation Orientation.
@param phaseOffset Phase offset.
@param gaussVariance Gaussian variance.
@param aspectRatio Aspect ratio.
@return Gabor response. | [
"public static ComplexNumber Function2D(int x, int y, double wavelength, double orientation, double phaseOffset, double gaussVariance, double aspectRatio) {\n\n double X = x * Math.cos(orientation) + y * Math.sin(orientation);\n double Y = -x * Math.sin(orientation) + y * Math.cos(orientation);\n\n double envelope = Math.exp(-((X * X + aspectRatio * aspectRatio * Y * Y) / (2 * gaussVariance * gaussVariance)));\n double real = Math.cos(2 * Math.PI * (X / wavelength) + phaseOffset);\n double imaginary = Math.sin(2 * Math.PI * (X / wavelength) + phaseOffset);\n\n return new ComplexNumber(envelope * real, envelope * imaginary);\n }"
] | [
"public static autoscaleprofile[] get(nitro_service service) throws Exception{\n\t\tautoscaleprofile obj = new autoscaleprofile();\n\t\tautoscaleprofile[] response = (autoscaleprofile[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void stripTrailingDelimiters(StringBuilder buffer)\n {\n int index = buffer.length() - 1;\n\n while (index > 0 && buffer.charAt(index) == m_delimiter)\n {\n --index;\n }\n\n buffer.setLength(index + 1);\n }",
"public static void main(String[] args) {\n DirectoryIterator iter = new DirectoryIterator(args);\n while(iter.hasNext())\n System.out.println(iter.next().getAbsolutePath());\n }",
"public static int[] Unique(int[] values) {\r\n HashSet<Integer> lst = new HashSet<Integer>();\r\n for (int i = 0; i < values.length; i++) {\r\n lst.add(values[i]);\r\n }\r\n\r\n int[] v = new int[lst.size()];\r\n Iterator<Integer> it = lst.iterator();\r\n for (int i = 0; i < v.length; i++) {\r\n v[i] = it.next();\r\n }\r\n\r\n return v;\r\n }",
"public Document createDOM(PDDocument doc) throws IOException\n {\n /* We call the original PDFTextStripper.writeText but nothing should\n be printed actually because our processing methods produce no output.\n They create the DOM structures instead */\n super.writeText(doc, new OutputStreamWriter(System.out));\n return this.doc;\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}",
"private void countKey(Map<String, Integer> map, String key, int count) {\n\t\tif (map.containsKey(key)) {\n\t\t\tmap.put(key, map.get(key) + count);\n\t\t} else {\n\t\t\tmap.put(key, count);\n\t\t}\n\t}",
"public static <T> Collection<T> diff(Collection<T> list1, Collection<T> list2) {\r\n Collection<T> diff = new ArrayList<T>();\r\n for (T t : list1) {\r\n if (!list2.contains(t)) {\r\n diff.add(t);\r\n }\r\n }\r\n return diff;\r\n }",
"public static URI setPath(final URI initialUri, final String path) {\n String finalPath = path;\n if (!finalPath.startsWith(\"/\")) {\n finalPath = '/' + path;\n }\n try {\n if (initialUri.getHost() == null && initialUri.getAuthority() != null) {\n return new URI(initialUri.getScheme(), initialUri.getAuthority(), finalPath,\n initialUri.getQuery(),\n initialUri.getFragment());\n } else {\n return new URI(initialUri.getScheme(), initialUri.getUserInfo(), initialUri.getHost(),\n initialUri.getPort(),\n finalPath, initialUri.getQuery(), initialUri.getFragment());\n }\n } catch (URISyntaxException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }"
] |
Returns the decoded string, in case it contains non us-ascii characters.
Returns the same string if it doesn't or the passed value in case
of an UnsupportedEncodingException.
@param str string to be decoded
@return the decoded string, in case it contains non us-ascii characters;
or the same string if it doesn't or the passed value in case
of an UnsupportedEncodingException. | [
"private String decodeStr(String str) {\r\n try {\r\n return MimeUtility.decodeText(str);\r\n } catch (UnsupportedEncodingException e) {\r\n return str;\r\n }\r\n }"
] | [
"public StateVertex crawlIndex() {\n\t\tLOG.debug(\"Setting up vertex of the index page\");\n\n\t\tif (basicAuthUrl != null) {\n\t\t\tbrowser.goToUrl(basicAuthUrl);\n\t\t}\n\n\t\tbrowser.goToUrl(url);\n\n\t\t// Run url first load plugin to clear the application state\n\t\tplugins.runOnUrlFirstLoadPlugins(context);\n\n\t\tplugins.runOnUrlLoadPlugins(context);\n\t\tStateVertex index = vertexFactory.createIndex(url.toString(), browser.getStrippedDom(),\n\t\t\t\tstateComparator.getStrippedDom(browser), browser);\n\t\tPreconditions.checkArgument(index.getId() == StateVertex.INDEX_ID,\n\t\t\t\t\"It seems some the index state is crawled more than once.\");\n\n\t\tLOG.debug(\"Parsing the index for candidate elements\");\n\t\tImmutableList<CandidateElement> extract = candidateExtractor.extract(index);\n\n\t\tplugins.runPreStateCrawlingPlugins(context, extract, index);\n\n\t\tcandidateActionCache.addActions(extract, index);\n\n\t\treturn index;\n\n\t}",
"public void setEnable(boolean flag) {\n if (flag == mIsEnabled)\n return;\n\n mIsEnabled = flag;\n\n if (getNative() != 0)\n {\n NativeComponent.setEnable(getNative(), flag);\n }\n if (flag)\n {\n onEnable();\n }\n else\n {\n onDisable();\n }\n }",
"static void tryAutoAttaching(final SlotReference slot) {\n if (!MetadataFinder.getInstance().getMountedMediaSlots().contains(slot)) {\n logger.error(\"Unable to auto-attach cache to empty slot {}\", slot);\n return;\n }\n if (MetadataFinder.getInstance().getMetadataCache(slot) != null) {\n logger.info(\"Not auto-attaching to slot {}; already has a cache attached.\", slot);\n return;\n }\n if (MetadataFinder.getInstance().getAutoAttachCacheFiles().isEmpty()) {\n logger.debug(\"No auto-attach files configured.\");\n return;\n }\n\n new Thread(new Runnable() {\n @Override\n public void run() {\n try {\n Thread.sleep(5); // Give us a chance to find out what type of media is in the new mount.\n final MediaDetails details = MetadataFinder.getInstance().getMediaDetailsFor(slot);\n if (details != null && details.mediaType == CdjStatus.TrackType.REKORDBOX) {\n // First stage attempt: See if we can match based on stored media details, which is both more reliable and\n // less disruptive than trying to sample the player database to compare entries.\n boolean attached = false;\n for (File file : MetadataFinder.getInstance().getAutoAttachCacheFiles()) {\n final MetadataCache cache = new MetadataCache(file);\n try {\n if (cache.sourceMedia != null && cache.sourceMedia.hashKey().equals(details.hashKey())) {\n // We found a solid match, no need to probe tracks.\n final boolean changed = cache.sourceMedia.hasChanged(details);\n logger.info(\"Auto-attaching metadata cache \" + cache.getName() + \" to slot \" + slot +\n \" based on media details \" + (changed? \"(changed since created)!\" : \"(unchanged).\"));\n MetadataFinder.getInstance().attachMetadataCacheInternal(slot, cache);\n attached = true;\n return;\n }\n } finally {\n if (!attached) {\n cache.close();\n }\n }\n }\n\n // Could not match based on media details; fall back to older method based on probing track metadata.\n ConnectionManager.ClientTask<Object> task = new ConnectionManager.ClientTask<Object>() {\n @Override\n public Object useClient(Client client) throws Exception {\n tryAutoAttachingWithConnection(slot, client);\n return null;\n }\n };\n ConnectionManager.getInstance().invokeWithClientSession(slot.player, task, \"trying to auto-attach metadata cache\");\n }\n } catch (Exception e) {\n logger.error(\"Problem trying to auto-attach metadata cache for slot \" + slot, e);\n }\n\n }\n }, \"Metadata cache file auto-attachment attempt\").start();\n }",
"public static Shell createSubshell(String pathElement, Shell parent, String appName, Object mainHandler) {\n return createSubshell(pathElement, parent, appName, mainHandler, new EmptyMultiMap<String, Object>());\n }",
"public final int toChars(int[] src, int srcOff, int srcLen, char[] dest, int destOff) {\n if (srcLen < 0) {\n throw new IllegalArgumentException(\"srcLen must be >= 0\");\n }\n int written = 0;\n for (int i = 0; i < srcLen; ++i) {\n written += Character.toChars(src[srcOff + i], dest, destOff + written);\n }\n return written;\n }",
"protected Connection openConnection() throws IOException {\n // Perhaps this can just be done once?\n CallbackHandler callbackHandler = null;\n SSLContext sslContext = null;\n if (realm != null) {\n sslContext = realm.getSSLContext();\n CallbackHandlerFactory handlerFactory = realm.getSecretCallbackHandlerFactory();\n if (handlerFactory != null) {\n String username = this.username != null ? this.username : localHostName;\n callbackHandler = handlerFactory.getCallbackHandler(username);\n }\n }\n final ProtocolConnectionConfiguration config = ProtocolConnectionConfiguration.copy(configuration);\n config.setCallbackHandler(callbackHandler);\n config.setSslContext(sslContext);\n config.setUri(uri);\n\n AuthenticationContext authenticationContext = this.authenticationContext != null ? this.authenticationContext : AuthenticationContext.captureCurrent();\n\n // Connect\n try {\n return authenticationContext.run((PrivilegedExceptionAction<Connection>) () -> ProtocolConnectionUtils.connectSync(config));\n } catch (PrivilegedActionException e) {\n if (e.getCause() instanceof IOException) {\n throw (IOException) e.getCause();\n }\n throw new IOException(e);\n }\n }",
"private void populateCalendarException(Record record, ProjectCalendar calendar) throws MPXJException\n {\n Date fromDate = record.getDate(0);\n Date toDate = record.getDate(1);\n boolean working = record.getNumericBoolean(2);\n\n // I have found an example MPX file where a single day exception is expressed with just the start date set.\n // If we find this for we assume that the end date is the same as the start date.\n if (fromDate != null && toDate == null)\n {\n toDate = fromDate;\n }\n\n ProjectCalendarException exception = calendar.addCalendarException(fromDate, toDate);\n if (working)\n {\n addExceptionRange(exception, record.getTime(3), record.getTime(4));\n addExceptionRange(exception, record.getTime(5), record.getTime(6));\n addExceptionRange(exception, record.getTime(7), record.getTime(8));\n }\n }",
"@Override\n public boolean decompose( ZMatrixRMaj A )\n {\n if( A.numRows != A.numCols )\n throw new IllegalArgumentException(\"A must be square.\");\n if( A.numRows <= 0 )\n return false;\n\n QH = A;\n\n N = A.numCols;\n\n if( b.length < N*2 ) {\n b = new double[ N*2 ];\n gammas = new double[ N ];\n u = new double[ N*2 ];\n }\n return _decompose();\n }",
"public LatLong getLocation() {\n if (location == null) {\n location = new LatLong((JSObject) (getJSObject().getMember(\"location\")));\n }\n return location;\n }"
] |
Given a string with method or package name, creates a Class Name with no
spaces and first letter lower case
@param String
- The name of the scenario/story. It should be in lower case.
@returns String - The class name | [
"public static String createFirstLowCaseName(String scenarioDescription) {\n String[] words = scenarioDescription.trim().split(\" \");\n String name = \"\";\n for (int i = 0; i < words.length; i++) {\n name += changeFirstLetterToCapital(words[i]);\n }\n return changeFirstLetterToLowerCase(name);\n }"
] | [
"void bootTimeScan(final DeploymentOperations deploymentOperations) {\n // WFCORE-1579: skip the scan if deployment dir is not available\n if (!checkDeploymentDir(this.deploymentDir)) {\n DeploymentScannerLogger.ROOT_LOGGER.bootTimeScanFailed(deploymentDir.getAbsolutePath());\n return;\n }\n\n this.establishDeployedContentList(this.deploymentDir, deploymentOperations);\n deployedContentEstablished = true;\n if (acquireScanLock()) {\n try {\n scan(true, deploymentOperations);\n } finally {\n releaseScanLock();\n }\n }\n }",
"public static double computeTauAndDivide(final int j, final int numRows ,\n final double[] u , final double max) {\n double tau = 0;\n// double div_max = 1.0/max;\n// if( Double.isInfinite(div_max)) {\n for( int i = j; i < numRows; i++ ) {\n double d = u[i] /= max;\n tau += d*d;\n }\n// } else {\n// for( int i = j; i < numRows; i++ ) {\n// double d = u[i] *= div_max;\n// tau += d*d;\n// }\n// }\n tau = Math.sqrt(tau);\n\n if( u[j] < 0 )\n tau = -tau;\n\n return tau;\n }",
"private void writePropertyStatisticsToFile(UsageStatistics usageStatistics,\n\t\t\tString fileName) {\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(fileName))) {\n\n\t\t\tout.println(\"Property id,in statements,in qualifiers,in references,total\");\n\n\t\t\tfor (Entry<PropertyIdValue, Integer> entry : usageStatistics.propertyCountsMain\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tint qCount = usageStatistics.propertyCountsQualifier.get(entry\n\t\t\t\t\t\t.getKey());\n\t\t\t\tint rCount = usageStatistics.propertyCountsReferences.get(entry\n\t\t\t\t\t\t.getKey());\n\t\t\t\tint total = entry.getValue() + qCount + rCount;\n\t\t\t\tout.println(entry.getKey().getId() + \",\" + entry.getValue()\n\t\t\t\t\t\t+ \",\" + qCount + \",\" + rCount + \",\" + total);\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}",
"protected void layoutGroupSubreports(DJGroup columnsGroup, JRDesignGroup jgroup) {\n\t\tlog.debug(\"Starting subreport layout...\");\n\t\tJRDesignBand footerBand = (JRDesignBand) ((JRDesignSection)jgroup.getGroupFooterSection()).getBandsList().get(0);\n\t\tJRDesignBand headerBand = (JRDesignBand) ((JRDesignSection)jgroup.getGroupHeaderSection()).getBandsList().get(0);\n\n\t\tlayOutSubReportInBand(columnsGroup, headerBand, DJConstants.HEADER);\n\t\tlayOutSubReportInBand(columnsGroup, footerBand, DJConstants.FOOTER);\n\n\t}",
"protected Object getFieldData(Integer id, FieldType type, byte[][] fixedData, Var2Data varData)\n {\n Object result = null;\n\n FieldItem item = m_map.get(type);\n if (item != null)\n {\n result = item.read(id, fixedData, varData);\n }\n\n return result;\n }",
"public double loglikelihood(List<IN> lineInfos) {\r\n double cll = 0.0;\r\n\r\n for (int i = 0; i < lineInfos.size(); i++) {\r\n Datum<String, String> d = makeDatum(lineInfos, i, featureFactory);\r\n Counter<String> c = classifier.logProbabilityOf(d);\r\n\r\n double total = Double.NEGATIVE_INFINITY;\r\n for (String s : c.keySet()) {\r\n total = SloppyMath.logAdd(total, c.getCount(s));\r\n }\r\n cll -= c.getCount(d.label()) - total;\r\n }\r\n // quadratic prior\r\n // HN: TODO: add other priors\r\n\r\n if (classifier instanceof LinearClassifier) {\r\n double sigmaSq = flags.sigma * flags.sigma;\r\n LinearClassifier<String, String> lc = (LinearClassifier<String, String>)classifier;\r\n for (String feature: lc.features()) {\r\n for (String classLabel: classIndex) {\r\n double w = lc.weight(feature, classLabel);\r\n cll += w * w / 2.0 / sigmaSq;\r\n }\r\n }\r\n }\r\n return cll;\r\n }",
"public static boolean isMapLiteralWithOnlyConstantValues(Expression expression) {\r\n if (expression instanceof MapExpression) {\r\n List<MapEntryExpression> entries = ((MapExpression) expression).getMapEntryExpressions();\r\n for (MapEntryExpression entry : entries) {\r\n if (!isConstantOrConstantLiteral(entry.getKeyExpression()) ||\r\n !isConstantOrConstantLiteral(entry.getValueExpression())) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }\r\n return false;\r\n }",
"public void build(double[] coords, int nump) throws IllegalArgumentException {\n if (nump < 4) {\n throw new IllegalArgumentException(\"Less than four input points specified\");\n }\n if (coords.length / 3 < nump) {\n throw new IllegalArgumentException(\"Coordinate array too small for specified number of points\");\n }\n initBuffers(nump);\n setPoints(coords, nump);\n buildHull();\n }",
"public void setHeader(String header, String value) {\n StringValidator.throwIfEmptyOrNull(\"header\", header);\n StringValidator.throwIfEmptyOrNull(\"value\", value);\n\n if (headers == null) {\n headers = new HashMap<String, String>();\n }\n\n headers.put(header, value);\n }"
] |
Combine the iterators into a single one.
@param iterators An iterator of iterators
@return a single combined iterator | [
"public static <T> Iterator<T> concat(Iterator<? extends Iterator<? extends T>> iterators) {\n Preconditions.checkArgumentNotNull(iterators, \"iterators\");\n return new CombinedIterator<T>(iterators);\n }"
] | [
"@Override\n protected void addBuildInfoProperties(BuildInfoBuilder builder) {\n if (envVars != null) {\n for (Map.Entry<String, String> entry : envVars.entrySet()) {\n builder.addProperty(BuildInfoProperties.BUILD_INFO_ENVIRONMENT_PREFIX + entry.getKey(), entry.getValue());\n }\n }\n\n if (sysVars != null) {\n for (Map.Entry<String, String> entry : sysVars.entrySet()) {\n builder.addProperty(entry.getKey(), entry.getValue());\n }\n }\n }",
"private void setFittingWeekDay(Calendar date) {\n\n date.set(Calendar.DAY_OF_MONTH, 1);\n int weekDayFirst = date.get(Calendar.DAY_OF_WEEK);\n int firstFittingWeekDay = (((m_weekDay.toInt() + I_CmsSerialDateValue.NUM_OF_WEEKDAYS) - weekDayFirst)\n % I_CmsSerialDateValue.NUM_OF_WEEKDAYS) + 1;\n int fittingWeekDay = firstFittingWeekDay + (I_CmsSerialDateValue.NUM_OF_WEEKDAYS * m_weekOfMonth.ordinal());\n if (fittingWeekDay > date.getActualMaximum(Calendar.DAY_OF_MONTH)) {\n fittingWeekDay -= I_CmsSerialDateValue.NUM_OF_WEEKDAYS;\n }\n date.set(Calendar.DAY_OF_MONTH, fittingWeekDay);\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 static void objectToXML(Object object, String fileName) throws FileNotFoundException {\r\n\t\tFileOutputStream fo = new FileOutputStream(fileName);\r\n\t\tXMLEncoder encoder = new XMLEncoder(fo);\r\n\t\tencoder.writeObject(object);\r\n\t\tencoder.close();\r\n\t}",
"public ParallelTaskBuilder preparePing() {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.setProtocol(RequestProtocol.PING);\n return cb;\n }",
"@Override\n\tpublic Object executeJavaScript(String code) throws CrawljaxException {\n\t\ttry {\n\t\t\tJavascriptExecutor js = (JavascriptExecutor) browser;\n\t\t\treturn js.executeScript(code);\n\t\t} catch (WebDriverException e) {\n\t\t\tthrowIfConnectionException(e);\n\t\t\tthrow new CrawljaxException(e);\n\t\t}\n\t}",
"private ProjectCalendar getTaskCalendar(Project.Tasks.Task task)\n {\n ProjectCalendar calendar = null;\n\n BigInteger calendarID = task.getCalendarUID();\n if (calendarID != null)\n {\n calendar = m_projectFile.getCalendarByUniqueID(Integer.valueOf(calendarID.intValue()));\n }\n\n return (calendar);\n }",
"private ResourceAssignment getExistingResourceAssignment(Resource resource)\n {\n ResourceAssignment assignment = null;\n Integer resourceUniqueID = null;\n\n if (resource != null)\n {\n Iterator<ResourceAssignment> iter = m_assignments.iterator();\n resourceUniqueID = resource.getUniqueID();\n\n while (iter.hasNext() == true)\n {\n assignment = iter.next();\n Integer uniqueID = assignment.getResourceUniqueID();\n if (uniqueID != null && uniqueID.equals(resourceUniqueID) == true)\n {\n break;\n }\n assignment = null;\n }\n }\n\n return assignment;\n }",
"public int[] getVertexPointIndices() {\n int[] indices = new int[numVertices];\n for (int i = 0; i < numVertices; i++) {\n indices[i] = vertexPointIndices[i];\n }\n return indices;\n }"
] |
once we're on ORM 5 | [
"@Override\n\tprotected void doProcessQueuedOps(PersistentCollection collection, Serializable key, int nextIndex, SharedSessionContractImplementor session)\n\t\t\tthrows HibernateException {\n\t\t// nothing to do\n\t}"
] | [
"public Location getInfo(String placeId, String woeId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_INFO);\r\n\r\n if (placeId != null) {\r\n parameters.put(\"place_id\", placeId);\r\n }\r\n if (woeId != null) {\r\n parameters.put(\"woe_id\", woeId);\r\n }\r\n\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 }",
"private static Set<String> excludedMethods(String... methodNames)\n {\n Set<String> set = new HashSet<String>(MpxjTreeNode.DEFAULT_EXCLUDED_METHODS);\n set.addAll(Arrays.asList(methodNames));\n return set;\n }",
"public <T> Observable<T> delayedEmitAsync(T event, int milliseconds) {\n return Observable.just(event).delay(milliseconds, TimeUnit.MILLISECONDS, Schedulers.immediate());\n }",
"public static String makePropertyName(String name) {\n char[] buf = new char[name.length() + 3];\n int pos = 0;\n buf[pos++] = 's';\n buf[pos++] = 'e';\n buf[pos++] = 't';\n\n for (int ix = 0; ix < name.length(); ix++) {\n char ch = name.charAt(ix);\n if (ix == 0)\n ch = Character.toUpperCase(ch);\n else if (ch == '-') {\n ix++;\n if (ix == name.length())\n break;\n ch = Character.toUpperCase(name.charAt(ix));\n }\n\n buf[pos++] = ch;\n }\n\n return new String(buf, 0, pos);\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 Field getDeclaredFieldWithPath(Class<?> clazz, String path) {\n\n int lastDot = path.lastIndexOf('.');\n\n if (lastDot > -1) {\n String parentPath = path.substring(0, lastDot);\n String fieldName = path.substring(lastDot + 1);\n Field parentField = getDeclaredFieldWithPath(clazz, parentPath);\n return getDeclaredFieldInHierarchy(parentField.getType(), fieldName);\n } else {\n return getDeclaredFieldInHierarchy(clazz, path);\n }\n }",
"public void poseFromBones()\n {\n for (int i = 0; i < getNumBones(); ++i)\n {\n GVRSceneObject bone = mBones[i];\n if (bone == null)\n {\n continue;\n }\n if ((mBoneOptions[i] & BONE_LOCK_ROTATION) != 0)\n {\n continue;\n }\n GVRTransform trans = bone.getTransform();\n mPose.setLocalMatrix(i, trans.getLocalModelMatrix4f());\n }\n mPose.sync();\n updateBonePose();\n }",
"private LocatorSelectionStrategy getLocatorSelectionStrategy(String locatorSelectionStrategy) {\n if (null == locatorSelectionStrategy) {\n return locatorSelectionStrategyMap.get(DEFAULT_STRATEGY).getInstance();\n }\n\n if (LOG.isLoggable(Level.FINE)) {\n LOG.log(Level.FINE, \"Strategy \" + locatorSelectionStrategy\n + \" was set for LocatorClientRegistrar.\");\n }\n\n if (locatorSelectionStrategyMap.containsKey(locatorSelectionStrategy)) {\n return locatorSelectionStrategyMap.get(locatorSelectionStrategy).getInstance();\n } else {\n if (LOG.isLoggable(Level.WARNING)) {\n LOG.log(Level.WARNING, \"LocatorSelectionStrategy \" + locatorSelectionStrategy\n + \" not registered at LocatorClientEnabler.\");\n }\n return locatorSelectionStrategyMap.get(DEFAULT_STRATEGY).getInstance();\n }\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<PaxDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<PaxDate>) super.zonedDateTime(temporal);\n }"
] |
Create a plan. The plan consists of batches. Each batch involves the
movement of no more than batchSize primary partitions. The movement of a
single primary partition may require migration of other n-ary replicas,
and potentially deletions. Migrating a primary or n-ary partition
requires migrating one partition-store for every store hosted at that
partition. | [
"private void plan() {\n // Mapping of stealer node to list of primary partitions being moved\n final TreeMultimap<Integer, Integer> stealerToStolenPrimaryPartitions = TreeMultimap.create();\n\n // Output initial and final cluster\n if(outputDir != null)\n RebalanceUtils.dumpClusters(currentCluster, finalCluster, outputDir);\n\n // Determine which partitions must be stolen\n for(Node stealerNode: finalCluster.getNodes()) {\n List<Integer> stolenPrimaryPartitions = RebalanceUtils.getStolenPrimaryPartitions(currentCluster,\n finalCluster,\n stealerNode.getId());\n if(stolenPrimaryPartitions.size() > 0) {\n numPrimaryPartitionMoves += stolenPrimaryPartitions.size();\n stealerToStolenPrimaryPartitions.putAll(stealerNode.getId(),\n stolenPrimaryPartitions);\n }\n }\n\n // Determine plan batch-by-batch\n int batches = 0;\n Cluster batchCurrentCluster = Cluster.cloneCluster(currentCluster);\n List<StoreDefinition> batchCurrentStoreDefs = this.currentStoreDefs;\n List<StoreDefinition> batchFinalStoreDefs = this.finalStoreDefs;\n Cluster batchFinalCluster = RebalanceUtils.getInterimCluster(this.currentCluster,\n this.finalCluster);\n\n while(!stealerToStolenPrimaryPartitions.isEmpty()) {\n\n int partitions = 0;\n List<Entry<Integer, Integer>> partitionsMoved = Lists.newArrayList();\n for(Entry<Integer, Integer> stealerToPartition: stealerToStolenPrimaryPartitions.entries()) {\n partitionsMoved.add(stealerToPartition);\n batchFinalCluster = UpdateClusterUtils.createUpdatedCluster(batchFinalCluster,\n stealerToPartition.getKey(),\n Lists.newArrayList(stealerToPartition.getValue()));\n partitions++;\n if(partitions == batchSize)\n break;\n }\n\n // Remove the partitions moved\n for(Iterator<Entry<Integer, Integer>> partitionMoved = partitionsMoved.iterator(); partitionMoved.hasNext();) {\n Entry<Integer, Integer> entry = partitionMoved.next();\n stealerToStolenPrimaryPartitions.remove(entry.getKey(), entry.getValue());\n }\n\n if(outputDir != null)\n RebalanceUtils.dumpClusters(batchCurrentCluster,\n batchFinalCluster,\n outputDir,\n \"batch-\" + Integer.toString(batches) + \".\");\n\n // Generate a plan to compute the tasks\n final RebalanceBatchPlan RebalanceBatchPlan = new RebalanceBatchPlan(batchCurrentCluster,\n batchCurrentStoreDefs,\n batchFinalCluster,\n batchFinalStoreDefs);\n batchPlans.add(RebalanceBatchPlan);\n\n numXZonePartitionStoreMoves += RebalanceBatchPlan.getCrossZonePartitionStoreMoves();\n numPartitionStoreMoves += RebalanceBatchPlan.getPartitionStoreMoves();\n nodeMoveMap.add(RebalanceBatchPlan.getNodeMoveMap());\n zoneMoveMap.add(RebalanceBatchPlan.getZoneMoveMap());\n\n batches++;\n batchCurrentCluster = Cluster.cloneCluster(batchFinalCluster);\n // batchCurrentStoreDefs can only be different from\n // batchFinalStoreDefs for the initial batch.\n batchCurrentStoreDefs = batchFinalStoreDefs;\n }\n\n logger.info(this);\n }"
] | [
"public static autoscalepolicy_binding get(nitro_service service, String name) throws Exception{\n\t\tautoscalepolicy_binding obj = new autoscalepolicy_binding();\n\t\tobj.set_name(name);\n\t\tautoscalepolicy_binding response = (autoscalepolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public synchronized void shutdown() {\n checkIsRunning();\n try {\n beanManager().fireEvent(new ContainerBeforeShutdown(id), BeforeDestroyed.Literal.APPLICATION);\n } finally {\n discard(id);\n // Destroy all the dependent beans correctly\n creationalContext.release();\n beanManager().fireEvent(new ContainerShutdown(id), Destroyed.Literal.APPLICATION);\n bootstrap.shutdown();\n WeldSELogger.LOG.weldContainerShutdown(id);\n }\n }",
"public Iterable<BoxLegalHoldAssignment.Info> getAssignments(String type, String id, int limit, String ... fields) {\n QueryStringBuilder builder = new QueryStringBuilder();\n if (type != null) {\n builder.appendParam(\"assign_to_type\", type);\n }\n if (id != null) {\n builder.appendParam(\"assign_to_id\", id);\n }\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields);\n }\n return new BoxResourceIterable<BoxLegalHoldAssignment.Info>(\n this.getAPI(), LEGAL_HOLD_ASSIGNMENTS_URL_TEMPLATE.buildWithQuery(\n this.getAPI().getBaseURL(), builder.toString(), this.getID()), limit) {\n\n @Override\n protected BoxLegalHoldAssignment.Info factory(JsonObject jsonObject) {\n BoxLegalHoldAssignment assignment = new BoxLegalHoldAssignment(\n BoxLegalHoldPolicy.this.getAPI(), jsonObject.get(\"id\").asString());\n return assignment.new Info(jsonObject);\n }\n };\n }",
"@Override\n public JulianDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }",
"public static void hideChannels(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.alsoHide(channel);\r\n }\r\n }\r\n }\r\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 }",
"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}",
"public IPv4AddressSection mask(IPv4AddressSection mask, boolean retainPrefix) throws IncompatibleAddressException, PrefixLenException, SizeMismatchException {\n\t\tcheckMaskSectionCount(mask);\n\t\treturn getSubnetSegments(\n\t\t\t\tthis,\n\t\t\t\tretainPrefix ? getPrefixLength() : null,\n\t\t\t\tgetAddressCreator(),\n\t\t\t\ttrue,\n\t\t\t\tthis::getSegment,\n\t\t\t\ti -> mask.getSegment(i).getSegmentValue(),\n\t\t\t\tfalse);\n\t}",
"public BufferedImage getNewImageInstance() {\n BufferedImage buf = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());\n buf.setData(image.getData());\n return buf;\n }"
] |
Execute a request through Odo processing
@param httpMethodProxyRequest
@param httpServletRequest
@param httpServletResponse
@param history | [
"private void executeProxyRequest(HttpMethod httpMethodProxyRequest,\n HttpServletRequest httpServletRequest,\n HttpServletResponse httpServletResponse, History history) {\n try {\n RequestInformation requestInfo = requestInformation.get();\n\n // Execute the request\n\n // set virtual host so the server knows how to direct the request\n // If the host header exists then this uses that value\n // Otherwise the hostname from the URL is used\n processVirtualHostName(httpMethodProxyRequest, httpServletRequest);\n cullDisabledPaths();\n\n // check for existence of ODO_PROXY_HEADER\n // finding it indicates a bad loop back through the proxy\n if (httpServletRequest.getHeader(Constants.ODO_PROXY_HEADER) != null) {\n logger.error(\"Request has looped back into the proxy. This will not be executed: {}\", httpServletRequest.getRequestURL());\n return;\n }\n\n // set ODO_PROXY_HEADER\n httpMethodProxyRequest.addRequestHeader(Constants.ODO_PROXY_HEADER, \"proxied\");\n\n requestInfo.blockRequest = hasRequestBlock();\n PluginResponse responseWrapper = new PluginResponse(httpServletResponse);\n requestInfo.jsonpCallback = stripJSONPToOutstr(httpServletRequest, responseWrapper);\n\n if (!requestInfo.blockRequest) {\n logger.info(\"Sending request to server\");\n\n history.setModified(requestInfo.modified);\n history.setRequestSent(true);\n\n executeRequest(httpMethodProxyRequest,\n httpServletRequest,\n responseWrapper,\n history);\n } else {\n history.setRequestSent(false);\n }\n\n logOriginalResponseHistory(responseWrapper, history);\n applyResponseOverrides(responseWrapper, httpServletRequest, httpMethodProxyRequest, history);\n // store history\n history.setModified(requestInfo.modified);\n logRequestHistory(httpMethodProxyRequest, responseWrapper, history);\n\n writeResponseOutput(responseWrapper, requestInfo.jsonpCallback);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }"
] | [
"public static <E extends Style.HasCssName, F extends Enum<? extends Style.HasCssName>> void addUniqueEnumStyleName(final UIObject uiObject,\n final Class<F> enumClass,\n final E style) {\n removeEnumStyleNames(uiObject, enumClass);\n addEnumStyleName(uiObject, style);\n }",
"public static int isValid( DMatrixRMaj cov ) {\n if( !MatrixFeatures_DDRM.isDiagonalPositive(cov) )\n return 1;\n\n if( !MatrixFeatures_DDRM.isSymmetric(cov,TOL) )\n return 2;\n\n if( !MatrixFeatures_DDRM.isPositiveSemidefinite(cov) )\n return 3;\n\n return 0;\n }",
"public static tmsessionpolicy_binding get(nitro_service service, String name) throws Exception{\n\t\ttmsessionpolicy_binding obj = new tmsessionpolicy_binding();\n\t\tobj.set_name(name);\n\t\ttmsessionpolicy_binding response = (tmsessionpolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"protected Map getAllVariables(){\n try{\n Iterator names = FreeMarkerTL.getEnvironment().getKnownVariableNames().iterator();\n Map vars = new HashMap();\n while (names.hasNext()) {\n Object name =names.next();\n vars.put(name, get(name.toString()));\n }\n return vars;\n }catch(Exception e){\n throw new ViewException(e);\n }\n }",
"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 }",
"private JSONValue dateToJson(Date d) {\n\n return null != d ? new JSONString(Long.toString(d.getTime())) : null;\n }",
"private static Path resolveDockerDefinition(Path fullpath) {\n final Path ymlPath = fullpath.resolveSibling(fullpath.getFileName() + \".yml\");\n if (Files.exists(ymlPath)) {\n return ymlPath;\n } else {\n final Path yamlPath = fullpath.resolveSibling(fullpath.getFileName() + \".yaml\");\n if (Files.exists(yamlPath)) {\n return yamlPath;\n }\n }\n\n return null;\n }",
"private ProjectFile readFile(String inputFile) throws MPXJException\n {\n ProjectReader reader = new UniversalProjectReader();\n ProjectFile projectFile = reader.read(inputFile);\n if (projectFile == null)\n {\n throw new IllegalArgumentException(\"Unsupported file type\");\n }\n return projectFile;\n }",
"public static sslaction[] get(nitro_service service) throws Exception{\n\t\tsslaction obj = new sslaction();\n\t\tsslaction[] response = (sslaction[])obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Sort MapRows based on a named attribute.
@param rows map rows to sort
@param attribute attribute to sort on
@return list argument (allows method chaining) | [
"private List<MapRow> sort(List<MapRow> rows, final String attribute)\n {\n Collections.sort(rows, new Comparator<MapRow>()\n {\n @Override public int compare(MapRow o1, MapRow o2)\n {\n String value1 = o1.getString(attribute);\n String value2 = o2.getString(attribute);\n return value1.compareTo(value2);\n }\n });\n return rows;\n }"
] | [
"public ItemRequest<Task> delete(String task) {\n \n String path = String.format(\"/tasks/%s\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"DELETE\");\n }",
"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 }",
"public long getTimeFor(int player) {\n TrackPositionUpdate update = positions.get(player);\n if (update != null) {\n return interpolateTimeSinceUpdate(update, System.nanoTime());\n }\n return -1; // We don't know.\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 Predicate is(final String sql) {\n return new Predicate() {\n public String toSql() {\n return sql;\n }\n public void init(AbstractSqlCreator creator) {\n }\n };\n }",
"private void checkGAs(List l)\r\n\t{\r\n\t\tfor (final Iterator i = l.iterator(); i.hasNext();)\r\n\t\t\tif (!(i.next() instanceof GroupAddress))\r\n\t\t\t\tthrow new KNXIllegalArgumentException(\"not a group address list\");\r\n\t}",
"public final ReadOnlyObjectProperty<LatLongBounds> boundsProperty() {\n if (bounds == null) {\n bounds = new ReadOnlyObjectWrapper<>(getBounds());\n addStateEventHandler(MapStateEventType.idle, () -> {\n bounds.set(getBounds());\n });\n }\n return bounds.getReadOnlyProperty();\n }",
"public Metadata createMetadata(String templateName, Metadata metadata) {\n String scope = Metadata.scopeBasedOnType(templateName);\n return this.createMetadata(templateName, scope, metadata);\n }",
"public void process(InputStream is) throws Exception\n {\n readHeader(is);\n readVersion(is);\n readTableData(readTableHeaders(is), is);\n }"
] |
except for the ones that make the content appear under the system bars. | [
"@TargetApi(VERSION_CODES.KITKAT)\n public static void showSystemUI(Activity activity) {\n View decorView = activity.getWindow().getDecorView();\n decorView.setSystemUiVisibility(\n View.SYSTEM_UI_FLAG_LAYOUT_STABLE\n | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION\n | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN\n );\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 }",
"private void addListeners(ProjectReader reader)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n reader.addProjectListener(listener);\n }\n }\n }",
"protected void recordContentLoader(final String patchID, final PatchContentLoader contentLoader) {\n if (contentLoaders.containsKey(patchID)) {\n throw new IllegalStateException(\"Content loader already registered for patch \" + patchID); // internal wrong usage, no i18n\n }\n contentLoaders.put(patchID, contentLoader);\n }",
"public List<String> uuids(long count) {\n final URI uri = new URIBase(clientUri).path(\"_uuids\").query(\"count\", count).build();\n final JsonObject json = get(uri, JsonObject.class);\n return getGson().fromJson(json.get(\"uuids\").toString(), DeserializationTypes.STRINGS);\n }",
"public synchronized PrivateKey getPrivateKeyForLocalCert(final X509Certificate cert)\n\tthrows CertificateEncodingException, KeyStoreException, UnrecoverableKeyException,\n\tNoSuchAlgorithmException\n\t{\n\t\tString thumbprint = ThumbprintUtil.getThumbprint(cert);\n\n\t\treturn (PrivateKey)_ks.getKey(thumbprint, _keypassword);\n\t}",
"public static void cacheParseFailure(XmlFileModel key)\n {\n map.put(getKey(key), new CacheDocument(true, null));\n }",
"public PreparedStatement getPreparedStatement(ClassDescriptor cds, String sql,\r\n boolean scrollable, int explicitFetchSizeHint, boolean callableStmt)\r\n throws PersistenceBrokerException\r\n {\r\n try\r\n {\r\n return cds.getStatementsForClass(m_conMan).getPreparedStmt(m_conMan.getConnection(), sql, scrollable, explicitFetchSizeHint, callableStmt);\r\n }\r\n catch (LookupException e)\r\n {\r\n throw new PersistenceBrokerException(\"Used ConnectionManager instance could not obtain a connection\", e);\r\n }\r\n }",
"private static MonolingualTextValue toTerm(MonolingualTextValue term) {\n\t\treturn term instanceof TermImpl ? term : new TermImpl(term.getLanguageCode(), term.getText());\n\t}",
"public GroovyFieldDoc[] properties() {\n Collections.sort(properties);\n return properties.toArray(new GroovyFieldDoc[properties.size()]);\n }"
] |
Uploads a new file to this folder with custom upload parameters.
@param uploadParams the custom upload parameters.
@return the uploaded file's info. | [
"public BoxFile.Info uploadFile(FileUploadParams uploadParams) {\n URL uploadURL = UPLOAD_FILE_URL.build(this.getAPI().getBaseUploadURL());\n BoxMultipartRequest request = new BoxMultipartRequest(getAPI(), uploadURL);\n\n JsonObject fieldJSON = new JsonObject();\n JsonObject parentIdJSON = new JsonObject();\n parentIdJSON.add(\"id\", getID());\n fieldJSON.add(\"name\", uploadParams.getName());\n fieldJSON.add(\"parent\", parentIdJSON);\n\n if (uploadParams.getCreated() != null) {\n fieldJSON.add(\"content_created_at\", BoxDateFormat.format(uploadParams.getCreated()));\n }\n\n if (uploadParams.getModified() != null) {\n fieldJSON.add(\"content_modified_at\", BoxDateFormat.format(uploadParams.getModified()));\n }\n\n if (uploadParams.getSHA1() != null && !uploadParams.getSHA1().isEmpty()) {\n request.setContentSHA1(uploadParams.getSHA1());\n }\n\n if (uploadParams.getDescription() != null) {\n fieldJSON.add(\"description\", uploadParams.getDescription());\n }\n\n request.putField(\"attributes\", fieldJSON.toString());\n\n if (uploadParams.getSize() > 0) {\n request.setFile(uploadParams.getContent(), uploadParams.getName(), uploadParams.getSize());\n } else if (uploadParams.getContent() != null) {\n request.setFile(uploadParams.getContent(), uploadParams.getName());\n } else {\n request.setUploadFileCallback(uploadParams.getUploadFileCallback(), uploadParams.getName());\n }\n\n BoxJSONResponse response;\n if (uploadParams.getProgressListener() == null) {\n response = (BoxJSONResponse) request.send();\n } else {\n response = (BoxJSONResponse) request.send(uploadParams.getProgressListener());\n }\n JsonObject collection = JsonObject.readFrom(response.getJSON());\n JsonArray entries = collection.get(\"entries\").asArray();\n JsonObject fileInfoJSON = entries.get(0).asObject();\n String uploadedFileID = fileInfoJSON.get(\"id\").asString();\n\n BoxFile uploadedFile = new BoxFile(getAPI(), uploadedFileID);\n return uploadedFile.new Info(fileInfoJSON);\n }"
] | [
"private void writeMapFile(String mapFileName, File jarFile, boolean mapClassMethods) throws IOException, XMLStreamException, ClassNotFoundException, IntrospectionException\n {\n FileWriter fw = new FileWriter(mapFileName);\n XMLOutputFactory xof = XMLOutputFactory.newInstance();\n XMLStreamWriter writer = xof.createXMLStreamWriter(fw);\n //XMLStreamWriter writer = new IndentingXMLStreamWriter(xof.createXMLStreamWriter(fw));\n\n writer.writeStartDocument();\n writer.writeStartElement(\"root\");\n writer.writeStartElement(\"assembly\");\n\n addClasses(writer, jarFile, mapClassMethods);\n\n writer.writeEndElement();\n writer.writeEndElement();\n writer.writeEndDocument();\n writer.flush();\n writer.close();\n\n fw.flush();\n fw.close();\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 }",
"protected boolean checkvalue(String colorvalue) {\n\n boolean valid = validateColorValue(colorvalue);\n if (valid) {\n if (colorvalue.length() == 4) {\n char[] chr = colorvalue.toCharArray();\n for (int i = 1; i < 4; i++) {\n String foo = String.valueOf(chr[i]);\n colorvalue = colorvalue.replaceFirst(foo, foo + foo);\n }\n }\n m_textboxColorValue.setValue(colorvalue, true);\n m_colorField.getElement().getStyle().setBackgroundColor(colorvalue);\n m_colorValue = colorvalue;\n }\n return valid;\n }",
"public static appfwlearningsettings[] get(nitro_service service) throws Exception{\n\t\tappfwlearningsettings obj = new appfwlearningsettings();\n\t\tappfwlearningsettings[] response = (appfwlearningsettings[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"@SuppressWarnings(\"unchecked\")\n public <T extends ReportModel> T getReportByName(String name, Class<T> clazz)\n {\n WindupVertexFrame model = this.getUniqueByProperty(ReportModel.REPORT_NAME, name);\n try\n {\n return (T) model;\n }\n catch (ClassCastException ex)\n {\n throw new WindupException(\"The vertex is not of expected frame type \" + clazz.getName() + \": \" + model.toPrettyString());\n }\n }",
"public boolean isLabelAnnotationIntroducingCharacter(char ch) {\r\n char[] cutChars = labelAnnotationIntroducingCharacters();\r\n for (char cutChar : cutChars) {\r\n if (ch == cutChar) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }",
"public static StoreDefinition getStoreDef(List<StoreDefinition> list, String name) {\n for(StoreDefinition def: list)\n if(def.getName().equals(name))\n return def;\n return null;\n }",
"public boolean getBoxBound(float[] corners)\n {\n int rc;\n if ((corners == null) || (corners.length != 6) ||\n ((rc = NativeVertexBuffer.getBoundingVolume(getNative(), corners)) < 0))\n {\n throw new IllegalArgumentException(\"Cannot copy box bound into array provided\");\n }\n return rc != 0;\n }",
"public static base_response disable(nitro_service client, nsfeature resource) throws Exception {\n\t\tnsfeature disableresource = new nsfeature();\n\t\tdisableresource.feature = resource.feature;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}"
] |
Convert an operation for deployment overlays to be executed on local servers.
Since this might be called in the case of redeployment of affected deployments, we need to take into account
the composite op resulting from such a transformation
@see AffectedDeploymentOverlay#redeployLinksAndTransformOperationForDomain
@param operation
@param host
@return | [
"private Map<Set<ServerIdentity>, ModelNode> getDeploymentOverlayOperations(ModelNode operation,\n ModelNode host) {\n final PathAddress realAddress = PathAddress.pathAddress(operation.get(OP_ADDR));\n if (realAddress.size() == 0 && COMPOSITE.equals(operation.get(OP).asString())) {\n //We have a composite operation resulting from a transformation to redeploy affected deployments\n //See redeploying deployments affected by an overlay.\n ModelNode serverOp = operation.clone();\n Map<ServerIdentity, Operations.CompositeOperationBuilder> composite = new HashMap<>();\n for (ModelNode step : serverOp.get(STEPS).asList()) {\n ModelNode newStep = step.clone();\n String groupName = PathAddress.pathAddress(step.get(OP_ADDR)).getElement(0).getValue();\n newStep.get(OP_ADDR).set(PathAddress.pathAddress(step.get(OP_ADDR)).subAddress(1).toModelNode());\n Set<ServerIdentity> servers = getServersForGroup(groupName, host, localHostName, serverProxies);\n for(ServerIdentity server : servers) {\n if(!composite.containsKey(server)) {\n composite.put(server, Operations.CompositeOperationBuilder.create());\n }\n composite.get(server).addStep(newStep);\n }\n if(!servers.isEmpty()) {\n newStep.get(OP_ADDR).set(PathAddress.pathAddress(step.get(OP_ADDR)).subAddress(1).toModelNode());\n }\n }\n if(!composite.isEmpty()) {\n Map<Set<ServerIdentity>, ModelNode> result = new HashMap<>();\n for(Entry<ServerIdentity, Operations.CompositeOperationBuilder> entry : composite.entrySet()) {\n result.put(Collections.singleton(entry.getKey()), entry.getValue().build().getOperation());\n }\n return result;\n }\n return Collections.emptyMap();\n }\n final Set<ServerIdentity> allServers = getAllRunningServers(host, localHostName, serverProxies);\n return Collections.singletonMap(allServers, operation.clone());\n }"
] | [
"protected void emitWithBurstCheck(float[] particlePositions, float[] particleVelocities,\n float[] particleTimeStamps)\n {\n if ( burstMode )\n {\n if ( executeOnce )\n {\n emit(particlePositions, particleVelocities, particleTimeStamps);\n executeOnce = false;\n }\n }\n else\n {\n emit(particlePositions, particleVelocities, particleTimeStamps);\n }\n\n }",
"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 }",
"public static void findSomeStringProperties(ApiConnection connection)\n\t\t\tthrows MediaWikiApiErrorException, IOException {\n\t\tWikibaseDataFetcher wbdf = new WikibaseDataFetcher(connection, siteIri);\n\t\twbdf.getFilter().excludeAllProperties();\n\t\twbdf.getFilter().setLanguageFilter(Collections.singleton(\"en\"));\n\n\t\tArrayList<PropertyIdValue> stringProperties = new ArrayList<>();\n\n\t\tSystem.out\n\t\t\t\t.println(\"*** Trying to find string properties for the example ... \");\n\t\tint propertyNumber = 1;\n\t\twhile (stringProperties.size() < 5) {\n\t\t\tArrayList<String> fetchProperties = new ArrayList<>();\n\t\t\tfor (int i = propertyNumber; i < propertyNumber + 10; i++) {\n\t\t\t\tfetchProperties.add(\"P\" + i);\n\t\t\t}\n\t\t\tpropertyNumber += 10;\n\t\t\tMap<String, EntityDocument> results = wbdf\n\t\t\t\t\t.getEntityDocuments(fetchProperties);\n\t\t\tfor (EntityDocument ed : results.values()) {\n\t\t\t\tPropertyDocument pd = (PropertyDocument) ed;\n\t\t\t\tif (DatatypeIdValue.DT_STRING.equals(pd.getDatatype().getIri())\n\t\t\t\t\t\t&& pd.getLabels().containsKey(\"en\")) {\n\t\t\t\t\tstringProperties.add(pd.getEntityId());\n\t\t\t\t\tSystem.out.println(\"* Found string property \"\n\t\t\t\t\t\t\t+ pd.getEntityId().getId() + \" (\"\n\t\t\t\t\t\t\t+ pd.getLabels().get(\"en\") + \")\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tstringProperty1 = stringProperties.get(0);\n\t\tstringProperty2 = stringProperties.get(1);\n\t\tstringProperty3 = stringProperties.get(2);\n\t\tstringProperty4 = stringProperties.get(3);\n\t\tstringProperty5 = stringProperties.get(4);\n\n\t\tSystem.out.println(\"*** Done.\");\n\t}",
"public static ConstraintType getInstance(Locale locale, String type)\n {\n int index = 0;\n\n String[] constraintTypes = LocaleData.getStringArray(locale, LocaleData.CONSTRAINT_TYPES);\n for (int loop = 0; loop < constraintTypes.length; loop++)\n {\n if (constraintTypes[loop].equalsIgnoreCase(type) == true)\n {\n index = loop;\n break;\n }\n }\n\n return (ConstraintType.getInstance(index));\n }",
"private void deliverFaderStartCommand(Set<Integer> playersToStart, Set<Integer> playersToStop) {\n for (final FaderStartListener listener : getFaderStartListeners()) {\n try {\n listener.fadersChanged(playersToStart, playersToStop);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering fader start command to listener\", t);\n }\n }\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 }",
"static byte[] hmacSha1(StringBuilder message, String key) {\n try {\n Mac mac = Mac.getInstance(\"HmacSHA1\");\n mac.init(new SecretKeySpec(key.getBytes(), \"HmacSHA1\"));\n return mac.doFinal(message.toString().getBytes());\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<CopticDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<CopticDate>) super.zonedDateTime(temporal);\n }",
"public static scala.collection.Iterable linkedListToScalaIterable(LinkedList<?> linkedList) {\n return JavaConverters.asScalaIterableConverter(linkedList).asScala();\n }"
] |
Set the specific device class of the node.
@param specificDeviceClass the specificDeviceClass to set
@exception IllegalArgumentException thrown when the specific device class does not match
the generic device class. | [
"public void setSpecificDeviceClass(Specific specificDeviceClass) throws IllegalArgumentException {\r\n\t\t\r\n\t\t// The specific Device class does not match the generic device class.\r\n\t\tif (specificDeviceClass.genericDeviceClass != Generic.NOT_KNOWN && \r\n\t\t\t\tspecificDeviceClass.genericDeviceClass != this.genericDeviceClass)\r\n\t\t\tthrow new IllegalArgumentException(\"specificDeviceClass\");\r\n\t\t\r\n\t\tthis.specificDeviceClass = specificDeviceClass;\r\n\t}"
] | [
"public void start() {\n nsLock.writeLock().lock();\n try {\n if (runnerThread != null) {\n return;\n }\n runnerThread =\n new Thread(new NamespaceChangeStreamRunner(\n new WeakReference<>(this), networkMonitor, logger));\n runnerThread.start();\n } finally {\n nsLock.writeLock().unlock();\n }\n }",
"private static void listProjectProperties(ProjectFile file)\n {\n SimpleDateFormat df = new SimpleDateFormat(\"dd/MM/yyyy HH:mm z\");\n ProjectProperties properties = file.getProjectProperties();\n Date startDate = properties.getStartDate();\n Date finishDate = properties.getFinishDate();\n String formattedStartDate = startDate == null ? \"(none)\" : df.format(startDate);\n String formattedFinishDate = finishDate == null ? \"(none)\" : df.format(finishDate);\n\n System.out.println(\"MPP file type: \" + properties.getMppFileType());\n System.out.println(\"Project Properties: StartDate=\" + formattedStartDate + \" FinishDate=\" + formattedFinishDate);\n System.out.println();\n }",
"@Override\n\tpublic void Invoke(final String method, JSONArray args,\n\t\t\tHubInvokeCallback callback) {\n\n\t\tif (method == null)\n {\n throw new IllegalArgumentException(\"method\");\n }\n\n if (args == null)\n {\n throw new IllegalArgumentException(\"args\");\n }\n\n final String callbackId = mConnection.RegisterCallback(callback);\n\n HubInvocation hubData = new HubInvocation(mHubName, method, args, callbackId);\n\n String value = hubData.Serialize();\n\n mConnection.Send(value, new SendCallback() \n {\n\t\t\t@Override\n\t\t\tpublic void OnSent(CharSequence messageSent) {\n\t\t\t\tLog.v(TAG, \"Invoke of \" + method + \"sent to \" + mHubName);\n\t\t\t\t// callback.OnSent() ??!?!?\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void OnError(Exception ex) {\n\t\t\t\t// TODO Cancel the callback\n\t\t\t\tLog.e(TAG, \"Failed to invoke \" + method + \"on \" + mHubName);\n\t\t\t\tmConnection.RemoveCallback(callbackId);\n\t\t\t\t// callback.OnError() ?!?!?\n\t\t\t}\n });\n }",
"public String get(final String key) {\n final Collection<Argument> args = map.get(key);\n if (args != null) {\n return args.iterator().hasNext() ? args.iterator().next().getValue() : null;\n }\n return null;\n }",
"public static tmtrafficpolicy_lbvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\ttmtrafficpolicy_lbvserver_binding obj = new tmtrafficpolicy_lbvserver_binding();\n\t\tobj.set_name(name);\n\t\ttmtrafficpolicy_lbvserver_binding response[] = (tmtrafficpolicy_lbvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public synchronized void addMapStats(\n final MapfishMapContext mapContext, final MapAttribute.MapAttributeValues mapValues) {\n this.mapStats.add(new MapStats(mapContext, mapValues));\n }",
"public void configure(Properties props) throws HibernateException {\r\n\t\ttry{\r\n\t\t\tthis.config = new BoneCPConfig(props);\r\n\r\n\t\t\t// old hibernate config\r\n\t\t\tString url = props.getProperty(CONFIG_CONNECTION_URL);\r\n\t\t\tString username = props.getProperty(CONFIG_CONNECTION_USERNAME);\r\n\t\t\tString password = props.getProperty(CONFIG_CONNECTION_PASSWORD);\r\n\t\t\tString driver = props.getProperty(CONFIG_CONNECTION_DRIVER_CLASS);\r\n\t\t\tif (url == null){\r\n\t\t\t\turl = props.getProperty(CONFIG_CONNECTION_URL_ALTERNATE);\r\n\t\t\t}\r\n\t\t\tif (username == null){\r\n\t\t\t\tusername = props.getProperty(CONFIG_CONNECTION_USERNAME_ALTERNATE);\r\n\t\t\t}\r\n\t\t\tif (password == null){\r\n\t\t\t\tpassword = props.getProperty(CONFIG_CONNECTION_PASSWORD_ALTERNATE);\r\n\t\t\t}\r\n\t\t\tif (driver == null){\r\n\t\t\t\tdriver = props.getProperty(CONFIG_CONNECTION_DRIVER_CLASS_ALTERNATE);\r\n\t\t\t}\r\n\r\n\t\t\tif (url != null){\r\n\t\t\t\tthis.config.setJdbcUrl(url);\r\n\t\t\t}\r\n\t\t\tif (username != null){\r\n\t\t\t\tthis.config.setUsername(username);\r\n\t\t\t}\r\n\t\t\tif (password != null){\r\n\t\t\t\tthis.config.setPassword(password);\r\n\t\t\t}\r\n\r\n\r\n\t\t\t// Remember Isolation level\r\n\t\t\tthis.isolation = ConfigurationHelper.getInteger(AvailableSettings.ISOLATION, props);\r\n\t\t\tthis.autocommit = ConfigurationHelper.getBoolean(AvailableSettings.AUTOCOMMIT, props);\r\n\r\n\t\t\tlogger.debug(this.config.toString());\r\n\r\n\t\t\tif (driver != null && !driver.trim().equals(\"\")){\r\n\t\t\t\tloadClass(driver);\r\n\t\t\t}\r\n\t\t\tif (this.config.getConnectionHookClassName() != null){\r\n\t\t\t\tObject hookClass = loadClass(this.config.getConnectionHookClassName()).newInstance();\r\n\t\t\t\tthis.config.setConnectionHook((ConnectionHook) hookClass);\r\n\t\t\t}\r\n\t\t\t// create the connection pool\r\n\t\t\tthis.pool = createPool(this.config);\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new HibernateException(e);\r\n\t\t}\r\n\t}",
"public static String formatDateRange(Context context, ReadablePartial start, ReadablePartial end, int flags) {\n return formatDateRange(context, toMillis(start), toMillis(end), flags);\n }",
"List<Message> getFullTrackList(final CdjStatus.TrackSourceSlot slot, final Client client, final int sortOrder)\n throws IOException, InterruptedException, TimeoutException {\n // Send the metadata menu request\n if (client.tryLockingForMenuOperations(MENU_TIMEOUT, TimeUnit.SECONDS)) {\n try {\n Message response = client.menuRequest(Message.KnownType.TRACK_MENU_REQ, Message.MenuIdentifier.MAIN_MENU, slot,\n new NumberField(sortOrder));\n final long count = response.getMenuResultsCount();\n if (count == Message.NO_MENU_RESULTS_AVAILABLE || count == 0) {\n return Collections.emptyList();\n }\n\n // Gather all the metadata menu items\n return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slot, CdjStatus.TrackType.REKORDBOX, response);\n }\n finally {\n client.unlockForMenuOperations();\n }\n } else {\n throw new TimeoutException(\"Unable to lock the player for menu operations\");\n }\n }"
] |
Replaces new line delimiters in the input stream with the Unix line feed.
@param input | [
"public static byte[] toUnixLineEndings( InputStream input ) throws IOException {\n String encoding = \"ISO-8859-1\";\n FixCrLfFilter filter = new FixCrLfFilter(new InputStreamReader(input, encoding));\n filter.setEol(FixCrLfFilter.CrLf.newInstance(\"unix\"));\n\n ByteArrayOutputStream filteredFile = new ByteArrayOutputStream();\n Utils.copy(new ReaderInputStream(filter, encoding), filteredFile);\n\n return filteredFile.toByteArray();\n }"
] | [
"private void readPattern(JSONObject patternJson) {\n\n setPatternType(readPatternType(patternJson));\n setInterval(readOptionalInt(patternJson, JsonKey.PATTERN_INTERVAL));\n setWeekDays(readWeekDays(patternJson));\n setDayOfMonth(readOptionalInt(patternJson, JsonKey.PATTERN_DAY_OF_MONTH));\n setEveryWorkingDay(readOptionalBoolean(patternJson, JsonKey.PATTERN_EVERYWORKINGDAY));\n setWeeksOfMonth(readWeeksOfMonth(patternJson));\n setIndividualDates(readDates(readOptionalArray(patternJson, JsonKey.PATTERN_DATES)));\n setMonth(readOptionalMonth(patternJson, JsonKey.PATTERN_MONTH));\n\n }",
"public void setResource(Resource resource)\n {\n m_resource = resource;\n String name = m_resource.getName();\n if (name == null || name.length() == 0)\n {\n name = \"Unnamed Resource\";\n }\n setName(name);\n }",
"public static <T> Object callMethod(Object obj,\n Class<T> c,\n String name,\n Class<?>[] classes,\n Object[] args) {\n try {\n Method m = getMethod(c, name, classes);\n return m.invoke(obj, args);\n } catch(InvocationTargetException e) {\n throw getCause(e);\n } catch(IllegalAccessException e) {\n throw new IllegalStateException(e);\n }\n }",
"private void processHyperlinkData(Resource resource, byte[] data)\n {\n if (data != null)\n {\n int offset = 12;\n String hyperlink;\n String address;\n String subaddress;\n\n offset += 12;\n hyperlink = MPPUtility.getUnicodeString(data, offset);\n offset += ((hyperlink.length() + 1) * 2);\n\n offset += 12;\n address = MPPUtility.getUnicodeString(data, offset);\n offset += ((address.length() + 1) * 2);\n\n offset += 12;\n subaddress = MPPUtility.getUnicodeString(data, offset);\n\n resource.setHyperlink(hyperlink);\n resource.setHyperlinkAddress(address);\n resource.setHyperlinkSubAddress(subaddress);\n }\n }",
"public static String getCacheDir(Context ctx) {\n return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || (!Environment.isExternalStorageRemovable() && ctx.getExternalCacheDir() != null) ?\n ctx.getExternalCacheDir().getPath() : ctx.getCacheDir().getPath();\n }",
"private static TransportType map2TransportType(String transportId) {\n TransportType type;\n if (CXF_HTTP_TRANSPORT_ID.equals(transportId) || SOAP_HTTP_TRANSPORT_ID.equals(transportId)) {\n type = TransportType.HTTP;\n } else {\n type = TransportType.OTHER;\n }\n return type;\n }",
"public static double I0(double x) {\r\n double ans;\r\n double ax = Math.abs(x);\r\n\r\n if (ax < 3.75) {\r\n double y = x / 3.75;\r\n y = y * y;\r\n ans = 1.0 + y * (3.5156229 + y * (3.0899424 + y * (1.2067492\r\n + y * (0.2659732 + y * (0.360768e-1 + y * 0.45813e-2)))));\r\n } else {\r\n double y = 3.75 / ax;\r\n ans = (Math.exp(ax) / Math.sqrt(ax)) * (0.39894228 + y * (0.1328592e-1\r\n + y * (0.225319e-2 + y * (-0.157565e-2 + y * (0.916281e-2\r\n + y * (-0.2057706e-1 + y * (0.2635537e-1 + y * (-0.1647633e-1\r\n + y * 0.392377e-2))))))));\r\n }\r\n\r\n return ans;\r\n }",
"public static final CurrencySymbolPosition parseCurrencySymbolPosition(String value)\n {\n CurrencySymbolPosition result = CurrencySymbolPosition.BEFORE;\n\n switch (NumberHelper.getInt(value))\n {\n case 0:\n {\n result = CurrencySymbolPosition.BEFORE;\n break;\n }\n\n case 1:\n {\n result = CurrencySymbolPosition.AFTER;\n break;\n }\n\n case 2:\n {\n result = CurrencySymbolPosition.BEFORE_WITH_SPACE;\n break;\n }\n\n case 3:\n {\n result = CurrencySymbolPosition.AFTER_WITH_SPACE;\n break;\n }\n }\n\n return (result);\n }",
"public Iterator getAllBaseTypes()\r\n {\r\n ArrayList baseTypes = new ArrayList();\r\n\r\n baseTypes.addAll(_directBaseTypes.values());\r\n\r\n for (int idx = baseTypes.size() - 1; idx >= 0; idx--)\r\n {\r\n ClassDescriptorDef curClassDef = (ClassDescriptorDef)baseTypes.get(idx);\r\n\r\n for (Iterator it = curClassDef.getDirectBaseTypes(); it.hasNext();)\r\n {\r\n ClassDescriptorDef curBaseTypeDef = (ClassDescriptorDef)it.next();\r\n\r\n if (!baseTypes.contains(curBaseTypeDef))\r\n {\r\n baseTypes.add(0, curBaseTypeDef);\r\n idx++;\r\n }\r\n }\r\n }\r\n return baseTypes.iterator();\r\n }"
] |
Helper method to remove invalid children that don't have a corresponding CmsSitemapClientEntry. | [
"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 }"
] | [
"@RequestMapping(value = \"/api/profile\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getList(Model model) throws Exception {\n logger.info(\"Using a GET request to list profiles\");\n return Utils.getJQGridJSON(profileService.findAllProfiles(), \"profiles\");\n }",
"public double[] getMoneynessAsOffsets() {\r\n\t\tDoubleStream moneyness = getGridNodesPerMoneyness().keySet().stream().mapToDouble(Integer::doubleValue);\r\n\t\tif(quotingConvention == QuotingConvention.PAYERVOLATILITYLOGNORMAL) {\r\n\t\t\tmoneyness = moneyness.map(new DoubleUnaryOperator() {\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic double applyAsDouble(double x) {\r\n\t\t\t\t\treturn x * 0.01;\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t} else if(quotingConvention == QuotingConvention.RECEIVERPRICE) {\r\n\t\t\tmoneyness = moneyness.map(new DoubleUnaryOperator() {\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic double applyAsDouble(double x) {\r\n\t\t\t\t\treturn - x * 0.0001;\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t} else {\r\n\t\t\tmoneyness = moneyness.map(new DoubleUnaryOperator() {\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic double applyAsDouble(double x) {\r\n\t\t\t\t\treturn x * 0.0001;\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t}\r\n\t\treturn moneyness.toArray();\r\n\t}",
"public static final Date utc2date(Long time) {\n\n // don't accept negative values\n if (time == null || time < 0) return null;\n \n // add the timezone offset\n time += timezoneOffsetMillis(new Date(time));\n\n return new Date(time);\n }",
"public static final BigInteger printDay(Day day)\n {\n return (day == null ? null : BigInteger.valueOf(day.getValue() - 1));\n }",
"public void setAllowBlank(boolean allowBlank) {\n this.allowBlank = allowBlank;\n\n // Setup the allow blank validation\n if (!allowBlank) {\n if (blankValidator == null) {\n blankValidator = createBlankValidator();\n }\n setupBlurValidation();\n addValidator(blankValidator);\n } else {\n removeValidator(blankValidator);\n }\n }",
"protected static CallableStatement memorize(final CallableStatement target, final ConnectionHandle connectionHandle) {\n\t\treturn (CallableStatement) Proxy.newProxyInstance(\n\t\t\t\tCallableStatementProxy.class.getClassLoader(),\n\t\t\t\tnew Class[] {CallableStatementProxy.class},\n\t\t\t\tnew MemorizeTransactionProxy(target, connectionHandle));\n\t}",
"public static BoxItem.Info getSharedItem(BoxAPIConnection api, String sharedLink) {\n return getSharedItem(api, sharedLink, null);\n }",
"public String getAccuracyDescription(int numDigits) {\r\n NumberFormat nf = NumberFormat.getNumberInstance();\r\n nf.setMaximumFractionDigits(numDigits);\r\n Triple<Double, Integer, Integer> accu = getAccuracyInfo();\r\n return nf.format(accu.first()) + \" (\" + accu.second() + \"/\" + (accu.second() + accu.third()) + \")\";\r\n }",
"public MtasCQLParserSentenceCondition createFullSentence()\n throws ParseException {\n if (fullCondition == null) {\n if (secondSentencePart == null) {\n if (firstBasicSentence != null) {\n fullCondition = new MtasCQLParserSentenceCondition(firstBasicSentence,\n ignoreClause, maximumIgnoreLength);\n\n } else {\n fullCondition = firstSentence;\n }\n fullCondition.setOccurence(firstMinimumOccurence,\n firstMaximumOccurence);\n if (firstOptional) {\n fullCondition.setOptional(firstOptional);\n }\n return fullCondition;\n } else {\n if (!orOperator) {\n if (firstBasicSentence != null) {\n firstBasicSentence.setOccurence(firstMinimumOccurence,\n firstMaximumOccurence);\n firstBasicSentence.setOptional(firstOptional);\n fullCondition = new MtasCQLParserSentenceCondition(\n firstBasicSentence, ignoreClause, maximumIgnoreLength);\n } else {\n firstSentence.setOccurence(firstMinimumOccurence,\n firstMaximumOccurence);\n firstSentence.setOptional(firstOptional);\n fullCondition = new MtasCQLParserSentenceCondition(firstSentence,\n ignoreClause, maximumIgnoreLength);\n }\n fullCondition.addSentenceToEndLatestSequence(\n secondSentencePart.createFullSentence());\n } else {\n MtasCQLParserSentenceCondition sentence = secondSentencePart\n .createFullSentence();\n if (firstBasicSentence != null) {\n sentence.addSentenceAsFirstOption(\n new MtasCQLParserSentenceCondition(firstBasicSentence,\n ignoreClause, maximumIgnoreLength));\n } else {\n sentence.addSentenceAsFirstOption(firstSentence);\n }\n fullCondition = sentence;\n }\n return fullCondition;\n }\n } else {\n return fullCondition;\n }\n }"
] |
Get the authentication method to use.
@return authentication method | [
"@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 String readCorrelationId(Message message) {\n String correlationId = null;\n Map<String, List<String>> headers = getOrCreateProtocolHeader(message);\n List<String> correlationIds = headers.get(CORRELATION_ID_KEY);\n if (correlationIds != null && correlationIds.size() > 0) {\n correlationId = correlationIds.get(0);\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"HTTP header '\" + CORRELATION_ID_KEY + \"' found: \" + correlationId);\n }\n } else {\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"No HTTP header '\" + CORRELATION_ID_KEY + \"' found\");\n }\n }\n\n return correlationId;\n }",
"protected void init(DMatrixRMaj A ) {\n UBV = A;\n\n m = UBV.numRows;\n n = UBV.numCols;\n\n min = Math.min(m,n);\n int max = Math.max(m,n);\n\n if( b.length < max+1 ) {\n b = new double[ max+1 ];\n u = new double[ max+1 ];\n }\n if( gammasU.length < m ) {\n gammasU = new double[ m ];\n }\n if( gammasV.length < n ) {\n gammasV = new double[ n ];\n }\n }",
"public static TransactionalProtocolClient.Operation wrap(final ModelNode operation, final OperationMessageHandler messageHandler, final OperationAttachments attachments) {\n return new TransactionalOperationImpl(operation, messageHandler, attachments);\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 static int cudnnConvolutionForward(\n cudnnHandle handle, \n Pointer alpha, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n cudnnFilterDescriptor wDesc, \n Pointer w, \n cudnnConvolutionDescriptor convDesc, \n int algo, \n Pointer workSpace, \n long workSpaceSizeInBytes, \n Pointer beta, \n cudnnTensorDescriptor yDesc, \n Pointer y)\n {\n return checkResult(cudnnConvolutionForwardNative(handle, alpha, xDesc, x, wDesc, w, convDesc, algo, workSpace, workSpaceSizeInBytes, beta, yDesc, y));\n }",
"public Set<ConstraintViolation> validate(DataSetInfo info) {\r\n\t\tSet<ConstraintViolation> errors = new LinkedHashSet<ConstraintViolation>();\r\n\t\ttry {\r\n\t\t\tif (info.isMandatory() && get(info.getDataSetNumber()) == null) {\r\n\t\t\t\terrors.add(new ConstraintViolation(info, ConstraintViolation.MANDATORY_MISSING));\r\n\t\t\t}\r\n\t\t\tif (!info.isRepeatable() && getAll(info.getDataSetNumber()).size() > 1) {\r\n\t\t\t\terrors.add(new ConstraintViolation(info, ConstraintViolation.REPEATABLE_REPEATED));\r\n\t\t\t}\r\n\t\t} catch (SerializationException e) {\r\n\t\t\terrors.add(new ConstraintViolation(info, ConstraintViolation.INVALID_VALUE));\r\n\t\t}\r\n\t\treturn errors;\r\n\t}",
"public GroovyClassDoc[] innerClasses() {\n Collections.sort(nested);\n return nested.toArray(new GroovyClassDoc[nested.size()]);\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 }",
"public void scale(double v){\n\t\tfor(int i = 0; i < this.size(); i++){\n\t\t\tthis.get(i).scale(v);;\n\t\t}\n\t}"
] |
Return the knot at a given position.
@param x the position
@return the knot number, or 1 if no knot found | [
"public int knotAt(int x) {\n\t\tfor (int i = 1; i < numKnots-1; i++)\n\t\t\tif (xKnots[i+1] > x)\n\t\t\t\treturn i;\n\t\treturn 1;\n\t}"
] | [
"public List<Throwable> getCauses(Throwable t)\n {\n List<Throwable> causes = new LinkedList<Throwable>();\n Throwable next = t;\n while (next.getCause() != null)\n {\n next = next.getCause();\n causes.add(next);\n }\n return causes;\n }",
"public List<Shard> getShards() {\n InputStream response = null;\n try {\n response = client.couchDbClient.get(new DatabaseURIHelper(db.getDBUri()).path(\"_shards\")\n .build());\n return getResponseList(response, client.getGson(), DeserializationTypes.SHARDS);\n } finally {\n close(response);\n }\n }",
"public boolean contentEquals(byte[] bytes, int offset, int len) {\n Preconditions.checkArgument(len >= 0 && offset >= 0 && offset + len <= bytes.length);\n return contentEqualsUnchecked(bytes, offset, len);\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 }",
"synchronized boolean reload(int permit, boolean suspend) {\n return internalSetState(new ReloadTask(permit, suspend), InternalState.SERVER_STARTED, InternalState.RELOADING);\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 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 }",
"public boolean filter(Event event) {\n LOG.info(\"StringContentFilter called\");\n \n if (wordsToFilter != null) {\n for (String filterWord : wordsToFilter) {\n if (event.getContent() != null\n && -1 != event.getContent().indexOf(filterWord)) {\n return true;\n }\n }\n }\n return false;\n }",
"public static List<DockerImage> getDockerImagesFromAgents(final int buildInfoId, TaskListener listener) throws IOException, InterruptedException {\n List<DockerImage> dockerImages = new ArrayList<DockerImage>();\n\n // Collect images from the master:\n dockerImages.addAll(getAndDiscardImagesByBuildId(buildInfoId));\n\n // Collect images from all the agents:\n List<Node> nodes = Jenkins.getInstance().getNodes();\n for (Node node : nodes) {\n if (node == null || node.getChannel() == null) {\n continue;\n }\n try {\n List<DockerImage> partialDockerImages = node.getChannel().call(new MasterToSlaveCallable<List<DockerImage>, IOException>() {\n public List<DockerImage> call() throws IOException {\n List<DockerImage> dockerImages = new ArrayList<DockerImage>();\n dockerImages.addAll(getAndDiscardImagesByBuildId(buildInfoId));\n return dockerImages;\n }\n });\n dockerImages.addAll(partialDockerImages);\n } catch (Exception e) {\n listener.getLogger().println(\"Could not collect docker images from Jenkins node '\" + node.getDisplayName() + \"' due to: \" + e.getMessage());\n }\n }\n return dockerImages;\n }"
] |
Opens a new FileOutputStream for a file of the given name in the given
result directory. Any file of this name that exists already will be
replaced. The caller is responsible for eventually closing the stream.
@param resultDirectory
the path to the result directory
@param filename
the name of the file to write to
@return FileOutputStream for the file
@throws IOException
if the file or example output directory could not be created | [
"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}"
] | [
"public static base_response add(nitro_service client, cachepolicylabel resource) throws Exception {\n\t\tcachepolicylabel addresource = new cachepolicylabel();\n\t\taddresource.labelname = resource.labelname;\n\t\taddresource.evaluates = resource.evaluates;\n\t\treturn addresource.add_resource(client);\n\t}",
"public static void getHistory() throws Exception{\n Client client = new Client(\"ProfileName\", false);\n\n // Obtain the 100 history entries starting from offset 0\n History[] history = client.refreshHistory(100, 0);\n\n client.clearHistory();\n }",
"private ModelNode resolveSubsystems(final List<ModelNode> extensions) {\n\n HostControllerLogger.ROOT_LOGGER.debug(\"Applying extensions provided by master\");\n final ModelNode result = operationExecutor.installSlaveExtensions(extensions);\n if (!SUCCESS.equals(result.get(OUTCOME).asString())) {\n throw HostControllerLogger.ROOT_LOGGER.failedToAddExtensions(result.get(FAILURE_DESCRIPTION));\n }\n final ModelNode subsystems = new ModelNode();\n for (final ModelNode extension : extensions) {\n extensionRegistry.recordSubsystemVersions(extension.asString(), subsystems);\n }\n return subsystems;\n }",
"public static authenticationtacacspolicy_systemglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationtacacspolicy_systemglobal_binding obj = new authenticationtacacspolicy_systemglobal_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationtacacspolicy_systemglobal_binding response[] = (authenticationtacacspolicy_systemglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private List<DomainControllerData> readFromFile(String directoryName) {\n List<DomainControllerData> data = new ArrayList<DomainControllerData>();\n if (directoryName == null) {\n return data;\n }\n\n if (conn == null) {\n init();\n }\n\n try {\n if (usingPreSignedUrls()) {\n PreSignedUrlParser parsedPut = new PreSignedUrlParser(pre_signed_put_url);\n directoryName = parsedPut.getPrefix();\n }\n String key = S3Util.sanitize(directoryName) + \"/\" + S3Util.sanitize(DC_FILE_NAME);\n GetResponse val = conn.get(location, key, null);\n if (val.object != null) {\n byte[] buf = val.object.data;\n if (buf != null && buf.length > 0) {\n try {\n data = S3Util.domainControllerDataFromByteBuffer(buf);\n } catch (Exception e) {\n throw HostControllerLogger.ROOT_LOGGER.failedMarshallingDomainControllerData();\n }\n }\n }\n return data;\n } catch (IOException e) {\n throw HostControllerLogger.ROOT_LOGGER.cannotAccessS3File(e.getLocalizedMessage());\n }\n }",
"public static float noise1(float x) {\n int bx0, bx1;\n float rx0, rx1, sx, t, u, v;\n\n if (start) {\n start = false;\n init();\n }\n\n t = x + N;\n bx0 = ((int)t) & BM;\n bx1 = (bx0+1) & BM;\n rx0 = t - (int)t;\n rx1 = rx0 - 1.0f;\n\n sx = sCurve(rx0);\n\n u = rx0 * g1[p[bx0]];\n v = rx1 * g1[p[bx1]];\n return 2.3f*lerp(sx, u, v);\n }",
"protected void internalReleaseConnection(ConnectionHandle connectionHandle) throws SQLException {\r\n\t\tif (!this.cachedPoolStrategy){\r\n\t\t\tconnectionHandle.clearStatementCaches(false);\r\n\t\t}\r\n\r\n\t\tif (connectionHandle.getReplayLog() != null){\r\n\t\t\tconnectionHandle.getReplayLog().clear();\r\n\t\t\tconnectionHandle.recoveryResult.getReplaceTarget().clear();\r\n\t\t}\r\n\r\n\t\tif (connectionHandle.isExpired() || \r\n\t\t\t\t(!this.poolShuttingDown \r\n\t\t\t\t\t\t&& connectionHandle.isPossiblyBroken()\r\n\t\t\t\t&& !isConnectionHandleAlive(connectionHandle))){\r\n\r\n if (connectionHandle.isExpired()) {\r\n connectionHandle.internalClose();\r\n }\r\n\r\n\t\t\tConnectionPartition connectionPartition = connectionHandle.getOriginatingPartition();\r\n\t\t\tpostDestroyConnection(connectionHandle);\r\n\r\n\t\t\tmaybeSignalForMoreConnections(connectionPartition);\r\n\t\t\tconnectionHandle.clearStatementCaches(true);\r\n\t\t\treturn; // don't place back in queue - connection is broken or expired.\r\n\t\t}\r\n\r\n\r\n\t\tconnectionHandle.setConnectionLastUsedInMs(System.currentTimeMillis());\r\n\t\tif (!this.poolShuttingDown){\r\n\t\t\tputConnectionBackInPartition(connectionHandle);\r\n\t\t} else {\r\n\t\t\tconnectionHandle.internalClose();\r\n\t\t}\r\n\t}",
"public static String getTypeValue(Class<? extends WindupFrame> clazz)\n {\n TypeValue typeValueAnnotation = clazz.getAnnotation(TypeValue.class);\n if (typeValueAnnotation == null)\n throw new IllegalArgumentException(\"Class \" + clazz.getCanonicalName() + \" lacks a @TypeValue annotation\");\n\n return typeValueAnnotation.value();\n }",
"public static double[][] pseudoInverse(double[][] matrix){\n\t\tif(isSolverUseApacheCommonsMath) {\n\t\t\t// Use LU from common math\n\t\t\tSingularValueDecomposition svd = new SingularValueDecomposition(new Array2DRowRealMatrix(matrix));\n\t\t\tdouble[][] matrixInverse = svd.getSolver().getInverse().getData();\n\n\t\t\treturn matrixInverse;\n\t\t}\n\t\telse {\n\t\t\treturn org.jblas.Solve.pinv(new org.jblas.DoubleMatrix(matrix)).toArray2();\n\t\t}\n\t}"
] |
Log a message with a throwable at the provided level. | [
"public void log(Level level, Throwable throwable, String msg, Object[] argArray) {\n\t\tlogIfEnabled(level, throwable, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, argArray);\n\t}"
] | [
"public Date getFinishDate()\n {\n Date result = (Date) getCachedValue(ProjectField.FINISH_DATE);\n if (result == null)\n {\n result = getParentFile().getFinishDate();\n }\n return (result);\n }",
"public void setCanvasWidthHeight(int width, int height) {\n hudWidth = width;\n hudHeight = height;\n HUD = Bitmap.createBitmap(width, height, Config.ARGB_8888);\n canvas = new Canvas(HUD);\n texture = null;\n }",
"public List<IssueCategory> getIssueCategories()\n {\n return this.issueCategories.values().stream()\n .sorted((category1, category2) -> category1.getPriority() - category2.getPriority())\n .collect(Collectors.toList());\n }",
"private int checkInInternal() {\n\n m_logStream.println(\"[\" + new Date() + \"] STARTING Git task\");\n m_logStream.println(\"=========================\");\n m_logStream.println();\n\n if (m_checkout) {\n m_logStream.println(\"Running checkout script\");\n\n } else if (!(m_resetHead || m_resetRemoteHead)) {\n m_logStream.println(\"Exporting relevant modules\");\n m_logStream.println(\"--------------------------\");\n m_logStream.println();\n\n exportModules();\n\n m_logStream.println();\n m_logStream.println(\"Calling script to check in the exports\");\n m_logStream.println(\"--------------------------------------\");\n m_logStream.println();\n\n } else {\n\n m_logStream.println();\n m_logStream.println(\"Calling script to reset the repository\");\n m_logStream.println(\"--------------------------------------\");\n m_logStream.println();\n\n }\n\n int exitCode = runCommitScript();\n if (exitCode != 0) {\n m_logStream.println();\n m_logStream.println(\"ERROR: Something went wrong. The script got exitcode \" + exitCode + \".\");\n m_logStream.println();\n }\n if ((exitCode == 0) && m_checkout) {\n boolean importOk = importModules();\n if (!importOk) {\n return -1;\n }\n }\n m_logStream.println(\"[\" + new Date() + \"] FINISHED Git task\");\n m_logStream.println();\n m_logStream.close();\n\n return exitCode;\n }",
"public <T extends Widget & Checkable> List<Integer> getCheckedWidgetIndexes() {\n List<Integer> checked = new ArrayList<>();\n List<Widget> children = getChildren();\n\n final int size = children.size();\n for (int i = 0, j = -1; i < size; ++i) {\n Widget c = children.get(i);\n if (c instanceof Checkable) {\n ++j;\n if (((Checkable) c).isChecked()) {\n checked.add(j);\n }\n }\n }\n\n return checked;\n }",
"public static void mark(DeploymentUnit unit) {\n unit = DeploymentUtils.getTopDeploymentUnit(unit);\n unit.putAttachment(MARKER, Boolean.TRUE);\n }",
"private void pushDeviceToken(final String token, final boolean register, final PushType type) {\n pushDeviceToken(this.context, token, register, type);\n }",
"public static void createEphemeralPath(ZkClient zkClient, String path, String data) {\n try {\n zkClient.createEphemeral(path, Utils.getBytes(data));\n } catch (ZkNoNodeException e) {\n createParentPath(zkClient, path);\n zkClient.createEphemeral(path, Utils.getBytes(data));\n }\n }",
"public static Object objectify(ObjectMapper mapper, Object source) {\n return objectify(mapper, source, Object.class);\n }"
] |
Returns the value stored for the given key at the point of call.
@param key a non null key
@return the value stored in the map for the given key | [
"public V get(K key) {\n ManagedReference<V> ref = internalMap.get(key);\n if (ref!=null) return ref.get();\n return null;\n }"
] | [
"public static int cudnnGetReductionWorkspaceSize(\n cudnnHandle handle, \n cudnnReduceTensorDescriptor reduceTensorDesc, \n cudnnTensorDescriptor aDesc, \n cudnnTensorDescriptor cDesc, \n long[] sizeInBytes)\n {\n return checkResult(cudnnGetReductionWorkspaceSizeNative(handle, reduceTensorDesc, aDesc, cDesc, sizeInBytes));\n }",
"public List<EnabledEndpoint> getEnabledEndpoints(int pathId, String clientUUID, String[] filters) throws Exception {\n ArrayList<EnabledEndpoint> enabledOverrides = new ArrayList<EnabledEndpoint>();\n PreparedStatement query = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n query = 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 query.setInt(1, pathId);\n query.setString(2, clientUUID);\n results = query.executeQuery();\n\n while (results.next()) {\n EnabledEndpoint endpoint = this.getPartialEnabledEndpointFromResultset(results);\n com.groupon.odo.proxylib.models.Method m = PathOverrideService.getInstance().getMethodForOverrideId(endpoint.getOverrideId());\n\n // this is an errant entry.. perhaps a method got deleted from a plugin\n // we'll also remove it from the endpoint\n if (m == null) {\n PathOverrideService.getInstance().removeOverride(endpoint.getOverrideId());\n continue;\n }\n\n // check filters and see if any match\n boolean addOverride = false;\n if (filters != null) {\n for (String filter : filters) {\n if (m.getMethodType().endsWith(filter)) {\n addOverride = true;\n break;\n }\n }\n } else {\n // if there are no filters then we assume that the requester wants all enabled overrides\n addOverride = true;\n }\n\n if (addOverride) {\n enabledOverrides.add(endpoint);\n }\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 (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n\n // now go through the ArrayList and get the method for all of the endpoints\n // have to do this so we don't have overlapping SQL queries\n ArrayList<EnabledEndpoint> enabledOverridesWithMethods = new ArrayList<EnabledEndpoint>();\n for (EnabledEndpoint endpoint : enabledOverrides) {\n if (endpoint.getOverrideId() >= 0) {\n com.groupon.odo.proxylib.models.Method m = PathOverrideService.getInstance().getMethodForOverrideId(endpoint.getOverrideId());\n endpoint.setMethodInformation(m);\n }\n enabledOverridesWithMethods.add(endpoint);\n }\n\n return enabledOverridesWithMethods;\n }",
"public void setOuterConeAngle(float angle)\n {\n setFloat(\"outer_cone_angle\", (float) Math.cos(Math.toRadians(angle)));\n mChanged.set(true);\n }",
"public void setCycleInterval(float newCycleInterval) {\n if ( (this.cycleInterval != newCycleInterval) && (newCycleInterval > 0) ) {\n for (GVRNodeAnimation gvrKeyFrameAnimation : gvrKeyFrameAnimations) {\n //TODO Cannot easily change the GVRAnimation's GVRChannel once set.\n }\n this.cycleInterval = newCycleInterval;\n }\n }",
"private void userInfoInit() {\n\t\tboolean first = true;\n\t\tuserId = null;\n\t\tuserLocale = null;\n\t\tuserName = null;\n\t\tuserOrganization = null;\n\t\tuserDivision = null;\n\t\tif (null != authentications) {\n\t\t\tfor (Authentication auth : authentications) {\n\t\t\t\tuserId = combine(userId, auth.getUserId());\n\t\t\t\tuserName = combine(userName, auth.getUserName());\n\t\t\t\tif (first) {\n\t\t\t\t\tuserLocale = auth.getUserLocale();\n\t\t\t\t\tfirst = false;\n\t\t\t\t} else {\n\t\t\t\t\tif (null != auth.getUserLocale() &&\n\t\t\t\t\t\t\t(null == userLocale || !userLocale.equals(auth.getUserLocale()))) {\n\t\t\t\t\t\tuserLocale = null;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tuserOrganization = combine(userOrganization, auth.getUserOrganization());\n\t\t\t\tuserDivision = combine(userDivision, auth.getUserDivision());\n\t\t\t}\n\t\t}\n\n\t\t// now calculate the \"id\" for this context, this should be independent of the data order, so sort\n\t\tMap<String, List<String>> idParts = new HashMap<String, List<String>>();\n\t\tif (null != authentications) {\n\t\t\tfor (Authentication auth : authentications) {\n\t\t\t\tList<String> auths = new ArrayList<String>();\n\t\t\t\tfor (BaseAuthorization ba : auth.getAuthorizations()) {\n\t\t\t\t\tauths.add(ba.getId());\n\t\t\t\t}\n\t\t\t\tCollections.sort(auths);\n\t\t\t\tidParts.put(auth.getSecurityServiceId(), auths);\n\t\t\t}\n\t\t}\n\t\tStringBuilder sb = new StringBuilder();\n\t\tList<String> sortedKeys = new ArrayList<String>(idParts.keySet());\n\t\tCollections.sort(sortedKeys);\n\t\tfor (String key : sortedKeys) {\n\t\t\tif (sb.length() > 0) {\n\t\t\t\tsb.append('|');\n\t\t\t}\n\t\t\tList<String> auths = idParts.get(key);\n\t\t\tfirst = true;\n\t\t\tfor (String ak : auths) {\n\t\t\t\tif (first) {\n\t\t\t\t\tfirst = false;\n\t\t\t\t} else {\n\t\t\t\t\tsb.append('|');\n\t\t\t\t}\n\t\t\t\tsb.append(ak);\n\t\t\t}\n\t\t\tsb.append('@');\n\t\t\tsb.append(key);\n\t\t}\n\t\tid = sb.toString();\n\t}",
"@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 systemsession get(nitro_service service, Long sid) throws Exception{\n\t\tsystemsession obj = new systemsession();\n\t\tobj.set_sid(sid);\n\t\tsystemsession response = (systemsession) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private void setFittingWeekDay(Calendar date) {\n\n date.set(Calendar.DAY_OF_MONTH, 1);\n int weekDayFirst = date.get(Calendar.DAY_OF_WEEK);\n int firstFittingWeekDay = (((m_weekDay.toInt() + I_CmsSerialDateValue.NUM_OF_WEEKDAYS) - weekDayFirst)\n % I_CmsSerialDateValue.NUM_OF_WEEKDAYS) + 1;\n int fittingWeekDay = firstFittingWeekDay + (I_CmsSerialDateValue.NUM_OF_WEEKDAYS * m_weekOfMonth.ordinal());\n if (fittingWeekDay > date.getActualMaximum(Calendar.DAY_OF_MONTH)) {\n fittingWeekDay -= I_CmsSerialDateValue.NUM_OF_WEEKDAYS;\n }\n date.set(Calendar.DAY_OF_MONTH, fittingWeekDay);\n }",
"public static dnstxtrec[] get(nitro_service service) throws Exception{\n\t\tdnstxtrec obj = new dnstxtrec();\n\t\tdnstxtrec[] response = (dnstxtrec[])obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Use this API to unset the properties of sslcertkey resources.
Properties that need to be unset are specified in args array. | [
"public static base_responses unset(nitro_service client, String certkey[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (certkey != null && certkey.length > 0) {\n\t\t\tsslcertkey unsetresources[] = new sslcertkey[certkey.length];\n\t\t\tfor (int i=0;i<certkey.length;i++){\n\t\t\t\tunsetresources[i] = new sslcertkey();\n\t\t\t\tunsetresources[i].certkey = certkey[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}"
] | [
"public static base_response Import(nitro_service client, sslfipskey resource) throws Exception {\n\t\tsslfipskey Importresource = new sslfipskey();\n\t\tImportresource.fipskeyname = resource.fipskeyname;\n\t\tImportresource.key = resource.key;\n\t\tImportresource.inform = resource.inform;\n\t\tImportresource.wrapkeyname = resource.wrapkeyname;\n\t\tImportresource.iv = resource.iv;\n\t\tImportresource.exponent = resource.exponent;\n\t\treturn Importresource.perform_operation(client,\"Import\");\n\t}",
"private byte[] getData(List<byte[]> blocks, int length)\n {\n byte[] result;\n\n if (blocks.isEmpty() == false)\n {\n if (length < 4)\n {\n length = 4;\n }\n\n result = new byte[length];\n int offset = 0;\n byte[] data;\n\n while (offset < length)\n {\n data = blocks.remove(0);\n System.arraycopy(data, 0, result, offset, data.length);\n offset += data.length;\n }\n }\n else\n {\n result = null;\n }\n\n return (result);\n }",
"public StackTraceElement[] asStackTrace() {\n\t\tint i = 1;\n\t\tStackTraceElement[] list = new StackTraceElement[this.size()];\n\t\tfor (Eventable e : this) {\n\t\t\tlist[this.size() - i] =\n\t\t\t\t\tnew StackTraceElement(e.getEventType().toString(), e.getIdentification()\n\t\t\t\t\t\t\t.toString(), e.getElement().toString(), i);\n\t\t\ti++;\n\t\t}\n\t\treturn list;\n\t}",
"@RequestMapping(value = \"/legendgraphic\", method = RequestMethod.GET)\n\tpublic ModelAndView getGraphic(@RequestParam(\"layerId\") String layerId,\n\t\t\t@RequestParam(value = \"styleName\", required = false) String styleName,\n\t\t\t@RequestParam(value = \"ruleIndex\", required = false) Integer ruleIndex,\n\t\t\t@RequestParam(value = \"format\", required = false) String format,\n\t\t\t@RequestParam(value = \"width\", required = false) Integer width,\n\t\t\t@RequestParam(value = \"height\", required = false) Integer height,\n\t\t\t@RequestParam(value = \"scale\", required = false) Double scale,\n\t\t\t@RequestParam(value = \"allRules\", required = false) Boolean allRules, HttpServletRequest request)\n\t\t\tthrows GeomajasException {\n\t\tif (!allRules) {\n\t\t\treturn getGraphic(layerId, styleName, ruleIndex, format, width, height, scale);\n\t\t} else {\n\t\t\treturn getGraphics(layerId, styleName, format, width, height, scale);\n\t\t}\n\t}",
"public IPv6AddressSegment join(IPv6AddressCreator creator, IPv4AddressSegment low) throws IncompatibleAddressException {\r\n\t\tint shift = IPv4Address.BITS_PER_SEGMENT;\r\n\t\tInteger prefix = getJoinedSegmentPrefixLength(shift, getSegmentPrefixLength(), low.getSegmentPrefixLength());\r\n\t\tif(isMultiple()) {\r\n\t\t\t//if the high segment has a range, the low segment must match the full range, \r\n\t\t\t//otherwise it is not possible to create an equivalent range when joining\r\n\t\t\tif(!low.isFullRange()) {\r\n\t\t\t\tthrow new IncompatibleAddressException(this, low, \"ipaddress.error.invalidMixedRange\");\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn creator.createSegment(\r\n\t\t\t\t(getSegmentValue() << shift) | low.getSegmentValue(), \r\n\t\t\t\t(getUpperSegmentValue() << shift) | low.getUpperSegmentValue(),\r\n\t\t\t\tprefix);\r\n\t}",
"public static long count(nitro_service service, String ciphergroupname) throws Exception{\n\t\tsslcipher_individualcipher_binding obj = new sslcipher_individualcipher_binding();\n\t\tobj.set_ciphergroupname(ciphergroupname);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tsslcipher_individualcipher_binding response[] = (sslcipher_individualcipher_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 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}",
"public static final Date getTimestampFromTenths(byte[] data, int offset)\n {\n long ms = ((long) getInt(data, offset)) * 6000;\n return (DateHelper.getTimestampFromLong(EPOCH + ms));\n }",
"public void setAlias(UserAlias userAlias)\r\n\t{\r\n\t\tm_alias = userAlias.getName();\r\n\r\n\t\t// propagate to SelectionCriteria,not to Criteria\r\n\t\tfor (int i = 0; i < m_criteria.size(); i++)\r\n\t\t{\r\n\t\t\tif (!(m_criteria.elementAt(i) instanceof Criteria))\r\n\t\t\t{\r\n\t\t\t\t((SelectionCriteria) m_criteria.elementAt(i)).setAlias(userAlias);\r\n\t\t\t}\r\n\t\t}\r\n\t}"
] |
Open an OutputStream and execute the function using the OutputStream.
@param function the function to execute
@return the URI and the file size | [
"protected PrintResult withOpenOutputStream(final PrintAction function) throws Exception {\n final File reportFile = getReportFile();\n final Processor.ExecutionContext executionContext;\n try (FileOutputStream out = new FileOutputStream(reportFile);\n BufferedOutputStream bout = new BufferedOutputStream(out)) {\n executionContext = function.run(bout);\n }\n return new PrintResult(reportFile.length(), executionContext);\n }"
] | [
"public static vrid6[] get(nitro_service service) throws Exception{\n\t\tvrid6 obj = new vrid6();\n\t\tvrid6[] response = (vrid6[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public SingleProfileBackup getProfileBackupData(int profileID, String clientUUID) throws Exception {\n SingleProfileBackup singleProfileBackup = new SingleProfileBackup();\n List<PathOverride> enabledPaths = new ArrayList<>();\n\n List<EndpointOverride> paths = PathOverrideService.getInstance().getPaths(profileID, clientUUID, null);\n for (EndpointOverride override : paths) {\n if (override.getRequestEnabled() || override.getResponseEnabled()) {\n PathOverride pathOverride = new PathOverride();\n pathOverride.setPathName(override.getPathName());\n if (override.getRequestEnabled()) {\n pathOverride.setRequestEnabled(true);\n }\n if (override.getResponseEnabled()) {\n pathOverride.setResponseEnabled(true);\n }\n\n pathOverride.setEnabledEndpoints(override.getEnabledEndpoints());\n enabledPaths.add(pathOverride);\n }\n }\n singleProfileBackup.setEnabledPaths(enabledPaths);\n\n Client backupClient = ClientService.getInstance().findClient(clientUUID, profileID);\n ServerGroup activeServerGroup = ServerRedirectService.getInstance().getServerGroup(backupClient.getActiveServerGroup(), profileID);\n singleProfileBackup.setActiveServerGroup(activeServerGroup);\n\n return singleProfileBackup;\n }",
"public static BoxStoragePolicyAssignment.Info create(BoxAPIConnection api, String policyID, String userID) {\n URL url = STORAGE_POLICY_ASSIGNMENT_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, HttpMethod.POST);\n JsonObject requestJSON = new JsonObject()\n .add(\"storage_policy\", new JsonObject()\n .add(\"type\", \"storage_policy\")\n .add(\"id\", policyID))\n .add(\"assigned_to\", new JsonObject()\n .add(\"type\", \"user\")\n .add(\"id\", userID));\n\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxStoragePolicyAssignment storagePolicyAssignment = new BoxStoragePolicyAssignment(api,\n responseJSON.get(\"id\").asString());\n\n return storagePolicyAssignment.new Info(responseJSON);\n }",
"private static List< Block > createBlocks(int[] data, boolean debug) {\r\n\r\n List< Block > blocks = new ArrayList<>();\r\n Block current = null;\r\n\r\n for (int i = 0; i < data.length; i++) {\r\n EncodingMode mode = chooseMode(data[i]);\r\n if ((current != null && current.mode == mode) &&\r\n (mode != EncodingMode.NUM || current.length < MAX_NUMERIC_COMPACTION_BLOCK_SIZE)) {\r\n current.length++;\r\n } else {\r\n current = new Block(mode);\r\n blocks.add(current);\r\n }\r\n }\r\n\r\n if (debug) {\r\n System.out.println(\"Initial block pattern: \" + blocks);\r\n }\r\n\r\n smoothBlocks(blocks);\r\n\r\n if (debug) {\r\n System.out.println(\"Final block pattern: \" + blocks);\r\n }\r\n\r\n return blocks;\r\n }",
"public static final BigInteger printDay(Day day)\n {\n return (day == null ? null : BigInteger.valueOf(day.getValue() - 1));\n }",
"public List<String> getModuleVersions(final String name, final FiltersHolder filters) {\n final List<String> versions = repositoryHandler.getModuleVersions(name, filters);\n\n if (versions.isEmpty()) {\n throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)\n .entity(\"Module \" + name + \" does not exist.\").build());\n }\n\n return versions;\n }",
"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 int addServerGroup(String groupName, int profileId) throws Exception {\n int groupId = -1;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\"INSERT INTO \" + Constants.DB_TABLE_SERVER_GROUPS\n + \"(\" + Constants.GENERIC_NAME + \",\" +\n Constants.GENERIC_PROFILE_ID + \")\"\n + \" VALUES (?, ?);\", PreparedStatement.RETURN_GENERATED_KEYS);\n statement.setString(1, groupName);\n statement.setInt(2, profileId);\n statement.executeUpdate();\n\n results = statement.getGeneratedKeys();\n\n if (results.next()) {\n groupId = results.getInt(1);\n } else {\n // something went wrong\n throw new Exception(\"Could not add group\");\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return groupId;\n }",
"private void checkAndAddRequiredSubStrings(final List<String> requiredSubStrings) {\n\t\tfor( String required : requiredSubStrings ) {\n\t\t\tif( required == null ) {\n\t\t\t\tthrow new NullPointerException(\"required substring should not be null\");\n\t\t\t}\n\t\t\tthis.requiredSubStrings.add(required);\n\t\t}\n\t}"
] |
Convert maturity given as offset in months to year fraction.
@param maturityInMonths The maturity as offset in months.
@return The maturity as year fraction. | [
"private double convertMaturity(int maturityInMonths) {\r\n\t\tSchedule schedule = fixMetaSchedule.generateSchedule(referenceDate, maturityInMonths, 12);\r\n\t\treturn schedule.getFixing(0);\r\n\t}"
] | [
"public static service_stats get(nitro_service service, String name) throws Exception{\n\t\tservice_stats obj = new service_stats();\n\t\tobj.set_name(name);\n\t\tservice_stats response = (service_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"public void pauseUpload() throws LocalOperationException {\n if (state == State.UPLOADING) {\n setState(State.PAUSED);\n executor.hardStop();\n } else {\n throw new LocalOperationException(\"Attempt to pause upload while assembly is not uploading\");\n }\n }",
"public void setFrustum(float[] frustum)\n {\n Matrix4f projMatrix = new Matrix4f();\n projMatrix.setFrustum(frustum[0], frustum[3], frustum[1], frustum[4], frustum[2], frustum[5]);\n setFrustum(projMatrix);\n }",
"private static void generateJson(CellScanner cellScanner, Function<Bytes, String> encoder,\n PrintStream out) throws JsonIOException {\n Gson gson = new GsonBuilder().serializeNulls().setDateFormat(DateFormat.LONG)\n .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).setVersion(1.0)\n .create();\n\n Map<String, String> json = new LinkedHashMap<>();\n for (RowColumnValue rcv : cellScanner) {\n json.put(FLUO_ROW, encoder.apply(rcv.getRow()));\n json.put(FLUO_COLUMN_FAMILY, encoder.apply(rcv.getColumn().getFamily()));\n json.put(FLUO_COLUMN_QUALIFIER, encoder.apply(rcv.getColumn().getQualifier()));\n json.put(FLUO_COLUMN_VISIBILITY, encoder.apply(rcv.getColumn().getVisibility()));\n json.put(FLUO_VALUE, encoder.apply(rcv.getValue()));\n gson.toJson(json, out);\n out.append(\"\\n\");\n\n if (out.checkError()) {\n break;\n }\n }\n out.flush();\n }",
"void addValue(V value, Resource resource) {\n\t\tthis.valueQueue.add(value);\n\t\tthis.valueSubjectQueue.add(resource);\n\t}",
"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 }",
"public static AssociationKeyMetadata getInverseAssociationKeyMetadata(OgmEntityPersister mainSidePersister, int propertyIndex) {\n\t\tType propertyType = mainSidePersister.getPropertyTypes()[propertyIndex];\n\t\tSessionFactoryImplementor factory = mainSidePersister.getFactory();\n\n\t\t// property represents no association, so no inverse meta-data can exist\n\t\tif ( !propertyType.isAssociationType() ) {\n\t\t\treturn null;\n\t\t}\n\n\t\tJoinable mainSideJoinable = ( (AssociationType) propertyType ).getAssociatedJoinable( factory );\n\t\tOgmEntityPersister inverseSidePersister = null;\n\n\t\t// to-many association\n\t\tif ( mainSideJoinable.isCollection() ) {\n\t\t\tinverseSidePersister = (OgmEntityPersister) ( (OgmCollectionPersister) mainSideJoinable ).getElementPersister();\n\t\t}\n\t\t// to-one\n\t\telse {\n\t\t\tinverseSidePersister = (OgmEntityPersister) mainSideJoinable;\n\t\t\tmainSideJoinable = mainSidePersister;\n\t\t}\n\n\t\tString mainSideProperty = mainSidePersister.getPropertyNames()[propertyIndex];\n\n\t\t// property is a one-to-one association (a many-to-one cannot be on the inverse side) -> get the meta-data\n\t\t// straight from the main-side persister\n\t\tAssociationKeyMetadata inverseOneToOneMetadata = mainSidePersister.getInverseOneToOneAssociationKeyMetadata( mainSideProperty );\n\t\tif ( inverseOneToOneMetadata != null ) {\n\t\t\treturn inverseOneToOneMetadata;\n\t\t}\n\n\t\t// process properties of inverse side and try to find association back to main side\n\t\tfor ( String candidateProperty : inverseSidePersister.getPropertyNames() ) {\n\t\t\tType type = inverseSidePersister.getPropertyType( candidateProperty );\n\n\t\t\t// candidate is a *-to-many association\n\t\t\tif ( type.isCollectionType() ) {\n\t\t\t\tOgmCollectionPersister inverseCollectionPersister = getPersister( factory, (CollectionType) type );\n\t\t\t\tString mappedByProperty = inverseCollectionPersister.getMappedByProperty();\n\t\t\t\tif ( mainSideProperty.equals( mappedByProperty ) ) {\n\t\t\t\t\tif ( isCollectionMatching( mainSideJoinable, inverseCollectionPersister ) ) {\n\t\t\t\t\t\treturn inverseCollectionPersister.getAssociationKeyMetadata();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}",
"private void persistDisabledVersion(long version) throws PersistenceFailureException {\n File disabledMarker = getDisabledMarkerFile(version);\n try {\n disabledMarker.createNewFile();\n } catch (IOException e) {\n throw new PersistenceFailureException(\"Failed to create the disabled marker at path: \" +\n disabledMarker.getAbsolutePath() + \"\\nThe store/version \" +\n \"will remain disabled only until the next restart.\", e);\n }\n }",
"public void setBackgroundColor(int colorRes) {\n if (getBackground() instanceof ShapeDrawable) {\n final Resources res = getResources();\n ((ShapeDrawable) getBackground()).getPaint().setColor(res.getColor(colorRes));\n }\n }"
] |
Returns a simple web page where certs can be downloaded. This is meant for mobile device setup.
@return
@throws Exception | [
"@RequestMapping(value = \"/cert\", method = {RequestMethod.GET, RequestMethod.HEAD})\n public String certPage() throws Exception {\n return \"cert\";\n }"
] | [
"public List<WebSocketConnection> get(String key) {\n final List<WebSocketConnection> retList = new ArrayList<>();\n accept(key, C.F.addTo(retList));\n return retList;\n }",
"@Override\n protected StatisticsMatrix createMatrix(int numRows, int numCols, MatrixType type) {\n return new StatisticsMatrix(numRows,numCols);\n }",
"public static String stringify(ObjectMapper mapper, Object object) {\n try {\n return mapper.writeValueAsString(object);\n } catch (JsonProcessingException e) {\n throw new IllegalArgumentException(e);\n }\n }",
"public void addClass(ClassDescriptorDef classDef)\r\n {\r\n classDef.setOwner(this);\r\n // Regardless of the format of the class name, we're using the fully qualified format\r\n // This is safe because of the package & class naming constraints of the Java language\r\n _classDefs.put(classDef.getQualifiedName(), classDef);\r\n }",
"public List<ServerRedirect> tableServers(int profileId, int serverGroupId) {\n ArrayList<ServerRedirect> servers = new ArrayList<>();\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_SERVERS +\n \" WHERE \" + Constants.GENERIC_PROFILE_ID + \" = ?\" +\n \" AND \" + Constants.SERVER_REDIRECT_GROUP_ID + \" = ?\"\n );\n queryStatement.setInt(1, profileId);\n queryStatement.setInt(2, serverGroupId);\n results = queryStatement.executeQuery();\n while (results.next()) {\n ServerRedirect curServer = new ServerRedirect(results.getInt(Constants.GENERIC_ID),\n results.getString(Constants.SERVER_REDIRECT_REGION),\n results.getString(Constants.SERVER_REDIRECT_SRC_URL),\n results.getString(Constants.SERVER_REDIRECT_DEST_URL),\n results.getString(Constants.SERVER_REDIRECT_HOST_HEADER));\n curServer.setProfileId(profileId);\n servers.add(curServer);\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n return servers;\n }",
"public List<EnabledEndpoint> getEnabledEndpoints(int pathId, String clientUUID, String[] filters) throws Exception {\n ArrayList<EnabledEndpoint> enabledOverrides = new ArrayList<EnabledEndpoint>();\n PreparedStatement query = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n query = 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 query.setInt(1, pathId);\n query.setString(2, clientUUID);\n results = query.executeQuery();\n\n while (results.next()) {\n EnabledEndpoint endpoint = this.getPartialEnabledEndpointFromResultset(results);\n com.groupon.odo.proxylib.models.Method m = PathOverrideService.getInstance().getMethodForOverrideId(endpoint.getOverrideId());\n\n // this is an errant entry.. perhaps a method got deleted from a plugin\n // we'll also remove it from the endpoint\n if (m == null) {\n PathOverrideService.getInstance().removeOverride(endpoint.getOverrideId());\n continue;\n }\n\n // check filters and see if any match\n boolean addOverride = false;\n if (filters != null) {\n for (String filter : filters) {\n if (m.getMethodType().endsWith(filter)) {\n addOverride = true;\n break;\n }\n }\n } else {\n // if there are no filters then we assume that the requester wants all enabled overrides\n addOverride = true;\n }\n\n if (addOverride) {\n enabledOverrides.add(endpoint);\n }\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 (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n\n // now go through the ArrayList and get the method for all of the endpoints\n // have to do this so we don't have overlapping SQL queries\n ArrayList<EnabledEndpoint> enabledOverridesWithMethods = new ArrayList<EnabledEndpoint>();\n for (EnabledEndpoint endpoint : enabledOverrides) {\n if (endpoint.getOverrideId() >= 0) {\n com.groupon.odo.proxylib.models.Method m = PathOverrideService.getInstance().getMethodForOverrideId(endpoint.getOverrideId());\n endpoint.setMethodInformation(m);\n }\n enabledOverridesWithMethods.add(endpoint);\n }\n\n return enabledOverridesWithMethods;\n }",
"public static int positionOf(char value, char[] array) {\n for (int i = 0; i < array.length; i++) {\n if (value == array[i]) {\n return i;\n }\n }\n throw new OkapiException(\"Unable to find character '\" + value + \"' in character array.\");\n }",
"protected List<String> parseWords(String line) {\n List<String> words = new ArrayList<String>();\n boolean insideWord = !isSpace(line.charAt(0));\n int last = 0;\n for( int i = 0; i < line.length(); i++) {\n char c = line.charAt(i);\n\n if( insideWord ) {\n // see if its at the end of a word\n if( isSpace(c)) {\n words.add( line.substring(last,i) );\n insideWord = false;\n }\n } else {\n if( !isSpace(c)) {\n last = i;\n insideWord = true;\n }\n }\n }\n\n // if the line ended add the final word\n if( insideWord ) {\n words.add( line.substring(last));\n }\n return words;\n }",
"private ModelNode createJVMNode() throws OperationFailedException {\n ModelNode jvm = new ModelNode().setEmptyObject();\n jvm.get(NAME).set(getProperty(\"java.vm.name\"));\n jvm.get(JAVA_VERSION).set(getProperty(\"java.vm.specification.version\"));\n jvm.get(JVM_VERSION).set(getProperty(\"java.version\"));\n jvm.get(JVM_VENDOR).set(getProperty(\"java.vm.vendor\"));\n jvm.get(JVM_HOME).set(getProperty(\"java.home\"));\n return jvm;\n }"
] |
Clears the proxy. A cleared proxy is defined as loaded
@see Collection#clear() | [
"public void clear()\r\n {\r\n Class collClass = getCollectionClass();\r\n\r\n // ECER: assure we notify all objects being removed, \r\n // necessary for RemovalAwareCollections...\r\n if (IRemovalAwareCollection.class.isAssignableFrom(collClass))\r\n {\r\n getData().clear();\r\n }\r\n else\r\n {\r\n Collection coll;\r\n // BRJ: use an empty collection so isLoaded will return true\r\n // for non RemovalAwareCollections only !! \r\n try\r\n {\r\n coll = (Collection) collClass.newInstance();\r\n }\r\n catch (Exception e)\r\n {\r\n coll = new ArrayList();\r\n }\r\n\r\n setData(coll);\r\n }\r\n _size = 0;\r\n }"
] | [
"public static String addFolderSlashIfNeeded(String folderName) {\n if (!\"\".equals(folderName) && !folderName.endsWith(\"/\")) {\n return folderName + \"/\";\n } else {\n return folderName;\n }\n }",
"private static boolean typeEquals(ParameterizedType from,\n\t\t\tParameterizedType to, Map<String, Type> typeVarMap) {\n\t\tif (from.getRawType().equals(to.getRawType())) {\n\t\t\tType[] fromArgs = from.getActualTypeArguments();\n\t\t\tType[] toArgs = to.getActualTypeArguments();\n\t\t\tfor (int i = 0; i < fromArgs.length; i++) {\n\t\t\t\tif (!matches(fromArgs[i], toArgs[i], typeVarMap)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}",
"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}",
"public static void findSomeStringProperties(ApiConnection connection)\n\t\t\tthrows MediaWikiApiErrorException, IOException {\n\t\tWikibaseDataFetcher wbdf = new WikibaseDataFetcher(connection, siteIri);\n\t\twbdf.getFilter().excludeAllProperties();\n\t\twbdf.getFilter().setLanguageFilter(Collections.singleton(\"en\"));\n\n\t\tArrayList<PropertyIdValue> stringProperties = new ArrayList<>();\n\n\t\tSystem.out\n\t\t\t\t.println(\"*** Trying to find string properties for the example ... \");\n\t\tint propertyNumber = 1;\n\t\twhile (stringProperties.size() < 5) {\n\t\t\tArrayList<String> fetchProperties = new ArrayList<>();\n\t\t\tfor (int i = propertyNumber; i < propertyNumber + 10; i++) {\n\t\t\t\tfetchProperties.add(\"P\" + i);\n\t\t\t}\n\t\t\tpropertyNumber += 10;\n\t\t\tMap<String, EntityDocument> results = wbdf\n\t\t\t\t\t.getEntityDocuments(fetchProperties);\n\t\t\tfor (EntityDocument ed : results.values()) {\n\t\t\t\tPropertyDocument pd = (PropertyDocument) ed;\n\t\t\t\tif (DatatypeIdValue.DT_STRING.equals(pd.getDatatype().getIri())\n\t\t\t\t\t\t&& pd.getLabels().containsKey(\"en\")) {\n\t\t\t\t\tstringProperties.add(pd.getEntityId());\n\t\t\t\t\tSystem.out.println(\"* Found string property \"\n\t\t\t\t\t\t\t+ pd.getEntityId().getId() + \" (\"\n\t\t\t\t\t\t\t+ pd.getLabels().get(\"en\") + \")\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tstringProperty1 = stringProperties.get(0);\n\t\tstringProperty2 = stringProperties.get(1);\n\t\tstringProperty3 = stringProperties.get(2);\n\t\tstringProperty4 = stringProperties.get(3);\n\t\tstringProperty5 = stringProperties.get(4);\n\n\t\tSystem.out.println(\"*** Done.\");\n\t}",
"@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 }",
"@SuppressWarnings(\"unchecked\")\n public static <T> T convert(Object fromValue, Class<T> toType) throws TypeCastException {\n return convert(fromValue, toType, (String) null);\n }",
"private void loadLibraryFromStream(String libname, InputStream is) {\r\n try {\r\n File tempfile = createTempFile(libname);\r\n OutputStream os = new FileOutputStream(tempfile);\r\n\r\n logger.debug(\"tempfile.getPath() = \" + tempfile.getPath());\r\n\r\n long savedTime = System.currentTimeMillis();\r\n\r\n // Leo says 8k block size is STANDARD ;)\r\n byte buf[] = new byte[8192];\r\n int len;\r\n while ((len = is.read(buf)) > 0) {\r\n os.write(buf, 0, len);\r\n }\r\n\r\n os.flush();\r\n InputStream lock = new FileInputStream(tempfile);\r\n os.close();\r\n\r\n double seconds = (double) (System.currentTimeMillis() - savedTime) / 1e3;\r\n logger.debug(\"Copying took \" + seconds + \" seconds.\");\r\n\r\n logger.debug(\"Loading library from \" + tempfile.getPath() + \".\");\r\n System.load(tempfile.getPath());\r\n\r\n lock.close();\r\n } catch (IOException io) {\r\n logger.error(\"Could not create the temp file: \" + io.toString() + \".\\n\");\r\n } catch (UnsatisfiedLinkError ule) {\r\n logger.error(\"Couldn't load copied link file: \" + ule.toString() + \".\\n\");\r\n throw ule;\r\n }\r\n }",
"public static base_response restore(nitro_service client, appfwprofile resource) throws Exception {\n\t\tappfwprofile restoreresource = new appfwprofile();\n\t\trestoreresource.archivename = resource.archivename;\n\t\treturn restoreresource.perform_operation(client,\"restore\");\n\t}",
"public static int countNonZero(DMatrixRMaj A){\n int total = 0;\n for (int row = 0, index=0; row < A.numRows; row++) {\n for (int col = 0; col < A.numCols; col++,index++) {\n if( A.data[index] != 0 ) {\n total++;\n }\n }\n }\n return total;\n }"
] |
Wrap an existing setter. | [
"private void wrapSetterMethod(ClassNode classNode, boolean bindable, String propertyName) {\r\n String getterName = \"get\" + MetaClassHelper.capitalize(propertyName);\r\n MethodNode setter = classNode.getSetterMethod(\"set\" + MetaClassHelper.capitalize(propertyName));\r\n\r\n if (setter != null) {\r\n // Get the existing code block\r\n Statement code = setter.getCode();\r\n\r\n Expression oldValue = varX(\"$oldValue\");\r\n Expression newValue = varX(\"$newValue\");\r\n Expression proposedValue = varX(setter.getParameters()[0].getName());\r\n BlockStatement block = new BlockStatement();\r\n\r\n // create a local variable to hold the old value from the getter\r\n block.addStatement(declS(oldValue, callThisX(getterName)));\r\n\r\n // add the fireVetoableChange method call\r\n block.addStatement(stmt(callThisX(\"fireVetoableChange\", args(\r\n constX(propertyName), oldValue, proposedValue))));\r\n\r\n // call the existing block, which will presumably set the value properly\r\n block.addStatement(code);\r\n\r\n if (bindable) {\r\n // get the new value to emit in the event\r\n block.addStatement(declS(newValue, callThisX(getterName)));\r\n\r\n // add the firePropertyChange method call\r\n block.addStatement(stmt(callThisX(\"firePropertyChange\", args(constX(propertyName), oldValue, newValue))));\r\n }\r\n\r\n // replace the existing code block with our new one\r\n setter.setCode(block);\r\n }\r\n }"
] | [
"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 boolean isActive(int profileId) {\n boolean active = false;\n PreparedStatement queryStatement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT \" + Constants.CLIENT_IS_ACTIVE + \" FROM \" + Constants.DB_TABLE_CLIENT +\n \" WHERE \" + Constants.GENERIC_CLIENT_UUID + \"= '-1' \" +\n \" AND \" + Constants.GENERIC_PROFILE_ID + \"= ? \"\n );\n queryStatement.setInt(1, profileId);\n logger.info(queryStatement.toString());\n ResultSet results = queryStatement.executeQuery();\n if (results.next()) {\n active = results.getBoolean(Constants.CLIENT_IS_ACTIVE);\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return active;\n }",
"public Swagger read(Set<Class<?>> classes) {\n Set<Class<?>> sortedClasses = new TreeSet<>((class1, class2) -> {\n if (class1.equals(class2)) {\n return 0;\n } else if (class1.isAssignableFrom(class2)) {\n return -1;\n } else if (class2.isAssignableFrom(class1)) {\n return 1;\n }\n return class1.getName().compareTo(class2.getName());\n });\n sortedClasses.addAll(classes);\n\n Map<Class<?>, ReaderListener> listeners = new HashMap<Class<?>, ReaderListener>();\n\n for (Class<?> cls : sortedClasses) {\n if (ReaderListener.class.isAssignableFrom(cls) && !listeners.containsKey(cls)) {\n try {\n listeners.put(cls, (ReaderListener) cls.newInstance());\n } catch (Exception e) {\n LOGGER.error(\"Failed to create ReaderListener\", e);\n }\n }\n }\n\n// for (ReaderListener listener : listeners.values()) {\n// try {\n// listener.beforeScan(this, swagger);\n// } catch (Exception e) {\n// LOGGER.error(\"Unexpected error invoking beforeScan listener [\" + listener.getClass().getName() + \"]\", e);\n// }\n// }\n\n // process SwaggerDefinitions first - so we get tags in desired order\n for (Class<?> cls : sortedClasses) {\n SwaggerDefinition swaggerDefinition = cls.getAnnotation(SwaggerDefinition.class);\n if (swaggerDefinition != null) {\n readSwaggerConfig(cls, swaggerDefinition);\n }\n }\n\n for (Class<?> cls : sortedClasses) {\n read(cls, \"\", null, false, new String[0], new String[0], new LinkedHashMap<>(), new ArrayList<>(), new HashSet<>());\n }\n\n// for (ReaderListener listener : listeners.values()) {\n// try {\n// listener.afterScan(this, swagger);\n// } catch (Exception e) {\n// LOGGER.error(\"Unexpected error invoking afterScan listener [\" + listener.getClass().getName() + \"]\", e);\n// }\n// }\n\n return swagger;\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}",
"public static base_response unset(nitro_service client, aaaparameter resource, String[] args) throws Exception{\n\t\taaaparameter unsetresource = new aaaparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public void ifHasProperty(String template, Properties attributes) throws XDocletException\r\n {\r\n String value = getPropertyValue(attributes.getProperty(ATTRIBUTE_LEVEL), attributes.getProperty(ATTRIBUTE_NAME));\r\n\r\n if (value != null)\r\n {\r\n generate(template);\r\n }\r\n }",
"private void updateWaveform(WaveformPreview preview) {\n this.preview.set(preview);\n if (preview == null) {\n waveformImage.set(null);\n } else {\n BufferedImage image = new BufferedImage(preview.segmentCount, preview.maxHeight, BufferedImage.TYPE_INT_RGB);\n Graphics g = image.getGraphics();\n g.setColor(Color.BLACK);\n g.fillRect(0, 0, preview.segmentCount, preview.maxHeight);\n for (int segment = 0; segment < preview.segmentCount; segment++) {\n g.setColor(preview.segmentColor(segment, false));\n g.drawLine(segment, preview.maxHeight, segment, preview.maxHeight - preview.segmentHeight(segment, false));\n if (preview.isColor) { // We have a front color segment to draw on top.\n g.setColor(preview.segmentColor(segment, true));\n g.drawLine(segment, preview.maxHeight, segment, preview.maxHeight - preview.segmentHeight(segment, true));\n }\n }\n waveformImage.set(image);\n }\n }",
"public void writeNameValuePair(String name, long value) throws IOException\n {\n internalWriteNameValuePair(name, Long.toString(value));\n }",
"@SuppressWarnings(\"unchecked\")\n public B setTargetType(Class<?> type) {\n Objects.requireNonNull(type);\n set(AbstractQuery.KEY_QUERY_TARGET_TYPE, type);\n return (B) this;\n }"
] |
Creates the publish button.
@param updateListener the update listener
@return the publish button | [
"public static Button createPublishButton(final I_CmsUpdateListener<String> updateListener) {\n\n Button publishButton = CmsToolBar.createButton(\n FontOpenCms.PUBLISH,\n CmsVaadinUtils.getMessageText(Messages.GUI_PUBLISH_BUTTON_TITLE_0));\n if (CmsAppWorkplaceUi.isOnlineProject()) {\n // disable publishing in online project\n publishButton.setEnabled(false);\n publishButton.setDescription(CmsVaadinUtils.getMessageText(Messages.GUI_TOOLBAR_NOT_AVAILABLE_ONLINE_0));\n }\n publishButton.addClickListener(new ClickListener() {\n\n /** Serial version id. */\n private static final long serialVersionUID = 1L;\n\n public void buttonClick(ClickEvent event) {\n\n CmsAppWorkplaceUi.get().disableGlobalShortcuts();\n CmsGwtDialogExtension extension = new CmsGwtDialogExtension(A_CmsUI.get(), updateListener);\n extension.openPublishDialog();\n }\n });\n return publishButton;\n }"
] | [
"public static String addFolderSlashIfNeeded(String folderName) {\n if (!\"\".equals(folderName) && !folderName.endsWith(\"/\")) {\n return folderName + \"/\";\n } else {\n return folderName;\n }\n }",
"public static base_response create(nitro_service client, ssldhparam resource) throws Exception {\n\t\tssldhparam createresource = new ssldhparam();\n\t\tcreateresource.dhfile = resource.dhfile;\n\t\tcreateresource.bits = resource.bits;\n\t\tcreateresource.gen = resource.gen;\n\t\treturn createresource.perform_operation(client,\"create\");\n\t}",
"public void add(final String source, final T destination) {\n\n // replace multiple slashes with a single slash.\n String path = source.replaceAll(\"/+\", \"/\");\n\n path = (path.endsWith(\"/\") && path.length() > 1)\n ? path.substring(0, path.length() - 1) : path;\n\n\n String[] parts = path.split(\"/\", maxPathParts + 2);\n if (parts.length - 1 > maxPathParts) {\n throw new IllegalArgumentException(String.format(\"Number of parts of path %s exceeds allowed limit %s\",\n source, maxPathParts));\n }\n StringBuilder sb = new StringBuilder();\n List<String> groupNames = new ArrayList<>();\n\n for (String part : parts) {\n Matcher groupMatcher = GROUP_PATTERN.matcher(part);\n if (groupMatcher.matches()) {\n groupNames.add(groupMatcher.group(1));\n sb.append(\"([^/]+?)\");\n } else if (WILD_CARD_PATTERN.matcher(part).matches()) {\n sb.append(\".*?\");\n } else {\n sb.append(part);\n }\n sb.append(\"/\");\n }\n\n //Ignore the last \"/\"\n sb.setLength(sb.length() - 1);\n\n Pattern pattern = Pattern.compile(sb.toString());\n patternRouteList.add(ImmutablePair.of(pattern, new RouteDestinationWithGroups(destination, groupNames)));\n }",
"private static CustomInfoType convertCustomInfo(Map<String, String> customInfo) {\n if (customInfo == null) {\n return null;\n }\n\n CustomInfoType ciType = new CustomInfoType();\n for (Entry<String, String> entry : customInfo.entrySet()) {\n CustomInfoType.Item cItem = new CustomInfoType.Item();\n cItem.setKey(entry.getKey());\n cItem.setValue(entry.getValue());\n ciType.getItem().add(cItem);\n }\n\n return ciType;\n }",
"public static Boolean parseBoolean(String value) throws ParseException\n {\n Boolean result = null;\n Integer number = parseInteger(value);\n if (number != null)\n {\n result = number.intValue() == 0 ? Boolean.FALSE : Boolean.TRUE;\n }\n\n return result;\n }",
"private static <T> Set<Type> getSessionBeanTypes(EnhancedAnnotated<T, ?> annotated, EjbDescriptor<T> ejbDescriptor) {\n ImmutableSet.Builder<Type> types = ImmutableSet.builder();\n // session beans\n Map<Class<?>, Type> typeMap = new LinkedHashMap<Class<?>, Type>();\n HierarchyDiscovery beanClassDiscovery = HierarchyDiscovery.forNormalizedType(ejbDescriptor.getBeanClass());\n for (BusinessInterfaceDescriptor<?> businessInterfaceDescriptor : ejbDescriptor.getLocalBusinessInterfaces()) {\n // first we need to resolve the local interface\n Type resolvedLocalInterface = beanClassDiscovery.resolveType(Types.getCanonicalType(businessInterfaceDescriptor.getInterface()));\n SessionBeanHierarchyDiscovery interfaceDiscovery = new SessionBeanHierarchyDiscovery(resolvedLocalInterface);\n if (beanClassDiscovery.getTypeMap().containsKey(businessInterfaceDescriptor.getInterface())) {\n // WELD-1675 Only add types also included in Annotated.getTypeClosure()\n for (Entry<Class<?>, Type> entry : interfaceDiscovery.getTypeMap().entrySet()) {\n if (annotated.getTypeClosure().contains(entry.getValue())) {\n typeMap.put(entry.getKey(), entry.getValue());\n }\n }\n } else {\n // Session bean class does not implement the business interface and @javax.ejb.Local applied to the session bean class\n typeMap.putAll(interfaceDiscovery.getTypeMap());\n }\n }\n if (annotated.isAnnotationPresent(Typed.class)) {\n types.addAll(Beans.getTypedTypes(typeMap, annotated.getJavaClass(), annotated.getAnnotation(Typed.class)));\n } else {\n typeMap.put(Object.class, Object.class);\n types.addAll(typeMap.values());\n }\n return Beans.getLegalBeanTypes(types.build(), annotated);\n }",
"public static String getContext(final PObject[] objs) {\n StringBuilder result = new StringBuilder(\"(\");\n boolean first = true;\n for (PObject obj: objs) {\n if (!first) {\n result.append('|');\n }\n first = false;\n result.append(obj.getCurrentPath());\n }\n result.append(')');\n return result.toString();\n }",
"public static CoordinateReferenceSystem parseProjection(\n final String projection, final Boolean longitudeFirst) {\n try {\n if (longitudeFirst == null) {\n return CRS.decode(projection);\n } else {\n return CRS.decode(projection, longitudeFirst);\n }\n } catch (NoSuchAuthorityCodeException e) {\n throw new RuntimeException(projection + \" was not recognized as a crs code\", e);\n } catch (FactoryException e) {\n throw new RuntimeException(\"Error occurred while parsing: \" + projection, e);\n }\n }",
"public static wisite_farmname_binding[] get(nitro_service service, String sitepath) throws Exception{\n\t\twisite_farmname_binding obj = new wisite_farmname_binding();\n\t\tobj.set_sitepath(sitepath);\n\t\twisite_farmname_binding response[] = (wisite_farmname_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Convert this buffer to a java array.
@return | [
"public byte[] toArray() {\n if (size() > Integer.MAX_VALUE)\n throw new IllegalStateException(\"Cannot create byte array of more than 2GB\");\n\n int len = (int) size();\n ByteBuffer bb = toDirectByteBuffer(0L, len);\n byte[] b = new byte[len];\n // Copy data to the array\n bb.get(b, 0, len);\n return b;\n }"
] | [
"public static ModelControllerClient createAndAdd(final ManagementChannelHandler handler) {\n final ExistingChannelModelControllerClient client = new ExistingChannelModelControllerClient(handler);\n handler.addHandlerFactory(client);\n return client;\n }",
"public Weld addBeanDefiningAnnotations(Class<? extends Annotation>... annotations) {\n for (Class<? extends Annotation> annotation : annotations) {\n this.extendedBeanDefiningAnnotations.add(annotation);\n }\n return this;\n }",
"public static vpath get(nitro_service service, String name) throws Exception{\n\t\tvpath obj = new vpath();\n\t\tobj.set_name(name);\n\t\tvpath response = (vpath) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static void openLogFile(String logPath) {\n\t\tif (logPath == null) {\n\t\t\tprintStream = System.out;\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tprintStream = new PrintStream(new File(logPath));\n\t\t\t} catch (FileNotFoundException e) {\n\t\t\t\tthrow new IllegalArgumentException(\"Log file \" + logPath + \" was not found\", e);\n\t\t\t}\n\t\t}\n\t}",
"public String[] getReportSamples() {\n final Map<String, String> sampleValues = new HashMap<>();\n sampleValues.put(\"name1\", \"Secure Transpiler Mars\");\n sampleValues.put(\"version1\", \"4.7.0\");\n sampleValues.put(\"name2\", \"Secure Transpiler Bounty\");\n sampleValues.put(\"version2\", \"5.0.0\");\n sampleValues.put(\"license\", \"CDDL-1.1\");\n sampleValues.put(\"name\", \"Secure Pretender\");\n sampleValues.put(\"version\", \"2.7.0\");\n sampleValues.put(\"organization\", \"Axway\");\n\n return ReportsRegistry.allReports()\n .stream()\n .map(report -> ReportUtils.generateSampleRequest(report, sampleValues))\n .map(request -> {\n try {\n String desc = \"\";\n final Optional<Report> byId = ReportsRegistry.findById(request.getReportId());\n\n if(byId.isPresent()) {\n desc = byId.get().getDescription() + \"<br/><br/>\";\n }\n\n return String.format(TWO_PLACES, desc, JsonUtils.serialize(request));\n } catch(IOException e) {\n return \"Error \" + e.getMessage();\n }\n })\n .collect(Collectors.toList())\n .toArray(new String[] {});\n }",
"private boolean setNextIterator()\r\n {\r\n boolean retval = false;\r\n // first, check if the activeIterator is null, and set it.\r\n if (m_activeIterator == null)\r\n {\r\n if (m_rsIterators.size() > 0)\r\n {\r\n m_activeIteratorIndex = 0;\r\n m_currentCursorPosition = 0;\r\n m_activeIterator = (OJBIterator) m_rsIterators.get(m_activeIteratorIndex);\r\n }\r\n }\r\n else if (!m_activeIterator.hasNext())\r\n {\r\n if (m_rsIterators.size() > (m_activeIteratorIndex + 1))\r\n {\r\n // we still have iterators in the collection, move to the\r\n // next one, increment the counter, and set the active\r\n // iterator.\r\n m_activeIteratorIndex++;\r\n m_currentCursorPosition = 0;\r\n m_activeIterator = (OJBIterator) m_rsIterators.get(m_activeIteratorIndex);\r\n retval = true;\r\n }\r\n }\r\n\r\n return retval;\r\n }",
"public RedwoodConfiguration neatExit(){\r\n tasks.add(new Runnable() { public void run() {\r\n Runtime.getRuntime().addShutdownHook(new Thread(){\r\n @Override public void run(){ Redwood.stop(); }\r\n });\r\n }});\r\n return this;\r\n }",
"protected void generateMopCalls(LinkedList<MethodNode> mopCalls, boolean useThis) {\n for (MethodNode method : mopCalls) {\n String name = getMopMethodName(method, useThis);\n Parameter[] parameters = method.getParameters();\n String methodDescriptor = BytecodeHelper.getMethodDescriptor(method.getReturnType(), method.getParameters());\n MethodVisitor mv = controller.getClassVisitor().visitMethod(ACC_PUBLIC | ACC_SYNTHETIC, name, methodDescriptor, null, null);\n controller.setMethodVisitor(mv);\n mv.visitVarInsn(ALOAD, 0);\n int newRegister = 1;\n OperandStack operandStack = controller.getOperandStack();\n for (Parameter parameter : parameters) {\n ClassNode type = parameter.getType();\n operandStack.load(parameter.getType(), newRegister);\n // increment to next register, double/long are using two places\n newRegister++;\n if (type == ClassHelper.double_TYPE || type == ClassHelper.long_TYPE) newRegister++;\n }\n operandStack.remove(parameters.length);\n ClassNode declaringClass = method.getDeclaringClass();\n // JDK 8 support for default methods in interfaces\n // this should probably be strenghtened when we support the A.super.foo() syntax\n int opcode = declaringClass.isInterface()?INVOKEINTERFACE:INVOKESPECIAL;\n mv.visitMethodInsn(opcode, BytecodeHelper.getClassInternalName(declaringClass), method.getName(), methodDescriptor, opcode == INVOKEINTERFACE);\n BytecodeHelper.doReturn(mv, method.getReturnType());\n mv.visitMaxs(0, 0);\n mv.visitEnd();\n controller.getClassNode().addMethod(name, ACC_PUBLIC | ACC_SYNTHETIC, method.getReturnType(), parameters, null, null);\n }\n }",
"protected static void sendInitSQL(Connection connection, String initSQL) throws SQLException{\r\n\t\t// fetch any configured setup sql.\r\n\t\tif (initSQL != null){\r\n\t\t\tStatement stmt = null;\r\n\t\t\ttry{\r\n\t\t\t\tstmt = connection.createStatement();\r\n\t\t\t\tstmt.execute(initSQL);\r\n\t\t\t\tif (testSupport){ // only to aid code coverage, normally set to false\r\n\t\t\t\t\tstmt = null;\r\n\t\t\t\t}\r\n\t\t\t} finally{\r\n\t\t\t\tif (stmt != null){\r\n\t\t\t\t\tstmt.close();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}"
] |
Add a newline to this sequence according to the configured lineDelimiter if the last line contains
something besides whitespace. | [
"public void newLineIfNotEmpty() {\n\t\tfor (int i = segments.size() - 1; i >= 0; i--) {\n\t\t\tString segment = segments.get(i);\n\t\t\tif (lineDelimiter.equals(segment)) {\n\t\t\t\tsegments.subList(i + 1, segments.size()).clear();\n\t\t\t\tcachedToString = null;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfor (int j = 0; j < segment.length(); j++) {\n\t\t\t\tif (!WhitespaceMatcher.isWhitespace(segment.charAt(j))) {\n\t\t\t\t\tnewLine();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tsegments.clear();\n\t\tcachedToString = null;\n\t}"
] | [
"protected TemporaryBrokerWrapper getBroker() throws PBFactoryException\r\n {\r\n PersistenceBrokerInternal broker;\r\n boolean needsClose = false;\r\n\r\n if (getBrokerKey() == null)\r\n {\r\n /*\r\n arminw:\r\n if no PBKey is set we throw an exception, because we don't\r\n know which PB (connection) should be used.\r\n */\r\n throw new OJBRuntimeException(\"Can't find associated PBKey. Need PBKey to obtain a valid\" +\r\n \"PersistenceBroker instance from intern resources.\");\r\n }\r\n // first try to use the current threaded broker to avoid blocking\r\n broker = PersistenceBrokerThreadMapping.currentPersistenceBroker(getBrokerKey());\r\n // current broker not found, create a intern new one\r\n if ((broker == null) || broker.isClosed())\r\n {\r\n broker = (PersistenceBrokerInternal) PersistenceBrokerFactory.createPersistenceBroker(getBrokerKey());\r\n /** Specifies whether we obtained a fresh broker which we have to close after we used it */\r\n needsClose = true;\r\n }\r\n return new TemporaryBrokerWrapper(broker, needsClose);\r\n }",
"@VisibleForTesting\n protected static int getBarSize(final ScaleBarRenderSettings settings) {\n if (settings.getParams().barSize != null) {\n return settings.getParams().barSize;\n } else {\n if (settings.getParams().getOrientation().isHorizontal()) {\n return settings.getMaxSize().height / 4;\n } else {\n return settings.getMaxSize().width / 4;\n }\n }\n }",
"public static String normalizeWS(String value) {\n char[] tmp = new char[value.length()];\n int pos = 0;\n boolean prevws = false;\n for (int ix = 0; ix < tmp.length; ix++) {\n char ch = value.charAt(ix);\n if (ch != ' ' && ch != '\\t' && ch != '\\n' && ch != '\\r') {\n if (prevws && pos != 0)\n tmp[pos++] = ' ';\n\n tmp[pos++] = ch;\n prevws = false;\n } else\n prevws = true;\n }\n return new String(tmp, 0, pos);\n }",
"private Iterable<Key> getSplitKey(List<Key> keys, int numSplits) {\n // If the number of keys is less than the number of splits, we are limited in the number of\n // splits we can make.\n if (keys.size() < numSplits - 1) {\n return keys;\n }\n\n // Calculate the number of keys per split. This should be KEYS_PER_SPLIT, but may\n // be less if there are not KEYS_PER_SPLIT * (numSplits - 1) scatter entities.\n //\n // Consider the following dataset, where - represents an entity and * represents an entity\n // that is returned as a scatter entity:\n // ||---*-----*----*-----*-----*------*----*----||\n // If we want 4 splits in this data, the optimal split would look like:\n // ||---*-----*----*-----*-----*------*----*----||\n // | | |\n // The scatter keys in the last region are not useful to us, so we never request them:\n // ||---*-----*----*-----*-----*------*---------||\n // | | |\n // With 6 scatter keys we want to set scatter points at indexes: 1, 3, 5.\n //\n // We keep this as a double so that any \"fractional\" keys per split get distributed throughout\n // the splits and don't make the last split significantly larger than the rest.\n double numKeysPerSplit = Math.max(1.0, ((double) keys.size()) / (numSplits - 1));\n\n List<Key> keysList = new ArrayList<Key>(numSplits - 1);\n // Grab the last sample for each split, otherwise the first split will be too small.\n for (int i = 1; i < numSplits; i++) {\n int splitIndex = (int) Math.round(i * numKeysPerSplit) - 1;\n keysList.add(keys.get(splitIndex));\n }\n\n return keysList;\n }",
"public static <T> Iterator<T> unique(Iterator<T> self) {\n return toList((Iterable<T>) unique(toList(self))).listIterator();\n }",
"@Deprecated\n public FluoConfiguration clearObservers() {\n Iterator<String> iter1 = getKeys(OBSERVER_PREFIX.substring(0, OBSERVER_PREFIX.length() - 1));\n while (iter1.hasNext()) {\n String key = iter1.next();\n clearProperty(key);\n }\n\n return this;\n }",
"public StitchObjectMapper withCodecRegistry(final CodecRegistry codecRegistry) {\n // We can't detect if their codecRegistry has any duplicate providers. There's also a chance\n // that putting ours first may prevent decoding of some of their classes if for example they\n // have their own way of decoding an Integer.\n final CodecRegistry newReg =\n CodecRegistries.fromRegistries(BsonUtils.DEFAULT_CODEC_REGISTRY, codecRegistry);\n return new StitchObjectMapper(this, newReg);\n }",
"public ModelNode buildExecutableRequest(CommandContext ctx) throws Exception {\n try {\n for (FailureDescProvider h : providers) {\n effectiveProviders.add(h);\n }\n // In case some key-store needs to be persisted\n for (String ks : ksToStore) {\n composite.get(Util.STEPS).add(ElytronUtil.storeKeyStore(ctx, ks));\n effectiveProviders.add(new FailureDescProvider() {\n @Override\n public String stepFailedDescription() {\n return \"Storing the key-store \" + ksToStore;\n }\n });\n }\n // Final steps\n for (int i = 0; i < finalSteps.size(); i++) {\n composite.get(Util.STEPS).add(finalSteps.get(i));\n effectiveProviders.add(finalProviders.get(i));\n }\n return composite;\n } catch (Exception ex) {\n try {\n failureOccured(ctx, null);\n } catch (Exception ex2) {\n ex.addSuppressed(ex2);\n }\n throw ex;\n }\n }",
"public RangeInfo subListBorders(int size) {\n if (inclusive == null) throw new IllegalStateException(\"Should not call subListBorders on a non-inclusive aware IntRange\");\n int tempFrom = from;\n if (tempFrom < 0) {\n tempFrom += size;\n }\n int tempTo = to;\n if (tempTo < 0) {\n tempTo += size;\n }\n if (tempFrom > tempTo) {\n return new RangeInfo(inclusive ? tempTo : tempTo + 1, tempFrom + 1, true);\n }\n return new RangeInfo(tempFrom, inclusive ? tempTo + 1 : tempTo, false);\n }"
] |
Select the specific vertex and fragment shader to use with this material.
The shader template is used to generate the sources for the vertex and
fragment shader based on the material properties only.
It will ignore the mesh attributes and all lights.
@param context
GVRContext
@param material
material to use with the shader
@return ID of vertex/fragment shader set | [
"public int bindShader(GVRContext context, GVRShaderData material, String vertexDesc)\n {\n String signature = getClass().getSimpleName();\n GVRShaderManager shaderManager = context.getShaderManager();\n\n synchronized (shaderManager)\n {\n int nativeShader = shaderManager.getShader(signature);\n if (nativeShader == 0)\n {\n nativeShader = addShader(shaderManager, signature, material);\n }\n return nativeShader;\n }\n }"
] | [
"public CollectionRequest<Team> findByOrganization(String organization) {\n \n String path = String.format(\"/organizations/%s/teams\", organization);\n return new CollectionRequest<Team>(this, Team.class, path, \"GET\");\n }",
"private <Y> void checkObserverMethod(EnhancedAnnotatedMethod<T, Y> annotated) {\n // Make sure exactly one and only one parameter is annotated with Observes or ObservesAsync\n List<EnhancedAnnotatedParameter<?, Y>> eventObjects = annotated.getEnhancedParameters(Observes.class);\n eventObjects.addAll(annotated.getEnhancedParameters(ObservesAsync.class));\n if (this.reception.equals(Reception.IF_EXISTS) && declaringBean.getScope().equals(Dependent.class)) {\n throw EventLogger.LOG.invalidScopedConditionalObserver(this, Formats.formatAsStackTraceElement(annotated.getJavaMember()));\n }\n if (eventObjects.size() > 1) {\n throw EventLogger.LOG.multipleEventParameters(this, Formats.formatAsStackTraceElement(annotated.getJavaMember()));\n }\n EnhancedAnnotatedParameter<?, Y> eventParameter = eventObjects.iterator().next();\n checkRequiredTypeAnnotations(eventParameter);\n // Check for parameters annotated with @Disposes\n List<?> disposeParams = annotated.getEnhancedParameters(Disposes.class);\n if (disposeParams.size() > 0) {\n throw EventLogger.LOG.invalidDisposesParameter(this, Formats.formatAsStackTraceElement(annotated.getJavaMember()));\n }\n // Check annotations on the method to make sure this is not a producer\n // method, initializer method, or destructor method.\n if (this.observerMethod.getAnnotated().isAnnotationPresent(Produces.class)) {\n throw EventLogger.LOG.invalidProducer(this, Formats.formatAsStackTraceElement(annotated.getJavaMember()));\n }\n if (this.observerMethod.getAnnotated().isAnnotationPresent(Inject.class)) {\n throw EventLogger.LOG.invalidInitializer(this, Formats.formatAsStackTraceElement(annotated.getJavaMember()));\n }\n boolean containerLifecycleObserverMethod = Observers.isContainerLifecycleObserverMethod(this);\n for (EnhancedAnnotatedParameter<?, ?> parameter : annotated.getEnhancedParameters()) {\n // if this is an observer method for container lifecycle event, it must not inject anything besides BeanManager\n if (containerLifecycleObserverMethod && !parameter.isAnnotationPresent(Observes.class) && !parameter.isAnnotationPresent(ObservesAsync.class) && !BeanManager.class.equals(parameter.getBaseType())) {\n throw EventLogger.LOG.invalidInjectionPoint(this, Formats.formatAsStackTraceElement(annotated.getJavaMember()));\n }\n }\n\n }",
"public View getFullScreenView() {\n if (mFullScreenView != null) {\n return mFullScreenView;\n }\n\n final DisplayMetrics metrics = new DisplayMetrics();\n mActivity.getWindowManager().getDefaultDisplay().getMetrics(metrics);\n final int screenWidthPixels = Math.max(metrics.widthPixels, metrics.heightPixels);\n final int screenHeightPixels = Math.min(metrics.widthPixels, metrics.heightPixels);\n\n final ViewGroup.LayoutParams layout = new ViewGroup.LayoutParams(screenWidthPixels, screenHeightPixels);\n mFullScreenView = new View(mActivity);\n mFullScreenView.setLayoutParams(layout);\n mRenderableViewGroup.addView(mFullScreenView);\n\n return mFullScreenView;\n }",
"public static QRDecomposition<DoubleMatrix> qr(DoubleMatrix A) {\n int minmn = min(A.rows, A.columns);\n DoubleMatrix result = A.dup();\n DoubleMatrix tau = new DoubleMatrix(minmn);\n SimpleBlas.geqrf(result, tau);\n DoubleMatrix R = new DoubleMatrix(A.rows, A.columns);\n for (int i = 0; i < A.rows; i++) {\n for (int j = i; j < A.columns; j++) {\n R.put(i, j, result.get(i, j));\n }\n }\n DoubleMatrix Q = DoubleMatrix.eye(A.rows);\n SimpleBlas.ormqr('L', 'N', result, tau, Q);\n return new QRDecomposition<DoubleMatrix>(Q, R);\n }",
"public NodeList getAt(String name) {\n NodeList answer = new NodeList();\n for (Object child : this) {\n if (child instanceof Node) {\n Node childNode = (Node) child;\n Object temp = childNode.get(name);\n if (temp instanceof Collection) {\n answer.addAll((Collection) temp);\n } else {\n answer.add(temp);\n }\n }\n }\n return answer;\n }",
"private I_CmsSearchResultWrapper getSearchResults() {\n\n // The second parameter is just ignored - so it does not matter\n m_searchController.updateFromRequestParameters(pageContext.getRequest().getParameterMap(), false);\n I_CmsSearchControllerCommon common = m_searchController.getCommon();\n // Do not search for empty query, if configured\n if (common.getState().getQuery().isEmpty()\n && (!common.getConfig().getIgnoreQueryParam() && !common.getConfig().getSearchForEmptyQueryParam())) {\n return new CmsSearchResultWrapper(m_searchController, null, null, m_cms, null);\n }\n Map<String, String[]> queryParams = null;\n boolean isEditMode = CmsJspTagEditable.isEditableRequest(pageContext.getRequest());\n if (isEditMode) {\n String params = \"\";\n if (common.getConfig().getIgnoreReleaseDate()) {\n params += \"&fq=released:[* TO *]\";\n }\n if (common.getConfig().getIgnoreExpirationDate()) {\n params += \"&fq=expired:[* TO *]\";\n }\n if (!params.isEmpty()) {\n queryParams = CmsRequestUtil.createParameterMap(params.substring(1));\n }\n }\n CmsSolrQuery query = new CmsSolrQuery(null, queryParams);\n m_searchController.addQueryParts(query, m_cms);\n try {\n // use \"complicated\" constructor to allow more than 50 results -> set ignoreMaxResults to true\n // also set resource filter to allow for returning unreleased/expired resources if necessary.\n CmsSolrResultList solrResultList = m_index.search(\n m_cms,\n query.clone(), // use a clone of the query, since the search function manipulates the query (removes highlighting parts), but we want to keep the original one.\n true,\n isEditMode ? CmsResourceFilter.IGNORE_EXPIRATION : null);\n return new CmsSearchResultWrapper(m_searchController, solrResultList, query, m_cms, null);\n } catch (CmsSearchException e) {\n LOG.warn(Messages.get().getBundle().key(Messages.LOG_TAG_SEARCH_SEARCH_FAILED_0), e);\n return new CmsSearchResultWrapper(m_searchController, null, query, m_cms, e);\n }\n }",
"public void start() {\n if (TransitionConfig.isDebug()) {\n getTransitionStateHolder().start();\n }\n\n mLastProgress = Float.MIN_VALUE;\n\n TransitionController transitionController;\n for (int i = 0, size = mTransitionControls.size(); i < size; i++) {\n transitionController = mTransitionControls.get(i);\n if (mInterpolator != null) {\n transitionController.setInterpolator(mInterpolator);\n }\n //required for ViewPager transitions to work\n if (mTarget != null) {\n transitionController.setTarget(mTarget);\n }\n transitionController.setUpdateStateAfterUpdateProgress(mUpdateStateAfterUpdateProgress);\n transitionController.start();\n }\n }",
"public <T> T getNodeMetaData(Object key) {\n if (metaDataMap == null) {\n return (T) null;\n }\n return (T) metaDataMap.get(key);\n }",
"public static final Rect getViewportBounds() {\n return new Rect(Window.getScrollLeft(), Window.getScrollTop(), Window.getClientWidth(), Window.getClientHeight());\n }"
] |
misc utility methods | [
"private float max(float x, float y, float z) {\n if (x > y) {\n // not y\n if (x > z) {\n return x;\n }\n else {\n return z;\n }\n }\n else {\n // not x\n if (y > z) {\n return y;\n }\n else {\n return z;\n }\n }\n }"
] | [
"private static int[] getErrorCorrection(int[] codewords, int ecclen) {\r\n\r\n ReedSolomon rs = new ReedSolomon();\r\n rs.init_gf(0x43);\r\n rs.init_code(ecclen, 1);\r\n rs.encode(codewords.length, codewords);\r\n\r\n int[] results = new int[ecclen];\r\n for (int i = 0; i < ecclen; i++) {\r\n results[i] = rs.getResult(results.length - 1 - i);\r\n }\r\n\r\n return results;\r\n }",
"public static dnspolicylabel[] get(nitro_service service) throws Exception{\n\t\tdnspolicylabel obj = new dnspolicylabel();\n\t\tdnspolicylabel[] response = (dnspolicylabel[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void removeSource(GVRAudioSource audioSource)\n {\n synchronized (mAudioSources)\n {\n audioSource.setListener(null);\n mAudioSources.remove(audioSource);\n }\n }",
"static <T> List<Template> getTemplates(T objectType) {\n try {\n List<Template> templates = new ArrayList<>();\n TEMP_FINDER.findAnnotations(templates, objectType);\n return templates;\n } catch (Exception e) {\n throw new IllegalStateException(e);\n }\n }",
"protected ClassDescriptor selectClassDescriptor(Map row) throws PersistenceBrokerException\r\n {\r\n ClassDescriptor result = m_cld;\r\n Class ojbConcreteClass = (Class) row.get(OJB_CONCRETE_CLASS_KEY);\r\n if(ojbConcreteClass != null)\r\n {\r\n result = m_cld.getRepository().getDescriptorFor(ojbConcreteClass);\r\n // if we can't find class-descriptor for concrete class, something wrong with mapping\r\n if (result == null)\r\n {\r\n throw new PersistenceBrokerException(\"Can't find class-descriptor for ojbConcreteClass '\"\r\n + ojbConcreteClass + \"', the main class was \" + m_cld.getClassNameOfObject());\r\n }\r\n }\r\n return result;\r\n }",
"public void setAssociation(String collectionRole, Association association) {\n\t\tif ( associations == null ) {\n\t\t\tassociations = new HashMap<>();\n\t\t}\n\t\tassociations.put( collectionRole, association );\n\t}",
"public List<TimephasedCost> getTimephasedActualCost()\n {\n if (m_timephasedActualCost == null)\n {\n Resource r = getResource();\n ResourceType type = r != null ? r.getType() : ResourceType.WORK;\n\n //for Work and Material resources, we will calculate in the normal way\n if (type != ResourceType.COST)\n {\n if (m_timephasedActualWork != null && m_timephasedActualWork.hasData())\n {\n if (hasMultipleCostRates())\n {\n m_timephasedActualCost = getTimephasedCostMultipleRates(getTimephasedActualWork(), getTimephasedActualOvertimeWork());\n }\n else\n {\n m_timephasedActualCost = getTimephasedCostSingleRate(getTimephasedActualWork(), getTimephasedActualOvertimeWork());\n }\n }\n }\n else\n {\n m_timephasedActualCost = getTimephasedActualCostFixedAmount();\n }\n\n }\n\n return m_timephasedActualCost;\n }",
"public final PJsonArray optJSONArray(final String key, final PJsonArray defaultValue) {\n PJsonArray result = optJSONArray(key);\n return result != null ? result : defaultValue;\n }",
"@Override\n public Response toResponse(ErrorDto e)\n {\n // String type = headers.getContentType() == null ? MediaType.APPLICATION_JSON : headers.getContentType();\n return Response.status(e.httpStatus).entity(e).type(MediaType.APPLICATION_JSON).build();\n }"
] |
Checks if the provided license is valid and could be stored into the database
@param license the license to test
@throws WebApplicationException if the data is corrupted | [
"public static void validate(final License license) {\n // A license should have a name\n if(license.getName() == null ||\n license.getName().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"License name should not be empty!\")\n .build());\n }\n\n // A license should have a long name\n if(license.getLongName() == null ||\n license.getLongName().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"License long name should not be empty!\")\n .build());\n }\n\n // If there is a regexp, it should compile\n if(license.getRegexp() != null &&\n !license.getRegexp().isEmpty()){\n try{\n Pattern.compile(license.getRegexp());\n }\n catch (PatternSyntaxException e){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"License regexp does not compile!\").build());\n }\n\n Pattern regex = Pattern.compile(\"[&%//]\");\n if(regex.matcher(license.getRegexp()).find()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"License regexp does not compile!\").build());\n }\n\n }\n }"
] | [
"public static responderparam get(nitro_service service) throws Exception{\n\t\tresponderparam obj = new responderparam();\n\t\tresponderparam[] response = (responderparam[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public static dnsview get(nitro_service service, String viewname) throws Exception{\n\t\tdnsview obj = new dnsview();\n\t\tobj.set_viewname(viewname);\n\t\tdnsview response = (dnsview) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static double TopsoeDivergence(double[] p, double[] q) {\n double r = 0;\n for (int i = 0; i < p.length; i++) {\n if (p[i] != 0 && q[i] != 0) {\n double den = p[i] + q[i];\n r += p[i] * Math.log(2 * p[i] / den) + q[i] * Math.log(2 * q[i] / den);\n }\n }\n return r;\n }",
"private void writeNotes(int recordNumber, String text) throws IOException\n {\n m_buffer.setLength(0);\n\n m_buffer.append(recordNumber);\n m_buffer.append(m_delimiter);\n\n if (text != null)\n {\n String note = stripLineBreaks(text, MPXConstants.EOL_PLACEHOLDER_STRING);\n boolean quote = (note.indexOf(m_delimiter) != -1 || note.indexOf('\"') != -1);\n int length = note.length();\n char c;\n\n if (quote == true)\n {\n m_buffer.append('\"');\n }\n\n for (int loop = 0; loop < length; loop++)\n {\n c = note.charAt(loop);\n\n switch (c)\n {\n case '\"':\n {\n m_buffer.append(\"\\\"\\\"\");\n break;\n }\n\n default:\n {\n m_buffer.append(c);\n break;\n }\n }\n }\n\n if (quote == true)\n {\n m_buffer.append('\"');\n }\n }\n\n m_buffer.append(MPXConstants.EOL);\n\n m_writer.write(m_buffer.toString());\n }",
"public <T> QueryResult<T> query(String partitionKey, String query, final Class<T> classOfT) {\n URI uri = new DatabaseURIHelper(db.getDBUri()).partition(partitionKey).path(\"_find\").build();\n return this.query(uri, query, classOfT);\n }",
"protected void update(float scale) {\n GVRSceneObject owner = getOwnerObject();\n if (isEnabled() && (owner != null) && owner.isEnabled())\n {\n float w = getWidth();\n float h = getHeight();\n mPose.update(mARPlane.getCenterPose(), scale);\n Matrix4f m = new Matrix4f();\n m.set(mPose.getPoseMatrix());\n m.scaleLocal(w * 0.95f, h * 0.95f, 1.0f);\n owner.getTransform().setModelMatrix(m);\n }\n }",
"static PatchingResult executeTasks(final IdentityPatchContext context, final IdentityPatchContext.FinalizeCallback callback) throws Exception {\n final List<PreparedTask> tasks = new ArrayList<PreparedTask>();\n final List<ContentItem> conflicts = new ArrayList<ContentItem>();\n // Identity\n prepareTasks(context.getIdentityEntry(), context, tasks, conflicts);\n // Layers\n for (final IdentityPatchContext.PatchEntry layer : context.getLayers()) {\n prepareTasks(layer, context, tasks, conflicts);\n }\n // AddOns\n for (final IdentityPatchContext.PatchEntry addOn : context.getAddOns()) {\n prepareTasks(addOn, context, tasks, conflicts);\n }\n // If there were problems report them\n if (!conflicts.isEmpty()) {\n throw PatchLogger.ROOT_LOGGER.conflictsDetected(conflicts);\n }\n // Execute the tasks\n for (final PreparedTask task : tasks) {\n // Unless it's excluded by the user\n final ContentItem item = task.getContentItem();\n if (item != null && context.isExcluded(item)) {\n continue;\n }\n // Run the task\n task.execute();\n }\n return context.finalize(callback);\n }",
"public static String compactToString(ModelNode node) {\n Objects.requireNonNull(node);\n final StringWriter stringWriter = new StringWriter();\n final PrintWriter writer = new PrintWriter(stringWriter, true);\n node.writeString(writer, true);\n return stringWriter.toString();\n }",
"private void saveLocalization() {\n\n SortedProperties localization = new SortedProperties();\n for (Object itemId : m_container.getItemIds()) {\n Item item = m_container.getItem(itemId);\n String key = item.getItemProperty(TableProperty.KEY).getValue().toString();\n String value = item.getItemProperty(TableProperty.TRANSLATION).getValue().toString();\n if (!(key.isEmpty() || value.isEmpty())) {\n localization.put(key, value);\n }\n }\n m_keyset.updateKeySet(m_localizations.get(m_locale).keySet(), localization.keySet());\n m_localizations.put(m_locale, localization);\n\n }"
] |
Utility function that constructs AdminClient.
@param url URL pointing to the bootstrap node
@return Newly constructed AdminClient | [
"public static AdminClient getAdminClient(String url) {\n ClientConfig config = new ClientConfig().setBootstrapUrls(url)\n .setConnectionTimeout(5, TimeUnit.SECONDS);\n\n AdminClientConfig adminConfig = new AdminClientConfig().setAdminSocketTimeoutSec(5);\n return new AdminClient(adminConfig, config);\n }"
] | [
"public ThreadInfo[] getThreadDump() {\n ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();\n return threadMxBean.dumpAllThreads(true, true);\n }",
"public void removeControl(String name) {\n Widget control = findChildByName(name);\n if (control != null) {\n removeChild(control);\n if (mBgResId != -1) {\n updateMesh();\n }\n }\n }",
"public static ResourceKey key(Class<?> clazz, String id) {\n return new ResourceKey(clazz.getName(), id);\n }",
"private ColumnDefinition[] columnDefinitions(ColumnDefinition[] columns, String[] order)\n {\n Map<String, ColumnDefinition> map = makeColumnMap(columns);\n ColumnDefinition[] result = new ColumnDefinition[order.length];\n for (int index = 0; index < order.length; index++)\n {\n result[index] = map.get(order[index]);\n }\n return result;\n }",
"public void setNamespace(String prefix, String namespaceURI) {\n ensureNotNull(\"Prefix\", prefix);\n ensureNotNull(\"Namespace URI\", namespaceURI);\n\n namespaces.put(prefix, namespaceURI);\n }",
"public List<MapRow> readTable(TableReader reader) throws IOException\n {\n reader.read();\n return reader.getRows();\n }",
"public Request option(String key, Object value) {\n this.options.put(key, value);\n return this;\n }",
"public static boolean invert(final DMatrixRMaj cov , final DMatrixRMaj cov_inv ) {\n if( cov.numCols <= 4 ) {\n if( cov.numCols != cov.numRows ) {\n throw new IllegalArgumentException(\"Must be a square matrix.\");\n }\n\n if( cov.numCols >= 2 )\n UnrolledInverseFromMinor_DDRM.inv(cov,cov_inv);\n else\n cov_inv.data[0] = 1.0/cov.data[0];\n\n } else {\n LinearSolverDense<DMatrixRMaj> solver = LinearSolverFactory_DDRM.symmPosDef(cov.numRows);\n // wrap it to make sure the covariance is not modified.\n solver = new LinearSolverSafe<DMatrixRMaj>(solver);\n if( !solver.setA(cov) )\n return false;\n solver.invert(cov_inv);\n }\n return true;\n }",
"public void close() {\n this.waitUntilInitialized();\n\n this.ongoingOperationsGroup.blockAndWait();\n\n syncLock.lock();\n try {\n if (this.networkMonitor != null) {\n this.networkMonitor.removeNetworkStateListener(this);\n }\n this.dispatcher.close();\n stop();\n this.localClient.close();\n } finally {\n syncLock.unlock();\n }\n }"
] |
Adds a module to the modules that should be exported.
If called at least once, the explicitly added modules will be exported
instead of the default modules.
@param moduleName the name of the module to export. | [
"public void addModuleToExport(final String moduleName) {\n\n if (m_modulesToExport == null) {\n m_modulesToExport = new HashSet<String>();\n }\n m_modulesToExport.add(moduleName);\n }"
] | [
"public Set<AttributeAccess.Flag> getFlags() {\n if (attributeAccess == null) {\n return Collections.emptySet();\n }\n return attributeAccess.getFlags();\n }",
"public void start() {\n if (TransitionConfig.isDebug()) {\n getTransitionStateHolder().start();\n }\n\n mLastProgress = Float.MIN_VALUE;\n\n TransitionController transitionController;\n for (int i = 0, size = mTransitionControls.size(); i < size; i++) {\n transitionController = mTransitionControls.get(i);\n if (mInterpolator != null) {\n transitionController.setInterpolator(mInterpolator);\n }\n //required for ViewPager transitions to work\n if (mTarget != null) {\n transitionController.setTarget(mTarget);\n }\n transitionController.setUpdateStateAfterUpdateProgress(mUpdateStateAfterUpdateProgress);\n transitionController.start();\n }\n }",
"@SuppressWarnings(\"unchecked\") private boolean isFieldPopulated(Task task, TaskField field)\n {\n boolean result = false;\n if (field != null)\n {\n Object value = task.getCachedValue(field);\n switch (field)\n {\n case PREDECESSORS:\n case SUCCESSORS:\n {\n result = value != null && !((List<Relation>) value).isEmpty();\n break;\n }\n\n default:\n {\n result = value != null;\n break;\n }\n }\n }\n return result;\n }",
"public String getFormattedParentValue()\n {\n String result = null;\n if (m_elements.size() > 2)\n {\n result = joinElements(m_elements.size() - 2);\n }\n return result;\n }",
"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 boolean hasUppercaseVariations(int base, boolean lowerOnly) {\n\t\tif(base > 10) {\n\t\t\tint count = getSegmentCount();\n\t\t\tfor(int i = 0; i < count; i++) {\n\t\t\t\tIPv6AddressSegment seg = getSegment(i);\n\t\t\t\tif(seg.hasUppercaseVariations(base, lowerOnly)) {\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}",
"boolean undoChanges() {\n final State state = stateUpdater.getAndSet(this, State.ROLLBACK_ONLY);\n if (state == State.COMPLETED || state == State.ROLLBACK_ONLY) {\n // Was actually completed already\n return false;\n }\n PatchingTaskContext.Mode currentMode = this.mode;\n mode = PatchingTaskContext.Mode.UNDO;\n final PatchContentLoader loader = PatchContentLoader.create(miscBackup, null, null);\n // Undo changes for the identity\n undoChanges(identityEntry, loader);\n // TODO maybe check if we need to do something for the layers too !?\n if (state == State.INVALIDATE || currentMode == PatchingTaskContext.Mode.ROLLBACK) {\n // For apply the state needs to be invalidate\n // For rollback the files are invalidated as part of the tasks\n final PatchingTaskContext.Mode mode = currentMode == PatchingTaskContext.Mode.APPLY ? PatchingTaskContext.Mode.ROLLBACK : PatchingTaskContext.Mode.APPLY;\n for (final File file : moduleInvalidations) {\n try {\n PatchModuleInvalidationUtils.processFile(this, file, mode);\n } catch (Exception e) {\n PatchLogger.ROOT_LOGGER.debugf(e, \"failed to restore state for %s\", file);\n }\n }\n if(!modulesToReenable.isEmpty()) {\n for (final File file : modulesToReenable) {\n try {\n PatchModuleInvalidationUtils.processFile(this, file, PatchingTaskContext.Mode.APPLY);\n } catch (Exception e) {\n PatchLogger.ROOT_LOGGER.debugf(e, \"failed to restore state for %s\", file);\n }\n }\n }\n if(!modulesToDisable.isEmpty()) {\n for (final File file : modulesToDisable) {\n try {\n PatchModuleInvalidationUtils.processFile(this, file, PatchingTaskContext.Mode.ROLLBACK);\n } catch (Exception e) {\n PatchLogger.ROOT_LOGGER.debugf(e, \"failed to restore state for %s\", file);\n }\n }\n }\n }\n return true;\n }",
"protected void update(float scale) {\n // Updates only when the plane is in the scene\n GVRSceneObject owner = getOwnerObject();\n\n if ((owner != null) && isEnabled() && owner.isEnabled())\n {\n convertFromARtoVRSpace(scale);\n }\n }",
"public static boolean isConstant(Expression expression, Object expected) {\r\n return expression instanceof ConstantExpression && expected.equals(((ConstantExpression) expression).getValue());\r\n }"
] |
Convert an Integer value into a String.
@param value Integer value
@return String value | [
"private String getIntegerString(Number value)\n {\n return (value == null ? null : Integer.toString(value.intValue()));\n }"
] | [
"public void clearHandlers() {\r\n\r\n for (Map<String, CmsAttributeHandler> handlers : m_handlers) {\r\n for (CmsAttributeHandler handler : handlers.values()) {\r\n handler.clearHandlers();\r\n }\r\n handlers.clear();\r\n }\r\n m_handlers.clear();\r\n m_handlers.add(new HashMap<String, CmsAttributeHandler>());\r\n m_handlerById.clear();\r\n }",
"public void commitWorkingCopy(final String commitMessage) throws IOException, InterruptedException {\n build.getWorkspace().act(new SVNCommitWorkingCopyCallable(commitMessage, getLocation(),\n getSvnAuthenticationProvider(build), buildListener));\n }",
"private ModelNode createJVMNode() throws OperationFailedException {\n ModelNode jvm = new ModelNode().setEmptyObject();\n jvm.get(NAME).set(getProperty(\"java.vm.name\"));\n jvm.get(JAVA_VERSION).set(getProperty(\"java.vm.specification.version\"));\n jvm.get(JVM_VERSION).set(getProperty(\"java.version\"));\n jvm.get(JVM_VENDOR).set(getProperty(\"java.vm.vendor\"));\n jvm.get(JVM_HOME).set(getProperty(\"java.home\"));\n return jvm;\n }",
"public void setAttributeEditable(Attribute attribute, boolean editable) {\n\t\tattribute.setEditable(editable);\n\t\tif (!(attribute instanceof LazyAttribute)) { // should not instantiate lazy attributes!\n\t\t\tif (attribute instanceof ManyToOneAttribute) {\n\t\t\t\tsetAttributeEditable(((ManyToOneAttribute) attribute).getValue(), editable);\n\t\t\t} else if (attribute instanceof OneToManyAttribute) {\n\t\t\t\tList<AssociationValue> values = ((OneToManyAttribute) attribute).getValue();\n\t\t\t\tfor (AssociationValue value : values) {\n\t\t\t\t\tsetAttributeEditable(value, editable);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<Symmetry454Date> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<Symmetry454Date>) super.localDateTime(temporal);\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 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 static String encodeQueryParam(String queryParam, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(queryParam, encoding, HierarchicalUriComponents.Type.QUERY_PARAM);\n\t}",
"PatchEntry getEntry(final String name, boolean addOn) {\n return addOn ? addOns.get(name) : layers.get(name);\n }"
] |
Update the lastCheckTime of the given record.
@param id the id
@param lastCheckTime the new value | [
"public final void updateLastCheckTime(final String id, final long lastCheckTime) {\n final CriteriaBuilder builder = getSession().getCriteriaBuilder();\n final CriteriaUpdate<PrintJobStatusExtImpl> update =\n builder.createCriteriaUpdate(PrintJobStatusExtImpl.class);\n final Root<PrintJobStatusExtImpl> root = update.from(PrintJobStatusExtImpl.class);\n update.where(builder.equal(root.get(\"referenceId\"), id));\n update.set(root.get(\"lastCheckTime\"), lastCheckTime);\n getSession().createQuery(update).executeUpdate();\n }"
] | [
"public void merge(final ResourceRoot additionalResourceRoot) {\n if(!additionalResourceRoot.getRoot().equals(root)) {\n throw ServerLogger.ROOT_LOGGER.cannotMergeResourceRoot(root, additionalResourceRoot.getRoot());\n }\n usePhysicalCodeSource = additionalResourceRoot.usePhysicalCodeSource;\n if(additionalResourceRoot.getExportFilters().isEmpty()) {\n //new root has no filters, so we don't want our existing filters to break anything\n //see WFLY-1527\n this.exportFilters.clear();\n } else {\n this.exportFilters.addAll(additionalResourceRoot.getExportFilters());\n }\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 static String join(Collection<String> s, String delimiter) {\r\n return join(s, delimiter, false);\r\n }",
"public int getRegisteredResourceRequestCount() {\n int count = 0;\n for(Entry<K, Queue<AsyncResourceRequest<V>>> entry: this.requestQueueMap.entrySet()) {\n // FYI: .size() is not constant time in the next call. ;)\n count += entry.getValue().size();\n }\n return count;\n }",
"public static Diagram parseJson(JSONObject json,\n Boolean keepGlossaryLink) throws JSONException {\n ArrayList<Shape> shapes = new ArrayList<Shape>();\n HashMap<String, JSONObject> flatJSON = flatRessources(json);\n for (String resourceId : flatJSON.keySet()) {\n parseRessource(shapes,\n flatJSON,\n resourceId,\n keepGlossaryLink);\n }\n String id = \"canvas\";\n\n if (json.has(\"resourceId\")) {\n id = json.getString(\"resourceId\");\n shapes.remove(new Shape(id));\n }\n ;\n Diagram diagram = new Diagram(id);\n\n // remove Diagram\n // (Diagram)getShapeWithId(json.getString(\"resourceId\"), shapes);\n parseStencilSet(json,\n diagram);\n parseSsextensions(json,\n diagram);\n parseStencil(json,\n diagram);\n parseProperties(json,\n diagram,\n keepGlossaryLink);\n parseChildShapes(shapes,\n json,\n diagram);\n parseBounds(json,\n diagram);\n diagram.setShapes(shapes);\n return diagram;\n }",
"public Date getFinish()\n {\n Date result = (Date) getCachedValue(AssignmentField.FINISH);\n if (result == null)\n {\n result = getTask().getFinish();\n }\n return result;\n }",
"public static DMatrixRMaj[] span(int dimen, int numVectors , Random rand ) {\n if( dimen < numVectors )\n throw new IllegalArgumentException(\"The number of vectors must be less than or equal to the dimension\");\n\n DMatrixRMaj u[] = new DMatrixRMaj[numVectors];\n\n u[0] = RandomMatrices_DDRM.rectangle(dimen,1,-1,1,rand);\n NormOps_DDRM.normalizeF(u[0]);\n\n for( int i = 1; i < numVectors; i++ ) {\n// System.out.println(\" i = \"+i);\n DMatrixRMaj a = new DMatrixRMaj(dimen,1);\n DMatrixRMaj r=null;\n\n for( int j = 0; j < i; j++ ) {\n// System.out.println(\"j = \"+j);\n if( j == 0 )\n r = RandomMatrices_DDRM.rectangle(dimen,1,-1,1,rand);\n\n // find a vector that is normal to vector j\n // u[i] = (1/2)*(r + Q[j]*r)\n a.set(r);\n VectorVectorMult_DDRM.householder(-2.0,u[j],r,a);\n CommonOps_DDRM.add(r,a,a);\n CommonOps_DDRM.scale(0.5,a);\n\n// UtilEjml.print(a);\n\n DMatrixRMaj t = a;\n a = r;\n r = t;\n\n // normalize it so it doesn't get too small\n double val = NormOps_DDRM.normF(r);\n if( val == 0 || Double.isNaN(val) || Double.isInfinite(val))\n throw new RuntimeException(\"Failed sanity check\");\n CommonOps_DDRM.divide(r,val);\n }\n\n u[i] = r;\n }\n\n return u;\n }",
"@Deprecated\n\tpublic List<Double> getResolutions() {\n\t\tList<Double> resolutions = new ArrayList<Double>();\n\t\tfor (ScaleInfo scale : getZoomLevels()) {\n\t\t\tresolutions.add(1. / scale.getPixelPerUnit());\n\t\t}\n\t\treturn resolutions;\n\t}",
"private Bpmn2Resource unmarshall(JsonParser parser,\n String preProcessingData) throws IOException {\n try {\n parser.nextToken(); // open the object\n ResourceSet rSet = new ResourceSetImpl();\n rSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(\"bpmn2\",\n new JBPMBpmn2ResourceFactoryImpl());\n Bpmn2Resource bpmn2 = (Bpmn2Resource) rSet.createResource(URI.createURI(\"virtual.bpmn2\"));\n rSet.getResources().add(bpmn2);\n _currentResource = bpmn2;\n\n if (preProcessingData == null || preProcessingData.length() < 1) {\n preProcessingData = \"ReadOnlyService\";\n }\n\n // do the unmarshalling now:\n Definitions def = (Definitions) unmarshallItem(parser,\n preProcessingData);\n def.setExporter(exporterName);\n def.setExporterVersion(exporterVersion);\n revisitUserTasks(def);\n revisitServiceTasks(def);\n revisitMessages(def);\n revisitCatchEvents(def);\n revisitThrowEvents(def);\n revisitLanes(def);\n revisitSubProcessItemDefs(def);\n revisitArtifacts(def);\n revisitGroups(def);\n revisitTaskAssociations(def);\n revisitTaskIoSpecification(def);\n revisitSendReceiveTasks(def);\n reconnectFlows();\n revisitGateways(def);\n revisitCatchEventsConvertToBoundary(def);\n revisitBoundaryEventsPositions(def);\n createDiagram(def);\n updateIDs(def);\n revisitDataObjects(def);\n revisitAssociationsIoSpec(def);\n revisitWsdlImports(def);\n revisitMultiInstanceTasks(def);\n addSimulation(def);\n revisitItemDefinitions(def);\n revisitProcessDoc(def);\n revisitDI(def);\n revisitSignalRef(def);\n orderDiagramElements(def);\n\n // return def;\n _currentResource.getContents().add(def);\n return _currentResource;\n } catch (Exception e) {\n _logger.error(e.getMessage());\n return _currentResource;\n } finally {\n parser.close();\n _objMap.clear();\n _idMap.clear();\n _outgoingFlows.clear();\n _sequenceFlowTargets.clear();\n _bounds.clear();\n _currentResource = null;\n }\n }"
] |
Inserts the specified array into the specified original array at the specified index.
@param original the original array into which we want to insert another array
@param index the index at which we want to insert the array
@param inserted the array that we want to insert
@return the combined array | [
"public static int[] insertArray(int[] original, int index, int[] inserted) {\n int[] modified = new int[original.length + inserted.length];\n System.arraycopy(original, 0, modified, 0, index);\n System.arraycopy(inserted, 0, modified, index, inserted.length);\n System.arraycopy(original, index, modified, index + inserted.length, modified.length - index - inserted.length);\n return modified;\n }"
] | [
"protected void generateFile(File file,\n String templateName,\n VelocityContext context) throws Exception\n {\n Writer writer = new BufferedWriter(new FileWriter(file));\n try\n {\n Velocity.mergeTemplate(classpathPrefix + templateName,\n ENCODING,\n context,\n writer);\n writer.flush();\n }\n finally\n {\n writer.close();\n }\n }",
"public void setHostName(String hostName) {\n if (hostName == null || hostName.contains(\":\")) {\n return;\n }\n ODO_HOST = hostName;\n BASE_URL = \"http://\" + ODO_HOST + \":\" + API_PORT + \"/\" + API_BASE + \"/\";\n }",
"public <Result, Param extends Resource> Result execWithTemporaryCaching(Param resource, IUnitOfWork<Result, Param> transaction) throws WrappedException {\n\t\tCacheAdapter cacheAdapter = getOrCreate(resource);\n\t\tIgnoreValuesMemento memento = cacheAdapter.ignoreNewValues();\n\t\ttry {\n\t\t\treturn transaction.exec(resource);\n\t\t} catch (Exception e) {\n\t\t\tthrow new WrappedException(e);\n\t\t} finally {\n\t\t\tmemento.done();\n\t\t}\n\t}",
"public RandomVariableInterface[] getBasisFunctions(double exerciseDate, LIBORModelMonteCarloSimulationInterface model) throws CalculationException {\n\n\t\tArrayList<RandomVariableInterface> basisFunctions = new ArrayList<RandomVariableInterface>();\n\n\t\tRandomVariableInterface basisFunction;\n\n\t\t// Constant\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tbasisFunctions.add(basisFunction);\n\n\t\t// LIBORs\n\t\tint liborPeriodIndex, liborPeriodIndexEnd;\n\t\tRandomVariableInterface rate;\n\n\t\t// 1 Period\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tliborPeriodIndex = model.getLiborPeriodIndex(exerciseDate);\n\t\tif(liborPeriodIndex < 0) {\n\t\t\tliborPeriodIndex = -liborPeriodIndex-1;\n\t\t}\n\t\tliborPeriodIndexEnd = liborPeriodIndex+1;\n\t\tdouble periodLength1 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex);\n\n\t\trate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd));\n\t\tbasisFunction = basisFunction.discount(rate, periodLength1);\n\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\tbasisFunction = basisFunction.discount(rate, periodLength1);\n\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t// n/2 Period\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tliborPeriodIndex = model.getLiborPeriodIndex(exerciseDate);\n\t\tif(liborPeriodIndex < 0) {\n\t\t\tliborPeriodIndex = -liborPeriodIndex-1;\n\t\t}\n\t\tliborPeriodIndexEnd = (liborPeriodIndex + model.getNumberOfLibors())/2;\n\n\t\tdouble periodLength2 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex);\n\n\t\tif(periodLength2 != periodLength1) {\n\t\t\trate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd));\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength2);\n\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength2);\n\t\t\t//\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength2);\n\t\t\t//\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\t\t}\n\n\n\t\t// n Period\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tliborPeriodIndex = model.getLiborPeriodIndex(exerciseDate);\n\t\tif(liborPeriodIndex < 0) {\n\t\t\tliborPeriodIndex = -liborPeriodIndex-1;\n\t\t}\n\t\tliborPeriodIndexEnd = model.getNumberOfLibors();\n\t\tdouble periodLength3 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex);\n\n\t\tif(periodLength3 != periodLength1 && periodLength3 != periodLength2) {\n\t\t\trate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd));\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength3);\n\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength3);\n\t\t\t//\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\t\t}\n\n\t\treturn basisFunctions.toArray(new RandomVariableInterface[0]);\n\t}",
"public void seekToDayOfYear(String dayOfYear) {\n int dayOfYearInt = Integer.parseInt(dayOfYear);\n assert(dayOfYearInt >= 1 && dayOfYearInt <= 366);\n \n markDateInvocation();\n \n dayOfYearInt = Math.min(dayOfYearInt, _calendar.getActualMaximum(Calendar.DAY_OF_YEAR));\n _calendar.set(Calendar.DAY_OF_YEAR, dayOfYearInt);\n }",
"public final static String process(final File file, final boolean safeMode) throws IOException\n {\n return process(file, Configuration.builder().setSafeMode(safeMode).build());\n }",
"public static String addFolderSlashIfNeeded(String folderName) {\n if (!\"\".equals(folderName) && !folderName.endsWith(\"/\")) {\n return folderName + \"/\";\n } else {\n return folderName;\n }\n }",
"protected void consumeChar(ImapRequestLineReader request, char expected)\n throws ProtocolException {\n char consumed = request.consume();\n if (consumed != expected) {\n throw new ProtocolException(\"Expected:'\" + expected + \"' found:'\" + consumed + '\\'');\n }\n }",
"public RedwoodConfiguration printChannels(final int width){\r\n tasks.add(new Runnable() { public void run() { Redwood.Util.printChannels(width);} });\r\n return this;\r\n }"
] |
Gets id of a link and creates the new one if necessary.
@param linkName name of the link.
@param allowCreate if set to true and if there is no link named as linkName,
create the new id for the linkName.
@return < 0 if there is no such link and create=false, else id of the link | [
"public int getLinkId(@NotNull final PersistentStoreTransaction txn, @NotNull final String linkName, final boolean allowCreate) {\n return allowCreate ? linkIds.getOrAllocateId(txn, linkName) : linkIds.getId(txn, linkName);\n }"
] | [
"public void addDependency(final ProcessorGraphNode node) {\n Assert.isTrue(node != this, \"A processor can't depends on himself\");\n\n this.dependencies.add(node);\n node.addRequirement(this);\n }",
"public static void startNamedTimer(String timerName, int todoFlags,\n\t\t\tlong threadId) {\n\t\tgetNamedTimer(timerName, todoFlags, threadId).start();\n\t}",
"public void unlinkFK(Object targetObject, ClassDescriptor cld, ObjectReferenceDescriptor rds)\n {\n setFKField(targetObject, cld, rds, null);\n }",
"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 }",
"public void fillFromToWith(int from, int to, Object val) {\r\n\tcheckRangeFromTo(from,to,this.size);\r\n\tfor (int i=from; i<=to;) setQuick(i++,val); \r\n}",
"public static String taskListToString(List<RebalanceTaskInfo> infos) {\n StringBuffer sb = new StringBuffer();\n for (RebalanceTaskInfo info : infos) {\n sb.append(\"\\t\").append(info.getDonorId()).append(\" -> \").append(info.getStealerId()).append(\" : [\");\n for (String storeName : info.getPartitionStores()) {\n sb.append(\"{\").append(storeName).append(\" : \").append(info.getPartitionIds(storeName)).append(\"}\");\n }\n sb.append(\"]\").append(Utils.NEWLINE);\n }\n return sb.toString();\n }",
"@SuppressWarnings(\"deprecation\")\n\tpublic static boolean dateEquals(java.util.Date d1, java.util.Date d2) {\n if (d1 == null || d2 == null) {\n return false;\n }\n\n return d1.getDate() == d2.getDate()\n && d1.getMonth() == d2.getMonth()\n && d1.getYear() == d2.getYear();\n }",
"private void writePropertyStatisticsToFile(UsageStatistics usageStatistics,\n\t\t\tString fileName) {\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(fileName))) {\n\n\t\t\tout.println(\"Property id,in statements,in qualifiers,in references,total\");\n\n\t\t\tfor (Entry<PropertyIdValue, Integer> entry : usageStatistics.propertyCountsMain\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tint qCount = usageStatistics.propertyCountsQualifier.get(entry\n\t\t\t\t\t\t.getKey());\n\t\t\t\tint rCount = usageStatistics.propertyCountsReferences.get(entry\n\t\t\t\t\t\t.getKey());\n\t\t\t\tint total = entry.getValue() + qCount + rCount;\n\t\t\t\tout.println(entry.getKey().getId() + \",\" + entry.getValue()\n\t\t\t\t\t\t+ \",\" + qCount + \",\" + rCount + \",\" + total);\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}",
"protected void checkConsecutiveAlpha() {\n\n Pattern symbolsPatter = Pattern.compile(REGEX_ALPHA_UC + \"+\");\n Matcher matcher = symbolsPatter.matcher(this.password);\n int met = 0;\n while (matcher.find()) {\n int start = matcher.start();\n int end = matcher.end();\n if (start == end) {\n continue;\n }\n int diff = end - start;\n if (diff >= 3) {\n met += diff;\n }\n\n }\n\n this.result.negative(met * CONSECUTIVE_ALPHA_WEIGHT);\n\n // alpha lower case\n\n symbolsPatter = Pattern.compile(REGEX_ALPHA_LC + \"+\");\n matcher = symbolsPatter.matcher(this.password);\n met = 0;\n while (matcher.find()) {\n int start = matcher.start();\n int end = matcher.end();\n if (start == end) {\n continue;\n }\n int diff = end - start;\n if (diff >= 3) {\n met += diff;\n }\n\n }\n\n this.result.negative(met * CONSECUTIVE_ALPHA_WEIGHT);\n }"
] |
Information about a specific release.
@param appName App name. See {@link #listApps} for a list of apps that can be used.
@param releaseName Release name. See {@link #listReleases} for a list of the app's releases.
@return the release object | [
"public Release getReleaseInfo(String appName, String releaseName) {\n return connection.execute(new ReleaseInfo(appName, releaseName), apiKey);\n }"
] | [
"private static String removeLastDot(final String pkgName) {\n\t\treturn pkgName.charAt(pkgName.length() - 1) == Characters.DOT ? pkgName.substring(0, pkgName.length() - 1) : pkgName;\n\t}",
"public boolean canLockBecauseOfInactivity(CmsObject cms, CmsUser user) {\n\n return !user.isManaged()\n && !user.isWebuser()\n && !OpenCms.getDefaultUsers().isDefaultUser(user.getName())\n && !OpenCms.getRoleManager().hasRole(cms, user.getName(), CmsRole.ROOT_ADMIN);\n }",
"public void waitAndRetry() {\n ContinueToSendToBatchSenderAsstManager continueToSendToBatchSenderAsstManager = new ContinueToSendToBatchSenderAsstManager(\n processedWorkerCount);\n\n logger.debug(\"NOW WAIT Another \" + asstManagerRetryIntervalMillis\n + \" MS. at \" + PcDateUtils.getNowDateTimeStrStandard());\n getContext()\n .system()\n .scheduler()\n .scheduleOnce(\n Duration.create(asstManagerRetryIntervalMillis,\n TimeUnit.MILLISECONDS), getSelf(),\n continueToSendToBatchSenderAsstManager,\n getContext().system().dispatcher(), getSelf());\n return;\n }",
"private static void attachToDecor(Activity activity, MenuDrawer menuDrawer) {\n ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView();\n ViewGroup decorChild = (ViewGroup) decorView.getChildAt(0);\n\n decorView.removeAllViews();\n decorView.addView(menuDrawer, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);\n\n menuDrawer.mContentContainer.addView(decorChild, decorChild.getLayoutParams());\n }",
"public void updateRepeatNumber(int newNum, int path_id, String client_uuid) throws Exception {\n updateRequestResponseTables(\"repeat_number\", newNum, getProfileIdFromPathID(path_id), client_uuid, path_id);\n }",
"@SuppressWarnings(\"SameParameterValue\")\n private void sendField(Field field) throws IOException {\n if (isConnected()) {\n try {\n field.write(channel);\n } catch (IOException e) {\n logger.warn(\"Problem trying to write field to dbserver, closing connection\", e);\n close();\n throw e;\n }\n return;\n }\n throw new IOException(\"sendField() called after dbserver connection was closed\");\n }",
"public static final PolylineOptions buildOpenArc(LatLong center, LatLong start, LatLong end) {\n MVCArray res = buildArcPoints(center, start, end);\n return new PolylineOptions().path(res);\n }",
"public static Double getDistanceBetweenCoordinates(Tuple2<Double, Double> point1, Tuple2<Double, Double> point2) {\r\n // sqrt( (x2-x1)^2 + (y2-y2)^2 )\r\n Double xDiff = point1._1() - point2._1();\r\n Double yDiff = point1._2() - point2._2();\r\n return Math.sqrt(xDiff * xDiff + yDiff * yDiff);\r\n }",
"public static void init() {\n reports.clear();\n Reflections reflections = new Reflections(REPORTS_PACKAGE);\n final Set<Class<? extends Report>> reportClasses = reflections.getSubTypesOf(Report.class);\n\n for(Class<? extends Report> c : reportClasses) {\n LOG.info(\"Report class: \" + c.getName());\n try {\n reports.add(c.newInstance());\n } catch (IllegalAccessException | InstantiationException e) {\n LOG.error(\"Error while loading report implementation classes\", e);\n }\n }\n\n if(LOG.isInfoEnabled()) {\n LOG.info(String.format(\"Detected %s reports\", reports.size()));\n }\n }"
] |
Return true if the processor of the node is currently being executed.
@param processorGraphNode the node to test. | [
"public boolean isRunning(final ProcessorGraphNode processorGraphNode) {\n this.processorLock.lock();\n try {\n return this.runningProcessors.containsKey(processorGraphNode.getProcessor());\n } finally {\n this.processorLock.unlock();\n }\n }"
] | [
"public static Priority getInstance(int priority)\n {\n Priority result;\n\n if (priority >= LOWEST && priority <= DO_NOT_LEVEL && (priority % 100 == 0))\n {\n result = VALUE[(priority / 100) - 1];\n }\n else\n {\n result = new Priority(priority);\n }\n\n return (result);\n }",
"public static authenticationtacacspolicy_systemglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationtacacspolicy_systemglobal_binding obj = new authenticationtacacspolicy_systemglobal_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationtacacspolicy_systemglobal_binding response[] = (authenticationtacacspolicy_systemglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public int scrollToNextPage() {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"scrollToNextPage getCurrentPage() = %d currentIndex = %d\",\n getCurrentPage(), mCurrentItemIndex);\n\n if (mSupportScrollByPage) {\n scrollToPage(getCurrentPage() + 1);\n } else {\n Log.w(TAG, \"Pagination is not enabled!\");\n }\n\n return mCurrentItemIndex;\n\t}",
"public void visitOpen(String packaze, int access, String... modules) {\n if (mv != null) {\n mv.visitOpen(packaze, access, modules);\n }\n }",
"private void processKeyValue(Map<ConfigurationKey, Object> properties, ConfigurationKey key, Object value) {\n if (value instanceof String) {\n value = key.convertValue((String) value);\n }\n if (key.isValidValue(value)) {\n Object previous = properties.put(key, value);\n if (previous != null && !previous.equals(value)) {\n throw ConfigurationLogger.LOG.configurationKeyHasDifferentValues(key.get(), previous, value);\n }\n } else {\n throw ConfigurationLogger.LOG.invalidConfigurationPropertyValue(value, key.get());\n }\n }",
"private void processHyperlinkData(Task task, byte[] data)\n {\n if (data != null)\n {\n int offset = 12;\n String hyperlink;\n String address;\n String subaddress;\n\n offset += 12;\n hyperlink = MPPUtility.getUnicodeString(data, offset);\n offset += ((hyperlink.length() + 1) * 2);\n\n offset += 12;\n address = MPPUtility.getUnicodeString(data, offset);\n offset += ((address.length() + 1) * 2);\n\n offset += 12;\n subaddress = MPPUtility.getUnicodeString(data, offset);\n\n task.setHyperlink(hyperlink);\n task.setHyperlinkAddress(address);\n task.setHyperlinkSubAddress(subaddress);\n }\n }",
"public static cachepolicylabel_policybinding_binding[] get(nitro_service service, String labelname) throws Exception{\n\t\tcachepolicylabel_policybinding_binding obj = new cachepolicylabel_policybinding_binding();\n\t\tobj.set_labelname(labelname);\n\t\tcachepolicylabel_policybinding_binding response[] = (cachepolicylabel_policybinding_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"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 }",
"public void setSingletonVariable(String name, WindupVertexFrame frame)\n {\n setVariable(name, Collections.singletonList(frame));\n }"
] |
Add a '<=' clause so the column must be less-than or equals-to the value. | [
"public Where<T, ID> le(String columnName, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,\n\t\t\t\tSimpleComparison.LESS_THAN_EQUAL_TO_OPERATION));\n\t\treturn this;\n\t}"
] | [
"public Map<Integer, TableDefinition> tableDefinitions()\n {\n Map<Integer, TableDefinition> result = new HashMap<Integer, TableDefinition>();\n\n result.put(Integer.valueOf(2), new TableDefinition(\"PROJECT_SUMMARY\", columnDefinitions(PROJECT_SUMMARY_COLUMNS, projectSummaryColumnsOrder())));\n result.put(Integer.valueOf(7), new TableDefinition(\"BAR\", columnDefinitions(BAR_COLUMNS, barColumnsOrder())));\n result.put(Integer.valueOf(11), new TableDefinition(\"CALENDAR\", columnDefinitions(CALENDAR_COLUMNS, calendarColumnsOrder())));\n result.put(Integer.valueOf(12), new TableDefinition(\"EXCEPTIONN\", columnDefinitions(EXCEPTIONN_COLUMNS, exceptionColumnsOrder())));\n result.put(Integer.valueOf(14), new TableDefinition(\"EXCEPTION_ASSIGNMENT\", columnDefinitions(EXCEPTION_ASSIGNMENT_COLUMNS, exceptionAssignmentColumnsOrder())));\n result.put(Integer.valueOf(15), new TableDefinition(\"TIME_ENTRY\", columnDefinitions(TIME_ENTRY_COLUMNS, timeEntryColumnsOrder())));\n result.put(Integer.valueOf(17), new TableDefinition(\"WORK_PATTERN\", columnDefinitions(WORK_PATTERN_COLUMNS, workPatternColumnsOrder()))); \n result.put(Integer.valueOf(18), new TableDefinition(\"TASK_COMPLETED_SECTION\", columnDefinitions(TASK_COMPLETED_SECTION_COLUMNS, taskCompletedSectionColumnsOrder()))); \n result.put(Integer.valueOf(21), new TableDefinition(\"TASK\", columnDefinitions(TASK_COLUMNS, taskColumnsOrder())));\n result.put(Integer.valueOf(22), new TableDefinition(\"MILESTONE\", columnDefinitions(MILESTONE_COLUMNS, milestoneColumnsOrder())));\n result.put(Integer.valueOf(23), new TableDefinition(\"EXPANDED_TASK\", columnDefinitions(EXPANDED_TASK_COLUMNS, expandedTaskColumnsOrder())));\n result.put(Integer.valueOf(25), new TableDefinition(\"LINK\", columnDefinitions(LINK_COLUMNS, linkColumnsOrder())));\n result.put(Integer.valueOf(61), new TableDefinition(\"CONSUMABLE_RESOURCE\", columnDefinitions(CONSUMABLE_RESOURCE_COLUMNS, consumableResourceColumnsOrder())));\n result.put(Integer.valueOf(62), new TableDefinition(\"PERMANENT_RESOURCE\", columnDefinitions(PERMANENT_RESOURCE_COLUMNS, permanentResourceColumnsOrder())));\n result.put(Integer.valueOf(63), new TableDefinition(\"PERM_RESOURCE_SKILL\", columnDefinitions(PERMANENT_RESOURCE_SKILL_COLUMNS, permanentResourceSkillColumnsOrder())));\n result.put(Integer.valueOf(67), new TableDefinition(\"PERMANENT_SCHEDUL_ALLOCATION\", columnDefinitions(PERMANENT_SCHEDULE_ALLOCATION_COLUMNS, permanentScheduleAllocationColumnsOrder())));\n result.put(Integer.valueOf(190), new TableDefinition(\"WBS_ENTRY\", columnDefinitions(WBS_ENTRY_COLUMNS, wbsEntryColumnsOrder())));\n\n return result;\n }",
"private void populateRecurringException(ProjectCalendarException mpxjException, Exceptions.Exception xmlException)\n {\n RecurringData data = mpxjException.getRecurring();\n xmlException.setEnteredByOccurrences(Boolean.TRUE);\n xmlException.setOccurrences(NumberHelper.getBigInteger(data.getOccurrences()));\n\n switch (data.getRecurrenceType())\n {\n case DAILY:\n {\n xmlException.setType(BigInteger.valueOf(7));\n xmlException.setPeriod(NumberHelper.getBigInteger(data.getFrequency()));\n break;\n }\n\n case WEEKLY:\n {\n xmlException.setType(BigInteger.valueOf(6));\n xmlException.setPeriod(NumberHelper.getBigInteger(data.getFrequency()));\n xmlException.setDaysOfWeek(getDaysOfTheWeek(data));\n break;\n }\n\n case MONTHLY:\n {\n xmlException.setPeriod(NumberHelper.getBigInteger(data.getFrequency()));\n if (data.getRelative())\n {\n xmlException.setType(BigInteger.valueOf(5));\n xmlException.setMonthItem(BigInteger.valueOf(data.getDayOfWeek().getValue() + 2));\n xmlException.setMonthPosition(BigInteger.valueOf(NumberHelper.getInt(data.getDayNumber()) - 1));\n }\n else\n {\n xmlException.setType(BigInteger.valueOf(4));\n xmlException.setMonthDay(NumberHelper.getBigInteger(data.getDayNumber()));\n }\n break;\n }\n\n case YEARLY:\n {\n xmlException.setMonth(BigInteger.valueOf(NumberHelper.getInt(data.getMonthNumber()) - 1));\n if (data.getRelative())\n {\n xmlException.setType(BigInteger.valueOf(3));\n xmlException.setMonthItem(BigInteger.valueOf(data.getDayOfWeek().getValue() + 2));\n xmlException.setMonthPosition(BigInteger.valueOf(NumberHelper.getInt(data.getDayNumber()) - 1));\n }\n else\n {\n xmlException.setType(BigInteger.valueOf(2));\n xmlException.setMonthDay(NumberHelper.getBigInteger(data.getDayNumber()));\n }\n }\n }\n }",
"public static <T> void write(BufferedWriter writer, DatabaseTableConfig<T> config) throws SQLException {\n\t\ttry {\n\t\t\twriteConfig(writer, config);\n\t\t} catch (IOException e) {\n\t\t\tthrow SqlExceptionUtil.create(\"Could not write config to writer\", e);\n\t\t}\n\t}",
"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 }",
"public static String parseString(String value)\n {\n if (value != null)\n {\n // Strip angle brackets if present\n if (!value.isEmpty() && value.charAt(0) == '<')\n {\n value = value.substring(1, value.length() - 1);\n }\n\n // Strip quotes if present\n if (!value.isEmpty() && value.charAt(0) == '\"')\n {\n value = value.substring(1, value.length() - 1);\n }\n }\n return value;\n }",
"public static int readInt(byte[] bytes, int offset) {\n return (((bytes[offset + 0] & 0xff) << 24) | ((bytes[offset + 1] & 0xff) << 16)\n | ((bytes[offset + 2] & 0xff) << 8) | (bytes[offset + 3] & 0xff));\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}",
"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 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 }"
] |
Copy a subsequence of Bytes to specific byte array. Uses the specified offset in the dest byte
array to start the copy.
@param start index of subsequence start (inclusive)
@param end index of subsequence end (exclusive)
@param dest destination array
@param destPos starting position in the destination data.
@exception IndexOutOfBoundsException if copying would cause access of data outside array
bounds.
@exception NullPointerException if either <code>src</code> or <code>dest</code> is
<code>null</code>.
@since 1.1.0 | [
"public void copyTo(int start, int end, byte[] dest, int destPos) {\n // this.subSequence(start, end).copyTo(dest, destPos) would allocate another Bytes object\n arraycopy(start, dest, destPos, end - start);\n }"
] | [
"public static 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 }",
"private synchronized Constructor getIndirectionHandlerConstructor()\r\n {\r\n if(_indirectionHandlerConstructor == null)\r\n {\r\n Class[] paramType = {PBKey.class, Identity.class};\r\n\r\n try\r\n {\r\n _indirectionHandlerConstructor = getIndirectionHandlerClass().getConstructor(paramType);\r\n }\r\n catch(NoSuchMethodException ex)\r\n {\r\n throw new MetadataException(\"The class \"\r\n + _indirectionHandlerClass.getName()\r\n + \" specified for IndirectionHandlerClass\"\r\n + \" is required to have a public constructor with signature (\"\r\n + PBKey.class.getName()\r\n + \", \"\r\n + Identity.class.getName()\r\n + \").\");\r\n }\r\n }\r\n return _indirectionHandlerConstructor;\r\n }",
"public void stop() {\n if (accelerometer != null) {\n queue.clear();\n sensorManager.unregisterListener(this, accelerometer);\n sensorManager = null;\n accelerometer = null;\n }\n }",
"public ClassNode annotatedWith(String name) {\n ClassNode anno = infoBase.node(name);\n this.annotations.add(anno);\n anno.annotated.add(this);\n return this;\n }",
"private static MonolingualTextValue toTerm(MonolingualTextValue term) {\n\t\treturn term instanceof TermImpl ? term : new TermImpl(term.getLanguageCode(), term.getText());\n\t}",
"public void getElevationForLocations(LocationElevationRequest req, ElevationServiceCallback callback) {\n \n this.callback = callback;\n \n JSObject doc = (JSObject) getJSObject().eval(\"document\");\n doc.setMember(getVariableName(), this);\n \n StringBuilder r = new StringBuilder(getVariableName())\n .append(\".\")\n .append(\"getElevationForLocations(\")\n .append(req.getVariableName())\n .append(\", \")\n .append(\"function(results, status) {alert('rec:'+status);\\ndocument.\")\n .append(getVariableName())\n .append(\".processResponse(results, status);});\");\n \n LOG.trace(\"ElevationService direct call: \" + r.toString());\n \n getJSObject().eval(r.toString());\n \n }",
"private String validatePattern() {\n\n String error = null;\n switch (getPatternType()) {\n case DAILY:\n error = isEveryWorkingDay() ? null : validateInterval();\n break;\n case WEEKLY:\n error = validateInterval();\n if (null == error) {\n error = validateWeekDaySet();\n }\n break;\n case MONTHLY:\n error = validateInterval();\n if (null == error) {\n error = validateMonthSet();\n if (null == error) {\n error = isWeekDaySet() ? validateWeekOfMonthSet() : validateDayOfMonth();\n }\n }\n break;\n case YEARLY:\n error = isWeekDaySet() ? validateWeekOfMonthSet() : validateDayOfMonth();\n break;\n case INDIVIDUAL:\n case NONE:\n default:\n }\n return error;\n }",
"protected void handleINEvent(Exchange exchange, String reqFid) throws Fault {\n Message inMsg = exchange.getInMessage();\n\n EventProducerInterceptor epi = null;\n FlowIdHelper.setFlowId(inMsg, reqFid);\n\n ListIterator<Interceptor<? extends Message>> interceptors = inMsg\n .getInterceptorChain().getIterator();\n\n while (interceptors.hasNext() && epi == null) {\n Interceptor<? extends Message> interceptor = interceptors.next();\n\n if (interceptor instanceof EventProducerInterceptor) {\n epi = (EventProducerInterceptor) interceptor;\n epi.handleMessage(inMsg);\n }\n }\n }",
"@NonNull\n @Override\n public File getParent(@NonNull final File from) {\n if (from.getPath().equals(getRoot().getPath())) {\n // Already at root, we can't go higher\n return from;\n } else if (from.getParentFile() != null) {\n return from.getParentFile();\n } else {\n return from;\n }\n }"
] |
If the belief its a count of some sort his counting its increased by one.
@param bName
- the name of the belief count. | [
"private void increaseBeliefCount(String bName) {\n Object belief = this.getBelief(bName);\n int count = 0;\n if (belief!=null) {\n count = (Integer) belief;\n }\n this.setBelief(bName, count + 1);\n }"
] | [
"public static void showOnlyChannels(Object... channels){\r\n for(LogRecordHandler handler : handlers){\r\n if(handler instanceof VisibilityHandler){\r\n VisibilityHandler visHandler = (VisibilityHandler) handler;\r\n visHandler.hideAll();\r\n for (Object channel : channels) {\r\n visHandler.alsoShow(channel);\r\n }\r\n }\r\n }\r\n }",
"public static void checkRequired(OptionSet options, List<String> opts)\n throws VoldemortException {\n List<String> optCopy = Lists.newArrayList();\n for(String opt: opts) {\n if(options.has(opt)) {\n optCopy.add(opt);\n }\n }\n if(optCopy.size() < 1) {\n System.err.println(\"Please specify one of the following options:\");\n for(String opt: opts) {\n System.err.println(\"--\" + opt);\n }\n Utils.croak(\"Missing required option.\");\n }\n if(optCopy.size() > 1) {\n System.err.println(\"Conflicting options:\");\n for(String opt: optCopy) {\n System.err.println(\"--\" + opt);\n }\n Utils.croak(\"Conflicting options detected.\");\n }\n }",
"public static boolean isAlternative(EnhancedAnnotated<?, ?> annotated, MergedStereotypes<?, ?> mergedStereotypes) {\n return annotated.isAnnotationPresent(Alternative.class) || mergedStereotypes.isAlternative();\n }",
"private static void listSlack(ProjectFile file)\n {\n for (Task task : file.getTasks())\n {\n System.out.println(task.getName() + \" Total Slack=\" + task.getTotalSlack() + \" Start Slack=\" + task.getStartSlack() + \" Finish Slack=\" + task.getFinishSlack());\n }\n }",
"public String objectToString(T object) {\n\t\tStringBuilder sb = new StringBuilder(64);\n\t\tsb.append(object.getClass().getSimpleName());\n\t\tfor (FieldType fieldType : fieldTypes) {\n\t\t\tsb.append(' ').append(fieldType.getColumnName()).append('=');\n\t\t\ttry {\n\t\t\t\tsb.append(fieldType.extractJavaFieldValue(object));\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow new IllegalStateException(\"Could not generate toString of field \" + fieldType, e);\n\t\t\t}\n\t\t}\n\t\treturn sb.toString();\n\t}",
"public static int getDayAsReadableInt(Calendar calendar) {\n int day = calendar.get(Calendar.DAY_OF_MONTH);\n int month = calendar.get(Calendar.MONTH) + 1;\n int year = calendar.get(Calendar.YEAR);\n return year * 10000 + month * 100 + day;\n }",
"private void processDefaultCurrency(Integer currencyID) throws SQLException\n {\n List<Row> rows = getRows(\"select * from \" + m_schema + \"currtype where curr_id=?\", currencyID);\n if (!rows.isEmpty())\n {\n Row row = rows.get(0);\n m_reader.processDefaultCurrency(row);\n }\n }",
"private void writeExceptions(List<ProjectCalendar> records) throws IOException\n {\n for (ProjectCalendar record : records)\n {\n if (!record.getCalendarExceptions().isEmpty())\n {\n // Need to move HOLI up here and get 15 exceptions per line as per USACE spec.\n // for now, we'll write one line for each calendar exception, hope there aren't too many\n //\n // changing this would be a serious upgrade, too much coding to do today....\n for (ProjectCalendarException ex : record.getCalendarExceptions())\n {\n writeCalendarException(record, ex);\n }\n }\n m_eventManager.fireCalendarWrittenEvent(record); // left here from MPX template, maybe not needed???\n }\n }",
"public Snackbar actionLabel(CharSequence actionButtonLabel) {\n mActionLabel = actionButtonLabel;\n if (snackbarAction != null) {\n snackbarAction.setText(mActionLabel);\n }\n return this;\n }"
] |
Get an exception reporting an unexpected end tag for an XML element.
@param reader the stream reader
@return the exception | [
"public static XMLStreamException unexpectedEndElement(final XMLExtendedStreamReader reader) {\n return ControllerLogger.ROOT_LOGGER.unexpectedEndElement(reader.getName(), reader.getLocation());\n }"
] | [
"@SuppressWarnings(\"WeakerAccess\")\n public TrackMetadata requestMetadataFrom(final CdjStatus status) {\n if (status.getTrackSourceSlot() == CdjStatus.TrackSourceSlot.NO_TRACK || status.getRekordboxId() == 0) {\n return null;\n }\n final DataReference track = new DataReference(status.getTrackSourcePlayer(), status.getTrackSourceSlot(),\n status.getRekordboxId());\n return requestMetadataFrom(track, status.getTrackType());\n }",
"static Artifact resolveConstrained(MavenProject project, String gav, Pattern versionRegex,\n ArtifactResolver resolver)\n throws VersionRangeResolutionException, ArtifactResolutionException {\n boolean latest = gav.endsWith(\":LATEST\");\n if (latest || gav.endsWith(\":RELEASE\")) {\n Artifact a = new DefaultArtifact(gav);\n\n if (latest) {\n versionRegex = versionRegex == null ? ANY : versionRegex;\n } else {\n versionRegex = versionRegex == null ? ANY_NON_SNAPSHOT : versionRegex;\n }\n\n String upTo = project.getGroupId().equals(a.getGroupId()) && project.getArtifactId().equals(a.getArtifactId())\n ? project.getVersion()\n : null;\n\n return resolver.resolveNewestMatching(gav, upTo, versionRegex, latest, latest);\n } else {\n String projectGav = getProjectArtifactCoordinates(project, null);\n Artifact ret = null;\n\n if (projectGav.equals(gav)) {\n ret = findProjectArtifact(project);\n }\n\n return ret == null ? resolver.resolveArtifact(gav) : ret;\n }\n }",
"private void executeBatch(int batchId, final RebalanceBatchPlan batchPlan) {\n final Cluster batchCurrentCluster = batchPlan.getCurrentCluster();\n final List<StoreDefinition> batchCurrentStoreDefs = batchPlan.getCurrentStoreDefs();\n final Cluster batchFinalCluster = batchPlan.getFinalCluster();\n final List<StoreDefinition> batchFinalStoreDefs = batchPlan.getFinalStoreDefs();\n\n try {\n final List<RebalanceTaskInfo> rebalanceTaskInfoList = batchPlan.getBatchPlan();\n\n if(rebalanceTaskInfoList.isEmpty()) {\n RebalanceUtils.printBatchLog(batchId, logger, \"Skipping batch \"\n + batchId + \" since it is empty.\");\n // Even though there is no rebalancing work to do, cluster\n // metadata must be updated so that the server is aware of the\n // new cluster xml.\n adminClient.rebalanceOps.rebalanceStateChange(batchCurrentCluster,\n batchFinalCluster,\n batchCurrentStoreDefs,\n batchFinalStoreDefs,\n rebalanceTaskInfoList,\n false,\n true,\n false,\n false,\n true);\n return;\n }\n\n RebalanceUtils.printBatchLog(batchId, logger, \"Starting batch \"\n + batchId + \".\");\n\n // Split the store definitions\n List<StoreDefinition> readOnlyStoreDefs = StoreDefinitionUtils.filterStores(batchFinalStoreDefs,\n true);\n List<StoreDefinition> readWriteStoreDefs = StoreDefinitionUtils.filterStores(batchFinalStoreDefs,\n false);\n boolean hasReadOnlyStores = readOnlyStoreDefs != null\n && readOnlyStoreDefs.size() > 0;\n boolean hasReadWriteStores = readWriteStoreDefs != null\n && readWriteStoreDefs.size() > 0;\n\n // STEP 1 - Cluster state change\n boolean finishedReadOnlyPhase = false;\n List<RebalanceTaskInfo> filteredRebalancePartitionPlanList = RebalanceUtils.filterTaskPlanWithStores(rebalanceTaskInfoList,\n readOnlyStoreDefs);\n\n rebalanceStateChange(batchId,\n batchCurrentCluster,\n batchCurrentStoreDefs,\n batchFinalCluster,\n batchFinalStoreDefs,\n filteredRebalancePartitionPlanList,\n hasReadOnlyStores,\n hasReadWriteStores,\n finishedReadOnlyPhase);\n\n // STEP 2 - Move RO data\n if(hasReadOnlyStores) {\n RebalanceBatchPlanProgressBar progressBar = batchPlan.getProgressBar(batchId);\n executeSubBatch(batchId,\n progressBar,\n batchCurrentCluster,\n batchCurrentStoreDefs,\n filteredRebalancePartitionPlanList,\n hasReadOnlyStores,\n hasReadWriteStores,\n finishedReadOnlyPhase);\n }\n\n // STEP 3 - Cluster change state\n finishedReadOnlyPhase = true;\n filteredRebalancePartitionPlanList = RebalanceUtils.filterTaskPlanWithStores(rebalanceTaskInfoList,\n readWriteStoreDefs);\n\n rebalanceStateChange(batchId,\n batchCurrentCluster,\n batchCurrentStoreDefs,\n batchFinalCluster,\n batchFinalStoreDefs,\n filteredRebalancePartitionPlanList,\n hasReadOnlyStores,\n hasReadWriteStores,\n finishedReadOnlyPhase);\n\n // STEP 4 - Move RW data\n if(hasReadWriteStores) {\n proxyPause();\n RebalanceBatchPlanProgressBar progressBar = batchPlan.getProgressBar(batchId);\n executeSubBatch(batchId,\n progressBar,\n batchCurrentCluster,\n batchCurrentStoreDefs,\n filteredRebalancePartitionPlanList,\n hasReadOnlyStores,\n hasReadWriteStores,\n finishedReadOnlyPhase);\n }\n\n RebalanceUtils.printBatchLog(batchId,\n logger,\n \"Successfully terminated batch \"\n + batchId + \".\");\n\n } catch(Exception e) {\n RebalanceUtils.printErrorLog(batchId, logger, \"Error in batch \"\n + batchId + \" - \" + e.getMessage(), e);\n throw new VoldemortException(\"Rebalance failed on batch \" + batchId,\n e);\n }\n }",
"public void setGlobal(int pathId, Boolean global) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + Constants.PATH_PROFILE_GLOBAL + \" = ? \" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setBoolean(1, global);\n statement.setInt(2, pathId);\n statement.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }",
"public double[] getScaleDenominators() {\n double[] dest = new double[this.scaleDenominators.length];\n System.arraycopy(this.scaleDenominators, 0, dest, 0, this.scaleDenominators.length);\n return dest;\n }",
"@Override\n public synchronized void start() {\n if (!started.getAndSet(true)) {\n finished.set(false);\n thread.start();\n }\n }",
"public void clear()\r\n {\r\n Class collClass = getCollectionClass();\r\n\r\n // ECER: assure we notify all objects being removed, \r\n // necessary for RemovalAwareCollections...\r\n if (IRemovalAwareCollection.class.isAssignableFrom(collClass))\r\n {\r\n getData().clear();\r\n }\r\n else\r\n {\r\n Collection coll;\r\n // BRJ: use an empty collection so isLoaded will return true\r\n // for non RemovalAwareCollections only !! \r\n try\r\n {\r\n coll = (Collection) collClass.newInstance();\r\n }\r\n catch (Exception e)\r\n {\r\n coll = new ArrayList();\r\n }\r\n\r\n setData(coll);\r\n }\r\n _size = 0;\r\n }",
"public static void setLocale(ProjectProperties properties, Locale locale)\n {\n properties.setMpxDelimiter(LocaleData.getChar(locale, LocaleData.FILE_DELIMITER));\n properties.setMpxProgramName(LocaleData.getString(locale, LocaleData.PROGRAM_NAME));\n properties.setMpxCodePage((CodePage) LocaleData.getObject(locale, LocaleData.CODE_PAGE));\n\n properties.setCurrencySymbol(LocaleData.getString(locale, LocaleData.CURRENCY_SYMBOL));\n properties.setSymbolPosition((CurrencySymbolPosition) LocaleData.getObject(locale, LocaleData.CURRENCY_SYMBOL_POSITION));\n properties.setCurrencyDigits(LocaleData.getInteger(locale, LocaleData.CURRENCY_DIGITS));\n properties.setThousandsSeparator(LocaleData.getChar(locale, LocaleData.CURRENCY_THOUSANDS_SEPARATOR));\n properties.setDecimalSeparator(LocaleData.getChar(locale, LocaleData.CURRENCY_DECIMAL_SEPARATOR));\n\n properties.setDateOrder((DateOrder) LocaleData.getObject(locale, LocaleData.DATE_ORDER));\n properties.setTimeFormat((ProjectTimeFormat) LocaleData.getObject(locale, LocaleData.TIME_FORMAT));\n properties.setDefaultStartTime(DateHelper.getTimeFromMinutesPastMidnight(LocaleData.getInteger(locale, LocaleData.DEFAULT_START_TIME)));\n properties.setDateSeparator(LocaleData.getChar(locale, LocaleData.DATE_SEPARATOR));\n properties.setTimeSeparator(LocaleData.getChar(locale, LocaleData.TIME_SEPARATOR));\n properties.setAMText(LocaleData.getString(locale, LocaleData.AM_TEXT));\n properties.setPMText(LocaleData.getString(locale, LocaleData.PM_TEXT));\n properties.setDateFormat((ProjectDateFormat) LocaleData.getObject(locale, LocaleData.DATE_FORMAT));\n properties.setBarTextDateFormat((ProjectDateFormat) LocaleData.getObject(locale, LocaleData.DATE_FORMAT));\n }",
"protected Violation createViolation(Integer lineNumber, String sourceLine, String message) {\n Violation violation = new Violation();\n violation.setRule(this);\n violation.setSourceLine(sourceLine);\n violation.setLineNumber(lineNumber);\n violation.setMessage(message);\n return violation;\n }"
] |
Add a new server mapping to current profile
@param sourceHost source hostname
@param destinationHost destination hostname
@param hostHeader host header
@return ServerRedirect | [
"public ServerRedirect addServerMapping(String sourceHost, String destinationHost, String hostHeader) {\n JSONObject response = null;\n\n ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();\n params.add(new BasicNameValuePair(\"srcUrl\", sourceHost));\n params.add(new BasicNameValuePair(\"destUrl\", destinationHost));\n params.add(new BasicNameValuePair(\"profileIdentifier\", this._profileName));\n if (hostHeader != null) {\n params.add(new BasicNameValuePair(\"hostHeader\", hostHeader));\n }\n\n try {\n BasicNameValuePair paramArray[] = new BasicNameValuePair[params.size()];\n params.toArray(paramArray);\n response = new JSONObject(doPost(BASE_SERVER, paramArray));\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n return getServerRedirectFromJSON(response);\n }"
] | [
"public static systemcore get(nitro_service service) throws Exception{\n\t\tsystemcore obj = new systemcore();\n\t\tsystemcore[] response = (systemcore[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public Object lookup(Identity oid)\r\n {\r\n Object ret = null;\r\n if (oid != null)\r\n {\r\n ObjectCache cache = getCache(oid, null, METHOD_LOOKUP);\r\n if (cache != null)\r\n {\r\n ret = cache.lookup(oid);\r\n }\r\n }\r\n return ret;\r\n }",
"public synchronized void shutdown() {\n checkIsRunning();\n try {\n beanManager().fireEvent(new ContainerBeforeShutdown(id), BeforeDestroyed.Literal.APPLICATION);\n } finally {\n discard(id);\n // Destroy all the dependent beans correctly\n creationalContext.release();\n beanManager().fireEvent(new ContainerShutdown(id), Destroyed.Literal.APPLICATION);\n bootstrap.shutdown();\n WeldSELogger.LOG.weldContainerShutdown(id);\n }\n }",
"public static Info neg(final Variable A, ManagerTempVariables manager) {\n Info ret = new Info();\n\n if( A instanceof VariableInteger ) {\n final VariableInteger output = manager.createInteger();\n ret.output = output;\n ret.op = new Operation(\"neg-i\") {\n @Override\n public void process() {\n output.value = -((VariableInteger)A).value;\n }\n };\n } else if( A instanceof VariableScalar ) {\n final VariableDouble output = manager.createDouble();\n ret.output = output;\n ret.op = new Operation(\"neg-s\") {\n @Override\n public void process() {\n output.value = -((VariableScalar)A).getDouble();\n }\n };\n } else if( A instanceof VariableMatrix ) {\n final VariableMatrix output = manager.createMatrix();\n ret.output = output;\n ret.op = new Operation(\"neg-m\") {\n @Override\n public void process() {\n DMatrixRMaj a = ((VariableMatrix)A).matrix;\n output.matrix.reshape(a.numRows, a.numCols);\n CommonOps_DDRM.changeSign(a, output.matrix);\n }\n };\n } else {\n throw new RuntimeException(\"Unsupported variable \"+A);\n }\n\n return ret;\n }",
"static String findNonProgressingOp(Resource resource, boolean forServer, long timeout) throws OperationFailedException {\n\n Resource.ResourceEntry nonProgressing = null;\n for (Resource.ResourceEntry child : resource.getChildren(ACTIVE_OPERATION)) {\n ModelNode model = child.getModel();\n if (model.get(EXCLUSIVE_RUNNING_TIME).asLong() > timeout) {\n nonProgressing = child;\n ControllerLogger.MGMT_OP_LOGGER.tracef(\"non-progressing op: %s\", nonProgressing.getModel());\n break;\n }\n }\n if (nonProgressing != null && !forServer) {\n // WFCORE-263\n // See if the op is non-progressing because it's the HC op waiting for commit\n // from the DC while other ops (i.e. ops proxied to our servers) associated\n // with the same domain-uuid are not completing\n ModelNode model = nonProgressing.getModel();\n if (model.get(DOMAIN_ROLLOUT).asBoolean()\n && OperationContext.ExecutionStatus.COMPLETING.toString().equals(model.get(EXECUTION_STATUS).asString())\n && model.hasDefined(DOMAIN_UUID)) {\n ControllerLogger.MGMT_OP_LOGGER.trace(\"Potential domain rollout issue\");\n String domainUUID = model.get(DOMAIN_UUID).asString();\n\n Set<String> relatedIds = null;\n List<Resource.ResourceEntry> relatedExecutingOps = null;\n for (Resource.ResourceEntry activeOp : resource.getChildren(ACTIVE_OPERATION)) {\n if (nonProgressing.getName().equals(activeOp.getName())) {\n continue; // ignore self\n }\n ModelNode opModel = activeOp.getModel();\n if (opModel.hasDefined(DOMAIN_UUID) && domainUUID.equals(opModel.get(DOMAIN_UUID).asString())\n && opModel.get(RUNNING_TIME).asLong() > timeout) {\n if (relatedIds == null) {\n relatedIds = new TreeSet<String>(); // order these as an aid to unit testing\n }\n relatedIds.add(activeOp.getName());\n\n // If the op is ExecutionStatus.EXECUTING that means it's still EXECUTING on the\n // server or a prepare message got lost. It would be COMPLETING if the server\n // had sent a prepare message, as that would result in ProxyStepHandler calling completeStep\n if (OperationContext.ExecutionStatus.EXECUTING.toString().equals(opModel.get(EXECUTION_STATUS).asString())) {\n if (relatedExecutingOps == null) {\n relatedExecutingOps = new ArrayList<Resource.ResourceEntry>();\n }\n relatedExecutingOps.add(activeOp);\n ControllerLogger.MGMT_OP_LOGGER.tracef(\"Related executing: %s\", opModel);\n } else ControllerLogger.MGMT_OP_LOGGER.tracef(\"Related non-executing: %s\", opModel);\n } else ControllerLogger.MGMT_OP_LOGGER.tracef(\"unrelated: %s\", opModel);\n }\n\n if (relatedIds != null) {\n // There are other ops associated with this domain-uuid that are also not completing\n // in the desired time, so we can't treat the one holding the lock as the problem.\n if (relatedExecutingOps != null && relatedExecutingOps.size() == 1) {\n // There's a single related op that's executing for too long. So we can report that one.\n // Note that it's possible that the same problem exists on other hosts as well\n // and that this cancellation will not resolve the overall problem. But, we only\n // get here on a slave HC and if the user is invoking this on a slave and not the\n // master, we'll assume they have a reason for doing that and want us to treat this\n // as a problem on this particular host.\n nonProgressing = relatedExecutingOps.get(0);\n } else {\n // Fail and provide a useful failure message.\n throw DomainManagementLogger.ROOT_LOGGER.domainRolloutNotProgressing(nonProgressing.getName(),\n timeout, domainUUID, relatedIds);\n }\n }\n }\n }\n\n return nonProgressing == null ? null : nonProgressing.getName();\n }",
"private static LogPriorType intToType(int intPrior) {\r\n LogPriorType[] values = LogPriorType.values();\r\n for (LogPriorType val : values) {\r\n if (val.ordinal() == intPrior) {\r\n return val;\r\n }\r\n }\r\n throw new IllegalArgumentException(intPrior + \" is not a legal LogPrior.\");\r\n }",
"private Double zeroIsNull(Double value)\n {\n if (value != null && value.doubleValue() == 0)\n {\n value = null;\n }\n return value;\n }",
"public final SimpleFeatureCollection autoTreat(final Template template, final String features)\n throws IOException {\n SimpleFeatureCollection featuresCollection = treatStringAsURL(template, features);\n if (featuresCollection == null) {\n featuresCollection = treatStringAsGeoJson(features);\n }\n return featuresCollection;\n }",
"private ProjectFile handleDatabaseInDirectory(File directory) throws Exception\n {\n byte[] buffer = new byte[BUFFER_SIZE];\n File[] files = directory.listFiles();\n if (files != null)\n {\n for (File file : files)\n {\n if (file.isDirectory())\n {\n continue;\n }\n\n FileInputStream fis = new FileInputStream(file);\n int bytesRead = fis.read(buffer);\n fis.close();\n\n //\n // If the file is smaller than the buffer we are peeking into,\n // it's probably not a valid schedule file.\n //\n if (bytesRead != BUFFER_SIZE)\n {\n continue;\n }\n\n if (matchesFingerprint(buffer, BTRIEVE_FINGERPRINT))\n {\n return handleP3BtrieveDatabase(directory);\n }\n\n if (matchesFingerprint(buffer, STW_FINGERPRINT))\n {\n return handleSureTrakDatabase(directory);\n }\n }\n }\n return null;\n }"
] |
Convert an object to a set of maps.
@param mapper the object mapper
@param source the source object
@return set | [
"public static Set<Map<String, Object>> setify(ObjectMapper mapper, Object source) {\n return (Set<Map<String, Object>>) collectify(mapper, source, Set.class);\n }"
] | [
"public static sslpolicy_lbvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tsslpolicy_lbvserver_binding obj = new sslpolicy_lbvserver_binding();\n\t\tobj.set_name(name);\n\t\tsslpolicy_lbvserver_binding response[] = (sslpolicy_lbvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void wrapSetterMethod(ClassNode classNode, boolean bindable, String propertyName) {\r\n String getterName = \"get\" + MetaClassHelper.capitalize(propertyName);\r\n MethodNode setter = classNode.getSetterMethod(\"set\" + MetaClassHelper.capitalize(propertyName));\r\n\r\n if (setter != null) {\r\n // Get the existing code block\r\n Statement code = setter.getCode();\r\n\r\n Expression oldValue = varX(\"$oldValue\");\r\n Expression newValue = varX(\"$newValue\");\r\n Expression proposedValue = varX(setter.getParameters()[0].getName());\r\n BlockStatement block = new BlockStatement();\r\n\r\n // create a local variable to hold the old value from the getter\r\n block.addStatement(declS(oldValue, callThisX(getterName)));\r\n\r\n // add the fireVetoableChange method call\r\n block.addStatement(stmt(callThisX(\"fireVetoableChange\", args(\r\n constX(propertyName), oldValue, proposedValue))));\r\n\r\n // call the existing block, which will presumably set the value properly\r\n block.addStatement(code);\r\n\r\n if (bindable) {\r\n // get the new value to emit in the event\r\n block.addStatement(declS(newValue, callThisX(getterName)));\r\n\r\n // add the firePropertyChange method call\r\n block.addStatement(stmt(callThisX(\"firePropertyChange\", args(constX(propertyName), oldValue, newValue))));\r\n }\r\n\r\n // replace the existing code block with our new one\r\n setter.setCode(block);\r\n }\r\n }",
"private String addIndexInputToList(String name, IndexInput in,\n String postingsFormatName) throws IOException {\n if (indexInputList.get(name) != null) {\n indexInputList.get(name).close();\n }\n if (in != null) {\n String localPostingsFormatName = postingsFormatName;\n if (localPostingsFormatName == null) {\n localPostingsFormatName = in.readString();\n } else if (!in.readString().equals(localPostingsFormatName)) {\n throw new IOException(\"delegate codec \" + name + \" doesn't equal \"\n + localPostingsFormatName);\n }\n indexInputList.put(name, in);\n indexInputOffsetList.put(name, in.getFilePointer());\n return localPostingsFormatName;\n } else {\n log.debug(\"no \" + name + \" registered\");\n return null;\n }\n }",
"public static void printDocumentation() {\n\t\tSystem.out\n\t\t\t\t.println(\"********************************************************************\");\n\t\tSystem.out.println(\"*** Wikidata Toolkit: GenderRatioProcessor\");\n\t\tSystem.out.println(\"*** \");\n\t\tSystem.out\n\t\t\t\t.println(\"*** This program will download and process dumps from Wikidata.\");\n\t\tSystem.out\n\t\t\t\t.println(\"*** It will compute the numbers of articles about humans across\");\n\t\tSystem.out\n\t\t\t\t.println(\"*** Wikimedia projects, and in particular it will count the articles\");\n\t\tSystem.out\n\t\t\t\t.println(\"*** for each sex/gender. Results will be stored in a CSV file.\");\n\t\tSystem.out.println(\"*** See source code for further details.\");\n\t\tSystem.out\n\t\t\t\t.println(\"********************************************************************\");\n\t}",
"protected long getUniqueLong(FieldDescriptor field) throws SequenceManagerException\r\n {\r\n boolean needsCommit = false;\r\n long result = 0;\r\n /*\r\n arminw:\r\n use the associated broker instance, check if broker was in tx or\r\n we need to commit used connection.\r\n */\r\n PersistenceBroker targetBroker = getBrokerForClass();\r\n if(!targetBroker.isInTransaction())\r\n {\r\n targetBroker.beginTransaction();\r\n needsCommit = true;\r\n }\r\n try\r\n {\r\n // lookup sequence name\r\n String sequenceName = calculateSequenceName(field);\r\n try\r\n {\r\n result = buildNextSequence(targetBroker, field.getClassDescriptor(), sequenceName);\r\n /*\r\n if 0 was returned we assume that the stored procedure\r\n did not work properly.\r\n */\r\n if (result == 0)\r\n {\r\n throw new SequenceManagerException(\"No incremented value retrieved\");\r\n }\r\n }\r\n catch (Exception e)\r\n {\r\n // maybe the sequence was not created\r\n log.info(\"Could not grab next key, message was \" + e.getMessage() +\r\n \" - try to write a new sequence entry to database\");\r\n try\r\n {\r\n // on create, make sure to get the max key for the table first\r\n long maxKey = SequenceManagerHelper.getMaxForExtent(targetBroker, field);\r\n createSequence(targetBroker, field, sequenceName, maxKey);\r\n }\r\n catch (Exception e1)\r\n {\r\n String eol = SystemUtils.LINE_SEPARATOR;\r\n throw new SequenceManagerException(eol + \"Could not grab next id, failed with \" + eol +\r\n e.getMessage() + eol + \"Creation of new sequence failed with \" +\r\n eol + e1.getMessage() + eol, e1);\r\n }\r\n try\r\n {\r\n result = buildNextSequence(targetBroker, field.getClassDescriptor(), sequenceName);\r\n }\r\n catch (Exception e1)\r\n {\r\n throw new SequenceManagerException(\"Could not grab next id although a sequence seems to exist\", e);\r\n }\r\n }\r\n }\r\n finally\r\n {\r\n if(targetBroker != null && needsCommit)\r\n {\r\n targetBroker.commitTransaction();\r\n }\r\n }\r\n return result;\r\n }",
"public void addClass(ClassDescriptorDef classDef)\r\n {\r\n classDef.setOwner(this);\r\n // Regardless of the format of the class name, we're using the fully qualified format\r\n // This is safe because of the package & class naming constraints of the Java language\r\n _classDefs.put(classDef.getQualifiedName(), classDef);\r\n }",
"public static Type getDeclaredBeanType(Class<?> clazz) {\n Type[] actualTypeArguments = Reflections.getActualTypeArguments(clazz);\n if (actualTypeArguments.length == 1) {\n return actualTypeArguments[0];\n } else {\n return null;\n }\n }",
"public static List<String> getDefaultConversionProviderChain(){\n List<String> defaultChain = getMonetaryConversionsSpi()\n .getDefaultProviderChain();\n Objects.requireNonNull(defaultChain, \"No default provider chain provided by SPI: \" +\n getMonetaryConversionsSpi().getClass().getName());\n return defaultChain;\n }",
"public PartialCollection<BoxItem.Info> getChildrenRange(long offset, long limit, String... fields) {\n QueryStringBuilder builder = new QueryStringBuilder()\n .appendParam(\"limit\", limit)\n .appendParam(\"offset\", offset);\n\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields).toString();\n }\n\n URL url = GET_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), builder.toString(), getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n String totalCountString = responseJSON.get(\"total_count\").toString();\n long fullSize = Double.valueOf(totalCountString).longValue();\n PartialCollection<BoxItem.Info> children = new PartialCollection<BoxItem.Info>(offset, limit, fullSize);\n JsonArray jsonArray = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : jsonArray) {\n JsonObject jsonObject = value.asObject();\n BoxItem.Info parsedItemInfo = (BoxItem.Info) BoxResource.parseInfo(this.getAPI(), jsonObject);\n if (parsedItemInfo != null) {\n children.add(parsedItemInfo);\n }\n }\n return children;\n }"
] |
Specify the address of the SOCKS proxy the connection should
use.
<p>Read the <a href="http://java.sun.com/javase/6/docs/technotes/guides/net/proxies.html">
Java Networking and Proxies</a> guide to understand the
proxies complexity.
<p>Be aware that this method only handles SOCKS proxies, not
HTTPS proxies. Use {@link #withProxy(Proxy)} instead.
@param host the hostname of the SOCKS proxy
@param port the port of the SOCKS proxy server
@return this | [
"public ApnsServiceBuilder withSocksProxy(String host, int port) {\n Proxy proxy = new Proxy(Proxy.Type.SOCKS,\n new InetSocketAddress(host, port));\n return withProxy(proxy);\n }"
] | [
"protected TableFontStyle getColumnFontStyle(byte[] data, int offset, Map<Integer, FontBase> fontBases)\n {\n int uniqueID = MPPUtility.getInt(data, offset);\n FieldType fieldType = MPPTaskField.getInstance(MPPUtility.getShort(data, offset + 4));\n Integer index = Integer.valueOf(MPPUtility.getByte(data, offset + 8));\n int style = MPPUtility.getByte(data, offset + 9);\n ColorType color = ColorType.getInstance(MPPUtility.getByte(data, offset + 10));\n int change = MPPUtility.getByte(data, offset + 12);\n\n FontBase fontBase = fontBases.get(index);\n\n boolean bold = ((style & 0x01) != 0);\n boolean italic = ((style & 0x02) != 0);\n boolean underline = ((style & 0x04) != 0);\n\n boolean boldChanged = ((change & 0x01) != 0);\n boolean underlineChanged = ((change & 0x02) != 0);\n boolean italicChanged = ((change & 0x04) != 0);\n boolean colorChanged = ((change & 0x08) != 0);\n boolean fontChanged = ((change & 0x10) != 0);\n boolean backgroundColorChanged = (uniqueID == -1);\n boolean backgroundPatternChanged = (uniqueID == -1);\n\n return (new TableFontStyle(uniqueID, fieldType, fontBase, italic, bold, underline, false, color.getColor(), Color.BLACK, BackgroundPattern.TRANSPARENT, italicChanged, boldChanged, underlineChanged, false, colorChanged, fontChanged, backgroundColorChanged, backgroundPatternChanged));\n }",
"private List<ParameterConverter> methodReturningConverters(final Class<?> type) {\n final List<ParameterConverter> converters = new ArrayList<>();\n for (final Method method : type.getMethods()) {\n if (method.isAnnotationPresent(AsParameterConverter.class)) {\n converters.add(new MethodReturningConverter(method, type, this));\n }\n }\n return converters;\n }",
"protected void solveL(double[] vv) {\n\n int ii = 0;\n\n for( int i = 0; i < n; i++ ) {\n int ip = indx[i];\n double sumReal = vv[ip*2];\n double sumImg = vv[ip*2+1];\n\n vv[ip*2] = vv[i*2];\n vv[ip*2+1] = vv[i*2+1];\n\n if( ii != 0 ) {\n// for( int j = ii-1; j < i; j++ )\n// sum -= dataLU[i* n +j]*vv[j];\n int index = i*stride + (ii-1)*2;\n for( int j = ii-1; j < i; j++ ){\n double luReal = dataLU[index++];\n double luImg = dataLU[index++];\n\n double vvReal = vv[j*2];\n double vvImg = vv[j*2+1];\n\n sumReal -= luReal*vvReal - luImg*vvImg;\n sumImg -= luReal*vvImg + luImg*vvReal;\n }\n } else if( sumReal*sumReal + sumImg*sumImg != 0.0 ) {\n ii=i+1;\n }\n vv[i*2] = sumReal;\n vv[i*2+1] = sumImg;\n }\n }",
"public List<Ticket> checkTickets(Set<String> tickets) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_CHECK_TICKETS);\r\n\r\n StringBuffer sb = new StringBuffer();\r\n Iterator<String> it = tickets.iterator();\r\n while (it.hasNext()) {\r\n if (sb.length() > 0) {\r\n sb.append(\",\");\r\n }\r\n Object obj = it.next();\r\n if (obj instanceof Ticket) {\r\n sb.append(((Ticket) obj).getTicketId());\r\n } else {\r\n sb.append(obj);\r\n }\r\n }\r\n parameters.put(\"tickets\", sb.toString());\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n // <uploader>\r\n // <ticket id=\"128\" complete=\"1\" photoid=\"2995\" />\r\n // <ticket id=\"129\" complete=\"0\" />\r\n // <ticket id=\"130\" complete=\"2\" />\r\n // <ticket id=\"131\" invalid=\"1\" />\r\n // </uploader>\r\n\r\n List<Ticket> list = new ArrayList<Ticket>();\r\n Element uploaderElement = response.getPayload();\r\n NodeList ticketNodes = uploaderElement.getElementsByTagName(\"ticket\");\r\n int n = ticketNodes.getLength();\r\n for (int i = 0; i < n; i++) {\r\n Element ticketElement = (Element) ticketNodes.item(i);\r\n String id = ticketElement.getAttribute(\"id\");\r\n String complete = ticketElement.getAttribute(\"complete\");\r\n boolean invalid = \"1\".equals(ticketElement.getAttribute(\"invalid\"));\r\n String photoId = ticketElement.getAttribute(\"photoid\");\r\n Ticket info = new Ticket();\r\n info.setTicketId(id);\r\n info.setInvalid(invalid);\r\n info.setStatus(Integer.parseInt(complete));\r\n info.setPhotoId(photoId);\r\n list.add(info);\r\n }\r\n return list;\r\n }",
"ArgumentsBuilder param(String param, String value) {\n if (value != null) {\n args.add(param);\n args.add(value);\n }\n return this;\n }",
"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 }",
"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}",
"@SuppressWarnings(\"unchecked\")\n\tpublic <T extends StatementDocument> T nullEdit(T currentDocument)\n\t\t\tthrows IOException, MediaWikiApiErrorException {\n\t\tStatementUpdate statementUpdate = new StatementUpdate(currentDocument,\n\t\t\t\tCollections.<Statement>emptyList(), Collections.<Statement>emptyList());\n\t\tstatementUpdate.setGuidGenerator(guidGenerator);\n\t\t\n\t return (T) this.wbEditingAction.wbEditEntity(currentDocument\n\t\t\t\t.getEntityId().getId(), null, null, null, statementUpdate\n\t\t\t\t.getJsonUpdateString(), false, this.editAsBot, currentDocument\n\t\t\t\t.getRevisionId(), null);\n\t}",
"public static Mono<Void> waitForCompletion(CloudFoundryClient cloudFoundryClient, Duration completionTimeout, String jobId) {\n return requestJobV3(cloudFoundryClient, jobId)\n .filter(job -> JobState.PROCESSING != job.getState())\n .repeatWhenEmpty(exponentialBackOff(Duration.ofSeconds(1), Duration.ofSeconds(15), completionTimeout))\n .filter(job -> JobState.FAILED == job.getState())\n .flatMap(JobUtils::getError);\n }"
] |
Remove a license from an artifact
@param gavc String The artifact GAVC
@param licenseId String The license id to be removed. | [
"public void removeLicenseFromArtifact(final String gavc, final String licenseId) {\n final DbArtifact dbArtifact = getArtifact(gavc);\n\n //\n // The artifact may not have the exact string associated with it, but rather one\n // matching license regexp expression.\n //\n repositoryHandler.removeLicenseFromArtifact(dbArtifact, licenseId, licenseMatcher);\n }"
] | [
"public String get(final long index) {\n return doWithJedis(new JedisCallable<String>() {\n @Override\n public String call(Jedis jedis) {\n return jedis.lindex(getKey(), index);\n }\n });\n }",
"private Level getLogLevel() {\n return isQuiet() ? Level.OFF : isVerbose() ? Level.DEBUG : Level.INFO;\n }",
"public List<RoutableDestination<T>> getDestinations(String path) {\n\n String cleanPath = (path.endsWith(\"/\") && path.length() > 1)\n ? path.substring(0, path.length() - 1) : path;\n\n List<RoutableDestination<T>> result = new ArrayList<>();\n\n for (ImmutablePair<Pattern, RouteDestinationWithGroups> patternRoute : patternRouteList) {\n Map<String, String> groupNameValuesBuilder = new HashMap<>();\n Matcher matcher = patternRoute.getFirst().matcher(cleanPath);\n if (matcher.matches()) {\n int matchIndex = 1;\n for (String name : patternRoute.getSecond().getGroupNames()) {\n String value = matcher.group(matchIndex);\n groupNameValuesBuilder.put(name, value);\n matchIndex++;\n }\n result.add(new RoutableDestination<>(patternRoute.getSecond().getDestination(), groupNameValuesBuilder));\n }\n }\n return result;\n }",
"private Renderer getPrototypeByIndex(final int prototypeIndex) {\n Renderer prototypeSelected = null;\n int i = 0;\n for (Renderer prototype : prototypes) {\n if (i == prototypeIndex) {\n prototypeSelected = prototype;\n }\n i++;\n }\n return prototypeSelected;\n }",
"public double getProgressFromResponse(ResponseOnSingeRequest myResponse) {\n\n double progress = 0.0;\n try {\n\n if (myResponse == null || myResponse.isFailObtainResponse()) {\n return progress;\n }\n\n String responseBody = myResponse.getResponseBody();\n Pattern regex = Pattern.compile(progressRegex);\n Matcher matcher = regex.matcher(responseBody);\n if (matcher.matches()) {\n String progressStr = matcher.group(1);\n progress = Double.parseDouble(progressStr);\n }\n\n } catch (Exception t) {\n logger.error(\"fail \" + t);\n\n }\n\n return progress;\n }",
"public static dnspolicylabel get(nitro_service service, String labelname) throws Exception{\n\t\tdnspolicylabel obj = new dnspolicylabel();\n\t\tobj.set_labelname(labelname);\n\t\tdnspolicylabel response = (dnspolicylabel) obj.get_resource(service);\n\t\treturn response;\n\t}",
"static Shell createTerminalConsoleShell(String prompt, String appName,\n ShellCommandHandler mainHandler, InputStream input, OutputStream output) {\n try {\n PrintStream out = new PrintStream(output);\n\n // Build jline terminal\n jline.Terminal term = TerminalFactory.get();\n final ConsoleReader console = new ConsoleReader(input, output, term);\n console.setBellEnabled(true);\n console.setHistoryEnabled(true);\n\n // Build console\n BufferedReader in = new BufferedReader(new InputStreamReader(\n new ConsoleReaderInputStream(console)));\n\n ConsoleIO.PromptListener promptListener = new ConsoleIO.PromptListener() {\n @Override\n public boolean onPrompt(String prompt) {\n console.setPrompt(prompt);\n return true; // suppress normal prompt\n }\n };\n\n return createConsoleShell(prompt, appName, mainHandler, in, out, out, promptListener);\n } catch (Exception e) {\n // Failover: use default shell\n BufferedReader in = new BufferedReader(new InputStreamReader(input));\n PrintStream out = new PrintStream(output);\n\n return createConsoleShell(prompt, appName, mainHandler, in, out, out, null);\n }\n }",
"protected BoneCP createPool(BoneCPConfig config) {\r\n\t\ttry{\r\n\t\t\treturn new BoneCP(config);\r\n\t\t} catch (SQLException e) {\r\n\t\t\tthrow new HibernateException(e);\r\n\t\t}\r\n\t}",
"void endOfRunDb()\n {\n DbConn cnx = null;\n\n try\n {\n cnx = Helpers.getNewDbSession();\n\n // Done: put inside history & remove instance from queue.\n History.create(cnx, this.ji, this.resultStatus, endDate);\n jqmlogger.trace(\"An History was just created for job instance \" + this.ji.getId());\n cnx.runUpdate(\"ji_delete_by_id\", this.ji.getId());\n cnx.commit();\n }\n catch (RuntimeException e)\n {\n endBlockDbFailureAnalysis(e);\n }\n finally\n {\n Helpers.closeQuietly(cnx);\n }\n }"
] |
Configures the given annotation as a tag.
This is useful if you want to treat annotations as tags in JGiven that you cannot or want not
to be annotated with the {@link com.tngtech.jgiven.annotation.IsTag} annotation.
@param tagAnnotation the tag to be configured
@return a configuration builder for configuring the tag | [
"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 }"
] | [
"protected <E> E read(Supplier<E> sup) {\n try {\n this.lock.readLock().lock();\n return sup.get();\n } finally {\n this.lock.readLock().unlock();\n }\n }",
"public void addClass(ClassDescriptorDef classDef)\r\n {\r\n classDef.setOwner(this);\r\n // Regardless of the format of the class name, we're using the fully qualified format\r\n // This is safe because of the package & class naming constraints of the Java language\r\n _classDefs.put(classDef.getQualifiedName(), classDef);\r\n }",
"public static autoscalepolicy_binding get(nitro_service service, String name) throws Exception{\n\t\tautoscalepolicy_binding obj = new autoscalepolicy_binding();\n\t\tobj.set_name(name);\n\t\tautoscalepolicy_binding response = (autoscalepolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public IPAddressSeqRange intersect(IPAddressSeqRange other) {\n\t\tIPAddress otherLower = other.getLower();\n\t\tIPAddress otherUpper = other.getUpper();\n\t\tIPAddress lower = this.getLower();\n\t\tIPAddress upper = this.getUpper();\n\t\tif(compareLowValues(lower, otherLower) <= 0) {\n\t\t\tif(compareLowValues(upper, otherUpper) >= 0) {\n\t\t\t\treturn other;\n\t\t\t} else if(compareLowValues(upper, otherLower) < 0) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn create(otherLower, upper);\n\t\t} else if(compareLowValues(otherUpper, upper) >= 0) {\n\t\t\treturn this;\n\t\t} else if(compareLowValues(otherUpper, lower) < 0) {\n\t\t\treturn null;\n\t\t}\n\t\treturn create(lower, otherUpper);\n\t}",
"public static String encodeAuthority(String authority, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(authority, encoding, HierarchicalUriComponents.Type.AUTHORITY);\n\t}",
"public double[] getMoneynessAsOffsets() {\r\n\t\tDoubleStream moneyness = getGridNodesPerMoneyness().keySet().stream().mapToDouble(Integer::doubleValue);\r\n\t\tif(quotingConvention == QuotingConvention.PAYERVOLATILITYLOGNORMAL) {\r\n\t\t\tmoneyness = moneyness.map(new DoubleUnaryOperator() {\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic double applyAsDouble(double x) {\r\n\t\t\t\t\treturn x * 0.01;\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t} else if(quotingConvention == QuotingConvention.RECEIVERPRICE) {\r\n\t\t\tmoneyness = moneyness.map(new DoubleUnaryOperator() {\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic double applyAsDouble(double x) {\r\n\t\t\t\t\treturn - x * 0.0001;\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t} else {\r\n\t\t\tmoneyness = moneyness.map(new DoubleUnaryOperator() {\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic double applyAsDouble(double x) {\r\n\t\t\t\t\treturn x * 0.0001;\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t}\r\n\t\treturn moneyness.toArray();\r\n\t}",
"public void setColorRange(int firstIndex, int lastIndex, int color1, int color2) {\n\t\tfor (int i = firstIndex; i <= lastIndex; i++)\n\t\t\tmap[i] = ImageMath.mixColors((float)(i-firstIndex)/(lastIndex-firstIndex), color1, color2);\n\t}",
"public void stopDrag() {\n mPhysicsDragger.stopDrag();\n\n mPhysicsContext.runOnPhysicsThread(new Runnable() {\n @Override\n public void run() {\n if (mRigidBodyDragMe != null) {\n NativePhysics3DWorld.stopDrag(getNative());\n mRigidBodyDragMe = null;\n }\n }\n });\n }",
"public synchronized void shutdownTaskScheduler(){\n if (scheduler != null && !scheduler.isShutdown()) {\n scheduler.shutdown();\n logger.info(\"shutdowned the task scheduler. No longer accepting new tasks\");\n scheduler = null;\n }\n }"
] |
Signal that this thread will not log any more messages in the multithreaded
environment | [
"public static void finishThread(){\r\n //--Create Task\r\n final long threadId = Thread.currentThread().getId();\r\n Runnable finish = new Runnable(){\r\n public void run(){\r\n releaseThreadControl(threadId);\r\n }\r\n };\r\n //--Run Task\r\n if(isThreaded){\r\n //(case: multithreaded)\r\n attemptThreadControl( threadId, finish );\r\n } else {\r\n //(case: no threading)\r\n throw new IllegalStateException(\"finishThreads() called outside of threaded environment\");\r\n }\r\n }"
] | [
"public GVRAnimator start(int animIndex)\n {\n if ((animIndex < 0) || (animIndex >= mAnimations.size()))\n {\n throw new IndexOutOfBoundsException(\"Animation index out of bounds\");\n }\n GVRAnimator anim = mAnimations.get(animIndex);\n start(anim);\n return anim;\n }",
"public <V> V getObject(final String key, final Class<V> type) {\n final Object obj = this.values.get(key);\n return type.cast(obj);\n }",
"public ProteusApplication addDefaultRoutes(RoutingHandler router)\n {\n\n if (config.hasPath(\"health.statusPath\")) {\n try {\n final String statusPath = config.getString(\"health.statusPath\");\n\n router.add(Methods.GET, statusPath, (final HttpServerExchange exchange) ->\n {\n exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, MediaType.TEXT_PLAIN);\n exchange.getResponseSender().send(\"OK\");\n });\n\n this.registeredEndpoints.add(EndpointInfo.builder().withConsumes(\"*/*\").withProduces(\"text/plain\").withPathTemplate(statusPath).withControllerName(\"Internal\").withMethod(Methods.GET).build());\n\n } catch (Exception e) {\n log.error(\"Error adding health status route.\", e.getMessage());\n }\n }\n\n if (config.hasPath(\"application.favicon\")) {\n try {\n\n final ByteBuffer faviconImageBuffer;\n\n final File faviconFile = new File(config.getString(\"application.favicon\"));\n\n if (!faviconFile.exists()) {\n try (final InputStream stream = this.getClass().getResourceAsStream(config.getString(\"application.favicon\"))) {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n\n byte[] buffer = new byte[4096];\n int read = 0;\n while (read != -1) {\n read = stream.read(buffer);\n if (read > 0) {\n baos.write(buffer, 0, read);\n }\n }\n\n faviconImageBuffer = ByteBuffer.wrap(baos.toByteArray());\n }\n\n } else {\n try (final InputStream stream = Files.newInputStream(Paths.get(config.getString(\"application.favicon\")))) {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n\n byte[] buffer = new byte[4096];\n int read = 0;\n while (read != -1) {\n read = stream.read(buffer);\n if (read > 0) {\n baos.write(buffer, 0, read);\n }\n }\n\n faviconImageBuffer = ByteBuffer.wrap(baos.toByteArray());\n }\n }\n\n router.add(Methods.GET, \"favicon.ico\", (final HttpServerExchange exchange) ->\n {\n exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, io.sinistral.proteus.server.MediaType.IMAGE_X_ICON.toString());\n exchange.getResponseSender().send(faviconImageBuffer);\n });\n\n } catch (Exception e) {\n log.error(\"Error adding favicon route.\", e.getMessage());\n }\n }\n\n return this;\n }",
"private FormInput formInputMatchingNode(Node element) {\n\t\tNamedNodeMap attributes = element.getAttributes();\n\t\tIdentification id;\n\n\t\tif (attributes.getNamedItem(\"id\") != null\n\t\t\t\t&& formFillMode != FormFillMode.XPATH_TRAINING) {\n\t\t\tid = new Identification(Identification.How.id,\n\t\t\t\t\tattributes.getNamedItem(\"id\").getNodeValue());\n\t\t\tFormInput input = this.formInputs.get(id);\n\t\t\tif (input != null) {\n\t\t\t\treturn input;\n\t\t\t}\n\t\t}\n\n\t\tif (attributes.getNamedItem(\"name\") != null\n\t\t\t\t&& formFillMode != FormFillMode.XPATH_TRAINING) {\n\t\t\tid = new Identification(Identification.How.name,\n\t\t\t\t\tattributes.getNamedItem(\"name\").getNodeValue());\n\t\t\tFormInput input = this.formInputs.get(id);\n\t\t\tif (input != null) {\n\t\t\t\treturn input;\n\t\t\t}\n\t\t}\n\n\t\tString xpathExpr = XPathHelper.getXPathExpression(element);\n\t\tif (xpathExpr != null && !xpathExpr.equals(\"\")) {\n\t\t\tid = new Identification(Identification.How.xpath, xpathExpr);\n\t\t\tFormInput input = this.formInputs.get(id);\n\t\t\tif (input != null) {\n\t\t\t\treturn input;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}",
"@Override\n public void sendResponse(StoreStats performanceStats,\n boolean isFromLocalZone,\n long startTimeInMs) throws Exception {\n\n /*\n * Pay attention to the code below. Note that in this method we wrap a multiPart object with a mimeMessage.\n * However when writing to the outputStream we only send the multiPart object and not the entire\n * mimeMessage. This is intentional.\n *\n * In the earlier version of this code we used to create a multiPart object and just send that multiPart\n * across the wire.\n *\n * However, we later discovered that upon setting the content of a MimeBodyPart, JavaMail internally creates\n * a DataHandler object wrapping the object you passed in. The part's Content-Type header is not updated\n * immediately. In order to get the headers updated, one needs to to call MimeMessage.saveChanges() on the\n * enclosing message, which cascades down the MIME structure into a call to MimeBodyPart.updateHeaders()\n * on the body part. It's this updateHeaders call that transfers the content type from the\n * DataHandler to the part's MIME Content-Type header.\n *\n * To make sure that the Content-Type headers are being updated (without changing too much code), we decided\n * to wrap the multiPart in a mimeMessage, call mimeMessage.saveChanges() and then just send the multiPart.\n * This is to make sure multiPart's headers are updated accurately.\n */\n\n MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));\n MimeMultipart multiPart = new MimeMultipart();\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\n String base64Key = RestUtils.encodeVoldemortKey(key.get());\n String contentLocationKey = \"/\" + this.storeName + \"/\" + base64Key;\n\n for(Versioned<byte[]> versionedValue: versionedValues) {\n\n byte[] responseValue = versionedValue.getValue();\n\n VectorClock vectorClock = (VectorClock) versionedValue.getVersion();\n String eTag = RestUtils.getSerializedVectorClock(vectorClock);\n numVectorClockEntries += vectorClock.getVersionMap().size();\n\n // Create the individual body part for each versioned value of the\n // requested key\n MimeBodyPart body = new MimeBodyPart();\n try {\n // Add the right headers\n body.addHeader(CONTENT_TYPE, \"application/octet-stream\");\n body.addHeader(CONTENT_TRANSFER_ENCODING, \"binary\");\n body.addHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK, eTag);\n body.setContent(responseValue, \"application/octet-stream\");\n body.addHeader(RestMessageHeaders.CONTENT_LENGTH,\n Integer.toString(responseValue.length));\n\n multiPart.addBodyPart(body);\n } catch(MessagingException me) {\n logger.error(\"Exception while constructing body part\", me);\n outputStream.close();\n throw me;\n }\n\n }\n message.setContent(multiPart);\n message.saveChanges();\n try {\n multiPart.writeTo(outputStream);\n } catch(Exception e) {\n logger.error(\"Exception while writing multipart to output stream\", e);\n outputStream.close();\n throw e;\n }\n ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer();\n responseContent.writeBytes(outputStream.toByteArray());\n\n // Create the Response object\n HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);\n\n // Set the right headers\n response.setHeader(CONTENT_TYPE, \"multipart/binary\");\n response.setHeader(CONTENT_TRANSFER_ENCODING, \"binary\");\n response.setHeader(CONTENT_LOCATION, contentLocationKey);\n\n // Copy the data into the payload\n response.setContent(responseContent);\n response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());\n\n // Write the response to the Netty Channel\n if(logger.isDebugEnabled()) {\n String keyStr = RestUtils.getKeyHexString(this.key);\n debugLog(\"GET\",\n this.storeName,\n keyStr,\n startTimeInMs,\n System.currentTimeMillis(),\n numVectorClockEntries);\n }\n this.messageEvent.getChannel().write(response);\n\n if(performanceStats != null && isFromLocalZone) {\n recordStats(performanceStats, startTimeInMs, Tracked.GET);\n }\n\n outputStream.close();\n\n }",
"private TrackMetadata requestMetadataInternal(final DataReference track, final CdjStatus.TrackType trackType,\n final boolean failIfPassive) {\n // First check if we are using cached data for this request.\n MetadataCache cache = getMetadataCache(SlotReference.getSlotReference(track));\n if (cache != null && trackType == CdjStatus.TrackType.REKORDBOX) {\n return cache.getTrackMetadata(null, track);\n }\n\n // Then see if any registered metadata providers can offer it for us.\n final MediaDetails sourceDetails = getMediaDetailsFor(track.getSlotReference());\n if (sourceDetails != null) {\n final TrackMetadata provided = allMetadataProviders.getTrackMetadata(sourceDetails, track);\n if (provided != null) {\n return provided;\n }\n }\n\n // At this point, unless we are allowed to actively request the data, we are done. We can always actively\n // request tracks from rekordbox.\n if (passive.get() && failIfPassive && track.slot != CdjStatus.TrackSourceSlot.COLLECTION) {\n return null;\n }\n\n // Use the dbserver protocol implementation to request the metadata.\n ConnectionManager.ClientTask<TrackMetadata> task = new ConnectionManager.ClientTask<TrackMetadata>() {\n @Override\n public TrackMetadata useClient(Client client) throws Exception {\n return queryMetadata(track, trackType, client);\n }\n };\n\n try {\n return ConnectionManager.getInstance().invokeWithClientSession(track.player, task, \"requesting metadata\");\n } catch (Exception e) {\n logger.error(\"Problem requesting metadata, returning null\", e);\n }\n return null;\n }",
"public boolean setCurrentConfiguration(CmsGitConfiguration configuration) {\n\n if ((null != configuration) && configuration.isValid()) {\n m_currentConfiguration = configuration;\n return true;\n }\n return false;\n }",
"protected String getExecutableJar() throws IOException {\n Manifest manifest = new Manifest();\n manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, \"1.0\");\n manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, MAIN);\n manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, getClasspath());\n\n Path jar = createTempDirectory(\"exec\").resolve(\"generate.jar\");\n try (JarOutputStream output = new JarOutputStream(Files.newOutputStream(jar), manifest)) {\n output.putNextEntry(new JarEntry(\"allure.properties\"));\n Path allureConfig = PROPERTIES.getAllureConfig();\n if (Files.exists(allureConfig)) {\n byte[] bytes = Files.readAllBytes(allureConfig);\n output.write(bytes);\n }\n output.closeEntry();\n }\n\n return jar.toAbsolutePath().toString();\n }",
"public static autoscaleaction[] get(nitro_service service) throws Exception{\n\t\tautoscaleaction obj = new autoscaleaction();\n\t\tautoscaleaction[] response = (autoscaleaction[])obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
A document that is paused no longer has remote updates applied to it.
Any local updates to this document cause it to be resumed. An example of pausing a document
is when a conflict is being resolved for that document and the handler throws an exception.
This method allows you to resume sync for a document.
@param namespace namespace for the document
@param documentId the id of the document to resume syncing
@return true if successfully resumed, false if the document
could not be found or there was an error resuming | [
"boolean resumeSyncForDocument(\n final MongoNamespace namespace,\n final BsonValue documentId\n ) {\n if (namespace == null || documentId == null) {\n return false;\n }\n\n final NamespaceSynchronizationConfig namespaceSynchronizationConfig;\n final CoreDocumentSynchronizationConfig config;\n\n if ((namespaceSynchronizationConfig = syncConfig.getNamespaceConfig(namespace)) == null\n || (config = namespaceSynchronizationConfig.getSynchronizedDocument(documentId)) == null) {\n return false;\n }\n\n config.setPaused(false);\n return !config.isPaused();\n }"
] | [
"public void setCharTranslator(CharacterTranslator charTranslator) {\r\n\t\tif(charTranslator!=null){\r\n\t\t\tthis.charTranslator = charTranslator;\r\n\t\t\tthis.htmlElementTranslator = null;\r\n\t\t\tthis.targetTranslator = null;\r\n\t\t}\r\n\t}",
"protected void updateTables()\n {\n byte[] data = m_model.getData();\n int columns = m_model.getColumns();\n int rows = (data.length / columns) + 1;\n int offset = m_model.getOffset();\n\n String[][] hexData = new String[rows][columns];\n String[][] asciiData = new String[rows][columns];\n\n int row = 0;\n int column = 0;\n StringBuilder hexValue = new StringBuilder();\n for (int index = offset; index < data.length; index++)\n {\n int value = data[index];\n hexValue.setLength(0);\n hexValue.append(HEX_DIGITS[(value & 0xF0) >> 4]);\n hexValue.append(HEX_DIGITS[value & 0x0F]);\n\n char c = (char) value;\n if ((c > 200) || (c < 27))\n {\n c = ' ';\n }\n\n hexData[row][column] = hexValue.toString();\n asciiData[row][column] = Character.toString(c);\n\n ++column;\n if (column == columns)\n {\n column = 0;\n ++row;\n }\n }\n\n String[] columnHeadings = new String[columns];\n TableModel hexTableModel = new DefaultTableModel(hexData, columnHeadings)\n {\n @Override public boolean isCellEditable(int r, int c)\n {\n return false;\n }\n };\n\n TableModel asciiTableModel = new DefaultTableModel(asciiData, columnHeadings)\n {\n @Override public boolean isCellEditable(int r, int c)\n {\n return false;\n }\n };\n\n m_model.setSizeValueLabel(Integer.toString(data.length));\n m_model.setHexTableModel(hexTableModel);\n m_model.setAsciiTableModel(asciiTableModel);\n m_model.setCurrentSelectionIndex(0);\n m_model.setPreviousSelectionIndex(0);\n }",
"public static Module unserializeModule(final String module) throws IOException {\n final ObjectMapper mapper = new ObjectMapper();\n mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);\n return mapper.readValue(module, Module.class);\n }",
"public static <T> List<List<T>> getNGrams(List<T> items, int minSize, int maxSize) {\r\n List<List<T>> ngrams = new ArrayList<List<T>>();\r\n int listSize = items.size();\r\n for (int i = 0; i < listSize; ++i) {\r\n for (int ngramSize = minSize; ngramSize <= maxSize; ++ngramSize) {\r\n if (i + ngramSize <= listSize) {\r\n List<T> ngram = new ArrayList<T>();\r\n for (int j = i; j < i + ngramSize; ++j) {\r\n ngram.add(items.get(j));\r\n }\r\n ngrams.add(ngram);\r\n }\r\n }\r\n }\r\n return ngrams;\r\n }",
"public static Operation createDeployOperation(final DeploymentDescription deployment) {\n Assert.checkNotNullParam(\"deployment\", deployment);\n final CompositeOperationBuilder builder = CompositeOperationBuilder.create(true);\n addDeployOperationStep(builder, deployment);\n return builder.build();\n }",
"private void clearWaveforms(DeviceAnnouncement announcement) {\n final int player = announcement.getNumber();\n // Iterate over a copy to avoid concurrent modification issues\n for (DeckReference deck : new HashSet<DeckReference>(previewHotCache.keySet())) {\n if (deck.player == player) {\n previewHotCache.remove(deck);\n if (deck.hotCue == 0) {\n deliverWaveformPreviewUpdate(player, null); // Inform listeners that preview is gone.\n }\n }\n }\n // Again iterate over a copy to avoid concurrent modification issues\n for (DeckReference deck : new HashSet<DeckReference>(detailHotCache.keySet())) {\n if (deck.player == player) {\n detailHotCache.remove(deck);\n if (deck.hotCue == 0) {\n deliverWaveformDetailUpdate(player, null); // Inform listeners that detail is gone.\n }\n }\n }\n }",
"public static ModelNode validateRequest(CommandContext ctx, ModelNode request) throws CommandFormatException {\n\n final Set<String> keys = request.keys();\n if (keys.size() == 2) { // no props\n return null;\n }\n ModelNode outcome = (ModelNode) ctx.get(Scope.REQUEST, DESCRIPTION_RESPONSE);\n if (outcome == null) {\n outcome = retrieveDescription(ctx, request, true);\n if (outcome == null) {\n return null;\n } else {\n ctx.set(Scope.REQUEST, DESCRIPTION_RESPONSE, outcome);\n }\n }\n if(!outcome.has(Util.RESULT)) {\n throw new CommandFormatException(\"Failed to perform \" + Util.READ_OPERATION_DESCRIPTION + \" to validate the request: result is not available.\");\n }\n\n final String operationName = request.get(Util.OPERATION).asString();\n\n final ModelNode result = outcome.get(Util.RESULT);\n final Set<String> definedProps = result.hasDefined(Util.REQUEST_PROPERTIES) ? result.get(Util.REQUEST_PROPERTIES).keys() : Collections.emptySet();\n if(definedProps.isEmpty()) {\n if(!(keys.size() == 3 && keys.contains(Util.OPERATION_HEADERS))) {\n throw new CommandFormatException(\"Operation '\" + operationName + \"' does not expect any property.\");\n }\n } else {\n int skipped = 0;\n for(String prop : keys) {\n if(skipped < 2 && (prop.equals(Util.ADDRESS) || prop.equals(Util.OPERATION))) {\n ++skipped;\n continue;\n }\n if(!definedProps.contains(prop)) {\n if(!Util.OPERATION_HEADERS.equals(prop)) {\n throw new CommandFormatException(\"'\" + prop + \"' is not found among the supported properties: \" + definedProps);\n }\n }\n }\n }\n return outcome;\n }",
"public static PersistenceBroker createPersistenceBroker(String jcdAlias,\r\n String user,\r\n String password) throws PBFactoryException\r\n {\r\n return PersistenceBrokerFactoryFactory.instance().\r\n createPersistenceBroker(jcdAlias, user, password);\r\n }",
"private boolean removeRelation(List<Relation> relationList, Task targetTask, RelationType type, Duration lag)\n {\n boolean matchFound = false;\n for (Relation relation : relationList)\n {\n if (relation.getTargetTask() == targetTask)\n {\n if (relation.getType() == type && relation.getLag().compareTo(lag) == 0)\n {\n matchFound = relationList.remove(relation);\n break;\n }\n }\n }\n return matchFound;\n }"
] |
Checks if the provided artifactQuery is valid
@param artifactQuery ArtifactQuery
@throws WebApplicationException if the data is corrupted | [
"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 String prepareStatementString() throws SQLException {\n\t\tList<ArgumentHolder> argList = new ArrayList<ArgumentHolder>();\n\t\treturn buildStatementString(argList);\n\t}",
"public void disableAll(int profileId, String client_uuid) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.CLIENT_PROFILE_ID + \" = ?\" +\n \" AND \" + Constants.CLIENT_CLIENT_UUID + \" =? \"\n );\n statement.setInt(1, profileId);\n statement.setString(2, client_uuid);\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 static base_response delete(nitro_service client, dnstxtrec resource) throws Exception {\n\t\tdnstxtrec deleteresource = new dnstxtrec();\n\t\tdeleteresource.domain = resource.domain;\n\t\tdeleteresource.String = resource.String;\n\t\tdeleteresource.recordid = resource.recordid;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"protected List<Integer> cancelAllActiveOperations() {\n final List<Integer> operations = new ArrayList<Integer>();\n for(final ActiveOperationImpl<?, ?> activeOperation : activeRequests.values()) {\n activeOperation.asyncCancel(false);\n operations.add(activeOperation.getOperationId());\n }\n return operations;\n }",
"public static BoxCollaborationWhitelist.Info create(final BoxAPIConnection api, String domain,\n WhitelistDirection direction) {\n\n URL url = COLLABORATION_WHITELIST_ENTRIES_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, HttpMethod.POST);\n JsonObject requestJSON = new JsonObject()\n .add(\"domain\", domain)\n .add(\"direction\", direction.toString());\n\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n BoxCollaborationWhitelist domainWhitelist =\n new BoxCollaborationWhitelist(api, responseJSON.get(\"id\").asString());\n\n return domainWhitelist.new Info(responseJSON);\n }",
"public int compareTo(InternalFeature o) {\n\t\tif (null == o) {\n\t\t\treturn -1; // avoid NPE, put null objects at the end\n\t\t}\n\t\tif (null != styleDefinition && null != o.getStyleInfo()) {\n\t\t\tif (styleDefinition.getIndex() > o.getStyleInfo().getIndex()) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tif (styleDefinition.getIndex() < o.getStyleInfo().getIndex()) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t\treturn 0;\n\t}",
"private static void tryWritePreferenceOnDisk(Preferences preference) throws BackingStoreException {\n final String DUMMY_PROP=\"dummywrite\";\n instance.put(DUMMY_PROP,\"test\");\n instance.flush();\n instance.remove(DUMMY_PROP);\n instance.flush();\n }",
"@Override\n public DMatrixRMaj getV(DMatrixRMaj V , boolean transpose , boolean compact ) {\n V = handleV(V, transpose, compact,m,n,min);\n CommonOps_DDRM.setIdentity(V);\n\n// UBV.print();\n\n // todo the very first multiplication can be avoided by setting to the rank1update output\n for( int j = min-1; j >= 0; j-- ) {\n u[j+1] = 1;\n for( int i = j+2; i < n; i++ ) {\n u[i] = UBV.get(j,i);\n }\n if( transpose )\n QrHelperFunctions_DDRM.rank1UpdateMultL(V, u, gammasV[j], j + 1, j + 1, n);\n else\n QrHelperFunctions_DDRM.rank1UpdateMultR(V, u, gammasV[j], j + 1, j + 1, n, this.b);\n }\n\n return V;\n }",
"private Object getAttributeRecursively(Object feature, String name) throws LayerException {\n\t\tif (feature == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// Split up properties: the first and the rest.\n\t\tString[] properties = name.split(SEPARATOR_REGEXP, 2);\n\t\tObject tempFeature;\n\n\t\t// If the first property is the identifier:\n\t\tif (properties[0].equals(getFeatureInfo().getIdentifier().getName())) {\n\t\t\ttempFeature = getId(feature);\n\t\t} else {\n\t\t\tEntity entity = entityMapper.asEntity(feature);\n\t\t\tHibernateEntity child = (HibernateEntity) entity.getChild(properties[0]);\n\t\t\ttempFeature = child == null ? null : child.getObject();\n\t\t}\n\n\t\t// Detect if the first property is a collection (one-to-many):\n\t\tif (tempFeature instanceof Collection<?>) {\n\t\t\tCollection<?> features = (Collection<?>) tempFeature;\n\t\t\tObject[] values = new Object[features.size()];\n\t\t\tint count = 0;\n\t\t\tfor (Object value : features) {\n\t\t\t\tif (properties.length == 1) {\n\t\t\t\t\tvalues[count++] = value;\n\t\t\t\t} else {\n\t\t\t\t\tvalues[count++] = getAttributeRecursively(value, properties[1]);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn values;\n\t\t} else { // Else first property is not a collection (one-to-many):\n\t\t\tif (properties.length == 1 || tempFeature == null) {\n\t\t\t\treturn tempFeature;\n\t\t\t} else {\n\t\t\t\treturn getAttributeRecursively(tempFeature, properties[1]);\n\t\t\t}\n\t\t}\n\t}"
] |
Parses the buffer into body content
@param in ByteBuffer to parse
@return a ByteBuffer with the parsed body content. Buffer in may not be depleted. If more data is
needed, null is returned. In the case of content complete, an empty ByteBuffer is returned.
@throws BaseExceptions.ParserException | [
"protected final ByteBuffer parseContent(ByteBuffer in) throws BaseExceptions.ParserException {\n if (contentComplete()) {\n throw new BaseExceptions.InvalidState(\"content already complete: \" + _endOfContent);\n } else {\n switch (_endOfContent) {\n case UNKNOWN_CONTENT:\n // This makes sense only for response parsing. Requests must always have\n // either Content-Length or Transfer-Encoding\n\n _endOfContent = EndOfContent.EOF_CONTENT;\n _contentLength = Long.MAX_VALUE; // Its up to the user to limit a body size\n return parseContent(in);\n\n case CONTENT_LENGTH:\n case EOF_CONTENT:\n return nonChunkedContent(in);\n\n case CHUNKED_CONTENT:\n return chunkedContent(in);\n\n default:\n throw new BaseExceptions.InvalidState(\"not implemented: \" + _endOfContent);\n }\n }\n }"
] | [
"public double[] calculateDrift(ArrayList<T> tracks){\n\t\tdouble[] result = new double[3];\n\t\t\n\t\tdouble sumX =0;\n\t\tdouble sumY = 0;\n\t\tdouble sumZ = 0;\n\t\tint N=0;\n\t\tfor(int i = 0; i < tracks.size(); i++){\n\t\t\tT t = tracks.get(i);\n\t\t\tTrajectoryValidIndexTimelagIterator it = new TrajectoryValidIndexTimelagIterator(t,1);\n\t\n\t\t\t//for(int j = 1; j < t.size(); j++){\n\t\t\twhile(it.hasNext()) {\n\t\t\t\tint j = it.next();\n\t\t\t\tsumX += t.get(j+1).x - t.get(j).x;\n\t\t\t\tsumY += t.get(j+1).y - t.get(j).y;\n\t\t\t\tsumZ += t.get(j+1).z - t.get(j).z;\n\t\t\t\tN++;\n\t\t\t}\n\t\t}\n\t\tresult[0] = sumX/N;\n\t\tresult[1] = sumY/N;\n\t\tresult[2] = sumZ/N;\n\t\treturn result;\n\t}",
"public List<IssueCategory> getIssueCategories()\n {\n return this.issueCategories.values().stream()\n .sorted((category1, category2) -> category1.getPriority() - category2.getPriority())\n .collect(Collectors.toList());\n }",
"private float[] generateParticleTimeStamps(float totalTime)\n {\n float timeStamps[] = new float[mEmitRate * 2];\n for ( int i = 0; i < mEmitRate * 2; i +=2 )\n {\n timeStamps[i] = totalTime + mRandom.nextFloat();\n timeStamps[i + 1] = 0;\n }\n return timeStamps;\n }",
"protected String findPath(String start, String end) {\n if (start.equals(end)) {\n return start;\n } else {\n return findPath(start, parent.get(end)) + \" -> \" + end;\n }\n }",
"public Path getReportDirectory()\n {\n WindupConfigurationModel cfg = WindupConfigurationService.getConfigurationModel(getGraphContext());\n Path path = cfg.getOutputPath().asFile().toPath().resolve(REPORTS_DIR);\n createDirectoryIfNeeded(path);\n return path.toAbsolutePath();\n }",
"static ParsedHost validateHostImpl(HostName fromHost) throws HostNameException {\n\t\tfinal String str = fromHost.toString();\n\t\tHostNameParameters validationOptions = fromHost.getValidationOptions();\n\t\treturn validateHost(fromHost, str, validationOptions);\n\t}",
"private static List<Class<?>> getClassHierarchy(Class<?> clazz) {\n\t\tList<Class<?>> hierarchy = new ArrayList<Class<?>>( 4 );\n\n\t\tfor ( Class<?> current = clazz; current != null; current = current.getSuperclass() ) {\n\t\t\thierarchy.add( current );\n\t\t}\n\n\t\treturn hierarchy;\n\t}",
"@Subscribe\n @SuppressForbidden(\"legitimate printStackTrace().\")\n public void onSuiteResult(AggregatedSuiteResultEvent e) {\n try {\n if (jsonWriter == null)\n return;\n\n slaves.put(e.getSlave().id, e.getSlave());\n e.serialize(jsonWriter, outputStreams);\n } catch (Exception ex) {\n ex.printStackTrace();\n junit4.log(\"Error serializing to JSON file: \"\n + Throwables.getStackTraceAsString(ex), Project.MSG_WARN);\n if (jsonWriter != null) {\n try {\n jsonWriter.close();\n } catch (Throwable ignored) {\n // Ignore.\n } finally {\n jsonWriter = null;\n }\n }\n }\n }",
"public void setMonitoringService(org.talend.esb.sam.common.service.MonitoringService monitoringService) {\n this.monitoringService = monitoringService;\n }"
] |
Validate that the configuration is valid.
@return any validation errors. | [
"public final List<Throwable> validate() {\n List<Throwable> validationErrors = new ArrayList<>();\n this.accessAssertion.validate(validationErrors, this);\n\n for (String jdbcDriver: this.jdbcDrivers) {\n try {\n Class.forName(jdbcDriver);\n } catch (ClassNotFoundException e) {\n try {\n Configuration.class.getClassLoader().loadClass(jdbcDriver);\n } catch (ClassNotFoundException e1) {\n validationErrors.add(new ConfigurationException(String.format(\n \"Unable to load JDBC driver: %s ensure that the web application has the jar \" +\n \"on its classpath\", jdbcDriver)));\n }\n }\n }\n\n if (this.configurationFile == null) {\n validationErrors.add(new ConfigurationException(\"Configuration file is field on configuration \" +\n \"object is null\"));\n }\n if (this.templates.isEmpty()) {\n validationErrors.add(new ConfigurationException(\"There are not templates defined.\"));\n }\n for (Template template: this.templates.values()) {\n template.validate(validationErrors, this);\n }\n\n for (HttpProxy proxy: this.proxies) {\n proxy.validate(validationErrors, this);\n }\n\n try {\n ColorParser.toColor(this.opaqueTileErrorColor);\n } catch (RuntimeException ex) {\n validationErrors.add(new ConfigurationException(\"Cannot parse opaqueTileErrorColor\", ex));\n }\n\n try {\n ColorParser.toColor(this.transparentTileErrorColor);\n } catch (RuntimeException ex) {\n validationErrors.add(new ConfigurationException(\"Cannot parse transparentTileErrorColor\", ex));\n }\n\n if (smtp != null) {\n smtp.validate(validationErrors, this);\n }\n\n return validationErrors;\n }"
] | [
"public ResultSetAndStatement executeQuery(Query query, ClassDescriptor cld) throws PersistenceBrokerException\r\n {\r\n if (logger.isDebugEnabled())\r\n {\r\n logger.debug(\"executeQuery: \" + query);\r\n }\r\n /*\r\n\t\t * MBAIRD: we should create a scrollable resultset if the start at\r\n\t\t * index or end at index is set\r\n\t\t */\r\n boolean scrollable = ((query.getStartAtIndex() > Query.NO_START_AT_INDEX) || (query.getEndAtIndex() > Query.NO_END_AT_INDEX));\r\n /*\r\n\t\t * OR if the prefetching of relationships is being used.\r\n\t\t */\r\n if (query != null && query.getPrefetchedRelationships() != null && !query.getPrefetchedRelationships().isEmpty())\r\n {\r\n scrollable = true;\r\n }\r\n final StatementManagerIF sm = broker.serviceStatementManager();\r\n final SelectStatement sql = broker.serviceSqlGenerator().getPreparedSelectStatement(query, cld);\r\n PreparedStatement stmt = null;\r\n ResultSet rs = null;\r\n try\r\n {\r\n final int queryFetchSize = query.getFetchSize();\r\n final boolean isStoredProcedure = isStoredProcedure(sql.getStatement());\r\n stmt = sm.getPreparedStatement(cld, sql.getStatement() ,\r\n scrollable, queryFetchSize, isStoredProcedure);\r\n if (isStoredProcedure)\r\n {\r\n // Query implemented as a stored procedure, which must return a result set.\r\n // Query sytax is: { ?= call PROCEDURE_NAME(?,...,?)}\r\n getPlatform().registerOutResultSet((CallableStatement) stmt, 1);\r\n sm.bindStatement(stmt, query, cld, 2);\r\n\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"executeQuery: \" + stmt);\r\n\r\n stmt.execute();\r\n rs = (ResultSet) ((CallableStatement) stmt).getObject(1);\r\n }\r\n else\r\n {\r\n sm.bindStatement(stmt, query, cld, 1);\r\n\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"executeQuery: \" + stmt);\r\n\r\n rs = stmt.executeQuery();\r\n }\r\n\r\n return new ResultSetAndStatement(sm, stmt, rs, sql);\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n // release resources on exception\r\n sm.closeResources(stmt, rs);\r\n logger.error(\"PersistenceBrokerException during the execution of the query: \" + e.getMessage(), e);\r\n throw e;\r\n }\r\n catch (SQLException e)\r\n {\r\n // release resources on exception\r\n sm.closeResources(stmt, rs);\r\n throw ExceptionHelper.generateException(e, sql.getStatement(), null, logger, null);\r\n }\r\n }",
"public static Map<String, String> mapStringToMap(String map) {\r\n String[] m = map.split(\"[,;]\");\r\n Map<String, String> res = new HashMap<String, String>();\r\n for (String str : m) {\r\n int index = str.lastIndexOf('=');\r\n String key = str.substring(0, index);\r\n String val = str.substring(index + 1);\r\n res.put(key.trim(), val.trim());\r\n }\r\n return res;\r\n }",
"@SuppressWarnings(\"unchecked\")\n public <V3, M4, C, N, Q> V3 getUp(AiWrapperProvider<V3, M4, C, N, Q> \n wrapperProvider) {\n \n return (V3) m_up;\n }",
"private License getLicense(final String licenseId) {\n License result = null;\n final Set<DbLicense> matchingLicenses = licenseMatcher.getMatchingLicenses(licenseId);\n\n if (matchingLicenses.isEmpty()) {\n result = DataModelFactory.createLicense(\"#\" + licenseId + \"# (to be identified)\", NOT_IDENTIFIED_YET, NOT_IDENTIFIED_YET, NOT_IDENTIFIED_YET, NOT_IDENTIFIED_YET);\n result.setUnknown(true);\n } else {\n if (matchingLicenses.size() > 1 && LOG.isWarnEnabled()) {\n LOG.warn(String.format(\"%s matches multiple licenses %s. \" +\n \"Please run the report showing multiple matching on licenses\",\n licenseId, matchingLicenses.toString()));\n }\n result = mapper.getLicense(matchingLicenses.iterator().next());\n\n }\n\n return result;\n }",
"public static bridgetable[] get(nitro_service service) throws Exception{\n\t\tbridgetable obj = new bridgetable();\n\t\tbridgetable[] response = (bridgetable[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"@SuppressWarnings(\"unchecked\")\n public void setVars(final Map<String, ? extends Object> vars) {\n this.vars = (Map<String, Object>)vars;\n }",
"private static String wordShapeDigits(final String s) {\r\n char[] outChars = null;\r\n\r\n for (int i = 0; i < s.length(); i++) {\r\n char c = s.charAt(i);\r\n if (Character.isDigit(c)) {\r\n if (outChars == null) {\r\n outChars = s.toCharArray();\r\n }\r\n outChars[i] = '9';\r\n }\r\n }\r\n if (outChars == null) {\r\n // no digit found\r\n return s;\r\n } else {\r\n return new String(outChars);\r\n }\r\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 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}"
] |
Use this API to fetch cachepolicy_cacheglobal_binding resources of given name . | [
"public static cachepolicy_cacheglobal_binding[] get(nitro_service service, String policyname) throws Exception{\n\t\tcachepolicy_cacheglobal_binding obj = new cachepolicy_cacheglobal_binding();\n\t\tobj.set_policyname(policyname);\n\t\tcachepolicy_cacheglobal_binding response[] = (cachepolicy_cacheglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"public static dos_stats get(nitro_service service, options option) throws Exception{\n\t\tdos_stats obj = new dos_stats();\n\t\tdos_stats[] response = (dos_stats[])obj.stat_resources(service,option);\n\t\treturn response[0];\n\t}",
"private void writeCalendars(List<ProjectCalendar> records)\n {\n\n //\n // Write project calendars\n //\n for (ProjectCalendar record : records)\n {\n m_buffer.setLength(0);\n m_buffer.append(\"CLDR \");\n m_buffer.append(SDEFmethods.lset(record.getUniqueID().toString(), 2)); // 2 character used, USACE allows 1\n String workDays = SDEFmethods.workDays(record); // custom line, like NYYYYYN for a week\n m_buffer.append(SDEFmethods.lset(workDays, 8));\n m_buffer.append(SDEFmethods.lset(record.getName(), 30));\n m_writer.println(m_buffer);\n }\n }",
"private void writeCustomFields() throws IOException\n {\n m_writer.writeStartList(\"custom_fields\");\n for (CustomField field : m_projectFile.getCustomFields())\n {\n writeCustomField(field);\n }\n m_writer.writeEndList();\n }",
"public void setHomeAsUpIndicator(Drawable indicator) {\n if(!deviceSupportMultiPane()) {\n pulsante.setHomeAsUpIndicator(indicator);\n }\n else {\n actionBar.setHomeAsUpIndicator(indicator);\n }\n }",
"public static Integer parseInteger(String value) throws ParseException\n {\n Integer result = null;\n\n if (value.length() > 0 && value.indexOf(' ') == -1)\n {\n if (value.indexOf('.') == -1)\n {\n result = Integer.valueOf(value);\n }\n else\n {\n Number n = DatatypeConverter.parseDouble(value);\n result = Integer.valueOf(n.intValue());\n }\n }\n\n return result;\n }",
"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 }",
"public static appfwpolicylabel_stats get(nitro_service service, String labelname) throws Exception{\n\t\tappfwpolicylabel_stats obj = new appfwpolicylabel_stats();\n\t\tobj.set_labelname(labelname);\n\t\tappfwpolicylabel_stats response = (appfwpolicylabel_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"private void logError(LifecycleListener listener, Exception e) {\n LOGGER.error(\"Error for listener \" + listener.getClass(), e);\n }",
"protected float computeUniformPadding(final CacheDataSet cache) {\n float axisSize = getViewPortSize(getOrientationAxis());\n float totalPadding = axisSize - cache.getTotalSize();\n float uniformPadding = totalPadding > 0 && cache.count() > 1 ?\n totalPadding / (cache.count() - 1) : 0;\n return uniformPadding;\n }"
] |
Delete any log segments matching the given predicate function
@throws IOException | [
"List<LogSegment> markDeletedWhile(LogSegmentFilter filter) throws IOException {\n synchronized (lock) {\n List<LogSegment> view = segments.getView();\n List<LogSegment> deletable = new ArrayList<LogSegment>();\n for (LogSegment seg : view) {\n if (filter.filter(seg)) {\n deletable.add(seg);\n }\n }\n for (LogSegment seg : deletable) {\n seg.setDeleted(true);\n }\n int numToDelete = deletable.size();\n //\n // if we are deleting everything, create a new empty segment\n if (numToDelete == view.size()) {\n if (view.get(numToDelete - 1).size() > 0) {\n roll();\n } else {\n // If the last segment to be deleted is empty and we roll the log, the new segment will have the same\n // file name. So simply reuse the last segment and reset the modified time.\n view.get(numToDelete - 1).getFile().setLastModified(System.currentTimeMillis());\n numToDelete -= 1;\n }\n }\n return segments.trunc(numToDelete);\n }\n }"
] | [
"private void started(final ProcessorGraphNode processorGraphNode) {\n this.processorLock.lock();\n try {\n this.runningProcessors.put(processorGraphNode.getProcessor(), null);\n } finally {\n this.processorLock.unlock();\n }\n }",
"public void registerDatatype(Class<? extends GVRHybridObject> textureClass,\n AsyncLoaderFactory<? extends GVRHybridObject, ?> asyncLoaderFactory) {\n mFactories.put(textureClass, asyncLoaderFactory);\n }",
"int read(InputStream is, int contentLength) {\n if (is != null) {\n try {\n int capacity = (contentLength > 0) ? (contentLength + 4096) : 16384;\n ByteArrayOutputStream buffer = new ByteArrayOutputStream(capacity);\n int nRead;\n byte[] data = new byte[16384];\n while ((nRead = is.read(data, 0, data.length)) != -1) {\n buffer.write(data, 0, nRead);\n }\n buffer.flush();\n\n read(buffer.toByteArray());\n } catch (IOException e) {\n Logger.d(TAG, \"Error reading data from stream\", e);\n }\n } else {\n status = STATUS_OPEN_ERROR;\n }\n\n try {\n if (is != null) {\n is.close();\n }\n } catch (IOException e) {\n Logger.d(TAG, \"Error closing stream\", e);\n }\n\n return status;\n }",
"public static <T> T get(String key, Class<T> clz) {\n return (T)m().get(key);\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<Symmetry454Date> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<Symmetry454Date>) super.localDateTime(temporal);\n }",
"public static boolean canUseAsDelayedQueue(final Jedis jedis, final String key) {\n final String type = jedis.type(key);\n return (ZSET.equalsIgnoreCase(type) || NONE.equalsIgnoreCase(type));\n }",
"public static int cudnnOpTensor(\n cudnnHandle handle, \n cudnnOpTensorDescriptor opTensorDesc, \n Pointer alpha1, \n cudnnTensorDescriptor aDesc, \n Pointer A, \n Pointer alpha2, \n cudnnTensorDescriptor bDesc, \n Pointer B, \n Pointer beta, \n cudnnTensorDescriptor cDesc, \n Pointer C)\n {\n return checkResult(cudnnOpTensorNative(handle, opTensorDesc, alpha1, aDesc, A, alpha2, bDesc, B, beta, cDesc, C));\n }",
"public void addCell(TableLayoutCell cell) {\n GridBagConstraints constraints = cell.getConstraints();\n constraints.insets = new Insets(cellpadding, cellpadding, cellpadding, cellpadding);\n add(cell.getComponent(), constraints);\n }",
"@Override\n public void populateObject(ProcessedCommand<Command<CI>, CI> processedCommand, InvocationProviders invocationProviders,\n AeshContext aeshContext, CommandLineParser.Mode mode)\n throws CommandLineParserException, OptionValidatorException {\n if(processedCommand.parserExceptions().size() > 0 && mode == CommandLineParser.Mode.VALIDATE)\n throw processedCommand.parserExceptions().get(0);\n for(ProcessedOption option : processedCommand.getOptions()) {\n if(option.getValues() != null && option.getValues().size() > 0)\n option.injectValueIntoField(getObject(), invocationProviders, aeshContext,\n mode == CommandLineParser.Mode.VALIDATE );\n else if(option.getDefaultValues().size() > 0) {\n option.injectValueIntoField(getObject(), invocationProviders, aeshContext,\n mode == CommandLineParser.Mode.VALIDATE);\n }\n else if(option.getOptionType().equals(OptionType.GROUP) && option.getProperties().size() > 0)\n option.injectValueIntoField(getObject(), invocationProviders, aeshContext,\n mode == CommandLineParser.Mode.VALIDATE);\n else\n resetField(getObject(), option.getFieldName(), option.hasValue());\n }\n //arguments\n if(processedCommand.getArguments() != null &&\n (processedCommand.getArguments().getValues().size() > 0 || processedCommand.getArguments().getDefaultValues().size() > 0))\n processedCommand.getArguments().injectValueIntoField(getObject(), invocationProviders, aeshContext,\n mode == CommandLineParser.Mode.VALIDATE);\n else if(processedCommand.getArguments() != null)\n resetField(getObject(), processedCommand.getArguments().getFieldName(), true);\n //argument\n if(processedCommand.getArgument() != null &&\n (processedCommand.getArgument().getValues().size() > 0 || processedCommand.getArgument().getDefaultValues().size() > 0))\n processedCommand.getArgument().injectValueIntoField(getObject(), invocationProviders, aeshContext,\n mode == CommandLineParser.Mode.VALIDATE);\n else if(processedCommand.getArgument() != null)\n resetField(getObject(), processedCommand.getArgument().getFieldName(), true);\n }"
] |
Reads the given text stream and compressed its content.
@param stream The input stream
@return A byte array containing the GZIP-compressed content of the stream
@throws IOException If an error ocurred | [
"private byte[] readStreamCompressed(InputStream stream) throws IOException\r\n {\r\n ByteArrayOutputStream bao = new ByteArrayOutputStream();\r\n GZIPOutputStream gos = new GZIPOutputStream(bao);\r\n OutputStreamWriter output = new OutputStreamWriter(gos);\r\n BufferedReader input = new BufferedReader(new InputStreamReader(stream));\r\n String line;\r\n\r\n while ((line = input.readLine()) != null)\r\n {\r\n output.write(line);\r\n output.write('\\n');\r\n }\r\n input.close();\r\n stream.close();\r\n output.close();\r\n gos.close();\r\n bao.close();\r\n return bao.toByteArray();\r\n }"
] | [
"private static void listRelationships(ProjectFile file)\n {\n for (Task task : file.getTasks())\n {\n System.out.print(task.getID());\n System.out.print('\\t');\n System.out.print(task.getName());\n System.out.print('\\t');\n\n dumpRelationList(task.getPredecessors());\n System.out.print('\\t');\n dumpRelationList(task.getSuccessors());\n System.out.println();\n }\n }",
"private void rotatorPushRight2( int m , int offset)\n {\n double b11 = bulge;\n double b12 = diag[m+offset];\n\n computeRotator(b12,-b11);\n\n diag[m+offset] = b12*c-b11*s;\n\n if( m+offset<N-1) {\n double b22 = off[m+offset];\n off[m+offset] = b22*c;\n bulge = b22*s;\n }\n\n// SimpleMatrix Q = createQ(m,m+offset, c, s, true);\n// B=Q.mult(B);\n//\n// B.print();\n// printMatrix();\n// System.out.println(\" bulge = \"+bulge);\n// System.out.println();\n\n if( Ut != null ) {\n updateRotator(Ut,m,m+offset,c,s);\n\n// SimpleMatrix.wrap(Ut).mult(B).mult(SimpleMatrix.wrap(Vt).transpose()).print();\n// printMatrix();\n// System.out.println(\"bulge = \"+bulge);\n// System.out.println();\n }\n }",
"@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 void setMaxConnectionAge(long maxConnectionAge, TimeUnit timeUnit) {\n\t\tthis.maxConnectionAgeInSeconds = TimeUnit.SECONDS.convert(maxConnectionAge, timeUnit);\n\t}",
"protected I_CmsSearchConfigurationFacetField parseFieldFacet(final String pathPrefix) {\n\n try {\n final String field = parseMandatoryStringValue(pathPrefix + XML_ELEMENT_FACET_FIELD);\n final String name = parseOptionalStringValue(pathPrefix + XML_ELEMENT_FACET_NAME);\n final String label = parseOptionalStringValue(pathPrefix + XML_ELEMENT_FACET_LABEL);\n final Integer minCount = parseOptionalIntValue(pathPrefix + XML_ELEMENT_FACET_MINCOUNT);\n final Integer limit = parseOptionalIntValue(pathPrefix + XML_ELEMENT_FACET_LIMIT);\n final String prefix = parseOptionalStringValue(pathPrefix + XML_ELEMENT_FACET_PREFIX);\n final String sorder = parseOptionalStringValue(pathPrefix + XML_ELEMENT_FACET_ORDER);\n I_CmsSearchConfigurationFacet.SortOrder order;\n try {\n order = I_CmsSearchConfigurationFacet.SortOrder.valueOf(sorder);\n } catch (@SuppressWarnings(\"unused\") final Exception e) {\n order = null;\n }\n final String filterQueryModifier = parseOptionalStringValue(\n pathPrefix + XML_ELEMENT_FACET_FILTERQUERYMODIFIER);\n final Boolean isAndFacet = parseOptionalBooleanValue(pathPrefix + XML_ELEMENT_FACET_ISANDFACET);\n final List<String> preselection = parseOptionalStringValues(pathPrefix + XML_ELEMENT_FACET_PRESELECTION);\n final Boolean ignoreAllFacetFilters = parseOptionalBooleanValue(\n pathPrefix + XML_ELEMENT_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 ignoreAllFacetFilters);\n } catch (final Exception e) {\n LOG.error(\n Messages.get().getBundle().key(\n Messages.ERR_FIELD_FACET_MANDATORY_KEY_MISSING_1,\n XML_ELEMENT_FACET_FIELD),\n e);\n return null;\n }\n }",
"protected void processTaskBaseline(Row row)\n {\n Integer id = row.getInteger(\"TASK_UID\");\n Task task = m_project.getTaskByUniqueID(id);\n if (task != null)\n {\n int index = row.getInt(\"TB_BASE_NUM\");\n\n task.setBaselineDuration(index, MPDUtility.getAdjustedDuration(m_project, row.getInt(\"TB_BASE_DUR\"), MPDUtility.getDurationTimeUnits(row.getInt(\"TB_BASE_DUR_FMT\"))));\n task.setBaselineStart(index, row.getDate(\"TB_BASE_START\"));\n task.setBaselineFinish(index, row.getDate(\"TB_BASE_FINISH\"));\n task.setBaselineWork(index, row.getDuration(\"TB_BASE_WORK\"));\n task.setBaselineCost(index, row.getCurrency(\"TB_BASE_COST\"));\n }\n }",
"protected void getBatch(int batchSize){\r\n\r\n// if (numCalls == 0) {\r\n// for (int i = 0; i < 1538*\\15; i++) {\r\n// randGenerator.nextInt(this.dataDimension());\r\n// }\r\n// }\r\n// numCalls++;\r\n\r\n if (thisBatch == null || thisBatch.length != batchSize){\r\n thisBatch = new int[batchSize];\r\n }\r\n\r\n //-----------------------------\r\n //RANDOM WITH REPLACEMENT\r\n //-----------------------------\r\n if (sampleMethod.equals(SamplingMethod.RandomWithReplacement)){\r\n for(int i = 0; i<batchSize;i++){\r\n thisBatch[i] = randGenerator.nextInt(this.dataDimension()); //Just generate a random index\r\n// System.err.println(\"numCalls = \"+(numCalls++));\r\n }\r\n //-----------------------------\r\n //ORDERED\r\n //-----------------------------\r\n }else if(sampleMethod.equals(SamplingMethod.Ordered)){\r\n for(int i = 0; i<batchSize;i++){\r\n thisBatch[i] = (curElement + i) % this.dataDimension() ; //Take the next batchSize points in order\r\n }\r\n curElement = (curElement + batchSize) % this.dataDimension(); //watch out for overflow\r\n\r\n //-----------------------------\r\n //RANDOM WITHOUT REPLACEMENT\r\n //-----------------------------\r\n }else if(sampleMethod.equals(SamplingMethod.RandomWithoutReplacement)){\r\n //Declare the indices array if needed.\r\n if (allIndices == null || allIndices.size()!= this.dataDimension()){\r\n\r\n allIndices = new ArrayList<Integer>();\r\n for(int i=0;i<this.dataDimension();i++){\r\n allIndices.add(i);\r\n }\r\n Collections.shuffle(allIndices,randGenerator);\r\n }\r\n\r\n for(int i = 0; i<batchSize;i++){\r\n thisBatch[i] = allIndices.get((curElement + i) % allIndices.size()); //Grab the next batchSize indices\r\n }\r\n\r\n if (curElement + batchSize > this.dataDimension()){\r\n Collections.shuffle(Arrays.asList(allIndices),randGenerator); //Shuffle if we got to the end of the list\r\n }\r\n\r\n //watch out for overflow\r\n curElement = (curElement + batchSize) % allIndices.size(); //Rollover\r\n\r\n\r\n }else{\r\n System.err.println(\"NO SAMPLING METHOD SELECTED\");\r\n System.exit(1);\r\n }\r\n\r\n\r\n }",
"public int getMinutesPerWeek()\n {\n return m_minutesPerWeek == null ? NumberHelper.getInt(getParentFile().getProjectProperties().getMinutesPerWeek()) : m_minutesPerWeek.intValue();\n }",
"@NonNull\n @Override\n public Loader<SortedList<FtpFile>> getLoader() {\n return new AsyncTaskLoader<SortedList<FtpFile>>(getContext()) {\n @Override\n public SortedList<FtpFile> loadInBackground() {\n SortedList<FtpFile> sortedList = new SortedList<>(FtpFile.class, new SortedListAdapterCallback<FtpFile>(getDummyAdapter()) {\n @Override\n public int compare(FtpFile lhs, FtpFile rhs) {\n if (lhs.isDirectory() && !rhs.isDirectory()) {\n return -1;\n } else if (rhs.isDirectory() && !lhs.isDirectory()) {\n return 1;\n } else {\n return lhs.getName().compareToIgnoreCase(rhs.getName());\n }\n }\n\n @Override\n public boolean areContentsTheSame(FtpFile oldItem, FtpFile newItem) {\n return oldItem.getName().equals(newItem.getName());\n }\n\n @Override\n public boolean areItemsTheSame(FtpFile item1, FtpFile item2) {\n return item1.getName().equals(item2.getName());\n }\n });\n\n\n if (!ftp.isConnected()) {\n // Connect\n try {\n ftp.connect(server, port);\n\n ftp.setFileType(FTP.ASCII_FILE_TYPE);\n ftp.enterLocalPassiveMode();\n ftp.setUseEPSVwithIPv4(false);\n\n if (!(loggedIn = ftp.login(username, password))) {\n ftp.logout();\n Log.e(TAG, \"Login failed\");\n }\n } catch (IOException e) {\n if (ftp.isConnected()) {\n try {\n ftp.disconnect();\n } catch (IOException ignored) {\n }\n }\n Log.e(TAG, \"Could not connect to server.\");\n }\n }\n\n if (loggedIn) {\n try {\n // handle if directory does not exist. Fall back to root.\n if (mCurrentPath == null || !mCurrentPath.isDirectory()) {\n mCurrentPath = getRoot();\n }\n\n sortedList.beginBatchedUpdates();\n for (FTPFile f : ftp.listFiles(mCurrentPath.getPath())) {\n FtpFile file;\n if (f.isDirectory()) {\n file = new FtpDir(mCurrentPath, f.getName());\n } else {\n file = new FtpFile(mCurrentPath, f.getName());\n }\n if (isItemVisible(file)) {\n sortedList.add(file);\n }\n }\n sortedList.endBatchedUpdates();\n } catch (IOException e) {\n Log.e(TAG, \"IOException: \" + e.getMessage());\n }\n }\n\n return sortedList;\n }\n\n /**\n * Handles a request to start the Loader.\n */\n @Override\n protected void onStartLoading() {\n super.onStartLoading();\n\n // handle if directory does not exist. Fall back to root.\n if (mCurrentPath == null || !mCurrentPath.isDirectory()) {\n mCurrentPath = getRoot();\n }\n\n forceLoad();\n }\n };\n }"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.