query
stringlengths 7
3.3k
| positive
sequencelengths 1
1
| negative
sequencelengths 9
9
|
---|---|---|
Cosine interpolation.
@param x1 X1 Value.
@param x2 X2 Value.
@param a Value.
@return Value. | [
"private double CosineInterpolate(double x1, double x2, double a) {\n double f = (1 - Math.cos(a * Math.PI)) * 0.5;\n\n return x1 * (1 - f) + x2 * f;\n }"
] | [
"public void updateIteratorPosition(int length) {\n if(length > 0) {\n //make sure we dont go OB\n if((length + character) > parsedLine.line().length())\n length = parsedLine.line().length() - character;\n\n //move word counter to the correct word\n while(hasNextWord() &&\n (length + character) >= parsedLine.words().get(word).lineIndex() +\n parsedLine.words().get(word).word().length())\n word++;\n\n character = length + character;\n }\n else\n throw new IllegalArgumentException(\"The length given must be > 0 and not exceed the boundary of the line (including the current position)\");\n }",
"private void handleContentLength(Event event) {\n if (event.getContent() == null) {\n return;\n }\n\n if (maxContentLength == -1 || event.getContent().length() <= maxContentLength) {\n return;\n }\n\n if (maxContentLength < CUT_START_TAG.length() + CUT_END_TAG.length()) {\n event.setContent(\"\");\n event.setContentCut(true);\n return;\n }\n\n int contentLength = maxContentLength - CUT_START_TAG.length() - CUT_END_TAG.length();\n event.setContent(CUT_START_TAG + event.getContent().substring(0, contentLength) + CUT_END_TAG);\n event.setContentCut(true);\n }",
"public void editPhotos(String photosetId, String primaryPhotoId, String[] photoIds) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT_PHOTOS);\r\n\r\n parameters.put(\"photoset_id\", photosetId);\r\n parameters.put(\"primary_photo_id\", primaryPhotoId);\r\n parameters.put(\"photo_ids\", StringUtilities.join(photoIds, \",\"));\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"public T addFile(final String name, final List<String> path, final byte[] newHash, final boolean isDirectory) {\n return addFile(name, path, newHash, isDirectory, null);\n }",
"public static int rank( DMatrixRMaj A ) {\n SingularValueDecomposition_F64<DMatrixRMaj> svd = DecompositionFactory_DDRM.svd(A.numRows,A.numCols,false,true,true);\n\n if( svd.inputModified() ) {\n A = A.copy();\n }\n if( !svd.decompose(A)) {\n throw new RuntimeException(\"SVD Failed!\");\n }\n\n int N = svd.numberOfSingularValues();\n double sv[] = svd.getSingularValues();\n\n double threshold = singularThreshold(sv,N);\n int count = 0;\n for (int i = 0; i < sv.length; i++) {\n if( sv[i] >= threshold ) {\n count++;\n }\n }\n return count;\n }",
"public static URL classFileUrl(Class<?> clazz) throws IOException {\n ClassLoader cl = clazz.getClassLoader();\n if (cl == null) {\n cl = ClassLoader.getSystemClassLoader();\n }\n URL res = cl.getResource(clazz.getName().replace('.', '/') + \".class\");\n if (res == null) {\n throw new IllegalArgumentException(\"Unable to locate class file for \" + clazz);\n }\n return res;\n }",
"public static boolean any(Object self, Closure closure) {\n BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);\n for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {\n if (bcw.call(iter.next())) return true;\n }\n return false;\n }",
"@Override\r\n\tpublic String toCompressedString() {\r\n\t\tString result;\r\n\t\tif(hasNoStringCache() || (result = getStringCache().compressedString) == null) {\r\n\t\t\tgetStringCache().compressedString = result = toNormalizedString(MACStringCache.compressedParams);\r\n\t\t}\r\n\t\treturn result;\r\n\t}",
"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 }"
] |
Resizes the array that represents this bit vector.
@param newArraySize
new array size | [
"void resizeArray(int newArraySize) {\n\t\tlong[] newArray = new long[newArraySize];\n\t\tSystem.arraycopy(this.arrayOfBits, 0, newArray, 0,\n\t\t\t\tMath.min(this.arrayOfBits.length, newArraySize));\n\t\tthis.arrayOfBits = newArray;\n\t}"
] | [
"public static Timer getNamedTimer(String timerName, int todoFlags,\n\t\t\tlong threadId) {\n\t\tTimer key = new Timer(timerName, todoFlags, threadId);\n\t\tregisteredTimers.putIfAbsent(key, key);\n\t\treturn registeredTimers.get(key);\n\t}",
"public void setMaintenanceMode(String appName, boolean enable) {\n connection.execute(new AppUpdate(appName, enable), apiKey);\n }",
"public OperationTransformerEntry resolveOperationTransformer(final PathAddress address, final String operationName, PlaceholderResolver placeholderResolver) {\n final Iterator<PathElement> iterator = address.iterator();\n final OperationTransformerEntry entry = resolveOperationTransformer(iterator, operationName, placeholderResolver);\n if(entry != null) {\n return entry;\n }\n // Default is forward unchanged\n return FORWARD;\n }",
"public static wisite_binding get(nitro_service service, String sitepath) throws Exception{\n\t\twisite_binding obj = new wisite_binding();\n\t\tobj.set_sitepath(sitepath);\n\t\twisite_binding response = (wisite_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public String getAlias(String path)\r\n {\r\n if (m_allPathsAliased && m_attributePath.lastIndexOf(path) != -1)\r\n {\r\n return m_name;\r\n }\r\n Object retObj = m_mapping.get(path);\r\n if (retObj != null)\r\n {\r\n return (String) retObj;\r\n }\r\n return null;\r\n }",
"public InsertIntoTable addRowsFromDelimited(File file, String delimiter, Object nullValue) {\n builder.addRowsFromDelimited(file, delimiter, nullValue);\n return this;\n }",
"private List<Long> collectLongMetric(String metricGetterName) {\n List<Long> vals = new ArrayList<Long>();\n for(BdbEnvironmentStats envStats: environmentStatsTracked) {\n vals.add((Long) ReflectUtils.callMethod(envStats,\n BdbEnvironmentStats.class,\n metricGetterName,\n new Class<?>[0],\n new Object[0]));\n }\n return vals;\n }",
"public Collection<Contact> getListRecentlyUploaded(Date lastUpload, String filter) throws FlickrException {\r\n List<Contact> contacts = new ArrayList<Contact>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIST_RECENTLY_UPLOADED);\r\n\r\n if (lastUpload != null) {\r\n parameters.put(\"date_lastupload\", String.valueOf(lastUpload.getTime() / 1000L));\r\n }\r\n if (filter != null) {\r\n parameters.put(\"filter\", filter);\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element contactsElement = response.getPayload();\r\n NodeList contactNodes = contactsElement.getElementsByTagName(\"contact\");\r\n for (int i = 0; i < contactNodes.getLength(); i++) {\r\n Element contactElement = (Element) contactNodes.item(i);\r\n Contact contact = new Contact();\r\n contact.setId(contactElement.getAttribute(\"nsid\"));\r\n contact.setUsername(contactElement.getAttribute(\"username\"));\r\n contact.setRealName(contactElement.getAttribute(\"realname\"));\r\n contact.setFriend(\"1\".equals(contactElement.getAttribute(\"friend\")));\r\n contact.setFamily(\"1\".equals(contactElement.getAttribute(\"family\")));\r\n contact.setIgnored(\"1\".equals(contactElement.getAttribute(\"ignored\")));\r\n contact.setOnline(OnlineStatus.fromType(contactElement.getAttribute(\"online\")));\r\n contact.setIconFarm(contactElement.getAttribute(\"iconfarm\"));\r\n contact.setIconServer(contactElement.getAttribute(\"iconserver\"));\r\n if (contact.getOnline() == OnlineStatus.AWAY) {\r\n contactElement.normalize();\r\n contact.setAwayMessage(XMLUtilities.getValue(contactElement));\r\n }\r\n contacts.add(contact);\r\n }\r\n return contacts;\r\n }",
"static void sendFailedResponse(final ManagementRequestContext<RegistrationContext> context, final byte errorCode, final String message) throws IOException {\n final ManagementResponseHeader header = ManagementResponseHeader.create(context.getRequestHeader());\n final FlushableDataOutput output = context.writeMessage(header);\n try {\n // This is an error\n output.writeByte(DomainControllerProtocol.PARAM_ERROR);\n // send error code\n output.writeByte(errorCode);\n // error message\n if (message == null) {\n output.writeUTF(\"unknown error\");\n } else {\n output.writeUTF(message);\n }\n // response end\n output.writeByte(ManagementProtocol.RESPONSE_END);\n output.close();\n } finally {\n StreamUtils.safeClose(output);\n }\n }"
] |
Moves our current playback position to the specified beat; this will be reflected in any status and beat packets
that we are sending. An incoming value less than one will jump us to the first beat.
@param beat the beat that we should pretend to be playing | [
"public synchronized void jumpToBeat(int beat) {\n\n if (beat < 1) {\n beat = 1;\n } else {\n beat = wrapBeat(beat);\n }\n\n if (playing.get()) {\n metronome.jumpToBeat(beat);\n } else {\n whereStopped.set(metronome.getSnapshot(metronome.getTimeOfBeat(beat)));\n }\n }"
] | [
"public static 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}",
"public void clearTmpData() {\n\t\tfor (Enumeration<?> e = breadthFirstEnumeration(); e.hasMoreElements(); ) {\n\t\t\t((LblTree) e.nextElement()).setTmpData(null);\n\t\t}\n\t}",
"public static dbdbprofile[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tdbdbprofile obj = new dbdbprofile();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tdbdbprofile[] response = (dbdbprofile[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}",
"public ServerSetup[] build(Properties properties) {\n List<ServerSetup> serverSetups = new ArrayList<>();\n\n String hostname = properties.getProperty(\"greenmail.hostname\", ServerSetup.getLocalHostAddress());\n long serverStartupTimeout =\n Long.parseLong(properties.getProperty(\"greenmail.startup.timeout\", \"-1\"));\n\n // Default setups\n addDefaultSetups(hostname, properties, serverSetups);\n\n // Default setups for test\n addTestSetups(hostname, properties, serverSetups);\n\n // Default setups\n for (String protocol : ServerSetup.PROTOCOLS) {\n addSetup(hostname, protocol, properties, serverSetups);\n }\n\n for (ServerSetup setup : serverSetups) {\n if (properties.containsKey(GREENMAIL_VERBOSE)) {\n setup.setVerbose(true);\n }\n if (serverStartupTimeout >= 0L) {\n setup.setServerStartupTimeout(serverStartupTimeout);\n }\n }\n\n return serverSetups.toArray(new ServerSetup[serverSetups.size()]);\n }",
"public void setEnable(boolean flag) {\n if (flag == mIsEnabled)\n return;\n\n mIsEnabled = flag;\n\n if (getNative() != 0)\n {\n NativeComponent.setEnable(getNative(), flag);\n }\n if (flag)\n {\n onEnable();\n }\n else\n {\n onDisable();\n }\n }",
"public void check(ModelDef modelDef, String checkLevel) throws ConstraintException\r\n {\r\n ensureReferencedKeys(modelDef, checkLevel);\r\n checkReferenceForeignkeys(modelDef, checkLevel);\r\n checkCollectionForeignkeys(modelDef, checkLevel);\r\n checkKeyModifications(modelDef, checkLevel);\r\n }",
"public static boolean isExclusivelyKnownArchive(GraphRewrite event, String filePath)\n {\n String extension = StringUtils.substringAfterLast(filePath, \".\");\n\n if (!StringUtils.equalsIgnoreCase(extension, \"jar\"))\n return false;\n\n ZipFile archive;\n try\n {\n archive = new ZipFile(filePath);\n } catch (IOException e)\n {\n return false;\n }\n\n WindupJavaConfigurationService javaConfigurationService = new WindupJavaConfigurationService(event.getGraphContext());\n WindupJavaConfigurationModel javaConfigurationModel = WindupJavaConfigurationService.getJavaConfigurationModel(event.getGraphContext());\n\n // indicates that the user did specify some packages to scan explicitly (as opposed to scanning everything)\n boolean customerPackagesSpecified = javaConfigurationModel.getScanJavaPackages().iterator().hasNext();\n\n // this should only be true if:\n // 1) the package does not contain *any* customer packages.\n // 2) the package contains \"known\" vendor packages.\n boolean exclusivelyKnown = false;\n\n String organization = null;\n Enumeration<?> e = archive.entries();\n\n // go through all entries...\n ZipEntry entry;\n while (e.hasMoreElements())\n {\n entry = (ZipEntry) e.nextElement();\n String entryName = entry.getName();\n\n if (entry.isDirectory() || !StringUtils.endsWith(entryName, \".class\"))\n continue;\n\n String classname = PathUtil.classFilePathToClassname(entryName);\n // if the package isn't current \"known\", try to match against known packages for this entry.\n if (!exclusivelyKnown)\n {\n organization = getOrganizationForPackage(event, classname);\n if (organization != null)\n {\n exclusivelyKnown = true;\n } else\n {\n // we couldn't find a package definitively, so ignore the archive\n exclusivelyKnown = false;\n break;\n }\n }\n\n // If the user specified package names and this is in those package names, then scan it anyway\n if (customerPackagesSpecified && javaConfigurationService.shouldScanPackage(classname))\n {\n return false;\n }\n }\n\n if (exclusivelyKnown)\n LOG.info(\"Known Package: \" + archive.getName() + \"; Organization: \" + organization);\n\n // Return the evaluated exclusively known value.\n return exclusivelyKnown;\n }",
"@SuppressWarnings(\"unchecked\")\n public static void executeCommand(String[] args) throws IOException {\n\n OptionParser parser = getParser();\n\n // declare parameters\n List<String> metaKeys = null;\n String url = null;\n List<Integer> nodeIds = null;\n Boolean allNodes = true;\n List<String> storeNames = null;\n\n // parse command-line input\n args = AdminToolUtils.copyArrayAddFirst(args, \"--\" + OPT_HEAD_META_GET_RO);\n OptionSet options = parser.parse(args);\n if(options.has(AdminParserUtils.OPT_HELP)) {\n printHelp(System.out);\n return;\n }\n\n // check required options and/or conflicting options\n AdminParserUtils.checkRequired(options, OPT_HEAD_META_GET_RO);\n AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);\n AdminParserUtils.checkOptional(options,\n AdminParserUtils.OPT_NODE,\n AdminParserUtils.OPT_ALL_NODES);\n AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_STORE);\n\n // load parameters\n metaKeys = (List<String>) options.valuesOf(OPT_HEAD_META_GET_RO);\n url = (String) options.valueOf(AdminParserUtils.OPT_URL);\n if(options.has(AdminParserUtils.OPT_NODE)) {\n nodeIds = (List<Integer>) options.valuesOf(AdminParserUtils.OPT_NODE);\n allNodes = false;\n }\n storeNames = (List<String>) options.valuesOf(AdminParserUtils.OPT_STORE);\n\n // execute command\n AdminClient adminClient = AdminToolUtils.getAdminClient(url);\n\n if(allNodes) {\n nodeIds = AdminToolUtils.getAllNodeIds(adminClient);\n }\n\n if(metaKeys.size() == 1 && metaKeys.get(0).equals(METAKEY_ALL)) {\n metaKeys = Lists.newArrayList();\n metaKeys.add(KEY_MAX_VERSION);\n metaKeys.add(KEY_CURRENT_VERSION);\n metaKeys.add(KEY_STORAGE_FORMAT);\n }\n\n doMetaGetRO(adminClient, nodeIds, storeNames, metaKeys);\n }",
"public Object getProperty(Object object) {\n MetaMethod getter = getGetter();\n if (getter == null) {\n if (field != null) return field.getProperty(object);\n //TODO: create a WriteOnlyException class?\n throw new GroovyRuntimeException(\"Cannot read write-only property: \" + name);\n }\n return getter.invoke(object, MetaClassHelper.EMPTY_ARRAY);\n }"
] |
Loads a PDF document and creates a DOM tree from it.
@param doc the source document
@return a DOM Document representing the DOM tree
@throws IOException | [
"public Document createDOM(PDDocument doc) throws IOException\n {\n /* We call the original PDFTextStripper.writeText but nothing should\n be printed actually because our processing methods produce no output.\n They create the DOM structures instead */\n super.writeText(doc, new OutputStreamWriter(System.out));\n return this.doc;\n }"
] | [
"private void postTraversalProcessing() {\n\t\tint nc1 = treeSize;\n\t\tinfo[KR] = new int[leafCount];\n\t\tinfo[RKR] = new int[leafCount];\n\n\t\tint lc = leafCount;\n\t\tint i = 0;\n\n\t\t// compute left-most leaf descendants\n\t\t// go along the left-most path, remember each node and assign to it the path's\n\t\t// leaf\n\t\t// compute right-most leaf descendants (in reversed postorder)\n\t\tfor (i = 0; i < treeSize; i++) {\n\t\t\tif (paths[LEFT][i] == -1) {\n\t\t\t\tinfo[POST2_LLD][i] = i;\n\t\t\t} else {\n\t\t\t\tinfo[POST2_LLD][i] = info[POST2_LLD][paths[LEFT][i]];\n\t\t\t}\n\t\t\tif (paths[RIGHT][i] == -1) {\n\t\t\t\tinfo[RPOST2_RLD][treeSize - 1 - info[POST2_PRE][i]] =\n\t\t\t\t\t\t(treeSize - 1 - info[POST2_PRE][i]);\n\t\t\t} else {\n\t\t\t\tinfo[RPOST2_RLD][treeSize - 1 - info[POST2_PRE][i]] =\n\t\t\t\t\t\tinfo[RPOST2_RLD][treeSize - 1\n\t\t\t\t\t\t\t\t- info[POST2_PRE][paths[RIGHT][i]]];\n\t\t\t}\n\t\t}\n\n\t\t// compute key root nodes\n\t\t// compute reversed key root nodes (in revrsed postorder)\n\t\tboolean[] visited = new boolean[nc1];\n\t\tboolean[] visitedR = new boolean[nc1];\n\t\tArrays.fill(visited, false);\n\t\tint k = lc - 1;\n\t\tint kR = lc - 1;\n\t\tfor (i = nc1 - 1; i >= 0; i--) {\n\t\t\tif (!visited[info[POST2_LLD][i]]) {\n\t\t\t\tinfo[KR][k] = i;\n\t\t\t\tvisited[info[POST2_LLD][i]] = true;\n\t\t\t\tk--;\n\t\t\t}\n\t\t\tif (!visitedR[info[RPOST2_RLD][i]]) {\n\t\t\t\tinfo[RKR][kR] = i;\n\t\t\t\tvisitedR[info[RPOST2_RLD][i]] = true;\n\t\t\t\tkR--;\n\t\t\t}\n\t\t}\n\n\t\t// compute minimal key roots for every subtree\n\t\t// compute minimal reversed key roots for every subtree (in reversed postorder)\n\t\tint parent = -1;\n\t\tint parentR = -1;\n\t\tfor (i = 0; i < leafCount; i++) {\n\t\t\tparent = info[KR][i];\n\t\t\twhile (parent > -1 && info[POST2_MIN_KR][parent] == -1) {\n\t\t\t\tinfo[POST2_MIN_KR][parent] = i;\n\t\t\t\tparent = info[POST2_PARENT][parent];\n\t\t\t}\n\t\t\tparentR = info[RKR][i];\n\t\t\twhile (parentR > -1 && info[RPOST2_MIN_RKR][parentR] == -1) {\n\t\t\t\tinfo[RPOST2_MIN_RKR][parentR] = i;\n\t\t\t\tparentR =\n\t\t\t\t\t\tinfo[POST2_PARENT][info[RPOST2_POST][parentR]]; // get parent's postorder\n\t\t\t\tif (parentR > -1) {\n\t\t\t\t\tparentR = treeSize - 1 - info[POST2_PRE][parentR]; // if parent exists get its\n\t\t\t\t\t// rev. postorder\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"public void setEndTime(final Date date) {\r\n\r\n if (!Objects.equals(m_model.getEnd(), date)) {\r\n m_model.setEnd(date);\r\n valueChanged();\r\n }\r\n\r\n }",
"void parseWorkerThreadPool(final XMLExtendedStreamReader reader, final ModelNode subsystemAdd) throws XMLStreamException {\n final int count = reader.getAttributeCount();\n for (int i = 0; i < count; i++) {\n requireNoNamespaceAttribute(reader, i);\n final String value = reader.getAttributeValue(i);\n final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));\n switch (attribute) {\n case WORKER_READ_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_READ_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_READ_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_READ_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_CORE_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_CORE_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_CORE_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_TASK_CORE_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_KEEPALIVE:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_KEEPALIVE)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_KEEPALIVE);\n }\n RemotingSubsystemRootResource.WORKER_TASK_KEEPALIVE.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_LIMIT:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_LIMIT)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_LIMIT);\n }\n RemotingSubsystemRootResource.WORKER_TASK_LIMIT.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_MAX_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_MAX_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_MAX_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_TASK_MAX_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_WRITE_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_WRITE_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_WRITE_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_WRITE_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n default:\n throw unexpectedAttribute(reader, i);\n }\n }\n requireNoContent(reader);\n }",
"public static void main(String[] args) {\r\n //Adding custom equivalence class generation transformer - NOTE this will get applied during graph traversal-->\r\n //MODEL USAGE EXAMPLE: <assign name=\"var_out_V1_2\" expr=\"%ssn\"/> <dg:transform name=\"EQ\"/>\r\n Map<String, DataTransformer> transformers = new HashMap<String, DataTransformer>();\r\n transformers.put(\"EQ\", new EquivalenceClassTransformer());\r\n Vector<CustomTagExtension> cte = new Vector<CustomTagExtension>();\r\n cte.add(new InLineTransformerExtension(transformers));\r\n Engine engine = new SCXMLEngine(cte);\n\r\n //will default to samplemachine, but you could specify a different file if you choose to\r\n InputStream is = CmdLine.class.getResourceAsStream(\"/\" + (args.length == 0 ? \"samplemachine\" : args[0]) + \".xml\");\n\r\n engine.setModelByInputFileStream(is);\n\r\n // Usually, this should be more than the number of threads you intend to run\r\n engine.setBootstrapMin(1);\n\r\n //Prepare the consumer with the proper writer and transformer\r\n DataConsumer consumer = new DataConsumer();\r\n consumer.addDataTransformer(new SampleMachineTransformer());\n\r\n //Adding custom equivalence class generation transformer - NOTE this will get applied post data generation.\r\n //MODEL USAGE EXAMPLE: <dg:assign name=\"var_out_V2\" set=\"%regex([0-9]{3}[A-Z0-9]{5})\"/>\r\n consumer.addDataTransformer(new EquivalenceClassTransformer());\n\r\n consumer.addDataWriter(new DefaultWriter(System.out,\r\n new String[]{\"var_1_1\", \"var_1_2\", \"var_1_3\", \"var_1_4\", \"var_1_5\", \"var_1_6\", \"var_1_7\",\r\n \"var_2_1\", \"var_2_2\", \"var_2_3\", \"var_2_4\", \"var_2_5\", \"var_2_6\", \"var_2_7\", \"var_2_8\"}));\n\r\n //Prepare the distributor\r\n DefaultDistributor defaultDistributor = new DefaultDistributor();\r\n defaultDistributor.setThreadCount(1);\r\n defaultDistributor.setDataConsumer(consumer);\r\n Logger.getLogger(\"org.apache\").setLevel(Level.WARN);\n\r\n engine.process(defaultDistributor);\r\n }",
"public ServerSocket createServerSocket() throws IOException {\n final ServerSocket socket = getServerSocketFactory().createServerSocket(name);\n socket.bind(getSocketAddress());\n return socket;\n }",
"@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 ProductFactoryCascade<T> addFactoryBefore(ProductFactory<? extends T> factory) {\n\t\tArrayList<ProductFactory<? extends T>> factories = new ArrayList<ProductFactory<? extends T>>(this.factories.size()+1);\n\t\tfactories.addAll(this.factories);\n\t\tfactories.add(0, factory);\n\t\treturn new ProductFactoryCascade<>(factories);\n\t}",
"private boolean subModuleExists(File dir) {\n if (isSlotDirectory(dir)) {\n return true;\n } else {\n File[] children = dir.listFiles(File::isDirectory);\n for (File child : children) {\n if (subModuleExists(child)) {\n return true;\n }\n }\n }\n\n return false;\n }",
"public BoxFileUploadSessionPart uploadPart(byte[] data, long offset, int partSize,\n long totalSizeOfFile) {\n URL uploadPartURL = this.sessionInfo.getSessionEndpoints().getUploadPartEndpoint();\n\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), uploadPartURL, HttpMethod.PUT);\n request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_OCTET_STREAM);\n\n MessageDigest digestInstance = null;\n try {\n digestInstance = MessageDigest.getInstance(DIGEST_ALGORITHM_SHA1);\n } catch (NoSuchAlgorithmException ae) {\n throw new BoxAPIException(\"Digest algorithm not found\", ae);\n }\n\n //Creates the digest using SHA1 algorithm. Then encodes the bytes using Base64.\n byte[] digestBytes = digestInstance.digest(data);\n String digest = Base64.encode(digestBytes);\n request.addHeader(HttpHeaders.DIGEST, DIGEST_HEADER_PREFIX_SHA + digest);\n //Content-Range: bytes offset-part/totalSize\n request.addHeader(HttpHeaders.CONTENT_RANGE,\n \"bytes \" + offset + \"-\" + (offset + partSize - 1) + \"/\" + totalSizeOfFile);\n\n //Creates the body\n request.setBody(new ByteArrayInputStream(data));\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n BoxFileUploadSessionPart part = new BoxFileUploadSessionPart((JsonObject) jsonObject.get(\"part\"));\n return part;\n }"
] |
Creates a tag directly from the working copy.
@param tagUrl The URL of the tag to create.
@param commitMessage Commit message
@return The commit info upon successful operation.
@throws IOException On IO of SVN failure | [
"public void createTag(final String tagUrl, final String commitMessage)\n throws IOException, InterruptedException {\n build.getWorkspace()\n .act(new SVNCreateTagCallable(tagUrl, commitMessage, getLocation(), getSvnAuthenticationProvider(build),\n buildListener));\n }"
] | [
"private String toResourceNameOnClasspath(String classPathRootOnDisk, File file) {\n String fileName = file.getAbsolutePath().replace(\"\\\\\", \"/\");\n return fileName.substring(classPathRootOnDisk.length());\n }",
"private void populateAnnotations(Collection<Annotation> annotations) {\n for (Annotation each : annotations) {\n this.annotations.put(each.annotationType(), each);\n }\n }",
"@SuppressWarnings(\"unchecked\")\n private void setProxyRequestHeaders(HttpServletRequest httpServletRequest,\n HttpMethod httpMethodProxyRequest) throws Exception {\n RequestInformation requestInfo = requestInformation.get();\n String hostName = HttpUtilities.getHostNameFromURL(httpServletRequest.getRequestURL().toString());\n // Get an Enumeration of all of the header names sent by the client\n Boolean stripTransferEncoding = false;\n Enumeration<String> enumerationOfHeaderNames = httpServletRequest.getHeaderNames();\n while (enumerationOfHeaderNames.hasMoreElements()) {\n String stringHeaderName = enumerationOfHeaderNames.nextElement();\n if (stringHeaderName.equalsIgnoreCase(STRING_CONTENT_LENGTH_HEADER_NAME)) {\n // don't add this header\n continue;\n }\n\n // The forwarding proxy may supply a POST encoding hint in ODO-POST-TYPE\n if (stringHeaderName.equalsIgnoreCase(\"ODO-POST-TYPE\") &&\n httpServletRequest.getHeader(\"ODO-POST-TYPE\").startsWith(\"content-length:\")) {\n stripTransferEncoding = true;\n }\n\n logger.info(\"Current header: {}\", stringHeaderName);\n // As per the Java Servlet API 2.5 documentation:\n // Some headers, such as Accept-Language can be sent by clients\n // as several headers each with a different value rather than\n // sending the header as a comma separated list.\n // Thus, we get an Enumeration of the header values sent by the\n // client\n Enumeration<String> enumerationOfHeaderValues = httpServletRequest.getHeaders(stringHeaderName);\n\n while (enumerationOfHeaderValues.hasMoreElements()) {\n String stringHeaderValue = enumerationOfHeaderValues.nextElement();\n // In case the proxy host is running multiple virtual servers,\n // rewrite the Host header to ensure that we get content from\n // the correct virtual server\n if (stringHeaderName.equalsIgnoreCase(STRING_HOST_HEADER_NAME) &&\n requestInfo.handle) {\n String hostValue = getHostHeaderForHost(hostName);\n if (hostValue != null) {\n stringHeaderValue = hostValue;\n }\n }\n\n Header header = new Header(stringHeaderName, stringHeaderValue);\n // Set the same header on the proxy request\n httpMethodProxyRequest.addRequestHeader(header);\n }\n }\n\n // this strips transfer encoding headers and adds in the appropriate content-length header\n // based on the hint provided in the ODO-POST-TYPE header(sent from BrowserMobProxyHandler)\n if (stripTransferEncoding) {\n httpMethodProxyRequest.removeRequestHeader(\"transfer-encoding\");\n\n // add content length back in based on the ODO information\n String contentLengthHint = httpServletRequest.getHeader(\"ODO-POST-TYPE\");\n String[] contentLengthParts = contentLengthHint.split(\":\");\n httpMethodProxyRequest.addRequestHeader(\"content-length\", contentLengthParts[1]);\n\n // remove the odo-post-type header\n httpMethodProxyRequest.removeRequestHeader(\"ODO-POST-TYPE\");\n }\n\n // bail if we aren't fully handling this request\n if (!requestInfo.handle) {\n return;\n }\n\n // deal with header overrides for the request\n processRequestHeaderOverrides(httpMethodProxyRequest);\n }",
"public static<T> Vendor<T> vendor(Callable<T> f) {\n\treturn j.vendor(f);\n }",
"public static URL codeLocationFromURL(String url) {\n try {\n return new URL(url);\n } catch (Exception e) {\n throw new InvalidCodeLocation(url);\n }\n }",
"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 }",
"public void setValue(float value) {\n\t\tmBarPointerPosition = Math.round((mSVToPosFactor * (1 - value))\n\t\t\t\t+ mBarPointerHaloRadius + (mBarLength / 2));\n\t\tcalculateColor(mBarPointerPosition);\n\t\tmBarPointerPaint.setColor(mColor);\n\t\t// Check whether the Saturation/Value bar is added to the ColorPicker\n\t\t// wheel\n\t\tif (mPicker != null) {\n\t\t\tmPicker.setNewCenterColor(mColor);\n\t\t\tmPicker.changeOpacityBarColor(mColor);\n\t\t}\n\t\tinvalidate();\n\t}",
"private void checkExtents(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n HashMap processedClasses = new HashMap();\r\n InheritanceHelper helper = new InheritanceHelper();\r\n ClassDescriptorDef curExtent;\r\n boolean canBeRemoved;\r\n\r\n for (Iterator it = classDef.getExtentClasses(); it.hasNext();)\r\n {\r\n curExtent = (ClassDescriptorDef)it.next();\r\n canBeRemoved = false;\r\n if (classDef.getName().equals(curExtent.getName()))\r\n {\r\n throw new ConstraintException(\"The class \"+classDef.getName()+\" specifies itself as an extent-class\");\r\n }\r\n else if (processedClasses.containsKey(curExtent))\r\n {\r\n canBeRemoved = true;\r\n }\r\n else\r\n {\r\n try\r\n {\r\n if (!helper.isSameOrSubTypeOf(curExtent, classDef.getName(), false))\r\n {\r\n throw new ConstraintException(\"The class \"+classDef.getName()+\" specifies an extent-class \"+curExtent.getName()+\" that is not a sub-type of it\");\r\n }\r\n // now we check whether we already have an extent for a base-class of this extent-class\r\n for (Iterator processedIt = processedClasses.keySet().iterator(); processedIt.hasNext();)\r\n {\r\n if (helper.isSameOrSubTypeOf(curExtent, ((ClassDescriptorDef)processedIt.next()).getName(), false))\r\n {\r\n canBeRemoved = true;\r\n break;\r\n }\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n // won't happen because we don't use lookup of the actual classes\r\n }\r\n }\r\n if (canBeRemoved)\r\n {\r\n it.remove();\r\n }\r\n processedClasses.put(curExtent, null);\r\n }\r\n }",
"public static int cudnnPoolingBackward(\n cudnnHandle handle, \n cudnnPoolingDescriptor poolingDesc, \n Pointer alpha, \n cudnnTensorDescriptor yDesc, \n Pointer y, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor dxDesc, \n Pointer dx)\n {\n return checkResult(cudnnPoolingBackwardNative(handle, poolingDesc, alpha, yDesc, y, dyDesc, dy, xDesc, x, beta, dxDesc, dx));\n }"
] |
Returns the 'Up' - vector of the camera coordinate system.
The returned vector is relative to the coordinate space defined by the
corresponding node.<p>
The 'right' vector of the camera coordinate system is the cross product
of the up and lookAt vectors. The default value is 0|1|0. The vector
may be normalized, but it needn't.<p>
This method is part of the wrapped API (see {@link AiWrapperProvider}
for details on wrappers).<p>
The built-in behavior is to return a {@link AiVector}.
@param wrapperProvider the wrapper provider (used for type inference)
@return the 'Up' vector | [
"@SuppressWarnings(\"unchecked\")\n public <V3, M4, C, N, Q> V3 getUp(AiWrapperProvider<V3, M4, C, N, Q> \n wrapperProvider) {\n \n return (V3) m_up;\n }"
] | [
"private static void parseChildShapes(ArrayList<Shape> shapes,\n JSONObject modelJSON,\n Shape current) throws JSONException {\n if (modelJSON.has(\"childShapes\")) {\n ArrayList<Shape> childShapes = new ArrayList<Shape>();\n\n JSONArray childShapeObject = modelJSON.getJSONArray(\"childShapes\");\n for (int i = 0; i < childShapeObject.length(); i++) {\n childShapes.add(getShapeWithId(childShapeObject.getJSONObject(i).getString(\"resourceId\"),\n shapes));\n }\n if (childShapes.size() > 0) {\n for (Shape each : childShapes) {\n each.setParent(current);\n }\n current.setChildShapes(childShapes);\n }\n ;\n }\n }",
"protected static FileWriter createFileWriter(String scenarioName,\n String aux_package_path, String dest_dir) throws BeastException {\n try {\n return new FileWriter(new File(createFolder(aux_package_path,\n dest_dir), scenarioName + \".story\"));\n } catch (IOException e) {\n String message = \"ERROR writing the \" + scenarioName\n + \".story file: \" + e.toString();\n logger.severe(message);\n throw new BeastException(message, e);\n }\n }",
"public static final TimeUnit parseWorkUnits(BigInteger value)\n {\n TimeUnit result = TimeUnit.HOURS;\n\n if (value != null)\n {\n switch (value.intValue())\n {\n case 1:\n {\n result = TimeUnit.MINUTES;\n break;\n }\n\n case 3:\n {\n result = TimeUnit.DAYS;\n break;\n }\n\n case 4:\n {\n result = TimeUnit.WEEKS;\n break;\n }\n\n case 5:\n {\n result = TimeUnit.MONTHS;\n break;\n }\n\n case 7:\n {\n result = TimeUnit.YEARS;\n break;\n }\n\n default:\n case 2:\n {\n result = TimeUnit.HOURS;\n break;\n }\n }\n }\n\n return (result);\n }",
"public String getRejectionLogMessageId() {\n String id = logMessageId;\n if (id == null) {\n id = getRejectionLogMessage(Collections.<String, ModelNode>emptyMap());\n }\n logMessageId = id;\n return logMessageId;\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 }",
"public static String getURL(String sourceURI) {\n String retval = sourceURI;\n int qPos = sourceURI.indexOf(\"?\");\n if (qPos != -1) {\n retval = retval.substring(0, qPos);\n }\n\n return retval;\n }",
"public void rotate(String photoId, int degrees) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ROTATE);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"degrees\", String.valueOf(degrees));\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 addCacheDetailsEntry(SlotReference slot, ZipOutputStream zos, WritableByteChannel channel) throws IOException {\n // Record the details of the media being cached, to make it easier to recognize now that we can.\n MediaDetails details = MetadataFinder.getInstance().getMediaDetailsFor(slot);\n if (details != null) {\n zos.putNextEntry(new ZipEntry(CACHE_DETAILS_ENTRY));\n Util.writeFully(details.getRawBytes(), channel);\n }\n }",
"@RequestMapping(value = \"group\", method = RequestMethod.GET)\n public String newGroupGet(Model model) {\n model.addAttribute(\"groups\",\n pathOverrideService.findAllGroups());\n return \"groups\";\n }"
] |
Gets the string representation of the path to the current JSON element.
@param key the leaf key | [
"public final String getPath(final String key) {\n StringBuilder result = new StringBuilder();\n addPathTo(result);\n result.append(\".\");\n result.append(getPathElement(key));\n return result.toString();\n }"
] | [
"public Task<Void> registerWithEmail(@NonNull final String email, @NonNull final String password) {\n return dispatcher.dispatchTask(\n new Callable<Void>() {\n @Override\n public Void call() {\n registerWithEmailInternal(email, password);\n return null;\n }\n });\n }",
"public BlockHeader read(byte[] buffer, int offset, int postHeaderSkipBytes)\n {\n m_offset = offset;\n\n System.arraycopy(buffer, m_offset, m_header, 0, 8);\n m_offset += 8;\n\n int nameLength = FastTrackUtility.getInt(buffer, m_offset);\n m_offset += 4;\n\n if (nameLength < 1 || nameLength > 255)\n {\n throw new UnexpectedStructureException();\n }\n\n m_name = new String(buffer, m_offset, nameLength, CharsetHelper.UTF16LE);\n m_offset += nameLength;\n\n m_columnType = FastTrackUtility.getShort(buffer, m_offset);\n m_offset += 2;\n\n m_flags = FastTrackUtility.getShort(buffer, m_offset);\n m_offset += 2;\n\n m_skip = new byte[postHeaderSkipBytes];\n System.arraycopy(buffer, m_offset, m_skip, 0, postHeaderSkipBytes);\n m_offset += postHeaderSkipBytes;\n\n return this;\n }",
"public static base_response update(nitro_service client, onlinkipv6prefix resource) throws Exception {\n\t\tonlinkipv6prefix updateresource = new onlinkipv6prefix();\n\t\tupdateresource.ipv6prefix = resource.ipv6prefix;\n\t\tupdateresource.onlinkprefix = resource.onlinkprefix;\n\t\tupdateresource.autonomusprefix = resource.autonomusprefix;\n\t\tupdateresource.depricateprefix = resource.depricateprefix;\n\t\tupdateresource.decrementprefixlifetimes = resource.decrementprefixlifetimes;\n\t\tupdateresource.prefixvalidelifetime = resource.prefixvalidelifetime;\n\t\tupdateresource.prefixpreferredlifetime = resource.prefixpreferredlifetime;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public static vpntrafficpolicy_aaagroup_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpntrafficpolicy_aaagroup_binding obj = new vpntrafficpolicy_aaagroup_binding();\n\t\tobj.set_name(name);\n\t\tvpntrafficpolicy_aaagroup_binding response[] = (vpntrafficpolicy_aaagroup_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void init(Map<String, String> testConfig, Map<String, String> hiveVars) {\n\n context.init();\n\n HiveConf hiveConf = context.getHiveConf();\n\n // merge test case properties with hive conf before HiveServer is started.\n for (Map.Entry<String, String> property : testConfig.entrySet()) {\n hiveConf.set(property.getKey(), property.getValue());\n }\n\n try {\n hiveServer2 = new HiveServer2();\n hiveServer2.init(hiveConf);\n\n // Locate the ClIService in the HiveServer2\n for (Service service : hiveServer2.getServices()) {\n if (service instanceof CLIService) {\n client = (CLIService) service;\n }\n }\n\n Preconditions.checkNotNull(client, \"ClIService was not initialized by HiveServer2\");\n\n sessionHandle = client.openSession(\"noUser\", \"noPassword\", null);\n\n SessionState sessionState = client.getSessionManager().getSession(sessionHandle).getSessionState();\n currentSessionState = sessionState;\n currentSessionState.setHiveVariables(hiveVars);\n } catch (Exception e) {\n throw new IllegalStateException(\"Failed to create HiveServer :\" + e.getMessage(), e);\n }\n\n // Ping hive server before we do anything more with it! If validation\n // is switched on, this will fail if metastorage is not set up properly\n pingHiveServer();\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 }",
"static String from(Class<?> entryClass) {\n List<String> tokens = tokenOf(entryClass);\n return fromTokens(tokens);\n }",
"public static Value.Builder makeValue(Date date) {\n return Value.newBuilder().setTimestampValue(toTimestamp(date.getTime() * 1000L));\n }",
"public static String getModuleName(final String moduleId) {\n final int splitter = moduleId.indexOf(':');\n if(splitter == -1){\n return moduleId;\n }\n return moduleId.substring(0, splitter);\n }"
] |
Delete an object from the database. | [
"public int delete(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException {\n\t\tif (mappedDelete == null) {\n\t\t\tmappedDelete = MappedDelete.build(dao, tableInfo);\n\t\t}\n\t\tint result = mappedDelete.delete(databaseConnection, data, objectCache);\n\t\tif (dao != null && !localIsInBatchMode.get()) {\n\t\t\tdao.notifyChanges();\n\t\t}\n\t\treturn result;\n\t}"
] | [
"public static int skipToNextMatchingShort(byte[] buffer, int offset, int value)\n {\n int nextOffset = offset;\n while (getShort(buffer, nextOffset) != value)\n {\n ++nextOffset;\n }\n nextOffset += 2;\n\n return nextOffset;\n }",
"public Triple<EObject, EReference, INode> decode(Resource res, String uriFragment) {\n\t\tif (isUseIndexFragment(res)) {\n\t\t\treturn getLazyProxyInformation(res, uriFragment);\n\t\t}\n\t\tList<String> split = Strings.split(uriFragment, SEP);\n\t\tEObject source = resolveShortFragment(res, split.get(1));\n\t\tEReference ref = fromShortExternalForm(source.eClass(), split.get(2));\n\t\tINode compositeNode = NodeModelUtils.getNode(source);\n\t\tif (compositeNode==null)\n\t\t\tthrow new IllegalStateException(\"Couldn't resolve lazy link, because no node model is attached.\");\n\t\tINode textNode = getNode(compositeNode, split.get(3));\n\t\treturn Tuples.create(source, ref, textNode);\n\t}",
"public static double StdDev( int[] values, double mean ){\n double stddev = 0;\n double diff;\n int hits;\n int total = 0;\n\n // for all values\n for ( int i = 0, n = values.length; i < n; i++ )\n {\n hits = values[i];\n diff = (double) i - mean;\n // accumulate std.dev.\n stddev += diff * diff * hits;\n // accumalate total\n total += hits;\n }\n\n return ( total == 0 ) ? 0 : Math.sqrt( stddev / (total - 1) );\n }",
"@Override\n public Collection<EnhancedAnnotatedConstructor<T>> getEnhancedConstructors(Class<? extends Annotation> annotationType) {\n Set<EnhancedAnnotatedConstructor<T>> ret = new HashSet<EnhancedAnnotatedConstructor<T>>();\n for (EnhancedAnnotatedConstructor<T> constructor : constructors) {\n if (constructor.isAnnotationPresent(annotationType)) {\n ret.add(constructor);\n }\n }\n return ret;\n }",
"private void setTableAliasForClassDescriptor(ClassDescriptor aCld, TableAlias anAlias)\r\n {\r\n if (m_cldToAlias.get(aCld) == null)\r\n {\r\n m_cldToAlias.put(aCld, anAlias);\r\n } \r\n }",
"public static BufferedImage convertImageToARGB( Image image ) {\n\t\tif ( image instanceof BufferedImage && ((BufferedImage)image).getType() == BufferedImage.TYPE_INT_ARGB )\n\t\t\treturn (BufferedImage)image;\n\t\tBufferedImage p = new BufferedImage( image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);\n\t\tGraphics2D g = p.createGraphics();\n\t\tg.drawImage( image, 0, 0, null );\n\t\tg.dispose();\n\t\treturn p;\n\t}",
"private ArrayList handleDependentCollections(Identity oid, Object obj,\r\n Object[] origCollections, Object[] newCollections,\r\n Object[] newCollectionsOfObjects)\r\n throws LockingException\r\n {\r\n ClassDescriptor mif = _pb.getClassDescriptor(obj.getClass());\r\n Collection colDescs = mif.getCollectionDescriptors();\r\n ArrayList newObjects = new ArrayList();\r\n int count = 0;\r\n\r\n for (Iterator it = colDescs.iterator(); it.hasNext(); count++)\r\n {\r\n CollectionDescriptor cds = (CollectionDescriptor) it.next();\r\n\r\n if (cds.getOtmDependent())\r\n {\r\n ArrayList origList = (origCollections == null ? null\r\n : (ArrayList) origCollections[count]);\r\n ArrayList newList = (ArrayList) newCollections[count];\r\n\r\n if (origList != null)\r\n {\r\n for (Iterator it2 = origList.iterator(); it2.hasNext(); )\r\n {\r\n Identity origOid = (Identity) it2.next();\r\n\r\n if ((newList == null) || !newList.contains(origOid))\r\n {\r\n markDelete(origOid, oid, true);\r\n }\r\n }\r\n }\r\n\r\n if (newList != null)\r\n {\r\n int countElem = 0;\r\n for (Iterator it2 = newList.iterator(); it2.hasNext(); countElem++)\r\n {\r\n Identity newOid = (Identity) it2.next();\r\n\r\n if ((origList == null) || !origList.contains(newOid))\r\n {\r\n ContextEntry entry = (ContextEntry) _objects.get(newOid);\r\n\r\n if (entry == null)\r\n {\r\n ArrayList relCol = (ArrayList)\r\n newCollectionsOfObjects[count];\r\n Object relObj = relCol.get(countElem);\r\n insertInternal(newOid, relObj, LockType.WRITE_LOCK,\r\n true, null, new Stack());\r\n newObjects.add(newOid);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n return newObjects;\r\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 boolean isWellKnownIPv4Translatable() { //rfc 6052 rfc 6144\n\t\t//64:ff9b::/96 prefix for auto ipv4/ipv6 translation\n\t\tif(getSegment(0).matches(0x64) && getSegment(1).matches(0xff9b)) {\n\t\t\tfor(int i=2; i<=5; i++) {\n\t\t\t\tif(!getSegment(i).isZero()) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}"
] |
Returns a reference definition of the given name if it exists.
@param name The name of the reference
@return The reference def or <code>null</code> if there is no such reference | [
"public ReferenceDescriptorDef getReference(String name)\r\n {\r\n ReferenceDescriptorDef refDef;\r\n\r\n for (Iterator it = _references.iterator(); it.hasNext(); )\r\n {\r\n refDef = (ReferenceDescriptorDef)it.next();\r\n if (refDef.getName().equals(name))\r\n {\r\n return refDef;\r\n }\r\n }\r\n return null;\r\n }"
] | [
"private static <R> RowKey buildRowKey(AssociationKey associationKey, R row, AssociationRowAccessor<R> accessor) {\n\t\tString[] columnNames = associationKey.getMetadata().getRowKeyColumnNames();\n\t\tObject[] columnValues = new Object[columnNames.length];\n\n\t\tfor ( int i = 0; i < columnNames.length; i++ ) {\n\t\t\tString columnName = columnNames[i];\n\t\t\tcolumnValues[i] = associationKey.getMetadata().isKeyColumn( columnName ) ? associationKey.getColumnValue( columnName ) : accessor.get( row, columnName );\n\t\t}\n\n\t\treturn new RowKey( columnNames, columnValues );\n\t}",
"public static void clearallLocalDBs() {\n for (final Map.Entry<MongoClient, Boolean> entry : localInstances.entrySet()) {\n for (final String dbName : entry.getKey().listDatabaseNames()) {\n entry.getKey().getDatabase(dbName).drop();\n }\n }\n }",
"public Class<?> getColumnType(int c) {\n\n for (int r = 0; r < m_data.size(); r++) {\n Object val = m_data.get(r).get(c);\n if (val != null) {\n return val.getClass();\n }\n }\n return Object.class;\n }",
"public CollectionRequest<Project> tasks(String project) {\n \n String path = String.format(\"/projects/%s/tasks\", project);\n return new CollectionRequest<Project>(this, Project.class, path, \"GET\");\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<EthiopicDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<EthiopicDate>) super.zonedDateTime(temporal);\n }",
"public void replace( Token original , Token target ) {\n if( first == original )\n first = target;\n if( last == original )\n last = target;\n\n target.next = original.next;\n target.previous = original.previous;\n\n if( original.next != null )\n original.next.previous = target;\n if( original.previous != null )\n original.previous.next = target;\n\n original.next = original.previous = null;\n }",
"protected static JRDesignExpression getExpressionFromVariable(JRDesignVariable var){\n\t\tJRDesignExpression exp = new JRDesignExpression();\n\t\texp.setText(\"$V{\" + var.getName() + \"}\");\n\t\texp.setValueClass(var.getValueClass());\n\t\treturn exp;\n\t}",
"protected void checkVariableName(GraphRewrite event, EvaluationContext context)\n {\n if (getInputVariablesName() == null)\n {\n setInputVariablesName(Iteration.getPayloadVariableName(event, context));\n }\n }",
"@Deprecated public Duration getDuration(String calendarName, Date startDate, Date endDate) throws MPXJException\n {\n ProjectCalendar calendar = getCalendarByName(calendarName);\n\n if (calendar == null)\n {\n throw new MPXJException(MPXJException.CALENDAR_ERROR + \": \" + calendarName);\n }\n\n return (calendar.getDuration(startDate, endDate));\n }"
] |
This produces a string with no compressed segments and all segments of full length,
which is 3 characters for IPv4 segments. | [
"@Override\n\tpublic String toFullString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = stringCache.fullString) == null) {\n\t\t\tstringCache.fullString = result = toNormalizedString(IPv4StringCache.fullParams);\n\t\t}\n\t\treturn result;\n\t}"
] | [
"public static DMatrixRMaj copyTriangle(DMatrixRMaj src , DMatrixRMaj dst , boolean upper ) {\n if( dst == null ) {\n dst = new DMatrixRMaj(src.numRows,src.numCols);\n } else if( src.numRows != dst.numRows || src.numCols != dst.numCols ) {\n throw new IllegalArgumentException(\"src and dst must have the same dimensions.\");\n }\n\n if( upper ) {\n int N = Math.min(src.numRows,src.numCols);\n for( int i = 0; i < N; i++ ) {\n int index = i*src.numCols+i;\n System.arraycopy(src.data,index,dst.data,index,src.numCols-i);\n }\n } else {\n for( int i = 0; i < src.numRows; i++ ) {\n int length = Math.min(i+1,src.numCols);\n int index = i*src.numCols;\n System.arraycopy(src.data,index,dst.data,index,length);\n }\n }\n\n return dst;\n }",
"public void execute() {\n try {\n while(true) {\n Event event = null;\n\n try {\n event = eventQueue.poll(timeout, unit);\n } catch(InterruptedException e) {\n throw new InsufficientOperationalNodesException(operation.getSimpleName()\n + \" operation interrupted!\", e);\n }\n\n if(event == null)\n throw new VoldemortException(operation.getSimpleName()\n + \" returned a null event\");\n\n if(event.equals(Event.ERROR)) {\n if(logger.isTraceEnabled())\n logger.trace(operation.getSimpleName()\n + \" request, events complete due to error\");\n\n break;\n } else if(event.equals(Event.COMPLETED)) {\n if(logger.isTraceEnabled())\n logger.trace(operation.getSimpleName() + \" request, events complete\");\n\n break;\n }\n\n Action action = eventActions.get(event);\n\n if(action == null)\n throw new IllegalStateException(\"action was null for event \" + event);\n\n if(logger.isTraceEnabled())\n logger.trace(operation.getSimpleName() + \" request, action \"\n + action.getClass().getSimpleName() + \" to handle \" + event\n + \" event\");\n\n action.execute(this);\n }\n } finally {\n finished = true;\n }\n }",
"public boolean detectOperaMobile() {\r\n\r\n if ((userAgent.indexOf(engineOpera) != -1)\r\n && ((userAgent.indexOf(mini) != -1) || (userAgent.indexOf(mobi) != -1))) {\r\n return true;\r\n }\r\n return false;\r\n }",
"public void removeMetadataProvider(MetadataProvider provider) {\n for (Set<MetadataProvider> providers : metadataProviders.values()) {\n providers.remove(provider);\n }\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 }",
"protected boolean isNetworkSection(int networkPrefixLength, boolean withPrefixLength) {\n\t\tint segmentCount = getSegmentCount();\n\t\tif(segmentCount == 0) {\n\t\t\treturn true;\n\t\t}\n\t\tint bitsPerSegment = getBitsPerSegment();\n\t\tint prefixedSegmentIndex = getNetworkSegmentIndex(networkPrefixLength, getBytesPerSegment(), bitsPerSegment);\n\t\tif(prefixedSegmentIndex + 1 < segmentCount) {\n\t\t\treturn false; //not the right number of segments\n\t\t}\n\t\t//the segment count matches, now compare the prefixed segment\n\t\tint segPrefLength = getPrefixedSegmentPrefixLength(bitsPerSegment, networkPrefixLength, prefixedSegmentIndex);\n\t\treturn !getSegment(segmentCount - 1).isNetworkChangedByPrefix(segPrefLength, withPrefixLength);\n\t}",
"private void processTasks(Gantt gantt)\n {\n ProjectCalendar calendar = m_projectFile.getDefaultCalendar();\n\n for (Gantt.Tasks.Task ganttTask : gantt.getTasks().getTask())\n {\n String wbs = ganttTask.getID();\n ChildTaskContainer parentTask = getParentTask(wbs);\n\n Task task = parentTask.addTask();\n //ganttTask.getB() // bar type\n //ganttTask.getBC() // bar color\n task.setCost(ganttTask.getC());\n task.setName(ganttTask.getContent());\n task.setDuration(ganttTask.getD());\n task.setDeadline(ganttTask.getDL());\n //ganttTask.getH() // height\n //ganttTask.getIn(); // indent\n task.setWBS(wbs);\n task.setPercentageComplete(ganttTask.getPC());\n task.setStart(ganttTask.getS());\n //ganttTask.getU(); // Unknown\n //ganttTask.getVA(); // Valign\n\n task.setFinish(calendar.getDate(task.getStart(), task.getDuration(), false));\n m_taskMap.put(wbs, task);\n }\n }",
"public static void changeSign(DMatrixSparseCSC A , DMatrixSparseCSC B ) {\n if( A != B ) {\n B.copyStructure(A);\n }\n\n for (int i = 0; i < A.nz_length; i++) {\n B.nz_values[i] = -A.nz_values[i];\n }\n }",
"public static void doMetaUpdateVersionsOnStores(AdminClient adminClient,\n List<StoreDefinition> oldStoreDefs,\n List<StoreDefinition> newStoreDefs) {\n Set<String> storeNamesUnion = new HashSet<String>();\n Map<String, StoreDefinition> oldStoreDefinitionMap = new HashMap<String, StoreDefinition>();\n Map<String, StoreDefinition> newStoreDefinitionMap = new HashMap<String, StoreDefinition>();\n List<String> storesChanged = new ArrayList<String>();\n for(StoreDefinition storeDef: oldStoreDefs) {\n String storeName = storeDef.getName();\n storeNamesUnion.add(storeName);\n oldStoreDefinitionMap.put(storeName, storeDef);\n }\n for(StoreDefinition storeDef: newStoreDefs) {\n String storeName = storeDef.getName();\n storeNamesUnion.add(storeName);\n newStoreDefinitionMap.put(storeName, storeDef);\n }\n for(String storeName: storeNamesUnion) {\n StoreDefinition oldStoreDef = oldStoreDefinitionMap.get(storeName);\n StoreDefinition newStoreDef = newStoreDefinitionMap.get(storeName);\n if(oldStoreDef == null && newStoreDef != null || oldStoreDef != null\n && newStoreDef == null || oldStoreDef != null && newStoreDef != null\n && !oldStoreDef.equals(newStoreDef)) {\n storesChanged.add(storeName);\n }\n }\n System.out.println(\"Updating metadata version for the following stores: \"\n + storesChanged);\n try {\n adminClient.metadataMgmtOps.updateMetadataversion(adminClient.getAdminClientCluster()\n .getNodeIds(),\n storesChanged);\n } catch(Exception e) {\n System.err.println(\"Error while updating metadata version for the specified store.\");\n }\n }"
] |
Ensure that a tool object is valid for creation. The API requires certain fields to be filled out.
Throws an IllegalArgumentException if the conditions are not met.
@param tool The external tool object we are trying to create | [
"private void ensureToolValidForCreation(ExternalTool tool) {\n //check for the unconditionally required fields\n if(StringUtils.isAnyBlank(tool.getName(), tool.getPrivacyLevel(), tool.getConsumerKey(), tool.getSharedSecret())) {\n throw new IllegalArgumentException(\"External tool requires all of the following for creation: name, privacy level, consumer key, shared secret\");\n }\n //check that there is either a URL or a domain. One or the other is required\n if(StringUtils.isBlank(tool.getUrl()) && StringUtils.isBlank(tool.getDomain())) {\n throw new IllegalArgumentException(\"External tool requires either a URL or domain for creation\");\n }\n }"
] | [
"private static void listCalendars(ProjectFile file)\n {\n for (ProjectCalendar cal : file.getCalendars())\n {\n System.out.println(cal.toString());\n }\n }",
"private void init()\n {\n style = new BoxStyle(UNIT);\n textLine = new StringBuilder();\n textMetrics = null;\n graphicsPath = new Vector<PathSegment>();\n startPage = 0;\n endPage = Integer.MAX_VALUE;\n fontTable = new FontTable();\n }",
"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 insertAfter(Token before, TokenList list ) {\n Token after = before.next;\n\n before.next = list.first;\n list.first.previous = before;\n if( after == null ) {\n last = list.last;\n } else {\n after.previous = list.last;\n list.last.next = after;\n }\n size += list.size;\n }",
"private Storepoint getCurrentStorepoint(Project phoenixProject)\n {\n List<Storepoint> storepoints = phoenixProject.getStorepoints().getStorepoint();\n Collections.sort(storepoints, new Comparator<Storepoint>()\n {\n @Override public int compare(Storepoint o1, Storepoint o2)\n {\n return DateHelper.compare(o2.getCreationTime(), o1.getCreationTime());\n }\n });\n return storepoints.get(0);\n }",
"public Date getStartDate()\n {\n Date startDate = null;\n\n for (Task task : m_tasks)\n {\n //\n // If a hidden \"summary\" task is present we ignore it\n //\n if (NumberHelper.getInt(task.getUniqueID()) == 0)\n {\n continue;\n }\n\n //\n // Select the actual or forecast start date. Note that the\n // behaviour is different for milestones. The milestone end date\n // is always correct, the milestone start date may be different\n // to reflect a missed deadline.\n //\n Date taskStartDate;\n if (task.getMilestone() == true)\n {\n taskStartDate = task.getActualFinish();\n if (taskStartDate == null)\n {\n taskStartDate = task.getFinish();\n }\n }\n else\n {\n taskStartDate = task.getActualStart();\n if (taskStartDate == null)\n {\n taskStartDate = task.getStart();\n }\n }\n\n if (taskStartDate != null)\n {\n if (startDate == null)\n {\n startDate = taskStartDate;\n }\n else\n {\n if (taskStartDate.getTime() < startDate.getTime())\n {\n startDate = taskStartDate;\n }\n }\n }\n }\n\n return (startDate);\n }",
"public AlbumArt requestArtworkFrom(final DataReference artReference, final CdjStatus.TrackType trackType) {\n ensureRunning();\n AlbumArt artwork = findArtInMemoryCaches(artReference); // First check the in-memory artwork caches.\n if (artwork == null) {\n artwork = requestArtworkInternal(artReference, trackType, false);\n }\n return artwork;\n }",
"public Where<T, ID> in(String columnName, Object... objects) throws SQLException {\n\t\treturn in(true, columnName, objects);\n\t}",
"public ByteArray readBytes(int size) throws IOException\n {\n byte[] data = new byte[size];\n m_stream.read(data);\n return new ByteArray(data);\n }"
] |
Create a new thread
@param name The name of the thread
@param runnable The work for the thread to do
@param daemon Should the thread block JVM shutdown?
@return The unstarted thread | [
"public static Thread newThread(String name, Runnable runnable, boolean daemon) {\n Thread thread = new Thread(runnable, name);\n thread.setDaemon(daemon);\n return thread;\n }"
] | [
"@Override\r\n public String upload(InputStream in, UploadMetaData metaData) throws FlickrException {\r\n Payload payload = new Payload(in);\r\n return sendUploadRequest(metaData, payload);\r\n }",
"protected void onRemoveParentObject(GVRSceneObject parent) {\n for (GVRComponent comp : mComponents.values()) {\n comp.onRemoveOwnersParent(parent);\n }\n }",
"public static <T> void notNull(final String name, final T value) {\n if (value == null) {\n throw new IllegalArgumentException(name + \" can not be null\");\n }\n }",
"public void getElevationAlongPath(PathElevationRequest req, ElevationServiceCallback callback) {\n \n this.callback = callback;\n \n JSObject doc = (JSObject) getJSObject().eval(\"document\");\n doc.setMember(getVariableName(), this);\n \n StringBuilder r = new StringBuilder(getVariableName())\n .append(\".\")\n .append(\"getElevationAlongPath(\")\n .append(req.getVariableName())\n .append(\", \")\n .append(\"function(results, status) {document.\")\n .append(getVariableName())\n .append(\".processResponse(results, status);});\");\n \n getJSObject().eval(r.toString());\n \n }",
"public static <S extends Matrix, D extends Matrix> LinearSolver<S,D> safe(LinearSolver<S,D> solver ) {\n if( solver.modifiesA() || solver.modifiesB() ) {\n if( solver instanceof LinearSolverDense ) {\n return new LinearSolverSafe((LinearSolverDense)solver);\n } else if( solver instanceof LinearSolverSparse ) {\n return new LinearSolverSparseSafe((LinearSolverSparse)solver);\n } else {\n throw new IllegalArgumentException(\"Unknown solver type\");\n }\n } else {\n return solver;\n }\n }",
"private static void generateJson(CellScanner cellScanner, Function<Bytes, String> encoder,\n PrintStream out) throws JsonIOException {\n Gson gson = new GsonBuilder().serializeNulls().setDateFormat(DateFormat.LONG)\n .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).setVersion(1.0)\n .create();\n\n Map<String, String> json = new LinkedHashMap<>();\n for (RowColumnValue rcv : cellScanner) {\n json.put(FLUO_ROW, encoder.apply(rcv.getRow()));\n json.put(FLUO_COLUMN_FAMILY, encoder.apply(rcv.getColumn().getFamily()));\n json.put(FLUO_COLUMN_QUALIFIER, encoder.apply(rcv.getColumn().getQualifier()));\n json.put(FLUO_COLUMN_VISIBILITY, encoder.apply(rcv.getColumn().getVisibility()));\n json.put(FLUO_VALUE, encoder.apply(rcv.getValue()));\n gson.toJson(json, out);\n out.append(\"\\n\");\n\n if (out.checkError()) {\n break;\n }\n }\n out.flush();\n }",
"public static GregorianCalendar millisToCalendar(long millis) {\r\n\r\n GregorianCalendar result = new GregorianCalendar();\r\n result.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\r\n result.setTimeInMillis((long)(Math.ceil(millis / 1000) * 1000));\r\n return result;\r\n }",
"public void refresh() {\n this.refreshLock.writeLock().lock();\n\n if (!this.canRefresh()) {\n this.refreshLock.writeLock().unlock();\n throw new IllegalStateException(\"The BoxAPIConnection cannot be refreshed because it doesn't have a \"\n + \"refresh token.\");\n }\n\n URL url = null;\n try {\n url = new URL(this.tokenURL);\n } catch (MalformedURLException e) {\n this.refreshLock.writeLock().unlock();\n assert false : \"An invalid refresh URL indicates a bug in the SDK.\";\n throw new RuntimeException(\"An invalid refresh URL indicates a bug in the SDK.\", e);\n }\n\n String urlParameters = String.format(\"grant_type=refresh_token&refresh_token=%s&client_id=%s&client_secret=%s\",\n this.refreshToken, this.clientID, this.clientSecret);\n\n BoxAPIRequest request = new BoxAPIRequest(this, url, \"POST\");\n request.shouldAuthenticate(false);\n request.setBody(urlParameters);\n\n String json;\n try {\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n json = response.getJSON();\n } catch (BoxAPIException e) {\n this.notifyError(e);\n this.refreshLock.writeLock().unlock();\n throw e;\n }\n\n JsonObject jsonObject = JsonObject.readFrom(json);\n this.accessToken = jsonObject.get(\"access_token\").asString();\n this.refreshToken = jsonObject.get(\"refresh_token\").asString();\n this.lastRefresh = System.currentTimeMillis();\n this.expires = jsonObject.get(\"expires_in\").asLong() * 1000;\n\n this.notifyRefresh();\n\n this.refreshLock.writeLock().unlock();\n }",
"public void setAngle(float angle) {\n this.angle = angle;\n float cos = (float) Math.cos(angle);\n float sin = (float) Math.sin(angle);\n m00 = cos;\n m01 = sin;\n m10 = -sin;\n m11 = cos;\n }"
] |
Construct new path by replacing file directory part. No
files are actually modified.
@param file path to move
@param target new path directory | [
"public static String movePath( final String file,\n final String target ) {\n final String name = new File(file).getName();\n return target.endsWith(\"/\") ? target + name : target + '/' + name;\n }"
] | [
"public static base_responses add(nitro_service client, vpath resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tvpath addresources[] = new vpath[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new vpath();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].destip = resources[i].destip;\n\t\t\t\taddresources[i].encapmode = resources[i].encapmode;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"public static Pair<HashMap<Node, Integer>, HashMap<Node, Integer>>\n getDonorsAndStealersForBalance(final Cluster nextCandidateCluster,\n Map<Integer, List<Integer>> numPartitionsPerNodePerZone) {\n HashMap<Node, Integer> donorNodes = Maps.newHashMap();\n HashMap<Node, Integer> stealerNodes = Maps.newHashMap();\n\n HashMap<Integer, Integer> numNodesAssignedInZone = Maps.newHashMap();\n for(Integer zoneId: nextCandidateCluster.getZoneIds()) {\n numNodesAssignedInZone.put(zoneId, 0);\n }\n for(Node node: nextCandidateCluster.getNodes()) {\n int zoneId = node.getZoneId();\n\n int offset = numNodesAssignedInZone.get(zoneId);\n numNodesAssignedInZone.put(zoneId, offset + 1);\n\n int numPartitions = numPartitionsPerNodePerZone.get(zoneId).get(offset);\n\n if(numPartitions < node.getNumberOfPartitions()) {\n donorNodes.put(node, numPartitions);\n } else if(numPartitions > node.getNumberOfPartitions()) {\n stealerNodes.put(node, numPartitions);\n }\n }\n\n // Print out donor/stealer information\n for(Node node: donorNodes.keySet()) {\n System.out.println(\"Donor Node: \" + node.getId() + \", zoneId \" + node.getZoneId()\n + \", numPartitions \" + node.getNumberOfPartitions()\n + \", target number of partitions \" + donorNodes.get(node));\n }\n for(Node node: stealerNodes.keySet()) {\n System.out.println(\"Stealer Node: \" + node.getId() + \", zoneId \" + node.getZoneId()\n + \", numPartitions \" + node.getNumberOfPartitions()\n + \", target number of partitions \" + stealerNodes.get(node));\n }\n\n return new Pair<HashMap<Node, Integer>, HashMap<Node, Integer>>(donorNodes, stealerNodes);\n }",
"private boolean includeDocument(ItemDocument itemDocument) {\n\t\tfor (StatementGroup sg : itemDocument.getStatementGroups()) {\n\t\t\t// \"P19\" is \"place of birth\" on Wikidata\n\t\t\tif (!\"P19\".equals(sg.getProperty().getId())) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (Statement s : sg) {\n\t\t\t\tif (s.getMainSnak() instanceof ValueSnak) {\n\t\t\t\t\tValue v = s.getValue();\n\t\t\t\t\t// \"Q1731\" is \"Dresden\" on Wikidata\n\t\t\t\t\tif (v instanceof ItemIdValue\n\t\t\t\t\t\t\t&& \"Q1731\".equals(((ItemIdValue) v).getId())) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"public static String formatBigDecimal(BigDecimal number) {\n\t\tif (number.signum() != -1) {\n\t\t\treturn \"+\" + number.toString();\n\t\t} else {\n\t\t\treturn number.toString();\n\t\t}\n\t}",
"public static DMatrixSparseCSC diag(double... values ) {\n int N = values.length;\n return diag(new DMatrixSparseCSC(N,N,N),values,0,N);\n }",
"protected ClassDescriptor selectClassDescriptor(Map row) throws PersistenceBrokerException\r\n {\r\n ClassDescriptor result = m_cld;\r\n Class ojbConcreteClass = (Class) row.get(OJB_CONCRETE_CLASS_KEY);\r\n if(ojbConcreteClass != null)\r\n {\r\n result = m_cld.getRepository().getDescriptorFor(ojbConcreteClass);\r\n // if we can't find class-descriptor for concrete class, something wrong with mapping\r\n if (result == null)\r\n {\r\n throw new PersistenceBrokerException(\"Can't find class-descriptor for ojbConcreteClass '\"\r\n + ojbConcreteClass + \"', the main class was \" + m_cld.getClassNameOfObject());\r\n }\r\n }\r\n return result;\r\n }",
"protected List<Integer> cancelAllActiveOperations() {\n final List<Integer> operations = new ArrayList<Integer>();\n for(final ActiveOperationImpl<?, ?> activeOperation : activeRequests.values()) {\n activeOperation.asyncCancel(false);\n operations.add(activeOperation.getOperationId());\n }\n return operations;\n }",
"public void getSpellcheckingResult(\n final HttpServletResponse res,\n final ServletRequest servletRequest,\n final CmsObject cms)\n throws CmsPermissionViolationException, IOException {\n\n // Perform a permission check\n performPermissionCheck(cms);\n\n // Set the appropriate response headers\n setResponeHeaders(res);\n\n // Figure out whether a JSON or HTTP request has been sent\n CmsSpellcheckingRequest cmsSpellcheckingRequest = null;\n try {\n String requestBody = getRequestBody(servletRequest);\n final JSONObject jsonRequest = new JSONObject(requestBody);\n cmsSpellcheckingRequest = parseJsonRequest(jsonRequest);\n } catch (Exception e) {\n LOG.debug(e.getMessage(), e);\n cmsSpellcheckingRequest = parseHttpRequest(servletRequest, cms);\n }\n\n if ((null != cmsSpellcheckingRequest) && cmsSpellcheckingRequest.isInitialized()) {\n // Perform the actual spellchecking\n final SpellCheckResponse spellCheckResponse = performSpellcheckQuery(cmsSpellcheckingRequest);\n\n /*\n * The field spellCheckResponse is null when exactly one correctly spelled word is passed to the spellchecker.\n * In this case it's safe to return an empty JSON formatted map, as the passed word is correct. Otherwise,\n * convert the spellchecker response into a new JSON formatted map.\n */\n if (null == spellCheckResponse) {\n cmsSpellcheckingRequest.m_wordSuggestions = new JSONObject();\n } else {\n cmsSpellcheckingRequest.m_wordSuggestions = getConvertedResponseAsJson(spellCheckResponse);\n }\n }\n\n // Send response back to the client\n sendResponse(res, cmsSpellcheckingRequest);\n }",
"public static synchronized void unregister(final String serviceName,\n final Callable<Class< ? >> factory) {\n if ( serviceName == null ) {\n throw new IllegalArgumentException( \"serviceName cannot be null\" );\n }\n if ( factories != null ) {\n List<Callable<Class< ? >>> l = factories.get( serviceName );\n if ( l != null ) {\n l.remove( factory );\n }\n }\n }"
] |
Given the byte buffer containing album art, build an actual image from it for easy rendering.
@return the newly-created image, ready to be drawn | [
"public BufferedImage getImage() {\n ByteBuffer artwork = getRawBytes();\n artwork.rewind();\n byte[] imageBytes = new byte[artwork.remaining()];\n artwork.get(imageBytes);\n try {\n return ImageIO.read(new ByteArrayInputStream(imageBytes));\n } catch (IOException e) {\n logger.error(\"Weird! Caught exception creating image from artwork bytes\", e);\n return null;\n }\n }"
] | [
"private static int getBlockLength(String text, int offset)\n {\n int startIndex = offset;\n boolean finished = false;\n char c;\n\n while (finished == false)\n {\n c = text.charAt(offset);\n switch (c)\n {\n case '\\r':\n case '\\n':\n case '}':\n {\n finished = true;\n break;\n }\n\n default:\n {\n ++offset;\n break;\n }\n }\n }\n\n int length = offset - startIndex;\n\n return (length);\n }",
"private static Clique valueOfHelper(int[] relativeIndices) {\r\n // if clique already exists, return that one\r\n Clique c = new Clique();\r\n c.relativeIndices = relativeIndices;\r\n return intern(c);\r\n }",
"public static void main(String[] args) {\r\n //Adding custom equivalence class generation transformer - NOTE this will get applied during graph traversal-->\r\n //MODEL USAGE EXAMPLE: <assign name=\"var_out_V1_2\" expr=\"%ssn\"/> <dg:transform name=\"EQ\"/>\r\n Map<String, DataTransformer> transformers = new HashMap<String, DataTransformer>();\r\n transformers.put(\"EQ\", new EquivalenceClassTransformer());\r\n Vector<CustomTagExtension> cte = new Vector<CustomTagExtension>();\r\n cte.add(new InLineTransformerExtension(transformers));\r\n Engine engine = new SCXMLEngine(cte);\n\r\n //will default to samplemachine, but you could specify a different file if you choose to\r\n InputStream is = CmdLine.class.getResourceAsStream(\"/\" + (args.length == 0 ? \"samplemachine\" : args[0]) + \".xml\");\n\r\n engine.setModelByInputFileStream(is);\n\r\n // Usually, this should be more than the number of threads you intend to run\r\n engine.setBootstrapMin(1);\n\r\n //Prepare the consumer with the proper writer and transformer\r\n DataConsumer consumer = new DataConsumer();\r\n consumer.addDataTransformer(new SampleMachineTransformer());\n\r\n //Adding custom equivalence class generation transformer - NOTE this will get applied post data generation.\r\n //MODEL USAGE EXAMPLE: <dg:assign name=\"var_out_V2\" set=\"%regex([0-9]{3}[A-Z0-9]{5})\"/>\r\n consumer.addDataTransformer(new EquivalenceClassTransformer());\n\r\n consumer.addDataWriter(new DefaultWriter(System.out,\r\n new String[]{\"var_1_1\", \"var_1_2\", \"var_1_3\", \"var_1_4\", \"var_1_5\", \"var_1_6\", \"var_1_7\",\r\n \"var_2_1\", \"var_2_2\", \"var_2_3\", \"var_2_4\", \"var_2_5\", \"var_2_6\", \"var_2_7\", \"var_2_8\"}));\n\r\n //Prepare the distributor\r\n DefaultDistributor defaultDistributor = new DefaultDistributor();\r\n defaultDistributor.setThreadCount(1);\r\n defaultDistributor.setDataConsumer(consumer);\r\n Logger.getLogger(\"org.apache\").setLevel(Level.WARN);\n\r\n engine.process(defaultDistributor);\r\n }",
"public void startServer() throws Exception {\n if (!externalDatabaseHost) {\n try {\n this.port = Utils.getSystemPort(Constants.SYS_DB_PORT);\n server = Server.createTcpServer(\"-tcpPort\", String.valueOf(port), \"-tcpAllowOthers\").start();\n } catch (SQLException e) {\n if (e.toString().contains(\"java.net.UnknownHostException\")) {\n logger.error(\"Startup failure. Potential bug in OSX & Java7. Workaround: add name of local machine to '/etc/hosts.'\");\n logger.error(\"Example: 127.0.0.1 MacBook\");\n throw e;\n }\n }\n }\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 }",
"public void addNavigationalInformationForInverseSide() {\n\t\tif ( log.isTraceEnabled() ) {\n\t\t\tlog.trace( \"Adding inverse navigational information for entity: \" + MessageHelper.infoString( persister, id, persister.getFactory() ) );\n\t\t}\n\n\t\tfor ( int propertyIndex = 0; propertyIndex < persister.getEntityMetamodel().getPropertySpan(); propertyIndex++ ) {\n\t\t\tif ( persister.isPropertyOfTable( propertyIndex, tableIndex ) ) {\n\t\t\t\tAssociationKeyMetadata associationKeyMetadata = getInverseAssociationKeyMetadata( propertyIndex );\n\n\t\t\t\t// there is no inverse association for the given property\n\t\t\t\tif ( associationKeyMetadata == null ) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tObject[] newColumnValues = LogicalPhysicalConverterHelper.getColumnValuesFromResultset(\n\t\t\t\t\t\tresultset,\n\t\t\t\t\t\tpersister.getPropertyColumnNames( propertyIndex )\n\t\t\t\t);\n\n\t\t\t\t//don't index null columns, this means no association\n\t\t\t\tif ( ! CollectionHelper.isEmptyOrContainsOnlyNull( ( newColumnValues ) ) ) {\n\t\t\t\t\taddNavigationalInformationForInverseSide( propertyIndex, associationKeyMetadata, newColumnValues );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"public boolean perform(Run<?, ?> build, Launcher launcher, TaskListener listener, EnvVars env, FilePath workDir, FilePath tempDir)\n throws InterruptedException, IOException {\n listener.getLogger().println(\"Jenkins Artifactory Plugin version: \" + ActionableHelper.getArtifactoryPluginVersion());\n FilePath mavenHome = getMavenHome(listener, env, launcher);\n\n if (!mavenHome.exists()) {\n listener.getLogger().println(\"Couldn't find Maven home at \" + mavenHome.getRemote() + \" on agent \" + Utils.getAgentName(workDir) +\n \". This could be because this build is running inside a Docker container.\");\n }\n ArgumentListBuilder cmdLine = buildMavenCmdLine(build, listener, env, launcher, mavenHome, workDir, tempDir);\n String[] cmds = cmdLine.toCommandArray();\n return RunMaven(build, launcher, listener, env, workDir, cmds);\n }",
"public void validateOperation(final ModelNode operation) {\n if (operation == null) {\n return;\n }\n final PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR));\n final String name = operation.get(OP).asString();\n\n OperationEntry entry = root.getOperationEntry(address, name);\n if (entry == null) {\n throwOrWarnAboutDescriptorProblem(ControllerLogger.ROOT_LOGGER.noOperationEntry(name, address));\n }\n //noinspection ConstantConditions\n if (entry.getType() == EntryType.PRIVATE || entry.getFlags().contains(OperationEntry.Flag.HIDDEN)) {\n return;\n }\n if (entry.getOperationHandler() == null) {\n throwOrWarnAboutDescriptorProblem(ControllerLogger.ROOT_LOGGER.noOperationHandler(name, address));\n }\n final DescriptionProvider provider = getDescriptionProvider(operation);\n final ModelNode description = provider.getModelDescription(null);\n\n final Map<String, ModelNode> describedProperties = getDescribedRequestProperties(operation, description);\n final Map<String, ModelNode> actualParams = getActualRequestProperties(operation);\n\n checkActualOperationParamsAreDescribed(operation, describedProperties, actualParams);\n checkAllRequiredPropertiesArePresent(description, operation, describedProperties, actualParams);\n checkParameterTypes(description, operation, describedProperties, actualParams);\n\n //TODO check ranges\n }",
"public 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 }"
] |
Return the build string of this instance of finmath-lib.
Currently this is the Git commit hash.
@return The build string of this instance of finmath-lib. | [
"public static String getBuildString() {\n\t\tString versionString = \"UNKNOWN\";\n\t\tProperties propeties = getProperites();\n\t\tif(propeties != null) {\n\t\t\tversionString = propeties.getProperty(\"finmath-lib.build\");\n\t\t}\n\t\treturn versionString;\n\t}"
] | [
"public static void generateJRXML(DynamicReport dr, LayoutManager layoutManager, Map _parameters, String xmlEncoding, OutputStream outputStream) throws JRException {\n JasperReport jr = generateJasperReport(dr, layoutManager, _parameters);\n if (xmlEncoding == null)\n xmlEncoding = DEFAULT_XML_ENCODING;\n JRXmlWriter.writeReport(jr, outputStream, xmlEncoding);\n }",
"@Override\n public PersistentResourceXMLDescription getParserDescription() {\n return PersistentResourceXMLDescription.builder(ElytronExtension.SUBSYSTEM_PATH, getNameSpace())\n .addAttribute(ElytronDefinition.DEFAULT_AUTHENTICATION_CONTEXT)\n .addAttribute(ElytronDefinition.INITIAL_PROVIDERS)\n .addAttribute(ElytronDefinition.FINAL_PROVIDERS)\n .addAttribute(ElytronDefinition.DISALLOWED_PROVIDERS)\n .addAttribute(ElytronDefinition.SECURITY_PROPERTIES, new AttributeParsers.PropertiesParser(null, SECURITY_PROPERTY, true), new AttributeMarshallers.PropertiesAttributeMarshaller(null, SECURITY_PROPERTY, true))\n .addChild(getAuthenticationClientParser())\n .addChild(getProviderParser())\n .addChild(getAuditLoggingParser())\n .addChild(getDomainParser())\n .addChild(getRealmParser())\n .addChild(getCredentialSecurityFactoryParser())\n .addChild(getMapperParser())\n .addChild(getHttpParser())\n .addChild(getSaslParser())\n .addChild(getTlsParser())\n .addChild(decorator(CREDENTIAL_STORES).addChild(new CredentialStoreParser().parser))\n .addChild(getDirContextParser())\n .addChild(getPolicyParser())\n .build();\n }",
"public static URI createRestURI(\n final String matrixId, final int row, final int col,\n final WMTSLayerParam layerParam) throws URISyntaxException {\n String path = layerParam.baseURL;\n if (layerParam.dimensions != null) {\n for (int i = 0; i < layerParam.dimensions.length; i++) {\n String dimension = layerParam.dimensions[i];\n String value = layerParam.dimensionParams.optString(dimension);\n if (value == null) {\n value = layerParam.dimensionParams.getString(dimension.toUpperCase());\n }\n path = path.replace(\"{\" + dimension + \"}\", value);\n }\n }\n path = path.replace(\"{TileMatrixSet}\", layerParam.matrixSet);\n path = path.replace(\"{TileMatrix}\", matrixId);\n path = path.replace(\"{TileRow}\", String.valueOf(row));\n path = path.replace(\"{TileCol}\", String.valueOf(col));\n path = path.replace(\"{style}\", layerParam.style);\n path = path.replace(\"{Layer}\", layerParam.layer);\n\n return new URI(path);\n }",
"public static tmsessionparameter get(nitro_service service) throws Exception{\n\t\ttmsessionparameter obj = new tmsessionparameter();\n\t\ttmsessionparameter[] response = (tmsessionparameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"private static void checkPreconditions(final List<String> forbiddenSubStrings) {\n\t\tif( forbiddenSubStrings == null ) {\n\t\t\tthrow new NullPointerException(\"forbiddenSubStrings list should not be null\");\n\t\t} else if( forbiddenSubStrings.isEmpty() ) {\n\t\t\tthrow new IllegalArgumentException(\"forbiddenSubStrings list should not be empty\");\n\t\t}\n\t}",
"public static base_response update(nitro_service client, cachecontentgroup resource) throws Exception {\n\t\tcachecontentgroup updateresource = new cachecontentgroup();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.weakposrelexpiry = resource.weakposrelexpiry;\n\t\tupdateresource.heurexpiryparam = resource.heurexpiryparam;\n\t\tupdateresource.relexpiry = resource.relexpiry;\n\t\tupdateresource.relexpirymillisec = resource.relexpirymillisec;\n\t\tupdateresource.absexpiry = resource.absexpiry;\n\t\tupdateresource.absexpirygmt = resource.absexpirygmt;\n\t\tupdateresource.weaknegrelexpiry = resource.weaknegrelexpiry;\n\t\tupdateresource.hitparams = resource.hitparams;\n\t\tupdateresource.invalparams = resource.invalparams;\n\t\tupdateresource.ignoreparamvaluecase = resource.ignoreparamvaluecase;\n\t\tupdateresource.matchcookies = resource.matchcookies;\n\t\tupdateresource.invalrestrictedtohost = resource.invalrestrictedtohost;\n\t\tupdateresource.polleverytime = resource.polleverytime;\n\t\tupdateresource.ignorereloadreq = resource.ignorereloadreq;\n\t\tupdateresource.removecookies = resource.removecookies;\n\t\tupdateresource.prefetch = resource.prefetch;\n\t\tupdateresource.prefetchperiod = resource.prefetchperiod;\n\t\tupdateresource.prefetchperiodmillisec = resource.prefetchperiodmillisec;\n\t\tupdateresource.prefetchmaxpending = resource.prefetchmaxpending;\n\t\tupdateresource.flashcache = resource.flashcache;\n\t\tupdateresource.expireatlastbyte = resource.expireatlastbyte;\n\t\tupdateresource.insertvia = resource.insertvia;\n\t\tupdateresource.insertage = resource.insertage;\n\t\tupdateresource.insertetag = resource.insertetag;\n\t\tupdateresource.cachecontrol = resource.cachecontrol;\n\t\tupdateresource.quickabortsize = resource.quickabortsize;\n\t\tupdateresource.minressize = resource.minressize;\n\t\tupdateresource.maxressize = resource.maxressize;\n\t\tupdateresource.memlimit = resource.memlimit;\n\t\tupdateresource.ignorereqcachinghdrs = resource.ignorereqcachinghdrs;\n\t\tupdateresource.minhits = resource.minhits;\n\t\tupdateresource.alwaysevalpolicies = resource.alwaysevalpolicies;\n\t\tupdateresource.persist = resource.persist;\n\t\tupdateresource.pinned = resource.pinned;\n\t\tupdateresource.lazydnsresolve = resource.lazydnsresolve;\n\t\tupdateresource.hitselector = resource.hitselector;\n\t\tupdateresource.invalselector = resource.invalselector;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public void validateUniqueIDsForMicrosoftProject()\n {\n if (!isEmpty())\n {\n for (T entity : this)\n {\n if (NumberHelper.getInt(entity.getUniqueID()) > MS_PROJECT_MAX_UNIQUE_ID)\n {\n renumberUniqueIDs();\n break;\n }\n }\n }\n }",
"public static base_response convert(nitro_service client, sslpkcs12 resource) throws Exception {\n\t\tsslpkcs12 convertresource = new sslpkcs12();\n\t\tconvertresource.outfile = resource.outfile;\n\t\tconvertresource.Import = resource.Import;\n\t\tconvertresource.pkcs12file = resource.pkcs12file;\n\t\tconvertresource.des = resource.des;\n\t\tconvertresource.des3 = resource.des3;\n\t\tconvertresource.export = resource.export;\n\t\tconvertresource.certfile = resource.certfile;\n\t\tconvertresource.keyfile = resource.keyfile;\n\t\tconvertresource.password = resource.password;\n\t\tconvertresource.pempassphrase = resource.pempassphrase;\n\t\treturn convertresource.perform_operation(client,\"convert\");\n\t}",
"public static vpath_stats get(nitro_service service) throws Exception{\n\t\tvpath_stats obj = new vpath_stats();\n\t\tvpath_stats[] response = (vpath_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}"
] |
Find the fields in which the Activity ID and Activity Type are stored. | [
"private void configureCustomFields()\n {\n CustomFieldContainer customFields = m_projectFile.getCustomFields();\n\n // If the caller hasn't already supplied a value for this field\n if (m_activityIDField == null)\n {\n m_activityIDField = (TaskField) customFields.getFieldByAlias(FieldTypeClass.TASK, \"Code\");\n if (m_activityIDField == null)\n {\n m_activityIDField = TaskField.WBS;\n }\n }\n\n // If the caller hasn't already supplied a value for this field\n if (m_activityTypeField == null)\n {\n m_activityTypeField = (TaskField) customFields.getFieldByAlias(FieldTypeClass.TASK, \"Activity Type\");\n }\n }"
] | [
"public void setColor(int n, int color) {\n\t\tint firstColor = map[0];\n\t\tint lastColor = map[256-1];\n\t\tif (n > 0)\n\t\t\tfor (int i = 0; i < n; i++)\n\t\t\t\tmap[i] = ImageMath.mixColors((float)i/n, firstColor, color);\n\t\tif (n < 256-1)\n\t\t\tfor (int i = n; i < 256; i++)\n\t\t\t\tmap[i] = ImageMath.mixColors((float)(i-n)/(256-n), color, lastColor);\n\t}",
"public ItemDocument updateStatements(ItemIdValue itemIdValue,\n\t\t\tList<Statement> addStatements, List<Statement> deleteStatements,\n\t\t\tString summary) throws MediaWikiApiErrorException, IOException {\n\n\t\tItemDocument currentDocument = (ItemDocument) this.wikibaseDataFetcher\n\t\t\t\t.getEntityDocument(itemIdValue.getId());\n\n\t\treturn updateStatements(currentDocument, addStatements,\n\t\t\t\tdeleteStatements, summary);\n\t}",
"public static Logger getLogger(String className) {\n\t\tif (logType == null) {\n\t\t\tlogType = findLogType();\n\t\t}\n\t\treturn new Logger(logType.createLog(className));\n\t}",
"public static Command newQuery(String identifier,\n String name) {\n return getCommandFactoryProvider().newQuery( identifier,\n name );\n\n }",
"public static final boolean setSelectedValue(ListBox list, String value, boolean addMissingValues) {\n\tif (value == null) {\n\t list.setSelectedIndex(0);\n\t return false;\n\t}\n\telse {\n\t int index = findValueInListBox(list, value);\n\t if (index >= 0) {\n\t\tlist.setSelectedIndex(index);\n\t\treturn true;\n\t }\n\n\t if (addMissingValues) {\n\t\tlist.addItem(value, value);\n\n\t\t// now that it's there, search again\n\t\tindex = findValueInListBox(list, value);\n\t\tlist.setSelectedIndex(index);\n\t\treturn true;\n\t }\n\n\t return false;\n\t}\n }",
"private void performDynamicStep() {\n // initially look for singular values of zero\n if( findingZeros ) {\n if( steps > 6 ) {\n findingZeros = false;\n } else {\n double scale = computeBulgeScale();\n performImplicitSingleStep(scale,0,false);\n }\n } else {\n // For very large and very small numbers the only way to prevent overflow/underflow\n // is to have a common scale between the wilkinson shift and the implicit single step\n // What happens if you don't is that when the wilkinson shift returns the value it\n // computed it multiplies it by the scale twice, which will cause an overflow\n double scale = computeBulgeScale();\n // use the wilkinson shift to perform a step\n double lambda = selectWilkinsonShift(scale);\n\n performImplicitSingleStep(scale,lambda,false);\n }\n }",
"public PeriodicEvent runEvery(Runnable task, float delay, float period,\n KeepRunning callback) {\n validateDelay(delay);\n validatePeriod(period);\n return new Event(task, delay, period, callback);\n }",
"private void processCustomFieldValues()\n {\n byte[] data = m_projectProps.getByteArray(Props.TASK_FIELD_ATTRIBUTES);\n if (data != null)\n {\n int index = 0;\n int offset = 0;\n // First the length\n int length = MPPUtility.getInt(data, offset);\n offset += 4;\n // Then the number of custom value lists\n int numberOfValueLists = MPPUtility.getInt(data, offset);\n offset += 4;\n\n // Then the value lists themselves\n FieldType field;\n int valueListOffset = 0;\n while (index < numberOfValueLists && offset < length)\n {\n // Each item consists of the Field ID (4 bytes) and the offset to the value list (4 bytes)\n\n // Get the Field\n field = FieldTypeHelper.getInstance(MPPUtility.getInt(data, offset));\n offset += 4;\n\n // Get the value list offset\n valueListOffset = MPPUtility.getInt(data, offset);\n offset += 4;\n // Read the value list itself\n if (valueListOffset < data.length)\n {\n int tempOffset = valueListOffset;\n tempOffset += 8;\n // Get the data offset\n int dataOffset = MPPUtility.getInt(data, tempOffset) + valueListOffset;\n tempOffset += 4;\n // Get the end of the data offset\n int endDataOffset = MPPUtility.getInt(data, tempOffset) + valueListOffset;\n tempOffset += 4;\n // Get the end of the description\n int endDescriptionOffset = MPPUtility.getInt(data, tempOffset) + valueListOffset;\n\n // Get the values themselves\n int valuesLength = endDataOffset - dataOffset;\n byte[] values = new byte[valuesLength];\n MPPUtility.getByteArray(data, dataOffset, valuesLength, values, 0);\n\n // Get the descriptions\n int descriptionsLength = endDescriptionOffset - endDataOffset;\n byte[] descriptions = new byte[descriptionsLength];\n MPPUtility.getByteArray(data, endDataOffset, descriptionsLength, descriptions, 0);\n\n populateContainer(field, values, descriptions);\n }\n index++;\n }\n }\n }",
"protected BlockBox createBlock(BlockBox parent, Element n, boolean replaced)\n {\n BlockBox root;\n if (replaced)\n {\n BlockReplacedBox rbox = new BlockReplacedBox((Element) n, (Graphics2D) parent.getGraphics().create(), parent.getVisualContext().create());\n rbox.setViewport(viewport);\n rbox.setContentObj(new ReplacedImage(rbox, rbox.getVisualContext(), baseurl, n.getAttribute(\"src\")));\n root = rbox;\n }\n else\n {\n root = new BlockBox((Element) n, (Graphics2D) parent.getGraphics().create(), parent.getVisualContext().create());\n root.setViewport(viewport);\n }\n root.setBase(baseurl);\n root.setParent(parent);\n root.setContainingBlockBox(parent);\n root.setClipBlock(viewport);\n root.setOrder(next_order++);\n return root;\n }"
] |
This is a convenience method used to add a calendar called
"Standard" to the project, and populate it with a default working week
and default working hours.
@return a new default calendar | [
"public ProjectCalendar addDefaultBaseCalendar()\n {\n ProjectCalendar calendar = add();\n\n calendar.setName(ProjectCalendar.DEFAULT_BASE_CALENDAR_NAME);\n\n calendar.setWorkingDay(Day.SUNDAY, false);\n calendar.setWorkingDay(Day.MONDAY, true);\n calendar.setWorkingDay(Day.TUESDAY, true);\n calendar.setWorkingDay(Day.WEDNESDAY, true);\n calendar.setWorkingDay(Day.THURSDAY, true);\n calendar.setWorkingDay(Day.FRIDAY, true);\n calendar.setWorkingDay(Day.SATURDAY, false);\n\n calendar.addDefaultCalendarHours();\n\n return (calendar);\n }"
] | [
"public static float smoothPulse(float a1, float a2, float b1, float b2, float x) {\n\t\tif (x < a1 || x >= b2)\n\t\t\treturn 0;\n\t\tif (x >= a2) {\n\t\t\tif (x < b1)\n\t\t\t\treturn 1.0f;\n\t\t\tx = (x - b1) / (b2 - b1);\n\t\t\treturn 1.0f - (x*x * (3.0f - 2.0f*x));\n\t\t}\n\t\tx = (x - a1) / (a2 - a1);\n\t\treturn x*x * (3.0f - 2.0f*x);\n\t}",
"public String getRecordSchema() throws IOException {\n Schema schema = getInputPathAvroSchema();\n String recSchema = schema.toString();\n return recSchema;\n }",
"public static DatabaseFieldConfig fromReader(BufferedReader reader) throws SQLException {\n\t\tDatabaseFieldConfig config = new DatabaseFieldConfig();\n\t\tboolean anything = false;\n\t\twhile (true) {\n\t\t\tString line;\n\t\t\ttry {\n\t\t\t\tline = reader.readLine();\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow SqlExceptionUtil.create(\"Could not read DatabaseFieldConfig from stream\", e);\n\t\t\t}\n\t\t\tif (line == null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// we do this so we can support multiple class configs per file\n\t\t\tif (line.equals(CONFIG_FILE_END_MARKER)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// skip empty lines or comments\n\t\t\tif (line.length() == 0 || line.startsWith(\"#\") || line.equals(CONFIG_FILE_START_MARKER)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tString[] parts = line.split(\"=\", -2);\n\t\t\tif (parts.length != 2) {\n\t\t\t\tthrow new SQLException(\"DatabaseFieldConfig reading from stream cannot parse line: \" + line);\n\t\t\t}\n\t\t\treadField(config, parts[0], parts[1]);\n\t\t\tanything = true;\n\t\t}\n\t\t// if we got any config lines then we return the config\n\t\tif (anything) {\n\t\t\treturn config;\n\t\t} else {\n\t\t\t// otherwise we return null for none\n\t\t\treturn null;\n\t\t}\n\t}",
"public void addVars(Map<String, String> env) {\n if (tagUrl != null) {\n env.put(\"RELEASE_SCM_TAG\", tagUrl);\n env.put(RT_RELEASE_STAGING + \"SCM_TAG\", tagUrl);\n }\n if (releaseBranch != null) {\n env.put(\"RELEASE_SCM_BRANCH\", releaseBranch);\n env.put(RT_RELEASE_STAGING + \"SCM_BRANCH\", releaseBranch);\n }\n if (releaseVersion != null) {\n env.put(RT_RELEASE_STAGING + \"VERSION\", releaseVersion);\n }\n if (nextVersion != null) {\n env.put(RT_RELEASE_STAGING + \"NEXT_VERSION\", nextVersion);\n }\n }",
"protected final StringBuilder getBaseUrl(final HttpServletRequest httpServletRequest) {\n StringBuilder baseURL = new StringBuilder();\n if (httpServletRequest.getContextPath() != null && !httpServletRequest.getContextPath().isEmpty()) {\n baseURL.append(httpServletRequest.getContextPath());\n }\n if (httpServletRequest.getServletPath() != null && !httpServletRequest.getServletPath().isEmpty()) {\n baseURL.append(httpServletRequest.getServletPath());\n }\n return baseURL;\n }",
"public static base_responses update(nitro_service client, tmtrafficaction resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\ttmtrafficaction updateresources[] = new tmtrafficaction[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new tmtrafficaction();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].apptimeout = resources[i].apptimeout;\n\t\t\t\tupdateresources[i].sso = resources[i].sso;\n\t\t\t\tupdateresources[i].formssoaction = resources[i].formssoaction;\n\t\t\t\tupdateresources[i].persistentcookie = resources[i].persistentcookie;\n\t\t\t\tupdateresources[i].initiatelogout = resources[i].initiatelogout;\n\t\t\t\tupdateresources[i].kcdaccount = resources[i].kcdaccount;\n\t\t\t\tupdateresources[i].samlssoprofile = resources[i].samlssoprofile;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"@Override\n public ResourceStorageLoadable getOrCreateResourceStorageLoadable(final StorageAwareResource resource) {\n try {\n final ResourceStorageProviderAdapter stateProvider = IterableExtensions.<ResourceStorageProviderAdapter>head(Iterables.<ResourceStorageProviderAdapter>filter(resource.getResourceSet().eAdapters(), ResourceStorageProviderAdapter.class));\n if ((stateProvider != null)) {\n final ResourceStorageLoadable inputStream = stateProvider.getResourceStorageLoadable(resource);\n if ((inputStream != null)) {\n return inputStream;\n }\n }\n InputStream _xifexpression = null;\n boolean _exists = resource.getResourceSet().getURIConverter().exists(this.getBinaryStorageURI(resource.getURI()), CollectionLiterals.<Object, Object>emptyMap());\n if (_exists) {\n _xifexpression = resource.getResourceSet().getURIConverter().createInputStream(this.getBinaryStorageURI(resource.getURI()));\n } else {\n InputStream _xblockexpression = null;\n {\n final AbstractFileSystemAccess2 fsa = this.getFileSystemAccess(resource);\n final String outputRelativePath = this.computeOutputPath(resource);\n _xblockexpression = fsa.readBinaryFile(outputRelativePath);\n }\n _xifexpression = _xblockexpression;\n }\n final InputStream inputStream_1 = _xifexpression;\n return this.createResourceStorageLoadable(inputStream_1);\n } catch (Throwable _e) {\n throw Exceptions.sneakyThrow(_e);\n }\n }",
"private static String handleRichError(final Response response, final String body) {\n if (!response.getHeaders().containsKey(Headers.CONTENT_TYPE)\n || !response.getHeaders().get(Headers.CONTENT_TYPE).equals(ContentTypes.APPLICATION_JSON)) {\n return body;\n }\n\n final Document doc;\n try {\n doc = BsonUtils.parseValue(body, Document.class);\n } catch (Exception e) {\n return body;\n }\n\n if (!doc.containsKey(Fields.ERROR)) {\n return body;\n }\n final String errorMsg = doc.getString(Fields.ERROR);\n if (!doc.containsKey(Fields.ERROR_CODE)) {\n return errorMsg;\n }\n\n final String errorCode = doc.getString(Fields.ERROR_CODE);\n throw new StitchServiceException(errorMsg, StitchServiceErrorCode.fromCodeName(errorCode));\n }",
"public AwsServiceClient withCodecRegistry(@Nonnull final CodecRegistry codecRegistry) {\n return new AwsServiceClientImpl(proxy.withCodecRegistry(codecRegistry), dispatcher);\n }"
] |
Retrieves a string value from the property data.
@param type Type identifier
@return string value | [
"public String getUnicodeString(Integer type)\n {\n String result = null;\n\n byte[] item = m_map.get(type);\n if (item != null)\n {\n result = MPPUtility.getUnicodeString(item, 0);\n }\n\n return (result);\n }"
] | [
"public void fireEvent(final WorkerEvent event, final Worker worker, final String queue, final Job job, \n final Object runner, final Object result, final Throwable t) {\n final ConcurrentSet<WorkerListener> listeners = this.eventListenerMap.get(event);\n if (listeners != null) {\n for (final WorkerListener listener : listeners) {\n if (listener != null) {\n try {\n listener.onEvent(event, worker, queue, job, runner, result, t);\n } catch (Exception e) {\n log.error(\"Failure executing listener \" + listener + \" for event \" + event \n + \" from queue \" + queue + \" on worker \" + worker, e);\n }\n }\n }\n }\n }",
"public static nsspparams get(nitro_service service) throws Exception{\n\t\tnsspparams obj = new nsspparams();\n\t\tnsspparams[] response = (nsspparams[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public static final Object getObject(Locale locale, String key)\n {\n ResourceBundle bundle = ResourceBundle.getBundle(LocaleData.class.getName(), locale);\n return (bundle.getObject(key));\n }",
"public static base_response add(nitro_service client, dbdbprofile resource) throws Exception {\n\t\tdbdbprofile addresource = new dbdbprofile();\n\t\taddresource.name = resource.name;\n\t\taddresource.interpretquery = resource.interpretquery;\n\t\taddresource.stickiness = resource.stickiness;\n\t\taddresource.kcdaccount = resource.kcdaccount;\n\t\taddresource.conmultiplex = resource.conmultiplex;\n\t\treturn addresource.add_resource(client);\n\t}",
"public void logAttributeWarning(PathAddress address, ModelNode operation, String message, Set<String> attributes) {\n messageQueue.add(new AttributeLogEntry(address, operation, message, attributes));\n }",
"private int checkInInternal() {\n\n m_logStream.println(\"[\" + new Date() + \"] STARTING Git task\");\n m_logStream.println(\"=========================\");\n m_logStream.println();\n\n if (m_checkout) {\n m_logStream.println(\"Running checkout script\");\n\n } else if (!(m_resetHead || m_resetRemoteHead)) {\n m_logStream.println(\"Exporting relevant modules\");\n m_logStream.println(\"--------------------------\");\n m_logStream.println();\n\n exportModules();\n\n m_logStream.println();\n m_logStream.println(\"Calling script to check in the exports\");\n m_logStream.println(\"--------------------------------------\");\n m_logStream.println();\n\n } else {\n\n m_logStream.println();\n m_logStream.println(\"Calling script to reset the repository\");\n m_logStream.println(\"--------------------------------------\");\n m_logStream.println();\n\n }\n\n int exitCode = runCommitScript();\n if (exitCode != 0) {\n m_logStream.println();\n m_logStream.println(\"ERROR: Something went wrong. The script got exitcode \" + exitCode + \".\");\n m_logStream.println();\n }\n if ((exitCode == 0) && m_checkout) {\n boolean importOk = importModules();\n if (!importOk) {\n return -1;\n }\n }\n m_logStream.println(\"[\" + new Date() + \"] FINISHED Git task\");\n m_logStream.println();\n m_logStream.close();\n\n return exitCode;\n }",
"private void getDailyDates(Calendar calendar, int frequency, List<Date> dates)\n {\n while (moreDates(calendar, dates))\n {\n dates.add(calendar.getTime());\n calendar.add(Calendar.DAY_OF_YEAR, frequency);\n }\n }",
"public static double[][] invert(double[][] matrix) {\n\n\t\tif(isSolverUseApacheCommonsMath) {\n\t\t\t// Use LU from common math\n\t\t\tLUDecomposition lu = new LUDecomposition(new Array2DRowRealMatrix(matrix));\n\t\t\tdouble[][] matrixInverse = lu.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}",
"public static void closeWindow(Component component) {\n\n Window window = getWindow(component);\n if (window != null) {\n window.close();\n }\n }"
] |
Return the position of an element inside an array
@param array the array where it looks for an element
@param element the element to find in the array
@param <T> the type of elements in the array
@return the position of the element if it's found in the array, -1 otherwise | [
"public static <T> int indexOf(T[] array, T element) {\n\t\tfor ( int i = 0; i < array.length; i++ ) {\n\t\t\tif ( array[i].equals( element ) ) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\treturn -1;\n\t}"
] | [
"public static String getTextContent(Document document, boolean individualTokens) {\n String textContent = null;\n if (individualTokens) {\n List<String> tokens = getTextTokens(document);\n textContent = StringUtils.join(tokens, \",\");\n } else {\n textContent =\n document.getDocumentElement().getTextContent().trim().replaceAll(\"\\\\s+\", \",\");\n }\n return textContent;\n }",
"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 ReferenceDescriptorDef getReference(String name)\r\n {\r\n ReferenceDescriptorDef refDef;\r\n\r\n for (Iterator it = _references.iterator(); it.hasNext(); )\r\n {\r\n refDef = (ReferenceDescriptorDef)it.next();\r\n if (refDef.getName().equals(name))\r\n {\r\n return refDef;\r\n }\r\n }\r\n return null;\r\n }",
"public PhotoList<Photo> search(SearchParameters params, 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_SEARCH);\r\n\r\n parameters.putAll(params.getAsParameters());\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 = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n 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 DiffNode getChild(final NodePath nodePath)\n\t{\n\t\tif (parentNode != null)\n\t\t{\n\t\t\treturn parentNode.getChild(nodePath.getElementSelectors());\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn getChild(nodePath.getElementSelectors());\n\t\t}\n\t}",
"public final static int readXMLUntil(final StringBuilder out, final String in, final int start, final char... end)\n {\n int pos = start;\n boolean inString = false;\n char stringChar = 0;\n while (pos < in.length())\n {\n final char ch = in.charAt(pos);\n if (inString)\n {\n if (ch == '\\\\')\n {\n out.append(ch);\n pos++;\n if (pos < in.length())\n {\n out.append(ch);\n pos++;\n }\n continue;\n }\n if (ch == stringChar)\n {\n inString = false;\n out.append(ch);\n pos++;\n continue;\n }\n }\n switch (ch)\n {\n case '\"':\n case '\\'':\n inString = true;\n stringChar = ch;\n break;\n }\n if (!inString)\n {\n boolean endReached = false;\n for (int n = 0; n < end.length; n++)\n {\n if (ch == end[n])\n {\n endReached = true;\n break;\n }\n }\n if (endReached)\n {\n break;\n }\n }\n out.append(ch);\n pos++;\n }\n\n return (pos == in.length()) ? -1 : pos;\n }",
"private String formatDuration(Object value)\n {\n String result = null;\n if (value instanceof Duration)\n {\n Duration duration = (Duration) value;\n result = m_formats.getDurationDecimalFormat().format(duration.getDuration()) + formatTimeUnit(duration.getUnits());\n }\n return result;\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 }",
"public static dnssuffix get(nitro_service service, String Dnssuffix) throws Exception{\n\t\tdnssuffix obj = new dnssuffix();\n\t\tobj.set_Dnssuffix(Dnssuffix);\n\t\tdnssuffix response = (dnssuffix) obj.get_resource(service);\n\t\treturn response;\n\t}"
] |
Set the payload to the fileModel of the given instance even though the variable is not directly of it's type. This is mainly to simplify the
creation of the rule, when the FileModel itself is not being iterated but just a model referencing it. | [
"@Override\n public void perform(GraphRewrite event, EvaluationContext context)\n {\n checkVariableName(event, context);\n WindupVertexFrame payload = resolveVariable(event, getVariableName());\n if (payload instanceof FileReferenceModel)\n {\n FileModel file = ((FileReferenceModel) payload).getFile();\n perform(event, context, (XmlFileModel) file);\n }\n else\n {\n super.perform(event, context);\n }\n\n }"
] | [
"protected String toHexString(boolean with0xPrefix, CharSequence zone) {\n\t\tif(isDualString()) {\n\t\t\treturn toNormalizedStringRange(toIPParams(with0xPrefix ? IPStringCache.hexPrefixedParams : IPStringCache.hexParams), getLower(), getUpper(), zone);\n\t\t}\n\t\treturn toIPParams(with0xPrefix ? IPStringCache.hexPrefixedParams : IPStringCache.hexParams).toString(this, zone);\n\t}",
"private String decodeStr(String str) {\r\n try {\r\n return MimeUtility.decodeText(str);\r\n } catch (UnsupportedEncodingException e) {\r\n return str;\r\n }\r\n }",
"public void switchDataSource(BoneCPConfig newConfig) throws SQLException {\n\t\tlogger.info(\"Switch to new datasource requested. New Config: \"+newConfig);\n\t\tDataSource oldDS = getTargetDataSource();\n \n\t\tif (!(oldDS instanceof BoneCPDataSource)){\n\t\t\tthrow new SQLException(\"Unknown datasource type! Was expecting BoneCPDataSource but received \"+oldDS.getClass()+\". Not switching datasource!\");\n\t\t}\n\t\t\n\t\tBoneCPDataSource newDS = new BoneCPDataSource(newConfig);\n\t\tnewDS.getConnection().close(); // initialize a connection (+ throw it away) to force the datasource to initialize the pool\n\t\t\n\t\t// force application to start using the new one \n\t\tsetTargetDataSource(newDS);\n\t\t\n\t\tlogger.info(\"Shutting down old datasource slowly. Old Config: \"+oldDS);\n\t\t// tell the old datasource to terminate. This terminates the pool lazily so existing checked out connections can still be used.\n\t\t((BoneCPDataSource)oldDS).close();\n\t}",
"@JavaScriptMethod\n @SuppressWarnings({\"UnusedDeclaration\"})\n public LoadBuildsResponse loadBuild(String buildId) {\n LoadBuildsResponse response = new LoadBuildsResponse();\n // When we load a new build we need also to reset the promotion plugin.\n // The null plugin is related to 'None' plugin.\n setPromotionPlugin(null);\n try {\n this.currentPromotionCandidate = promotionCandidates.get(buildId);\n if (this.currentPromotionCandidate == null) {\n throw new IllegalArgumentException(\"Can't find build by ID: \" + buildId);\n }\n List<String> repositoryKeys = getRepositoryKeys();\n List<UserPluginInfo> plugins = getPromotionsUserPluginInfo();\n PromotionConfig promotionConfig = getPromotionConfig();\n String defaultTargetRepository = getDefaultPromotionTargetRepository();\n if (StringUtils.isNotBlank(defaultTargetRepository) && repositoryKeys.contains(defaultTargetRepository)) {\n promotionConfig.setTargetRepo(defaultTargetRepository);\n }\n response.addRepositories(repositoryKeys);\n response.setPlugins(plugins);\n response.setPromotionConfig(promotionConfig);\n response.setSuccess(true);\n } catch (Exception e) {\n response.setResponseMessage(e.getMessage());\n }\n return response;\n }",
"public UpdateBuilder<T, ID> updateColumnValue(String columnName, Object value) throws SQLException {\n\t\tFieldType fieldType = verifyColumnName(columnName);\n\t\tif (fieldType.isForeignCollection()) {\n\t\t\tthrow new SQLException(\"Can't update foreign colletion field: \" + columnName);\n\t\t}\n\t\taddUpdateColumnToList(columnName, new SetValue(columnName, fieldType, value));\n\t\treturn this;\n\t}",
"public static final Date getDate(InputStream is) throws IOException\n {\n long timeInSeconds = getInt(is);\n if (timeInSeconds == 0x93406FFF)\n {\n return null;\n }\n timeInSeconds -= 3600;\n timeInSeconds *= 1000;\n return DateHelper.getDateFromLong(timeInSeconds);\n }",
"public static sslcertkey_sslocspresponder_binding[] get(nitro_service service, String certkey) throws Exception{\n\t\tsslcertkey_sslocspresponder_binding obj = new sslcertkey_sslocspresponder_binding();\n\t\tobj.set_certkey(certkey);\n\t\tsslcertkey_sslocspresponder_binding response[] = (sslcertkey_sslocspresponder_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public final void updateLastCheckTime(final String id, final long lastCheckTime) {\n final CriteriaBuilder builder = getSession().getCriteriaBuilder();\n final CriteriaUpdate<PrintJobStatusExtImpl> update =\n builder.createCriteriaUpdate(PrintJobStatusExtImpl.class);\n final Root<PrintJobStatusExtImpl> root = update.from(PrintJobStatusExtImpl.class);\n update.where(builder.equal(root.get(\"referenceId\"), id));\n update.set(root.get(\"lastCheckTime\"), lastCheckTime);\n getSession().createQuery(update).executeUpdate();\n }",
"public <T> Map<String, List<T>> queryGroups(String query, Class<T> classOfT) {\r\n InputStream instream = null;\r\n try {\r\n Reader reader = new InputStreamReader(instream = queryForStream(query), \"UTF-8\");\r\n JsonObject json = new JsonParser().parse(reader).getAsJsonObject();\r\n Map<String, List<T>> result = new LinkedHashMap<String, List<T>>();\r\n if (json.has(\"groups\")) {\r\n for (JsonElement e : json.getAsJsonArray(\"groups\")) {\r\n String groupName = e.getAsJsonObject().get(\"by\").getAsString();\r\n List<T> orows = new ArrayList<T>();\r\n if (!includeDocs) {\r\n log.warning(\"includeDocs set to false and attempting to retrieve doc. \" +\r\n \"null object will be returned\");\r\n }\r\n for (JsonElement rows : e.getAsJsonObject().getAsJsonArray(\"rows\")) {\r\n orows.add(jsonToObject(client.getGson(), rows, \"doc\", classOfT));\r\n }\r\n result.put(groupName, orows);\r\n }// end for(groups)\r\n }// end hasgroups\r\n else {\r\n log.warning(\"No grouped results available. Use query() if non grouped query\");\r\n }\r\n return result;\r\n } catch (UnsupportedEncodingException e1) {\r\n // This should never happen as every implementation of the java platform is required\r\n // to support UTF-8.\r\n throw new RuntimeException(e1);\r\n } finally {\r\n close(instream);\r\n }\r\n }"
] |
compare between two points. | [
"public int compare(Vector3 o1, Vector3 o2) {\n\t\tint ans = 0;\n\n\t\tif (o1 != null && o2 != null) {\n\t\t\tVector3 d1 = o1;\n\t\t\tVector3 d2 = o2;\n\n\t\t\tif (d1.x > d2.x)\n\t\t\t\treturn 1;\n\t\t\tif (d1.x < d2.x)\n\t\t\t\treturn -1;\n\t\t\t// x1 == x2\n\t\t\tif (d1.y > d2.y)\n\t\t\t\treturn 1;\n\t\t\tif (d1.y < d2.y)\n\t\t\t\treturn -1;\n\t\t} else {\n\t\t\tif (o1 == null && o2 == null)\n\t\t\t\treturn 0;\n\t\t\tif (o1 == null && o2 != null)\n\t\t\t\treturn 1;\n\t\t\tif (o1 != null && o2 == null)\n\t\t\t\treturn -1;\n\t\t}\n\t\t\n\t\treturn ans;\n\t}"
] | [
"@SuppressWarnings(\"InsecureCryptoUsage\") // Only used in known-weak crypto \"legacy\" mode.\n static byte[] aes128Encrypt(StringBuilder message, String key) {\n try {\n key = normalizeString(key, 16);\n rightPadString(message, '{', 16);\n Cipher cipher = Cipher.getInstance(\"AES/ECB/NoPadding\");\n cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(), \"AES\"));\n return cipher.doFinal(message.toString().getBytes());\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }",
"public static base_responses delete(nitro_service client, String jsoncontenttypevalue[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (jsoncontenttypevalue != null && jsoncontenttypevalue.length > 0) {\n\t\t\tappfwjsoncontenttype deleteresources[] = new appfwjsoncontenttype[jsoncontenttypevalue.length];\n\t\t\tfor (int i=0;i<jsoncontenttypevalue.length;i++){\n\t\t\t\tdeleteresources[i] = new appfwjsoncontenttype();\n\t\t\t\tdeleteresources[i].jsoncontenttypevalue = jsoncontenttypevalue[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"public Excerpt typeParameters() {\n if (getTypeParameters().isEmpty()) {\n return Excerpts.EMPTY;\n } else {\n return Excerpts.add(\"<%s>\", Excerpts.join(\", \", getTypeParameters()));\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 getKey(int keyIndex, float[] values)\n {\n int index = keyIndex * mFloatsPerKey;\n System.arraycopy(mKeys, index + 1, values, 0, values.length);\n }",
"public void setAcquireRetryDelay(long acquireRetryDelay, TimeUnit timeUnit) {\n\t\tthis.acquireRetryDelayInMs = TimeUnit.MILLISECONDS.convert(acquireRetryDelay, timeUnit);\n\t}",
"private File[] getFilesFromProperty(final String name, final Properties props) {\n String sep = WildFlySecurityManager.getPropertyPrivileged(\"path.separator\", null);\n String value = props.getProperty(name, null);\n if (value != null) {\n final String[] paths = value.split(Pattern.quote(sep));\n final int len = paths.length;\n final File[] files = new File[len];\n for (int i = 0; i < len; i++) {\n files[i] = new File(paths[i]);\n }\n return files;\n }\n return NO_FILES;\n }",
"private void writeCustomField(CustomField field) throws IOException\n {\n if (field.getAlias() != null)\n {\n m_writer.writeStartObject(null);\n m_writer.writeNameValuePair(\"field_type_class\", field.getFieldType().getFieldTypeClass().name().toLowerCase());\n m_writer.writeNameValuePair(\"field_type\", field.getFieldType().name().toLowerCase());\n m_writer.writeNameValuePair(\"field_alias\", field.getAlias());\n m_writer.writeEndObject();\n }\n }",
"protected void finishBox()\n {\n \tif (textLine.length() > 0)\n \t{\n String s;\n if (isReversed(Character.getDirectionality(textLine.charAt(0))))\n s = textLine.reverse().toString();\n else\n s = textLine.toString();\n\n curstyle.setLeft(textMetrics.getX());\n curstyle.setTop(textMetrics.getTop());\n curstyle.setLineHeight(textMetrics.getHeight());\n\n\t renderText(s, textMetrics);\n\t textLine = new StringBuilder();\n\t textMetrics = null;\n \t}\n }"
] |
key function. first validate if the ACM has adequate data; then execute
it after the validation. the new ParallelTask task guareetee to have the
targethost meta and command meta not null
@param handler
the handler
@return the parallel task | [
"public ParallelTask execute(ParallecResponseHandler handler) {\n\n ParallelTask task = new ParallelTask();\n\n try {\n targetHostMeta = new TargetHostMeta(targetHosts);\n\n final ParallelTask taskReal = new ParallelTask(requestProtocol,\n concurrency, httpMeta, targetHostMeta, sshMeta, tcpMeta, udpMeta, pingMeta,\n handler, responseContext, \n replacementVarMapNodeSpecific, replacementVarMap,\n requestReplacementType, \n config);\n\n task = taskReal;\n\n logger.info(\"***********START_PARALLEL_HTTP_TASK_\"\n + task.getTaskId() + \"***********\");\n\n // throws ParallelTaskInvalidException\n task.validateWithFillDefault();\n\n task.setSubmitTime(System.currentTimeMillis());\n\n if (task.getConfig().isEnableCapacityAwareTaskScheduler()) {\n\n //late initialize the task scheduler\n ParallelTaskManager.getInstance().initTaskSchedulerIfNot();\n // add task to the wait queue\n ParallelTaskManager.getInstance().getWaitQ().add(task);\n\n logger.info(\"Enabled CapacityAwareTaskScheduler. Submitted task to waitQ in builder.. \"\n + task.getTaskId());\n\n } else {\n\n logger.info(\n \"Disabled CapacityAwareTaskScheduler. Immediately execute task {} \",\n task.getTaskId());\n\n Runnable director = new Runnable() {\n\n public void run() {\n ParallelTaskManager.getInstance()\n .generateUpdateExecuteTask(taskReal);\n }\n };\n new Thread(director).start();\n }\n\n if (this.getMode() == TaskRunMode.SYNC) {\n logger.info(\"Executing task {} in SYNC mode... \",\n task.getTaskId());\n\n while (task != null && !task.isCompleted()) {\n try {\n Thread.sleep(500L);\n } catch (InterruptedException e) {\n logger.error(\"InterruptedException \" + e);\n }\n }\n }\n } catch (ParallelTaskInvalidException ex) {\n\n logger.info(\"Request is invalid with missing parts. Details: \"\n + ex.getMessage() + \" Cannot execute at this time. \"\n + \" Please review your request and try again.\\nCommand:\"\n + httpMeta.toString());\n\n task.setState(ParallelTaskState.COMPLETED_WITH_ERROR);\n task.getTaskErrorMetas().add(\n new TaskErrorMeta(TaskErrorType.VALIDATION_ERROR,\n \"validation eror\"));\n\n } catch (Exception t) {\n logger.error(\"fail task builder. Unknown error: \" + t, t);\n task.setState(ParallelTaskState.COMPLETED_WITH_ERROR);\n task.getTaskErrorMetas().add(\n new TaskErrorMeta(TaskErrorType.UNKNOWN, \"unknown eror\",\n t));\n }\n\n logger.info(\"***********FINISH_PARALLEL_HTTP_TASK_\" + task.getTaskId()\n + \"***********\");\n return task;\n\n }"
] | [
"@SuppressWarnings(\"unchecked\")\n protected String addeDependency(Appliable<? extends Indexable> appliable) {\n TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) appliable;\n return this.addDependency(dependency);\n }",
"public static void checkDirectory(File directory) {\n if (!(directory.exists() || directory.mkdirs())) {\n throw new ReportGenerationException(\n String.format(\"Can't create data directory <%s>\", directory.getAbsolutePath())\n );\n }\n }",
"@Override\n public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)\n throws InterruptedException, IOException {\n listener.getLogger().println(\"Jenkins Artifactory Plugin version: \" + ActionableHelper.getArtifactoryPluginVersion());\n EnvVars env = build.getEnvironment(listener);\n FilePath workDir = build.getModuleRoot();\n FilePath ws = build.getWorkspace();\n FilePath mavenHome = getMavenHome(listener, env, launcher);\n\n if (!mavenHome.exists()) {\n listener.error(\"Couldn't find Maven home: \" + mavenHome.getRemote());\n throw new Run.RunnerAbortedException();\n }\n ArgumentListBuilder cmdLine = buildMavenCmdLine(build, listener, env, launcher, mavenHome, ws, ws);\n String[] cmds = cmdLine.toCommandArray();\n return RunMaven(build, launcher, listener, env, workDir, cmds);\n }",
"public Class<E> getEventClass() {\n if (cachedClazz != null) {\n return cachedClazz;\n }\n Class<?> clazz = this.getClass();\n while (clazz != Object.class) {\n try {\n Type mySuperclass = clazz.getGenericSuperclass();\n Type tType = ((ParameterizedType) mySuperclass).getActualTypeArguments()[0];\n cachedClazz = (Class<E>) Class.forName(tType.getTypeName());\n return cachedClazz;\n } catch (Exception e) {\n }\n clazz = clazz.getSuperclass();\n }\n throw new IllegalStateException(\"Failed to load event class - \" + this.getClass().getCanonicalName());\n }",
"private void ensureReferencedFKs(ModelDef modelDef, CollectionDescriptorDef collDef) throws ConstraintException\r\n {\r\n String elementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF);\r\n ClassDescriptorDef elementClassDef = modelDef.getClass(elementClassName);\r\n String fkFieldNames = collDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY);\r\n ArrayList missingFields = new ArrayList();\r\n SequencedHashMap fkFields = new SequencedHashMap();\r\n\r\n // first we gather all field names\r\n for (CommaListIterator it = new CommaListIterator(fkFieldNames); it.hasNext();)\r\n {\r\n String fieldName = (String)it.next();\r\n FieldDescriptorDef fieldDef = elementClassDef.getField(fieldName);\r\n\r\n if (fieldDef == null)\r\n {\r\n missingFields.add(fieldName);\r\n }\r\n fkFields.put(fieldName, fieldDef);\r\n }\r\n\r\n // next we traverse all sub types and gather fields as we go\r\n for (Iterator it = elementClassDef.getAllExtentClasses(); it.hasNext() && !missingFields.isEmpty();)\r\n {\r\n ClassDescriptorDef subTypeDef = (ClassDescriptorDef)it.next();\r\n\r\n for (int idx = 0; idx < missingFields.size();)\r\n {\r\n FieldDescriptorDef fieldDef = subTypeDef.getField((String)missingFields.get(idx));\r\n\r\n if (fieldDef != null)\r\n {\r\n fkFields.put(fieldDef.getName(), fieldDef);\r\n missingFields.remove(idx);\r\n }\r\n else\r\n {\r\n idx++;\r\n }\r\n }\r\n }\r\n if (!missingFields.isEmpty())\r\n {\r\n throw new ConstraintException(\"Cannot find field \"+missingFields.get(0).toString()+\" in the hierarchy with root type \"+\r\n elementClassDef.getName()+\" which is used as foreignkey in collection \"+\r\n collDef.getName()+\" in \"+collDef.getOwner().getName());\r\n }\r\n\r\n // copy the found fields into the element class\r\n ensureFields(elementClassDef, fkFields.values());\r\n }",
"private List<Row> createExceptionAssignmentRowList(String exceptionData)\n {\n List<Row> list = new ArrayList<Row>();\n String[] exceptions = exceptionData.split(\",|:\");\n int index = 1;\n while (index < exceptions.length)\n {\n Date startDate = DatatypeConverter.parseEpochTimestamp(exceptions[index + 0]);\n Date endDate = DatatypeConverter.parseEpochTimestamp(exceptions[index + 1]);\n //Integer exceptionTypeID = Integer.valueOf(exceptions[index + 2]);\n\n Map<String, Object> map = new HashMap<String, Object>();\n map.put(\"STARU_DATE\", startDate);\n map.put(\"ENE_DATE\", endDate);\n\n list.add(new MapRow(map));\n\n index += 3;\n }\n\n return list;\n }",
"public static base_responses update(nitro_service client, responderpolicy resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tresponderpolicy updateresources[] = new responderpolicy[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new responderpolicy();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].rule = resources[i].rule;\n\t\t\t\tupdateresources[i].action = resources[i].action;\n\t\t\t\tupdateresources[i].undefaction = resources[i].undefaction;\n\t\t\t\tupdateresources[i].comment = resources[i].comment;\n\t\t\t\tupdateresources[i].logaction = resources[i].logaction;\n\t\t\t\tupdateresources[i].appflowaction = resources[i].appflowaction;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public ModelNode toModelNode() {\n final ModelNode node = new ModelNode().setEmptyList();\n for (PathElement element : pathAddressList) {\n final String value;\n if (element.isMultiTarget() && !element.isWildcard()) {\n value = '[' + element.getValue() + ']';\n } else {\n value = element.getValue();\n }\n node.add(element.getKey(), value);\n }\n return node;\n }",
"public static AppDescriptor of(String appName, Class<?> entryClass) {\n System.setProperty(\"osgl.version.suppress-var-found-warning\", \"true\");\n return of(appName, entryClass, Version.of(entryClass));\n }"
] |
Facade method for operating the Shell.
Run the obtained Shell with commandLoop().
@see org.gearvrf.debug.cli.Shell#Shell(org.gearvrf.debug.cli.Shell.Settings, org.gearvrf.debug.cli.CommandTable, java.util.List)
@param prompt Prompt to be displayed
@param appName The app name string
@param mainHandler Command handler
@return Shell that can be either further customized or run directly by calling commandLoop(). | [
"public static Shell createConsoleShell(String prompt, String appName, Object mainHandler) {\n return createConsoleShell(prompt, appName, mainHandler, new EmptyMultiMap<String, Object>());\n }"
] | [
"protected boolean waitForJobs() throws InterruptedException {\n final Pair<Long, Job> peekPair;\n try (Guard ignored = timeQueue.lock()) {\n peekPair = timeQueue.peekPair();\n }\n if (peekPair == null) {\n awake.acquire();\n return true;\n }\n final long timeout = Long.MAX_VALUE - peekPair.getFirst() - System.currentTimeMillis();\n if (timeout < 0) {\n return false;\n }\n return awake.tryAcquire(timeout, TimeUnit.MILLISECONDS);\n }",
"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}",
"public static ModelNode addCurrentServerGroupsToHostInfoModel(boolean ignoreUnaffectedServerGroups, Resource hostModel, ModelNode model) {\n if (!ignoreUnaffectedServerGroups) {\n return model;\n }\n model.get(IGNORE_UNUSED_CONFIG).set(ignoreUnaffectedServerGroups);\n addServerGroupsToModel(hostModel, model);\n return model;\n }",
"private void updateBaseCalendarNames(List<Pair<ProjectCalendar, Integer>> baseCalendars)\n {\n for (Pair<ProjectCalendar, Integer> pair : baseCalendars)\n {\n ProjectCalendar cal = pair.getFirst();\n Integer baseCalendarID = pair.getSecond();\n ProjectCalendar baseCal = m_calendarMap.get(baseCalendarID);\n if (baseCal != null)\n {\n cal.setParent(baseCal);\n }\n }\n }",
"@SuppressWarnings(\"unchecked\")\n public static <E> E getObject(String className) {\n if (className == null) {\n return (E) null;\n }\n try {\n return (E) Class.forName(className).newInstance();\n } catch (InstantiationException e) {\n throw new RuntimeException(e);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n }",
"public void addPropertyChangeListener (String propertyName, java.beans.PropertyChangeListener listener)\r\n {\r\n this.propertyChangeDelegate.addPropertyChangeListener(propertyName, listener);\r\n }",
"public GenericCriteria process(ProjectProperties properties, byte[] data, int dataOffset, int entryOffset, List<GenericCriteriaPrompt> prompts, List<FieldType> fields, boolean[] criteriaType)\n {\n m_properties = properties;\n m_prompts = prompts;\n m_fields = fields;\n m_criteriaType = criteriaType;\n m_dataOffset = dataOffset;\n if (m_criteriaType != null)\n {\n m_criteriaType[0] = true;\n m_criteriaType[1] = true;\n }\n\n m_criteriaBlockMap.clear();\n\n m_criteriaData = data;\n m_criteriaTextStart = MPPUtility.getShort(m_criteriaData, m_dataOffset + getCriteriaTextStartOffset());\n\n //\n // Populate the map\n //\n int criteriaStartOffset = getCriteriaStartOffset();\n int criteriaBlockSize = getCriteriaBlockSize();\n\n //System.out.println();\n //System.out.println(ByteArrayHelper.hexdump(data, dataOffset, criteriaStartOffset, false));\n\n if (m_criteriaData.length <= m_criteriaTextStart)\n {\n return null; // bad data\n }\n\n while (criteriaStartOffset + criteriaBlockSize <= m_criteriaTextStart)\n {\n byte[] block = new byte[criteriaBlockSize];\n System.arraycopy(m_criteriaData, m_dataOffset + criteriaStartOffset, block, 0, criteriaBlockSize);\n m_criteriaBlockMap.put(Integer.valueOf(criteriaStartOffset), block);\n //System.out.println(Integer.toHexString(criteriaStartOffset) + \": \" + ByteArrayHelper.hexdump(block, false));\n criteriaStartOffset += criteriaBlockSize;\n }\n\n if (entryOffset == -1)\n {\n entryOffset = getCriteriaStartOffset();\n }\n\n List<GenericCriteria> list = new LinkedList<GenericCriteria>();\n processBlock(list, m_criteriaBlockMap.get(Integer.valueOf(entryOffset)));\n GenericCriteria criteria;\n if (list.isEmpty())\n {\n criteria = null;\n }\n else\n {\n criteria = list.get(0);\n }\n return criteria;\n }",
"@SuppressWarnings(\"unchecked\")\n public Multimap<String, Processor> getAllRequiredAttributes() {\n Multimap<String, Processor> requiredInputs = HashMultimap.create();\n for (ProcessorGraphNode root: this.roots) {\n final BiMap<String, String> inputMapper = root.getInputMapper();\n for (String attr: inputMapper.keySet()) {\n requiredInputs.put(attr, root.getProcessor());\n }\n final Object inputParameter = root.getProcessor().createInputParameter();\n if (inputParameter instanceof Values) {\n continue;\n } else if (inputParameter != null) {\n final Class<?> inputParameterClass = inputParameter.getClass();\n final Set<String> requiredAttributesDefinedInInputParameter =\n getAttributeNames(inputParameterClass,\n FILTER_ONLY_REQUIRED_ATTRIBUTES);\n for (String attName: requiredAttributesDefinedInInputParameter) {\n try {\n if (inputParameterClass.getField(attName).getType() == Values.class) {\n continue;\n }\n } catch (NoSuchFieldException e) {\n throw new RuntimeException(e);\n }\n String mappedName = ProcessorUtils.getInputValueName(\n root.getProcessor().getInputPrefix(),\n inputMapper, attName);\n requiredInputs.put(mappedName, root.getProcessor());\n }\n }\n }\n\n return requiredInputs;\n }",
"public static void rebuild(final MODE newMode) {\n if (mode != newMode) {\n mode = newMode;\n TYPE type;\n switch (mode) {\n case DEBUG:\n type = TYPE.ANDROID;\n Log.startFullLog();\n break;\n case DEVELOPER:\n type = TYPE.PERSISTENT;\n Log.stopFullLog();\n break;\n case USER:\n type = TYPE.ANDROID;\n break;\n default:\n type = DEFAULT_TYPE;\n Log.stopFullLog();\n break;\n }\n currentLog = getLog(type);\n }\n }"
] |
A static method that provides an easy way to create a list of a
certain parametric type.
This static constructor works better with generics.
@param list The list to pad
@param padding The padding element (may be null)
@return The padded list | [
"public static <IN> PaddedList<IN> valueOf(List<IN> list, IN padding) {\r\n return new PaddedList<IN>(list, padding);\r\n }"
] | [
"@JmxOperation(description = \"Forcefully invoke the log cleaning\")\n public void cleanLogs() {\n synchronized(lock) {\n try {\n for(Environment environment: environments.values()) {\n environment.cleanLog();\n }\n } catch(DatabaseException e) {\n throw new VoldemortException(e);\n }\n }\n }",
"private ProjectFile handleMDBFile(InputStream stream) throws Exception\n {\n File file = InputStreamHelper.writeStreamToTempFile(stream, \".mdb\");\n\n try\n {\n Class.forName(\"sun.jdbc.odbc.JdbcOdbcDriver\");\n String url = \"jdbc:odbc:DRIVER=Microsoft Access Driver (*.mdb);DBQ=\" + file.getCanonicalPath();\n Set<String> tableNames = populateTableNames(url);\n\n if (tableNames.contains(\"MSP_PROJECTS\"))\n {\n return readProjectFile(new MPDDatabaseReader(), file);\n }\n\n if (tableNames.contains(\"EXCEPTIONN\"))\n {\n return readProjectFile(new AstaDatabaseReader(), file);\n }\n\n return null;\n }\n\n finally\n {\n FileHelper.deleteQuietly(file);\n }\n }",
"@PreDestroy\n public final void shutdown() {\n this.timer.shutdownNow();\n this.executor.shutdownNow();\n if (this.cleanUpTimer != null) {\n this.cleanUpTimer.shutdownNow();\n }\n }",
"static String tokenize(PageMetadata<?, ?> pageMetadata) {\n try {\n Gson g = getGsonWithKeyAdapter(pageMetadata.pageRequestParameters);\n return new String(Base64.encodeBase64URLSafe(g.toJson(new PaginationToken\n (pageMetadata)).getBytes(\"UTF-8\")),\n Charset.forName(\"UTF-8\"));\n } catch (UnsupportedEncodingException e) {\n //all JVMs should support UTF-8\n throw new RuntimeException(e);\n }\n }",
"public T mapRow(ResultSet rs) throws SQLException {\n Map<String, Object> map = new HashMap<String, Object>();\n ResultSetMetaData metadata = rs.getMetaData();\n\n for (int i = 1; i <= metadata.getColumnCount(); ++i) {\n String label = metadata.getColumnLabel(i);\n\n final Object value;\n // calling getObject on a BLOB/CLOB produces weird results\n switch (metadata.getColumnType(i)) {\n case Types.BLOB:\n value = rs.getBytes(i);\n break;\n case Types.CLOB:\n value = rs.getString(i);\n break;\n default:\n value = rs.getObject(i);\n }\n\n // don't use table name extractor because we don't want aliased table name\n boolean overwrite = this.tableName != null && this.tableName.equals(metadata.getTableName(i));\n String tableName = TABLE_NAME_EXTRACTOR.getTableName(metadata, i);\n if (tableName != null && !tableName.isEmpty()) {\n String qualifiedName = tableName + \".\" + metadata.getColumnName(i);\n add(map, qualifiedName, value, overwrite);\n }\n\n add(map, label, value, overwrite);\n }\n\n return objectMapper.convertValue(map, type);\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 static void sendEvent(Context context, Parcelable event) {\n Intent intent = new Intent(EventManager.ACTION_ACCESSORY_EVENT);\n intent.putExtra(EventManager.EXTRA_EVENT, event);\n context.sendBroadcast(intent);\n }",
"public void setAcquireRetryDelay(long acquireRetryDelay, TimeUnit timeUnit) {\n\t\tthis.acquireRetryDelayInMs = TimeUnit.MILLISECONDS.convert(acquireRetryDelay, timeUnit);\n\t}",
"public Duration getStartSlack()\n {\n Duration startSlack = (Duration) getCachedValue(TaskField.START_SLACK);\n if (startSlack == null)\n {\n Duration duration = getDuration();\n if (duration != null)\n {\n startSlack = DateHelper.getVariance(this, getEarlyStart(), getLateStart(), duration.getUnits());\n set(TaskField.START_SLACK, startSlack);\n }\n }\n return (startSlack);\n }"
] |
Creates a new deployment for the file. If the file is a directory the content will be deployed exploded using
the file system location.
@param content the file containing the content
@return the deployment | [
"public static Deployment of(final File content) {\n final DeploymentContent deploymentContent = DeploymentContent.of(Assert.checkNotNullParam(\"content\", content).toPath());\n return new Deployment(deploymentContent, null);\n }"
] | [
"public Set<TupleOperation> getOperations() {\n\t\tif ( currentState == null ) {\n\t\t\treturn Collections.emptySet();\n\t\t}\n\t\telse {\n\t\t\treturn new SetFromCollection<TupleOperation>( currentState.values() );\n\t\t}\n\t}",
"public void setName(int pathId, String pathName) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + Constants.PATH_PROFILE_PATHNAME + \" = ?\" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, pathName);\n statement.setInt(2, pathId);\n statement.executeUpdate();\n statement.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }",
"public float[] getFloatArray(String attributeName)\n {\n float[] array = NativeVertexBuffer.getFloatArray(getNative(), attributeName);\n if (array == null)\n {\n throw new IllegalArgumentException(\"Attribute name \" + attributeName + \" cannot be accessed\");\n }\n return array;\n }",
"public void setRotation(String rotation) {\r\n if (rotation != null) {\r\n try {\r\n setRotation(Integer.parseInt(rotation));\r\n } catch (NumberFormatException e) {\r\n setRotation(-1);\r\n }\r\n }\r\n }",
"public Collection<String> getCurrencyCodes() {\n Collection<String> result = get(KEY_QUERY_CURRENCY_CODES, Collection.class);\n if (result == null) {\n return Collections.emptySet();\n }\n return result;\n }",
"private Video generateRandomVideo() {\n Video video = new Video();\n configureFavoriteStatus(video);\n configureLikeStatus(video);\n configureLiveStatus(video);\n configureTitleAndThumbnail(video);\n return video;\n }",
"private void executeResult() throws Exception {\n\t\tresult = createResult();\n\n\t\tString timerKey = \"executeResult: \" + getResultCode();\n\t\ttry {\n\t\t\tUtilTimerStack.push(timerKey);\n\t\t\tif (result != null) {\n\t\t\t\tresult.execute(this);\n\t\t\t} else if (resultCode != null && !Action.NONE.equals(resultCode)) {\n\t\t\t\tthrow new ConfigurationException(\"No result defined for action \" + getAction().getClass().getName()\n\t\t\t\t\t\t+ \" and result \" + getResultCode(), proxy.getConfig());\n\t\t\t} else {\n\t\t\t\tif (LOG.isDebugEnabled()) {\n\t\t\t\t\tLOG.debug(\"No result returned for action \" + getAction().getClass().getName() + \" at \"\n\t\t\t\t\t\t\t+ proxy.getConfig().getLocation());\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tUtilTimerStack.pop(timerKey);\n\t\t}\n\t}",
"public DiscreteInterval minus(DiscreteInterval other) {\n return new DiscreteInterval(this.min - other.max, this.max - other.min);\n }",
"public JsonNode apply(final JsonNode node) {\n requireNonNull(node, \"node\");\n JsonNode ret = node.deepCopy();\n for (final JsonPatchOperation operation : operations) {\n ret = operation.apply(ret);\n }\n\n return ret;\n }"
] |
Resize and return the image passing the new height and width
@param height
@param width
@return | [
"public BufferedImage getBufferedImage(int width, int height) {\n // using the new approach of Java 2D API\n BufferedImage buf = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);\n Graphics2D g2d = (Graphics2D) buf.getGraphics();\n g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);\n g2d.drawImage(image, 0, 0, width, height, null);\n g2d.dispose();\n return (buf);\n }"
] | [
"public static Map<String, List<String>> getResponseHeaders(String stringUrl,\n boolean followRedirects) throws IOException {\n URL url = new URL(stringUrl);\n HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n conn.setInstanceFollowRedirects(followRedirects);\n \n InputStream is = conn.getInputStream();\n if (\"gzip\".equals(conn.getContentEncoding())) {\n is = new GZIPInputStream(is);\n }\n\n Map<String, List<String>> headers = new LinkedHashMap<String, List<String>>(conn.getHeaderFields());\n headers.put(\"X-Content\", Arrays.asList(MyStreamUtils.readContent(is)));\n headers.put(\"X-URL\", Arrays.asList(conn.getURL().toString()));\n headers.put(\"X-Status\", Arrays.asList(String.valueOf(conn.getResponseCode())));\n \n return headers;\n }",
"public static base_response enable(nitro_service client, String acl6name) throws Exception {\n\t\tnsacl6 enableresource = new nsacl6();\n\t\tenableresource.acl6name = acl6name;\n\t\treturn enableresource.perform_operation(client,\"enable\");\n\t}",
"public static void closeMASCaseManager(File caseManager) {\n\n FileWriter caseManagerWriter;\n try {\n caseManagerWriter = new FileWriter(caseManager, true);\n caseManagerWriter.write(\"}\\n\");\n caseManagerWriter.flush();\n caseManagerWriter.close();\n } catch (IOException e) {\n Logger logger = Logger\n .getLogger(\"CreateMASCaseManager.closeMASCaseManager\");\n logger.info(\"ERROR: There is a mistake closing caseManager file.\\n\");\n }\n\n }",
"public static base_responses add(nitro_service client, ntpserver resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tntpserver addresources[] = new ntpserver[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new ntpserver();\n\t\t\t\taddresources[i].serverip = resources[i].serverip;\n\t\t\t\taddresources[i].servername = resources[i].servername;\n\t\t\t\taddresources[i].minpoll = resources[i].minpoll;\n\t\t\t\taddresources[i].maxpoll = resources[i].maxpoll;\n\t\t\t\taddresources[i].autokey = resources[i].autokey;\n\t\t\t\taddresources[i].key = resources[i].key;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"public List<Object> getAll(int dataSet) throws SerializationException {\r\n\t\tList<Object> result = new ArrayList<Object>();\r\n\t\tfor (Iterator<DataSet> i = dataSets.iterator(); i.hasNext();) {\r\n\t\t\tDataSet ds = i.next();\r\n\t\t\tDataSetInfo info = ds.getInfo();\r\n\t\t\tif (info.getDataSetNumber() == dataSet) {\r\n\t\t\t\tresult.add(getData(ds));\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn result;\r\n\t}",
"public static MediaType binary( MediaType.Type type, String subType ) {\n return new MediaType( type, subType, true );\n }",
"private void writeMap(String fieldName, Object value) throws IOException\n {\n @SuppressWarnings(\"unchecked\")\n Map<String, Object> map = (Map<String, Object>) value;\n m_writer.writeStartObject(fieldName);\n for (Map.Entry<String, Object> entry : map.entrySet())\n {\n Object entryValue = entry.getValue();\n if (entryValue != null)\n {\n DataType type = TYPE_MAP.get(entryValue.getClass().getName());\n if (type == null)\n {\n type = DataType.STRING;\n entryValue = entryValue.toString();\n }\n writeField(entry.getKey(), type, entryValue);\n }\n }\n m_writer.writeEndObject();\n }",
"private FieldType findForeignFieldType(Class<?> clazz, Class<?> foreignClass, Dao<?, ?> foreignDao)\n\t\t\tthrows SQLException {\n\t\tString foreignColumnName = fieldConfig.getForeignCollectionForeignFieldName();\n\t\tfor (FieldType fieldType : foreignDao.getTableInfo().getFieldTypes()) {\n\t\t\tif (fieldType.getType() == foreignClass\n\t\t\t\t\t&& (foreignColumnName == null || fieldType.getField().getName().equals(foreignColumnName))) {\n\t\t\t\tif (!fieldType.fieldConfig.isForeign() && !fieldType.fieldConfig.isForeignAutoRefresh()) {\n\t\t\t\t\t// this may never be reached\n\t\t\t\t\tthrow new SQLException(\"Foreign collection object \" + clazz + \" for field '\" + field.getName()\n\t\t\t\t\t\t\t+ \"' contains a field of class \" + foreignClass + \" but it's not foreign\");\n\t\t\t\t}\n\t\t\t\treturn fieldType;\n\t\t\t}\n\t\t}\n\t\t// build our complex error message\n\t\tStringBuilder sb = new StringBuilder();\n\t\tsb.append(\"Foreign collection class \").append(clazz.getName());\n\t\tsb.append(\" for field '\").append(field.getName()).append(\"' column-name does not contain a foreign field\");\n\t\tif (foreignColumnName != null) {\n\t\t\tsb.append(\" named '\").append(foreignColumnName).append('\\'');\n\t\t}\n\t\tsb.append(\" of class \").append(foreignClass.getName());\n\t\tthrow new SQLException(sb.toString());\n\t}",
"public static Statement open(String driverklass, String jdbcuri,\n Properties props) {\n try {\n Driver driver = (Driver) ObjectUtils.instantiate(driverklass);\n Connection conn = driver.connect(jdbcuri, props);\n if (conn == null)\n throw new DukeException(\"Couldn't connect to database at \" +\n jdbcuri);\n return conn.createStatement();\n\n } catch (SQLException e) {\n throw new DukeException(e);\n }\n }"
] |
Perform a security check against OpenCms.
@param cms The OpenCms object.
@throws CmsPermissionViolationException in case of the anonymous guest user | [
"private void performPermissionCheck(CmsObject cms) throws CmsPermissionViolationException {\n\n if (cms.getRequestContext().getCurrentUser().isGuestUser()) {\n throw new CmsPermissionViolationException(null);\n }\n }"
] | [
"public static String decodeUrlIso(String stringToDecode) {\n try {\n return URLDecoder.decode(stringToDecode, \"ISO-8859-1\");\n } catch (UnsupportedEncodingException e1) {\n throw new RuntimeException(e1);\n }\n }",
"public <T> T fetchObject(String objectId, Class<T> type) {\n\t\tURI uri = URIBuilder.fromUri(getBaseGraphApiUrl() + objectId).build();\n\t\treturn getRestTemplate().getForObject(uri, type);\n\t}",
"public void prepareServer() {\n try {\n server = new Server(0);\n jettyHandler = new AbstractHandler() {\n public void handle(String target, Request req, HttpServletRequest request,\n HttpServletResponse response) throws IOException, ServletException {\n response.setContentType(\"text/plain\");\n\n String[] operands = request.getRequestURI().split(\"/\");\n\n String name = \"\";\n String command = \"\";\n String value = \"\";\n\n //operands[0] = \"\", request starts with a \"/\"\n\n if (operands.length >= 2) {\n name = operands[1];\n }\n\n if (operands.length >= 3) {\n command = operands[2];\n }\n\n if (operands.length >= 4) {\n value = operands[3];\n }\n\n if (command.equals(\"report\")) { //report a number of lines written\n response.getWriter().write(makeReport(name, value));\n } else if (command.equals(\"request\") && value.equals(\"block\")) { //request a new block of work\n response.getWriter().write(requestBlock(name));\n } else if (command.equals(\"request\") && value.equals(\"name\")) { //request a new name to report with\n response.getWriter().write(requestName());\n } else { //non recognized response\n response.getWriter().write(\"exit\");\n }\n\n ((Request) request).setHandled(true);\n }\n };\n\n server.setHandler(jettyHandler);\n\n // Select any available port\n server.start();\n Connector[] connectors = server.getConnectors();\n NetworkConnector nc = (NetworkConnector) connectors[0];\n listeningPort = nc.getLocalPort();\n hostName = InetAddress.getLocalHost().getHostName();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }",
"public static String getContext(final PObject[] objs) {\n StringBuilder result = new StringBuilder(\"(\");\n boolean first = true;\n for (PObject obj: objs) {\n if (!first) {\n result.append('|');\n }\n first = false;\n result.append(obj.getCurrentPath());\n }\n result.append(')');\n return result.toString();\n }",
"private void readWBS(ChildTaskContainer parent, Integer id)\n {\n Integer currentID = id;\n Table table = getTable(\"WBSTAB\");\n\n while (currentID.intValue() != 0)\n {\n MapRow row = table.find(currentID);\n Integer taskID = row.getInteger(\"TASK_ID\");\n Task task = readTask(parent, taskID);\n Integer childID = row.getInteger(\"CHILD_ID\");\n if (childID.intValue() != 0)\n {\n readWBS(task, childID);\n }\n currentID = row.getInteger(\"NEXT_ID\");\n }\n }",
"public ClientConfig setIdleConnectionTimeout(long idleConnectionTimeout, TimeUnit unit) {\n if (idleConnectionTimeout <= 0) {\n this.idleConnectionTimeoutMs = -1;\n } else {\n if(unit.toMinutes(idleConnectionTimeout) < 10) {\n throw new IllegalArgumentException(\"idleConnectionTimeout should be minimum of 10 minutes\");\n }\n this.idleConnectionTimeoutMs = unit.toMillis(idleConnectionTimeout);\n }\n return this;\n }",
"private synchronized Class<?> getClass(String className) throws Exception {\n // see if we need to invalidate the class\n ClassInformation classInfo = classInformation.get(className);\n File classFile = new File(classInfo.pluginPath);\n if (classFile.lastModified() > classInfo.lastModified) {\n logger.info(\"Class {} has been modified, reloading\", className);\n logger.info(\"Thread ID: {}\", Thread.currentThread().getId());\n classInfo.loaded = false;\n classInformation.put(className, classInfo);\n\n // also cleanup anything in methodInformation with this className so it gets reloaded\n Iterator<Map.Entry<String, com.groupon.odo.proxylib.models.Method>> iter = methodInformation.entrySet().iterator();\n while (iter.hasNext()) {\n Map.Entry<String, com.groupon.odo.proxylib.models.Method> entry = iter.next();\n if (entry.getKey().startsWith(className)) {\n iter.remove();\n }\n }\n }\n\n if (!classInfo.loaded) {\n loadClass(className);\n }\n\n return classInfo.loadedClass;\n }",
"public static int[] binaryToRgb(boolean[] binaryArray) {\n int[] rgbArray = new int[binaryArray.length];\n\n for (int i = 0; i < binaryArray.length; i++) {\n if (binaryArray[i]) {\n rgbArray[i] = 0x00000000;\n } else {\n rgbArray[i] = 0x00FFFFFF;\n }\n }\n return rgbArray;\n }",
"public void fire(StepEvent event) {\n Step step = stepStorage.getLast();\n event.process(step);\n\n notifier.fire(event);\n }"
] |
try to delegate the master to handle the response
@param response
@return true if the master accepted the response; false if the master
didn't accept | [
"public synchronized boolean tryDelegateResponseHandling(Response<ByteArray, Object> response) {\n if(responseHandlingCutoff) {\n return false;\n } else {\n responseQueue.offer(response);\n this.notifyAll();\n return true;\n }\n }"
] | [
"protected void resize( VariableMatrix mat , int numRows , int numCols ) {\n if( mat.isTemp() ) {\n mat.matrix.reshape(numRows,numCols);\n }\n }",
"protected void internalClose() throws SQLException {\r\n\t\ttry {\r\n\t\t\tclearStatementCaches(true);\r\n\t\t\tif (this.connection != null){ // safety!\r\n\t\t\t\tthis.connection.close();\r\n\r\n\t\t\t\tif (!this.connectionTrackingDisabled && this.finalizableRefs != null){\r\n\t\t\t\t\tthis.finalizableRefs.remove(this.connection);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tthis.logicallyClosed.set(true);\r\n\t\t} catch (SQLException e) {\r\n\t\t\tthrow markPossiblyBroken(e);\r\n\t\t}\r\n\t}",
"public static <T extends CharSequence> T eachMatch(T self, CharSequence regex, @ClosureParams(value=FromString.class, options={\"List<String>\",\"String[]\"}) Closure closure) {\n eachMatch(self.toString(), regex.toString(), closure);\n return self;\n }",
"public String getResourcePath()\n {\n switch (resourceType)\n {\n case ANDROID_ASSETS: return assetPath;\n\n case ANDROID_RESOURCE: return resourceFilePath;\n\n case LINUX_FILESYSTEM: return filePath;\n\n case NETWORK: return url.getPath();\n\n case INPUT_STREAM: return inputStreamName;\n\n default: return null;\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 }",
"public ItemRequest<Task> addFollowers(String task) {\n \n String path = String.format(\"/tasks/%s/addFollowers\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }",
"public RuleEnvelope getRule(String ruleId) throws ApiException {\n ApiResponse<RuleEnvelope> resp = getRuleWithHttpInfo(ruleId);\n return resp.getData();\n }",
"public ResourceAssignment addResourceAssignment(Resource resource)\n {\n ResourceAssignment assignment = getExistingResourceAssignment(resource);\n\n if (assignment == null)\n {\n assignment = new ResourceAssignment(getParentFile(), this);\n m_assignments.add(assignment);\n getParentFile().getResourceAssignments().add(assignment);\n\n assignment.setTaskUniqueID(getUniqueID());\n assignment.setWork(getDuration());\n assignment.setUnits(ResourceAssignment.DEFAULT_UNITS);\n\n if (resource != null)\n {\n assignment.setResourceUniqueID(resource.getUniqueID());\n resource.addResourceAssignment(assignment);\n }\n }\n\n return (assignment);\n }",
"public static void divideElementsCol(final int blockLength ,\n final DSubmatrixD1 Y , final int col , final double val ) {\n final int width = Math.min(blockLength,Y.col1-Y.col0);\n\n final double dataY[] = Y.original.data;\n\n for( int i = Y.row0; i < Y.row1; i += blockLength ) {\n int height = Math.min( blockLength , Y.row1 - i );\n\n int index = i*Y.original.numCols + height*Y.col0 + col;\n\n if( i == Y.row0 ) {\n index += width*(col+1);\n\n for( int k = col+1; k < height; k++ , index += width ) {\n dataY[index] /= val;\n }\n } else {\n int endIndex = index + width*height;\n //for( int k = 0; k < height; k++\n for( ; index != endIndex; index += width ) {\n dataY[index] /= val;\n }\n }\n }\n }"
] |
Invite a user to an enterprise.
@param api the API connection to use for the request.
@param userLogin the login of the user to invite.
@param enterpriseID the ID of the enterprise to invite the user to.
@return the invite info. | [
"public static Info inviteUserToEnterprise(BoxAPIConnection api, String userLogin, String enterpriseID) {\n\n URL url = INVITE_CREATION_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n\n JsonObject body = new JsonObject();\n\n JsonObject enterprise = new JsonObject();\n enterprise.add(\"id\", enterpriseID);\n body.add(\"enterprise\", enterprise);\n\n JsonObject actionableBy = new JsonObject();\n actionableBy.add(\"login\", userLogin);\n body.add(\"actionable_by\", actionableBy);\n\n request.setBody(body);\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxInvite invite = new BoxInvite(api, responseJSON.get(\"id\").asString());\n return invite.new Info(responseJSON);\n }"
] | [
"private void modifyBeliefCount(int count){\n introspector.setBeliefValue(getLocalName(), Definitions.RECEIVED_MESSAGE_COUNT, getBeliefCount()+count, null);\n }",
"public static PipelineConfiguration.Builder parse(ModelNode json) {\n ModelNode analyzerIncludeNode = json.get(\"analyzers\").get(\"include\");\n ModelNode analyzerExcludeNode = json.get(\"analyzers\").get(\"exclude\");\n ModelNode filterIncludeNode = json.get(\"filters\").get(\"include\");\n ModelNode filterExcludeNode = json.get(\"filters\").get(\"exclude\");\n ModelNode transformIncludeNode = json.get(\"transforms\").get(\"include\");\n ModelNode transformExcludeNode = json.get(\"transforms\").get(\"exclude\");\n ModelNode reporterIncludeNode = json.get(\"reporters\").get(\"include\");\n ModelNode reporterExcludeNode = json.get(\"reporters\").get(\"exclude\");\n\n return builder()\n .withTransformationBlocks(json.get(\"transformBlocks\"))\n .withAnalyzerExtensionIdsInclude(asStringList(analyzerIncludeNode))\n .withAnalyzerExtensionIdsExclude(asStringList(analyzerExcludeNode))\n .withFilterExtensionIdsInclude(asStringList(filterIncludeNode))\n .withFilterExtensionIdsExclude(asStringList(filterExcludeNode))\n .withTransformExtensionIdsInclude(asStringList(transformIncludeNode))\n .withTransformExtensionIdsExclude(asStringList(transformExcludeNode))\n .withReporterExtensionIdsInclude(asStringList(reporterIncludeNode))\n .withReporterExtensionIdsExclude(asStringList(reporterExcludeNode));\n }",
"public Collection<Tag> getListUser(String userId) throws FlickrException {\n\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_LIST_USER);\n\n parameters.put(\"user_id\", userId);\n\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\n if (response.isError()) {\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\n }\n\n Element whoElement = response.getPayload();\n\n List<Tag> tags = new ArrayList<Tag>();\n Element tagsElement = (Element) whoElement.getElementsByTagName(\"tags\").item(0);\n NodeList tagElements = tagsElement.getElementsByTagName(\"tag\");\n for (int i = 0; i < tagElements.getLength(); i++) {\n Element tagElement = (Element) tagElements.item(i);\n Tag tag = new Tag();\n tag.setValue(((Text) tagElement.getFirstChild()).getData());\n tags.add(tag);\n }\n return tags;\n }",
"public static final List<String> listProjectNames(File directory)\n {\n List<String> result = new ArrayList<String>();\n\n File[] files = directory.listFiles(new FilenameFilter()\n {\n @Override public boolean accept(File dir, String name)\n {\n return name.toUpperCase().endsWith(\"STR.P3\");\n }\n });\n\n if (files != null)\n {\n for (File file : files)\n {\n String fileName = file.getName();\n String prefix = fileName.substring(0, fileName.length() - 6);\n result.add(prefix);\n }\n }\n\n Collections.sort(result);\n\n return result;\n }",
"private void addUDFValue(FieldTypeClass fieldType, FieldContainer container, Row row)\n {\n Integer fieldId = row.getInteger(\"udf_type_id\");\n String fieldName = m_udfFields.get(fieldId);\n\n Object value = null;\n FieldType field = m_project.getCustomFields().getFieldByAlias(fieldType, fieldName);\n if (field != null)\n {\n DataType fieldDataType = field.getDataType();\n\n switch (fieldDataType)\n {\n case DATE:\n {\n value = row.getDate(\"udf_date\");\n break;\n }\n\n case CURRENCY:\n case NUMERIC:\n {\n value = row.getDouble(\"udf_number\");\n break;\n }\n\n case GUID:\n case INTEGER:\n {\n value = row.getInteger(\"udf_code_id\");\n break;\n }\n\n case BOOLEAN:\n {\n String text = row.getString(\"udf_text\");\n if (text != null)\n {\n // before a normal boolean parse, we try to lookup the text as a P6 static type indicator UDF\n value = STATICTYPE_UDF_MAP.get(text);\n if (value == null)\n {\n value = Boolean.valueOf(row.getBoolean(\"udf_text\"));\n }\n }\n else\n {\n value = Boolean.valueOf(row.getBoolean(\"udf_number\"));\n }\n break;\n }\n\n default:\n {\n value = row.getString(\"udf_text\");\n break;\n }\n }\n\n container.set(field, value);\n }\n }",
"public void finalizeConfig() {\n assert !configFinalized;\n\n try {\n retrieveEngine();\n } catch (Exception e) {\n throw new RuntimeException(e.getMessage(), e);\n }\n configFinalized = true;\n }",
"public static base_responses delete(nitro_service client, String hostname[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (hostname != null && hostname.length > 0) {\n\t\t\tdnsaaaarec deleteresources[] = new dnsaaaarec[hostname.length];\n\t\t\tfor (int i=0;i<hostname.length;i++){\n\t\t\t\tdeleteresources[i] = new dnsaaaarec();\n\t\t\t\tdeleteresources[i].hostname = hostname[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"@Override\n public double get( int row , int col ) {\n if( col < 0 || col >= numCols || row < 0 || row >= numRows ) {\n throw new IllegalArgumentException(\"Specified element is out of bounds: \"+row+\" \"+col);\n }\n\n return data[ row * numCols + col ];\n }",
"public static Variable deserialize(String s,\n VariableType variableType,\n List<String> dataTypes) {\n Variable var = new Variable(variableType);\n String[] varParts = s.split(\":\");\n if (varParts.length > 0) {\n String name = varParts[0];\n if (!name.isEmpty()) {\n var.setName(name);\n if (varParts.length == 2) {\n String dataType = varParts[1];\n if (!dataType.isEmpty()) {\n if (dataTypes != null && dataTypes.contains(dataType)) {\n var.setDataType(dataType);\n } else {\n var.setCustomDataType(dataType);\n }\n }\n }\n }\n }\n return var;\n }"
] |
Return a key to identify the connection descriptor. | [
"public PBKey getPBKey()\r\n {\r\n if (pbKey == null)\r\n {\r\n this.pbKey = new PBKey(this.getJcdAlias(), this.getUserName(), this.getPassWord());\r\n }\r\n return pbKey;\r\n }"
] | [
"public static String formatConnectionTerminationMessage(final String connectionName, final String host, final String connectionReason, final String terminationReason) {\n\t\treturn CON_TERMINATION_FORMAT.format(new Object[] { connectionName, host, connectionReason, terminationReason });\n\t}",
"public void updateInfo(BoxWebLink.Info info) {\n URL url = WEB_LINK_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"PUT\");\n request.setBody(info.getPendingChanges());\n String body = info.getPendingChanges();\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n info.update(jsonObject);\n }",
"private void enforceSrid(Object feature) throws LayerException {\n\t\tGeometry geom = getFeatureModel().getGeometry(feature);\n\t\tif (null != geom) {\n\t\t\tgeom.setSRID(srid);\n\t\t\tgetFeatureModel().setGeometry(feature, geom);\n\t\t}\n\t}",
"private Integer getOutlineLevel(Task task)\n {\n String value = task.getWBS();\n Integer result = Integer.valueOf(1);\n if (value != null && value.length() > 0)\n {\n String[] path = WBS_SPLIT_REGEX.split(value);\n result = Integer.valueOf(path.length);\n }\n return result;\n }",
"public static void main(String[] args) {\r\n //Adding custom equivalence class generation transformer - NOTE this will get applied during graph traversal-->\r\n //MODEL USAGE EXAMPLE: <assign name=\"var_out_V1_2\" expr=\"%ssn\"/> <dg:transform name=\"EQ\"/>\r\n Map<String, DataTransformer> transformers = new HashMap<String, DataTransformer>();\r\n transformers.put(\"EQ\", new EquivalenceClassTransformer());\r\n Vector<CustomTagExtension> cte = new Vector<CustomTagExtension>();\r\n cte.add(new InLineTransformerExtension(transformers));\r\n Engine engine = new SCXMLEngine(cte);\n\r\n //will default to samplemachine, but you could specify a different file if you choose to\r\n InputStream is = CmdLine.class.getResourceAsStream(\"/\" + (args.length == 0 ? \"samplemachine\" : args[0]) + \".xml\");\n\r\n engine.setModelByInputFileStream(is);\n\r\n // Usually, this should be more than the number of threads you intend to run\r\n engine.setBootstrapMin(1);\n\r\n //Prepare the consumer with the proper writer and transformer\r\n DataConsumer consumer = new DataConsumer();\r\n consumer.addDataTransformer(new SampleMachineTransformer());\n\r\n //Adding custom equivalence class generation transformer - NOTE this will get applied post data generation.\r\n //MODEL USAGE EXAMPLE: <dg:assign name=\"var_out_V2\" set=\"%regex([0-9]{3}[A-Z0-9]{5})\"/>\r\n consumer.addDataTransformer(new EquivalenceClassTransformer());\n\r\n consumer.addDataWriter(new DefaultWriter(System.out,\r\n new String[]{\"var_1_1\", \"var_1_2\", \"var_1_3\", \"var_1_4\", \"var_1_5\", \"var_1_6\", \"var_1_7\",\r\n \"var_2_1\", \"var_2_2\", \"var_2_3\", \"var_2_4\", \"var_2_5\", \"var_2_6\", \"var_2_7\", \"var_2_8\"}));\n\r\n //Prepare the distributor\r\n DefaultDistributor defaultDistributor = new DefaultDistributor();\r\n defaultDistributor.setThreadCount(1);\r\n defaultDistributor.setDataConsumer(consumer);\r\n Logger.getLogger(\"org.apache\").setLevel(Level.WARN);\n\r\n engine.process(defaultDistributor);\r\n }",
"public static appfwsignatures get(nitro_service service) throws Exception{\n\t\tappfwsignatures obj = new appfwsignatures();\n\t\tappfwsignatures[] response = (appfwsignatures[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public RedwoodConfiguration loggingClass(final Class<?> classToIgnoreInTraces){\r\n tasks.add(new Runnable() { public void run() { Redwood.addLoggingClass(classToIgnoreInTraces.getName()); } });\r\n return this;\r\n }",
"public void setShortAttribute(String name, Short value) {\n\t\tensureValue();\n\t\tAttribute attribute = new ShortAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetValue().getAllAttributes().put(name, attribute);\n\t}",
"private static final Duration parseDurationInFractionsOfMinutes(ProjectProperties properties, Number value, TimeUnit targetTimeUnit, int factor)\n {\n Duration result = null;\n\n if (value != null)\n {\n result = Duration.getInstance(value.intValue() / factor, TimeUnit.MINUTES);\n if (targetTimeUnit != result.getUnits())\n {\n result = result.convertUnits(targetTimeUnit, properties);\n }\n }\n\n return (result);\n }"
] |
Returns a fine-grained word shape classifier, that equivalence classes
lower and upper case and digits, and collapses sequences of the
same type, but keeps all punctuation. This adds an extra recognizer
for a greek letter embedded in the String, which is useful for bio. | [
"private static String wordShapeDan2Bio(String s, Collection<String> knownLCWords) {\r\n if (containsGreekLetter(s)) {\r\n return wordShapeDan2(s, knownLCWords) + \"-GREEK\";\r\n } else {\r\n return wordShapeDan2(s, knownLCWords);\r\n }\r\n }"
] | [
"private RandomVariable getValueUnderlyingNumeraireRelative(LIBORModelMonteCarloSimulationModel model, Schedule legSchedule, boolean paysFloat, double swaprate, double notional) throws CalculationException {\r\n\t\tRandomVariable value\t= model.getRandomVariableForConstant(0.0);\r\n\r\n\t\tfor(int periodIndex = legSchedule.getNumberOfPeriods() - 1; periodIndex >= 0; periodIndex--) {\r\n\r\n\t\t\tdouble fixingTime = FloatingpointDate.getFloatingPointDateFromDate(model.getReferenceDate().toLocalDate(), legSchedule.getPeriod(periodIndex).getFixing());\r\n\t\t\tdouble paymentTime = FloatingpointDate.getFloatingPointDateFromDate(model.getReferenceDate().toLocalDate(), legSchedule.getPeriod(periodIndex).getPayment());\r\n\t\t\tdouble periodLength\t= legSchedule.getPeriodLength(periodIndex);\r\n\r\n\t\t\tRandomVariable\tnumeraireAtPayment = model.getNumeraire(paymentTime);\r\n\t\t\tRandomVariable\tmonteCarloProbabilitiesAtPayment = model.getMonteCarloWeights(paymentTime);\r\n\t\t\tif(swaprate != 0.0) {\r\n\t\t\t\tRandomVariable periodCashFlowFix = model.getRandomVariableForConstant(swaprate * periodLength * notional).div(numeraireAtPayment).mult(monteCarloProbabilitiesAtPayment);\r\n\t\t\t\tvalue = value.add(periodCashFlowFix);\r\n\t\t\t}\r\n\t\t\tif(paysFloat) {\r\n\t\t\t\tRandomVariable libor = model.getLIBOR(fixingTime, fixingTime, paymentTime);\r\n\t\t\t\tRandomVariable periodCashFlowFloat = libor.mult(periodLength).mult(notional).div(numeraireAtPayment).mult(monteCarloProbabilitiesAtPayment);\r\n\t\t\t\tvalue = value.add(periodCashFlowFloat);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn value;\r\n\t}",
"private String getLogRequestIdentifier() {\n if (logIdentifier == null) {\n logIdentifier = String.format(\"%s-%s %s %s\", Integer.toHexString(hashCode()),\n numberOfRetries, connection.getRequestMethod(), connection.getURL());\n }\n return logIdentifier;\n }",
"@Pure\n\t@Inline(value = \"$3.union($1, $4.singletonMap($2.getKey(), $2.getValue()))\",\n\t\t\timported = { MapExtensions.class, Collections.class })\n\tpublic static <K, V> Map<K, V> operator_plus(Map<K, V> left, final Pair<? extends K, ? extends V> right) {\n\t\treturn union(left, Collections.singletonMap(right.getKey(), right.getValue()));\n\t}",
"public static String getValue(Element element) {\r\n if (element != null) {\r\n Node dataNode = element.getFirstChild();\r\n if (dataNode != null) {\r\n return ((Text) dataNode).getData();\r\n }\r\n }\r\n return null;\r\n }",
"@Override\n\tpublic void format(final StringBuffer sbuf, final LoggingEvent event) {\n\t\tfor (int i = 0; i < patternConverters.length; i++) {\n\t\t\tfinal int startField = sbuf.length();\n\t\t\tpatternConverters[i].format(event, sbuf);\n\t\t\tpatternFields[i].format(startField, sbuf);\n\t\t}\n\t}",
"public static CharSequence getAt(CharSequence text, IntRange range) {\n return getAt(text, (Range) range);\n }",
"private Integer getNextOrdinalForMethodId(int methodId, String pathName) throws Exception {\n String pathInfo = doGet(BASE_PATH + uriEncode(pathName), new BasicNameValuePair[0]);\n JSONObject pathResponse = new JSONObject(pathInfo);\n\n JSONArray enabledEndpoints = pathResponse.getJSONArray(\"enabledEndpoints\");\n int lastOrdinal = 0;\n for (int x = 0; x < enabledEndpoints.length(); x++) {\n if (enabledEndpoints.getJSONObject(x).getInt(\"overrideId\") == methodId) {\n lastOrdinal++;\n }\n }\n return lastOrdinal + 1;\n }",
"public static String serialize(final Object obj) throws IOException {\n\t\tfinal ObjectMapper mapper = new ObjectMapper();\n mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);\n\t\treturn mapper.writeValueAsString(obj);\n\t\t\n\t}",
"public void unbind(T service, Map<String, Object> props) {\n synchronized (serviceMap) {\n serviceMap.remove(ServiceUtil.getComparableForServiceRanking(props));\n updateSortedServices();\n }\n }"
] |
Establish connection to the ChromeCast device | [
"private void connect() throws IOException, GeneralSecurityException {\n synchronized (closedSync) {\n if (socket == null || socket.isClosed()) {\n SSLContext sc = SSLContext.getInstance(\"SSL\");\n sc.init(null, new TrustManager[] { new X509TrustAllManager() }, new SecureRandom());\n socket = sc.getSocketFactory().createSocket();\n socket.connect(address);\n }\n /**\n * Authenticate\n */\n CastChannel.DeviceAuthMessage authMessage = CastChannel.DeviceAuthMessage.newBuilder()\n .setChallenge(CastChannel.AuthChallenge.newBuilder().build())\n .build();\n\n CastChannel.CastMessage msg = CastChannel.CastMessage.newBuilder()\n .setDestinationId(DEFAULT_RECEIVER_ID)\n .setNamespace(\"urn:x-cast:com.google.cast.tp.deviceauth\")\n .setPayloadType(CastChannel.CastMessage.PayloadType.BINARY)\n .setProtocolVersion(CastChannel.CastMessage.ProtocolVersion.CASTV2_1_0)\n .setSourceId(name)\n .setPayloadBinary(authMessage.toByteString())\n .build();\n\n write(msg);\n CastChannel.CastMessage response = read();\n CastChannel.DeviceAuthMessage authResponse = CastChannel.DeviceAuthMessage.parseFrom(response.getPayloadBinary());\n if (authResponse.hasError()) {\n throw new ChromeCastException(\"Authentication failed: \" + authResponse.getError().getErrorType().toString());\n }\n\n /**\n * Send 'PING' message\n */\n PingThread pingThread = new PingThread();\n pingThread.run();\n\n /**\n * Send 'CONNECT' message to start session\n */\n write(\"urn:x-cast:com.google.cast.tp.connection\", StandardMessage.connect(), DEFAULT_RECEIVER_ID);\n\n /**\n * Start ping/pong and reader thread\n */\n pingTimer = new Timer(name + \" PING\");\n pingTimer.schedule(pingThread, 1000, PING_PERIOD);\n\n reader = new ReadThread();\n reader.start();\n\n if (closed) {\n closed = false;\n notifyListenerOfConnectionEvent(true);\n }\n }\n }"
] | [
"public static String makePropertyName(String name) {\n char[] buf = new char[name.length() + 3];\n int pos = 0;\n buf[pos++] = 's';\n buf[pos++] = 'e';\n buf[pos++] = 't';\n\n for (int ix = 0; ix < name.length(); ix++) {\n char ch = name.charAt(ix);\n if (ix == 0)\n ch = Character.toUpperCase(ch);\n else if (ch == '-') {\n ix++;\n if (ix == name.length())\n break;\n ch = Character.toUpperCase(name.charAt(ix));\n }\n\n buf[pos++] = ch;\n }\n\n return new String(buf, 0, pos);\n }",
"private void deleteLinks(@NotNull final PersistentStoreTransaction txn, @NotNull final PersistentEntity entity) {\n final PersistentEntityId id = entity.getId();\n final int entityTypeId = id.getTypeId();\n final long entityLocalId = id.getLocalId();\n final Transaction envTxn = txn.getEnvironmentTransaction();\n final LinksTable links = getLinksTable(txn, entityTypeId);\n final IntHashSet deletedLinks = new IntHashSet();\n try (Cursor cursor = links.getFirstIndexCursor(envTxn)) {\n for (boolean success = cursor.getSearchKeyRange(PropertyKey.propertyKeyToEntry(new PropertyKey(entityLocalId, 0))) != null;\n success; success = cursor.getNext()) {\n final ByteIterable keyEntry = cursor.getKey();\n final PropertyKey key = PropertyKey.entryToPropertyKey(keyEntry);\n if (key.getEntityLocalId() != entityLocalId) {\n break;\n }\n final ByteIterable valueEntry = cursor.getValue();\n if (links.delete(envTxn, keyEntry, valueEntry)) {\n int linkId = key.getPropertyId();\n if (getLinkName(txn, linkId) != null) {\n deletedLinks.add(linkId);\n final LinkValue linkValue = LinkValue.entryToLinkValue(valueEntry);\n txn.linkDeleted(entity.getId(), (PersistentEntityId) linkValue.getEntityId(), linkValue.getLinkId());\n }\n }\n }\n }\n for (Integer linkId : deletedLinks) {\n links.deleteAllIndex(envTxn, linkId, entityLocalId);\n }\n }",
"public static base_response update(nitro_service client, nd6ravariables resource) throws Exception {\n\t\tnd6ravariables updateresource = new nd6ravariables();\n\t\tupdateresource.vlan = resource.vlan;\n\t\tupdateresource.ceaserouteradv = resource.ceaserouteradv;\n\t\tupdateresource.sendrouteradv = resource.sendrouteradv;\n\t\tupdateresource.srclinklayeraddroption = resource.srclinklayeraddroption;\n\t\tupdateresource.onlyunicastrtadvresponse = resource.onlyunicastrtadvresponse;\n\t\tupdateresource.managedaddrconfig = resource.managedaddrconfig;\n\t\tupdateresource.otheraddrconfig = resource.otheraddrconfig;\n\t\tupdateresource.currhoplimit = resource.currhoplimit;\n\t\tupdateresource.maxrtadvinterval = resource.maxrtadvinterval;\n\t\tupdateresource.minrtadvinterval = resource.minrtadvinterval;\n\t\tupdateresource.linkmtu = resource.linkmtu;\n\t\tupdateresource.reachabletime = resource.reachabletime;\n\t\tupdateresource.retranstime = resource.retranstime;\n\t\tupdateresource.defaultlifetime = resource.defaultlifetime;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public Diff compare(String left, String right) {\n\t\treturn compare(getCtType(left), getCtType(right));\n\t}",
"public static Method findSetMethod(Field field, DatabaseType databaseType, boolean throwExceptions)\n\t\t\tthrows IllegalArgumentException {\n\t\tMethod fieldSetMethod = findMethodFromNames(field, false, throwExceptions,\n\t\t\t\tmethodFromField(field, \"set\", databaseType, true), methodFromField(field, \"set\", databaseType, false));\n\t\tif (fieldSetMethod == null) {\n\t\t\treturn null;\n\t\t}\n\t\tif (fieldSetMethod.getReturnType() != void.class) {\n\t\t\tif (throwExceptions) {\n\t\t\t\tthrow new IllegalArgumentException(\"Return type of set method \" + fieldSetMethod.getName() + \" returns \"\n\t\t\t\t\t\t+ fieldSetMethod.getReturnType() + \" instead of void\");\n\t\t\t} else {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\treturn fieldSetMethod;\n\t}",
"public static Map<String, List<String>> getResponseHeaders(String stringUrl,\n boolean followRedirects) throws IOException {\n URL url = new URL(stringUrl);\n HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n conn.setInstanceFollowRedirects(followRedirects);\n \n InputStream is = conn.getInputStream();\n if (\"gzip\".equals(conn.getContentEncoding())) {\n is = new GZIPInputStream(is);\n }\n\n Map<String, List<String>> headers = new LinkedHashMap<String, List<String>>(conn.getHeaderFields());\n headers.put(\"X-Content\", Arrays.asList(MyStreamUtils.readContent(is)));\n headers.put(\"X-URL\", Arrays.asList(conn.getURL().toString()));\n headers.put(\"X-Status\", Arrays.asList(String.valueOf(conn.getResponseCode())));\n \n return headers;\n }",
"private Storepoint getCurrentStorepoint(Project phoenixProject)\n {\n List<Storepoint> storepoints = phoenixProject.getStorepoints().getStorepoint();\n Collections.sort(storepoints, new Comparator<Storepoint>()\n {\n @Override public int compare(Storepoint o1, Storepoint o2)\n {\n return DateHelper.compare(o2.getCreationTime(), o1.getCreationTime());\n }\n });\n return storepoints.get(0);\n }",
"private void queryDatabaseMetaData()\n {\n ResultSet rs = null;\n\n try\n {\n Set<String> tables = new HashSet<String>();\n DatabaseMetaData dmd = m_connection.getMetaData();\n rs = dmd.getTables(null, null, null, null);\n while (rs.next())\n {\n tables.add(rs.getString(\"TABLE_NAME\"));\n }\n\n m_hasResourceBaselines = tables.contains(\"MSP_RESOURCE_BASELINES\");\n m_hasTaskBaselines = tables.contains(\"MSP_TASK_BASELINES\");\n m_hasAssignmentBaselines = tables.contains(\"MSP_ASSIGNMENT_BASELINES\");\n }\n\n catch (Exception ex)\n {\n // Ignore errors when reading meta data\n }\n\n finally\n {\n if (rs != null)\n {\n try\n {\n rs.close();\n }\n\n catch (SQLException ex)\n {\n // Ignore errors when closing result set\n }\n rs = null;\n }\n }\n }",
"private void handleApplicationUpdateRequest(SerialMessage incomingMessage) {\n\t\tlogger.trace(\"Handle Message Application Update Request\");\n\t\tint nodeId = incomingMessage.getMessagePayloadByte(1);\n\t\t\n\t\tlogger.trace(\"Application Update Request from Node \" + nodeId);\n\t\tUpdateState updateState = UpdateState.getUpdateState(incomingMessage.getMessagePayloadByte(0));\n\t\t\n\t\tswitch (updateState) {\n\t\t\tcase NODE_INFO_RECEIVED:\n\t\t\t\tlogger.debug(\"Application update request, node information received.\");\t\t\t\n\t\t\t\tint length = incomingMessage.getMessagePayloadByte(2);\n\t\t\t\tZWaveNode node = getNode(nodeId);\n\t\t\t\t\n\t\t\t\tnode.resetResendCount();\n\t\t\t\t\n\t\t\t\tfor (int i = 6; i < length + 3; i++) {\n\t\t\t\t\tint data = incomingMessage.getMessagePayloadByte(i);\n\t\t\t\t\tif(data == 0xef ) {\n\t\t\t\t\t\t// TODO: Implement control command classes\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tlogger.debug(String.format(\"Adding command class 0x%02X to the list of supported command classes.\", data));\n\t\t\t\t\tZWaveCommandClass commandClass = ZWaveCommandClass.getInstance(data, node, this);\n\t\t\t\t\tif (commandClass != null)\n\t\t\t\t\t\tnode.addCommandClass(commandClass);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// advance node stage.\n\t\t\t\tnode.advanceNodeStage();\n\t\t\t\t\n\t\t\t\tif (incomingMessage.getMessageClass() == this.lastSentMessage.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\tbreak;\n\t\t\tcase NODE_INFO_REQ_FAILED:\n\t\t\t\tlogger.debug(\"Application update request, Node Info Request Failed, re-request node info.\");\n\t\t\t\t\n\t\t\t\tSerialMessage requestInfoMessage = this.lastSentMessage;\n\t\t\t\t\n\t\t\t\tif (requestInfoMessage.getMessageClass() != SerialMessage.SerialMessageClass.RequestNodeInfo) {\n\t\t\t\t\tlogger.warn(\"Got application update request without node info request, ignoring.\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\tif (--requestInfoMessage.attempts >= 0) {\n\t\t\t\t\tlogger.error(\"Got Node Info Request Failed while sending this serial message. Requeueing\");\n\t\t\t\t\tthis.enqueue(requestInfoMessage);\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tlogger.warn(\"Node Info Request Failed 3x. Discarding message: {}\", lastSentMessage.toString());\n\t\t\t\t}\n\t\t\t\ttransactionCompleted.release();\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tlogger.warn(String.format(\"TODO: Implement Application Update Request Handling of %s (0x%02X).\", updateState.getLabel(), updateState.getKey()));\n\t\t}\n\t}"
] |
Computes the inverse permutation vector
@param original Original permutation vector
@param inverse It's inverse | [
"public static void permutationInverse( int []original , int []inverse , int length ) {\n for (int i = 0; i < length; i++) {\n inverse[original[i]] = i;\n }\n }"
] | [
"private void getMonthlyAbsoluteDates(Calendar calendar, int frequency, List<Date> dates)\n {\n int currentDayNumber = calendar.get(Calendar.DAY_OF_MONTH);\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n int requiredDayNumber = NumberHelper.getInt(m_dayNumber);\n if (requiredDayNumber < currentDayNumber)\n {\n calendar.add(Calendar.MONTH, 1);\n }\n\n while (moreDates(calendar, dates))\n {\n int useDayNumber = requiredDayNumber;\n int maxDayNumber = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);\n if (useDayNumber > maxDayNumber)\n {\n useDayNumber = maxDayNumber;\n }\n calendar.set(Calendar.DAY_OF_MONTH, useDayNumber);\n dates.add(calendar.getTime());\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n calendar.add(Calendar.MONTH, frequency);\n }\n }",
"public Collection<Group> getGroups() throws FlickrException {\r\n GroupList<Group> groups = new GroupList<Group>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_GROUPS);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element groupsElement = response.getPayload();\r\n groups.setPage(groupsElement.getAttribute(\"page\"));\r\n groups.setPages(groupsElement.getAttribute(\"pages\"));\r\n groups.setPerPage(groupsElement.getAttribute(\"perpage\"));\r\n groups.setTotal(groupsElement.getAttribute(\"total\"));\r\n NodeList groupNodes = groupsElement.getElementsByTagName(\"group\");\r\n for (int i = 0; i < groupNodes.getLength(); i++) {\r\n Element groupElement = (Element) groupNodes.item(i);\r\n Group group = new Group();\r\n group.setId(groupElement.getAttribute(\"id\"));\r\n group.setName(groupElement.getAttribute(\"name\"));\r\n group.setAdmin(\"1\".equals(groupElement.getAttribute(\"admin\")));\r\n group.setPrivacy(groupElement.getAttribute(\"privacy\"));\r\n group.setIconServer(groupElement.getAttribute(\"iconserver\"));\r\n group.setIconFarm(groupElement.getAttribute(\"iconfarm\"));\r\n group.setPhotoCount(groupElement.getAttribute(\"photos\"));\r\n groups.add(group);\r\n }\r\n return groups;\r\n }",
"protected void restoreAutoCommitState()\r\n {\r\n try\r\n {\r\n if(!broker.isManaged())\r\n {\r\n if (jcd.getUseAutoCommit() == JdbcConnectionDescriptor.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE\r\n && originalAutoCommitState == true && con != null && !con.isClosed())\r\n {\r\n platform.changeAutoCommitState(jcd, con, true);\r\n }\r\n }\r\n else\r\n {\r\n if(log.isDebugEnabled()) log.debug(\r\n \"Found managed environment setting in PB, will skip Platform.changeAutoCommitState(...) call\");\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n // should never be reached\r\n throw new OJBRuntimeException(\"Restore of connection autocommit state failed\", e);\r\n }\r\n }",
"public Response remove(DesignDocument designDocument) {\r\n assertNotEmpty(designDocument, \"DesignDocument\");\r\n ensureDesignPrefixObject(designDocument);\r\n return db.remove(designDocument);\r\n }",
"public static String get(String language) {\n language = language.toLowerCase();\n if(\"ecmascript\".equals(language)) {\n language = \"javascript\";\n }\n\n String extension = extensions.get(language);\n if(extension == null) {\n return null;\n\n } else {\n return loadScriptEnv(language, extension);\n\n }\n }",
"private T getWrappedPublisher(Publisher flexiblePublisher, Class<T> type) {\n if (!(flexiblePublisher instanceof FlexiblePublisher)) {\n throw new IllegalArgumentException(String.format(\"Publisher should be of type: '%s'. Found type: '%s'\",\n FlexiblePublisher.class, flexiblePublisher.getClass()));\n }\n\n List<ConditionalPublisher> conditions = ((FlexiblePublisher) flexiblePublisher).getPublishers();\n for (ConditionalPublisher condition : conditions) {\n if (type.isInstance(condition.getPublisher())) {\n return type.cast(condition.getPublisher());\n }\n }\n\n return null;\n }",
"public static cacheselector[] get(nitro_service service, String selectorname[]) throws Exception{\n\t\tif (selectorname !=null && selectorname.length>0) {\n\t\t\tcacheselector response[] = new cacheselector[selectorname.length];\n\t\t\tcacheselector obj[] = new cacheselector[selectorname.length];\n\t\t\tfor (int i=0;i<selectorname.length;i++) {\n\t\t\t\tobj[i] = new cacheselector();\n\t\t\t\tobj[i].set_selectorname(selectorname[i]);\n\t\t\t\tresponse[i] = (cacheselector) 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 Span toSpan(Range range) {\n return new Span(toRowColumn(range.getStartKey()), range.isStartKeyInclusive(),\n toRowColumn(range.getEndKey()), range.isEndKeyInclusive());\n }",
"public static dospolicy get(nitro_service service, String name) throws Exception{\n\t\tdospolicy obj = new dospolicy();\n\t\tobj.set_name(name);\n\t\tdospolicy response = (dospolicy) obj.get_resource(service);\n\t\treturn response;\n\t}"
] |
Turn a resultset into EndpointOverride
@param results results containing relevant information
@return EndpointOverride
@throws Exception exception | [
"private EndpointOverride getEndpointOverrideFromResultSet(ResultSet results) throws Exception {\n EndpointOverride endpoint = new EndpointOverride();\n endpoint.setPathId(results.getInt(Constants.GENERIC_ID));\n endpoint.setPath(results.getString(Constants.PATH_PROFILE_ACTUAL_PATH));\n endpoint.setBodyFilter(results.getString(Constants.PATH_PROFILE_BODY_FILTER));\n endpoint.setPathName(results.getString(Constants.PATH_PROFILE_PATHNAME));\n endpoint.setContentType(results.getString(Constants.PATH_PROFILE_CONTENT_TYPE));\n endpoint.setRequestType(results.getInt(Constants.PATH_PROFILE_REQUEST_TYPE));\n endpoint.setRepeatNumber(results.getInt(Constants.REQUEST_RESPONSE_REPEAT_NUMBER));\n endpoint.setGroupIds(results.getString(Constants.PATH_PROFILE_GROUP_IDS));\n endpoint.setRequestEnabled(results.getBoolean(Constants.REQUEST_RESPONSE_REQUEST_ENABLED));\n endpoint.setResponseEnabled(results.getBoolean(Constants.REQUEST_RESPONSE_RESPONSE_ENABLED));\n endpoint.setClientUUID(results.getString(Constants.GENERIC_CLIENT_UUID));\n endpoint.setProfileId(results.getInt(Constants.GENERIC_PROFILE_ID));\n endpoint.setGlobal(results.getBoolean(Constants.PATH_PROFILE_GLOBAL));\n return endpoint;\n }"
] | [
"public Collection getReaders(Object obj)\r\n\t{\r\n\t\tCollection result = null;\r\n try\r\n {\r\n Identity oid = new Identity(obj, getBroker());\r\n byte selector = (byte) 'r';\r\n byte[] requestBarr = buildRequestArray(oid, selector);\r\n \r\n HttpURLConnection conn = getHttpUrlConnection();\r\n \r\n //post request\r\n BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream());\r\n out.write(requestBarr,0,requestBarr.length);\r\n out.flush();\t\t\r\n \r\n // read result from \r\n InputStream in = conn.getInputStream();\r\n ObjectInputStream ois = new ObjectInputStream(in);\r\n result = (Collection) ois.readObject();\r\n \r\n // cleanup\r\n ois.close();\r\n out.close();\r\n conn.disconnect();\t\t\r\n }\r\n catch (Throwable t)\r\n {\r\n throw new PersistenceBrokerException(t);\r\n }\r\n return result;\r\n\t}",
"public static void ensureNotSingular( DMatrixSparseCSC A , Random rand ) {\n// if( A.numRows < A.numCols ) {\n// throw new IllegalArgumentException(\"Fewer equations than variables\");\n// }\n\n int []s = UtilEjml.shuffled(A.numRows,rand);\n Arrays.sort(s);\n\n int N = Math.min(A.numCols,A.numRows);\n for (int col = 0; col < N; col++) {\n A.set(s[col],col,rand.nextDouble()+0.5);\n }\n }",
"public Method getGetMethod(final Object object, final String fieldName) {\n\t\tif( object == null ) {\n\t\t\tthrow new NullPointerException(\"object should not be null\");\n\t\t} else if( fieldName == null ) {\n\t\t\tthrow new NullPointerException(\"fieldName should not be null\");\n\t\t}\n\t\t\n\t\tMethod method = getCache.get(object.getClass().getName(), fieldName);\n\t\tif( method == null ) {\n\t\t\tmethod = ReflectionUtils.findGetter(object, fieldName);\n\t\t\tgetCache.set(object.getClass().getName(), fieldName, method);\n\t\t}\n\t\treturn method;\n\t}",
"@Override\n public void accept(ICompilationUnit sourceUnit, AccessRestriction accessRestriction) {\n // Switch the current policy and compilation result for this unit to the requested one.\n CompilationResult unitResult =\n new CompilationResult(sourceUnit, this.totalUnits, this.totalUnits, this.options.maxProblemsPerUnit);\n unitResult.checkSecondaryTypes = true;\n try {\n if (this.options.verbose) {\n String count = String.valueOf(this.totalUnits + 1);\n this.out.println(\n Messages.bind(Messages.compilation_request,\n new String[] {\n count,\n count,\n new String(sourceUnit.getFileName())\n }));\n }\n // diet parsing for large collection of unit\n CompilationUnitDeclaration parsedUnit;\n if (this.totalUnits < this.parseThreshold) {\n parsedUnit = this.parser.parse(sourceUnit, unitResult);\n } else {\n parsedUnit = this.parser.dietParse(sourceUnit, unitResult);\n }\n // initial type binding creation\n this.lookupEnvironment.buildTypeBindings(parsedUnit, accessRestriction);\n addCompilationUnit(sourceUnit, parsedUnit);\n\n // binding resolution\n this.lookupEnvironment.completeTypeBindings(parsedUnit);\n } catch (AbortCompilationUnit e) {\n // at this point, currentCompilationUnitResult may not be sourceUnit, but some other\n // one requested further along to resolve sourceUnit.\n if (unitResult.compilationUnit == sourceUnit) { // only report once\n this.requestor.acceptResult(unitResult.tagAsAccepted());\n } else {\n throw e; // want to abort enclosing request to compile\n }\n }\n }",
"public static authenticationvserver_auditnslogpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_auditnslogpolicy_binding obj = new authenticationvserver_auditnslogpolicy_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_auditnslogpolicy_binding response[] = (authenticationvserver_auditnslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private String quoteFormatCharacters(String literal)\n {\n StringBuilder sb = new StringBuilder();\n int length = literal.length();\n char c;\n\n for (int loop = 0; loop < length; loop++)\n {\n c = literal.charAt(loop);\n switch (c)\n {\n case '0':\n case '#':\n case '.':\n case '-':\n case ',':\n case 'E':\n case ';':\n case '%':\n {\n sb.append(\"'\");\n sb.append(c);\n sb.append(\"'\");\n break;\n }\n\n default:\n {\n sb.append(c);\n break;\n }\n }\n }\n\n return (sb.toString());\n }",
"private Component createAddKeyButton() {\n\n // the \"+\" button\n Button addKeyButton = new Button();\n addKeyButton.addStyleName(\"icon-only\");\n addKeyButton.addStyleName(\"borderless-colored\");\n addKeyButton.setDescription(m_messages.key(Messages.GUI_ADD_KEY_0));\n addKeyButton.setIcon(FontOpenCms.CIRCLE_PLUS, m_messages.key(Messages.GUI_ADD_KEY_0));\n addKeyButton.addClickListener(new ClickListener() {\n\n private static final long serialVersionUID = 1L;\n\n public void buttonClick(ClickEvent event) {\n\n handleAddKey();\n\n }\n });\n return addKeyButton;\n }",
"public static PackageNameMappingWithPackagePattern fromPackage(String packagePattern)\n {\n PackageNameMapping packageNameMapping = new PackageNameMapping();\n packageNameMapping.setPackagePattern(packagePattern);\n return packageNameMapping;\n }",
"public static <T> FastEvent<T> of(Class<T> type, BeanManagerImpl manager, ObserverNotifier notifier, Annotation... qualifiers) {\n ResolvedObservers<T> resolvedObserverMethods = notifier.<T> resolveObserverMethods(type, qualifiers);\n if (resolvedObserverMethods.isMetadataRequired()) {\n EventMetadata metadata = new EventMetadataImpl(type, null, qualifiers);\n CurrentEventMetadata metadataService = manager.getServices().get(CurrentEventMetadata.class);\n return new FastEventWithMetadataPropagation<T>(resolvedObserverMethods, metadata, metadataService);\n } else {\n return new FastEvent<T>(resolvedObserverMethods);\n }\n }"
] |
Use this API to update clusternodegroup resources. | [
"public static base_responses update(nitro_service client, clusternodegroup resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tclusternodegroup updateresources[] = new clusternodegroup[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new clusternodegroup();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].strict = resources[i].strict;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}"
] | [
"public static ProducerRequest readFrom(ByteBuffer buffer) {\n String topic = Utils.readShortString(buffer);\n int partition = buffer.getInt();\n int messageSetSize = buffer.getInt();\n ByteBuffer messageSetBuffer = buffer.slice();\n messageSetBuffer.limit(messageSetSize);\n buffer.position(buffer.position() + messageSetSize);\n return new ProducerRequest(topic, partition, new ByteBufferMessageSet(messageSetBuffer));\n }",
"protected void createSequence(PersistenceBroker broker, FieldDescriptor field,\r\n String sequenceName, long maxKey) throws Exception\r\n {\r\n Statement stmt = null;\r\n try\r\n {\r\n stmt = broker.serviceStatementManager().getGenericStatement(field.getClassDescriptor(), Query.NOT_SCROLLABLE);\r\n stmt.execute(sp_createSequenceQuery(sequenceName, maxKey));\r\n }\r\n catch (Exception e)\r\n {\r\n log.error(e);\r\n throw new SequenceManagerException(\"Could not create new row in \"+SEQ_TABLE_NAME+\" table - TABLENAME=\" +\r\n sequenceName + \" field=\" + field.getColumnName(), e);\r\n }\r\n finally\r\n {\r\n try\r\n {\r\n if (stmt != null) stmt.close();\r\n }\r\n catch (SQLException sqle)\r\n {\r\n if(log.isDebugEnabled())\r\n log.debug(\"Threw SQLException while in createSequence and closing stmt\", sqle);\r\n // ignore it\r\n }\r\n }\r\n }",
"public void extractFieldTypes(DatabaseType databaseType) throws SQLException {\n\t\tif (fieldTypes == null) {\n\t\t\tif (fieldConfigs == null) {\n\t\t\t\tfieldTypes = extractFieldTypes(databaseType, dataClass, tableName);\n\t\t\t} else {\n\t\t\t\tfieldTypes = convertFieldConfigs(databaseType, tableName, fieldConfigs);\n\t\t\t}\n\t\t}\n\t}",
"public static long getTxInfoCacheWeight(FluoConfiguration conf) {\n long size = conf.getLong(TX_INFO_CACHE_WEIGHT, TX_INFO_CACHE_WEIGHT_DEFAULT);\n if (size <= 0) {\n throw new IllegalArgumentException(\"Cache size must be positive for \" + TX_INFO_CACHE_WEIGHT);\n }\n return size;\n }",
"public void visitOpen(String packaze, int access, String... modules) {\n if (mv != null) {\n mv.visitOpen(packaze, access, modules);\n }\n }",
"public void delete() {\n BoxAPIConnection api = this.getAPI();\n URL url = COLLABORATION_WHITELIST_ENTRY_URL_TEMPLATE.build(api.getBaseURL(), this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(api, url, HttpMethod.DELETE);\n BoxAPIResponse response = request.send();\n response.disconnect();\n }",
"public static void copyRecursively(final Path source, final Path target, boolean overwrite) throws IOException {\n final CopyOption[] options;\n if (overwrite) {\n options = new CopyOption[]{StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING};\n } else {\n options = new CopyOption[]{StandardCopyOption.COPY_ATTRIBUTES};\n }\n Files.walkFileTree(source, new FileVisitor<Path>() {\n @Override\n public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {\n Files.copy(dir, target.resolve(source.relativize(dir)), options);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n Files.copy(file, target.resolve(source.relativize(file)), options);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {\n DeploymentRepositoryLogger.ROOT_LOGGER.cannotCopyFile(exc, file);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {\n return FileVisitResult.CONTINUE;\n }\n });\n }",
"@Override\n\tpublic List<String> contentTypes() {\n\t\tList<String> contentTypes = null;\n\t\tfinal HttpServletRequest request = getHttpRequest();\n\n\t\tif (favorParameterOverAcceptHeader) {\n\t\t\tcontentTypes = getFavoredParameterValueAsList(request);\n\t\t} else {\n\t\t\tcontentTypes = getAcceptHeaderValues(request);\n\t\t}\n\n\t\tif (isEmpty(contentTypes)) {\n\t\t\tlogger.debug(\"Setting content types to default: {}.\", DEFAULT_SUPPORTED_CONTENT_TYPES);\n\n\t\t\tcontentTypes = DEFAULT_SUPPORTED_CONTENT_TYPES;\n\t\t}\n\n\t\treturn unmodifiableList(contentTypes);\n\t}",
"@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 }"
] |
Helper method to abstract out the common logic from the various users methods.
@param api the API connection to be used when retrieving the users.
@param filterTerm The filter term to lookup users by (login for external, login or name for managed)
@param userType The type of users we want to search with this request.
Valid values are 'managed' (enterprise users), 'external' or 'all'
@param externalAppUserId the external app user id that has been set for an app user
@param fields the fields to retrieve. Leave this out for the standard fields.
@return An iterator over the selected users. | [
"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 }"
] | [
"void recordPreparedOperation(final TransactionalProtocolClient.PreparedOperation<ServerTaskExecutor.ServerOperation> preparedOperation) {\n recordPreparedTask(new ServerTaskExecutor.ServerPreparedResponse(preparedOperation));\n }",
"public void notifyHeaderItemMoved(int fromPosition, int toPosition) {\n if (fromPosition < 0 || toPosition < 0 || fromPosition >= headerItemCount || toPosition >= headerItemCount) {\n throw new IndexOutOfBoundsException(\"The given fromPosition \" + fromPosition + \" or toPosition \" + toPosition + \" is not within the position bounds for header items [0 - \" + (headerItemCount - 1) + \"].\");\n }\n notifyItemMoved(fromPosition, toPosition);\n }",
"public static base_response update(nitro_service client, autoscaleprofile resource) throws Exception {\n\t\tautoscaleprofile updateresource = new autoscaleprofile();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.url = resource.url;\n\t\tupdateresource.apikey = resource.apikey;\n\t\tupdateresource.sharedsecret = resource.sharedsecret;\n\t\treturn updateresource.update_resource(client);\n\t}",
"@Deprecated\n public ClientConfig setNodeBannagePeriod(int nodeBannagePeriod, TimeUnit unit) {\n this.failureDetectorBannagePeriod = unit.toMillis(nodeBannagePeriod);\n return this;\n }",
"public static int hash(int input)\n {\n int k1 = mixK1(input);\n int h1 = mixH1(DEFAULT_SEED, k1);\n\n return fmix(h1, SizeOf.SIZE_OF_INT);\n }",
"private String getSignature(String sharedSecret, Map<String, String> params) {\r\n StringBuffer buffer = new StringBuffer();\r\n buffer.append(sharedSecret);\r\n for (Map.Entry<String, String> entry : params.entrySet()) {\r\n buffer.append(entry.getKey());\r\n buffer.append(entry.getValue());\r\n }\r\n\r\n try {\r\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\r\n return ByteUtilities.toHexString(md.digest(buffer.toString().getBytes(\"UTF-8\")));\r\n } catch (NoSuchAlgorithmException e) {\r\n throw new RuntimeException(e);\r\n } catch (UnsupportedEncodingException u) {\r\n throw new RuntimeException(u);\r\n }\r\n }",
"public Iterable<BoxTaskAssignment.Info> getAllAssignments(String ... fields) {\n final QueryStringBuilder builder = new QueryStringBuilder();\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields);\n }\n return new Iterable<BoxTaskAssignment.Info>() {\n public Iterator<BoxTaskAssignment.Info> iterator() {\n URL url = GET_ASSIGNMENTS_URL_TEMPLATE.buildWithQuery(\n BoxTask.this.getAPI().getBaseURL(), builder.toString(), BoxTask.this.getID());\n return new BoxTaskAssignmentIterator(BoxTask.this.getAPI(), url);\n }\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 static Command newInsert(Object object,\n String outIdentifier) {\n return getCommandFactoryProvider().newInsert( object,\n outIdentifier );\n }"
] |
Parameter validity check. | [
"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 final void setOrientation(int orientation) {\n mOrientation = orientation;\n mOrientationState = getOrientationStateFromParam(mOrientation);\n invalidate();\n if (mOuterAdapter != null) {\n mOuterAdapter.setOrientation(mOrientation);\n }\n\n }",
"public static double blackScholesOptionTheta(\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 theta\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 theta = volatility * Math.exp(-0.5*dPlus*dPlus) / Math.sqrt(2.0 * Math.PI) / Math.sqrt(optionMaturity) / 2 * initialStockValue + riskFreeRate * optionStrike * Math.exp(-riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus);\n\n\t\t\treturn theta;\n\t\t}\n\t}",
"public IPv6AddressSegment join(IPv6AddressCreator creator, IPv4AddressSegment low) throws IncompatibleAddressException {\r\n\t\tint shift = IPv4Address.BITS_PER_SEGMENT;\r\n\t\tInteger prefix = getJoinedSegmentPrefixLength(shift, getSegmentPrefixLength(), low.getSegmentPrefixLength());\r\n\t\tif(isMultiple()) {\r\n\t\t\t//if the high segment has a range, the low segment must match the full range, \r\n\t\t\t//otherwise it is not possible to create an equivalent range when joining\r\n\t\t\tif(!low.isFullRange()) {\r\n\t\t\t\tthrow new IncompatibleAddressException(this, low, \"ipaddress.error.invalidMixedRange\");\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn creator.createSegment(\r\n\t\t\t\t(getSegmentValue() << shift) | low.getSegmentValue(), \r\n\t\t\t\t(getUpperSegmentValue() << shift) | low.getUpperSegmentValue(),\r\n\t\t\t\tprefix);\r\n\t}",
"public static void ensureXPathNotEmpty(NodeList nodeList, String expression) {\n if (nodeList == null || nodeList.getLength() == 0) {\n throw LOG.unableToFindXPathExpression(expression);\n }\n }",
"public static boolean isBadXmlCharacter(char c) {\n boolean cDataCharacter = c < '\\u0020' && c != '\\t' && c != '\\r' && c != '\\n';\n cDataCharacter |= (c >= '\\uD800' && c < '\\uE000');\n cDataCharacter |= (c == '\\uFFFE' || c == '\\uFFFF');\n return cDataCharacter;\n }",
"public Headers getAllHeaders() {\n Headers requestHeaders = getHeaders();\n requestHeaders = hasPayload() ? requestHeaders.withContentType(getPayload().get().getMimeType()) : requestHeaders;\n //We don't want to add headers more than once.\n return requestHeaders;\n }",
"public static appfwpolicy_csvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwpolicy_csvserver_binding obj = new appfwpolicy_csvserver_binding();\n\t\tobj.set_name(name);\n\t\tappfwpolicy_csvserver_binding response[] = (appfwpolicy_csvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\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 }",
"public static final Date getTimestampFromTenths(byte[] data, int offset)\n {\n long ms = ((long) getInt(data, offset)) * 6000;\n return (DateHelper.getTimestampFromLong(EPOCH + ms));\n }"
] |
Gets the declared bean type
@return The bean type | [
"public static Type getDeclaredBeanType(Class<?> clazz) {\n Type[] actualTypeArguments = Reflections.getActualTypeArguments(clazz);\n if (actualTypeArguments.length == 1) {\n return actualTypeArguments[0];\n } else {\n return null;\n }\n }"
] | [
"private void onClickAdd() {\n\n if (m_currentLocation.isPresent()) {\n CmsFavoriteEntry entry = m_currentLocation.get();\n List<CmsFavoriteEntry> entries = getEntries();\n entries.add(entry);\n try {\n m_favDao.saveFavorites(entries);\n } catch (Exception e) {\n CmsErrorDialog.showErrorDialog(e);\n }\n m_context.close();\n }\n }",
"public static Command newInsert(Object object,\n String outIdentifier) {\n return getCommandFactoryProvider().newInsert( object,\n outIdentifier );\n }",
"public void removeChildTask(Task child)\n {\n if (m_children.remove(child))\n {\n child.m_parent = null;\n }\n setSummary(!m_children.isEmpty());\n }",
"public void setTimewarpInt(String timewarp) {\n\n try {\n m_userSettings.setTimeWarp(Long.valueOf(timewarp).longValue());\n } catch (Exception e) {\n m_userSettings.setTimeWarp(-1);\n }\n }",
"protected void queryTimerEnd(String sql, long queryStartTime) {\r\n\t\tif ((this.queryExecuteTimeLimit != 0) \r\n\t\t\t\t&& (this.connectionHook != null)){\r\n\t\t\tlong timeElapsed = (System.nanoTime() - queryStartTime);\r\n\t\t\t\r\n\t\t\tif (timeElapsed > this.queryExecuteTimeLimit){\r\n\t\t\t\tthis.connectionHook.onQueryExecuteTimeLimitExceeded(this.connectionHandle, this, sql, this.logParams, timeElapsed);\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tif (this.statisticsEnabled){\r\n\t\t\tthis.statistics.incrementStatementsExecuted();\r\n\t\t\tthis.statistics.addStatementExecuteTime(System.nanoTime() - queryStartTime);\r\n\t\t\t\r\n\t\t}\r\n\r\n\t}",
"protected void generateRoutes()\n {\n try {\n\n//\t\t\tOptional<io.sinistral.proteus.annotations.Chain> typeLevelWrapAnnotation = Optional.ofNullable(controllerClass.getAnnotation(io.sinistral.proteus.annotations.Chain.class));\n//\t\t\t\n//\t\t\ttypeLevelWrapAnnotation.ifPresent( a -> {\n//\t\t\t\t \n//\t\t\t\tio.sinistral.proteus.annotations.Chain w = typeLevelWrapAnnotation.get();\n//\n//\t\t\t\tClass<? extends HandlerWrapper> wrapperClasses[] = w.value();\n//\n//\t\t\t\tfor (int i = 0; i < wrapperClasses.length; i++)\n//\t\t\t\t{\n//\t\t\t\t\tClass<? extends HandlerWrapper> wrapperClass = wrapperClasses[i];\n//\n//\t\t\t\t\tString wrapperName = generateFieldName(wrapperClass.getCanonicalName());\n//\n//\t\t\t\t\thandlerWrapperMap.put(wrapperClass, wrapperName);\n//\t\t\t\t}\n//\t\t\t\t\n//\t\t\t});\n//\t\t\t\n//\t\t\tfor(Method m : this.controllerClass.getDeclaredMethods())\n//\t\t\t{\n//\t\t\t\n//\t\t\t\tOptional<io.sinistral.proteus.annotations.Chain> methodLevelWrapAnnotation = Optional.ofNullable(m.getAnnotation(io.sinistral.proteus.annotations.Chain.class));\n//\t\t\t\t\n//\t\t\t\tmethodLevelWrapAnnotation.ifPresent( a -> {\n//\t\t\t\t\t \n//\t\t\t\t\tio.sinistral.proteus.annotations.Chain w = methodLevelWrapAnnotation.get();\n//\t\n//\t\t\t\t\tClass<? extends HandlerWrapper> wrapperClasses[] = w.value();\n//\t\n//\t\t\t\t\tfor (int i = 0; i < wrapperClasses.length; i++)\n//\t\t\t\t\t{\n//\t\t\t\t\t\tClass<? extends HandlerWrapper> wrapperClass = wrapperClasses[i];\n//\t\n//\t\t\t\t\t\tString wrapperName = generateFieldName(wrapperClass.getCanonicalName());\n//\t\n//\t\t\t\t\t\thandlerWrapperMap.put(wrapperClass, wrapperName);\n//\t\t\t\t\t}\n//\t\t\t\t\t\n//\t\t\t\t});\n//\n//\t\t\t}\n//\t\t\t\n//\t\t\tlog.info(\"handlerWrapperMap: \" + handlerWrapperMap);\n\n TypeSpec.Builder typeBuilder = TypeSpec.classBuilder(className).addModifiers(Modifier.PUBLIC)\n .addSuperinterface(ParameterizedTypeName.get(Supplier.class, RoutingHandler.class));\n\n ClassName extractorClass = ClassName.get(\"io.sinistral.proteus.server\", \"Extractors\");\n\n ClassName injectClass = ClassName.get(\"com.google.inject\", \"Inject\");\n\n\n MethodSpec.Builder constructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addAnnotation(injectClass);\n\n String className = this.controllerClass.getSimpleName().toLowerCase() + \"Controller\";\n\n typeBuilder.addField(this.controllerClass, className, Modifier.PROTECTED, Modifier.FINAL);\n\n ClassName wrapperClass = ClassName.get(\"io.undertow.server\", \"HandlerWrapper\");\n ClassName stringClass = ClassName.get(\"java.lang\", \"String\");\n ClassName mapClass = ClassName.get(\"java.util\", \"Map\");\n\n TypeName mapOfWrappers = ParameterizedTypeName.get(mapClass, stringClass, wrapperClass);\n\n TypeName annotatedMapOfWrappers = mapOfWrappers\n .annotated(AnnotationSpec.builder(com.google.inject.name.Named.class).addMember(\"value\", \"$S\", \"registeredHandlerWrappers\").build());\n\n typeBuilder.addField(mapOfWrappers, \"registeredHandlerWrappers\", Modifier.PROTECTED, Modifier.FINAL);\n\n\n constructor.addParameter(this.controllerClass, className);\n constructor.addParameter(annotatedMapOfWrappers, \"registeredHandlerWrappers\");\n\n constructor.addStatement(\"this.$N = $N\", className, className);\n constructor.addStatement(\"this.$N = $N\", \"registeredHandlerWrappers\", \"registeredHandlerWrappers\");\n\n addClassMethodHandlers(typeBuilder, this.controllerClass);\n\n typeBuilder.addMethod(constructor.build());\n\n JavaFile javaFile = JavaFile.builder(packageName, typeBuilder.build()).addStaticImport(extractorClass, \"*\").build();\n\n StringBuilder sb = new StringBuilder();\n\n javaFile.writeTo(sb);\n\n this.sourceString = sb.toString();\n\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n }\n }",
"public final static String process(final String input, final Configuration configuration)\n {\n try\n {\n return process(new StringReader(input), configuration);\n }\n catch (final IOException e)\n {\n // This _can never_ happen\n return null;\n }\n }",
"public void sendJsonToUrl(Object data, String url) {\n sendToUrl(JSON.toJSONString(data), url);\n }",
"public ServerSocket createServerSocket() throws IOException {\n final ServerSocket socket = getServerSocketFactory().createServerSocket(name);\n socket.bind(getSocketAddress());\n return socket;\n }"
] |
Lift a Java Func2 to a Scala Function2
@param f the function to lift
@returns the Scala function | [
"public static<A, B, Z> Function2<A, B, Z> lift(Func2<A, B, Z> f) {\n\treturn bridge.lift(f);\n }"
] | [
"private boolean checkConverged(DMatrixRMaj A) {\n double worst = 0;\n double worst2 = 0;\n for( int j = 0; j < A.numRows; j++ ) {\n double val = Math.abs(q2.data[j] - q0.data[j]);\n if( val > worst ) worst = val;\n val = Math.abs(q2.data[j] + q0.data[j]);\n if( val > worst2 ) worst2 = val;\n }\n\n // swap vectors\n DMatrixRMaj temp = q0;\n q0 = q2;\n q2 = temp;\n\n if( worst < tol )\n return true;\n else if( worst2 < tol )\n return true;\n else\n return false;\n }",
"static String expandUriComponent(String source, UriTemplateVariables uriVariables) {\n\t\tif (source == null) {\n\t\t\treturn null;\n\t\t}\n\t\tif (source.indexOf('{') == -1) {\n\t\t\treturn source;\n\t\t}\n\t\tMatcher matcher = NAMES_PATTERN.matcher(source);\n\t\tStringBuffer sb = new StringBuffer();\n\t\twhile (matcher.find()) {\n\t\t\tString match = matcher.group(1);\n\t\t\tString variableName = getVariableName(match);\n\t\t\tObject variableValue = uriVariables.getValue(variableName);\n\t\t\tif (UriTemplateVariables.SKIP_VALUE.equals(variableValue)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tString variableValueString = getVariableValueAsString(variableValue);\n\t\t\tString replacement = Matcher.quoteReplacement(variableValueString);\n\t\t\tmatcher.appendReplacement(sb, replacement);\n\t\t}\n\t\tmatcher.appendTail(sb);\n\t\treturn sb.toString();\n\t}",
"public ProgressBar stop() {\n target.kill();\n try {\n thread.join();\n target.consoleStream.print(\"\\n\");\n target.consoleStream.flush();\n }\n catch (InterruptedException ex) { }\n return this;\n }",
"public static Project dependsOnArtifact(Artifact artifact)\n {\n Project project = new Project();\n project.artifact = artifact;\n return project;\n }",
"public final void printClientConfig(final JSONWriter json) throws JSONException {\n json.key(\"attributes\");\n json.array();\n for (Map.Entry<String, Attribute> entry: this.attributes.entrySet()) {\n Attribute attribute = entry.getValue();\n if (attribute.getClass().getAnnotation(InternalAttribute.class) == null) {\n json.object();\n attribute.printClientConfig(json, this);\n json.endObject();\n }\n }\n json.endArray();\n }",
"private void parseLdapAuthorization_1_5(final XMLExtendedStreamReader reader,\n final ModelNode realmAddress, final List<ModelNode> list) throws XMLStreamException {\n ModelNode addr = realmAddress.clone().add(AUTHORIZATION, LDAP);\n ModelNode ldapAuthorization = Util.getEmptyOperation(ADD, addr);\n\n list.add(ldapAuthorization);\n\n Set<Attribute> required = EnumSet.of(Attribute.CONNECTION);\n final int count = reader.getAttributeCount();\n for (int i = 0; i < count; i++) {\n final String value = reader.getAttributeValue(i);\n if (!isNoNamespaceAttribute(reader, i)) {\n throw unexpectedAttribute(reader, i);\n } else {\n final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));\n required.remove(attribute);\n switch (attribute) {\n case CONNECTION: {\n LdapAuthorizationResourceDefinition.CONNECTION.parseAndSetParameter(value, ldapAuthorization, reader);\n break;\n }\n default: {\n throw unexpectedAttribute(reader, i);\n }\n }\n }\n }\n\n if (required.isEmpty() == false) {\n throw missingRequired(reader, required);\n }\n\n Set<Element> foundElements = new HashSet<Element>();\n while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {\n requireNamespace(reader, namespace);\n final Element element = Element.forName(reader.getLocalName());\n if (foundElements.add(element) == false) {\n throw unexpectedElement(reader); // Only one of each allowed.\n }\n switch (element) {\n case USERNAME_TO_DN: {\n switch (namespace.getMajorVersion()) {\n case 1: // 1.5 up to but not including 2.0\n parseUsernameToDn_1_5(reader, addr, list);\n break;\n default: // 2.0 and onwards\n parseUsernameToDn_2_0(reader, addr, list);\n break;\n }\n\n break;\n }\n case GROUP_SEARCH: {\n switch (namespace) {\n case DOMAIN_1_5:\n case DOMAIN_1_6:\n parseGroupSearch_1_5(reader, addr, list);\n break;\n default:\n parseGroupSearch_1_7_and_2_0(reader, addr, list);\n break;\n }\n break;\n }\n default: {\n throw unexpectedElement(reader);\n }\n }\n }\n }",
"@Override\n public void solve(DMatrixRBlock B, DMatrixRBlock X) {\n if( B.blockLength != blockLength )\n throw new IllegalArgumentException(\"Unexpected blocklength in B.\");\n\n DSubmatrixD1 L = new DSubmatrixD1(decomposer.getT(null));\n\n if( X != null ) {\n if( X.blockLength != blockLength )\n throw new IllegalArgumentException(\"Unexpected blocklength in X.\");\n if( X.numRows != L.col1 ) throw new IllegalArgumentException(\"Not enough rows in X\");\n }\n \n if( B.numRows != L.col1 ) throw new IllegalArgumentException(\"Not enough rows in B\");\n\n // L * L^T*X = B\n\n // Solve for Y: L*Y = B\n TriangularSolver_DDRB.solve(blockLength,false,L,new DSubmatrixD1(B),false);\n\n // L^T * X = Y\n TriangularSolver_DDRB.solve(blockLength,false,L,new DSubmatrixD1(B),true);\n\n if( X != null ) {\n // copy the solution from B into X\n MatrixOps_DDRB.extractAligned(B,X);\n }\n\n }",
"public static Object getObjectFromColumn(ResultSet rs, Integer jdbcType, int columnId)\r\n throws SQLException\r\n {\r\n return getObjectFromColumn(rs, null, jdbcType, null, columnId);\r\n }",
"private void postProcessTasks() throws MPXJException\n {\n //\n // Renumber ID values using a large increment to allow\n // space for later inserts.\n //\n TreeMap<Integer, Integer> taskMap = new TreeMap<Integer, Integer>();\n\n // I've found a pathological case of an MPP file with around 102k blank tasks...\n int nextIDIncrement = 102000;\n int nextID = (m_file.getTaskByUniqueID(Integer.valueOf(0)) == null ? nextIDIncrement : 0);\n for (Map.Entry<Long, Integer> entry : m_taskOrder.entrySet())\n {\n taskMap.put(Integer.valueOf(nextID), entry.getValue());\n nextID += nextIDIncrement;\n }\n\n //\n // Insert any null tasks into the correct location\n //\n int insertionCount = 0;\n Map<Integer, Integer> offsetMap = new HashMap<Integer, Integer>();\n for (Map.Entry<Integer, Integer> entry : m_nullTaskOrder.entrySet())\n {\n int idValue = entry.getKey().intValue();\n int baseTargetIdValue = (idValue - insertionCount) * nextIDIncrement;\n int targetIDValue = baseTargetIdValue;\n Integer previousOffsetKey = Integer.valueOf(baseTargetIdValue);\n Integer previousOffset = offsetMap.get(previousOffsetKey);\n int offset = previousOffset == null ? 0 : previousOffset.intValue() + 1;\n ++insertionCount;\n\n while (taskMap.containsKey(Integer.valueOf(targetIDValue)))\n {\n ++offset;\n if (offset == nextIDIncrement)\n {\n throw new MPXJException(\"Unable to fix task order\");\n }\n targetIDValue = baseTargetIdValue - (nextIDIncrement - offset);\n }\n\n offsetMap.put(previousOffsetKey, Integer.valueOf(offset));\n taskMap.put(Integer.valueOf(targetIDValue), entry.getValue());\n }\n\n //\n // Finally, we can renumber the tasks\n //\n nextID = (m_file.getTaskByUniqueID(Integer.valueOf(0)) == null ? 1 : 0);\n for (Map.Entry<Integer, Integer> entry : taskMap.entrySet())\n {\n Task task = m_file.getTaskByUniqueID(entry.getValue());\n if (task != null)\n {\n task.setID(Integer.valueOf(nextID));\n }\n nextID++;\n }\n }"
] |
Sets the request body to the contents of a String.
<p>If the contents of the body are large, then it may be more efficient to use an {@link InputStream} instead of
a String. Using a String requires that the entire body be in memory before sending the request.</p>
@param body a String containing the contents of the body. | [
"public void setBody(String body) {\n byte[] bytes = body.getBytes(StandardCharsets.UTF_8);\n this.bodyLength = bytes.length;\n this.body = new ByteArrayInputStream(bytes);\n }"
] | [
"public static dnsview[] get(nitro_service service, String viewname[]) throws Exception{\n\t\tif (viewname !=null && viewname.length>0) {\n\t\t\tdnsview response[] = new dnsview[viewname.length];\n\t\t\tdnsview obj[] = new dnsview[viewname.length];\n\t\t\tfor (int i=0;i<viewname.length;i++) {\n\t\t\t\tobj[i] = new dnsview();\n\t\t\t\tobj[i].set_viewname(viewname[i]);\n\t\t\t\tresponse[i] = (dnsview) 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 boolean isLong(CharSequence self) {\n try {\n Long.valueOf(self.toString().trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n }",
"public static InternetPrintWriter createForEncoding(OutputStream outputStream, boolean autoFlush, Charset charset) {\r\n return new InternetPrintWriter(new OutputStreamWriter(outputStream, charset), autoFlush);\r\n }",
"private String getResourceType(Resource resource)\n {\n String result;\n net.sf.mpxj.ResourceType type = resource.getType();\n if (type == null)\n {\n type = net.sf.mpxj.ResourceType.WORK;\n }\n\n switch (type)\n {\n case MATERIAL:\n {\n result = \"Material\";\n break;\n }\n\n case COST:\n {\n result = \"Nonlabor\";\n break;\n }\n\n default:\n {\n result = \"Labor\";\n break;\n }\n }\n\n return result;\n }",
"public static boolean isMethodNamed(MethodCallExpression methodCall, String methodNamePattern, Integer numArguments) {\r\n Expression method = methodCall.getMethod();\r\n\r\n // !important: performance enhancement\r\n boolean IS_NAME_MATCH = false;\r\n if (method instanceof ConstantExpression) {\r\n if (((ConstantExpression) method).getValue() instanceof String) {\r\n IS_NAME_MATCH = ((String)((ConstantExpression) method).getValue()).matches(methodNamePattern);\r\n }\r\n }\r\n\r\n if (IS_NAME_MATCH && numArguments != null) {\r\n return AstUtil.getMethodArguments(methodCall).size() == numArguments;\r\n }\r\n return IS_NAME_MATCH;\r\n }",
"private static Object getParam(final Object param) {\n\t\tfinal StringBuilder sb = new StringBuilder();\n\t\tif(param instanceof String){\n\t\t\tsb.append(\"'\");\n\t\t\tsb.append((String)param);\n\t\t\tsb.append(\"'\");\n\t\t}\n\t\telse if(param instanceof Boolean){\n\t\t\tsb.append(String.valueOf((Boolean)param));\t\t\t\n\t\t}\n else if(param instanceof Integer){\n sb.append(String.valueOf((Integer)param));\n }\n else if(param instanceof DBRegExp){\n sb.append('/');\n sb.append(((DBRegExp) param).toString());\n sb.append('/');\n }\n\t\t\n\t\treturn sb.toString();\n\t}",
"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 }",
"public String getRepoKey() {\n String repoKey;\n if (isDynamicMode()) {\n repoKey = keyFromText;\n } else {\n repoKey = keyFromSelect;\n }\n return repoKey;\n }",
"public boolean contains(Date date)\n {\n boolean result = false;\n\n if (date != null)\n {\n result = (DateHelper.compare(getFromDate(), getToDate(), date) == 0);\n }\n\n return (result);\n }"
] |
Use this API to fetch all the transformpolicylabel resources that are configured on netscaler. | [
"public static transformpolicylabel[] get(nitro_service service) throws Exception{\n\t\ttransformpolicylabel obj = new transformpolicylabel();\n\t\ttransformpolicylabel[] response = (transformpolicylabel[])obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"protected View postDeclineView() {\n\t\treturn new TopLevelWindowRedirect() {\n\t\t\t@Override\n\t\t\tprotected String getRedirectUrl(Map<String, ?> model) {\n\t\t\t\treturn postDeclineUrl;\n\t\t\t}\n\t\t};\n\t}",
"public void setSchema(String schema)\n {\n if (schema.charAt(schema.length() - 1) != '.')\n {\n schema = schema + '.';\n }\n m_schema = schema;\n }",
"public static base_response reset(nitro_service client) throws Exception {\n\t\tappfwlearningdata resetresource = new appfwlearningdata();\n\t\treturn resetresource.perform_operation(client,\"reset\");\n\t}",
"@Subscribe\n public void onQuit(AggregatedQuitEvent e) {\n if (summaryFile != null) {\n try {\n Persister persister = new Persister();\n persister.write(new MavenFailsafeSummaryModel(summaryListener.getResult()), summaryFile);\n } catch (Exception x) {\n junit4.log(\"Could not serialize summary report.\", x, Project.MSG_WARN);\n }\n }\n }",
"@SuppressWarnings(\"unchecked\")\n public <T extends ReportModel> T getReportByName(String name, Class<T> clazz)\n {\n WindupVertexFrame model = this.getUniqueByProperty(ReportModel.REPORT_NAME, name);\n try\n {\n return (T) model;\n }\n catch (ClassCastException ex)\n {\n throw new WindupException(\"The vertex is not of expected frame type \" + clazz.getName() + \": \" + model.toPrettyString());\n }\n }",
"public List<CmsFavoriteEntry> loadFavorites() throws CmsException {\n\n List<CmsFavoriteEntry> result = new ArrayList<>();\n try {\n CmsUser user = readUser();\n String data = (String)user.getAdditionalInfo(ADDINFO_KEY);\n if (CmsStringUtil.isEmptyOrWhitespaceOnly(data)) {\n return new ArrayList<>();\n }\n JSONObject json = new JSONObject(data);\n JSONArray array = json.getJSONArray(BASE_KEY);\n for (int i = 0; i < array.length(); i++) {\n JSONObject fav = array.getJSONObject(i);\n try {\n CmsFavoriteEntry entry = new CmsFavoriteEntry(fav);\n if (validate(entry)) {\n result.add(entry);\n }\n } catch (Exception e) {\n LOG.warn(e.getLocalizedMessage(), e);\n }\n\n }\n } catch (JSONException e) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n return result;\n }",
"@Nullable\n public final Credentials toCredentials(final AuthScope authscope) {\n try {\n\n if (!matches(MatchInfo.fromAuthScope(authscope))) {\n return null;\n }\n } catch (UnknownHostException | MalformedURLException | SocketException e) {\n throw new RuntimeException(e);\n }\n if (this.username == null) {\n return null;\n }\n\n final String passwordString;\n if (this.password != null) {\n passwordString = new String(this.password);\n } else {\n passwordString = null;\n }\n return new UsernamePasswordCredentials(this.username, passwordString);\n }",
"public List<T> parseList(JsonParser jsonParser) throws IOException {\n List<T> list = new ArrayList<>();\n if (jsonParser.getCurrentToken() == JsonToken.START_ARRAY) {\n while (jsonParser.nextToken() != JsonToken.END_ARRAY) {\n list.add(parse(jsonParser));\n }\n }\n return list;\n }",
"protected void addConstructors(ClassFile proxyClassType, List<DeferredBytecode> initialValueBytecode) {\n try {\n if (getBeanType().isInterface()) {\n ConstructorUtils.addDefaultConstructor(proxyClassType, initialValueBytecode, !useConstructedFlag());\n } else {\n boolean constructorFound = false;\n for (Constructor<?> constructor : AccessController.doPrivileged(new GetDeclaredConstructorsAction(getBeanType()))) {\n if ((constructor.getModifiers() & Modifier.PRIVATE) == 0) {\n constructorFound = true;\n String[] exceptions = new String[constructor.getExceptionTypes().length];\n for (int i = 0; i < exceptions.length; ++i) {\n exceptions[i] = constructor.getExceptionTypes()[i].getName();\n }\n ConstructorUtils.addConstructor(BytecodeUtils.VOID_CLASS_DESCRIPTOR, DescriptorUtils.parameterDescriptors(constructor.getParameterTypes()), exceptions, proxyClassType, initialValueBytecode, !useConstructedFlag());\n }\n }\n if (!constructorFound) {\n // the bean only has private constructors, we need to generate\n // two fake constructors that call each other\n addConstructorsForBeanWithPrivateConstructors(proxyClassType);\n }\n }\n } catch (Exception e) {\n throw new WeldException(e);\n }\n }"
] |
Bean types of a session bean. | [
"private static <T> Set<Type> getSessionBeanTypes(EnhancedAnnotated<T, ?> annotated, EjbDescriptor<T> ejbDescriptor) {\n ImmutableSet.Builder<Type> types = ImmutableSet.builder();\n // session beans\n Map<Class<?>, Type> typeMap = new LinkedHashMap<Class<?>, Type>();\n HierarchyDiscovery beanClassDiscovery = HierarchyDiscovery.forNormalizedType(ejbDescriptor.getBeanClass());\n for (BusinessInterfaceDescriptor<?> businessInterfaceDescriptor : ejbDescriptor.getLocalBusinessInterfaces()) {\n // first we need to resolve the local interface\n Type resolvedLocalInterface = beanClassDiscovery.resolveType(Types.getCanonicalType(businessInterfaceDescriptor.getInterface()));\n SessionBeanHierarchyDiscovery interfaceDiscovery = new SessionBeanHierarchyDiscovery(resolvedLocalInterface);\n if (beanClassDiscovery.getTypeMap().containsKey(businessInterfaceDescriptor.getInterface())) {\n // WELD-1675 Only add types also included in Annotated.getTypeClosure()\n for (Entry<Class<?>, Type> entry : interfaceDiscovery.getTypeMap().entrySet()) {\n if (annotated.getTypeClosure().contains(entry.getValue())) {\n typeMap.put(entry.getKey(), entry.getValue());\n }\n }\n } else {\n // Session bean class does not implement the business interface and @javax.ejb.Local applied to the session bean class\n typeMap.putAll(interfaceDiscovery.getTypeMap());\n }\n }\n if (annotated.isAnnotationPresent(Typed.class)) {\n types.addAll(Beans.getTypedTypes(typeMap, annotated.getJavaClass(), annotated.getAnnotation(Typed.class)));\n } else {\n typeMap.put(Object.class, Object.class);\n types.addAll(typeMap.values());\n }\n return Beans.getLegalBeanTypes(types.build(), annotated);\n }"
] | [
"public static float noise1(float x) {\n int bx0, bx1;\n float rx0, rx1, sx, t, u, v;\n\n if (start) {\n start = false;\n init();\n }\n\n t = x + N;\n bx0 = ((int)t) & BM;\n bx1 = (bx0+1) & BM;\n rx0 = t - (int)t;\n rx1 = rx0 - 1.0f;\n\n sx = sCurve(rx0);\n\n u = rx0 * g1[p[bx0]];\n v = rx1 * g1[p[bx1]];\n return 2.3f*lerp(sx, u, v);\n }",
"public void afterDeploymentValidation(@Observes @Priority(1) AfterDeploymentValidation event, BeanManager beanManager) {\n BeanManagerImpl manager = BeanManagerProxy.unwrap(beanManager);\n probe.init(manager);\n if (isJMXSupportEnabled(manager)) {\n try {\n MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();\n mbs.registerMBean(new ProbeDynamicMBean(jsonDataProvider, JsonDataProvider.class), constructProbeJsonDataMBeanName(manager, probe));\n } catch (MalformedObjectNameException | InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) {\n event.addDeploymentProblem(ProbeLogger.LOG.unableToRegisterMBean(JsonDataProvider.class, manager.getContextId(), e));\n }\n }\n addContainerLifecycleEvent(event, null, beanManager);\n exportDataIfNeeded(manager);\n }",
"private void addToGraph(ClassDoc cd) {\n\t// avoid adding twice the same class, but don't rely on cg.getClassInfo\n\t// since there are other ways to add a classInfor than printing the class\n\tif (visited.contains(cd.toString()))\n\t return;\n\n\tvisited.add(cd.toString());\n\tcg.printClass(cd, false);\n\tcg.printRelations(cd);\n\tif (opt.inferRelationships)\n\t cg.printInferredRelations(cd);\n\tif (opt.inferDependencies)\n\t cg.printInferredDependencies(cd);\n }",
"private void flushHotCacheSlot(SlotReference slot) {\n // Iterate over a copy to avoid concurrent modification issues\n for (Map.Entry<DeckReference, TrackMetadata> entry : new HashMap<DeckReference,TrackMetadata>(hotCache).entrySet()) {\n if (slot == SlotReference.getSlotReference(entry.getValue().trackReference)) {\n logger.debug(\"Evicting cached metadata in response to unmount report {}\", entry.getValue());\n hotCache.remove(entry.getKey());\n }\n }\n }",
"public void registerDropPasteWorker(DropPasteWorkerInterface worker)\r\n {\r\n this.dropPasteWorkerSet.add(worker);\r\n defaultDropTarget.setDefaultActions( \r\n defaultDropTarget.getDefaultActions() \r\n | worker.getAcceptableActions(defaultDropTarget.getComponent())\r\n );\r\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 ModelControllerClient createAndAdd(final ManagementChannelHandler handler) {\n final ExistingChannelModelControllerClient client = new ExistingChannelModelControllerClient(handler);\n handler.addHandlerFactory(client);\n return client;\n }",
"public static String getSerializedVectorClocks(List<VectorClock> vectorClocks) {\n List<VectorClockWrapper> vectorClockWrappers = new ArrayList<VectorClockWrapper>();\n for(VectorClock vc: vectorClocks) {\n vectorClockWrappers.add(new VectorClockWrapper(vc));\n }\n String serializedVC = \"\";\n try {\n serializedVC = mapper.writeValueAsString(vectorClockWrappers);\n } catch(Exception e) {\n e.printStackTrace();\n }\n return serializedVC;\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 }"
] |
Append the text supplied by the Writer at the end of the File, using a specified encoding.
@param file a File
@param writer the Writer supplying the text to append at the end of the File
@param charset the charset used
@throws IOException if an IOException occurs.
@since 2.3 | [
"public static void append(File file, Writer writer, String charset) throws IOException {\n appendBuffered(file, writer, charset);\n }"
] | [
"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 checkPrimaryKey(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 if (classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, true) &&\r\n classDef.getPrimaryKeys().isEmpty())\r\n {\r\n LogHelper.warn(true,\r\n getClass(),\r\n \"checkPrimaryKey\",\r\n \"The class \"+classDef.getName()+\" has no primary key\");\r\n }\r\n }",
"public static List<Node> getSiblings(Node parent, Node element) {\n\t\tList<Node> result = new ArrayList<>();\n\t\tNodeList list = parent.getChildNodes();\n\n\t\tfor (int i = 0; i < list.getLength(); i++) {\n\t\t\tNode el = list.item(i);\n\n\t\t\tif (el.getNodeName().equals(element.getNodeName())) {\n\t\t\t\tresult.add(el);\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}",
"public void setSize(int size) {\n if (size != MaterialProgressDrawable.LARGE && size != MaterialProgressDrawable.DEFAULT) {\n return;\n }\n final DisplayMetrics metrics = getResources().getDisplayMetrics();\n if (size == MaterialProgressDrawable.LARGE) {\n mCircleHeight = mCircleWidth = (int) (CIRCLE_DIAMETER_LARGE * metrics.density);\n } else {\n mCircleHeight = mCircleWidth = (int) (CIRCLE_DIAMETER * metrics.density);\n }\n // force the bounds of the progress circle inside the circle view to\n // update by setting it to null before updating its size and then\n // re-setting it\n mCircleView.setImageDrawable(null);\n mProgress.updateSizes(size);\n mCircleView.setImageDrawable(mProgress);\n }",
"@Nullable\n public final String getStringContent(final long blobHandle, @NotNull final Transaction txn) throws IOException {\n String result;\n result = stringContentCache.tryKey(this, blobHandle);\n if (result == null) {\n final InputStream content = getContent(blobHandle, txn);\n if (content == null) {\n logger.error(\"Blob string not found: \" + getBlobLocation(blobHandle), new FileNotFoundException());\n }\n result = content == null ? null : UTFUtil.readUTF(content);\n if (result != null && result.length() <= config.getBlobStringsCacheMaxValueSize()) {\n if (stringContentCache.getObject(this, blobHandle) == null) {\n stringContentCache.cacheObject(this, blobHandle, result);\n }\n }\n }\n return result;\n }",
"@Deprecated\r\n public Location resolvePlaceURL(String flickrPlacesUrl) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_RESOLVE_PLACE_URL);\r\n\r\n parameters.put(\"url\", flickrPlacesUrl);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element locationElement = response.getPayload();\r\n return parseLocation(locationElement);\r\n }",
"@Override\n public ConditionBuilder as(String variable)\n {\n Assert.notNull(variable, \"Variable name must not be null.\");\n this.setOutputVariablesName(variable);\n return this;\n }",
"@Override\n\tpublic void write(final char[] cbuf, final int off, final int len) throws IOException {\n\t\tint offset = off;\n\t\tint length = len;\n\t\twhile (suppressLineCount > 0 && length > 0) {\n\t\t\tlength = -1;\n\t\t\tfor (int i = 0; i < len && suppressLineCount > 0; i++) {\n\t\t\t\tif (cbuf[off + i] == '\\n') {\n\t\t\t\t\toffset = off + i + 1;\n\t\t\t\t\tlength = len - i - 1;\n\t\t\t\t\tsuppressLineCount--;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (length <= 0)\n\t\t\t\treturn;\n\t\t}\n\t\tdelegate.write(cbuf, offset, length);\n\t}",
"public static synchronized void registerDao(ConnectionSource connectionSource, Dao<?, ?> dao) {\n\t\tif (connectionSource == null) {\n\t\t\tthrow new IllegalArgumentException(\"connectionSource argument cannot be null\");\n\t\t}\n\t\taddDaoToClassMap(new ClassConnectionSource(connectionSource, dao.getDataClass()), dao);\n\t}"
] |
Checks if the provided module is valid and could be stored into the database
@param module the module to test
@throws WebApplicationException if the data is corrupted | [
"public static void validate(final Module module) {\n if (null == module) {\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Module cannot be null!\")\n .build());\n }\n if(module.getName() == null ||\n module.getName().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Module name cannot be null or empty!\")\n .build());\n }\n if(module.getVersion()== null ||\n module.getVersion().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Module version cannot be null or empty!\")\n .build());\n }\n\n // Check artifacts\n for(final Artifact artifact: DataUtils.getAllArtifacts(module)){\n validate(artifact);\n }\n\n // Check dependencies\n for(final Dependency dependency: DataUtils.getAllDependencies(module)){\n validate(dependency.getTarget());\n }\n }"
] | [
"@Override\n public boolean minimize(DifferentiableBatchFunction function, IntDoubleVector point) {\n return minimize(function, point, null);\n }",
"public static base_responses clear(nitro_service client, bridgetable resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tbridgetable clearresources[] = new bridgetable[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tclearresources[i] = new bridgetable();\n\t\t\t\tclearresources[i].vlan = resources[i].vlan;\n\t\t\t\tclearresources[i].ifnum = resources[i].ifnum;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, clearresources,\"clear\");\n\t\t}\n\t\treturn result;\n\t}",
"private Charset getCharset()\n {\n Charset result = m_charset;\n if (result == null)\n {\n // We default to CP1252 as this seems to be the most common encoding\n result = m_encoding == null ? CharsetHelper.CP1252 : Charset.forName(m_encoding);\n }\n return result;\n }",
"public static Timer getNamedTotalTimer(String timerName) {\n\t\tlong totalCpuTime = 0;\n\t\tlong totalSystemTime = 0;\n\t\tint measurements = 0;\n\t\tint timerCount = 0;\n\t\tint todoFlags = RECORD_NONE;\n\n\t\tTimer previousTimer = null;\n\t\tfor (Map.Entry<Timer, Timer> entry : registeredTimers.entrySet()) {\n\t\t\tif (entry.getValue().name.equals(timerName)) {\n\t\t\t\tpreviousTimer = entry.getValue();\n\t\t\t\ttimerCount += 1;\n\t\t\t\ttotalCpuTime += previousTimer.totalCpuTime;\n\t\t\t\ttotalSystemTime += previousTimer.totalWallTime;\n\t\t\t\tmeasurements += previousTimer.measurements;\n\t\t\t\ttodoFlags |= previousTimer.todoFlags;\n\t\t\t}\n\t\t}\n\n\t\tif (timerCount == 1) {\n\t\t\treturn previousTimer;\n\t\t} else {\n\t\t\tTimer result = new Timer(timerName, todoFlags, 0);\n\t\t\tresult.totalCpuTime = totalCpuTime;\n\t\t\tresult.totalWallTime = totalSystemTime;\n\t\t\tresult.measurements = measurements;\n\t\t\tresult.threadCount = timerCount;\n\t\t\treturn result;\n\t\t}\n\t}",
"@Override\n public void close() {\n if (closed)\n return;\n closed = true;\n tcpSocketConsumer.prepareToShutdown();\n\n if (shouldSendCloseMessage)\n\n eventLoop.addHandler(new EventHandler() {\n @Override\n public boolean action() throws InvalidEventHandlerException {\n try {\n TcpChannelHub.this.sendCloseMessage();\n tcpSocketConsumer.stop();\n closed = true;\n\n if (LOG.isDebugEnabled())\n Jvm.debug().on(getClass(), \"closing connection to \" + socketAddressSupplier);\n\n while (clientChannel != null) {\n\n if (LOG.isDebugEnabled())\n Jvm.debug().on(getClass(), \"waiting for disconnect to \" + socketAddressSupplier);\n }\n } catch (ConnectionDroppedException e) {\n throw new InvalidEventHandlerException(e);\n }\n\n // we just want this to run once\n throw new InvalidEventHandlerException();\n }\n\n @NotNull\n @Override\n public String toString() {\n return TcpChannelHub.class.getSimpleName() + \"..close()\";\n }\n });\n }",
"public HiveShellContainer evaluateStatement(List<? extends Script> scripts, Object target, TemporaryFolder temporaryFolder, Statement base) throws Throwable {\n container = null;\n FileUtil.setPermission(temporaryFolder.getRoot(), FsPermission.getDirDefault());\n try {\n LOGGER.info(\"Setting up {} in {}\", getName(), temporaryFolder.getRoot().getAbsolutePath());\n container = createHiveServerContainer(scripts, target, temporaryFolder);\n base.evaluate();\n return container;\n } finally {\n tearDown();\n }\n }",
"okhttp3.Response get(String url, Map<String, Object> params)\n throws RequestException, LocalOperationException {\n\n String fullUrl = getFullUrl(url);\n okhttp3.Request request = new okhttp3.Request.Builder()\n .url(addUrlParams(fullUrl, toPayload(params)))\n .addHeader(\"Transloadit-Client\", version)\n .build();\n\n try {\n return httpClient.newCall(request).execute();\n } catch (IOException e) {\n throw new RequestException(e);\n }\n }",
"@Deprecated\n public static <T> T buildJsonResponse(Response response, Class<T> clazz) throws IOException, SlackApiException {\n if (response.code() == 200) {\n String body = response.body().string();\n DETAILED_LOGGER.accept(new HttpResponseListener.State(SlackConfig.DEFAULT, response, body));\n return GsonFactory.createSnakeCase().fromJson(body, clazz);\n } else {\n String body = response.body().string();\n throw new SlackApiException(response, body);\n }\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 }"
] |
Apply the remote read domain model result.
@param result the domain model result
@return whether it was applied successfully or not | [
"boolean applyDomainModel(ModelNode result) {\n if(! result.hasDefined(ModelDescriptionConstants.RESULT)) {\n return false;\n }\n final List<ModelNode> bootOperations= result.get(ModelDescriptionConstants.RESULT).asList();\n return callback.applyDomainModel(bootOperations);\n }"
] | [
"private void writeCustomFields() throws IOException\n {\n m_writer.writeStartList(\"custom_fields\");\n for (CustomField field : m_projectFile.getCustomFields())\n {\n writeCustomField(field);\n }\n m_writer.writeEndList();\n }",
"private void ensureToolValidForCreation(ExternalTool tool) {\n //check for the unconditionally required fields\n if(StringUtils.isAnyBlank(tool.getName(), tool.getPrivacyLevel(), tool.getConsumerKey(), tool.getSharedSecret())) {\n throw new IllegalArgumentException(\"External tool requires all of the following for creation: name, privacy level, consumer key, shared secret\");\n }\n //check that there is either a URL or a domain. One or the other is required\n if(StringUtils.isBlank(tool.getUrl()) && StringUtils.isBlank(tool.getDomain())) {\n throw new IllegalArgumentException(\"External tool requires either a URL or domain for creation\");\n }\n }",
"public void declareShovel(String vhost, ShovelInfo info) {\n Map<String, Object> props = info.getDetails().getPublishProperties();\n if(props != null && props.isEmpty()) {\n throw new IllegalArgumentException(\"Shovel publish properties must be a non-empty map or null\");\n }\n final URI uri = uriWithPath(\"./parameters/shovel/\" + encodePathSegment(vhost) + \"/\" + encodePathSegment(info.getName()));\n this.rt.put(uri, info);\n }",
"@Override\n public void accept(ICompilationUnit sourceUnit, AccessRestriction accessRestriction) {\n // Switch the current policy and compilation result for this unit to the requested one.\n CompilationResult unitResult =\n new CompilationResult(sourceUnit, this.totalUnits, this.totalUnits, this.options.maxProblemsPerUnit);\n unitResult.checkSecondaryTypes = true;\n try {\n if (this.options.verbose) {\n String count = String.valueOf(this.totalUnits + 1);\n this.out.println(\n Messages.bind(Messages.compilation_request,\n new String[] {\n count,\n count,\n new String(sourceUnit.getFileName())\n }));\n }\n // diet parsing for large collection of unit\n CompilationUnitDeclaration parsedUnit;\n if (this.totalUnits < this.parseThreshold) {\n parsedUnit = this.parser.parse(sourceUnit, unitResult);\n } else {\n parsedUnit = this.parser.dietParse(sourceUnit, unitResult);\n }\n // initial type binding creation\n this.lookupEnvironment.buildTypeBindings(parsedUnit, accessRestriction);\n addCompilationUnit(sourceUnit, parsedUnit);\n\n // binding resolution\n this.lookupEnvironment.completeTypeBindings(parsedUnit);\n } catch (AbortCompilationUnit e) {\n // at this point, currentCompilationUnitResult may not be sourceUnit, but some other\n // one requested further along to resolve sourceUnit.\n if (unitResult.compilationUnit == sourceUnit) { // only report once\n this.requestor.acceptResult(unitResult.tagAsAccepted());\n } else {\n throw e; // want to abort enclosing request to compile\n }\n }\n }",
"void writeSomeValueRestriction(String propertyUri, String rangeUri,\n\t\t\tResource bnode) throws RDFHandlerException {\n\t\tthis.rdfWriter.writeTripleValueObject(bnode, RdfWriter.RDF_TYPE,\n\t\t\t\tRdfWriter.OWL_RESTRICTION);\n\t\tthis.rdfWriter.writeTripleUriObject(bnode, RdfWriter.OWL_ON_PROPERTY,\n\t\t\t\tpropertyUri);\n\t\tthis.rdfWriter.writeTripleUriObject(bnode,\n\t\t\t\tRdfWriter.OWL_SOME_VALUES_FROM, rangeUri);\n\t}",
"protected void addPropertiesStart(String type) {\n putProperty(PropertyKey.Host.name(), IpUtils.getHostName());\n putProperty(PropertyKey.Type.name(), type);\n putProperty(PropertyKey.Status.name(), Status.Start.name());\n }",
"public double getBearing(LatLong end) {\n if (this.equals(end)) {\n return 0;\n }\n\n double lat1 = latToRadians();\n double lon1 = longToRadians();\n double lat2 = end.latToRadians();\n double lon2 = end.longToRadians();\n\n double angle = -Math.atan2(Math.sin(lon1 - lon2) * Math.cos(lat2),\n Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)\n * Math.cos(lat2) * Math.cos(lon1 - lon2));\n\n if (angle < 0.0) {\n angle += Math.PI * 2.0;\n }\n if (angle > Math.PI) {\n angle -= Math.PI * 2.0;\n }\n\n return Math.toDegrees(angle);\n }",
"private void deliverBeatAnnouncement(final Beat beat) {\n for (final MasterListener listener : getMasterListeners()) {\n try {\n listener.newBeat(beat);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering master beat announcement to listener\", t);\n }\n }\n }",
"@Override public void setID(Integer val)\n {\n ProjectFile parent = getParentFile();\n Integer previous = getID();\n\n if (previous != null)\n {\n parent.getTasks().unmapID(previous);\n }\n\n parent.getTasks().mapID(val, this);\n\n set(TaskField.ID, val);\n }"
] |
Calculate start dates for a monthly recurrence.
@param calendar current date
@param frequency frequency
@param dates array of start dates | [
"private void getMonthlyDates(Calendar calendar, int frequency, List<Date> dates)\n {\n if (m_relative)\n {\n getMonthlyRelativeDates(calendar, frequency, dates);\n }\n else\n {\n getMonthlyAbsoluteDates(calendar, frequency, dates);\n }\n }"
] | [
"public static String getAt(GString text, Range range) {\n return getAt(text.toString(), range);\n }",
"private static JsonArray getJsonArray(List<String> keys) {\n JsonArray array = new JsonArray();\n for (String key : keys) {\n array.add(key);\n }\n\n return array;\n }",
"void update(JsonObject jsonObject) {\n for (JsonObject.Member member : jsonObject) {\n if (member.getValue().isNull()) {\n continue;\n }\n\n this.parseJSONMember(member);\n }\n\n this.clearPendingChanges();\n }",
"public static void writeProcessorOutputToValues(\n final Object output,\n final Processor<?, ?> processor,\n final Values values) {\n Map<String, String> mapper = processor.getOutputMapperBiMap();\n if (mapper == null) {\n mapper = Collections.emptyMap();\n }\n\n final Collection<Field> fields = getAllAttributes(output.getClass());\n for (Field field: fields) {\n String name = getOutputValueName(processor.getOutputPrefix(), mapper, field);\n try {\n final Object value = field.get(output);\n if (value != null) {\n values.put(name, value);\n } else {\n values.remove(name);\n }\n } catch (IllegalAccessException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }\n }",
"public final String getPath(final String key) {\n StringBuilder result = new StringBuilder();\n addPathTo(result);\n result.append(\".\");\n result.append(getPathElement(key));\n return result.toString();\n }",
"@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n public void blacklistNode(int nodeId) {\n Collection<Node> nodesInCluster = adminClient.getAdminClientCluster().getNodes();\n\n if(blackListedNodes == null) {\n blackListedNodes = new ArrayList();\n }\n blackListedNodes.add(nodeId);\n\n for(Node node: nodesInCluster) {\n\n if(node.getId() == nodeId) {\n nodesToStream.remove(node);\n break;\n }\n\n }\n\n for(String store: storeNames) {\n try {\n SocketAndStreams sands = nodeIdStoreToSocketAndStreams.get(new Pair(store, nodeId));\n close(sands.getSocket());\n SocketDestination destination = nodeIdStoreToSocketRequest.get(new Pair(store,\n nodeId));\n streamingSocketPool.checkin(destination, sands);\n } catch(Exception ioE) {\n logger.error(ioE);\n }\n }\n }",
"public void setCloseConnectionWatchTimeout(long closeConnectionWatchTimeout, TimeUnit timeUnit) {\n\t\tthis.closeConnectionWatchTimeoutInMs = TimeUnit.MILLISECONDS.convert(closeConnectionWatchTimeout, timeUnit);\n\t}",
"void backupConfiguration() throws IOException {\n\n final String configuration = Constants.CONFIGURATION;\n\n final File a = new File(installedImage.getAppClientDir(), configuration);\n final File d = new File(installedImage.getDomainDir(), configuration);\n final File s = new File(installedImage.getStandaloneDir(), configuration);\n\n if (a.exists()) {\n final File ab = new File(configBackup, Constants.APP_CLIENT);\n backupDirectory(a, ab);\n }\n if (d.exists()) {\n final File db = new File(configBackup, Constants.DOMAIN);\n backupDirectory(d, db);\n }\n if (s.exists()) {\n final File sb = new File(configBackup, Constants.STANDALONE);\n backupDirectory(s, sb);\n }\n\n }",
"private Integer getNullOnValue(Integer value, int nullValue)\n {\n return (NumberHelper.getInt(value) == nullValue ? null : value);\n }"
] |
Load the given configuration file. | [
"public static void load(File file)\n {\n try(FileInputStream inputStream = new FileInputStream(file))\n {\n LineIterator it = IOUtils.lineIterator(inputStream, \"UTF-8\");\n while (it.hasNext())\n {\n String line = it.next();\n if (!line.startsWith(\"#\") && !line.trim().isEmpty())\n {\n add(line);\n }\n }\n }\n catch (Exception e)\n {\n throw new WindupException(\"Failed loading archive ignore patterns from [\" + file.toString() + \"]\", e);\n }\n }"
] | [
"private void processActivity(Activity activity)\n {\n Task task = getParentTask(activity).addTask();\n task.setText(1, activity.getId());\n\n task.setActualDuration(activity.getActualDuration());\n task.setActualFinish(activity.getActualFinish());\n task.setActualStart(activity.getActualStart());\n //activity.getBaseunit()\n //activity.getBilled()\n //activity.getCalendar()\n //activity.getCostAccount()\n task.setCreateDate(activity.getCreationTime());\n task.setFinish(activity.getCurrentFinish());\n task.setStart(activity.getCurrentStart());\n task.setName(activity.getDescription());\n task.setDuration(activity.getDurationAtCompletion());\n task.setEarlyFinish(activity.getEarlyFinish());\n task.setEarlyStart(activity.getEarlyStart());\n task.setFreeSlack(activity.getFreeFloat());\n task.setLateFinish(activity.getLateFinish());\n task.setLateStart(activity.getLateStart());\n task.setNotes(activity.getNotes());\n task.setBaselineDuration(activity.getOriginalDuration());\n //activity.getPathFloat()\n task.setPhysicalPercentComplete(activity.getPhysicalPercentComplete());\n task.setRemainingDuration(activity.getRemainingDuration());\n task.setCost(activity.getTotalCost());\n task.setTotalSlack(activity.getTotalFloat());\n task.setMilestone(activityIsMilestone(activity));\n //activity.getUserDefined()\n task.setGUID(activity.getUuid());\n\n if (task.getMilestone())\n {\n if (activityIsStartMilestone(activity))\n {\n task.setFinish(task.getStart());\n }\n else\n {\n task.setStart(task.getFinish());\n }\n }\n\n if (task.getActualStart() == null)\n {\n task.setPercentageComplete(Integer.valueOf(0));\n }\n else\n {\n if (task.getActualFinish() != null)\n {\n task.setPercentageComplete(Integer.valueOf(100));\n }\n else\n {\n Duration remaining = activity.getRemainingDuration();\n Duration total = activity.getDurationAtCompletion();\n if (remaining != null && total != null && total.getDuration() != 0)\n {\n double percentComplete = ((total.getDuration() - remaining.getDuration()) * 100.0) / total.getDuration();\n task.setPercentageComplete(Double.valueOf(percentComplete));\n }\n }\n }\n\n m_activityMap.put(activity.getId(), task);\n }",
"public <T> void setState(HttpConnectionInterceptor interceptor, String stateName, T\n stateObjectToStore) {\n Map<String, Object> state = interceptorStates.get(interceptor);\n if (state == null) {\n interceptorStates.put(interceptor, (state = new ConcurrentHashMap<String, Object>()));\n }\n state.put(stateName, stateObjectToStore);\n }",
"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}",
"public static String getStatusText(int nHttpStatusCode) {\n\n Integer intKey = new Integer(nHttpStatusCode);\n\n if (!mapStatusCodes.containsKey(intKey)) {\n return \"\";\n } else {\n return mapStatusCodes.get(intKey);\n }\n }",
"public static List<GVRAtlasInformation> loadAtlasInformation(InputStream ins) {\n try {\n int size = ins.available();\n byte[] buffer = new byte[size];\n\n ins.read(buffer);\n\n return loadAtlasInformation(new JSONArray(new String(buffer, \"UTF-8\")));\n } catch (JSONException je) {\n je.printStackTrace();\n } catch (IOException ex) {\n ex.printStackTrace();\n }\n\n return null;\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 }",
"public BoxUser.Info getInfo(String... fields) {\n URL url;\n if (fields.length > 0) {\n String queryString = new QueryStringBuilder().appendParam(\"fields\", fields).toString();\n url = USER_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID());\n } else {\n url = USER_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n }\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n return new Info(jsonObject);\n }",
"private void markDateInvocation() {\n\n _updatePreviousDates = !_dateGivenInGroup;\n _dateGivenInGroup = true;\n _dateGroup.setDateInferred(false);\n\n if(_firstDateInvocationInGroup) {\n // if a time has been given within the current date group, \n // we capture the current time before resetting the calendar\n if(_timeGivenInGroup) {\n int hours = _calendar.get(Calendar.HOUR_OF_DAY);\n int minutes = _calendar.get(Calendar.MINUTE);\n int seconds = _calendar.get(Calendar.SECOND);\n resetCalendar();\n _calendar.set(Calendar.HOUR_OF_DAY, hours);\n _calendar.set(Calendar.MINUTE, minutes);\n _calendar.set(Calendar.SECOND, seconds);\n }\n else {\n resetCalendar();\n }\n _firstDateInvocationInGroup = false;\n }\n }",
"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}"
] |
Reverses a sequence of elements.
@param array Array containing the sequence
@param first Beginning of the range
@param last One past the end of the range
@exception ArrayIndexOutOfBoundsException If the range
is invalid. | [
"private static void reverse(int first, int last, Swapper swapper) {\r\n\t// no more needed since manually inlined\r\n\twhile (first < --last) {\r\n\t\tswapper.swap(first++,last);\r\n\t}\r\n}"
] | [
"public int readInt(int offset, byte[] data)\n {\n int result = 0;\n int i = offset + m_offset;\n for (int shiftBy = 0; shiftBy < 32; shiftBy += 8)\n {\n result |= ((data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }",
"private static int getTrimmedYStart(BufferedImage img) {\n int width = img.getWidth();\n int height = img.getHeight();\n int yStart = height;\n\n for (int i = 0; i < width; i++) {\n for (int j = 0; j < height; j++) {\n if (img.getRGB(i, j) != Color.WHITE.getRGB() && j < yStart) {\n yStart = j;\n break;\n }\n }\n }\n\n return yStart;\n }",
"private void updateImageInfo() {\n\n String crop = getCrop();\n String point = getPoint();\n m_imageInfoDisplay.fillContent(m_info, crop, point);\n }",
"public LatLong getLocation() {\n if (location == null) {\n location = new LatLong((JSObject) (getJSObject().getMember(\"location\")));\n }\n return location;\n }",
"String calculateDisplayTimestamp(long time){\n long now = System.currentTimeMillis()/1000;\n long diff = now-time;\n if(diff < 60){\n return \"Just Now\";\n }else if(diff > 60 && diff < 59*60){\n return (diff/(60)) + \" mins ago\";\n }else if(diff > 59*60 && diff < 23*59*60 ){\n return diff/(60*60) > 1 ? diff/(60*60) + \" hours ago\" : diff/(60*60) + \" hour ago\";\n }else if(diff > 24*60*60 && diff < 48*60*60){\n return \"Yesterday\";\n }else {\n @SuppressLint(\"SimpleDateFormat\")\n SimpleDateFormat sdf = new SimpleDateFormat(\"dd MMM\");\n return sdf.format(new Date(time));\n }\n }",
"@Override\n public final double getDouble(final String key) {\n Double result = optDouble(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }",
"public synchronized Object removeRoleMapping(final String roleName) {\n /*\n * Would not expect this to happen during boot so don't offer the 'immediate' optimisation.\n */\n HashMap<String, RoleMappingImpl> newRoles = new HashMap<String, RoleMappingImpl>(roleMappings);\n if (newRoles.containsKey(roleName)) {\n RoleMappingImpl removed = newRoles.remove(roleName);\n Object removalKey = new Object();\n removedRoles.put(removalKey, removed);\n roleMappings = Collections.unmodifiableMap(newRoles);\n\n return removalKey;\n }\n\n return null;\n }",
"public static BuildRetention createBuildRetention(Run build, boolean discardOldArtifacts) {\n BuildRetention buildRetention = new BuildRetention(discardOldArtifacts);\n LogRotator rotator = null;\n BuildDiscarder buildDiscarder = build.getParent().getBuildDiscarder();\n if (buildDiscarder != null && buildDiscarder instanceof LogRotator) {\n rotator = (LogRotator) buildDiscarder;\n }\n if (rotator == null) {\n return buildRetention;\n }\n if (rotator.getNumToKeep() > -1) {\n buildRetention.setCount(rotator.getNumToKeep());\n }\n if (rotator.getDaysToKeep() > -1) {\n Calendar calendar = Calendar.getInstance();\n calendar.add(Calendar.DAY_OF_YEAR, -rotator.getDaysToKeep());\n buildRetention.setMinimumBuildDate(new Date(calendar.getTimeInMillis()));\n }\n List<String> notToBeDeleted = ExtractorUtils.getBuildNumbersNotToBeDeleted(build);\n buildRetention.setBuildNumbersNotToBeDiscarded(notToBeDeleted);\n return buildRetention;\n }",
"public final double[] getDpiSuggestions() {\n if (this.dpiSuggestions == null) {\n List<Double> list = new ArrayList<>();\n for (double suggestion: DEFAULT_DPI_VALUES) {\n if (suggestion <= this.maxDpi) {\n list.add(suggestion);\n }\n }\n double[] suggestions = new double[list.size()];\n for (int i = 0; i < suggestions.length; i++) {\n suggestions[i] = list.get(i);\n }\n return suggestions;\n }\n return this.dpiSuggestions;\n }"
] |
Static factory method.
@param targetVariable
the variable to find the effective {@code putfield} or
{@code putstatic} instruction for.
@param controlFlowBlocks
all control flow blocks of an initialising constructor or
method.
@return a new instance of this class. | [
"public static EffectiveAssignmentInsnFinder newInstance(final FieldNode targetVariable,\n final Collection<ControlFlowBlock> controlFlowBlocks) {\n return new EffectiveAssignmentInsnFinder(checkNotNull(targetVariable), checkNotNull(controlFlowBlocks));\n }"
] | [
"private static <T, ID> MappedDeleteCollection<T, ID> build(Dao<T, ID> dao, TableInfo<T, ID> tableInfo, int dataSize)\n\t\t\tthrows SQLException {\n\t\tFieldType idField = tableInfo.getIdField();\n\t\tif (idField == null) {\n\t\t\tthrow new SQLException(\n\t\t\t\t\t\"Cannot delete \" + tableInfo.getDataClass() + \" because it doesn't have an id field defined\");\n\t\t}\n\t\tStringBuilder sb = new StringBuilder(128);\n\t\tDatabaseType databaseType = dao.getConnectionSource().getDatabaseType();\n\t\tappendTableName(databaseType, sb, \"DELETE FROM \", tableInfo.getTableName());\n\t\tFieldType[] argFieldTypes = new FieldType[dataSize];\n\t\tappendWhereIds(databaseType, idField, sb, dataSize, argFieldTypes);\n\t\treturn new MappedDeleteCollection<T, ID>(dao, tableInfo, sb.toString(), argFieldTypes);\n\t}",
"public List<String> findAssociationPath(String targetTypeName, List<String> pathWithoutAlias) {\n\t\tList<String> subPath = new ArrayList<String>( pathWithoutAlias.size() );\n\t\tfor ( String name : pathWithoutAlias ) {\n\t\t\tsubPath.add( name );\n\t\t\tif ( isAssociation( targetTypeName, subPath ) ) {\n\t\t\t\treturn subPath;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"@Inline(value = \"$1.put($2.getKey(), $2.getValue())\", statementExpression = true)\n\tpublic static <K, V> V operator_add(Map<K, V> map, Pair<? extends K, ? extends V> entry) {\n\t\treturn map.put(entry.getKey(), entry.getValue());\n\t}",
"public static streamidentifier_stats get(nitro_service service, String name) throws Exception{\n\t\tstreamidentifier_stats obj = new streamidentifier_stats();\n\t\tobj.set_name(name);\n\t\tstreamidentifier_stats response = (streamidentifier_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"public static appfwhtmlerrorpage get(nitro_service service, options option) throws Exception{\n\t\tappfwhtmlerrorpage obj = new appfwhtmlerrorpage();\n\t\tappfwhtmlerrorpage[] response = (appfwhtmlerrorpage[])obj.get_resources(service,option);\n\t\treturn response[0];\n\t}",
"private static Class<?> getRawClass(Type type) {\n if (type instanceof Class) {\n return (Class<?>) type;\n }\n if (type instanceof ParameterizedType) {\n return getRawClass(((ParameterizedType) type).getRawType());\n }\n // For TypeVariable and WildcardType, returns the first upper bound.\n if (type instanceof TypeVariable) {\n return getRawClass(((TypeVariable) type).getBounds()[0]);\n }\n if (type instanceof WildcardType) {\n return getRawClass(((WildcardType) type).getUpperBounds()[0]);\n }\n if (type instanceof GenericArrayType) {\n Class<?> componentClass = getRawClass(((GenericArrayType) type).getGenericComponentType());\n return Array.newInstance(componentClass, 0).getClass();\n }\n // This shouldn't happen as we captured all implementations of Type above (as or Java 8)\n throw new IllegalArgumentException(\"Unsupported type \" + type + \" of type class \" + type.getClass());\n }",
"private Integer getFrequency(Project.Calendars.Calendar.Exceptions.Exception exception)\n {\n Integer period = NumberHelper.getInteger(exception.getPeriod());\n if (period == null)\n {\n period = Integer.valueOf(1);\n }\n return period;\n }",
"public <S extends AddressSegment> void getSplitSegments(S segs[], int index, AddressSegmentCreator<S> creator) {\r\n\t\tif(!isMultiple()) {\r\n\t\t\tint bitSizeSplit = IPv6Address.BITS_PER_SEGMENT >>> 1;\r\n\t\t\tInteger myPrefix = getSegmentPrefixLength();\r\n\t\t\tInteger highPrefixBits = getSplitSegmentPrefix(bitSizeSplit, myPrefix, 0);\r\n\t\t\tInteger lowPrefixBits = getSplitSegmentPrefix(bitSizeSplit, myPrefix, 1);\r\n\t\t\tif(index >= 0 && index < segs.length) {\r\n\t\t\t\tsegs[index] = creator.createSegment(highByte(), highPrefixBits);\r\n\t\t\t}\r\n\t\t\tif(++index >= 0 && index < segs.length) {\r\n\t\t\t\tsegs[index] = creator.createSegment(lowByte(), lowPrefixBits);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tgetSplitSegmentsMultiple(segs, index, creator);\r\n\t\t}\r\n\t}",
"@SuppressWarnings(\"unchecked\")\n public T[] nextCombinationAsArray()\n {\n T[] combination = (T[]) Array.newInstance(elements.getClass().getComponentType(),\n combinationIndices.length);\n return nextCombinationAsArray(combination);\n }"
] |
Appends the key and value to the address and sets the address on the operation.
@param operation the operation to set the address on
@param base the base address
@param key the key for the new address
@param value the value for the new address | [
"static void addOperationAddress(final ModelNode operation, final PathAddress base, final String key, final String value) {\n operation.get(OP_ADDR).set(base.append(key, value).toModelNode());\n }"
] | [
"public void setDateOnly(boolean dateOnly) {\n\n if (m_dateOnly != dateOnly) {\n m_dateOnly = dateOnly;\n if (m_dateOnly) {\n m_time.removeFromParent();\n m_am.removeFromParent();\n m_pm.removeFromParent();\n } else {\n m_timeField.add(m_time);\n m_timeField.add(m_am);\n m_timeField.add(m_pm);\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 static String renderJson(Object o) {\n\n Gson gson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting()\n .create();\n return gson.toJson(o);\n }",
"private void uncheckAll(CmsList<? extends I_CmsListItem> list) {\r\n\r\n for (Widget it : list) {\r\n CmsTreeItem treeItem = (CmsTreeItem)it;\r\n treeItem.getCheckBox().setChecked(false);\r\n uncheckAll(treeItem.getChildren());\r\n }\r\n }",
"public static vlan get(nitro_service service, Long id) throws Exception{\n\t\tvlan obj = new vlan();\n\t\tobj.set_id(id);\n\t\tvlan response = (vlan) obj.get_resource(service);\n\t\treturn response;\n\t}",
"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 StyleFilter findStyleFilter(Object feature, List<StyleFilter> styles) {\n\t\tfor (StyleFilter styleFilter : styles) {\n\t\t\tif (styleFilter.getFilter().evaluate(feature)) {\n\t\t\t\treturn styleFilter;\n\t\t\t}\n\t\t}\n\t\treturn new StyleFilterImpl();\n\t}",
"@UiThread\n protected void parentExpandedFromViewHolder(int flatParentPosition) {\n ExpandableWrapper<P, C> parentWrapper = mFlatItemList.get(flatParentPosition);\n updateExpandedParent(parentWrapper, flatParentPosition, true);\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}"
] |
Give next index i where i and i+timelag is valid | [
"public Integer next() {\n\t\tfor(int i = currentIndex; i < t.size(); i++){\n\t\t\tif(i+timelag>=t.size()){\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif((t.get(i) != null) && (t.get(i+timelag) != null)){\n\t\t\t\tif(overlap){\n\t\t\t\t\tcurrentIndex = i+1;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tcurrentIndex = i+timelag;\n\t\t\t\t}\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn null;\n\t}"
] | [
"public static String takeWhile(GString self, @ClosureParams(value=SimpleType.class, options=\"char\") Closure condition) {\n return (String) takeWhile(self.toString(), condition);\n }",
"public static String stringify(ObjectMapper mapper, Object object) {\n try {\n return mapper.writeValueAsString(object);\n } catch (JsonProcessingException e) {\n throw new IllegalArgumentException(e);\n }\n }",
"public Rectangle toRelative(Rectangle rect) {\n\t\treturn new Rectangle(rect.getLeft() - origX, rect.getBottom() - origY, rect.getRight() - origX, rect.getTop()\n\t\t\t\t- origY);\n\t}",
"public List<String> subList(final long fromIndex, final long toIndex) {\n return doWithJedis(new JedisCallable<List<String>>() {\n @Override\n public List<String> call(Jedis jedis) {\n return jedis.lrange(getKey(), fromIndex, toIndex);\n }\n });\n }",
"public void addModuleDir(final String moduleDir) {\n if (moduleDir == null) {\n throw LauncherMessages.MESSAGES.nullParam(\"moduleDir\");\n }\n // Validate the path\n final Path path = Paths.get(moduleDir).normalize();\n modulesDirs.add(path.toString());\n }",
"public synchronized void maybeThrottle(int eventsSeen) {\n if (maxRatePerSecond > 0) {\n long now = time.milliseconds();\n try {\n rateSensor.record(eventsSeen, now);\n } catch (QuotaViolationException e) {\n // If we're over quota, we calculate how long to sleep to compensate.\n double currentRate = e.getValue();\n if (currentRate > this.maxRatePerSecond) {\n double excessRate = currentRate - this.maxRatePerSecond;\n long sleepTimeMs = Math.round(excessRate / this.maxRatePerSecond * voldemort.utils.Time.MS_PER_SECOND);\n if(logger.isDebugEnabled()) {\n logger.debug(\"Throttler quota exceeded:\\n\" +\n \"eventsSeen \\t= \" + eventsSeen + \" in this call of maybeThrotte(),\\n\" +\n \"currentRate \\t= \" + currentRate + \" events/sec,\\n\" +\n \"maxRatePerSecond \\t= \" + this.maxRatePerSecond + \" events/sec,\\n\" +\n \"excessRate \\t= \" + excessRate + \" events/sec,\\n\" +\n \"sleeping for \\t\" + sleepTimeMs + \" ms to compensate.\\n\" +\n \"rateConfig.timeWindowMs() = \" + rateConfig.timeWindowMs());\n }\n if (sleepTimeMs > rateConfig.timeWindowMs()) {\n logger.warn(\"Throttler sleep time (\" + sleepTimeMs + \" ms) exceeds \" +\n \"window size (\" + rateConfig.timeWindowMs() + \" ms). This will likely \" +\n \"result in not being able to honor the rate limit accurately.\");\n // When using the HDFS Fetcher, setting the hdfs.fetcher.buffer.size\n // too high could cause this problem.\n }\n time.sleep(sleepTimeMs);\n } else if (logger.isDebugEnabled()) {\n logger.debug(\"Weird. Got QuotaValidationException but measured rate not over rateLimit: \" +\n \"currentRate = \" + currentRate + \" , rateLimit = \" + this.maxRatePerSecond);\n }\n }\n }\n }",
"protected void mergeSameCost(LinkedList<TimephasedCost> list)\n {\n LinkedList<TimephasedCost> result = new LinkedList<TimephasedCost>();\n\n TimephasedCost previousAssignment = null;\n for (TimephasedCost assignment : list)\n {\n if (previousAssignment == null)\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n result.add(assignment);\n }\n else\n {\n Number previousAssignmentCost = previousAssignment.getAmountPerDay();\n Number assignmentCost = assignment.getTotalAmount();\n\n if (NumberHelper.equals(previousAssignmentCost.doubleValue(), assignmentCost.doubleValue(), 0.01))\n {\n Date assignmentStart = previousAssignment.getStart();\n Date assignmentFinish = assignment.getFinish();\n double total = previousAssignment.getTotalAmount().doubleValue();\n total += assignmentCost.doubleValue();\n\n TimephasedCost merged = new TimephasedCost();\n merged.setStart(assignmentStart);\n merged.setFinish(assignmentFinish);\n merged.setAmountPerDay(assignmentCost);\n merged.setTotalAmount(Double.valueOf(total));\n\n result.removeLast();\n assignment = merged;\n }\n else\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n }\n result.add(assignment);\n }\n\n previousAssignment = assignment;\n }\n\n list.clear();\n list.addAll(result);\n }",
"public BeanDefinition toInternal(BeanDefinitionInfo beanDefinitionInfo) {\n\t\tif (beanDefinitionInfo instanceof GenericBeanDefinitionInfo) {\n\t\t\tGenericBeanDefinitionInfo genericInfo = (GenericBeanDefinitionInfo) beanDefinitionInfo;\n\t\t\tGenericBeanDefinition def = new GenericBeanDefinition();\n\t\t\tdef.setBeanClassName(genericInfo.getClassName());\n\t\t\tif (genericInfo.getPropertyValues() != null) {\n\t\t\t\tMutablePropertyValues propertyValues = new MutablePropertyValues();\n\t\t\t\tfor (Entry<String, BeanMetadataElementInfo> entry : genericInfo.getPropertyValues().entrySet()) {\n\t\t\t\t\tBeanMetadataElementInfo info = entry.getValue();\n\t\t\t\t\tpropertyValues.add(entry.getKey(), toInternal(info));\n\t\t\t\t}\n\t\t\t\tdef.setPropertyValues(propertyValues);\n\t\t\t}\n\t\t\treturn def;\n\t\t} else if (beanDefinitionInfo instanceof ObjectBeanDefinitionInfo) {\n\t\t\tObjectBeanDefinitionInfo objectInfo = (ObjectBeanDefinitionInfo) beanDefinitionInfo;\n\t\t\treturn createBeanDefinitionByIntrospection(objectInfo.getObject());\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\"Conversion to internal of \" + beanDefinitionInfo.getClass().getName()\n\t\t\t\t\t+ \" not implemented\");\n\t\t}\n\t}",
"public BoxFolder.Info createFolder(String name) {\n JsonObject parent = new JsonObject();\n parent.add(\"id\", this.getID());\n\n JsonObject newFolder = new JsonObject();\n newFolder.add(\"name\", name);\n newFolder.add(\"parent\", parent);\n\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), CREATE_FOLDER_URL.build(this.getAPI().getBaseURL()),\n \"POST\");\n request.setBody(newFolder.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxFolder createdFolder = new BoxFolder(this.getAPI(), responseJSON.get(\"id\").asString());\n return createdFolder.new Info(responseJSON);\n }"
] |
FIXME Remove this method | [
"@Override\n @Deprecated\n public List<CardWithActions> getBoardMemberActivity(String boardId, String memberId,\n String actionFilter, Argument... args) {\n if (actionFilter == null)\n actionFilter = \"all\";\n Argument[] argsAndFilter = Arrays.copyOf(args, args.length + 1);\n argsAndFilter[args.length] = new Argument(\"actions\", actionFilter);\n\n return asList(() -> get(createUrl(GET_BOARD_MEMBER_CARDS).params(argsAndFilter).asString(),\n CardWithActions[].class, boardId, memberId));\n }"
] | [
"public String getCsv() {\n\n StringWriter writer = new StringWriter();\n try (CSVWriter csv = new CSVWriter(writer)) {\n List<String> headers = new ArrayList<>();\n for (String col : m_columns) {\n headers.add(col);\n }\n csv.writeNext(headers.toArray(new String[] {}));\n for (List<Object> row : m_data) {\n List<String> colCsv = new ArrayList<>();\n for (Object col : row) {\n colCsv.add(String.valueOf(col));\n }\n csv.writeNext(colCsv.toArray(new String[] {}));\n }\n return writer.toString();\n } catch (IOException e) {\n return null;\n }\n }",
"public static Object newInstance(String className) throws InstantiationException,\r\n IllegalAccessException,\r\n ClassNotFoundException\r\n {\r\n return newInstance(getClass(className));\r\n }",
"public StateVertex crawlIndex() {\n\t\tLOG.debug(\"Setting up vertex of the index page\");\n\n\t\tif (basicAuthUrl != null) {\n\t\t\tbrowser.goToUrl(basicAuthUrl);\n\t\t}\n\n\t\tbrowser.goToUrl(url);\n\n\t\t// Run url first load plugin to clear the application state\n\t\tplugins.runOnUrlFirstLoadPlugins(context);\n\n\t\tplugins.runOnUrlLoadPlugins(context);\n\t\tStateVertex index = vertexFactory.createIndex(url.toString(), browser.getStrippedDom(),\n\t\t\t\tstateComparator.getStrippedDom(browser), browser);\n\t\tPreconditions.checkArgument(index.getId() == StateVertex.INDEX_ID,\n\t\t\t\t\"It seems some the index state is crawled more than once.\");\n\n\t\tLOG.debug(\"Parsing the index for candidate elements\");\n\t\tImmutableList<CandidateElement> extract = candidateExtractor.extract(index);\n\n\t\tplugins.runPreStateCrawlingPlugins(context, extract, index);\n\n\t\tcandidateActionCache.addActions(extract, index);\n\n\t\treturn index;\n\n\t}",
"public void registerDatatype(Class<? extends GVRHybridObject> textureClass,\n AsyncLoaderFactory<? extends GVRHybridObject, ?> asyncLoaderFactory) {\n mFactories.put(textureClass, asyncLoaderFactory);\n }",
"@Override\n public AccountingDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }",
"protected static void safeWriteErrorResponse(final Channel channel, final ManagementProtocolHeader header, final Throwable error) {\n if(header.getType() == ManagementProtocol.TYPE_REQUEST) {\n try {\n writeErrorResponse(channel, (ManagementRequestHeader) header, error);\n } catch(IOException ioe) {\n ProtocolLogger.ROOT_LOGGER.tracef(ioe, \"failed to write error response for %s on channel: %s\", header, channel);\n }\n }\n }",
"private void saveToBundleDescriptor() throws CmsException {\n\n if (null != m_descFile) {\n m_removeDescriptorOnCancel = false;\n updateBundleDescriptorContent();\n m_descFile.getFile().setContents(m_descContent.marshal());\n m_cms.writeFile(m_descFile.getFile());\n }\n }",
"public int addServerRedirect(String region, String srcUrl, String destUrl, String hostHeader, int profileId, int groupId) throws Exception {\n int serverId = -1;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\"INSERT INTO \" + Constants.DB_TABLE_SERVERS\n + \"(\" + Constants.SERVER_REDIRECT_REGION + \",\" +\n Constants.SERVER_REDIRECT_SRC_URL + \",\" +\n Constants.SERVER_REDIRECT_DEST_URL + \",\" +\n Constants.SERVER_REDIRECT_HOST_HEADER + \",\" +\n Constants.SERVER_REDIRECT_PROFILE_ID + \",\" +\n Constants.SERVER_REDIRECT_GROUP_ID + \")\"\n + \" VALUES (?, ?, ?, ?, ?, ?);\", PreparedStatement.RETURN_GENERATED_KEYS);\n statement.setString(1, region);\n statement.setString(2, srcUrl);\n statement.setString(3, destUrl);\n statement.setString(4, hostHeader);\n statement.setInt(5, profileId);\n statement.setInt(6, groupId);\n statement.executeUpdate();\n\n results = statement.getGeneratedKeys();\n\n if (results.next()) {\n serverId = results.getInt(1);\n } else {\n // something went wrong\n throw new Exception(\"Could not add path\");\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return serverId;\n }",
"public PhotoList<Photo> getContactsPhotos(int count, boolean justFriends, boolean singlePhoto, boolean includeSelf) 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_CONTACTS_PHOTOS);\r\n\r\n if (count > 0) {\r\n parameters.put(\"count\", Integer.toString(count));\r\n }\r\n if (justFriends) {\r\n parameters.put(\"just_friends\", \"1\");\r\n }\r\n if (singlePhoto) {\r\n parameters.put(\"single_photo\", \"1\");\r\n }\r\n if (includeSelf) {\r\n parameters.put(\"include_self\", \"1\");\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\r\n photos.setPage(\"1\");\r\n photos.setPages(\"1\");\r\n photos.setPerPage(\"\" + photoNodes.getLength());\r\n photos.setTotal(\"\" + photoNodes.getLength());\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 }"
] |
This method is used by JNI, do not call or modify.
@param type the type
@param number the number | [
"@SuppressWarnings(\"unused\")\n private void setTextureNumber(int type, int number) {\n m_numTextures.put(AiTextureType.fromRawValue(type), number);\n }"
] | [
"public CSTNode set( int index, CSTNode element ) \n {\n \n if( elements == null ) \n {\n throw new GroovyBugError( \"attempt to set() on a EMPTY Reduction\" );\n }\n\n if( index == 0 && !(element instanceof Token) ) \n {\n\n //\n // It's not the greatest of design that the interface allows this, but it\n // is a tradeoff with convenience, and the convenience is more important.\n\n throw new GroovyBugError( \"attempt to set() a non-Token as root of a Reduction\" );\n }\n\n\n //\n // Fill slots with nulls, if necessary.\n\n int count = elements.size();\n if( index >= count ) \n {\n for( int i = count; i <= index; i++ ) \n {\n elements.add( null );\n }\n }\n\n //\n // Then set in the element.\n\n elements.set( index, element );\n\n return element;\n }",
"@SuppressWarnings(\"unchecked\")\n protected static void visitSubreports(DynamicReport dr, Map _parameters) {\n for (DJGroup group : dr.getColumnsGroups()) {\n //Header Subreports\n for (Subreport subreport : group.getHeaderSubreports()) {\n if (subreport.getDynamicReport() != null) {\n visitSubreport(dr, subreport);\n visitSubreports(subreport.getDynamicReport(), _parameters);\n }\n }\n\n //Footer Subreports\n for (Subreport subreport : group.getFooterSubreports()) {\n if (subreport.getDynamicReport() != null) {\n visitSubreport(dr, subreport);\n visitSubreports(subreport.getDynamicReport(), _parameters);\n }\n }\n }\n\n }",
"public void add(String photoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ADD);\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"public static <K,V> Map<K,V> minus(Map<K,V> self, Map removeMe) {\n final Map<K,V> ansMap = createSimilarMap(self);\n ansMap.putAll(self);\n if (removeMe != null && removeMe.size() > 0) {\n for (Map.Entry<K, V> e1 : self.entrySet()) {\n for (Object e2 : removeMe.entrySet()) {\n if (DefaultTypeTransformation.compareEqual(e1, e2)) {\n ansMap.remove(e1.getKey());\n }\n }\n }\n }\n return ansMap;\n }",
"public void updateInfo(BoxWebLink.Info info) {\n URL url = WEB_LINK_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"PUT\");\n request.setBody(info.getPendingChanges());\n String body = info.getPendingChanges();\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n info.update(jsonObject);\n }",
"public void startAnimation()\n {\n Date time = new Date();\n this.beginAnimation = time.getTime();\n this.endAnimation = beginAnimation + (long) (animationTime * 1000);\n this.animate = true;\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 }",
"public void recordCheckoutTimeUs(SocketDestination dest, long checkoutTimeUs) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordCheckoutTimeUs(null, checkoutTimeUs);\n recordCheckoutTimeUs(null, checkoutTimeUs);\n } else {\n this.checkoutTimeRequestCounter.addRequest(checkoutTimeUs * Time.NS_PER_US);\n }\n }",
"protected void runImportScript(CmsObject cms, CmsModule module) {\n\n LOG.info(\"Executing import script for module \" + module.getName());\n m_report.println(\n org.opencms.module.Messages.get().container(org.opencms.module.Messages.RPT_IMPORT_SCRIPT_HEADER_0),\n I_CmsReport.FORMAT_HEADLINE);\n String importScript = \"echo on\\n\" + module.getImportScript();\n ByteArrayOutputStream buffer = new ByteArrayOutputStream();\n PrintStream out = new PrintStream(buffer);\n CmsShell shell = new CmsShell(cms, \"${user}@${project}:${siteroot}|${uri}>\", null, out, out);\n shell.execute(importScript);\n String outputString = buffer.toString();\n LOG.info(\"Shell output for import script was: \\n\" + outputString);\n m_report.println(\n org.opencms.module.Messages.get().container(\n org.opencms.module.Messages.RPT_IMPORT_SCRIPT_OUTPUT_1,\n outputString));\n }"
] |
Process this deployment for annotations. This will use an annotation indexer to create an index of all annotations
found in this deployment and attach it to the deployment unit context.
@param phaseContext the deployment unit context
@throws DeploymentUnitProcessingException | [
"public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {\n final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();\n for (ResourceRoot resourceRoot : DeploymentUtils.allResourceRoots(deploymentUnit)) {\n ResourceRootIndexer.indexResourceRoot(resourceRoot);\n }\n }"
] | [
"public static vpntrafficpolicy_vpnglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpntrafficpolicy_vpnglobal_binding obj = new vpntrafficpolicy_vpnglobal_binding();\n\t\tobj.set_name(name);\n\t\tvpntrafficpolicy_vpnglobal_binding response[] = (vpntrafficpolicy_vpnglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private int getBeliefCount() {\n Integer count = (Integer)introspector.getBeliefBase(ListenerMockAgent.this).get(Definitions.RECEIVED_MESSAGE_COUNT);\n if (count == null) count = 0; // Just in case, not really sure if this is necessary.\n return count;\n }",
"private void checkExactlyTheWeeksCheckBoxes(Collection<WeekOfMonth> weeksToCheck) {\r\n\r\n for (CmsCheckBox cb : m_checkboxes) {\r\n cb.setChecked(weeksToCheck.contains(WeekOfMonth.valueOf(cb.getInternalValue())));\r\n }\r\n }",
"public static void rebuild(final MODE newMode) {\n if (mode != newMode) {\n mode = newMode;\n TYPE type;\n switch (mode) {\n case DEBUG:\n type = TYPE.ANDROID;\n Log.startFullLog();\n break;\n case DEVELOPER:\n type = TYPE.PERSISTENT;\n Log.stopFullLog();\n break;\n case USER:\n type = TYPE.ANDROID;\n break;\n default:\n type = DEFAULT_TYPE;\n Log.stopFullLog();\n break;\n }\n currentLog = getLog(type);\n }\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 static dospolicy get(nitro_service service, String name) throws Exception{\n\t\tdospolicy obj = new dospolicy();\n\t\tobj.set_name(name);\n\t\tdospolicy response = (dospolicy) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public ConfigOptionBuilder setDefaultWith( Object defaultValue ) {\n co.setHasDefault( true );\n co.setValue( defaultValue );\n return setOptional();\n }",
"public boolean checkWrite(TransactionImpl tx, Object obj)\r\n {\r\n LockEntry writer = getWriter(obj);\r\n if (writer == null)\r\n return false;\r\n else if (writer.isOwnedBy(tx))\r\n return true;\r\n else\r\n return false;\r\n }",
"private ColumnDef addColumnFor(FieldDescriptorDef fieldDef, TableDef tableDef)\r\n {\r\n String name = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN);\r\n ColumnDef columnDef = tableDef.getColumn(name);\r\n\r\n if (columnDef == null)\r\n {\r\n columnDef = new ColumnDef(name);\r\n tableDef.addColumn(columnDef);\r\n }\r\n if (!fieldDef.isNested())\r\n { \r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_JAVANAME, fieldDef.getName());\r\n }\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_TYPE, fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_ID, fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_ID));\r\n if (fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_PRIMARYKEY, false))\r\n {\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_PRIMARYKEY, \"true\");\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_REQUIRED, \"true\");\r\n }\r\n else if (!fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_NULLABLE, true))\r\n {\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_REQUIRED, \"true\");\r\n }\r\n if (\"database\".equals(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_AUTOINCREMENT)))\r\n {\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_AUTOINCREMENT, \"true\");\r\n }\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_SIZE, fieldDef.getSizeConstraint());\r\n if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_DOCUMENTATION))\r\n {\r\n columnDef.setProperty(PropertyHelper.OJB_PROPERTY_DOCUMENTATION,\r\n fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_DOCUMENTATION));\r\n }\r\n if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_COLUMN_DOCUMENTATION))\r\n {\r\n columnDef.setProperty(PropertyHelper.OJB_PROPERTY_COLUMN_DOCUMENTATION,\r\n fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN_DOCUMENTATION));\r\n }\r\n return columnDef;\r\n }"
] |
Create the patching task based on the definition.
@param definition the task description
@param provider the content provider
@param context the task context
@return the created task | [
"static PatchingTask createTask(final PatchingTasks.ContentTaskDefinition definition, final PatchContentProvider provider, final IdentityPatchContext.PatchEntry context) {\n final PatchContentLoader contentLoader = provider.getLoader(definition.getTarget().getPatchId());\n final PatchingTaskDescription description = PatchingTaskDescription.create(definition, contentLoader);\n return PatchingTask.Factory.create(description, context);\n }"
] | [
"protected static <T, A> ManagementRequestHandler<T, A> getFallbackHandler(final ManagementRequestHeader header) {\n return new ManagementRequestHandler<T, A>() {\n @Override\n public void handleRequest(final DataInput input, ActiveOperation.ResultHandler<T> resultHandler, ManagementRequestContext<A> context) throws IOException {\n final Exception error = ProtocolLogger.ROOT_LOGGER.noSuchResponseHandler(Integer.toHexString(header.getRequestId()));\n if(resultHandler.failed(error)) {\n safeWriteErrorResponse(context.getChannel(), context.getRequestHeader(), error);\n }\n }\n };\n }",
"public void removeMetadataProvider(MetadataProvider provider) {\n for (Set<MetadataProvider> providers : metadataProviders.values()) {\n providers.remove(provider);\n }\n }",
"private long getTotalUploadSize() throws IOException {\n long size = 0;\n for (Map.Entry<String, File> entry : files.entrySet()) {\n size += entry.getValue().length();\n }\n\n for (Map.Entry<String, InputStream> entry : fileStreams.entrySet()) {\n size += entry.getValue().available();\n }\n return size;\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 void checkGAs(List l)\r\n\t{\r\n\t\tfor (final Iterator i = l.iterator(); i.hasNext();)\r\n\t\t\tif (!(i.next() instanceof GroupAddress))\r\n\t\t\t\tthrow new KNXIllegalArgumentException(\"not a group address list\");\r\n\t}",
"public void histogramToStructure(int histogram[] ) {\n col_idx[0] = 0;\n int index = 0;\n for (int i = 1; i <= numCols; i++) {\n col_idx[i] = index += histogram[i-1];\n }\n nz_length = index;\n growMaxLength( nz_length , false);\n if( col_idx[numCols] != nz_length )\n throw new RuntimeException(\"Egads\");\n }",
"public static void unsetCurrentPersistenceBroker(PBKey key, PersistenceBrokerInternal broker)\r\n throws PBFactoryException\r\n {\r\n HashMap map = (HashMap) currentBrokerMap.get();\r\n WeakHashMap set = null;\r\n if(map != null)\r\n {\r\n set = (WeakHashMap) map.get(key);\r\n if(set != null)\r\n {\r\n set.remove(broker);\r\n if(set.isEmpty())\r\n {\r\n map.remove(key);\r\n }\r\n }\r\n if(map.isEmpty())\r\n {\r\n currentBrokerMap.set(null);\r\n synchronized(lock) {\r\n loadedHMs.remove(map);\r\n }\r\n }\r\n }\r\n }",
"private void readColumn(int startIndex, int length) throws Exception\n {\n if (m_currentTable != null)\n {\n int value = FastTrackUtility.getByte(m_buffer, startIndex);\n Class<?> klass = COLUMN_MAP[value];\n if (klass == null)\n {\n klass = UnknownColumn.class;\n }\n\n FastTrackColumn column = (FastTrackColumn) klass.newInstance();\n m_currentColumn = column;\n\n logColumnData(startIndex, length);\n\n column.read(m_currentTable.getType(), m_buffer, startIndex, length);\n FastTrackField type = column.getType();\n\n //\n // Don't try to add this data if:\n // 1. We don't know what type it is\n // 2. We have seen the type already\n //\n if (type != null && !m_currentFields.contains(type))\n {\n m_currentFields.add(type);\n m_currentTable.addColumn(column);\n updateDurationTimeUnit(column);\n updateWorkTimeUnit(column);\n\n logColumn(column);\n }\n }\n }",
"public static Info eye( final Variable A , ManagerTempVariables manager) {\n Info ret = new Info();\n final VariableMatrix output = manager.createMatrix();\n ret.output = output;\n\n if( A instanceof VariableMatrix ) {\n ret.op = new Operation(\"eye-m\") {\n @Override\n public void process() {\n DMatrixRMaj mA = ((VariableMatrix)A).matrix;\n output.matrix.reshape(mA.numRows,mA.numCols);\n CommonOps_DDRM.setIdentity(output.matrix);\n }\n };\n } else if( A instanceof VariableInteger ) {\n ret.op = new Operation(\"eye-i\") {\n @Override\n public void process() {\n int N = ((VariableInteger)A).value;\n output.matrix.reshape(N,N);\n CommonOps_DDRM.setIdentity(output.matrix);\n }\n };\n } else {\n throw new RuntimeException(\"Unsupported variable type \"+A);\n }\n\n return ret;\n }"
] |
write CustomInfo list into table.
@param event the event | [
"private void writeCustomInfo(Event event) {\n // insert customInfo (key/value) into DB\n for (Map.Entry<String, String> customInfo : event.getCustomInfo().entrySet()) {\n long cust_id = dbDialect.getIncrementer().nextLongValue();\n getJdbcTemplate()\n .update(\"insert into EVENTS_CUSTOMINFO (ID, EVENT_ID, CUST_KEY, CUST_VALUE)\"\n + \" values (?,?,?,?)\",\n cust_id, event.getPersistedId(), customInfo.getKey(), customInfo.getValue());\n }\n }"
] | [
"@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public Searcher addBooleanFilter(String attribute, Boolean value) {\n booleanFilterMap.put(attribute, value);\n rebuildQueryFacetFilters();\n return this;\n }",
"protected static final Long parseUsingFallbacksWithColon(String text, DateTimeFormat timeFormat) {\n if (text.indexOf(':') == -1) {\n text = text.replace(\" \", \"\");\n int numdigits = 0;\n int lastdigit = 0;\n for (int i = 0; i < text.length(); i++) {\n char c = text.charAt(i);\n if (Character.isDigit(c)) {\n numdigits++;\n lastdigit = i;\n }\n }\n if (numdigits == 1 || numdigits == 2) {\n // insert :00\n int colon = lastdigit + 1;\n text = text.substring(0, colon) + \":00\" + text.substring(colon);\n }\n else if (numdigits > 2) {\n // insert :\n int colon = lastdigit - 1;\n text = text.substring(0, colon) + \":\" + text.substring(colon);\n }\n return parseUsingFallbacks(text, timeFormat);\n }\n else {\n return null;\n }\n }",
"public static void moveBandsElemnts(int yOffset, JRDesignBand band) {\n\t\tif (band == null)\n\t\t\treturn;\n\n\t\tfor (JRChild jrChild : band.getChildren()) {\n\t\t\tJRDesignElement elem = (JRDesignElement) jrChild;\n\t\t\telem.setY(elem.getY() + yOffset);\n\t\t}\n\t}",
"public static String eachMatch(String self, String regex, @ClosureParams(value=FromString.class, options={\"List<String>\",\"String[]\"}) Closure closure) {\n return eachMatch(self, Pattern.compile(regex), closure);\n }",
"public static PropertyResourceBundle getBundle(String baseName, Locale locale) throws UnsupportedEncodingException, IOException{\n\t\tInputStream is = UTF8PropertyResourceBundle.class.getResourceAsStream(\"/\"+baseName + \"_\"+locale.toString()+PROPERTIES_EXT);\n\t\tif(is != null){\n\t\t\treturn new PropertyResourceBundle(new InputStreamReader(is, \"UTF-8\"));\n\t\t}\n\t\treturn null;\n\t}",
"@Override\n public <T extends ViewGroup.MarginLayoutParams> T setSelectionMargin(int marginPx, T layoutParams) {\n return mSelectionGravityState.setSelectionMargin(marginPx, layoutParams);\n }",
"public ReferenceBuilder withPropertyValue(PropertyIdValue propertyIdValue,\n\t\t\tValue value) {\n\t\tgetSnakList(propertyIdValue).add(\n\t\t\t\tfactory.getValueSnak(propertyIdValue, value));\n\t\treturn getThis();\n\t}",
"private String getPathSelectString() {\n String queryString = \"SELECT \" + Constants.DB_TABLE_REQUEST_RESPONSE + \".\" + Constants.GENERIC_CLIENT_UUID +\n \",\" + Constants.DB_TABLE_PATH + \".\" + Constants.GENERIC_ID +\n \",\" + Constants.PATH_PROFILE_PATHNAME +\n \",\" + Constants.PATH_PROFILE_ACTUAL_PATH +\n \",\" + Constants.PATH_PROFILE_BODY_FILTER +\n \",\" + Constants.PATH_PROFILE_GROUP_IDS +\n \",\" + Constants.DB_TABLE_PATH + \".\" + Constants.PATH_PROFILE_PROFILE_ID +\n \",\" + Constants.PATH_PROFILE_PATH_ORDER +\n \",\" + Constants.REQUEST_RESPONSE_REPEAT_NUMBER +\n \",\" + Constants.REQUEST_RESPONSE_REQUEST_ENABLED +\n \",\" + Constants.REQUEST_RESPONSE_RESPONSE_ENABLED +\n \",\" + Constants.PATH_PROFILE_CONTENT_TYPE +\n \",\" + Constants.PATH_PROFILE_REQUEST_TYPE +\n \",\" + Constants.PATH_PROFILE_GLOBAL +\n \" FROM \" + Constants.DB_TABLE_PATH +\n \" JOIN \" + Constants.DB_TABLE_REQUEST_RESPONSE +\n \" ON \" + Constants.DB_TABLE_PATH + \".\" + Constants.GENERIC_ID +\n \"=\" + Constants.DB_TABLE_REQUEST_RESPONSE + \".\" + Constants.REQUEST_RESPONSE_PATH_ID +\n \" AND \" + Constants.DB_TABLE_REQUEST_RESPONSE + \".\" + Constants.GENERIC_CLIENT_UUID + \" = ?\";\n\n return queryString;\n }",
"public final void notifyHeaderItemChanged(int position) {\n if (position < 0 || position >= headerItemCount) {\n throw new IndexOutOfBoundsException(\"The given position \" + position + \" is not within the position bounds for header items [0 - \" + (headerItemCount - 1) + \"].\");\n }\n notifyItemChanged(position);\n }"
] |
Configure if you want this collapsible container to
accordion its child elements or use expandable. | [
"public void setAccordion(boolean accordion) {\n getElement().setAttribute(\"data-collapsible\", accordion ? CssName.ACCORDION : CssName.EXPANDABLE);\n reload();\n }"
] | [
"public void onDrawFrame(float frameTime) {\n final GVRSceneObject owner = getOwnerObject();\n if (owner == null) {\n return;\n }\n\n final int size = mRanges.size();\n final GVRTransform t = getGVRContext().getMainScene().getMainCameraRig().getCenterCamera().getTransform();\n\n for (final Object[] range : mRanges) {\n ((GVRSceneObject)range[1]).setEnable(false);\n }\n\n for (int i = size - 1; i >= 0; --i) {\n final Object[] range = mRanges.get(i);\n final GVRSceneObject child = (GVRSceneObject) range[1];\n if (child.getParent() != owner) {\n Log.w(TAG, \"the scene object for distance greater than \" + range[0] + \" is not a child of the owner; skipping it\");\n continue;\n }\n\n final float[] values = child.getBoundingVolumeRawValues();\n mCenter.set(values[0], values[1], values[2], 1.0f);\n mVector.set(t.getPositionX(), t.getPositionY(), t.getPositionZ(), 1.0f);\n\n mVector.sub(mCenter);\n mVector.negate();\n\n float distance = mVector.dot(mVector);\n\n if (distance >= (Float) range[0]) {\n child.setEnable(true);\n break;\n }\n }\n }",
"private static void bodyWithConcatenation(\n SourceBuilder code,\n Map<Property, PropertyCodeGenerator> generatorsByProperty,\n String typename) {\n code.add(\" return \\\"%s{\", typename);\n String prefix = \"\";\n for (Property property : generatorsByProperty.keySet()) {\n PropertyCodeGenerator generator = generatorsByProperty.get(property);\n code.add(\"%s%s=\\\" + %s + \\\"\",\n prefix, property.getName(), (Excerpt) generator::addToStringValue);\n prefix = \", \";\n }\n code.add(\"}\\\";%n\");\n }",
"public static void sendEvent(Context context, Parcelable event) {\n Intent intent = new Intent(EventManager.ACTION_ACCESSORY_EVENT);\n intent.putExtra(EventManager.EXTRA_EVENT, event);\n context.sendBroadcast(intent);\n }",
"private JSONObject getConvertedResponseAsJson(SpellCheckResponse response) {\n\n if (null == response) {\n return null;\n }\n\n final JSONObject suggestions = new JSONObject();\n final Map<String, Suggestion> solrSuggestions = response.getSuggestionMap();\n\n // Add suggestions to the response\n for (final String key : solrSuggestions.keySet()) {\n\n // Indicator to ignore words that are erroneously marked as misspelled.\n boolean ignoreWord = false;\n\n // Suggestions that are in the form \"Xxxx\" -> \"xxxx\" should be ignored.\n if (Character.isUpperCase(key.codePointAt(0))) {\n final String lowercaseKey = key.toLowerCase();\n // If the suggestion map doesn't contain the lowercased word, ignore this entry.\n if (!solrSuggestions.containsKey(lowercaseKey)) {\n ignoreWord = true;\n }\n }\n\n if (!ignoreWord) {\n try {\n // Get suggestions as List\n final List<String> l = solrSuggestions.get(key).getAlternatives();\n suggestions.put(key, l);\n } catch (JSONException e) {\n LOG.debug(\"Exception while converting Solr spellcheckresponse to JSON. \", e);\n }\n }\n }\n\n return suggestions;\n }",
"public static base_response change(nitro_service client, appfwsignatures resource) throws Exception {\n\t\tappfwsignatures updateresource = new appfwsignatures();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.mergedefault = resource.mergedefault;\n\t\treturn updateresource.perform_operation(client,\"update\");\n\t}",
"synchronized void stop(Integer timeout) {\n final InternalState required = this.requiredState;\n if(required != InternalState.STOPPED) {\n this.requiredState = InternalState.STOPPED;\n ROOT_LOGGER.stoppingServer(serverName);\n // Only send the stop operation if the server is started\n if (internalState == InternalState.SERVER_STARTED) {\n internalSetState(new ServerStopTask(timeout), internalState, InternalState.PROCESS_STOPPING);\n } else {\n transition(false);\n }\n }\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 Map<String, Table> getIndex(Table table)\n {\n Map<String, Table> result;\n\n if (!table.getResourceFlag())\n {\n result = m_taskTablesByName;\n }\n else\n {\n result = m_resourceTablesByName;\n }\n return result;\n }",
"public void deleteRedirect(int id) {\n try {\n sqlService.executeUpdate(\"DELETE FROM \" + Constants.DB_TABLE_SERVERS +\n \" WHERE \" + Constants.GENERIC_ID + \" = \" + id + \";\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n }"
] |
Set the parent from which this week is derived.
@param parent parent week | [
"void setParent(ProjectCalendarWeek parent)\n {\n m_parent = parent;\n\n for (int loop = 0; loop < m_days.length; loop++)\n {\n if (m_days[loop] == null)\n {\n m_days[loop] = DayType.DEFAULT;\n }\n }\n }"
] | [
"@SuppressForbidden(\"legitimate sysstreams.\")\n private static void redirectStreams(final Serializer serializer, final boolean flushFrequently) {\n final PrintStream origSysOut = System.out;\n final PrintStream origSysErr = System.err;\n\n // Set warnings stream to System.err.\n warnings = System.err;\n AccessController.doPrivileged(new PrivilegedAction<Void>() {\n @SuppressForbidden(\"legitimate PrintStream with default charset.\")\n @Override\n public Void run() {\n System.setOut(new PrintStream(new BufferedOutputStream(new ChunkedStream() {\n @Override\n public void write(byte[] b, int off, int len) throws IOException {\n if (multiplexStdStreams) {\n origSysOut.write(b, off, len);\n }\n serializer.serialize(new AppendStdOutEvent(b, off, len));\n if (flushFrequently) serializer.flush();\n }\n })));\n\n System.setErr(new PrintStream(new BufferedOutputStream(new ChunkedStream() {\n @Override\n public void write(byte[] b, int off, int len) throws IOException {\n if (multiplexStdStreams) {\n origSysErr.write(b, off, len);\n }\n serializer.serialize(new AppendStdErrEvent(b, off, len));\n if (flushFrequently) serializer.flush();\n }\n })));\n return null;\n }\n });\n }",
"private void showSettingsMenu(final Cursor cursor) {\n Log.d(TAG, \"showSettingsMenu\");\n enableSettingsCursor(cursor);\n context.runOnGlThread(new Runnable() {\n @Override\n public void run() {\n new SettingsView(context, scene, CursorManager.this,\n settingsCursor.getIoDevice().getCursorControllerId(), cursor, new\n SettingsChangeListener() {\n @Override\n public void onBack(boolean cascading) {\n disableSettingsCursor();\n }\n\n @Override\n public int onDeviceChanged(IoDevice device) {\n // we are changing the io device on the settings cursor\n removeCursorFromScene(settingsCursor);\n IoDevice clickedDevice = getAvailableIoDevice(device);\n settingsCursor.setIoDevice(clickedDevice);\n addCursorToScene(settingsCursor);\n return device.getCursorControllerId();\n }\n });\n }\n });\n }",
"public void originalClass(String template, Properties attributes) throws XDocletException\r\n {\r\n pushCurrentClass(_curClassDef.getOriginalClass());\r\n generate(template);\r\n popCurrentClass();\r\n }",
"public static String join(final Collection<?> collection, final String separator) {\n StringBuffer buffer = new StringBuffer();\n boolean first = true;\n Iterator<?> iter = collection.iterator();\n while (iter.hasNext()) {\n Object next = iter.next();\n if (first) {\n first = false;\n } else {\n buffer.append(separator);\n }\n buffer.append(next);\n }\n return buffer.toString();\n }",
"public static int byteSizeOf(Bitmap bitmap) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {\n return bitmap.getAllocationByteCount();\n } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {\n return bitmap.getByteCount();\n } else {\n return bitmap.getRowBytes() * bitmap.getHeight();\n }\n }",
"public static OptionalString ofNullable(ResourceKey key, String value) {\n return new GenericOptionalString(RUNTIME_SOURCE, key, value);\n }",
"public MwDumpFile findMostRecentDump(DumpContentType dumpContentType) {\n\t\tList<MwDumpFile> dumps = findAllDumps(dumpContentType);\n\n\t\tfor (MwDumpFile dump : dumps) {\n\t\t\tif (dump.isAvailable()) {\n\t\t\t\treturn dump;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"public static <T extends Range> T findRange(List<T> ranges, long value, int arraySize) {\n if (ranges.size() < 1) return null;\n T first = ranges.get(0);\n T last = ranges.get(arraySize - 1);\n // check out of bounds\n if (value < first.start() || value > last.start() + last.size()) {\n throw new OffsetOutOfRangeException(format(\"offset %s is out of range (%s, %s)\",//\n value,first.start(),last.start()+last.size()));\n }\n\n // check at the end\n if (value == last.start() + last.size()) return null;\n\n int low = 0;\n int high = arraySize - 1;\n while (low <= high) {\n int mid = (high + low) / 2;\n T found = ranges.get(mid);\n if (found.contains(value)) {\n return found;\n } else if (value < found.start()) {\n high = mid - 1;\n } else {\n low = mid + 1;\n }\n }\n return null;\n }",
"public static void cacheParseFailure(XmlFileModel key)\n {\n map.put(getKey(key), new CacheDocument(true, null));\n }"
] |
Set the minimum date limit. | [
"public void setDateMin(Date dateMin) {\n this.dateMin = dateMin;\n\n if (isAttached() && dateMin != null) {\n getPicker().set(\"min\", JsDate.create((double) dateMin.getTime()));\n }\n }"
] | [
"public void setDerivatives(double[] parameters, double[][] derivatives) throws SolverException {\n\t\t// Calculate new derivatives. Note that this method is called only with\n\t\t// parameters = parameterCurrent, so we may use valueCurrent.\n\n\t\tVector<Future<double[]>> valueFutures = new Vector<Future<double[]>>(parameterCurrent.length);\n\t\tfor (int parameterIndex = 0; parameterIndex < parameterCurrent.length; parameterIndex++) {\n\t\t\tfinal double[] parametersNew\t= parameters.clone();\n\t\t\tfinal double[] derivative\t\t= derivatives[parameterIndex];\n\n\t\t\tfinal int workerParameterIndex = parameterIndex;\n\t\t\tCallable<double[]> worker = new Callable<double[]>() {\n\t\t\t\tpublic double[] call() {\n\t\t\t\t\tdouble parameterFiniteDifference;\n\t\t\t\t\tif(parameterSteps != null) {\n\t\t\t\t\t\tparameterFiniteDifference = parameterSteps[workerParameterIndex];\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * Try to adaptively set a parameter shift. Note that in some\n\t\t\t\t\t\t * applications it may be important to set parameterSteps.\n\t\t\t\t\t\t * appropriately.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tparameterFiniteDifference = (Math.abs(parametersNew[workerParameterIndex]) + 1) * 1E-8;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Shift parameter value\n\t\t\t\t\tparametersNew[workerParameterIndex] += parameterFiniteDifference;\n\n\t\t\t\t\t// Calculate derivative as (valueUpShift - valueCurrent) / parameterFiniteDifference\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsetValues(parametersNew, derivative);\n\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t// We signal an exception to calculate the derivative as NaN\n\t\t\t\t\t\tArrays.fill(derivative, Double.NaN);\n\t\t\t\t\t}\n\t\t\t\t\tfor (int valueIndex = 0; valueIndex < valueCurrent.length; valueIndex++) {\n\t\t\t\t\t\tderivative[valueIndex] -= valueCurrent[valueIndex];\n\t\t\t\t\t\tderivative[valueIndex] /= parameterFiniteDifference;\n\t\t\t\t\t\tif(Double.isNaN(derivative[valueIndex])) {\n\t\t\t\t\t\t\tderivative[valueIndex] = 0.0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn derivative;\n\t\t\t\t}\n\t\t\t};\n\t\t\tif(executor != null) {\n\t\t\t\tFuture<double[]> valueFuture = executor.submit(worker);\n\t\t\t\tvalueFutures.add(parameterIndex, valueFuture);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tFutureTask<double[]> valueFutureTask = new FutureTask<double[]>(worker);\n\t\t\t\tvalueFutureTask.run();\n\t\t\t\tvalueFutures.add(parameterIndex, valueFutureTask);\n\t\t\t}\n\t\t}\n\n\t\tfor (int parameterIndex = 0; parameterIndex < parameterCurrent.length; parameterIndex++) {\n\t\t\ttry {\n\t\t\t\tderivatives[parameterIndex] = valueFutures.get(parameterIndex).get();\n\t\t\t}\n\t\t\tcatch (InterruptedException e) {\n\t\t\t\tthrow new SolverException(e);\n\t\t\t} catch (ExecutionException e) {\n\t\t\t\tthrow new SolverException(e);\n\t\t\t}\n\t\t}\n\t}",
"private void reInitLayoutElements() {\n\n m_panel.clear();\n for (CmsCheckBox cb : m_checkBoxes) {\n m_panel.add(setStyle(m_onlyLabels ? new Label(cb.getText()) : cb));\n }\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 }",
"private static String getSolrSpellcheckRfsPath() {\n\n String sPath = OpenCms.getSystemInfo().getWebInfRfsPath();\n\n if (!OpenCms.getSystemInfo().getWebInfRfsPath().endsWith(File.separator)) {\n sPath += File.separator;\n }\n\n return sPath + \"solr\" + File.separator + \"spellcheck\" + File.separator + \"data\";\n }",
"@SuppressWarnings(\"unused\")\n public Handedness getHandedness()\n {\n if ((currentControllerEvent == null) || currentControllerEvent.isRecycled())\n {\n return null;\n }\n return currentControllerEvent.handedness == 0.0f ?\n Handedness.LEFT : Handedness.RIGHT;\n }",
"public void setFirstOccurence(int min, int max) throws ParseException {\n if (fullCondition == null) {\n if ((min < 0) || (min > max) || (max < 1)) {\n throw new ParseException(\"Illegal number {\" + min + \",\" + max + \"}\");\n }\n if (min == 0) {\n firstOptional = true;\n }\n firstMinimumOccurence = Math.max(1, min);\n firstMaximumOccurence = max;\n } else {\n throw new ParseException(\"fullCondition already generated\");\n }\n }",
"public static gslbservice_stats get(nitro_service service, String servicename) throws Exception{\n\t\tgslbservice_stats obj = new gslbservice_stats();\n\t\tobj.set_servicename(servicename);\n\t\tgslbservice_stats response = (gslbservice_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"public static void checkRequired(OptionSet options, String opt1, String opt2)\n throws VoldemortException {\n List<String> opts = Lists.newArrayList();\n opts.add(opt1);\n opts.add(opt2);\n checkRequired(options, opts);\n }",
"public static Iterable<BoxGroup.Info> getAllGroupsByName(final BoxAPIConnection api, String name) {\n final QueryStringBuilder builder = new QueryStringBuilder();\n if (name == null || name.trim().isEmpty()) {\n throw new BoxAPIException(\"Searching groups by name requires a non NULL or non empty name\");\n } else {\n builder.appendParam(\"name\", name);\n }\n\n return new Iterable<BoxGroup.Info>() {\n public Iterator<BoxGroup.Info> iterator() {\n URL url = GROUPS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString());\n return new BoxGroupIterator(api, url);\n }\n };\n }"
] |
create a consumer
@param zookeeperConfig connect config of zookeeper; ex: 127.0.0.1:2181/jafka
@param topic the topic to be watched
@param groupId grouping the consumer clients
@param listener message listener
@return the real consumer | [
"public static StringConsumers buildConsumer(\n final String zookeeperConfig,//\n final String topic,//\n final String groupId, //\n final IMessageListener<String> listener) {\n return buildConsumer(zookeeperConfig, topic, groupId, listener, 2);\n }"
] | [
"private Object getValue(FieldType field, byte[] block)\n {\n Object result = null;\n\n switch (block[0])\n {\n case 0x07: // Field\n {\n result = getFieldType(block);\n break;\n }\n\n case 0x01: // Constant value\n {\n result = getConstantValue(field, block);\n break;\n }\n\n case 0x00: // Prompt\n {\n result = getPromptValue(field, block);\n break;\n }\n }\n\n return result;\n }",
"public static String getVersionString() {\n\t\tString versionString = \"UNKNOWN\";\n\t\tProperties propeties = getProperites();\n\t\tif(propeties != null) {\n\t\t\tversionString = propeties.getProperty(\"finmath-lib.version\");\n\t\t}\n\t\treturn versionString;\n\t}",
"public List<PathAddressTransformer> getPathTransformations(final PathAddress address, PlaceholderResolver placeholderResolver) {\n final List<PathAddressTransformer> list = new ArrayList<PathAddressTransformer>();\n final Iterator<PathElement> iterator = address.iterator();\n resolvePathTransformers(iterator, list, placeholderResolver);\n if(iterator.hasNext()) {\n while(iterator.hasNext()) {\n iterator.next();\n list.add(PathAddressTransformer.DEFAULT);\n }\n }\n return list;\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 }",
"public static appflowpolicylabel get(nitro_service service, String labelname) throws Exception{\n\t\tappflowpolicylabel obj = new appflowpolicylabel();\n\t\tobj.set_labelname(labelname);\n\t\tappflowpolicylabel response = (appflowpolicylabel) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static URI setQueryParams(final URI initialUri, final Multimap<String, String> queryParams) {\n StringBuilder queryString = new StringBuilder();\n for (Map.Entry<String, String> entry: queryParams.entries()) {\n if (queryString.length() > 0) {\n queryString.append(\"&\");\n }\n queryString.append(entry.getKey()).append(\"=\").append(entry.getValue());\n }\n try {\n if (initialUri.getHost() == null && initialUri.getAuthority() != null) {\n return new URI(initialUri.getScheme(), initialUri.getAuthority(), initialUri.getPath(),\n queryString.toString(),\n initialUri.getFragment());\n } else {\n return new URI(initialUri.getScheme(), initialUri.getUserInfo(), initialUri.getHost(),\n initialUri.getPort(),\n initialUri.getPath(),\n queryString.toString(), initialUri.getFragment());\n }\n } catch (URISyntaxException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }",
"public String getDependencyJsonModel() throws IOException {\n final Artifact artifact = DataModelFactory.createArtifact(\"\",\"\",\"\",\"\",\"\",\"\",\"\");\n return JsonUtils.serialize(DataModelFactory.createDependency(artifact, Scope.COMPILE));\n }",
"@Deprecated\r\n public InputStream getOriginalAsStream() throws IOException, FlickrException {\r\n if (originalFormat != null) {\r\n return getOriginalImageAsStream(\"_o.\" + originalFormat);\r\n }\r\n return getOriginalImageAsStream(DEFAULT_ORIGINAL_IMAGE_SUFFIX);\r\n }",
"private void readCalendars(Storepoint phoenixProject)\n {\n Calendars calendars = phoenixProject.getCalendars();\n if (calendars != null)\n {\n for (Calendar calendar : calendars.getCalendar())\n {\n readCalendar(calendar);\n }\n\n ProjectCalendar defaultCalendar = m_projectFile.getCalendarByName(phoenixProject.getDefaultCalendar());\n if (defaultCalendar != null)\n {\n m_projectFile.getProjectProperties().setDefaultCalendarName(defaultCalendar.getName());\n }\n }\n }"
] |
Sets the value associated with the given key; if the the key is one
of the hashable keys, throws an exception.
@throws HashableCoreMapException Attempting to set the value for an
immutable, hashable key. | [
"@Override\r\n public <VALUEBASE, VALUE extends VALUEBASE, KEY extends Key<CoreMap, VALUEBASE>>\r\n VALUE set(Class<KEY> key, VALUE value) {\r\n \r\n if (immutableKeys.contains(key)) {\r\n throw new HashableCoreMapException(\"Attempt to change value \" +\r\n \t\t\"of immutable field \"+key.getSimpleName());\r\n }\r\n \r\n return super.set(key, value);\r\n }"
] | [
"public void setEmptyDefault(String iso) {\n if (iso == null || iso.isEmpty()) {\n iso = DEFAULT_COUNTRY;\n }\n int defaultIdx = mCountries.indexOfIso(iso);\n mSelectedCountry = mCountries.get(defaultIdx);\n mCountrySpinner.setSelection(defaultIdx);\n }",
"public final void notifyContentItemChanged(int position) {\n if (position < 0 || position >= contentItemCount) {\n throw new IndexOutOfBoundsException(\"The given position \" + position\n + \" is not within the position bounds for content items [0 - \" + (contentItemCount - 1) + \"].\");\n }\n notifyItemChanged(position + headerItemCount);\n }",
"protected String findPath(String start, String end) {\n if (start.equals(end)) {\n return start;\n } else {\n return findPath(start, parent.get(end)) + \" -> \" + end;\n }\n }",
"public static double StdDev( int[] values, double mean ){\n double stddev = 0;\n double diff;\n int hits;\n int total = 0;\n\n // for all values\n for ( int i = 0, n = values.length; i < n; i++ )\n {\n hits = values[i];\n diff = (double) i - mean;\n // accumulate std.dev.\n stddev += diff * diff * hits;\n // accumalate total\n total += hits;\n }\n\n return ( total == 0 ) ? 0 : Math.sqrt( stddev / (total - 1) );\n }",
"private void handleMultiInstanceReportResponse(SerialMessage serialMessage,\r\n\t\t\tint offset) {\r\n\t\tlogger.trace(\"Process Multi-instance Report\");\r\n\t\tint commandClassCode = serialMessage.getMessagePayloadByte(offset);\r\n\t\tint instances = serialMessage.getMessagePayloadByte(offset + 1);\r\n\r\n\t\tif (instances == 0) {\r\n\t\t\tsetInstances(1);\r\n\t\t} else \r\n\t\t{\r\n\t\t\tCommandClass commandClass = CommandClass.getCommandClass(commandClassCode);\r\n\t\t\t\r\n\t\t\tif (commandClass == null) {\r\n\t\t\t\tlogger.error(String.format(\"Unsupported command class 0x%02x\", commandClassCode));\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tlogger.debug(String.format(\"Node %d Requested Command Class = %s (0x%02x)\", this.getNode().getNodeId(), commandClass.getLabel() , commandClassCode));\r\n\t\t\tZWaveCommandClass zwaveCommandClass = this.getNode().getCommandClass(commandClass);\r\n\t\t\t\r\n\t\t\tif (zwaveCommandClass == null) {\r\n\t\t\t\tlogger.error(String.format(\"Unsupported command class %s (0x%02x)\", commandClass.getLabel(), commandClassCode));\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tzwaveCommandClass.setInstances(instances);\r\n\t\t\tlogger.debug(String.format(\"Node %d Instances = %d, number of instances set.\", this.getNode().getNodeId(), instances));\r\n\t\t}\r\n\t\t\r\n\t\tfor (ZWaveCommandClass zwaveCommandClass : this.getNode().getCommandClasses())\r\n\t\t\tif (zwaveCommandClass.getInstances() == 0) // still waiting for an instance report of another command class. \r\n\t\t\t\treturn;\r\n\t\t\r\n\t\t// advance node stage.\r\n\t\tthis.getNode().advanceNodeStage();\r\n\t}",
"public static void createUsers(GreenMailOperations greenMail, InternetAddress... addresses) {\n for (InternetAddress address : addresses) {\n greenMail.setUser(address.getAddress(), address.getAddress());\n }\n }",
"public ListActiveCoursesInAccountOptions searchTerm(String searchTerm) {\n if(searchTerm == null || searchTerm.length() < 3) {\n throw new IllegalArgumentException(\"Search term must be at least 3 characters\");\n }\n addSingleItem(\"search_term\", searchTerm);\n return this;\n }",
"public static boolean sameLists(String list1, String list2)\r\n {\r\n return new CommaListIterator(list1).equals(new CommaListIterator(list2));\r\n }",
"protected Map<String, String> getGalleryOpenParams(\n CmsObject cms,\n CmsMessages messages,\n I_CmsWidgetParameter param,\n String resource,\n long hashId) {\n\n Map<String, String> result = new HashMap<String, String>();\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_MODE, A_CmsAjaxGallery.MODE_WIDGET);\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_STORAGE_PREFIX, getGalleryStoragePrefix());\n result.put(I_CmsGalleryProviderConstants.CONFIG_RESOURCE_TYPES, getGalleryTypes());\n if (param.getId() != null) {\n result.put(I_CmsGalleryProviderConstants.KEY_FIELD_ID, param.getId());\n // use javascript to read the current field value\n result.put(\n I_CmsGalleryProviderConstants.CONFIG_CURRENT_ELEMENT,\n \"'+document.getElementById('\" + param.getId() + \"').getAttribute('value')+'\");\n }\n result.put(I_CmsGalleryProviderConstants.KEY_HASH_ID, \"\" + hashId);\n // the edited resource\n if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(resource)) {\n result.put(I_CmsGalleryProviderConstants.CONFIG_REFERENCE_PATH, resource);\n }\n // the start up gallery path\n CmsGalleryWidgetConfiguration configuration = getWidgetConfiguration(cms, messages, param);\n if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(configuration.getStartup())) {\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_PATH, configuration.getStartup());\n }\n // set gallery types if available\n if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(configuration.getGalleryTypes())) {\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_TYPES, configuration.getGalleryTypes());\n }\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_NAME, getGalleryName());\n return result;\n }"
] |
Initializes class data structures and parameters | [
"void initialize(DMatrixSparseCSC A) {\n m = A.numRows;\n n = A.numCols;\n int s = 4*n + (ata ? (n+m+1) : 0);\n\n gw.reshape(s);\n w = gw.data;\n\n // compute the transpose of A\n At.reshape(A.numCols,A.numRows,A.nz_length);\n CommonOps_DSCC.transpose(A,At,gw);\n\n // initialize w\n Arrays.fill(w,0,s,-1); // assign all values in workspace to -1\n\n ancestor = 0;\n maxfirst = n;\n prevleaf = 2*n;\n first = 3*n;\n }"
] | [
"public void pushDryRun() throws Exception {\n if (releaseAction.isCreateVcsTag()) {\n if (scmManager.isTagExists(scmManager.getRemoteConfig(releaseAction.getTargetRemoteName()), releaseAction.getTagUrl())) {\n throw new Exception(String.format(\"Tag with name '%s' already exists\", releaseAction.getTagUrl()));\n }\n }\n\n String testTagName = releaseAction.getTagUrl() + \"_test\";\n try {\n scmManager.testPush(scmManager.getRemoteConfig(releaseAction.getTargetRemoteName()), testTagName);\n } catch (Exception e) {\n throw new Exception(String.format(\"Failed while attempting push dry-run: %s\", e.getMessage()), e);\n } finally {\n if (scmManager.isTagExists(scmManager.getRemoteConfig(releaseAction.getTargetRemoteName()), testTagName)) {\n scmManager.deleteLocalTag(testTagName);\n }\n }\n }",
"public boolean shouldCompress(String requestUri) {\n\t\tString uri = requestUri.toLowerCase();\n\t\treturn checkSuffixes(uri, zipSuffixes);\n\t}",
"public static boolean zipFolder(File folder, String fileName){\n\t\tboolean success = false;\n\t\tif(!folder.isDirectory()){\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tif(fileName == null){\n\t\t\tfileName = folder.getAbsolutePath()+ZIP_EXT;\n\t\t}\n\t\t\n\t\tZipArchiveOutputStream zipOutput = null;\n\t\ttry {\n\t\t\tzipOutput = new ZipArchiveOutputStream(new File(fileName));\n\t\t\t\n\t\t\tsuccess = addFolderContentToZip(folder,zipOutput,\"\");\n\n\t\t\tzipOutput.close();\n\t\t\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t\treturn false;\n\t\t}\n\t\tfinally{\n\t\t\ttry {\n\t\t\t\tif(zipOutput != null){\n\t\t\t\t\tzipOutput.close();\n\t\t\t\t}\n\t\t\t} catch (IOException e) {}\n\t\t}\n\t\treturn success;\n\t}",
"public Collection<Photocount> getCounts(Date[] dates, Date[] takenDates) throws FlickrException {\r\n List<Photocount> photocounts = new ArrayList<Photocount>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_COUNTS);\r\n\r\n if (dates == null && takenDates == null) {\r\n throw new IllegalArgumentException(\"You must provide a value for either dates or takenDates\");\r\n }\r\n\r\n if (dates != null) {\r\n List<String> dateList = new ArrayList<String>();\r\n for (int i = 0; i < dates.length; i++) {\r\n dateList.add(String.valueOf(dates[i].getTime() / 1000L));\r\n }\r\n parameters.put(\"dates\", StringUtilities.join(dateList, \",\"));\r\n }\r\n\r\n if (takenDates != null) {\r\n List<String> takenDateList = new ArrayList<String>();\r\n for (int i = 0; i < takenDates.length; i++) {\r\n takenDateList.add(String.valueOf(takenDates[i].getTime() / 1000L));\r\n }\r\n parameters.put(\"taken_dates\", StringUtilities.join(takenDateList, \",\"));\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photocountsElement = response.getPayload();\r\n NodeList photocountNodes = photocountsElement.getElementsByTagName(\"photocount\");\r\n for (int i = 0; i < photocountNodes.getLength(); i++) {\r\n Element photocountElement = (Element) photocountNodes.item(i);\r\n Photocount photocount = new Photocount();\r\n photocount.setCount(photocountElement.getAttribute(\"count\"));\r\n photocount.setFromDate(photocountElement.getAttribute(\"fromdate\"));\r\n photocount.setToDate(photocountElement.getAttribute(\"todate\"));\r\n photocounts.add(photocount);\r\n }\r\n return photocounts;\r\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 }",
"public Object getColumnValue(String columnName) {\n\t\tfor ( int j = 0; j < columnNames.length; j++ ) {\n\t\t\tif ( columnNames[j].equals( columnName ) ) {\n\t\t\t\treturn columnValues[j];\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"public void setRightValue(int index, Object value)\n {\n m_definedRightValues[index] = value;\n\n if (value instanceof FieldType)\n {\n m_symbolicValues = true;\n }\n else\n {\n if (value instanceof Duration)\n {\n if (((Duration) value).getUnits() != TimeUnit.HOURS)\n {\n value = ((Duration) value).convertUnits(TimeUnit.HOURS, m_properties);\n }\n }\n }\n\n m_workingRightValues[index] = value;\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 Object newInstance(String className) {\n try {\n return classLoader.loadClass(className).newInstance();\n } catch (Exception e) {\n throw new ScalaInstanceNotFound(className);\n }\n }"
] |
Convert from a DTO to an internal Spring bean definition.
@param beanDefinitionDto The DTO object.
@return Returns a Spring bean definition. | [
"public BeanDefinition toInternal(BeanDefinitionInfo beanDefinitionInfo) {\n\t\tif (beanDefinitionInfo instanceof GenericBeanDefinitionInfo) {\n\t\t\tGenericBeanDefinitionInfo genericInfo = (GenericBeanDefinitionInfo) beanDefinitionInfo;\n\t\t\tGenericBeanDefinition def = new GenericBeanDefinition();\n\t\t\tdef.setBeanClassName(genericInfo.getClassName());\n\t\t\tif (genericInfo.getPropertyValues() != null) {\n\t\t\t\tMutablePropertyValues propertyValues = new MutablePropertyValues();\n\t\t\t\tfor (Entry<String, BeanMetadataElementInfo> entry : genericInfo.getPropertyValues().entrySet()) {\n\t\t\t\t\tBeanMetadataElementInfo info = entry.getValue();\n\t\t\t\t\tpropertyValues.add(entry.getKey(), toInternal(info));\n\t\t\t\t}\n\t\t\t\tdef.setPropertyValues(propertyValues);\n\t\t\t}\n\t\t\treturn def;\n\t\t} else if (beanDefinitionInfo instanceof ObjectBeanDefinitionInfo) {\n\t\t\tObjectBeanDefinitionInfo objectInfo = (ObjectBeanDefinitionInfo) beanDefinitionInfo;\n\t\t\treturn createBeanDefinitionByIntrospection(objectInfo.getObject());\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\"Conversion to internal of \" + beanDefinitionInfo.getClass().getName()\n\t\t\t\t\t+ \" not implemented\");\n\t\t}\n\t}"
] | [
"public void setMonitoringService(org.talend.esb.sam.common.service.MonitoringService monitoringService) {\n this.monitoringService = monitoringService;\n }",
"private void checkAndAddRequiredSubStrings(final List<String> requiredSubStrings) {\n\t\tfor( String required : requiredSubStrings ) {\n\t\t\tif( required == null ) {\n\t\t\t\tthrow new NullPointerException(\"required substring should not be null\");\n\t\t\t}\n\t\t\tthis.requiredSubStrings.add(required);\n\t\t}\n\t}",
"public void mark() {\n final long currentTimeMillis = clock.currentTimeMillis();\n\n synchronized (queue) {\n if (queue.size() == capacity) {\n /*\n * we're all filled up already, let's dequeue the oldest\n * timestamp to make room for this new one.\n */\n queue.removeFirst();\n }\n queue.addLast(currentTimeMillis);\n }\n }",
"public boolean hasProperties(Set<PropertyKey> keys) {\n for (PropertyKey key : keys) {\n if (null == getProperty(key.m_key)) {\n return false;\n }\n }\n \n return true;\n }",
"public static appfwwsdl get(nitro_service service, String name) throws Exception{\n\t\tappfwwsdl obj = new appfwwsdl();\n\t\tobj.set_name(name);\n\t\tappfwwsdl response = (appfwwsdl) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static cmppolicylabel_cmppolicy_binding[] get(nitro_service service, String labelname) throws Exception{\n\t\tcmppolicylabel_cmppolicy_binding obj = new cmppolicylabel_cmppolicy_binding();\n\t\tobj.set_labelname(labelname);\n\t\tcmppolicylabel_cmppolicy_binding response[] = (cmppolicylabel_cmppolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public Info getInfo() {\n BoxAPIConnection api = this.getAPI();\n URL url = COLLABORATION_URL_TEMPLATE.build(api.getBaseURL(), this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n return new Info(jsonObject);\n }",
"public static int daysDiff(Date earlierDate, Date laterDate) {\n if (earlierDate == null || laterDate == null) {\n return 0;\n }\n\n return (int) ((laterDate.getTime() / DAY_MILLIS) - (earlierDate.getTime() / DAY_MILLIS));\n }",
"@Override\n public final int getInt(final String key) {\n Integer result = optInt(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }"
] |
Retrieves the class object for the given qualified class name.
@param className The qualified name of the class
@param initialize Whether the class shall be initialized
@return The class object | [
"public static Class getClass(String className, boolean initialize) throws ClassNotFoundException\r\n {\r\n return Class.forName(className, initialize, getClassLoader());\r\n }"
] | [
"public void setShadow(float radius, float dx, float dy, int color) {\n\t\tshadowRadius = radius;\n\t\tshadowDx = dx;\n\t\tshadowDy = dy;\n\t\tshadowColor = color;\n\t\tupdateShadow();\n\t}",
"private static BoxRetentionPolicy.Info createRetentionPolicy(BoxAPIConnection api, String name, String type,\r\n int length, String action) {\r\n return createRetentionPolicy(api, name, type, length, action, null);\r\n }",
"public DiscreteInterval plus(DiscreteInterval other) {\n return new DiscreteInterval(this.min + other.min, this.max + other.max);\n }",
"private int handleIOException(IOException ex) throws IOException {\n\t\tif (AUTH_ERROR.equals(ex.getMessage()) || AUTH_ERROR_JELLY_BEAN.equals(ex.getMessage())) {\n\t\t\treturn HttpStatus.UNAUTHORIZED.value();\n\t\t} else if (PROXY_AUTH_ERROR.equals(ex.getMessage())) {\n\t\t\treturn HttpStatus.PROXY_AUTHENTICATION_REQUIRED.value();\n\t\t} else {\n\t\t\tthrow ex;\n\t\t}\n\t}",
"public static void setDefaultConfiguration(SimpleConfiguration config) {\n config.setProperty(CONNECTION_ZOOKEEPERS_PROP, CONNECTION_ZOOKEEPERS_DEFAULT);\n config.setProperty(CONNECTION_ZOOKEEPER_TIMEOUT_PROP, CONNECTION_ZOOKEEPER_TIMEOUT_DEFAULT);\n config.setProperty(DFS_ROOT_PROP, DFS_ROOT_DEFAULT);\n config.setProperty(ACCUMULO_ZOOKEEPERS_PROP, ACCUMULO_ZOOKEEPERS_DEFAULT);\n config.setProperty(WORKER_NUM_THREADS_PROP, WORKER_NUM_THREADS_DEFAULT);\n config.setProperty(TRANSACTION_ROLLBACK_TIME_PROP, TRANSACTION_ROLLBACK_TIME_DEFAULT);\n config.setProperty(LOADER_NUM_THREADS_PROP, LOADER_NUM_THREADS_DEFAULT);\n config.setProperty(LOADER_QUEUE_SIZE_PROP, LOADER_QUEUE_SIZE_DEFAULT);\n config.setProperty(MINI_START_ACCUMULO_PROP, MINI_START_ACCUMULO_DEFAULT);\n config.setProperty(MINI_DATA_DIR_PROP, MINI_DATA_DIR_DEFAULT);\n }",
"public boolean handleKeyDeletion(final String key) {\n\n if (m_keyset.getKeySet().contains(key)) {\n if (removeKeyForAllLanguages(key)) {\n m_keyset.removeKey(key);\n return true;\n } else {\n return false;\n }\n }\n return true;\n }",
"public Set<MetadataProvider> getMetadataProviders(MediaDetails sourceMedia) {\n String key = (sourceMedia == null)? \"\" : sourceMedia.hashKey();\n Set<MetadataProvider> result = metadataProviders.get(key);\n if (result == null) {\n return Collections.emptySet();\n }\n return Collections.unmodifiableSet(new HashSet<MetadataProvider>(result));\n }",
"public static ObjectName registerMbean(String typeName, Object obj) {\n MBeanServer server = ManagementFactory.getPlatformMBeanServer();\n ObjectName name = JmxUtils.createObjectName(JmxUtils.getPackageName(obj.getClass()),\n typeName);\n registerMbean(server, JmxUtils.createModelMBean(obj), name);\n return name;\n }",
"public byte[] toArray() {\n byte[] copy = new byte[length];\n System.arraycopy(data, offset, copy, 0, length);\n return copy;\n }"
] |
Sets the jdbcLevel. parse the string setting and check that it is indeed an integer.
@param jdbcLevel The jdbcLevel to set | [
"public void setJdbcLevel(String jdbcLevel)\r\n {\r\n if (jdbcLevel != null)\r\n {\r\n try\r\n {\r\n double intLevel = Double.parseDouble(jdbcLevel);\r\n setJdbcLevel(intLevel);\r\n }\r\n catch(NumberFormatException nfe)\r\n {\r\n setJdbcLevel(2.0);\r\n logger.info(\"Specified JDBC level was not numeric (Value=\" + jdbcLevel + \"), used default jdbc level of 2.0 \");\r\n }\r\n }\r\n else\r\n {\r\n setJdbcLevel(2.0);\r\n logger.info(\"Specified JDBC level was null, used default jdbc level of 2.0 \");\r\n }\r\n }"
] | [
"protected View postDeclineView() {\n\t\treturn new TopLevelWindowRedirect() {\n\t\t\t@Override\n\t\t\tprotected String getRedirectUrl(Map<String, ?> model) {\n\t\t\t\treturn postDeclineUrl;\n\t\t\t}\n\t\t};\n\t}",
"public static Value.Builder makeValue(Date date) {\n return Value.newBuilder().setTimestampValue(toTimestamp(date.getTime() * 1000L));\n }",
"protected void checkConflictingRoles() {\n if (getType().isAnnotationPresent(Interceptor.class)) {\n throw BeanLogger.LOG.ejbCannotBeInterceptor(getType());\n }\n if (getType().isAnnotationPresent(Decorator.class)) {\n throw BeanLogger.LOG.ejbCannotBeDecorator(getType());\n }\n }",
"@Subscribe\n public void onQuit(AggregatedQuitEvent e) {\n if (summaryFile != null) {\n try {\n Persister persister = new Persister();\n persister.write(new MavenFailsafeSummaryModel(summaryListener.getResult()), summaryFile);\n } catch (Exception x) {\n junit4.log(\"Could not serialize summary report.\", x, Project.MSG_WARN);\n }\n }\n }",
"public StreamReader getTableData(String name) throws IOException\n {\n InputStream stream = new ByteArrayInputStream(m_tableData.get(name));\n if (m_majorVersion > 5)\n { \n byte[] header = new byte[24];\n stream.read(header);\n SynchroLogger.log(\"TABLE HEADER\", header);\n }\n return new StreamReader(m_majorVersion, stream);\n }",
"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 GVRAnimator start(int animIndex)\n {\n if ((animIndex < 0) || (animIndex >= mAnimations.size()))\n {\n throw new IndexOutOfBoundsException(\"Animation index out of bounds\");\n }\n GVRAnimator anim = mAnimations.get(animIndex);\n start(anim);\n return anim;\n }",
"public Enumeration getPKEnumerationByQuery(Class primaryKeyClass, Query query) throws PersistenceBrokerException\n {\n if (logger.isDebugEnabled()) logger.debug(\"getPKEnumerationByQuery \" + query);\n\n query.setFetchSize(1);\n ClassDescriptor cld = getClassDescriptor(query.getSearchClass());\n return new PkEnumeration(query, cld, primaryKeyClass, this);\n }",
"private String formatPriority(Priority value)\n {\n String result = null;\n\n if (value != null)\n {\n String[] priorityTypes = LocaleData.getStringArray(m_locale, LocaleData.PRIORITY_TYPES);\n int priority = value.getValue();\n if (priority < Priority.LOWEST)\n {\n priority = Priority.LOWEST;\n }\n else\n {\n if (priority > Priority.DO_NOT_LEVEL)\n {\n priority = Priority.DO_NOT_LEVEL;\n }\n }\n\n priority /= 100;\n\n result = priorityTypes[priority - 1];\n }\n\n return (result);\n }"
] |
Factory for 'and' and 'or' predicates. | [
"private static Predicate join(final String joinWord, final List<Predicate> preds) {\n return new Predicate() {\n public void init(AbstractSqlCreator creator) {\n for (Predicate p : preds) {\n p.init(creator);\n }\n }\n public String toSql() {\n StringBuilder sb = new StringBuilder()\n .append(\"(\");\n boolean first = true;\n for (Predicate p : preds) {\n if (!first) {\n sb.append(\" \").append(joinWord).append(\" \");\n }\n sb.append(p.toSql());\n first = false;\n }\n return sb.append(\")\").toString();\n }\n };\n }"
] | [
"public static LBuffer loadFrom(File file) throws IOException {\n FileChannel fin = new FileInputStream(file).getChannel();\n long fileSize = fin.size();\n if (fileSize > Integer.MAX_VALUE)\n throw new IllegalArgumentException(\"Cannot load from file more than 2GB: \" + file);\n LBuffer b = new LBuffer((int) fileSize);\n long pos = 0L;\n WritableChannelWrap ch = new WritableChannelWrap(b);\n while (pos < fileSize) {\n pos += fin.transferTo(0, fileSize, ch);\n }\n return b;\n }",
"public DbOrganization getOrganization(final DbArtifact dbArtifact) {\n final DbModule module = getModule(dbArtifact);\n\n if(module == null || module.getOrganization() == null){\n return null;\n }\n\n return repositoryHandler.getOrganization(module.getOrganization());\n }",
"public static Polygon calculateBounds(final MapfishMapContext context) {\n double rotation = context.getRootContext().getRotation();\n ReferencedEnvelope env = context.getRootContext().toReferencedEnvelope();\n\n Coordinate centre = env.centre();\n AffineTransform rotateInstance = AffineTransform.getRotateInstance(rotation, centre.x, centre.y);\n\n double[] dstPts = new double[8];\n double[] srcPts = {\n env.getMinX(), env.getMinY(), env.getMinX(), env.getMaxY(),\n env.getMaxX(), env.getMaxY(), env.getMaxX(), env.getMinY()\n };\n\n rotateInstance.transform(srcPts, 0, dstPts, 0, 4);\n\n return new GeometryFactory().createPolygon(new Coordinate[]{\n new Coordinate(dstPts[0], dstPts[1]), new Coordinate(dstPts[2], dstPts[3]),\n new Coordinate(dstPts[4], dstPts[5]), new Coordinate(dstPts[6], dstPts[7]),\n new Coordinate(dstPts[0], dstPts[1])\n });\n }",
"public void setAppender(final Appender appender) {\n if (this.appender != null) {\n close();\n }\n checkAccess(this);\n if (applyLayout && appender != null) {\n final Formatter formatter = getFormatter();\n appender.setLayout(formatter == null ? null : new FormatterLayout(formatter));\n }\n appenderUpdater.set(this, appender);\n }",
"public Collection getReaders(Object obj)\r\n {\r\n \tcheckTimedOutLocks();\r\n Identity oid = new Identity(obj,getBroker());\r\n return getReaders(oid);\r\n }",
"public static DMatrixRMaj convert(DMatrixRBlock src , DMatrixRMaj dst )\n {\n return ConvertDMatrixStruct.convert(src,dst);\n }",
"public void addRequest(long timeNS,\n long numEmptyResponses,\n long valueBytes,\n long keyBytes,\n long getAllAggregatedCount) {\n // timing instrumentation (trace only)\n long startTimeNs = 0;\n if(logger.isTraceEnabled()) {\n startTimeNs = System.nanoTime();\n }\n\n long currentTime = time.milliseconds();\n\n timeSensor.record((double) timeNS / voldemort.utils.Time.NS_PER_MS, currentTime);\n emptyResponseKeysSensor.record(numEmptyResponses, currentTime);\n valueBytesSensor.record(valueBytes, currentTime);\n keyBytesSensor.record(keyBytes, currentTime);\n getAllKeysCountSensor.record(getAllAggregatedCount, currentTime);\n\n // timing instrumentation (trace only)\n if(logger.isTraceEnabled()) {\n logger.trace(\"addRequest took \" + (System.nanoTime() - startTimeNs) + \" ns.\");\n }\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 }",
"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 }"
] |
Read resource data. | [
"private void processResources() throws SQLException\n {\n List<Row> rows = getRows(\"select * from zresource where zproject=? order by zorderinproject\", m_projectID);\n for (Row row : rows)\n {\n Resource resource = m_project.addResource();\n resource.setUniqueID(row.getInteger(\"Z_PK\"));\n resource.setEmailAddress(row.getString(\"ZEMAIL\"));\n resource.setInitials(row.getString(\"ZINITIALS\"));\n resource.setName(row.getString(\"ZTITLE_\"));\n resource.setGUID(row.getUUID(\"ZUNIQUEID\"));\n resource.setType(row.getResourceType(\"ZTYPE\"));\n resource.setMaterialLabel(row.getString(\"ZMATERIALUNIT\"));\n\n if (resource.getType() == ResourceType.WORK)\n {\n resource.setMaxUnits(Double.valueOf(NumberHelper.getDouble(row.getDouble(\"ZAVAILABLEUNITS_\")) * 100.0));\n }\n\n Integer calendarID = row.getInteger(\"ZRESOURCECALENDAR\");\n if (calendarID != null)\n {\n ProjectCalendar calendar = m_project.getCalendarByUniqueID(calendarID);\n if (calendar != null)\n {\n calendar.setName(resource.getName());\n resource.setResourceCalendar(calendar);\n }\n }\n\n m_eventManager.fireResourceReadEvent(resource);\n }\n }"
] | [
"public void ifPropertyValueEquals(String template, Properties attributes) throws XDocletException\r\n {\r\n String value = getPropertyValue(attributes.getProperty(ATTRIBUTE_LEVEL), attributes.getProperty(ATTRIBUTE_NAME));\r\n String expected = attributes.getProperty(ATTRIBUTE_VALUE);\r\n\r\n if (value == null)\r\n {\r\n value = attributes.getProperty(ATTRIBUTE_DEFAULT);\r\n }\r\n if (expected.equals(value))\r\n {\r\n generate(template);\r\n }\r\n }",
"public void addStep(String name, String robot, Map<String, Object> options){\n steps.addStep(name, robot, options);\n }",
"public void addFkToThisClass(String column)\r\n {\r\n if (fksToThisClass == null)\r\n {\r\n fksToThisClass = new Vector();\r\n }\r\n fksToThisClass.add(column);\r\n fksToThisClassAry = null;\r\n }",
"public static void closeMASCaseManager(File caseManager) {\n\n FileWriter caseManagerWriter;\n try {\n caseManagerWriter = new FileWriter(caseManager, true);\n caseManagerWriter.write(\"}\\n\");\n caseManagerWriter.flush();\n caseManagerWriter.close();\n } catch (IOException e) {\n Logger logger = Logger\n .getLogger(\"CreateMASCaseManager.closeMASCaseManager\");\n logger.info(\"ERROR: There is a mistake closing caseManager file.\\n\");\n }\n\n }",
"public static gslbservice[] get(nitro_service service) throws Exception{\n\t\tgslbservice obj = new gslbservice();\n\t\tgslbservice[] response = (gslbservice[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"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 void main(String[] args) {\r\n Settings settings = new Settings();\r\n new JCommander(settings, args);\r\n\r\n if (!settings.isGuiSupressed()) {\r\n OkapiUI okapiUi = new OkapiUI();\r\n okapiUi.setVisible(true);\r\n } else {\r\n int returnValue;\r\n \r\n returnValue = commandLine(settings);\r\n \r\n if (returnValue != 0) {\r\n System.out.println(\"An error occurred\");\r\n }\r\n }\r\n }",
"public double computeLikelihoodP() {\n double ret = 1.0;\n\n for( int i = 0; i < r.numRows; i++ ) {\n double a = r.get(i,0);\n\n ret *= Math.exp(-a*a/2.0);\n }\n\n return ret;\n }",
"public List<Formation> listFormation(String appName) {\n return connection.execute(new FormationList(appName), apiKey);\n }"
] |
This procedure sets permissions to the given file to not allow everybody to read it.
Only when underlying OS allows the change.
@param file File to set permissions | [
"private void setFileNotWorldReadablePermissions(File file) {\n file.setReadable(false, false);\n file.setWritable(false, false);\n file.setExecutable(false, false);\n file.setReadable(true, true);\n file.setWritable(true, true);\n }"
] | [
"private static Constraint loadConstraint(Annotation context) {\n Constraint constraint = null;\n final ServiceLoader<Constraint> constraints = ServiceLoader.load(Constraint.class);\n\n for (Constraint aConstraint : constraints) {\n try {\n aConstraint.getClass().getDeclaredMethod(\"check\", context.annotationType());\n constraint = aConstraint;\n break;\n } catch (NoSuchMethodException e) {\n // Look for next implementation if method not found with required signature.\n }\n }\n\n if (constraint == null) {\n throw new IllegalStateException(\"Couldn't found any implementation of \" + Constraint.class.getName());\n }\n return constraint;\n }",
"public synchronized int skip(int count) {\n if (count > available) {\n count = available;\n }\n idxGet = (idxGet + count) % capacity;\n available -= count;\n return count;\n }",
"public Set<? extends Processor<?, ?>> getAllProcessors() {\n IdentityHashMap<Processor<?, ?>, Void> all = new IdentityHashMap<>();\n all.put(this.getProcessor(), null);\n for (ProcessorGraphNode<?, ?> dependency: this.dependencies) {\n for (Processor<?, ?> p: dependency.getAllProcessors()) {\n all.put(p, null);\n }\n }\n return all.keySet();\n }",
"private static Dimension adaptTileDimensions(\n final Dimension pixels, final int maxWidth, final int maxHeight) {\n return new Dimension(adaptTileDimension(pixels.width, maxWidth),\n adaptTileDimension(pixels.height, maxHeight));\n }",
"private void setUserFieldValue(UDFAssignmentType udf, DataType dataType, Object value)\n {\n switch (dataType)\n {\n case DURATION:\n {\n udf.setTextValue(((Duration) value).toString());\n break;\n }\n\n case CURRENCY:\n {\n if (!(value instanceof Double))\n {\n value = Double.valueOf(((Number) value).doubleValue());\n }\n udf.setCostValue((Double) value);\n break;\n }\n\n case BINARY:\n {\n udf.setTextValue(\"\");\n break;\n }\n\n case STRING:\n {\n udf.setTextValue((String) value);\n break;\n }\n\n case DATE:\n {\n udf.setStartDateValue((Date) value);\n break;\n }\n\n case NUMERIC:\n {\n if (!(value instanceof Double))\n {\n value = Double.valueOf(((Number) value).doubleValue());\n }\n udf.setDoubleValue((Double) value);\n break;\n }\n\n case BOOLEAN:\n {\n udf.setIntegerValue(BooleanHelper.getBoolean((Boolean) value) ? Integer.valueOf(1) : Integer.valueOf(0));\n break;\n }\n\n case INTEGER:\n case SHORT:\n {\n udf.setIntegerValue(NumberHelper.getInteger((Number) value));\n break;\n }\n\n default:\n {\n throw new RuntimeException(\"Unconvertible data type: \" + dataType);\n }\n }\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 static vpnglobal_authenticationsamlpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tvpnglobal_authenticationsamlpolicy_binding obj = new vpnglobal_authenticationsamlpolicy_binding();\n\t\tvpnglobal_authenticationsamlpolicy_binding response[] = (vpnglobal_authenticationsamlpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public Response executeToResponse(HttpConnection connection) {\n InputStream is = null;\n try {\n is = this.executeToInputStream(connection);\n Response response = getResponse(is, Response.class, getGson());\n response.setStatusCode(connection.getConnection().getResponseCode());\n response.setReason(connection.getConnection().getResponseMessage());\n return response;\n } catch (IOException e) {\n throw new CouchDbException(\"Error retrieving response code or message.\", e);\n } finally {\n close(is);\n }\n }",
"@Override\n public final Integer optInt(final String key) {\n final int result = this.obj.optInt(key, Integer.MIN_VALUE);\n return result == Integer.MIN_VALUE ? null : result;\n }"
] |
Use this API to delete clusterinstance of given name. | [
"public static base_response delete(nitro_service client, Long clid) throws Exception {\n\t\tclusterinstance deleteresource = new clusterinstance();\n\t\tdeleteresource.clid = clid;\n\t\treturn deleteresource.delete_resource(client);\n\t}"
] | [
"@Override\n\tpublic double getDiscountFactor(AnalyticModelInterface model, double maturity)\n\t{\n\t\t// Change time scale\n\t\tmaturity *= timeScaling;\n\n\t\tdouble beta1\t= parameter[0];\n\t\tdouble beta2\t= parameter[1];\n\t\tdouble beta3\t= parameter[2];\n\t\tdouble beta4\t= parameter[3];\n\t\tdouble tau1\t\t= parameter[4];\n\t\tdouble tau2\t\t= parameter[5];\n\n\t\tdouble x1 = tau1 > 0 ? FastMath.exp(-maturity/tau1) : 0.0;\n\t\tdouble x2 = tau2 > 0 ? FastMath.exp(-maturity/tau2) : 0.0;\n\n\t\tdouble y1 = tau1 > 0 ? (maturity > 0.0 ? (1.0-x1)/maturity*tau1 : 1.0) : 0.0;\n\t\tdouble y2 = tau2 > 0 ? (maturity > 0.0 ? (1.0-x2)/maturity*tau2 : 1.0) : 0.0;\n\n\t\tdouble zeroRate = beta1 + beta2 * y1 + beta3 * (y1-x1) + beta4 * (y2-x2);\n\n\t\treturn Math.exp(- zeroRate * maturity);\n\t}",
"public static double JaccardDistance(double[] p, double[] q) {\n double distance = 0;\n int intersection = 0, union = 0;\n\n for (int x = 0; x < p.length; x++) {\n if ((p[x] != 0) || (q[x] != 0)) {\n if (p[x] == q[x]) {\n intersection++;\n }\n\n union++;\n }\n }\n\n if (union != 0)\n distance = 1.0 - ((double) intersection / (double) union);\n else\n distance = 0;\n\n return distance;\n }",
"public static Predicate is(final String sql) {\n return new Predicate() {\n public String toSql() {\n return sql;\n }\n public void init(AbstractSqlCreator creator) {\n }\n };\n }",
"public List<Object> getAll(int dataSet) throws SerializationException {\r\n\t\tList<Object> result = new ArrayList<Object>();\r\n\t\tfor (Iterator<DataSet> i = dataSets.iterator(); i.hasNext();) {\r\n\t\t\tDataSet ds = i.next();\r\n\t\t\tDataSetInfo info = ds.getInfo();\r\n\t\t\tif (info.getDataSetNumber() == dataSet) {\r\n\t\t\t\tresult.add(getData(ds));\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn result;\r\n\t}",
"private <T> T request(ClientRequest<T> delegate, String operationName) {\n long startTimeMs = -1;\n long startTimeNs = -1;\n\n if(logger.isDebugEnabled()) {\n startTimeMs = System.currentTimeMillis();\n }\n ClientRequestExecutor clientRequestExecutor = pool.checkout(destination);\n String debugMsgStr = \"\";\n\n startTimeNs = System.nanoTime();\n\n BlockingClientRequest<T> blockingClientRequest = null;\n try {\n blockingClientRequest = new BlockingClientRequest<T>(delegate, timeoutMs);\n clientRequestExecutor.addClientRequest(blockingClientRequest,\n timeoutMs,\n System.nanoTime() - startTimeNs);\n\n boolean awaitResult = blockingClientRequest.await();\n\n if(awaitResult == false) {\n blockingClientRequest.timeOut();\n }\n\n if(logger.isDebugEnabled())\n debugMsgStr += \"success\";\n\n return blockingClientRequest.getResult();\n } catch(InterruptedException e) {\n\n if(logger.isDebugEnabled())\n debugMsgStr += \"unreachable: \" + e.getMessage();\n\n throw new UnreachableStoreException(\"Failure in \" + operationName + \" on \"\n + destination + \": \" + e.getMessage(), e);\n } catch(UnreachableStoreException e) {\n clientRequestExecutor.close();\n\n if(logger.isDebugEnabled())\n debugMsgStr += \"failure: \" + e.getMessage();\n\n throw new UnreachableStoreException(\"Failure in \" + operationName + \" on \"\n + destination + \": \" + e.getMessage(), e.getCause());\n } finally {\n if(blockingClientRequest != null && !blockingClientRequest.isComplete()) {\n // close the executor if we timed out\n clientRequestExecutor.close();\n }\n // Record operation time\n long opTimeNs = Utils.elapsedTimeNs(startTimeNs, System.nanoTime());\n if(stats != null) {\n stats.recordSyncOpTimeNs(destination, opTimeNs);\n }\n if(logger.isDebugEnabled()) {\n logger.debug(\"Sync request end, type: \"\n + operationName\n + \" requestRef: \"\n + System.identityHashCode(delegate)\n + \" totalTimeNs: \"\n + opTimeNs\n + \" start time: \"\n + startTimeMs\n + \" end time: \"\n + System.currentTimeMillis()\n + \" client:\"\n + clientRequestExecutor.getSocketChannel().socket().getLocalAddress()\n + \":\"\n + clientRequestExecutor.getSocketChannel().socket().getLocalPort()\n + \" server: \"\n + clientRequestExecutor.getSocketChannel()\n .socket()\n .getRemoteSocketAddress() + \" outcome: \"\n + debugMsgStr);\n }\n\n pool.checkin(destination, clientRequestExecutor);\n }\n }",
"@Deprecated\n public static RemoteProxyController create(final ManagementChannelHandler channelAssociation, final PathAddress pathAddress, final ProxyOperationAddressTranslator addressTranslator) {\n final TransactionalProtocolClient client = TransactionalProtocolHandlers.createClient(channelAssociation);\n // the remote proxy\n return create(client, pathAddress, addressTranslator, ModelVersion.CURRENT);\n }",
"static String encodeUriComponent(String source, String encoding, Type type) throws UnsupportedEncodingException {\n\t\tif (source == null) {\n\t\t\treturn null;\n\t\t}\n\t\tAssert.hasLength(encoding, \"Encoding must not be empty\");\n\t\tbyte[] bytes = encodeBytes(source.getBytes(encoding), type);\n\t\treturn new String(bytes, \"US-ASCII\");\n\t}",
"private void addBlock(List<GenericCriteria> list, byte[] block, TestOperator operator)\n {\n GenericCriteria result = new GenericCriteria(m_properties);\n result.setOperator(operator);\n list.add(result);\n processBlock(result.getCriteriaList(), getChildBlock(block));\n processBlock(list, getListNextBlock(block));\n }",
"protected boolean isFiltered(Param param) {\n\t\tAbstractElement elementToParse = param.elementToParse;\n\t\twhile (elementToParse != null) {\n\t\t\tif (isFiltered(elementToParse, param)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\telementToParse = getEnclosingSingleElementGroup(elementToParse);\n\t\t}\n\t\treturn false;\n\t}"
] |
Only call with monitor for 'this' held | [
"private void map(Resource root) {\n\n for (Resource.ResourceEntry serverGroup : root.getChildren(SERVER_GROUP)) {\n String serverGroupName = serverGroup.getName();\n ModelNode serverGroupModel = serverGroup.getModel();\n String profile = serverGroupModel.require(PROFILE).asString();\n store(serverGroupName, profile, profilesToGroups);\n String socketBindingGroup = serverGroupModel.require(SOCKET_BINDING_GROUP).asString();\n store(serverGroupName, socketBindingGroup, socketsToGroups);\n\n for (Resource.ResourceEntry deployment : serverGroup.getChildren(DEPLOYMENT)) {\n store(serverGroupName, deployment.getName(), deploymentsToGroups);\n }\n\n for (Resource.ResourceEntry overlay : serverGroup.getChildren(DEPLOYMENT_OVERLAY)) {\n store(serverGroupName, overlay.getName(), overlaysToGroups);\n }\n\n }\n\n for (Resource.ResourceEntry host : root.getChildren(HOST)) {\n String hostName = host.getPathElement().getValue();\n for (Resource.ResourceEntry serverConfig : host.getChildren(SERVER_CONFIG)) {\n ModelNode serverConfigModel = serverConfig.getModel();\n String serverGroupName = serverConfigModel.require(GROUP).asString();\n store(serverGroupName, hostName, hostsToGroups);\n }\n }\n }"
] | [
"@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public Searcher cancelPendingRequests() {\n if (pendingRequests.size() != 0) {\n for (int i = 0; i < pendingRequests.size(); i++) {\n int reqId = pendingRequests.keyAt(i);\n Request r = pendingRequests.valueAt(i);\n if (!r.isFinished() && !r.isCancelled()) {\n cancelRequest(r, reqId);\n }\n }\n }\n return this;\n }",
"public static int rank( DMatrixRMaj A ) {\n SingularValueDecomposition_F64<DMatrixRMaj> svd = DecompositionFactory_DDRM.svd(A.numRows,A.numCols,false,true,true);\n\n if( svd.inputModified() ) {\n A = A.copy();\n }\n if( !svd.decompose(A)) {\n throw new RuntimeException(\"SVD Failed!\");\n }\n\n int N = svd.numberOfSingularValues();\n double sv[] = svd.getSingularValues();\n\n double threshold = singularThreshold(sv,N);\n int count = 0;\n for (int i = 0; i < sv.length; i++) {\n if( sv[i] >= threshold ) {\n count++;\n }\n }\n return count;\n }",
"public static csvserver_cachepolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_cachepolicy_binding obj = new csvserver_cachepolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_cachepolicy_binding response[] = (csvserver_cachepolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public CollectionRequest<Task> getTasksWithTag(String tag) {\n \n String path = String.format(\"/tags/%s/tasks\", tag);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }",
"private static final String correctNumberFormat(String value)\n {\n String result;\n int index = value.indexOf(',');\n if (index == -1)\n {\n result = value;\n }\n else\n {\n char[] chars = value.toCharArray();\n chars[index] = '.';\n result = new String(chars);\n }\n return result;\n }",
"protected void postDestroyConnection(ConnectionHandle handle){\r\n\t\tConnectionPartition partition = handle.getOriginatingPartition();\r\n\r\n\t\tif (this.finalizableRefQueue != null && handle.getInternalConnection() != null){ //safety\r\n\t\t\tthis.finalizableRefs.remove(handle.getInternalConnection());\r\n\t\t\t//\t\t\tassert o != null : \"Did not manage to remove connection from finalizable ref queue\";\r\n\t\t}\r\n\r\n\t\tpartition.updateCreatedConnections(-1);\r\n\t\tpartition.setUnableToCreateMoreTransactions(false); // we can create new ones now, this is an optimization\r\n\r\n\r\n\t\t// \"Destroying\" for us means: don't put it back in the pool.\r\n\t\tif (handle.getConnectionHook() != null){\r\n\t\t\thandle.getConnectionHook().onDestroy(handle);\r\n\t\t}\r\n\r\n\t}",
"public static void writeFlowId(Message message, String flowId) {\n if (!(message instanceof SoapMessage)) {\n return;\n }\n SoapMessage soapMessage = (SoapMessage)message;\n Header hdFlowId = soapMessage.getHeader(FLOW_ID_QNAME);\n if (hdFlowId != null) {\n LOG.warning(\"FlowId already existing in soap header, need not to write FlowId header.\");\n return;\n }\n\n try {\n soapMessage.getHeaders().add(\n new Header(FLOW_ID_QNAME, flowId, new JAXBDataBinding(String.class)));\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Stored flowId '\" + flowId + \"' in soap header: \" + FLOW_ID_QNAME);\n }\n } catch (JAXBException e) {\n LOG.log(Level.SEVERE, \"Couldn't create flowId header.\", e);\n }\n\n }",
"void applyFreshParticleOnScreen(\n @NonNull final Scene scene,\n final int position\n ) {\n final int w = scene.getWidth();\n final int h = scene.getHeight();\n if (w == 0 || h == 0) {\n throw new IllegalStateException(\n \"Cannot generate particles if scene width or height is 0\");\n }\n\n final double direction = Math.toRadians(random.nextInt(360));\n final float dCos = (float) Math.cos(direction);\n final float dSin = (float) Math.sin(direction);\n final float x = random.nextInt(w);\n final float y = random.nextInt(h);\n final float speedFactor = newRandomIndividualParticleSpeedFactor();\n final float radius = newRandomIndividualParticleRadius(scene);\n\n scene.setParticleData(\n position,\n x,\n y,\n dCos,\n dSin,\n radius,\n speedFactor);\n }",
"public List<Profile> findAllProfiles() throws Exception {\n ArrayList<Profile> allProfiles = new ArrayList<>();\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_PROFILE);\n results = statement.executeQuery();\n while (results.next()) {\n allProfiles.add(this.getProfileFromResultSet(results));\n }\n } catch (Exception e) {\n throw e;\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 return allProfiles;\n }"
] |
Use this API to fetch the statistics of all vpath_stats resources that are configured on netscaler. | [
"public static vpath_stats get(nitro_service service) throws Exception{\n\t\tvpath_stats obj = new vpath_stats();\n\t\tvpath_stats[] response = (vpath_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}"
] | [
"protected Element createLineElement(float x1, float y1, float x2, float y2)\n {\n HtmlDivLine line = new HtmlDivLine(x1, y1, x2, y2);\n String color = colorString(getGraphicsState().getStrokingColor());\n\n StringBuilder pstyle = new StringBuilder(50);\n pstyle.append(\"left:\").append(style.formatLength(line.getLeft())).append(';');\n pstyle.append(\"top:\").append(style.formatLength(line.getTop())).append(';');\n pstyle.append(\"width:\").append(style.formatLength(line.getWidth())).append(';');\n pstyle.append(\"height:\").append(style.formatLength(line.getHeight())).append(';');\n pstyle.append(line.getBorderSide()).append(':').append(style.formatLength(line.getLineStrokeWidth())).append(\" solid \").append(color).append(';');\n if (line.getAngleDegrees() != 0)\n pstyle.append(\"transform:\").append(\"rotate(\").append(line.getAngleDegrees()).append(\"deg);\");\n\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 }",
"static DocumentVersionInfo getRemoteVersionInfo(final BsonDocument remoteDocument) {\n final BsonDocument version = getDocumentVersionDoc(remoteDocument);\n return new DocumentVersionInfo(\n version,\n remoteDocument != null\n ? BsonUtils.getDocumentId(remoteDocument) : null\n );\n }",
"public static boolean propertyExists(Class<?> clazz, String property, ElementType elementType) {\n\t\tif ( ElementType.FIELD.equals( elementType ) ) {\n\t\t\treturn getDeclaredField( clazz, property ) != null;\n\t\t}\n\t\telse {\n\t\t\tString capitalizedPropertyName = capitalize( property );\n\n\t\t\tMethod method = getMethod( clazz, PROPERTY_ACCESSOR_PREFIX_GET + capitalizedPropertyName );\n\t\t\tif ( method != null && method.getReturnType() != void.class ) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tmethod = getMethod( clazz, PROPERTY_ACCESSOR_PREFIX_IS + capitalizedPropertyName );\n\t\t\tif ( method != null && method.getReturnType() == boolean.class ) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}",
"private <A extends Annotation> AnnotationConverter<A> getConverter(Annotation annotation) {\n\t\tMappingOption mappingOption = annotation.annotationType().getAnnotation( MappingOption.class );\n\t\tif ( mappingOption == null ) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// wrong type would be a programming error of the annotation developer\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tClass<? extends AnnotationConverter<A>> converterClass = (Class<? extends AnnotationConverter<A>>) mappingOption.value();\n\n\t\ttry {\n\t\t\treturn converterClass.newInstance();\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tthrow log.cannotConvertAnnotation( converterClass, e );\n\t\t}\n\t}",
"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 static base_responses update(nitro_service client, nspbr6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnspbr6 updateresources[] = new nspbr6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nspbr6();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].action = resources[i].action;\n\t\t\t\tupdateresources[i].srcipv6 = resources[i].srcipv6;\n\t\t\t\tupdateresources[i].srcipop = resources[i].srcipop;\n\t\t\t\tupdateresources[i].srcipv6val = resources[i].srcipv6val;\n\t\t\t\tupdateresources[i].srcport = resources[i].srcport;\n\t\t\t\tupdateresources[i].srcportop = resources[i].srcportop;\n\t\t\t\tupdateresources[i].srcportval = resources[i].srcportval;\n\t\t\t\tupdateresources[i].destipv6 = resources[i].destipv6;\n\t\t\t\tupdateresources[i].destipop = resources[i].destipop;\n\t\t\t\tupdateresources[i].destipv6val = resources[i].destipv6val;\n\t\t\t\tupdateresources[i].destport = resources[i].destport;\n\t\t\t\tupdateresources[i].destportop = resources[i].destportop;\n\t\t\t\tupdateresources[i].destportval = resources[i].destportval;\n\t\t\t\tupdateresources[i].srcmac = resources[i].srcmac;\n\t\t\t\tupdateresources[i].protocol = resources[i].protocol;\n\t\t\t\tupdateresources[i].protocolnumber = resources[i].protocolnumber;\n\t\t\t\tupdateresources[i].vlan = resources[i].vlan;\n\t\t\t\tupdateresources[i].Interface = resources[i].Interface;\n\t\t\t\tupdateresources[i].priority = resources[i].priority;\n\t\t\t\tupdateresources[i].msr = resources[i].msr;\n\t\t\t\tupdateresources[i].monitor = resources[i].monitor;\n\t\t\t\tupdateresources[i].nexthop = resources[i].nexthop;\n\t\t\t\tupdateresources[i].nexthopval = resources[i].nexthopval;\n\t\t\t\tupdateresources[i].nexthopvlan = resources[i].nexthopvlan;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public MediaType copyQualityValue(MediaType mediaType) {\n\t\tif (!mediaType.parameters.containsKey(PARAM_QUALITY_FACTOR)) {\n\t\t\treturn this;\n\t\t}\n\t\tMap<String, String> params = new LinkedHashMap<String, String>(this.parameters);\n\t\tparams.put(PARAM_QUALITY_FACTOR, mediaType.parameters.get(PARAM_QUALITY_FACTOR));\n\t\treturn new MediaType(this, params);\n\t}",
"public static boolean isTypeManagedBeanOrDecoratorOrInterceptor(AnnotatedType<?> annotatedType) {\n Class<?> javaClass = annotatedType.getJavaClass();\n return !javaClass.isEnum() && !Extension.class.isAssignableFrom(javaClass)\n && Reflections.isTopLevelOrStaticNestedClass(javaClass) && !Reflections.isParameterizedTypeWithWildcard(javaClass)\n && hasSimpleCdiConstructor(annotatedType);\n }",
"public static base_responses unset(nitro_service client, gslbservice resources[], String[] args) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tgslbservice unsetresources[] = new gslbservice[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tunsetresources[i] = new gslbservice();\n\t\t\t\tunsetresources[i].servicename = resources[i].servicename;\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}"
] |
Determine whether the given element matches this element.
An element matches this element when keys are equal, values are equal
or this element value is a wildcard.
@param pe the element to check
@return {@code true} if the element matches | [
"public boolean matches(PathElement pe) {\n return pe.key.equals(key) && (isWildcard() || pe.value.equals(value));\n }"
] | [
"public static void changeSign(DMatrixSparseCSC A , DMatrixSparseCSC B ) {\n if( A != B ) {\n B.copyStructure(A);\n }\n\n for (int i = 0; i < A.nz_length; i++) {\n B.nz_values[i] = -A.nz_values[i];\n }\n }",
"public static vpnsessionaction[] get(nitro_service service) throws Exception{\n\t\tvpnsessionaction obj = new vpnsessionaction();\n\t\tvpnsessionaction[] response = (vpnsessionaction[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static boolean isLogDownloadAvailable(CliGuiContext cliGuiCtx) {\n ModelNode readOps = null;\n try {\n readOps = cliGuiCtx.getExecutor().doCommand(\"/subsystem=logging:read-children-types\");\n } catch (CommandFormatException | IOException e) {\n return false;\n }\n if (!readOps.get(\"result\").isDefined()) return false;\n for (ModelNode op: readOps.get(\"result\").asList()) {\n if (\"log-file\".equals(op.asString())) return true;\n }\n return false;\n }",
"private String fixApiDocRoot(String str) {\n\tif (str == null)\n\t return null;\n\tString fixed = str.trim();\n\tif (fixed.isEmpty())\n\t return \"\";\n\tif (File.separatorChar != '/')\n\t fixed = fixed.replace(File.separatorChar, '/');\n\tif (!fixed.endsWith(\"/\"))\n\t fixed = fixed + \"/\";\n\treturn fixed;\n }",
"private double getExpectedProbability(double x)\n {\n double y = 1 / (standardDeviation * Math.sqrt(Math.PI * 2));\n double z = -(Math.pow(x - mean, 2) / (2 * Math.pow(standardDeviation, 2)));\n return y * Math.exp(z);\n }",
"public ItemRequest<Section> findById(String section) {\n \n String path = String.format(\"/sections/%s\", section);\n return new ItemRequest<Section>(this, Section.class, path, \"GET\");\n }",
"@Override\n\tpublic Iterator<? extends IPAddressSeqRange> prefixIterator(int prefixLength) {\n\t\tif(!isMultiple()) {\n\t\t\treturn new Iterator<IPAddressSeqRange>() {\n\t\t\t\tIPAddressSeqRange orig = IPAddressSeqRange.this;\n\n\t\t\t\t@Override\n\t\t\t\tpublic boolean hasNext() {\n\t\t\t\t\treturn orig != null;\n\t\t\t\t}\n\n\t\t\t @Override\n\t\t\t\tpublic IPAddressSeqRange next() {\n\t\t\t \tif(orig == null) {\n\t\t\t \t\tthrow new NoSuchElementException();\n\t\t\t \t}\n\t\t\t \tIPAddressSeqRange result = orig;\n\t\t\t \torig = null;\n\t\t\t \treturn result;\n\t\t\t }\n\t\t\t\n\t\t\t @Override\n\t\t\t\tpublic void remove() {\n\t\t\t \tthrow new UnsupportedOperationException();\n\t\t\t }\n\t\t\t};\n\t\t}\n\t\treturn new Iterator<IPAddressSeqRange>() {\n\t\t\tIterator<? extends IPAddress> prefixBlockIterator = prefixBlockIterator(prefixLength);\n\t\t\tprivate boolean first = true;\n\n\t\t\t@Override\n\t\t\tpublic boolean hasNext() {\n\t\t\t\treturn prefixBlockIterator.hasNext();\n\t\t\t}\n\n\t\t @Override\n\t\t\tpublic IPAddressSeqRange next() {\n\t\t \tIPAddress next = prefixBlockIterator.next();\n\t\t \tif(first) {\n\t\t \t\tfirst = false;\n\t\t \t\t// next is a prefix block\n\t\t \t\tIPAddress lower = getLower();\n\t\t \t\tif(hasNext()) {\n\t\t\t \t\tif(!lower.includesZeroHost(prefixLength)) {\n\t\t\t \t\t\treturn create(lower, next.getUpper());\n\t\t\t \t\t}\n\t\t \t\t} else {\n\t\t \t\t\tIPAddress upper = getUpper();\n\t\t \t\t\tif(!lower.includesZeroHost(prefixLength) || !upper.includesMaxHost(prefixLength)) {\n\t\t \t\t\t\treturn create(lower, upper);\n\t\t \t\t\t}\n\t\t \t\t}\n\t\t \t} else if(!hasNext()) {\n\t\t \t\tIPAddress upper = getUpper();\n\t\t \t\tif(!upper.includesMaxHost(prefixLength)) {\n\t\t \t\t\treturn create(next.getLower(), upper);\n\t\t \t\t}\n\t\t \t}\n\t\t \treturn next.toSequentialRange();\n\t\t }\n\t\t\n\t\t @Override\n\t\t\tpublic void remove() {\n\t\t \tthrow new UnsupportedOperationException();\n\t\t }\n\t\t};\n\t}",
"public int[] getPositions() {\n int[] list;\n if (assumeSinglePosition) {\n list = new int[1];\n list[0] = super.startPosition();\n return list;\n } else {\n try {\n processEncodedPayload();\n list = mtasPosition.getPositions();\n if (list != null) {\n return mtasPosition.getPositions();\n }\n } catch (IOException e) {\n log.debug(e);\n // do nothing\n }\n int start = super.startPosition();\n int end = super.endPosition();\n list = new int[end - start];\n for (int i = start; i < end; i++)\n list[i - start] = i;\n return list;\n }\n }",
"public static locationfile get(nitro_service service) throws Exception{\n\t\tlocationfile obj = new locationfile();\n\t\tlocationfile[] response = (locationfile[])obj.get_resources(service);\n\t\treturn response[0];\n\t}"
] |
Sends a multipart response. Each body part represents a versioned value
of the given key.
@throws IOException
@throws MessagingException | [
"@Override\n public void sendResponse(StoreStats performanceStats,\n boolean isFromLocalZone,\n long startTimeInMs) throws Exception {\n\n /*\n * Pay attention to the code below. Note that in this method we wrap a multiPart object with a mimeMessage.\n * However when writing to the outputStream we only send the multiPart object and not the entire\n * mimeMessage. This is intentional.\n *\n * In the earlier version of this code we used to create a multiPart object and just send that multiPart\n * across the wire.\n *\n * However, we later discovered that upon setting the content of a MimeBodyPart, JavaMail internally creates\n * a DataHandler object wrapping the object you passed in. The part's Content-Type header is not updated\n * immediately. In order to get the headers updated, one needs to to call MimeMessage.saveChanges() on the\n * enclosing message, which cascades down the MIME structure into a call to MimeBodyPart.updateHeaders()\n * on the body part. It's this updateHeaders call that transfers the content type from the\n * DataHandler to the part's MIME Content-Type header.\n *\n * To make sure that the Content-Type headers are being updated (without changing too much code), we decided\n * to wrap the multiPart in a mimeMessage, call mimeMessage.saveChanges() and then just send the multiPart.\n * This is to make sure multiPart's headers are updated accurately.\n */\n\n MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));\n MimeMultipart multiPart = new MimeMultipart();\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\n String base64Key = RestUtils.encodeVoldemortKey(key.get());\n String contentLocationKey = \"/\" + this.storeName + \"/\" + base64Key;\n\n for(Versioned<byte[]> versionedValue: versionedValues) {\n\n byte[] responseValue = versionedValue.getValue();\n\n VectorClock vectorClock = (VectorClock) versionedValue.getVersion();\n String eTag = RestUtils.getSerializedVectorClock(vectorClock);\n numVectorClockEntries += vectorClock.getVersionMap().size();\n\n // Create the individual body part for each versioned value of the\n // requested key\n MimeBodyPart body = new MimeBodyPart();\n try {\n // Add the right headers\n body.addHeader(CONTENT_TYPE, \"application/octet-stream\");\n body.addHeader(CONTENT_TRANSFER_ENCODING, \"binary\");\n body.addHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK, eTag);\n body.setContent(responseValue, \"application/octet-stream\");\n body.addHeader(RestMessageHeaders.CONTENT_LENGTH,\n Integer.toString(responseValue.length));\n\n multiPart.addBodyPart(body);\n } catch(MessagingException me) {\n logger.error(\"Exception while constructing body part\", me);\n outputStream.close();\n throw me;\n }\n\n }\n message.setContent(multiPart);\n message.saveChanges();\n try {\n multiPart.writeTo(outputStream);\n } catch(Exception e) {\n logger.error(\"Exception while writing multipart to output stream\", e);\n outputStream.close();\n throw e;\n }\n ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer();\n responseContent.writeBytes(outputStream.toByteArray());\n\n // Create the Response object\n HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);\n\n // Set the right headers\n response.setHeader(CONTENT_TYPE, \"multipart/binary\");\n response.setHeader(CONTENT_TRANSFER_ENCODING, \"binary\");\n response.setHeader(CONTENT_LOCATION, contentLocationKey);\n\n // Copy the data into the payload\n response.setContent(responseContent);\n response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());\n\n // Write the response to the Netty Channel\n if(logger.isDebugEnabled()) {\n String keyStr = RestUtils.getKeyHexString(this.key);\n debugLog(\"GET\",\n this.storeName,\n keyStr,\n startTimeInMs,\n System.currentTimeMillis(),\n numVectorClockEntries);\n }\n this.messageEvent.getChannel().write(response);\n\n if(performanceStats != null && isFromLocalZone) {\n recordStats(performanceStats, startTimeInMs, Tracked.GET);\n }\n\n outputStream.close();\n\n }"
] | [
"public static void addHeaders(BoundRequestBuilder builder,\n Map<String, String> headerMap) {\n for (Entry<String, String> entry : headerMap.entrySet()) {\n String name = entry.getKey();\n String value = entry.getValue();\n builder.addHeader(name, value);\n }\n\n }",
"public void setTotalColorForColumn(int column, Color color){\r\n\t\tint map = (colors.length-1) - column;\r\n\t\tcolors[map][colors[0].length-1]=color;\r\n\t}",
"protected String getQueryModifier() {\n\n String queryModifier = parseOptionalStringValue(m_configObject, JSON_KEY_QUERY_MODIFIER);\n return (null == queryModifier) && (null != m_baseConfig)\n ? m_baseConfig.getGeneralConfig().getQueryModifier()\n : queryModifier;\n }",
"public static base_response unset(nitro_service client, csparameter resource, String[] args) throws Exception{\n\t\tcsparameter unsetresource = new csparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public static auditsyslogpolicy_lbvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditsyslogpolicy_lbvserver_binding obj = new auditsyslogpolicy_lbvserver_binding();\n\t\tobj.set_name(name);\n\t\tauditsyslogpolicy_lbvserver_binding response[] = (auditsyslogpolicy_lbvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static base_response flush(nitro_service client, cacheobject resource) throws Exception {\n\t\tcacheobject flushresource = new cacheobject();\n\t\tflushresource.locator = resource.locator;\n\t\tflushresource.url = resource.url;\n\t\tflushresource.host = resource.host;\n\t\tflushresource.port = resource.port;\n\t\tflushresource.groupname = resource.groupname;\n\t\tflushresource.httpmethod = resource.httpmethod;\n\t\tflushresource.force = resource.force;\n\t\treturn flushresource.perform_operation(client,\"flush\");\n\t}",
"public AreaOfInterest copy() {\n AreaOfInterest aoi = new AreaOfInterest();\n aoi.display = this.display;\n aoi.area = this.area;\n aoi.polygon = this.polygon;\n aoi.style = this.style;\n aoi.renderAsSvg = this.renderAsSvg;\n return aoi;\n }",
"public <A extends Collection<? super ResultT>> A into(final A target) {\n forEach(new Block<ResultT>() {\n @Override\n public void apply(@Nonnull final ResultT t) {\n target.add(t);\n }\n });\n return target;\n }",
"public int numOccurrences(int year, int month, int day) {\n DateTimeFormatter parser = ISODateTimeFormat.date();\n DateTime date = parser.parseDateTime(year + \"-\" + month + \"-\" + \"01\");\n Calendar cal = Calendar.getInstance();\n cal.setTime(date.toDate());\n GregorianChronology calendar = GregorianChronology.getInstance();\n DateTimeField field = calendar.dayOfMonth();\n\n int days = 0;\n int count = 0;\n int num = field.getMaximumValue(new LocalDate(year, month, day, calendar));\n while (days < num) {\n if (cal.get(Calendar.DAY_OF_WEEK) == day) {\n count++;\n }\n date = date.plusDays(1);\n cal.setTime(date.toDate());\n\n days++;\n }\n return count;\n }"
] |
Extract information from a resource ID string with the resource type
as the identifier.
@param id the resource ID
@param identifier the identifier to match, e.g. "resourceGroups", "storageAccounts"
@return the information extracted from the identifier | [
"public static String extractFromResourceId(String id, String identifier) {\n if (id == null || identifier == null) {\n return id;\n }\n Pattern pattern = Pattern.compile(identifier + \"/[-\\\\w._]+\");\n Matcher matcher = pattern.matcher(id);\n if (matcher.find()) {\n return matcher.group().split(\"/\")[1];\n } else {\n return null;\n }\n }"
] | [
"public void setRightValue(int index, Object value)\n {\n m_definedRightValues[index] = value;\n\n if (value instanceof FieldType)\n {\n m_symbolicValues = true;\n }\n else\n {\n if (value instanceof Duration)\n {\n if (((Duration) value).getUnits() != TimeUnit.HOURS)\n {\n value = ((Duration) value).convertUnits(TimeUnit.HOURS, m_properties);\n }\n }\n }\n\n m_workingRightValues[index] = value;\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 static base_response restart(nitro_service client) throws Exception {\n\t\tdbsmonitors restartresource = new dbsmonitors();\n\t\treturn restartresource.perform_operation(client,\"restart\");\n\t}",
"private void saveLocalization() {\n\n SortedProperties localization = new SortedProperties();\n for (Object itemId : m_container.getItemIds()) {\n Item item = m_container.getItem(itemId);\n String key = item.getItemProperty(TableProperty.KEY).getValue().toString();\n String value = item.getItemProperty(TableProperty.TRANSLATION).getValue().toString();\n if (!(key.isEmpty() || value.isEmpty())) {\n localization.put(key, value);\n }\n }\n m_keyset.updateKeySet(m_localizations.get(m_locale).keySet(), localization.keySet());\n m_localizations.put(m_locale, localization);\n\n }",
"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 }",
"public final void setExceptions(SortedSet<Date> dates) {\n\n m_exceptions.clear();\n if (null != dates) {\n m_exceptions.addAll(dates);\n }\n\n }",
"private Component createAddKeyButton() {\n\n // the \"+\" button\n Button addKeyButton = new Button();\n addKeyButton.addStyleName(\"icon-only\");\n addKeyButton.addStyleName(\"borderless-colored\");\n addKeyButton.setDescription(m_messages.key(Messages.GUI_ADD_KEY_0));\n addKeyButton.setIcon(FontOpenCms.CIRCLE_PLUS, m_messages.key(Messages.GUI_ADD_KEY_0));\n addKeyButton.addClickListener(new ClickListener() {\n\n private static final long serialVersionUID = 1L;\n\n public void buttonClick(ClickEvent event) {\n\n handleAddKey();\n\n }\n });\n return addKeyButton;\n }",
"protected InputStream getCompressorInputStream(InputStream inputStream,\n\t\t\tCompressionType compressionType) throws IOException {\n\t\tswitch (compressionType) {\n\t\tcase NONE:\n\t\t\treturn inputStream;\n\t\tcase GZIP:\n\t\t\treturn new GZIPInputStream(inputStream);\n\t\tcase BZ2:\n\t\t\treturn new BZip2CompressorInputStream(new BufferedInputStream(\n\t\t\t\t\tinputStream));\n\t\tdefault:\n\t\t\tthrow new IllegalArgumentException(\"Unsupported compression type: \"\n\t\t\t\t\t+ compressionType);\n\t\t}\n\t}",
"public T[] toArray(T[] tArray) {\n List<T> array = new ArrayList<T>(100);\n for (Iterator<T> it = iterator(); it.hasNext();) {\n T val = it.next();\n if (val != null) array.add(val);\n }\n return array.toArray(tArray);\n }"
] |
Use this API to fetch a sslglobal_sslpolicy_binding resources. | [
"public static sslglobal_sslpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tsslglobal_sslpolicy_binding obj = new sslglobal_sslpolicy_binding();\n\t\tsslglobal_sslpolicy_binding response[] = (sslglobal_sslpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"private void handleUpdate(final CdjStatus update) {\n // First see if any metadata caches need evicting or mount sets need updating.\n if (update.isLocalUsbEmpty()) {\n final SlotReference slot = SlotReference.getSlotReference(update.getDeviceNumber(), CdjStatus.TrackSourceSlot.USB_SLOT);\n detachMetadataCache(slot);\n flushHotCacheSlot(slot);\n removeMount(slot);\n } else if (update.isLocalUsbLoaded()) {\n recordMount(SlotReference.getSlotReference(update.getDeviceNumber(), CdjStatus.TrackSourceSlot.USB_SLOT));\n }\n\n if (update.isLocalSdEmpty()) {\n final SlotReference slot = SlotReference.getSlotReference(update.getDeviceNumber(), CdjStatus.TrackSourceSlot.SD_SLOT);\n detachMetadataCache(slot);\n flushHotCacheSlot(slot);\n removeMount(slot);\n } else if (update.isLocalSdLoaded()){\n recordMount(SlotReference.getSlotReference(update.getDeviceNumber(), CdjStatus.TrackSourceSlot.SD_SLOT));\n }\n\n if (update.isDiscSlotEmpty()) {\n removeMount(SlotReference.getSlotReference(update.getDeviceNumber(), CdjStatus.TrackSourceSlot.CD_SLOT));\n } else {\n recordMount(SlotReference.getSlotReference(update.getDeviceNumber(), CdjStatus.TrackSourceSlot.CD_SLOT));\n }\n\n // Now see if a track has changed that needs new metadata.\n if (update.getTrackType() == CdjStatus.TrackType.UNKNOWN ||\n update.getTrackType() == CdjStatus.TrackType.NO_TRACK ||\n update.getTrackSourceSlot() == CdjStatus.TrackSourceSlot.NO_TRACK ||\n update.getTrackSourceSlot() == CdjStatus.TrackSourceSlot.UNKNOWN ||\n update.getRekordboxId() == 0) { // We no longer have metadata for this device.\n clearDeck(update);\n } else { // We can offer metadata for this device; check if we already looked up this track.\n final TrackMetadata lastMetadata = hotCache.get(DeckReference.getDeckReference(update.getDeviceNumber(), 0));\n final DataReference trackReference = new DataReference(update.getTrackSourcePlayer(),\n update.getTrackSourceSlot(), update.getRekordboxId());\n if (lastMetadata == null || !lastMetadata.trackReference.equals(trackReference)) { // We have something new!\n // First see if we can find the new track in the hot cache as a hot cue\n for (TrackMetadata cached : hotCache.values()) {\n if (cached.trackReference.equals(trackReference)) { // Found a hot cue hit, use it.\n updateMetadata(update, cached);\n return;\n }\n }\n\n // Not in the hot cache so try actually retrieving it.\n if (activeRequests.add(update.getTrackSourcePlayer())) {\n // We had to make sure we were not already asking for this track.\n clearDeck(update); // We won't know what it is until our request completes.\n new Thread(new Runnable() {\n @Override\n public void run() {\n try {\n TrackMetadata data = requestMetadataInternal(trackReference, update.getTrackType(), true);\n if (data != null) {\n updateMetadata(update, data);\n }\n } catch (Exception e) {\n logger.warn(\"Problem requesting track metadata from update\" + update, e);\n } finally {\n activeRequests.remove(update.getTrackSourcePlayer());\n }\n }\n }, \"MetadataFinder metadata request\").start();\n }\n }\n }\n }",
"public void loadProfile(Object key)\r\n {\r\n if (!isEnablePerThreadChanges())\r\n {\r\n throw new MetadataException(\"Can not load profile with disabled per thread mode\");\r\n }\r\n DescriptorRepository rep = (DescriptorRepository) metadataProfiles.get(key);\r\n if (rep == null)\r\n {\r\n throw new MetadataException(\"Can not find profile for key '\" + key + \"'\");\r\n }\r\n currentProfileKey.set(key);\r\n setDescriptor(rep);\r\n }",
"public static final GVRPickedObject[] pickVisible(GVRScene scene) {\n sFindObjectsLock.lock();\n try {\n final GVRPickedObject[] result = NativePicker.pickVisible(scene.getNative());\n return result;\n } finally {\n sFindObjectsLock.unlock();\n }\n }",
"public static float noise2(float x, float y) {\n int bx0, bx1, by0, by1, b00, b10, b01, b11;\n float rx0, rx1, ry0, ry1, q[], sx, sy, a, b, t, u, v;\n int i, j;\n\n if (start) {\n start = false;\n init();\n }\n\n t = x + N;\n bx0 = ((int)t) & BM;\n bx1 = (bx0+1) & BM;\n rx0 = t - (int)t;\n rx1 = rx0 - 1.0f;\n\n t = y + N;\n by0 = ((int)t) & BM;\n by1 = (by0+1) & BM;\n ry0 = t - (int)t;\n ry1 = ry0 - 1.0f;\n\n i = p[bx0];\n j = p[bx1];\n\n b00 = p[i + by0];\n b10 = p[j + by0];\n b01 = p[i + by1];\n b11 = p[j + by1];\n\n sx = sCurve(rx0);\n sy = sCurve(ry0);\n\n q = g2[b00]; u = rx0 * q[0] + ry0 * q[1];\n q = g2[b10]; v = rx1 * q[0] + ry0 * q[1];\n a = lerp(sx, u, v);\n\n q = g2[b01]; u = rx0 * q[0] + ry1 * q[1];\n q = g2[b11]; v = rx1 * q[0] + ry1 * q[1];\n b = lerp(sx, u, v);\n\n return 1.5f*lerp(sy, a, b);\n }",
"public static final long getLong(byte[] data, int offset)\n {\n long result = 0;\n int i = offset;\n for (int shiftBy = 0; shiftBy < 64; shiftBy += 8)\n {\n result |= ((long) (data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }",
"public static Class<?> resolvePrimitiveIfNecessary(Class<?> clazz) {\n\t\tAssert.notNull(clazz, \"Class must not be null\");\n\t\treturn (clazz.isPrimitive() && clazz != void.class? primitiveTypeToWrapperMap.get(clazz) : clazz);\n\t}",
"public void process(DirectoryEntry projectDir, ProjectFile file, DocumentInputStreamFactory inputStreamFactory) throws IOException\n {\n DirectoryEntry consDir;\n try\n {\n consDir = (DirectoryEntry) projectDir.getEntry(\"TBkndCons\");\n }\n\n catch (FileNotFoundException ex)\n {\n consDir = null;\n }\n\n if (consDir != null)\n {\n FixedMeta consFixedMeta = new FixedMeta(new DocumentInputStream(((DocumentEntry) consDir.getEntry(\"FixedMeta\"))), 10);\n FixedData consFixedData = new FixedData(consFixedMeta, 20, inputStreamFactory.getInstance(consDir, \"FixedData\"));\n // FixedMeta consFixed2Meta = new FixedMeta(new DocumentInputStream(((DocumentEntry) consDir.getEntry(\"Fixed2Meta\"))), 9);\n // FixedData consFixed2Data = new FixedData(consFixed2Meta, 48, getEncryptableInputStream(consDir, \"Fixed2Data\"));\n\n int count = consFixedMeta.getAdjustedItemCount();\n int lastConstraintID = -1;\n\n ProjectProperties properties = file.getProjectProperties();\n EventManager eventManager = file.getEventManager();\n\n boolean project15 = NumberHelper.getInt(properties.getMppFileType()) == 14 && NumberHelper.getInt(properties.getApplicationVersion()) > ApplicationVersion.PROJECT_2010;\n int durationUnitsOffset = project15 ? 18 : 14;\n int durationOffset = project15 ? 14 : 16;\n\n for (int loop = 0; loop < count; loop++)\n {\n byte[] metaData = consFixedMeta.getByteArrayValue(loop);\n\n //\n // SourceForge bug 2209477: we were reading an int here, but\n // it looks like the deleted flag is just a short.\n //\n if (MPPUtility.getShort(metaData, 0) != 0)\n {\n continue;\n }\n\n int index = consFixedData.getIndexFromOffset(MPPUtility.getInt(metaData, 4));\n if (index == -1)\n {\n continue;\n }\n\n //\n // Do we have enough data?\n //\n byte[] data = consFixedData.getByteArrayValue(index);\n if (data.length < 14)\n {\n continue;\n }\n\n int constraintID = MPPUtility.getInt(data, 0);\n if (constraintID <= lastConstraintID)\n {\n continue;\n }\n\n lastConstraintID = constraintID;\n int taskID1 = MPPUtility.getInt(data, 4);\n int taskID2 = MPPUtility.getInt(data, 8);\n\n if (taskID1 == taskID2)\n {\n continue;\n }\n\n // byte[] metaData2 = consFixed2Meta.getByteArrayValue(loop);\n // int index2 = consFixed2Data.getIndexFromOffset(MPPUtility.getInt(metaData2, 4));\n // byte[] data2 = consFixed2Data.getByteArrayValue(index2);\n\n Task task1 = file.getTaskByUniqueID(Integer.valueOf(taskID1));\n Task task2 = file.getTaskByUniqueID(Integer.valueOf(taskID2));\n if (task1 != null && task2 != null)\n {\n RelationType type = RelationType.getInstance(MPPUtility.getShort(data, 12));\n TimeUnit durationUnits = MPPUtility.getDurationTimeUnits(MPPUtility.getShort(data, durationUnitsOffset));\n Duration lag = MPPUtility.getAdjustedDuration(properties, MPPUtility.getInt(data, durationOffset), durationUnits);\n Relation relation = task2.addPredecessor(task1, type, lag);\n relation.setUniqueID(Integer.valueOf(constraintID));\n eventManager.fireRelationReadEvent(relation);\n }\n }\n }\n }",
"public void addRoute(String path, Class<? extends Actor> actorClass) throws RouteAlreadyMappedException {\n addRoute(new Route(path, false), actorClass);\n }",
"public static base_response unset(nitro_service client, snmpalarm resource, String[] args) throws Exception{\n\t\tsnmpalarm unsetresource = new snmpalarm();\n\t\tunsetresource.trapname = resource.trapname;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}"
] |
Use this API to unset the properties of sslcertkey resource.
Properties that need to be unset are specified in args array. | [
"public static base_response unset(nitro_service client, sslcertkey resource, String[] args) throws Exception{\n\t\tsslcertkey unsetresource = new sslcertkey();\n\t\tunsetresource.certkey = resource.certkey;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}"
] | [
"public static nspbr6_stats get(nitro_service service, String name) throws Exception{\n\t\tnspbr6_stats obj = new nspbr6_stats();\n\t\tobj.set_name(name);\n\t\tnspbr6_stats response = (nspbr6_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"public static Properties getProps(Properties props, String name, Properties defaultProperties) {\n final String propString = props.getProperty(name);\n if (propString == null) return defaultProperties;\n String[] propValues = propString.split(\",\");\n if (propValues.length < 1) {\n throw new IllegalArgumentException(\"Illegal format of specifying properties '\" + propString + \"'\");\n }\n Properties properties = new Properties();\n for (int i = 0; i < propValues.length; i++) {\n String[] prop = propValues[i].split(\"=\");\n if (prop.length != 2) throw new IllegalArgumentException(\"Illegal format of specifying properties '\" + propValues[i] + \"'\");\n properties.put(prop[0], prop[1]);\n }\n return properties;\n }",
"public void mark() {\n final long currentTimeMillis = clock.currentTimeMillis();\n\n synchronized (queue) {\n if (queue.size() == capacity) {\n /*\n * we're all filled up already, let's dequeue the oldest\n * timestamp to make room for this new one.\n */\n queue.removeFirst();\n }\n queue.addLast(currentTimeMillis);\n }\n }",
"public List<MapRow> readTableConditional(Class<? extends TableReader> readerClass) throws IOException\n {\n List<MapRow> result;\n if (DatatypeConverter.getBoolean(m_stream))\n {\n result = readTable(readerClass);\n }\n else\n {\n result = Collections.emptyList();\n }\n return result;\n }",
"private FormInput formInputMatchingNode(Node element) {\n\t\tNamedNodeMap attributes = element.getAttributes();\n\t\tIdentification id;\n\n\t\tif (attributes.getNamedItem(\"id\") != null\n\t\t\t\t&& formFillMode != FormFillMode.XPATH_TRAINING) {\n\t\t\tid = new Identification(Identification.How.id,\n\t\t\t\t\tattributes.getNamedItem(\"id\").getNodeValue());\n\t\t\tFormInput input = this.formInputs.get(id);\n\t\t\tif (input != null) {\n\t\t\t\treturn input;\n\t\t\t}\n\t\t}\n\n\t\tif (attributes.getNamedItem(\"name\") != null\n\t\t\t\t&& formFillMode != FormFillMode.XPATH_TRAINING) {\n\t\t\tid = new Identification(Identification.How.name,\n\t\t\t\t\tattributes.getNamedItem(\"name\").getNodeValue());\n\t\t\tFormInput input = this.formInputs.get(id);\n\t\t\tif (input != null) {\n\t\t\t\treturn input;\n\t\t\t}\n\t\t}\n\n\t\tString xpathExpr = XPathHelper.getXPathExpression(element);\n\t\tif (xpathExpr != null && !xpathExpr.equals(\"\")) {\n\t\t\tid = new Identification(Identification.How.xpath, xpathExpr);\n\t\t\tFormInput input = this.formInputs.get(id);\n\t\t\tif (input != null) {\n\t\t\t\treturn input;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}",
"private long getTotalTime(ProjectCalendarDateRanges exception, Date date, boolean after)\n {\n long currentTime = DateHelper.getCanonicalTime(date).getTime();\n long total = 0;\n for (DateRange range : exception)\n {\n total += getTime(range.getStart(), range.getEnd(), currentTime, after);\n }\n return (total);\n }",
"private void updateArt(TrackMetadataUpdate update, AlbumArt art) {\n hotCache.put(DeckReference.getDeckReference(update.player, 0), art); // 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 hotCache.put(DeckReference.getDeckReference(update.player, entry.hotCueNumber), art);\n }\n }\n }\n deliverAlbumArtUpdate(update.player, art);\n }",
"public synchronized int getPartitionStoreCount() {\n int count = 0;\n for (String store : storeToPartitionIds.keySet()) {\n count += storeToPartitionIds.get(store).size();\n }\n return count;\n }",
"@Pure\n\tpublic static <P1, P2, RESULT> Function1<P2, RESULT> curry(final Function2<? super P1, ? super P2, ? extends RESULT> function,\n\t\t\tfinal P1 argument) {\n\t\tif (function == null)\n\t\t\tthrow new NullPointerException(\"function\");\n\t\treturn new Function1<P2, RESULT>() {\n\t\t\t@Override\n\t\t\tpublic RESULT apply(P2 p) {\n\t\t\t\treturn function.apply(argument, p);\n\t\t\t}\n\t\t};\n\t}"
] |
Methods returns InetAddress for localhost
@return InetAddress of the localhost
@throws UnknownHostException if localhost could not be resolved | [
"public static InetAddress getLocalHost() throws UnknownHostException {\n InetAddress addr;\n try {\n addr = InetAddress.getLocalHost();\n } catch (ArrayIndexOutOfBoundsException e) { //this is workaround for mac osx bug see AS7-3223 and JGRP-1404\n addr = InetAddress.getByName(null);\n }\n return addr;\n }"
] | [
"public static void show(DMatrixD1 A , String title ) {\n JFrame frame = new JFrame(title);\n\n int width = 300;\n int height = 300;\n\n if( A.numRows > A.numCols) {\n width = width*A.numCols/A.numRows;\n } else {\n height = height*A.numRows/A.numCols;\n }\n\n DMatrixComponent panel = new DMatrixComponent(width,height);\n panel.setMatrix(A);\n\n frame.add(panel, BorderLayout.CENTER);\n\n frame.pack();\n frame.setVisible(true);\n\n }",
"public static Artifact getIdlArtifact(Artifact artifact, ArtifactFactory artifactFactory,\n ArtifactResolver artifactResolver,\n ArtifactRepository localRepository,\n List<ArtifactRepository> remoteRepos,\n String classifier)\n throws MojoExecutionException {\n Artifact idlArtifact = artifactFactory.createArtifactWithClassifier(\n artifact.getGroupId(),\n artifact.getArtifactId(),\n artifact.getVersion(),\n \"jar\",\n classifier);\n try {\n artifactResolver.resolve(idlArtifact, remoteRepos, localRepository);\n return idlArtifact;\n } catch (final ArtifactResolutionException e) {\n throw new MojoExecutionException(\n \"Failed to resolve one or more idl artifacts:\\n\\n\" + e.getMessage(), e);\n } catch (final ArtifactNotFoundException e) {\n throw new MojoExecutionException(\n \"Failed to resolve one or more idl artifacts:\\n\\n\" + e.getMessage(), e);\n }\n }",
"void checkRmModelConformance() {\n final AmVisitor<AmObject, AmConstraintContext> visitor = AmVisitors.preorder(new ConformanceVisitor());\n ArchetypeWalker.walkConstraints(visitor, archetype, new AmConstraintContext());\n }",
"public static <T> Collection<MemberResponse<T>> executeOptimistic(IExecutorService execSvc, Set<Member> members, Callable<T> callable) {\n \treturn executeOptimistic(execSvc, members, callable, 60, TimeUnit.SECONDS);\n }",
"private void logRequestHistory(HttpMethod httpMethodProxyRequest, PluginResponse httpServletResponse,\n History history) {\n try {\n if (requestInformation.get().handle && requestInformation.get().client.getIsActive()) {\n logger.info(\"Storing history\");\n String createdDate;\n SimpleDateFormat sdf = new SimpleDateFormat();\n sdf.setTimeZone(new SimpleTimeZone(0, \"GMT\"));\n sdf.applyPattern(\"dd MMM yyyy HH:mm:ss\");\n createdDate = sdf.format(new Date()) + \" GMT\";\n\n history.setCreatedAt(createdDate);\n history.setRequestURL(HttpUtilities.getURL(httpMethodProxyRequest.getURI().toString()));\n history.setRequestParams(httpMethodProxyRequest.getQueryString() == null ? \"\"\n : httpMethodProxyRequest.getQueryString());\n history.setRequestHeaders(HttpUtilities.getHeaders(httpMethodProxyRequest));\n history.setResponseHeaders(HttpUtilities.getHeaders(httpServletResponse));\n history.setResponseCode(Integer.toString(httpServletResponse.getStatus()));\n history.setResponseContentType(httpServletResponse.getContentType());\n history.setResponseData(httpServletResponse.getContentString());\n history.setResponseBodyDecoded(httpServletResponse.isContentDecoded());\n HistoryService.getInstance().addHistory(history);\n logger.info(\"Done storing\");\n }\n } catch (URIException e) {\n e.printStackTrace();\n }\n }",
"public static void addHeaders(BoundRequestBuilder builder,\n Map<String, String> headerMap) {\n for (Entry<String, String> entry : headerMap.entrySet()) {\n String name = entry.getKey();\n String value = entry.getValue();\n builder.addHeader(name, value);\n }\n\n }",
"public static URL asUrlOrResource(String s) {\n if (Strings.isNullOrEmpty(s)) {\n return null;\n }\n\n try {\n return new URL(s);\n } catch (MalformedURLException e) {\n //If its not a valid URL try to treat it as a local resource.\n return findConfigResource(s);\n }\n }",
"public List<DbMigration> getMigrationsSinceVersion(int version) {\n List<DbMigration> dbMigrations = new ArrayList<>();\n migrationScripts.stream().filter(script -> script.getVersion() > version).forEach(script -> {\n String content = loadScriptContent(script);\n dbMigrations.add(new DbMigration(script.getScriptName(), script.getVersion(), content));\n });\n return dbMigrations;\n }",
"public final void setExceptions(SortedSet<Date> dates) {\n\n m_exceptions.clear();\n if (null != dates) {\n m_exceptions.addAll(dates);\n }\n\n }"
] |
Turn given source String array into sorted array.
@param array the source array
@return the sorted array (never <code>null</code>) | [
"public static String[] sortStringArray(String[] array) {\n if (isEmpty(array)) {\n return new String[0];\n }\n Arrays.sort(array);\n return array;\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 }",
"public SwaptionDataLattice append(SwaptionDataLattice other, AnalyticModel model) {\r\n\r\n\t\tSwaptionDataLattice combined = new SwaptionDataLattice(referenceDate, quotingConvention, displacement,\r\n\t\t\t\tforwardCurveName, discountCurveName, floatMetaSchedule, fixMetaSchedule);\r\n\t\tcombined.entryMap.putAll(entryMap);\r\n\r\n\t\tif(quotingConvention == other.quotingConvention && displacement == other.displacement) {\r\n\t\t\tcombined.entryMap.putAll(other.entryMap);\r\n\t\t} else {\r\n\t\t\tSwaptionDataLattice converted = other.convertLattice(quotingConvention, displacement, model);\r\n\t\t\tcombined.entryMap.putAll(converted.entryMap);\r\n\t\t}\r\n\r\n\t\treturn combined;\r\n\t}",
"public void addFile(String description, FileModel fileModel)\n {\n Map<FileModel, ProblemFileSummary> files = addDescription(description);\n\n if (files.containsKey(fileModel))\n {\n files.get(fileModel).addOccurrence();\n } else {\n files.put(fileModel, new ProblemFileSummary(fileModel, 1));\n }\n }",
"public static CmsResourceTypeStatResultList init(CmsResourceTypeStatResultList resList) {\n\n if (resList == null) {\n return new CmsResourceTypeStatResultList();\n }\n\n resList.deleteOld();\n return resList;\n }",
"protected T checkReturnValue(T instance) {\n if (instance == null && !isDependent()) {\n throw BeanLogger.LOG.nullNotAllowedFromProducer(getProducer(), Formats.formatAsStackTraceElement(getAnnotated().getJavaMember()));\n }\n if (instance == null) {\n InjectionPoint injectionPoint = beanManager.getServices().get(CurrentInjectionPoint.class).peek();\n if (injectionPoint != null) {\n Class<?> injectionPointRawType = Reflections.getRawType(injectionPoint.getType());\n if (injectionPointRawType.isPrimitive()) {\n return cast(Defaults.getJlsDefaultValue(injectionPointRawType));\n }\n }\n }\n if (instance != null && !(instance instanceof Serializable)) {\n if (beanManager.isPassivatingScope(getScope())) {\n throw BeanLogger.LOG.nonSerializableProductError(getProducer(), Formats.formatAsStackTraceElement(getAnnotated().getJavaMember()));\n }\n InjectionPoint injectionPoint = beanManager.getServices().get(CurrentInjectionPoint.class).peek();\n if (injectionPoint != null && injectionPoint.getBean() != null && Beans.isPassivatingScope(injectionPoint.getBean(), beanManager)) {\n // Transient field is passivation capable injection point\n if (!(injectionPoint.getMember() instanceof Field) || !injectionPoint.isTransient()) {\n throw BeanLogger.LOG.unserializableProductInjectionError(this, Formats.formatAsStackTraceElement(getAnnotated().getJavaMember()),\n injectionPoint, Formats.formatAsStackTraceElement(injectionPoint.getMember()));\n }\n }\n }\n return instance;\n }",
"private void populateResourceAssignment(Record record, ResourceAssignment assignment) throws MPXJException\n {\n //\n // Handle malformed MPX files - ensure that we can locate the resource\n // using either the Unique ID attribute or the ID attribute.\n //\n Resource resource = m_projectFile.getResourceByUniqueID(record.getInteger(12));\n if (resource == null)\n {\n resource = m_projectFile.getResourceByID(record.getInteger(0));\n }\n\n assignment.setUnits(record.getUnits(1));\n assignment.setWork(record.getDuration(2));\n assignment.setBaselineWork(record.getDuration(3));\n assignment.setActualWork(record.getDuration(4));\n assignment.setOvertimeWork(record.getDuration(5));\n assignment.setCost(record.getCurrency(6));\n assignment.setBaselineCost(record.getCurrency(7));\n assignment.setActualCost(record.getCurrency(8));\n assignment.setStart(record.getDateTime(9));\n assignment.setFinish(record.getDateTime(10));\n assignment.setDelay(record.getDuration(11));\n\n //\n // Calculate the remaining work\n //\n Duration work = assignment.getWork();\n Duration actualWork = assignment.getActualWork();\n if (work != null && actualWork != null)\n {\n if (work.getUnits() != actualWork.getUnits())\n {\n actualWork = actualWork.convertUnits(work.getUnits(), m_projectFile.getProjectProperties());\n }\n\n assignment.setRemainingWork(Duration.getInstance(work.getDuration() - actualWork.getDuration(), work.getUnits()));\n }\n\n if (resource != null)\n {\n assignment.setResourceUniqueID(resource.getUniqueID());\n resource.addResourceAssignment(assignment);\n }\n\n m_eventManager.fireAssignmentReadEvent(assignment);\n }",
"public String getToken() {\n String id = null == answer ? text : answer;\n return Act.app().crypto().generateToken(id);\n }",
"private void sendResponse(final HttpServletResponse res, final CmsSpellcheckingRequest request) throws IOException {\n\n final PrintWriter pw = res.getWriter();\n final JSONObject response = getJsonFormattedSpellcheckResult(request);\n pw.println(response.toString());\n pw.close();\n }",
"private List<Entry> sortEntries(List<Entry> loadedEntries) {\n Collections.sort(loadedEntries, new Comparator<Entry>() {\n @Override\n public int compare(Entry entry1, Entry entry2) {\n int result = (int) (entry1.cuePosition - entry2.cuePosition);\n if (result == 0) {\n int h1 = (entry1.hotCueNumber != 0) ? 1 : 0;\n int h2 = (entry2.hotCueNumber != 0) ? 1 : 0;\n result = h1 - h2;\n }\n return result;\n }\n });\n return Collections.unmodifiableList(loadedEntries);\n }"
] |
Adds version information. | [
"private static void addVersionInfo(byte[] grid, int size, int version) {\n // TODO: Zint masks with 0x41 instead of 0x01; which is correct? https://sourceforge.net/p/zint/tickets/110/\n long version_data = QR_ANNEX_D[version - 7];\n for (int i = 0; i < 6; i++) {\n grid[((size - 11) * size) + i] += (version_data >> (i * 3)) & 0x01;\n grid[((size - 10) * size) + i] += (version_data >> ((i * 3) + 1)) & 0x01;\n grid[((size - 9) * size) + i] += (version_data >> ((i * 3) + 2)) & 0x01;\n grid[(i * size) + (size - 11)] += (version_data >> (i * 3)) & 0x01;\n grid[(i * size) + (size - 10)] += (version_data >> ((i * 3) + 1)) & 0x01;\n grid[(i * size) + (size - 9)] += (version_data >> ((i * 3) + 2)) & 0x01;\n }\n }"
] | [
"public static String fancyStringF(double value, DecimalFormat format, int length, int significant) {\n\n String formatted = fancyString(value, format, length, significant);\n\n int n = length-formatted.length();\n if( n > 0 ) {\n StringBuilder builder = new StringBuilder(n);\n for (int i = 0; i < n; i++) {\n builder.append(' ');\n }\n return formatted + builder.toString();\n } else {\n return formatted;\n }\n }",
"@Api\n\tpublic void setUrl(String url) throws LayerException {\n\t\ttry {\n\t\t\tthis.url = url;\n\t\t\tMap<String, Object> params = new HashMap<String, Object>();\n\t\t\tparams.put(\"url\", url);\n\t\t\tDataStore store = DataStoreFactory.create(params);\n\t\t\tsetDataStore(store);\n\t\t} catch (IOException ioe) {\n\t\t\tthrow new LayerException(ioe, ExceptionCode.INVALID_SHAPE_FILE_URL, url);\n\t\t}\n\t}",
"public static long access2d(DMatrixRMaj a , DMatrixRMaj b , DMatrixRMaj c )\n {\n long timeBefore = System.currentTimeMillis();\n\n for( int i = 0; i < a.numRows; i++ ) {\n\n for( int j = 0; j < b.numCols; j++ ) {\n c.set(i,j,a.get(i,0)*b.get(0,j));\n }\n\n for( int k = 1; k < b.numRows; k++ ) {\n for( int j = 0; j < b.numCols; j++ ) {\n// c.set(i,j, c.get(i,j) + a.get(i,k)*b.get(k,j));\n c.data[i*b.numCols+j] +=a.get(i,k)*b.get(k,j);\n }\n }\n }\n\n return System.currentTimeMillis() - timeBefore;\n }",
"@UiHandler(\"m_atDay\")\r\n void onWeekDayChange(ValueChangeEvent<String> event) {\r\n\r\n if (handleChange()) {\r\n m_controller.setWeekDay(event.getValue());\r\n }\r\n }",
"private PersistentResourceXMLDescription getSimpleMapperParser() {\n if (version.equals(Version.VERSION_1_0)) {\n return simpleMapperParser_1_0;\n } else if (version.equals(Version.VERSION_1_1)) {\n return simpleMapperParser_1_1;\n }\n return simpleMapperParser;\n }",
"public DbLicense resolve(final String licenseId) {\n\n for (final Entry<String, DbLicense> regexp : licensesRegexp.entrySet()) {\n try {\n if (licenseId.matches(regexp.getKey())) {\n return regexp.getValue();\n }\n } catch (PatternSyntaxException e) {\n LOG.error(\"Wrong pattern for the following license \" + regexp.getValue().getName(), e);\n continue;\n }\n }\n\n if(LOG.isWarnEnabled()) {\n LOG.warn(String.format(\"No matching pattern for license %s\", licenseId));\n }\n return null;\n }",
"private static boolean containsGreekLetter(String s) {\r\n Matcher m = biogreek.matcher(s);\r\n return m.find();\r\n }",
"public CSTNode get( int index ) \n {\n CSTNode element = null;\n\n if( index < size() ) \n {\n element = (CSTNode)elements.get( index );\n }\n\n return element;\n }",
"public String getUniformDescriptor(GVRContext ctx)\n {\n if (mShaderTemplate == null)\n {\n mShaderTemplate = makeTemplate(ID, ctx);\n ctx.getShaderManager().addShaderID(this);\n }\n return mShaderTemplate.getUniformDescriptor();\n }"
] |
Layout children inside the layout container | [
"public void layoutChildren() {\n\n Set<Integer> copySet;\n synchronized (mMeasuredChildren) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"layoutChildren [%d] layout = %s\",\n mMeasuredChildren.size(), this);\n copySet = new HashSet<>(mMeasuredChildren);\n }\n for (int nextMeasured: copySet) {\n Widget child = mContainer.get(nextMeasured);\n if (child != null) {\n child.preventTransformChanged(true);\n layoutChild(nextMeasured);\n postLayoutChild(nextMeasured);\n child.preventTransformChanged(false);\n }\n\n }\n }"
] | [
"protected Integer getCorrectIndex(Integer index) {\n Integer size = jsonNode.size();\n Integer newIndex = index;\n\n // reverse walking through the array\n if(index < 0) {\n newIndex = size + index;\n }\n\n // the negative index would be greater than the size a second time!\n if(newIndex < 0) {\n throw LOG.indexOutOfBounds(index, size);\n }\n\n // the index is greater as the actual size\n if(index > size) {\n throw LOG.indexOutOfBounds(index, size);\n }\n\n return newIndex;\n }",
"public static String rgb(int r, int g, int b) {\n if (r < -100 || r > 100) {\n throw new IllegalArgumentException(\"Red value must be between -100 and 100, inclusive.\");\n }\n if (g < -100 || g > 100) {\n throw new IllegalArgumentException(\"Green value must be between -100 and 100, inclusive.\");\n }\n if (b < -100 || b > 100) {\n throw new IllegalArgumentException(\"Blue value must be between -100 and 100, inclusive.\");\n }\n return FILTER_RGB + \"(\" + r + \",\" + g + \",\" + b + \")\";\n }",
"private static boolean getSystemConnectivity(Context context) {\n try {\n ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n if (cm == null) {\n return false;\n }\n\n NetworkInfo activeNetwork = cm.getActiveNetworkInfo();\n return activeNetwork.isConnectedOrConnecting();\n } catch (Exception exception) {\n return false;\n }\n }",
"public static appfwwsdl get(nitro_service service) throws Exception{\n\t\tappfwwsdl obj = new appfwwsdl();\n\t\tappfwwsdl[] response = (appfwwsdl[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"@PostConstruct\n\tprotected void buildCopyrightMap() {\n\t\tif (null == declaredPlugins) {\n\t\t\treturn;\n\t\t}\n\t\t// go over all plug-ins, adding copyright info, avoiding duplicates (on object key)\n\t\tfor (PluginInfo plugin : declaredPlugins.values()) {\n\t\t\tfor (CopyrightInfo copyright : plugin.getCopyrightInfo()) {\n\t\t\t\tString key = copyright.getKey();\n\t\t\t\tString msg = copyright.getKey() + \": \" + copyright.getCopyright() + \" : licensed as \" +\n\t\t\t\t\t\tcopyright.getLicenseName() + \", see \" + copyright.getLicenseUrl();\n\t\t\t\tif (null != copyright.getSourceUrl()) {\n\t\t\t\t\tmsg += \" source \" + copyright.getSourceUrl();\n\t\t\t\t}\n\t\t\t\tif (!copyrightMap.containsKey(key)) {\n\t\t\t\t\tlog.info(msg);\n\t\t\t\t\tcopyrightMap.put(key, copyright);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"public void contextInitialized(ServletContextEvent event) {\n this.context = event.getServletContext();\n\n // Output a simple message to the server's console\n System.out.println(\"The Simple Web App. Is Ready\");\n\n ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(\n \"/client.xml\");\n LocatorService client = (LocatorService) context\n .getBean(\"locatorService\");\n\n String serviceHost = this.context.getInitParameter(\"serviceHost\");\n\n try {\n client.registerEndpoint(new QName(\n \"http://talend.org/esb/examples/\", \"GreeterService\"),\n serviceHost, BindingType.SOAP_11, TransportType.HTTP, null);\n } catch (InterruptedExceptionFault e) {\n e.printStackTrace();\n } catch (ServiceLocatorFault e) {\n e.printStackTrace();\n }\n }",
"public void setAttribute(String strKey, Object value)\r\n {\r\n this.propertyChangeDelegate.firePropertyChange(strKey,\r\n hmAttributes.put(strKey, value), value);\r\n }",
"public static KnowledgeBuilderConfiguration newKnowledgeBuilderConfiguration(Properties properties,\n ClassLoader... classLoaders) {\n return FactoryServiceHolder.factoryService.newKnowledgeBuilderConfiguration( properties, classLoaders );\n }",
"private void writeFinalResults() {\n\t\t// Print a final report:\n\t\tprintStatus();\n\n\t\t// Store property counts in files:\n\t\twritePropertyStatisticsToFile(this.itemStatistics,\n\t\t\t\t\"item-property-counts.csv\");\n\t\twritePropertyStatisticsToFile(this.propertyStatistics,\n\t\t\t\t\"property-property-counts.csv\");\n\n\t\t// Store site link statistics in file:\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers\n\t\t\t\t\t\t.openExampleFileOuputStream(\"site-link-counts.csv\"))) {\n\n\t\t\tout.println(\"Site key,Site links\");\n\t\t\tfor (Entry<String, Integer> entry : this.siteLinkStatistics\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tout.println(entry.getKey() + \",\" + entry.getValue());\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\t// Store term statistics in file:\n\t\twriteTermStatisticsToFile(this.itemStatistics, \"item-term-counts.csv\");\n\t\twriteTermStatisticsToFile(this.propertyStatistics,\n\t\t\t\t\"property-term-counts.csv\");\n\t}"
] |
Rollback an app to a specific release.
@param appName App name. See {@link #listApps} for a list of apps that can be used.
@param releaseUuid Release UUID. See {@link #listReleases} for a list of the app's releases.
@return the release object | [
"public Release rollback(String appName, String releaseUuid) {\n return connection.execute(new Rollback(appName, releaseUuid), apiKey);\n }"
] | [
"public SwaptionDataLattice append(SwaptionDataLattice other, AnalyticModel model) {\r\n\r\n\t\tSwaptionDataLattice combined = new SwaptionDataLattice(referenceDate, quotingConvention, displacement,\r\n\t\t\t\tforwardCurveName, discountCurveName, floatMetaSchedule, fixMetaSchedule);\r\n\t\tcombined.entryMap.putAll(entryMap);\r\n\r\n\t\tif(quotingConvention == other.quotingConvention && displacement == other.displacement) {\r\n\t\t\tcombined.entryMap.putAll(other.entryMap);\r\n\t\t} else {\r\n\t\t\tSwaptionDataLattice converted = other.convertLattice(quotingConvention, displacement, model);\r\n\t\t\tcombined.entryMap.putAll(converted.entryMap);\r\n\t\t}\r\n\r\n\t\treturn combined;\r\n\t}",
"public Map<String, String> getUploadParameters() {\r\n Map<String, String> parameters = new TreeMap<>();\r\n\r\n\r\n String title = getTitle();\r\n if (title != null) {\r\n parameters.put(\"title\", title);\r\n }\r\n\r\n String description = getDescription();\r\n if (description != null) {\r\n parameters.put(\"description\", description);\r\n }\r\n\r\n Collection<String> tags = getTags();\r\n if (tags != null) {\r\n parameters.put(\"tags\", StringUtilities.join(tags, \" \"));\r\n }\r\n\r\n if (isHidden() != null) {\r\n parameters.put(\"hidden\", isHidden().booleanValue() ? \"1\" : \"0\");\r\n }\r\n\r\n if (getSafetyLevel() != null) {\r\n parameters.put(\"safety_level\", getSafetyLevel());\r\n }\r\n\r\n if (getContentType() != null) {\r\n parameters.put(\"content_type\", getContentType());\r\n }\r\n\r\n if (getPhotoId() != null) {\r\n parameters.put(\"photo_id\", getPhotoId());\r\n }\r\n\r\n parameters.put(\"is_public\", isPublicFlag() ? \"1\" : \"0\");\r\n parameters.put(\"is_family\", isFamilyFlag() ? \"1\" : \"0\");\r\n parameters.put(\"is_friend\", isFriendFlag() ? \"1\" : \"0\");\r\n parameters.put(\"async\", isAsync() ? \"1\" : \"0\");\r\n\r\n return parameters;\r\n }",
"public static ExtensibleConfigurationPersister createDomainXmlConfigurationPersister(final ConfigurationFile file, ExecutorService executorService, ExtensionRegistry extensionRegistry, final HostControllerEnvironment environment) {\n DomainXml domainXml = new DomainXml(Module.getBootModuleLoader(), executorService, extensionRegistry);\n\n boolean suppressLoad = false;\n ConfigurationFile.InteractionPolicy policy = file.getInteractionPolicy();\n final boolean isReloaded = environment.getRunningModeControl().isReloaded();\n\n if (!isReloaded && (policy == ConfigurationFile.InteractionPolicy.NEW && (file.getBootFile().exists() && file.getBootFile().length() != 0))) {\n throw HostControllerLogger.ROOT_LOGGER.cannotOverwriteDomainXmlWithEmpty(file.getBootFile().getName());\n }\n\n if (!isReloaded && (policy == ConfigurationFile.InteractionPolicy.NEW || policy == ConfigurationFile.InteractionPolicy.DISCARD)) {\n suppressLoad = true;\n }\n\n BackupXmlConfigurationPersister persister = new BackupXmlConfigurationPersister(file, new QName(Namespace.CURRENT.getUriString(), \"domain\"), domainXml, domainXml, suppressLoad);\n for (Namespace namespace : Namespace.domainValues()) {\n if (!namespace.equals(Namespace.CURRENT)) {\n persister.registerAdditionalRootElement(new QName(namespace.getUriString(), \"domain\"), domainXml);\n }\n }\n extensionRegistry.setWriterRegistry(persister);\n return persister;\n }",
"public String getValueSchema() throws IOException {\n Schema schema = getInputPathAvroSchema();\n String valueSchema = schema.getField(valueFieldName).schema().toString();\n return valueSchema;\n }",
"protected synchronized void doClose()\r\n {\r\n try\r\n {\r\n LockManager lm = getImplementation().getLockManager();\r\n Enumeration en = objectEnvelopeTable.elements();\r\n while (en.hasMoreElements())\r\n {\r\n ObjectEnvelope oe = (ObjectEnvelope) en.nextElement();\r\n lm.releaseLock(this, oe.getIdentity(), oe.getObject());\r\n }\r\n\r\n //remove locks for objects which haven't been materialized yet\r\n for (Iterator it = unmaterializedLocks.iterator(); it.hasNext();)\r\n {\r\n lm.releaseLock(this, it.next());\r\n }\r\n\r\n // this tx is no longer interested in materialization callbacks\r\n unRegisterFromAllIndirectionHandlers();\r\n unRegisterFromAllCollectionProxies();\r\n }\r\n finally\r\n {\r\n /**\r\n * MBAIRD: Be nice and close the table to release all refs\r\n */\r\n if (log.isDebugEnabled())\r\n log.debug(\"Close Transaction and release current PB \" + broker + \" on tx \" + this);\r\n // remove current thread from LocalTxManager\r\n // to avoid problems for succeeding calls of the same thread\r\n implementation.getTxManager().deregisterTx(this);\r\n // now cleanup and prepare for reuse\r\n refresh();\r\n }\r\n }",
"private void addApiDocRoots(String packageListUrl) {\n\tBufferedReader br = null;\n\tpackageListUrl = fixApiDocRoot(packageListUrl);\n\ttry {\n\t URL url = new URL(packageListUrl + \"/package-list\");\n\t br = new BufferedReader(new InputStreamReader(url.openStream()));\n\t String line;\n\t while((line = br.readLine()) != null) {\n\t\tline = line + \".\";\n\t\tPattern pattern = Pattern.compile(line.replace(\".\", \"\\\\.\") + \"[^\\\\.]*\");\n\t\tapiDocMap.put(pattern, packageListUrl);\n\t }\n\t} catch(IOException e) {\n\t System.err.println(\"Errors happened while accessing the package-list file at \"\n\t\t + packageListUrl);\n\t} finally {\n\t if(br != null)\n\t\ttry {\n\t\t br.close();\n\t\t} catch (IOException e) {}\n\t}\n\t\n }",
"public static final int getInt(InputStream is) throws IOException\n {\n byte[] data = new byte[4];\n is.read(data);\n return getInt(data, 0);\n }",
"@Subscribe\n public void onSuiteResult(AggregatedSuiteResultEvent e) {\n long millis = e.getExecutionTime();\n String suiteName = e.getDescription().getDisplayName();\n \n List<Long> values = hints.get(suiteName);\n if (values == null) {\n hints.put(suiteName, values = new ArrayList<>());\n }\n values.add(millis);\n while (values.size() > historyLength)\n values.remove(0);\n }",
"protected void processDescriptions(List<MonolingualTextValue> descriptions) {\n for(MonolingualTextValue description : descriptions) {\n \tNameWithUpdate currentValue = newDescriptions.get(description.getLanguageCode());\n \t// only mark the description as added if the value we are writing is different from the current one\n \tif (currentValue == null || !currentValue.value.equals(description)) {\n \t\tnewDescriptions.put(description.getLanguageCode(),\n new NameWithUpdate(description, true));\n \t}\n }\n }"
] |
Check that an array only contains null elements.
@param values, can't be null
@return | [
"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}"
] | [
"private Field getFieldRecursive(Class c, String name) throws NoSuchFieldException\r\n {\r\n try\r\n {\r\n return c.getDeclaredField(name);\r\n }\r\n catch (NoSuchFieldException e)\r\n {\r\n // if field could not be found in the inheritance hierarchy, signal error\r\n if ((c == Object.class) || (c.getSuperclass() == null) || c.isInterface())\r\n {\r\n throw e;\r\n }\r\n // if field could not be found in class c try in superclass\r\n else\r\n {\r\n return getFieldRecursive(c.getSuperclass(), name);\r\n }\r\n }\r\n }",
"@RequestMapping(value = \"api/edit/enable/custom\", method = RequestMethod.POST)\n public\n @ResponseBody\n String enableCustomResponse(Model model, String custom, int path_id,\n @RequestParam(defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) throws Exception {\n if (custom.equals(\"undefined\"))\n return null;\n editService.enableCustomResponse(custom, path_id, clientUUID);\n return null;\n }",
"public static base_response add(nitro_service client, locationfile resource) throws Exception {\n\t\tlocationfile addresource = new locationfile();\n\t\taddresource.Locationfile = resource.Locationfile;\n\t\taddresource.format = resource.format;\n\t\treturn addresource.add_resource(client);\n\t}",
"private ModelNode resolveExpressionsRecursively(final ModelNode node) throws OperationFailedException {\n if (!node.isDefined()) {\n return node;\n }\n\n ModelType type = node.getType();\n ModelNode resolved;\n if (type == ModelType.EXPRESSION) {\n resolved = resolveExpressionStringRecursively(node.asExpression().getExpressionString(), lenient, true);\n } else if (type == ModelType.OBJECT) {\n resolved = node.clone();\n for (Property prop : resolved.asPropertyList()) {\n resolved.get(prop.getName()).set(resolveExpressionsRecursively(prop.getValue()));\n }\n } else if (type == ModelType.LIST) {\n resolved = node.clone();\n ModelNode list = new ModelNode();\n list.setEmptyList();\n for (ModelNode current : resolved.asList()) {\n list.add(resolveExpressionsRecursively(current));\n }\n resolved = list;\n } else if (type == ModelType.PROPERTY) {\n resolved = node.clone();\n resolved.set(resolved.asProperty().getName(), resolveExpressionsRecursively(resolved.asProperty().getValue()));\n } else {\n resolved = node;\n }\n\n return resolved;\n }",
"private static final double printDurationFractionsOfMinutes(Duration duration, int factor)\n {\n double result = 0;\n\n if (duration != null)\n {\n result = duration.getDuration();\n\n switch (duration.getUnits())\n {\n case HOURS:\n case ELAPSED_HOURS:\n {\n result *= 60;\n break;\n }\n\n case DAYS:\n {\n result *= (60 * 8);\n break;\n }\n\n case ELAPSED_DAYS:\n {\n result *= (60 * 24);\n break;\n }\n\n case WEEKS:\n {\n result *= (60 * 8 * 5);\n break;\n }\n\n case ELAPSED_WEEKS:\n {\n result *= (60 * 24 * 7);\n break;\n }\n\n case MONTHS:\n {\n result *= (60 * 8 * 5 * 4);\n break;\n }\n\n case ELAPSED_MONTHS:\n {\n result *= (60 * 24 * 30);\n break;\n }\n\n case YEARS:\n {\n result *= (60 * 8 * 5 * 52);\n break;\n }\n\n case ELAPSED_YEARS:\n {\n result *= (60 * 24 * 365);\n break;\n }\n\n default:\n {\n break;\n }\n }\n }\n\n result *= factor;\n\n return (result);\n }",
"public int getTotalLeased(){\r\n\t\tint total=0;\r\n\t\tfor (int i=0; i < this.partitionCount && this.partitions[i] != null; i++){\r\n\t\t\ttotal+=this.partitions[i].getCreatedConnections()-this.partitions[i].getAvailableConnections();\r\n\t\t}\r\n\t\treturn total;\r\n\t}",
"@Override\n public AccountingDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }",
"public void setSchema(String schema)\n {\n if (schema == null)\n {\n schema = \"\";\n }\n else\n {\n if (!schema.isEmpty() && !schema.endsWith(\".\"))\n {\n schema = schema + '.';\n }\n }\n m_schema = schema;\n }",
"public static BoxDeveloperEditionAPIConnection getAppEnterpriseConnection(BoxConfig boxConfig) {\n\n BoxDeveloperEditionAPIConnection connection = getAppEnterpriseConnection(boxConfig.getEnterpriseId(),\n boxConfig.getClientId(), boxConfig.getClientSecret(), boxConfig.getJWTEncryptionPreferences());\n\n return connection;\n }"
] |
Finds or opens a client to talk to the dbserver on the specified player, incrementing its use count.
@param targetPlayer the player number whose database needs to be interacted with
@param description a short description of the task being performed for error reporting if it fails,
should be a verb phrase like "requesting track metadata"
@return the communication client for talking to that player, or {@code null} if the player could not be found
@throws IllegalStateException if we can't find the target player or there is no suitable player number for us
to pretend to be
@throws IOException if there is a problem communicating | [
"private synchronized Client allocateClient(int targetPlayer, String description) throws IOException {\n Client result = openClients.get(targetPlayer);\n if (result == null) {\n // We need to open a new connection.\n final DeviceAnnouncement deviceAnnouncement = DeviceFinder.getInstance().getLatestAnnouncementFrom(targetPlayer);\n if (deviceAnnouncement == null) {\n throw new IllegalStateException(\"Player \" + targetPlayer + \" could not be found \" + description);\n }\n final int dbServerPort = getPlayerDBServerPort(targetPlayer);\n if (dbServerPort < 0) {\n throw new IllegalStateException(\"Player \" + targetPlayer + \" does not have a db server \" + description);\n }\n\n final byte posingAsPlayerNumber = (byte) chooseAskingPlayerNumber(targetPlayer);\n\n Socket socket = null;\n try {\n InetSocketAddress address = new InetSocketAddress(deviceAnnouncement.getAddress(), dbServerPort);\n socket = new Socket();\n socket.connect(address, socketTimeout.get());\n socket.setSoTimeout(socketTimeout.get());\n result = new Client(socket, targetPlayer, posingAsPlayerNumber);\n } catch (IOException e) {\n try {\n socket.close();\n } catch (IOException e2) {\n logger.error(\"Problem closing socket for failed client creation attempt \" + description);\n }\n throw e;\n }\n openClients.put(targetPlayer, result);\n useCounts.put(result, 0);\n }\n useCounts.put(result, useCounts.get(result) + 1);\n return result;\n }"
] | [
"public String getDbProperty(String key) {\n\n // extract the database key out of the entire key\n String databaseKey = key.substring(0, key.indexOf('.'));\n Properties databaseProperties = getDatabaseProperties().get(databaseKey);\n\n return databaseProperties.getProperty(key, \"\");\n }",
"private void setQR(DMatrixRMaj Q , DMatrixRMaj R , int growRows ) {\n if( Q.numRows != Q.numCols ) {\n throw new IllegalArgumentException(\"Q should be square.\");\n }\n\n this.Q = Q;\n this.R = R;\n\n m = Q.numRows;\n n = R.numCols;\n\n if( m+growRows > maxRows || n > maxCols ) {\n if( autoGrow ) {\n declareInternalData(m+growRows,n);\n } else {\n throw new IllegalArgumentException(\"Autogrow has been set to false and the maximum number of rows\" +\n \" or columns has been exceeded.\");\n }\n }\n }",
"protected void validateResultsDirectories() {\n for (String result : results) {\n if (Files.notExists(Paths.get(result))) {\n throw new AllureCommandException(String.format(\"Report directory <%s> not found.\", result));\n }\n }\n }",
"public boolean checkPrefixes(String uri, String[] patterns) {\n\t\tfor (String pattern : patterns) {\n\t\t\tif (pattern.length() > 0) {\n\t\t\t\tif (uri.startsWith(pattern)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"private void writeAttributeTypes(String name, FieldType[] types) throws IOException\n {\n m_writer.writeStartObject(name);\n for (FieldType field : types)\n {\n m_writer.writeNameValuePair(field.name().toLowerCase(), field.getDataType().getValue());\n }\n m_writer.writeEndObject();\n }",
"public void reportCompletion(NodeT completed) {\n completed.setPreparer(true);\n String dependency = completed.key();\n for (String dependentKey : nodeTable.get(dependency).dependentKeys()) {\n DAGNode<DataT, NodeT> dependent = nodeTable.get(dependentKey);\n dependent.lock().lock();\n try {\n dependent.onSuccessfulResolution(dependency);\n if (dependent.hasAllResolved()) {\n queue.add(dependent.key());\n }\n } finally {\n dependent.lock().unlock();\n }\n }\n }",
"public static base_response unset(nitro_service client, ipv6 resource, String[] args) throws Exception{\n\t\tipv6 unsetresource = new ipv6();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public static String urlEncode(String path) throws URISyntaxException {\n if (isNullOrEmpty(path)) return path;\n\n return UrlEscapers.urlFragmentEscaper().escape(path);\n }",
"public static boolean isInverse(DMatrixRMaj a , DMatrixRMaj b , double tol ) {\n if( a.numRows != b.numRows || a.numCols != b.numCols ) {\n return false;\n }\n\n int numRows = a.numRows;\n int numCols = a.numCols;\n\n for( int i = 0; i < numRows; i++ ) {\n for( int j = 0; j < numCols; j++ ) {\n double total = 0;\n for( int k = 0; k < numCols; k++ ) {\n total += a.get(i,k)*b.get(k,j);\n }\n\n if( i == j ) {\n if( !(Math.abs(total-1) <= tol) )\n return false;\n } else if( !(Math.abs(total) <= tol) )\n return false;\n }\n }\n\n return true;\n }"
] |
Authenticates the API connection by obtaining access and refresh tokens using the auth code that was obtained
from the first half of OAuth.
@param authCode the auth code obtained from the first half of the OAuth process. | [
"public void authenticate(String authCode) {\n URL url = null;\n try {\n url = new URL(this.tokenURL);\n } catch (MalformedURLException e) {\n assert false : \"An invalid token URL indicates a bug in the SDK.\";\n throw new RuntimeException(\"An invalid token URL indicates a bug in the SDK.\", e);\n }\n\n String urlParameters = String.format(\"grant_type=authorization_code&code=%s&client_id=%s&client_secret=%s\",\n authCode, this.clientID, this.clientSecret);\n\n BoxAPIRequest request = new BoxAPIRequest(this, url, \"POST\");\n request.shouldAuthenticate(false);\n request.setBody(urlParameters);\n\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n String json = response.getJSON();\n\n JsonObject jsonObject = JsonObject.readFrom(json);\n this.accessToken = jsonObject.get(\"access_token\").asString();\n this.refreshToken = jsonObject.get(\"refresh_token\").asString();\n this.lastRefresh = System.currentTimeMillis();\n this.expires = jsonObject.get(\"expires_in\").asLong() * 1000;\n }"
] | [
"private void scheduleBatchLoadIfNeeded(Serializable id, SharedSessionContractImplementor session) throws MappingException {\n\t\t//cannot batch fetch by unique key (property-ref associations)\n\t\tif ( StringHelper.isEmpty( delegate.getRHSUniqueKeyPropertyName() ) && id != null ) {\n\t\t\tEntityPersister persister = session.getFactory().getMetamodel().entityPersister( delegate.getAssociatedEntityName() );\n\t\t\tEntityKey entityKey = session.generateEntityKey( id, persister );\n\t\t\tif ( !session.getPersistenceContext().containsEntity( entityKey ) ) {\n\t\t\t\tsession.getPersistenceContext().getBatchFetchQueue().addBatchLoadableEntityKey( entityKey );\n\t\t\t}\n\t\t}\n\t}",
"@Override\n public CopticDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }",
"public void useNewSOAPService(boolean direct) throws Exception {\n URL wsdlURL = getClass().getResource(\"/CustomerServiceNew.wsdl\");\n org.customer.service.CustomerServiceService service = \n new org.customer.service.CustomerServiceService(wsdlURL);\n \n org.customer.service.CustomerService customerService = \n direct ? service.getCustomerServicePort() : service.getCustomerServiceNewPort();\n\n System.out.println(\"Using new SOAP CustomerService with new client\");\n \n customer.v2.Customer customer = createNewCustomer(\"Barry New SOAP\");\n customerService.updateCustomer(customer);\n customer = customerService.getCustomerByName(\"Barry New SOAP\");\n printNewCustomerDetails(customer);\n }",
"public void dispatchKeyEvent(int code, int action) {\n int keyCode = 0;\n int keyAction = 0;\n if (code == BUTTON_1) {\n keyCode = KeyEvent.KEYCODE_BUTTON_1;\n } else if (code == BUTTON_2) {\n keyCode = KeyEvent.KEYCODE_BUTTON_2;\n }\n\n if (action == ACTION_DOWN) {\n keyAction = KeyEvent.ACTION_DOWN;\n } else if (action == ACTION_UP) {\n keyAction = KeyEvent.ACTION_UP;\n }\n\n KeyEvent keyEvent = new KeyEvent(keyAction, keyCode);\n setKeyEvent(keyEvent);\n }",
"public List<List<IN>> classifyRaw(String str,\r\n DocumentReaderAndWriter<IN> readerAndWriter) {\r\n ObjectBank<List<IN>> documents =\r\n makeObjectBankFromString(str, readerAndWriter);\r\n List<List<IN>> result = new ArrayList<List<IN>>();\r\n\r\n for (List<IN> document : documents) {\r\n classify(document);\r\n\r\n List<IN> sentence = new ArrayList<IN>();\r\n for (IN wi : document) {\r\n // TaggedWord word = new TaggedWord(wi.word(), wi.answer());\r\n // sentence.add(word);\r\n sentence.add(wi);\r\n }\r\n result.add(sentence);\r\n }\r\n return result;\r\n }",
"protected static final Long parseUsingFallbacksWithColon(String text, DateTimeFormat timeFormat) {\n if (text.indexOf(':') == -1) {\n text = text.replace(\" \", \"\");\n int numdigits = 0;\n int lastdigit = 0;\n for (int i = 0; i < text.length(); i++) {\n char c = text.charAt(i);\n if (Character.isDigit(c)) {\n numdigits++;\n lastdigit = i;\n }\n }\n if (numdigits == 1 || numdigits == 2) {\n // insert :00\n int colon = lastdigit + 1;\n text = text.substring(0, colon) + \":00\" + text.substring(colon);\n }\n else if (numdigits > 2) {\n // insert :\n int colon = lastdigit - 1;\n text = text.substring(0, colon) + \":\" + text.substring(colon);\n }\n return parseUsingFallbacks(text, timeFormat);\n }\n else {\n return null;\n }\n }",
"public Iterator getAllBaseTypes()\r\n {\r\n ArrayList baseTypes = new ArrayList();\r\n\r\n baseTypes.addAll(_directBaseTypes.values());\r\n\r\n for (int idx = baseTypes.size() - 1; idx >= 0; idx--)\r\n {\r\n ClassDescriptorDef curClassDef = (ClassDescriptorDef)baseTypes.get(idx);\r\n\r\n for (Iterator it = curClassDef.getDirectBaseTypes(); it.hasNext();)\r\n {\r\n ClassDescriptorDef curBaseTypeDef = (ClassDescriptorDef)it.next();\r\n\r\n if (!baseTypes.contains(curBaseTypeDef))\r\n {\r\n baseTypes.add(0, curBaseTypeDef);\r\n idx++;\r\n }\r\n }\r\n }\r\n return baseTypes.iterator();\r\n }",
"public void characters(char ch[], int start, int length)\r\n {\r\n if (m_CurrentString == null)\r\n m_CurrentString = new String(ch, start, length);\r\n else\r\n m_CurrentString += new String(ch, start, length);\r\n }",
"public static BoxAPIConnection restore(String clientID, String clientSecret, String state) {\n BoxAPIConnection api = new BoxAPIConnection(clientID, clientSecret);\n api.restore(state);\n return api;\n }"
] |
Checks if a point is in the given rectangle.
@param _Rect rectangle which is checked
@param _X x-coordinate of the point
@param _Y y-coordinate of the point
@return True if the points intersects with the rectangle. | [
"public static boolean intersectsPointWithRectF(RectF _Rect, float _X, float _Y) {\n return _X > _Rect.left && _X < _Rect.right && _Y > _Rect.top && _Y < _Rect.bottom;\n }"
] | [
"protected <T, A> ActiveOperation<T, A> removeActiveOperation(Integer id) {\n final ActiveOperation<T, A> removed = removeUnderLock(id);\n if(removed != null) {\n for(final Map.Entry<Integer, ActiveRequest<?, ?>> requestEntry : requests.entrySet()) {\n final ActiveRequest<?, ?> request = requestEntry.getValue();\n if(request.context == removed) {\n requests.remove(requestEntry.getKey());\n }\n }\n }\n return removed;\n }",
"public byte[] keyToStorageFormat(byte[] key) {\n\n switch(getReadOnlyStorageFormat()) {\n case READONLY_V0:\n case READONLY_V1:\n return ByteUtils.md5(key);\n case READONLY_V2:\n return ByteUtils.copy(ByteUtils.md5(key), 0, 2 * ByteUtils.SIZE_OF_INT);\n default:\n throw new VoldemortException(\"Unknown read-only storage format\");\n }\n }",
"public static<T> SessionVar<T> vendSessionVar(T defValue) {\n\treturn (new VarsJBridge()).vendSessionVar(defValue, new Exception());\n }",
"private Map<Integer, List<Row>> createWorkPatternAssignmentMap(List<Row> rows) throws ParseException\n {\n Map<Integer, List<Row>> map = new HashMap<Integer, List<Row>>();\n for (Row row : rows)\n {\n Integer calendarID = row.getInteger(\"ID\");\n String workPatterns = row.getString(\"WORK_PATTERNS\");\n map.put(calendarID, createWorkPatternAssignmentRowList(workPatterns));\n }\n return map;\n }",
"@RequestMapping(value = \"/api/plugins\", method = RequestMethod.POST)\n public\n @ResponseBody\n HashMap<String, Object> addPluginPath(Model model, Plugin add) throws Exception {\n PluginManager.getInstance().addPluginPath(add.getPath());\n\n return pluginInformation();\n }",
"public SelectBuilder orderBy(String name, boolean ascending) {\n if (ascending) {\n orderBys.add(name + \" asc\");\n } else {\n orderBys.add(name + \" desc\");\n }\n return this;\n }",
"private boolean isRecyclable(View convertView, T content) {\n boolean isRecyclable = false;\n if (convertView != null && convertView.getTag() != null) {\n Class prototypeClass = getPrototypeClass(content);\n validatePrototypeClass(prototypeClass);\n isRecyclable = prototypeClass.equals(convertView.getTag().getClass());\n }\n return isRecyclable;\n }",
"public static void showErrorDialog(String message, String details) {\n\n Window window = prepareWindow(DialogWidth.wide);\n window.setCaption(\"Error\");\n window.setContent(new CmsSetupErrorDialog(message, details, null, window));\n A_CmsUI.get().addWindow(window);\n\n }",
"static Date parseDate(String dateString) {\n try {\n return DATE_FORMAT.parseDateTime(dateString).toDate();\n } catch (IllegalArgumentException e) {\n return null;\n }\n }"
] |
Clears the handler hierarchy. | [
"public void clearHandlers() {\r\n\r\n for (Map<String, CmsAttributeHandler> handlers : m_handlers) {\r\n for (CmsAttributeHandler handler : handlers.values()) {\r\n handler.clearHandlers();\r\n }\r\n handlers.clear();\r\n }\r\n m_handlers.clear();\r\n m_handlers.add(new HashMap<String, CmsAttributeHandler>());\r\n m_handlerById.clear();\r\n }"
] | [
"protected void handleResponse(int responseCode, InputStream inputStream) {\n BufferedReader rd = null;\n try {\n // Buffer the result into a string\n rd = new BufferedReader(new InputStreamReader(inputStream));\n StringBuilder sb = new StringBuilder();\n String line;\n while((line = rd.readLine()) != null) {\n sb.append(line);\n }\n log.info(\"HttpHook [\" + hookName + \"] received \" + responseCode + \" response: \" + sb);\n } catch (IOException e) {\n log.error(\"Error while reading response for HttpHook [\" + hookName + \"]\", e);\n } finally {\n if (rd != null) {\n try {\n rd.close();\n } catch (IOException e) {\n // no-op\n }\n }\n }\n }",
"public void process() {\n // are we ready to process yet, or have we had an error, and are\n // waiting a bit longer in the hope that it will resolve itself?\n if (error_skips > 0) {\n error_skips--;\n return;\n }\n \n try {\n if (logger != null)\n logger.debug(\"Starting processing\");\n status = \"Processing\";\n lastCheck = System.currentTimeMillis();\n\n // FIXME: how to break off processing if we don't want to keep going?\n processor.deduplicate(batch_size);\n\n status = \"Sleeping\";\n if (logger != null)\n logger.debug(\"Finished processing\");\n } catch (Throwable e) {\n status = \"Thread blocked on error: \" + e;\n if (logger != null)\n logger.error(\"Error in processing; waiting\", e);\n error_skips = error_factor;\n }\n }",
"public static <T> int createTable(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig)\n\t\t\tthrows SQLException {\n\t\tDao<T, ?> dao = DaoManager.createDao(connectionSource, tableConfig);\n\t\treturn doCreateTable(dao, false);\n\t}",
"protected void parseSequencesWithColons(TokenList tokens , Sequence sequence ) {\n\n TokenList.Token t = tokens.getFirst();\n if( t == null )\n return;\n\n int state = 0;\n\n TokenList.Token start = null;\n TokenList.Token middle = null;\n TokenList.Token prev = t;\n\n boolean last = false;\n while( true ) {\n if( state == 0 ) {\n if( isVariableInteger(t) && (t.next != null && t.next.getSymbol() == Symbol.COLON) ) {\n start = t;\n state = 1;\n t = t.next;\n } else if( t != null && t.getSymbol() == Symbol.COLON ) {\n // If it starts with a colon then it must be 'all' or a type-o\n IntegerSequence range = new IntegerSequence.Range(null,null);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(range);\n TokenList.Token n = new TokenList.Token(varSequence);\n tokens.insert(t.previous, n);\n tokens.remove(t);\n t = n;\n }\n } else if( state == 1 ) {\n // var : ?\n if (isVariableInteger(t)) {\n state = 2;\n } else {\n // array range\n IntegerSequence range = new IntegerSequence.Range(start,null);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(range);\n replaceSequence(tokens, varSequence, start, prev);\n state = 0;\n }\n } else if ( state == 2 ) {\n // var:var ?\n if( t != null && t.getSymbol() == Symbol.COLON ) {\n middle = prev;\n state = 3;\n } else {\n // create for sequence with start and stop elements only\n IntegerSequence numbers = new IntegerSequence.For(start,null,prev);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(numbers);\n replaceSequence(tokens, varSequence, start, prev );\n if( t != null )\n t = t.previous;\n state = 0;\n }\n } else if ( state == 3 ) {\n // var:var: ?\n if( isVariableInteger(t) ) {\n // create 'for' sequence with three variables\n IntegerSequence numbers = new IntegerSequence.For(start,middle,t);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(numbers);\n t = replaceSequence(tokens, varSequence, start, t);\n } else {\n // array range with 2 elements\n IntegerSequence numbers = new IntegerSequence.Range(start,middle);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(numbers);\n replaceSequence(tokens, varSequence, start, prev);\n }\n state = 0;\n }\n\n if( last ) {\n break;\n } else if( t.next == null ) {\n // handle the case where it is the last token in the sequence\n last = true;\n }\n prev = t;\n t = t.next;\n }\n }",
"public void createPdfLayout(Dimension dim)\n {\n if (pdfdocument != null) //processing a PDF document\n {\n try {\n if (createImage)\n img = new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_RGB);\n Graphics2D ig = img.createGraphics();\n \n log.info(\"Creating PDF boxes\");\n VisualContext ctx = new VisualContext(null, null);\n \n boxtree = new CSSBoxTree(ig, ctx, dim, baseurl);\n boxtree.setConfig(config);\n boxtree.processDocument(pdfdocument, startPage, endPage);\n viewport = boxtree.getViewport();\n root = boxtree.getDocument().getDocumentElement();\n log.info(\"We have \" + boxtree.getLastId() + \" boxes\");\n viewport.initSubtree();\n \n log.info(\"Layout for \"+dim.width+\"px\");\n viewport.doLayout(dim.width, true, true);\n log.info(\"Resulting size: \" + viewport.getWidth() + \"x\" + viewport.getHeight() + \" (\" + viewport + \")\");\n \n log.info(\"Updating viewport size\");\n viewport.updateBounds(dim);\n log.info(\"Resulting size: \" + viewport.getWidth() + \"x\" + viewport.getHeight() + \" (\" + viewport + \")\");\n \n if (createImage && (viewport.getWidth() > dim.width || viewport.getHeight() > dim.height))\n {\n img = new BufferedImage(Math.max(viewport.getWidth(), dim.width),\n Math.max(viewport.getHeight(), dim.height),\n BufferedImage.TYPE_INT_RGB);\n ig = img.createGraphics();\n }\n \n log.info(\"Positioning for \"+img.getWidth()+\"x\"+img.getHeight()+\"px\");\n viewport.absolutePositions();\n \n clearCanvas();\n viewport.draw(new GraphicsRenderer(ig));\n setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));\n revalidate();\n } catch (ParserConfigurationException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n else if (root != null) //processing a DOM tree\n {\n super.createLayout(dim);\n }\n }",
"public void load(File file) {\n try {\n PropertiesConfiguration config = new PropertiesConfiguration();\n // disabled to prevent accumulo classpath value from being shortened\n config.setDelimiterParsingDisabled(true);\n config.load(file);\n ((CompositeConfiguration) internalConfig).addConfiguration(config);\n } catch (ConfigurationException e) {\n throw new IllegalArgumentException(e);\n }\n }",
"public static int skipToNextMatchingShort(byte[] buffer, int offset, int value)\n {\n int nextOffset = offset;\n while (getShort(buffer, nextOffset) != value)\n {\n ++nextOffset;\n }\n nextOffset += 2;\n\n return nextOffset;\n }",
"public static <S extends Matrix, D extends Matrix> LinearSolver<S,D> safe(LinearSolver<S,D> solver ) {\n if( solver.modifiesA() || solver.modifiesB() ) {\n if( solver instanceof LinearSolverDense ) {\n return new LinearSolverSafe((LinearSolverDense)solver);\n } else if( solver instanceof LinearSolverSparse ) {\n return new LinearSolverSparseSafe((LinearSolverSparse)solver);\n } else {\n throw new IllegalArgumentException(\"Unknown solver type\");\n }\n } else {\n return solver;\n }\n }",
"public static cacheselector[] get(nitro_service service, String selectorname[]) throws Exception{\n\t\tif (selectorname !=null && selectorname.length>0) {\n\t\t\tcacheselector response[] = new cacheselector[selectorname.length];\n\t\t\tcacheselector obj[] = new cacheselector[selectorname.length];\n\t\t\tfor (int i=0;i<selectorname.length;i++) {\n\t\t\t\tobj[i] = new cacheselector();\n\t\t\t\tobj[i].set_selectorname(selectorname[i]);\n\t\t\t\tresponse[i] = (cacheselector) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}"
] |
Gets the value of the callout property.
<p>
This accessor method returns a reference to the live list,
not a snapshot. Therefore any modification you make to the
returned list will be present inside the JAXB object.
This is why there is not a <CODE>set</CODE> method for the callout property.
<p>
For example, to add a new item, do as follows:
<pre>
getCallout().add(newItem);
</pre>
<p>
Objects of the following type(s) are allowed in the list
{@link Callouts.Callout } | [
"public List<Callouts.Callout> getCallout()\n {\n if (callout == null)\n {\n callout = new ArrayList<Callouts.Callout>();\n }\n return this.callout;\n }"
] | [
"public static NodeCache startAppIdWatcher(Environment env) {\n try {\n CuratorFramework curator = env.getSharedResources().getCurator();\n\n byte[] uuidBytes = curator.getData().forPath(ZookeeperPath.CONFIG_FLUO_APPLICATION_ID);\n if (uuidBytes == null) {\n Halt.halt(\"Fluo Application UUID not found\");\n throw new RuntimeException(); // make findbugs happy\n }\n\n final String uuid = new String(uuidBytes, StandardCharsets.UTF_8);\n\n final NodeCache nodeCache = new NodeCache(curator, ZookeeperPath.CONFIG_FLUO_APPLICATION_ID);\n nodeCache.getListenable().addListener(() -> {\n ChildData node = nodeCache.getCurrentData();\n if (node == null || !uuid.equals(new String(node.getData(), StandardCharsets.UTF_8))) {\n Halt.halt(\"Fluo Application UUID has changed or disappeared\");\n }\n });\n nodeCache.start();\n return nodeCache;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }",
"public ParallelTaskBuilder prepareTcp(String command) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.setProtocol(RequestProtocol.TCP);\n cb.getTcpMeta().setCommand(command);\n return cb;\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}",
"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 }",
"String buildSelect(String htmlAttributes, SelectOptions options) {\n\n return buildSelect(htmlAttributes, options.getOptions(), options.getValues(), options.getSelectedIndex());\n }",
"private MBeanServer getServerForName(String name) {\n try {\n MBeanServer mbeanServer = null;\n final ObjectName objectNameQuery = new ObjectName(name + \":type=Service,*\");\n\n for (final MBeanServer server : MBeanServerFactory.findMBeanServer(null)) {\n if (server.queryNames(objectNameQuery, null).size() > 0) {\n mbeanServer = server;\n // we found it, bail out\n break;\n }\n }\n\n return mbeanServer;\n } catch (Exception e) {\n }\n\n return null;\n }",
"public static String resolveOrOriginal(String input) {\n try {\n return resolve(input, true);\n } catch (UnresolvedExpressionException e) {\n return input;\n }\n }",
"public static hanode_routemonitor_binding[] get(nitro_service service, Long id) throws Exception{\n\t\thanode_routemonitor_binding obj = new hanode_routemonitor_binding();\n\t\tobj.set_id(id);\n\t\thanode_routemonitor_binding response[] = (hanode_routemonitor_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public String invokeOperation(String operationName, Map<String, String[]> parameterMap)\n throws JMException, UnsupportedEncodingException {\n MBeanOperationInfo operationInfo = getOperationInfo(operationName);\n MBeanOperationInvoker invoker = createMBeanOperationInvoker(mBeanServer, objectName, operationInfo);\n return sanitizer.escapeValue(invoker.invokeOperation(parameterMap));\n }"
] |
Will start the HiveServer.
@param testConfig Specific test case properties. Will be merged with the HiveConf of the context
@param hiveVars HiveVars to pass on to the HiveServer for this session | [
"public void init(Map<String, String> testConfig, Map<String, String> hiveVars) {\n\n context.init();\n\n HiveConf hiveConf = context.getHiveConf();\n\n // merge test case properties with hive conf before HiveServer is started.\n for (Map.Entry<String, String> property : testConfig.entrySet()) {\n hiveConf.set(property.getKey(), property.getValue());\n }\n\n try {\n hiveServer2 = new HiveServer2();\n hiveServer2.init(hiveConf);\n\n // Locate the ClIService in the HiveServer2\n for (Service service : hiveServer2.getServices()) {\n if (service instanceof CLIService) {\n client = (CLIService) service;\n }\n }\n\n Preconditions.checkNotNull(client, \"ClIService was not initialized by HiveServer2\");\n\n sessionHandle = client.openSession(\"noUser\", \"noPassword\", null);\n\n SessionState sessionState = client.getSessionManager().getSession(sessionHandle).getSessionState();\n currentSessionState = sessionState;\n currentSessionState.setHiveVariables(hiveVars);\n } catch (Exception e) {\n throw new IllegalStateException(\"Failed to create HiveServer :\" + e.getMessage(), e);\n }\n\n // Ping hive server before we do anything more with it! If validation\n // is switched on, this will fail if metastorage is not set up properly\n pingHiveServer();\n }"
] | [
"static void tryAutoAttaching(final SlotReference slot) {\n if (!MetadataFinder.getInstance().getMountedMediaSlots().contains(slot)) {\n logger.error(\"Unable to auto-attach cache to empty slot {}\", slot);\n return;\n }\n if (MetadataFinder.getInstance().getMetadataCache(slot) != null) {\n logger.info(\"Not auto-attaching to slot {}; already has a cache attached.\", slot);\n return;\n }\n if (MetadataFinder.getInstance().getAutoAttachCacheFiles().isEmpty()) {\n logger.debug(\"No auto-attach files configured.\");\n return;\n }\n\n new Thread(new Runnable() {\n @Override\n public void run() {\n try {\n Thread.sleep(5); // Give us a chance to find out what type of media is in the new mount.\n final MediaDetails details = MetadataFinder.getInstance().getMediaDetailsFor(slot);\n if (details != null && details.mediaType == CdjStatus.TrackType.REKORDBOX) {\n // First stage attempt: See if we can match based on stored media details, which is both more reliable and\n // less disruptive than trying to sample the player database to compare entries.\n boolean attached = false;\n for (File file : MetadataFinder.getInstance().getAutoAttachCacheFiles()) {\n final MetadataCache cache = new MetadataCache(file);\n try {\n if (cache.sourceMedia != null && cache.sourceMedia.hashKey().equals(details.hashKey())) {\n // We found a solid match, no need to probe tracks.\n final boolean changed = cache.sourceMedia.hasChanged(details);\n logger.info(\"Auto-attaching metadata cache \" + cache.getName() + \" to slot \" + slot +\n \" based on media details \" + (changed? \"(changed since created)!\" : \"(unchanged).\"));\n MetadataFinder.getInstance().attachMetadataCacheInternal(slot, cache);\n attached = true;\n return;\n }\n } finally {\n if (!attached) {\n cache.close();\n }\n }\n }\n\n // Could not match based on media details; fall back to older method based on probing track metadata.\n ConnectionManager.ClientTask<Object> task = new ConnectionManager.ClientTask<Object>() {\n @Override\n public Object useClient(Client client) throws Exception {\n tryAutoAttachingWithConnection(slot, client);\n return null;\n }\n };\n ConnectionManager.getInstance().invokeWithClientSession(slot.player, task, \"trying to auto-attach metadata cache\");\n }\n } catch (Exception e) {\n logger.error(\"Problem trying to auto-attach metadata cache for slot \" + slot, e);\n }\n\n }\n }, \"Metadata cache file auto-attachment attempt\").start();\n }",
"public Date getStart()\n {\n Date result = (Date) getCachedValue(AssignmentField.START);\n if (result == null)\n {\n result = getTask().getStart();\n }\n return result;\n }",
"public void createOverride(int groupId, String methodName, String className) throws Exception {\n // first make sure this doesn't already exist\n for (Method method : EditService.getInstance().getMethodsFromGroupId(groupId, null)) {\n if (method.getMethodName().equals(methodName) && method.getClassName().equals(className)) {\n // don't add if it already exists in the group\n return;\n }\n }\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n PreparedStatement statement = sqlConnection.prepareStatement(\n \"INSERT INTO \" + Constants.DB_TABLE_OVERRIDE\n + \"(\" + Constants.OVERRIDE_METHOD_NAME\n + \",\" + Constants.OVERRIDE_CLASS_NAME\n + \",\" + Constants.OVERRIDE_GROUP_ID\n + \")\"\n + \" VALUES (?, ?, ?)\"\n );\n statement.setString(1, methodName);\n statement.setString(2, className);\n statement.setInt(3, groupId);\n statement.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n }\n }",
"public static vpnvserver_vpnnexthopserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_vpnnexthopserver_binding obj = new vpnvserver_vpnnexthopserver_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_vpnnexthopserver_binding response[] = (vpnvserver_vpnnexthopserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void expireDevices() {\n long now = System.currentTimeMillis();\n // Make a copy so we don't have to worry about concurrent modification.\n Map<InetAddress, DeviceAnnouncement> copy = new HashMap<InetAddress, DeviceAnnouncement>(devices);\n for (Map.Entry<InetAddress, DeviceAnnouncement> entry : copy.entrySet()) {\n if (now - entry.getValue().getTimestamp() > MAXIMUM_AGE) {\n devices.remove(entry.getKey());\n deliverLostAnnouncement(entry.getValue());\n }\n }\n if (devices.isEmpty()) {\n firstDeviceTime.set(0); // We have lost contact with the Pro DJ Link network, so start over with next device.\n }\n }",
"public Stats getCollectionStats(String collectionId, Date date) throws FlickrException {\n return getStats(METHOD_GET_COLLECTION_STATS, \"collection_id\", collectionId, date);\n }",
"public void getGradient(int[] batch, double[] gradient) {\n for (int i=0; i<batch.length; i++) {\n addGradient(i, gradient);\n }\n }",
"public static float noise1(float x) {\n int bx0, bx1;\n float rx0, rx1, sx, t, u, v;\n\n if (start) {\n start = false;\n init();\n }\n\n t = x + N;\n bx0 = ((int)t) & BM;\n bx1 = (bx0+1) & BM;\n rx0 = t - (int)t;\n rx1 = rx0 - 1.0f;\n\n sx = sCurve(rx0);\n\n u = rx0 * g1[p[bx0]];\n v = rx1 * g1[p[bx1]];\n return 2.3f*lerp(sx, u, v);\n }",
"public boolean contains(String column) {\n\t\tfor ( String columnName : columnNames ) {\n\t\t\tif ( columnName.equals( column ) ) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}"
] |
Gets the URL of the route with given name.
@param routeName to return its URL
@return URL backed by the route with given name. | [
"public Optional<URL> getRoute(String routeName) {\n Route route = getClient().routes()\n .inNamespace(namespace).withName(routeName).get();\n\n return route != null ? Optional.ofNullable(createUrlFromRoute(route)) : Optional.empty();\n }"
] | [
"public void add( int row , int col , double value ) {\n if( col < 0 || col >= numCols || row < 0 || row >= numRows ) {\n throw new IllegalArgumentException(\"Specified element is out of bounds\");\n }\n\n data[ row * numCols + col ] += value;\n }",
"public static JasperPrint generateJasperPrint(DynamicReport dr, LayoutManager layoutManager, JRDataSource ds, Map<String, Object> _parameters) throws JRException {\n log.info(\"generating JasperPrint\");\n JasperPrint jp;\n\n\n JasperReport jr = DynamicJasperHelper.generateJasperReport(dr, layoutManager, _parameters);\n jp = JasperFillManager.fillReport(jr, _parameters, ds);\n\n return jp;\n }",
"public final void setWeekDay(WeekDay weekDay) {\n\n SortedSet<WeekDay> wds = new TreeSet<>();\n if (null != weekDay) {\n wds.add(weekDay);\n }\n setWeekDays(wds);\n\n }",
"public static int cudnnGetActivationDescriptor(\n cudnnActivationDescriptor activationDesc, \n int[] mode, \n int[] reluNanOpt, \n double[] coef)/** ceiling for clipped RELU, alpha for ELU */\n {\n return checkResult(cudnnGetActivationDescriptorNative(activationDesc, mode, reluNanOpt, coef));\n }",
"public void set(Object receiver, String fieldName, /* @Nullable */ Object value) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {\n\t\tPreconditions.checkNotNull(receiver,\"receiver\");\n\t\tPreconditions.checkNotNull(fieldName,\"fieldName\");\n\t\tClass<? extends Object> clazz = receiver.getClass();\n\t\tField f = getDeclaredField(clazz, fieldName);\n\t\tif (!f.isAccessible())\n\t\t\tf.setAccessible(true);\n\t\tf.set(receiver, value);\n\t}",
"public static List getAt(Matcher self, Collection indices) {\n List result = new ArrayList();\n for (Object value : indices) {\n if (value instanceof Range) {\n result.addAll(getAt(self, (Range) value));\n } else {\n int idx = DefaultTypeTransformation.intUnbox(value);\n result.add(getAt(self, idx));\n }\n }\n return result;\n }",
"public void open(File versionDir) {\n /* acquire modification lock */\n fileModificationLock.writeLock().lock();\n try {\n /* check that the store is currently closed */\n if(isOpen)\n throw new IllegalStateException(\"Attempt to open already open store.\");\n\n // Find version directory from symbolic link or max version id\n if(versionDir == null) {\n versionDir = ReadOnlyUtils.getCurrentVersion(storeDir);\n\n if(versionDir == null)\n versionDir = new File(storeDir, \"version-0\");\n }\n\n // Set the max version id\n long versionId = ReadOnlyUtils.getVersionId(versionDir);\n if(versionId == -1) {\n throw new VoldemortException(\"Unable to parse id from version directory \"\n + versionDir.getAbsolutePath());\n }\n Utils.mkdirs(versionDir);\n\n // Validate symbolic link, and create it if it doesn't already exist\n Utils.symlink(versionDir.getAbsolutePath(), storeDir.getAbsolutePath() + File.separator + \"latest\");\n this.fileSet = new ChunkedFileSet(versionDir, routingStrategy, nodeId, maxValueBufferAllocationSize);\n storeVersionManager.syncInternalStateFromFileSystem(false);\n this.lastSwapped = System.currentTimeMillis();\n this.isOpen = true;\n } catch(IOException e) {\n logger.error(\"Error in opening store\", e);\n } finally {\n fileModificationLock.writeLock().unlock();\n }\n }",
"ModelNode toModelNode() {\n ModelNode result = null;\n if (map != null) {\n result = new ModelNode();\n for (Map.Entry<PathAddress, ResourceData> entry : map.entrySet()) {\n ModelNode item = new ModelNode();\n PathAddress pa = entry.getKey();\n item.get(ABSOLUTE_ADDRESS).set(pa.toModelNode());\n ResourceData rd = entry.getValue();\n item.get(RELATIVE_ADDRESS).set(pa.subAddress(baseAddressLength).toModelNode());\n ModelNode attrs = new ModelNode().setEmptyList();\n if (rd.attributes != null) {\n for (String attr : rd.attributes) {\n attrs.add(attr);\n }\n }\n if (attrs.asInt() > 0) {\n item.get(FILTERED_ATTRIBUTES).set(attrs);\n }\n ModelNode children = new ModelNode().setEmptyList();\n if (rd.children != null) {\n for (PathElement pe : rd.children) {\n children.add(new Property(pe.getKey(), new ModelNode(pe.getValue())));\n }\n }\n if (children.asInt() > 0) {\n item.get(UNREADABLE_CHILDREN).set(children);\n }\n ModelNode childTypes = new ModelNode().setEmptyList();\n if (rd.childTypes != null) {\n Set<String> added = new HashSet<String>();\n for (PathElement pe : rd.childTypes) {\n if (added.add(pe.getKey())) {\n childTypes.add(pe.getKey());\n }\n }\n }\n if (childTypes.asInt() > 0) {\n item.get(FILTERED_CHILDREN_TYPES).set(childTypes);\n }\n result.add(item);\n }\n }\n return result;\n }",
"public static NodeList evaluateXpathExpression(String domStr, String xpathExpr)\n\t\t\tthrows XPathExpressionException, IOException {\n\t\tDocument dom = DomUtils.asDocument(domStr);\n\t\treturn evaluateXpathExpression(dom, xpathExpr);\n\t}"
] |
Copies the given container page to the provided root path.
@param originalPage the page to copy
@param targetPageRootPath the root path of the copy target.
@throws CmsException thrown if something goes wrong.
@throws NoCustomReplacementException if a custom replacement is not found for a type which requires it. | [
"public void copyPageOnly(CmsResource originalPage, String targetPageRootPath)\n throws CmsException, NoCustomReplacementException {\n\n if ((null == originalPage)\n || !OpenCms.getResourceManager().getResourceType(originalPage).getTypeName().equals(\n CmsResourceTypeXmlContainerPage.getStaticTypeName())) {\n throw new CmsException(new CmsMessageContainer(Messages.get(), Messages.ERR_PAGECOPY_INVALID_PAGE_0));\n }\n m_originalPage = originalPage;\n CmsObject rootCms = getRootCms();\n rootCms.copyResource(originalPage.getRootPath(), targetPageRootPath);\n CmsResource copiedPage = rootCms.readResource(targetPageRootPath, CmsResourceFilter.IGNORE_EXPIRATION);\n m_targetFolder = rootCms.readResource(CmsResource.getFolderPath(copiedPage.getRootPath()));\n replaceElements(copiedPage);\n attachLocaleGroups(copiedPage);\n tryUnlock(copiedPage);\n\n }"
] | [
"public static JsonPatch generate(final JsonNode source, final JsonNode target, ReplaceMode replaceMode) {\n requireNonNull(source, \"source\");\n requireNonNull(target, \"target\");\n final DiffProcessor processor = new DiffProcessor(replaceMode, () -> unchangedValues(source, target));\n generateDiffs(processor, EMPTY_JSON_POINTER, source, target);\n return processor.getPatch();\n }",
"public String addPostRunDependent(FunctionalTaskItem dependent) {\n Objects.requireNonNull(dependent);\n return this.taskGroup().addPostRunDependent(dependent);\n }",
"private void setFields(Map<String, FieldType> map, MapRow row, FieldContainer container)\n {\n if (row != null)\n {\n for (Map.Entry<String, FieldType> entry : map.entrySet())\n {\n container.set(entry.getValue(), row.getObject(entry.getKey()));\n }\n }\n }",
"public static BufferedImage resizeToWidth(BufferedImage originalImage, int widthOut) {\n \n int width = originalImage.getWidth();\n \n int height = originalImage.getHeight();\n \n int widthPercent = (widthOut * 100) / width;\n \n int newHeight = (height * widthPercent) / 100;\n \n BufferedImage resizedImage =\n new BufferedImage(widthOut, newHeight, BufferedImage.TYPE_INT_ARGB);\n Graphics2D g = resizedImage.createGraphics();\n g.drawImage(originalImage, 0, 0, widthOut, newHeight, null);\n g.dispose();\n \n return resizedImage;\n }",
"public static void checkEigenvalues() {\n DoubleMatrix A = new DoubleMatrix(new double[][]{\n {3.0, 2.0, 0.0},\n {2.0, 3.0, 2.0},\n {0.0, 2.0, 3.0}\n });\n\n DoubleMatrix E = new DoubleMatrix(3, 1);\n\n NativeBlas.dsyev('N', 'U', 3, A.data, 0, 3, E.data, 0);\n check(\"checking existence of dsyev...\", true);\n }",
"protected static boolean isOperatorLR( Symbol s ) {\n if( s == null )\n return false;\n\n switch( s ) {\n case ELEMENT_DIVIDE:\n case ELEMENT_TIMES:\n case ELEMENT_POWER:\n case RDIVIDE:\n case LDIVIDE:\n case TIMES:\n case POWER:\n case PLUS:\n case MINUS:\n case ASSIGN:\n return true;\n }\n return false;\n }",
"private static void alterHtmlDocs(Options opt, String outputFolder, String packageName, String className,\n\t String htmlFileName, Pattern insertPointPattern, RootDoc root) throws IOException {\n\t// setup files\n\tFile output = new File(outputFolder, packageName.replace(\".\", \"/\"));\n\tFile htmlFile = new File(output, htmlFileName);\n\tFile alteredFile = new File(htmlFile.getAbsolutePath() + \".uml\");\n\tif (!htmlFile.exists()) {\n\t System.err.println(\"Expected file not found: \" + htmlFile.getAbsolutePath());\n\t return;\n\t}\n\n\t// parse & rewrite\n\tBufferedWriter writer = null;\n\tBufferedReader reader = null;\n\tboolean matched = false;\n\ttry {\n\t writer = new BufferedWriter(new OutputStreamWriter(new\n\t\t FileOutputStream(alteredFile), opt.outputEncoding));\n\t reader = new BufferedReader(new InputStreamReader(new\n\t\t FileInputStream(htmlFile), opt.outputEncoding));\n\n\t String line;\n\t while ((line = reader.readLine()) != null) {\n\t\twriter.write(line);\n\t\twriter.newLine();\n\t\tif (!matched && insertPointPattern.matcher(line).matches()) {\n\t\t matched = true;\n\t\t\t\n\t\t String tag;\n\t\t if (opt.autoSize)\n\t\t tag = String.format(UML_AUTO_SIZED_DIV_TAG, className);\n\t\t else\n tag = String.format(UML_DIV_TAG, className);\n\t\t if (opt.collapsibleDiagrams)\n\t\t \ttag = String.format(EXPANDABLE_UML, tag, \"Show UML class diagram\", \"Hide UML class diagram\");\n\t\t writer.write(\"<!-- UML diagram added by UMLGraph version \" +\n\t\t \t\tVersion.VERSION + \n\t\t\t\t\" (http://www.spinellis.gr/umlgraph/) -->\");\n\t\t writer.newLine();\n\t\t writer.write(tag);\n\t\t writer.newLine();\n\t\t}\n\t }\n\t} finally {\n\t if (writer != null)\n\t\twriter.close();\n\t if (reader != null)\n\t\treader.close();\n\t}\n\n\t// if altered, delete old file and rename new one to the old file name\n\tif (matched) {\n\t htmlFile.delete();\n\t alteredFile.renameTo(htmlFile);\n\t} else {\n\t root.printNotice(\"Warning, could not find a line that matches the pattern '\" + insertPointPattern.pattern() \n\t\t + \"'.\\n Class diagram reference not inserted\");\n\t alteredFile.delete();\n\t}\n }",
"public static String removeOpenCmsContext(final String path) {\n\n String context = OpenCms.getSystemInfo().getOpenCmsContext();\n if (path.startsWith(context + \"/\")) {\n return path.substring(context.length());\n }\n String renderPrefix = OpenCms.getStaticExportManager().getVfsPrefix();\n if (path.startsWith(renderPrefix + \"/\")) {\n return path.substring(renderPrefix.length());\n }\n return path;\n }",
"public void prepareServer() {\n try {\n server = new Server(0);\n jettyHandler = new AbstractHandler() {\n public void handle(String target, Request req, HttpServletRequest request,\n HttpServletResponse response) throws IOException, ServletException {\n response.setContentType(\"text/plain\");\n\n String[] operands = request.getRequestURI().split(\"/\");\n\n String name = \"\";\n String command = \"\";\n String value = \"\";\n\n //operands[0] = \"\", request starts with a \"/\"\n\n if (operands.length >= 2) {\n name = operands[1];\n }\n\n if (operands.length >= 3) {\n command = operands[2];\n }\n\n if (operands.length >= 4) {\n value = operands[3];\n }\n\n if (command.equals(\"report\")) { //report a number of lines written\n response.getWriter().write(makeReport(name, value));\n } else if (command.equals(\"request\") && value.equals(\"block\")) { //request a new block of work\n response.getWriter().write(requestBlock(name));\n } else if (command.equals(\"request\") && value.equals(\"name\")) { //request a new name to report with\n response.getWriter().write(requestName());\n } else { //non recognized response\n response.getWriter().write(\"exit\");\n }\n\n ((Request) request).setHandled(true);\n }\n };\n\n server.setHandler(jettyHandler);\n\n // Select any available port\n server.start();\n Connector[] connectors = server.getConnectors();\n NetworkConnector nc = (NetworkConnector) connectors[0];\n listeningPort = nc.getLocalPort();\n hostName = InetAddress.getLocalHost().getHostName();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }"
] |
Issue the database statements to drop the table associated with a table configuration.
<p>
<b>WARNING:</b> This is [obviously] very destructive and is unrecoverable.
</p>
@param connectionSource
Associated connection source.
@param tableConfig
Hand or spring wired table configuration. If null then the class must have {@link DatabaseField}
annotations.
@param ignoreErrors
If set to true then try each statement regardless of {@link SQLException} thrown previously.
@return The number of statements executed to do so. | [
"public static <T, ID> int dropTable(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig,\n\t\t\tboolean ignoreErrors) throws SQLException {\n\t\tDatabaseType databaseType = connectionSource.getDatabaseType();\n\t\tDao<T, ID> dao = DaoManager.createDao(connectionSource, tableConfig);\n\t\tif (dao instanceof BaseDaoImpl<?, ?>) {\n\t\t\treturn doDropTable(databaseType, connectionSource, ((BaseDaoImpl<?, ?>) dao).getTableInfo(), ignoreErrors);\n\t\t} else {\n\t\t\ttableConfig.extractFieldTypes(databaseType);\n\t\t\tTableInfo<T, ID> tableInfo = new TableInfo<T, ID>(databaseType, tableConfig);\n\t\t\treturn doDropTable(databaseType, connectionSource, tableInfo, ignoreErrors);\n\t\t}\n\t}"
] | [
"public static base_responses update(nitro_service client, bridgetable resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tbridgetable updateresources[] = new bridgetable[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new bridgetable();\n\t\t\t\tupdateresources[i].bridgeage = resources[i].bridgeage;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public ResourceIterator<Node> findEntities(GraphDatabaseService executionEngine) {\n\t\tResult result = executionEngine.execute( getFindEntitiesQuery() );\n\t\treturn result.columnAs( BaseNeo4jEntityQueries.ENTITY_ALIAS );\n\t}",
"protected final boolean isValidEndTypeForPattern() {\n\n if (getEndType() == null) {\n return false;\n }\n switch (getPatternType()) {\n case DAILY:\n case WEEKLY:\n case MONTHLY:\n case YEARLY:\n return (getEndType().equals(EndType.DATE) || getEndType().equals(EndType.TIMES));\n case INDIVIDUAL:\n case NONE:\n return getEndType().equals(EndType.SINGLE);\n default:\n return false;\n }\n }",
"public static void showBooks(final ListOfBooks booksList){\n \t\n \tif(booksList != null && booksList.getBook() != null && !booksList.getBook().isEmpty()){\n \t\tList<BookType> books = booksList.getBook();\n \t\tSystem.out.println(\"\\nNumber of books: \" + books.size());\n \t\tint cnt = 0;\n \t\tfor (BookType book : books) {\n \t\t\tSystem.out.println(\"\\nBookNum: \" + (cnt++ + 1));\n \t\t\tList<PersonType> authors = book.getAuthor();\n \t\t\tif(authors != null && !authors.isEmpty()){\n \t\t\t\tfor (PersonType author : authors) {\n \t\t\t\t\tSystem.out.println(\"Author: \" + author.getFirstName() + \n \t\t\t\t\t\t\t\t\t\t\" \" + author.getLastName());\n\t\t\t\t\t}\n \t\t\t}\n \t\t\tSystem.out.println(\"Title: \" + book.getTitle());\n \t\t\tSystem.out.println(\"Year: \" + book.getYearPublished());\n \t\t\tif(book.getISBN()!=null){\n \t\t\t\tSystem.out.println(\"ISBN: \" + book.getISBN());\n \t\t\t}\n\t\t\t\t\n\t\t\t}\n \t}else{\n \t\tSystem.out.println(\"List of books is empty\");\n \t}\n \tSystem.out.println(\"\");\n\t}",
"public <V> V getAttachment(final AttachmentKey<V> key) {\n assert key != null;\n return key.cast(contextAttachments.get(key));\n }",
"@Override\n public SuggestionsInterface getSuggestionsInterface() {\n if (suggestionsInterface == null) {\n suggestionsInterface = new SuggestionsInterface(apiKey, sharedSecret, transport);\n }\n return suggestionsInterface;\n }",
"public InputStream sendRequest(String requestMethod,\n\t\t\tMap<String, String> parameters) throws IOException {\n\t\tString queryString = getQueryString(parameters);\n\t\tURL url = new URL(this.apiBaseUrl);\n\t\tHttpURLConnection connection = (HttpURLConnection) WebResourceFetcherImpl\n\t\t\t\t.getUrlConnection(url);\n\n\t\tsetupConnection(requestMethod, queryString, connection);\n\t\tOutputStreamWriter writer = new OutputStreamWriter(\n\t\t\t\tconnection.getOutputStream());\n\t\twriter.write(queryString);\n\t\twriter.flush();\n\t\twriter.close();\n\n\t\tint rc = connection.getResponseCode();\n\t\tif (rc != 200) {\n\t\t\tlogger.warn(\"Error: API request returned response code \" + rc);\n\t\t}\n\n\t\tInputStream iStream = connection.getInputStream();\n\t\tfillCookies(connection.getHeaderFields());\n\t\treturn iStream;\n\t}",
"public void spawnThread(DukeController controller, int check_interval) {\n this.controller = controller;\n timer = mgr.schedule(this, 0, check_interval * 1000); // convert to ms\n }",
"public static void acceptsFile(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_F, OPT_FILE), \"file path for input/output\")\n .withRequiredArg()\n .describedAs(\"file-path\")\n .ofType(String.class);\n }"
] |
Evaluates an EL.
@param vars the variables to be available for the evaluation.
@param el the EL string to evaluate.
@param returnType the class the EL evaluates to.
@return the evaluated EL as an instance of the specified return type.
@throws ELEvalException if the EL could not be evaluated. | [
"public <T> T eval(ELVars vars, String el, Class<T> returnType) throws ELEvalException {\n Utils.checkNotNull(vars, \"vars\");\n Utils.checkNotNull(el, \"expression\");\n Utils.checkNotNull(returnType, \"returnType\");\n VARIABLES_IN_SCOPE_TL.set(vars);\n try {\n return evaluate(vars, el, returnType);\n } finally {\n VARIABLES_IN_SCOPE_TL.set(null);\n }\n }"
] | [
"public static boolean isConstantVal(DMatrixRMaj mat , double val , double tol )\n {\n // see if the result is an identity matrix\n int index = 0;\n for( int i = 0; i < mat.numRows; i++ ) {\n for( int j = 0; j < mat.numCols; j++ ) {\n if( !(Math.abs(mat.get(index++)-val) <= tol) )\n return false;\n\n }\n }\n\n return true;\n }",
"public static List<Artifact> getAllArtifacts(final Module module){\n final List<Artifact> artifacts = new ArrayList<Artifact>();\n\n for(final Module subModule: module.getSubmodules()){\n artifacts.addAll(getAllArtifacts(subModule));\n }\n\n artifacts.addAll(module.getArtifacts());\n\n return artifacts;\n }",
"protected void createKeystore() {\n\n\t\tjava.security.cert.Certificate signingCert = null;\n\t\tPrivateKey caPrivKey = null;\n\n\t\tif(_caCert == null || _caPrivKey == null)\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tlog.debug(\"Keystore or signing cert & keypair not found. Generating...\");\n\n\t\t\t\tKeyPair caKeypair = getRSAKeyPair();\n\t\t\t\tcaPrivKey = caKeypair.getPrivate();\n\t\t\t\tsigningCert = CertificateCreator.createTypicalMasterCert(caKeypair);\n\n\t\t\t\tlog.debug(\"Done generating signing cert\");\n\t\t\t\tlog.debug(signingCert);\n\n\t\t\t\t_ks.load(null, _keystorepass);\n\n\t\t\t\t_ks.setCertificateEntry(_caCertAlias, signingCert);\n\t\t\t\t_ks.setKeyEntry(_caPrivKeyAlias, caPrivKey, _keypassword, new java.security.cert.Certificate[] {signingCert});\n\n\t\t\t\tFile caKsFile = new File(root, _caPrivateKeystore);\n\n\t\t\t\tOutputStream os = new FileOutputStream(caKsFile);\n\t\t\t\t_ks.store(os, _keystorepass);\n\n\t\t\t\tlog.debug(\"Wrote JKS keystore to: \" +\n\t\t\t\t\t\tcaKsFile.getAbsolutePath());\n\n\t\t\t\t// also export a .cer that can be imported as a trusted root\n\t\t\t\t// to disable all warning dialogs for interception\n\n\t\t\t\tFile signingCertFile = new File(root, EXPORTED_CERT_NAME);\n\n\t\t\t\tFileOutputStream cerOut = new FileOutputStream(signingCertFile);\n\n\t\t\t\tbyte[] buf = signingCert.getEncoded();\n\n\t\t\t\tlog.debug(\"Wrote signing cert to: \" + signingCertFile.getAbsolutePath());\n\n\t\t\t\tcerOut.write(buf);\n\t\t\t\tcerOut.flush();\n\t\t\t\tcerOut.close();\n\n\t\t\t\t_caCert = (X509Certificate)signingCert;\n\t\t\t\t_caPrivKey = caPrivKey;\n\t\t\t}\n\t\t\tcatch(Exception e)\n\t\t\t{\n\t\t\t\tlog.error(\"Fatal error creating/storing keystore or signing cert.\", e);\n\t\t\t\tthrow new Error(e);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlog.debug(\"Successfully loaded keystore.\");\n\t\t\tlog.debug(_caCert);\n\n\t\t}\n\n\t}",
"public IGoal[] getAgentGoals(final String agent_name, Connector connector) {\n ((IExternalAccess) connector.getAgentsExternalAccess(agent_name))\n .scheduleStep(new IComponentStep<Plan>() {\n\n public IFuture<Plan> execute(IInternalAccess ia) {\n IBDIInternalAccess bia = (IBDIInternalAccess) ia;\n\n goals = bia.getGoalbase().getGoals();\n return null;\n }\n }).get(new ThreadSuspendable());\n\n return goals;\n }",
"public void setSourceUrl(String newUrl, int id) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_SERVERS +\n \" SET \" + Constants.SERVER_REDIRECT_SRC_URL + \" = ?\" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, newUrl);\n statement.setInt(2, id);\n statement.executeUpdate();\n statement.close();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }",
"public int getIndexMin() {\n int indexMin = 0;\n double min = getEigenvalue(0).getMagnitude2();\n\n final int N = getNumberOfEigenvalues();\n for( int i = 1; i < N; i++ ) {\n double m = getEigenvalue(i).getMagnitude2();\n if( m < min ) {\n min = m;\n indexMin = i;\n }\n }\n\n return indexMin;\n }",
"public static <T, C extends Comparable<? super C>> List<T> sortBy(Iterable<T> iterable,\n\t\t\tfinal Functions.Function1<? super T, C> key) {\n\t\treturn ListExtensions.sortInplaceBy(Lists.newArrayList(iterable), key);\n\t}",
"public static final Duration getDuration(double value, TimeUnit type)\n {\n double duration;\n // Value is given in 1/10 of minute\n switch (type)\n {\n case MINUTES:\n case ELAPSED_MINUTES:\n {\n duration = value / 10;\n break;\n }\n\n case HOURS:\n case ELAPSED_HOURS:\n {\n duration = value / 600; // 60 * 10\n break;\n }\n\n case DAYS:\n {\n duration = value / 4800; // 8 * 60 * 10\n break;\n }\n\n case ELAPSED_DAYS:\n {\n duration = value / 14400; // 24 * 60 * 10\n break;\n }\n\n case WEEKS:\n {\n duration = value / 24000; // 5 * 8 * 60 * 10\n break;\n }\n\n case ELAPSED_WEEKS:\n {\n duration = value / 100800; // 7 * 24 * 60 * 10\n break;\n }\n\n case MONTHS:\n {\n duration = value / 96000; // 4 * 5 * 8 * 60 * 10\n break;\n }\n\n case ELAPSED_MONTHS:\n {\n duration = value / 432000; // 30 * 24 * 60 * 10\n break;\n }\n\n default:\n {\n duration = value;\n break;\n }\n }\n return (Duration.getInstance(duration, type));\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 }"
] |
Retrieves an integer value from the extended data.
@param type Type identifier
@return integer value | [
"public int getInt(Integer type)\n {\n int result = 0;\n\n byte[] item = m_map.get(type);\n if (item != null)\n {\n result = MPPUtility.getInt(item, 0);\n }\n\n return (result);\n }"
] | [
"public static GVRTexture loadFutureCubemapTexture(\n GVRContext gvrContext, ResourceCache<GVRImage> textureCache,\n GVRAndroidResource resource, int priority,\n Map<String, Integer> faceIndexMap) {\n GVRTexture tex = new GVRTexture(gvrContext);\n GVRImage cached = textureCache.get(resource);\n if (cached != null)\n {\n Log.v(\"ASSET\", \"Future Texture: %s loaded from cache\", cached.getFileName());\n tex.setImage(cached);\n }\n else\n {\n AsyncCubemapTexture.get().loadTexture(gvrContext,\n CancelableCallbackWrapper.wrap(GVRCubemapImage.class, tex),\n resource, priority, faceIndexMap);\n\n }\n return tex;\n }",
"public Object copy(final Object obj, final PersistenceBroker broker)\r\n {\r\n return clone(obj, IdentityMapFactory.getIdentityMap(), broker);\r\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 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 }",
"private void writeResources()\n {\n Resources resources = m_factory.createResources();\n m_plannerProject.setResources(resources);\n List<net.sf.mpxj.planner.schema.Resource> resourceList = resources.getResource();\n for (Resource mpxjResource : m_projectFile.getResources())\n {\n net.sf.mpxj.planner.schema.Resource plannerResource = m_factory.createResource();\n resourceList.add(plannerResource);\n writeResource(mpxjResource, plannerResource);\n }\n }",
"@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 static String quoteSort(Sort[] sort) {\n LinkedList<String> sorts = new LinkedList<String>();\n for (Sort pair : sort) {\n sorts.add(String.format(\"{%s: %s}\", Helpers.quote(pair.getName()), Helpers.quote(pair.getOrder().toString())));\n }\n return sorts.toString();\n }",
"public void setOptions(Doc p) {\n\tif (p == null)\n\t return;\n\n\tfor (Tag tag : p.tags(\"opt\"))\n\t setOption(StringUtil.tokenize(tag.text()));\n }\n\n /**\n * Check if the supplied string matches an entity specified\n * with the -hide parameter.\n * @return true if the string matches.\n */\n public boolean matchesHideExpression(String s) {\n\tfor (Pattern hidePattern : hidePatterns) {\n\t // micro-optimization because the \"all pattern\" is heavily used in UmlGraphDoc\n\t if(hidePattern == allPattern)\n\t\treturn true;\n\t \n\t Matcher m = hidePattern.matcher(s);\n\t if (strictMatching ? m.matches() : m.find())\n\t\treturn true;\n\t}\n\treturn false;\n }\n \n /**\n * Check if the supplied string matches an entity specified\n * with the -include parameter.\n * @return true if the string matches.\n */\n public boolean matchesIncludeExpression(String s) {\n\tfor (Pattern includePattern : includePatterns) {\n\t Matcher m = includePattern.matcher(s);\n\t if (strictMatching ? m.matches() : m.find())\n\t\treturn true;\n\t}\n\treturn false;\n }\n\n /**\n * Check if the supplied string matches an entity specified\n * with the -collpackages parameter.\n * @return true if the string matches.\n */\n public boolean matchesCollPackageExpression(String s) {\n\tfor (Pattern collPattern : collPackages) {\n\t Matcher m = collPattern.matcher(s);\n\t if (strictMatching ? m.matches() : m.find())\n\t\treturn true;\n\t}\n\treturn false;\n }\n \n // ---------------------------------------------------------------- \n // OptionProvider methods\n // ---------------------------------------------------------------- \n \n public Options getOptionsFor(ClassDoc cd) {\n\tOptions localOpt = getGlobalOptions();\n\tlocalOpt.setOptions(cd);\n\treturn localOpt;\n }\n\n public Options getOptionsFor(String name) {\n\treturn getGlobalOptions();\n }\n\n public Options getGlobalOptions() {\n\treturn (Options) clone();\n }\n\n public void overrideForClass(Options opt, ClassDoc cd) {\n\t// nothing to do\n }",
"public static Date getTime(int hour, int minutes)\n {\n Calendar cal = popCalendar();\n cal.set(Calendar.HOUR_OF_DAY, hour);\n cal.set(Calendar.MINUTE, minutes);\n cal.set(Calendar.SECOND, 0);\n Date result = cal.getTime();\n pushCalendar(cal);\n return result;\n }"
] |
Execute a Runnable on a thread pool thread
@param priority
The thread priority. Be careful with this! <blockquote>
<b>Note:</b> Use Thread.MIN_PRIORITY..Thread.MAX_PRIORITY
(1..10), <b>not</b> the Process/Linux -20..19 range!
</blockquote>
@param threadProc
The code to run. It doesn't matter if this code never returns
- by using spawn (and, hence the thread pool) there is at
least a chance that you will be reusing a thread, thus saving
teardown/startup costs.
@return A Future<?> that lets you wait for thread completion, if
necessary | [
"private static Future<?> spawn(final int priority, final Runnable threadProc) {\n return threadPool.submit(new Runnable() {\n\n @Override\n public void run() {\n Thread current = Thread.currentThread();\n int defaultPriority = current.getPriority();\n\n try {\n current.setPriority(priority);\n\n /*\n * We yield to give the foreground process a chance to run.\n * This also means that the new priority takes effect RIGHT\n * AWAY, not after the next blocking call or quantum\n * timeout.\n */\n Thread.yield();\n\n try {\n threadProc.run();\n } catch (Exception e) {\n logException(TAG, e);\n }\n } finally {\n current.setPriority(defaultPriority);\n }\n\n }\n\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 }",
"protected void addProcessedData(List<List<CRFDatum<Collection<String>, String>>> processedData, int[][][][] data,\r\n int[][] labels, int offset) {\r\n for (int i = 0, pdSize = processedData.size(); i < pdSize; i++) {\r\n int dataIndex = i + offset;\r\n List<CRFDatum<Collection<String>, String>> document = processedData.get(i);\r\n int dsize = document.size();\r\n labels[dataIndex] = new int[dsize];\r\n data[dataIndex] = new int[dsize][][];\r\n for (int j = 0; j < dsize; j++) {\r\n CRFDatum<Collection<String>, String> crfDatum = document.get(j);\r\n // add label, they are offset by extra context\r\n labels[dataIndex][j] = classIndex.indexOf(crfDatum.label());\r\n // add features\r\n List<Collection<String>> cliques = crfDatum.asFeatures();\r\n int csize = cliques.size();\r\n data[dataIndex][j] = new int[csize][];\r\n for (int k = 0; k < csize; k++) {\r\n Collection<String> features = cliques.get(k);\r\n\r\n // Debug only: Remove\r\n // if (j < windowSize) {\r\n // System.err.println(\"addProcessedData: Features Size: \" +\r\n // features.size());\r\n // }\r\n\r\n data[dataIndex][j][k] = new int[features.size()];\r\n\r\n int m = 0;\r\n try {\r\n for (String feature : features) {\r\n // System.err.println(\"feature \" + feature);\r\n // if (featureIndex.indexOf(feature)) ;\r\n if (featureIndex == null) {\r\n System.out.println(\"Feature is NULL!\");\r\n }\r\n data[dataIndex][j][k][m] = featureIndex.indexOf(feature);\r\n m++;\r\n }\r\n } catch (Exception e) {\r\n e.printStackTrace();\r\n System.err.printf(\"[index=%d, j=%d, k=%d, m=%d]\\n\", dataIndex, j, k, m);\r\n System.err.println(\"data.length \" + data.length);\r\n System.err.println(\"data[dataIndex].length \" + data[dataIndex].length);\r\n System.err.println(\"data[dataIndex][j].length \" + data[dataIndex][j].length);\r\n System.err.println(\"data[dataIndex][j][k].length \" + data[dataIndex][j].length);\r\n System.err.println(\"data[dataIndex][j][k][m] \" + data[dataIndex][j][k][m]);\r\n return;\r\n }\r\n }\r\n }\r\n }\r\n }",
"public 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 }",
"protected Method resolveTargetMethod(Message message,\n FieldDescriptor payloadField) {\n Method targetMethod = fieldToMethod.get(payloadField);\n\n if (targetMethod == null) {\n // look up and cache target method; this block is called only once\n // per target method, so synchronized is ok\n synchronized (this) {\n targetMethod = fieldToMethod.get(payloadField);\n if (targetMethod == null) {\n String name = payloadField.getName();\n for (Method method : service.getClass().getMethods()) {\n if (method.getName().equals(name)) {\n try {\n method.setAccessible(true);\n } catch (Exception ex) {\n log.log(Level.SEVERE,\"Error accessing RPC method\",ex);\n }\n\n targetMethod = method;\n fieldToMethod.put(payloadField, targetMethod);\n break;\n }\n }\n }\n }\n }\n\n if (targetMethod != null) {\n return targetMethod;\n } else {\n throw new RuntimeException(\"No matching method found by the name '\"\n + payloadField.getName() + \"'\");\n }\n }",
"private String getDynamicAttributeValue(\n CmsFile file,\n I_CmsXmlContentValue value,\n String attributeName,\n CmsEntity editedLocalEntity) {\n\n if ((null != editedLocalEntity) && (editedLocalEntity.getAttribute(attributeName) != null)) {\n getSessionCache().setDynamicValue(\n attributeName,\n editedLocalEntity.getAttribute(attributeName).getSimpleValue());\n }\n String currentValue = getSessionCache().getDynamicValue(attributeName);\n if (null != currentValue) {\n return currentValue;\n }\n if (null != file) {\n if (value.getTypeName().equals(CmsXmlDynamicCategoryValue.TYPE_NAME)) {\n List<CmsCategory> categories = new ArrayList<CmsCategory>(0);\n try {\n categories = CmsCategoryService.getInstance().readResourceCategories(getCmsObject(), file);\n } catch (CmsException e) {\n LOG.error(Messages.get().getBundle().key(Messages.ERROR_FAILED_READING_CATEGORIES_1), e);\n }\n I_CmsWidget widget = null;\n widget = CmsWidgetUtil.collectWidgetInfo(value).getWidget();\n if ((null != widget) && (widget instanceof CmsCategoryWidget)) {\n String mainCategoryPath = ((CmsCategoryWidget)widget).getStartingCategory(\n getCmsObject(),\n getCmsObject().getSitePath(file));\n StringBuffer pathes = new StringBuffer();\n for (CmsCategory category : categories) {\n if (category.getPath().startsWith(mainCategoryPath)) {\n String path = category.getBasePath() + category.getPath();\n path = getCmsObject().getRequestContext().removeSiteRoot(path);\n pathes.append(path).append(',');\n }\n }\n String dynamicConfigString = pathes.length() > 0 ? pathes.substring(0, pathes.length() - 1) : \"\";\n getSessionCache().setDynamicValue(attributeName, dynamicConfigString);\n return dynamicConfigString;\n }\n }\n }\n return \"\";\n\n }",
"public static Integer getDurationUnits(RecurringTask recurrence)\n {\n Duration duration = recurrence.getDuration();\n Integer result = null;\n\n if (duration != null)\n {\n result = UNITS_MAP.get(duration.getUnits());\n }\n\n return (result);\n }",
"public static base_response update(nitro_service client, ntpserver resource) throws Exception {\n\t\tntpserver updateresource = new ntpserver();\n\t\tupdateresource.serverip = resource.serverip;\n\t\tupdateresource.servername = resource.servername;\n\t\tupdateresource.minpoll = resource.minpoll;\n\t\tupdateresource.maxpoll = resource.maxpoll;\n\t\tupdateresource.preferredntpserver = resource.preferredntpserver;\n\t\tupdateresource.autokey = resource.autokey;\n\t\tupdateresource.key = resource.key;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public void fillRect(int x, int y, int w, int h, Color c) {\n int color = c.getRGB();\n for (int i = x; i < x + w; i++) {\n for (int j = y; j < y + h; j++) {\n setIntColor(i, j, color);\n }\n }\n }",
"protected void refresh()\r\n {\r\n if (log.isDebugEnabled())\r\n log.debug(\"Refresh this transaction for reuse: \" + this);\r\n try\r\n {\r\n // we reuse ObjectEnvelopeTable instance\r\n objectEnvelopeTable.refresh();\r\n }\r\n catch (Exception e)\r\n {\r\n if (log.isDebugEnabled())\r\n {\r\n log.debug(\"error closing object envelope table : \" + e.getMessage());\r\n e.printStackTrace();\r\n }\r\n }\r\n cleanupBroker();\r\n // clear the temporary used named roots map\r\n // we should do that, because same tx instance\r\n // could be used several times\r\n broker = null;\r\n clearRegistrationList();\r\n unmaterializedLocks.clear();\r\n txStatus = Status.STATUS_NO_TRANSACTION;\r\n }"
] |
Ensure the current throughput levels for the tracked operation does not
exceed set quota limits. Throws an exception if exceeded quota.
@param quotaKey
@param trackedOp | [
"private void checkRateLimit(String quotaKey, Tracked trackedOp) {\n String quotaValue = null;\n try {\n if(!metadataStore.getQuotaEnforcingEnabledUnlocked()) {\n return;\n }\n quotaValue = quotaStore.cacheGet(quotaKey);\n // Store may not have any quotas\n if(quotaValue == null) {\n return;\n }\n // But, if it does\n float currentRate = getThroughput(trackedOp);\n float allowedRate = Float.parseFloat(quotaValue);\n // TODO the histogram should be reasonably accurate to do all\n // these things.. (ghost qps and all)\n\n // Report the current quota usage level\n quotaStats.reportQuotaUsed(trackedOp, Utils.safeGetPercentage(currentRate, allowedRate));\n\n // check if we have exceeded rate.\n if(currentRate > allowedRate) {\n quotaStats.reportRateLimitedOp(trackedOp);\n throw new QuotaExceededException(\"Exceeded rate limit for \" + quotaKey\n + \". Maximum allowed : \" + allowedRate\n + \" Current: \" + currentRate);\n }\n } catch(NumberFormatException nfe) {\n // move on, if we cannot parse quota value properly\n logger.debug(\"Invalid formatting of quota value for key \" + quotaKey + \" : \"\n + quotaValue);\n }\n }"
] | [
"@Nonnull\n\tprivate static Properties findDefaultProperties() {\n\t\tfinal InputStream in = SourceCodeFormatter.class.getClassLoader().getResourceAsStream(DEFAULT_PROPERTIES_PATH);\n\t\tfinal Properties p = new Properties();\n\t\ttry {\n\t\t\tp.load(in);\n\t\t} catch (final IOException e) {\n\t\t\tthrow new RuntimeException(String.format(\"Can not load resource %s\", DEFAULT_PROPERTIES_PATH));\n\t\t}\n\t\treturn p;\n\t}",
"public IGoal[] getAgentGoals(final String agent_name, Connector connector) {\n ((IExternalAccess) connector.getAgentsExternalAccess(agent_name))\n .scheduleStep(new IComponentStep<Plan>() {\n\n public IFuture<Plan> execute(IInternalAccess ia) {\n IBDIInternalAccess bia = (IBDIInternalAccess) ia;\n\n goals = bia.getGoalbase().getGoals();\n return null;\n }\n }).get(new ThreadSuspendable());\n\n return goals;\n }",
"void backup() throws ConfigurationPersistenceException {\n if (!doneBootup.get()) {\n return;\n }\n try {\n if (!interactionPolicy.isReadOnly()) {\n //Move the main file to the versioned history\n moveFile(mainFile, getVersionedFile(mainFile));\n } else {\n //Copy the Last file to the versioned history\n moveFile(lastFile, getVersionedFile(mainFile));\n }\n int seq = sequence.get();\n // delete unwanted backup files\n int currentHistoryLength = getInteger(CURRENT_HISTORY_LENGTH_PROPERTY, CURRENT_HISTORY_LENGTH, 0);\n if (seq > currentHistoryLength) {\n for (int k = seq - currentHistoryLength; k > 0; k--) {\n File delete = getVersionedFile(mainFile, k);\n if (! delete.exists()) {\n break;\n }\n delete.delete();\n }\n }\n } catch (IOException e) {\n throw ControllerLogger.ROOT_LOGGER.failedToBackup(e, mainFile);\n }\n }",
"protected void processTusFiles(String assemblyUrl) throws IOException, ProtocolException {\n tusClient.setUploadCreationURL(new URL(getClient().getHostUrl() + \"/resumable/files/\"));\n tusClient.enableResuming(tusURLStore);\n\n for (Map.Entry<String, File> entry : files.entrySet()) {\n processTusFile(entry.getValue(), entry.getKey(), assemblyUrl);\n }\n\n for (Map.Entry<String, InputStream> entry : fileStreams.entrySet()) {\n processTusFile(entry.getValue(), entry.getKey(), assemblyUrl);\n }\n }",
"private void setHeaderList(Map<String, List<String>> headers, String name, String value) {\n\n List<String> values = new ArrayList<String>();\n values.add(SET_HEADER + value);\n headers.put(name, values);\n }",
"protected static void captureSystemStreams(boolean captureOut, boolean captureErr){\r\n if(captureOut){\r\n System.setOut(new RedwoodPrintStream(STDOUT, realSysOut));\r\n }\r\n if(captureErr){\r\n System.setErr(new RedwoodPrintStream(STDERR, realSysErr));\r\n }\r\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 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 void writeDurationField(String fieldName, Object value) throws IOException\n {\n if (value instanceof String)\n {\n m_writer.writeNameValuePair(fieldName + \"_text\", (String) value);\n }\n else\n {\n Duration val = (Duration) value;\n if (val.getDuration() != 0)\n {\n Duration minutes = val.convertUnits(TimeUnit.MINUTES, m_projectFile.getProjectProperties());\n long seconds = (long) (minutes.getDuration() * 60.0);\n m_writer.writeNameValuePair(fieldName, seconds);\n }\n }\n }"
] |
A regular embedded is an element that it is embedded but it is not a key or a collection.
@param keyColumnNames the column names representing the identifier of the entity
@param column the column we want to check
@return {@code true} if the column represent an attribute of a regular embedded element, {@code false} otherwise | [
"public static boolean isPartOfRegularEmbedded(String[] keyColumnNames, String column) {\n\t\treturn isPartOfEmbedded( column ) && !ArrayHelper.contains( keyColumnNames, column );\n\t}"
] | [
"private void ensureElementClassRef(CollectionDescriptorDef collDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n String arrayElementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ARRAY_ELEMENT_CLASS_REF);\r\n\r\n if (!collDef.hasProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF))\r\n {\r\n if (arrayElementClassName != null)\r\n {\r\n // we use the array element type\r\n collDef.setProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF, arrayElementClassName);\r\n }\r\n else\r\n {\r\n throw new ConstraintException(\"Collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" does not specify its element class\");\r\n }\r\n }\r\n\r\n // now checking the element type\r\n ModelDef model = (ModelDef)collDef.getOwner().getOwner();\r\n String elementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF);\r\n ClassDescriptorDef elementClassDef = model.getClass(elementClassName);\r\n\r\n if (elementClassDef == null)\r\n {\r\n throw new ConstraintException(\"Collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" references an unknown class \"+elementClassName);\r\n }\r\n if (!elementClassDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_OJB_PERSISTENT, false))\r\n {\r\n throw new ConstraintException(\"The element class \"+elementClassName+\" of the collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" is not persistent\");\r\n }\r\n if (CHECKLEVEL_STRICT.equals(checkLevel) && (arrayElementClassName != null))\r\n {\r\n // specified element class must be a subtype of the element type\r\n try\r\n {\r\n InheritanceHelper helper = new InheritanceHelper();\r\n\r\n if (!helper.isSameOrSubTypeOf(elementClassDef, arrayElementClassName, true))\r\n {\r\n throw new ConstraintException(\"The element class \"+elementClassName+\" of the collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" is not the same or a subtype of the array base type \"+arrayElementClassName);\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"Could not find the class \"+ex.getMessage()+\" on the classpath while checking the collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName());\r\n }\r\n }\r\n // we're adjusting the property to use the classloader-compatible form\r\n collDef.setProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF, elementClassDef.getName());\r\n }",
"@SuppressWarnings(\"unchecked\")\n public void updateStoreDefinitions(Versioned<byte[]> valueBytes) {\n // acquire write lock\n writeLock.lock();\n\n try {\n Versioned<String> value = new Versioned<String>(ByteUtils.getString(valueBytes.getValue(),\n \"UTF-8\"),\n valueBytes.getVersion());\n Versioned<Object> valueObject = convertStringToObject(STORES_KEY, value);\n StoreDefinitionsMapper mapper = new StoreDefinitionsMapper();\n List<StoreDefinition> storeDefinitions = (List<StoreDefinition>) valueObject.getValue();\n\n // Check for backwards compatibility\n StoreDefinitionUtils.validateSchemasAsNeeded(storeDefinitions);\n\n StoreDefinitionUtils.validateNewStoreDefsAreNonBreaking(getStoreDefList(), storeDefinitions);\n\n // Go through each store definition and do a corresponding put\n for(StoreDefinition storeDef: storeDefinitions) {\n if(!this.storeNames.contains(storeDef.getName())) {\n throw new VoldemortException(\"Cannot update a store which does not exist !\");\n }\n\n String storeDefStr = mapper.writeStore(storeDef);\n Versioned<String> versionedValueStr = new Versioned<String>(storeDefStr,\n value.getVersion());\n this.storeDefinitionsStorageEngine.put(storeDef.getName(), versionedValueStr, \"\");\n\n // Update the metadata cache\n this.metadataCache.put(storeDef.getName(),\n new Versioned<Object>(storeDefStr, value.getVersion()));\n }\n\n // Re-initialize the store definitions\n initStoreDefinitions(value.getVersion());\n\n // Update routing strategies\n // TODO: Make this more fine grained.. i.e only update listeners for\n // a specific store.\n updateRoutingStrategies(getCluster(), getStoreDefList());\n } finally {\n writeLock.unlock();\n }\n }",
"protected ValueContainer[] getAllValues(ClassDescriptor cld, Object obj) throws PersistenceBrokerException\r\n {\r\n return m_broker.serviceBrokerHelper().getAllRwValues(cld, obj);\r\n }",
"@SuppressWarnings(\"deprecation\")\n public BUILDER setAllowedValues(String ... allowedValues) {\n assert allowedValues!= null;\n this.allowedValues = new ModelNode[allowedValues.length];\n for (int i = 0; i < allowedValues.length; i++) {\n this.allowedValues[i] = new ModelNode(allowedValues[i]);\n }\n return (BUILDER) this;\n }",
"void handleAddKey() {\n\n String key = m_addKeyInput.getValue();\n if (m_listener.handleAddKey(key)) {\n Notification.show(\n key.isEmpty()\n ? m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_EMPTY_KEY_SUCCESSFULLY_ADDED_0)\n : m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_SUCCESSFULLY_ADDED_1, key));\n } else {\n CmsMessageBundleEditorTypes.showWarning(\n m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_ALREADEY_EXISTS_CAPTION_0),\n m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_ALREADEY_EXISTS_DESCRIPTION_1, key));\n\n }\n m_addKeyInput.focus();\n m_addKeyInput.selectAll();\n }",
"public MaterialAccount getAccountAtCurrentPosition(int position) {\n\n if (position < 0 || position >= accountManager.size())\n throw new RuntimeException(\"Account Index Overflow\");\n\n return findAccountNumber(position);\n }",
"private static int readObjectData(int offset, String text, List<RTFEmbeddedObject> objects)\n {\n LinkedList<byte[]> blocks = new LinkedList<byte[]>();\n\n offset += (OBJDATA.length());\n offset = skipEndOfLine(text, offset);\n int length;\n int lastOffset = offset;\n\n while (offset != -1)\n {\n length = getBlockLength(text, offset);\n lastOffset = readDataBlock(text, offset, length, blocks);\n offset = skipEndOfLine(text, lastOffset);\n }\n\n RTFEmbeddedObject headerObject;\n RTFEmbeddedObject dataObject;\n\n while (blocks.isEmpty() == false)\n {\n headerObject = new RTFEmbeddedObject(blocks, 2);\n objects.add(headerObject);\n\n if (blocks.isEmpty() == false)\n {\n dataObject = new RTFEmbeddedObject(blocks, headerObject.getTypeFlag2());\n objects.add(dataObject);\n }\n }\n\n return (lastOffset);\n }",
"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}",
"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 }"
] |
Move this rectangle to the specified bottom-left point.
@param rect rectangle to move
@param x new x origin
@param y new y origin | [
"public void moveRectangleTo(Rectangle rect, float x, float y) {\n\t\tfloat width = rect.getWidth();\n\t\tfloat height = rect.getHeight();\n\t\trect.setLeft(x);\n\t\trect.setBottom(y);\n\t\trect.setRight(rect.getLeft() + width);\n\t\trect.setTop(rect.getBottom() + height);\n\t}"
] | [
"public String getToken() {\n String id = null == answer ? text : answer;\n return Act.app().crypto().generateToken(id);\n }",
"private void addServer(CmsSiteMatcher matcher, CmsSite site) {\n\n Map<CmsSiteMatcher, CmsSite> siteMatcherSites = new HashMap<CmsSiteMatcher, CmsSite>(m_siteMatcherSites);\n siteMatcherSites.put(matcher, site);\n setSiteMatcherSites(siteMatcherSites);\n }",
"@Override\n public List<ConfigIssue> init(Service.Context context) {\n this.context = context;\n return init();\n }",
"public static auditmessages[] get(nitro_service service, auditmessages_args args) throws Exception{\n\t\tauditmessages obj = new auditmessages();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tauditmessages[] response = (auditmessages[])obj.get_resources(service, option);\n\t\treturn response;\n\t}",
"public static authenticationnegotiatepolicy_binding get(nitro_service service, String name) throws Exception{\n\t\tauthenticationnegotiatepolicy_binding obj = new authenticationnegotiatepolicy_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationnegotiatepolicy_binding response = (authenticationnegotiatepolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static final String getString(InputStream is) throws IOException\n {\n int type = is.read();\n if (type != 1)\n {\n throw new IllegalArgumentException(\"Unexpected string format\");\n }\n\n Charset charset = CharsetHelper.UTF8;\n \n int length = is.read();\n if (length == 0xFF)\n {\n length = getShort(is);\n if (length == 0xFFFE)\n {\n charset = CharsetHelper.UTF16LE;\n length = (is.read() * 2);\n }\n }\n\n String result;\n if (length == 0)\n {\n result = null;\n }\n else\n {\n byte[] stringData = new byte[length]; \n is.read(stringData);\n result = new String(stringData, charset);\n }\n return result;\n }",
"public static XClass getMemberType() throws XDocletException\r\n {\r\n if (getCurrentField() != null) {\r\n return getCurrentField().getType();\r\n }\r\n else if (getCurrentMethod() != null) {\r\n XMethod method = getCurrentMethod();\r\n\r\n if (MethodTagsHandler.isGetterMethod(method)) {\r\n return method.getReturnType().getType();\r\n }\r\n else if (MethodTagsHandler.isSetterMethod(method)) {\r\n XParameter param = (XParameter)method.getParameters().iterator().next();\r\n\r\n return param.getType();\r\n }\r\n }\r\n return null;\r\n }",
"public void attachHoursToDay(ProjectCalendarHours hours)\n {\n if (hours.getParentCalendar() != this)\n {\n throw new IllegalArgumentException();\n }\n m_hours[hours.getDay().getValue() - 1] = hours;\n }",
"public void setJdbcLevel(String jdbcLevel)\r\n {\r\n if (jdbcLevel != null)\r\n {\r\n try\r\n {\r\n double intLevel = Double.parseDouble(jdbcLevel);\r\n setJdbcLevel(intLevel);\r\n }\r\n catch(NumberFormatException nfe)\r\n {\r\n setJdbcLevel(2.0);\r\n logger.info(\"Specified JDBC level was not numeric (Value=\" + jdbcLevel + \"), used default jdbc level of 2.0 \");\r\n }\r\n }\r\n else\r\n {\r\n setJdbcLevel(2.0);\r\n logger.info(\"Specified JDBC level was null, used default jdbc level of 2.0 \");\r\n }\r\n }"
] |
returns an Enumeration of PrimaryKey Objects for objects of class DataClass.
The Elements returned come from a SELECT ... WHERE Statement
that is defined by the fields and their coresponding values of listFields
and listValues.
Useful for EJB Finder Methods...
@param primaryKeyClass the pk class for the searched objects
@param query the query | [
"public Enumeration getPKEnumerationByQuery(Class primaryKeyClass, Query query) throws PersistenceBrokerException\n {\n if (logger.isDebugEnabled()) logger.debug(\"getPKEnumerationByQuery \" + query);\n\n query.setFetchSize(1);\n ClassDescriptor cld = getClassDescriptor(query.getSearchClass());\n return new PkEnumeration(query, cld, primaryKeyClass, this);\n }"
] | [
"public void addMarker(Marker marker) {\n if (markers == null) {\n markers = new HashSet<>();\n }\n markers.add(marker);\n marker.setMap(this);\n }",
"public static <T> Set<T> toSet(Iterator<? extends T> iterator) {\n\t\treturn Sets.newLinkedHashSet(toIterable(iterator));\n\t}",
"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}",
"public GVRAnimation setOnFinish(GVROnFinish callback) {\n mOnFinish = callback;\n\n // Do the instance-of test at set-time, not at use-time\n mOnRepeat = callback instanceof GVROnRepeat ? (GVROnRepeat) callback\n : null;\n if (mOnRepeat != null) {\n mRepeatCount = -1; // loop until iterate() returns false\n }\n return this;\n }",
"public AreaOfInterest copy() {\n AreaOfInterest aoi = new AreaOfInterest();\n aoi.display = this.display;\n aoi.area = this.area;\n aoi.polygon = this.polygon;\n aoi.style = this.style;\n aoi.renderAsSvg = this.renderAsSvg;\n return aoi;\n }",
"public void clearMarkers() {\n if (markers != null && !markers.isEmpty()) {\n markers.forEach((m) -> {\n m.setMap(null);\n });\n markers.clear();\n }",
"public static base_response update(nitro_service client, autoscaleprofile resource) throws Exception {\n\t\tautoscaleprofile updateresource = new autoscaleprofile();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.url = resource.url;\n\t\tupdateresource.apikey = resource.apikey;\n\t\tupdateresource.sharedsecret = resource.sharedsecret;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public AsciiTable setPaddingRight(int paddingRight) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingRight(paddingRight);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public static java.sql.Time rollTime(java.util.Date startDate, int period, int amount) {\n GregorianCalendar gc = new GregorianCalendar();\n gc.setTime(startDate);\n gc.add(period, amount);\n return new java.sql.Time(gc.getTime().getTime());\n }"
] |
Use this API to export appfwlearningdata resources. | [
"public static base_responses export(nitro_service client, appfwlearningdata resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tappfwlearningdata exportresources[] = new appfwlearningdata[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\texportresources[i] = new appfwlearningdata();\n\t\t\t\texportresources[i].profilename = resources[i].profilename;\n\t\t\t\texportresources[i].securitycheck = resources[i].securitycheck;\n\t\t\t\texportresources[i].target = resources[i].target;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, exportresources,\"export\");\n\t\t}\n\t\treturn result;\n\t}"
] | [
"private Map<String, String> toPayload(Map<String, Object> data) throws LocalOperationException {\n Map<String, Object> dataClone = new HashMap<String, Object>(data);\n dataClone.put(\"auth\", getAuthData());\n\n Map<String, String> payload = new HashMap<String, String>();\n payload.put(\"params\", jsonifyData(dataClone));\n\n if (transloadit.shouldSignRequest) {\n payload.put(\"signature\", getSignature(jsonifyData(dataClone)));\n }\n return payload;\n }",
"public static void scanClassPathForFormattingAnnotations() {\n\n\t\tExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);\n\n\t\t// scan classpath and filter out classes that don't begin with \"com.nds\"\n\t\tReflections reflections = new Reflections(\"com.nds\",\"com.cisco\");\n\n\t\tSet<Class<?>> annotated = reflections.getTypesAnnotatedWith(DefaultFormat.class);\n\n// Reflections ciscoReflections = new Reflections(\"com.cisco\");\n//\n// annotated.addAll(ciscoReflections.getTypesAnnotatedWith(DefaultFormat.class));\n\n\t\tfor (Class<?> markerClass : annotated) {\n\n\t\t\t// if the marker class is indeed implementing FoundationLoggingMarker\n\t\t\t// interface\n\t\t\tif (FoundationLoggingMarker.class.isAssignableFrom(markerClass)) {\n\n\t\t\t\tfinal Class<? extends FoundationLoggingMarker> clazz = (Class<? extends FoundationLoggingMarker>) markerClass;\n\n\t\t\t\texecutorService.execute(new Runnable() {\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void run() {\n\n\t\t\t\t\t\tif (markersMap.get(clazz) == null) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t// generate formatter class for this marker\n\t\t\t\t\t\t\t\t// class\n\t\t\t\t\t\t\t\tgenerateAndUpdateFormatterInMap(clazz);\n\t\t\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t\t\tLOGGER.trace(\"problem generating formatter class from static scan method. error is: \" + e.toString());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t} else {// if marker class does not implement FoundationLoggingMarker\n\t\t\t\t\t// interface, log ERROR\n\n\t\t\t\t// verify the LOGGER was initialized. It might not be as this\n\t\t\t\t// Method is called in a static block\n\t\t\t\tif (LOGGER == null) {\n\t\t\t\t\tLOGGER = LoggerFactory.getLogger(AbstractFoundationLoggingMarker.class);\n\t\t\t\t}\n\t\t\t\tLOGGER.error(\"Formatter annotations should only appear on foundationLoggingMarker implementations\");\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\tTimeUnit.SECONDS.sleep(30);\n\t\t} catch (InterruptedException e) {\n\t\t\tLOGGER.trace(e.toString(), e);\n\t\t}\n\t\texecutorService.shutdown();\n\t\t// try {\n\t\t// executorService.awaitTermination(15, TimeUnit.SECONDS);\n\t\t// } catch (InterruptedException e) {\n\t\t// LOGGER.error(\"creation of formatters has been interrupted\");\n\t\t// }\n\t}",
"public String toDottedString() {\r\n\t\tString result = null;\r\n\t\tif(hasNoStringCache() || (result = getStringCache().dottedString) == null) {\r\n\t\t\tAddressDivisionGrouping dottedGrouping = getDottedGrouping();\r\n\t\t\tgetStringCache().dottedString = result = toNormalizedString(MACStringCache.dottedParams, dottedGrouping);\r\n\t\t}\r\n\t\treturn result;\r\n\t}",
"public TransactionImpl getCurrentTransaction()\r\n {\r\n TransactionImpl tx = tx_table.get(Thread.currentThread());\r\n if(tx == null)\r\n {\r\n throw new TransactionNotInProgressException(\"Calling method needed transaction, but no transaction found for current thread :-(\");\r\n }\r\n return tx;\r\n }",
"public static Field getField(Class clazz, String fieldName)\r\n {\r\n try\r\n {\r\n return clazz.getField(fieldName);\r\n }\r\n catch (Exception ignored)\r\n {}\r\n return null;\r\n }",
"private static void addFormatInfoEval(byte[] eval, int size, EccLevel ecc_level, int pattern) {\n\n int format = pattern;\n int seq;\n int i;\n\n switch(ecc_level) {\n case L: format += 0x08; break;\n case Q: format += 0x18; break;\n case H: format += 0x10; break;\n }\n\n seq = QR_ANNEX_C[format];\n\n for (i = 0; i < 6; i++) {\n eval[(i * size) + 8] = (byte) ((((seq >> i) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);\n }\n\n for (i = 0; i < 8; i++) {\n eval[(8 * size) + (size - i - 1)] = (byte) ((((seq >> i) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);\n }\n\n for (i = 0; i < 6; i++) {\n eval[(8 * size) + (5 - i)] = (byte) ((((seq >> (i + 9)) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);\n }\n\n for (i = 0; i < 7; i++) {\n eval[(((size - 7) + i) * size) + 8] = (byte) ((((seq >> (i + 8)) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);\n }\n\n eval[(7 * size) + 8] = (byte) ((((seq >> 6) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);\n eval[(8 * size) + 8] = (byte) ((((seq >> 7) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);\n eval[(8 * size) + 7] = (byte) ((((seq >> 8) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);\n }",
"private void handleGetVersionResponse(SerialMessage incomingMessage) {\n\t\tthis.ZWaveLibraryType = incomingMessage.getMessagePayloadByte(12);\n\t\tthis.zWaveVersion = new String(ArrayUtils.subarray(incomingMessage.getMessagePayload(), 0, 11));\n\t\tlogger.debug(String.format(\"Got MessageGetVersion response. Version = %s, Library Type = 0x%02X\", zWaveVersion, ZWaveLibraryType));\n\t}",
"public CollectionDescriptorDef getCollection(String name)\r\n {\r\n CollectionDescriptorDef collDef = null;\r\n\r\n for (Iterator it = _collections.iterator(); it.hasNext(); )\r\n {\r\n collDef = (CollectionDescriptorDef)it.next();\r\n if (collDef.getName().equals(name))\r\n {\r\n return collDef;\r\n }\r\n }\r\n return null;\r\n }",
"public void setAttribute(final String name, final Attribute attribute) {\n if (name.equals(MAP_KEY)) {\n this.mapAttribute = (MapAttribute) attribute;\n }\n }"
] |
Returns the arguments as a list in their command line form.
@return the arguments for the command line | [
"public List<String> asList() {\n final List<String> result = new ArrayList<>();\n for (Collection<Argument> args : map.values()) {\n for (Argument arg : args) {\n result.add(arg.asCommandLineArgument());\n }\n }\n return result;\n }"
] | [
"public static DMatrixRMaj triangularUpper(int dimen , int hessenberg , double min , double max , Random rand )\n {\n if( hessenberg < 0 )\n throw new RuntimeException(\"hessenberg must be more than or equal to 0\");\n\n double range = max-min;\n\n DMatrixRMaj A = new DMatrixRMaj(dimen,dimen);\n\n for( int i = 0; i < dimen; i++ ) {\n int start = i <= hessenberg ? 0 : i-hessenberg;\n\n for( int j = start; j < dimen; j++ ) {\n A.set(i,j, rand.nextDouble()*range+min);\n }\n\n }\n\n return A;\n }",
"protected void mergeSameWork(LinkedList<TimephasedWork> list)\n {\n LinkedList<TimephasedWork> result = new LinkedList<TimephasedWork>();\n\n TimephasedWork previousAssignment = null;\n for (TimephasedWork assignment : list)\n {\n if (previousAssignment == null)\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n result.add(assignment);\n }\n else\n {\n Duration previousAssignmentWork = previousAssignment.getAmountPerDay();\n Duration assignmentWork = assignment.getTotalAmount();\n\n if (NumberHelper.equals(previousAssignmentWork.getDuration(), assignmentWork.getDuration(), 0.01))\n {\n Date assignmentStart = previousAssignment.getStart();\n Date assignmentFinish = assignment.getFinish();\n double total = previousAssignment.getTotalAmount().getDuration();\n total += assignmentWork.getDuration();\n Duration totalWork = Duration.getInstance(total, TimeUnit.MINUTES);\n\n TimephasedWork merged = new TimephasedWork();\n merged.setStart(assignmentStart);\n merged.setFinish(assignmentFinish);\n merged.setAmountPerDay(assignmentWork);\n merged.setTotalAmount(totalWork);\n\n result.removeLast();\n assignment = merged;\n }\n else\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n }\n result.add(assignment);\n }\n\n previousAssignment = assignment;\n }\n\n list.clear();\n list.addAll(result);\n }",
"private void lockOnChange(Object propertyId) throws CmsException {\n\n if (isDescriptorProperty(propertyId)) {\n lockDescriptor();\n } else {\n Locale l = m_bundleType.equals(BundleType.PROPERTY) ? m_locale : null;\n lockLocalization(l);\n }\n\n }",
"public ProjectCalendar getByName(String calendarName)\n {\n ProjectCalendar calendar = null;\n\n if (calendarName != null && calendarName.length() != 0)\n {\n Iterator<ProjectCalendar> iter = iterator();\n while (iter.hasNext() == true)\n {\n calendar = iter.next();\n String name = calendar.getName();\n\n if ((name != null) && (name.equalsIgnoreCase(calendarName) == true))\n {\n break;\n }\n\n calendar = null;\n }\n }\n\n return (calendar);\n }",
"public static URL asUrlOrResource(String s) {\n if (Strings.isNullOrEmpty(s)) {\n return null;\n }\n\n try {\n return new URL(s);\n } catch (MalformedURLException e) {\n //If its not a valid URL try to treat it as a local resource.\n return findConfigResource(s);\n }\n }",
"public double getValueWithGivenYield(double evaluationTime, double rate, AnalyticModel model) {\n\t\tDiscountCurve referenceCurve = DiscountCurveInterpolation.createDiscountCurveFromDiscountFactors(\"referenceCurve\", new double[] {0.0, 1.0}, new double[] {1.0, 1.0});\n\t\treturn getValueWithGivenSpreadOverCurve(evaluationTime, referenceCurve, rate, model);\n\t}",
"public static String getDumpFileWebDirectory(\n\t\t\tDumpContentType dumpContentType, String projectName) {\n\t\tif (dumpContentType == DumpContentType.JSON) {\n\t\t\tif (\"wikidatawiki\".equals(projectName)) {\n\t\t\t\treturn WmfDumpFile.DUMP_SITE_BASE_URL\n\t\t\t\t\t\t+ WmfDumpFile.WEB_DIRECTORY.get(dumpContentType)\n\t\t\t\t\t\t+ \"wikidata\" + \"/\";\n\t\t\t} else {\n\t\t\t\tthrow new RuntimeException(\n\t\t\t\t\t\t\"Wikimedia Foundation uses non-systematic directory names for this type of dump file.\"\n\t\t\t\t\t\t\t\t+ \" I don't know where to find dumps of project \"\n\t\t\t\t\t\t\t\t+ projectName);\n\t\t\t}\n\t\t} else if (WmfDumpFile.WEB_DIRECTORY.containsKey(dumpContentType)) {\n\t\t\treturn WmfDumpFile.DUMP_SITE_BASE_URL\n\t\t\t\t\t+ WmfDumpFile.WEB_DIRECTORY.get(dumpContentType)\n\t\t\t\t\t+ projectName + \"/\";\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\"Unsupported dump type \"\n\t\t\t\t\t+ dumpContentType);\n\t\t}\n\t}",
"private void deleteBackups() {\n File[] storeDirList = ReadOnlyUtils.getVersionDirs(storeDir, 0L, getCurrentVersionId());\n if(storeDirList != null && storeDirList.length > (numBackups + 1)) {\n // delete ALL old directories asynchronously\n File[] extraBackups = ReadOnlyUtils.findKthVersionedDir(storeDirList,\n 0,\n storeDirList.length\n - (numBackups + 1) - 1);\n if(extraBackups != null) {\n for(File backUpFile: extraBackups) {\n deleteAsync(backUpFile);\n }\n }\n }\n }",
"public CollectionValuedMap<K, V> deltaClone() {\r\n CollectionValuedMap<K, V> result = new CollectionValuedMap<K, V>(null, cf, true);\r\n result.map = new DeltaMap<K, Collection<V>>(this.map);\r\n return result;\r\n }"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.