query
stringlengths
7
3.3k
positive
sequencelengths
1
1
negative
sequencelengths
9
9
Attempts to create a human-readable String representation of the provided rule.
[ "public static String ruleToRuleContentsString(Rule originalRule, int indentLevel)\n {\n if (originalRule instanceof Context && ((Context) originalRule).containsKey(RuleMetadataType.RULE_XML))\n {\n return (String) ((Context) originalRule).get(RuleMetadataType.RULE_XML);\n }\n\n if (!(originalRule instanceof RuleBuilder))\n {\n return wrap(originalRule.toString(), MAX_WIDTH, indentLevel);\n }\n final RuleBuilder rule = (RuleBuilder) originalRule;\n StringBuilder result = new StringBuilder();\n if (indentLevel == 0)\n result.append(\"addRule()\");\n\n for (Condition condition : rule.getConditions())\n {\n String conditionToString = conditionToString(condition, indentLevel + 1);\n if (!conditionToString.isEmpty())\n {\n result.append(System.lineSeparator());\n insertPadding(result, indentLevel + 1);\n result.append(\".when(\").append(wrap(conditionToString, MAX_WIDTH, indentLevel + 2)).append(\")\");\n }\n\n }\n for (Operation operation : rule.getOperations())\n {\n String operationToString = operationToString(operation, indentLevel + 1);\n if (!operationToString.isEmpty())\n {\n result.append(System.lineSeparator());\n insertPadding(result, indentLevel + 1);\n result.append(\".perform(\").append(wrap(operationToString, MAX_WIDTH, indentLevel + 2)).append(\")\");\n }\n }\n if (rule.getId() != null && !rule.getId().isEmpty())\n {\n result.append(System.lineSeparator());\n insertPadding(result, indentLevel);\n result.append(\"withId(\\\"\").append(rule.getId()).append(\"\\\")\");\n }\n\n if (rule.priority() != 0)\n {\n result.append(System.lineSeparator());\n insertPadding(result, indentLevel);\n result.append(\".withPriority(\").append(rule.priority()).append(\")\");\n }\n\n return result.toString();\n }" ]
[ "public void callFunction(String className, String methodName, PluginArguments pluginArgs, Object... args) throws Exception {\n Class<?> cls = getClass(className);\n\n ArrayList<Object> newArgs = new ArrayList<>();\n newArgs.add(pluginArgs);\n com.groupon.odo.proxylib.models.Method m = preparePluginMethod(newArgs, className, methodName, args);\n\n m.getMethod().invoke(cls, newArgs.toArray(new Object[0]));\n }", "private static I_CmsResourceBundle tryBundle(String localizedName) {\n\n I_CmsResourceBundle result = null;\n\n try {\n\n String resourceName = localizedName.replace('.', '/') + \".properties\";\n URL url = CmsResourceBundleLoader.class.getClassLoader().getResource(resourceName);\n\n I_CmsResourceBundle additionalBundle = m_permanentCache.get(localizedName);\n if (additionalBundle != null) {\n result = additionalBundle.getClone();\n } else if (url != null) {\n // the resource was found on the file system\n InputStream is = null;\n String path = CmsFileUtil.normalizePath(url);\n File file = new File(path);\n try {\n // try to load the resource bundle from a file, NOT with the resource loader first\n // this is important since using #getResourceAsStream() may return cached results,\n // for example Tomcat by default does cache all resources loaded by the class loader\n // this means a changed resource bundle file is not loaded\n is = new FileInputStream(file);\n } catch (IOException ex) {\n // this will happen if the resource is contained for example in a .jar file\n is = CmsResourceBundleLoader.class.getClassLoader().getResourceAsStream(resourceName);\n } catch (AccessControlException acex) {\n // fixed bug #1550\n // this will happen if the resource is contained for example in a .jar file\n // and security manager is turned on.\n is = CmsResourceBundleLoader.class.getClassLoader().getResourceAsStream(resourceName);\n }\n if (is != null) {\n result = new CmsPropertyResourceBundle(is);\n }\n }\n } catch (IOException ex) {\n // can't localized these message since this may lead to a chicken-egg problem\n MissingResourceException mre = new MissingResourceException(\n \"Failed to load bundle '\" + localizedName + \"'\",\n localizedName,\n \"\");\n mre.initCause(ex);\n throw mre;\n }\n\n return result;\n }", "private void getSingleValue(Method method, Object object, Map<String, String> map)\n {\n Object value;\n try\n {\n value = filterValue(method.invoke(object));\n }\n catch (Exception ex)\n {\n value = ex.toString();\n }\n\n if (value != null)\n {\n map.put(getPropertyName(method), String.valueOf(value));\n }\n }", "private void addBlock(List<GenericCriteria> list, byte[] block, TestOperator operator)\n {\n GenericCriteria result = new GenericCriteria(m_properties);\n result.setOperator(operator);\n list.add(result);\n processBlock(result.getCriteriaList(), getChildBlock(block));\n processBlock(list, getListNextBlock(block));\n }", "@NonNull public CharSequence getQuery() {\n if (searchView != null) {\n return searchView.getQuery();\n } else if (supportView != null) {\n return supportView.getQuery();\n }\n throw new IllegalStateException(ERROR_NO_SEARCHVIEW);\n }", "public DbInfo info() {\n return client.couchDbClient.get(new DatabaseURIHelper(db.getDBUri()).getDatabaseUri(),\n DbInfo.class);\n }", "void logAuditRecord() {\n trackConfigurationChange();\n if (!auditLogged) {\n try {\n AccessAuditContext accessContext = SecurityActions.currentAccessAuditContext();\n Caller caller = getCaller();\n auditLogger.log(\n isReadOnly(),\n resultAction,\n caller == null ? null : caller.getName(),\n accessContext == null ? null : accessContext.getDomainUuid(),\n accessContext == null ? null : accessContext.getAccessMechanism(),\n accessContext == null ? null : accessContext.getRemoteAddress(),\n getModel(),\n controllerOperations);\n auditLogged = true;\n } catch (Exception e) {\n ControllerLogger.MGMT_OP_LOGGER.failedToUpdateAuditLog(e);\n }\n }\n }", "public <T> void cleanNullReferences(Class<T> clazz) {\n\t\tMap<Object, Reference<Object>> objectMap = getMapForClass(clazz);\n\t\tif (objectMap != null) {\n\t\t\tcleanMap(objectMap);\n\t\t}\n\t}", "protected <H extends EventHandler> HandlerRegistration addHandler(final H handler, GwtEvent.Type<H> type) {\r\n\r\n return ensureHandlers().addHandlerToSource(type, this, handler);\r\n }" ]
Use this API to fetch filtered set of vpnglobal_auditnslogpolicy_binding resources. set the filter parameter values in filtervalue object.
[ "public static vpnglobal_auditnslogpolicy_binding[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tvpnglobal_auditnslogpolicy_binding obj = new vpnglobal_auditnslogpolicy_binding();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tvpnglobal_auditnslogpolicy_binding[] response = (vpnglobal_auditnslogpolicy_binding[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}" ]
[ "protected void processOutlineCodeField(Integer entityID, Row row)\n {\n processField(row, \"OC_FIELD_ID\", entityID, row.getString(\"OC_NAME\"));\n }", "public static void installDomainConnectorServices(final OperationContext context,\n final ServiceTarget serviceTarget,\n final ServiceName endpointName,\n final ServiceName networkInterfaceBinding,\n final int port,\n final OptionMap options,\n final ServiceName securityRealm,\n final ServiceName saslAuthenticationFactory,\n final ServiceName sslContext) {\n String sbmCap = \"org.wildfly.management.socket-binding-manager\";\n ServiceName sbmName = context.hasOptionalCapability(sbmCap, NATIVE_MANAGEMENT_RUNTIME_CAPABILITY.getName(), null)\n ? context.getCapabilityServiceName(sbmCap, SocketBindingManager.class) : null;\n installConnectorServicesForNetworkInterfaceBinding(serviceTarget, endpointName, MANAGEMENT_CONNECTOR,\n networkInterfaceBinding, port, options, securityRealm, saslAuthenticationFactory, sslContext, sbmName);\n }", "public static long count(nitro_service service, Long td) throws Exception{\n\t\tnstrafficdomain_bridgegroup_binding obj = new nstrafficdomain_bridgegroup_binding();\n\t\tobj.set_td(td);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tnstrafficdomain_bridgegroup_binding response[] = (nstrafficdomain_bridgegroup_binding[]) obj.get_resources(service,option);\n\t\tif (response != null) {\n\t\t\treturn response[0].__count;\n\t\t}\n\t\treturn 0;\n\t}", "public static ScheduledExecutorService newScheduledDaemonThreadPool(int corePoolSize) {\n return Executors.newScheduledThreadPool(corePoolSize, r -> {\n Thread t = Executors.defaultThreadFactory().newThread(r);\n t.setDaemon(true);\n return t;\n });\n }", "public static base_responses add(nitro_service client, sslcertkey resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslcertkey addresources[] = new sslcertkey[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new sslcertkey();\n\t\t\t\taddresources[i].certkey = resources[i].certkey;\n\t\t\t\taddresources[i].cert = resources[i].cert;\n\t\t\t\taddresources[i].key = resources[i].key;\n\t\t\t\taddresources[i].password = resources[i].password;\n\t\t\t\taddresources[i].fipskey = resources[i].fipskey;\n\t\t\t\taddresources[i].inform = resources[i].inform;\n\t\t\t\taddresources[i].passplain = resources[i].passplain;\n\t\t\t\taddresources[i].expirymonitor = resources[i].expirymonitor;\n\t\t\t\taddresources[i].notificationperiod = resources[i].notificationperiod;\n\t\t\t\taddresources[i].bundle = resources[i].bundle;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "private static void tryWritePreferenceOnDisk(Preferences preference) throws BackingStoreException {\n final String DUMMY_PROP=\"dummywrite\";\n instance.put(DUMMY_PROP,\"test\");\n instance.flush();\n instance.remove(DUMMY_PROP);\n instance.flush();\n }", "private void countEntity() {\n\t\tif (!this.timer.isRunning()) {\n\t\t\tstartTimer();\n\t\t}\n\n\t\tthis.entityCount++;\n\t\tif (this.entityCount % 100 == 0) {\n\t\t\ttimer.stop();\n\t\t\tint seconds = (int) (timer.getTotalWallTime() / 1000000000);\n\t\t\tif (seconds >= this.lastSeconds + this.reportInterval) {\n\t\t\t\tthis.lastSeconds = seconds;\n\t\t\t\tprintStatus();\n\t\t\t\tif (this.timeout > 0 && seconds > this.timeout) {\n\t\t\t\t\tlogger.info(\"Timeout. Aborting processing.\");\n\t\t\t\t\tthrow new TimeoutException();\n\t\t\t\t}\n\t\t\t}\n\t\t\ttimer.start();\n\t\t}\n\t}", "public static DMatrixRMaj[] splitIntoVectors(DMatrix1Row A , boolean column )\n {\n int w = column ? A.numCols : A.numRows;\n\n int M = column ? A.numRows : 1;\n int N = column ? 1 : A.numCols;\n\n int o = Math.max(M,N);\n\n DMatrixRMaj[] ret = new DMatrixRMaj[w];\n\n for( int i = 0; i < w; i++ ) {\n DMatrixRMaj a = new DMatrixRMaj(M,N);\n\n if( column )\n subvector(A,0,i,o,false,0,a);\n else\n subvector(A,i,0,o,true,0,a);\n\n ret[i] = a;\n }\n\n return ret;\n }", "public String toIPTC(SubjectReferenceSystem srs) {\r\n\t\tStringBuffer b = new StringBuffer();\r\n\t\tb.append(\"IPTC:\");\r\n\t\tb.append(getNumber());\r\n\t\tb.append(\":\");\r\n\t\tif (getNumber().endsWith(\"000000\")) {\r\n\t\t\tb.append(toIPTCHelper(srs.getName(this)));\r\n\t\t\tb.append(\"::\");\r\n\t\t} else if (getNumber().endsWith(\"000\")) {\r\n\t\t\tb.append(toIPTCHelper(srs.getName(srs.get(getNumber().substring(0, 2) + \"000000\"))));\r\n\t\t\tb.append(\":\");\r\n\t\t\tb.append(toIPTCHelper(srs.getName(this)));\r\n\t\t\tb.append(\":\");\r\n\t\t} else {\r\n\t\t\tb.append(toIPTCHelper(srs.getName(srs.get(getNumber().substring(0, 2) + \"000000\"))));\r\n\t\t\tb.append(\":\");\r\n\t\t\tb.append(toIPTCHelper(srs.getName(srs.get(getNumber().substring(0, 5) + \"000\"))));\r\n\t\t\tb.append(\":\");\r\n\t\t\tb.append(toIPTCHelper(srs.getName(this)));\r\n\t\t}\r\n\t\treturn b.toString();\r\n\t}" ]
Shut down the input manager. After this call, GearVRf will not be able to access IO devices.
[ "public void close()\n {\n inputManager.unregisterInputDeviceListener(inputDeviceListener);\n mouseDeviceManager.forceStopThread();\n gamepadDeviceManager.forceStopThread();\n controllerIds.clear();\n cache.clear();\n controllers.clear();\n }" ]
[ "protected PreparedStatement prepareStatement(Connection con,\r\n String sql,\r\n boolean scrollable,\r\n boolean createPreparedStatement,\r\n int explicitFetchSizeHint)\r\n throws SQLException\r\n {\r\n PreparedStatement result;\r\n\r\n // if a JDBC1.0 driver is used the signature\r\n // prepareStatement(String, int, int) is not defined.\r\n // we then call the JDBC1.0 variant prepareStatement(String)\r\n try\r\n {\r\n // if necessary use JDB1.0 methods\r\n if (!FORCEJDBC1_0)\r\n {\r\n if (createPreparedStatement)\r\n {\r\n result =\r\n con.prepareStatement(\r\n sql,\r\n scrollable\r\n ? ResultSet.TYPE_SCROLL_INSENSITIVE\r\n : ResultSet.TYPE_FORWARD_ONLY,\r\n ResultSet.CONCUR_READ_ONLY);\r\n afterJdbc2CapableStatementCreate(result, explicitFetchSizeHint);\r\n }\r\n else\r\n {\r\n result =\r\n con.prepareCall(\r\n sql,\r\n scrollable\r\n ? ResultSet.TYPE_SCROLL_INSENSITIVE\r\n : ResultSet.TYPE_FORWARD_ONLY,\r\n ResultSet.CONCUR_READ_ONLY);\r\n }\r\n }\r\n else\r\n {\r\n if (createPreparedStatement)\r\n {\r\n result = con.prepareStatement(sql);\r\n }\r\n else\r\n {\r\n result = con.prepareCall(sql);\r\n }\r\n }\r\n }\r\n catch (AbstractMethodError err)\r\n {\r\n // this exception is raised if Driver is not JDBC 2.0 compliant\r\n log.warn(\"Used driver seems not JDBC 2.0 compatible, use the JDBC 1.0 mode\", err);\r\n if (createPreparedStatement)\r\n {\r\n result = con.prepareStatement(sql);\r\n }\r\n else\r\n {\r\n result = con.prepareCall(sql);\r\n }\r\n FORCEJDBC1_0 = true;\r\n }\r\n catch (SQLException eSql)\r\n {\r\n // there are JDBC Driver that nominally implement JDBC 2.0, but\r\n // throw DriverNotCapableExceptions. If we catch one of these\r\n // we force usage of JDBC 1.0\r\n if (eSql\r\n .getClass()\r\n .getName()\r\n .equals(\"interbase.interclient.DriverNotCapableException\"))\r\n {\r\n log.warn(\"JDBC 2.0 problems with this interbase driver, we use the JDBC 1.0 mode\");\r\n if (createPreparedStatement)\r\n {\r\n result = con.prepareStatement(sql);\r\n }\r\n else\r\n {\r\n result = con.prepareCall(sql);\r\n }\r\n FORCEJDBC1_0 = true;\r\n }\r\n else\r\n {\r\n throw eSql;\r\n }\r\n }\r\n try\r\n {\r\n if (!ProxyHelper.isNormalOjbProxy(result)) // tomdz: What about VirtualProxy\r\n {\r\n platform.afterStatementCreate(result);\r\n }\r\n }\r\n catch (PlatformException e)\r\n {\r\n log.error(\"Platform dependend failure\", e);\r\n }\r\n return result;\r\n }", "public static void changeSign(DMatrixSparseCSC A , DMatrixSparseCSC B ) {\n if( A != B ) {\n B.copyStructure(A);\n }\n\n for (int i = 0; i < A.nz_length; i++) {\n B.nz_values[i] = -A.nz_values[i];\n }\n }", "protected void updateTables()\n {\n byte[] data = m_model.getData();\n int columns = m_model.getColumns();\n int rows = (data.length / columns) + 1;\n int offset = m_model.getOffset();\n\n String[][] hexData = new String[rows][columns];\n String[][] asciiData = new String[rows][columns];\n\n int row = 0;\n int column = 0;\n StringBuilder hexValue = new StringBuilder();\n for (int index = offset; index < data.length; index++)\n {\n int value = data[index];\n hexValue.setLength(0);\n hexValue.append(HEX_DIGITS[(value & 0xF0) >> 4]);\n hexValue.append(HEX_DIGITS[value & 0x0F]);\n\n char c = (char) value;\n if ((c > 200) || (c < 27))\n {\n c = ' ';\n }\n\n hexData[row][column] = hexValue.toString();\n asciiData[row][column] = Character.toString(c);\n\n ++column;\n if (column == columns)\n {\n column = 0;\n ++row;\n }\n }\n\n String[] columnHeadings = new String[columns];\n TableModel hexTableModel = new DefaultTableModel(hexData, columnHeadings)\n {\n @Override public boolean isCellEditable(int r, int c)\n {\n return false;\n }\n };\n\n TableModel asciiTableModel = new DefaultTableModel(asciiData, columnHeadings)\n {\n @Override public boolean isCellEditable(int r, int c)\n {\n return false;\n }\n };\n\n m_model.setSizeValueLabel(Integer.toString(data.length));\n m_model.setHexTableModel(hexTableModel);\n m_model.setAsciiTableModel(asciiTableModel);\n m_model.setCurrentSelectionIndex(0);\n m_model.setPreviousSelectionIndex(0);\n }", "private Pair<Double, String>\n summarizeBalance(final Map<Integer, Integer> nodeIdToPartitionCount, String title) {\n StringBuilder builder = new StringBuilder();\n builder.append(\"\\n\" + title + \"\\n\");\n\n Map<Integer, ZoneBalanceStats> zoneToBalanceStats = new HashMap<Integer, ZoneBalanceStats>();\n for(Integer zoneId: cluster.getZoneIds()) {\n zoneToBalanceStats.put(zoneId, new ZoneBalanceStats());\n }\n\n for(Node node: cluster.getNodes()) {\n int curCount = nodeIdToPartitionCount.get(node.getId());\n builder.append(\"\\tNode ID: \" + node.getId() + \" : \" + curCount + \" (\" + node.getHost()\n + \")\\n\");\n zoneToBalanceStats.get(node.getZoneId()).addPartitions(curCount);\n }\n\n // double utilityToBeMinimized = Double.MIN_VALUE;\n double utilityToBeMinimized = 0;\n for(Integer zoneId: cluster.getZoneIds()) {\n builder.append(\"Zone \" + zoneId + \"\\n\");\n builder.append(zoneToBalanceStats.get(zoneId).dumpStats());\n utilityToBeMinimized += zoneToBalanceStats.get(zoneId).getUtility();\n /*- \n * Another utility function to consider \n if(zoneToBalanceStats.get(zoneId).getMaxMinRatio() > utilityToBeMinimized) {\n utilityToBeMinimized = zoneToBalanceStats.get(zoneId).getUtility();\n }\n */\n }\n\n return Pair.create(utilityToBeMinimized, builder.toString());\n }", "@Override\r\n public String upload(InputStream in, UploadMetaData metaData) throws FlickrException {\r\n Payload payload = new Payload(in);\r\n return sendUploadRequest(metaData, payload);\r\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 }", "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 nsrpcnode[] get(nitro_service service) throws Exception{\n\t\tnsrpcnode obj = new nsrpcnode();\n\t\tnsrpcnode[] response = (nsrpcnode[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public final File getTaskDirectory() {\n createIfMissing(this.working, \"Working\");\n try {\n return Files.createTempDirectory(this.working.toPath(), TASK_DIR_PREFIX).toFile();\n } catch (IOException e) {\n throw new AssertionError(\"Unable to create temporary directory in '\" + this.working + \"'\");\n }\n }" ]
Stop listening for device announcements. Also discard any announcements which had been received, and notify any registered listeners that those devices have been lost.
[ "@SuppressWarnings(\"WeakerAccess\")\n public synchronized void stop() {\n if (isRunning()) {\n final Set<DeviceAnnouncement> lastDevices = getCurrentDevices();\n socket.get().close();\n socket.set(null);\n devices.clear();\n firstDeviceTime.set(0);\n // Report the loss of all our devices, on the proper thread, outside our lock\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (DeviceAnnouncement announcement : lastDevices) {\n deliverLostAnnouncement(announcement);\n }\n }\n });\n deliverLifecycleAnnouncement(logger, false);\n }\n }" ]
[ "@RequestMapping(value = \"/api/profile\", method = RequestMethod.POST)\n public\n @ResponseBody\n HashMap<String, Object> addProfile(Model model, String name) throws Exception {\n logger.info(\"Should be adding the profile name when I hit the enter button={}\", name);\n return Utils.getJQGridJSON(profileService.add(name), \"profile\");\n }", "private PreparedStatement prepareBatchStatement(String sql)\r\n {\r\n String sqlCmd = sql.substring(0, 7);\r\n\r\n if (sqlCmd.equals(\"UPDATE \") || sqlCmd.equals(\"DELETE \") || (_useBatchInserts && sqlCmd.equals(\"INSERT \")))\r\n {\r\n PreparedStatement stmt = (PreparedStatement) _statements.get(sql);\r\n if (stmt == null)\r\n {\r\n // [olegnitz] for JDK 1.2 we need to list both PreparedStatement and Statement\r\n // interfaces, otherwise proxy.jar works incorrectly\r\n stmt = (PreparedStatement) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{\r\n PreparedStatement.class, Statement.class, BatchPreparedStatement.class},\r\n new PreparedStatementInvocationHandler(this, sql, m_jcd));\r\n _statements.put(sql, stmt);\r\n }\r\n return stmt;\r\n }\r\n else\r\n {\r\n return null;\r\n }\r\n }", "private 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 synchronized void abortTransaction() throws TransactionNotInProgressException\n {\n if(isInTransaction())\n {\n fireBrokerEvent(BEFORE_ROLLBACK_EVENT);\n setInTransaction(false);\n clearRegistrationLists();\n referencesBroker.removePrefetchingListeners();\n /*\n arminw:\n check if we in local tx, before do local rollback\n Necessary, because ConnectionManager may do a rollback by itself\n or in managed environments the used connection is already be closed\n */\n if(connectionManager.isInLocalTransaction()) this.connectionManager.localRollback();\n fireBrokerEvent(AFTER_ROLLBACK_EVENT);\n }\n }", "public ApnsServiceBuilder withAuthProxy(Proxy proxy, String proxyUsername, String proxyPassword) {\n this.proxy = proxy;\n this.proxyUsername = proxyUsername;\n this.proxyPassword = proxyPassword;\n return this;\n }", "protected float[] transformPosition(float x, float y)\n {\n Point2D.Float point = super.transformedPoint(x, y);\n AffineTransform pageTransform = createCurrentPageTransformation();\n Point2D.Float transformedPoint = (Point2D.Float) pageTransform.transform(point, null);\n\n return new float[]{(float) transformedPoint.getX(), (float) transformedPoint.getY()};\n }", "@SuppressWarnings(\"deprecation\")\n @Deprecated\n public final void validateAndSet(ModelNode operationObject, final ModelNode model) throws OperationFailedException {\n validateOperation(operationObject);\n for (AttributeDefinition ad : this.parameters) {\n ad.validateAndSet(operationObject, model);\n }\n }", "public static DMatrixRMaj nullspaceQR( DMatrixRMaj A , int totalSingular ) {\n SolveNullSpaceQR_DDRM solver = new SolveNullSpaceQR_DDRM();\n\n DMatrixRMaj nullspace = new DMatrixRMaj(1,1);\n\n if( !solver.process(A,totalSingular,nullspace))\n throw new RuntimeException(\"Solver failed. try SVD based method instead?\");\n\n return nullspace;\n }", "public static URL asUrlOrResource(String s) {\n if (Strings.isNullOrEmpty(s)) {\n return null;\n }\n\n try {\n return new URL(s);\n } catch (MalformedURLException e) {\n //If its not a valid URL try to treat it as a local resource.\n return findConfigResource(s);\n }\n }" ]
Process any StepEvent. You can change last added to stepStorage step using this method. @param event to process
[ "public void fire(StepEvent event) {\n Step step = stepStorage.getLast();\n event.process(step);\n\n notifier.fire(event);\n }" ]
[ "public void useNewSOAPServiceWithOldClientAndRedirection() throws Exception {\n URL wsdlURL = getClass().getResource(\"/CustomerService.wsdl\");\n com.example.customerservice.CustomerServiceService service = \n new com.example.customerservice.CustomerServiceService(wsdlURL);\n \n com.example.customerservice.CustomerService customerService = \n service.getCustomerServiceRedirectPort();\n\n System.out.println(\"Using new SOAP CustomerService with old client and the redirection\");\n \n customer.v1.Customer customer = createOldCustomer(\"Barry Old to New SOAP With Redirection\");\n customerService.updateCustomer(customer);\n customer = customerService.getCustomerByName(\"Barry Old to New SOAP With Redirection\");\n printOldCustomerDetails(customer);\n }", "public <FT, FID> BaseForeignCollection<FT, FID> buildForeignCollection(Object parent, FID id) throws SQLException {\n\t\t// this can happen if we have a foreign-auto-refresh scenario\n\t\tif (foreignFieldType == null) {\n\t\t\treturn null;\n\t\t}\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tDao<FT, FID> castDao = (Dao<FT, FID>) foreignDao;\n\t\tif (!fieldConfig.isForeignCollectionEager()) {\n\t\t\t// we know this won't go recursive so no need for the counters\n\t\t\treturn new LazyForeignCollection<FT, FID>(castDao, parent, id, foreignFieldType,\n\t\t\t\t\tfieldConfig.getForeignCollectionOrderColumnName(), fieldConfig.isForeignCollectionOrderAscending());\n\t\t}\n\n\t\t// try not to create level counter objects unless we have to\n\t\tLevelCounters levelCounters = threadLevelCounters.get();\n\t\tif (levelCounters == null) {\n\t\t\tif (fieldConfig.getForeignCollectionMaxEagerLevel() == 0) {\n\t\t\t\t// then return a lazy collection instead\n\t\t\t\treturn new LazyForeignCollection<FT, FID>(castDao, parent, id, foreignFieldType,\n\t\t\t\t\t\tfieldConfig.getForeignCollectionOrderColumnName(),\n\t\t\t\t\t\tfieldConfig.isForeignCollectionOrderAscending());\n\t\t\t}\n\t\t\tlevelCounters = new LevelCounters();\n\t\t\tthreadLevelCounters.set(levelCounters);\n\t\t}\n\n\t\tif (levelCounters.foreignCollectionLevel == 0) {\n\t\t\tlevelCounters.foreignCollectionLevelMax = fieldConfig.getForeignCollectionMaxEagerLevel();\n\t\t}\n\t\t// are we over our level limit?\n\t\tif (levelCounters.foreignCollectionLevel >= levelCounters.foreignCollectionLevelMax) {\n\t\t\t// then return a lazy collection instead\n\t\t\treturn new LazyForeignCollection<FT, FID>(castDao, parent, id, foreignFieldType,\n\t\t\t\t\tfieldConfig.getForeignCollectionOrderColumnName(), fieldConfig.isForeignCollectionOrderAscending());\n\t\t}\n\t\tlevelCounters.foreignCollectionLevel++;\n\t\ttry {\n\t\t\treturn new EagerForeignCollection<FT, FID>(castDao, parent, id, foreignFieldType,\n\t\t\t\t\tfieldConfig.getForeignCollectionOrderColumnName(), fieldConfig.isForeignCollectionOrderAscending());\n\t\t} finally {\n\t\t\tlevelCounters.foreignCollectionLevel--;\n\t\t}\n\t}", "public static PipelineConfiguration.Builder parse(ModelNode json) {\n ModelNode analyzerIncludeNode = json.get(\"analyzers\").get(\"include\");\n ModelNode analyzerExcludeNode = json.get(\"analyzers\").get(\"exclude\");\n ModelNode filterIncludeNode = json.get(\"filters\").get(\"include\");\n ModelNode filterExcludeNode = json.get(\"filters\").get(\"exclude\");\n ModelNode transformIncludeNode = json.get(\"transforms\").get(\"include\");\n ModelNode transformExcludeNode = json.get(\"transforms\").get(\"exclude\");\n ModelNode reporterIncludeNode = json.get(\"reporters\").get(\"include\");\n ModelNode reporterExcludeNode = json.get(\"reporters\").get(\"exclude\");\n\n return builder()\n .withTransformationBlocks(json.get(\"transformBlocks\"))\n .withAnalyzerExtensionIdsInclude(asStringList(analyzerIncludeNode))\n .withAnalyzerExtensionIdsExclude(asStringList(analyzerExcludeNode))\n .withFilterExtensionIdsInclude(asStringList(filterIncludeNode))\n .withFilterExtensionIdsExclude(asStringList(filterExcludeNode))\n .withTransformExtensionIdsInclude(asStringList(transformIncludeNode))\n .withTransformExtensionIdsExclude(asStringList(transformExcludeNode))\n .withReporterExtensionIdsInclude(asStringList(reporterIncludeNode))\n .withReporterExtensionIdsExclude(asStringList(reporterExcludeNode));\n }", "protected int readByte(InputStream is) throws IOException\n {\n byte[] data = new byte[1];\n if (is.read(data) != data.length)\n {\n throw new EOFException();\n }\n\n return (MPPUtility.getByte(data, 0));\n }", "public List<Integer> getAsyncOperationList(boolean showCompleted) {\n /**\n * Create a copy using an immutable set to avoid a\n * {@link java.util.ConcurrentModificationException}\n */\n Set<Integer> keySet = ImmutableSet.copyOf(operations.keySet());\n\n if(showCompleted)\n return new ArrayList<Integer>(keySet);\n\n List<Integer> keyList = new ArrayList<Integer>();\n for(int key: keySet) {\n AsyncOperation operation = operations.get(key);\n if(operation != null && !operation.getStatus().isComplete())\n keyList.add(key);\n }\n return keyList;\n }", "public static void Backward(double[] data) {\n\n double[] result = new double[data.length];\n double sum;\n double scale = Math.sqrt(2.0 / data.length);\n for (int t = 0; t < data.length; t++) {\n sum = 0;\n for (int j = 0; j < data.length; j++) {\n double cos = Math.cos(((2 * t + 1) * j * Math.PI) / (2 * data.length));\n sum += alpha(j) * data[j] * cos;\n }\n result[t] = scale * sum;\n }\n for (int i = 0; i < data.length; i++) {\n data[i] = result[i];\n }\n }", "protected static int calculateShift(int minimumValue, int maximumValue) {\n\t\tint shift = 0;\n\t\tint value = 1;\n\t\twhile (value < minimumValue && value < maximumValue) {\n\t\t\tvalue <<= 1;\n\t\t\tshift++;\n\t\t}\n\t\treturn shift;\n\t}", "public static<Z> Function0<Z> lift(Func0<Z> f) {\n\treturn bridge.lift(f);\n }", "boolean undoChanges() {\n final State state = stateUpdater.getAndSet(this, State.ROLLBACK_ONLY);\n if (state == State.COMPLETED || state == State.ROLLBACK_ONLY) {\n // Was actually completed already\n return false;\n }\n PatchingTaskContext.Mode currentMode = this.mode;\n mode = PatchingTaskContext.Mode.UNDO;\n final PatchContentLoader loader = PatchContentLoader.create(miscBackup, null, null);\n // Undo changes for the identity\n undoChanges(identityEntry, loader);\n // TODO maybe check if we need to do something for the layers too !?\n if (state == State.INVALIDATE || currentMode == PatchingTaskContext.Mode.ROLLBACK) {\n // For apply the state needs to be invalidate\n // For rollback the files are invalidated as part of the tasks\n final PatchingTaskContext.Mode mode = currentMode == PatchingTaskContext.Mode.APPLY ? PatchingTaskContext.Mode.ROLLBACK : PatchingTaskContext.Mode.APPLY;\n for (final File file : moduleInvalidations) {\n try {\n PatchModuleInvalidationUtils.processFile(this, file, mode);\n } catch (Exception e) {\n PatchLogger.ROOT_LOGGER.debugf(e, \"failed to restore state for %s\", file);\n }\n }\n if(!modulesToReenable.isEmpty()) {\n for (final File file : modulesToReenable) {\n try {\n PatchModuleInvalidationUtils.processFile(this, file, PatchingTaskContext.Mode.APPLY);\n } catch (Exception e) {\n PatchLogger.ROOT_LOGGER.debugf(e, \"failed to restore state for %s\", file);\n }\n }\n }\n if(!modulesToDisable.isEmpty()) {\n for (final File file : modulesToDisable) {\n try {\n PatchModuleInvalidationUtils.processFile(this, file, PatchingTaskContext.Mode.ROLLBACK);\n } catch (Exception e) {\n PatchLogger.ROOT_LOGGER.debugf(e, \"failed to restore state for %s\", file);\n }\n }\n }\n }\n return true;\n }" ]
Load physics information for the current avatar @param filename name of physics file @param scene scene the avatar is part of @throws IOException if physics file cannot be parsed
[ "public void loadPhysics(String filename, GVRScene scene) throws IOException\n {\n GVRPhysicsLoader.loadPhysicsFile(getGVRContext(), filename, true, scene);\n }" ]
[ "public boolean isWorkingDate(Date date)\n {\n Calendar cal = DateHelper.popCalendar(date);\n Day day = Day.getInstance(cal.get(Calendar.DAY_OF_WEEK));\n DateHelper.pushCalendar(cal);\n return isWorkingDate(date, day);\n }", "public static final String printResourceType(ResourceType value)\n {\n return (Integer.toString(value == null ? ResourceType.WORK.getValue() : value.getValue()));\n }", "public static base_response add(nitro_service client, vpnclientlessaccesspolicy resource) throws Exception {\n\t\tvpnclientlessaccesspolicy addresource = new vpnclientlessaccesspolicy();\n\t\taddresource.name = resource.name;\n\t\taddresource.rule = resource.rule;\n\t\taddresource.profilename = resource.profilename;\n\t\treturn addresource.add_resource(client);\n\t}", "public final int toChars(int[] src, int srcOff, int srcLen, char[] dest, int destOff) {\n if (srcLen < 0) {\n throw new IllegalArgumentException(\"srcLen must be >= 0\");\n }\n int written = 0;\n for (int i = 0; i < srcLen; ++i) {\n written += Character.toChars(src[srcOff + i], dest, destOff + written);\n }\n return written;\n }", "boolean attachmentsAreStructurallyDifferent( List<AttachmentModel> firstAttachments, List<AttachmentModel> otherAttachments ) {\n if( firstAttachments.size() != otherAttachments.size() ) {\n return true;\n }\n\n for( int i = 0; i < firstAttachments.size(); i++ ) {\n if( attachmentIsStructurallyDifferent( firstAttachments.get( i ), otherAttachments.get( i ) ) ) {\n return true;\n }\n }\n return false;\n }", "public static void dumpBlockData(int headerSize, int blockSize, byte[] data)\n {\n if (data != null)\n {\n System.out.println(ByteArrayHelper.hexdump(data, 0, headerSize, false));\n int index = headerSize;\n while (index < data.length)\n {\n System.out.println(ByteArrayHelper.hexdump(data, index, blockSize, false));\n index += blockSize;\n }\n }\n }", "@Override\n public PersistentResourceXMLDescription getParserDescription() {\n return PersistentResourceXMLDescription.builder(ElytronExtension.SUBSYSTEM_PATH, getNameSpace())\n .addAttribute(ElytronDefinition.DEFAULT_AUTHENTICATION_CONTEXT)\n .addAttribute(ElytronDefinition.INITIAL_PROVIDERS)\n .addAttribute(ElytronDefinition.FINAL_PROVIDERS)\n .addAttribute(ElytronDefinition.DISALLOWED_PROVIDERS)\n .addAttribute(ElytronDefinition.SECURITY_PROPERTIES, new AttributeParsers.PropertiesParser(null, SECURITY_PROPERTY, true), new AttributeMarshallers.PropertiesAttributeMarshaller(null, SECURITY_PROPERTY, true))\n .addChild(getAuthenticationClientParser())\n .addChild(getProviderParser())\n .addChild(getAuditLoggingParser())\n .addChild(getDomainParser())\n .addChild(getRealmParser())\n .addChild(getCredentialSecurityFactoryParser())\n .addChild(getMapperParser())\n .addChild(getHttpParser())\n .addChild(getSaslParser())\n .addChild(getTlsParser())\n .addChild(decorator(CREDENTIAL_STORES).addChild(new CredentialStoreParser().parser))\n .addChild(getDirContextParser())\n .addChild(getPolicyParser())\n .build();\n }", "protected void notifyBufferChange(char[] newData, int numChars) {\n synchronized(bufferChangeLoggers) {\n Iterator<BufferChangeLogger> iterator = bufferChangeLoggers.iterator();\n while (iterator.hasNext()) {\n iterator.next().bufferChanged(newData, numChars);\n }\n }\n }", "public static PredicateExpression all(Object... rhs) {\n PredicateExpression ex = new PredicateExpression( \"$all\", rhs);\n if (rhs.length == 1) {\n ex.single = true;\n }\n return ex;\n }" ]
Log a warning for the resource at the provided address and the given attributes, using the provided detail message. @param address where warning occurred @param message custom error message to append @param attributes attributes we that have problems about
[ "public void logAttributeWarning(PathAddress address, String message, Set<String> attributes) {\n messageQueue.add(new AttributeLogEntry(address, null, message, attributes));\n }" ]
[ "private String getInverseOneToOneProperty(String property, OgmEntityPersister otherSidePersister) {\n\t\tfor ( String candidate : otherSidePersister.getPropertyNames() ) {\n\t\t\tType candidateType = otherSidePersister.getPropertyType( candidate );\n\t\t\tif ( candidateType.isEntityType()\n\t\t\t\t\t&& ( ( (EntityType) candidateType ).isOneToOne()\n\t\t\t\t\t&& isOneToOneMatching( this, property, (OneToOneType) candidateType ) ) ) {\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}", "public static void validate(final String bic) throws BicFormatException,\n UnsupportedCountryException {\n try {\n validateEmpty(bic);\n validateLength(bic);\n validateCase(bic);\n validateBankCode(bic);\n validateCountryCode(bic);\n validateLocationCode(bic);\n\n if(hasBranchCode(bic)) {\n validateBranchCode(bic);\n }\n } catch (UnsupportedCountryException e) {\n throw e;\n } catch (RuntimeException e) {\n throw new BicFormatException(UNKNOWN, e.getMessage());\n }\n }", "public static float[][] toFloat(int[][] array) {\n float[][] n = new float[array.length][array[0].length];\n for (int i = 0; i < array.length; i++) {\n for (int j = 0; j < array[0].length; j++) {\n n[i][j] = (float) array[i][j];\n }\n }\n return n;\n }", "public static aaaglobal_binding get(nitro_service service) throws Exception{\n\t\taaaglobal_binding obj = new aaaglobal_binding();\n\t\taaaglobal_binding response = (aaaglobal_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "public String getEditorParameter(CmsObject cms, String editor, String param) {\n\n String path = OpenCms.getSystemInfo().getConfigFilePath(cms, \"editors/\" + editor + \".properties\");\n CmsVfsMemoryObjectCache cache = CmsVfsMemoryObjectCache.getVfsMemoryObjectCache();\n CmsParameterConfiguration config = (CmsParameterConfiguration)cache.getCachedObject(cms, path);\n if (config == null) {\n try {\n CmsFile file = cms.readFile(path);\n try (ByteArrayInputStream input = new ByteArrayInputStream(file.getContents())) {\n config = new CmsParameterConfiguration(input); // Uses ISO-8859-1, should be OK for config parameters\n cache.putCachedObject(cms, path, config);\n }\n } catch (CmsVfsResourceNotFoundException e) {\n return null;\n } catch (Exception e) {\n LOG.error(e.getLocalizedMessage(), e);\n return null;\n }\n }\n return config.getString(param, null);\n }", "public Object convertStringToJavaField(String value, int columnPos) throws SQLException {\n\t\tif (value == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn fieldConverter.resultStringToJava(this, value, columnPos);\n\t\t}\n\t}", "public static cmppolicylabel_cmppolicy_binding[] get(nitro_service service, String labelname) throws Exception{\n\t\tcmppolicylabel_cmppolicy_binding obj = new cmppolicylabel_cmppolicy_binding();\n\t\tobj.set_labelname(labelname);\n\t\tcmppolicylabel_cmppolicy_binding response[] = (cmppolicylabel_cmppolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public Metadata replace(String path, String value) {\n this.values.set(this.pathToProperty(path), value);\n this.addOp(\"replace\", path, value);\n return this;\n }", "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}" ]
Returns the compact records for all teams in the organization visible to the authorized user. @param organization Globally unique identifier for the workspace or organization. @return Request object
[ "public CollectionRequest<Team> findByOrganization(String organization) {\n \n String path = String.format(\"/organizations/%s/teams\", organization);\n return new CollectionRequest<Team>(this, Team.class, path, \"GET\");\n }" ]
[ "private void readCalendars(Project ganttProject)\n {\n m_mpxjCalendar = m_projectFile.addCalendar();\n m_mpxjCalendar.setName(ProjectCalendar.DEFAULT_BASE_CALENDAR_NAME);\n\n Calendars gpCalendar = ganttProject.getCalendars();\n setWorkingDays(m_mpxjCalendar, gpCalendar);\n setExceptions(m_mpxjCalendar, gpCalendar);\n m_eventManager.fireCalendarReadEvent(m_mpxjCalendar);\n }", "@Override\n protected void initBuilderSpecific() throws Exception {\n reset();\n FilePath workspace = getModuleRoot(EnvVars.masterEnvVars);\n FilePath gradlePropertiesPath = new FilePath(workspace, \"gradle.properties\");\n if (releaseProps == null) {\n releaseProps = PropertyUtils.getModulesPropertiesFromPropFile(gradlePropertiesPath, getReleaseProperties());\n }\n if (nextIntegProps == null) {\n nextIntegProps =\n PropertyUtils.getModulesPropertiesFromPropFile(gradlePropertiesPath, getNextIntegProperties());\n }\n }", "public static inat get(nitro_service service, String name) throws Exception{\n\t\tinat obj = new inat();\n\t\tobj.set_name(name);\n\t\tinat response = (inat) obj.get_resource(service);\n\t\treturn response;\n\t}", "private boolean removeRelation(List<Relation> relationList, Task targetTask, RelationType type, Duration lag)\n {\n boolean matchFound = false;\n for (Relation relation : relationList)\n {\n if (relation.getTargetTask() == targetTask)\n {\n if (relation.getType() == type && relation.getLag().compareTo(lag) == 0)\n {\n matchFound = relationList.remove(relation);\n break;\n }\n }\n }\n return matchFound;\n }", "private String getResourceType(Resource resource)\n {\n String result;\n net.sf.mpxj.ResourceType type = resource.getType();\n if (type == null)\n {\n type = net.sf.mpxj.ResourceType.WORK;\n }\n\n switch (type)\n {\n case MATERIAL:\n {\n result = \"Material\";\n break;\n }\n\n case COST:\n {\n result = \"Nonlabor\";\n break;\n }\n\n default:\n {\n result = \"Labor\";\n break;\n }\n }\n\n return result;\n }", "public static String readUntilTag(Reader r) throws IOException {\r\n if (!r.ready()) {\r\n return \"\";\r\n }\r\n StringBuilder b = new StringBuilder();\r\n int c = r.read();\r\n while (c >= 0 && c != '<') {\r\n b.append((char) c);\r\n c = r.read();\r\n }\r\n return b.toString();\r\n }", "private void makeSingularPositive() {\n numSingular = qralg.getNumberOfSingularValues();\n singularValues = qralg.getSingularValues();\n\n for( int i = 0; i < numSingular; i++ ) {\n double val = singularValues[i];\n\n if( val < 0 ) {\n singularValues[i] = -val;\n\n if( computeU ) {\n // compute the results of multiplying it by an element of -1 at this location in\n // a diagonal matrix.\n int start = i* Ut.numCols;\n int stop = start+ Ut.numCols;\n\n for( int j = start; j < stop; j++ ) {\n Ut.data[j] = -Ut.data[j];\n }\n }\n }\n }\n }", "public ItemRequest<Task> addSubtask(String task) {\n \n String path = String.format(\"/tasks/%s/subtasks\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }", "public static boolean isTemplatePath(String string) {\n int sz = string.length();\n if (sz == 0) {\n return true;\n }\n for (int i = 0; i < sz; ++i) {\n char c = string.charAt(i);\n switch (c) {\n case ' ':\n case '\\t':\n case '\\b':\n case '<':\n case '>':\n case '(':\n case ')':\n case '[':\n case ']':\n case '{':\n case '}':\n case '!':\n case '@':\n case '#':\n case '*':\n case '?':\n case '%':\n case '|':\n case ',':\n case ':':\n case ';':\n case '^':\n case '&':\n return false;\n }\n }\n return true;\n }" ]
Set the host. @param host the host
[ "public final void setHost(final String host) throws UnknownHostException {\n this.host = host;\n final InetAddress[] inetAddresses = InetAddress.getAllByName(host);\n\n for (InetAddress address: inetAddresses) {\n final AddressHostMatcher matcher = new AddressHostMatcher();\n matcher.setIp(address.getHostAddress());\n this.matchersForHost.add(matcher);\n }\n }" ]
[ "private void SetNewViewpoint(String url) {\n Viewpoint vp = null;\n // get the name without the '#' sign\n String vpURL = url.substring(1, url.length());\n for (Viewpoint viewpoint : viewpoints) {\n if ( viewpoint.getName().equalsIgnoreCase(vpURL) ) {\n vp = viewpoint;\n }\n }\n if ( vp != null ) {\n // found the Viewpoint matching the url\n GVRCameraRig mainCameraRig = gvrContext.getMainScene().getMainCameraRig();\n float[] cameraPosition = vp.getPosition();\n mainCameraRig.getTransform().setPosition( cameraPosition[0], cameraPosition[1], cameraPosition[2] );\n\n // Set the Gaze controller position which is where the pick ray\n // begins in the direction of camera.lookt()\n GVRCursorController gazeController = null;\n GVRInputManager inputManager = gvrContext.getInputManager();\n\n List<GVRCursorController> controllerList = inputManager.getCursorControllers();\n\n for(GVRCursorController controller: controllerList){\n if(controller.getControllerType() == GVRControllerType.GAZE);\n {\n gazeController = controller;\n break;\n }\n }\n if ( gazeController != null) {\n gazeController.setOrigin(cameraPosition[0], cameraPosition[1], cameraPosition[2]);\n }\n }\n else {\n Log.e(TAG, \"Viewpoint named \" + vpURL + \" not found (defined).\");\n }\n }", "public static BoxDeveloperEditionAPIConnection getAppEnterpriseConnection(BoxConfig boxConfig) {\n\n BoxDeveloperEditionAPIConnection connection = getAppEnterpriseConnection(boxConfig.getEnterpriseId(),\n boxConfig.getClientId(), boxConfig.getClientSecret(), boxConfig.getJWTEncryptionPreferences());\n\n return connection;\n }", "private void queryDatabaseMetaData()\n {\n ResultSet rs = null;\n\n try\n {\n Set<String> tables = new HashSet<String>();\n DatabaseMetaData dmd = m_connection.getMetaData();\n rs = dmd.getTables(null, null, null, null);\n while (rs.next())\n {\n tables.add(rs.getString(\"TABLE_NAME\"));\n }\n\n m_hasResourceBaselines = tables.contains(\"MSP_RESOURCE_BASELINES\");\n m_hasTaskBaselines = tables.contains(\"MSP_TASK_BASELINES\");\n m_hasAssignmentBaselines = tables.contains(\"MSP_ASSIGNMENT_BASELINES\");\n }\n\n catch (Exception ex)\n {\n // Ignore errors when reading meta data\n }\n\n finally\n {\n if (rs != null)\n {\n try\n {\n rs.close();\n }\n\n catch (SQLException ex)\n {\n // Ignore errors when closing result set\n }\n rs = null;\n }\n }\n }", "ModelNode toModelNode() {\n ModelNode result = null;\n if (map != null) {\n result = new ModelNode();\n for (Map.Entry<PathAddress, ResourceData> entry : map.entrySet()) {\n ModelNode item = new ModelNode();\n PathAddress pa = entry.getKey();\n item.get(ABSOLUTE_ADDRESS).set(pa.toModelNode());\n ResourceData rd = entry.getValue();\n item.get(RELATIVE_ADDRESS).set(pa.subAddress(baseAddressLength).toModelNode());\n ModelNode attrs = new ModelNode().setEmptyList();\n if (rd.attributes != null) {\n for (String attr : rd.attributes) {\n attrs.add(attr);\n }\n }\n if (attrs.asInt() > 0) {\n item.get(FILTERED_ATTRIBUTES).set(attrs);\n }\n ModelNode children = new ModelNode().setEmptyList();\n if (rd.children != null) {\n for (PathElement pe : rd.children) {\n children.add(new Property(pe.getKey(), new ModelNode(pe.getValue())));\n }\n }\n if (children.asInt() > 0) {\n item.get(UNREADABLE_CHILDREN).set(children);\n }\n ModelNode childTypes = new ModelNode().setEmptyList();\n if (rd.childTypes != null) {\n Set<String> added = new HashSet<String>();\n for (PathElement pe : rd.childTypes) {\n if (added.add(pe.getKey())) {\n childTypes.add(pe.getKey());\n }\n }\n }\n if (childTypes.asInt() > 0) {\n item.get(FILTERED_CHILDREN_TYPES).set(childTypes);\n }\n result.add(item);\n }\n }\n return result;\n }", "public static int daysDiff(Date earlierDate, Date laterDate) {\n if (earlierDate == null || laterDate == null) {\n return 0;\n }\n\n return (int) ((laterDate.getTime() / DAY_MILLIS) - (earlierDate.getTime() / DAY_MILLIS));\n }", "public void addPostEffect(GVRMaterial postEffectData) {\n GVRContext ctx = getGVRContext();\n\n if (mPostEffects == null)\n {\n mPostEffects = new GVRRenderData(ctx, postEffectData);\n GVRMesh dummyMesh = new GVRMesh(getGVRContext(),\"float3 a_position float2 a_texcoord\");\n mPostEffects.setMesh(dummyMesh);\n NativeCamera.setPostEffect(getNative(), mPostEffects.getNative());\n mPostEffects.setCullFace(GVRRenderPass.GVRCullFaceEnum.None);\n }\n else\n {\n GVRRenderPass rpass = new GVRRenderPass(ctx, postEffectData);\n rpass.setCullFace(GVRRenderPass.GVRCullFaceEnum.None);\n mPostEffects.addPass(rpass);\n }\n }", "private String parseEnvelope() {\r\n List<String> response = new ArrayList<>();\r\n //1. Date ---------------\r\n response.add(LB + Q + sentDateEnvelopeString + Q + SP);\r\n //2. Subject ---------------\r\n if (subject != null && (subject.length() != 0)) {\r\n response.add(Q + escapeHeader(subject) + Q + SP);\r\n } else {\r\n response.add(NIL + SP);\r\n }\r\n //3. From ---------------\r\n addAddressToEnvelopeIfAvailable(from, response);\r\n response.add(SP);\r\n //4. Sender ---------------\r\n addAddressToEnvelopeIfAvailableWithNetscapeFeature(sender, response);\r\n response.add(SP);\r\n addAddressToEnvelopeIfAvailableWithNetscapeFeature(replyTo, response);\r\n response.add(SP);\r\n addAddressToEnvelopeIfAvailable(to, response);\r\n response.add(SP);\r\n addAddressToEnvelopeIfAvailable(cc, response);\r\n response.add(SP);\r\n addAddressToEnvelopeIfAvailable(bcc, response);\r\n response.add(SP);\r\n if (inReplyTo != null && inReplyTo.length > 0) {\r\n response.add(inReplyTo[0]);\r\n } else {\r\n response.add(NIL);\r\n }\r\n response.add(SP);\r\n if (messageID != null && messageID.length > 0) {\r\n messageID[0] = escapeHeader(messageID[0]);\r\n response.add(Q + messageID[0] + Q);\r\n } else {\r\n response.add(NIL);\r\n }\r\n response.add(RB);\r\n\r\n StringBuilder buf = new StringBuilder(16 * response.size());\r\n for (String aResponse : response) {\r\n buf.append(aResponse);\r\n }\r\n\r\n return buf.toString();\r\n }", "public Response getTemplate(String id) throws RequestException, LocalOperationException {\n Request request = new Request(this);\n return new Response(request.get(\"/templates/\" + id));\n }", "public static java.util.Date rollDateTime(java.util.Date startDate, int period, int amount) {\n GregorianCalendar gc = new GregorianCalendar();\n gc.setTime(startDate);\n gc.add(period, amount);\n return new java.util.Date(gc.getTime().getTime());\n }" ]
Filter everything until we found the first NL character.
[ "@Override\n\tpublic void write(final char[] cbuf, final int off, final int len) throws IOException {\n\t\tint offset = off;\n\t\tint length = len;\n\t\twhile (suppressLineCount > 0 && length > 0) {\n\t\t\tlength = -1;\n\t\t\tfor (int i = 0; i < len && suppressLineCount > 0; i++) {\n\t\t\t\tif (cbuf[off + i] == '\\n') {\n\t\t\t\t\toffset = off + i + 1;\n\t\t\t\t\tlength = len - i - 1;\n\t\t\t\t\tsuppressLineCount--;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (length <= 0)\n\t\t\t\treturn;\n\t\t}\n\t\tdelegate.write(cbuf, offset, length);\n\t}" ]
[ "public static boolean nullSafeEquals(final Object obj1, final Object obj2) {\n return ((obj1 == null && obj2 == null)\n || (obj1 != null && obj2 != null && obj1.equals(obj2)));\n }", "@Override\n\tpublic void clear() {\n\t\tif (dao == null) {\n\t\t\treturn;\n\t\t}\n\t\tCloseableIterator<T> iterator = closeableIterator();\n\t\ttry {\n\t\t\twhile (iterator.hasNext()) {\n\t\t\t\titerator.next();\n\t\t\t\titerator.remove();\n\t\t\t}\n\t\t} finally {\n\t\t\tIOUtils.closeQuietly(iterator);\n\t\t}\n\t}", "private String typeParameters(Options opt, ParameterizedType t) {\n\tif (t == null)\n\t return \"\";\n\tStringBuffer tp = new StringBuffer(1000).append(\"&lt;\");\n\tType args[] = t.typeArguments();\n\tfor (int i = 0; i < args.length; i++) {\n\t tp.append(type(opt, args[i], true));\n\t if (i != args.length - 1)\n\t\ttp.append(\", \");\n\t}\n\treturn tp.append(\"&gt;\").toString();\n }", "private static String decode(String s) {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n for (int i = 0; i < s.length(); i++) {\n char ch = s.charAt(i);\n if (ch == '%') {\n baos.write(hexToInt(s.charAt(i + 1)) * 16 + hexToInt(s.charAt(i + 2)));\n i += 2;\n continue;\n }\n baos.write(ch);\n }\n try {\n return new String(baos.toByteArray(), \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n throw new Error(e); // impossible\n }\n }", "public static void registerOgmExternalizers(GlobalConfiguration globalCfg) {\n\t\tMap<Integer, AdvancedExternalizer<?>> externalizerMap = globalCfg.serialization().advancedExternalizers();\n\t\texternalizerMap.putAll( ogmExternalizers );\n\t}", "public CurrencyQueryBuilder setCountries(Locale... countries) {\n return set(CurrencyQuery.KEY_QUERY_COUNTRIES, Arrays.asList(countries));\n }", "public void scaleWeights(double scale) {\r\n for (int i = 0; i < weights.length; i++) {\r\n for (int j = 0; j < weights[i].length; j++) {\r\n weights[i][j] *= scale;\r\n }\r\n }\r\n }", "@Override\n public List<Assignment> assign(Collection<String> suiteNames, int slaves, long seed) {\n // Read hints first.\n final Map<String,List<Long>> hints = ExecutionTimesReport.mergeHints(resources, suiteNames);\n\n // Preprocess and sort costs. Take the median for each suite's measurements as the \n // weight to avoid extreme measurements from screwing up the average.\n final List<SuiteHint> costs = new ArrayList<>();\n for (String suiteName : suiteNames) {\n final List<Long> suiteHint = hints.get(suiteName);\n if (suiteHint != null) {\n // Take the median for each suite's measurements as the weight\n // to avoid extreme measurements from screwing up the average.\n Collections.sort(suiteHint);\n final Long median = suiteHint.get(suiteHint.size() / 2);\n costs.add(new SuiteHint(suiteName, median));\n }\n }\n Collections.sort(costs, SuiteHint.DESCENDING_BY_WEIGHT);\n\n // Apply the assignment heuristic.\n final PriorityQueue<SlaveLoad> pq = new PriorityQueue<SlaveLoad>(\n slaves, SlaveLoad.ASCENDING_BY_ESTIMATED_FINISH);\n for (int i = 0; i < slaves; i++) {\n pq.add(new SlaveLoad(i));\n }\n\n final List<Assignment> assignments = new ArrayList<>();\n for (SuiteHint hint : costs) {\n SlaveLoad slave = pq.remove();\n slave.estimatedFinish += hint.cost;\n pq.add(slave);\n\n owner.log(\"Expected execution time for \" + hint.suiteName + \": \" +\n Duration.toHumanDuration(hint.cost),\n Project.MSG_DEBUG);\n\n assignments.add(new Assignment(hint.suiteName, slave.id, (int) hint.cost));\n }\n\n // Dump estimated execution times.\n TreeMap<Integer, SlaveLoad> ordered = new TreeMap<Integer, SlaveLoad>();\n while (!pq.isEmpty()) {\n SlaveLoad slave = pq.remove();\n ordered.put(slave.id, slave);\n }\n for (Integer id : ordered.keySet()) {\n final SlaveLoad slave = ordered.get(id);\n owner.log(String.format(Locale.ROOT, \n \"Expected execution time on JVM J%d: %8.2fs\",\n slave.id,\n slave.estimatedFinish / 1000.0f), \n verbose ? Project.MSG_INFO : Project.MSG_DEBUG);\n }\n\n return assignments;\n }", "public synchronized final void closeStream() {\n try {\n if ((stream != null) && (streamState == StreamStates.OPEN)) {\n stream.close();\n stream = null;\n }\n streamState = StreamStates.CLOSED;\n } catch (IOException e) {\n e.printStackTrace();\n }\n }" ]
Use this API to enable nsacl6 resources of given names.
[ "public static base_responses enable(nitro_service client, String acl6name[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (acl6name != null && acl6name.length > 0) {\n\t\t\tnsacl6 enableresources[] = new nsacl6[acl6name.length];\n\t\t\tfor (int i=0;i<acl6name.length;i++){\n\t\t\t\tenableresources[i] = new nsacl6();\n\t\t\t\tenableresources[i].acl6name = acl6name[i];\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, enableresources,\"enable\");\n\t\t}\n\t\treturn result;\n\t}" ]
[ "public void unlink(Object obj, ObjectReferenceDescriptor ord, boolean insert)\r\n {\r\n linkOrUnlink(false, obj, ord, insert);\r\n }", "protected void updateLabelActiveStyle() {\n if (this.valueBoxBase.getText() != null && !this.valueBoxBase.getText().isEmpty()) {\n label.addStyleName(CssName.ACTIVE);\n } else {\n label.removeStyleName(CssName.ACTIVE);\n }\n }", "private Object[] convert(FieldConversion[] fcs, Object[] values)\r\n {\r\n Object[] convertedValues = new Object[values.length];\r\n \r\n for (int i= 0; i < values.length; i++)\r\n {\r\n convertedValues[i] = fcs[i].sqlToJava(values[i]);\r\n }\r\n\r\n return convertedValues;\r\n }", "static void processFile(final IdentityPatchContext context, final File file, final PatchingTaskContext.Mode mode) throws IOException {\n if (mode == PatchingTaskContext.Mode.APPLY) {\n if (ENABLE_INVALIDATION) {\n updateJar(file, GOOD_ENDSIG_PATTERN, BAD_BYTE_SKIP, CRIPPLED_ENDSIG, GOOD_ENDSIG);\n backup(context, file);\n }\n } else if (mode == PatchingTaskContext.Mode.ROLLBACK) {\n updateJar(file, CRIPPLED_ENDSIG_PATTERN, BAD_BYTE_SKIP, GOOD_ENDSIG, CRIPPLED_ENDSIG);\n restore(context, file);\n } else {\n throw new IllegalStateException();\n }\n }", "private void merge(Integer cid1, Integer cid2) {\n Collection<String> klass1 = classix.get(cid1);\n Collection<String> klass2 = classix.get(cid2);\n\n // if klass1 is the smaller, swap the two\n if (klass1.size() < klass2.size()) {\n Collection<String> tmp = klass2;\n klass2 = klass1;\n klass1 = tmp;\n\n Integer itmp = cid2;\n cid2 = cid1;\n cid1 = itmp;\n }\n\n // now perform the actual merge\n for (String id : klass2) {\n klass1.add(id);\n recordix.put(id, cid1);\n }\n\n // delete the smaller class, and we're done\n classix.remove(cid2);\n }", "private static List<String> parseModifiers(int modifiers) {\n List<String> result = new ArrayList<String>();\n if (Modifier.isPrivate(modifiers)) {\n result.add(\"private\");\n }\n if (Modifier.isProtected(modifiers)) {\n result.add(\"protected\");\n }\n if (Modifier.isPublic(modifiers)) {\n result.add(\"public\");\n }\n if (Modifier.isAbstract(modifiers)) {\n result.add(\"abstract\");\n }\n if (Modifier.isFinal(modifiers)) {\n result.add(\"final\");\n }\n if (Modifier.isNative(modifiers)) {\n result.add(\"native\");\n }\n if (Modifier.isStatic(modifiers)) {\n result.add(\"static\");\n }\n if (Modifier.isStrict(modifiers)) {\n result.add(\"strict\");\n }\n if (Modifier.isSynchronized(modifiers)) {\n result.add(\"synchronized\");\n }\n if (Modifier.isTransient(modifiers)) {\n result.add(\"transient\");\n }\n if (Modifier.isVolatile(modifiers)) {\n result.add(\"volatile\");\n }\n if (Modifier.isInterface(modifiers)) {\n result.add(\"interface\");\n }\n return result;\n }", "public 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 }", "public QueryBuilder<T, ID> orderByRaw(String rawSql) {\n\t\taddOrderBy(new OrderBy(rawSql, (ArgumentHolder[]) null));\n\t\treturn this;\n\t}", "public Search groupField(String fieldName, boolean isNumber) {\r\n assertNotEmpty(fieldName, \"fieldName\");\r\n if (isNumber) {\r\n databaseHelper.query(\"group_field\", fieldName + \"<number>\");\r\n } else {\r\n databaseHelper.query(\"group_field\", fieldName);\r\n }\r\n return this;\r\n }" ]
sets the class object described by this descriptor. @param c the class to describe
[ "public void setClassOfObject(Class c)\r\n {\r\n m_Class = c;\r\n isAbstract = Modifier.isAbstract(m_Class.getModifiers());\r\n // TODO : Shouldn't the HashMap in DescriptorRepository be updated as well?\r\n }" ]
[ "private List<TimephasedCost> getTimephasedCostMultipleRates(List<TimephasedWork> standardWorkList, List<TimephasedWork> overtimeWorkList)\n {\n List<TimephasedWork> standardWorkResult = new LinkedList<TimephasedWork>();\n List<TimephasedWork> overtimeWorkResult = new LinkedList<TimephasedWork>();\n CostRateTable table = getCostRateTable();\n ProjectCalendar calendar = getCalendar();\n\n Iterator<TimephasedWork> iter = overtimeWorkList.iterator();\n for (TimephasedWork standardWork : standardWorkList)\n {\n TimephasedWork overtimeWork = iter.hasNext() ? iter.next() : null;\n\n int startIndex = getCostRateTableEntryIndex(standardWork.getStart());\n int finishIndex = getCostRateTableEntryIndex(standardWork.getFinish());\n\n if (startIndex == finishIndex)\n {\n standardWorkResult.add(standardWork);\n if (overtimeWork != null)\n {\n overtimeWorkResult.add(overtimeWork);\n }\n }\n else\n {\n standardWorkResult.addAll(splitWork(table, calendar, standardWork, startIndex));\n if (overtimeWork != null)\n {\n overtimeWorkResult.addAll(splitWork(table, calendar, overtimeWork, startIndex));\n }\n }\n }\n\n return getTimephasedCostSingleRate(standardWorkResult, overtimeWorkResult);\n }", "private String tail(String moduleName) {\n if (moduleName.indexOf(MODULE_NAME_SEPARATOR) > 0) {\n return moduleName.substring(moduleName.indexOf(MODULE_NAME_SEPARATOR) + 1);\n } else {\n return \"\";\n }\n }", "public void drawGeometry(Geometry geometry, SymbolInfo symbol, Color fillColor, Color strokeColor, float lineWidth,\n\t\t\tfloat[] dashArray, Rectangle clipRect) {\n\t\ttemplate.saveState();\n\t\t// clipping code\n\t\tif (clipRect != null) {\n\t\t\ttemplate.rectangle(clipRect.getLeft() + origX, clipRect.getBottom() + origY, clipRect.getWidth(), clipRect\n\t\t\t\t\t.getHeight());\n\t\t\ttemplate.clip();\n\t\t\ttemplate.newPath();\n\t\t}\n\t\tsetStroke(strokeColor, lineWidth, dashArray);\n\t\tsetFill(fillColor);\n\t\tdrawGeometry(geometry, symbol);\n\t\ttemplate.restoreState();\n\t}", "private String toLengthText(long bytes) {\n if (bytes < 1024) {\n return bytes + \" B\";\n } else if (bytes < 1024 * 1024) {\n return (bytes / 1024) + \" KB\";\n } else if (bytes < 1024 * 1024 * 1024) {\n return String.format(\"%.2f MB\", bytes / (1024.0 * 1024.0));\n } else {\n return String.format(\"%.2f GB\", bytes / (1024.0 * 1024.0 * 1024.0));\n }\n }", "@TargetApi(VERSION_CODES.KITKAT)\n public static void showSystemUI(Activity activity) {\n View decorView = activity.getWindow().getDecorView();\n decorView.setSystemUiVisibility(\n View.SYSTEM_UI_FLAG_LAYOUT_STABLE\n | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION\n | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN\n );\n }", "public B importContext(AbstractContext context, boolean overwriteDuplicates){\n for (Map.Entry<String, Object> en : context.data.entrySet()) {\n if (overwriteDuplicates) {\n this.data.put(en.getKey(), en.getValue());\n }else{\n this.data.putIfAbsent(en.getKey(), en.getValue());\n }\n }\n return (B) this;\n }", "private void onClickAdd() {\n\n if (m_currentLocation.isPresent()) {\n CmsFavoriteEntry entry = m_currentLocation.get();\n List<CmsFavoriteEntry> entries = getEntries();\n entries.add(entry);\n try {\n m_favDao.saveFavorites(entries);\n } catch (Exception e) {\n CmsErrorDialog.showErrorDialog(e);\n }\n m_context.close();\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 static ProtocolConnectionManager create(final Connection connection, final ConnectionOpenHandler openHandler) {\n return create(new EstablishedConnection(connection, openHandler));\n }" ]
Maps this iterable from the source document type to the target document type. @param mapper a function that maps from the source to the target document type @param <U> the target document type @return an iterable which maps T to U
[ "public <U> CoreRemoteMongoIterable<U> map(final Function<ResultT, U> mapper) {\n return new CoreRemoteMappingIterable<>(this, mapper);\n }" ]
[ "public static rsskeytype get(nitro_service service) throws Exception{\n\t\trsskeytype obj = new rsskeytype();\n\t\trsskeytype[] response = (rsskeytype[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public String computeTrackSignature(final String title, final SearchableItem artist, final int duration,\n final WaveformDetail waveformDetail, final BeatGrid beatGrid) {\n final String safeTitle = (title == null)? \"\" : title;\n final String artistName = (artist == null)? \"[no artist]\" : artist.label;\n try {\n // Compute the SHA-1 hash of our fields\n MessageDigest digest = MessageDigest.getInstance(\"SHA1\");\n digest.update(safeTitle.getBytes(\"UTF-8\"));\n digest.update((byte) 0);\n digest.update(artistName.getBytes(\"UTF-8\"));\n digest.update((byte) 0);\n digestInteger(digest, duration);\n digest.update(waveformDetail.getData());\n for (int i = 1; i <= beatGrid.beatCount; i++) {\n digestInteger(digest, beatGrid.getBeatWithinBar(i));\n digestInteger(digest, (int)beatGrid.getTimeWithinTrack(i));\n }\n byte[] result = digest.digest();\n\n // Create a hex string representation of the hash\n StringBuilder hex = new StringBuilder(result.length * 2);\n for (byte aResult : result) {\n hex.append(Integer.toString((aResult & 0xff) + 0x100, 16).substring(1));\n }\n\n return hex.toString();\n\n } catch (NullPointerException e) {\n logger.info(\"Returning null track signature because an input element was null.\", e);\n } catch (NoSuchAlgorithmException e) {\n logger.error(\"Unable to obtain SHA-1 MessageDigest instance for computing track signatures.\", e);\n } catch (UnsupportedEncodingException e) {\n logger.error(\"Unable to work with UTF-8 string encoding for computing track signatures.\", e);\n }\n return null; // We were unable to compute a signature\n }", "public void check(CollectionDescriptorDef collDef, String checkLevel) throws ConstraintException\r\n {\r\n ensureElementClassRef(collDef, checkLevel);\r\n checkInheritedForeignkey(collDef, checkLevel);\r\n ensureCollectionClass(collDef, checkLevel);\r\n checkProxyPrefetchingLimit(collDef, checkLevel);\r\n checkOrderby(collDef, checkLevel);\r\n checkQueryCustomizer(collDef, checkLevel);\r\n }", "private static boolean isWideningPrimitive(Class<?> argumentClass, Class<?> targetClass) {\n return WIDENING_TABLE.containsKey(argumentClass) && WIDENING_TABLE.get(argumentClass).contains(targetClass);\n }", "public static String expandLine(CharSequence self, int tabStop) {\n String s = self.toString();\n int index;\n while ((index = s.indexOf('\\t')) != -1) {\n StringBuilder builder = new StringBuilder(s);\n int count = tabStop - index % tabStop;\n builder.deleteCharAt(index);\n for (int i = 0; i < count; i++) builder.insert(index, \" \");\n s = builder.toString();\n }\n return s;\n }", "private void readTasks(Project phoenixProject, Storepoint storepoint)\n {\n processLayouts(phoenixProject);\n processActivityCodes(storepoint);\n processActivities(storepoint);\n updateDates();\n }", "public void bindDelete(PreparedStatement stmt, ClassDescriptor cld, Object obj) throws SQLException\r\n {\r\n if (cld.getDeleteProcedure() != null)\r\n {\r\n this.bindProcedure(stmt, cld, obj, cld.getDeleteProcedure());\r\n }\r\n else\r\n {\r\n int index = 1;\r\n ValueContainer[] values, currentLockingValues;\r\n\r\n currentLockingValues = cld.getCurrentLockingValues(obj);\r\n // parameters for WHERE-clause pk\r\n values = getKeyValues(m_broker, cld, obj);\r\n for (int i = 0; i < values.length; i++)\r\n {\r\n setObjectForStatement(stmt, index, values[i].getValue(), values[i].getJdbcType().getType());\r\n index++;\r\n }\r\n\r\n // parameters for WHERE-clause locking\r\n values = currentLockingValues;\r\n for (int i = 0; i < values.length; i++)\r\n {\r\n setObjectForStatement(stmt, index, values[i].getValue(), values[i].getJdbcType().getType());\r\n index++;\r\n }\r\n }\r\n }", "private void setResourceInformation() {\n\n String sitePath = m_cms.getSitePath(m_resource);\n int pathEnd = sitePath.lastIndexOf('/') + 1;\n String baseName = sitePath.substring(pathEnd);\n m_sitepath = sitePath.substring(0, pathEnd);\n switch (CmsMessageBundleEditorTypes.BundleType.toBundleType(\n OpenCms.getResourceManager().getResourceType(m_resource).getTypeName())) {\n case PROPERTY:\n String localeSuffix = CmsStringUtil.getLocaleSuffixForName(baseName);\n if ((null != localeSuffix) && !localeSuffix.isEmpty()) {\n baseName = baseName.substring(\n 0,\n baseName.lastIndexOf(localeSuffix) - (1 /* cut off trailing underscore, too*/));\n m_locale = CmsLocaleManager.getLocale(localeSuffix);\n }\n if ((null == m_locale) || !m_locales.contains(m_locale)) {\n m_switchedLocaleOnOpening = true;\n m_locale = m_locales.iterator().next();\n }\n break;\n case XML:\n m_locale = OpenCms.getLocaleManager().getBestAvailableLocaleForXmlContent(\n m_cms,\n m_resource,\n m_xmlBundle);\n break;\n case DESCRIPTOR:\n m_basename = baseName.substring(\n 0,\n baseName.length() - CmsMessageBundleEditorTypes.Descriptor.POSTFIX.length());\n m_locale = new Locale(\"en\");\n break;\n default:\n throw new IllegalArgumentException(\n Messages.get().container(\n Messages.ERR_UNSUPPORTED_BUNDLE_TYPE_1,\n CmsMessageBundleEditorTypes.BundleType.toBundleType(\n OpenCms.getResourceManager().getResourceType(m_resource).getTypeName())).toString());\n }\n m_basename = baseName;\n\n }", "public String getDynamicValue(String attribute) {\n\n return null == m_dynamicValues ? null : m_dynamicValues.get(attribute);\n }" ]
Checks to see if the two matrices have the same shape and same pattern of non-zero elements @param a Matrix @param b Matrix @return true if the structure is the same
[ "public static boolean isSameStructure(DMatrixSparseCSC a , DMatrixSparseCSC b) {\n if( a.numRows == b.numRows && a.numCols == b.numCols && a.nz_length == b.nz_length) {\n for (int i = 0; i <= a.numCols; i++) {\n if( a.col_idx[i] != b.col_idx[i] )\n return false;\n }\n for (int i = 0; i < a.nz_length; i++) {\n if( a.nz_rows[i] != b.nz_rows[i] )\n return false;\n }\n return true;\n }\n return false;\n }" ]
[ "private static Properties loadGradleProperties(FilePath gradlePropertiesFilePath)\n throws IOException, InterruptedException {\n return gradlePropertiesFilePath.act(new MasterToSlaveFileCallable<Properties>() {\n public Properties invoke(File gradlePropertiesFile, VirtualChannel channel) throws IOException, InterruptedException {\n Properties gradleProps = new Properties();\n if (gradlePropertiesFile.exists()) {\n debuggingLogger.fine(\"Gradle properties file exists at: \" + gradlePropertiesFile.getAbsolutePath());\n FileInputStream stream = null;\n try {\n stream = new FileInputStream(gradlePropertiesFile);\n gradleProps.load(stream);\n } catch (IOException e) {\n debuggingLogger.fine(\"IO exception occurred while trying to read properties file from: \" +\n gradlePropertiesFile.getAbsolutePath());\n throw new RuntimeException(e);\n } finally {\n IOUtils.closeQuietly(stream);\n }\n }\n return gradleProps;\n }\n });\n\n }", "protected boolean isPrefixBlock(long divisionValue, long upperValue, int divisionPrefixLen) {\n\t\tif(divisionPrefixLen == 0) {\n\t\t\treturn divisionValue == 0 && upperValue == getMaxValue();\n\t\t}\n\t\tlong ones = ~0L;\n\t\tlong divisionBitMask = ~(ones << getBitCount());\n\t\tlong divisionPrefixMask = ones << (getBitCount() - divisionPrefixLen);\n\t\tlong divisionNonPrefixMask = ~divisionPrefixMask;\n\t\treturn testRange(divisionValue,\n\t\t\t\tupperValue,\n\t\t\t\tupperValue,\n\t\t\t\tdivisionPrefixMask & divisionBitMask,\n\t\t\t\tdivisionNonPrefixMask);\n\t}", "protected void print(String text) {\n String tableStart = format(PARAMETER_TABLE_START, PARAMETER_TABLE_START);\n String tableEnd = format(PARAMETER_TABLE_END, PARAMETER_TABLE_END);\n boolean containsTable = text.contains(tableStart) && text.contains(tableEnd);\n String textToPrint = containsTable ? transformPrintingTable(text, tableStart, tableEnd) : text;\n print(output, textToPrint\n .replace(format(PARAMETER_VALUE_START, PARAMETER_VALUE_START), format(\"parameterValueStart\", EMPTY))\n .replace(format(PARAMETER_VALUE_END, PARAMETER_VALUE_END), format(\"parameterValueEnd\", EMPTY))\n .replace(format(PARAMETER_VALUE_NEWLINE, PARAMETER_VALUE_NEWLINE), format(\"parameterValueNewline\", NL)));\n }", "public <T> T get(Class<T> type) {\n return get(type.getName(), type);\n }", "protected void addFacetPart(CmsSolrQuery query) {\n\n query.set(\"facet\", \"true\");\n String excludes = \"\";\n if (m_config.getIgnoreAllFacetFilters()\n || (!m_state.getCheckedEntries().isEmpty() && !m_config.getIsAndFacet())) {\n excludes = \"{!ex=\" + m_config.getIgnoreTags() + \"}\";\n }\n\n for (I_CmsFacetQueryItem q : m_config.getQueryList()) {\n query.add(\"facet.query\", excludes + q.getQuery());\n }\n }", "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 }", "private void addTasks(MpxjTreeNode parentNode, ChildTaskContainer parent)\n {\n for (Task task : parent.getChildTasks())\n {\n final Task t = task;\n MpxjTreeNode childNode = new MpxjTreeNode(task, TASK_EXCLUDED_METHODS)\n {\n @Override public String toString()\n {\n return t.getName();\n }\n };\n parentNode.add(childNode);\n addTasks(childNode, task);\n }\n }", "private void started(final ProcessorGraphNode processorGraphNode) {\n this.processorLock.lock();\n try {\n this.runningProcessors.put(processorGraphNode.getProcessor(), null);\n } finally {\n this.processorLock.unlock();\n }\n }", "public static List<Integer> asList(int[] a) {\r\n List<Integer> result = new ArrayList<Integer>(a.length);\r\n for (int i = 0; i < a.length; i++) {\r\n result.add(Integer.valueOf(a[i]));\r\n }\r\n return result;\r\n }" ]
Prints the data for a single class to the given stream. This will be a single line in CSV. @param out the output to write to @param classRecord the class record to write @param entityIdValue the item id that this class record belongs to
[ "private void printClassRecord(PrintStream out, ClassRecord classRecord,\n\t\t\tEntityIdValue entityIdValue) {\n\t\tprintTerms(out, classRecord.itemDocument, entityIdValue, \"\\\"\"\n\t\t\t\t+ getClassLabel(entityIdValue) + \"\\\"\");\n\t\tprintImage(out, classRecord.itemDocument);\n\n\t\tout.print(\",\" + classRecord.itemCount + \",\" + classRecord.subclassCount);\n\n\t\tprintClassList(out, classRecord.superClasses);\n\n\t\tHashSet<EntityIdValue> superClasses = new HashSet<>();\n\t\tfor (EntityIdValue superClass : classRecord.superClasses) {\n\t\t\taddSuperClasses(superClass, superClasses);\n\t\t}\n\n\t\tprintClassList(out, superClasses);\n\n\t\tprintRelatedProperties(out, classRecord);\n\n\t\tout.println(\"\");\n\t}" ]
[ "public static void redeployLinksAndTransformOperation(OperationContext context, ModelNode removeOperation, PathAddress deploymentsRootAddress, Set<String> runtimeNames) throws OperationFailedException {\n Set<String> deploymentNames = listDeployments(context.readResourceFromRoot(deploymentsRootAddress), runtimeNames);\n Operations.CompositeOperationBuilder opBuilder = Operations.CompositeOperationBuilder.create();\n if (deploymentNames.isEmpty()) {\n for (String s : runtimeNames) {\n ServerLogger.ROOT_LOGGER.debugf(\"We haven't found any deployment for %s in server-group %s\", s, deploymentsRootAddress.getLastElement().getValue());\n }\n }\n if(removeOperation != null) {\n opBuilder.addStep(removeOperation);\n }\n for (String deploymentName : deploymentNames) {\n opBuilder.addStep(addRedeployStep(deploymentsRootAddress.append(DEPLOYMENT, deploymentName)));\n }\n List<DomainOperationTransmuter> transformers = context.getAttachment(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS);\n if (transformers == null) {\n context.attach(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS, transformers = new ArrayList<>());\n }\n final ModelNode slave = opBuilder.build().getOperation();\n transformers.add(new OverlayOperationTransmuter(slave, context.getCurrentAddress()));\n }", "public 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 void swapSubstring(BitString other, int start, int length)\n {\n assertValidIndex(start);\n other.assertValidIndex(start);\n \n int word = start / WORD_LENGTH;\n\n int partialWordSize = (WORD_LENGTH - start) % WORD_LENGTH;\n if (partialWordSize > 0)\n {\n swapBits(other, word, 0xFFFFFFFF << (WORD_LENGTH - partialWordSize));\n ++word;\n }\n\n int remainingBits = length - partialWordSize;\n int stop = remainingBits / WORD_LENGTH;\n for (int i = word; i < stop; i++)\n {\n int temp = data[i];\n data[i] = other.data[i];\n other.data[i] = temp;\n }\n\n remainingBits %= WORD_LENGTH;\n if (remainingBits > 0)\n {\n swapBits(other, word, 0xFFFFFFFF >>> (WORD_LENGTH - remainingBits));\n }\n }", "@Override\n\tprotected void doProcessQueuedOps(PersistentCollection collection, Serializable key, int nextIndex, SharedSessionContractImplementor session)\n\t\t\tthrows HibernateException {\n\t\t// nothing to do\n\t}", "public static void ensureXPathNotEmpty(NodeList nodeList, String expression) {\n if (nodeList == null || nodeList.getLength() == 0) {\n throw LOG.unableToFindXPathExpression(expression);\n }\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 static ConsistencyLevel determineConsistency(Map<Value, Set<ClusterNode>> versionNodeSetMap,\n int replicationFactor) {\n boolean fullyConsistent = true;\n Value latestVersion = null;\n for (Map.Entry<Value, Set<ClusterNode>> versionNodeSetEntry : versionNodeSetMap.entrySet()) {\n Value value = versionNodeSetEntry.getKey();\n if (latestVersion == null) {\n latestVersion = value;\n } else if (value.isTimeStampLaterThan(latestVersion)) {\n latestVersion = value;\n }\n Set<ClusterNode> nodeSet = versionNodeSetEntry.getValue();\n fullyConsistent = fullyConsistent && (nodeSet.size() == replicationFactor);\n }\n if (fullyConsistent) {\n return ConsistencyLevel.FULL;\n } else {\n // latest write consistent, effectively consistent\n if (latestVersion != null && versionNodeSetMap.get(latestVersion).size() == replicationFactor) {\n return ConsistencyLevel.LATEST_CONSISTENT;\n }\n // all other states inconsistent\n return ConsistencyLevel.INCONSISTENT;\n }\n }", "protected void addProcessedData(List<List<CRFDatum<Collection<String>, String>>> processedData, int[][][][] data,\r\n int[][] labels, int offset) {\r\n for (int i = 0, pdSize = processedData.size(); i < pdSize; i++) {\r\n int dataIndex = i + offset;\r\n List<CRFDatum<Collection<String>, String>> document = processedData.get(i);\r\n int dsize = document.size();\r\n labels[dataIndex] = new int[dsize];\r\n data[dataIndex] = new int[dsize][][];\r\n for (int j = 0; j < dsize; j++) {\r\n CRFDatum<Collection<String>, String> crfDatum = document.get(j);\r\n // add label, they are offset by extra context\r\n labels[dataIndex][j] = classIndex.indexOf(crfDatum.label());\r\n // add features\r\n List<Collection<String>> cliques = crfDatum.asFeatures();\r\n int csize = cliques.size();\r\n data[dataIndex][j] = new int[csize][];\r\n for (int k = 0; k < csize; k++) {\r\n Collection<String> features = cliques.get(k);\r\n\r\n // Debug only: Remove\r\n // if (j < windowSize) {\r\n // System.err.println(\"addProcessedData: Features Size: \" +\r\n // features.size());\r\n // }\r\n\r\n data[dataIndex][j][k] = new int[features.size()];\r\n\r\n int m = 0;\r\n try {\r\n for (String feature : features) {\r\n // System.err.println(\"feature \" + feature);\r\n // if (featureIndex.indexOf(feature)) ;\r\n if (featureIndex == null) {\r\n System.out.println(\"Feature is NULL!\");\r\n }\r\n data[dataIndex][j][k][m] = featureIndex.indexOf(feature);\r\n m++;\r\n }\r\n } catch (Exception e) {\r\n e.printStackTrace();\r\n System.err.printf(\"[index=%d, j=%d, k=%d, m=%d]\\n\", dataIndex, j, k, m);\r\n System.err.println(\"data.length \" + data.length);\r\n System.err.println(\"data[dataIndex].length \" + data[dataIndex].length);\r\n System.err.println(\"data[dataIndex][j].length \" + data[dataIndex][j].length);\r\n System.err.println(\"data[dataIndex][j][k].length \" + data[dataIndex][j].length);\r\n System.err.println(\"data[dataIndex][j][k][m] \" + data[dataIndex][j][k][m]);\r\n return;\r\n }\r\n }\r\n }\r\n }\r\n }", "public int addKey(String key) {\n JdkUtils.requireNonNull(key);\n int nextIndex = keys.size();\n final Integer mapIndex = JdkUtils.putIfAbsent(keys, key, nextIndex);\n return mapIndex == null ? nextIndex : mapIndex;\n }" ]
Extracts the list of columns from the given field list. @param fields The fields @return The corresponding columns
[ "private List getColumns(List fields)\r\n {\r\n ArrayList columns = new ArrayList();\r\n\r\n for (Iterator it = fields.iterator(); it.hasNext();)\r\n {\r\n FieldDescriptorDef fieldDef = (FieldDescriptorDef)it.next();\r\n\r\n columns.add(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN));\r\n }\r\n return columns;\r\n }" ]
[ "private void readResourceCustomPropertyDefinitions(Resources gpResources)\n {\n CustomField field = m_projectFile.getCustomFields().getCustomField(ResourceField.TEXT1);\n field.setAlias(\"Phone\");\n\n for (CustomPropertyDefinition definition : gpResources.getCustomPropertyDefinition())\n {\n //\n // Find the next available field of the correct type.\n //\n String type = definition.getType();\n FieldType fieldType = RESOURCE_PROPERTY_TYPES.get(type).getField();\n\n //\n // If we have run out of fields of the right type, try using a text field.\n //\n if (fieldType == null)\n {\n fieldType = RESOURCE_PROPERTY_TYPES.get(\"text\").getField();\n }\n\n //\n // If we actually have a field available, set the alias to match\n // the name used in GanttProject.\n //\n if (fieldType != null)\n {\n field = m_projectFile.getCustomFields().getCustomField(fieldType);\n field.setAlias(definition.getName());\n String defaultValue = definition.getDefaultValue();\n if (defaultValue != null && defaultValue.isEmpty())\n {\n defaultValue = null;\n }\n m_resourcePropertyDefinitions.put(definition.getId(), new Pair<FieldType, String>(fieldType, defaultValue));\n }\n }\n }", "public LuaPreparedScript endPreparedScriptReturn(LuaValue value, LuaScriptConfig config) {\n add(new LuaAstReturnStatement(argument(value)));\n return endPreparedScript(config);\n }", "public static onlinkipv6prefix get(nitro_service service, String ipv6prefix) throws Exception{\n\t\tonlinkipv6prefix obj = new onlinkipv6prefix();\n\t\tobj.set_ipv6prefix(ipv6prefix);\n\t\tonlinkipv6prefix response = (onlinkipv6prefix) obj.get_resource(service);\n\t\treturn response;\n\t}", "private ResourceField selectField(ResourceField[] fields, int index)\n {\n if (index < 1 || index > fields.length)\n {\n throw new IllegalArgumentException(index + \" is not a valid field index\");\n }\n return (fields[index - 1]);\n }", "public CustomHeadersInterceptor addHeaderMultimap(Map<String, List<String>> headers) {\n this.headers.putAll(headers);\n return this;\n }", "public static sslvserver_sslcertkey_binding[] get(nitro_service service, String vservername) throws Exception{\n\t\tsslvserver_sslcertkey_binding obj = new sslvserver_sslcertkey_binding();\n\t\tobj.set_vservername(vservername);\n\t\tsslvserver_sslcertkey_binding response[] = (sslvserver_sslcertkey_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public List<Gallery> getList(String userId, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIST);\r\n parameters.put(\"user_id\", userId);\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", String.valueOf(perPage));\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", String.valueOf(page));\r\n }\r\n\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element element = response.getPayload();\r\n GalleryList<Gallery> galleries = new GalleryList<Gallery>();\r\n galleries.setPage(element.getAttribute(\"page\"));\r\n galleries.setPages(element.getAttribute(\"pages\"));\r\n galleries.setPerPage(element.getAttribute(\"per_page\"));\r\n galleries.setTotal(element.getAttribute(\"total\"));\r\n\r\n NodeList galleryNodes = element.getElementsByTagName(\"gallery\");\r\n for (int i = 0; i < galleryNodes.getLength(); i++) {\r\n Element galleryElement = (Element) galleryNodes.item(i);\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.setPrimaryPhotoFarm(galleryElement.getAttribute(\"primary_photo_farm\"));\r\n gallery.setPrimaryPhotoSecret(galleryElement.getAttribute(\"primary_photo_secret\"));\r\n gallery.setPhotoCount(galleryElement.getAttribute(\"count_photos\"));\r\n gallery.setVideoCount(galleryElement.getAttribute(\"count_videos\"));\r\n\r\n galleries.add(gallery);\r\n }\r\n return galleries;\r\n }", "public ExecutorLoadBalancingConfig<GROUP> useLoadBalancedEnumOrdinalPrioritizer(Class<GROUP> groupClass) {\n if(!groupClass.isEnum()) {\n throw new IllegalArgumentException(\"The group class \"+groupClass+\" is not an enum\");\n }\n groupPrioritizer = new LoadBalancedPriorityPrioritizer<GROUP>(new EnumOrdinalPrioritizer<GROUP>());\n return this;\n }", "private void ensureConversion(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n // we issue a warning if we encounter a field with a java.util.Date java type without a conversion\r\n if (\"java.util.Date\".equals(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JAVA_TYPE)) &&\r\n !fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_CONVERSION))\r\n {\r\n LogHelper.warn(true,\r\n FieldDescriptorConstraints.class,\r\n \"ensureConversion\",\r\n \"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\r\n \" of type java.util.Date is directly mapped to jdbc-type \"+\r\n fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE)+\r\n \". However, most JDBC drivers can't handle java.util.Date directly so you might want to \"+\r\n \" use a conversion for converting it to a JDBC datatype like TIMESTAMP.\");\r\n }\r\n\r\n String conversionClass = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_CONVERSION);\r\n\r\n if (((conversionClass == null) || (conversionClass.length() == 0)) &&\r\n fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_CONVERSION) &&\r\n fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_JDBC_TYPE).equals(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE)))\r\n {\r\n conversionClass = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_CONVERSION);\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_CONVERSION, conversionClass);\r\n }\r\n // now checking\r\n if (CHECKLEVEL_STRICT.equals(checkLevel) && (conversionClass != null) && (conversionClass.length() > 0))\r\n {\r\n InheritanceHelper helper = new InheritanceHelper();\r\n\r\n try\r\n {\r\n if (!helper.isSameOrSubTypeOf(conversionClass, CONVERSION_INTERFACE))\r\n {\r\n throw new ConstraintException(\"The conversion class specified for field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" does not implement the necessary interface \"+CONVERSION_INTERFACE);\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"The class \"+ex.getMessage()+\" hasn't been found on the classpath while checking the conversion class specified for field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName());\r\n }\r\n }\r\n}" ]
Extract the field types from the fieldConfigs if they have not already been configured.
[ "public void extractFieldTypes(DatabaseType databaseType) throws SQLException {\n\t\tif (fieldTypes == null) {\n\t\t\tif (fieldConfigs == null) {\n\t\t\t\tfieldTypes = extractFieldTypes(databaseType, dataClass, tableName);\n\t\t\t} else {\n\t\t\t\tfieldTypes = convertFieldConfigs(databaseType, tableName, fieldConfigs);\n\t\t\t}\n\t\t}\n\t}" ]
[ "public 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 }", "public synchronized void addCertAndPrivateKey(String hostname, final X509Certificate cert, final PrivateKey privKey)\n\tthrows KeyStoreException, CertificateException, NoSuchAlgorithmException\n\t{\n//\t\tString alias = ThumbprintUtil.getThumbprint(cert);\n\n\t\t_ks.deleteEntry(hostname);\n\n _ks.setCertificateEntry(hostname, cert);\n\t\t_ks.setKeyEntry(hostname, privKey, _keypassword, new java.security.cert.Certificate[] {cert});\n\n\t\tif(persistImmediately)\n\t\t{\n\t\t\tpersist();\n\t\t}\n\n\t}", "@ArgumentsChecked\n\t@Throws(IllegalNullArgumentException.class)\n\tpublic static byte checkByte(@Nonnull final Number number) {\n\t\tCheck.notNull(number, \"number\");\n\t\tif (!isInByteRange(number)) {\n\t\t\tthrow new IllegalNumberRangeException(number.toString(), BYTE_MIN, BYTE_MAX);\n\t\t}\n\n\t\treturn number.byteValue();\n\t}", "public CmsJspInstanceDateBean getToInstanceDate() {\n\n if (m_instanceDate == null) {\n m_instanceDate = new CmsJspInstanceDateBean(getToDate(), m_cms.getRequestContext().getLocale());\n }\n return m_instanceDate;\n }", "private void checkForCycles(DefaultDirectedWeightedGraph<RuleProvider, DefaultEdge> graph)\n {\n CycleDetector<RuleProvider, DefaultEdge> cycleDetector = new CycleDetector<>(graph);\n\n if (cycleDetector.detectCycles())\n {\n // if we have cycles, then try to throw an exception with some usable data\n Set<RuleProvider> cycles = cycleDetector.findCycles();\n StringBuilder errorSB = new StringBuilder();\n for (RuleProvider cycle : cycles)\n {\n errorSB.append(\"Found dependency cycle involving: \" + cycle.getMetadata().getID()).append(System.lineSeparator());\n Set<RuleProvider> subCycleSet = cycleDetector.findCyclesContainingVertex(cycle);\n for (RuleProvider subCycle : subCycleSet)\n {\n errorSB.append(\"\\tSubcycle: \" + subCycle.getMetadata().getID()).append(System.lineSeparator());\n }\n }\n throw new RuntimeException(\"Dependency cycles detected: \" + errorSB.toString());\n }\n }", "public void setManyToOneAttribute(String name, AssociationValue value) {\n\t\tensureAttributes();\n\t\tAttribute attribute = new ManyToOneAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetAllAttributes().put(name, attribute);\n\n\t}", "public static String fixLanguageCodeIfDeprecated(String wikimediaLanguageCode) {\n\t\tif (DEPRECATED_LANGUAGE_CODES.containsKey(wikimediaLanguageCode)) {\n\t\t\treturn DEPRECATED_LANGUAGE_CODES.get(wikimediaLanguageCode);\n\t\t} else {\n\t\t\treturn wikimediaLanguageCode;\n\t\t}\n\t}", "private Renderer recycle(View convertView, T content) {\n Renderer renderer = (Renderer) convertView.getTag();\n renderer.onRecycle(content);\n return renderer;\n }", "public static long count(nitro_service service, Long id) throws Exception{\n\t\tbridgegroup_vlan_binding obj = new bridgegroup_vlan_binding();\n\t\tobj.set_id(id);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tbridgegroup_vlan_binding response[] = (bridgegroup_vlan_binding[]) obj.get_resources(service,option);\n\t\tif (response != null) {\n\t\t\treturn response[0].__count;\n\t\t}\n\t\treturn 0;\n\t}" ]
Create an object of the given type using a constructor that matches the supplied arguments and invoke the setters with the supplied variables. @param <T> the object type @param clazz the type to create @param args the arguments to the constructor @param vars the named arguments for setters @return a new object of the given type, initialized with the given arguments @throws NoSuchConstructorException if there is not a constructor that matches the given arguments @throws AmbiguousConstructorException if there is more than one constructor that matches the given arguments @throws ReflectiveOperationException if any of the reflective operations throw an exception
[ "public static <T> T createObject(final Class<T> clazz, final Object[] args, final Map<String,Object> vars) \n throws NoSuchConstructorException, AmbiguousConstructorException, ReflectiveOperationException {\n return invokeSetters(findConstructor(clazz, args).newInstance(args), vars);\n }" ]
[ "Map<UUID, UUID> getActivityCodes(Activity activity)\n {\n Map<UUID, UUID> map = m_activityCodeCache.get(activity);\n if (map == null)\n {\n map = new HashMap<UUID, UUID>();\n m_activityCodeCache.put(activity, map);\n for (CodeAssignment ca : activity.getCodeAssignment())\n {\n UUID code = getUUID(ca.getCodeUuid(), ca.getCode());\n UUID value = getUUID(ca.getValueUuid(), ca.getValue());\n map.put(code, value);\n }\n }\n return map;\n }", "public static double calculateBoundedness(double D, int N, double timelag, double confRadius){\n\t\tdouble r = confRadius;\n\t\tdouble cov_area = a(N)*D*timelag;\n\t\tdouble res = cov_area/(4*r*r);\n\t\treturn res;\n\t}", "@Pure\n\t@Inline(value = \"$3.union($1, $4.singletonMap($2.getKey(), $2.getValue()))\",\n\t\t\timported = { MapExtensions.class, Collections.class })\n\tpublic static <K, V> Map<K, V> operator_plus(Map<K, V> left, final Pair<? extends K, ? extends V> right) {\n\t\treturn union(left, Collections.singletonMap(right.getKey(), right.getValue()));\n\t}", "public void stop() {\n instanceLock.writeLock().lock();\n try {\n for (final NamespaceChangeStreamListener streamer : nsStreamers.values()) {\n streamer.stop();\n }\n } finally {\n instanceLock.writeLock().unlock();\n }\n }", "public Task add()\n {\n Task task = new Task(m_projectFile, (Task) null);\n add(task);\n m_projectFile.getChildTasks().add(task);\n return task;\n }", "private static ClassLoader getParentCl()\n {\n try\n {\n Method m = ClassLoader.class.getMethod(\"getPlatformClassLoader\");\n return (ClassLoader) m.invoke(null);\n }\n catch (NoSuchMethodException e)\n {\n // Java < 9, just use the bootstrap CL.\n return null;\n }\n catch (Exception e)\n {\n throw new JqmInitError(\"Could not fetch Platform Class Loader\", e);\n }\n }", "@Pure\n\tpublic static <P1> Procedure0 curry(final Procedure1<? super P1> procedure, final P1 argument) {\n\t\tif (procedure == null)\n\t\t\tthrow new NullPointerException(\"procedure\");\n\t\treturn new Procedure0() {\n\t\t\t@Override\n\t\t\tpublic void apply() {\n\t\t\t\tprocedure.apply(argument);\n\t\t\t}\n\t\t};\n\t}", "public static String replaceVariables( final VariableResolver pResolver, final String pExpression, final String pOpen, final String pClose ) {\n final char[] open = pOpen.toCharArray();\n final char[] close = pClose.toCharArray();\n\n final StringBuilder out = new StringBuilder();\n StringBuilder sb = new StringBuilder();\n char[] last = null;\n int wo = 0;\n int wc = 0;\n int level = 0;\n for (char c : pExpression.toCharArray()) {\n if (c == open[wo]) {\n if (wc > 0) {\n sb.append(close, 0, wc);\n }\n wc = 0;\n wo++;\n if (open.length == wo) {\n // found open\n if (last == open) {\n out.append(open);\n }\n level++;\n out.append(sb);\n sb = new StringBuilder();\n wo = 0;\n last = open;\n }\n } else if (c == close[wc]) {\n if (wo > 0) {\n sb.append(open, 0, wo);\n }\n wo = 0;\n wc++;\n if (close.length == wc) {\n // found close\n if (last == open) {\n final String variable = pResolver.get(sb.toString());\n if (variable != null) {\n out.append(variable);\n } else {\n out.append(open);\n out.append(sb);\n out.append(close);\n }\n } else {\n out.append(sb);\n out.append(close);\n }\n sb = new StringBuilder();\n level--;\n wc = 0;\n last = close;\n }\n } else {\n\n if (wo > 0) {\n sb.append(open, 0, wo);\n }\n\n if (wc > 0) {\n sb.append(close, 0, wc);\n }\n\n sb.append(c);\n\n wo = wc = 0;\n }\n }\n\n if (wo > 0) {\n sb.append(open, 0, wo);\n }\n\n if (wc > 0) {\n sb.append(close, 0, wc);\n }\n\n if (level > 0) {\n out.append(open);\n }\n out.append(sb);\n\n return out.toString();\n }", "public static base_response rename(nitro_service client, responderpolicy resource, String new_name) throws Exception {\n\t\tresponderpolicy renameresource = new responderpolicy();\n\t\trenameresource.name = resource.name;\n\t\treturn renameresource.rename_resource(client,new_name);\n\t}" ]
Set the week day the events should occur. @param weekDay the week day to set.
[ "public final void setWeekDay(WeekDay weekDay) {\n\n SortedSet<WeekDay> wds = new TreeSet<>();\n if (null != weekDay) {\n wds.add(weekDay);\n }\n setWeekDays(wds);\n\n }" ]
[ "private boolean checkConverged(DMatrixRMaj A) {\n double worst = 0;\n double worst2 = 0;\n for( int j = 0; j < A.numRows; j++ ) {\n double val = Math.abs(q2.data[j] - q0.data[j]);\n if( val > worst ) worst = val;\n val = Math.abs(q2.data[j] + q0.data[j]);\n if( val > worst2 ) worst2 = val;\n }\n\n // swap vectors\n DMatrixRMaj temp = q0;\n q0 = q2;\n q2 = temp;\n\n if( worst < tol )\n return true;\n else if( worst2 < tol )\n return true;\n else\n return false;\n }", "void applyFreshParticleOnScreen(\n @NonNull final Scene scene,\n final int position\n ) {\n final int w = scene.getWidth();\n final int h = scene.getHeight();\n if (w == 0 || h == 0) {\n throw new IllegalStateException(\n \"Cannot generate particles if scene width or height is 0\");\n }\n\n final double direction = Math.toRadians(random.nextInt(360));\n final float dCos = (float) Math.cos(direction);\n final float dSin = (float) Math.sin(direction);\n final float x = random.nextInt(w);\n final float y = random.nextInt(h);\n final float speedFactor = newRandomIndividualParticleSpeedFactor();\n final float radius = newRandomIndividualParticleRadius(scene);\n\n scene.setParticleData(\n position,\n x,\n y,\n dCos,\n dSin,\n radius,\n speedFactor);\n }", "private String getHierarchyTable(ClassDescriptorDef classDef)\r\n {\r\n ArrayList queue = new ArrayList();\r\n String tableName = null;\r\n\r\n queue.add(classDef);\r\n\r\n while (!queue.isEmpty())\r\n {\r\n ClassDescriptorDef curClassDef = (ClassDescriptorDef)queue.get(0);\r\n\r\n queue.remove(0);\r\n\r\n if (curClassDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, true))\r\n {\r\n if (tableName != null)\r\n {\r\n if (!tableName.equals(curClassDef.getProperty(PropertyHelper.OJB_PROPERTY_TABLE)))\r\n {\r\n return null;\r\n }\r\n }\r\n else\r\n {\r\n tableName = curClassDef.getProperty(PropertyHelper.OJB_PROPERTY_TABLE);\r\n }\r\n }\r\n for (Iterator it = curClassDef.getExtentClasses(); it.hasNext();)\r\n {\r\n curClassDef = (ClassDescriptorDef)it.next();\r\n\r\n if (curClassDef.getReference(\"super\") == null)\r\n {\r\n queue.add(curClassDef);\r\n }\r\n }\r\n }\r\n return tableName;\r\n }", "private void addDependencyToGraph(final DbDependency dependency, final AbstractGraph graph, final int depth, final String parentId) {\n // In that case of Axway artifact we will add a module to the graph\n if (filters.getCorporateFilter().filter(dependency)) {\n final DbModule dbTarget = repoHandler.getModuleOf(dependency.getTarget());\n\n // if there is no module, add the artifact to the graph\n if(dbTarget == null){\n LOG.error(\"Got missing reference: \" + dependency.getTarget());\n final DbArtifact dbArtifact = DataUtils.createDbArtifact(dependency.getTarget());\n final String targetElementId = graph.getId(dbArtifact);\n graph.addElement(targetElementId, dbArtifact.getVersion(), false);\n graph.addDependency(parentId, targetElementId, dependency.getScope());\n return;\n }\n\n // Add the element to the graph\n addModuleToGraph(dbTarget, graph, depth + 1);\n\n //Add the dependency to the graph\n final String moduleElementId = graph.getId(dbTarget);\n graph.addDependency(parentId, moduleElementId, dependency.getScope());\n }\n // In case a third-party we will add an artifact\n else {\n final DbArtifact dbTarget = repoHandler.getArtifact(dependency.getTarget());\n if(dbTarget == null){\n LOG.error(\"Got missing artifact: \" + dependency.getTarget());\n return;\n }\n\n if(!graph.isTreated(graph.getId(dbTarget))){\n final ModelMapper modelMapper = new ModelMapper(repoHandler);\n final Artifact target = modelMapper.getArtifact(dbTarget);\n final String targetElementId = graph.getId(target);\n graph.addElement(targetElementId, target.getVersion(), false);\n graph.addDependency(parentId, targetElementId, dependency.getScope());\n }\n }\n }", "public Map<BsonValue, ChangeEvent<BsonDocument>> getEventsForNamespace(\n final MongoNamespace namespace\n ) {\n this.instanceLock.readLock().lock();\n final NamespaceChangeStreamListener streamer;\n try {\n streamer = nsStreamers.get(namespace);\n } finally {\n this.instanceLock.readLock().unlock();\n }\n if (streamer == null) {\n return new HashMap<>();\n }\n return streamer.getEvents();\n }", "public static String getSerializedVectorClock(VectorClock vc) {\n VectorClockWrapper vcWrapper = new VectorClockWrapper(vc);\n String serializedVC = \"\";\n try {\n serializedVC = mapper.writeValueAsString(vcWrapper);\n } catch(Exception e) {\n e.printStackTrace();\n }\n return serializedVC;\n }", "public boolean contains(Color color) {\n return exists(p -> p.toInt() == color.toPixel().toInt());\n }", "public void deleteRebalancingState(RebalanceTaskInfo stealInfo) {\n // acquire write lock\n writeLock.lock();\n try {\n RebalancerState rebalancerState = getRebalancerState();\n\n if(!rebalancerState.remove(stealInfo))\n throw new IllegalArgumentException(\"Couldn't find \" + stealInfo + \" in \"\n + rebalancerState + \" while deleting\");\n\n if(rebalancerState.isEmpty()) {\n logger.debug(\"Cleaning all rebalancing state\");\n cleanAllRebalancingState();\n } else {\n put(REBALANCING_STEAL_INFO, rebalancerState);\n initCache(REBALANCING_STEAL_INFO);\n }\n } finally {\n writeLock.unlock();\n }\n }", "public static String getHeaders(HttpServletRequest request) {\n String headerString = \"\";\n Enumeration<String> headerNames = request.getHeaderNames();\n\n while (headerNames.hasMoreElements()) {\n String name = headerNames.nextElement();\n if (name.equals(Constants.ODO_PROXY_HEADER)) {\n // skip.. don't want to log this\n continue;\n }\n\n if (headerString.length() != 0) {\n headerString += \"\\n\";\n }\n\n headerString += name + \": \" + request.getHeader(name);\n }\n\n return headerString;\n }" ]
Returns iterable with all assignments of this retention policy. @param limit the limit of entries per response. The default value is 100. @param fields the fields to retrieve. @return an iterable containing all assignments.
[ "public Iterable<BoxRetentionPolicyAssignment.Info> getAllAssignments(int limit, String ... fields) {\r\n return this.getAssignments(null, limit, fields);\r\n }" ]
[ "public void processCalendar(Row calendarRow, Map<Integer, Row> workPatternMap, Map<Integer, List<Row>> workPatternAssignmentMap, Map<Integer, List<Row>> exceptionAssignmentMap, Map<Integer, List<Row>> timeEntryMap, Map<Integer, DayType> exceptionTypeMap)\n {\n //\n // Create the calendar and add the default working hours\n //\n ProjectCalendar calendar = m_project.addCalendar();\n Integer dominantWorkPatternID = calendarRow.getInteger(\"DOMINANT_WORK_PATTERN\");\n calendar.setUniqueID(calendarRow.getInteger(\"CALENDARID\"));\n processWorkPattern(calendar, dominantWorkPatternID, workPatternMap, timeEntryMap, exceptionTypeMap);\n calendar.setName(calendarRow.getString(\"NAMK\"));\n\n //\n // Add any additional working weeks\n //\n List<Row> rows = workPatternAssignmentMap.get(calendar.getUniqueID());\n if (rows != null)\n {\n for (Row row : rows)\n {\n Integer workPatternID = row.getInteger(\"WORK_PATTERN\");\n if (!workPatternID.equals(dominantWorkPatternID))\n {\n ProjectCalendarWeek week = calendar.addWorkWeek();\n week.setDateRange(new DateRange(row.getDate(\"START_DATE\"), row.getDate(\"END_DATE\")));\n processWorkPattern(week, workPatternID, workPatternMap, timeEntryMap, exceptionTypeMap);\n }\n }\n }\n\n //\n // Add exceptions - not sure how exceptions which turn non-working days into working days are handled by Asta - if at all?\n //\n rows = exceptionAssignmentMap.get(calendar.getUniqueID());\n if (rows != null)\n {\n for (Row row : rows)\n {\n Date startDate = row.getDate(\"STARU_DATE\");\n Date endDate = row.getDate(\"ENE_DATE\");\n calendar.addCalendarException(startDate, endDate);\n }\n }\n\n m_eventManager.fireCalendarReadEvent(calendar);\n }", "public static String replaceVariables( final VariableResolver pResolver, final String pExpression, final String pOpen, final String pClose ) {\n final char[] open = pOpen.toCharArray();\n final char[] close = pClose.toCharArray();\n\n final StringBuilder out = new StringBuilder();\n StringBuilder sb = new StringBuilder();\n char[] last = null;\n int wo = 0;\n int wc = 0;\n int level = 0;\n for (char c : pExpression.toCharArray()) {\n if (c == open[wo]) {\n if (wc > 0) {\n sb.append(close, 0, wc);\n }\n wc = 0;\n wo++;\n if (open.length == wo) {\n // found open\n if (last == open) {\n out.append(open);\n }\n level++;\n out.append(sb);\n sb = new StringBuilder();\n wo = 0;\n last = open;\n }\n } else if (c == close[wc]) {\n if (wo > 0) {\n sb.append(open, 0, wo);\n }\n wo = 0;\n wc++;\n if (close.length == wc) {\n // found close\n if (last == open) {\n final String variable = pResolver.get(sb.toString());\n if (variable != null) {\n out.append(variable);\n } else {\n out.append(open);\n out.append(sb);\n out.append(close);\n }\n } else {\n out.append(sb);\n out.append(close);\n }\n sb = new StringBuilder();\n level--;\n wc = 0;\n last = close;\n }\n } else {\n\n if (wo > 0) {\n sb.append(open, 0, wo);\n }\n\n if (wc > 0) {\n sb.append(close, 0, wc);\n }\n\n sb.append(c);\n\n wo = wc = 0;\n }\n }\n\n if (wo > 0) {\n sb.append(open, 0, wo);\n }\n\n if (wc > 0) {\n sb.append(close, 0, wc);\n }\n\n if (level > 0) {\n out.append(open);\n }\n out.append(sb);\n\n return out.toString();\n }", "@Override\r\n public String upload(InputStream in, UploadMetaData metaData) throws FlickrException {\r\n Payload payload = new Payload(in);\r\n return sendUploadRequest(metaData, payload);\r\n }", "public void setModel(Database databaseModel, DescriptorRepository objModel)\r\n {\r\n _dbModel = databaseModel;\r\n _preparedModel = new PreparedModel(objModel, databaseModel);\r\n }", "public double[] getMoneynessAsOffsets() {\r\n\t\tDoubleStream moneyness = getGridNodesPerMoneyness().keySet().stream().mapToDouble(Integer::doubleValue);\r\n\t\tif(quotingConvention == QuotingConvention.PAYERVOLATILITYLOGNORMAL) {\r\n\t\t\tmoneyness = moneyness.map(new DoubleUnaryOperator() {\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic double applyAsDouble(double x) {\r\n\t\t\t\t\treturn x * 0.01;\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t} else if(quotingConvention == QuotingConvention.RECEIVERPRICE) {\r\n\t\t\tmoneyness = moneyness.map(new DoubleUnaryOperator() {\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic double applyAsDouble(double x) {\r\n\t\t\t\t\treturn - x * 0.0001;\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t} else {\r\n\t\t\tmoneyness = moneyness.map(new DoubleUnaryOperator() {\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic double applyAsDouble(double x) {\r\n\t\t\t\t\treturn x * 0.0001;\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t}\r\n\t\treturn moneyness.toArray();\r\n\t}", "public static base_response add(nitro_service client, cachepolicylabel resource) throws Exception {\n\t\tcachepolicylabel addresource = new cachepolicylabel();\n\t\taddresource.labelname = resource.labelname;\n\t\taddresource.evaluates = resource.evaluates;\n\t\treturn addresource.add_resource(client);\n\t}", "public DesignDocument get(String id) {\r\n assertNotEmpty(id, \"id\");\r\n return db.find(DesignDocument.class, ensureDesignPrefix(id));\r\n }", "@SuppressWarnings(\"unchecked\")\r\n\tpublic List<Difference> compare() {\r\n\t\tDiff diff = new Diff(this.controlDOM, this.testDOM);\r\n\t\tDetailedDiff detDiff = new DetailedDiff(diff);\r\n\t\treturn detDiff.getAllDifferences();\r\n\t}", "public char pollChar() {\n if(hasNextChar()) {\n if(hasNextWord() &&\n character+1 >= parsedLine.words().get(word).lineIndex()+\n parsedLine.words().get(word).word().length())\n word++;\n return parsedLine.line().charAt(character++);\n }\n return '\\u0000';\n }" ]
Create a new Time, with no date component.
[ "public static java.sql.Time newTime() {\n return new java.sql.Time(System.currentTimeMillis() % DAY_MILLIS);\n }" ]
[ "private List<I_CmsSearchConfigurationSortOption> getSortOptions() {\n\n final List<I_CmsSearchConfigurationSortOption> options = new ArrayList<I_CmsSearchConfigurationSortOption>();\n final CmsXmlContentValueSequence sortOptions = m_xml.getValueSequence(XML_ELEMENT_SORTOPTIONS, m_locale);\n if (sortOptions == null) {\n return null;\n } else {\n for (int i = 0; i < sortOptions.getElementCount(); i++) {\n final I_CmsSearchConfigurationSortOption option = parseSortOption(\n sortOptions.getValue(i).getPath() + \"/\");\n if (option != null) {\n options.add(option);\n }\n }\n return options;\n }\n }", "private int[] getCompressIndexAndCount(CompressOptions options, boolean createMixed) {\n\t\tif(options != null) {\n\t\t\tCompressionChoiceOptions rangeSelection = options.rangeSelection;\n\t\t\tRangeList compressibleSegs = rangeSelection.compressHost() ? getZeroRangeSegments() : getZeroSegments();\n\t\t\tint maxIndex = -1, maxCount = 0;\n\t\t\tint segmentCount = getSegmentCount();\n\t\t\t\n\t\t\tboolean compressMixed = createMixed && options.compressMixedOptions.compressMixed(this);\n\t\t\tboolean preferHost = (rangeSelection == CompressOptions.CompressionChoiceOptions.HOST_PREFERRED);\n\t\t\tboolean preferMixed = createMixed && (rangeSelection == CompressOptions.CompressionChoiceOptions.MIXED_PREFERRED);\n\t\t\tfor(int i = compressibleSegs.size() - 1; i >= 0 ; i--) {\n\t\t\t\tRange range = compressibleSegs.getRange(i);\n\t\t\t\tint index = range.index;\n\t\t\t\tint count = range.length;\n\t\t\t\tif(createMixed) {\n\t\t\t\t\t//so here we shorten the range to exclude the mixed part if necessary\n\t\t\t\t\tint mixedIndex = IPv6Address.MIXED_ORIGINAL_SEGMENT_COUNT - addressSegmentIndex;\n\t\t\t\t\tif(!compressMixed ||\n\t\t\t\t\t\t\tindex > mixedIndex || index + count < segmentCount) { //range does not include entire mixed part. We never compress only part of a mixed part.\n\t\t\t\t\t\t//the compressible range must stop at the mixed part\n\t\t\t\t\t\tcount = Math.min(count, mixedIndex - index);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//select this range if is the longest\n\t\t\t\tif(count > 0 && count >= maxCount && (options.compressSingle || count > 1)) {\n\t\t\t\t\tmaxIndex = index;\n\t\t\t\t\tmaxCount = count;\n\t\t\t\t}\n\t\t\t\tif(preferHost && isPrefixed() &&\n\t\t\t\t\t\t((index + count) * IPv6Address.BITS_PER_SEGMENT) > getNetworkPrefixLength()) { //this range contains the host\n\t\t\t\t\t//Since we are going backwards, this means we select as the maximum any zero segment that includes the host\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif(preferMixed && index + count >= segmentCount) { //this range contains the mixed section\n\t\t\t\t\t//Since we are going backwards, this means we select to compress the mixed segment\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(maxIndex >= 0) {\n\t\t\t\treturn new int[] {maxIndex, maxCount};\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}", "public Feature toDto(InternalFeature feature, int featureIncludes) throws GeomajasException {\n\t\tif (feature == null) {\n\t\t\treturn null;\n\t\t}\n\t\tFeature dto = new Feature(feature.getId());\n\t\tif ((featureIncludes & VectorLayerService.FEATURE_INCLUDE_ATTRIBUTES) != 0 && null != feature.getAttributes()) {\n\t\t\t// need to assure lazy attributes are converted to non-lazy attributes\n\t\t\tMap<String, Attribute> attributes = new HashMap<String, Attribute>();\n\t\t\tfor (Map.Entry<String, Attribute> entry : feature.getAttributes().entrySet()) {\n\t\t\t\tAttribute value = entry.getValue();\n\t\t\t\tif (value instanceof LazyAttribute) {\n\t\t\t\t\tvalue = ((LazyAttribute) value).instantiate();\n\t\t\t\t}\n\t\t\t\tattributes.put(entry.getKey(), value);\n\t\t\t}\n\t\t\tdto.setAttributes(attributes);\n\t\t}\n\t\tif ((featureIncludes & VectorLayerService.FEATURE_INCLUDE_LABEL) != 0) {\n\t\t\tdto.setLabel(feature.getLabel());\n\t\t}\n\t\tif ((featureIncludes & VectorLayerService.FEATURE_INCLUDE_GEOMETRY) != 0) {\n\t\t\tdto.setGeometry(toDto(feature.getGeometry()));\n\t\t}\n\t\tif ((featureIncludes & VectorLayerService.FEATURE_INCLUDE_STYLE) != 0 && null != feature.getStyleInfo()) {\n\t\t\tdto.setStyleId(feature.getStyleInfo().getStyleId());\n\t\t}\n\t\tInternalFeatureImpl vFeature = (InternalFeatureImpl) feature;\n\t\tdto.setClipped(vFeature.isClipped());\n\t\tdto.setUpdatable(feature.isEditable());\n\t\tdto.setDeletable(feature.isDeletable());\n\t\treturn dto;\n\t}", "public synchronized List<String> propertyListOf(Class<?> c) {\n String cn = c.getName();\n List<String> ls = repo.get(cn);\n if (ls != null) {\n return ls;\n }\n Set<Class<?>> circularReferenceDetector = new HashSet<>();\n ls = propertyListOf(c, circularReferenceDetector, null);\n repo.put(c.getName(), ls);\n return ls;\n }", "public final URI render(\n final MapfishMapContext mapContext,\n final ScalebarAttributeValues scalebarParams,\n final File tempFolder,\n final Template template)\n throws IOException, ParserConfigurationException {\n final double dpi = mapContext.getDPI();\n\n // get the map bounds\n final Rectangle paintArea = new Rectangle(mapContext.getMapSize());\n MapBounds bounds = mapContext.getBounds();\n\n final DistanceUnit mapUnit = getUnit(bounds);\n final Scale scale = bounds.getScale(paintArea, PDF_DPI);\n final double scaleDenominator = scale.getDenominator(scalebarParams.geodetic,\n bounds.getProjection(), dpi, bounds.getCenter());\n\n DistanceUnit scaleUnit = scalebarParams.getUnit();\n if (scaleUnit == null) {\n scaleUnit = mapUnit;\n }\n\n // adjust scalebar width and height to the DPI value\n final double maxLengthInPixel = (scalebarParams.getOrientation().isHorizontal()) ?\n scalebarParams.getSize().width : scalebarParams.getSize().height;\n\n final double maxIntervalLengthInWorldUnits = DistanceUnit.PX.convertTo(maxLengthInPixel, scaleUnit)\n * scaleDenominator / scalebarParams.intervals;\n final double niceIntervalLengthInWorldUnits =\n getNearestNiceValue(maxIntervalLengthInWorldUnits, scaleUnit, scalebarParams.lockUnits);\n\n final ScaleBarRenderSettings settings = new ScaleBarRenderSettings();\n settings.setParams(scalebarParams);\n settings.setMaxSize(scalebarParams.getSize());\n settings.setPadding(getPadding(settings));\n\n // start the rendering\n File path = null;\n if (template.getConfiguration().renderAsSvg(scalebarParams.renderAsSvg)) {\n // render scalebar as SVG\n final SVGGraphics2D graphics2D = CreateMapProcessor.createSvgGraphics(scalebarParams.getSize());\n\n try {\n tryLayout(\n graphics2D, scaleUnit, scaleDenominator,\n niceIntervalLengthInWorldUnits, settings, 0);\n\n path = File.createTempFile(\"scalebar-graphic-\", \".svg\", tempFolder);\n CreateMapProcessor.saveSvgFile(graphics2D, path);\n } finally {\n graphics2D.dispose();\n }\n } else {\n // render scalebar as raster graphic\n double dpiRatio = mapContext.getDPI() / PDF_DPI;\n final BufferedImage bufferedImage = new BufferedImage(\n (int) Math.round(scalebarParams.getSize().width * dpiRatio),\n (int) Math.round(scalebarParams.getSize().height * dpiRatio),\n TYPE_4BYTE_ABGR);\n final Graphics2D graphics2D = bufferedImage.createGraphics();\n\n try {\n AffineTransform saveAF = new AffineTransform(graphics2D.getTransform());\n graphics2D.scale(dpiRatio, dpiRatio);\n tryLayout(\n graphics2D, scaleUnit, scaleDenominator,\n niceIntervalLengthInWorldUnits, settings, 0);\n graphics2D.setTransform(saveAF);\n\n path = File.createTempFile(\"scalebar-graphic-\", \".png\", tempFolder);\n ImageUtils.writeImage(bufferedImage, \"png\", path);\n } finally {\n graphics2D.dispose();\n }\n }\n\n return path.toURI();\n }", "@Override\n\tpublic Inet6Address toInetAddress() {\n\t\tif(hasZone()) {\n\t\t\tInet6Address result;\n\t\t\tif(hasNoValueCache() || (result = valueCache.inetAddress) == null) {\n\t\t\t\tvalueCache.inetAddress = result = (Inet6Address) toInetAddressImpl(getBytes());\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\t\treturn (Inet6Address) super.toInetAddress();\n\t}", "public BoxFile.Info upload(BoxAPIConnection boxApi, String folderId, InputStream stream, URL url,\n String fileName, long fileSize) throws InterruptedException, IOException {\n //Create a upload session\n BoxFileUploadSession.Info session = this.createUploadSession(boxApi, folderId, url, fileName, fileSize);\n return this.uploadHelper(session, stream, fileSize);\n }", "public void forAllClassDefinitions(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _model.getClasses(); it.hasNext(); )\r\n {\r\n _curClassDef = (ClassDescriptorDef)it.next();\r\n generate(template);\r\n }\r\n _curClassDef = null;\r\n\r\n LogHelper.debug(true, OjbTagsHandler.class, \"forAllClassDefinitions\", \"Processed \"+_model.getNumClasses()+\" types\");\r\n }", "void merge(Archetype flatParent, Archetype specialized) {\n expandAttributeNodes(specialized.getDefinition());\n\n flattenCObject(RmPath.ROOT, null, flatParent.getDefinition(), specialized.getDefinition());\n\n\n mergeOntologies(flatParent.getTerminology(), specialized.getTerminology());\n if (flatParent.getAnnotations() != null) {\n if (specialized.getAnnotations() == null) {\n specialized.setAnnotations(new ResourceAnnotations());\n }\n annotationsMerger.merge(flatParent.getAnnotations().getItems(), specialized.getAnnotations().getItems());\n }\n }" ]
Keep track of this handle tied to which thread so that if the thread is terminated we can reclaim our connection handle. We also @param c connection handle to track.
[ "protected void threadWatch(final ConnectionHandle c) {\r\n\t\tthis.threadFinalizableRefs.put(c, new FinalizableWeakReference<Thread>(Thread.currentThread(), this.finalizableRefQueue) {\r\n\t\t\tpublic void finalizeReferent() {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tif (!CachedConnectionStrategy.this.pool.poolShuttingDown){\r\n\t\t\t\t\t\t\tlogger.debug(\"Monitored thread is dead, closing off allocated connection.\");\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tc.internalClose();\r\n\t\t\t\t\t} catch (SQLException e) {\r\n\t\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t\t}\r\n\t\t\t\t\tCachedConnectionStrategy.this.threadFinalizableRefs.remove(c);\r\n\t\t\t}\r\n\t\t});\r\n\t}" ]
[ "public void moveRectangleTo(Rectangle rect, float x, float y) {\n\t\tfloat width = rect.getWidth();\n\t\tfloat height = rect.getHeight();\n\t\trect.setLeft(x);\n\t\trect.setBottom(y);\n\t\trect.setRight(rect.getLeft() + width);\n\t\trect.setTop(rect.getBottom() + height);\n\t}", "public static tunnelip_stats[] get(nitro_service service) throws Exception{\n\t\ttunnelip_stats obj = new tunnelip_stats();\n\t\ttunnelip_stats[] response = (tunnelip_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}", "public MathTransform calculateLabelTransform(final CoordinateReferenceSystem mapCrs) {\n MathTransform labelTransform;\n if (this.labelProjection != null) {\n try {\n labelTransform = CRS.findMathTransform(mapCrs, this.labelCRS, true);\n } catch (FactoryException e) {\n throw new RuntimeException(e);\n }\n } else {\n labelTransform = IdentityTransform.create(2);\n }\n\n return labelTransform;\n }", "public boolean toggleProfile(Boolean enabled) {\n // TODO: make this return values properly\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"active\", enabled.toString())\n };\n try {\n String uri = BASE_PROFILE + uriEncode(this._profileName) + \"/\" + BASE_CLIENTS + \"/\";\n if (_clientId == null) {\n uri += \"-1\";\n } else {\n uri += _clientId;\n }\n JSONObject response = new JSONObject(doPost(uri, params));\n } catch (Exception e) {\n // some sort of error\n System.out.println(e.getMessage());\n return false;\n }\n return true;\n }", "protected List<String> getPluginsPath() throws IOException {\n List<String> result = new ArrayList<>();\n Path pluginsDirectory = PROPERTIES.getAllureHome().resolve(\"plugins\").toAbsolutePath();\n if (Files.notExists(pluginsDirectory)) {\n return Collections.emptyList();\n }\n\n try (DirectoryStream<Path> plugins = Files.newDirectoryStream(pluginsDirectory, JAR_FILES)) {\n for (Path plugin : plugins) {\n result.add(plugin.toUri().toURL().toString());\n }\n }\n return result;\n }", "public int delete(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException {\n\t\tif (mappedDelete == null) {\n\t\t\tmappedDelete = MappedDelete.build(dao, tableInfo);\n\t\t}\n\t\tint result = mappedDelete.delete(databaseConnection, data, objectCache);\n\t\tif (dao != null && !localIsInBatchMode.get()) {\n\t\t\tdao.notifyChanges();\n\t\t}\n\t\treturn result;\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}", "static JndiContext createJndiContext() throws NamingException\n {\n try\n {\n if (!NamingManager.hasInitialContextFactoryBuilder())\n {\n JndiContext ctx = new JndiContext();\n NamingManager.setInitialContextFactoryBuilder(ctx);\n return ctx;\n }\n else\n {\n return (JndiContext) NamingManager.getInitialContext(null);\n }\n }\n catch (Exception e)\n {\n jqmlogger.error(\"Could not create JNDI context: \" + e.getMessage());\n NamingException ex = new NamingException(\"Could not initialize JNDI Context\");\n ex.setRootCause(e);\n throw ex;\n }\n }", "public static Map<String, List<String>> getResponseHeaders(String stringUrl) throws IOException {\n return getResponseHeaders(stringUrl, true);\n }" ]
Updates the story and returns the full record for the updated story. Only comment stories can have their text updated, and only comment stories and attachment stories can be pinned. Only one of `text` and `html_text` can be specified. @param story Globally unique identifier for the story. @return Request object
[ "public ItemRequest<Story> update(String story) {\n \n String path = String.format(\"/stories/%s\", story);\n return new ItemRequest<Story>(this, Story.class, path, \"PUT\");\n }" ]
[ "private boolean initRequestHandler(SelectionKey selectionKey) {\n ByteBuffer inputBuffer = inputStream.getBuffer();\n int remaining = inputBuffer.remaining();\n\n // Don't have enough bytes to determine the protocol yet...\n if(remaining < 3)\n return true;\n\n byte[] protoBytes = { inputBuffer.get(0), inputBuffer.get(1), inputBuffer.get(2) };\n\n try {\n String proto = ByteUtils.getString(protoBytes, \"UTF-8\");\n inputBuffer.clear();\n RequestFormatType requestFormatType = RequestFormatType.fromCode(proto);\n requestHandler = requestHandlerFactory.getRequestHandler(requestFormatType);\n\n if(logger.isInfoEnabled())\n logger.info(\"Protocol negotiated for \" + socketChannel.socket() + \": \"\n + requestFormatType.getDisplayName());\n\n // The protocol negotiation is the first request, so respond by\n // sticking the bytes in the output buffer, signaling the Selector,\n // and returning false to denote no further processing is needed.\n outputStream.getBuffer().put(ByteUtils.getBytes(\"ok\", \"UTF-8\"));\n prepForWrite(selectionKey);\n\n return false;\n } catch(IllegalArgumentException e) {\n // okay we got some nonsense. For backwards compatibility,\n // assume this is an old client who does not know how to negotiate\n RequestFormatType requestFormatType = RequestFormatType.VOLDEMORT_V0;\n requestHandler = requestHandlerFactory.getRequestHandler(requestFormatType);\n\n if(logger.isInfoEnabled())\n logger.info(\"No protocol proposal given for \" + socketChannel.socket()\n + \", assuming \" + requestFormatType.getDisplayName());\n\n return true;\n }\n }", "public boolean shouldBeInReport(final DbDependency dependency) {\n if(dependency == null){\n return false;\n }\n if(dependency.getTarget() == null){\n return false;\n }\n if(corporateFilter != null){\n if(!decorator.getShowThirdparty() && !corporateFilter.filter(dependency)){\n return false;\n }\n if(!decorator.getShowCorporate() && corporateFilter.filter(dependency)){\n return false;\n }\n }\n\n if(!scopeHandler.filter(dependency)){\n return false;\n }\n\n return true;\n }", "@Override\n public <X> X getScreenshotAs(OutputType<X> target) {\n // Get the screenshot as base64 and convert it to the requested type (i.e. OutputType<T>)\n String base64 = (String) execute(DriverCommand.SCREENSHOT).getValue();\n return target.convertFromBase64Png(base64);\n }", "public void setKey(int keyIndex, float time, final float[] values)\n {\n int index = keyIndex * mFloatsPerKey;\n Integer valSize = mFloatsPerKey-1;\n\n if (values.length != valSize)\n {\n throw new IllegalArgumentException(\"This key needs \" + valSize.toString() + \" float per value\");\n }\n mKeys[index] = time;\n System.arraycopy(values, 0, mKeys, index + 1, values.length);\n }", "private void updateBundleDescriptorContent() throws CmsXmlException {\n\n if (m_descContent.hasLocale(Descriptor.LOCALE)) {\n m_descContent.removeLocale(Descriptor.LOCALE);\n }\n m_descContent.addLocale(m_cms, Descriptor.LOCALE);\n\n int i = 0;\n Property<Object> descProp;\n String desc;\n Property<Object> defaultValueProp;\n String defaultValue;\n Map<String, Item> keyItemMap = getKeyItemMap();\n List<String> keys = new ArrayList<String>(keyItemMap.keySet());\n Collections.sort(keys, CmsCaseInsensitiveStringComparator.getInstance());\n for (Object key : keys) {\n if ((null != key) && !key.toString().isEmpty()) {\n\n m_descContent.addValue(m_cms, Descriptor.N_MESSAGE, Descriptor.LOCALE, i);\n i++;\n String messagePrefix = Descriptor.N_MESSAGE + \"[\" + i + \"]/\";\n\n m_descContent.getValue(messagePrefix + Descriptor.N_KEY, Descriptor.LOCALE).setStringValue(\n m_cms,\n (String)key);\n descProp = keyItemMap.get(key).getItemProperty(TableProperty.DESCRIPTION);\n if ((null != descProp) && (null != descProp.getValue())) {\n desc = descProp.getValue().toString();\n m_descContent.getValue(messagePrefix + Descriptor.N_DESCRIPTION, Descriptor.LOCALE).setStringValue(\n m_cms,\n desc);\n }\n\n defaultValueProp = keyItemMap.get(key).getItemProperty(TableProperty.DEFAULT);\n if ((null != defaultValueProp) && (null != defaultValueProp.getValue())) {\n defaultValue = defaultValueProp.getValue().toString();\n m_descContent.getValue(messagePrefix + Descriptor.N_DEFAULT, Descriptor.LOCALE).setStringValue(\n m_cms,\n defaultValue);\n }\n\n }\n }\n\n }", "private void addToGraph(ClassDoc cd) {\n\t// avoid adding twice the same class, but don't rely on cg.getClassInfo\n\t// since there are other ways to add a classInfor than printing the class\n\tif (visited.contains(cd.toString()))\n\t return;\n\n\tvisited.add(cd.toString());\n\tcg.printClass(cd, false);\n\tcg.printRelations(cd);\n\tif (opt.inferRelationships)\n\t cg.printInferredRelations(cd);\n\tif (opt.inferDependencies)\n\t cg.printInferredDependencies(cd);\n }", "public final static int readMdLink(final StringBuilder out, final String in, final int start)\n {\n int pos = start;\n int counter = 1;\n while (pos < in.length())\n {\n final char ch = in.charAt(pos);\n if (ch == '\\\\' && pos + 1 < in.length())\n {\n pos = escape(out, in.charAt(pos + 1), pos);\n }\n else\n {\n boolean endReached = false;\n switch (ch)\n {\n case '(':\n counter++;\n break;\n case ' ':\n if (counter == 1)\n {\n endReached = true;\n }\n break;\n case ')':\n counter--;\n if (counter == 0)\n {\n endReached = true;\n }\n break;\n }\n if (endReached)\n {\n break;\n }\n out.append(ch);\n }\n pos++;\n }\n\n return (pos == in.length()) ? -1 : pos;\n }", "public PartialCollection<BoxItem.Info> searchRange(long offset, long limit, final BoxSearchParameters bsp) {\n QueryStringBuilder builder = bsp.getQueryParameters()\n .appendParam(\"limit\", limit)\n .appendParam(\"offset\", offset);\n URL url = SEARCH_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n String totalCountString = responseJSON.get(\"total_count\").toString();\n long fullSize = Double.valueOf(totalCountString).longValue();\n PartialCollection<BoxItem.Info> results = 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 results.add(parsedItemInfo);\n }\n }\n return results;\n }", "public static int[] Unique(int[] values) {\r\n HashSet<Integer> lst = new HashSet<Integer>();\r\n for (int i = 0; i < values.length; i++) {\r\n lst.add(values[i]);\r\n }\r\n\r\n int[] v = new int[lst.size()];\r\n Iterator<Integer> it = lst.iterator();\r\n for (int i = 0; i < v.length; i++) {\r\n v[i] = it.next();\r\n }\r\n\r\n return v;\r\n }" ]
Perform a post-boot scan to remove any deployments added during boot that failed to deploy properly. This method isn't private solely to allow a unit test in the same package to call it.
[ "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 List<Artifact> getAllArtifacts(final Module module){\n final List<Artifact> artifacts = new ArrayList<Artifact>();\n\n for(final Module subModule: module.getSubmodules()){\n artifacts.addAll(getAllArtifacts(subModule));\n }\n\n artifacts.addAll(module.getArtifacts());\n\n return artifacts;\n }", "public Character getCharacter(int field)\n {\n Character result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n result = Character.valueOf(m_fields[field].charAt(0));\n }\n else\n {\n result = null;\n }\n\n return (result);\n }", "private void setHint() {\n if (mPhoneEdit != null && mSelectedCountry != null && mSelectedCountry.getIso() != null) {\n Phonenumber.PhoneNumber phoneNumber = mPhoneUtil.getExampleNumberForType(mSelectedCountry.getIso(), PhoneNumberUtil.PhoneNumberType.MOBILE);\n if (phoneNumber != null) {\n mPhoneEdit.setHint(mPhoneUtil.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.NATIONAL));\n }\n }\n }", "public static void symmetric(DMatrixRMaj A, double min, double max, Random rand) {\n if( A.numRows != A.numCols )\n throw new IllegalArgumentException(\"A must be a square matrix\");\n\n double range = max-min;\n\n int length = A.numRows;\n\n for( int i = 0; i < length; i++ ) {\n for( int j = i; j < length; j++ ) {\n double val = rand.nextDouble()*range + min;\n A.set(i,j,val);\n A.set(j,i,val);\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 }", "private String getHostHeaderForHost(String hostName) {\n List<ServerRedirect> servers = serverRedirectService.tableServers(requestInformation.get().client.getId());\n for (ServerRedirect server : servers) {\n if (server.getSrcUrl().compareTo(hostName) == 0) {\n String hostHeader = server.getHostHeader();\n if (hostHeader == null || hostHeader.length() == 0) {\n return null;\n }\n return hostHeader;\n }\n }\n return null;\n }", "private static void createList( int data[], int k , int level , List<int[]> ret )\n {\n data[k] = level;\n\n if( level < data.length-1 ) {\n for( int i = 0; i < data.length; i++ ) {\n if( data[i] == -1 ) {\n createList(data,i,level+1,ret);\n }\n }\n } else {\n int []copy = new int[data.length];\n System.arraycopy(data,0,copy,0,data.length);\n ret.add(copy);\n }\n data[k] = -1;\n }", "static PlexusConfiguration convert(ModelNode configuration, ModelNode jsonSchema, String extensionId, String id) {\n ConversionContext ctx = new ConversionContext();\n ctx.currentSchema = jsonSchema;\n ctx.rootSchema = jsonSchema;\n ctx.pushTag(extensionId);\n ctx.id = id;\n return convert(configuration, ctx);\n }", "public void onSplashScreenCreated(GVRSceneObject splashScreen) {\n GVRTransform transform = splashScreen.getTransform();\n transform.setPosition(0, 0, DEFAULT_SPLASH_Z);\n }" ]
This method removes trailing delimiter characters. @param buffer input sring buffer
[ "private void stripTrailingDelimiters(StringBuilder buffer)\n {\n int index = buffer.length() - 1;\n\n while (index > 0 && buffer.charAt(index) == m_delimiter)\n {\n --index;\n }\n\n buffer.setLength(index + 1);\n }" ]
[ "public 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 }", "public Set<D> getMatchedDeclaration() {\n Set<D> bindedSet = new HashSet<D>();\n for (Map.Entry<ServiceReference<D>, Boolean> e : declarations.entrySet()) {\n if (e.getValue()) {\n bindedSet.add(getDeclaration(e.getKey()));\n }\n }\n return bindedSet;\n }", "public GenericCriteria process(ProjectProperties properties, byte[] data, int dataOffset, int entryOffset, List<GenericCriteriaPrompt> prompts, List<FieldType> fields, boolean[] criteriaType)\n {\n m_properties = properties;\n m_prompts = prompts;\n m_fields = fields;\n m_criteriaType = criteriaType;\n m_dataOffset = dataOffset;\n if (m_criteriaType != null)\n {\n m_criteriaType[0] = true;\n m_criteriaType[1] = true;\n }\n\n m_criteriaBlockMap.clear();\n\n m_criteriaData = data;\n m_criteriaTextStart = MPPUtility.getShort(m_criteriaData, m_dataOffset + getCriteriaTextStartOffset());\n\n //\n // Populate the map\n //\n int criteriaStartOffset = getCriteriaStartOffset();\n int criteriaBlockSize = getCriteriaBlockSize();\n\n //System.out.println();\n //System.out.println(ByteArrayHelper.hexdump(data, dataOffset, criteriaStartOffset, false));\n\n if (m_criteriaData.length <= m_criteriaTextStart)\n {\n return null; // bad data\n }\n\n while (criteriaStartOffset + criteriaBlockSize <= m_criteriaTextStart)\n {\n byte[] block = new byte[criteriaBlockSize];\n System.arraycopy(m_criteriaData, m_dataOffset + criteriaStartOffset, block, 0, criteriaBlockSize);\n m_criteriaBlockMap.put(Integer.valueOf(criteriaStartOffset), block);\n //System.out.println(Integer.toHexString(criteriaStartOffset) + \": \" + ByteArrayHelper.hexdump(block, false));\n criteriaStartOffset += criteriaBlockSize;\n }\n\n if (entryOffset == -1)\n {\n entryOffset = getCriteriaStartOffset();\n }\n\n List<GenericCriteria> list = new LinkedList<GenericCriteria>();\n processBlock(list, m_criteriaBlockMap.get(Integer.valueOf(entryOffset)));\n GenericCriteria criteria;\n if (list.isEmpty())\n {\n criteria = null;\n }\n else\n {\n criteria = list.get(0);\n }\n return criteria;\n }", "public static <E> String serialize(Map<String, E> map, Class<E> jsonObjectClass) throws IOException {\n return mapperFor(jsonObjectClass).serialize(map);\n }", "MongoCollection<BsonDocument> getUndoCollection(final MongoNamespace namespace) {\n return localClient\n .getDatabase(String.format(\"sync_undo_%s\", namespace.getDatabaseName()))\n .getCollection(namespace.getCollectionName(), BsonDocument.class)\n .withCodecRegistry(MongoClientSettings.getDefaultCodecRegistry());\n }", "public static int getLineCount(String str) {\r\n if (null == str || str.isEmpty()) {\r\n return 0;\r\n }\r\n int count = 1;\r\n for (char c : str.toCharArray()) {\r\n if ('\\n' == c) {\r\n count++;\r\n }\r\n }\r\n return count;\r\n }", "@Pure\n\tpublic static <P1, P2, P3, P4, RESULT> Function3<P2, P3, P4, RESULT> curry(\n\t\t\tfinal Function4<? super P1, ? super P2, ? super P3, ? super P4, ? extends RESULT> function, final P1 argument) {\n\t\tif (function == null)\n\t\t\tthrow new NullPointerException(\"function\");\n\t\treturn new Function3<P2, P3, P4, RESULT>() {\n\t\t\t@Override\n\t\t\tpublic RESULT apply(P2 p2, P3 p3, P4 p4) {\n\t\t\t\treturn function.apply(argument, p2, p3, p4);\n\t\t\t}\n\t\t};\n\t}", "private String appendXmlEndingTag(String value) {\r\n StringBuilder sb = new StringBuilder();\r\n sb.append(\"</\").append(value).append(\">\");\n\r\n return sb.toString();\r\n }", "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 }" ]
Writes the torque schemata to files in the given directory and returns a comma-separated list of the filenames. @param dir The directory to write the files to @return The list of filenames @throws IOException If an error occurred
[ "private String writeSchemata(File dir) throws IOException\r\n {\r\n writeCompressedTexts(dir, _torqueSchemata);\r\n\r\n StringBuffer includes = new StringBuffer();\r\n\r\n for (Iterator it = _torqueSchemata.keySet().iterator(); it.hasNext();)\r\n {\r\n includes.append((String)it.next());\r\n if (it.hasNext())\r\n {\r\n includes.append(\",\");\r\n }\r\n }\r\n return includes.toString();\r\n }" ]
[ "public boolean validation() throws ParallelTaskInvalidException {\n\n ParallelTask task = new ParallelTask();\n targetHostMeta = new TargetHostMeta(targetHosts);\n\n task = new ParallelTask(requestProtocol, concurrency, httpMeta,\n targetHostMeta, sshMeta, tcpMeta, udpMeta, pingMeta, null, responseContext,\n replacementVarMapNodeSpecific,\n replacementVarMap, requestReplacementType, config);\n boolean valid = false;\n\n try {\n valid = task.validateWithFillDefault();\n } catch (ParallelTaskInvalidException e) {\n logger.info(\"task is invalid \" + e);\n }\n\n return valid;\n\n }", "public static base_responses add(nitro_service client, dnstxtrec resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdnstxtrec addresources[] = new dnstxtrec[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dnstxtrec();\n\t\t\t\taddresources[i].domain = resources[i].domain;\n\t\t\t\taddresources[i].String = resources[i].String;\n\t\t\t\taddresources[i].ttl = resources[i].ttl;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public Collection<HazeltaskTask<GROUP>> call() throws Exception {\n try {\n if(isShutdownNow)\n return this.getDistributedExecutorService().shutdownNowWithHazeltask();\n else\n this.getDistributedExecutorService().shutdown();\n } catch(IllegalStateException e) {}\n \n return Collections.emptyList();\n }", "private void renderBlurLayer(float slideOffset) {\n if (enableBlur) {\n if (slideOffset == 0 || forceRedraw) {\n clearBlurView();\n }\n\n if (slideOffset > 0f && blurView == null) {\n if (drawerLayout.getChildCount() == 2) {\n blurView = new ImageView(drawerLayout.getContext());\n blurView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));\n blurView.setScaleType(ImageView.ScaleType.FIT_CENTER);\n drawerLayout.addView(blurView, 1);\n }\n\n if (BuilderUtil.isOnUiThread()) {\n if (cacheMode.equals(CacheMode.AUTO) || forceRedraw) {\n dali.load(drawerLayout.getChildAt(0)).blurRadius(blurRadius).downScale(downSample).noFade().error(Dali.NO_RESID).concurrent().skipCache().into(blurView);\n forceRedraw = false;\n } else {\n dali.load(drawerLayout.getChildAt(0)).blurRadius(blurRadius).downScale(downSample).noFade().error(Dali.NO_RESID).concurrent().into(blurView);\n }\n }\n }\n\n if (slideOffset > 0f && slideOffset < 1f) {\n int alpha = (int) Math.ceil((double) slideOffset * 255d);\n LegacySDKUtil.setImageAlpha(blurView, alpha);\n }\n }\n }", "public void setIntVec(int[] data)\n {\n if (data == null)\n {\n throw new IllegalArgumentException(\"Input data for indices cannot be null\");\n }\n if (getIndexSize() != 4)\n {\n throw new UnsupportedOperationException(\"Cannot update short indices with int array\");\n }\n if (!NativeIndexBuffer.setIntArray(getNative(), data))\n {\n throw new UnsupportedOperationException(\"Input array is wrong size\");\n }\n }", "public static String getArtifactoryPluginVersion() {\n String pluginsSortName = \"artifactory\";\n //Validates Jenkins existence because in some jobs the Jenkins instance is unreachable\n if (Jenkins.getInstance() != null\n && Jenkins.getInstance().getPlugin(pluginsSortName) != null\n && Jenkins.getInstance().getPlugin(pluginsSortName).getWrapper() != null) {\n return Jenkins.getInstance().getPlugin(pluginsSortName).getWrapper().getVersion();\n }\n return \"\";\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 }", "static VaultConfig loadExternalFile(File f) throws XMLStreamException {\n if(f == null) {\n throw new IllegalArgumentException(\"File is null\");\n }\n if(!f.exists()) {\n throw new XMLStreamException(\"Failed to locate vault file \" + f.getAbsolutePath());\n }\n\n final VaultConfig config = new VaultConfig();\n BufferedInputStream input = null;\n try {\n final XMLMapper mapper = XMLMapper.Factory.create();\n final XMLElementReader<VaultConfig> reader = new ExternalVaultConfigReader();\n mapper.registerRootElement(new QName(VAULT), reader);\n FileInputStream is = new FileInputStream(f);\n input = new BufferedInputStream(is);\n XMLStreamReader streamReader = XMLInputFactory.newInstance().createXMLStreamReader(input);\n mapper.parseDocument(config, streamReader);\n streamReader.close();\n } catch(FileNotFoundException e) {\n throw new XMLStreamException(\"Vault file not found\", e);\n } catch(XMLStreamException t) {\n throw t;\n } finally {\n StreamUtils.safeClose(input);\n }\n return config;\n }", "private void updateBaseCalendarNames(List<Pair<ProjectCalendar, Integer>> baseCalendars, HashMap<Integer, ProjectCalendar> map)\n {\n for (Pair<ProjectCalendar, Integer> pair : baseCalendars)\n {\n ProjectCalendar cal = pair.getFirst();\n Integer baseCalendarID = pair.getSecond();\n ProjectCalendar baseCal = map.get(baseCalendarID);\n if (baseCal != null && baseCal.getName() != null)\n {\n cal.setParent(baseCal);\n }\n else\n {\n // Remove invalid calendar to avoid serious problems later.\n m_file.removeCalendar(cal);\n }\n }\n }" ]
Sets the text alignment for all cells in the row. @param textAlignment new text alignment @throws NullPointerException if the argument was null @return this to allow chaining @throws {@link NullPointerException} if the argument was null
[ "public AT_Row setTextAlignment(TextAlignment textAlignment){\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setTextAlignment(textAlignment);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}" ]
[ "public boolean isObjectsFieldValueDefault(Object object) throws SQLException {\n\t\tObject fieldValue = extractJavaFieldValue(object);\n\t\treturn isFieldValueDefault(fieldValue);\n\t}", "@SuppressWarnings(\"unchecked\")\n protected Class<? extends Annotation> annotationTypeForName(String name) {\n try {\n return (Class<? extends Annotation>) resourceLoader.classForName(name);\n } catch (ResourceLoadingException cnfe) {\n return DUMMY_ANNOTATION;\n }\n }", "public static vlan_nsip6_binding[] get(nitro_service service, Long id) throws Exception{\n\t\tvlan_nsip6_binding obj = new vlan_nsip6_binding();\n\t\tobj.set_id(id);\n\t\tvlan_nsip6_binding response[] = (vlan_nsip6_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "int getItemViewType(T content) {\n Class prototypeClass = getPrototypeClass(content);\n validatePrototypeClass(prototypeClass);\n return getItemViewType(prototypeClass);\n }", "protected LogContext getOrCreate(final String loggingProfile) {\n LogContext result = profileContexts.get(loggingProfile);\n if (result == null) {\n result = LogContext.create();\n final LogContext current = profileContexts.putIfAbsent(loggingProfile, result);\n if (current != null) {\n result = current;\n }\n }\n return result;\n }", "String getRangeUri(PropertyIdValue propertyIdValue) {\n\t\tString datatype = this.propertyRegister\n\t\t\t\t.getPropertyType(propertyIdValue);\n\n\t\tif (datatype == null)\n\t\t\treturn null;\n\n\t\tswitch (datatype) {\n\t\tcase DatatypeIdValue.DT_MONOLINGUAL_TEXT:\n\t\t\tthis.rdfConversionBuffer.addDatatypeProperty(propertyIdValue);\n\t\t\treturn Vocabulary.RDF_LANG_STRING;\n\t\tcase DatatypeIdValue.DT_STRING:\n\t\tcase DatatypeIdValue.DT_EXTERNAL_ID:\n\t\tcase DatatypeIdValue.DT_MATH:\n\t\t\tthis.rdfConversionBuffer.addDatatypeProperty(propertyIdValue);\n\t\t\treturn Vocabulary.XSD_STRING;\n\t\tcase DatatypeIdValue.DT_COMMONS_MEDIA:\n\t\tcase DatatypeIdValue.DT_GLOBE_COORDINATES:\n\t\tcase DatatypeIdValue.DT_ITEM:\n\t\tcase DatatypeIdValue.DT_PROPERTY:\n\t\tcase DatatypeIdValue.DT_LEXEME:\n\t\tcase DatatypeIdValue.DT_FORM:\n\t\tcase DatatypeIdValue.DT_SENSE:\n\t\tcase DatatypeIdValue.DT_TIME:\n\t\tcase DatatypeIdValue.DT_URL:\n\t\tcase DatatypeIdValue.DT_GEO_SHAPE:\n\t\tcase DatatypeIdValue.DT_TABULAR_DATA:\n\t\tcase DatatypeIdValue.DT_QUANTITY:\n\t\t\tthis.rdfConversionBuffer.addObjectProperty(propertyIdValue);\n\t\t\treturn Vocabulary.OWL_THING;\n\t\tdefault:\n\t\t\treturn null;\n\t\t}\n\t}", "public static int getStatusBarHeight(Context context, boolean force) {\n int result = 0;\n int resourceId = context.getResources().getIdentifier(\"status_bar_height\", \"dimen\", \"android\");\n if (resourceId > 0) {\n result = context.getResources().getDimensionPixelSize(resourceId);\n }\n\n int dimenResult = context.getResources().getDimensionPixelSize(R.dimen.tool_bar_top_padding);\n //if our dimension is 0 return 0 because on those devices we don't need the height\n if (dimenResult == 0 && !force) {\n return 0;\n } else {\n //if our dimens is > 0 && the result == 0 use the dimenResult else the result;\n return result == 0 ? dimenResult : result;\n }\n }", "private boolean isInInnerCircle(float x, float y) {\n return GearWearableUtility.isInCircle(x, y, CENTER_X, CENTER_Y, INNER_RADIUS);\n }", "public Collection<Group> search(String text, int perPage, int page) throws FlickrException {\r\n GroupList<Group> groupList = new GroupList<Group>();\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SEARCH);\r\n\r\n parameters.put(\"text\", text);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", String.valueOf(perPage));\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", String.valueOf(page));\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element groupsElement = response.getPayload();\r\n NodeList groupNodes = groupsElement.getElementsByTagName(\"group\");\r\n groupList.setPage(XMLUtilities.getIntAttribute(groupsElement, \"page\"));\r\n groupList.setPages(XMLUtilities.getIntAttribute(groupsElement, \"pages\"));\r\n groupList.setPerPage(XMLUtilities.getIntAttribute(groupsElement, \"perpage\"));\r\n groupList.setTotal(XMLUtilities.getIntAttribute(groupsElement, \"total\"));\r\n for (int i = 0; i < groupNodes.getLength(); i++) {\r\n Element groupElement = (Element) groupNodes.item(i);\r\n Group group = new Group();\r\n group.setId(groupElement.getAttribute(\"nsid\"));\r\n group.setName(groupElement.getAttribute(\"name\"));\r\n groupList.add(group);\r\n }\r\n return groupList;\r\n }" ]
Overridden 'consume' method. Corresponding parent method will be called necessary number of times @param initialVars - a map containing the initial variables assignments @return the number of lines written
[ "public int consume(Map<String, String> initialVars) {\r\n int result = 0;\n\r\n for (int i = 0; i < repeatNumber; i++) {\r\n result += super.consume(initialVars);\r\n }\n\r\n return result;\r\n }" ]
[ "private void addResources(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (Resource resource : file.getResources())\n {\n final Resource r = resource;\n MpxjTreeNode childNode = new MpxjTreeNode(resource)\n {\n @Override public String toString()\n {\n return r.getName();\n }\n };\n parentNode.add(childNode);\n }\n }", "private void processOutlineCodeValues() throws IOException\n {\n DirectoryEntry outlineCodeDir = (DirectoryEntry) m_projectDir.getEntry(\"TBkndOutlCode\");\n FixedMeta fm = new FixedMeta(new DocumentInputStream(((DocumentEntry) outlineCodeDir.getEntry(\"FixedMeta\"))), 10);\n FixedData fd = new FixedData(fm, new DocumentInputStream(((DocumentEntry) outlineCodeDir.getEntry(\"FixedData\"))));\n\n Map<Integer, FieldType> map = new HashMap<Integer, FieldType>();\n\n int items = fm.getItemCount();\n for (int loop = 0; loop < items; loop++)\n {\n byte[] data = fd.getByteArrayValue(loop);\n if (data.length < 18)\n {\n continue;\n }\n\n int index = MPPUtility.getShort(data, 0);\n int fieldID = MPPUtility.getInt(data, 12);\n FieldType fieldType = FieldTypeHelper.getInstance(fieldID);\n if (fieldType.getFieldTypeClass() != FieldTypeClass.UNKNOWN)\n {\n map.put(Integer.valueOf(index), fieldType);\n }\n }\n\n VarMeta outlineCodeVarMeta = new VarMeta9(new DocumentInputStream(((DocumentEntry) outlineCodeDir.getEntry(\"VarMeta\"))));\n Var2Data outlineCodeVarData = new Var2Data(outlineCodeVarMeta, new DocumentInputStream(((DocumentEntry) outlineCodeDir.getEntry(\"Var2Data\"))));\n\n Map<FieldType, List<Pair<String, String>>> valueMap = new HashMap<FieldType, List<Pair<String, String>>>();\n\n for (Integer id : outlineCodeVarMeta.getUniqueIdentifierArray())\n {\n FieldType fieldType = map.get(id);\n String value = outlineCodeVarData.getUnicodeString(id, VALUE);\n String description = outlineCodeVarData.getUnicodeString(id, DESCRIPTION);\n\n List<Pair<String, String>> list = valueMap.get(fieldType);\n if (list == null)\n {\n list = new ArrayList<Pair<String, String>>();\n valueMap.put(fieldType, list);\n }\n list.add(new Pair<String, String>(value, description));\n }\n\n for (Entry<FieldType, List<Pair<String, String>>> entry : valueMap.entrySet())\n {\n populateContainer(entry.getKey(), entry.getValue());\n }\n }", "private void readTasks(Project plannerProject) throws MPXJException\n {\n Tasks tasks = plannerProject.getTasks();\n if (tasks != null)\n {\n for (net.sf.mpxj.planner.schema.Task task : tasks.getTask())\n {\n readTask(null, task);\n }\n\n for (net.sf.mpxj.planner.schema.Task task : tasks.getTask())\n {\n readPredecessors(task);\n }\n }\n\n m_projectFile.updateStructure();\n }", "public Vector3Axis delta(Vector3f v) {\n Vector3Axis ret = new Vector3Axis(Float.NaN, Float.NaN, Float.NaN);\n if (x != Float.NaN && v.x != Float.NaN && !equal(x, v.x)) {\n ret.set(x - v.x, Layout.Axis.X);\n }\n if (y != Float.NaN && v.y != Float.NaN && !equal(y, v.y)) {\n ret.set(y - v.y, Layout.Axis.Y);\n }\n if (z != Float.NaN && v.z != Float.NaN && !equal(z, v.z)) {\n ret.set(z - v.z, Layout.Axis.Z);\n }\n return ret;\n }", "protected void removeEmptyDirectories(File outputDirectory)\n {\n if (outputDirectory.exists())\n {\n for (File file : outputDirectory.listFiles(new EmptyDirectoryFilter()))\n {\n file.delete();\n }\n }\n }", "public String getPermalink(CmsObject cms, String resourceName, CmsUUID detailContentId) {\n\n String permalink = \"\";\n try {\n permalink = substituteLink(cms, CmsPermalinkResourceHandler.PERMALINK_HANDLER);\n String id = cms.readResource(resourceName, CmsResourceFilter.ALL).getStructureId().toString();\n permalink += id;\n if (detailContentId != null) {\n permalink += \":\" + detailContentId;\n }\n String ext = CmsFileUtil.getExtension(resourceName);\n if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(ext)) {\n permalink += ext;\n }\n CmsSite currentSite = OpenCms.getSiteManager().getCurrentSite(cms);\n String serverPrefix = null;\n if (currentSite == OpenCms.getSiteManager().getDefaultSite()) {\n Optional<CmsSite> siteForDefaultUri = OpenCms.getSiteManager().getSiteForDefaultUri();\n if (siteForDefaultUri.isPresent()) {\n serverPrefix = siteForDefaultUri.get().getServerPrefix(cms, resourceName);\n } else {\n serverPrefix = OpenCms.getSiteManager().getWorkplaceServer();\n }\n } else {\n serverPrefix = currentSite.getServerPrefix(cms, resourceName);\n }\n\n if (!permalink.startsWith(serverPrefix)) {\n permalink = serverPrefix + permalink;\n }\n } catch (CmsException e) {\n // if something wrong\n permalink = e.getLocalizedMessage();\n if (LOG.isErrorEnabled()) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n }\n return permalink;\n }", "private static String getSolrSpellcheckRfsPath() {\n\n String sPath = OpenCms.getSystemInfo().getWebInfRfsPath();\n\n if (!OpenCms.getSystemInfo().getWebInfRfsPath().endsWith(File.separator)) {\n sPath += File.separator;\n }\n\n return sPath + \"solr\" + File.separator + \"spellcheck\" + File.separator + \"data\";\n }", "@RequestMapping(value = \"/api/scripts\", method = RequestMethod.POST)\n public\n @ResponseBody\n Script addScript(Model model,\n @RequestParam(required = true) String name,\n @RequestParam(required = true) String script) throws Exception {\n\n return ScriptService.getInstance().addScript(name, script);\n }", "public static authenticationvserver_authenticationlocalpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_authenticationlocalpolicy_binding obj = new authenticationvserver_authenticationlocalpolicy_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_authenticationlocalpolicy_binding response[] = (authenticationvserver_authenticationlocalpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
Configure column aliases.
[ "private void applyAliases()\n {\n CustomFieldContainer fields = m_projectFile.getCustomFields();\n for (Map.Entry<FieldType, String> entry : ALIASES.entrySet())\n {\n fields.getCustomField(entry.getKey()).setAlias(entry.getValue());\n }\n }" ]
[ "public static base_response clear(nitro_service client, nsconfig resource) throws Exception {\n\t\tnsconfig clearresource = new nsconfig();\n\t\tclearresource.force = resource.force;\n\t\tclearresource.level = resource.level;\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}", "public static base_responses disable(nitro_service client, String id[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (id != null && id.length > 0) {\n\t\t\tInterface disableresources[] = new Interface[id.length];\n\t\t\tfor (int i=0;i<id.length;i++){\n\t\t\t\tdisableresources[i] = new Interface();\n\t\t\t\tdisableresources[i].id = id[i];\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, disableresources,\"disable\");\n\t\t}\n\t\treturn result;\n\t}", "public static final long getLong6(byte[] data, int offset)\n {\n long result = 0;\n int i = offset;\n for (int shiftBy = 0; shiftBy < 48; shiftBy += 8)\n {\n result |= ((long) (data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\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 }", "private Renderer createRenderer(T content, ViewGroup parent) {\n int prototypeIndex = getPrototypeIndex(content);\n Renderer renderer = getPrototypeByIndex(prototypeIndex).copy();\n renderer.onCreate(content, layoutInflater, parent);\n return renderer;\n }", "public static MediaType text( String subType, Charset charset ) {\n return nonBinary( TEXT, subType, charset );\n }", "public Relationship createRelationshipForEmbeddedAssociation(GraphDatabaseService executionEngine, AssociationKey associationKey, EntityKey embeddedKey) {\n\t\tString query = initCreateEmbeddedAssociationQuery( associationKey, embeddedKey );\n\t\tObject[] queryValues = createRelationshipForEmbeddedQueryValues( associationKey, embeddedKey );\n\t\treturn executeQuery( executionEngine, query, queryValues );\n\t}", "private Object filterValue(Object value)\n {\n if (value instanceof Boolean && !((Boolean) value).booleanValue())\n {\n value = null;\n }\n if (value instanceof String && ((String) value).isEmpty())\n {\n value = null;\n }\n if (value instanceof Double && ((Double) value).doubleValue() == 0.0)\n {\n value = null;\n }\n if (value instanceof Integer && ((Integer) value).intValue() == 0)\n {\n value = null;\n }\n if (value instanceof Duration && ((Duration) value).getDuration() == 0.0)\n {\n value = null;\n }\n\n return value;\n }", "public Class getSearchClass()\r\n\t{\r\n\t\tObject obj = getExampleObject();\r\n\r\n\t\tif (obj instanceof Identity)\r\n\t\t{\r\n\t\t\treturn ((Identity) obj).getObjectsTopLevelClass();\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn obj.getClass();\r\n\t\t}\r\n\t}" ]
Add a photo to the user's favorites. @param photoId The photo ID @throws FlickrException
[ "public void add(String photoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ADD);\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }" ]
[ "public AT_Row setPaddingTopChar(Character paddingTopChar) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingTopChar(paddingTopChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "@Override\n public final PObject getObject(final String key) {\n PObject result = optObject(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }", "public void storeIfNew(final DbArtifact fromClient) {\n final DbArtifact existing = repositoryHandler.getArtifact(fromClient.getGavc());\n\n if(existing != null){\n existing.setLicenses(fromClient.getLicenses());\n store(existing);\n }\n\n if(existing == null){\n\t store(fromClient);\n }\n }", "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 static <T extends JsonRtn> T parseJsonRtn(String jsonRtn, Class<T> jsonRtnClazz) {\n T rtn = JSONObject.parseObject(jsonRtn, jsonRtnClazz);\n appendErrorHumanMsg(rtn);\n return rtn;\n }", "public String clean(String value) {\n String orig = value;\n \n // check if there's a + before the first digit\n boolean initialplus = findPlus(value);\n \n // remove everything but digits\n value = sub.clean(value);\n if (value == null)\n return null;\n\n // check for initial '00'\n boolean zerozero = !initialplus && value.startsWith(\"00\");\n if (zerozero)\n value = value.substring(2); // strip off the zeros\n\n // look for country code\n CountryCode ccode = findCountryCode(value);\n if (ccode == null) {\n // no country code, let's do what little we can\n if (initialplus || zerozero)\n return orig; // this number is messed up. dare not touch\n return value;\n\n } else {\n value = value.substring(ccode.getPrefix().length()); // strip off ccode\n if (ccode.getStripZero() && value.startsWith(\"0\"))\n value = value.substring(1); // strip the zero\n\n if (ccode.isRightFormat(value))\n return \"+\" + ccode.getPrefix() + \" \" + value;\n else\n return orig; // don't dare touch this\n }\n }", "private static Interval parseEndDateTime(Instant start, ZoneOffset offset, CharSequence endStr) {\n try {\n TemporalAccessor temporal = DateTimeFormatter.ISO_DATE_TIME.parseBest(endStr, OffsetDateTime::from, LocalDateTime::from);\n if (temporal instanceof OffsetDateTime) {\n OffsetDateTime odt = (OffsetDateTime) temporal;\n return Interval.of(start, odt.toInstant());\n } else {\n // infer offset from start if not specified by end\n LocalDateTime ldt = (LocalDateTime) temporal;\n return Interval.of(start, ldt.toInstant(offset));\n }\n } catch (DateTimeParseException ex) {\n Instant end = Instant.parse(endStr);\n return Interval.of(start, end);\n }\n }", "private void onChangedImpl(final int preferableCenterPosition) {\n for (ListOnChangedListener listener: mOnChangedListeners) {\n listener.onChangedStart(this);\n }\n\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"onChangedImpl(%s): items [%d] views [%d] mLayouts.size() = %d \" +\n \"preferableCenterPosition = %d\",\n getName(), getDataCount(), getViewCount(), mContent.mLayouts.size(), preferableCenterPosition);\n\n // TODO: selectively recycle data based on the changes in the data set\n mPreferableCenterPosition = preferableCenterPosition;\n recycleChildren();\n }", "public static FileOutputStream openResultFileOuputStream(\n\t\t\tPath resultDirectory, String filename) throws IOException {\n\t\tPath filePath = resultDirectory.resolve(filename);\n\t\treturn new FileOutputStream(filePath.toFile());\n\t}" ]
Use this API to fetch aaagroup_authorizationpolicy_binding resources of given name .
[ "public static aaagroup_authorizationpolicy_binding[] get(nitro_service service, String groupname) throws Exception{\n\t\taaagroup_authorizationpolicy_binding obj = new aaagroup_authorizationpolicy_binding();\n\t\tobj.set_groupname(groupname);\n\t\taaagroup_authorizationpolicy_binding response[] = (aaagroup_authorizationpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "public List<TerminalString> getOptionLongNamesWithDash() {\n List<ProcessedOption> opts = getOptions();\n List<TerminalString> names = new ArrayList<>(opts.size());\n for (ProcessedOption o : opts) {\n if(o.getValues().size() == 0 &&\n o.activator().isActivated(new ParsedCommand(this)))\n names.add(o.getRenderedNameWithDashes());\n }\n\n return names;\n }", "public void addRequiredValues(@Nonnull final Values sourceValues) {\n Object taskDirectory = sourceValues.getObject(TASK_DIRECTORY_KEY, Object.class);\n MfClientHttpRequestFactoryProvider requestFactoryProvider =\n sourceValues.getObject(CLIENT_HTTP_REQUEST_FACTORY_KEY,\n MfClientHttpRequestFactoryProvider.class);\n Template template = sourceValues.getObject(TEMPLATE_KEY, Template.class);\n PDFConfig pdfConfig = sourceValues.getObject(PDF_CONFIG_KEY, PDFConfig.class);\n String subReportDir = sourceValues.getString(SUBREPORT_DIR_KEY);\n\n this.values.put(TASK_DIRECTORY_KEY, taskDirectory);\n this.values.put(CLIENT_HTTP_REQUEST_FACTORY_KEY, requestFactoryProvider);\n this.values.put(TEMPLATE_KEY, template);\n this.values.put(PDF_CONFIG_KEY, pdfConfig);\n this.values.put(SUBREPORT_DIR_KEY, subReportDir);\n this.values.put(VALUES_KEY, this);\n this.values.put(JOB_ID_KEY, sourceValues.getString(JOB_ID_KEY));\n this.values.put(LOCALE_KEY, sourceValues.getObject(LOCALE_KEY, Locale.class));\n }", "public int rebalanceNode(final RebalanceTaskInfo stealInfo) {\n\n final RebalanceTaskInfo info = metadataStore.getRebalancerState()\n .find(stealInfo.getDonorId());\n\n // Do we have the plan in the state?\n if(info == null) {\n throw new VoldemortException(\"Could not find plan \" + stealInfo\n + \" in the server state on \" + metadataStore.getNodeId());\n } else if(!info.equals(stealInfo)) {\n // If we do have the plan, is it the same\n throw new VoldemortException(\"The plan in server state \" + info\n + \" is not the same as the process passed \" + stealInfo);\n } else if(!acquireRebalancingPermit(stealInfo.getDonorId())) {\n // Both are same, now try to acquire a lock for the donor node\n throw new AlreadyRebalancingException(\"Node \" + metadataStore.getNodeId()\n + \" is already rebalancing from donor \"\n + info.getDonorId() + \" with info \" + info);\n }\n\n // Acquired lock successfully, start rebalancing...\n int requestId = asyncService.getUniqueRequestId();\n\n // Why do we pass 'info' instead of 'stealInfo'? So that we can change\n // the state as the stores finish rebalance\n asyncService.submitOperation(requestId,\n new StealerBasedRebalanceAsyncOperation(this,\n voldemortConfig,\n metadataStore,\n requestId,\n info));\n\n return requestId;\n }", "protected <T> T fromJsonString(String json, Class<T> clazz) {\n\t\treturn _gsonParser.fromJson(json, clazz);\n\t}", "public Jar setJarPrefix(Path file) {\n verifyNotSealed();\n if (jos != null)\n throw new IllegalStateException(\"Really executable cannot be set after entries are added.\");\n if (file != null && jarPrefixStr != null)\n throw new IllegalStateException(\"A prefix has already been set (\" + jarPrefixStr + \")\");\n this.jarPrefixFile = file;\n return this;\n }", "public void setMeta(String photoId, String title, String description) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SET_META);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"title\", title);\r\n parameters.put(\"description\", description);\r\n\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }", "private void writeResource(Resource record) throws IOException\n {\n m_buffer.setLength(0);\n\n //\n // Write the resource record\n //\n int[] fields = m_resourceModel.getModel();\n\n m_buffer.append(MPXConstants.RESOURCE_RECORD_NUMBER);\n for (int loop = 0; loop < fields.length; loop++)\n {\n int mpxFieldType = fields[loop];\n if (mpxFieldType == -1)\n {\n break;\n }\n\n ResourceField resourceField = MPXResourceField.getMpxjField(mpxFieldType);\n Object value = record.getCachedValue(resourceField);\n value = formatType(resourceField.getDataType(), value);\n\n m_buffer.append(m_delimiter);\n m_buffer.append(format(value));\n }\n\n stripTrailingDelimiters(m_buffer);\n m_buffer.append(MPXConstants.EOL);\n m_writer.write(m_buffer.toString());\n\n //\n // Write the resource notes\n //\n String notes = record.getNotes();\n if (notes.length() != 0)\n {\n writeNotes(MPXConstants.RESOURCE_NOTES_RECORD_NUMBER, notes);\n }\n\n //\n // Write the resource calendar\n //\n if (record.getResourceCalendar() != null)\n {\n writeCalendar(record.getResourceCalendar());\n }\n\n m_eventManager.fireResourceWrittenEvent(record);\n }", "public synchronized void stop () {\n if (isRunning()) {\n MetadataFinder.getInstance().removeTrackMetadataListener(metadataListener);\n WaveformFinder.getInstance().removeWaveformListener(waveformListener);\n BeatGridFinder.getInstance().removeBeatGridListener(beatGridListener);\n running.set(false);\n pendingUpdates.clear();\n queueHandler.interrupt();\n queueHandler = null;\n\n // Report the loss of our signatures, on the proper thread, outside our lock\n final Set<Integer> dyingSignatures = new HashSet<Integer>(signatures.keySet());\n signatures.clear();\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (Integer player : dyingSignatures) {\n deliverSignatureUpdate(player, null);\n }\n }\n });\n }\n deliverLifecycleAnnouncement(logger, false);\n }", "@SuppressWarnings(\"unused\")\n public boolean isValid() {\n Phonenumber.PhoneNumber phoneNumber = getPhoneNumber();\n return phoneNumber != null && mPhoneUtil.isValidNumber(phoneNumber);\n }" ]
Checks to see if matrix 'a' is the same as this matrix within the specified tolerance. @param a The matrix it is being compared against. @param tol How similar they must be to be equals. @return If they are equal within tolerance of each other.
[ "public boolean isIdentical(T a, double tol) {\n if( a.getType() != getType() )\n return false;\n return ops.isIdentical(mat,a.mat,tol);\n }" ]
[ "public BufferedImage getBufferedImage(int width, int height) {\n // using the new approach of Java 2D API\n BufferedImage buf = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);\n Graphics2D g2d = (Graphics2D) buf.getGraphics();\n g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);\n g2d.drawImage(image, 0, 0, width, height, null);\n g2d.dispose();\n return (buf);\n }", "private Map<String, String> generateCommonConfigPart() {\n\n Map<String, String> result = new HashMap<>();\n if (m_category != null) {\n result.put(CONFIGURATION_CATEGORY, m_category);\n }\n // append 'only leafs' to configuration\n if (m_onlyLeafs) {\n result.put(CONFIGURATION_ONLYLEAFS, null);\n }\n // append 'property' to configuration\n if (m_property != null) {\n result.put(CONFIGURATION_PROPERTY, m_property);\n }\n // append 'selectionType' to configuration\n if (m_selectiontype != null) {\n result.put(CONFIGURATION_SELECTIONTYPE, m_selectiontype);\n }\n return result;\n }", "public Association getAssociation(String collectionRole) {\n\t\tif ( associations == null ) {\n\t\t\treturn null;\n\t\t}\n\t\treturn associations.get( collectionRole );\n\t}", "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 cacheselector get(nitro_service service, String selectorname) throws Exception{\n\t\tcacheselector obj = new cacheselector();\n\t\tobj.set_selectorname(selectorname);\n\t\tcacheselector response = (cacheselector) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static sslcertkey_sslocspresponder_binding[] get(nitro_service service, String certkey) throws Exception{\n\t\tsslcertkey_sslocspresponder_binding obj = new sslcertkey_sslocspresponder_binding();\n\t\tobj.set_certkey(certkey);\n\t\tsslcertkey_sslocspresponder_binding response[] = (sslcertkey_sslocspresponder_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void linkOneToOne(Object obj, ClassDescriptor cld, ObjectReferenceDescriptor rds, boolean insert)\n {\n storeAndLinkOneToOne(true, obj, cld, rds, true);\n }", "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 }", "@SuppressWarnings(\"unchecked\") public Relation addPredecessor(Task targetTask, RelationType type, Duration lag)\n {\n //\n // Ensure that we have a valid lag duration\n //\n if (lag == null)\n {\n lag = Duration.getInstance(0, TimeUnit.DAYS);\n }\n\n //\n // Retrieve the list of predecessors\n //\n List<Relation> predecessorList = (List<Relation>) getCachedValue(TaskField.PREDECESSORS);\n\n //\n // Ensure that there is only one predecessor relationship between\n // these two tasks.\n //\n Relation predecessorRelation = null;\n Iterator<Relation> iter = predecessorList.iterator();\n while (iter.hasNext() == true)\n {\n predecessorRelation = iter.next();\n if (predecessorRelation.getTargetTask() == targetTask)\n {\n if (predecessorRelation.getType() != type || predecessorRelation.getLag().compareTo(lag) != 0)\n {\n predecessorRelation = null;\n }\n break;\n }\n predecessorRelation = null;\n }\n\n //\n // If necessary, create a new predecessor relationship\n //\n if (predecessorRelation == null)\n {\n predecessorRelation = new Relation(this, targetTask, type, lag);\n predecessorList.add(predecessorRelation);\n }\n\n //\n // Retrieve the list of successors\n //\n List<Relation> successorList = (List<Relation>) targetTask.getCachedValue(TaskField.SUCCESSORS);\n\n //\n // Ensure that there is only one successor relationship between\n // these two tasks.\n //\n Relation successorRelation = null;\n iter = successorList.iterator();\n while (iter.hasNext() == true)\n {\n successorRelation = iter.next();\n if (successorRelation.getTargetTask() == this)\n {\n if (successorRelation.getType() != type || successorRelation.getLag().compareTo(lag) != 0)\n {\n successorRelation = null;\n }\n break;\n }\n successorRelation = null;\n }\n\n //\n // If necessary, create a new successor relationship\n //\n if (successorRelation == null)\n {\n successorRelation = new Relation(targetTask, this, type, lag);\n successorList.add(successorRelation);\n }\n\n return (predecessorRelation);\n }" ]
Send a tempo changed announcement to all registered master listeners. @param tempo the new master tempo
[ "private void deliverTempoChangedAnnouncement(final double tempo) {\n for (final MasterListener listener : getMasterListeners()) {\n try {\n listener.tempoChanged(tempo);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering tempo changed announcement to listener\", t);\n }\n }\n }" ]
[ "void setPaused(final boolean isPaused) {\n docLock.writeLock().lock();\n try {\n docsColl.updateOne(\n getDocFilter(namespace, documentId),\n new BsonDocument(\"$set\",\n new BsonDocument(\n ConfigCodec.Fields.IS_PAUSED,\n new BsonBoolean(isPaused))));\n this.isPaused = isPaused;\n } catch (IllegalStateException e) {\n // eat this\n } finally {\n docLock.writeLock().unlock();\n }\n }", "public boolean isWorkingDate(Date date)\n {\n Calendar cal = DateHelper.popCalendar(date);\n Day day = Day.getInstance(cal.get(Calendar.DAY_OF_WEEK));\n DateHelper.pushCalendar(cal);\n return isWorkingDate(date, day);\n }", "public Duration getWork(Date startDate, Date endDate, TimeUnit format)\n {\n DateRange range = new DateRange(startDate, endDate);\n Long cachedResult = m_workingDateCache.get(range);\n long totalTime = 0;\n\n if (cachedResult == null)\n {\n //\n // We want the start date to be the earliest date, and the end date\n // to be the latest date. Set a flag here to indicate if we have swapped\n // the order of the supplied date.\n //\n boolean invert = false;\n if (startDate.getTime() > endDate.getTime())\n {\n invert = true;\n Date temp = startDate;\n startDate = endDate;\n endDate = temp;\n }\n\n Date canonicalStartDate = DateHelper.getDayStartDate(startDate);\n Date canonicalEndDate = DateHelper.getDayStartDate(endDate);\n\n if (canonicalStartDate.getTime() == canonicalEndDate.getTime())\n {\n ProjectCalendarDateRanges ranges = getRanges(startDate, null, null);\n if (ranges.getRangeCount() != 0)\n {\n totalTime = getTotalTime(ranges, startDate, endDate);\n }\n }\n else\n {\n //\n // Find the first working day in the range\n //\n Date currentDate = startDate;\n Calendar cal = Calendar.getInstance();\n cal.setTime(startDate);\n Day day = Day.getInstance(cal.get(Calendar.DAY_OF_WEEK));\n while (isWorkingDate(currentDate, day) == false && currentDate.getTime() < canonicalEndDate.getTime())\n {\n cal.add(Calendar.DAY_OF_YEAR, 1);\n currentDate = cal.getTime();\n day = day.getNextDay();\n }\n\n if (currentDate.getTime() < canonicalEndDate.getTime())\n {\n //\n // Calculate the amount of working time for this day\n //\n totalTime += getTotalTime(getRanges(currentDate, null, day), currentDate, true);\n\n //\n // Process each working day until we reach the last day\n //\n while (true)\n {\n cal.add(Calendar.DAY_OF_YEAR, 1);\n currentDate = cal.getTime();\n day = day.getNextDay();\n\n //\n // We have reached the last day\n //\n if (currentDate.getTime() >= canonicalEndDate.getTime())\n {\n break;\n }\n\n //\n // Skip this day if it has no working time\n //\n ProjectCalendarDateRanges ranges = getRanges(currentDate, null, day);\n if (ranges.getRangeCount() == 0)\n {\n continue;\n }\n\n //\n // Add the working time for the whole day\n //\n totalTime += getTotalTime(ranges);\n }\n }\n\n //\n // We are now at the last day\n //\n ProjectCalendarDateRanges ranges = getRanges(endDate, null, day);\n if (ranges.getRangeCount() != 0)\n {\n totalTime += getTotalTime(ranges, DateHelper.getDayStartDate(endDate), endDate);\n }\n }\n\n if (invert)\n {\n totalTime = -totalTime;\n }\n\n m_workingDateCache.put(range, Long.valueOf(totalTime));\n }\n else\n {\n totalTime = cachedResult.longValue();\n }\n\n return convertFormat(totalTime, format);\n }", "public static java.sql.Date getDate(Object value) {\n try {\n return toDate(value);\n } catch (ParseException pe) {\n pe.printStackTrace();\n return null;\n }\n }", "private void cleanUpAction() {\n\n try {\n m_model.deleteDescriptorIfNecessary();\n } catch (CmsException e) {\n LOG.error(m_messages.key(Messages.ERR_DELETING_DESCRIPTOR_0), e);\n }\n // unlock resource\n m_model.unlock();\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 static void embedSvgGraphic(\n final SVGElement svgRoot,\n final SVGElement newSvgRoot, final Document newDocument,\n final Dimension targetSize, final Double rotation) {\n final String originalWidth = svgRoot.getAttributeNS(null, \"width\");\n final String originalHeight = svgRoot.getAttributeNS(null, \"height\");\n /*\n * To scale the SVG graphic and to apply the rotation, we distinguish two\n * cases: width and height is set on the original SVG or not.\n *\n * Case 1: Width and height is set\n * If width and height is set, we wrap the original SVG into 2 new SVG elements\n * and a container element.\n *\n * Example:\n * Original SVG:\n * <svg width=\"100\" height=\"100\"></svg>\n *\n * New SVG (scaled to 300x300 and rotated by 90 degree):\n * <svg width=\"300\" height=\"300\">\n * <g transform=\"rotate(90.0 150 150)\">\n * <svg width=\"100%\" height=\"100%\" viewBox=\"0 0 100 100\">\n * <svg width=\"100\" height=\"100\"></svg>\n * </svg>\n * </g>\n * </svg>\n *\n * The requested size is set on the outermost <svg>. Then, the rotation is applied to the\n * <g> container and the scaling is achieved with the viewBox parameter on the 2nd <svg>.\n *\n *\n * Case 2: Width and height is not set\n * In this case the original SVG is wrapped into just one container and one new SVG element.\n * The rotation is set on the container, and the scaling happens automatically.\n *\n * Example:\n * Original SVG:\n * <svg viewBox=\"0 0 61.06 91.83\"></svg>\n *\n * New SVG (scaled to 300x300 and rotated by 90 degree):\n * <svg width=\"300\" height=\"300\">\n * <g transform=\"rotate(90.0 150 150)\">\n * <svg viewBox=\"0 0 61.06 91.83\"></svg>\n * </g>\n * </svg>\n */\n if (!StringUtils.isEmpty(originalWidth) && !StringUtils.isEmpty(originalHeight)) {\n Element wrapperContainer = newDocument.createElementNS(SVG_NS, \"g\");\n wrapperContainer.setAttributeNS(\n null,\n SVGConstants.SVG_TRANSFORM_ATTRIBUTE,\n getRotateTransformation(targetSize, rotation));\n newSvgRoot.appendChild(wrapperContainer);\n\n Element wrapperSvg = newDocument.createElementNS(SVG_NS, \"svg\");\n wrapperSvg.setAttributeNS(null, \"width\", \"100%\");\n wrapperSvg.setAttributeNS(null, \"height\", \"100%\");\n wrapperSvg.setAttributeNS(null, \"viewBox\", \"0 0 \" + originalWidth\n + \" \" + originalHeight);\n wrapperContainer.appendChild(wrapperSvg);\n\n Node svgRootImported = newDocument.importNode(svgRoot, true);\n wrapperSvg.appendChild(svgRootImported);\n } else if (StringUtils.isEmpty(originalWidth) && StringUtils.isEmpty(originalHeight)) {\n Element wrapperContainer = newDocument.createElementNS(SVG_NS, \"g\");\n wrapperContainer.setAttributeNS(\n null,\n SVGConstants.SVG_TRANSFORM_ATTRIBUTE,\n getRotateTransformation(targetSize, rotation));\n newSvgRoot.appendChild(wrapperContainer);\n\n Node svgRootImported = newDocument.importNode(svgRoot, true);\n wrapperContainer.appendChild(svgRootImported);\n } else {\n throw new IllegalArgumentException(\n \"Unsupported or invalid north-arrow SVG graphic: The same unit (px, em, %, ...) must be\" +\n \" \" +\n \"used for `width` and `height`.\");\n }\n }", "private static void invokeSetter(final Object bean, final Method setMethod, final Object fieldValue) {\n\t\ttry {\n\t\t\tsetMethod.setAccessible(true);\n\t\t\tsetMethod.invoke(bean, fieldValue);\n\t\t}\n\t\tcatch(final Exception e) {\n\t\t\tthrow new SuperCsvReflectionException(String.format(\"error invoking method %s()\", setMethod.getName()), e);\n\t\t}\n\t}", "public boolean load()\r\n {\r\n \t_load();\r\n \tjava.util.Iterator it = this.alChildren.iterator();\r\n \twhile (it.hasNext())\r\n \t{\r\n \t\tObject o = it.next();\r\n \t\tif (o instanceof OjbMetaTreeNode) ((OjbMetaTreeNode)o).load();\r\n \t}\r\n \treturn true;\r\n }" ]
Get the server redirects belonging to a server group @param profileId ID of profile @param serverGroupId ID of server group @return Collection of ServerRedirect for a server group
[ "public List<ServerRedirect> tableServers(int profileId, int serverGroupId) {\n ArrayList<ServerRedirect> servers = new ArrayList<>();\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_SERVERS +\n \" WHERE \" + Constants.GENERIC_PROFILE_ID + \" = ?\" +\n \" AND \" + Constants.SERVER_REDIRECT_GROUP_ID + \" = ?\"\n );\n queryStatement.setInt(1, profileId);\n queryStatement.setInt(2, serverGroupId);\n results = queryStatement.executeQuery();\n while (results.next()) {\n ServerRedirect curServer = new ServerRedirect(results.getInt(Constants.GENERIC_ID),\n results.getString(Constants.SERVER_REDIRECT_REGION),\n results.getString(Constants.SERVER_REDIRECT_SRC_URL),\n results.getString(Constants.SERVER_REDIRECT_DEST_URL),\n results.getString(Constants.SERVER_REDIRECT_HOST_HEADER));\n curServer.setProfileId(profileId);\n servers.add(curServer);\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n return servers;\n }" ]
[ "@Override\n public DMatrixRMaj getA() {\n if( A.data.length < numRows*numCols ) {\n A = new DMatrixRMaj(numRows,numCols);\n }\n A.reshape(numRows,numCols, false);\n CommonOps_DDRM.mult(Q,R,A);\n\n return A;\n }", "public static <T> List<T> load(ClassLoader classLoader, Class<T> serviceType) {\n List<T> foundServices = new ArrayList<>();\n Iterator<T> iterator = ServiceLoader.load(serviceType, classLoader).iterator();\n\n while (checkHasNextSafely(iterator)) {\n try {\n T item = iterator.next();\n foundServices.add(item);\n LOGGER.debug(String.format(\"Found %s [%s]\", serviceType.getSimpleName(), item.toString()));\n } catch (ServiceConfigurationError e) {\n LOGGER.trace(\"Can't find services using Java SPI\", e);\n LOGGER.error(e.getMessage());\n }\n }\n return foundServices;\n }", "private void init(AttributeSet attrs) {\n inflate(getContext(), R.layout.intl_phone_input, this);\n\n /**+\n * Country spinner\n */\n mCountrySpinner = (Spinner) findViewById(R.id.intl_phone_edit__country);\n mCountrySpinnerAdapter = new CountrySpinnerAdapter(getContext());\n mCountrySpinner.setAdapter(mCountrySpinnerAdapter);\n\n mCountries = CountriesFetcher.getCountries(getContext());\n mCountrySpinnerAdapter.addAll(mCountries);\n mCountrySpinner.setOnItemSelectedListener(mCountrySpinnerListener);\n\n setFlagDefaults(attrs);\n\n /**\n * Phone text field\n */\n mPhoneEdit = (EditText) findViewById(R.id.intl_phone_edit__phone);\n mPhoneEdit.addTextChangedListener(mPhoneNumberWatcher);\n\n setDefault();\n setEditTextDefaults(attrs);\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 }", "private void populateCalendarHours(Record record, ProjectCalendarHours hours) throws MPXJException\n {\n hours.setDay(Day.getInstance(NumberHelper.getInt(record.getInteger(0))));\n addDateRange(hours, record.getTime(1), record.getTime(2));\n addDateRange(hours, record.getTime(3), record.getTime(4));\n addDateRange(hours, record.getTime(5), record.getTime(6));\n }", "private String getStringPredicate(String fieldName, List<String> filterValues, List<Object> prms)\n {\n if (filterValues != null && !filterValues.isEmpty())\n {\n String res = \"\";\n for (String filterValue : filterValues)\n {\n if (filterValue == null)\n {\n continue;\n }\n if (!filterValue.isEmpty())\n {\n prms.add(filterValue);\n if (filterValue.contains(\"%\"))\n {\n res += String.format(\"(%s LIKE ?) OR \", fieldName);\n }\n else\n {\n res += String.format(\"(%s = ?) OR \", fieldName);\n }\n }\n else\n {\n res += String.format(\"(%s IS NULL OR %s = '') OR \", fieldName, fieldName);\n }\n }\n if (!res.isEmpty())\n {\n res = \"AND (\" + res.substring(0, res.length() - 4) + \") \";\n return res;\n }\n }\n return \"\";\n }", "public QueryBuilder<T, ID> orderByRaw(String rawSql) {\n\t\taddOrderBy(new OrderBy(rawSql, (ArgumentHolder[]) null));\n\t\treturn this;\n\t}", "public QueryBuilder<T, ID> orderByRaw(String rawSql) {\n\t\taddOrderBy(new OrderBy(rawSql, (ArgumentHolder[]) null));\n\t\treturn this;\n\t}", "public static ZMatrixRMaj householderVector(ZMatrixRMaj x ) {\n ZMatrixRMaj u = x.copy();\n\n double max = CommonOps_ZDRM.elementMaxAbs(u);\n\n CommonOps_ZDRM.elementDivide(u, max, 0, u);\n\n double nx = NormOps_ZDRM.normF(u);\n Complex_F64 c = new Complex_F64();\n u.get(0,0,c);\n\n double realTau,imagTau;\n\n if( c.getMagnitude() == 0 ) {\n realTau = nx;\n imagTau = 0;\n } else {\n realTau = c.real/c.getMagnitude()*nx;\n imagTau = c.imaginary/c.getMagnitude()*nx;\n }\n\n u.set(0,0,c.real + realTau,c.imaginary + imagTau);\n CommonOps_ZDRM.elementDivide(u,u.getReal(0,0),u.getImag(0,0),u);\n\n return u;\n }" ]
Create a new queued pool using the defaults for key of type K, request of type R, and value of Type V. @param factory The factory that creates objects @return The created pool
[ "public static <K, V> QueuedKeyedResourcePool<K, V> create(ResourceFactory<K, V> factory) {\n return create(factory, new ResourcePoolConfig());\n }" ]
[ "protected void updateLabelActiveStyle() {\n if (this.valueBoxBase.getText() != null && !this.valueBoxBase.getText().isEmpty()) {\n label.addStyleName(CssName.ACTIVE);\n } else {\n label.removeStyleName(CssName.ACTIVE);\n }\n }", "private void writeTasks(Project project)\n {\n Project.Tasks tasks = m_factory.createProjectTasks();\n project.setTasks(tasks);\n List<Project.Tasks.Task> list = tasks.getTask();\n\n for (Task task : m_projectFile.getTasks())\n {\n list.add(writeTask(task));\n }\n }", "private static void setupFlowId(SoapMessage message) {\n String flowId = FlowIdHelper.getFlowId(message);\n\n if (flowId == null) {\n flowId = FlowIdProtocolHeaderCodec.readFlowId(message);\n }\n\n if (flowId == null) {\n flowId = FlowIdSoapCodec.readFlowId(message);\n }\n\n if (flowId == null) {\n Exchange ex = message.getExchange();\n if (null!=ex){\n Message reqMsg = ex.getOutMessage();\n if ( null != reqMsg) {\n flowId = FlowIdHelper.getFlowId(reqMsg);\n }\n }\n }\n\n if (flowId != null && !flowId.isEmpty()) {\n FlowIdHelper.setFlowId(message, flowId);\n }\n }", "public static String parseRoot(String zookeepers) {\n int slashIndex = zookeepers.indexOf(\"/\");\n if (slashIndex != -1) {\n return zookeepers.substring(slashIndex).trim();\n }\n return \"/\";\n }", "private void updatePreview(TrackMetadataUpdate update, WaveformPreview preview) {\n previewHotCache.put(DeckReference.getDeckReference(update.player, 0), preview); // Main deck\n if (update.metadata.getCueList() != null) { // Update the cache with any hot cues in this track as well\n for (CueList.Entry entry : update.metadata.getCueList().entries) {\n if (entry.hotCueNumber != 0) {\n previewHotCache.put(DeckReference.getDeckReference(update.player, entry.hotCueNumber), preview);\n }\n }\n }\n deliverWaveformPreviewUpdate(update.player, preview);\n }", "protected void mergeVerticalBlocks() {\n for(int i = 0; i < rectangles.size() - 1; i++) {\n for(int j = i + 1; j < rectangles.size(); j++) {\n Rectangle2D.Double firstRect = rectangles.get(i);\n Rectangle2D.Double secondRect = rectangles.get(j);\n if (roughlyEqual(firstRect.x, secondRect.x) && roughlyEqual(firstRect.width, secondRect.width)) {\n if (roughlyEqual(firstRect.y + firstRect.height, secondRect.y)) {\n firstRect.height += secondRect.height;\n rectangles.set(i, firstRect);\n rectangles.remove(j);\n }\n }\n }\n }\n }", "public void addImportedPackages(Set<String> importedPackages) {\n\t\taddImportedPackages(importedPackages.toArray(new String[importedPackages.size()]));\n\t}", "public void setRoles(List<NamedRoleInfo> roles) {\n\t\tthis.roles = roles;\n\t\tList<AuthorizationInfo> authorizations = new ArrayList<AuthorizationInfo>();\n\t\tfor (NamedRoleInfo role : roles) {\n\t\t\tauthorizations.addAll(role.getAuthorizations());\n\t\t}\n\t\tsuper.setAuthorizations(authorizations);\n\t}", "private void checkAnonymous(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n String access = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_ACCESS);\r\n\r\n if (!\"anonymous\".equals(access))\r\n {\r\n throw new ConstraintException(\"The access property of the field \"+fieldDef.getName()+\" defined in class \"+fieldDef.getOwner().getName()+\" cannot be changed\");\r\n }\r\n\r\n if ((fieldDef.getName() == null) || (fieldDef.getName().length() == 0))\r\n {\r\n throw new ConstraintException(\"An anonymous field defined in class \"+fieldDef.getOwner().getName()+\" has no name\");\r\n }\r\n }" ]
Finish initializing service. @throws IOException oop
[ "@PostConstruct\n\tprotected void init() throws IOException {\n\t\t// base configuration from XML file\n\t\tif (null != configurationFile) {\n\t\t\tlog.debug(\"Get base configuration from {}\", configurationFile);\n\t\t\tmanager = new DefaultCacheManager(configurationFile);\n\t\t} else {\n\t\t\tGlobalConfigurationBuilder builder = new GlobalConfigurationBuilder();\n\t\t\tbuilder.globalJmxStatistics().allowDuplicateDomains(true);\n\t\t\tmanager = new DefaultCacheManager(builder.build());\n\t\t}\n\n\t\tif (listener == null) {\n\t\t\tlistener = new InfinispanCacheListener();\n\t\t}\n\t\tmanager.addListener(listener);\n\n\t\t// cache for caching the cache configurations (hmmm, sounds a bit strange)\n\t\tMap<String, Map<CacheCategory, CacheService>> cacheCache = \n\t\t\t\tnew HashMap<String, Map<CacheCategory, CacheService>>();\n\n\t\t// build default configuration\n\t\tif (null != defaultConfiguration) {\n\t\t\tsetCaches(cacheCache, null, defaultConfiguration);\n\t\t}\n\n\t\t// build layer specific configurations\n\t\tfor (Layer layer : layerMap.values()) {\n\t\t\tCacheInfo ci = configurationService.getLayerExtraInfo(layer.getLayerInfo(), CacheInfo.class);\n\t\t\tif (null != ci) {\n\t\t\t\tsetCaches(cacheCache, layer, ci);\n\t\t\t}\n\t\t}\n\t}" ]
[ "private void readRelationships(Project gpProject)\n {\n for (net.sf.mpxj.ganttproject.schema.Task gpTask : gpProject.getTasks().getTask())\n {\n readRelationships(gpTask);\n }\n }", "public static base_responses flush(nitro_service client, cachecontentgroup resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcachecontentgroup flushresources[] = new cachecontentgroup[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tflushresources[i] = new cachecontentgroup();\n\t\t\t\tflushresources[i].name = resources[i].name;\n\t\t\t\tflushresources[i].query = resources[i].query;\n\t\t\t\tflushresources[i].host = resources[i].host;\n\t\t\t\tflushresources[i].selectorvalue = resources[i].selectorvalue;\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 synchronized void mapPublicKeys(final PublicKey original, final PublicKey substitute)\n\t{\n\t\t_mappedPublicKeys.put(original, substitute);\n\t\tif(persistImmediately) { persistPublicKeyMap(); }\n\t}", "public void update(int width, int height, int sampleCount) {\n if (capturing) {\n throw new IllegalStateException(\"Cannot update backing texture while capturing\");\n }\n\n this.width = width;\n this.height = height;\n\n if (sampleCount == 0)\n captureTexture = new GVRRenderTexture(getGVRContext(), width, height);\n else\n captureTexture = new GVRRenderTexture(getGVRContext(), width, height, sampleCount);\n\n setRenderTexture(captureTexture);\n readBackBuffer = new int[width * height];\n }", "public static Object newInstance(Class target, Class[] types, Object[] args) throws InstantiationException,\r\n IllegalAccessException,\r\n IllegalArgumentException,\r\n InvocationTargetException,\r\n NoSuchMethodException,\r\n SecurityException\r\n {\r\n return newInstance(target, types, args, false);\r\n }", "public void addProducer(Broker broker) {\n Properties props = new Properties();\n props.put(\"host\", broker.host);\n props.put(\"port\", \"\" + broker.port);\n props.putAll(config.getProperties());\n if (sync) {\n SyncProducer producer = new SyncProducer(new SyncProducerConfig(props));\n logger.info(\"Creating sync producer for broker id = \" + broker.id + \" at \" + broker.host + \":\" + broker.port);\n syncProducers.put(broker.id, producer);\n } else {\n AsyncProducer<V> producer = new AsyncProducer<V>(new AsyncProducerConfig(props),//\n new SyncProducer(new SyncProducerConfig(props)),//\n serializer,//\n eventHandler,//\n config.getEventHandlerProperties(),//\n this.callbackHandler, //\n config.getCbkHandlerProperties());\n producer.start();\n logger.info(\"Creating async producer for broker id = \" + broker.id + \" at \" + broker.host + \":\" + broker.port);\n asyncProducers.put(broker.id, producer);\n }\n }", "private boolean isClockwise(Point center, Point a, Point b) {\n double cross = (a.x - center.x) * (b.y - center.y) - (b.x - center.x) * (a.y - center.y);\n return cross > 0;\n }", "private String[] readXMLDeclaration(Reader r) throws KNXMLException\r\n\t{\r\n\t\tfinal StringBuffer buf = new StringBuffer(100);\r\n\t\ttry {\r\n\t\t\tfor (int c = 0; (c = r.read()) != -1 && c != '?';)\r\n\t\t\t\tbuf.append((char) c);\r\n\t\t}\r\n\t\tcatch (final IOException e) {\r\n\t\t\tthrow new KNXMLException(\"reading XML declaration, \" + e.getMessage(), buf\r\n\t\t\t\t.toString(), 0);\r\n\t\t}\r\n\t\tString s = buf.toString().trim();\r\n\r\n\t\tString version = null;\r\n\t\tString encoding = null;\r\n\t\tString standalone = null;\r\n\r\n\t\tfor (int state = 0; state < 3; ++state)\r\n\t\t\tif (state == 0 && s.startsWith(\"version\")) {\r\n\t\t\t\tversion = getAttValue(s = s.substring(7));\r\n\t\t\t\ts = s.substring(s.indexOf(version) + version.length() + 1).trim();\r\n\t\t\t}\r\n\t\t\telse if (state == 1 && s.startsWith(\"encoding\")) {\r\n\t\t\t\tencoding = getAttValue(s = s.substring(8));\r\n\t\t\t\ts = s.substring(s.indexOf(encoding) + encoding.length() + 1).trim();\r\n\t\t\t}\r\n\t\t\telse if (state == 1 || state == 2) {\r\n\t\t\t\tif (s.startsWith(\"standalone\")) {\r\n\t\t\t\t\tstandalone = getAttValue(s);\r\n\t\t\t\t\tif (!standalone.equals(\"yes\") && !standalone.equals(\"no\"))\r\n\t\t\t\t\t\tthrow new KNXMLException(\"invalid standalone pseudo-attribute\",\r\n\t\t\t\t\t\t\tstandalone, 0);\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t\tthrow new KNXMLException(\"unknown XML declaration pseudo-attribute\", s, 0);\r\n\t\treturn new String[] { version, encoding, standalone };\r\n\t}", "public GreenMailConfiguration build(Properties properties) {\n GreenMailConfiguration configuration = new GreenMailConfiguration();\n String usersParam = properties.getProperty(GREENMAIL_USERS);\n if (null != usersParam) {\n String[] usersArray = usersParam.split(\",\");\n for (String user : usersArray) {\n extractAndAddUser(configuration, user);\n }\n }\n String disabledAuthentication = properties.getProperty(GREENMAIL_AUTH_DISABLED);\n if (null != disabledAuthentication) {\n configuration.withDisabledAuthentication();\n }\n return configuration;\n }" ]
The documentation for InputStream.skip indicates that it can bail out early, and not skip the requested number of bytes. I've encountered this in practice, hence this helper method. @param stream InputStream instance @param skip number of bytes to skip
[ "public static void skip(InputStream stream, long skip) throws IOException\n {\n long count = skip;\n while (count > 0)\n {\n count -= stream.skip(count);\n }\n }" ]
[ "public Pixel[] pixels() {\n Pixel[] pixels = new Pixel[count()];\n Point[] points = points();\n for (int k = 0; k < points.length; k++) {\n pixels[k] = pixel(points[k]);\n }\n return pixels;\n }", "@Override public void process(MPPReader reader, ProjectFile file, DirectoryEntry root) throws MPXJException, IOException\n {\n try\n {\n populateMemberData(reader, file, root);\n processProjectProperties();\n\n if (!reader.getReadPropertiesOnly())\n {\n processCalendarData();\n processResourceData();\n processTaskData();\n processConstraintData();\n processAssignmentData();\n\n if (reader.getReadPresentationData())\n {\n processViewPropertyData();\n processViewData();\n processTableData();\n }\n }\n }\n\n finally\n {\n clearMemberData();\n }\n }", "void commitTempFile(File temp) throws ConfigurationPersistenceException {\n if (!doneBootup.get()) {\n return;\n }\n if (!interactionPolicy.isReadOnly()) {\n FilePersistenceUtils.moveTempFileToMain(temp, mainFile);\n } else {\n FilePersistenceUtils.moveTempFileToMain(temp, lastFile);\n }\n }", "public void 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 void createAndAddButton(PatternType pattern, String messageKey) {\n\n CmsRadioButton btn = new CmsRadioButton(pattern.toString(), Messages.get().key(messageKey));\n btn.addStyleName(I_CmsWidgetsLayoutBundle.INSTANCE.widgetCss().radioButtonlabel());\n btn.setGroup(m_groupPattern);\n m_patternButtons.put(pattern, btn);\n m_patternRadioButtonsPanel.add(btn);\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 }", "private void initManagementPart() {\n\n m_manageExceptionsButton.setText(Messages.get().key(Messages.GUI_SERIALDATE_BUTTON_MANAGE_EXCEPTIONS_0));\n m_manageExceptionsButton.getElement().getStyle().setFloat(Style.Float.RIGHT);\n }", "private static Set<String> imageOrientationsOf(ImageMetadata metadata) {\n\n String exifIFD0DirName = new ExifIFD0Directory().getName();\n\n Tag[] tags = Arrays.stream(metadata.getDirectories())\n .filter(dir -> dir.getName().equals(exifIFD0DirName))\n .findFirst()\n .map(Directory::getTags)\n .orElseGet(() -> new Tag[0]);\n\n return Arrays.stream(tags)\n .filter(tag -> tag.getType() == 274)\n .map(Tag::getRawValue)\n .collect(Collectors.toSet());\n }", "public String getPromotionDetailsJsonModel() throws IOException {\n final PromotionEvaluationReport sampleReport = new PromotionEvaluationReport();\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.UNPROMOTED_MSG, \"com.acme.secure-smh:core-relay:1.2.0\"), MAJOR);\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.DO_NOT_USE_MSG, \"com.google.guava:guava:20.0\"), MAJOR);\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.MISSING_LICENSE_MSG, \"org.apache.maven.wagon:wagon-webdav-jackrabbit:2.12\"), MINOR);\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.UNACCEPTABLE_LICENSE_MSG,\n \"aopaliance:aopaliance:1.0 licensed as Attribution-ShareAlike 2.5 Generic, \" +\n \"org.polyjdbc:polyjdbc0.7.1 licensed as Creative Commons Attribution-ShareAlike 3.0 Unported License\"),\n MINOR);\n\n sampleReport.addMessage(PromotionReportTranslator.SNAPSHOT_VERSION_MSG, Tag.CRITICAL);\n return JsonUtils.serialize(sampleReport);\n }" ]
Given a particular id, return the correct contextual. For contextuals which aren't passivation capable, the contextual can't be found in another container, and null will be returned. @param id An identifier for the contextual @return the contextual
[ "public <C extends Contextual<I>, I> C getContextual(String id) {\n return this.<C, I>getContextual(new StringBeanIdentifier(id));\n }" ]
[ "public RandomVariable[] getGradient(){\r\n\r\n\t\t// for now let us take the case for output-dimension equal to one!\r\n\t\tint numberOfVariables = getNumberOfVariablesInList();\r\n\t\tint numberOfCalculationSteps = factory.getNumberOfEntriesInList();\r\n\r\n\t\tRandomVariable[] omega_hat = new RandomVariable[numberOfCalculationSteps];\r\n\r\n\t\t// first entry gets initialized\r\n\t\tomega_hat[numberOfCalculationSteps-1] = new RandomVariableFromDoubleArray(1.0);\r\n\r\n\t\t/*\r\n\t\t * TODO: Find way that calculations form here on are not 'recorded' by the factory\r\n\t\t * IDEA: Let the calculation below run on {@link RandomVariableFromDoubleArray}, ie cast everything down!\r\n\t\t * */\r\n\r\n\t\tfor(int functionIndex = numberOfCalculationSteps - 2; functionIndex > 0; functionIndex--){\r\n\t\t\t// apply chain rule\r\n\t\t\tomega_hat[functionIndex] = new RandomVariableFromDoubleArray(0.0);\r\n\r\n\t\t\t/*TODO: save all D_{i,j}*\\omega_j in vector and sum up later */\r\n\t\t\tfor(RandomVariableUniqueVariable parent:parentsVariables){\r\n\r\n\t\t\t\tint variableIndex = parent.getVariableID();\r\n\r\n\t\t\t\tomega_hat[functionIndex] = omega_hat[functionIndex].add(getPartialDerivative(functionIndex, variableIndex).mult(omega_hat[variableIndex]));\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/* Due to the fact that we can still introduce 'new' true variables on the fly they are NOT the last couple of indices!\r\n\t\t * Thus save the indices of the true variables and recover them after finalizing all the calculations\r\n\t\t * IDEA: quit calculation after minimal true variable index is reached */\r\n\t\tRandomVariable[] gradient = new RandomVariable[numberOfVariables];\r\n\r\n\t\t/* TODO: sort array in correct manner! */\r\n\t\tint[] indicesOfVariables = getIDsOfVariablesInList();\r\n\r\n\t\tfor(int i = 0; i < numberOfVariables; i++){\r\n\t\t\tgradient[i] = omega_hat[numberOfCalculationSteps - numberOfVariables + indicesOfVariables[i]];\r\n\t\t}\r\n\r\n\t\treturn gradient;\r\n\t}", "protected String findPath(String start, String end) {\n if (start.equals(end)) {\n return start;\n } else {\n return findPath(start, parent.get(end)) + \" -> \" + end;\n }\n }", "public Group lookupGroup(String url) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_LOOKUP_GROUP);\r\n\r\n parameters.put(\"url\", url);\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 Group group = new Group();\r\n Element payload = response.getPayload();\r\n Element groupnameElement = (Element) payload.getElementsByTagName(\"groupname\").item(0);\r\n group.setId(payload.getAttribute(\"id\"));\r\n group.setName(((Text) groupnameElement.getFirstChild()).getData());\r\n return group;\r\n }", "public Double getAvgEventValue() {\n resetIfNeeded();\n synchronized(this) {\n long eventsLastInterval = numEventsLastInterval - numEventsLastLastInterval;\n if(eventsLastInterval > 0)\n return ((totalEventValueLastInterval - totalEventValueLastLastInterval) * 1.0)\n / eventsLastInterval;\n else\n return 0.0;\n }\n }", "public ParallelTaskBuilder setSshPrivKeyRelativePathWtihPassphrase(\n String privKeyRelativePath, String passphrase) {\n this.sshMeta.setPrivKeyRelativePath(privKeyRelativePath);\n this.sshMeta.setPrivKeyUsePassphrase(true);\n this.sshMeta.setPassphrase(passphrase);\n this.sshMeta.setSshLoginType(SshLoginType.KEY);\n return this;\n }", "private ProjectCalendar getTaskCalendar(Project.Tasks.Task task)\n {\n ProjectCalendar calendar = null;\n\n BigInteger calendarID = task.getCalendarUID();\n if (calendarID != null)\n {\n calendar = m_projectFile.getCalendarByUniqueID(Integer.valueOf(calendarID.intValue()));\n }\n\n return (calendar);\n }", "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 void put(@NotNull final PersistentStoreTransaction txn,\n final long localId,\n @NotNull final ByteIterable value,\n @Nullable final ByteIterable oldValue,\n final int propertyId,\n @NotNull final ComparableValueType type) {\n final Store valueIdx = getOrCreateValueIndex(txn, propertyId);\n final ByteIterable key = PropertyKey.propertyKeyToEntry(new PropertyKey(localId, propertyId));\n final Transaction envTxn = txn.getEnvironmentTransaction();\n primaryStore.put(envTxn, key, value);\n final ByteIterable secondaryValue = LongBinding.longToCompressedEntry(localId);\n boolean success;\n if (oldValue == null) {\n success = allPropsIndex.put(envTxn, IntegerBinding.intToCompressedEntry(propertyId), secondaryValue);\n } else {\n success = deleteFromStore(envTxn, valueIdx, secondaryValue, createSecondaryKeys(store.getPropertyTypes(), oldValue, type));\n }\n if (success) {\n for (final ByteIterable secondaryKey : createSecondaryKeys(store.getPropertyTypes(), value, type)) {\n valueIdx.put(envTxn, secondaryKey, secondaryValue);\n }\n }\n checkStatus(success, \"Failed to put\");\n }", "public static base_response Import(nitro_service client, sslfipskey resource) throws Exception {\n\t\tsslfipskey Importresource = new sslfipskey();\n\t\tImportresource.fipskeyname = resource.fipskeyname;\n\t\tImportresource.key = resource.key;\n\t\tImportresource.inform = resource.inform;\n\t\tImportresource.wrapkeyname = resource.wrapkeyname;\n\t\tImportresource.iv = resource.iv;\n\t\tImportresource.exponent = resource.exponent;\n\t\treturn Importresource.perform_operation(client,\"Import\");\n\t}" ]
Recovers the state of synchronization for a namespace in case a system failure happened. The goal is to revert the namespace to a known, good state. This method itself is resilient to failures, since it doesn't delete any documents from the undo collection until the collection is in the desired state with respect to those documents.
[ "private void recoverNamespace(final NamespaceSynchronizationConfig nsConfig) {\n final MongoCollection<BsonDocument> undoCollection =\n getUndoCollection(nsConfig.getNamespace());\n final MongoCollection<BsonDocument> localCollection =\n getLocalCollection(nsConfig.getNamespace());\n final List<BsonDocument> undoDocs = undoCollection.find().into(new ArrayList<>());\n final Set<BsonValue> recoveredIds = new HashSet<>();\n\n\n // Replace local docs with undo docs. Presence of an undo doc implies we had a system failure\n // during a write. This covers updates and deletes.\n for (final BsonDocument undoDoc : undoDocs) {\n final BsonValue documentId = BsonUtils.getDocumentId(undoDoc);\n final BsonDocument filter = getDocumentIdFilter(documentId);\n localCollection.findOneAndReplace(\n filter, undoDoc, new FindOneAndReplaceOptions().upsert(true));\n recoveredIds.add(documentId);\n }\n\n // If we recovered a document, but its pending writes are set to do something else, then the\n // failure occurred after the pending writes were set, but before the undo document was\n // deleted. In this case, we should restore the document to the state that the pending\n // write indicates. There is a possibility that the pending write is from before the failed\n // operation, but in that case, the findOneAndReplace or delete is a no-op since restoring\n // the document to the state of the change event would be the same as recovering the undo\n // document.\n for (final CoreDocumentSynchronizationConfig docConfig : nsConfig.getSynchronizedDocuments()) {\n final BsonValue documentId = docConfig.getDocumentId();\n final BsonDocument filter = getDocumentIdFilter(documentId);\n\n if (recoveredIds.contains(docConfig.getDocumentId())) {\n final ChangeEvent<BsonDocument> pendingWrite = docConfig.getLastUncommittedChangeEvent();\n if (pendingWrite != null) {\n switch (pendingWrite.getOperationType()) {\n case INSERT:\n case UPDATE:\n case REPLACE:\n localCollection.findOneAndReplace(\n filter,\n pendingWrite.getFullDocument(),\n new FindOneAndReplaceOptions().upsert(true)\n );\n break;\n case DELETE:\n localCollection.deleteOne(filter);\n break;\n default:\n // There should never be pending writes with an unknown event type, but if someone\n // is messing with the config collection we want to stop the synchronizer to prevent\n // further data corruption.\n throw new IllegalStateException(\n \"there should not be a pending write with an unknown event type\"\n );\n }\n }\n }\n }\n\n // Delete all of our undo documents. If we've reached this point, we've recovered the local\n // collection to the state we want with respect to all of our undo documents. If we fail before\n // these deletes or while carrying out the deletes, but after recovering the documents to\n // their desired state, that's okay because the next recovery pass will be effectively a no-op\n // up to this point.\n for (final BsonValue recoveredId : recoveredIds) {\n undoCollection.deleteOne(getDocumentIdFilter(recoveredId));\n }\n\n // Find local documents for which there are no document configs and delete them. This covers\n // inserts, upserts, and desync deletes. This will occur on any recovery pass regardless of\n // the documents in the undo collection, so it's fine that we do this after deleting the undo\n // documents.\n localCollection.deleteMany(new BsonDocument(\n \"_id\",\n new BsonDocument(\n \"$nin\",\n new BsonArray(new ArrayList<>(\n this.syncConfig.getSynchronizedDocumentIds(nsConfig.getNamespace()))))));\n }" ]
[ "public List<Message> requestFolderMenuFrom(final SlotReference slotReference, final int sortOrder, final int folderId)\n throws Exception {\n\n ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {\n @Override\n public List<Message> useClient(Client client) throws Exception {\n if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) {\n try {\n logger.debug(\"Requesting Key menu.\");\n Message response = client.menuRequestTyped(Message.KnownType.FOLDER_MENU_REQ, Message.MenuIdentifier.MAIN_MENU, slotReference.slot,\n CdjStatus.TrackType.UNANALYZED, new NumberField(sortOrder), new NumberField(folderId), new NumberField(0xffffff));\n return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.UNANALYZED, response);\n } finally {\n client.unlockForMenuOperations();\n }\n } else {\n throw new TimeoutException(\"Unable to lock player for menu operations.\");\n }\n }\n };\n\n return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, \"requesting folder menu\");\n }", "public static base_responses add(nitro_service client, dnspolicylabel resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdnspolicylabel addresources[] = new dnspolicylabel[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dnspolicylabel();\n\t\t\t\taddresources[i].labelname = resources[i].labelname;\n\t\t\t\taddresources[i].transform = resources[i].transform;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public void deleteStoreDefinition(String storeName) {\n // acquire write lock\n writeLock.lock();\n\n try {\n // Check if store exists\n if(!this.storeNames.contains(storeName)) {\n throw new VoldemortException(\"Requested store to be deleted does not exist !\");\n }\n\n // Otherwise remove from the STORES directory. Note: The version\n // argument is not required here since the\n // ConfigurationStorageEngine simply ignores this.\n this.storeDefinitionsStorageEngine.delete(storeName, null);\n\n // Update the metadata cache\n this.metadataCache.remove(storeName);\n\n // Re-initialize the store definitions. This is primarily required\n // to re-create the value for key: 'stores.xml'. This is necessary\n // for backwards compatibility.\n initStoreDefinitions(null);\n } finally {\n writeLock.unlock();\n }\n }", "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 }", "public String userAgent() {\n return String.format(\"Azure-SDK-For-Java/%s OS:%s MacAddressHash:%s Java:%s\",\n getClass().getPackage().getImplementationVersion(),\n OS,\n MAC_ADDRESS_HASH,\n JAVA_VERSION);\n }", "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 }", "public void loadWithTimeout(int timeout) {\n\n for (String stylesheet : m_stylesheets) {\n boolean alreadyLoaded = checkStylesheet(stylesheet);\n if (alreadyLoaded) {\n m_loadCounter += 1;\n } else {\n appendStylesheet(stylesheet, m_jsCallback);\n }\n }\n checkAllLoaded();\n if (timeout > 0) {\n Timer timer = new Timer() {\n\n @SuppressWarnings(\"synthetic-access\")\n @Override\n public void run() {\n\n callCallback();\n }\n };\n\n timer.schedule(timeout);\n }\n }", "public static List<String> getArgumentNames(MethodCallExpression methodCall) {\r\n ArrayList<String> result = new ArrayList<String>();\r\n\r\n Expression arguments = methodCall.getArguments();\r\n List<Expression> argExpressions = null;\r\n if (arguments instanceof ArrayExpression) {\r\n argExpressions = ((ArrayExpression) arguments).getExpressions();\r\n } else if (arguments instanceof ListExpression) {\r\n argExpressions = ((ListExpression) arguments).getExpressions();\r\n } else if (arguments instanceof TupleExpression) {\r\n argExpressions = ((TupleExpression) arguments).getExpressions();\r\n } else {\r\n LOG.warn(\"getArgumentNames arguments is not an expected type\");\r\n }\r\n\r\n if (argExpressions != null) {\r\n for (Expression exp : argExpressions) {\r\n if (exp instanceof VariableExpression) {\r\n result.add(((VariableExpression) exp).getName());\r\n }\r\n }\r\n }\r\n return result;\r\n }", "public void growMaxLength( int arrayLength , boolean preserveValue ) {\n if( arrayLength < 0 )\n throw new IllegalArgumentException(\"Negative array length. Overflow?\");\n // see if multiplying numRows*numCols will cause an overflow. If it won't then pick the smaller of the two\n if( numRows != 0 && numCols <= Integer.MAX_VALUE / numRows ) {\n // save the user from themselves\n arrayLength = Math.min(numRows*numCols, arrayLength);\n }\n if( nz_values == null || arrayLength > this.nz_values.length ) {\n double[] data = new double[ arrayLength ];\n int[] row_idx = new int[ arrayLength ];\n\n if( preserveValue ) {\n if( nz_values == null )\n throw new IllegalArgumentException(\"Can't preserve values when uninitialized\");\n System.arraycopy(this.nz_values, 0, data, 0, this.nz_length);\n System.arraycopy(this.nz_rows, 0, row_idx, 0, this.nz_length);\n }\n\n this.nz_values = data;\n this.nz_rows = row_idx;\n }\n }" ]
Polls the next char from the stack @return next char
[ "public char pollChar() {\n if(hasNextChar()) {\n if(hasNextWord() &&\n character+1 >= parsedLine.words().get(word).lineIndex()+\n parsedLine.words().get(word).word().length())\n word++;\n return parsedLine.line().charAt(character++);\n }\n return '\\u0000';\n }" ]
[ "public void generateReport(List<XmlSuite> xmlSuites,\n List<ISuite> suites,\n String outputDirectoryName)\n {\n removeEmptyDirectories(new File(outputDirectoryName));\n \n boolean useFrames = System.getProperty(FRAMES_PROPERTY, \"true\").equals(\"true\");\n boolean onlyFailures = System.getProperty(ONLY_FAILURES_PROPERTY, \"false\").equals(\"true\");\n\n File outputDirectory = new File(outputDirectoryName, REPORT_DIRECTORY);\n outputDirectory.mkdirs();\n\n try\n {\n if (useFrames)\n {\n createFrameset(outputDirectory);\n }\n createOverview(suites, outputDirectory, !useFrames, onlyFailures);\n createSuiteList(suites, outputDirectory, onlyFailures);\n createGroups(suites, outputDirectory);\n createResults(suites, outputDirectory, onlyFailures);\n createLog(outputDirectory, onlyFailures);\n copyResources(outputDirectory);\n }\n catch (Exception ex)\n {\n throw new ReportNGException(\"Failed generating HTML report.\", ex);\n }\n }", "public static base_responses update(nitro_service client, onlinkipv6prefix resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tonlinkipv6prefix updateresources[] = new onlinkipv6prefix[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new onlinkipv6prefix();\n\t\t\t\tupdateresources[i].ipv6prefix = resources[i].ipv6prefix;\n\t\t\t\tupdateresources[i].onlinkprefix = resources[i].onlinkprefix;\n\t\t\t\tupdateresources[i].autonomusprefix = resources[i].autonomusprefix;\n\t\t\t\tupdateresources[i].depricateprefix = resources[i].depricateprefix;\n\t\t\t\tupdateresources[i].decrementprefixlifetimes = resources[i].decrementprefixlifetimes;\n\t\t\t\tupdateresources[i].prefixvalidelifetime = resources[i].prefixvalidelifetime;\n\t\t\t\tupdateresources[i].prefixpreferredlifetime = resources[i].prefixpreferredlifetime;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "public static authenticationvserver_auditnslogpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_auditnslogpolicy_binding obj = new authenticationvserver_auditnslogpolicy_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_auditnslogpolicy_binding response[] = (authenticationvserver_auditnslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "protected CDI11Deployment createDeployment(ServletContext context, CDI11Bootstrap bootstrap) {\n\n ImmutableSet.Builder<Metadata<Extension>> extensionsBuilder = ImmutableSet.builder();\n extensionsBuilder.addAll(bootstrap.loadExtensions(WeldResourceLoader.getClassLoader()));\n if (isDevModeEnabled) {\n extensionsBuilder.add(new MetadataImpl<Extension>(DevelopmentMode.getProbeExtension(resourceLoader), \"N/A\"));\n }\n\n final Iterable<Metadata<Extension>> extensions = extensionsBuilder.build();\n final TypeDiscoveryConfiguration typeDiscoveryConfiguration = bootstrap.startExtensions(extensions);\n final EEModuleDescriptor eeModule = new EEModuleDescriptorImpl(context.getContextPath(), ModuleType.WEB);\n\n final DiscoveryStrategy strategy = DiscoveryStrategyFactory.create(resourceLoader, bootstrap, typeDiscoveryConfiguration.getKnownBeanDefiningAnnotations(),\n Boolean.parseBoolean(context.getInitParameter(Jandex.DISABLE_JANDEX_DISCOVERY_STRATEGY)));\n\n if (Jandex.isJandexAvailable(resourceLoader)) {\n try {\n Class<? extends BeanArchiveHandler> handlerClass = Reflections.loadClass(resourceLoader, JANDEX_SERVLET_CONTEXT_BEAN_ARCHIVE_HANDLER);\n strategy.registerHandler((SecurityActions.newConstructorInstance(handlerClass, new Class<?>[] { ServletContext.class }, context)));\n } catch (Exception e) {\n throw CommonLogger.LOG.unableToInstantiate(JANDEX_SERVLET_CONTEXT_BEAN_ARCHIVE_HANDLER, Arrays.toString(new Object[] { context }), e);\n }\n } else {\n strategy.registerHandler(new ServletContextBeanArchiveHandler(context));\n }\n strategy.setScanner(new WebAppBeanArchiveScanner(resourceLoader, bootstrap, context));\n Set<WeldBeanDeploymentArchive> beanDeploymentArchives = strategy.performDiscovery();\n\n String isolation = context.getInitParameter(CONTEXT_PARAM_ARCHIVE_ISOLATION);\n\n if (isolation == null || Boolean.valueOf(isolation)) {\n CommonLogger.LOG.archiveIsolationEnabled();\n } else {\n CommonLogger.LOG.archiveIsolationDisabled();\n Set<WeldBeanDeploymentArchive> flatDeployment = new HashSet<WeldBeanDeploymentArchive>();\n flatDeployment.add(WeldBeanDeploymentArchive.merge(bootstrap, beanDeploymentArchives));\n beanDeploymentArchives = flatDeployment;\n }\n\n for (BeanDeploymentArchive archive : beanDeploymentArchives) {\n archive.getServices().add(EEModuleDescriptor.class, eeModule);\n }\n\n CDI11Deployment deployment = new WeldDeployment(resourceLoader, bootstrap, beanDeploymentArchives, extensions) {\n @Override\n protected WeldBeanDeploymentArchive createAdditionalBeanDeploymentArchive() {\n WeldBeanDeploymentArchive archive = super.createAdditionalBeanDeploymentArchive();\n archive.getServices().add(EEModuleDescriptor.class, eeModule);\n return archive;\n }\n };\n\n if (strategy.getClassFileServices() != null) {\n deployment.getServices().add(ClassFileServices.class, strategy.getClassFileServices());\n }\n return deployment;\n }", "@Nullable\n @VisibleForTesting\n protected PolygonSymbolizer createPolygonSymbolizer(final PJsonObject styleJson) {\n if (this.allowNullSymbolizer && !styleJson.has(JSON_FILL_COLOR)) {\n return null;\n }\n\n final PolygonSymbolizer symbolizer = this.styleBuilder.createPolygonSymbolizer();\n symbolizer.setFill(createFill(styleJson));\n\n symbolizer.setStroke(createStroke(styleJson, false));\n\n return symbolizer;\n }", "public static Status from(Set<ServiceReference> serviceReferencesBound, Set<ServiceReference> serviceReferencesHandled) {\n if (serviceReferencesBound == null && serviceReferencesHandled == null) {\n throw new IllegalArgumentException(\"Cannot create a status with serviceReferencesBound == null\" +\n \"and serviceReferencesHandled == null\");\n } else if (serviceReferencesBound == null) {\n throw new IllegalArgumentException(\"Cannot create a status with serviceReferencesBound == null\");\n } else if (serviceReferencesHandled == null) {\n throw new IllegalArgumentException(\"Cannot create a status with serviceReferencesHandled == null\");\n }\n return new Status(serviceReferencesBound, serviceReferencesHandled);\n }", "public static void showChannels(Object... channels){\r\n // TODO this could share more code with the other show/hide(Only)Channels methods\r\n for(LogRecordHandler handler : handlers){\r\n if(handler instanceof VisibilityHandler){\r\n VisibilityHandler visHandler = (VisibilityHandler) handler;\r\n for (Object channel : channels) {\r\n visHandler.alsoShow(channel);\r\n }\r\n }\r\n }\r\n }", "public void setProjectionMatrix(float x1, float y1, float z1, float w1,\n float x2, float y2, float z2, float w2, float x3, float y3,\n float z3, float w3, float x4, float y4, float z4, float w4) {\n NativeCustomCamera.setProjectionMatrix(getNative(), x1, y1, z1, w1, x2,\n y2, z2, w2, x3, y3, z3, w3, x4, y4, z4, w4);\n }", "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 }" ]
Check whether the media seems to have changed since a saved version of it was used. We ignore changes in free space because those probably just reflect history entries being added. @param originalMedia the media details when information about it was saved @return true if there have been detectable significant changes to the media since it was saved @throws IllegalArgumentException if the {@link #hashKey()} values of the media detail objects differ
[ "public boolean hasChanged(MediaDetails originalMedia) {\n if (!hashKey().equals(originalMedia.hashKey())) {\n throw new IllegalArgumentException(\"Can't compare media details with different hashKey values\");\n }\n return playlistCount != originalMedia.playlistCount || trackCount != originalMedia.trackCount;\n }" ]
[ "static void endInitialization(WeldContainer container, boolean isShutdownHookEnabled) {\n container.complete();\n // If needed, register one shutdown hook for all containers\n if (shutdownHook == null && isShutdownHookEnabled) {\n synchronized (LOCK) {\n if (shutdownHook == null) {\n shutdownHook = new ShutdownHook();\n SecurityActions.addShutdownHook(shutdownHook);\n }\n }\n }\n container.fireContainerInitializedEvent();\n }", "public DbArtifact getArtifact(final String gavc) {\n final DbArtifact artifact = repositoryHandler.getArtifact(gavc);\n\n if(artifact == null){\n throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)\n .entity(\"Artifact \" + gavc + \" does not exist.\").build());\n }\n\n return artifact;\n }", "public static int findLastIndexOf(Object self, int startIndex, Closure closure) {\n int result = -1;\n int i = 0;\n BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);\n for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); i++) {\n Object value = iter.next();\n if (i < startIndex) {\n continue;\n }\n if (bcw.call(value)) {\n result = i;\n }\n }\n return result;\n }", "static void export(String path, String queueName, DbConn cnx) throws JqmXmlException\n {\n // Argument tests\n if (queueName == null)\n {\n throw new IllegalArgumentException(\"queue name cannot be null\");\n }\n if (cnx == null)\n {\n throw new IllegalArgumentException(\"database connection cannot be null\");\n }\n Queue q = CommonXml.findQueue(queueName, cnx);\n if (q == null)\n {\n throw new IllegalArgumentException(\"there is no queue named \" + queueName);\n }\n\n List<Queue> l = new ArrayList<>();\n l.add(q);\n export(path, l, cnx);\n }", "private String parameter(Options opt, Parameter p[]) {\n\tStringBuilder par = new StringBuilder(1000);\n\tfor (int i = 0; i < p.length; i++) {\n\t par.append(p[i].name() + typeAnnotation(opt, p[i].type()));\n\t if (i + 1 < p.length)\n\t\tpar.append(\", \");\n\t}\n\treturn par.toString();\n }", "public static ComplexNumber Multiply(ComplexNumber z1, double scalar) {\r\n return new ComplexNumber(z1.real * scalar, z1.imaginary * scalar);\r\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 }", "public static int cudnnConvolutionBackwardBias(\n cudnnHandle handle, \n Pointer alpha, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n Pointer beta, \n cudnnTensorDescriptor dbDesc, \n Pointer db)\n {\n return checkResult(cudnnConvolutionBackwardBiasNative(handle, alpha, dyDesc, dy, beta, dbDesc, db));\n }", "public <T> T invokeWithClientSession(int targetPlayer, ClientTask<T> task, String description)\n throws Exception {\n if (!isRunning()) {\n throw new IllegalStateException(\"ConnectionManager is not running, aborting \" + description);\n }\n\n final Client client = allocateClient(targetPlayer, description);\n try {\n return task.useClient(client);\n } finally {\n freeClient(client);\n }\n }" ]
gets the profile_name associated with a specific id
[ "public String getProfileIdFromClientId(int id) {\n return (String) sqlService.getFromTable(Constants.CLIENT_PROFILE_ID, Constants.GENERIC_ID, id, Constants.DB_TABLE_CLIENT);\n }" ]
[ "public CollectionRequest<Task> findByTag(String tag) {\n \n String path = String.format(\"/tags/%s/tasks\", tag);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }", "public static Calendar parseDividendDate(String date) {\n if (!Utils.isParseable(date)) {\n return null;\n }\n date = date.trim();\n SimpleDateFormat format = new SimpleDateFormat(Utils.getDividendDateFormat(date), Locale.US);\n format.setTimeZone(TimeZone.getTimeZone(YahooFinance.TIMEZONE));\n try {\n Calendar today = Calendar.getInstance(TimeZone.getTimeZone(YahooFinance.TIMEZONE));\n Calendar parsedDate = Calendar.getInstance(TimeZone.getTimeZone(YahooFinance.TIMEZONE));\n parsedDate.setTime(format.parse(date));\n\n if (parsedDate.get(Calendar.YEAR) == 1970) {\n // Not really clear which year the dividend date is... making a reasonable guess.\n int monthDiff = parsedDate.get(Calendar.MONTH) - today.get(Calendar.MONTH);\n int year = today.get(Calendar.YEAR);\n if (monthDiff > 6) {\n year -= 1;\n } else if (monthDiff < -6) {\n year += 1;\n }\n parsedDate.set(Calendar.YEAR, year);\n }\n\n return parsedDate;\n } catch (ParseException ex) {\n log.warn(\"Failed to parse dividend date: \" + date);\n log.debug(\"Failed to parse dividend date: \" + date, ex);\n return null;\n }\n }", "private void addTable(TableDef table)\r\n {\r\n table.setOwner(this);\r\n _tableDefs.put(table.getName(), table);\r\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}", "private ServerDetails createInitialDeployDetailsFromOldDeployDetails(ServerDetails oldDeployerDetails) {\n RepositoryConf oldDeployRepositoryConfig = oldDeployerDetails.getDeployReleaseRepository();\n RepositoryConf oldSnapshotDeployRepositoryConfig = oldDeployerDetails.getDeploySnapshotRepository();\n RepositoryConf deployReleaseRepos = oldDeployRepositoryConfig == null ? RepositoryConf.emptyRepositoryConfig : oldDeployRepositoryConfig;\n RepositoryConf deploySnapshotRepos = oldSnapshotDeployRepositoryConfig == null ? RepositoryConf.emptyRepositoryConfig : oldSnapshotDeployRepositoryConfig;\n return new ServerDetails(oldDeployerDetails.getArtifactoryName(), oldDeployerDetails.getArtifactoryUrl(),\n deployReleaseRepos, deploySnapshotRepos, null, null, null, null);\n }", "public void okResponse(String responseCode, String message) {\r\n untagged();\r\n message(OK);\r\n responseCode(responseCode);\r\n message(message);\r\n end();\r\n }", "public V put(K key, V value) {\n final int hash;\n int index;\n if (key == null) {\n hash = 0;\n index = indexOfNull();\n } else {\n hash = key.hashCode();\n index = indexOf(key, hash);\n }\n if (index >= 0) {\n index = (index<<1) + 1;\n final V old = (V)mArray[index];\n mArray[index] = value;\n return old;\n }\n\n index = ~index;\n if (mSize >= mHashes.length) {\n final int n = mSize >= (BASE_SIZE*2) ? (mSize+(mSize>>1))\n : (mSize >= BASE_SIZE ? (BASE_SIZE*2) : BASE_SIZE);\n\n final int[] ohashes = mHashes;\n final Object[] oarray = mArray;\n allocArrays(n);\n\n if (mHashes.length > 0) {\n System.arraycopy(ohashes, 0, mHashes, 0, ohashes.length);\n System.arraycopy(oarray, 0, mArray, 0, oarray.length);\n }\n\n freeArrays(ohashes, oarray, mSize);\n }\n\n if (index < mSize) {\n System.arraycopy(mHashes, index, mHashes, index + 1, mSize - index);\n System.arraycopy(mArray, index << 1, mArray, (index + 1) << 1, (mSize - index) << 1);\n }\n\n mHashes[index] = hash;\n mArray[index<<1] = key;\n mArray[(index<<1)+1] = value;\n mSize++;\n return null;\n }", "public static Property getChildAddress(final ModelNode address) {\n if (address.getType() != ModelType.LIST) {\n throw new IllegalArgumentException(\"The address type must be a list.\");\n }\n final List<Property> addressParts = address.asPropertyList();\n if (addressParts.isEmpty()) {\n throw new IllegalArgumentException(\"The address is empty.\");\n }\n return addressParts.get(addressParts.size() - 1);\n }", "public double getValue(ForwardCurve forwardCurve, double swaprateVolatility) {\n\t\tdouble[] swapTenor = new double[fixingDates.length+1];\n\t\tSystem.arraycopy(fixingDates, 0, swapTenor, 0, fixingDates.length);\n\t\tswapTenor[swapTenor.length-1] = paymentDates[paymentDates.length-1];\n\n\t\tTimeDiscretization fixTenor\t= new TimeDiscretizationFromArray(swapTenor);\n\t\tTimeDiscretization floatTenor\t= new TimeDiscretizationFromArray(swapTenor);\n\t\tdouble forwardSwapRate = Swap.getForwardSwapRate(fixTenor, floatTenor, forwardCurve);\n\t\tdouble swapAnnuity = SwapAnnuity.getSwapAnnuity(fixTenor, forwardCurve);\n\t\tdouble payoffUnit = SwapAnnuity.getSwapAnnuity(new TimeDiscretizationFromArray(swapTenor[0], swapTenor[1]), forwardCurve) / (swapTenor[1] - swapTenor[0]);\n\t\treturn AnalyticFormulas.huntKennedyCMSOptionValue(forwardSwapRate, swaprateVolatility, swapAnnuity, exerciseDate, swapTenor[swapTenor.length-1]-swapTenor[0], payoffUnit, strike) * (swapTenor[1] - swapTenor[0]);\n\t}" ]
Convert a Planner time into a Java date. 0800 @param value Planner time @return Java Date instance
[ "private Date getTime(String value) throws MPXJException\n {\n try\n {\n Number hours = m_twoDigitFormat.parse(value.substring(0, 2));\n Number minutes = m_twoDigitFormat.parse(value.substring(2, 4));\n\n Calendar cal = DateHelper.popCalendar();\n cal.set(Calendar.HOUR_OF_DAY, hours.intValue());\n cal.set(Calendar.MINUTE, minutes.intValue());\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MILLISECOND, 0);\n Date result = cal.getTime();\n DateHelper.pushCalendar(cal);\n \n return result;\n }\n\n catch (ParseException ex)\n {\n throw new MPXJException(\"Failed to parse time \" + value, ex);\n }\n }" ]
[ "public static boolean any(Object self, Closure closure) {\n BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);\n for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {\n if (bcw.call(iter.next())) return true;\n }\n return false;\n }", "private void readCollectionElement(\n\t\tfinal Object optionalOwner,\n\t\tfinal Serializable optionalKey,\n\t\tfinal CollectionPersister persister,\n\t\tfinal CollectionAliases descriptor,\n\t\tfinal ResultSet rs,\n\t\tfinal SharedSessionContractImplementor session)\n\t\t\t\tthrows HibernateException, SQLException {\n\n\t\tfinal PersistenceContext persistenceContext = session.getPersistenceContext();\n\n\t\t//implement persister.readKey using the grid type (later)\n\t\tfinal Serializable collectionRowKey = (Serializable) persister.readKey(\n\t\t\t\trs,\n\t\t\t\tdescriptor.getSuffixedKeyAliases(),\n\t\t\t\tsession\n\t\t);\n\n\t\tif ( collectionRowKey != null ) {\n\t\t\t// we found a collection element in the result set\n\n\t\t\tif ( log.isDebugEnabled() ) {\n\t\t\t\tlog.debug(\n\t\t\t\t\t\t\"found row of collection: \" +\n\t\t\t\t\t\tMessageHelper.collectionInfoString( persister, collectionRowKey, getFactory() )\n\t\t\t\t\t);\n\t\t\t}\n\n\t\t\tObject owner = optionalOwner;\n\t\t\tif ( owner == null ) {\n\t\t\t\towner = persistenceContext.getCollectionOwner( collectionRowKey, persister );\n\t\t\t\tif ( owner == null ) {\n\t\t\t\t\t//TODO: This is assertion is disabled because there is a bug that means the\n\t\t\t\t\t//\t original owner of a transient, uninitialized collection is not known\n\t\t\t\t\t//\t if the collection is re-referenced by a different object associated\n\t\t\t\t\t//\t with the current Session\n\t\t\t\t\t//throw new AssertionFailure(\"bug loading unowned collection\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tPersistentCollection rowCollection = persistenceContext.getLoadContexts()\n\t\t\t\t\t.getCollectionLoadContext( rs )\n\t\t\t\t\t.getLoadingCollection( persister, collectionRowKey );\n\n\t\t\tif ( rowCollection != null ) {\n\t\t\t\thydrateRowCollection( persister, descriptor, rs, owner, rowCollection );\n\t\t\t}\n\n\t\t}\n\t\telse if ( optionalKey != null ) {\n\t\t\t// we did not find a collection element in the result set, so we\n\t\t\t// ensure that a collection is created with the owner's identifier,\n\t\t\t// since what we have is an empty collection\n\n\t\t\tif ( log.isDebugEnabled() ) {\n\t\t\t\tlog.debug(\n\t\t\t\t\t\t\"result set contains (possibly empty) collection: \" +\n\t\t\t\t\t\tMessageHelper.collectionInfoString( persister, optionalKey, getFactory() )\n\t\t\t\t\t);\n\t\t\t}\n\n\t\t\tpersistenceContext.getLoadContexts()\n\t\t\t\t\t.getCollectionLoadContext( rs )\n\t\t\t\t\t.getLoadingCollection( persister, optionalKey ); // handle empty collection\n\n\t\t}\n\n\t\t// else no collection element, but also no owner\n\n\t}", "public static DatabaseFieldConfig fromReader(BufferedReader reader) throws SQLException {\n\t\tDatabaseFieldConfig config = new DatabaseFieldConfig();\n\t\tboolean anything = false;\n\t\twhile (true) {\n\t\t\tString line;\n\t\t\ttry {\n\t\t\t\tline = reader.readLine();\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow SqlExceptionUtil.create(\"Could not read DatabaseFieldConfig from stream\", e);\n\t\t\t}\n\t\t\tif (line == null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// we do this so we can support multiple class configs per file\n\t\t\tif (line.equals(CONFIG_FILE_END_MARKER)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// skip empty lines or comments\n\t\t\tif (line.length() == 0 || line.startsWith(\"#\") || line.equals(CONFIG_FILE_START_MARKER)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tString[] parts = line.split(\"=\", -2);\n\t\t\tif (parts.length != 2) {\n\t\t\t\tthrow new SQLException(\"DatabaseFieldConfig reading from stream cannot parse line: \" + line);\n\t\t\t}\n\t\t\treadField(config, parts[0], parts[1]);\n\t\t\tanything = true;\n\t\t}\n\t\t// if we got any config lines then we return the config\n\t\tif (anything) {\n\t\t\treturn config;\n\t\t} else {\n\t\t\t// otherwise we return null for none\n\t\t\treturn null;\n\t\t}\n\t}", "public static void Backward(double[] data) {\n\n double[] result = new double[data.length];\n double sum;\n double scale = Math.sqrt(2.0 / data.length);\n for (int t = 0; t < data.length; t++) {\n sum = 0;\n for (int j = 0; j < data.length; j++) {\n double cos = Math.cos(((2 * t + 1) * j * Math.PI) / (2 * data.length));\n sum += alpha(j) * data[j] * cos;\n }\n result[t] = scale * sum;\n }\n for (int i = 0; i < data.length; i++) {\n data[i] = result[i];\n }\n }", "private JarFile loadJar(File archive) throws DecompilationException\n {\n try\n {\n return new JarFile(archive);\n }\n catch (IOException ex)\n {\n throw new DecompilationException(\"Can't load .jar: \" + archive.getPath(), ex);\n }\n }", "private static String getJsonFromRaw(Context context, int resource) {\n String json;\n try {\n InputStream inputStream = context.getResources().openRawResource(resource);\n int size = inputStream.available();\n byte[] buffer = new byte[size];\n inputStream.read(buffer);\n inputStream.close();\n json = new String(buffer, \"UTF-8\");\n } catch (IOException ex) {\n ex.printStackTrace();\n return null;\n }\n return json;\n }", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void pushNotificationViewedEvent(Bundle extras){\n\n if (extras == null || extras.isEmpty() || extras.get(Constants.NOTIFICATION_TAG) == null) {\n getConfigLogger().debug(getAccountId(), \"Push notification: \" + (extras == null ? \"NULL\" : extras.toString()) + \" not from CleverTap - will not process Notification Viewed event.\");\n return;\n }\n\n if (!extras.containsKey(Constants.NOTIFICATION_ID_TAG) || (extras.getString(Constants.NOTIFICATION_ID_TAG) == null)) {\n getConfigLogger().debug(getAccountId(), \"Push notification ID Tag is null, not processing Notification Viewed event for: \" + extras.toString());\n return;\n }\n\n // Check for dupe notification views; if same notficationdId within specified time interval (2 secs) don't process\n boolean isDuplicate = checkDuplicateNotificationIds(extras, notificationViewedIdTagMap, Constants.NOTIFICATION_VIEWED_ID_TAG_INTERVAL);\n if (isDuplicate) {\n getConfigLogger().debug(getAccountId(), \"Already processed Notification Viewed event for \" + extras.toString() + \", dropping duplicate.\");\n return;\n }\n\n JSONObject event = new JSONObject();\n try {\n JSONObject notif = getWzrkFields(extras);\n event.put(\"evtName\", Constants.NOTIFICATION_VIEWED_EVENT_NAME);\n event.put(\"evtData\", notif);\n } catch (Throwable ignored) {\n //no-op\n }\n queueEvent(context, event, Constants.RAISED_EVENT);\n }", "public static void validateClusterZonesSame(final Cluster lhs, final Cluster rhs) {\n Set<Zone> lhsSet = new HashSet<Zone>(lhs.getZones());\n Set<Zone> rhsSet = new HashSet<Zone>(rhs.getZones());\n if(!lhsSet.equals(rhsSet))\n throw new VoldemortException(\"Zones are not the same [ lhs cluster zones (\"\n + lhs.getZones() + \") not equal to rhs cluster zones (\"\n + rhs.getZones() + \") ]\");\n }", "public void startTask(int id, String taskName) {\n if (isActivated) {\n durations.add(new Duration(id, taskName, BenchmarkUtil.elapsedRealTimeNanos()));\n }\n }" ]
This method is provided to allow an absolute period of time represented by start and end dates into a duration in working days based on this calendar instance. This method takes account of any exceptions defined for this calendar. @param startDate start of the period @param endDate end of the period @return new Duration object
[ "public Duration getDuration(Date startDate, Date endDate)\n {\n Calendar cal = DateHelper.popCalendar(startDate);\n int days = getDaysInRange(startDate, endDate);\n int duration = 0;\n Day day = Day.getInstance(cal.get(Calendar.DAY_OF_WEEK));\n\n while (days > 0)\n {\n if (isWorkingDate(cal.getTime(), day) == true)\n {\n ++duration;\n }\n\n --days;\n day = day.getNextDay();\n cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR) + 1);\n }\n DateHelper.pushCalendar(cal);\n \n return (Duration.getInstance(duration, TimeUnit.DAYS));\n }" ]
[ "public List<String> subList(final long fromIndex, final long toIndex) {\n return doWithJedis(new JedisCallable<List<String>>() {\n @Override\n public List<String> call(Jedis jedis) {\n return jedis.lrange(getKey(), fromIndex, toIndex);\n }\n });\n }", "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 void forAllProcedures(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _curClassDef.getProcedures(); it.hasNext(); )\r\n {\r\n _curProcedureDef = (ProcedureDef)it.next();\r\n generate(template);\r\n }\r\n _curProcedureDef = null;\r\n }", "public synchronized void removeAllSceneObjects() {\n final GVRCameraRig rig = getMainCameraRig();\n final GVRSceneObject head = rig.getOwnerObject();\n rig.removeAllChildren();\n\n NativeScene.removeAllSceneObjects(getNative());\n for (final GVRSceneObject child : mSceneRoot.getChildren()) {\n child.getParent().removeChildObject(child);\n }\n\n if (null != head) {\n mSceneRoot.addChildObject(head);\n }\n\n final int numControllers = getGVRContext().getInputManager().clear();\n if (numControllers > 0)\n {\n getGVRContext().getInputManager().selectController();\n }\n\n getGVRContext().runOnGlThread(new Runnable() {\n @Override\n public void run() {\n NativeScene.deleteLightsAndDepthTextureOnRenderThread(getNative());\n }\n });\n }", "public String[] parseMFString(String mfString) {\n Vector<String> strings = new Vector<String>();\n\n StringReader sr = new StringReader(mfString);\n StreamTokenizer st = new StreamTokenizer(sr);\n st.quoteChar('\"');\n st.quoteChar('\\'');\n String[] mfStrings = null;\n\n int tokenType;\n try {\n while ((tokenType = st.nextToken()) != StreamTokenizer.TT_EOF) {\n\n strings.add(st.sval);\n\n }\n } catch (IOException e) {\n\n Log.d(TAG, \"String parsing Error: \" + e);\n\n e.printStackTrace();\n }\n mfStrings = new String[strings.size()];\n for (int i = 0; i < strings.size(); i++) {\n mfStrings[i] = strings.get(i);\n }\n return mfStrings;\n }", "private void ensureFields(ClassDescriptorDef classDef, Collection fields) throws ConstraintException\r\n {\r\n boolean forceVirtual = !classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_REPOSITORY_INFO, true);\r\n\r\n for (Iterator it = fields.iterator(); it.hasNext();)\r\n {\r\n FieldDescriptorDef fieldDef = (FieldDescriptorDef)it.next();\r\n\r\n // First we check whether this field is already present in the class\r\n FieldDescriptorDef foundFieldDef = classDef.getField(fieldDef.getName());\r\n\r\n if (foundFieldDef != null)\r\n {\r\n if (isEqual(fieldDef, foundFieldDef))\r\n {\r\n if (forceVirtual)\r\n {\r\n foundFieldDef.setProperty(PropertyHelper.OJB_PROPERTY_VIRTUAL_FIELD, \"true\");\r\n }\r\n continue;\r\n }\r\n else\r\n {\r\n throw new ConstraintException(\"Cannot pull up the declaration of the required field \"+fieldDef.getName()+\r\n \" from type \"+fieldDef.getOwner().getName()+\" to basetype \"+classDef.getName()+\r\n \" because there is already a different field of the same name\");\r\n }\r\n }\r\n\r\n // perhaps a reference or collection ?\r\n if (classDef.getCollection(fieldDef.getName()) != null)\r\n {\r\n throw new ConstraintException(\"Cannot pull up the declaration of the required field \"+fieldDef.getName()+\r\n \" from type \"+fieldDef.getOwner().getName()+\" to basetype \"+classDef.getName()+\r\n \" because there is already a collection of the same name\");\r\n }\r\n if (classDef.getReference(fieldDef.getName()) != null)\r\n {\r\n throw new ConstraintException(\"Cannot pull up the declaration of the required field \"+fieldDef.getName()+\r\n \" from type \"+fieldDef.getOwner().getName()+\" to basetype \"+classDef.getName()+\r\n \" because there is already a reference of the same name\");\r\n }\r\n classDef.addFieldClone(fieldDef);\r\n classDef.getField(fieldDef.getName()).setProperty(PropertyHelper.OJB_PROPERTY_VIRTUAL_FIELD, \"true\");\r\n }\r\n }", "public static base_response flush(nitro_service client, cachecontentgroup resource) throws Exception {\n\t\tcachecontentgroup flushresource = new cachecontentgroup();\n\t\tflushresource.name = resource.name;\n\t\tflushresource.query = resource.query;\n\t\tflushresource.host = resource.host;\n\t\tflushresource.selectorvalue = resource.selectorvalue;\n\t\tflushresource.force = resource.force;\n\t\treturn flushresource.perform_operation(client,\"flush\");\n\t}", "public void setTargetBytecode(String version) {\n if (CompilerConfiguration.PRE_JDK5.equals(version) || CompilerConfiguration.POST_JDK5.equals(version)) {\n this.targetBytecode = version;\n }\n }", "public static SQLException create(String message, Throwable cause) {\n\t\tSQLException sqlException;\n\t\tif (cause instanceof SQLException) {\n\t\t\t// if the cause is another SQLException, pass alot of the SQL state\n\t\t\tsqlException = new SQLException(message, ((SQLException) cause).getSQLState());\n\t\t} else {\n\t\t\tsqlException = new SQLException(message);\n\t\t}\n\t\tsqlException.initCause(cause);\n\t\treturn sqlException;\n\t}" ]
Adds a data set with date-time value to IIM file. @param ds data set id (see constants in IIM class) @param date date to set. Null values are silently ignored. @throws SerializationException if value can't be serialized by data set's serializer @throws InvalidDataSetException if data set isn't defined
[ "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}" ]
[ "private void renderThumbnail(Video video) {\n Picasso.with(getContext()).cancelRequest(thumbnail);\n Picasso.with(getContext())\n .load(video.getThumbnail())\n .placeholder(R.drawable.placeholder)\n .into(thumbnail);\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 PropertyOrder.Builder makeOrder(String property,\n PropertyOrder.Direction direction) {\n return PropertyOrder.newBuilder()\n .setProperty(makePropertyReference(property))\n .setDirection(direction);\n }", "@Override public ProjectFile read(String accessDatabaseFileName) throws MPXJException\n {\n try\n {\n Class.forName(\"sun.jdbc.odbc.JdbcOdbcDriver\");\n String url = \"jdbc:odbc:DRIVER=Microsoft Access Driver (*.mdb);DBQ=\" + accessDatabaseFileName;\n m_connection = DriverManager.getConnection(url);\n m_projectID = Integer.valueOf(1);\n return (read());\n }\n\n catch (ClassNotFoundException ex)\n {\n throw new MPXJException(\"Failed to load JDBC driver\", ex);\n }\n\n catch (SQLException ex)\n {\n throw new MPXJException(\"Failed to create connection\", ex);\n }\n\n finally\n {\n if (m_connection != null)\n {\n try\n {\n m_connection.close();\n }\n\n catch (SQLException ex)\n {\n // silently ignore exceptions when closing connection\n }\n }\n }\n }", "public ArrayList<Duration> segmentWork(ProjectCalendar projectCalendar, List<TimephasedWork> work, TimescaleUnits rangeUnits, List<DateRange> dateList)\n {\n ArrayList<Duration> result = new ArrayList<Duration>(dateList.size());\n int lastStartIndex = 0;\n\n //\n // Iterate through the list of dates range we are interested in.\n // Each date range in this list corresponds to a column\n // shown on the \"timescale\" view by MS Project\n //\n for (DateRange range : dateList)\n {\n //\n // If the current date range does not intersect with any of the\n // assignment date ranges in the list, then we show a zero\n // duration for this date range.\n //\n int startIndex = lastStartIndex == -1 ? -1 : getStartIndex(range, work, lastStartIndex);\n if (startIndex == -1)\n {\n result.add(Duration.getInstance(0, TimeUnit.HOURS));\n }\n else\n {\n //\n // We have found an assignment which intersects with the current\n // date range, call the method below to determine how\n // much time from this resource assignment can be allocated\n // to the current date range.\n //\n result.add(getRangeDuration(projectCalendar, rangeUnits, range, work, startIndex));\n lastStartIndex = startIndex;\n }\n }\n\n return result;\n }", "protected void statusInfoMessage(final String tag) {\n if(logger.isInfoEnabled()) {\n logger.info(tag + \" : [partition: \" + currentPartition + \", partitionFetched: \"\n + currentPartitionFetched\n + \"] for store \" + storageEngine.getName());\n }\n }", "private void countEntity() {\n\t\tif (!this.timer.isRunning()) {\n\t\t\tstartTimer();\n\t\t}\n\n\t\tthis.entityCount++;\n\t\tif (this.entityCount % 100 == 0) {\n\t\t\ttimer.stop();\n\t\t\tint seconds = (int) (timer.getTotalWallTime() / 1000000000);\n\t\t\tif (seconds >= this.lastSeconds + this.reportInterval) {\n\t\t\t\tthis.lastSeconds = seconds;\n\t\t\t\tprintStatus();\n\t\t\t\tif (this.timeout > 0 && seconds > this.timeout) {\n\t\t\t\t\tlogger.info(\"Timeout. Aborting processing.\");\n\t\t\t\t\tthrow new TimeoutException();\n\t\t\t\t}\n\t\t\t}\n\t\t\ttimer.start();\n\t\t}\n\t}", "public static inat get(nitro_service service, String name) throws Exception{\n\t\tinat obj = new inat();\n\t\tobj.set_name(name);\n\t\tinat response = (inat) obj.get_resource(service);\n\t\treturn response;\n\t}", "private void flushOutput() throws IOException {\n outStream.flush();\n outWriter.completeLine();\n errStream.flush();\n errWriter.completeLine();\n }" ]
Compares two sets of snaks, given by iterators. The method is optimised for short lists of snaks, as they are typically found in claims and references. @param snaks1 @param snaks2 @return true if the lists are equal
[ "protected boolean isSameSnakSet(Iterator<Snak> snaks1, Iterator<Snak> snaks2) {\n\t\tArrayList<Snak> snakList1 = new ArrayList<>(5);\n\t\twhile (snaks1.hasNext()) {\n\t\t\tsnakList1.add(snaks1.next());\n\t\t}\n\n\t\tint snakCount2 = 0;\n\t\twhile (snaks2.hasNext()) {\n\t\t\tsnakCount2++;\n\t\t\tSnak snak2 = snaks2.next();\n\t\t\tboolean found = false;\n\t\t\tfor (int i = 0; i < snakList1.size(); i++) {\n\t\t\t\tif (snak2.equals(snakList1.get(i))) {\n\t\t\t\t\tsnakList1.set(i, null);\n\t\t\t\t\tfound = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!found) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn snakCount2 == snakList1.size();\n\t}" ]
[ "@Modified(id = \"exporterServices\")\n void modifiedExporterService(ServiceReference<ExporterService> serviceReference) {\n try {\n exportersManager.modified(serviceReference);\n } catch (InvalidFilterException invalidFilterException) {\n LOG.error(\"The ServiceProperty \\\"\" + TARGET_FILTER_PROPERTY + \"\\\" of the ExporterService \"\n + bundleContext.getService(serviceReference) + \" doesn't provides a valid Filter.\"\n + \" To be used, it must provides a correct \\\"\" + TARGET_FILTER_PROPERTY + \"\\\" ServiceProperty.\",\n invalidFilterException\n );\n exportersManager.removeLinks(serviceReference);\n return;\n }\n if (exportersManager.matched(serviceReference)) {\n exportersManager.updateLinks(serviceReference);\n } else {\n exportersManager.removeLinks(serviceReference);\n }\n }", "public WebSocketContext sendToTagged(String message, String tag, boolean excludeSelf) {\n return sendToConnections(message, tag, manager.tagRegistry(), excludeSelf);\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 }", "private void readTaskCustomPropertyDefinitions(Tasks gpTasks)\n {\n for (Taskproperty definition : gpTasks.getTaskproperties().getTaskproperty())\n {\n //\n // Ignore everything but custom values\n //\n if (!\"custom\".equals(definition.getType()))\n {\n continue;\n }\n\n //\n // Find the next available field of the correct type.\n //\n String type = definition.getValuetype();\n FieldType fieldType = TASK_PROPERTY_TYPES.get(type).getField();\n\n //\n // If we have run out of fields of the right type, try using a text field.\n //\n if (fieldType == null)\n {\n fieldType = TASK_PROPERTY_TYPES.get(\"text\").getField();\n }\n\n //\n // If we actually have a field available, set the alias to match\n // the name used in GanttProject.\n //\n if (fieldType != null)\n {\n CustomField field = m_projectFile.getCustomFields().getCustomField(fieldType);\n field.setAlias(definition.getName());\n String defaultValue = definition.getDefaultvalue();\n if (defaultValue != null && defaultValue.isEmpty())\n {\n defaultValue = null;\n }\n m_taskPropertyDefinitions.put(definition.getId(), new Pair<FieldType, String>(fieldType, defaultValue));\n }\n }\n }", "public void setOutlineCode(int index, String value)\n {\n set(selectField(TaskFieldLists.CUSTOM_OUTLINE_CODE, index), value);\n }", "public Object getBean(String name) {\n\t\tBean bean = beans.get(name);\n\t\tif (null == bean) {\n\t\t\treturn null;\n\t\t}\n\t\treturn bean.object;\n\t}", "@Deprecated\n public static OptionMap create(final ExpressionResolver resolver, final ModelNode model, final OptionMap defaults) throws OperationFailedException {\n final OptionMap map = OptionMap.builder()\n .addAll(defaults)\n .set(Options.WORKER_READ_THREADS, RemotingSubsystemRootResource.WORKER_READ_THREADS.resolveModelAttribute(resolver, model).asInt())\n .set(Options.WORKER_TASK_CORE_THREADS, RemotingSubsystemRootResource.WORKER_TASK_CORE_THREADS.resolveModelAttribute(resolver, model).asInt())\n .set(Options.WORKER_TASK_KEEPALIVE, RemotingSubsystemRootResource.WORKER_TASK_KEEPALIVE.resolveModelAttribute(resolver, model).asInt())\n .set(Options.WORKER_TASK_LIMIT, RemotingSubsystemRootResource.WORKER_TASK_LIMIT.resolveModelAttribute(resolver, model).asInt())\n .set(Options.WORKER_TASK_MAX_THREADS, RemotingSubsystemRootResource.WORKER_TASK_MAX_THREADS.resolveModelAttribute(resolver, model).asInt())\n .set(Options.WORKER_WRITE_THREADS, RemotingSubsystemRootResource.WORKER_WRITE_THREADS.resolveModelAttribute(resolver, model).asInt())\n .set(Options.WORKER_READ_THREADS, RemotingSubsystemRootResource.WORKER_READ_THREADS.resolveModelAttribute(resolver, model).asInt())\n .getMap();\n return map;\n }", "public ArrayList<Double> segmentBaselineCost(ProjectFile file, List<TimephasedCost> cost, TimescaleUnits rangeUnits, ArrayList<DateRange> dateList)\n {\n return segmentCost(file.getBaselineCalendar(), cost, rangeUnits, dateList);\n }", "private void writeStringField(String fieldName, Object value) throws IOException\n {\n String val = value.toString();\n if (!val.isEmpty())\n {\n m_writer.writeNameValuePair(fieldName, val);\n }\n }" ]
Merges individual days together into time spans where the same work is undertaken each day. @param list assignment data
[ "protected void mergeSameWork(LinkedList<TimephasedWork> list)\n {\n LinkedList<TimephasedWork> result = new LinkedList<TimephasedWork>();\n\n TimephasedWork previousAssignment = null;\n for (TimephasedWork assignment : list)\n {\n if (previousAssignment == null)\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n result.add(assignment);\n }\n else\n {\n Duration previousAssignmentWork = previousAssignment.getAmountPerDay();\n Duration assignmentWork = assignment.getTotalAmount();\n\n if (NumberHelper.equals(previousAssignmentWork.getDuration(), assignmentWork.getDuration(), 0.01))\n {\n Date assignmentStart = previousAssignment.getStart();\n Date assignmentFinish = assignment.getFinish();\n double total = previousAssignment.getTotalAmount().getDuration();\n total += assignmentWork.getDuration();\n Duration totalWork = Duration.getInstance(total, TimeUnit.MINUTES);\n\n TimephasedWork merged = new TimephasedWork();\n merged.setStart(assignmentStart);\n merged.setFinish(assignmentFinish);\n merged.setAmountPerDay(assignmentWork);\n merged.setTotalAmount(totalWork);\n\n result.removeLast();\n assignment = merged;\n }\n else\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n }\n result.add(assignment);\n }\n\n previousAssignment = assignment;\n }\n\n list.clear();\n list.addAll(result);\n }" ]
[ "public byte[] getByteArrayValue(int index)\n {\n byte[] result = null;\n\n if (m_array[index] != null)\n {\n result = (byte[]) m_array[index];\n }\n\n return (result);\n }", "public void removeMapping(K key, V value) {\r\n if (treatCollectionsAsImmutable) {\r\n Collection<V> c = map.get(key);\r\n if (c != null) {\r\n Collection<V> newC = cf.newCollection();\r\n newC.addAll(c);\r\n newC.remove(value);\r\n map.put(key, newC);\r\n }\r\n\r\n } else {\r\n Collection<V> c = get(key);\r\n c.remove(value);\r\n }\r\n }", "public DynamicReportBuilder setColspan(int colNumber, int colQuantity, String colspanTitle) {\n this.setColspan(colNumber, colQuantity, colspanTitle, null);\n\n return this;\n\n }", "public static ComplexNumber Divide(ComplexNumber z1, ComplexNumber z2) {\r\n\r\n ComplexNumber conj = ComplexNumber.Conjugate(z2);\r\n\r\n double a = z1.real * conj.real + ((z1.imaginary * conj.imaginary) * -1);\r\n double b = z1.real * conj.imaginary + (z1.imaginary * conj.real);\r\n\r\n double c = z2.real * conj.real + ((z2.imaginary * conj.imaginary) * -1);\r\n\r\n return new ComplexNumber(a / c, b / c);\r\n }", "public List<MapRow> readTableConditional(Class<? extends TableReader> readerClass) throws IOException\n {\n List<MapRow> result;\n if (DatatypeConverter.getBoolean(m_stream))\n {\n result = readTable(readerClass);\n }\n else\n {\n result = Collections.emptyList();\n }\n return result;\n }", "public static void dumpClusterToFile(String outputDirName, String fileName, Cluster cluster) {\n\n if(outputDirName != null) {\n File outputDir = new File(outputDirName);\n if(!outputDir.exists()) {\n Utils.mkdirs(outputDir);\n }\n\n try {\n FileUtils.writeStringToFile(new File(outputDirName, fileName),\n new ClusterMapper().writeCluster(cluster));\n } catch(IOException e) {\n logger.error(\"IOException during dumpClusterToFile: \" + e);\n }\n }\n }", "public List<Method> getMethodsFromGroupId(int groupId, String[] filters) throws Exception {\n ArrayList<Method> methods = new ArrayList<Method>();\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_OVERRIDE +\n \" WHERE \" + Constants.OVERRIDE_GROUP_ID + \" = ?\"\n );\n statement.setInt(1, groupId);\n results = statement.executeQuery();\n while (results.next()) {\n Method method = PathOverrideService.getInstance().getMethodForOverrideId(results.getInt(\"id\"));\n if (method == null) {\n continue;\n }\n\n // decide whether or not to add this method based on the filters\n boolean add = true;\n if (filters != null) {\n add = false;\n for (String filter : filters) {\n if (method.getMethodType().endsWith(filter)) {\n add = true;\n break;\n }\n }\n }\n\n if (add && !methods.contains(method)) {\n methods.add(method);\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return methods;\n }", "public void setDates(String photoId, Date datePosted, Date dateTaken, String dateTakenGranularity) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SET_DATES);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n if (datePosted != null) {\r\n parameters.put(\"date_posted\", Long.toString(datePosted.getTime() / 1000));\r\n }\r\n\r\n if (dateTaken != null) {\r\n parameters.put(\"date_taken\", ((DateFormat) DATE_FORMATS.get()).format(dateTaken));\r\n }\r\n\r\n if (dateTakenGranularity != null) {\r\n parameters.put(\"date_taken_granularity\", dateTakenGranularity);\r\n }\r\n\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }", "public static void scaleCol( double alpha , DMatrixRMaj A , int col ) {\n int idx = col;\n for (int row = 0; row < A.numRows; row++, idx += A.numCols) {\n A.data[idx] *= alpha;\n }\n }" ]
Gets bounds which are identical for all dimensions. @param dim The number of dimensions. @param l The value of all lower bounds. @param u The value of all upper bounds. @return The new bounds.
[ "public static Bounds getSymmetricBounds(int dim, double l, double u) {\n double [] L = new double[dim];\n double [] U = new double[dim];\n for(int i=0; i<dim; i++) {\n L[i] = l;\n U[i] = u;\n }\n return new Bounds(L, U);\n }" ]
[ "public static base_response add(nitro_service client, vpnclientlessaccesspolicy resource) throws Exception {\n\t\tvpnclientlessaccesspolicy addresource = new vpnclientlessaccesspolicy();\n\t\taddresource.name = resource.name;\n\t\taddresource.rule = resource.rule;\n\t\taddresource.profilename = resource.profilename;\n\t\treturn addresource.add_resource(client);\n\t}", "private static void listAssignments(ProjectFile file)\n {\n Task task;\n Resource resource;\n String taskName;\n String resourceName;\n\n for (ResourceAssignment assignment : file.getResourceAssignments())\n {\n task = assignment.getTask();\n if (task == null)\n {\n taskName = \"(null task)\";\n }\n else\n {\n taskName = task.getName();\n }\n\n resource = assignment.getResource();\n if (resource == null)\n {\n resourceName = \"(null resource)\";\n }\n else\n {\n resourceName = resource.getName();\n }\n\n System.out.println(\"Assignment: Task=\" + taskName + \" Resource=\" + resourceName);\n if (task != null)\n {\n listTimephasedWork(assignment);\n }\n }\n\n System.out.println();\n }", "private <T> List<Class<?>> filter(List<Class<?>> enabledClasses, List<Class<?>> globallyEnabledClasses, LogMessageCallback logMessageCallback,\n BeanDeployment deployment) {\n for (Iterator<Class<?>> iterator = enabledClasses.iterator(); iterator.hasNext(); ) {\n Class<?> enabledClass = iterator.next();\n if (globallyEnabledClasses.contains(enabledClass)) {\n logMessageCallback.log(enabledClass, deployment.getBeanDeploymentArchive().getId());\n iterator.remove();\n }\n }\n return enabledClasses;\n }", "public static final boolean valueIsNotDefault(FieldType type, Object value)\n {\n boolean result = true;\n\n if (value == null)\n {\n result = false;\n }\n else\n {\n DataType dataType = type.getDataType();\n switch (dataType)\n {\n case BOOLEAN:\n {\n result = ((Boolean) value).booleanValue();\n break;\n }\n\n case CURRENCY:\n case NUMERIC:\n {\n result = !NumberHelper.equals(((Number) value).doubleValue(), 0.0, 0.00001);\n break;\n }\n\n case DURATION:\n {\n result = (((Duration) value).getDuration() != 0);\n break;\n }\n\n default:\n {\n break;\n }\n }\n }\n\n return result;\n }", "public static boolean isIdentity(DMatrix a , double tol )\n {\n for( int i = 0; i < a.getNumRows(); i++ ) {\n for( int j = 0; j < a.getNumCols(); j++ ) {\n if( i == j ) {\n if( Math.abs(a.get(i,j)-1.0) > tol )\n return false;\n } else {\n if( Math.abs(a.get(i,j)) > tol )\n return false;\n }\n }\n }\n return true;\n }", "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 void setSeriesEndDate(Date date) {\r\n\r\n if (!Objects.equals(m_model.getSeriesEndDate(), date)) {\r\n m_model.setSeriesEndDate(date);\r\n valueChanged();\r\n }\r\n\r\n }", "public static void addStory(File caseManager, String storyName,\n String testPath, String user, String feature, String benefit) throws BeastException {\n FileWriter caseManagerWriter;\n\n String storyClass = SystemReader.createClassName(storyName);\n try {\n BufferedReader reader = new BufferedReader(new FileReader(\n caseManager));\n String targetLine1 = \" public void \"\n + MASReader.createFirstLowCaseName(storyName) + \"() {\";\n String targetLine2 = \" Result result = JUnitCore.runClasses(\" + testPath + \".\"\n + storyClass + \".class);\";\n String in;\n while ((in = reader.readLine()) != null) {\n if (in.equals(targetLine1)) {\n while ((in = reader.readLine()) != null) {\n if (in.equals(targetLine2)) {\n reader.close();\n // This test is already written in the case manager.\n return;\n }\n }\n reader.close();\n throw new BeastException(\"Two different stories with the same name (same method name) are being created in the same CaseManager file. That is not possible. Please, change the name of the story: \" + testPath + \".\"\n + storyClass + \".java\");\n }\n }\n reader.close();\n caseManagerWriter = new FileWriter(caseManager, true);\n caseManagerWriter.write(\" /**\\n\");\n caseManagerWriter.write(\" * This is the story: \" + storyName\n + \"\\n\");\n caseManagerWriter.write(\" * requested by: \" + user + \"\\n\");\n caseManagerWriter.write(\" * providing the feature: \" + feature\n + \"\\n\");\n caseManagerWriter.write(\" * so the user gets the benefit: \"\n + benefit + \"\\n\");\n caseManagerWriter.write(\" */\\n\");\n caseManagerWriter.write(\" @Test\\n\");\n caseManagerWriter.write(\" public void \"\n + MASReader.createFirstLowCaseName(storyName) + \"() {\\n\");\n caseManagerWriter.write(\" Result result = JUnitCore.runClasses(\" + testPath\n + \".\" + storyClass + \".class);\\n\");\n caseManagerWriter.write(\" Assert.assertTrue(result.wasSuccessful());\\n\");\n caseManagerWriter.write(\" }\\n\");\n caseManagerWriter.write(\"\\n\");\n caseManagerWriter.flush();\n caseManagerWriter.close();\n } catch (IOException e) {\n Logger logger = Logger.getLogger(\"CreateMASCaseManager.createTest\");\n logger.info(\"ERROR writing the file\");\n }\n\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<CopticDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<CopticDate>) super.localDateTime(temporal);\n }" ]
Creates a real valued diagonal matrix of the specified type
[ "public static SimpleMatrix diag( Class type, double ...vals ) {\n SimpleMatrix M = new SimpleMatrix(vals.length,vals.length,type);\n for (int i = 0; i < vals.length; i++) {\n M.set(i,i,vals[i]);\n }\n return M;\n }" ]
[ "public String toUriString(final java.net.URI uri) {\n return this.toUriString(URI.createURI(uri.normalize().toString()));\n }", "protected SingleBusLocatorRegistrar getRegistrar(Bus bus) {\n SingleBusLocatorRegistrar registrar = busRegistrars.get(bus);\n if (registrar == null) {\n check(locatorClient, \"serviceLocator\", \"registerService\");\n registrar = new SingleBusLocatorRegistrar(bus);\n registrar.setServiceLocator(locatorClient);\n registrar.setEndpointPrefix(endpointPrefix);\n Map<String, String> endpointPrefixes = new HashMap<String, String>();\n endpointPrefixes.put(\"HTTP\", endpointPrefixHttp);\n endpointPrefixes.put(\"HTTPS\", endpointPrefixHttps);\n registrar.setEndpointPrefixes(endpointPrefixes);\n busRegistrars.put(bus, registrar);\n addLifeCycleListener(bus);\n }\n return registrar;\n }", "public boolean setUpCameraForVrMode(final int fpsMode) {\n\n cameraSetUpStatus = false;\n this.fpsMode = fpsMode;\n\n if (!isCameraOpen) {\n Log.e(TAG, \"Camera is not open\");\n return false;\n }\n if (fpsMode < 0 || fpsMode > 2) {\n Log.e(TAG,\n \"Invalid fpsMode: %d. It can only take values 0, 1, or 2.\", fpsMode);\n } else {\n Parameters params = camera.getParameters();\n\n // check if the device supports vr mode preview\n if (\"true\".equalsIgnoreCase(params.get(\"vrmode-supported\"))) {\n\n Log.v(TAG, \"VR Mode supported!\");\n\n // set vr mode\n params.set(\"vrmode\", 1);\n\n // true if the apps intend to record videos using\n // MediaRecorder\n params.setRecordingHint(true);\n\n // set preview size\n // params.setPreviewSize(640, 480);\n\n // set fast-fps-mode: 0 for 30fps, 1 for 60 fps,\n // 2 for 120 fps\n params.set(\"fast-fps-mode\", fpsMode);\n\n switch (fpsMode) {\n case 0: // 30 fps\n params.setPreviewFpsRange(30000, 30000);\n break;\n case 1: // 60 fps\n params.setPreviewFpsRange(60000, 60000);\n break;\n case 2: // 120 fps\n params.setPreviewFpsRange(120000, 120000);\n break;\n default:\n }\n\n // for auto focus\n params.set(\"focus-mode\", \"continuous-video\");\n\n params.setVideoStabilization(false);\n if (\"true\".equalsIgnoreCase(params.get(\"ois-supported\"))) {\n params.set(\"ois\", \"center\");\n }\n\n camera.setParameters(params);\n cameraSetUpStatus = true;\n }\n }\n\n return cameraSetUpStatus;\n }", "public void stop() {\n if (accelerometer != null) {\n queue.clear();\n sensorManager.unregisterListener(this, accelerometer);\n sensorManager = null;\n accelerometer = null;\n }\n }", "public void fireAssignmentWrittenEvent(ResourceAssignment resourceAssignment)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.assignmentWritten(resourceAssignment);\n }\n }\n }", "public Mapping<T> addFields() {\n\n if (idColumn == null) {\n throw new RuntimeException(\"Map ID column before adding class fields\");\n }\n\n for (Field f : ReflectionUtils.getDeclaredFieldsInHierarchy(clazz)) {\n if (!Modifier.isStatic(f.getModifiers())\n && !isFieldMapped(f.getName())\n && !ignoredFields.contains(f.getName())) {\n addColumn(f.getName());\n }\n }\n\n return this;\n }", "public void setKnotType(int n, int type) {\n\t\tknotTypes[n] = (byte)((knotTypes[n] & ~COLOR_MASK) | type);\n\t\trebuildGradient();\n\t}", "public static nsrpcnode get(nitro_service service, String ipaddress) throws Exception{\n\t\tnsrpcnode obj = new nsrpcnode();\n\t\tobj.set_ipaddress(ipaddress);\n\t\tnsrpcnode response = (nsrpcnode) obj.get_resource(service);\n\t\treturn response;\n\t}", "public ParallelTaskBuilder prepareHttpDelete(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n\n cb.getHttpMeta().setHttpMethod(HttpMethod.DELETE);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\n }" ]
Classify the contents of a file. @param filename Contains the sentence(s) to be classified. @return {@link List} of classified List of IN.
[ "public List<List<IN>> classifyFile(String filename) {\r\n ObjectBank<List<IN>> documents =\r\n makeObjectBankFromFile(filename, plainTextReaderAndWriter);\r\n List<List<IN>> result = new ArrayList<List<IN>>();\r\n\r\n for (List<IN> document : documents) {\r\n // System.err.println(document);\r\n classify(document);\r\n\r\n List<IN> sentence = new ArrayList<IN>();\r\n for (IN wi : document) {\r\n sentence.add(wi);\r\n // System.err.println(wi);\r\n }\r\n result.add(sentence);\r\n }\r\n return result;\r\n }" ]
[ "private void updateDurationTimeUnit(FastTrackColumn column)\n {\n if (m_durationTimeUnit == null && isDurationColumn(column))\n {\n int value = ((DurationColumn) column).getTimeUnitValue();\n if (value != 1)\n {\n m_durationTimeUnit = FastTrackUtility.getTimeUnit(value);\n }\n }\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 }", "private void init(final List<DbLicense> licenses) {\n licensesRegexp.clear();\n\n for (final DbLicense license : licenses) {\n if (license.getRegexp() == null ||\n license.getRegexp().isEmpty()) {\n licensesRegexp.put(license.getName(), license);\n } else {\n licensesRegexp.put(license.getRegexp(), license);\n }\n }\n }", "public ItemRequest<Webhook> deleteById(String webhook) {\n \n String path = String.format(\"/webhooks/%s\", webhook);\n return new ItemRequest<Webhook>(this, Webhook.class, path, \"DELETE\");\n }", "public void stop()\n {\n if (mAudioListener != null)\n {\n Log.d(\"SOUND\", \"stopping audio source %d %s\", getSourceId(), getSoundFile());\n mAudioListener.getAudioEngine().stopSound(getSourceId());\n }\n }", "public void mark() {\n final long currentTimeMillis = clock.currentTimeMillis();\n\n synchronized (queue) {\n if (queue.size() == capacity) {\n /*\n * we're all filled up already, let's dequeue the oldest\n * timestamp to make room for this new one.\n */\n queue.removeFirst();\n }\n queue.addLast(currentTimeMillis);\n }\n }", "@GwtIncompatible(\"Class.getDeclaredFields\")\n\tpublic ToStringBuilder addAllFields() {\n\t\tList<Field> fields = getAllDeclaredFields(instance.getClass());\n\t\tfor(Field field : fields) {\n\t\t\taddField(field);\n\t\t}\n\t\treturn this;\n\t}", "public final void unregisterView(final View view) {\n mActivity.runOnUiThread(new Runnable() {\n @Override\n public void run() {\n if (null != mRenderableViewGroup && view.getParent() == mRenderableViewGroup) {\n mRenderableViewGroup.removeView(view);\n }\n }\n });\n }", "public void addForeignkey(String relationName, String remoteTable, List localColumns, List remoteColumns)\r\n {\r\n ForeignkeyDef foreignkeyDef = new ForeignkeyDef(relationName, remoteTable);\r\n\r\n // the field arrays have the same length if we already checked the constraints\r\n for (int idx = 0; idx < localColumns.size(); idx++)\r\n {\r\n foreignkeyDef.addColumnPair((String)localColumns.get(idx),\r\n (String)remoteColumns.get(idx));\r\n }\r\n\r\n // we got to determine whether this foreignkey is already present \r\n ForeignkeyDef def = null;\r\n\r\n for (Iterator it = getForeignkeys(); it.hasNext();)\r\n {\r\n def = (ForeignkeyDef)it.next();\r\n if (foreignkeyDef.equals(def))\r\n {\r\n return;\r\n }\r\n }\r\n foreignkeyDef.setOwner(this);\r\n _foreignkeys.add(foreignkeyDef);\r\n }" ]
Get the collection of public contacts for the specified user ID. This method does not require authentication. @param userId The user ID @return The Collection of Contact objects @throws FlickrException
[ "public Collection<Contact> getPublicList(String userId) throws FlickrException {\r\n List<Contact> contacts = new ArrayList<Contact>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PUBLIC_LIST);\r\n parameters.put(\"user_id\", userId);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element contactsElement = response.getPayload();\r\n NodeList contactNodes = contactsElement.getElementsByTagName(\"contact\");\r\n for (int i = 0; i < contactNodes.getLength(); i++) {\r\n Element contactElement = (Element) contactNodes.item(i);\r\n Contact contact = new Contact();\r\n contact.setId(contactElement.getAttribute(\"nsid\"));\r\n contact.setUsername(contactElement.getAttribute(\"username\"));\r\n contact.setIgnored(\"1\".equals(contactElement.getAttribute(\"ignored\")));\r\n contact.setOnline(OnlineStatus.fromType(contactElement.getAttribute(\"online\")));\r\n contact.setIconFarm(contactElement.getAttribute(\"iconfarm\"));\r\n contact.setIconServer(contactElement.getAttribute(\"iconserver\"));\r\n if (contact.getOnline() == OnlineStatus.AWAY) {\r\n contactElement.normalize();\r\n contact.setAwayMessage(XMLUtilities.getValue(contactElement));\r\n }\r\n contacts.add(contact);\r\n }\r\n return contacts;\r\n }" ]
[ "public static base_responses delete(nitro_service client, String hostname[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (hostname != null && hostname.length > 0) {\n\t\t\tdnsaaaarec deleteresources[] = new dnsaaaarec[hostname.length];\n\t\t\tfor (int i=0;i<hostname.length;i++){\n\t\t\t\tdeleteresources[i] = new dnsaaaarec();\n\t\t\t\tdeleteresources[i].hostname = hostname[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "public static void generateOutputFile(Random rng,\n File outputFile) throws IOException\n {\n DataOutputStream dataOutput = null;\n try\n {\n dataOutput = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outputFile)));\n for (int i = 0; i < INT_COUNT; i++)\n {\n dataOutput.writeInt(rng.nextInt());\n }\n dataOutput.flush();\n }\n finally\n {\n if (dataOutput != null)\n {\n dataOutput.close();\n }\n }\n }", "public static int readInt(byte[] bytes, int offset) {\n return (((bytes[offset + 0] & 0xff) << 24) | ((bytes[offset + 1] & 0xff) << 16)\n | ((bytes[offset + 2] & 0xff) << 8) | (bytes[offset + 3] & 0xff));\n }", "protected void updateForNewConfiguration(CmsGitConfiguration gitConfig) {\n\n if (!m_checkinBean.setCurrentConfiguration(gitConfig)) {\n Notification.show(\n CmsVaadinUtils.getMessageText(Messages.GUI_GIT_CONFIGURATION_SWITCH_FAILED_0),\n CmsVaadinUtils.getMessageText(Messages.GUI_GIT_CONFIGURATION_SWITCH_FAILED_DESC_0),\n Type.ERROR_MESSAGE);\n m_configurationSelector.select(m_checkinBean.getCurrentConfiguration());\n return;\n }\n\n resetSelectableModules();\n for (final String moduleName : gitConfig.getConfiguredModules()) {\n addSelectableModule(moduleName);\n }\n updateNewModuleSelector();\n m_pullFirst.setValue(Boolean.valueOf(gitConfig.getDefaultAutoPullBefore()));\n m_pullAfterCommit.setValue(Boolean.valueOf(gitConfig.getDefaultAutoPullAfter()));\n m_addAndCommit.setValue(Boolean.valueOf(gitConfig.getDefaultAutoCommit()));\n m_pushAutomatically.setValue(Boolean.valueOf(gitConfig.getDefaultAutoPush()));\n m_commitMessage.setValue(Strings.nullToEmpty(gitConfig.getDefaultCommitMessage()));\n m_copyAndUnzip.setValue(Boolean.valueOf(gitConfig.getDefaultCopyAndUnzip()));\n m_excludeLib.setValue(Boolean.valueOf(gitConfig.getDefaultExcludeLibs()));\n m_ignoreUnclean.setValue(Boolean.valueOf(gitConfig.getDefaultIngoreUnclean()));\n m_userField.setValue(Strings.nullToEmpty(gitConfig.getDefaultGitUserName()));\n m_emailField.setValue(Strings.nullToEmpty(gitConfig.getDefaultGitUserEmail()));\n\n }", "private void processCalendars() throws SQLException\n {\n List<Row> rows = getTable(\"EXCEPTIONN\");\n Map<Integer, DayType> exceptionMap = m_reader.createExceptionTypeMap(rows);\n\n rows = getTable(\"WORK_PATTERN\");\n Map<Integer, Row> workPatternMap = m_reader.createWorkPatternMap(rows);\n\n rows = new LinkedList<Row>();// getTable(\"WORK_PATTERN_ASSIGNMENT\"); // Need to generate an example\n Map<Integer, List<Row>> workPatternAssignmentMap = m_reader.createWorkPatternAssignmentMap(rows);\n\n rows = getTable(\"EXCEPTION_ASSIGNMENT\");\n Map<Integer, List<Row>> exceptionAssignmentMap = m_reader.createExceptionAssignmentMap(rows);\n\n rows = getTable(\"TIME_ENTRY\");\n Map<Integer, List<Row>> timeEntryMap = m_reader.createTimeEntryMap(rows);\n\n rows = getTable(\"CALENDAR\");\n Collections.sort(rows, CALENDAR_COMPARATOR);\n for (Row row : rows)\n {\n m_reader.processCalendar(row, workPatternMap, workPatternAssignmentMap, exceptionAssignmentMap, timeEntryMap, exceptionMap);\n }\n\n //\n // Update unique counters at this point as we will be generating\n // resource calendars, and will need to auto generate IDs\n //\n m_reader.getProject().getProjectConfig().updateUniqueCounters();\n }", "@Override\n protected boolean changeDirection(int currentIndex, int centerIndex, boolean inBounds) {\n boolean changed = false;\n if (getGravityInternal() == Gravity.CENTER &&\n currentIndex <= centerIndex &&\n currentIndex == 0 || !inBounds) {\n\n changed = true;\n }\n return changed;\n }", "public void resetResendCount() {\n\t\tthis.resendCount = 0;\n\t\tif (this.initializationComplete)\n\t\t\tthis.nodeStage = NodeStage.NODEBUILDINFO_DONE;\n\t\tthis.lastUpdated = Calendar.getInstance().getTime();\n\t}", "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}", "public static Element getChild(Element element, String name) {\r\n return (Element) element.getElementsByTagName(name).item(0);\r\n }" ]
Use this API to fetch statistics of lbvserver_stats resource of given name .
[ "public static lbvserver_stats get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_stats obj = new lbvserver_stats();\n\t\tobj.set_name(name);\n\t\tlbvserver_stats response = (lbvserver_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}" ]
[ "public base_response enable_features(String[] features) throws Exception\n\t{\n\t\tbase_response result = null;\n\t\tnsfeature resource = new nsfeature();\n\t\tresource.set_feature(features);\n\t\toptions option = new options();\n\t\toption.set_action(\"enable\");\n\t\tresult = resource.perform_operation(this, option);\n\t\treturn result;\n\t}", "public PromotionEvaluationReport getModulePromotionReport(final String name, final String version) throws GrapesCommunicationException {\n return getModulePromotionReportRaw(name, version, false, PromotionEvaluationReport.class);\n }", "public static Pair<String, String> stringIntern(Pair<String, String> p) {\r\n return new MutableInternedPair(p);\r\n }", "public boolean shouldBeInReport(final DbDependency dependency) {\n if(dependency == null){\n return false;\n }\n if(dependency.getTarget() == null){\n return false;\n }\n if(corporateFilter != null){\n if(!decorator.getShowThirdparty() && !corporateFilter.filter(dependency)){\n return false;\n }\n if(!decorator.getShowCorporate() && corporateFilter.filter(dependency)){\n return false;\n }\n }\n\n if(!scopeHandler.filter(dependency)){\n return false;\n }\n\n return true;\n }", "private static BoxRetentionPolicyAssignment.Info createAssignment(BoxAPIConnection api, String policyID,\r\n JsonObject assignTo, JsonArray filter) {\r\n URL url = ASSIGNMENTS_URL_TEMPLATE.build(api.getBaseURL());\r\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\r\n\r\n JsonObject requestJSON = new JsonObject()\r\n .add(\"policy_id\", policyID)\r\n .add(\"assign_to\", assignTo);\r\n\r\n if (filter != null) {\r\n requestJSON.add(\"filter_fields\", filter);\r\n }\r\n\r\n request.setBody(requestJSON.toString());\r\n BoxJSONResponse response = (BoxJSONResponse) request.send();\r\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\r\n BoxRetentionPolicyAssignment createdAssignment\r\n = new BoxRetentionPolicyAssignment(api, responseJSON.get(\"id\").asString());\r\n return createdAssignment.new Info(responseJSON);\r\n }", "public static String getDateCreatedTimeRangeFilterQuery(String searchField, long startTime, long endTime) {\n\n String sStartTime = null;\n String sEndTime = null;\n\n // Convert startTime to ISO 8601 format\n if ((startTime > Long.MIN_VALUE) && (startTime < Long.MAX_VALUE)) {\n sStartTime = CmsSearchUtil.getDateAsIso8601(new Date(startTime));\n }\n\n // Convert endTime to ISO 8601 format\n if ((endTime > Long.MIN_VALUE) && (endTime < Long.MAX_VALUE)) {\n sEndTime = CmsSearchUtil.getDateAsIso8601(new Date(endTime));\n }\n\n // Build Solr range string\n final String rangeString = CmsSearchUtil.getSolrRangeString(sStartTime, sEndTime);\n\n // Build Solr filter string\n return String.format(\"%s:%s\", searchField, rangeString);\n }", "public static void cache(XmlFileModel key, Document document)\n {\n String cacheKey = getKey(key);\n map.put(cacheKey, new CacheDocument(false, document));\n }", "protected void showStep(A_CmsSetupStep step) {\n\n Window window = newWindow();\n window.setContent(step);\n window.setCaption(step.getTitle());\n A_CmsUI.get().addWindow(window);\n window.center();\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 }" ]
delete topic never used @param topic topic name @param password password @return number of partitions deleted @throws IOException if an I/O error
[ "public int deleteTopic(String topic, String password) throws IOException {\n KV<Receive, ErrorMapping> response = send(new DeleterRequest(topic, password));\n return Utils.deserializeIntArray(response.k.buffer())[0];\n }" ]
[ "@Deprecated\n\tpublic void processMostRecentDump(DumpContentType dumpContentType,\n\t\t\tMwDumpFileProcessor dumpFileProcessor) {\n\t\tMwDumpFile dumpFile = getMostRecentDump(dumpContentType);\n\t\tif (dumpFile != null) {\n\t\t\tprocessDumpFile(dumpFile, dumpFileProcessor);\n\t\t}\n\t}", "@Pure\n\tpublic static <P1, P2, P3, P4, P5> Procedure4<P2, P3, P4, P5> curry(final Procedure5<? super P1, ? super P2, ? super P3, ? super P4, ? super P5> procedure,\n\t\t\tfinal P1 argument) {\n\t\tif (procedure == null)\n\t\t\tthrow new NullPointerException(\"procedure\");\n\t\treturn new Procedure4<P2, P3, P4, P5>() {\n\t\t\t@Override\n\t\t\tpublic void apply(P2 p2, P3 p3, P4 p4, P5 p5) {\n\t\t\t\tprocedure.apply(argument, p2, p3, p4, p5);\n\t\t\t}\n\t\t};\n\t}", "public final Template getTemplate(final String name) {\n final Template template = this.templates.get(name);\n if (template != null) {\n this.accessAssertion.assertAccess(\"Configuration\", this);\n template.assertAccessible(name);\n } else {\n throw new IllegalArgumentException(String.format(\"Template '%s' does not exist. Options are: \" +\n \"%s\", name, this.templates.keySet()));\n }\n return template;\n }", "private boolean isToIgnore(CtElement element) {\n\t\tif (element instanceof CtStatementList && !(element instanceof CtCase)) {\n\t\t\tif (element.getRoleInParent() == CtRole.ELSE || element.getRoleInParent() == CtRole.THEN) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn element.isImplicit() || element instanceof CtReference;\n\t}", "public static void setIndex(Matcher matcher, int idx) {\n int count = getCount(matcher);\n if (idx < -count || idx >= count) {\n throw new IndexOutOfBoundsException(\"index is out of range \" + (-count) + \"..\" + (count - 1) + \" (index = \" + idx + \")\");\n }\n if (idx == 0) {\n matcher.reset();\n } else if (idx > 0) {\n matcher.reset();\n for (int i = 0; i < idx; i++) {\n matcher.find();\n }\n } else if (idx < 0) {\n matcher.reset();\n idx += getCount(matcher);\n for (int i = 0; i < idx; i++) {\n matcher.find();\n }\n }\n }", "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 }", "public static BufferedImage createImage(ImageProducer producer) {\n\t\tPixelGrabber pg = new PixelGrabber(producer, 0, 0, -1, -1, null, 0, 0);\n\t\ttry {\n\t\t\tpg.grabPixels();\n\t\t} catch (InterruptedException e) {\n\t\t\tthrow new RuntimeException(\"Image fetch interrupted\");\n\t\t}\n\t\tif ((pg.status() & ImageObserver.ABORT) != 0)\n\t\t\tthrow new RuntimeException(\"Image fetch aborted\");\n\t\tif ((pg.status() & ImageObserver.ERROR) != 0)\n\t\t\tthrow new RuntimeException(\"Image fetch error\");\n\t\tBufferedImage p = new BufferedImage(pg.getWidth(), pg.getHeight(), BufferedImage.TYPE_INT_ARGB);\n\t\tp.setRGB(0, 0, pg.getWidth(), pg.getHeight(), (int[])pg.getPixels(), 0, pg.getWidth());\n\t\treturn p;\n\t}", "public void takeNoteOfGradient(IntDoubleVector gradient) {\n gradient.iterate(new FnIntDoubleToVoid() { \n @Override\n public void call(int index, double value) {\n gradSumSquares[index] += value * value;\n assert !Double.isNaN(gradSumSquares[index]);\n }\n });\n }", "public static List<Dependency> getAllDependencies(final Module module) {\n final Set<Dependency> dependencies = new HashSet<Dependency>();\n final List<String> producedArtifacts = new ArrayList<String>();\n for(final Artifact artifact: getAllArtifacts(module)){\n producedArtifacts.add(artifact.getGavc());\n }\n\n dependencies.addAll(getAllDependencies(module, producedArtifacts));\n\n return new ArrayList<Dependency>(dependencies);\n }" ]
Mojos perform different dependency resolution, so we add dependencies for each mojo.
[ "@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 }" ]
[ "public void prettyPrint(StringBuffer sb, int indent) {\n sb.append(Log.getSpaces(indent));\n sb.append(getClass().getSimpleName());\n sb.append(\" [name=\");\n sb.append(this.getName());\n sb.append(\"]\");\n sb.append(System.lineSeparator());\n GVRRenderData rdata = getRenderData();\n GVRTransform trans = getTransform();\n\n if (rdata == null) {\n sb.append(Log.getSpaces(indent + 2));\n sb.append(\"RenderData: null\");\n sb.append(System.lineSeparator());\n } else {\n rdata.prettyPrint(sb, indent + 2);\n }\n sb.append(Log.getSpaces(indent + 2));\n sb.append(\"Transform: \"); sb.append(trans);\n sb.append(System.lineSeparator());\n\n // dump its children\n for (GVRSceneObject child : getChildren()) {\n child.prettyPrint(sb, indent + 2);\n }\n }", "private Query getQueryByCriteriaCount(QueryByCriteria aQuery)\r\n {\r\n Class searchClass = aQuery.getSearchClass();\r\n ReportQueryByCriteria countQuery = null;\r\n Criteria countCrit = null;\r\n String[] columns = new String[1];\r\n\r\n // BRJ: copied Criteria without groupby, orderby, and prefetched relationships\r\n if (aQuery.getCriteria() != null)\r\n {\r\n countCrit = aQuery.getCriteria().copy(false, false, false);\r\n }\r\n\r\n if (aQuery.isDistinct())\r\n {\r\n // BRJ: Count distinct is dbms dependent\r\n // hsql/sapdb: select count (distinct(person_id || project_id)) from person_project\r\n // mysql: select count (distinct person_id,project_id) from person_project\r\n // [tomdz]\r\n // Some databases have no support for multi-column count distinct (e.g. Derby)\r\n // Here we use a SELECT count(*) FROM (SELECT DISTINCT ...) instead \r\n //\r\n // concatenation of pk-columns is a simple way to obtain a single column\r\n // but concatenation is also dbms dependent:\r\n //\r\n // SELECT count(distinct concat(row1, row2, row3)) mysql\r\n // SELECT count(distinct (row1 || row2 || row3)) ansi\r\n // SELECT count(distinct (row1 + row2 + row3)) ms sql-server\r\n\r\n FieldDescriptor[] pkFields = m_broker.getClassDescriptor(searchClass).getPkFields();\r\n String[] keyColumns = new String[pkFields.length];\r\n\r\n if (pkFields.length > 1)\r\n {\r\n // TODO: Use ColumnName. This is a temporary solution because\r\n // we cannot yet resolve multiple columns in the same attribute.\r\n for (int idx = 0; idx < pkFields.length; idx++)\r\n {\r\n keyColumns[idx] = pkFields[idx].getColumnName();\r\n }\r\n }\r\n else\r\n {\r\n for (int idx = 0; idx < pkFields.length; idx++)\r\n {\r\n keyColumns[idx] = pkFields[idx].getAttributeName();\r\n }\r\n }\r\n // [tomdz]\r\n // TODO: Add support for databases that do not support COUNT DISTINCT over multiple columns\r\n// if (getPlatform().supportsMultiColumnCountDistinct())\r\n// {\r\n// columns[0] = \"count(distinct \" + getPlatform().concatenate(keyColumns) + \")\";\r\n// }\r\n// else\r\n// {\r\n// columns = keyColumns;\r\n// }\r\n\r\n columns[0] = \"count(distinct \" + getPlatform().concatenate(keyColumns) + \")\";\r\n }\r\n else\r\n {\r\n columns[0] = \"count(*)\";\r\n }\r\n\r\n // BRJ: we have to preserve indirection table !\r\n if (aQuery instanceof MtoNQuery)\r\n {\r\n MtoNQuery mnQuery = (MtoNQuery)aQuery;\r\n ReportQueryByMtoNCriteria mnReportQuery = new ReportQueryByMtoNCriteria(searchClass, columns, countCrit);\r\n\r\n mnReportQuery.setIndirectionTable(mnQuery.getIndirectionTable());\r\n countQuery = mnReportQuery;\r\n }\r\n else\r\n {\r\n countQuery = new ReportQueryByCriteria(searchClass, columns, countCrit);\r\n }\r\n\r\n // BRJ: we have to preserve outer-join-settings (by André Markwalder)\r\n for (Iterator outerJoinPath = aQuery.getOuterJoinPaths().iterator(); outerJoinPath.hasNext();)\r\n {\r\n String path = (String) outerJoinPath.next();\r\n\r\n if (aQuery.isPathOuterJoin(path))\r\n {\r\n countQuery.setPathOuterJoin(path);\r\n }\r\n }\r\n\r\n //BRJ: add orderBy Columns asJoinAttributes\r\n List orderBy = aQuery.getOrderBy();\r\n\r\n if ((orderBy != null) && !orderBy.isEmpty())\r\n {\r\n String[] joinAttributes = new String[orderBy.size()];\r\n\r\n for (int idx = 0; idx < orderBy.size(); idx++)\r\n {\r\n joinAttributes[idx] = ((FieldHelper)orderBy.get(idx)).name;\r\n }\r\n countQuery.setJoinAttributes(joinAttributes);\r\n }\r\n\r\n // [tomdz]\r\n // TODO:\r\n // For those databases that do not support COUNT DISTINCT over multiple columns\r\n // we wrap the normal SELECT DISTINCT that we just created, into a SELECT count(*)\r\n // For this however we need a report query that gets its data from a sub query instead\r\n // of a table (target class)\r\n// if (aQuery.isDistinct() && !getPlatform().supportsMultiColumnCountDistinct())\r\n// {\r\n// }\r\n\r\n return countQuery;\r\n }", "public BoxFile.Info commit(String digest, List<BoxFileUploadSessionPart> parts,\n Map<String, String> attributes, String ifMatch, String ifNoneMatch) {\n\n URL commitURL = this.sessionInfo.getSessionEndpoints().getCommitEndpoint();\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), commitURL, HttpMethod.POST);\n request.addHeader(HttpHeaders.DIGEST, DIGEST_HEADER_PREFIX_SHA + digest);\n request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON);\n\n if (ifMatch != null) {\n request.addHeader(HttpHeaders.IF_MATCH, ifMatch);\n }\n\n if (ifNoneMatch != null) {\n request.addHeader(HttpHeaders.IF_NONE_MATCH, ifNoneMatch);\n }\n\n //Creates the body of the request\n String body = this.getCommitBody(parts, attributes);\n request.setBody(body);\n\n BoxAPIResponse response = request.send();\n //Retry the commit operation after the given number of seconds if the HTTP response code is 202.\n if (response.getResponseCode() == 202) {\n String retryInterval = response.getHeaderField(\"retry-after\");\n if (retryInterval != null) {\n try {\n Thread.sleep(new Integer(retryInterval) * 1000);\n } catch (InterruptedException ie) {\n throw new BoxAPIException(\"Commit retry failed. \", ie);\n }\n\n return this.commit(digest, parts, attributes, ifMatch, ifNoneMatch);\n }\n }\n\n if (response instanceof BoxJSONResponse) {\n //Create the file instance from the response\n return this.getFile((BoxJSONResponse) response);\n } else {\n throw new BoxAPIException(\"Commit response content type is not application/json. The response code : \"\n + response.getResponseCode());\n }\n }", "private static void logVersionWarnings(String label1, String version1, String label2, String version2) {\n\t\tif (version1 == null) {\n\t\t\tif (version2 != null) {\n\t\t\t\twarning(null, \"Unknown version\", \" for {}, version for {} is '{}'\", new Object[] { label1, label2,\n\t\t\t\t\t\tversion2 });\n\t\t\t}\n\t\t} else {\n\t\t\tif (version2 == null) {\n\t\t\t\twarning(null, \"Unknown version\", \" for {}, version for {} is '{}'\", new Object[] { label2, label1,\n\t\t\t\t\t\tversion1 });\n\t\t\t} else if (!version1.equals(version2)) {\n\t\t\t\twarning(null, \"Mismatched versions\", \": {} is '{}', while {} is '{}'\", new Object[] { label1, version1,\n\t\t\t\t\t\tlabel2, version2 });\n\t\t\t}\n\t\t}\n\t}", "public static String frame(String imageUrl) {\n if (imageUrl == null || imageUrl.length() == 0) {\n throw new IllegalArgumentException(\"Image URL must not be blank.\");\n }\n return FILTER_FRAME + \"(\" + imageUrl + \")\";\n }", "public String getDefaultTableName()\r\n {\r\n String name = getName();\r\n int lastDotPos = name.lastIndexOf('.');\r\n int lastDollarPos = name.lastIndexOf('$');\r\n\r\n return lastDollarPos > lastDotPos ? name.substring(lastDollarPos + 1) : name.substring(lastDotPos + 1);\r\n }", "public static Document readDocumentFromString(String s) throws Exception {\r\n InputSource in = new InputSource(new StringReader(s));\r\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\r\n factory.setNamespaceAware(false);\r\n return factory.newDocumentBuilder().parse(in);\r\n }", "private boolean includeDocument(ItemDocument itemDocument) {\n\t\tfor (StatementGroup sg : itemDocument.getStatementGroups()) {\n\t\t\t// \"P19\" is \"place of birth\" on Wikidata\n\t\t\tif (!\"P19\".equals(sg.getProperty().getId())) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (Statement s : sg) {\n\t\t\t\tif (s.getMainSnak() instanceof ValueSnak) {\n\t\t\t\t\tValue v = s.getValue();\n\t\t\t\t\t// \"Q1731\" is \"Dresden\" on Wikidata\n\t\t\t\t\tif (v instanceof ItemIdValue\n\t\t\t\t\t\t\t&& \"Q1731\".equals(((ItemIdValue) v).getId())) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "public void postLicense(final License license, final String user, final String password) throws GrapesCommunicationException, AuthenticationException {\n final Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.licenseResourcePath());\n final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, license);\n\n client.destroy();\n if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){\n final String message = \"Failed to POST license\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n }" ]
Sets the left padding character for all cells in the row. @param paddingLeftChar new padding character, ignored if null @return this to allow chaining
[ "public AT_Row setPaddingLeftChar(Character paddingLeftChar) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingLeftChar(paddingLeftChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}" ]
[ "public 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 String urlEncode(String s) {\n if (s == null || s.isEmpty()) {\n return s;\n }\n\n return URL.encodeQueryString(s);\n }", "public String getAttribute(String section, String name) {\n Attributes attr = getManifest().getAttributes(section);\n return attr != null ? attr.getValue(name) : null;\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 }", "public void addRoute(String path, Class<? extends Actor> actorClass) throws RouteAlreadyMappedException {\n addRoute(new Route(path, false), actorClass);\n }", "public static int count(CharSequence self, CharSequence text) {\n int answer = 0;\n for (int idx = 0; true; idx++) {\n idx = self.toString().indexOf(text.toString(), idx);\n // break once idx goes to -1 or for case of empty string once\n // we get to the end to avoid JDK library bug (see GROOVY-5858)\n if (idx < answer) break;\n ++answer;\n }\n return answer;\n }", "public static lbmonbindings_servicegroup_binding[] get(nitro_service service, String monitorname) throws Exception{\n\t\tlbmonbindings_servicegroup_binding obj = new lbmonbindings_servicegroup_binding();\n\t\tobj.set_monitorname(monitorname);\n\t\tlbmonbindings_servicegroup_binding response[] = (lbmonbindings_servicegroup_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public AlbumArt requestArtworkFrom(final DataReference artReference, final CdjStatus.TrackType trackType) {\n ensureRunning();\n AlbumArt artwork = findArtInMemoryCaches(artReference); // First check the in-memory artwork caches.\n if (artwork == null) {\n artwork = requestArtworkInternal(artReference, trackType, false);\n }\n return artwork;\n }", "public void unlinkFK(Object targetObject, ClassDescriptor cld, ObjectReferenceDescriptor rds)\n {\n setFKField(targetObject, cld, rds, null);\n }" ]
Acquire the shared lock, with a max wait timeout to acquire. @param permit - the permit Integer for this operation. May not be {@code null}. @param timeout - the timeout scalar quantity. @param unit - see {@code TimeUnit} for quantities. @return {@code boolean} true on successful acquire. @throws InterruptedException - if the acquiring thread was interrupted. @throws IllegalArgumentException if {@code permit} is null.
[ "boolean lockSharedInterruptibly(final Integer permit, final long timeout, final TimeUnit unit) throws InterruptedException {\n if (permit == null) {\n throw new IllegalArgumentException();\n }\n return sync.tryAcquireSharedNanos(permit, unit.toNanos(timeout));\n }" ]
[ "public BoxFolder.Info restoreFolder(String folderID, 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_FOLDER_URL_TEMPLATE.build(this.api.getBaseURL(), folderID);\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 BoxFolder restoredFolder = new BoxFolder(this.api, responseJSON.get(\"id\").asString());\n return restoredFolder.new Info(responseJSON);\n }", "private void addCalendars(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (ProjectCalendar calendar : file.getCalendars())\n {\n addCalendar(parentNode, calendar);\n }\n }", "private void processColumns()\n {\n int fieldID = MPPUtility.getInt(m_data, m_headerOffset);\n m_headerOffset += 4;\n\n m_dataOffset = MPPUtility.getInt(m_data, m_headerOffset);\n m_headerOffset += 4;\n\n FieldType type = FieldTypeHelper.getInstance(fieldID);\n if (type.getDataType() != null)\n {\n processKnownType(type);\n }\n }", "public double d(double x){\n\t\tint intervalNumber =getIntervalNumber(x);\n\t\tif (intervalNumber==0 || intervalNumber==points.length) {\n\t\t\treturn x;\n\t\t}\n\t\treturn getIntervalReferencePoint(intervalNumber-1);\n\t}", "public Iterator<?> getElements(Filter filter, int offset, int maxResultSize) throws LayerException {\n\t\tif (null == filter) {\n\t\t\tfilter = Filter.INCLUDE;\n\t\t}\n\t\tList<Object> filteredList = new ArrayList<Object>();\n\t\ttry {\n\t\t\tsynchronized (featuresById) {\n\t\t\t\tfor (Object feature : featuresById.values()) {\n\t\t\t\t\tif (filter.evaluate(feature)) {\n\t\t\t\t\t\tfilteredList.add(feature);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (Exception e) { // NOSONAR\n\t\t\tthrow new LayerException(e, ExceptionCode.FILTER_EVALUATION_PROBLEM, filter, getId());\n\t\t}\n\t\t// Sorting of elements.\n\t\tif (comparator != null) {\n\t\t\tCollections.sort(filteredList, comparator);\n\t\t}\n\t\tif (maxResultSize > 0) {\n\t\t\tint fromIndex = Math.max(0, offset);\n\t\t\tint toIndex = Math.min(offset + maxResultSize, filteredList.size());\n\t\t\ttoIndex = Math.max(fromIndex, toIndex);\n\t\t\treturn filteredList.subList(fromIndex, toIndex).iterator();\n\t\t} else {\n\t\t\treturn filteredList.iterator();\n\t\t}\n\t}", "public static Properties loadProps(String filename) {\n Properties props = new Properties();\n FileInputStream fis = null;\n try {\n fis = new FileInputStream(filename);\n props.load(fis);\n return props;\n } catch (IOException ex) {\n throw new RuntimeException(ex);\n } finally {\n Closer.closeQuietly(fis);\n }\n\n }", "public String getPublicConfigValue(String key) throws ConfigurationException {\n if (!allProps.containsKey(key)) {\n throw new UndefinedPropertyException(\"The requested config key does not exist.\");\n }\n if (restrictedConfigs.contains(key)) {\n throw new ConfigurationException(\"The requested config key is not publicly available!\");\n }\n return allProps.get(key);\n }", "public static base_responses update(nitro_service client, nsrpcnode resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsrpcnode updateresources[] = new nsrpcnode[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nsrpcnode();\n\t\t\t\tupdateresources[i].ipaddress = resources[i].ipaddress;\n\t\t\t\tupdateresources[i].password = resources[i].password;\n\t\t\t\tupdateresources[i].srcip = resources[i].srcip;\n\t\t\t\tupdateresources[i].secure = resources[i].secure;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "private boolean setAvailable(NodeStatus nodeStatus, boolean isAvailable) {\n synchronized(nodeStatus) {\n boolean previous = nodeStatus.isAvailable();\n\n nodeStatus.setAvailable(isAvailable);\n nodeStatus.setLastChecked(getConfig().getTime().getMilliseconds());\n\n return previous;\n }\n }" ]
Returns the index of the eigenvalue which has the largest magnitude. @return index of the largest magnitude eigen value.
[ "public int getIndexMax() {\n int indexMax = 0;\n double max = getEigenvalue(0).getMagnitude2();\n\n final int N = getNumberOfEigenvalues();\n for( int i = 1; i < N; i++ ) {\n double m = getEigenvalue(i).getMagnitude2();\n if( m > max ) {\n max = m;\n indexMax = i;\n }\n }\n\n return indexMax;\n }" ]
[ "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 delete(nitro_service client, String labelname) throws Exception {\n\t\tdnspolicylabel deleteresource = new dnspolicylabel();\n\t\tdeleteresource.labelname = labelname;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public void setEndType(final String value) {\r\n\r\n final EndType endType = EndType.valueOf(value);\r\n if (!endType.equals(m_model.getEndType())) {\r\n removeExceptionsOnChange(new Command() {\r\n\r\n public void execute() {\r\n\r\n switch (endType) {\r\n case SINGLE:\r\n m_model.setOccurrences(0);\r\n m_model.setSeriesEndDate(null);\r\n break;\r\n case TIMES:\r\n m_model.setOccurrences(10);\r\n m_model.setSeriesEndDate(null);\r\n break;\r\n case DATE:\r\n m_model.setOccurrences(0);\r\n m_model.setSeriesEndDate(m_model.getStart() == null ? new Date() : m_model.getStart());\r\n break;\r\n default:\r\n break;\r\n }\r\n m_model.setEndType(endType);\r\n valueChanged();\r\n }\r\n });\r\n }\r\n\r\n }", "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 }", "public OperationTransformerRegistry resolveServer(final ModelVersion mgmtVersion, final ModelNode subsystems) {\n return resolveServer(mgmtVersion, resolveVersions(subsystems));\n }", "public void execute() {\n try {\n while(true) {\n Event event = null;\n\n try {\n event = eventQueue.poll(timeout, unit);\n } catch(InterruptedException e) {\n throw new InsufficientOperationalNodesException(operation.getSimpleName()\n + \" operation interrupted!\", e);\n }\n\n if(event == null)\n throw new VoldemortException(operation.getSimpleName()\n + \" returned a null event\");\n\n if(event.equals(Event.ERROR)) {\n if(logger.isTraceEnabled())\n logger.trace(operation.getSimpleName()\n + \" request, events complete due to error\");\n\n break;\n } else if(event.equals(Event.COMPLETED)) {\n if(logger.isTraceEnabled())\n logger.trace(operation.getSimpleName() + \" request, events complete\");\n\n break;\n }\n\n Action action = eventActions.get(event);\n\n if(action == null)\n throw new IllegalStateException(\"action was null for event \" + event);\n\n if(logger.isTraceEnabled())\n logger.trace(operation.getSimpleName() + \" request, action \"\n + action.getClass().getSimpleName() + \" to handle \" + event\n + \" event\");\n\n action.execute(this);\n }\n } finally {\n finished = true;\n }\n }", "private static JSONArray parseDockers(ArrayList<Point> dockers) throws JSONException {\n if (dockers != null) {\n JSONArray dockersArray = new JSONArray();\n\n for (Point docker : dockers) {\n JSONObject dockerObject = new JSONObject();\n\n dockerObject.put(\"x\",\n docker.getX().doubleValue());\n dockerObject.put(\"y\",\n docker.getY().doubleValue());\n\n dockersArray.put(dockerObject);\n }\n\n return dockersArray;\n }\n\n return new JSONArray();\n }", "public void setDynamicValue(String attribute, String value) {\n\n if (null == m_dynamicValues) {\n m_dynamicValues = new ConcurrentHashMap<String, String>();\n }\n m_dynamicValues.put(attribute, value);\n }", "public void execute() throws IOException {\n try {\n prepare();\n\n boolean commitResult = commit();\n if (commitResult == false) {\n throw PatchLogger.ROOT_LOGGER.failedToDeleteBackup();\n }\n } catch (PrepareException pe){\n rollback();\n\n throw PatchLogger.ROOT_LOGGER.failedToDelete(pe.getPath());\n }\n\n }" ]
Checks the given class descriptor for correct row-reader setting. @param classDef The class descriptor @param checkLevel The current check level (this constraint is only checked in strict) @exception ConstraintException If the constraint has been violated
[ "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 }" ]
[ "public static void calculateLegendInformation(List<? extends BaseModel> _Models, float _StartX, float _EndX, Paint _Paint) {\n float textMargin = Utils.dpToPx(10.f);\n float lastX = _StartX;\n\n // calculate the legend label positions and check if there is enough space to display the label,\n // if not the label will not be shown\n for (BaseModel model : _Models) {\n if (!model.isIgnore()) {\n Rect textBounds = new Rect();\n RectF legendBounds = model.getLegendBounds();\n\n _Paint.getTextBounds(model.getLegendLabel(), 0, model.getLegendLabel().length(), textBounds);\n model.setTextBounds(textBounds);\n\n float centerX = legendBounds.centerX();\n float centeredTextPos = centerX - (textBounds.width() / 2);\n float textStartPos = centeredTextPos - textMargin;\n\n // check if the text is too big to fit on the screen\n if (centeredTextPos + textBounds.width() > _EndX - textMargin) {\n model.setShowLabel(false);\n } else {\n // check if the current legend label overrides the label before\n // if the label overrides the label before, the current label will not be shown.\n // If not the label will be shown and the label position is calculated\n if (textStartPos < lastX) {\n if (lastX + textMargin < legendBounds.left) {\n model.setLegendLabelPosition((int) (lastX + textMargin));\n model.setShowLabel(true);\n lastX = lastX + textMargin + textBounds.width();\n } else {\n model.setShowLabel(false);\n }\n } else {\n model.setShowLabel(true);\n model.setLegendLabelPosition((int) centeredTextPos);\n lastX = centerX + (textBounds.width() / 2);\n }\n }\n }\n }\n\n }", "protected Iterator<MACAddress> iterator(MACAddress original) {\r\n\t\tMACAddressCreator creator = getAddressCreator();\r\n\t\tboolean isSingle = !isMultiple();\r\n\t\treturn iterator(\r\n\t\t\t\tisSingle ? original : null, \r\n\t\t\t\tcreator,//using a lambda for this one results in a big performance hit\r\n\t\t\t\tisSingle ? null : segmentsIterator(),\r\n\t\t\t\tgetNetwork().getPrefixConfiguration().allPrefixedAddressesAreSubnets() ? null : getPrefixLength());\r\n\t}", "public int getIndexMin() {\n int indexMin = 0;\n double min = getEigenvalue(0).getMagnitude2();\n\n final int N = getNumberOfEigenvalues();\n for( int i = 1; i < N; i++ ) {\n double m = getEigenvalue(i).getMagnitude2();\n if( m < min ) {\n min = m;\n indexMin = i;\n }\n }\n\n return indexMin;\n }", "public void contextInitialized(ServletContextEvent event) {\n this.context = event.getServletContext();\n\n // Output a simple message to the server's console\n System.out.println(\"The Simple Web App. Is Ready\");\n\n ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(\n \"/client.xml\");\n LocatorService client = (LocatorService) context\n .getBean(\"locatorService\");\n\n String serviceHost = this.context.getInitParameter(\"serviceHost\");\n\n try {\n client.registerEndpoint(new QName(\n \"http://talend.org/esb/examples/\", \"GreeterService\"),\n serviceHost, BindingType.SOAP_11, TransportType.HTTP, null);\n } catch (InterruptedExceptionFault e) {\n e.printStackTrace();\n } catch (ServiceLocatorFault e) {\n e.printStackTrace();\n }\n }", "public static String insertDumpInformation(String pattern,\n\t\t\tString dateStamp, String project) {\n\t\tif (pattern == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn pattern.replace(\"{DATE}\", dateStamp).replace(\"{PROJECT}\",\n\t\t\t\t\tproject);\n\t\t}\n\t}", "public void setWorkingDay(Day day, boolean working)\n {\n setWorkingDay(day, (working ? DayType.WORKING : DayType.NON_WORKING));\n }", "@SuppressWarnings(\"unchecked\")\n public final FluentModelImplT withoutTag(String key) {\n if (this.inner().getTags() != null) {\n this.inner().getTags().remove(key);\n }\n return (FluentModelImplT) this;\n }", "private void writeFinalResults() {\n\t\t// Print a final report:\n\t\tprintStatus();\n\n\t\t// Store property counts in files:\n\t\twritePropertyStatisticsToFile(this.itemStatistics,\n\t\t\t\t\"item-property-counts.csv\");\n\t\twritePropertyStatisticsToFile(this.propertyStatistics,\n\t\t\t\t\"property-property-counts.csv\");\n\n\t\t// Store site link statistics in file:\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers\n\t\t\t\t\t\t.openExampleFileOuputStream(\"site-link-counts.csv\"))) {\n\n\t\t\tout.println(\"Site key,Site links\");\n\t\t\tfor (Entry<String, Integer> entry : this.siteLinkStatistics\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tout.println(entry.getKey() + \",\" + entry.getValue());\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\t// Store term statistics in file:\n\t\twriteTermStatisticsToFile(this.itemStatistics, \"item-term-counts.csv\");\n\t\twriteTermStatisticsToFile(this.propertyStatistics,\n\t\t\t\t\"property-term-counts.csv\");\n\t}", "public void setValue(float value) {\n\t\tmBarPointerPosition = Math.round((mSVToPosFactor * (1 - value))\n\t\t\t\t+ mBarPointerHaloRadius + (mBarLength / 2));\n\t\tcalculateColor(mBarPointerPosition);\n\t\tmBarPointerPaint.setColor(mColor);\n\t\t// Check whether the Saturation/Value bar is added to the ColorPicker\n\t\t// wheel\n\t\tif (mPicker != null) {\n\t\t\tmPicker.setNewCenterColor(mColor);\n\t\t\tmPicker.changeOpacityBarColor(mColor);\n\t\t}\n\t\tinvalidate();\n\t}" ]
Checks if a given number is in the range of a byte. @param number a number which should be in the range of a byte (positive or negative) @see java.lang.Byte#MIN_VALUE @see java.lang.Byte#MAX_VALUE @return number as a byte (rounding might occur)
[ "@ArgumentsChecked\n\t@Throws(IllegalNullArgumentException.class)\n\tpublic static byte checkByte(@Nonnull final Number number) {\n\t\tCheck.notNull(number, \"number\");\n\t\tif (!isInByteRange(number)) {\n\t\t\tthrow new IllegalNumberRangeException(number.toString(), BYTE_MIN, BYTE_MAX);\n\t\t}\n\n\t\treturn number.byteValue();\n\t}" ]
[ "@SuppressWarnings(\"unchecked\") public Map<String, Object> getCustomProperties()\n {\n return (Map<String, Object>) getCachedValue(ProjectField.CUSTOM_PROPERTIES);\n }", "public static Rectangle getSelectedBounds(BufferedImage p) {\n\t\tint width = p.getWidth();\n int height = p.getHeight();\n\t\tint maxX = 0, maxY = 0, minX = width, minY = height;\n\t\tboolean anySelected = false;\n\t\tint y1;\n\t\tint [] pixels = null;\n\t\t\n\t\tfor (y1 = height-1; y1 >= 0; y1--) {\n\t\t\tpixels = getRGB( p, 0, y1, width, 1, pixels );\n\t\t\tfor (int x = 0; x < minX; x++) {\n\t\t\t\tif ((pixels[x] & 0xff000000) != 0) {\n\t\t\t\t\tminX = x;\n\t\t\t\t\tmaxY = y1;\n\t\t\t\t\tanySelected = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int x = width-1; x >= maxX; x--) {\n\t\t\t\tif ((pixels[x] & 0xff000000) != 0) {\n\t\t\t\t\tmaxX = x;\n\t\t\t\t\tmaxY = y1;\n\t\t\t\t\tanySelected = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ( anySelected )\n\t\t\t\tbreak;\n\t\t}\n\t\tpixels = null;\n\t\tfor (int y = 0; y < y1; y++) {\n\t\t\tpixels = getRGB( p, 0, y, width, 1, pixels );\n\t\t\tfor (int x = 0; x < minX; x++) {\n\t\t\t\tif ((pixels[x] & 0xff000000) != 0) {\n\t\t\t\t\tminX = x;\n\t\t\t\t\tif ( y < minY )\n\t\t\t\t\t\tminY = y;\n\t\t\t\t\tanySelected = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int x = width-1; x >= maxX; x--) {\n\t\t\t\tif ((pixels[x] & 0xff000000) != 0) {\n\t\t\t\t\tmaxX = x;\n\t\t\t\t\tif ( y < minY )\n\t\t\t\t\t\tminY = y;\n\t\t\t\t\tanySelected = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif ( anySelected )\n\t\t\treturn new Rectangle( minX, minY, maxX-minX+1, maxY-minY+1 );\n\t\treturn null;\n\t}", "@DELETE\n @Path(\"/{name}\" + ServerAPI.GET_CORPORATE_GROUPIDS)\n public Response removeCorporateGroupIdPrefix(@Auth final DbCredential credential, @PathParam(\"name\") final String organizationId, final String corporateGroupId){\n LOG.info(\"Got an remove a corporate groupId prefix request for organization \" + organizationId +\".\");\n if(!credential.getRoles().contains(DbCredential.AvailableRoles.DATA_UPDATER)){\n throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).build());\n }\n\n if(corporateGroupId == null || corporateGroupId.isEmpty()){\n LOG.error(\"No corporate GroupId to remove!\");\n return Response.serverError().status(HttpStatus.BAD_REQUEST_400).build();\n }\n\n getOrganizationHandler().removeCorporateGroupId(organizationId, corporateGroupId);\n\n return Response.ok(\"done\").build();\n }", "protected final boolean isDurationValid() {\n\n if (isValidEndTypeForPattern()) {\n switch (getEndType()) {\n case DATE:\n return (getStart().getTime() < (getSeriesEndDate().getTime() + DAY_IN_MILLIS));\n case TIMES:\n return getOccurrences() > 0;\n case SINGLE:\n return true;\n default:\n return false;\n }\n } else {\n return false;\n }\n }", "public synchronized void setMonitoredPlayer(final int player) {\n if (player < 0) {\n throw new IllegalArgumentException(\"player cannot be negative\");\n }\n clearPlaybackState();\n monitoredPlayer.set(player);\n if (player > 0) { // Start monitoring the specified player\n setPlaybackState(player, 0, false); // Start with default values for required simple state.\n VirtualCdj.getInstance().addUpdateListener(updateListener);\n MetadataFinder.getInstance().addTrackMetadataListener(metadataListener);\n cueList.set(null); // Assume the worst, but see if we have one available next.\n if (MetadataFinder.getInstance().isRunning()) {\n TrackMetadata metadata = MetadataFinder.getInstance().getLatestMetadataFor(player);\n if (metadata != null) {\n cueList.set(metadata.getCueList());\n }\n }\n WaveformFinder.getInstance().addWaveformListener(waveformListener);\n if (WaveformFinder.getInstance().isRunning() && WaveformFinder.getInstance().isFindingDetails()) {\n waveform.set(WaveformFinder.getInstance().getLatestDetailFor(player));\n } else {\n waveform.set(null);\n }\n BeatGridFinder.getInstance().addBeatGridListener(beatGridListener);\n if (BeatGridFinder.getInstance().isRunning()) {\n beatGrid.set(BeatGridFinder.getInstance().getLatestBeatGridFor(player));\n } else {\n beatGrid.set(null);\n }\n try {\n TimeFinder.getInstance().start();\n if (!animating.getAndSet(true)) {\n // Create the thread to update our position smoothly as the track plays\n new Thread(new Runnable() {\n @Override\n public void run() {\n while (animating.get()) {\n try {\n Thread.sleep(33); // Animate at 30 fps\n } catch (InterruptedException e) {\n logger.warn(\"Waveform animation thread interrupted; ending\");\n animating.set(false);\n }\n setPlaybackPosition(TimeFinder.getInstance().getTimeFor(getMonitoredPlayer()));\n }\n }\n }).start();\n }\n } catch (Exception e) {\n logger.error(\"Unable to start the TimeFinder to animate the waveform detail view\");\n animating.set(false);\n }\n } else { // Stop monitoring any player\n animating.set(false);\n VirtualCdj.getInstance().removeUpdateListener(updateListener);\n MetadataFinder.getInstance().removeTrackMetadataListener(metadataListener);\n WaveformFinder.getInstance().removeWaveformListener(waveformListener);\n cueList.set(null);\n waveform.set(null);\n beatGrid.set(null);\n }\n if (!autoScroll.get()) {\n invalidate();\n }\n repaint();\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 }", "protected void initializeJdbcConnection(Connection con, JdbcConnectionDescriptor jcd)\r\n throws LookupException\r\n {\r\n try\r\n {\r\n PlatformFactory.getPlatformFor(jcd).initializeJdbcConnection(jcd, con);\r\n }\r\n catch (PlatformException e)\r\n {\r\n throw new LookupException(\"Platform dependent initialization of connection failed\", e);\r\n }\r\n }", "public float conditionalLogProb(int[] given, int of) {\r\n if (given.length != windowSize - 1) {\r\n System.err.println(\"error computing conditional log prob\");\r\n System.exit(0);\r\n }\r\n int[] label = indicesFront(given);\r\n float[] masses = new float[label.length];\r\n for (int i = 0; i < masses.length; i++) {\r\n masses[i] = table[label[i]];\r\n }\r\n float z = ArrayMath.logSum(masses);\r\n\r\n return table[indexOf(given, of)] - z;\r\n }", "protected Channel awaitChannel() throws IOException {\n Channel channel = this.channel;\n if(channel != null) {\n return channel;\n }\n synchronized (lock) {\n for(;;) {\n if(state == State.CLOSED) {\n throw ProtocolLogger.ROOT_LOGGER.channelClosed();\n }\n channel = this.channel;\n if(channel != null) {\n return channel;\n }\n if(state == State.CLOSING) {\n throw ProtocolLogger.ROOT_LOGGER.channelClosed();\n }\n try {\n lock.wait();\n } catch (InterruptedException e) {\n throw new IOException(e);\n }\n }\n }\n }" ]
Write back to hints file.
[ "@Subscribe\n public void onEnd(AggregatedQuitEvent e) {\n try {\n writeHints(hintsFile, hints);\n } catch (IOException exception) {\n outer.log(\"Could not write back the hints file.\", exception, Project.MSG_ERR);\n }\n }" ]
[ "public Column getColumn(String columnName) {\n if (columnName == null) {\n return null;\n }\n for (Column column : columns) {\n if (columnName.equals(column.getData())) {\n return column;\n }\n }\n return null;\n }", "protected void setBeanStore(BoundBeanStore beanStore) {\n if (beanStore == null) {\n this.beanStore.remove();\n } else {\n this.beanStore.set(beanStore);\n }\n }", "private void pushDeviceToken(final String token, final boolean register, final PushType type) {\n pushDeviceToken(this.context, token, register, type);\n }", "public static streamidentifier_stats get(nitro_service service, String name) throws Exception{\n\t\tstreamidentifier_stats obj = new streamidentifier_stats();\n\t\tobj.set_name(name);\n\t\tstreamidentifier_stats response = (streamidentifier_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "public PhotoList<Photo> getUntagged(int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_UNTAGGED);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", Integer.toString(perPage));\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", Integer.toString(page));\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n PhotoList<Photo> photos = PhotoUtils.createPhotoList(photosElement);\r\n return photos;\r\n }", "@SuppressWarnings(\"unchecked\") public final List<MapRow> getRows(String name)\n {\n return (List<MapRow>) getObject(name);\n }", "public static int getMpxField(int value)\n {\n int result = 0;\n\n if (value >= 0 && value < MPXJ_MPX_ARRAY.length)\n {\n result = MPXJ_MPX_ARRAY[value];\n }\n return (result);\n }", "public static List<String> getParameterNames(MethodNode node) {\r\n ArrayList<String> result = new ArrayList<String>();\r\n\r\n if (node.getParameters() != null) {\r\n for (Parameter parameter : node.getParameters()) {\r\n result.add(parameter.getName());\r\n }\r\n }\r\n return result;\r\n }", "private void resetCalendar() {\n _calendar = getCalendar();\n if (_defaultTimeZone != null) {\n _calendar.setTimeZone(_defaultTimeZone);\n }\n _currentYear = _calendar.get(Calendar.YEAR);\n }" ]
Sets the occurence. @param min the min @param max the max @throws ParseException the parse exception
[ "public void setOccurence(int min, int max) throws ParseException {\n if (!simplified) {\n if ((min < 0) || (min > max) || (max < 1)) {\n throw new ParseException(\"Illegal number {\" + min + \",\" + max + \"}\");\n }\n if (min == 0) {\n optional = true;\n }\n minimumOccurence = Math.max(1, min);\n maximumOccurence = max;\n } else {\n throw new ParseException(\"already simplified\");\n }\n }" ]
[ "public void addPropertyChangeListener (String propertyName, java.beans.PropertyChangeListener listener)\r\n {\r\n this.propertyChangeDelegate.addPropertyChangeListener(propertyName, listener);\r\n }", "boolean lockShared(final Integer permit, final long timeout, final TimeUnit unit) {\n boolean result = false;\n try {\n result = lockSharedInterruptibly(permit, timeout, unit);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n return result;\n }", "public static <T> List<T> copyOf(T[] elements) {\n Preconditions.checkNotNull(elements);\n return ofInternal(elements.clone());\n }", "public void useXopAttachmentServiceWithWebClient() throws Exception {\n\n final String serviceURI = \"http://localhost:\" + port + \"/services/attachments/xop\";\n \n JAXRSClientFactoryBean factoryBean = new JAXRSClientFactoryBean();\n factoryBean.setAddress(serviceURI);\n factoryBean.setProperties(Collections.singletonMap(org.apache.cxf.message.Message.MTOM_ENABLED, \n (Object)\"true\"));\n WebClient client = factoryBean.createWebClient();\n WebClient.getConfig(client).getRequestContext().put(\"support.type.as.multipart\", \n \"true\"); \n client.type(\"multipart/related\").accept(\"multipart/related\");\n \n XopBean xop = createXopBean();\n \n System.out.println();\n System.out.println(\"Posting a XOP attachment with a WebClient\");\n \n XopBean xopResponse = client.post(xop, XopBean.class);\n \n verifyXopResponse(xop, xopResponse);\n }", "public static KieRuntimeLogger newFileLogger(KieRuntimeEventManager session,\n String fileName) {\n return getKnowledgeRuntimeLoggerProvider().newFileLogger( session,\n fileName );\n }", "protected int _countPeriods(String str)\n {\n int commas = 0;\n for (int i = 0, end = str.length(); i < end; ++i) {\n int ch = str.charAt(i);\n if (ch < '0' || ch > '9') {\n if (ch == '.') {\n ++commas;\n } else {\n return -1;\n }\n }\n }\n return commas;\n }", "public String[] init(String[] argv, int min, int max,\n Collection<CommandLineParser.Option> options)\n throws IOException, SAXException {\n // parse command line\n parser = new CommandLineParser();\n parser.setMinimumArguments(min);\n parser.setMaximumArguments(max);\n parser.registerOption(new CommandLineParser.BooleanOption(\"reindex\", 'I'));\n if (options != null)\n for (CommandLineParser.Option option : options)\n parser.registerOption(option);\n\n try {\n argv = parser.parse(argv);\n } catch (CommandLineParser.CommandLineParserException e) {\n System.err.println(\"ERROR: \" + e.getMessage());\n usage();\n System.exit(1);\n }\n\n // do we need to reindex?\n boolean reindex = parser.getOptionState(\"reindex\");\n\n // load configuration\n config = ConfigLoader.load(argv[0]);\n database = config.getDatabase(reindex); // overwrite iff reindex\n if (database.isInMemory())\n reindex = true; // no other way to do it in this case\n\n // reindex, if requested\n if (reindex)\n reindex(config, database);\n\n return argv;\n }", "private long getTotalTime(ProjectCalendarDateRanges exception)\n {\n long total = 0;\n for (DateRange range : exception)\n {\n total += getTime(range.getStart(), range.getEnd());\n }\n return (total);\n }", "public static double elementSumSq( DMatrixD1 m ) {\n\n // minimize round off error\n double maxAbs = CommonOps_DDRM.elementMaxAbs(m);\n if( maxAbs == 0)\n return 0;\n\n double total = 0;\n \n int N = m.getNumElements();\n for( int i = 0; i < N; i++ ) {\n double d = m.data[i]/maxAbs;\n total += d*d;\n }\n\n return maxAbs*total*maxAbs;\n }" ]
Gets the data handler from event. @param event the event @return the data handler
[ "private static DataHandler getDataHandlerForString(Event event) {\n try {\n return new DataHandler(new ByteDataSource(event.getContent().getBytes(\"UTF-8\")));\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(e);\n }\n }" ]
[ "public ValueContainer[] getKeyValues(ClassDescriptor cld, Identity oid) throws PersistenceBrokerException\r\n {\r\n return getKeyValues(cld, oid, true);\r\n }", "public final void setColorPreferred(boolean preferColor) {\n if (this.preferColor.compareAndSet(!preferColor, preferColor) && isRunning()) {\n stop();\n try {\n start();\n } catch (Exception e) {\n logger.error(\"Unexplained exception restarting; we had been running already!\", e);\n }\n }\n }", "public static void configure(Job conf, SimpleConfiguration props) {\n try {\n\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n props.save(baos);\n\n conf.getConfiguration().set(PROPS_CONF_KEY,\n new String(baos.toByteArray(), StandardCharsets.UTF_8));\n\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }", "public static Command newInsertElements(Collection objects, String outIdentifier, boolean returnObject, String entryPoint) {\n return getCommandFactoryProvider().newInsertElements( objects, outIdentifier, returnObject, entryPoint );\n }", "public static double normP(DMatrixRMaj A , double p ) {\n if( p == 1 ) {\n return normP1(A);\n } else if( p == 2 ) {\n return normP2(A);\n } else if( Double.isInfinite(p)) {\n return normPInf(A);\n }\n if( MatrixFeatures_DDRM.isVector(A) ) {\n return elementP(A,p);\n } else {\n throw new IllegalArgumentException(\"Doesn't support induced norms yet.\");\n }\n }", "public OAuth1RequestToken exchangeAuthToken(String authToken) throws FlickrException {\r\n\r\n // Use TreeMap so keys are automatically sorted alphabetically\r\n Map<String, String> parameters = new TreeMap<String, String>();\r\n parameters.put(\"method\", METHOD_EXCHANGE_TOKEN);\r\n parameters.put(Flickr.API_KEY, apiKey);\r\n // This method call must be signed using Flickr (not OAuth) style signing\r\n parameters.put(\"api_sig\", getSignature(sharedSecret, parameters));\r\n\r\n Response response = transportAPI.getNonOAuth(transportAPI.getPath(), parameters);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n OAuth1RequestToken accessToken = constructToken(response);\r\n\r\n return accessToken;\r\n }", "public Object copy(final Object obj, final PersistenceBroker broker)\r\n {\r\n return clone(obj, IdentityMapFactory.getIdentityMap(), broker);\r\n }", "public static base_response delete(nitro_service client, String viewname) throws Exception {\n\t\tdnsview deleteresource = new dnsview();\n\t\tdeleteresource.viewname = viewname;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public static double Function1D(double x, double mean, double amplitude, double position, double width, double phase, double frequency) {\n double envelope = mean + amplitude * Math.exp(-Math.pow((x - position), 2) / Math.pow((2 * width), 2));\n double carry = Math.cos(2 * Math.PI * frequency * (x - position) + phase);\n return envelope * carry;\n }" ]
Adds custom header to request @param key @param value
[ "public DownloadRequest addCustomHeader(String key, String value) {\n mCustomHeader.put(key, value);\n return this;\n }" ]
[ "private void readProjectHeader()\n {\n Table table = m_tables.get(\"DIR\");\n MapRow row = table.find(\"\");\n if (row != null)\n {\n setFields(PROJECT_FIELDS, row, m_projectFile.getProjectProperties());\n m_wbsFormat = new P3WbsFormat(row);\n }\n }", "public static synchronized void addCachedDatabaseConfigs(Collection<DatabaseTableConfig<?>> configs) {\n\t\tMap<Class<?>, DatabaseTableConfig<?>> newMap;\n\t\tif (configMap == null) {\n\t\t\tnewMap = new HashMap<Class<?>, DatabaseTableConfig<?>>();\n\t\t} else {\n\t\t\tnewMap = new HashMap<Class<?>, DatabaseTableConfig<?>>(configMap);\n\t\t}\n\t\tfor (DatabaseTableConfig<?> config : configs) {\n\t\t\tnewMap.put(config.getDataClass(), config);\n\t\t\tlogger.info(\"Loaded configuration for {}\", config.getDataClass());\n\t\t}\n\t\tconfigMap = newMap;\n\t}", "public static int checkVlen(int i) {\n int count = 0;\n if (i >= -112 && i <= 127) {\n return 1;\n } else {\n int len = -112;\n if (i < 0) {\n i ^= -1L; // take one's complement'\n len = -120;\n }\n\n long tmp = i;\n while (tmp != 0) {\n tmp = tmp >> 8;\n len--;\n }\n\n count++;\n\n len = (len < -120) ? -(len + 120) : -(len + 112);\n\n while (len != 0) {\n count++;\n len--;\n }\n\n return count;\n }\n }", "public void addForeignkey(String relationName, String remoteTable, List localColumns, List remoteColumns)\r\n {\r\n ForeignkeyDef foreignkeyDef = new ForeignkeyDef(relationName, remoteTable);\r\n\r\n // the field arrays have the same length if we already checked the constraints\r\n for (int idx = 0; idx < localColumns.size(); idx++)\r\n {\r\n foreignkeyDef.addColumnPair((String)localColumns.get(idx),\r\n (String)remoteColumns.get(idx));\r\n }\r\n\r\n // we got to determine whether this foreignkey is already present \r\n ForeignkeyDef def = null;\r\n\r\n for (Iterator it = getForeignkeys(); it.hasNext();)\r\n {\r\n def = (ForeignkeyDef)it.next();\r\n if (foreignkeyDef.equals(def))\r\n {\r\n return;\r\n }\r\n }\r\n foreignkeyDef.setOwner(this);\r\n _foreignkeys.add(foreignkeyDef);\r\n }", "public static NodeList evaluateXpathExpression(String domStr, String xpathExpr)\n\t\t\tthrows XPathExpressionException, IOException {\n\t\tDocument dom = DomUtils.asDocument(domStr);\n\t\treturn evaluateXpathExpression(dom, xpathExpr);\n\t}", "public static int[] Concatenate(int[] array, int[] array2) {\n int[] all = new int[array.length + array2.length];\n int idx = 0;\n\n //First array\n for (int i = 0; i < array.length; i++)\n all[idx++] = array[i];\n\n //Second array\n for (int i = 0; i < array2.length; i++)\n all[idx++] = array2[i];\n\n return all;\n }", "@Override\n\tpublic boolean containsPrefixBlock(int prefixLength) {\n\t\tcheckSubnet(this, prefixLength);\n\t\tint divisionCount = getDivisionCount();\n\t\tint prevBitCount = 0;\n\t\tfor(int i = 0; i < divisionCount; i++) {\n\t\t\tAddressDivision division = getDivision(i);\n\t\t\tint bitCount = division.getBitCount();\n\t\t\tint totalBitCount = bitCount + prevBitCount;\n\t\t\tif(prefixLength < totalBitCount) {\n\t\t\t\tint divPrefixLen = Math.max(0, prefixLength - prevBitCount);\n\t\t\t\tif(!division.isPrefixBlock(division.getDivisionValue(), division.getUpperDivisionValue(), divPrefixLen)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tfor(++i; i < divisionCount; i++) {\n\t\t\t\t\tdivision = getDivision(i);\n\t\t\t\t\tif(!division.isFullRange()) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tprevBitCount = totalBitCount;\n\t\t}\n\t\treturn true;\n\t}", "public static Dimension getDimension(File videoFile) throws IOException {\n try (FileInputStream fis = new FileInputStream(videoFile)) {\n return getDimension(fis, new AtomicReference<ByteBuffer>());\n }\n }", "void successfulBoot() throws ConfigurationPersistenceException {\n synchronized (this) {\n if (doneBootup.get()) {\n return;\n }\n final File copySource;\n if (!interactionPolicy.isReadOnly()) {\n copySource = mainFile;\n } else {\n\n if ( FilePersistenceUtils.isParentFolderWritable(mainFile) ) {\n copySource = new File(mainFile.getParentFile(), mainFile.getName() + \".boot\");\n } else{\n copySource = new File(configurationDir, mainFile.getName() + \".boot\");\n }\n\n FilePersistenceUtils.deleteFile(copySource);\n }\n\n try {\n if (!bootFile.equals(copySource)) {\n FilePersistenceUtils.copyFile(bootFile, copySource);\n }\n\n createHistoryDirectory();\n\n final File historyBase = new File(historyRoot, mainFile.getName());\n lastFile = addSuffixToFile(historyBase, LAST);\n final File boot = addSuffixToFile(historyBase, BOOT);\n final File initial = addSuffixToFile(historyBase, INITIAL);\n\n if (!initial.exists()) {\n FilePersistenceUtils.copyFile(copySource, initial);\n }\n\n FilePersistenceUtils.copyFile(copySource, lastFile);\n FilePersistenceUtils.copyFile(copySource, boot);\n } catch (IOException e) {\n throw ControllerLogger.ROOT_LOGGER.failedToCreateConfigurationBackup(e, bootFile);\n } finally {\n if (interactionPolicy.isReadOnly()) {\n //Delete the temporary file\n try {\n FilePersistenceUtils.deleteFile(copySource);\n } catch (Exception ignore) {\n }\n }\n }\n doneBootup.set(true);\n }\n }" ]
Sets the provided metadata on the folder, overwriting any existing metadata keys already present. @param templateName the name of the metadata template. @param scope the scope of the template (usually "global" or "enterprise"). @param metadata the new metadata values. @return the metadata returned from the server.
[ "public Metadata setMetadata(String templateName, String scope, Metadata metadata) {\n Metadata metadataValue = null;\n\n try {\n metadataValue = this.createMetadata(templateName, scope, metadata);\n } catch (BoxAPIException e) {\n if (e.getResponseCode() == 409) {\n Metadata metadataToUpdate = new Metadata(scope, templateName);\n for (JsonValue value : metadata.getOperations()) {\n if (value.asObject().get(\"value\").isNumber()) {\n metadataToUpdate.add(value.asObject().get(\"path\").asString(),\n value.asObject().get(\"value\").asFloat());\n } else if (value.asObject().get(\"value\").isString()) {\n metadataToUpdate.add(value.asObject().get(\"path\").asString(),\n value.asObject().get(\"value\").asString());\n } else if (value.asObject().get(\"value\").isArray()) {\n ArrayList<String> list = new ArrayList<String>();\n for (JsonValue jsonValue : value.asObject().get(\"value\").asArray()) {\n list.add(jsonValue.asString());\n }\n metadataToUpdate.add(value.asObject().get(\"path\").asString(), list);\n }\n }\n metadataValue = this.updateMetadata(metadataToUpdate);\n }\n }\n\n return metadataValue;\n }" ]
[ "public static void indexResourceRoot(final ResourceRoot resourceRoot) throws DeploymentUnitProcessingException {\n if (resourceRoot.getAttachment(Attachments.ANNOTATION_INDEX) != null) {\n return;\n }\n\n VirtualFile indexFile = resourceRoot.getRoot().getChild(ModuleIndexBuilder.INDEX_LOCATION);\n if (indexFile.exists()) {\n try {\n IndexReader reader = new IndexReader(indexFile.openStream());\n resourceRoot.putAttachment(Attachments.ANNOTATION_INDEX, reader.read());\n ServerLogger.DEPLOYMENT_LOGGER.tracef(\"Found and read index at: %s\", indexFile);\n return;\n } catch (Exception e) {\n ServerLogger.DEPLOYMENT_LOGGER.cannotLoadAnnotationIndex(indexFile.getPathName());\n }\n }\n\n // if this flag is present and set to false then do not index the resource\n Boolean shouldIndexResource = resourceRoot.getAttachment(Attachments.INDEX_RESOURCE_ROOT);\n if (shouldIndexResource != null && !shouldIndexResource) {\n return;\n }\n\n final List<String> indexIgnorePathList = resourceRoot.getAttachment(Attachments.INDEX_IGNORE_PATHS);\n final Set<String> indexIgnorePaths;\n if (indexIgnorePathList != null && !indexIgnorePathList.isEmpty()) {\n indexIgnorePaths = new HashSet<String>(indexIgnorePathList);\n } else {\n indexIgnorePaths = null;\n }\n\n final VirtualFile virtualFile = resourceRoot.getRoot();\n final Indexer indexer = new Indexer();\n try {\n final VisitorAttributes visitorAttributes = new VisitorAttributes();\n visitorAttributes.setLeavesOnly(true);\n visitorAttributes.setRecurseFilter(new VirtualFileFilter() {\n public boolean accepts(VirtualFile file) {\n return indexIgnorePaths == null || !indexIgnorePaths.contains(file.getPathNameRelativeTo(virtualFile));\n }\n });\n\n final List<VirtualFile> classChildren = virtualFile.getChildren(new SuffixMatchFilter(\".class\", visitorAttributes));\n for (VirtualFile classFile : classChildren) {\n InputStream inputStream = null;\n try {\n inputStream = classFile.openStream();\n indexer.index(inputStream);\n } catch (Exception e) {\n ServerLogger.DEPLOYMENT_LOGGER.cannotIndexClass(classFile.getPathNameRelativeTo(virtualFile), virtualFile.getPathName(), e);\n } finally {\n VFSUtils.safeClose(inputStream);\n }\n }\n final Index index = indexer.complete();\n resourceRoot.putAttachment(Attachments.ANNOTATION_INDEX, index);\n ServerLogger.DEPLOYMENT_LOGGER.tracef(\"Generated index for archive %s\", virtualFile);\n } catch (Throwable t) {\n throw ServerLogger.ROOT_LOGGER.deploymentIndexingFailed(t);\n }\n }", "public CodePage getCodePage(int field)\n {\n CodePage result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n result = CodePage.getInstance(m_fields[field]);\n }\n else\n {\n result = CodePage.getInstance(null);\n }\n\n return (result);\n }", "private void ensureIndexIsUnlocked(String dataDir) {\n\n Collection<File> lockFiles = new ArrayList<File>(2);\n lockFiles.add(\n new File(\n CmsFileUtil.addTrailingSeparator(CmsFileUtil.addTrailingSeparator(dataDir) + \"index\") + \"write.lock\"));\n lockFiles.add(\n new File(\n CmsFileUtil.addTrailingSeparator(CmsFileUtil.addTrailingSeparator(dataDir) + \"spellcheck\")\n + \"write.lock\"));\n for (File lockFile : lockFiles) {\n if (lockFile.exists()) {\n lockFile.delete();\n LOG.warn(\n \"Forcely unlocking index with data dir \\\"\"\n + dataDir\n + \"\\\" by removing file \\\"\"\n + lockFile.getAbsolutePath()\n + \"\\\".\");\n }\n }\n }", "protected void addFacetPart(CmsSolrQuery query) {\n\n StringBuffer value = new StringBuffer();\n value.append(\"{!key=\").append(m_config.getName());\n addFacetOptions(value);\n if (m_config.getIgnoreAllFacetFilters()\n || (!m_state.getCheckedEntries().isEmpty() && !m_config.getIsAndFacet())) {\n value.append(\" ex=\").append(m_config.getIgnoreTags());\n }\n value.append(\"}\");\n value.append(m_config.getRange());\n query.add(\"facet.range\", value.toString());\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 }", "private String validatePattern() {\n\n String error = null;\n switch (getPatternType()) {\n case DAILY:\n error = isEveryWorkingDay() ? null : validateInterval();\n break;\n case WEEKLY:\n error = validateInterval();\n if (null == error) {\n error = validateWeekDaySet();\n }\n break;\n case MONTHLY:\n error = validateInterval();\n if (null == error) {\n error = validateMonthSet();\n if (null == error) {\n error = isWeekDaySet() ? validateWeekOfMonthSet() : validateDayOfMonth();\n }\n }\n break;\n case YEARLY:\n error = isWeekDaySet() ? validateWeekOfMonthSet() : validateDayOfMonth();\n break;\n case INDIVIDUAL:\n case NONE:\n default:\n }\n return error;\n }", "public String getLinkCopyText(JSONObject jsonObject){\n if(jsonObject == null) return \"\";\n try {\n JSONObject copyObject = jsonObject.has(\"copyText\") ? jsonObject.getJSONObject(\"copyText\") : null;\n if(copyObject != null){\n return copyObject.has(\"text\") ? copyObject.getString(\"text\") : \"\";\n }else{\n return \"\";\n }\n } catch (JSONException e) {\n Logger.v(\"Unable to get Link Text with JSON - \"+e.getLocalizedMessage());\n return \"\";\n }\n }", "public static List<String> getDefaultConversionProviderChain(){\n List<String> defaultChain = getMonetaryConversionsSpi()\n .getDefaultProviderChain();\n Objects.requireNonNull(defaultChain, \"No default provider chain provided by SPI: \" +\n getMonetaryConversionsSpi().getClass().getName());\n return defaultChain;\n }", "@Override\n public PmdRuleSet create() {\n final SAXBuilder parser = new SAXBuilder();\n final Document dom;\n try {\n dom = parser.build(source);\n } catch (JDOMException | IOException e) {\n if (messages != null) {\n messages.addErrorText(INVALID_INPUT + \" : \" + e.getMessage());\n }\n LOG.error(INVALID_INPUT, e);\n return new PmdRuleSet();\n }\n\n final Element eltResultset = dom.getRootElement();\n final Namespace namespace = eltResultset.getNamespace();\n final PmdRuleSet result = new PmdRuleSet();\n\n final String name = eltResultset.getAttributeValue(\"name\");\n final Element descriptionElement = getChild(eltResultset, namespace);\n\n result.setName(name);\n\n if (descriptionElement != null) {\n result.setDescription(descriptionElement.getValue());\n }\n\n for (Element eltRule : getChildren(eltResultset, \"rule\", namespace)) {\n PmdRule pmdRule = new PmdRule(eltRule.getAttributeValue(\"ref\"));\n pmdRule.setClazz(eltRule.getAttributeValue(\"class\"));\n pmdRule.setName(eltRule.getAttributeValue(\"name\"));\n pmdRule.setMessage(eltRule.getAttributeValue(\"message\"));\n parsePmdPriority(eltRule, pmdRule, namespace);\n parsePmdProperties(eltRule, pmdRule, namespace);\n result.addRule(pmdRule);\n }\n return result;\n }" ]
Use this API to update nsspparams.
[ "public static base_response update(nitro_service client, nsspparams resource) throws Exception {\n\t\tnsspparams updateresource = new nsspparams();\n\t\tupdateresource.basethreshold = resource.basethreshold;\n\t\tupdateresource.throttle = resource.throttle;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
[ "public void setConnectTimeout(int millis) {\n\t\tClientHttpRequestFactory f = getRequestFactory();\n\t\tif (f instanceof SimpleClientHttpRequestFactory) {\n\t\t\t((SimpleClientHttpRequestFactory) f).setConnectTimeout(millis);\n\t\t}\n\t\telse {\n\t\t\t((HttpComponentsClientHttpRequestFactory) f).setConnectTimeout(millis);\n\t\t}\n\t}", "public void clearSelections() {\n for (CheckableViewHolder vh : mCheckedVisibleViewHolders) {\n vh.checkbox.setChecked(false);\n }\n mCheckedVisibleViewHolders.clear();\n mCheckedItems.clear();\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}", "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 Collection<Integer> getNumericCodes() {\n Collection<Integer> result = get(KEY_QUERY_NUMERIC_CODES, Collection.class);\n if (result == null) {\n return Collections.emptySet();\n }\n return result;\n }", "private PGPSecretKey getSecretKey(InputStream input, String keyId) throws IOException, PGPException {\n PGPSecretKeyRingCollection keyrings = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(input), new JcaKeyFingerprintCalculator());\n\n Iterator rIt = keyrings.getKeyRings();\n\n while (rIt.hasNext()) {\n PGPSecretKeyRing kRing = (PGPSecretKeyRing) rIt.next();\n Iterator kIt = kRing.getSecretKeys();\n\n while (kIt.hasNext()) {\n PGPSecretKey key = (PGPSecretKey) kIt.next();\n\n if (key.isSigningKey() && String.format(\"%08x\", key.getKeyID() & 0xFFFFFFFFL).equals(keyId.toLowerCase())) {\n return key;\n }\n }\n }\n\n return null;\n }", "public String isChecked(String value1, String value2) {\n\n if ((value1 == null) || (value2 == null)) {\n return \"\";\n }\n\n if (value1.trim().equalsIgnoreCase(value2.trim())) {\n return \"checked\";\n }\n\n return \"\";\n }", "public static boolean isInverse(DMatrixRMaj a , DMatrixRMaj b , double tol ) {\n if( a.numRows != b.numRows || a.numCols != b.numCols ) {\n return false;\n }\n\n int numRows = a.numRows;\n int numCols = a.numCols;\n\n for( int i = 0; i < numRows; i++ ) {\n for( int j = 0; j < numCols; j++ ) {\n double total = 0;\n for( int k = 0; k < numCols; k++ ) {\n total += a.get(i,k)*b.get(k,j);\n }\n\n if( i == j ) {\n if( !(Math.abs(total-1) <= tol) )\n return false;\n } else if( !(Math.abs(total) <= tol) )\n return false;\n }\n }\n\n return true;\n }", "private static void parseBounds(JSONObject modelJSON,\n Shape current) throws JSONException {\n if (modelJSON.has(\"bounds\")) {\n JSONObject boundsObject = modelJSON.getJSONObject(\"bounds\");\n current.setBounds(new Bounds(new Point(boundsObject.getJSONObject(\"lowerRight\").getDouble(\"x\"),\n boundsObject.getJSONObject(\"lowerRight\").getDouble(\n \"y\")),\n new Point(boundsObject.getJSONObject(\"upperLeft\").getDouble(\"x\"),\n boundsObject.getJSONObject(\"upperLeft\").getDouble(\"y\"))));\n }\n }" ]
Implementation of FNV-1a hash algorithm. @see <a href="https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function"> ttps://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function</a> @param doc the document to hash @return
[ "public static long hash(final BsonDocument doc) {\n if (doc == null) {\n return 0L;\n }\n\n final byte[] docBytes = toBytes(doc);\n long hashValue = FNV_64BIT_OFFSET_BASIS;\n\n for (int offset = 0; offset < docBytes.length; offset++) {\n hashValue ^= (0xFF & docBytes[offset]);\n hashValue *= FNV_64BIT_PRIME;\n }\n\n return hashValue;\n }" ]
[ "private void bumpScores(Map<Long, Score> candidates,\n List<Bucket> buckets,\n int ix) {\n for (; ix < buckets.size(); ix++) {\n Bucket b = buckets.get(ix);\n if (b.nextfree > CUTOFF_FACTOR_2 * candidates.size())\n return;\n double score = b.getScore();\n for (Score s : candidates.values())\n if (b.contains(s.id))\n s.score += score;\n }\n }", "public void wireSteps( CanWire canWire ) {\n for( StageState steps : stages.values() ) {\n canWire.wire( steps.instance );\n }\n }", "public void enableClipRegion() {\n if (mClippingEnabled) {\n Log.w(TAG, \"Clipping has been enabled already for %s!\", getName());\n return;\n }\n Log.d(Log.SUBSYSTEM.WIDGET, TAG, \"enableClipping for %s [%f, %f, %f]\",\n getName(), getViewPortWidth(), getViewPortHeight(), getViewPortDepth());\n\n mClippingEnabled = true;\n\n GVRTexture texture = WidgetLib.getTextureHelper().getSolidColorTexture(Color.YELLOW);\n\n GVRSceneObject clippingObj = new GVRSceneObject(mContext, getViewPortWidth(), getViewPortHeight(), texture);\n clippingObj.setName(\"clippingObj\");\n clippingObj.getRenderData()\n .setRenderingOrder(GVRRenderData.GVRRenderingOrder.STENCIL)\n .setStencilTest(true)\n .setStencilFunc(GLES30.GL_ALWAYS, 1, 0xFF)\n .setStencilOp(GLES30.GL_KEEP, GLES30.GL_KEEP, GLES30.GL_REPLACE)\n .setStencilMask(0xFF);\n\n mSceneObject.addChildObject(clippingObj);\n\n for (Widget child : getChildren()) {\n setObjectClipped(child);\n }\n }", "public void setEnterpriseDate(int index, Date value)\n {\n set(selectField(AssignmentFieldLists.ENTERPRISE_DATE, index), value);\n }", "public void setTargetDirectory(String directory) {\n if (directory != null && directory.length() > 0) {\n this.targetDirectory = new File(directory);\n } else {\n this.targetDirectory = null;\n }\n }", "@Override\n public final PArray getArray(final String key) {\n PArray result = optArray(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }", "public static void validate(final License license) {\n // A license should have a name\n if(license.getName() == null ||\n license.getName().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"License name should not be empty!\")\n .build());\n }\n\n // A license should have a long name\n if(license.getLongName() == null ||\n license.getLongName().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"License long name should not be empty!\")\n .build());\n }\n\n // If there is a regexp, it should compile\n if(license.getRegexp() != null &&\n !license.getRegexp().isEmpty()){\n try{\n Pattern.compile(license.getRegexp());\n }\n catch (PatternSyntaxException e){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"License regexp does not compile!\").build());\n }\n\n Pattern regex = Pattern.compile(\"[&%//]\");\n if(regex.matcher(license.getRegexp()).find()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"License regexp does not compile!\").build());\n }\n\n }\n }", "public static Variable upcastToGeneratedBuilder(\n SourceBuilder code, Datatype datatype, String builder) {\n return code.scope().computeIfAbsent(Declaration.UPCAST, () -> {\n Variable base = new Variable(\"base\");\n code.addLine(UPCAST_COMMENT)\n .addLine(\"%s %s = %s;\", datatype.getGeneratedBuilder(), base, builder);\n return base;\n });\n }", "@Override\n protected void runUnsafe() throws Exception {\n Path reportDirectory = getReportDirectoryPath();\n Files.walkFileTree(reportDirectory, new DeleteVisitor());\n LOGGER.info(\"Report directory <{}> was successfully cleaned.\", reportDirectory);\n }" ]
Adds a symbol to the end of the token list @param symbol Symbol which is to be added @return The new Token created around symbol
[ "public Token add( Symbol symbol ) {\n Token t = new Token(symbol);\n push( t );\n return t;\n }" ]
[ "private void applyProperties(AssociationKey associationKey, Tuple associationRow, Relationship relationship) {\n\t\tString[] indexColumns = associationKey.getMetadata().getRowKeyIndexColumnNames();\n\t\tfor ( int i = 0; i < indexColumns.length; i++ ) {\n\t\t\tString propertyName = indexColumns[i];\n\t\t\tObject propertyValue = associationRow.get( propertyName );\n\t\t\trelationship.setProperty( propertyName, propertyValue );\n\t\t}\n\t}", "public void loadModel(GVRAndroidResource avatarResource)\n {\n EnumSet<GVRImportSettings> settings = GVRImportSettings.getRecommendedSettingsWith(EnumSet.of(GVRImportSettings.OPTIMIZE_GRAPH, GVRImportSettings.NO_ANIMATION));\n GVRContext ctx = mAvatarRoot.getGVRContext();\n GVRResourceVolume volume = new GVRResourceVolume(ctx, avatarResource);\n GVRSceneObject modelRoot = new GVRSceneObject(ctx);\n\n mAvatarRoot.addChildObject(modelRoot);\n ctx.getAssetLoader().loadModel(volume, modelRoot, settings, false, mLoadModelHandler);\n }", "public static base_responses delete(nitro_service client, ntpserver resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tntpserver deleteresources[] = new ntpserver[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new ntpserver();\n\t\t\t\tdeleteresources[i].serverip = resources[i].serverip;\n\t\t\t\tdeleteresources[i].servername = resources[i].servername;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "public static <T extends Comparable<? super T>> List<T> sort(Iterable<T> iterable) {\n\t\tList<T> asList = Lists.newArrayList(iterable);\n\t\tif (iterable instanceof SortedSet<?>) {\n\t\t\tif (((SortedSet<T>) iterable).comparator() == null) {\n\t\t\t\treturn asList;\n\t\t\t}\n\t\t}\n\t\treturn ListExtensions.sortInplace(asList);\n\t}", "private void updateMax(MtasRBTreeNode n, MtasRBTreeNode c) {\n if (c != null) {\n if (n.max < c.max) {\n n.max = c.max;\n }\n }\n }", "public void deleteById(Object id) {\n\n int count = beginDelete().whereEquals(idColumn.getColumnName(), id).delete();\n\n if (count == 0) {\n throw new RowNotFoundException(table, id);\n }\n }", "public long[] append(MessageSet messages) throws IOException {\n checkMutable();\n long written = 0L;\n while (written < messages.getSizeInBytes())\n written += messages.writeTo(channel, 0, messages.getSizeInBytes());\n long beforeOffset = setSize.getAndAdd(written);\n return new long[]{written, beforeOffset};\n }", "public List<BindingInfo> getQueueBindings(String vhost, String queue) {\n final URI uri = uriWithPath(\"./queues/\" + encodePathSegment(vhost) +\n \"/\" + encodePathSegment(queue) + \"/bindings\");\n final BindingInfo[] result = this.rt.getForObject(uri, BindingInfo[].class);\n return asListOrNull(result);\n }", "private List<MapRow> sort(List<MapRow> rows, final String attribute)\n {\n Collections.sort(rows, new Comparator<MapRow>()\n {\n @Override public int compare(MapRow o1, MapRow o2)\n {\n String value1 = o1.getString(attribute);\n String value2 = o2.getString(attribute);\n return value1.compareTo(value2);\n }\n });\n return rows;\n }" ]
Retrieve the state object associated with the specified interceptor instance and property name on this request context. @param interceptor the interceptor instance @param stateName the name key that the state object was stored under @param stateType class of the type the stored state should be returned as @param <T> the type the stored state should be returned as @return the stored state object @see #setState(HttpConnectionInterceptor, String, Object) @since 2.6.0
[ "public <T> T getState(HttpConnectionInterceptor interceptor, String stateName, Class<T>\n stateType) {\n Map<String, Object> state = interceptorStates.get(interceptor);\n if (state != null) {\n return stateType.cast(state.get(stateName));\n } else {\n return null;\n }\n }" ]
[ "public static CmsPair<String, Map<String, String>> parseEmbeddedGalleryOptions(String configuration) {\n\n final Map<String, String> galleryOptions = Maps.newHashMap();\n String resultConfig = CmsStringUtil.substitute(\n PATTERN_EMBEDDED_GALLERY_CONFIG,\n configuration,\n new I_CmsRegexSubstitution() {\n\n public String substituteMatch(String string, Matcher matcher) {\n\n String galleryName = string.substring(matcher.start(1), matcher.end(1));\n String embeddedConfig = string.substring(matcher.start(2), matcher.end(2));\n galleryOptions.put(galleryName, embeddedConfig);\n return galleryName;\n }\n });\n return CmsPair.create(resultConfig, galleryOptions);\n }", "public static synchronized ExecutionStatistics get()\n {\n Thread currentThread = Thread.currentThread();\n if (stats.get(currentThread) == null)\n {\n stats.put(currentThread, new ExecutionStatistics());\n }\n return stats.get(currentThread);\n }", "public static AliasFinder newInstance(final String variableName, final ControlFlowBlock controlFlowBlockToExamine) {\n checkArgument(!variableName.isEmpty());\n return new AliasFinder(variableName, checkNotNull(controlFlowBlockToExamine));\n }", "@Override\n\tpublic ProxyAuthenticationMethod getMethod() {\n\t\tswitch (authenticationMethod) {\n\t\tcase BASIC:\n\t\t\treturn ProxyAuthenticationMethod.BASIC;\n\t\tcase DIGEST:\n\t\t\treturn ProxyAuthenticationMethod.DIGEST;\n\t\tcase URL:\n\t\t\treturn ProxyAuthenticationMethod.URL;\n\t\tdefault:\n\t\t\treturn null;\n\t\t}\n\t}", "public static String getFilename(String path) throws IllegalArgumentException {\n if (Pattern.matches(sPatternUrl, path))\n return getURLFilename(path);\n\n return new File(path).getName();\n }", "public static <T> void filterListToMap(final Map<String, T> destinationMap, final String[] nameMapping,\n\t\tfinal List<? extends T> sourceList) {\n\t\tif( destinationMap == null ) {\n\t\t\tthrow new NullPointerException(\"destinationMap should not be null\");\n\t\t} else if( nameMapping == null ) {\n\t\t\tthrow new NullPointerException(\"nameMapping should not be null\");\n\t\t} else if( sourceList == null ) {\n\t\t\tthrow new NullPointerException(\"sourceList should not be null\");\n\t\t} else if( nameMapping.length != sourceList.size() ) {\n\t\t\tthrow new SuperCsvException(\n\t\t\t\tString\n\t\t\t\t\t.format(\n\t\t\t\t\t\t\"the nameMapping array and the sourceList should be the same size (nameMapping length = %d, sourceList size = %d)\",\n\t\t\t\t\t\tnameMapping.length, sourceList.size()));\n\t\t}\n\t\t\n\t\tdestinationMap.clear();\n\t\t\n\t\tfor( int i = 0; i < nameMapping.length; i++ ) {\n\t\t\tfinal String key = nameMapping[i];\n\t\t\t\n\t\t\tif( key == null ) {\n\t\t\t\tcontinue; // null's in the name mapping means skip column\n\t\t\t}\n\t\t\t\n\t\t\t// no duplicates allowed\n\t\t\tif( destinationMap.containsKey(key) ) {\n\t\t\t\tthrow new SuperCsvException(String.format(\"duplicate nameMapping '%s' at index %d\", key, i));\n\t\t\t}\n\t\t\t\n\t\t\tdestinationMap.put(key, sourceList.get(i));\n\t\t}\n\t}", "public static URL asUrlOrResource(String s) {\n if (Strings.isNullOrEmpty(s)) {\n return null;\n }\n\n try {\n return new URL(s);\n } catch (MalformedURLException e) {\n //If its not a valid URL try to treat it as a local resource.\n return findConfigResource(s);\n }\n }", "private void throwOrWarnAboutDescriptorProblem(String message) {\n if (validateDescriptions) {\n throw new IllegalArgumentException(message);\n }\n ControllerLogger.ROOT_LOGGER.warn(message);\n }", "private static List<CmsCategory> getCategories(CmsObject cms, CmsResource resource) {\n\n if ((null != resource) && (null != cms)) {\n try {\n return CmsCategoryService.getInstance().readResourceCategories(cms, resource);\n } catch (CmsException e) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n }\n return new ArrayList<CmsCategory>(0);\n }" ]
Create a set out of the items in the Iterable. @param <T> The type of items in the Iterable. @param items The items to be made into a set. @return A set consisting of the items from the Iterable.
[ "public static <T> Set<T> toSet(Iterable<T> items) {\r\n Set<T> set = new HashSet<T>();\r\n addAll(set, items);\r\n return set;\r\n }" ]
[ "public JSONObject getPathFromEndpoint(String pathValue, String requestType) throws Exception {\n int type = getRequestTypeFromString(requestType);\n String url = BASE_PATH;\n JSONObject response = new JSONObject(doGet(url, null));\n JSONArray paths = response.getJSONArray(\"paths\");\n for (int i = 0; i < paths.length(); i++) {\n JSONObject path = paths.getJSONObject(i);\n if (path.getString(\"path\").equals(pathValue) && path.getInt(\"requestType\") == type) {\n return path;\n }\n }\n return null;\n }", "public final void notifyHeaderItemRangeChanged(int positionStart, int itemCount) {\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount >= headerItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \" + (positionStart + itemCount - 1) + \"] is not within the position bounds for header items [0 - \" + (headerItemCount - 1) + \"].\");\n }\n notifyItemRangeChanged(positionStart, itemCount);\n }", "public void setClassOfObject(Class c)\r\n {\r\n m_Class = c;\r\n isAbstract = Modifier.isAbstract(m_Class.getModifiers());\r\n // TODO : Shouldn't the HashMap in DescriptorRepository be updated as well?\r\n }", "public void setOccurence(int min, int max) throws ParseException {\n if (!simplified) {\n if ((min < 0) || (min > max) || (max < 1)) {\n throw new ParseException(\"Illegal number {\" + min + \",\" + max + \"}\");\n }\n if (min == 0) {\n optional = true;\n }\n minimumOccurence = Math.max(1, min);\n maximumOccurence = max;\n } else {\n throw new ParseException(\"already simplified\");\n }\n }", "protected void checkConsecutiveAlpha() {\n\n Pattern symbolsPatter = Pattern.compile(REGEX_ALPHA_UC + \"+\");\n Matcher matcher = symbolsPatter.matcher(this.password);\n int met = 0;\n while (matcher.find()) {\n int start = matcher.start();\n int end = matcher.end();\n if (start == end) {\n continue;\n }\n int diff = end - start;\n if (diff >= 3) {\n met += diff;\n }\n\n }\n\n this.result.negative(met * CONSECUTIVE_ALPHA_WEIGHT);\n\n // alpha lower case\n\n symbolsPatter = Pattern.compile(REGEX_ALPHA_LC + \"+\");\n matcher = symbolsPatter.matcher(this.password);\n met = 0;\n while (matcher.find()) {\n int start = matcher.start();\n int end = matcher.end();\n if (start == end) {\n continue;\n }\n int diff = end - start;\n if (diff >= 3) {\n met += diff;\n }\n\n }\n\n this.result.negative(met * CONSECUTIVE_ALPHA_WEIGHT);\n }", "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 }", "public void update(Record record, boolean isText) throws MPXJException\n {\n int length = record.getLength();\n\n for (int i = 0; i < length; i++)\n {\n if (isText == true)\n {\n add(getTaskCode(record.getString(i)));\n }\n else\n {\n add(record.getInteger(i).intValue());\n }\n }\n }", "public static void calculatePointDiff(Point2D _P1, Point2D _P2, Point2D _Result, float _Multiplier) {\n float diffX = _P2.getX() - _P1.getX();\n float diffY = _P2.getY() - _P1.getY();\n _Result.setX(_P1.getX() + (diffX * _Multiplier));\n _Result.setY(_P1.getY() + (diffY * _Multiplier));\n }", "public 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 }" ]
Returns the configured body or the default value.
[ "@Nonnull\n public String getBody() {\n if (body == null) {\n return storage == null ? DEFAULT_BODY : DEFAULT_BODY_STORAGE;\n } else {\n return body;\n }\n }" ]
[ "@Override\n public void perform(GraphRewrite event, EvaluationContext context)\n {\n checkVariableName(event, context);\n WindupVertexFrame payload = resolveVariable(event, getVariableName());\n if (payload instanceof FileReferenceModel)\n {\n FileModel file = ((FileReferenceModel) payload).getFile();\n perform(event, context, (XmlFileModel) file);\n }\n else\n {\n super.perform(event, context);\n }\n\n }", "private void checkTexRange(AiTextureType type, int index) {\n if (index < 0 || index > m_numTextures.get(type)) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Size: \" +\n m_numTextures.get(type));\n }\n }", "@Override\n public void init(NamedList args) {\n\n Object regex = args.remove(PARAM_REGEX);\n if (null == regex) {\n throw new SolrException(ErrorCode.SERVER_ERROR, \"Missing required init parameter: \" + PARAM_REGEX);\n }\n try {\n m_regex = Pattern.compile(regex.toString());\n } catch (PatternSyntaxException e) {\n throw new SolrException(ErrorCode.SERVER_ERROR, \"Invalid regex: \" + regex, e);\n }\n\n Object replacement = args.remove(PARAM_REPLACEMENT);\n if (null == replacement) {\n throw new SolrException(ErrorCode.SERVER_ERROR, \"Missing required init parameter: \" + PARAM_REPLACEMENT);\n }\n m_replacement = replacement.toString();\n\n Object source = args.remove(PARAM_SOURCE);\n if (null == source) {\n throw new SolrException(ErrorCode.SERVER_ERROR, \"Missing required init parameter: \" + PARAM_SOURCE);\n }\n m_source = source.toString();\n\n Object target = args.remove(PARAM_TARGET);\n if (null == target) {\n throw new SolrException(ErrorCode.SERVER_ERROR, \"Missing required init parameter: \" + PARAM_TARGET);\n }\n m_target = target.toString();\n\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 ClassificationModel attachLink(ClassificationModel classificationModel, LinkModel linkModel)\n {\n for (LinkModel existing : classificationModel.getLinks())\n {\n if (StringUtils.equals(existing.getLink(), linkModel.getLink()))\n {\n return classificationModel;\n }\n }\n classificationModel.addLink(linkModel);\n return classificationModel;\n }", "private static long switchValue8(long currentHexValue, int digitCount) {\n\t\tlong result = 0x7 & currentHexValue;\n\t\tint shift = 0;\n\t\twhile(--digitCount > 0) {\n\t\t\tshift += 3;\n\t\t\tcurrentHexValue >>>= 4;\n\t\t\tresult |= (0x7 & currentHexValue) << shift;\n\t\t}\n\t\treturn result;\n\t}", "@RequestMapping(value = \"/api/plugins\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getPluginInformation() {\n return pluginInformation();\n }", "public SelectBuilder orderBy(String name, boolean ascending) {\n if (ascending) {\n orderBys.add(name + \" asc\");\n } else {\n orderBys.add(name + \" desc\");\n }\n return this;\n }", "public Set<MetadataProvider> getMetadataProviders(MediaDetails sourceMedia) {\n String key = (sourceMedia == null)? \"\" : sourceMedia.hashKey();\n Set<MetadataProvider> result = metadataProviders.get(key);\n if (result == null) {\n return Collections.emptySet();\n }\n return Collections.unmodifiableSet(new HashSet<MetadataProvider>(result));\n }" ]
Creates a sort configuration iff at least one of the parameters is not null and the options list is not empty. @param sortParam The request parameter used to send the currently chosen search option. @param options The available sort options. @param defaultOption The default sort option. @return the sort configuration or null, depending on the arguments.
[ "public static CmsSearchConfigurationSorting create(\n final String sortParam,\n final List<I_CmsSearchConfigurationSortOption> options,\n final I_CmsSearchConfigurationSortOption defaultOption) {\n\n return (null != sortParam) || ((null != options) && !options.isEmpty()) || (null != defaultOption)\n ? new CmsSearchConfigurationSorting(sortParam, options, defaultOption)\n : null;\n }" ]
[ "public static URL codeLocationFromURL(String url) {\n try {\n return new URL(url);\n } catch (Exception e) {\n throw new InvalidCodeLocation(url);\n }\n }", "public static tmglobal_binding get(nitro_service service) throws Exception{\n\t\ttmglobal_binding obj = new tmglobal_binding();\n\t\ttmglobal_binding response = (tmglobal_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "@PostConstruct\n\tprotected void postConstruct() throws GeomajasException {\n\t\tif (null != crsDefinitions) {\n\t\t\tfor (CrsInfo crsInfo : crsDefinitions.values()) {\n\t\t\t\ttry {\n\t\t\t\t\tCoordinateReferenceSystem crs = CRS.parseWKT(crsInfo.getCrsWkt());\n\t\t\t\t\tString code = crsInfo.getKey();\n\t\t\t\t\tcrsCache.put(code, CrsFactory.getCrs(code, crs));\n\t\t\t\t} catch (FactoryException e) {\n\t\t\t\t\tthrow new GeomajasException(e, ExceptionCode.CRS_DECODE_FAILURE_FOR_MAP, crsInfo.getKey());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (null != crsTransformDefinitions) {\n\t\t\tfor (CrsTransformInfo crsTransformInfo : crsTransformDefinitions.values()) {\n\t\t\t\tString key = getTransformKey(crsTransformInfo);\n\t\t\t\ttransformCache.put(key, getCrsTransform(key, crsTransformInfo));\n\t\t\t}\n\t\t}\n\t\tGeometryFactory factory = new GeometryFactory();\n\t\tEMPTY_GEOMETRIES.put(Point.class, factory.createPoint((Coordinate) null));\n\t\tEMPTY_GEOMETRIES.put(LineString.class, factory.createLineString((Coordinate[]) null));\n\t\tEMPTY_GEOMETRIES.put(Polygon.class, factory.createPolygon(null, null));\n\t\tEMPTY_GEOMETRIES.put(MultiPoint.class, factory.createMultiPoint((Coordinate[]) null));\n\t\tEMPTY_GEOMETRIES.put(MultiLineString.class, factory.createMultiLineString((LineString[]) null)); // cast needed!\n\t\tEMPTY_GEOMETRIES.put(MultiPolygon.class, factory.createMultiPolygon((Polygon[]) null)); // cast needed!\n\t\tEMPTY_GEOMETRIES.put(Geometry.class, factory.createGeometryCollection(null));\n\t}", "public static Iterable<BoxFileVersionRetention.Info> getAll(BoxAPIConnection api, String ... fields) {\n return getRetentions(api, new QueryFilter(), fields);\n }", "@Deprecated\n public static OptionMap create(final ExpressionResolver resolver, final ModelNode model, final OptionMap defaults) throws OperationFailedException {\n final OptionMap map = OptionMap.builder()\n .addAll(defaults)\n .set(Options.WORKER_READ_THREADS, RemotingSubsystemRootResource.WORKER_READ_THREADS.resolveModelAttribute(resolver, model).asInt())\n .set(Options.WORKER_TASK_CORE_THREADS, RemotingSubsystemRootResource.WORKER_TASK_CORE_THREADS.resolveModelAttribute(resolver, model).asInt())\n .set(Options.WORKER_TASK_KEEPALIVE, RemotingSubsystemRootResource.WORKER_TASK_KEEPALIVE.resolveModelAttribute(resolver, model).asInt())\n .set(Options.WORKER_TASK_LIMIT, RemotingSubsystemRootResource.WORKER_TASK_LIMIT.resolveModelAttribute(resolver, model).asInt())\n .set(Options.WORKER_TASK_MAX_THREADS, RemotingSubsystemRootResource.WORKER_TASK_MAX_THREADS.resolveModelAttribute(resolver, model).asInt())\n .set(Options.WORKER_WRITE_THREADS, RemotingSubsystemRootResource.WORKER_WRITE_THREADS.resolveModelAttribute(resolver, model).asInt())\n .set(Options.WORKER_READ_THREADS, RemotingSubsystemRootResource.WORKER_READ_THREADS.resolveModelAttribute(resolver, model).asInt())\n .getMap();\n return map;\n }", "public byte[] getMessageBuffer() {\n\t\tByteArrayOutputStream resultByteBuffer = new ByteArrayOutputStream();\n\t\tbyte[] result;\n\t\tresultByteBuffer.write((byte)0x01);\n\t\tint messageLength = messagePayload.length + \n\t\t\t\t(this.messageClass == SerialMessageClass.SendData && \n\t\t\t\tthis.messageType == SerialMessageType.Request ? 5 : 3); // calculate and set length\n\t\t\n\t\tresultByteBuffer.write((byte) messageLength);\n\t\tresultByteBuffer.write((byte) messageType.ordinal());\n\t\tresultByteBuffer.write((byte) messageClass.getKey());\n\t\t\n\t\ttry {\n\t\t\tresultByteBuffer.write(messagePayload);\n\t\t} catch (IOException e) {\n\t\t\t\n\t\t}\n\n\t\t// callback ID and transmit options for a Send Data message.\n\t\tif (this.messageClass == SerialMessageClass.SendData && this.messageType == SerialMessageType.Request) {\n\t\t\tresultByteBuffer.write(transmitOptions);\n\t\t\tresultByteBuffer.write(callbackId);\n\t\t}\n\t\t\n\t\tresultByteBuffer.write((byte) 0x00);\n\t\tresult = resultByteBuffer.toByteArray();\n\t\tresult[result.length - 1] = 0x01;\n\t\tresult[result.length - 1] = calculateChecksum(result);\n\t\tlogger.debug(\"Assembled message buffer = \" + SerialMessage.bb2hex(result));\n\t\treturn result;\n\t}", "public synchronized static <D extends Dao<T, ?>, T> D lookupDao(ConnectionSource connectionSource,\n\t\t\tDatabaseTableConfig<T> tableConfig) {\n\t\tif (connectionSource == null) {\n\t\t\tthrow new IllegalArgumentException(\"connectionSource argument cannot be null\");\n\t\t}\n\t\tTableConfigConnectionSource key = new TableConfigConnectionSource(connectionSource, tableConfig);\n\t\tDao<?, ?> dao = lookupDao(key);\n\t\tif (dao == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\t@SuppressWarnings(\"unchecked\")\n\t\t\tD castDao = (D) dao;\n\t\t\treturn castDao;\n\t\t}\n\t}", "private void refreshMetadataCache(final Queue<WindupMetadataSystem> metadataSystemCache, final DecompilerSettings settings)\n {\n metadataSystemCache.clear();\n for (int i = 0; i < this.getNumberOfThreads(); i++)\n {\n metadataSystemCache.add(new NoRetryMetadataSystem(settings.getTypeLoader()));\n }\n }", "private void logShort(CharSequence message, boolean trim) throws IOException {\n int length = message.length();\n if (trim) {\n while (length > 0 && Character.isWhitespace(message.charAt(length - 1))) {\n length--;\n }\n }\n\n char [] chars = new char [length + 1];\n for (int i = 0; i < length; i++) {\n chars[i] = message.charAt(i);\n }\n chars[length] = '\\n';\n\n output.write(chars);\n }" ]
Returns a string that encodes the result of a method invocation. Effectively, this just removes any headers from the encoded response. @param encodedResponse @return string that encodes the result of a method invocation
[ "private static String getEncodedInstance(String encodedResponse) {\n if (isReturnValue(encodedResponse) || isThrownException(encodedResponse)) {\n return encodedResponse.substring(4);\n }\n\n return encodedResponse;\n }" ]
[ "private void checkAndAddForbiddenStrings(final List<String> forbiddenSubStrings) {\n\t\tfor( String forbidden : forbiddenSubStrings ) {\n\t\t\tif( forbidden == null ) {\n\t\t\t\tthrow new NullPointerException(\"forbidden substring should not be null\");\n\t\t\t}\n\t\t\tthis.forbiddenSubStrings.add(forbidden);\n\t\t}\n\t}", "protected void addAlias(MonolingualTextValue alias) {\n String lang = alias.getLanguageCode();\n AliasesWithUpdate currentAliasesUpdate = newAliases.get(lang);\n \n NameWithUpdate currentLabel = newLabels.get(lang);\n // If there isn't any label for that language, put the alias there\n if (currentLabel == null) {\n newLabels.put(lang, new NameWithUpdate(alias, true));\n // If the new alias is equal to the current label, skip it\n } else if (!currentLabel.value.equals(alias)) {\n \tif (currentAliasesUpdate == null) {\n \t\tcurrentAliasesUpdate = new AliasesWithUpdate(new ArrayList<MonolingualTextValue>(), true);\n \t}\n \tList<MonolingualTextValue> currentAliases = currentAliasesUpdate.aliases;\n \tif(!currentAliases.contains(alias)) {\n \t\tcurrentAliases.add(alias);\n \t\tcurrentAliasesUpdate.added.add(alias);\n \t\tcurrentAliasesUpdate.write = true;\n \t}\n \tnewAliases.put(lang, currentAliasesUpdate);\n }\n }", "public void process(SearchDistributor distributor) {\r\n List<PossibleState> bootStrap;\r\n try {\r\n bootStrap = bfs(bootStrapMin);\r\n } catch (ModelException e) {\r\n bootStrap = new LinkedList<>();\r\n }\n\r\n List<Frontier> frontiers = new LinkedList<>();\r\n for (PossibleState p : bootStrap) {\r\n SCXMLFrontier dge = new SCXMLFrontier(p, model, tagExtensionList);\r\n frontiers.add(dge);\r\n }\n\r\n distributor.distribute(frontiers);\r\n }", "private String getPathSelectString() {\n String queryString = \"SELECT \" + Constants.DB_TABLE_REQUEST_RESPONSE + \".\" + Constants.GENERIC_CLIENT_UUID +\n \",\" + Constants.DB_TABLE_PATH + \".\" + Constants.GENERIC_ID +\n \",\" + Constants.PATH_PROFILE_PATHNAME +\n \",\" + Constants.PATH_PROFILE_ACTUAL_PATH +\n \",\" + Constants.PATH_PROFILE_BODY_FILTER +\n \",\" + Constants.PATH_PROFILE_GROUP_IDS +\n \",\" + Constants.DB_TABLE_PATH + \".\" + Constants.PATH_PROFILE_PROFILE_ID +\n \",\" + Constants.PATH_PROFILE_PATH_ORDER +\n \",\" + Constants.REQUEST_RESPONSE_REPEAT_NUMBER +\n \",\" + Constants.REQUEST_RESPONSE_REQUEST_ENABLED +\n \",\" + Constants.REQUEST_RESPONSE_RESPONSE_ENABLED +\n \",\" + Constants.PATH_PROFILE_CONTENT_TYPE +\n \",\" + Constants.PATH_PROFILE_REQUEST_TYPE +\n \",\" + Constants.PATH_PROFILE_GLOBAL +\n \" FROM \" + Constants.DB_TABLE_PATH +\n \" JOIN \" + Constants.DB_TABLE_REQUEST_RESPONSE +\n \" ON \" + Constants.DB_TABLE_PATH + \".\" + Constants.GENERIC_ID +\n \"=\" + Constants.DB_TABLE_REQUEST_RESPONSE + \".\" + Constants.REQUEST_RESPONSE_PATH_ID +\n \" AND \" + Constants.DB_TABLE_REQUEST_RESPONSE + \".\" + Constants.GENERIC_CLIENT_UUID + \" = ?\";\n\n return queryString;\n }", "public DbArtifact getArtifact(final String gavc) {\n final DbArtifact artifact = repositoryHandler.getArtifact(gavc);\n\n if(artifact == null){\n throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)\n .entity(\"Artifact \" + gavc + \" does not exist.\").build());\n }\n\n return artifact;\n }", "public boolean hasForeignkey(String name)\r\n {\r\n String realName = (name == null ? \"\" : name);\r\n ForeignkeyDef def = null;\r\n\r\n for (Iterator it = getForeignkeys(); it.hasNext();)\r\n {\r\n def = (ForeignkeyDef)it.next();\r\n if (realName.equals(def.getName()))\r\n {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }", "public static List<File> listFiles(File[] directories, IOFileFilter fileFilter, IOFileFilter dirFilter) {\n List<File> files = new ArrayList<>();\n for (File directory : directories) {\n if (!directory.isDirectory()) {\n continue;\n }\n Collection<File> filesInDirectory = FileUtils.listFiles(directory,\n fileFilter,\n dirFilter);\n files.addAll(filesInDirectory);\n }\n return files;\n }", "private synchronized JsonSchema getInputPathJsonSchema() throws IOException {\n if (inputPathJsonSchema == null) {\n // No need to query Hadoop more than once as this shouldn't change mid-run,\n // thus, we can lazily initialize and cache the result.\n inputPathJsonSchema = HadoopUtils.getSchemaFromPath(getInputPath());\n }\n return inputPathJsonSchema;\n }", "public static base_response delete(nitro_service client) throws Exception {\n\t\tlocationfile deleteresource = new locationfile();\n\t\treturn deleteresource.delete_resource(client);\n\t}" ]
set the Modification state to a new value. Used during state transitions. @param newModificationState org.apache.ojb.server.states.ModificationState
[ "public void setModificationState(ModificationState newModificationState)\r\n {\r\n if(newModificationState != modificationState)\r\n {\r\n if(log.isDebugEnabled())\r\n {\r\n log.debug(\"object state transition for object \" + this.oid + \" (\"\r\n + modificationState + \" --> \" + newModificationState + \")\");\r\n// try{throw new Exception();}catch(Exception e)\r\n// {\r\n// e.printStackTrace();\r\n// }\r\n }\r\n modificationState = newModificationState;\r\n }\r\n }" ]
[ "private void saveLocalization() {\n\n SortedProperties localization = new SortedProperties();\n for (Object itemId : m_container.getItemIds()) {\n Item item = m_container.getItem(itemId);\n String key = item.getItemProperty(TableProperty.KEY).getValue().toString();\n String value = item.getItemProperty(TableProperty.TRANSLATION).getValue().toString();\n if (!(key.isEmpty() || value.isEmpty())) {\n localization.put(key, value);\n }\n }\n m_keyset.updateKeySet(m_localizations.get(m_locale).keySet(), localization.keySet());\n m_localizations.put(m_locale, localization);\n\n }", "private String getPathSelectString() {\n String queryString = \"SELECT \" + Constants.DB_TABLE_REQUEST_RESPONSE + \".\" + Constants.GENERIC_CLIENT_UUID +\n \",\" + Constants.DB_TABLE_PATH + \".\" + Constants.GENERIC_ID +\n \",\" + Constants.PATH_PROFILE_PATHNAME +\n \",\" + Constants.PATH_PROFILE_ACTUAL_PATH +\n \",\" + Constants.PATH_PROFILE_BODY_FILTER +\n \",\" + Constants.PATH_PROFILE_GROUP_IDS +\n \",\" + Constants.DB_TABLE_PATH + \".\" + Constants.PATH_PROFILE_PROFILE_ID +\n \",\" + Constants.PATH_PROFILE_PATH_ORDER +\n \",\" + Constants.REQUEST_RESPONSE_REPEAT_NUMBER +\n \",\" + Constants.REQUEST_RESPONSE_REQUEST_ENABLED +\n \",\" + Constants.REQUEST_RESPONSE_RESPONSE_ENABLED +\n \",\" + Constants.PATH_PROFILE_CONTENT_TYPE +\n \",\" + Constants.PATH_PROFILE_REQUEST_TYPE +\n \",\" + Constants.PATH_PROFILE_GLOBAL +\n \" FROM \" + Constants.DB_TABLE_PATH +\n \" JOIN \" + Constants.DB_TABLE_REQUEST_RESPONSE +\n \" ON \" + Constants.DB_TABLE_PATH + \".\" + Constants.GENERIC_ID +\n \"=\" + Constants.DB_TABLE_REQUEST_RESPONSE + \".\" + Constants.REQUEST_RESPONSE_PATH_ID +\n \" AND \" + Constants.DB_TABLE_REQUEST_RESPONSE + \".\" + Constants.GENERIC_CLIENT_UUID + \" = ?\";\n\n return queryString;\n }", "public void forAllIndices(String template, Properties attributes) throws XDocletException\r\n {\r\n boolean processUnique = TypeConversionUtil.stringToBoolean(attributes.getProperty(ATTRIBUTE_UNIQUE), false);\r\n\r\n // first the default index\r\n _curIndexDef = _curTableDef.getIndex(null);\r\n if ((_curIndexDef != null) && (processUnique == _curIndexDef.isUnique()))\r\n {\r\n generate(template);\r\n }\r\n for (Iterator it = _curTableDef.getIndices(); it.hasNext(); )\r\n {\r\n _curIndexDef = (IndexDef)it.next();\r\n if (!_curIndexDef.isDefault() && (processUnique == _curIndexDef.isUnique()))\r\n { \r\n generate(template);\r\n }\r\n }\r\n _curIndexDef = null;\r\n }", "public static ResourceKey key(Class<?> clazz, String id) {\n return new ResourceKey(clazz.getName(), id);\n }", "public void loadProfile(Object key)\r\n {\r\n if (!isEnablePerThreadChanges())\r\n {\r\n throw new MetadataException(\"Can not load profile with disabled per thread mode\");\r\n }\r\n DescriptorRepository rep = (DescriptorRepository) metadataProfiles.get(key);\r\n if (rep == null)\r\n {\r\n throw new MetadataException(\"Can not find profile for key '\" + key + \"'\");\r\n }\r\n currentProfileKey.set(key);\r\n setDescriptor(rep);\r\n }", "private TableAlias getTableAliasForPath(String aPath, String aUserAlias, List hintClasses)\r\n {\r\n if (aUserAlias == null)\r\n {\r\n return getTableAliasForPath(aPath, hintClasses);\r\n }\r\n else\r\n {\r\n\t\t\treturn getTableAliasForPath(aUserAlias + ALIAS_SEPARATOR + aPath, hintClasses);\r\n }\r\n }", "public static base_response unset(nitro_service client, rnatparam resource, String[] args) throws Exception{\n\t\trnatparam unsetresource = new rnatparam();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "private Map<Integer, Integer> getNodeIdToPrimaryCount(Cluster cluster) {\n Map<Integer, Integer> nodeIdToPrimaryCount = Maps.newHashMap();\n for(Node node: cluster.getNodes()) {\n nodeIdToPrimaryCount.put(node.getId(), node.getPartitionIds().size());\n }\n\n return nodeIdToPrimaryCount;\n }", "public EndpointOverride getPath(int pathId, String clientUUID, String[] filters) throws Exception {\n EndpointOverride endpoint = null;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n String queryString = this.getPathSelectString();\n queryString += \" AND \" + Constants.DB_TABLE_PATH + \".\" + Constants.GENERIC_ID + \"=\" + pathId + \";\";\n statement = sqlConnection.prepareStatement(queryString);\n statement.setString(1, clientUUID);\n\n results = statement.executeQuery();\n\n if (results.next()) {\n endpoint = this.getEndpointOverrideFromResultSet(results);\n endpoint.setFilters(filters);\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return endpoint;\n }" ]
Find container env. @param ctx the container context @param dump the exception dump @return valid container or null
[ "protected Container findContainer(ContainerContext ctx, StringBuilder dump) {\n Container container = null;\n // 1. Custom container class\n String containerClassName = ctx.getServletContext().getInitParameter(Container.CONTEXT_PARAM_CONTAINER_CLASS);\n if (containerClassName != null) {\n try {\n Class<Container> containerClass = Reflections.classForName(resourceLoader, containerClassName);\n container = SecurityActions.newInstance(containerClass);\n WeldServletLogger.LOG.containerDetectionSkipped(containerClassName);\n } catch (Exception e) {\n WeldServletLogger.LOG.unableToInstantiateCustomContainerClass(containerClassName);\n WeldServletLogger.LOG.catchingDebug(e);\n }\n }\n if (container == null) {\n // 2. Service providers\n Iterable<Container> extContainers = ServiceLoader.load(Container.class, getClass().getClassLoader());\n container = checkContainers(ctx, dump, extContainers);\n if (container == null) {\n // 3. Built-in containers in predefined order\n container = checkContainers(ctx, dump,\n Arrays.asList(TomcatContainer.INSTANCE, JettyContainer.INSTANCE, UndertowContainer.INSTANCE, GwtDevHostedModeContainer.INSTANCE));\n }\n }\n return container;\n }" ]
[ "public double mean() {\n double total = 0;\n\n final int N = getNumElements();\n for( int i = 0; i < N; i++ ) {\n total += get(i);\n }\n\n return total/N;\n }", "public void setBREE(String bree) {\n\t\tString old = mainAttributes.get(BUNDLE_REQUIREDEXECUTIONENVIRONMENT);\n\t\tif (!bree.equals(old)) {\n\t\t\tthis.mainAttributes.put(BUNDLE_REQUIREDEXECUTIONENVIRONMENT, bree);\n\t\t\tthis.modified = true;\n\t\t\tthis.bree = bree;\n\t\t}\n\t}", "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 boolean perform(Run<?, ?> build, Launcher launcher, TaskListener listener, EnvVars env, FilePath workDir, FilePath tempDir)\n throws InterruptedException, IOException {\n listener.getLogger().println(\"Jenkins Artifactory Plugin version: \" + ActionableHelper.getArtifactoryPluginVersion());\n FilePath mavenHome = getMavenHome(listener, env, launcher);\n\n if (!mavenHome.exists()) {\n listener.getLogger().println(\"Couldn't find Maven home at \" + mavenHome.getRemote() + \" on agent \" + Utils.getAgentName(workDir) +\n \". This could be because this build is running inside a Docker container.\");\n }\n ArgumentListBuilder cmdLine = buildMavenCmdLine(build, listener, env, launcher, mavenHome, workDir, tempDir);\n String[] cmds = cmdLine.toCommandArray();\n return RunMaven(build, launcher, listener, env, workDir, cmds);\n }", "public int evaluate(FieldContainer container)\n {\n //\n // First step - determine the list of criteria we are should use\n //\n List<GraphicalIndicatorCriteria> criteria;\n if (container instanceof Task)\n {\n Task task = (Task) container;\n if (NumberHelper.getInt(task.getUniqueID()) == 0)\n {\n if (m_projectSummaryInheritsFromSummaryRows == false)\n {\n criteria = m_projectSummaryCriteria;\n }\n else\n {\n if (m_summaryRowsInheritFromNonSummaryRows == false)\n {\n criteria = m_summaryRowCriteria;\n }\n else\n {\n criteria = m_nonSummaryRowCriteria;\n }\n }\n }\n else\n {\n if (task.getSummary() == true)\n {\n if (m_summaryRowsInheritFromNonSummaryRows == false)\n {\n criteria = m_summaryRowCriteria;\n }\n else\n {\n criteria = m_nonSummaryRowCriteria;\n }\n }\n else\n {\n criteria = m_nonSummaryRowCriteria;\n }\n }\n }\n else\n {\n // It is possible to have a resource summary row, but at the moment\n // I can't see how you can determine this.\n criteria = m_nonSummaryRowCriteria;\n }\n\n //\n // Now we have the criteria, evaluate each one until we get a result\n //\n int result = -1;\n for (GraphicalIndicatorCriteria gic : criteria)\n {\n result = gic.evaluate(container);\n if (result != -1)\n {\n break;\n }\n }\n\n //\n // If we still don't have a result at the end, return the\n // default value, which is 0\n //\n if (result == -1)\n {\n result = 0;\n }\n\n return (result);\n }", "public Boolean invoke(File pomFile, VirtualChannel channel) throws IOException, InterruptedException {\n\n org.jfrog.build.extractor.maven.reader.ModuleName current = new org.jfrog.build.extractor.maven.reader.ModuleName(\n currentModule.groupId, currentModule.artifactId);\n\n Map<org.jfrog.build.extractor.maven.reader.ModuleName, String> modules = Maps.newLinkedHashMap();\n for (Map.Entry<ModuleName, String> entry : versionsByModule.entrySet()) {\n modules.put(new org.jfrog.build.extractor.maven.reader.ModuleName(\n entry.getKey().groupId, entry.getKey().artifactId), entry.getValue());\n }\n\n org.jfrog.build.extractor.maven.transformer.PomTransformer transformer =\n new org.jfrog.build.extractor.maven.transformer.PomTransformer(current, modules, scmUrl,\n failOnSnapshot);\n\n return transformer.transform(pomFile);\n }", "private EventTypeEnum getEventType(Message message) {\n boolean isRequestor = MessageUtils.isRequestor(message);\n boolean isFault = MessageUtils.isFault(message);\n boolean isOutbound = MessageUtils.isOutbound(message);\n\n //Needed because if it is rest request and method does not exists had better to return Fault\n if(!isFault && isRestMessage(message)) {\n isFault = (message.getExchange().get(\"org.apache.cxf.resource.operation.name\") == null);\n if (!isFault) {\n Integer responseCode = (Integer) message.get(Message.RESPONSE_CODE);\n if (null != responseCode) {\n isFault = (responseCode >= 400);\n }\n }\n }\n if (isOutbound) {\n if (isFault) {\n return EventTypeEnum.FAULT_OUT;\n } else {\n return isRequestor ? EventTypeEnum.REQ_OUT : EventTypeEnum.RESP_OUT;\n }\n } else {\n if (isFault) {\n return EventTypeEnum.FAULT_IN;\n } else {\n return isRequestor ? EventTypeEnum.RESP_IN : EventTypeEnum.REQ_IN;\n }\n }\n }", "public CollectionRequest<Section> findByProject(String project) {\n \n String path = String.format(\"/projects/%s/sections\", project);\n return new CollectionRequest<Section>(this, Section.class, path, \"GET\");\n }", "public long[] append(MessageSet messages) throws IOException {\n checkMutable();\n long written = 0L;\n while (written < messages.getSizeInBytes())\n written += messages.writeTo(channel, 0, messages.getSizeInBytes());\n long beforeOffset = setSize.getAndAdd(written);\n return new long[]{written, beforeOffset};\n }" ]
This method is used to initiate a release staging process using the Artifactory Release Staging API.
[ "@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 }" ]
[ "private static Class<?> extractClass(Class<?> ownerClass, Type arg) {\n\t\tif (arg instanceof ParameterizedType) {\n\t\t\treturn extractClass(ownerClass, ((ParameterizedType) arg).getRawType());\n\t\t}\n\t\telse if (arg instanceof GenericArrayType) {\n\t\t\tGenericArrayType gat = (GenericArrayType) arg;\n\t\t\tType gt = gat.getGenericComponentType();\n\t\t\tClass<?> componentClass = extractClass(ownerClass, gt);\n\t\t\treturn Array.newInstance(componentClass, 0).getClass();\n\t\t}\n\t\telse if (arg instanceof TypeVariable) {\n\t\t\tTypeVariable tv = (TypeVariable) arg;\n\t\t\targ = getTypeVariableMap(ownerClass).get(tv);\n\t\t\tif (arg == null) {\n\t\t\t\targ = extractBoundForTypeVariable(tv);\n\t\t\t\tif (arg instanceof ParameterizedType) {\n\t\t\t\t\treturn extractClass(ownerClass, ((ParameterizedType) arg).getRawType());\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn extractClass(ownerClass, arg);\n\t\t\t}\n\t\t}\n\t\treturn (arg instanceof Class ? (Class) arg : Object.class);\n\t}", "private void sendCloseMessage() {\n\n this.lock(() -> {\n\n TcpChannelHub.this.writeMetaDataForKnownTID(0, outWire, null, 0);\n\n TcpChannelHub.this.outWire.writeDocument(false, w ->\n w.writeEventName(EventId.onClientClosing).text(\"\"));\n\n }, TryLock.LOCK);\n\n // wait up to 1 seconds to receive an close request acknowledgment from the server\n try {\n final boolean await = receivedClosedAcknowledgement.await(1, TimeUnit.SECONDS);\n if (!await)\n if (Jvm.isDebugEnabled(getClass()))\n Jvm.debug().on(getClass(), \"SERVER IGNORED CLOSE REQUEST: shutting down the client anyway as the \" +\n \"server did not respond to the close() request.\");\n } catch (InterruptedException ignore) {\n Thread.currentThread().interrupt();\n }\n }", "public void validate() throws PackagingException {\n if (control == null || !control.isDirectory()) {\n throw new PackagingException(\"The 'control' attribute doesn't point to a directory. \" + control);\n }\n\n if (changesIn != null) {\n\n if (changesIn.exists() && (!changesIn.isFile() || !changesIn.canRead())) {\n throw new PackagingException(\"The 'changesIn' setting needs to point to a readable file. \" + changesIn + \" was not found/readable.\");\n }\n\n if (changesOut != null && !isWritableFile(changesOut)) {\n throw new PackagingException(\"Cannot write the output for 'changesOut' to \" + changesOut);\n }\n\n if (changesSave != null && !isWritableFile(changesSave)) {\n throw new PackagingException(\"Cannot write the output for 'changesSave' to \" + changesSave);\n }\n\n } else {\n if (changesOut != null || changesSave != null) {\n throw new PackagingException(\"The 'changesOut' or 'changesSave' settings may only be used when there is a 'changesIn' specified.\");\n }\n }\n\n if (Compression.toEnum(compression) == null) {\n throw new PackagingException(\"The compression method '\" + compression + \"' is not supported (expected 'none', 'gzip', 'bzip2' or 'xz')\");\n }\n\n if (deb == null) {\n throw new PackagingException(\"You need to specify where the deb file is supposed to be created.\");\n }\n\n getDigestCode(digest);\n }", "synchronized boolean markReadMessageForId(String messageId, String userId){\n if(messageId == null || userId == null) return false;\n\n final String tName = Table.INBOX_MESSAGES.getName();\n try{\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n ContentValues cv = new ContentValues();\n cv.put(IS_READ,1);\n db.update(Table.INBOX_MESSAGES.getName(), cv,_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 }", "private <T extends Index> List<T> listIndexType(String type, Class<T> modelType) {\n List<T> indexesOfType = new ArrayList<T>();\n Gson g = new Gson();\n for (JsonElement index : indexes) {\n if (index.isJsonObject()) {\n JsonObject indexDefinition = index.getAsJsonObject();\n JsonElement indexType = indexDefinition.get(\"type\");\n if (indexType != null && indexType.isJsonPrimitive()) {\n JsonPrimitive indexTypePrimitive = indexType.getAsJsonPrimitive();\n if (type == null || (indexTypePrimitive.isString() && indexTypePrimitive\n .getAsString().equals(type))) {\n indexesOfType.add(g.fromJson(indexDefinition, modelType));\n }\n }\n }\n }\n return indexesOfType;\n }", "public void createOverride(int groupId, String methodName, String className) throws Exception {\n // first make sure this doesn't already exist\n for (Method method : EditService.getInstance().getMethodsFromGroupId(groupId, null)) {\n if (method.getMethodName().equals(methodName) && method.getClassName().equals(className)) {\n // don't add if it already exists in the group\n return;\n }\n }\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n PreparedStatement statement = sqlConnection.prepareStatement(\n \"INSERT INTO \" + Constants.DB_TABLE_OVERRIDE\n + \"(\" + Constants.OVERRIDE_METHOD_NAME\n + \",\" + Constants.OVERRIDE_CLASS_NAME\n + \",\" + Constants.OVERRIDE_GROUP_ID\n + \")\"\n + \" VALUES (?, ?, ?)\"\n );\n statement.setString(1, methodName);\n statement.setString(2, className);\n statement.setInt(3, groupId);\n statement.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n }\n }", "private Serializable doWorkInIsolationTransaction(final SharedSessionContractImplementor session)\n\t\t\tthrows HibernateException {\n\t\tclass Work extends AbstractReturningWork<IntegralDataTypeHolder> {\n\t\t\tprivate final SharedSessionContractImplementor localSession = session;\n\n\t\t\t@Override\n\t\t\tpublic IntegralDataTypeHolder execute(Connection connection) throws SQLException {\n\t\t\t\ttry {\n\t\t\t\t\treturn doWorkInCurrentTransactionIfAny( localSession );\n\t\t\t\t}\n\t\t\t\tcatch ( RuntimeException sqle ) {\n\t\t\t\t\tthrow new HibernateException( \"Could not get or update next value\", sqle );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t//we want to work out of transaction\n\t\tboolean workInTransaction = false;\n\t\tWork work = new Work();\n\t\tSerializable generatedValue = session.getTransactionCoordinator().createIsolationDelegate().delegateWork( work, workInTransaction );\n\t\treturn generatedValue;\n\t}", "public Where<T, ID> or(Where<T, ID> left, Where<T, ID> right, Where<T, ID>... others) {\n\t\tClause[] clauses = buildClauseArray(others, \"OR\");\n\t\tClause secondClause = pop(\"OR\");\n\t\tClause firstClause = pop(\"OR\");\n\t\taddClause(new ManyClause(firstClause, secondClause, clauses, ManyClause.OR_OPERATION));\n\t\treturn this;\n\t}", "public Set<DbLicense> resolveLicenses(List<String> licStrings) {\n Set<DbLicense> result = new HashSet<>();\n\n licStrings\n .stream()\n .map(this::getMatchingLicenses)\n .forEach(result::addAll);\n\n return result;\n }" ]
Compare two versions @param other @return an integer: 0 if equals, -1 if older, 1 if newer @throws IncomparableException is thrown when two versions are not coparable
[ "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}" ]
[ "private Statement createStatement(Connection con, boolean scrollable, int explicitFetchSizeHint)\r\n throws java.sql.SQLException\r\n {\r\n Statement result;\r\n try\r\n {\r\n // if necessary use JDBC1.0 methods\r\n if (!FORCEJDBC1_0)\r\n {\r\n result =\r\n con.createStatement(\r\n scrollable\r\n ? ResultSet.TYPE_SCROLL_INSENSITIVE\r\n : ResultSet.TYPE_FORWARD_ONLY,\r\n ResultSet.CONCUR_READ_ONLY);\r\n afterJdbc2CapableStatementCreate(result, explicitFetchSizeHint);\r\n }\r\n else\r\n {\r\n result = con.createStatement();\r\n }\r\n }\r\n catch (AbstractMethodError err)\r\n {\r\n // if a JDBC1.0 driver is used, the signature\r\n // createStatement(int, int) is not defined.\r\n // we then call the JDBC1.0 variant createStatement()\r\n log.warn(\"Used driver seems not JDBC 2.0 compatible, use the JDBC 1.0 mode\", err);\r\n result = con.createStatement();\r\n FORCEJDBC1_0 = true;\r\n }\r\n catch (SQLException eSql)\r\n {\r\n // there are JDBC Driver that nominally implement JDBC 2.0, but\r\n // throw DriverNotCapableExceptions. If we catch one of these\r\n // we force usage of JDBC 1.0\r\n if (eSql.getClass().getName()\r\n .equals(\"interbase.interclient.DriverNotCapableException\"))\r\n {\r\n log.warn(\"JDBC 2.0 problems with this interbase driver, we use the JDBC 1.0 mode\");\r\n FORCEJDBC1_0 = true;\r\n result = con.createStatement();\r\n }\r\n else\r\n {\r\n throw eSql;\r\n }\r\n }\r\n try\r\n {\r\n platform.afterStatementCreate(result);\r\n }\r\n catch (PlatformException e)\r\n {\r\n log.error(\"Platform dependend failure\", e);\r\n }\r\n return result;\r\n }", "public String getFormattedParentValue()\n {\n String result = null;\n if (m_elements.size() > 2)\n {\n result = joinElements(m_elements.size() - 2);\n }\n return result;\n }", "private static int resolveDomainTimeoutAdder() {\n String propValue = WildFlySecurityManager.getPropertyPrivileged(DOMAIN_TEST_SYSTEM_PROPERTY, DEFAULT_DOMAIN_TIMEOUT_STRING);\n if (sysPropDomainValue == null || !sysPropDomainValue.equals(propValue)) {\n // First call or the system property changed\n sysPropDomainValue = propValue;\n int number = -1;\n try {\n number = Integer.valueOf(sysPropDomainValue);\n } catch (NumberFormatException nfe) {\n // ignored\n }\n\n if (number > 0) {\n defaultDomainValue = number; // this one is in ms\n } else {\n ControllerLogger.MGMT_OP_LOGGER.invalidDefaultBlockingTimeout(sysPropDomainValue, DOMAIN_TEST_SYSTEM_PROPERTY, DEFAULT_DOMAIN_TIMEOUT_ADDER);\n defaultDomainValue = DEFAULT_DOMAIN_TIMEOUT_ADDER;\n }\n }\n return defaultDomainValue;\n }", "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 }", "public List<Dependency> getModuleDependencies(final String moduleId, final FiltersHolder filters){\n final DbModule module = moduleHandler.getModule(moduleId);\n final DbOrganization organization = moduleHandler.getOrganization(module);\n filters.setCorporateFilter(new CorporateFilter(organization));\n\n return getModuleDependencies(module, filters, 1, new ArrayList<String>());\n }", "public static <T> T invokeSetters(final T instance, final Map<String,Object> vars) \n throws ReflectiveOperationException {\n if (instance != null && vars != null) {\n final Class<?> clazz = instance.getClass();\n final Method[] methods = clazz.getMethods();\n for (final Entry<String,Object> entry : vars.entrySet()) {\n final String methodName = \"set\" + entry.getKey().substring(0, 1).toUpperCase(Locale.US) \n + entry.getKey().substring(1);\n boolean found = false;\n for (final Method method : methods) {\n if (methodName.equals(method.getName()) && method.getParameterTypes().length == 1) {\n method.invoke(instance, entry.getValue());\n found = true;\n break;\n }\n }\n if (!found) {\n throw new NoSuchMethodException(\"Expected setter named '\" + methodName \n + \"' for var '\" + entry.getKey() + \"'\");\n }\n }\n }\n return instance;\n }", "public void setPlaying(boolean playing) {\n\n if (this.playing.get() == playing) {\n return;\n }\n\n this.playing.set(playing);\n\n if (playing) {\n metronome.jumpToBeat(whereStopped.get().getBeat());\n if (isSendingStatus()) { // Need to also start the beat sender.\n beatSender.set(new BeatSender(metronome));\n }\n } else {\n final BeatSender activeSender = beatSender.get();\n if (activeSender != null) { // We have a beat sender we need to stop.\n activeSender.shutDown();\n beatSender.set(null);\n }\n whereStopped.set(metronome.getSnapshot());\n }\n }", "public void takeNoteOfGradient(IntDoubleVector gradient) {\n gradient.iterate(new FnIntDoubleToVoid() { \n @Override\n public void call(int index, double value) {\n gradSumSquares[index] += value * value;\n assert !Double.isNaN(gradSumSquares[index]);\n }\n });\n }", "private static void reallyValidatePseudoScopedBean(Bean<?> bean, BeanManagerImpl beanManager, Set<Object> dependencyPath, Set<Bean<?>> validatedBeans) {\n // see if we have already seen this bean in the dependency path\n if (dependencyPath.contains(bean)) {\n // create a list that shows the path to the bean\n List<Object> realDependencyPath = new ArrayList<Object>(dependencyPath);\n realDependencyPath.add(bean);\n throw ValidatorLogger.LOG.pseudoScopedBeanHasCircularReferences(WeldCollections.toMultiRowString(realDependencyPath));\n }\n if (validatedBeans.contains(bean)) {\n return;\n }\n dependencyPath.add(bean);\n for (InjectionPoint injectionPoint : bean.getInjectionPoints()) {\n if (!injectionPoint.isDelegate()) {\n dependencyPath.add(injectionPoint);\n validatePseudoScopedInjectionPoint(injectionPoint, beanManager, dependencyPath, validatedBeans);\n dependencyPath.remove(injectionPoint);\n }\n }\n if (bean instanceof DecorableBean<?>) {\n final List<Decorator<?>> decorators = Reflections.<DecorableBean<?>>cast(bean).getDecorators();\n if (!decorators.isEmpty()) {\n for (final Decorator<?> decorator : decorators) {\n reallyValidatePseudoScopedBean(decorator, beanManager, dependencyPath, validatedBeans);\n }\n }\n }\n if (bean instanceof AbstractProducerBean<?, ?, ?> && !(bean instanceof EEResourceProducerField<?, ?>)) {\n AbstractProducerBean<?, ?, ?> producer = (AbstractProducerBean<?, ?, ?>) bean;\n if (!beanManager.isNormalScope(producer.getDeclaringBean().getScope()) && !producer.getAnnotated().isStatic()) {\n reallyValidatePseudoScopedBean(producer.getDeclaringBean(), beanManager, dependencyPath, validatedBeans);\n }\n }\n validatedBeans.add(bean);\n dependencyPath.remove(bean);\n }" ]
Convert a Java String instance into the equivalent array of single or double bytes. @param value Java String instance representing text @param unicode true if double byte characters are required @return byte array representing the supplied text
[ "private byte[] getBytes(String value, boolean unicode)\n {\n byte[] result;\n if (unicode)\n {\n int start = 0;\n // Get the bytes in UTF-16\n byte[] bytes;\n\n try\n {\n bytes = value.getBytes(\"UTF-16\");\n }\n catch (UnsupportedEncodingException e)\n {\n bytes = value.getBytes();\n }\n\n if (bytes.length > 2 && bytes[0] == -2 && bytes[1] == -1)\n {\n // Skip the unicode identifier\n start = 2;\n }\n result = new byte[bytes.length - start];\n for (int loop = start; loop < bytes.length - 1; loop += 2)\n {\n // Swap the order here\n result[loop - start] = bytes[loop + 1];\n result[loop + 1 - start] = bytes[loop];\n }\n }\n else\n {\n result = new byte[value.length() + 1];\n System.arraycopy(value.getBytes(), 0, result, 0, value.length());\n }\n return (result);\n }" ]
[ "@Override\n public void onRotationSensor(long timeStamp, float rotationW, float rotationX, float rotationY, float rotationZ,\n float gyroX, float gyroY, float gyroZ) {\n GVRCameraRig cameraRig = null;\n if (mMainScene != null) {\n cameraRig = mMainScene.getMainCameraRig();\n }\n\n if (cameraRig != null) {\n cameraRig.setRotationSensorData(timeStamp, rotationW, rotationX, rotationY, rotationZ, gyroX, gyroY, gyroZ);\n updateSensoredScene();\n }\n }", "public float getPositionY(int vertex) {\n if (!hasPositions()) {\n throw new IllegalStateException(\"mesh has no positions\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_vertices.getFloat((vertex * 3 + 1) * SIZEOF_FLOAT);\n }", "private void checkExtents(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n HashMap processedClasses = new HashMap();\r\n InheritanceHelper helper = new InheritanceHelper();\r\n ClassDescriptorDef curExtent;\r\n boolean canBeRemoved;\r\n\r\n for (Iterator it = classDef.getExtentClasses(); it.hasNext();)\r\n {\r\n curExtent = (ClassDescriptorDef)it.next();\r\n canBeRemoved = false;\r\n if (classDef.getName().equals(curExtent.getName()))\r\n {\r\n throw new ConstraintException(\"The class \"+classDef.getName()+\" specifies itself as an extent-class\");\r\n }\r\n else if (processedClasses.containsKey(curExtent))\r\n {\r\n canBeRemoved = true;\r\n }\r\n else\r\n {\r\n try\r\n {\r\n if (!helper.isSameOrSubTypeOf(curExtent, classDef.getName(), false))\r\n {\r\n throw new ConstraintException(\"The class \"+classDef.getName()+\" specifies an extent-class \"+curExtent.getName()+\" that is not a sub-type of it\");\r\n }\r\n // now we check whether we already have an extent for a base-class of this extent-class\r\n for (Iterator processedIt = processedClasses.keySet().iterator(); processedIt.hasNext();)\r\n {\r\n if (helper.isSameOrSubTypeOf(curExtent, ((ClassDescriptorDef)processedIt.next()).getName(), false))\r\n {\r\n canBeRemoved = true;\r\n break;\r\n }\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n // won't happen because we don't use lookup of the actual classes\r\n }\r\n }\r\n if (canBeRemoved)\r\n {\r\n it.remove();\r\n }\r\n processedClasses.put(curExtent, null);\r\n }\r\n }", "public void writeNameValuePair(String name, String value) throws IOException\n {\n internalWriteNameValuePair(name, escapeString(value));\n }", "public void removeEntity(GraphDatabaseService executionEngine, Object[] columnValues) {\n\t\tMap<String, Object> params = params( columnValues );\n\t\texecutionEngine.execute( getRemoveEntityQuery(), params );\n\t}", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<JulianDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<JulianDate>) super.localDateTime(temporal);\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 }", "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 PBKey getPBKey()\r\n {\r\n if (pbKey == null)\r\n {\r\n this.pbKey = new PBKey(this.getJcdAlias(), this.getUserName(), this.getPassWord());\r\n }\r\n return pbKey;\r\n }" ]
Throws an exception if at least one results directory is missing.
[ "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 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 void run() {\r\n\t\tConnectionHandle connection = null;\r\n\t\tlong tmp;\r\n\t\tlong nextCheckInMs = this.maxAgeInMs;\r\n\r\n\t\tint partitionSize= this.partition.getAvailableConnections();\r\n\t\tlong currentTime = System.currentTimeMillis();\r\n\t\tfor (int i=0; i < partitionSize; i++){\r\n\t\t\ttry {\r\n\t\t\t\tconnection = this.partition.getFreeConnections().poll();\r\n\r\n\t\t\t\tif (connection != null){\r\n\t\t\t\t\tconnection.setOriginatingPartition(this.partition);\r\n\r\n\t\t\t\t\ttmp = this.maxAgeInMs - (currentTime - connection.getConnectionCreationTimeInMs()); \r\n\r\n\t\t\t\t\tif (tmp < nextCheckInMs){\r\n\t\t\t\t\t\tnextCheckInMs = tmp; \r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif (connection.isExpired(currentTime)){\r\n\t\t\t\t\t\t// kill off this connection\r\n\t\t\t\t\t\tcloseConnection(connection);\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t}\r\n\r\n\r\n\t\t\t\t\t\r\n\t\t\t\t\tif (this.lifoMode){\r\n\t\t\t\t\t\t// we can't put it back normally or it will end up in front again.\r\n\t\t\t\t\t\tif (!(connection.getOriginatingPartition().getFreeConnections().offer(connection))){\r\n\t\t\t\t\t\t\tconnection.internalClose();\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tthis.pool.putConnectionBackInPartition(connection);\r\n\t\t\t\t\t}\r\n\r\n\r\n\t\t\t\t\tThread.sleep(20L); // test slowly, this is not an operation that we're in a hurry to deal with (avoid CPU spikes)...\r\n\t\t\t\t}\r\n\t\t\t} catch (Throwable e) {\r\n\t\t\t\t\tlogger.error(\"Connection max age thread exception.\", e);\r\n\t\t\t}\r\n\r\n\t\t} // throw it back on the queue\r\n\r\n\t}", "private void applyAliases()\n {\n CustomFieldContainer fields = m_projectFile.getCustomFields();\n for (Map.Entry<FieldType, String> entry : ALIASES.entrySet())\n {\n fields.getCustomField(entry.getKey()).setAlias(entry.getValue());\n }\n }", "static void i(String message){\n if (getStaticDebugLevel() >= CleverTapAPI.LogLevel.INFO.intValue()){\n Log.i(Constants.CLEVERTAP_LOG_TAG,message);\n }\n }", "public void retrieveReferences(Object newObj, ClassDescriptor cld, boolean forced) throws PersistenceBrokerException\r\n {\r\n Iterator i = cld.getObjectReferenceDescriptors().iterator();\r\n\r\n // turn off auto prefetching for related proxies\r\n final Class saveClassToPrefetch = classToPrefetch;\r\n classToPrefetch = null;\r\n\r\n pb.getInternalCache().enableMaterializationCache();\r\n try\r\n {\r\n while (i.hasNext())\r\n {\r\n ObjectReferenceDescriptor rds = (ObjectReferenceDescriptor) i.next();\r\n retrieveReference(newObj, cld, rds, forced);\r\n }\r\n\r\n pb.getInternalCache().disableMaterializationCache();\r\n }\r\n catch(RuntimeException e)\r\n {\r\n pb.getInternalCache().doLocalClear();\r\n throw e;\r\n }\r\n finally\r\n {\r\n classToPrefetch = saveClassToPrefetch;\r\n }\r\n }", "@Subscribe\n @SuppressForbidden(\"legitimate printStackTrace().\")\n public void onSuiteResult(AggregatedSuiteResultEvent e) {\n try {\n if (jsonWriter == null)\n return;\n\n slaves.put(e.getSlave().id, e.getSlave());\n e.serialize(jsonWriter, outputStreams);\n } catch (Exception ex) {\n ex.printStackTrace();\n junit4.log(\"Error serializing to JSON file: \"\n + Throwables.getStackTraceAsString(ex), Project.MSG_WARN);\n if (jsonWriter != null) {\n try {\n jsonWriter.close();\n } catch (Throwable ignored) {\n // Ignore.\n } finally {\n jsonWriter = null;\n }\n }\n }\n }", "private void sendEvents(final List<Event> events) {\n if (null != handlers) {\n for (EventHandler current : handlers) {\n for (Event event : events) {\n current.handleEvent(event);\n }\n }\n }\n\n LOG.info(\"Put events(\" + events.size() + \") to Monitoring Server.\");\n\n try {\n if (sendToEventadmin) {\n EventAdminPublisher.publish(events);\n } else {\n monitoringServiceClient.putEvents(events);\n }\n } catch (MonitoringException e) {\n throw e;\n } catch (Exception e) {\n throw new MonitoringException(\"002\",\n \"Unknown error while execute put events to Monitoring Server\", e);\n }\n\n }", "public WaveformDetail requestWaveformDetailFrom(final DataReference dataReference) {\n ensureRunning();\n for (WaveformDetail cached : detailHotCache.values()) {\n if (cached.dataReference.equals(dataReference)) { // Found a hot cue hit, use it.\n return cached;\n }\n }\n return requestDetailInternal(dataReference, false);\n }", "private 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 }" ]
Find the channel in the animation that animates the named bone. @param boneName name of bone to animate.
[ "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 }" ]
[ "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 }", "@NonNull\n @Override\n public Loader<SortedList<File>> getLoader() {\n return new AsyncTaskLoader<SortedList<File>>(getActivity()) {\n\n FileObserver fileObserver;\n\n @Override\n public SortedList<File> loadInBackground() {\n File[] listFiles = mCurrentPath.listFiles();\n final int initCap = listFiles == null ? 0 : listFiles.length;\n\n SortedList<File> files = new SortedList<>(File.class, new SortedListAdapterCallback<File>(getDummyAdapter()) {\n @Override\n public int compare(File lhs, File rhs) {\n return compareFiles(lhs, rhs);\n }\n\n @Override\n public boolean areContentsTheSame(File file, File file2) {\n return file.getAbsolutePath().equals(file2.getAbsolutePath()) && (file.isFile() == file2.isFile());\n }\n\n @Override\n public boolean areItemsTheSame(File file, File file2) {\n return areContentsTheSame(file, file2);\n }\n }, initCap);\n\n\n files.beginBatchedUpdates();\n if (listFiles != null) {\n for (java.io.File f : listFiles) {\n if (isItemVisible(f)) {\n files.add(f);\n }\n }\n }\n files.endBatchedUpdates();\n\n return files;\n }\n\n /**\n * Handles a request to start the Loader.\n */\n @Override\n protected void onStartLoading() {\n super.onStartLoading();\n\n // handle if directory does not exist. Fall back to root.\n if (mCurrentPath == null || !mCurrentPath.isDirectory()) {\n mCurrentPath = getRoot();\n }\n\n // Start watching for changes\n fileObserver = new FileObserver(mCurrentPath.getPath(),\n FileObserver.CREATE |\n FileObserver.DELETE\n | FileObserver.MOVED_FROM | FileObserver.MOVED_TO\n ) {\n\n @Override\n public void onEvent(int event, String path) {\n // Reload\n onContentChanged();\n }\n };\n fileObserver.startWatching();\n\n forceLoad();\n }\n\n /**\n * Handles a request to completely reset the Loader.\n */\n @Override\n protected void onReset() {\n super.onReset();\n\n // Stop watching\n if (fileObserver != null) {\n fileObserver.stopWatching();\n fileObserver = null;\n }\n }\n };\n }", "public Object getObjectByIdentity(Identity id)\r\n throws PersistenceBrokerException\r\n {\r\n checkOpen();\r\n ObjectEnvelope envelope = objectEnvelopeTable.getByIdentity(id);\r\n if (envelope != null)\r\n {\r\n return (envelope.needsDelete() ? null : envelope.getObject());\r\n }\r\n else\r\n {\r\n return getBroker().getObjectByIdentity(id);\r\n }\r\n }", "public boolean checkContains(String uri, String[] patterns) {\n\t\tfor (String pattern : patterns) {\n\t\t\tif (pattern.length() > 0) {\n\t\t\t\tif (uri.contains(pattern)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "public void setOnKeyboardDone(final IntlPhoneInputListener listener) {\n mPhoneEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n @Override\n public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {\n if (actionId == EditorInfo.IME_ACTION_DONE) {\n listener.done(IntlPhoneInput.this, isValid());\n }\n return false;\n }\n });\n }", "private void createStringMappings(MtasTokenIdFactory mtasTokenIdFactory,\n Level level, String stringValue, int offsetStart, int offsetEnd,\n int position) throws IOException {\n // System.out.println(\"createStringMappings string \");\n String[] stringValues = MtasPennTreebankReader.createStrings(stringValue,\n Pattern.quote(STRING_SPLITTER));\n if (stringValues.length > 0 && !stringValues[0].trim().isEmpty()) {\n MtasToken token = new MtasTokenString(mtasTokenIdFactory.createTokenId(),\n \"t\", filterString(stringValues[0].trim()), position);\n token.setOffset(offsetStart, offsetEnd);\n tokenCollection.add(token);\n level.tokens.add(token);\n }\n if (stringValues.length > 1 && !stringValues[1].trim().isEmpty()) {\n MtasToken token = new MtasTokenString(mtasTokenIdFactory.createTokenId(),\n \"lemma\", filterString(stringValues[1].trim()), position);\n token.setOffset(offsetStart, offsetEnd);\n tokenCollection.add(token);\n level.tokens.add(token);\n }\n }", "public static ipset get(nitro_service service, String name) throws Exception{\n\t\tipset obj = new ipset();\n\t\tobj.set_name(name);\n\t\tipset response = (ipset) obj.get_resource(service);\n\t\treturn response;\n\t}", "public void extractFieldTypes(DatabaseType databaseType) throws SQLException {\n\t\tif (fieldTypes == null) {\n\t\t\tif (fieldConfigs == null) {\n\t\t\t\tfieldTypes = extractFieldTypes(databaseType, dataClass, tableName);\n\t\t\t} else {\n\t\t\t\tfieldTypes = convertFieldConfigs(databaseType, tableName, fieldConfigs);\n\t\t\t}\n\t\t}\n\t}", "public static ModelNode validateRequest(CommandContext ctx, ModelNode request) throws CommandFormatException {\n\n final Set<String> keys = request.keys();\n if (keys.size() == 2) { // no props\n return null;\n }\n ModelNode outcome = (ModelNode) ctx.get(Scope.REQUEST, DESCRIPTION_RESPONSE);\n if (outcome == null) {\n outcome = retrieveDescription(ctx, request, true);\n if (outcome == null) {\n return null;\n } else {\n ctx.set(Scope.REQUEST, DESCRIPTION_RESPONSE, outcome);\n }\n }\n if(!outcome.has(Util.RESULT)) {\n throw new CommandFormatException(\"Failed to perform \" + Util.READ_OPERATION_DESCRIPTION + \" to validate the request: result is not available.\");\n }\n\n final String operationName = request.get(Util.OPERATION).asString();\n\n final ModelNode result = outcome.get(Util.RESULT);\n final Set<String> definedProps = result.hasDefined(Util.REQUEST_PROPERTIES) ? result.get(Util.REQUEST_PROPERTIES).keys() : Collections.emptySet();\n if(definedProps.isEmpty()) {\n if(!(keys.size() == 3 && keys.contains(Util.OPERATION_HEADERS))) {\n throw new CommandFormatException(\"Operation '\" + operationName + \"' does not expect any property.\");\n }\n } else {\n int skipped = 0;\n for(String prop : keys) {\n if(skipped < 2 && (prop.equals(Util.ADDRESS) || prop.equals(Util.OPERATION))) {\n ++skipped;\n continue;\n }\n if(!definedProps.contains(prop)) {\n if(!Util.OPERATION_HEADERS.equals(prop)) {\n throw new CommandFormatException(\"'\" + prop + \"' is not found among the supported properties: \" + definedProps);\n }\n }\n }\n }\n return outcome;\n }" ]
Post boolean flag "DO_NOT_USE" to an artifact @param gavc @param doNotUse @param user @param password @throws GrapesCommunicationException
[ "public void postDoNotUseArtifact(final String gavc, final Boolean doNotUse, final String user, final String password) throws GrapesCommunicationException, AuthenticationException {\n final Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getDoNotUseArtifact(gavc));\n final ClientResponse response = resource.queryParam(ServerAPI.DO_NOT_USE, doNotUse.toString())\n .accept(MediaType.APPLICATION_JSON).post(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = \"Failed to post do not use artifact\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n }" ]
[ "protected boolean _load ()\r\n {\r\n java.sql.ResultSet rs = null;\r\n try\r\n {\r\n \r\n // This synchronization is necessary for Oracle JDBC drivers 8.1.7, 9.0.1, 9.2.0.1\r\n // The documentation says synchronization is done within the driver, but they\r\n // must have overlooked something. Without the lock we'd get mysterious error\r\n // messages. \r\n synchronized(getDbMeta())\r\n {\r\n \r\n getDbMetaTreeModel().setStatusBarMessage(\"Reading schemas for catalog \" \r\n + this.getAttribute(ATT_CATALOG_NAME));\r\n rs = getDbMeta().getSchemas();\r\n final java.util.ArrayList alNew = new java.util.ArrayList();\r\n int count = 0;\r\n while (rs.next())\r\n {\r\n getDbMetaTreeModel().setStatusBarMessage(\"Creating schema \" + getCatalogName() + \".\" + rs.getString(\"TABLE_SCHEM\"));\r\n alNew.add(new DBMetaSchemaNode(getDbMeta(),\r\n getDbMetaTreeModel(),\r\n DBMetaCatalogNode.this, \r\n rs.getString(\"TABLE_SCHEM\")));\r\n count++;\r\n }\r\n if (count == 0) \r\n alNew.add(new DBMetaSchemaNode(getDbMeta(), \r\n getDbMetaTreeModel(),\r\n DBMetaCatalogNode.this, null));\r\n alChildren = alNew; \r\n javax.swing.SwingUtilities.invokeLater(new Runnable()\r\n {\r\n public void run()\r\n {\r\n getDbMetaTreeModel().nodeStructureChanged(DBMetaCatalogNode.this);\r\n }\r\n });\r\n rs.close();\r\n }\r\n }\r\n catch (java.sql.SQLException sqlEx)\r\n {\r\n getDbMetaTreeModel().reportSqlError(\"Error retrieving schemas\", sqlEx);\r\n try\r\n {\r\n if (rs != null) rs.close ();\r\n }\r\n catch (java.sql.SQLException sqlEx2)\r\n {\r\n this.getDbMetaTreeModel().reportSqlError(\"Error retrieving schemas\", sqlEx2);\r\n } \r\n return false;\r\n }\r\n return true;\r\n }", "private static boolean containsObject(Object searchFor, Object[] searchIn)\r\n {\r\n for (int i = 0; i < searchIn.length; i++)\r\n {\r\n if (searchFor == searchIn[i])\r\n {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }", "public ActionContext applyContentType(Result result) {\n if (!result.status().isError()) {\n return applyContentType();\n }\n return applyContentType(contentTypeForErrorResult(req()));\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 }", "private <T extends TimephasedItem<?>> int getStartIndex(DateRange range, List<T> assignments, int startIndex)\n {\n int result = -1;\n if (assignments != null)\n {\n long rangeStart = range.getStart().getTime();\n long rangeEnd = range.getEnd().getTime();\n\n for (int loop = startIndex; loop < assignments.size(); loop++)\n {\n T assignment = assignments.get(loop);\n int compareResult = DateHelper.compare(assignment.getStart(), assignment.getFinish(), rangeStart);\n\n //\n // The start of the target range falls after the assignment end -\n // move on to test the next assignment.\n //\n if (compareResult > 0)\n {\n continue;\n }\n\n //\n // The start of the target range falls within the assignment -\n // return the index of this assignment to the caller.\n //\n if (compareResult == 0)\n {\n result = loop;\n break;\n }\n\n //\n // At this point, we know that the start of the target range is before\n // the assignment start. We need to determine if the end of the\n // target range overlaps the assignment.\n //\n compareResult = DateHelper.compare(assignment.getStart(), assignment.getFinish(), rangeEnd);\n if (compareResult >= 0)\n {\n result = loop;\n break;\n }\n }\n }\n return result;\n }", "@Override\n public boolean decompose(DMatrixRBlock A) {\n if( A.numCols != A.numRows )\n throw new IllegalArgumentException(\"A must be square\");\n\n this.T = A;\n\n if( lower )\n return decomposeLower();\n else\n return decomposeUpper();\n }", "private void processRemarks(GanttDesignerRemark remark)\n {\n for (GanttDesignerRemark.Task remarkTask : remark.getTask())\n {\n Integer id = remarkTask.getRow();\n Task task = m_projectFile.getTaskByID(id);\n String notes = task.getNotes();\n if (notes.isEmpty())\n {\n notes = remarkTask.getContent();\n }\n else\n {\n notes = notes + '\\n' + remarkTask.getContent();\n }\n task.setNotes(notes);\n }\n }", "void merge(Archetype flatParent, Archetype specialized) {\n expandAttributeNodes(specialized.getDefinition());\n\n flattenCObject(RmPath.ROOT, null, flatParent.getDefinition(), specialized.getDefinition());\n\n\n mergeOntologies(flatParent.getTerminology(), specialized.getTerminology());\n if (flatParent.getAnnotations() != null) {\n if (specialized.getAnnotations() == null) {\n specialized.setAnnotations(new ResourceAnnotations());\n }\n annotationsMerger.merge(flatParent.getAnnotations().getItems(), specialized.getAnnotations().getItems());\n }\n }", "private String formatConstraintType(ConstraintType type)\n {\n return (type == null ? null : LocaleData.getStringArray(m_locale, LocaleData.CONSTRAINT_TYPES)[type.getValue()]);\n }" ]
Convert a string value into the appropriate Java field value.
[ "public Object convertStringToJavaField(String value, int columnPos) throws SQLException {\n\t\tif (value == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn fieldConverter.resultStringToJava(this, value, columnPos);\n\t\t}\n\t}" ]
[ "private void appendClazzColumnForSelect(StringBuffer buf)\r\n {\r\n ClassDescriptor cld = getSearchClassDescriptor();\r\n ClassDescriptor[] clds = getMultiJoinedClassDescriptors(cld);\r\n\r\n if (clds.length == 0)\r\n {\r\n return;\r\n }\r\n \r\n buf.append(\",CASE\");\r\n\r\n for (int i = clds.length; i > 0; i--)\r\n {\r\n buf.append(\" WHEN \");\r\n\r\n ClassDescriptor subCld = clds[i - 1];\r\n FieldDescriptor[] fieldDescriptors = subCld.getPkFields();\r\n\r\n TableAlias alias = getTableAliasForClassDescriptor(subCld);\r\n for (int j = 0; j < fieldDescriptors.length; j++)\r\n {\r\n FieldDescriptor field = fieldDescriptors[j];\r\n if (j > 0)\r\n {\r\n buf.append(\" AND \");\r\n }\r\n appendColumn(alias, field, buf);\r\n buf.append(\" IS NOT NULL\");\r\n }\r\n buf.append(\" THEN '\").append(subCld.getClassNameOfObject()).append(\"'\");\r\n }\r\n buf.append(\" ELSE '\").append(cld.getClassNameOfObject()).append(\"'\");\r\n buf.append(\" END AS \" + SqlHelper.OJB_CLASS_COLUMN);\r\n }", "@Override\n public JulianDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }", "@Deprecated\r\n public Category browse(String catId) throws FlickrException {\r\n List<Subcategory> subcategories = new ArrayList<Subcategory>();\r\n List<Group> groups = new ArrayList<Group>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_BROWSE);\r\n\r\n if (catId != null) {\r\n parameters.put(\"cat_id\", catId);\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element categoryElement = response.getPayload();\r\n\r\n Category category = new Category();\r\n category.setName(categoryElement.getAttribute(\"name\"));\r\n category.setPath(categoryElement.getAttribute(\"path\"));\r\n category.setPathIds(categoryElement.getAttribute(\"pathids\"));\r\n\r\n NodeList subcatNodes = categoryElement.getElementsByTagName(\"subcat\");\r\n for (int i = 0; i < subcatNodes.getLength(); i++) {\r\n Element node = (Element) subcatNodes.item(i);\r\n Subcategory subcategory = new Subcategory();\r\n subcategory.setId(Integer.parseInt(node.getAttribute(\"id\")));\r\n subcategory.setName(node.getAttribute(\"name\"));\r\n subcategory.setCount(Integer.parseInt(node.getAttribute(\"count\")));\r\n\r\n subcategories.add(subcategory);\r\n }\r\n\r\n NodeList groupNodes = categoryElement.getElementsByTagName(\"group\");\r\n for (int i = 0; i < groupNodes.getLength(); i++) {\r\n Element node = (Element) groupNodes.item(i);\r\n Group group = new Group();\r\n group.setId(node.getAttribute(\"nsid\"));\r\n group.setName(node.getAttribute(\"name\"));\r\n group.setMembers(node.getAttribute(\"members\"));\r\n\r\n groups.add(group);\r\n }\r\n\r\n category.setGroups(groups);\r\n category.setSubcategories(subcategories);\r\n\r\n return category;\r\n }", "private Constructor<T> findNoArgConstructor(Class<T> dataClass) {\n\t\tConstructor<T>[] constructors;\n\t\ttry {\n\t\t\t@SuppressWarnings(\"unchecked\")\n\t\t\tConstructor<T>[] consts = (Constructor<T>[]) dataClass.getDeclaredConstructors();\n\t\t\t// i do this [grossness] to be able to move the Suppress inside the method\n\t\t\tconstructors = consts;\n\t\t} catch (Exception e) {\n\t\t\tthrow new IllegalArgumentException(\"Can't lookup declared constructors for \" + dataClass, e);\n\t\t}\n\t\tfor (Constructor<T> con : constructors) {\n\t\t\tif (con.getParameterTypes().length == 0) {\n\t\t\t\tif (!con.isAccessible()) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tcon.setAccessible(true);\n\t\t\t\t\t} catch (SecurityException e) {\n\t\t\t\t\t\tthrow new IllegalArgumentException(\"Could not open access to constructor for \" + dataClass);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn con;\n\t\t\t}\n\t\t}\n\t\tif (dataClass.getEnclosingClass() == null) {\n\t\t\tthrow new IllegalArgumentException(\"Can't find a no-arg constructor for \" + dataClass);\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Can't find a no-arg constructor for \" + dataClass + \". Missing static on inner class?\");\n\t\t}\n\t}", "@Override\n\tpublic String toFullString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = getStringCache().fullString) == null) {\n\t\t\tgetStringCache().fullString = result = toNormalizedString(IPv6StringCache.fullParams);\n\t\t}\n\t\treturn result;\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 }", "public void updateIteratorPosition(int length) {\n if(length > 0) {\n //make sure we dont go OB\n if((length + character) > parsedLine.line().length())\n length = parsedLine.line().length() - character;\n\n //move word counter to the correct word\n while(hasNextWord() &&\n (length + character) >= parsedLine.words().get(word).lineIndex() +\n parsedLine.words().get(word).word().length())\n word++;\n\n character = length + character;\n }\n else\n throw new IllegalArgumentException(\"The length given must be > 0 and not exceed the boundary of the line (including the current position)\");\n }", "public List<ServerRedirect> deleteServerMapping(int serverMappingId) {\n ArrayList<ServerRedirect> servers = new ArrayList<ServerRedirect>();\n try {\n JSONArray serverArray = new JSONArray(doDelete(BASE_SERVER + \"/\" + serverMappingId, null));\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\n return servers;\n }", "public FieldDescriptor getAutoIncrementField()\r\n {\r\n if (m_autoIncrementField == null)\r\n {\r\n FieldDescriptor[] fds = getPkFields();\r\n\r\n for (int i = 0; i < fds.length; i++)\r\n {\r\n FieldDescriptor fd = fds[i];\r\n if (fd.isAutoIncrement())\r\n {\r\n m_autoIncrementField = fd;\r\n break;\r\n }\r\n }\r\n }\r\n if (m_autoIncrementField == null)\r\n {\r\n LoggerFactory.getDefaultLogger().warn(\r\n this.getClass().getName()\r\n + \": \"\r\n + \"Could not find autoincrement attribute for class: \"\r\n + this.getClassNameOfObject());\r\n }\r\n return m_autoIncrementField;\r\n }" ]
This method extracts byte arrays from the embedded object data and converts them into RTFEmbeddedObject instances, which it then adds to the supplied list. @param offset offset into the RTF document @param text RTF document @param objects destination for RTFEmbeddedObject instances @return new offset into the RTF document
[ "private static int readObjectData(int offset, String text, List<RTFEmbeddedObject> objects)\n {\n LinkedList<byte[]> blocks = new LinkedList<byte[]>();\n\n offset += (OBJDATA.length());\n offset = skipEndOfLine(text, offset);\n int length;\n int lastOffset = offset;\n\n while (offset != -1)\n {\n length = getBlockLength(text, offset);\n lastOffset = readDataBlock(text, offset, length, blocks);\n offset = skipEndOfLine(text, lastOffset);\n }\n\n RTFEmbeddedObject headerObject;\n RTFEmbeddedObject dataObject;\n\n while (blocks.isEmpty() == false)\n {\n headerObject = new RTFEmbeddedObject(blocks, 2);\n objects.add(headerObject);\n\n if (blocks.isEmpty() == false)\n {\n dataObject = new RTFEmbeddedObject(blocks, headerObject.getTypeFlag2());\n objects.add(dataObject);\n }\n }\n\n return (lastOffset);\n }" ]
[ "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 }", "public Date getPreviousWorkFinish(Date date)\n {\n Calendar cal = Calendar.getInstance();\n cal.setTime(date);\n updateToPreviousWorkFinish(cal);\n return cal.getTime();\n }", "public static DesignDocument fromFile(File file) throws FileNotFoundException {\r\n assertNotEmpty(file, \"Design js file\");\r\n DesignDocument designDocument;\r\n Gson gson = new Gson();\r\n InputStreamReader reader = null;\r\n try {\r\n reader = new InputStreamReader(new FileInputStream(file),\"UTF-8\");\r\n //Deserialize JS file contents into DesignDocument object\r\n designDocument = gson.fromJson(reader, DesignDocument.class);\r\n return designDocument;\r\n } catch (UnsupportedEncodingException e) {\r\n //UTF-8 should be supported on all JVMs\r\n throw new RuntimeException(e);\r\n } finally {\r\n IOUtils.closeQuietly(reader);\r\n }\r\n }", "public FindByIndexOptions useIndex(String designDocument, String indexName) {\r\n assertNotNull(designDocument, \"designDocument\");\r\n assertNotNull(indexName, \"indexName\");\r\n JsonArray index = new JsonArray();\r\n index.add(new JsonPrimitive(designDocument));\r\n index.add(new JsonPrimitive(indexName));\r\n this.useIndex = index;\r\n return this;\r\n }", "public Object convertJavaFieldToSqlArgValue(Object fieldVal) throws SQLException {\n\t\t/*\n\t\t * Limitation here. Some people may want to override the null with their own value in the converter but we\n\t\t * currently don't allow that. Specifying a default value I guess is a better mechanism.\n\t\t */\n\t\tif (fieldVal == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn fieldConverter.javaToSqlArg(this, fieldVal);\n\t\t}\n\t}", "private static boolean syncWithMaster(final Resource domain, final PathElement hostElement) {\n final Resource host = domain.getChild(hostElement);\n assert host != null;\n\n final Set<String> profiles = new HashSet<>();\n final Set<String> serverGroups = new HashSet<>();\n final Set<String> socketBindings = new HashSet<>();\n\n for (final Resource.ResourceEntry serverConfig : host.getChildren(SERVER_CONFIG)) {\n final ModelNode model = serverConfig.getModel();\n final String group = model.require(GROUP).asString();\n if (!serverGroups.contains(group)) {\n serverGroups.add(group);\n }\n if (model.hasDefined(SOCKET_BINDING_GROUP)) {\n processSocketBindingGroup(domain, model.require(SOCKET_BINDING_GROUP).asString(), socketBindings);\n }\n\n }\n\n // process referenced server-groups\n for (final Resource.ResourceEntry serverGroup : domain.getChildren(SERVER_GROUP)) {\n // If we have an unreferenced server-group\n if (!serverGroups.remove(serverGroup.getName())) {\n return true;\n }\n final ModelNode model = serverGroup.getModel();\n\n final String profile = model.require(PROFILE).asString();\n // Process the profile\n processProfile(domain, profile, profiles);\n // Process the socket-binding-group\n processSocketBindingGroup(domain, model.require(SOCKET_BINDING_GROUP).asString(), socketBindings);\n }\n // If we are missing a server group\n if (!serverGroups.isEmpty()) {\n return true;\n }\n // Process profiles\n for (final Resource.ResourceEntry profile : domain.getChildren(PROFILE)) {\n // We have an unreferenced profile\n if (!profiles.remove(profile.getName())) {\n return true;\n }\n }\n // We are missing a profile\n if (!profiles.isEmpty()) {\n return true;\n }\n // Process socket-binding groups\n for (final Resource.ResourceEntry socketBindingGroup : domain.getChildren(SOCKET_BINDING_GROUP)) {\n // We have an unreferenced socket-binding group\n if (!socketBindings.remove(socketBindingGroup.getName())) {\n return true;\n }\n }\n // We are missing a socket-binding group\n if (!socketBindings.isEmpty()) {\n return true;\n }\n // Looks good!\n return false;\n }", "protected boolean closeAtomically() {\n if (isClosed.compareAndSet(false, true)) {\n Closeable.closeQuietly(networkStatsListener);\n return true;\n } else {\n //was already closed.\n return false;\n }\n }", "public GeoShapeMapper transform(GeoTransformation... transformations) {\n if (this.transformations == null) {\n this.transformations = Arrays.asList(transformations);\n } else {\n this.transformations.addAll(Arrays.asList(transformations));\n }\n return this;\n }", "public ResourceAssignment addResourceAssignment(Resource resource)\n {\n ResourceAssignment assignment = getExistingResourceAssignment(resource);\n\n if (assignment == null)\n {\n assignment = new ResourceAssignment(getParentFile(), this);\n m_assignments.add(assignment);\n getParentFile().getResourceAssignments().add(assignment);\n\n assignment.setTaskUniqueID(getUniqueID());\n assignment.setWork(getDuration());\n assignment.setUnits(ResourceAssignment.DEFAULT_UNITS);\n\n if (resource != null)\n {\n assignment.setResourceUniqueID(resource.getUniqueID());\n resource.addResourceAssignment(assignment);\n }\n }\n\n return (assignment);\n }" ]
Get the connectivity state as reported by the Android system @param context Android context @return the connectivity state as reported by the Android system
[ "private static boolean getSystemConnectivity(Context context) {\n try {\n ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n if (cm == null) {\n return false;\n }\n\n NetworkInfo activeNetwork = cm.getActiveNetworkInfo();\n return activeNetwork.isConnectedOrConnecting();\n } catch (Exception exception) {\n return false;\n }\n }" ]
[ "private void copyResources(File outputDirectory) throws IOException\n {\n copyClasspathResource(outputDirectory, \"reportng.css\", \"reportng.css\");\n copyClasspathResource(outputDirectory, \"reportng.js\", \"reportng.js\");\n // If there is a custom stylesheet, copy that.\n File customStylesheet = META.getStylesheetPath();\n\n if (customStylesheet != null)\n {\n if (customStylesheet.exists())\n {\n copyFile(outputDirectory, customStylesheet, CUSTOM_STYLE_FILE);\n }\n else\n {\n // If not found, try to read the file as a resource on the classpath\n // useful when reportng is called by a jarred up library\n InputStream stream = ClassLoader.getSystemClassLoader().getResourceAsStream(customStylesheet.getPath());\n if (stream != null)\n {\n copyStream(outputDirectory, stream, CUSTOM_STYLE_FILE);\n }\n }\n }\n }", "public static Optimizer<DifferentiableFunction> getRegularizedOptimizer(final Optimizer<DifferentiableFunction> opt,\n final double l1Lambda, final double l2Lambda) {\n if (l1Lambda == 0 && l2Lambda == 0) {\n return opt;\n }\n return new Optimizer<DifferentiableFunction>() {\n \n @Override\n public boolean minimize(DifferentiableFunction objective, IntDoubleVector point) {\n DifferentiableFunction fn = getRegularizedFn(objective, false, l1Lambda, l2Lambda);\n return opt.minimize(fn, point);\n }\n \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 static void validateClusterPartitionState(final Cluster subsetCluster,\n final Cluster supersetCluster) {\n if(!supersetCluster.getNodeIds().containsAll(subsetCluster.getNodeIds())) {\n throw new VoldemortException(\"Superset cluster does not contain all nodes from subset cluster[ subset cluster node ids (\"\n + subsetCluster.getNodeIds()\n + \") are not a subset of superset cluster node ids (\"\n + supersetCluster.getNodeIds() + \") ]\");\n\n }\n for(int nodeId: subsetCluster.getNodeIds()) {\n Node supersetNode = supersetCluster.getNodeById(nodeId);\n Node subsetNode = subsetCluster.getNodeById(nodeId);\n if(!supersetNode.getPartitionIds().equals(subsetNode.getPartitionIds())) {\n throw new VoldemortRebalancingException(\"Partition IDs do not match between clusters for nodes with id \"\n + nodeId\n + \" : subset cluster has \"\n + subsetNode.getPartitionIds()\n + \" and superset cluster has \"\n + supersetNode.getPartitionIds());\n }\n }\n Set<Integer> nodeIds = supersetCluster.getNodeIds();\n nodeIds.removeAll(subsetCluster.getNodeIds());\n for(int nodeId: nodeIds) {\n Node supersetNode = supersetCluster.getNodeById(nodeId);\n if(!supersetNode.getPartitionIds().isEmpty()) {\n throw new VoldemortRebalancingException(\"New node \"\n + nodeId\n + \" in superset cluster already has partitions: \"\n + supersetNode.getPartitionIds());\n }\n }\n }", "public static <T> Set<T> toSet(Iterator<? extends T> iterator) {\n\t\treturn Sets.newLinkedHashSet(toIterable(iterator));\n\t}", "private static synchronized boolean isLog4JConfigured()\r\n {\r\n if(!log4jConfigured)\r\n {\r\n Enumeration en = org.apache.log4j.Logger.getRootLogger().getAllAppenders();\r\n\r\n if (!(en instanceof org.apache.log4j.helpers.NullEnumeration))\r\n {\r\n log4jConfigured = true;\r\n }\r\n else\r\n {\r\n Enumeration cats = LogManager.getCurrentLoggers();\r\n while (cats.hasMoreElements())\r\n {\r\n org.apache.log4j.Logger c = (org.apache.log4j.Logger) cats.nextElement();\r\n if (!(c.getAllAppenders() instanceof org.apache.log4j.helpers.NullEnumeration))\r\n {\r\n log4jConfigured = true;\r\n }\r\n }\r\n }\r\n if(log4jConfigured)\r\n {\r\n String msg = \"Log4J is already configured, will not search for log4j properties file\";\r\n LoggerFactory.getBootLogger().info(msg);\r\n }\r\n else\r\n {\r\n LoggerFactory.getBootLogger().info(\"Log4J is not configured\");\r\n }\r\n }\r\n return log4jConfigured;\r\n }", "@SuppressWarnings(\"SameParameterValue\")\n private void delegatingRepaint(int x, int y, int width, int height) {\n final RepaintDelegate delegate = repaintDelegate.get();\n if (delegate != null) {\n //logger.info(\"Delegating repaint: \" + x + \", \" + y + \", \" + width + \", \" + height);\n delegate.repaint(x, y, width, height);\n } else {\n //logger.info(\"Normal repaint: \" + x + \", \" + y + \", \" + width + \", \" + height);\n repaint(x, y, width, height);\n }\n }", "public void execute() {\n State currentState = state.getAndSet(State.RUNNING);\n if (currentState == State.RUNNING) {\n throw new IllegalStateException(\n \"ExecutionChain is already running!\");\n }\n executeRunnable = new ExecuteRunnable();\n }", "private void checkExactlyTheWeeksCheckBoxes(Collection<WeekOfMonth> weeksToCheck) {\r\n\r\n for (CmsCheckBox cb : m_checkboxes) {\r\n cb.setChecked(weeksToCheck.contains(WeekOfMonth.valueOf(cb.getInternalValue())));\r\n }\r\n }" ]
Poll for the next N waiting jobs in line. @param size maximum amount of jobs to poll for @return up to "size" jobs
[ "public final List<PrintJobStatusExtImpl> poll(final int size) {\n final CriteriaBuilder builder = getSession().getCriteriaBuilder();\n final CriteriaQuery<PrintJobStatusExtImpl> criteria =\n builder.createQuery(PrintJobStatusExtImpl.class);\n final Root<PrintJobStatusExtImpl> root = criteria.from(PrintJobStatusExtImpl.class);\n root.alias(\"pj\");\n criteria.where(builder.equal(root.get(\"status\"), PrintJobStatus.Status.WAITING));\n criteria.orderBy(builder.asc(root.get(\"entry\").get(\"startTime\")));\n final Query<PrintJobStatusExtImpl> query = getSession().createQuery(criteria);\n query.setMaxResults(size);\n // LOCK but don't wait for release (since this is run continuously\n // anyway, no wait prevents deadlock)\n query.setLockMode(\"pj\", LockMode.UPGRADE_NOWAIT);\n try {\n return query.getResultList();\n } catch (PessimisticLockException ex) {\n // Another process was polling at the same time. We can ignore this error\n return Collections.emptyList();\n }\n }" ]
[ "private void readRelationships(Project gpProject)\n {\n for (net.sf.mpxj.ganttproject.schema.Task gpTask : gpProject.getTasks().getTask())\n {\n readRelationships(gpTask);\n }\n }", "public static boolean any(Object self, Closure closure) {\n BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);\n for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {\n if (bcw.call(iter.next())) return true;\n }\n return false;\n }", "public <T> T get(URI uri, Class<T> classType) {\n HttpConnection connection = Http.GET(uri);\n InputStream response = executeToInputStream(connection);\n try {\n return getResponse(response, classType, getGson());\n } finally {\n close(response);\n }\n }", "private static ClassLoader getParentCl()\n {\n try\n {\n Method m = ClassLoader.class.getMethod(\"getPlatformClassLoader\");\n return (ClassLoader) m.invoke(null);\n }\n catch (NoSuchMethodException e)\n {\n // Java < 9, just use the bootstrap CL.\n return null;\n }\n catch (Exception e)\n {\n throw new JqmInitError(\"Could not fetch Platform Class Loader\", e);\n }\n }", "public static base_responses save(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 saveresources[] = new cacheobject[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tsaveresources[i] = new cacheobject();\n\t\t\t\tsaveresources[i].locator = resources[i].locator;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, saveresources,\"save\");\n\t\t}\n\t\treturn result;\n\t}", "private static URI createSvg(\n final Dimension targetSize,\n final RasterReference rasterReference, final Double rotation,\n final Color backgroundColor, final File workingDir)\n throws IOException {\n // load SVG graphic\n final SVGElement svgRoot = parseSvg(rasterReference.inputStream);\n\n // create a new SVG graphic in which the existing graphic is embedded (scaled and rotated)\n DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();\n Document newDocument = impl.createDocument(SVG_NS, \"svg\", null);\n SVGElement newSvgRoot = (SVGElement) newDocument.getDocumentElement();\n newSvgRoot.setAttributeNS(null, \"width\", Integer.toString(targetSize.width));\n newSvgRoot.setAttributeNS(null, \"height\", Integer.toString(targetSize.height));\n\n setSvgBackground(backgroundColor, targetSize, newDocument, newSvgRoot);\n embedSvgGraphic(svgRoot, newSvgRoot, newDocument, targetSize, rotation);\n File path = writeSvgToFile(newDocument, workingDir);\n\n return path.toURI();\n }", "public Sequence compile( String equation , boolean assignment, boolean debug ) {\n\n functions.setManagerTemp(managerTemp);\n\n Sequence sequence = new Sequence();\n TokenList tokens = extractTokens(equation,managerTemp);\n\n if( tokens.size() < 3 )\n throw new RuntimeException(\"Too few tokens\");\n\n TokenList.Token t0 = tokens.getFirst();\n\n if( t0.word != null && t0.word.compareToIgnoreCase(\"macro\") == 0 ) {\n parseMacro(tokens,sequence);\n } else {\n insertFunctionsAndVariables(tokens);\n insertMacros(tokens);\n if (debug) {\n System.out.println(\"Parsed tokens:\\n------------\");\n tokens.print();\n System.out.println();\n }\n\n // Get the results variable\n if (t0.getType() != Type.VARIABLE && t0.getType() != Type.WORD) {\n compileTokens(sequence,tokens);\n // If there's no output then this is acceptable, otherwise it's assumed to be a bug\n // If there's no output then a configuration was changed\n Variable variable = tokens.getFirst().getVariable();\n if( variable != null ) {\n if( assignment )\n throw new IllegalArgumentException(\"No assignment to an output variable could be found. Found \" + t0);\n else {\n sequence.output = variable; // set this to be the output for print()\n }\n }\n\n } else {\n compileAssignment(sequence, tokens, t0);\n }\n\n if (debug) {\n System.out.println(\"Operations:\\n------------\");\n for (int i = 0; i < sequence.operations.size(); i++) {\n System.out.println(sequence.operations.get(i).name());\n }\n }\n }\n\n return sequence;\n }", "protected I_CmsSearchDocument createDefaultIndexDocument() {\n\n try {\n return m_index.getFieldConfiguration().createDocument(m_cms, m_res, m_index, null);\n } catch (CmsException e) {\n LOG.error(\n \"Default document for \"\n + m_res.getRootPath()\n + \" and index \"\n + m_index.getName()\n + \" could not be created.\",\n e);\n return null;\n }\n }", "public ParallelTaskBuilder prepareHttpGet(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n \n cb.getHttpMeta().setHttpMethod(HttpMethod.GET);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n \n return cb;\n }" ]
Checks whether the given field definition is used as the primary key of a class referenced by a reference. @param modelDef The model @param fieldDef The current field descriptor def @return The reference that uses the field or <code>null</code> if the field is not used in this way
[ "private ReferenceDescriptorDef usedByReference(ModelDef modelDef, FieldDescriptorDef fieldDef)\r\n {\r\n String ownerClassName = ((ClassDescriptorDef)fieldDef.getOwner()).getQualifiedName();\r\n ClassDescriptorDef classDef;\r\n ReferenceDescriptorDef refDef;\r\n String targetClassName;\r\n\r\n // only relevant for primarykey fields\r\n if (PropertyHelper.toBoolean(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_PRIMARYKEY), false))\r\n {\r\n for (Iterator classIt = modelDef.getClasses(); classIt.hasNext();)\r\n {\r\n classDef = (ClassDescriptorDef)classIt.next();\r\n for (Iterator refIt = classDef.getReferences(); refIt.hasNext();)\r\n {\r\n refDef = (ReferenceDescriptorDef)refIt.next();\r\n targetClassName = refDef.getProperty(PropertyHelper.OJB_PROPERTY_CLASS_REF).replace('$', '.');\r\n if (ownerClassName.equals(targetClassName))\r\n {\r\n // the field is a primary key of the class referenced by this reference descriptor\r\n return refDef;\r\n }\r\n }\r\n }\r\n }\r\n return null;\r\n }" ]
[ "public static appflowglobal_binding get(nitro_service service) throws Exception{\n\t\tappflowglobal_binding obj = new appflowglobal_binding();\n\t\tappflowglobal_binding response = (appflowglobal_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "public String join(List<String> list) {\n\n if (list == null) {\n return null;\n }\n\n StringBuilder sb = new StringBuilder();\n boolean first = true;\n for (String s : list) {\n\n if (s == null) {\n if (convertEmptyToNull) {\n s = \"\";\n } else {\n throw new IllegalArgumentException(\"StringListFlattener does not support null strings in the list. Consider calling setConvertEmptyToNull(true).\");\n }\n }\n\n if (!first) {\n sb.append(separator);\n }\n\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n if (c == escapeChar || c == separator) {\n sb.append(escapeChar);\n }\n sb.append(c);\n }\n\n first = false;\n }\n return sb.toString();\n }", "public void process(ProjectProperties properties, FilterContainer filters, FixedData fixedData, Var2Data varData)\n {\n int filterCount = fixedData.getItemCount();\n boolean[] criteriaType = new boolean[2];\n CriteriaReader criteriaReader = getCriteriaReader();\n\n for (int filterLoop = 0; filterLoop < filterCount; filterLoop++)\n {\n byte[] filterFixedData = fixedData.getByteArrayValue(filterLoop);\n if (filterFixedData == null || filterFixedData.length < 4)\n {\n continue;\n }\n\n Filter filter = new Filter();\n filter.setID(Integer.valueOf(MPPUtility.getInt(filterFixedData, 0)));\n filter.setName(MPPUtility.removeAmpersands(MPPUtility.getUnicodeString(filterFixedData, 4)));\n byte[] filterVarData = varData.getByteArray(filter.getID(), getVarDataType());\n if (filterVarData == null)\n {\n continue;\n }\n\n //System.out.println(ByteArrayHelper.hexdump(filterVarData, true, 16, \"\"));\n List<GenericCriteriaPrompt> prompts = new LinkedList<GenericCriteriaPrompt>();\n\n filter.setShowRelatedSummaryRows(MPPUtility.getByte(filterVarData, 4) != 0);\n filter.setCriteria(criteriaReader.process(properties, filterVarData, 0, -1, prompts, null, criteriaType));\n\n filter.setIsTaskFilter(criteriaType[0]);\n filter.setIsResourceFilter(criteriaType[1]);\n filter.setPrompts(prompts);\n\n filters.addFilter(filter);\n //System.out.println(filter);\n }\n }", "void merge(Archetype flatParent, Archetype specialized) {\n expandAttributeNodes(specialized.getDefinition());\n\n flattenCObject(RmPath.ROOT, null, flatParent.getDefinition(), specialized.getDefinition());\n\n\n mergeOntologies(flatParent.getTerminology(), specialized.getTerminology());\n if (flatParent.getAnnotations() != null) {\n if (specialized.getAnnotations() == null) {\n specialized.setAnnotations(new ResourceAnnotations());\n }\n annotationsMerger.merge(flatParent.getAnnotations().getItems(), specialized.getAnnotations().getItems());\n }\n }", "public static nssimpleacl[] get(nitro_service service, String aclname[]) throws Exception{\n\t\tif (aclname !=null && aclname.length>0) {\n\t\t\tnssimpleacl response[] = new nssimpleacl[aclname.length];\n\t\t\tnssimpleacl obj[] = new nssimpleacl[aclname.length];\n\t\t\tfor (int i=0;i<aclname.length;i++) {\n\t\t\t\tobj[i] = new nssimpleacl();\n\t\t\t\tobj[i].set_aclname(aclname[i]);\n\t\t\t\tresponse[i] = (nssimpleacl) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "public void setEveryWorkingDay(final boolean isEveryWorkingDay) {\n\n if (m_model.isEveryWorkingDay() != isEveryWorkingDay) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setEveryWorkingDay(Boolean.valueOf(isEveryWorkingDay));\n m_model.setInterval(getPatternDefaultValues().getInterval());\n onValueChange();\n }\n });\n }\n }", "public void configure(Configuration pConfig) throws ConfigurationException\r\n {\r\n if (pConfig instanceof PBPoolConfiguration)\r\n {\r\n PBPoolConfiguration conf = (PBPoolConfiguration) pConfig;\r\n this.setMaxActive(conf.getMaxActive());\r\n this.setMaxIdle(conf.getMaxIdle());\r\n this.setMaxWait(conf.getMaxWaitMillis());\r\n this.setMinEvictableIdleTimeMillis(conf.getMinEvictableIdleTimeMillis());\r\n this.setTimeBetweenEvictionRunsMillis(conf.getTimeBetweenEvictionRunsMilli());\r\n this.setWhenExhaustedAction(conf.getWhenExhaustedAction());\r\n }\r\n else\r\n {\r\n LoggerFactory.getDefaultLogger().error(this.getClass().getName() +\r\n \" cannot read configuration properties, use default.\");\r\n }\r\n }", "public static BsonDocument copyOfDocument(final BsonDocument document) {\n final BsonDocument newDocument = new BsonDocument();\n for (final Map.Entry<String, BsonValue> kv : document.entrySet()) {\n newDocument.put(kv.getKey(), kv.getValue());\n }\n return newDocument;\n }", "public static authenticationradiusaction[] get(nitro_service service) throws Exception{\n\t\tauthenticationradiusaction obj = new authenticationradiusaction();\n\t\tauthenticationradiusaction[] response = (authenticationradiusaction[])obj.get_resources(service);\n\t\treturn response;\n\t}" ]
send object to client and serialize it using JSON @param objectToSend the object to send @param cb the callback after sending the message
[ "protected final void sendObjectToSocket(Object objectToSend, WriteCallback cb) {\n Session sess = this.getSession();\n if (sess != null) {\n String json;\n try {\n json = this.mapper.writeValueAsString(objectToSend);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(\"Failed to serialize object\", e);\n }\n sess.getRemote().sendString(json, cb);\n }\n }" ]
[ "public void updateSequenceElement(int[] sequence, int pos, int oldVal) {\r\n if(models != null){\r\n for(int i = 0; i < models.length; i++)\r\n models[i].updateSequenceElement(sequence, pos, oldVal);\r\n return; \r\n }\r\n model1.updateSequenceElement(sequence, pos, 0);\r\n model2.updateSequenceElement(sequence, pos, 0);\r\n }", "private static boolean isValidPropertyClass(final PropertyDescriptor _property) {\n final Class type = _property.getPropertyType();\n return Number.class.isAssignableFrom(type) || type == String.class || Date.class.isAssignableFrom(type) || type == Boolean.class;\n }", "public ConverterServerBuilder workerPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit) {\n assertNumericArgument(corePoolSize, true);\n assertNumericArgument(maximumPoolSize, true);\n assertNumericArgument(corePoolSize + maximumPoolSize, false);\n assertNumericArgument(keepAliveTime, true);\n this.corePoolSize = corePoolSize;\n this.maximumPoolSize = maximumPoolSize;\n this.keepAliveTime = unit.toMillis(keepAliveTime);\n return this;\n }", "protected void destroy() {\n ContextLogger.LOG.contextCleared(this);\n final BeanStore beanStore = getBeanStore();\n if (beanStore == null) {\n throw ContextLogger.LOG.noBeanStoreAvailable(this);\n }\n for (BeanIdentifier id : beanStore) {\n destroyContextualInstance(beanStore.get(id));\n }\n beanStore.clear();\n }", "@Programmatic\n public <T> List<T> fromExcel(\n final Blob excelBlob,\n final Class<T> cls,\n final String sheetName) throws ExcelService.Exception {\n return fromExcel(excelBlob, new WorksheetSpec(cls, sheetName));\n }", "void addValue(V value, Resource resource) {\n\t\tthis.valueQueue.add(value);\n\t\tthis.valueSubjectQueue.add(resource);\n\t}", "public static int serialize(final File directory, String name, Object obj) {\n try (FileOutputStream stream = new FileOutputStream(new File(directory, name))) {\n return serialize(stream, obj);\n } catch (IOException e) {\n throw new ReportGenerationException(e);\n }\n }", "public static <T> SortedSet<T> asImmutable(SortedSet<T> self) {\n return Collections.unmodifiableSortedSet(self);\n }", "public void postArtifact(final Artifact artifact, final String user, final String password) throws GrapesCommunicationException, AuthenticationException {\n final Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.artifactResourcePath());\n final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, artifact);\n\n client.destroy();\n if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){\n final String message = \"Failed to POST artifact\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n }" ]
We have received notification that a device is no longer on the network, so clear out all its waveforms. @param announcement the packet which reported the device’s disappearance
[ "private void clearWaveforms(DeviceAnnouncement announcement) {\n final int player = announcement.getNumber();\n // Iterate over a copy to avoid concurrent modification issues\n for (DeckReference deck : new HashSet<DeckReference>(previewHotCache.keySet())) {\n if (deck.player == player) {\n previewHotCache.remove(deck);\n if (deck.hotCue == 0) {\n deliverWaveformPreviewUpdate(player, null); // Inform listeners that preview is gone.\n }\n }\n }\n // Again iterate over a copy to avoid concurrent modification issues\n for (DeckReference deck : new HashSet<DeckReference>(detailHotCache.keySet())) {\n if (deck.player == player) {\n detailHotCache.remove(deck);\n if (deck.hotCue == 0) {\n deliverWaveformDetailUpdate(player, null); // Inform listeners that detail is gone.\n }\n }\n }\n }" ]
[ "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 synchronized static SQLiteDatabase getConnection(Context context) {\n\t\tif (database == null) {\n\t\t\t// Construct the single helper and open the unique(!) db connection for the app\n\t\t\tdatabase = new CupboardDbHelper(context.getApplicationContext()).getWritableDatabase();\n\t\t}\n\t\treturn database;\n\t}", "public Quaternionf ConvertDirectionalVectorToQuaternion(Vector3f d) {\n d.negate();\n Quaternionf q = new Quaternionf();\n // check for exception condition\n if ((d.x == 0) && (d.z == 0)) {\n // exception condition if direction is (0,y,0):\n // straight up, straight down or all zero's.\n if (d.y > 0) { // direction straight up\n AxisAngle4f angleAxis = new AxisAngle4f(-(float) Math.PI / 2, 1, 0,\n 0);\n q.set(angleAxis);\n } else if (d.y < 0) { // direction straight down\n AxisAngle4f angleAxis = new AxisAngle4f((float) Math.PI / 2, 1, 0, 0);\n q.set(angleAxis);\n } else { // All zero's. Just set to identity quaternion\n q.identity();\n }\n } else {\n d.normalize();\n Vector3f up = new Vector3f(0, 1, 0);\n Vector3f s = new Vector3f();\n d.cross(up, s);\n s.normalize();\n Vector3f u = new Vector3f();\n d.cross(s, u);\n u.normalize();\n Matrix4f matrix = new Matrix4f(s.x, s.y, s.z, 0, u.x, u.y, u.z, 0, d.x,\n d.y, d.z, 0, 0, 0, 0, 1);\n q.setFromNormalized(matrix);\n }\n return q;\n }", "public static base_responses delete(nitro_service client, String ipv6address[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (ipv6address != null && ipv6address.length > 0) {\n\t\t\tnsip6 deleteresources[] = new nsip6[ipv6address.length];\n\t\t\tfor (int i=0;i<ipv6address.length;i++){\n\t\t\t\tdeleteresources[i] = new nsip6();\n\t\t\t\tdeleteresources[i].ipv6address = ipv6address[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "public Document removeDocument(String key) throws PrintingException {\n\t\tif (documentMap.containsKey(key)) {\n\t\t\treturn documentMap.remove(key);\n\t\t} else {\n\t\t\tthrow new PrintingException(PrintingException.DOCUMENT_NOT_FOUND, key);\n\t\t}\n\t}", "public Collection values()\r\n {\r\n if (values != null) return values;\r\n values = new AbstractCollection()\r\n {\r\n public int size()\r\n {\r\n return size;\r\n }\r\n\r\n public void clear()\r\n {\r\n ReferenceMap.this.clear();\r\n }\r\n\r\n public Iterator iterator()\r\n {\r\n return new ValueIterator();\r\n }\r\n };\r\n return values;\r\n }", "public Class<?> getColumnType(int c) {\n\n for (int r = 0; r < m_data.size(); r++) {\n Object val = m_data.get(r).get(c);\n if (val != null) {\n return val.getClass();\n }\n }\n return Object.class;\n }", "public void setLicense(String photoId, int licenseId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SET_LICENSE);\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"license_id\", Integer.toString(licenseId));\r\n\r\n // Note: This method requires an HTTP POST request.\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n // This method has no specific response - It returns an empty sucess response if it completes without error.\r\n\r\n }", "protected void setResults(GraphRewrite event, String variable, Iterable<? extends WindupVertexFrame> results)\n {\n Variables variables = Variables.instance(event);\n Iterable<? extends WindupVertexFrame> existingVariables = variables.findVariable(variable, 1);\n if (existingVariables != null)\n {\n variables.setVariable(variable, Iterables.concat(existingVariables, results));\n }\n else\n {\n variables.setVariable(variable, results);\n }\n }" ]
Configure high fps settings in the camera for VR mode @param fpsMode integer indicating the desired fps: 0 means 30 fps, 1 means 60 fps, and 2 means 120 fps. Any other value is invalid. @return A boolean indicating the status of the method call. It may be false due to multiple reasons including: 1) supplying invalid fpsMode as the input parameter, 2) VR mode not supported.
[ "public boolean setUpCameraForVrMode(final int fpsMode) {\n\n cameraSetUpStatus = false;\n this.fpsMode = fpsMode;\n\n if (!isCameraOpen) {\n Log.e(TAG, \"Camera is not open\");\n return false;\n }\n if (fpsMode < 0 || fpsMode > 2) {\n Log.e(TAG,\n \"Invalid fpsMode: %d. It can only take values 0, 1, or 2.\", fpsMode);\n } else {\n Parameters params = camera.getParameters();\n\n // check if the device supports vr mode preview\n if (\"true\".equalsIgnoreCase(params.get(\"vrmode-supported\"))) {\n\n Log.v(TAG, \"VR Mode supported!\");\n\n // set vr mode\n params.set(\"vrmode\", 1);\n\n // true if the apps intend to record videos using\n // MediaRecorder\n params.setRecordingHint(true);\n\n // set preview size\n // params.setPreviewSize(640, 480);\n\n // set fast-fps-mode: 0 for 30fps, 1 for 60 fps,\n // 2 for 120 fps\n params.set(\"fast-fps-mode\", fpsMode);\n\n switch (fpsMode) {\n case 0: // 30 fps\n params.setPreviewFpsRange(30000, 30000);\n break;\n case 1: // 60 fps\n params.setPreviewFpsRange(60000, 60000);\n break;\n case 2: // 120 fps\n params.setPreviewFpsRange(120000, 120000);\n break;\n default:\n }\n\n // for auto focus\n params.set(\"focus-mode\", \"continuous-video\");\n\n params.setVideoStabilization(false);\n if (\"true\".equalsIgnoreCase(params.get(\"ois-supported\"))) {\n params.set(\"ois\", \"center\");\n }\n\n camera.setParameters(params);\n cameraSetUpStatus = true;\n }\n }\n\n return cameraSetUpStatus;\n }" ]
[ "public static double findMax( double[] u, int startU , int length ) {\n double max = -1;\n\n int index = startU*2;\n int stopIndex = (startU + length)*2;\n for( ; index < stopIndex;) {\n double real = u[index++];\n double img = u[index++];\n\n double val = real*real + img*img;\n\n if( val > max ) {\n max = val;\n }\n }\n\n return Math.sqrt(max);\n }", "private void scheduleBatchLoadIfNeeded(Serializable id, SharedSessionContractImplementor session) throws MappingException {\n\t\t//cannot batch fetch by unique key (property-ref associations)\n\t\tif ( StringHelper.isEmpty( delegate.getRHSUniqueKeyPropertyName() ) && id != null ) {\n\t\t\tEntityPersister persister = session.getFactory().getMetamodel().entityPersister( delegate.getAssociatedEntityName() );\n\t\t\tEntityKey entityKey = session.generateEntityKey( id, persister );\n\t\t\tif ( !session.getPersistenceContext().containsEntity( entityKey ) ) {\n\t\t\t\tsession.getPersistenceContext().getBatchFetchQueue().addBatchLoadableEntityKey( entityKey );\n\t\t\t}\n\t\t}\n\t}", "public static boolean equal(Vector3f v1, Vector3f v2) {\n return equal(v1.x, v2.x) && equal(v1.y, v2.y) && equal(v1.z, v2.z);\n }", "public <V> V attachIfAbsent(final AttachmentKey<V> key, final V value) {\n assert key != null;\n return key.cast(contextAttachments.putIfAbsent(key, value));\n }", "private void checkOrMarkPrivateAccess(Expression source, MethodNode mn) {\n if (mn==null) {\n return;\n }\n ClassNode declaringClass = mn.getDeclaringClass();\n ClassNode enclosingClassNode = typeCheckingContext.getEnclosingClassNode();\n if (declaringClass != enclosingClassNode || typeCheckingContext.getEnclosingClosure() != null) {\n int mods = mn.getModifiers();\n boolean sameModule = declaringClass.getModule() == enclosingClassNode.getModule();\n String packageName = declaringClass.getPackageName();\n if (packageName==null) {\n packageName = \"\";\n }\n if ((Modifier.isPrivate(mods) && sameModule)\n || (Modifier.isProtected(mods) && !packageName.equals(enclosingClassNode.getPackageName()))) {\n addPrivateFieldOrMethodAccess(source, sameModule? declaringClass : enclosingClassNode, StaticTypesMarker.PV_METHODS_ACCESS, mn);\n }\n }\n }", "private void verifiedCopyFile(File sourceFile, File destFile) throws IOException {\n if(!destFile.exists()) {\n destFile.createNewFile();\n }\n\n FileInputStream source = null;\n FileOutputStream destination = null;\n LogVerificationInputStream verifyStream = null;\n try {\n source = new FileInputStream(sourceFile);\n destination = new FileOutputStream(destFile);\n verifyStream = new LogVerificationInputStream(env, source, sourceFile.getName());\n\n final byte[] buf = new byte[LOGVERIFY_BUFSIZE];\n\n while(true) {\n final int len = verifyStream.read(buf);\n if(len < 0) {\n break;\n }\n destination.write(buf, 0, len);\n }\n\n } finally {\n if(verifyStream != null) {\n verifyStream.close();\n }\n if(destination != null) {\n destination.close();\n }\n }\n }", "public CollectionRequest<User> findByWorkspace(String workspace) {\n \n String path = String.format(\"/workspaces/%s/users\", workspace);\n return new CollectionRequest<User>(this, User.class, path, \"GET\");\n }", "public Integer getEnd() {\n if (mtasPositionType.equals(POSITION_RANGE)\n || mtasPositionType.equals(POSITION_SET)) {\n return mtasPositionEnd;\n } else if (mtasPositionType.equals(POSITION_SINGLE)) {\n return mtasPositionStart;\n } else {\n return null;\n }\n }", "public static void validateExternalizersPresent(EmbeddedCacheManager externalCacheManager) {\n\t\tMap<Integer, AdvancedExternalizer<?>> externalizerMap = externalCacheManager\n\t\t\t\t.getCacheManagerConfiguration()\n\t\t\t\t.serialization()\n\t\t\t\t.advancedExternalizers();\n\t\tfor ( AdvancedExternalizer<?> ogmExternalizer : ogmExternalizers.values() ) {\n\t\t\tfinal Integer externalizerId = ogmExternalizer.getId();\n\t\t\tAdvancedExternalizer<?> registeredExternalizer = externalizerMap.get( externalizerId );\n\t\t\tif ( registeredExternalizer == null ) {\n\t\t\t\tthrow log.externalizersNotRegistered( externalizerId, ogmExternalizer.getClass() );\n\t\t\t}\n\t\t\telse if ( !registeredExternalizer.getClass().equals( ogmExternalizer ) ) {\n\t\t\t\tif ( registeredExternalizer.getClass().toString().equals( ogmExternalizer.getClass().toString() ) ) {\n\t\t\t\t\t// same class name, yet different Class definition!\n\t\t\t\t\tthrow log.registeredExternalizerNotLoadedFromOGMClassloader( registeredExternalizer.getClass() );\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow log.externalizerIdNotMatchingType( externalizerId, registeredExternalizer, ogmExternalizer );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}" ]
SearchService is a service which shares the information about Persons with the PersonService. It lets users search for individual people using simple or complex search expressions. The interaction with this service also verifies that the JAX-RS server is capable of supporting multiple root resource classes
[ "private void useSearchService() throws Exception {\n\n System.out.println(\"Searching...\");\n\n WebClient wc = WebClient.create(\"http://localhost:\" + port + \"/services/personservice/search\");\n WebClient.getConfig(wc).getHttpConduit().getClient().setReceiveTimeout(10000000L);\n wc.accept(MediaType.APPLICATION_XML);\n \n // Moves to \"/services/personservice/search\"\n wc.path(\"person\");\n \n SearchConditionBuilder builder = SearchConditionBuilder.instance(); \n \n System.out.println(\"Find people with the name Fred or Lorraine:\");\n \n String query = builder.is(\"name\").equalTo(\"Fred\").or()\n .is(\"name\").equalTo(\"Lorraine\")\n .query();\n findPersons(wc, query);\n \n System.out.println(\"Find all people who are no more than 30 years old\");\n query = builder.is(\"age\").lessOrEqualTo(30)\n \t\t.query();\n \n findPersons(wc, query);\n \n System.out.println(\"Find all people who are older than 28 and whose father name is John\");\n query = builder.is(\"age\").greaterThan(28)\n \t\t.and(\"fatherName\").equalTo(\"John\")\n \t\t.query();\n \n findPersons(wc, query);\n\n System.out.println(\"Find all people who have children with name Fred\");\n query = builder.is(\"childName\").equalTo(\"Fred\")\n \t\t.query();\n \n findPersons(wc, query);\n \n //Moves to \"/services/personservice/personinfo\"\n wc.reset().accept(MediaType.APPLICATION_XML);\n wc.path(\"personinfo\");\n \n System.out.println(\"Find all people younger than 40 using JPA2 Tuples\");\n query = builder.is(\"age\").lessThan(40).query();\n \n // Use URI path component to capture the query expression\n wc.path(query);\n \n \n Collection<? extends PersonInfo> personInfos = wc.getCollection(PersonInfo.class);\n for (PersonInfo pi : personInfos) {\n \tSystem.out.println(\"ID : \" + pi.getId());\n }\n\n wc.close();\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 }", "private void throwExceptionIfSafetyRestrictionsAreViolated(CmsObject cms, CmsSolrQuery query, boolean isSpell)\r\n throws CmsSearchException {\r\n\r\n if (!isDebug(cms, query)) {\r\n if (isSpell) {\r\n if (m_handlerSpellDisabled) {\r\n throw new CmsSearchException(Messages.get().container(Messages.GUI_HANDLER_REQUEST_NOT_ALLOWED_0));\r\n }\r\n } else {\r\n if (m_handlerSelectDisabled) {\r\n throw new CmsSearchException(Messages.get().container(Messages.GUI_HANDLER_REQUEST_NOT_ALLOWED_0));\r\n }\r\n int start = null != query.getStart() ? query.getStart().intValue() : 0;\r\n int rows = null != query.getRows() ? query.getRows().intValue() : CmsSolrQuery.DEFAULT_ROWS.intValue();\r\n if ((m_handlerMaxAllowedResultsAtAll >= 0) && ((rows + start) > m_handlerMaxAllowedResultsAtAll)) {\r\n throw new CmsSearchException(\r\n Messages.get().container(\r\n Messages.GUI_HANDLER_TOO_MANY_RESULTS_REQUESTED_AT_ALL_2,\r\n Integer.valueOf(m_handlerMaxAllowedResultsAtAll),\r\n Integer.valueOf(rows + start)));\r\n }\r\n if ((m_handlerMaxAllowedResultsPerPage >= 0) && (rows > m_handlerMaxAllowedResultsPerPage)) {\r\n throw new CmsSearchException(\r\n Messages.get().container(\r\n Messages.GUI_HANDLER_TOO_MANY_RESULTS_REQUESTED_PER_PAGE_2,\r\n Integer.valueOf(m_handlerMaxAllowedResultsPerPage),\r\n Integer.valueOf(rows)));\r\n }\r\n if ((null != m_handlerAllowedFields) && (Stream.of(m_handlerAllowedFields).anyMatch(x -> true))) {\r\n if (query.getFields().equals(CmsSolrQuery.ALL_RETURN_FIELDS)) {\r\n query.setFields(m_handlerAllowedFields);\r\n } else {\r\n for (String requestedField : query.getFields().split(\",\")) {\r\n if (Stream.of(m_handlerAllowedFields).noneMatch(\r\n allowedField -> allowedField.equals(requestedField))) {\r\n throw new CmsSearchException(\r\n Messages.get().container(\r\n Messages.GUI_HANDLER_REQUESTED_FIELD_NOT_ALLOWED_2,\r\n requestedField,\r\n Stream.of(m_handlerAllowedFields).reduce(\"\", (a, b) -> a + \",\" + b)));\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }", "public static URL findConfigResource(String resourceName) {\n if (Strings.isNullOrEmpty(resourceName)) {\n return null;\n }\n\n final URL url = resourceName.startsWith(ROOT) ? DefaultConfiguration.class.getResource(resourceName)\n : DefaultConfiguration.class.getResource(ROOT + resourceName);\n\n if (url != null) {\n return url;\n }\n\n // This is useful to get resource under META-INF directory\n String[] resourceNamePrefix = new String[] {\"META-INF/fabric8/\", \"META-INF/fabric8/\"};\n\n for (String resource : resourceNamePrefix) {\n String fullResourceName = resource + resourceName;\n\n URL candidate = KubernetesResourceLocator.class.getResource(fullResourceName.startsWith(ROOT) ? fullResourceName : ROOT + fullResourceName);\n if (candidate != null) {\n return candidate;\n }\n }\n\n return null;\n }", "public Map<String, String> getTitleLocale() {\n\n if (m_localeTitles == null) {\n m_localeTitles = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n public Object transform(Object inputLocale) {\n\n Locale locale = null;\n if (null != inputLocale) {\n if (inputLocale instanceof Locale) {\n locale = (Locale)inputLocale;\n } else if (inputLocale instanceof String) {\n try {\n locale = LocaleUtils.toLocale((String)inputLocale);\n } catch (IllegalArgumentException | NullPointerException e) {\n // do nothing, just go on without locale\n }\n }\n }\n return getLocaleSpecificTitle(locale);\n }\n\n });\n }\n return m_localeTitles;\n }", "public static double fastNormP2( DMatrixRMaj A ) {\n if( MatrixFeatures_DDRM.isVector(A)) {\n return fastNormF(A);\n } else {\n return inducedP2(A);\n }\n }", "public AbstractGraph getModuleGraph(final String moduleId) {\n final ModuleHandler moduleHandler = new ModuleHandler(repoHandler);\n final DbModule module = moduleHandler.getModule(moduleId);\n final DbOrganization organization = moduleHandler.getOrganization(module);\n\n filters.setCorporateFilter(new CorporateFilter(organization));\n\n final AbstractGraph graph = new ModuleGraph();\n addModuleToGraph(module, graph, 0);\n\n return graph;\n }", "public void deleteLicense(final String licName) {\n final DbLicense dbLicense = getLicense(licName);\n\n repoHandler.deleteLicense(dbLicense.getName());\n\n final FiltersHolder filters = new FiltersHolder();\n final LicenseIdFilter licenseIdFilter = new LicenseIdFilter(licName);\n filters.addFilter(licenseIdFilter);\n\n for (final DbArtifact artifact : repoHandler.getArtifacts(filters)) {\n repoHandler.removeLicenseFromArtifact(artifact, licName, this);\n }\n }", "public Double getAvgEventValue() {\n resetIfNeeded();\n synchronized(this) {\n long eventsLastInterval = numEventsLastInterval - numEventsLastLastInterval;\n if(eventsLastInterval > 0)\n return ((totalEventValueLastInterval - totalEventValueLastLastInterval) * 1.0)\n / eventsLastInterval;\n else\n return 0.0;\n }\n }", "static Map<String, Set<String>> getChildAddresses(final OperationContext context, final PathAddress addr, final ImmutableManagementResourceRegistration registry, Resource resource, final String validChildType) {\n\n Map<String, Set<String>> result = new HashMap<>();\n Predicate<String> validChildTypeFilter = childType -> (validChildType == null) || validChildType.equals(childType);\n\n if (resource != null) {\n for (String childType : registry.getChildNames(PathAddress.EMPTY_ADDRESS)) {\n if (validChildTypeFilter.test(childType)) {\n List<String> list = new ArrayList<>();\n for (String child : resource.getChildrenNames(childType)) {\n if (registry.getSubModel(PathAddress.pathAddress(PathElement.pathElement(childType, child))) != null) {\n list.add(child);\n }\n }\n result.put(childType, new LinkedHashSet<>(list));\n }\n }\n }\n\n Set<PathElement> paths = registry.getChildAddresses(PathAddress.EMPTY_ADDRESS);\n for (PathElement path : paths) {\n String childType = path.getKey();\n if (validChildTypeFilter.test(childType)) {\n Set<String> children = result.get(childType);\n if (children == null) {\n // WFLY-3306 Ensure we have an entry for any valid child type\n children = new LinkedHashSet<>();\n result.put(childType, children);\n }\n ImmutableManagementResourceRegistration childRegistration = registry.getSubModel(PathAddress.pathAddress(path));\n if (childRegistration != null) {\n AliasEntry aliasEntry = childRegistration.getAliasEntry();\n if (aliasEntry != null) {\n PathAddress childAddr = addr.append(path);\n PathAddress target = aliasEntry.convertToTargetAddress(childAddr, AliasContext.create(childAddr, context));\n assert !childAddr.equals(target) : \"Alias was not translated\";\n PathAddress targetParent = target.getParent();\n Resource parentResource = context.readResourceFromRoot(targetParent, false);\n if (parentResource != null) {\n PathElement targetElement = target.getLastElement();\n if (targetElement.isWildcard()) {\n children.addAll(parentResource.getChildrenNames(targetElement.getKey()));\n } else if (parentResource.hasChild(targetElement)) {\n children.add(path.getValue());\n }\n }\n }\n if (!path.isWildcard() && childRegistration.isRemote()) {\n children.add(path.getValue());\n }\n }\n }\n }\n\n return result;\n }" ]
Remove a part of a CharSequence. This replaces the first occurrence of the pattern within self with '' and returns the result. @param self a String @param pattern a Pattern representing the part to remove @return a String minus the part to be removed @since 2.2.0
[ "public static String minus(CharSequence self, Pattern pattern) {\n return pattern.matcher(self).replaceFirst(\"\");\n }" ]
[ "public void overrideCubeProperties(DockerCompositions overrideDockerCompositions) {\n final Set<String> containerIds = overrideDockerCompositions.getContainerIds();\n for (String containerId : containerIds) {\n\n // main definition of containers contains a container that must be overrode\n if (containers.containsKey(containerId)) {\n final CubeContainer cubeContainer = containers.get(containerId);\n final CubeContainer overrideCubeContainer = overrideDockerCompositions.get(containerId);\n\n cubeContainer.setRemoveVolumes(overrideCubeContainer.getRemoveVolumes());\n \n cubeContainer.setAlwaysPull(overrideCubeContainer.getAlwaysPull());\n\n if (overrideCubeContainer.hasAwait()) {\n cubeContainer.setAwait(overrideCubeContainer.getAwait());\n }\n\n if (overrideCubeContainer.hasBeforeStop()) {\n cubeContainer.setBeforeStop(overrideCubeContainer.getBeforeStop());\n }\n\n if (overrideCubeContainer.isManual()) {\n cubeContainer.setManual(overrideCubeContainer.isManual());\n }\n\n if (overrideCubeContainer.isKillContainer()) {\n cubeContainer.setKillContainer(overrideCubeContainer.isKillContainer());\n }\n } else {\n logger.warning(String.format(\"Overriding Container %s are not defined in main definition of containers.\",\n containerId));\n }\n }\n }", "public ItemRequest<Story> update(String story) {\n \n String path = String.format(\"/stories/%s\", story);\n return new ItemRequest<Story>(this, Story.class, path, \"PUT\");\n }", "@Override\n public final Double optDouble(final String key, final Double defaultValue) {\n Double result = optDouble(key);\n return result == null ? defaultValue : result;\n }", "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}", "@Override\n public void onNewState(CrawlerContext context, StateVertex vertex) {\n LOG.debug(\"onNewState\");\n StateBuilder state = outModelCache.addStateIfAbsent(vertex);\n visitedStates.putIfAbsent(state.getName(), vertex);\n\n saveScreenshot(context.getBrowser(), state.getName(), vertex);\n\n outputBuilder.persistDom(state.getName(), context.getBrowser().getUnStrippedDom());\n }", "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 long getTime(Date start, Date end)\n {\n long total = 0;\n if (start != null && end != null)\n {\n Date startTime = DateHelper.getCanonicalTime(start);\n Date endTime = DateHelper.getCanonicalTime(end);\n\n Date startDay = DateHelper.getDayStartDate(start);\n Date finishDay = DateHelper.getDayStartDate(end);\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.getTime() != finishDay.getTime())\n { \n endTime = DateHelper.addDays(endTime, 1);\n }\n\n total = (endTime.getTime() - startTime.getTime());\n }\n return (total);\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 }", "public boolean removeCustomResponse(String pathValue, String requestType) {\n try {\n JSONObject path = getPathFromEndpoint(pathValue, requestType);\n if (path == null) {\n return false;\n }\n String pathId = path.getString(\"pathId\");\n return resetResponseOverride(pathId);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }" ]
Get's the user's current upload limits, User object only contains user_id @return Media Limits
[ "public User getLimits() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIMITS);\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 userElement = response.getPayload();\r\n User user = new User();\r\n user.setId(userElement.getAttribute(\"nsid\"));\r\n NodeList photoNodes = userElement.getElementsByTagName(\"photos\");\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element plElement = (Element) photoNodes.item(i);\r\n PhotoLimits pl = new PhotoLimits();\r\n user.setPhotoLimits(pl);\r\n pl.setMaxDisplay(plElement.getAttribute(\"maxdisplaypx\"));\r\n pl.setMaxUpload(plElement.getAttribute(\"maxupload\"));\r\n }\r\n NodeList videoNodes = userElement.getElementsByTagName(\"videos\");\r\n for (int i = 0; i < videoNodes.getLength(); i++) {\r\n Element vlElement = (Element) videoNodes.item(i);\r\n VideoLimits vl = new VideoLimits();\r\n user.setPhotoLimits(vl);\r\n vl.setMaxDuration(vlElement.getAttribute(\"maxduration\"));\r\n vl.setMaxUpload(vlElement.getAttribute(\"maxupload\"));\r\n }\r\n return user;\r\n }" ]
[ "private List<Versioned<byte[]>> filterExpiredEntries(ByteArray key, List<Versioned<byte[]>> vals) {\n Iterator<Versioned<byte[]>> valsIterator = vals.iterator();\n while(valsIterator.hasNext()) {\n Versioned<byte[]> val = valsIterator.next();\n VectorClock clock = (VectorClock) val.getVersion();\n // omit if expired\n if(clock.getTimestamp() < (time.getMilliseconds() - this.retentionTimeMs)) {\n valsIterator.remove();\n // delete stale value if configured\n if(deleteExpiredEntries) {\n getInnerStore().delete(key, clock);\n }\n }\n }\n return vals;\n }", "public Optional<URL> getServiceUrl() {\n Optional<Service> optionalService = client.services().inNamespace(namespace)\n .list().getItems()\n .stream()\n .findFirst();\n\n return optionalService\n .map(this::createUrlForService)\n .orElse(Optional.empty());\n }", "public void notifySubscriberCallback(ContentNotification cn) {\n String content = fetchContentFromPublisher(cn);\n\n distributeContentToSubscribers(content, cn.getUrl());\n }", "public void load(File file) {\n try {\n PropertiesConfiguration config = new PropertiesConfiguration();\n // disabled to prevent accumulo classpath value from being shortened\n config.setDelimiterParsingDisabled(true);\n config.load(file);\n ((CompositeConfiguration) internalConfig).addConfiguration(config);\n } catch (ConfigurationException e) {\n throw new IllegalArgumentException(e);\n }\n }", "public static ConsistencyLevel determineConsistency(Map<Value, Set<ClusterNode>> versionNodeSetMap,\n int replicationFactor) {\n boolean fullyConsistent = true;\n Value latestVersion = null;\n for (Map.Entry<Value, Set<ClusterNode>> versionNodeSetEntry : versionNodeSetMap.entrySet()) {\n Value value = versionNodeSetEntry.getKey();\n if (latestVersion == null) {\n latestVersion = value;\n } else if (value.isTimeStampLaterThan(latestVersion)) {\n latestVersion = value;\n }\n Set<ClusterNode> nodeSet = versionNodeSetEntry.getValue();\n fullyConsistent = fullyConsistent && (nodeSet.size() == replicationFactor);\n }\n if (fullyConsistent) {\n return ConsistencyLevel.FULL;\n } else {\n // latest write consistent, effectively consistent\n if (latestVersion != null && versionNodeSetMap.get(latestVersion).size() == replicationFactor) {\n return ConsistencyLevel.LATEST_CONSISTENT;\n }\n // all other states inconsistent\n return ConsistencyLevel.INCONSISTENT;\n }\n }", "@Override\n public View getDropDownView(int position, View convertView, ViewGroup parent) {\n final ViewHolder viewHolder;\n if (convertView == null) {\n convertView = mLayoutInflater.inflate(R.layout.item_country, parent, false);\n viewHolder = new ViewHolder();\n viewHolder.mImageView = (ImageView) convertView.findViewById(R.id.intl_phone_edit__country__item_image);\n viewHolder.mNameView = (TextView) convertView.findViewById(R.id.intl_phone_edit__country__item_name);\n viewHolder.mDialCode = (TextView) convertView.findViewById(R.id.intl_phone_edit__country__item_dialcode);\n convertView.setTag(viewHolder);\n } else {\n viewHolder = (ViewHolder) convertView.getTag();\n }\n\n Country country = getItem(position);\n viewHolder.mImageView.setImageResource(getFlagResource(country));\n viewHolder.mNameView.setText(country.getName());\n viewHolder.mDialCode.setText(String.format(\"+%s\", country.getDialCode()));\n return convertView;\n }", "protected void addLineContent(BufferedReader bufferedFileReader, List<String> content, String line) throws IOException {\n content.add(line);\n }", "public BoxFolder.Info restoreFolder(String folderID, 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_FOLDER_URL_TEMPLATE.build(this.api.getBaseURL(), folderID);\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 BoxFolder restoredFolder = new BoxFolder(this.api, responseJSON.get(\"id\").asString());\n return restoredFolder.new Info(responseJSON);\n }", "public void addColumnNotNull(String column)\r\n {\r\n\t\t// PAW\r\n\t\t// SelectionCriteria c = ValueCriteria.buildNotNullCriteria(column, getAlias());\r\n\t\tSelectionCriteria c = ValueCriteria.buildNotNullCriteria(column, getUserAlias(column));\r\n c.setTranslateAttribute(false);\r\n addSelectionCriteria(c);\r\n }" ]
Validates an operation against its description provider @param operation The operation to validate @throws IllegalArgumentException if the operation is not valid
[ "public void validateOperation(final ModelNode operation) {\n if (operation == null) {\n return;\n }\n final PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR));\n final String name = operation.get(OP).asString();\n\n OperationEntry entry = root.getOperationEntry(address, name);\n if (entry == null) {\n throwOrWarnAboutDescriptorProblem(ControllerLogger.ROOT_LOGGER.noOperationEntry(name, address));\n }\n //noinspection ConstantConditions\n if (entry.getType() == EntryType.PRIVATE || entry.getFlags().contains(OperationEntry.Flag.HIDDEN)) {\n return;\n }\n if (entry.getOperationHandler() == null) {\n throwOrWarnAboutDescriptorProblem(ControllerLogger.ROOT_LOGGER.noOperationHandler(name, address));\n }\n final DescriptionProvider provider = getDescriptionProvider(operation);\n final ModelNode description = provider.getModelDescription(null);\n\n final Map<String, ModelNode> describedProperties = getDescribedRequestProperties(operation, description);\n final Map<String, ModelNode> actualParams = getActualRequestProperties(operation);\n\n checkActualOperationParamsAreDescribed(operation, describedProperties, actualParams);\n checkAllRequiredPropertiesArePresent(description, operation, describedProperties, actualParams);\n checkParameterTypes(description, operation, describedProperties, actualParams);\n\n //TODO check ranges\n }" ]
[ "public static Cluster swapGreedyRandomPartitions(final Cluster nextCandidateCluster,\n final List<Integer> nodeIds,\n final int greedySwapMaxPartitionsPerNode,\n final int greedySwapMaxPartitionsPerZone,\n List<StoreDefinition> storeDefs) {\n\n System.out.println(\"GreedyRandom : nodeIds:\" + nodeIds);\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n double currentUtility = new PartitionBalance(returnCluster, storeDefs).getUtility();\n int nodeIdA = -1;\n int nodeIdB = -1;\n int partitionIdA = -1;\n int partitionIdB = -1;\n\n for(int nodeIdAPrime: nodeIds) {\n System.out.println(\"GreedyRandom : processing nodeId:\" + nodeIdAPrime);\n List<Integer> partitionIdsAPrime = new ArrayList<Integer>();\n partitionIdsAPrime.addAll(returnCluster.getNodeById(nodeIdAPrime).getPartitionIds());\n Collections.shuffle(partitionIdsAPrime);\n\n int maxPartitionsInAPrime = Math.min(greedySwapMaxPartitionsPerNode,\n partitionIdsAPrime.size());\n\n for(int offsetAPrime = 0; offsetAPrime < maxPartitionsInAPrime; offsetAPrime++) {\n Integer partitionIdAPrime = partitionIdsAPrime.get(offsetAPrime);\n List<Pair<Integer, Integer>> partitionIdsZone = new ArrayList<Pair<Integer, Integer>>();\n for(int nodeIdBPrime: nodeIds) {\n if(nodeIdBPrime == nodeIdAPrime)\n continue;\n for(Integer partitionIdBPrime: returnCluster.getNodeById(nodeIdBPrime)\n .getPartitionIds()) {\n partitionIdsZone.add(new Pair<Integer, Integer>(nodeIdBPrime,\n partitionIdBPrime));\n }\n }\n\n Collections.shuffle(partitionIdsZone);\n int maxPartitionsInZone = Math.min(greedySwapMaxPartitionsPerZone,\n partitionIdsZone.size());\n for(int offsetZone = 0; offsetZone < maxPartitionsInZone; offsetZone++) {\n Integer nodeIdBPrime = partitionIdsZone.get(offsetZone).getFirst();\n Integer partitionIdBPrime = partitionIdsZone.get(offsetZone).getSecond();\n Cluster swapResult = swapPartitions(returnCluster,\n nodeIdAPrime,\n partitionIdAPrime,\n nodeIdBPrime,\n partitionIdBPrime);\n double swapUtility = new PartitionBalance(swapResult, storeDefs).getUtility();\n if(swapUtility < currentUtility) {\n currentUtility = swapUtility;\n System.out.println(\" -> \" + currentUtility);\n nodeIdA = nodeIdAPrime;\n partitionIdA = partitionIdAPrime;\n nodeIdB = nodeIdBPrime;\n partitionIdB = partitionIdBPrime;\n }\n }\n }\n }\n\n if(nodeIdA == -1) {\n return returnCluster;\n }\n return swapPartitions(returnCluster, nodeIdA, partitionIdA, nodeIdB, partitionIdB);\n }", "public static aaapreauthenticationpolicy_binding get(nitro_service service, String name) throws Exception{\n\t\taaapreauthenticationpolicy_binding obj = new aaapreauthenticationpolicy_binding();\n\t\tobj.set_name(name);\n\t\taaapreauthenticationpolicy_binding response = (aaapreauthenticationpolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "private void initHasMasterMode() throws CmsException {\n\n if (hasDescriptor()\n && m_cms.hasPermissions(m_desc, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.ALL)) {\n m_hasMasterMode = true;\n } else {\n m_hasMasterMode = false;\n }\n }", "public boolean startsWith(Bytes prefix) {\n Objects.requireNonNull(prefix, \"startWith(Bytes prefix) cannot have null parameter\");\n\n if (prefix.length > this.length) {\n return false;\n } else {\n int end = this.offset + prefix.length;\n for (int i = this.offset, j = prefix.offset; i < end; i++, j++) {\n if (this.data[i] != prefix.data[j]) {\n return false;\n }\n }\n }\n return true;\n }", "public void processStencilSet() throws IOException {\n StringBuilder stencilSetFileContents = new StringBuilder();\n\n Scanner scanner = null;\n try {\n scanner = new Scanner(new File(ssInFile),\n \"UTF-8\");\n String currentLine = \"\";\n String prevLine = \"\";\n while (scanner.hasNextLine()) {\n prevLine = currentLine;\n currentLine = scanner.nextLine();\n\n String trimmedPrevLine = prevLine.trim();\n String trimmedCurrentLine = currentLine.trim();\n\n // First time processing - replace view=\"<file>.svg\" with _view_file=\"<file>.svg\" + view=\"<svg_xml>\"\n if (trimmedCurrentLine.matches(VIEW_PROPERTY_NAME_PATTERN) && trimmedCurrentLine.endsWith(VIEW_PROPERTY_VALUE_SUFFIX)) {\n String newLines = processViewPropertySvgReference(currentLine);\n stencilSetFileContents.append(newLines);\n }\n // Second time processing - replace view=\"<svg_xml>\" with refreshed contents of file referenced by previous line\n else if (trimmedPrevLine.matches(VIEW_FILE_PROPERTY_NAME_PATTERN) && trimmedPrevLine.endsWith(VIEW_PROPERTY_VALUE_SUFFIX)\n && trimmedCurrentLine.matches(VIEW_PROPERTY_NAME_PATTERN)) {\n String newLines = processViewFilePropertySvgReference(prevLine,\n currentLine);\n stencilSetFileContents.append(newLines);\n } else {\n stencilSetFileContents.append(currentLine + LINE_SEPARATOR);\n }\n }\n } finally {\n if (scanner != null) {\n scanner.close();\n }\n }\n\n Writer out = null;\n try {\n out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ssOutFile),\n \"UTF-8\"));\n out.write(stencilSetFileContents.toString());\n } catch (FileNotFoundException e) {\n\n } catch (UnsupportedEncodingException e) {\n } catch (IOException e) {\n } finally {\n if (out != null) {\n try {\n out.close();\n } catch (IOException e) {\n }\n }\n }\n\n System.out.println(\"SVG files referenced more than once:\");\n for (Map.Entry<String, Integer> stringIntegerEntry : mapSVGCounts.entrySet()) {\n if (stringIntegerEntry.getValue() > 1) {\n System.out.println(\"\\t\" + stringIntegerEntry.getKey() + \"\\t = \" + stringIntegerEntry.getValue());\n }\n }\n }", "public synchronized List<String> propertyListOf(Class<?> c) {\n String cn = c.getName();\n List<String> ls = repo.get(cn);\n if (ls != null) {\n return ls;\n }\n Set<Class<?>> circularReferenceDetector = new HashSet<>();\n ls = propertyListOf(c, circularReferenceDetector, null);\n repo.put(c.getName(), ls);\n return ls;\n }", "public int getOpacity() {\n\t\tint opacity = Math\n\t\t\t\t.round((mPosToOpacFactor * (mBarPointerPosition - mBarPointerHaloRadius)));\n\t\tif (opacity < 5) {\n\t\t\treturn 0x00;\n\t\t} else if (opacity > 250) {\n\t\t\treturn 0xFF;\n\t\t} else {\n\t\t\treturn opacity;\n\t\t}\n\t}", "static BsonDocument getDocumentVersionDoc(final BsonDocument document) {\n if (document == null || !document.containsKey(DOCUMENT_VERSION_FIELD)) {\n return null;\n }\n return document.getDocument(DOCUMENT_VERSION_FIELD, null);\n }", "public static base_responses update(nitro_service client, nsip6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsip6 updateresources[] = new nsip6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nsip6();\n\t\t\t\tupdateresources[i].ipv6address = resources[i].ipv6address;\n\t\t\t\tupdateresources[i].td = resources[i].td;\n\t\t\t\tupdateresources[i].nd = resources[i].nd;\n\t\t\t\tupdateresources[i].icmp = resources[i].icmp;\n\t\t\t\tupdateresources[i].vserver = resources[i].vserver;\n\t\t\t\tupdateresources[i].telnet = resources[i].telnet;\n\t\t\t\tupdateresources[i].ftp = resources[i].ftp;\n\t\t\t\tupdateresources[i].gui = resources[i].gui;\n\t\t\t\tupdateresources[i].ssh = resources[i].ssh;\n\t\t\t\tupdateresources[i].snmp = resources[i].snmp;\n\t\t\t\tupdateresources[i].mgmtaccess = resources[i].mgmtaccess;\n\t\t\t\tupdateresources[i].restrictaccess = resources[i].restrictaccess;\n\t\t\t\tupdateresources[i].state = resources[i].state;\n\t\t\t\tupdateresources[i].map = resources[i].map;\n\t\t\t\tupdateresources[i].dynamicrouting = resources[i].dynamicrouting;\n\t\t\t\tupdateresources[i].hostroute = resources[i].hostroute;\n\t\t\t\tupdateresources[i].ip6hostrtgw = resources[i].ip6hostrtgw;\n\t\t\t\tupdateresources[i].metric = resources[i].metric;\n\t\t\t\tupdateresources[i].vserverrhilevel = resources[i].vserverrhilevel;\n\t\t\t\tupdateresources[i].ospf6lsatype = resources[i].ospf6lsatype;\n\t\t\t\tupdateresources[i].ospfarea = resources[i].ospfarea;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}" ]
Adds a Statement. @param rank rank of the statement @param subject rdf resource that refers to the statement
[ "public void add(StatementRank rank, Resource subject) {\n\t\tif (this.bestRank == rank) {\n\t\t\tsubjects.add(subject);\n\t\t} else if(bestRank == StatementRank.NORMAL && rank == StatementRank.PREFERRED) {\n\t\t\t//We found a preferred statement\n\t\t\tsubjects.clear();\n\t\t\tbestRank = StatementRank.PREFERRED;\n\t\t\tsubjects.add(subject);\n\t\t}\n\t}" ]
[ "public void parseAndAddDictionaries(CmsObject cms) throws CmsRoleViolationException {\n\n OpenCms.getRoleManager().checkRole(cms, CmsRole.ROOT_ADMIN);\n CmsSpellcheckDictionaryIndexer.parseAndAddZippedDictionaries(m_solrClient, cms);\n CmsSpellcheckDictionaryIndexer.parseAndAddDictionaries(m_solrClient, cms);\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 Tokenizer<Tree> getTokenizer(final Reader r) {\r\n return new AbstractTokenizer<Tree>() {\r\n TreeReader tr = trf.newTreeReader(r);\r\n @Override\r\n public Tree getNext() {\r\n try {\r\n return tr.readTree();\r\n }\r\n catch(IOException e) {\r\n System.err.println(\"Error in reading tree.\");\r\n return null;\r\n }\r\n }\r\n };\r\n }", "@NonNull\n @UiThread\n private HashMap<Integer, Boolean> generateExpandedStateMap() {\n HashMap<Integer, Boolean> parentHashMap = new HashMap<>();\n int childCount = 0;\n\n int listItemCount = mFlatItemList.size();\n for (int i = 0; i < listItemCount; i++) {\n if (mFlatItemList.get(i) != null) {\n ExpandableWrapper<P, C> listItem = mFlatItemList.get(i);\n if (listItem.isParent()) {\n parentHashMap.put(i - childCount, listItem.isExpanded());\n } else {\n childCount++;\n }\n }\n }\n\n return parentHashMap;\n }", "private static String getColumnTitle(final PropertyDescriptor _property) {\n final StringBuilder buffer = new StringBuilder();\n final String name = _property.getName();\n buffer.append(Character.toUpperCase(name.charAt(0)));\n for (int i = 1; i < name.length(); i++) {\n final char c = name.charAt(i);\n if (Character.isUpperCase(c)) {\n buffer.append(' ');\n }\n buffer.append(c);\n }\n return buffer.toString();\n }", "public Set<Class<?>> getPrevented() {\n if (this.prevent == null) {\n return Collections.emptySet();\n }\n return Collections.unmodifiableSet(this.prevent);\n }", "public static Object newInstance(String className, Class type, Object arg) throws InstantiationException,\r\n IllegalAccessException,\r\n IllegalArgumentException,\r\n InvocationTargetException,\r\n NoSuchMethodException,\r\n SecurityException,\r\n ClassNotFoundException\r\n {\r\n return newInstance(className, new Class[]{type}, new Object[]{arg});\r\n }", "public static String termPrefix(String term) {\n int i = term.indexOf(MtasToken.DELIMITER);\n String prefix = term;\n if (i >= 0) {\n prefix = term.substring(0, i);\n }\n return prefix.replace(\"\\u0000\", \"\");\n }", "public static transformpolicy get(nitro_service service, String name) throws Exception{\n\t\ttransformpolicy obj = new transformpolicy();\n\t\tobj.set_name(name);\n\t\ttransformpolicy response = (transformpolicy) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
Run the configured crawl. This method blocks until the crawl is done. @return the CrawlSession once the crawl is done.
[ "@Override\n\tpublic CrawlSession call() {\n\t\tsetMaximumCrawlTimeIfNeeded();\n\t\tplugins.runPreCrawlingPlugins(config);\n\t\tCrawlTaskConsumer firstConsumer = consumerFactory.get();\n\t\tStateVertex firstState = firstConsumer.crawlIndex();\n\t\tcrawlSessionProvider.setup(firstState);\n\t\tplugins.runOnNewStatePlugins(firstConsumer.getContext(), firstState);\n\t\texecuteConsumers(firstConsumer);\n\t\treturn crawlSessionProvider.get();\n\t}" ]
[ "@Inject(\"struts.json.action.fileProtocols\")\n\tpublic void setFileProtocols(String fileProtocols) {\n\t\tif (StringUtils.isNotBlank(fileProtocols)) {\n\t\t\tthis.fileProtocols = TextParseUtil.commaDelimitedStringToSet(fileProtocols);\n\t\t}\n\t}", "@Override\n public boolean invokeFunction(String funcName, Object[] params) {\n // Run script if it is dirty. This makes sure the script is run\n // on the same thread as the caller (suppose the caller is always\n // calling from the same thread).\n checkDirty();\n\n // Skip bad functions\n if (isBadFunction(funcName)) {\n return false;\n }\n\n String statement = getInvokeStatementCached(funcName, params);\n\n synchronized (mEngineLock) {\n localBindings = mLocalEngine.getBindings(ScriptContext.ENGINE_SCOPE);\n if (localBindings == null) {\n localBindings = mLocalEngine.createBindings();\n mLocalEngine.setBindings(localBindings, ScriptContext.ENGINE_SCOPE);\n }\n }\n\n fillBindings(localBindings, params);\n\n try {\n mLocalEngine.eval(statement);\n } catch (ScriptException e) {\n // The function is either undefined or throws, avoid invoking it later\n addBadFunction(funcName);\n mLastError = e.getMessage();\n return false;\n } finally {\n removeBindings(localBindings, params);\n }\n\n return true;\n }", "private String formatUnits(Number value)\n {\n return (value == null ? null : m_formats.getUnitsDecimalFormat().format(value.doubleValue() / 100));\n }", "public SourceBuilder addLine(String fmt, Object... args) {\n add(fmt, args);\n source.append(LINE_SEPARATOR);\n return this;\n }", "public static Boolean assertTrue(Boolean value, String message) {\n if (!Boolean.valueOf(value))\n throw new IllegalArgumentException(message);\n return value;\n }", "private static String removeLastDot(final String pkgName) {\n\t\treturn pkgName.charAt(pkgName.length() - 1) == Characters.DOT ? pkgName.substring(0, pkgName.length() - 1) : pkgName;\n\t}", "public static rnatparam get(nitro_service service) throws Exception{\n\t\trnatparam obj = new rnatparam();\n\t\trnatparam[] response = (rnatparam[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public void storeIfNew(final DbArtifact fromClient) {\n final DbArtifact existing = repositoryHandler.getArtifact(fromClient.getGavc());\n\n if(existing != null){\n existing.setLicenses(fromClient.getLicenses());\n store(existing);\n }\n\n if(existing == null){\n\t store(fromClient);\n }\n }", "public int readInt(int offset, byte[] data)\n {\n int result = 0;\n int i = offset + m_offset;\n for (int shiftBy = 0; shiftBy < 32; shiftBy += 8)\n {\n result |= ((data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }" ]
Returns the path in the RFS where the Solr spellcheck files reside. @return String representation of Solrs spellcheck RFS path.
[ "private static String getSolrSpellcheckRfsPath() {\n\n String sPath = OpenCms.getSystemInfo().getWebInfRfsPath();\n\n if (!OpenCms.getSystemInfo().getWebInfRfsPath().endsWith(File.separator)) {\n sPath += File.separator;\n }\n\n return sPath + \"solr\" + File.separator + \"spellcheck\" + File.separator + \"data\";\n }" ]
[ "public void transform(DataPipe cr) {\n for (Map.Entry<String, String> entry : cr.getDataMap().entrySet()) {\n String value = entry.getValue();\n\n if (value.equals(\"#{customplaceholder}\")) {\n // Generate a random number\n int ran = rand.nextInt();\n entry.setValue(String.valueOf(ran));\n }\n }\n }", "public static int cudnnConvolutionBackwardBias(\n cudnnHandle handle, \n Pointer alpha, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n Pointer beta, \n cudnnTensorDescriptor dbDesc, \n Pointer db)\n {\n return checkResult(cudnnConvolutionBackwardBiasNative(handle, alpha, dyDesc, dy, beta, dbDesc, db));\n }", "public static String unexpand(CharSequence self, int tabStop) {\n String s = self.toString();\n if (s.length() == 0) return s;\n try {\n StringBuilder builder = new StringBuilder();\n for (String line : readLines((CharSequence) s)) {\n builder.append(unexpandLine(line, tabStop));\n builder.append(\"\\n\");\n }\n // remove the normalized ending line ending if it was not present\n if (!s.endsWith(\"\\n\")) {\n builder.deleteCharAt(builder.length() - 1);\n }\n return builder.toString();\n } catch (IOException e) {\n /* ignore */\n }\n return s;\n }", "private void logTimeTakenByRuleProvider(GraphContext graphContext, Context context, int ruleIndex, int timeTaken)\n {\n AbstractRuleProvider ruleProvider = (AbstractRuleProvider) context.get(RuleMetadataType.RULE_PROVIDER);\n if (ruleProvider == null)\n return;\n\n if (!timeTakenByProvider.containsKey(ruleProvider))\n {\n RuleProviderExecutionStatisticsModel model = new RuleProviderExecutionStatisticsService(graphContext)\n .create();\n model.setRuleIndex(ruleIndex);\n model.setRuleProviderID(ruleProvider.getMetadata().getID());\n model.setTimeTaken(timeTaken);\n\n timeTakenByProvider.put(ruleProvider, model.getElement().id());\n }\n else\n {\n RuleProviderExecutionStatisticsService service = new RuleProviderExecutionStatisticsService(graphContext);\n RuleProviderExecutionStatisticsModel model = service.getById(timeTakenByProvider.get(ruleProvider));\n int prevTimeTaken = model.getTimeTaken();\n model.setTimeTaken(prevTimeTaken + timeTaken);\n }\n logTimeTakenByPhase(graphContext, ruleProvider.getMetadata().getPhase(), timeTaken);\n }", "public synchronized void setSynced(boolean sync) {\n if (synced.get() != sync) {\n // We are changing sync state, so add or remove our master listener as appropriate.\n if (sync && isSendingStatus()) {\n addMasterListener(ourSyncMasterListener);\n } else {\n removeMasterListener(ourSyncMasterListener);\n }\n\n // Also, if there is a tempo master, and we just got synced, adopt its tempo.\n if (!isTempoMaster() && getTempoMaster() != null) {\n setTempo(getMasterTempo());\n }\n }\n synced.set(sync);\n }", "private void deleteBackups() {\n File[] storeDirList = ReadOnlyUtils.getVersionDirs(storeDir, 0L, getCurrentVersionId());\n if(storeDirList != null && storeDirList.length > (numBackups + 1)) {\n // delete ALL old directories asynchronously\n File[] extraBackups = ReadOnlyUtils.findKthVersionedDir(storeDirList,\n 0,\n storeDirList.length\n - (numBackups + 1) - 1);\n if(extraBackups != null) {\n for(File backUpFile: extraBackups) {\n deleteAsync(backUpFile);\n }\n }\n }\n }", "private static Data loadLeapSeconds() {\n Data bestData = null;\n URL url = null;\n try {\n // this is the new location of the file, working on Java 8, Java 9 class path and Java 9 module path\n Enumeration<URL> en = Thread.currentThread().getContextClassLoader().getResources(\"META-INF/\" + LEAP_SECONDS_TXT);\n while (en.hasMoreElements()) {\n url = en.nextElement();\n Data candidate = loadLeapSeconds(url);\n if (bestData == null || candidate.getNewestDate() > bestData.getNewestDate()) {\n bestData = candidate;\n }\n }\n // this location does not work on Java 9 module path because the resource is encapsulated\n en = Thread.currentThread().getContextClassLoader().getResources(LEAP_SECONDS_TXT);\n while (en.hasMoreElements()) {\n url = en.nextElement();\n Data candidate = loadLeapSeconds(url);\n if (bestData == null || candidate.getNewestDate() > bestData.getNewestDate()) {\n bestData = candidate;\n }\n }\n // this location is the canonical one, and class-based loading works on Java 9 module path\n url = SystemUtcRules.class.getResource(\"/\" + LEAP_SECONDS_TXT);\n if (url != null) {\n Data candidate = loadLeapSeconds(url);\n if (bestData == null || candidate.getNewestDate() > bestData.getNewestDate()) {\n bestData = candidate;\n }\n }\n } catch (Exception ex) {\n throw new RuntimeException(\"Unable to load time-zone rule data: \" + url, ex);\n }\n if (bestData == null) {\n // no data on classpath, but we allow manual registration of leap seconds\n // setup basic known data - MJD 1972-01-01 is 41317L, where offset was 10\n bestData = new Data(new long[] {41317L}, new int[] {10}, new long[] {tai(41317L, 10)});\n }\n return bestData;\n }", "public static double Taneja(double[] p, double[] q) {\n double r = 0;\n for (int i = 0; i < p.length; i++) {\n if (p[i] != 0 && q[i] != 0) {\n double pq = p[i] + q[i];\n r += (pq / 2) * Math.log(pq / (2 * Math.sqrt(p[i] * q[i])));\n }\n }\n return r;\n }", "public <T extends CanvasWriter> T getWriter(Class<T> type, OauthToken oauthToken) {\n return getWriter(type, oauthToken, false);\n }" ]
Migrate to Jenkins "Credentials" plugin from the old credential implementation
[ "public void credentialsMigration(T overrider, Class overriderClass) {\n try {\n deployerMigration(overrider, overriderClass);\n resolverMigration(overrider, overriderClass);\n } catch (NoSuchFieldException | IllegalAccessException | IOException e) {\n converterErrors.add(getConversionErrorMessage(overrider, e));\n }\n }" ]
[ "public static String format(final String code, final Properties options, final LineEnding lineEnding) {\n\t\tCheck.notEmpty(code, \"code\");\n\t\tCheck.notEmpty(options, \"options\");\n\t\tCheck.notNull(lineEnding, \"lineEnding\");\n\n\t\tfinal CodeFormatter formatter = ToolFactory.createCodeFormatter(options);\n\t\tfinal String lineSeparator = LineEnding.find(lineEnding, code);\n\t\tTextEdit te = null;\n\t\ttry {\n\t\t\tte = formatter.format(CodeFormatter.K_COMPILATION_UNIT, code, 0, code.length(), 0, lineSeparator);\n\t\t} catch (final Exception formatFailed) {\n\t\t\tLOG.warn(\"Formatting failed\", formatFailed);\n\t\t}\n\n\t\tString formattedCode = code;\n\t\tif (te == null) {\n\t\t\tLOG.info(\"Code cannot be formatted. Possible cause is unmatched source/target/compliance version.\");\n\t\t} else {\n\n\t\t\tfinal IDocument doc = new Document(code);\n\t\t\ttry {\n\t\t\t\tte.apply(doc);\n\t\t\t} catch (final Exception e) {\n\t\t\t\tLOG.warn(e.getLocalizedMessage(), e);\n\t\t\t}\n\t\t\tformattedCode = doc.get();\n\t\t}\n\t\treturn formattedCode;\n\t}", "public static <T> List<T> toList(Iterable<T> items) {\r\n List<T> list = new ArrayList<T>();\r\n addAll(list, items);\r\n return list;\r\n }", "List<MwDumpFile> mergeDumpLists(List<MwDumpFile> localDumps,\n\t\t\tList<MwDumpFile> onlineDumps) {\n\t\tList<MwDumpFile> result = new ArrayList<>(localDumps);\n\n\t\tHashSet<String> localDateStamps = new HashSet<>();\n\t\tfor (MwDumpFile dumpFile : localDumps) {\n\t\t\tlocalDateStamps.add(dumpFile.getDateStamp());\n\t\t}\n\t\tfor (MwDumpFile dumpFile : onlineDumps) {\n\t\t\tif (!localDateStamps.contains(dumpFile.getDateStamp())) {\n\t\t\t\tresult.add(dumpFile);\n\t\t\t}\n\t\t}\n\t\tresult.sort(Collections.reverseOrder(new MwDumpFile.DateComparator()));\n\t\treturn result;\n\t}", "public synchronized void pauseDeployment(final String deployment, ServerActivityCallback listener) {\n final List<ControlPoint> eps = new ArrayList<ControlPoint>();\n for (ControlPoint ep : entryPoints.values()) {\n if (ep.getDeployment().equals(deployment)) {\n if(!ep.isPaused()) {\n eps.add(ep);\n }\n }\n }\n CountingRequestCountCallback realListener = new CountingRequestCountCallback(eps.size(), listener);\n for (ControlPoint ep : eps) {\n ep.pause(realListener);\n }\n }", "@Override\n public DiscordianDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }", "public <T> List<T> query(String query, Class<T> classOfT) {\r\n InputStream instream = null;\r\n List<T> result = new ArrayList<T>();\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 if (json.has(\"rows\")) {\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 e : json.getAsJsonArray(\"rows\")) {\r\n result.add(jsonToObject(client.getGson(), e, \"doc\", classOfT));\r\n }\r\n } else {\r\n log.warning(\"No ungrouped result available. Use queryGroups() if grouping set\");\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 <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 Set<String> rangeByRank(final long start, final long end) {\n return doWithJedis(new JedisCallable<Set<String>>() {\n @Override\n public Set<String> call(Jedis jedis) {\n return jedis.zrange(getKey(), start, end);\n }\n });\n }", "@JsonAnySetter\n public void setUnknownField(final String name, final Object value) {\n this.unknownFields.put(name, value);\n }" ]
Returns an Object array of all FK field values of the specified object. If the specified object is an unmaterialized Proxy, it will be materialized to read the FK values. @throws MetadataException if an error occours while accessing ForeingKey values on obj
[ "public Object[] getForeignKeyValues(Object obj, ClassDescriptor mif)\r\n throws PersistenceBrokerException\r\n {\r\n FieldDescriptor[] fks = getForeignKeyFieldDescriptors(mif);\r\n // materialize object only if FK fields are declared\r\n if(fks.length > 0) obj = ProxyHelper.getRealObject(obj);\r\n Object[] result = new Object[fks.length];\r\n for (int i = 0; i < result.length; i++)\r\n {\r\n FieldDescriptor fmd = fks[i];\r\n PersistentField f = fmd.getPersistentField();\r\n\r\n // BRJ: do NOT convert.\r\n // conversion is done when binding the sql-statement\r\n //\r\n // FieldConversion fc = fmd.getFieldConversion();\r\n // Object val = fc.javaToSql(f.get(obj));\r\n\r\n result[i] = f.get(obj);\r\n }\r\n return result;\r\n }" ]
[ "public DateRange getRange(int index)\n {\n DateRange result;\n\n if (index >= 0 && index < m_ranges.size())\n {\n result = m_ranges.get(index);\n }\n else\n {\n result = DateRange.EMPTY_RANGE;\n }\n\n return (result);\n }", "public IPv6AddressSection[] mergeToSequentialBlocks(IPv6AddressSection ...sections) throws SizeMismatchException {\n\t\tList<IPAddressSegmentSeries> blocks = getMergedSequentialBlocks(this, sections, true, createSeriesCreator(getAddressCreator(), getMaxSegmentValue()));\n\t\treturn blocks.toArray(new IPv6AddressSection[blocks.size()]);\n\t}", "public void createPdfLayout(Dimension dim)\n {\n if (pdfdocument != null) //processing a PDF document\n {\n try {\n if (createImage)\n img = new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_RGB);\n Graphics2D ig = img.createGraphics();\n \n log.info(\"Creating PDF boxes\");\n VisualContext ctx = new VisualContext(null, null);\n \n boxtree = new CSSBoxTree(ig, ctx, dim, baseurl);\n boxtree.setConfig(config);\n boxtree.processDocument(pdfdocument, startPage, endPage);\n viewport = boxtree.getViewport();\n root = boxtree.getDocument().getDocumentElement();\n log.info(\"We have \" + boxtree.getLastId() + \" boxes\");\n viewport.initSubtree();\n \n log.info(\"Layout for \"+dim.width+\"px\");\n viewport.doLayout(dim.width, true, true);\n log.info(\"Resulting size: \" + viewport.getWidth() + \"x\" + viewport.getHeight() + \" (\" + viewport + \")\");\n \n log.info(\"Updating viewport size\");\n viewport.updateBounds(dim);\n log.info(\"Resulting size: \" + viewport.getWidth() + \"x\" + viewport.getHeight() + \" (\" + viewport + \")\");\n \n if (createImage && (viewport.getWidth() > dim.width || viewport.getHeight() > dim.height))\n {\n img = new BufferedImage(Math.max(viewport.getWidth(), dim.width),\n Math.max(viewport.getHeight(), dim.height),\n BufferedImage.TYPE_INT_RGB);\n ig = img.createGraphics();\n }\n \n log.info(\"Positioning for \"+img.getWidth()+\"x\"+img.getHeight()+\"px\");\n viewport.absolutePositions();\n \n clearCanvas();\n viewport.draw(new GraphicsRenderer(ig));\n setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));\n revalidate();\n } catch (ParserConfigurationException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n else if (root != null) //processing a DOM tree\n {\n super.createLayout(dim);\n }\n }", "@Override\n public boolean isCompleteRequest(ByteBuffer buffer) {\n DataInputStream inputStream = new DataInputStream(new ByteBufferBackedInputStream(buffer));\n\n try {\n int dataSize = inputStream.readInt();\n\n if(logger.isTraceEnabled())\n logger.trace(\"In isCompleteRequest, dataSize: \" + dataSize + \", buffer position: \"\n + buffer.position());\n\n if(dataSize == -1)\n return true;\n\n // Here we skip over the data (without reading it in) and\n // move our position to just past it.\n buffer.position(buffer.position() + dataSize);\n\n return true;\n } catch(Exception e) {\n // This could also occur if the various methods we call into\n // re-throw a corrupted value error as some other type of exception.\n // For example, updating the position on a buffer past its limit\n // throws an InvalidArgumentException.\n if(logger.isTraceEnabled())\n logger.trace(\"In isCompleteRequest, probable partial read occurred: \" + e);\n\n return false;\n }\n }", "public void setJdbcLevel(String jdbcLevel)\r\n {\r\n if (jdbcLevel != null)\r\n {\r\n try\r\n {\r\n double intLevel = Double.parseDouble(jdbcLevel);\r\n setJdbcLevel(intLevel);\r\n }\r\n catch(NumberFormatException nfe)\r\n {\r\n setJdbcLevel(2.0);\r\n logger.info(\"Specified JDBC level was not numeric (Value=\" + jdbcLevel + \"), used default jdbc level of 2.0 \");\r\n }\r\n }\r\n else\r\n {\r\n setJdbcLevel(2.0);\r\n logger.info(\"Specified JDBC level was null, used default jdbc level of 2.0 \");\r\n }\r\n }", "public static CrashReport fromJson(String json) throws IllegalArgumentException {\n try {\n return new CrashReport(json);\n } catch (JSONException je) {\n throw new IllegalArgumentException(je.toString());\n }\n }", "public static String getStringOption(Map<String, String> configOptions, String optionKey, String defaultValue) {\n\n String result = configOptions.get(optionKey);\n return null != result ? result : defaultValue;\n }", "private static final String correctNumberFormat(String value)\n {\n String result;\n int index = value.indexOf(',');\n if (index == -1)\n {\n result = value;\n }\n else\n {\n char[] chars = value.toCharArray();\n chars[index] = '.';\n result = new String(chars);\n }\n return result;\n }", "protected static final Long parseUsingFallbacksWithColon(String text, DateTimeFormat timeFormat) {\n if (text.indexOf(':') == -1) {\n text = text.replace(\" \", \"\");\n int numdigits = 0;\n int lastdigit = 0;\n for (int i = 0; i < text.length(); i++) {\n char c = text.charAt(i);\n if (Character.isDigit(c)) {\n numdigits++;\n lastdigit = i;\n }\n }\n if (numdigits == 1 || numdigits == 2) {\n // insert :00\n int colon = lastdigit + 1;\n text = text.substring(0, colon) + \":00\" + text.substring(colon);\n }\n else if (numdigits > 2) {\n // insert :\n int colon = lastdigit - 1;\n text = text.substring(0, colon) + \":\" + text.substring(colon);\n }\n return parseUsingFallbacks(text, timeFormat);\n }\n else {\n return null;\n }\n }" ]
Use this API to fetch systemsession resource of given name .
[ "public static systemsession get(nitro_service service, Long sid) throws Exception{\n\t\tsystemsession obj = new systemsession();\n\t\tobj.set_sid(sid);\n\t\tsystemsession response = (systemsession) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
[ "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 }", "static void setSingleParam(String key, String value, DbConn cnx)\n {\n QueryResult r = cnx.runUpdate(\"globalprm_update_value_by_key\", value, key);\n if (r.nbUpdated == 0)\n {\n cnx.runUpdate(\"globalprm_insert\", key, value);\n }\n cnx.commit();\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 void postConstruct(GeoService geoService, DtoConverterService converterService) throws GeomajasException {\n\t\tif (null == layerInfo) {\n\t\t\tlayerInfo = new RasterLayerInfo();\n\t\t}\n\t\tlayerInfo.setCrs(TiledRasterLayerService.MERCATOR);\n\t\tcrs = geoService.getCrs2(TiledRasterLayerService.MERCATOR);\n\t\tlayerInfo.setTileWidth(tileSize);\n\t\tlayerInfo.setTileHeight(tileSize);\n\t\tBbox bbox = new Bbox(-TiledRasterLayerService.HALF_EQUATOR_IN_METERS,\n\t\t\t\t-TiledRasterLayerService.HALF_EQUATOR_IN_METERS, TiledRasterLayerService.EQUATOR_IN_METERS,\n\t\t\t\tTiledRasterLayerService.EQUATOR_IN_METERS);\n\t\tlayerInfo.setMaxExtent(bbox);\n\t\tmaxBounds = converterService.toInternal(bbox);\n\n\t\tresolutions = new double[maxZoomLevel + 1];\n\t\tdouble powerOfTwo = 1;\n\t\tfor (int zoomLevel = 0; zoomLevel <= maxZoomLevel; zoomLevel++) {\n\t\t\tdouble resolution = (TiledRasterLayerService.EQUATOR_IN_METERS) / (tileSize * powerOfTwo);\n\t\t\tresolutions[zoomLevel] = resolution;\n\t\t\tpowerOfTwo *= 2;\n\t\t}\n\t}", "private Server setUpServer() {\n Server server = new Server(port);\n ResourceHandler handler = new ResourceHandler();\n handler.setDirectoriesListed(true);\n handler.setWelcomeFiles(new String[]{\"index.html\"});\n handler.setResourceBase(getReportDirectoryPath().toAbsolutePath().toString());\n HandlerList handlers = new HandlerList();\n handlers.setHandlers(new Handler[]{handler, new DefaultHandler()});\n server.setStopAtShutdown(true);\n server.setHandler(handlers);\n return server;\n }", "private void dbUpgrade()\n {\n DbConn cnx = this.getConn();\n Map<String, Object> rs = null;\n int db_schema_version = 0;\n try\n {\n rs = cnx.runSelectSingleRow(\"version_select_latest\");\n db_schema_version = (Integer) rs.get(\"VERSION_D1\");\n }\n catch (Exception e)\n {\n // Database is to be created, so version 0 is OK.\n }\n cnx.rollback();\n\n if (SCHEMA_VERSION > db_schema_version)\n {\n jqmlogger.warn(\"Database is being upgraded from version {} to version {}\", db_schema_version, SCHEMA_VERSION);\n\n // Upgrade scripts are named from_to.sql with 5 padding (e.g. 00000_00003.sql)\n // We try to find the fastest path (e.g. a direct 00000_00005.sql for creating a version 5 schema from nothing)\n // This is a simplistic and non-optimal algorithm as we try only a single path (no going back)\n\n int loop_from = db_schema_version;\n int to = db_schema_version;\n List<String> toApply = new ArrayList<>();\n toApply.addAll(adapter.preSchemaCreationScripts());\n\n while (to != SCHEMA_VERSION)\n {\n boolean progressed = false;\n for (int loop_to = SCHEMA_VERSION; loop_to > db_schema_version; loop_to--)\n {\n String migrationFileName = String.format(\"/sql/%05d_%05d.sql\", loop_from, loop_to);\n jqmlogger.debug(\"Trying migration script {}\", migrationFileName);\n if (Db.class.getResource(migrationFileName) != null)\n {\n toApply.add(migrationFileName);\n to = loop_to;\n loop_from = loop_to;\n progressed = true;\n break;\n }\n }\n\n if (!progressed)\n {\n break;\n }\n }\n if (to != SCHEMA_VERSION)\n {\n throw new DatabaseException(\n \"There is no migration path from version \" + db_schema_version + \" to version \" + SCHEMA_VERSION);\n }\n\n for (String s : toApply)\n {\n jqmlogger.info(\"Running migration script {}\", s);\n ScriptRunner.run(cnx, s);\n }\n cnx.commit(); // Yes, really. For advanced DB!\n\n cnx.close(); // HSQLDB does not refresh its schema without this.\n cnx = getConn();\n\n cnx.runUpdate(\"version_insert\", SCHEMA_VERSION, SCHEMA_COMPATIBLE_VERSION);\n cnx.commit();\n jqmlogger.info(\"Database is now up to date\");\n }\n else\n {\n jqmlogger.info(\"Database is already up to date\");\n }\n cnx.close();\n }", "private boolean relevant(File currentLogFile, GregorianCalendar lastRelevantDate) {\n\t\tString fileName=currentLogFile.getName();\n\t\tPattern p = Pattern.compile(APPENER_DATE_DEFAULT_PATTERN);\n\t\tMatcher m = p.matcher(fileName);\n\t\tif(m.find()){\n\t\t\tint year=Integer.parseInt(m.group(1));\n\t\t\tint month=Integer.parseInt(m.group(2));\n\t\t\tint dayOfMonth=Integer.parseInt(m.group(3));\n\t\t\tGregorianCalendar fileDate=new GregorianCalendar(year, month, dayOfMonth);\n\t\t\tfileDate.add(Calendar.MONTH,-1); //Because of Calendar save the month such that January is 0\n\t\t\treturn fileDate.compareTo(lastRelevantDate)>0;\n\t\t}\n\t\telse{\n\t\t\treturn false;\n\t\t}\n\t}", "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}", "public static void applyHyperLinkToElement(DynamicJasperDesign design, DJHyperLink djlink, JRDesignChart chart, String name) {\n\t\tJRDesignExpression hlpe = ExpressionUtils.createAndRegisterExpression(design, name, djlink.getExpression());\n\t\tchart.setHyperlinkReferenceExpression(hlpe);\n\t\tchart.setHyperlinkType( HyperlinkTypeEnum.REFERENCE ); //FIXME Should this be a parameter in the future?\n\t\t\t\t\n\t\tif (djlink.getTooltip() != null){\t\t\t\n\t\t\tJRDesignExpression tooltipExp = ExpressionUtils.createAndRegisterExpression(design, \"tooltip_\" + name, djlink.getTooltip());\n\t\t\tchart.setHyperlinkTooltipExpression(tooltipExp);\n\t\t}\n\t}" ]
Process a currency definition. @param row record from XER file
[ "private void processCurrency(Row row)\n {\n String currencyName = row.getString(\"curr_short_name\");\n DecimalFormatSymbols symbols = new DecimalFormatSymbols();\n symbols.setDecimalSeparator(row.getString(\"decimal_symbol\").charAt(0));\n symbols.setGroupingSeparator(row.getString(\"digit_group_symbol\").charAt(0));\n DecimalFormat nf = new DecimalFormat();\n nf.setDecimalFormatSymbols(symbols);\n nf.applyPattern(\"#.#\");\n m_currencyMap.put(currencyName, nf);\n\n if (currencyName.equalsIgnoreCase(m_defaultCurrencyName))\n {\n m_numberFormat = nf;\n m_defaultCurrencyData = row;\n }\n }" ]
[ "public static List<List<RTFEmbeddedObject>> getEmbeddedObjects(String text)\n {\n List<List<RTFEmbeddedObject>> objects = null;\n List<RTFEmbeddedObject> objectData;\n\n int offset = text.indexOf(OBJDATA);\n if (offset != -1)\n {\n objects = new LinkedList<List<RTFEmbeddedObject>>();\n\n while (offset != -1)\n {\n objectData = new LinkedList<RTFEmbeddedObject>();\n objects.add(objectData);\n offset = readObjectData(offset, text, objectData);\n offset = text.indexOf(OBJDATA, offset);\n }\n }\n\n return (objects);\n }", "public float conditionalLogProb(int[] given, int of) {\r\n if (given.length != windowSize - 1) {\r\n System.err.println(\"error computing conditional log prob\");\r\n System.exit(0);\r\n }\r\n int[] label = indicesFront(given);\r\n float[] masses = new float[label.length];\r\n for (int i = 0; i < masses.length; i++) {\r\n masses[i] = table[label[i]];\r\n }\r\n float z = ArrayMath.logSum(masses);\r\n\r\n return table[indexOf(given, of)] - z;\r\n }", "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 }", "public static void addIndex(DBCollection collection, String field, boolean asc, boolean background) {\n int dir = (asc) ? 1 : -1;\n collection.createIndex(new BasicDBObject(field, dir), new BasicDBObject(\"background\", background));\n }", "private float[] generateParticleTimeStamps(float totalTime)\n {\n float timeStamps[] = new float[mEmitRate * 2];\n\n if ( burstMode ) {\n for (int i = 0; i < mEmitRate * 2; i += 2) {\n timeStamps[i] = totalTime;\n timeStamps[i + 1] = 0;\n }\n }\n else {\n for (int i = 0; i < mEmitRate * 2; i += 2) {\n timeStamps[i] = totalTime + mRandom.nextFloat();\n timeStamps[i + 1] = 0;\n }\n }\n return timeStamps;\n\n }", "public ParsedWord pollParsedWord() {\n if(hasNextWord()) {\n //set correct next char\n if(parsedLine.words().size() > (word+1))\n character = parsedLine.words().get(word+1).lineIndex();\n else\n character = -1;\n return parsedLine.words().get(word++);\n }\n else\n return new ParsedWord(null, -1);\n }", "public static DeploymentReflectionIndex create() {\n final SecurityManager sm = System.getSecurityManager();\n if (sm != null) {\n sm.checkPermission(ServerPermission.CREATE_DEPLOYMENT_REFLECTION_INDEX);\n }\n return new DeploymentReflectionIndex();\n }", "public static URL buildUrl(String scheme, String host, int port, String path, Map<String, String> parameters) throws MalformedURLException {\r\n checkSchemeAndPort(scheme, port);\r\n StringBuilder buffer = new StringBuilder();\r\n if (!host.startsWith(scheme + \"://\")) {\r\n buffer.append(scheme).append(\"://\");\r\n }\r\n buffer.append(host);\r\n if (port > 0) {\r\n buffer.append(':');\r\n buffer.append(port);\r\n }\r\n if (path == null) {\r\n path = \"/\";\r\n }\r\n buffer.append(path);\r\n\r\n if (!parameters.isEmpty()) {\r\n buffer.append('?');\r\n }\r\n int size = parameters.size();\r\n for (Map.Entry<String, String> entry : parameters.entrySet()) {\r\n buffer.append(entry.getKey());\r\n buffer.append('=');\r\n Object value = entry.getValue();\r\n if (value != null) {\r\n String string = value.toString();\r\n try {\r\n string = URLEncoder.encode(string, UTF8);\r\n } catch (UnsupportedEncodingException e) {\r\n // Should never happen, but just in case\r\n }\r\n buffer.append(string);\r\n }\r\n if (--size != 0) {\r\n buffer.append('&');\r\n }\r\n }\r\n\r\n /*\r\n * RequestContext requestContext = RequestContext.getRequestContext(); Auth auth = requestContext.getAuth(); if (auth != null &&\r\n * !ignoreMethod(getMethod(parameters))) { buffer.append(\"&api_sig=\"); buffer.append(AuthUtilities.getSignature(sharedSecret, parameters)); }\r\n */\r\n\r\n return new URL(buffer.toString());\r\n }", "public 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}" ]
Read filename from spec.
[ "private static String getFileName(@Nullable final MapPrinter mapPrinter, final PJsonObject spec) {\n String fileName = spec.optString(Constants.OUTPUT_FILENAME_KEY);\n if (fileName != null) {\n return fileName;\n }\n\n if (mapPrinter != null) {\n final Configuration config = mapPrinter.getConfiguration();\n final String templateName = spec.getString(Constants.JSON_LAYOUT_KEY);\n\n final Template template = config.getTemplate(templateName);\n\n if (template.getOutputFilename() != null) {\n return template.getOutputFilename();\n }\n\n if (config.getOutputFilename() != null) {\n return config.getOutputFilename();\n }\n }\n return \"mapfish-print-report\";\n }" ]
[ "static synchronized LogContext configureLogContext(final File logDir, final File configDir, final String defaultLogFileName, final CommandContext ctx) {\n final LogContext embeddedLogContext = Holder.LOG_CONTEXT;\n final Path bootLog = logDir.toPath().resolve(Paths.get(defaultLogFileName));\n final Path loggingProperties = configDir.toPath().resolve(Paths.get(\"logging.properties\"));\n if (Files.exists(loggingProperties)) {\n WildFlySecurityManager.setPropertyPrivileged(\"org.jboss.boot.log.file\", bootLog.toAbsolutePath().toString());\n\n try (final InputStream in = Files.newInputStream(loggingProperties)) {\n // Attempt to get the configurator from the root logger\n Configurator configurator = embeddedLogContext.getAttachment(\"\", Configurator.ATTACHMENT_KEY);\n if (configurator == null) {\n configurator = new PropertyConfigurator(embeddedLogContext);\n final Configurator existing = embeddedLogContext.getLogger(\"\").attachIfAbsent(Configurator.ATTACHMENT_KEY, configurator);\n if (existing != null) {\n configurator = existing;\n }\n }\n configurator.configure(in);\n } catch (IOException e) {\n ctx.printLine(String.format(\"Unable to configure logging from configuration file %s. Reason: %s\", loggingProperties, e.getLocalizedMessage()));\n }\n }\n return embeddedLogContext;\n }", "public void setPublishQueueShutdowntime(String publishQueueShutdowntime) {\n\n if (m_frozen) {\n throw new CmsRuntimeException(Messages.get().container(Messages.ERR_CONFIG_FROZEN_0));\n }\n m_publishQueueShutdowntime = Integer.parseInt(publishQueueShutdowntime);\n }", "public 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}", "private void writeTasks() throws IOException\n {\n writeAttributeTypes(\"task_types\", TaskField.values());\n\n m_writer.writeStartList(\"tasks\");\n for (Task task : m_projectFile.getChildTasks())\n {\n writeTask(task);\n }\n m_writer.writeEndList();\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 }", "private void distributedProcessFinish(ResponseBuilder rb,\n ComponentFields mtasFields) throws IOException {\n // rewrite\n\n Object mtasResponseRaw;\n if ((mtasResponseRaw = rb.rsp.getValues().get(\"mtas\")) != null\n && mtasResponseRaw instanceof NamedList) {\n NamedList<Object> mtasResponse = (NamedList<Object>) mtasResponseRaw;\n Object mtasResponseTermvectorRaw;\n if ((mtasResponseTermvectorRaw = mtasResponse.get(NAME)) != null\n && mtasResponseTermvectorRaw instanceof ArrayList) {\n MtasSolrResultUtil.rewrite(\n (ArrayList<Object>) mtasResponseTermvectorRaw, searchComponent);\n }\n }\n }", "protected List<String> splitLinesAndNewLines(String text) {\n\t\tif (text == null)\n\t\t\treturn Collections.emptyList();\n\t\tint idx = initialSegmentSize(text);\n\t\tif (idx == text.length()) {\n\t\t\treturn Collections.singletonList(text);\n\t\t}\n\n\t\treturn continueSplitting(text, idx);\n\t}", "private void tryToSetParsedValue(String value) throws Exception {\n\n JSONObject json = JSONParser.parseStrict(value).isObject();\n JSONValue val = json.get(JsonKey.START);\n setStart(readOptionalDate(val));\n val = json.get(JsonKey.END);\n setEnd(readOptionalDate(val));\n setWholeDay(readOptionalBoolean(json.get(JsonKey.WHOLE_DAY)));\n JSONObject patternJson = json.get(JsonKey.PATTERN).isObject();\n readPattern(patternJson);\n setExceptions(readDates(json.get(JsonKey.EXCEPTIONS)));\n setSeriesEndDate(readOptionalDate(json.get(JsonKey.SERIES_ENDDATE)));\n setOccurrences(readOptionalInt(json.get(JsonKey.SERIES_OCCURRENCES)));\n setDerivedEndType();\n setCurrentTillEnd(readOptionalBoolean(json.get(JsonKey.CURRENT_TILL_END)));\n setParentSeriesId(readOptionalUUID(json.get(JsonKey.PARENT_SERIES)));\n\n }", "public ValueContainer[] getKeyValues(ClassDescriptor cld, Identity oid, boolean convertToSql) throws PersistenceBrokerException\r\n {\r\n FieldDescriptor[] pkFields = cld.getPkFields();\r\n ValueContainer[] result = new ValueContainer[pkFields.length];\r\n Object[] pkValues = oid.getPrimaryKeyValues();\r\n\r\n try\r\n {\r\n for(int i = 0; i < result.length; i++)\r\n {\r\n FieldDescriptor fd = pkFields[i];\r\n Object cv = pkValues[i];\r\n if(convertToSql)\r\n {\r\n // BRJ : apply type and value mapping\r\n cv = fd.getFieldConversion().javaToSql(cv);\r\n }\r\n result[i] = new ValueContainer(cv, fd.getJdbcType());\r\n }\r\n }\r\n catch(Exception e)\r\n {\r\n throw new PersistenceBrokerException(\"Can't generate primary key values for given Identity \" + oid, e);\r\n }\r\n return result;\r\n }" ]