query
stringlengths
7
3.3k
positive
sequencelengths
1
1
negative
sequencelengths
9
9
Plots the MSD curve with the trajectory t and adds the fitted model for anomalous diffusion above. @param t @param lagMin Minimum timelag (e.g. 1,2,3..) lagMin*timelag = elapsed time in seconds @param lagMax lagMax Maximum timelag (e.g. 1,2,3..) lagMax*timelag = elapsed time in seconds @param timelag Elapsed time between two frames. @param a Exponent alpha of power law function @param D Diffusion coeffcient
[ "public static Chart getMSDLineWithPowerModelChart(Trajectory t, int lagMin,\n\t\t\tint lagMax, double timelag, double a, double D) {\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] = 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^alpha\", xData, modelData);\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\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 TimephasedCostContainer getBaselineCost(ProjectCalendar calendar, TimephasedCostNormaliser normaliser, byte[] data, boolean raw)\n {\n TimephasedCostContainer result = null;\n\n if (data != null && data.length > 0)\n {\n LinkedList<TimephasedCost> list = null;\n\n //System.out.println(ByteArrayHelper.hexdump(data, false));\n int index = 16; // 16 byte header\n int blockSize = 20;\n double previousTotalCost = 0;\n\n Date blockStartDate = MPPUtility.getTimestampFromTenths(data, index + 16);\n index += blockSize;\n\n while (index + blockSize <= data.length)\n {\n Date blockEndDate = MPPUtility.getTimestampFromTenths(data, index + 16);\n double currentTotalCost = (double) ((long) MPPUtility.getDouble(data, index + 8)) / 100;\n if (!costEquals(previousTotalCost, currentTotalCost))\n {\n TimephasedCost cost = new TimephasedCost();\n cost.setStart(blockStartDate);\n cost.setFinish(blockEndDate);\n cost.setTotalAmount(Double.valueOf(currentTotalCost - previousTotalCost));\n\n if (list == null)\n {\n list = new LinkedList<TimephasedCost>();\n }\n list.add(cost);\n //System.out.println(cost);\n\n previousTotalCost = currentTotalCost;\n }\n\n blockStartDate = blockEndDate;\n index += blockSize;\n }\n\n if (list != null)\n {\n result = new DefaultTimephasedCostContainer(calendar, normaliser, list, raw);\n }\n }\n\n return result;\n }", "public static appfwprofile_cookieconsistency_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_cookieconsistency_binding obj = new appfwprofile_cookieconsistency_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_cookieconsistency_binding response[] = (appfwprofile_cookieconsistency_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void setValue(T value)\n {\n try\n {\n lock.writeLock().lock();\n this.value = value;\n }\n finally\n {\n lock.writeLock().unlock();\n }\n }", "public static Boolean askConfirm(Boolean confirm, String opDesc) throws IOException {\n if(confirm) {\n System.out.println(\"Confirmed \" + opDesc + \" in command-line.\");\n return true;\n } else {\n System.out.println(\"Are you sure you want to \" + opDesc + \"? (yes/no)\");\n BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));\n String text = buffer.readLine().toLowerCase(Locale.ENGLISH);\n boolean go = text.equals(\"yes\") || text.equals(\"y\");\n if (!go) {\n System.out.println(\"Did not confirm; \" + opDesc + \" aborted.\");\n }\n return go;\n }\n }", "public static 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}", "protected void checkJobType(final String jobName, final Class<?> jobType) {\n if (jobName == null) {\n throw new IllegalArgumentException(\"jobName must not be null\");\n }\n if (jobType == null) {\n throw new IllegalArgumentException(\"jobType must not be null\");\n }\n if (!(Runnable.class.isAssignableFrom(jobType)) \n && !(Callable.class.isAssignableFrom(jobType))) {\n throw new IllegalArgumentException(\n \"jobType must implement either Runnable or Callable: \" + jobType);\n }\n }", "private void fillToolBar(final I_CmsAppUIContext context) {\n\n context.setAppTitle(m_messages.key(Messages.GUI_APP_TITLE_0));\n\n // create components\n Component publishBtn = createPublishButton();\n m_saveBtn = createSaveButton();\n m_saveExitBtn = createSaveExitButton();\n Component closeBtn = createCloseButton();\n\n context.enableDefaultToolbarButtons(false);\n context.addToolbarButtonRight(closeBtn);\n context.addToolbarButton(publishBtn);\n context.addToolbarButton(m_saveExitBtn);\n context.addToolbarButton(m_saveBtn);\n\n Component addDescriptorBtn = createAddDescriptorButton();\n if (m_model.hasDescriptor() || m_model.getBundleType().equals(BundleType.DESCRIPTOR)) {\n addDescriptorBtn.setEnabled(false);\n }\n context.addToolbarButton(addDescriptorBtn);\n if (m_model.getBundleType().equals(BundleType.XML)) {\n Component convertToPropertyBundleBtn = createConvertToPropertyBundleButton();\n context.addToolbarButton(convertToPropertyBundleBtn);\n }\n }", "public static List<DatabaseTableConfig<?>> loadDatabaseConfigFromReader(BufferedReader reader) throws SQLException {\n\t\tList<DatabaseTableConfig<?>> list = new ArrayList<DatabaseTableConfig<?>>();\n\t\twhile (true) {\n\t\t\tDatabaseTableConfig<?> config = DatabaseTableConfigLoader.fromReader(reader);\n\t\t\tif (config == null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tlist.add(config);\n\t\t}\n\t\treturn list;\n\t}" ]
Constructs a new ClientBuilder for building a CloudantClient instance to connect to the Cloudant server with the specified account. @param account the Cloudant account name to connect to e.g. "example" is the account name for the "example.cloudant.com" endpoint @return a new ClientBuilder for the account @throws IllegalArgumentException if the specified account name forms an invalid endpoint URL
[ "public static ClientBuilder account(String account) {\n logger.config(\"Account: \" + account);\n return ClientBuilder.url(\n convertStringToURL(String.format(\"https://%s.cloudant.com\", account)));\n }" ]
[ "public List<String> getArtifactVersions(final String gavc) {\n final DbArtifact artifact = getArtifact(gavc);\n return repositoryHandler.getArtifactVersions(artifact);\n }", "public static authenticationvserver_authenticationnegotiatepolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_authenticationnegotiatepolicy_binding obj = new authenticationvserver_authenticationnegotiatepolicy_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_authenticationnegotiatepolicy_binding response[] = (authenticationvserver_authenticationnegotiatepolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public Map<Integer, RandomVariable> getGradient(){\r\n\r\n\t\tint numberOfCalculationSteps = getFunctionList().size();\r\n\r\n\t\tRandomVariable[] omegaHat = new RandomVariable[numberOfCalculationSteps];\r\n\r\n\t\tomegaHat[numberOfCalculationSteps-1] = new RandomVariableFromDoubleArray(1.0);\r\n\r\n\t\tfor(int variableIndex = numberOfCalculationSteps-2; variableIndex >= 0; variableIndex--){\r\n\r\n\t\t\tomegaHat[variableIndex] = new RandomVariableFromDoubleArray(0.0);\r\n\r\n\t\t\tArrayList<Integer> childrenList = getAADRandomVariableFromList(variableIndex).getChildrenIndices();\r\n\r\n\t\t\tfor(int functionIndex:childrenList){\r\n\t\t\t\tRandomVariable D_i_j = getPartialDerivative(functionIndex, variableIndex);\r\n\t\t\t\tomegaHat[variableIndex] = omegaHat[variableIndex].addProduct(D_i_j, omegaHat[functionIndex]);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tArrayList<Integer> arrayListOfAllIndicesOfDependentRandomVariables = getArrayListOfAllIndicesOfDependentRandomVariables();\r\n\r\n\t\tMap<Integer, RandomVariable> gradient = new HashMap<Integer, RandomVariable>();\r\n\r\n\t\tfor(Integer indexOfDependentRandomVariable: arrayListOfAllIndicesOfDependentRandomVariables){\r\n\t\t\tgradient.put(indexOfDependentRandomVariable, omegaHat[arrayListOfAllIndicesOfDependentRandomVariables.get(indexOfDependentRandomVariable)]);\r\n\t\t}\r\n\r\n\t\treturn gradient;\r\n\t}", "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 boolean isAvailable() throws Exception {\n try {\n Registry myRegistry = LocateRegistry.getRegistry(\"127.0.0.1\", port);\n com.groupon.odo.proxylib.hostsedit.rmi.Message impl = (com.groupon.odo.proxylib.hostsedit.rmi.Message) myRegistry.lookup(SERVICE_NAME);\n return true;\n } catch (Exception e) {\n return false;\n }\n }", "public static boolean applyTo(ImageHolder imageHolder, ImageView imageView, String tag) {\n if (imageHolder != null && imageView != null) {\n return imageHolder.applyTo(imageView, tag);\n }\n return false;\n }", "public static void Forward(double[][] data) {\n double[][] result = new double[data.length][data[0].length];\n\n for (int m = 0; m < data.length; m++) {\n for (int n = 0; n < data[0].length; n++) {\n double sum = 0;\n for (int i = 0; i < result.length; i++) {\n for (int k = 0; k < data.length; k++) {\n sum += data[i][k] * cas(((2.0 * Math.PI) / data.length) * (i * m + k * n));\n }\n result[m][n] = (1.0 / data.length) * sum;\n }\n }\n }\n\n for (int i = 0; i < data.length; i++) {\n for (int j = 0; j < data[0].length; j++) {\n data[i][j] = result[i][j];\n }\n }\n }", "public void forAllExtents(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _curClassDef.getExtentClasses(); it.hasNext(); )\r\n {\r\n _curExtent = (ClassDescriptorDef)it.next();\r\n generate(template);\r\n }\r\n _curExtent = null;\r\n }", "private boolean computeEigenValues() {\n // make a copy of the internal tridiagonal matrix data for later use\n diagSaved = helper.copyDiag(diagSaved);\n offSaved = helper.copyOff(offSaved);\n\n vector.setQ(null);\n vector.setFastEigenvalues(true);\n\n // extract the eigenvalues\n if( !vector.process(-1,null,null) )\n return false;\n\n // save a copy of them since this data structure will be recycled next\n values = helper.copyEigenvalues(values);\n return true;\n }" ]
Creates an operations that targets the valiadating handler. @param operationToValidate the operation that this handler will validate @return the validation operation
[ "private static ModelNode createOperation(final ModelNode operationToValidate) {\n PathAddress pa = PathAddress.pathAddress(operationToValidate.require(OP_ADDR));\n PathAddress validationAddress = pa.subAddress(0, pa.size() - 1);\n\n return Util.getEmptyOperation(\"validate-cache\", validationAddress.toModelNode());\n }" ]
[ "private boolean fireEvent(Eventable eventable) {\n\t\tEventable eventToFire = eventable;\n\t\tif (eventable.getIdentification().getHow().toString().equals(\"xpath\")\n\t\t\t\t&& eventable.getRelatedFrame().equals(\"\")) {\n\t\t\teventToFire = resolveByXpath(eventable, eventToFire);\n\t\t}\n\t\tboolean isFired = false;\n\t\ttry {\n\t\t\tisFired = browser.fireEventAndWait(eventToFire);\n\t\t} catch (ElementNotVisibleException | NoSuchElementException e) {\n\t\t\tif (crawlRules.isCrawlHiddenAnchors() && eventToFire.getElement() != null\n\t\t\t\t\t&& \"A\".equals(eventToFire.getElement().getTag())) {\n\t\t\t\tisFired = visitAnchorHrefIfPossible(eventToFire);\n\t\t\t} else {\n\t\t\t\tLOG.debug(\"Ignoring invisible element {}\", eventToFire.getElement());\n\t\t\t}\n\t\t} catch (InterruptedException e) {\n\t\t\tLOG.debug(\"Interrupted during fire event\");\n\t\t\tinterruptThread();\n\t\t\treturn false;\n\t\t}\n\n\t\tLOG.debug(\"Event fired={} for eventable {}\", isFired, eventable);\n\n\t\tif (isFired) {\n\t\t\t// Let the controller execute its specified wait operation on the browser thread safe.\n\t\t\twaitConditionChecker.wait(browser);\n\t\t\tbrowser.closeOtherWindows();\n\t\t\treturn true;\n\t\t} else {\n\t\t\t/*\n\t\t\t * Execute the OnFireEventFailedPlugins with the current crawlPath with the crawlPath\n\t\t\t * removed 1 state to represent the path TO here.\n\t\t\t */\n\t\t\tplugins.runOnFireEventFailedPlugins(context, eventable,\n\t\t\t\t\tcrawlpath.immutableCopyWithoutLast());\n\t\t\treturn false; // no event fired\n\t\t}\n\t}", "protected byte[] getUpperBytesInternal() {\n\t\tbyte cached[];\n\t\tif(hasNoValueCache()) {\n\t\t\tValueCache cache = valueCache;\n\t\t\tcache.upperBytes = cached = getBytesImpl(false);\n\t\t\tif(!isMultiple()) {\n\t\t\t\tcache.lowerBytes = cached;\n\t\t\t}\n\t\t} else {\n\t\t\tValueCache cache = valueCache;\n\t\t\tif((cached = cache.upperBytes) == null) {\n\t\t\t\tif(!isMultiple()) {\n\t\t\t\t\tif((cached = cache.lowerBytes) != null) {\n\t\t\t\t\t\tcache.upperBytes = cached;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcache.lowerBytes = cache.upperBytes = cached = getBytesImpl(false);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tcache.upperBytes = cached = getBytesImpl(false);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn cached;\n\t}", "public static long bytesToNumber(byte[] buffer, int start, int length) {\n long result = 0;\n for (int index = start; index < start + length; index++) {\n result = (result << 8) + unsign(buffer[index]);\n }\n return result;\n }", "private String pathToProperty(String path) {\n if (path == null || !path.startsWith(\"/\")) {\n throw new IllegalArgumentException(\"Path must be prefixed with a \\\"/\\\".\");\n }\n return path.substring(1);\n }", "public static final String getSelectedText(ListBox list) {\n\tint index = list.getSelectedIndex();\n\treturn (index >= 0) ? list.getItemText(index) : null;\n }", "public static base_response update(nitro_service client, gslbservice resource) throws Exception {\n\t\tgslbservice updateresource = new gslbservice();\n\t\tupdateresource.servicename = resource.servicename;\n\t\tupdateresource.ipaddress = resource.ipaddress;\n\t\tupdateresource.publicip = resource.publicip;\n\t\tupdateresource.publicport = resource.publicport;\n\t\tupdateresource.cip = resource.cip;\n\t\tupdateresource.cipheader = resource.cipheader;\n\t\tupdateresource.sitepersistence = resource.sitepersistence;\n\t\tupdateresource.siteprefix = resource.siteprefix;\n\t\tupdateresource.maxclient = resource.maxclient;\n\t\tupdateresource.healthmonitor = resource.healthmonitor;\n\t\tupdateresource.maxbandwidth = resource.maxbandwidth;\n\t\tupdateresource.downstateflush = resource.downstateflush;\n\t\tupdateresource.maxaaausers = resource.maxaaausers;\n\t\tupdateresource.viewname = resource.viewname;\n\t\tupdateresource.viewip = resource.viewip;\n\t\tupdateresource.monthreshold = resource.monthreshold;\n\t\tupdateresource.weight = resource.weight;\n\t\tupdateresource.monitor_name_svc = resource.monitor_name_svc;\n\t\tupdateresource.hashid = resource.hashid;\n\t\tupdateresource.comment = resource.comment;\n\t\tupdateresource.appflowlog = resource.appflowlog;\n\t\treturn updateresource.update_resource(client);\n\t}", "public static base_responses delete(nitro_service client, String serverip[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (serverip != null && serverip.length > 0) {\n\t\t\tntpserver deleteresources[] = new ntpserver[serverip.length];\n\t\t\tfor (int i=0;i<serverip.length;i++){\n\t\t\t\tdeleteresources[i] = new ntpserver();\n\t\t\t\tdeleteresources[i].serverip = serverip[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "public Collection<Blog> getList() throws FlickrException {\r\n List<Blog> blogs = new ArrayList<Blog>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIST);\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element blogsElement = response.getPayload();\r\n NodeList blogNodes = blogsElement.getElementsByTagName(\"blog\");\r\n for (int i = 0; i < blogNodes.getLength(); i++) {\r\n Element blogElement = (Element) blogNodes.item(i);\r\n Blog blog = new Blog();\r\n blog.setId(blogElement.getAttribute(\"id\"));\r\n blog.setName(blogElement.getAttribute(\"name\"));\r\n blog.setNeedPassword(\"1\".equals(blogElement.getAttribute(\"needspassword\")));\r\n blog.setUrl(blogElement.getAttribute(\"url\"));\r\n blogs.add(blog);\r\n }\r\n return blogs;\r\n }", "public void begin(String key)\n {\n if (key == null)\n {\n return;\n }\n TimingData data = executionInfo.get(key);\n if (data == null)\n {\n data = new TimingData(key);\n executionInfo.put(key, data);\n }\n data.begin();\n }" ]
Restores a trashed folder back to its original location. @param folderID the ID of the trashed folder. @return info about the restored folder.
[ "public BoxFolder.Info restoreFolder(String folderID) {\n URL url = RESTORE_FOLDER_URL_TEMPLATE.build(this.api.getBaseURL(), folderID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"POST\");\n JsonObject requestJSON = new JsonObject()\n .add(\"\", \"\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxFolder restoredFolder = new BoxFolder(this.api, responseJSON.get(\"id\").asString());\n return restoredFolder.new Info(responseJSON);\n }" ]
[ "public Set<String> rangeByLexReverse(final LexRange lexRange) {\n return doWithJedis(new JedisCallable<Set<String>>() {\n @Override\n public Set<String> call(Jedis jedis) {\n if (lexRange.hasLimit()) {\n return jedis.zrevrangeByLex(getKey(), lexRange.fromReverse(), lexRange.toReverse(), lexRange.offset(), lexRange.count());\n } else {\n return jedis.zrevrangeByLex(getKey(), lexRange.fromReverse(), lexRange.toReverse());\n }\n }\n });\n }", "public ItemRequest<ProjectStatus> findById(String projectStatus) {\n\n String path = String.format(\"/project_statuses/%s\", projectStatus);\n return new ItemRequest<ProjectStatus>(this, ProjectStatus.class, path, \"GET\");\n }", "public static void unsetCurrentPersistenceBroker(PBKey key, PersistenceBrokerInternal broker)\r\n throws PBFactoryException\r\n {\r\n HashMap map = (HashMap) currentBrokerMap.get();\r\n WeakHashMap set = null;\r\n if(map != null)\r\n {\r\n set = (WeakHashMap) map.get(key);\r\n if(set != null)\r\n {\r\n set.remove(broker);\r\n if(set.isEmpty())\r\n {\r\n map.remove(key);\r\n }\r\n }\r\n if(map.isEmpty())\r\n {\r\n currentBrokerMap.set(null);\r\n synchronized(lock) {\r\n loadedHMs.remove(map);\r\n }\r\n }\r\n }\r\n }", "void reportError(Throwable throwable) {\n if (logger != null)\n logger.error(\"Timer reported error\", throwable);\n status = \"Thread blocked on error: \" + throwable;\n error_skips = error_factor;\n }", "public static ModelMBean createModelMBean(Object o) {\n try {\n ModelMBean mbean = new RequiredModelMBean();\n JmxManaged annotation = o.getClass().getAnnotation(JmxManaged.class);\n String description = annotation == null ? \"\" : annotation.description();\n ModelMBeanInfo info = new ModelMBeanInfoSupport(o.getClass().getName(),\n description,\n extractAttributeInfo(o),\n new ModelMBeanConstructorInfo[0],\n extractOperationInfo(o),\n new ModelMBeanNotificationInfo[0]);\n mbean.setModelMBeanInfo(info);\n mbean.setManagedResource(o, \"ObjectReference\");\n\n return mbean;\n } catch(MBeanException e) {\n throw new VoldemortException(e);\n } catch(InvalidTargetObjectTypeException e) {\n throw new VoldemortException(e);\n } catch(InstanceNotFoundException e) {\n throw new VoldemortException(e);\n }\n }", "public Bundler put(String key, Parcelable value) {\n delegate.putParcelable(key, value);\n return this;\n }", "private void parseUsersAuthentication(final XMLExtendedStreamReader reader,\n final ModelNode realmAddress, final List<ModelNode> list)\n throws XMLStreamException {\n final ModelNode usersAddress = realmAddress.clone().add(AUTHENTICATION, USERS);\n list.add(Util.getEmptyOperation(ADD, usersAddress));\n\n while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {\n requireNamespace(reader, namespace);\n final Element element = Element.forName(reader.getLocalName());\n switch (element) {\n case USER: {\n parseUser(reader, usersAddress, list);\n break;\n }\n default: {\n throw unexpectedElement(reader);\n }\n }\n }\n }", "public static void awaitRoute(URL routeUrl, int timeout, TimeUnit timeoutUnit, int repetitions, int... statusCodes) {\n AtomicInteger successfulAwaitsInARow = new AtomicInteger(0);\n await().atMost(timeout, timeoutUnit).until(() -> {\n if (tryConnect(routeUrl, statusCodes)) {\n successfulAwaitsInARow.incrementAndGet();\n } else {\n successfulAwaitsInARow.set(0);\n }\n return successfulAwaitsInARow.get() >= repetitions;\n });\n }", "public List<ServerRedirect> getServerMappings() {\n ArrayList<ServerRedirect> servers = new ArrayList<ServerRedirect>();\n try {\n JSONObject response = new JSONObject(doGet(BASE_SERVER, null));\n JSONArray serverArray = response.getJSONArray(\"servers\");\n\n for (int i = 0; i < serverArray.length(); i++) {\n JSONObject jsonServer = serverArray.getJSONObject(i);\n ServerRedirect server = getServerRedirectFromJSON(jsonServer);\n if (server != null) {\n servers.add(server);\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n return servers;\n }" ]
This method processes any extended attributes associated with a resource. @param xml MSPDI resource instance @param mpx MPX resource instance
[ "private void readResourceExtendedAttributes(Project.Resources.Resource xml, Resource mpx)\n {\n for (Project.Resources.Resource.ExtendedAttribute attrib : xml.getExtendedAttribute())\n {\n int xmlFieldID = Integer.parseInt(attrib.getFieldID()) & 0x0000FFFF;\n ResourceField mpxFieldID = MPPResourceField.getInstance(xmlFieldID);\n TimeUnit durationFormat = DatatypeConverter.parseDurationTimeUnits(attrib.getDurationFormat(), null);\n DatatypeConverter.parseExtendedAttribute(m_projectFile, mpx, attrib.getValue(), mpxFieldID, durationFormat);\n }\n }" ]
[ "@Override\n public void handleExceptions(MessageEvent messageEvent, Exception exception) {\n\n if(exception instanceof InvalidMetadataException) {\n logger.error(\"Exception when deleting. The requested key does not exist in this partition\",\n exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE,\n \"The requested key does not exist in this partition\");\n } else if(exception instanceof PersistenceFailureException) {\n logger.error(\"Exception when deleting. Operation failed\", exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.INTERNAL_SERVER_ERROR,\n \"Operation failed\");\n } else if(exception instanceof UnsupportedOperationException) {\n logger.error(\"Exception when deleting. Operation not supported in read-only store \",\n exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.METHOD_NOT_ALLOWED,\n \"Operation not supported in read-only store\");\n } else if(exception instanceof StoreTimeoutException) {\n String errorDescription = \"DELETE Request timed out: \" + exception.getMessage();\n logger.error(errorDescription);\n writeErrorResponse(messageEvent, HttpResponseStatus.REQUEST_TIMEOUT, errorDescription);\n } else if(exception instanceof InsufficientOperationalNodesException) {\n String errorDescription = \"DELETE Request failed: \" + exception.getMessage();\n logger.error(errorDescription);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.INTERNAL_SERVER_ERROR,\n errorDescription);\n } else {\n super.handleExceptions(messageEvent, exception);\n }\n }", "@Beta\n public MSICredentials withIdentityId(String identityId) {\n this.identityId = identityId;\n this.clientId = null;\n this.objectId = null;\n return this;\n }", "public static JqmEngineOperations startEngine(String name, JqmEngineHandler handler)\n {\n JqmEngine e = new JqmEngine();\n e.start(name, handler);\n return e;\n }", "public String processIndexDescriptor(Properties attributes) throws XDocletException\r\n {\r\n String name = attributes.getProperty(ATTRIBUTE_NAME);\r\n IndexDescriptorDef indexDef = _curClassDef.getIndexDescriptor(name);\r\n String attrName;\r\n \r\n if (indexDef == null)\r\n { \r\n indexDef = new IndexDescriptorDef(name);\r\n _curClassDef.addIndexDescriptor(indexDef);\r\n }\r\n\r\n if ((indexDef.getName() == null) || (indexDef.getName().length() == 0))\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.INDEX_NAME_MISSING,\r\n new String[]{_curClassDef.getName()}));\r\n }\r\n attributes.remove(ATTRIBUTE_NAME);\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n indexDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n return \"\";\r\n }", "private static String getBundle(String friendlyName, String className, int truncate)\r\n\t{\r\n\t\ttry {\r\n\t\t\tcl.loadClass(className);\r\n\t\t\tint start = className.length();\r\n\t\t\tfor (int i = 0; i < truncate; ++i)\r\n\t\t\t\tstart = className.lastIndexOf('.', start - 1);\r\n\t\t\tfinal String bundle = className.substring(0, start);\r\n\t\t\treturn \"+ \" + friendlyName + align(friendlyName) + \"- \" + bundle;\r\n\t\t}\r\n\t\tcatch (final ClassNotFoundException e) {}\r\n\t\tcatch (final NoClassDefFoundError e) {}\r\n\t\treturn \"- \" + friendlyName + align(friendlyName) + \"- not available\";\r\n\t}", "public String generateDigest(InputStream stream) {\n MessageDigest digest = null;\n try {\n digest = MessageDigest.getInstance(DIGEST_ALGORITHM_SHA1);\n } catch (NoSuchAlgorithmException ae) {\n throw new BoxAPIException(\"Digest algorithm not found\", ae);\n }\n\n //Calcuate the digest using the stream.\n DigestInputStream dis = new DigestInputStream(stream, digest);\n try {\n int value = dis.read();\n while (value != -1) {\n value = dis.read();\n }\n } catch (IOException ioe) {\n throw new BoxAPIException(\"Reading the stream failed.\", ioe);\n }\n\n //Get the calculated digest for the stream\n byte[] digestBytes = digest.digest();\n return Base64.encode(digestBytes);\n }", "public static gslbdomain_stats[] get(nitro_service service) throws Exception{\n\t\tgslbdomain_stats obj = new gslbdomain_stats();\n\t\tgslbdomain_stats[] response = (gslbdomain_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}", "public void setShortVec(char[] data)\n {\n if (data == null)\n {\n throw new IllegalArgumentException(\"Input data for indices cannot be null\");\n }\n if (getIndexSize() != 2)\n {\n throw new UnsupportedOperationException(\"Cannot update integer indices with char array\");\n }\n if (!NativeIndexBuffer.setShortArray(getNative(), data))\n {\n throw new UnsupportedOperationException(\"Input array is wrong size\");\n }\n }", "public double[][] getPositionsAsArray(){\n\t\tdouble[][] posAsArr = new double[size()][3];\n\t\tfor(int i = 0; i < size(); i++){\n\t\t\tif(get(i)!=null){\n\t\t\t\tposAsArr[i][0] = get(i).x;\n\t\t\t\tposAsArr[i][1] = get(i).y;\n\t\t\t\tposAsArr[i][2] = get(i).z;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tposAsArr[i] = null;\n\t\t\t}\n\t\t}\n\t\treturn posAsArr;\n\t}" ]
Convenience method to determine if a character is special to the regex system. @param chr the character to test @return is the character a special character.
[ "private boolean isSpecial(final char chr) {\n\t\treturn ((chr == '.') || (chr == '?') || (chr == '*') || (chr == '^') || (chr == '$') || (chr == '+')\n\t\t\t\t|| (chr == '[') || (chr == ']') || (chr == '(') || (chr == ')') || (chr == '|') || (chr == '\\\\')\n\t\t\t\t|| (chr == '&'));\n\t}" ]
[ "private String getSymbolName(char c)\n {\n String result = null;\n\n switch (c)\n {\n case ',':\n {\n result = \"Comma\";\n break;\n }\n\n case '.':\n {\n result = \"Period\";\n break;\n }\n }\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 }", "protected int readShort(int offset, byte[] data)\n {\n int result = 0;\n int i = offset + m_offset;\n for (int shiftBy = 0; shiftBy < 16; shiftBy += 8)\n {\n result |= ((data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }", "private void readContents(int maxFrames) {\n // Read GIF file content blocks.\n boolean done = false;\n while (!(done || err() || header.frameCount > maxFrames)) {\n int code = read();\n switch (code) {\n // Image separator.\n case 0x2C:\n // The graphics control extension is optional, but will always come first if it exists.\n // If one did\n // exist, there will be a non-null current frame which we should use. However if one\n // did not exist,\n // the current frame will be null and we must create it here. See issue #134.\n if (header.currentFrame == null) {\n header.currentFrame = new GifFrame();\n }\n readBitmap();\n break;\n // Extension.\n case 0x21:\n code = read();\n switch (code) {\n // Graphics control extension.\n case 0xf9:\n // Start a new frame.\n header.currentFrame = new GifFrame();\n readGraphicControlExt();\n break;\n // Application extension.\n case 0xff:\n readBlock();\n String app = \"\";\n for (int i = 0; i < 11; i++) {\n app += (char) block[i];\n }\n if (app.equals(\"NETSCAPE2.0\")) {\n readNetscapeExt();\n } else {\n // Don't care.\n skip();\n }\n break;\n // Comment extension.\n case 0xfe:\n skip();\n break;\n // Plain text extension.\n case 0x01:\n skip();\n break;\n // Uninteresting extension.\n default:\n skip();\n }\n break;\n // Terminator.\n case 0x3b:\n done = true;\n break;\n // Bad byte, but keep going and see what happens break;\n case 0x00:\n default:\n header.status = GifDecoder.STATUS_FORMAT_ERROR;\n }\n }\n }", "public GroovyFieldDoc[] properties() {\n Collections.sort(properties);\n return properties.toArray(new GroovyFieldDoc[properties.size()]);\n }", "public static Class<?> getMapValueFieldType(Field mapField, int nestingLevel) {\n\t\treturn getGenericFieldType(mapField, Map.class, 1, null, nestingLevel);\n\t}", "public boolean hasRequiredAdminProps() {\n boolean valid = true;\n valid &= hasRequiredClientProps();\n valid &= verifyStringPropSet(ACCUMULO_TABLE_PROP, ADMIN_ACCUMULO_TABLE_PROP);\n return valid;\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}", "public static ModelMBeanOperationInfo[] extractOperationInfo(Object object) {\n ArrayList<ModelMBeanOperationInfo> infos = new ArrayList<ModelMBeanOperationInfo>();\n for(Method m: object.getClass().getMethods()) {\n JmxOperation jmxOperation = m.getAnnotation(JmxOperation.class);\n JmxGetter jmxGetter = m.getAnnotation(JmxGetter.class);\n JmxSetter jmxSetter = m.getAnnotation(JmxSetter.class);\n if(jmxOperation != null || jmxGetter != null || jmxSetter != null) {\n String description = \"\";\n int visibility = 1;\n int impact = MBeanOperationInfo.UNKNOWN;\n if(jmxOperation != null) {\n description = jmxOperation.description();\n impact = jmxOperation.impact();\n } else if(jmxGetter != null) {\n description = jmxGetter.description();\n impact = MBeanOperationInfo.INFO;\n visibility = 4;\n } else if(jmxSetter != null) {\n description = jmxSetter.description();\n impact = MBeanOperationInfo.ACTION;\n visibility = 4;\n }\n ModelMBeanOperationInfo info = new ModelMBeanOperationInfo(m.getName(),\n description,\n extractParameterInfo(m),\n m.getReturnType()\n .getName(), impact);\n info.getDescriptor().setField(\"visibility\", Integer.toString(visibility));\n infos.add(info);\n }\n }\n\n return infos.toArray(new ModelMBeanOperationInfo[infos.size()]);\n }" ]
Replace error msg. @param origMsg the orig msg @return the string
[ "public static String replaceErrorMsg(String origMsg) {\n\n String replaceMsg = origMsg;\n for (ERROR_TYPE errorType : ERROR_TYPE.values()) {\n\n if (origMsg == null) {\n replaceMsg = PcConstants.NA;\n return replaceMsg;\n }\n\n if (origMsg.contains(errorMapOrig.get(errorType))) {\n replaceMsg = errorMapReplace.get(errorType);\n break;\n }\n\n }\n\n return replaceMsg;\n\n }" ]
[ "public static base_response save(nitro_service client, cachecontentgroup resource) throws Exception {\n\t\tcachecontentgroup saveresource = new cachecontentgroup();\n\t\tsaveresource.name = resource.name;\n\t\treturn saveresource.perform_operation(client,\"save\");\n\t}", "public SchedulerDocsResponse.Doc schedulerDoc(String docId) {\n assertNotEmpty(docId, \"docId\");\n return this.get(new DatabaseURIHelper(getBaseUri()).\n path(\"_scheduler\").path(\"docs\").path(\"_replicator\").path(docId).build(),\n SchedulerDocsResponse.Doc.class);\n }", "public static void pauseTimer(final String type) {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return;\n }\n\n instance.components.get(type).pauseTimer();\n }", "private void logError(LifecycleListener listener, Exception e) {\n LOGGER.error(\"Error for listener \" + listener.getClass(), e);\n }", "public void fatal(String msg) {\n\t\tlogIfEnabled(Level.FATAL, null, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, null);\n\t}", "private void checkOrderby(CollectionDescriptorDef collDef, 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 orderbySpec = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ORDERBY);\r\n\r\n if ((orderbySpec == null) || (orderbySpec.length() == 0))\r\n {\r\n return;\r\n }\r\n\r\n ClassDescriptorDef ownerClass = (ClassDescriptorDef)collDef.getOwner();\r\n String elementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF).replace('$', '.');\r\n ClassDescriptorDef elementClass = ((ModelDef)ownerClass.getOwner()).getClass(elementClassName);\r\n FieldDescriptorDef fieldDef;\r\n String token;\r\n String fieldName;\r\n String ordering;\r\n int pos;\r\n\r\n for (CommaListIterator it = new CommaListIterator(orderbySpec); it.hasNext();)\r\n {\r\n token = it.getNext();\r\n pos = token.indexOf('=');\r\n if (pos == -1)\r\n {\r\n fieldName = token;\r\n ordering = null;\r\n }\r\n else\r\n {\r\n fieldName = token.substring(0, pos);\r\n ordering = token.substring(pos + 1);\r\n }\r\n fieldDef = elementClass.getField(fieldName);\r\n if (fieldDef == null)\r\n {\r\n throw new ConstraintException(\"The field \"+fieldName+\" specified in the orderby attribute of the collection \"+collDef.getName()+\" in class \"+ownerClass.getName()+\" hasn't been found in the element class \"+elementClass.getName());\r\n }\r\n if ((ordering != null) && (ordering.length() > 0) &&\r\n !\"ASC\".equals(ordering) && !\"DESC\".equals(ordering))\r\n {\r\n throw new ConstraintException(\"The ordering \"+ordering+\" specified in the orderby attribute of the collection \"+collDef.getName()+\" in class \"+ownerClass.getName()+\" is invalid\");\r\n }\r\n }\r\n }", "public void stop() {\n syncLock.lock();\n try {\n if (syncThread == null) {\n return;\n }\n instanceChangeStreamListener.stop();\n syncThread.interrupt();\n try {\n syncThread.join();\n } catch (final InterruptedException e) {\n return;\n }\n syncThread = null;\n isRunning = false;\n } finally {\n syncLock.unlock();\n }\n }", "public final void save(final PrintJobStatusExtImpl entry) {\n getSession().merge(entry);\n getSession().flush();\n getSession().evict(entry);\n }", "public void refreshBitmapShader()\n\t{\n\t\tshader = new BitmapShader(Bitmap.createScaledBitmap(image, canvasSize, canvasSize, false), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);\n\t}" ]
Removes the task from the specified project. The task will still exist in the system, but it will not be in the project anymore. Returns an empty data block. @param task The task to remove from a project. @return Request object
[ "public ItemRequest<Task> removeProject(String task) {\n \n String path = String.format(\"/tasks/%s/removeProject\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }" ]
[ "private 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 void setPatternScheme(final boolean isByWeekDay, final boolean fireChange) {\n\n if (isByWeekDay ^ (null != m_model.getWeekDay())) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n if (isByWeekDay) {\n m_model.setWeekOfMonth(getPatternDefaultValues().getWeekOfMonth());\n m_model.setWeekDay(getPatternDefaultValues().getWeekDay());\n } else {\n m_model.clearWeekDays();\n m_model.clearWeeksOfMonth();\n m_model.setDayOfMonth(getPatternDefaultValues().getDayOfMonth());\n }\n m_model.setInterval(getPatternDefaultValues().getInterval());\n if (fireChange) {\n onValueChange();\n }\n }\n });\n }\n\n }", "public boolean getBit(int index)\n {\n assertValidIndex(index);\n int word = index / WORD_LENGTH;\n int offset = index % WORD_LENGTH;\n return (data[word] & (1 << offset)) != 0;\n }", "public void execute() throws MojoExecutionException, MojoFailureException {\n try {\n Set<File> thriftFiles = findThriftFiles();\n\n final File outputDirectory = getOutputDirectory();\n ImmutableSet<File> outputFiles = findGeneratedFilesInDirectory(getOutputDirectory());\n\n Set<String> compileRoots = new HashSet<String>();\n compileRoots.add(\"scrooge\");\n\n if (thriftFiles.isEmpty()) {\n getLog().info(\"No thrift files to compile.\");\n } else if (checkStaleness && ((lastModified(thriftFiles) + staleMillis) < lastModified(outputFiles))) {\n getLog().info(\"Generated thrift files up to date, skipping compile.\");\n attachFiles(compileRoots);\n } else {\n outputDirectory.mkdirs();\n\n // Quick fix to fix issues with two mvn installs in a row (ie no clean)\n cleanDirectory(outputDirectory);\n\n getLog().info(format(\"compiling thrift files %s with Scrooge\", thriftFiles));\n synchronized(lock) {\n ScroogeRunner runner = new ScroogeRunner();\n Map<String, String> thriftNamespaceMap = new HashMap<String, String>();\n for (ThriftNamespaceMapping mapping : thriftNamespaceMappings) {\n thriftNamespaceMap.put(mapping.getFrom(), mapping.getTo());\n }\n\n // Include thrifts from resource as well.\n Set<File> includes = thriftIncludes;\n includes.add(getResourcesOutputDirectory());\n\n // Include thrift root\n final File thriftSourceRoot = getThriftSourceRoot();\n if (thriftSourceRoot != null && thriftSourceRoot.exists()) {\n includes.add(thriftSourceRoot);\n }\n\n runner.compile(\n getLog(),\n includeOutputDirectoryNamespace ? new File(outputDirectory, \"scrooge\") : outputDirectory,\n thriftFiles,\n includes,\n thriftNamespaceMap,\n language,\n thriftOpts);\n }\n attachFiles(compileRoots);\n }\n } catch (IOException e) {\n throw new MojoExecutionException(\"An IO error occurred\", e);\n }\n }", "public BoxFileUploadSessionPart uploadPart(InputStream stream, long offset, int partSize,\n long totalSizeOfFile) {\n\n URL uploadPartURL = this.sessionInfo.getSessionEndpoints().getUploadPartEndpoint();\n\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), uploadPartURL, HttpMethod.PUT);\n request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_OCTET_STREAM);\n\n //Read the partSize bytes from the stream\n byte[] bytes = new byte[partSize];\n try {\n stream.read(bytes);\n } catch (IOException ioe) {\n throw new BoxAPIException(\"Reading data from stream failed.\", ioe);\n }\n\n return this.uploadPart(bytes, offset, partSize, totalSizeOfFile);\n }", "public static void setFilterBoxStyle(TextField searchBox) {\n\n searchBox.setIcon(FontOpenCms.FILTER);\n\n searchBox.setPlaceholder(\n org.opencms.ui.apps.Messages.get().getBundle(UI.getCurrent().getLocale()).key(\n org.opencms.ui.apps.Messages.GUI_EXPLORER_FILTER_0));\n searchBox.addStyleName(ValoTheme.TEXTFIELD_INLINE_ICON);\n }", "public static String getImageIdFromAgent(Launcher launcher, final String imageTag, final String host) throws IOException, InterruptedException {\n return launcher.getChannel().call(new MasterToSlaveCallable<String, IOException>() {\n public String call() throws IOException {\n return DockerUtils.getImageIdFromTag(imageTag, host);\n }\n });\n }", "private void exportModules() {\n\n // avoid to export modules if unnecessary\n if (((null != m_copyAndUnzip) && !m_copyAndUnzip.booleanValue())\n || ((null == m_copyAndUnzip) && !m_currentConfiguration.getDefaultCopyAndUnzip())) {\n m_logStream.println();\n m_logStream.println(\"NOT EXPORTING MODULES - you disabled copy and unzip.\");\n m_logStream.println();\n return;\n }\n CmsModuleManager moduleManager = OpenCms.getModuleManager();\n\n Collection<String> modulesToExport = ((m_modulesToExport == null) || m_modulesToExport.isEmpty())\n ? m_currentConfiguration.getConfiguredModules()\n : m_modulesToExport;\n\n for (String moduleName : modulesToExport) {\n CmsModule module = moduleManager.getModule(moduleName);\n if (module != null) {\n CmsModuleImportExportHandler handler = CmsModuleImportExportHandler.getExportHandler(\n getCmsObject(),\n module,\n \"Git export handler\");\n try {\n handler.exportData(\n getCmsObject(),\n new CmsPrintStreamReport(\n m_logStream,\n OpenCms.getWorkplaceManager().getWorkplaceLocale(getCmsObject()),\n false));\n } catch (CmsRoleViolationException | CmsConfigurationException | CmsImportExportException e) {\n e.printStackTrace(m_logStream);\n }\n }\n }\n }", "protected String getUserDefinedFieldName(String field) {\n int index = field.indexOf('-');\n char letter = getUserDefinedFieldLetter();\n\n for (int i = 0; i < index; ++i) {\n if (field.charAt(i) == letter) {\n return field.substring(index + 1);\n }\n }\n\n return null;\n }" ]
converts the file URIs with an absent authority to one with an empty
[ "public URI withEmptyAuthority(final URI uri) {\n URI _xifexpression = null;\n if ((uri.isFile() && (uri.authority() == null))) {\n _xifexpression = URI.createHierarchicalURI(uri.scheme(), \"\", uri.device(), uri.segments(), uri.query(), uri.fragment());\n } else {\n _xifexpression = uri;\n }\n return _xifexpression;\n }" ]
[ "public void addNotification(@Observes final DesignerNotificationEvent event) {\n if (user.getIdentifier().equals(event.getUserId())) {\n\n if (event.getNotification() != null && !event.getNotification().equals(\"openinxmleditor\")) {\n final NotificationPopupView view = new NotificationPopupView();\n activeNotifications.add(view);\n view.setPopupPosition(getMargin(),\n activeNotifications.size() * SPACING);\n\n view.setNotification(event.getNotification());\n view.setType(event.getType());\n view.setNotificationWidth(getWidth() + \"px\");\n view.show(new Command() {\n\n @Override\n public void execute() {\n //The notification has been shown and can now be removed\n deactiveNotifications.add(view);\n remove();\n }\n });\n }\n }\n }", "public Metadata updateMetadata(Metadata metadata) {\n String scope;\n if (metadata.getScope().equals(Metadata.GLOBAL_METADATA_SCOPE)) {\n scope = Metadata.GLOBAL_METADATA_SCOPE;\n } else {\n scope = Metadata.ENTERPRISE_METADATA_SCOPE;\n }\n\n URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(),\n scope, metadata.getTemplateName());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"PUT\");\n request.addHeader(\"Content-Type\", \"application/json-patch+json\");\n request.setBody(metadata.getPatch());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n return new Metadata(JsonObject.readFrom(response.getJSON()));\n }", "public static base_response add(nitro_service client, ntpserver resource) throws Exception {\n\t\tntpserver addresource = new ntpserver();\n\t\taddresource.serverip = resource.serverip;\n\t\taddresource.servername = resource.servername;\n\t\taddresource.minpoll = resource.minpoll;\n\t\taddresource.maxpoll = resource.maxpoll;\n\t\taddresource.autokey = resource.autokey;\n\t\taddresource.key = resource.key;\n\t\treturn addresource.add_resource(client);\n\t}", "public static <T> T withObjectStreams(Socket socket, @ClosureParams(value=SimpleType.class, options={\"java.io.ObjectInputStream\",\"java.io.ObjectOutputStream\"}) Closure<T> closure) throws IOException {\n InputStream input = socket.getInputStream();\n OutputStream output = socket.getOutputStream();\n ObjectOutputStream oos = new ObjectOutputStream(output);\n ObjectInputStream ois = new ObjectInputStream(input);\n try {\n T result = closure.call(new Object[]{ois, oos});\n\n InputStream temp1 = ois;\n ois = null;\n temp1.close();\n temp1 = input;\n input = null;\n temp1.close();\n OutputStream temp2 = oos;\n oos = null;\n temp2.close();\n temp2 = output;\n output = null;\n temp2.close();\n\n return result;\n } finally {\n closeWithWarning(ois);\n closeWithWarning(input);\n closeWithWarning(oos);\n closeWithWarning(output);\n }\n }", "public PhotoList<Photo> getClusterPhotos(String tag, String clusterId) throws FlickrException {\n\n PhotoList<Photo> photos = new PhotoList<Photo>();\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_CLUSTER_PHOTOS);\n\n parameters.put(\"tag\", tag);\n parameters.put(\"cluster_id\", clusterId);\n\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\n if (response.isError()) {\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\n }\n\n Element photosElement = response.getPayload();\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\n photos.setPage(\"1\");\n photos.setPages(\"1\");\n photos.setPerPage(\"\" + photoNodes.getLength());\n photos.setTotal(\"\" + photoNodes.getLength());\n for (int i = 0; i < photoNodes.getLength(); i++) {\n Element photoElement = (Element) photoNodes.item(i);\n photos.add(PhotoUtils.createPhoto(photoElement));\n }\n return photos;\n }", "private void processRedirect(String stringStatusCode,\n HttpMethod httpMethodProxyRequest,\n HttpServletRequest httpServletRequest,\n HttpServletResponse httpServletResponse) throws Exception {\n // Check if the proxy response is a redirect\n // The following code is adapted from\n // org.tigris.noodle.filters.CheckForRedirect\n // Hooray for open source software\n\n String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();\n if (stringLocation == null) {\n throw new ServletException(\"Received status code: \"\n + stringStatusCode + \" but no \"\n + STRING_LOCATION_HEADER\n + \" header was found in the response\");\n }\n // Modify the redirect to go to this proxy servlet rather than the proxied host\n String stringMyHostName = httpServletRequest.getServerName();\n if (httpServletRequest.getServerPort() != 80) {\n stringMyHostName += \":\" + httpServletRequest.getServerPort();\n }\n stringMyHostName += httpServletRequest.getContextPath();\n httpServletResponse.sendRedirect(stringLocation.replace(\n getProxyHostAndPort() + this.getProxyPath(),\n stringMyHostName));\n }", "public static base_response update(nitro_service client, systemuser resource) throws Exception {\n\t\tsystemuser updateresource = new systemuser();\n\t\tupdateresource.username = resource.username;\n\t\tupdateresource.password = resource.password;\n\t\tupdateresource.externalauth = resource.externalauth;\n\t\tupdateresource.promptstring = resource.promptstring;\n\t\tupdateresource.timeout = resource.timeout;\n\t\treturn updateresource.update_resource(client);\n\t}", "public byte[] getValueAsArray() {\n ByteBuffer buffer = getValue();\n byte[] result = new byte[buffer.remaining()];\n buffer.get(result);\n return result;\n }", "public ValueContainer[] getValuesForObject(FieldDescriptor[] fields, Object obj, boolean convertToSql, boolean assignAutoincrement) throws PersistenceBrokerException\r\n {\r\n ValueContainer[] result = new ValueContainer[fields.length];\r\n\r\n for(int i = 0; i < fields.length; i++)\r\n {\r\n FieldDescriptor fd = fields[i];\r\n Object cv = fd.getPersistentField().get(obj);\r\n\r\n /*\r\n handle autoincrement attributes if\r\n - is a autoincrement field\r\n - field represents a 'null' value, is nullified\r\n and generate a new value\r\n */\r\n if(assignAutoincrement && fd.isAutoIncrement() && representsNull(fd, cv))\r\n {\r\n /*\r\n setAutoIncrementValue returns a value that is\r\n properly typed for the java-world. This value\r\n needs to be converted to it's corresponding\r\n sql type so that the entire result array contains\r\n objects that are properly typed for sql.\r\n */\r\n cv = setAutoIncrementValue(fd, obj);\r\n }\r\n if(convertToSql)\r\n {\r\n // apply type and value conversion\r\n cv = fd.getFieldConversion().javaToSql(cv);\r\n }\r\n // create ValueContainer\r\n result[i] = new ValueContainer(cv, fd.getJdbcType());\r\n }\r\n return result;\r\n }" ]
Start offering shared dbserver sessions. @throws SocketException if there is a problem opening connections
[ "public synchronized void start() throws SocketException {\n if (!isRunning()) {\n DeviceFinder.getInstance().addLifecycleListener(lifecycleListener);\n DeviceFinder.getInstance().addDeviceAnnouncementListener(announcementListener);\n DeviceFinder.getInstance().start();\n for (DeviceAnnouncement device: DeviceFinder.getInstance().getCurrentDevices()) {\n requestPlayerDBServerPort(device);\n }\n\n new Thread(null, new Runnable() {\n @Override\n public void run() {\n while (isRunning()) {\n try {\n Thread.sleep(500);\n } catch (InterruptedException e) {\n logger.warn(\"Interrupted sleeping to close idle dbserver clients\");\n }\n closeIdleClients();\n }\n logger.info(\"Idle dbserver client closer shutting down.\");\n }\n }, \"Idle dbserver client closer\").start();\n\n running.set(true);\n deliverLifecycleAnnouncement(logger, true);\n }\n }" ]
[ "public boolean isEmbeddedProperty(String targetTypeName, List<String> namesWithoutAlias) {\n\t\tOgmEntityPersister persister = getPersister( targetTypeName );\n\t\tType propertyType = persister.getPropertyType( namesWithoutAlias.get( 0 ) );\n\t\tif ( propertyType.isComponentType() ) {\n\t\t\t// Embedded\n\t\t\treturn true;\n\t\t}\n\t\telse if ( propertyType.isAssociationType() ) {\n\t\t\tJoinable associatedJoinable = ( (AssociationType) propertyType ).getAssociatedJoinable( persister.getFactory() );\n\t\t\tif ( associatedJoinable.isCollection() ) {\n\t\t\t\tOgmCollectionPersister collectionPersister = (OgmCollectionPersister) associatedJoinable;\n\t\t\t\treturn collectionPersister.getType().isComponentType();\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "public void setValue(int numStrings, String[] newValues) {\n value.clear();\n if (numStrings == newValues.length) {\n for (int i = 0; i < newValues.length; i++) {\n value.add(newValues[i]);\n }\n }\n else {\n Log.e(TAG, \"X3D MFString setValue() numStrings not equal total newValues\");\n }\n }", "public static lbvserver_scpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_scpolicy_binding obj = new lbvserver_scpolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_scpolicy_binding response[] = (lbvserver_scpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static AbstractReportGenerator generateHtml5Report() {\n AbstractReportGenerator report;\n try {\n Class<?> aClass = new ReportGenerator().getClass().getClassLoader()\n .loadClass( \"com.tngtech.jgiven.report.html5.Html5ReportGenerator\" );\n report = (AbstractReportGenerator) aClass.newInstance();\n } catch( ClassNotFoundException e ) {\n throw new JGivenInstallationException( \"The JGiven HTML5 Report Generator seems not to be on the classpath.\\n\"\n + \"Ensure that you have a dependency to jgiven-html5-report.\" );\n } catch( Exception e ) {\n throw new JGivenInternalDefectException( \"The HTML5 Report Generator could not be instantiated.\", e );\n }\n return report;\n }", "private void processCalendarData(List<ProjectCalendar> calendars) throws SQLException\n {\n for (ProjectCalendar calendar : calendars)\n {\n processCalendarData(calendar, getRows(\"SELECT * FROM MSP_CALENDAR_DATA WHERE PROJ_ID=? AND CAL_UID=?\", m_projectID, calendar.getUniqueID()));\n }\n }", "public void createLinks(ServiceReference<S> declarationBinderRef) {\n for (D declaration : linkerManagement.getMatchedDeclaration()) {\n if (linkerManagement.canBeLinked(declaration, declarationBinderRef)) {\n linkerManagement.link(declaration, declarationBinderRef);\n }\n }\n }", "public static String replaceFirst(final CharSequence self, final CharSequence regex, final CharSequence replacement) {\n return self.toString().replaceFirst(regex.toString(), replacement.toString());\n }", "protected NodeData createPageStyle()\n {\n NodeData ret = createBlockStyle();\n TermFactory tf = CSSFactory.getTermFactory();\n ret.push(createDeclaration(\"position\", tf.createIdent(\"relative\")));\n\t\tret.push(createDeclaration(\"border-width\", tf.createLength(1f, Unit.px)));\n\t\tret.push(createDeclaration(\"border-style\", tf.createIdent(\"solid\")));\n\t\tret.push(createDeclaration(\"border-color\", tf.createColor(0, 0, 255)));\n\t\tret.push(createDeclaration(\"margin\", tf.createLength(0.5f, Unit.em)));\n\t\t\n PDRectangle layout = getCurrentMediaBox();\n if (layout != null)\n {\n float w = layout.getWidth();\n float h = layout.getHeight();\n final int rot = pdpage.getRotation();\n if (rot == 90 || rot == 270)\n {\n float x = w; w = h; h = x;\n }\n \n ret.push(createDeclaration(\"width\", tf.createLength(w, unit)));\n ret.push(createDeclaration(\"height\", tf.createLength(h, unit)));\n }\n else\n log.warn(\"No media box found\");\n \n return ret;\n }", "@SuppressForbidden(\"legitimate sysstreams.\")\n private static void redirectStreams(final Serializer serializer, final boolean flushFrequently) {\n final PrintStream origSysOut = System.out;\n final PrintStream origSysErr = System.err;\n\n // Set warnings stream to System.err.\n warnings = System.err;\n AccessController.doPrivileged(new PrivilegedAction<Void>() {\n @SuppressForbidden(\"legitimate PrintStream with default charset.\")\n @Override\n public Void run() {\n System.setOut(new PrintStream(new BufferedOutputStream(new ChunkedStream() {\n @Override\n public void write(byte[] b, int off, int len) throws IOException {\n if (multiplexStdStreams) {\n origSysOut.write(b, off, len);\n }\n serializer.serialize(new AppendStdOutEvent(b, off, len));\n if (flushFrequently) serializer.flush();\n }\n })));\n\n System.setErr(new PrintStream(new BufferedOutputStream(new ChunkedStream() {\n @Override\n public void write(byte[] b, int off, int len) throws IOException {\n if (multiplexStdStreams) {\n origSysErr.write(b, off, len);\n }\n serializer.serialize(new AppendStdErrEvent(b, off, len));\n if (flushFrequently) serializer.flush();\n }\n })));\n return null;\n }\n });\n }" ]
Resize the key data area. This function will truncate the keys if the initial setting was too large. @oaran numKeys the desired number of keys
[ "public void resizeKeys(int numKeys)\n {\n int n = numKeys * mFloatsPerKey;\n if (mKeys.length == n)\n {\n return;\n }\n float[] newKeys = new float[n];\n n = Math.min(n, mKeys.length);\n\n System.arraycopy(mKeys, 0, newKeys, 0, n);\n mKeys = newKeys;\n mFloatInterpolator.setKeyData(mKeys);\n }" ]
[ "public static void validateObserverMethod(ObserverMethod<?> observerMethod, BeanManager beanManager, ObserverMethod<?> originalObserverMethod) {\n Set<Annotation> qualifiers = observerMethod.getObservedQualifiers();\n if (observerMethod.getBeanClass() == null) {\n throw EventLogger.LOG.observerMethodsMethodReturnsNull(\"getBeanClass\", observerMethod);\n }\n if (observerMethod.getObservedType() == null) {\n throw EventLogger.LOG.observerMethodsMethodReturnsNull(\"getObservedType\", observerMethod);\n }\n Bindings.validateQualifiers(qualifiers, beanManager, observerMethod, \"ObserverMethod.getObservedQualifiers\");\n if (observerMethod.getReception() == null) {\n throw EventLogger.LOG.observerMethodsMethodReturnsNull(\"getReception\", observerMethod);\n }\n if (observerMethod.getTransactionPhase() == null) {\n throw EventLogger.LOG.observerMethodsMethodReturnsNull(\"getTransactionPhase\", observerMethod);\n }\n if (originalObserverMethod != null && (!observerMethod.getBeanClass().equals(originalObserverMethod.getBeanClass()))) {\n throw EventLogger.LOG.beanClassMismatch(originalObserverMethod, observerMethod);\n }\n if (!(observerMethod instanceof SyntheticObserverMethod) && !hasNotifyOverriden(observerMethod.getClass(), observerMethod)) {\n throw EventLogger.LOG.notifyMethodNotImplemented(observerMethod);\n }\n }", "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 }", "public static base_response delete(nitro_service client, String username) throws Exception {\n\t\tsystemuser deleteresource = new systemuser();\n\t\tdeleteresource.username = username;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public static void downloadUrl(String stringUrl, Map<String, String> parameters, File fileToSave)\n throws IOException {\n URL url = new URL(stringUrl);\n HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n conn.setFollowRedirects(true);\n \n if (parameters != null) {\n for (Entry<String, String> entry : parameters.entrySet()) {\n conn.addRequestProperty(entry.getKey(), entry.getValue());\n }\n }\n\n\n boolean redirect = false;\n\n // normally, 3xx is redirect\n int status = conn.getResponseCode();\n if (status != HttpURLConnection.HTTP_OK) {\n if (status == HttpURLConnection.HTTP_MOVED_TEMP\n || status == HttpURLConnection.HTTP_MOVED_PERM\n || status == HttpURLConnection.HTTP_SEE_OTHER)\n redirect = true;\n }\n\n if (redirect) {\n\n // get redirect url from \"location\" header field\n String newUrl = conn.getHeaderField(\"Location\");\n\n // get the cookie if need, for login\n String cookies = conn.getHeaderField(\"Set-Cookie\");\n\n // open the new connnection again\n conn = (HttpURLConnection) new URL(newUrl).openConnection();\n conn.setRequestProperty(\"Cookie\", cookies);\n\n }\n \n byte[] data = MyStreamUtils.readContentBytes(conn.getInputStream());\n FileOutputStream fos = new FileOutputStream(fileToSave);\n fos.write(data);\n fos.close();\n }", "public static String writeSingleClientConfigAvro(Properties props) {\n // TODO: Use a dedicated json lib. We shouldn't be manually manipulating json...\n String avroConfig = \"\";\n Boolean firstProp = true;\n for(String key: props.stringPropertyNames()) {\n if(firstProp) {\n firstProp = false;\n } else {\n avroConfig = avroConfig + \",\\n\";\n }\n avroConfig = avroConfig + \"\\t\\t\\\"\" + key + \"\\\": \\\"\" + props.getProperty(key) + \"\\\"\";\n }\n if(avroConfig.isEmpty()) {\n return \"{}\";\n } else {\n return \"{\\n\" + avroConfig + \"\\n\\t}\";\n }\n }", "public boolean needsRefresh() {\n boolean needsRefresh;\n\n this.refreshLock.readLock().lock();\n long now = System.currentTimeMillis();\n long tokenDuration = (now - this.lastRefresh);\n needsRefresh = (tokenDuration >= this.expires - REFRESH_EPSILON);\n this.refreshLock.readLock().unlock();\n\n return needsRefresh;\n }", "public static String urlEncode(String path) throws URISyntaxException {\n if (isNullOrEmpty(path)) return path;\n\n return UrlEscapers.urlFragmentEscaper().escape(path);\n }", "@VisibleForTesting\n protected static double getNearestNiceValue(\n final double value, final DistanceUnit scaleUnit, final boolean lockUnits) {\n DistanceUnit bestUnit = bestUnit(scaleUnit, value, lockUnits);\n double factor = scaleUnit.convertTo(1.0, bestUnit);\n\n // nearest power of 10 lower than value\n int digits = (int) Math.floor((Math.log(value * factor) / Math.log(10)));\n double pow10 = Math.pow(10, digits);\n\n // ok, find first character\n double firstChar = value * factor / pow10;\n\n // right, put it into the correct bracket\n int barLen;\n if (firstChar >= 10.0) {\n barLen = 10;\n } else if (firstChar >= 5.0) {\n barLen = 5;\n } else if (firstChar >= 2.0) {\n barLen = 2;\n } else {\n barLen = 1;\n }\n\n // scale it up the correct power of 10\n return barLen * pow10 / factor;\n }", "public static ContainerDescription getContainerDescription(final ModelControllerClient client) throws IOException, OperationExecutionException {\n return DefaultContainerDescription.lookup(Assert.checkNotNullParam(\"client\", client));\n }" ]
Does the slice contain only 7-bit ASCII characters.
[ "public static boolean isAscii(Slice utf8)\n {\n int length = utf8.length();\n int offset = 0;\n\n // Length rounded to 8 bytes\n int length8 = length & 0x7FFF_FFF8;\n for (; offset < length8; offset += 8) {\n if ((utf8.getLongUnchecked(offset) & TOP_MASK64) != 0) {\n return false;\n }\n }\n // Enough bytes left for 32 bits?\n if (offset + 4 < length) {\n if ((utf8.getIntUnchecked(offset) & TOP_MASK32) != 0) {\n return false;\n }\n\n offset += 4;\n }\n // Do the rest one by one\n for (; offset < length; offset++) {\n if ((utf8.getByteUnchecked(offset) & 0x80) != 0) {\n return false;\n }\n }\n\n return true;\n }" ]
[ "private Object getLiteralValue(Expression expression) {\n\t\tif (!(expression instanceof Literal)) {\n\t\t\tthrow new IllegalArgumentException(\"Expression \" + expression + \" is not a Literal.\");\n\t\t}\n\t\treturn ((Literal) expression).getValue();\n\t}", "@UiHandler(\"m_seriesCheckBox\")\n void onSeriesChange(ValueChangeEvent<Boolean> event) {\n\n if (handleChange()) {\n m_controller.setIsSeries(event.getValue());\n }\n }", "public void generateTracedFile(final IFileSystemAccess2 fsa, final String path, final EObject rootTrace, final StringConcatenationClient code) {\n final CompositeGeneratorNode node = this.trace(rootTrace, code);\n this.generateTracedFile(fsa, path, node);\n }", "@Override\n public void registerAttributes(ManagementResourceRegistration resourceRegistration) {\n for (AttributeAccess attr : attributes.values()) {\n resourceRegistration.registerReadOnlyAttribute(attr.getAttributeDefinition(), null);\n }\n }", "public void setFromJSON(Context context, JSONObject properties) {\n String backgroundResStr = optString(properties, Properties.background);\n if (backgroundResStr != null && !backgroundResStr.isEmpty()) {\n final int backgroundResId = getId(context, backgroundResStr, \"drawable\");\n setBackGround(context.getResources().getDrawable(backgroundResId, null));\n }\n\n setBackgroundColor(getJSONColor(properties, Properties.background_color, getBackgroundColor()));\n setGravity(optInt(properties, TextContainer.Properties.gravity, getGravity()));\n setRefreshFrequency(optEnum(properties, Properties.refresh_freq, getRefreshFrequency()));\n setTextColor(getJSONColor(properties, Properties.text_color, getTextColor()));\n setText(optString(properties, Properties.text, (String) getText()));\n setTextSize(optFloat(properties, Properties.text_size, getTextSize()));\n\n final JSONObject typefaceJson = optJSONObject(properties, Properties.typeface);\n\n if (typefaceJson != null) {\n try {\n Typeface typeface = WidgetLib.getTypefaceManager().getTypeface(typefaceJson);\n setTypeface(typeface);\n } catch (Throwable e) {\n Log.e(TAG, e, \"Couldn't set typeface from properties: %s\", typefaceJson);\n }\n }\n }", "public Date getStart()\n {\n Date result = null;\n for (ResourceAssignment assignment : m_assignments)\n {\n if (result == null || DateHelper.compare(result, assignment.getStart()) > 0)\n {\n result = assignment.getStart();\n }\n }\n return (result);\n }", "public void racRent() {\n\t\tpos = pos - 1;\n\t\tString userName = CarSearch.getLastSearchParams()[0];\n\t\tString pickupDate = CarSearch.getLastSearchParams()[1];\n\t\tString returnDate = CarSearch.getLastSearchParams()[2];\n\t\tthis.searcher.search(userName, pickupDate, returnDate);\n\t\tif (searcher!=null && searcher.getCars()!= null && pos < searcher.getCars().size() && searcher.getCars().get(pos) != null) {\n\t\t\tRESStatusType resStatus = reserver.reserveCar(searcher.getCustomer()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, searcher.getCars().get(pos)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, pickupDate\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, returnDate);\n\t\t\tConfirmationType confirm = reserver.getConfirmation(resStatus\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, searcher.getCustomer()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, searcher.getCars().get(pos)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, pickupDate\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, returnDate);\n\n\t\t\tRESCarType car = confirm.getCar();\n\t\t\tCustomerDetailsType customer = confirm.getCustomer();\n\t\t\t\n\t\t\tSystem.out.println(MessageFormat.format(CONFIRMATION\n\t\t\t\t\t, confirm.getDescription()\n\t\t\t\t\t, confirm.getReservationId()\n\t\t\t\t\t, customer.getName()\n\t\t\t\t\t, customer.getEmail()\n\t\t\t\t\t, customer.getCity()\n\t\t\t\t\t, customer.getStatus()\n\t\t\t\t\t, car.getBrand()\n\t\t\t\t\t, car.getDesignModel()\n\t\t\t\t\t, confirm.getFromDate()\n\t\t\t\t\t, confirm.getToDate()\n\t\t\t\t\t, padl(car.getRateDay(), 10)\n\t\t\t\t\t, padl(car.getRateWeekend(), 10)\n\t\t\t\t\t, padl(confirm.getCreditPoints().toString(), 7)));\n\t\t} else {\n\t\t\tSystem.out.println(\"Invalid selection: \" + (pos+1)); //$NON-NLS-1$\n\t\t}\n\t}", "public void leave(String groupId, Boolean deletePhotos) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_LEAVE);\r\n parameters.put(\"group_id\", groupId);\r\n parameters.put(\"delete_photos\", deletePhotos);\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }", "private Project.Tasks.Task.PredecessorLink writePredecessor(Integer taskID, RelationType type, Duration lag)\n {\n Project.Tasks.Task.PredecessorLink link = m_factory.createProjectTasksTaskPredecessorLink();\n\n link.setPredecessorUID(NumberHelper.getBigInteger(taskID));\n link.setType(BigInteger.valueOf(type.getValue()));\n link.setCrossProject(Boolean.FALSE); // SF-300: required to keep P6 happy when importing MSPDI files\n\n if (lag != null && lag.getDuration() != 0)\n {\n double linkLag = lag.getDuration();\n if (lag.getUnits() != TimeUnit.PERCENT && lag.getUnits() != TimeUnit.ELAPSED_PERCENT)\n {\n linkLag = 10.0 * Duration.convertUnits(linkLag, lag.getUnits(), TimeUnit.MINUTES, m_projectFile.getProjectProperties()).getDuration();\n }\n link.setLinkLag(BigInteger.valueOf((long) linkLag));\n link.setLagFormat(DatatypeConverter.printDurationTimeUnits(lag.getUnits(), false));\n }\n else\n {\n // SF-329: default required to keep Powerproject happy when importing MSPDI files\n link.setLinkLag(BIGINTEGER_ZERO);\n link.setLagFormat(DatatypeConverter.printDurationTimeUnits(m_projectFile.getProjectProperties().getDefaultDurationUnits(), false));\n }\n\n return (link);\n }" ]
Checks if this child holds the current active state. If the child is or contains the active state it is applied.
[ "protected void checkActiveState(Widget child) {\n // Check if this widget has a valid href\n String href = child.getElement().getAttribute(\"href\");\n String url = Window.Location.getHref();\n int pos = url.indexOf(\"#\");\n String location = pos >= 0 ? url.substring(pos, url.length()) : \"\";\n\n if (!href.isEmpty() && location.startsWith(href)) {\n ListItem li = findListItemParent(child);\n if (li != null) {\n makeActive(li);\n }\n } else if (child instanceof HasWidgets) {\n // Recursive check\n for (Widget w : (HasWidgets) child) {\n checkActiveState(w);\n }\n }\n }" ]
[ "public List<Integer> getConnectionRetries() {\n List<Integer> items = new ArrayList<Integer>();\n for (int i = 0; i < 10; i++) {\n items.add(i);\n }\n return items;\n }", "private void addForward(AnalyticModel model, double fixingTime, RandomVariable forward, boolean isParameter) {\n\t\tdouble interpolationEntitiyTime;\n\t\tRandomVariable interpolationEntityForwardValue;\n\t\tswitch(interpolationEntityForward) {\n\t\tcase FORWARD:\n\t\tdefault:\n\t\t\tinterpolationEntitiyTime = fixingTime;\n\t\t\tinterpolationEntityForwardValue = forward;\n\t\t\tbreak;\n\t\tcase FORWARD_TIMES_DISCOUNTFACTOR:\n\t\t\tinterpolationEntitiyTime = fixingTime;\n\t\t\tinterpolationEntityForwardValue = forward.mult(model.getDiscountCurve(getDiscountCurveName()).getValue(model, fixingTime+getPaymentOffset(fixingTime)));\n\t\t\tbreak;\n\t\tcase ZERO:\n\t\t{\n\t\t\tdouble paymentOffset = getPaymentOffset(fixingTime);\n\t\t\tinterpolationEntitiyTime = fixingTime+paymentOffset;\n\t\t\tinterpolationEntityForwardValue = forward.mult(paymentOffset).add(1.0).log().div(paymentOffset);\n\t\t\tbreak;\n\t\t}\n\t\tcase DISCOUNTFACTOR:\n\t\t{\n\t\t\tdouble paymentOffset = getPaymentOffset(fixingTime);\n\t\t\tinterpolationEntitiyTime\t\t= fixingTime+paymentOffset;\n\t\t\tinterpolationEntityForwardValue = getValue(fixingTime).div(forward.mult(paymentOffset).add(1.0));\n\t\t\tbreak;\n\t\t}\n\t\t}\n\t\tsuper.addPoint(interpolationEntitiyTime, interpolationEntityForwardValue, isParameter);\n\t}", "public static Value.Builder makeValue(Date date) {\n return Value.newBuilder().setTimestampValue(toTimestamp(date.getTime() * 1000L));\n }", "public Point2D.Double minDistancePointSpline(Point2D.Double p, int nPointsPerSegment){\n\t\t\tdouble minDistance = Double.MAX_VALUE;\n\t\t\tPoint2D.Double minDistancePoint = null;\n\t\t int numberOfSplines = spline.getN();\n\t\t double[] knots = spline.getKnots();\n\t\t for(int i = 0; i < numberOfSplines; i++){\n\t\t \tdouble x = knots[i];\n\t\t \tdouble stopx = knots[i+1];\n\t\t \tdouble dx = (stopx-x)/nPointsPerSegment;\n\t\t \t\n\t\t \tfor(int j = 0; j < nPointsPerSegment; j++){\n\t\t \t\tPoint2D.Double candidate = new Point2D.Double(x, spline.value(x));\n\t\t \t\tdouble d = p.distance(candidate);\n\t\t \t\tif(d<minDistance){\n\t\t \t\t\tminDistance = d;\n\t\t \t\t\tminDistancePoint = candidate;\n\t\t \t\t}\n\t\t \t\tx += dx;\n\t\t \t}\n\t\t \t\n\t\t }\n\t\t return minDistancePoint;\n\t}", "private static void createDirectory(Path path) throws IOException {\n\t\ttry {\n\t\t\tFiles.createDirectory(path);\n\t\t} catch (FileAlreadyExistsException e) {\n\t\t\tif (!Files.isDirectory(path)) {\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t}", "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 }", "@Override\r\n public <VALUEBASE, VALUE extends VALUEBASE, KEY extends Key<CoreMap, VALUEBASE>>\r\n VALUE set(Class<KEY> key, VALUE value) {\r\n \r\n if (immutableKeys.contains(key)) {\r\n throw new HashableCoreMapException(\"Attempt to change value \" +\r\n \t\t\"of immutable field \"+key.getSimpleName());\r\n }\r\n \r\n return super.set(key, value);\r\n }", "public List<File> getAutoAttachCacheFiles() {\n ArrayList<File> currentFiles = new ArrayList<File>(autoAttachCacheFiles);\n Collections.sort(currentFiles, new Comparator<File>() {\n @Override\n public int compare(File o1, File o2) {\n return o1.getName().compareTo(o2.getName());\n }\n });\n return Collections.unmodifiableList(currentFiles);\n }", "@Deprecated\n private static ListAttributeDefinition wrapAsList(final AttributeDefinition def) {\n final ListAttributeDefinition list = new ListAttributeDefinition(new SimpleListAttributeDefinition.Builder(def.getName(), def)\n .setElementValidator(def.getValidator())) {\n\n\n @Override\n public ModelNode getNoTextDescription(boolean forOperation) {\n final ModelNode model = super.getNoTextDescription(forOperation);\n setValueType(model);\n return model;\n }\n\n @Override\n protected void addValueTypeDescription(final ModelNode node, final ResourceBundle bundle) {\n setValueType(node);\n }\n\n @Override\n public void marshallAsElement(final ModelNode resourceModel, final boolean marshalDefault, final XMLStreamWriter writer) throws XMLStreamException {\n throw new RuntimeException();\n }\n\n @Override\n protected void addAttributeValueTypeDescription(ModelNode node, ResourceDescriptionResolver resolver, Locale locale, ResourceBundle bundle) {\n setValueType(node);\n }\n\n @Override\n protected void addOperationParameterValueTypeDescription(ModelNode node, String operationName, ResourceDescriptionResolver resolver, Locale locale, ResourceBundle bundle) {\n setValueType(node);\n }\n\n private void setValueType(ModelNode node) {\n node.get(ModelDescriptionConstants.VALUE_TYPE).set(ModelType.STRING);\n }\n };\n return list;\n }" ]
Get a property as a boolean or throw exception. @param key the property name
[ "@Override\n public final boolean getBool(final String key) {\n Boolean result = optBool(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }" ]
[ "public static void printHelp(final Options options) {\n Collection<Option> c = options.getOptions();\n System.out.println(\"Command line options are:\");\n int longestLongOption = 0;\n for (Option op : c) {\n if (op.getLongOpt().length() > longestLongOption) {\n longestLongOption = op.getLongOpt().length();\n }\n }\n\n longestLongOption += 2;\n String spaces = StringUtils.repeat(\" \", longestLongOption);\n\n for (Option op : c) {\n System.out.print(\"\\t-\" + op.getOpt() + \" --\" + op.getLongOpt());\n if (op.getLongOpt().length() < spaces.length()) {\n System.out.print(spaces.substring(op.getLongOpt().length()));\n } else {\n System.out.print(\" \");\n }\n System.out.println(op.getDescription());\n }\n }", "protected Class getClassCacheEntry(String name) {\n if (name == null) return null;\n synchronized (classCache) {\n return classCache.get(name);\n }\n }", "protected void propagateOnNoPick(GVRPicker picker)\n {\n if (mEventOptions.contains(EventOptions.SEND_PICK_EVENTS))\n {\n if (mEventOptions.contains(EventOptions.SEND_TO_LISTENERS))\n {\n getGVRContext().getEventManager().sendEvent(this, IPickEvents.class, \"onNoPick\", picker);\n }\n if (mEventOptions.contains(EventOptions.SEND_TO_SCENE) && (mScene != null))\n {\n getGVRContext().getEventManager().sendEvent(mScene, IPickEvents.class, \"onNoPick\", picker);\n }\n }\n }", "public static lbvserver[] get(nitro_service service) throws Exception{\n\t\tlbvserver obj = new lbvserver();\n\t\tlbvserver[] response = (lbvserver[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public void updateColor(TestColor color) {\n\n switch (color) {\n case green:\n m_forwardButton.setEnabled(true);\n m_confirmCheckbox.setVisible(false);\n m_status.setValue(STATUS_GREEN);\n break;\n case yellow:\n m_forwardButton.setEnabled(false);\n m_confirmCheckbox.setVisible(true);\n m_status.setValue(STATUS_YELLOW);\n break;\n case red:\n m_forwardButton.setEnabled(false);\n m_confirmCheckbox.setVisible(true);\n m_status.setValue(STATUS_RED);\n break;\n default:\n break;\n }\n }", "public static base_responses flush(nitro_service client, cacheobject resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcacheobject flushresources[] = new cacheobject[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tflushresources[i] = new cacheobject();\n\t\t\t\tflushresources[i].locator = resources[i].locator;\n\t\t\t\tflushresources[i].url = resources[i].url;\n\t\t\t\tflushresources[i].host = resources[i].host;\n\t\t\t\tflushresources[i].port = resources[i].port;\n\t\t\t\tflushresources[i].groupname = resources[i].groupname;\n\t\t\t\tflushresources[i].httpmethod = resources[i].httpmethod;\n\t\t\t\tflushresources[i].force = resources[i].force;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, flushresources,\"flush\");\n\t\t}\n\t\treturn result;\n\t}", "public static String digestToFileName(String digest) {\n if (StringUtils.startsWith(digest, \"sha1\")) {\n return \"manifest.json\";\n }\n return getShaVersion(digest) + \"__\" + getShaValue(digest);\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 static void initializeDomainRegistry(final TransformerRegistry registry) {\n\n //The chains for transforming will be as follows\n //For JBoss EAP: 8.0.0 -> 5.0.0 -> 4.0.0 -> 1.8.0 -> 1.7.0 -> 1.6.0 -> 1.5.0\n\n registerRootTransformers(registry);\n registerChainedManagementTransformers(registry);\n registerChainedServerGroupTransformers(registry);\n registerProfileTransformers(registry);\n registerSocketBindingGroupTransformers(registry);\n registerDeploymentTransformers(registry);\n }" ]
Get the active operation. @param id the active operation id @return the active operation, {@code null} if if there is no registered operation
[ "protected <T, A> ActiveOperation<T, A> getActiveOperation(final Integer id) {\n //noinspection unchecked\n return (ActiveOperation<T, A>) activeRequests.get(id);\n }" ]
[ "public void info(Throwable throwable, String msg, Object[] argArray) {\n\t\tlogIfEnabled(Level.INFO, throwable, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, argArray);\n\t}", "public void value2x2( double a11 , double a12, double a21 , double a22 )\n {\n // apply a rotators such that th a11 and a22 elements are the same\n double c,s;\n\n if( a12 + a21 == 0 ) { // is this pointless since\n c = s = 1.0 / Math.sqrt(2);\n } else {\n double aa = (a11-a22);\n double bb = (a12+a21);\n\n double t_hat = aa/bb;\n double t = t_hat/(1.0 + Math.sqrt(1.0+t_hat*t_hat));\n\n c = 1.0/ Math.sqrt(1.0+t*t);\n s = c*t;\n }\n\n double c2 = c*c;\n double s2 = s*s;\n double cs = c*s;\n\n double b11 = c2*a11 + s2*a22 - cs*(a12+a21);\n double b12 = c2*a12 - s2*a21 + cs*(a11-a22);\n double b21 = c2*a21 - s2*a12 + cs*(a11-a22);\n// double b22 = c2*a22 + s2*a11 + cs*(a12+a21);\n\n // apply second rotator to make A upper triangular if real eigenvalues\n if( b21*b12 >= 0 ) {\n if( b12 == 0 ) {\n c = 0;\n s = 1;\n } else {\n s = Math.sqrt(b21/(b12+b21));\n c = Math.sqrt(b12/(b12+b21));\n }\n\n// c2 = b12;//c*c;\n// s2 = b21;//s*s;\n cs = c*s;\n\n a11 = b11 - cs*(b12 + b21);\n// a12 = c2*b12 - s2*b21;\n// a21 = c2*b21 - s2*b12;\n a22 = b11 + cs*(b12 + b21);\n\n value0.real = a11;\n value1.real = a22;\n\n value0.imaginary = value1.imaginary = 0;\n\n } else {\n value0.real = value1.real = b11;\n value0.imaginary = Math.sqrt(-b21*b12);\n value1.imaginary = -value0.imaginary;\n }\n }", "public 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}", "HtmlTag attr(String name, String value) {\n if (attrs == null) {\n attrs = new HashMap<>();\n }\n attrs.put(name, value);\n return this;\n }", "public static List<Expression> getVariableExpressions(DeclarationExpression declarationExpression) {\r\n Expression leftExpression = declarationExpression.getLeftExpression();\r\n\r\n // !important: performance enhancement\r\n if (leftExpression instanceof ArrayExpression) {\r\n List<Expression> expressions = ((ArrayExpression) leftExpression).getExpressions();\r\n return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions;\r\n } else if (leftExpression instanceof ListExpression) {\r\n List<Expression> expressions = ((ListExpression) leftExpression).getExpressions();\r\n return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions;\r\n } else if (leftExpression instanceof TupleExpression) {\r\n List<Expression> expressions = ((TupleExpression) leftExpression).getExpressions();\r\n return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions;\r\n } else if (leftExpression instanceof VariableExpression) {\r\n return Arrays.asList(leftExpression);\r\n }\r\n // todo: write warning\r\n return Collections.emptyList();\r\n }", "public RenderScript getRenderScript() {\n if (renderScript == null) {\n renderScript = RenderScript.create(context, renderScriptContextType);\n }\n return renderScript;\n }", "void decodeContentType(String rawLine) {\r\n int slash = rawLine.indexOf('/');\r\n if (slash == -1) {\r\n// if (DEBUG) getLogger().debug(\"decoding ... no slash found\");\r\n return;\r\n } else {\r\n primaryType = rawLine.substring(0, slash).trim();\r\n }\r\n int semicolon = rawLine.indexOf(';');\r\n if (semicolon == -1) {\r\n// if (DEBUG) getLogger().debug(\"decoding ... no semicolon found\");\r\n secondaryType = rawLine.substring(slash + 1).trim();\r\n return;\r\n }\r\n // have parameters\r\n secondaryType = rawLine.substring(slash + 1, semicolon).trim();\r\n Header h = new Header(rawLine);\r\n parameters = h.getParams();\r\n }", "public Date getFinishTime(Date date)\n {\n Date result = null;\n\n if (date != null)\n {\n ProjectCalendarDateRanges ranges = getRanges(date, null, null);\n if (ranges == null)\n {\n result = getParentFile().getProjectProperties().getDefaultEndTime();\n result = DateHelper.getCanonicalTime(result);\n }\n else\n {\n Date rangeStart = result = ranges.getRange(0).getStart();\n Date rangeFinish = ranges.getRange(ranges.getRangeCount() - 1).getEnd();\n Date startDay = DateHelper.getDayStartDate(rangeStart);\n Date finishDay = DateHelper.getDayStartDate(rangeFinish);\n\n result = DateHelper.getCanonicalTime(rangeFinish);\n\n //\n // Handle the case where the end of the range is at midnight -\n // this will show up as the start and end days not matching\n //\n if (startDay != null && finishDay != null && startDay.getTime() != finishDay.getTime())\n {\n result = DateHelper.addDays(result, 1);\n }\n }\n }\n return result;\n }", "public void refreshConnection() throws SQLException{\r\n\t\tthis.connection.close(); // if it's still in use, close it.\r\n\t\ttry{\r\n\t\t\tthis.connection = this.pool.obtainRawInternalConnection();\r\n\t\t} catch(SQLException e){\r\n\t\t\tthrow markPossiblyBroken(e);\r\n\t\t}\r\n\t}" ]
Publish finish events for each of the specified query types <pre> {@code RequestEvents.start("get", 1l, bus, "typeA", "custom"); try { return "ok"; } finally { RequestEvents.finish("get", 1l, bus, "typeA", "custom"); } } </pre> @param query Completed query @param correlationId Identifier @param bus EventBus to post events to @param types Query types to post to event bus
[ "public static <T> void finish(T query, long correlationId, EventBus bus, String... types) {\n for (String type : types) {\n RemoveQuery<T> next = finish(query, correlationId, type);\n bus.post(next);\n }\n }" ]
[ "public int tally() {\n long currentTimeMillis = clock.currentTimeMillis();\n\n // calculates time for which we remove any errors before\n final long removeTimesBeforeMillis = currentTimeMillis - windowMillis;\n\n synchronized (queue) {\n // drain out any expired timestamps but don't drain past empty\n while (!queue.isEmpty() && queue.peek() < removeTimesBeforeMillis) {\n queue.removeFirst();\n }\n return queue.size();\n }\n }", "private static MonolingualTextValue toTerm(MonolingualTextValue term) {\n\t\treturn term instanceof TermImpl ? term : new TermImpl(term.getLanguageCode(), term.getText());\n\t}", "private static String loadUA(ClassLoader loader, String filename){\n String ua = \"cloudant-http\";\n String version = \"unknown\";\n final InputStream propStream = loader.getResourceAsStream(filename);\n final Properties properties = new Properties();\n try {\n if (propStream != null) {\n try {\n properties.load(propStream);\n } finally {\n propStream.close();\n }\n }\n ua = properties.getProperty(\"user.agent.name\", ua);\n version = properties.getProperty(\"user.agent.version\", version);\n } catch (IOException e) {\n // Swallow exception and use default values.\n }\n\n return String.format(Locale.ENGLISH, \"%s/%s\", ua,version);\n }", "@Override\n public void clear() {\n values.clear();\n listBox.clear();\n\n clearStatusText();\n if (emptyPlaceHolder != null) {\n insertEmptyPlaceHolder(emptyPlaceHolder);\n }\n reload();\n if (isAllowBlank()) {\n addBlankItemIfNeeded();\n }\n }", "public static <E> Set<E> diff(Set<E> s1, Set<E> s2) {\r\n Set<E> s = new HashSet<E>();\r\n for (E o : s1) {\r\n if (!s2.contains(o)) {\r\n s.add(o);\r\n }\r\n }\r\n return s;\r\n }", "public void postConstruct() {\n parseGeometry();\n\n Assert.isTrue(this.polygon != null, \"Polygon is null. 'area' string is: '\" + this.area + \"'\");\n Assert.isTrue(this.display != null, \"'display' is null\");\n\n Assert.isTrue(this.style == null || this.display == AoiDisplay.RENDER,\n \"'style' does not make sense unless 'display' == RENDER. In this case 'display' == \" +\n this.display);\n }", "private static boolean isDisabledHandler(final LogContext logContext, final String handlerName) {\n final Map<String, String> disableHandlers = logContext.getAttachment(CommonAttributes.ROOT_LOGGER_NAME, DISABLED_HANDLERS_KEY);\n return disableHandlers != null && disableHandlers.containsKey(handlerName);\n }", "protected void closeServerSocket() {\n // Close server socket, we do not accept new requests anymore.\n // This also terminates the server thread if blocking on socket.accept.\n if (null != serverSocket) {\n try {\n if (!serverSocket.isClosed()) {\n serverSocket.close();\n if (log.isTraceEnabled()) {\n log.trace(\"Closed server socket \" + serverSocket + \"/ref=\"\n + Integer.toHexString(System.identityHashCode(serverSocket))\n + \" for \" + getName());\n }\n }\n } catch (IOException e) {\n throw new IllegalStateException(\"Failed to successfully quit server \" + getName(), e);\n }\n }\n }", "public static int getLineNumber(Member member) {\n\n if (!(member instanceof Method || member instanceof Constructor)) {\n // We are not able to get this info for fields\n return 0;\n }\n\n // BCEL is an optional dependency, if we cannot load it, simply return 0\n if (!Reflections.isClassLoadable(BCEL_CLASS, WeldClassLoaderResourceLoader.INSTANCE)) {\n return 0;\n }\n\n String classFile = member.getDeclaringClass().getName().replace('.', '/');\n ClassLoaderResourceLoader classFileResourceLoader = new ClassLoaderResourceLoader(member.getDeclaringClass().getClassLoader());\n InputStream in = null;\n\n try {\n URL classFileUrl = classFileResourceLoader.getResource(classFile + \".class\");\n\n if (classFileUrl == null) {\n // The class file is not available\n return 0;\n }\n in = classFileUrl.openStream();\n\n ClassParser cp = new ClassParser(in, classFile);\n JavaClass javaClass = cp.parse();\n\n // First get all declared methods and constructors\n // Note that in bytecode constructor is translated into a method\n org.apache.bcel.classfile.Method[] methods = javaClass.getMethods();\n org.apache.bcel.classfile.Method match = null;\n\n String signature;\n String name;\n if (member instanceof Method) {\n signature = DescriptorUtils.methodDescriptor((Method) member);\n name = member.getName();\n } else if (member instanceof Constructor) {\n signature = DescriptorUtils.makeDescriptor((Constructor<?>) member);\n name = INIT_METHOD_NAME;\n } else {\n return 0;\n }\n\n for (org.apache.bcel.classfile.Method method : methods) {\n // Matching method must have the same name, modifiers and signature\n if (method.getName().equals(name)\n && member.getModifiers() == method.getModifiers()\n && method.getSignature().equals(signature)) {\n match = method;\n }\n }\n if (match != null) {\n // If a method is found, try to obtain the optional LineNumberTable attribute\n LineNumberTable lineNumberTable = match.getLineNumberTable();\n if (lineNumberTable != null) {\n int line = lineNumberTable.getSourceLine(0);\n return line == -1 ? 0 : line;\n }\n }\n // No suitable method found\n return 0;\n\n } catch (Throwable t) {\n return 0;\n } finally {\n if (in != null) {\n try {\n in.close();\n } catch (Exception e) {\n return 0;\n }\n }\n }\n }" ]
Take a stab at fixing validation problems ? @param object
[ "private void validate(Object object) {\n\t\tSet<ConstraintViolation<Object>> viols = validator.validate(object);\n\t\tfor (ConstraintViolation<Object> constraintViolation : viols) {\n\t\t\tif (Null.class.isAssignableFrom(constraintViolation.getConstraintDescriptor().getAnnotation().getClass())) {\n\t\t\t\tObject o = constraintViolation.getLeafBean();\n\t\t\t\tIterator<Node> iterator = constraintViolation.getPropertyPath().iterator();\n\t\t\t\tString propertyName = null;\n\t\t\t\twhile (iterator.hasNext()) {\n\t\t\t\t\tpropertyName = iterator.next().getName();\n\t\t\t\t}\n\t\t\t\tif (propertyName != null) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tPropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(o.getClass(), propertyName);\n\t\t\t\t\t\tdescriptor.getWriteMethod().invoke(o, new Object[] { null });\n\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}" ]
[ "public static base_responses add(nitro_service client, gslbsite resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tgslbsite addresources[] = new gslbsite[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new gslbsite();\n\t\t\t\taddresources[i].sitename = resources[i].sitename;\n\t\t\t\taddresources[i].sitetype = resources[i].sitetype;\n\t\t\t\taddresources[i].siteipaddress = resources[i].siteipaddress;\n\t\t\t\taddresources[i].publicip = resources[i].publicip;\n\t\t\t\taddresources[i].metricexchange = resources[i].metricexchange;\n\t\t\t\taddresources[i].nwmetricexchange = resources[i].nwmetricexchange;\n\t\t\t\taddresources[i].sessionexchange = resources[i].sessionexchange;\n\t\t\t\taddresources[i].triggermonitor = resources[i].triggermonitor;\n\t\t\t\taddresources[i].parentsite = resources[i].parentsite;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "final void roll(final long timeForSuffix) {\n\n final File backupFile = this.prepareBackupFile(timeForSuffix);\n\n // close filename\n this.getAppender().closeFile();\n\n // rename filename on disk to filename+suffix(+number)\n this.doFileRoll(this.getAppender().getIoFile(), backupFile);\n\n // setup new file 'filename'\n this.getAppender().openFile();\n\n this.fireFileRollEvent(new FileRollEvent(this, backupFile));\n }", "public static void unregisterMbean(MBeanServer server, ObjectName name) {\n try {\n server.unregisterMBean(name);\n } catch(Exception e) {\n logger.error(\"Error unregistering mbean\", e);\n }\n }", "private void addUserDefinedField(FieldTypeClass fieldType, UserFieldDataType dataType, String name)\n {\n try\n {\n switch (fieldType)\n {\n case TASK:\n TaskField taskField;\n\n do\n {\n taskField = m_taskUdfCounters.nextField(TaskField.class, dataType);\n }\n while (m_taskFields.containsKey(taskField) || m_wbsFields.containsKey(taskField));\n\n m_project.getCustomFields().getCustomField(taskField).setAlias(name);\n\n break;\n case RESOURCE:\n ResourceField resourceField;\n\n do\n {\n resourceField = m_resourceUdfCounters.nextField(ResourceField.class, dataType);\n }\n while (m_resourceFields.containsKey(resourceField));\n\n m_project.getCustomFields().getCustomField(resourceField).setAlias(name);\n\n break;\n case ASSIGNMENT:\n AssignmentField assignmentField;\n\n do\n {\n assignmentField = m_assignmentUdfCounters.nextField(AssignmentField.class, dataType);\n }\n while (m_assignmentFields.containsKey(assignmentField));\n\n m_project.getCustomFields().getCustomField(assignmentField).setAlias(name);\n\n break;\n default:\n break;\n }\n }\n\n catch (Exception ex)\n {\n //\n // SF#227: If we get an exception thrown here... it's likely that\n // we've run out of user defined fields, for example\n // there are only 30 TEXT fields. We'll ignore this: the user\n // defined field won't be mapped to an alias, so we'll\n // ignore it when we read in the values.\n //\n }\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<EthiopicDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<EthiopicDate>) super.localDateTime(temporal);\n }", "@JsonIgnore\n public void setUnknownFields(final Map<String,Object> unknownFields) {\n this.unknownFields.clear();\n this.unknownFields.putAll(unknownFields);\n }", "public int[] next()\n {\n boolean hasNewPerm = false;\n\n escape:while( level >= 0) {\n// boolean foundZero = false;\n for( int i = iter[level]; i < data.length; i = iter[level] ) {\n iter[level]++;\n\n if( data[i] == -1 ) {\n level++;\n data[i] = level-1;\n\n if( level >= data.length ) {\n // a new permutation has been created return the results.\n hasNewPerm = true;\n System.arraycopy(data,0,ret,0,ret.length);\n level = level-1;\n data[i] = -1;\n break escape;\n } else {\n valk[level] = i;\n }\n }\n }\n\n data[valk[level]] = -1;\n iter[level] = 0;\n level = level-1;\n\n }\n\n if( hasNewPerm )\n return ret;\n return null;\n }", "void release() {\n\t\tif (mCurrentRequests != null) {\n\t\t\tsynchronized (mCurrentRequests) {\n\t\t\t\tmCurrentRequests.clear();\n\t\t\t\tmCurrentRequests = null;\n\t\t\t}\n\t\t}\n\n\t\tif (mDownloadQueue != null) {\n\t\t\tmDownloadQueue = null;\n\t\t}\n\n\t\tif (mDownloadDispatchers != null) {\n\t\t\tstop();\n\n\t\t\tfor (int i = 0; i < mDownloadDispatchers.length; i++) {\n\t\t\t\tmDownloadDispatchers[i] = null;\n\t\t\t}\n\t\t\tmDownloadDispatchers = null;\n\t\t}\n\n\t}", "public <T> Method getSetMethod(final Object object, final String fieldName, final Class<?> argumentType) {\n\t\tif( object == null ) {\n\t\t\tthrow new NullPointerException(\"object should not be null\");\n\t\t} else if( fieldName == null ) {\n\t\t\tthrow new NullPointerException(\"fieldName should not be null\");\n\t\t} else if( argumentType == null ) {\n\t\t\tthrow new NullPointerException(\"argumentType should not be null\");\n\t\t}\n\t\t\n\t\tMethod method = setMethodsCache.get(object.getClass(), argumentType, fieldName);\n\t\tif( method == null ) {\n\t\t\tmethod = ReflectionUtils.findSetter(object, fieldName, argumentType);\n\t\t\tsetMethodsCache.set(object.getClass(), argumentType, fieldName, method);\n\t\t}\n\t\treturn method;\n\t}" ]
create an instance from the className @param <E> class of object @param className full class name @return an object or null if className is null
[ "@SuppressWarnings(\"unchecked\")\n public static <E> E getObject(String className) {\n if (className == null) {\n return (E) null;\n }\n try {\n return (E) Class.forName(className).newInstance();\n } catch (InstantiationException e) {\n throw new RuntimeException(e);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n }" ]
[ "public void disconnect() {\n\t\tif (sendThread != null) {\n\t\t\tsendThread.interrupt();\n\t\t\ttry {\n\t\t\t\tsendThread.join();\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t\tsendThread = null;\n\t\t}\n\t\tif (receiveThread != null) {\n\t\t\treceiveThread.interrupt();\n\t\t\ttry {\n\t\t\t\treceiveThread.join();\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t\treceiveThread = null;\n\t\t}\n\t\tif(transactionCompleted.availablePermits() < 0)\n\t\t\ttransactionCompleted.release(transactionCompleted.availablePermits());\n\t\t\n\t\ttransactionCompleted.drainPermits();\n\t\tlogger.trace(\"Transaction completed permit count -> {}\", transactionCompleted.availablePermits());\n\t\tif (this.serialPort != null) {\n\t\t\tthis.serialPort.close();\n\t\t\tthis.serialPort = null;\n\t\t}\n\t\tlogger.info(\"Disconnected from serial port\");\n\t}", "public void setHtmlElementTranslator(HtmlElementTranslator htmlElementTranslator) {\r\n\t\tif(htmlElementTranslator!=null){\r\n\t\t\tthis.htmlElementTranslator = htmlElementTranslator;\r\n\t\t\tthis.charTranslator = null;\r\n\t\t\tthis.targetTranslator = null;\r\n\t\t}\r\n\t}", "public String getCsv() {\n\n StringWriter writer = new StringWriter();\n try (CSVWriter csv = new CSVWriter(writer)) {\n List<String> headers = new ArrayList<>();\n for (String col : m_columns) {\n headers.add(col);\n }\n csv.writeNext(headers.toArray(new String[] {}));\n for (List<Object> row : m_data) {\n List<String> colCsv = new ArrayList<>();\n for (Object col : row) {\n colCsv.add(String.valueOf(col));\n }\n csv.writeNext(colCsv.toArray(new String[] {}));\n }\n return writer.toString();\n } catch (IOException e) {\n return null;\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}", "private static long createLongSeed(byte[] seed)\n {\n if (seed == null || seed.length != SEED_SIZE_BYTES)\n {\n throw new IllegalArgumentException(\"Java RNG requires a 64-bit (8-byte) seed.\");\n }\n return BinaryUtils.convertBytesToLong(seed, 0);\n }", "public String getKeyValue(String key){\n String keyName = keysMap.get(key);\n if (keyName != null){\n return keyName;\n }\n return \"\"; //key wasn't defined in keys properties file\n }", "public static boolean isFloat(CharSequence self) {\n try {\n Float.valueOf(self.toString().trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n }", "protected Violation createViolation(SourceCode sourceCode, ASTNode node, String message) {\n String sourceLine = sourceCode.line(node.getLineNumber()-1);\n return createViolation(node.getLineNumber(), sourceLine, message);\n }", "@Override\n public Optional<String> hash(final Optional<URL> url) throws IOException {\n if (!url.isPresent()) {\n return Optional.absent();\n }\n logger.debug(\"Calculating md5 hash, url:{}\", url);\n if (isHotReloadModeOff()) {\n final String md5 = cache.getIfPresent(url.get());\n\n logger.debug(\"md5 hash:{}\", md5);\n\n if (md5 != null) {\n return Optional.of(md5);\n }\n }\n\n final InputStream is = url.get().openStream();\n final String md5 = getMD5Checksum(is);\n\n if (isHotReloadModeOff()) {\n logger.debug(\"caching url:{} with hash:{}\", url, md5);\n\n cache.put(url.get(), md5);\n }\n\n return Optional.fromNullable(md5);\n }" ]
Microsoft Project bases the order of tasks displayed on their ID value. This method takes the hierarchical structure of tasks represented in MPXJ and renumbers the ID values to ensure that this structure is displayed as expected in Microsoft Project. This is typically used to deal with the case where a hierarchical task structure has been created programmatically in MPXJ.
[ "public void synchronizeTaskIDToHierarchy()\n {\n clear();\n\n int currentID = (getByID(Integer.valueOf(0)) == null ? 1 : 0);\n for (Task task : m_projectFile.getChildTasks())\n {\n task.setID(Integer.valueOf(currentID++));\n add(task);\n currentID = synchroizeTaskIDToHierarchy(task, currentID);\n }\n }" ]
[ "public Sites getSitesInformation() throws IOException {\n\t\tMwDumpFile sitesTableDump = getMostRecentDump(DumpContentType.SITES);\n\t\tif (sitesTableDump == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// Create a suitable processor for such dumps and process the file:\n\t\tMwSitesDumpFileProcessor sitesDumpFileProcessor = new MwSitesDumpFileProcessor();\n\t\tsitesDumpFileProcessor.processDumpFileContents(\n\t\t\t\tsitesTableDump.getDumpFileStream(), sitesTableDump);\n\n\t\treturn sitesDumpFileProcessor.getSites();\n\t}", "public String addClassification(String classificationType) {\n Metadata metadata = new Metadata().add(Metadata.CLASSIFICATION_KEY, classificationType);\n Metadata classification = this.createMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY,\n \"enterprise\", metadata);\n\n return classification.getString(Metadata.CLASSIFICATION_KEY);\n }", "public static Organization unserializeOrganization(final String organization) throws IOException {\n final ObjectMapper mapper = new ObjectMapper();\n mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);\n return mapper.readValue(organization, Organization.class);\n }", "public void sendSyncModeCommand(int deviceNumber, boolean synced) throws IOException {\n final DeviceUpdate update = getLatestStatusFor(deviceNumber);\n if (update == null) {\n throw new IllegalArgumentException(\"Device \" + deviceNumber + \" not found on network.\");\n }\n sendSyncModeCommand(update, synced);\n }", "public void initializePersistenceStrategy(CacheMappingType cacheMappingType, Set<EntityKeyMetadata> entityTypes, Set<AssociationKeyMetadata> associationTypes, Set<IdSourceKeyMetadata> idSourceTypes, Iterable<Namespace> namespaces) {\n\t\tpersistenceStrategy = PersistenceStrategy.getInstance(\n\t\t\t\tcacheMappingType,\n\t\t\t\texternalCacheManager,\n\t\t\t\tconfig.getConfigurationUrl(),\n\t\t\t\tjtaPlatform,\n\t\t\t\tentityTypes,\n\t\t\t\tassociationTypes,\n\t\t\t\tidSourceTypes\n\t\t);\n\n\t\t// creates handler for TableGenerator Id sources\n\t\tboolean requiresCounter = hasIdGeneration( idSourceTypes );\n\t\tif ( requiresCounter ) {\n\t\t\tthis.tableClusterHandler = new TableClusteredCounterHandler( persistenceStrategy.getCacheManager().getCacheManager() );\n\t\t}\n\n\t\t// creates handlers for SequenceGenerator Id sources\n\t\tfor ( Namespace namespace : namespaces ) {\n\t\t\tfor ( Sequence seq : namespace.getSequences() ) {\n\t\t\t\tthis.sequenceCounterHandlers.put( seq.getExportIdentifier(),\n\t\t\t\t\t\tnew SequenceClusteredCounterHandler( persistenceStrategy.getCacheManager().getCacheManager(), seq ) );\n\t\t\t}\n\t\t}\n\n\t\t// clear resources\n\t\tthis.externalCacheManager = null;\n\t\tthis.jtaPlatform = null;\n\t}", "public static void showErrorDialog(String message, String details) {\n\n Window window = prepareWindow(DialogWidth.wide);\n window.setCaption(\"Error\");\n window.setContent(new CmsSetupErrorDialog(message, details, null, window));\n A_CmsUI.get().addWindow(window);\n\n }", "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 ManagementModelNode getSelectedNode() {\n if (tree.getSelectionPath() == null) return null;\n return (ManagementModelNode)tree.getSelectionPath().getLastPathComponent();\n }", "private void initializeSignProperties() {\n if (!signPackage && !signChanges) {\n return;\n }\n\n if (key != null && keyring != null && passphrase != null) {\n return;\n }\n\n Map<String, String> properties =\n readPropertiesFromActiveProfiles(signCfgPrefix, KEY, KEYRING, PASSPHRASE);\n\n key = lookupIfEmpty(key, properties, KEY);\n keyring = lookupIfEmpty(keyring, properties, KEYRING);\n passphrase = decrypt(lookupIfEmpty(passphrase, properties, PASSPHRASE));\n\n if (keyring == null) {\n try {\n keyring = Utils.guessKeyRingFile().getAbsolutePath();\n console.info(\"Located keyring at \" + keyring);\n } catch (FileNotFoundException e) {\n console.warn(e.getMessage());\n }\n }\n }" ]
Gets a list of split keys given a desired number of splits. <p>This list will contain multiple split keys for each split. Only a single split key will be chosen as the split point, however providing multiple keys allows for more uniform sharding. @param numSplits the number of desired splits. @param query the user query. @param partition the partition to run the query in. @param datastore the datastore containing the data. @throws DatastoreException if there was an error when executing the datastore query.
[ "private List<Key> getScatterKeys(\n int numSplits, Query query, PartitionId partition, Datastore datastore)\n throws DatastoreException {\n Query.Builder scatterPointQuery = createScatterQuery(query, numSplits);\n\n List<Key> keySplits = new ArrayList<Key>();\n\n QueryResultBatch batch;\n do {\n RunQueryRequest scatterRequest =\n RunQueryRequest.newBuilder()\n .setPartitionId(partition)\n .setQuery(scatterPointQuery)\n .build();\n batch = datastore.runQuery(scatterRequest).getBatch();\n for (EntityResult result : batch.getEntityResultsList()) {\n keySplits.add(result.getEntity().getKey());\n }\n scatterPointQuery.setStartCursor(batch.getEndCursor());\n scatterPointQuery.getLimitBuilder().setValue(\n scatterPointQuery.getLimit().getValue() - batch.getEntityResultsCount());\n } while (batch.getMoreResults() == MoreResultsType.NOT_FINISHED);\n Collections.sort(keySplits, DatastoreHelper.getKeyComparator());\n return keySplits;\n }" ]
[ "private void debugLogStart(String operationType,\n Long originTimeInMS,\n Long requestReceivedTimeInMs,\n String keyString) {\n long durationInMs = requestReceivedTimeInMs - originTimeInMS;\n logger.debug(\"Received a new request. Operation Type: \" + operationType + \" , key(s): \"\n + keyString + \" , Store: \" + this.storeName + \" , Origin time (in ms): \"\n + originTimeInMS + \" . Request received at time(in ms): \"\n + requestReceivedTimeInMs\n + \" , Duration from RESTClient to CoordinatorFatClient(in ms): \"\n + durationInMs);\n\n }", "public static <K, V> Map<K, V> immutableMapView(Map<K, V> map) {\n if (map instanceof ImmutableMap<?, ?>) {\n return map;\n }\n return Collections.unmodifiableMap(map);\n }", "public static boolean isOperationDefined(final ModelNode operation) {\n for (final AttributeDefinition def : ROOT_ATTRIBUTES) {\n if (operation.hasDefined(def.getName())) {\n return true;\n }\n }\n return false;\n }", "public static LocalDate getDateFromFloatingPointDate(LocalDate referenceDate, double floatingPointDate) {\n\t\tif(referenceDate == null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn referenceDate.plusDays((int)Math.round(floatingPointDate*365.0));\n\t}", "private void writePredecessors(Task mpxjTask, net.sf.mpxj.planner.schema.Task plannerTask)\n {\n Predecessors plannerPredecessors = m_factory.createPredecessors();\n plannerTask.setPredecessors(plannerPredecessors);\n List<Predecessor> predecessorList = plannerPredecessors.getPredecessor();\n int id = 0;\n\n List<Relation> predecessors = mpxjTask.getPredecessors();\n for (Relation rel : predecessors)\n {\n Integer taskUniqueID = rel.getTargetTask().getUniqueID();\n Predecessor plannerPredecessor = m_factory.createPredecessor();\n plannerPredecessor.setId(getIntegerString(++id));\n plannerPredecessor.setPredecessorId(getIntegerString(taskUniqueID));\n plannerPredecessor.setLag(getDurationString(rel.getLag()));\n plannerPredecessor.setType(RELATIONSHIP_TYPES.get(rel.getType()));\n predecessorList.add(plannerPredecessor);\n m_eventManager.fireRelationWrittenEvent(rel);\n }\n }", "public static <T> int createTable(ConnectionSource connectionSource, Class<T> dataClass) throws SQLException {\n\t\tDao<T, ?> dao = DaoManager.createDao(connectionSource, dataClass);\n\t\treturn doCreateTable(dao, false);\n\t}", "private void resetStoreDefinitions(Set<String> storeNamesToDelete) {\n // Clear entries in the metadata cache\n for(String storeName: storeNamesToDelete) {\n this.metadataCache.remove(storeName);\n this.storeDefinitionsStorageEngine.delete(storeName, null);\n this.storeNames.remove(storeName);\n }\n }", "synchronized void openConnection(final ModelController controller, final ActiveOperation.CompletedCallback<ModelNode> callback) throws Exception {\n boolean ok = false;\n final Connection connection = connectionManager.connect();\n try {\n channelHandler.executeRequest(new ServerRegisterRequest(), null, callback);\n // HC is the same version, so it will support sending the subject\n channelHandler.getAttachments().attach(TransactionalProtocolClient.SEND_IDENTITY, Boolean.TRUE);\n channelHandler.getAttachments().attach(TransactionalProtocolClient.SEND_IN_VM, Boolean.TRUE);\n channelHandler.addHandlerFactory(new TransactionalProtocolOperationHandler(controller, channelHandler, responseAttachmentSupport));\n ok = true;\n } finally {\n if(!ok) {\n connection.close();\n }\n }\n }", "private Profile getProfileFromResultSet(ResultSet result) throws Exception {\n Profile profile = new Profile();\n profile.setId(result.getInt(Constants.GENERIC_ID));\n Clob clobProfileName = result.getClob(Constants.PROFILE_PROFILE_NAME);\n String profileName = clobProfileName.getSubString(1, (int) clobProfileName.length());\n profile.setName(profileName);\n return profile;\n }" ]
Checks if the link target is a secure link.<p @param cms the current CMS context @param vfsName the path of the link target @param targetSite the target site containing the detail page @param secureRequest true if the currently running request is secure @return true if the link should be a secure link
[ "protected boolean isSecureLink(CmsObject cms, String vfsName, CmsSite targetSite, boolean secureRequest) {\n\n return OpenCms.getStaticExportManager().isSecureLink(cms, vfsName, targetSite.getSiteRoot(), secureRequest);\n }" ]
[ "public double totalCount() {\r\n if (depth() == 1) {\r\n return total; // I think this one is always OK. Not very principled here, though.\r\n } else {\r\n double result = 0.0;\r\n for (K o: topLevelKeySet()) {\r\n result += conditionalizeOnce(o).totalCount();\r\n }\r\n return result;\r\n }\r\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 }", "public static base_responses delete(nitro_service client, clusterinstance resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tclusterinstance deleteresources[] = new clusterinstance[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new clusterinstance();\n\t\t\t\tdeleteresources[i].clid = resources[i].clid;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "public static VectorClock makeClock(Set<Integer> serverIds, long clockValue, long timestamp) {\n List<ClockEntry> clockEntries = new ArrayList<ClockEntry>(serverIds.size());\n for(Integer serverId: serverIds) {\n clockEntries.add(new ClockEntry(serverId.shortValue(), clockValue));\n }\n return new VectorClock(clockEntries, timestamp);\n }", "@SuppressWarnings(\"unchecked\")\n public void put(String key, Versioned<Object> value) {\n // acquire write lock\n writeLock.lock();\n\n try {\n if(this.storeNames.contains(key) || key.equals(STORES_KEY)) {\n\n // Check for backwards compatibility\n List<StoreDefinition> storeDefinitions = (List<StoreDefinition>) value.getValue();\n StoreDefinitionUtils.validateSchemasAsNeeded(storeDefinitions);\n\n // If the put is on the entire stores.xml key, delete the\n // additional stores which do not exist in the specified\n // stores.xml\n Set<String> storeNamesToDelete = new HashSet<String>();\n for(String storeName: this.storeNames) {\n storeNamesToDelete.add(storeName);\n }\n\n // Add / update the list of store definitions specified in the\n // value\n StoreDefinitionsMapper mapper = new StoreDefinitionsMapper();\n\n // Update the STORES directory and the corresponding entry in\n // metadata cache\n Set<String> specifiedStoreNames = new HashSet<String>();\n for(StoreDefinition storeDef: storeDefinitions) {\n specifiedStoreNames.add(storeDef.getName());\n String storeDefStr = mapper.writeStore(storeDef);\n Versioned<String> versionedValueStr = new Versioned<String>(storeDefStr,\n value.getVersion());\n this.storeDefinitionsStorageEngine.put(storeDef.getName(),\n versionedValueStr,\n \"\");\n\n // Update the metadata cache\n this.metadataCache.put(storeDef.getName(),\n new Versioned<Object>(storeDefStr, value.getVersion()));\n }\n\n if(key.equals(STORES_KEY)) {\n storeNamesToDelete.removeAll(specifiedStoreNames);\n resetStoreDefinitions(storeNamesToDelete);\n }\n\n // Re-initialize the store definitions\n initStoreDefinitions(value.getVersion());\n\n // Update routing strategies\n updateRoutingStrategies(getCluster(), getStoreDefList());\n\n } else if(METADATA_KEYS.contains(key)) {\n // try inserting into inner store first\n putInner(key, convertObjectToString(key, value));\n\n // cache all keys if innerStore put succeeded\n metadataCache.put(key, value);\n\n // do special stuff if needed\n if(CLUSTER_KEY.equals(key)) {\n updateRoutingStrategies((Cluster) value.getValue(), getStoreDefList());\n } else if(NODE_ID_KEY.equals(key)) {\n initNodeId(getNodeIdNoLock());\n } else if(SYSTEM_STORES_KEY.equals(key))\n throw new VoldemortException(\"Cannot overwrite system store definitions\");\n\n } else {\n throw new VoldemortException(\"Unhandled Key:\" + key + \" for MetadataStore put()\");\n }\n } finally {\n writeLock.unlock();\n }\n }", "public static String replaceFirst(final CharSequence self, final CharSequence regex, final CharSequence replacement) {\n return self.toString().replaceFirst(regex.toString(), replacement.toString());\n }", "private Map<String, ColumnDefinition> makeColumnMap(ColumnDefinition[] columns)\n {\n Map<String, ColumnDefinition> map = new HashMap<String, ColumnDefinition>();\n for (ColumnDefinition def : columns)\n {\n map.put(def.getName(), def);\n }\n return map;\n }", "public static String getPostString(InputStream is, String encoding) {\n try {\n StringWriter sw = new StringWriter();\n IOUtils.copy(is, sw, encoding);\n\n return sw.toString();\n } catch (IOException e) {\n // no op\n return null;\n } finally {\n IOUtils.closeQuietly(is);\n }\n }", "public void addDateTimeHelper(int ds, Date date) throws SerializationException, InvalidDataSetException {\r\n\t\tif (date == null) {\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tDataSetInfo dsi = dsiFactory.create(ds);\r\n\r\n\t\tSimpleDateFormat df = new SimpleDateFormat(dsi.getSerializer().toString());\r\n\t\tString value = df.format(date);\r\n\t\tbyte[] data = dsi.getSerializer().serialize(value, activeSerializationContext);\r\n\t\tDataSet dataSet = new DefaultDataSet(dsi, data);\r\n\t\tadd(dataSet);\r\n\t}" ]
Scale all widgets in Main Scene hierarchy @param scale
[ "public void setScale(final float scale) {\n if (equal(mScale, scale) != true) {\n Log.d(TAG, \"setScale(): old: %.2f, new: %.2f\", mScale, scale);\n mScale = scale;\n setScale(mSceneRootObject, scale);\n setScale(mMainCameraRootObject, scale);\n setScale(mLeftCameraRootObject, scale);\n setScale(mRightCameraRootObject, scale);\n for (OnScaledListener listener : mOnScaledListeners) {\n try {\n listener.onScaled(scale);\n } catch (Exception e) {\n e.printStackTrace();\n Log.e(TAG, e, \"setScale()\");\n }\n }\n }\n }" ]
[ "public static base_response renumber(nitro_service client) throws Exception {\n\t\tnspbr6 renumberresource = new nspbr6();\n\t\treturn renumberresource.perform_operation(client,\"renumber\");\n\t}", "private byte[] createErrorImage(int width, int height, Exception e) throws IOException {\n\t\tString error = e.getMessage();\n\t\tif (null == error) {\n\t\t\tWriter result = new StringWriter();\n\t\t\tPrintWriter printWriter = new PrintWriter(result);\n\t\t\te.printStackTrace(printWriter);\n\t\t\terror = result.toString();\n\t\t}\n\n\t\tBufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);\n\t\tGraphics2D g = (Graphics2D) image.getGraphics();\n\n\t\tg.setColor(Color.RED);\n\t\tg.drawString(error, ERROR_MESSAGE_X, height / 2);\n\n\t\tByteArrayOutputStream out = new ByteArrayOutputStream();\n\t\tImageIO.write(image, \"PNG\", out);\n\t\tout.flush();\n\t\tbyte[] result = out.toByteArray();\n\t\tout.close();\n\n\t\treturn result;\n\t}", "public void setIndexBuffer(GVRIndexBuffer ibuf)\n {\n mIndices = ibuf;\n NativeMesh.setIndexBuffer(getNative(), (ibuf != null) ? ibuf.getNative() : 0L);\n }", "public static String getDays(RecurringTask task)\n {\n StringBuilder sb = new StringBuilder();\n for (Day day : Day.values())\n {\n sb.append(task.getWeeklyDay(day) ? \"1\" : \"0\");\n }\n return sb.toString();\n }", "public void forAllMemberTags(String template, Properties attributes) throws XDocletException\r\n {\r\n if (getCurrentField() != null) {\r\n forAllMemberTags(template, attributes, FOR_FIELD, XDocletTagshandlerMessages.ONLY_CALL_FIELD_NOT_NULL, new String[]{\"forAllMemberTags\"});\r\n }\r\n else if (getCurrentMethod() != null) {\r\n forAllMemberTags(template, attributes, FOR_METHOD, XDocletTagshandlerMessages.ONLY_CALL_METHOD_NOT_NULL, new String[]{\"forAllMemberTags\"});\r\n }\r\n }", "protected void handleResponseOut(T message) throws Fault {\n Message reqMsg = message.getExchange().getInMessage();\n if (reqMsg == null) {\n LOG.warning(\"InMessage is null!\");\n return;\n }\n\n // No flowId for oneway message\n Exchange ex = reqMsg.getExchange();\n if (ex.isOneWay()) {\n return;\n }\n\n String reqFid = FlowIdHelper.getFlowId(reqMsg);\n\n // if some interceptor throws fault before FlowIdProducerIn fired\n if (reqFid == null) {\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Some interceptor throws fault.Setting FlowId in response.\");\n }\n reqFid = FlowIdProtocolHeaderCodec.readFlowId(message);\n }\n\n // write IN message to SAM repo in case fault\n if (reqFid == null) {\n Message inMsg = ex.getInMessage();\n\n reqFid = FlowIdProtocolHeaderCodec.readFlowId(inMsg);\n if (null != reqFid) {\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"FlowId '\" + reqFid\n + \"' found in message of fault incoming exchange.\");\n LOG.fine(\"Calling EventProducerInterceptor to log IN message\");\n }\n handleINEvent(ex, reqFid);\n }\n }\n\n if (reqFid == null) {\n reqFid = FlowIdSoapCodec.readFlowId(message);\n }\n\n if (reqFid != null) {\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"FlowId '\" + reqFid + \"' found in incoming message.\");\n }\n } else {\n reqFid = ContextUtils.generateUUID();\n // write IN message to SAM repo in case fault\n if (null != ex.getOutFaultMessage()) {\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"FlowId '\" + reqFid\n + \"' generated for fault message.\");\n LOG.fine(\"Calling EventProducerInterceptor to log IN message\");\n }\n handleINEvent(ex, reqFid);\n }\n\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"No flowId found in incoming message! Generate new flowId \"\n + reqFid);\n }\n }\n\n FlowIdHelper.setFlowId(message, reqFid);\n\n }", "private String generatedBuilderSimpleName(TypeElement type) {\n String packageName = elements.getPackageOf(type).getQualifiedName().toString();\n String originalName = type.getQualifiedName().toString();\n checkState(originalName.startsWith(packageName + \".\"));\n String nameWithoutPackage = originalName.substring(packageName.length() + 1);\n return String.format(BUILDER_SIMPLE_NAME_TEMPLATE, nameWithoutPackage.replaceAll(\"\\\\.\", \"_\"));\n }", "@SuppressWarnings(\"WeakerAccess\")\n public int findBeatAtTime(long milliseconds) {\n int found = Arrays.binarySearch(timeWithinTrackValues, milliseconds);\n if (found >= 0) { // An exact match, just change 0-based array index to 1-based beat number\n return found + 1;\n } else if (found == -1) { // We are before the first beat\n return found;\n } else { // We are after some beat, report its beat number\n return -(found + 1);\n }\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 }" ]
Ensure that all logs are replayed, any other logs can not be added before end of this function.
[ "@Override\n protected <T> CompletableFuture<T> doExecute(Command<T> command) throws Exception {\n final CompletableFuture<T> future = new CompletableFuture<>();\n executor.execute(() -> {\n try {\n future.complete(blockingExecute(command));\n } catch (Throwable t) {\n future.completeExceptionally(t);\n }\n });\n return future;\n }" ]
[ "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}", "@Override\n public DecompilationResult decompileClassFile(Path rootDir, Path classFilePath, Path outputDir)\n throws DecompilationException\n {\n Checks.checkDirectoryToBeRead(rootDir.toFile(), \"Classes root dir\");\n File classFile = classFilePath.toFile();\n Checks.checkFileToBeRead(classFile, \"Class file\");\n Checks.checkDirectoryToBeFilled(outputDir.toFile(), \"Output directory\");\n\n log.info(\"Decompiling .class '\" + classFilePath + \"' to '\" + outputDir + \"' from: '\" + rootDir + \"'\");\n\n String name = classFilePath.normalize().toAbsolutePath().toString().substring(rootDir.toAbsolutePath().toString().length() + 1);\n final String typeName = StringUtils.removeEnd(name, \".class\");// .replace('/', '.');\n\n DecompilationResult result = new DecompilationResult();\n try\n {\n DecompilerSettings settings = getDefaultSettings(outputDir.toFile());\n this.procyonConf.setDecompilerSettings(settings); // TODO: This is horrible mess.\n\n final ITypeLoader typeLoader = new CompositeTypeLoader(new WindupClasspathTypeLoader(rootDir.toString()), new ClasspathTypeLoader());\n WindupMetadataSystem metadataSystem = new WindupMetadataSystem(typeLoader);\n File outputFile = this.decompileType(settings, metadataSystem, typeName);\n result.addDecompiled(Collections.singletonList(classFilePath.toString()), outputFile.getAbsolutePath());\n }\n catch (Throwable e)\n {\n DecompilationFailure failure = new DecompilationFailure(\"Error during decompilation of \"\n + classFilePath.toString() + \":\\n \" + e.getMessage(), Collections.singletonList(name), e);\n log.severe(failure.getMessage());\n result.addFailure(failure);\n }\n\n return result;\n }", "public GVRAnimationChannel findChannel(String boneName)\n {\n int boneId = mSkeleton.getBoneIndex(boneName);\n if (boneId >= 0)\n {\n return mBoneChannels[boneId];\n }\n return null;\n }", "private void normalizeSelectedCategories() {\r\n\r\n Collection<String> normalizedCategories = new ArrayList<String>(m_selectedCategories.size());\r\n for (CmsTreeItem item : m_categories.values()) {\r\n if (item.getCheckBox().isChecked()) {\r\n normalizedCategories.add(item.getId());\r\n }\r\n }\r\n m_selectedCategories = normalizedCategories;\r\n\r\n }", "public void addChannel(String boneName, GVRAnimationChannel channel)\n {\n int boneId = mSkeleton.getBoneIndex(boneName);\n if (boneId >= 0)\n {\n mBoneChannels[boneId] = channel;\n mSkeleton.setBoneOptions(boneId, GVRSkeleton.BONE_ANIMATE);\n Log.d(\"BONE\", \"Adding animation channel %d %s \", boneId, boneName);\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 TFuture<JsonResponse<AdvertiseResponse>> advertise() {\n\n final AdvertiseRequest advertiseRequest = new AdvertiseRequest();\n advertiseRequest.addService(service, 0);\n\n // TODO: options for hard fail, retries etc.\n final JsonRequest<AdvertiseRequest> request = new JsonRequest.Builder<AdvertiseRequest>(\n HYPERBAHN_SERVICE_NAME,\n HYPERBAHN_ADVERTISE_ENDPOINT\n )\n .setBody(advertiseRequest)\n .setTimeout(REQUEST_TIMEOUT)\n .setRetryLimit(4)\n .build();\n\n final TFuture<JsonResponse<AdvertiseResponse>> future = hyperbahnChannel.send(request);\n future.addCallback(new TFutureCallback<JsonResponse<AdvertiseResponse>>() {\n @Override\n public void onResponse(JsonResponse<AdvertiseResponse> response) {\n if (response.isError()) {\n logger.error(\"Failed to advertise to Hyperbahn: {} - {}\",\n response.getError().getErrorType(),\n response.getError().getMessage());\n }\n\n if (destroyed.get()) {\n return;\n }\n\n scheduleAdvertise();\n }\n });\n\n return future;\n }", "public void makePickable(GVRSceneObject sceneObject) {\n try {\n GVRMeshCollider collider = new GVRMeshCollider(sceneObject.getGVRContext(), false);\n sceneObject.attachComponent(collider);\n } catch (Exception e) {\n // Possible that some objects (X3D panel nodes) are without mesh\n Log.e(Log.SUBSYSTEM.INPUT, TAG, \"makePickable(): possible that some objects (X3D panel nodes) are without mesh!\");\n }\n }", "public void sendLoadTrackCommand(DeviceUpdate target, int rekordboxId,\n int sourcePlayer, CdjStatus.TrackSourceSlot sourceSlot, CdjStatus.TrackType sourceType)\n throws IOException {\n ensureRunning();\n byte[] payload = new byte[LOAD_TRACK_PAYLOAD.length];\n System.arraycopy(LOAD_TRACK_PAYLOAD, 0, payload, 0, LOAD_TRACK_PAYLOAD.length);\n payload[0x02] = getDeviceNumber();\n payload[0x05] = getDeviceNumber();\n payload[0x09] = (byte)sourcePlayer;\n payload[0x0a] = sourceSlot.protocolValue;\n payload[0x0b] = sourceType.protocolValue;\n Util.numberToBytes(rekordboxId, payload, 0x0d, 4);\n assembleAndSendPacket(Util.PacketType.LOAD_TRACK_COMMAND, payload, target.getAddress(), UPDATE_PORT);\n }" ]
Use this API to fetch all the clusternodegroup resources that are configured on netscaler.
[ "public static clusternodegroup[] get(nitro_service service) throws Exception{\n\t\tclusternodegroup obj = new clusternodegroup();\n\t\tclusternodegroup[] response = (clusternodegroup[])obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "public void handleStateEvent(String callbackKey) {\n if (handlers.containsKey(callbackKey) && handlers.get(callbackKey) instanceof StateEventHandler) {\n ((StateEventHandler) handlers.get(callbackKey)).handle();\n } else {\n System.err.println(\"Error in handle: \" + callbackKey + \" for state handler \");\n }\n }", "public static synchronized DeckReference getDeckReference(int player, int hotCue) {\n Map<Integer, DeckReference> playerMap = instances.get(player);\n if (playerMap == null) {\n playerMap = new HashMap<Integer, DeckReference>();\n instances.put(player, playerMap);\n }\n DeckReference result = playerMap.get(hotCue);\n if (result == null) {\n result = new DeckReference(player, hotCue);\n playerMap.put(hotCue, result);\n }\n return result;\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 }", "@Override\n public void destroy(T instance, CreationalContext<T> creationalContext) {\n super.destroy(instance, creationalContext);\n try {\n getProducer().preDestroy(instance);\n // WELD-1010 hack?\n if (creationalContext instanceof CreationalContextImpl) {\n ((CreationalContextImpl<T>) creationalContext).release(this, instance);\n } else {\n creationalContext.release();\n }\n } catch (Exception e) {\n BeanLogger.LOG.errorDestroying(instance, this);\n BeanLogger.LOG.catchingDebug(e);\n }\n }", "public double get( int index ) {\n MatrixType type = mat.getType();\n\n if( type.isReal()) {\n if (type.getBits() == 64) {\n return ((DMatrixRMaj) mat).data[index];\n } else {\n return ((FMatrixRMaj) mat).data[index];\n }\n } else {\n throw new IllegalArgumentException(\"Complex matrix. Call get(int,Complex64F) instead\");\n }\n }", "private static <R> RowKey buildRowKey(AssociationKey associationKey, R row, AssociationRowAccessor<R> accessor) {\n\t\tString[] columnNames = associationKey.getMetadata().getRowKeyColumnNames();\n\t\tObject[] columnValues = new Object[columnNames.length];\n\n\t\tfor ( int i = 0; i < columnNames.length; i++ ) {\n\t\t\tString columnName = columnNames[i];\n\t\t\tcolumnValues[i] = associationKey.getMetadata().isKeyColumn( columnName ) ? associationKey.getColumnValue( columnName ) : accessor.get( row, columnName );\n\t\t}\n\n\t\treturn new RowKey( columnNames, columnValues );\n\t}", "protected void runStatements(Reader reader, PrintStream out)\n throws IOException {\n log.debug(\"runStatements()\");\n StringBuilder txt = new StringBuilder();\n String line = \"\";\n BufferedReader in = new BufferedReader(reader);\n\n while ((line = in.readLine()) != null) {\n line = getProject().replaceProperties(line);\n if (line.indexOf(\"--\") >= 0) {\n txt.append(\"\\n\");\n }\n }\n // Catch any statements not followed by ;\n if (!txt.toString().equals(\"\")) {\n execGroovy(txt.toString(), out);\n }\n }", "public static rnat6_nsip6_binding[] get(nitro_service service, String name) throws Exception{\n\t\trnat6_nsip6_binding obj = new rnat6_nsip6_binding();\n\t\tobj.set_name(name);\n\t\trnat6_nsip6_binding response[] = (rnat6_nsip6_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "protected final void _onConnect(WebSocketContext context) {\n if (null != connectionListener) {\n connectionListener.onConnect(context);\n }\n connectionListenerManager.notifyFreeListeners(context, false);\n Act.eventBus().emit(new WebSocketConnectEvent(context));\n }" ]
B tensor is ignored for CUDNN_OP_TENSOR_SQRT, CUDNN_OP_TENSOR_NOT.
[ "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 int millisecondsToX(long milliseconds) {\n if (autoScroll.get()) {\n int playHead = (getWidth() / 2) + 2;\n long offset = milliseconds - getFurthestPlaybackPosition();\n return playHead + (Util.timeToHalfFrame(offset) / scale.get());\n }\n return Util.timeToHalfFrame(milliseconds) / scale.get();\n }", "public static base_response expire(nitro_service client, cachecontentgroup resource) throws Exception {\n\t\tcachecontentgroup expireresource = new cachecontentgroup();\n\t\texpireresource.name = resource.name;\n\t\treturn expireresource.perform_operation(client,\"expire\");\n\t}", "public static Function<String, String> createStringTemplateSource(\n I_CmsFormatterBean formatter,\n Supplier<CmsXmlContent> contentSupplier) {\n\n return key -> {\n String result = null;\n if (formatter != null) {\n result = formatter.getAttributes().get(key);\n }\n if (result == null) {\n CmsXmlContent content = contentSupplier.get();\n if (content != null) {\n result = content.getHandler().getParameter(key);\n }\n }\n return result;\n };\n }", "@SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n public List<HazeltaskTask<G>> shutdownNow() {\n\t return (List<HazeltaskTask<G>>) (List) localExecutorPool.shutdownNow();\n\t}", "private static void checkSensibility(AnnotatedType<?> type) {\n // check if it has a constructor\n if (type.getConstructors().isEmpty() && !type.getJavaClass().isInterface()) {\n MetadataLogger.LOG.noConstructor(type);\n }\n\n Set<Class<?>> hierarchy = new HashSet<Class<?>>();\n for (Class<?> clazz = type.getJavaClass(); clazz != null; clazz = clazz.getSuperclass()) {\n hierarchy.add(clazz);\n hierarchy.addAll(Reflections.getInterfaceClosure(clazz));\n }\n checkMembersBelongToHierarchy(type.getConstructors(), hierarchy, type);\n checkMembersBelongToHierarchy(type.getMethods(), hierarchy, type);\n checkMembersBelongToHierarchy(type.getFields(), hierarchy, type);\n }", "public static String format(Flags flags) {\r\n StringBuilder buf = new StringBuilder();\r\n buf.append('(');\r\n if (flags.contains(Flags.Flag.ANSWERED)) {\r\n buf.append(\"\\\\Answered \");\r\n }\r\n if (flags.contains(Flags.Flag.DELETED)) {\r\n buf.append(\"\\\\Deleted \");\r\n }\r\n if (flags.contains(Flags.Flag.DRAFT)) {\r\n buf.append(\"\\\\Draft \");\r\n }\r\n if (flags.contains(Flags.Flag.FLAGGED)) {\r\n buf.append(\"\\\\Flagged \");\r\n }\r\n if (flags.contains(Flags.Flag.RECENT)) {\r\n buf.append(\"\\\\Recent \");\r\n }\r\n if (flags.contains(Flags.Flag.SEEN)) {\r\n buf.append(\"\\\\Seen \");\r\n }\r\n String[] userFlags = flags.getUserFlags();\r\n if(null!=userFlags) {\r\n for(String uf: userFlags) {\r\n buf.append(uf).append(' ');\r\n }\r\n }\r\n // Remove the trailing space, if necessary.\r\n if (buf.length() > 1) {\r\n buf.setLength(buf.length() - 1);\r\n }\r\n buf.append(')');\r\n return buf.toString();\r\n }", "public ByteBuffer[] toDirectByteBuffers(long offset, long size) {\n long pos = offset;\n long blockSize = Integer.MAX_VALUE;\n long limit = offset + size;\n int numBuffers = (int) ((size + (blockSize - 1)) / blockSize);\n ByteBuffer[] result = new ByteBuffer[numBuffers];\n int index = 0;\n while (pos < limit) {\n long blockLength = Math.min(limit - pos, blockSize);\n result[index++] = UnsafeUtil.newDirectByteBuffer(address() + pos, (int) blockLength, this)\n .order(ByteOrder.nativeOrder());\n pos += blockLength;\n }\n return result;\n\n }", "public void sendFaderStartCommand(Set<Integer> deviceNumbersToStart, Set<Integer> deviceNumbersToStop) throws IOException {\n ensureRunning();\n byte[] payload = new byte[FADER_START_PAYLOAD.length];\n System.arraycopy(FADER_START_PAYLOAD, 0, payload, 0, FADER_START_PAYLOAD.length);\n payload[2] = getDeviceNumber();\n\n for (int i = 1; i <= 4; i++) {\n if (deviceNumbersToStart.contains(i)) {\n payload[i + 4] = 0;\n }\n if (deviceNumbersToStop.contains(i)) {\n payload[i + 4] = 1;\n }\n }\n\n assembleAndSendPacket(Util.PacketType.FADER_START_COMMAND, payload, getBroadcastAddress(), BeatFinder.BEAT_PORT);\n }", "public void setSeed(String randomSeed) {\n if (!Strings.isNullOrEmpty(getProject().getUserProperty(SYSPROP_RANDOM_SEED()))) {\n String userProperty = getProject().getUserProperty(SYSPROP_RANDOM_SEED());\n if (!userProperty.equals(randomSeed)) {\n log(\"Ignoring seed attribute because it is overridden by user properties.\", Project.MSG_WARN);\n }\n } else if (!Strings.isNullOrEmpty(randomSeed)) {\n this.random = randomSeed;\n }\n }" ]
Stores the gathered usage statistics about term uses by language to a CSV file. @param usageStatistics the statistics to store @param fileName the name of the file to use
[ "private void writeTermStatisticsToFile(UsageStatistics usageStatistics,\n\t\t\tString fileName) {\n\n\t\t// Make sure all keys are present in label count map:\n\t\tfor (String key : usageStatistics.aliasCounts.keySet()) {\n\t\t\tcountKey(usageStatistics.labelCounts, key, 0);\n\t\t}\n\t\tfor (String key : usageStatistics.descriptionCounts.keySet()) {\n\t\t\tcountKey(usageStatistics.labelCounts, key, 0);\n\t\t}\n\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(fileName))) {\n\n\t\t\tout.println(\"Language,Labels,Descriptions,Aliases\");\n\t\t\tfor (Entry<String, Integer> entry : usageStatistics.labelCounts\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tcountKey(usageStatistics.aliasCounts, entry.getKey(), 0);\n\t\t\t\tint aCount = usageStatistics.aliasCounts.get(entry.getKey());\n\t\t\t\tcountKey(usageStatistics.descriptionCounts, entry.getKey(), 0);\n\t\t\t\tint dCount = usageStatistics.descriptionCounts.get(entry\n\t\t\t\t\t\t.getKey());\n\t\t\t\tout.println(entry.getKey() + \",\" + entry.getValue() + \",\"\n\t\t\t\t\t\t+ dCount + \",\" + aCount);\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}" ]
[ "public static ModelNode createReadResourceOperation(final ModelNode address, final boolean recursive) {\n final ModelNode op = createOperation(READ_RESOURCE_OPERATION, address);\n op.get(RECURSIVE).set(recursive);\n return op;\n }", "public int nullity() {\n if( is64 ) {\n return SingularOps_DDRM.nullity((SingularValueDecomposition_F64)svd, 10.0 * UtilEjml.EPS);\n } else {\n return SingularOps_FDRM.nullity((SingularValueDecomposition_F32)svd, 5.0f * UtilEjml.F_EPS);\n }\n }", "public List<Collaborator> listCollaborators(String appName) {\n return connection.execute(new CollabList(appName), apiKey);\n }", "public static PathAddress pathAddress(final ModelNode node) {\n if (node.isDefined()) {\n\n// final List<Property> props = node.asPropertyList();\n // Following bit is crap TODO; uncomment above and delete below\n // when bug is fixed\n final List<Property> props = new ArrayList<Property>();\n String key = null;\n for (ModelNode element : node.asList()) {\n Property prop = null;\n if (element.getType() == ModelType.PROPERTY || element.getType() == ModelType.OBJECT) {\n prop = element.asProperty();\n } else if (key == null) {\n key = element.asString();\n } else {\n prop = new Property(key, element);\n }\n if (prop != null) {\n props.add(prop);\n key = null;\n }\n\n }\n if (props.size() == 0) {\n return EMPTY_ADDRESS;\n } else {\n final Set<String> seen = new HashSet<String>();\n final List<PathElement> values = new ArrayList<PathElement>();\n int index = 0;\n for (final Property prop : props) {\n final String name = prop.getName();\n if (seen.add(name)) {\n values.add(new PathElement(name, prop.getValue().asString()));\n } else {\n throw duplicateElement(name);\n }\n if (index == 1 && name.equals(SERVER) && seen.contains(HOST)) {\n seen.clear();\n }\n index++;\n }\n return new PathAddress(Collections.unmodifiableList(values));\n }\n } else {\n return EMPTY_ADDRESS;\n }\n }", "public void stopAnimation() {\n if(widget != null) {\n widget.removeStyleName(\"animated\");\n widget.removeStyleName(transition.getCssName());\n widget.removeStyleName(CssName.INFINITE);\n }\n }", "public synchronized int put(byte[] src, int off, int len) {\n if (available == capacity) {\n return 0;\n }\n\n // limit is last index to put + 1\n int limit = idxPut < idxGet ? idxGet : capacity;\n int count = Math.min(limit - idxPut, len);\n System.arraycopy(src, off, buffer, idxPut, count);\n idxPut += count;\n\n if (idxPut == capacity) {\n // Array end reached, check if we have more\n int count2 = Math.min(len - count, idxGet);\n if (count2 > 0) {\n System.arraycopy(src, off + count, buffer, 0, count2);\n idxPut = count2;\n count += count2;\n } else {\n idxPut = 0;\n }\n }\n available += count;\n return count;\n }", "boolean lockInterruptibly(final Integer permit, final long timeout, final TimeUnit unit) throws InterruptedException {\n if (permit == null) {\n throw new IllegalArgumentException();\n }\n return sync.tryAcquireNanos(permit, unit.toNanos(timeout));\n }", "public static void load(File file)\n {\n try(FileInputStream inputStream = new FileInputStream(file))\n {\n LineIterator it = IOUtils.lineIterator(inputStream, \"UTF-8\");\n while (it.hasNext())\n {\n String line = it.next();\n if (!line.startsWith(\"#\") && !line.trim().isEmpty())\n {\n add(line);\n }\n }\n }\n catch (Exception e)\n {\n throw new WindupException(\"Failed loading archive ignore patterns from [\" + file.toString() + \"]\", e);\n }\n }", "@SuppressWarnings(\"unused\")\n public static void changeCredentials(String accountID, String token) {\n changeCredentials(accountID, token, null);\n }" ]
This method reads an eight byte integer from the input array. @param data the input array @param offset offset of integer data in the array @return integer value
[ "public static final long getLong(byte[] data, int offset)\n {\n if (data.length != 8)\n {\n throw new UnexpectedStructureException();\n }\n\n long result = 0;\n int i = offset;\n for (int shiftBy = 0; shiftBy < 64; shiftBy += 8)\n {\n result |= ((long) (data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }" ]
[ "public void generateOutlineNumber(Task parent)\n {\n String outline;\n\n if (parent == null)\n {\n if (NumberHelper.getInt(getUniqueID()) == 0)\n {\n outline = \"0\";\n }\n else\n {\n outline = Integer.toString(getParentFile().getChildTasks().size() + 1);\n }\n }\n else\n {\n outline = parent.getOutlineNumber();\n\n int index = outline.lastIndexOf(\".0\");\n\n if (index != -1)\n {\n outline = outline.substring(0, index);\n }\n\n int childTaskCount = parent.getChildTasks().size() + 1;\n if (outline.equals(\"0\"))\n {\n outline = Integer.toString(childTaskCount);\n }\n else\n {\n outline += (\".\" + childTaskCount);\n }\n }\n\n setOutlineNumber(outline);\n }", "public synchronized void addRoleMapping(final String roleName) {\n HashMap<String, RoleMappingImpl> newRoles = new HashMap<String, RoleMappingImpl>(roleMappings);\n if (newRoles.containsKey(roleName) == false) {\n newRoles.put(roleName, new RoleMappingImpl(roleName));\n roleMappings = Collections.unmodifiableMap(newRoles);\n }\n }", "public void waitForBuffer(long timeoutMilli) {\n //assert(callerProcessing.booleanValue() == false);\n\n synchronized(buffer) {\n if( dirtyBuffer )\n return;\n if( !foundEOF() ) {\n logger.trace(\"Waiting for things to come in, or until timeout\");\n try {\n if( timeoutMilli > 0 )\n buffer.wait(timeoutMilli);\n else\n buffer.wait();\n } catch(InterruptedException ie) {\n logger.trace(\"Woken up, while waiting for buffer\");\n }\n // this might went early, but running the processing again isn't a big deal\n logger.trace(\"Waited\");\n }\n }\n }", "protected static Connection memorize(final Connection target, final ConnectionHandle connectionHandle) {\n\n\t\treturn (Connection) Proxy.newProxyInstance(\n\t\t\t\tConnectionProxy.class.getClassLoader(),\n\t\t\t\tnew Class[] {ConnectionProxy.class},\n\t\t\t\tnew MemorizeTransactionProxy(target, connectionHandle));\n\t}", "public void setSchema(String schema)\n {\n if (schema.charAt(schema.length() - 1) != '.')\n {\n schema = schema + '.';\n }\n m_schema = schema;\n }", "public final void visitChildren(final Visitor visitor)\n\t{\n\t\tfor (final DiffNode child : children.values())\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tchild.visit(visitor);\n\t\t\t}\n\t\t\tcatch (final StopVisitationException e)\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}", "public Integer next() {\n\t\tfor(int i = currentIndex; i < t.size(); i++){\n\t\t\tif(i+timelag>=t.size()){\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif((t.get(i) != null) && (t.get(i+timelag) != null)){\n\t\t\t\tif(overlap){\n\t\t\t\t\tcurrentIndex = i+1;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tcurrentIndex = i+timelag;\n\t\t\t\t}\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn null;\n\t}", "private DefBase getDefForLevel(String level)\r\n {\r\n if (LEVEL_CLASS.equals(level))\r\n {\r\n return _curClassDef;\r\n }\r\n else if (LEVEL_FIELD.equals(level))\r\n {\r\n return _curFieldDef;\r\n }\r\n else if (LEVEL_REFERENCE.equals(level))\r\n {\r\n return _curReferenceDef;\r\n }\r\n else if (LEVEL_COLLECTION.equals(level))\r\n {\r\n return _curCollectionDef;\r\n }\r\n else if (LEVEL_OBJECT_CACHE.equals(level))\r\n {\r\n return _curObjectCacheDef;\r\n }\r\n else if (LEVEL_INDEX_DESC.equals(level))\r\n {\r\n return _curIndexDescriptorDef;\r\n }\r\n else if (LEVEL_TABLE.equals(level))\r\n {\r\n return _curTableDef;\r\n }\r\n else if (LEVEL_COLUMN.equals(level))\r\n {\r\n return _curColumnDef;\r\n }\r\n else if (LEVEL_FOREIGNKEY.equals(level))\r\n {\r\n return _curForeignkeyDef;\r\n }\r\n else if (LEVEL_INDEX.equals(level))\r\n {\r\n return _curIndexDef;\r\n }\r\n else if (LEVEL_PROCEDURE.equals(level))\r\n {\r\n return _curProcedureDef;\r\n }\r\n else if (LEVEL_PROCEDURE_ARGUMENT.equals(level))\r\n {\r\n return _curProcedureArgumentDef;\r\n }\r\n else\r\n {\r\n return null;\r\n }\r\n }", "public void set(String name, Object value) {\n hashAttributes.put(name, value);\n\n if (plugin != null) {\n plugin.invalidate();\n }\n }" ]
Write exceptions into the format used by MSPDI files from Project 2007 onwards. @param calendar parent calendar @param exceptions list of exceptions
[ "private void writeExceptions12(Project.Calendars.Calendar calendar, List<ProjectCalendarException> exceptions)\n {\n Exceptions ce = m_factory.createProjectCalendarsCalendarExceptions();\n calendar.setExceptions(ce);\n List<Exceptions.Exception> el = ce.getException();\n\n for (ProjectCalendarException exception : exceptions)\n {\n Exceptions.Exception ex = m_factory.createProjectCalendarsCalendarExceptionsException();\n el.add(ex);\n\n ex.setName(exception.getName());\n boolean working = exception.getWorking();\n ex.setDayWorking(Boolean.valueOf(working));\n\n if (exception.getRecurring() == null)\n {\n ex.setEnteredByOccurrences(Boolean.FALSE);\n ex.setOccurrences(BigInteger.ONE);\n ex.setType(BigInteger.ONE);\n }\n else\n {\n populateRecurringException(exception, ex);\n }\n\n Project.Calendars.Calendar.Exceptions.Exception.TimePeriod period = m_factory.createProjectCalendarsCalendarExceptionsExceptionTimePeriod();\n ex.setTimePeriod(period);\n period.setFromDate(exception.getFromDate());\n period.setToDate(exception.getToDate());\n\n if (working)\n {\n Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes times = m_factory.createProjectCalendarsCalendarExceptionsExceptionWorkingTimes();\n ex.setWorkingTimes(times);\n List<Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes.WorkingTime> timesList = times.getWorkingTime();\n\n for (DateRange range : exception)\n {\n Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes.WorkingTime time = m_factory.createProjectCalendarsCalendarExceptionsExceptionWorkingTimesWorkingTime();\n timesList.add(time);\n\n time.setFromTime(range.getStart());\n time.setToTime(range.getEnd());\n }\n }\n }\n }" ]
[ "public static auditnslogpolicy_systemglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditnslogpolicy_systemglobal_binding obj = new auditnslogpolicy_systemglobal_binding();\n\t\tobj.set_name(name);\n\t\tauditnslogpolicy_systemglobal_binding response[] = (auditnslogpolicy_systemglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public int update(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException {\n\t\ttry {\n\t\t\t// there is always and id field as an argument so just return 0 lines updated\n\t\t\tif (argFieldTypes.length <= 1) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tObject[] args = getFieldObjects(data);\n\t\t\tObject newVersion = null;\n\t\t\tif (versionFieldType != null) {\n\t\t\t\tnewVersion = versionFieldType.extractJavaFieldValue(data);\n\t\t\t\tnewVersion = versionFieldType.moveToNextValue(newVersion);\n\t\t\t\targs[versionFieldTypeIndex] = versionFieldType.convertJavaFieldToSqlArgValue(newVersion);\n\t\t\t}\n\t\t\tint rowC = databaseConnection.update(statement, args, argFieldTypes);\n\t\t\tif (rowC > 0) {\n\t\t\t\tif (newVersion != null) {\n\t\t\t\t\t// if we have updated a row then update the version field in our object to the new value\n\t\t\t\t\tversionFieldType.assignField(connectionSource, data, newVersion, false, null);\n\t\t\t\t}\n\t\t\t\tif (objectCache != null) {\n\t\t\t\t\t// if we've changed something then see if we need to update our cache\n\t\t\t\t\tObject id = idField.extractJavaFieldValue(data);\n\t\t\t\t\tT cachedData = objectCache.get(clazz, id);\n\t\t\t\t\tif (cachedData != null && cachedData != data) {\n\t\t\t\t\t\t// copy each field from the updated data into the cached object\n\t\t\t\t\t\tfor (FieldType fieldType : tableInfo.getFieldTypes()) {\n\t\t\t\t\t\t\tif (fieldType != idField) {\n\t\t\t\t\t\t\t\tfieldType.assignField(connectionSource, cachedData,\n\t\t\t\t\t\t\t\t\t\tfieldType.extractJavaFieldValue(data), false, objectCache);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tlogger.debug(\"update data with statement '{}' and {} args, changed {} rows\", statement, args.length, rowC);\n\t\t\tif (args.length > 0) {\n\t\t\t\t// need to do the (Object) cast to force args to be a single object\n\t\t\t\tlogger.trace(\"update arguments: {}\", (Object) args);\n\t\t\t}\n\t\t\treturn rowC;\n\t\t} catch (SQLException e) {\n\t\t\tthrow SqlExceptionUtil.create(\"Unable to run update stmt on object \" + data + \": \" + statement, e);\n\t\t}\n\t}", "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 }", "public static void setTranslucentNavigationFlag(Activity activity, boolean on) {\n if (Build.VERSION.SDK_INT >= 19) {\n setFlag(activity, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, on);\n }\n }", "public void execute(CommandHandler handler,\n int timeout,\n TimeUnit unit) throws\n CommandLineException,\n InterruptedException, ExecutionException, TimeoutException {\n ExecutableBuilder builder = new ExecutableBuilder() {\n CommandContext c = newTimeoutCommandContext(ctx);\n @Override\n public Executable build() {\n return () -> {\n handler.handle(c);\n };\n }\n\n @Override\n public CommandContext getCommandContext() {\n return c;\n }\n };\n execute(builder, timeout, unit);\n }", "protected static void statistics(int from, int to) {\r\n\t// check that primes contain no accidental errors\r\n\tfor (int i=0; i<primeCapacities.length-1; i++) {\r\n\t\tif (primeCapacities[i] >= primeCapacities[i+1]) throw new RuntimeException(\"primes are unsorted or contain duplicates; detected at \"+i+\"@\"+primeCapacities[i]);\r\n\t}\r\n\t\r\n\tdouble accDeviation = 0.0;\r\n\tdouble maxDeviation = - 1.0;\r\n\r\n\tfor (int i=from; i<=to; i++) {\r\n\t\tint primeCapacity = nextPrime(i);\r\n\t\t//System.out.println(primeCapacity);\r\n\t\tdouble deviation = (primeCapacity - i) / (double)i;\r\n\t\t\r\n\t\tif (deviation > maxDeviation) {\r\n\t\t\tmaxDeviation = deviation;\r\n\t\t\tSystem.out.println(\"new maxdev @\"+i+\"@dev=\"+maxDeviation);\r\n\t\t}\r\n\r\n\t\taccDeviation += deviation;\r\n\t}\r\n\tlong width = 1 + (long)to - (long)from;\r\n\t\r\n\tdouble meanDeviation = accDeviation/width;\r\n\tSystem.out.println(\"Statistics for [\"+ from + \",\"+to+\"] are as follows\");\r\n\tSystem.out.println(\"meanDeviation = \"+(float)meanDeviation*100+\" %\");\r\n\tSystem.out.println(\"maxDeviation = \"+(float)maxDeviation*100+\" %\");\r\n}", "public final int toCodePoints(char[] src, int srcOff, int srcLen, int[] dest, int destOff) {\n if (srcLen < 0) {\n throw new IllegalArgumentException(\"srcLen must be >= 0\");\n }\n int codePointCount = 0;\n for (int i = 0; i < srcLen; ) {\n final int cp = codePointAt(src, srcOff + i, srcOff + srcLen);\n final int charCount = Character.charCount(cp);\n dest[destOff + codePointCount++] = cp;\n i += charCount;\n }\n return codePointCount;\n }", "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 }", "static String fromPackageName(String packageName) {\n List<String> tokens = tokenOf(packageName);\n return fromTokens(tokens);\n }" ]
Saves the favorites. @param favorites the list of favorites to save @throws CmsException if something goes wrong
[ "public void saveFavorites(List<CmsFavoriteEntry> favorites) throws CmsException {\n\n try {\n JSONObject json = new JSONObject();\n JSONArray array = new JSONArray();\n for (CmsFavoriteEntry entry : favorites) {\n array.put(entry.toJson());\n }\n json.put(BASE_KEY, array);\n String data = json.toString();\n CmsUser user = readUser();\n user.setAdditionalInfo(ADDINFO_KEY, data);\n m_cms.writeUser(user);\n } catch (JSONException e) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n\n }" ]
[ "public synchronized Response doCommandFullResponse(String command) throws CommandFormatException, IOException {\n ModelNode request = cmdCtx.buildRequest(command);\n boolean replacedBytes = replaceFilePathsWithBytes(request);\n OperationResponse response = execute(request, isSlowCommand(command) || replacedBytes);\n return new Response(command, request, response);\n }", "private void readProjectProperties(Project ganttProject)\n {\n ProjectProperties mpxjProperties = m_projectFile.getProjectProperties();\n mpxjProperties.setName(ganttProject.getName());\n mpxjProperties.setCompany(ganttProject.getCompany());\n mpxjProperties.setDefaultDurationUnits(TimeUnit.DAYS);\n\n String locale = ganttProject.getLocale();\n if (locale == null)\n {\n locale = \"en_US\";\n }\n m_localeDateFormat = DateFormat.getDateInstance(DateFormat.SHORT, new Locale(locale));\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}", "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\n public final float getFloat(final int i) {\n double val = this.array.optDouble(i, Double.MAX_VALUE);\n if (val == Double.MAX_VALUE) {\n throw new ObjectMissingException(this, \"[\" + i + \"]\");\n }\n return (float) val;\n }", "public static CentralDogma forConfig(File configFile) throws IOException {\n requireNonNull(configFile, \"configFile\");\n return new CentralDogma(Jackson.readValue(configFile, CentralDogmaConfig.class));\n }", "public synchronized void jumpToBeat(int beat) {\n\n if (beat < 1) {\n beat = 1;\n } else {\n beat = wrapBeat(beat);\n }\n\n if (playing.get()) {\n metronome.jumpToBeat(beat);\n } else {\n whereStopped.set(metronome.getSnapshot(metronome.getTimeOfBeat(beat)));\n }\n }", "public static BoxAPIConnection restore(String clientID, String clientSecret, String state) {\n BoxAPIConnection api = new BoxAPIConnection(clientID, clientSecret);\n api.restore(state);\n return api;\n }", "private void initKeySetForXmlBundle() {\n\n // consider only available locales\n for (Locale l : m_locales) {\n if (m_xmlBundle.hasLocale(l)) {\n Set<Object> keys = new HashSet<Object>();\n for (I_CmsXmlContentValue msg : m_xmlBundle.getValueSequence(\"Message\", l).getValues()) {\n String msgpath = msg.getPath();\n keys.add(m_xmlBundle.getStringValue(m_cms, msgpath + \"/Key\", l));\n }\n m_keyset.updateKeySet(null, keys);\n }\n }\n\n }" ]
Returns the names of parser rules that should be called in order to obtain the follow elements for the parser call stack described by the given param.
[ "public String[][] getRequiredRuleNames(Param param) {\n\t\tif (isFiltered(param)) {\n\t\t\treturn EMPTY_ARRAY;\n\t\t}\n\t\tAbstractElement elementToParse = param.elementToParse;\n\t\tString ruleName = param.ruleName;\n\t\tif (ruleName == null) {\n\t\t\treturn getRequiredRuleNames(param, elementToParse);\n\t\t}\n\t\treturn getAdjustedRequiredRuleNames(param, elementToParse, ruleName);\n\t}" ]
[ "protected void setupPivotInfo() {\n for( int col = 0; col < numCols; col++ ) {\n pivots[col] = col;\n double c[] = dataQR[col];\n double norm = 0;\n for( int row = 0; row < numRows; row++ ) {\n double element = c[row];\n norm += element*element;\n }\n normsCol[col] = norm;\n }\n }", "private void ensureReferencedPKs(ModelDef modelDef, CollectionDescriptorDef collDef) throws ConstraintException\r\n {\r\n String elementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF);\r\n ClassDescriptorDef elementClassDef = modelDef.getClass(elementClassName);\r\n String indirTable = collDef.getProperty(PropertyHelper.OJB_PROPERTY_INDIRECTION_TABLE);\r\n String localKey = collDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY);\r\n String remoteKey = collDef.getProperty(PropertyHelper.OJB_PROPERTY_REMOTE_FOREIGNKEY);\r\n boolean hasRemoteKey = remoteKey != null;\r\n ArrayList fittingCollections = new ArrayList();\r\n\r\n // we're checking for the fitting remote collection(s) and also\r\n // use their foreignkey as remote-foreignkey in the original collection definition\r\n for (Iterator it = elementClassDef.getAllExtentClasses(); it.hasNext();)\r\n {\r\n ClassDescriptorDef subTypeDef = (ClassDescriptorDef)it.next();\r\n\r\n // find the collection in the element class that has the same indirection table\r\n for (Iterator collIt = subTypeDef.getCollections(); collIt.hasNext();)\r\n {\r\n CollectionDescriptorDef curCollDef = (CollectionDescriptorDef)collIt.next();\r\n\r\n if (indirTable.equals(curCollDef.getProperty(PropertyHelper.OJB_PROPERTY_INDIRECTION_TABLE)) &&\r\n (collDef != curCollDef) &&\r\n (!hasRemoteKey || CommaListIterator.sameLists(remoteKey, curCollDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY))) &&\r\n (!curCollDef.hasProperty(PropertyHelper.OJB_PROPERTY_REMOTE_FOREIGNKEY) ||\r\n CommaListIterator.sameLists(localKey, curCollDef.getProperty(PropertyHelper.OJB_PROPERTY_REMOTE_FOREIGNKEY))))\r\n {\r\n fittingCollections.add(curCollDef);\r\n }\r\n }\r\n }\r\n if (!fittingCollections.isEmpty())\r\n {\r\n // if there is more than one, check that they match, i.e. that they all have the same foreignkeys\r\n if (!hasRemoteKey && (fittingCollections.size() > 1))\r\n {\r\n CollectionDescriptorDef firstCollDef = (CollectionDescriptorDef)fittingCollections.get(0);\r\n String foreignKey = firstCollDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY);\r\n\r\n for (int idx = 1; idx < fittingCollections.size(); idx++)\r\n {\r\n CollectionDescriptorDef curCollDef = (CollectionDescriptorDef)fittingCollections.get(idx);\r\n\r\n if (!CommaListIterator.sameLists(foreignKey, curCollDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY)))\r\n {\r\n throw new ConstraintException(\"Cannot determine the element-side collection that corresponds to the collection \"+\r\n collDef.getName()+\" in type \"+collDef.getOwner().getName()+\r\n \" because there are at least two different collections that would fit.\"+\r\n \" Specifying remote-foreignkey in the original collection \"+collDef.getName()+\r\n \" will perhaps help\");\r\n }\r\n }\r\n // store the found keys at the collections\r\n collDef.setProperty(PropertyHelper.OJB_PROPERTY_REMOTE_FOREIGNKEY, foreignKey);\r\n for (int idx = 0; idx < fittingCollections.size(); idx++)\r\n {\r\n CollectionDescriptorDef curCollDef = (CollectionDescriptorDef)fittingCollections.get(idx);\r\n\r\n curCollDef.setProperty(PropertyHelper.OJB_PROPERTY_REMOTE_FOREIGNKEY, localKey);\r\n }\r\n }\r\n }\r\n\r\n // copy subclass pk fields into target class (if not already present)\r\n ensurePKsFromHierarchy(elementClassDef);\r\n }", "public void setPickingEnabled(boolean enabled) {\n if (enabled != getPickingEnabled()) {\n if (enabled) {\n attachComponent(new GVRSphereCollider(getGVRContext()));\n } else {\n detachComponent(GVRCollider.getComponentType());\n }\n }\n }", "protected AllowableActions collectAllowableActions(CmsObject cms, CmsResource file) {\r\n\r\n try {\r\n\r\n if (file == null) {\r\n throw new IllegalArgumentException(\"File must not be null!\");\r\n }\r\n CmsLock lock = cms.getLock(file);\r\n CmsUser user = cms.getRequestContext().getCurrentUser();\r\n boolean canWrite = !cms.getRequestContext().getCurrentProject().isOnlineProject()\r\n && (lock.isOwnedBy(user) || lock.isLockableBy(user))\r\n && cms.hasPermissions(file, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.DEFAULT);\r\n boolean isReadOnly = !canWrite;\r\n boolean isFolder = file.isFolder();\r\n boolean isRoot = file.getRootPath().length() <= 1;\r\n\r\n Set<Action> aas = new LinkedHashSet<Action>();\r\n addAction(aas, Action.CAN_GET_OBJECT_PARENTS, !isRoot);\r\n addAction(aas, Action.CAN_GET_PROPERTIES, true);\r\n addAction(aas, Action.CAN_UPDATE_PROPERTIES, !isReadOnly);\r\n addAction(aas, Action.CAN_MOVE_OBJECT, !isReadOnly && !isRoot);\r\n addAction(aas, Action.CAN_DELETE_OBJECT, !isReadOnly && !isRoot);\r\n if (isFolder) {\r\n addAction(aas, Action.CAN_GET_DESCENDANTS, true);\r\n addAction(aas, Action.CAN_GET_CHILDREN, true);\r\n addAction(aas, Action.CAN_GET_FOLDER_PARENT, !isRoot);\r\n addAction(aas, Action.CAN_GET_FOLDER_TREE, true);\r\n addAction(aas, Action.CAN_CREATE_DOCUMENT, !isReadOnly);\r\n addAction(aas, Action.CAN_CREATE_FOLDER, !isReadOnly);\r\n addAction(aas, Action.CAN_DELETE_TREE, !isReadOnly);\r\n } else {\r\n addAction(aas, Action.CAN_GET_CONTENT_STREAM, true);\r\n addAction(aas, Action.CAN_SET_CONTENT_STREAM, !isReadOnly);\r\n addAction(aas, Action.CAN_GET_ALL_VERSIONS, true);\r\n }\r\n AllowableActionsImpl result = new AllowableActionsImpl();\r\n result.setAllowableActions(aas);\r\n return result;\r\n } catch (CmsException e) {\r\n handleCmsException(e);\r\n return null;\r\n }\r\n }", "private void animateIndicatorInvalidate() {\n if (mIndicatorScroller.computeScrollOffset()) {\n mIndicatorOffset = mIndicatorScroller.getCurr();\n invalidate();\n\n if (!mIndicatorScroller.isFinished()) {\n postOnAnimation(mIndicatorRunnable);\n return;\n }\n }\n\n completeAnimatingIndicator();\n }", "protected static Connection memorize(final Connection target, final ConnectionHandle connectionHandle) {\n\n\t\treturn (Connection) Proxy.newProxyInstance(\n\t\t\t\tConnectionProxy.class.getClassLoader(),\n\t\t\t\tnew Class[] {ConnectionProxy.class},\n\t\t\t\tnew MemorizeTransactionProxy(target, connectionHandle));\n\t}", "public void addBeanToBeanMapping(BeanToBeanMapping beanToBeanMapping) {\r\n\t\tbeanToBeanMappings.put(ClassPair.get(beanToBeanMapping\r\n\t\t\t\t.getSourceClass(), beanToBeanMapping.getDestinationClass()),\r\n\t\t\t\tbeanToBeanMapping);\r\n\t}", "private static FieldType getPlaceholder(final Class<?> type, final int fieldID)\n {\n return new FieldType()\n {\n @Override public FieldTypeClass getFieldTypeClass()\n {\n return FieldTypeClass.UNKNOWN;\n }\n\n @Override public String name()\n {\n return \"UNKNOWN\";\n }\n\n @Override public int getValue()\n {\n return fieldID;\n }\n\n @Override public String getName()\n {\n return \"Unknown \" + (type == null ? \"\" : type.getSimpleName() + \"(\" + fieldID + \")\");\n }\n\n @Override public String getName(Locale locale)\n {\n return getName();\n }\n\n @Override public DataType getDataType()\n {\n return null;\n }\n\n @Override public FieldType getUnitsType()\n {\n return null;\n }\n\n @Override public String toString()\n {\n return getName();\n }\n };\n }", "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 }" ]
Check if a given string is a template path or template content If the string contains anyone the following characters then we assume it is content, otherwise it is path: * space characters * non numeric-alphabetic characters except: ** dot "." ** dollar: "$" @param string the string to be tested @return `true` if the string literal is template content or `false` otherwise
[ "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 }" ]
[ "public Photo getInfo(String photoId, String secret) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_INFO);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n if (secret != null) {\r\n parameters.put(\"secret\", secret);\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photoElement = response.getPayload();\r\n\r\n return PhotoUtils.createPhoto(photoElement);\r\n }", "@Override\n\tpublic void set(String headerName, String headerValue) {\n\t\tList<String> headerValues = new LinkedList<String>();\n\t\theaderValues.add(headerValue);\n\t\theaders.put(headerName, headerValues);\n\t}", "public static boolean isSpreadSafe(Expression expression) {\r\n if (expression instanceof MethodCallExpression) {\r\n return ((MethodCallExpression) expression).isSpreadSafe();\r\n }\r\n if (expression instanceof PropertyExpression) {\r\n return ((PropertyExpression) expression).isSpreadSafe();\r\n }\r\n return false;\r\n }", "private FieldType findForeignFieldType(Class<?> clazz, Class<?> foreignClass, Dao<?, ?> foreignDao)\n\t\t\tthrows SQLException {\n\t\tString foreignColumnName = fieldConfig.getForeignCollectionForeignFieldName();\n\t\tfor (FieldType fieldType : foreignDao.getTableInfo().getFieldTypes()) {\n\t\t\tif (fieldType.getType() == foreignClass\n\t\t\t\t\t&& (foreignColumnName == null || fieldType.getField().getName().equals(foreignColumnName))) {\n\t\t\t\tif (!fieldType.fieldConfig.isForeign() && !fieldType.fieldConfig.isForeignAutoRefresh()) {\n\t\t\t\t\t// this may never be reached\n\t\t\t\t\tthrow new SQLException(\"Foreign collection object \" + clazz + \" for field '\" + field.getName()\n\t\t\t\t\t\t\t+ \"' contains a field of class \" + foreignClass + \" but it's not foreign\");\n\t\t\t\t}\n\t\t\t\treturn fieldType;\n\t\t\t}\n\t\t}\n\t\t// build our complex error message\n\t\tStringBuilder sb = new StringBuilder();\n\t\tsb.append(\"Foreign collection class \").append(clazz.getName());\n\t\tsb.append(\" for field '\").append(field.getName()).append(\"' column-name does not contain a foreign field\");\n\t\tif (foreignColumnName != null) {\n\t\t\tsb.append(\" named '\").append(foreignColumnName).append('\\'');\n\t\t}\n\t\tsb.append(\" of class \").append(foreignClass.getName());\n\t\tthrow new SQLException(sb.toString());\n\t}", "public static CentralDogma forConfig(File configFile) throws IOException {\n requireNonNull(configFile, \"configFile\");\n return new CentralDogma(Jackson.readValue(configFile, CentralDogmaConfig.class));\n }", "public RandomVariable[] getValues(double[] times) {\n\t\tRandomVariable[] values = new RandomVariable[times.length];\n\n\t\tfor(int i=0; i<times.length; i++) {\n\t\t\tvalues[i] = getValue(null, times[i]);\n\t\t}\n\n\t\treturn values;\n\t}", "public void addImportedPackages(Set<String> importedPackages) {\n\t\taddImportedPackages(importedPackages.toArray(new String[importedPackages.size()]));\n\t}", "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 detect(final String... packageNames) throws IOException {\n final String[] pkgNameFilter = new String[packageNames.length];\n for (int i = 0; i < pkgNameFilter.length; ++i) {\n pkgNameFilter[i] = packageNames[i].replace('.', '/');\n if (!pkgNameFilter[i].endsWith(\"/\")) {\n pkgNameFilter[i] = pkgNameFilter[i].concat(\"/\");\n }\n }\n final Set<File> files = new HashSet<>();\n final ClassLoader loader = Thread.currentThread().getContextClassLoader();\n for (final String packageName : pkgNameFilter) {\n final Enumeration<URL> resourceEnum = loader.getResources(packageName);\n while (resourceEnum.hasMoreElements()) {\n final URL url = resourceEnum.nextElement();\n if (\"file\".equals(url.getProtocol())) {\n final File dir = toFile(url);\n if (dir.isDirectory()) {\n files.add(dir);\n } else {\n throw new AssertionError(\"Not a recognized file URL: \" + url);\n }\n } else {\n final File jarFile = toFile(openJarURLConnection(url).getJarFileURL());\n if (jarFile.isFile()) {\n files.add(jarFile);\n } else {\n throw new AssertionError(\"Not a File: \" + jarFile);\n }\n }\n }\n }\n if (DEBUG) {\n print(\"Files to scan: %s\", files);\n }\n if (!files.isEmpty()) {\n // see http://shipilev.net/blog/2016/arrays-wisdom-ancients/#_conclusion\n detect(new ClassFileIterator(files.toArray(new File[0]), pkgNameFilter));\n }\n }" ]
Post-configure retreival of server engine.
[ "public void retrieveEngine() throws GeneralSecurityException, IOException {\n if (serverEngineFactory == null) {\n return;\n }\n engine = serverEngineFactory.retrieveHTTPServerEngine(nurl.getPort());\n if (engine == null) {\n engine = serverEngineFactory.getHTTPServerEngine(nurl.getHost(), nurl.getPort(), nurl.getProtocol());\n }\n\n assert engine != null;\n TLSServerParameters serverParameters = engine.getTlsServerParameters();\n if (serverParameters != null && serverParameters.getCertConstraints() != null) {\n CertificateConstraintsType constraints = serverParameters.getCertConstraints();\n if (constraints != null) {\n certConstraints = CertConstraintsJaxBUtils.createCertConstraints(constraints);\n }\n }\n\n // When configuring for \"http\", however, it is still possible that\n // Spring configuration has configured the port for https.\n if (!nurl.getProtocol().equals(engine.getProtocol())) {\n throw new IllegalStateException(\"Port \" + engine.getPort() + \" is configured with wrong protocol \\\"\" + engine.getProtocol() + \"\\\" for \\\"\" + nurl + \"\\\"\");\n }\n }" ]
[ "public Response remove(String id) {\r\n assertNotEmpty(id, \"id\");\r\n id = ensureDesignPrefix(id);\r\n String revision = null;\r\n // Get the revision ID from ETag, removing leading and trailing \"\r\n revision = client.executeRequest(Http.HEAD(new DatabaseURIHelper(db.getDBUri()\r\n ).documentUri(id))).getConnection().getHeaderField(\"ETag\");\r\n if (revision != null) {\r\n revision = revision.substring(1, revision.length() - 1);\r\n return db.remove(id, revision);\r\n } else {\r\n throw new CouchDbException(\"No ETag header found for design document with id \" + id);\r\n }\r\n }", "public static void assertValidMetadata(ByteArray key,\n RoutingStrategy routingStrategy,\n Node currentNode) {\n List<Node> nodes = routingStrategy.routeRequest(key.get());\n for(Node node: nodes) {\n if(node.getId() == currentNode.getId()) {\n return;\n }\n }\n\n throw new InvalidMetadataException(\"Client accessing key belonging to partitions \"\n + routingStrategy.getPartitionList(key.get())\n + \" not present at \" + currentNode);\n }", "private void postTraversalProcessing() {\n\t\tint nc1 = treeSize;\n\t\tinfo[KR] = new int[leafCount];\n\t\tinfo[RKR] = new int[leafCount];\n\n\t\tint lc = leafCount;\n\t\tint i = 0;\n\n\t\t// compute left-most leaf descendants\n\t\t// go along the left-most path, remember each node and assign to it the path's\n\t\t// leaf\n\t\t// compute right-most leaf descendants (in reversed postorder)\n\t\tfor (i = 0; i < treeSize; i++) {\n\t\t\tif (paths[LEFT][i] == -1) {\n\t\t\t\tinfo[POST2_LLD][i] = i;\n\t\t\t} else {\n\t\t\t\tinfo[POST2_LLD][i] = info[POST2_LLD][paths[LEFT][i]];\n\t\t\t}\n\t\t\tif (paths[RIGHT][i] == -1) {\n\t\t\t\tinfo[RPOST2_RLD][treeSize - 1 - info[POST2_PRE][i]] =\n\t\t\t\t\t\t(treeSize - 1 - info[POST2_PRE][i]);\n\t\t\t} else {\n\t\t\t\tinfo[RPOST2_RLD][treeSize - 1 - info[POST2_PRE][i]] =\n\t\t\t\t\t\tinfo[RPOST2_RLD][treeSize - 1\n\t\t\t\t\t\t\t\t- info[POST2_PRE][paths[RIGHT][i]]];\n\t\t\t}\n\t\t}\n\n\t\t// compute key root nodes\n\t\t// compute reversed key root nodes (in revrsed postorder)\n\t\tboolean[] visited = new boolean[nc1];\n\t\tboolean[] visitedR = new boolean[nc1];\n\t\tArrays.fill(visited, false);\n\t\tint k = lc - 1;\n\t\tint kR = lc - 1;\n\t\tfor (i = nc1 - 1; i >= 0; i--) {\n\t\t\tif (!visited[info[POST2_LLD][i]]) {\n\t\t\t\tinfo[KR][k] = i;\n\t\t\t\tvisited[info[POST2_LLD][i]] = true;\n\t\t\t\tk--;\n\t\t\t}\n\t\t\tif (!visitedR[info[RPOST2_RLD][i]]) {\n\t\t\t\tinfo[RKR][kR] = i;\n\t\t\t\tvisitedR[info[RPOST2_RLD][i]] = true;\n\t\t\t\tkR--;\n\t\t\t}\n\t\t}\n\n\t\t// compute minimal key roots for every subtree\n\t\t// compute minimal reversed key roots for every subtree (in reversed postorder)\n\t\tint parent = -1;\n\t\tint parentR = -1;\n\t\tfor (i = 0; i < leafCount; i++) {\n\t\t\tparent = info[KR][i];\n\t\t\twhile (parent > -1 && info[POST2_MIN_KR][parent] == -1) {\n\t\t\t\tinfo[POST2_MIN_KR][parent] = i;\n\t\t\t\tparent = info[POST2_PARENT][parent];\n\t\t\t}\n\t\t\tparentR = info[RKR][i];\n\t\t\twhile (parentR > -1 && info[RPOST2_MIN_RKR][parentR] == -1) {\n\t\t\t\tinfo[RPOST2_MIN_RKR][parentR] = i;\n\t\t\t\tparentR =\n\t\t\t\t\t\tinfo[POST2_PARENT][info[RPOST2_POST][parentR]]; // get parent's postorder\n\t\t\t\tif (parentR > -1) {\n\t\t\t\t\tparentR = treeSize - 1 - info[POST2_PRE][parentR]; // if parent exists get its\n\t\t\t\t\t// rev. postorder\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "public static nsacl6_stats get(nitro_service service, String acl6name) throws Exception{\n\t\tnsacl6_stats obj = new nsacl6_stats();\n\t\tobj.set_acl6name(acl6name);\n\t\tnsacl6_stats response = (nsacl6_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "private String readOptionalString(JSONObject json, String key, String defaultValue) {\n\n try {\n String str = json.getString(key);\n if (str != null) {\n return str;\n }\n\n } catch (JSONException e) {\n LOG.debug(\"Reading optional JSON string failed. Default to provided default value.\", e);\n }\n return defaultValue;\n }", "public static String toXml(DeploymentDescriptor descriptor) {\n try {\n\n Marshaller marshaller = getContext().createMarshaller();\n marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);\n marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, \"http://www.jboss.org/jbpm deployment-descriptor.xsd\");\n marshaller.setSchema(schema);\n StringWriter stringWriter = new StringWriter();\n\n // clone the object and cleanup transients\n DeploymentDescriptor clone = ((DeploymentDescriptorImpl) descriptor).clearClone();\n\n marshaller.marshal(clone, stringWriter);\n String output = stringWriter.toString();\n\n return output;\n } catch (Exception e) {\n throw new RuntimeException(\"Unable to generate xml from deployment descriptor\", e);\n }\n }", "public static route6[] get(nitro_service service) throws Exception{\n\t\troute6 obj = new route6();\n\t\troute6[] response = (route6[])obj.get_resources(service);\n\t\treturn response;\n\t}", "@SuppressWarnings({\"unchecked\", \"WeakerAccess\"})\n public static <T> List<T> readListAttributeElement(final XMLExtendedStreamReader reader, final String attributeName,\n final Class<T> type) throws XMLStreamException {\n requireSingleAttribute(reader, attributeName);\n // todo: fix this when this method signature is corrected\n final List<T> value = (List<T>) reader.getListAttributeValue(0, type);\n requireNoContent(reader);\n return value;\n }", "public JsonTypeDefinition projectionType(String... properties) {\n if(this.getType() instanceof Map<?, ?>) {\n Map<?, ?> type = (Map<?, ?>) getType();\n Arrays.sort(properties);\n Map<String, Object> newType = new LinkedHashMap<String, Object>();\n for(String prop: properties)\n newType.put(prop, type.get(prop));\n return new JsonTypeDefinition(newType);\n } else {\n throw new IllegalArgumentException(\"Cannot take the projection of a type that is not a Map.\");\n }\n }" ]
Returns the rendered element content for all the given containers. @param element the element to render @param containers the containers the element appears in @return a map from container names to rendered page contents
[ "private Map<String, String> getContentsByContainerName(\n CmsContainerElementBean element,\n Collection<CmsContainer> containers) {\n\n CmsFormatterConfiguration configs = getFormatterConfiguration(element.getResource());\n Map<String, String> result = new HashMap<String, String>();\n for (CmsContainer container : containers) {\n String content = getContentByContainer(element, container, configs);\n if (content != null) {\n content = removeScriptTags(content);\n }\n result.put(container.getName(), content);\n }\n return result;\n }" ]
[ "public static nstrafficdomain_binding get(nitro_service service, Long td) throws Exception{\n\t\tnstrafficdomain_binding obj = new nstrafficdomain_binding();\n\t\tobj.set_td(td);\n\t\tnstrafficdomain_binding response = (nstrafficdomain_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "protected boolean hasPermissions(CmsObject cms, CmsSolrDocument doc, CmsResourceFilter filter) {\r\n\r\n return null != (filter == null ? getResource(cms, doc) : getResource(cms, doc, filter));\r\n }", "static ChangeEvent<BsonDocument> changeEventForLocalReplace(\n final MongoNamespace namespace,\n final BsonValue documentId,\n final BsonDocument document,\n final boolean writePending\n ) {\n return new ChangeEvent<>(\n new BsonDocument(),\n OperationType.REPLACE,\n document,\n namespace,\n new BsonDocument(\"_id\", documentId),\n null,\n writePending);\n }", "public double computeLikelihoodP() {\n double ret = 1.0;\n\n for( int i = 0; i < r.numRows; i++ ) {\n double a = r.get(i,0);\n\n ret *= Math.exp(-a*a/2.0);\n }\n\n return ret;\n }", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public static void changeCredentials(String accountID, String token, String region) {\n if(defaultConfig != null){\n Logger.i(\"CleverTap SDK already initialized with accountID:\"+defaultConfig.getAccountId()\n +\" and token:\"+defaultConfig.getAccountToken()+\". Cannot change credentials to \"\n + accountID + \" and \" + token);\n return;\n }\n\n ManifestInfo.changeCredentials(accountID,token,region);\n }", "protected void processLink(Row row)\n {\n Task predecessorTask = m_project.getTaskByUniqueID(row.getInteger(\"LINK_PRED_UID\"));\n Task successorTask = m_project.getTaskByUniqueID(row.getInteger(\"LINK_SUCC_UID\"));\n if (predecessorTask != null && successorTask != null)\n {\n RelationType type = RelationType.getInstance(row.getInt(\"LINK_TYPE\"));\n TimeUnit durationUnits = MPDUtility.getDurationTimeUnits(row.getInt(\"LINK_LAG_FMT\"));\n Duration duration = MPDUtility.getDuration(row.getDouble(\"LINK_LAG\").doubleValue(), durationUnits);\n Relation relation = successorTask.addPredecessor(predecessorTask, type, duration);\n relation.setUniqueID(row.getInteger(\"LINK_UID\"));\n m_eventManager.fireRelationReadEvent(relation);\n }\n }", "@SuppressWarnings(\"resource\")\n public static FileChannel openChannel(File file, boolean mutable) throws IOException {\n if (mutable) {\n return new RandomAccessFile(file, \"rw\").getChannel();\n }\n return new FileInputStream(file).getChannel();\n }", "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 void deployApplication(String applicationName, URL... urls) throws IOException {\n this.applicationName = applicationName;\n\n for (URL url : urls) {\n try (InputStream inputStream = url.openStream()) {\n deploy(inputStream);\n }\n }\n }" ]
Create a clone of this volatility surface using a generic calibration of its parameters to given market data. @param calibrationModel The model used during calibration (contains additional objects required during valuation, e.g. curves). @param calibrationProducts The calibration products. @param calibrationTargetValues The target values of the calibration products. @param calibrationParameters A map containing additional settings like "evaluationTime" (Double). @param parameterTransformation An optional parameter transformation. @param optimizerFactory The factory providing the optimizer to be used during calibration. @return An object having the same type as this one, using (hopefully) calibrated parameters. @throws SolverException Exception thrown when solver fails.
[ "public AbstractVolatilitySurfaceParametric getCloneCalibrated(final AnalyticModel calibrationModel, final Vector<AnalyticProduct> calibrationProducts, final List<Double> calibrationTargetValues, Map<String,Object> calibrationParameters, final ParameterTransformation parameterTransformation, OptimizerFactory optimizerFactory) throws SolverException {\n\t\tif(calibrationParameters == null) {\n\t\t\tcalibrationParameters = new HashMap<>();\n\t\t}\n\t\tInteger maxIterationsParameter\t= (Integer)calibrationParameters.get(\"maxIterations\");\n\t\tDouble\taccuracyParameter\t\t= (Double)calibrationParameters.get(\"accuracy\");\n\t\tDouble\tevaluationTimeParameter\t\t= (Double)calibrationParameters.get(\"evaluationTime\");\n\n\t\t// @TODO currently ignored, we use the setting form the OptimizerFactory\n\t\tint maxIterations\t\t= maxIterationsParameter != null ? maxIterationsParameter.intValue() : 600;\n\t\tdouble accuracy\t\t\t= accuracyParameter != null ? accuracyParameter.doubleValue() : 1E-8;\n\t\tdouble evaluationTime\t= evaluationTimeParameter != null ? evaluationTimeParameter.doubleValue() : 0.0;\n\n\t\tAnalyticModel model = calibrationModel.addVolatilitySurfaces(this);\n\t\tSolver solver = new Solver(model, calibrationProducts, calibrationTargetValues, parameterTransformation, evaluationTime, optimizerFactory);\n\n\t\tSet<ParameterObject> objectsToCalibrate = new HashSet<>();\n\t\tobjectsToCalibrate.add(this);\n\t\tAnalyticModel modelCalibrated = solver.getCalibratedModel(objectsToCalibrate);\n\n\t\t// Diagnostic output\n\t\tif (logger.isLoggable(Level.FINE)) {\n\t\t\tdouble lastAccuracy\t\t= solver.getAccuracy();\n\t\t\tint \tlastIterations\t= solver.getIterations();\n\n\t\t\tlogger.fine(\"The solver achieved an accuracy of \" + lastAccuracy + \" in \" + lastIterations + \".\");\n\t\t}\n\n\t\treturn (AbstractVolatilitySurfaceParametric)modelCalibrated.getVolatilitySurface(this.getName());\n\t}" ]
[ "protected StreamRequestHandlerState determineRequestHandlerState(String itemTag) {\n\n if (keyIterator.hasNext() && !fetchedEnoughForAllPartitions()) {\n return StreamRequestHandlerState.WRITING;\n } else {\n logger.info(\"Finished fetch \" + itemTag + \" for store '\" + storageEngine.getName()\n + \"' with partitions \" + partitionIds);\n progressInfoMessage(\"Fetch \" + itemTag + \" (end of scan)\");\n\n return StreamRequestHandlerState.COMPLETE;\n }\n }", "public Integer getNodesPartitionIdForKey(int nodeId, final byte[] key) {\n // this is all the partitions the key replicates to.\n List<Integer> partitionIds = getReplicatingPartitionList(key);\n for(Integer partitionId: partitionIds) {\n // check which of the replicating partitions belongs to the node in\n // question\n if(getNodeIdForPartitionId(partitionId) == nodeId) {\n return partitionId;\n }\n }\n return null;\n }", "public static tunneltrafficpolicy[] get(nitro_service service, options option) throws Exception{\n\t\ttunneltrafficpolicy obj = new tunneltrafficpolicy();\n\t\ttunneltrafficpolicy[] response = (tunneltrafficpolicy[])obj.get_resources(service,option);\n\t\treturn response;\n\t}", "public void forAllMemberTagTokens(String template, Properties attributes) throws XDocletException\r\n {\r\n if (getCurrentField() != null) {\r\n forAllMemberTagTokens(template, attributes, FOR_FIELD);\r\n }\r\n else if (getCurrentMethod() != null) {\r\n forAllMemberTagTokens(template, attributes, FOR_METHOD);\r\n }\r\n }", "@SuppressWarnings(\"unchecked\") private Object formatType(DataType type, Object value)\n {\n switch (type)\n {\n case DATE:\n {\n value = formatDateTime(value);\n break;\n }\n\n case CURRENCY:\n {\n value = formatCurrency((Number) value);\n break;\n }\n\n case UNITS:\n {\n value = formatUnits((Number) value);\n break;\n }\n\n case PERCENTAGE:\n {\n value = formatPercentage((Number) value);\n break;\n }\n\n case ACCRUE:\n {\n value = formatAccrueType((AccrueType) value);\n break;\n }\n\n case CONSTRAINT:\n {\n value = formatConstraintType((ConstraintType) value);\n break;\n }\n\n case WORK:\n case DURATION:\n {\n value = formatDuration(value);\n break;\n }\n\n case RATE:\n {\n value = formatRate((Rate) value);\n break;\n }\n\n case PRIORITY:\n {\n value = formatPriority((Priority) value);\n break;\n }\n\n case RELATION_LIST:\n {\n value = formatRelationList((List<Relation>) value);\n break;\n }\n\n case TASK_TYPE:\n {\n value = formatTaskType((TaskType) value);\n break;\n }\n\n default:\n {\n break;\n }\n }\n\n return (value);\n }", "@SuppressWarnings({\"unchecked\", \"WeakerAccess\"})\n public static <T> List<T> readListAttributeElement(final XMLExtendedStreamReader reader, final String attributeName,\n final Class<T> type) throws XMLStreamException {\n requireSingleAttribute(reader, attributeName);\n // todo: fix this when this method signature is corrected\n final List<T> value = (List<T>) reader.getListAttributeValue(0, type);\n requireNoContent(reader);\n return value;\n }", "public static float noise2(float x, float y) {\n int bx0, bx1, by0, by1, b00, b10, b01, b11;\n float rx0, rx1, ry0, ry1, q[], sx, sy, a, b, t, u, v;\n int i, j;\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 t = y + N;\n by0 = ((int)t) & BM;\n by1 = (by0+1) & BM;\n ry0 = t - (int)t;\n ry1 = ry0 - 1.0f;\n\n i = p[bx0];\n j = p[bx1];\n\n b00 = p[i + by0];\n b10 = p[j + by0];\n b01 = p[i + by1];\n b11 = p[j + by1];\n\n sx = sCurve(rx0);\n sy = sCurve(ry0);\n\n q = g2[b00]; u = rx0 * q[0] + ry0 * q[1];\n q = g2[b10]; v = rx1 * q[0] + ry0 * q[1];\n a = lerp(sx, u, v);\n\n q = g2[b01]; u = rx0 * q[0] + ry1 * q[1];\n q = g2[b11]; v = rx1 * q[0] + ry1 * q[1];\n b = lerp(sx, u, v);\n\n return 1.5f*lerp(sy, a, b);\n }", "protected void processTusFiles(String assemblyUrl) throws IOException, ProtocolException {\n tusClient.setUploadCreationURL(new URL(getClient().getHostUrl() + \"/resumable/files/\"));\n tusClient.enableResuming(tusURLStore);\n\n for (Map.Entry<String, File> entry : files.entrySet()) {\n processTusFile(entry.getValue(), entry.getKey(), assemblyUrl);\n }\n\n for (Map.Entry<String, InputStream> entry : fileStreams.entrySet()) {\n processTusFile(entry.getValue(), entry.getKey(), assemblyUrl);\n }\n }", "public CustomHeadersInterceptor addHeader(String name, String value) {\n if (!this.headers.containsKey(name)) {\n this.headers.put(name, new ArrayList<String>());\n }\n this.headers.get(name).add(value);\n return this;\n }" ]
Use this API to add nsip6.
[ "public static base_response add(nitro_service client, nsip6 resource) throws Exception {\n\t\tnsip6 addresource = new nsip6();\n\t\taddresource.ipv6address = resource.ipv6address;\n\t\taddresource.scope = resource.scope;\n\t\taddresource.type = resource.type;\n\t\taddresource.vlan = resource.vlan;\n\t\taddresource.nd = resource.nd;\n\t\taddresource.icmp = resource.icmp;\n\t\taddresource.vserver = resource.vserver;\n\t\taddresource.telnet = resource.telnet;\n\t\taddresource.ftp = resource.ftp;\n\t\taddresource.gui = resource.gui;\n\t\taddresource.ssh = resource.ssh;\n\t\taddresource.snmp = resource.snmp;\n\t\taddresource.mgmtaccess = resource.mgmtaccess;\n\t\taddresource.restrictaccess = resource.restrictaccess;\n\t\taddresource.dynamicrouting = resource.dynamicrouting;\n\t\taddresource.hostroute = resource.hostroute;\n\t\taddresource.ip6hostrtgw = resource.ip6hostrtgw;\n\t\taddresource.metric = resource.metric;\n\t\taddresource.vserverrhilevel = resource.vserverrhilevel;\n\t\taddresource.ospf6lsatype = resource.ospf6lsatype;\n\t\taddresource.ospfarea = resource.ospfarea;\n\t\taddresource.state = resource.state;\n\t\taddresource.map = resource.map;\n\t\taddresource.ownernode = resource.ownernode;\n\t\taddresource.td = resource.td;\n\t\treturn addresource.add_resource(client);\n\t}" ]
[ "public Triple<EObject, EReference, INode> decode(Resource res, String uriFragment) {\n\t\tif (isUseIndexFragment(res)) {\n\t\t\treturn getLazyProxyInformation(res, uriFragment);\n\t\t}\n\t\tList<String> split = Strings.split(uriFragment, SEP);\n\t\tEObject source = resolveShortFragment(res, split.get(1));\n\t\tEReference ref = fromShortExternalForm(source.eClass(), split.get(2));\n\t\tINode compositeNode = NodeModelUtils.getNode(source);\n\t\tif (compositeNode==null)\n\t\t\tthrow new IllegalStateException(\"Couldn't resolve lazy link, because no node model is attached.\");\n\t\tINode textNode = getNode(compositeNode, split.get(3));\n\t\treturn Tuples.create(source, ref, textNode);\n\t}", "public void addClass(ClassNode node) {\n node = node.redirect();\n String name = node.getName();\n ClassNode stored = classes.get(name);\n if (stored != null && stored != node) {\n // we have a duplicate class!\n // One possibility for this is, that we declared a script and a\n // class in the same file and named the class like the file\n SourceUnit nodeSource = node.getModule().getContext();\n SourceUnit storedSource = stored.getModule().getContext();\n String txt = \"Invalid duplicate class definition of class \" + node.getName() + \" : \";\n if (nodeSource == storedSource) {\n // same class in same source\n txt += \"The source \" + nodeSource.getName() + \" contains at least two definitions of the class \" + node.getName() + \".\\n\";\n if (node.isScriptBody() || stored.isScriptBody()) {\n txt += \"One of the classes is an explicit generated class using the class statement, the other is a class generated from\" +\n \" the script body based on the file name. Solutions are to change the file name or to change the class name.\\n\";\n }\n } else {\n txt += \"The sources \" + nodeSource.getName() + \" and \" + storedSource.getName() + \" each contain a class with the name \" + node.getName() + \".\\n\";\n }\n nodeSource.getErrorCollector().addErrorAndContinue(\n new SyntaxErrorMessage(new SyntaxException(txt, node.getLineNumber(), node.getColumnNumber(), node.getLastLineNumber(), node.getLastColumnNumber()), nodeSource)\n );\n }\n classes.put(name, node);\n\n if (classesToCompile.containsKey(name)) {\n ClassNode cn = classesToCompile.get(name);\n cn.setRedirect(node);\n classesToCompile.remove(name);\n }\n }", "@SuppressWarnings(\"unchecked\")\n private static Object resolveConflictWithResolver(\n final ConflictHandler conflictResolver,\n final BsonValue documentId,\n final ChangeEvent localEvent,\n final ChangeEvent remoteEvent\n ) {\n return conflictResolver.resolveConflict(\n documentId,\n localEvent,\n remoteEvent);\n }", "@Override\r\n public V remove(Object key) {\r\n if (fast) {\r\n synchronized (this) {\r\n Map<K, V> temp = cloneMap(map);\r\n V result = temp.remove(key);\r\n map = temp;\r\n return (result);\r\n }\r\n } else {\r\n synchronized (map) {\r\n return (map.remove(key));\r\n }\r\n }\r\n }", "public void setProgressBackgroundColor(int colorRes) {\n mCircleView.setBackgroundColor(colorRes);\n mProgress.setBackgroundColor(getResources().getColor(colorRes));\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 }", "public byte[] join(Map<Integer, byte[]> parts) {\n checkArgument(parts.size() > 0, \"No parts provided\");\n final int[] lengths = parts.values().stream().mapToInt(v -> v.length).distinct().toArray();\n checkArgument(lengths.length == 1, \"Varying lengths of part values\");\n final byte[] secret = new byte[lengths[0]];\n for (int i = 0; i < secret.length; i++) {\n final byte[][] points = new byte[parts.size()][2];\n int j = 0;\n for (Map.Entry<Integer, byte[]> part : parts.entrySet()) {\n points[j][0] = part.getKey().byteValue();\n points[j][1] = part.getValue()[i];\n j++;\n }\n secret[i] = GF256.interpolate(points);\n }\n return secret;\n }", "public Token add( String word ) {\n Token t = new Token(word);\n push( t );\n return t;\n }", "public static void deleteMetadataTemplate(BoxAPIConnection api, String scope, String template) {\n\n URL url = METADATA_TEMPLATE_URL_TEMPLATE.build(api.getBaseURL(), scope, template);\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"DELETE\");\n\n request.send();\n }" ]
This method lists all tasks defined in the file in a hierarchical format, reflecting the parent-child relationships between them. @param file MPX file
[ "private static void listHierarchy(ProjectFile file)\n {\n for (Task task : file.getChildTasks())\n {\n System.out.println(\"Task: \" + task.getName() + \"\\t\" + task.getStart() + \"\\t\" + task.getFinish());\n listHierarchy(task, \" \");\n }\n\n System.out.println();\n }" ]
[ "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 static route6[] get(nitro_service service, route6_args args) throws Exception{\n\t\troute6 obj = new route6();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\troute6[] response = (route6[])obj.get_resources(service, option);\n\t\treturn response;\n\t}", "protected static boolean isMaskCompatibleWithRange(long value, long upperValue, long maskValue, long maxValue) {\n\t\tif(value == upperValue || maskValue == maxValue || maskValue == 0) {\n\t\t\treturn true;\n\t\t}\n\n\t\t//algorithm:\n\t\t//here we find the highest bit that is part of the range, highestDifferingBitInRange (ie changes from lower to upper)\n\t\t//then we find the highest bit in the mask that is 1 that is the same or below highestDifferingBitInRange (if such a bit exists)\n\t\t\n\t\t//this gives us the highest bit that is part of the masked range (ie changes from lower to upper after applying the mask)\n\t\t//if this latter bit exists, then any bit below it in the mask must be 1 to include the entire range.\n\t\t\n\t\tlong differing = value ^ upperValue;\n\t\tboolean foundDiffering = (differing != 0);\n\t\tboolean differingIsLowestBit = (differing == 1);\n\t\tif(foundDiffering && !differingIsLowestBit) {\n\t\t\tint highestDifferingBitInRange = Long.numberOfLeadingZeros(differing);\n\t\t\tlong maskMask = ~0L >>> highestDifferingBitInRange;\n\t\t\tlong differingMasked = maskValue & maskMask;\n\t\t\tfoundDiffering = (differingMasked != 0);\n\t\t\tdifferingIsLowestBit = (differingMasked == 1);\n\t\t\tif(foundDiffering && !differingIsLowestBit) {\n\t\t\t\t//anything below highestDifferingBitMasked in the mask must be ones\n\t\t\t\t//Also, if we have masked out any 1 bit in the original, then anything that we do not mask out that follows must be all 1s\n\t\t\t\tint highestDifferingBitMasked = Long.numberOfLeadingZeros(differingMasked);\n\t\t\t\tlong hostMask = ~0L >>> (highestDifferingBitMasked + 1);//for the first mask bit that is 1, all bits that follow must also be 1\n\t\t\t\tif((maskValue & hostMask) != hostMask) { //check if all ones below\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif(highestDifferingBitMasked > highestDifferingBitInRange) {\n\t\t\t\t\t//We have masked out a 1 bit, so we need to check that all bits in upper value that we do not mask out are also 1 bits, otherwise we end up missing values in the masked range\n\t\t\t\t\t//This check is unnecessary for prefix-length subnets, only non-standard ranges might fail this check.\n\t\t\t\t\t//For instance, if we have range 0000 to 1010\n\t\t\t\t\t//and we mask upper and lower with 0111\n\t\t\t\t\t//we get 0000 to 0010, but 0111 was in original range, and the mask of that value retains that value\n\t\t\t\t\t//so that value needs to be in final range, and it's not.\n\t\t\t\t\t//What went wrong is that we masked out the top bit, and any other bit that is not masked out must be 1.\n\t\t\t\t\t//To work, our original range needed to be 0000 to 1111, with the three 1s following the first masked-out 1\n\t\t\t\t\tlong hostMaskUpper = ~0L >>> highestDifferingBitMasked;\n\t\t\t\t\tif((upperValue & hostMaskUpper) != hostMaskUpper) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}", "public ILog getLog(String topic, int partition) {\n TopicNameValidator.validate(topic);\n Pool<Integer, Log> p = getLogPool(topic, partition);\n return p == null ? null : p.get(partition);\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 }", "protected void addRow(int uniqueID, Map<String, Object> map)\n {\n m_rows.put(Integer.valueOf(uniqueID), new MapRow(map));\n }", "public int readFrom(byte[] src, int srcOffset, long destOffset, int length) {\n int readLen = (int) Math.min(src.length - srcOffset, Math.min(size() - destOffset, length));\n ByteBuffer b = toDirectByteBuffer(destOffset, readLen);\n b.position(0);\n b.put(src, srcOffset, readLen);\n return readLen;\n }", "private void decreaseIndent() throws IOException\n {\n if (m_pretty)\n {\n m_writer.write('\\n');\n m_indent = m_indent.substring(0, m_indent.length() - INDENT.length());\n m_writer.write(m_indent);\n }\n m_firstNameValuePair.pop();\n }", "public static boolean isListLiteralWithOnlyConstantValues(Expression expression) {\r\n if (expression instanceof ListExpression) {\r\n List<Expression> expressions = ((ListExpression) expression).getExpressions();\r\n for (Expression e : expressions) {\r\n if (!isConstantOrConstantLiteral(e)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }\r\n return false;\r\n }" ]
Use this API to fetch sslcipher_individualcipher_binding resources of given name .
[ "public static sslcipher_individualcipher_binding[] get(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\tsslcipher_individualcipher_binding response[] = (sslcipher_individualcipher_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "private List<CmsGitConfiguration> readConfigFiles() {\n\n List<CmsGitConfiguration> configurations = new LinkedList<CmsGitConfiguration>();\n\n // Default configuration file for backwards compatibility\n addConfigurationIfValid(configurations, new File(DEFAULT_CONFIG_FILE));\n\n // All files in the config folder\n File configFolder = new File(DEFAULT_CONFIG_FOLDER);\n if (configFolder.isDirectory()) {\n for (File configFile : configFolder.listFiles()) {\n addConfigurationIfValid(configurations, configFile);\n }\n }\n return configurations;\n }", "protected Path createTempDirectory(String prefix) {\n try {\n return Files.createTempDirectory(tempDirectory, prefix);\n } catch (IOException e) {\n throw new AllureCommandException(e);\n }\n }", "private void appendJoinSQL92(Join join, StringBuffer where, StringBuffer buf)\r\n {\r\n if (join.isOuter)\r\n {\r\n buf.append(\" LEFT OUTER JOIN \");\r\n }\r\n else\r\n {\r\n buf.append(\" INNER JOIN \");\r\n }\r\n if (join.right.hasJoins())\r\n {\r\n buf.append(\"(\");\r\n appendTableWithJoins(join.right, where, buf);\r\n buf.append(\")\");\r\n }\r\n else\r\n {\r\n appendTableWithJoins(join.right, where, buf);\r\n }\r\n buf.append(\" ON \");\r\n join.appendJoinEqualities(buf);\r\n }", "private void readResourceAssignment(Allocation gpAllocation)\n {\n Integer taskID = Integer.valueOf(NumberHelper.getInt(gpAllocation.getTaskId()) + 1);\n Integer resourceID = Integer.valueOf(NumberHelper.getInt(gpAllocation.getResourceId()) + 1);\n Task task = m_projectFile.getTaskByUniqueID(taskID);\n Resource resource = m_projectFile.getResourceByUniqueID(resourceID);\n if (task != null && resource != null)\n {\n ResourceAssignment mpxjAssignment = task.addResourceAssignment(resource);\n mpxjAssignment.setUnits(gpAllocation.getLoad());\n m_eventManager.fireAssignmentReadEvent(mpxjAssignment);\n }\n }", "public String toText() {\n StringBuilder sb = new StringBuilder();\n if (!description.isEmpty()) {\n sb.append(description.toText());\n sb.append(EOL);\n }\n if (!blockTags.isEmpty()) {\n sb.append(EOL);\n }\n for (JavadocBlockTag tag : blockTags) {\n sb.append(tag.toText()).append(EOL);\n }\n return sb.toString();\n }", "public int createPartitions(String topic, int partitionNum, boolean enlarge) throws IOException {\n KV<Receive, ErrorMapping> response = send(new CreaterRequest(topic, partitionNum, enlarge));\n return Utils.deserializeIntArray(response.k.buffer())[0];\n }", "protected void unregisterDriver(){\r\n\t\tString jdbcURL = this.config.getJdbcUrl();\r\n\t\tif ((jdbcURL != null) && this.config.isDeregisterDriverOnClose()){\r\n\t\t\tlogger.info(\"Unregistering JDBC driver for : \"+jdbcURL);\r\n\t\t\ttry {\r\n\t\t\t\tDriverManager.deregisterDriver(DriverManager.getDriver(jdbcURL));\r\n\t\t\t} catch (SQLException e) {\r\n\t\t\t\tlogger.info(\"Unregistering driver failed.\", e);\r\n\t\t\t}\r\n\t\t}\r\n\t}", "@AfterThrowing(pointcut = \"execution(* org.apache.cassandra.thrift.CassandraServer.doInsert(..))\", throwing = \"throwable\")\n public void logErrorFromThrownException(final JoinPoint joinPoint, final Throwable throwable) {\n final String className = joinPoint.getTarget().getClass().getName();\n final String methodName = joinPoint.getSignature().getName();\n\n logger.error(\"Could not write to cassandra! Method: \" + className + \".\"+ methodName + \"()\", throwable);\n }", "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}" ]
Writes a list of timephased data to the MSPDI file. @param assignmentID current assignment ID @param list output list of timephased data items @param data input list of timephased data @param type list type (planned or completed)
[ "private void writeAssignmentTimephasedData(BigInteger assignmentID, List<TimephasedDataType> list, List<TimephasedWork> data, int type)\n {\n for (TimephasedWork mpx : data)\n {\n TimephasedDataType xml = m_factory.createTimephasedDataType();\n list.add(xml);\n\n xml.setStart(mpx.getStart());\n xml.setFinish(mpx.getFinish());\n xml.setType(BigInteger.valueOf(type));\n xml.setUID(assignmentID);\n xml.setUnit(DatatypeConverter.printDurationTimeUnits(mpx.getTotalAmount(), false));\n xml.setValue(DatatypeConverter.printDuration(this, mpx.getTotalAmount()));\n }\n }" ]
[ "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<DiscordianDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<DiscordianDate>) super.localDateTime(temporal);\n }", "static GVRCollider lookup(long nativePointer)\n {\n synchronized (sColliders)\n {\n WeakReference<GVRCollider> weakReference = sColliders.get(nativePointer);\n return weakReference == null ? null : weakReference.get();\n }\n }", "private void remove() {\n if (removing) {\n return;\n }\n if (deactiveNotifications.size() == 0) {\n return;\n }\n removing = true;\n final NotificationPopupView view = deactiveNotifications.get(0);\n final LinearFadeOutAnimation fadeOutAnimation = new LinearFadeOutAnimation(view) {\n\n @Override\n public void onUpdate(double progress) {\n super.onUpdate(progress);\n for (int i = 0; i < activeNotifications.size(); i++) {\n NotificationPopupView v = activeNotifications.get(i);\n final int left = v.getPopupLeft();\n final int top = (int) (((i + 1) * SPACING) - (progress * SPACING));\n v.setPopupPosition(left,\n top);\n }\n }\n\n @Override\n public void onComplete() {\n super.onComplete();\n view.hide();\n deactiveNotifications.remove(view);\n activeNotifications.remove(view);\n removing = false;\n remove();\n }\n };\n fadeOutAnimation.run(500);\n }", "private void deliverAlbumArtUpdate(int player, AlbumArt art) {\n if (!getAlbumArtListeners().isEmpty()) {\n final AlbumArtUpdate update = new AlbumArtUpdate(player, art);\n for (final AlbumArtListener listener : getAlbumArtListeners()) {\n try {\n listener.albumArtChanged(update);\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering album art update to listener\", t);\n }\n }\n }\n }", "private JSONArray getApplicablePathNames (String requestUrl, Integer requestType) throws Exception {\n RequestInformation requestInfo = requestInformation.get();\n List<EndpointOverride> applicablePaths;\n JSONArray pathNames = new JSONArray();\n // Get all paths that match the request\n applicablePaths = PathOverrideService.getInstance().getSelectedPaths(Constants.OVERRIDE_TYPE_REQUEST, requestInfo.client,\n requestInfo.profile,\n requestUrl + \"?\" + requestInfo.originalRequestInfo.getQueryString(),\n requestType, true);\n // Extract just the path name from each path\n for (EndpointOverride path : applicablePaths) {\n JSONObject pathName = new JSONObject();\n pathName.put(\"name\", path.getPathName());\n pathNames.put(pathName);\n }\n\n return pathNames;\n }", "public ArrayList<IntPoint> process(ImageSource fastBitmap) {\r\n //FastBitmap l = new FastBitmap(fastBitmap);\r\n if (points == null) {\r\n apply(fastBitmap);\r\n }\r\n\r\n int width = fastBitmap.getWidth();\r\n int height = fastBitmap.getHeight();\r\n points = new ArrayList<IntPoint>();\r\n\r\n if (fastBitmap.isGrayscale()) {\r\n for (int x = 0; x < height; x++) {\r\n for (int y = 0; y < width; y++) {\r\n if (fastBitmap.getRGB(y, x) == 255) points.add(new IntPoint(y, x));\r\n }\r\n }\r\n } else {\r\n for (int x = 0; x < height; x++) {\r\n for (int y = 0; y < width; y++) {\r\n // TODO Check for green and blue?\r\n if (fastBitmap.getR(y, x) == 255) points.add(new IntPoint(y, x));\r\n }\r\n }\r\n }\r\n\r\n return points;\r\n }", "@Deprecated\r\n public Location resolvePlaceURL(String flickrPlacesUrl) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_RESOLVE_PLACE_URL);\r\n\r\n parameters.put(\"url\", flickrPlacesUrl);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element locationElement = response.getPayload();\r\n return parseLocation(locationElement);\r\n }", "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 static Date addDays(Date date, int days)\n {\n Calendar cal = popCalendar(date);\n cal.add(Calendar.DAY_OF_YEAR, days);\n Date result = cal.getTime();\n pushCalendar(cal);\n return result; \n }" ]
Method to build Integration Flow for Mail. Suppress Warnings for MailInboundChannelAdapterSpec. @return Integration Flow object for Mail Source
[ "@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n\tprivate IntegrationFlowBuilder getFlowBuilder() {\n\n\t\tIntegrationFlowBuilder flowBuilder;\n\t\tURLName urlName = this.properties.getUrl();\n\n\t\tif (this.properties.isIdleImap()) {\n\t\t\tflowBuilder = getIdleImapFlow(urlName);\n\t\t}\n\t\telse {\n\n\t\t\tMailInboundChannelAdapterSpec adapterSpec;\n\t\t\tswitch (urlName.getProtocol().toUpperCase()) {\n\t\t\t\tcase \"IMAP\":\n\t\t\t\tcase \"IMAPS\":\n\t\t\t\t\tadapterSpec = getImapFlowBuilder(urlName);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"POP3\":\n\t\t\t\tcase \"POP3S\":\n\t\t\t\t\tadapterSpec = getPop3FlowBuilder(urlName);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\t\"Unsupported mail protocol: \" + urlName.getProtocol());\n\t\t\t}\n\t\t\tflowBuilder = IntegrationFlows.from(\n\t\t\t\t\tadapterSpec.javaMailProperties(getJavaMailProperties(urlName))\n\t\t\t\t\t\t\t.selectorExpression(this.properties.getExpression())\n\t\t\t\t\t\t\t.shouldDeleteMessages(this.properties.isDelete()),\n\t\t\t\t\tnew Consumer<SourcePollingChannelAdapterSpec>() {\n\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void accept(\n\t\t\t\t\t\t\t\tSourcePollingChannelAdapterSpec sourcePollingChannelAdapterSpec) {\n\t\t\t\t\t\t\tsourcePollingChannelAdapterSpec.poller(MailSourceConfiguration.this.defaultPoller);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t});\n\n\t\t}\n\t\treturn flowBuilder;\n\t}" ]
[ "void initialize(DMatrixSparseCSC A) {\n m = A.numRows;\n n = A.numCols;\n int s = 4*n + (ata ? (n+m+1) : 0);\n\n gw.reshape(s);\n w = gw.data;\n\n // compute the transpose of A\n At.reshape(A.numCols,A.numRows,A.nz_length);\n CommonOps_DSCC.transpose(A,At,gw);\n\n // initialize w\n Arrays.fill(w,0,s,-1); // assign all values in workspace to -1\n\n ancestor = 0;\n maxfirst = n;\n prevleaf = 2*n;\n first = 3*n;\n }", "public static String[] allUpperCase(String... strings){\n\t\tString[] tmp = new String[strings.length];\n\t\tfor(int idx=0;idx<strings.length;idx++){\n\t\t\tif(strings[idx] != null){\n\t\t\t\ttmp[idx] = strings[idx].toUpperCase();\n\t\t\t}\n\t\t}\n\t\treturn tmp;\n\t}", "public Map<String, String> getTitleLocale() {\n\n if (m_localeTitles == null) {\n m_localeTitles = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n public Object transform(Object inputLocale) {\n\n Locale locale = null;\n if (null != inputLocale) {\n if (inputLocale instanceof Locale) {\n locale = (Locale)inputLocale;\n } else if (inputLocale instanceof String) {\n try {\n locale = LocaleUtils.toLocale((String)inputLocale);\n } catch (IllegalArgumentException | NullPointerException e) {\n // do nothing, just go on without locale\n }\n }\n }\n return getLocaleSpecificTitle(locale);\n }\n\n });\n }\n return m_localeTitles;\n }", "public static File newFile(File baseDir, String... segments) {\n File f = baseDir;\n for (String segment : segments) {\n f = new File(f, segment);\n }\n return f;\n }", "public static int ptb2Text(Reader ptbText, Writer w) throws IOException {\r\n int numTokens = 0;\r\n PTB2TextLexer lexer = new PTB2TextLexer(ptbText);\r\n for (String token; (token = lexer.next()) != null; ) {\r\n numTokens++;\r\n w.write(token);\r\n }\r\n return numTokens;\r\n }", "@Deprecated\n public static <T> ServiceBuilder<T> addServerExecutorDependency(ServiceBuilder<T> builder, Injector<ExecutorService> injector) {\n return builder.addDependency(ServerService.MANAGEMENT_EXECUTOR, ExecutorService.class, injector);\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 final void setOrientation(int orientation) {\n mOrientation = orientation;\n mOrientationState = getOrientationStateFromParam(mOrientation);\n invalidate();\n if (mOuterAdapter != null) {\n mOuterAdapter.setOrientation(mOrientation);\n }\n\n }", "protected void _format(EObject obj, IFormattableDocument document) {\n\t\tfor (EObject child : obj.eContents())\n\t\t\tdocument.format(child);\n\t}" ]
Creates a converter function that converts value into primitive type. @return A converter function or {@code null} if the given type is not primitive type or boxed type
[ "@Nullable\n private static Converter<List<String>, Object> createPrimitiveTypeConverter(final Class<?> resultClass) {\n Object defaultValue = defaultValue(resultClass);\n\n if (defaultValue == null) {\n // For primitive type, the default value shouldn't be null\n return null;\n }\n\n return new BasicConverter(defaultValue) {\n @Override\n protected Object convert(String value) throws Exception {\n return valueOf(value, resultClass);\n }\n };\n }" ]
[ "private void clearMetadata(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>(hotCache.keySet())) {\n if (deck.player == player) {\n hotCache.remove(deck);\n if (deck.hotCue == 0) {\n deliverTrackMetadataUpdate(player, null); // Inform listeners the metadata is gone.\n }\n }\n }\n }", "public static List<Integer> checkKeyBelongsToPartition(byte[] key,\n Set<Pair<Integer, HashMap<Integer, List<Integer>>>> stealerNodeToMappingTuples,\n Cluster cluster,\n StoreDefinition storeDef) {\n List<Integer> keyPartitions = new RoutingStrategyFactory().updateRoutingStrategy(storeDef,\n cluster)\n .getPartitionList(key);\n List<Integer> nodesToPush = Lists.newArrayList();\n for(Pair<Integer, HashMap<Integer, List<Integer>>> stealNodeToMap: stealerNodeToMappingTuples) {\n List<Integer> nodePartitions = cluster.getNodeById(stealNodeToMap.getFirst())\n .getPartitionIds();\n if(StoreRoutingPlan.checkKeyBelongsToPartition(keyPartitions,\n nodePartitions,\n stealNodeToMap.getSecond())) {\n nodesToPush.add(stealNodeToMap.getFirst());\n }\n }\n return nodesToPush;\n }", "private void handleIncomingMessage(SerialMessage incomingMessage) {\n\t\t\n\t\tlogger.debug(\"Incoming message to process\");\n\t\tlogger.debug(incomingMessage.toString());\n\t\t\n\t\tswitch (incomingMessage.getMessageType()) {\n\t\t\tcase Request:\n\t\t\t\thandleIncomingRequestMessage(incomingMessage);\n\t\t\t\tbreak;\n\t\t\tcase Response:\n\t\t\t\thandleIncomingResponseMessage(incomingMessage);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tlogger.warn(\"Unsupported incomingMessageType: 0x%02X\", incomingMessage.getMessageType());\n\t\t}\n\t}", "public MapBounds getRotatedBoundsAdjustedForPreciseRotatedMapSize() {\n Rectangle2D.Double paintAreaPrecise = getRotatedMapSizePrecise();\n Rectangle paintArea = new Rectangle(MapfishMapContext.rectangleDoubleToDimension(paintAreaPrecise));\n return getRotatedBounds(paintAreaPrecise, paintArea);\n }", "public static base_responses apply(nitro_service client, nspbr6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnspbr6 applyresources[] = new nspbr6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tapplyresources[i] = new nspbr6();\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, applyresources,\"apply\");\n\t\t}\n\t\treturn result;\n\t}", "public static void deleteMetadataTemplate(BoxAPIConnection api, String scope, String template) {\n\n URL url = METADATA_TEMPLATE_URL_TEMPLATE.build(api.getBaseURL(), scope, template);\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"DELETE\");\n\n request.send();\n }", "public BoxFile.Info uploadLargeFile(InputStream inputStream, String fileName, long fileSize)\n throws InterruptedException, IOException {\n URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL());\n return new LargeFileUpload().\n upload(this.getAPI(), this.getID(), inputStream, url, fileName, fileSize);\n }", "public static int cudnnLRNCrossChannelForward(\n cudnnHandle handle, \n cudnnLRNDescriptor normDesc, \n int lrnMode, \n Pointer alpha, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor yDesc, \n Pointer y)\n {\n return checkResult(cudnnLRNCrossChannelForwardNative(handle, normDesc, lrnMode, alpha, xDesc, x, beta, yDesc, y));\n }", "@Override\n public boolean postExecute(MavenBuildProxy build, MavenProject pom, MojoInfo mojo, BuildListener listener,\n Throwable error) {\n //listener.getLogger().println(\"[MavenDependenciesRecorder] mojo: \" + mojo.getClass() + \":\" + mojo.getGoal());\n //listener.getLogger().println(\"[MavenDependenciesRecorder] dependencies: \" + pom.getArtifacts());\n recordMavenDependencies(pom.getArtifacts());\n return true;\n }" ]
Reads the file version and configures the expected file format. @param token token containing the file version @throws MPXJException
[ "private void processFileType(String token) throws MPXJException\n {\n String version = token.substring(2).split(\" \")[0];\n //System.out.println(version);\n Class<? extends AbstractFileFormat> fileFormatClass = FILE_VERSION_MAP.get(Integer.valueOf(version));\n if (fileFormatClass == null)\n {\n throw new MPXJException(\"Unsupported PP file format version \" + version);\n }\n\n try\n {\n AbstractFileFormat format = fileFormatClass.newInstance();\n m_tableDefinitions = format.tableDefinitions();\n m_epochDateFormat = format.epochDateFormat();\n }\n catch (Exception ex)\n {\n throw new MPXJException(\"Failed to configure file format\", ex);\n }\n }" ]
[ "public static vpath_stats get(nitro_service service) throws Exception{\n\t\tvpath_stats obj = new vpath_stats();\n\t\tvpath_stats[] response = (vpath_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}", "public boolean shouldCompress(String requestUri) {\n\t\tString uri = requestUri.toLowerCase();\n\t\treturn checkSuffixes(uri, zipSuffixes);\n\t}", "public void editPhotos(String photosetId, String primaryPhotoId, String[] photoIds) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT_PHOTOS);\r\n\r\n parameters.put(\"photoset_id\", photosetId);\r\n parameters.put(\"primary_photo_id\", primaryPhotoId);\r\n parameters.put(\"photo_ids\", StringUtilities.join(photoIds, \",\"));\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }", "public static String[] tokenizeUnquoted(String s) {\r\n List tokens = new LinkedList();\r\n int first = 0;\r\n while (first < s.length()) {\r\n first = skipWhitespace(s, first);\r\n int last = scanToken(s, first);\r\n if (first < last) {\r\n tokens.add(s.substring(first, last));\r\n }\r\n first = last;\r\n }\r\n return (String[])tokens.toArray(new String[tokens.size()]);\r\n }", "public static aaauser_aaagroup_binding[] get(nitro_service service, String username) throws Exception{\n\t\taaauser_aaagroup_binding obj = new aaauser_aaagroup_binding();\n\t\tobj.set_username(username);\n\t\taaauser_aaagroup_binding response[] = (aaauser_aaagroup_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "@NonNull\n public static String placeholders(final int numberOfPlaceholders) {\n if (numberOfPlaceholders == 1) {\n return \"?\"; // fffast\n } else if (numberOfPlaceholders == 0) {\n return \"\";\n } else if (numberOfPlaceholders < 0) {\n throw new IllegalArgumentException(\"numberOfPlaceholders must be >= 0, but was = \" + numberOfPlaceholders);\n }\n\n final StringBuilder stringBuilder = new StringBuilder((numberOfPlaceholders * 2) - 1);\n\n for (int i = 0; i < numberOfPlaceholders; i++) {\n stringBuilder.append('?');\n\n if (i != numberOfPlaceholders - 1) {\n stringBuilder.append(',');\n }\n }\n\n return stringBuilder.toString();\n }", "public static void setTime(Calendar calendar, int hourOfDay, int minute, int second, int millisecond) {\n calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);\n calendar.set(Calendar.MINUTE, minute);\n calendar.set(Calendar.SECOND, second);\n calendar.set(Calendar.MILLISECOND, millisecond);\n }", "@PrefMetadata(type = CmsTimeWarpPreference.class)\n public String getTimeWarp() {\n\n long warp = m_settings.getTimeWarp();\n return warp < 0 ? \"\" : \"\" + warp; // if timewarp < 0 (i.e. time warp is not set), use the empty string because we don't want the date selector widget to interpret the negative value\n }", "static Shell createTelnetConsoleShell(String prompt, String appName,\n ShellCommandHandler mainHandler, InputStream input, OutputStream output) {\n try {\n // Set up nvt4j; ignore the initial clear & reposition\n final nvt4j.impl.Terminal nvt4jTerminal = new nvt4j.impl.Terminal(input, output) {\n private boolean cleared;\n private boolean moved;\n\n @Override\n public void clear() throws IOException {\n if (this.cleared)\n super.clear();\n this.cleared = true;\n }\n\n @Override\n public void move(int row, int col) throws IOException {\n if (this.moved)\n super.move(row, col);\n this.moved = true;\n }\n };\n nvt4jTerminal.put(nvt4j.impl.Terminal.AUTO_WRAP_ON);\n nvt4jTerminal.setCursor(true);\n\n // Have JLine do input & output through telnet terminal\n final InputStream jlineInput = new InputStream() {\n @Override\n public int read() throws IOException {\n return nvt4jTerminal.get();\n }\n };\n final OutputStream jlineOutput = new OutputStream() {\n @Override\n public void write(int value) throws IOException {\n nvt4jTerminal.put(value);\n }\n };\n\n return createTerminalConsoleShell(prompt, appName, mainHandler, jlineInput, jlineOutput);\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 }" ]
Tell a device to become tempo master. @param deviceNumber the device we want to take over the role of tempo master @throws IOException if there is a problem sending the command to the device @throws IllegalStateException if the {@code VirtualCdj} is not active @throws IllegalArgumentException if {@code deviceNumber} is not found on the network
[ "public void appointTempoMaster(int deviceNumber) throws IOException {\n final DeviceUpdate update = getLatestStatusFor(deviceNumber);\n if (update == null) {\n throw new IllegalArgumentException(\"Device \" + deviceNumber + \" not found on network.\");\n }\n appointTempoMaster(update);\n }" ]
[ "public void loginAndRedirectBack(Object userIdentifier, String defaultLandingUrl) {\n login(userIdentifier);\n RedirectToLoginUrl.redirectToOriginalUrl(this, defaultLandingUrl);\n }", "public static <K, V> void operator_remove(Map<K, V> map, Iterable<? super K> keysToRemove) {\n\t\tfor (final Object key : keysToRemove) {\n\t\t\tmap.remove(key);\n\t\t}\n\t}", "public void deleteOrganization(final String organizationId) {\n final DbOrganization dbOrganization = getOrganization(organizationId);\n repositoryHandler.deleteOrganization(dbOrganization.getName());\n repositoryHandler.removeModulesOrganization(dbOrganization);\n }", "private boolean pathMatches(Path path, SquigglyContext context) {\n List<SquigglyNode> nodes = context.getNodes();\n Set<String> viewStack = null;\n SquigglyNode viewNode = null;\n\n int pathSize = path.getElements().size();\n int lastIdx = pathSize - 1;\n\n for (int i = 0; i < pathSize; i++) {\n PathElement element = path.getElements().get(i);\n\n if (viewNode != null && !viewNode.isSquiggly()) {\n Class beanClass = element.getBeanClass();\n\n if (beanClass != null && !Map.class.isAssignableFrom(beanClass)) {\n Set<String> propertyNames = getPropertyNamesFromViewStack(element, viewStack);\n\n if (!propertyNames.contains(element.getName())) {\n return false;\n }\n }\n\n } else if (nodes.isEmpty()) {\n return false;\n } else {\n\n SquigglyNode match = findBestSimpleNode(element, nodes);\n\n if (match == null) {\n match = findBestViewNode(element, nodes);\n\n if (match != null) {\n viewNode = match;\n viewStack = addToViewStack(viewStack, viewNode);\n }\n } else if (match.isAnyShallow()) {\n viewNode = match;\n } else if (match.isAnyDeep()) {\n return true;\n }\n\n if (match == null) {\n if (isJsonUnwrapped(element)) {\n continue;\n }\n\n return false;\n }\n\n if (match.isNegated()) {\n return false;\n }\n\n nodes = match.getChildren();\n\n if (i < lastIdx && nodes.isEmpty() && !match.isEmptyNested() && SquigglyConfig.isFilterImplicitlyIncludeBaseFields()) {\n nodes = BASE_VIEW_NODES;\n }\n }\n }\n\n return true;\n }", "public Number getCostVariance()\n {\n Number variance = (Number) getCachedValue(TaskField.COST_VARIANCE);\n if (variance == null)\n {\n Number cost = getCost();\n Number baselineCost = getBaselineCost();\n if (cost != null && baselineCost != null)\n {\n variance = NumberHelper.getDouble(cost.doubleValue() - baselineCost.doubleValue());\n set(TaskField.COST_VARIANCE, variance);\n }\n }\n return (variance);\n }", "private void readCalendars(Project project) throws MPXJException\n {\n Calendars calendars = project.getCalendars();\n if (calendars != null)\n {\n for (net.sf.mpxj.planner.schema.Calendar cal : calendars.getCalendar())\n {\n readCalendar(cal, null);\n }\n\n Integer defaultCalendarID = getInteger(project.getCalendar());\n m_defaultCalendar = m_projectFile.getCalendarByUniqueID(defaultCalendarID);\n if (m_defaultCalendar != null)\n {\n m_projectFile.getProjectProperties().setDefaultCalendarName(m_defaultCalendar.getName());\n }\n }\n }", "public static KnowledgeBuilderConfiguration newKnowledgeBuilderConfiguration(Properties properties,\n ClassLoader... classLoaders) {\n return FactoryServiceHolder.factoryService.newKnowledgeBuilderConfiguration( properties, classLoaders );\n }", "protected String createName() {\n final StringBuilder buf = new StringBuilder(128);\n try {\n buf.append(InetAddress.getLocalHost().getHostName()).append(COLON)\n .append(ManagementFactory.getRuntimeMXBean().getName().split(\"@\")[0]) // PID\n .append('-').append(this.workerId).append(COLON).append(JAVA_DYNAMIC_QUEUES);\n for (final String queueName : this.queueNames) {\n buf.append(',').append(queueName);\n }\n } catch (UnknownHostException uhe) {\n throw new RuntimeException(uhe);\n }\n return buf.toString();\n }", "public static rnat6_nsip6_binding[] get(nitro_service service, String name) throws Exception{\n\t\trnat6_nsip6_binding obj = new rnat6_nsip6_binding();\n\t\tobj.set_name(name);\n\t\trnat6_nsip6_binding response[] = (rnat6_nsip6_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
Create a structured Record instance from the flat text data. Null is returned if errors are encountered during parse. @param text flat text data @return Record instance
[ "public static Record getRecord(String text)\n {\n Record root;\n\n try\n {\n root = new Record(text);\n }\n\n //\n // I've come across invalid calendar data in an otherwise fine Primavera\n // database belonging to a customer. We deal with this gracefully here\n // rather than propagating an exception.\n //\n catch (Exception ex)\n {\n root = null;\n }\n\n return root;\n }" ]
[ "protected void queryTimerEnd(String sql, long queryStartTime) {\r\n\t\tif ((this.queryExecuteTimeLimit != 0) \r\n\t\t\t\t&& (this.connectionHook != null)){\r\n\t\t\tlong timeElapsed = (System.nanoTime() - queryStartTime);\r\n\t\t\t\r\n\t\t\tif (timeElapsed > this.queryExecuteTimeLimit){\r\n\t\t\t\tthis.connectionHook.onQueryExecuteTimeLimitExceeded(this.connectionHandle, this, sql, this.logParams, timeElapsed);\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tif (this.statisticsEnabled){\r\n\t\t\tthis.statistics.incrementStatementsExecuted();\r\n\t\t\tthis.statistics.addStatementExecuteTime(System.nanoTime() - queryStartTime);\r\n\t\t\t\r\n\t\t}\r\n\r\n\t}", "private static String[] readArgsFile(String argsFile) throws IOException {\n final ArrayList<String> lines = new ArrayList<String>();\n final BufferedReader reader = new BufferedReader(\n new InputStreamReader(\n new FileInputStream(argsFile), \"UTF-8\"));\n try {\n String line;\n while ((line = reader.readLine()) != null) {\n line = line.trim();\n if (!line.isEmpty() && !line.startsWith(\"#\")) {\n lines.add(line);\n }\n }\n } finally {\n reader.close();\n }\n return lines.toArray(new String [lines.size()]);\n }", "public ViewPort then(Functions.Func1<ViewPortChange> then, ViewPortFallback fallback) {\n assert then != null : \"'then' callback cannot be null\";\n this.then = then;\n this.fallback = fallback;\n return load();\n }", "protected Violation createViolationForImport(SourceCode sourceCode, ImportNode importNode, String message) {\n Map importInfo = ImportUtil.sourceLineAndNumberForImport(sourceCode, importNode);\n Violation violation = new Violation();\n violation.setRule(this);\n violation.setSourceLine((String) importInfo.get(\"sourceLine\"));\n violation.setLineNumber((Integer) importInfo.get(\"lineNumber\"));\n violation.setMessage(message);\n return violation;\n }", "@Override\n public Configuration configuration() {\n return new MostUsefulConfiguration()\n // where to find the stories\n .useStoryLoader(new LoadFromClasspath(this.getClass())) \n // CONSOLE and TXT reporting\n .useStoryReporterBuilder(new StoryReporterBuilder().withDefaultFormats().withFormats(Format.CONSOLE, Format.TXT)); \n }", "public static void main(String[] args) throws Exception {\r\n StringUtils.printErrInvocationString(\"CMMClassifier\", args);\r\n\r\n Properties props = StringUtils.argsToProperties(args);\r\n CMMClassifier cmm = new CMMClassifier<CoreLabel>(props);\r\n String testFile = cmm.flags.testFile;\r\n String textFile = cmm.flags.textFile;\r\n String loadPath = cmm.flags.loadClassifier;\r\n String serializeTo = cmm.flags.serializeTo;\r\n\r\n // cmm.crossValidateTrainAndTest(trainFile);\r\n if (loadPath != null) {\r\n cmm.loadClassifierNoExceptions(loadPath, props);\r\n } else if (cmm.flags.loadJarClassifier != null) {\r\n cmm.loadJarClassifier(cmm.flags.loadJarClassifier, props);\r\n } else if (cmm.flags.trainFile != null) {\r\n if (cmm.flags.biasedTrainFile != null) {\r\n cmm.trainSemiSup();\r\n } else {\r\n cmm.train();\r\n }\r\n } else {\r\n cmm.loadDefaultClassifier();\r\n }\r\n\r\n if (serializeTo != null) {\r\n cmm.serializeClassifier(serializeTo);\r\n }\r\n\r\n if (testFile != null) {\r\n cmm.classifyAndWriteAnswers(testFile, cmm.makeReaderAndWriter());\r\n } else if (cmm.flags.testFiles != null) {\r\n cmm.classifyAndWriteAnswers(cmm.flags.baseTestDir, cmm.flags.testFiles,\r\n cmm.makeReaderAndWriter());\r\n }\r\n\r\n if (textFile != null) {\r\n DocumentReaderAndWriter readerAndWriter =\r\n new PlainTextDocumentReaderAndWriter();\r\n cmm.classifyAndWriteAnswers(textFile, readerAndWriter);\r\n }\r\n }", "public static Object[] filterMapToObjectArray(final Map<String, ?> values, final String[] nameMapping) {\n\t\t\n\t\tif( values == null ) {\n\t\t\tthrow new NullPointerException(\"values should not be null\");\n\t\t} else if( nameMapping == null ) {\n\t\t\tthrow new NullPointerException(\"nameMapping should not be null\");\n\t\t}\n\t\t\n\t\tfinal Object[] targetArray = new Object[nameMapping.length];\n\t\tint i = 0;\n\t\tfor( final String name : nameMapping ) {\n\t\t\ttargetArray[i++] = values.get(name);\n\t\t}\n\t\treturn targetArray;\n\t}", "public B importContext(AbstractContext context){\n Objects.requireNonNull(context);\n return importContext(context, false);\n }", "private void addGreeting(String guestbookName, String user, String message)\n throws DatastoreException {\n Entity.Builder greeting = Entity.newBuilder();\n greeting.setKey(makeKey(GUESTBOOK_KIND, guestbookName, GREETING_KIND));\n greeting.getMutableProperties().put(USER_PROPERTY, makeValue(user).build());\n greeting.getMutableProperties().put(MESSAGE_PROPERTY, makeValue(message).build());\n greeting.getMutableProperties().put(DATE_PROPERTY, makeValue(new Date()).build());\n Key greetingKey = insert(greeting.build());\n System.out.println(\"greeting key is: \" + greetingKey);\n }" ]
Add new control at the end of control bar with specified touch listener, control label and resource. Size of control bar is updated based on new number of controls. @param name name of the control to remove @param resId the control face @param label the control label @param listener touch listener
[ "public Widget addControl(String name, int resId, String label, Widget.OnTouchListener listener) {\n return addControl(name, resId, label, listener, -1);\n }" ]
[ "public static base_response disable(nitro_service client, Long clid) throws Exception {\n\t\tclusterinstance disableresource = new clusterinstance();\n\t\tdisableresource.clid = clid;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}", "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}", "private ClassDescriptor[] getMultiJoinedClassDescriptors(ClassDescriptor cld)\r\n {\r\n DescriptorRepository repository = cld.getRepository();\r\n Class[] multiJoinedClasses = repository.getSubClassesMultipleJoinedTables(cld, true);\r\n ClassDescriptor[] result = new ClassDescriptor[multiJoinedClasses.length];\r\n\r\n for (int i = 0 ; i < multiJoinedClasses.length; i++)\r\n {\r\n result[i] = repository.getDescriptorFor(multiJoinedClasses[i]);\r\n }\r\n\r\n return result;\r\n }", "public static base_responses delete(nitro_service client, String fipskeyname[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (fipskeyname != null && fipskeyname.length > 0) {\n\t\t\tsslfipskey deleteresources[] = new sslfipskey[fipskeyname.length];\n\t\t\tfor (int i=0;i<fipskeyname.length;i++){\n\t\t\t\tdeleteresources[i] = new sslfipskey();\n\t\t\t\tdeleteresources[i].fipskeyname = fipskeyname[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "private boolean canSuccessorProceed() {\n\n if (predecessor != null && !predecessor.canSuccessorProceed()) {\n return false;\n }\n\n synchronized (this) {\n while (responseCount < groups.size()) {\n try {\n wait();\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n return false;\n }\n }\n return !failed;\n }\n }", "public void keyboardSupportEnabled(Activity activity, boolean enable) {\n if (getContent() != null && getContent().getChildCount() > 0) {\n if (mKeyboardUtil == null) {\n mKeyboardUtil = new KeyboardUtil(activity, getContent().getChildAt(0));\n mKeyboardUtil.disable();\n }\n\n if (enable) {\n mKeyboardUtil.enable();\n } else {\n mKeyboardUtil.disable();\n }\n }\n }", "public SqlStatement getPreparedUpdateStatement(ClassDescriptor cld)\r\n {\r\n SqlForClass sfc = getSqlForClass(cld);\r\n SqlStatement result = sfc.getUpdateSql();\r\n if(result == null)\r\n {\r\n ProcedureDescriptor pd = cld.getUpdateProcedure();\r\n\r\n if(pd == null)\r\n {\r\n result = new SqlUpdateStatement(cld, logger);\r\n }\r\n else\r\n {\r\n result = new SqlProcedureStatement(pd, logger);\r\n }\r\n // set the sql string\r\n sfc.setUpdateSql(result);\r\n\r\n if(logger.isDebugEnabled())\r\n {\r\n logger.debug(\"SQL:\" + result.getStatement());\r\n }\r\n }\r\n return result;\r\n }", "static void i(String message){\n if (getStaticDebugLevel() >= CleverTapAPI.LogLevel.INFO.intValue()){\n Log.i(Constants.CLEVERTAP_LOG_TAG,message);\n }\n }", "public static Map<String, Object> introspect(Object obj) throws IntrospectionException, InvocationTargetException, IllegalAccessException {\n\t\tMap<String, Object> result = new HashMap<>();\n\t\tBeanInfo info = Introspector.getBeanInfo( obj.getClass() );\n\t\tfor ( PropertyDescriptor pd : info.getPropertyDescriptors() ) {\n\t\t\tMethod reader = pd.getReadMethod();\n\t\t\tString name = pd.getName();\n\t\t\tif ( reader != null && !\"class\".equals( name ) ) {\n\t\t\t\tresult.put( name, reader.invoke( obj ) );\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}" ]
Helper method fro providers to fire hotkey event in a separate thread @param hotKey hotkey to fire
[ "protected void fireEvent(HotKey hotKey) {\n HotKeyEvent event = new HotKeyEvent(hotKey);\n if (useSwingEventQueue) {\n SwingUtilities.invokeLater(event);\n } else {\n if (eventQueue == null) {\n eventQueue = Executors.newSingleThreadExecutor();\n }\n eventQueue.execute(event);\n }\n }" ]
[ "public static final long getLong(InputStream is) throws IOException\n {\n byte[] data = new byte[8];\n is.read(data);\n return getLong(data, 0);\n }", "public void release(Contextual<T> contextual, T instance) {\n synchronized (dependentInstances) {\n for (ContextualInstance<?> dependentInstance : dependentInstances) {\n // do not destroy contextual again, since it's just being destroyed\n if (contextual == null || !(dependentInstance.getContextual().equals(contextual))) {\n destroy(dependentInstance);\n }\n }\n }\n if (resourceReferences != null) {\n for (ResourceReference<?> reference : resourceReferences) {\n reference.release();\n }\n }\n }", "@SuppressWarnings(\"unchecked\")\n public <V3, M4, C, N, Q> N getSceneRoot(AiWrapperProvider<V3, M4, C, N, Q> \n wrapperProvider) {\n\n return (N) m_sceneRoot;\n }", "protected ServiceRegistration registerProxy(Object objectProxy, Class clazz) {\n Dictionary<String, Object> props = new Hashtable<String, Object>();\n ServiceRegistration registration;\n registration = context.registerService(clazz, objectProxy, props);\n\n return registration;\n }", "private void readPredecessor(Task currTask, Project.Tasks.Task.PredecessorLink link)\n {\n BigInteger uid = link.getPredecessorUID();\n if (uid != null)\n {\n Task prevTask = m_projectFile.getTaskByUniqueID(Integer.valueOf(uid.intValue()));\n if (prevTask != null)\n {\n RelationType type;\n if (link.getType() != null)\n {\n type = RelationType.getInstance(link.getType().intValue());\n }\n else\n {\n type = RelationType.FINISH_START;\n }\n\n TimeUnit lagUnits = DatatypeConverter.parseDurationTimeUnits(link.getLagFormat());\n\n Duration lagDuration;\n int lag = NumberHelper.getInt(link.getLinkLag());\n if (lag == 0)\n {\n lagDuration = Duration.getInstance(0, lagUnits);\n }\n else\n {\n if (lagUnits == TimeUnit.PERCENT || lagUnits == TimeUnit.ELAPSED_PERCENT)\n {\n lagDuration = Duration.getInstance(lag, lagUnits);\n }\n else\n {\n lagDuration = Duration.convertUnits(lag / 10.0, TimeUnit.MINUTES, lagUnits, m_projectFile.getProjectProperties());\n }\n }\n\n Relation relation = currTask.addPredecessor(prevTask, type, lagDuration);\n m_eventManager.fireRelationReadEvent(relation);\n }\n }\n }", "public String getNamefromId(int id) {\n return (String) sqlService.getFromTable(\n Constants.PROFILE_PROFILE_NAME, Constants.GENERIC_ID,\n id, Constants.DB_TABLE_PROFILE);\n }", "protected ValueContainer[] getKeyValues(PersistenceBroker broker, ClassDescriptor cld, Identity oid) throws PersistenceBrokerException\r\n {\r\n return broker.serviceBrokerHelper().getKeyValues(cld, oid);\r\n }", "public static String getOffsetCodeFromCurveName(String curveName) {\r\n\t\tif(curveName == null || curveName.length() == 0) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\tString[] splits = curveName.split(\"(?<=\\\\D)(?=\\\\d)\");\r\n\t\tString offsetCode = splits[splits.length-1];\r\n\t\tif(!Character.isDigit(offsetCode.charAt(0))) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\toffsetCode = offsetCode.split(\"(?<=[A-Za-z])(?=.)\", 2)[0];\r\n\t\toffsetCode = offsetCode.replaceAll( \"[\\\\W_]\", \"\" );\r\n\t\treturn offsetCode;\r\n\t}", "private String dbProp(String name) {\n\n String dbType = m_setupBean.getDatabase();\n Object prop = m_setupBean.getDatabaseProperties().get(dbType).get(dbType + \".\" + name);\n if (prop == null) {\n return \"\";\n }\n return prop.toString();\n }" ]
Use this API to delete ntpserver resources of given names.
[ "public static base_responses delete(nitro_service client, String serverip[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (serverip != null && serverip.length > 0) {\n\t\t\tntpserver deleteresources[] = new ntpserver[serverip.length];\n\t\t\tfor (int i=0;i<serverip.length;i++){\n\t\t\t\tdeleteresources[i] = new ntpserver();\n\t\t\t\tdeleteresources[i].serverip = serverip[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 base_response add(nitro_service client, responderpolicy resource) throws Exception {\n\t\tresponderpolicy addresource = new responderpolicy();\n\t\taddresource.name = resource.name;\n\t\taddresource.rule = resource.rule;\n\t\taddresource.action = resource.action;\n\t\taddresource.undefaction = resource.undefaction;\n\t\taddresource.comment = resource.comment;\n\t\taddresource.logaction = resource.logaction;\n\t\taddresource.appflowaction = resource.appflowaction;\n\t\treturn addresource.add_resource(client);\n\t}", "private void processScheduleOptions()\n {\n List<Row> rows = getRows(\"schedoptions\", \"proj_id\", m_projectID);\n if (rows.isEmpty() == false)\n {\n Row row = rows.get(0);\n Map<String, Object> customProperties = new HashMap<String, Object>();\n customProperties.put(\"LagCalendar\", row.getString(\"sched_calendar_on_relationship_lag\"));\n customProperties.put(\"RetainedLogic\", Boolean.valueOf(row.getBoolean(\"sched_retained_logic\")));\n customProperties.put(\"ProgressOverride\", Boolean.valueOf(row.getBoolean(\"sched_progress_override\")));\n customProperties.put(\"IgnoreOtherProjectRelationships\", row.getString(\"sched_outer_depend_type\"));\n customProperties.put(\"StartToStartLagCalculationType\", Boolean.valueOf(row.getBoolean(\"sched_lag_early_start_flag\")));\n m_reader.getProject().getProjectProperties().setCustomProperties(customProperties);\n }\n }", "public PartialCollection<BoxItem.Info> getChildrenRange(long offset, long limit, String... fields) {\n QueryStringBuilder builder = new QueryStringBuilder()\n .appendParam(\"limit\", limit)\n .appendParam(\"offset\", offset);\n\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields).toString();\n }\n\n URL url = GET_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), builder.toString(), getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n String totalCountString = responseJSON.get(\"total_count\").toString();\n long fullSize = Double.valueOf(totalCountString).longValue();\n PartialCollection<BoxItem.Info> children = new PartialCollection<BoxItem.Info>(offset, limit, fullSize);\n JsonArray jsonArray = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : jsonArray) {\n JsonObject jsonObject = value.asObject();\n BoxItem.Info parsedItemInfo = (BoxItem.Info) BoxResource.parseInfo(this.getAPI(), jsonObject);\n if (parsedItemInfo != null) {\n children.add(parsedItemInfo);\n }\n }\n return children;\n }", "public synchronized void removeControlPoint(ControlPoint controlPoint) {\n if (controlPoint.decreaseReferenceCount() == 0) {\n ControlPointIdentifier id = new ControlPointIdentifier(controlPoint.getDeployment(), controlPoint.getEntryPoint());\n entryPoints.remove(id);\n }\n }", "public static Set<Map<String, Object>> setify(ObjectMapper mapper, Object source) {\n return (Set<Map<String, Object>>) collectify(mapper, source, Set.class);\n }", "public synchronized void reset() {\n this.authorizerDescription = StandardRBACAuthorizer.AUTHORIZER_DESCRIPTION;\n this.useIdentityRoles = this.nonFacadeMBeansSensitive = false;\n this.roleMappings = new HashMap<String, RoleMappingImpl>();\n RoleMaps oldRoleMaps = this.roleMaps;\n this.roleMaps = new RoleMaps(authorizerDescription.getStandardRoles(), Collections.<String, ScopedRole>emptyMap());\n for (ScopedRole role : oldRoleMaps.scopedRoles.values()) {\n for (ScopedRoleListener listener : scopedRoleListeners) {\n try {\n listener.scopedRoleRemoved(role);\n } catch (Exception ignored) {\n // TODO log an ERROR\n }\n }\n }\n }", "@Override\n\tpublic void set(String headerName, String headerValue) {\n\t\tList<String> headerValues = new LinkedList<String>();\n\t\theaderValues.add(headerValue);\n\t\theaders.put(headerName, headerValues);\n\t}", "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 }", "public <T> InternalEjbDescriptor<T> get(String beanName) {\n return cast(ejbByName.get(beanName));\n }" ]
Record a content loader for a given patch id. @param patchID the patch id @param contentLoader the content loader
[ "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 void afterCompletion(int status)\r\n {\r\n if(afterCompletionCall) return;\r\n\r\n log.info(\"Method afterCompletion was called\");\r\n try\r\n {\r\n switch(status)\r\n {\r\n case Status.STATUS_COMMITTED:\r\n if(log.isDebugEnabled())\r\n {\r\n log.debug(\"Method afterCompletion: Do commit internal odmg-tx, status of JTA-tx is \" + TxUtil.getStatusString(status));\r\n }\r\n commit();\r\n break;\r\n default:\r\n log.error(\"Method afterCompletion: Do abort call on internal odmg-tx, status of JTA-tx is \" + TxUtil.getStatusString(status));\r\n abort();\r\n }\r\n }\r\n finally\r\n {\r\n afterCompletionCall = true;\r\n log.info(\"Method afterCompletion finished\");\r\n }\r\n }", "public void process()\n {\n if (m_data != null)\n {\n int index = 0;\n int offset = 0;\n // First the length (repeated twice)\n int length = MPPUtility.getInt(m_data, offset);\n offset += 8;\n // Then the number of custom columns\n int numberOfAliases = MPPUtility.getInt(m_data, offset);\n offset += 4;\n\n // Then the aliases themselves\n while (index < numberOfAliases && offset < length)\n {\n // Each item consists of the Field ID (2 bytes), 40 0B marker (2 bytes), and the\n // offset to the string (4 bytes)\n\n // Get the Field ID\n int fieldID = MPPUtility.getInt(m_data, offset);\n offset += 4;\n // Get the alias offset (offset + 4 for some reason).\n int aliasOffset = MPPUtility.getInt(m_data, offset) + 4;\n offset += 4;\n // Read the alias itself\n if (aliasOffset < m_data.length)\n {\n String alias = MPPUtility.getUnicodeString(m_data, aliasOffset);\n m_fields.getCustomField(FieldTypeHelper.getInstance(fieldID)).setAlias(alias);\n }\n index++;\n }\n }\n }", "public static void writeBytes(byte[] bytes, long value, int offset, int numBytes) {\n int shift = 0;\n for(int i = offset + numBytes - 1; i >= offset; i--) {\n bytes[i] = (byte) (0xFF & (value >> shift));\n shift += 8;\n }\n }", "private long getTime(Date start1, Date end1, Date start2, Date end2)\n {\n long total = 0;\n\n if (start1 != null && end1 != null && start2 != null && end2 != null)\n {\n long start;\n long end;\n\n if (start1.getTime() < start2.getTime())\n {\n start = start2.getTime();\n }\n else\n {\n start = start1.getTime();\n }\n\n if (end1.getTime() < end2.getTime())\n {\n end = end1.getTime();\n }\n else\n {\n end = end2.getTime();\n }\n\n if (start < end)\n {\n total = end - start;\n }\n }\n\n return (total);\n }", "public boolean decompose(DMatrixRMaj mat , int indexStart , int n ) {\n double m[] = mat.data;\n\n double el_ii;\n double div_el_ii=0;\n\n for( int i = 0; i < n; i++ ) {\n for( int j = i; j < n; j++ ) {\n double sum = m[indexStart+i*mat.numCols+j];\n\n int iEl = i*n;\n int jEl = j*n;\n int end = iEl+i;\n // k = 0:i-1\n for( ; iEl<end; iEl++,jEl++ ) {\n// sum -= el[i*n+k]*el[j*n+k];\n sum -= el[iEl]*el[jEl];\n }\n\n if( i == j ) {\n // is it positive-definate?\n if( sum <= 0.0 )\n return false;\n\n el_ii = Math.sqrt(sum);\n el[i*n+i] = el_ii;\n m[indexStart+i*mat.numCols+i] = el_ii;\n div_el_ii = 1.0/el_ii;\n } else {\n double v = sum*div_el_ii;\n el[j*n+i] = v;\n m[indexStart+j*mat.numCols+i] = v;\n }\n }\n }\n\n return true;\n }", "protected boolean isZero( int index ) {\n double bottom = Math.abs(diag[index])+Math.abs(diag[index+1]);\n\n return( Math.abs(off[index]) <= bottom*UtilEjml.EPS);\n }", "protected void setBeanDeploymentArchivesAccessibility() {\n for (WeldBeanDeploymentArchive beanDeploymentArchive : beanDeploymentArchives) {\n Set<WeldBeanDeploymentArchive> accessibleArchives = new HashSet<>();\n for (WeldBeanDeploymentArchive candidate : beanDeploymentArchives) {\n if (candidate.equals(beanDeploymentArchive)) {\n continue;\n }\n accessibleArchives.add(candidate);\n }\n beanDeploymentArchive.setAccessibleBeanDeploymentArchives(accessibleArchives);\n }\n }", "@Nullable\n private static Converter<List<String>, Object> createPrimitiveTypeConverter(final Class<?> resultClass) {\n Object defaultValue = defaultValue(resultClass);\n\n if (defaultValue == null) {\n // For primitive type, the default value shouldn't be null\n return null;\n }\n\n return new BasicConverter(defaultValue) {\n @Override\n protected Object convert(String value) throws Exception {\n return valueOf(value, resultClass);\n }\n };\n }", "public DesignDocument get(String id) {\r\n assertNotEmpty(id, \"id\");\r\n return db.find(DesignDocument.class, ensureDesignPrefix(id));\r\n }" ]
Returns a new color that has the hue adjusted by the specified amount.
[ "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 }" ]
[ "public PhotoContext getContext(String photoId, String userId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_CONTEXT);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"user_id\", userId);\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 Collection<Element> payload = response.getPayloadCollection();\r\n PhotoContext photoContext = new PhotoContext();\r\n for (Element element : payload) {\r\n String elementName = element.getTagName();\r\n if (elementName.equals(\"prevphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(element.getAttribute(\"id\"));\r\n photoContext.setPreviousPhoto(photo);\r\n } else if (elementName.equals(\"nextphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(element.getAttribute(\"id\"));\r\n photoContext.setNextPhoto(photo);\r\n } else {\r\n if (logger.isInfoEnabled()) {\r\n logger.info(\"unsupported element name: \" + elementName);\r\n }\r\n }\r\n }\r\n return photoContext;\r\n }", "public Duration getWorkVariance()\n {\n Duration variance = (Duration) getCachedValue(ResourceField.WORK_VARIANCE);\n if (variance == null)\n {\n Duration work = getWork();\n Duration baselineWork = getBaselineWork();\n if (work != null && baselineWork != null)\n {\n variance = Duration.getInstance(work.getDuration() - baselineWork.convertUnits(work.getUnits(), getParentFile().getProjectProperties()).getDuration(), work.getUnits());\n set(ResourceField.WORK_VARIANCE, variance);\n }\n }\n return (variance);\n }", "public VerticalLayout getEmptyLayout() {\n\n m_emptyLayout = CmsVaadinUtils.getInfoLayout(CmsOuTreeType.USER.getEmptyMessageKey());\n setVisible(size() > 0);\n m_emptyLayout.setVisible(size() == 0);\n return m_emptyLayout;\n }", "public void setVelocityRange( final Vector3f minV, final Vector3f maxV )\n {\n if (null != mGVRContext) {\n mGVRContext.runOnGlThread(new Runnable() {\n\n @Override\n public void run() {\n minVelocity = minV;\n maxVelocity = maxV;\n }\n });\n }\n }", "public void attachMetadataCache(SlotReference slot, File file)\n throws IOException {\n ensureRunning();\n if (slot.player < 1 || slot.player > 4 || DeviceFinder.getInstance().getLatestAnnouncementFrom(slot.player) == null) {\n throw new IllegalArgumentException(\"unable to attach metadata cache for player \" + slot.player);\n }\n if ((slot.slot != CdjStatus.TrackSourceSlot.USB_SLOT) && (slot.slot != CdjStatus.TrackSourceSlot.SD_SLOT)) {\n throw new IllegalArgumentException(\"unable to attach metadata cache for slot \" + slot.slot);\n }\n\n MetadataCache cache = new MetadataCache(file);\n final MediaDetails slotDetails = getMediaDetailsFor(slot);\n if (cache.sourceMedia != null && slotDetails != null) {\n if (!slotDetails.hashKey().equals(cache.sourceMedia.hashKey())) {\n throw new IllegalArgumentException(\"Cache was created for different media (\" + cache.sourceMedia.hashKey() +\n \") than is in the slot (\" + slotDetails.hashKey() + \").\");\n }\n if (slotDetails.hasChanged(cache.sourceMedia)) {\n logger.warn(\"Media has changed (\" + slotDetails + \") since cache was created (\" + cache.sourceMedia +\n \"). Attaching anyway as instructed.\");\n }\n }\n attachMetadataCacheInternal(slot, cache);\n }", "public void retrieveReference(Object pInstance, String pAttributeName) throws PersistenceBrokerException\n {\n if (logger.isDebugEnabled())\n {\n \tlogger.debug(\"Retrieving reference named [\"+pAttributeName+\"] on object of type [\"+\n \t pInstance.getClass().getName()+\"]\");\n }\n ClassDescriptor cld = getClassDescriptor(pInstance.getClass());\n CollectionDescriptor cod = cld.getCollectionDescriptorByName(pAttributeName);\n getInternalCache().enableMaterializationCache();\n // to avoid problems with circular references, locally cache the current object instance\n Identity oid = serviceIdentity().buildIdentity(pInstance);\n boolean needLocalRemove = false;\n if(getInternalCache().doLocalLookup(oid) == null)\n {\n getInternalCache().doInternalCache(oid, pInstance, MaterializationCache.TYPE_TEMP);\n needLocalRemove = true;\n }\n try\n {\n if (cod != null)\n {\n referencesBroker.retrieveCollection(pInstance, cld, cod, true);\n }\n else\n {\n ObjectReferenceDescriptor ord = cld.getObjectReferenceDescriptorByName(pAttributeName);\n if (ord != null)\n {\n referencesBroker.retrieveReference(pInstance, cld, ord, true);\n }\n else\n {\n throw new PersistenceBrokerException(\"did not find attribute \" + pAttributeName +\n \" for class \" + pInstance.getClass().getName());\n }\n }\n // do locally remove the object to avoid problems with object state detection (insert/update),\n // because objects found in the cache detected as 'old' means 'update'\n if(needLocalRemove) getInternalCache().doLocalRemove(oid);\n getInternalCache().disableMaterializationCache();\n }\n catch(RuntimeException e)\n {\n getInternalCache().doLocalClear();\n throw e;\n }\n }", "public static CmsGalleryTabConfiguration resolve(String configStr) {\r\n\r\n CmsGalleryTabConfiguration tabConfig;\r\n if (CmsStringUtil.isEmptyOrWhitespaceOnly(configStr)) {\r\n configStr = \"*sitemap,types,galleries,categories,vfstree,search,results\";\r\n }\r\n if (DEFAULT_CONFIGURATIONS != null) {\r\n tabConfig = DEFAULT_CONFIGURATIONS.get(configStr);\r\n if (tabConfig != null) {\r\n return tabConfig;\r\n }\r\n\r\n }\r\n return parse(configStr);\r\n }", "public static FileStatus[] getDataChunkFiles(FileSystem fs,\n Path path,\n final int partitionId,\n final int replicaType) throws IOException {\n return fs.listStatus(path, new PathFilter() {\n\n public boolean accept(Path input) {\n if(input.getName().matches(\"^\" + Integer.toString(partitionId) + \"_\"\n + Integer.toString(replicaType) + \"_[\\\\d]+\\\\.data\")) {\n return true;\n } else {\n return false;\n }\n }\n });\n }", "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}" ]
Retrieves a byte value from the property data. @param type Type identifier @return byte value
[ "public byte getByte(Integer type)\n {\n byte result = 0;\n\n byte[] item = m_map.get(type);\n if (item != null)\n {\n result = item[0];\n }\n\n return (result);\n }" ]
[ "public PhotoList<Photo> getPhotos(String photosetId, Set<String> extras, int privacy_filter, int perPage, int page) throws FlickrException {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PHOTOS);\r\n\r\n parameters.put(\"photoset_id\", photosetId);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", String.valueOf(perPage));\r\n }\r\n\r\n if (page > 0) {\r\n parameters.put(\"page\", String.valueOf(page));\r\n }\r\n\r\n if (privacy_filter > 0) {\r\n parameters.put(\"privacy_filter\", \"\" + privacy_filter);\r\n }\r\n\r\n if (extras != null && !extras.isEmpty()) {\r\n parameters.put(Extras.KEY_EXTRAS, StringUtilities.join(extras, \",\"));\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element photoset = response.getPayload();\r\n NodeList photoElements = photoset.getElementsByTagName(\"photo\");\r\n photos.setPage(photoset.getAttribute(\"page\"));\r\n photos.setPages(photoset.getAttribute(\"pages\"));\r\n photos.setPerPage(photoset.getAttribute(\"per_page\"));\r\n photos.setTotal(photoset.getAttribute(\"total\"));\r\n\r\n for (int i = 0; i < photoElements.getLength(); i++) {\r\n Element photoElement = (Element) photoElements.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement, photoset));\r\n }\r\n\r\n return photos;\r\n }", "public static Field getField(Class clazz, String fieldName)\r\n {\r\n try\r\n {\r\n return clazz.getField(fieldName);\r\n }\r\n catch (Exception ignored)\r\n {}\r\n return null;\r\n }", "public void setHtml(String html) {\n this.html = html;\n\n if (widget != null) {\n if (widget.isAttached()) {\n tooltipElement.find(\"span\")\n .html(html != null ? html : \"\");\n } else {\n widget.addAttachHandler(event ->\n tooltipElement.find(\"span\")\n .html(html != null ? html : \"\"));\n }\n } else {\n GWT.log(\"Please initialize the Target widget.\", new IllegalStateException());\n }\n }", "@Nonnull\n public final Style getDefaultStyle(@Nonnull final String geometryType) {\n String normalizedGeomName = GEOMETRY_NAME_ALIASES.get(geometryType.toLowerCase());\n if (normalizedGeomName == null) {\n normalizedGeomName = geometryType.toLowerCase();\n }\n Style style = this.defaultStyle.get(normalizedGeomName.toLowerCase());\n if (style == null) {\n style = this.namedStyles.get(normalizedGeomName.toLowerCase());\n }\n\n if (style == null) {\n StyleBuilder builder = new StyleBuilder();\n final Symbolizer symbolizer;\n if (isPointType(normalizedGeomName)) {\n symbolizer = builder.createPointSymbolizer();\n } else if (isLineType(normalizedGeomName)) {\n symbolizer = builder.createLineSymbolizer(Color.black, 2);\n } else if (isPolygonType(normalizedGeomName)) {\n symbolizer = builder.createPolygonSymbolizer(Color.lightGray, Color.black, 2);\n } else if (normalizedGeomName.equalsIgnoreCase(Constants.Style.Raster.NAME)) {\n symbolizer = builder.createRasterSymbolizer();\n } else if (normalizedGeomName.startsWith(Constants.Style.OverviewMap.NAME)) {\n symbolizer = createMapOverviewStyle(normalizedGeomName, builder);\n } else {\n final Style geomStyle = this.defaultStyle.get(Geometry.class.getSimpleName().toLowerCase());\n if (geomStyle != null) {\n return geomStyle;\n } else {\n symbolizer = builder.createPointSymbolizer();\n }\n }\n style = builder.createStyle(symbolizer);\n }\n return style;\n }", "protected boolean isStoredProcedure(String sql)\r\n {\r\n /*\r\n Stored procedures start with\r\n {?= call <procedure-name>[<arg1>,<arg2>, ...]}\r\n or\r\n {call <procedure-name>[<arg1>,<arg2>, ...]}\r\n but also statements with white space like\r\n { ?= call <procedure-name>[<arg1>,<arg2>, ...]}\r\n are possible.\r\n */\r\n int k = 0, i = 0;\r\n char c;\r\n while(k < 3 && i < sql.length())\r\n {\r\n c = sql.charAt(i);\r\n if(c != ' ')\r\n {\r\n switch (k)\r\n {\r\n case 0:\r\n if(c != '{') return false;\r\n break;\r\n case 1:\r\n if(c != '?' && c != 'c') return false;\r\n break;\r\n case 2:\r\n if(c != '=' && c != 'a') return false;\r\n break;\r\n }\r\n k++;\r\n }\r\n i++;\r\n }\r\n return true;\r\n }", "public void register(Delta delta) {\n\t\tfinal IResourceDescription newDesc = delta.getNew();\n\t\tif (newDesc == null) {\n\t\t\tremoveDescription(delta.getUri());\n\t\t} else {\n\t\t\taddDescription(delta.getUri(), newDesc);\n\t\t}\n\t}", "public static StitchAppClient getAppClient(\n @Nonnull final String clientAppId\n ) {\n ensureInitialized();\n\n synchronized (Stitch.class) {\n if (!appClients.containsKey(clientAppId)) {\n throw new IllegalStateException(\n String.format(\"client for app '%s' has not yet been initialized\", clientAppId));\n }\n return appClients.get(clientAppId);\n }\n }", "@Nullable\n private static Object valueOf(String value, Class<?> cls) {\n if (cls == Boolean.TYPE) {\n return Boolean.valueOf(value);\n }\n if (cls == Character.TYPE) {\n return value.length() >= 1 ? value.charAt(0) : defaultValue(char.class);\n }\n if (cls == Byte.TYPE) {\n return Byte.valueOf(value);\n }\n if (cls == Short.TYPE) {\n return Short.valueOf(value);\n }\n if (cls == Integer.TYPE) {\n return Integer.valueOf(value);\n }\n if (cls == Long.TYPE) {\n return Long.valueOf(value);\n }\n if (cls == Float.TYPE) {\n return Float.valueOf(value);\n }\n if (cls == Double.TYPE) {\n return Double.valueOf(value);\n }\n return null;\n }", "public void processDefaultCurrency(Row row)\n {\n ProjectProperties properties = m_project.getProjectProperties();\n properties.setCurrencySymbol(row.getString(\"curr_symbol\"));\n properties.setSymbolPosition(CURRENCY_SYMBOL_POSITION_MAP.get(row.getString(\"pos_curr_fmt_type\")));\n properties.setCurrencyDigits(row.getInteger(\"decimal_digit_cnt\"));\n properties.setThousandsSeparator(row.getString(\"digit_group_symbol\").charAt(0));\n properties.setDecimalSeparator(row.getString(\"decimal_symbol\").charAt(0));\n }" ]
Produces an IPv4 address from any sequence of 4 bytes in this IPv6 address. @param byteIndex the byte index to start @throws IndexOutOfBoundsException if the index is less than zero or bigger than 7 @return
[ "public IPv4Address getEmbeddedIPv4Address(int byteIndex) {\n\t\tif(byteIndex == IPv6Address.MIXED_ORIGINAL_SEGMENT_COUNT * IPv6Address.BYTES_PER_SEGMENT) {\n\t\t\treturn getEmbeddedIPv4Address();\n\t\t}\n\t\tIPv4AddressCreator creator = getIPv4Network().getAddressCreator();\n\t\treturn creator.createAddress(getSection().getEmbeddedIPv4AddressSection(byteIndex, byteIndex + IPv4Address.BYTE_COUNT)); /* address creation */\n\t}" ]
[ "public static <T> T load(String resourcePath, BeanSpec spec) {\n return load(resourcePath, spec, false);\n }", "public static AccrueType getInstance(String type, Locale locale)\n {\n AccrueType result = null;\n\n String[] typeNames = LocaleData.getStringArray(locale, LocaleData.ACCRUE_TYPES);\n\n for (int loop = 0; loop < typeNames.length; loop++)\n {\n if (typeNames[loop].equalsIgnoreCase(type) == true)\n {\n result = AccrueType.getInstance(loop + 1);\n break;\n }\n }\n\n if (result == null)\n {\n result = AccrueType.PRORATED;\n }\n\n return (result);\n }", "void attachMetadataCacheInternal(SlotReference slot, MetadataCache cache) {\n MetadataCache oldCache = metadataCacheFiles.put(slot, cache);\n if (oldCache != null) {\n try {\n oldCache.close();\n } catch (IOException e) {\n logger.error(\"Problem closing previous metadata cache\", e);\n }\n }\n\n deliverCacheUpdate(slot, cache);\n }", "public void setBit(int index, boolean set)\n {\n assertValidIndex(index);\n int word = index / WORD_LENGTH;\n int offset = index % WORD_LENGTH;\n if (set)\n {\n data[word] |= (1 << offset);\n }\n else // Unset the bit.\n {\n data[word] &= ~(1 << offset);\n }\n }", "public static final PatchOperationTarget createHost(final String hostName, final ModelControllerClient client) {\n final PathElement host = PathElement.pathElement(HOST, hostName);\n final PathAddress address = PathAddress.EMPTY_ADDRESS.append(host, CORE_SERVICES);\n return new RemotePatchOperationTarget(address, client);\n }", "public T modifyModule(final String moduleName, final String slot, final byte[] existingHash, final byte[] newHash) {\n final ContentItem item = createModuleItem(moduleName, slot, newHash);\n addContentModification(createContentModification(item, ModificationType.MODIFY, existingHash));\n return returnThis();\n }", "public byte[] toByteArray() {\n try {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n ObjectOutputStream oos = new ObjectOutputStream(baos);\n oos.writeObject(this);\n return baos.toByteArray();\n } catch (IOException e) {\n throw E.ioException(e);\n }\n }", "public static vpnglobal_intranetip_binding[] get(nitro_service service) throws Exception{\n\t\tvpnglobal_intranetip_binding obj = new vpnglobal_intranetip_binding();\n\t\tvpnglobal_intranetip_binding response[] = (vpnglobal_intranetip_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public StringBuilder getSQLCondition(StringBuilder builder, String columnName) {\n\t\tString string = networkString.getString();\n\t\tif(isEntireAddress) {\n\t\t\tmatchString(builder, columnName, string);\n\t\t} else {\n\t\t\tmatchSubString(\n\t\t\t\t\tbuilder,\n\t\t\t\t\tcolumnName,\n\t\t\t\t\tnetworkString.getTrailingSegmentSeparator(),\n\t\t\t\t\tnetworkString.getTrailingSeparatorCount() + 1,\n\t\t\t\t\tstring);\n\t\t}\n\t\treturn builder;\n\t}" ]
Configures the log context. @param configFile the configuration file @param classLoader the class loader to use for the configuration @param logContext the log context to configure @return {@code true} if the log context was successfully configured, otherwise {@code false} @throws DeploymentUnitProcessingException if the configuration fails
[ "private LoggingConfigurationService configure(final ResourceRoot root, final VirtualFile configFile, final ClassLoader classLoader, final LogContext logContext) throws DeploymentUnitProcessingException {\n InputStream configStream = null;\n try {\n LoggingLogger.ROOT_LOGGER.debugf(\"Found logging configuration file: %s\", configFile);\n\n // Get the filname and open the stream\n final String fileName = configFile.getName();\n configStream = configFile.openStream();\n\n // Check the type of the configuration file\n if (isLog4jConfiguration(fileName)) {\n final ClassLoader current = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();\n final LogContext old = logContextSelector.getAndSet(CONTEXT_LOCK, logContext);\n try {\n WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader);\n if (LOG4J_XML.equals(fileName) || JBOSS_LOG4J_XML.equals(fileName)) {\n new DOMConfigurator().doConfigure(configStream, org.apache.log4j.JBossLogManagerFacade.getLoggerRepository(logContext));\n } else {\n final Properties properties = new Properties();\n properties.load(new InputStreamReader(configStream, ENCODING));\n new org.apache.log4j.PropertyConfigurator().doConfigure(properties, org.apache.log4j.JBossLogManagerFacade.getLoggerRepository(logContext));\n }\n } finally {\n logContextSelector.getAndSet(CONTEXT_LOCK, old);\n WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(current);\n }\n return new LoggingConfigurationService(null, resolveRelativePath(root, configFile));\n } else {\n // Create a properties file\n final Properties properties = new Properties();\n properties.load(new InputStreamReader(configStream, ENCODING));\n // Attempt to see if this is a J.U.L. configuration file\n if (isJulConfiguration(properties)) {\n LoggingLogger.ROOT_LOGGER.julConfigurationFileFound(configFile.getName());\n } else {\n // Load non-log4j types\n final PropertyConfigurator propertyConfigurator = new PropertyConfigurator(logContext);\n propertyConfigurator.configure(properties);\n return new LoggingConfigurationService(propertyConfigurator.getLogContextConfiguration(), resolveRelativePath(root, configFile));\n }\n }\n } catch (Exception e) {\n throw LoggingLogger.ROOT_LOGGER.failedToConfigureLogging(e, configFile.getName());\n } finally {\n safeClose(configStream);\n }\n return null;\n }" ]
[ "public void updateUniqueCounters()\n {\n //\n // Update task unique IDs\n //\n for (Task task : m_parent.getTasks())\n {\n int uniqueID = NumberHelper.getInt(task.getUniqueID());\n if (uniqueID > m_taskUniqueID)\n {\n m_taskUniqueID = uniqueID;\n }\n }\n\n //\n // Update resource unique IDs\n //\n for (Resource resource : m_parent.getResources())\n {\n int uniqueID = NumberHelper.getInt(resource.getUniqueID());\n if (uniqueID > m_resourceUniqueID)\n {\n m_resourceUniqueID = uniqueID;\n }\n }\n\n //\n // Update calendar unique IDs\n //\n for (ProjectCalendar calendar : m_parent.getCalendars())\n {\n int uniqueID = NumberHelper.getInt(calendar.getUniqueID());\n if (uniqueID > m_calendarUniqueID)\n {\n m_calendarUniqueID = uniqueID;\n }\n }\n\n //\n // Update assignment unique IDs\n //\n for (ResourceAssignment assignment : m_parent.getResourceAssignments())\n {\n int uniqueID = NumberHelper.getInt(assignment.getUniqueID());\n if (uniqueID > m_assignmentUniqueID)\n {\n m_assignmentUniqueID = uniqueID;\n }\n }\n }", "public static boolean isInteger(CharSequence self) {\n try {\n Integer.valueOf(self.toString().trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n }", "public ParallelTaskBuilder setReplaceVarMapToSingleTargetFromMap(\n Map<String, StrStrMap> replacementVarMapNodeSpecific,\n String uniformTargetHost) {\n setReplacementVarMapNodeSpecific(replacementVarMapNodeSpecific);\n\n if (Strings.isNullOrEmpty(uniformTargetHost)) {\n logger.error(\"uniform target host is empty or null. skip setting.\");\n return this;\n }\n for (Entry<String, StrStrMap> entry : replacementVarMapNodeSpecific\n .entrySet()) {\n\n if (entry.getValue() != null) {\n entry.getValue().addPair(PcConstants.UNIFORM_TARGET_HOST_VAR,\n uniformTargetHost);\n }\n }\n return this;\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}", "public Response remove(String id, String rev) {\r\n assertNotEmpty(id, \"id\");\r\n assertNotEmpty(id, \"rev\");\r\n return db.remove(ensureDesignPrefix(id), rev);\r\n\r\n }", "public static Trajectory getTrajectoryByID(List<? extends Trajectory> t, int id){\n\t\tTrajectory track = null;\n\t\tfor(int i = 0; i < t.size() ; i++){\n\t\t\tif(t.get(i).getID()==id){\n\t\t\t\ttrack = t.get(i);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn track;\n\t}", "public static void scale(GVRMesh mesh, float x, float y, float z) {\n final float [] vertices = mesh.getVertices();\n final int vsize = vertices.length;\n\n for (int i = 0; i < vsize; i += 3) {\n vertices[i] *= x;\n vertices[i + 1] *= y;\n vertices[i + 2] *= z;\n }\n\n mesh.setVertices(vertices);\n }", "public static CharSequence getAt(CharSequence text, Range range) {\n RangeInfo info = subListBorders(text.length(), range);\n CharSequence sequence = text.subSequence(info.from, info.to);\n return info.reverse ? reverse(sequence) : sequence;\n }", "@Override\n public PaxDate date(int prolepticYear, int month, int dayOfMonth) {\n return PaxDate.of(prolepticYear, month, dayOfMonth);\n }" ]
Calculates Sine value of the complex number. @param z1 A Complex Number instance. @return Returns new ComplexNumber instance containing the Sine value of the specified complex number.
[ "public static ComplexNumber Sin(ComplexNumber z1) {\r\n ComplexNumber result = new ComplexNumber();\r\n\r\n if (z1.imaginary == 0.0) {\r\n result.real = Math.sin(z1.real);\r\n result.imaginary = 0.0;\r\n } else {\r\n result.real = Math.sin(z1.real) * Math.cosh(z1.imaginary);\r\n result.imaginary = Math.cos(z1.real) * Math.sinh(z1.imaginary);\r\n }\r\n\r\n return result;\r\n }" ]
[ "@SafeVarargs\n public static void registerFilterTypes(final Class<? extends DynamicFilter>... types) {\n FILTER_TYPES.addAll(Arrays.asList(types));\n }", "protected static Connection memorize(final Connection target, final ConnectionHandle connectionHandle) {\n\n\t\treturn (Connection) Proxy.newProxyInstance(\n\t\t\t\tConnectionProxy.class.getClassLoader(),\n\t\t\t\tnew Class[] {ConnectionProxy.class},\n\t\t\t\tnew MemorizeTransactionProxy(target, connectionHandle));\n\t}", "private static void bodyWithConcatenation(\n SourceBuilder code,\n Map<Property, PropertyCodeGenerator> generatorsByProperty,\n String typename) {\n code.add(\" return \\\"%s{\", typename);\n String prefix = \"\";\n for (Property property : generatorsByProperty.keySet()) {\n PropertyCodeGenerator generator = generatorsByProperty.get(property);\n code.add(\"%s%s=\\\" + %s + \\\"\",\n prefix, property.getName(), (Excerpt) generator::addToStringValue);\n prefix = \", \";\n }\n code.add(\"}\\\";%n\");\n }", "public BlurBuilder brightness(float brightness) {\n data.preProcessors.add(new RenderscriptBrightnessProcessor(data.contextWrapper.getRenderScript(), brightness, data.contextWrapper.getResources()));\n return this;\n }", "private void doDelete(Object obj, boolean ignoreReferences) throws PersistenceBrokerException\n {\n //logger.info(\"DELETING \" + obj);\n // object is not null\n if (obj != null)\n {\n obj = getProxyFactory().getRealObject(obj);\n /**\n * Kuali Foundation modification -- 8/24/2007\n */\n if ( obj == null ) return;\n /**\n * End of Kuali Foundation modification\n */\n /**\n * MBAIRD\n * 1. if we are marked for delete already, avoid recursing on this object\n *\n * arminw:\n * use object instead Identity object in markedForDelete List,\n * because using objects we get a better performance. I can't find\n * side-effects in doing so.\n */\n if (markedForDelete.contains(obj))\n {\n return;\n }\n \n ClassDescriptor cld = getClassDescriptor(obj.getClass());\n //BRJ: check for valid pk\n if (!serviceBrokerHelper().assertValidPkForDelete(cld, obj))\n {\n String msg = \"Cannot delete object without valid PKs. \" + obj;\n logger.error(msg);\n return;\n }\n \n /**\n * MBAIRD\n * 2. register object in markedForDelete map.\n */\n markedForDelete.add(obj);\n Identity oid = serviceIdentity().buildIdentity(cld, obj);\n\n // Invoke events on PersistenceBrokerAware instances and listeners\n BEFORE_DELETE_EVENT.setTarget(obj);\n fireBrokerEvent(BEFORE_DELETE_EVENT);\n BEFORE_DELETE_EVENT.setTarget(null);\n\n // now perform deletion\n performDeletion(cld, obj, oid, ignoreReferences);\n \t \t \n // Invoke events on PersistenceBrokerAware instances and listeners\n AFTER_DELETE_EVENT.setTarget(obj);\n fireBrokerEvent(AFTER_DELETE_EVENT);\n AFTER_DELETE_EVENT.setTarget(null);\n \t \t \t\n // let the connection manager to execute batch\n connectionManager.executeBatchIfNecessary();\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 }", "public static long randomLongBetween(long min, long max) {\n Random rand = new Random();\n return min + (long) (rand.nextDouble() * (max - min));\n }", "public boolean addMethodToResponseOverride(String pathName, String methodName) {\n // need to find out the ID for the method\n // TODO: change api for adding methods to take the name instead of ID\n try {\n Integer overrideId = getOverrideIdForMethodName(methodName);\n\n // now post to path api to add this is a selected override\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"addOverride\", overrideId.toString()),\n new BasicNameValuePair(\"profileIdentifier\", this._profileName)\n };\n JSONObject response = new JSONObject(doPost(BASE_PATH + uriEncode(pathName), params));\n // check enabled endpoints array to see if this overrideID exists\n JSONArray enabled = response.getJSONArray(\"enabledEndpoints\");\n for (int x = 0; x < enabled.length(); x++) {\n if (enabled.getJSONObject(x).getInt(\"overrideId\") == overrideId) {\n return true;\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return false;\n }", "public void parseVersion( String version )\n {\n DefaultVersioning artifactVersion = new DefaultVersioning( version );\n\n getLog().debug( \"Parsed Version\" );\n getLog().debug( \" major: \" + artifactVersion.getMajor() );\n getLog().debug( \" minor: \" + artifactVersion.getMinor() );\n getLog().debug( \" incremental: \" + artifactVersion.getPatch() );\n getLog().debug( \" buildnumber: \" + artifactVersion.getBuildNumber() );\n getLog().debug( \" qualifier: \" + artifactVersion.getQualifier() );\n\n defineVersionProperty( \"majorVersion\", artifactVersion.getMajor() );\n defineVersionProperty( \"minorVersion\", artifactVersion.getMinor() );\n defineVersionProperty( \"incrementalVersion\", artifactVersion.getPatch() );\n defineVersionProperty( \"buildNumber\", artifactVersion.getBuildNumber() );\n\n defineVersionProperty( \"nextMajorVersion\", artifactVersion.getMajor() + 1 );\n defineVersionProperty( \"nextMinorVersion\", artifactVersion.getMinor() + 1 );\n defineVersionProperty( \"nextIncrementalVersion\", artifactVersion.getPatch() + 1 );\n defineVersionProperty( \"nextBuildNumber\", artifactVersion.getBuildNumber() + 1 );\n\n defineFormattedVersionProperty( \"majorVersion\", String.format( formatMajor, artifactVersion.getMajor() ) );\n defineFormattedVersionProperty( \"minorVersion\", String.format( formatMinor, artifactVersion.getMinor() ) );\n defineFormattedVersionProperty( \"incrementalVersion\", String.format( formatIncremental, artifactVersion.getPatch() ) );\n defineFormattedVersionProperty( \"buildNumber\", String.format( formatBuildNumber, artifactVersion.getBuildNumber() ));\n\n defineFormattedVersionProperty( \"nextMajorVersion\", String.format( formatMajor, artifactVersion.getMajor() + 1 ));\n defineFormattedVersionProperty( \"nextMinorVersion\", String.format( formatMinor, artifactVersion.getMinor() + 1 ));\n defineFormattedVersionProperty( \"nextIncrementalVersion\", String.format( formatIncremental, artifactVersion.getPatch() + 1 ));\n defineFormattedVersionProperty( \"nextBuildNumber\", String.format( formatBuildNumber, artifactVersion.getBuildNumber() + 1 ));\n \n String osgi = artifactVersion.getAsOSGiVersion();\n\n String qualifier = artifactVersion.getQualifier();\n String qualifierQuestion = \"\";\n if ( qualifier == null )\n {\n qualifier = \"\";\n } else {\n qualifierQuestion = qualifierPrefix;\n }\n\n defineVersionProperty( \"qualifier\", qualifier );\n defineVersionProperty( \"qualifier?\", qualifierQuestion + qualifier );\n\n defineVersionProperty( \"osgiVersion\", osgi );\n }" ]
Cleans the object key. @param name Name of the object key @return The {@link ValidationResult} object containing the object, and the error code(if any)
[ "ValidationResult cleanObjectKey(String name) {\n ValidationResult vr = new ValidationResult();\n name = name.trim();\n for (String x : objectKeyCharsNotAllowed)\n name = name.replace(x, \"\");\n\n if (name.length() > Constants.MAX_KEY_LENGTH) {\n name = name.substring(0, Constants.MAX_KEY_LENGTH-1);\n vr.setErrorDesc(name.trim() + \"... exceeds the limit of \"+ Constants.MAX_KEY_LENGTH + \" characters. Trimmed\");\n vr.setErrorCode(520);\n }\n\n vr.setObject(name.trim());\n\n return vr;\n }" ]
[ "public boolean setCurrentPage(final int page) {\n Log.d(TAG, \"setPageId pageId = %d\", page);\n return (page >= 0 && page < getCheckableCount()) && check(page);\n }", "private Collection<TestClassResults> flattenResults(List<ISuite> suites)\n {\n Map<IClass, TestClassResults> flattenedResults = new HashMap<IClass, TestClassResults>();\n for (ISuite suite : suites)\n {\n for (ISuiteResult suiteResult : suite.getResults().values())\n {\n // Failed and skipped configuration methods are treated as test failures.\n organiseByClass(suiteResult.getTestContext().getFailedConfigurations().getAllResults(), flattenedResults);\n organiseByClass(suiteResult.getTestContext().getSkippedConfigurations().getAllResults(), flattenedResults);\n // Successful configuration methods are not included.\n \n organiseByClass(suiteResult.getTestContext().getFailedTests().getAllResults(), flattenedResults);\n organiseByClass(suiteResult.getTestContext().getSkippedTests().getAllResults(), flattenedResults);\n organiseByClass(suiteResult.getTestContext().getPassedTests().getAllResults(), flattenedResults);\n }\n }\n return flattenedResults.values();\n }", "private void readHeaderProperties(BufferedInputStream stream) throws IOException\n {\n String header = readHeaderString(stream);\n for (String property : header.split(\"\\\\|\"))\n {\n String[] expression = property.split(\"=\");\n m_properties.put(expression[0], expression[1]);\n }\n }", "public static String getClassName(Class<?> c) {\n String name = c.getName();\n return name.substring(name.lastIndexOf('.') + 1, name.length());\n }", "@RequestMapping(value = \"/api/plugins\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getPluginInformation() {\n return pluginInformation();\n }", "public String getRandomHoliday(String earliest, String latest) {\n String dateString = \"\";\n DateTimeFormatter parser = ISODateTimeFormat.date();\n DateTime earlyDate = parser.parseDateTime(earliest);\n DateTime lateDate = parser.parseDateTime(latest);\n List<Holiday> holidays = new LinkedList<>();\n\n int min = Integer.parseInt(earlyDate.toString().substring(0, 4));\n int max = Integer.parseInt(lateDate.toString().substring(0, 4));\n int range = max - min + 1;\n int randomYear = (int) (Math.random() * range) + min;\n\n for (Holiday s : EquivalenceClassTransformer.HOLIDAYS) {\n holidays.add(s);\n }\n Collections.shuffle(holidays);\n\n for (Holiday holiday : holidays) {\n dateString = convertToReadableDate(holiday.forYear(randomYear));\n if (toDate(dateString).after(toDate(earliest)) && toDate(dateString).before(toDate(latest))) {\n break;\n }\n }\n return dateString;\n }", "public static lbvserver_cachepolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_cachepolicy_binding obj = new lbvserver_cachepolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_cachepolicy_binding response[] = (lbvserver_cachepolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public double computeLikelihoodP() {\n double ret = 1.0;\n\n for( int i = 0; i < r.numRows; i++ ) {\n double a = r.get(i,0);\n\n ret *= Math.exp(-a*a/2.0);\n }\n\n return ret;\n }", "private void initialize(Handler callbackHandler, int threadPoolSize) {\n\t\tmDownloadDispatchers = new DownloadDispatcher[threadPoolSize];\n\t\tmDelivery = new CallBackDelivery(callbackHandler);\n\t}" ]
Computes the square root of the complex number. @param input Input complex number. @param root Output. The square root of the input
[ "public static void sqrt(Complex_F64 input, Complex_F64 root)\n {\n double r = input.getMagnitude();\n double a = input.real;\n\n root.real = Math.sqrt((r+a)/2.0);\n root.imaginary = Math.sqrt((r-a)/2.0);\n if( input.imaginary < 0 )\n root.imaginary = -root.imaginary;\n }" ]
[ "public static ZMatrixRMaj hermitian(int length, double min, double max, Random rand) {\n ZMatrixRMaj A = new ZMatrixRMaj(length,length);\n\n fillHermitian(A, min, max, rand);\n\n return A;\n }", "public void populateFromAttributes(\n @Nonnull final Template template,\n @Nonnull final Map<String, Attribute> attributes,\n @Nonnull final PObject requestJsonAttributes) {\n if (requestJsonAttributes.has(JSON_REQUEST_HEADERS) &&\n requestJsonAttributes.getObject(JSON_REQUEST_HEADERS).has(JSON_REQUEST_HEADERS) &&\n !attributes.containsKey(JSON_REQUEST_HEADERS)) {\n attributes.put(JSON_REQUEST_HEADERS, new HttpRequestHeadersAttribute());\n }\n for (Map.Entry<String, Attribute> attribute: attributes.entrySet()) {\n try {\n put(attribute.getKey(),\n attribute.getValue().getValue(template, attribute.getKey(), requestJsonAttributes));\n } catch (ObjectMissingException | IllegalArgumentException e) {\n throw e;\n } catch (Throwable e) {\n String templateName = \"unknown\";\n for (Map.Entry<String, Template> entry: template.getConfiguration().getTemplates()\n .entrySet()) {\n if (entry.getValue() == template) {\n templateName = entry.getKey();\n break;\n }\n }\n\n String defaults = \"\";\n\n if (attribute instanceof ReflectiveAttribute<?>) {\n ReflectiveAttribute<?> reflectiveAttribute = (ReflectiveAttribute<?>) attribute;\n defaults = \"\\n\\n The attribute defaults are: \" + reflectiveAttribute.getDefaultValue();\n }\n\n String errorMsg = \"An error occurred when creating a value from the '\" + attribute.getKey() +\n \"' attribute for the '\" +\n templateName + \"' template.\\n\\nThe JSON is: \\n\" + requestJsonAttributes + defaults +\n \"\\n\" +\n e.toString();\n\n throw new AttributeParsingException(errorMsg, e);\n }\n }\n\n if (template.getConfiguration().isThrowErrorOnExtraParameters()) {\n final List<String> extraProperties = new ArrayList<>();\n for (Iterator<String> it = requestJsonAttributes.keys(); it.hasNext(); ) {\n final String attributeName = it.next();\n if (!attributes.containsKey(attributeName)) {\n extraProperties.add(attributeName);\n }\n }\n\n if (!extraProperties.isEmpty()) {\n throw new ExtraPropertyException(\"Extra properties found in the request attributes\",\n extraProperties, attributes.keySet());\n }\n }\n }", "public int getBoneIndex(GVRSceneObject bone)\n {\n for (int i = 0; i < getNumBones(); ++i)\n if (mBones[i] == bone)\n return i;\n return -1;\n }", "public void setKnotType(int n, int type) {\n\t\tknotTypes[n] = (byte)((knotTypes[n] & ~COLOR_MASK) | type);\n\t\trebuildGradient();\n\t}", "private void checkRowReader(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (!CHECKLEVEL_STRICT.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n \r\n String rowReaderName = classDef.getProperty(PropertyHelper.OJB_PROPERTY_ROW_READER);\r\n\r\n if (rowReaderName == null)\r\n {\r\n return;\r\n }\r\n\r\n try\r\n {\r\n InheritanceHelper helper = new InheritanceHelper();\r\n\r\n if (!helper.isSameOrSubTypeOf(rowReaderName, ROW_READER_INTERFACE))\r\n {\r\n throw new ConstraintException(\"The class \"+rowReaderName+\" specified as row-reader of class \"+classDef.getName()+\" does not implement the interface \"+ROW_READER_INTERFACE);\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"Could not find the class \"+ex.getMessage()+\" on the classpath while checking the row-reader class \"+rowReaderName+\" of class \"+classDef.getName());\r\n }\r\n }", "@Override\n protected void _acceptTimestampVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint)\n throws JsonMappingException\n {\n SerializerProvider prov = visitor.getProvider();\n if ((prov != null) && useNanoseconds(prov)) {\n JsonNumberFormatVisitor v2 = visitor.expectNumberFormat(typeHint);\n if (v2 != null) {\n v2.numberType(NumberType.BIG_DECIMAL);\n }\n } else {\n JsonIntegerFormatVisitor v2 = visitor.expectIntegerFormat(typeHint);\n if (v2 != null) {\n v2.numberType(NumberType.LONG);\n }\n }\n }", "protected FluentModelTImpl find(String key) {\n for (Map.Entry<String, FluentModelTImpl> entry : this.childCollection.entrySet()) {\n if (entry.getKey().equalsIgnoreCase(key)) {\n return entry.getValue();\n }\n }\n return null;\n }", "public void setColorForTotal(int row, int column, Color color){\r\n\t\tint mapC = (colors.length-1) - column;\r\n\t\tint mapR = (colors[0].length-1) - row;\r\n\t\tcolors[mapC][mapR]=color;\t\t\r\n\t}", "private void deliverMediaDetailsUpdate(final MediaDetails details) {\n for (MediaDetailsListener listener : getMediaDetailsListeners()) {\n try {\n listener.detailsAvailable(details);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering media details response to listener\", t);\n }\n }\n }" ]
Initialize the pattern controllers.
[ "private void initPatternControllers() {\r\n\r\n m_patternControllers.put(PatternType.NONE, new CmsPatternPanelNoneController());\r\n m_patternControllers.put(PatternType.DAILY, new CmsPatternPanelDailyController(m_model, this));\r\n m_patternControllers.put(PatternType.WEEKLY, new CmsPatternPanelWeeklyController(m_model, this));\r\n m_patternControllers.put(PatternType.MONTHLY, new CmsPatternPanelMonthlyController(m_model, this));\r\n m_patternControllers.put(PatternType.YEARLY, new CmsPatternPanelYearlyController(m_model, this));\r\n // m_patternControllers.put(PatternType.INDIVIDUAL, new CmsPatternPanelIndividualController(m_model, this));\r\n }" ]
[ "public List<ProjectFile> readAll() throws MPXJException\n {\n Map<Integer, String> projects = listProjects();\n List<ProjectFile> result = new ArrayList<ProjectFile>(projects.keySet().size());\n for (Integer id : projects.keySet())\n {\n setProjectID(id.intValue());\n result.add(read());\n }\n return result;\n }", "public static authenticationlocalpolicy_authenticationvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationlocalpolicy_authenticationvserver_binding obj = new authenticationlocalpolicy_authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationlocalpolicy_authenticationvserver_binding response[] = (authenticationlocalpolicy_authenticationvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private void writeCalendar(ProjectCalendar mpxjCalendar, net.sf.mpxj.planner.schema.Calendar plannerCalendar) throws JAXBException\n {\n //\n // Populate basic details\n //\n plannerCalendar.setId(getIntegerString(mpxjCalendar.getUniqueID()));\n plannerCalendar.setName(getString(mpxjCalendar.getName()));\n\n //\n // Set working and non working days\n //\n DefaultWeek dw = m_factory.createDefaultWeek();\n plannerCalendar.setDefaultWeek(dw);\n dw.setMon(getWorkingDayString(mpxjCalendar, Day.MONDAY));\n dw.setTue(getWorkingDayString(mpxjCalendar, Day.TUESDAY));\n dw.setWed(getWorkingDayString(mpxjCalendar, Day.WEDNESDAY));\n dw.setThu(getWorkingDayString(mpxjCalendar, Day.THURSDAY));\n dw.setFri(getWorkingDayString(mpxjCalendar, Day.FRIDAY));\n dw.setSat(getWorkingDayString(mpxjCalendar, Day.SATURDAY));\n dw.setSun(getWorkingDayString(mpxjCalendar, Day.SUNDAY));\n\n //\n // Set working hours\n //\n OverriddenDayTypes odt = m_factory.createOverriddenDayTypes();\n plannerCalendar.setOverriddenDayTypes(odt);\n List<OverriddenDayType> typeList = odt.getOverriddenDayType();\n Sequence uniqueID = new Sequence(0);\n\n //\n // This is a bit arbitrary, so not ideal, however...\n // The idea here is that MS Project allows us to specify working hours\n // for each day of the week individually. Planner doesn't do this,\n // but instead allows us to specify working hours for each day type.\n // What we are doing here is stepping through the days of the week to\n // find the first working day, then using the hours for that day\n // as the hours for the working day type in Planner.\n //\n for (int dayLoop = 1; dayLoop < 8; dayLoop++)\n {\n Day day = Day.getInstance(dayLoop);\n if (mpxjCalendar.isWorkingDay(day))\n {\n processWorkingHours(mpxjCalendar, uniqueID, day, typeList);\n break;\n }\n }\n\n //\n // Process exception days\n //\n Days plannerDays = m_factory.createDays();\n plannerCalendar.setDays(plannerDays);\n List<net.sf.mpxj.planner.schema.Day> dayList = plannerDays.getDay();\n processExceptionDays(mpxjCalendar, dayList);\n\n m_eventManager.fireCalendarWrittenEvent(mpxjCalendar);\n\n //\n // Process any derived calendars\n //\n List<net.sf.mpxj.planner.schema.Calendar> calendarList = plannerCalendar.getCalendar();\n\n for (ProjectCalendar mpxjDerivedCalendar : mpxjCalendar.getDerivedCalendars())\n {\n net.sf.mpxj.planner.schema.Calendar plannerDerivedCalendar = m_factory.createCalendar();\n calendarList.add(plannerDerivedCalendar);\n writeCalendar(mpxjDerivedCalendar, plannerDerivedCalendar);\n }\n }", "public ClassNode parent(String name) {\n this.parent = infoBase.node(name);\n this.parent.addChild(this);\n for (ClassNode intf : parent.interfaces.values()) {\n addInterface(intf);\n }\n return this;\n }", "public static base_responses update(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 updateresources[] = new route6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new route6();\n\t\t\t\tupdateresources[i].network = resources[i].network;\n\t\t\t\tupdateresources[i].gateway = resources[i].gateway;\n\t\t\t\tupdateresources[i].vlan = resources[i].vlan;\n\t\t\t\tupdateresources[i].weight = resources[i].weight;\n\t\t\t\tupdateresources[i].distance = resources[i].distance;\n\t\t\t\tupdateresources[i].cost = resources[i].cost;\n\t\t\t\tupdateresources[i].advertise = resources[i].advertise;\n\t\t\t\tupdateresources[i].msr = resources[i].msr;\n\t\t\t\tupdateresources[i].monitor = resources[i].monitor;\n\t\t\t\tupdateresources[i].td = resources[i].td;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "@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 void setDefaultInterval(long defaultInterval) {\n \tif(defaultInterval <= 0) {\n \t\tLOG.severe(\"collector.scheduler.interval must be greater than 0. Recommended value is 500-1000. Current value is \" + defaultInterval);\n \t\tthrow new IllegalArgumentException(\"collector.scheduler.interval must be greater than 0. Recommended value is 500-1000. Current value is \" + defaultInterval);\n \t}\n this.defaultInterval = defaultInterval;\n }", "private Map<String, Object> getMapFromJSON(String json) {\n Map<String, Object> propMap = new HashMap<String, Object>();\n ObjectMapper mapper = new ObjectMapper();\n\n // Initialize string if empty\n if (json == null || json.length() == 0) {\n json = \"{}\";\n }\n\n try {\n // Convert string\n propMap = mapper.readValue(json, new TypeReference<HashMap<String, Object>>(){});\n } catch (Exception e) {\n ;\n }\n return propMap;\n }", "public List<Task> getActiveTasks() {\n InputStream response = null;\n URI uri = new URIBase(getBaseUri()).path(\"_active_tasks\").build();\n try {\n response = couchDbClient.get(uri);\n return getResponseList(response, couchDbClient.getGson(), DeserializationTypes.TASKS);\n } finally {\n close(response);\n }\n }" ]
Get the element at the index as a string. @param i the index of the element to access
[ "@Override\n public final String getString(final int i) {\n String val = this.array.optString(i, null);\n if (val == null) {\n throw new ObjectMissingException(this, \"[\" + i + \"]\");\n }\n return val;\n }" ]
[ "private JSONArray readOptionalArray(JSONObject json, String key) {\n\n try {\n return json.getJSONArray(key);\n } catch (JSONException e) {\n LOG.debug(\"Reading optional JSON array failed. Default to provided default value.\", e);\n }\n return null;\n }", "private Options getOptions() {\n\t\tOptions options = new Options();\n\t\toptions.addOption(\"h\", HELP, false, \"print this message\");\n\t\toptions.addOption(VERSION, false, \"print the version information and exit\");\n\n\t\toptions.addOption(\"b\", BROWSER, true,\n\t\t \"browser type: \" + availableBrowsers() + \". Default is Firefox\");\n\n\t\toptions.addOption(BROWSER_REMOTE_URL, true,\n\t\t \"The remote url if you have configured a remote browser\");\n\n\t\toptions.addOption(\"d\", DEPTH, true, \"crawl depth level. Default is 2\");\n\n\t\toptions.addOption(\"s\", MAXSTATES, true,\n\t\t \"max number of states to crawl. Default is 0 (unlimited)\");\n\n\t\toptions.addOption(\"p\", PARALLEL, true,\n\t\t \"Number of browsers to use for crawling. Default is 1\");\n\t\toptions.addOption(\"o\", OVERRIDE, false, \"Override the output directory if non-empty\");\n\n\t\toptions.addOption(\"a\", CRAWL_HIDDEN_ANCHORS, false,\n\t\t \"Crawl anchors even if they are not visible in the browser.\");\n\n\t\toptions.addOption(\"t\", TIME_OUT, true,\n\t\t \"Specify the maximum crawl time in minutes\");\n\n\t\toptions.addOption(CLICK, true,\n\t\t \"a comma separated list of HTML tags that should be clicked. Default is A and BUTTON\");\n\n\t\toptions.addOption(WAIT_AFTER_EVENT, true,\n\t\t \"the time to wait after an event has been fired in milliseconds. Default is \"\n\t\t + CrawlRules.DEFAULT_WAIT_AFTER_EVENT);\n\n\t\toptions.addOption(WAIT_AFTER_RELOAD, true,\n\t\t \"the time to wait after an URL has been loaded in milliseconds. Default is \"\n\t\t + CrawlRules.DEFAULT_WAIT_AFTER_RELOAD);\n\n\t\toptions.addOption(\"v\", VERBOSE, false, \"Be extra verbose\");\n\t\toptions.addOption(LOG_FILE, true, \"Log to this file instead of the console\");\n\n\t\treturn options;\n\t}", "public static void main(String[] args) throws IOException, ClassNotFoundException {\r\n CoNLLDocumentReaderAndWriter f = new CoNLLDocumentReaderAndWriter();\r\n f.init(new SeqClassifierFlags());\r\n int numDocs = 0;\r\n int numTokens = 0;\r\n int numEntities = 0;\r\n String lastAnsBase = \"\";\r\n for (Iterator<List<CoreLabel>> it = f.getIterator(new FileReader(args[0])); it.hasNext(); ) {\r\n List<CoreLabel> doc = it.next();\r\n numDocs++;\r\n for (CoreLabel fl : doc) {\r\n // System.out.println(\"FL \" + (++i) + \" was \" + fl);\r\n if (fl.word().equals(BOUNDARY)) {\r\n continue;\r\n }\r\n String ans = fl.get(AnswerAnnotation.class);\r\n String ansBase;\r\n String ansPrefix;\r\n String[] bits = ans.split(\"-\");\r\n if (bits.length == 1) {\r\n ansBase = bits[0];\r\n ansPrefix = \"\";\r\n } else {\r\n ansBase = bits[1];\r\n ansPrefix = bits[0];\r\n }\r\n numTokens++;\r\n if (ansBase.equals(\"O\")) {\r\n } else if (ansBase.equals(lastAnsBase)) {\r\n if (ansPrefix.equals(\"B\")) {\r\n numEntities++;\r\n }\r\n } else {\r\n numEntities++;\r\n }\r\n }\r\n }\r\n System.out.println(\"File \" + args[0] + \" has \" + numDocs + \" documents, \" +\r\n numTokens + \" (non-blank line) tokens and \" +\r\n numEntities + \" entities.\");\r\n }", "private void processRanges(List<DateRange> ranges, ProjectCalendarDateRanges container)\n {\n if (ranges != null)\n {\n for (DateRange range : ranges)\n {\n container.addRange(range);\n }\n }\n }", "public void process(ProjectFile file, Var2Data varData, byte[] fixedData) throws IOException\n {\n Props props = getProps(varData);\n //System.out.println(props);\n if (props != null)\n {\n String viewName = MPPUtility.removeAmpersands(props.getUnicodeString(VIEW_NAME));\n byte[] listData = props.getByteArray(VIEW_CONTENTS);\n List<Integer> uniqueIdList = new LinkedList<Integer>();\n if (listData != null)\n {\n for (int index = 0; index < listData.length; index += 4)\n {\n Integer uniqueID = Integer.valueOf(MPPUtility.getInt(listData, index));\n\n //\n // Ensure that we have a valid task, and that if we have and\n // ID of zero, this is the first task shown.\n //\n if (file.getTaskByUniqueID(uniqueID) != null && (uniqueID.intValue() != 0 || index == 0))\n {\n uniqueIdList.add(uniqueID);\n }\n }\n }\n\n int filterID = MPPUtility.getShort(fixedData, 128);\n\n ViewState state = new ViewState(file, viewName, uniqueIdList, filterID);\n file.getViews().setViewState(state);\n }\n }", "public Gallery lookupGallery(String galleryId) throws FlickrException {\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_LOOKUP_GALLERY);\r\n parameters.put(\"url\", galleryId);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element galleryElement = response.getPayload();\r\n Gallery gallery = new Gallery();\r\n gallery.setId(galleryElement.getAttribute(\"id\"));\r\n gallery.setUrl(galleryElement.getAttribute(\"url\"));\r\n\r\n User owner = new User();\r\n owner.setId(galleryElement.getAttribute(\"owner\"));\r\n gallery.setOwner(owner);\r\n gallery.setCreateDate(galleryElement.getAttribute(\"date_create\"));\r\n gallery.setUpdateDate(galleryElement.getAttribute(\"date_update\"));\r\n gallery.setPrimaryPhotoId(galleryElement.getAttribute(\"primary_photo_id\"));\r\n gallery.setPrimaryPhotoServer(galleryElement.getAttribute(\"primary_photo_server\"));\r\n gallery.setVideoCount(galleryElement.getAttribute(\"count_videos\"));\r\n gallery.setPhotoCount(galleryElement.getAttribute(\"count_photos\"));\r\n gallery.setPrimaryPhotoFarm(galleryElement.getAttribute(\"farm\"));\r\n gallery.setPrimaryPhotoSecret(galleryElement.getAttribute(\"secret\"));\r\n\r\n gallery.setTitle(XMLUtilities.getChildValue(galleryElement, \"title\"));\r\n gallery.setDesc(XMLUtilities.getChildValue(galleryElement, \"description\"));\r\n return gallery;\r\n }", "public 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 static String stringifyJavascriptObject(Object object) {\n StringBuilder bld = new StringBuilder();\n stringify(object, bld);\n return bld.toString();\n }", "protected static String ConvertBinaryOperator(int oper)\r\n {\r\n // Convert the operator into the proper string\r\n String oper_string;\r\n switch (oper)\r\n {\r\n default:\r\n case EQUAL:\r\n oper_string = \"=\";\r\n break;\r\n case LIKE:\r\n oper_string = \"LIKE\";\r\n break;\r\n case NOT_EQUAL:\r\n oper_string = \"!=\";\r\n break;\r\n case LESS_THAN:\r\n oper_string = \"<\";\r\n break;\r\n case GREATER_THAN:\r\n oper_string = \">\";\r\n break;\r\n case GREATER_EQUAL:\r\n oper_string = \">=\";\r\n break;\r\n case LESS_EQUAL:\r\n oper_string = \"<=\";\r\n break;\r\n }\r\n return oper_string;\r\n }" ]
This function returns the first external IP address encountered @return IP address or null @throws Exception
[ "public static String getPublicIPAddress() throws Exception {\n final String IPV4_REGEX = \"\\\\A(25[0-5]|2[0-4]\\\\d|[0-1]?\\\\d?\\\\d)(\\\\.(25[0-5]|2[0-4]\\\\d|[0-1]?\\\\d?\\\\d)){3}\\\\z\";\n\n String ipAddr = null;\n Enumeration e = NetworkInterface.getNetworkInterfaces();\n while (e.hasMoreElements()) {\n NetworkInterface n = (NetworkInterface) e.nextElement();\n Enumeration ee = n.getInetAddresses();\n while (ee.hasMoreElements()) {\n InetAddress i = (InetAddress) ee.nextElement();\n\n // Pick the first non loop back address\n if ((!i.isLoopbackAddress() && i.isSiteLocalAddress()) ||\n i.getHostAddress().matches(IPV4_REGEX)) {\n ipAddr = i.getHostAddress();\n break;\n }\n }\n if (ipAddr != null) {\n break;\n }\n }\n\n return ipAddr;\n }" ]
[ "public void start() {\n if (this.started) {\n throw new IllegalStateException(\"Cannot start the EventStream because it isn't stopped.\");\n }\n\n final long initialPosition;\n\n if (this.startingPosition == STREAM_POSITION_NOW) {\n BoxAPIRequest request = new BoxAPIRequest(this.api, EVENT_URL.build(this.api.getBaseURL(), \"now\"), \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n initialPosition = jsonObject.get(\"next_stream_position\").asLong();\n } else {\n assert this.startingPosition >= 0 : \"Starting position must be non-negative\";\n initialPosition = this.startingPosition;\n }\n\n this.poller = new Poller(initialPosition);\n\n this.pollerThread = new Thread(this.poller);\n this.pollerThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {\n public void uncaughtException(Thread t, Throwable e) {\n EventStream.this.notifyException(e);\n }\n });\n this.pollerThread.start();\n\n this.started = true;\n }", "public static final String decodePassword(byte[] data, byte encryptionCode)\n {\n String result;\n\n if (data.length < MINIMUM_PASSWORD_DATA_LENGTH)\n {\n result = null;\n }\n else\n {\n MPPUtility.decodeBuffer(data, encryptionCode);\n\n StringBuilder buffer = new StringBuilder();\n char c;\n\n for (int i = 0; i < PASSWORD_MASK.length; i++)\n {\n int index = PASSWORD_MASK[i];\n c = (char) data[index];\n\n if (c == 0)\n {\n break;\n }\n buffer.append(c);\n }\n\n result = buffer.toString();\n }\n\n return (result);\n }", "public static ServiceName deploymentUnitName(String name, Phase phase) {\n return JBOSS_DEPLOYMENT_UNIT.append(name, phase.name());\n }", "private int getLiteralId(String literal) throws PersistenceBrokerException\r\n {\r\n ////logger.debug(\"lookup: \" + literal);\r\n try\r\n {\r\n return tags.getIdByTag(literal);\r\n }\r\n catch (NullPointerException t)\r\n {\r\n throw new MetadataException(\"unknown literal: '\" + literal + \"'\",t);\r\n }\r\n\r\n }", "public synchronized void cleanWaitTaskQueue() {\n\n for (ParallelTask task : waitQ) {\n task.setState(ParallelTaskState.COMPLETED_WITH_ERROR);\n task.getTaskErrorMetas().add(\n new TaskErrorMeta(TaskErrorType.USER_CANCELED, \"NA\"));\n logger.info(\n \"task {} removed from wait q. This task has been marked as USER CANCELED.\",\n task.getTaskId());\n\n }\n\n waitQ.clear();\n }", "public static Range toRange(Span span) {\n return new Range(toKey(span.getStart()), span.isStartInclusive(), toKey(span.getEnd()),\n span.isEndInclusive());\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 }", "private void processGraphicalIndicators()\n {\n GraphicalIndicatorReader graphicalIndicatorReader = new GraphicalIndicatorReader();\n graphicalIndicatorReader.process(m_file.getCustomFields(), m_file.getProjectProperties(), m_projectProps);\n }", "public static boolean isPrimitiveWrapperArray(Class<?> clazz) {\n\t\tAssert.notNull(clazz, \"Class must not be null\");\n\t\treturn (clazz.isArray() && isPrimitiveWrapper(clazz.getComponentType()));\n\t}" ]
The selectionStrategy given as String argument is selected as locatorSelectionStrategy. If selectionStrategy is null, the defaultLocatorSelectionStrategy is used instead. Then the new locatorSelectionStrategy is connected to the locatorClient and the matcher. A new LocatorTargetSelector is created, set to the locatorSelectionStrategy and then set as selector in the conduitSelectorHolder. @param conduitSelectorHolder @param matcher @param selectionStrategy
[ "public void enable(ConduitSelectorHolder conduitSelectorHolder, SLPropertiesMatcher matcher,\n String selectionStrategy) {\n LocatorTargetSelector selector = new LocatorTargetSelector();\n selector.setEndpoint(conduitSelectorHolder.getConduitSelector().getEndpoint());\n\n String actualStrategy = selectionStrategy != null ? selectionStrategy : defaultLocatorSelectionStrategy;\n \n LocatorSelectionStrategy locatorSelectionStrategy = getLocatorSelectionStrategy(actualStrategy);\n locatorSelectionStrategy.setServiceLocator(locatorClient);\n if (matcher != null) {\n locatorSelectionStrategy.setMatcher(matcher);\n }\n selector.setLocatorSelectionStrategy(locatorSelectionStrategy);\n\n if (LOG.isLoggable(Level.INFO)) {\n LOG.log(Level.INFO, \"Client enabled with strategy \"\n + locatorSelectionStrategy.getClass().getName() + \".\");\n }\n conduitSelectorHolder.setConduitSelector(selector);\n\n if (LOG.isLoggable(Level.FINE)) {\n LOG.log(Level.FINE, \"Successfully enabled client \" + conduitSelectorHolder\n + \" for the service locator\");\n }\n }" ]
[ "public synchronized boolean tryDelegateSlop(Node node) {\n if(asyncCallbackShouldSendhint) {\n return false;\n } else {\n slopDestinations.put(node, true);\n return true;\n }\n }", "public double[] Kernel1D(int size) {\n if (((size % 2) == 0) || (size < 3) || (size > 101)) {\n try {\n throw new Exception(\"Wrong size\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n int r = size / 2;\n // kernel\n double[] kernel = new double[size];\n\n // compute kernel\n for (int x = -r, i = 0; i < size; x++, i++) {\n kernel[i] = Function1D(x);\n }\n\n return kernel;\n }", "public boolean mapsCell(String cell) {\n return mappers.values().stream().anyMatch(mapper -> mapper.mapsCell(cell));\n }", "public CentralDogmaBuilder port(InetSocketAddress localAddress, SessionProtocol protocol) {\n return port(new ServerPort(localAddress, protocol));\n }", "public static final byte[] cloneSubArray(byte[] data, int offset, int size)\n {\n byte[] newData = new byte[size];\n System.arraycopy(data, offset, newData, 0, size);\n return (newData);\n }", "private void openBrowser(URI url) throws IOException {\n if (Desktop.isDesktopSupported()) {\n Desktop.getDesktop().browse(url);\n } else {\n LOGGER.error(\"Can not open browser because this capability is not supported on \" +\n \"your platform. You can use the link below to open the report manually.\");\n }\n }", "private void processAssignments() throws SQLException\n {\n List<Row> rows = getRows(\"select * from zscheduleitem where zproject=? and z_ent=? order by zorderinactivity\", m_projectID, m_entityMap.get(\"Assignment\"));\n for (Row row : rows)\n {\n Task task = m_project.getTaskByUniqueID(row.getInteger(\"ZACTIVITY_\"));\n Resource resource = m_project.getResourceByUniqueID(row.getInteger(\"ZRESOURCE\"));\n if (task != null && resource != null)\n {\n ResourceAssignment assignment = task.addResourceAssignment(resource);\n assignment.setGUID(row.getUUID(\"ZUNIQUEID\"));\n assignment.setActualFinish(row.getTimestamp(\"ZGIVENACTUALENDDATE_\"));\n assignment.setActualStart(row.getTimestamp(\"ZGIVENACTUALSTARTDATE_\"));\n\n assignment.setWork(assignmentDuration(task, row.getWork(\"ZGIVENWORK_\")));\n assignment.setOvertimeWork(assignmentDuration(task, row.getWork(\"ZGIVENWORKOVERTIME_\")));\n assignment.setActualWork(assignmentDuration(task, row.getWork(\"ZGIVENACTUALWORK_\")));\n assignment.setActualOvertimeWork(assignmentDuration(task, row.getWork(\"ZGIVENACTUALWORKOVERTIME_\")));\n assignment.setRemainingWork(assignmentDuration(task, row.getWork(\"ZGIVENREMAININGWORK_\")));\n\n assignment.setLevelingDelay(row.getDuration(\"ZLEVELINGDELAY_\"));\n\n if (assignment.getRemainingWork() == null)\n {\n assignment.setRemainingWork(assignment.getWork());\n }\n\n if (resource.getType() == ResourceType.WORK)\n {\n assignment.setUnits(Double.valueOf(NumberHelper.getDouble(row.getDouble(\"ZRESOURCEUNITS_\")) * 100.0));\n }\n }\n }\n }", "public SerialMessage getSupportedMessage() {\r\n\t\tlogger.debug(\"Creating new message for application command SENSOR_ALARM_SUPPORTED_GET for node {}\", this.getNode().getNodeId());\r\n\t\t\r\n\t\tif (this.getNode().getManufacturer() == 0x010F && this.getNode().getDeviceType() == 0x0501) {\r\n\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\treturn null;\r\n\t\t}\r\n\t\t\r\n\t\tSerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessage.SerialMessageClass.SendData, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.ApplicationCommandHandler, SerialMessage.SerialMessagePriority.Get);\r\n \tbyte[] newPayload = { \t(byte) this.getNode().getNodeId(), \r\n \t\t\t\t\t\t\t2, \r\n\t\t\t\t\t\t\t\t(byte) getCommandClass().getKey(), \r\n\t\t\t\t\t\t\t\t(byte) SENSOR_ALARM_SUPPORTED_GET };\r\n \tresult.setMessagePayload(newPayload);\r\n \treturn result;\t\t\r\n\t}", "public void stopServer() throws Exception {\n if (!externalDatabaseHost) {\n try (Connection sqlConnection = getConnection()) {\n sqlConnection.prepareStatement(\"SHUTDOWN\").execute();\n } catch (Exception e) {\n }\n\n try {\n server.stop();\n } catch (Exception e) {\n }\n }\n }" ]
Get a list of referrers from a given domain to a photo. @param date (Required) Stats will be returned for this date. A day according to Flickr Stats starts at midnight GMT for all users, and timestamps will automatically be rounded down to the start of the day. @param domain (Required) The domain to return referrers for. This should be a hostname (eg: "flickr.com") with no protocol or pathname. @param photoId (Optional) The id of the photo to get stats for. If not provided, stats for all photos will be returned. @param perPage (Optional) Number of domains to return per page. If this argument is omitted, it defaults to 25. The maximum allowed value is 100. @param page (Optional) The page of results to return. If this argument is omitted, it defaults to 1. @see "http://www.flickr.com/services/api/flickr.stats.getPhotoReferrers.html"
[ "public ReferrerList getPhotoReferrers(Date date, String domain, String photoId, int perPage, int page) throws FlickrException {\n return getReferrers(METHOD_GET_PHOTO_REFERRERS, domain, \"photo_id\", photoId, date, perPage, page);\n }" ]
[ "public static synchronized FormInputValueHelper getInstance(\n\t\t\tInputSpecification inputSpecification, FormFillMode formFillMode) {\n\t\tif (instance == null)\n\t\t\tinstance = new FormInputValueHelper(inputSpecification,\n\t\t\t\t\tformFillMode);\n\t\treturn instance;\n\t}", "private void retrieveNextPage() {\n if (this.pageSize < Long.MAX_VALUE || this.itemLimit < Long.MAX_VALUE) {\n this.request.query(\"limit\", Math.min(this.pageSize, this.itemLimit - this.count));\n } else {\n this.request.query(\"limit\", null);\n }\n ResultBodyCollection<T> page = null;\n try {\n page = this.getNext();\n } catch (IOException exception) {\n // See comments in hasNext().\n this.ioException = exception;\n }\n if (page != null) {\n this.continuation = this.getContinuation(page);\n if (page.data != null && !page.data.isEmpty()) {\n this.count += page.data.size();\n this.nextData = page.data;\n } else {\n this.nextData = null;\n }\n } else {\n this.continuation = null;\n this.nextData = null;\n }\n }", "public void execute() throws MojoExecutionException, MojoFailureException {\n try {\n Set<File> thriftFiles = findThriftFiles();\n\n final File outputDirectory = getOutputDirectory();\n ImmutableSet<File> outputFiles = findGeneratedFilesInDirectory(getOutputDirectory());\n\n Set<String> compileRoots = new HashSet<String>();\n compileRoots.add(\"scrooge\");\n\n if (thriftFiles.isEmpty()) {\n getLog().info(\"No thrift files to compile.\");\n } else if (checkStaleness && ((lastModified(thriftFiles) + staleMillis) < lastModified(outputFiles))) {\n getLog().info(\"Generated thrift files up to date, skipping compile.\");\n attachFiles(compileRoots);\n } else {\n outputDirectory.mkdirs();\n\n // Quick fix to fix issues with two mvn installs in a row (ie no clean)\n cleanDirectory(outputDirectory);\n\n getLog().info(format(\"compiling thrift files %s with Scrooge\", thriftFiles));\n synchronized(lock) {\n ScroogeRunner runner = new ScroogeRunner();\n Map<String, String> thriftNamespaceMap = new HashMap<String, String>();\n for (ThriftNamespaceMapping mapping : thriftNamespaceMappings) {\n thriftNamespaceMap.put(mapping.getFrom(), mapping.getTo());\n }\n\n // Include thrifts from resource as well.\n Set<File> includes = thriftIncludes;\n includes.add(getResourcesOutputDirectory());\n\n // Include thrift root\n final File thriftSourceRoot = getThriftSourceRoot();\n if (thriftSourceRoot != null && thriftSourceRoot.exists()) {\n includes.add(thriftSourceRoot);\n }\n\n runner.compile(\n getLog(),\n includeOutputDirectoryNamespace ? new File(outputDirectory, \"scrooge\") : outputDirectory,\n thriftFiles,\n includes,\n thriftNamespaceMap,\n language,\n thriftOpts);\n }\n attachFiles(compileRoots);\n }\n } catch (IOException e) {\n throw new MojoExecutionException(\"An IO error occurred\", e);\n }\n }", "public void setDateMin(Date dateMin) {\n this.dateMin = dateMin;\n\n if (isAttached() && dateMin != null) {\n getPicker().set(\"min\", JsDate.create((double) dateMin.getTime()));\n }\n }", "public static Cluster swapRandomPartitionsWithinZone(final Cluster nextCandidateCluster,\n final int zoneId) {\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n Random r = new Random();\n\n List<Integer> nodeIdsInZone = new ArrayList<Integer>(nextCandidateCluster.getNodeIdsInZone(zoneId));\n\n if(nodeIdsInZone.size() == 0) {\n return returnCluster;\n }\n\n // Select random stealer node\n int stealerNodeOffset = r.nextInt(nodeIdsInZone.size());\n Integer stealerNodeId = nodeIdsInZone.get(stealerNodeOffset);\n\n // Select random stealer partition\n List<Integer> stealerPartitions = returnCluster.getNodeById(stealerNodeId)\n .getPartitionIds();\n if(stealerPartitions.size() == 0) {\n return nextCandidateCluster;\n }\n int stealerPartitionOffset = r.nextInt(stealerPartitions.size());\n int stealerPartitionId = stealerPartitions.get(stealerPartitionOffset);\n\n // Select random donor node\n List<Integer> donorNodeIds = new ArrayList<Integer>();\n donorNodeIds.addAll(nodeIdsInZone);\n donorNodeIds.remove(stealerNodeId);\n\n if(donorNodeIds.isEmpty()) { // No donor nodes!\n return returnCluster;\n }\n int donorIdOffset = r.nextInt(donorNodeIds.size());\n Integer donorNodeId = donorNodeIds.get(donorIdOffset);\n\n // Select random donor partition\n List<Integer> donorPartitions = returnCluster.getNodeById(donorNodeId).getPartitionIds();\n int donorPartitionOffset = r.nextInt(donorPartitions.size());\n int donorPartitionId = donorPartitions.get(donorPartitionOffset);\n\n return swapPartitions(returnCluster,\n stealerNodeId,\n stealerPartitionId,\n donorNodeId,\n donorPartitionId);\n }", "@Override\n public QueryBuilderFind excludingType(final Class<? extends WindupVertexFrame> type)\n {\n pipelineCriteria.add(new QueryGremlinCriterion()\n {\n @Override\n public void query(GraphRewrite event, GraphTraversal<?, Vertex> pipeline)\n {\n pipeline.filter(it -> !GraphTypeManager.hasType(type, it.get()));\n }\n });\n return this;\n }", "private boolean isRelated(Task task, List<Relation> list)\n {\n boolean result = false;\n for (Relation relation : list)\n {\n if (relation.getTargetTask().getUniqueID().intValue() == task.getUniqueID().intValue())\n {\n result = true;\n break;\n }\n }\n return result;\n }", "public static snmpuser[] get(nitro_service service, options option) throws Exception{\n\t\tsnmpuser obj = new snmpuser();\n\t\tsnmpuser[] response = (snmpuser[])obj.get_resources(service,option);\n\t\treturn response;\n\t}", "static <T extends GridDialect> T getDialectFacetOrNull(GridDialect gridDialect, Class<T> facetType) {\n\t\tif ( hasFacet( gridDialect, facetType ) ) {\n\t\t\t@SuppressWarnings(\"unchecked\")\n\t\t\tT asFacet = (T) gridDialect;\n\t\t\treturn asFacet;\n\t\t}\n\n\t\treturn null;\n\t}" ]
Returns details of a previously-requested Organization export. @param organizationExport Globally unique identifier for the Organization export. @return Request object
[ "public ItemRequest<OrganizationExport> findById(String organizationExport) {\n \n String path = String.format(\"/organization_exports/%s\", organizationExport);\n return new ItemRequest<OrganizationExport>(this, OrganizationExport.class, path, \"GET\");\n }" ]
[ "public static void validateZip(File file) throws IOException {\n ZipInputStream zipInput = new ZipInputStream(new FileInputStream(file));\n ZipEntry zipEntry = zipInput.getNextEntry();\n\n while (zipEntry != null) {\n zipEntry = zipInput.getNextEntry();\n }\n\n try {\n if (zipInput != null) {\n zipInput.close();\n }\n } catch (IOException e) {\n }\n }", "private synchronized Client allocateClient(int targetPlayer, String description) throws IOException {\n Client result = openClients.get(targetPlayer);\n if (result == null) {\n // We need to open a new connection.\n final DeviceAnnouncement deviceAnnouncement = DeviceFinder.getInstance().getLatestAnnouncementFrom(targetPlayer);\n if (deviceAnnouncement == null) {\n throw new IllegalStateException(\"Player \" + targetPlayer + \" could not be found \" + description);\n }\n final int dbServerPort = getPlayerDBServerPort(targetPlayer);\n if (dbServerPort < 0) {\n throw new IllegalStateException(\"Player \" + targetPlayer + \" does not have a db server \" + description);\n }\n\n final byte posingAsPlayerNumber = (byte) chooseAskingPlayerNumber(targetPlayer);\n\n Socket socket = null;\n try {\n InetSocketAddress address = new InetSocketAddress(deviceAnnouncement.getAddress(), dbServerPort);\n socket = new Socket();\n socket.connect(address, socketTimeout.get());\n socket.setSoTimeout(socketTimeout.get());\n result = new Client(socket, targetPlayer, posingAsPlayerNumber);\n } catch (IOException e) {\n try {\n socket.close();\n } catch (IOException e2) {\n logger.error(\"Problem closing socket for failed client creation attempt \" + description);\n }\n throw e;\n }\n openClients.put(targetPlayer, result);\n useCounts.put(result, 0);\n }\n useCounts.put(result, useCounts.get(result) + 1);\n return result;\n }", "private List<ExpandableWrapper<P, C>> generateFlattenedParentChildList(List<P> parentList) {\n List<ExpandableWrapper<P, C>> flatItemList = new ArrayList<>();\n\n int parentCount = parentList.size();\n for (int i = 0; i < parentCount; i++) {\n P parent = parentList.get(i);\n generateParentWrapper(flatItemList, parent, parent.isInitiallyExpanded());\n }\n\n return flatItemList;\n }", "public static String getPublicIPAddress() throws Exception {\n final String IPV4_REGEX = \"\\\\A(25[0-5]|2[0-4]\\\\d|[0-1]?\\\\d?\\\\d)(\\\\.(25[0-5]|2[0-4]\\\\d|[0-1]?\\\\d?\\\\d)){3}\\\\z\";\n\n String ipAddr = null;\n Enumeration e = NetworkInterface.getNetworkInterfaces();\n while (e.hasMoreElements()) {\n NetworkInterface n = (NetworkInterface) e.nextElement();\n Enumeration ee = n.getInetAddresses();\n while (ee.hasMoreElements()) {\n InetAddress i = (InetAddress) ee.nextElement();\n\n // Pick the first non loop back address\n if ((!i.isLoopbackAddress() && i.isSiteLocalAddress()) ||\n i.getHostAddress().matches(IPV4_REGEX)) {\n ipAddr = i.getHostAddress();\n break;\n }\n }\n if (ipAddr != null) {\n break;\n }\n }\n\n return ipAddr;\n }", "private void readCostRateTables(Resource resource, Rates rates)\n {\n if (rates == null)\n {\n CostRateTable table = new CostRateTable();\n table.add(CostRateTableEntry.DEFAULT_ENTRY);\n resource.setCostRateTable(0, table);\n\n table = new CostRateTable();\n table.add(CostRateTableEntry.DEFAULT_ENTRY);\n resource.setCostRateTable(1, table);\n\n table = new CostRateTable();\n table.add(CostRateTableEntry.DEFAULT_ENTRY);\n resource.setCostRateTable(2, table);\n\n table = new CostRateTable();\n table.add(CostRateTableEntry.DEFAULT_ENTRY);\n resource.setCostRateTable(3, table);\n\n table = new CostRateTable();\n table.add(CostRateTableEntry.DEFAULT_ENTRY);\n resource.setCostRateTable(4, table);\n }\n else\n {\n Set<CostRateTable> tables = new HashSet<CostRateTable>();\n\n for (net.sf.mpxj.mspdi.schema.Project.Resources.Resource.Rates.Rate rate : rates.getRate())\n {\n Rate standardRate = DatatypeConverter.parseRate(rate.getStandardRate());\n TimeUnit standardRateFormat = DatatypeConverter.parseTimeUnit(rate.getStandardRateFormat());\n Rate overtimeRate = DatatypeConverter.parseRate(rate.getOvertimeRate());\n TimeUnit overtimeRateFormat = DatatypeConverter.parseTimeUnit(rate.getOvertimeRateFormat());\n Double costPerUse = DatatypeConverter.parseCurrency(rate.getCostPerUse());\n Date endDate = rate.getRatesTo();\n\n CostRateTableEntry entry = new CostRateTableEntry(standardRate, standardRateFormat, overtimeRate, overtimeRateFormat, costPerUse, endDate);\n\n int tableIndex = rate.getRateTable().intValue();\n CostRateTable table = resource.getCostRateTable(tableIndex);\n if (table == null)\n {\n table = new CostRateTable();\n resource.setCostRateTable(tableIndex, table);\n }\n table.add(entry);\n tables.add(table);\n }\n\n for (CostRateTable table : tables)\n {\n Collections.sort(table);\n }\n }\n }", "private boolean isWorkingDate(Date date, Day day)\n {\n ProjectCalendarDateRanges ranges = getRanges(date, null, day);\n return ranges.getRangeCount() != 0;\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 StreamReader getTableData(String name) throws IOException\n {\n InputStream stream = new ByteArrayInputStream(m_tableData.get(name));\n if (m_majorVersion > 5)\n { \n byte[] header = new byte[24];\n stream.read(header);\n SynchroLogger.log(\"TABLE HEADER\", header);\n }\n return new StreamReader(m_majorVersion, stream);\n }", "private void fillQueue(QueueItem item, Integer minStartPosition,\n Integer maxStartPosition, Integer minEndPosition) throws IOException {\n int newStartPosition;\n int newEndPosition;\n Integer firstRetrievedPosition = null;\n // remove everything below minStartPosition\n if ((minStartPosition != null) && (item.lowestPosition != null)\n && (item.lowestPosition < minStartPosition)) {\n item.del((minStartPosition - 1));\n }\n // fill queue\n while (!item.noMorePositions) {\n boolean doNotCollectAnotherPosition;\n doNotCollectAnotherPosition = item.filledPosition\n && (minStartPosition == null) && (maxStartPosition == null);\n doNotCollectAnotherPosition |= item.filledPosition\n && (maxStartPosition != null) && (item.lastRetrievedPosition != null)\n && (maxStartPosition < item.lastRetrievedPosition);\n if (doNotCollectAnotherPosition) {\n return;\n } else {\n // collect another full position\n firstRetrievedPosition = null;\n while (!item.noMorePositions) {\n newStartPosition = item.sequenceSpans.spans.nextStartPosition();\n if (newStartPosition == NO_MORE_POSITIONS) {\n if (!item.queue.isEmpty()) {\n item.filledPosition = true;\n item.lastFilledPosition = item.lastRetrievedPosition;\n }\n item.noMorePositions = true;\n return;\n } else if ((minStartPosition != null)\n && (newStartPosition < minStartPosition)) {\n // do nothing\n } else {\n newEndPosition = item.sequenceSpans.spans.endPosition();\n if ((minEndPosition == null) || (newEndPosition >= minEndPosition\n - ignoreItem.getMinStartPosition(docId, newEndPosition))) {\n item.add(newStartPosition, newEndPosition);\n if (firstRetrievedPosition == null) {\n firstRetrievedPosition = newStartPosition;\n } else if (!firstRetrievedPosition.equals(newStartPosition)) {\n break;\n }\n }\n }\n }\n }\n }\n }" ]
Use this API to fetch filtered set of appfwlearningsettings resources. set the filter parameter values in filtervalue object.
[ "public static appfwlearningsettings[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tappfwlearningsettings obj = new appfwlearningsettings();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tappfwlearningsettings[] response = (appfwlearningsettings[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}" ]
[ "public static boolean isConstantVal(DMatrixRMaj mat , double val , double tol )\n {\n // see if the result is an identity matrix\n int index = 0;\n for( int i = 0; i < mat.numRows; i++ ) {\n for( int j = 0; j < mat.numCols; j++ ) {\n if( !(Math.abs(mat.get(index++)-val) <= tol) )\n return false;\n\n }\n }\n\n return true;\n }", "public static DoubleMatrix[] fullSVD(DoubleMatrix A) {\n int m = A.rows;\n int n = A.columns;\n\n DoubleMatrix U = new DoubleMatrix(m, m);\n DoubleMatrix S = new DoubleMatrix(min(m, n));\n DoubleMatrix V = new DoubleMatrix(n, n);\n\n int info = NativeBlas.dgesvd('A', 'A', m, n, A.dup().data, 0, m, S.data, 0, U.data, 0, m, V.data, 0, n);\n\n if (info > 0) {\n throw new LapackConvergenceException(\"GESVD\", info + \" superdiagonals of an intermediate bidiagonal form failed to converge.\");\n }\n\n return new DoubleMatrix[]{U, S, V.transpose()};\n }", "public Vector<Graph<UserStub>> generateAllNodeDataTypeGraphCombinationsOfMaxLength(int length) {\r\n Vector<Graph<UserStub>> graphs = super.generateAllNodeDataTypeGraphCombinationsOfMaxLength(length);\n\r\n if (WRITE_STRUCTURES_IN_PARALLEL) {\r\n // Left as an exercise to the student.\r\n throw new NotImplementedError();\r\n } else {\r\n int i = 0;\r\n for (Iterator<Graph<UserStub>> iter = graphs.toIterator(); iter.hasNext();) {\r\n Graph<UserStub> graph = iter.next();\r\n graph.setGraphId(\"S_\" + ++i + \"_\" + graph.allNodes().size());\r\n graph.writeDotFile(outDir + graph.graphId() + \".gv\", false, ALSO_WRITE_AS_PNG);\r\n }\r\n System.out.println(\"Wrote \" + i + \" graph files in DOT format to \" + outDir + \"\");\r\n }\n\r\n return graphs;\r\n }", "public Envelope getMaxExtent() {\n final int minX = 0;\n final int maxX = 1;\n final int minY = 2;\n final int maxY = 3;\n return new Envelope(this.maxExtent[minX], this.maxExtent[minY], this.maxExtent[maxX],\n this.maxExtent[maxY]);\n }", "public static Trajectory resample(Trajectory t, int n){\n\t\tTrajectory t1 = new Trajectory(2);\n\t\t\n\t\tfor(int i = 0; i < t.size(); i=i+n){\n\t\t\tt1.add(t.get(i));\n\t\t}\n\t\t\n\t\treturn t1;\n\t}", "@SuppressWarnings(\"unchecked\")\n public static <E> void serialize(E object, ParameterizedType<E> parameterizedType, OutputStream os) throws IOException {\n mapperFor(parameterizedType).serialize(object, os);\n }", "public static int getPercentage(String percentage) {\n if (isNotEmpty(percentage) && isNumeric(percentage)) {\n int p = Integer.parseInt(percentage);\n return p;\n } else {\n return 0;\n }\n }", "private void beforeBatch(BatchBackend backend) {\n\t\tif ( this.purgeAtStart ) {\n\t\t\t// purgeAll for affected entities\n\t\t\tIndexedTypeSet targetedTypes = searchFactoryImplementor.getIndexedTypesPolymorphic( rootIndexedTypes );\n\t\t\tfor ( IndexedTypeIdentifier type : targetedTypes ) {\n\t\t\t\t// needs do be in-sync work to make sure we wait for the end of it.\n\t\t\t\tbackend.doWorkInSync( new PurgeAllLuceneWork( tenantId, type ) );\n\t\t\t}\n\t\t\tif ( this.optimizeAfterPurge ) {\n\t\t\t\tbackend.optimize( targetedTypes );\n\t\t\t}\n\t\t}\n\t}", "public static void mlock(Pointer addr, long len) {\n\n int res = Delegate.mlock(addr, new NativeLong(len));\n if(res != 0) {\n if(logger.isDebugEnabled()) {\n logger.debug(\"Mlock failed probably because of insufficient privileges, errno:\"\n + errno.strerror() + \", return value:\" + res);\n }\n } else {\n if(logger.isDebugEnabled())\n logger.debug(\"Mlock successfull\");\n\n }\n\n }" ]
Deletes the first element from the receiver that matches the specified element. Does nothing, if no such matching element is contained. Tests elements for equality or identity as specified by <tt>testForEquality</tt>. When testing for equality, two elements <tt>e1</tt> and <tt>e2</tt> are <i>equal</i> if <tt>(e1==null ? e2==null : e1.equals(e2))</tt>.) @param testForEquality if true -> tests for equality, otherwise for identity. @param element the element to be deleted.
[ "public void delete(Object element, boolean testForEquality) {\r\n\tint index = indexOfFromTo(element, 0, size-1, testForEquality);\r\n\tif (index>=0) removeFromTo(index,index);\r\n}" ]
[ "public void writeTo(WritableByteChannel channel) throws IOException {\n for (ByteBuffer buffer : toDirectByteBuffers()) {\n channel.write(buffer);\n }\n }", "static Style get(final GridParam params) {\n final StyleBuilder builder = new StyleBuilder();\n\n final Symbolizer pointSymbolizer = crossSymbolizer(\"shape://plus\", builder, CROSS_SIZE,\n params.gridColor);\n final Style style = builder.createStyle(pointSymbolizer);\n final List<Symbolizer> symbolizers = style.featureTypeStyles().get(0).rules().get(0).symbolizers();\n\n if (params.haloRadius > 0.0) {\n Symbolizer halo = crossSymbolizer(\"cross\", builder, CROSS_SIZE + params.haloRadius * 2.0,\n params.haloColor);\n symbolizers.add(0, halo);\n }\n\n return style;\n }", "@Override\n public void onDismiss(DialogInterface dialog) {\n if (mOldDialog != null && mOldDialog == dialog) {\n // This is the callback from the old progress dialog that was already dismissed before\n // the device orientation change, so just ignore it.\n return;\n }\n super.onDismiss(dialog);\n }", "public static List<File> extract(File zipFile, File outputFolder) throws IOException {\n List<File> extracted = new ArrayList<File>();\n\n byte[] buffer = new byte[2048];\n\n if (!outputFolder.exists()) {\n outputFolder.mkdir();\n }\n\n ZipInputStream zipInput = new ZipInputStream(new FileInputStream(zipFile));\n\n ZipEntry zipEntry = zipInput.getNextEntry();\n\n while (zipEntry != null) {\n\n String neFileNameName = zipEntry.getName();\n File newFile = new File(outputFolder + File.separator + neFileNameName);\n\n newFile.getParentFile().mkdirs();\n\n if (!zipEntry.isDirectory()) {\n FileOutputStream fos = new FileOutputStream(newFile);\n\n int size;\n while ((size = zipInput.read(buffer)) > 0) {\n fos.write(buffer, 0, size);\n }\n\n fos.close();\n extracted.add(newFile);\n }\n\n zipEntry = zipInput.getNextEntry();\n }\n\n zipInput.closeEntry();\n zipInput.close();\n\n return extracted;\n\n }", "public CompositeGeneratorNode indent(final CompositeGeneratorNode parent, final String indentString) {\n final IndentNode indent = new IndentNode(indentString);\n List<IGeneratorNode> _children = parent.getChildren();\n _children.add(indent);\n return indent;\n }", "void checkRmModelConformance() {\n final AmVisitor<AmObject, AmConstraintContext> visitor = AmVisitors.preorder(new ConformanceVisitor());\n ArchetypeWalker.walkConstraints(visitor, archetype, new AmConstraintContext());\n }", "protected Object getProxyFromResultSet() throws PersistenceBrokerException\r\n {\r\n // 1. get Identity of current row:\r\n Identity oid = getIdentityFromResultSet();\r\n\r\n // 2. return a Proxy instance:\r\n return getBroker().createProxy(getItemProxyClass(), oid);\r\n }", "public static String printUUID(UUID guid)\n {\n return guid == null ? null : \"{\" + guid.toString().toUpperCase() + \"}\";\n }", "public static base_response add(nitro_service client, inat resource) throws Exception {\n\t\tinat addresource = new inat();\n\t\taddresource.name = resource.name;\n\t\taddresource.publicip = resource.publicip;\n\t\taddresource.privateip = resource.privateip;\n\t\taddresource.tcpproxy = resource.tcpproxy;\n\t\taddresource.ftp = resource.ftp;\n\t\taddresource.tftp = resource.tftp;\n\t\taddresource.usip = resource.usip;\n\t\taddresource.usnip = resource.usnip;\n\t\taddresource.proxyip = resource.proxyip;\n\t\taddresource.mode = resource.mode;\n\t\taddresource.td = resource.td;\n\t\treturn addresource.add_resource(client);\n\t}" ]
Fills a rectangle in the image. @param x rect�s start position in x-axis @param y rect�s start positioj in y-axis @param w rect�s width @param h rect�s height @param c rect�s color
[ "public void fillRect(int x, int y, int w, int h, Color c) {\n int color = c.getRGB();\n for (int i = x; i < x + w; i++) {\n for (int j = y; j < y + h; j++) {\n setIntColor(i, j, color);\n }\n }\n }" ]
[ "public static double blackScholesATMOptionValue(\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble forward,\n\t\t\tdouble payoffUnit)\n\t{\n\t\tif(optionMaturity < 0) {\n\t\t\treturn 0.0;\n\t\t}\n\n\t\t// Calculate analytic value\n\t\tdouble dPlus = 0.5 * volatility * Math.sqrt(optionMaturity);\n\t\tdouble dMinus = -dPlus;\n\n\t\tdouble valueAnalytic = (NormalDistribution.cumulativeDistribution(dPlus) - NormalDistribution.cumulativeDistribution(dMinus)) * forward * payoffUnit;\n\n\t\treturn valueAnalytic;\n\t}", "public static byte[] getDocumentToByteArray(Document dom) {\n try {\n TransformerFactory tFactory = TransformerFactory.newInstance();\n\n Transformer transformer = tFactory.newTransformer();\n transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n transformer\n .setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, \"no\");\n transformer.setOutputProperty(OutputKeys.METHOD, \"html\");\n // TODO should be fixed to read doctype declaration\n transformer\n .setOutputProperty(\n OutputKeys.DOCTYPE_PUBLIC,\n \"-//W3C//DTD XHTML 1.0 Strict//EN\\\" \"\n + \"\\\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\");\n\n DOMSource source = new DOMSource(dom);\n\n ByteArrayOutputStream out = new ByteArrayOutputStream();\n Result result = new StreamResult(out);\n transformer.transform(source, result);\n\n return out.toByteArray();\n } catch (TransformerException e) {\n LOGGER.error(\"Error while converting the document to a byte array\",\n e);\n }\n return null;\n\n }", "public boolean shouldIncrementVersionBasedOnResources(CmsObject cms) throws CmsException {\n\n if (m_checkpointTime == 0) {\n return true;\n }\n\n // adjust the site root, if necessary\n CmsObject cmsClone = adjustSiteRootIfNecessary(cms, this);\n\n // calculate the module resources\n List<CmsResource> moduleResources = calculateModuleResources(cmsClone, this);\n\n for (CmsResource resource : moduleResources) {\n try {\n List<CmsResource> resourcesToCheck = Lists.newArrayList();\n resourcesToCheck.add(resource);\n if (resource.isFolder()) {\n resourcesToCheck.addAll(cms.readResources(resource, CmsResourceFilter.IGNORE_EXPIRATION, true));\n }\n for (CmsResource resourceToCheck : resourcesToCheck) {\n if (resourceToCheck.getDateLastModified() > m_checkpointTime) {\n return true;\n }\n }\n } catch (CmsException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n continue;\n }\n }\n return false;\n }", "public static dnsview_binding get(nitro_service service, String viewname) throws Exception{\n\t\tdnsview_binding obj = new dnsview_binding();\n\t\tobj.set_viewname(viewname);\n\t\tdnsview_binding response = (dnsview_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "public Set<String> findResourceNames(String location, URI locationUri) throws IOException {\n String filePath = toFilePath(locationUri);\n File folder = new File(filePath);\n if (!folder.isDirectory()) {\n LOGGER.debug(\"Skipping path as it is not a directory: \" + filePath);\n return new TreeSet<>();\n }\n\n String classPathRootOnDisk = filePath.substring(0, filePath.length() - location.length());\n if (!classPathRootOnDisk.endsWith(File.separator)) {\n classPathRootOnDisk = classPathRootOnDisk + File.separator;\n }\n LOGGER.debug(\"Scanning starting at classpath root in filesystem: \" + classPathRootOnDisk);\n return findResourceNamesFromFileSystem(classPathRootOnDisk, location, folder);\n }", "public Map<DeckReference, AlbumArt> getLoadedArt() {\n ensureRunning();\n // Make a copy so callers get an immutable snapshot of the current state.\n return Collections.unmodifiableMap(new HashMap<DeckReference, AlbumArt>(hotCache));\n }", "public static Field read(DataInputStream is) throws IOException {\n final byte tag = is.readByte();\n final Field result;\n switch (tag) {\n case 0x0f:\n case 0x10:\n case 0x11:\n result = new NumberField(tag, is);\n break;\n\n case 0x14:\n result = new BinaryField(is);\n break;\n\n case 0x26:\n result = new StringField(is);\n break;\n\n default:\n throw new IOException(\"Unable to read a field with type tag \" + tag);\n }\n\n logger.debug(\"..received> {}\", result);\n return result;\n }", "public <T> void setState(HttpConnectionInterceptor interceptor, String stateName, T\n stateObjectToStore) {\n Map<String, Object> state = interceptorStates.get(interceptor);\n if (state == null) {\n interceptorStates.put(interceptor, (state = new ConcurrentHashMap<String, Object>()));\n }\n state.put(stateName, stateObjectToStore);\n }", "public static String join(Collection<String> s, String delimiter) {\r\n return join(s, delimiter, false);\r\n }" ]
Load the layers based on the default setup. @param jbossHome the jboss home directory @param productConfig the product config @param repoRoots the repository roots @return the available layers @throws IOException
[ "public static InstalledIdentity load(final File jbossHome, final ProductConfig productConfig, final File... repoRoots) throws IOException {\n final InstalledImage installedImage = installedImage(jbossHome);\n return load(installedImage, productConfig, Arrays.<File>asList(repoRoots), Collections.<File>emptyList());\n }" ]
[ "public boolean setCurrentPage(final int page) {\n Log.d(TAG, \"setPageId pageId = %d\", page);\n return (page >= 0 && page < getCheckableCount()) && check(page);\n }", "public synchronized Object removeRoleMapping(final String roleName) {\n /*\n * Would not expect this to happen during boot so don't offer the 'immediate' optimisation.\n */\n HashMap<String, RoleMappingImpl> newRoles = new HashMap<String, RoleMappingImpl>(roleMappings);\n if (newRoles.containsKey(roleName)) {\n RoleMappingImpl removed = newRoles.remove(roleName);\n Object removalKey = new Object();\n removedRoles.put(removalKey, removed);\n roleMappings = Collections.unmodifiableMap(newRoles);\n\n return removalKey;\n }\n\n return null;\n }", "private static QName convertString(String str) {\n if (str != null) {\n return QName.valueOf(str);\n } else {\n return null;\n }\n }", "public static int[] binaryToRgb(boolean[] binaryArray) {\n int[] rgbArray = new int[binaryArray.length];\n\n for (int i = 0; i < binaryArray.length; i++) {\n if (binaryArray[i]) {\n rgbArray[i] = 0x00000000;\n } else {\n rgbArray[i] = 0x00FFFFFF;\n }\n }\n return rgbArray;\n }", "public String printHelp(String commandName) {\n int maxLength = 0;\n int width = 80;\n List<ProcessedOption> opts = getOptions();\n for (ProcessedOption o : opts) {\n if(o.getFormattedLength() > maxLength)\n maxLength = o.getFormattedLength();\n }\n\n StringBuilder sb = new StringBuilder();\n //first line\n sb.append(\"Usage: \");\n if(commandName == null || commandName.length() == 0)\n sb.append(name());\n else\n sb.append(commandName);\n if(opts.size() > 0)\n sb.append(\" [<options>]\");\n\n if(argument != null) {\n if(argument.isTypeAssignableByResourcesOrFile())\n sb.append(\" <file>\");\n else\n sb.append(\" <\").append(argument.getFieldName()).append(\">\");\n }\n\n if(arguments != null) {\n if(arguments.isTypeAssignableByResourcesOrFile())\n sb.append(\" [<files>]\");\n else\n sb.append(\" [<\").append(arguments.getFieldName()).append(\">]\");\n }\n sb.append(Config.getLineSeparator());\n //second line\n sb.append(description()).append(Config.getLineSeparator());\n\n //options and arguments\n if (opts.size() > 0)\n sb.append(Config.getLineSeparator()).append(\"Options:\").append(Config.getLineSeparator());\n for (ProcessedOption o : opts)\n sb.append(o.getFormattedOption(2, maxLength+4, width)).append(Config.getLineSeparator());\n if(arguments != null) {\n sb.append(Config.getLineSeparator()).append(\"Arguments:\").append(Config.getLineSeparator());\n sb.append(arguments.getFormattedOption(2, maxLength+4, width)).append(Config.getLineSeparator());\n }\n if(argument != null) {\n sb.append(Config.getLineSeparator()).append(\"Argument:\").append(Config.getLineSeparator());\n sb.append(argument.getFormattedOption(2, maxLength+4, width)).append(Config.getLineSeparator());\n }\n return sb.toString();\n }", "PatchEntry getEntry(final String name, boolean addOn) {\n return addOn ? addOns.get(name) : layers.get(name);\n }", "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 }", "public ItemRequest<Project> createInTeam(String team) {\n \n String path = String.format(\"/teams/%s/projects\", team);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\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 }" ]
Retuns the Windows UNC style path with backslashs intead of forward slashes. @return The UNC path.
[ "public String getUncPath() {\n getUncPath0();\n if( share == null ) {\n return \"\\\\\\\\\" + url.getHost();\n }\n return \"\\\\\\\\\" + url.getHost() + canon.replace( '/', '\\\\' );\n }" ]
[ "public static boolean zipFolder(File folder, String fileName){\n\t\tboolean success = false;\n\t\tif(!folder.isDirectory()){\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tif(fileName == null){\n\t\t\tfileName = folder.getAbsolutePath()+ZIP_EXT;\n\t\t}\n\t\t\n\t\tZipArchiveOutputStream zipOutput = null;\n\t\ttry {\n\t\t\tzipOutput = new ZipArchiveOutputStream(new File(fileName));\n\t\t\t\n\t\t\tsuccess = addFolderContentToZip(folder,zipOutput,\"\");\n\n\t\t\tzipOutput.close();\n\t\t\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t\treturn false;\n\t\t}\n\t\tfinally{\n\t\t\ttry {\n\t\t\t\tif(zipOutput != null){\n\t\t\t\t\tzipOutput.close();\n\t\t\t\t}\n\t\t\t} catch (IOException e) {}\n\t\t}\n\t\treturn success;\n\t}", "private boolean hidden(ProgramElementDoc c) {\n\tif (c.tags(\"hidden\").length > 0 || c.tags(\"view\").length > 0)\n\t return true;\n\tOptions opt = optionProvider.getOptionsFor(c instanceof ClassDoc ? (ClassDoc) c : c.containingClass());\n\treturn opt.matchesHideExpression(c.toString()) //\n\t\t|| (opt.hidePrivateInner && c instanceof ClassDoc && c.isPrivate() && ((ClassDoc) c).containingClass() != null);\n }", "protected boolean isReserved( String name ) {\n if( functions.isFunctionName(name))\n return true;\n\n for (int i = 0; i < name.length(); i++) {\n if( !isLetter(name.charAt(i)) )\n return true;\n }\n return false;\n }", "private PreparedStatement prepareBatchStatement(String sql)\r\n {\r\n String sqlCmd = sql.substring(0, 7);\r\n\r\n if (sqlCmd.equals(\"UPDATE \") || sqlCmd.equals(\"DELETE \") || (_useBatchInserts && sqlCmd.equals(\"INSERT \")))\r\n {\r\n PreparedStatement stmt = (PreparedStatement) _statements.get(sql);\r\n if (stmt == null)\r\n {\r\n // [olegnitz] for JDK 1.2 we need to list both PreparedStatement and Statement\r\n // interfaces, otherwise proxy.jar works incorrectly\r\n stmt = (PreparedStatement) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{\r\n PreparedStatement.class, Statement.class, BatchPreparedStatement.class},\r\n new PreparedStatementInvocationHandler(this, sql, m_jcd));\r\n _statements.put(sql, stmt);\r\n }\r\n return stmt;\r\n }\r\n else\r\n {\r\n return null;\r\n }\r\n }", "public String getShortMessage(Locale locale) {\n\t\tString message;\n\t\tmessage = translate(Integer.toString(exceptionCode), locale);\n\t\tif (message != null && msgParameters != null && msgParameters.length > 0) {\n\t\t\tfor (int i = 0; i < msgParameters.length; i++) {\n\t\t\t\tboolean isIncluded = false;\n\t\t\t\tString needTranslationParam = \"$${\" + i + \"}\";\n\t\t\t\tif (message.contains(needTranslationParam)) {\n\t\t\t\t\tString translation = translate(msgParameters[i], locale);\n\t\t\t\t\tif (null == translation && null != msgParameters[i]) {\n\t\t\t\t\t\ttranslation = msgParameters[i].toString();\n\t\t\t\t\t}\n\t\t\t\t\tif (null == translation) {\n\t\t\t\t\t\ttranslation = \"[null]\";\n\t\t\t\t\t}\n\t\t\t\t\tmessage = message.replace(needTranslationParam, translation);\n\t\t\t\t\tisIncluded = true;\n\t\t\t\t}\n\t\t\t\tString verbatimParam = \"${\" + i + \"}\";\n\t\t\t\tString rs = null == msgParameters[i] ? \"[null]\" : msgParameters[i].toString();\n\t\t\t\tif (message.contains(verbatimParam)) {\n\t\t\t\t\tmessage = message.replace(verbatimParam, rs);\n\t\t\t\t\tisIncluded = true;\n\t\t\t\t}\n\t\t\t\tif (!isIncluded) {\n\t\t\t\t\tmessage = message + \" (\" + rs + \")\"; // NOSONAR replace/contains makes StringBuilder use difficult\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn message;\n\t}", "protected BoxWatermark applyWatermark(URLTemplate itemUrl, String imprint) {\n URL watermarkUrl = itemUrl.build(this.getAPI().getBaseURL(), this.getID());\n URL url = WATERMARK_URL_TEMPLATE.build(watermarkUrl.toString());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"PUT\");\n JsonObject body = new JsonObject()\n .add(BoxWatermark.WATERMARK_JSON_KEY, new JsonObject()\n .add(BoxWatermark.WATERMARK_IMPRINT_JSON_KEY, imprint));\n request.setBody(body.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n return new BoxWatermark(response.getJSON());\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 void checkId(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 id = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_ID);\r\n\r\n if ((id != null) && (id.length() > 0))\r\n {\r\n try\r\n {\r\n Integer.parseInt(id);\r\n }\r\n catch (NumberFormatException ex)\r\n {\r\n throw new ConstraintException(\"The id attribute of field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" is not a valid number\");\r\n }\r\n }\r\n }", "private void stopDone() {\n synchronized (stopLock) {\n final StopContext stopContext = this.stopContext;\n this.stopContext = null;\n if (stopContext != null) {\n stopContext.complete();\n }\n stopLock.notifyAll();\n }\n }" ]
Unlocks a file.
[ "public void unlock() {\n String queryString = new QueryStringBuilder().appendParam(\"fields\", \"lock\").toString();\n URL url = FILE_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"PUT\");\n\n JsonObject lockObject = new JsonObject();\n lockObject.add(\"lock\", JsonObject.NULL);\n\n request.setBody(lockObject.toString());\n request.send();\n }" ]
[ "public static base_response unset(nitro_service client, snmpmanager resource, String[] args) throws Exception{\n\t\tsnmpmanager unsetresource = new snmpmanager();\n\t\tunsetresource.ipaddress = resource.ipaddress;\n\t\tunsetresource.netmask = resource.netmask;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "private void attributes(Options opt, FieldDoc fd[]) {\n\tfor (FieldDoc f : fd) {\n\t if (hidden(f))\n\t\tcontinue;\n\t stereotype(opt, f, Align.LEFT);\n\t String att = visibility(opt, f) + f.name();\n\t if (opt.showType)\n\t\tatt += typeAnnotation(opt, f.type());\n\t tableLine(Align.LEFT, att);\n\t tagvalue(opt, f);\n\t}\n }", "public List<String> deviceTypes() {\n Integer count = json().size(DEVICE_FAMILIES);\n List<String> deviceTypes = new ArrayList<String>(count);\n for(int i = 0 ; i < count ; i++) {\n String familyNumber = json().stringValue(DEVICE_FAMILIES, i);\n if(familyNumber.equals(\"1\")) deviceTypes.add(\"iPhone\");\n if(familyNumber.equals(\"2\")) deviceTypes.add(\"iPad\");\n }\n return deviceTypes;\n }", "ValidationResult cleanMultiValuePropertyKey(String name) {\n ValidationResult vr = cleanObjectKey(name);\n\n name = (String) vr.getObject();\n\n // make sure its not a known property key (reserved in the case of multi-value)\n\n try {\n RestrictedMultiValueFields rf = RestrictedMultiValueFields.valueOf(name);\n //noinspection ConstantConditions\n if (rf != null) {\n vr.setErrorDesc(name + \"... is a restricted key for multi-value properties. Operation aborted.\");\n vr.setErrorCode(523);\n vr.setObject(null);\n }\n } catch (Throwable t) {\n //no-op\n }\n\n return vr;\n }", "private void processBaseFonts(byte[] data)\n {\n int offset = 0;\n\n int blockCount = MPPUtility.getShort(data, 0);\n offset += 2;\n\n int size;\n String name;\n\n for (int loop = 0; loop < blockCount; loop++)\n {\n /*unknownAttribute = MPPUtility.getShort(data, offset);*/\n offset += 2;\n\n size = MPPUtility.getShort(data, offset);\n offset += 2;\n\n name = MPPUtility.getUnicodeString(data, offset);\n offset += 64;\n\n if (name.length() != 0)\n {\n FontBase fontBase = new FontBase(Integer.valueOf(loop), name, size);\n m_fontBases.put(fontBase.getIndex(), fontBase);\n }\n }\n }", "@Override\n public void destroy(SocketDestination dest, ClientRequestExecutor clientRequestExecutor)\n throws Exception {\n clientRequestExecutor.close();\n int numDestroyed = destroyed.incrementAndGet();\n if(stats != null) {\n stats.incrementCount(dest, ClientSocketStats.Tracked.CONNECTION_DESTROYED_EVENT);\n }\n\n if(logger.isDebugEnabled())\n logger.debug(\"Destroyed socket \" + numDestroyed + \" connection to \" + dest.getHost()\n + \":\" + dest.getPort());\n }", "String escapeValue(Object value) {\n return HtmlUtils.htmlEscape(value != null ? value.toString() : \"<null>\");\n }", "public static URI setQueryParams(final URI initialUri, final Multimap<String, String> queryParams) {\n StringBuilder queryString = new StringBuilder();\n for (Map.Entry<String, String> entry: queryParams.entries()) {\n if (queryString.length() > 0) {\n queryString.append(\"&\");\n }\n queryString.append(entry.getKey()).append(\"=\").append(entry.getValue());\n }\n try {\n if (initialUri.getHost() == null && initialUri.getAuthority() != null) {\n return new URI(initialUri.getScheme(), initialUri.getAuthority(), initialUri.getPath(),\n queryString.toString(),\n initialUri.getFragment());\n } else {\n return new URI(initialUri.getScheme(), initialUri.getUserInfo(), initialUri.getHost(),\n initialUri.getPort(),\n initialUri.getPath(),\n queryString.toString(), initialUri.getFragment());\n }\n } catch (URISyntaxException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }", "private List<Entity> runQuery(Query query) throws DatastoreException {\n RunQueryRequest.Builder request = RunQueryRequest.newBuilder();\n request.setQuery(query);\n RunQueryResponse response = datastore.runQuery(request.build());\n\n if (response.getBatch().getMoreResults() == QueryResultBatch.MoreResultsType.NOT_FINISHED) {\n System.err.println(\"WARNING: partial results\\n\");\n }\n List<EntityResult> results = response.getBatch().getEntityResultsList();\n List<Entity> entities = new ArrayList<Entity>(results.size());\n for (EntityResult result : results) {\n entities.add(result.getEntity());\n }\n return entities;\n }" ]
Create new logging action This method check if there is an old instance for this thread-local If not - Initialize new instance and set it as this thread-local's instance @param logger @param auditor @param instance @return whether new instance was set to thread-local
[ "protected static boolean createLoggingAction(final Logger logger, final Logger auditor, final TransactionLogger instance) {\n TransactionLogger oldInstance = getInstance();\n if (oldInstance == null || oldInstance.finished) {\n if(loggingKeys == null) {\n synchronized (TransactionLogger.class) {\n if (loggingKeys == null) {\n logger.info(\"Initializing 'LoggingKeysHandler' class\");\n loggingKeys = new LoggingKeysHandler(keysPropStream);\n }\n }\n }\n initInstance(instance, logger, auditor);\n setInstance(instance);\n return true;\n }\n return false; // Really not sure it can happen - since we arrive here in a new thread of transaction I think it's ThreadLocal should be empty. But leaving this code just in case...\n }" ]
[ "public static final Duration parseDurationInThousanthsOfMinutes(ProjectProperties properties, Number value, TimeUnit targetTimeUnit)\n {\n return parseDurationInFractionsOfMinutes(properties, value, targetTimeUnit, 1000);\n }", "public Response updateTemplate(String id, Map<String, Object> options)\n throws RequestException, LocalOperationException {\n Request request = new Request(this);\n return new Response(request.put(\"/templates/\" + id, options));\n }", "public static Map<FieldType, String> getDefaultResourceFieldMap()\n {\n Map<FieldType, String> map = new LinkedHashMap<FieldType, String>();\n\n map.put(ResourceField.UNIQUE_ID, \"rsrc_id\");\n map.put(ResourceField.GUID, \"guid\");\n map.put(ResourceField.NAME, \"rsrc_name\");\n map.put(ResourceField.CODE, \"employee_code\");\n map.put(ResourceField.EMAIL_ADDRESS, \"email_addr\");\n map.put(ResourceField.NOTES, \"rsrc_notes\");\n map.put(ResourceField.CREATED, \"create_date\");\n map.put(ResourceField.TYPE, \"rsrc_type\");\n map.put(ResourceField.INITIALS, \"rsrc_short_name\");\n map.put(ResourceField.PARENT_ID, \"parent_rsrc_id\");\n\n return map;\n }", "public void setShortVec(CharBuffer data)\n {\n if (data == null)\n {\n throw new IllegalArgumentException(\"Input data for indices cannot be null\");\n }\n if (getIndexSize() != 2)\n {\n throw new UnsupportedOperationException(\"Cannot update integer indices with char array\");\n }\n if (data.isDirect())\n {\n if (!NativeIndexBuffer.setShortVec(getNative(), data))\n {\n throw new UnsupportedOperationException(\"Input buffer is wrong size\");\n }\n }\n else if (data.hasArray())\n {\n if (!NativeIndexBuffer.setShortArray(getNative(), data.array()))\n {\n throw new UnsupportedOperationException(\"Input buffer is wrong size\");\n }\n }\n else\n {\n throw new UnsupportedOperationException(\n \"CharBuffer type not supported. Must be direct or have backing array\");\n }\n }", "public void setInRGB(IntRange inRGB) {\r\n this.inRed = inRGB;\r\n this.inGreen = inRGB;\r\n this.inBlue = inRGB;\r\n\r\n CalculateMap(inRGB, outRed, mapRed);\r\n CalculateMap(inRGB, outGreen, mapGreen);\r\n CalculateMap(inRGB, outBlue, mapBlue);\r\n }", "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 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 void addModuleToExport(final String moduleName) {\n\n if (m_modulesToExport == null) {\n m_modulesToExport = new HashSet<String>();\n }\n m_modulesToExport.add(moduleName);\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 }" ]
Deletes a redirect by id @param id redirect ID
[ "public void deleteRedirect(int id) {\n try {\n sqlService.executeUpdate(\"DELETE FROM \" + Constants.DB_TABLE_SERVERS +\n \" WHERE \" + Constants.GENERIC_ID + \" = \" + id + \";\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n }" ]
[ "public void setOfflineState(boolean setToOffline) {\n // acquire write lock\n writeLock.lock();\n try {\n String currentState = ByteUtils.getString(get(SERVER_STATE_KEY, null).get(0).getValue(),\n \"UTF-8\");\n if(setToOffline) {\n // from NORMAL_SERVER to OFFLINE_SERVER\n if(currentState.equals(VoldemortState.NORMAL_SERVER.toString())) {\n put(SERVER_STATE_KEY, VoldemortState.OFFLINE_SERVER);\n initCache(SERVER_STATE_KEY);\n put(SLOP_STREAMING_ENABLED_KEY, false);\n initCache(SLOP_STREAMING_ENABLED_KEY);\n put(PARTITION_STREAMING_ENABLED_KEY, false);\n initCache(PARTITION_STREAMING_ENABLED_KEY);\n put(READONLY_FETCH_ENABLED_KEY, false);\n initCache(READONLY_FETCH_ENABLED_KEY);\n } else if(currentState.equals(VoldemortState.OFFLINE_SERVER.toString())) {\n logger.warn(\"Already in OFFLINE_SERVER state.\");\n return;\n } else {\n logger.error(\"Cannot enter OFFLINE_SERVER state from \" + currentState);\n throw new VoldemortException(\"Cannot enter OFFLINE_SERVER state from \"\n + currentState);\n }\n } else {\n // from OFFLINE_SERVER to NORMAL_SERVER\n if(currentState.equals(VoldemortState.NORMAL_SERVER.toString())) {\n logger.warn(\"Already in NORMAL_SERVER state.\");\n return;\n } else if(currentState.equals(VoldemortState.OFFLINE_SERVER.toString())) {\n put(SERVER_STATE_KEY, VoldemortState.NORMAL_SERVER);\n initCache(SERVER_STATE_KEY);\n put(SLOP_STREAMING_ENABLED_KEY, true);\n initCache(SLOP_STREAMING_ENABLED_KEY);\n put(PARTITION_STREAMING_ENABLED_KEY, true);\n initCache(PARTITION_STREAMING_ENABLED_KEY);\n put(READONLY_FETCH_ENABLED_KEY, true);\n initCache(READONLY_FETCH_ENABLED_KEY);\n init();\n initNodeId(getNodeIdNoLock());\n } else {\n logger.error(\"Cannot enter NORMAL_SERVER state from \" + currentState);\n throw new VoldemortException(\"Cannot enter NORMAL_SERVER state from \"\n + currentState);\n }\n }\n } finally {\n writeLock.unlock();\n }\n }", "public static <InnerT> Observable<InnerT> convertListToInnerAsync(Observable<List<InnerT>> innerList) {\n return innerList.flatMap(new Func1<List<InnerT>, Observable<InnerT>>() {\n @Override\n public Observable<InnerT> call(List<InnerT> inners) {\n return Observable.from(inners);\n }\n });\n }", "public static clusternodegroup get(nitro_service service, String name) throws Exception{\n\t\tclusternodegroup obj = new clusternodegroup();\n\t\tobj.set_name(name);\n\t\tclusternodegroup response = (clusternodegroup) obj.get_resource(service);\n\t\treturn response;\n\t}", "public void detect(final String... packageNames) throws IOException {\n final String[] pkgNameFilter = new String[packageNames.length];\n for (int i = 0; i < pkgNameFilter.length; ++i) {\n pkgNameFilter[i] = packageNames[i].replace('.', '/');\n if (!pkgNameFilter[i].endsWith(\"/\")) {\n pkgNameFilter[i] = pkgNameFilter[i].concat(\"/\");\n }\n }\n final Set<File> files = new HashSet<>();\n final ClassLoader loader = Thread.currentThread().getContextClassLoader();\n for (final String packageName : pkgNameFilter) {\n final Enumeration<URL> resourceEnum = loader.getResources(packageName);\n while (resourceEnum.hasMoreElements()) {\n final URL url = resourceEnum.nextElement();\n if (\"file\".equals(url.getProtocol())) {\n final File dir = toFile(url);\n if (dir.isDirectory()) {\n files.add(dir);\n } else {\n throw new AssertionError(\"Not a recognized file URL: \" + url);\n }\n } else {\n final File jarFile = toFile(openJarURLConnection(url).getJarFileURL());\n if (jarFile.isFile()) {\n files.add(jarFile);\n } else {\n throw new AssertionError(\"Not a File: \" + jarFile);\n }\n }\n }\n }\n if (DEBUG) {\n print(\"Files to scan: %s\", files);\n }\n if (!files.isEmpty()) {\n // see http://shipilev.net/blog/2016/arrays-wisdom-ancients/#_conclusion\n detect(new ClassFileIterator(files.toArray(new File[0]), pkgNameFilter));\n }\n }", "private void setPlaybackPosition(long milliseconds) {\n PlaybackState oldState = currentSimpleState();\n if (oldState != null && oldState.position != milliseconds) {\n setPlaybackState(oldState.player, milliseconds, oldState.playing);\n }\n }", "protected void validateResultsDirectories() {\n for (String result : results) {\n if (Files.notExists(Paths.get(result))) {\n throw new AllureCommandException(String.format(\"Report directory <%s> not found.\", result));\n }\n }\n }", "public StochasticPathwiseLevenbergMarquardt getCloneWithModifiedTargetValues(List<RandomVariable> newTargetVaues, List<RandomVariable> newWeights, boolean isUseBestParametersAsInitialParameters) throws CloneNotSupportedException {\n\t\tStochasticPathwiseLevenbergMarquardt clonedOptimizer = clone();\n\t\tclonedOptimizer.targetValues = numberListToDoubleArray(newTargetVaues);\n\t\tclonedOptimizer.weights = numberListToDoubleArray(newWeights);\n\n\t\tif(isUseBestParametersAsInitialParameters && this.done()) {\n\t\t\tclonedOptimizer.initialParameters = this.getBestFitParameters();\n\t\t}\n\n\t\treturn clonedOptimizer;\n\t}", "private void writeAssignments()\n {\n Allocations allocations = m_factory.createAllocations();\n m_plannerProject.setAllocations(allocations);\n\n List<Allocation> allocationList = allocations.getAllocation();\n for (ResourceAssignment mpxjAssignment : m_projectFile.getResourceAssignments())\n {\n Allocation plannerAllocation = m_factory.createAllocation();\n allocationList.add(plannerAllocation);\n\n plannerAllocation.setTaskId(getIntegerString(mpxjAssignment.getTask().getUniqueID()));\n plannerAllocation.setResourceId(getIntegerString(mpxjAssignment.getResourceUniqueID()));\n plannerAllocation.setUnits(getIntegerString(mpxjAssignment.getUnits()));\n\n m_eventManager.fireAssignmentWrittenEvent(mpxjAssignment);\n }\n }", "private void processWorkWeeks(byte[] data, int offset, ProjectCalendar cal)\n {\n // System.out.println(\"Calendar=\" + cal.getName());\n // System.out.println(\"Work week block start offset=\" + offset);\n // System.out.println(ByteArrayHelper.hexdump(data, true, 16, \"\"));\n\n // skip 4 byte header\n offset += 4;\n\n while (data.length >= offset + ((7 * 60) + 2 + 2 + 8 + 4))\n {\n //System.out.println(\"Week start offset=\" + offset);\n ProjectCalendarWeek week = cal.addWorkWeek();\n for (Day day : Day.values())\n {\n // 60 byte block per day\n processWorkWeekDay(data, offset, week, day);\n offset += 60;\n }\n\n Date startDate = DateHelper.getDayStartDate(MPPUtility.getDate(data, offset));\n offset += 2;\n\n Date finishDate = DateHelper.getDayEndDate(MPPUtility.getDate(data, offset));\n offset += 2;\n\n // skip unknown 8 bytes\n //System.out.println(ByteArrayHelper.hexdump(data, offset, 8, false));\n offset += 8;\n\n //\n // Extract the name length - ensure that it is aligned to a 4 byte boundary\n //\n int nameLength = MPPUtility.getInt(data, offset);\n if (nameLength % 4 != 0)\n {\n nameLength = ((nameLength / 4) + 1) * 4;\n }\n offset += 4;\n\n if (nameLength != 0)\n {\n String name = MPPUtility.getUnicodeString(data, offset, nameLength);\n offset += nameLength;\n week.setName(name);\n }\n\n week.setDateRange(new DateRange(startDate, finishDate));\n // System.out.println(week);\n }\n }" ]
Use this API to fetch appflowpolicy_appflowpolicylabel_binding resources of given name .
[ "public static appflowpolicy_appflowpolicylabel_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappflowpolicy_appflowpolicylabel_binding obj = new appflowpolicy_appflowpolicylabel_binding();\n\t\tobj.set_name(name);\n\t\tappflowpolicy_appflowpolicylabel_binding response[] = (appflowpolicy_appflowpolicylabel_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "private void readAssignments(Resource mpxjResource, net.sf.mpxj.phoenix.schema.Project.Storepoints.Storepoint.Resources.Resource res)\n {\n for (Assignment assignment : res.getAssignment())\n {\n readAssignment(mpxjResource, assignment);\n }\n }", "public ItemRequest<Tag> delete(String tag) {\n \n String path = String.format(\"/tags/%s\", tag);\n return new ItemRequest<Tag>(this, Tag.class, path, \"DELETE\");\n }", "public static String getOffsetCodeFromSchedule(Schedule schedule) {\r\n\r\n\t\tdouble doubleLength = 0;\r\n\t\tfor(int i = 0; i < schedule.getNumberOfPeriods(); i ++) {\r\n\t\t\tdoubleLength += schedule.getPeriodLength(i);\r\n\t\t}\r\n\t\tdoubleLength /= schedule.getNumberOfPeriods();\r\n\r\n\t\tdoubleLength *= 12;\r\n\t\tint periodLength = (int) Math.round(doubleLength);\r\n\r\n\r\n\t\tString offsetCode = periodLength + \"M\";\r\n\t\treturn offsetCode;\r\n\t}", "protected AbstractColumn buildSimpleBarcodeColumn() {\n\t\tBarCodeColumn column = new BarCodeColumn();\n\t\tpopulateCommonAttributes(column);\n\t\tcolumn.setColumnProperty(columnProperty);\n\t\tcolumn.setExpressionToGroupBy(customExpressionToGroupBy);\n\t\tcolumn.setScaleMode(imageScaleMode);\n\t\tcolumn.setApplicationIdentifier(applicationIdentifier);\n\t\tcolumn.setBarcodeType(barcodeType);\n\t\tcolumn.setShowText(showText);\n\t\tcolumn.setCheckSum(checkSum);\n\t\treturn column;\n\t}", "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 }", "synchronized void removeEvents(Table table) {\n final String tName = table.getName();\n\n try {\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n db.delete(tName, null, null);\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Error removing all events from table \" + tName + \" Recreating DB\");\n deleteDB();\n } finally {\n dbHelper.close();\n }\n }", "public InputStream sendRequest(String requestMethod,\n\t\t\tMap<String, String> parameters) throws IOException {\n\t\tString queryString = getQueryString(parameters);\n\t\tURL url = new URL(this.apiBaseUrl);\n\t\tHttpURLConnection connection = (HttpURLConnection) WebResourceFetcherImpl\n\t\t\t\t.getUrlConnection(url);\n\n\t\tsetupConnection(requestMethod, queryString, connection);\n\t\tOutputStreamWriter writer = new OutputStreamWriter(\n\t\t\t\tconnection.getOutputStream());\n\t\twriter.write(queryString);\n\t\twriter.flush();\n\t\twriter.close();\n\n\t\tint rc = connection.getResponseCode();\n\t\tif (rc != 200) {\n\t\t\tlogger.warn(\"Error: API request returned response code \" + rc);\n\t\t}\n\n\t\tInputStream iStream = connection.getInputStream();\n\t\tfillCookies(connection.getHeaderFields());\n\t\treturn iStream;\n\t}", "private void removeListener(CmsUUID listenerId) {\n\n getRequest().getSession().removeAttribute(SESSION_ATTRIBUTE_LISTENER_ID);\n m_listeners.remove(listenerId);\n }", "public List<LogSegment> trunc(int newStart) {\n if (newStart < 0) {\n throw new IllegalArgumentException(\"Starting index must be positive.\");\n }\n while (true) {\n List<LogSegment> curr = contents.get();\n int newLength = Math.max(curr.size() - newStart, 0);\n List<LogSegment> updatedList = new ArrayList<LogSegment>(curr.subList(Math.min(newStart, curr.size() - 1),\n curr.size()));\n if (contents.compareAndSet(curr, updatedList)) {\n return curr.subList(0, curr.size() - newLength);\n }\n }\n }" ]
Obtain collection of profiles @param model @return @throws Exception
[ "@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 }" ]
[ "private int read() {\n int curByte = 0;\n try {\n curByte = rawData.get() & 0xFF;\n } catch (Exception e) {\n header.status = GifDecoder.STATUS_FORMAT_ERROR;\n }\n return curByte;\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 }", "@Override\n public List<InstalledIdentity> getInstalledIdentities() throws PatchingException {\n\n List<InstalledIdentity> installedIdentities;\n\n final File metadataDir = installedImage.getInstallationMetadata();\n if(!metadataDir.exists()) {\n installedIdentities = Collections.singletonList(defaultIdentity);\n } else {\n final String defaultConf = defaultIdentity.getIdentity().getName() + Constants.DOT_CONF;\n final File[] identityConfs = metadataDir.listFiles(new FileFilter() {\n @Override\n public boolean accept(File pathname) {\n return pathname.isFile() &&\n pathname.getName().endsWith(Constants.DOT_CONF) &&\n !pathname.getName().equals(defaultConf);\n }\n });\n if(identityConfs == null || identityConfs.length == 0) {\n installedIdentities = Collections.singletonList(defaultIdentity);\n } else {\n installedIdentities = new ArrayList<InstalledIdentity>(identityConfs.length + 1);\n installedIdentities.add(defaultIdentity);\n for(File conf : identityConfs) {\n final Properties props = loadProductConf(conf);\n String productName = conf.getName();\n productName = productName.substring(0, productName.length() - Constants.DOT_CONF.length());\n final String productVersion = props.getProperty(Constants.CURRENT_VERSION);\n\n InstalledIdentity identity;\n try {\n identity = LayersFactory.load(installedImage, new ProductConfig(productName, productVersion, null), moduleRoots, bundleRoots);\n } catch (IOException e) {\n throw new PatchingException(PatchLogger.ROOT_LOGGER.failedToLoadInfo(productName), e);\n }\n installedIdentities.add(identity);\n }\n }\n }\n return installedIdentities;\n }", "private void processGeneratedProperties(\n\t\t\tSerializable id,\n\t\t\tObject entity,\n\t\t\tObject[] state,\n\t\t\tSharedSessionContractImplementor session,\n\t\t\tGenerationTiming matchTiming) {\n\n\t\tTuple tuple = getFreshTuple( EntityKeyBuilder.fromPersister( this, id, session ), session );\n\t\tsaveSharedTuple( entity, tuple, session );\n\n\t\tif ( tuple == null || tuple.getSnapshot().isEmpty() ) {\n\t\t\tthrow log.couldNotRetrieveEntityForRetrievalOfGeneratedProperties( getEntityName(), id );\n\t\t}\n\n\t\tint propertyIndex = -1;\n\t\tfor ( NonIdentifierAttribute attribute : getEntityMetamodel().getProperties() ) {\n\t\t\tpropertyIndex++;\n\t\t\tfinal ValueGeneration valueGeneration = attribute.getValueGenerationStrategy();\n\t\t\tif ( isReadRequired( valueGeneration, matchTiming ) ) {\n\t\t\t\tObject hydratedState = gridPropertyTypes[propertyIndex].hydrate( tuple, getPropertyAliases( \"\", propertyIndex ), session, entity );\n\t\t\t\tstate[propertyIndex] = gridPropertyTypes[propertyIndex].resolve( hydratedState, session, entity );\n\t\t\t\tsetPropertyValue( entity, propertyIndex, state[propertyIndex] );\n\t\t\t}\n\t\t}\n\t}", "public static Number parseDouble(String value) throws ParseException\n {\n\n Number result = null;\n value = parseString(value);\n\n // If we still have a value\n if (value != null && !value.isEmpty() && !value.equals(\"-1 -1\"))\n {\n int index = value.indexOf(\"E+\");\n if (index != -1)\n {\n value = value.substring(0, index) + 'E' + value.substring(index + 2, value.length());\n }\n\n if (value.indexOf('E') != -1)\n {\n result = DOUBLE_FORMAT.get().parse(value);\n }\n else\n {\n result = Double.valueOf(value);\n }\n }\n\n return result;\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 void setAmbientIntensity(float r, float g, float b, float a) {\n setVec4(\"ambient_intensity\", r, g, b, a);\n }", "private static void registerCommonClasses(Class<?>... commonClasses) {\n\t\tfor (Class<?> clazz : commonClasses) {\n\t\t\tcommonClassCache.put(clazz.getName(), clazz);\n\t\t}\n\t}", "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 }" ]
Returns iterable with all non-deleted file version legal holds for this legal hold policy. @param limit the limit of entries per response. The default value is 100. @param fields the fields to retrieve. @return an iterable containing file version legal holds info.
[ "public Iterable<BoxFileVersionLegalHold.Info> getFileVersionHolds(int limit, String ... fields) {\n QueryStringBuilder queryString = new QueryStringBuilder().appendParam(\"policy_id\", this.getID());\n if (fields.length > 0) {\n queryString.appendParam(\"fields\", fields);\n }\n URL url = LIST_OF_FILE_VERSION_HOLDS_URL_TEMPLATE.buildWithQuery(getAPI().getBaseURL(), queryString.toString());\n return new BoxResourceIterable<BoxFileVersionLegalHold.Info>(getAPI(), url, limit) {\n\n @Override\n protected BoxFileVersionLegalHold.Info factory(JsonObject jsonObject) {\n BoxFileVersionLegalHold assignment\n = new BoxFileVersionLegalHold(getAPI(), jsonObject.get(\"id\").asString());\n return assignment.new Info(jsonObject);\n }\n\n };\n }" ]
[ "public static int getHostSegmentIndex(int networkPrefixLength, int bytesPerSegment, int bitsPerSegment) {\n\t\tif(bytesPerSegment > 1) {\n\t\t\tif(bytesPerSegment == 2) {\n\t\t\t\treturn networkPrefixLength >> 4;\n\t\t\t}\n\t\t\treturn networkPrefixLength / bitsPerSegment;\n\t\t}\n\t\treturn networkPrefixLength >> 3;\n\t}", "public static final long getLong(byte[] data, int offset)\n {\n if (data.length != 8)\n {\n throw new UnexpectedStructureException();\n }\n\n long result = 0;\n int i = offset;\n for (int shiftBy = 0; shiftBy < 64; shiftBy += 8)\n {\n result |= ((long) (data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }", "public void setFrustum(Matrix4f projMatrix)\n {\n if (projMatrix != null)\n {\n if (mProjMatrix == null)\n {\n mProjMatrix = new float[16];\n }\n mProjMatrix = projMatrix.get(mProjMatrix, 0);\n mScene.setPickVisible(false);\n if (mCuller != null)\n {\n mCuller.set(projMatrix);\n }\n else\n {\n mCuller = new FrustumIntersection(projMatrix);\n }\n }\n mProjection = projMatrix;\n }", "protected static void printValuesSorted(String message, Set<String> values)\n {\n System.out.println();\n System.out.println(message + \":\");\n List<String> sorted = new ArrayList<>(values);\n Collections.sort(sorted);\n for (String value : sorted)\n {\n System.out.println(\"\\t\" + value);\n }\n }", "@PostConstruct\n public final void init() throws URISyntaxException {\n final String address = getConfig(ADDRESS, null);\n if (address != null) {\n final URI uri = new URI(\"udp://\" + address);\n final String prefix = getConfig(PREFIX, \"mapfish-print\").replace(\"%h\", getHostname());\n final int period = Integer.parseInt(getConfig(PERIOD, \"10\"));\n LOGGER.info(\"Starting a StatsD reporter targeting {} with prefix {} and period {}s\",\n uri, prefix, period);\n this.reporter = StatsDReporter.forRegistry(this.metricRegistry)\n .prefixedWith(prefix)\n .build(uri.getHost(), uri.getPort());\n this.reporter.start(period, TimeUnit.SECONDS);\n }\n }", "protected StrongCounter getCounterOrCreateIt(String counterName, int initialValue) {\n\t\tCounterManager counterManager = EmbeddedCounterManagerFactory.asCounterManager( cacheManager );\n\t\tif ( !counterManager.isDefined( counterName ) ) {\n\t\t\tLOG.tracef( \"Counter %s is not defined, creating it\", counterName );\n\n\t\t\t// global configuration is mandatory in order to define\n\t\t\t// a new clustered counter with persistent storage\n\t\t\tvalidateGlobalConfiguration();\n\n\t\t\tcounterManager.defineCounter( counterName,\n\t\t\t\tCounterConfiguration.builder(\n\t\t\t\t\tCounterType.UNBOUNDED_STRONG )\n\t\t\t\t\t\t.initialValue( initialValue )\n\t\t\t\t\t\t.storage( Storage.PERSISTENT )\n\t\t\t\t\t\t.build() );\n\t\t}\n\n\t\tStrongCounter strongCounter = counterManager.getStrongCounter( counterName );\n\t\treturn strongCounter;\n\t}", "public Object getProperty(Object object) {\n MetaMethod getter = getGetter();\n if (getter == null) {\n if (field != null) return field.getProperty(object);\n //TODO: create a WriteOnlyException class?\n throw new GroovyRuntimeException(\"Cannot read write-only property: \" + name);\n }\n return getter.invoke(object, MetaClassHelper.EMPTY_ARRAY);\n }", "public int getReplaceContextLength() {\n\t\tif (replaceContextLength == null) {\n\t\t\tint replacementOffset = getReplaceRegion().getOffset();\n\t\t\tITextRegion currentRegion = getCurrentNode().getTextRegion();\n\t\t\tint replaceContextLength = currentRegion.getLength() - (replacementOffset - currentRegion.getOffset());\n\t\t\tthis.replaceContextLength = replaceContextLength;\n\t\t\treturn replaceContextLength;\n\t\t}\n\t\treturn replaceContextLength.intValue();\n\t}", "public static authenticationldappolicy_vpnglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationldappolicy_vpnglobal_binding obj = new authenticationldappolicy_vpnglobal_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationldappolicy_vpnglobal_binding response[] = (authenticationldappolicy_vpnglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
Creates a MetaMatcher based on the filter content. @param filterAsString the String representation of the filter @param metaMatchers the Map of custom MetaMatchers @return A MetaMatcher used to match the filter content
[ "protected MetaMatcher createMetaMatcher(String filterAsString, Map<String, MetaMatcher> metaMatchers) {\n \tfor ( String key : metaMatchers.keySet() ){\n \t\tif ( filterAsString.startsWith(key)){\n \t\t\treturn metaMatchers.get(key);\n \t\t}\n \t}\n if (filterAsString.startsWith(GROOVY)) {\n return new GroovyMetaMatcher();\n }\n return new DefaultMetaMatcher();\n }" ]
[ "@Override public Integer getOffset(Integer id, Integer type)\n {\n Integer result = null;\n\n Map<Integer, Integer> map = m_table.get(id);\n if (map != null && type != null)\n {\n result = map.get(type);\n }\n\n return (result);\n }", "public static final String printExtendedAttributeDate(Date value)\n {\n return (value == null ? null : DATE_FORMAT.get().format(value));\n }", "@Override\n public Map<String, Set<String>> cleanObsoleteContent() {\n if(!readWrite) {\n return Collections.emptyMap();\n }\n Map<String, Set<String>> cleanedContents = new HashMap<>(2);\n cleanedContents.put(MARKED_CONTENT, new HashSet<>());\n cleanedContents.put(DELETED_CONTENT, new HashSet<>());\n synchronized (contentHashReferences) {\n for (ContentReference fsContent : listLocalContents()) {\n if (!readWrite) {\n return Collections.emptyMap();\n }\n if (!contentHashReferences.containsKey(fsContent.getHexHash())) { //We have no reference to this content\n if (markAsObsolete(fsContent)) {\n cleanedContents.get(DELETED_CONTENT).add(fsContent.getContentIdentifier());\n } else {\n cleanedContents.get(MARKED_CONTENT).add(fsContent.getContentIdentifier());\n }\n } else {\n obsoleteContents.remove(fsContent.getHexHash()); //Remove existing references from obsoleteContents\n }\n }\n }\n return cleanedContents;\n }", "private void readTaskExtendedAttributes(Project.Tasks.Task xml, Task mpx)\n {\n for (Project.Tasks.Task.ExtendedAttribute attrib : xml.getExtendedAttribute())\n {\n int xmlFieldID = Integer.parseInt(attrib.getFieldID()) & 0x0000FFFF;\n TaskField mpxFieldID = MPPTaskField.getInstance(xmlFieldID);\n TimeUnit durationFormat = DatatypeConverter.parseDurationTimeUnits(attrib.getDurationFormat(), null);\n DatatypeConverter.parseExtendedAttribute(m_projectFile, mpx, attrib.getValue(), mpxFieldID, durationFormat);\n }\n }", "private void readCalendars(Project project, HashMap<BigInteger, ProjectCalendar> map)\n {\n Project.Calendars calendars = project.getCalendars();\n if (calendars != null)\n {\n LinkedList<Pair<ProjectCalendar, BigInteger>> baseCalendars = new LinkedList<Pair<ProjectCalendar, BigInteger>>();\n for (Project.Calendars.Calendar cal : calendars.getCalendar())\n {\n readCalendar(cal, map, baseCalendars);\n }\n updateBaseCalendarNames(baseCalendars, map);\n }\n\n try\n {\n ProjectProperties properties = m_projectFile.getProjectProperties();\n BigInteger calendarID = new BigInteger(properties.getDefaultCalendarName());\n ProjectCalendar calendar = map.get(calendarID);\n m_projectFile.setDefaultCalendar(calendar);\n }\n\n catch (Exception ex)\n {\n // Ignore exceptions\n }\n }", "private static long getVersionId(String versionDir) {\n try {\n return Long.parseLong(versionDir.replace(\"version-\", \"\"));\n } catch(NumberFormatException e) {\n logger.trace(\"Cannot parse version directory to obtain id \" + versionDir);\n return -1;\n }\n }", "private void flushHotCacheSlot(SlotReference slot) {\n // Iterate over a copy to avoid concurrent modification issues\n for (Map.Entry<DeckReference, TrackMetadata> entry : new HashMap<DeckReference,TrackMetadata>(hotCache).entrySet()) {\n if (slot == SlotReference.getSlotReference(entry.getValue().trackReference)) {\n logger.debug(\"Evicting cached metadata in response to unmount report {}\", entry.getValue());\n hotCache.remove(entry.getKey());\n }\n }\n }", "public static base_response delete(nitro_service client, String acl6name) throws Exception {\n\t\tnsacl6 deleteresource = new nsacl6();\n\t\tdeleteresource.acl6name = acl6name;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public void appendImmediate(Object object, String indentation) {\n\t\tfor (int i = segments.size() - 1; i >= 0; i--) {\n\t\t\tString segment = segments.get(i);\n\t\t\tfor (int j = 0; j < segment.length(); j++) {\n\t\t\t\tif (!WhitespaceMatcher.isWhitespace(segment.charAt(j))) {\n\t\t\t\t\tappend(object, indentation, i + 1);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tappend(object, indentation, 0);\n\t}" ]
Return a named object associated with the specified key.
[ "Object lookup(String key) throws ObjectNameNotFoundException\r\n {\r\n Object result = null;\r\n NamedEntry entry = localLookup(key);\r\n // can't find local bound object\r\n if(entry == null)\r\n {\r\n try\r\n {\r\n PersistenceBroker broker = tx.getBroker();\r\n // build Identity to lookup entry\r\n Identity oid = broker.serviceIdentity().buildIdentity(NamedEntry.class, key);\r\n entry = (NamedEntry) broker.getObjectByIdentity(oid);\r\n }\r\n catch(Exception e)\r\n {\r\n log.error(\"Can't materialize bound object for key '\" + key + \"'\", e);\r\n }\r\n }\r\n if(entry == null)\r\n {\r\n log.info(\"No object found for key '\" + key + \"'\");\r\n }\r\n else\r\n {\r\n Object obj = entry.getObject();\r\n // found a persistent capable object associated with that key\r\n if(obj instanceof Identity)\r\n {\r\n Identity objectIdentity = (Identity) obj;\r\n result = tx.getBroker().getObjectByIdentity(objectIdentity);\r\n // lock the persistance capable object\r\n RuntimeObject rt = new RuntimeObject(result, objectIdentity, tx, false);\r\n tx.lockAndRegister(rt, Transaction.READ, tx.getRegistrationList());\r\n }\r\n else\r\n {\r\n // nothing else to do\r\n result = obj;\r\n }\r\n }\r\n if(result == null) throw new ObjectNameNotFoundException(\"Can't find named object for name '\" + key + \"'\");\r\n return result;\r\n }" ]
[ "public int compare(final Version other) throws IncomparableException{\n\t\t// Cannot compare branch versions and others \n\t\tif(!isBranch().equals(other.isBranch())){\n\t\t\tthrow new IncomparableException();\n\t\t}\n\t\t\n\t\t// Compare digits\n\t\tfinal int minDigitSize = getDigitsSize() < other.getDigitsSize()? getDigitsSize(): other.getDigitsSize();\n\t\t\n\t\tfor(int i = 0; i < minDigitSize ; i++){\n\t\t\tif(!getDigit(i).equals(other.getDigit(i))){\n\t\t\t\treturn getDigit(i).compareTo(other.getDigit(i));\n\t\t\t}\n\t\t}\n\t\t\n\t\t// If not the same number of digits and the first digits are equals, the longest is the newer\n\t\tif(!getDigitsSize().equals(other.getDigitsSize())){\n\t\t\treturn getDigitsSize() > other.getDigitsSize()? 1: -1;\n\t\t}\n\n if(isBranch() && !getBranchId().equals(other.getBranchId())){\n\t\t\treturn getBranchId().compareTo(other.getBranchId());\n\t\t}\n\t\t\n\t\t// if the digits are the same, a snapshot is newer than a release\n\t\tif(isSnapshot() && other.isRelease()){\n\t\t\treturn 1;\n\t\t}\n\t\t\n\t\tif(isRelease() && other.isSnapshot()){\n\t\t\treturn -1;\n\t\t}\n\t\t\n\t\t// if both versions are releases, compare the releaseID\n\t\tif(isRelease() && other.isRelease()){\n\t\t\treturn getReleaseId().compareTo(other.getReleaseId());\n\t\t}\n\t\t\n\t\treturn 0;\n\t}", "public static appfwprofile_safeobject_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_safeobject_binding obj = new appfwprofile_safeobject_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_safeobject_binding response[] = (appfwprofile_safeobject_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public Date getBaselineFinish()\n {\n Object result = getCachedValue(TaskField.BASELINE_FINISH);\n if (result == null)\n {\n result = getCachedValue(TaskField.BASELINE_ESTIMATED_FINISH);\n }\n\n if (!(result instanceof Date))\n {\n result = null;\n }\n return (Date) result;\n }", "private void readCalendar(Gantt gantt)\n {\n Gantt.Calendar ganttCalendar = gantt.getCalendar();\n m_projectFile.getProjectProperties().setWeekStartDay(ganttCalendar.getWeekStart());\n\n ProjectCalendar calendar = m_projectFile.addCalendar();\n calendar.setName(\"Standard\");\n m_projectFile.setDefaultCalendar(calendar);\n\n String workingDays = ganttCalendar.getWorkDays();\n calendar.setWorkingDay(Day.SUNDAY, workingDays.charAt(0) == '1');\n calendar.setWorkingDay(Day.MONDAY, workingDays.charAt(1) == '1');\n calendar.setWorkingDay(Day.TUESDAY, workingDays.charAt(2) == '1');\n calendar.setWorkingDay(Day.WEDNESDAY, workingDays.charAt(3) == '1');\n calendar.setWorkingDay(Day.THURSDAY, workingDays.charAt(4) == '1');\n calendar.setWorkingDay(Day.FRIDAY, workingDays.charAt(5) == '1');\n calendar.setWorkingDay(Day.SATURDAY, workingDays.charAt(6) == '1');\n\n for (int i = 1; i <= 7; i++)\n {\n Day day = Day.getInstance(i);\n ProjectCalendarHours hours = calendar.addCalendarHours(day);\n if (calendar.isWorkingDay(day))\n {\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING);\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON);\n }\n }\n\n for (Gantt.Holidays.Holiday holiday : gantt.getHolidays().getHoliday())\n {\n ProjectCalendarException exception = calendar.addCalendarException(holiday.getDate(), holiday.getDate());\n exception.setName(holiday.getContent());\n }\n }", "private boolean containsValue(StatementGroup statementGroup, Value value) {\n\t\tfor (Statement s : statementGroup) {\n\t\t\tif (value.equals(s.getValue())) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}", "public static base_responses unset(nitro_service client, onlinkipv6prefix resources[], String[] args) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tonlinkipv6prefix unsetresources[] = new onlinkipv6prefix[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tunsetresources[i] = new onlinkipv6prefix();\n\t\t\t\tunsetresources[i].ipv6prefix = resources[i].ipv6prefix;\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}", "public static int secondsDiff(Date earlierDate, Date laterDate) {\n if (earlierDate == null || laterDate == null) {\n return 0;\n }\n\n return (int) ((laterDate.getTime() / SECOND_MILLIS) - (earlierDate.getTime() / SECOND_MILLIS));\n }", "public void rollback()\r\n {\r\n try\r\n {\r\n Iterator iter = mvOrderOfIds.iterator();\r\n while(iter.hasNext())\r\n {\r\n ObjectEnvelope mod = (ObjectEnvelope) mhtObjectEnvelopes.get(iter.next());\r\n if(log.isDebugEnabled())\r\n log.debug(\"rollback: \" + mod);\r\n // if the Object has been modified by transaction, mark object as dirty\r\n if(mod.hasChanged(transaction.getBroker()))\r\n {\r\n mod.setModificationState(mod.getModificationState().markDirty());\r\n }\r\n mod.getModificationState().rollback(mod);\r\n }\r\n }\r\n finally\r\n {\r\n needsCommit = false;\r\n }\r\n afterWriteCleanup();\r\n }", "public Date getPreviousWorkFinish(Date date)\n {\n Calendar cal = Calendar.getInstance();\n cal.setTime(date);\n updateToPreviousWorkFinish(cal);\n return cal.getTime();\n }" ]
Copy bytes from an input stream to a file and log progress @param is the input stream to read @param destFile the file to write to @throws IOException if an I/O error occurs
[ "private void stream(InputStream is, File destFile) throws IOException {\n try {\n startProgress();\n OutputStream os = new FileOutputStream(destFile);\n \n boolean finished = false;\n try {\n byte[] buf = new byte[1024 * 10];\n int read;\n while ((read = is.read(buf)) >= 0) {\n os.write(buf, 0, read);\n processedBytes += read;\n logProgress();\n }\n \n os.flush();\n finished = true;\n } finally {\n os.close();\n if (!finished) {\n destFile.delete();\n }\n }\n } finally {\n is.close();\n completeProgress();\n }\n }" ]
[ "private void checkDuplicateStdOutOutput(DumpProcessingAction newAction) {\n\t\tif (newAction.useStdOut()) {\n\t\t\tif (this.quiet) {\n\t\t\t\tlogger.warn(\"Multiple actions are using stdout as output destination.\");\n\t\t\t}\n\t\t\tthis.quiet = true;\n\t\t}\n\t}", "private void readAssignments(Resource mpxjResource, net.sf.mpxj.phoenix.schema.Project.Storepoints.Storepoint.Resources.Resource res)\n {\n for (Assignment assignment : res.getAssignment())\n {\n readAssignment(mpxjResource, assignment);\n }\n }", "public static final Integer parseInteger(String value)\n {\n return (value == null || value.length() == 0 ? null : Integer.valueOf(Integer.parseInt(value)));\n }", "@Override\n public void prettyPrint(StringBuffer sb, int indent)\n {\n sb.append(Log.getSpaces(indent));\n sb.append(GVRBone.class.getSimpleName());\n sb.append(\" [name=\" + getName() + \", boneId=\" + getBoneId()\n + \", offsetMatrix=\" + getOffsetMatrix()\n + \", finalTransformMatrix=\" + getFinalTransformMatrix() // crashes debugger\n + \"]\");\n sb.append(System.lineSeparator());\n }", "public static void divideElementsCol(final int blockLength ,\n final DSubmatrixD1 Y , final int col , final double val ) {\n final int width = Math.min(blockLength,Y.col1-Y.col0);\n\n final double dataY[] = Y.original.data;\n\n for( int i = Y.row0; i < Y.row1; i += blockLength ) {\n int height = Math.min( blockLength , Y.row1 - i );\n\n int index = i*Y.original.numCols + height*Y.col0 + col;\n\n if( i == Y.row0 ) {\n index += width*(col+1);\n\n for( int k = col+1; k < height; k++ , index += width ) {\n dataY[index] /= val;\n }\n } else {\n int endIndex = index + width*height;\n //for( int k = 0; k < height; k++\n for( ; index != endIndex; index += width ) {\n dataY[index] /= val;\n }\n }\n }\n }", "@Override\n public void perform(Rewrite event, EvaluationContext context)\n {\n perform((GraphRewrite) event, context);\n }", "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 }", "@Deprecated\n public static TraceContextHolder wrap(TraceContext traceContext) {\n return (traceContext != null) ? new TraceContextHolder(traceContext) : TraceContextHolder.EMPTY;\n }", "private ProjectFile readTextFile(InputStream inputStream) throws MPXJException\n {\n ProjectReader reader = new AstaTextFileReader();\n addListeners(reader);\n return reader.read(inputStream);\n }" ]
The main method called from the command line. @param args the command line arguments
[ "public static void main(String[] args) {\n try {\n new StartMain(args).go();\n } catch(Throwable t) {\n WeldSELogger.LOG.error(\"Application exited with an exception\", t);\n System.exit(1);\n }\n }" ]
[ "private Map<String, Class<? extends RulePhase>> loadPhases()\n {\n Map<String, Class<? extends RulePhase>> phases;\n phases = new HashMap<>();\n Furnace furnace = FurnaceHolder.getFurnace();\n for (RulePhase phase : furnace.getAddonRegistry().getServices(RulePhase.class))\n {\n @SuppressWarnings(\"unchecked\")\n Class<? extends RulePhase> unwrappedClass = (Class<? extends RulePhase>) Proxies.unwrap(phase).getClass();\n String simpleName = unwrappedClass.getSimpleName();\n phases.put(classNameToMapKey(simpleName), unwrappedClass);\n }\n return Collections.unmodifiableMap(phases);\n }", "static String makeLayout(String descriptor, String blockName, boolean useUBO)\n {\n return NativeShaderManager.makeLayout(descriptor, blockName, useUBO);\n }", "public Response remove(String id) {\r\n assertNotEmpty(id, \"id\");\r\n id = ensureDesignPrefix(id);\r\n String revision = null;\r\n // Get the revision ID from ETag, removing leading and trailing \"\r\n revision = client.executeRequest(Http.HEAD(new DatabaseURIHelper(db.getDBUri()\r\n ).documentUri(id))).getConnection().getHeaderField(\"ETag\");\r\n if (revision != null) {\r\n revision = revision.substring(1, revision.length() - 1);\r\n return db.remove(id, revision);\r\n } else {\r\n throw new CouchDbException(\"No ETag header found for design document with id \" + id);\r\n }\r\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 }", "public String getEditedFilePath() {\n\n switch (getBundleType()) {\n case DESCRIPTOR:\n return m_cms.getSitePath(m_desc);\n case PROPERTY:\n return null != m_lockedBundleFiles.get(getLocale())\n ? m_cms.getSitePath(m_lockedBundleFiles.get(getLocale()).getFile())\n : m_cms.getSitePath(m_resource);\n case XML:\n return m_cms.getSitePath(m_resource);\n default:\n throw new IllegalArgumentException();\n }\n }", "public synchronized static void registerImagOnAgents(Launcher launcher, final String imageTag,\n final String host, final String targetRepo, final ArrayListMultimap<String, String> artifactsProps,\n final int buildInfoId) throws IOException, InterruptedException {\n // Master\n final String imageId = getImageIdFromAgent(launcher, imageTag, host);\n registerImage(imageId, imageTag, targetRepo, artifactsProps, buildInfoId);\n\n // 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 node.getChannel().call(new MasterToSlaveCallable<Boolean, IOException>() {\n public Boolean call() throws IOException {\n registerImage(imageId, imageTag, targetRepo, artifactsProps, buildInfoId);\n return true;\n }\n });\n } catch (Exception e) {\n launcher.getListener().getLogger().println(\"Could not register docker image \" + imageTag +\n \" on Jenkins node '\" + node.getDisplayName() + \"' due to: \" + e.getMessage() +\n \" This could be because this node is now offline.\"\n );\n }\n }\n }", "public static void compress(File dir, File zipFile) throws IOException {\n\n FileOutputStream fos = new FileOutputStream(zipFile);\n ZipOutputStream zos = new ZipOutputStream(fos);\n\n recursiveAddZip(dir, zos, dir);\n\n zos.finish();\n zos.close();\n\n }", "public String addressPath() {\n if (isLeaf) {\n ManagementModelNode parent = (ManagementModelNode)getParent();\n return parent.addressPath();\n }\n\n StringBuilder builder = new StringBuilder();\n for (Object pathElement : getUserObjectPath()) {\n UserObject userObj = (UserObject)pathElement;\n if (userObj.isRoot()) { // don't want to escape root\n builder.append(userObj.getName());\n continue;\n }\n\n builder.append(userObj.getName());\n builder.append(\"=\");\n builder.append(userObj.getEscapedValue());\n builder.append(\"/\");\n }\n\n return builder.toString();\n }", "public void removeCorporateGroupId(final String organizationId, final String corporateGroupId) {\n final DbOrganization dbOrganization = getOrganization(organizationId);\n\n if(dbOrganization.getCorporateGroupIdPrefixes().contains(corporateGroupId)){\n dbOrganization.getCorporateGroupIdPrefixes().remove(corporateGroupId);\n repositoryHandler.store(dbOrganization);\n }\n\n repositoryHandler.removeModulesOrganization(corporateGroupId, dbOrganization);\n }" ]
Initializes the Stitch SDK so that app clients can be created. @param context An Android context value.
[ "public static void initialize(final Context context) {\n if (!initialized.compareAndSet(false, true)) {\n return;\n }\n\n applicationContext = context.getApplicationContext();\n\n final String packageName = applicationContext.getPackageName();\n localAppName = packageName;\n\n final PackageManager manager = applicationContext.getPackageManager();\n try {\n final PackageInfo pkgInfo = manager.getPackageInfo(packageName, 0);\n localAppVersion = pkgInfo.versionName;\n } catch (final NameNotFoundException e) {\n Log.d(TAG, \"Failed to get version of application, will not send in device info.\");\n }\n\n Log.d(TAG, \"Initialized android SDK\");\n }" ]
[ "public static auditnslogpolicy_vpnvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditnslogpolicy_vpnvserver_binding obj = new auditnslogpolicy_vpnvserver_binding();\n\t\tobj.set_name(name);\n\t\tauditnslogpolicy_vpnvserver_binding response[] = (auditnslogpolicy_vpnvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public <T> void cleanNullReferencesAll() {\n\t\tfor (Map<Object, Reference<Object>> objectMap : classMaps.values()) {\n\t\t\tcleanMap(objectMap);\n\t\t}\n\t}", "public Task<Void> resendConfirmationEmail(@NonNull final String email) {\n return dispatcher.dispatchTask(\n new Callable<Void>() {\n @Override\n public Void call() {\n resendConfirmationEmailInternal(email);\n return null;\n }\n });\n }", "public void unbind(T service, Map<String, Object> props) {\n synchronized (serviceMap) {\n serviceMap.remove(ServiceUtil.getComparableForServiceRanking(props));\n updateSortedServices();\n }\n }", "public synchronized Object[] getIds() {\n String[] keys = getAllKeys();\n int size = keys.length + indexedProps.size();\n Object[] res = new Object[size];\n System.arraycopy(keys, 0, res, 0, keys.length);\n int i = keys.length;\n // now add all indexed properties\n for (Object index : indexedProps.keySet()) {\n res[i++] = index;\n }\n return res;\n }", "public static List<String> getCommaSeparatedStringValues(String paramValue, String type) {\n List<String> commaSeparatedProps = Lists.newArrayList();\n for(String url: Utils.COMMA_SEP.split(paramValue.trim()))\n if(url.trim().length() > 0)\n commaSeparatedProps.add(url);\n\n if(commaSeparatedProps.size() == 0) {\n throw new RuntimeException(\"Number of \" + type + \" should be greater than zero\");\n }\n return commaSeparatedProps;\n }", "public void setSeed(String randomSeed) {\n if (!Strings.isNullOrEmpty(getProject().getUserProperty(SYSPROP_RANDOM_SEED()))) {\n String userProperty = getProject().getUserProperty(SYSPROP_RANDOM_SEED());\n if (!userProperty.equals(randomSeed)) {\n log(\"Ignoring seed attribute because it is overridden by user properties.\", Project.MSG_WARN);\n }\n } else if (!Strings.isNullOrEmpty(randomSeed)) {\n this.random = randomSeed;\n }\n }", "public static base_responses update(nitro_service client, sslocspresponder resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslocspresponder updateresources[] = new sslocspresponder[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new sslocspresponder();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].url = resources[i].url;\n\t\t\t\tupdateresources[i].cache = resources[i].cache;\n\t\t\t\tupdateresources[i].cachetimeout = resources[i].cachetimeout;\n\t\t\t\tupdateresources[i].batchingdepth = resources[i].batchingdepth;\n\t\t\t\tupdateresources[i].batchingdelay = resources[i].batchingdelay;\n\t\t\t\tupdateresources[i].resptimeout = resources[i].resptimeout;\n\t\t\t\tupdateresources[i].respondercert = resources[i].respondercert;\n\t\t\t\tupdateresources[i].trustresponder = resources[i].trustresponder;\n\t\t\t\tupdateresources[i].producedattimeskew = resources[i].producedattimeskew;\n\t\t\t\tupdateresources[i].signingcert = resources[i].signingcert;\n\t\t\t\tupdateresources[i].usenonce = resources[i].usenonce;\n\t\t\t\tupdateresources[i].insertclientcert = resources[i].insertclientcert;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "public static <T> void injectEEFields(Iterable<Set<ResourceInjection<?>>> resourceInjectionsHierarchy,\n T beanInstance, CreationalContext<T> ctx) {\n for (Set<ResourceInjection<?>> resourceInjections : resourceInjectionsHierarchy) {\n for (ResourceInjection<?> resourceInjection : resourceInjections) {\n resourceInjection.injectResourceReference(beanInstance, ctx);\n }\n }\n }" ]
Deletes the inbox message for given messageId @param messageId String messageId @return boolean value based on success of operation
[ "synchronized boolean deleteMessageForId(String messageId, String userId){\n if(messageId == null || userId == null) return false;\n\n final String tName = Table.INBOX_MESSAGES.getName();\n\n try {\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n db.delete(tName, _ID + \" = ? AND \" + USER_ID + \" = ?\", new String[]{messageId,userId});\n return true;\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Error removing stale records from \" + tName, e);\n return false;\n } finally {\n dbHelper.close();\n }\n }" ]
[ "public void executeUpdate(ClassDescriptor cld, Object obj) throws PersistenceBrokerException\r\n {\r\n if (logger.isDebugEnabled())\r\n {\r\n logger.debug(\"executeUpdate: \" + obj);\r\n }\r\n\r\n // obj with nothing but key fields is not updated\r\n if (cld.getNonPkRwFields().length == 0)\r\n {\r\n return;\r\n }\r\n\r\n final StatementManagerIF sm = broker.serviceStatementManager();\r\n PreparedStatement stmt = null;\r\n // BRJ: preserve current locking values\r\n // locking values will be restored in case of exception\r\n ValueContainer[] oldLockingValues;\r\n oldLockingValues = cld.getCurrentLockingValues(obj);\r\n try\r\n {\r\n stmt = sm.getUpdateStatement(cld);\r\n if (stmt == null)\r\n {\r\n logger.error(\"getUpdateStatement returned a null statement\");\r\n throw new PersistenceBrokerException(\"getUpdateStatement returned a null statement\");\r\n }\r\n\r\n sm.bindUpdate(stmt, cld, obj);\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"executeUpdate: \" + stmt);\r\n\r\n if ((stmt.executeUpdate() == 0) && cld.isLocking()) //BRJ\r\n {\r\n /**\r\n * Kuali Foundation modification -- 6/19/2009\r\n */\r\n \tString objToString = \"\";\r\n \ttry {\r\n \t\tobjToString = obj.toString();\r\n \t} catch (Exception ex) {}\r\n throw new OptimisticLockException(\"Object has been modified by someone else: \" + objToString, obj);\r\n /**\r\n * End of Kuali Foundation modification\r\n */\r\n }\r\n\r\n // Harvest any return values.\r\n harvestReturnValues(cld.getUpdateProcedure(), obj, stmt);\r\n }\r\n catch (OptimisticLockException e)\r\n {\r\n // Don't log as error\r\n if (logger.isDebugEnabled())\r\n logger.debug(\r\n \"OptimisticLockException during the execution of update: \" + e.getMessage(),\r\n e);\r\n throw e;\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n // BRJ: restore old locking values\r\n setLockingValues(cld, obj, oldLockingValues);\r\n\r\n logger.error(\r\n \"PersistenceBrokerException during the execution of the update: \" + e.getMessage(),\r\n e);\r\n throw e;\r\n }\r\n catch (SQLException e)\r\n {\r\n final String sql = broker.serviceSqlGenerator().getPreparedUpdateStatement(cld).getStatement();\r\n throw ExceptionHelper.generateException(e, sql, cld, logger, obj);\r\n }\r\n finally\r\n {\r\n sm.closeResources(stmt, null);\r\n }\r\n }", "private SynchroTable readTableHeader(byte[] header)\n {\n SynchroTable result = null;\n String tableName = DatatypeConverter.getSimpleString(header, 0);\n if (!tableName.isEmpty())\n {\n int offset = DatatypeConverter.getInt(header, 40);\n result = new SynchroTable(tableName, offset);\n }\n return result;\n }", "private void writeDurationField(String fieldName, Object value) throws IOException\n {\n if (value instanceof String)\n {\n m_writer.writeNameValuePair(fieldName + \"_text\", (String) value);\n }\n else\n {\n Duration val = (Duration) value;\n if (val.getDuration() != 0)\n {\n Duration minutes = val.convertUnits(TimeUnit.MINUTES, m_projectFile.getProjectProperties());\n long seconds = (long) (minutes.getDuration() * 60.0);\n m_writer.writeNameValuePair(fieldName, seconds);\n }\n }\n }", "@SuppressWarnings(\"deprecation\")\n public ResponseFromManager sendTaskToExecutionManager(ParallelTask task) {\n\n ResponseFromManager commandResponseFromManager = null;\n ActorRef executionManager = null;\n try {\n // Start new job\n logger.info(\"!!STARTED sendAgentCommandToManager : \"\n + task.getTaskId() + \" at \"\n + PcDateUtils.getNowDateTimeStr());\n\n executionManager = ActorConfig.createAndGetActorSystem().actorOf(\n Props.create(ExecutionManager.class, task),\n \"ExecutionManager-\" + task.getTaskId());\n\n final FiniteDuration duration = Duration.create(task.getConfig()\n .getTimeoutAskManagerSec(), TimeUnit.SECONDS);\n // Timeout timeout = new\n // Timeout(FiniteDuration.parse(\"300 seconds\"));\n Future<Object> future = Patterns.ask(executionManager,\n new InitialRequestToManager(task), new Timeout(duration));\n\n // set ref\n task.executionManager = executionManager;\n\n commandResponseFromManager = (ResponseFromManager) Await.result(\n future, duration);\n\n logger.info(\"!!COMPLETED sendTaskToExecutionManager : \"\n + task.getTaskId() + \" at \"\n + PcDateUtils.getNowDateTimeStr()\n + \" \\t\\t GenericResponseMap in future size: \"\n + commandResponseFromManager.getResponseCount());\n\n } catch (Exception ex) {\n logger.error(\"Exception in sendTaskToExecutionManager {} details {}: \",\n ex, ex);\n\n } finally {\n // stop the manager\n if (executionManager != null && !executionManager.isTerminated()) {\n ActorConfig.createAndGetActorSystem().stop(executionManager);\n }\n\n if (task.getConfig().isAutoSaveLogToLocal()) {\n task.saveLogToLocal();\n }\n\n }\n\n return commandResponseFromManager;\n\n }", "public RedwoodConfiguration hideChannels(final Object[] channels){\r\n tasks.add(new Runnable() { public void run() { Redwood.hideChannels(channels); } });\r\n return this;\r\n }", "@SuppressWarnings(\"deprecation\")\n\tpublic static boolean isTimeInRange(java.sql.Time start, java.sql.Time end, java.util.Date d) {\n d = new java.sql.Time(d.getHours(), d.getMinutes(), d.getSeconds());\n\n if (start == null || end == null) {\n return false;\n }\n\n if (start.before(end) && (!(d.after(start) && d.before(end)))) {\n return false;\n }\n\n if (end.before(start) && (!(d.after(end) || d.before(start)))) {\n return false;\n }\n return true;\n }", "public double getValueWithGivenYield(double evaluationTime, double rate, AnalyticModel model) {\n\t\tDiscountCurve referenceCurve = DiscountCurveInterpolation.createDiscountCurveFromDiscountFactors(\"referenceCurve\", new double[] {0.0, 1.0}, new double[] {1.0, 1.0});\n\t\treturn getValueWithGivenSpreadOverCurve(evaluationTime, referenceCurve, rate, model);\n\t}", "public boolean containsEntryFor(int maturityInMonths, int tenorInMonths, int moneynessBP) {\r\n\t\treturn entryMap.containsKey(new DataKey(maturityInMonths, tenorInMonths, moneynessBP));\r\n\t}", "public void alias( Object ...args ) {\n if( args.length % 2 == 1 )\n throw new RuntimeException(\"Even number of arguments expected\");\n\n for (int i = 0; i < args.length; i += 2) {\n aliasGeneric( args[i], (String)args[i+1]);\n }\n }" ]
Call batch tasks inside of a connection which may, or may not, have been "saved".
[ "public <CT> CT callBatchTasks(ConnectionSource connectionSource, Callable<CT> callable) throws SQLException {\n\t\tif (connectionSource.isSingleConnection(tableInfo.getTableName())) {\n\t\t\tsynchronized (this) {\n\t\t\t\treturn doCallBatchTasks(connectionSource, callable);\n\t\t\t}\n\t\t} else {\n\t\t\treturn doCallBatchTasks(connectionSource, callable);\n\t\t}\n\t}" ]
[ "private void logColumnData(int startIndex, int length)\n {\n if (m_log != null)\n {\n m_log.println();\n m_log.println(FastTrackUtility.hexdump(m_buffer, startIndex, length, true, 16, \"\"));\n m_log.println();\n m_log.flush();\n }\n }", "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 }", "@Override\n public DiscordianDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }", "static List<List<String>> handleNewLines( List<List<String>> tableModel ) {\n List<List<String>> result = Lists.newArrayListWithExpectedSize( tableModel.size() );\n\n for( List<String> row : tableModel ) {\n if( hasNewline( row ) ) {\n result.addAll( splitRow( row ) );\n } else {\n result.add( row );\n }\n }\n\n return result;\n }", "protected void addPropertiesStart(String type) {\n putProperty(PropertyKey.Host.name(), IpUtils.getHostName());\n putProperty(PropertyKey.Type.name(), type);\n putProperty(PropertyKey.Status.name(), Status.Start.name());\n }", "@Override\n\tpublic boolean isPrefixBlock() {\n\t\tInteger networkPrefixLength = getNetworkPrefixLength();\n\t\tif(networkPrefixLength == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif(getNetwork().getPrefixConfiguration().allPrefixedAddressesAreSubnets()) {\n\t\t\treturn true;\n\t\t}\n\t\treturn containsPrefixBlock(networkPrefixLength);\n\t}", "protected OJBIterator getIteratorFromQuery(Query query, ClassDescriptor cld) throws PersistenceBrokerException\n {\n RsIteratorFactory factory = RsIteratorFactoryImpl.getInstance();\n OJBIterator result = getRsIteratorFromQuery(query, cld, factory);\n\n if (query.usePaging())\n {\n result = new PagingIterator(result, query.getStartAtIndex(), query.getEndAtIndex());\n }\n return result;\n }", "public void processTasks(List<Row> bars, List<Row> expandedTasks, List<Row> tasks, List<Row> milestones)\n {\n List<Row> parentBars = buildRowHierarchy(bars, expandedTasks, tasks, milestones);\n createTasks(m_project, \"\", parentBars);\n deriveProjectCalendar();\n updateStructure();\n }", "private Envelope getBoundsLocal(Filter filter) throws LayerException {\n\t\ttry {\n\t\t\tSession session = getSessionFactory().getCurrentSession();\n\t\t\tCriteria criteria = session.createCriteria(getFeatureInfo().getDataSourceName());\n\t\t\tCriteriaVisitor visitor = new CriteriaVisitor((HibernateFeatureModel) getFeatureModel(), dateFormat);\n\t\t\tCriterion c = (Criterion) filter.accept(visitor, criteria);\n\t\t\tif (c != null) {\n\t\t\t\tcriteria.add(c);\n\t\t\t}\n\t\t\tcriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);\n\t\t\tList<?> features = criteria.list();\n\t\t\tEnvelope bounds = new Envelope();\n\t\t\tfor (Object f : features) {\n\t\t\t\tEnvelope geomBounds = getFeatureModel().getGeometry(f).getEnvelopeInternal();\n\t\t\t\tif (!geomBounds.isNull()) {\n\t\t\t\t\tbounds.expandToInclude(geomBounds);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn bounds;\n\t\t} catch (HibernateException he) {\n\t\t\tthrow new HibernateLayerException(he, ExceptionCode.HIBERNATE_LOAD_FILTER_FAIL, getFeatureInfo()\n\t\t\t\t\t.getDataSourceName(), filter.toString());\n\t\t}\n\t}" ]
Determines run length for each 'initial' partition ID. Note that a contiguous run may "wrap around" the end of the ring. @param cluster @param zoneId @return map of initial partition Id to length of contiguous run of partition IDs within the same zone..
[ "public static Map<Integer, Integer> getMapOfContiguousPartitions(final Cluster cluster,\n int zoneId) {\n List<Integer> partitionIds = new ArrayList<Integer>(cluster.getPartitionIdsInZone(zoneId));\n Map<Integer, Integer> partitionIdToRunLength = Maps.newHashMap();\n\n if(partitionIds.isEmpty()) {\n return partitionIdToRunLength;\n }\n\n int lastPartitionId = partitionIds.get(0);\n int initPartitionId = lastPartitionId;\n\n for(int offset = 1; offset < partitionIds.size(); offset++) {\n int partitionId = partitionIds.get(offset);\n if(partitionId == lastPartitionId + 1) {\n lastPartitionId = partitionId;\n continue;\n }\n int runLength = lastPartitionId - initPartitionId + 1;\n\n partitionIdToRunLength.put(initPartitionId, runLength);\n\n initPartitionId = partitionId;\n lastPartitionId = initPartitionId;\n }\n\n int runLength = lastPartitionId - initPartitionId + 1;\n if(lastPartitionId == cluster.getNumberOfPartitions() - 1\n && partitionIdToRunLength.containsKey(0)) {\n // special case of contiguity that wraps around the ring.\n partitionIdToRunLength.put(initPartitionId, runLength + partitionIdToRunLength.get(0));\n partitionIdToRunLength.remove(0);\n } else {\n partitionIdToRunLength.put(initPartitionId, runLength);\n }\n\n return partitionIdToRunLength;\n }" ]
[ "public void logAttributeWarning(PathAddress address, String message, Set<String> attributes) {\n messageQueue.add(new AttributeLogEntry(address, null, message, attributes));\n }", "public static List<Integer> getAllPartitions(AdminClient adminClient) {\n List<Integer> partIds = Lists.newArrayList();\n partIds = Lists.newArrayList();\n for(Node node: adminClient.getAdminClientCluster().getNodes()) {\n partIds.addAll(node.getPartitionIds());\n }\n return partIds;\n }", "public void addChildTask(Task child)\n {\n child.m_parent = this;\n m_children.add(child);\n setSummary(true);\n\n if (getParentFile().getProjectConfig().getAutoOutlineLevel() == true)\n {\n child.setOutlineLevel(Integer.valueOf(NumberHelper.getInt(getOutlineLevel()) + 1));\n }\n }", "public void writeObject(Object o, GraphicsDocument document, boolean asChild) throws RenderException {\n\t\tdocument.writeElement(\"vml:shape\", asChild);\n\t\tPoint p = (Point) o;\n\t\tString adj = document.getFormatter().format(p.getX()) + \",\"\n\t\t\t\t+ document.getFormatter().format(p.getY());\n\t\tdocument.writeAttribute(\"adj\", adj);\n\t}", "public static lbvserver[] get(nitro_service service) throws Exception{\n\t\tlbvserver obj = new lbvserver();\n\t\tlbvserver[] response = (lbvserver[])obj.get_resources(service);\n\t\treturn response;\n\t}", "protected String parseOptionalStringValue(final String path) {\n\n final I_CmsXmlContentValue value = m_xml.getValue(path, m_locale);\n if (value == null) {\n return null;\n } else {\n return value.getStringValue(null);\n }\n }", "public ReferrerList getPhotosetReferrers(Date date, String domain, String photosetId, int perPage, int page) throws FlickrException {\n return getReferrers(METHOD_GET_PHOTOSET_REFERRERS, domain, \"photoset_id\", photosetId, date, perPage, page);\n }", "protected <C> C convert(Object object, Class<C> targetClass) {\n return this.mapper.convertValue(object, targetClass);\n }", "protected void prepareForwardedRequestHeaders(RequestData request, ForwardDestination destination) {\n HttpHeaders headers = request.getHeaders();\n headers.set(HOST, destination.getUri().getAuthority());\n headers.remove(TE);\n }" ]
test, how many times the group was present in the list of groups.
[ "private Map<String, Integer> runSampling(\n final ProctorContext proctorContext,\n final Set<String> targetTestNames,\n final TestType testType,\n final int determinationsToRun\n ) {\n final Set<String> targetTestGroups = getTargetTestGroups(targetTestNames);\n final Map<String, Integer> testGroupToOccurrences = Maps.newTreeMap();\n for (final String testGroup : targetTestGroups) {\n testGroupToOccurrences.put(testGroup, 0);\n }\n\n for (int i = 0; i < determinationsToRun; ++i) {\n final Identifiers identifiers = TestType.RANDOM.equals(testType)\n ? new Identifiers(Collections.<TestType, String>emptyMap(), /* randomEnabled */ true)\n : Identifiers.of(testType, Long.toString(random.nextLong()));\n final AbstractGroups groups = supplier.getRandomGroups(proctorContext, identifiers);\n for (final Entry<String, TestBucket> e : groups.getProctorResult().getBuckets().entrySet()) {\n final String testName = e.getKey();\n if (targetTestNames.contains(testName)) {\n final int group = e.getValue().getValue();\n final String testGroup = testName + group;\n testGroupToOccurrences.put(testGroup, testGroupToOccurrences.get(testGroup) + 1);\n }\n }\n }\n\n return testGroupToOccurrences;\n }" ]
[ "public double getRate(AnalyticModel model) {\n\t\tif(model==null) {\n\t\t\tthrow new IllegalArgumentException(\"model==null\");\n\t\t}\n\n\t\tForwardCurve forwardCurve = model.getForwardCurve(forwardCurveName);\n\t\tif(forwardCurve==null) {\n\t\t\tthrow new IllegalArgumentException(\"No forward curve of name '\" + forwardCurveName + \"' found in given model:\\n\" + model.toString());\n\t\t}\n\n\t\tdouble fixingDate = schedule.getFixing(0);\n\t\treturn forwardCurve.getForward(model,fixingDate);\n\t}", "public void processCollection(String template, Properties attributes) throws XDocletException\r\n {\r\n String name = OjbMemberTagsHandler.getMemberName();\r\n CollectionDescriptorDef collDef = _curClassDef.getCollection(name);\r\n String attrName;\r\n\r\n if (collDef == null)\r\n {\r\n collDef = new CollectionDescriptorDef(name);\r\n _curClassDef.addCollection(collDef);\r\n }\r\n LogHelper.debug(false, OjbTagsHandler.class, \"processCollection\", \" Processing collection \"+collDef.getName());\r\n\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n collDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n if (OjbMemberTagsHandler.getMemberDimension() > 0)\r\n {\r\n // we store the array-element type for later use\r\n collDef.setProperty(PropertyHelper.OJB_PROPERTY_ARRAY_ELEMENT_CLASS_REF,\r\n OjbMemberTagsHandler.getMemberType().getQualifiedName());\r\n }\r\n else\r\n { \r\n collDef.setProperty(PropertyHelper.OJB_PROPERTY_VARIABLE_TYPE,\r\n OjbMemberTagsHandler.getMemberType().getQualifiedName());\r\n }\r\n\r\n _curCollectionDef = collDef;\r\n generate(template);\r\n _curCollectionDef = null;\r\n }", "public void recordCheckoutQueueLength(SocketDestination dest, int queueLength) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordCheckoutQueueLength(null, queueLength);\n recordCheckoutQueueLength(null, queueLength);\n } else {\n this.checkoutQueueLengthHistogram.insert(queueLength);\n checkMonitoringInterval();\n }\n }", "public static ipset_nsip_binding[] get(nitro_service service, String name) throws Exception{\n\t\tipset_nsip_binding obj = new ipset_nsip_binding();\n\t\tobj.set_name(name);\n\t\tipset_nsip_binding response[] = (ipset_nsip_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "@PostConstruct\n public void initDatabase() {\n MongoDBInit.LOGGER.info(\"initializing MongoDB\");\n String dbName = System.getProperty(\"mongodb.name\");\n if (dbName == null) {\n throw new RuntimeException(\"Missing database name; Set system property 'mongodb.name'\");\n }\n MongoDatabase db = this.mongo.getDatabase(dbName);\n\n try {\n PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();\n Resource[] resources = resolver.getResources(\"classpath*:mongodb/*.ndjson\");\n MongoDBInit.LOGGER.info(\"Scanning for collection data\");\n for (Resource res : resources) {\n String filename = res.getFilename();\n String collection = filename.substring(0, filename.length() - 7);\n MongoDBInit.LOGGER.info(\"Found collection file: {}\", collection);\n MongoCollection<DBObject> dbCollection = db.getCollection(collection, DBObject.class);\n try (Scanner scan = new Scanner(res.getInputStream(), \"UTF-8\")) {\n int lines = 0;\n while (scan.hasNextLine()) {\n String json = scan.nextLine();\n Object parse = JSON.parse(json);\n if (parse instanceof DBObject) {\n DBObject dbObject = (DBObject) parse;\n dbCollection.insertOne(dbObject);\n } else {\n MongoDBInit.LOGGER.error(\"Invalid object found: {}\", parse);\n throw new RuntimeException(\"Invalid object\");\n }\n lines++;\n }\n MongoDBInit.LOGGER.info(\"Imported {} objects into collection {}\", lines, collection);\n }\n }\n } catch (IOException e) {\n throw new RuntimeException(\"Error importing objects\", e);\n }\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 }", "private boolean isWorkingDay(ProjectCalendar mpxjCalendar, Day day)\n {\n boolean result = false;\n net.sf.mpxj.DayType type = mpxjCalendar.getWorkingDay(day);\n if (type == null)\n {\n type = net.sf.mpxj.DayType.DEFAULT;\n }\n\n switch (type)\n {\n case WORKING:\n {\n result = true;\n break;\n }\n\n case NON_WORKING:\n {\n result = false;\n break;\n }\n\n case DEFAULT:\n {\n if (mpxjCalendar.getParent() == null)\n {\n result = false;\n }\n else\n {\n result = isWorkingDay(mpxjCalendar.getParent(), day);\n }\n break;\n }\n }\n\n return (result);\n }", "public static base_responses delete(nitro_service client, String certkey[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (certkey != null && certkey.length > 0) {\n\t\t\tsslcertkey deleteresources[] = new sslcertkey[certkey.length];\n\t\t\tfor (int i=0;i<certkey.length;i++){\n\t\t\t\tdeleteresources[i] = new sslcertkey();\n\t\t\t\tdeleteresources[i].certkey = certkey[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "private Integer getFrequency(Project.Calendars.Calendar.Exceptions.Exception exception)\n {\n Integer period = NumberHelper.getInteger(exception.getPeriod());\n if (period == null)\n {\n period = Integer.valueOf(1);\n }\n return period;\n }" ]
Determine how many forked JVMs to use.
[ "private int determineForkedJvmCount(TestsCollection testCollection) {\n int cores = Runtime.getRuntime().availableProcessors();\n int jvmCount;\n if (this.parallelism.equals(PARALLELISM_AUTO)) {\n if (cores >= 8) {\n // Maximum parallel jvms is 4, conserve some memory and memory bandwidth.\n jvmCount = 4;\n } else if (cores >= 4) {\n // Make some space for the aggregator.\n jvmCount = 3;\n } else if (cores == 3) {\n // Yes, three-core chips are a thing.\n jvmCount = 2;\n } else {\n // even for dual cores it usually makes no sense to fork more than one\n // JVM.\n jvmCount = 1;\n }\n } else if (this.parallelism.equals(PARALLELISM_MAX)) {\n jvmCount = Runtime.getRuntime().availableProcessors();\n } else {\n try {\n jvmCount = Math.max(1, Integer.parseInt(parallelism));\n } catch (NumberFormatException e) {\n throw new BuildException(\"parallelism must be 'auto', 'max' or a valid integer: \"\n + parallelism);\n }\n }\n\n if (!testCollection.hasReplicatedSuites()) {\n jvmCount = Math.min(testCollection.testClasses.size(), jvmCount);\n }\n return jvmCount;\n }" ]
[ "protected Object[] getFieldObjects(Object data) throws SQLException {\n\t\tObject[] objects = new Object[argFieldTypes.length];\n\t\tfor (int i = 0; i < argFieldTypes.length; i++) {\n\t\t\tFieldType fieldType = argFieldTypes[i];\n\t\t\tif (fieldType.isAllowGeneratedIdInsert()) {\n\t\t\t\tobjects[i] = fieldType.getFieldValueIfNotDefault(data);\n\t\t\t} else {\n\t\t\t\tobjects[i] = fieldType.extractJavaFieldToSqlArgValue(data);\n\t\t\t}\n\t\t\tif (objects[i] == null) {\n\t\t\t\t// NOTE: the default value could be null as well\n\t\t\t\tobjects[i] = fieldType.getDefaultValue();\n\t\t\t}\n\t\t}\n\t\treturn objects;\n\t}", "private 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 }", "String calculateDisplayTimestamp(long time){\n long now = System.currentTimeMillis()/1000;\n long diff = now-time;\n if(diff < 60){\n return \"Just Now\";\n }else if(diff > 60 && diff < 59*60){\n return (diff/(60)) + \" mins ago\";\n }else if(diff > 59*60 && diff < 23*59*60 ){\n return diff/(60*60) > 1 ? diff/(60*60) + \" hours ago\" : diff/(60*60) + \" hour ago\";\n }else if(diff > 24*60*60 && diff < 48*60*60){\n return \"Yesterday\";\n }else {\n @SuppressLint(\"SimpleDateFormat\")\n SimpleDateFormat sdf = new SimpleDateFormat(\"dd MMM\");\n return sdf.format(new Date(time));\n }\n }", "public static spilloverpolicy get(nitro_service service, String name) throws Exception{\n\t\tspilloverpolicy obj = new spilloverpolicy();\n\t\tobj.set_name(name);\n\t\tspilloverpolicy response = (spilloverpolicy) obj.get_resource(service);\n\t\treturn response;\n\t}", "private InputValue getInputValue(FormInput input) {\n\n\t\t/* Get the DOM element from Selenium. */\n\t\tWebElement inputElement = browser.getWebElement(input.getIdentification());\n\n\t\tswitch (input.getType()) {\n\t\t\tcase TEXT:\n\t\t\tcase PASSWORD:\n\t\t\tcase HIDDEN:\n\t\t\tcase SELECT:\n\t\t\tcase TEXTAREA:\n\t\t\t\treturn new InputValue(inputElement.getAttribute(\"value\"));\n\t\t\tcase RADIO:\n\t\t\tcase CHECKBOX:\n\t\t\tdefault:\n\t\t\t\tString value = inputElement.getAttribute(\"value\");\n\t\t\t\tBoolean checked = inputElement.isSelected();\n\t\t\t\treturn new InputValue(value, checked);\n\t\t}\n\n\t}", "public void unregisterComponent(java.awt.Component c)\r\n {\r\n java.awt.dnd.DragGestureRecognizer recognizer = \r\n (java.awt.dnd.DragGestureRecognizer)this.hmDragGestureRecognizers.remove(c);\r\n if (recognizer != null)\r\n recognizer.setComponent(null);\r\n }", "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 }", "public int executeRefresh(DatabaseConnection databaseConnection, T data, ObjectCache objectCache)\n\t\t\tthrows SQLException {\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tID id = (ID) idField.extractJavaFieldValue(data);\n\t\t// we don't care about the cache here\n\t\tT result = super.execute(databaseConnection, id, null);\n\t\tif (result == null) {\n\t\t\treturn 0;\n\t\t}\n\t\t// copy each field from the result into the passed in object\n\t\tfor (FieldType fieldType : resultsFieldTypes) {\n\t\t\tif (fieldType != idField) {\n\t\t\t\tfieldType.assignField(connectionSource, data, fieldType.extractJavaFieldValue(result), false,\n\t\t\t\t\t\tobjectCache);\n\t\t\t}\n\t\t}\n\t\treturn 1;\n\t}", "public static String getShortName(String className) {\n\t\tAssert.hasLength(className, \"Class name must not be empty\");\n\t\tint lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR);\n\t\tint nameEndIndex = className.indexOf(CGLIB_CLASS_SEPARATOR);\n\t\tif (nameEndIndex == -1) {\n\t\t\tnameEndIndex = className.length();\n\t\t}\n\t\tString shortName = className.substring(lastDotIndex + 1, nameEndIndex);\n\t\tshortName = shortName.replace(INNER_CLASS_SEPARATOR, PACKAGE_SEPARATOR);\n\t\treturn shortName;\n\t}" ]
Empirical data from 3.x, actual =40
[ "public Model interpolateModel(Model model, File projectDir, ModelBuildingRequest config,\n\t\t\tModelProblemCollector problems) {\n\t\tinterpolateObject(model, model, projectDir, config, problems);\n\n\t\treturn model;\n\t}" ]
[ "private String FCMGetFreshToken(final String senderID) {\n String token = null;\n try {\n if(senderID != null){\n getConfigLogger().verbose(getAccountId(), \"FcmManager: Requesting a FCM token with Sender Id - \"+senderID);\n token = FirebaseInstanceId.getInstance().getToken(senderID, FirebaseMessaging.INSTANCE_ID_SCOPE);\n }else {\n getConfigLogger().verbose(getAccountId(), \"FcmManager: Requesting a FCM token\");\n token = FirebaseInstanceId.getInstance().getToken();\n }\n getConfigLogger().info(getAccountId(),\"FCM token: \"+token);\n } catch (Throwable t) {\n getConfigLogger().verbose(getAccountId(), \"FcmManager: Error requesting FCM token\", t);\n }\n return token;\n }", "protected void onNewParentObject(GVRSceneObject parent) {\n for (GVRComponent comp : mComponents.values()) {\n comp.onNewOwnersParent(parent);\n }\n }", "public static void writeInt(byte[] bytes, int value, int offset) {\n bytes[offset] = (byte) (0xFF & (value >> 24));\n bytes[offset + 1] = (byte) (0xFF & (value >> 16));\n bytes[offset + 2] = (byte) (0xFF & (value >> 8));\n bytes[offset + 3] = (byte) (0xFF & value);\n }", "@Override\n public final String getString(final int i) {\n String val = this.array.optString(i, null);\n if (val == null) {\n throw new ObjectMissingException(this, \"[\" + i + \"]\");\n }\n return val;\n }", "private void stopDone() {\n synchronized (stopLock) {\n final StopContext stopContext = this.stopContext;\n this.stopContext = null;\n if (stopContext != null) {\n stopContext.complete();\n }\n stopLock.notifyAll();\n }\n }", "public static<A, B, Z> Function2<A, B, Z> lift(Func2<A, B, Z> f) {\n\treturn bridge.lift(f);\n }", "public final void notifyHeaderItemChanged(int position) {\n if (position < 0 || position >= headerItemCount) {\n throw new IndexOutOfBoundsException(\"The given position \" + position + \" is not within the position bounds for header items [0 - \" + (headerItemCount - 1) + \"].\");\n }\n notifyItemChanged(position);\n }", "public void addProperty(String name, String... values) {\n List<String> valueList = new ArrayList<String>();\n for (String value : values) {\n valueList.add(value.trim());\n }\n properties.put(name.trim(), valueList);\n }", "public static <E extends Enum<E>> EnumStringConverter<E> create(Class<E> enumType) {\n return new EnumStringConverter<E>(enumType);\n }" ]
Parses the given XML doc to extract the properties and return them into a java.util.Properties. @param doc to parse @param sectionName which section to extract @return Properties map
[ "private Properties parseXML(Document doc, String sectionName) {\n\t\tint found = -1;\n\t\tProperties results = new Properties();\n\t\tNodeList config = null;\n\t\tif (sectionName == null){\n\t\t\tconfig = doc.getElementsByTagName(\"default-config\");\n\t\t\tfound = 0;\n\t\t} else {\n\t\t\tconfig = doc.getElementsByTagName(\"named-config\");\n\t\t\tif(config != null && config.getLength() > 0) {\n\t\t\t\tfor (int i = 0; i < config.getLength(); i++) {\n\t\t\t\t\tNode node = config.item(i);\n\t\t\t\t\tif(node.getNodeType() == Node.ELEMENT_NODE ){\n\t\t\t\t\t\tNamedNodeMap attributes = node.getAttributes();\n\t\t\t\t\t\tif (attributes != null && attributes.getLength() > 0){\n\t\t\t\t\t\t\tNode name = attributes.getNamedItem(\"name\");\n\t\t\t\t\t\t\tif (name.getNodeValue().equalsIgnoreCase(sectionName)){\n\t\t\t\t\t\t\t\tfound = i;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (found == -1){\n\t\t\t\tconfig = null;\n\t\t\t\tlogger.warn(\"Did not find \"+sectionName+\" section in config file. Reverting to defaults.\");\n\t\t\t}\n\t\t}\n\n\t\tif(config != null && config.getLength() > 0) {\n\t\t\tNode node = config.item(found);\n\t\t\tif(node.getNodeType() == Node.ELEMENT_NODE){\n\t\t\t\tElement elementEntry = (Element)node;\n\t\t\t\tNodeList childNodeList = elementEntry.getChildNodes();\n\t\t\t\tfor (int j = 0; j < childNodeList.getLength(); j++) {\n\t\t\t\t\tNode node_j = childNodeList.item(j);\n\t\t\t\t\tif (node_j.getNodeType() == Node.ELEMENT_NODE) {\n\t\t\t\t\t\tElement piece = (Element) node_j;\n\t\t\t\t\t\tNamedNodeMap attributes = piece.getAttributes();\n\t\t\t\t\t\tif (attributes != null && attributes.getLength() > 0){\n\t\t\t\t\t\t\tresults.put(attributes.item(0).getNodeValue(), piece.getTextContent());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn results;\n\t}" ]
[ "public static void writeUnsignedShort(byte[] bytes, int value, int offset) {\n bytes[offset] = (byte) (0xFF & (value >> 8));\n bytes[offset + 1] = (byte) (0xFF & value);\n }", "private static Iterable<BoxUser.Info> getUsersInfoForType(final BoxAPIConnection api,\n final String filterTerm, final String userType, final String externalAppUserId, final String... fields) {\n return new Iterable<BoxUser.Info>() {\n public Iterator<BoxUser.Info> iterator() {\n QueryStringBuilder builder = new QueryStringBuilder();\n if (filterTerm != null) {\n builder.appendParam(\"filter_term\", filterTerm);\n }\n if (userType != null) {\n builder.appendParam(\"user_type\", userType);\n }\n if (externalAppUserId != null) {\n builder.appendParam(\"external_app_user_id\", externalAppUserId);\n }\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields);\n }\n URL url = USERS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString());\n return new BoxUserIterator(api, url);\n }\n };\n }", "@Override\n public void removeStorageEngine(StorageEngine<ByteArray, byte[], byte[]> engine) {\n String storeName = engine.getName();\n BdbStorageEngine bdbEngine = (BdbStorageEngine) engine;\n\n synchronized(lock) {\n\n // Only cleanup the environment if it is per store. We cannot\n // cleanup a shared 'Environment' object\n if(useOneEnvPerStore) {\n\n Environment environment = this.environments.get(storeName);\n if(environment == null) {\n // Nothing to clean up.\n return;\n }\n\n // Remove from the set of unreserved stores if needed.\n if(this.unreservedStores.remove(environment)) {\n logger.info(\"Removed environment for store name: \" + storeName\n + \" from unreserved stores\");\n } else {\n logger.info(\"No environment found in unreserved stores for store name: \"\n + storeName);\n }\n\n // Try to delete the BDB directory associated\n File bdbDir = environment.getHome();\n if(bdbDir.exists() && bdbDir.isDirectory()) {\n String bdbDirPath = bdbDir.getPath();\n try {\n FileUtils.deleteDirectory(bdbDir);\n logger.info(\"Successfully deleted BDB directory : \" + bdbDirPath\n + \" for store name: \" + storeName);\n } catch(IOException e) {\n logger.error(\"Unable to delete BDB directory: \" + bdbDirPath\n + \" for store name: \" + storeName);\n }\n }\n\n // Remove the reference to BdbEnvironmentStats, which holds a\n // reference to the Environment\n BdbEnvironmentStats bdbEnvStats = bdbEngine.getBdbEnvironmentStats();\n this.aggBdbStats.unTrackEnvironment(bdbEnvStats);\n\n // Unregister the JMX bean for Environment\n if(voldemortConfig.isJmxEnabled()) {\n ObjectName name = JmxUtils.createObjectName(JmxUtils.getPackageName(bdbEnvStats.getClass()),\n storeName);\n // Un-register the environment stats mbean\n JmxUtils.unregisterMbean(name);\n }\n\n // Cleanup the environment\n environment.close();\n this.environments.remove(storeName);\n logger.info(\"Successfully closed the environment for store name : \" + storeName);\n\n }\n }\n }", "public BoxFile.Info restoreFile(String fileID, String newName, String newParentID) {\n JsonObject requestJSON = new JsonObject();\n\n if (newName != null) {\n requestJSON.add(\"name\", newName);\n }\n\n if (newParentID != null) {\n JsonObject parent = new JsonObject();\n parent.add(\"id\", newParentID);\n requestJSON.add(\"parent\", parent);\n }\n\n URL url = RESTORE_FILE_URL_TEMPLATE.build(this.api.getBaseURL(), fileID);\n BoxJSONRequest request = new BoxJSONRequest(this.api, url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxFile restoredFile = new BoxFile(this.api, responseJSON.get(\"id\").asString());\n return restoredFile.new Info(responseJSON);\n }", "protected void associateBatched(Collection owners, Collection children)\r\n {\r\n CollectionDescriptor cds = getCollectionDescriptor();\r\n PersistentField field = cds.getPersistentField();\r\n PersistenceBroker pb = getBroker();\r\n Class ownerTopLevelClass = pb.getTopLevelClass(getOwnerClassDescriptor().getClassOfObject());\r\n Class collectionClass = cds.getCollectionClass(); // this collection type will be used:\r\n HashMap ownerIdsToLists = new HashMap(owners.size());\r\n\r\n IdentityFactory identityFactory = pb.serviceIdentity();\r\n // initialize the owner list map\r\n for (Iterator it = owners.iterator(); it.hasNext();)\r\n {\r\n Object owner = it.next();\r\n ownerIdsToLists.put(identityFactory.buildIdentity(getOwnerClassDescriptor(), owner), new ArrayList());\r\n }\r\n\r\n // build the children lists for the owners\r\n for (Iterator it = children.iterator(); it.hasNext();)\r\n {\r\n Object child = it.next();\r\n // BRJ: use cld for real class, relatedObject could be Proxy\r\n ClassDescriptor cld = getDescriptorRepository().getDescriptorFor(ProxyHelper.getRealClass(child));\r\n\r\n Object[] fkValues = cds.getForeignKeyValues(child, cld);\r\n Identity ownerId = identityFactory.buildIdentity(null, ownerTopLevelClass, fkValues);\r\n List list = (List) ownerIdsToLists.get(ownerId);\r\n if (list != null)\r\n {\r\n list.add(child);\r\n }\r\n }\r\n\r\n // connect children list to owners\r\n for (Iterator it = owners.iterator(); it.hasNext();)\r\n {\r\n Object result;\r\n Object owner = it.next();\r\n Identity ownerId = identityFactory.buildIdentity(owner);\r\n List list = (List) ownerIdsToLists.get(ownerId);\r\n\r\n if ((collectionClass == null) && field.getType().isArray())\r\n {\r\n int length = list.size();\r\n Class itemtype = field.getType().getComponentType();\r\n result = Array.newInstance(itemtype, length);\r\n for (int j = 0; j < length; j++)\r\n {\r\n Array.set(result, j, list.get(j));\r\n }\r\n }\r\n else\r\n {\r\n ManageableCollection col = createCollection(cds, collectionClass);\r\n for (Iterator it2 = list.iterator(); it2.hasNext();)\r\n {\r\n col.ojbAdd(it2.next());\r\n }\r\n result = col;\r\n }\r\n\r\n Object value = field.get(owner);\r\n if ((value instanceof CollectionProxyDefaultImpl) && (result instanceof Collection))\r\n {\r\n ((CollectionProxyDefaultImpl) value).setData((Collection) result);\r\n }\r\n else\r\n {\r\n field.set(owner, result);\r\n }\r\n }\r\n }", "public static List<Object> listOfEntities(SharedSessionContractImplementor session, Type[] resultTypes, ClosableIterator<Tuple> tuples) {\n\t\tClass<?> returnedClass = resultTypes[0].getReturnedClass();\n\t\tTupleBasedEntityLoader loader = getLoader( session, returnedClass );\n\t\tOgmLoadingContext ogmLoadingContext = new OgmLoadingContext();\n\t\togmLoadingContext.setTuples( getTuplesAsList( tuples ) );\n\t\treturn loader.loadEntitiesFromTuples( session, LockOptions.NONE, ogmLoadingContext );\n\t}", "public void setLoop(boolean doLoop, GVRContext gvrContext) {\n if (this.loop != doLoop ) {\n // a change in the loop\n for (GVRNodeAnimation gvrKeyFrameAnimation : gvrKeyFrameAnimations) {\n if (doLoop) gvrKeyFrameAnimation.setRepeatMode(GVRRepeatMode.REPEATED);\n else gvrKeyFrameAnimation.setRepeatMode(GVRRepeatMode.ONCE);\n }\n // be sure to start the animations if loop is true\n if ( doLoop ) {\n for (GVRNodeAnimation gvrKeyFrameAnimation : gvrKeyFrameAnimations) {\n gvrKeyFrameAnimation.start(gvrContext.getAnimationEngine() );\n }\n }\n this.loop = doLoop;\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 }", "private void addTraceForFrame(WebSocketFrame frame, String type) {\n\t\tMap<String, Object> trace = new LinkedHashMap<>();\n\t\ttrace.put(\"type\", type);\n\t\ttrace.put(\"direction\", \"in\");\n\t\tif (frame instanceof TextWebSocketFrame) {\n\t\t\ttrace.put(\"payload\", ((TextWebSocketFrame) frame).text());\n\t\t}\n\n\t\tif (traceEnabled) {\n\t\t\twebsocketTraceRepository.add(trace);\n\t\t}\n\t}" ]
Creates a new empty HTML document tree. @throws ParserConfigurationException
[ "protected void createDocument() throws ParserConfigurationException\n {\n DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();\n DocumentBuilder builder = builderFactory.newDocumentBuilder();\n DocumentType doctype = builder.getDOMImplementation().createDocumentType(\"html\", \"-//W3C//DTD XHTML 1.1//EN\", \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\");\n doc = builder.getDOMImplementation().createDocument(\"http://www.w3.org/1999/xhtml\", \"html\", doctype);\n \n head = doc.createElement(\"head\");\n Element meta = doc.createElement(\"meta\");\n meta.setAttribute(\"http-equiv\", \"content-type\");\n meta.setAttribute(\"content\", \"text/html;charset=utf-8\");\n head.appendChild(meta);\n title = doc.createElement(\"title\");\n title.setTextContent(\"PDF Document\");\n head.appendChild(title);\n globalStyle = doc.createElement(\"style\");\n globalStyle.setAttribute(\"type\", \"text/css\");\n //globalStyle.setTextContent(createGlobalStyle());\n head.appendChild(globalStyle);\n \n body = doc.createElement(\"body\");\n \n Element root = doc.getDocumentElement();\n root.appendChild(head);\n root.appendChild(body);\n }" ]
[ "protected void setColumnsFinalWidth() {\n log.debug(\"Setting columns final width.\");\n float factor;\n int printableArea = report.getOptions().getColumnWidth();\n\n //Create a list with only the visible columns.\n List visibleColums = getVisibleColumns();\n\n\n if (report.getOptions().isUseFullPageWidth()) {\n int columnsWidth = 0;\n int notRezisableWidth = 0;\n\n //Store in a variable the total with of all visible columns\n for (Object visibleColum : visibleColums) {\n AbstractColumn col = (AbstractColumn) visibleColum;\n columnsWidth += col.getWidth();\n if (col.isFixedWidth())\n notRezisableWidth += col.getWidth();\n }\n\n\n factor = (float) (printableArea - notRezisableWidth) / (float) (columnsWidth - notRezisableWidth);\n\n log.debug(\"printableArea = \" + printableArea\n + \", columnsWidth = \" + columnsWidth\n + \", columnsWidth = \" + columnsWidth\n + \", notRezisableWidth = \" + notRezisableWidth\n + \", factor = \" + factor);\n\n int acumulated = 0;\n int colFinalWidth;\n\n //Select the non-resizable columns\n Collection resizableColumns = CollectionUtils.select(visibleColums, new Predicate() {\n public boolean evaluate(Object arg0) {\n return !((AbstractColumn) arg0).isFixedWidth();\n }\n\n });\n\n //Finally, set the new width to the resizable columns\n for (Iterator iter = resizableColumns.iterator(); iter.hasNext(); ) {\n AbstractColumn col = (AbstractColumn) iter.next();\n\n if (!iter.hasNext()) {\n col.setWidth(printableArea - notRezisableWidth - acumulated);\n } else {\n colFinalWidth = (new Float(col.getWidth() * factor)).intValue();\n acumulated += colFinalWidth;\n col.setWidth(colFinalWidth);\n }\n }\n }\n\n // If the columns width changed, the X position must be setted again.\n int posx = 0;\n for (Object visibleColum : visibleColums) {\n AbstractColumn col = (AbstractColumn) visibleColum;\n col.setPosX(posx);\n posx += col.getWidth();\n }\n }", "public MembersList<Member> getList(String groupId, Set<String> memberTypes, int perPage, int page) throws FlickrException {\r\n MembersList<Member> members = new MembersList<Member>();\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIST);\r\n\r\n parameters.put(\"group_id\", groupId);\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 if (memberTypes != null) {\r\n parameters.put(\"membertypes\", StringUtilities.join(memberTypes, \",\"));\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 mElement = response.getPayload();\r\n members.setPage(mElement.getAttribute(\"page\"));\r\n members.setPages(mElement.getAttribute(\"pages\"));\r\n members.setPerPage(mElement.getAttribute(\"perpage\"));\r\n members.setTotal(mElement.getAttribute(\"total\"));\r\n\r\n NodeList mNodes = mElement.getElementsByTagName(\"member\");\r\n for (int i = 0; i < mNodes.getLength(); i++) {\r\n Element element = (Element) mNodes.item(i);\r\n members.add(parseMember(element));\r\n }\r\n return members;\r\n }", "public Map<String, String> getSitePath() {\n\n if (m_sitePaths == null) {\n m_sitePaths = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n public Object transform(Object rootPath) {\n\n if (rootPath instanceof String) {\n return getRequestContext().removeSiteRoot((String)rootPath);\n }\n return null;\n }\n });\n }\n return m_sitePaths;\n }", "@Override\n @SuppressFBWarnings(value = \"UL_UNRELEASED_LOCK\", justification = \"False positive from FindBugs\")\n public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {\n if (!isActive()) {\n throw new ContextNotActiveException();\n }\n checkContextInitialized();\n final BeanStore beanStore = getBeanStore();\n if (beanStore == null) {\n return null;\n }\n if (contextual == null) {\n throw ContextLogger.LOG.contextualIsNull();\n }\n BeanIdentifier id = getId(contextual);\n ContextualInstance<T> beanInstance = beanStore.get(id);\n if (beanInstance != null) {\n return beanInstance.getInstance();\n } else if (creationalContext != null) {\n LockedBean lock = null;\n try {\n if (multithreaded) {\n lock = beanStore.lock(id);\n beanInstance = beanStore.get(id);\n if (beanInstance != null) {\n return beanInstance.getInstance();\n }\n }\n T instance = contextual.create(creationalContext);\n if (instance != null) {\n beanInstance = new SerializableContextualInstanceImpl<Contextual<T>, T>(contextual, instance, creationalContext, serviceRegistry.get(ContextualStore.class));\n beanStore.put(id, beanInstance);\n }\n return instance;\n } finally {\n if (lock != null) {\n lock.unlock();\n }\n }\n } else {\n return null;\n }\n }", "public final void setOrientation(int orientation) {\n mOrientation = orientation;\n mOrientationState = getOrientationStateFromParam(mOrientation);\n invalidate();\n if (mOuterAdapter != null) {\n mOuterAdapter.setOrientation(mOrientation);\n }\n\n }", "private void stopDone() {\n synchronized (stopLock) {\n final StopContext stopContext = this.stopContext;\n this.stopContext = null;\n if (stopContext != null) {\n stopContext.complete();\n }\n stopLock.notifyAll();\n }\n }", "public HashMap<String, Object> getFirstResult(String query)\n throws Exception {\n HashMap<String, Object> result = null;\n\n Statement queryStatement = null;\n ResultSet results = null;\n try (Connection sqlConnection = getConnection()) {\n queryStatement = sqlConnection.createStatement();\n results = queryStatement.executeQuery(query);\n if (results.next()) {\n result = new HashMap<>();\n String[] columns = getColumnNames(results.getMetaData());\n\n for (String column : columns) {\n result.put(column, results.getObject(column));\n }\n }\n } catch (Exception e) {\n\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return result;\n }", "private void writeFileCreationRecord() throws IOException\n {\n ProjectProperties properties = m_projectFile.getProjectProperties();\n\n m_buffer.setLength(0);\n m_buffer.append(\"MPX\");\n m_buffer.append(m_delimiter);\n m_buffer.append(properties.getMpxProgramName());\n m_buffer.append(m_delimiter);\n m_buffer.append(properties.getMpxFileVersion());\n m_buffer.append(m_delimiter);\n m_buffer.append(properties.getMpxCodePage());\n m_buffer.append(MPXConstants.EOL);\n m_writer.write(m_buffer.toString());\n }", "public void retrieveProxyCollections(Object newObj, ClassDescriptor cld, boolean forced) throws PersistenceBrokerException\r\n {\r\n doRetrieveCollections(newObj, cld, forced, true);\r\n }" ]
this remove the linebreak. @param input the input @param patternStr the pattern str @return the string
[ "public static String stringMatcherByPattern(String input, String patternStr) {\n\n String output = PcConstants.SYSTEM_FAIL_MATCH_REGEX;\n\n // 20140105: fix the NPE issue\n if (patternStr == null) {\n logger.error(\"patternStr is NULL! (Expected when the aggregation rule is not defined at \"\n + PcDateUtils.getNowDateTimeStrStandard());\n return output;\n }\n\n if (input == null) {\n logger.error(\"input (Expected when the response is null and now try to match on response) is NULL in stringMatcherByPattern() at \"\n + PcDateUtils.getNowDateTimeStrStandard());\n return output;\n } else {\n input = input.replace(\"\\n\", \"\").replace(\"\\r\", \"\");\n }\n\n logger.debug(\"input: \" + input);\n logger.debug(\"patternStr: \" + patternStr);\n\n Pattern patternMetric = Pattern.compile(patternStr, Pattern.MULTILINE);\n\n final Matcher matcher = patternMetric.matcher(input);\n if (matcher.matches()) {\n output = matcher.group(1);\n }\n return output;\n }" ]
[ "private void writeProperties() throws IOException\n {\n writeAttributeTypes(\"property_types\", ProjectField.values());\n writeFields(\"property_values\", m_projectFile.getProjectProperties(), ProjectField.values());\n }", "public Map getPathClasses()\r\n\t{\r\n\t\tif (m_pathClasses.isEmpty())\r\n\t\t{\r\n\t\t\tif (m_parentCriteria == null)\r\n\t\t\t{\r\n\t\t\t\tif (m_query == null)\r\n\t\t\t\t{\r\n\t\t\t\t\treturn m_pathClasses;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\treturn m_query.getPathClasses();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\treturn m_parentCriteria.getPathClasses();\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn m_pathClasses;\r\n\t\t}\r\n\t}", "public static <T extends Annotation> List<T> searchForAnnotation(Method method, Class<T> annotation) {\n if (method == null) {\n return Lists.newArrayList();\n }\n return searchClasses(method, annotation, method.getDeclaringClass());\n }", "public ContentAssistEntry createProposal(final String proposal, final String prefix, final ContentAssistContext context, final String kind, final Procedure1<? super ContentAssistEntry> init) {\n boolean _isValidProposal = this.isValidProposal(proposal, prefix, context);\n if (_isValidProposal) {\n final ContentAssistEntry result = new ContentAssistEntry();\n result.setProposal(proposal);\n result.setPrefix(prefix);\n if ((kind != null)) {\n result.setKind(kind);\n }\n if ((init != null)) {\n init.apply(result);\n }\n return result;\n }\n return null;\n }", "public ByteArray readBytes(int size) throws IOException\n {\n byte[] data = new byte[size];\n m_stream.read(data);\n return new ByteArray(data);\n }", "@SuppressWarnings({\"UnusedDeclaration\"})\n protected void doApi(StaplerRequest req, StaplerResponse resp) throws IOException, ServletException {\n try {\n log.log(Level.INFO, \"Initiating Artifactory Release Staging using API\");\n // Enforce release permissions\n project.checkPermission(ArtifactoryPlugin.RELEASE);\n // In case a staging user plugin is configured, the init() method invoke it:\n init();\n // Read the values provided by the staging user plugin and assign them to data members in this class.\n // Those values can be overriden by URL arguments sent with the API:\n readStagingPluginValues();\n // Read values from the request and override the staging plugin values:\n overrideStagingPluginParams(req);\n // Schedule the release build:\n Queue.WaitingItem item = Jenkins.getInstance().getQueue().schedule(\n project, 0,\n new Action[]{this, new CauseAction(new Cause.UserIdCause())}\n );\n if (item == null) {\n log.log(Level.SEVERE, \"Failed to schedule a release build following a Release API invocation\");\n resp.setStatus(StaplerResponse.SC_INTERNAL_SERVER_ERROR);\n } else {\n String url = req.getContextPath() + '/' + item.getUrl();\n JSONObject json = new JSONObject();\n json.element(\"queueItem\", item.getId());\n json.element(\"releaseVersion\", getReleaseVersion());\n json.element(\"nextVersion\", getNextVersion());\n json.element(\"releaseBranch\", getReleaseBranch());\n // Must use getOutputStream as sendRedirect uses getOutputStream (and closes it)\n resp.getOutputStream().print(json.toString());\n resp.sendRedirect(201, url);\n }\n } catch (Exception e) {\n log.log(Level.SEVERE, \"Artifactory Release Staging API invocation failed: \" + e.getMessage(), e);\n resp.setStatus(StaplerResponse.SC_INTERNAL_SERVER_ERROR);\n ErrorResponse errorResponse = new ErrorResponse(StaplerResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());\n ObjectMapper mapper = new ObjectMapper();\n mapper.enable(SerializationFeature.INDENT_OUTPUT);\n resp.getWriter().write(mapper.writeValueAsString(errorResponse));\n }\n }", "void backupConfiguration() throws IOException {\n\n final String configuration = Constants.CONFIGURATION;\n\n final File a = new File(installedImage.getAppClientDir(), configuration);\n final File d = new File(installedImage.getDomainDir(), configuration);\n final File s = new File(installedImage.getStandaloneDir(), configuration);\n\n if (a.exists()) {\n final File ab = new File(configBackup, Constants.APP_CLIENT);\n backupDirectory(a, ab);\n }\n if (d.exists()) {\n final File db = new File(configBackup, Constants.DOMAIN);\n backupDirectory(d, db);\n }\n if (s.exists()) {\n final File sb = new File(configBackup, Constants.STANDALONE);\n backupDirectory(s, sb);\n }\n\n }", "protected static PatchElement createRollbackElement(final PatchEntry entry) {\n final PatchElement patchElement = entry.element;\n final String patchId;\n final Patch.PatchType patchType = patchElement.getProvider().getPatchType();\n if (patchType == Patch.PatchType.CUMULATIVE) {\n patchId = entry.getCumulativePatchID();\n } else {\n patchId = patchElement.getId();\n }\n return createPatchElement(entry, patchId, entry.rollbackActions);\n }", "public static GVRCameraRig makeInstance(GVRContext gvrContext) {\n final GVRCameraRig result = gvrContext.getApplication().getDelegate().makeCameraRig(gvrContext);\n result.init(gvrContext);\n return result;\n }" ]
Retrieve list of resource extended attributes. @return list of extended attributes
[ "private List<ResourceField> getAllResourceExtendedAttributes()\n {\n ArrayList<ResourceField> result = new ArrayList<ResourceField>();\n result.addAll(Arrays.asList(ResourceFieldLists.CUSTOM_TEXT));\n result.addAll(Arrays.asList(ResourceFieldLists.CUSTOM_START));\n result.addAll(Arrays.asList(ResourceFieldLists.CUSTOM_FINISH));\n result.addAll(Arrays.asList(ResourceFieldLists.CUSTOM_COST));\n result.addAll(Arrays.asList(ResourceFieldLists.CUSTOM_DATE));\n result.addAll(Arrays.asList(ResourceFieldLists.CUSTOM_FLAG));\n result.addAll(Arrays.asList(ResourceFieldLists.CUSTOM_NUMBER));\n result.addAll(Arrays.asList(ResourceFieldLists.CUSTOM_DURATION));\n result.addAll(Arrays.asList(ResourceFieldLists.CUSTOM_OUTLINE_CODE));\n result.addAll(Arrays.asList(ResourceFieldLists.ENTERPRISE_COST));\n result.addAll(Arrays.asList(ResourceFieldLists.ENTERPRISE_DATE));\n result.addAll(Arrays.asList(ResourceFieldLists.ENTERPRISE_DURATION));\n result.addAll(Arrays.asList(ResourceFieldLists.ENTERPRISE_FLAG));\n result.addAll(Arrays.asList(ResourceFieldLists.ENTERPRISE_NUMBER));\n result.addAll(Arrays.asList(ResourceFieldLists.ENTERPRISE_TEXT));\n return result;\n }" ]
[ "protected String getIsolationLevelAsString()\r\n {\r\n if (defaultIsolationLevel == IL_READ_UNCOMMITTED)\r\n {\r\n return LITERAL_IL_READ_UNCOMMITTED;\r\n }\r\n else if (defaultIsolationLevel == IL_READ_COMMITTED)\r\n {\r\n return LITERAL_IL_READ_COMMITTED;\r\n }\r\n else if (defaultIsolationLevel == IL_REPEATABLE_READ)\r\n {\r\n return LITERAL_IL_REPEATABLE_READ;\r\n }\r\n else if (defaultIsolationLevel == IL_SERIALIZABLE)\r\n {\r\n return LITERAL_IL_SERIALIZABLE;\r\n }\r\n else if (defaultIsolationLevel == IL_OPTIMISTIC)\r\n {\r\n return LITERAL_IL_OPTIMISTIC;\r\n }\r\n return LITERAL_IL_READ_UNCOMMITTED;\r\n }", "public boolean deleteExisting(final File file) {\n if (!file.exists()) {\n return true;\n }\n boolean deleted = false;\n if (file.canWrite()) {\n deleted = file.delete();\n } else {\n LogLog.debug(file + \" is not writeable for delete (retrying)\");\n }\n if (!deleted) {\n if (!file.exists()) {\n deleted = true;\n } else {\n file.delete();\n deleted = (!file.exists());\n }\n }\n return deleted;\n }", "public <T> void setState(HttpConnectionInterceptor interceptor, String stateName, T\n stateObjectToStore) {\n Map<String, Object> state = interceptorStates.get(interceptor);\n if (state == null) {\n interceptorStates.put(interceptor, (state = new ConcurrentHashMap<String, Object>()));\n }\n state.put(stateName, stateObjectToStore);\n }", "synchronized void asyncReconnect(final URI reconnectUri, String authKey, final ReconnectCallback callback) {\n if (getState() != State.OPEN) {\n return;\n }\n // Update the configuration with the new credentials\n final ProtocolConnectionConfiguration config = ProtocolConnectionConfiguration.copy(configuration);\n config.setCallbackHandler(createClientCallbackHandler(userName, authKey));\n config.setUri(reconnectUri);\n this.configuration = config;\n\n final ReconnectRunner reconnectTask = this.reconnectRunner;\n if (reconnectTask == null) {\n final ReconnectRunner task = new ReconnectRunner();\n task.callback = callback;\n task.future = executorService.submit(task);\n } else {\n reconnectTask.callback = callback;\n }\n }", "private List<Row> getRows(String tableName, String columnName, Integer id)\n {\n List<Row> result;\n List<Row> table = m_tables.get(tableName);\n if (table == null)\n {\n result = Collections.<Row> emptyList();\n }\n else\n {\n if (columnName == null)\n {\n result = table;\n }\n else\n {\n result = new LinkedList<Row>();\n for (Row row : table)\n {\n if (NumberHelper.equals(id, row.getInteger(columnName)))\n {\n result.add(row);\n }\n }\n }\n }\n return result;\n }", "private void handleDirectory(final Predicate<String> filter, final File rootDir, final List<String> discoveredFiles)\n {\n try\n {\n new DirectoryWalker<String>()\n {\n private Path startDir;\n\n public void walk() throws IOException\n {\n this.startDir = rootDir.toPath();\n this.walk(rootDir, discoveredFiles);\n }\n\n @Override\n protected void handleFile(File file, int depth, Collection<String> discoveredFiles) throws IOException\n {\n String newPath = startDir.relativize(file.toPath()).toString();\n if (filter.accept(newPath))\n discoveredFiles.add(newPath);\n }\n\n }.walk();\n }\n catch (IOException ex)\n {\n LOG.log(Level.SEVERE, \"Error reading Furnace addon directory\", ex);\n }\n }", "public void update(int number) {\n byte[] numberInBytes = new byte[ByteUtils.SIZE_OF_INT];\n ByteUtils.writeInt(numberInBytes, number, 0);\n update(numberInBytes);\n }", "public boolean isAssociation(String targetTypeName, List<String> pathWithoutAlias) {\n\t\tOgmEntityPersister persister = getPersister( targetTypeName );\n\t\tType propertyType = persister.getPropertyType( pathWithoutAlias.get( 0 ) );\n\t\treturn propertyType.isAssociationType();\n\t}", "public List<NodeValue<K, V>> getRepairs(List<NodeValue<K, V>> nodeValues) {\n int size = nodeValues.size();\n if(size <= 1)\n return Collections.emptyList();\n\n Map<K, List<NodeValue<K, V>>> keyToNodeValues = Maps.newHashMap();\n for(NodeValue<K, V> nodeValue: nodeValues) {\n List<NodeValue<K, V>> keyNodeValues = keyToNodeValues.get(nodeValue.getKey());\n if(keyNodeValues == null) {\n keyNodeValues = Lists.newArrayListWithCapacity(5);\n keyToNodeValues.put(nodeValue.getKey(), keyNodeValues);\n }\n keyNodeValues.add(nodeValue);\n }\n\n List<NodeValue<K, V>> result = Lists.newArrayList();\n for(List<NodeValue<K, V>> keyNodeValues: keyToNodeValues.values())\n result.addAll(singleKeyGetRepairs(keyNodeValues));\n return result;\n }" ]
Use this API to add snmpmanager.
[ "public static base_response add(nitro_service client, snmpmanager resource) throws Exception {\n\t\tsnmpmanager addresource = new snmpmanager();\n\t\taddresource.ipaddress = resource.ipaddress;\n\t\taddresource.netmask = resource.netmask;\n\t\taddresource.domainresolveretry = resource.domainresolveretry;\n\t\treturn addresource.add_resource(client);\n\t}" ]
[ "public void appointTempoMaster(int deviceNumber) throws IOException {\n final DeviceUpdate update = getLatestStatusFor(deviceNumber);\n if (update == null) {\n throw new IllegalArgumentException(\"Device \" + deviceNumber + \" not found on network.\");\n }\n appointTempoMaster(update);\n }", "public static <E> Set<E> union(Set<E> s1, Set<E> s2) {\r\n Set<E> s = new HashSet<E>();\r\n s.addAll(s1);\r\n s.addAll(s2);\r\n return s;\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}", "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 boolean isObjectsFieldValueDefault(Object object) throws SQLException {\n\t\tObject fieldValue = extractJavaFieldValue(object);\n\t\treturn isFieldValueDefault(fieldValue);\n\t}", "@SuppressWarnings(\"WeakerAccess\")\n public ByteBuffer getRawData() {\n if (rawData != null) {\n rawData.rewind();\n return rawData.slice();\n }\n return null;\n }", "public static rewritepolicy_csvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\trewritepolicy_csvserver_binding obj = new rewritepolicy_csvserver_binding();\n\t\tobj.set_name(name);\n\t\trewritepolicy_csvserver_binding response[] = (rewritepolicy_csvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "@Nullable public GeoTarget getCanonAncestor(GeoTarget.Type type) {\n for (GeoTarget target = this; target != null; target = target.canonParent()) {\n if (target.key.type == type) {\n return target;\n }\n }\n\n return null;\n }", "private String getBearerToken(HttpConnectionInterceptorContext context) {\n final AtomicReference<String> iamTokenResponse = new AtomicReference<String>();\n boolean result = super.requestCookie(context, iamServerUrl, iamTokenRequestBody,\n \"application/x-www-form-urlencoded\", \"application/json\",\n new StoreBearerCallable(iamTokenResponse));\n if (result) {\n return iamTokenResponse.get();\n } else {\n return null;\n }\n }" ]
Use this API to unset the properties of onlinkipv6prefix resources. Properties that need to be unset are specified in args array.
[ "public static base_responses unset(nitro_service client, onlinkipv6prefix resources[], String[] args) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tonlinkipv6prefix unsetresources[] = new onlinkipv6prefix[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tunsetresources[i] = new onlinkipv6prefix();\n\t\t\t\tunsetresources[i].ipv6prefix = resources[i].ipv6prefix;\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}" ]
[ "private FieldDescriptorDef cloneField(FieldDescriptorDef fieldDef, String prefix)\r\n {\r\n FieldDescriptorDef copyFieldDef = new FieldDescriptorDef(fieldDef, prefix);\r\n\r\n copyFieldDef.setOwner(this);\r\n // we remove properties that are only relevant to the class the features are declared in\r\n copyFieldDef.setProperty(PropertyHelper.OJB_PROPERTY_IGNORE, null);\r\n\r\n Properties mod = getModification(copyFieldDef.getName());\r\n\r\n if (mod != null)\r\n {\r\n if (!PropertyHelper.toBoolean(mod.getProperty(PropertyHelper.OJB_PROPERTY_IGNORE), false) &&\r\n hasFeature(copyFieldDef.getName()))\r\n {\r\n LogHelper.warn(true,\r\n ClassDescriptorDef.class,\r\n \"process\",\r\n \"Class \"+getName()+\" has a feature that has the same name as its included field \"+\r\n copyFieldDef.getName()+\" from class \"+fieldDef.getOwner().getName()); \r\n }\r\n copyFieldDef.applyModifications(mod);\r\n }\r\n return copyFieldDef;\r\n }", "void portForward(final Patch patch, IdentityPatchContext context) throws PatchingException, IOException, XMLStreamException {\n assert patch.getIdentity().getPatchType() == Patch.PatchType.CUMULATIVE;\n\n final PatchingHistory history = context.getHistory();\n for (final PatchElement element : patch.getElements()) {\n\n final PatchElementProvider provider = element.getProvider();\n final String name = provider.getName();\n final boolean addOn = provider.isAddOn();\n\n final IdentityPatchContext.PatchEntry target = context.resolveForElement(element);\n final String cumulativePatchID = target.getCumulativePatchID();\n if (Constants.BASE.equals(cumulativePatchID)) {\n reenableRolledBackInBase(target);\n continue;\n }\n\n boolean found = false;\n final PatchingHistory.Iterator iterator = history.iterator();\n while (iterator.hasNextCP()) {\n final PatchingHistory.Entry entry = iterator.nextCP();\n final String patchId = addOn ? entry.getAddOnPatches().get(name) : entry.getLayerPatches().get(name);\n\n if (patchId != null && patchId.equals(cumulativePatchID)) {\n final Patch original = loadPatchInformation(entry.getPatchId(), installedImage);\n for (final PatchElement originalElement : original.getElements()) {\n if (name.equals(originalElement.getProvider().getName())\n && addOn == originalElement.getProvider().isAddOn()) {\n PatchingTasks.addMissingModifications(target, originalElement.getModifications(), ContentItemFilter.ALL_BUT_MISC);\n }\n }\n // Record a loader to have access to the current modules\n final DirectoryStructure structure = target.getDirectoryStructure();\n final File modulesRoot = structure.getModulePatchDirectory(patchId);\n final File bundlesRoot = structure.getBundlesPatchDirectory(patchId);\n final PatchContentLoader loader = PatchContentLoader.create(null, bundlesRoot, modulesRoot);\n context.recordContentLoader(patchId, loader);\n found = true;\n break;\n }\n }\n if (!found) {\n throw PatchLogger.ROOT_LOGGER.patchNotFoundInHistory(cumulativePatchID);\n }\n\n reenableRolledBackInBase(target);\n }\n }", "@Deprecated\n @SuppressWarnings(\"deprecation\")\n public void push(String eventName, HashMap<String, Object> chargeDetails,\n ArrayList<HashMap<String, Object>> items)\n throws InvalidEventNameException {\n // This method is for only charged events\n if (!eventName.equals(Constants.CHARGED_EVENT)) {\n throw new InvalidEventNameException(\"Not a charged event\");\n }\n CleverTapAPI cleverTapAPI = weakReference.get();\n if(cleverTapAPI == null){\n Logger.d(\"CleverTap Instance is null.\");\n } else {\n cleverTapAPI.pushChargedEvent(chargeDetails, items);\n }\n }", "public <T> Map<String, List<T>> queryGroups(String query, Class<T> classOfT) {\r\n InputStream instream = null;\r\n try {\r\n Reader reader = new InputStreamReader(instream = queryForStream(query), \"UTF-8\");\r\n JsonObject json = new JsonParser().parse(reader).getAsJsonObject();\r\n Map<String, List<T>> result = new LinkedHashMap<String, List<T>>();\r\n if (json.has(\"groups\")) {\r\n for (JsonElement e : json.getAsJsonArray(\"groups\")) {\r\n String groupName = e.getAsJsonObject().get(\"by\").getAsString();\r\n List<T> orows = new ArrayList<T>();\r\n if (!includeDocs) {\r\n log.warning(\"includeDocs set to false and attempting to retrieve doc. \" +\r\n \"null object will be returned\");\r\n }\r\n for (JsonElement rows : e.getAsJsonObject().getAsJsonArray(\"rows\")) {\r\n orows.add(jsonToObject(client.getGson(), rows, \"doc\", classOfT));\r\n }\r\n result.put(groupName, orows);\r\n }// end for(groups)\r\n }// end hasgroups\r\n else {\r\n log.warning(\"No grouped results available. Use query() if non grouped query\");\r\n }\r\n return result;\r\n } catch (UnsupportedEncodingException e1) {\r\n // This should never happen as every implementation of the java platform is required\r\n // to support UTF-8.\r\n throw new RuntimeException(e1);\r\n } finally {\r\n close(instream);\r\n }\r\n }", "public static String getHeaders(HttpServletResponse response) {\n String headerString = \"\";\n Collection<String> headerNames = response.getHeaderNames();\n for (String headerName : headerNames) {\n // there may be multiple headers per header name\n for (String headerValue : response.getHeaders(headerName)) {\n if (headerString.length() != 0) {\n headerString += \"\\n\";\n }\n\n headerString += headerName + \": \" + headerValue;\n }\n }\n\n return headerString;\n }", "public void setKeywords(final List<String> keywords) {\n StringBuilder builder = new StringBuilder();\n for (String keyword: keywords) {\n if (builder.length() > 0) {\n builder.append(',');\n }\n builder.append(keyword.trim());\n }\n this.keywords = Optional.of(builder.toString());\n }", "public long countByLex(final LexRange lexRange) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.zlexcount(getKey(), lexRange.from(), lexRange.to());\n }\n });\n }", "public static int cudnnLRNCrossChannelBackward(\n cudnnHandle handle, \n cudnnLRNDescriptor normDesc, \n int lrnMode, \n Pointer alpha, \n cudnnTensorDescriptor yDesc, \n Pointer y, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor dxDesc, \n Pointer dx)\n {\n return checkResult(cudnnLRNCrossChannelBackwardNative(handle, normDesc, lrnMode, alpha, yDesc, y, dyDesc, dy, xDesc, x, beta, dxDesc, dx));\n }", "private boolean activityIsMilestone(Activity activity)\n {\n String type = activity.getType();\n return type != null && type.indexOf(\"Milestone\") != -1;\n }" ]
Adds the HIBC prefix and check digit to the specified data, returning the resultant data string. @see <a href="https://sourceforge.net/p/zint/code/ci/master/tree/backend/library.c">Corresponding Zint code</a>
[ "private String hibcProcess(String source) {\n\n // HIBC 2.6 allows up to 110 characters, not including the \"+\" prefix or the check digit\n if (source.length() > 110) {\n throw new OkapiException(\"Data too long for HIBC LIC\");\n }\n\n source = source.toUpperCase();\n if (!source.matches(\"[A-Z0-9-\\\\. \\\\$/+\\\\%]+?\")) {\n throw new OkapiException(\"Invalid characters in input\");\n }\n\n int counter = 41;\n for (int i = 0; i < source.length(); i++) {\n counter += positionOf(source.charAt(i), HIBC_CHAR_TABLE);\n }\n counter = counter % 43;\n\n char checkDigit = HIBC_CHAR_TABLE[counter];\n\n encodeInfo += \"HIBC Check Digit Counter: \" + counter + \"\\n\";\n encodeInfo += \"HIBC Check Digit: \" + checkDigit + \"\\n\";\n\n return \"+\" + source + checkDigit;\n }" ]
[ "private void writeTask(Task task) throws IOException\n {\n writeFields(null, task, TaskField.values());\n for (Task child : task.getChildTasks())\n {\n writeTask(child);\n }\n }", "public static final String getString(byte[] data, int offset)\n {\n return getString(data, offset, data.length - offset);\n }", "public void unload()\n {\n if (mAudioListener != null)\n {\n Log.d(\"SOUND\", \"unloading audio source %d %s\", getSourceId(), getSoundFile());\n mAudioListener.getAudioEngine().unloadSoundFile(getSoundFile());\n }\n mSoundFile = null;\n mSourceId = GvrAudioEngine.INVALID_ID;\n }", "public static byte[] getBytes(String string, String encoding) {\n try {\n return string.getBytes(encoding);\n } catch(UnsupportedEncodingException e) {\n throw new IllegalArgumentException(encoding + \" is not a known encoding name.\", e);\n }\n }", "public void addModuleDir(final String moduleDir) {\n if (moduleDir == null) {\n throw LauncherMessages.MESSAGES.nullParam(\"moduleDir\");\n }\n // Validate the path\n final Path path = Paths.get(moduleDir).normalize();\n modulesDirs.add(path.toString());\n }", "@Inline(value = \"$1.remove($2.getKey(), $2.getValue())\", statementExpression = true)\n\tpublic static <K, V> boolean operator_remove(Map<K, V> map, Pair<? extends K, ? extends V> entry) {\n\t\t//TODO use the JRE 1.8 API: map.remove(entry.getKey(), entry.getValue());\n\t\tfinal K key = entry.getKey();\n\t\tfinal V storedValue = map.get(entry.getKey());\n\t if (!Objects.equal(storedValue, entry.getValue())\n\t\t\t|| (storedValue == null && !map.containsKey(key))) {\n\t return false;\n \t}\n \tmap.remove(key);\n\t return true;\n\t}", "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 }", "protected boolean shouldApplyThisRuleTo(ClassNode classNode) {\r\n // TODO Consider caching applyTo, doNotApplyTo and associated WildcardPatterns\r\n boolean shouldApply = true;\r\n\r\n String applyTo = getApplyToClassNames();\r\n String doNotApplyTo = getDoNotApplyToClassNames();\r\n\r\n if (applyTo != null && applyTo.length() > 0) {\r\n WildcardPattern pattern = new WildcardPattern(applyTo, true);\r\n shouldApply = pattern.matches(classNode.getNameWithoutPackage()) || pattern.matches(classNode.getName());\r\n }\r\n\r\n if (shouldApply && doNotApplyTo != null && doNotApplyTo.length() > 0) {\r\n WildcardPattern pattern = new WildcardPattern(doNotApplyTo, true);\r\n shouldApply = !pattern.matches(classNode.getNameWithoutPackage()) && !pattern.matches(classNode.getName());\r\n }\r\n\r\n return shouldApply;\r\n }", "public void putAll(Map<KEY, VALUE> mapDataToPut) {\n int targetSize = maxSize - mapDataToPut.size();\n if (maxSize > 0 && values.size() > targetSize) {\n evictToTargetSize(targetSize);\n }\n Set<Entry<KEY, VALUE>> entries = mapDataToPut.entrySet();\n for (Entry<KEY, VALUE> entry : entries) {\n put(entry.getKey(), entry.getValue());\n }\n }" ]
Retrieve an instance of the ResourceField class based on the data read from an MPX file. @param value value from an MS Project file @return instance of this class
[ "public static ResourceField getMpxjField(int value)\n {\n ResourceField result = null;\n\n if (value >= 0 && value < MPX_MPXJ_ARRAY.length)\n {\n result = MPX_MPXJ_ARRAY[value];\n }\n\n return (result);\n }" ]
[ "private static void parseDockers(JSONObject modelJSON,\n Shape current) throws JSONException {\n if (modelJSON.has(\"dockers\")) {\n ArrayList<Point> dockers = new ArrayList<Point>();\n\n JSONArray dockersObject = modelJSON.getJSONArray(\"dockers\");\n for (int i = 0; i < dockersObject.length(); i++) {\n Double x = dockersObject.getJSONObject(i).getDouble(\"x\");\n Double y = dockersObject.getJSONObject(i).getDouble(\"y\");\n dockers.add(new Point(x,\n y));\n }\n if (dockers.size() > 0) {\n current.setDockers(dockers);\n }\n }\n }", "public ImmutableList<CandidateElement> extract(StateVertex currentState)\n\t\t\tthrows CrawljaxException {\n\t\tLinkedList<CandidateElement> results = new LinkedList<>();\n\n\t\tif (!checkedElements.checkCrawlCondition(browser)) {\n\t\t\tLOG.info(\"State {} did not satisfy the CrawlConditions.\", currentState.getName());\n\t\t\treturn ImmutableList.of();\n\t\t}\n\t\tLOG.debug(\"Looking in state: {} for candidate elements\", currentState.getName());\n\n\t\ttry {\n\t\t\tDocument dom = DomUtils.asDocument(browser.getStrippedDomWithoutIframeContent());\n\t\t\textractElements(dom, results, \"\");\n\t\t} catch (IOException e) {\n\t\t\tLOG.error(e.getMessage(), e);\n\t\t\tthrow new CrawljaxException(e);\n\t\t}\n\t\tif (randomizeElementsOrder) {\n\t\t\tCollections.shuffle(results);\n\t\t}\n\t\tcurrentState.setElementsFound(results);\n\t\tLOG.debug(\"Found {} new candidate elements to analyze!\", results.size());\n\t\treturn ImmutableList.copyOf(results);\n\t}", "@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 HashSet<String> getDataById(String id) throws IOException {\n if (idToVersion.containsKey(id)) {\n return get(id);\n } else {\n return null;\n }\n }", "public void abort()\r\n {\r\n /*\r\n do nothing if already rolledback\r\n */\r\n if (txStatus == Status.STATUS_NO_TRANSACTION\r\n || txStatus == Status.STATUS_UNKNOWN\r\n || txStatus == Status.STATUS_ROLLEDBACK)\r\n {\r\n log.info(\"Nothing to abort, tx is not active - status is \" + TxUtil.getStatusString(txStatus));\r\n return;\r\n }\r\n // check status of tx\r\n if (txStatus != Status.STATUS_ACTIVE && txStatus != Status.STATUS_PREPARED &&\r\n txStatus != Status.STATUS_MARKED_ROLLBACK)\r\n {\r\n throw new IllegalStateException(\"Illegal state for abort call, state was '\" + TxUtil.getStatusString(txStatus) + \"'\");\r\n }\r\n if(log.isEnabledFor(Logger.INFO))\r\n {\r\n log.info(\"Abort transaction was called on tx \" + this);\r\n }\r\n try\r\n {\r\n try\r\n {\r\n doAbort();\r\n }\r\n catch(Exception e)\r\n {\r\n log.error(\"Error while abort transaction, will be skipped\", e);\r\n }\r\n\r\n // used in managed environments, ignored in non-managed\r\n this.implementation.getTxManager().abortExternalTx(this);\r\n\r\n try\r\n {\r\n if(hasBroker() && getBroker().isInTransaction())\r\n {\r\n getBroker().abortTransaction();\r\n }\r\n }\r\n catch(Exception e)\r\n {\r\n log.error(\"Error while do abort used broker instance, will be skipped\", e);\r\n }\r\n }\r\n finally\r\n {\r\n txStatus = Status.STATUS_ROLLEDBACK;\r\n // cleanup things, e.g. release all locks\r\n doClose();\r\n }\r\n }", "public float getNormalX(int vertex) {\n if (!hasNormals()) {\n throw new IllegalStateException(\"mesh has no normals\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_normals.getFloat(vertex * 3 * SIZEOF_FLOAT);\n }", "private <T> void add(EjbDescriptor<T> ejbDescriptor) {\n InternalEjbDescriptor<T> internalEjbDescriptor = InternalEjbDescriptor.of(ejbDescriptor);\n ejbByName.put(ejbDescriptor.getEjbName(), internalEjbDescriptor);\n ejbByClass.put(ejbDescriptor.getBeanClass(), internalEjbDescriptor.getEjbName());\n }", "private String resolveExpressionString(final String unresolvedString) throws OperationFailedException {\n\n // parseAndResolve should only be providing expressions with no leading or trailing chars\n assert unresolvedString.startsWith(\"${\") && unresolvedString.endsWith(\"}\");\n\n // Default result is no change from input\n String result = unresolvedString;\n\n ModelNode resolveNode = new ModelNode(new ValueExpression(unresolvedString));\n\n // Try plug-in resolution; i.e. vault\n resolvePluggableExpression(resolveNode);\n\n if (resolveNode.getType() == ModelType.EXPRESSION ) {\n // resolvePluggableExpression did nothing. Try standard resolution\n String resolvedString = resolveStandardExpression(resolveNode);\n if (!unresolvedString.equals(resolvedString)) {\n // resolveStandardExpression made progress\n result = resolvedString;\n } // else there is nothing more we can do with this string\n } else {\n // resolvePluggableExpression made progress\n result = resolveNode.asString();\n }\n\n return result;\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 }" ]
Use this API to unset the properties of clusterinstance resource. Properties that need to be unset are specified in args array.
[ "public static base_response unset(nitro_service client, clusterinstance resource, String[] args) throws Exception{\n\t\tclusterinstance unsetresource = new clusterinstance();\n\t\tunsetresource.clid = resource.clid;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}" ]
[ "private Integer getIntegerPropertyOverrideValue(String name, String key) {\n if (properties != null) {\n String propertyName = getPropertyName(name, key);\n\n String propertyOverrideValue = properties.getProperty(propertyName);\n\n if (propertyOverrideValue != null) {\n try {\n return Integer.parseInt(propertyOverrideValue);\n }\n catch (NumberFormatException e) {\n logger.error(\"Could not parse property override key={}, value={}\",\n key, propertyOverrideValue);\n }\n }\n }\n return null;\n }", "private Map<String, String> getContentsByContainerName(\n CmsContainerElementBean element,\n Collection<CmsContainer> containers) {\n\n CmsFormatterConfiguration configs = getFormatterConfiguration(element.getResource());\n Map<String, String> result = new HashMap<String, String>();\n for (CmsContainer container : containers) {\n String content = getContentByContainer(element, container, configs);\n if (content != null) {\n content = removeScriptTags(content);\n }\n result.put(container.getName(), content);\n }\n return result;\n }", "public String[] getUrl() {\n String[] valueDestination = new String[ url.size() ];\n this.url.getValue(valueDestination);\n return valueDestination;\n }", "private void removeTimedOutLocks(long timeout)\r\n {\r\n int count = 0;\r\n long maxAge = System.currentTimeMillis() - timeout;\r\n boolean breakFromLoop = false;\r\n ObjectLocks temp = null;\r\n \tsynchronized (locktable)\r\n \t{\r\n\t Iterator it = locktable.values().iterator();\r\n\t /**\r\n\t * run this loop while:\r\n\t * - we have more in the iterator\r\n\t * - the breakFromLoop flag hasn't been set\r\n\t * - we haven't removed more than the limit for this cleaning iteration.\r\n\t */\r\n\t while (it.hasNext() && !breakFromLoop && (count <= MAX_LOCKS_TO_CLEAN))\r\n\t {\r\n\t \ttemp = (ObjectLocks) it.next();\r\n\t \tif (temp.getWriter() != null)\r\n\t \t{\r\n\t\t \tif (temp.getWriter().getTimestamp() < maxAge)\r\n\t\t \t{\r\n\t\t \t\t// writer has timed out, set it to null\r\n\t\t \t\ttemp.setWriter(null);\r\n\t\t \t}\r\n\t \t}\r\n\t \tif (temp.getYoungestReader() < maxAge)\r\n\t \t{\r\n\t \t\t// all readers are older than timeout.\r\n\t \t\ttemp.getReaders().clear();\r\n\t \t\tif (temp.getWriter() == null)\r\n\t \t\t{\r\n\t \t\t\t// all readers and writer are older than timeout,\r\n\t \t\t\t// remove the objectLock from the iterator (which\r\n\t \t\t\t// is backed by the map, so it will be removed.\r\n\t \t\t\tit.remove();\r\n\t \t\t}\r\n\t \t}\r\n\t \telse\r\n\t \t{\r\n\t \t\t// we need to walk each reader.\r\n\t \t\tIterator readerIt = temp.getReaders().values().iterator();\r\n\t \t\tLockEntry readerLock = null;\r\n\t \t\twhile (readerIt.hasNext())\r\n\t \t\t{\r\n\t \t\t\treaderLock = (LockEntry) readerIt.next();\r\n\t \t\t\tif (readerLock.getTimestamp() < maxAge)\r\n\t \t\t\t{\r\n\t \t\t\t\t// this read lock is old, remove it.\r\n\t \t\t\t\treaderIt.remove();\r\n\t \t\t\t}\r\n\t \t\t}\r\n\t \t}\r\n\t \tcount++;\r\n\t }\r\n \t}\r\n }", "private static String preparePlaceHolders(int length) {\n StringBuilder builder = new StringBuilder();\n for (int i = 0; i < length; ) {\n builder.append(\"?\");\n if (++i < length) {\n builder.append(\",\");\n }\n }\n return builder.toString();\n }", "public Future<HazeltaskTask<GROUP>> addPendingTaskAsync(HazeltaskTask<GROUP> task) {\n return pendingTask.putAsync(task.getId(), task);\n }", "public boolean needMerge(@NotNull final BasePage left, @NotNull final BasePage right) {\n final int leftSize = left.getSize();\n final int rightSize = right.getSize();\n return leftSize == 0 || rightSize == 0 ||\n leftSize + rightSize <= (((isDupTree(left) ? getDupPageMaxSize() : getPageMaxSize()) * 7) >> 3);\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 static ResourceField getInstance(int value)\n {\n ResourceField result = null;\n\n if (value >= 0 && value < FIELD_ARRAY.length)\n {\n result = FIELD_ARRAY[value];\n }\n else\n {\n if ((value & 0x8000) != 0)\n {\n int baseValue = ResourceField.ENTERPRISE_CUSTOM_FIELD1.getValue();\n int id = baseValue + (value & 0xFFF);\n result = ResourceField.getInstance(id);\n }\n }\n\n return (result);\n }" ]
Send a sync command to all registered listeners. @param command the byte which identifies the type of sync command we received
[ "private void deliverSyncCommand(byte command) {\n for (final SyncListener listener : getSyncListeners()) {\n try {\n switch (command) {\n\n case 0x01:\n listener.becomeMaster();\n\n case 0x10:\n listener.setSyncMode(true);\n break;\n\n case 0x20:\n listener.setSyncMode(false);\n break;\n\n }\n } catch (Throwable t) {\n logger.warn(\"Problem delivering sync command to listener\", t);\n }\n }\n }" ]
[ "public void delete(Object element, boolean testForEquality) {\r\n\tint index = indexOfFromTo(element, 0, size-1, testForEquality);\r\n\tif (index>=0) removeFromTo(index,index);\r\n}", "@Deprecated public Duration getDuration(String calendarName, Date startDate, Date endDate) throws MPXJException\n {\n ProjectCalendar calendar = getCalendarByName(calendarName);\n\n if (calendar == null)\n {\n throw new MPXJException(MPXJException.CALENDAR_ERROR + \": \" + calendarName);\n }\n\n return (calendar.getDuration(startDate, endDate));\n }", "public DefaultStreamingEndpoint languages(List<String> languages) {\n addPostParameter(Constants.LANGUAGE_PARAM, Joiner.on(',').join(languages));\n return this;\n }", "public static base_response update(nitro_service client, cmpparameter resource) throws Exception {\n\t\tcmpparameter updateresource = new cmpparameter();\n\t\tupdateresource.cmplevel = resource.cmplevel;\n\t\tupdateresource.quantumsize = resource.quantumsize;\n\t\tupdateresource.servercmp = resource.servercmp;\n\t\tupdateresource.heurexpiry = resource.heurexpiry;\n\t\tupdateresource.heurexpirythres = resource.heurexpirythres;\n\t\tupdateresource.heurexpiryhistwt = resource.heurexpiryhistwt;\n\t\tupdateresource.minressize = resource.minressize;\n\t\tupdateresource.cmpbypasspct = resource.cmpbypasspct;\n\t\tupdateresource.cmponpush = resource.cmponpush;\n\t\tupdateresource.policytype = resource.policytype;\n\t\tupdateresource.addvaryheader = resource.addvaryheader;\n\t\tupdateresource.externalcache = resource.externalcache;\n\t\treturn updateresource.update_resource(client);\n\t}", "public void writeLock(EntityKey key, int timeout) {\n\t\tReadWriteLock lock = getLock( key );\n\t\tLock writeLock = lock.writeLock();\n\t\tacquireLock( key, timeout, writeLock );\n\t}", "public void cache(Identity oid, Object obj)\r\n {\r\n try\r\n {\r\n jcsCache.put(oid.toString(), obj);\r\n }\r\n catch (CacheException e)\r\n {\r\n throw new RuntimeCacheException(e);\r\n }\r\n }", "private Map<String, String> fillInitialVariables() {\r\n Map<String, TransitionTarget> targets = model.getChildren();\n\r\n Set<String> variables = new HashSet<>();\r\n for (TransitionTarget target : targets.values()) {\r\n OnEntry entry = target.getOnEntry();\r\n List<Action> actions = entry.getActions();\r\n for (Action action : actions) {\r\n if (action instanceof Assign) {\r\n String variable = ((Assign) action).getName();\r\n variables.add(variable);\r\n } else if (action instanceof SetAssignExtension.SetAssignTag) {\r\n String variable = ((SetAssignExtension.SetAssignTag) action).getName();\r\n variables.add(variable);\r\n }\r\n }\r\n }\n\r\n Map<String, String> result = new HashMap<>();\r\n for (String variable : variables) {\r\n result.put(variable, \"\");\r\n }\n\r\n return result;\r\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 }", "private Map<ConfigurationKey, Object> getObsoleteSystemProperties() {\n Map<ConfigurationKey, Object> found = new EnumMap<ConfigurationKey, Object>(ConfigurationKey.class);\n String concurrentDeployment = getSystemProperty(\"org.jboss.weld.bootstrap.properties.concurrentDeployment\");\n if (concurrentDeployment != null) {\n processKeyValue(found, ConfigurationKey.CONCURRENT_DEPLOYMENT, concurrentDeployment);\n found.put(ConfigurationKey.CONCURRENT_DEPLOYMENT, ConfigurationKey.CONCURRENT_DEPLOYMENT.convertValue(concurrentDeployment));\n }\n String preloaderThreadPoolSize = getSystemProperty(\"org.jboss.weld.bootstrap.properties.preloaderThreadPoolSize\");\n if (preloaderThreadPoolSize != null) {\n found.put(ConfigurationKey.PRELOADER_THREAD_POOL_SIZE, ConfigurationKey.PRELOADER_THREAD_POOL_SIZE.convertValue(preloaderThreadPoolSize));\n }\n return found;\n }" ]
Convert a name into initials. @param name source name @return initials
[ "private String getInitials(String name)\n {\n String result = null;\n\n if (name != null && name.length() != 0)\n {\n StringBuilder sb = new StringBuilder();\n sb.append(name.charAt(0));\n int index = 1;\n while (true)\n {\n index = name.indexOf(' ', index);\n if (index == -1)\n {\n break;\n }\n\n ++index;\n if (index < name.length() && name.charAt(index) != ' ')\n {\n sb.append(name.charAt(index));\n }\n\n ++index;\n }\n\n result = sb.toString();\n }\n\n return result;\n }" ]
[ "public int executeTask(final TransactionalProtocolClient.TransactionalOperationListener<ServerOperation> listener, final ServerUpdateTask task) {\n try {\n return execute(listener, task.getServerIdentity(), task.getOperation());\n } catch (OperationFailedException e) {\n // Handle failures operation transformation failures\n final ServerIdentity identity = task.getServerIdentity();\n final ServerOperation serverOperation = new ServerOperation(identity, task.getOperation(), null, null, OperationResultTransformer.ORIGINAL_RESULT);\n final TransactionalProtocolClient.PreparedOperation<ServerOperation> result = BlockingQueueOperationListener.FailedOperation.create(serverOperation, e);\n listener.operationPrepared(result);\n recordExecutedRequest(new ExecutedServerRequest(identity, result.getFinalResult(), OperationResultTransformer.ORIGINAL_RESULT));\n return 1; // 1 ms timeout since there is no reason to wait for the locally stored result\n }\n\n }", "public void removeAllChildren() {\n for (final GVRSceneObject so : headTransformObject.getChildren()) {\n final boolean notCamera = (so != leftCameraObject && so != rightCameraObject && so != centerCameraObject);\n if (notCamera) {\n headTransformObject.removeChildObject(so);\n }\n }\n }", "double getThreshold(String x, String y, double p) {\r\n\t\treturn 2 * Math.max(x.length(), y.length()) * (1 - p);\r\n\t}", "public static vpnclientlessaccesspolicy_binding get(nitro_service service, String name) throws Exception{\n\t\tvpnclientlessaccesspolicy_binding obj = new vpnclientlessaccesspolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnclientlessaccesspolicy_binding response = (vpnclientlessaccesspolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static GVRCameraRig makeInstance(GVRContext gvrContext) {\n final GVRCameraRig result = gvrContext.getApplication().getDelegate().makeCameraRig(gvrContext);\n result.init(gvrContext);\n return result;\n }", "public boolean isHoliday(String dateString) {\n boolean isHoliday = false;\n for (Holiday date : EquivalenceClassTransformer.HOLIDAYS) {\n if (convertToReadableDate(date.forYear(Integer.parseInt(dateString.substring(0, 4)))).equals(dateString)) {\n isHoliday = true;\n }\n }\n return isHoliday;\n }", "private IndexedContainer createContainerForBundleWithoutDescriptor() throws IOException, CmsException {\n\n IndexedContainer container = new IndexedContainer();\n\n // create properties\n container.addContainerProperty(TableProperty.KEY, String.class, \"\");\n container.addContainerProperty(TableProperty.TRANSLATION, String.class, \"\");\n\n // add entries\n SortedProperties localization = getLocalization(m_locale);\n Set<Object> keySet = m_keyset.getKeySet();\n for (Object key : keySet) {\n\n Object itemId = container.addItem();\n Item item = container.getItem(itemId);\n item.getItemProperty(TableProperty.KEY).setValue(key);\n Object translation = localization.get(key);\n item.getItemProperty(TableProperty.TRANSLATION).setValue(null == translation ? \"\" : translation);\n }\n\n return container;\n }", "public static base_response flush(nitro_service client, nssimpleacl resource) throws Exception {\n\t\tnssimpleacl flushresource = new nssimpleacl();\n\t\tflushresource.estsessions = resource.estsessions;\n\t\treturn flushresource.perform_operation(client,\"flush\");\n\t}", "public GVRComponent detachComponent(long type) {\n NativeSceneObject.detachComponent(getNative(), type);\n synchronized (mComponents) {\n GVRComponent component = mComponents.remove(type);\n if (component != null) {\n component.setOwnerObject(null);\n }\n return component;\n }\n }" ]
Creates a simple deployment description. @param name the name for the deployment @param serverGroups the server groups @return the deployment description
[ "public static SimpleDeploymentDescription of(final String name, @SuppressWarnings(\"TypeMayBeWeakened\") final Set<String> serverGroups) {\n final SimpleDeploymentDescription result = of(name);\n if (serverGroups != null) {\n result.addServerGroups(serverGroups);\n }\n return result;\n }" ]
[ "public static base_responses enable(nitro_service client, Long clid[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (clid != null && clid.length > 0) {\n\t\t\tclusterinstance enableresources[] = new clusterinstance[clid.length];\n\t\t\tfor (int i=0;i<clid.length;i++){\n\t\t\t\tenableresources[i] = new clusterinstance();\n\t\t\t\tenableresources[i].clid = clid[i];\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, enableresources,\"enable\");\n\t\t}\n\t\treturn result;\n\t}", "@Override\n public void setDraggable(Element elem, String draggable) {\n super.setDraggable(elem, draggable);\n if (\"true\".equals(draggable)) {\n elem.getStyle().setProperty(\"webkitUserDrag\", \"element\");\n } else {\n elem.getStyle().clearProperty(\"webkitUserDrag\");\n }\n }", "public static base_responses unset(nitro_service client, String selectorname[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (selectorname != null && selectorname.length > 0) {\n\t\t\tnslimitselector unsetresources[] = new nslimitselector[selectorname.length];\n\t\t\tfor (int i=0;i<selectorname.length;i++){\n\t\t\t\tunsetresources[i] = new nslimitselector();\n\t\t\t\tunsetresources[i].selectorname = selectorname[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}", "@Pure\n\tpublic static <K, V> Map<K, V> operator_minus(Map<K, V> left, final Pair<? extends K, ? extends V> right) {\n\t\treturn Maps.filterEntries(left, new Predicate<Entry<K, V>>() {\n\t\t\t@Override\n\t\t\tpublic boolean apply(Entry<K, V> input) {\n\t\t\t\treturn !Objects.equal(input.getKey(), right.getKey()) || !Objects.equal(input.getValue(), right.getValue());\n\t\t\t}\n\t\t});\n\t}", "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 }", "protected boolean hasTimeOutHeader() {\n\n boolean result = false;\n String timeoutValStr = this.request.getHeader(RestMessageHeaders.X_VOLD_REQUEST_TIMEOUT_MS);\n if(timeoutValStr != null) {\n try {\n this.parsedTimeoutInMs = Long.parseLong(timeoutValStr);\n if(this.parsedTimeoutInMs < 0) {\n RestErrorHandler.writeErrorResponse(messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Time out cannot be negative \");\n\n } else {\n result = true;\n }\n } catch(NumberFormatException nfe) {\n logger.error(\"Exception when validating request. Incorrect timeout parameter. Cannot parse this to long: \"\n + timeoutValStr,\n nfe);\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Incorrect timeout parameter. Cannot parse this to long: \"\n + timeoutValStr);\n }\n } else {\n logger.error(\"Error when validating request. Missing timeout parameter.\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Missing timeout parameter.\");\n }\n return result;\n }", "protected static String ConvertBinaryOperator(int oper)\r\n {\r\n // Convert the operator into the proper string\r\n String oper_string;\r\n switch (oper)\r\n {\r\n default:\r\n case EQUAL:\r\n oper_string = \"=\";\r\n break;\r\n case LIKE:\r\n oper_string = \"LIKE\";\r\n break;\r\n case NOT_EQUAL:\r\n oper_string = \"!=\";\r\n break;\r\n case LESS_THAN:\r\n oper_string = \"<\";\r\n break;\r\n case GREATER_THAN:\r\n oper_string = \">\";\r\n break;\r\n case GREATER_EQUAL:\r\n oper_string = \">=\";\r\n break;\r\n case LESS_EQUAL:\r\n oper_string = \"<=\";\r\n break;\r\n }\r\n return oper_string;\r\n }", "protected String adaptFilePath(String filePath) {\n // Convert windows file path to target FS\n String targetPath = filePath.replaceAll(\"\\\\\\\\\", volumeType.getSeparator());\n\n return targetPath;\n }", "private void setPlaybackPosition(long milliseconds) {\n PlaybackState oldState = currentSimpleState();\n if (oldState != null && oldState.position != milliseconds) {\n setPlaybackState(oldState.player, milliseconds, oldState.playing);\n }\n }" ]
Finds the column with the largest normal and makes that the first column @param j Current column being inspected
[ "protected void swapColumns( int j ) {\n\n // find the column with the largest norm\n int largestIndex = j;\n double largestNorm = normsCol[j];\n for( int col = j+1; col < numCols; col++ ) {\n double n = normsCol[col];\n if( n > largestNorm ) {\n largestNorm = n;\n largestIndex = col;\n }\n }\n // swap the columns\n double []tempC = dataQR[j];\n dataQR[j] = dataQR[largestIndex];\n dataQR[largestIndex] = tempC;\n double tempN = normsCol[j];\n normsCol[j] = normsCol[largestIndex];\n normsCol[largestIndex] = tempN;\n int tempP = pivots[j];\n pivots[j] = pivots[largestIndex];\n pivots[largestIndex] = tempP;\n }" ]
[ "private void ensureCollectionClass(CollectionDescriptorDef collDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n if (collDef.hasProperty(PropertyHelper.OJB_PROPERTY_ARRAY_ELEMENT_CLASS_REF))\r\n {\r\n // an array cannot have a collection-class specified \r\n if (collDef.hasProperty(PropertyHelper.OJB_PROPERTY_COLLECTION_CLASS))\r\n {\r\n throw new ConstraintException(\"Collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" is an array but does specify collection-class\");\r\n }\r\n else\r\n {\r\n // no further processing necessary as its an array\r\n return;\r\n }\r\n }\r\n\r\n if (CHECKLEVEL_STRICT.equals(checkLevel))\r\n { \r\n InheritanceHelper helper = new InheritanceHelper();\r\n ModelDef model = (ModelDef)collDef.getOwner().getOwner();\r\n String specifiedClass = collDef.getProperty(PropertyHelper.OJB_PROPERTY_COLLECTION_CLASS);\r\n String variableType = collDef.getProperty(PropertyHelper.OJB_PROPERTY_VARIABLE_TYPE);\r\n \r\n try\r\n {\r\n if (specifiedClass != null)\r\n {\r\n // if we have a specified class then it has to implement the manageable collection and be a sub type of the variable type\r\n if (!helper.isSameOrSubTypeOf(specifiedClass, variableType))\r\n {\r\n throw new ConstraintException(\"The type \"+specifiedClass+\" specified as collection-class of the collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" is not a sub type of the variable type \"+variableType);\r\n }\r\n if (!helper.isSameOrSubTypeOf(specifiedClass, MANAGEABLE_COLLECTION_INTERFACE))\r\n {\r\n throw new ConstraintException(\"The type \"+specifiedClass+\" specified as collection-class of the collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" does not implement \"+MANAGEABLE_COLLECTION_INTERFACE);\r\n }\r\n }\r\n else\r\n {\r\n // no collection class specified so the variable type has to be a collection type\r\n if (helper.isSameOrSubTypeOf(variableType, MANAGEABLE_COLLECTION_INTERFACE))\r\n {\r\n // we can specify it as a collection-class as it is an manageable collection\r\n collDef.setProperty(PropertyHelper.OJB_PROPERTY_COLLECTION_CLASS, variableType);\r\n }\r\n else if (!helper.isSameOrSubTypeOf(variableType, JAVA_COLLECTION_INTERFACE))\r\n {\r\n throw new ConstraintException(\"The collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" needs the collection-class attribute as its variable type does not implement \"+JAVA_COLLECTION_INTERFACE);\r\n }\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"Could not find the class \"+ex.getMessage()+\" on the classpath while checking the collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName());\r\n }\r\n }\r\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}", "protected static boolean createLoggingAction(final Logger logger, final Logger auditor, final TransactionLogger instance) {\n TransactionLogger oldInstance = getInstance();\n if (oldInstance == null || oldInstance.finished) {\n if(loggingKeys == null) {\n synchronized (TransactionLogger.class) {\n if (loggingKeys == null) {\n logger.info(\"Initializing 'LoggingKeysHandler' class\");\n loggingKeys = new LoggingKeysHandler(keysPropStream);\n }\n }\n }\n initInstance(instance, logger, auditor);\n setInstance(instance);\n return true;\n }\n return false; // Really not sure it can happen - since we arrive here in a new thread of transaction I think it's ThreadLocal should be empty. But leaving this code just in case...\n }", "public void pushDryRun() throws Exception {\n if (releaseAction.isCreateVcsTag()) {\n if (scmManager.isTagExists(scmManager.getRemoteConfig(releaseAction.getTargetRemoteName()), releaseAction.getTagUrl())) {\n throw new Exception(String.format(\"Tag with name '%s' already exists\", releaseAction.getTagUrl()));\n }\n }\n\n String testTagName = releaseAction.getTagUrl() + \"_test\";\n try {\n scmManager.testPush(scmManager.getRemoteConfig(releaseAction.getTargetRemoteName()), testTagName);\n } catch (Exception e) {\n throw new Exception(String.format(\"Failed while attempting push dry-run: %s\", e.getMessage()), e);\n } finally {\n if (scmManager.isTagExists(scmManager.getRemoteConfig(releaseAction.getTargetRemoteName()), testTagName)) {\n scmManager.deleteLocalTag(testTagName);\n }\n }\n }", "public long queryForLong(DatabaseConnection databaseConnection, PreparedStmt<T> preparedStmt) throws SQLException {\n\t\tCompiledStatement compiledStatement = preparedStmt.compile(databaseConnection, StatementType.SELECT_LONG);\n\t\tDatabaseResults results = null;\n\t\ttry {\n\t\t\tresults = compiledStatement.runQuery(null);\n\t\t\tif (results.first()) {\n\t\t\t\treturn results.getLong(0);\n\t\t\t} else {\n\t\t\t\tthrow new SQLException(\"No result found in queryForLong: \" + preparedStmt.getStatement());\n\t\t\t}\n\t\t} finally {\n\t\t\tIOUtils.closeThrowSqlException(results, \"results\");\n\t\t\tIOUtils.closeThrowSqlException(compiledStatement, \"compiled statement\");\n\t\t}\n\t}", "PatchEntry getEntry(final String name, boolean addOn) {\n return addOn ? addOns.get(name) : layers.get(name);\n }", "public float getChildSize(final int dataIndex, final Axis axis) {\n float size = 0;\n Widget child = mContainer.get(dataIndex);\n if (child != null) {\n switch (axis) {\n case X:\n size = child.getLayoutWidth();\n break;\n case Y:\n size = child.getLayoutHeight();\n break;\n case Z:\n size = child.getLayoutDepth();\n break;\n default:\n throw new RuntimeAssertion(\"Bad axis specified: %s\", axis);\n }\n }\n return size;\n }", "public static base_response update(nitro_service client, aaaparameter resource) throws Exception {\n\t\taaaparameter updateresource = new aaaparameter();\n\t\tupdateresource.enablestaticpagecaching = resource.enablestaticpagecaching;\n\t\tupdateresource.enableenhancedauthfeedback = resource.enableenhancedauthfeedback;\n\t\tupdateresource.defaultauthtype = resource.defaultauthtype;\n\t\tupdateresource.maxaaausers = resource.maxaaausers;\n\t\tupdateresource.maxloginattempts = resource.maxloginattempts;\n\t\tupdateresource.failedlogintimeout = resource.failedlogintimeout;\n\t\tupdateresource.aaadnatip = resource.aaadnatip;\n\t\treturn updateresource.update_resource(client);\n\t}", "private String registerEventHandler(GFXEventHandler h) {\n //checkInitialized();\n if (!registeredOnJS) {\n JSObject doc = (JSObject) runtime.execute(\"document\");\n doc.setMember(\"jsHandlers\", jsHandlers);\n registeredOnJS = true;\n }\n return jsHandlers.registerHandler(h);\n }" ]
Notifies that a content item is removed. @param position the position.
[ "public final void notifyContentItemRemoved(int position) {\n if (position < 0 || position >= contentItemCount) {\n throw new IndexOutOfBoundsException(\"The given position \" + position\n + \" is not within the position bounds for content items [0 - \"\n + (contentItemCount - 1) + \"].\");\n }\n notifyItemRemoved(position + headerItemCount);\n }" ]
[ "public static Multimap<String, String> getParameters(final String rawQuery) {\n Multimap<String, String> result = HashMultimap.create();\n if (rawQuery == null) {\n return result;\n }\n\n StringTokenizer tokens = new StringTokenizer(rawQuery, \"&\");\n while (tokens.hasMoreTokens()) {\n String pair = tokens.nextToken();\n int pos = pair.indexOf('=');\n String key;\n String value;\n if (pos == -1) {\n key = pair;\n value = \"\";\n } else {\n\n try {\n key = URLDecoder.decode(pair.substring(0, pos), \"UTF-8\");\n value = URLDecoder.decode(pair.substring(pos + 1), \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }\n\n result.put(key, value);\n }\n return result;\n }", "protected AbstractColumn buildSimpleColumn() {\n\t\tSimpleColumn column = new SimpleColumn();\n\t\tpopulateCommonAttributes(column);\n\t\tcolumnProperty.getFieldProperties().putAll(fieldProperties);\n\t\tcolumn.setColumnProperty(columnProperty);\n\t\tcolumn.setExpressionToGroupBy(customExpressionToGroupBy);\n\t\tcolumn.setFieldDescription(fieldDescription);\n\t\treturn column;\n\t}", "public int tally() {\n long currentTimeMillis = clock.currentTimeMillis();\n\n // calculates time for which we remove any errors before\n final long removeTimesBeforeMillis = currentTimeMillis - windowMillis;\n\n synchronized (queue) {\n // drain out any expired timestamps but don't drain past empty\n while (!queue.isEmpty() && queue.peek() < removeTimesBeforeMillis) {\n queue.removeFirst();\n }\n return queue.size();\n }\n }", "private long interpolateTimeSinceUpdate(TrackPositionUpdate update, long currentTimestamp) {\n if (!update.playing) {\n return update.milliseconds;\n }\n long elapsedMillis = (currentTimestamp - update.timestamp) / 1000000;\n long moved = Math.round(update.pitch * elapsedMillis);\n if (update.reverse) {\n return update.milliseconds - moved;\n }\n return update.milliseconds + moved;\n }", "public static base_response flush(nitro_service client, nssimpleacl resource) throws Exception {\n\t\tnssimpleacl flushresource = new nssimpleacl();\n\t\tflushresource.estsessions = resource.estsessions;\n\t\treturn flushresource.perform_operation(client,\"flush\");\n\t}", "protected void appendWhereClause(ClassDescriptor cld, boolean useLocking, StringBuffer stmt)\r\n {\r\n FieldDescriptor[] pkFields = cld.getPkFields();\r\n FieldDescriptor[] fields;\r\n\r\n fields = pkFields;\r\n if(useLocking)\r\n {\r\n FieldDescriptor[] lockingFields = cld.getLockingFields();\r\n if(lockingFields.length > 0)\r\n {\r\n fields = new FieldDescriptor[pkFields.length + lockingFields.length];\r\n System.arraycopy(pkFields, 0, fields, 0, pkFields.length);\r\n System.arraycopy(lockingFields, 0, fields, pkFields.length, lockingFields.length);\r\n }\r\n }\r\n\r\n appendWhereClause(fields, stmt);\r\n }", "private Duration convertFormat(long totalTime, TimeUnit format)\n {\n double duration = totalTime;\n\n switch (format)\n {\n case MINUTES:\n case ELAPSED_MINUTES:\n {\n duration /= (60 * 1000);\n break;\n }\n\n case HOURS:\n case ELAPSED_HOURS:\n {\n duration /= (60 * 60 * 1000);\n break;\n }\n\n case DAYS:\n {\n double minutesPerDay = getMinutesPerDay();\n if (minutesPerDay != 0)\n {\n duration /= (minutesPerDay * 60 * 1000);\n }\n else\n {\n duration = 0;\n }\n break;\n }\n\n case WEEKS:\n {\n double minutesPerWeek = getMinutesPerWeek();\n if (minutesPerWeek != 0)\n {\n duration /= (minutesPerWeek * 60 * 1000);\n }\n else\n {\n duration = 0;\n }\n break;\n }\n\n case MONTHS:\n {\n double daysPerMonth = getParentFile().getProjectProperties().getDaysPerMonth().doubleValue();\n double minutesPerDay = getMinutesPerDay();\n if (daysPerMonth != 0 && minutesPerDay != 0)\n {\n duration /= (daysPerMonth * minutesPerDay * 60 * 1000);\n }\n else\n {\n duration = 0;\n }\n break;\n }\n\n case ELAPSED_DAYS:\n {\n duration /= (24 * 60 * 60 * 1000);\n break;\n }\n\n case ELAPSED_WEEKS:\n {\n duration /= (7 * 24 * 60 * 60 * 1000);\n break;\n }\n\n case ELAPSED_MONTHS:\n {\n duration /= (30 * 24 * 60 * 60 * 1000);\n break;\n }\n\n default:\n {\n throw new IllegalArgumentException(\"TimeUnit \" + format + \" not supported\");\n }\n }\n\n return (Duration.getInstance(duration, format));\n }", "private void validate(Object object) {\n\t\tSet<ConstraintViolation<Object>> viols = validator.validate(object);\n\t\tfor (ConstraintViolation<Object> constraintViolation : viols) {\n\t\t\tif (Null.class.isAssignableFrom(constraintViolation.getConstraintDescriptor().getAnnotation().getClass())) {\n\t\t\t\tObject o = constraintViolation.getLeafBean();\n\t\t\t\tIterator<Node> iterator = constraintViolation.getPropertyPath().iterator();\n\t\t\t\tString propertyName = null;\n\t\t\t\twhile (iterator.hasNext()) {\n\t\t\t\t\tpropertyName = iterator.next().getName();\n\t\t\t\t}\n\t\t\t\tif (propertyName != null) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tPropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(o.getClass(), propertyName);\n\t\t\t\t\t\tdescriptor.getWriteMethod().invoke(o, new Object[] { null });\n\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "public static base_response update(nitro_service client, nsacl6 resource) throws Exception {\n\t\tnsacl6 updateresource = new nsacl6();\n\t\tupdateresource.acl6name = resource.acl6name;\n\t\tupdateresource.aclaction = resource.aclaction;\n\t\tupdateresource.srcipv6 = resource.srcipv6;\n\t\tupdateresource.srcipop = resource.srcipop;\n\t\tupdateresource.srcipv6val = resource.srcipv6val;\n\t\tupdateresource.srcport = resource.srcport;\n\t\tupdateresource.srcportop = resource.srcportop;\n\t\tupdateresource.srcportval = resource.srcportval;\n\t\tupdateresource.destipv6 = resource.destipv6;\n\t\tupdateresource.destipop = resource.destipop;\n\t\tupdateresource.destipv6val = resource.destipv6val;\n\t\tupdateresource.destport = resource.destport;\n\t\tupdateresource.destportop = resource.destportop;\n\t\tupdateresource.destportval = resource.destportval;\n\t\tupdateresource.srcmac = resource.srcmac;\n\t\tupdateresource.protocol = resource.protocol;\n\t\tupdateresource.protocolnumber = resource.protocolnumber;\n\t\tupdateresource.icmptype = resource.icmptype;\n\t\tupdateresource.icmpcode = resource.icmpcode;\n\t\tupdateresource.vlan = resource.vlan;\n\t\tupdateresource.Interface = resource.Interface;\n\t\tupdateresource.priority = resource.priority;\n\t\tupdateresource.established = resource.established;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
Reads the current properties for a language. If not already done, the properties are read from the respective file. @param locale the locale for which the localization should be returned. @return the properties. @throws IOException thrown if reading the properties from a file fails. @throws CmsException thrown if reading the properties from a file fails.
[ "private SortedProperties getLocalization(Locale locale) throws IOException, CmsException {\n\n if (null == m_localizations.get(locale)) {\n switch (m_bundleType) {\n case PROPERTY:\n loadLocalizationFromPropertyBundle(locale);\n break;\n case XML:\n loadLocalizationFromXmlBundle(locale);\n break;\n case DESCRIPTOR:\n return null;\n default:\n break;\n }\n }\n return m_localizations.get(locale);\n }" ]
[ "public void updateBuildpackInstallations(String appName, List<String> buildpacks) {\n connection.execute(new BuildpackInstallationUpdate(appName, buildpacks), apiKey);\n }", "public void releaseAll() {\n synchronized(this) {\n Object[] refSet = allocatedMemoryReferences.values().toArray();\n if(refSet.length != 0) {\n logger.finer(\"Releasing allocated memory regions\");\n }\n for(Object ref : refSet) {\n release((MemoryReference) ref);\n }\n }\n }", "private static void validatePseudoScopedBean(Bean<?> bean, BeanManagerImpl beanManager) {\n if (bean.getInjectionPoints().isEmpty()) {\n // Skip validation if there are no injection points (e.g. for classes which are not intended to be used as beans)\n return;\n }\n reallyValidatePseudoScopedBean(bean, beanManager, new LinkedHashSet<Object>(), new HashSet<Bean<?>>());\n }", "public void animate(GVRHybridObject object, float animationTime)\n {\n GVRMeshMorph morph = (GVRMeshMorph) mTarget;\n\n mKeyInterpolator.animate(animationTime * mDuration, mCurrentValues);\n morph.setWeights(mCurrentValues);\n\n }", "public void addChildTaskBefore(Task child, Task previousSibling)\n {\n int index = m_children.indexOf(previousSibling);\n if (index == -1)\n {\n m_children.add(child);\n }\n else\n {\n m_children.add(index, child);\n }\n\n child.m_parent = this;\n setSummary(true);\n\n if (getParentFile().getProjectConfig().getAutoOutlineLevel() == true)\n {\n child.setOutlineLevel(Integer.valueOf(NumberHelper.getInt(getOutlineLevel()) + 1));\n }\n }", "public Task<Void> confirmUser(@NonNull final String token, @NonNull final String tokenId) {\n return dispatcher.dispatchTask(\n new Callable<Void>() {\n @Override\n public Void call() {\n confirmUserInternal(token, tokenId);\n return null;\n }\n });\n }", "public static boolean ensureJedisConnection(final Jedis jedis) {\n final boolean jedisOK = testJedisConnection(jedis);\n if (!jedisOK) {\n try {\n jedis.quit();\n } catch (Exception e) {\n } // Ignore\n try {\n jedis.disconnect();\n } catch (Exception e) {\n } // Ignore\n jedis.connect();\n }\n return jedisOK;\n }", "public static void acceptsFormat(OptionParser parser) {\n parser.accepts(OPT_FORMAT, \"format of key or entry, could be hex, json or binary\")\n .withRequiredArg()\n .describedAs(\"hex | json | binary\")\n .ofType(String.class);\n }", "public static String join(final Collection<?> collection, final String separator) {\n StringBuffer buffer = new StringBuffer();\n boolean first = true;\n Iterator<?> iter = collection.iterator();\n while (iter.hasNext()) {\n Object next = iter.next();\n if (first) {\n first = false;\n } else {\n buffer.append(separator);\n }\n buffer.append(next);\n }\n return buffer.toString();\n }" ]
Returns the full user record for the single user with the provided ID. @param user An identifier for the user. Can be one of an email address, the globally unique identifier for the user, or the keyword `me` to indicate the current user making the request. @return Request object
[ "public ItemRequest<User> findById(String user) {\n \n String path = String.format(\"/users/%s\", user);\n return new ItemRequest<User>(this, User.class, path, \"GET\");\n }" ]
[ "public static base_response unset(nitro_service client, cmpparameter resource, String[] args) throws Exception{\n\t\tcmpparameter unsetresource = new cmpparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "private ProjectFile read() throws Exception\n {\n m_project = new ProjectFile();\n m_eventManager = m_project.getEventManager();\n\n ProjectConfig config = m_project.getProjectConfig();\n config.setAutoCalendarUniqueID(false);\n config.setAutoTaskID(false);\n config.setAutoTaskUniqueID(false);\n config.setAutoResourceUniqueID(false);\n config.setAutoWBS(false);\n config.setAutoOutlineNumber(false);\n\n m_project.getProjectProperties().setFileApplication(\"FastTrack\");\n m_project.getProjectProperties().setFileType(\"FTS\");\n\n m_eventManager.addProjectListeners(m_projectListeners);\n\n // processProject();\n // processCalendars();\n processResources();\n processTasks();\n processDependencies();\n processAssignments();\n\n return m_project;\n }", "public Record findRecordById(String id) {\n if (directory == null)\n init();\n\n Property idprop = config.getIdentityProperties().iterator().next();\n for (Record r : lookup(idprop, id))\n if (r.getValue(idprop.getName()).equals(id))\n return r;\n\n return null; // not found\n }", "public void makePickable(GVRSceneObject sceneObject) {\n try {\n GVRMeshCollider collider = new GVRMeshCollider(sceneObject.getGVRContext(), false);\n sceneObject.attachComponent(collider);\n } catch (Exception e) {\n // Possible that some objects (X3D panel nodes) are without mesh\n Log.e(Log.SUBSYSTEM.INPUT, TAG, \"makePickable(): possible that some objects (X3D panel nodes) are without mesh!\");\n }\n }", "public Object doGetObjectByIdentity(Identity id) throws PersistenceBrokerException\n {\n if (logger.isDebugEnabled()) logger.debug(\"getObjectByIdentity \" + id);\n\n // check if object is present in ObjectCache:\n Object obj = objectCache.lookup(id);\n // only perform a db lookup if necessary (object not cached yet)\n if (obj == null)\n {\n obj = getDBObject(id);\n }\n else\n {\n ClassDescriptor cld = getClassDescriptor(obj.getClass());\n // if specified in the ClassDescriptor the instance must be refreshed\n if (cld.isAlwaysRefresh())\n {\n refreshInstance(obj, id, cld);\n }\n // now refresh all references\n checkRefreshRelationships(obj, id, cld);\n }\n\n // Invoke events on PersistenceBrokerAware instances and listeners\n AFTER_LOOKUP_EVENT.setTarget(obj);\n fireBrokerEvent(AFTER_LOOKUP_EVENT);\n AFTER_LOOKUP_EVENT.setTarget(null);\n\n //logger.info(\"RETRIEVING object \" + obj);\n return obj;\n }", "public StatementBuilder withQualifierValue(PropertyIdValue propertyIdValue,\n\t\t\tValue value) {\n\t\twithQualifier(factory.getValueSnak(propertyIdValue, value));\n\t\treturn getThis();\n\t}", "public static byte[] synchronizeSlaveHostController(ModelNode operation, final PathAddress address, HostFileRepository fileRepository, ContentRepository contentRepository, boolean backup, byte[] oldHash) {\n ModelNode operationContentItem = operation.get(DeploymentAttributes.CONTENT_RESOURCE_ALL.getName()).get(0);\n byte[] newHash = operationContentItem.require(CONTENT_HASH.getName()).asBytes();\n if (needRemoteContent(fileRepository, contentRepository, backup, oldHash)) { // backup DC needs to pull the content\n fileRepository.getDeploymentFiles(ModelContentReference.fromModelAddress(address, newHash));\n }\n return newHash;\n }", "public void addBeanToBeanMapping(BeanToBeanMapping beanToBeanMapping) {\r\n\t\tbeanToBeanMappings.put(ClassPair.get(beanToBeanMapping\r\n\t\t\t\t.getSourceClass(), beanToBeanMapping.getDestinationClass()),\r\n\t\t\t\tbeanToBeanMapping);\r\n\t}", "public static String keyVersionToString(ByteArray key,\n Map<Value, Set<ClusterNode>> versionMap,\n String storeName,\n Integer partitionId) {\n StringBuilder record = new StringBuilder();\n for (Map.Entry<Value, Set<ClusterNode>> versionSet : versionMap.entrySet()) {\n Value value = versionSet.getKey();\n Set<ClusterNode> nodeSet = versionSet.getValue();\n\n record.append(\"BAD_KEY,\");\n record.append(storeName + \",\");\n record.append(partitionId + \",\");\n record.append(ByteUtils.toHexString(key.get()) + \",\");\n record.append(nodeSet.toString().replace(\", \", \";\") + \",\");\n record.append(value.toString());\n }\n return record.toString();\n }" ]
End building the script, adding a return value statement @param config the configuration for the script to build @param value the value to return @return the new {@link LuaScript} instance
[ "public LuaScript endScriptReturn(LuaValue value, LuaScriptConfig config) {\n add(new LuaAstReturnStatement(argument(value)));\n String scriptText = buildScriptText();\n return new BasicLuaScript(scriptText, config);\n }" ]
[ "public T update(T entity) throws RowNotFoundException, OptimisticLockException {\n\n if (!hasPrimaryKey(entity)) {\n throw new RuntimeException(String.format(\"Tried to update entity of type %s without a primary key\", entity\n .getClass().getSimpleName()));\n }\n\n UpdateCreator update = new UpdateCreator(table);\n\n update.whereEquals(idColumn.getColumnName(), getPrimaryKey(entity));\n\n if (versionColumn != null) {\n update.set(versionColumn.getColumnName() + \" = \" + versionColumn.getColumnName() + \" + 1\");\n update.whereEquals(versionColumn.getColumnName(), getVersion(entity));\n }\n\n for (Column column : columns) {\n if (!column.isReadOnly()) {\n update.setValue(column.getColumnName(), getFieldValueAsColumn(entity, column));\n }\n }\n\n int rows = new JdbcTemplate(ormConfig.getDataSource()).update(update);\n\n if (rows == 1) {\n\n if (versionColumn != null) {\n ReflectionUtils.setFieldValue(entity, versionColumn.getFieldName(), getVersion(entity) + 1);\n }\n\n return entity;\n\n } else if (rows > 1) {\n\n throw new RuntimeException(\n String.format(\"Updating table %s with id %s updated %d rows. There must be a mapping problem. Is column %s really the primary key?\",\n table, getPrimaryKey(entity), rows, idColumn));\n\n } else {\n\n //\n // Updated zero rows. This could be because our ID is wrong, or\n // because our object is out-of date. Let's try querying just by ID.\n //\n\n SelectCreator selectById = new SelectCreator()\n .column(\"count(*)\")\n .from(table)\n .whereEquals(idColumn.getColumnName(), getPrimaryKey(entity));\n\n rows = new JdbcTemplate(ormConfig.getDataSource()).query(selectById, new ResultSetExtractor<Integer>() {\n @Override\n public Integer extractData(ResultSet rs) throws SQLException, DataAccessException {\n rs.next();\n return rs.getInt(1);\n }\n });\n\n if (rows == 0) {\n throw new RowNotFoundException(table, getPrimaryKey(entity));\n } else {\n throw new OptimisticLockException(table, getPrimaryKey(entity));\n }\n }\n }", "public void removeOverride(int overrideId, int pathId, Integer ordinal, String clientUUID) {\n // TODO: reorder priorities after removal\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n int enabledId = getEnabledEndpoint(pathId, overrideId, ordinal, clientUUID).getId();\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, enabledId);\n statement.executeUpdate();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "private void writeToFile(List<DomainControllerData> data, String domainName) throws IOException {\n if(domainName == null || data == null) {\n return;\n }\n\n if (conn == null) {\n init();\n }\n\n try {\n String key = S3Util.sanitize(domainName) + \"/\" + S3Util.sanitize(DC_FILE_NAME);\n byte[] buf = S3Util.domainControllerDataToByteBuffer(data);\n S3Object val = new S3Object(buf, null);\n if (usingPreSignedUrls()) {\n Map headers = new TreeMap();\n headers.put(\"x-amz-acl\", Arrays.asList(\"public-read\"));\n conn.put(pre_signed_put_url, val, headers).connection.getResponseMessage();\n } else {\n Map headers = new TreeMap();\n headers.put(\"Content-Type\", Arrays.asList(\"text/plain\"));\n conn.put(location, key, val, headers).connection.getResponseMessage();\n }\n }\n catch(Exception e) {\n throw HostControllerLogger.ROOT_LOGGER.cannotWriteToS3File(e.getLocalizedMessage());\n }\n }", "private Integer getFrequency(Project.Calendars.Calendar.Exceptions.Exception exception)\n {\n Integer period = NumberHelper.getInteger(exception.getPeriod());\n if (period == null)\n {\n period = Integer.valueOf(1);\n }\n return period;\n }", "private void saveToXmlVfsBundle() throws CmsException {\n\n if (m_lockedBundleFiles.get(null) != null) { // If the file was not locked, no changes were made, i.e., storing is not necessary.\n for (Locale l : m_locales) {\n SortedProperties props = m_localizations.get(l);\n if (null != props) {\n if (m_xmlBundle.hasLocale(l)) {\n m_xmlBundle.removeLocale(l);\n }\n m_xmlBundle.addLocale(m_cms, l);\n int i = 0;\n List<Object> keys = new ArrayList<Object>(props.keySet());\n Collections.sort(keys, CmsCaseInsensitiveStringComparator.getInstance());\n for (Object key : keys) {\n if ((null != key) && !key.toString().isEmpty()) {\n String value = props.getProperty(key.toString());\n if (!value.isEmpty()) {\n m_xmlBundle.addValue(m_cms, \"Message\", l, i);\n i++;\n m_xmlBundle.getValue(\"Message[\" + i + \"]/Key\", l).setStringValue(m_cms, key.toString());\n m_xmlBundle.getValue(\"Message[\" + i + \"]/Value\", l).setStringValue(m_cms, value);\n }\n }\n }\n }\n CmsFile bundleFile = m_lockedBundleFiles.get(null).getFile();\n bundleFile.setContents(m_xmlBundle.marshal());\n m_cms.writeFile(bundleFile);\n }\n }\n }", "@UiThread\n protected void parentCollapsedFromViewHolder(int flatParentPosition) {\n ExpandableWrapper<P, C> parentWrapper = mFlatItemList.get(flatParentPosition);\n updateCollapsedParent(parentWrapper, flatParentPosition, true);\n }", "public Map<String, SetAndCount> getAggregateResultFullSummary() {\n\n Map<String, SetAndCount> summaryMap = new ConcurrentHashMap<String, SetAndCount>();\n\n for (Entry<String, LinkedHashSet<String>> entry : aggregateResultMap\n .entrySet()) {\n summaryMap.put(entry.getKey(), new SetAndCount(entry.getValue()));\n }\n\n return summaryMap;\n }", "public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {\n if (!isActive()) {\n throw new ContextNotActiveException();\n }\n if (creationalContext != null) {\n T instance = contextual.create(creationalContext);\n if (creationalContext instanceof WeldCreationalContext<?>) {\n addDependentInstance(instance, contextual, (WeldCreationalContext<T>) creationalContext);\n }\n return instance;\n } else {\n return null;\n }\n }", "@Override\n public void process() {\n if (client.isDone() || executorService.isTerminated()) {\n throw new IllegalStateException(\"Client is already stopped\");\n }\n Runnable runner = new Runnable() {\n @Override\n public void run() {\n try {\n while (!client.isDone()) {\n String msg = messageQueue.take();\n try {\n parseMessage(msg);\n } catch (Exception e) {\n logger.warn(\"Exception thrown during parsing msg \" + msg, e);\n onException(e);\n }\n }\n } catch (Exception e) {\n onException(e);\n }\n }\n };\n\n executorService.execute(runner);\n }" ]
Use this API to update systemuser.
[ "public static base_response update(nitro_service client, systemuser resource) throws Exception {\n\t\tsystemuser updateresource = new systemuser();\n\t\tupdateresource.username = resource.username;\n\t\tupdateresource.password = resource.password;\n\t\tupdateresource.externalauth = resource.externalauth;\n\t\tupdateresource.promptstring = resource.promptstring;\n\t\tupdateresource.timeout = resource.timeout;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
[ "public static String getParentIdFromAgent(Launcher launcher, final String imageID, final String host) throws IOException, InterruptedException {\n return launcher.getChannel().call(new MasterToSlaveCallable<String, IOException>() {\n public String call() throws IOException {\n return DockerUtils.getParentId(imageID, host);\n }\n });\n }", "public T modifyBundle(final String moduleName, final String slot, final byte[] existingHash, final byte[] newHash) {\n final ContentItem item = createBundleItem(moduleName, slot, newHash);\n addContentModification(createContentModification(item, ModificationType.MODIFY, existingHash));\n return returnThis();\n }", "@Override\n public synchronized void resume() {\n this.paused = false;\n ServerActivityCallback listener = listenerUpdater.get(this);\n if (listener != null) {\n listenerUpdater.compareAndSet(this, listener, null);\n }\n while (!taskQueue.isEmpty() && (activeRequestCount < maxRequestCount || maxRequestCount < 0)) {\n runQueuedTask(false);\n }\n }", "okhttp3.Response delete(String url, Map<String, Object> params)\n throws RequestException, LocalOperationException {\n okhttp3.Request request = new okhttp3.Request.Builder()\n .url(getFullUrl(url))\n .delete(getBody(toPayload(params), null))\n .addHeader(\"Transloadit-Client\", version)\n .build();\n\n try {\n return httpClient.newCall(request).execute();\n } catch (IOException e) {\n throw new RequestException(e);\n }\n }", "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 void setMaxConnectionAge(long maxConnectionAge, TimeUnit timeUnit) {\n\t\tthis.maxConnectionAgeInSeconds = TimeUnit.SECONDS.convert(maxConnectionAge, timeUnit);\n\t}", "public void copyTo(int srcOffset, byte[] destArray, int destOffset, int size) {\n int cursor = destOffset;\n for (ByteBuffer bb : toDirectByteBuffers(srcOffset, size)) {\n int bbSize = bb.remaining();\n if ((cursor + bbSize) > destArray.length)\n throw new ArrayIndexOutOfBoundsException(String.format(\"cursor + bbSize = %,d\", cursor + bbSize));\n bb.get(destArray, cursor, bbSize);\n cursor += bbSize;\n }\n }", "private void writeToDelegate(byte[] data) {\n\n if (m_delegateStream != null) {\n try {\n m_delegateStream.write(data);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n }", "public static final String printExtendedAttributeCurrency(Number value)\n {\n return (value == null ? null : NUMBER_FORMAT.get().format(value.doubleValue() * 100));\n }" ]