query
stringlengths
7
3.3k
positive
sequencelengths
1
1
negative
sequencelengths
9
9
Gets the date time str standard. @param d the d @return the date time str standard
[ "public static String getDateTimeStrStandard(Date d) {\n if (d == null)\n return \"\";\n\n if (d.getTime() == 0L)\n return \"Never\";\n\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy.MM.dd.HH.mm.ss.SSSZ\");\n\n return sdf.format(d);\n }" ]
[ "public List<TimephasedWork> getTimephasedOvertimeWork()\n {\n if (m_timephasedOvertimeWork == null && m_timephasedWork != null && getOvertimeWork() != null)\n {\n double perDayFactor = getRemainingOvertimeWork().getDuration() / (getRemainingWork().getDuration() - getRemainingOvertimeWork().getDuration());\n double totalFactor = getRemainingOvertimeWork().getDuration() / getRemainingWork().getDuration();\n\n perDayFactor = Double.isNaN(perDayFactor) ? 0 : perDayFactor;\n totalFactor = Double.isNaN(totalFactor) ? 0 : totalFactor;\n\n m_timephasedOvertimeWork = new DefaultTimephasedWorkContainer(m_timephasedWork, perDayFactor, totalFactor);\n }\n return m_timephasedOvertimeWork == null ? null : m_timephasedOvertimeWork.getData();\n }", "public static <T> Set<T> getSet(Collection<T> collection) {\n Set<T> set = new LinkedHashSet<T>();\n set.addAll(collection);\n\n return set;\n }", "private ProjectFile handleZipFile(InputStream stream) throws Exception\n {\n File dir = null;\n\n try\n {\n dir = InputStreamHelper.writeZipStreamToTempDir(stream);\n ProjectFile result = handleDirectory(dir);\n if (result != null)\n {\n return result;\n }\n }\n\n finally\n {\n FileHelper.deleteQuietly(dir);\n }\n\n return null;\n }", "public static Object buildNewObjectInstance(ClassDescriptor cld)\r\n {\r\n Object result = null;\r\n\r\n // If either the factory class and/or factory method is null,\r\n // just follow the normal code path and create via constructor\r\n if ((cld.getFactoryClass() == null) || (cld.getFactoryMethod() == null))\r\n {\r\n try\r\n {\r\n // 1. create an empty Object (persistent classes need a public default constructor)\r\n Constructor con = cld.getZeroArgumentConstructor();\r\n if(con == null)\r\n {\r\n throw new ClassNotPersistenceCapableException(\r\n \"A zero argument constructor was not provided! Class was '\" + cld.getClassNameOfObject() + \"'\");\r\n }\r\n result = ConstructorHelper.instantiate(con);\r\n }\r\n catch (InstantiationException e)\r\n {\r\n throw new ClassNotPersistenceCapableException(\r\n \"Can't instantiate class '\" + cld.getClassNameOfObject()+\"'\");\r\n }\r\n }\r\n else\r\n {\r\n try\r\n {\r\n // 1. create an empty Object by calling the no-parms factory method\r\n Method method = cld.getFactoryMethod();\r\n\r\n if (Modifier.isStatic(method.getModifiers()))\r\n {\r\n // method is static so call it directly\r\n result = method.invoke(null, null);\r\n }\r\n else\r\n {\r\n // method is not static, so create an object of the factory first\r\n // note that this requires a public no-parameter (default) constructor\r\n Object factoryInstance = cld.getFactoryClass().newInstance();\r\n\r\n result = method.invoke(factoryInstance, null);\r\n }\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new PersistenceBrokerException(\"Unable to build object instance of class '\"\r\n + cld.getClassNameOfObject() + \"' from factory:\" + cld.getFactoryClass()\r\n + \".\" + cld.getFactoryMethod(), ex);\r\n }\r\n }\r\n return result;\r\n }", "private Object getLiteralValue(Expression expression) {\n\t\tif (!(expression instanceof Literal)) {\n\t\t\tthrow new IllegalArgumentException(\"Expression \" + expression + \" is not a Literal.\");\n\t\t}\n\t\treturn ((Literal) expression).getValue();\n\t}", "@SuppressWarnings(\"unused\")\n public static void addTo(\n AbstractSingleComponentContainer componentContainer,\n int scrollBarrier,\n int barrierMargin,\n String styleName) {\n\n new CmsScrollPositionCss(componentContainer, scrollBarrier, barrierMargin, styleName);\n }", "private boolean isClockwise(Point center, Point a, Point b) {\n double cross = (a.x - center.x) * (b.y - center.y) - (b.x - center.x) * (a.y - center.y);\n return cross > 0;\n }", "public void addHiDpiImage(String factor, CmsJspImageBean image) {\n\n if (m_hiDpiImages == null) {\n m_hiDpiImages = CmsCollectionsGenericWrapper.createLazyMap(new CmsScaleHiDpiTransformer());\n }\n m_hiDpiImages.put(factor, image);\n }", "public static RowColumn toRowColumn(Key key) {\n if (key == null) {\n return RowColumn.EMPTY;\n }\n if ((key.getRow() == null) || key.getRow().getLength() == 0) {\n return RowColumn.EMPTY;\n }\n Bytes row = ByteUtil.toBytes(key.getRow());\n if ((key.getColumnFamily() == null) || key.getColumnFamily().getLength() == 0) {\n return new RowColumn(row);\n }\n Bytes cf = ByteUtil.toBytes(key.getColumnFamily());\n if ((key.getColumnQualifier() == null) || key.getColumnQualifier().getLength() == 0) {\n return new RowColumn(row, new Column(cf));\n }\n Bytes cq = ByteUtil.toBytes(key.getColumnQualifier());\n if ((key.getColumnVisibility() == null) || key.getColumnVisibility().getLength() == 0) {\n return new RowColumn(row, new Column(cf, cq));\n }\n Bytes cv = ByteUtil.toBytes(key.getColumnVisibility());\n return new RowColumn(row, new Column(cf, cq, cv));\n }" ]
Set whether the player holding the waveform is playing, which changes the indicator color to white from red. This method can only be used in situations where the component is tied to a single player, and therefore has a single playback position. @param playing if {@code true}, draw the position marker in white, otherwise red @see #setPlaybackState
[ "private void setPlaying(boolean playing) {\n PlaybackState oldState = currentSimpleState();\n if (oldState != null && oldState.playing != playing) {\n setPlaybackState(oldState.player, oldState.position, playing);\n }\n }" ]
[ "private void remove(String directoryName) {\n if ((directoryName == null) || (conn == null))\n return;\n\n String key = S3Util.sanitize(directoryName) + \"/\" + S3Util.sanitize(DC_FILE_NAME);\n try {\n Map headers = new TreeMap();\n headers.put(\"Content-Type\", Arrays.asList(\"text/plain\"));\n if (usingPreSignedUrls()) {\n conn.delete(pre_signed_delete_url).connection.getResponseMessage();\n } else {\n conn.delete(location, key, headers).connection.getResponseMessage();\n }\n }\n catch(Exception e) {\n ROOT_LOGGER.cannotRemoveS3File(e);\n }\n }", "@VisibleForTesting\n protected static double getNearestNiceValue(\n final double value, final DistanceUnit scaleUnit, final boolean lockUnits) {\n DistanceUnit bestUnit = bestUnit(scaleUnit, value, lockUnits);\n double factor = scaleUnit.convertTo(1.0, bestUnit);\n\n // nearest power of 10 lower than value\n int digits = (int) Math.floor((Math.log(value * factor) / Math.log(10)));\n double pow10 = Math.pow(10, digits);\n\n // ok, find first character\n double firstChar = value * factor / pow10;\n\n // right, put it into the correct bracket\n int barLen;\n if (firstChar >= 10.0) {\n barLen = 10;\n } else if (firstChar >= 5.0) {\n barLen = 5;\n } else if (firstChar >= 2.0) {\n barLen = 2;\n } else {\n barLen = 1;\n }\n\n // scale it up the correct power of 10\n return barLen * pow10 / factor;\n }", "@RequestMapping(value = \"api/edit/server\", method = RequestMethod.POST)\n public\n @ResponseBody\n ServerRedirect addRedirectToProfile(Model model,\n @RequestParam(value = \"profileId\", required = false) Integer profileId,\n @RequestParam(value = \"profileIdentifier\", required = false) String profileIdentifier,\n @RequestParam(value = \"srcUrl\", required = true) String srcUrl,\n @RequestParam(value = \"destUrl\", required = true) String destUrl,\n @RequestParam(value = \"clientUUID\", required = true) String clientUUID,\n @RequestParam(value = \"hostHeader\", required = false) String hostHeader) throws Exception {\n if (profileId == null && profileIdentifier == null) {\n throw new Exception(\"profileId required\");\n }\n if (profileId == null) {\n profileId = ProfileService.getInstance().getIdFromName(profileIdentifier);\n }\n\n int clientId = ClientService.getInstance().findClient(clientUUID, profileId).getId();\n\n int redirectId = ServerRedirectService.getInstance().addServerRedirectToProfile(\"\", srcUrl, destUrl, hostHeader,\n profileId, clientId);\n return ServerRedirectService.getInstance().getRedirect(redirectId);\n }", "public <G extends T> RendererBuilder<T> bind(Class<G> clazz, Renderer<? extends G> prototype) {\n if (clazz == null || prototype == null) {\n throw new IllegalArgumentException(\n \"The binding RecyclerView binding can't be configured using null instances\");\n }\n prototypes.add(prototype);\n binding.put(clazz, prototype.getClass());\n return this;\n }", "public String build() {\n if (!root.containsKey(\"mdm\")) {\n insertCustomAlert();\n root.put(\"aps\", aps);\n }\n try {\n return mapper.writeValueAsString(root);\n } catch (final Exception e) {\n throw new RuntimeException(e);\n }\n }", "@Override\n protected void addLineContent(BufferedReader bufferedFileReader, List<String> content, String line) throws IOException {\n // Is the line an empty comment \"#\" ?\n if (line.startsWith(COMMENT_PREFIX) && line.length() == 1) {\n String nextLine = bufferedFileReader.readLine();\n if (nextLine != null) {\n // Is the next line the realm name \"#$REALM_NAME=\" ?\n if (nextLine.startsWith(COMMENT_PREFIX) && nextLine.contains(REALM_COMMENT_PREFIX)) {\n // Realm name block detected!\n // The next line must be and empty comment \"#\"\n bufferedFileReader.readLine();\n // Avoid adding the realm block\n } else {\n // It's a user comment...\n content.add(line);\n content.add(nextLine);\n }\n } else {\n super.addLineContent(bufferedFileReader, content, line);\n }\n } else {\n super.addLineContent(bufferedFileReader, content, line);\n }\n }", "public String findAlias(String entityAlias, List<String> propertyPathWithoutAlias) {\n\t\tRelationshipAliasTree aliasTree = relationshipAliases.get( entityAlias );\n\t\tif ( aliasTree == null ) {\n\t\t\treturn null;\n\t\t}\n\t\tRelationshipAliasTree associationAlias = aliasTree;\n\t\tfor ( int i = 0; i < propertyPathWithoutAlias.size(); i++ ) {\n\t\t\tassociationAlias = associationAlias.findChild( propertyPathWithoutAlias.get( i ) );\n\t\t\tif ( associationAlias == null ) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\treturn associationAlias.getAlias();\n\t}", "public boolean clearParameters() {\n this.query = null;\n this.fields = null;\n this.scope = null;\n this.fileExtensions = null;\n this.createdRange = null;\n this.updatedRange = null;\n this.sizeRange = null;\n this.ownerUserIds = null;\n this.ancestorFolderIds = null;\n this.contentTypes = null;\n this.type = null;\n this.trashContent = null;\n this.metadataFilter = null;\n this.sort = null;\n this.direction = null;\n return true;\n }", "public void validateInjectionPoint(InjectionPoint ij, BeanManagerImpl beanManager) {\n validateInjectionPointForDefinitionErrors(ij, ij.getBean(), beanManager);\n validateMetadataInjectionPoint(ij, ij.getBean(), ValidatorLogger.INJECTION_INTO_NON_BEAN);\n validateEventMetadataInjectionPoint(ij);\n validateInjectionPointForDeploymentProblems(ij, ij.getBean(), beanManager);\n }" ]
Uploads a new large file. @param boxApi the API connection to be used by the upload session. @param folderId the id of the folder in which the file will be uploaded. @param stream the input stream that feeds the content of the file. @param url the upload session URL. @param fileName the name of the file to be created. @param fileSize the total size of the file. @return the created file instance. @throws InterruptedException when a thread gets interupted. @throws IOException when reading a stream throws exception.
[ "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 static authenticationradiusaction get(nitro_service service, String name) throws Exception{\n\t\tauthenticationradiusaction obj = new authenticationradiusaction();\n\t\tobj.set_name(name);\n\t\tauthenticationradiusaction response = (authenticationradiusaction) obj.get_resource(service);\n\t\treturn response;\n\t}", "protected void recycleChildren() {\n for (ListItemHostWidget host: getAllHosts()) {\n recycle(host);\n }\n mContent.onTransformChanged();\n mContent.requestLayout();\n }", "@SuppressWarnings(\"unchecked\")\n\tpublic <S extends IPAddressPartConfiguredString<T, P>> SQLStringMatcher<T, P, S> getNetworkStringMatcher(boolean isEntireAddress, IPAddressSQLTranslator translator) {\n\t\treturn new SQLStringMatcher<T, P, S>((S) this, isEntireAddress, translator);\n\t}", "public static StringBuffer leftShift(String self, Object value) {\n return new StringBuffer(self).append(value);\n }", "private FieldDescriptor getFldFromReference(TableAlias aTableAlias, ObjectReferenceDescriptor anOrd)\r\n {\r\n FieldDescriptor fld = null;\r\n\r\n if (aTableAlias == getRoot())\r\n {\r\n // no path expression\r\n FieldDescriptor[] fk = anOrd.getForeignKeyFieldDescriptors(aTableAlias.cld);\r\n if (fk.length > 0)\r\n {\r\n fld = fk[0];\r\n }\r\n }\r\n else\r\n {\r\n // attribute with path expression\r\n /**\r\n * MBAIRD\r\n * potentially people are referring to objects, not to the object's primary key, \r\n * and then we need to take the primary key attribute of the referenced object \r\n * to help them out.\r\n */\r\n ClassDescriptor cld = aTableAlias.cld.getRepository().getDescriptorFor(anOrd.getItemClass());\r\n if (cld != null)\r\n {\r\n fld = aTableAlias.cld.getFieldDescriptorByName(cld.getPkFields()[0].getPersistentField().getName());\r\n }\r\n }\r\n\r\n return fld;\r\n }", "private static void attachToDecor(Activity activity, MenuDrawer menuDrawer) {\n ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView();\n ViewGroup decorChild = (ViewGroup) decorView.getChildAt(0);\n\n decorView.removeAllViews();\n decorView.addView(menuDrawer, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);\n\n menuDrawer.mContentContainer.addView(decorChild, decorChild.getLayoutParams());\n }", "private void adjustVisibleColumns() {\n\n if (m_table.isColumnCollapsingAllowed()) {\n if ((m_model.hasDefaultValues()) || m_model.getBundleType().equals(BundleType.DESCRIPTOR)) {\n m_table.setColumnCollapsed(TableProperty.DEFAULT, false);\n } else {\n m_table.setColumnCollapsed(TableProperty.DEFAULT, true);\n }\n\n if (((m_model.getEditMode().equals(EditMode.MASTER) || m_model.hasDescriptionValues()))\n || m_model.getBundleType().equals(BundleType.DESCRIPTOR)) {\n m_table.setColumnCollapsed(TableProperty.DESCRIPTION, false);\n } else {\n m_table.setColumnCollapsed(TableProperty.DESCRIPTION, true);\n }\n }\n }", "public long removeRangeByScore(final ScoreRange scoreRange) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.zremrangeByScore(getKey(), scoreRange.from(), scoreRange.to());\n }\n });\n }", "public static Cluster\n balanceContiguousPartitionsPerZone(final Cluster nextCandidateCluster,\n final int maxContiguousPartitionsPerZone) {\n System.out.println(\"Balance number of contiguous partitions within a zone.\");\n System.out.println(\"numPartitionsPerZone\");\n for(int zoneId: nextCandidateCluster.getZoneIds()) {\n System.out.println(zoneId + \" : \"\n + nextCandidateCluster.getNumberOfPartitionsInZone(zoneId));\n }\n System.out.println(\"numNodesPerZone\");\n for(int zoneId: nextCandidateCluster.getZoneIds()) {\n System.out.println(zoneId + \" : \" + nextCandidateCluster.getNumberOfNodesInZone(zoneId));\n }\n\n // Break up contiguous partitions within each zone\n HashMap<Integer, List<Integer>> partitionsToRemoveFromZone = Maps.newHashMap();\n System.out.println(\"Contiguous partitions\");\n for(Integer zoneId: nextCandidateCluster.getZoneIds()) {\n System.out.println(\"\\tZone: \" + zoneId);\n Map<Integer, Integer> partitionToRunLength = PartitionBalanceUtils.getMapOfContiguousPartitions(nextCandidateCluster,\n zoneId);\n\n List<Integer> partitionsToRemoveFromThisZone = new ArrayList<Integer>();\n for(Map.Entry<Integer, Integer> entry: partitionToRunLength.entrySet()) {\n if(entry.getValue() > maxContiguousPartitionsPerZone) {\n List<Integer> contiguousPartitions = new ArrayList<Integer>(entry.getValue());\n for(int partitionId = entry.getKey(); partitionId < entry.getKey()\n + entry.getValue(); partitionId++) {\n contiguousPartitions.add(partitionId\n % nextCandidateCluster.getNumberOfPartitions());\n }\n System.out.println(\"Contiguous partitions: \" + contiguousPartitions);\n partitionsToRemoveFromThisZone.addAll(Utils.removeItemsToSplitListEvenly(contiguousPartitions,\n maxContiguousPartitionsPerZone));\n }\n }\n\n partitionsToRemoveFromZone.put(zoneId, partitionsToRemoveFromThisZone);\n System.out.println(\"\\t\\tPartitions to remove: \" + partitionsToRemoveFromThisZone);\n }\n\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n\n Random r = new Random();\n for(int zoneId: returnCluster.getZoneIds()) {\n for(int partitionId: partitionsToRemoveFromZone.get(zoneId)) {\n // Pick a random other zone Id\n List<Integer> otherZoneIds = new ArrayList<Integer>();\n for(int otherZoneId: returnCluster.getZoneIds()) {\n if(otherZoneId != zoneId) {\n otherZoneIds.add(otherZoneId);\n }\n }\n int whichOtherZoneId = otherZoneIds.get(r.nextInt(otherZoneIds.size()));\n\n // Pick a random node from other zone ID\n int whichNodeOffset = r.nextInt(returnCluster.getNumberOfNodesInZone(whichOtherZoneId));\n int whichNodeId = new ArrayList<Integer>(returnCluster.getNodeIdsInZone(whichOtherZoneId)).get(whichNodeOffset);\n\n // Steal partition from one zone to another!\n returnCluster = UpdateClusterUtils.createUpdatedCluster(returnCluster,\n whichNodeId,\n Lists.newArrayList(partitionId));\n }\n }\n\n return returnCluster;\n\n }" ]
Retrieve the configuration of the named template. @param name the template name;
[ "public final Template getTemplate(final String name) {\n final Template template = this.templates.get(name);\n if (template != null) {\n this.accessAssertion.assertAccess(\"Configuration\", this);\n template.assertAccessible(name);\n } else {\n throw new IllegalArgumentException(String.format(\"Template '%s' does not exist. Options are: \" +\n \"%s\", name, this.templates.keySet()));\n }\n return template;\n }" ]
[ "public User getUploadStatus() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_UPLOAD_STATUS);\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(\"id\"));\r\n user.setPro(\"1\".equals(userElement.getAttribute(\"ispro\")));\r\n user.setUsername(XMLUtilities.getChildValue(userElement, \"username\"));\r\n\r\n Element bandwidthElement = XMLUtilities.getChild(userElement, \"bandwidth\");\r\n user.setBandwidthMax(bandwidthElement.getAttribute(\"max\"));\r\n user.setBandwidthUsed(bandwidthElement.getAttribute(\"used\"));\r\n user.setIsBandwidthUnlimited(\"1\".equals(bandwidthElement.getAttribute(\"unlimited\")));\r\n\r\n Element filesizeElement = XMLUtilities.getChild(userElement, \"filesize\");\r\n user.setFilesizeMax(filesizeElement.getAttribute(\"max\"));\r\n\r\n Element setsElement = XMLUtilities.getChild(userElement, \"sets\");\r\n user.setSetsCreated(setsElement.getAttribute(\"created\"));\r\n user.setSetsRemaining(setsElement.getAttribute(\"remaining\"));\r\n\r\n Element videosElement = XMLUtilities.getChild(userElement, \"videos\");\r\n user.setVideosUploaded(videosElement.getAttribute(\"uploaded\"));\r\n user.setVideosRemaining(videosElement.getAttribute(\"remaining\"));\r\n\r\n Element videoSizeElement = XMLUtilities.getChild(userElement, \"videosize\");\r\n user.setVideoSizeMax(videoSizeElement.getAttribute(\"maxbytes\"));\r\n\r\n return user;\r\n }", "public void updateActive(int profileId, String clientUUID, Boolean active) throws Exception {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_CLIENT +\n \" SET \" + Constants.CLIENT_IS_ACTIVE + \"= ?\" +\n \" WHERE \" + Constants.GENERIC_CLIENT_UUID + \"= ? \" +\n \" AND \" + Constants.GENERIC_PROFILE_ID + \"= ?\"\n );\n statement.setBoolean(1, active);\n statement.setString(2, clientUUID);\n statement.setInt(3, profileId);\n statement.executeUpdate();\n } catch (Exception e) {\n // ok to swallow this.. just means there wasn't any\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "public Collection<Method> getAllMethods(String name, int paramCount) {\n final Map<ParamList, Map<Class<?>, Method>> nameMap = methods.get(name);\n if (nameMap == null) {\n return Collections.emptySet();\n }\n final Collection<Method> methods = new ArrayList<Method>();\n for (Map<Class<?>, Method> map : nameMap.values()) {\n for (Method method : map.values()) {\n if (method.getParameterTypes().length == paramCount) {\n methods.add(method);\n }\n }\n }\n return methods;\n }", "public static base_responses update(nitro_service client, snmpmanager resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsnmpmanager updateresources[] = new snmpmanager[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new snmpmanager();\n\t\t\t\tupdateresources[i].ipaddress = resources[i].ipaddress;\n\t\t\t\tupdateresources[i].netmask = resources[i].netmask;\n\t\t\t\tupdateresources[i].domainresolveretry = resources[i].domainresolveretry;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "public List<Long> getOffsets(OffsetRequest offsetRequest) {\n ILog log = getLog(offsetRequest.topic, offsetRequest.partition);\n if (log != null) {\n return log.getOffsetsBefore(offsetRequest);\n }\n return ILog.EMPTY_OFFSETS;\n }", "@Override\n @SuppressFBWarnings(value = \"UL_UNRELEASED_LOCK\", justification = \"False positive from FindBugs\")\n public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {\n if (!isActive()) {\n throw new ContextNotActiveException();\n }\n checkContextInitialized();\n final BeanStore beanStore = getBeanStore();\n if (beanStore == null) {\n return null;\n }\n if (contextual == null) {\n throw ContextLogger.LOG.contextualIsNull();\n }\n BeanIdentifier id = getId(contextual);\n ContextualInstance<T> beanInstance = beanStore.get(id);\n if (beanInstance != null) {\n return beanInstance.getInstance();\n } else if (creationalContext != null) {\n LockedBean lock = null;\n try {\n if (multithreaded) {\n lock = beanStore.lock(id);\n beanInstance = beanStore.get(id);\n if (beanInstance != null) {\n return beanInstance.getInstance();\n }\n }\n T instance = contextual.create(creationalContext);\n if (instance != null) {\n beanInstance = new SerializableContextualInstanceImpl<Contextual<T>, T>(contextual, instance, creationalContext, serviceRegistry.get(ContextualStore.class));\n beanStore.put(id, beanInstance);\n }\n return instance;\n } finally {\n if (lock != null) {\n lock.unlock();\n }\n }\n } else {\n return null;\n }\n }", "public 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 }", "public static ManagementProtocolHeader parse(DataInput input) throws IOException {\n validateSignature(input);\n expectHeader(input, ManagementProtocol.VERSION_FIELD);\n int version = input.readInt();\n expectHeader(input, ManagementProtocol.TYPE);\n byte type = input.readByte();\n switch (type) {\n case ManagementProtocol.TYPE_REQUEST:\n return new ManagementRequestHeader(version, input);\n case ManagementProtocol.TYPE_RESPONSE:\n return new ManagementResponseHeader(version, input);\n case ManagementProtocol.TYPE_BYE_BYE:\n return new ManagementByeByeHeader(version);\n case ManagementProtocol.TYPE_PING:\n return new ManagementPingHeader(version);\n case ManagementProtocol.TYPE_PONG:\n return new ManagementPongHeader(version);\n default:\n throw ProtocolLogger.ROOT_LOGGER.invalidType(\"0x\" + Integer.toHexString(type));\n }\n }", "public static spilloverpolicy[] get(nitro_service service, options option) throws Exception{\n\t\tspilloverpolicy obj = new spilloverpolicy();\n\t\tspilloverpolicy[] response = (spilloverpolicy[])obj.get_resources(service,option);\n\t\treturn response;\n\t}" ]
Get the number of views, comments and favorites on a photostream for a given date. @param date (Required) Stats will be returned for this date. A day according to Flickr Stats starts at midnight GMT for all users, and timestamps will automatically be rounded down to the start of the day. @see "http://www.flickr.com/services/api/flickr.stats.getPhotostreamStats.htm"
[ "public Stats getPhotostreamStats(Date date) throws FlickrException {\n return getStats(METHOD_GET_PHOTOSTREAM_STATS, null, null, date);\n }" ]
[ "private EditorState getDefaultState() {\n\n List<TableProperty> cols = new ArrayList<TableProperty>(1);\n cols.add(TableProperty.TRANSLATION);\n\n return new EditorState(cols, false);\n }", "public static DoubleMatrix expm(DoubleMatrix A) {\n // constants for pade approximation\n final double c0 = 1.0;\n final double c1 = 0.5;\n final double c2 = 0.12;\n final double c3 = 0.01833333333333333;\n final double c4 = 0.0019927536231884053;\n final double c5 = 1.630434782608695E-4;\n final double c6 = 1.0351966873706E-5;\n final double c7 = 5.175983436853E-7;\n final double c8 = 2.0431513566525E-8;\n final double c9 = 6.306022705717593E-10;\n final double c10 = 1.4837700484041396E-11;\n final double c11 = 2.5291534915979653E-13;\n final double c12 = 2.8101705462199615E-15;\n final double c13 = 1.5440497506703084E-17;\n\n int j = Math.max(0, 1 + (int) Math.floor(Math.log(A.normmax()) / Math.log(2)));\n DoubleMatrix As = A.div((double) Math.pow(2, j)); // scaled version of A\n int n = A.getRows();\n\n // calculate D and N using special Horner techniques\n DoubleMatrix As_2 = As.mmul(As);\n DoubleMatrix As_4 = As_2.mmul(As_2);\n DoubleMatrix As_6 = As_4.mmul(As_2);\n // U = c0*I + c2*A^2 + c4*A^4 + (c6*I + c8*A^2 + c10*A^4 + c12*A^6)*A^6\n DoubleMatrix U = DoubleMatrix.eye(n).muli(c0).addi(As_2.mul(c2)).addi(As_4.mul(c4)).addi(\n DoubleMatrix.eye(n).muli(c6).addi(As_2.mul(c8)).addi(As_4.mul(c10)).addi(As_6.mul(c12)).mmuli(As_6));\n // V = c1*I + c3*A^2 + c5*A^4 + (c7*I + c9*A^2 + c11*A^4 + c13*A^6)*A^6\n DoubleMatrix V = DoubleMatrix.eye(n).muli(c1).addi(As_2.mul(c3)).addi(As_4.mul(c5)).addi(\n DoubleMatrix.eye(n).muli(c7).addi(As_2.mul(c9)).addi(As_4.mul(c11)).addi(As_6.mul(c13)).mmuli(As_6));\n\n DoubleMatrix AV = As.mmuli(V);\n DoubleMatrix N = U.add(AV);\n DoubleMatrix D = U.subi(AV);\n\n // solve DF = N for F\n DoubleMatrix F = Solve.solve(D, N);\n\n // now square j times\n for (int k = 0; k < j; k++) {\n F.mmuli(F);\n }\n\n return F;\n }", "synchronized void reconnectServerProcess(final ManagedServerBootCmdFactory factory) {\n if(this.requiredState != InternalState.SERVER_STARTED) {\n this.bootConfiguration = factory;\n this.requiredState = InternalState.SERVER_STARTED;\n ROOT_LOGGER.reconnectingServer(serverName);\n internalSetState(new ReconnectTask(), InternalState.STOPPED, InternalState.SEND_STDIN);\n }\n }", "public static void addLazyDefinitions(SourceBuilder code) {\n Set<Declaration> defined = new HashSet<>();\n\n // Definitions may lazily declare new names; ensure we add them all\n List<Declaration> declarations =\n code.scope().keysOfType(Declaration.class).stream().sorted().collect(toList());\n while (!defined.containsAll(declarations)) {\n for (Declaration declaration : declarations) {\n if (defined.add(declaration)) {\n code.add(code.scope().get(declaration).definition);\n }\n }\n declarations = code.scope().keysOfType(Declaration.class).stream().sorted().collect(toList());\n }\n }", "public static double getHaltonNumberForGivenBase(long index, int base) {\n\t\tindex += 1;\n\n\t\tdouble x = 0.0;\n\t\tdouble factor = 1.0 / base;\n\t\twhile(index > 0) {\n\t\t\tx += (index % base) * factor;\n\t\t\tfactor /= base;\n\t\t\tindex /= base;\n\t\t}\n\n\t\treturn x;\n\t}", "protected void appendHavingClause(StringBuffer having, Criteria crit, StringBuffer stmt)\r\n {\r\n if (having.length() == 0)\r\n {\r\n having = null;\r\n }\r\n\r\n if (having != null || crit != null)\r\n {\r\n stmt.append(\" HAVING \");\r\n appendClause(having, crit, stmt);\r\n }\r\n }", "@Override\n public List<JobInstance> getJobs(Query query)\n {\n return JqmClientFactory.getClient().getJobs(query);\n }", "public static BoxUser.Info createAppUser(BoxAPIConnection api, String name,\n CreateUserParams params) {\n\n params.setIsPlatformAccessOnly(true);\n return createEnterpriseUser(api, null, name, params);\n }", "public static String getAt(String text, IntRange range) {\n return getAt(text, (Range) range);\n }" ]
Given a list of store definitions, filters the list depending on the boolean @param storeDefs Complete list of store definitions @param isReadOnly Boolean indicating whether filter on read-only or not? @return List of filtered store definition
[ "public static List<StoreDefinition> filterStores(List<StoreDefinition> storeDefs,\n final boolean isReadOnly) {\n List<StoreDefinition> filteredStores = Lists.newArrayList();\n for(StoreDefinition storeDef: storeDefs) {\n if(storeDef.getType().equals(ReadOnlyStorageConfiguration.TYPE_NAME) == isReadOnly) {\n filteredStores.add(storeDef);\n }\n }\n return filteredStores;\n }" ]
[ "public static lbvserver_servicegroup_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_servicegroup_binding obj = new lbvserver_servicegroup_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_servicegroup_binding response[] = (lbvserver_servicegroup_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static <T> List<T> makeList(T... items) {\r\n List<T> s = new ArrayList<T>(items.length);\r\n for (int i = 0; i < items.length; i++) {\r\n s.add(items[i]);\r\n }\r\n return s;\r\n }", "private void addAnnotationValues(ClassReference annotatedReference, AnnotationClassReference typeRef, Annotation node)\n {\n Map<String, AnnotationValue> annotationValueMap = new HashMap<>();\n if (node instanceof SingleMemberAnnotation)\n {\n SingleMemberAnnotation singleMemberAnnotation = (SingleMemberAnnotation) node;\n AnnotationValue value = getAnnotationValueForExpression(annotatedReference, singleMemberAnnotation.getValue());\n annotationValueMap.put(\"value\", value);\n }\n else if (node instanceof NormalAnnotation)\n {\n @SuppressWarnings(\"unchecked\")\n List<MemberValuePair> annotationValues = ((NormalAnnotation) node).values();\n for (MemberValuePair annotationValue : annotationValues)\n {\n String key = annotationValue.getName().toString();\n Expression expression = annotationValue.getValue();\n AnnotationValue value = getAnnotationValueForExpression(annotatedReference, expression);\n annotationValueMap.put(key, value);\n }\n }\n typeRef.setAnnotationValues(annotationValueMap);\n }", "static TarArchiveEntry defaultFileEntryWithName( final String fileName ) {\n TarArchiveEntry entry = new TarArchiveEntry(fileName, true);\n entry.setUserId(ROOT_UID);\n entry.setUserName(ROOT_NAME);\n entry.setGroupId(ROOT_UID);\n entry.setGroupName(ROOT_NAME);\n entry.setMode(TarArchiveEntry.DEFAULT_FILE_MODE);\n return entry;\n }", "@Override\n protected void reset() {\n super.reset();\n mapClassesToNamedBoundProviders.clear();\n mapClassesToUnNamedBoundProviders.clear();\n hasTestModules = false;\n installBindingForScope();\n }", "public JSONObject toJSON() {\n try {\n return new JSONObject(properties).putOpt(\"name\", getName());\n } catch (JSONException e) {\n e.printStackTrace();\n Log.e(TAG, e, \"toJSON()\");\n throw new RuntimeAssertion(\"NodeEntry.toJSON() failed for '%s'\", this);\n }\n }", "public JsonTypeDefinition projectionType(String... properties) {\n if(this.getType() instanceof Map<?, ?>) {\n Map<?, ?> type = (Map<?, ?>) getType();\n Arrays.sort(properties);\n Map<String, Object> newType = new LinkedHashMap<String, Object>();\n for(String prop: properties)\n newType.put(prop, type.get(prop));\n return new JsonTypeDefinition(newType);\n } else {\n throw new IllegalArgumentException(\"Cannot take the projection of a type that is not a Map.\");\n }\n }", "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 static authenticationlocalpolicy_authenticationvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationlocalpolicy_authenticationvserver_binding obj = new authenticationlocalpolicy_authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationlocalpolicy_authenticationvserver_binding response[] = (authenticationlocalpolicy_authenticationvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
Create a FreeMarkerOperation with the provided furnace instance template path, and varNames. The variables in varNames will be provided to the template, and a new ReportModel will be created with these variables attached.
[ "public static FreeMarkerOperation create(Furnace furnace, String templatePath, String outputFilename,\n String... varNames)\n {\n return new FreeMarkerOperation(furnace, templatePath, outputFilename, varNames);\n }" ]
[ "public static void main(String[] args) {\r\n TreebankLanguagePack tlp = new PennTreebankLanguagePack();\r\n System.out.println(\"Start symbol: \" + tlp.startSymbol());\r\n String start = tlp.startSymbol();\r\n System.out.println(\"Should be true: \" + (tlp.isStartSymbol(start)));\r\n String[] strs = {\"-\", \"-LLB-\", \"NP-2\", \"NP=3\", \"NP-LGS\", \"NP-TMP=3\"};\r\n for (String str : strs) {\r\n System.out.println(\"String: \" + str + \" basic: \" + tlp.basicCategory(str) + \" basicAndFunc: \" + tlp.categoryAndFunction(str));\r\n }\r\n }", "private static void listTaskNotes(ProjectFile file)\n {\n for (Task task : file.getTasks())\n {\n String notes = task.getNotes();\n\n if (notes.length() != 0)\n {\n System.out.println(\"Notes for \" + task.getName() + \": \" + notes);\n }\n }\n\n System.out.println();\n }", "public static void registerParams(DynamicJasperDesign jd, Map _parameters) {\n for (Object key : _parameters.keySet()) {\n if (key instanceof String) {\n try {\n Object value = _parameters.get(key);\n if (jd.getParametersMap().get(key) != null) {\n log.warn(\"Parameter \\\"\" + key + \"\\\" already registered, skipping this one: \" + value);\n continue;\n }\n\n JRDesignParameter parameter = new JRDesignParameter();\n\n if (value == null) //There are some Map implementations that allows nulls values, just go on\n continue;\n\n//\t\t\t\t\tparameter.setValueClassName(value.getClass().getCanonicalName());\n Class clazz = value.getClass().getComponentType();\n if (clazz == null)\n clazz = value.getClass();\n parameter.setValueClass(clazz); //NOTE this is very strange\n //when using an array as subreport-data-source, I must pass the parameter class name like this: value.getClass().getComponentType()\n parameter.setName((String) key);\n jd.addParameter(parameter);\n } catch (JRException e) {\n //nothing to do\n }\n }\n\n }\n\n }", "public <T> T with( Closure<T> closure ) {\n return DefaultGroovyMethods.with( null, closure ) ;\n }", "private void handleArchiveByFile(Predicate<String> filter, File archive, List<String> discoveredFiles)\n {\n try\n {\n try (ZipFile zip = new ZipFile(archive))\n {\n Enumeration<? extends ZipEntry> entries = zip.entries();\n \n while (entries.hasMoreElements())\n {\n ZipEntry entry = entries.nextElement();\n String name = entry.getName();\n if (filter.accept(name))\n discoveredFiles.add(name);\n }\n }\n }\n catch (IOException e)\n {\n throw new RuntimeException(\"Error handling file \" + archive, e);\n }\n }", "public List<String> getServiceImplementations(String serviceTypeName) {\n final List<String> strings = services.get(serviceTypeName);\n return strings == null ? Collections.<String>emptyList() : Collections.unmodifiableList(strings);\n }", "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 Path getTransformedXSLTPath(FileModel payload)\n {\n ReportService reportService = new ReportService(getGraphContext());\n Path outputPath = reportService.getReportDirectory();\n outputPath = outputPath.resolve(this.getRelativeTransformedXSLTPath(payload));\n if (!Files.isDirectory(outputPath))\n {\n try\n {\n Files.createDirectories(outputPath);\n }\n catch (IOException e)\n {\n throw new WindupException(\"Failed to create output directory at: \" + outputPath + \" due to: \"\n + e.getMessage(), e);\n }\n }\n return outputPath;\n }", "public EventsRequest<Event> get(String resource, String sync) {\n return new EventsRequest<Event>(this, Event.class, \"/events\", \"GET\")\n .query(\"resource\", resource)\n .query(\"sync\", sync);\n }" ]
Set the end type as derived from other values.
[ "protected final void setDerivedEndType() {\n\n m_endType = getPatternType().equals(PatternType.NONE) || getPatternType().equals(PatternType.INDIVIDUAL)\n ? EndType.SINGLE\n : null != getSeriesEndDate() ? EndType.DATE : EndType.TIMES;\n }" ]
[ "private boolean costRateTableWriteRequired(CostRateTableEntry entry, Date from)\n {\n boolean fromDate = (DateHelper.compare(from, DateHelper.FIRST_DATE) > 0);\n boolean toDate = (DateHelper.compare(entry.getEndDate(), DateHelper.LAST_DATE) > 0);\n boolean costPerUse = (NumberHelper.getDouble(entry.getCostPerUse()) != 0);\n boolean overtimeRate = (entry.getOvertimeRate() != null && entry.getOvertimeRate().getAmount() != 0);\n boolean standardRate = (entry.getStandardRate() != null && entry.getStandardRate().getAmount() != 0);\n return (fromDate || toDate || costPerUse || overtimeRate || standardRate);\n }", "@SuppressWarnings(\"unchecked\")\n public List<Field> getValueAsList() {\n return (List<Field>) type.convert(getValue(), Type.LIST);\n }", "public <T> DiffNode compare(final T working, final T base)\n\t{\n\t\tdispatcher.resetInstanceMemory();\n\t\ttry\n\t\t{\n\t\t\treturn dispatcher.dispatch(DiffNode.ROOT, Instances.of(working, base), RootAccessor.getInstance());\n\t\t}\n\t\tfinally\n\t\t{\n\t\t\tdispatcher.clearInstanceMemory();\n\t\t}\n\t}", "public final void setAttributes(final Map<String, Attribute> attributes) {\n for (Map.Entry<String, Attribute> entry: attributes.entrySet()) {\n Object attribute = entry.getValue();\n if (!(attribute instanceof Attribute)) {\n final String msg =\n \"Attribute: '\" + entry.getKey() + \"' is not an attribute. It is a: \" + attribute;\n LOGGER.error(\"Error setting the Attributes: {}\", msg);\n throw new IllegalArgumentException(msg);\n } else {\n ((Attribute) attribute).setConfigName(entry.getKey());\n }\n }\n this.attributes = attributes;\n }", "private boolean removeRelation(List<Relation> relationList, Task targetTask, RelationType type, Duration lag)\n {\n boolean matchFound = false;\n for (Relation relation : relationList)\n {\n if (relation.getTargetTask() == targetTask)\n {\n if (relation.getType() == type && relation.getLag().compareTo(lag) == 0)\n {\n matchFound = relationList.remove(relation);\n break;\n }\n }\n }\n return matchFound;\n }", "private List<org.jfrog.hudson.pipeline.types.File> getBuildFilesList(Stream<? extends BaseBuildFileBean> buildFilesStream) {\n return buildFilesStream\n .filter(buildFile -> StringUtils.isNotBlank(buildFile.getLocalPath()))\n .filter(buildFile -> StringUtils.isNotBlank(buildFile.getRemotePath()))\n .map(org.jfrog.hudson.pipeline.types.File::new)\n .distinct()\n .collect(Collectors.toList());\n }", "@Pure\n\t@Inline(value = \"$3.union($1, $2)\", imported = MapExtensions.class)\n\tpublic static <K, V> Map<K, V> operator_plus(Map<K, V> left, Map<? extends K, ? extends V> right) {\n\t\treturn union(left, right);\n\t}", "public static lbvserver_auditnslogpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_auditnslogpolicy_binding obj = new lbvserver_auditnslogpolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_auditnslogpolicy_binding response[] = (lbvserver_auditnslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public String calculateCacheKey(String sql, int autoGeneratedKeys) {\r\n\t\tStringBuilder tmp = new StringBuilder(sql.length()+4);\r\n\t\ttmp.append(sql);\r\n\t\ttmp.append(autoGeneratedKeys);\r\n\t\treturn tmp.toString();\r\n\t}" ]
Escapes args' string values according to format @param format the Format used by the PrintStream @param args the array of args to escape @return The cloned and escaped array of args
[ "protected Object[] escape(final Format format, Object... args) {\n // Transformer that escapes HTML,XML,JSON strings\n Transformer<Object, Object> escapingTransformer = new Transformer<Object, Object>() {\n @Override\n public Object transform(Object object) {\n return format.escapeValue(object);\n }\n };\n List<Object> list = Arrays.asList(ArrayUtils.clone(args));\n CollectionUtils.transform(list, escapingTransformer);\n return list.toArray();\n }" ]
[ "public static Trajectory addPositionNoise(Trajectory t, double sd){\n\t\tCentralRandomNumberGenerator r = CentralRandomNumberGenerator.getInstance();\n\t\tTrajectory newt = new Trajectory(t.getDimension());\n\t\t\n\t\tfor(int i = 0; i < t.size(); i++){\n\t\t\tnewt.add(t.get(i));\n\t\t\tfor(int j = 1; j <= t.getDimension(); j++){\n\t\t\t\tswitch (j) {\n\t\t\t\tcase 1:\n\t\t\t\t\tnewt.get(i).setX(newt.get(i).x + r.nextGaussian()*sd);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tnewt.get(i).setY(newt.get(i).y + r.nextGaussian()*sd);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3:\n\t\t\t\t\tnewt.get(i).setZ(newt.get(i).z + r.nextGaussian()*sd);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn newt;\n\t\t\n\t}", "public static final BigDecimal printCurrency(Number value)\n {\n return (value == null || value.doubleValue() == 0 ? null : new BigDecimal(value.doubleValue() * 100));\n }", "public synchronized boolean isComplete(int requestId, boolean remove) {\n if (!operations.containsKey(requestId))\n throw new VoldemortException(\"No operation with id \" + requestId + \" found\");\n\n if (operations.get(requestId).getStatus().isComplete()) {\n if (logger.isDebugEnabled())\n logger.debug(\"Operation complete \" + requestId);\n\n if (remove)\n operations.remove(requestId);\n\n return true;\n }\n\n return false;\n }", "public static lbvserver_auditnslogpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_auditnslogpolicy_binding obj = new lbvserver_auditnslogpolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_auditnslogpolicy_binding response[] = (lbvserver_auditnslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void shutdown() {\n final Connection connection;\n synchronized (this) {\n if(shutdown) return;\n shutdown = true;\n connection = this.connection;\n if(connectTask != null) {\n connectTask.shutdown();\n }\n }\n if (connection != null) {\n connection.closeAsync();\n }\n }", "public static <K,V> Map<K,V> asImmutable(Map<? extends K, ? extends V> self) {\n return Collections.unmodifiableMap(self);\n }", "private void executePlan(RebalancePlan rebalancePlan) {\n logger.info(\"Starting to execute rebalance Plan!\");\n\n int batchCount = 0;\n int partitionStoreCount = 0;\n long totalTimeMs = 0;\n\n List<RebalanceBatchPlan> entirePlan = rebalancePlan.getPlan();\n int numBatches = entirePlan.size();\n int numPartitionStores = rebalancePlan.getPartitionStoresMoved();\n\n for(RebalanceBatchPlan batchPlan: entirePlan) {\n logger.info(\"======== REBALANCING BATCH \" + (batchCount + 1)\n + \" ========\");\n RebalanceUtils.printBatchLog(batchCount,\n logger,\n batchPlan.toString());\n\n long startTimeMs = System.currentTimeMillis();\n // ACTUALLY DO A BATCH OF REBALANCING!\n executeBatch(batchCount, batchPlan);\n totalTimeMs += (System.currentTimeMillis() - startTimeMs);\n\n // Bump up the statistics\n batchCount++;\n partitionStoreCount += batchPlan.getPartitionStoreMoves();\n batchStatusLog(batchCount,\n numBatches,\n partitionStoreCount,\n numPartitionStores,\n totalTimeMs);\n }\n }", "public void loadObject(Object object, Set<String> excludedMethods)\n {\n m_model.setTableModel(createTableModel(object, excludedMethods));\n }", "public static base_response delete(nitro_service client, String jsoncontenttypevalue) throws Exception {\n\t\tappfwjsoncontenttype deleteresource = new appfwjsoncontenttype();\n\t\tdeleteresource.jsoncontenttypevalue = jsoncontenttypevalue;\n\t\treturn deleteresource.delete_resource(client);\n\t}" ]
use this method to construct the ChainingIterator iterator by iterator.
[ "public void addIterator(OJBIterator iterator)\r\n {\r\n /**\r\n * only add iterators that are not null and non-empty.\r\n */\r\n if (iterator != null)\r\n {\r\n if (iterator.hasNext())\r\n {\r\n setNextIterator();\r\n m_rsIterators.add(iterator);\r\n }\r\n }\r\n }" ]
[ "public void flipBit(int index)\n {\n assertValidIndex(index);\n int word = index / WORD_LENGTH;\n int offset = index % WORD_LENGTH;\n data[word] ^= (1 << offset);\n }", "public static String getDefaultJdbcTypeFor(String javaType)\r\n {\r\n return _jdbcMappings.containsKey(javaType) ? (String)_jdbcMappings.get(javaType) : JDBC_DEFAULT_TYPE;\r\n }", "private void increaseBeliefCount(String bName) {\n Object belief = this.getBelief(bName);\n int count = 0;\n if (belief!=null) {\n count = (Integer) belief;\n }\n this.setBelief(bName, count + 1);\n }", "@PreDestroy\n public void disconnectLocator() throws InterruptedException,\n ServiceLocatorException {\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Destroy Locator client\");\n }\n\n if (endpointCollector != null) {\n endpointCollector.stopScheduledCollection();\n }\n \n if (locatorClient != null) {\n locatorClient.disconnect();\n locatorClient = null;\n }\n }", "public static route6[] get(nitro_service service, route6_args args) throws Exception{\n\t\troute6 obj = new route6();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\troute6[] response = (route6[])obj.get_resources(service, option);\n\t\treturn response;\n\t}", "private GregorianCalendar getLastReleventDate(GregorianCalendar currentDate) {\n\t\tint age=this.getProperties().getMaxFileAge();\n\t\tGregorianCalendar result=new GregorianCalendar(currentDate.get(Calendar.YEAR),currentDate.get(Calendar.MONTH),currentDate.get(Calendar.DAY_OF_MONTH));\n\t\tresult.add(Calendar.DAY_OF_MONTH, -age);\n\t\treturn result;\n\t}", "private Duration getAssignmentWork(ProjectCalendar calendar, TimephasedWork assignment)\n {\n Date assignmentStart = assignment.getStart();\n\n Date splitStart = assignmentStart;\n Date splitFinishTime = calendar.getFinishTime(splitStart);\n Date splitFinish = DateHelper.setTime(splitStart, splitFinishTime);\n\n Duration calendarSplitWork = calendar.getWork(splitStart, splitFinish, TimeUnit.MINUTES);\n Duration assignmentWorkPerDay = assignment.getAmountPerDay();\n Duration splitWork;\n\n double splitMinutes = assignmentWorkPerDay.getDuration();\n splitMinutes *= calendarSplitWork.getDuration();\n splitMinutes /= (8 * 60); // this appears to be a fixed value\n splitWork = Duration.getInstance(splitMinutes, TimeUnit.MINUTES);\n return splitWork;\n }", "public static Processor<DataSinkTask> sink(DataSink dataSink, int parallelism, String description, UserConfig taskConf, ActorSystem system) {\n io.gearpump.streaming.Processor<DataSinkTask> p = DataSinkProcessor.apply(dataSink, parallelism, description, taskConf, system);\n return new Processor(p);\n }", "public WebSocketContext sendToUser(String message, String username) {\n return sendToConnections(message, username, manager.usernameRegistry(), true);\n }" ]
Returns true if a pixel with the given color exists @param color the pixel colour to look for. @return true if there exists at least one pixel that has the given pixels color
[ "public boolean contains(Color color) {\n return exists(p -> p.toInt() == color.toPixel().toInt());\n }" ]
[ "public BoundRequestBuilder createRequest()\n throws HttpRequestCreateException {\n BoundRequestBuilder builder = null;\n\n getLogger().debug(\"AHC completeUrl \" + requestUrl);\n\n try {\n\n switch (httpMethod) {\n case GET:\n builder = client.prepareGet(requestUrl);\n break;\n case POST:\n builder = client.preparePost(requestUrl);\n break;\n case PUT:\n builder = client.preparePut(requestUrl);\n break;\n case HEAD:\n builder = client.prepareHead(requestUrl);\n break;\n case OPTIONS:\n builder = client.prepareOptions(requestUrl);\n break;\n case DELETE:\n builder = client.prepareDelete(requestUrl);\n break;\n default:\n break;\n }\n\n PcHttpUtils.addHeaders(builder, this.httpHeaderMap);\n if (!Strings.isNullOrEmpty(postData)) {\n builder.setBody(postData);\n String charset = \"\";\n if (null!=this.httpHeaderMap) {\n charset = this.httpHeaderMap.get(\"charset\");\n }\n if(!Strings.isNullOrEmpty(charset)) {\n builder.setBodyEncoding(charset);\n }\n }\n\n } catch (Exception t) {\n throw new HttpRequestCreateException(\n \"Error in creating request in Httpworker. \"\n + \" If BoundRequestBuilder is null. Then fail to create.\",\n t);\n }\n\n return builder;\n\n }", "@Override\n public String getPartialFilterSelector() {\n return (def.selector != null) ? def.selector.toString() : null;\n }", "public final void reset()\n {\n for (int i = 0; i < combinationIndices.length; i++)\n {\n combinationIndices[i] = i;\n }\n remainingCombinations = totalCombinations;\n }", "public static MBeanParameterInfo[] extractParameterInfo(Method m) {\n Class<?>[] types = m.getParameterTypes();\n Annotation[][] annotations = m.getParameterAnnotations();\n MBeanParameterInfo[] params = new MBeanParameterInfo[types.length];\n for(int i = 0; i < params.length; i++) {\n boolean hasAnnotation = false;\n for(int j = 0; j < annotations[i].length; j++) {\n if(annotations[i][j] instanceof JmxParam) {\n JmxParam param = (JmxParam) annotations[i][j];\n params[i] = new MBeanParameterInfo(param.name(),\n types[i].getName(),\n param.description());\n hasAnnotation = true;\n break;\n }\n }\n if(!hasAnnotation) {\n params[i] = new MBeanParameterInfo(\"\", types[i].getName(), \"\");\n }\n }\n\n return params;\n }", "protected boolean determineFeatureState(final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, boolean defaultState) {\n final IStandardExpressionParser expressionParser = StandardExpressions.getExpressionParser(context.getConfiguration());\n final IStandardExpression expression = expressionParser.parseExpression(context, attributeValue);\n final Object value = expression.execute(context);\n if (value != null) {\n return isFeatureActive(value.toString());\n }\n else {\n return defaultState;\n }\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 static void extractHouseholderColumn( ZMatrixRMaj A ,\n int row0 , int row1 ,\n int col , double u[], int offsetU )\n {\n int indexU = (row0+offsetU)*2;\n u[indexU++] = 1;\n u[indexU++] = 0;\n\n for (int row = row0+1; row < row1; row++) {\n int indexA = A.getIndex(row,col);\n u[indexU++] = A.data[indexA];\n u[indexU++] = A.data[indexA+1];\n }\n }", "public View getFullScreenView() {\n if (mFullScreenView != null) {\n return mFullScreenView;\n }\n\n final DisplayMetrics metrics = new DisplayMetrics();\n mActivity.getWindowManager().getDefaultDisplay().getMetrics(metrics);\n final int screenWidthPixels = Math.max(metrics.widthPixels, metrics.heightPixels);\n final int screenHeightPixels = Math.min(metrics.widthPixels, metrics.heightPixels);\n\n final ViewGroup.LayoutParams layout = new ViewGroup.LayoutParams(screenWidthPixels, screenHeightPixels);\n mFullScreenView = new View(mActivity);\n mFullScreenView.setLayoutParams(layout);\n mRenderableViewGroup.addView(mFullScreenView);\n\n return mFullScreenView;\n }", "public static boolean organizeAssociationMapByRowKey(\n\t\t\torg.hibernate.ogm.model.spi.Association association,\n\t\t\tAssociationKey key,\n\t\t\tAssociationContext associationContext) {\n\n\t\tif ( association.isEmpty() ) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif ( key.getMetadata().getRowKeyIndexColumnNames().length != 1 ) {\n\t\t\treturn false;\n\t\t}\n\n\t\tObject valueOfFirstRow = association.get( association.getKeys().iterator().next() )\n\t\t\t\t.get( key.getMetadata().getRowKeyIndexColumnNames()[0] );\n\n\t\tif ( !( valueOfFirstRow instanceof String ) ) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// The list style may be explicitly enforced for compatibility reasons\n\t\treturn getMapStorage( associationContext ) == MapStorageType.BY_KEY;\n\t}" ]
return request is success by JsonRtn object @param jsonRtn @return
[ "public static boolean isSuccess(JsonRtn jsonRtn) {\n if (jsonRtn == null) {\n return false;\n }\n\n String errCode = jsonRtn.getErrCode();\n if (StringUtils.isEmpty(errCode) || StringUtils.equals(WECHAT_JSON_RTN_SUCCESS_CODE, errCode)) {\n return true;\n }\n\n return false;\n }" ]
[ "private void readAssignment(Resource resource, Assignment assignment)\n {\n Task task = m_activityMap.get(assignment.getActivity());\n if (task != null)\n {\n task.addResourceAssignment(resource);\n }\n }", "static AbstractLazyPatchableTarget createPatchableTarget(final String name, final LayerPathConfig layer, final File metadata, final InstalledImage image) throws IOException {\n // patchable target\n return new AbstractLazyPatchableTarget() {\n\n @Override\n public InstalledImage getInstalledImage() {\n return image;\n }\n\n @Override\n public File getModuleRoot() {\n return layer.modulePath;\n }\n\n @Override\n public File getBundleRepositoryRoot() {\n return layer.bundlePath;\n }\n\n public File getPatchesMetadata() {\n return metadata;\n }\n\n @Override\n public String getName() {\n return name;\n }\n };\n }", "public static DoubleMatrix expm(DoubleMatrix A) {\n // constants for pade approximation\n final double c0 = 1.0;\n final double c1 = 0.5;\n final double c2 = 0.12;\n final double c3 = 0.01833333333333333;\n final double c4 = 0.0019927536231884053;\n final double c5 = 1.630434782608695E-4;\n final double c6 = 1.0351966873706E-5;\n final double c7 = 5.175983436853E-7;\n final double c8 = 2.0431513566525E-8;\n final double c9 = 6.306022705717593E-10;\n final double c10 = 1.4837700484041396E-11;\n final double c11 = 2.5291534915979653E-13;\n final double c12 = 2.8101705462199615E-15;\n final double c13 = 1.5440497506703084E-17;\n\n int j = Math.max(0, 1 + (int) Math.floor(Math.log(A.normmax()) / Math.log(2)));\n DoubleMatrix As = A.div((double) Math.pow(2, j)); // scaled version of A\n int n = A.getRows();\n\n // calculate D and N using special Horner techniques\n DoubleMatrix As_2 = As.mmul(As);\n DoubleMatrix As_4 = As_2.mmul(As_2);\n DoubleMatrix As_6 = As_4.mmul(As_2);\n // U = c0*I + c2*A^2 + c4*A^4 + (c6*I + c8*A^2 + c10*A^4 + c12*A^6)*A^6\n DoubleMatrix U = DoubleMatrix.eye(n).muli(c0).addi(As_2.mul(c2)).addi(As_4.mul(c4)).addi(\n DoubleMatrix.eye(n).muli(c6).addi(As_2.mul(c8)).addi(As_4.mul(c10)).addi(As_6.mul(c12)).mmuli(As_6));\n // V = c1*I + c3*A^2 + c5*A^4 + (c7*I + c9*A^2 + c11*A^4 + c13*A^6)*A^6\n DoubleMatrix V = DoubleMatrix.eye(n).muli(c1).addi(As_2.mul(c3)).addi(As_4.mul(c5)).addi(\n DoubleMatrix.eye(n).muli(c7).addi(As_2.mul(c9)).addi(As_4.mul(c11)).addi(As_6.mul(c13)).mmuli(As_6));\n\n DoubleMatrix AV = As.mmuli(V);\n DoubleMatrix N = U.add(AV);\n DoubleMatrix D = U.subi(AV);\n\n // solve DF = N for F\n DoubleMatrix F = Solve.solve(D, N);\n\n // now square j times\n for (int k = 0; k < j; k++) {\n F.mmuli(F);\n }\n\n return F;\n }", "public Bundler put(String key, CharSequence value) {\n delegate.putCharSequence(key, value);\n return this;\n }", "@Deprecated\n public ApnsServiceBuilder withProxySocket(Socket proxySocket) {\n return this.withProxy(new Proxy(Proxy.Type.SOCKS,\n proxySocket.getRemoteSocketAddress()));\n }", "public static double KullbackLeiblerDivergence(double[] p, double[] q) {\n boolean intersection = false;\n double k = 0;\n\n for (int i = 0; i < p.length; i++) {\n if (p[i] != 0 && q[i] != 0) {\n intersection = true;\n k += p[i] * Math.log(p[i] / q[i]);\n }\n }\n\n if (intersection)\n return k;\n else\n return Double.POSITIVE_INFINITY;\n }", "public static Shell createConsoleShell(String prompt, String appName, Object... handlers) {\n ConsoleIO io = new ConsoleIO();\n\n List<String> path = new ArrayList<String>(1);\n path.add(prompt);\n\n MultiMap<String, Object> modifAuxHandlers = new ArrayHashMultiMap<String, Object>();\n modifAuxHandlers.put(\"!\", io);\n\n Shell theShell = new Shell(new Shell.Settings(io, io, modifAuxHandlers, false),\n new CommandTable(new DashJoinedNamer(true)), path);\n theShell.setAppName(appName);\n\n theShell.addMainHandler(theShell, \"!\");\n theShell.addMainHandler(new HelpCommandHandler(), \"?\");\n for (Object h : handlers) {\n theShell.addMainHandler(h, \"\");\n }\n\n return theShell;\n }", "private static synchronized FileOutputWriter createFileWriter(final TypeDefinition type, final DecompilerSettings settings)\n throws IOException\n {\n final String outputDirectory = settings.getOutputDirectory();\n\n final String fileName = type.getName() + settings.getLanguage().getFileExtension();\n final String packageName = type.getPackageName();\n\n // foo.Bar -> foo/Bar.java\n final String subDir = StringUtils.defaultIfEmpty(packageName, \"\").replace('.', File.separatorChar);\n final String outputPath = PathHelper.combine(outputDirectory, subDir, fileName);\n\n final File outputFile = new File(outputPath);\n final File parentDir = outputFile.getParentFile();\n\n if (parentDir != null && !parentDir.exists() && !parentDir.mkdirs())\n {\n throw new IllegalStateException(\"Could not create directory:\" + parentDir);\n }\n\n if (!outputFile.exists() && !outputFile.createNewFile())\n {\n throw new IllegalStateException(\"Could not create output file: \" + outputPath);\n }\n\n return new FileOutputWriter(outputFile, settings);\n }", "private void writeResources()\n {\n for (Resource resource : m_projectFile.getResources())\n {\n if (resource.getUniqueID().intValue() != 0)\n {\n writeResource(resource);\n }\n }\n }" ]
Generate the specified output file by merging the specified Velocity template with the supplied context.
[ "protected void generateFile(File file,\n String templateName,\n VelocityContext context) throws Exception\n {\n Writer writer = new BufferedWriter(new FileWriter(file));\n try\n {\n Velocity.mergeTemplate(classpathPrefix + templateName,\n ENCODING,\n context,\n writer);\n writer.flush();\n }\n finally\n {\n writer.close();\n }\n }" ]
[ "public static String constructUrl(final HttpServerExchange exchange, final String path) {\n final HeaderMap headers = exchange.getRequestHeaders();\n String host = headers.getFirst(HOST);\n String protocol = exchange.getConnection().getSslSessionInfo() != null ? \"https\" : \"http\";\n\n return protocol + \"://\" + host + path;\n }", "void register(long mjDay, int leapAdjustment) {\n if (leapAdjustment != -1 && leapAdjustment != 1) {\n throw new IllegalArgumentException(\"Leap adjustment must be -1 or 1\");\n }\n Data data = dataRef.get();\n int pos = Arrays.binarySearch(data.dates, mjDay);\n int currentAdj = pos > 0 ? data.offsets[pos] - data.offsets[pos - 1] : 0;\n if (currentAdj == leapAdjustment) {\n return; // matches previous definition\n }\n if (mjDay <= data.dates[data.dates.length - 1]) {\n throw new IllegalArgumentException(\"Date must be after the last configured leap second date\");\n }\n long[] dates = Arrays.copyOf(data.dates, data.dates.length + 1);\n int[] offsets = Arrays.copyOf(data.offsets, data.offsets.length + 1);\n long[] taiSeconds = Arrays.copyOf(data.taiSeconds, data.taiSeconds.length + 1);\n int offset = offsets[offsets.length - 2] + leapAdjustment;\n dates[dates.length - 1] = mjDay;\n offsets[offsets.length - 1] = offset;\n taiSeconds[taiSeconds.length - 1] = tai(mjDay, offset);\n Data newData = new Data(dates, offsets, taiSeconds);\n if (dataRef.compareAndSet(data, newData) == false) {\n throw new ConcurrentModificationException(\"Unable to update leap second rules as they have already been updated\");\n }\n }", "protected void\t\tcalcLocal(Bone bone, int parentId)\n {\n if (parentId < 0)\n {\n bone.LocalMatrix.set(bone.WorldMatrix);\n return;\n }\n\t/*\n\t * WorldMatrix = WorldMatrix(parent) * LocalMatrix\n\t * LocalMatrix = INVERSE[ WorldMatrix(parent) ] * WorldMatrix\n\t */\n getWorldMatrix(parentId, mTempMtxA);\t// WorldMatrix(par)\n mTempMtxA.invert();\t\t\t\t\t // INVERSE[ WorldMatrix(parent) ]\n mTempMtxA.mul(bone.WorldMatrix, bone.LocalMatrix); // LocalMatrix = INVERSE[ WorldMatrix(parent) ] * WorldMatrix\n }", "void close() {\n try {\n performTeardownExchange();\n } catch (IOException e) {\n logger.warn(\"Problem reporting our intention to close the dbserver connection\", e);\n }\n try {\n channel.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing dbserver client output channel\", e);\n }\n try {\n os.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing dbserver client output stream\", e);\n }\n try {\n is.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing dbserver client input stream\", e);\n }\n try {\n socket.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing dbserver client socket\", e);\n }\n }", "public static String readTextFile(File file) {\n try {\n return readTextFile(new FileReader(file));\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n return null;\n }\n }", "public static float calculateMaxTextHeight(Paint _Paint, String _Text) {\n Rect height = new Rect();\n String text = _Text == null ? \"MgHITasger\" : _Text;\n _Paint.getTextBounds(text, 0, text.length(), height);\n return height.height();\n }", "public Set<RGBColor> colours() {\n return stream().map(Pixel::toColor).collect(Collectors.toSet());\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public Stream<ChangeEvent<DocumentT>> watch(final BsonValue... ids)\n throws InterruptedException, IOException {\n return operations.watch(\n new HashSet<>(Arrays.asList(ids)),\n false,\n documentClass\n ).execute(service);\n }", "private synchronized void freeClient(Client client) {\n int current = useCounts.get(client);\n if (current > 0) {\n timestamps.put(client, System.currentTimeMillis()); // Mark that it was used until now.\n useCounts.put(client, current - 1);\n if ((current == 1) && (idleLimit.get() == 0)) {\n closeClient(client); // This was the last use, and we are supposed to immediately close idle clients.\n }\n } else {\n logger.error(\"Ignoring attempt to free a client that is not allocated: {}\", client);\n }\n }" ]
Map custom info. @param ciType the custom info type @return the map
[ "private static Map<String, String> mapCustomInfo(CustomInfoType ciType){\n Map<String, String> customInfo = new HashMap<String, String>();\n if (ciType != null){\n for (CustomInfoType.Item item : ciType.getItem()) {\n customInfo.put(item.getKey(), item.getValue());\n }\n }\n return customInfo;\n }" ]
[ "public static String marshal(Object object) {\n if (object == null) {\n return null;\n }\n\n try {\n JAXBContext jaxbCtx = JAXBContext.newInstance(object.getClass());\n\n Marshaller marshaller = jaxbCtx.createMarshaller();\n marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);\n\n StringWriter sw = new StringWriter();\n marshaller.marshal(object, sw);\n\n return sw.toString();\n } catch (Exception e) {\n }\n\n return null;\n }", "public AT_Row setHtmlElementTranslator(HtmlElementTranslator htmlElementTranslator) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setHtmlElementTranslator(htmlElementTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "@SuppressWarnings(\"unchecked\")\n private static Object resolveConflictWithResolver(\n final ConflictHandler conflictResolver,\n final BsonValue documentId,\n final ChangeEvent localEvent,\n final ChangeEvent remoteEvent\n ) {\n return conflictResolver.resolveConflict(\n documentId,\n localEvent,\n remoteEvent);\n }", "public static DoubleMatrix cholesky(DoubleMatrix A) {\n DoubleMatrix result = A.dup();\n int info = NativeBlas.dpotrf('U', A.rows, result.data, 0, A.rows);\n if (info < 0) {\n throw new LapackArgumentException(\"DPOTRF\", -info);\n } else if (info > 0) {\n throw new LapackPositivityException(\"DPOTRF\", \"Minor \" + info + \" was negative. Matrix must be positive definite.\");\n }\n clearLower(result);\n return result;\n }", "public static RouteInfo of(ActionContext context) {\n H.Method m = context.req().method();\n String path = context.req().url();\n RequestHandler handler = context.handler();\n if (null == handler) {\n handler = UNKNOWN_HANDLER;\n }\n return new RouteInfo(m, path, handler);\n }", "private boolean verify(String key, BoxSignatureAlgorithm actualAlgorithm, String actualSignature,\n String webHookPayload, String deliveryTimestamp) {\n if (actualSignature == null) {\n return false;\n }\n\n byte[] actual = Base64.decode(actualSignature);\n byte[] expected = this.signRaw(actualAlgorithm, key, webHookPayload, deliveryTimestamp);\n\n return Arrays.equals(expected, actual);\n }", "protected AbstractBeanDeployer<E> deploySpecialized() {\n // ensure that all decorators are initialized before initializing\n // the rest of the beans\n for (DecoratorImpl<?> bean : getEnvironment().getDecorators()) {\n bean.initialize(getEnvironment());\n containerLifecycleEvents.fireProcessBean(getManager(), bean);\n manager.addDecorator(bean);\n BootstrapLogger.LOG.foundDecorator(bean);\n }\n for (InterceptorImpl<?> bean : getEnvironment().getInterceptors()) {\n bean.initialize(getEnvironment());\n containerLifecycleEvents.fireProcessBean(getManager(), bean);\n manager.addInterceptor(bean);\n BootstrapLogger.LOG.foundInterceptor(bean);\n }\n return this;\n }", "private boolean operations(Options opt, ConstructorDoc m[]) {\n\tboolean printed = false;\n\tfor (ConstructorDoc cd : m) {\n\t if (hidden(cd))\n\t\tcontinue;\n\t stereotype(opt, cd, Align.LEFT);\n\t String cs = visibility(opt, cd) + cd.name() //\n\t\t + (opt.showType ? \"(\" + parameter(opt, cd.parameters()) + \")\" : \"()\");\n\t tableLine(Align.LEFT, cs);\n\t tagvalue(opt, cd);\n\t printed = true;\n\t}\n\treturn printed;\n }", "public static nslimitidentifier_binding get(nitro_service service, String limitidentifier) throws Exception{\n\t\tnslimitidentifier_binding obj = new nslimitidentifier_binding();\n\t\tobj.set_limitidentifier(limitidentifier);\n\t\tnslimitidentifier_binding response = (nslimitidentifier_binding) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
Unlock all edited resources.
[ "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 Type[] getActualTypeArguments(Type type) {\n Type resolvedType = Types.getCanonicalType(type);\n if (resolvedType instanceof ParameterizedType) {\n return ((ParameterizedType) resolvedType).getActualTypeArguments();\n } else {\n return EMPTY_TYPES;\n }\n }", "private static String getPath(Service service, Annotation... qualifiers) {\n for (Annotation q : qualifiers) {\n if (q instanceof Scheme) {\n return ((Scheme) q).value();\n }\n }\n\n if (service.getMetadata() != null && service.getMetadata().getAnnotations() != null) {\n String s = service.getMetadata().getAnnotations().get(SERVICE_SCHEME);\n if (s != null && s.isEmpty()) {\n return s;\n }\n }\n return DEFAULT_PATH;\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 int[] sampleBatchWithReplacement() {\n // Sample the indices with replacement.\n int[] batch = new int[batchSize];\n for (int i=0; i<batch.length; i++) {\n batch[i] = Prng.nextInt(numExamples);\n }\n return batch;\n }", "private void readResourceExtendedAttributes(Project.Resources.Resource xml, Resource mpx)\n {\n for (Project.Resources.Resource.ExtendedAttribute attrib : xml.getExtendedAttribute())\n {\n int xmlFieldID = Integer.parseInt(attrib.getFieldID()) & 0x0000FFFF;\n ResourceField mpxFieldID = MPPResourceField.getInstance(xmlFieldID);\n TimeUnit durationFormat = DatatypeConverter.parseDurationTimeUnits(attrib.getDurationFormat(), null);\n DatatypeConverter.parseExtendedAttribute(m_projectFile, mpx, attrib.getValue(), mpxFieldID, durationFormat);\n }\n }", "private String dumpZoneNAryDetails(StoreRoutingPlan storeRoutingPlan) {\n StringBuilder sb = new StringBuilder();\n\n sb.append(\"\\tDetailed Dump (Zone N-Aries):\").append(Utils.NEWLINE);\n for(Node node: storeRoutingPlan.getCluster().getNodes()) {\n int zoneId = node.getZoneId();\n int nodeId = node.getId();\n sb.append(\"\\tNode ID: \" + nodeId + \" in zone \" + zoneId).append(Utils.NEWLINE);\n List<Integer> naries = storeRoutingPlan.getZoneNAryPartitionIds(nodeId);\n Map<Integer, List<Integer>> zoneNaryTypeToPartitionIds = new HashMap<Integer, List<Integer>>();\n for(int nary: naries) {\n int zoneReplicaType = storeRoutingPlan.getZoneNaryForNodesPartition(zoneId,\n nodeId,\n nary);\n if(!zoneNaryTypeToPartitionIds.containsKey(zoneReplicaType)) {\n zoneNaryTypeToPartitionIds.put(zoneReplicaType, new ArrayList<Integer>());\n }\n zoneNaryTypeToPartitionIds.get(zoneReplicaType).add(nary);\n }\n\n for(int replicaType: new TreeSet<Integer>(zoneNaryTypeToPartitionIds.keySet())) {\n sb.append(\"\\t\\t\" + replicaType + \" : \");\n sb.append(zoneNaryTypeToPartitionIds.get(replicaType).toString());\n sb.append(Utils.NEWLINE);\n }\n }\n\n return sb.toString();\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 void handleSerialApiGetInitDataResponse(\n\t\t\tSerialMessage incomingMessage) {\n\t\tlogger.debug(String.format(\"Got MessageSerialApiGetInitData response.\"));\n\t\tthis.isConnected = true;\n\t\tint nodeBytes = incomingMessage.getMessagePayloadByte(2);\n\t\t\n\t\tif (nodeBytes != NODE_BYTES) {\n\t\t\tlogger.error(\"Invalid number of node bytes = {}\", nodeBytes);\n\t\t\treturn;\n\t\t}\n\n\t\tint nodeId = 1;\n\t\t\n\t\t// loop bytes\n\t\tfor (int i = 3;i < 3 + nodeBytes;i++) {\n\t\t\tint incomingByte = incomingMessage.getMessagePayloadByte(i);\n\t\t\t// loop bits in byte\n\t\t\tfor (int j=0;j<8;j++) {\n\t\t\t\tint b1 = incomingByte & (int)Math.pow(2.0D, j);\n\t\t\t\tint b2 = (int)Math.pow(2.0D, j);\n\t\t\t\tif (b1 == b2) {\n\t\t\t\t\tlogger.info(String.format(\"Found node id = %d\", nodeId));\n\t\t\t\t\t// Place nodes in the local ZWave Controller \n\t\t\t\t\tthis.zwaveNodes.put(nodeId, new ZWaveNode(this.homeId, nodeId, this));\n\t\t\t\t\tthis.getNode(nodeId).advanceNodeStage();\n\t\t\t\t}\n\t\t\t\tnodeId++;\n\t\t\t}\n\t\t}\n\t\t\n\t\tlogger.info(\"------------Number of Nodes Found Registered to ZWave Controller------------\");\n\t\tlogger.info(String.format(\"# Nodes = %d\", this.zwaveNodes.size()));\n\t\tlogger.info(\"----------------------------------------------------------------------------\");\n\t\t\n\t\t// Advance node stage for the first node.\n\t}", "public void removePrefetchingListeners()\r\n {\r\n if (prefetchingListeners != null)\r\n {\r\n for (Iterator it = prefetchingListeners.iterator(); it.hasNext(); )\r\n {\r\n PBPrefetchingListener listener = (PBPrefetchingListener) it.next();\r\n listener.removeThisListener();\r\n }\r\n prefetchingListeners.clear();\r\n }\r\n }" ]
Isn't there a method for this in GeoTools? @param crs CRS string in the form of 'EPSG:<srid>'. @return SRID as integer.
[ "public int getSridFromCrs(String crs) {\n\t\tint crsInt;\n\t\tif (crs.indexOf(':') != -1) {\n\t\t\tcrsInt = Integer.parseInt(crs.substring(crs.indexOf(':') + 1));\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tcrsInt = Integer.parseInt(crs);\n\t\t\t} catch (NumberFormatException e) {\n\t\t\t\tcrsInt = 0;\n\t\t\t}\n\t\t}\n\t\treturn crsInt;\n\t}" ]
[ "public RuntimeParameter addParameter(String key, String value)\n {\n RuntimeParameter jp = new RuntimeParameter();\n jp.setJi(this.getId());\n jp.setKey(key);\n jp.setValue(value);\n return jp;\n }", "public void abort() {\n URL abortURL = this.sessionInfo.getSessionEndpoints().getAbortEndpoint();\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), abortURL, HttpMethod.DELETE);\n request.send();\n }", "public static List<String> splitAsList(String text, String delimiter) {\n List<String> answer = new ArrayList<String>();\n if (text != null && text.length() > 0) {\n answer.addAll(Arrays.asList(text.split(delimiter)));\n }\n return answer;\n }", "private List<SynchroTable> readTableHeaders(InputStream is) throws IOException\n {\n // Read the headers\n List<SynchroTable> tables = new ArrayList<SynchroTable>();\n byte[] header = new byte[48];\n while (true)\n {\n is.read(header);\n m_offset += 48;\n SynchroTable table = readTableHeader(header);\n if (table == null)\n {\n break;\n }\n tables.add(table);\n }\n\n // Ensure sorted by offset\n Collections.sort(tables, new Comparator<SynchroTable>()\n {\n @Override public int compare(SynchroTable o1, SynchroTable o2)\n {\n return o1.getOffset() - o2.getOffset();\n }\n });\n\n // Calculate lengths\n SynchroTable previousTable = null;\n for (SynchroTable table : tables)\n {\n if (previousTable != null)\n {\n previousTable.setLength(table.getOffset() - previousTable.getOffset());\n }\n\n previousTable = table;\n }\n\n for (SynchroTable table : tables)\n {\n SynchroLogger.log(\"TABLE\", table);\n }\n\n return tables;\n }", "public IndexDef getIndex(String name)\r\n {\r\n String realName = (name == null ? \"\" : name);\r\n IndexDef def = null;\r\n\r\n for (Iterator it = getIndices(); it.hasNext();)\r\n {\r\n def = (IndexDef)it.next();\r\n if (def.getName().equals(realName))\r\n {\r\n return def;\r\n }\r\n }\r\n return null;\r\n }", "@PrefMetadata(type = CmsHiddenBuiltinPreference.class)\n public String getExplorerFileEntryOptions() {\n\n if (m_settings.getExplorerFileEntryOptions() == null) {\n return \"\";\n } else {\n return \"\" + m_settings.getExplorerFileEntryOptions();\n }\n }", "void createDirectory(Path path) throws IOException {\n\t\tif (Files.exists(path) && Files.isDirectory(path)) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.readOnly) {\n\t\t\tthrow new FileNotFoundException(\n\t\t\t\t\t\"The requested directory \\\"\"\n\t\t\t\t\t\t\t+ path.toString()\n\t\t\t\t\t\t\t+ \"\\\" does not exist and we are in read-only mode, so it cannot be created.\");\n\t\t}\n\n\t\tFiles.createDirectory(path);\n\t}", "private static void parseOutgoings(ArrayList<Shape> shapes,\n JSONObject modelJSON,\n Shape current) throws JSONException {\n if (modelJSON.has(\"outgoing\")) {\n ArrayList<Shape> outgoings = new ArrayList<Shape>();\n JSONArray outgoingObject = modelJSON.getJSONArray(\"outgoing\");\n for (int i = 0; i < outgoingObject.length(); i++) {\n Shape out = getShapeWithId(outgoingObject.getJSONObject(i).getString(\"resourceId\"),\n shapes);\n outgoings.add(out);\n out.addIncoming(current);\n }\n if (outgoings.size() > 0) {\n current.setOutgoings(outgoings);\n }\n }\n }", "public static base_responses update(nitro_service client, gslbsite resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tgslbsite updateresources[] = new gslbsite[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new gslbsite();\n\t\t\t\tupdateresources[i].sitename = resources[i].sitename;\n\t\t\t\tupdateresources[i].metricexchange = resources[i].metricexchange;\n\t\t\t\tupdateresources[i].nwmetricexchange = resources[i].nwmetricexchange;\n\t\t\t\tupdateresources[i].sessionexchange = resources[i].sessionexchange;\n\t\t\t\tupdateresources[i].triggermonitor = resources[i].triggermonitor;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}" ]
Returns information for a specific path id @param pathId ID of path @param clientUUID client UUID @param filters filters to set on endpoint @return EndpointOverride @throws Exception exception
[ "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 }" ]
[ "protected void generateFile(File file,\n String templateName,\n VelocityContext context) throws Exception\n {\n Writer writer = new BufferedWriter(new FileWriter(file));\n try\n {\n Velocity.mergeTemplate(classpathPrefix + templateName,\n ENCODING,\n context,\n writer);\n writer.flush();\n }\n finally\n {\n writer.close();\n }\n }", "public Scale getNearestScale(\n final ZoomLevels zoomLevels,\n final double tolerance,\n final ZoomLevelSnapStrategy zoomLevelSnapStrategy,\n final boolean geodetic,\n final Rectangle paintArea,\n final double dpi) {\n\n final Scale scale = getScale(paintArea, dpi);\n final Scale correctedScale;\n final double scaleRatio;\n if (geodetic) {\n final double currentScaleDenominator = scale.getGeodeticDenominator(\n getProjection(), dpi, getCenter());\n scaleRatio = scale.getDenominator(dpi) / currentScaleDenominator;\n correctedScale = scale.toResolution(scale.getResolution() / scaleRatio);\n } else {\n scaleRatio = 1;\n correctedScale = scale;\n }\n\n DistanceUnit unit = DistanceUnit.fromProjection(getProjection());\n final ZoomLevelSnapStrategy.SearchResult result = zoomLevelSnapStrategy.search(\n correctedScale, tolerance, zoomLevels);\n final Scale newScale;\n\n if (geodetic) {\n newScale = new Scale(\n result.getScale(unit).getDenominator(PDF_DPI) * scaleRatio,\n getProjection(), dpi);\n } else {\n newScale = result.getScale(unit);\n }\n\n return newScale;\n }", "public static void start(final GVRContext context, final String appId, final ResultListener listener) {\n if (null == listener) {\n throw new IllegalArgumentException(\"listener cannot be null\");\n }\n\n final Activity activity = context.getActivity();\n final long result = create(activity, appId);\n if (0 != result) {\n throw new IllegalStateException(\"Could not initialize the platform sdk; error code: \" + result);\n }\n\n context.registerDrawFrameListener(new GVRDrawFrameListener() {\n @Override\n public void onDrawFrame(float frameTime) {\n final int result = processEntitlementCheckResponse();\n if (0 != result) {\n context.unregisterDrawFrameListener(this);\n\n final Runnable runnable;\n if (-1 == result) {\n runnable = new Runnable() {\n @Override\n public void run() {\n listener.onFailure();\n }\n };\n } else {\n runnable = new Runnable() {\n @Override\n public void run() {\n listener.onSuccess();\n }\n };\n }\n activity.runOnUiThread(runnable);\n }\n }\n });\n }", "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 F resolve(R resolvable, boolean cache) {\n R wrappedResolvable = wrap(resolvable);\n if (cache) {\n return resolved.getValue(wrappedResolvable);\n } else {\n return resolverFunction.apply(wrappedResolvable);\n }\n }", "public String get() {\n\t\tsynchronized (LOCK) {\n\t\t\tif (!initialised) {\n\t\t\t\t// generate the random number\n\t\t\t\tRandom rnd = new Random();\t// @todo need a different seed, this is now time based and I\n\t\t\t\t// would prefer something different, like an object address\n\t\t\t\t// get the random number, instead of getting an integer and converting that to base64 later,\n\t\t\t\t// we get a string and narrow that down to base64, use the top 6 bits of the characters\n\t\t\t\t// as they are more random than the bottom ones...\n\t\t\t\trnd.nextBytes(value);\t\t// get some random characters\n\t\t\t\tvalue[3] = BASE64[((value[3] >> 2) & BITS_6)]; // NOSONAR\n\t\t\t\tvalue[4] = BASE64[((value[4] >> 2) & BITS_6)]; // NOSONAR\n\t\t\t\tvalue[5] = BASE64[((value[5] >> 2) & BITS_6)]; // NOSONAR\n\t\t\t\tvalue[6] = BASE64[((value[6] >> 2) & BITS_6)]; // NOSONAR\n\t\t\t\tvalue[7] = BASE64[((value[7] >> 2) & BITS_6)]; // NOSONAR\n\n\t\t\t\t// complete the time part in the HIGH value of the token\n\t\t\t\t// this also sets the initial low value\n\t\t\t\tcompleteToken(rnd);\n\n\t\t\t\tinitialised = true;\n\t\t\t}\n\n\t\t\t// fill in LOW value in id\n\t\t\tint l = low;\n\t\t\tvalue[0] = BASE64[(l & BITS_6)];\n\t\t\tl >>= SHIFT_6;\n\t\t\tvalue[1] = BASE64[(l & BITS_6)];\n\t\t\tl >>= SHIFT_6;\n\t\t\tvalue[2] = BASE64[(l & BITS_6)];\n\n\t\t\tString res = new String(value);\n\n\t\t\t// increment LOW\n\t\t\tlow++;\n\t\t\tif (low == LOW_MAX) {\n\t\t\t\tlow = 0;\n\t\t\t}\n\t\t\tif (low == lowLast) {\n\t\t\t\ttime = System.currentTimeMillis();\n\t\t\t\tcompleteToken();\n\t\t\t}\n\n\t\t\treturn res;\n\t\t}\n\t}", "public DynamicReportBuilder setQuery(String text, String language) {\n this.report.setQuery(new DJQuery(text, language));\n return this;\n }", "public Snackbar actionLabel(CharSequence actionButtonLabel) {\n mActionLabel = actionButtonLabel;\n if (snackbarAction != null) {\n snackbarAction.setText(mActionLabel);\n }\n return this;\n }", "public final PJsonObject getJSONObject(final int i) {\n JSONObject val = this.array.optJSONObject(i);\n final String context = \"[\" + i + \"]\";\n if (val == null) {\n throw new ObjectMissingException(this, context);\n }\n return new PJsonObject(this, val, context);\n }" ]
Creates a new deployment for the path. If the path is a directory the content will be deployed exploded using the file system location. @param content the path containing the content @return the deployment
[ "public static Deployment of(final Path content) {\n final DeploymentContent deploymentContent = DeploymentContent.of(Assert.checkNotNullParam(\"content\", content));\n return new Deployment(deploymentContent, null);\n }" ]
[ "public History[] refreshHistory(int limit, int offset) throws Exception {\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"limit\", String.valueOf(limit)),\n new BasicNameValuePair(\"offset\", String.valueOf(offset))\n };\n return constructHistory(params);\n }", "public String text() {\n String previousText = null;\n StringBuilder buffer = null;\n for (Object child : this) {\n String text = null;\n if (child instanceof String) {\n text = (String) child;\n } else if (child instanceof Node) {\n text = ((Node) child).text();\n }\n if (text != null) {\n if (previousText == null) {\n previousText = text;\n } else {\n if (buffer == null) {\n buffer = new StringBuilder();\n buffer.append(previousText);\n }\n buffer.append(text);\n }\n }\n }\n if (buffer != null) {\n return buffer.toString();\n }\n if (previousText != null) {\n return previousText;\n }\n return \"\";\n }", "public Set<String> getConfiguredWorkplaceBundles() {\n\n CmsADEConfigData configData = internalLookupConfiguration(null, null);\n return configData.getConfiguredWorkplaceBundles();\n }", "public static base_response update(nitro_service client, dbdbprofile resource) throws Exception {\n\t\tdbdbprofile updateresource = new dbdbprofile();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.interpretquery = resource.interpretquery;\n\t\tupdateresource.stickiness = resource.stickiness;\n\t\tupdateresource.kcdaccount = resource.kcdaccount;\n\t\tupdateresource.conmultiplex = resource.conmultiplex;\n\t\treturn updateresource.update_resource(client);\n\t}", "protected OJBIterator getIteratorFromQuery(Query query, ClassDescriptor cld) throws PersistenceBrokerException\n {\n RsIteratorFactory factory = RsIteratorFactoryImpl.getInstance();\n OJBIterator result = getRsIteratorFromQuery(query, cld, factory);\n\n if (query.usePaging())\n {\n result = new PagingIterator(result, query.getStartAtIndex(), query.getEndAtIndex());\n }\n return result;\n }", "public Map<String, MBeanOperationInfo> getOperationMetadata() {\n\n MBeanOperationInfo[] operations = mBeanInfo.getOperations();\n\n Map<String, MBeanOperationInfo> operationMap = new TreeMap<String, MBeanOperationInfo>();\n for (MBeanOperationInfo operation: operations) {\n operationMap.put(operation.getName(), operation);\n }\n return operationMap;\n }", "public static void updatePathTable(String columnName, Object newData, int path_id) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + columnName + \" = ?\" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setObject(1, newData);\n statement.setInt(2, path_id);\n statement.executeUpdate();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "public FieldType getFieldTypeFromVarDataKey(Integer key)\n {\n FieldType result = null;\n for (Entry<FieldType, FieldMap.FieldItem> entry : m_map.entrySet())\n {\n if (entry.getValue().getFieldLocation() == FieldLocation.VAR_DATA && entry.getValue().getVarDataKey().equals(key))\n {\n result = entry.getKey();\n break;\n }\n }\n return result;\n }", "public static byte[] getDocumentToByteArray(Document dom) {\n try {\n TransformerFactory tFactory = TransformerFactory.newInstance();\n\n Transformer transformer = tFactory.newTransformer();\n transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n transformer\n .setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, \"no\");\n transformer.setOutputProperty(OutputKeys.METHOD, \"html\");\n // TODO should be fixed to read doctype declaration\n transformer\n .setOutputProperty(\n OutputKeys.DOCTYPE_PUBLIC,\n \"-//W3C//DTD XHTML 1.0 Strict//EN\\\" \"\n + \"\\\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\");\n\n DOMSource source = new DOMSource(dom);\n\n ByteArrayOutputStream out = new ByteArrayOutputStream();\n Result result = new StreamResult(out);\n transformer.transform(source, result);\n\n return out.toByteArray();\n } catch (TransformerException e) {\n LOGGER.error(\"Error while converting the document to a byte array\",\n e);\n }\n return null;\n\n }" ]
Get transformer to use. @return transformation to apply
[ "private GeometryCoordinateSequenceTransformer getTransformer() {\n\t\tif (unitToPixel == null) {\n\t\t\tunitToPixel = new GeometryCoordinateSequenceTransformer();\n\t\t\tunitToPixel.setMathTransform(ProjectiveTransform.create(new AffineTransform(scale, 0, 0, -scale, -scale\n\t\t\t\t\t* panOrigin.x, scale * panOrigin.y)));\n\t\t}\n\t\treturn unitToPixel;\n\t}" ]
[ "public CmsContextMenu getContextMenuForItem(Object itemId) {\n\n CmsContextMenu result = null;\n try {\n final Item item = m_container.getItem(itemId);\n Property<?> keyProp = item.getItemProperty(TableProperty.KEY);\n String key = (String)keyProp.getValue();\n if ((null != key) && !key.isEmpty()) {\n loadAllRemainingLocalizations();\n final Map<Locale, String> localesWithEntries = new HashMap<Locale, String>();\n for (Locale l : m_localizations.keySet()) {\n if (l != m_locale) {\n String value = m_localizations.get(l).getProperty(key);\n if ((null != value) && !value.isEmpty()) {\n localesWithEntries.put(l, value);\n }\n }\n }\n if (!localesWithEntries.isEmpty()) {\n result = new CmsContextMenu();\n ContextMenuItem mainItem = result.addItem(\n Messages.get().getBundle(UI.getCurrent().getLocale()).key(\n Messages.GUI_BUNDLE_EDITOR_CONTEXT_COPY_LOCALE_0));\n for (final Locale l : localesWithEntries.keySet()) {\n\n ContextMenuItem menuItem = mainItem.addItem(l.getDisplayName(UI.getCurrent().getLocale()));\n menuItem.addItemClickListener(new ContextMenuItemClickListener() {\n\n public void contextMenuItemClicked(ContextMenuItemClickEvent event) {\n\n item.getItemProperty(TableProperty.TRANSLATION).setValue(localesWithEntries.get(l));\n\n }\n });\n }\n }\n }\n } catch (Exception e) {\n LOG.error(e.getLocalizedMessage(), e);\n //TODO: Improve\n }\n return result;\n }", "public static String getParentIdFromAgent(Launcher launcher, final String imageID, final String host) throws IOException, InterruptedException {\n return launcher.getChannel().call(new MasterToSlaveCallable<String, IOException>() {\n public String call() throws IOException {\n return DockerUtils.getParentId(imageID, host);\n }\n });\n }", "public static boolean containsUid(IdRange[] idRanges, long uid) {\r\n if (null != idRanges && idRanges.length > 0) {\r\n for (IdRange range : idRanges) {\r\n if (range.includes(uid)) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n }", "private boolean isSpecial(final char chr) {\n\t\treturn ((chr == '.') || (chr == '?') || (chr == '*') || (chr == '^') || (chr == '$') || (chr == '+')\n\t\t\t\t|| (chr == '[') || (chr == ']') || (chr == '(') || (chr == ')') || (chr == '|') || (chr == '\\\\')\n\t\t\t\t|| (chr == '&'));\n\t}", "@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 handleChange(Object propertyId) {\n\n if (!m_saveBtn.isEnabled()) {\n m_saveBtn.setEnabled(true);\n m_saveExitBtn.setEnabled(true);\n }\n m_model.handleChange(propertyId);\n\n }", "public static Map<String, List<String>> getResponseHeaders(String stringUrl) throws IOException {\n return getResponseHeaders(stringUrl, true);\n }", "public ItemRequest<CustomField> update(String customField) {\n \n String path = String.format(\"/custom_fields/%s\", customField);\n return new ItemRequest<CustomField>(this, CustomField.class, path, \"PUT\");\n }", "private void writePropertyData() {\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(\"properties.csv\"))) {\n\n\t\t\tout.println(\"Id\" + \",Label\" + \",Description\" + \",URL\" + \",Datatype\"\n\t\t\t\t\t+ \",Uses in statements\" + \",Items with such statements\"\n\t\t\t\t\t+ \",Uses in statements with qualifiers\"\n\t\t\t\t\t+ \",Uses in qualifiers\" + \",Uses in references\"\n\t\t\t\t\t+ \",Uses total\" + \",Related properties\");\n\n\t\t\tList<Entry<PropertyIdValue, PropertyRecord>> list = new ArrayList<Entry<PropertyIdValue, PropertyRecord>>(\n\t\t\t\t\tthis.propertyRecords.entrySet());\n\t\t\tCollections.sort(list, new UsageRecordComparator());\n\t\t\tfor (Entry<PropertyIdValue, PropertyRecord> entry : list) {\n\t\t\t\tprintPropertyRecord(out, entry.getValue(), entry.getKey());\n\t\t\t}\n\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}" ]
Use this API to fetch snmpalarm resource of given name .
[ "public static snmpalarm get(nitro_service service, String trapname) throws Exception{\n\t\tsnmpalarm obj = new snmpalarm();\n\t\tobj.set_trapname(trapname);\n\t\tsnmpalarm response = (snmpalarm) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
[ "static GVRCollider lookup(long nativePointer)\n {\n synchronized (sColliders)\n {\n WeakReference<GVRCollider> weakReference = sColliders.get(nativePointer);\n return weakReference == null ? null : weakReference.get();\n }\n }", "public static void writeShort(byte[] bytes, short value, int offset) {\n bytes[offset] = (byte) (0xFF & (value >> 8));\n bytes[offset + 1] = (byte) (0xFF & value);\n }", "public void revisitThrowEvents(Definitions def) {\n List<RootElement> rootElements = def.getRootElements();\n List<Signal> toAddSignals = new ArrayList<Signal>();\n Set<Error> toAddErrors = new HashSet<Error>();\n Set<Escalation> toAddEscalations = new HashSet<Escalation>();\n Set<Message> toAddMessages = new HashSet<Message>();\n Set<ItemDefinition> toAddItemDefinitions = new HashSet<ItemDefinition>();\n for (RootElement root : rootElements) {\n if (root instanceof Process) {\n setThrowEventsInfo((Process) root,\n def,\n rootElements,\n toAddSignals,\n toAddErrors,\n toAddEscalations,\n toAddMessages,\n toAddItemDefinitions);\n }\n }\n for (Lane lane : _lanes) {\n setThrowEventsInfoForLanes(lane,\n def,\n rootElements,\n toAddSignals,\n toAddErrors,\n toAddEscalations,\n toAddMessages,\n toAddItemDefinitions);\n }\n for (Signal s : toAddSignals) {\n def.getRootElements().add(s);\n }\n for (Error er : toAddErrors) {\n def.getRootElements().add(er);\n }\n for (Escalation es : toAddEscalations) {\n def.getRootElements().add(es);\n }\n for (ItemDefinition idef : toAddItemDefinitions) {\n def.getRootElements().add(idef);\n }\n for (Message msg : toAddMessages) {\n def.getRootElements().add(msg);\n }\n }", "@SuppressWarnings(\"unused\")\n public Phonenumber.PhoneNumber getPhoneNumber() {\n try {\n String iso = null;\n if (mSelectedCountry != null) {\n iso = mSelectedCountry.getIso();\n }\n return mPhoneUtil.parse(mPhoneEdit.getText().toString(), iso);\n } catch (NumberParseException ignored) {\n return null;\n }\n }", "public static String encodeHost(String host, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(host, encoding, HierarchicalUriComponents.Type.HOST_IPV4);\n\t}", "public static void touch(final File folder , final String fileName) throws IOException {\n if(!folder.exists()){\n folder.mkdirs();\n }\n\n final File touchedFile = new File(folder, fileName);\n\n // The JVM will only 'touch' the file if you instantiate a\n // FileOutputStream instance for the file in question.\n // You don't actually write any data to the file through\n // the FileOutputStream. Just instantiate it and close it.\n\n try (\n FileOutputStream doneFOS = new FileOutputStream(touchedFile);\n ) {\n // Touching the file\n }\n catch (FileNotFoundException e) {\n throw new FileNotFoundException(\"Failed to the find file.\" + e);\n }\n }", "private CompiledStatement assignStatementArguments(CompiledStatement stmt) throws SQLException {\n\t\tboolean ok = false;\n\t\ttry {\n\t\t\tif (limit != null) {\n\t\t\t\t// we use this if SQL statement LIMITs are not supported by this database type\n\t\t\t\tstmt.setMaxRows(limit.intValue());\n\t\t\t}\n\t\t\t// set any arguments if we are logging our object\n\t\t\tObject[] argValues = null;\n\t\t\tif (logger.isLevelEnabled(Level.TRACE) && argHolders.length > 0) {\n\t\t\t\targValues = new Object[argHolders.length];\n\t\t\t}\n\t\t\tfor (int i = 0; i < argHolders.length; i++) {\n\t\t\t\tObject argValue = argHolders[i].getSqlArgValue();\n\t\t\t\tFieldType fieldType = argFieldTypes[i];\n\t\t\t\tSqlType sqlType;\n\t\t\t\tif (fieldType == null) {\n\t\t\t\t\tsqlType = argHolders[i].getSqlType();\n\t\t\t\t} else {\n\t\t\t\t\tsqlType = fieldType.getSqlType();\n\t\t\t\t}\n\t\t\t\tstmt.setObject(i, argValue, sqlType);\n\t\t\t\tif (argValues != null) {\n\t\t\t\t\targValues[i] = argValue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tlogger.debug(\"prepared statement '{}' with {} args\", statement, argHolders.length);\n\t\t\tif (argValues != null) {\n\t\t\t\t// need to do the (Object) cast to force args to be a single object\n\t\t\t\tlogger.trace(\"prepared statement arguments: {}\", (Object) argValues);\n\t\t\t}\n\t\t\tok = true;\n\t\t\treturn stmt;\n\t\t} finally {\n\t\t\tif (!ok) {\n\t\t\t\tIOUtils.closeThrowSqlException(stmt, \"statement\");\n\t\t\t}\n\t\t}\n\t}", "void markReferenceElements(PersistenceBroker broker)\r\n {\r\n // these cases will be handled by ObjectEnvelopeTable#cascadingDependents()\r\n // if(getModificationState().needsInsert() || getModificationState().needsDelete()) return;\r\n\r\n Map oldImage = getBeforeImage();\r\n Map newImage = getCurrentImage();\r\n\r\n Iterator iter = newImage.entrySet().iterator();\r\n while (iter.hasNext())\r\n {\r\n Map.Entry entry = (Map.Entry) iter.next();\r\n Object key = entry.getKey();\r\n // we only interested in references\r\n if(key instanceof ObjectReferenceDescriptor)\r\n {\r\n Image oldRefImage = (Image) oldImage.get(key);\r\n Image newRefImage = (Image) entry.getValue();\r\n newRefImage.performReferenceDetection(oldRefImage);\r\n }\r\n }\r\n }", "public BoxAPIResponse send(ProgressListener listener) {\n if (this.api == null) {\n this.backoffCounter.reset(BoxGlobalSettings.getMaxRequestAttempts());\n } else {\n this.backoffCounter.reset(this.api.getMaxRequestAttempts());\n }\n\n while (this.backoffCounter.getAttemptsRemaining() > 0) {\n try {\n return this.trySend(listener);\n } catch (BoxAPIException apiException) {\n if (!this.backoffCounter.decrement() || !isResponseRetryable(apiException.getResponseCode())) {\n throw apiException;\n }\n\n try {\n this.resetBody();\n } catch (IOException ioException) {\n throw apiException;\n }\n\n try {\n this.backoffCounter.waitBackoff();\n } catch (InterruptedException interruptedException) {\n Thread.currentThread().interrupt();\n throw apiException;\n }\n }\n }\n\n throw new RuntimeException();\n }" ]
Runs a query that returns a single int.
[ "public static int queryForInt(Statement stmt, String sql, int nullvalue) {\n try {\n ResultSet rs = stmt.executeQuery(sql);\n try {\n if (!rs.next())\n return nullvalue;\n \n return rs.getInt(1);\n } finally {\n rs.close();\n }\n } catch (SQLException e) {\n throw new DukeException(e);\n }\n }" ]
[ "public void checkAllGroupsSatisfied(final String currentPath) {\n StringBuilder errors = new StringBuilder();\n\n for (OneOfGroup group: this.mapping.values()) {\n\n if (group.satisfiedBy.isEmpty()) {\n errors.append(\"\\n\");\n errors.append(\"\\t* The OneOf choice: \").append(group.name)\n .append(\" was not satisfied. One (and only one) of the \");\n errors.append(\"following fields is required in the request data: \")\n .append(toNames(group.choices));\n }\n\n Collection<OneOfSatisfier> oneOfSatisfiers =\n Collections2.filter(group.satisfiedBy, input -> !input.isCanSatisfy);\n if (oneOfSatisfiers.size() > 1) {\n errors.append(\"\\n\");\n errors.append(\"\\t* The OneOf choice: \").append(group.name)\n .append(\" was satisfied by too many fields. Only one choice \");\n errors.append(\"may be in the request data. The fields found were: \")\n .append(toNames(toFields(group.satisfiedBy)));\n }\n }\n\n Assert.equals(0, errors.length(),\n \"\\nErrors were detected when analysing the @OneOf dependencies of '\" + currentPath +\n \"': \\n\" + errors);\n }", "public static inatparam get(nitro_service service) throws Exception{\n\t\tinatparam obj = new inatparam();\n\t\tinatparam[] response = (inatparam[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public DateRange getRange(int index)\n {\n DateRange result;\n\n if (index >= 0 && index < m_ranges.size())\n {\n result = m_ranges.get(index);\n }\n else\n {\n result = DateRange.EMPTY_RANGE;\n }\n\n return (result);\n }", "private List<Point2D> merge(final List<Point2D> one, final List<Point2D> two) {\n final Set<Point2D> oneSet = new HashSet<Point2D>(one);\n for (Point2D item : two) {\n if (!oneSet.contains(item)) {\n one.add(item);\n }\n }\n return one;\n }", "public GVRSceneObject startDrag(GVRSceneObject dragMe, float relX, float relY, float relZ) {\n synchronized (mLock) {\n if (mCursorController == null) {\n Log.w(TAG, \"Physics drag failed: Cursor controller not found!\");\n return null;\n }\n\n if (mDragMe != null) {\n Log.w(TAG, \"Physics drag failed: Previous drag wasn't finished!\");\n return null;\n }\n\n if (mPivotObject == null) {\n mPivotObject = onCreatePivotObject(mContext);\n }\n\n mDragMe = dragMe;\n\n GVRTransform t = dragMe.getTransform();\n\n /* It is not possible to drag a rigid body directly, we need a pivot object.\n We are using the pivot object's position as pivot of the dragging's physics constraint.\n */\n mPivotObject.getTransform().setPosition(t.getPositionX() + relX,\n t.getPositionY() + relY, t.getPositionZ() + relZ);\n\n mCursorController.startDrag(mPivotObject);\n }\n\n return mPivotObject;\n }", "public static void main(String args[]) throws Exception {\n final StringBuffer buffer = new StringBuffer(\"The lazy fox\");\n Thread t1 = new Thread() {\n public void run() {\n synchronized(buffer) {\n buffer.delete(0,4);\n buffer.append(\" in the middle\");\n System.err.println(\"Middle\");\n try { Thread.sleep(4000); } catch(Exception e) {}\n buffer.append(\" of fall\");\n System.err.println(\"Fall\");\n }\n }\n };\n Thread t2 = new Thread() {\n public void run() {\n try { Thread.sleep(1000); } catch(Exception e) {}\n buffer.append(\" jump over the fence\");\n System.err.println(\"Fence\");\n }\n };\n t1.start();\n t2.start();\n\n t1.join();\n t2.join();\n System.err.println(buffer);\n }", "private void visitImplicitFirstFrame() {\n // There can be at most descriptor.length() + 1 locals\n int frameIndex = startFrame(0, descriptor.length() + 1, 0);\n if ((access & Opcodes.ACC_STATIC) == 0) {\n if ((access & ACC_CONSTRUCTOR) == 0) {\n frame[frameIndex++] = Frame.OBJECT | cw.addType(cw.thisName);\n } else {\n frame[frameIndex++] = Frame.UNINITIALIZED_THIS;\n }\n }\n int i = 1;\n loop: while (true) {\n int j = i;\n switch (descriptor.charAt(i++)) {\n case 'Z':\n case 'C':\n case 'B':\n case 'S':\n case 'I':\n frame[frameIndex++] = Frame.INTEGER;\n break;\n case 'F':\n frame[frameIndex++] = Frame.FLOAT;\n break;\n case 'J':\n frame[frameIndex++] = Frame.LONG;\n break;\n case 'D':\n frame[frameIndex++] = Frame.DOUBLE;\n break;\n case '[':\n while (descriptor.charAt(i) == '[') {\n ++i;\n }\n if (descriptor.charAt(i) == 'L') {\n ++i;\n while (descriptor.charAt(i) != ';') {\n ++i;\n }\n }\n frame[frameIndex++] = Frame.type(cw, descriptor.substring(j, ++i));\n break;\n case 'L':\n while (descriptor.charAt(i) != ';') {\n ++i;\n }\n frame[frameIndex++] = Frame.OBJECT\n | cw.addType(descriptor.substring(j + 1, i++));\n break;\n default:\n break loop;\n }\n }\n frame[1] = frameIndex - 3;\n endFrame();\n }", "private static boolean scanForEndSig(File file, FileChannel channel) throws IOException, NonScannableZipException {\n\n // TODO Consider just reading in MAX_REVERSE_SCAN bytes -- increased peak memory cost but less complex\n\n ByteBuffer bb = getByteBuffer(CHUNK_SIZE);\n long start = channel.size();\n long end = Math.max(0, start - MAX_REVERSE_SCAN);\n long channelPos = Math.max(0, start - CHUNK_SIZE);\n long lastChannelPos = channelPos;\n boolean firstRead = true;\n while (lastChannelPos >= end) {\n\n read(bb, channel, channelPos);\n\n int actualRead = bb.limit();\n if (firstRead) {\n long expectedRead = Math.min(CHUNK_SIZE, start);\n if (actualRead > expectedRead) {\n // File is still growing\n return false;\n }\n firstRead = false;\n }\n\n int bufferPos = actualRead -1;\n while (bufferPos >= SIG_PATTERN_LENGTH) {\n\n // Following is based on the Boyer Moore algorithm but simplified to reflect\n // a) the pattern is static\n // b) the pattern has no repeating bytes\n\n int patternPos;\n for (patternPos = SIG_PATTERN_LENGTH - 1;\n patternPos >= 0 && ENDSIG_PATTERN[patternPos] == bb.get(bufferPos - patternPos);\n --patternPos) {\n // empty loop while bytes match\n }\n\n // Switch gives same results as checking the \"good suffix array\" in the Boyer Moore algorithm\n switch (patternPos) {\n case -1: {\n // Pattern matched. Confirm is this is the start of a valid end of central dir record\n long startEndRecord = channelPos + bufferPos - SIG_PATTERN_LENGTH + 1;\n if (validateEndRecord(file, channel, startEndRecord)) {\n return true;\n }\n // wasn't a valid end record; continue scan\n bufferPos -= 4;\n break;\n }\n case 3: {\n // No bytes matched; the common case.\n // With our pattern, this is the only case where the Boyer Moore algorithm's \"bad char array\" may\n // produce a shift greater than the \"good suffix array\" (which would shift 1 byte)\n int idx = bb.get(bufferPos - patternPos) - Byte.MIN_VALUE;\n bufferPos -= END_BAD_BYTE_SKIP[idx];\n break;\n }\n default:\n // 1 or more bytes matched\n bufferPos -= 4;\n }\n }\n\n // Move back a full chunk. If we didn't read a full chunk, that's ok,\n // it means we read all data and the outer while loop will terminate\n if (channelPos <= bufferPos) {\n break;\n }\n lastChannelPos = channelPos;\n channelPos -= Math.min(channelPos - bufferPos, CHUNK_SIZE - bufferPos);\n }\n\n return false;\n }", "private String getResourceField(int key)\n {\n String result = null;\n\n if (key > 0 && key < m_resourceNames.length)\n {\n result = m_resourceNames[key];\n }\n\n return (result);\n }" ]
Add a misc file. @param name the file name @param path the relative path @param newHash the new hash of the added content @param isDirectory whether the file is a directory or not @return the builder
[ "public T addFile(final String name, final List<String> path, final byte[] newHash, final boolean isDirectory) {\n return addFile(name, path, newHash, isDirectory, null);\n }" ]
[ "@Override\r\n @SuppressWarnings(\"unchecked\")\r\n public V put(K key, V value) {\r\n if (value == null) {\r\n return put(key, (V)nullValue);\r\n }\r\n // key could be not in original or in deltaMap\r\n // key could be not in original but in deltaMap\r\n // key could be in original but removed from deltaMap\r\n // key could be in original but mapped to something else in deltaMap\r\n V result = deltaMap.put(key, value);\r\n if (result == null) {\r\n return originalMap.get(key);\r\n }\r\n if (result == nullValue) {\r\n return null;\r\n }\r\n if (result == removedValue) {\r\n return null;\r\n }\r\n return result;\r\n }", "private List<AssignmentField> getAllAssignmentExtendedAttributes()\n {\n ArrayList<AssignmentField> result = new ArrayList<AssignmentField>();\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_COST));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_DATE));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_DURATION));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_COST));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_DATE));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_DURATION));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_FLAG));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_NUMBER));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_RESOURCE_MULTI_VALUE));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_RESOURCE_OUTLINE_CODE));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_TEXT));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_FINISH));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_FLAG));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_NUMBER));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_START));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_TEXT));\n return result;\n }", "public CrosstabBuilder setColumnStyles(Style headerStyle, Style totalStyle, Style totalHeaderStyle) {\r\n\t\tcrosstab.setColumnHeaderStyle(headerStyle);\r\n\t\tcrosstab.setColumnTotalheaderStyle(totalHeaderStyle);\r\n\t\tcrosstab.setColumnTotalStyle(totalStyle);\r\n\t\treturn this;\r\n\t}", "public ItemRequest<Team> findById(String team) {\n \n String path = String.format(\"/teams/%s\", team);\n return new ItemRequest<Team>(this, Team.class, path, \"GET\");\n }", "public FormAction setValuesInForm(Form form) {\r\n\t\tFormAction formAction = new FormAction();\r\n\t\tform.setFormAction(formAction);\r\n\t\tthis.forms.add(form);\r\n\t\treturn formAction;\r\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 void errorFuture(UUID taskId, Exception e) {\n DistributedFuture<GROUP, Serializable> future = remove(taskId);\n if(future != null) {\n future.setException(e);\n }\n }", "public static boolean isPartOfRegularEmbedded(String[] keyColumnNames, String column) {\n\t\treturn isPartOfEmbedded( column ) && !ArrayHelper.contains( keyColumnNames, column );\n\t}", "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}" ]
Initializes a type @param name The name of the class @return The instance of the class. Returns a dummy if the class was not found.
[ "protected Class<?> classForName(String name) {\n try {\n return resourceLoader.classForName(name);\n } catch (ResourceLoadingException cnfe) {\n return DUMMY_CLASS;\n }\n }" ]
[ "public static boolean isVariable(ASTNode expression, String pattern) {\r\n return (expression instanceof VariableExpression && ((VariableExpression) expression).getName().matches(pattern));\r\n }", "protected String getDBManipulationUrl()\r\n {\r\n JdbcConnectionDescriptor jcd = getConnection();\r\n\r\n return jcd.getProtocol()+\":\"+jcd.getSubProtocol()+\":\"+jcd.getDbAlias();\r\n }", "public void loadClassifier(InputStream in, Properties props) throws IOException, ClassCastException,\r\n ClassNotFoundException {\r\n loadClassifier(new ObjectInputStream(in), props);\r\n }", "public Build getBuildInfo(String appName, String buildId) {\n return connection.execute(new BuildInfo(appName, buildId), apiKey);\n }", "public void setWriteTimeout(int writeTimeout) {\n\t\tthis.client = this.client.newBuilder()\n\t\t\t\t.writeTimeout(writeTimeout, TimeUnit.MILLISECONDS)\n\t\t\t\t.build();\n\t}", "@GET\n @Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON})\n @Path(\"/{name}\" + ServerAPI.GET_CORPORATE_GROUPIDS)\n public Response getCorporateGroupIdPrefix(@PathParam(\"name\") final String organizationId){\n LOG.info(\"Got a get corporate groupId prefix request for organization \" + organizationId +\".\");\n\n final ListView view = new ListView(\"Organization \" + organizationId, \"Corporate GroupId Prefix\");\n final List<String> corporateGroupIds = getOrganizationHandler().getCorporateGroupIds(organizationId);\n view.addAll(corporateGroupIds);\n\n return Response.ok(view).build();\n }", "protected void processAssignmentBaseline(Row row)\n {\n Integer id = row.getInteger(\"ASSN_UID\");\n ResourceAssignment assignment = m_assignmentMap.get(id);\n if (assignment != null)\n {\n int index = row.getInt(\"AB_BASE_NUM\");\n\n assignment.setBaselineStart(index, row.getDate(\"AB_BASE_START\"));\n assignment.setBaselineFinish(index, row.getDate(\"AB_BASE_FINISH\"));\n assignment.setBaselineWork(index, row.getDuration(\"AB_BASE_WORK\"));\n assignment.setBaselineCost(index, row.getCurrency(\"AB_BASE_COST\"));\n }\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 }", "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 }" ]
Return the AnnotationNode for the named annotation, or else null. Supports Groovy 1.5 and Groovy 1.6. @param node - the AnnotatedNode @param name - the name of the annotation @return the AnnotationNode or else null
[ "public static AnnotationNode getAnnotation(AnnotatedNode node, String name) {\r\n List<AnnotationNode> annotations = node.getAnnotations();\r\n for (AnnotationNode annot : annotations) {\r\n if (annot.getClassNode().getName().equals(name)) {\r\n return annot;\r\n }\r\n }\r\n return null;\r\n }" ]
[ "public int getHotCueCount() {\n if (rawMessage != null) {\n return (int) ((NumberField) rawMessage.arguments.get(5)).getValue();\n }\n int total = 0;\n for (Entry entry : entries) {\n if (entry.hotCueNumber > 0) {\n ++total;\n }\n }\n return total;\n }", "public static void extract(DMatrixRMaj src, int indexes[] , int length , DMatrixRMaj dst ) {\n if( !MatrixFeatures_DDRM.isVector(dst))\n throw new MatrixDimensionException(\"Dst must be a vector\");\n if( length != dst.getNumElements())\n throw new MatrixDimensionException(\"Unexpected number of elements in dst vector\");\n\n for (int i = 0; i < length; i++) {\n dst.data[i] = src.data[indexes[i]];\n }\n }", "protected void handleRequestOut(T message) throws Fault {\n String flowId = FlowIdHelper.getFlowId(message);\n if (flowId == null\n && message.containsKey(PhaseInterceptorChain.PREVIOUS_MESSAGE)) {\n // Web Service consumer is acting as an intermediary\n @SuppressWarnings(\"unchecked\")\n WeakReference<Message> wrPreviousMessage = (WeakReference<Message>) message\n .get(PhaseInterceptorChain.PREVIOUS_MESSAGE);\n Message previousMessage = (Message) wrPreviousMessage.get();\n flowId = FlowIdHelper.getFlowId(previousMessage);\n if (flowId != null && LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"flowId '\" + flowId + \"' found in previous message\");\n }\n }\n\n if (flowId == null) {\n // No flowId found. Generate one.\n flowId = ContextUtils.generateUUID();\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Generate new flowId '\" + flowId + \"'\");\n }\n }\n\n FlowIdHelper.setFlowId(message, flowId);\n }", "public static final Duration parseDuration(String value)\n {\n return value == null ? null : Duration.getInstance(Double.parseDouble(value), TimeUnit.DAYS);\n }", "public Set<String> findResourceNames(String location, URI locationUri) throws IOException {\n String filePath = toFilePath(locationUri);\n File folder = new File(filePath);\n if (!folder.isDirectory()) {\n LOGGER.debug(\"Skipping path as it is not a directory: \" + filePath);\n return new TreeSet<>();\n }\n\n String classPathRootOnDisk = filePath.substring(0, filePath.length() - location.length());\n if (!classPathRootOnDisk.endsWith(File.separator)) {\n classPathRootOnDisk = classPathRootOnDisk + File.separator;\n }\n LOGGER.debug(\"Scanning starting at classpath root in filesystem: \" + classPathRootOnDisk);\n return findResourceNamesFromFileSystem(classPathRootOnDisk, location, folder);\n }", "private void processConstraints(Row row, Task task)\n {\n ConstraintType constraintType = ConstraintType.AS_SOON_AS_POSSIBLE;\n Date constraintDate = null;\n\n switch (row.getInt(\"CONSTRAINU\"))\n {\n case 0:\n {\n if (row.getInt(\"PLACEMENT\") == 0)\n {\n constraintType = ConstraintType.AS_SOON_AS_POSSIBLE;\n }\n else\n {\n constraintType = ConstraintType.AS_LATE_AS_POSSIBLE;\n }\n break;\n }\n\n case 1:\n {\n constraintType = ConstraintType.MUST_START_ON;\n constraintDate = row.getDate(\"START_CONSTRAINT_DATE\");\n break;\n }\n\n case 2:\n {\n constraintType = ConstraintType.START_NO_LATER_THAN;\n constraintDate = row.getDate(\"START_CONSTRAINT_DATE\");\n break;\n }\n\n case 3:\n {\n constraintType = ConstraintType.START_NO_EARLIER_THAN;\n constraintDate = row.getDate(\"START_CONSTRAINT_DATE\");\n break;\n }\n\n case 4:\n {\n constraintType = ConstraintType.MUST_FINISH_ON;\n constraintDate = row.getDate(\"END_CONSTRAINT_DATE\");\n break;\n }\n\n case 5:\n {\n constraintType = ConstraintType.FINISH_NO_LATER_THAN;\n constraintDate = row.getDate(\"END_CONSTRAINT_DATE\");\n break;\n }\n\n case 6:\n {\n constraintType = ConstraintType.FINISH_NO_EARLIER_THAN;\n constraintDate = row.getDate(\"END_CONSTRAINT_DATE\");\n break;\n }\n\n case 8:\n {\n task.setDeadline(row.getDate(\"END_CONSTRAINT_DATE\"));\n break;\n }\n }\n\n task.setConstraintType(constraintType);\n task.setConstraintDate(constraintDate);\n }", "public static int convertBytesToInt(byte[] bytes, int offset)\n {\n return (BITWISE_BYTE_TO_INT & bytes[offset + 3])\n | ((BITWISE_BYTE_TO_INT & bytes[offset + 2]) << 8)\n | ((BITWISE_BYTE_TO_INT & bytes[offset + 1]) << 16)\n | ((BITWISE_BYTE_TO_INT & bytes[offset]) << 24);\n }", "public static Map<String,String> unserializeBuildInfo(final String buildInfo) throws IOException {\n final ObjectMapper mapper = new ObjectMapper();\n mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);\n return mapper.readValue(buildInfo, new TypeReference<Map<String, Object>>(){});\n }", "protected void layoutGroupSubreports(DJGroup columnsGroup, JRDesignGroup jgroup) {\n\t\tlog.debug(\"Starting subreport layout...\");\n\t\tJRDesignBand footerBand = (JRDesignBand) ((JRDesignSection)jgroup.getGroupFooterSection()).getBandsList().get(0);\n\t\tJRDesignBand headerBand = (JRDesignBand) ((JRDesignSection)jgroup.getGroupHeaderSection()).getBandsList().get(0);\n\n\t\tlayOutSubReportInBand(columnsGroup, headerBand, DJConstants.HEADER);\n\t\tlayOutSubReportInBand(columnsGroup, footerBand, DJConstants.FOOTER);\n\n\t}" ]
Gets a list of registered docker images from the images cache, if it has been registered to the cache for a specific build-info ID and if a docker manifest has been captured for it by the build-info proxy. Additionally, the methods also removes the returned images from the cache. @param buildInfoId @return
[ "public static List<DockerImage> getAndDiscardImagesByBuildId(int buildInfoId) {\n List<DockerImage> list = new ArrayList<DockerImage>();\n synchronized(images) {\n Iterator<DockerImage> it = images.iterator();\n while (it.hasNext()) {\n DockerImage image = it.next();\n if (image.getBuildInfoId() == buildInfoId) {\n if (image.hasManifest()) {\n list.add(image);\n }\n it.remove();\n } else // Remove old images from the cache, for which build-info hasn't been published to Artifactory:\n if (image.isExpired()) {\n it.remove();\n }\n }\n }\n return list;\n }" ]
[ "public void setOutRGB(IntRange outRGB) {\r\n this.outRed = outRGB;\r\n this.outGreen = outRGB;\r\n this.outBlue = outRGB;\r\n\r\n CalculateMap(inRed, outRGB, mapRed);\r\n CalculateMap(inGreen, outRGB, mapGreen);\r\n CalculateMap(inBlue, outRGB, mapBlue);\r\n }", "@Nonnull\n public BufferedImage createBufferedImage(final int imageWidth, final int imageHeight) {\n return new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_4BYTE_ABGR);\n }", "public void assignField(ConnectionSource connectionSource, Object data, Object val, boolean parentObject,\n\t\t\tObjectCache objectCache) throws SQLException {\n\n\t\tif (logger.isLevelEnabled(Level.TRACE)) {\n\t\t\tlogger.trace(\"assiging from data {}, val {}: {}\", (data == null ? \"null\" : data.getClass()),\n\t\t\t\t\t(val == null ? \"null\" : val.getClass()), val);\n\t\t}\n\t\t// if this is a foreign object then val is the foreign object's id val\n\t\tif (foreignRefField != null && val != null) {\n\t\t\t// get the current field value which is the foreign-id\n\t\t\tObject foreignRef = extractJavaFieldValue(data);\n\t\t\t/*\n\t\t\t * See if we don't need to create a new foreign object. If we are refreshing and the id field has not\n\t\t\t * changed then there is no need to create a new foreign object and maybe lose previously refreshed field\n\t\t\t * information.\n\t\t\t */\n\t\t\tif (foreignRef != null && foreignRef.equals(val)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// awhitlock: raised as OrmLite issue: bug #122\n\t\t\tObject cachedVal;\n\t\t\tObjectCache foreignCache = foreignDao.getObjectCache();\n\t\t\tif (foreignCache == null) {\n\t\t\t\tcachedVal = null;\n\t\t\t} else {\n\t\t\t\tcachedVal = foreignCache.get(getType(), val);\n\t\t\t}\n\t\t\tif (cachedVal != null) {\n\t\t\t\tval = cachedVal;\n\t\t\t} else if (!parentObject) {\n\t\t\t\t// the value we are to assign to our field is now the foreign object itself\n\t\t\t\tval = createForeignObject(connectionSource, val, objectCache);\n\t\t\t}\n\t\t}\n\n\t\tif (fieldSetMethod == null) {\n\t\t\ttry {\n\t\t\t\tfield.set(data, val);\n\t\t\t} catch (IllegalArgumentException e) {\n\t\t\t\tif (val == null) {\n\t\t\t\t\tthrow SqlExceptionUtil.create(\"Could not assign object '\" + val + \"' to field \" + this, e);\n\t\t\t\t} else {\n\t\t\t\t\tthrow SqlExceptionUtil.create(\n\t\t\t\t\t\t\t\"Could not assign object '\" + val + \"' of type \" + val.getClass() + \" to field \" + this, e);\n\t\t\t\t}\n\t\t\t} catch (IllegalAccessException e) {\n\t\t\t\tthrow SqlExceptionUtil.create(\n\t\t\t\t\t\t\"Could not assign object '\" + val + \"' of type \" + val.getClass() + \"' to field \" + this, e);\n\t\t\t}\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tfieldSetMethod.invoke(data, val);\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow SqlExceptionUtil\n\t\t\t\t\t\t.create(\"Could not call \" + fieldSetMethod + \" on object with '\" + val + \"' for \" + this, e);\n\t\t\t}\n\t\t}\n\t}", "private static void checkPreconditions(List<String> requiredSubStrings) {\n\t\tif( requiredSubStrings == null ) {\n\t\t\tthrow new NullPointerException(\"requiredSubStrings List should not be null\");\n\t\t} else if( requiredSubStrings.isEmpty() ) {\n\t\t\tthrow new IllegalArgumentException(\"requiredSubStrings List should not be empty\");\n\t\t}\n\t}", "public ServerGroup addServerGroup(String groupName) {\n ServerGroup group = new ServerGroup();\n\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"name\", groupName),\n new BasicNameValuePair(\"profileIdentifier\", this._profileName)\n };\n try {\n JSONObject response = new JSONObject(doPost(BASE_SERVERGROUP, params));\n group = getServerGroupFromJSON(response);\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n return group;\n }", "protected void associateBatched(Collection owners, Collection children)\r\n {\r\n ObjectReferenceDescriptor ord = getObjectReferenceDescriptor();\r\n ClassDescriptor cld = getOwnerClassDescriptor();\r\n Object owner;\r\n Object relatedObject;\r\n Object fkValues[];\r\n Identity id;\r\n PersistenceBroker pb = getBroker();\r\n PersistentField field = ord.getPersistentField();\r\n Class topLevelClass = pb.getTopLevelClass(ord.getItemClass());\r\n HashMap childrenMap = new HashMap(children.size());\r\n\r\n\r\n for (Iterator it = children.iterator(); it.hasNext(); )\r\n {\r\n relatedObject = it.next();\r\n childrenMap.put(pb.serviceIdentity().buildIdentity(relatedObject), relatedObject);\r\n }\r\n\r\n for (Iterator it = owners.iterator(); it.hasNext(); )\r\n {\r\n owner = it.next();\r\n fkValues = ord.getForeignKeyValues(owner,cld);\r\n if (isNull(fkValues))\r\n {\r\n field.set(owner, null);\r\n continue;\r\n }\r\n id = pb.serviceIdentity().buildIdentity(null, topLevelClass, fkValues);\r\n relatedObject = childrenMap.get(id);\r\n field.set(owner, relatedObject);\r\n }\r\n }", "public void addColumnIsNull(String column)\r\n {\r\n\t\t// PAW\r\n\t\t//SelectionCriteria c = ValueCriteria.buildNullCriteria(column, getAlias());\r\n\t\tSelectionCriteria c = ValueCriteria.buildNullCriteria(column, getUserAlias(column));\r\n c.setTranslateAttribute(false);\r\n addSelectionCriteria(c);\r\n }", "public ItemRequest<Project> addFollowers(String project) {\n \n String path = String.format(\"/projects/%s/addFollowers\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\n }", "public static String objectToColumnString(Object object, String delimiter, String[] fieldNames)\r\n throws IllegalAccessException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException\r\n {\r\n StringBuilder sb = new StringBuilder();\r\n for (int i = 0; i < fieldNames.length; i++) {\r\n if (sb.length() > 0) {\r\n sb.append(delimiter);\r\n }\r\n try {\r\n Field field = object.getClass().getDeclaredField(fieldNames[i]);\r\n sb.append(field.get(object)) ;\r\n } catch (IllegalAccessException ex) {\r\n Method method = object.getClass().getDeclaredMethod(\"get\" + StringUtils.capitalize(fieldNames[i]));\r\n sb.append(method.invoke(object));\r\n }\r\n }\r\n return sb.toString();\r\n }" ]
Compares two avro strings which contains multiple store configs @param configAvro1 @param configAvro2 @return true if two config avro strings have same content
[ "public static Boolean compareMultipleClientConfigAvro(String configAvro1, String configAvro2) {\n Map<String, Properties> mapStoreToProps1 = readMultipleClientConfigAvro(configAvro1);\n Map<String, Properties> mapStoreToProps2 = readMultipleClientConfigAvro(configAvro2);\n Set<String> keySet1 = mapStoreToProps1.keySet();\n Set<String> keySet2 = mapStoreToProps2.keySet();\n if(!keySet1.equals(keySet2)) {\n return false;\n }\n for(String storeName: keySet1) {\n Properties props1 = mapStoreToProps1.get(storeName);\n Properties props2 = mapStoreToProps2.get(storeName);\n if(!props1.equals(props2)) {\n return false;\n }\n }\n return true;\n }" ]
[ "public static byte[] decodeBase64(String value) {\n int byteShift = 4;\n int tmp = 0;\n boolean done = false;\n final StringBuilder buffer = new StringBuilder();\n\n for (int i = 0; i != value.length(); i++) {\n final char c = value.charAt(i);\n final int sixBit = (c < 123) ? EncodingGroovyMethodsSupport.TRANSLATE_TABLE[c] : 66;\n\n if (sixBit < 64) {\n if (done)\n throw new RuntimeException(\"= character not at end of base64 value\"); // TODO: change this exception type\n\n tmp = (tmp << 6) | sixBit;\n\n if (byteShift-- != 4) {\n buffer.append((char) ((tmp >> (byteShift * 2)) & 0XFF));\n }\n\n } else if (sixBit == 64) {\n\n byteShift--;\n done = true;\n\n } else if (sixBit == 66) {\n // RFC 2045 says that I'm allowed to take the presence of\n // these characters as evidence of data corruption\n // So I will\n throw new RuntimeException(\"bad character in base64 value\"); // TODO: change this exception type\n }\n\n if (byteShift == 0) byteShift = 4;\n }\n\n try {\n return buffer.toString().getBytes(\"ISO-8859-1\");\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(\"Base 64 decode produced byte values > 255\"); // TODO: change this exception type\n }\n }", "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}", "@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 }", "private Set<String> checkModel(final ModelNode model, TransformationContext context) throws OperationFailedException {\n final Set<String> attributes = new HashSet<String>();\n AttributeTransformationRequirementChecker checker;\n for (final String attribute : attributeNames) {\n if (model.hasDefined(attribute)) {\n if (attributeCheckers != null && (checker = attributeCheckers.get(attribute)) != null) {\n if (checker.isAttributeTransformationRequired(attribute, model.get(attribute), context)) {\n attributes.add(attribute);\n }\n } else if (SIMPLE_EXPRESSIONS.isAttributeTransformationRequired(attribute, model.get(attribute), context)) {\n attributes.add(attribute);\n }\n }\n }\n return attributes;\n }", "private static Iterable<BoxUser.Info> getUsersInfoForType(final BoxAPIConnection api,\n final String filterTerm, final String userType, final String externalAppUserId, final String... fields) {\n return new Iterable<BoxUser.Info>() {\n public Iterator<BoxUser.Info> iterator() {\n QueryStringBuilder builder = new QueryStringBuilder();\n if (filterTerm != null) {\n builder.appendParam(\"filter_term\", filterTerm);\n }\n if (userType != null) {\n builder.appendParam(\"user_type\", userType);\n }\n if (externalAppUserId != null) {\n builder.appendParam(\"external_app_user_id\", externalAppUserId);\n }\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields);\n }\n URL url = USERS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString());\n return new BoxUserIterator(api, url);\n }\n };\n }", "public PreparedStatement getPreparedStatement(ClassDescriptor cds, String sql,\r\n boolean scrollable, int explicitFetchSizeHint, boolean callableStmt)\r\n throws PersistenceBrokerException\r\n {\r\n try\r\n {\r\n return cds.getStatementsForClass(m_conMan).getPreparedStmt(m_conMan.getConnection(), sql, scrollable, explicitFetchSizeHint, callableStmt);\r\n }\r\n catch (LookupException e)\r\n {\r\n throw new PersistenceBrokerException(\"Used ConnectionManager instance could not obtain a connection\", e);\r\n }\r\n }", "@RequestMapping(value = \"/api/scripts\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getScripts(Model model,\n @RequestParam(required = false) Integer type) throws Exception {\n Script[] scripts = ScriptService.getInstance().getScripts(type);\n return Utils.getJQGridJSON(scripts, \"scripts\");\n }", "public static nslimitselector get(nitro_service service, String selectorname) throws Exception{\n\t\tnslimitselector obj = new nslimitselector();\n\t\tobj.set_selectorname(selectorname);\n\t\tnslimitselector response = (nslimitselector) obj.get_resource(service);\n\t\treturn response;\n\t}", "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 }" ]
Assign a new value to this field. @param numStrings - number of strings @param newValues - the new strings
[ "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 }" ]
[ "private void addArrayMethods(List<MethodNode> methods, ClassNode receiver, String name, ClassNode[] args) {\n if (args.length!=1) return;\n if (!receiver.isArray()) return;\n if (!isIntCategory(getUnwrapper(args[0]))) return;\n if (\"getAt\".equals(name)) {\n MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC, receiver.getComponentType(), new Parameter[]{new Parameter(args[0],\"arg\")}, null, null);\n node.setDeclaringClass(receiver.redirect());\n methods.add(node);\n } else if (\"setAt\".equals(name)) {\n MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC, VOID_TYPE, new Parameter[]{new Parameter(args[0],\"arg\")}, null, null);\n node.setDeclaringClass(receiver.redirect());\n methods.add(node);\n }\n }", "@Override\n public InternationalFixedDate date(int prolepticYear, int month, int dayOfMonth) {\n return InternationalFixedDate.of(prolepticYear, month, dayOfMonth);\n }", "public static Collection<CurrencyUnit> getCurrencies(String... providers) {\n return Optional.ofNullable(MONETARY_CURRENCIES_SINGLETON_SPI()).orElseThrow(\n () -> new MonetaryException(\"No MonetaryCurrenciesSingletonSpi loaded, check your system setup.\"))\n .getCurrencies(providers);\n }", "private ArrayList handleDependentReferences(Identity oid, Object userObject,\r\n Object[] origFields, Object[] newFields, Object[] newRefs)\r\n throws LockingException\r\n {\r\n ClassDescriptor mif = _pb.getClassDescriptor(userObject.getClass());\r\n FieldDescriptor[] fieldDescs = mif.getFieldDescriptions();\r\n Collection refDescs = mif.getObjectReferenceDescriptors();\r\n int count = 1 + fieldDescs.length;\r\n ArrayList newObjects = new ArrayList();\r\n int countRefs = 0;\r\n\r\n for (Iterator it = refDescs.iterator(); it.hasNext(); count++, countRefs++)\r\n {\r\n ObjectReferenceDescriptor rds = (ObjectReferenceDescriptor) it.next();\r\n Identity origOid = (origFields == null ? null : (Identity) origFields[count]);\r\n Identity newOid = (Identity) newFields[count];\r\n\r\n if (rds.getOtmDependent())\r\n {\r\n if ((origOid == null) && (newOid != null))\r\n {\r\n ContextEntry entry = (ContextEntry) _objects.get(newOid);\r\n\r\n if (entry == null)\r\n {\r\n Object relObj = newRefs[countRefs];\r\n insertInternal(newOid, relObj, LockType.WRITE_LOCK,\r\n true, oid, new Stack());\r\n newObjects.add(newOid);\r\n }\r\n }\r\n else if ((origOid != null) &&\r\n ((newOid == null) || !newOid.equals(origOid)))\r\n {\r\n markDelete(origOid, oid, false);\r\n }\r\n }\r\n }\r\n\r\n return newObjects;\r\n }", "public static int Mode( int[] values ){\n int mode = 0, curMax = 0;\n\n for ( int i = 0, length = values.length; i < length; i++ )\n {\n if ( values[i] > curMax )\n {\n curMax = values[i];\n mode = i;\n }\n }\n return mode;\n }", "private void getMultipleValues(Method method, Object object, Map<String, String> map)\n {\n try\n {\n int index = 1;\n while (true)\n {\n Object value = filterValue(method.invoke(object, Integer.valueOf(index)));\n if (value != null)\n {\n map.put(getPropertyName(method, index), String.valueOf(value));\n }\n ++index;\n }\n }\n catch (Exception ex)\n {\n // Reached the end of the valid indexes\n }\n }", "public float getChildSize(final int dataIndex, final Axis axis) {\n float size = 0;\n Widget child = mContainer.get(dataIndex);\n if (child != null) {\n switch (axis) {\n case X:\n size = child.getLayoutWidth();\n break;\n case Y:\n size = child.getLayoutHeight();\n break;\n case Z:\n size = child.getLayoutDepth();\n break;\n default:\n throw new RuntimeAssertion(\"Bad axis specified: %s\", axis);\n }\n }\n return size;\n }", "public static double blackScholesDigitalOptionDelta(\n\t\t\tdouble initialStockValue,\n\t\t\tdouble riskFreeRate,\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike)\n\t{\n\t\tif(optionStrike <= 0.0 || optionMaturity <= 0.0)\n\t\t{\n\t\t\t// The Black-Scholes model does not consider it being an option\n\t\t\treturn 0.0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Calculate delta\n\t\t\tdouble dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));\n\t\t\tdouble dMinus = dPlus - volatility * Math.sqrt(optionMaturity);\n\n\t\t\tdouble delta = Math.exp(-0.5*dMinus*dMinus) / (Math.sqrt(2.0 * Math.PI * optionMaturity) * initialStockValue * volatility);\n\n\t\t\treturn delta;\n\t\t}\n\t}", "public ProviderContextBuilder setRateTypes(Collection<RateType> rateTypes) {\n Objects.requireNonNull(rateTypes);\n if (rateTypes.isEmpty()) {\n throw new IllegalArgumentException(\"At least one RateType is required.\");\n }\n Set<RateType> rtSet = new HashSet<>(rateTypes);\n set(ProviderContext.KEY_RATE_TYPES, rtSet);\n return this;\n }" ]
Use this API to add tmtrafficaction.
[ "public static base_response add(nitro_service client, tmtrafficaction resource) throws Exception {\n\t\ttmtrafficaction addresource = new tmtrafficaction();\n\t\taddresource.name = resource.name;\n\t\taddresource.apptimeout = resource.apptimeout;\n\t\taddresource.sso = resource.sso;\n\t\taddresource.formssoaction = resource.formssoaction;\n\t\taddresource.persistentcookie = resource.persistentcookie;\n\t\taddresource.initiatelogout = resource.initiatelogout;\n\t\taddresource.kcdaccount = resource.kcdaccount;\n\t\taddresource.samlssoprofile = resource.samlssoprofile;\n\t\treturn addresource.add_resource(client);\n\t}" ]
[ "private void loadCadidateString() {\n volumeUp = mGvrContext.getActivity().getResources().getString(R.string.volume_up);\n volumeDown = mGvrContext.getActivity().getResources().getString(R.string.volume_down);\n zoomIn = mGvrContext.getActivity().getResources().getString(R.string.zoom_in);\n zoomOut = mGvrContext.getActivity().getResources().getString(R.string.zoom_out);\n invertedColors = mGvrContext.getActivity().getResources().getString(R.string.inverted_colors);\n talkBack = mGvrContext.getActivity().getResources().getString(R.string.talk_back);\n disableTalkBack = mGvrContext.getActivity().getResources().getString(R.string.disable_talk_back);\n }", "protected synchronized ResourceRoot getSeamIntResourceRoot() throws DeploymentUnitProcessingException {\n try {\n if (seamIntResourceRoot == null) {\n final ModuleLoader moduleLoader = Module.getBootModuleLoader();\n Module extModule = moduleLoader.loadModule(EXT_CONTENT_MODULE);\n URL url = extModule.getExportedResource(SEAM_INT_JAR);\n if (url == null)\n throw ServerLogger.ROOT_LOGGER.noSeamIntegrationJarPresent(extModule);\n\n File file = new File(url.toURI());\n VirtualFile vf = VFS.getChild(file.toURI());\n final Closeable mountHandle = VFS.mountZip(file, vf, TempFileProviderService.provider());\n Service<Closeable> mountHandleService = new Service<Closeable>() {\n public void start(StartContext startContext) throws StartException {\n }\n\n public void stop(StopContext stopContext) {\n VFSUtils.safeClose(mountHandle);\n }\n\n public Closeable getValue() throws IllegalStateException, IllegalArgumentException {\n return mountHandle;\n }\n };\n ServiceBuilder<Closeable> builder = serviceTarget.addService(ServiceName.JBOSS.append(SEAM_INT_JAR),\n mountHandleService);\n builder.setInitialMode(ServiceController.Mode.ACTIVE).install();\n serviceTarget = null; // our cleanup service install work is done\n\n MountHandle dummy = MountHandle.create(null); // actual close is done by the MSC service above\n seamIntResourceRoot = new ResourceRoot(vf, dummy);\n }\n return seamIntResourceRoot;\n } catch (Exception e) {\n throw new DeploymentUnitProcessingException(e);\n }\n }", "public String generateSignature(HashMap<String, Integer> defined, GVRLight[] lightlist)\n {\n return getClass().getSimpleName();\n }", "@UiHandler(\"m_wholeDayCheckBox\")\n void onWholeDayChange(ValueChangeEvent<Boolean> event) {\n\n //TODO: Improve - adjust time selections?\n if (handleChange()) {\n m_controller.setWholeDay(event.getValue());\n }\n }", "public boolean putAtomic(C instance, K key, V value, Map<K, V> snapshot) {\n Assert.checkNotNullParam(\"key\", key);\n final Map<K, V> newMap;\n final int oldSize = snapshot.size();\n if (oldSize == 0) {\n newMap = Collections.singletonMap(key, value);\n } else if (oldSize == 1) {\n final Map.Entry<K, V> entry = snapshot.entrySet().iterator().next();\n final K oldKey = entry.getKey();\n if (oldKey.equals(key)) {\n return false;\n } else {\n newMap = new FastCopyHashMap<K, V>(snapshot);\n newMap.put(key, value);\n }\n } else {\n newMap = new FastCopyHashMap<K, V>(snapshot);\n newMap.put(key, value);\n }\n return updater.compareAndSet(instance, snapshot, newMap);\n }", "public static base_responses unlink(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 unlinkresources[] = new sslcertkey[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tunlinkresources[i] = new sslcertkey();\n\t\t\t\tunlinkresources[i].certkey = resources[i].certkey;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, unlinkresources,\"unlink\");\n\t\t}\n\t\treturn result;\n\t}", "public static <E extends Style.HasCssName, F extends Enum<? extends Style.HasCssName>> void addUniqueEnumStyleName(final UIObject uiObject,\n final Class<F> enumClass,\n final E style) {\n removeEnumStyleNames(uiObject, enumClass);\n addEnumStyleName(uiObject, style);\n }", "public void fireResourceWrittenEvent(Resource resource)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.resourceWritten(resource);\n }\n }\n }", "private PersistenceBroker obtainBroker()\r\n {\r\n PersistenceBroker _broker;\r\n try\r\n {\r\n if (pbKey == null)\r\n {\r\n //throw new OJBRuntimeException(\"Not possible to do action, cause no tx runnning and no PBKey is set\");\r\n log.warn(\"No tx runnning and PBKey is null, try to use the default PB\");\r\n _broker = PersistenceBrokerFactory.defaultPersistenceBroker();\r\n }\r\n else\r\n {\r\n _broker = PersistenceBrokerFactory.createPersistenceBroker(pbKey);\r\n }\r\n }\r\n catch (PBFactoryException e)\r\n {\r\n log.error(\"Could not obtain PB for PBKey \" + pbKey, e);\r\n throw new OJBRuntimeException(\"Unexpected micro-kernel exception\", e);\r\n }\r\n return _broker;\r\n }" ]
SuppressWarnings I really want to return HazeltaskTasks instead of Runnable
[ "@SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n public List<HazeltaskTask<G>> shutdownNow() {\n\t return (List<HazeltaskTask<G>>) (List) localExecutorPool.shutdownNow();\n\t}" ]
[ "public static void checkFloatNotNaNOrInfinity(String parameterName,\n float data) {\n if (Float.isNaN(data) || Float.isInfinite(data)) {\n throw Exceptions.IllegalArgument(\n \"%s should never be NaN or Infinite.\", parameterName);\n }\n }", "private static Point getScreenSize(Context context, Point p) {\n if (p == null) {\n p = new Point();\n }\n WindowManager windowManager = (WindowManager) context\n .getSystemService(Context.WINDOW_SERVICE);\n Display display = windowManager.getDefaultDisplay();\n display.getSize(p);\n return p;\n }", "public static TestSuiteResult unmarshal(File testSuite) throws IOException {\n try (InputStream stream = new FileInputStream(testSuite)) {\n return unmarshal(stream);\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 }", "public static appfwjsoncontenttype[] get(nitro_service service, options option) throws Exception{\n\t\tappfwjsoncontenttype obj = new appfwjsoncontenttype();\n\t\tappfwjsoncontenttype[] response = (appfwjsoncontenttype[])obj.get_resources(service,option);\n\t\treturn response;\n\t}", "private void appendDefaultValue(StringBuilder sb, FieldType fieldType, Object defaultValue) {\n\t\tif (fieldType.isEscapedDefaultValue()) {\n\t\t\tappendEscapedWord(sb, defaultValue.toString());\n\t\t} else {\n\t\t\tsb.append(defaultValue);\n\t\t}\n\t}", "public String getRecordSchema() throws IOException {\n Schema schema = getInputPathAvroSchema();\n String recSchema = schema.toString();\n return recSchema;\n }", "public void addChannel(String boneName, GVRAnimationChannel channel)\n {\n int boneId = mSkeleton.getBoneIndex(boneName);\n if (boneId >= 0)\n {\n mBoneChannels[boneId] = channel;\n mSkeleton.setBoneOptions(boneId, GVRSkeleton.BONE_ANIMATE);\n Log.d(\"BONE\", \"Adding animation channel %d %s \", boneId, boneName);\n }\n }", "GVRShader makeTemplate(Class<? extends GVRShader> id, GVRContext ctx)\n {\n try\n {\n Constructor<? extends GVRShader> maker = id.getDeclaredConstructor(GVRContext.class);\n return maker.newInstance(ctx);\n }\n catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex)\n {\n try\n {\n Constructor<? extends GVRShader> maker = id.getDeclaredConstructor();\n return maker.newInstance();\n }\n catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex2)\n {\n ctx.getEventManager().sendEvent(ctx, IErrorEvents.class, \"onError\", new Object[] {ex2.getMessage(), this});\n return null;\n }\n }\n }" ]
Find the logging profile attached to any resource. @param resourceRoot the root resource @return the logging profile name or {@code null} if one was not found
[ "private String findLoggingProfile(final ResourceRoot resourceRoot) {\n final Manifest manifest = resourceRoot.getAttachment(Attachments.MANIFEST);\n if (manifest != null) {\n final String loggingProfile = manifest.getMainAttributes().getValue(LOGGING_PROFILE);\n if (loggingProfile != null) {\n LoggingLogger.ROOT_LOGGER.debugf(\"Logging profile '%s' found in '%s'.\", loggingProfile, resourceRoot);\n return loggingProfile;\n }\n }\n return null;\n }" ]
[ "public void edit(Note note) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT);\r\n\r\n parameters.put(\"note_id\", note.getId());\r\n Rectangle bounds = note.getBounds();\r\n if (bounds != null) {\r\n parameters.put(\"note_x\", String.valueOf(bounds.x));\r\n parameters.put(\"note_y\", String.valueOf(bounds.y));\r\n parameters.put(\"note_w\", String.valueOf(bounds.width));\r\n parameters.put(\"note_h\", String.valueOf(bounds.height));\r\n }\r\n String text = note.getText();\r\n if (text != null) {\r\n parameters.put(\"note_text\", text);\r\n }\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }", "private static void listTaskNotes(ProjectFile file)\n {\n for (Task task : file.getTasks())\n {\n String notes = task.getNotes();\n\n if (notes.length() != 0)\n {\n System.out.println(\"Notes for \" + task.getName() + \": \" + notes);\n }\n }\n\n System.out.println();\n }", "public void reset() {\n state = BreakerState.CLOSED;\n isHardTrip = false;\n byPass = false;\n isAttemptLive = false;\n\n notifyBreakerStateChange(getStatus());\n }", "public T withAlias(String text, String languageCode) {\n\t\twithAlias(factory.getMonolingualTextValue(text, languageCode));\n\t\treturn getThis();\n\t}", "private static String loadUA(ClassLoader loader, String filename){\n String ua = \"cloudant-http\";\n String version = \"unknown\";\n final InputStream propStream = loader.getResourceAsStream(filename);\n final Properties properties = new Properties();\n try {\n if (propStream != null) {\n try {\n properties.load(propStream);\n } finally {\n propStream.close();\n }\n }\n ua = properties.getProperty(\"user.agent.name\", ua);\n version = properties.getProperty(\"user.agent.version\", version);\n } catch (IOException e) {\n // Swallow exception and use default values.\n }\n\n return String.format(Locale.ENGLISH, \"%s/%s\", ua,version);\n }", "private void readProjectProperties(Project project) throws MPXJException\n {\n ProjectProperties properties = m_projectFile.getProjectProperties();\n\n properties.setCompany(project.getCompany());\n properties.setManager(project.getManager());\n properties.setName(project.getName());\n properties.setStartDate(getDateTime(project.getProjectStart()));\n }", "@SuppressWarnings(\"deprecation\")\n @RequestMapping(value = \"/api/backup\", method = RequestMethod.GET)\n public\n @ResponseBody\n String getBackup(Model model, HttpServletResponse response) throws Exception {\n response.addHeader(\"Content-Disposition\", \"attachment; filename=backup.json\");\n response.setContentType(\"application/json\");\n\n Backup backup = BackupService.getInstance().getBackupData();\n ObjectMapper objectMapper = new ObjectMapper();\n ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter();\n\n return writer.withView(ViewFilters.Default.class).writeValueAsString(backup);\n }", "public String astring(ImapRequestLineReader request) throws ProtocolException {\n char next = request.nextWordChar();\n switch (next) {\n case '\"':\n return consumeQuoted(request);\n case '{':\n return consumeLiteral(request);\n default:\n return atom(request);\n }\n }", "public JsonNode wbSetLabel(String id, String site, String title,\n\t\t\tString newEntity, String language, String value,\n\t\t\tboolean bot, long baserevid, String summary)\n\t\t\t\t\tthrows IOException, MediaWikiApiErrorException {\n\t\tValidate.notNull(language,\n\t\t\t\t\"Language parameter cannot be null when setting a label\");\n\t\t\n\t\tMap<String, String> parameters = new HashMap<String, String>();\n\t\tparameters.put(\"language\", language);\n\t\tif (value != null) {\n\t\t\tparameters.put(\"value\", value);\n\t\t}\n\t\t\n\t\tJsonNode response = performAPIAction(\"wbsetlabel\", id, site, title, newEntity,\n\t\t\t\tparameters, summary, baserevid, bot);\n\t\treturn response;\n\t}" ]
This method changes package_path into folder's path @param path , as es.upm.gsi @return the new path, es/upm/gsi
[ "public static String createFolderPath(String path) {\n\n String[] pathParts = path.split(\"\\\\.\");\n String path2 = \"\";\n for (String part : pathParts) {\n if (path2.equals(\"\")) {\n path2 = part;\n } else {\n path2 = path2 + File.separator\n + changeFirstLetterToLowerCase(createClassName(part));\n }\n }\n\n return path2;\n }" ]
[ "private boolean isDepOfIdlArtifact(Artifact artifact, Map<String, Artifact> depsMap) {\n List<String> depTrail = artifact.getDependencyTrail();\n // depTrail can be null sometimes, which seems like a maven bug\n if (depTrail != null) {\n for (String name : depTrail) {\n Artifact dep = depsMap.get(name);\n if (dep != null && isIdlCalssifier(dep, classifier)) {\n return true;\n }\n }\n }\n return false;\n }", "@SuppressWarnings(\"unchecked\")\n protected String addPostRunDependent(Creatable<? extends Indexable> creatable) {\n TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) creatable;\n return this.addPostRunDependent(dependency);\n }", "private static String resolveJavaCommand(final Path javaHome) {\n final String exe;\n if (javaHome == null) {\n exe = \"java\";\n } else {\n exe = javaHome.resolve(\"bin\").resolve(\"java\").toString();\n }\n if (exe.contains(\" \")) {\n return \"\\\"\" + exe + \"\\\"\";\n }\n return exe;\n }", "public void sendToTagged(String message, String ... labels) {\n for (String label : labels) {\n sendToTagged(message, label);\n }\n }", "@Override\n public TagsInterface getTagsInterface() {\n if (tagsInterface == null) {\n tagsInterface = new TagsInterface(apiKey, sharedSecret, transport);\n }\n return tagsInterface;\n }", "public void enable(ConduitSelectorHolder conduitSelectorHolder, SLPropertiesMatcher matcher,\n String selectionStrategy) {\n LocatorTargetSelector selector = new LocatorTargetSelector();\n selector.setEndpoint(conduitSelectorHolder.getConduitSelector().getEndpoint());\n\n String actualStrategy = selectionStrategy != null ? selectionStrategy : defaultLocatorSelectionStrategy;\n \n LocatorSelectionStrategy locatorSelectionStrategy = getLocatorSelectionStrategy(actualStrategy);\n locatorSelectionStrategy.setServiceLocator(locatorClient);\n if (matcher != null) {\n locatorSelectionStrategy.setMatcher(matcher);\n }\n selector.setLocatorSelectionStrategy(locatorSelectionStrategy);\n\n if (LOG.isLoggable(Level.INFO)) {\n LOG.log(Level.INFO, \"Client enabled with strategy \"\n + locatorSelectionStrategy.getClass().getName() + \".\");\n }\n conduitSelectorHolder.setConduitSelector(selector);\n\n if (LOG.isLoggable(Level.FINE)) {\n LOG.log(Level.FINE, \"Successfully enabled client \" + conduitSelectorHolder\n + \" for the service locator\");\n }\n }", "public static final Integer getInteger(String value)\n {\n Integer result;\n\n try\n {\n result = Integer.valueOf(Integer.parseInt(value));\n }\n\n catch (Exception ex)\n {\n result = null;\n }\n\n return (result);\n }", "private void printSuggestion( String arg, List<ConfigOption> co ) {\n List<ConfigOption> sortedList = new ArrayList<ConfigOption>( co );\n Collections.sort( sortedList, new ConfigOptionLevenshteinDistance( arg ) );\n System.err.println( \"Parse error for argument \\\"\" + arg + \"\\\", did you mean \" + sortedList.get( 0 ).getCommandLineOption()\n .showFlagInfo() + \"? Ignoring for now.\" );\n\n }", "public BlurBuilder contrast(float contrast) {\n data.preProcessors.add(new ContrastProcessor(data.contextWrapper.getRenderScript(), Math.max(Math.min(1500.f, contrast), -1500.f)));\n return this;\n }" ]
Invoke the setters for the given variables on the given instance. @param <T> the instance type @param instance the instance to inject with the variables @param vars the variables to inject @return the instance @throws ReflectiveOperationException if there was a problem finding or invoking a setter method
[ "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 static clusterinstance[] get(nitro_service service) throws Exception{\n\t\tclusterinstance obj = new clusterinstance();\n\t\tclusterinstance[] response = (clusterinstance[])obj.get_resources(service);\n\t\treturn response;\n\t}", "protected Element createRectangleElement(float x, float y, float width, float height, boolean stroke, boolean fill)\n {\n float lineWidth = transformWidth(getGraphicsState().getLineWidth());\n \tfloat wcor = stroke ? lineWidth : 0.0f;\n float strokeOffset = wcor == 0 ? 0 : wcor / 2;\n width = width - wcor < 0 ? 1 : width - wcor;\n height = height - wcor < 0 ? 1 : height - wcor;\n\n StringBuilder pstyle = new StringBuilder(50);\n \tpstyle.append(\"left:\").append(style.formatLength(x - strokeOffset)).append(';');\n pstyle.append(\"top:\").append(style.formatLength(y - strokeOffset)).append(';');\n pstyle.append(\"width:\").append(style.formatLength(width)).append(';');\n pstyle.append(\"height:\").append(style.formatLength(height)).append(';');\n \t \n \tif (stroke)\n \t{\n String color = colorString(getGraphicsState().getStrokingColor());\n \tpstyle.append(\"border:\").append(style.formatLength(lineWidth)).append(\" solid \").append(color).append(';');\n \t}\n \t\n \tif (fill)\n \t{\n String fcolor = colorString(getGraphicsState().getNonStrokingColor());\n \t pstyle.append(\"background-color:\").append(fcolor).append(';');\n \t}\n \t\n Element el = doc.createElement(\"div\");\n el.setAttribute(\"class\", \"r\");\n el.setAttribute(\"style\", pstyle.toString());\n el.appendChild(doc.createEntityReference(\"nbsp\"));\n return el;\n }", "public static Observable<byte[]> downloadFileAsync(String url, Retrofit retrofit) {\n FileService service = retrofit.create(FileService.class);\n Observable<ResponseBody> response = service.download(url);\n return response.map(new Func1<ResponseBody, byte[]>() {\n @Override\n public byte[] call(ResponseBody responseBody) {\n try {\n return responseBody.bytes();\n } catch (IOException e) {\n throw Exceptions.propagate(e);\n }\n }\n });\n }", "@Override\n public Response doRequest(final StitchRequest stitchReq) {\n initAppMetadata(clientAppId);\n\n return super.doRequestUrl(stitchReq, getHostname());\n }", "public void clearSources()\n {\n synchronized (mAudioSources)\n {\n for (GVRAudioSource source : mAudioSources)\n {\n source.setListener(null);\n }\n mAudioSources.clear();\n }\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 }", "public long findPosition(long nOccurrence) {\n\t\tupdateCount();\n\t\tif (nOccurrence <= 0) {\n\t\t\treturn RankedBitVector.NOT_FOUND;\n\t\t}\n\t\tint findPos = (int) (nOccurrence / this.blockSize);\n\t\tif (findPos < this.positionArray.length) {\n\t\t\tlong pos0 = this.positionArray[findPos];\n\t\t\tlong leftOccurrences = nOccurrence - (findPos * this.blockSize);\n\t\t\tif (leftOccurrences == 0) {\n\t\t\t\treturn pos0;\n\t\t\t}\n\t\t\tfor (long index = pos0 + 1; index < this.bitVector.size(); index++) {\n\t\t\t\tif (this.bitVector.getBit(index) == this.bit) {\n\t\t\t\t\tleftOccurrences--;\n\t\t\t\t}\n\t\t\t\tif (leftOccurrences == 0) {\n\t\t\t\t\treturn index;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn RankedBitVector.NOT_FOUND;\n\t}", "public 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}", "private long size(final Jedis jedis, final String queueName) {\n final String key = key(QUEUE, queueName);\n final long size;\n if (JedisUtils.isDelayedQueue(jedis, key)) { // If delayed queue, use ZCARD\n size = jedis.zcard(key);\n } else { // Else, use LLEN\n size = jedis.llen(key);\n }\n return size;\n }" ]
Helper method to create a string template source for a given formatter and content. @param formatter the formatter @param contentSupplier the content supplier @return the string template provider
[ "public static Function<String, String> createStringTemplateSource(\n I_CmsFormatterBean formatter,\n Supplier<CmsXmlContent> contentSupplier) {\n\n return key -> {\n String result = null;\n if (formatter != null) {\n result = formatter.getAttributes().get(key);\n }\n if (result == null) {\n CmsXmlContent content = contentSupplier.get();\n if (content != null) {\n result = content.getHandler().getParameter(key);\n }\n }\n return result;\n };\n }" ]
[ "public void rename(String newName) {\n URL url = FILE_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"PUT\");\n\n JsonObject updateInfo = new JsonObject();\n updateInfo.add(\"name\", newName);\n\n request.setBody(updateInfo.toString());\n BoxAPIResponse response = request.send();\n response.disconnect();\n }", "public static systemcore get(nitro_service service) throws Exception{\n\t\tsystemcore obj = new systemcore();\n\t\tsystemcore[] response = (systemcore[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "void checkRmModelConformance() {\n final AmVisitor<AmObject, AmConstraintContext> visitor = AmVisitors.preorder(new ConformanceVisitor());\n ArchetypeWalker.walkConstraints(visitor, archetype, new AmConstraintContext());\n }", "public static String blur(int radius, int sigma) {\n if (radius < 1) {\n throw new IllegalArgumentException(\"Radius must be greater than zero.\");\n }\n if (radius > 150) {\n throw new IllegalArgumentException(\"Radius must be lower or equal than 150.\");\n }\n if (sigma < 0) {\n throw new IllegalArgumentException(\"Sigma must be greater than zero.\");\n }\n return FILTER_BLUR + \"(\" + radius + \",\" + sigma + \")\";\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 static void main(String[] args) {\n CmdLine cmd = new CmdLine();\n Configuration conf = new Configuration();\n int res = 0;\n try {\n res = ToolRunner.run(conf, cmd, args);\n } catch (Exception e) {\n System.err.println(\"Error while running MR job\");\n e.printStackTrace();\n }\n System.exit(res);\n }", "protected JRDesignGroup getParent(JRDesignGroup group) {\n int index = realGroups.indexOf(group);\n return (index > 0) ? (JRDesignGroup) realGroups.get(index - 1) : group;\n }", "private void processOutlineCodeFields(Row parentRow) throws SQLException\n {\n Integer entityID = parentRow.getInteger(\"CODE_REF_UID\");\n Integer outlineCodeEntityID = parentRow.getInteger(\"CODE_UID\");\n\n for (ResultSetRow row : getRows(\"SELECT * FROM MSP_OUTLINE_CODES WHERE CODE_UID=?\", outlineCodeEntityID))\n {\n processOutlineCodeField(entityID, row);\n }\n }", "public static StringBuilder leftShift(StringBuilder self, Object value) {\n self.append(value);\n return self;\n }" ]
Returns true if the string matches the name of a function
[ "public boolean isFunctionName( String s ) {\n if( input1.containsKey(s))\n return true;\n if( inputN.containsKey(s))\n return true;\n\n return false;\n }" ]
[ "public static aaagroup_vpntrafficpolicy_binding[] get(nitro_service service, String groupname) throws Exception{\n\t\taaagroup_vpntrafficpolicy_binding obj = new aaagroup_vpntrafficpolicy_binding();\n\t\tobj.set_groupname(groupname);\n\t\taaagroup_vpntrafficpolicy_binding response[] = (aaagroup_vpntrafficpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private void deliverDatabaseUpdate(SlotReference slot, Database database, boolean available) {\n for (final DatabaseListener listener : getDatabaseListeners()) {\n try {\n if (available) {\n listener.databaseMounted(slot, database);\n } else {\n listener.databaseUnmounted(slot, database);\n }\n } catch (Throwable t) {\n logger.warn(\"Problem delivering rekordbox database availability update to listener\", t);\n }\n }\n }", "public static boolean isPackageOrClassName(String s) {\n if (S.blank(s)) {\n return false;\n }\n S.List parts = S.fastSplit(s, \".\");\n if (parts.size() < 2) {\n return false;\n }\n for (String part: parts) {\n if (!Character.isJavaIdentifierStart(part.charAt(0))) {\n return false;\n }\n for (int i = 1, len = part.length(); i < len; ++i) {\n if (!Character.isJavaIdentifierPart(part.charAt(i))) {\n return false;\n }\n }\n }\n return true;\n }", "public String getString(int field)\n {\n String result;\n\n if (field < m_fields.length)\n {\n result = m_fields[field];\n\n if (result != null)\n {\n result = result.replace(MPXConstants.EOL_PLACEHOLDER, '\\n');\n }\n }\n else\n {\n result = null;\n }\n\n return (result);\n }", "private FieldType addUserDefinedField(FieldTypeClass fieldType, UserFieldDataType dataType, String name)\n {\n FieldType field = null;\n \n try\n {\n switch (fieldType)\n {\n case TASK:\n {\n do\n {\n field = m_taskUdfCounters.nextField(TaskField.class, dataType);\n }\n while (RESERVED_TASK_FIELDS.contains(field));\n\n m_projectFile.getCustomFields().getCustomField(field).setAlias(name);\n\n break;\n }\n \n case RESOURCE:\n {\n field = m_resourceUdfCounters.nextField(ResourceField.class, dataType);\n m_projectFile.getCustomFields().getCustomField(field).setAlias(name);\n break;\n }\n \n case ASSIGNMENT:\n {\n field = m_assignmentUdfCounters.nextField(AssignmentField.class, dataType);\n m_projectFile.getCustomFields().getCustomField(field).setAlias(name);\n break;\n }\n \n default:\n {\n break;\n }\n } \n }\n\n catch (Exception ex)\n {\n //\n // SF#227: If we get an exception thrown here... it's likely that\n // we've run out of user defined fields, for example\n // there are only 30 TEXT fields. We'll ignore this: the user\n // defined field won't be mapped to an alias, so we'll\n // ignore it when we read in the values.\n //\n }\n \n return field;\n }", "public static base_response update(nitro_service client, dospolicy resource) throws Exception {\n\t\tdospolicy updateresource = new dospolicy();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.qdepth = resource.qdepth;\n\t\tupdateresource.cltdetectrate = resource.cltdetectrate;\n\t\treturn updateresource.update_resource(client);\n\t}", "public static String printUUID(UUID guid)\n {\n return guid == null ? null : \"{\" + guid.toString().toUpperCase() + \"}\";\n }", "public ItemRequest<Project> addMembers(String project) {\n \n String path = String.format(\"/projects/%s/addMembers\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\n }", "public static String readCorrelationId(Message message) {\n String correlationId = null;\n Map<String, List<String>> headers = getOrCreateProtocolHeader(message);\n List<String> correlationIds = headers.get(CORRELATION_ID_KEY);\n if (correlationIds != null && correlationIds.size() > 0) {\n correlationId = correlationIds.get(0);\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"HTTP header '\" + CORRELATION_ID_KEY + \"' found: \" + correlationId);\n }\n } else {\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"No HTTP header '\" + CORRELATION_ID_KEY + \"' found\");\n }\n }\n\n return correlationId;\n }" ]
The transaction will be executed. While it is running, any semantic state change in the given resource will be ignored and the cache will not be cleared.
[ "public <Result, Param extends Resource> Result execWithoutCacheClear(Param resource, IUnitOfWork<Result, Param> transaction) throws WrappedException {\n\t\tCacheAdapter cacheAdapter = getOrCreate(resource);\n\t\ttry {\n\t\t\tcacheAdapter.ignoreNotifications();\n\t\t\treturn transaction.exec(resource);\n\t\t} catch (RuntimeException e) {\n\t\t\tthrow e;\n\t\t} catch (Exception e) {\n\t\t\tthrow new WrappedException(e);\n\t\t} finally {\n\t\t\tcacheAdapter.listenToNotifications();\n\t\t}\n\t}" ]
[ "public void populateFromAttributes(\n @Nonnull final Template template,\n @Nonnull final Map<String, Attribute> attributes,\n @Nonnull final PObject requestJsonAttributes) {\n if (requestJsonAttributes.has(JSON_REQUEST_HEADERS) &&\n requestJsonAttributes.getObject(JSON_REQUEST_HEADERS).has(JSON_REQUEST_HEADERS) &&\n !attributes.containsKey(JSON_REQUEST_HEADERS)) {\n attributes.put(JSON_REQUEST_HEADERS, new HttpRequestHeadersAttribute());\n }\n for (Map.Entry<String, Attribute> attribute: attributes.entrySet()) {\n try {\n put(attribute.getKey(),\n attribute.getValue().getValue(template, attribute.getKey(), requestJsonAttributes));\n } catch (ObjectMissingException | IllegalArgumentException e) {\n throw e;\n } catch (Throwable e) {\n String templateName = \"unknown\";\n for (Map.Entry<String, Template> entry: template.getConfiguration().getTemplates()\n .entrySet()) {\n if (entry.getValue() == template) {\n templateName = entry.getKey();\n break;\n }\n }\n\n String defaults = \"\";\n\n if (attribute instanceof ReflectiveAttribute<?>) {\n ReflectiveAttribute<?> reflectiveAttribute = (ReflectiveAttribute<?>) attribute;\n defaults = \"\\n\\n The attribute defaults are: \" + reflectiveAttribute.getDefaultValue();\n }\n\n String errorMsg = \"An error occurred when creating a value from the '\" + attribute.getKey() +\n \"' attribute for the '\" +\n templateName + \"' template.\\n\\nThe JSON is: \\n\" + requestJsonAttributes + defaults +\n \"\\n\" +\n e.toString();\n\n throw new AttributeParsingException(errorMsg, e);\n }\n }\n\n if (template.getConfiguration().isThrowErrorOnExtraParameters()) {\n final List<String> extraProperties = new ArrayList<>();\n for (Iterator<String> it = requestJsonAttributes.keys(); it.hasNext(); ) {\n final String attributeName = it.next();\n if (!attributes.containsKey(attributeName)) {\n extraProperties.add(attributeName);\n }\n }\n\n if (!extraProperties.isEmpty()) {\n throw new ExtraPropertyException(\"Extra properties found in the request attributes\",\n extraProperties, attributes.keySet());\n }\n }\n }", "public void forAllForeignkeys(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _curTableDef.getForeignkeys(); it.hasNext(); )\r\n {\r\n _curForeignkeyDef = (ForeignkeyDef)it.next();\r\n generate(template);\r\n }\r\n _curForeignkeyDef = null;\r\n }", "public PhotoList<Photo> getPublicPhotos(String userId, Set<String> extras, int perPage, int page) throws FlickrException {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PUBLIC_PHOTOS);\r\n\r\n parameters.put(\"user_id\", userId);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n\r\n if (extras != null) {\r\n parameters.put(Extras.KEY_EXTRAS, StringUtilities.join(extras, \",\"));\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n photos.setPage(photosElement.getAttribute(\"page\"));\r\n photos.setPages(photosElement.getAttribute(\"pages\"));\r\n photos.setPerPage(photosElement.getAttribute(\"perpage\"));\r\n photos.setTotal(photosElement.getAttribute(\"total\"));\r\n\r\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element photoElement = (Element) photoNodes.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement));\r\n }\r\n return photos;\r\n }", "public void drawText(String text, Font font, Rectangle box, Color fontColor) {\n\t\ttemplate.saveState();\n\t\t// get the font\n\t\tDefaultFontMapper mapper = new DefaultFontMapper();\n\t\tBaseFont bf = mapper.awtToPdf(font);\n\t\ttemplate.setFontAndSize(bf, font.getSize());\n\n\t\t// calculate descent\n\t\tfloat descent = 0;\n\t\tif (text != null) {\n\t\t\tdescent = bf.getDescentPoint(text, font.getSize());\n\t\t}\n\n\t\t// calculate the fitting size\n\t\tRectangle fit = getTextSize(text, font);\n\n\t\t// draw text if necessary\n\t\ttemplate.setColorFill(fontColor);\n\t\ttemplate.beginText();\n\t\ttemplate.showTextAligned(PdfContentByte.ALIGN_LEFT, text, origX + box.getLeft() + 0.5f\n\t\t\t\t* (box.getWidth() - fit.getWidth()), origY + box.getBottom() + 0.5f\n\t\t\t\t* (box.getHeight() - fit.getHeight()) - descent, 0);\n\t\ttemplate.endText();\n\t\ttemplate.restoreState();\n\t}", "protected static PatchElement createRollbackElement(final PatchEntry entry) {\n final PatchElement patchElement = entry.element;\n final String patchId;\n final Patch.PatchType patchType = patchElement.getProvider().getPatchType();\n if (patchType == Patch.PatchType.CUMULATIVE) {\n patchId = entry.getCumulativePatchID();\n } else {\n patchId = patchElement.getId();\n }\n return createPatchElement(entry, patchId, entry.rollbackActions);\n }", "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 }", "@Nonnull\n public static Builder builder(Revapi revapi) {\n List<String> knownExtensionIds = new ArrayList<>();\n\n addExtensionIds(revapi.getPipelineConfiguration().getApiAnalyzerTypes(), knownExtensionIds);\n addExtensionIds(revapi.getPipelineConfiguration().getTransformTypes(), knownExtensionIds);\n addExtensionIds(revapi.getPipelineConfiguration().getFilterTypes(), knownExtensionIds);\n addExtensionIds(revapi.getPipelineConfiguration().getReporterTypes(), knownExtensionIds);\n\n return new Builder(knownExtensionIds);\n }", "public void setPickingEnabled(boolean enabled) {\n if (enabled != getPickingEnabled()) {\n if (enabled) {\n attachComponent(new GVRSphereCollider(getGVRContext()));\n } else {\n detachComponent(GVRCollider.getComponentType());\n }\n }\n }", "int acquireTransaction(@NotNull final Thread thread) {\n try (CriticalSection ignored = criticalSection.enter()) {\n final int currentThreadPermits = getThreadPermitsToAcquire(thread);\n waitForPermits(thread, currentThreadPermits > 0 ? nestedQueue : regularQueue, 1, currentThreadPermits);\n }\n return 1;\n }" ]
Use this API to fetch the statistics of all tunnelip_stats resources that are configured on netscaler.
[ "public static tunnelip_stats[] get(nitro_service service) throws Exception{\n\t\ttunnelip_stats obj = new tunnelip_stats();\n\t\ttunnelip_stats[] response = (tunnelip_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}" ]
[ "public static String printUUID(UUID guid)\n {\n return guid == null ? null : \"{\" + guid.toString().toUpperCase() + \"}\";\n }", "public void validateOperations(final List<ModelNode> operations) {\n if (operations == null) {\n return;\n }\n\n for (ModelNode operation : operations) {\n try {\n validateOperation(operation);\n } catch (RuntimeException e) {\n if (exitOnError) {\n throw e;\n } else {\n System.out.println(\"---- Operation validation error:\");\n System.out.println(e.getMessage());\n }\n\n }\n }\n }", "public static List<DomainControllerData> domainControllerDataFromByteBuffer(byte[] buffer) throws Exception {\n List<DomainControllerData> retval = new ArrayList<DomainControllerData>();\n if (buffer == null) {\n return retval;\n }\n ByteArrayInputStream in_stream = new ByteArrayInputStream(buffer);\n DataInputStream in = new DataInputStream(in_stream);\n String content = SEPARATOR;\n while (SEPARATOR.equals(content)) {\n DomainControllerData data = new DomainControllerData();\n data.readFrom(in);\n retval.add(data);\n try {\n content = readString(in);\n } catch (EOFException ex) {\n content = null;\n }\n }\n in.close();\n return retval;\n }", "public void append(String str, String indentation) {\n\t\tif (indentation.isEmpty()) {\n\t\t\tappend(str);\n\t\t} else if (str != null)\n\t\t\tappend(indentation, str, segments.size());\n\t}", "public void setMat4(String key, 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 {\n checkKeyIsUniform(key);\n NativeLight.setMat4(getNative(), key, x1, y1, z1, w1, x2, y2,\n z2, w2, x3, y3, z3, w3, x4, y4, z4, w4);\n }", "public IPv4AddressSection getEmbeddedIPv4AddressSection(int startIndex, int endIndex) {\n\t\tif(startIndex == ((IPv6Address.MIXED_ORIGINAL_SEGMENT_COUNT - this.addressSegmentIndex) << 1) && endIndex == (getSegmentCount() << 1)) {\n\t\t\treturn getEmbeddedIPv4AddressSection();\n\t\t}\n\t\tIPv4AddressCreator creator = getIPv4Network().getAddressCreator();\n\t\tIPv4AddressSegment[] segments = creator.createSegmentArray((endIndex - startIndex) >> 1);\n\t\tint i = startIndex, j = 0;\n\t\tif(i % IPv6Address.BYTES_PER_SEGMENT == 1) {\n\t\t\tIPv6AddressSegment ipv6Segment = getSegment(i >> 1);\n\t\t\ti++;\n\t\t\tipv6Segment.getSplitSegments(segments, j - 1, creator);\n\t\t\tj++;\n\t\t}\n\t\tfor(; i < endIndex; i <<= 1, j <<= 1) {\n\t\t\tIPv6AddressSegment ipv6Segment = getSegment(i >> 1);\n\t\t\tipv6Segment.getSplitSegments(segments, j, creator);\n\t\t}\n\t\treturn createEmbeddedSection(creator, segments, this);\n\t}", "GVRSceneObject makeParticleMesh(float[] vertices, float[] velocities,\n float[] particleTimeStamps )\n {\n mParticleMesh = new GVRMesh(mGVRContext);\n\n //pass the particle positions as vertices, velocities as normals, and\n //spawning times as texture coordinates.\n mParticleMesh.setVertices(vertices);\n mParticleMesh.setNormals(velocities);\n mParticleMesh.setTexCoords(particleTimeStamps);\n\n particleID = new GVRShaderId(ParticleShader.class);\n material = new GVRMaterial(mGVRContext, particleID);\n\n material.setVec4(\"u_color\", mColorMultiplier.x, mColorMultiplier.y,\n mColorMultiplier.z, mColorMultiplier.w);\n material.setFloat(\"u_particle_age\", mAge);\n material.setVec3(\"u_acceleration\", mAcceleration.x, mAcceleration.y, mAcceleration.z);\n material.setFloat(\"u_particle_size\", mSize);\n material.setFloat(\"u_size_change_rate\", mParticleSizeRate);\n material.setFloat(\"u_fade\", mFadeWithAge);\n material.setFloat(\"u_noise_factor\", mNoiseFactor);\n\n GVRRenderData renderData = new GVRRenderData(mGVRContext);\n renderData.setMaterial(material);\n renderData.setMesh(mParticleMesh);\n material.setMainTexture(mTexture);\n\n GVRSceneObject meshObject = new GVRSceneObject(mGVRContext);\n meshObject.attachRenderData(renderData);\n meshObject.getRenderData().setMaterial(material);\n\n // Set the draw mode to GL_POINTS, disable writing to depth buffer, enable depth testing\n // and set the rendering order to transparent.\n // Disabling writing to depth buffer ensure that the particles blend correctly\n // and keeping the depth test on along with rendering them\n // after the geometry queue makes sure they occlude, and are occluded, correctly.\n\n meshObject.getRenderData().setDrawMode(GL_POINTS);\n meshObject.getRenderData().setDepthTest(true);\n meshObject.getRenderData().setDepthMask(false);\n meshObject.getRenderData().setRenderingOrder(GVRRenderData.GVRRenderingOrder.TRANSPARENT);\n\n return meshObject;\n }", "public List<String> uuids(long count) {\n final URI uri = new URIBase(clientUri).path(\"_uuids\").query(\"count\", count).build();\n final JsonObject json = get(uri, JsonObject.class);\n return getGson().fromJson(json.get(\"uuids\").toString(), DeserializationTypes.STRINGS);\n }", "protected float getViewPortSize(final Axis axis) {\n float size = mViewPort == null ? 0 : mViewPort.get(axis);\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"getViewPortSize for %s %f mViewPort = %s\", axis, size, mViewPort);\n return size;\n }" ]
Return the profileId for a path @param path_id ID of path @return ID of profile @throws Exception exception
[ "public static int getProfileIdFromPathID(int path_id) throws Exception {\n return (Integer) SQLService.getInstance().getFromTable(Constants.GENERIC_PROFILE_ID, Constants.GENERIC_ID, path_id, Constants.DB_TABLE_PATH);\n }" ]
[ "public static route6[] get(nitro_service service, route6_args args) throws Exception{\n\t\troute6 obj = new route6();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\troute6[] response = (route6[])obj.get_resources(service, option);\n\t\treturn response;\n\t}", "public void removeWorstFit() {\n // find the observation with the most error\n int worstIndex=-1;\n double worstError = -1;\n\n for( int i = 0; i < y.numRows; i++ ) {\n double predictedObs = 0;\n\n for( int j = 0; j < coef.numRows; j++ ) {\n predictedObs += A.get(i,j)*coef.get(j,0);\n }\n\n double error = Math.abs(predictedObs- y.get(i,0));\n\n if( error > worstError ) {\n worstError = error;\n worstIndex = i;\n }\n }\n\n // nothing left to remove, so just return\n if( worstIndex == -1 )\n return;\n\n // remove that observation\n removeObservation(worstIndex);\n\n // update A\n solver.removeRowFromA(worstIndex);\n\n // solve for the parameters again\n solver.solve(y,coef);\n }", "protected void generateTitleBand() {\n\t\tlog.debug(\"Generating title band...\");\n\t\tJRDesignBand band = (JRDesignBand) getDesign().getPageHeader();\n\t\tint yOffset = 0;\n\n\t\t//If title is not present then subtitle will be ignored\n\t\tif (getReport().getTitle() == null)\n\t\t\treturn;\n\n\t\tif (band != null && !getDesign().isTitleNewPage()){\n\t\t\t//Title and subtitle comes afer the page header\n\t\t\tyOffset = band.getHeight();\n\n\t\t} else {\n\t\t\tband = (JRDesignBand) getDesign().getTitle();\n\t\t\tif (band == null){\n\t\t\t\tband = new JRDesignBand();\n\t\t\t\tgetDesign().setTitle(band);\n\t\t\t}\n\t\t}\n\n\t\tJRDesignExpression printWhenExpression = new JRDesignExpression();\n\t\tprintWhenExpression.setValueClass(Boolean.class);\n\t\tprintWhenExpression.setText(EXPRESSION_TRUE_WHEN_FIRST_PAGE);\n\n\t\tJRDesignTextField title = new JRDesignTextField();\n\t\tJRDesignExpression exp = new JRDesignExpression();\n\t\tif (getReport().isTitleIsJrExpression()){\n\t\t\texp.setText(getReport().getTitle());\n\t\t}else {\n\t\t\texp.setText(\"\\\"\" + Utils.escapeTextForExpression( getReport().getTitle()) + \"\\\"\");\n\t\t}\n\t\texp.setValueClass(String.class);\n\t\ttitle.setExpression(exp);\n\t\ttitle.setWidth(getReport().getOptions().getPrintableWidth());\n\t\ttitle.setHeight(getReport().getOptions().getTitleHeight());\n\t\ttitle.setY(yOffset);\n\t\ttitle.setPrintWhenExpression(printWhenExpression);\n\t\ttitle.setRemoveLineWhenBlank(true);\n\t\tapplyStyleToElement(getReport().getTitleStyle(), title);\n\t\ttitle.setStretchType( StretchTypeEnum.NO_STRETCH );\n\t\tband.addElement(title);\n\n\t\tJRDesignTextField subtitle = new JRDesignTextField();\n\t\tif (getReport().getSubtitle() != null) {\n\t\t\tJRDesignExpression exp2 = new JRDesignExpression();\n\t\t\texp2.setText(\"\\\"\" + getReport().getSubtitle() + \"\\\"\");\n\t\t\texp2.setValueClass(String.class);\n\t\t\tsubtitle.setExpression(exp2);\n\t\t\tsubtitle.setWidth(getReport().getOptions().getPrintableWidth());\n\t\t\tsubtitle.setHeight(getReport().getOptions().getSubtitleHeight());\n\t\t\tsubtitle.setY(title.getY() + title.getHeight());\n\t\t\tsubtitle.setPrintWhenExpression(printWhenExpression);\n\t\t\tsubtitle.setRemoveLineWhenBlank(true);\n\t\t\tapplyStyleToElement(getReport().getSubtitleStyle(), subtitle);\n\t\t\ttitle.setStretchType( StretchTypeEnum.NO_STRETCH );\n\t\t\tband.addElement(subtitle);\n\t\t}\n\n\n\t}", "public static void log(final String templateName, final Template template, final Values values) {\n new ValuesLogger().doLog(templateName, template, values);\n }", "private void addAnnotationValues(ClassReference annotatedReference, AnnotationClassReference typeRef, Annotation node)\n {\n Map<String, AnnotationValue> annotationValueMap = new HashMap<>();\n if (node instanceof SingleMemberAnnotation)\n {\n SingleMemberAnnotation singleMemberAnnotation = (SingleMemberAnnotation) node;\n AnnotationValue value = getAnnotationValueForExpression(annotatedReference, singleMemberAnnotation.getValue());\n annotationValueMap.put(\"value\", value);\n }\n else if (node instanceof NormalAnnotation)\n {\n @SuppressWarnings(\"unchecked\")\n List<MemberValuePair> annotationValues = ((NormalAnnotation) node).values();\n for (MemberValuePair annotationValue : annotationValues)\n {\n String key = annotationValue.getName().toString();\n Expression expression = annotationValue.getValue();\n AnnotationValue value = getAnnotationValueForExpression(annotatedReference, expression);\n annotationValueMap.put(key, value);\n }\n }\n typeRef.setAnnotationValues(annotationValueMap);\n }", "public static String getAt(CharSequence self, Collection indices) {\n StringBuilder answer = new StringBuilder();\n for (Object value : indices) {\n if (value instanceof Range) {\n answer.append(getAt(self, (Range) value));\n } else if (value instanceof Collection) {\n answer.append(getAt(self, (Collection) value));\n } else {\n int idx = DefaultTypeTransformation.intUnbox(value);\n answer.append(getAt(self, idx));\n }\n }\n return answer.toString();\n }", "public void put(@NotNull final Transaction txn, final long localId,\n final int blobId, @NotNull final ByteIterable value) {\n primaryStore.put(txn, PropertyKey.propertyKeyToEntry(new PropertyKey(localId, blobId)), value);\n allBlobsIndex.put(txn, IntegerBinding.intToCompressedEntry(blobId), LongBinding.longToCompressedEntry(localId));\n }", "public FullTypeSignature getTypeErasureSignature() {\r\n\t\tif (typeErasureSignature == null) {\r\n\t\t\ttypeErasureSignature = new ClassTypeSignature(binaryName,\r\n\t\t\t\t\tnew TypeArgSignature[0], ownerTypeSignature == null ? null\r\n\t\t\t\t\t\t\t: (ClassTypeSignature) ownerTypeSignature\r\n\t\t\t\t\t\t\t\t\t.getTypeErasureSignature());\r\n\t\t}\r\n\t\treturn typeErasureSignature;\r\n\t}", "public static Configuration loadFromString(String config)\n throws IOException, SAXException {\n ConfigurationImpl cfg = new ConfigurationImpl();\n\n XMLReader parser = XMLReaderFactory.createXMLReader();\n parser.setContentHandler(new ConfigHandler(cfg, null));\n Reader reader = new StringReader(config);\n parser.parse(new InputSource(reader));\n return cfg;\n }" ]
Set new list data set @param list new data set
[ "public void setList(List<T> list) {\n if (list != mList) {\n mList = list;\n if (mList == null) {\n notifyInvalidated();\n } else {\n notifyChanged();\n }\n }\n }" ]
[ "public RedwoodConfiguration loggingClass(final String classToIgnoreInTraces){\r\n tasks.add(new Runnable() { public void run() { Redwood.addLoggingClass(classToIgnoreInTraces); } });\r\n return this;\r\n }", "public static tmtrafficpolicy_tmglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\ttmtrafficpolicy_tmglobal_binding obj = new tmtrafficpolicy_tmglobal_binding();\n\t\tobj.set_name(name);\n\t\ttmtrafficpolicy_tmglobal_binding response[] = (tmtrafficpolicy_tmglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private TableAlias createTableAlias(String aTable, String aPath, String aUserAlias)\r\n {\r\n\t\tif (aUserAlias == null)\r\n\t\t{\r\n\t\t\treturn createTableAlias(aTable, aPath);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn createTableAlias(aTable, aUserAlias + ALIAS_SEPARATOR + aPath);\r\n\t\t}\r\n }", "public static Collection<Component> getComponentsList() {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return null;\n }\n\n return instance.components.values();\n }", "public Map<InetSocketAddress, ServerPort> activePorts() {\n final Server server = this.server;\n if (server != null) {\n return server.activePorts();\n } else {\n return Collections.emptyMap();\n }\n }", "public boolean isIdentical(T a, double tol) {\n if( a.getType() != getType() )\n return false;\n return ops.isIdentical(mat,a.mat,tol);\n }", "@SuppressWarnings({\"UnusedDeclaration\"})\n public void doIndex(StaplerRequest req, StaplerResponse resp) throws IOException, ServletException {\n req.getView(this, chooseAction()).forward(req, resp);\n }", "public synchronized void createImportationDeclaration(String deviceId, String deviceType, String deviceSubType) {\n Map<String, Object> metadata = new HashMap<String, Object>();\n metadata.put(Constants.DEVICE_ID, deviceId);\n metadata.put(Constants.DEVICE_TYPE, deviceType);\n metadata.put(Constants.DEVICE_TYPE_SUB, deviceSubType);\n metadata.put(\"scope\", \"generic\");\n ImportDeclaration declaration = ImportDeclarationBuilder.fromMetadata(metadata).build();\n\n importDeclarations.put(deviceId, declaration);\n\n registerImportDeclaration(declaration);\n }", "private XopBean createXopBean() throws Exception {\n XopBean xop = new XopBean();\n xop.setName(\"xopName\");\n \n InputStream is = getClass().getResourceAsStream(\"/java.jpg\");\n byte[] data = IOUtils.readBytesFromStream(is);\n \n // Pass java.jpg as an array of bytes\n xop.setBytes(data);\n \n // Wrap java.jpg as a DataHandler\n xop.setDatahandler(new DataHandler(\n new ByteArrayDataSource(data, \"application/octet-stream\")));\n \n if (Boolean.getBoolean(\"java.awt.headless\")) {\n System.out.println(\"Running headless. Ignoring an Image property.\");\n } else {\n xop.setImage(getImage(\"/java.jpg\"));\n }\n \n return xop;\n }" ]
Add the operation at the end of Stage MODEL if this operation has not already been registered. This operation should be added if any of the following occur: - - The authorization configuration is removed from a security realm. - The rbac provider is changed to rbac. - A role is removed. - An include is removed from a role. - A management interface is removed. Note: This list only includes actions that could invalidate the configuration, actions that would not invalidate the configuration do not need this operation registering. e.g. Adding a role, if the configuration was already valid this could not invalidate it. @param context - The OperationContext to use to register the step.
[ "public static void addOperation(final OperationContext context) {\n RbacSanityCheckOperation added = context.getAttachment(KEY);\n if (added == null) {\n // TODO support managed domain\n if (!context.isNormalServer()) return;\n context.addStep(createOperation(), INSTANCE, Stage.MODEL);\n context.attach(KEY, INSTANCE);\n }\n }" ]
[ "public static DMatrixRMaj extractColumn(DMatrixRMaj a , int column , DMatrixRMaj out ) {\n if( out == null)\n out = new DMatrixRMaj(a.numRows,1);\n else if( !MatrixFeatures_DDRM.isVector(out) || out.getNumElements() != a.numRows )\n throw new MatrixDimensionException(\"Output must be a vector of length \"+a.numRows);\n\n int index = column;\n for (int i = 0; i < a.numRows; i++, index += a.numCols ) {\n out.data[i] = a.data[index];\n }\n return out;\n }", "public double[] getZeroRates(double[] maturities)\n\t{\n\t\tdouble[] values = new double[maturities.length];\n\n\t\tfor(int i=0; i<maturities.length; i++) {\n\t\t\tvalues[i] = getZeroRate(maturities[i]);\n\t\t}\n\n\t\treturn values;\n\t}", "private void getYearlyDates(Calendar calendar, List<Date> dates)\n {\n if (m_relative)\n {\n getYearlyRelativeDates(calendar, dates);\n }\n else\n {\n getYearlyAbsoluteDates(calendar, dates);\n }\n }", "public int getMinutesPerWeek()\n {\n return m_minutesPerWeek == null ? NumberHelper.getInt(getParentFile().getProjectProperties().getMinutesPerWeek()) : m_minutesPerWeek.intValue();\n }", "public static Multimap<String, String> getParameters(final String rawQuery) {\n Multimap<String, String> result = HashMultimap.create();\n if (rawQuery == null) {\n return result;\n }\n\n StringTokenizer tokens = new StringTokenizer(rawQuery, \"&\");\n while (tokens.hasMoreTokens()) {\n String pair = tokens.nextToken();\n int pos = pair.indexOf('=');\n String key;\n String value;\n if (pos == -1) {\n key = pair;\n value = \"\";\n } else {\n\n try {\n key = URLDecoder.decode(pair.substring(0, pos), \"UTF-8\");\n value = URLDecoder.decode(pair.substring(pos + 1), \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }\n\n result.put(key, value);\n }\n return result;\n }", "public static final void getByteArray(byte[] data, int offset, int size, byte[] buffer, int bufferOffset)\n {\n System.arraycopy(data, offset, buffer, bufferOffset, size);\n }", "private RandomVariable getShortRate(int timeIndex) throws CalculationException {\n\t\tdouble time = getProcess().getTime(timeIndex);\n\t\tdouble timePrev = timeIndex > 0 ? getProcess().getTime(timeIndex-1) : time;\n\t\tdouble timeNext = getProcess().getTime(timeIndex+1);\n\n\t\tRandomVariable zeroRate = getZeroRateFromForwardCurve(time); //getDiscountFactorFromForwardCurve(time).div(getDiscountFactorFromForwardCurve(timeNext)).log().div(timeNext-time);\n\n\t\tRandomVariable alpha = getDV(0, time);\n\n\t\tRandomVariable value = getProcess().getProcessValue(timeIndex, 0);\n\t\tvalue = value.add(alpha);\n\t\t//\t\tvalue = value.sub(Math.log(value.exp().getAverage()));\n\n\t\tvalue = value.add(zeroRate);\n\n\t\treturn value;\n\t}", "public <T> T get(Class<T> type) {\n return get(type.getName(), type);\n }", "private void readTask(ChildTaskContainer mpxjParent, net.sf.mpxj.ganttproject.schema.Task gpTask)\n {\n Task mpxjTask = mpxjParent.addTask();\n mpxjTask.setUniqueID(Integer.valueOf(NumberHelper.getInt(gpTask.getId()) + 1));\n mpxjTask.setName(gpTask.getName());\n mpxjTask.setPercentageComplete(gpTask.getComplete());\n mpxjTask.setPriority(getPriority(gpTask.getPriority()));\n mpxjTask.setHyperlink(gpTask.getWebLink());\n\n Duration duration = Duration.getInstance(NumberHelper.getDouble(gpTask.getDuration()), TimeUnit.DAYS);\n mpxjTask.setDuration(duration);\n\n if (duration.getDuration() == 0)\n {\n mpxjTask.setMilestone(true);\n }\n else\n {\n mpxjTask.setStart(gpTask.getStart());\n mpxjTask.setFinish(m_mpxjCalendar.getDate(gpTask.getStart(), mpxjTask.getDuration(), false));\n }\n\n mpxjTask.setConstraintDate(gpTask.getThirdDate());\n if (mpxjTask.getConstraintDate() != null)\n {\n // TODO: you don't appear to be able to change this setting in GanttProject\n // task.getThirdDateConstraint()\n mpxjTask.setConstraintType(ConstraintType.START_NO_EARLIER_THAN);\n }\n\n readTaskCustomFields(gpTask, mpxjTask);\n\n m_eventManager.fireTaskReadEvent(mpxjTask);\n\n // TODO: read custom values\n\n //\n // Process child tasks\n //\n for (net.sf.mpxj.ganttproject.schema.Task childTask : gpTask.getTask())\n {\n readTask(mpxjTask, childTask);\n }\n }" ]
retrieve an Object by query I.e perform a SELECT ... FROM ... WHERE ... in an RDBMS
[ "public Object getObjectByQuery(Query query) throws PersistenceBrokerException\n {\n Object result = null;\n if (query instanceof QueryByIdentity)\n {\n // example obj may be an entity or an Identity\n Object obj = query.getExampleObject();\n if (obj instanceof Identity)\n {\n Identity oid = (Identity) obj;\n result = getObjectByIdentity(oid);\n }\n else\n {\n // TODO: This workaround doesn't allow 'null' for PK fields\n if (!serviceBrokerHelper().hasNullPKField(getClassDescriptor(obj.getClass()), obj))\n {\n Identity oid = serviceIdentity().buildIdentity(obj);\n result = getObjectByIdentity(oid);\n }\n }\n }\n else\n {\n Class itemClass = query.getSearchClass();\n ClassDescriptor cld = getClassDescriptor(itemClass);\n /*\n use OJB intern Iterator, thus we are able to close used\n resources instantly\n */\n OJBIterator it = getIteratorFromQuery(query, cld);\n /*\n arminw:\n patch by Andre Clute, instead of taking the first found result\n try to get the first found none null result.\n He wrote:\n I have a situation where an item with a certain criteria is in my\n database twice -- once deleted, and then a non-deleted version of it.\n When I do a PB.getObjectByQuery(), the RsIterator get's both results\n from the database, but the first row is the deleted row, so my RowReader\n filters it out, and do not get the right result.\n */\n try\n {\n while (result==null && it.hasNext())\n {\n result = it.next();\n }\n } // make sure that we close the used resources\n finally\n {\n if(it != null) it.releaseDbResources();\n }\n }\n return result;\n }" ]
[ "public DomainList getPhotosetDomains(Date date, String photosetId, int perPage, int page) throws FlickrException {\n return getDomains(METHOD_GET_PHOTOSET_DOMAINS, \"photoset_id\", photosetId, date, perPage, page);\n }", "@SuppressWarnings(\"WeakerAccess\")\n public Map<DeckReference, BeatGrid> getLoadedBeatGrids() {\n ensureRunning();\n // Make a copy so callers get an immutable snapshot of the current state.\n return Collections.unmodifiableMap(new HashMap<DeckReference, BeatGrid>(hotCache));\n }", "private void resetStoreDefinitions(Set<String> storeNamesToDelete) {\n // Clear entries in the metadata cache\n for(String storeName: storeNamesToDelete) {\n this.metadataCache.remove(storeName);\n this.storeDefinitionsStorageEngine.delete(storeName, null);\n this.storeNames.remove(storeName);\n }\n }", "private void validateAttributes() {\n if (content == null) {\n throw new NullContentException(\"RendererBuilder needs content to create Renderer instances\");\n }\n\n if (parent == null) {\n throw new NullParentException(\"RendererBuilder needs a parent to inflate Renderer instances\");\n }\n\n if (layoutInflater == null) {\n throw new NullLayoutInflaterException(\n \"RendererBuilder needs a LayoutInflater to inflate Renderer instances\");\n }\n }", "public boolean getNumericBoolean(int field)\n {\n boolean result = false;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n result = Integer.parseInt(m_fields[field]) == 1;\n }\n\n return (result);\n }", "public static autoscaleprofile[] get(nitro_service service) throws Exception{\n\t\tautoscaleprofile obj = new autoscaleprofile();\n\t\tautoscaleprofile[] response = (autoscaleprofile[])obj.get_resources(service);\n\t\treturn response;\n\t}", "I_CmsSerialDateServiceAsync getService() {\r\n\r\n if (SERVICE == null) {\r\n SERVICE = GWT.create(I_CmsSerialDateService.class);\r\n String serviceUrl = CmsCoreProvider.get().link(\"org.opencms.ade.contenteditor.CmsSerialDateService.gwt\");\r\n ((ServiceDefTarget)SERVICE).setServiceEntryPoint(serviceUrl);\r\n }\r\n return SERVICE;\r\n }", "public void promoteModule(final String name, final String version, 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.promoteModulePath(name, version));\n final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = String.format(FAILED_TO_GET_MODULE, \"promote module\", name, version);\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 }", "public int getCurrentPage() {\n int currentPage = 1;\n int count = mScrollable.getScrollingItemsCount();\n if (mSupportScrollByPage && mCurrentItemIndex >= 0 &&\n mCurrentItemIndex < count) {\n currentPage = (Math.min(mCurrentItemIndex + mPageSize - 1, count - 1)/mPageSize);\n }\n return currentPage;\n }" ]
Sets the jdbc connection to use. @param jcd The connection to use @throws PlatformException If the target database cannot be handled with torque
[ "public void setConnection(JdbcConnectionDescriptor jcd) throws PlatformException\r\n {\r\n _jcd = jcd;\r\n\r\n String targetDatabase = (String)_dbmsToTorqueDb.get(_jcd.getDbms().toLowerCase());\r\n\r\n if (targetDatabase == null)\r\n {\r\n throw new PlatformException(\"Database \"+_jcd.getDbms()+\" is not supported by torque\");\r\n }\r\n if (!targetDatabase.equals(_targetDatabase))\r\n {\r\n _targetDatabase = targetDatabase;\r\n _creationScript = null;\r\n _initScripts.clear();\r\n }\r\n }" ]
[ "public void removeAllAnimations() {\n for (int i = 0, size = mAnimationList.size(); i < size; i++) {\n mAnimationList.get(i).removeAnimationListener(mAnimationListener);\n }\n mAnimationList.clear();\n }", "public static Bytes toBytes(Text t) {\n return Bytes.of(t.getBytes(), 0, t.getLength());\n }", "public static CmsGalleryTabConfiguration resolve(String configStr) {\r\n\r\n CmsGalleryTabConfiguration tabConfig;\r\n if (CmsStringUtil.isEmptyOrWhitespaceOnly(configStr)) {\r\n configStr = \"*sitemap,types,galleries,categories,vfstree,search,results\";\r\n }\r\n if (DEFAULT_CONFIGURATIONS != null) {\r\n tabConfig = DEFAULT_CONFIGURATIONS.get(configStr);\r\n if (tabConfig != null) {\r\n return tabConfig;\r\n }\r\n\r\n }\r\n return parse(configStr);\r\n }", "static int createDeliverable(String path, String originalFileName, String fileFamily, Integer jobId, DbConn cnx)\n {\n QueryResult qr = cnx.runUpdate(\"deliverable_insert\", fileFamily, path, jobId, originalFileName, UUID.randomUUID().toString());\n return qr.getGeneratedId();\n }", "boolean lockInterruptibly(final Integer permit, final long timeout, final TimeUnit unit) throws InterruptedException {\n if (permit == null) {\n throw new IllegalArgumentException();\n }\n return sync.tryAcquireNanos(permit, unit.toNanos(timeout));\n }", "private Map<Integer, Integer> getNodeIdToZonePrimaryCount(Cluster cluster,\n StoreRoutingPlan storeRoutingPlan) {\n Map<Integer, Integer> nodeIdToZonePrimaryCount = Maps.newHashMap();\n for(Integer nodeId: cluster.getNodeIds()) {\n nodeIdToZonePrimaryCount.put(nodeId,\n storeRoutingPlan.getZonePrimaryPartitionIds(nodeId).size());\n }\n\n return nodeIdToZonePrimaryCount;\n }", "public void moveUp(I_CmsEditableGroupRow row) {\n\n int index = m_container.getComponentIndex(row);\n if (index > 0) {\n m_container.removeComponent(row);\n m_container.addComponent(row, index - 1);\n }\n updateButtonBars();\n }", "public Authentication getAuthentication(String token) {\n\t\tif (null != token) {\n\t\t\tTokenContainer container = tokens.get(token);\n\t\t\tif (null != container) {\n\t\t\t\tif (container.isValid()) {\n\t\t\t\t\treturn container.getAuthentication();\n\t\t\t\t} else {\n\t\t\t\t\tlogout(token);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}", "public void addNamespace(final MongoNamespace namespace) {\n this.instanceLock.writeLock().lock();\n try {\n if (this.nsStreamers.containsKey(namespace)) {\n return;\n }\n final NamespaceChangeStreamListener streamer =\n new NamespaceChangeStreamListener(\n namespace,\n instanceConfig.getNamespaceConfig(namespace),\n service,\n networkMonitor,\n authMonitor,\n getLockForNamespace(namespace));\n this.nsStreamers.put(namespace, streamer);\n } finally {\n this.instanceLock.writeLock().unlock();\n }\n }" ]
Sets up and declares internal data structures. @param diag Diagonal elements from tridiagonal matrix. Modified. @param off Off diagonal elements from tridiagonal matrix. Modified. @param numCols number of columns (and rows) in the matrix.
[ "public void init( double diag[] ,\n double off[],\n int numCols ) {\n reset(numCols);\n\n this.diag = diag;\n this.off = off;\n }" ]
[ "public static String readTextFile(InputStream inputStream) {\n InputStreamReader streamReader = new InputStreamReader(inputStream);\n return readTextFile(streamReader);\n }", "private void processChildTasks(Task parentTask) throws SQLException\n {\n List<Row> rows = getRows(\"select * from zscheduleitem where zparentactivity_=? and z_ent=? order by zorderinparentactivity\", parentTask.getUniqueID(), m_entityMap.get(\"Activity\"));\n for (Row row : rows)\n {\n Task task = parentTask.addTask();\n populateTask(row, task);\n processChildTasks(task);\n }\n }", "private void deEndify(List<CoreLabel> tokens) {\r\n if (flags.retainEntitySubclassification) {\r\n return;\r\n }\r\n tokens = new PaddedList<CoreLabel>(tokens, new CoreLabel());\r\n int k = tokens.size();\r\n String[] newAnswers = new String[k];\r\n for (int i = 0; i < k; i++) {\r\n CoreLabel c = tokens.get(i);\r\n CoreLabel p = tokens.get(i - 1);\r\n if (c.get(AnswerAnnotation.class).length() > 1 && c.get(AnswerAnnotation.class).charAt(1) == '-') {\r\n String base = c.get(AnswerAnnotation.class).substring(2);\r\n String pBase = (p.get(AnswerAnnotation.class).length() <= 2 ? p.get(AnswerAnnotation.class) : p.get(AnswerAnnotation.class).substring(2));\r\n boolean isSecond = (base.equals(pBase));\r\n boolean isStart = (c.get(AnswerAnnotation.class).charAt(0) == 'B' || c.get(AnswerAnnotation.class).charAt(0) == 'S');\r\n if (isSecond && isStart) {\r\n newAnswers[i] = intern(\"B-\" + base);\r\n } else {\r\n newAnswers[i] = intern(\"I-\" + base);\r\n }\r\n } else {\r\n newAnswers[i] = c.get(AnswerAnnotation.class);\r\n }\r\n }\r\n for (int i = 0; i < k; i++) {\r\n CoreLabel c = tokens.get(i);\r\n c.set(AnswerAnnotation.class, newAnswers[i]);\r\n }\r\n }", "@Override\n public View getView(int position, View convertView, ViewGroup parent) {\n Country country = getItem(position);\n\n if (convertView == null) {\n convertView = new ImageView(getContext());\n }\n\n ((ImageView) convertView).setImageResource(getFlagResource(country));\n\n return convertView;\n }", "public Set<Class> entityClasses() {\n EntityMetaInfoRepo repo = app().entityMetaInfoRepo().forDb(id);\n return null == repo ? C.<Class>set() : repo.entityClasses();\n }", "public void merge() {\n Thread currentThread = Thread.currentThread();\n if(!stats.get(currentThread).equals(this) || currentThread instanceof WindupChildThread) {\n throw new IllegalArgumentException(\"Trying to merge executionstatistics from a \"\n + \"different thread that is not registered as main thread of application run\");\n }\n\n for (Thread thread : stats.keySet())\n {\n if(thread instanceof WindupChildThread && ((WindupChildThread) thread).getParentThread().equals(currentThread)) {\n merge(stats.get(thread));\n }\n }\n }", "protected Collection loadData() throws PersistenceBrokerException\r\n {\r\n PersistenceBroker broker = getBroker();\r\n try\r\n {\r\n Collection result;\r\n\r\n if (_data != null) // could be set by listener\r\n {\r\n result = _data;\r\n }\r\n else if (_size != 0)\r\n {\r\n // TODO: returned ManageableCollection should extend Collection to avoid\r\n // this cast\r\n result = (Collection) broker.getCollectionByQuery(getCollectionClass(), getQuery());\r\n }\r\n else\r\n {\r\n result = (Collection)getCollectionClass().newInstance();\r\n }\r\n return result;\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new PersistenceBrokerException(ex);\r\n }\r\n finally\r\n {\r\n releaseBroker(broker);\r\n }\r\n }", "protected void createNewFile(final File file) {\n try {\n file.createNewFile();\n setFileNotWorldReadablePermissions(file);\n } catch (IOException e){\n throw new RuntimeException(e);\n }\n }", "protected void appenHtmlFooter(StringBuffer buffer) {\n\n if (m_configuredFooter != null) {\n buffer.append(m_configuredFooter);\n } else {\n buffer.append(\" </body>\\r\\n\" + \"</html>\");\n }\n }" ]
Set the draw mode for this mesh. Default is GL_TRIANGLES. @param drawMode
[ "public GVRRenderData setDrawMode(int drawMode) {\n if (drawMode != GL_POINTS && drawMode != GL_LINES\n && drawMode != GL_LINE_STRIP && drawMode != GL_LINE_LOOP\n && drawMode != GL_TRIANGLES && drawMode != GL_TRIANGLE_STRIP\n && drawMode != GL_TRIANGLE_FAN) {\n throw new IllegalArgumentException(\n \"drawMode must be one of GL_POINTS, GL_LINES, GL_LINE_STRIP, GL_LINE_LOOP, GL_TRIANGLES, GL_TRIANGLE_FAN, GL_TRIANGLE_STRIP.\");\n }\n NativeRenderData.setDrawMode(getNative(), drawMode);\n return this;\n }" ]
[ "public int getXForBeat(int beat) {\n BeatGrid grid = beatGrid.get();\n if (grid != null) {\n return millisecondsToX(grid.getTimeWithinTrack(beat));\n }\n return 0;\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 static void zero( DMatrixSparseCSC A , int row0, int row1, int col0, int col1 ) {\n for (int col = col1-1; col >= col0; col--) {\n int numRemoved = 0;\n\n int idx0 = A.col_idx[col], idx1 = A.col_idx[col+1];\n for (int i = idx0; i < idx1; i++) {\n int row = A.nz_rows[i];\n\n // if sorted a faster technique could be used\n if( row >= row0 && row < row1 ) {\n numRemoved++;\n } else if( numRemoved > 0 ){\n A.nz_rows[i-numRemoved]=row;\n A.nz_values[i-numRemoved]=A.nz_values[i];\n }\n }\n\n if( numRemoved > 0 ) {\n // this could be done more intelligently. Each time a column is adjusted all the columns are adjusted\n // after it. Maybe accumulate the changes in each column and do it in one pass? Need an array to store\n // those results though\n\n for (int i = idx1; i < A.nz_length; i++) {\n A.nz_rows[i - numRemoved] = A.nz_rows[i];\n A.nz_values[i - numRemoved] = A.nz_values[i];\n }\n A.nz_length -= numRemoved;\n\n for (int i = col+1; i <= A.numCols; i++) {\n A.col_idx[i] -= numRemoved;\n }\n }\n }\n }", "public static Method getStaticMethod(Class<?> clazz, String methodName, Class<?>... args) {\n\t\tAssert.notNull(clazz, \"Class must not be null\");\n\t\tAssert.notNull(methodName, \"Method name must not be null\");\n\t\ttry {\n\t\t\tMethod method = clazz.getMethod(methodName, args);\n\t\t\treturn Modifier.isStatic(method.getModifiers()) ? method : null;\n\t\t}\n\t\tcatch (NoSuchMethodException ex) {\n\t\t\treturn null;\n\t\t}\n\t}", "private static String wordShapeDigits(final String s) {\r\n char[] outChars = null;\r\n\r\n for (int i = 0; i < s.length(); i++) {\r\n char c = s.charAt(i);\r\n if (Character.isDigit(c)) {\r\n if (outChars == null) {\r\n outChars = s.toCharArray();\r\n }\r\n outChars[i] = '9';\r\n }\r\n }\r\n if (outChars == null) {\r\n // no digit found\r\n return s;\r\n } else {\r\n return new String(outChars);\r\n }\r\n }", "public void deleteFile(String fileID) {\n URL url = FILE_INFO_URL_TEMPLATE.build(this.api.getBaseURL(), fileID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"DELETE\");\n BoxAPIResponse response = request.send();\n response.disconnect();\n }", "private void removeFromInverseAssociations(\n\t\t\tTuple resultset,\n\t\t\tint tableIndex,\n\t\t\tSerializable id,\n\t\t\tSharedSessionContractImplementor session) {\n\t\tnew EntityAssociationUpdater( this )\n\t\t\t\t.id( id )\n\t\t\t\t.resultset( resultset )\n\t\t\t\t.session( session )\n\t\t\t\t.tableIndex( tableIndex )\n\t\t\t\t.propertyMightRequireInverseAssociationManagement( propertyMightBeMainSideOfBidirectionalAssociation )\n\t\t\t\t.removeNavigationalInformationFromInverseSide();\n\t}", "public static void main(String[] args) {\n String modelFile = \"\";\n String outputFile = \"\";\n int numberOfRows = 0;\n try {\n modelFile = args[0];\n outputFile = args[1];\n numberOfRows = Integer.valueOf(args[2]);\n } catch (IndexOutOfBoundsException | NumberFormatException e) {\n System.out.println(\"ERROR! Invalid command line arguments, expecting: <scxml model file> \"\n + \"<desired csv output file> <desired number of output rows>\");\n return;\n }\n\n FileInputStream model = null;\n try {\n model = new FileInputStream(modelFile);\n } catch (FileNotFoundException e) {\n System.out.println(\"ERROR! Model file not found\");\n return;\n }\n\n SCXMLEngine engine = new SCXMLEngine();\n engine.setModelByInputFileStream(model);\n engine.setBootstrapMin(5);\n\n DataConsumer consumer = new DataConsumer();\n CSVFileWriter writer;\n try {\n writer = new CSVFileWriter(outputFile);\n } catch (IOException e) {\n System.out.println(\"ERROR! Can not write to output csv file\");\n return;\n }\n consumer.addDataWriter(writer);\n\n DefaultDistributor dist = new DefaultDistributor();\n dist.setThreadCount(5);\n dist.setMaxNumberOfLines(numberOfRows);\n dist.setDataConsumer(consumer);\n\n engine.process(dist);\n writer.closeCSVFile();\n\n System.out.println(\"COMPLETE!\");\n }", "public static <T> void finish(T query, long correlationId, EventBus bus, String... labels) {\n for (String type : labels) {\n RemoveLabelledQuery<T> next = finish(query, correlationId, type);\n bus.post(next);\n }\n }" ]
Return a list of unique namespace and predicate pairs, optionally limited by predicate or namespace, in alphabetical order. This method does not require authentication. @param namespace optional, can be null @param predicate optional, can be null @param perPage The number of photos to show per page @param page The page offset @return NamespacesList containing Pair-objects @throws FlickrException
[ "public NamespacesList<Pair> getPairs(String namespace, String predicate, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n NamespacesList<Pair> nsList = new NamespacesList<Pair>();\r\n parameters.put(\"method\", METHOD_GET_PAIRS);\r\n\r\n if (namespace != null) {\r\n parameters.put(\"namespace\", namespace);\r\n }\r\n if (predicate != null) {\r\n parameters.put(\"predicate\", predicate);\r\n }\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element nsElement = response.getPayload();\r\n NodeList nsNodes = nsElement.getElementsByTagName(\"pair\");\r\n nsList.setPage(nsElement.getAttribute(\"page\"));\r\n nsList.setPages(nsElement.getAttribute(\"pages\"));\r\n nsList.setPerPage(nsElement.getAttribute(\"perPage\"));\r\n nsList.setTotal(\"\" + nsNodes.getLength());\r\n for (int i = 0; i < nsNodes.getLength(); i++) {\r\n Element element = (Element) nsNodes.item(i);\r\n nsList.add(parsePair(element));\r\n }\r\n return nsList;\r\n }" ]
[ "private boolean ensureValidSetter(final Expression expression, final Expression leftExpression, final Expression rightExpression, final SetterInfo setterInfo) {\n // for expressions like foo = { ... }\n // we know that the RHS type is a closure\n // but we must check if the binary expression is an assignment\n // because we need to check if a setter uses @DelegatesTo\n VariableExpression ve = new VariableExpression(\"%\", setterInfo.receiverType);\n MethodCallExpression call = new MethodCallExpression(\n ve,\n setterInfo.name,\n rightExpression\n );\n call.setImplicitThis(false);\n visitMethodCallExpression(call);\n MethodNode directSetterCandidate = call.getNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET);\n if (directSetterCandidate==null) {\n // this may happen if there's a setter of type boolean/String/Class, and that we are using the property\n // notation AND that the RHS is not a boolean/String/Class\n for (MethodNode setter : setterInfo.setters) {\n ClassNode type = getWrapper(setter.getParameters()[0].getOriginType());\n if (Boolean_TYPE.equals(type) || STRING_TYPE.equals(type) || CLASS_Type.equals(type)) {\n call = new MethodCallExpression(\n ve,\n setterInfo.name,\n new CastExpression(type,rightExpression)\n );\n call.setImplicitThis(false);\n visitMethodCallExpression(call);\n directSetterCandidate = call.getNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET);\n if (directSetterCandidate!=null) {\n break;\n }\n }\n }\n }\n if (directSetterCandidate != null) {\n for (MethodNode setter : setterInfo.setters) {\n if (setter == directSetterCandidate) {\n leftExpression.putNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET, directSetterCandidate);\n storeType(leftExpression, getType(rightExpression));\n break;\n }\n }\n } else {\n ClassNode firstSetterType = setterInfo.setters.iterator().next().getParameters()[0].getOriginType();\n addAssignmentError(firstSetterType, getType(rightExpression), expression);\n return true;\n }\n return false;\n }", "public List<Cluster> cluster(final Collection<Point2D> points) {\n \tfinal List<Cluster> clusters = new ArrayList<Cluster>();\n final Map<Point2D, PointStatus> visited = new HashMap<Point2D, DBScan.PointStatus>();\n\n KDTree<Point2D> tree = new KDTree<Point2D>(2);\n \n // Populate the kdTree\n for (final Point2D point : points) {\n \tdouble[] key = {point.x, point.y};\n \ttree.insert(key, point);\n }\n \n for (final Point2D point : points) {\n if (visited.get(point) != null) {\n continue;\n }\n final List<Point2D> neighbors = getNeighbors(point, tree);\n if (neighbors.size() >= minPoints) {\n // DBSCAN does not care about center points\n final Cluster cluster = new Cluster(clusters.size());\n clusters.add(expandCluster(cluster, point, neighbors, tree, visited));\n } else {\n visited.put(point, PointStatus.NOISE);\n }\n }\n\n for (Cluster cluster : clusters) {\n \tcluster.calculateCentroid();\n }\n \n return clusters;\n }", "public static<A, B, C, Z> Function3<A, B, C, Z> lift(Func3<A, B, C, Z> f) {\n\treturn bridge.lift(f);\n }", "protected int getDonorId(StoreRoutingPlan currentSRP,\n StoreRoutingPlan finalSRP,\n int stealerZoneId,\n int stealerNodeId,\n int stealerPartitionId) {\n int stealerZoneNAry = finalSRP.getZoneNaryForNodesPartition(stealerZoneId,\n stealerNodeId,\n stealerPartitionId);\n\n int donorZoneId;\n if(currentSRP.zoneNAryExists(stealerZoneId, stealerZoneNAry, stealerPartitionId)) {\n // Steal from local n-ary (since one exists).\n donorZoneId = stealerZoneId;\n } else {\n // Steal from zone that hosts primary partition Id.\n int currentMasterNodeId = currentSRP.getNodeIdForPartitionId(stealerPartitionId);\n donorZoneId = currentCluster.getNodeById(currentMasterNodeId).getZoneId();\n }\n\n return currentSRP.getNodeIdForZoneNary(donorZoneId, stealerZoneNAry, stealerPartitionId);\n\n }", "public ReplicationResult trigger() {\n assertNotEmpty(source, \"Source\");\n assertNotEmpty(target, \"Target\");\n InputStream response = null;\n try {\n JsonObject json = createJson();\n if (log.isLoggable(Level.FINE)) {\n log.fine(json.toString());\n }\n\n final URI uri = new DatabaseURIHelper(client.getBaseUri()).path(\"_replicate\").build();\n response = client.post(uri, json.toString());\n final InputStreamReader reader = new InputStreamReader(response, \"UTF-8\");\n return client.getGson().fromJson(reader, ReplicationResult.class);\n } catch (UnsupportedEncodingException e) {\n // This should never happen as every implementation of the java platform is required\n // to support UTF-8.\n throw new RuntimeException(e);\n } finally {\n close(response);\n }\n }", "public void addTags(String photoId, String[] tags) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ADD_TAGS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"tags\", StringUtilities.join(tags, \" \", true));\r\n\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }", "public static base_response save(nitro_service client) throws Exception {\n\t\tnsconfig saveresource = new nsconfig();\n\t\treturn saveresource.perform_operation(client,\"save\");\n\t}", "public static double normP2( DMatrixRMaj A ) {\n if( MatrixFeatures_DDRM.isVector(A)) {\n return normF(A);\n } else {\n return inducedP2(A);\n }\n }", "public static List<CompiledAutomaton> createAutomata(String prefix,\n String regexp, Map<String, Automaton> automatonMap) throws IOException {\n List<CompiledAutomaton> list = new ArrayList<>();\n Automaton automatonRegexp = null;\n if (regexp != null) {\n RegExp re = new RegExp(prefix + MtasToken.DELIMITER + regexp + \"\\u0000*\");\n automatonRegexp = re.toAutomaton();\n }\n int step = 500;\n List<String> keyList = new ArrayList<>(automatonMap.keySet());\n for (int i = 0; i < keyList.size(); i += step) {\n int localStep = step;\n boolean success = false;\n CompiledAutomaton compiledAutomaton = null;\n while (!success) {\n success = true;\n int next = Math.min(keyList.size(), i + localStep);\n List<Automaton> listAutomaton = new ArrayList<>();\n for (int j = i; j < next; j++) {\n listAutomaton.add(automatonMap.get(keyList.get(j)));\n }\n Automaton automatonList = Operations.union(listAutomaton);\n Automaton automaton;\n if (automatonRegexp != null) {\n automaton = Operations.intersection(automatonList, automatonRegexp);\n } else {\n automaton = automatonList;\n }\n try {\n compiledAutomaton = new CompiledAutomaton(automaton);\n } catch (TooComplexToDeterminizeException e) {\n log.debug(e);\n success = false;\n if (localStep > 1) {\n localStep /= 2;\n } else {\n throw new IOException(\"TooComplexToDeterminizeException\");\n }\n }\n }\n list.add(compiledAutomaton);\n }\n return list;\n }" ]
We have more input since wait started
[ "public static void main(String args[]) throws Exception {\n final StringBuffer buffer = new StringBuffer(\"The lazy fox\");\n Thread t1 = new Thread() {\n public void run() {\n synchronized(buffer) {\n buffer.delete(0,4);\n buffer.append(\" in the middle\");\n System.err.println(\"Middle\");\n try { Thread.sleep(4000); } catch(Exception e) {}\n buffer.append(\" of fall\");\n System.err.println(\"Fall\");\n }\n }\n };\n Thread t2 = new Thread() {\n public void run() {\n try { Thread.sleep(1000); } catch(Exception e) {}\n buffer.append(\" jump over the fence\");\n System.err.println(\"Fence\");\n }\n };\n t1.start();\n t2.start();\n\n t1.join();\n t2.join();\n System.err.println(buffer);\n }" ]
[ "private void clearQueues(final Context context) {\n synchronized (eventLock) {\n\n DBAdapter adapter = loadDBAdapter(context);\n DBAdapter.Table tableName = DBAdapter.Table.EVENTS;\n\n adapter.removeEvents(tableName);\n tableName = DBAdapter.Table.PROFILE_EVENTS;\n adapter.removeEvents(tableName);\n\n clearUserContext(context);\n }\n }", "@Deprecated\n\t@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n\tpublic void setAttributes(Map<String, PrimitiveAttribute<?>> attributes) {\n\t\tif (!isPrimitiveOnly()) {\n\t\t\tthrow new UnsupportedOperationException(\"Primitive API not supported for nested association values\");\n\t\t}\n\t\tthis.attributes = (Map) attributes;\n\t}", "public static Command newInsert(Object object,\n String outIdentifier) {\n return getCommandFactoryProvider().newInsert( object,\n outIdentifier );\n }", "public void setTileUrls(List<String> tileUrls) {\n\t\tthis.tileUrls = tileUrls;\n\t\tif (null != urlStrategy) {\n\t\t\turlStrategy.setUrls(tileUrls);\n\t\t}\n\t}", "public static void getHistory() throws Exception{\n Client client = new Client(\"ProfileName\", false);\n\n // Obtain the 100 history entries starting from offset 0\n History[] history = client.refreshHistory(100, 0);\n\n client.clearHistory();\n }", "public int compare(Object objA, Object objB)\r\n {\r\n String idAStr = _table.getColumn((String)objA).getProperty(\"id\");\r\n String idBStr = _table.getColumn((String)objB).getProperty(\"id\");\r\n int idA;\r\n int idB;\r\n\r\n try {\r\n idA = Integer.parseInt(idAStr);\r\n }\r\n catch (Exception ex) {\r\n return 1;\r\n }\r\n try {\r\n idB = Integer.parseInt(idBStr);\r\n }\r\n catch (Exception ex) {\r\n return -1;\r\n }\r\n return idA < idB ? -1 : (idA > idB ? 1 : 0);\r\n }", "public static snmpalarm[] get(nitro_service service, String trapname[]) throws Exception{\n\t\tif (trapname !=null && trapname.length>0) {\n\t\t\tsnmpalarm response[] = new snmpalarm[trapname.length];\n\t\t\tsnmpalarm obj[] = new snmpalarm[trapname.length];\n\t\t\tfor (int i=0;i<trapname.length;i++) {\n\t\t\t\tobj[i] = new snmpalarm();\n\t\t\t\tobj[i].set_trapname(trapname[i]);\n\t\t\t\tresponse[i] = (snmpalarm) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "public static final void setPosition(UIObject o, Rect pos) {\n Style style = o.getElement().getStyle();\n style.setPropertyPx(\"left\", pos.x);\n style.setPropertyPx(\"top\", pos.y);\n }", "public static Map<String, List<String>> getPartitionsForTopics(ZkClient zkClient, Collection<String> topics) {\n Map<String, List<String>> ret = new HashMap<String, List<String>>();\n for (String topic : topics) {\n List<String> partList = new ArrayList<String>();\n List<String> brokers = getChildrenParentMayNotExist(zkClient, BrokerTopicsPath + \"/\" + topic);\n if (brokers != null) {\n for (String broker : brokers) {\n final String parts = readData(zkClient, BrokerTopicsPath + \"/\" + topic + \"/\" + broker);\n int nParts = Integer.parseInt(parts);\n for (int i = 0; i < nParts; i++) {\n partList.add(broker + \"-\" + i);\n }\n }\n }\n Collections.sort(partList);\n ret.put(topic, partList);\n }\n return ret;\n }" ]
Use this API to fetch appfwprofile resource of given name .
[ "public static appfwprofile get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile obj = new appfwprofile();\n\t\tobj.set_name(name);\n\t\tappfwprofile response = (appfwprofile) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
[ "public static <E> Collection<E> collectify(ObjectMapper mapper, Object source, Class<? extends Collection> targetCollectionType, Class<E> targetElementType) {\n CollectionType collectionType = mapper.getTypeFactory().constructCollectionType(targetCollectionType, targetElementType);\n return objectify(mapper, convertToCollection(source), collectionType);\n }", "public boolean ifTaskCompletedSuccessOrFailureFromResponse(\n ResponseOnSingeRequest myResponse) {\n\n boolean isCompleted = false;\n try {\n\n if (myResponse == null || myResponse.isFailObtainResponse()) {\n return isCompleted;\n }\n\n String responseBody = myResponse.getResponseBody();\n if (responseBody.matches(successRegex)\n || responseBody.matches(failureRegex)) {\n isCompleted = true;\n }\n\n } catch (Exception t) {\n logger.error(\"fail \" + t);\n\n }\n return isCompleted;\n }", "private static TechReportPlacement processPlaceLabels(GraphContext graphContext, Set<String> tagNames)\n {\n TagGraphService tagService = new TagGraphService(graphContext);\n\n if (tagNames.size() < 3)\n throw new WindupException(\"There should always be exactly 3 placement labels - row, sector, column/box. It was: \" + tagNames);\n if (tagNames.size() > 3)\n LOG.severe(\"There should always be exactly 3 placement labels - row, sector, column/box. It was: \" + tagNames);\n\n TechReportPlacement placement = new TechReportPlacement();\n\n final TagModel placeSectorsTag = tagService.getTagByName(\"techReport:placeSectors\");\n final TagModel placeBoxesTag = tagService.getTagByName(\"techReport:placeBoxes\");\n final TagModel placeRowsTag = tagService.getTagByName(\"techReport:placeRows\");\n\n Set<String> unknownTags = new HashSet<>();\n for (String name : tagNames)\n {\n final TagModel tag = tagService.getTagByName(name);\n if (null == tag)\n continue;\n\n if (TagGraphService.isTagUnderTagOrSame(tag, placeSectorsTag))\n {\n placement.sector = tag;\n }\n else if (TagGraphService.isTagUnderTagOrSame(tag, placeBoxesTag))\n {\n placement.box = tag;\n }\n else if (TagGraphService.isTagUnderTagOrSame(tag, placeRowsTag))\n {\n placement.row = tag;\n }\n else\n {\n unknownTags.add(name);\n }\n }\n placement.unknown = unknownTags;\n\n LOG.fine(String.format(\"\\t\\tLabels %s identified as: sector: %s, box: %s, row: %s\", tagNames, placement.sector, placement.box,\n placement.row));\n if (placement.box == null || placement.row == null)\n {\n LOG.severe(String.format(\n \"There should always be exactly 3 placement labels - row, sector, column/box. Found: %s, of which box: %s, row: %s\", tagNames,\n placement.box, placement.row));\n }\n return placement;\n }", "public static List<String> getNodeListFromStringLineSeperateOrSpaceSeperate(\n String listStr, boolean removeDuplicate) {\n\n List<String> nodes = new ArrayList<String>();\n\n for (String token : listStr.split(\"[\\\\r?\\\\n| +]+\")) {\n\n // 20131025: fix if fqdn has space in the end.\n if (token != null && !token.trim().isEmpty()) {\n nodes.add(token.trim());\n\n }\n }\n\n if (removeDuplicate) {\n removeDuplicateNodeList(nodes);\n }\n logger.info(\"Target hosts size : \" + nodes.size());\n\n return nodes;\n\n }", "public static Chart getMSDLineWithConfinedModelChart(Trajectory t, int lagMin,\n\t\t\tint lagMax, double timelag, double a, double b, double c, double d) {\n\n\t\tdouble[] xData = new double[lagMax - lagMin + 1];\n\t\tdouble[] yData = new double[lagMax - lagMin + 1];\n\t\tdouble[] modelData = new double[lagMax - lagMin + 1];\n\t\tMeanSquaredDisplacmentFeature msdeval = new MeanSquaredDisplacmentFeature(\n\t\t\t\tt, lagMin);\n\t\tmsdeval.setTrajectory(t);\n\t\tmsdeval.setTimelag(lagMin);\n\t\tfor (int i = lagMin; i < lagMax + 1; i++) {\n\t\t\tmsdeval.setTimelag(i);\n\t\t\tdouble msdhelp = msdeval.evaluate()[0];\n\t\t\txData[i - lagMin] = i;\n\t\t\tyData[i - lagMin] = msdhelp;\n\t\t\tmodelData[i - lagMin] = a\n\t\t\t\t\t* (1 - b * Math.exp((-4 * d) * ((i * timelag) / a) * c));\n\t\t}\n\n\t\t// Create Chart\n\t\tChart chart = QuickChart.getChart(\"MSD Line\", \"LAG\", \"MSD\", \"MSD\",\n\t\t\t\txData, yData);\n\t\tif(Math.abs(1-b)<0.00001 && Math.abs(1-a)<0.00001){\n\t\t\tchart.addSeries(\"y=a*(1-exp(-4*D*t/a))\", xData, modelData);\n\t\t}else{\n\t\t\tchart.addSeries(\"y=a*(1-b*exp(-4*c*D*t/a))\", xData, modelData);\n\t\t}\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}", "public double compare(String v1, String v2) {\n // FIXME: it should be possible here to say that, actually, we\n // didn't learn anything from comparing these two values, so that\n // probability is set to 0.5.\n\n if (comparator == null)\n return 0.5; // we ignore properties with no comparator\n\n // first, we call the comparator, to get a measure of how similar\n // these two values are. note that this is not the same as what we\n // are going to return, which is a probability.\n double sim = comparator.compare(v1, v2);\n\n // we have been configured with a high probability (for equal\n // values) and a low probability (for different values). given\n // sim, which is a measure of the similarity somewhere in between\n // equal and different, we now compute our estimate of the\n // probability.\n\n // if sim = 1.0, we return high. if sim = 0.0, we return low. for\n // values in between we need to compute a little. the obvious\n // formula to use would be (sim * (high - low)) + low, which\n // spreads the values out equally spaced between high and low.\n\n // however, if the similarity is higher than 0.5 we don't want to\n // consider this negative evidence, and so there's a threshold\n // there. also, users felt Duke was too eager to merge records,\n // and wanted probabilities to fall off faster with lower\n // probabilities, and so we square sim in order to achieve this.\n\n if (sim >= 0.5)\n return ((high - 0.5) * (sim * sim)) + 0.5;\n else\n return low;\n }", "public boolean isServerAvailable(){\n final Client client = getClient();\n final ClientResponse response = client.resource(serverURL).get(ClientResponse.class);\n\n if(ClientResponse.Status.OK.getStatusCode() == response.getStatus()){\n return true;\n }\n\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, \"Failed to reach the targeted Grapes server\", response.getStatus()));\n }\n client.destroy();\n\n return false;\n }", "@Override\n public boolean supportsNativeRotation() {\n return this.params.useNativeAngle &&\n (this.params.serverType == WmsLayerParam.ServerType.MAPSERVER ||\n this.params.serverType == WmsLayerParam.ServerType.GEOSERVER);\n }", "public static boolean containsUid(IdRange[] idRanges, long uid) {\r\n if (null != idRanges && idRanges.length > 0) {\r\n for (IdRange range : idRanges) {\r\n if (range.includes(uid)) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n }" ]
Reads a command "tag" from the request.
[ "public String tag(ImapRequestLineReader request) throws ProtocolException {\n CharacterValidator validator = new TagCharValidator();\n return consumeWord(request, validator);\n }" ]
[ "public void racRent() {\n\t\tpos = pos - 1;\n\t\tString userName = CarSearch.getLastSearchParams()[0];\n\t\tString pickupDate = CarSearch.getLastSearchParams()[1];\n\t\tString returnDate = CarSearch.getLastSearchParams()[2];\n\t\tthis.searcher.search(userName, pickupDate, returnDate);\n\t\tif (searcher!=null && searcher.getCars()!= null && pos < searcher.getCars().size() && searcher.getCars().get(pos) != null) {\n\t\t\tRESStatusType resStatus = reserver.reserveCar(searcher.getCustomer()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, searcher.getCars().get(pos)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, pickupDate\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, returnDate);\n\t\t\tConfirmationType confirm = reserver.getConfirmation(resStatus\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, searcher.getCustomer()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, searcher.getCars().get(pos)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, pickupDate\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, returnDate);\n\n\t\t\tRESCarType car = confirm.getCar();\n\t\t\tCustomerDetailsType customer = confirm.getCustomer();\n\t\t\t\n\t\t\tSystem.out.println(MessageFormat.format(CONFIRMATION\n\t\t\t\t\t, confirm.getDescription()\n\t\t\t\t\t, confirm.getReservationId()\n\t\t\t\t\t, customer.getName()\n\t\t\t\t\t, customer.getEmail()\n\t\t\t\t\t, customer.getCity()\n\t\t\t\t\t, customer.getStatus()\n\t\t\t\t\t, car.getBrand()\n\t\t\t\t\t, car.getDesignModel()\n\t\t\t\t\t, confirm.getFromDate()\n\t\t\t\t\t, confirm.getToDate()\n\t\t\t\t\t, padl(car.getRateDay(), 10)\n\t\t\t\t\t, padl(car.getRateWeekend(), 10)\n\t\t\t\t\t, padl(confirm.getCreditPoints().toString(), 7)));\n\t\t} else {\n\t\t\tSystem.out.println(\"Invalid selection: \" + (pos+1)); //$NON-NLS-1$\n\t\t}\n\t}", "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 }", "public static sslcertkey_sslvserver_binding[] get(nitro_service service, String certkey) throws Exception{\n\t\tsslcertkey_sslvserver_binding obj = new sslcertkey_sslvserver_binding();\n\t\tobj.set_certkey(certkey);\n\t\tsslcertkey_sslvserver_binding response[] = (sslcertkey_sslvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static boolean hasFacet(GridDialect gridDialect, Class<? extends GridDialect> facetType) {\n\t\tif ( gridDialect instanceof ForwardingGridDialect ) {\n\t\t\treturn hasFacet( ( (ForwardingGridDialect<?>) gridDialect ).getGridDialect(), facetType );\n\t\t}\n\t\telse {\n\t\t\treturn facetType.isAssignableFrom( gridDialect.getClass() );\n\t\t}\n\t}", "List<String> getRuleFlowNames(HttpServletRequest req) {\n final String[] projectAndBranch = getProjectAndBranchNames(req);\n\n // Query RuleFlowGroups for asset project and branch\n List<RefactoringPageRow> results = queryService.query(\n DesignerFindRuleFlowNamesQuery.NAME,\n new HashSet<ValueIndexTerm>() {{\n add(new ValueSharedPartIndexTerm(\"*\",\n PartType.RULEFLOW_GROUP,\n TermSearchType.WILDCARD));\n add(new ValueModuleNameIndexTerm(projectAndBranch[0]));\n if (projectAndBranch[1] != null) {\n add(new ValueBranchNameIndexTerm(projectAndBranch[1]));\n }\n }});\n\n final List<String> ruleFlowGroupNames = new ArrayList<String>();\n for (RefactoringPageRow row : results) {\n ruleFlowGroupNames.add((String) row.getValue());\n }\n Collections.sort(ruleFlowGroupNames);\n\n // Query RuleFlowGroups for all projects and branches\n results = queryService.query(\n DesignerFindRuleFlowNamesQuery.NAME,\n new HashSet<ValueIndexTerm>() {{\n add(new ValueSharedPartIndexTerm(\"*\",\n PartType.RULEFLOW_GROUP,\n TermSearchType.WILDCARD));\n }});\n final List<String> otherRuleFlowGroupNames = new LinkedList<String>();\n for (RefactoringPageRow row : results) {\n String ruleFlowGroupName = (String) row.getValue();\n if (!ruleFlowGroupNames.contains(ruleFlowGroupName)) {\n // but only add the new ones\n otherRuleFlowGroupNames.add(ruleFlowGroupName);\n }\n }\n Collections.sort(otherRuleFlowGroupNames);\n\n ruleFlowGroupNames.addAll(otherRuleFlowGroupNames);\n\n return ruleFlowGroupNames;\n }", "public static void validateInterimFinalCluster(final Cluster interimCluster,\n final Cluster finalCluster) {\n validateClusterPartitionCounts(interimCluster, finalCluster);\n validateClusterZonesSame(interimCluster, finalCluster);\n validateClusterNodeCounts(interimCluster, finalCluster);\n validateClusterNodeState(interimCluster, finalCluster);\n return;\n }", "public <T extends OutputStream> T write(T os) throws IOException {\n close();\n\n if (!(this.os instanceof ByteArrayOutputStream))\n throw new IllegalStateException(\"Cannot write to another target if setOutputStream has been called\");\n final byte[] content = ((ByteArrayOutputStream) this.os).toByteArray();\n\n if (packer != null)\n packer.pack(new JarInputStream(new ByteArrayInputStream(content)), os);\n else\n os.write(content);\n\n os.close();\n return os;\n }", "@Override\n public CompletableFuture<Map<String, Change<?>>> diff(Revision from, Revision to, String pathPattern) {\n final ServiceRequestContext ctx = context();\n return CompletableFuture.supplyAsync(() -> {\n requireNonNull(from, \"from\");\n requireNonNull(to, \"to\");\n requireNonNull(pathPattern, \"pathPattern\");\n\n failFastIfTimedOut(this, logger, ctx, \"diff\", from, to, pathPattern);\n\n final RevisionRange range = normalizeNow(from, to).toAscending();\n readLock();\n try (RevWalk rw = new RevWalk(jGitRepository)) {\n final RevTree treeA = rw.parseTree(commitIdDatabase.get(range.from()));\n final RevTree treeB = rw.parseTree(commitIdDatabase.get(range.to()));\n\n // Compare the two Git trees.\n // Note that we do not cache here because CachingRepository caches the final result already.\n return toChangeMap(blockingCompareTreesUncached(treeA, treeB,\n pathPatternFilterOrTreeFilter(pathPattern)));\n } catch (StorageException e) {\n throw e;\n } catch (Exception e) {\n throw new StorageException(\"failed to parse two trees: range=\" + range, e);\n } finally {\n readUnlock();\n }\n }, repositoryWorker);\n }", "public static void main(final String[] args) throws IOException\n {\n // This is just a _hack_ ...\n BufferedReader reader = null;\n if (args.length == 0)\n {\n System.err.println(\"No input file specified.\");\n System.exit(-1);\n }\n if (args.length > 1)\n {\n reader = new BufferedReader(new InputStreamReader(new FileInputStream(args[1]), \"UTF-8\"));\n String line = reader.readLine();\n while (line != null && !line.startsWith(\"<!-- ###\"))\n {\n System.out.println(line);\n line = reader.readLine();\n }\n }\n System.out.println(Processor.process(new File(args[0])));\n if (args.length > 1 && reader != null)\n {\n String line = reader.readLine();\n while (line != null)\n {\n System.out.println(line);\n line = reader.readLine();\n }\n reader.close();\n }\n }" ]
Convert a given date to a floating point date using a given reference date. @param referenceDate The reference date associated with \( t=0 \). @param date The given date to be associated with the return value \( T \). @return The value T measuring the distance of reference date and date by ACT/365 with SECONDS_PER_DAY seconds used as the smallest time unit and SECONDS_PER_DAY is a constant 365*24*60*60.
[ "public static double getFloatingPointDateFromDate(LocalDateTime referenceDate, LocalDateTime date) {\n\t\tDuration duration = Duration.between(referenceDate, date);\n\t\treturn ((double)duration.getSeconds()) / SECONDS_PER_DAY;\n\t}" ]
[ "public Map<String, Object> getArtifactFieldsFilters() {\n\t\tfinal Map<String, Object> params = new HashMap<String, Object>();\n\n for(final Filter filter: filters){\n params.putAll(filter.artifactFilterFields());\n }\n\n\t\treturn params;\n\t}", "private void readResource(Document.Resources.Resource resource)\n {\n Resource mpxjResource = m_projectFile.addResource();\n mpxjResource.setName(resource.getName());\n mpxjResource.setResourceCalendar(m_calendarMap.get(resource.getCalendarID()));\n mpxjResource.setStandardRate(new Rate(resource.getCost(), resource.getCostTimeUnit()));\n mpxjResource.setEmailAddress(resource.getEMail());\n mpxjResource.setGroup(resource.getGroup());\n //resource.getHyperlinks()\n mpxjResource.setUniqueID(resource.getID());\n //resource.getMarkerID()\n mpxjResource.setNotes(resource.getNote());\n mpxjResource.setID(Integer.valueOf(resource.getOutlineNumber()));\n //resource.getStyleProject()\n mpxjResource.setType(resource.getSubType() == null ? resource.getType() : resource.getSubType());\n }", "public ParallelTask getTaskFromInProgressMap(String jobId) {\n if (!inprogressTaskMap.containsKey(jobId))\n return null;\n return inprogressTaskMap.get(jobId);\n }", "public Counter<K1> sumInnerCounter() {\r\n Counter<K1> summed = new ClassicCounter<K1>();\r\n for (K1 key : this.firstKeySet()) {\r\n summed.incrementCount(key, this.getCounter(key).totalCount());\r\n }\r\n return summed;\r\n }", "protected static boolean fileDoesNotExist(String file, String path,\n String dest_dir) {\n\n File f = new File(dest_dir);\n if (!f.isDirectory())\n return false;\n\n String folderPath = createFolderPath(path);\n\n f = new File(f, folderPath);\n\n File javaFile = new File(f, file);\n boolean result = !javaFile.exists();\n\n return result;\n }", "public static List<String> getStoreNames(List<StoreDefinition> storeDefList) {\n List<String> storeList = new ArrayList<String>();\n for(StoreDefinition def: storeDefList) {\n storeList.add(def.getName());\n }\n return storeList;\n }", "public SqlStatement getPreparedDeleteStatement(Query query, ClassDescriptor cld)\r\n {\r\n return new SqlDeleteByQuery(m_platform, cld, query, logger);\r\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 detectTierIphone() {\r\n\r\n if (detectIphoneOrIpod()\r\n || detectAndroidPhone()\r\n || detectWindowsPhone()\r\n || detectBlackBerry10Phone()\r\n || (detectBlackBerryWebKit() && detectBlackBerryTouch())\r\n || detectPalmWebOS()\r\n || detectBada()\r\n || detectTizen()\r\n || detectFirefoxOSPhone()\r\n || detectSailfishPhone()\r\n || detectUbuntuPhone()\r\n || detectGamingHandheld()) {\r\n return true;\r\n }\r\n return false;\r\n }" ]
Collection of JRVariable @param variables @return
[ "public static String getVariablesMapExpression(Collection variables) {\n StringBuilder variablesMap = new StringBuilder(\"new \" + PropertiesMap.class.getName() + \"()\");\n for (Object variable : variables) {\n JRVariable jrvar = (JRVariable) variable;\n String varname = jrvar.getName();\n variablesMap.append(\".with(\\\"\").append(varname).append(\"\\\",$V{\").append(varname).append(\"})\");\n }\n return variablesMap.toString();\n }" ]
[ "public GVRShader getTemplate(GVRContext ctx)\n {\n if (mShaderTemplate == null)\n {\n mShaderTemplate = makeTemplate(ID, ctx);\n ctx.getShaderManager().addShaderID(this);\n }\n return mShaderTemplate;\n }", "private void calculateMenuItemPosition() {\n\n float itemRadius = (expandedRadius + collapsedRadius) / 2, f;\n RectF area = new RectF(\n center.x - itemRadius,\n center.y - itemRadius,\n center.x + itemRadius,\n center.y + itemRadius);\n Path path = new Path();\n path.addArc(area, (float) fromAngle, (float) (toAngle - fromAngle));\n PathMeasure measure = new PathMeasure(path, false);\n float len = measure.getLength();\n int divisor = getChildCount();\n float divider = len / divisor;\n\n for (int i = 0; i < getChildCount(); i++) {\n float[] coords = new float[2];\n measure.getPosTan(i * divider + divider * .5f, coords, null);\n FilterMenu.Item item = (FilterMenu.Item) getChildAt(i).getTag();\n item.setX((int) coords[0] - item.getView().getMeasuredWidth() / 2);\n item.setY((int) coords[1] - item.getView().getMeasuredHeight() / 2);\n }\n }", "private void populateRecurringException(ProjectCalendarException mpxjException, Exceptions.Exception xmlException)\n {\n RecurringData data = mpxjException.getRecurring();\n xmlException.setEnteredByOccurrences(Boolean.TRUE);\n xmlException.setOccurrences(NumberHelper.getBigInteger(data.getOccurrences()));\n\n switch (data.getRecurrenceType())\n {\n case DAILY:\n {\n xmlException.setType(BigInteger.valueOf(7));\n xmlException.setPeriod(NumberHelper.getBigInteger(data.getFrequency()));\n break;\n }\n\n case WEEKLY:\n {\n xmlException.setType(BigInteger.valueOf(6));\n xmlException.setPeriod(NumberHelper.getBigInteger(data.getFrequency()));\n xmlException.setDaysOfWeek(getDaysOfTheWeek(data));\n break;\n }\n\n case MONTHLY:\n {\n xmlException.setPeriod(NumberHelper.getBigInteger(data.getFrequency()));\n if (data.getRelative())\n {\n xmlException.setType(BigInteger.valueOf(5));\n xmlException.setMonthItem(BigInteger.valueOf(data.getDayOfWeek().getValue() + 2));\n xmlException.setMonthPosition(BigInteger.valueOf(NumberHelper.getInt(data.getDayNumber()) - 1));\n }\n else\n {\n xmlException.setType(BigInteger.valueOf(4));\n xmlException.setMonthDay(NumberHelper.getBigInteger(data.getDayNumber()));\n }\n break;\n }\n\n case YEARLY:\n {\n xmlException.setMonth(BigInteger.valueOf(NumberHelper.getInt(data.getMonthNumber()) - 1));\n if (data.getRelative())\n {\n xmlException.setType(BigInteger.valueOf(3));\n xmlException.setMonthItem(BigInteger.valueOf(data.getDayOfWeek().getValue() + 2));\n xmlException.setMonthPosition(BigInteger.valueOf(NumberHelper.getInt(data.getDayNumber()) - 1));\n }\n else\n {\n xmlException.setType(BigInteger.valueOf(2));\n xmlException.setMonthDay(NumberHelper.getBigInteger(data.getDayNumber()));\n }\n }\n }\n }", "public static void launchPermissionSettings(Activity activity) {\n Intent intent = new Intent();\n intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);\n intent.setData(Uri.fromParts(\"package\", activity.getPackageName(), null));\n activity.startActivity(intent);\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 containsOnlyNull(Object... values){\t\n\t\tfor(Object o : values){\n\t\t\tif(o!= null){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}", "protected Query buildMtoNImplementorQuery(Collection ids)\r\n {\r\n String[] indFkCols = getFksToThisClass();\r\n String[] indItemFkCols = getFksToItemClass();\r\n FieldDescriptor[] pkFields = getOwnerClassDescriptor().getPkFields();\r\n FieldDescriptor[] itemPkFields = getItemClassDescriptor().getPkFields();\r\n String[] cols = new String[indFkCols.length + indItemFkCols.length];\r\n int[] jdbcTypes = new int[indFkCols.length + indItemFkCols.length];\r\n\r\n // concatenate the columns[]\r\n System.arraycopy(indFkCols, 0, cols, 0, indFkCols.length);\r\n System.arraycopy(indItemFkCols, 0, cols, indFkCols.length, indItemFkCols.length);\r\n\r\n Criteria crit = buildPrefetchCriteria(ids, indFkCols, indItemFkCols, itemPkFields);\r\n\r\n // determine the jdbcTypes of the pks\r\n for (int i = 0; i < pkFields.length; i++)\r\n {\r\n jdbcTypes[i] = pkFields[i].getJdbcType().getType();\r\n }\r\n for (int i = 0; i < itemPkFields.length; i++)\r\n {\r\n jdbcTypes[pkFields.length + i] = itemPkFields[i].getJdbcType().getType();\r\n }\r\n\r\n ReportQueryByMtoNCriteria q = new ReportQueryByMtoNCriteria(getItemClassDescriptor().getClassOfObject(), cols,\r\n crit, false);\r\n q.setIndirectionTable(getCollectionDescriptor().getIndirectionTable());\r\n q.setJdbcTypes(jdbcTypes);\r\n\r\n CollectionDescriptor cds = getCollectionDescriptor();\r\n //check if collection must be ordered\r\n if (!cds.getOrderBy().isEmpty())\r\n {\r\n Iterator iter = cds.getOrderBy().iterator();\r\n while (iter.hasNext())\r\n {\r\n q.addOrderBy((FieldHelper) iter.next());\r\n }\r\n }\r\n \r\n return q;\r\n }", "private void handleIncomingRequestMessage(SerialMessage incomingMessage) {\n\t\tlogger.debug(\"Message type = REQUEST\");\n\t\tswitch (incomingMessage.getMessageClass()) {\n\t\t\tcase ApplicationCommandHandler:\n\t\t\t\thandleApplicationCommandRequest(incomingMessage);\n\t\t\t\tbreak;\n\t\t\tcase SendData:\n\t\t\t\thandleSendDataRequest(incomingMessage);\n\t\t\t\tbreak;\n\t\t\tcase ApplicationUpdate:\n\t\t\t\thandleApplicationUpdateRequest(incomingMessage);\n\t\t\t\tbreak;\n\t\tdefault:\n\t\t\tlogger.warn(String.format(\"TODO: Implement processing of Request Message = %s (0x%02X)\",\n\t\t\t\t\tincomingMessage.getMessageClass().getLabel(),\n\t\t\t\t\tincomingMessage.getMessageClass().getKey()));\n\t\t\tbreak;\t\n\t\t}\n\t}", "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 }" ]
Append Join for SQL92 Syntax without parentheses
[ "private void appendJoinSQL92NoParen(Join join, StringBuffer where, StringBuffer buf)\r\n {\r\n if (join.isOuter)\r\n {\r\n buf.append(\" LEFT OUTER JOIN \");\r\n }\r\n else\r\n {\r\n buf.append(\" INNER JOIN \");\r\n }\r\n\r\n buf.append(join.right.getTableAndAlias());\r\n buf.append(\" ON \");\r\n join.appendJoinEqualities(buf);\r\n\r\n appendTableWithJoins(join.right, where, buf);\r\n }" ]
[ "public Object remove(String name) {\n\t\tThreadScopeContext context = ThreadScopeContextHolder.getContext();\n\t\treturn context.remove(name);\n\t}", "protected void load()\r\n {\r\n // properties file may be set as a System property.\r\n // if no property is set take default name.\r\n String fn = System.getProperty(OJB_PROPERTIES_FILE, OJB_PROPERTIES_FILE);\r\n setFilename(fn);\r\n super.load();\r\n\r\n // default repository & connection descriptor file\r\n repositoryFilename = getString(\"repositoryFile\", OJB_METADATA_FILE);\r\n\r\n // object cache class\r\n objectCacheClass = getClass(\"ObjectCacheClass\", ObjectCacheDefaultImpl.class, ObjectCache.class);\r\n\r\n // load PersistentField Class\r\n persistentFieldClass =\r\n getClass(\"PersistentFieldClass\", PersistentFieldDirectImpl.class, PersistentField.class);\r\n\r\n // load PersistenceBroker Class\r\n persistenceBrokerClass =\r\n getClass(\"PersistenceBrokerClass\", PersistenceBrokerImpl.class, PersistenceBroker.class);\r\n\r\n // load ListProxy Class\r\n listProxyClass = getClass(\"ListProxyClass\", ListProxyDefaultImpl.class);\r\n\r\n // load SetProxy Class\r\n setProxyClass = getClass(\"SetProxyClass\", SetProxyDefaultImpl.class);\r\n\r\n // load CollectionProxy Class\r\n collectionProxyClass = getClass(\"CollectionProxyClass\", CollectionProxyDefaultImpl.class);\r\n\r\n // load IndirectionHandler Class\r\n indirectionHandlerClass =\r\n getClass(\"IndirectionHandlerClass\", IndirectionHandlerJDKImpl.class, IndirectionHandler.class);\r\n \r\n // load ProxyFactory Class\r\n proxyFactoryClass =\r\n getClass(\"ProxyFactoryClass\", ProxyFactoryJDKImpl.class, ProxyFactory.class);\r\n\r\n // load configuration for ImplicitLocking parameter:\r\n useImplicitLocking = getBoolean(\"ImplicitLocking\", false);\r\n\r\n // load configuration for LockAssociations parameter:\r\n lockAssociationAsWrites = (getString(\"LockAssociations\", \"WRITE\").equalsIgnoreCase(\"WRITE\"));\r\n\r\n // load OQL Collection Class\r\n oqlCollectionClass = getClass(\"OqlCollectionClass\", DListImpl.class, ManageableCollection.class);\r\n\r\n // set the limit for IN-sql , -1 for no limits\r\n sqlInLimit = getInteger(\"SqlInLimit\", -1);\r\n\r\n //load configuration for PB pool\r\n maxActive = getInteger(PoolConfiguration.MAX_ACTIVE,\r\n PoolConfiguration.DEFAULT_MAX_ACTIVE);\r\n maxIdle = getInteger(PoolConfiguration.MAX_IDLE,\r\n PoolConfiguration.DEFAULT_MAX_IDLE);\r\n maxWait = getLong(PoolConfiguration.MAX_WAIT,\r\n PoolConfiguration.DEFAULT_MAX_WAIT);\r\n timeBetweenEvictionRunsMillis = getLong(PoolConfiguration.TIME_BETWEEN_EVICTION_RUNS_MILLIS,\r\n PoolConfiguration.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS);\r\n minEvictableIdleTimeMillis = getLong(PoolConfiguration.MIN_EVICTABLE_IDLE_TIME_MILLIS,\r\n PoolConfiguration.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS);\r\n whenExhaustedAction = getByte(PoolConfiguration.WHEN_EXHAUSTED_ACTION,\r\n PoolConfiguration.DEFAULT_WHEN_EXHAUSTED_ACTION);\r\n\r\n useSerializedRepository = getBoolean(\"useSerializedRepository\", false);\r\n }", "public AsciiTable setPaddingTopChar(Character paddingTopChar) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingTopChar(paddingTopChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public void process(String driverClass, String connectionString, String projectID, String outputFile) throws Exception\n {\n System.out.println(\"Reading Primavera database started.\");\n\n Class.forName(driverClass);\n Properties props = new Properties();\n\n //\n // This is not a very robust way to detect that we're working with SQLlite...\n // If you are trying to grab data from\n // a standalone P6 using SQLite, the SQLite JDBC driver needs this property\n // in order to correctly parse timestamps.\n //\n if (driverClass.equals(\"org.sqlite.JDBC\"))\n {\n props.setProperty(\"date_string_format\", \"yyyy-MM-dd HH:mm:ss\");\n }\n\n Connection c = DriverManager.getConnection(connectionString, props);\n PrimaveraDatabaseReader reader = new PrimaveraDatabaseReader();\n reader.setConnection(c);\n\n processProject(reader, Integer.parseInt(projectID), outputFile);\n }", "public LuaPreparedScript endPreparedScript(LuaScriptConfig config) {\n if (!endsWithReturnStatement()) {\n add(new LuaAstReturnStatement());\n }\n String scriptText = buildScriptText();\n ArrayList<LuaKeyArgument> keyList = new ArrayList<>(keyArg2AstArg.keySet());\n ArrayList<LuaValueArgument> argvList = new ArrayList<>(valueArg2AstArg.keySet());\n if (config.isThreadSafe()) {\n return new ThreadSafeLuaPreparedScript(scriptText, keyList, argvList, config);\n } else {\n return new BasicLuaPreparedScript(scriptText, keyList, argvList, config);\n }\n }", "public static void mark(DeploymentUnit unit) {\n unit = DeploymentUtils.getTopDeploymentUnit(unit);\n unit.putAttachment(MARKER, Boolean.TRUE);\n }", "public static void writeCorrelationId(Message message, String correlationId) {\n Map<String, List<String>> headers = getOrCreateProtocolHeader(message);\n headers.put(CORRELATIONID_HTTP_HEADER_NAME, Collections.singletonList(correlationId));\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"HTTP header '\" + CORRELATIONID_HTTP_HEADER_NAME + \"' set to: \" + correlationId);\n }\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 }", "private String getOrdinal(Integer value)\n {\n String result;\n int index = value.intValue();\n if (index >= ORDINAL.length)\n {\n result = \"every \" + index + \"th\";\n }\n else\n {\n result = ORDINAL[index];\n }\n return result;\n }" ]
Skips variable length blocks up to and including next zero length block.
[ "private void skip() {\n try {\n int blockSize;\n do {\n blockSize = read();\n rawData.position(rawData.position() + blockSize);\n } while (blockSize > 0);\n } catch (IllegalArgumentException ex) {\n }\n }" ]
[ "private static String get(Properties p, String key, String defaultValue, Set<String> used){\r\n String rtn = p.getProperty(key, defaultValue);\r\n used.add(key);\r\n return rtn;\r\n }", "public void commit() {\n if (directory == null)\n return;\n\n try {\n if (reader != null)\n reader.close();\n\n // it turns out that IndexWriter.optimize actually slows\n // searches down, because it invalidates the cache. therefore\n // not calling it any more.\n // http://www.searchworkings.org/blog/-/blogs/uwe-says%3A-is-your-reader-atomic\n // iwriter.optimize();\n\n iwriter.commit();\n openSearchers();\n } catch (IOException e) {\n throw new DukeException(e);\n }\n }", "public static double[][] pseudoInverse(double[][] matrix){\n\t\tif(isSolverUseApacheCommonsMath) {\n\t\t\t// Use LU from common math\n\t\t\tSingularValueDecomposition svd = new SingularValueDecomposition(new Array2DRowRealMatrix(matrix));\n\t\t\tdouble[][] matrixInverse = svd.getSolver().getInverse().getData();\n\n\t\t\treturn matrixInverse;\n\t\t}\n\t\telse {\n\t\t\treturn org.jblas.Solve.pinv(new org.jblas.DoubleMatrix(matrix)).toArray2();\n\t\t}\n\t}", "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 synchronized Schema getInputPathAvroSchema() throws IOException {\n if (inputPathAvroSchema == 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 inputPathAvroSchema = AvroUtils.getAvroSchemaFromPath(getInputPath());\n }\n return inputPathAvroSchema;\n }", "public boolean isBitwiseOrCompatibleWithRange(int maskValue, Integer segmentPrefixLength) throws PrefixLenException {\r\n\t\treturn super.isBitwiseOrCompatibleWithRange(maskValue, segmentPrefixLength, getNetwork().getPrefixConfiguration().allPrefixedAddressesAreSubnets());\r\n\t}", "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 }", "public void deployApplication(String applicationName, String... classpathLocations) throws IOException {\n\n final List<URL> classpathElements = Arrays.stream(classpathLocations)\n .map(classpath -> Thread.currentThread().getContextClassLoader().getResource(classpath))\n .collect(Collectors.toList());\n\n deployApplication(applicationName, classpathElements.toArray(new URL[classpathElements.size()]));\n }", "@JsonAnySetter\n public void setUnknownField(final String name, final Object value) {\n this.unknownFields.put(name, value);\n }" ]
Checks constraints on this model. @param checkLevel The amount of checks to perform @throws ConstraintException If a constraint has been violated
[ "public void checkConstraints(String checkLevel) throws ConstraintException\r\n {\r\n // check constraints now after all classes have been processed\r\n for (Iterator it = getClasses(); it.hasNext();)\r\n {\r\n ((ClassDescriptorDef)it.next()).checkConstraints(checkLevel);\r\n }\r\n // additional model constraints that either deal with bigger parts of the model or\r\n // can only be checked after the individual classes have been checked (e.g. specific\r\n // attributes have been ensured)\r\n new ModelConstraints().check(this, checkLevel);\r\n }" ]
[ "public static base_response add(nitro_service client, sslcipher resource) throws Exception {\n\t\tsslcipher addresource = new sslcipher();\n\t\taddresource.ciphergroupname = resource.ciphergroupname;\n\t\taddresource.ciphgrpalias = resource.ciphgrpalias;\n\t\treturn addresource.add_resource(client);\n\t}", "private static List<String> parseAndCompare(List<String> fileNames, int masterPartitionId) {\n List<String> sourceFileNames = new ArrayList<String>();\n for(String fileName: fileNames) {\n String[] partitionIdReplicaChunk = fileName.split(SPLIT_LITERAL);\n if(Integer.parseInt(partitionIdReplicaChunk[0]) == masterPartitionId) {\n sourceFileNames.add(fileName);\n }\n }\n return sourceFileNames;\n }", "public static DMatrixRMaj diagonal(int N , double min , double max , Random rand ) {\n return diagonal(N,N,min,max,rand);\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 prepare() throws IOException, DocumentException, PrintingException {\n\t\tif (baos == null) {\n\t\t\tbaos = new ByteArrayOutputStream(); // let it grow as much as needed\n\t\t}\n\t\tbaos.reset();\n\t\tboolean resize = false;\n\t\tif (page.getConstraint().getWidth() == 0 || page.getConstraint().getHeight() == 0) {\n\t\t\tresize = true;\n\t\t}\n\t\t// Create a document in the requested ISO scale.\n\t\tDocument document = new Document(page.getBounds(), 0, 0, 0, 0);\n\t\tPdfWriter writer;\n\t\twriter = PdfWriter.getInstance(document, baos);\n\n\t\t// Render in correct colors for transparent rasters\n\t\twriter.setRgbTransparencyBlending(true);\n\n\t\t// The mapView is not scaled to the document, we assume the mapView\n\t\t// has the right ratio.\n\n\t\t// Write document title and metadata\n\t\tdocument.open();\n\t\tPdfContext context = new PdfContext(writer);\n\t\tcontext.initSize(page.getBounds());\n\t\t// first pass of all children to calculate size\n\t\tpage.calculateSize(context);\n\t\tif (resize) {\n\t\t\t// we now know the bounds of the document\n\t\t\t// round 'm up and restart with a new document\n\t\t\tint width = (int) Math.ceil(page.getBounds().getWidth());\n\t\t\tint height = (int) Math.ceil(page.getBounds().getHeight());\n\t\t\tpage.getConstraint().setWidth(width);\n\t\t\tpage.getConstraint().setHeight(height);\n\n\t\t\tdocument = new Document(new Rectangle(width, height), 0, 0, 0, 0);\n\t\t\twriter = PdfWriter.getInstance(document, baos);\n\t\t\t// Render in correct colors for transparent rasters\n\t\t\twriter.setRgbTransparencyBlending(true);\n\n\t\t\tdocument.open();\n\t\t\tbaos.reset();\n\t\t\tcontext = new PdfContext(writer);\n\t\t\tcontext.initSize(page.getBounds());\n\t\t}\n\t\t// int compressionLevel = writer.getCompressionLevel(); // For testing\n\t\t// writer.setCompressionLevel(0);\n\n\t\t// Actual drawing\n\t\tdocument.addTitle(\"Geomajas\");\n\t\t// second pass to layout\n\t\tpage.layout(context);\n\t\t// finally render (uses baos)\n\t\tpage.render(context);\n\n\t\tdocument.add(context.getImage());\n\t\t// Now close the document\n\t\tdocument.close();\n\t}", "private boolean ensureValidSetter(final Expression expression, final Expression leftExpression, final Expression rightExpression, final SetterInfo setterInfo) {\n // for expressions like foo = { ... }\n // we know that the RHS type is a closure\n // but we must check if the binary expression is an assignment\n // because we need to check if a setter uses @DelegatesTo\n VariableExpression ve = new VariableExpression(\"%\", setterInfo.receiverType);\n MethodCallExpression call = new MethodCallExpression(\n ve,\n setterInfo.name,\n rightExpression\n );\n call.setImplicitThis(false);\n visitMethodCallExpression(call);\n MethodNode directSetterCandidate = call.getNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET);\n if (directSetterCandidate==null) {\n // this may happen if there's a setter of type boolean/String/Class, and that we are using the property\n // notation AND that the RHS is not a boolean/String/Class\n for (MethodNode setter : setterInfo.setters) {\n ClassNode type = getWrapper(setter.getParameters()[0].getOriginType());\n if (Boolean_TYPE.equals(type) || STRING_TYPE.equals(type) || CLASS_Type.equals(type)) {\n call = new MethodCallExpression(\n ve,\n setterInfo.name,\n new CastExpression(type,rightExpression)\n );\n call.setImplicitThis(false);\n visitMethodCallExpression(call);\n directSetterCandidate = call.getNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET);\n if (directSetterCandidate!=null) {\n break;\n }\n }\n }\n }\n if (directSetterCandidate != null) {\n for (MethodNode setter : setterInfo.setters) {\n if (setter == directSetterCandidate) {\n leftExpression.putNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET, directSetterCandidate);\n storeType(leftExpression, getType(rightExpression));\n break;\n }\n }\n } else {\n ClassNode firstSetterType = setterInfo.setters.iterator().next().getParameters()[0].getOriginType();\n addAssignmentError(firstSetterType, getType(rightExpression), expression);\n return true;\n }\n return false;\n }", "public GVRAnimation setDuration(float start, float end)\n {\n if(start>end || start<0 || end>mDuration){\n throw new IllegalArgumentException(\"start and end values are wrong\");\n }\n animationOffset = start;\n mDuration = end-start;\n return this;\n }", "public static final long getLong(byte[] data, int offset)\n {\n if (data.length != 8)\n {\n throw new UnexpectedStructureException();\n }\n\n long result = 0;\n int i = offset;\n for (int shiftBy = 0; shiftBy < 64; shiftBy += 8)\n {\n result |= ((long) (data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }", "private Duration getDuration(Double duration)\n {\n Duration result = null;\n\n if (duration != null)\n {\n result = Duration.getInstance(NumberHelper.getDouble(duration), TimeUnit.HOURS);\n }\n\n return result;\n }" ]
Create an MD5 hash of a string. @param input Input string. @return Hash of input. @throws IllegalArgumentException if {@code input} is blank.
[ "static String md5(String input) {\n if (input == null || input.length() == 0) {\n throw new IllegalArgumentException(\"Input string must not be blank.\");\n }\n try {\n MessageDigest algorithm = MessageDigest.getInstance(\"MD5\");\n algorithm.reset();\n algorithm.update(input.getBytes());\n byte[] messageDigest = algorithm.digest();\n\n StringBuilder hexString = new StringBuilder();\n for (byte messageByte : messageDigest) {\n hexString.append(Integer.toHexString((messageByte & 0xFF) | 0x100).substring(1, 3));\n }\n return hexString.toString();\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }" ]
[ "private final void replyErrors(final String errorMessage,\n final String stackTrace, final String statusCode,\n final int statusCodeInt) {\n reply(true, errorMessage, stackTrace, statusCode, statusCodeInt,\n PcConstants.NA, null);\n\n }", "public 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 boolean isFalse(Expression expression) {\r\n if (expression == null) {\r\n return false;\r\n }\r\n if (expression instanceof PropertyExpression && classNodeImplementsType(((PropertyExpression) expression).getObjectExpression().getType(), Boolean.class)) {\r\n if (((PropertyExpression) expression).getProperty() instanceof ConstantExpression\r\n && \"FALSE\".equals(((ConstantExpression) ((PropertyExpression) expression).getProperty()).getValue())) {\r\n return true;\r\n }\r\n }\r\n return ((expression instanceof ConstantExpression) && ((ConstantExpression) expression).isFalseExpression())\r\n || \"Boolean.FALSE\".equals(expression.getText());\r\n }", "public static authenticationvserver_authenticationtacacspolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_authenticationtacacspolicy_binding obj = new authenticationvserver_authenticationtacacspolicy_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_authenticationtacacspolicy_binding response[] = (authenticationvserver_authenticationtacacspolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private void addDefaults()\n {\n this.issueCategories.putIfAbsent(MANDATORY, new IssueCategory(MANDATORY, IssueCategoryRegistry.class.getCanonicalName(), \"Mandatory\", MANDATORY, 1000, true));\n this.issueCategories.putIfAbsent(OPTIONAL, new IssueCategory(OPTIONAL, IssueCategoryRegistry.class.getCanonicalName(), \"Optional\", OPTIONAL, 1000, true));\n this.issueCategories.putIfAbsent(POTENTIAL, new IssueCategory(POTENTIAL, IssueCategoryRegistry.class.getCanonicalName(), \"Potential Issues\", POTENTIAL, 1000, true));\n this.issueCategories.putIfAbsent(CLOUD_MANDATORY, new IssueCategory(CLOUD_MANDATORY, IssueCategoryRegistry.class.getCanonicalName(), \"Cloud Mandatory\", CLOUD_MANDATORY, 1000, true));\n this.issueCategories.putIfAbsent(INFORMATION, new IssueCategory(INFORMATION, IssueCategoryRegistry.class.getCanonicalName(), \"Information\", INFORMATION, 1000, true));\n }", "public void sendFaderStartCommand(Set<Integer> deviceNumbersToStart, Set<Integer> deviceNumbersToStop) throws IOException {\n ensureRunning();\n byte[] payload = new byte[FADER_START_PAYLOAD.length];\n System.arraycopy(FADER_START_PAYLOAD, 0, payload, 0, FADER_START_PAYLOAD.length);\n payload[2] = getDeviceNumber();\n\n for (int i = 1; i <= 4; i++) {\n if (deviceNumbersToStart.contains(i)) {\n payload[i + 4] = 0;\n }\n if (deviceNumbersToStop.contains(i)) {\n payload[i + 4] = 1;\n }\n }\n\n assembleAndSendPacket(Util.PacketType.FADER_START_COMMAND, payload, getBroadcastAddress(), BeatFinder.BEAT_PORT);\n }", "public static void setLocale(ProjectProperties properties, Locale locale)\n {\n properties.setMpxDelimiter(LocaleData.getChar(locale, LocaleData.FILE_DELIMITER));\n properties.setMpxProgramName(LocaleData.getString(locale, LocaleData.PROGRAM_NAME));\n properties.setMpxCodePage((CodePage) LocaleData.getObject(locale, LocaleData.CODE_PAGE));\n\n properties.setCurrencySymbol(LocaleData.getString(locale, LocaleData.CURRENCY_SYMBOL));\n properties.setSymbolPosition((CurrencySymbolPosition) LocaleData.getObject(locale, LocaleData.CURRENCY_SYMBOL_POSITION));\n properties.setCurrencyDigits(LocaleData.getInteger(locale, LocaleData.CURRENCY_DIGITS));\n properties.setThousandsSeparator(LocaleData.getChar(locale, LocaleData.CURRENCY_THOUSANDS_SEPARATOR));\n properties.setDecimalSeparator(LocaleData.getChar(locale, LocaleData.CURRENCY_DECIMAL_SEPARATOR));\n\n properties.setDateOrder((DateOrder) LocaleData.getObject(locale, LocaleData.DATE_ORDER));\n properties.setTimeFormat((ProjectTimeFormat) LocaleData.getObject(locale, LocaleData.TIME_FORMAT));\n properties.setDefaultStartTime(DateHelper.getTimeFromMinutesPastMidnight(LocaleData.getInteger(locale, LocaleData.DEFAULT_START_TIME)));\n properties.setDateSeparator(LocaleData.getChar(locale, LocaleData.DATE_SEPARATOR));\n properties.setTimeSeparator(LocaleData.getChar(locale, LocaleData.TIME_SEPARATOR));\n properties.setAMText(LocaleData.getString(locale, LocaleData.AM_TEXT));\n properties.setPMText(LocaleData.getString(locale, LocaleData.PM_TEXT));\n properties.setDateFormat((ProjectDateFormat) LocaleData.getObject(locale, LocaleData.DATE_FORMAT));\n properties.setBarTextDateFormat((ProjectDateFormat) LocaleData.getObject(locale, LocaleData.DATE_FORMAT));\n }", "private void deliverFaderStartCommand(Set<Integer> playersToStart, Set<Integer> playersToStop) {\n for (final FaderStartListener listener : getFaderStartListeners()) {\n try {\n listener.fadersChanged(playersToStart, playersToStop);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering fader start command to listener\", t);\n }\n }\n }", "public void signIn(String key, Collection<WebSocketConnection> connections) {\n if (connections.isEmpty()) {\n return;\n }\n Map<WebSocketConnection, WebSocketConnection> newMap = new HashMap<>();\n for (WebSocketConnection conn : connections) {\n newMap.put(conn, conn);\n }\n ConcurrentMap<WebSocketConnection, WebSocketConnection> bag = ensureConnectionList(key);\n bag.putAll(newMap);\n }" ]
Set OAuth 1 authentication credentials for the replication target @param consumerSecret client secret @param consumerKey client identifier @param tokenSecret OAuth server token secret @param token OAuth server issued token @return this Replication instance to set more options or trigger the replication
[ "public Replication targetOauth(String consumerSecret,\r\n String consumerKey, String tokenSecret, String token) {\r\n this.replication = replication.targetOauth(consumerSecret, consumerKey,\r\n tokenSecret, token);\r\n return this;\r\n }" ]
[ "private Envelope getLayerEnvelope(ProxyLayerSupport layer) {\n\t\tBbox bounds = layer.getLayerInfo().getMaxExtent();\n\t\treturn new Envelope(bounds.getX(), bounds.getMaxX(), bounds.getY(), bounds.getMaxY());\n\t}", "public static int isValid( DMatrixRMaj cov ) {\n if( !MatrixFeatures_DDRM.isDiagonalPositive(cov) )\n return 1;\n\n if( !MatrixFeatures_DDRM.isSymmetric(cov,TOL) )\n return 2;\n\n if( !MatrixFeatures_DDRM.isPositiveSemidefinite(cov) )\n return 3;\n\n return 0;\n }", "public static double I(int n, double x) {\r\n if (n < 0)\r\n throw new IllegalArgumentException(\"the variable n out of range.\");\r\n else if (n == 0)\r\n return I0(x);\r\n else if (n == 1)\r\n return I(x);\r\n\r\n if (x == 0.0)\r\n return 0.0;\r\n\r\n double ACC = 40.0;\r\n double BIGNO = 1.0e+10;\r\n double BIGNI = 1.0e-10;\r\n\r\n double tox = 2.0 / Math.abs(x);\r\n double bip = 0, ans = 0.0;\r\n double bi = 1.0;\r\n\r\n for (int j = 2 * (n + (int) Math.sqrt(ACC * n)); j > 0; j--) {\r\n double bim = bip + j * tox * bi;\r\n bip = bi;\r\n bi = bim;\r\n\r\n if (Math.abs(bi) > BIGNO) {\r\n ans *= BIGNI;\r\n bi *= BIGNI;\r\n bip *= BIGNI;\r\n }\r\n\r\n if (j == n)\r\n ans = bip;\r\n }\r\n\r\n ans *= I0(x) / bi;\r\n return x < 0.0 && n % 2 == 1 ? -ans : ans;\r\n }", "public boolean isActive(int profileId) {\n boolean active = false;\n PreparedStatement queryStatement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT \" + Constants.CLIENT_IS_ACTIVE + \" FROM \" + Constants.DB_TABLE_CLIENT +\n \" WHERE \" + Constants.GENERIC_CLIENT_UUID + \"= '-1' \" +\n \" AND \" + Constants.GENERIC_PROFILE_ID + \"= ? \"\n );\n queryStatement.setInt(1, profileId);\n logger.info(queryStatement.toString());\n ResultSet results = queryStatement.executeQuery();\n if (results.next()) {\n active = results.getBoolean(Constants.CLIENT_IS_ACTIVE);\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return active;\n }", "public static String getXPathExpression(Node node) {\n\t\tObject xpathCache = node.getUserData(FULL_XPATH_CACHE);\n\t\tif (xpathCache != null) {\n\t\t\treturn xpathCache.toString();\n\t\t}\n\t\tNode parent = node.getParentNode();\n\n\t\tif ((parent == null) || parent.getNodeName().contains(\"#document\")) {\n\t\t\tString xPath = \"/\" + node.getNodeName() + \"[1]\";\n\t\t\tnode.setUserData(FULL_XPATH_CACHE, xPath, null);\n\t\t\treturn xPath;\n\t\t}\n\n\t\tif (node.hasAttributes() && node.getAttributes().getNamedItem(\"id\") != null) {\n\t\t\tString xPath = \"//\" + node.getNodeName() + \"[@id = '\"\n\t\t\t\t\t+ node.getAttributes().getNamedItem(\"id\").getNodeValue() + \"']\";\n\t\t\tnode.setUserData(FULL_XPATH_CACHE, xPath, null);\n\t\t\treturn xPath;\n\t\t}\n\n\t\tStringBuffer buffer = new StringBuffer();\n\n\t\tif (parent != node) {\n\t\t\tbuffer.append(getXPathExpression(parent));\n\t\t\tbuffer.append(\"/\");\n\t\t}\n\n\t\tbuffer.append(node.getNodeName());\n\n\t\tList<Node> mySiblings = getSiblings(parent, node);\n\n\t\tfor (int i = 0; i < mySiblings.size(); i++) {\n\t\t\tNode el = mySiblings.get(i);\n\n\t\t\tif (el.equals(node)) {\n\t\t\t\tbuffer.append('[').append(Integer.toString(i + 1)).append(']');\n\t\t\t\t// Found so break;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tString xPath = buffer.toString();\n\t\tnode.setUserData(FULL_XPATH_CACHE, xPath, null);\n\t\treturn xPath;\n\t}", "public ModelNode registerDeploymentSubsystemResource(final String subsystemName, final Resource resource) {\n assert subsystemName != null : \"The subsystemName cannot be null\";\n assert resource != null : \"The resource cannot be null\";\n return registerDeploymentSubResource(subsystemName, PathAddress.EMPTY_ADDRESS, resource);\n }", "public List<String> invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {\n MavenProject mavenProject = getMavenProject(f.getAbsolutePath());\n return mavenProject.getModel().getModules();\n }", "public static base_responses add(nitro_service client, nsacl6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsacl6 addresources[] = new nsacl6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new nsacl6();\n\t\t\t\taddresources[i].acl6name = resources[i].acl6name;\n\t\t\t\taddresources[i].acl6action = resources[i].acl6action;\n\t\t\t\taddresources[i].td = resources[i].td;\n\t\t\t\taddresources[i].srcipv6 = resources[i].srcipv6;\n\t\t\t\taddresources[i].srcipop = resources[i].srcipop;\n\t\t\t\taddresources[i].srcipv6val = resources[i].srcipv6val;\n\t\t\t\taddresources[i].srcport = resources[i].srcport;\n\t\t\t\taddresources[i].srcportop = resources[i].srcportop;\n\t\t\t\taddresources[i].srcportval = resources[i].srcportval;\n\t\t\t\taddresources[i].destipv6 = resources[i].destipv6;\n\t\t\t\taddresources[i].destipop = resources[i].destipop;\n\t\t\t\taddresources[i].destipv6val = resources[i].destipv6val;\n\t\t\t\taddresources[i].destport = resources[i].destport;\n\t\t\t\taddresources[i].destportop = resources[i].destportop;\n\t\t\t\taddresources[i].destportval = resources[i].destportval;\n\t\t\t\taddresources[i].ttl = resources[i].ttl;\n\t\t\t\taddresources[i].srcmac = resources[i].srcmac;\n\t\t\t\taddresources[i].protocol = resources[i].protocol;\n\t\t\t\taddresources[i].protocolnumber = resources[i].protocolnumber;\n\t\t\t\taddresources[i].vlan = resources[i].vlan;\n\t\t\t\taddresources[i].Interface = resources[i].Interface;\n\t\t\t\taddresources[i].established = resources[i].established;\n\t\t\t\taddresources[i].icmptype = resources[i].icmptype;\n\t\t\t\taddresources[i].icmpcode = resources[i].icmpcode;\n\t\t\t\taddresources[i].priority = resources[i].priority;\n\t\t\t\taddresources[i].state = resources[i].state;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "private void deliverFaderStartCommand(Set<Integer> playersToStart, Set<Integer> playersToStop) {\n for (final FaderStartListener listener : getFaderStartListeners()) {\n try {\n listener.fadersChanged(playersToStart, playersToStop);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering fader start command to listener\", t);\n }\n }\n }" ]
Closes the transactor node by removing its node in Zookeeper
[ "@Override\n public void close() {\n status = TrStatus.CLOSED;\n try {\n node.close();\n } catch (IOException e) {\n log.error(\"Failed to close ephemeral node\");\n throw new IllegalStateException(e);\n }\n }" ]
[ "public void handleChannelClosed(final Channel closed, final IOException e) {\n for(final ActiveOperationImpl<?, ?> activeOperation : activeRequests.values()) {\n if (activeOperation.getChannel() == closed) {\n // Only call cancel, to also interrupt still active threads\n activeOperation.getResultHandler().cancel();\n }\n }\n }", "public void writeNameValuePair(String name, Date value) throws IOException\n {\n internalWriteNameValuePair(name, m_format.format(value));\n }", "private static JSONObject parseTarget(Shape target) throws JSONException {\n JSONObject targetObject = new JSONObject();\n\n targetObject.put(\"resourceId\",\n target.getResourceId().toString());\n\n return targetObject;\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 static AppDescriptor of(String appName, String packageName) {\n String[] packages = packageName.split(S.COMMON_SEP);\n return of(appName, packageName, Version.ofPackage(packages[0]));\n }", "public static Span toSpan(Range range) {\n return new Span(toRowColumn(range.getStartKey()), range.isStartKeyInclusive(),\n toRowColumn(range.getEndKey()), range.isEndKeyInclusive());\n }", "public static boolean updateImageParentOnAgents(final JenkinsBuildInfoLog log, final String imageTag, final String host, final int buildInfoId) throws IOException, InterruptedException {\n boolean parentUpdated = updateImageParent(log, imageTag, host, buildInfoId);\n List<Node> nodes = Jenkins.getInstance().getNodes();\n for (Node node : nodes) {\n if (node == null || node.getChannel() == null) {\n continue;\n }\n boolean parentNodeUpdated = node.getChannel().call(new MasterToSlaveCallable<Boolean, IOException>() {\n public Boolean call() throws IOException {\n return updateImageParent(log, imageTag, host, buildInfoId);\n }\n });\n parentUpdated = parentUpdated ? parentUpdated : parentNodeUpdated;\n }\n return parentUpdated;\n }", "@Override\n public List<Integer> getReplicatingPartitionList(int index) {\n List<Node> preferenceNodesList = new ArrayList<Node>(getNumReplicas());\n List<Integer> replicationPartitionsList = new ArrayList<Integer>(getNumReplicas());\n\n // Copy Zone based Replication Factor\n HashMap<Integer, Integer> requiredRepFactor = new HashMap<Integer, Integer>();\n requiredRepFactor.putAll(zoneReplicationFactor);\n\n // Cross-check if individual zone replication factor equals global\n int sum = 0;\n for(Integer zoneRepFactor: requiredRepFactor.values()) {\n sum += zoneRepFactor;\n }\n\n if(sum != getNumReplicas())\n throw new IllegalArgumentException(\"Number of zone replicas is not equal to the total replication factor\");\n\n if(getPartitionToNode().length == 0) {\n return new ArrayList<Integer>(0);\n }\n\n for(int i = 0; i < getPartitionToNode().length; i++) {\n // add this one if we haven't already, and it can satisfy some zone\n // replicationFactor\n Node currentNode = getNodeByPartition(index);\n if(!preferenceNodesList.contains(currentNode)) {\n preferenceNodesList.add(currentNode);\n if(checkZoneRequirement(requiredRepFactor, currentNode.getZoneId()))\n replicationPartitionsList.add(index);\n }\n\n // if we have enough, go home\n if(replicationPartitionsList.size() >= getNumReplicas())\n return replicationPartitionsList;\n // move to next clockwise slot on the ring\n index = (index + 1) % getPartitionToNode().length;\n }\n\n // we don't have enough, but that may be okay\n return replicationPartitionsList;\n }", "private int[] changeColor() {\n int[] changedPixels = new int[pixels.length];\n double frequenz = 2 * Math.PI / 1020;\n\n for (int i = 0; i < pixels.length; i++) {\n int argb = pixels[i];\n int a = (argb >> 24) & 0xff;\n int r = (argb >> 16) & 0xff;\n int g = (argb >> 8) & 0xff;\n int b = argb & 0xff;\n\n r = (int) (255 * Math.sin(frequenz * r));\n b = (int) (-255 * Math.cos(frequenz * b) + 255);\n\n changedPixels[i] = (a << 24) | (r << 16) | (g << 8) | b;\n }\n\n return changedPixels;\n }" ]
Populate the UDF values for this entity. @param tableName parent table name @param type entity type @param container entity @param uniqueID entity Unique ID
[ "private void populateUserDefinedFieldValues(String tableName, FieldTypeClass type, FieldContainer container, Integer uniqueID)\n {\n Map<Integer, List<Row>> tableData = m_udfValues.get(tableName);\n if (tableData != null)\n {\n List<Row> udf = tableData.get(uniqueID);\n if (udf != null)\n {\n for (Row r : udf)\n {\n addUDFValue(type, container, r);\n }\n }\n }\n }" ]
[ "public void schedule(BackoffTask task, long initialDelay, long fixedDelay) {\n \tsynchronized (queue) {\n\t \tstart();\n\t queue.put(new DelayedTimerTask(task, initialDelay, fixedDelay));\n \t}\n }", "private boolean isCacheable(PipelineContext context) throws GeomajasException {\n\t\tVectorLayer layer = context.get(PipelineCode.LAYER_KEY, VectorLayer.class);\n\t\treturn !(layer instanceof VectorLayerLazyFeatureConversionSupport &&\n\t\t\t\t((VectorLayerLazyFeatureConversionSupport) layer).useLazyFeatureConversion());\n\t}", "public String generateDigest(InputStream stream) {\n MessageDigest digest = null;\n try {\n digest = MessageDigest.getInstance(DIGEST_ALGORITHM_SHA1);\n } catch (NoSuchAlgorithmException ae) {\n throw new BoxAPIException(\"Digest algorithm not found\", ae);\n }\n\n //Calcuate the digest using the stream.\n DigestInputStream dis = new DigestInputStream(stream, digest);\n try {\n int value = dis.read();\n while (value != -1) {\n value = dis.read();\n }\n } catch (IOException ioe) {\n throw new BoxAPIException(\"Reading the stream failed.\", ioe);\n }\n\n //Get the calculated digest for the stream\n byte[] digestBytes = digest.digest();\n return Base64.encode(digestBytes);\n }", "public void setBundleActivator(String bundleActivator) {\n\t\tString old = mainAttributes.get(BUNDLE_ACTIVATOR);\n\t\tif (!bundleActivator.equals(old)) {\n\t\t\tthis.mainAttributes.put(BUNDLE_ACTIVATOR, bundleActivator);\n\t\t\tthis.modified = true;\n\t\t\tthis.bundleActivator = bundleActivator;\n\t\t}\n\t}", "public static Map<String, String[]> mapUrlEncodedParameters(byte[] dataArray) throws Exception {\n Map<String, String[]> mapPostParameters = new HashMap<String, String[]>();\n\n try {\n ByteArrayOutputStream byteout = new ByteArrayOutputStream();\n for (int x = 0; x < dataArray.length; x++) {\n // split the data up by & to get the parts\n if (dataArray[x] == '&' || x == (dataArray.length - 1)) {\n if (x == (dataArray.length - 1)) {\n byteout.write(dataArray[x]);\n }\n // find '=' and split the data up into key value pairs\n int equalsPos = -1;\n ByteArrayOutputStream key = new ByteArrayOutputStream();\n ByteArrayOutputStream value = new ByteArrayOutputStream();\n byte[] byteArray = byteout.toByteArray();\n for (int xx = 0; xx < byteArray.length; xx++) {\n if (byteArray[xx] == '=') {\n equalsPos = xx;\n } else {\n if (equalsPos == -1) {\n key.write(byteArray[xx]);\n } else {\n value.write(byteArray[xx]);\n }\n }\n }\n\n ArrayList<String> values = new ArrayList<String>();\n\n if (mapPostParameters.containsKey(key.toString())) {\n values = new ArrayList<String>(Arrays.asList(mapPostParameters.get(key.toString())));\n mapPostParameters.remove(key.toString());\n }\n\n values.add(value.toString());\n /**\n * If equalsPos is not -1, then there was a '=' for the key\n * If value.size is 0, then there is no value so want to add in the '='\n * Since it will not be added later like params with keys and valued\n */\n if (equalsPos != -1 && value.size() == 0) {\n key.write((byte) '=');\n }\n\n mapPostParameters.put(key.toString(), values.toArray(new String[values.size()]));\n\n byteout = new ByteArrayOutputStream();\n } else {\n byteout.write(dataArray[x]);\n }\n }\n } catch (Exception e) {\n throw new Exception(\"Could not parse request data: \" + e.getMessage());\n }\n\n return mapPostParameters;\n }", "public final int toChars(int[] src, int srcOff, int srcLen, char[] dest, int destOff) {\n if (srcLen < 0) {\n throw new IllegalArgumentException(\"srcLen must be >= 0\");\n }\n int written = 0;\n for (int i = 0; i < srcLen; ++i) {\n written += Character.toChars(src[srcOff + i], dest, destOff + written);\n }\n return written;\n }", "List getOrderby()\r\n {\r\n List result = _getOrderby();\r\n Iterator iter = getCriteria().iterator();\r\n Object crit;\r\n\r\n while (iter.hasNext())\r\n {\r\n crit = iter.next();\r\n if (crit instanceof Criteria)\r\n {\r\n result.addAll(((Criteria) crit).getOrderby());\r\n }\r\n }\r\n\r\n return result;\r\n }", "public void setSpeed(float newValue) {\n if (newValue < 0) newValue = 0;\n this.pitch.setValue( newValue );\n this.speed.setValue( newValue );\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 }" ]
Initializes communication with the Z-Wave controller stick.
[ "public void initialize() {\n\t\tthis.enqueue(new SerialMessage(SerialMessage.SerialMessageClass.GetVersion, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.GetVersion, SerialMessage.SerialMessagePriority.High));\n\t\tthis.enqueue(new SerialMessage(SerialMessage.SerialMessageClass.MemoryGetId, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.MemoryGetId, SerialMessage.SerialMessagePriority.High));\n\t\tthis.enqueue(new SerialMessage(SerialMessage.SerialMessageClass.SerialApiGetCapabilities, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.SerialApiGetCapabilities, SerialMessage.SerialMessagePriority.High));\n\t}" ]
[ "public static java.util.Date newDateTime() {\n return new java.util.Date((System.currentTimeMillis() / SECOND_MILLIS) * SECOND_MILLIS);\n }", "protected void recordPreparedOperation(final ServerIdentity identity, final TransactionalProtocolClient.PreparedOperation<ServerTaskExecutor.ServerOperation> prepared) {\n final ModelNode preparedResult = prepared.getPreparedResult();\n // Hmm do the server results need to get translated as well as the host one?\n // final ModelNode transformedResult = prepared.getOperation().transformResult(preparedResult);\n updatePolicy.recordServerResult(identity, preparedResult);\n executor.recordPreparedOperation(prepared);\n }", "void fileWritten() throws ConfigurationPersistenceException {\n if (!doneBootup.get() || interactionPolicy.isReadOnly()) {\n return;\n }\n try {\n FilePersistenceUtils.copyFile(mainFile, lastFile);\n } catch (IOException e) {\n throw ControllerLogger.ROOT_LOGGER.failedToBackup(e, mainFile);\n }\n }", "public static SimpleMatrix diag( Class type, double ...vals ) {\n SimpleMatrix M = new SimpleMatrix(vals.length,vals.length,type);\n for (int i = 0; i < vals.length; i++) {\n M.set(i,i,vals[i]);\n }\n return M;\n }", "public static JRDesignExpression getDataSourceExpression(DJDataSource ds) {\n JRDesignExpression exp = new JRDesignExpression();\n exp.setValueClass(JRDataSource.class);\n\n String dsType = getDataSourceTypeStr(ds.getDataSourceType());\n String expText = null;\n if (ds.getDataSourceOrigin() == DJConstants.DATA_SOURCE_ORIGIN_FIELD) {\n expText = dsType + \"$F{\" + ds.getDataSourceExpression() + \"})\";\n } else if (ds.getDataSourceOrigin() == DJConstants.DATA_SOURCE_ORIGIN_PARAMETER) {\n expText = dsType + REPORT_PARAMETERS_MAP + \".get( \\\"\" + ds.getDataSourceExpression() + \"\\\" ) )\";\n } else if (ds.getDataSourceOrigin() == DJConstants.DATA_SOURCE_TYPE_SQL_CONNECTION) {\n expText = dsType + REPORT_PARAMETERS_MAP + \".get( \\\"\" + ds.getDataSourceExpression() + \"\\\" ) )\";\n } else if (ds.getDataSourceOrigin() == DJConstants.DATA_SOURCE_ORIGIN_REPORT_DATASOURCE) {\n expText = \"((\" + JRDataSource.class.getName() + \") $P{REPORT_DATA_SOURCE})\";\n }\n\n exp.setText(expText);\n\n return exp;\n }", "HtmlTag attr(String name, String value) {\n if (attrs == null) {\n attrs = new HashMap<>();\n }\n attrs.put(name, value);\n return this;\n }", "public void addAppenderEvent(final Category cat, final Appender appender) {\n\n\t\tupdateDefaultLayout(appender);\n\n\t\tif (appender instanceof FoundationFileRollingAppender) {\n\t\t\tfinal FoundationFileRollingAppender timeSizeRollingAppender = (FoundationFileRollingAppender) appender;\n\n\t\t\t// update the appender with default vales such as logging pattern, file size etc.\n\t\t\t//updateDefaultTimeAndSizeRollingAppender(timeSizeRollingAppender);\n\n\t\t\t// read teh proeprties and determine if archiving should be enabled.\n\t\t\tupdateArchivingSupport(timeSizeRollingAppender);\n\n\t\t\t// by default add the rolling file listener to enable application\n\t\t\t// state.\n\t\t\ttimeSizeRollingAppender.setFileRollEventListener(FoundationRollEventListener.class.getName());\n\n\t\t\tboolean rollOnStartup = true;\n\n\t\t\tif (FoundationLogger.log4jConfigProps != null && FoundationLogger.log4jConfigProps.containsKey(FoundationLoggerConstants.Foundation_ROLL_ON_STARTUP.toString())) {\n\t\t\t\trollOnStartup = Boolean.valueOf(FoundationLogger.log4jConfigProps.getProperty(FoundationLoggerConstants.Foundation_ROLL_ON_STARTUP.toString()));\n\t\t\t}\n\n\t\t\ttimeSizeRollingAppender.setRollOnStartup(rollOnStartup);\n\n\t\t\t// refresh the appender\n\t\t\ttimeSizeRollingAppender.activateOptions();\n\n\t\t\t\n\t\t//\ttimeSizeRollingAppender.setOriginalLayout(); //So application state will not make any problems\n\n\t\t}else if(!(appender instanceof FoundationFileRollingAppender) && (appender instanceof TimeAndSizeRollingAppender)){ //TimeAndSizeRollingAppender\n\t\t\tfinal TimeAndSizeRollingAppender timeSizeRollingAppender = (TimeAndSizeRollingAppender) appender;\n\n\t\t\t// update the appender with default vales such as logging pattern, file size etc.\n\t\t\tupdateDefaultTimeAndSizeRollingAppender(timeSizeRollingAppender);\n\n\t\t\t// read teh proeprties and determine if archiving should be enabled.\n\t\t\tupdateArchivingSupport(timeSizeRollingAppender);\n\n\t\t\t// by default add the rolling file listener to enable application\n\t\t\t// state.\n\t\t\ttimeSizeRollingAppender.setFileRollEventListener(FoundationRollEventListener.class.getName());\n\n\t\t\tboolean rollOnStartup = true;\n\n\t\t\tif (FoundationLogger.log4jConfigProps != null && FoundationLogger.log4jConfigProps.containsKey(FoundationLoggerConstants.Foundation_ROLL_ON_STARTUP.toString())) {\n\t\t\t\trollOnStartup = Boolean.valueOf(FoundationLogger.log4jConfigProps.getProperty(FoundationLoggerConstants.Foundation_ROLL_ON_STARTUP.toString()));\n\t\t\t}\n\n\t\t\ttimeSizeRollingAppender.setRollOnStartup(rollOnStartup);\n\n\t\t\t// refresh the appender\n\t\t\ttimeSizeRollingAppender.activateOptions();\n\n\t\t\t\n\t\t//\ttimeSizeRollingAppender.setOriginalLayout();\n\t\t}\n\t\tif ( ! (appender instanceof org.apache.log4j.AsyncAppender))\n initiateAsyncSupport(appender);\n\n\t}", "protected List<Integer> getPageSizes() {\n\n try {\n return Collections.singletonList(Integer.valueOf(m_configObject.getInt(JSON_KEY_PAGESIZE)));\n } catch (JSONException e) {\n List<Integer> result = null;\n String pageSizesString = null;\n try {\n pageSizesString = m_configObject.getString(JSON_KEY_PAGESIZE);\n String[] pageSizesArray = pageSizesString.split(\"-\");\n if (pageSizesArray.length > 0) {\n result = new ArrayList<>(pageSizesArray.length);\n for (int i = 0; i < pageSizesArray.length; i++) {\n result.add(Integer.valueOf(pageSizesArray[i]));\n }\n }\n return result;\n } catch (NumberFormatException | JSONException e1) {\n LOG.warn(Messages.get().getBundle().key(Messages.LOG_PARSING_PAGE_SIZES_FAILED_1, pageSizesString), e);\n }\n if (null == m_baseConfig) {\n if (LOG.isInfoEnabled()) {\n LOG.info(Messages.get().getBundle().key(Messages.LOG_NO_PAGESIZE_SPECIFIED_0), e);\n }\n return null;\n } else {\n return m_baseConfig.getPaginationConfig().getPageSizes();\n }\n }\n }", "public static AssociationKeyMetadata getInverseAssociationKeyMetadata(OgmEntityPersister mainSidePersister, int propertyIndex) {\n\t\tType propertyType = mainSidePersister.getPropertyTypes()[propertyIndex];\n\t\tSessionFactoryImplementor factory = mainSidePersister.getFactory();\n\n\t\t// property represents no association, so no inverse meta-data can exist\n\t\tif ( !propertyType.isAssociationType() ) {\n\t\t\treturn null;\n\t\t}\n\n\t\tJoinable mainSideJoinable = ( (AssociationType) propertyType ).getAssociatedJoinable( factory );\n\t\tOgmEntityPersister inverseSidePersister = null;\n\n\t\t// to-many association\n\t\tif ( mainSideJoinable.isCollection() ) {\n\t\t\tinverseSidePersister = (OgmEntityPersister) ( (OgmCollectionPersister) mainSideJoinable ).getElementPersister();\n\t\t}\n\t\t// to-one\n\t\telse {\n\t\t\tinverseSidePersister = (OgmEntityPersister) mainSideJoinable;\n\t\t\tmainSideJoinable = mainSidePersister;\n\t\t}\n\n\t\tString mainSideProperty = mainSidePersister.getPropertyNames()[propertyIndex];\n\n\t\t// property is a one-to-one association (a many-to-one cannot be on the inverse side) -> get the meta-data\n\t\t// straight from the main-side persister\n\t\tAssociationKeyMetadata inverseOneToOneMetadata = mainSidePersister.getInverseOneToOneAssociationKeyMetadata( mainSideProperty );\n\t\tif ( inverseOneToOneMetadata != null ) {\n\t\t\treturn inverseOneToOneMetadata;\n\t\t}\n\n\t\t// process properties of inverse side and try to find association back to main side\n\t\tfor ( String candidateProperty : inverseSidePersister.getPropertyNames() ) {\n\t\t\tType type = inverseSidePersister.getPropertyType( candidateProperty );\n\n\t\t\t// candidate is a *-to-many association\n\t\t\tif ( type.isCollectionType() ) {\n\t\t\t\tOgmCollectionPersister inverseCollectionPersister = getPersister( factory, (CollectionType) type );\n\t\t\t\tString mappedByProperty = inverseCollectionPersister.getMappedByProperty();\n\t\t\t\tif ( mainSideProperty.equals( mappedByProperty ) ) {\n\t\t\t\t\tif ( isCollectionMatching( mainSideJoinable, inverseCollectionPersister ) ) {\n\t\t\t\t\t\treturn inverseCollectionPersister.getAssociationKeyMetadata();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}" ]
Called from the native side @param eye
[ "void onDrawEye(int eye, int swapChainIndex, boolean use_multiview) {\n mCurrentEye = eye;\n if (!(mSensoredScene == null || !mMainScene.equals(mSensoredScene))) {\n GVRCameraRig mainCameraRig = mMainScene.getMainCameraRig();\n\n if (use_multiview) {\n\n if (DEBUG_STATS) {\n mTracerDrawEyes1.enter(); // this eye is drawn first\n mTracerDrawEyes2.enter();\n }\n GVRRenderTarget renderTarget = mRenderBundle.getRenderTarget(EYE.MULTIVIEW, swapChainIndex);\n GVRCamera camera = mMainScene.getMainCameraRig().getCenterCamera();\n GVRCamera left_camera = mMainScene.getMainCameraRig().getLeftCamera();\n renderTarget.cullFromCamera(mMainScene, camera,mRenderBundle.getShaderManager());\n\n captureCenterEye(renderTarget, true);\n capture3DScreenShot(renderTarget, true);\n\n renderTarget.render(mMainScene, left_camera, mRenderBundle.getShaderManager(),mRenderBundle.getPostEffectRenderTextureA(),\n mRenderBundle.getPostEffectRenderTextureB());\n\n captureRightEye(renderTarget, true);\n captureLeftEye(renderTarget, true);\n\n captureFinish();\n\n if (DEBUG_STATS) {\n mTracerDrawEyes1.leave();\n mTracerDrawEyes2.leave();\n }\n\n\n } else {\n\n if (eye == 1) {\n if (DEBUG_STATS) {\n mTracerDrawEyes1.enter();\n }\n\n GVRCamera rightCamera = mainCameraRig.getRightCamera();\n GVRRenderTarget renderTarget = mRenderBundle.getRenderTarget(EYE.RIGHT, swapChainIndex);\n renderTarget.render(mMainScene, rightCamera, mRenderBundle.getShaderManager(), mRenderBundle.getPostEffectRenderTextureA(),\n mRenderBundle.getPostEffectRenderTextureB());\n captureRightEye(renderTarget, false);\n\n captureFinish();\n if (DEBUG_STATS) {\n mTracerDrawEyes1.leave();\n mTracerDrawEyes.leave();\n }\n } else {\n if (DEBUG_STATS) {\n mTracerDrawEyes1.leave();\n mTracerDrawEyes.leave();\n }\n\n\n GVRRenderTarget renderTarget = mRenderBundle.getRenderTarget(EYE.LEFT, swapChainIndex);\n GVRCamera leftCamera = mainCameraRig.getLeftCamera();\n\n capture3DScreenShot(renderTarget, false);\n\n renderTarget.cullFromCamera(mMainScene, mainCameraRig.getCenterCamera(), mRenderBundle.getShaderManager());\n captureCenterEye(renderTarget, false);\n renderTarget.render(mMainScene, leftCamera, mRenderBundle.getShaderManager(), mRenderBundle.getPostEffectRenderTextureA(), mRenderBundle.getPostEffectRenderTextureB());\n\n captureLeftEye(renderTarget, false);\n\n if (DEBUG_STATS) {\n mTracerDrawEyes2.leave();\n }\n }\n }\n }\n }" ]
[ "protected void addPoint(double time, RandomVariable value, boolean isParameter) {\n\t\tsynchronized (rationalFunctionInterpolationLazyInitLock) {\n\t\t\tif(interpolationEntity == InterpolationEntity.LOG_OF_VALUE_PER_TIME && time == 0) {\n\t\t\t\tboolean containsOne = false; int index=0;\n\t\t\t\tfor(int i = 0; i< value.size(); i++){if(value.get(i)==1.0) {containsOne = true; index=i; break;}}\n\t\t\t\tif(containsOne && isParameter == false) {\n\t\t\t\t\treturn;\n\t\t\t\t} else {\n\t\t\t\t\tthrow new IllegalArgumentException(\"The interpolation method LOG_OF_VALUE_PER_TIME does not allow to add a value at time = 0 other than 1.0 (received 1 at index\" + index + \").\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tRandomVariable interpolationEntityValue = interpolationEntityFromValue(value, time);\n\n\t\t\tint index = getTimeIndex(time);\n\t\t\tif(index >= 0) {\n\t\t\t\tif(points.get(index).value == interpolationEntityValue) {\n\t\t\t\t\treturn;\t\t\t// Already in list\n\t\t\t\t} else if(isParameter) {\n\t\t\t\t\treturn;\n\t\t\t\t} else {\n\t\t\t\t\tthrow new RuntimeException(\"Trying to add a value for a time for which another value already exists.\");\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Insert the new point, retain ordering.\n\t\t\t\tPoint point = new Point(time, interpolationEntityValue, isParameter);\n\t\t\t\tpoints.add(-index-1, point);\n\n\t\t\t\tif(isParameter) {\n\t\t\t\t\t// Add this point also to the list of parameters\n\t\t\t\t\tint parameterIndex = getParameterIndex(time);\n\t\t\t\t\tif(parameterIndex >= 0) {\n\t\t\t\t\t\tnew RuntimeException(\"CurveFromInterpolationPoints inconsistent.\");\n\t\t\t\t\t}\n\t\t\t\t\tpointsBeingParameters.add(-parameterIndex-1, point);\n\t\t\t\t}\n\t\t\t}\n\t\t\trationalFunctionInterpolation = null;\n\t\t\tcurveCacheReference = null;\n\t\t}\n\t}", "public CollectionRequest<Project> findByTeam(String team) {\n \n String path = String.format(\"/teams/%s/projects\", team);\n return new CollectionRequest<Project>(this, Project.class, path, \"GET\");\n }", "public void setEnable(boolean flag)\n {\n if (mEnabled == flag)\n {\n return;\n }\n mEnabled = flag;\n if (flag)\n {\n mContext.registerDrawFrameListener(this);\n mContext.getApplication().getEventReceiver().addListener(this);\n mAudioEngine.resume();\n }\n else\n {\n mContext.unregisterDrawFrameListener(this);\n mContext.getApplication().getEventReceiver().removeListener(this);\n mAudioEngine.pause();\n }\n }", "public void processActivityCodes(List<Row> types, List<Row> typeValues, List<Row> assignments)\n {\n ActivityCodeContainer container = m_project.getActivityCodes();\n Map<Integer, ActivityCode> map = new HashMap<Integer, ActivityCode>();\n\n for (Row row : types)\n {\n ActivityCode code = new ActivityCode(row.getInteger(\"actv_code_type_id\"), row.getString(\"actv_code_type\"));\n container.add(code);\n map.put(code.getUniqueID(), code);\n }\n\n for (Row row : typeValues)\n {\n ActivityCode code = map.get(row.getInteger(\"actv_code_type_id\"));\n if (code != null)\n {\n ActivityCodeValue value = code.addValue(row.getInteger(\"actv_code_id\"), row.getString(\"short_name\"), row.getString(\"actv_code_name\"));\n m_activityCodeMap.put(value.getUniqueID(), value);\n }\n }\n\n for (Row row : assignments)\n {\n Integer taskID = row.getInteger(\"task_id\");\n List<Integer> list = m_activityCodeAssignments.get(taskID);\n if (list == null)\n {\n list = new ArrayList<Integer>();\n m_activityCodeAssignments.put(taskID, list);\n }\n list.add(row.getInteger(\"actv_code_id\"));\n }\n }", "public PreparedStatementCreator count(final Dialect dialect) {\n return new PreparedStatementCreator() {\n public PreparedStatement createPreparedStatement(Connection con)\n throws SQLException {\n return getPreparedStatementCreator()\n .setSql(dialect.createCountSelect(builder.toString()))\n .createPreparedStatement(con);\n }\n };\n }", "public PreparedStatement getDeleteStatement(ClassDescriptor cld) throws PersistenceBrokerSQLException, PersistenceBrokerException\r\n {\r\n try\r\n {\r\n return cld.getStatementsForClass(m_conMan).getDeleteStmt(m_conMan.getConnection());\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new PersistenceBrokerSQLException(\"Could not build statement ask for\", e);\r\n }\r\n catch (LookupException e)\r\n {\r\n throw new PersistenceBrokerException(\"Used ConnectionManager instance could not obtain a connection\", e);\r\n }\r\n }", "public static base_responses add(nitro_service client, vlan resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tvlan addresources[] = new vlan[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new vlan();\n\t\t\t\taddresources[i].id = resources[i].id;\n\t\t\t\taddresources[i].aliasname = resources[i].aliasname;\n\t\t\t\taddresources[i].ipv6dynamicrouting = resources[i].ipv6dynamicrouting;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public static StringTemplateGroup readStringTemplateGroup(InputStream stream) {\n\n try {\n return new StringTemplateGroup(\n new InputStreamReader(stream, \"UTF-8\"),\n DefaultTemplateLexer.class,\n new StringTemplateErrorListener() {\n\n @SuppressWarnings(\"synthetic-access\")\n public void error(String arg0, Throwable arg1) {\n\n LOG.error(arg0 + \": \" + arg1.getMessage(), arg1);\n }\n\n @SuppressWarnings(\"synthetic-access\")\n public void warning(String arg0) {\n\n LOG.warn(arg0);\n\n }\n });\n } catch (Exception e) {\n LOG.error(e.getLocalizedMessage(), e);\n return new StringTemplateGroup(\"dummy\");\n }\n }", "public float get(Layout.Axis axis) {\n switch (axis) {\n case X:\n return x;\n case Y:\n return y;\n case Z:\n return z;\n default:\n throw new RuntimeAssertion(\"Bad axis specified: %s\", axis);\n }\n }" ]
Given a read-only store name and a directory, swaps it in while returning the directory path being swapped out @param storeName The name of the read-only store @param directory The directory being swapped in @return The directory path which was swapped out @throws VoldemortException
[ "private String swapStore(String storeName, String directory) throws VoldemortException {\n\n ReadOnlyStorageEngine store = getReadOnlyStorageEngine(metadataStore,\n storeRepository,\n storeName);\n\n if(!Utils.isReadableDir(directory))\n throw new VoldemortException(\"Store directory '\" + directory\n + \"' is not a readable directory.\");\n\n String currentDirPath = store.getCurrentDirPath();\n\n logger.info(\"Swapping RO store '\" + storeName + \"' to version directory '\" + directory\n + \"'\");\n store.swapFiles(directory);\n logger.info(\"Swapping swapped RO store '\" + storeName + \"' to version directory '\"\n + directory + \"'\");\n\n return currentDirPath;\n }" ]
[ "public static Thumbor create(String host, String key) {\n if (key == null || key.length() == 0) {\n throw new IllegalArgumentException(\"Key must not be blank.\");\n }\n return new Thumbor(host, key);\n }", "protected boolean isItemAccepted(byte[] key) {\n boolean entryAccepted = false;\n if (!fetchOrphaned) {\n if (isKeyNeeded(key)) {\n entryAccepted = true;\n }\n } else {\n if (!StoreRoutingPlan.checkKeyBelongsToNode(key, nodeId, initialCluster, storeDef)) {\n entryAccepted = true;\n }\n }\n return entryAccepted;\n }", "public static boolean isSameStructure(DMatrixSparseCSC a , DMatrixSparseCSC b) {\n if( a.numRows == b.numRows && a.numCols == b.numCols && a.nz_length == b.nz_length) {\n for (int i = 0; i <= a.numCols; i++) {\n if( a.col_idx[i] != b.col_idx[i] )\n return false;\n }\n for (int i = 0; i < a.nz_length; i++) {\n if( a.nz_rows[i] != b.nz_rows[i] )\n return false;\n }\n return true;\n }\n return false;\n }", "public static base_responses delete(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 deleteresources[] = new dnstxtrec[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new dnstxtrec();\n\t\t\t\tdeleteresources[i].domain = resources[i].domain;\n\t\t\t\tdeleteresources[i].String = resources[i].String;\n\t\t\t\tdeleteresources[i].recordid = resources[i].recordid;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "public Set<RGBColor> colours() {\n return stream().map(Pixel::toColor).collect(Collectors.toSet());\n }", "protected String getJavaExecutablePath() {\n String executableName = isWindows() ? \"bin/java.exe\" : \"bin/java\";\n return PROPERTIES.getJavaHome().resolve(executableName).toAbsolutePath().toString();\n }", "public static synchronized DeckReference getDeckReference(int player, int hotCue) {\n Map<Integer, DeckReference> playerMap = instances.get(player);\n if (playerMap == null) {\n playerMap = new HashMap<Integer, DeckReference>();\n instances.put(player, playerMap);\n }\n DeckReference result = playerMap.get(hotCue);\n if (result == null) {\n result = new DeckReference(player, hotCue);\n playerMap.put(hotCue, result);\n }\n return result;\n }", "private void writeBooleanField(String fieldName, Object value) throws IOException\n {\n boolean val = ((Boolean) value).booleanValue();\n if (val)\n {\n m_writer.writeNameValuePair(fieldName, val);\n }\n }", "SimpleJsonEncoder appendToJSONUnquoted(final String key, final Object value) {\n if (closed) {\n throw new IllegalStateException(\"Encoder already closed\");\n }\n if (value != null) {\n appendKey(key);\n sb.append(value);\n }\n return this;\n }" ]
Creates a resource ID from information of a generic resource. @param subscriptionId the subscription UUID @param resourceGroupName the resource group name @param resourceProviderNamespace the resource provider namespace @param resourceType the type of the resource or nested resource @param resourceName name of the resource or nested resource @param parentResourcePath parent resource's relative path to the provider, if the resource is a generic resource @return the resource ID string
[ "public static String constructResourceId(\n final String subscriptionId,\n final String resourceGroupName,\n final String resourceProviderNamespace,\n final String resourceType,\n final String resourceName,\n final String parentResourcePath) {\n String prefixedParentPath = parentResourcePath;\n if (parentResourcePath != null && !parentResourcePath.isEmpty()) {\n prefixedParentPath = \"/\" + parentResourcePath;\n }\n return String.format(\n \"/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s\",\n subscriptionId,\n resourceGroupName,\n resourceProviderNamespace,\n prefixedParentPath,\n resourceType,\n resourceName);\n }" ]
[ "public static double KullbackLeiblerDivergence(double[] p, double[] q) {\n boolean intersection = false;\n double k = 0;\n\n for (int i = 0; i < p.length; i++) {\n if (p[i] != 0 && q[i] != 0) {\n intersection = true;\n k += p[i] * Math.log(p[i] / q[i]);\n }\n }\n\n if (intersection)\n return k;\n else\n return Double.POSITIVE_INFINITY;\n }", "public NamespacesList<Value> getValues(String namespace, String predicate, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n NamespacesList<Value> valuesList = new NamespacesList<Value>();\r\n parameters.put(\"method\", METHOD_GET_VALUES);\r\n\r\n if (namespace != null) {\r\n parameters.put(\"namespace\", namespace);\r\n }\r\n if (predicate != null) {\r\n parameters.put(\"predicate\", predicate);\r\n }\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element nsElement = response.getPayload();\r\n NodeList nsNodes = nsElement.getElementsByTagName(\"value\");\r\n valuesList.setPage(nsElement.getAttribute(\"page\"));\r\n valuesList.setPages(nsElement.getAttribute(\"pages\"));\r\n valuesList.setPerPage(nsElement.getAttribute(\"perPage\"));\r\n valuesList.setTotal(\"\" + nsNodes.getLength());\r\n for (int i = 0; i < nsNodes.getLength(); i++) {\r\n Element element = (Element) nsNodes.item(i);\r\n Value value = parseValue(element);\r\n value.setNamespace(namespace);\r\n value.setPredicate(predicate);\r\n valuesList.add(value);\r\n }\r\n return valuesList;\r\n }", "public static<Z> Function0<Z> lift(Callable<Z> f) {\n\treturn bridge.lift(f);\n }", "public List<BuildpackInstallation> listBuildpackInstallations(String appName) {\n return connection.execute(new BuildpackInstallationList(appName), apiKey);\n }", "private void store(final PrintJobStatus printJobStatus) throws JSONException {\n JSONObject metadata = new JSONObject();\n metadata.put(JSON_REQUEST_DATA, printJobStatus.getEntry().getRequestData().getInternalObj());\n metadata.put(JSON_STATUS, printJobStatus.getStatus().toString());\n metadata.put(JSON_START_DATE, printJobStatus.getStartTime());\n metadata.put(JSON_REQUEST_COUNT, printJobStatus.getRequestCount());\n if (printJobStatus.getCompletionDate() != null) {\n metadata.put(JSON_COMPLETION_DATE, printJobStatus.getCompletionTime());\n }\n metadata.put(JSON_ACCESS_ASSERTION, this.assertionPersister.marshal(printJobStatus.getAccess()));\n if (printJobStatus.getError() != null) {\n metadata.put(JSON_ERROR, printJobStatus.getError());\n }\n if (printJobStatus.getResult() != null) {\n metadata.put(JSON_REPORT_URI, printJobStatus.getResult().getReportURIString());\n metadata.put(JSON_FILENAME, printJobStatus.getResult().getFileName());\n metadata.put(JSON_FILE_EXT, printJobStatus.getResult().getFileExtension());\n metadata.put(JSON_MIME_TYPE, printJobStatus.getResult().getMimeType());\n }\n this.registry.put(RESULT_METADATA + printJobStatus.getReferenceId(), metadata);\n }", "private void logOriginalRequestHistory(String requestType,\n HttpServletRequest request, History history) {\n logger.info(\"Storing original request history\");\n history.setRequestType(requestType);\n history.setOriginalRequestHeaders(HttpUtilities.getHeaders(request));\n history.setOriginalRequestURL(request.getRequestURL().toString());\n history.setOriginalRequestParams(request.getQueryString() == null ? \"\" : request.getQueryString());\n logger.info(\"Done storing\");\n }", "public static base_responses add(nitro_service client, sslocspresponder resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslocspresponder addresources[] = new sslocspresponder[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new sslocspresponder();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].url = resources[i].url;\n\t\t\t\taddresources[i].cache = resources[i].cache;\n\t\t\t\taddresources[i].cachetimeout = resources[i].cachetimeout;\n\t\t\t\taddresources[i].batchingdepth = resources[i].batchingdepth;\n\t\t\t\taddresources[i].batchingdelay = resources[i].batchingdelay;\n\t\t\t\taddresources[i].resptimeout = resources[i].resptimeout;\n\t\t\t\taddresources[i].respondercert = resources[i].respondercert;\n\t\t\t\taddresources[i].trustresponder = resources[i].trustresponder;\n\t\t\t\taddresources[i].producedattimeskew = resources[i].producedattimeskew;\n\t\t\t\taddresources[i].signingcert = resources[i].signingcert;\n\t\t\t\taddresources[i].usenonce = resources[i].usenonce;\n\t\t\t\taddresources[i].insertclientcert = resources[i].insertclientcert;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public static MetadataTemplate getMetadataTemplateByID(BoxAPIConnection api, String templateID) {\n\n URL url = METADATA_TEMPLATE_BY_ID_URL_TEMPLATE.build(api.getBaseURL(), templateID);\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n return new MetadataTemplate(response.getJSON());\n }", "private void writeAssignments()\n {\n for (ResourceAssignment assignment : m_projectFile.getResourceAssignments())\n {\n Resource resource = assignment.getResource();\n if (resource != null)\n {\n Task task = assignment.getTask();\n if (task != null && task.getUniqueID().intValue() != 0 && !task.getSummary())\n {\n writeAssignment(assignment);\n }\n }\n }\n }" ]
Checks that the modified features exist. @param classDef The class descriptor @param checkLevel The current check level (this constraint is checked in basic and strict) @exception ConstraintException If the constraint has been violated
[ "private void checkModifications(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n HashMap features = new HashMap();\r\n FeatureDescriptorDef def;\r\n\r\n for (Iterator it = classDef.getFields(); it.hasNext();)\r\n {\r\n def = (FeatureDescriptorDef)it.next();\r\n features.put(def.getName(), def);\r\n }\r\n for (Iterator it = classDef.getReferences(); it.hasNext();)\r\n {\r\n def = (FeatureDescriptorDef)it.next();\r\n features.put(def.getName(), def);\r\n }\r\n for (Iterator it = classDef.getCollections(); it.hasNext();)\r\n {\r\n def = (FeatureDescriptorDef)it.next();\r\n features.put(def.getName(), def);\r\n }\r\n\r\n // now checking the modifications\r\n Properties mods;\r\n String modName;\r\n String propName;\r\n\r\n for (Iterator it = classDef.getModificationNames(); it.hasNext();)\r\n {\r\n modName = (String)it.next();\r\n if (!features.containsKey(modName))\r\n {\r\n throw new ConstraintException(\"Class \"+classDef.getName()+\" contains a modification for an unknown feature \"+modName);\r\n }\r\n def = (FeatureDescriptorDef)features.get(modName);\r\n if (def.getOriginal() == null)\r\n {\r\n throw new ConstraintException(\"Class \"+classDef.getName()+\" contains a modification for a feature \"+modName+\" that is not inherited but defined in the same class\");\r\n }\r\n // checking modification\r\n mods = classDef.getModification(modName);\r\n for (Iterator propIt = mods.keySet().iterator(); propIt.hasNext();)\r\n {\r\n propName = (String)propIt.next();\r\n if (!PropertyHelper.isPropertyAllowed(def.getClass(), propName))\r\n {\r\n throw new ConstraintException(\"The modification of attribute \"+propName+\" in class \"+classDef.getName()+\" is not applicable to the feature \"+modName);\r\n }\r\n }\r\n }\r\n }" ]
[ "public static int cudnnSoftmaxForward(\n cudnnHandle handle, \n int algo, \n int mode, \n Pointer alpha, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor yDesc, \n Pointer y)\n {\n return checkResult(cudnnSoftmaxForwardNative(handle, algo, mode, alpha, xDesc, x, beta, yDesc, y));\n }", "public void removeJobType(final Class<?> jobType) {\n if (jobType == null) {\n throw new IllegalArgumentException(\"jobType must not be null\");\n }\n this.jobTypes.values().remove(jobType);\n }", "public static nsrollbackcmd[] get(nitro_service service, nsrollbackcmd_args args) throws Exception{\n\t\tnsrollbackcmd obj = new nsrollbackcmd();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tnsrollbackcmd[] response = (nsrollbackcmd[])obj.get_resources(service, option);\n\t\treturn response;\n\t}", "public double getCouponPayment(int periodIndex, AnalyticModel model) {\n\n\t\tForwardCurve forwardCurve = model.getForwardCurve(forwardCurveName);\n\t\tif(forwardCurve == null && forwardCurveName != null && forwardCurveName.length() > 0) {\n\t\t\tthrow new IllegalArgumentException(\"No forward curve with name '\" + forwardCurveName + \"' was found in the model:\\n\" + model.toString());\n\t\t}\n\n\t\tdouble periodLength\t= schedule.getPeriodLength(periodIndex);\n\t\tdouble couponPayment=fixedCoupon ;\n\t\tif(forwardCurve != null ) {\n\t\t\tcouponPayment = floatingSpread+forwardCurve.getForward(model, schedule.getFixing(periodIndex));\n\t\t}\n\t\treturn couponPayment*periodLength;\n\t}", "public FileModel getChildFile(ArchiveModel archiveModel, String filePath)\n {\n filePath = FilenameUtils.separatorsToUnix(filePath);\n StringTokenizer stk = new StringTokenizer(filePath, \"/\");\n\n FileModel currentFileModel = archiveModel;\n while (stk.hasMoreTokens() && currentFileModel != null)\n {\n String pathElement = stk.nextToken();\n\n currentFileModel = findFileModel(currentFileModel, pathElement);\n }\n return currentFileModel;\n }", "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 List<File> getConfigFiles() {\n\n String[] filenames = {\n \"opencms-modules.xml\",\n \"opencms-system.xml\",\n \"opencms-vfs.xml\",\n \"opencms-importexport.xml\",\n \"opencms-sites.xml\",\n \"opencms-variables.xml\",\n \"opencms-scheduler.xml\",\n \"opencms-workplace.xml\",\n \"opencms-search.xml\"};\n List<File> result = new ArrayList<>();\n for (String fn : filenames) {\n File file = new File(m_configDir, fn);\n if (file.exists()) {\n result.add(file);\n }\n }\n return result;\n }", "public DbOrganization getOrganization(final String organizationId) {\n final DbOrganization dbOrganization = repositoryHandler.getOrganization(organizationId);\n\n if(dbOrganization == null){\n throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)\n .entity(\"Organization \" + organizationId + \" does not exist.\").build());\n }\n\n return dbOrganization;\n }", "@Deprecated\n public String get(String path) {\n final JsonValue value = this.values.get(this.pathToProperty(path));\n if (value == null) {\n return null;\n }\n if (!value.isString()) {\n return value.toString();\n }\n return value.asString();\n }" ]
Takes the file, reads it in, and prints out the likelihood of each possible label at each point. @param filename The path to the specified file
[ "public void printProbs(String filename,\r\n DocumentReaderAndWriter<IN> readerAndWriter) {\r\n // only for the OCR data does this matter\r\n flags.ocrTrain = false;\r\n\r\n ObjectBank<List<IN>> docs =\r\n makeObjectBankFromFile(filename, readerAndWriter);\r\n printProbsDocuments(docs);\r\n }" ]
[ "public static byte[] concat(Bytes... listOfBytes) {\n int offset = 0;\n int size = 0;\n\n for (Bytes b : listOfBytes) {\n size += b.length() + checkVlen(b.length());\n }\n\n byte[] data = new byte[size];\n for (Bytes b : listOfBytes) {\n offset = writeVint(data, offset, b.length());\n b.copyTo(0, b.length(), data, offset);\n offset += b.length();\n }\n return data;\n }", "private int getFixedDataFieldSize(FieldType type)\n {\n int result = 0;\n DataType dataType = type.getDataType();\n if (dataType != null)\n {\n switch (dataType)\n {\n case DATE:\n case INTEGER:\n case DURATION:\n {\n result = 4;\n break;\n }\n\n case TIME_UNITS:\n case CONSTRAINT:\n case PRIORITY:\n case PERCENTAGE:\n case TASK_TYPE:\n case ACCRUE:\n case SHORT:\n case BOOLEAN:\n case DELAY:\n case WORKGROUP:\n case RATE_UNITS:\n case EARNED_VALUE_METHOD:\n case RESOURCE_REQUEST_TYPE:\n {\n result = 2;\n break;\n }\n\n case CURRENCY:\n case UNITS:\n case RATE:\n case WORK:\n {\n result = 8;\n break;\n }\n\n case WORK_UNITS:\n {\n result = 1;\n break;\n }\n\n case GUID:\n {\n result = 16;\n break;\n }\n\n default:\n {\n result = 0;\n break;\n }\n }\n }\n\n return result;\n }", "final public void addOffset(Integer start, Integer end) {\n if (tokenOffset == null) {\n setOffset(start, end);\n } else if ((start == null) || (end == null)) {\n // do nothing\n } else if (start > end) {\n throw new IllegalArgumentException(\"Start offset after end offset\");\n } else {\n tokenOffset.add(start, end);\n }\n }", "@Override\n public void map(GenericData.Record record,\n AvroCollector<Pair<ByteBuffer, ByteBuffer>> collector,\n Reporter reporter) throws IOException {\n\n byte[] keyBytes = null;\n byte[] valBytes = null;\n Object keyRecord = null;\n Object valRecord = null;\n try {\n keyRecord = record.get(keyField);\n valRecord = record.get(valField);\n keyBytes = keySerializer.toBytes(keyRecord);\n valBytes = valueSerializer.toBytes(valRecord);\n\n this.collectorWrapper.setCollector(collector);\n this.mapper.map(keyBytes, valBytes, this.collectorWrapper);\n\n recordCounter++;\n } catch (OutOfMemoryError oom) {\n logger.error(oomErrorMessage(reporter));\n if (keyBytes == null) {\n logger.error(\"keyRecord caused OOM!\");\n } else {\n logger.error(\"keyRecord: \" + keyRecord);\n logger.error(\"valRecord: \" + (valBytes == null ? \"caused OOM\" : valRecord));\n }\n throw new VoldemortException(oomErrorMessage(reporter), oom);\n }\n }", "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 }", "public static final String printDuration(Duration value)\n {\n return value == null ? null : Double.toString(value.getDuration());\n }", "public void updateLinks(ServiceReference<S> serviceReference) {\n for (D declaration : linkerManagement.getMatchedDeclaration()) {\n boolean isAlreadyLinked = declaration.getStatus().getServiceReferencesBounded().contains(serviceReference);\n boolean canBeLinked = linkerManagement.canBeLinked(declaration, serviceReference);\n if (isAlreadyLinked && !canBeLinked) {\n linkerManagement.unlink(declaration, serviceReference);\n } else if (!isAlreadyLinked && canBeLinked) {\n linkerManagement.link(declaration, serviceReference);\n }\n }\n }", "public static SQLService getInstance() throws Exception {\n if (_instance == null) {\n _instance = new SQLService();\n _instance.startServer();\n\n // default pool size is 20\n // can be overriden by env variable\n int dbPool = 20;\n if (Utils.getEnvironmentOptionValue(Constants.SYS_DATABASE_POOL_SIZE) != null) {\n dbPool = Integer.valueOf(Utils.getEnvironmentOptionValue(Constants.SYS_DATABASE_POOL_SIZE));\n }\n\n // initialize connection pool\n PoolProperties p = new PoolProperties();\n String connectString = \"jdbc:h2:tcp://\" + _instance.databaseHost + \":\" + String.valueOf(_instance.port) + \"/\" +\n _instance.databaseName + \"/proxydb;MULTI_THREADED=true;AUTO_RECONNECT=TRUE;AUTOCOMMIT=ON\";\n p.setUrl(connectString);\n p.setDriverClassName(\"org.h2.Driver\");\n p.setUsername(\"sa\");\n p.setJmxEnabled(true);\n p.setTestWhileIdle(false);\n p.setTestOnBorrow(true);\n p.setValidationQuery(\"SELECT 1\");\n p.setTestOnReturn(false);\n p.setValidationInterval(5000);\n p.setTimeBetweenEvictionRunsMillis(30000);\n p.setMaxActive(dbPool);\n p.setInitialSize(5);\n p.setMaxWait(30000);\n p.setRemoveAbandonedTimeout(60);\n p.setMinEvictableIdleTimeMillis(30000);\n p.setMinIdle(10);\n p.setLogAbandoned(true);\n p.setRemoveAbandoned(true);\n _instance.datasource = new DataSource();\n _instance.datasource.setPoolProperties(p);\n }\n return _instance;\n }", "private void addDependent(String pathName, String relativeTo) {\n if (relativeTo != null) {\n Set<String> dependents = dependenctRelativePaths.get(relativeTo);\n if (dependents == null) {\n dependents = new HashSet<String>();\n dependenctRelativePaths.put(relativeTo, dependents);\n }\n dependents.add(pathName);\n }\n }" ]
Use this API to fetch authenticationldappolicy_vpnglobal_binding resources of given name .
[ "public static authenticationldappolicy_vpnglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationldappolicy_vpnglobal_binding obj = new authenticationldappolicy_vpnglobal_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationldappolicy_vpnglobal_binding response[] = (authenticationldappolicy_vpnglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "public boolean shouldCache(String requestUri) {\n\t\tString uri = requestUri.toLowerCase();\n\t\treturn checkContains(uri, cacheIdentifiers) || checkSuffixes(uri, cacheSuffixes);\n\t}", "public static Span toSpan(Range range) {\n return new Span(toRowColumn(range.getStartKey()), range.isStartKeyInclusive(),\n toRowColumn(range.getEndKey()), range.isEndKeyInclusive());\n }", "protected void _format(EObject obj, IFormattableDocument document) {\n\t\tfor (EObject child : obj.eContents())\n\t\t\tdocument.format(child);\n\t}", "public Matrix4f getFinalTransformMatrix()\n {\n final FloatBuffer fb = ByteBuffer.allocateDirect(4*4*4).order(ByteOrder.nativeOrder()).asFloatBuffer();\n NativeBone.getFinalTransformMatrix(getNative(), fb);\n return new Matrix4f(fb);\n }", "public static boolean isArray(Type type) {\n return (type instanceof GenericArrayType) || (type instanceof Class<?> && ((Class<?>) type).isArray());\n }", "public void cross(Vector3d v1, Vector3d v2) {\n double tmpx = v1.y * v2.z - v1.z * v2.y;\n double tmpy = v1.z * v2.x - v1.x * v2.z;\n double tmpz = v1.x * v2.y - v1.y * v2.x;\n\n x = tmpx;\n y = tmpy;\n z = tmpz;\n }", "@SuppressWarnings(\"checkstyle:illegalcatch\")\n private boolean sendMessage(final byte[] messageToSend) {\n try {\n connectionPool.execute(new PooledObjectConsumer<TcpConnection>() {\n @Override\n public void accept(final TcpConnection tcpConnection) throws IOException {\n tcpConnection.write(messageToSend);\n }\n });\n } catch (final Exception e) {\n addError(String.format(\"Error sending message via tcp://%s:%s\",\n getGraylogHost(), getGraylogPort()), e);\n\n return false;\n }\n\n return true;\n }", "@Override\n @SuppressFBWarnings(value = \"UL_UNRELEASED_LOCK\", justification = \"False positive from FindBugs\")\n public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {\n if (!isActive()) {\n throw new ContextNotActiveException();\n }\n checkContextInitialized();\n final BeanStore beanStore = getBeanStore();\n if (beanStore == null) {\n return null;\n }\n if (contextual == null) {\n throw ContextLogger.LOG.contextualIsNull();\n }\n BeanIdentifier id = getId(contextual);\n ContextualInstance<T> beanInstance = beanStore.get(id);\n if (beanInstance != null) {\n return beanInstance.getInstance();\n } else if (creationalContext != null) {\n LockedBean lock = null;\n try {\n if (multithreaded) {\n lock = beanStore.lock(id);\n beanInstance = beanStore.get(id);\n if (beanInstance != null) {\n return beanInstance.getInstance();\n }\n }\n T instance = contextual.create(creationalContext);\n if (instance != null) {\n beanInstance = new SerializableContextualInstanceImpl<Contextual<T>, T>(contextual, instance, creationalContext, serviceRegistry.get(ContextualStore.class));\n beanStore.put(id, beanInstance);\n }\n return instance;\n } finally {\n if (lock != null) {\n lock.unlock();\n }\n }\n } else {\n return null;\n }\n }", "void processSiteRow(String siteRow) {\n\t\tString[] row = getSiteRowFields(siteRow);\n\n\t\tString filePath = \"\";\n\t\tString pagePath = \"\";\n\n\t\tString dataArray = row[8].substring(row[8].indexOf('{'),\n\t\t\t\trow[8].length() - 2);\n\n\t\t// Explanation for the regular expression below:\n\t\t// \"'{' or ';'\" followed by either\n\t\t// \"NOT: ';', '{', or '}'\" repeated one or more times; or\n\t\t// \"a single '}'\"\n\t\t// The first case matches \";s:5:\\\"paths\\\"\"\n\t\t// but also \";a:2:\" in \"{s:5:\\\"paths\\\";a:2:{s:9:\\ ...\".\n\t\t// The second case matches \";}\" which terminates (sub)arrays.\n\t\tMatcher matcher = Pattern.compile(\"[{;](([^;}{][^;}{]*)|[}])\").matcher(\n\t\t\t\tdataArray);\n\t\tString prevString = \"\";\n\t\tString curString = \"\";\n\t\tString path = \"\";\n\t\tboolean valuePosition = false;\n\n\t\twhile (matcher.find()) {\n\t\t\tString match = matcher.group().substring(1);\n\t\t\tif (match.length() == 0) {\n\t\t\t\tvaluePosition = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (match.charAt(0) == 's') {\n\t\t\t\tvaluePosition = !valuePosition && !\"\".equals(prevString);\n\t\t\t\tcurString = match.substring(match.indexOf('\"') + 1,\n\t\t\t\t\t\tmatch.length() - 2);\n\t\t\t} else if (match.charAt(0) == 'a') {\n\t\t\t\tvaluePosition = false;\n\t\t\t\tpath = path + \"/\" + prevString;\n\t\t\t} else if (\"}\".equals(match)) {\n\t\t\t\tvaluePosition = false;\n\t\t\t\tpath = path.substring(0, path.lastIndexOf('/'));\n\t\t\t}\n\n\t\t\tif (valuePosition && \"file_path\".equals(prevString)\n\t\t\t\t\t&& \"/paths\".equals(path)) {\n\t\t\t\tfilePath = curString;\n\t\t\t} else if (valuePosition && \"page_path\".equals(prevString)\n\t\t\t\t\t&& \"/paths\".equals(path)) {\n\t\t\t\tpagePath = curString;\n\t\t\t}\n\n\t\t\tprevString = curString;\n\t\t\tcurString = \"\";\n\t\t}\n\n\t\tMwSitesDumpFileProcessor.logger.debug(\"Found site data \\\"\" + row[1]\n\t\t\t\t+ \"\\\" (group \\\"\" + row[3] + \"\\\", language \\\"\" + row[5]\n\t\t\t\t+ \"\\\", type \\\"\" + row[2] + \"\\\")\");\n\t\tthis.sites.setSiteInformation(row[1], row[3], row[5], row[2], filePath,\n\t\t\t\tpagePath);\n\t}" ]
Use this API to add snmpuser resources.
[ "public static base_responses add(nitro_service client, snmpuser resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsnmpuser addresources[] = new snmpuser[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new snmpuser();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].group = resources[i].group;\n\t\t\t\taddresources[i].authtype = resources[i].authtype;\n\t\t\t\taddresources[i].authpasswd = resources[i].authpasswd;\n\t\t\t\taddresources[i].privtype = resources[i].privtype;\n\t\t\t\taddresources[i].privpasswd = resources[i].privpasswd;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}" ]
[ "private void handleSendDataRequest(SerialMessage incomingMessage) {\n\t\tlogger.trace(\"Handle Message Send Data Request\");\n\t\t\n\t\tint callbackId = incomingMessage.getMessagePayloadByte(0);\n\t\tTransmissionState status = TransmissionState.getTransmissionState(incomingMessage.getMessagePayloadByte(1));\n\t\tSerialMessage originalMessage = this.lastSentMessage;\n\t\t\n\t\tif (status == null) {\n\t\t\tlogger.warn(\"Transmission state not found, ignoring.\");\n\t\t\treturn;\n\t\t}\n\n\t\tlogger.debug(\"CallBack ID = {}\", callbackId);\n\t\tlogger.debug(String.format(\"Status = %s (0x%02x)\", status.getLabel(), status.getKey()));\n\t\t\n\t\tif (originalMessage == null || originalMessage.getCallbackId() != callbackId) {\n\t\t\tlogger.warn(\"Already processed another send data request for this callback Id, ignoring.\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tswitch (status) {\n\t\t\tcase COMPLETE_OK:\n\t\t\t\tZWaveNode node = this.getNode(originalMessage.getMessageNode());\n\t\t\t\tnode.resetResendCount();\n\t\t\t\t\n\t\t\t\t// in case we received a ping response and the node is alive, we proceed with the next node stage for this node.\n\t\t\t\tif (node != null && node.getNodeStage() == NodeStage.NODEBUILDINFO_PING) {\n\t\t\t\t\tnode.advanceNodeStage();\n\t\t\t\t}\n\t\t\t\tif (incomingMessage.getMessageClass() == originalMessage.getExpectedReply() && !incomingMessage.isTransActionCanceled()) {\n\t\t\t\t\tnotifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));\n\t\t\t\t\ttransactionCompleted.release();\n\t\t\t\t\tlogger.trace(\"Released. Transaction completed permit count -> {}\", transactionCompleted.availablePermits());\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\tcase COMPLETE_NO_ACK:\n\t\t\tcase COMPLETE_FAIL:\n\t\t\tcase COMPLETE_NOT_IDLE:\n\t\t\tcase COMPLETE_NOROUTE:\n\t\t\t\ttry {\n\t\t\t\t\thandleFailedSendDataRequest(originalMessage);\n\t\t\t\t} finally {\n\t\t\t\t\ttransactionCompleted.release();\n\t\t\t\t\tlogger.trace(\"Released. Transaction completed permit count -> {}\", transactionCompleted.availablePermits());\n\t\t\t\t}\n\t\t\tdefault:\n\t\t}\n\t}", "public static final Path resolveSecurely(Path rootPath, String path) {\n Path resolvedPath;\n if(path == null || path.isEmpty()) {\n resolvedPath = rootPath.normalize();\n } else {\n String relativePath = removeSuperflousSlashes(path);\n resolvedPath = rootPath.resolve(relativePath).normalize();\n }\n if(!resolvedPath.startsWith(rootPath)) {\n throw DeploymentRepositoryLogger.ROOT_LOGGER.forbiddenPath(path);\n }\n return resolvedPath;\n }", "@Override\n public EthiopicDate date(Era era, int yearOfEra, int month, int dayOfMonth) {\n return date(prolepticYear(era, yearOfEra), month, dayOfMonth);\n }", "public static final UUID getUUID(InputStream is) throws IOException\n {\n byte[] data = new byte[16];\n is.read(data);\n\n long long1 = 0;\n long1 |= ((long) (data[3] & 0xFF)) << 56;\n long1 |= ((long) (data[2] & 0xFF)) << 48;\n long1 |= ((long) (data[1] & 0xFF)) << 40;\n long1 |= ((long) (data[0] & 0xFF)) << 32;\n long1 |= ((long) (data[5] & 0xFF)) << 24;\n long1 |= ((long) (data[4] & 0xFF)) << 16;\n long1 |= ((long) (data[7] & 0xFF)) << 8;\n long1 |= ((long) (data[6] & 0xFF)) << 0;\n\n long long2 = 0;\n long2 |= ((long) (data[8] & 0xFF)) << 56;\n long2 |= ((long) (data[9] & 0xFF)) << 48;\n long2 |= ((long) (data[10] & 0xFF)) << 40;\n long2 |= ((long) (data[11] & 0xFF)) << 32;\n long2 |= ((long) (data[12] & 0xFF)) << 24;\n long2 |= ((long) (data[13] & 0xFF)) << 16;\n long2 |= ((long) (data[14] & 0xFF)) << 8;\n long2 |= ((long) (data[15] & 0xFF)) << 0;\n\n return new UUID(long1, long2);\n }", "public void reinitIfClosed() {\n if (isClosed.get()) {\n logger.info(\"External Resource was released. Now Re-initializing resources ...\");\n\n ActorConfig.createAndGetActorSystem();\n httpClientStore.reinit();\n tcpSshPingResourceStore.reinit();\n try {\n Thread.sleep(1000l);\n } catch (InterruptedException e) {\n logger.error(\"error reinit httpClientStore\", e);\n }\n isClosed.set(false);\n logger.info(\"Parallel Client Resources has been reinitialized.\");\n } else {\n logger.debug(\"NO OP. Resource was not released.\");\n }\n }", "private ClassLoaderInterface getClassLoader() {\n\t\tMap<String, Object> application = ActionContext.getContext().getApplication();\n\t\tif (application != null) {\n\t\t\treturn (ClassLoaderInterface) application.get(ClassLoaderInterface.CLASS_LOADER_INTERFACE);\n\t\t}\n\t\treturn null;\n\t}", "public static Artifact withVersion(Version v)\n {\n Artifact artifact = new Artifact();\n artifact.version = v;\n return artifact;\n }", "public static void acceptsJson(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_J, OPT_JSON),\n \"fetch key/entry by key value of json type\")\n .withRequiredArg()\n .describedAs(\"key-list\")\n .withValuesSeparatedBy(',')\n .ofType(String.class);\n }", "static void addHeaders(HttpUriRequest httpRequest, HttpHeaders headers) {\n\t\tfor (Map.Entry<String, List<String>> entry : headers.entrySet()) {\n\t\t\tString headerName = entry.getKey();\n\t\t\tif (HttpHeaders.COOKIE.equalsIgnoreCase(headerName)) { // RFC 6265\n\t\t\t\tString headerValue = StringUtils.collectionToDelimitedString(entry.getValue(), \"; \");\n\t\t\t\thttpRequest.addHeader(headerName, headerValue);\n\t\t\t}\n\t\t\telse if (!HTTP.CONTENT_LEN.equalsIgnoreCase(headerName) &&\n\t\t\t\t\t!HTTP.TRANSFER_ENCODING.equalsIgnoreCase(headerName)) {\n\t\t\t\tfor (String headerValue : entry.getValue()) {\n\t\t\t\t\thttpRequest.addHeader(headerName, headerValue);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}" ]
Creates image stream request and returns it in JSON formatted string. @param name Name of the image stream @param insecure If the registry where the image is stored is insecure @param image Image name, includes registry information and tag @param version Image stream version. @return JSON formatted string
[ "private static String createImageStreamRequest(String name, String version, String image, boolean insecure) {\n JSONObject imageStream = new JSONObject();\n JSONObject metadata = new JSONObject();\n JSONObject annotations = new JSONObject();\n\n metadata.put(\"name\", name);\n annotations.put(\"openshift.io/image.insecureRepository\", insecure);\n metadata.put(\"annotations\", annotations);\n\n // Definition of the image\n JSONObject from = new JSONObject();\n from.put(\"kind\", \"DockerImage\");\n from.put(\"name\", image);\n\n JSONObject importPolicy = new JSONObject();\n importPolicy.put(\"insecure\", insecure);\n\n JSONObject tag = new JSONObject();\n tag.put(\"name\", version);\n tag.put(\"from\", from);\n tag.put(\"importPolicy\", importPolicy);\n\n JSONObject tagAnnotations = new JSONObject();\n tagAnnotations.put(\"version\", version);\n tag.put(\"annotations\", tagAnnotations);\n\n JSONArray tags = new JSONArray();\n tags.add(tag);\n\n // Add image definition to image stream\n JSONObject spec = new JSONObject();\n spec.put(\"tags\", tags);\n\n imageStream.put(\"kind\", \"ImageStream\");\n imageStream.put(\"apiVersion\", \"v1\");\n imageStream.put(\"metadata\", metadata);\n imageStream.put(\"spec\", spec);\n\n return imageStream.toJSONString();\n }" ]
[ "public SqlStatement getPreparedDeleteStatement(Query query, ClassDescriptor cld)\r\n {\r\n return new SqlDeleteByQuery(m_platform, cld, query, logger);\r\n }", "public TFuture<JsonResponse<AdvertiseResponse>> advertise() {\n\n final AdvertiseRequest advertiseRequest = new AdvertiseRequest();\n advertiseRequest.addService(service, 0);\n\n // TODO: options for hard fail, retries etc.\n final JsonRequest<AdvertiseRequest> request = new JsonRequest.Builder<AdvertiseRequest>(\n HYPERBAHN_SERVICE_NAME,\n HYPERBAHN_ADVERTISE_ENDPOINT\n )\n .setBody(advertiseRequest)\n .setTimeout(REQUEST_TIMEOUT)\n .setRetryLimit(4)\n .build();\n\n final TFuture<JsonResponse<AdvertiseResponse>> future = hyperbahnChannel.send(request);\n future.addCallback(new TFutureCallback<JsonResponse<AdvertiseResponse>>() {\n @Override\n public void onResponse(JsonResponse<AdvertiseResponse> response) {\n if (response.isError()) {\n logger.error(\"Failed to advertise to Hyperbahn: {} - {}\",\n response.getError().getErrorType(),\n response.getError().getMessage());\n }\n\n if (destroyed.get()) {\n return;\n }\n\n scheduleAdvertise();\n }\n });\n\n return future;\n }", "public InternalTile paint(InternalTile tile) throws RenderException {\n\t\tif (tile.getContentType().equals(VectorTileContentType.URL_CONTENT)) {\n\t\t\tif (urlBuilder != null) {\n\t\t\t\tif (paintGeometries) {\n\t\t\t\t\turlBuilder.paintGeometries(paintGeometries);\n\t\t\t\t\turlBuilder.paintLabels(false);\n\t\t\t\t\ttile.setFeatureContent(urlBuilder.getImageUrl());\n\t\t\t\t}\n\t\t\t\tif (paintLabels) {\n\t\t\t\t\turlBuilder.paintGeometries(false);\n\t\t\t\t\turlBuilder.paintLabels(paintLabels);\n\t\t\t\t\ttile.setLabelContent(urlBuilder.getImageUrl());\n\t\t\t\t}\n\t\t\t\treturn tile;\n\t\t\t}\n\t\t}\n\t\treturn tile;\n\t}", "@SuppressWarnings(\"WeakerAccess\")\n public Map<DeckReference, WaveformPreview> getLoadedPreviews() {\n ensureRunning();\n // Make a copy so callers get an immutable snapshot of the current state.\n return Collections.unmodifiableMap(new HashMap<DeckReference, WaveformPreview>(previewHotCache));\n }", "public void checkAllRequirementsSatisfied(final String currentPath) {\n StringBuilder errors = new StringBuilder();\n\n for (Field field: this.dependantsInJson) {\n final Collection<String> requirements = this.dependantToRequirementsMap.get(field);\n if (!requirements.isEmpty()) {\n errors.append(\"\\n\");\n String type = field.getType().getName();\n if (field.getType().isArray()) {\n type = field.getType().getComponentType().getName() + \"[]\";\n }\n errors.append(\"\\t* \").append(type).append(' ').append(field.getName()).append(\" depends on \")\n .append(requirements);\n }\n }\n Assert.equals(0, errors.length(),\n \"\\nErrors were detected when analysing the @Requires dependencies of '\" +\n currentPath + \"': \" + errors);\n }", "public void push( Token token ) {\n size++;\n if( first == null ) {\n first = token;\n last = token;\n token.previous = null;\n token.next = null;\n } else {\n last.next = token;\n token.previous = last;\n token.next = null;\n last = token;\n }\n }", "static void init() {// NOPMD\n\n\t\tdetermineIfNTEventLogIsSupported();\n\n\t\tURL resource = null;\n\n\t\tfinal String configurationOptionStr = OptionConverter.getSystemProperty(DEFAULT_CONFIGURATION_KEY, null);\n\n\t\tif (configurationOptionStr != null) {\n\t\t\ttry {\n\t\t\t\tresource = new URL(configurationOptionStr);\n\t\t\t} catch (MalformedURLException ex) {\n\t\t\t\t// so, resource is not a URL:\n\t\t\t\t// attempt to get the resource from the class path\n\t\t\t\tresource = Loader.getResource(configurationOptionStr);\n\t\t\t}\n\t\t}\n\t\tif (resource == null) {\n\t\t\tresource = Loader.getResource(DEFAULT_CONFIGURATION_FILE); // NOPMD\n\t\t}\n\n\t\tif (resource == null) {\n\t\t\tSystem.err.println(\"[FoundationLogger] Can not find resource: \" + DEFAULT_CONFIGURATION_FILE); // NOPMD\n\t\t\tthrow new FoundationIOException(\"Can not find resource: \" + DEFAULT_CONFIGURATION_FILE); // NOPMD\n\t\t}\n\n\t\t// update the log manager to use the Foundation repository.\n\t\tfinal RepositorySelector foundationRepositorySelector = new FoundationRepositorySelector(FoundationLogFactory.foundationLogHierarchy);\n\t\tLogManager.setRepositorySelector(foundationRepositorySelector, null);\n\n\t\t// set logger to info so we always want to see these logs even if root\n\t\t// is set to ERROR.\n\t\tfinal Logger logger = getLogger(FoundationLogger.class);\n\n\t\tfinal String logPropFile = resource.getPath();\n\t\tlog4jConfigProps = getLogProperties(resource);\n\t\t\n\t\t// select and configure again so the loggers are created with the right\n\t\t// level after the repository selector was updated.\n\t\tOptionConverter.selectAndConfigure(resource, null, FoundationLogFactory.foundationLogHierarchy);\n\n\t\t// start watching for property changes\n\t\tsetUpPropFileReloading(logger, logPropFile, log4jConfigProps);\n\n\t\t// add syslog appender or windows event viewer appender\n//\t\tsetupOSSystemLog(logger, log4jConfigProps);\n\n\t\t// parseMarkerPatterns(log4jConfigProps);\n\t\t// parseMarkerPurePattern(log4jConfigProps);\n//\t\tudpateMarkerStructuredLogOverrideMap(logger);\n\n AbstractFoundationLoggingMarker.init();\n\n\t\tupdateSniffingLoggersLevel(logger);\n\n setupJULSupport(resource);\n\n }", "@SuppressWarnings(\"unchecked\")\n private static synchronized Map<String, Boolean> getCache(GraphRewrite event)\n {\n Map<String, Boolean> result = (Map<String, Boolean>)event.getRewriteContext().get(ClassificationServiceCache.class);\n if (result == null)\n {\n result = Collections.synchronizedMap(new LRUMap(30000));\n event.getRewriteContext().put(ClassificationServiceCache.class, result);\n }\n return result;\n }", "public String format() {\r\n if (getName().equals(\"*\")) {\r\n return \"*\";\r\n }\r\n else {\r\n StringBuilder sb = new StringBuilder();\r\n if (isWeak()) {\r\n sb.append(\"W/\");\r\n }\r\n return sb.append('\"').append(getName()).append('\"').toString();\r\n }\r\n }" ]
Returns a representation of the date from the value attributes as ISO 8601 encoding. @param value @return ISO 8601 value (String)
[ "public static String formatTimeISO8601(TimeValue value) {\n\t\tStringBuilder builder = new StringBuilder();\n\t\tDecimalFormat yearForm = new DecimalFormat(FORMAT_YEAR);\n\t\tDecimalFormat timeForm = new DecimalFormat(FORMAT_OTHER);\n\t\tif (value.getYear() > 0) {\n\t\t\tbuilder.append(\"+\");\n\t\t}\n\t\tbuilder.append(yearForm.format(value.getYear()));\n\t\tbuilder.append(\"-\");\n\t\tbuilder.append(timeForm.format(value.getMonth()));\n\t\tbuilder.append(\"-\");\n\t\tbuilder.append(timeForm.format(value.getDay()));\n\t\tbuilder.append(\"T\");\n\t\tbuilder.append(timeForm.format(value.getHour()));\n\t\tbuilder.append(\":\");\n\t\tbuilder.append(timeForm.format(value.getMinute()));\n\t\tbuilder.append(\":\");\n\t\tbuilder.append(timeForm.format(value.getSecond()));\n\t\tbuilder.append(\"Z\");\n\t\treturn builder.toString();\n\t}" ]
[ "public Replication queryParams(Map<String, Object> queryParams) {\r\n this.replication = replication.queryParams(queryParams);\r\n return this;\r\n }", "public Duration getBaselineDuration()\n {\n Object result = getCachedValue(TaskField.BASELINE_DURATION);\n if (result == null)\n {\n result = getCachedValue(TaskField.BASELINE_ESTIMATED_DURATION);\n }\n\n if (!(result instanceof Duration))\n {\n result = null;\n }\n return (Duration) result;\n }", "protected static void checkQueues(final Iterable<String> queues) {\n if (queues == null) {\n throw new IllegalArgumentException(\"queues must not be null\");\n }\n for (final String queue : queues) {\n if (queue == null || \"\".equals(queue)) {\n throw new IllegalArgumentException(\"queues' members must not be null: \" + queues);\n }\n }\n }", "public void updateUniqueCounters()\n {\n //\n // Update task unique IDs\n //\n for (Task task : m_parent.getTasks())\n {\n int uniqueID = NumberHelper.getInt(task.getUniqueID());\n if (uniqueID > m_taskUniqueID)\n {\n m_taskUniqueID = uniqueID;\n }\n }\n\n //\n // Update resource unique IDs\n //\n for (Resource resource : m_parent.getResources())\n {\n int uniqueID = NumberHelper.getInt(resource.getUniqueID());\n if (uniqueID > m_resourceUniqueID)\n {\n m_resourceUniqueID = uniqueID;\n }\n }\n\n //\n // Update calendar unique IDs\n //\n for (ProjectCalendar calendar : m_parent.getCalendars())\n {\n int uniqueID = NumberHelper.getInt(calendar.getUniqueID());\n if (uniqueID > m_calendarUniqueID)\n {\n m_calendarUniqueID = uniqueID;\n }\n }\n\n //\n // Update assignment unique IDs\n //\n for (ResourceAssignment assignment : m_parent.getResourceAssignments())\n {\n int uniqueID = NumberHelper.getInt(assignment.getUniqueID());\n if (uniqueID > m_assignmentUniqueID)\n {\n m_assignmentUniqueID = uniqueID;\n }\n }\n }", "public static policydataset get(nitro_service service, String name) throws Exception{\n\t\tpolicydataset obj = new policydataset();\n\t\tobj.set_name(name);\n\t\tpolicydataset response = (policydataset) obj.get_resource(service);\n\t\treturn response;\n\t}", "public TokenList extractSubList( Token begin , Token end ) {\n if( begin == end ) {\n remove(begin);\n return new TokenList(begin,begin);\n } else {\n if( first == begin ) {\n first = end.next;\n }\n if( last == end ) {\n last = begin.previous;\n }\n if( begin.previous != null ) {\n begin.previous.next = end.next;\n }\n if( end.next != null ) {\n end.next.previous = begin.previous;\n }\n begin.previous = null;\n end.next = null;\n\n TokenList ret = new TokenList(begin,end);\n size -= ret.size();\n return ret;\n }\n }", "public MaterialAccount getAccountByTitle(String title) {\n for(MaterialAccount account : accountManager)\n if(currentAccount.getTitle().equals(title))\n return account;\n\n return null;\n }", "private String randomString(String[] s) {\n if (s == null || s.length <= 0) return \"\";\n return s[this.random.nextInt(s.length)];\n }", "private void writeCalendar(ProjectCalendar mpxjCalendar, net.sf.mpxj.planner.schema.Calendar plannerCalendar) throws JAXBException\n {\n //\n // Populate basic details\n //\n plannerCalendar.setId(getIntegerString(mpxjCalendar.getUniqueID()));\n plannerCalendar.setName(getString(mpxjCalendar.getName()));\n\n //\n // Set working and non working days\n //\n DefaultWeek dw = m_factory.createDefaultWeek();\n plannerCalendar.setDefaultWeek(dw);\n dw.setMon(getWorkingDayString(mpxjCalendar, Day.MONDAY));\n dw.setTue(getWorkingDayString(mpxjCalendar, Day.TUESDAY));\n dw.setWed(getWorkingDayString(mpxjCalendar, Day.WEDNESDAY));\n dw.setThu(getWorkingDayString(mpxjCalendar, Day.THURSDAY));\n dw.setFri(getWorkingDayString(mpxjCalendar, Day.FRIDAY));\n dw.setSat(getWorkingDayString(mpxjCalendar, Day.SATURDAY));\n dw.setSun(getWorkingDayString(mpxjCalendar, Day.SUNDAY));\n\n //\n // Set working hours\n //\n OverriddenDayTypes odt = m_factory.createOverriddenDayTypes();\n plannerCalendar.setOverriddenDayTypes(odt);\n List<OverriddenDayType> typeList = odt.getOverriddenDayType();\n Sequence uniqueID = new Sequence(0);\n\n //\n // This is a bit arbitrary, so not ideal, however...\n // The idea here is that MS Project allows us to specify working hours\n // for each day of the week individually. Planner doesn't do this,\n // but instead allows us to specify working hours for each day type.\n // What we are doing here is stepping through the days of the week to\n // find the first working day, then using the hours for that day\n // as the hours for the working day type in Planner.\n //\n for (int dayLoop = 1; dayLoop < 8; dayLoop++)\n {\n Day day = Day.getInstance(dayLoop);\n if (mpxjCalendar.isWorkingDay(day))\n {\n processWorkingHours(mpxjCalendar, uniqueID, day, typeList);\n break;\n }\n }\n\n //\n // Process exception days\n //\n Days plannerDays = m_factory.createDays();\n plannerCalendar.setDays(plannerDays);\n List<net.sf.mpxj.planner.schema.Day> dayList = plannerDays.getDay();\n processExceptionDays(mpxjCalendar, dayList);\n\n m_eventManager.fireCalendarWrittenEvent(mpxjCalendar);\n\n //\n // Process any derived calendars\n //\n List<net.sf.mpxj.planner.schema.Calendar> calendarList = plannerCalendar.getCalendar();\n\n for (ProjectCalendar mpxjDerivedCalendar : mpxjCalendar.getDerivedCalendars())\n {\n net.sf.mpxj.planner.schema.Calendar plannerDerivedCalendar = m_factory.createCalendar();\n calendarList.add(plannerDerivedCalendar);\n writeCalendar(mpxjDerivedCalendar, plannerDerivedCalendar);\n }\n }" ]
Use this API to update snmpuser.
[ "public static base_response update(nitro_service client, snmpuser resource) throws Exception {\n\t\tsnmpuser updateresource = new snmpuser();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.group = resource.group;\n\t\tupdateresource.authtype = resource.authtype;\n\t\tupdateresource.authpasswd = resource.authpasswd;\n\t\tupdateresource.privtype = resource.privtype;\n\t\tupdateresource.privpasswd = resource.privpasswd;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
[ "public void removePath(int pathId) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n // remove any enabled overrides with this path\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \" = ?\"\n );\n statement.setInt(1, pathId);\n statement.executeUpdate();\n statement.close();\n\n // remove path\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_PATH\n + \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, pathId);\n statement.executeUpdate();\n statement.close();\n\n //remove path from responseRequest\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_REQUEST_RESPONSE\n + \" WHERE \" + Constants.REQUEST_RESPONSE_PATH_ID + \" = ?\"\n );\n statement.setInt(1, pathId);\n statement.executeUpdate();\n statement.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "public static RgbaColor fromRgba(String rgba) {\n if (rgba.length() == 0) return getDefaultColor();\n\n String[] parts = getRgbaParts(rgba).split(\",\");\n if (parts.length == 4) {\n return new RgbaColor(parseInt(parts[0]),\n parseInt(parts[1]),\n parseInt(parts[2]),\n parseFloat(parts[3]));\n }\n else {\n return getDefaultColor();\n }\n }", "public List<BoxTaskAssignment.Info> getAssignments() {\n URL url = GET_ASSIGNMENTS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int totalCount = responseJSON.get(\"total_count\").asInt();\n List<BoxTaskAssignment.Info> assignments = new ArrayList<BoxTaskAssignment.Info>(totalCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : entries) {\n JsonObject assignmentJSON = value.asObject();\n BoxTaskAssignment assignment = new BoxTaskAssignment(this.getAPI(), assignmentJSON.get(\"id\").asString());\n BoxTaskAssignment.Info info = assignment.new Info(assignmentJSON);\n assignments.add(info);\n }\n\n return assignments;\n }", "public InputStream getInstance(DirectoryEntry directory, String name) throws IOException\n {\n DocumentEntry entry = (DocumentEntry) directory.getEntry(name);\n InputStream stream;\n if (m_encrypted)\n {\n stream = new EncryptedDocumentInputStream(entry, m_encryptionCode);\n }\n else\n {\n stream = new DocumentInputStream(entry);\n }\n\n return stream;\n }", "static <T> StitchEvent<T> fromEvent(final Event event,\n final Decoder<T> decoder) {\n return new StitchEvent<>(event.getEventName(), event.getData(), decoder);\n }", "protected <T> T invokeJavascriptReturnValue(String function, Class<T> returnType) {\n Object returnObject = invokeJavascript(function);\n if (returnObject instanceof JSObject) {\n try {\n Constructor<T> constructor = returnType.getConstructor(JSObject.class);\n return constructor.newInstance((JSObject) returnObject);\n } catch (Exception ex) {\n throw new IllegalStateException(ex);\n }\n } else {\n return (T) returnObject;\n }\n }", "public static ComplexNumber Tan(ComplexNumber z1) {\r\n ComplexNumber result = new ComplexNumber();\r\n\r\n if (z1.imaginary == 0.0) {\r\n result.real = Math.tan(z1.real);\r\n result.imaginary = 0.0;\r\n } else {\r\n double real2 = 2 * z1.real;\r\n double imag2 = 2 * z1.imaginary;\r\n double denom = Math.cos(real2) + Math.cosh(real2);\r\n\r\n result.real = Math.sin(real2) / denom;\r\n result.imaginary = Math.sinh(imag2) / denom;\r\n }\r\n\r\n return result;\r\n }", "public CollectionDescriptor getCollectionDescriptorByName(String name)\r\n {\r\n if (name == null)\r\n {\r\n return null;\r\n }\r\n\r\n CollectionDescriptor cod = (CollectionDescriptor) getCollectionDescriptorNameMap().get(name);\r\n\r\n //\r\n // BRJ: if the CollectionDescriptor is not found\r\n // look in the ClassDescriptor referenced by 'super' for it\r\n //\r\n if (cod == null)\r\n {\r\n ClassDescriptor superCld = getSuperClassDescriptor();\r\n if (superCld != null)\r\n {\r\n cod = superCld.getCollectionDescriptorByName(name);\r\n }\r\n }\r\n\r\n return cod;\r\n }", "public Path relativize(Path other) {\n\t\tif (other.isAbsolute() != isAbsolute())\n\t\t\tthrow new IllegalArgumentException(\"This path and the given path are not both absolute or both relative: \" + toString() + \" | \" + other.toString());\n\t\tif (startsWith(other)) {\n\t\t\treturn internalRelativize(this, other);\n\t\t} else if (other.startsWith(this)) {\n\t\t\treturn internalRelativize(other, this);\n\t\t}\n\t\treturn null;\n\t}" ]
Read the leaf tasks for an individual WBS node. @param parent parent task @param id first task ID
[ "private void readLeafTasks(Task parent, Integer id)\n {\n Integer currentID = id;\n Table table = getTable(\"A1TAB\");\n while (currentID.intValue() != 0)\n {\n if (m_projectFile.getTaskByUniqueID(currentID) == null)\n {\n readTask(parent, currentID);\n }\n currentID = table.find(currentID).getInteger(\"NEXT_TASK_ID\");\n }\n }" ]
[ "public AccrueType getAccrueType(int field)\n {\n AccrueType result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n result = AccrueTypeUtility.getInstance(m_fields[field], m_locale);\n }\n else\n {\n result = null;\n }\n\n return (result);\n }", "public static vpnglobal_auditnslogpolicy_binding[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tvpnglobal_auditnslogpolicy_binding obj = new vpnglobal_auditnslogpolicy_binding();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tvpnglobal_auditnslogpolicy_binding[] response = (vpnglobal_auditnslogpolicy_binding[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}", "protected <E> E read(Supplier<E> sup) {\n try {\n this.lock.readLock().lock();\n return sup.get();\n } finally {\n this.lock.readLock().unlock();\n }\n }", "public void setWeekDays(SortedSet<WeekDay> weekDays) {\n\n final SortedSet<WeekDay> newWeekDays = null == weekDays ? new TreeSet<WeekDay>() : weekDays;\n SortedSet<WeekDay> currentWeekDays = m_model.getWeekDays();\n if (!currentWeekDays.equals(newWeekDays)) {\n conditionallyRemoveExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setWeekDays(newWeekDays);\n onValueChange();\n }\n }, !newWeekDays.containsAll(m_model.getWeekDays()));\n }\n }", "public static String format(ImageFormat format) {\n if (format == null) {\n throw new IllegalArgumentException(\"You must specify an image format.\");\n }\n return FILTER_FORMAT + \"(\" + format.value + \")\";\n }", "private AsyncResourceRequest<V> getNextUnexpiredResourceRequest(Queue<AsyncResourceRequest<V>> requestQueue) {\n AsyncResourceRequest<V> resourceRequest = requestQueue.poll();\n while(resourceRequest != null) {\n if(resourceRequest.getDeadlineNs() < System.nanoTime()) {\n resourceRequest.handleTimeout();\n resourceRequest = requestQueue.poll();\n } else {\n break;\n }\n }\n return resourceRequest;\n }", "public Object getProxyTarget(){\r\n\t\ttry {\r\n\t\t\treturn Proxy.getInvocationHandler(this.connection).invoke(null, this.getClass().getMethod(\"getProxyTarget\"), null);\r\n\t\t} catch (Throwable t) {\r\n\t\t\tthrow new RuntimeException(\"BoneCP: Internal error - transaction replay log is not turned on?\", t);\r\n\t\t}\r\n\t}", "protected void debugLog(String operationType, Long receivedTimeInMs) {\n long durationInMs = receivedTimeInMs - (this.parsedRequestOriginTimeInMs);\n int numVectorClockEntries = (this.parsedVectorClock == null ? 0\n : this.parsedVectorClock.getVersionMap()\n .size());\n logger.debug(\"Received a new request. Operation type: \" + operationType + \" , Key(s): \"\n + keysHexString(this.parsedKeys) + \" , Store: \" + this.storeName\n + \" , Origin time (in ms): \" + (this.parsedRequestOriginTimeInMs)\n + \" , Request received at time(in ms): \" + receivedTimeInMs\n + \" , Num vector clock entries: \" + numVectorClockEntries\n + \" , Duration from RESTClient to CoordinatorRestRequestValidator(in ms): \"\n + durationInMs);\n\n }", "public static <E> Set<E> setify(ObjectMapper mapper, Object source, Class<E> targetElementType) {\n return (Set<E>) collectify(mapper, source, Set.class, targetElementType);\n }" ]
generate a message for loglevel ERROR @param pObject the message Object
[ "public final void error(Object pObject)\r\n\t{\r\n\t\tgetLogger().log(FQCN, Level.ERROR, pObject, null);\r\n\t}" ]
[ "private void setVerticalScrollbar(final CmsScrollBar scrollbar, int width) {\r\n\r\n // Validate.\r\n if ((scrollbar == m_scrollbar) || (scrollbar == null)) {\r\n return;\r\n }\r\n // Detach new child.\r\n\r\n scrollbar.asWidget().removeFromParent();\r\n // Remove old child.\r\n if (m_scrollbar != null) {\r\n if (m_verticalScrollbarHandlerRegistration != null) {\r\n m_verticalScrollbarHandlerRegistration.removeHandler();\r\n m_verticalScrollbarHandlerRegistration = null;\r\n }\r\n remove(m_scrollbar);\r\n }\r\n m_scrollLayer.appendChild(scrollbar.asWidget().getElement());\r\n adopt(scrollbar.asWidget());\r\n\r\n // Logical attach.\r\n m_scrollbar = scrollbar;\r\n m_verticalScrollbarWidth = width;\r\n\r\n // Initialize the new scrollbar.\r\n m_verticalScrollbarHandlerRegistration = scrollbar.addValueChangeHandler(new ValueChangeHandler<Integer>() {\r\n\r\n public void onValueChange(ValueChangeEvent<Integer> event) {\r\n\r\n int vPos = scrollbar.getVerticalScrollPosition();\r\n int v = getVerticalScrollPosition();\r\n if (v != vPos) {\r\n setVerticalScrollPosition(vPos);\r\n }\r\n\r\n }\r\n });\r\n maybeUpdateScrollbars();\r\n }", "@SuppressWarnings(\"unchecked\")\n public void put(String key, Versioned<Object> value) {\n // acquire write lock\n writeLock.lock();\n\n try {\n if(this.storeNames.contains(key) || key.equals(STORES_KEY)) {\n\n // Check for backwards compatibility\n List<StoreDefinition> storeDefinitions = (List<StoreDefinition>) value.getValue();\n StoreDefinitionUtils.validateSchemasAsNeeded(storeDefinitions);\n\n // If the put is on the entire stores.xml key, delete the\n // additional stores which do not exist in the specified\n // stores.xml\n Set<String> storeNamesToDelete = new HashSet<String>();\n for(String storeName: this.storeNames) {\n storeNamesToDelete.add(storeName);\n }\n\n // Add / update the list of store definitions specified in the\n // value\n StoreDefinitionsMapper mapper = new StoreDefinitionsMapper();\n\n // Update the STORES directory and the corresponding entry in\n // metadata cache\n Set<String> specifiedStoreNames = new HashSet<String>();\n for(StoreDefinition storeDef: storeDefinitions) {\n specifiedStoreNames.add(storeDef.getName());\n String storeDefStr = mapper.writeStore(storeDef);\n Versioned<String> versionedValueStr = new Versioned<String>(storeDefStr,\n value.getVersion());\n this.storeDefinitionsStorageEngine.put(storeDef.getName(),\n versionedValueStr,\n \"\");\n\n // Update the metadata cache\n this.metadataCache.put(storeDef.getName(),\n new Versioned<Object>(storeDefStr, value.getVersion()));\n }\n\n if(key.equals(STORES_KEY)) {\n storeNamesToDelete.removeAll(specifiedStoreNames);\n resetStoreDefinitions(storeNamesToDelete);\n }\n\n // Re-initialize the store definitions\n initStoreDefinitions(value.getVersion());\n\n // Update routing strategies\n updateRoutingStrategies(getCluster(), getStoreDefList());\n\n } else if(METADATA_KEYS.contains(key)) {\n // try inserting into inner store first\n putInner(key, convertObjectToString(key, value));\n\n // cache all keys if innerStore put succeeded\n metadataCache.put(key, value);\n\n // do special stuff if needed\n if(CLUSTER_KEY.equals(key)) {\n updateRoutingStrategies((Cluster) value.getValue(), getStoreDefList());\n } else if(NODE_ID_KEY.equals(key)) {\n initNodeId(getNodeIdNoLock());\n } else if(SYSTEM_STORES_KEY.equals(key))\n throw new VoldemortException(\"Cannot overwrite system store definitions\");\n\n } else {\n throw new VoldemortException(\"Unhandled Key:\" + key + \" for MetadataStore put()\");\n }\n } finally {\n writeLock.unlock();\n }\n }", "public 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 }", "private Map<String, Criteria> getCriterias(Map<String, String[]> params) {\n Map<String, Criteria> result = new HashMap<String, Criteria>();\n for (Map.Entry<String, String[]> param : params.entrySet()) {\n for (Criteria criteria : FILTER_CRITERIAS) {\n if (criteria.getName().equals(param.getKey())) {\n try {\n Criteria[] parsedCriterias = criteria.parseValue(param.getValue()[0]);\n for (Criteria parsedCriteria : parsedCriterias) {\n result.put(parsedCriteria.getName(), parsedCriteria);\n }\n } catch (Exception e) {\n // Exception happened during paring\n LOG.log(Level.SEVERE, \"Error parsing parameter \" + param.getKey(), e);\n }\n break;\n }\n }\n }\n return result;\n }", "public static Map<FieldType, String> getDefaultResourceFieldMap()\n {\n Map<FieldType, String> map = new LinkedHashMap<FieldType, String>();\n\n map.put(ResourceField.UNIQUE_ID, \"rsrc_id\");\n map.put(ResourceField.GUID, \"guid\");\n map.put(ResourceField.NAME, \"rsrc_name\");\n map.put(ResourceField.CODE, \"employee_code\");\n map.put(ResourceField.EMAIL_ADDRESS, \"email_addr\");\n map.put(ResourceField.NOTES, \"rsrc_notes\");\n map.put(ResourceField.CREATED, \"create_date\");\n map.put(ResourceField.TYPE, \"rsrc_type\");\n map.put(ResourceField.INITIALS, \"rsrc_short_name\");\n map.put(ResourceField.PARENT_ID, \"parent_rsrc_id\");\n\n return map;\n }", "@SuppressWarnings(\"unchecked\")\n protected void addPostRunDependent(Executable<? extends Indexable> executable) {\n TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) executable;\n this.addPostRunDependent(dependency);\n }", "public static dospolicy[] get(nitro_service service) throws Exception{\n\t\tdospolicy obj = new dospolicy();\n\t\tdospolicy[] response = (dospolicy[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public static String convertToFileSystemChar(String name) {\n String erg = \"\";\n Matcher m = Pattern.compile(\"[a-z0-9 _#&@\\\\[\\\\(\\\\)\\\\]\\\\-\\\\.]\", Pattern.CASE_INSENSITIVE).matcher(name);\n while (m.find()) {\n erg += name.substring(m.start(), m.end());\n }\n if (erg.length() > 200) {\n erg = erg.substring(0, 200);\n System.out.println(\"cut filename: \" + erg);\n }\n return erg;\n }", "public static void endRequest() {\n final List<RequestScopedItem> result = CACHE.get();\n if (result != null) {\n CACHE.remove();\n for (final RequestScopedItem item : result) {\n item.invalidate();\n }\n }\n }" ]
Use this API to enable nsfeature.
[ "public static base_response enable(nitro_service client, nsfeature resource) throws Exception {\n\t\tnsfeature enableresource = new nsfeature();\n\t\tenableresource.feature = resource.feature;\n\t\treturn enableresource.perform_operation(client,\"enable\");\n\t}" ]
[ "boolean lockInterruptibly(final Integer permit, final long timeout, final TimeUnit unit) throws InterruptedException {\n if (permit == null) {\n throw new IllegalArgumentException();\n }\n return sync.tryAcquireNanos(permit, unit.toNanos(timeout));\n }", "private int[] changeColor() {\n int[] changedPixels = new int[pixels.length];\n double frequenz = 2 * Math.PI / 1020;\n\n for (int i = 0; i < pixels.length; i++) {\n int argb = pixels[i];\n int a = (argb >> 24) & 0xff;\n int r = (argb >> 16) & 0xff;\n int g = (argb >> 8) & 0xff;\n int b = argb & 0xff;\n\n r = (int) (255 * Math.sin(frequenz * r));\n b = (int) (-255 * Math.cos(frequenz * b) + 255);\n\n changedPixels[i] = (a << 24) | (r << 16) | (g << 8) | b;\n }\n\n return changedPixels;\n }", "public int update(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException {\n\t\ttry {\n\t\t\t// there is always and id field as an argument so just return 0 lines updated\n\t\t\tif (argFieldTypes.length <= 1) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tObject[] args = getFieldObjects(data);\n\t\t\tObject newVersion = null;\n\t\t\tif (versionFieldType != null) {\n\t\t\t\tnewVersion = versionFieldType.extractJavaFieldValue(data);\n\t\t\t\tnewVersion = versionFieldType.moveToNextValue(newVersion);\n\t\t\t\targs[versionFieldTypeIndex] = versionFieldType.convertJavaFieldToSqlArgValue(newVersion);\n\t\t\t}\n\t\t\tint rowC = databaseConnection.update(statement, args, argFieldTypes);\n\t\t\tif (rowC > 0) {\n\t\t\t\tif (newVersion != null) {\n\t\t\t\t\t// if we have updated a row then update the version field in our object to the new value\n\t\t\t\t\tversionFieldType.assignField(connectionSource, data, newVersion, false, null);\n\t\t\t\t}\n\t\t\t\tif (objectCache != null) {\n\t\t\t\t\t// if we've changed something then see if we need to update our cache\n\t\t\t\t\tObject id = idField.extractJavaFieldValue(data);\n\t\t\t\t\tT cachedData = objectCache.get(clazz, id);\n\t\t\t\t\tif (cachedData != null && cachedData != data) {\n\t\t\t\t\t\t// copy each field from the updated data into the cached object\n\t\t\t\t\t\tfor (FieldType fieldType : tableInfo.getFieldTypes()) {\n\t\t\t\t\t\t\tif (fieldType != idField) {\n\t\t\t\t\t\t\t\tfieldType.assignField(connectionSource, cachedData,\n\t\t\t\t\t\t\t\t\t\tfieldType.extractJavaFieldValue(data), false, objectCache);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tlogger.debug(\"update data with statement '{}' and {} args, changed {} rows\", statement, args.length, rowC);\n\t\t\tif (args.length > 0) {\n\t\t\t\t// need to do the (Object) cast to force args to be a single object\n\t\t\t\tlogger.trace(\"update arguments: {}\", (Object) args);\n\t\t\t}\n\t\t\treturn rowC;\n\t\t} catch (SQLException e) {\n\t\t\tthrow SqlExceptionUtil.create(\"Unable to run update stmt on object \" + data + \": \" + statement, e);\n\t\t}\n\t}", "public void end(String key)\n {\n if (key == null)\n {\n return;\n }\n TimingData data = executionInfo.get(key);\n if (data == null)\n {\n LOG.info(\"Called end with key: \" + key + \" without ever calling begin\");\n return;\n }\n data.end();\n }", "private void populateContainer(FieldType field, byte[] values, byte[] descriptions)\n {\n CustomField config = m_container.getCustomField(field);\n CustomFieldLookupTable table = config.getLookupTable();\n\n List<Object> descriptionList = convertType(DataType.STRING, descriptions);\n List<Object> valueList = convertType(field.getDataType(), values);\n for (int index = 0; index < descriptionList.size(); index++)\n {\n CustomFieldValueItem item = new CustomFieldValueItem(Integer.valueOf(0));\n item.setDescription((String) descriptionList.get(index));\n if (index < valueList.size())\n {\n item.setValue(valueList.get(index));\n }\n table.add(item);\n }\n }", "public static <T> T buildInstanceForMap(Class<T> clazz, Map<String, Object> values)\n throws InstantiationException, IllegalAccessException, IntrospectionException,\n IllegalArgumentException, InvocationTargetException {\n return buildInstanceForMap(clazz, values, new MyDefaultReflectionDifferenceHandler());\n }", "private static void checkSorted(int[] sorted) {\r\n for (int i = 0; i < sorted.length-1; i++) {\r\n if (sorted[i] > sorted[i+1]) {\r\n throw new RuntimeException(\"input must be sorted!\");\r\n }\r\n }\r\n }", "public static base_responses unset(nitro_service client, String username[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (username != null && username.length > 0) {\n\t\t\tsystemuser unsetresources[] = new systemuser[username.length];\n\t\t\tfor (int i=0;i<username.length;i++){\n\t\t\t\tunsetresources[i] = new systemuser();\n\t\t\t\tunsetresources[i].username = username[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}", "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 }" ]
Build a new WebDriver based EmbeddedBrowser. @return the new build WebDriver based embeddedBrowser
[ "@Override\n\tpublic EmbeddedBrowser get() {\n\t\tLOGGER.debug(\"Setting up a Browser\");\n\t\t// Retrieve the config values used\n\t\tImmutableSortedSet<String> filterAttributes =\n\t\t\t\tconfiguration.getCrawlRules().getPreCrawlConfig().getFilterAttributeNames();\n\t\tlong crawlWaitReload = configuration.getCrawlRules().getWaitAfterReloadUrl();\n\t\tlong crawlWaitEvent = configuration.getCrawlRules().getWaitAfterEvent();\n\n\t\t// Determine the requested browser type\n\t\tEmbeddedBrowser browser = null;\n\t\tEmbeddedBrowser.BrowserType browserType =\n\t\t\t\tconfiguration.getBrowserConfig().getBrowserType();\n\t\ttry {\n\t\t\tswitch (browserType) {\n\t\t\t\tcase CHROME:\n\t\t\t\t\tbrowser = newChromeBrowser(filterAttributes, crawlWaitReload, crawlWaitEvent,\n\t\t\t\t\t\t\tfalse);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CHROME_HEADLESS:\n\t\t\t\t\tbrowser = newChromeBrowser(filterAttributes, crawlWaitReload,\n\t\t\t\t\t\t\tcrawlWaitEvent, true);\n\t\t\t\t\tbreak;\n\t\t\t\tcase FIREFOX:\n\t\t\t\t\tbrowser = newFirefoxBrowser(filterAttributes, crawlWaitReload, crawlWaitEvent,\n\t\t\t\t\t\t\tfalse);\n\t\t\t\t\tbreak;\n\t\t\t\tcase FIREFOX_HEADLESS:\n\t\t\t\t\tbrowser = newFirefoxBrowser(filterAttributes, crawlWaitReload, crawlWaitEvent,\n\t\t\t\t\t\t\ttrue);\n\t\t\t\t\tbreak;\n\t\t\t\tcase REMOTE:\n\t\t\t\t\tbrowser = WebDriverBackedEmbeddedBrowser.withRemoteDriver(\n\t\t\t\t\t\t\tconfiguration.getBrowserConfig().getRemoteHubUrl(), filterAttributes,\n\t\t\t\t\t\t\tcrawlWaitEvent, crawlWaitReload);\n\t\t\t\t\tbreak;\n\t\t\t\tcase PHANTOMJS:\n\t\t\t\t\tbrowser =\n\t\t\t\t\t\t\tnewPhantomJSDriver(filterAttributes, crawlWaitReload, crawlWaitEvent);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new IllegalStateException(\"Unrecognized browser type \"\n\t\t\t\t\t\t\t+ configuration.getBrowserConfig().getBrowserType());\n\t\t\t}\n\t\t} catch (IllegalStateException e) {\n\t\t\tLOGGER.error(\"Crawling with {} failed: \" + e.getMessage(), browserType.toString());\n\t\t\tthrow e;\n\t\t}\n\n\t\t/* for Retina display. */\n\t\tif (browser instanceof WebDriverBackedEmbeddedBrowser) {\n\t\t\tint pixelDensity =\n\t\t\t\t\tthis.configuration.getBrowserConfig().getBrowserOptions().getPixelDensity();\n\t\t\tif (pixelDensity != -1)\n\t\t\t\t((WebDriverBackedEmbeddedBrowser) browser).setPixelDensity(pixelDensity);\n\t\t}\n\n\t\tplugins.runOnBrowserCreatedPlugins(browser);\n\t\treturn browser;\n\t}" ]
[ "public ItemRequest<ProjectStatus> createInProject(String project) {\n\n String path = String.format(\"/projects/%s/project_statuses\", project);\n return new ItemRequest<ProjectStatus>(this, ProjectStatus.class, path, \"POST\");\n }", "public static void setSourceLevelUrisWithoutCopy(final ResourceSet resourceSet, final Set<URI> uris) {\n final SourceLevelURIsAdapter adapter = SourceLevelURIsAdapter.findOrCreateAdapter(resourceSet);\n adapter.sourceLevelURIs = uris;\n }", "@SuppressWarnings({\"WeakerAccess\"})\n protected void initDeviceID() {\n getDeviceCachedInfo(); // put this here to avoid running on main thread\n\n // generate a provisional while we do the rest async\n generateProvisionalGUID();\n // grab and cache the googleAdID in any event if available\n // if we already have a deviceID we won't user ad id as the guid\n cacheGoogleAdID();\n\n // if we already have a device ID use it and just notify\n // otherwise generate one, either from ad id if available or the provisional\n String deviceID = getDeviceID();\n if (deviceID == null || deviceID.trim().length() <= 2) {\n generateDeviceID();\n }\n\n }", "public void processSplitData(Task task, List<TimephasedWork> timephasedComplete, List<TimephasedWork> timephasedPlanned)\n {\n Date splitsComplete = null;\n TimephasedWork lastComplete = null;\n TimephasedWork firstPlanned = null;\n if (!timephasedComplete.isEmpty())\n {\n lastComplete = timephasedComplete.get(timephasedComplete.size() - 1);\n splitsComplete = lastComplete.getFinish();\n }\n\n if (!timephasedPlanned.isEmpty())\n {\n firstPlanned = timephasedPlanned.get(0);\n }\n\n LinkedList<DateRange> splits = new LinkedList<DateRange>();\n TimephasedWork lastAssignment = null;\n DateRange lastRange = null;\n for (TimephasedWork assignment : timephasedComplete)\n {\n if (lastAssignment != null && lastRange != null && lastAssignment.getTotalAmount().getDuration() != 0 && assignment.getTotalAmount().getDuration() != 0)\n {\n splits.removeLast();\n lastRange = new DateRange(lastRange.getStart(), assignment.getFinish());\n }\n else\n {\n lastRange = new DateRange(assignment.getStart(), assignment.getFinish());\n }\n splits.add(lastRange);\n lastAssignment = assignment;\n }\n\n //\n // We may not have a split, we may just have a partially\n // complete split.\n //\n Date splitStart = null;\n if (lastComplete != null && firstPlanned != null && lastComplete.getTotalAmount().getDuration() != 0 && firstPlanned.getTotalAmount().getDuration() != 0)\n {\n lastRange = splits.removeLast();\n splitStart = lastRange.getStart();\n }\n\n lastAssignment = null;\n lastRange = null;\n for (TimephasedWork assignment : timephasedPlanned)\n {\n if (splitStart == null)\n {\n if (lastAssignment != null && lastRange != null && lastAssignment.getTotalAmount().getDuration() != 0 && assignment.getTotalAmount().getDuration() != 0)\n {\n splits.removeLast();\n lastRange = new DateRange(lastRange.getStart(), assignment.getFinish());\n }\n else\n {\n lastRange = new DateRange(assignment.getStart(), assignment.getFinish());\n }\n }\n else\n {\n lastRange = new DateRange(splitStart, assignment.getFinish());\n }\n splits.add(lastRange);\n splitStart = null;\n lastAssignment = assignment;\n }\n\n //\n // We must have a minimum of 3 entries for this to be a valid split task\n //\n if (splits.size() > 2)\n {\n task.getSplits().addAll(splits);\n task.setSplitCompleteDuration(splitsComplete);\n }\n else\n {\n task.setSplits(null);\n task.setSplitCompleteDuration(null);\n }\n }", "public void set(int index, T object) {\n synchronized (mLock) {\n if (mOriginalValues != null) {\n mOriginalValues.set(index, object);\n } else {\n mObjects.set(index, object);\n }\n }\n if (mNotifyOnChange) notifyDataSetChanged();\n }", "public static String taskListToString(List<RebalanceTaskInfo> infos) {\n StringBuffer sb = new StringBuffer();\n for (RebalanceTaskInfo info : infos) {\n sb.append(\"\\t\").append(info.getDonorId()).append(\" -> \").append(info.getStealerId()).append(\" : [\");\n for (String storeName : info.getPartitionStores()) {\n sb.append(\"{\").append(storeName).append(\" : \").append(info.getPartitionIds(storeName)).append(\"}\");\n }\n sb.append(\"]\").append(Utils.NEWLINE);\n }\n return sb.toString();\n }", "protected static List<StackTraceElement> filterStackTrace(StackTraceElement[] stack) {\r\n List<StackTraceElement> filteredStack = new ArrayList<StackTraceElement>();\r\n\r\n int i = 2; // we can skip the first two (first is getStackTrace(), second is this method)\r\n while (i < stack.length) {\r\n boolean isLoggingClass = false;\r\n for (String loggingClass : loggingClasses) {\r\n String className = stack[i].getClassName();\r\n if (className.startsWith(loggingClass)) {\r\n isLoggingClass = true;\r\n break;\r\n }\r\n }\r\n if (!isLoggingClass) {\r\n filteredStack.add(stack[i]);\r\n }\r\n\r\n i += 1;\r\n }\r\n\r\n // if we didn't find anything, keep the full stack\r\n if (filteredStack.size() == 0) {\r\n return Arrays.asList(stack);\r\n }\r\n return filteredStack;\r\n }", "private static final void writeJson(Writer os, //\n Object object, //\n SerializeConfig config, //\n SerializeFilter[] filters, //\n DateFormat dateFormat, //\n int defaultFeatures, //\n SerializerFeature... features) {\n SerializeWriter writer = new SerializeWriter(os, defaultFeatures, features);\n\n try {\n JSONSerializer serializer = new JSONSerializer(writer, config);\n\n if (dateFormat != null) {\n serializer.setDateFormat(dateFormat);\n serializer.config(SerializerFeature.WriteDateUseDateFormat, true);\n }\n\n if (filters != null) {\n for (SerializeFilter filter : filters) {\n serializer.addFilter(filter);\n }\n }\n serializer.write(object);\n } finally {\n writer.close();\n }\n }", "public void fireCalendarReadEvent(ProjectCalendar calendar)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.calendarRead(calendar);\n }\n }\n }" ]
Set a proxy for REST-requests. @param proxyHost @param proxyPort
[ "public void setProxy(String proxyHost, int proxyPort) {\n System.setProperty(\"http.proxySet\", \"true\");\n System.setProperty(\"http.proxyHost\", proxyHost);\n System.setProperty(\"http.proxyPort\", \"\" + proxyPort);\n System.setProperty(\"https.proxyHost\", proxyHost);\n System.setProperty(\"https.proxyPort\", \"\" + proxyPort);\n }" ]
[ "public static clusterinstance[] get(nitro_service service) throws Exception{\n\t\tclusterinstance obj = new clusterinstance();\n\t\tclusterinstance[] response = (clusterinstance[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public static base_response add(nitro_service client, policydataset resource) throws Exception {\n\t\tpolicydataset addresource = new policydataset();\n\t\taddresource.name = resource.name;\n\t\taddresource.type = resource.type;\n\t\taddresource.indextype = resource.indextype;\n\t\treturn addresource.add_resource(client);\n\t}", "public double distanceToPlane(Point3d p) {\n return normal.x * p.x + normal.y * p.y + normal.z * p.z - planeOffset;\n }", "public final PJsonObject optJSONObject(final String key) {\n final JSONObject val = this.obj.optJSONObject(key);\n return val != null ? new PJsonObject(this, val, key) : null;\n }", "public Swagger read(Class<?> cls) {\n SwaggerDefinition swaggerDefinition = cls.getAnnotation(SwaggerDefinition.class);\n if (swaggerDefinition != null) {\n readSwaggerConfig(cls, swaggerDefinition);\n }\n\n return read(cls, \"\", null, false, new String[0], new String[0], new LinkedHashMap<>(), new ArrayList<>(), new HashSet<>());\n }", "public IPv4Address getEmbeddedIPv4Address(int byteIndex) {\n\t\tif(byteIndex == IPv6Address.MIXED_ORIGINAL_SEGMENT_COUNT * IPv6Address.BYTES_PER_SEGMENT) {\n\t\t\treturn getEmbeddedIPv4Address();\n\t\t}\n\t\tIPv4AddressCreator creator = getIPv4Network().getAddressCreator();\n\t\treturn creator.createAddress(getSection().getEmbeddedIPv4AddressSection(byteIndex, byteIndex + IPv4Address.BYTE_COUNT)); /* address creation */\n\t}", "private Map<String, Object> getMapFromJSON(String json) {\n Map<String, Object> propMap = new HashMap<String, Object>();\n ObjectMapper mapper = new ObjectMapper();\n\n // Initialize string if empty\n if (json == null || json.length() == 0) {\n json = \"{}\";\n }\n\n try {\n // Convert string\n propMap = mapper.readValue(json, new TypeReference<HashMap<String, Object>>(){});\n } catch (Exception e) {\n ;\n }\n return propMap;\n }", "public com.groupon.odo.proxylib.models.Method getMethodForOverrideId(int overrideId) {\n com.groupon.odo.proxylib.models.Method method = null;\n\n // special case for IDs < 0\n if (overrideId < 0) {\n method = new com.groupon.odo.proxylib.models.Method();\n method.setId(overrideId);\n\n if (method.getId() == Constants.PLUGIN_RESPONSE_OVERRIDE_CUSTOM ||\n method.getId() == Constants.PLUGIN_RESPONSE_HEADER_OVERRIDE_ADD ||\n method.getId() == Constants.PLUGIN_RESPONSE_HEADER_OVERRIDE_REMOVE) {\n method.setMethodType(Constants.PLUGIN_TYPE_RESPONSE_OVERRIDE);\n } else {\n method.setMethodType(Constants.PLUGIN_TYPE_REQUEST_OVERRIDE);\n }\n } else {\n // get method information from the database\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_OVERRIDE +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n queryStatement.setInt(1, overrideId);\n results = queryStatement.executeQuery();\n\n if (results.next()) {\n method = new com.groupon.odo.proxylib.models.Method();\n method.setClassName(results.getString(Constants.OVERRIDE_CLASS_NAME));\n method.setMethodName(results.getString(Constants.OVERRIDE_METHOD_NAME));\n }\n } catch (SQLException e) {\n e.printStackTrace();\n return null;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n // if method is still null then just return\n if (method == null) {\n return method;\n }\n\n // now get the rest of the data from the plugin manager\n // this gets all of the actual method data\n try {\n method = PluginManager.getInstance().getMethod(method.getClassName(), method.getMethodName());\n method.setId(overrideId);\n } catch (Exception e) {\n // there was some problem.. return null\n return null;\n }\n }\n\n return method;\n }", "private static ModelNode createOperation(ServerIdentity identity) {\n // The server address\n final ModelNode address = new ModelNode();\n address.add(ModelDescriptionConstants.HOST, identity.getHostName());\n address.add(ModelDescriptionConstants.RUNNING_SERVER, identity.getServerName());\n //\n final ModelNode operation = OPERATION.clone();\n operation.get(ModelDescriptionConstants.OP_ADDR).set(address);\n return operation;\n }" ]
Draws the specified image with the first rectangle's bounds, clipping with the second one and adding transparency. @param img image @param rect rectangle @param clipRect clipping bounds
[ "public void drawImage(Image img, Rectangle rect, Rectangle clipRect) {\n\t\tdrawImage(img, rect, clipRect, 1);\n\t}" ]
[ "public void setWeekOfMonth(String weekOfMonthStr) {\n\n final WeekOfMonth weekOfMonth = WeekOfMonth.valueOf(weekOfMonthStr);\n if ((null == m_model.getWeekOfMonth()) || !m_model.getWeekOfMonth().equals(weekOfMonth)) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setWeekOfMonth(weekOfMonth);\n onValueChange();\n }\n });\n }\n\n }", "public static Artifact withVersion(Version v)\n {\n Artifact artifact = new Artifact();\n artifact.version = v;\n return artifact;\n }", "public static <K,V> SortedMap<K,V> asImmutable(SortedMap<K, ? extends V> self) {\n return Collections.unmodifiableSortedMap(self);\n }", "private boolean isZonesSatisfied() {\n boolean zonesSatisfied = false;\n if(pipelineData.getZonesRequired() == null) {\n zonesSatisfied = true;\n } else {\n int numZonesSatisfied = pipelineData.getZoneResponses().size();\n if(numZonesSatisfied >= (pipelineData.getZonesRequired() + 1)) {\n zonesSatisfied = true;\n }\n }\n return zonesSatisfied;\n }", "static byte[] hmacSha1(StringBuilder message, String key) {\n try {\n Mac mac = Mac.getInstance(\"HmacSHA1\");\n mac.init(new SecretKeySpec(key.getBytes(), \"HmacSHA1\"));\n return mac.doFinal(message.toString().getBytes());\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }", "private Object getParameter(String name, String value) throws ParseException, NumberFormatException {\n\t\tObject result = null;\n\t\tif (name.length() > 0) {\n\n\t\t\tswitch (name.charAt(0)) {\n\t\t\t\tcase 'i':\n\t\t\t\t\tif (null == value || value.length() == 0) {\n\t\t\t\t\t\tvalue = \"0\";\n\t\t\t\t\t}\n\t\t\t\t\tresult = new Integer(value);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'f':\n\t\t\t\t\tif (name.startsWith(\"form\")) {\n\t\t\t\t\t\tresult = value;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (null == value || value.length() == 0) {\n\t\t\t\t\t\t\tvalue = \"0.0\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tresult = new Double(value);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'd':\n\t\t\t\t\tif (null == value || value.length() == 0) {\n\t\t\t\t\t\tresult = null;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tSimpleDateFormat dateParser = new SimpleDateFormat(\"yyyy-MM-dd\");\n\t\t\t\t\t\tresult = dateParser.parse(value);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 't':\n\t\t\t\t\tif (null == value || value.length() == 0) {\n\t\t\t\t\t\tresult = null;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tSimpleDateFormat timeParser = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n\t\t\t\t\t\tresult = timeParser.parse(value);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'b':\n\t\t\t\t\tresult = \"true\".equalsIgnoreCase(value) ? Boolean.TRUE : Boolean.FALSE;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tresult = value;\n\t\t\t}\n\t\t\tif (log.isDebugEnabled()) {\n\t\t\t\tif (result != null) {\n\t\t\t\t\tlog.debug(\n\t\t\t\t\t\t\t\"parameter \" + name + \" value \" + result + \" class \" + result.getClass().getName());\n\t\t\t\t} else {\n\t\t\t\t\tlog.debug(\"parameter\" + name + \"is null\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}", "@Api\n\tpublic void setNamedRoles(Map<String, List<NamedRoleInfo>> namedRoles) {\n\t\tthis.namedRoles = namedRoles;\n\t\tldapRoleMapping = new HashMap<String, Set<String>>();\n\t\tfor (String roleName : namedRoles.keySet()) {\n\t\t\tif (!ldapRoleMapping.containsKey(roleName)) {\n\t\t\t\tldapRoleMapping.put(roleName, new HashSet<String>());\n\t\t\t}\n\t\t\tfor (NamedRoleInfo role : namedRoles.get(roleName)) {\n\t\t\t\tldapRoleMapping.get(roleName).add(role.getName());\n\t\t\t}\n\t\t}\n\t}", "private void addCheckBox(Date date, boolean checkState) {\n\n CmsCheckBox cb = generateCheckBox(date, checkState);\n m_checkBoxes.add(cb);\n reInitLayoutElements();\n\n }", "private double getConstraint(double x1, double x2)\n {\n double c1,c2,h;\n c1 = -x1*x1-x2*x2+1+0.1*Math.cos(16*Math.atan(x1/x2));\n c2 = (x1-0.5)*(x1-0.5)+(x2-0.5)*(x2-0.5)-0.5;\n if(c1>c2)\n h = (c1>0)?c1:0;\n else\n h = (c2>0)?c2:0;\n return h;\n }" ]
set the layout which will host the ScrimInsetsFrameLayout and its layoutParams @param container @param layoutParams @return
[ "public MaterializeBuilder withContainer(ViewGroup container, ViewGroup.LayoutParams layoutParams) {\n this.mContainer = container;\n this.mContainerLayoutParams = layoutParams;\n return this;\n }" ]
[ "public static CredentialsConfig getPreferredDeployer(DeployerOverrider deployerOverrider, ArtifactoryServer server) {\n if (deployerOverrider.isOverridingDefaultDeployer()) {\n CredentialsConfig deployerCredentialsConfig = deployerOverrider.getDeployerCredentialsConfig();\n if (deployerCredentialsConfig != null) {\n return deployerCredentialsConfig;\n }\n }\n\n if (server != null) {\n CredentialsConfig deployerCredentials = server.getDeployerCredentialsConfig();\n if (deployerCredentials != null) {\n return deployerCredentials;\n }\n }\n\n return CredentialsConfig.EMPTY_CREDENTIALS_CONFIG;\n }", "public void setDefault() {\n try {\n TelephonyManager telephonyManager = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);\n String phone = telephonyManager.getLine1Number();\n if (phone != null && !phone.isEmpty()) {\n this.setNumber(phone);\n } else {\n String iso = telephonyManager.getNetworkCountryIso();\n setEmptyDefault(iso);\n }\n } catch (SecurityException e) {\n setEmptyDefault();\n }\n }", "@Deprecated\r\n public Category browse(String catId) throws FlickrException {\r\n List<Subcategory> subcategories = new ArrayList<Subcategory>();\r\n List<Group> groups = new ArrayList<Group>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_BROWSE);\r\n\r\n if (catId != null) {\r\n parameters.put(\"cat_id\", catId);\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element categoryElement = response.getPayload();\r\n\r\n Category category = new Category();\r\n category.setName(categoryElement.getAttribute(\"name\"));\r\n category.setPath(categoryElement.getAttribute(\"path\"));\r\n category.setPathIds(categoryElement.getAttribute(\"pathids\"));\r\n\r\n NodeList subcatNodes = categoryElement.getElementsByTagName(\"subcat\");\r\n for (int i = 0; i < subcatNodes.getLength(); i++) {\r\n Element node = (Element) subcatNodes.item(i);\r\n Subcategory subcategory = new Subcategory();\r\n subcategory.setId(Integer.parseInt(node.getAttribute(\"id\")));\r\n subcategory.setName(node.getAttribute(\"name\"));\r\n subcategory.setCount(Integer.parseInt(node.getAttribute(\"count\")));\r\n\r\n subcategories.add(subcategory);\r\n }\r\n\r\n NodeList groupNodes = categoryElement.getElementsByTagName(\"group\");\r\n for (int i = 0; i < groupNodes.getLength(); i++) {\r\n Element node = (Element) groupNodes.item(i);\r\n Group group = new Group();\r\n group.setId(node.getAttribute(\"nsid\"));\r\n group.setName(node.getAttribute(\"name\"));\r\n group.setMembers(node.getAttribute(\"members\"));\r\n\r\n groups.add(group);\r\n }\r\n\r\n category.setGroups(groups);\r\n category.setSubcategories(subcategories);\r\n\r\n return category;\r\n }", "protected List<TransformationDescription> buildChildren() {\n if(children.isEmpty()) {\n return Collections.emptyList();\n }\n final List<TransformationDescription> children = new ArrayList<TransformationDescription>();\n for(final TransformationDescriptionBuilder builder : this.children) {\n children.add(builder.build());\n }\n return children;\n }", "private void adjustOptionsColumn(\n CmsMessageBundleEditorTypes.EditMode oldMode,\n CmsMessageBundleEditorTypes.EditMode newMode) {\n\n if (m_model.isShowOptionsColumn(oldMode) != m_model.isShowOptionsColumn(newMode)) {\n m_table.removeGeneratedColumn(TableProperty.OPTIONS);\n if (m_model.isShowOptionsColumn(newMode)) {\n // Don't know why exactly setting the filter field invisible is necessary here,\n // it should be already set invisible - but apparently not setting it invisible again\n // will result in the field being visible.\n m_table.setFilterFieldVisible(TableProperty.OPTIONS, false);\n m_table.addGeneratedColumn(TableProperty.OPTIONS, m_optionsColumn);\n }\n }\n }", "private void readPredecessors(net.sf.mpxj.planner.schema.Task plannerTask)\n {\n Task mpxjTask = m_projectFile.getTaskByUniqueID(getInteger(plannerTask.getId()));\n\n Predecessors predecessors = plannerTask.getPredecessors();\n if (predecessors != null)\n {\n List<Predecessor> predecessorList = predecessors.getPredecessor();\n for (Predecessor predecessor : predecessorList)\n {\n Integer predecessorID = getInteger(predecessor.getPredecessorId());\n Task predecessorTask = m_projectFile.getTaskByUniqueID(predecessorID);\n if (predecessorTask != null)\n {\n Duration lag = getDuration(predecessor.getLag());\n if (lag == null)\n {\n lag = Duration.getInstance(0, TimeUnit.HOURS);\n }\n Relation relation = mpxjTask.addPredecessor(predecessorTask, RELATIONSHIP_TYPES.get(predecessor.getType()), lag);\n m_eventManager.fireRelationReadEvent(relation);\n }\n }\n }\n\n //\n // Process child tasks\n //\n List<net.sf.mpxj.planner.schema.Task> childTasks = plannerTask.getTask();\n for (net.sf.mpxj.planner.schema.Task childTask : childTasks)\n {\n readPredecessors(childTask);\n }\n }", "@SuppressWarnings(\"unchecked\")\n private void addPrivateFieldsAccessors(ClassNode node) {\n Set<ASTNode> accessedFields = (Set<ASTNode>) node.getNodeMetaData(StaticTypesMarker.PV_FIELDS_ACCESS);\n if (accessedFields==null) return;\n Map<String, MethodNode> privateConstantAccessors = (Map<String, MethodNode>) node.getNodeMetaData(PRIVATE_FIELDS_ACCESSORS);\n if (privateConstantAccessors!=null) {\n // already added\n return;\n }\n int acc = -1;\n privateConstantAccessors = new HashMap<String, MethodNode>();\n final int access = Opcodes.ACC_STATIC | Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC;\n for (FieldNode fieldNode : node.getFields()) {\n if (accessedFields.contains(fieldNode)) {\n\n acc++;\n Parameter param = new Parameter(node.getPlainNodeReference(), \"$that\");\n Expression receiver = fieldNode.isStatic()?new ClassExpression(node):new VariableExpression(param);\n Statement stmt = new ExpressionStatement(new PropertyExpression(\n receiver,\n fieldNode.getName()\n ));\n MethodNode accessor = node.addMethod(\"pfaccess$\"+acc, access, fieldNode.getOriginType(), new Parameter[]{param}, ClassNode.EMPTY_ARRAY, stmt);\n privateConstantAccessors.put(fieldNode.getName(), accessor);\n }\n }\n node.setNodeMetaData(PRIVATE_FIELDS_ACCESSORS, privateConstantAccessors);\n }", "protected CmsProject createAndSetModuleImportProject(CmsObject cms, CmsModule module) throws CmsException {\n\n CmsProject importProject = cms.createProject(\n org.opencms.module.Messages.get().getBundle(cms.getRequestContext().getLocale()).key(\n org.opencms.module.Messages.GUI_IMPORT_MODULE_PROJECT_NAME_1,\n new Object[] {module.getName()}),\n org.opencms.module.Messages.get().getBundle(cms.getRequestContext().getLocale()).key(\n org.opencms.module.Messages.GUI_IMPORT_MODULE_PROJECT_DESC_1,\n new Object[] {module.getName()}),\n OpenCms.getDefaultUsers().getGroupAdministrators(),\n OpenCms.getDefaultUsers().getGroupAdministrators(),\n CmsProject.PROJECT_TYPE_TEMPORARY);\n cms.getRequestContext().setCurrentProject(importProject);\n cms.copyResourceToProject(\"/\");\n return importProject;\n }", "public void pause(ServerActivityCallback requestCountListener) {\n if (paused) {\n throw ServerLogger.ROOT_LOGGER.serverAlreadyPaused();\n }\n this.paused = true;\n listenerUpdater.set(this, requestCountListener);\n if (activeRequestCountUpdater.get(this) == 0) {\n if (listenerUpdater.compareAndSet(this, requestCountListener, null)) {\n requestCountListener.done();\n }\n }\n }" ]
Set a Background Drawable using the appropriate Android version api call @param view @param drawable
[ "public static void setBackgroundDrawable(View view, Drawable drawable) {\n if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {\n view.setBackgroundDrawable(drawable);\n } else {\n view.setBackground(drawable);\n }\n }" ]
[ "public List<Map<String, String>> produceNWise(int nWise, String[] coVariables, Map<String, String[]> variableDomains) {\r\n List<Set<String>> tuples = makeNWiseTuples(coVariables, nWise);\n\r\n List<Map<String, String>> testCases = new ArrayList<>();\r\n for (Set<String> tuple : tuples) {\r\n testCases.addAll(expandTupleIntoTestCases(tuple, variableDomains));\r\n }\n\r\n return testCases;\r\n }", "public Swagger read(Set<Class<?>> classes) {\n Set<Class<?>> sortedClasses = new TreeSet<>((class1, class2) -> {\n if (class1.equals(class2)) {\n return 0;\n } else if (class1.isAssignableFrom(class2)) {\n return -1;\n } else if (class2.isAssignableFrom(class1)) {\n return 1;\n }\n return class1.getName().compareTo(class2.getName());\n });\n sortedClasses.addAll(classes);\n\n Map<Class<?>, ReaderListener> listeners = new HashMap<Class<?>, ReaderListener>();\n\n for (Class<?> cls : sortedClasses) {\n if (ReaderListener.class.isAssignableFrom(cls) && !listeners.containsKey(cls)) {\n try {\n listeners.put(cls, (ReaderListener) cls.newInstance());\n } catch (Exception e) {\n LOGGER.error(\"Failed to create ReaderListener\", e);\n }\n }\n }\n\n// for (ReaderListener listener : listeners.values()) {\n// try {\n// listener.beforeScan(this, swagger);\n// } catch (Exception e) {\n// LOGGER.error(\"Unexpected error invoking beforeScan listener [\" + listener.getClass().getName() + \"]\", e);\n// }\n// }\n\n // process SwaggerDefinitions first - so we get tags in desired order\n for (Class<?> cls : sortedClasses) {\n SwaggerDefinition swaggerDefinition = cls.getAnnotation(SwaggerDefinition.class);\n if (swaggerDefinition != null) {\n readSwaggerConfig(cls, swaggerDefinition);\n }\n }\n\n for (Class<?> cls : sortedClasses) {\n read(cls, \"\", null, false, new String[0], new String[0], new LinkedHashMap<>(), new ArrayList<>(), new HashSet<>());\n }\n\n// for (ReaderListener listener : listeners.values()) {\n// try {\n// listener.afterScan(this, swagger);\n// } catch (Exception e) {\n// LOGGER.error(\"Unexpected error invoking afterScan listener [\" + listener.getClass().getName() + \"]\", e);\n// }\n// }\n\n return swagger;\n }", "protected T createInstance() {\n try {\n Constructor<T> ctor = clazz.getDeclaredConstructor();\n ctor.setAccessible(true);\n return ctor.newInstance();\n } catch (InstantiationException e) {\n throw new RuntimeException(e);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n } catch (SecurityException e) {\n throw new RuntimeException(e);\n } catch (NoSuchMethodException e) {\n throw new RuntimeException(e);\n } catch (IllegalArgumentException e) {\n throw new RuntimeException(e);\n } catch (InvocationTargetException e) {\n throw new RuntimeException(e);\n }\n }", "private boolean isDescriptorProperty(Object property) {\n\n return (getBundleType().equals(BundleType.DESCRIPTOR)\n || (hasDescriptor()\n && (property.equals(TableProperty.KEY)\n || property.equals(TableProperty.DEFAULT)\n || property.equals(TableProperty.DESCRIPTION))));\n }", "public Where<T, ID> isNull(String columnName) throws SQLException {\n\t\taddClause(new IsNull(columnName, findColumnFieldType(columnName)));\n\t\treturn this;\n\t}", "protected static <S extends IPAddressSegment> void normalizePrefixBoundary(\n\t\t\tint sectionPrefixBits,\n\t\t\tS segments[],\n\t\t\tint segmentBitCount,\n\t\t\tint segmentByteCount,\n\t\t\tBiFunction<S, Integer, S> segProducer) {\n\t\t//we've already verified segment prefixes in super constructor. We simply need to check the case where the prefix is at a segment boundary,\n\t\t//whether the network side has the correct prefix\n\t\tint networkSegmentIndex = getNetworkSegmentIndex(sectionPrefixBits, segmentByteCount, segmentBitCount);\n\t\tif(networkSegmentIndex >= 0) {\n\t\t\tS segment = segments[networkSegmentIndex];\n\t\t\tif(!segment.isPrefixed()) {\n\t\t\t\tsegments[networkSegmentIndex] = segProducer.apply(segment, segmentBitCount);\n\t\t\t}\n\t\t}\n\t}", "public List<ServerGroup> tableServerGroups(int profileId) {\n ArrayList<ServerGroup> serverGroups = 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_SERVER_GROUPS +\n \" WHERE \" + Constants.GENERIC_PROFILE_ID + \" = ? \" +\n \"ORDER BY \" + Constants.GENERIC_NAME\n );\n queryStatement.setInt(1, profileId);\n results = queryStatement.executeQuery();\n while (results.next()) {\n ServerGroup curServerGroup = new ServerGroup(results.getInt(Constants.GENERIC_ID),\n results.getString(Constants.GENERIC_NAME),\n results.getInt(Constants.GENERIC_PROFILE_ID));\n curServerGroup.setServers(tableServers(profileId, curServerGroup.getId()));\n serverGroups.add(curServerGroup);\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n return serverGroups;\n }", "@Modified(id = \"importerServices\")\n void modifiedImporterService(ServiceReference<ImporterService> serviceReference) {\n try {\n importersManager.modified(serviceReference);\n } catch (InvalidFilterException invalidFilterException) {\n LOG.error(\"The ServiceProperty \\\"\" + TARGET_FILTER_PROPERTY + \"\\\" of the ImporterService \"\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 importersManager.removeLinks(serviceReference);\n return;\n }\n if (importersManager.matched(serviceReference)) {\n importersManager.updateLinks(serviceReference);\n } else {\n importersManager.removeLinks(serviceReference);\n }\n }", "private String getTypeString(Class<?> c)\n {\n String result = TYPE_MAP.get(c);\n if (result == null)\n {\n result = c.getName();\n if (!result.endsWith(\";\") && !result.startsWith(\"[\"))\n {\n result = \"L\" + result + \";\";\n }\n }\n return result;\n }" ]
Detect what has changed in the store definition and rewire BDB environments accordingly. @param storeDef updated store definition
[ "public void update(StoreDefinition storeDef) {\n if(!useOneEnvPerStore)\n throw new VoldemortException(\"Memory foot print can be set only when using different environments per store\");\n\n String storeName = storeDef.getName();\n Environment environment = environments.get(storeName);\n // change reservation amount of reserved store\n if(!unreservedStores.contains(environment) && storeDef.hasMemoryFootprint()) {\n EnvironmentMutableConfig mConfig = environment.getMutableConfig();\n long currentCacheSize = mConfig.getCacheSize();\n long newCacheSize = storeDef.getMemoryFootprintMB() * ByteUtils.BYTES_PER_MB;\n if(currentCacheSize != newCacheSize) {\n long newReservedCacheSize = this.reservedCacheSize - currentCacheSize\n + newCacheSize;\n\n // check that we leave a 'minimum' shared cache\n if((voldemortConfig.getBdbCacheSize() - newReservedCacheSize) < voldemortConfig.getBdbMinimumSharedCache()) {\n throw new StorageInitializationException(\"Reservation of \"\n + storeDef.getMemoryFootprintMB()\n + \" MB for store \"\n + storeName\n + \" violates minimum shared cache size of \"\n + voldemortConfig.getBdbMinimumSharedCache());\n }\n\n this.reservedCacheSize = newReservedCacheSize;\n adjustCacheSizes();\n mConfig.setCacheSize(newCacheSize);\n environment.setMutableConfig(mConfig);\n logger.info(\"Setting private cache for store \" + storeDef.getName() + \" to \"\n + newCacheSize);\n }\n } else {\n // we cannot support changing a reserved store to unreserved or vice\n // versa since the sharedCache param is not mutable\n throw new VoldemortException(\"Cannot switch between shared and private cache dynamically\");\n }\n }" ]
[ "public static boolean decomposeSafe(DecompositionInterface<ZMatrixRMaj> decomposition, ZMatrixRMaj a) {\n\n if( decomposition.inputModified() ) {\n a = a.copy();\n }\n return decomposition.decompose(a);\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 static void downloadUrl(String stringUrl, Map<String, String> parameters, File fileToSave)\n throws IOException {\n URL url = new URL(stringUrl);\n HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n conn.setFollowRedirects(true);\n \n if (parameters != null) {\n for (Entry<String, String> entry : parameters.entrySet()) {\n conn.addRequestProperty(entry.getKey(), entry.getValue());\n }\n }\n\n\n boolean redirect = false;\n\n // normally, 3xx is redirect\n int status = conn.getResponseCode();\n if (status != HttpURLConnection.HTTP_OK) {\n if (status == HttpURLConnection.HTTP_MOVED_TEMP\n || status == HttpURLConnection.HTTP_MOVED_PERM\n || status == HttpURLConnection.HTTP_SEE_OTHER)\n redirect = true;\n }\n\n if (redirect) {\n\n // get redirect url from \"location\" header field\n String newUrl = conn.getHeaderField(\"Location\");\n\n // get the cookie if need, for login\n String cookies = conn.getHeaderField(\"Set-Cookie\");\n\n // open the new connnection again\n conn = (HttpURLConnection) new URL(newUrl).openConnection();\n conn.setRequestProperty(\"Cookie\", cookies);\n\n }\n \n byte[] data = MyStreamUtils.readContentBytes(conn.getInputStream());\n FileOutputStream fos = new FileOutputStream(fileToSave);\n fos.write(data);\n fos.close();\n }", "public static void addService(final ServiceTarget serviceTarget, final Bootstrap.Configuration configuration,\n final ControlledProcessState processState, final BootstrapListener bootstrapListener,\n final RunningModeControl runningModeControl, final AbstractVaultReader vaultReader, final ManagedAuditLogger auditLogger,\n final DelegatingConfigurableAuthorizer authorizer, final ManagementSecurityIdentitySupplier securityIdentitySupplier,\n final SuspendController suspendController) {\n\n // Install Executor services\n final ThreadGroup threadGroup = new ThreadGroup(\"ServerService ThreadGroup\");\n final String namePattern = \"ServerService Thread Pool -- %t\";\n final ThreadFactory threadFactory = doPrivileged(new PrivilegedAction<ThreadFactory>() {\n public ThreadFactory run() {\n return new JBossThreadFactory(threadGroup, Boolean.FALSE, null, namePattern, null, null);\n }\n });\n\n // TODO determine why QueuelessThreadPoolService makes boot take > 35 secs\n// final QueuelessThreadPoolService serverExecutorService = new QueuelessThreadPoolService(Integer.MAX_VALUE, false, new TimeSpec(TimeUnit.SECONDS, 5));\n// serverExecutorService.getThreadFactoryInjector().inject(threadFactory);\n final boolean forDomain = ProcessType.DOMAIN_SERVER == getProcessType(configuration.getServerEnvironment());\n final ServerExecutorService serverExecutorService = new ServerExecutorService(threadFactory, forDomain);\n serviceTarget.addService(MANAGEMENT_EXECUTOR, serverExecutorService)\n .addAliases(Services.JBOSS_SERVER_EXECUTOR, ManagementRemotingServices.SHUTDOWN_EXECUTOR_NAME) // Use this executor for mgmt shutdown for now\n .install();\n final ServerScheduledExecutorService serverScheduledExecutorService = new ServerScheduledExecutorService(threadFactory);\n serviceTarget.addService(JBOSS_SERVER_SCHEDULED_EXECUTOR, serverScheduledExecutorService)\n .addAliases(JBOSS_SERVER_SCHEDULED_EXECUTOR)\n .addDependency(MANAGEMENT_EXECUTOR, ExecutorService.class, serverScheduledExecutorService.executorInjector)\n .install();\n\n final CapabilityRegistry capabilityRegistry = configuration.getCapabilityRegistry();\n ServerService service = new ServerService(configuration, processState, null, bootstrapListener, new ServerDelegatingResourceDefinition(),\n runningModeControl, vaultReader, auditLogger, authorizer, securityIdentitySupplier, capabilityRegistry, suspendController);\n\n ExternalManagementRequestExecutor.install(serviceTarget, threadGroup, EXECUTOR_CAPABILITY.getCapabilityServiceName(), service.getStabilityMonitor());\n\n ServiceBuilder<?> serviceBuilder = serviceTarget.addService(Services.JBOSS_SERVER_CONTROLLER, service);\n serviceBuilder.addDependency(DeploymentMountProvider.SERVICE_NAME,DeploymentMountProvider.class, service.injectedDeploymentRepository);\n serviceBuilder.addDependency(ContentRepository.SERVICE_NAME, ContentRepository.class, service.injectedContentRepository);\n serviceBuilder.addDependency(Services.JBOSS_SERVICE_MODULE_LOADER, ServiceModuleLoader.class, service.injectedModuleLoader);\n serviceBuilder.addDependency(Services.JBOSS_EXTERNAL_MODULE_SERVICE, ExternalModuleService.class,\n service.injectedExternalModuleService);\n serviceBuilder.addDependency(PATH_MANAGER_CAPABILITY.getCapabilityServiceName(), PathManager.class, service.injectedPathManagerService);\n if (configuration.getServerEnvironment().isAllowModelControllerExecutor()) {\n serviceBuilder.addDependency(MANAGEMENT_EXECUTOR, ExecutorService.class, service.getExecutorServiceInjector());\n }\n if (configuration.getServerEnvironment().getLaunchType() == ServerEnvironment.LaunchType.DOMAIN) {\n serviceBuilder.addDependency(HostControllerConnectionService.SERVICE_NAME, ControllerInstabilityListener.class,\n service.getContainerInstabilityInjector());\n }\n\n serviceBuilder.install();\n }", "public static double volatilityConversionLognormalATMtoNormalATM(double forward, double displacement, double maturity, double lognormalVolatiltiy) {\n\t\tdouble x = lognormalVolatiltiy * Math.sqrt(maturity / 8);\n\t\tdouble y = org.apache.commons.math3.special.Erf.erf(x);\n\t\tdouble normalVol = Math.sqrt(2*Math.PI / maturity) * (forward+displacement) * y;\n\n\t\treturn normalVol;\n\t}", "public static String getTabularData(String[] labels, String[][] data, int padding) {\n int[] size = new int[labels.length];\n \n for (int i = 0; i < labels.length; i++) {\n size[i] = labels[i].length() + padding;\n }\n \n for (String[] row : data) {\n for (int i = 0; i < labels.length; i++) {\n if (row[i].length() >= size[i]) {\n size[i] = row[i].length() + padding;\n }\n }\n }\n \n StringBuffer tabularData = new StringBuffer();\n \n for (int i = 0; i < labels.length; i++) {\n tabularData.append(labels[i]);\n tabularData.append(fill(' ', size[i] - labels[i].length()));\n }\n \n tabularData.append(\"\\n\");\n \n for (int i = 0; i < labels.length; i++) {\n tabularData.append(fill('=', size[i] - 1)).append(\" \");\n }\n \n tabularData.append(\"\\n\");\n \n \n for (String[] row : data) {\n for (int i = 0; i < labels.length; i++) {\n tabularData.append(row[i]);\n tabularData.append(fill(' ', size[i] - row[i].length()));\n }\n \n tabularData.append(\"\\n\");\n }\n \n return tabularData.toString();\n }", "private void tagvalue(Options opt, Doc c) {\n\tTag tags[] = c.tags(\"tagvalue\");\n\tif (tags.length == 0)\n\t return;\n\t\n\tfor (Tag tag : tags) {\n\t String t[] = tokenize(tag.text());\n\t if (t.length != 2) {\n\t\tSystem.err.println(\"@tagvalue expects two fields: \" + tag.text());\n\t\tcontinue;\n\t }\n\t tableLine(Align.RIGHT, Font.TAG.wrap(opt, \"{\" + t[0] + \" = \" + t[1] + \"}\"));\n\t}\n }", "@SuppressWarnings(\"deprecation\")\n protected ModelNode executeReadOnlyOperation(final ModelNode operation, final OperationMessageHandler handler, final OperationTransactionControl control, final OperationStepHandler prepareStep, final int operationId) {\n final AbstractOperationContext delegateContext = getDelegateContext(operationId);\n CurrentOperationIdHolder.setCurrentOperationID(operationId);\n try {\n return executeReadOnlyOperation(operation, delegateContext.getManagementModel(), control, prepareStep, delegateContext);\n } finally {\n CurrentOperationIdHolder.setCurrentOperationID(null);\n }\n }", "private void handleDmrString(final ModelNode node, final String name, final String value) {\n final String realValue = value.substring(2);\n node.get(name).set(ModelNode.fromString(realValue));\n }" ]
Scans a path on the filesystem for resources inside the given classpath location. @param location The system-independent location on the classpath. @param locationUri The system-specific physical location URI. @return a sorted set containing all the resources inside the given location @throws IOException if an error accessing the filesystem happens
[ "public Set<String> findResourceNames(String location, URI locationUri) throws IOException {\n String filePath = toFilePath(locationUri);\n File folder = new File(filePath);\n if (!folder.isDirectory()) {\n LOGGER.debug(\"Skipping path as it is not a directory: \" + filePath);\n return new TreeSet<>();\n }\n\n String classPathRootOnDisk = filePath.substring(0, filePath.length() - location.length());\n if (!classPathRootOnDisk.endsWith(File.separator)) {\n classPathRootOnDisk = classPathRootOnDisk + File.separator;\n }\n LOGGER.debug(\"Scanning starting at classpath root in filesystem: \" + classPathRootOnDisk);\n return findResourceNamesFromFileSystem(classPathRootOnDisk, location, folder);\n }" ]
[ "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 base_response delete(nitro_service client, String servicename) throws Exception {\n\t\tgslbservice deleteresource = new gslbservice();\n\t\tdeleteresource.servicename = servicename;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public void setCloseConnectionWatchTimeout(long closeConnectionWatchTimeout, TimeUnit timeUnit) {\n\t\tthis.closeConnectionWatchTimeoutInMs = TimeUnit.MILLISECONDS.convert(closeConnectionWatchTimeout, timeUnit);\n\t}", "public static base_response update(nitro_service client, nsconfig resource) throws Exception {\n\t\tnsconfig updateresource = new nsconfig();\n\t\tupdateresource.ipaddress = resource.ipaddress;\n\t\tupdateresource.netmask = resource.netmask;\n\t\tupdateresource.nsvlan = resource.nsvlan;\n\t\tupdateresource.ifnum = resource.ifnum;\n\t\tupdateresource.tagged = resource.tagged;\n\t\tupdateresource.httpport = resource.httpport;\n\t\tupdateresource.maxconn = resource.maxconn;\n\t\tupdateresource.maxreq = resource.maxreq;\n\t\tupdateresource.cip = resource.cip;\n\t\tupdateresource.cipheader = resource.cipheader;\n\t\tupdateresource.cookieversion = resource.cookieversion;\n\t\tupdateresource.securecookie = resource.securecookie;\n\t\tupdateresource.pmtumin = resource.pmtumin;\n\t\tupdateresource.pmtutimeout = resource.pmtutimeout;\n\t\tupdateresource.ftpportrange = resource.ftpportrange;\n\t\tupdateresource.crportrange = resource.crportrange;\n\t\tupdateresource.timezone = resource.timezone;\n\t\tupdateresource.grantquotamaxclient = resource.grantquotamaxclient;\n\t\tupdateresource.exclusivequotamaxclient = resource.exclusivequotamaxclient;\n\t\tupdateresource.grantquotaspillover = resource.grantquotaspillover;\n\t\tupdateresource.exclusivequotaspillover = resource.exclusivequotaspillover;\n\t\tupdateresource.nwfwmode = resource.nwfwmode;\n\t\treturn updateresource.update_resource(client);\n\t}", "@UiThread\n public int getParentAdapterPosition() {\n int flatPosition = getAdapterPosition();\n if (flatPosition == RecyclerView.NO_POSITION) {\n return flatPosition;\n }\n\n return mExpandableAdapter.getNearestParentPosition(flatPosition);\n }", "public static base_response add(nitro_service client, responderpolicy resource) throws Exception {\n\t\tresponderpolicy addresource = new responderpolicy();\n\t\taddresource.name = resource.name;\n\t\taddresource.rule = resource.rule;\n\t\taddresource.action = resource.action;\n\t\taddresource.undefaction = resource.undefaction;\n\t\taddresource.comment = resource.comment;\n\t\taddresource.logaction = resource.logaction;\n\t\taddresource.appflowaction = resource.appflowaction;\n\t\treturn addresource.add_resource(client);\n\t}", "public AT_Row setPaddingTop(int paddingTop) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingTop(paddingTop);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "private void ensureNoTableInfoIfNoRepositoryInfo(ClassDescriptorDef classDef, String checkLevel)\r\n {\r\n if (!classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_REPOSITORY_INFO, true))\r\n {\r\n classDef.setProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, \"false\");\r\n }\r\n }", "private String findLoggingProfile(final ResourceRoot resourceRoot) {\n final Manifest manifest = resourceRoot.getAttachment(Attachments.MANIFEST);\n if (manifest != null) {\n final String loggingProfile = manifest.getMainAttributes().getValue(LOGGING_PROFILE);\n if (loggingProfile != null) {\n LoggingLogger.ROOT_LOGGER.debugf(\"Logging profile '%s' found in '%s'.\", loggingProfile, resourceRoot);\n return loggingProfile;\n }\n }\n return null;\n }" ]
Validates that we only have allowable filters. <p>Note that equality and ancestor filters are allowed, however they may result in inefficient sharding.
[ "private void validateFilter(Filter filter) throws IllegalArgumentException {\n switch (filter.getFilterTypeCase()) {\n case COMPOSITE_FILTER:\n for (Filter subFilter : filter.getCompositeFilter().getFiltersList()) {\n validateFilter(subFilter);\n }\n break;\n case PROPERTY_FILTER:\n if (UNSUPPORTED_OPERATORS.contains(filter.getPropertyFilter().getOp())) {\n throw new IllegalArgumentException(\"Query cannot have any inequality filters.\");\n }\n break;\n default:\n throw new IllegalArgumentException(\n \"Unsupported filter type: \" + filter.getFilterTypeCase());\n }\n }" ]
[ "public ApiClient setHttpClient(OkHttpClient newHttpClient) {\n if (!httpClient.equals(newHttpClient)) {\n newHttpClient.networkInterceptors().addAll(httpClient.networkInterceptors());\n httpClient.networkInterceptors().clear();\n newHttpClient.interceptors().addAll(httpClient.interceptors());\n httpClient.interceptors().clear();\n this.httpClient = newHttpClient;\n }\n return this;\n }", "public void registerCollectionSizeGauge(\n\t\t\tCollectionSizeGauge collectionSizeGauge) {\n\t\tString name = createMetricName(LocalTaskExecutorService.class,\n\t\t\t\t\"queue-size\");\n\t\tmetrics.register(name, collectionSizeGauge);\n\t}", "private List<Row> join(List<Row> leftRows, String leftColumn, String rightTable, List<Row> rightRows, String rightColumn)\n {\n List<Row> result = new LinkedList<Row>();\n\n RowComparator leftComparator = new RowComparator(new String[]\n {\n leftColumn\n });\n RowComparator rightComparator = new RowComparator(new String[]\n {\n rightColumn\n });\n Collections.sort(leftRows, leftComparator);\n Collections.sort(rightRows, rightComparator);\n\n ListIterator<Row> rightIterator = rightRows.listIterator();\n Row rightRow = rightIterator.hasNext() ? rightIterator.next() : null;\n\n for (Row leftRow : leftRows)\n {\n Integer leftValue = leftRow.getInteger(leftColumn);\n boolean match = false;\n\n while (rightRow != null)\n {\n Integer rightValue = rightRow.getInteger(rightColumn);\n int comparison = leftValue.compareTo(rightValue);\n if (comparison == 0)\n {\n match = true;\n break;\n }\n\n if (comparison < 0)\n {\n if (rightIterator.hasPrevious())\n {\n rightRow = rightIterator.previous();\n }\n break;\n }\n\n rightRow = rightIterator.next();\n }\n\n if (match && rightRow != null)\n {\n Map<String, Object> newMap = new HashMap<String, Object>(((MapRow) leftRow).getMap());\n\n for (Entry<String, Object> entry : ((MapRow) rightRow).getMap().entrySet())\n {\n String key = entry.getKey();\n if (newMap.containsKey(key))\n {\n key = rightTable + \".\" + key;\n }\n newMap.put(key, entry.getValue());\n }\n\n result.add(new MapRow(newMap));\n }\n }\n\n return result;\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 addAllWithFilter(Map<String, String> toMap, Map<String, String> fromMap, IncludeExcludePatterns pattern) {\n for (Object o : fromMap.entrySet()) {\n Map.Entry entry = (Map.Entry) o;\n String key = (String) entry.getKey();\n if (PatternMatcher.pathConflicts(key, pattern)) {\n continue;\n }\n toMap.put(key, (String) entry.getValue());\n }\n }", "private Duration assignmentDuration(Task task, Duration work)\n {\n Duration result = work;\n\n if (result != null)\n {\n if (result.getUnits() == TimeUnit.PERCENT)\n {\n Duration taskWork = task.getWork();\n if (taskWork != null)\n {\n result = Duration.getInstance(taskWork.getDuration() * result.getDuration(), taskWork.getUnits());\n }\n }\n }\n return result;\n }", "public final void notifyFooterItemChanged(int position) {\n if (position < 0 || position >= footerItemCount) {\n throw new IndexOutOfBoundsException(\"The given position \" + position\n + \" is not within the position bounds for footer items [0 - \"\n + (footerItemCount - 1) + \"].\");\n }\n notifyItemChanged(position + headerItemCount + contentItemCount);\n }", "private void readAssignments(Resource mpxjResource, net.sf.mpxj.phoenix.schema.Project.Storepoints.Storepoint.Resources.Resource res)\n {\n for (Assignment assignment : res.getAssignment())\n {\n readAssignment(mpxjResource, assignment);\n }\n }", "public void addStoreDefinition(StoreDefinition storeDef) {\n // acquire write lock\n writeLock.lock();\n\n try {\n // Check if store already exists\n if(this.storeNames.contains(storeDef.getName())) {\n throw new VoldemortException(\"Store already exists !\");\n }\n\n // Check for backwards compatibility\n StoreDefinitionUtils.validateSchemaAsNeeded(storeDef);\n\n // Otherwise add to the STORES directory\n StoreDefinitionsMapper mapper = new StoreDefinitionsMapper();\n String storeDefStr = mapper.writeStore(storeDef);\n Versioned<String> versionedValueStr = new Versioned<String>(storeDefStr);\n this.storeDefinitionsStorageEngine.put(storeDef.getName(), versionedValueStr, null);\n\n // Update the metadata cache\n this.metadataCache.put(storeDef.getName(), new Versioned<Object>(storeDefStr));\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\n updateRoutingStrategies(getCluster(), getStoreDefList());\n } finally {\n writeLock.unlock();\n }\n }" ]
If the status of a print job is not checked for a while, we assume that the user is no longer interested in the report, and we cancel the job. @param printJob @return is the abandoned timeout exceeded?
[ "private boolean isAbandoned(final SubmittedPrintJob printJob) {\n final long duration = ThreadPoolJobManager.this.jobQueue.timeSinceLastStatusCheck(\n printJob.getEntry().getReferenceId());\n final boolean abandoned =\n duration > TimeUnit.SECONDS.toMillis(ThreadPoolJobManager.this.abandonedTimeout);\n if (abandoned) {\n LOGGER.info(\"Job {} is abandoned (no status check within the last {} seconds)\",\n printJob.getEntry().getReferenceId(), ThreadPoolJobManager.this.abandonedTimeout);\n }\n return abandoned;\n }" ]
[ "public String[] getNormalizedLabels() {\n\t\tif(isValid()) {\n\t\t\treturn parsedHost.getNormalizedLabels();\n\t\t}\n\t\tif(host.length() == 0) {\n\t\t\treturn new String[0];\n\t\t}\n\t\treturn new String[] {host};\n\t}", "public void run(Configuration configuration, List<CandidateSteps> candidateSteps, Story story, MetaFilter filter)\n throws Throwable {\n run(configuration, candidateSteps, story, filter, null);\n }", "public void addPathToRequestResponseTable(int profileId, String clientUUID, int pathId) throws Exception {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection\n .prepareStatement(\"INSERT INTO \" + Constants.DB_TABLE_REQUEST_RESPONSE +\n \"(\" + Constants.REQUEST_RESPONSE_PATH_ID + \",\"\n + Constants.GENERIC_PROFILE_ID + \",\"\n + Constants.GENERIC_CLIENT_UUID + \",\"\n + Constants.REQUEST_RESPONSE_REPEAT_NUMBER + \",\"\n + Constants.REQUEST_RESPONSE_RESPONSE_ENABLED + \",\"\n + Constants.REQUEST_RESPONSE_REQUEST_ENABLED + \",\"\n + Constants.REQUEST_RESPONSE_CUSTOM_RESPONSE + \",\"\n + Constants.REQUEST_RESPONSE_CUSTOM_REQUEST + \")\"\n + \" VALUES (?, ?, ?, ?, ?, ?, ?, ?);\");\n statement.setInt(1, pathId);\n statement.setInt(2, profileId);\n statement.setString(3, clientUUID);\n statement.setInt(4, -1);\n statement.setInt(5, 0);\n statement.setInt(6, 0);\n statement.setString(7, \"\");\n statement.setString(8, \"\");\n statement.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "public static boolean isStandaloneRunning(final ModelControllerClient client) {\n try {\n final ModelNode response = client.execute(Operations.createReadAttributeOperation(EMPTY_ADDRESS, \"server-state\"));\n if (Operations.isSuccessfulOutcome(response)) {\n final String state = Operations.readResult(response).asString();\n return !CONTROLLER_PROCESS_STATE_STARTING.equals(state)\n && !CONTROLLER_PROCESS_STATE_STOPPING.equals(state);\n }\n } catch (RuntimeException | IOException e) {\n LOGGER.trace(\"Interrupted determining if standalone is running\", e);\n }\n return false;\n }", "public BoxCollaborationWhitelistExemptTarget.Info getInfo() {\n URL url = COLLABORATION_WHITELIST_EXEMPT_TARGET_ENTRY_URL_TEMPLATE.build(this.getAPI().getBaseURL(),\n this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, HttpMethod.GET);\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n\n return new Info(JsonObject.readFrom(response.getJSON()));\n }", "public void deleteOrganization(final String organizationId) {\n final DbOrganization dbOrganization = getOrganization(organizationId);\n repositoryHandler.deleteOrganization(dbOrganization.getName());\n repositoryHandler.removeModulesOrganization(dbOrganization);\n }", "public Object getRealSubject() throws PersistenceBrokerException\r\n\t{\r\n\t\tif (_realSubject == null)\r\n\t\t{\r\n\t\t\tbeforeMaterialization();\r\n\t\t\t_realSubject = materializeSubject();\r\n\t\t\tafterMaterialization();\r\n\t\t}\r\n\t\treturn _realSubject;\r\n\t}", "public void loadObject(Object object, Set<String> excludedMethods)\n {\n m_model.setTableModel(createTableModel(object, excludedMethods));\n }", "public static List<DockerImage> getAndDiscardImagesByBuildId(int buildInfoId) {\n List<DockerImage> list = new ArrayList<DockerImage>();\n synchronized(images) {\n Iterator<DockerImage> it = images.iterator();\n while (it.hasNext()) {\n DockerImage image = it.next();\n if (image.getBuildInfoId() == buildInfoId) {\n if (image.hasManifest()) {\n list.add(image);\n }\n it.remove();\n } else // Remove old images from the cache, for which build-info hasn't been published to Artifactory:\n if (image.isExpired()) {\n it.remove();\n }\n }\n }\n return list;\n }" ]
Gets an exception reporting an unexpected XML element. @param reader a reference to the stream reader. @return the constructed {@link javax.xml.stream.XMLStreamException}.
[ "private static XMLStreamException unexpectedElement(final XMLStreamReader reader) {\n return SecurityManagerLogger.ROOT_LOGGER.unexpectedElement(reader.getName(), reader.getLocation());\n }" ]
[ "public void update(int width, int height, float[] data)\n throws IllegalArgumentException\n {\n if ((width <= 0) || (height <= 0) ||\n (data == null) || (data.length < height * width * mFloatsPerPixel))\n {\n throw new IllegalArgumentException();\n }\n NativeFloatImage.update(getNative(), width, height, 0, data);\n }", "@Override\n public void close(SocketDestination destination) {\n factory.setLastClosedTimestamp(destination);\n queuedPool.reset(destination);\n }", "void sign(byte[] data, int offset, int length,\n ServerMessageBlock request, ServerMessageBlock response) {\n request.signSeq = signSequence;\n if( response != null ) {\n response.signSeq = signSequence + 1;\n response.verifyFailed = false;\n }\n\n try {\n update(macSigningKey, 0, macSigningKey.length);\n int index = offset + ServerMessageBlock.SIGNATURE_OFFSET;\n for (int i = 0; i < 8; i++) data[index + i] = 0;\n ServerMessageBlock.writeInt4(signSequence, data, index);\n update(data, offset, length);\n System.arraycopy(digest(), 0, data, index, 8);\n if (bypass) {\n bypass = false;\n System.arraycopy(\"BSRSPYL \".getBytes(), 0, data, index, 8);\n }\n } catch (Exception ex) {\n if( log.level > 0 )\n ex.printStackTrace( log );\n } finally {\n signSequence += 2;\n }\n }", "private void srand(int ijkl) {\n u = new double[97];\n\n int ij = ijkl / 30082;\n int kl = ijkl % 30082;\n\n // Handle the seed range errors\n // First random number seed must be between 0 and 31328\n // Second seed must have a value between 0 and 30081\n if (ij < 0 || ij > 31328 || kl < 0 || kl > 30081) {\n ij = ij % 31329;\n kl = kl % 30082;\n }\n\n int i = ((ij / 177) % 177) + 2;\n int j = (ij % 177) + 2;\n int k = ((kl / 169) % 178) + 1;\n int l = kl % 169;\n\n int m;\n double s, t;\n for (int ii = 0; ii < 97; ii++) {\n s = 0.0;\n t = 0.5;\n for (int jj = 0; jj < 24; jj++) {\n m = (((i * j) % 179) * k) % 179;\n i = j;\n j = k;\n k = m;\n l = (53 * l + 1) % 169;\n if (((l * m) % 64) >= 32) {\n s += t;\n }\n t *= 0.5;\n }\n u[ii] = s;\n }\n\n c = 362436.0 / 16777216.0;\n cd = 7654321.0 / 16777216.0;\n cm = 16777213.0 / 16777216.0;\n i97 = 96;\n j97 = 32;\n }", "public static appfwprofile_csrftag_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_csrftag_binding obj = new appfwprofile_csrftag_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_csrftag_binding response[] = (appfwprofile_csrftag_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public double getValueAsPrice(double evaluationTime, AnalyticModel model) {\n\t\tForwardCurve\tforwardCurve\t= model.getForwardCurve(forwardCurveName);\n\t\tDiscountCurve\tdiscountCurve\t= model.getDiscountCurve(discountCurveName);\n\n\t\tDiscountCurve\tdiscountCurveForForward = null;\n\t\tif(forwardCurve == null && forwardCurveName != null && forwardCurveName.length() > 0) {\n\t\t\t// User might like to get forward from discount curve.\n\t\t\tdiscountCurveForForward\t= model.getDiscountCurve(forwardCurveName);\n\n\t\t\tif(discountCurveForForward == null) {\n\t\t\t\t// User specified a name for the forward curve, but no curve was found.\n\t\t\t\tthrow new IllegalArgumentException(\"No curve of the name \" + forwardCurveName + \" was found in the model.\");\n\t\t\t}\n\t\t}\n\n\t\tdouble value = 0.0;\n\t\tfor(int periodIndex=0; periodIndex<schedule.getNumberOfPeriods(); periodIndex++) {\n\t\t\tdouble fixingDate\t= schedule.getFixing(periodIndex);\n\t\t\tdouble paymentDate\t= schedule.getPayment(periodIndex);\n\t\t\tdouble periodLength\t= schedule.getPeriodLength(periodIndex);\n\n\t\t\t/*\n\t\t\t * We do not count empty periods.\n\t\t\t * Since empty periods are an indication for a ill-specified product,\n\t\t\t * it might be reasonable to throw an illegal argument exception instead.\n\t\t\t */\n\t\t\tif(periodLength == 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tdouble forward = 0.0;\n\t\t\tif(forwardCurve != null) {\n\t\t\t\tforward\t\t\t+= forwardCurve.getForward(model, fixingDate, paymentDate-fixingDate);\n\t\t\t}\n\t\t\telse if(discountCurveForForward != null) {\n\t\t\t\t/*\n\t\t\t\t * Classical single curve case: using a discount curve as a forward curve.\n\t\t\t\t * This is only implemented for demonstration purposes (an exception would also be appropriate :-)\n\t\t\t\t */\n\t\t\t\tif(fixingDate != paymentDate) {\n\t\t\t\t\tforward\t\t\t+= (discountCurveForForward.getDiscountFactor(fixingDate) / discountCurveForForward.getDiscountFactor(paymentDate) - 1.0) / (paymentDate-fixingDate);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdouble discountFactor\t= paymentDate > evaluationTime ? discountCurve.getDiscountFactor(model, paymentDate) : 0.0;\n\t\t\tdouble payoffUnit = discountFactor * periodLength;\n\n\t\t\tdouble effektiveStrike = strike;\n\t\t\tif(isStrikeMoneyness) {\n\t\t\t\teffektiveStrike += getATMForward(model, true);\n\t\t\t}\n\n\t\t\tVolatilitySurface volatilitySurface\t= model.getVolatilitySurface(volatiltiySufaceName);\n\t\t\tif(volatilitySurface == null) {\n\t\t\t\tthrow new IllegalArgumentException(\"Volatility surface not found in model: \" + volatiltiySufaceName);\n\t\t\t}\n\t\t\tif(volatilitySurface.getQuotingConvention() == QuotingConvention.VOLATILITYLOGNORMAL) {\n\t\t\t\tdouble volatility = volatilitySurface.getValue(model, fixingDate, effektiveStrike, VolatilitySurface.QuotingConvention.VOLATILITYLOGNORMAL);\n\t\t\t\tvalue += AnalyticFormulas.blackScholesGeneralizedOptionValue(forward, volatility, fixingDate, effektiveStrike, payoffUnit);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Default to normal volatility as quoting convention\n\t\t\t\tdouble volatility = volatilitySurface.getValue(model, fixingDate, effektiveStrike, VolatilitySurface.QuotingConvention.VOLATILITYNORMAL);\n\t\t\t\tvalue += AnalyticFormulas.bachelierOptionValue(forward, volatility, fixingDate, effektiveStrike, payoffUnit);\n\t\t\t}\n\t\t}\n\n\t\treturn value / discountCurve.getDiscountFactor(model, evaluationTime);\n\t}", "protected boolean computeOffset(final int dataIndex, CacheDataSet cache) {\n float layoutOffset = getLayoutOffset();\n int pos = cache.getPos(dataIndex);\n float startDataOffset = Float.NaN;\n float endDataOffset = Float.NaN;\n if (pos > 0) {\n int id = cache.getId(pos - 1);\n if (id != -1) {\n startDataOffset = cache.getEndDataOffset(id);\n if (!Float.isNaN(startDataOffset)) {\n endDataOffset = cache.setDataAfter(dataIndex, startDataOffset);\n }\n }\n } else if (pos == 0) {\n int id = cache.getId(pos + 1);\n if (id != -1) {\n endDataOffset = cache.getStartDataOffset(id);\n if (!Float.isNaN(endDataOffset)) {\n startDataOffset = cache.setDataBefore(dataIndex, endDataOffset);\n }\n } else {\n startDataOffset = getStartingOffset((cache.getTotalSizeWithPadding()));\n endDataOffset = cache.setDataAfter(dataIndex, startDataOffset);\n }\n }\n\n Log.d(LAYOUT, TAG, \"computeOffset [%d, %d]: startDataOffset = %f endDataOffset = %f\",\n dataIndex, pos, startDataOffset, endDataOffset);\n\n boolean inBounds = !Float.isNaN(cache.getDataOffset(dataIndex)) &&\n endDataOffset > layoutOffset &&\n startDataOffset < -layoutOffset;\n\n return inBounds;\n }", "public ItemRequest<CustomField> updateEnumOption(String enumOption) {\n \n String path = String.format(\"/enum_options/%s\", enumOption);\n return new ItemRequest<CustomField>(this, CustomField.class, path, \"PUT\");\n }", "public Object materializeObject(ClassDescriptor cld, Identity oid)\r\n throws PersistenceBrokerException\r\n {\r\n final StatementManagerIF sm = broker.serviceStatementManager();\r\n final SelectStatement sql = broker.serviceSqlGenerator().getPreparedSelectByPkStatement(cld);\r\n Object result = null;\r\n PreparedStatement stmt = null;\r\n ResultSet rs = null;\r\n try\r\n {\r\n stmt = sm.getSelectByPKStatement(cld);\r\n if (stmt == null)\r\n {\r\n logger.error(\"getSelectByPKStatement returned a null statement\");\r\n throw new PersistenceBrokerException(\"getSelectByPKStatement returned a null statement\");\r\n }\r\n /*\r\n arminw: currently a select by PK could never be a stored procedure,\r\n thus we can always set 'false'. Is this correct??\r\n */\r\n sm.bindSelect(stmt, oid, cld, false);\r\n rs = stmt.executeQuery();\r\n // data available read object, else return null\r\n ResultSetAndStatement rs_stmt = new ResultSetAndStatement(broker.serviceStatementManager(), stmt, rs, sql);\r\n if (rs.next())\r\n {\r\n Map row = new HashMap();\r\n cld.getRowReader().readObjectArrayFrom(rs_stmt, row);\r\n result = cld.getRowReader().readObjectFrom(row);\r\n }\r\n // close resources\r\n rs_stmt.close();\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n // release resources on exception\r\n sm.closeResources(stmt, rs);\r\n logger.error(\"PersistenceBrokerException during the execution of materializeObject: \" + e.getMessage(), e);\r\n throw e;\r\n }\r\n catch (SQLException e)\r\n {\r\n // release resources on exception\r\n sm.closeResources(stmt, rs);\r\n throw ExceptionHelper.generateException(e, sql.getStatement(), cld, logger, null);\r\n }\r\n return result;\r\n }" ]
Write an attribute name. @param name attribute name
[ "private void writeName(String name) throws IOException\n {\n m_writer.write('\"');\n m_writer.write(name);\n m_writer.write('\"');\n m_writer.write(\":\");\n }" ]
[ "public static base_response unset(nitro_service client, sslparameter resource, String[] args) throws Exception{\n\t\tsslparameter unsetresource = new sslparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public Jar setMapAttribute(String name, Map<String, ?> values) {\n return setAttribute(name, join(values));\n }", "@SuppressWarnings(\"deprecation\")\n public boolean cancelOnTargetHosts(List<String> targetHosts) {\n\n boolean success = false;\n\n try {\n\n switch (state) {\n\n case IN_PROGRESS:\n if (executionManager != null\n && !executionManager.isTerminated()) {\n executionManager.tell(new CancelTaskOnHostRequest(\n targetHosts), executionManager);\n logger.info(\n \"asked task to stop from running on target hosts with count {}...\",\n targetHosts.size());\n } else {\n logger.info(\"manager already killed or not exist.. NO OP\");\n }\n success = true;\n break;\n case COMPLETED_WITHOUT_ERROR:\n case COMPLETED_WITH_ERROR:\n case WAITING:\n logger.info(\"will NO OP for cancelOnTargetHost as it is not in IN_PROGRESS state\");\n success = true;\n break;\n default:\n break;\n\n }\n\n } catch (Exception e) {\n logger.error(\n \"cancel task {} on hosts with count {} error with exception details \",\n this.getTaskId(), targetHosts.size(), e);\n }\n\n return success;\n }", "private void writeToDelegate(byte[] data) {\n\n if (m_delegateStream != null) {\n try {\n m_delegateStream.write(data);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n }", "public static void doEnqueue(final Jedis jedis, final String namespace, final String queue, final String jobJson) {\n jedis.sadd(JesqueUtils.createKey(namespace, QUEUES), queue);\n jedis.rpush(JesqueUtils.createKey(namespace, QUEUE, queue), jobJson);\n }", "public static void startCheck(String extra) {\n startCheckTime = System.currentTimeMillis();\n nextCheckTime = startCheckTime;\n Log.d(Log.SUBSYSTEM.TRACING, \"FPSCounter\" , \"[%d] startCheck %s\", startCheckTime, extra);\n }", "public static void setTime(Calendar cal, Date time)\n {\n if (time != null)\n {\n Calendar startCalendar = popCalendar(time);\n cal.set(Calendar.HOUR_OF_DAY, startCalendar.get(Calendar.HOUR_OF_DAY));\n cal.set(Calendar.MINUTE, startCalendar.get(Calendar.MINUTE));\n cal.set(Calendar.SECOND, startCalendar.get(Calendar.SECOND));\n pushCalendar(startCalendar);\n }\n }", "protected Object[] getParameterValues(Object specialVal, BeanManagerImpl manager, CreationalContext<?> ctx, CreationalContext<?> transientReferenceContext) {\n if (getInjectionPoints().isEmpty()) {\n if (specialInjectionPointIndex == -1) {\n return Arrays2.EMPTY_ARRAY;\n } else {\n return new Object[] { specialVal };\n }\n }\n Object[] parameterValues = new Object[getParameterInjectionPoints().size()];\n List<ParameterInjectionPoint<?, X>> parameters = getParameterInjectionPoints();\n for (int i = 0; i < parameterValues.length; i++) {\n ParameterInjectionPoint<?, ?> param = parameters.get(i);\n if (i == specialInjectionPointIndex) {\n parameterValues[i] = specialVal;\n } else if (hasTransientReferenceParameter && param.getAnnotated().isAnnotationPresent(TransientReference.class)) {\n parameterValues[i] = param.getValueToInject(manager, transientReferenceContext);\n } else {\n parameterValues[i] = param.getValueToInject(manager, ctx);\n }\n }\n return parameterValues;\n }", "private void updateRoutingStrategies(Cluster cluster, List<StoreDefinition> storeDefs) {\n // acquire write lock\n writeLock.lock();\n try {\n VectorClock clock = new VectorClock();\n if(metadataCache.containsKey(ROUTING_STRATEGY_KEY))\n clock = (VectorClock) metadataCache.get(ROUTING_STRATEGY_KEY).getVersion();\n\n logger.info(\"Updating routing strategy for all stores\");\n HashMap<String, StoreDefinition> storeDefMap = makeStoreDefinitionMap(storeDefs);\n HashMap<String, RoutingStrategy> routingStrategyMap = createRoutingStrategyMap(cluster,\n storeDefMap);\n this.metadataCache.put(ROUTING_STRATEGY_KEY,\n new Versioned<Object>(routingStrategyMap,\n clock.incremented(getNodeId(),\n System.currentTimeMillis())));\n\n for(String storeName: storeNameTolisteners.keySet()) {\n RoutingStrategy updatedRoutingStrategy = routingStrategyMap.get(storeName);\n if(updatedRoutingStrategy != null) {\n try {\n for(MetadataStoreListener listener: storeNameTolisteners.get(storeName)) {\n listener.updateRoutingStrategy(updatedRoutingStrategy);\n listener.updateStoreDefinition(storeDefMap.get(storeName));\n }\n } catch(Exception e) {\n if(logger.isEnabledFor(Level.WARN))\n logger.warn(e, e);\n }\n }\n\n }\n } finally {\n writeLock.unlock();\n }\n }" ]
Create an LBuffer from a given file. @param file @return @throws IOException
[ "public static LBuffer loadFrom(File file) throws IOException {\n FileChannel fin = new FileInputStream(file).getChannel();\n long fileSize = fin.size();\n if (fileSize > Integer.MAX_VALUE)\n throw new IllegalArgumentException(\"Cannot load from file more than 2GB: \" + file);\n LBuffer b = new LBuffer((int) fileSize);\n long pos = 0L;\n WritableChannelWrap ch = new WritableChannelWrap(b);\n while (pos < fileSize) {\n pos += fin.transferTo(0, fileSize, ch);\n }\n return b;\n }" ]
[ "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 ParallelTaskBuilder setTargetHostsFromJsonPath(String jsonPath,\n String sourcePath, HostsSourceType sourceType)\n throws TargetHostsLoadException {\n\n this.targetHosts = targetHostBuilder.setTargetHostsFromJsonPath(jsonPath, sourcePath,\n sourceType);\n return this;\n\n }", "@SuppressWarnings(\"deprecation\")\n public ResponseFromManager sendTaskToExecutionManager(ParallelTask task) {\n\n ResponseFromManager commandResponseFromManager = null;\n ActorRef executionManager = null;\n try {\n // Start new job\n logger.info(\"!!STARTED sendAgentCommandToManager : \"\n + task.getTaskId() + \" at \"\n + PcDateUtils.getNowDateTimeStr());\n\n executionManager = ActorConfig.createAndGetActorSystem().actorOf(\n Props.create(ExecutionManager.class, task),\n \"ExecutionManager-\" + task.getTaskId());\n\n final FiniteDuration duration = Duration.create(task.getConfig()\n .getTimeoutAskManagerSec(), TimeUnit.SECONDS);\n // Timeout timeout = new\n // Timeout(FiniteDuration.parse(\"300 seconds\"));\n Future<Object> future = Patterns.ask(executionManager,\n new InitialRequestToManager(task), new Timeout(duration));\n\n // set ref\n task.executionManager = executionManager;\n\n commandResponseFromManager = (ResponseFromManager) Await.result(\n future, duration);\n\n logger.info(\"!!COMPLETED sendTaskToExecutionManager : \"\n + task.getTaskId() + \" at \"\n + PcDateUtils.getNowDateTimeStr()\n + \" \\t\\t GenericResponseMap in future size: \"\n + commandResponseFromManager.getResponseCount());\n\n } catch (Exception ex) {\n logger.error(\"Exception in sendTaskToExecutionManager {} details {}: \",\n ex, ex);\n\n } finally {\n // stop the manager\n if (executionManager != null && !executionManager.isTerminated()) {\n ActorConfig.createAndGetActorSystem().stop(executionManager);\n }\n\n if (task.getConfig().isAutoSaveLogToLocal()) {\n task.saveLogToLocal();\n }\n\n }\n\n return commandResponseFromManager;\n\n }", "public static SVGGraphics2D createSvgGraphics(final Dimension size)\n throws ParserConfigurationException {\n DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\n DocumentBuilder db = dbf.newDocumentBuilder();\n Document document = db.getDOMImplementation().createDocument(null, \"svg\", null);\n\n SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(document);\n ctx.setStyleHandler(new OpacityAdjustingStyleHandler());\n ctx.setComment(\"Generated by GeoTools2 with Batik SVG Generator\");\n\n SVGGraphics2D g2d = new SVGGraphics2D(ctx, true);\n g2d.setSVGCanvasSize(size);\n\n return g2d;\n }", "public T insert(T entity) {\n\n if (!hasPrimaryKey(entity)) {\n throw new RuntimeException(String.format(\"Tried to insert entity of type %s with null or zero primary key\",\n entity.getClass().getSimpleName()));\n }\n\n InsertCreator insert = new InsertCreator(table);\n\n insert.setValue(idColumn.getColumnName(), getPrimaryKey(entity));\n\n if (versionColumn != null) {\n insert.setValue(versionColumn.getColumnName(), 0);\n }\n\n for (Column column : columns) {\n if (!column.isReadOnly()) {\n insert.setValue(column.getColumnName(), getFieldValueAsColumn(entity, column));\n }\n }\n\n new JdbcTemplate(ormConfig.getDataSource()).update(insert);\n\n if (versionColumn != null) {\n ReflectionUtils.setFieldValue(entity, versionColumn.getFieldName(), 0);\n }\n\n return entity;\n }", "public static final Number parseUnits(Number value)\n {\n return (value == null ? null : NumberHelper.getDouble(value.doubleValue() * 100));\n }", "public void close() throws IOException {\n for (CloseableHttpClient c : cachedClients.values()) {\n c.close();\n }\n cachedClients.clear();\n }", "public static String compactDump(INode node, boolean showHidden) {\n\t\tStringBuilder result = new StringBuilder();\n\t\ttry {\n\t\t\tcompactDump(node, showHidden, \"\", result);\n\t\t} catch (IOException e) {\n\t\t\treturn e.getMessage();\n\t\t}\n\t\treturn result.toString();\n\t}", "public void unlinkFK(Object targetObject, ClassDescriptor cld, ObjectReferenceDescriptor rds)\n {\n setFKField(targetObject, cld, rds, null);\n }" ]
A loop driver for applying operations to all primary ClassNodes in our AST. Automatically skips units that have already been processed through the current phase.
[ "public void applyToPrimaryClassNodes(PrimaryClassNodeOperation body) throws CompilationFailedException {\n Iterator classNodes = getPrimaryClassNodes(body.needSortedInput()).iterator();\n while (classNodes.hasNext()) {\n SourceUnit context = null;\n try {\n ClassNode classNode = (ClassNode) classNodes.next();\n context = classNode.getModule().getContext();\n if (context == null || context.phase < phase || (context.phase == phase && !context.phaseComplete)) {\n int offset = 1;\n Iterator<InnerClassNode> iterator = classNode.getInnerClasses();\n while (iterator.hasNext()) {\n iterator.next();\n offset++;\n }\n body.call(context, new GeneratorContext(this.ast, offset), classNode);\n }\n } catch (CompilationFailedException e) {\n // fall through, getErrorReporter().failIfErrors() will trigger\n } catch (NullPointerException npe) {\n GroovyBugError gbe = new GroovyBugError(\"unexpected NullpointerException\", npe);\n changeBugText(gbe, context);\n throw gbe;\n } catch (GroovyBugError e) {\n changeBugText(e, context);\n throw e;\n } catch (NoClassDefFoundError e) {\n // effort to get more logging in case a dependency of a class is loaded\n // although it shouldn't have\n convertUncaughtExceptionToCompilationError(e);\n } catch (Exception e) {\n convertUncaughtExceptionToCompilationError(e);\n }\n }\n\n getErrorCollector().failIfErrors();\n }" ]
[ "public StitchEvent<T> nextEvent() throws IOException {\n final Event nextEvent = eventStream.nextEvent();\n if (nextEvent == null) {\n return null;\n }\n\n return StitchEvent.fromEvent(nextEvent, this.decoder);\n }", "private String getRowLineBuf(int colCount, List<Integer> colMaxLenList, String[][] data) {\n\t\t\n\t\tS.Buffer rowBuilder = S.buffer();\n\t\tint colWidth;\n\t\t\n\t\tfor (int i = 0 ; i < colCount ; i ++) {\n\t\t\t\n\t\t\tcolWidth = colMaxLenList.get(i) + 3;\n\t\t\t\n\t\t\tfor (int j = 0; j < colWidth ; j ++) {\n\t\t\t\tif (j==0) {\n\t\t\t\t\trowBuilder.append(\"+\");\n\t\t\t\t} else if ((i+1 == colCount && j+1 == colWidth)) {//for last column close the border\n\t\t\t\t\trowBuilder.append(\"-+\");\n\t\t\t\t} else {\n\t\t\t\t\trowBuilder.append(\"-\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn rowBuilder.append(\"\\n\").toString();\n\t}", "@Override\r\n public String upload(File file, UploadMetaData metaData) throws FlickrException {\r\n Payload payload = new Payload(file);\r\n return sendUploadRequest(metaData, payload);\r\n }", "public static long addressToLong(InetAddress address) {\n long result = 0;\n for (byte element : address.getAddress()) {\n result = (result << 8) + unsign(element);\n }\n return result;\n }", "public static final void setSize(UIObject o, Rect size) {\n o.setPixelSize(size.w, size.h);\n\n }", "public ItemDocumentBuilder withSiteLink(String title, String siteKey,\n\t\t\tItemIdValue... badges) {\n\t\twithSiteLink(factory.getSiteLink(title, siteKey, Arrays.asList(badges)));\n\t\treturn this;\n\t}", "protected void appendWhereClause(StringBuffer where, Criteria crit, StringBuffer stmt)\r\n {\r\n if (where.length() == 0)\r\n {\r\n where = null;\r\n }\r\n\r\n if (where != null || (crit != null && !crit.isEmpty()))\r\n {\r\n stmt.append(\" WHERE \");\r\n appendClause(where, crit, stmt);\r\n }\r\n }", "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 }", "public void processCollection(String template, Properties attributes) throws XDocletException\r\n {\r\n String name = OjbMemberTagsHandler.getMemberName();\r\n CollectionDescriptorDef collDef = _curClassDef.getCollection(name);\r\n String attrName;\r\n\r\n if (collDef == null)\r\n {\r\n collDef = new CollectionDescriptorDef(name);\r\n _curClassDef.addCollection(collDef);\r\n }\r\n LogHelper.debug(false, OjbTagsHandler.class, \"processCollection\", \" Processing collection \"+collDef.getName());\r\n\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n collDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n if (OjbMemberTagsHandler.getMemberDimension() > 0)\r\n {\r\n // we store the array-element type for later use\r\n collDef.setProperty(PropertyHelper.OJB_PROPERTY_ARRAY_ELEMENT_CLASS_REF,\r\n OjbMemberTagsHandler.getMemberType().getQualifiedName());\r\n }\r\n else\r\n { \r\n collDef.setProperty(PropertyHelper.OJB_PROPERTY_VARIABLE_TYPE,\r\n OjbMemberTagsHandler.getMemberType().getQualifiedName());\r\n }\r\n\r\n _curCollectionDef = collDef;\r\n generate(template);\r\n _curCollectionDef = null;\r\n }" ]
Call the constructor for the given class, inferring the correct types for the arguments. This could be confusing if there are multiple constructors with the same number of arguments and the values themselves don't disambiguate. @param klass The class to construct @param args The arguments @return The constructed value
[ "public static <T> T callConstructor(Class<T> klass, Object[] args) {\n Class<?>[] klasses = new Class[args.length];\n for(int i = 0; i < args.length; i++)\n klasses[i] = args[i].getClass();\n return callConstructor(klass, klasses, args);\n }" ]
[ "public static JRDesignGroup getJRDesignGroup(DynamicJasperDesign jd, LayoutManager layoutManager, DJGroup group) {\n\t\tMap references = layoutManager.getReferencesMap();\n\t\tfor (Object o : references.keySet()) {\n\t\t\tString groupName = (String) o;\n\t\t\tDJGroup djGroup = (DJGroup) references.get(groupName);\n\t\t\tif (group == djGroup) {\n\t\t\t\treturn (JRDesignGroup) jd.getGroupsMap().get(groupName);\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}", "@Override\n public T getById(Object id)\n {\n return context.getFramed().getFramedVertex(this.type, id);\n }", "public static authenticationradiusaction get(nitro_service service, String name) throws Exception{\n\t\tauthenticationradiusaction obj = new authenticationradiusaction();\n\t\tobj.set_name(name);\n\t\tauthenticationradiusaction response = (authenticationradiusaction) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static Multimap<String, String> getParameters(final String rawQuery) {\n Multimap<String, String> result = HashMultimap.create();\n if (rawQuery == null) {\n return result;\n }\n\n StringTokenizer tokens = new StringTokenizer(rawQuery, \"&\");\n while (tokens.hasMoreTokens()) {\n String pair = tokens.nextToken();\n int pos = pair.indexOf('=');\n String key;\n String value;\n if (pos == -1) {\n key = pair;\n value = \"\";\n } else {\n\n try {\n key = URLDecoder.decode(pair.substring(0, pos), \"UTF-8\");\n value = URLDecoder.decode(pair.substring(pos + 1), \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }\n\n result.put(key, value);\n }\n return result;\n }", "private FieldConversion[] getPkFieldConversion(ClassDescriptor cld)\r\n {\r\n FieldDescriptor[] pks = cld.getPkFields();\r\n FieldConversion[] fc = new FieldConversion[pks.length]; \r\n \r\n for (int i= 0; i < pks.length; i++)\r\n {\r\n fc[i] = pks[i].getFieldConversion();\r\n }\r\n \r\n return fc;\r\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 double getValue(int[] batch) {\n double value = 0.0;\n for (int i=0; i<batch.length; i++) {\n value += getValue(i);\n }\n return value;\n }", "public void setRegExp(final String pattern,\n final String invalidCharactersInNameErrorMessage,\n final String invalidCharacterTypedMessage) {\n regExp = RegExp.compile(pattern);\n this.invalidCharactersInNameErrorMessage = invalidCharactersInNameErrorMessage;\n this.invalidCharacterTypedMessage = invalidCharacterTypedMessage;\n }", "public static void pow(ComplexPolar_F64 a , int N , ComplexPolar_F64 result )\n {\n result.r = Math.pow(a.r,N);\n result.theta = N*a.theta;\n }" ]
Load a test file, run the classifier on it, and then write a Viterbi search graph for each sequence. @param testFile The file to test on.
[ "public void classifyAndWriteViterbiSearchGraph(String testFile, String searchGraphPrefix, DocumentReaderAndWriter<IN> readerAndWriter) throws IOException {\r\n Timing timer = new Timing();\r\n ObjectBank<List<IN>> documents =\r\n makeObjectBankFromFile(testFile, readerAndWriter);\r\n int numWords = 0;\r\n int numSentences = 0;\r\n\r\n for (List<IN> doc : documents) {\r\n DFSA<String, Integer> tagLattice = getViterbiSearchGraph(doc, AnswerAnnotation.class);\r\n numWords += doc.size();\r\n PrintWriter latticeWriter = new PrintWriter(new FileOutputStream(searchGraphPrefix + '.' + numSentences\r\n + \".wlattice\"));\r\n PrintWriter vsgWriter = new PrintWriter(new FileOutputStream(searchGraphPrefix + '.' + numSentences + \".lattice\"));\r\n if (readerAndWriter instanceof LatticeWriter)\r\n ((LatticeWriter) readerAndWriter).printLattice(tagLattice, doc, latticeWriter);\r\n tagLattice.printAttFsmFormat(vsgWriter);\r\n latticeWriter.close();\r\n vsgWriter.close();\r\n numSentences++;\r\n }\r\n\r\n long millis = timer.stop();\r\n double wordspersec = numWords / (((double) millis) / 1000);\r\n NumberFormat nf = new DecimalFormat(\"0.00\"); // easier way!\r\n System.err.println(this.getClass().getName() + \" tagged \" + numWords + \" words in \" + numSentences\r\n + \" documents at \" + nf.format(wordspersec) + \" words per second.\");\r\n }" ]
[ "public void unload()\n {\n if (mAudioListener != null)\n {\n Log.d(\"SOUND\", \"unloading audio source %d %s\", getSourceId(), getSoundFile());\n mAudioListener.getAudioEngine().unloadSoundFile(getSoundFile());\n }\n mSoundFile = null;\n mSourceId = GvrAudioEngine.INVALID_ID;\n }", "public static nsacl6[] get(nitro_service service, String acl6name[]) throws Exception{\n\t\tif (acl6name !=null && acl6name.length>0) {\n\t\t\tnsacl6 response[] = new nsacl6[acl6name.length];\n\t\t\tnsacl6 obj[] = new nsacl6[acl6name.length];\n\t\t\tfor (int i=0;i<acl6name.length;i++) {\n\t\t\t\tobj[i] = new nsacl6();\n\t\t\t\tobj[i].set_acl6name(acl6name[i]);\n\t\t\t\tresponse[i] = (nsacl6) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "private void performDownload(HttpResponse response, File destFile)\n throws IOException {\n HttpEntity entity = response.getEntity();\n if (entity == null) {\n return;\n }\n \n //get content length\n long contentLength = entity.getContentLength();\n if (contentLength >= 0) {\n size = toLengthText(contentLength);\n }\n \n processedBytes = 0;\n loggedKb = 0;\n \n //open stream and start downloading\n InputStream is = entity.getContent();\n streamAndMove(is, destFile);\n }", "public static Drawable decideIcon(ImageHolder imageHolder, Context ctx, int iconColor, boolean tint) {\n if (imageHolder == null) {\n return null;\n } else {\n return imageHolder.decideIcon(ctx, iconColor, tint);\n }\n }", "private AlbumArt requestArtworkInternal(final DataReference artReference, final CdjStatus.TrackType trackType,\n final boolean failIfPassive) {\n\n // First check if we are using cached data for this slot.\n MetadataCache cache = MetadataFinder.getInstance().getMetadataCache(SlotReference.getSlotReference(artReference));\n if (cache != null) {\n final AlbumArt result = cache.getAlbumArt(null, artReference);\n if (result != null) {\n artCache.put(artReference, result);\n }\n return result;\n }\n\n // Then see if any registered metadata providers can offer it for us.\n final MediaDetails sourceDetails = MetadataFinder.getInstance().getMediaDetailsFor(artReference.getSlotReference());\n if (sourceDetails != null) {\n final AlbumArt provided = MetadataFinder.getInstance().allMetadataProviders.getAlbumArt(sourceDetails, artReference);\n if (provided != null) {\n return provided;\n }\n }\n\n // At this point, unless we are allowed to actively request the data, we are done. We can always actively\n // request tracks from rekordbox.\n if (MetadataFinder.getInstance().isPassive() && failIfPassive && artReference.slot != CdjStatus.TrackSourceSlot.COLLECTION) {\n return null;\n }\n\n // We have to actually request the art using the dbserver protocol.\n ConnectionManager.ClientTask<AlbumArt> task = new ConnectionManager.ClientTask<AlbumArt>() {\n @Override\n public AlbumArt useClient(Client client) throws Exception {\n return getArtwork(artReference.rekordboxId, SlotReference.getSlotReference(artReference), trackType, client);\n }\n };\n\n try {\n AlbumArt artwork = ConnectionManager.getInstance().invokeWithClientSession(artReference.player, task, \"requesting artwork\");\n if (artwork != null) { // Our cache file load or network request succeeded, so add to the level 2 cache.\n artCache.put(artReference, artwork);\n }\n return artwork;\n } catch (Exception e) {\n logger.error(\"Problem requesting album art, returning null\", e);\n }\n return null;\n }", "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 }", "public static nspbr6[] get(nitro_service service) throws Exception{\n\t\tnspbr6 obj = new nspbr6();\n\t\tnspbr6[] response = (nspbr6[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public static boolean isCacheSafe(Class<?> clazz, ClassLoader classLoader) {\n\t\tAssert.notNull(clazz, \"Class must not be null\");\n\t\ttry {\n\t\t\tClassLoader target = clazz.getClassLoader();\n\t\t\tif (target == null) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tClassLoader cur = classLoader;\n\t\t\tif (cur == target) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\twhile (cur != null) {\n\t\t\t\tcur = cur.getParent();\n\t\t\t\tif (cur == target) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\tcatch (SecurityException ex) {\n\t\t\t// Probably from the system ClassLoader - let's consider it safe.\n\t\t\treturn true;\n\t\t}\n\t}", "public static ResourceKey key(Enum<?> value) {\n return new ResourceKey(value.getClass().getName(), value.name());\n }" ]
Read data for a single table and store it. @param is input stream @param table table header
[ "private void readTable(InputStream is, SynchroTable table) throws IOException\n {\n int skip = table.getOffset() - m_offset;\n if (skip != 0)\n {\n StreamHelper.skip(is, skip);\n m_offset += skip;\n }\n\n String tableName = DatatypeConverter.getString(is);\n int tableNameLength = 2 + tableName.length();\n m_offset += tableNameLength;\n\n int dataLength;\n if (table.getLength() == -1)\n {\n dataLength = is.available();\n }\n else\n {\n dataLength = table.getLength() - tableNameLength;\n }\n\n SynchroLogger.log(\"READ\", tableName);\n\n byte[] compressedTableData = new byte[dataLength];\n is.read(compressedTableData);\n m_offset += dataLength;\n\n Inflater inflater = new Inflater();\n inflater.setInput(compressedTableData);\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream(compressedTableData.length);\n byte[] buffer = new byte[1024];\n while (!inflater.finished())\n {\n int count;\n\n try\n {\n count = inflater.inflate(buffer);\n }\n catch (DataFormatException ex)\n {\n throw new IOException(ex);\n }\n outputStream.write(buffer, 0, count);\n }\n outputStream.close();\n byte[] uncompressedTableData = outputStream.toByteArray();\n\n SynchroLogger.log(uncompressedTableData);\n\n m_tableData.put(table.getName(), uncompressedTableData);\n }" ]
[ "protected String failMsg(final Throwable thrwbl, final String queue, final Job job) throws IOException {\n final JobFailure failure = new JobFailure();\n failure.setFailedAt(new Date());\n failure.setWorker(this.name);\n failure.setQueue(queue);\n failure.setPayload(job);\n failure.setThrowable(thrwbl);\n return ObjectMapperFactory.get().writeValueAsString(failure);\n }", "public String generateDigest(InputStream stream) {\n MessageDigest digest = null;\n try {\n digest = MessageDigest.getInstance(DIGEST_ALGORITHM_SHA1);\n } catch (NoSuchAlgorithmException ae) {\n throw new BoxAPIException(\"Digest algorithm not found\", ae);\n }\n\n //Calcuate the digest using the stream.\n DigestInputStream dis = new DigestInputStream(stream, digest);\n try {\n int value = dis.read();\n while (value != -1) {\n value = dis.read();\n }\n } catch (IOException ioe) {\n throw new BoxAPIException(\"Reading the stream failed.\", ioe);\n }\n\n //Get the calculated digest for the stream\n byte[] digestBytes = digest.digest();\n return Base64.encode(digestBytes);\n }", "public ImmutableList<CandidateElement> extract(StateVertex currentState)\n\t\t\tthrows CrawljaxException {\n\t\tLinkedList<CandidateElement> results = new LinkedList<>();\n\n\t\tif (!checkedElements.checkCrawlCondition(browser)) {\n\t\t\tLOG.info(\"State {} did not satisfy the CrawlConditions.\", currentState.getName());\n\t\t\treturn ImmutableList.of();\n\t\t}\n\t\tLOG.debug(\"Looking in state: {} for candidate elements\", currentState.getName());\n\n\t\ttry {\n\t\t\tDocument dom = DomUtils.asDocument(browser.getStrippedDomWithoutIframeContent());\n\t\t\textractElements(dom, results, \"\");\n\t\t} catch (IOException e) {\n\t\t\tLOG.error(e.getMessage(), e);\n\t\t\tthrow new CrawljaxException(e);\n\t\t}\n\t\tif (randomizeElementsOrder) {\n\t\t\tCollections.shuffle(results);\n\t\t}\n\t\tcurrentState.setElementsFound(results);\n\t\tLOG.debug(\"Found {} new candidate elements to analyze!\", results.size());\n\t\treturn ImmutableList.copyOf(results);\n\t}", "protected void checkObserverMethods() {\n Collection<EnhancedAnnotatedMethod<?, ? super T>> observerMethods = BeanMethods.getObserverMethods(this.getEnhancedAnnotated());\n Collection<EnhancedAnnotatedMethod<?, ? super T>> asyncObserverMethods = BeanMethods.getAsyncObserverMethods(this.getEnhancedAnnotated());\n checkObserverMethods(observerMethods);\n checkObserverMethods(asyncObserverMethods);\n }", "public static String fileNameClean(String s) {\r\n char[] chars = s.toCharArray();\r\n StringBuilder sb = new StringBuilder();\r\n for (char c : chars) {\r\n if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c == '_')) {\r\n sb.append(c);\r\n } else {\r\n if (c == ' ' || c == '-') {\r\n sb.append('_');\r\n } else {\r\n sb.append('x').append((int) c).append('x');\r\n }\r\n }\r\n }\r\n return sb.toString();\r\n }", "private static int readDataBlock(String text, int offset, int length, List<byte[]> blocks)\n {\n int bytes = length / 2;\n byte[] data = new byte[bytes];\n\n for (int index = 0; index < bytes; index++)\n {\n data[index] = (byte) Integer.parseInt(text.substring(offset, offset + 2), 16);\n offset += 2;\n }\n\n blocks.add(data);\n return (offset);\n }", "public static Set<String> commaDelimitedListToSet(String str) {\n Set<String> set = new TreeSet<String>();\n String[] tokens = commaDelimitedListToStringArray(str);\n Collections.addAll(set, tokens);\n return set;\n }", "private boolean computeUWV() {\n bidiag.getDiagonal(diag,off);\n qralg.setMatrix(numRowsT,numColsT,diag,off);\n\n// long pointA = System.currentTimeMillis();\n // compute U and V matrices\n if( computeU )\n Ut = bidiag.getU(Ut,true,compact);\n if( computeV )\n Vt = bidiag.getV(Vt,true,compact);\n\n qralg.setFastValues(false);\n if( computeU )\n qralg.setUt(Ut);\n else\n qralg.setUt(null);\n if( computeV )\n qralg.setVt(Vt);\n else\n qralg.setVt(null);\n\n// long pointB = System.currentTimeMillis();\n\n boolean ret = !qralg.process();\n\n// long pointC = System.currentTimeMillis();\n// System.out.println(\" compute UV \"+(pointB-pointA)+\" QR = \"+(pointC-pointB));\n\n return ret;\n }", "public List<Map<String, String>> produceNWise(int nWise, String[] coVariables, Map<String, String[]> variableDomains) {\r\n List<Set<String>> tuples = makeNWiseTuples(coVariables, nWise);\n\r\n List<Map<String, String>> testCases = new ArrayList<>();\r\n for (Set<String> tuple : tuples) {\r\n testCases.addAll(expandTupleIntoTestCases(tuple, variableDomains));\r\n }\n\r\n return testCases;\r\n }" ]
Heat Equation Boundary Conditions
[ "private double u_neg_inf(double x, double tau) {\n\t\treturn f(boundaryCondition.getValueAtLowerBoundary(model, f_t(tau), f_s(x)), x, tau);\n\t}" ]
[ "public static void writeHints(File file, Map<String,List<Long>> hints) throws IOException {\n Closer closer = Closer.create();\n try {\n BufferedWriter w = closer.register(Files.newWriter(file, Charsets.UTF_8));\n if (!(hints instanceof SortedMap)) {\n hints = new TreeMap<String,List<Long>>(hints);\n }\n \n Joiner joiner = Joiner.on(',');\n for (Map.Entry<String,List<Long>> e : hints.entrySet()) {\n w.write(e.getKey());\n w.write(\"=\");\n joiner.appendTo(w, e.getValue());\n w.write(\"\\n\");\n }\n } catch (Throwable t) {\n throw closer.rethrow(t);\n } finally {\n closer.close();\n }\n }", "public void cache(String key, Object obj) {\n H.Session sess = session();\n if (null != sess) {\n sess.cache(key, obj);\n } else {\n app().cache().put(key, obj);\n }\n }", "private String listToCSV(List<String> list) {\n String csvStr = \"\";\n for (String item : list) {\n csvStr += \",\" + item;\n }\n\n return csvStr.length() > 1 ? csvStr.substring(1) : csvStr;\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 static List<Expression> getVariableExpressions(DeclarationExpression declarationExpression) {\r\n Expression leftExpression = declarationExpression.getLeftExpression();\r\n\r\n // !important: performance enhancement\r\n if (leftExpression instanceof ArrayExpression) {\r\n List<Expression> expressions = ((ArrayExpression) leftExpression).getExpressions();\r\n return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions;\r\n } else if (leftExpression instanceof ListExpression) {\r\n List<Expression> expressions = ((ListExpression) leftExpression).getExpressions();\r\n return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions;\r\n } else if (leftExpression instanceof TupleExpression) {\r\n List<Expression> expressions = ((TupleExpression) leftExpression).getExpressions();\r\n return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions;\r\n } else if (leftExpression instanceof VariableExpression) {\r\n return Arrays.asList(leftExpression);\r\n }\r\n // todo: write warning\r\n return Collections.emptyList();\r\n }", "@Override\n\tpublic List<Object> loadEntitiesFromTuples(SharedSessionContractImplementor session, LockOptions lockOptions, OgmLoadingContext ogmContext) {\n\t\treturn loadEntity( null, null, session, lockOptions, ogmContext );\n\t}", "public static sslaction get(nitro_service service, String name) throws Exception{\n\t\tsslaction obj = new sslaction();\n\t\tobj.set_name(name);\n\t\tsslaction response = (sslaction) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static TimeZone get(String suffix) {\n if(SUFFIX_TIMEZONES.containsKey(suffix)) {\n return SUFFIX_TIMEZONES.get(suffix);\n }\n log.warn(\"Cannot find time zone for exchange suffix: '{}'. Using default: America/New_York\", suffix);\n return SUFFIX_TIMEZONES.get(\"\");\n }", "public static double HighAccuracyComplemented(double x) {\n double[] R =\n {\n 1.25331413731550025, 0.421369229288054473, 0.236652382913560671,\n 0.162377660896867462, 0.123131963257932296, 0.0990285964717319214,\n 0.0827662865013691773, 0.0710695805388521071, 0.0622586659950261958\n };\n\n int j = (int) (0.5 * (Math.abs(x) + 1));\n\n double a = R[j];\n double z = 2 * j;\n double b = a * z - 1;\n\n double h = Math.abs(x) - z;\n double q = h * h;\n double pwr = 1;\n\n double sum = a + h * b;\n double term = a;\n\n\n for (int i = 2; sum != term; i += 2) {\n term = sum;\n\n a = (a + z * b) / (i);\n b = (b + z * a) / (i + 1);\n pwr *= q;\n\n sum = term + pwr * (a + h * b);\n }\n\n sum *= Math.exp(-0.5 * (x * x) - 0.5 * Constants.Log2PI);\n\n return (x >= 0) ? sum : (1.0 - sum);\n }" ]
Expands all parents in a range of indices in the list of parents. @param startParentPosition The index at which to to start expanding parents @param parentCount The number of parents to expand
[ "@UiThread\n public void expandParentRange(int startParentPosition, int parentCount) {\n int endParentPosition = startParentPosition + parentCount;\n for (int i = startParentPosition; i < endParentPosition; i++) {\n expandParent(i);\n }\n }" ]
[ "private JsonObject getPendingJSONObject() {\n for (Map.Entry<String, BoxJSONObject> entry : this.children.entrySet()) {\n BoxJSONObject child = entry.getValue();\n JsonObject jsonObject = child.getPendingJSONObject();\n if (jsonObject != null) {\n if (this.pendingChanges == null) {\n this.pendingChanges = new JsonObject();\n }\n\n this.pendingChanges.set(entry.getKey(), jsonObject);\n }\n }\n return this.pendingChanges;\n }", "public void deleteFolder(String folderID) {\n URL url = FOLDER_INFO_URL_TEMPLATE.build(this.api.getBaseURL(), folderID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"DELETE\");\n BoxAPIResponse response = request.send();\n response.disconnect();\n }", "public static String urlEncode(String path) throws URISyntaxException {\n if (isNullOrEmpty(path)) return path;\n\n return UrlEscapers.urlFragmentEscaper().escape(path);\n }", "public static Type boxedType(Type type) {\n if (type instanceof Class<?>) {\n return boxedClass((Class<?>) type);\n } else {\n return type;\n }\n }", "public static systemsession[] get(nitro_service service, Long sid[]) throws Exception{\n\t\tif (sid !=null && sid.length>0) {\n\t\t\tsystemsession response[] = new systemsession[sid.length];\n\t\t\tsystemsession obj[] = new systemsession[sid.length];\n\t\t\tfor (int i=0;i<sid.length;i++) {\n\t\t\t\tobj[i] = new systemsession();\n\t\t\t\tobj[i].set_sid(sid[i]);\n\t\t\t\tresponse[i] = (systemsession) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "public Metadata createMetadata(String templateName, Metadata metadata) {\n String scope = Metadata.scopeBasedOnType(templateName);\n return this.createMetadata(templateName, scope, metadata);\n }", "public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {\n final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();\n final ServicesAttachment servicesAttachment = deploymentUnit.getAttachment(Attachments.SERVICES);\n if (servicesAttachment == null || servicesAttachment.getServiceImplementations(ServiceActivator.class.getName()).isEmpty()) {\n return; // Skip it if it has not been marked\n }\n final Module module = deploymentUnit.getAttachment(Attachments.MODULE);\n if (module == null) {\n return; // Skip deployments with no module\n }\n\n AttachmentList<DeploymentUnit> duList = deploymentUnit.getAttachment(Attachments.SUB_DEPLOYMENTS);\n List<String> serviceAcitvatorList = new ArrayList<String>();\n if (duList!=null && !duList.isEmpty()) {\n for (DeploymentUnit du : duList) {\n ServicesAttachment duServicesAttachment = du.getAttachment(Attachments.SERVICES);\n for (String serv : duServicesAttachment.getServiceImplementations(ServiceActivator.class.getName())) {\n serviceAcitvatorList.add(serv);\n }\n }\n }\n\n ServiceRegistry serviceRegistry = phaseContext.getServiceRegistry();\n if (WildFlySecurityManager.isChecking()) {\n //service registry allows you to modify internal server state across all deployments\n //if a security manager is present we use a version that has permission checks\n serviceRegistry = new SecuredServiceRegistry(serviceRegistry);\n }\n final ServiceActivatorContext serviceActivatorContext = new ServiceActivatorContextImpl(phaseContext.getServiceTarget(), serviceRegistry);\n\n final ClassLoader current = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();\n\n try {\n WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(module.getClassLoader());\n for (ServiceActivator serviceActivator : module.loadService(ServiceActivator.class)) {\n try {\n for (String serv : servicesAttachment.getServiceImplementations(ServiceActivator.class.getName())) {\n if (serv.compareTo(serviceActivator.getClass().getName()) == 0 && !serviceAcitvatorList.contains(serv)) {\n serviceActivator.activate(serviceActivatorContext);\n break;\n }\n }\n } catch (ServiceRegistryException e) {\n throw new DeploymentUnitProcessingException(e);\n }\n }\n } finally {\n WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(current);\n }\n }", "public ThreadInfo[] getThreadDump() {\n ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();\n return threadMxBean.dumpAllThreads(true, true);\n }", "private void readTask(ChildTaskContainer mpxjParent, net.sf.mpxj.ganttproject.schema.Task gpTask)\n {\n Task mpxjTask = mpxjParent.addTask();\n mpxjTask.setUniqueID(Integer.valueOf(NumberHelper.getInt(gpTask.getId()) + 1));\n mpxjTask.setName(gpTask.getName());\n mpxjTask.setPercentageComplete(gpTask.getComplete());\n mpxjTask.setPriority(getPriority(gpTask.getPriority()));\n mpxjTask.setHyperlink(gpTask.getWebLink());\n\n Duration duration = Duration.getInstance(NumberHelper.getDouble(gpTask.getDuration()), TimeUnit.DAYS);\n mpxjTask.setDuration(duration);\n\n if (duration.getDuration() == 0)\n {\n mpxjTask.setMilestone(true);\n }\n else\n {\n mpxjTask.setStart(gpTask.getStart());\n mpxjTask.setFinish(m_mpxjCalendar.getDate(gpTask.getStart(), mpxjTask.getDuration(), false));\n }\n\n mpxjTask.setConstraintDate(gpTask.getThirdDate());\n if (mpxjTask.getConstraintDate() != null)\n {\n // TODO: you don't appear to be able to change this setting in GanttProject\n // task.getThirdDateConstraint()\n mpxjTask.setConstraintType(ConstraintType.START_NO_EARLIER_THAN);\n }\n\n readTaskCustomFields(gpTask, mpxjTask);\n\n m_eventManager.fireTaskReadEvent(mpxjTask);\n\n // TODO: read custom values\n\n //\n // Process child tasks\n //\n for (net.sf.mpxj.ganttproject.schema.Task childTask : gpTask.getTask())\n {\n readTask(mpxjTask, childTask);\n }\n }" ]
Read custom property definitions for tasks. @param gpTasks GanttProject tasks
[ "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 synchronized void releaseRebalancingPermit(int nodeId) {\n boolean removed = rebalancePermits.remove(nodeId);\n logger.info(\"Releasing rebalancing permit for node id \" + nodeId + \", returned: \" + removed);\n if(!removed)\n throw new VoldemortException(new IllegalStateException(\"Invalid state, must hold a \"\n + \"permit to release\"));\n }", "public Curve getRegressionCurve(){\n\t\t// @TODO Add threadsafe lazy init.\n\t\tif(regressionCurve !=null) {\n\t\t\treturn regressionCurve;\n\t\t}\n\t\tDoubleMatrix a = solveEquationSystem();\n\t\tdouble[] curvePoints=new double[partition.getLength()];\n\t\tcurvePoints[0]=a.get(0);\n\t\tfor(int i=1;i<curvePoints.length;i++) {\n\t\t\tcurvePoints[i]=curvePoints[i-1]+a.get(i)*(partition.getIntervalLength(i-1));\n\t\t}\n\t\treturn new CurveInterpolation(\n\t\t\t\t\"RegressionCurve\",\n\t\t\t\treferenceDate,\n\t\t\t\tCurveInterpolation.InterpolationMethod.LINEAR,\n\t\t\t\tCurveInterpolation.ExtrapolationMethod.CONSTANT,\n\t\t\t\tCurveInterpolation.InterpolationEntity.VALUE,\n\t\t\t\tpartition.getPoints(),\n\t\t\t\tcurvePoints);\n\t}", "public static Chart getMSDLineChart(Trajectory t, int lagMin, int lagMax) {\n\t\treturn getMSDLineChart(t, lagMin, lagMax, new MeanSquaredDisplacmentFeature(t,\n\t\t\t\tlagMin));\n\t}", "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 }", "private static String makeAsciiTableCell(Object obj, int padLeft, int padRight, boolean tsv) {\r\n String result = obj.toString();\r\n if (padLeft > 0) {\r\n result = padLeft(result, padLeft);\r\n }\r\n if (padRight > 0) {\r\n result = pad(result, padRight);\r\n }\r\n if (tsv) {\r\n result = result + '\\t';\r\n }\r\n return result;\r\n }", "public static <E> String serialize(Map<String, E> map, Class<E> jsonObjectClass) throws IOException {\n return mapperFor(jsonObjectClass).serialize(map);\n }", "public static <E> Set<E> intersection(Set<E> s1, Set<E> s2) {\r\n Set<E> s = new HashSet<E>();\r\n s.addAll(s1);\r\n s.retainAll(s2);\r\n return s;\r\n }", "public void unlock() {\n String queryString = new QueryStringBuilder().appendParam(\"fields\", \"lock\").toString();\n URL url = FILE_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"PUT\");\n\n JsonObject lockObject = new JsonObject();\n lockObject.add(\"lock\", JsonObject.NULL);\n\n request.setBody(lockObject.toString());\n request.send();\n }", "public void sendValue(int nodeId, int endpoint, int value) {\n\t\tZWaveNode node = this.getNode(nodeId);\n\t\tZWaveSetCommands zwaveCommandClass = null;\n\t\tSerialMessage serialMessage = null;\n\t\t\n\t\tfor (ZWaveCommandClass.CommandClass commandClass : new ZWaveCommandClass.CommandClass[] { ZWaveCommandClass.CommandClass.SWITCH_MULTILEVEL, ZWaveCommandClass.CommandClass.SWITCH_BINARY, ZWaveCommandClass.CommandClass.BASIC }) {\n\t\t\tzwaveCommandClass = (ZWaveSetCommands)node.resolveCommandClass(commandClass, endpoint);\n\t\t\tif (zwaveCommandClass != null)\n\t\t\t\tbreak;\n\t\t}\n\t\t\n\t\tif (zwaveCommandClass == null) {\n\t\t\tlogger.error(\"No Command Class found on node {}, instance/endpoint {} to request level.\", nodeId, endpoint);\n\t\t\treturn;\n\t\t}\n\t\t\t \n\t\tserialMessage = node.encapsulate(zwaveCommandClass.setValueMessage(value), (ZWaveCommandClass)zwaveCommandClass, endpoint);\n\t\t\n\t\tif (serialMessage != null)\n\t\t\tthis.sendData(serialMessage);\n\t\t\n\t\t// read back level on \"ON\" command\n\t\tif (((ZWaveCommandClass)zwaveCommandClass).getCommandClass() == ZWaveCommandClass.CommandClass.SWITCH_MULTILEVEL && value == 255)\n\t\t\tthis.requestValue(nodeId, endpoint);\n\t}" ]
Read FTS file data from the configured source and return a populated ProjectFile instance. @return ProjectFile instance
[ "private ProjectFile read() throws Exception\n {\n m_project = new ProjectFile();\n m_eventManager = m_project.getEventManager();\n\n ProjectConfig config = m_project.getProjectConfig();\n config.setAutoCalendarUniqueID(false);\n config.setAutoTaskID(false);\n config.setAutoTaskUniqueID(false);\n config.setAutoResourceUniqueID(false);\n config.setAutoWBS(false);\n config.setAutoOutlineNumber(false);\n\n m_project.getProjectProperties().setFileApplication(\"FastTrack\");\n m_project.getProjectProperties().setFileType(\"FTS\");\n\n m_eventManager.addProjectListeners(m_projectListeners);\n\n // processProject();\n // processCalendars();\n processResources();\n processTasks();\n processDependencies();\n processAssignments();\n\n return m_project;\n }" ]
[ "@Override\n @SuppressLint(\"NewApi\")\n public boolean onTouch(View v, MotionEvent event) {\n if(touchable) {\n\n if (event.getAction() == MotionEvent.ACTION_DOWN) {\n view.setBackgroundColor(colorPressed);\n\n return true;\n }\n\n if (event.getAction() == MotionEvent.ACTION_CANCEL) {\n if (isSelected)\n view.setBackgroundColor(colorSelected);\n else\n view.setBackgroundColor(colorUnpressed);\n\n return true;\n }\n\n\n if (event.getAction() == MotionEvent.ACTION_UP) {\n\n view.setBackgroundColor(colorSelected);\n afterClick();\n\n return true;\n }\n }\n\n return false;\n }", "public void setSizes(Collection<Size> sizes) {\r\n for (Size size : sizes) {\r\n if (size.getLabel() == Size.SMALL) {\r\n smallSize = size;\r\n } else if (size.getLabel() == Size.SQUARE) {\r\n squareSize = size;\r\n } else if (size.getLabel() == Size.THUMB) {\r\n thumbnailSize = size;\r\n } else if (size.getLabel() == Size.MEDIUM) {\r\n mediumSize = size;\r\n } else if (size.getLabel() == Size.LARGE) {\r\n largeSize = size;\r\n } else if (size.getLabel() == Size.LARGE_1600) {\r\n large1600Size = size;\r\n } else if (size.getLabel() == Size.LARGE_2048) {\r\n large2048Size = size;\r\n } else if (size.getLabel() == Size.ORIGINAL) {\r\n originalSize = size;\r\n } else if (size.getLabel() == Size.SQUARE_LARGE) {\r\n squareLargeSize = size;\r\n } else if (size.getLabel() == Size.SMALL_320) {\r\n small320Size = size;\r\n } else if (size.getLabel() == Size.MEDIUM_640) {\r\n medium640Size = size;\r\n } else if (size.getLabel() == Size.MEDIUM_800) {\r\n medium800Size = size;\r\n } else if (size.getLabel() == Size.VIDEO_PLAYER) {\r\n videoPlayer = size;\r\n } else if (size.getLabel() == Size.SITE_MP4) {\r\n siteMP4 = size;\r\n } else if (size.getLabel() == Size.VIDEO_ORIGINAL) {\r\n videoOriginal = size;\r\n }\r\n else if (size.getLabel() == Size.MOBILE_MP4) {\r\n \tmobileMP4 = size;\r\n }\r\n else if (size.getLabel() == Size.HD_MP4) {\r\n \thdMP4 = size;\r\n }\r\n }\r\n }", "private Integer getKeyPartitionId(byte[] key) {\n Integer keyPartitionId = storeInstance.getNodesPartitionIdForKey(nodeId, key);\n\n Utils.notNull(keyPartitionId);\n return keyPartitionId;\n }", "public <T extends Widget & Checkable> List<Integer> getCheckedWidgetIndexes() {\n List<Integer> checked = new ArrayList<>();\n List<Widget> children = getChildren();\n\n final int size = children.size();\n for (int i = 0, j = -1; i < size; ++i) {\n Widget c = children.get(i);\n if (c instanceof Checkable) {\n ++j;\n if (((Checkable) c).isChecked()) {\n checked.add(j);\n }\n }\n }\n\n return checked;\n }", "@SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n public List<HazeltaskTask<G>> shutdownNow() {\n\t return (List<HazeltaskTask<G>>) (List) localExecutorPool.shutdownNow();\n\t}", "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 base_response delete(nitro_service client, String selectorname) throws Exception {\n\t\tcacheselector deleteresource = new cacheselector();\n\t\tdeleteresource.selectorname = selectorname;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public void setPath(int pathId, String path) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + Constants.PATH_PROFILE_ACTUAL_PATH + \" = ? \" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, path);\n statement.setInt(2, pathId);\n statement.executeUpdate();\n statement.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "protected void generateTitleBand() {\n\t\tlog.debug(\"Generating title band...\");\n\t\tJRDesignBand band = (JRDesignBand) getDesign().getPageHeader();\n\t\tint yOffset = 0;\n\n\t\t//If title is not present then subtitle will be ignored\n\t\tif (getReport().getTitle() == null)\n\t\t\treturn;\n\n\t\tif (band != null && !getDesign().isTitleNewPage()){\n\t\t\t//Title and subtitle comes afer the page header\n\t\t\tyOffset = band.getHeight();\n\n\t\t} else {\n\t\t\tband = (JRDesignBand) getDesign().getTitle();\n\t\t\tif (band == null){\n\t\t\t\tband = new JRDesignBand();\n\t\t\t\tgetDesign().setTitle(band);\n\t\t\t}\n\t\t}\n\n\t\tJRDesignExpression printWhenExpression = new JRDesignExpression();\n\t\tprintWhenExpression.setValueClass(Boolean.class);\n\t\tprintWhenExpression.setText(EXPRESSION_TRUE_WHEN_FIRST_PAGE);\n\n\t\tJRDesignTextField title = new JRDesignTextField();\n\t\tJRDesignExpression exp = new JRDesignExpression();\n\t\tif (getReport().isTitleIsJrExpression()){\n\t\t\texp.setText(getReport().getTitle());\n\t\t}else {\n\t\t\texp.setText(\"\\\"\" + Utils.escapeTextForExpression( getReport().getTitle()) + \"\\\"\");\n\t\t}\n\t\texp.setValueClass(String.class);\n\t\ttitle.setExpression(exp);\n\t\ttitle.setWidth(getReport().getOptions().getPrintableWidth());\n\t\ttitle.setHeight(getReport().getOptions().getTitleHeight());\n\t\ttitle.setY(yOffset);\n\t\ttitle.setPrintWhenExpression(printWhenExpression);\n\t\ttitle.setRemoveLineWhenBlank(true);\n\t\tapplyStyleToElement(getReport().getTitleStyle(), title);\n\t\ttitle.setStretchType( StretchTypeEnum.NO_STRETCH );\n\t\tband.addElement(title);\n\n\t\tJRDesignTextField subtitle = new JRDesignTextField();\n\t\tif (getReport().getSubtitle() != null) {\n\t\t\tJRDesignExpression exp2 = new JRDesignExpression();\n\t\t\texp2.setText(\"\\\"\" + getReport().getSubtitle() + \"\\\"\");\n\t\t\texp2.setValueClass(String.class);\n\t\t\tsubtitle.setExpression(exp2);\n\t\t\tsubtitle.setWidth(getReport().getOptions().getPrintableWidth());\n\t\t\tsubtitle.setHeight(getReport().getOptions().getSubtitleHeight());\n\t\t\tsubtitle.setY(title.getY() + title.getHeight());\n\t\t\tsubtitle.setPrintWhenExpression(printWhenExpression);\n\t\t\tsubtitle.setRemoveLineWhenBlank(true);\n\t\t\tapplyStyleToElement(getReport().getSubtitleStyle(), subtitle);\n\t\t\ttitle.setStretchType( StretchTypeEnum.NO_STRETCH );\n\t\t\tband.addElement(subtitle);\n\t\t}\n\n\n\t}" ]
Convert a collection of objects to a JSON array with the string representations of that objects. @param collection the collection of objects. @return the JSON array with the string representations.
[ "private JSONArray toJsonStringArray(Collection<? extends Object> collection) {\n\n if (null != collection) {\n JSONArray array = new JSONArray();\n for (Object o : collection) {\n array.put(\"\" + o);\n }\n return array;\n } else {\n return null;\n }\n }" ]
[ "public IPv4AddressSection mask(IPv4AddressSection mask, boolean retainPrefix) throws IncompatibleAddressException, PrefixLenException, SizeMismatchException {\n\t\tcheckMaskSectionCount(mask);\n\t\treturn getSubnetSegments(\n\t\t\t\tthis,\n\t\t\t\tretainPrefix ? getPrefixLength() : null,\n\t\t\t\tgetAddressCreator(),\n\t\t\t\ttrue,\n\t\t\t\tthis::getSegment,\n\t\t\t\ti -> mask.getSegment(i).getSegmentValue(),\n\t\t\t\tfalse);\n\t}", "public static <T> List<T> asImmutable(List<? extends T> self) {\n return Collections.unmodifiableList(self);\n }", "public String getModuleJenkinsJobInfo(final DbArtifact dbArtifact) {\n\t\tfinal DbModule module = getModule(dbArtifact);\n\t\tif(module == null){\n\t\t\treturn \"\";\n\t\t}\n\t\t\n\t\tfinal String jenkinsJobUrl = module.getBuildInfo().get(\"jenkins-job-url\");\n\t\t\n\t\tif(jenkinsJobUrl == null){\n\t\t\treturn \"\";\t\t\t\n\t\t}\n\n\t\treturn jenkinsJobUrl;\n\t}", "static GVRCollider lookup(long nativePointer)\n {\n synchronized (sColliders)\n {\n WeakReference<GVRCollider> weakReference = sColliders.get(nativePointer);\n return weakReference == null ? null : weakReference.get();\n }\n }", "private String buildAliasKey(String aPath, List hintClasses)\r\n {\r\n if (hintClasses == null || hintClasses.isEmpty())\r\n {\r\n return aPath;\r\n }\r\n \r\n StringBuffer buf = new StringBuffer(aPath);\r\n for (Iterator iter = hintClasses.iterator(); iter.hasNext();)\r\n {\r\n Class hint = (Class) iter.next();\r\n buf.append(\" \");\r\n buf.append(hint.getName());\r\n }\r\n return buf.toString();\r\n }", "public static authorizationpolicylabel_binding get(nitro_service service, String labelname) throws Exception{\n\t\tauthorizationpolicylabel_binding obj = new authorizationpolicylabel_binding();\n\t\tobj.set_labelname(labelname);\n\t\tauthorizationpolicylabel_binding response = (authorizationpolicylabel_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "protected int getRequestTypeFromString(String requestType) {\n if (\"GET\".equals(requestType)) {\n return REQUEST_TYPE_GET;\n }\n if (\"POST\".equals(requestType)) {\n return REQUEST_TYPE_POST;\n }\n if (\"PUT\".equals(requestType)) {\n return REQUEST_TYPE_PUT;\n }\n if (\"DELETE\".equals(requestType)) {\n return REQUEST_TYPE_DELETE;\n }\n return REQUEST_TYPE_ALL;\n }", "public void set(float val, Layout.Axis axis) {\n switch (axis) {\n case X:\n x = val;\n break;\n case Y:\n y = val;\n break;\n case Z:\n z = val;\n break;\n default:\n throw new RuntimeAssertion(\"Bad axis specified: %s\", axis);\n }\n }", "public synchronized void resumeControlPoint(final String entryPoint) {\n for (ControlPoint ep : entryPoints.values()) {\n if (ep.getEntryPoint().equals(entryPoint)) {\n ep.resume();\n }\n }\n }" ]
Finds out which dump files of the given type have been downloaded already. The result is a list of objects that describe the available dump files, in descending order by their date. Not all of the dumps included might be actually available. @param dumpContentType the type of dump to consider @return list of objects that provide information on available dumps
[ "List<MwDumpFile> findDumpsLocally(DumpContentType dumpContentType) {\n\n\t\tString directoryPattern = WmfDumpFile.getDumpFileDirectoryName(\n\t\t\t\tdumpContentType, \"*\");\n\n\t\tList<String> dumpFileDirectories;\n\t\ttry {\n\t\t\tdumpFileDirectories = this.dumpfileDirectoryManager\n\t\t\t\t\t.getSubdirectories(directoryPattern);\n\t\t} catch (IOException e) {\n\t\t\tlogger.error(\"Unable to access dump directory: \" + e.toString());\n\t\t\treturn Collections.emptyList();\n\t\t}\n\n\t\tList<MwDumpFile> result = new ArrayList<>();\n\n\t\tfor (String directory : dumpFileDirectories) {\n\t\t\tString dateStamp = WmfDumpFile\n\t\t\t\t\t.getDateStampFromDumpFileDirectoryName(dumpContentType,\n\t\t\t\t\t\t\tdirectory);\n\t\t\tif (dateStamp.matches(WmfDumpFileManager.DATE_STAMP_PATTERN)) {\n\t\t\t\tWmfLocalDumpFile dumpFile = new WmfLocalDumpFile(dateStamp,\n\t\t\t\t\t\tthis.projectName, dumpfileDirectoryManager,\n\t\t\t\t\t\tdumpContentType);\n\t\t\t\tif (dumpFile.isAvailable()) {\n\t\t\t\t\tresult.add(dumpFile);\n\t\t\t\t} else {\n\t\t\t\t\tlogger.error(\"Incomplete local dump file data. Maybe delete \"\n\t\t\t\t\t\t\t+ dumpFile.getDumpfileDirectory()\n\t\t\t\t\t\t\t+ \" to attempt fresh download.\");\n\t\t\t\t}\n\t\t\t} // else: silently ignore directories that don't match\n\t\t}\n\n\t\tresult.sort(Collections.reverseOrder(new MwDumpFile.DateComparator()));\n\n\t\tlogger.info(\"Found \" + result.size() + \" local dumps of type \"\n\t\t\t\t+ dumpContentType + \": \" + result);\n\n\t\treturn result;\n\t}" ]
[ "public static boolean isFileExist(String filePath) {\n\n File f = new File(filePath);\n\n return f.exists() && !f.isDirectory();\n }", "public static dnstxtrec[] get(nitro_service service) throws Exception{\n\t\tdnstxtrec obj = new dnstxtrec();\n\t\tdnstxtrec[] response = (dnstxtrec[])obj.get_resources(service);\n\t\treturn response;\n\t}", "Path resolveBaseDir(final String name, final String dirName) {\n final String currentDir = SecurityActions.getPropertyPrivileged(name);\n if (currentDir == null) {\n return jbossHomeDir.resolve(dirName);\n }\n return Paths.get(currentDir);\n }", "private void addDirectSubTypes(XClass type, ArrayList subTypes)\r\n {\r\n if (type.isInterface())\r\n {\r\n if (type.getExtendingInterfaces() != null)\r\n {\r\n subTypes.addAll(type.getExtendingInterfaces());\r\n }\r\n // we have to traverse the implementing classes as these array contains all classes that\r\n // implement the interface, not only those who have an \"implement\" declaration\r\n // note that for whatever reason the declared interfaces are not exported via the XClass interface\r\n // so we have to get them via the underlying class which is hopefully a subclass of AbstractClass\r\n if (type.getImplementingClasses() != null)\r\n {\r\n Collection declaredInterfaces = null;\r\n XClass subType;\r\n\r\n for (Iterator it = type.getImplementingClasses().iterator(); it.hasNext(); )\r\n {\r\n subType = (XClass)it.next();\r\n if (subType instanceof AbstractClass)\r\n {\r\n declaredInterfaces = ((AbstractClass)subType).getDeclaredInterfaces();\r\n if ((declaredInterfaces != null) && declaredInterfaces.contains(type))\r\n {\r\n subTypes.add(subType);\r\n }\r\n }\r\n else\r\n {\r\n // Otherwise we have to live with the bug\r\n subTypes.add(subType);\r\n }\r\n }\r\n }\r\n }\r\n else\r\n {\r\n subTypes.addAll(type.getDirectSubclasses());\r\n }\r\n }", "public static base_responses add(nitro_service client, sslcipher resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslcipher addresources[] = new sslcipher[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new sslcipher();\n\t\t\t\taddresources[i].ciphergroupname = resources[i].ciphergroupname;\n\t\t\t\taddresources[i].ciphgrpalias = resources[i].ciphgrpalias;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public static int findVerticalOffset(JRDesignBand band) {\n\t\tint finalHeight = 0;\n\t\tif (band != null) {\n\t\t\tfor (JRChild jrChild : band.getChildren()) {\n\t\t\t\tJRDesignElement element = (JRDesignElement) jrChild;\n\t\t\t\tint currentHeight = element.getY() + element.getHeight();\n\t\t\t\tif (currentHeight > finalHeight) finalHeight = currentHeight;\n\t\t\t}\n\t\t\treturn finalHeight;\n\t\t}\n\t\treturn finalHeight;\n\t}", "public static Observable<Void> mapToVoid(Observable<?> fromObservable) {\n if (fromObservable != null) {\n return fromObservable.subscribeOn(Schedulers.io())\n .map(new RXMapper<Void>());\n } else {\n return Observable.empty();\n }\n }", "public 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 }", "final void waitForSizeQueue(final int queueSize) {\n synchronized (this.queue) {\n while (this.queue.size() > queueSize) {\n try {\n this.queue.wait(250L);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n }\n try {\n Thread.sleep(500L);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n this.queue.notifyAll();\n }\n }" ]
Creates a new connection from the data source that the connection descriptor represents. If the connection descriptor does not directly contain the data source then a JNDI lookup is performed to retrieve the data source. @param jcd The connection descriptor @return A connection instance @throws LookupException if we can't get a connection from the datasource either due to a naming exception, a failed sanity check, or a SQLException.
[ "protected Connection newConnectionFromDataSource(JdbcConnectionDescriptor jcd)\r\n throws LookupException\r\n {\r\n Connection retval = null;\r\n // use JNDI lookup\r\n DataSource ds = jcd.getDataSource();\r\n\r\n if (ds == null)\r\n {\r\n // [tomdz] Would it suffice to store the datasources only at the JCDs ?\r\n // Only possible problem would be serialization of the JCD because\r\n // the data source object in the JCD does not 'survive' this\r\n ds = (DataSource) dataSourceCache.get(jcd.getDatasourceName());\r\n }\r\n try\r\n {\r\n if (ds == null)\r\n {\r\n /**\r\n * this synchronization block won't be a big deal as we only look up\r\n * new datasources not found in the map.\r\n */\r\n synchronized (dataSourceCache)\r\n {\r\n InitialContext ic = new InitialContext();\r\n ds = (DataSource) ic.lookup(jcd.getDatasourceName());\r\n /**\r\n * cache the datasource lookup.\r\n */\r\n dataSourceCache.put(jcd.getDatasourceName(), ds);\r\n }\r\n }\r\n if (jcd.getUserName() == null)\r\n {\r\n retval = ds.getConnection();\r\n }\r\n else\r\n {\r\n retval = ds.getConnection(jcd.getUserName(), jcd.getPassWord());\r\n }\r\n }\r\n catch (SQLException sqlEx)\r\n {\r\n log.error(\"SQLException thrown while trying to get Connection from Datasource (\" +\r\n jcd.getDatasourceName() + \")\", sqlEx);\r\n throw new LookupException(\"SQLException thrown while trying to get Connection from Datasource (\" +\r\n jcd.getDatasourceName() + \")\", sqlEx);\r\n }\r\n catch (NamingException namingEx)\r\n {\r\n log.error(\"Naming Exception while looking up DataSource (\" + jcd.getDatasourceName() + \")\", namingEx);\r\n throw new LookupException(\"Naming Exception while looking up DataSource (\" + jcd.getDatasourceName() +\r\n \")\", namingEx);\r\n }\r\n // initialize connection\r\n initializeJdbcConnection(retval, jcd);\r\n if(log.isDebugEnabled()) log.debug(\"Create new connection using DataSource: \"+retval);\r\n return retval;\r\n }" ]
[ "private void revisitMessages(Definitions def) {\n List<RootElement> rootElements = def.getRootElements();\n List<ItemDefinition> toAddDefinitions = new ArrayList<ItemDefinition>();\n for (RootElement root : rootElements) {\n if (root instanceof Message) {\n if (!existsMessageItemDefinition(rootElements,\n root.getId())) {\n ItemDefinition itemdef = Bpmn2Factory.eINSTANCE.createItemDefinition();\n itemdef.setId(root.getId() + \"Type\");\n toAddDefinitions.add(itemdef);\n ((Message) root).setItemRef(itemdef);\n }\n }\n }\n for (ItemDefinition id : toAddDefinitions) {\n def.getRootElements().add(id);\n }\n }", "private static JsonObject getFieldJsonObject(Field field) {\n JsonObject fieldObj = new JsonObject();\n fieldObj.add(\"type\", field.getType());\n fieldObj.add(\"key\", field.getKey());\n fieldObj.add(\"displayName\", field.getDisplayName());\n\n String fieldDesc = field.getDescription();\n if (fieldDesc != null) {\n fieldObj.add(\"description\", field.getDescription());\n }\n\n Boolean fieldIsHidden = field.getIsHidden();\n if (fieldIsHidden != null) {\n fieldObj.add(\"hidden\", field.getIsHidden());\n }\n\n JsonArray array = new JsonArray();\n List<String> options = field.getOptions();\n if (options != null && !options.isEmpty()) {\n for (String option : options) {\n JsonObject optionObj = new JsonObject();\n optionObj.add(\"key\", option);\n\n array.add(optionObj);\n }\n fieldObj.add(\"options\", array);\n }\n\n return fieldObj;\n }", "public PersonTagList<PersonTag> getList(String photoId) throws FlickrException {\r\n\r\n // Delegating this to photos.people.PeopleInterface - Naming standard would be to use PeopleInterface but having 2 the same name can cause issues\r\n com.flickr4java.flickr.photos.people.PeopleInterface pi = new com.flickr4java.flickr.photos.people.PeopleInterface(apiKey, sharedSecret, transportAPI);\r\n return pi.getList(photoId);\r\n }", "public List<Class<?>> scanClasses(Predicate<String> filter)\n {\n List<Class<?>> discoveredClasses = new ArrayList<>(128);\n\n // For each Forge addon...\n for (Addon addon : furnace.getAddonRegistry().getAddons(AddonFilters.allStarted()))\n {\n List<String> discoveredFileNames = filterAddonResources(addon, filter);\n\n // Then try to load the classes.\n for (String discoveredFilename : discoveredFileNames)\n {\n String clsName = PathUtil.classFilePathToClassname(discoveredFilename);\n try\n {\n Class<?> clazz = addon.getClassLoader().loadClass(clsName);\n discoveredClasses.add(clazz);\n }\n catch (ClassNotFoundException ex)\n {\n LOG.log(Level.WARNING, \"Failed to load class for name '\" + clsName + \"':\\n\" + ex.getMessage(), ex);\n }\n }\n }\n return discoveredClasses;\n }", "synchronized void removeEvents(Table table) {\n final String tName = table.getName();\n\n try {\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n db.delete(tName, null, null);\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Error removing all events from table \" + tName + \" Recreating DB\");\n deleteDB();\n } finally {\n dbHelper.close();\n }\n }", "public Stats getPhotoStats(String photoId, Date date) throws FlickrException {\n return getStats(METHOD_GET_PHOTO_STATS, \"photo_id\", photoId, date);\n }", "public TableReader read() throws IOException\n {\n int tableHeader = m_stream.readInt();\n if (tableHeader != 0x39AF547A)\n {\n throw new IllegalArgumentException(\"Unexpected file format\");\n }\n\n int recordCount = m_stream.readInt();\n for (int loop = 0; loop < recordCount; loop++)\n {\n int rowMagicNumber = m_stream.readInt();\n if (rowMagicNumber != rowMagicNumber())\n {\n throw new IllegalArgumentException(\"Unexpected file format\");\n }\n\n // We use a LinkedHashMap to preserve insertion order in iteration\n // Useful when debugging the file format.\n Map<String, Object> map = new LinkedHashMap<String, Object>();\n\n if (hasUUID())\n {\n readUUID(m_stream, map);\n }\n\n readRow(m_stream, map);\n\n SynchroLogger.log(\"READER\", getClass(), map);\n\n m_rows.add(new MapRow(map));\n }\n\n int tableTrailer = m_stream.readInt();\n if (tableTrailer != 0x6F99E416)\n {\n throw new IllegalArgumentException(\"Unexpected file format\");\n }\n\n postTrailer(m_stream);\n\n return this;\n }", "public ProjectCalendar getBaselineCalendar()\n {\n //\n // Attempt to locate the calendar normally used by baselines\n // If this isn't present, fall back to using the default\n // project calendar.\n //\n ProjectCalendar result = getCalendarByName(\"Used for Microsoft Project 98 Baseline Calendar\");\n if (result == null)\n {\n result = getDefaultCalendar();\n }\n return result;\n }", "@Override\n public Object[] getAgentPlans(String agent_name, Connector connector) {\n // Not supported in JADE\n connector.getLogger().warning(\"Non suported method for Jade Platform. There is no plans in Jade platform.\");\n throw new java.lang.UnsupportedOperationException(\"Non suported method for Jade Platform. There is no extra properties.\");\n }" ]
Creates a new ServerDetails object for deployer, this will take URL and name from the oldDeployer ServerDetails
[ "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 }" ]
[ "protected void doSave() {\n\n List<CmsFavoriteEntry> entries = getEntries();\n try {\n m_favDao.saveFavorites(entries);\n } catch (Exception e) {\n CmsErrorDialog.showErrorDialog(e);\n }\n }", "public static String nextWord(String string) {\n int index = 0;\n while (index < string.length() && !Character.isWhitespace(string.charAt(index))) {\n index++;\n }\n return string.substring(0, index);\n }", "public AsciiTable setPaddingLeft(int paddingLeft) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingLeft(paddingLeft);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public static filterglobal_filterpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tfilterglobal_filterpolicy_binding obj = new filterglobal_filterpolicy_binding();\n\t\tfilterglobal_filterpolicy_binding response[] = (filterglobal_filterpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public Rate getRate(int field) throws MPXJException\n {\n Rate result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n try\n {\n String rate = m_fields[field];\n int index = rate.indexOf('/');\n double amount;\n TimeUnit units;\n\n if (index == -1)\n {\n amount = m_formats.getCurrencyFormat().parse(rate).doubleValue();\n units = TimeUnit.HOURS;\n }\n else\n {\n amount = m_formats.getCurrencyFormat().parse(rate.substring(0, index)).doubleValue();\n units = TimeUnitUtility.getInstance(rate.substring(index + 1), m_locale);\n }\n\n result = new Rate(amount, units);\n }\n\n catch (ParseException ex)\n {\n throw new MPXJException(\"Failed to parse rate\", ex);\n }\n }\n else\n {\n result = null;\n }\n\n return (result);\n }", "private EventType createEventType(EventEnumType type) {\n EventType eventType = new EventType();\n eventType.setTimestamp(Converter.convertDate(new Date()));\n eventType.setEventType(type);\n\n OriginatorType origType = new OriginatorType();\n origType.setProcessId(Converter.getPID());\n try {\n InetAddress inetAddress = InetAddress.getLocalHost();\n origType.setIp(inetAddress.getHostAddress());\n origType.setHostname(inetAddress.getHostName());\n } catch (UnknownHostException e) {\n origType.setHostname(\"Unknown hostname\");\n origType.setIp(\"Unknown ip address\");\n }\n eventType.setOriginator(origType);\n\n String path = System.getProperty(\"karaf.home\");\n CustomInfoType ciType = new CustomInfoType();\n CustomInfoType.Item cItem = new CustomInfoType.Item();\n cItem.setKey(\"path\");\n cItem.setValue(path);\n ciType.getItem().add(cItem);\n eventType.setCustomInfo(ciType);\n\n return eventType;\n }", "public static BMatrixRMaj randomBinary(int numRow , int numCol , Random rand ) {\n BMatrixRMaj mat = new BMatrixRMaj(numRow,numCol);\n\n setRandomB(mat, rand);\n\n return mat;\n }", "public static void printToFile(String filename, String message) {\r\n printToFile(new File(filename), message, false);\r\n }", "public static Constructor<?> getConstructor(final Class<?> clazz,\n final Class<?>... argumentTypes) throws NoSuchMethodException {\n try {\n return AccessController\n .doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() {\n public Constructor<?> run()\n throws NoSuchMethodException {\n return clazz.getConstructor(argumentTypes);\n }\n });\n }\n // Unwrap\n catch (final PrivilegedActionException pae) {\n final Throwable t = pae.getCause();\n // Rethrow\n if (t instanceof NoSuchMethodException) {\n throw (NoSuchMethodException) t;\n } else {\n // No other checked Exception thrown by Class.getConstructor\n try {\n throw (RuntimeException) t;\n }\n // Just in case we've really messed up\n catch (final ClassCastException cce) {\n throw new RuntimeException(\n \"Obtained unchecked Exception; this code should never be reached\",\n t);\n }\n }\n }\n }" ]
Creates an internal project and repositories such as a token storage.
[ "public static void initializeInternalProject(CommandExecutor executor) {\n final long creationTimeMillis = System.currentTimeMillis();\n try {\n executor.execute(createProject(creationTimeMillis, Author.SYSTEM, INTERNAL_PROJ))\n .get();\n } catch (Throwable cause) {\n cause = Exceptions.peel(cause);\n if (!(cause instanceof ProjectExistsException)) {\n throw new Error(\"failed to initialize an internal project\", cause);\n }\n }\n // These repositories might be created when creating an internal project, but we try to create them\n // again here in order to make sure them exist because sometimes their names are changed.\n for (final String repo : ImmutableList.of(Project.REPO_META, Project.REPO_DOGMA)) {\n try {\n executor.execute(createRepository(creationTimeMillis, Author.SYSTEM, INTERNAL_PROJ, repo))\n .get();\n } catch (Throwable cause) {\n cause = Exceptions.peel(cause);\n if (!(cause instanceof RepositoryExistsException)) {\n throw new Error(cause);\n }\n }\n }\n }" ]
[ "protected List splitInCriteria(Object attribute, Collection values, boolean negative, int inLimit)\r\n {\r\n List result = new ArrayList();\r\n Collection inCollection = new ArrayList();\r\n\r\n if (values == null || values.isEmpty())\r\n {\r\n // OQL creates empty Criteria for late binding\r\n result.add(buildInCriteria(attribute, negative, values));\r\n }\r\n else\r\n {\r\n Iterator iter = values.iterator();\r\n\r\n while (iter.hasNext())\r\n {\r\n inCollection.add(iter.next());\r\n if (inCollection.size() == inLimit || !iter.hasNext())\r\n {\r\n result.add(buildInCriteria(attribute, negative, inCollection));\r\n inCollection = new ArrayList();\r\n }\r\n }\r\n }\r\n return result;\r\n }", "public static vpnglobal_intranetip_binding[] get(nitro_service service) throws Exception{\n\t\tvpnglobal_intranetip_binding obj = new vpnglobal_intranetip_binding();\n\t\tvpnglobal_intranetip_binding response[] = (vpnglobal_intranetip_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void removeDescriptor(Object validKey)\r\n {\r\n PBKey pbKey;\r\n if (validKey instanceof PBKey)\r\n {\r\n pbKey = (PBKey) validKey;\r\n }\r\n else if (validKey instanceof JdbcConnectionDescriptor)\r\n {\r\n pbKey = ((JdbcConnectionDescriptor) validKey).getPBKey();\r\n }\r\n else\r\n {\r\n throw new MetadataException(\"Could not remove descriptor, given object was no vaild key: \" +\r\n validKey);\r\n }\r\n Object removed = null;\r\n synchronized (jcdMap)\r\n {\r\n removed = jcdMap.remove(pbKey);\r\n jcdAliasToPBKeyMap.remove(pbKey.getAlias());\r\n }\r\n log.info(\"Remove descriptor: \" + removed);\r\n }", "public static Collection<ContentStream> toContentStreams(final String str, final String contentType) {\n\n if (str == null) {\n return null;\n }\n\n ArrayList<ContentStream> streams = new ArrayList<>(1);\n ContentStreamBase ccc = new ContentStreamBase.StringStream(str);\n ccc.setContentType(contentType);\n streams.add(ccc);\n return streams;\n }", "private String getProject(CmsObject cms, CmsFavoriteEntry entry) throws CmsException {\n\n String result = m_projectLabels.get(entry.getProjectId());\n if (result == null) {\n result = cms.readProject(entry.getProjectId()).getName();\n m_projectLabels.put(entry.getProjectId(), result);\n }\n return result;\n }", "public Set<Action.ActionEffect> getActionEffects() {\n switch(getImpact()) {\n case CLASSLOADING:\n case WRITE:\n return WRITES;\n case READ_ONLY:\n return READS;\n default:\n throw new IllegalStateException();\n }\n\n }", "protected Map getAllVariables(){\n try{\n Iterator names = FreeMarkerTL.getEnvironment().getKnownVariableNames().iterator();\n Map vars = new HashMap();\n while (names.hasNext()) {\n Object name =names.next();\n vars.put(name, get(name.toString()));\n }\n return vars;\n }catch(Exception e){\n throw new ViewException(e);\n }\n }", "public static <X, T> ProducerField<X, T> of(BeanAttributes<T> attributes, EnhancedAnnotatedField<T, ? super X> field, AbstractClassBean<X> declaringBean, DisposalMethod<X, ?> disposalMethod, BeanManagerImpl beanManager, ServiceRegistry services) {\n return new ProducerField<X, T>(attributes, field, declaringBean, disposalMethod, beanManager, services);\n }", "private void addArrayMethods(List<MethodNode> methods, ClassNode receiver, String name, ClassNode[] args) {\n if (args.length!=1) return;\n if (!receiver.isArray()) return;\n if (!isIntCategory(getUnwrapper(args[0]))) return;\n if (\"getAt\".equals(name)) {\n MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC, receiver.getComponentType(), new Parameter[]{new Parameter(args[0],\"arg\")}, null, null);\n node.setDeclaringClass(receiver.redirect());\n methods.add(node);\n } else if (\"setAt\".equals(name)) {\n MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC, VOID_TYPE, new Parameter[]{new Parameter(args[0],\"arg\")}, null, null);\n node.setDeclaringClass(receiver.redirect());\n methods.add(node);\n }\n }" ]
Load a properties file from a file path @param gradlePropertiesFilePath The file path where the gradle.properties is located. @return The loaded properties. @throws IOException In case an error occurs while reading the properties file, this exception is thrown.
[ "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 }" ]
[ "private String buildAliasKey(String aPath, List hintClasses)\r\n {\r\n if (hintClasses == null || hintClasses.isEmpty())\r\n {\r\n return aPath;\r\n }\r\n \r\n StringBuffer buf = new StringBuffer(aPath);\r\n for (Iterator iter = hintClasses.iterator(); iter.hasNext();)\r\n {\r\n Class hint = (Class) iter.next();\r\n buf.append(\" \");\r\n buf.append(hint.getName());\r\n }\r\n return buf.toString();\r\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 registerComponent(java.awt.Component c)\r\n {\r\n unregisterComponent(c);\r\n if (recognizerAbstractClass == null)\r\n {\r\n hmDragGestureRecognizers.put(c, \r\n dragSource.createDefaultDragGestureRecognizer(c, \r\n dragWorker.getAcceptableActions(c), dgListener)\r\n );\r\n }\r\n else\r\n {\r\n hmDragGestureRecognizers.put(c, \r\n dragSource.createDragGestureRecognizer (recognizerAbstractClass,\r\n c, dragWorker.getAcceptableActions(c), dgListener)\r\n );\r\n }\r\n }", "public static Cluster vacateZone(Cluster currentCluster, int dropZoneId) {\n Cluster returnCluster = Cluster.cloneCluster(currentCluster);\n // Go over each node in the zone being dropped\n for(Integer nodeId: currentCluster.getNodeIdsInZone(dropZoneId)) {\n // For each node grab all the partitions it hosts\n for(Integer partitionId: currentCluster.getNodeById(nodeId).getPartitionIds()) {\n // Now for each partition find a new home..which would be a node\n // in one of the existing zones\n int finalZoneId = -1;\n int finalNodeId = -1;\n int adjacentPartitionId = partitionId;\n do {\n adjacentPartitionId = (adjacentPartitionId + 1)\n % currentCluster.getNumberOfPartitions();\n finalNodeId = currentCluster.getNodeForPartitionId(adjacentPartitionId).getId();\n finalZoneId = currentCluster.getZoneForPartitionId(adjacentPartitionId).getId();\n if(adjacentPartitionId == partitionId) {\n logger.error(\"PartitionId \" + partitionId + \"stays unchanged \\n\");\n } else {\n logger.info(\"PartitionId \" + partitionId\n + \" goes together with partition \" + adjacentPartitionId\n + \" on node \" + finalNodeId + \" in zone \" + finalZoneId);\n returnCluster = UpdateClusterUtils.createUpdatedCluster(returnCluster,\n finalNodeId,\n Lists.newArrayList(partitionId));\n }\n } while(finalZoneId == dropZoneId);\n }\n }\n return returnCluster;\n }", "@Override\n public final Double optDouble(final String key) {\n double result = this.obj.optDouble(key, Double.NaN);\n if (Double.isNaN(result)) {\n return null;\n }\n return result;\n }", "public ClassNode annotatedWith(String name) {\n ClassNode anno = infoBase.node(name);\n this.annotations.add(anno);\n anno.annotated.add(this);\n return this;\n }", "@Override\n public boolean setA(DMatrixRBlock A) {\n if( A.numRows < A.numCols )\n throw new IllegalArgumentException(\"Number of rows must be more than or equal to the number of columns. \" +\n \"Can't solve an underdetermined system.\");\n\n if( !decomposer.decompose(A))\n return false;\n\n this.QR = decomposer.getQR();\n\n return true;\n }", "public static CmsUUID readId(JSONObject obj, String key) {\n\n String strValue = obj.optString(key);\n if (!CmsUUID.isValidUUID(strValue)) {\n return null;\n }\n return new CmsUUID(strValue);\n }", "@Override\n public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {\n final ServletRequest r1 = request;\n chain.doFilter(request, new HttpServletResponseWrapper((HttpServletResponse) response) {\n @SuppressWarnings(\"unchecked\")\n public void setHeader(String name, String value) {\n ArrayList<String> headersToRemove = new ArrayList<String>();\n \n if (r1.getAttribute(\"com.groupon.odo.removeHeaders\") != null)\n headersToRemove = (ArrayList<String>) r1.getAttribute(\"com.groupon.odo.removeHeaders\");\n\n boolean removeHeader = false;\n // need to loop through removeHeaders to make things case insensitive\n for (String headerToRemove : headersToRemove) {\n if (headerToRemove.toLowerCase().equals(name.toLowerCase())) {\n removeHeader = true;\n break;\n }\n }\n\n if (! removeHeader) {\n super.setHeader(name, value);\n }\n }\n });\n }" ]
Login the user and redirect back to original URL. If no original URL found then redirect to `defaultLandingUrl`. @param userIdentifier the user identifier, could be either userId or username @param defaultLandingUrl the URL to be redirected if original URL not found
[ "public void loginAndRedirectBack(Object userIdentifier, String defaultLandingUrl) {\n login(userIdentifier);\n RedirectToLoginUrl.redirectToOriginalUrl(this, defaultLandingUrl);\n }" ]
[ "public Where<T, ID> ge(String columnName, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,\n\t\t\t\tSimpleComparison.GREATER_THAN_EQUAL_TO_OPERATION));\n\t\treturn this;\n\t}", "static ChangeEvent<BsonDocument> changeEventForLocalUpdate(\n final MongoNamespace namespace,\n final BsonValue documentId,\n final UpdateDescription update,\n final BsonDocument fullDocumentAfterUpdate,\n final boolean writePending\n ) {\n return new ChangeEvent<>(\n new BsonDocument(),\n OperationType.UPDATE,\n fullDocumentAfterUpdate,\n namespace,\n new BsonDocument(\"_id\", documentId),\n update,\n writePending);\n }", "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 void evictCache(String key) {\n H.Session sess = session();\n if (null != sess) {\n sess.evict(key);\n } else {\n app().cache().evict(key);\n }\n }", "public 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 JSONObject exportConfigurationAndProfile(String oldExport) {\n try {\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"oldExport\", oldExport)\n };\n String url = BASE_BACKUP_PROFILE + \"/\" + uriEncode(this._profileName) + \"/\" + this._clientId;\n return new JSONObject(doGet(url, new BasicNameValuePair[]{}));\n } catch (Exception e) {\n return new JSONObject();\n }\n }", "static boolean matchPath(String[] tokenizedPattern, String[] strDirs, boolean isCaseSensitive) {\n int patIdxStart = 0;\n int patIdxEnd = tokenizedPattern.length - 1;\n int strIdxStart = 0;\n int strIdxEnd = strDirs.length - 1;\n\n // up to first '**'\n while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) {\n String patDir = tokenizedPattern[patIdxStart];\n if (patDir.equals(DEEP_TREE_MATCH)) {\n break;\n }\n if (!match(patDir, strDirs[strIdxStart], isCaseSensitive)) {\n return false;\n }\n patIdxStart++;\n strIdxStart++;\n }\n if (strIdxStart > strIdxEnd) {\n // String is exhausted\n for (int i = patIdxStart; i <= patIdxEnd; i++) {\n if (!tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {\n return false;\n }\n }\n return true;\n } else {\n if (patIdxStart > patIdxEnd) {\n // String not exhausted, but pattern is. Failure.\n return false;\n }\n }\n\n // up to last '**'\n while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) {\n String patDir = tokenizedPattern[patIdxEnd];\n if (patDir.equals(DEEP_TREE_MATCH)) {\n break;\n }\n if (!match(patDir, strDirs[strIdxEnd], isCaseSensitive)) {\n return false;\n }\n patIdxEnd--;\n strIdxEnd--;\n }\n if (strIdxStart > strIdxEnd) {\n // String is exhausted\n for (int i = patIdxStart; i <= patIdxEnd; i++) {\n if (!tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {\n return false;\n }\n }\n return true;\n }\n\n while (patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd) {\n int patIdxTmp = -1;\n for (int i = patIdxStart + 1; i <= patIdxEnd; i++) {\n if (tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {\n patIdxTmp = i;\n break;\n }\n }\n if (patIdxTmp == patIdxStart + 1) {\n // '**/**' situation, so skip one\n patIdxStart++;\n continue;\n }\n // Find the pattern between padIdxStart & padIdxTmp in str between\n // strIdxStart & strIdxEnd\n int patLength = (patIdxTmp - patIdxStart - 1);\n int strLength = (strIdxEnd - strIdxStart + 1);\n int foundIdx = -1;\n strLoop:\n for (int i = 0; i <= strLength - patLength; i++) {\n for (int j = 0; j < patLength; j++) {\n String subPat = tokenizedPattern[patIdxStart + j + 1];\n String subStr = strDirs[strIdxStart + i + j];\n if (!match(subPat, subStr, isCaseSensitive)) {\n continue strLoop;\n }\n }\n\n foundIdx = strIdxStart + i;\n break;\n }\n\n if (foundIdx == -1) {\n return false;\n }\n\n patIdxStart = patIdxTmp;\n strIdxStart = foundIdx + patLength;\n }\n\n for (int i = patIdxStart; i <= patIdxEnd; i++) {\n if (!tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {\n return false;\n }\n }\n\n return true;\n }", "public static DMatrixRMaj wrap(int numRows , int numCols , double []data ) {\n DMatrixRMaj s = new DMatrixRMaj();\n s.data = data;\n s.numRows = numRows;\n s.numCols = numCols;\n\n return s;\n }", "private static OkHttpClient getUnsafeOkHttpClient() {\n try {\n // Create a trust manager that does not validate certificate chains\n final TrustManager[] trustAllCerts = new TrustManager[] {\n new X509TrustManager() {\n @Override\n public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n @Override\n public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n @Override\n public java.security.cert.X509Certificate[] getAcceptedIssuers() {\n return null;\n }\n }\n };\n\n // Install the all-trusting trust manager\n final SSLContext sslContext = SSLContext.getInstance(\"SSL\");\n sslContext.init(null, trustAllCerts, new java.security.SecureRandom());\n // Create an ssl socket factory with our all-trusting manager\n final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();\n\n OkHttpClient okHttpClient = new OkHttpClient();\n okHttpClient.setSslSocketFactory(sslSocketFactory);\n okHttpClient.setHostnameVerifier(new HostnameVerifier() {\n @Override\n public boolean verify(String hostname, SSLSession session) {\n return true;\n }\n });\n\n return okHttpClient;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }" ]
Returns the current definition on the indicated level. @param level The level @return The definition
[ "private DefBase getDefForLevel(String level)\r\n {\r\n if (LEVEL_CLASS.equals(level))\r\n {\r\n return _curClassDef;\r\n }\r\n else if (LEVEL_FIELD.equals(level))\r\n {\r\n return _curFieldDef;\r\n }\r\n else if (LEVEL_REFERENCE.equals(level))\r\n {\r\n return _curReferenceDef;\r\n }\r\n else if (LEVEL_COLLECTION.equals(level))\r\n {\r\n return _curCollectionDef;\r\n }\r\n else if (LEVEL_OBJECT_CACHE.equals(level))\r\n {\r\n return _curObjectCacheDef;\r\n }\r\n else if (LEVEL_INDEX_DESC.equals(level))\r\n {\r\n return _curIndexDescriptorDef;\r\n }\r\n else if (LEVEL_TABLE.equals(level))\r\n {\r\n return _curTableDef;\r\n }\r\n else if (LEVEL_COLUMN.equals(level))\r\n {\r\n return _curColumnDef;\r\n }\r\n else if (LEVEL_FOREIGNKEY.equals(level))\r\n {\r\n return _curForeignkeyDef;\r\n }\r\n else if (LEVEL_INDEX.equals(level))\r\n {\r\n return _curIndexDef;\r\n }\r\n else if (LEVEL_PROCEDURE.equals(level))\r\n {\r\n return _curProcedureDef;\r\n }\r\n else if (LEVEL_PROCEDURE_ARGUMENT.equals(level))\r\n {\r\n return _curProcedureArgumentDef;\r\n }\r\n else\r\n {\r\n return null;\r\n }\r\n }" ]
[ "public final static void appendCode(final StringBuilder out, final String in, final int start, final int end)\n {\n for (int i = start; i < end; i++)\n {\n final char c;\n switch (c = in.charAt(i))\n {\n case '&':\n out.append(\"&amp;\");\n break;\n case '<':\n out.append(\"&lt;\");\n break;\n case '>':\n out.append(\"&gt;\");\n break;\n default:\n out.append(c);\n break;\n }\n }\n }", "public List<EnabledEndpoint> getEnabledEndpoints(int pathId, String clientUUID, String[] filters) throws Exception {\n ArrayList<EnabledEndpoint> enabledOverrides = new ArrayList<EnabledEndpoint>();\n PreparedStatement query = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n query = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \"=?\" +\n \" AND \" + Constants.GENERIC_CLIENT_UUID + \"=?\" +\n \" ORDER BY \" + Constants.ENABLED_OVERRIDES_PRIORITY\n );\n query.setInt(1, pathId);\n query.setString(2, clientUUID);\n results = query.executeQuery();\n\n while (results.next()) {\n EnabledEndpoint endpoint = this.getPartialEnabledEndpointFromResultset(results);\n com.groupon.odo.proxylib.models.Method m = PathOverrideService.getInstance().getMethodForOverrideId(endpoint.getOverrideId());\n\n // this is an errant entry.. perhaps a method got deleted from a plugin\n // we'll also remove it from the endpoint\n if (m == null) {\n PathOverrideService.getInstance().removeOverride(endpoint.getOverrideId());\n continue;\n }\n\n // check filters and see if any match\n boolean addOverride = false;\n if (filters != null) {\n for (String filter : filters) {\n if (m.getMethodType().endsWith(filter)) {\n addOverride = true;\n break;\n }\n }\n } else {\n // if there are no filters then we assume that the requester wants all enabled overrides\n addOverride = true;\n }\n\n if (addOverride) {\n enabledOverrides.add(endpoint);\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n\n // now go through the ArrayList and get the method for all of the endpoints\n // have to do this so we don't have overlapping SQL queries\n ArrayList<EnabledEndpoint> enabledOverridesWithMethods = new ArrayList<EnabledEndpoint>();\n for (EnabledEndpoint endpoint : enabledOverrides) {\n if (endpoint.getOverrideId() >= 0) {\n com.groupon.odo.proxylib.models.Method m = PathOverrideService.getInstance().getMethodForOverrideId(endpoint.getOverrideId());\n endpoint.setMethodInformation(m);\n }\n enabledOverridesWithMethods.add(endpoint);\n }\n\n return enabledOverridesWithMethods;\n }", "private static String preparePlaceHolders(int length) {\n StringBuilder builder = new StringBuilder();\n for (int i = 0; i < length; ) {\n builder.append(\"?\");\n if (++i < length) {\n builder.append(\",\");\n }\n }\n return builder.toString();\n }", "public static base_response update(nitro_service client, snmpuser resource) throws Exception {\n\t\tsnmpuser updateresource = new snmpuser();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.group = resource.group;\n\t\tupdateresource.authtype = resource.authtype;\n\t\tupdateresource.authpasswd = resource.authpasswd;\n\t\tupdateresource.privtype = resource.privtype;\n\t\tupdateresource.privpasswd = resource.privpasswd;\n\t\treturn updateresource.update_resource(client);\n\t}", "public static int longestCommonContiguousSubstring(String s, String t) {\r\n if (s.length() == 0 || t.length() == 0) {\r\n return 0;\r\n }\r\n int M = s.length();\r\n int N = t.length();\r\n int[][] d = new int[M + 1][N + 1];\r\n for (int j = 0; j <= N; j++) {\r\n d[0][j] = 0;\r\n }\r\n for (int i = 0; i <= M; i++) {\r\n d[i][0] = 0;\r\n }\r\n\r\n int max = 0;\r\n for (int i = 1; i <= M; i++) {\r\n for (int j = 1; j <= N; j++) {\r\n if (s.charAt(i - 1) == t.charAt(j - 1)) {\r\n d[i][j] = d[i - 1][j - 1] + 1;\r\n } else {\r\n d[i][j] = 0;\r\n }\r\n\r\n if (d[i][j] > max) {\r\n max = d[i][j];\r\n }\r\n }\r\n }\r\n // System.err.println(\"LCCS(\" + s + \",\" + t + \") = \" + max);\r\n return max;\r\n }", "private static void unpackFace(File outputDirectory) throws IOException {\n ClassLoader loader = AllureMain.class.getClassLoader();\n for (ClassPath.ResourceInfo info : ClassPath.from(loader).getResources()) {\n Matcher matcher = REPORT_RESOURCE_PATTERN.matcher(info.getResourceName());\n if (matcher.find()) {\n String resourcePath = matcher.group(1);\n File dest = new File(outputDirectory, resourcePath);\n Files.createParentDirs(dest);\n try (FileOutputStream output = new FileOutputStream(dest);\n InputStream input = info.url().openStream()) {\n IOUtils.copy(input, output);\n LOGGER.debug(\"{} successfully copied.\", resourcePath);\n }\n }\n }\n }", "private TrackSourceSlot findTrackSourceSlot() {\n TrackSourceSlot result = TRACK_SOURCE_SLOT_MAP.get(packetBytes[41]);\n if (result == null) {\n return TrackSourceSlot.UNKNOWN;\n }\n return result;\n }", "private static String getPath(Service service, Annotation... qualifiers) {\n for (Annotation q : qualifiers) {\n if (q instanceof Scheme) {\n return ((Scheme) q).value();\n }\n }\n\n if (service.getMetadata() != null && service.getMetadata().getAnnotations() != null) {\n String s = service.getMetadata().getAnnotations().get(SERVICE_SCHEME);\n if (s != null && s.isEmpty()) {\n return s;\n }\n }\n return DEFAULT_PATH;\n }", "public <Ex extends Throwable> Try<R,Ex> execute(T input,Class<Ex> classes){\n\t\t\n\t\treturn Try.withCatch( ()->transactionTemplate.execute(status-> transaction.apply(input)),classes);\n\t\t \n\t}" ]
Retrieve the value of a single-valued parameter. @param key @param defaultValue @param cnx
[ "public static String getParameter(DbConn cnx, String key, String defaultValue)\n {\n try\n {\n return cnx.runSelectSingle(\"globalprm_select_by_key\", 3, String.class, key);\n }\n catch (NoResultException e)\n {\n return defaultValue;\n }\n }" ]
[ "public static <E> List<E> listify(ObjectMapper mapper, Object source, Class<E> targetElementType) {\n return (List<E>) collectify(mapper, source, List.class, targetElementType);\n }", "private void writeCalendars() throws JAXBException\n {\n //\n // Create the new Planner calendar list\n //\n Calendars calendars = m_factory.createCalendars();\n m_plannerProject.setCalendars(calendars);\n writeDayTypes(calendars);\n List<net.sf.mpxj.planner.schema.Calendar> calendar = calendars.getCalendar();\n\n //\n // Process each calendar in turn\n //\n for (ProjectCalendar mpxjCalendar : m_projectFile.getCalendars())\n {\n net.sf.mpxj.planner.schema.Calendar plannerCalendar = m_factory.createCalendar();\n calendar.add(plannerCalendar);\n writeCalendar(mpxjCalendar, plannerCalendar);\n }\n }", "public String getTypeDescriptor() {\n if (typeDescriptor == null) {\n StringBuilder buf = new StringBuilder(name.length() + parameters.length * 10);\n buf.append(returnType.getName());\n buf.append(' ');\n buf.append(name);\n buf.append('(');\n for (int i = 0; i < parameters.length; i++) {\n if (i > 0) {\n buf.append(\", \");\n }\n Parameter param = parameters[i];\n buf.append(formatTypeName(param.getType()));\n }\n buf.append(')');\n typeDescriptor = buf.toString();\n }\n return typeDescriptor;\n }", "@SuppressWarnings(\"unchecked\")\n public void put(String key, Versioned<Object> value) {\n // acquire write lock\n writeLock.lock();\n\n try {\n if(this.storeNames.contains(key) || key.equals(STORES_KEY)) {\n\n // Check for backwards compatibility\n List<StoreDefinition> storeDefinitions = (List<StoreDefinition>) value.getValue();\n StoreDefinitionUtils.validateSchemasAsNeeded(storeDefinitions);\n\n // If the put is on the entire stores.xml key, delete the\n // additional stores which do not exist in the specified\n // stores.xml\n Set<String> storeNamesToDelete = new HashSet<String>();\n for(String storeName: this.storeNames) {\n storeNamesToDelete.add(storeName);\n }\n\n // Add / update the list of store definitions specified in the\n // value\n StoreDefinitionsMapper mapper = new StoreDefinitionsMapper();\n\n // Update the STORES directory and the corresponding entry in\n // metadata cache\n Set<String> specifiedStoreNames = new HashSet<String>();\n for(StoreDefinition storeDef: storeDefinitions) {\n specifiedStoreNames.add(storeDef.getName());\n String storeDefStr = mapper.writeStore(storeDef);\n Versioned<String> versionedValueStr = new Versioned<String>(storeDefStr,\n value.getVersion());\n this.storeDefinitionsStorageEngine.put(storeDef.getName(),\n versionedValueStr,\n \"\");\n\n // Update the metadata cache\n this.metadataCache.put(storeDef.getName(),\n new Versioned<Object>(storeDefStr, value.getVersion()));\n }\n\n if(key.equals(STORES_KEY)) {\n storeNamesToDelete.removeAll(specifiedStoreNames);\n resetStoreDefinitions(storeNamesToDelete);\n }\n\n // Re-initialize the store definitions\n initStoreDefinitions(value.getVersion());\n\n // Update routing strategies\n updateRoutingStrategies(getCluster(), getStoreDefList());\n\n } else if(METADATA_KEYS.contains(key)) {\n // try inserting into inner store first\n putInner(key, convertObjectToString(key, value));\n\n // cache all keys if innerStore put succeeded\n metadataCache.put(key, value);\n\n // do special stuff if needed\n if(CLUSTER_KEY.equals(key)) {\n updateRoutingStrategies((Cluster) value.getValue(), getStoreDefList());\n } else if(NODE_ID_KEY.equals(key)) {\n initNodeId(getNodeIdNoLock());\n } else if(SYSTEM_STORES_KEY.equals(key))\n throw new VoldemortException(\"Cannot overwrite system store definitions\");\n\n } else {\n throw new VoldemortException(\"Unhandled Key:\" + key + \" for MetadataStore put()\");\n }\n } finally {\n writeLock.unlock();\n }\n }", "private Optional<? extends SoyMsgBundle> mergeMsgBundles(final Locale locale, final List<SoyMsgBundle> soyMsgBundles) {\n if (soyMsgBundles.isEmpty()) {\n return Optional.absent();\n }\n\n final List<SoyMsg> msgs = Lists.newArrayList();\n for (final SoyMsgBundle smb : soyMsgBundles) {\n for (final Iterator<SoyMsg> it = smb.iterator(); it.hasNext();) {\n msgs.add(it.next());\n }\n }\n\n return Optional.of(new SoyMsgBundleImpl(locale.toString(), msgs));\n }", "public static WebDriverBackedEmbeddedBrowser withRemoteDriver(String hubUrl,\n\t\t\tImmutableSortedSet<String> filterAttributes, long crawlWaitEvent,\n\t\t\tlong crawlWaitReload) {\n\t\treturn WebDriverBackedEmbeddedBrowser.withDriver(buildRemoteWebDriver(hubUrl),\n\t\t\t\tfilterAttributes, crawlWaitEvent,\n\t\t\t\tcrawlWaitReload);\n\t}", "public static void Shuffle(double[] array, long seed) {\n Random random = new Random();\n if (seed != 0) random.setSeed(seed);\n\n for (int i = array.length - 1; i > 0; i--) {\n int index = random.nextInt(i + 1);\n double temp = array[index];\n array[index] = array[i];\n array[i] = temp;\n }\n }", "public static responderparam get(nitro_service service) throws Exception{\n\t\tresponderparam obj = new responderparam();\n\t\tresponderparam[] response = (responderparam[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<AccountingDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<AccountingDate>) super.zonedDateTime(temporal);\n }" ]
Sets the specified double attribute to the specified value. @param name name of the attribute @param value value of the attribute @since 1.9.0
[ "public void setDoubleAttribute(String name, Double value) {\n\t\tensureAttributes();\n\t\tAttribute attribute = new DoubleAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetAllAttributes().put(name, attribute);\n\n\t}" ]
[ "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 }", "protected static void statistics(int from, int to) {\r\n\t// check that primes contain no accidental errors\r\n\tfor (int i=0; i<primeCapacities.length-1; i++) {\r\n\t\tif (primeCapacities[i] >= primeCapacities[i+1]) throw new RuntimeException(\"primes are unsorted or contain duplicates; detected at \"+i+\"@\"+primeCapacities[i]);\r\n\t}\r\n\t\r\n\tdouble accDeviation = 0.0;\r\n\tdouble maxDeviation = - 1.0;\r\n\r\n\tfor (int i=from; i<=to; i++) {\r\n\t\tint primeCapacity = nextPrime(i);\r\n\t\t//System.out.println(primeCapacity);\r\n\t\tdouble deviation = (primeCapacity - i) / (double)i;\r\n\t\t\r\n\t\tif (deviation > maxDeviation) {\r\n\t\t\tmaxDeviation = deviation;\r\n\t\t\tSystem.out.println(\"new maxdev @\"+i+\"@dev=\"+maxDeviation);\r\n\t\t}\r\n\r\n\t\taccDeviation += deviation;\r\n\t}\r\n\tlong width = 1 + (long)to - (long)from;\r\n\t\r\n\tdouble meanDeviation = accDeviation/width;\r\n\tSystem.out.println(\"Statistics for [\"+ from + \",\"+to+\"] are as follows\");\r\n\tSystem.out.println(\"meanDeviation = \"+(float)meanDeviation*100+\" %\");\r\n\tSystem.out.println(\"maxDeviation = \"+(float)maxDeviation*100+\" %\");\r\n}", "public InputStream call(String methodName, MessageLite request) throws DatastoreException {\n logger.fine(\"remote datastore call \" + methodName);\n\n long startTime = System.currentTimeMillis();\n try {\n HttpResponse httpResponse;\n try {\n rpcCount.incrementAndGet();\n ProtoHttpContent payload = new ProtoHttpContent(request);\n HttpRequest httpRequest = client.buildPostRequest(resolveURL(methodName), payload);\n httpRequest.getHeaders().put(API_FORMAT_VERSION_HEADER, API_FORMAT_VERSION);\n // Don't throw an HTTPResponseException on error. It converts the response to a String and\n // throws away the original, whereas we need the raw bytes to parse it as a proto.\n httpRequest.setThrowExceptionOnExecuteError(false);\n // Datastore requests typically time out after 60s; set the read timeout to slightly longer\n // than that by default (can be overridden via the HttpRequestInitializer).\n httpRequest.setReadTimeout(65 * 1000);\n if (initializer != null) {\n initializer.initialize(httpRequest);\n }\n httpResponse = httpRequest.execute();\n if (!httpResponse.isSuccessStatusCode()) {\n try (InputStream content = GzipFixingInputStream.maybeWrap(httpResponse.getContent())) {\n throw makeException(url, methodName, content,\n httpResponse.getContentType(), httpResponse.getContentCharset(), null,\n httpResponse.getStatusCode());\n }\n }\n return GzipFixingInputStream.maybeWrap(httpResponse.getContent());\n } catch (SocketTimeoutException e) {\n throw makeException(url, methodName, Code.DEADLINE_EXCEEDED, \"Deadline exceeded\", e);\n } catch (IOException e) {\n throw makeException(url, methodName, Code.UNAVAILABLE, \"I/O error\", e);\n }\n } finally {\n long elapsedTime = System.currentTimeMillis() - startTime;\n logger.fine(\"remote datastore call \" + methodName + \" took \" + elapsedTime + \" ms\");\n }\n }", "public void deleteMetadata(String templateName, String scope) {\n URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), scope, templateName);\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"DELETE\");\n BoxAPIResponse response = request.send();\n response.disconnect();\n }", "@Value(\"${locator.strategy}\")\n public void setDefaultLocatorSelectionStrategy(String defaultLocatorSelectionStrategy) {\n this.defaultLocatorSelectionStrategy = defaultLocatorSelectionStrategy;\n if (LOG.isLoggable(Level.FINE)) {\n LOG.log(Level.FINE, \"Default strategy \" + defaultLocatorSelectionStrategy\n + \" was set for LocatorClientRegistrar.\");\n }\n }", "private void deliverDatabaseUpdate(SlotReference slot, Database database, boolean available) {\n for (final DatabaseListener listener : getDatabaseListeners()) {\n try {\n if (available) {\n listener.databaseMounted(slot, database);\n } else {\n listener.databaseUnmounted(slot, database);\n }\n } catch (Throwable t) {\n logger.warn(\"Problem delivering rekordbox database availability update to listener\", t);\n }\n }\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 }", "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 }", "@Deprecated\n public FluoConfiguration clearObservers() {\n Iterator<String> iter1 = getKeys(OBSERVER_PREFIX.substring(0, OBSERVER_PREFIX.length() - 1));\n while (iter1.hasNext()) {\n String key = iter1.next();\n clearProperty(key);\n }\n\n return this;\n }" ]