query
stringlengths 7
3.3k
| positive
sequencelengths 1
1
| negative
sequencelengths 9
9
|
---|---|---|
This method extracts data for a single resource from a Phoenix file.
@param phoenixResource resource data
@return Resource instance | [
"private Resource readResource(net.sf.mpxj.phoenix.schema.Project.Storepoints.Storepoint.Resources.Resource phoenixResource)\n {\n Resource mpxjResource = m_projectFile.addResource();\n\n TimeUnit rateUnits = phoenixResource.getMonetarybase();\n if (rateUnits == null)\n {\n rateUnits = TimeUnit.HOURS;\n }\n\n // phoenixResource.getMaximum()\n mpxjResource.setCostPerUse(phoenixResource.getMonetarycostperuse());\n mpxjResource.setStandardRate(new Rate(phoenixResource.getMonetaryrate(), rateUnits));\n mpxjResource.setStandardRateUnits(rateUnits);\n mpxjResource.setName(phoenixResource.getName());\n mpxjResource.setType(phoenixResource.getType());\n mpxjResource.setMaterialLabel(phoenixResource.getUnitslabel());\n //phoenixResource.getUnitsperbase()\n mpxjResource.setGUID(phoenixResource.getUuid());\n\n m_eventManager.fireResourceReadEvent(mpxjResource);\n\n return mpxjResource;\n }"
] | [
"public boolean getNumericBoolean(int field)\n {\n boolean result = false;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n result = Integer.parseInt(m_fields[field]) == 1;\n }\n\n return (result);\n }",
"private void readNormalDay(ProjectCalendar calendar, Project.Calendars.Calendar.WeekDays.WeekDay weekDay)\n {\n int dayNumber = weekDay.getDayType().intValue();\n Day day = Day.getInstance(dayNumber);\n calendar.setWorkingDay(day, BooleanHelper.getBoolean(weekDay.isDayWorking()));\n ProjectCalendarHours hours = calendar.addCalendarHours(day);\n\n Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes times = weekDay.getWorkingTimes();\n if (times != null)\n {\n for (Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime period : times.getWorkingTime())\n {\n Date startTime = period.getFromTime();\n Date endTime = period.getToTime();\n\n if (startTime != null && endTime != null)\n {\n if (startTime.getTime() >= endTime.getTime())\n {\n endTime = DateHelper.addDays(endTime, 1);\n }\n\n hours.addRange(new DateRange(startTime, endTime));\n }\n }\n }\n }",
"public static void checkRequired(OptionSet options, List<String> opts)\n throws VoldemortException {\n List<String> optCopy = Lists.newArrayList();\n for(String opt: opts) {\n if(options.has(opt)) {\n optCopy.add(opt);\n }\n }\n if(optCopy.size() < 1) {\n System.err.println(\"Please specify one of the following options:\");\n for(String opt: opts) {\n System.err.println(\"--\" + opt);\n }\n Utils.croak(\"Missing required option.\");\n }\n if(optCopy.size() > 1) {\n System.err.println(\"Conflicting options:\");\n for(String opt: optCopy) {\n System.err.println(\"--\" + opt);\n }\n Utils.croak(\"Conflicting options detected.\");\n }\n }",
"private void populateDefaultSettings(Record record, ProjectProperties properties) throws MPXJException\n {\n properties.setDefaultDurationUnits(record.getTimeUnit(0));\n properties.setDefaultDurationIsFixed(record.getNumericBoolean(1));\n properties.setDefaultWorkUnits(record.getTimeUnit(2));\n properties.setMinutesPerDay(Double.valueOf(NumberHelper.getDouble(record.getFloat(3)) * 60));\n properties.setMinutesPerWeek(Double.valueOf(NumberHelper.getDouble(record.getFloat(4)) * 60));\n properties.setDefaultStandardRate(record.getRate(5));\n properties.setDefaultOvertimeRate(record.getRate(6));\n properties.setUpdatingTaskStatusUpdatesResourceStatus(record.getNumericBoolean(7));\n properties.setSplitInProgressTasks(record.getNumericBoolean(8));\n }",
"public static sslvserver_sslcertkey_binding[] get(nitro_service service, String vservername) throws Exception{\n\t\tsslvserver_sslcertkey_binding obj = new sslvserver_sslcertkey_binding();\n\t\tobj.set_vservername(vservername);\n\t\tsslvserver_sslcertkey_binding response[] = (sslvserver_sslcertkey_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"protected void load()\r\n {\r\n properties = new Properties();\r\n\r\n String filename = getFilename();\r\n \r\n try\r\n {\r\n URL url = ClassHelper.getResource(filename);\r\n\r\n if (url == null)\r\n {\r\n url = (new File(filename)).toURL();\r\n }\r\n\r\n logger.info(\"Loading OJB's properties: \" + url);\r\n\r\n URLConnection conn = url.openConnection();\r\n conn.setUseCaches(false);\r\n conn.connect();\r\n InputStream strIn = conn.getInputStream();\r\n properties.load(strIn);\r\n strIn.close();\r\n }\r\n catch (FileNotFoundException ex)\r\n {\r\n // [tomdz] If the filename is explicitly reset (null or empty string) then we'll\r\n // output an info message because the user did this on purpose\r\n // Otherwise, we'll output a warning\r\n if ((filename == null) || (filename.length() == 0))\r\n {\r\n logger.info(\"Starting OJB without a properties file. OJB is using default settings instead.\");\r\n }\r\n else\r\n {\r\n logger.warn(\"Could not load properties file '\"+filename+\"'. Using default settings!\", ex);\r\n }\r\n // [tomdz] There seems to be no use of this setting ?\r\n //properties.put(\"valid\", \"false\");\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new MetadataException(\"An error happend while loading the properties file '\"+filename+\"'\", ex);\r\n }\r\n }",
"public void associateTypeJndiResource(JNDIResourceModel resource, String type)\n {\n if (type == null || resource == null)\n {\n return;\n }\n\n if (StringUtils.equals(type, \"javax.sql.DataSource\") && !(resource instanceof DataSourceModel))\n {\n DataSourceModel ds = GraphService.addTypeToModel(this.getGraphContext(), resource, DataSourceModel.class);\n }\n else if (StringUtils.equals(type, \"javax.jms.Queue\") && !(resource instanceof JmsDestinationModel))\n {\n JmsDestinationModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsDestinationModel.class);\n jms.setDestinationType(JmsDestinationType.QUEUE);\n }\n else if (StringUtils.equals(type, \"javax.jms.QueueConnectionFactory\") && !(resource instanceof JmsConnectionFactoryModel))\n {\n JmsConnectionFactoryModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsConnectionFactoryModel.class);\n jms.setConnectionFactoryType(JmsDestinationType.QUEUE);\n }\n else if (StringUtils.equals(type, \"javax.jms.Topic\") && !(resource instanceof JmsDestinationModel))\n {\n JmsDestinationModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsDestinationModel.class);\n jms.setDestinationType(JmsDestinationType.TOPIC);\n }\n else if (StringUtils.equals(type, \"javax.jms.TopicConnectionFactory\") && !(resource instanceof JmsConnectionFactoryModel))\n {\n JmsConnectionFactoryModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsConnectionFactoryModel.class);\n jms.setConnectionFactoryType(JmsDestinationType.TOPIC);\n }\n }",
"public static final Bytes of(String s) {\n Objects.requireNonNull(s);\n if (s.isEmpty()) {\n return EMPTY;\n }\n byte[] data = s.getBytes(StandardCharsets.UTF_8);\n return new Bytes(data, s);\n }",
"private void processRedirect(String stringStatusCode,\n HttpMethod httpMethodProxyRequest,\n HttpServletRequest httpServletRequest,\n HttpServletResponse httpServletResponse) throws Exception {\n // Check if the proxy response is a redirect\n // The following code is adapted from\n // org.tigris.noodle.filters.CheckForRedirect\n // Hooray for open source software\n\n String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();\n if (stringLocation == null) {\n throw new ServletException(\"Received status code: \"\n + stringStatusCode + \" but no \"\n + STRING_LOCATION_HEADER\n + \" header was found in the response\");\n }\n // Modify the redirect to go to this proxy servlet rather than the proxied host\n String stringMyHostName = httpServletRequest.getServerName();\n if (httpServletRequest.getServerPort() != 80) {\n stringMyHostName += \":\" + httpServletRequest.getServerPort();\n }\n stringMyHostName += httpServletRequest.getContextPath();\n httpServletResponse.sendRedirect(stringLocation.replace(\n getProxyHostAndPort() + this.getProxyPath(),\n stringMyHostName));\n }"
] |
When set to true, all items in layout will be considered having the size of the largest child. If false, all items are
measured normally. Disabled by default.
@param enable true to measure children using the size of the largest child, false - otherwise. | [
"public void enableUniformSize(final boolean enable) {\n if (mUniformSize != enable) {\n mUniformSize = enable;\n if (mContainer != null) {\n mContainer.onLayoutChanged(this);\n }\n }\n }"
] | [
"public boolean shouldNotCache(String requestUri) {\n\t\tString uri = requestUri.toLowerCase();\n\t\treturn checkContains(uri, noCacheIdentifiers) || checkSuffixes(uri, noCacheSuffixes);\n\t}",
"public MediaType removeQualityValue() {\n\t\tif (!this.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.remove(PARAM_QUALITY_FACTOR);\n\t\treturn new MediaType(this, params);\n\t}",
"private String writeSchemata(File dir) throws IOException\r\n {\r\n writeCompressedTexts(dir, _torqueSchemata);\r\n\r\n StringBuffer includes = new StringBuffer();\r\n\r\n for (Iterator it = _torqueSchemata.keySet().iterator(); it.hasNext();)\r\n {\r\n includes.append((String)it.next());\r\n if (it.hasNext())\r\n {\r\n includes.append(\",\");\r\n }\r\n }\r\n return includes.toString();\r\n }",
"protected void onLegendDataChanged() {\n\n int legendCount = mLegendList.size();\n float margin = (mGraphWidth / legendCount);\n float currentOffset = 0;\n\n for (LegendModel model : mLegendList) {\n model.setLegendBounds(new RectF(currentOffset, 0, currentOffset + margin, mLegendHeight));\n currentOffset += margin;\n }\n\n Utils.calculateLegendInformation(mLegendList, 0, mGraphWidth, mLegendPaint);\n\n invalidateGlobal();\n }",
"public static double Sinh(double x, int nTerms) {\r\n if (nTerms < 2) return x;\r\n if (nTerms == 2) {\r\n return x + (x * x * x) / 6D;\r\n } else {\r\n\r\n double mult = x * x * x;\r\n double fact = 6;\r\n int factS = 5;\r\n double result = x + mult / fact;\r\n for (int i = 3; i <= nTerms; i++) {\r\n mult *= x * x;\r\n fact *= factS * (factS - 1);\r\n factS += 2;\r\n result += mult / fact;\r\n }\r\n\r\n return result;\r\n }\r\n }",
"private List<String> processAllListeners(View rootView) {\n List<String> refinementAttributes = new ArrayList<>();\n\n // Register any AlgoliaResultsListener (unless it has a different variant than searcher)\n final List<AlgoliaResultsListener> resultListeners = LayoutViews.findByClass((ViewGroup) rootView, AlgoliaResultsListener.class);\n if (resultListeners.isEmpty()) {\n throw new IllegalStateException(Errors.LAYOUT_MISSING_RESULT_LISTENER);\n }\n for (AlgoliaResultsListener listener : resultListeners) {\n if (!this.resultListeners.contains(listener)) {\n final String variant = BindingHelper.getVariantForView((View) listener);\n if (variant == null || searcher.variant.equals(variant)) {\n this.resultListeners.add(listener);\n searcher.registerResultListener(listener);\n prepareWidget(listener, refinementAttributes);\n }\n }\n }\n\n // Register any AlgoliaErrorListener (unless it has a different variant than searcher)\n final List<AlgoliaErrorListener> errorListeners = LayoutViews.findByClass((ViewGroup) rootView, AlgoliaErrorListener.class);\n for (AlgoliaErrorListener listener : errorListeners) {\n if (!this.errorListeners.contains(listener)) {\n final String variant = BindingHelper.getVariantForView((View) listener);\n if (variant == null || searcher.variant.equals(variant)) {\n this.errorListeners.add(listener);\n }\n }\n searcher.registerErrorListener(listener);\n prepareWidget(listener, refinementAttributes);\n }\n\n // Register any AlgoliaSearcherListener (unless it has a different variant than searcher)\n final List<AlgoliaSearcherListener> searcherListeners = LayoutViews.findByClass((ViewGroup) rootView, AlgoliaSearcherListener.class);\n for (AlgoliaSearcherListener listener : searcherListeners) {\n final String variant = BindingHelper.getVariantForView((View) listener);\n if (variant == null || searcher.variant.equals(variant)) {\n listener.initWithSearcher(searcher);\n prepareWidget(listener, refinementAttributes);\n }\n }\n\n return refinementAttributes;\n }",
"public ClassNode annotatedWith(String name) {\n ClassNode anno = infoBase.node(name);\n this.annotations.add(anno);\n anno.annotated.add(this);\n return this;\n }",
"@Override\n public boolean accept(File file) {\n //All directories are added in the least that can be read by the Application\n if (file.isDirectory()&&file.canRead())\n { return true;\n }\n else if(properties.selection_type==DialogConfigs.DIR_SELECT)\n { /* True for files, If the selection type is Directory type, ie.\n * Only directory has to be selected from the list, then all files are\n * ignored.\n */\n return false;\n }\n else\n { /* Check whether name of the file ends with the extension. Added if it\n * does.\n */\n String name = file.getName().toLowerCase(Locale.getDefault());\n for (String ext : validExtensions) {\n if (name.endsWith(ext)) {\n return true;\n }\n }\n }\n return false;\n }",
"public static final PatchOperationTarget createLocal(final File jbossHome, List<File> moduleRoots, List<File> bundlesRoots) throws IOException {\n final PatchTool tool = PatchTool.Factory.createLocalTool(jbossHome, moduleRoots, bundlesRoots);\n return new LocalPatchOperationTarget(tool);\n }"
] |
Output the SQL type for a Java String. | [
"protected void appendStringType(StringBuilder sb, FieldType fieldType, int fieldWidth) {\n\t\tif (isVarcharFieldWidthSupported()) {\n\t\t\tsb.append(\"VARCHAR(\").append(fieldWidth).append(')');\n\t\t} else {\n\t\t\tsb.append(\"VARCHAR\");\n\t\t}\n\t}"
] | [
"public Stats getCollectionStats(String collectionId, Date date) throws FlickrException {\n return getStats(METHOD_GET_COLLECTION_STATS, \"collection_id\", collectionId, date);\n }",
"List<MwDumpFile> findDumpsLocally(DumpContentType dumpContentType) {\n\n\t\tString directoryPattern = WmfDumpFile.getDumpFileDirectoryName(\n\t\t\t\tdumpContentType, \"*\");\n\n\t\tList<String> dumpFileDirectories;\n\t\ttry {\n\t\t\tdumpFileDirectories = this.dumpfileDirectoryManager\n\t\t\t\t\t.getSubdirectories(directoryPattern);\n\t\t} catch (IOException e) {\n\t\t\tlogger.error(\"Unable to access dump directory: \" + e.toString());\n\t\t\treturn Collections.emptyList();\n\t\t}\n\n\t\tList<MwDumpFile> result = new ArrayList<>();\n\n\t\tfor (String directory : dumpFileDirectories) {\n\t\t\tString dateStamp = WmfDumpFile\n\t\t\t\t\t.getDateStampFromDumpFileDirectoryName(dumpContentType,\n\t\t\t\t\t\t\tdirectory);\n\t\t\tif (dateStamp.matches(WmfDumpFileManager.DATE_STAMP_PATTERN)) {\n\t\t\t\tWmfLocalDumpFile dumpFile = new WmfLocalDumpFile(dateStamp,\n\t\t\t\t\t\tthis.projectName, dumpfileDirectoryManager,\n\t\t\t\t\t\tdumpContentType);\n\t\t\t\tif (dumpFile.isAvailable()) {\n\t\t\t\t\tresult.add(dumpFile);\n\t\t\t\t} else {\n\t\t\t\t\tlogger.error(\"Incomplete local dump file data. Maybe delete \"\n\t\t\t\t\t\t\t+ dumpFile.getDumpfileDirectory()\n\t\t\t\t\t\t\t+ \" to attempt fresh download.\");\n\t\t\t\t}\n\t\t\t} // else: silently ignore directories that don't match\n\t\t}\n\n\t\tresult.sort(Collections.reverseOrder(new MwDumpFile.DateComparator()));\n\n\t\tlogger.info(\"Found \" + result.size() + \" local dumps of type \"\n\t\t\t\t+ dumpContentType + \": \" + result);\n\n\t\treturn result;\n\t}",
"@Deprecated\r\n private BufferedImage getImage(String suffix) throws IOException {\r\n StringBuffer buffer = getBaseImageUrl();\r\n buffer.append(suffix);\r\n return _getImage(buffer.toString());\r\n }",
"static Shell createTerminalConsoleShell(String prompt, String appName,\n ShellCommandHandler mainHandler, InputStream input, OutputStream output) {\n try {\n PrintStream out = new PrintStream(output);\n\n // Build jline terminal\n jline.Terminal term = TerminalFactory.get();\n final ConsoleReader console = new ConsoleReader(input, output, term);\n console.setBellEnabled(true);\n console.setHistoryEnabled(true);\n\n // Build console\n BufferedReader in = new BufferedReader(new InputStreamReader(\n new ConsoleReaderInputStream(console)));\n\n ConsoleIO.PromptListener promptListener = new ConsoleIO.PromptListener() {\n @Override\n public boolean onPrompt(String prompt) {\n console.setPrompt(prompt);\n return true; // suppress normal prompt\n }\n };\n\n return createConsoleShell(prompt, appName, mainHandler, in, out, out, promptListener);\n } catch (Exception e) {\n // Failover: use default shell\n BufferedReader in = new BufferedReader(new InputStreamReader(input));\n PrintStream out = new PrintStream(output);\n\n return createConsoleShell(prompt, appName, mainHandler, in, out, out, null);\n }\n }",
"public void setConnectionTimeout(long connectionTimeout, TimeUnit timeUnit) {\n\t\tthis.connectionTimeoutInMs = TimeUnit.MILLISECONDS.convert(connectionTimeout, timeUnit);\n\t}",
"public void addWord(MtasCQLParserWordFullCondition w) throws ParseException {\n assert w.getCondition()\n .not() == false : \"condition word should be positive in sentence definition\";\n if (!simplified) {\n partList.add(w);\n } else {\n throw new ParseException(\"already simplified\");\n }\n }",
"public static void main(final String[] args) {\n if (System.getProperty(\"db.name\") == null) {\n System.out.println(\"Not running in multi-instance mode: no DB to connect to\");\n System.exit(1);\n }\n while (true) {\n try {\n Class.forName(\"org.postgresql.Driver\");\n DriverManager.getConnection(\"jdbc:postgresql://\" + System.getProperty(\"db.host\") + \":5432/\" +\n System.getProperty(\"db.name\"),\n System.getProperty(\"db.username\"),\n System.getProperty(\"db.password\"));\n System.out.println(\"Opened database successfully. Running in multi-instance mode\");\n System.exit(0);\n return;\n } catch (Exception e) {\n System.out.println(\"Failed to connect to the DB: \" + e.toString());\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e1) {\n //ignored\n }\n }\n }\n }",
"private void processColumns()\n {\n int fieldID = MPPUtility.getInt(m_data, m_headerOffset);\n m_headerOffset += 4;\n\n m_dataOffset = MPPUtility.getInt(m_data, m_headerOffset);\n m_headerOffset += 4;\n\n FieldType type = FieldTypeHelper.getInstance(fieldID);\n if (type.getDataType() != null)\n {\n processKnownType(type);\n }\n }",
"public PartialCollection<BoxItem.Info> searchRange(long offset, long limit, final BoxSearchParameters bsp) {\n QueryStringBuilder builder = bsp.getQueryParameters()\n .appendParam(\"limit\", limit)\n .appendParam(\"offset\", offset);\n URL url = SEARCH_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n String totalCountString = responseJSON.get(\"total_count\").toString();\n long fullSize = Double.valueOf(totalCountString).longValue();\n PartialCollection<BoxItem.Info> results = new PartialCollection<BoxItem.Info>(offset, limit, fullSize);\n JsonArray jsonArray = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : jsonArray) {\n JsonObject jsonObject = value.asObject();\n BoxItem.Info parsedItemInfo = (BoxItem.Info) BoxResource.parseInfo(this.getAPI(), jsonObject);\n if (parsedItemInfo != null) {\n results.add(parsedItemInfo);\n }\n }\n return results;\n }"
] |
Based on the current request represented by the HttpExchange construct a complete URL for the supplied path.
@param exchange - The current HttpExchange
@param path - The path to include in the constructed URL
@return The constructed URL | [
"public static String constructUrl(final HttpServerExchange exchange, final String path) {\n final HeaderMap headers = exchange.getRequestHeaders();\n String host = headers.getFirst(HOST);\n String protocol = exchange.getConnection().getSslSessionInfo() != null ? \"https\" : \"http\";\n\n return protocol + \"://\" + host + path;\n }"
] | [
"private void setMax(MtasRBTreeNode n) {\n n.max = n.right;\n if (n.leftChild != null) {\n n.max = Math.max(n.max, n.leftChild.max);\n }\n if (n.rightChild != null) {\n n.max = Math.max(n.max, n.rightChild.max);\n }\n }",
"public CollectionRequest<Task> tags(String task) {\n \n String path = String.format(\"/tasks/%s/tags\", task);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }",
"private static String removeLastDot(final String pkgName) {\n\t\treturn pkgName.charAt(pkgName.length() - 1) == Characters.DOT ? pkgName.substring(0, pkgName.length() - 1) : pkgName;\n\t}",
"public final void unregisterView(final View view) {\n mActivity.runOnUiThread(new Runnable() {\n @Override\n public void run() {\n if (null != mRenderableViewGroup && view.getParent() == mRenderableViewGroup) {\n mRenderableViewGroup.removeView(view);\n }\n }\n });\n }",
"public void openReport(String newState, A_CmsReportThread thread, String label) {\n\n setReport(newState, thread);\n m_labels.put(thread, label);\n openSubView(newState, true);\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 void setOnQueryTextListener(@NonNull final SearchView.OnQueryTextListener listener) {\n if (searchView != null) {\n searchView.setOnQueryTextListener(listener);\n } else if (supportView != null) {\n supportView.setOnQueryTextListener(new android.support.v7.widget.SearchView.OnQueryTextListener() {\n @Override public boolean onQueryTextSubmit(String query) {\n return listener.onQueryTextSubmit(query);\n }\n\n @Override public boolean onQueryTextChange(String newText) {\n return listener.onQueryTextChange(newText);\n }\n });\n } else {\n throw new IllegalStateException(ERROR_NO_SEARCHVIEW);\n }\n }",
"public static base_response Force(nitro_service client, hafailover resource) throws Exception {\n\t\thafailover Forceresource = new hafailover();\n\t\tForceresource.force = resource.force;\n\t\treturn Forceresource.perform_operation(client,\"Force\");\n\t}",
"private EventType createEventType(EventEnumType type) {\n EventType eventType = new EventType();\n eventType.setTimestamp(Converter.convertDate(new Date()));\n eventType.setEventType(type);\n\n OriginatorType origType = new OriginatorType();\n origType.setProcessId(Converter.getPID());\n try {\n InetAddress inetAddress = InetAddress.getLocalHost();\n origType.setIp(inetAddress.getHostAddress());\n origType.setHostname(inetAddress.getHostName());\n } catch (UnknownHostException e) {\n origType.setHostname(\"Unknown hostname\");\n origType.setIp(\"Unknown ip address\");\n }\n eventType.setOriginator(origType);\n\n String path = System.getProperty(\"karaf.home\");\n CustomInfoType ciType = new CustomInfoType();\n CustomInfoType.Item cItem = new CustomInfoType.Item();\n cItem.setKey(\"path\");\n cItem.setValue(path);\n ciType.getItem().add(cItem);\n eventType.setCustomInfo(ciType);\n\n return eventType;\n }"
] |
Launch Sample Activity residing in the same module | [
"@OnClick(R.id.navigateToSampleActivity)\n public void onSampleActivityCTAClick() {\n StringParcel parcel1 = new StringParcel(\"Andy\");\n StringParcel parcel2 = new StringParcel(\"Tony\");\n\n List<StringParcel> parcelList = new ArrayList<>();\n parcelList.add(parcel1);\n parcelList.add(parcel2);\n\n SparseArray<StringParcel> parcelSparseArray = new SparseArray<>();\n parcelSparseArray.put(0, parcel1);\n parcelSparseArray.put(2, parcel2);\n\n Intent intent = HensonNavigator.gotoSampleActivity(this)\n .defaultKeyExtra(\"defaultKeyExtra\")\n .extraInt(4)\n .extraListParcelable(parcelList)\n .extraParcel(parcel1)\n .extraParcelable(ComplexParcelable.random())\n .extraSparseArrayParcelable(parcelSparseArray)\n .extraString(\"a string\")\n .build();\n\n startActivity(intent);\n }"
] | [
"public Bundler put(String key, CharSequence value) {\n delegate.putCharSequence(key, value);\n return this;\n }",
"public static Type getDeclaredBeanType(Class<?> clazz) {\n Type[] actualTypeArguments = Reflections.getActualTypeArguments(clazz);\n if (actualTypeArguments.length == 1) {\n return actualTypeArguments[0];\n } else {\n return null;\n }\n }",
"@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 }",
"void releaseTransaction(@NotNull final Thread thread, final int permits) {\n try (CriticalSection ignored = criticalSection.enter()) {\n int currentThreadPermits = getThreadPermits(thread);\n if (permits > currentThreadPermits) {\n throw new ExodusException(\"Can't release more permits than it was acquired\");\n }\n acquiredPermits -= permits;\n currentThreadPermits -= permits;\n if (currentThreadPermits == 0) {\n threadPermits.remove(thread);\n } else {\n threadPermits.put(thread, currentThreadPermits);\n }\n notifyNextWaiters();\n }\n }",
"boolean resumeSyncForDocument(\n final MongoNamespace namespace,\n final BsonValue documentId\n ) {\n if (namespace == null || documentId == null) {\n return false;\n }\n\n final NamespaceSynchronizationConfig namespaceSynchronizationConfig;\n final CoreDocumentSynchronizationConfig config;\n\n if ((namespaceSynchronizationConfig = syncConfig.getNamespaceConfig(namespace)) == null\n || (config = namespaceSynchronizationConfig.getSynchronizedDocument(documentId)) == null) {\n return false;\n }\n\n config.setPaused(false);\n return !config.isPaused();\n }",
"public 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 }",
"public final boolean hasReturnValues()\r\n {\r\n if (this.hasReturnValue())\r\n {\r\n return true;\r\n }\r\n else\r\n {\r\n // TODO: We may be able to 'pre-calculate' the results\r\n // of this loop by just checking arguments as they are added\r\n // The only problem is that the 'isReturnedbyProcedure' property\r\n // can be modified once the argument is added to this procedure.\r\n // If that occurs, then 'pre-calculated' results will be inacccurate.\r\n Iterator iter = this.getArguments().iterator();\r\n while (iter.hasNext())\r\n {\r\n ArgumentDescriptor arg = (ArgumentDescriptor) iter.next();\r\n if (arg.getIsReturnedByProcedure())\r\n {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n }",
"protected final boolean isPatternValid() {\n\n switch (getPatternType()) {\n case DAILY:\n return isEveryWorkingDay() || isIntervalValid();\n case WEEKLY:\n return isIntervalValid() && isWeekDaySet();\n case MONTHLY:\n return isIntervalValid() && isWeekDaySet() ? isWeekOfMonthSet() : isDayOfMonthValid();\n case YEARLY:\n return isMonthSet() && isWeekDaySet() ? isWeekOfMonthSet() : isDayOfMonthValid();\n case INDIVIDUAL:\n case NONE:\n return true;\n default:\n return false;\n }\n }",
"public void generateOutlineNumber(Task parent)\n {\n String outline;\n\n if (parent == null)\n {\n if (NumberHelper.getInt(getUniqueID()) == 0)\n {\n outline = \"0\";\n }\n else\n {\n outline = Integer.toString(getParentFile().getChildTasks().size() + 1);\n }\n }\n else\n {\n outline = parent.getOutlineNumber();\n\n int index = outline.lastIndexOf(\".0\");\n\n if (index != -1)\n {\n outline = outline.substring(0, index);\n }\n\n int childTaskCount = parent.getChildTasks().size() + 1;\n if (outline.equals(\"0\"))\n {\n outline = Integer.toString(childTaskCount);\n }\n else\n {\n outline += (\".\" + childTaskCount);\n }\n }\n\n setOutlineNumber(outline);\n }"
] |
compares two snippet | [
"public Diff compare(String left, String right) {\n\t\treturn compare(getCtType(left), getCtType(right));\n\t}"
] | [
"@Override\n public int read(char[] cbuf, int off, int len) throws IOException {\n int numChars = super.read(cbuf, off, len);\n replaceBadXmlCharactersBySpace(cbuf, off, len);\n return numChars;\n }",
"public static <T> boolean addAll(Collection<T> target, Iterable<? extends T> iterable) {\n if (iterable instanceof Collection) {\n return target.addAll((Collection<? extends T>) iterable);\n }\n return Iterators.addAll(target, iterable.iterator());\n }",
"private void processResources() throws IOException\n {\n CompanyReader reader = new CompanyReader(m_data.getTableData(\"Companies\"));\n reader.read();\n for (MapRow companyRow : reader.getRows())\n {\n // TODO: need to sort by type as well as by name!\n for (MapRow resourceRow : sort(companyRow.getRows(\"RESOURCES\"), \"NAME\"))\n {\n processResource(resourceRow);\n }\n }\n }",
"public static void writeUnsignedShort(byte[] bytes, int value, int offset) {\n bytes[offset] = (byte) (0xFF & (value >> 8));\n bytes[offset + 1] = (byte) (0xFF & value);\n }",
"public boolean clearSelection(boolean requestLayout) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"clearSelection [%d]\", mSelectedItemsList.size());\n\n boolean updateLayout = false;\n List<ListItemHostWidget> views = getAllHosts();\n for (ListItemHostWidget host: views) {\n if (host.isSelected()) {\n host.setSelected(false);\n updateLayout = true;\n if (requestLayout) {\n host.requestLayout();\n }\n }\n }\n clearSelectedItemsList();\n return updateLayout;\n }",
"private void updateRemoveQ( int rowIndex ) {\n Qm.set(Q);\n Q.reshape(m_m,m_m, false);\n\n for( int i = 0; i < rowIndex; i++ ) {\n for( int j = 1; j < m; j++ ) {\n double sum = 0;\n for( int k = 0; k < m; k++ ) {\n sum += Qm.data[i*m+k]* U_tran.data[j*m+k];\n }\n Q.data[i*m_m+j-1] = sum;\n }\n }\n\n for( int i = rowIndex+1; i < m; i++ ) {\n for( int j = 1; j < m; j++ ) {\n double sum = 0;\n for( int k = 0; k < m; k++ ) {\n sum += Qm.data[i*m+k]* U_tran.data[j*m+k];\n }\n Q.data[(i-1)*m_m+j-1] = sum;\n }\n }\n }",
"@RequestMapping(value = \"/profiles\", method = RequestMethod.GET)\n public String list(Model model) {\n Profile profiles = new Profile();\n model.addAttribute(\"addNewProfile\", profiles);\n model.addAttribute(\"version\", Constants.VERSION);\n logger.info(\"Loading initial page\");\n\n return \"profiles\";\n }",
"public MessageSet read(long readOffset, long size) throws IOException {\n return new FileMessageSet(channel, this.offset + readOffset, //\n Math.min(this.offset + readOffset + size, highWaterMark()), false, new AtomicBoolean(false));\n }",
"public static Boolean assertTrue(Boolean value, String message) {\n if (!Boolean.valueOf(value))\n throw new IllegalArgumentException(message);\n return value;\n }"
] |
Figure out the starting waveform segment that corresponds to the specified coordinate in the window.
@param x the column being drawn
@return the offset into the waveform at the current scale and playback time that should be drawn there | [
"private int getSegmentForX(int x) {\n if (autoScroll.get()) {\n int playHead = (x - (getWidth() / 2));\n int offset = Util.timeToHalfFrame(getFurthestPlaybackPosition()) / scale.get();\n return (playHead + offset) * scale.get();\n }\n return x * scale.get();\n }"
] | [
"@Override\n\tpublic String getFirst(String headerName) {\n\t\tList<String> headerValues = headers.get(headerName);\n\t\treturn headerValues != null ? headerValues.get(0) : null;\n\t}",
"public static List<DockerImage> getAndDiscardImagesByBuildId(int buildInfoId) {\n List<DockerImage> list = new ArrayList<DockerImage>();\n synchronized(images) {\n Iterator<DockerImage> it = images.iterator();\n while (it.hasNext()) {\n DockerImage image = it.next();\n if (image.getBuildInfoId() == buildInfoId) {\n if (image.hasManifest()) {\n list.add(image);\n }\n it.remove();\n } else // Remove old images from the cache, for which build-info hasn't been published to Artifactory:\n if (image.isExpired()) {\n it.remove();\n }\n }\n }\n return list;\n }",
"private static IndexOptions prepareOptions(MongoDBIndexType indexType, Document options, String indexName, boolean unique) {\n\t\tIndexOptions indexOptions = new IndexOptions();\n\t\tindexOptions.name( indexName ).unique( unique ).background( options.getBoolean( \"background\" , false ) );\n\n\t\tif ( unique ) {\n\t\t\t// MongoDB only allows one null value per unique index which is not in line with what we usually consider\n\t\t\t// as the definition of a unique constraint. Thus, we mark the index as sparse to only index values\n\t\t\t// defined and avoid this issue. We do this only if a partialFilterExpression has not been defined\n\t\t\t// as partialFilterExpression and sparse are exclusive.\n\t\t\tindexOptions.sparse( !options.containsKey( \"partialFilterExpression\" ) );\n\t\t}\n\t\telse if ( options.containsKey( \"partialFilterExpression\" ) ) {\n\t\t\tindexOptions.partialFilterExpression( (Bson) options.get( \"partialFilterExpression\" ) );\n\t\t}\n\t\tif ( options.containsKey( \"expireAfterSeconds\" ) ) {\n\t\t\t//@todo is it correct?\n\t\t\tindexOptions.expireAfter( options.getInteger( \"expireAfterSeconds\" ).longValue() , TimeUnit.SECONDS );\n\n\t\t}\n\n\t\tif ( MongoDBIndexType.TEXT.equals( indexType ) ) {\n\t\t\t// text is an option we take into account to mark an index as a full text index as we cannot put \"text\" as\n\t\t\t// the order like MongoDB as ORM explicitly checks that the order is either asc or desc.\n\t\t\t// we remove the option from the Document so that we don't pass it to MongoDB\n\t\t\tif ( options.containsKey( \"default_language\" ) ) {\n\t\t\t\tindexOptions.defaultLanguage( options.getString( \"default_language\" ) );\n\t\t\t}\n\t\t\tif ( options.containsKey( \"weights\" ) ) {\n\t\t\t\tindexOptions.weights( (Bson) options.get( \"weights\" ) );\n\t\t\t}\n\n\t\t\toptions.remove( \"text\" );\n\t\t}\n\t\treturn indexOptions;\n\t}",
"public static base_response delete(nitro_service client, snmpmanager resource) throws Exception {\n\t\tsnmpmanager deleteresource = new snmpmanager();\n\t\tdeleteresource.ipaddress = resource.ipaddress;\n\t\tdeleteresource.netmask = resource.netmask;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"public static ComplexNumber Subtract(ComplexNumber z1, ComplexNumber z2) {\r\n return new ComplexNumber(z1.real - z2.real, z1.imaginary - z2.imaginary);\r\n }",
"public static String getShortClassName(Object o) {\r\n String name = o.getClass().getName();\r\n int index = name.lastIndexOf('.');\r\n if (index >= 0) {\r\n name = name.substring(index + 1);\r\n }\r\n return name;\r\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 }",
"public static int numberAwareCompareTo(Comparable self, Comparable other) {\n NumberAwareComparator<Comparable> numberAwareComparator = new NumberAwareComparator<Comparable>();\n return numberAwareComparator.compare(self, other);\n }",
"public void addEvent(Event event) {\n if(event == null)\n throw new IllegalStateException(\"event must be non-null\");\n\n if(logger.isTraceEnabled())\n logger.trace(\"Adding event \" + event);\n\n eventQueue.add(event);\n }"
] |
Convert the server side feature to a DTO feature that can be sent to the client.
@param feature
The server-side feature representation.
@param featureIncludes
Indicate which aspects of the should be included see {@link VectorLayerService}
@return Returns the DTO feature. | [
"public Feature toDto(InternalFeature feature, int featureIncludes) throws GeomajasException {\n\t\tif (feature == null) {\n\t\t\treturn null;\n\t\t}\n\t\tFeature dto = new Feature(feature.getId());\n\t\tif ((featureIncludes & VectorLayerService.FEATURE_INCLUDE_ATTRIBUTES) != 0 && null != feature.getAttributes()) {\n\t\t\t// need to assure lazy attributes are converted to non-lazy attributes\n\t\t\tMap<String, Attribute> attributes = new HashMap<String, Attribute>();\n\t\t\tfor (Map.Entry<String, Attribute> entry : feature.getAttributes().entrySet()) {\n\t\t\t\tAttribute value = entry.getValue();\n\t\t\t\tif (value instanceof LazyAttribute) {\n\t\t\t\t\tvalue = ((LazyAttribute) value).instantiate();\n\t\t\t\t}\n\t\t\t\tattributes.put(entry.getKey(), value);\n\t\t\t}\n\t\t\tdto.setAttributes(attributes);\n\t\t}\n\t\tif ((featureIncludes & VectorLayerService.FEATURE_INCLUDE_LABEL) != 0) {\n\t\t\tdto.setLabel(feature.getLabel());\n\t\t}\n\t\tif ((featureIncludes & VectorLayerService.FEATURE_INCLUDE_GEOMETRY) != 0) {\n\t\t\tdto.setGeometry(toDto(feature.getGeometry()));\n\t\t}\n\t\tif ((featureIncludes & VectorLayerService.FEATURE_INCLUDE_STYLE) != 0 && null != feature.getStyleInfo()) {\n\t\t\tdto.setStyleId(feature.getStyleInfo().getStyleId());\n\t\t}\n\t\tInternalFeatureImpl vFeature = (InternalFeatureImpl) feature;\n\t\tdto.setClipped(vFeature.isClipped());\n\t\tdto.setUpdatable(feature.isEditable());\n\t\tdto.setDeletable(feature.isDeletable());\n\t\treturn dto;\n\t}"
] | [
"public static ResourceField getInstance(int value)\n {\n ResourceField result = null;\n\n if (value >= 0 && value < FIELD_ARRAY.length)\n {\n result = FIELD_ARRAY[value];\n }\n else\n {\n if ((value & 0x8000) != 0)\n {\n int baseValue = ResourceField.ENTERPRISE_CUSTOM_FIELD1.getValue();\n int id = baseValue + (value & 0xFFF);\n result = ResourceField.getInstance(id);\n }\n }\n\n return (result);\n }",
"@Override\n public void setActive(boolean active) {\n this.active = active;\n\n if (parent != null) {\n fireCollapsibleHandler();\n removeStyleName(CssName.ACTIVE);\n if (header != null) {\n header.removeStyleName(CssName.ACTIVE);\n }\n if (active) {\n if (parent != null && parent.isAccordion()) {\n parent.clearActive();\n }\n addStyleName(CssName.ACTIVE);\n\n if (header != null) {\n header.addStyleName(CssName.ACTIVE);\n }\n }\n\n if (body != null) {\n body.setDisplay(active ? Display.BLOCK : Display.NONE);\n }\n } else {\n GWT.log(\"Please make sure that the Collapsible parent is attached or existed.\", new IllegalStateException());\n }\n }",
"public long removeAll(final String... members) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.srem(getKey(), members);\n }\n });\n }",
"private float[] calculatePointerPosition(float angle) {\n\t\tfloat x = (float) (mColorWheelRadius * Math.cos(angle));\n\t\tfloat y = (float) (mColorWheelRadius * Math.sin(angle));\n\n\t\treturn new float[] { x, y };\n\t}",
"public void writeBasicDeclarations() throws RDFHandlerException {\n\t\tfor (Map.Entry<String, String> uriType : Vocabulary\n\t\t\t\t.getKnownVocabularyTypes().entrySet()) {\n\t\t\tthis.rdfWriter.writeTripleUriObject(uriType.getKey(),\n\t\t\t\t\tRdfWriter.RDF_TYPE, uriType.getValue());\n\t\t}\n\t}",
"public void edit(int currentChangeListId, FilePath filePath) throws Exception {\n establishConnection().editFile(currentChangeListId, new File(filePath.getRemote()));\n }",
"public static long addressToLong(InetAddress address) {\n long result = 0;\n for (byte element : address.getAddress()) {\n result = (result << 8) + unsign(element);\n }\n return result;\n }",
"public static 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 static Module unserializeModule(final String module) throws IOException {\n final ObjectMapper mapper = new ObjectMapper();\n mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);\n return mapper.readValue(module, Module.class);\n }"
] |
Removes all pending broadcasts
@param sessionIds to remove broadcast for (or null for all sessions) | [
"private void removeAllBroadcasts(Set<String> sessionIds) {\n\n if (sessionIds == null) {\n for (CmsSessionInfo info : OpenCms.getSessionManager().getSessionInfos()) {\n OpenCms.getSessionManager().getBroadcastQueue(info.getSessionId().getStringValue()).clear();\n }\n return;\n }\n for (String sessionId : sessionIds) {\n OpenCms.getSessionManager().getBroadcastQueue(sessionId).clear();\n }\n }"
] | [
"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 }",
"private boolean renameKeyForAllLanguages(String oldKey, String newKey) {\n\n try {\n loadAllRemainingLocalizations();\n lockAllLocalizations(oldKey);\n if (hasDescriptor()) {\n lockDescriptor();\n }\n } catch (CmsException | IOException e) {\n LOG.error(e.getLocalizedMessage(), e);\n return false;\n }\n for (Entry<Locale, SortedProperties> entry : m_localizations.entrySet()) {\n SortedProperties localization = entry.getValue();\n if (localization.containsKey(oldKey)) {\n String value = localization.getProperty(oldKey);\n localization.remove(oldKey);\n localization.put(newKey, value);\n m_changedTranslations.add(entry.getKey());\n }\n }\n if (hasDescriptor()) {\n CmsXmlContentValueSequence messages = m_descContent.getValueSequence(\n Descriptor.N_MESSAGE,\n Descriptor.LOCALE);\n for (int i = 0; i < messages.getElementCount(); i++) {\n\n String prefix = messages.getValue(i).getPath() + \"/\";\n String key = m_descContent.getValue(prefix + Descriptor.N_KEY, Descriptor.LOCALE).getStringValue(m_cms);\n if (key == oldKey) {\n m_descContent.getValue(prefix + Descriptor.N_KEY, Descriptor.LOCALE).setStringValue(m_cms, newKey);\n break;\n }\n }\n m_descriptorHasChanges = true;\n }\n m_keyset.renameKey(oldKey, newKey);\n return true;\n }",
"public void editMeta(String photosetId, String title, String description) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT_META);\r\n\r\n parameters.put(\"photoset_id\", photosetId);\r\n parameters.put(\"title\", title);\r\n if (description != null) {\r\n parameters.put(\"description\", description);\r\n }\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"@Api\n\tpublic void setNamedRoles(Map<String, List<NamedRoleInfo>> namedRoles) {\n\t\tthis.namedRoles = namedRoles;\n\t\tldapRoleMapping = new HashMap<String, Set<String>>();\n\t\tfor (String roleName : namedRoles.keySet()) {\n\t\t\tif (!ldapRoleMapping.containsKey(roleName)) {\n\t\t\t\tldapRoleMapping.put(roleName, new HashSet<String>());\n\t\t\t}\n\t\t\tfor (NamedRoleInfo role : namedRoles.get(roleName)) {\n\t\t\t\tldapRoleMapping.get(roleName).add(role.getName());\n\t\t\t}\n\t\t}\n\t}",
"public void setLargePayloadSupportEnabled(AmazonS3 s3, String s3BucketName) {\n\t\tif (s3 == null || s3BucketName == null) {\n\t\t\tString errorMessage = \"S3 client and/or S3 bucket name cannot be null.\";\n\t\t\tLOG.error(errorMessage);\n\t\t\tthrow new AmazonClientException(errorMessage);\n\t\t}\n\t\tif (isLargePayloadSupportEnabled()) {\n\t\t\tLOG.warn(\"Large-payload support is already enabled. Overwriting AmazonS3Client and S3BucketName.\");\n\t\t}\n\t\tthis.s3 = s3;\n\t\tthis.s3BucketName = s3BucketName;\n\t\tlargePayloadSupport = true;\n\t\tLOG.info(\"Large-payload support enabled.\");\n\t}",
"public WaveformPreview requestWaveformPreviewFrom(final DataReference dataReference) {\n ensureRunning();\n for (WaveformPreview cached : previewHotCache.values()) {\n if (cached.dataReference.equals(dataReference)) { // Found a hot cue hit, use it.\n return cached;\n }\n }\n return requestPreviewInternal(dataReference, false);\n }",
"public static String writeMultipleClientConfigAvro(Map<String, Properties> mapStoreToProps) {\n // TODO: Use a dedicated json lib. We shouldn't be manually manipulating json...\n String avroConfig = \"\";\n Boolean firstStore = true;\n for(String storeName: mapStoreToProps.keySet()) {\n if(firstStore) {\n firstStore = false;\n } else {\n avroConfig = avroConfig + \",\\n\";\n }\n Properties props = mapStoreToProps.get(storeName);\n avroConfig = avroConfig + \"\\t\\\"\" + storeName + \"\\\": \"\n + writeSingleClientConfigAvro(props);\n\n }\n return \"{\\n\" + avroConfig + \"\\n}\";\n }",
"public static base_response expire(nitro_service client, cacheobject resource) throws Exception {\n\t\tcacheobject expireresource = new cacheobject();\n\t\texpireresource.locator = resource.locator;\n\t\texpireresource.url = resource.url;\n\t\texpireresource.host = resource.host;\n\t\texpireresource.port = resource.port;\n\t\texpireresource.groupname = resource.groupname;\n\t\texpireresource.httpmethod = resource.httpmethod;\n\t\treturn expireresource.perform_operation(client,\"expire\");\n\t}",
"public static int getPercentage(String percentage) {\n if (isNotEmpty(percentage) && isNumeric(percentage)) {\n int p = Integer.parseInt(percentage);\n return p;\n } else {\n return 0;\n }\n }"
] |
Method used to write the name of the scenarios methods
@param word
@return the same word starting with lower case | [
"public static String changeFirstLetterToLowerCase(String word) {\n char[] letras = word.toCharArray();\n char a = letras[0];\n letras[0] = Character.toLowerCase(a);\n return new String(letras);\n }"
] | [
"private void logColumnData(int startIndex, int length)\n {\n if (m_log != null)\n {\n m_log.println();\n m_log.println(FastTrackUtility.hexdump(m_buffer, startIndex, length, true, 16, \"\"));\n m_log.println();\n m_log.flush();\n }\n }",
"private void findScrollView(ViewGroup viewGroup) {\n scrollChild = viewGroup;\n if (viewGroup.getChildCount() > 0) {\n int count = viewGroup.getChildCount();\n View child;\n for (int i = 0; i < count; i++) {\n child = viewGroup.getChildAt(i);\n if (child instanceof AbsListView || child instanceof ScrollView || child instanceof ViewPager || child instanceof WebView) {\n scrollChild = child;\n return;\n }\n }\n }\n }",
"public static double blackModelCapletValue(\n\t\t\tdouble forward,\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike,\n\t\t\tdouble periodLength,\n\t\t\tdouble discountFactor)\n\t{\n\t\t// May be interpreted as a special version of the Black-Scholes Formula\n\t\treturn AnalyticFormulas.blackScholesGeneralizedOptionValue(forward, volatility, optionMaturity, optionStrike, periodLength * discountFactor);\n\t}",
"public static void handleDomainOperationResponseStreams(final OperationContext context,\n final ModelNode responseNode,\n final List<OperationResponse.StreamEntry> streams) {\n\n if (responseNode.hasDefined(RESPONSE_HEADERS)) {\n ModelNode responseHeaders = responseNode.get(RESPONSE_HEADERS);\n // Strip out any stream header as the header created by this process is what counts\n responseHeaders.remove(ATTACHED_STREAMS);\n if (responseHeaders.asInt() == 0) {\n responseNode.remove(RESPONSE_HEADERS);\n }\n }\n\n for (OperationResponse.StreamEntry streamEntry : streams) {\n context.attachResultStream(streamEntry.getUUID(), streamEntry.getMimeType(), streamEntry.getStream());\n }\n }",
"public static StringBuffer leftShift(String self, Object value) {\n return new StringBuffer(self).append(value);\n }",
"public static base_response unlink(nitro_service client, sslcertkey resource) throws Exception {\n\t\tsslcertkey unlinkresource = new sslcertkey();\n\t\tunlinkresource.certkey = resource.certkey;\n\t\treturn unlinkresource.perform_operation(client,\"unlink\");\n\t}",
"public void setValue(FieldContainer container, byte[] data)\n {\n if (data != null)\n {\n container.set(m_type, ((MPPUtility.getInt(data, m_offset) & m_mask) == 0) ? m_zeroValue : m_nonZeroValue);\n }\n }",
"public void setObjectForStatement(PreparedStatement ps, int index,\r\n Object value, int sqlType) throws SQLException\r\n {\r\n if (sqlType == Types.TINYINT)\r\n {\r\n ps.setByte(index, ((Byte) value).byteValue());\r\n }\r\n else\r\n {\r\n super.setObjectForStatement(ps, index, value, sqlType);\r\n }\r\n }",
"public static servicegroupbindings get(nitro_service service, String servicegroupname) throws Exception{\n\t\tservicegroupbindings obj = new servicegroupbindings();\n\t\tobj.set_servicegroupname(servicegroupname);\n\t\tservicegroupbindings response = (servicegroupbindings) obj.get_resource(service);\n\t\treturn response;\n\t}"
] |
Log modified request
@param httpMethodProxyRequest
@param httpServletResponse
@param history | [
"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 base_responses update(nitro_service client, nsip6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsip6 updateresources[] = new nsip6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nsip6();\n\t\t\t\tupdateresources[i].ipv6address = resources[i].ipv6address;\n\t\t\t\tupdateresources[i].td = resources[i].td;\n\t\t\t\tupdateresources[i].nd = resources[i].nd;\n\t\t\t\tupdateresources[i].icmp = resources[i].icmp;\n\t\t\t\tupdateresources[i].vserver = resources[i].vserver;\n\t\t\t\tupdateresources[i].telnet = resources[i].telnet;\n\t\t\t\tupdateresources[i].ftp = resources[i].ftp;\n\t\t\t\tupdateresources[i].gui = resources[i].gui;\n\t\t\t\tupdateresources[i].ssh = resources[i].ssh;\n\t\t\t\tupdateresources[i].snmp = resources[i].snmp;\n\t\t\t\tupdateresources[i].mgmtaccess = resources[i].mgmtaccess;\n\t\t\t\tupdateresources[i].restrictaccess = resources[i].restrictaccess;\n\t\t\t\tupdateresources[i].state = resources[i].state;\n\t\t\t\tupdateresources[i].map = resources[i].map;\n\t\t\t\tupdateresources[i].dynamicrouting = resources[i].dynamicrouting;\n\t\t\t\tupdateresources[i].hostroute = resources[i].hostroute;\n\t\t\t\tupdateresources[i].ip6hostrtgw = resources[i].ip6hostrtgw;\n\t\t\t\tupdateresources[i].metric = resources[i].metric;\n\t\t\t\tupdateresources[i].vserverrhilevel = resources[i].vserverrhilevel;\n\t\t\t\tupdateresources[i].ospf6lsatype = resources[i].ospf6lsatype;\n\t\t\t\tupdateresources[i].ospfarea = resources[i].ospfarea;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"private void fireEventForNonWebModules(Type eventType, Object event, Annotation... qualifiers) {\n try {\n BeanDeploymentModules modules = deploymentManager.getServices().get(BeanDeploymentModules.class);\n if (modules != null) {\n // fire event for non-web modules\n // web modules are handled by HttpContextLifecycle\n for (BeanDeploymentModule module : modules) {\n if (!module.isWebModule()) {\n module.fireEvent(eventType, event, qualifiers);\n }\n }\n }\n } catch (Exception ignored) {\n }\n }",
"public void add(final IndexableTaskItem taskItem) {\n this.dependsOnTaskGroup.addPostRunDependentTaskGroup(taskItem.taskGroup());\n this.collection.add(taskItem);\n }",
"public List depthFirst() {\n List answer = new NodeList();\n answer.add(this);\n answer.addAll(depthFirstRest());\n return answer;\n }",
"private String GCMGetFreshToken(final String senderID) {\n getConfigLogger().verbose(getAccountId(), \"GcmManager: Requesting a GCM token for Sender ID - \" + senderID);\n String token = null;\n try {\n token = InstanceID.getInstance(context)\n .getToken(senderID, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);\n getConfigLogger().info(getAccountId(), \"GCM token : \" + token);\n } catch (Throwable t) {\n getConfigLogger().verbose(getAccountId(), \"GcmManager: Error requesting GCM token\", t);\n }\n return token;\n }",
"public static base_responses update(nitro_service client, appfwlearningsettings resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tappfwlearningsettings updateresources[] = new appfwlearningsettings[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new appfwlearningsettings();\n\t\t\t\tupdateresources[i].profilename = resources[i].profilename;\n\t\t\t\tupdateresources[i].starturlminthreshold = resources[i].starturlminthreshold;\n\t\t\t\tupdateresources[i].starturlpercentthreshold = resources[i].starturlpercentthreshold;\n\t\t\t\tupdateresources[i].cookieconsistencyminthreshold = resources[i].cookieconsistencyminthreshold;\n\t\t\t\tupdateresources[i].cookieconsistencypercentthreshold = resources[i].cookieconsistencypercentthreshold;\n\t\t\t\tupdateresources[i].csrftagminthreshold = resources[i].csrftagminthreshold;\n\t\t\t\tupdateresources[i].csrftagpercentthreshold = resources[i].csrftagpercentthreshold;\n\t\t\t\tupdateresources[i].fieldconsistencyminthreshold = resources[i].fieldconsistencyminthreshold;\n\t\t\t\tupdateresources[i].fieldconsistencypercentthreshold = resources[i].fieldconsistencypercentthreshold;\n\t\t\t\tupdateresources[i].crosssitescriptingminthreshold = resources[i].crosssitescriptingminthreshold;\n\t\t\t\tupdateresources[i].crosssitescriptingpercentthreshold = resources[i].crosssitescriptingpercentthreshold;\n\t\t\t\tupdateresources[i].sqlinjectionminthreshold = resources[i].sqlinjectionminthreshold;\n\t\t\t\tupdateresources[i].sqlinjectionpercentthreshold = resources[i].sqlinjectionpercentthreshold;\n\t\t\t\tupdateresources[i].fieldformatminthreshold = resources[i].fieldformatminthreshold;\n\t\t\t\tupdateresources[i].fieldformatpercentthreshold = resources[i].fieldformatpercentthreshold;\n\t\t\t\tupdateresources[i].xmlwsiminthreshold = resources[i].xmlwsiminthreshold;\n\t\t\t\tupdateresources[i].xmlwsipercentthreshold = resources[i].xmlwsipercentthreshold;\n\t\t\t\tupdateresources[i].xmlattachmentminthreshold = resources[i].xmlattachmentminthreshold;\n\t\t\t\tupdateresources[i].xmlattachmentpercentthreshold = resources[i].xmlattachmentpercentthreshold;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public void setValue(Vector3f pos) {\n mX = pos.x;\n mY = pos.y;\n mZ = pos.z;\n }",
"private void writeActivity(Task mpxj)\n {\n ActivityType xml = m_factory.createActivityType();\n m_project.getActivity().add(xml);\n\n Task parentTask = mpxj.getParentTask();\n Integer parentObjectID = parentTask == null ? null : parentTask.getUniqueID();\n\n xml.setActualStartDate(mpxj.getActualStart());\n xml.setActualFinishDate(mpxj.getActualFinish());\n xml.setAtCompletionDuration(getDuration(mpxj.getDuration()));\n xml.setCalendarObjectId(getCalendarUniqueID(mpxj.getCalendar()));\n xml.setDurationPercentComplete(getPercentage(mpxj.getPercentageComplete()));\n xml.setDurationType(DURATION_TYPE_MAP.get(mpxj.getType()));\n xml.setFinishDate(mpxj.getFinish());\n xml.setGUID(DatatypeConverter.printUUID(mpxj.getGUID()));\n xml.setId(getActivityID(mpxj));\n xml.setName(mpxj.getName());\n xml.setObjectId(mpxj.getUniqueID());\n xml.setPercentComplete(getPercentage(mpxj.getPercentageComplete()));\n xml.setPercentCompleteType(\"Duration\");\n xml.setPrimaryConstraintType(CONSTRAINT_TYPE_MAP.get(mpxj.getConstraintType()));\n xml.setPrimaryConstraintDate(mpxj.getConstraintDate());\n xml.setPlannedDuration(getDuration(mpxj.getDuration()));\n xml.setPlannedFinishDate(mpxj.getFinish());\n xml.setPlannedStartDate(mpxj.getStart());\n xml.setProjectObjectId(PROJECT_OBJECT_ID);\n xml.setRemainingDuration(getDuration(mpxj.getRemainingDuration()));\n xml.setRemainingEarlyFinishDate(mpxj.getEarlyFinish());\n xml.setRemainingEarlyStartDate(mpxj.getResume());\n xml.setRemainingLaborCost(NumberHelper.DOUBLE_ZERO);\n xml.setRemainingLaborUnits(NumberHelper.DOUBLE_ZERO);\n xml.setRemainingNonLaborCost(NumberHelper.DOUBLE_ZERO);\n xml.setRemainingNonLaborUnits(NumberHelper.DOUBLE_ZERO);\n xml.setStartDate(mpxj.getStart());\n xml.setStatus(getActivityStatus(mpxj));\n xml.setType(extractAndConvertTaskType(mpxj));\n xml.setWBSObjectId(parentObjectID);\n xml.getUDF().addAll(writeUDFType(FieldTypeClass.TASK, mpxj));\n\n writePredecessors(mpxj);\n }",
"public void writeReferences() throws RDFHandlerException {\n\t\tIterator<Reference> referenceIterator = this.referenceQueue.iterator();\n\t\tfor (Resource resource : this.referenceSubjectQueue) {\n\t\t\tfinal Reference reference = referenceIterator.next();\n\t\t\tif (this.declaredReferences.add(resource)) {\n\t\t\t\twriteReference(reference, resource);\n\t\t\t}\n\t\t}\n\t\tthis.referenceSubjectQueue.clear();\n\t\tthis.referenceQueue.clear();\n\n\t\tthis.snakRdfConverter.writeAuxiliaryTriples();\n\t}"
] |
Sets no of currency digits.
@param currDigs Available values, 0,1,2 | [
"public void setCurrencyDigits(Integer currDigs)\n {\n if (currDigs == null)\n {\n currDigs = DEFAULT_CURRENCY_DIGITS;\n }\n set(ProjectField.CURRENCY_DIGITS, currDigs);\n }"
] | [
"@Override\n public DMatrixRMaj getV(DMatrixRMaj V , boolean transpose , boolean compact ) {\n V = handleV(V, transpose, compact,m,n,min);\n CommonOps_DDRM.setIdentity(V);\n\n// UBV.print();\n\n // todo the very first multiplication can be avoided by setting to the rank1update output\n for( int j = min-1; j >= 0; j-- ) {\n u[j+1] = 1;\n for( int i = j+2; i < n; i++ ) {\n u[i] = UBV.get(j,i);\n }\n if( transpose )\n QrHelperFunctions_DDRM.rank1UpdateMultL(V, u, gammasV[j], j + 1, j + 1, n);\n else\n QrHelperFunctions_DDRM.rank1UpdateMultR(V, u, gammasV[j], j + 1, j + 1, n, this.b);\n }\n\n return V;\n }",
"public void copyCategories(CmsObject cms, CmsResource fromResource, String toResourceSitePath) throws CmsException {\n\n List<CmsCategory> categories = readResourceCategories(cms, fromResource);\n for (CmsCategory category : categories) {\n addResourceToCategory(cms, toResourceSitePath, category);\n }\n }",
"private List<Point2D> merge(final List<Point2D> one, final List<Point2D> two) {\n final Set<Point2D> oneSet = new HashSet<Point2D>(one);\n for (Point2D item : two) {\n if (!oneSet.contains(item)) {\n one.add(item);\n }\n }\n return one;\n }",
"public void setPromoted(final boolean promoted) {\n this.promoted = promoted;\n\n for (final Artifact artifact : artifacts) {\n artifact.setPromoted(promoted);\n }\n\n for (final Module suModule : submodules) {\n suModule.setPromoted(promoted);\n }\n }",
"public void addExtraInfo(String key, Object value) {\n // Turn extraInfo into map\n Map<String, Object> infoMap = (HashMap<String, Object>)getMapFromJSON(extraInfo);\n // Add value\n infoMap.put(key, value);\n\n // Turn back into string\n extraInfo = getJSONFromMap(infoMap);\n }",
"public ParallelTaskBuilder setReplaceVarMapToSingleTargetSingleVar(\n String variable, List<String> replaceList, String uniformTargetHost) {\n\n if (Strings.isNullOrEmpty(uniformTargetHost)) {\n logger.error(\"uniform target host is empty or null. skil setting.\");\n return this;\n }\n this.replacementVarMapNodeSpecific.clear();\n this.targetHosts.clear();\n int i = 0;\n for (String replace : replaceList) {\n if (replace == null){\n logger.error(\"null replacement.. skip\");\n continue;\n }\n String hostName = PcConstants.API_PREFIX + i;\n\n replacementVarMapNodeSpecific.put(\n hostName,\n new StrStrMap().addPair(variable, replace).addPair(\n PcConstants.UNIFORM_TARGET_HOST_VAR,\n uniformTargetHost));\n targetHosts.add(hostName);\n ++i;\n }\n this.requestReplacementType = RequestReplacementType.TARGET_HOST_SPECIFIC_VAR_REPLACEMENT;\n logger.info(\n \"Set requestReplacementType as {} for single target. Will disable the set target hosts.\"\n + \"Also Simulated \"\n + \"Now Already set targetHost list with size {}. \\nPLEASE NOT TO SET TARGET HOSTS AGAIN WITH THIS API.\",\n requestReplacementType.toString(), targetHosts.size());\n\n return this;\n }",
"public String getUrl(){\n\t\tfinal StringBuilder sb = new StringBuilder();\n\t\tsb.append(\"http://\");\n\t\tsb.append(getHttpConfiguration().getBindHost().get());\n\t\tsb.append(\":\");\n\t\tsb.append(getHttpConfiguration().getPort());\n\t\t\n\t\treturn sb.toString();\n\t}",
"@SuppressWarnings(\"unchecked\")\n protected void addPostRunDependent(Executable<? extends Indexable> executable) {\n TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) executable;\n this.addPostRunDependent(dependency);\n }",
"protected RendererViewHolder buildRendererViewHolder() {\n validateAttributesToCreateANewRendererViewHolder();\n\n Renderer renderer = getPrototypeByIndex(viewType).copy();\n renderer.onCreate(null, layoutInflater, parent);\n return new RendererViewHolder(renderer);\n }"
] |
Initialize the local plugins registry
@param context the servlet context necessary to grab
the files inside the servlet.
@return the set of local plugins organized by name | [
"public static Map<String, IDiagramPlugin>\n getLocalPluginsRegistry(ServletContext context) {\n if (LOCAL == null) {\n LOCAL = initializeLocalPlugins(context);\n }\n return LOCAL;\n }"
] | [
"public void setSessionTimeout(int timeout) {\n ((ZKBackend) getBackend()).setSessionTimeout(timeout);\n\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Locator session timeout set to: \" + timeout);\n }\n }",
"public static Class<?> resolveReturnType(Method method, Class<?> clazz) {\n\t\tAssert.notNull(method, \"Method must not be null\");\n\t\tType genericType = method.getGenericReturnType();\n\t\tAssert.notNull(clazz, \"Class must not be null\");\n\t\tMap<TypeVariable, Type> typeVariableMap = getTypeVariableMap(clazz);\n\t\tType rawType = getRawType(genericType, typeVariableMap);\n\t\treturn (rawType instanceof Class ? (Class<?>) rawType : method.getReturnType());\n\t}",
"private void writeProjectProperties()\n {\n ProjectProperties properties = m_projectFile.getProjectProperties();\n\n m_plannerProject.setCompany(properties.getCompany());\n m_plannerProject.setManager(properties.getManager());\n m_plannerProject.setName(getString(properties.getName()));\n m_plannerProject.setProjectStart(getDateTime(properties.getStartDate()));\n m_plannerProject.setCalendar(getIntegerString(m_projectFile.getDefaultCalendar().getUniqueID()));\n m_plannerProject.setMrprojectVersion(\"2\");\n }",
"public static void ensureChildElement(DomXmlElement parentElement, DomXmlElement childElement) {\n Node parent = childElement.unwrap().getParentNode();\n if (parent == null || !parentElement.unwrap().isEqualNode(parent)) {\n throw LOG.elementIsNotChildOfThisElement(childElement, parentElement);\n }\n }",
"private Observable<Indexable> processFaultedTaskAsync(final TaskGroupEntry<TaskItem> faultedEntry,\n final Throwable throwable,\n final InvocationContext context) {\n markGroupAsCancelledIfTerminationStrategyIsIPTC();\n reportError(faultedEntry, throwable);\n if (isRootEntry(faultedEntry)) {\n if (shouldPropagateException(throwable)) {\n return toErrorObservable(throwable);\n }\n return Observable.empty();\n } else if (shouldPropagateException(throwable)) {\n return Observable.concatDelayError(invokeReadyTasksAsync(context), toErrorObservable(throwable));\n } else {\n return invokeReadyTasksAsync(context);\n }\n }",
"private void readResource(net.sf.mpxj.ganttproject.schema.Resource gpResource)\n {\n Resource mpxjResource = m_projectFile.addResource();\n mpxjResource.setUniqueID(Integer.valueOf(NumberHelper.getInt(gpResource.getId()) + 1));\n mpxjResource.setName(gpResource.getName());\n mpxjResource.setEmailAddress(gpResource.getContacts());\n mpxjResource.setText(1, gpResource.getPhone());\n mpxjResource.setGroup(m_roleDefinitions.get(gpResource.getFunction()));\n\n net.sf.mpxj.ganttproject.schema.Rate gpRate = gpResource.getRate();\n if (gpRate != null)\n {\n mpxjResource.setStandardRate(new Rate(gpRate.getValueAttribute(), TimeUnit.DAYS));\n }\n readResourceCustomFields(gpResource, mpxjResource);\n m_eventManager.fireResourceReadEvent(mpxjResource);\n }",
"public void setChildren(List<PrintComponent<?>> children) {\n\t\tthis.children = children;\n\t\t// needed for Json unmarshall !!!!\n\t\tfor (PrintComponent<?> child : children) {\n\t\t\tchild.setParent(this);\n\t\t}\n\t}",
"public ParallelTaskBuilder prepareHttpDelete(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n\n cb.getHttpMeta().setHttpMethod(HttpMethod.DELETE);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\n }",
"private void readBitFields(MppBitFlag[] flags, FieldContainer container, byte[] data)\n {\n for (MppBitFlag flag : flags)\n {\n flag.setValue(container, data);\n }\n }"
] |
Sets the drawable used as the drawer indicator.
@param drawable The drawable used as the drawer indicator. | [
"public void setSlideDrawable(Drawable drawable) {\n mSlideDrawable = new SlideDrawable(drawable);\n mSlideDrawable.setIsRtl(ViewHelper.getLayoutDirection(this) == LAYOUT_DIRECTION_RTL);\n\n if (mActionBarHelper != null) {\n mActionBarHelper.setDisplayShowHomeAsUpEnabled(true);\n\n if (mDrawerIndicatorEnabled) {\n mActionBarHelper.setActionBarUpIndicator(mSlideDrawable,\n isMenuVisible() ? mDrawerOpenContentDesc : mDrawerClosedContentDesc);\n }\n }\n }"
] | [
"private void initializeLogging() {\n\t\t// Since logging is static, make sure this is done only once even if\n\t\t// multiple clients are created (e.g., during tests)\n\t\tif (consoleAppender != null) {\n\t\t\treturn;\n\t\t}\n\n\t\tconsoleAppender = new ConsoleAppender();\n\t\tconsoleAppender.setLayout(new PatternLayout(LOG_PATTERN));\n\t\tconsoleAppender.setThreshold(Level.INFO);\n\t\tLevelRangeFilter filter = new LevelRangeFilter();\n\t\tfilter.setLevelMin(Level.TRACE);\n\t\tfilter.setLevelMax(Level.INFO);\n\t\tconsoleAppender.addFilter(filter);\n\t\tconsoleAppender.activateOptions();\n\t\torg.apache.log4j.Logger.getRootLogger().addAppender(consoleAppender);\n\n\t\terrorAppender = new ConsoleAppender();\n\t\terrorAppender.setLayout(new PatternLayout(LOG_PATTERN));\n\t\terrorAppender.setThreshold(Level.WARN);\n\t\terrorAppender.setTarget(ConsoleAppender.SYSTEM_ERR);\n\t\terrorAppender.activateOptions();\n\t\torg.apache.log4j.Logger.getRootLogger().addAppender(errorAppender);\n\t}",
"private String formatDateTimeNull(Date value)\n {\n return (value == null ? m_formats.getNullText() : m_formats.getDateTimeFormat().format(value));\n }",
"public void cullHistory(final int profileId, final String clientUUID, final int limit) throws Exception {\n\n //Allow only 1 delete thread to run\n if (threadActive) {\n return;\n }\n\n threadActive = true;\n //Create a thread so proxy will continue to work during long delete\n Thread t1 = new Thread(new Runnable() {\n @Override\n public void run() {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n String sqlQuery = \"SELECT COUNT(\" + Constants.GENERIC_ID + \") FROM \" + Constants.DB_TABLE_HISTORY + \" \";\n\n // see if profileId is set or not (-1)\n if (profileId != -1) {\n sqlQuery += \"WHERE \" + Constants.GENERIC_PROFILE_ID + \"=\" + profileId + \" \";\n }\n\n if (clientUUID != null && clientUUID.compareTo(\"\") != 0) {\n sqlQuery += \"AND \" + Constants.GENERIC_CLIENT_UUID + \"='\" + clientUUID + \"' \";\n }\n sqlQuery += \";\";\n\n Statement query = sqlConnection.createStatement();\n ResultSet results = query.executeQuery(sqlQuery);\n if (results.next()) {\n if (results.getInt(\"COUNT(\" + Constants.GENERIC_ID + \")\") < (limit + 10000)) {\n return;\n }\n }\n //Find the last item in the table\n statement = sqlConnection.prepareStatement(\"SELECT \" + Constants.GENERIC_ID + \" FROM \" + Constants.DB_TABLE_HISTORY +\n \" WHERE \" + Constants.CLIENT_CLIENT_UUID + \" = \\'\" + clientUUID + \"\\'\" +\n \" AND \" + Constants.CLIENT_PROFILE_ID + \" = \" + profileId +\n \" ORDER BY \" + Constants.GENERIC_ID + \" ASC LIMIT 1\");\n\n ResultSet resultSet = statement.executeQuery();\n if (resultSet.next()) {\n int currentSpot = resultSet.getInt(Constants.GENERIC_ID) + 100;\n int finalDelete = currentSpot + 10000;\n //Delete 100 items at a time until 10000 are deleted\n //Do this so table is unlocked frequently to allow other proxy items to access it\n while (currentSpot < finalDelete) {\n PreparedStatement deleteStatement = sqlConnection.prepareStatement(\"DELETE FROM \" + Constants.DB_TABLE_HISTORY +\n \" WHERE \" + Constants.CLIENT_CLIENT_UUID + \" = \\'\" + clientUUID + \"\\'\" +\n \" AND \" + Constants.CLIENT_PROFILE_ID + \" = \" + profileId +\n \" AND \" + Constants.GENERIC_ID + \" < \" + currentSpot);\n deleteStatement.executeUpdate();\n currentSpot += 100;\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n threadActive = false;\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }\n });\n\n t1.start();\n }",
"private void computeCosts() {\n cost = Long.MAX_VALUE;\n for (QueueItem item : queueSpans) {\n cost = Math.min(cost, item.sequenceSpans.spans.cost());\n }\n }",
"public void setWeekDays(SortedSet<WeekDay> weekDays) {\n\n final SortedSet<WeekDay> newWeekDays = null == weekDays ? new TreeSet<WeekDay>() : weekDays;\n SortedSet<WeekDay> currentWeekDays = m_model.getWeekDays();\n if (!currentWeekDays.equals(newWeekDays)) {\n conditionallyRemoveExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setWeekDays(newWeekDays);\n onValueChange();\n }\n }, !newWeekDays.containsAll(m_model.getWeekDays()));\n }\n }",
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public int getInboxMessageUnreadCount(){\n synchronized (inboxControllerLock) {\n if (this.ctInboxController != null) {\n return ctInboxController.unreadCount();\n } else {\n getConfigLogger().debug(getAccountId(), \"Notification Inbox not initialized\");\n return -1;\n }\n }\n }",
"@Nonnull\n protected Payload getPayload(final String testName) {\n // Get the current bucket.\n final TestBucket testBucket = buckets.get(testName);\n\n // Lookup Payloads for this test\n if (testBucket != null) {\n final Payload payload = testBucket.getPayload();\n if (null != payload) {\n return payload;\n }\n }\n\n return Payload.EMPTY_PAYLOAD;\n }",
"public void setKnotType(int n, int type) {\n\t\tknotTypes[n] = (byte)((knotTypes[n] & ~COLOR_MASK) | type);\n\t\trebuildGradient();\n\t}",
"private void readAssignmentExtendedAttributes(Project.Assignments.Assignment xml, ResourceAssignment mpx)\n {\n for (Project.Assignments.Assignment.ExtendedAttribute attrib : xml.getExtendedAttribute())\n {\n int xmlFieldID = Integer.parseInt(attrib.getFieldID()) & 0x0000FFFF;\n AssignmentField mpxFieldID = MPPAssignmentField.getInstance(xmlFieldID);\n TimeUnit durationFormat = DatatypeConverter.parseDurationTimeUnits(attrib.getDurationFormat(), null);\n DatatypeConverter.parseExtendedAttribute(m_projectFile, mpx, attrib.getValue(), mpxFieldID, durationFormat);\n }\n }"
] |
Adds columns for the specified properties.
@param _properties the array of <code>PropertyDescriptor</code>s to be added.
@throws ColumnBuilderException if an error occurs.
@throws ClassNotFoundException if an error occurs. | [
"private void addProperties(final PropertyDescriptor[] _properties) throws ColumnBuilderException, ClassNotFoundException {\n for (final PropertyDescriptor property : _properties) {\n if (isValidProperty(property)) {\n addColumn(getColumnTitle(property), property.getName(), property.getPropertyType().getName(), getColumnWidth(property));\n }\n }\n setUseFullPageWidth(true);\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 WebSocketContext messageReceived(String receivedMessage) {\n this.stringMessage = S.string(receivedMessage).trim();\n isJson = stringMessage.startsWith(\"{\") || stringMessage.startsWith(\"]\");\n tryParseQueryParams();\n return this;\n }",
"public static String fromClassPath() {\n Set<String> versions = new HashSet<>();\n try {\n ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n Enumeration<URL> manifests = classLoader.getResources(\"META-INF/MANIFEST.MF\");\n\n while (manifests.hasMoreElements()) {\n URL manifestURL = manifests.nextElement();\n try (InputStream is = manifestURL.openStream()) {\n Manifest manifest = new Manifest();\n manifest.read(is);\n\n Attributes buildInfo = manifest.getAttributes(\"Build-Info\");\n if (buildInfo != null) {\n if (buildInfo.getValue(\"Selenium-Version\") != null) {\n versions.add(buildInfo.getValue(\"Selenium-Version\"));\n } else {\n // might be in build-info part\n if (manifest.getEntries() != null) {\n if (manifest.getEntries().containsKey(\"Build-Info\")) {\n final Attributes attributes = manifest.getEntries().get(\"Build-Info\");\n\n if (attributes.getValue(\"Selenium-Version\") != null) {\n versions.add(attributes.getValue(\"Selenium-Version\"));\n }\n }\n }\n }\n }\n }\n }\n } catch (Exception e) {\n logger.log(Level.WARNING,\n \"Exception {0} occurred while resolving selenium version and latest image is going to be used.\",\n e.getMessage());\n return SELENIUM_VERSION;\n }\n\n if (versions.isEmpty()) {\n logger.log(Level.INFO, \"No version of Selenium found in classpath. Using latest image.\");\n return SELENIUM_VERSION;\n }\n\n String foundVersion = versions.iterator().next();\n if (versions.size() > 1) {\n logger.log(Level.WARNING, \"Multiple versions of Selenium found in classpath. Using the first one found {0}.\",\n foundVersion);\n }\n\n return foundVersion;\n }",
"public static String getCountryCodeAndCheckDigit(final String iban) {\n return iban.substring(COUNTRY_CODE_INDEX,\n COUNTRY_CODE_INDEX + COUNTRY_CODE_LENGTH + CHECK_DIGIT_LENGTH);\n }",
"public Release rollback(String appName, String releaseUuid) {\n return connection.execute(new Rollback(appName, releaseUuid), apiKey);\n }",
"public static Node updateNode(Node node, List<Integer> partitionsList) {\n return new Node(node.getId(),\n node.getHost(),\n node.getHttpPort(),\n node.getSocketPort(),\n node.getAdminPort(),\n node.getZoneId(),\n partitionsList);\n }",
"public static base_responses enable(nitro_service client, String trapname[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (trapname != null && trapname.length > 0) {\n\t\t\tsnmpalarm enableresources[] = new snmpalarm[trapname.length];\n\t\t\tfor (int i=0;i<trapname.length;i++){\n\t\t\t\tenableresources[i] = new snmpalarm();\n\t\t\t\tenableresources[i].trapname = trapname[i];\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, enableresources,\"enable\");\n\t\t}\n\t\treturn result;\n\t}",
"public double getValue(ForwardCurve forwardCurve, double swaprateVolatility) {\n\t\tdouble[] swapTenor = new double[fixingDates.length+1];\n\t\tSystem.arraycopy(fixingDates, 0, swapTenor, 0, fixingDates.length);\n\t\tswapTenor[swapTenor.length-1] = paymentDates[paymentDates.length-1];\n\n\t\tTimeDiscretization fixTenor\t= new TimeDiscretizationFromArray(swapTenor);\n\t\tTimeDiscretization floatTenor\t= new TimeDiscretizationFromArray(swapTenor);\n\t\tdouble forwardSwapRate = Swap.getForwardSwapRate(fixTenor, floatTenor, forwardCurve);\n\t\tdouble swapAnnuity = SwapAnnuity.getSwapAnnuity(fixTenor, forwardCurve);\n\t\tdouble payoffUnit = SwapAnnuity.getSwapAnnuity(new TimeDiscretizationFromArray(swapTenor[0], swapTenor[1]), forwardCurve) / (swapTenor[1] - swapTenor[0]);\n\t\treturn AnalyticFormulas.huntKennedyCMSOptionValue(forwardSwapRate, swaprateVolatility, swapAnnuity, exerciseDate, swapTenor[swapTenor.length-1]-swapTenor[0], payoffUnit, strike) * (swapTenor[1] - swapTenor[0]);\n\t}",
"public int getTotalCreatedConnections(){\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();\r\n\t\t}\r\n\t\treturn total;\r\n\t}"
] |
Gets the i-th half-edge associated with the face.
@param i
the half-edge index, in the range 0-2.
@return the half-edge | [
"public HalfEdge getEdge(int i) {\n HalfEdge he = he0;\n while (i > 0) {\n he = he.next;\n i--;\n }\n while (i < 0) {\n he = he.prev;\n i++;\n }\n return he;\n }"
] | [
"public void setBooleanAttribute(String name, Boolean value) {\n\t\tensureValue();\n\t\tAttribute attribute = new BooleanAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetValue().getAllAttributes().put(name, attribute);\n\t}",
"public String getLinkColor(JSONObject jsonObject){\n if(jsonObject == null) return null;\n try {\n return jsonObject.has(\"color\") ? jsonObject.getString(\"color\") : \"\";\n } catch (JSONException e) {\n Logger.v(\"Unable to get Link Text Color with JSON - \"+e.getLocalizedMessage());\n return null;\n }\n }",
"private static boolean isAssignableFrom(Type from, GenericArrayType to) {\n\t\tType toGenericComponentType = to.getGenericComponentType();\n\t\tif (toGenericComponentType instanceof ParameterizedType) {\n\t\t\tType t = from;\n\t\t\tif (from instanceof GenericArrayType) {\n\t\t\t\tt = ((GenericArrayType) from).getGenericComponentType();\n\t\t\t} else if (from instanceof Class) {\n\t\t\t\tClass<?> classType = (Class<?>) from;\n\t\t\t\twhile (classType.isArray()) {\n\t\t\t\t\tclassType = classType.getComponentType();\n\t\t\t\t}\n\t\t\t\tt = classType;\n\t\t\t}\n\t\t\treturn isAssignableFrom(t,\n\t\t\t\t\t(ParameterizedType) toGenericComponentType,\n\t\t\t\t\tnew HashMap<String, Type>());\n\t\t}\n\t\t// No generic defined on \"to\"; therefore, return true and let other\n\t\t// checks determine assignability\n\t\treturn true;\n\t}",
"@Override\n public HandlerRegistration addSearchFinishHandler(final SearchFinishEvent.SearchFinishHandler handler) {\n return addHandler(handler, SearchFinishEvent.TYPE);\n }",
"public int getCrossZonePartitionStoreMoves() {\n int xzonePartitionStoreMoves = 0;\n for (RebalanceTaskInfo info : batchPlan) {\n Node donorNode = finalCluster.getNodeById(info.getDonorId());\n Node stealerNode = finalCluster.getNodeById(info.getStealerId());\n\n if(donorNode.getZoneId() != stealerNode.getZoneId()) {\n xzonePartitionStoreMoves += info.getPartitionStoreMoves();\n }\n }\n\n return xzonePartitionStoreMoves;\n }",
"private Map<StandardMethod, UnderrideLevel> findUnderriddenMethods(\n Iterable<ExecutableElement> methods) {\n Map<StandardMethod, ExecutableElement> standardMethods = new LinkedHashMap<>();\n for (ExecutableElement method : methods) {\n Optional<StandardMethod> standardMethod = maybeStandardMethod(method);\n if (standardMethod.isPresent() && isUnderride(method)) {\n standardMethods.put(standardMethod.get(), method);\n }\n }\n if (standardMethods.containsKey(StandardMethod.EQUALS)\n != standardMethods.containsKey(StandardMethod.HASH_CODE)) {\n ExecutableElement underriddenMethod = standardMethods.containsKey(StandardMethod.EQUALS)\n ? standardMethods.get(StandardMethod.EQUALS)\n : standardMethods.get(StandardMethod.HASH_CODE);\n messager.printMessage(ERROR,\n \"hashCode and equals must be implemented together on FreeBuilder types\",\n underriddenMethod);\n }\n ImmutableMap.Builder<StandardMethod, UnderrideLevel> result = ImmutableMap.builder();\n for (StandardMethod standardMethod : standardMethods.keySet()) {\n if (standardMethods.get(standardMethod).getModifiers().contains(Modifier.FINAL)) {\n result.put(standardMethod, UnderrideLevel.FINAL);\n } else {\n result.put(standardMethod, UnderrideLevel.OVERRIDEABLE);\n }\n }\n return result.build();\n }",
"void addSubsystem(final OperationTransformerRegistry registry, final String name, final ModelVersion version) {\n final OperationTransformerRegistry profile = registry.getChild(PathAddress.pathAddress(PROFILE));\n final OperationTransformerRegistry server = registry.getChild(PathAddress.pathAddress(HOST, SERVER));\n final PathAddress address = PathAddress.pathAddress(PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, name));\n subsystem.mergeSubtree(profile, Collections.singletonMap(address, version));\n if(server != null) {\n subsystem.mergeSubtree(server, Collections.singletonMap(address, version));\n }\n }",
"public static base_response delete(nitro_service client, lbroute resource) throws Exception {\n\t\tlbroute deleteresource = new lbroute();\n\t\tdeleteresource.network = resource.network;\n\t\tdeleteresource.netmask = resource.netmask;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"public static vpnvserver_auditnslogpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_auditnslogpolicy_binding obj = new vpnvserver_auditnslogpolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_auditnslogpolicy_binding response[] = (vpnvserver_auditnslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Returns the formula for the percentage
@param group
@param type
@return | [
"public String getTextForExpression(DJGroup group, DJGroup childGroup, String type) {\n\t\treturn \"new Double( $V{\" + getReportName() + \"_\" + getGroupVariableName(childGroup) + \"}.doubleValue() / $V{\" + getReportName() + \"_\" + getGroupVariableName(type,group.getColumnToGroupBy().getColumnProperty().getProperty()) + \"}.doubleValue())\";\n\t}"
] | [
"public static aaaparameter get(nitro_service service) throws Exception{\n\t\taaaparameter obj = new aaaparameter();\n\t\taaaparameter[] response = (aaaparameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"private AlbumArt findArtInMemoryCaches(DataReference artReference) {\n // First see if we can find the new track in the hot cache as a hot cue\n for (AlbumArt cached : hotCache.values()) {\n if (cached.artReference.equals(artReference)) { // Found a hot cue hit, use it.\n return cached;\n }\n }\n\n // Not in the hot cache, see if it is in our LRU cache\n return artCache.get(artReference);\n }",
"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 }",
"@Override\n public void fire(StepStartedEvent event) {\n for (LifecycleListener listener : listeners) {\n try {\n listener.fire(event);\n } catch (Exception e) {\n logError(listener, e);\n }\n }\n }",
"static void initializeExtension(ExtensionRegistry extensionRegistry, String module,\n ManagementResourceRegistration rootRegistration,\n ExtensionRegistryType extensionRegistryType) {\n try {\n boolean unknownModule = false;\n boolean initialized = false;\n for (Extension extension : Module.loadServiceFromCallerModuleLoader(module, Extension.class)) {\n ClassLoader oldTccl = WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(extension.getClass());\n try {\n if (unknownModule || !extensionRegistry.getExtensionModuleNames().contains(module)) {\n // This extension wasn't handled by the standalone.xml or domain.xml parsing logic, so we\n // need to initialize its parsers so we can display what XML namespaces it supports\n extensionRegistry.initializeParsers(extension, module, null);\n // AS7-6190 - ensure we initialize parsers for other extensions from this module\n // now that we know the registry was unaware of the module\n unknownModule = true;\n }\n extension.initialize(extensionRegistry.getExtensionContext(module, rootRegistration, extensionRegistryType));\n } finally {\n WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTccl);\n }\n initialized = true;\n }\n if (!initialized) {\n throw ControllerLogger.ROOT_LOGGER.notFound(\"META-INF/services/\", Extension.class.getName(), module);\n }\n } catch (ModuleNotFoundException e) {\n // Treat this as a user mistake, e.g. incorrect module name.\n // Throw OFE so post-boot it only gets logged at DEBUG.\n throw ControllerLogger.ROOT_LOGGER.extensionModuleNotFound(e, module);\n } catch (ModuleLoadException e) {\n // The module is there but can't be loaded. Treat this as an internal problem.\n // Throw a runtime exception so it always gets logged at ERROR in the server log with stack trace details.\n throw ControllerLogger.ROOT_LOGGER.extensionModuleLoadingFailure(e, module);\n }\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 appfwglobal_auditnslogpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tappfwglobal_auditnslogpolicy_binding obj = new appfwglobal_auditnslogpolicy_binding();\n\t\tappfwglobal_auditnslogpolicy_binding response[] = (appfwglobal_auditnslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static dnssuffix[] get(nitro_service service, String Dnssuffix[]) throws Exception{\n\t\tif (Dnssuffix !=null && Dnssuffix.length>0) {\n\t\t\tdnssuffix response[] = new dnssuffix[Dnssuffix.length];\n\t\t\tdnssuffix obj[] = new dnssuffix[Dnssuffix.length];\n\t\t\tfor (int i=0;i<Dnssuffix.length;i++) {\n\t\t\t\tobj[i] = new dnssuffix();\n\t\t\t\tobj[i].set_Dnssuffix(Dnssuffix[i]);\n\t\t\t\tresponse[i] = (dnssuffix) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}",
"public boolean isWorkingDay(Day day)\n {\n DayType value = getWorkingDay(day);\n boolean result;\n\n if (value == DayType.DEFAULT)\n {\n ProjectCalendar cal = getParent();\n if (cal != null)\n {\n result = cal.isWorkingDay(day);\n }\n else\n {\n result = (day != Day.SATURDAY && day != Day.SUNDAY);\n }\n }\n else\n {\n result = (value == DayType.WORKING);\n }\n\n return (result);\n }"
] |
Sets the RegExp pattern for the TextBox
@param pattern
@param invalidCharactersInNameErrorMessage | [
"public void setRegExp(final String pattern,\n final String invalidCharactersInNameErrorMessage,\n final String invalidCharacterTypedMessage) {\n regExp = RegExp.compile(pattern);\n this.invalidCharactersInNameErrorMessage = invalidCharactersInNameErrorMessage;\n this.invalidCharacterTypedMessage = invalidCharacterTypedMessage;\n }"
] | [
"private GVRCursorController addDevice(int deviceId) {\n InputDevice device = inputManager.getInputDevice(deviceId);\n GVRControllerType controllerType = getGVRInputDeviceType(device);\n\n if (mEnabledControllerTypes == null)\n {\n return null;\n }\n if (controllerType == GVRControllerType.GAZE && !mEnabledControllerTypes.contains(GVRControllerType.GAZE))\n {\n return null;\n }\n\n int key;\n if (controllerType == GVRControllerType.GAZE) {\n // create the controller if there isn't one. \n if (gazeCursorController == null) {\n gazeCursorController = new GVRGazeCursorController(context, GVRControllerType.GAZE,\n GVRDeviceConstants.OCULUS_GEARVR_DEVICE_NAME,\n GVRDeviceConstants.OCULUS_GEARVR_TOUCHPAD_VENDOR_ID,\n GVRDeviceConstants.OCULUS_GEARVR_TOUCHPAD_PRODUCT_ID);\n }\n // use the cached gaze key\n key = GAZE_CACHED_KEY;\n } else {\n key = getCacheKey(device, controllerType);\n }\n\n if (key != -1)\n {\n GVRCursorController controller = cache.get(key);\n if (controller == null)\n {\n if ((mEnabledControllerTypes == null) || !mEnabledControllerTypes.contains(controllerType))\n {\n return null;\n }\n if (controllerType == GVRControllerType.MOUSE)\n {\n controller = mouseDeviceManager.getCursorController(context, device.getName(), device.getVendorId(), device.getProductId());\n }\n else if (controllerType == GVRControllerType.GAMEPAD)\n {\n controller = gamepadDeviceManager.getCursorController(context, device.getName(), device.getVendorId(), device.getProductId());\n }\n else if (controllerType == GVRControllerType.GAZE)\n {\n controller = gazeCursorController;\n }\n cache.put(key, controller);\n controllerIds.put(device.getId(), controller);\n return controller;\n }\n else\n {\n controllerIds.put(device.getId(), controller);\n }\n }\n return null;\n }",
"private void readResourceAssignments()\n {\n for (MapRow row : getTable(\"USGTAB\"))\n {\n Task task = m_projectFile.getTaskByUniqueID(row.getInteger(\"TASK_ID\"));\n Resource resource = m_projectFile.getResourceByUniqueID(row.getInteger(\"RESOURCE_ID\"));\n if (task != null && resource != null)\n {\n ResourceAssignment assignment = task.addResourceAssignment(resource);\n m_eventManager.fireAssignmentReadEvent(assignment);\n }\n }\n }",
"public static lbvserver_filterpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_filterpolicy_binding obj = new lbvserver_filterpolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_filterpolicy_binding response[] = (lbvserver_filterpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static gslbsite[] get(nitro_service service, options option) throws Exception{\n\t\tgslbsite obj = new gslbsite();\n\t\tgslbsite[] response = (gslbsite[])obj.get_resources(service,option);\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 void setEnterpriseCost(int index, Number value)\n {\n set(selectField(AssignmentFieldLists.ENTERPRISE_COST, index), value);\n }",
"private void recurseAndAddFiles(GraphRewrite event, EvaluationContext context,\n Path tempFolder,\n FileService fileService, ArchiveModel archiveModel,\n FileModel parentFileModel, boolean subArchivesOnly)\n {\n checkCancelled(event);\n\n int numberAdded = 0;\n\n FileFilter filter = TrueFileFilter.TRUE;\n if (archiveModel instanceof IdentifiedArchiveModel)\n {\n filter = new IdentifiedArchiveFileFilter(archiveModel);\n }\n\n File fileReference;\n if (parentFileModel instanceof ArchiveModel)\n fileReference = new File(((ArchiveModel) parentFileModel).getUnzippedDirectory());\n else\n fileReference = parentFileModel.asFile();\n\n WindupJavaConfigurationService windupJavaConfigurationService = new WindupJavaConfigurationService(event.getGraphContext());\n File[] subFiles = fileReference.listFiles();\n if (subFiles == null)\n return;\n\n for (File subFile : subFiles)\n {\n if (!filter.accept(subFile))\n continue;\n\n if (subArchivesOnly && !ZipUtil.endsWithZipExtension(subFile.getAbsolutePath()))\n continue;\n\n FileModel subFileModel = fileService.createByFilePath(parentFileModel, subFile.getAbsolutePath());\n\n // check if this file should be ignored\n if (windupJavaConfigurationService.checkIfIgnored(event, subFileModel))\n continue;\n\n numberAdded++;\n if (numberAdded % 250 == 0)\n event.getGraphContext().commit();\n\n if (subFile.isFile() && ZipUtil.endsWithZipExtension(subFileModel.getFilePath()))\n {\n File newZipFile = subFileModel.asFile();\n ArchiveModel newArchiveModel = GraphService.addTypeToModel(event.getGraphContext(), subFileModel, ArchiveModel.class);\n newArchiveModel.setParentArchive(archiveModel);\n newArchiveModel.setArchiveName(newZipFile.getName());\n\n /*\n * New archive must be reloaded in case the archive should be ignored\n */\n newArchiveModel = GraphService.refresh(event.getGraphContext(), newArchiveModel);\n\n ArchiveModel canonicalArchiveModel = null;\n for (FileModel otherMatches : fileService.findAllByProperty(FileModel.SHA1_HASH, newArchiveModel.getSHA1Hash()))\n {\n if (otherMatches instanceof ArchiveModel && !otherMatches.equals(newArchiveModel) && !(otherMatches instanceof DuplicateArchiveModel))\n {\n canonicalArchiveModel = (ArchiveModel)otherMatches;\n break;\n }\n }\n\n if (canonicalArchiveModel != null)\n {\n // handle as duplicate\n DuplicateArchiveModel duplicateArchive = GraphService.addTypeToModel(event.getGraphContext(), newArchiveModel, DuplicateArchiveModel.class);\n duplicateArchive.setCanonicalArchive(canonicalArchiveModel);\n\n // create dupes for child archives\n unzipToTempDirectory(event, context, tempFolder, newZipFile, duplicateArchive, true);\n } else\n {\n unzipToTempDirectory(event, context, tempFolder, newZipFile, newArchiveModel, false);\n }\n } else if (subFile.isDirectory())\n {\n recurseAndAddFiles(event, context, tempFolder, fileService, archiveModel, subFileModel, false);\n }\n }\n }",
"private static void checkPreconditions(List<String> requiredSubStrings) {\n\t\tif( requiredSubStrings == null ) {\n\t\t\tthrow new NullPointerException(\"requiredSubStrings List should not be null\");\n\t\t} else if( requiredSubStrings.isEmpty() ) {\n\t\t\tthrow new IllegalArgumentException(\"requiredSubStrings List should not be empty\");\n\t\t}\n\t}",
"public final File getBuildFileFor(\n final Configuration configuration, final File jasperFileXml,\n final String extension, final Logger logger) {\n final String configurationAbsolutePath = configuration.getDirectory().getPath();\n final int prefixToConfiguration = configurationAbsolutePath.length() + 1;\n final String parentDir = jasperFileXml.getAbsoluteFile().getParent();\n final String relativePathToFile;\n if (configurationAbsolutePath.equals(parentDir)) {\n relativePathToFile = FilenameUtils.getBaseName(jasperFileXml.getName());\n } else {\n final String relativePathToContainingDirectory = parentDir.substring(prefixToConfiguration);\n relativePathToFile = relativePathToContainingDirectory + File.separator +\n FilenameUtils.getBaseName(jasperFileXml.getName());\n }\n\n final File buildFile = new File(getJasperCompilation(configuration), relativePathToFile + extension);\n\n if (!buildFile.getParentFile().exists() && !buildFile.getParentFile().mkdirs()) {\n logger.error(\"Unable to create directory for containing compiled jasper report templates: {}\",\n buildFile.getParentFile());\n }\n return buildFile;\n }"
] |
Use this API to add lbroute. | [
"public static base_response add(nitro_service client, lbroute resource) throws Exception {\n\t\tlbroute addresource = new lbroute();\n\t\taddresource.network = resource.network;\n\t\taddresource.netmask = resource.netmask;\n\t\taddresource.gatewayname = resource.gatewayname;\n\t\treturn addresource.add_resource(client);\n\t}"
] | [
"protected RdfSerializer createRdfSerializer() throws IOException {\n\n\t\tString outputDestinationFinal;\n\t\tif (this.outputDestination != null) {\n\t\t\toutputDestinationFinal = this.outputDestination;\n\t\t} else {\n\t\t\toutputDestinationFinal = \"{PROJECT}\" + this.taskName + \"{DATE}\"\n\t\t\t\t\t+ \".nt\";\n\t\t}\n\n\t\tOutputStream exportOutputStream = getOutputStream(this.useStdOut,\n\t\t\t\tinsertDumpInformation(outputDestinationFinal),\n\t\t\t\tthis.compressionType);\n\n\t\tRdfSerializer serializer = new RdfSerializer(RDFFormat.NTRIPLES,\n\t\t\t\texportOutputStream, this.sites,\n\t\t\t\tPropertyRegister.getWikidataPropertyRegister());\n\t\tserializer.setTasks(this.tasks);\n\n\t\treturn serializer;\n\t}",
"@TargetApi(VERSION_CODES.KITKAT)\n public static void hideSystemUI(Activity activity) {\n // Set the IMMERSIVE flag.\n // Set the content to appear under the system bars so that the content\n // doesn't resize when the system bars hideSelf and show.\n View decorView = activity.getWindow().getDecorView();\n decorView.setSystemUiVisibility(\n View.SYSTEM_UI_FLAG_LAYOUT_STABLE\n | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION\n | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN\n | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hideSelf nav bar\n | View.SYSTEM_UI_FLAG_FULLSCREEN // hideSelf status bar\n | View.SYSTEM_UI_FLAG_IMMERSIVE\n );\n }",
"public static systementitydata[] get(nitro_service service, systementitydata_args args) throws Exception{\n\t\tsystementitydata obj = new systementitydata();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tsystementitydata[] response = (systementitydata[])obj.get_resources(service, option);\n\t\treturn response;\n\t}",
"private org.apache.tools.ant.types.Path resolveFiles(org.apache.tools.ant.types.Path path) {\n org.apache.tools.ant.types.Path cloned = new org.apache.tools.ant.types.Path(getProject());\n for (String location : path.list()) {\n cloned.createPathElement().setLocation(new File(location));\n }\n return cloned;\n }",
"@Override\n\tpublic void visit(Rule rule) {\n\t\tRule copy = null;\n\t\tFilter filterCopy = null;\n\n\t\tif (rule.getFilter() != null) {\n\t\t\tFilter filter = rule.getFilter();\n\t\t\tfilterCopy = copy(filter);\n\t\t}\n\n\t\tList<Symbolizer> symsCopy = new ArrayList<Symbolizer>();\n\t\tfor (Symbolizer sym : rule.symbolizers()) {\n\t\t\tif (!skipSymbolizer(sym)) {\n\t\t\t\tSymbolizer symCopy = copy(sym);\n\t\t\t\tsymsCopy.add(symCopy);\n\t\t\t}\n\t\t}\n\n\t\tGraphic[] legendCopy = rule.getLegendGraphic();\n\t\tfor (int i = 0; i < legendCopy.length; i++) {\n\t\t\tlegendCopy[i] = copy(legendCopy[i]);\n\t\t}\n\n\t\tDescription descCopy = rule.getDescription();\n\t\tdescCopy = copy(descCopy);\n\n\t\tcopy = sf.createRule();\n\t\tcopy.symbolizers().addAll(symsCopy);\n\t\tcopy.setDescription(descCopy);\n\t\tcopy.setLegendGraphic(legendCopy);\n\t\tcopy.setName(rule.getName());\n\t\tcopy.setFilter(filterCopy);\n\t\tcopy.setElseFilter(rule.isElseFilter());\n\t\tcopy.setMaxScaleDenominator(rule.getMaxScaleDenominator());\n\t\tcopy.setMinScaleDenominator(rule.getMinScaleDenominator());\n\n\t\tif (STRICT && !copy.equals(rule)) {\n\t\t\tthrow new IllegalStateException(\n\t\t\t\t\t\"Was unable to duplicate provided Rule:\" + rule);\n\t\t}\n\t\tpages.push(copy);\n\t}",
"public static base_response disable(nitro_service client, String trapname) throws Exception {\n\t\tsnmpalarm disableresource = new snmpalarm();\n\t\tdisableresource.trapname = trapname;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}",
"public boolean matches(String resourcePath) {\n if (!valid) {\n return false;\n }\n if (resourcePath == null) {\n return acceptsContextPathEmpty;\n }\n if (contextPathRegex != null && !contextPathRegex.matcher(resourcePath).matches()) {\n return false;\n }\n if (contextPathBlacklistRegex != null && contextPathBlacklistRegex.matcher(resourcePath).matches()) {\n return false;\n }\n return true;\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 }",
"private static int nextIndex( String description, int defaultIndex ) {\n\n Pattern startsWithNumber = Pattern.compile( \"(\\\\d+).*\" );\n Matcher matcher = startsWithNumber.matcher( description );\n if( matcher.matches() ) {\n return Integer.parseInt( matcher.group( 1 ) ) - 1;\n }\n\n return defaultIndex;\n }"
] |
Search for photos which match the given search parameters.
@param params
The search parameters
@param perPage
The number of photos to show per page
@param page
The page offset
@return A PhotoList
@throws FlickrException | [
"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 }"
] | [
"private Envelope getBoundsLocal(Filter filter) throws LayerException {\n\t\ttry {\n\t\t\tSession session = getSessionFactory().getCurrentSession();\n\t\t\tCriteria criteria = session.createCriteria(getFeatureInfo().getDataSourceName());\n\t\t\tCriteriaVisitor visitor = new CriteriaVisitor((HibernateFeatureModel) getFeatureModel(), dateFormat);\n\t\t\tCriterion c = (Criterion) filter.accept(visitor, criteria);\n\t\t\tif (c != null) {\n\t\t\t\tcriteria.add(c);\n\t\t\t}\n\t\t\tcriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);\n\t\t\tList<?> features = criteria.list();\n\t\t\tEnvelope bounds = new Envelope();\n\t\t\tfor (Object f : features) {\n\t\t\t\tEnvelope geomBounds = getFeatureModel().getGeometry(f).getEnvelopeInternal();\n\t\t\t\tif (!geomBounds.isNull()) {\n\t\t\t\t\tbounds.expandToInclude(geomBounds);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn bounds;\n\t\t} catch (HibernateException he) {\n\t\t\tthrow new HibernateLayerException(he, ExceptionCode.HIBERNATE_LOAD_FILTER_FAIL, getFeatureInfo()\n\t\t\t\t\t.getDataSourceName(), filter.toString());\n\t\t}\n\t}",
"@SuppressWarnings(\"unchecked\")\n public final FluentModelImplT withoutTag(String key) {\n if (this.inner().getTags() != null) {\n this.inner().getTags().remove(key);\n }\n return (FluentModelImplT) this;\n }",
"public static java.util.Date newDateTime() {\n return new java.util.Date((System.currentTimeMillis() / SECOND_MILLIS) * SECOND_MILLIS);\n }",
"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 void addAll(int index, T... items) {\n List<T> collection = Arrays.asList(items);\n synchronized (mLock) {\n if (mOriginalValues != null) {\n mOriginalValues.addAll(index, collection);\n } else {\n mObjects.addAll(index, collection);\n }\n }\n if (mNotifyOnChange) notifyDataSetChanged();\n }",
"public static <T> T assertNull(T value, String message) {\n if (value != null)\n throw new IllegalStateException(message);\n return value;\n }",
"public void useNewSOAPServiceWithOldClient() throws Exception {\n \n URL wsdlURL = getClass().getResource(\"/CustomerServiceNew.wsdl\");\n com.example.customerservice.CustomerServiceService service = \n new com.example.customerservice.CustomerServiceService(wsdlURL);\n \n com.example.customerservice.CustomerService customerService = \n service.getCustomerServicePort();\n\n // The outgoing new Customer data needs to be transformed for \n // the old service to understand it and the response from the old service\n // needs to be transformed for this new client to understand it.\n Client client = ClientProxy.getClient(customerService);\n addTransformInterceptors(client.getInInterceptors(),\n client.getOutInterceptors(),\n false);\n \n System.out.println(\"Using new SOAP CustomerService with old client\");\n \n customer.v1.Customer customer = createOldCustomer(\"Barry Old to New SOAP\");\n customerService.updateCustomer(customer);\n customer = customerService.getCustomerByName(\"Barry Old to New SOAP\");\n printOldCustomerDetails(customer);\n }",
"public Bundler put(String key, Bundle value) {\n delegate.putBundle(key, value);\n return this;\n }",
"public static int getMpxField(int value)\n {\n int result = 0;\n\n if (value >= 0 && value < MPXJ_MPX_ARRAY.length)\n {\n result = MPXJ_MPX_ARRAY[value];\n }\n return (result);\n }"
] |
add a single Object to the Collection. This method is used during reading Collection elements
from the database. Thus it is is save to cast anObject to the underlying element type of the
collection. | [
"public void ojbAdd(Object anObject)\r\n {\r\n DSetEntry entry = prepareEntry(anObject);\r\n entry.setPosition(elements.size());\r\n elements.add(entry);\r\n }"
] | [
"public void linkOneToOne(Object obj, ClassDescriptor cld, ObjectReferenceDescriptor rds, boolean insert)\n {\n storeAndLinkOneToOne(true, obj, cld, rds, true);\n }",
"public void close()\t{\n\t\tif (watchdog != null) {\n\t\t\twatchdog.cancel();\n\t\t\twatchdog = null;\n\t\t}\n\t\t\n\t\tdisconnect();\n\t\t\n\t\t// clear nodes collection and send queue\n\t\tfor (Object listener : this.zwaveEventListeners.toArray()) {\n\t\t\tif (!(listener instanceof ZWaveNode))\n\t\t\t\tcontinue;\n\t\t\t\n\t\t\tthis.zwaveEventListeners.remove(listener);\n\t\t}\n\t\t\n\t\tthis.zwaveNodes.clear();\n\t\tthis.sendQueue.clear();\n\t\t\n\t\tlogger.info(\"Stopped Z-Wave controller\");\n\t}",
"public static double SymmetricChiSquareDivergence(double[] p, double[] q) {\n double r = 0;\n for (int i = 0; i < p.length; i++) {\n double den = p[i] * q[i];\n if (den != 0) {\n double p1 = p[i] - q[i];\n double p2 = p[i] + q[i];\n r += (p1 * p1 * p2) / den;\n }\n }\n\n return r;\n }",
"private List<String> parseRssFeedForeCast(String feed) {\n String[] result = feed.split(\"<br />\");\n List<String> returnList = new ArrayList<String>();\n String[] result2 = result[2].split(\"<BR />\");\n\n returnList.add(result2[3] + \"\\n\");\n returnList.add(result[3] + \"\\n\");\n returnList.add(result[4] + \"\\n\");\n returnList.add(result[5] + \"\\n\");\n returnList.add(result[6] + \"\\n\");\n\n return returnList;\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 void addTypes(Injector injector, List<Class<?>> types) {\n for (Binding<?> binding : injector.getBindings().values()) {\n Key<?> key = binding.getKey();\n Type type = key.getTypeLiteral().getType();\n if (hasAnnotatedMethods(type)) {\n types.add(((Class<?>)type));\n }\n }\n if (injector.getParent() != null) {\n addTypes(injector.getParent(), types);\n }\n }",
"public static String readFileContentToString(String filePath)\n throws IOException {\n String content = \"\";\n content = Files.toString(new File(filePath), Charsets.UTF_8);\n return content;\n }",
"protected <T, A> ActiveOperation<T, A> getActiveOperation(final ManagementRequestHeader header) {\n return getActiveOperation(header.getBatchId());\n }",
"public DbConn getConn()\n {\n Connection cnx = null;\n try\n {\n Thread.interrupted(); // this is VERY sad. Needed for Oracle driver which otherwise fails spectacularly.\n cnx = _ds.getConnection();\n if (cnx.getAutoCommit())\n {\n cnx.setAutoCommit(false);\n cnx.rollback(); // To ensure no open transaction created by the pool before changing TX mode\n }\n\n if (cnx.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED)\n {\n cnx.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);\n }\n\n return new DbConn(this, cnx);\n }\n catch (SQLException e)\n {\n DbHelper.closeQuietly(cnx); // May have been left open when the pool has given us a failed connection.\n throw new DatabaseException(e);\n }\n }"
] |
Generates a sub-trajectory | [
"@Override\n\tpublic Trajectory subList(int fromIndex, int toIndex) {\n\t\tTrajectory t = new Trajectory(dimension);\n\t\t\n\t\tfor(int i = fromIndex; i < toIndex; i++){\n\t\t\tt.add(this.get(i));\n\t\t}\n\t\treturn t;\n\t}"
] | [
"public static List<Dependency> getAllDependencies(final Module module) {\n final Set<Dependency> dependencies = new HashSet<Dependency>();\n final List<String> producedArtifacts = new ArrayList<String>();\n for(final Artifact artifact: getAllArtifacts(module)){\n producedArtifacts.add(artifact.getGavc());\n }\n\n dependencies.addAll(getAllDependencies(module, producedArtifacts));\n\n return new ArrayList<Dependency>(dependencies);\n }",
"private void writeTasks(Project project)\n {\n Project.Tasks tasks = m_factory.createProjectTasks();\n project.setTasks(tasks);\n List<Project.Tasks.Task> list = tasks.getTask();\n\n for (Task task : m_projectFile.getTasks())\n {\n list.add(writeTask(task));\n }\n }",
"public static Multimap<String, String> convertToMultiMap(final PObject objectParams) {\n Multimap<String, String> params = HashMultimap.create();\n if (objectParams != null) {\n Iterator<String> customParamsIter = objectParams.keys();\n while (customParamsIter.hasNext()) {\n String key = customParamsIter.next();\n if (objectParams.isArray(key)) {\n final PArray array = objectParams.optArray(key);\n for (int i = 0; i < array.size(); i++) {\n params.put(key, array.getString(i));\n }\n } else {\n params.put(key, objectParams.optString(key, \"\"));\n }\n }\n }\n\n return params;\n }",
"private boolean isRedeployAfterRemoval(ModelNode operation) {\n return operation.hasDefined(DEPLOYMENT_OVERLAY_LINK_REMOVAL) &&\n operation.get(DEPLOYMENT_OVERLAY_LINK_REMOVAL).asBoolean();\n }",
"private static String getEncodedInstance(String encodedResponse) {\n if (isReturnValue(encodedResponse) || isThrownException(encodedResponse)) {\n return encodedResponse.substring(4);\n }\n\n return encodedResponse;\n }",
"private void appendClazzColumnForSelect(StringBuffer buf)\r\n {\r\n ClassDescriptor cld = getSearchClassDescriptor();\r\n ClassDescriptor[] clds = getMultiJoinedClassDescriptors(cld);\r\n\r\n if (clds.length == 0)\r\n {\r\n return;\r\n }\r\n \r\n buf.append(\",CASE\");\r\n\r\n for (int i = clds.length; i > 0; i--)\r\n {\r\n buf.append(\" WHEN \");\r\n\r\n ClassDescriptor subCld = clds[i - 1];\r\n FieldDescriptor[] fieldDescriptors = subCld.getPkFields();\r\n\r\n TableAlias alias = getTableAliasForClassDescriptor(subCld);\r\n for (int j = 0; j < fieldDescriptors.length; j++)\r\n {\r\n FieldDescriptor field = fieldDescriptors[j];\r\n if (j > 0)\r\n {\r\n buf.append(\" AND \");\r\n }\r\n appendColumn(alias, field, buf);\r\n buf.append(\" IS NOT NULL\");\r\n }\r\n buf.append(\" THEN '\").append(subCld.getClassNameOfObject()).append(\"'\");\r\n }\r\n buf.append(\" ELSE '\").append(cld.getClassNameOfObject()).append(\"'\");\r\n buf.append(\" END AS \" + SqlHelper.OJB_CLASS_COLUMN);\r\n }",
"public Date getFinish()\n {\n Date result = (Date) getCachedValue(AssignmentField.FINISH);\n if (result == null)\n {\n result = getTask().getFinish();\n }\n return result;\n }",
"public static base_responses add(nitro_service client, authenticationradiusaction resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tauthenticationradiusaction addresources[] = new authenticationradiusaction[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new authenticationradiusaction();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].serverip = resources[i].serverip;\n\t\t\t\taddresources[i].serverport = resources[i].serverport;\n\t\t\t\taddresources[i].authtimeout = resources[i].authtimeout;\n\t\t\t\taddresources[i].radkey = resources[i].radkey;\n\t\t\t\taddresources[i].radnasip = resources[i].radnasip;\n\t\t\t\taddresources[i].radnasid = resources[i].radnasid;\n\t\t\t\taddresources[i].radvendorid = resources[i].radvendorid;\n\t\t\t\taddresources[i].radattributetype = resources[i].radattributetype;\n\t\t\t\taddresources[i].radgroupsprefix = resources[i].radgroupsprefix;\n\t\t\t\taddresources[i].radgroupseparator = resources[i].radgroupseparator;\n\t\t\t\taddresources[i].passencoding = resources[i].passencoding;\n\t\t\t\taddresources[i].ipvendorid = resources[i].ipvendorid;\n\t\t\t\taddresources[i].ipattributetype = resources[i].ipattributetype;\n\t\t\t\taddresources[i].accounting = resources[i].accounting;\n\t\t\t\taddresources[i].pwdvendorid = resources[i].pwdvendorid;\n\t\t\t\taddresources[i].pwdattributetype = resources[i].pwdattributetype;\n\t\t\t\taddresources[i].defaultauthenticationgroup = resources[i].defaultauthenticationgroup;\n\t\t\t\taddresources[i].callingstationid = resources[i].callingstationid;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"public static base_responses add(nitro_service client, snmpmanager resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsnmpmanager addresources[] = new snmpmanager[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new snmpmanager();\n\t\t\t\taddresources[i].ipaddress = resources[i].ipaddress;\n\t\t\t\taddresources[i].netmask = resources[i].netmask;\n\t\t\t\taddresources[i].domainresolveretry = resources[i].domainresolveretry;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}"
] |
Walk project references recursively, adding thrift files to the provided list. | [
"List<File> getRecursiveThriftFiles(MavenProject project, String outputDirectory, List<File> files) throws IOException {\n HashFunction hashFun = Hashing.md5();\n File dir = new File(new File(project.getFile().getParent(), \"target\"), outputDirectory);\n if (dir.exists()) {\n URI baseDir = getFileURI(dir);\n for (File f : findThriftFilesInDirectory(dir)) {\n URI fileURI = getFileURI(f);\n String relPath = baseDir.relativize(fileURI).getPath();\n File destFolder = getResourcesOutputDirectory();\n destFolder.mkdirs();\n File destFile = new File(destFolder, relPath);\n if (!destFile.exists() || (destFile.isFile() && !Files.hash(f, hashFun).equals(Files.hash(destFile, hashFun)))) {\n getLog().info(format(\"copying %s to %s\", f.getCanonicalPath(), destFile.getCanonicalPath()));\n copyFile(f, destFile);\n }\n files.add(destFile);\n }\n }\n Map<String, MavenProject> refs = project.getProjectReferences();\n for (String name : refs.keySet()) {\n getRecursiveThriftFiles(refs.get(name), outputDirectory, files);\n }\n return files;\n }"
] | [
"static ReadMasterDomainModelUtil readMasterDomainResourcesForInitialConnect(final Transformers transformers,\n final Transformers.TransformationInputs transformationInputs,\n final Transformers.ResourceIgnoredTransformationRegistry ignoredTransformationRegistry,\n final Resource domainRoot) throws OperationFailedException {\n\n Resource transformedResource = transformers.transformRootResource(transformationInputs, domainRoot, ignoredTransformationRegistry);\n ReadMasterDomainModelUtil util = new ReadMasterDomainModelUtil();\n util.describedResources = util.describeAsNodeList(PathAddress.EMPTY_ADDRESS, transformedResource, false);\n return util;\n }",
"protected void ensureDJStyles() {\n //first of all, register all parent styles if any\n for (Style style : getReport().getStyles().values()) {\n addStyleToDesign(style);\n }\n\n Style defaultDetailStyle = getReport().getOptions().getDefaultDetailStyle();\n\n Style defaultHeaderStyle = getReport().getOptions().getDefaultHeaderStyle();\n for (AbstractColumn column : report.getColumns()) {\n if (column.getStyle() == null)\n column.setStyle(defaultDetailStyle);\n if (column.getHeaderStyle() == null)\n column.setHeaderStyle(defaultHeaderStyle);\n }\n }",
"public void put(@NotNull final Transaction txn, final long localId,\n final int blobId, @NotNull final ByteIterable value) {\n primaryStore.put(txn, PropertyKey.propertyKeyToEntry(new PropertyKey(localId, blobId)), value);\n allBlobsIndex.put(txn, IntegerBinding.intToCompressedEntry(blobId), LongBinding.longToCompressedEntry(localId));\n }",
"private void addCalendarExceptions(Table table, ProjectCalendar calendar, Integer exceptionID)\n {\n Integer currentExceptionID = exceptionID;\n while (true)\n {\n MapRow row = table.find(currentExceptionID);\n if (row == null)\n {\n break;\n }\n\n Date date = row.getDate(\"DATE\");\n ProjectCalendarException exception = calendar.addCalendarException(date, date);\n if (row.getBoolean(\"WORKING\"))\n {\n exception.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING);\n exception.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON);\n }\n\n currentExceptionID = row.getInteger(\"NEXT_CALENDAR_EXCEPTION_ID\");\n }\n }",
"public void fireCalendarWrittenEvent(ProjectCalendar calendar)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.calendarWritten(calendar);\n }\n }\n }",
"public static String defaultString(final String str, final String fallback) {\n return isNullOrEmpty(str) ? fallback : str;\n }",
"public static double Y(double x) {\r\n if (x < 8.0) {\r\n double y = x * x;\r\n double ans1 = x * (-0.4900604943e13 + y * (0.1275274390e13\r\n + y * (-0.5153438139e11 + y * (0.7349264551e9\r\n + y * (-0.4237922726e7 + y * 0.8511937935e4)))));\r\n double ans2 = 0.2499580570e14 + y * (0.4244419664e12\r\n + y * (0.3733650367e10 + y * (0.2245904002e8\r\n + y * (0.1020426050e6 + y * (0.3549632885e3 + y)))));\r\n return (ans1 / ans2) + 0.636619772 * (J(x) * Math.log(x) - 1.0 / x);\r\n } else {\r\n double z = 8.0 / x;\r\n double y = z * z;\r\n double xx = x - 2.356194491;\r\n double ans1 = 1.0 + y * (0.183105e-2 + y * (-0.3516396496e-4\r\n + y * (0.2457520174e-5 + y * (-0.240337019e-6))));\r\n double ans2 = 0.04687499995 + y * (-0.2002690873e-3\r\n + y * (0.8449199096e-5 + y * (-0.88228987e-6\r\n + y * 0.105787412e-6)));\r\n return Math.sqrt(0.636619772 / x) *\r\n (Math.sin(xx) * ans1 + z * Math.cos(xx) * ans2);\r\n }\r\n }",
"public void associateTypeJndiResource(JNDIResourceModel resource, String type)\n {\n if (type == null || resource == null)\n {\n return;\n }\n\n if (StringUtils.equals(type, \"javax.sql.DataSource\") && !(resource instanceof DataSourceModel))\n {\n DataSourceModel ds = GraphService.addTypeToModel(this.getGraphContext(), resource, DataSourceModel.class);\n }\n else if (StringUtils.equals(type, \"javax.jms.Queue\") && !(resource instanceof JmsDestinationModel))\n {\n JmsDestinationModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsDestinationModel.class);\n jms.setDestinationType(JmsDestinationType.QUEUE);\n }\n else if (StringUtils.equals(type, \"javax.jms.QueueConnectionFactory\") && !(resource instanceof JmsConnectionFactoryModel))\n {\n JmsConnectionFactoryModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsConnectionFactoryModel.class);\n jms.setConnectionFactoryType(JmsDestinationType.QUEUE);\n }\n else if (StringUtils.equals(type, \"javax.jms.Topic\") && !(resource instanceof JmsDestinationModel))\n {\n JmsDestinationModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsDestinationModel.class);\n jms.setDestinationType(JmsDestinationType.TOPIC);\n }\n else if (StringUtils.equals(type, \"javax.jms.TopicConnectionFactory\") && !(resource instanceof JmsConnectionFactoryModel))\n {\n JmsConnectionFactoryModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsConnectionFactoryModel.class);\n jms.setConnectionFactoryType(JmsDestinationType.TOPIC);\n }\n }",
"@PostConstruct\n\tprotected void checkPluginDependencies() throws GeomajasException {\n\t\tif (\"true\".equals(System.getProperty(\"skipPluginDependencyCheck\"))) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (null == declaredPlugins) {\n\t\t\treturn;\n\t\t}\n\n\t\t// start by going through all plug-ins to build a map of versions for plug-in keys\n\t\t// includes verification that each key is only used once\n\t\tMap<String, String> versions = new HashMap<String, String>();\n\t\tfor (PluginInfo plugin : declaredPlugins.values()) {\n\t\t\tString name = plugin.getVersion().getName();\n\t\t\tString version = plugin.getVersion().getVersion();\n\t\t\t// check for multiple plugin with same name but different versions (duplicates allowed for jar+source dep)\n\t\t\tif (null != version) {\n\t\t\t\tString otherVersion = versions.get(name);\n\t\t\t\tif (null != otherVersion) {\n\t\t\t\t\tif (!version.startsWith(EXPR_START)) {\n\t\t\t\t\t\tif (!otherVersion.startsWith(EXPR_START) && !otherVersion.equals(version)) {\n\t\t\t\t\t\t\tthrow new GeomajasException(ExceptionCode.DEPENDENCY_CHECK_INVALID_DUPLICATE,\n\t\t\t\t\t\t\t\t\tname, version, versions.get(name));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tversions.put(name, version);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tversions.put(name, version);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Check dependencies\n\t\tStringBuilder message = new StringBuilder();\n\t\tString backendVersion = versions.get(\"Geomajas\");\n\t\tfor (PluginInfo plugin : declaredPlugins.values()) {\n\t\t\tString name = plugin.getVersion().getName();\n\t\t\tmessage.append(checkVersion(name, \"Geomajas back-end\", plugin.getBackendVersion(), backendVersion));\n\t\t\tList<PluginVersionInfo> dependencies = plugin.getDependencies();\n\t\t\tif (null != dependencies) {\n\t\t\t\tfor (PluginVersionInfo dependency : plugin.getDependencies()) {\n\t\t\t\t\tString depName = dependency.getName();\n\t\t\t\t\tmessage.append(checkVersion(name, depName, dependency.getVersion(), versions.get(depName)));\n\t\t\t\t}\n\t\t\t}\n\t\t\tdependencies = plugin.getOptionalDependencies();\n\t\t\tif (null != dependencies) {\n\t\t\t\tfor (PluginVersionInfo dependency : dependencies) {\n\t\t\t\t\tString depName = dependency.getName();\n\t\t\t\t\tString availableVersion = versions.get(depName);\n\t\t\t\t\tif (null != availableVersion) {\n\t\t\t\t\t\tmessage.append(checkVersion(name, depName, dependency.getVersion(), versions.get(depName)));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (message.length() > 0) {\n\t\t\tthrow new GeomajasException(ExceptionCode.DEPENDENCY_CHECK_FAILED, message.toString());\n\t\t}\n\n\t\trecorder.record(GROUP, VALUE);\n\t}"
] |
Sets a JSON String as a request entity.
@param connnection The request of {@link HttpConnection}
@param body The JSON String to set. | [
"public static void setEntity(HttpConnection connnection, String body, String contentType) {\n connnection.requestProperties.put(\"Content-type\", contentType);\n connnection.setRequestBody(body);\n }"
] | [
"private int getPositiveInteger(String number) {\n try {\n return Math.max(0, Integer.parseInt(number));\n } catch (NumberFormatException e) {\n return 0;\n }\n }",
"protected static void validateSignature(final DataInput input) throws IOException {\n final byte[] signatureBytes = new byte[4];\n input.readFully(signatureBytes);\n if (!Arrays.equals(ManagementProtocol.SIGNATURE, signatureBytes)) {\n throw ProtocolLogger.ROOT_LOGGER.invalidSignature(Arrays.toString(signatureBytes));\n }\n }",
"public PatchingResult rollbackLast(final ContentVerificationPolicy contentPolicy, final boolean resetConfiguration, InstallationManager.InstallationModification modification) throws PatchingException {\n\n // Determine the patch id to rollback\n String patchId;\n final List<String> oneOffs = modification.getPatchIDs();\n if (oneOffs.isEmpty()) {\n patchId = modification.getCumulativePatchID();\n if (patchId == null || Constants.NOT_PATCHED.equals(patchId)) {\n throw PatchLogger.ROOT_LOGGER.noPatchesApplied();\n }\n } else {\n patchId = oneOffs.get(0);//oneOffs.get(oneOffs.size() - 1);\n }\n return rollbackPatch(patchId, contentPolicy, false, resetConfiguration, modification);\n }",
"@Pure\n\tpublic static <P1> Procedure0 curry(final Procedure1<? super P1> procedure, final P1 argument) {\n\t\tif (procedure == null)\n\t\t\tthrow new NullPointerException(\"procedure\");\n\t\treturn new Procedure0() {\n\t\t\t@Override\n\t\t\tpublic void apply() {\n\t\t\t\tprocedure.apply(argument);\n\t\t\t}\n\t\t};\n\t}",
"public Map<String, SetAndCount> getAggregateResultFullSummary() {\n\n Map<String, SetAndCount> summaryMap = new ConcurrentHashMap<String, SetAndCount>();\n\n for (Entry<String, LinkedHashSet<String>> entry : aggregateResultMap\n .entrySet()) {\n summaryMap.put(entry.getKey(), new SetAndCount(entry.getValue()));\n }\n\n return summaryMap;\n }",
"public List<GVRAtlasInformation> getAtlasInformation()\n {\n if ((mImage != null) && (mImage instanceof GVRImageAtlas))\n {\n return ((GVRImageAtlas) mImage).getAtlasInformation();\n }\n return null;\n }",
"public ResultSetAndStatement executeSQL(\r\n final String sql,\r\n ClassDescriptor cld,\r\n ValueContainer[] values,\r\n boolean scrollable)\r\n throws PersistenceBrokerException\r\n {\r\n if (logger.isDebugEnabled()) logger.debug(\"executeSQL: \" + sql);\r\n final boolean isStoredprocedure = isStoredProcedure(sql);\r\n final StatementManagerIF sm = broker.serviceStatementManager();\r\n PreparedStatement stmt = null;\r\n ResultSet rs = null;\r\n try\r\n {\r\n stmt = sm.getPreparedStatement(cld, sql,\r\n scrollable, StatementManagerIF.FETCH_SIZE_NOT_EXPLICITLY_SET, isStoredprocedure);\r\n if (isStoredprocedure)\r\n {\r\n // Query implemented as a stored procedure, which must return a result set.\r\n // Query sytax is: { ?= call PROCEDURE_NAME(?,...,?)}\r\n getPlatform().registerOutResultSet((CallableStatement) stmt, 1);\r\n sm.bindValues(stmt, values, 2);\r\n stmt.execute();\r\n rs = (ResultSet) ((CallableStatement) stmt).getObject(1);\r\n }\r\n else\r\n {\r\n sm.bindValues(stmt, values, 1);\r\n rs = stmt.executeQuery();\r\n }\r\n\r\n // as we return the resultset for further operations, we cannot release the statement yet.\r\n // that has to be done by the JdbcAccess-clients (i.e. RsIterator, ProxyRsIterator and PkEnumeration.)\r\n return new ResultSetAndStatement(sm, stmt, rs, new SelectStatement()\r\n {\r\n public Query getQueryInstance()\r\n {\r\n return null;\r\n }\r\n\r\n public int getColumnIndex(FieldDescriptor fld)\r\n {\r\n return JdbcType.MIN_INT;\r\n }\r\n\r\n public String getStatement()\r\n {\r\n return sql;\r\n }\r\n });\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n // release resources on exception\r\n sm.closeResources(stmt, rs);\r\n logger.error(\"PersistenceBrokerException during the execution of the SQL query: \" + e.getMessage(), e);\r\n throw e;\r\n }\r\n catch (SQLException e)\r\n {\r\n // release resources on exception\r\n sm.closeResources(stmt, rs);\r\n throw ExceptionHelper.generateException(e, sql, cld, values, logger, null);\r\n }\r\n }",
"void close(Supplier<CentralDogmaException> failureCauseSupplier) {\n requireNonNull(failureCauseSupplier, \"failureCauseSupplier\");\n if (closePending.compareAndSet(null, failureCauseSupplier)) {\n repositoryWorker.execute(() -> {\n rwLock.writeLock().lock();\n try {\n if (commitIdDatabase != null) {\n try {\n commitIdDatabase.close();\n } catch (Exception e) {\n logger.warn(\"Failed to close a commitId database:\", e);\n }\n }\n\n if (jGitRepository != null) {\n try {\n jGitRepository.close();\n } catch (Exception e) {\n logger.warn(\"Failed to close a Git repository: {}\",\n jGitRepository.getDirectory(), e);\n }\n }\n } finally {\n rwLock.writeLock().unlock();\n commitWatchers.close(failureCauseSupplier);\n closeFuture.complete(null);\n }\n });\n }\n\n closeFuture.join();\n }",
"private static String wordShapeDan1(String s) {\r\n boolean digit = true;\r\n boolean upper = true;\r\n boolean lower = true;\r\n boolean mixed = true;\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 digit = false;\r\n }\r\n if (!Character.isLowerCase(c)) {\r\n lower = false;\r\n }\r\n if (!Character.isUpperCase(c)) {\r\n upper = false;\r\n }\r\n if ((i == 0 && !Character.isUpperCase(c)) || (i >= 1 && !Character.isLowerCase(c))) {\r\n mixed = false;\r\n }\r\n }\r\n if (digit) {\r\n return \"ALL-DIGITS\";\r\n }\r\n if (upper) {\r\n return \"ALL-UPPER\";\r\n }\r\n if (lower) {\r\n return \"ALL-LOWER\";\r\n }\r\n if (mixed) {\r\n return \"MIXED-CASE\";\r\n }\r\n return \"OTHER\";\r\n }"
] |
Delete the partition steal information from the rebalancer state
@param stealInfo The steal information to delete | [
"public void deleteRebalancingState(RebalanceTaskInfo stealInfo) {\n // acquire write lock\n writeLock.lock();\n try {\n RebalancerState rebalancerState = getRebalancerState();\n\n if(!rebalancerState.remove(stealInfo))\n throw new IllegalArgumentException(\"Couldn't find \" + stealInfo + \" in \"\n + rebalancerState + \" while deleting\");\n\n if(rebalancerState.isEmpty()) {\n logger.debug(\"Cleaning all rebalancing state\");\n cleanAllRebalancingState();\n } else {\n put(REBALANCING_STEAL_INFO, rebalancerState);\n initCache(REBALANCING_STEAL_INFO);\n }\n } finally {\n writeLock.unlock();\n }\n }"
] | [
"public List<Map<String, String>> pipelinePossibleStates(NWiseAction action, List<Map<String, String>> possibleStateList) {\r\n String[] coVariables = action.getCoVariables().split(\",\");\r\n int n = Integer.valueOf(action.getN());\n\r\n List<Map<String, String>> newPossibleStateList = new ArrayList<>();\n\r\n for (Map<String, String> possibleState : possibleStateList) {\r\n Map<String, String[]> variableDomains = new HashMap<>();\r\n Map<String, String> defaultVariableValues = new HashMap<>();\r\n for (String variable : coVariables) {\r\n String variableMetaInfo = possibleState.get(variable);\r\n String[] variableDomain = variableMetaInfo.split(\",\");\r\n variableDomains.put(variable, variableDomain);\r\n defaultVariableValues.put(variable, variableDomain[0]);\r\n }\n\r\n List<Map<String, String>> nWiseCombinations = produceNWise(n, coVariables, variableDomains);\r\n for (Map<String, String> nWiseCombination : nWiseCombinations) {\r\n Map<String, String> newPossibleState = new HashMap<>(possibleState);\r\n newPossibleState.putAll(defaultVariableValues);\r\n newPossibleState.putAll(nWiseCombination);\r\n newPossibleStateList.add(newPossibleState);\r\n }\r\n }\n\r\n return newPossibleStateList;\r\n }",
"@Override\r\n public String replace(File file, String flickrId, boolean async) throws FlickrException {\r\n Payload payload = new Payload(file, flickrId);\r\n return sendReplaceRequest(async, payload);\r\n }",
"private void sendAnnouncement(InetAddress broadcastAddress) {\n try {\n DatagramPacket announcement = new DatagramPacket(announcementBytes, announcementBytes.length,\n broadcastAddress, DeviceFinder.ANNOUNCEMENT_PORT);\n socket.get().send(announcement);\n Thread.sleep(getAnnounceInterval());\n } catch (Throwable t) {\n logger.warn(\"Unable to send announcement packet, shutting down\", t);\n stop();\n }\n }",
"protected float getLayoutOffset() {\n //final int offsetSign = getOffsetSign();\n final float axisSize = getViewPortSize(getOrientationAxis());\n float layoutOffset = - axisSize / 2;\n Log.d(LAYOUT, TAG, \"getLayoutOffset(): dimension: %5.2f, layoutOffset: %5.2f\",\n axisSize, layoutOffset);\n\n return layoutOffset;\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 IndexDescriptorDef getIndexDescriptor(String name)\r\n {\r\n IndexDescriptorDef indexDef = null;\r\n\r\n for (Iterator it = _indexDescriptors.iterator(); it.hasNext(); )\r\n {\r\n indexDef = (IndexDescriptorDef)it.next();\r\n if (indexDef.getName().equals(name))\r\n {\r\n return indexDef;\r\n }\r\n }\r\n return null;\r\n }",
"private void verifyXopResponse(XopBean xopOriginal, XopBean xopResponse) {\n if (!Arrays.equals(xopResponse.getBytes(), xopOriginal.getBytes())) {\n throw new RuntimeException(\"Received XOP attachment is corrupted\");\n }\n System.out.println();\n System.out.println(\"XOP attachment has been successfully received\");\n }",
"public MtasCQLParserSentenceCondition createFullSentence()\n throws ParseException {\n if (fullCondition == null) {\n if (secondSentencePart == null) {\n if (firstBasicSentence != null) {\n fullCondition = new MtasCQLParserSentenceCondition(firstBasicSentence,\n ignoreClause, maximumIgnoreLength);\n\n } else {\n fullCondition = firstSentence;\n }\n fullCondition.setOccurence(firstMinimumOccurence,\n firstMaximumOccurence);\n if (firstOptional) {\n fullCondition.setOptional(firstOptional);\n }\n return fullCondition;\n } else {\n if (!orOperator) {\n if (firstBasicSentence != null) {\n firstBasicSentence.setOccurence(firstMinimumOccurence,\n firstMaximumOccurence);\n firstBasicSentence.setOptional(firstOptional);\n fullCondition = new MtasCQLParserSentenceCondition(\n firstBasicSentence, ignoreClause, maximumIgnoreLength);\n } else {\n firstSentence.setOccurence(firstMinimumOccurence,\n firstMaximumOccurence);\n firstSentence.setOptional(firstOptional);\n fullCondition = new MtasCQLParserSentenceCondition(firstSentence,\n ignoreClause, maximumIgnoreLength);\n }\n fullCondition.addSentenceToEndLatestSequence(\n secondSentencePart.createFullSentence());\n } else {\n MtasCQLParserSentenceCondition sentence = secondSentencePart\n .createFullSentence();\n if (firstBasicSentence != null) {\n sentence.addSentenceAsFirstOption(\n new MtasCQLParserSentenceCondition(firstBasicSentence,\n ignoreClause, maximumIgnoreLength));\n } else {\n sentence.addSentenceAsFirstOption(firstSentence);\n }\n fullCondition = sentence;\n }\n return fullCondition;\n }\n } else {\n return fullCondition;\n }\n }",
"public static String determineAccessorName(@Nonnull final AccessorPrefix prefix, @Nonnull final String fieldName) {\n\t\tCheck.notNull(prefix, \"prefix\");\n\t\tCheck.notEmpty(fieldName, \"fieldName\");\n\t\tfinal Matcher m = PATTERN.matcher(fieldName);\n\t\tCheck.stateIsTrue(m.find(), \"passed field name '%s' is not applicable\", fieldName);\n\t\tfinal String name = m.group();\n\t\treturn prefix.getPrefix() + name.substring(0, 1).toUpperCase() + name.substring(1);\n\t}"
] |
do the parsing on an JSONObject, assumes that the json is hierarchical
ordered, so all shapes are reachable over child relations
@param json hierarchical JSON object
@return Model with all shapes defined in JSON
@throws org.json.JSONException | [
"public static Diagram parseJson(JSONObject json,\n Boolean keepGlossaryLink) throws JSONException {\n ArrayList<Shape> shapes = new ArrayList<Shape>();\n HashMap<String, JSONObject> flatJSON = flatRessources(json);\n for (String resourceId : flatJSON.keySet()) {\n parseRessource(shapes,\n flatJSON,\n resourceId,\n keepGlossaryLink);\n }\n String id = \"canvas\";\n\n if (json.has(\"resourceId\")) {\n id = json.getString(\"resourceId\");\n shapes.remove(new Shape(id));\n }\n ;\n Diagram diagram = new Diagram(id);\n\n // remove Diagram\n // (Diagram)getShapeWithId(json.getString(\"resourceId\"), shapes);\n parseStencilSet(json,\n diagram);\n parseSsextensions(json,\n diagram);\n parseStencil(json,\n diagram);\n parseProperties(json,\n diagram,\n keepGlossaryLink);\n parseChildShapes(shapes,\n json,\n diagram);\n parseBounds(json,\n diagram);\n diagram.setShapes(shapes);\n return diagram;\n }"
] | [
"public static scpolicy_stats get(nitro_service service, String name) throws Exception{\n\t\tscpolicy_stats obj = new scpolicy_stats();\n\t\tobj.set_name(name);\n\t\tscpolicy_stats response = (scpolicy_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"public static long getMaxId(PersistenceBroker brokerForClass, Class topLevel, FieldDescriptor original) throws PersistenceBrokerException\r\n {\r\n long max = 0;\r\n long tmp;\r\n ClassDescriptor cld = brokerForClass.getClassDescriptor(topLevel);\r\n\r\n // if class is not an interface / not abstract we have to search its directly mapped table\r\n if (!cld.isInterface() && !cld.isAbstract())\r\n {\r\n tmp = getMaxIdForClass(brokerForClass, cld, original);\r\n if (tmp > max)\r\n {\r\n max = tmp;\r\n }\r\n }\r\n // if class is an extent we have to search through its subclasses\r\n if (cld.isExtent())\r\n {\r\n Vector extentClasses = cld.getExtentClasses();\r\n for (int i = 0; i < extentClasses.size(); i++)\r\n {\r\n Class extentClass = (Class) extentClasses.get(i);\r\n if (cld.getClassOfObject().equals(extentClass))\r\n {\r\n throw new PersistenceBrokerException(\"Circular extent in \" + extentClass +\r\n \", please check the repository\");\r\n }\r\n else\r\n {\r\n // fix by Mark Rowell\r\n // Call recursive\r\n tmp = getMaxId(brokerForClass, extentClass, original);\r\n }\r\n if (tmp > max)\r\n {\r\n max = tmp;\r\n }\r\n }\r\n }\r\n return max;\r\n }",
"protected void\t\tcalcWorld(Bone bone, int parentId)\n {\n getWorldMatrix(parentId, mTempMtxB); // WorldMatrix (parent) TempMtxB\n mTempMtxB.mul(bone.LocalMatrix); // WorldMatrix = WorldMatrix(parent) * LocalMatrix\n bone.WorldMatrix.set(mTempMtxB);\n }",
"protected void addLoadError(PdfContext context, ImageException e) {\n\t\tBbox imageBounds = e.getRasterImage().getBounds();\n\t\tfloat scaleFactor = (float) (72 / getMap().getRasterResolution());\n\t\tfloat width = (float) imageBounds.getWidth() * scaleFactor;\n\t\tfloat height = (float) imageBounds.getHeight() * scaleFactor;\n\t\t// subtract screen position of lower-left corner\n\t\tfloat x = (float) (imageBounds.getX() - rasterScale * bbox.getMinX()) * scaleFactor;\n\t\t// shift y to lower left corner, flip y to user space and subtract\n\t\t// screen position of lower-left\n\t\t// corner\n\t\tfloat y = (float) (-imageBounds.getY() - imageBounds.getHeight() - rasterScale * bbox.getMinY()) * scaleFactor;\n\t\tif (log.isDebugEnabled()) {\n\t\t\tlog.debug(\"adding failed message=\" + width + \",height=\" + height + \",x=\" + x + \",y=\" + y);\n\t\t}\n\t\tfloat textHeight = context.getTextSize(\"failed\", ERROR_FONT).getHeight() * 3f;\n\t\tRectangle rec = new Rectangle(x, y, x + width, y + height);\n\t\tcontext.strokeRectangle(rec, Color.RED, 0.5f);\n\t\tcontext.drawText(getNlsString(\"RasterLayerComponent.loaderror.line1\"), ERROR_FONT, new Rectangle(x, y\n\t\t\t\t+ textHeight, x + width, y + height), Color.RED);\n\t\tcontext.drawText(getNlsString(\"RasterLayerComponent.loaderror.line2\"), ERROR_FONT, rec, Color.RED);\n\t\tcontext.drawText(getNlsString(\"RasterLayerComponent.loaderror.line3\"), ERROR_FONT, new Rectangle(x, y\n\t\t\t\t- textHeight, x + width, y + height), Color.RED);\n\t}",
"public static int Hamming(String first, String second) {\n\n if (first.length() != second.length())\n throw new IllegalArgumentException(\"The size of string must be the same.\");\n\n int diff = 0;\n for (int i = 0; i < first.length(); i++)\n if (first.charAt(i) != second.charAt(i))\n diff++;\n return diff;\n }",
"private void readTableBlock(int startIndex, int blockLength)\n {\n for (int index = startIndex; index < (startIndex + blockLength - 11); index++)\n {\n if (matchPattern(TABLE_BLOCK_PATTERNS, index))\n {\n int offset = index + 7;\n int nameLength = FastTrackUtility.getInt(m_buffer, offset);\n offset += 4;\n String name = new String(m_buffer, offset, nameLength, CharsetHelper.UTF16LE).toUpperCase();\n FastTrackTableType type = REQUIRED_TABLES.get(name);\n if (type != null)\n {\n m_currentTable = new FastTrackTable(type, this);\n m_tables.put(type, m_currentTable);\n }\n else\n {\n m_currentTable = null;\n }\n m_currentFields.clear();\n break;\n }\n }\n }",
"private void logOriginalRequestHistory(String requestType,\n HttpServletRequest request, History history) {\n logger.info(\"Storing original request history\");\n history.setRequestType(requestType);\n history.setOriginalRequestHeaders(HttpUtilities.getHeaders(request));\n history.setOriginalRequestURL(request.getRequestURL().toString());\n history.setOriginalRequestParams(request.getQueryString() == null ? \"\" : request.getQueryString());\n logger.info(\"Done storing\");\n }",
"private boolean evaluateLogicalOperator(FieldContainer container, Map<GenericCriteriaPrompt, Object> promptValues)\n {\n boolean result = false;\n\n if (m_criteriaList.size() == 0)\n {\n result = true;\n }\n else\n {\n for (GenericCriteria criteria : m_criteriaList)\n {\n result = criteria.evaluate(container, promptValues);\n if ((m_operator == TestOperator.AND && !result) || (m_operator == TestOperator.OR && result))\n {\n break;\n }\n }\n }\n\n return result;\n }",
"public static String groupFromResourceId(String id) {\n return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null;\n }"
] |
Initializes the metadataCache for MetadataStore | [
"private void init() {\n logger.info(\"metadata init().\");\n\n writeLock.lock();\n try {\n // Required keys\n initCache(CLUSTER_KEY);\n\n // If stores definition storage engine is not null, initialize metadata\n // Add the mapping from key to the storage engine used\n if(this.storeDefinitionsStorageEngine != null) {\n initStoreDefinitions(null);\n } else {\n initCache(STORES_KEY);\n }\n\n // Initialize system store in the metadata cache\n initSystemCache();\n initSystemRoutingStrategies(getCluster());\n\n // Initialize with default if not present\n initCache(SLOP_STREAMING_ENABLED_KEY, true);\n initCache(PARTITION_STREAMING_ENABLED_KEY, true);\n initCache(READONLY_FETCH_ENABLED_KEY, true);\n initCache(QUOTA_ENFORCEMENT_ENABLED_KEY, true);\n initCache(REBALANCING_STEAL_INFO, new RebalancerState(new ArrayList<RebalanceTaskInfo>()));\n initCache(SERVER_STATE_KEY, VoldemortState.NORMAL_SERVER.toString());\n initCache(REBALANCING_SOURCE_CLUSTER_XML, null);\n initCache(REBALANCING_SOURCE_STORES_XML, null);\n\n\n } finally {\n writeLock.unlock();\n }\n }"
] | [
"public AT_Row setPaddingRight(int paddingRight) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingRight(paddingRight);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public static Date max(Date d1, Date d2)\n {\n Date result;\n if (d1 == null)\n {\n result = d2;\n }\n else\n if (d2 == null)\n {\n result = d1;\n }\n else\n {\n result = (d1.compareTo(d2) > 0) ? d1 : d2;\n }\n return result;\n }",
"public static int cudnnSoftmaxForward(\n cudnnHandle handle, \n int algo, \n int mode, \n Pointer alpha, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor yDesc, \n Pointer y)\n {\n return checkResult(cudnnSoftmaxForwardNative(handle, algo, mode, alpha, xDesc, x, beta, yDesc, y));\n }",
"public static CharSequence getAt(CharSequence text, Range range) {\n RangeInfo info = subListBorders(text.length(), range);\n CharSequence sequence = text.subSequence(info.from, info.to);\n return info.reverse ? reverse(sequence) : sequence;\n }",
"public CliCommandBuilder setController(final String hostname, final int port) {\n setController(formatAddress(null, hostname, port));\n return this;\n }",
"public FindByIndexOptions useIndex(String designDocument, String indexName) {\r\n assertNotNull(designDocument, \"designDocument\");\r\n assertNotNull(indexName, \"indexName\");\r\n JsonArray index = new JsonArray();\r\n index.add(new JsonPrimitive(designDocument));\r\n index.add(new JsonPrimitive(indexName));\r\n this.useIndex = index;\r\n return this;\r\n }",
"public static sslcipher_individualcipher_binding[] get(nitro_service service, String ciphergroupname) throws Exception{\n\t\tsslcipher_individualcipher_binding obj = new sslcipher_individualcipher_binding();\n\t\tobj.set_ciphergroupname(ciphergroupname);\n\t\tsslcipher_individualcipher_binding response[] = (sslcipher_individualcipher_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private SearchableItem buildSearchableItem(Message menuItem) {\n return new SearchableItem((int) ((NumberField) menuItem.arguments.get(1)).getValue(),\n ((StringField) menuItem.arguments.get(3)).getValue());\n }",
"public String getSearchJsonModel() throws IOException {\n DbSearch search = new DbSearch();\n search.setArtifacts(new ArrayList<>());\n search.setModules(new ArrayList<>());\n return JsonUtils.serialize(search);\n }"
] |
Returns the error correction codewords for the specified data codewords.
@param codewords the codewords that we need error correction codewords for
@param ecclen the number of error correction codewords needed
@return the error correction codewords for the specified data codewords | [
"private static int[] getErrorCorrection(int[] codewords, int ecclen) {\r\n\r\n ReedSolomon rs = new ReedSolomon();\r\n rs.init_gf(0x43);\r\n rs.init_code(ecclen, 1);\r\n rs.encode(codewords.length, codewords);\r\n\r\n int[] results = new int[ecclen];\r\n for (int i = 0; i < ecclen; i++) {\r\n results[i] = rs.getResult(results.length - 1 - i);\r\n }\r\n\r\n return results;\r\n }"
] | [
"protected String calculateNextVersion(String fromVersion) {\n // first turn it to release version\n fromVersion = calculateReleaseVersion(fromVersion);\n String nextVersion;\n int lastDotIndex = fromVersion.lastIndexOf('.');\n try {\n if (lastDotIndex != -1) {\n // probably a major minor version e.g., 2.1.1\n String minorVersionToken = fromVersion.substring(lastDotIndex + 1);\n String nextMinorVersion;\n int lastDashIndex = minorVersionToken.lastIndexOf('-');\n if (lastDashIndex != -1) {\n // probably a minor-buildNum e.g., 2.1.1-4 (should change to 2.1.1-5)\n String buildNumber = minorVersionToken.substring(lastDashIndex + 1);\n int nextBuildNumber = Integer.parseInt(buildNumber) + 1;\n nextMinorVersion = minorVersionToken.substring(0, lastDashIndex + 1) + nextBuildNumber;\n } else {\n nextMinorVersion = Integer.parseInt(minorVersionToken) + 1 + \"\";\n }\n nextVersion = fromVersion.substring(0, lastDotIndex + 1) + nextMinorVersion;\n } else {\n // maybe it's just a major version; try to parse as an int\n int nextMajorVersion = Integer.parseInt(fromVersion) + 1;\n nextVersion = nextMajorVersion + \"\";\n }\n } catch (NumberFormatException e) {\n return fromVersion;\n }\n return nextVersion + \"-SNAPSHOT\";\n }",
"public String toUriString(final java.net.URI uri) {\n return this.toUriString(URI.createURI(uri.normalize().toString()));\n }",
"public static Interface[] get(nitro_service service) throws Exception{\n\t\tInterface obj = new Interface();\n\t\tInterface[] response = (Interface[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public Map<TimestampMode, List<String>> getDefaultTimestampModes() {\n\n Map<TimestampMode, List<String>> result = new HashMap<TimestampMode, List<String>>();\n for (String resourcetype : m_defaultTimestampModes.keySet()) {\n TimestampMode mode = m_defaultTimestampModes.get(resourcetype);\n if (result.containsKey(mode)) {\n result.get(mode).add(resourcetype);\n } else {\n List<String> list = new ArrayList<String>();\n list.add(resourcetype);\n result.put(mode, list);\n }\n }\n return result;\n }",
"public RedwoodConfiguration stderr(){\r\n LogRecordHandler visibility = new VisibilityHandler();\r\n LogRecordHandler console = Redwood.ConsoleHandler.err();\r\n return this\r\n .rootHandler(visibility)\r\n .handler(visibility, console);\r\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 }",
"protected void merge(Set<Annotation> stereotypeAnnotations) {\n final MetaAnnotationStore store = manager.getServices().get(MetaAnnotationStore.class);\n for (Annotation stereotypeAnnotation : stereotypeAnnotations) {\n // Retrieve and merge all metadata from stereotypes\n StereotypeModel<?> stereotype = store.getStereotype(stereotypeAnnotation.annotationType());\n if (stereotype == null) {\n throw MetadataLogger.LOG.stereotypeNotRegistered(stereotypeAnnotation);\n }\n if (stereotype.isAlternative()) {\n alternative = true;\n }\n if (stereotype.getDefaultScopeType() != null) {\n possibleScopeTypes.add(stereotype.getDefaultScopeType());\n }\n if (stereotype.isBeanNameDefaulted()) {\n beanNameDefaulted = true;\n }\n this.stereotypes.add(stereotypeAnnotation.annotationType());\n // Merge in inherited stereotypes\n merge(stereotype.getInheritedStereotypes());\n }\n }",
"private ServerBootstrap createBootstrap(final ChannelGroup channelGroup) throws Exception {\n EventLoopGroup bossGroup = new NioEventLoopGroup(bossThreadPoolSize,\n createDaemonThreadFactory(serviceName + \"-boss-thread-%d\"));\n EventLoopGroup workerGroup = new NioEventLoopGroup(workerThreadPoolSize,\n createDaemonThreadFactory(serviceName + \"-worker-thread-%d\"));\n ServerBootstrap bootstrap = new ServerBootstrap();\n bootstrap\n .group(bossGroup, workerGroup)\n .channel(NioServerSocketChannel.class)\n .childHandler(new ChannelInitializer<SocketChannel>() {\n @Override\n protected void initChannel(SocketChannel ch) throws Exception {\n channelGroup.add(ch);\n\n ChannelPipeline pipeline = ch.pipeline();\n if (sslHandlerFactory != null) {\n // Add SSLHandler if SSL is enabled\n pipeline.addLast(\"ssl\", sslHandlerFactory.create(ch.alloc()));\n }\n pipeline.addLast(\"codec\", new HttpServerCodec());\n pipeline.addLast(\"compressor\", new HttpContentCompressor());\n pipeline.addLast(\"chunkedWriter\", new ChunkedWriteHandler());\n pipeline.addLast(\"keepAlive\", new HttpServerKeepAliveHandler());\n pipeline.addLast(\"router\", new RequestRouter(resourceHandler, httpChunkLimit, sslHandlerFactory != null));\n if (eventExecutorGroup == null) {\n pipeline.addLast(\"dispatcher\", new HttpDispatcher());\n } else {\n pipeline.addLast(eventExecutorGroup, \"dispatcher\", new HttpDispatcher());\n }\n\n if (pipelineModifier != null) {\n pipelineModifier.modify(pipeline);\n }\n }\n });\n\n for (Map.Entry<ChannelOption, Object> entry : channelConfigs.entrySet()) {\n bootstrap.option(entry.getKey(), entry.getValue());\n }\n for (Map.Entry<ChannelOption, Object> entry : childChannelConfigs.entrySet()) {\n bootstrap.childOption(entry.getKey(), entry.getValue());\n }\n\n return bootstrap;\n }",
"@Override public Task addTask()\n {\n ProjectFile parent = getParentFile();\n\n Task task = new Task(parent, this);\n\n m_children.add(task);\n\n parent.getTasks().add(task);\n\n setSummary(true);\n\n return (task);\n }"
] |
Returns an integer array that contains the default values for all the
texture parameters.
@return an integer array that contains the default values for all the
texture parameters. | [
"public int[] getDefalutValuesArray() {\n int[] defaultValues = new int[5];\n\n defaultValues[0] = GLES20.GL_LINEAR_MIPMAP_NEAREST; // MIN FILTER\n defaultValues[1] = GLES20.GL_LINEAR; // MAG FILTER\n defaultValues[2] = 1; // ANISO FILTER\n defaultValues[3] = GLES20.GL_CLAMP_TO_EDGE; // WRAP S\n defaultValues[4] = GLES20.GL_CLAMP_TO_EDGE; // WRAP T\n\n return defaultValues;\n }"
] | [
"public static ResourceKey key(Class<?> clazz, Enum<?> value) {\n return new ResourceKey(clazz.getName(), value.name());\n }",
"public static ProctorLoadResult verify(\n @Nonnull final TestMatrixArtifact testMatrix,\n final String matrixSource,\n @Nonnull final Map<String, TestSpecification> requiredTests,\n @Nonnull final FunctionMapper functionMapper,\n final ProvidedContext providedContext,\n @Nonnull final Set<String> dynamicTests\n ) {\n final ProctorLoadResult.Builder resultBuilder = ProctorLoadResult.newBuilder();\n\n final Map<String, Map<Integer, String>> allTestsKnownBuckets = Maps.newHashMapWithExpectedSize(requiredTests.size());\n for (final Entry<String, TestSpecification> entry : requiredTests.entrySet()) {\n final Map<Integer, String> bucketValueToName = Maps.newHashMap();\n for (final Entry<String, Integer> bucket : entry.getValue().getBuckets().entrySet()) {\n bucketValueToName.put(bucket.getValue(), bucket.getKey());\n }\n allTestsKnownBuckets.put(entry.getKey(), bucketValueToName);\n }\n\n final Map<String, ConsumableTestDefinition> definedTests = testMatrix.getTests();\n final SetView<String> missingTests = Sets.difference(requiredTests.keySet(), definedTests.keySet());\n resultBuilder.recordAllMissing(missingTests);\n for (final Entry<String, ConsumableTestDefinition> entry : definedTests.entrySet()) {\n final String testName = entry.getKey();\n\n final Map<Integer, String> knownBuckets;\n final TestSpecification specification;\n final boolean isRequired;\n if (allTestsKnownBuckets.containsKey(testName)) {\n // required in specification\n isRequired = true;\n knownBuckets = allTestsKnownBuckets.remove(testName);\n specification = requiredTests.get(testName);\n } else if (dynamicTests.contains(testName)) {\n // resolved by dynamic filter\n isRequired = false;\n knownBuckets = Collections.emptyMap();\n specification = new TestSpecification();\n } else {\n // we don't care about this test\n continue;\n }\n\n final ConsumableTestDefinition testDefinition = entry.getValue();\n\n try {\n verifyTest(testName, testDefinition, specification, knownBuckets, matrixSource, functionMapper, providedContext);\n\n } catch (IncompatibleTestMatrixException e) {\n if (isRequired) {\n LOGGER.error(String.format(\"Unable to load test matrix for a required test %s\", testName), e);\n resultBuilder.recordError(testName, e);\n } else {\n LOGGER.info(String.format(\"Unable to load test matrix for a dynamic test %s\", testName), e);\n resultBuilder.recordIncompatibleDynamicTest(testName, e);\n }\n }\n }\n\n // TODO mjs - is this check additive?\n resultBuilder.recordAllMissing(allTestsKnownBuckets.keySet());\n\n resultBuilder.recordVerifiedRules(providedContext.shouldEvaluate());\n\n final ProctorLoadResult loadResult = resultBuilder.build();\n\n return loadResult;\n }",
"@Override\n public boolean minimize(DifferentiableBatchFunction function, IntDoubleVector point) {\n return minimize(function, point, null);\n }",
"public boolean matches(String resourcePath) {\n if (!valid) {\n return false;\n }\n if (resourcePath == null) {\n return acceptsContextPathEmpty;\n }\n if (contextPathRegex != null && !contextPathRegex.matcher(resourcePath).matches()) {\n return false;\n }\n if (contextPathBlacklistRegex != null && contextPathBlacklistRegex.matcher(resourcePath).matches()) {\n return false;\n }\n return true;\n }",
"public static authenticationvserver_authenticationtacacspolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_authenticationtacacspolicy_binding obj = new authenticationvserver_authenticationtacacspolicy_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_authenticationtacacspolicy_binding response[] = (authenticationvserver_authenticationtacacspolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void addAll(int index, T... items) {\n List<T> collection = Arrays.asList(items);\n synchronized (mLock) {\n if (mOriginalValues != null) {\n mOriginalValues.addAll(index, collection);\n } else {\n mObjects.addAll(index, collection);\n }\n }\n if (mNotifyOnChange) notifyDataSetChanged();\n }",
"private void destroySession() {\n currentSessionId = 0;\n setAppLaunchPushed(false);\n getConfigLogger().verbose(getAccountId(),\"Session destroyed; Session ID is now 0\");\n clearSource();\n clearMedium();\n clearCampaign();\n clearWzrkParams();\n }",
"@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients/delete\", method = RequestMethod.POST)\n public\n @ResponseBody\n HashMap<String, Object> deleteClient(Model model,\n @RequestParam(\"profileIdentifier\") String profileIdentifier,\n @RequestParam(\"clientUUID\") String[] clientUUID) throws Exception {\n\n logger.info(\"Attempting to remove clients from the profile: \", profileIdentifier);\n logger.info(\"Attempting to remove the following clients: {}\", Arrays.toString(clientUUID));\n\n HashMap<String, Object> valueHash = new HashMap<String, Object>();\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n\n for( int i = 0; i < clientUUID.length; i++ )\n {\n if (clientUUID[i].compareTo(Constants.PROFILE_CLIENT_DEFAULT_ID) == 0)\n throw new Exception(\"Default client cannot be deleted\");\n\n clientService.remove(profileId, clientUUID[i]);\n }\n\n valueHash.put(\"clients\", clientService.findAllClients(profileId));\n return valueHash;\n }",
"public static base_response enable(nitro_service client, nsfeature resource) throws Exception {\n\t\tnsfeature enableresource = new nsfeature();\n\t\tenableresource.feature = resource.feature;\n\t\treturn enableresource.perform_operation(client,\"enable\");\n\t}"
] |
See if a range for assignment is specified. If so return the range, otherwise return null
Example of assign range:
a(0:3,4:5) = blah
a((0+2):3,4:5) = blah | [
"private List<Variable> parseAssignRange(Sequence sequence, TokenList tokens, TokenList.Token t0) {\n // find assignment symbol\n TokenList.Token tokenAssign = t0.next;\n while( tokenAssign != null && tokenAssign.symbol != Symbol.ASSIGN ) {\n tokenAssign = tokenAssign.next;\n }\n\n if( tokenAssign == null )\n throw new ParseError(\"Can't find assignment operator\");\n\n // see if it is a sub matrix before\n if( tokenAssign.previous.symbol == Symbol.PAREN_RIGHT ) {\n TokenList.Token start = t0.next;\n if( start.symbol != Symbol.PAREN_LEFT )\n throw new ParseError((\"Expected left param for assignment\"));\n TokenList.Token end = tokenAssign.previous;\n TokenList subTokens = tokens.extractSubList(start,end);\n subTokens.remove(subTokens.getFirst());\n subTokens.remove(subTokens.getLast());\n\n handleParentheses(subTokens,sequence);\n\n List<TokenList.Token> inputs = parseParameterCommaBlock(subTokens, sequence);\n\n if (inputs.isEmpty())\n throw new ParseError(\"Empty function input parameters\");\n\n List<Variable> range = new ArrayList<>();\n addSubMatrixVariables(inputs, range);\n if( range.size() != 1 && range.size() != 2 ) {\n throw new ParseError(\"Unexpected number of range variables. 1 or 2 expected\");\n }\n return range;\n }\n\n return null;\n }"
] | [
"CueList getCueList(int rekordboxId, CdjStatus.TrackSourceSlot slot, Client client)\n throws IOException {\n Message response = client.simpleRequest(Message.KnownType.CUE_LIST_REQ, null,\n client.buildRMST(Message.MenuIdentifier.DATA, slot), new NumberField(rekordboxId));\n if (response.knownType == Message.KnownType.CUE_LIST) {\n return new CueList(response);\n }\n logger.error(\"Unexpected response type when requesting cue list: {}\", response);\n return null;\n }",
"public void setCurrencySymbol(String symbol)\n {\n if (symbol == null)\n {\n symbol = DEFAULT_CURRENCY_SYMBOL;\n }\n\n set(ProjectField.CURRENCY_SYMBOL, symbol);\n }",
"public static final String printTaskUID(Integer value)\n {\n ProjectFile file = PARENT_FILE.get();\n if (file != null)\n {\n file.getEventManager().fireTaskWrittenEvent(file.getTaskByUniqueID(value));\n }\n return (value.toString());\n }",
"private static CallSite realBootstrap(Lookup caller, String name, int callID, MethodType type, boolean safe, boolean thisCall, boolean spreadCall) {\n // since indy does not give us the runtime types\n // we produce first a dummy call site, which then changes the target to one,\n // that does the method selection including the the direct call to the \n // real method.\n MutableCallSite mc = new MutableCallSite(type);\n MethodHandle mh = makeFallBack(mc,caller.lookupClass(),name,callID,type,safe,thisCall,spreadCall);\n mc.setTarget(mh);\n return mc;\n }",
"public Response remove(String id, String rev) {\r\n assertNotEmpty(id, \"id\");\r\n assertNotEmpty(id, \"rev\");\r\n return db.remove(ensureDesignPrefix(id), rev);\r\n\r\n }",
"public GetAssignmentGroupOptions includes(List<Include> includes) {\n List<Include> assignmentDependents = Arrays.asList(Include.DISCUSSION_TOPIC, Include.ASSIGNMENT_VISIBILITY, Include.SUBMISSION);\n if(includes.stream().anyMatch(assignmentDependents::contains) && !includes.contains(Include.ASSIGNMENTS)) {\n throw new IllegalArgumentException(\"Including discussion topics, all dates, assignment visibility or submissions is only valid if you also include submissions\");\n }\n addEnumList(\"include[]\", includes);\n return this;\n }",
"public final PJsonArray toJSON() {\n JSONArray jsonArray = new JSONArray();\n final int size = this.array.size();\n for (int i = 0; i < size; i++) {\n final Object o = get(i);\n if (o instanceof PYamlObject) {\n PYamlObject pYamlObject = (PYamlObject) o;\n jsonArray.put(pYamlObject.toJSON().getInternalObj());\n } else if (o instanceof PYamlArray) {\n PYamlArray pYamlArray = (PYamlArray) o;\n jsonArray.put(pYamlArray.toJSON().getInternalArray());\n } else {\n jsonArray.put(o);\n }\n\n }\n return new PJsonArray(null, jsonArray, getContextName());\n }",
"private static void updateJar(final File file, final byte[] searchPattern, final int[] badSkipBytes, final int newSig, final int endSig) throws IOException {\n final RandomAccessFile raf = new RandomAccessFile(file, \"rw\");\n try {\n final FileChannel channel = raf.getChannel();\n try {\n long pos = channel.size() - ENDLEN;\n final ScanContext context;\n if (newSig == CRIPPLED_ENDSIG) {\n context = new ScanContext(GOOD_ENDSIG_PATTERN, CRIPPLED_ENDSIG_PATTERN);\n } else if (newSig == GOOD_ENDSIG) {\n context = new ScanContext(CRIPPLED_ENDSIG_PATTERN, GOOD_ENDSIG_PATTERN);\n } else {\n context = null;\n }\n\n if (!validateEndRecord(file, channel, pos, endSig)) {\n pos = scanForEndSig(file, channel, context);\n }\n if (pos == -1) {\n if (context.state == State.NOT_FOUND) {\n // Don't fail patching if we cannot validate a valid zip\n PatchLogger.ROOT_LOGGER.cannotInvalidateZip(file.getAbsolutePath());\n }\n return;\n }\n // Update the central directory record\n channel.position(pos);\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(ByteOrder.LITTLE_ENDIAN);\n buffer.putInt(newSig);\n buffer.flip();\n while (buffer.hasRemaining()) {\n channel.write(buffer);\n }\n } finally {\n safeClose(channel);\n }\n } finally {\n safeClose(raf);\n }\n }",
"public static FormValidation validateArtifactoryCombinationFilter(String value)\n throws IOException, InterruptedException {\n String url = Util.fixEmptyAndTrim(value);\n if (url == null)\n return FormValidation.error(\"Mandatory field - You don`t have any deploy matches\");\n\n return FormValidation.ok();\n }"
] |
The local event will decide the next state of the document in question.
@param <T> the type of class represented by the document in the change event.
@return the local full document which may be null. | [
"public static <T> ConflictHandler<T> localWins() {\n return new ConflictHandler<T>() {\n @Override\n public T resolveConflict(\n final BsonValue documentId,\n final ChangeEvent<T> localEvent,\n final ChangeEvent<T> remoteEvent\n ) {\n return localEvent.getFullDocument();\n }\n };\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 }",
"protected String addPostRunDependent(TaskGroup.HasTaskGroup dependent) {\n Objects.requireNonNull(dependent);\n this.taskGroup.addPostRunDependentTaskGroup(dependent.taskGroup());\n return dependent.taskGroup().key();\n }",
"private void addAllWithFilter(Map<String, String> toMap, Map<String, String> fromMap, IncludeExcludePatterns pattern) {\n for (Object o : fromMap.entrySet()) {\n Map.Entry entry = (Map.Entry) o;\n String key = (String) entry.getKey();\n if (PatternMatcher.pathConflicts(key, pattern)) {\n continue;\n }\n toMap.put(key, (String) entry.getValue());\n }\n }",
"private void countCooccurringProperties(\n\t\t\tStatementDocument statementDocument, UsageRecord usageRecord,\n\t\t\tPropertyIdValue thisPropertyIdValue) {\n\t\tfor (StatementGroup sg : statementDocument.getStatementGroups()) {\n\t\t\tif (!sg.getProperty().equals(thisPropertyIdValue)) {\n\t\t\t\tInteger propertyId = getNumId(sg.getProperty().getId(), false);\n\t\t\t\tif (!usageRecord.propertyCoCounts.containsKey(propertyId)) {\n\t\t\t\t\tusageRecord.propertyCoCounts.put(propertyId, 1);\n\t\t\t\t} else {\n\t\t\t\t\tusageRecord.propertyCoCounts.put(propertyId,\n\t\t\t\t\t\t\tusageRecord.propertyCoCounts.get(propertyId) + 1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"public static AppDescriptor deserializeFrom(byte[] bytes) {\n try {\n ByteArrayInputStream bais = new ByteArrayInputStream(bytes);\n ObjectInputStream ois = new ObjectInputStream(bais);\n return (AppDescriptor) ois.readObject();\n } catch (IOException e) {\n throw E.ioException(e);\n } catch (ClassNotFoundException e) {\n throw E.unexpected(e);\n }\n }",
"public static synchronized void clearDaoCache() {\n\t\tif (classMap != null) {\n\t\t\tclassMap.clear();\n\t\t\tclassMap = null;\n\t\t}\n\t\tif (tableConfigMap != null) {\n\t\t\ttableConfigMap.clear();\n\t\t\ttableConfigMap = null;\n\t\t}\n\t}",
"private boolean contentEqualsUnchecked(byte[] bytes, int offset, int len) {\n if (length != len) {\n return false;\n }\n\n return compareToUnchecked(bytes, offset, len) == 0;\n }",
"public Where<T, ID> and() {\n\t\tManyClause clause = new ManyClause(pop(\"AND\"), ManyClause.AND_OPERATION);\n\t\tpush(clause);\n\t\taddNeedsFuture(clause);\n\t\treturn this;\n\t}",
"@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 }"
] |
Use this API to fetch a vpnglobal_vpntrafficpolicy_binding resources. | [
"public static vpnglobal_vpntrafficpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tvpnglobal_vpntrafficpolicy_binding obj = new vpnglobal_vpntrafficpolicy_binding();\n\t\tvpnglobal_vpntrafficpolicy_binding response[] = (vpnglobal_vpntrafficpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"public String getString(Integer id, Integer type)\n {\n return (getString(m_meta.getOffset(id, type)));\n }",
"public static <InnerT> Observable<InnerT> convertListToInnerAsync(Observable<List<InnerT>> innerList) {\n return innerList.flatMap(new Func1<List<InnerT>, Observable<InnerT>>() {\n @Override\n public Observable<InnerT> call(List<InnerT> inners) {\n return Observable.from(inners);\n }\n });\n }",
"public double[] getBasisVector( int which ) {\n if( which < 0 || which >= numComponents )\n throw new IllegalArgumentException(\"Invalid component\");\n\n DMatrixRMaj v = new DMatrixRMaj(1,A.numCols);\n CommonOps_DDRM.extract(V_t,which,which+1,0,A.numCols,v,0,0);\n\n return v.data;\n }",
"public void putBeanDeployments(BeanDeploymentArchiveMapping bdaMapping) {\n for (Entry<BeanDeploymentArchive, BeanManagerImpl> entry : bdaMapping.getBdaToBeanManagerMap().entrySet()) {\n beanDeploymentArchives.put(entry.getKey(), entry.getValue());\n addBeanManager(entry.getValue());\n }\n }",
"public void bind(Object object, String name)\r\n throws ObjectNameNotUniqueException\r\n {\r\n /**\r\n * Is DB open? ODMG 3.0 says it has to be to call bind.\r\n */\r\n if (!this.isOpen())\r\n {\r\n throw new DatabaseClosedException(\"Database is not open. Must have an open DB to call bind.\");\r\n }\r\n /**\r\n * Is Tx open? ODMG 3.0 says it has to be to call bind.\r\n */\r\n TransactionImpl tx = getTransaction();\r\n if (tx == null || !tx.isOpen())\r\n {\r\n throw new TransactionNotInProgressException(\"Tx is not open. Must have an open TX to call bind.\");\r\n }\r\n\r\n tx.getNamedRootsMap().bind(object, name);\r\n }",
"private void stopDone() {\n synchronized (stopLock) {\n final StopContext stopContext = this.stopContext;\n this.stopContext = null;\n if (stopContext != null) {\n stopContext.complete();\n }\n stopLock.notifyAll();\n }\n }",
"@SuppressWarnings(\"unchecked\")\n private void addPrivateFieldsAccessors(ClassNode node) {\n Set<ASTNode> accessedFields = (Set<ASTNode>) node.getNodeMetaData(StaticTypesMarker.PV_FIELDS_ACCESS);\n if (accessedFields==null) return;\n Map<String, MethodNode> privateConstantAccessors = (Map<String, MethodNode>) node.getNodeMetaData(PRIVATE_FIELDS_ACCESSORS);\n if (privateConstantAccessors!=null) {\n // already added\n return;\n }\n int acc = -1;\n privateConstantAccessors = new HashMap<String, MethodNode>();\n final int access = Opcodes.ACC_STATIC | Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC;\n for (FieldNode fieldNode : node.getFields()) {\n if (accessedFields.contains(fieldNode)) {\n\n acc++;\n Parameter param = new Parameter(node.getPlainNodeReference(), \"$that\");\n Expression receiver = fieldNode.isStatic()?new ClassExpression(node):new VariableExpression(param);\n Statement stmt = new ExpressionStatement(new PropertyExpression(\n receiver,\n fieldNode.getName()\n ));\n MethodNode accessor = node.addMethod(\"pfaccess$\"+acc, access, fieldNode.getOriginType(), new Parameter[]{param}, ClassNode.EMPTY_ARRAY, stmt);\n privateConstantAccessors.put(fieldNode.getName(), accessor);\n }\n }\n node.setNodeMetaData(PRIVATE_FIELDS_ACCESSORS, privateConstantAccessors);\n }",
"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 }",
"protected List<CmsUUID> undelete() throws CmsException {\n\n List<CmsUUID> modifiedResources = new ArrayList<CmsUUID>();\n CmsObject cms = m_context.getCms();\n for (CmsResource resource : m_context.getResources()) {\n CmsLockActionRecord actionRecord = null;\n try {\n actionRecord = CmsLockUtil.ensureLock(m_context.getCms(), resource);\n cms.undeleteResource(cms.getSitePath(resource), true);\n modifiedResources.add(resource.getStructureId());\n } finally {\n if ((actionRecord != null) && (actionRecord.getChange() == LockChange.locked)) {\n\n try {\n cms.unlockResource(resource);\n } catch (CmsLockException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n }\n }\n }\n }\n return modifiedResources;\n }"
] |
Checks if the date is a holiday
@param dateString the date
@return true if it is a holiday, false otherwise | [
"public boolean isHoliday(String dateString) {\n boolean isHoliday = false;\n for (Holiday date : EquivalenceClassTransformer.HOLIDAYS) {\n if (convertToReadableDate(date.forYear(Integer.parseInt(dateString.substring(0, 4)))).equals(dateString)) {\n isHoliday = true;\n }\n }\n return isHoliday;\n }"
] | [
"public boolean matches(PathElement pe) {\n return pe.key.equals(key) && (isWildcard() || pe.value.equals(value));\n }",
"public CmsSolrQuery getQuery(CmsObject cms) {\n\n final CmsSolrQuery query = new CmsSolrQuery();\n\n // set categories\n query.setCategories(m_categories);\n\n // set container types\n if (null != m_containerTypes) {\n query.addFilterQuery(CmsSearchField.FIELD_CONTAINER_TYPES, m_containerTypes, false, false);\n }\n\n // Set date created time filter\n query.addFilterQuery(\n CmsSearchUtil.getDateCreatedTimeRangeFilterQuery(\n CmsSearchField.FIELD_DATE_CREATED,\n getDateCreatedRange().m_startTime,\n getDateCreatedRange().m_endTime));\n\n // Set date last modified time filter\n query.addFilterQuery(\n CmsSearchUtil.getDateCreatedTimeRangeFilterQuery(\n CmsSearchField.FIELD_DATE_LASTMODIFIED,\n getDateLastModifiedRange().m_startTime,\n getDateLastModifiedRange().m_endTime));\n\n // set scope / folders to search in\n m_foldersToSearchIn = new ArrayList<String>();\n addFoldersToSearchIn(m_folders);\n addFoldersToSearchIn(m_galleries);\n setSearchFolders(cms);\n query.addFilterQuery(\n CmsSearchField.FIELD_PARENT_FOLDERS,\n new ArrayList<String>(m_foldersToSearchIn),\n false,\n true);\n\n if (!m_ignoreSearchExclude) {\n // Reference for the values: CmsGallerySearchIndex.java, field EXCLUDE_PROPERTY_VALUES\n query.addFilterQuery(\n \"-\" + CmsSearchField.FIELD_SEARCH_EXCLUDE,\n Arrays.asList(\n new String[] {\n A_CmsSearchIndex.PROPERTY_SEARCH_EXCLUDE_VALUE_ALL,\n A_CmsSearchIndex.PROPERTY_SEARCH_EXCLUDE_VALUE_GALLERY}),\n false,\n true);\n }\n\n // set matches per page\n query.setRows(new Integer(m_matchesPerPage));\n\n // set resource types\n if (null != m_resourceTypes) {\n List<String> resourceTypes = new ArrayList<>(m_resourceTypes);\n if (m_resourceTypes.contains(CmsResourceTypeFunctionConfig.TYPE_NAME)\n && !m_resourceTypes.contains(CmsXmlDynamicFunctionHandler.TYPE_FUNCTION)) {\n resourceTypes.add(CmsXmlDynamicFunctionHandler.TYPE_FUNCTION);\n }\n query.setResourceTypes(resourceTypes);\n }\n\n // set result page\n query.setStart(new Integer((m_resultPage - 1) * m_matchesPerPage));\n\n // set search locale\n if (null != m_locale) {\n query.setLocales(CmsLocaleManager.getLocale(m_locale));\n }\n\n // set search words\n if (null != m_words) {\n query.setQuery(m_words);\n }\n\n // set sort order\n query.setSort(getSort().getFirst(), getSort().getSecond());\n\n // set result collapsing by id\n query.addFilterQuery(\"{!collapse field=id}\");\n\n query.setFields(CmsGallerySearchResult.getRequiredSolrFields());\n\n if ((m_allowedFunctions != null) && !m_allowedFunctions.isEmpty()) {\n String functionFilter = \"((-type:(\"\n + CmsXmlDynamicFunctionHandler.TYPE_FUNCTION\n + \" OR \"\n + CmsResourceTypeFunctionConfig.TYPE_NAME\n + \")) OR (id:(\";\n Iterator<CmsUUID> it = m_allowedFunctions.iterator();\n while (it.hasNext()) {\n CmsUUID id = it.next();\n functionFilter += id.toString();\n if (it.hasNext()) {\n functionFilter += \" OR \";\n }\n }\n functionFilter += \")))\";\n query.addFilterQuery(functionFilter);\n }\n\n return query;\n }",
"protected AllowableActions collectAllowableActions(CmsObject cms, CmsResource file) {\r\n\r\n try {\r\n\r\n if (file == null) {\r\n throw new IllegalArgumentException(\"File must not be null!\");\r\n }\r\n CmsLock lock = cms.getLock(file);\r\n CmsUser user = cms.getRequestContext().getCurrentUser();\r\n boolean canWrite = !cms.getRequestContext().getCurrentProject().isOnlineProject()\r\n && (lock.isOwnedBy(user) || lock.isLockableBy(user))\r\n && cms.hasPermissions(file, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.DEFAULT);\r\n boolean isReadOnly = !canWrite;\r\n boolean isFolder = file.isFolder();\r\n boolean isRoot = file.getRootPath().length() <= 1;\r\n\r\n Set<Action> aas = new LinkedHashSet<Action>();\r\n addAction(aas, Action.CAN_GET_OBJECT_PARENTS, !isRoot);\r\n addAction(aas, Action.CAN_GET_PROPERTIES, true);\r\n addAction(aas, Action.CAN_UPDATE_PROPERTIES, !isReadOnly);\r\n addAction(aas, Action.CAN_MOVE_OBJECT, !isReadOnly && !isRoot);\r\n addAction(aas, Action.CAN_DELETE_OBJECT, !isReadOnly && !isRoot);\r\n if (isFolder) {\r\n addAction(aas, Action.CAN_GET_DESCENDANTS, true);\r\n addAction(aas, Action.CAN_GET_CHILDREN, true);\r\n addAction(aas, Action.CAN_GET_FOLDER_PARENT, !isRoot);\r\n addAction(aas, Action.CAN_GET_FOLDER_TREE, true);\r\n addAction(aas, Action.CAN_CREATE_DOCUMENT, !isReadOnly);\r\n addAction(aas, Action.CAN_CREATE_FOLDER, !isReadOnly);\r\n addAction(aas, Action.CAN_DELETE_TREE, !isReadOnly);\r\n } else {\r\n addAction(aas, Action.CAN_GET_CONTENT_STREAM, true);\r\n addAction(aas, Action.CAN_SET_CONTENT_STREAM, !isReadOnly);\r\n addAction(aas, Action.CAN_GET_ALL_VERSIONS, true);\r\n }\r\n AllowableActionsImpl result = new AllowableActionsImpl();\r\n result.setAllowableActions(aas);\r\n return result;\r\n } catch (CmsException e) {\r\n handleCmsException(e);\r\n return null;\r\n }\r\n }",
"public static String readStringFromUrlGeneric(String url)\n throws IOException {\n InputStream is = null;\n URL urlObj = null;\n String responseString = PcConstants.NA;\n try {\n urlObj = new URL(url);\n URLConnection con = urlObj.openConnection();\n\n con.setConnectTimeout(ParallecGlobalConfig.urlConnectionConnectTimeoutMillis);\n con.setReadTimeout(ParallecGlobalConfig.urlConnectionReadTimeoutMillis);\n is = con.getInputStream();\n\n BufferedReader rd = new BufferedReader(new InputStreamReader(is,\n Charset.forName(\"UTF-8\")));\n responseString = PcFileNetworkIoUtils.readAll(rd);\n\n } finally {\n\n if (is != null) {\n is.close();\n }\n\n }\n\n return responseString;\n }",
"protected boolean isDuplicate(String eventID) {\n if (this.receivedEvents == null) {\n this.receivedEvents = new LRUCache<String>();\n }\n\n return !this.receivedEvents.add(eventID);\n }",
"private void processWorkWeeks(byte[] data, int offset, ProjectCalendar cal)\n {\n // System.out.println(\"Calendar=\" + cal.getName());\n // System.out.println(\"Work week block start offset=\" + offset);\n // System.out.println(ByteArrayHelper.hexdump(data, true, 16, \"\"));\n\n // skip 4 byte header\n offset += 4;\n\n while (data.length >= offset + ((7 * 60) + 2 + 2 + 8 + 4))\n {\n //System.out.println(\"Week start offset=\" + offset);\n ProjectCalendarWeek week = cal.addWorkWeek();\n for (Day day : Day.values())\n {\n // 60 byte block per day\n processWorkWeekDay(data, offset, week, day);\n offset += 60;\n }\n\n Date startDate = DateHelper.getDayStartDate(MPPUtility.getDate(data, offset));\n offset += 2;\n\n Date finishDate = DateHelper.getDayEndDate(MPPUtility.getDate(data, offset));\n offset += 2;\n\n // skip unknown 8 bytes\n //System.out.println(ByteArrayHelper.hexdump(data, offset, 8, false));\n offset += 8;\n\n //\n // Extract the name length - ensure that it is aligned to a 4 byte boundary\n //\n int nameLength = MPPUtility.getInt(data, offset);\n if (nameLength % 4 != 0)\n {\n nameLength = ((nameLength / 4) + 1) * 4;\n }\n offset += 4;\n\n if (nameLength != 0)\n {\n String name = MPPUtility.getUnicodeString(data, offset, nameLength);\n offset += nameLength;\n week.setName(name);\n }\n\n week.setDateRange(new DateRange(startDate, finishDate));\n // System.out.println(week);\n }\n }",
"private void maybeUpdateScrollbarPositions() {\r\n\r\n if (!isAttached()) {\r\n return;\r\n }\r\n\r\n if (m_scrollbar != null) {\r\n int vPos = getVerticalScrollPosition();\r\n if (m_scrollbar.getVerticalScrollPosition() != vPos) {\r\n m_scrollbar.setVerticalScrollPosition(vPos);\r\n }\r\n }\r\n }",
"public static boolean isFileExist(String filePath) {\n\n File f = new File(filePath);\n\n return f.exists() && !f.isDirectory();\n }",
"public DiscreteInterval minus(DiscreteInterval other) {\n return new DiscreteInterval(this.min - other.max, this.max - other.min);\n }"
] |
Get log level depends on provided client parameters such as verbose and quiet. | [
"private Level getLogLevel() {\n return isQuiet() ? Level.OFF : isVerbose() ? Level.DEBUG : Level.INFO;\n }"
] | [
"public static base_response clear(nitro_service client) throws Exception {\n\t\tnspbr6 clearresource = new nspbr6();\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}",
"public int compareTo(Rational other)\n {\n if (denominator == other.getDenominator())\n {\n return ((Long) numerator).compareTo(other.getNumerator());\n }\n else\n {\n Long adjustedNumerator = numerator * other.getDenominator();\n Long otherAdjustedNumerator = other.getNumerator() * denominator;\n return adjustedNumerator.compareTo(otherAdjustedNumerator);\n }\n }",
"public static sslaction[] get(nitro_service service) throws Exception{\n\t\tsslaction obj = new sslaction();\n\t\tsslaction[] response = (sslaction[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static void logLong(String TAG, String longString) {\n InputStream is = new ByteArrayInputStream( longString.getBytes() );\n @SuppressWarnings(\"resource\")\n Scanner scan = new Scanner(is);\n while (scan.hasNextLine()) {\n Log.v(TAG, scan.nextLine());\n }\n }",
"public static void checkCreateUpload(CmsObject cms, CmsUgcConfiguration config, String name, long size)\n throws CmsUgcException {\n\n if (!config.getUploadParentFolder().isPresent()) {\n String message = Messages.get().container(Messages.ERR_NO_UPLOADS_ALLOWED_0).key(\n cms.getRequestContext().getLocale());\n throw new CmsUgcException(CmsUgcConstants.ErrorCode.errNoUploadAllowed, message);\n }\n\n if (config.getMaxUploadSize().isPresent()) {\n if (config.getMaxUploadSize().get().longValue() < size) {\n String message = Messages.get().container(Messages.ERR_UPLOAD_TOO_BIG_1, name).key(\n cms.getRequestContext().getLocale());\n throw new CmsUgcException(CmsUgcConstants.ErrorCode.errMaxUploadSizeExceeded, message);\n }\n }\n\n if (config.getValidExtensions().isPresent()) {\n List<String> validExtensions = config.getValidExtensions().get();\n boolean foundExtension = false;\n for (String extension : validExtensions) {\n if (name.toLowerCase().endsWith(extension.toLowerCase())) {\n foundExtension = true;\n break;\n }\n }\n if (!foundExtension) {\n String message = Messages.get().container(Messages.ERR_UPLOAD_FILE_EXTENSION_NOT_ALLOWED_1, name).key(\n cms.getRequestContext().getLocale());\n throw new CmsUgcException(CmsUgcConstants.ErrorCode.errInvalidExtension, message);\n }\n }\n }",
"ModelNode toModelNode() {\n ModelNode result = null;\n if (map != null) {\n result = new ModelNode();\n for (Map.Entry<PathAddress, ResourceData> entry : map.entrySet()) {\n ModelNode item = new ModelNode();\n PathAddress pa = entry.getKey();\n item.get(ABSOLUTE_ADDRESS).set(pa.toModelNode());\n ResourceData rd = entry.getValue();\n item.get(RELATIVE_ADDRESS).set(pa.subAddress(baseAddressLength).toModelNode());\n ModelNode attrs = new ModelNode().setEmptyList();\n if (rd.attributes != null) {\n for (String attr : rd.attributes) {\n attrs.add(attr);\n }\n }\n if (attrs.asInt() > 0) {\n item.get(FILTERED_ATTRIBUTES).set(attrs);\n }\n ModelNode children = new ModelNode().setEmptyList();\n if (rd.children != null) {\n for (PathElement pe : rd.children) {\n children.add(new Property(pe.getKey(), new ModelNode(pe.getValue())));\n }\n }\n if (children.asInt() > 0) {\n item.get(UNREADABLE_CHILDREN).set(children);\n }\n ModelNode childTypes = new ModelNode().setEmptyList();\n if (rd.childTypes != null) {\n Set<String> added = new HashSet<String>();\n for (PathElement pe : rd.childTypes) {\n if (added.add(pe.getKey())) {\n childTypes.add(pe.getKey());\n }\n }\n }\n if (childTypes.asInt() > 0) {\n item.get(FILTERED_CHILDREN_TYPES).set(childTypes);\n }\n result.add(item);\n }\n }\n return result;\n }",
"public void logAttributeWarning(PathAddress address, String message, Set<String> attributes) {\n messageQueue.add(new AttributeLogEntry(address, null, message, attributes));\n }",
"private List<Integer> getNodeIdListForPartitionIdList(List<Integer> partitionIds)\n throws VoldemortException {\n List<Integer> nodeIds = new ArrayList<Integer>(partitionIds.size());\n for(Integer partitionId: partitionIds) {\n int nodeId = getNodeIdForPartitionId(partitionId);\n if(nodeIds.contains(nodeId)) {\n throw new VoldemortException(\"Node ID \" + nodeId + \" already in list of Node IDs.\");\n } else {\n nodeIds.add(nodeId);\n }\n }\n return nodeIds;\n }",
"public static authenticationvserver_authenticationtacacspolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_authenticationtacacspolicy_binding obj = new authenticationvserver_authenticationtacacspolicy_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_authenticationtacacspolicy_binding response[] = (authenticationvserver_authenticationtacacspolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Returns a new created connection
@param jcd the connection descriptor
@return an instance of Connection from the drivermanager | [
"protected Connection newConnectionFromDriverManager(JdbcConnectionDescriptor jcd)\r\n throws LookupException\r\n {\r\n Connection retval = null;\r\n // use JDBC DriverManager\r\n final String driver = jcd.getDriver();\r\n final String url = getDbURL(jcd);\r\n try\r\n {\r\n // loads the driver - NB call to newInstance() added to force initialisation\r\n ClassHelper.getClass(driver, true);\r\n final String user = jcd.getUserName();\r\n final String password = jcd.getPassWord();\r\n final Properties properties = getJdbcProperties(jcd, user, password);\r\n if (properties.isEmpty())\r\n {\r\n if (user == null)\r\n {\r\n retval = DriverManager.getConnection(url);\r\n }\r\n else\r\n {\r\n retval = DriverManager.getConnection(url, user, password);\r\n }\r\n }\r\n else\r\n {\r\n retval = DriverManager.getConnection(url, properties);\r\n }\r\n }\r\n catch (SQLException sqlEx)\r\n {\r\n log.error(\"Error getting Connection from DriverManager with url (\" + url + \") and driver (\" + driver + \")\", sqlEx);\r\n throw new LookupException(\"Error getting Connection from DriverManager with url (\" + url + \") and driver (\" + driver + \")\", sqlEx);\r\n }\r\n catch (ClassNotFoundException cnfEx)\r\n {\r\n log.error(cnfEx);\r\n throw new LookupException(\"A class was not found\", cnfEx);\r\n }\r\n catch (Exception e)\r\n {\r\n log.error(\"Instantiation of jdbc driver failed\", e);\r\n throw new LookupException(\"Instantiation of jdbc driver failed\", e);\r\n }\r\n // initialize connection\r\n initializeJdbcConnection(retval, jcd);\r\n if(log.isDebugEnabled()) log.debug(\"Create new connection using DriverManager: \"+retval);\r\n return retval;\r\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}",
"public static<T> SessionVar<T> vendSessionVar(T defValue) {\n\treturn (new VarsJBridge()).vendSessionVar(defValue, new Exception());\n }",
"@Modified(id = \"exporterServices\")\n void modifiedExporterService(ServiceReference<ExporterService> serviceReference) {\n try {\n exportersManager.modified(serviceReference);\n } catch (InvalidFilterException invalidFilterException) {\n LOG.error(\"The ServiceProperty \\\"\" + TARGET_FILTER_PROPERTY + \"\\\" of the ExporterService \"\n + bundleContext.getService(serviceReference) + \" doesn't provides a valid Filter.\"\n + \" To be used, it must provides a correct \\\"\" + TARGET_FILTER_PROPERTY + \"\\\" ServiceProperty.\",\n invalidFilterException\n );\n exportersManager.removeLinks(serviceReference);\n return;\n }\n if (exportersManager.matched(serviceReference)) {\n exportersManager.updateLinks(serviceReference);\n } else {\n exportersManager.removeLinks(serviceReference);\n }\n }",
"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}",
"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 }",
"public Constructor<?> getCompatibleConstructor(Class<?> type,\r\n\t\t\tClass<?> argumentType) {\r\n\t\ttry {\r\n\t\t\treturn type.getConstructor(new Class[] { argumentType });\r\n\t\t} catch (Exception e) {\r\n\t\t\t// get public classes and interfaces\r\n\t\t\tClass<?>[] types = type.getClasses();\r\n\r\n\t\t\tfor (int i = 0; i < types.length; i++) {\r\n\t\t\t\ttry {\r\n\t\t\t\t\treturn type.getConstructor(new Class[] { types[i] });\r\n\t\t\t\t} catch (Exception e1) {\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn null;\r\n\t}",
"private OperationResponse executeForResult(final OperationExecutionContext executionContext) throws IOException {\n try {\n return execute(executionContext).get();\n } catch(Exception e) {\n throw new IOException(e);\n }\n }",
"@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n\tprivate IntegrationFlowBuilder getFlowBuilder() {\n\n\t\tIntegrationFlowBuilder flowBuilder;\n\t\tURLName urlName = this.properties.getUrl();\n\n\t\tif (this.properties.isIdleImap()) {\n\t\t\tflowBuilder = getIdleImapFlow(urlName);\n\t\t}\n\t\telse {\n\n\t\t\tMailInboundChannelAdapterSpec adapterSpec;\n\t\t\tswitch (urlName.getProtocol().toUpperCase()) {\n\t\t\t\tcase \"IMAP\":\n\t\t\t\tcase \"IMAPS\":\n\t\t\t\t\tadapterSpec = getImapFlowBuilder(urlName);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"POP3\":\n\t\t\t\tcase \"POP3S\":\n\t\t\t\t\tadapterSpec = getPop3FlowBuilder(urlName);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\t\"Unsupported mail protocol: \" + urlName.getProtocol());\n\t\t\t}\n\t\t\tflowBuilder = IntegrationFlows.from(\n\t\t\t\t\tadapterSpec.javaMailProperties(getJavaMailProperties(urlName))\n\t\t\t\t\t\t\t.selectorExpression(this.properties.getExpression())\n\t\t\t\t\t\t\t.shouldDeleteMessages(this.properties.isDelete()),\n\t\t\t\t\tnew Consumer<SourcePollingChannelAdapterSpec>() {\n\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void accept(\n\t\t\t\t\t\t\t\tSourcePollingChannelAdapterSpec sourcePollingChannelAdapterSpec) {\n\t\t\t\t\t\t\tsourcePollingChannelAdapterSpec.poller(MailSourceConfiguration.this.defaultPoller);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t});\n\n\t\t}\n\t\treturn flowBuilder;\n\t}",
"public List<MapRow> readTable(TableReader reader) throws IOException\n {\n reader.read();\n return reader.getRows();\n }"
] |
Parse units.
@param value units value
@return units value | [
"public static final Number parseUnits(Number value)\n {\n return (value == null ? null : NumberHelper.getDouble(value.doubleValue() * 100));\n }"
] | [
"public static void dumpMaterialProperty(AiMaterial.Property property) {\n System.out.print(property.getKey() + \" \" + property.getSemantic() + \n \" \" + property.getIndex() + \": \");\n Object data = property.getData();\n \n if (data instanceof ByteBuffer) {\n ByteBuffer buf = (ByteBuffer) data;\n for (int i = 0; i < buf.capacity(); i++) {\n System.out.print(Integer.toHexString(buf.get(i) & 0xFF) + \" \");\n }\n \n System.out.println();\n }\n else {\n System.out.println(data.toString());\n }\n }",
"public void setColorRange(int firstIndex, int lastIndex, int color1, int color2) {\n\t\tfor (int i = firstIndex; i <= lastIndex; i++)\n\t\t\tmap[i] = ImageMath.mixColors((float)(i-firstIndex)/(lastIndex-firstIndex), color1, color2);\n\t}",
"public static <T> T splitEachLine(InputStream stream, String regex, String charset, @ClosureParams(value=FromString.class,options=\"List<String>\") Closure<T> closure) throws IOException {\n return splitEachLine(new BufferedReader(new InputStreamReader(stream, charset)), regex, closure);\n }",
"public 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 }",
"public void openReport(String newState, A_CmsReportThread thread, String label) {\n\n setReport(newState, thread);\n m_labels.put(thread, label);\n openSubView(newState, true);\n }",
"private boolean matchesFingerprint(byte[] buffer, Pattern fingerprint)\n {\n return fingerprint.matcher(m_charset == null ? new String(buffer) : new String(buffer, m_charset)).matches();\n }",
"public static HashMap<String, String> getParameters(String query) {\n HashMap<String, String> params = new HashMap<String, String>();\n if (query == null || query.length() == 0) {\n return params;\n }\n\n String[] splitQuery = query.split(\"&\");\n for (String splitItem : splitQuery) {\n String[] items = splitItem.split(\"=\");\n\n if (items.length == 1) {\n params.put(items[0], \"\");\n } else {\n params.put(items[0], items[1]);\n }\n }\n\n return params;\n }",
"public void notifyEventListeners(ZWaveEvent event) {\n\t\tlogger.debug(\"Notifying event listeners\");\n\t\tfor (ZWaveEventListener listener : this.zwaveEventListeners) {\n\t\t\tlogger.trace(\"Notifying {}\", listener.toString());\n\t\t\tlistener.ZWaveIncomingEvent(event);\n\t\t}\n\t}",
"public static autoscaleprofile[] get(nitro_service service) throws Exception{\n\t\tautoscaleprofile obj = new autoscaleprofile();\n\t\tautoscaleprofile[] response = (autoscaleprofile[])obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Returns status message.
@param user CmsUser
@param disabled boolean
@param newUser boolean
@return String | [
"String getStatus(CmsUser user, boolean disabled, boolean newUser) {\n\n if (disabled) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_DISABLED_0);\n }\n if (newUser) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_INACTIVE_0);\n }\n if (OpenCms.getLoginManager().isUserTempDisabled(user.getName())) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_UNLOCK_USER_STATUS_0);\n }\n if (isUserPasswordReset(user)) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_PASSWORT_RESET_0);\n }\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_ACTIVE_0);\n }"
] | [
"@Override\n\tpublic <T> T get(Object key, Resource resource, Provider<T> provider) {\n\t\tif(resource == null) {\n\t\t\treturn provider.get();\n\t\t}\n\t\tCacheAdapter adapter = getOrCreate(resource);\n\t\tT element = adapter.<T>internalGet(key);\n\t\tif (element==null) {\n\t\t\telement = provider.get();\n\t\t\tcacheMiss(adapter);\n\t\t\tadapter.set(key, element);\n\t\t} else {\n\t\t\tcacheHit(adapter);\n\t\t}\n\t\tif (element == CacheAdapter.NULL) {\n\t\t\treturn null;\n\t\t}\n\t\treturn element;\n\t}",
"private synchronized void setInitializationMethod(Method newMethod)\r\n {\r\n if (newMethod != null)\r\n {\r\n // make sure it's a no argument method\r\n if (newMethod.getParameterTypes().length > 0)\r\n {\r\n throw new MetadataException(\r\n \"Initialization methods must be zero argument methods: \"\r\n + newMethod.getClass().getName()\r\n + \".\"\r\n + newMethod.getName());\r\n }\r\n\r\n // make it accessible if it's not already\r\n if (!newMethod.isAccessible())\r\n {\r\n newMethod.setAccessible(true);\r\n }\r\n }\r\n this.initializationMethod = newMethod;\r\n }",
"@Override\r\n public synchronized long skip(final long length) throws IOException {\r\n final long skip = super.skip(length);\r\n this.count += skip;\r\n return skip;\r\n }",
"public CollectionRequest<Project> findByWorkspace(String workspace) {\n \n String path = String.format(\"/workspaces/%s/projects\", workspace);\n return new CollectionRequest<Project>(this, Project.class, path, \"GET\");\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 double Function1D(double x) {\n return Math.exp(x * x / (-2 * sqrSigma)) / (Math.sqrt(2 * Math.PI) * sigma);\n }",
"public SelectStatement getPreparedSelectStatement(Query query, ClassDescriptor cld)\r\n {\r\n SelectStatement sql = new SqlSelectStatement(m_platform, cld, query, logger);\r\n if (logger.isDebugEnabled())\r\n {\r\n logger.debug(\"SQL:\" + sql.getStatement());\r\n }\r\n return sql;\r\n }",
"public int scrollToNextPage() {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"scrollToNextPage getCurrentPage() = %d currentIndex = %d\",\n getCurrentPage(), mCurrentItemIndex);\n\n if (mSupportScrollByPage) {\n scrollToPage(getCurrentPage() + 1);\n } else {\n Log.w(TAG, \"Pagination is not enabled!\");\n }\n\n return mCurrentItemIndex;\n\t}",
"public static TextEncryptor queryableText(CharSequence password, CharSequence salt) {\n\t\treturn new HexEncodingTextEncryptor(new AndroidAesBytesEncryptor(password.toString(), salt, AndroidKeyGenerators.shared(16)));\n\t}"
] |
Used to map from a var data key to a field type. Note this
is designed for diagnostic use only, and uses an inefficient search.
@param key var data key
@return field type | [
"public FieldType getFieldTypeFromVarDataKey(Integer key)\n {\n FieldType result = null;\n for (Entry<FieldType, FieldMap.FieldItem> entry : m_map.entrySet())\n {\n if (entry.getValue().getFieldLocation() == FieldLocation.VAR_DATA && entry.getValue().getVarDataKey().equals(key))\n {\n result = entry.getKey();\n break;\n }\n }\n return result;\n }"
] | [
"public static void checkFloatNotNaNOrInfinity(String parameterName,\n float data) {\n if (Float.isNaN(data) || Float.isInfinite(data)) {\n throw Exceptions.IllegalArgument(\n \"%s should never be NaN or Infinite.\", parameterName);\n }\n }",
"public ValueContainer[] getKeyValues(ClassDescriptor cld, Identity oid, boolean convertToSql) throws PersistenceBrokerException\r\n {\r\n FieldDescriptor[] pkFields = cld.getPkFields();\r\n ValueContainer[] result = new ValueContainer[pkFields.length];\r\n Object[] pkValues = oid.getPrimaryKeyValues();\r\n\r\n try\r\n {\r\n for(int i = 0; i < result.length; i++)\r\n {\r\n FieldDescriptor fd = pkFields[i];\r\n Object cv = pkValues[i];\r\n if(convertToSql)\r\n {\r\n // BRJ : apply type and value mapping\r\n cv = fd.getFieldConversion().javaToSql(cv);\r\n }\r\n result[i] = new ValueContainer(cv, fd.getJdbcType());\r\n }\r\n }\r\n catch(Exception e)\r\n {\r\n throw new PersistenceBrokerException(\"Can't generate primary key values for given Identity \" + oid, e);\r\n }\r\n return result;\r\n }",
"public void addForeignkey(String relationName, String remoteTable, List localColumns, List remoteColumns)\r\n {\r\n ForeignkeyDef foreignkeyDef = new ForeignkeyDef(relationName, remoteTable);\r\n\r\n // the field arrays have the same length if we already checked the constraints\r\n for (int idx = 0; idx < localColumns.size(); idx++)\r\n {\r\n foreignkeyDef.addColumnPair((String)localColumns.get(idx),\r\n (String)remoteColumns.get(idx));\r\n }\r\n\r\n // we got to determine whether this foreignkey is already present \r\n ForeignkeyDef def = null;\r\n\r\n for (Iterator it = getForeignkeys(); it.hasNext();)\r\n {\r\n def = (ForeignkeyDef)it.next();\r\n if (foreignkeyDef.equals(def))\r\n {\r\n return;\r\n }\r\n }\r\n foreignkeyDef.setOwner(this);\r\n _foreignkeys.add(foreignkeyDef);\r\n }",
"public boolean isUpToDate(final DbArtifact artifact) {\n final List<String> versions = repoHandler.getArtifactVersions(artifact);\n final String currentVersion = artifact.getVersion();\n\n final String lastDevVersion = getLastVersion(versions);\n final String lastReleaseVersion = getLastRelease(versions);\n\n if(lastDevVersion == null || lastReleaseVersion == null) {\n // Plain Text comparison against version \"strings\"\n for(final String version: versions){\n if(version.compareTo(currentVersion) > 0){\n return false;\n }\n }\n return true;\n } else {\n return currentVersion.equals(lastDevVersion) || currentVersion.equals(lastReleaseVersion);\n }\n }",
"static void initializeExtension(ExtensionRegistry extensionRegistry, String module,\n ManagementResourceRegistration rootRegistration,\n ExtensionRegistryType extensionRegistryType) {\n try {\n boolean unknownModule = false;\n boolean initialized = false;\n for (Extension extension : Module.loadServiceFromCallerModuleLoader(module, Extension.class)) {\n ClassLoader oldTccl = WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(extension.getClass());\n try {\n if (unknownModule || !extensionRegistry.getExtensionModuleNames().contains(module)) {\n // This extension wasn't handled by the standalone.xml or domain.xml parsing logic, so we\n // need to initialize its parsers so we can display what XML namespaces it supports\n extensionRegistry.initializeParsers(extension, module, null);\n // AS7-6190 - ensure we initialize parsers for other extensions from this module\n // now that we know the registry was unaware of the module\n unknownModule = true;\n }\n extension.initialize(extensionRegistry.getExtensionContext(module, rootRegistration, extensionRegistryType));\n } finally {\n WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTccl);\n }\n initialized = true;\n }\n if (!initialized) {\n throw ControllerLogger.ROOT_LOGGER.notFound(\"META-INF/services/\", Extension.class.getName(), module);\n }\n } catch (ModuleNotFoundException e) {\n // Treat this as a user mistake, e.g. incorrect module name.\n // Throw OFE so post-boot it only gets logged at DEBUG.\n throw ControllerLogger.ROOT_LOGGER.extensionModuleNotFound(e, module);\n } catch (ModuleLoadException e) {\n // The module is there but can't be loaded. Treat this as an internal problem.\n // Throw a runtime exception so it always gets logged at ERROR in the server log with stack trace details.\n throw ControllerLogger.ROOT_LOGGER.extensionModuleLoadingFailure(e, module);\n }\n }",
"public PhotoList<Photo> getPublicPhotos(String userId, Set<String> extras, int perPage, int page) throws FlickrException {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PUBLIC_PHOTOS);\r\n\r\n parameters.put(\"user_id\", userId);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n\r\n if (extras != null) {\r\n parameters.put(Extras.KEY_EXTRAS, StringUtilities.join(extras, \",\"));\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n photos.setPage(photosElement.getAttribute(\"page\"));\r\n photos.setPages(photosElement.getAttribute(\"pages\"));\r\n photos.setPerPage(photosElement.getAttribute(\"perpage\"));\r\n photos.setTotal(photosElement.getAttribute(\"total\"));\r\n\r\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element photoElement = (Element) photoNodes.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement));\r\n }\r\n return photos;\r\n }",
"public AT_Row setPaddingBottom(int paddingBottom) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingBottom(paddingBottom);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"void markReferenceElements(PersistenceBroker broker)\r\n {\r\n // these cases will be handled by ObjectEnvelopeTable#cascadingDependents()\r\n // if(getModificationState().needsInsert() || getModificationState().needsDelete()) return;\r\n\r\n Map oldImage = getBeforeImage();\r\n Map newImage = getCurrentImage();\r\n\r\n Iterator iter = newImage.entrySet().iterator();\r\n while (iter.hasNext())\r\n {\r\n Map.Entry entry = (Map.Entry) iter.next();\r\n Object key = entry.getKey();\r\n // we only interested in references\r\n if(key instanceof ObjectReferenceDescriptor)\r\n {\r\n Image oldRefImage = (Image) oldImage.get(key);\r\n Image newRefImage = (Image) entry.getValue();\r\n newRefImage.performReferenceDetection(oldRefImage);\r\n }\r\n }\r\n }",
"public 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 }"
] |
Searches for commas in the set of tokens. Used for inputs to functions.
Ignore comma's which are inside a [ ] block
@return List of output tokens between the commas | [
"protected List<TokenList.Token> parseParameterCommaBlock( TokenList tokens, Sequence sequence ) {\n // find all the comma tokens\n List<TokenList.Token> commas = new ArrayList<TokenList.Token>();\n TokenList.Token token = tokens.first;\n\n int numBracket = 0;\n while( token != null ) {\n if( token.getType() == Type.SYMBOL ) {\n switch( token.getSymbol() ) {\n case COMMA:\n if( numBracket == 0)\n commas.add(token);\n break;\n\n case BRACKET_LEFT: numBracket++; break;\n case BRACKET_RIGHT: numBracket--; break;\n }\n }\n token = token.next;\n }\n\n List<TokenList.Token> output = new ArrayList<TokenList.Token>();\n if( commas.isEmpty() ) {\n output.add(parseBlockNoParentheses(tokens, sequence, false));\n } else {\n TokenList.Token before = tokens.first;\n for (int i = 0; i < commas.size(); i++) {\n TokenList.Token after = commas.get(i);\n if( before == after )\n throw new ParseError(\"No empty function inputs allowed!\");\n TokenList.Token tmp = after.next;\n TokenList sublist = tokens.extractSubList(before,after);\n sublist.remove(after);// remove the comma\n output.add(parseBlockNoParentheses(sublist, sequence, false));\n before = tmp;\n }\n\n // if the last character is a comma then after.next above will be null and thus before is null\n if( before == null )\n throw new ParseError(\"No empty function inputs allowed!\");\n\n TokenList.Token after = tokens.last;\n TokenList sublist = tokens.extractSubList(before, after);\n output.add(parseBlockNoParentheses(sublist, sequence, false));\n }\n\n return output;\n }"
] | [
"private void startRelayWithPortTollerance(HttpServer server, SslListener relay, int tries) throws Exception {\n if (tries >= 5) {\n throw new BindException(\"Unable to bind to several ports, most recently \" + relay.getPort() + \". Giving up\");\n }\n try {\n if (server.isStarted()) {\n relay.start();\n } else {\n throw new RuntimeException(\"Can't start SslRelay: server is not started (perhaps it was just shut down?)\");\n }\n } catch (BindException e) {\n // doh - the port is being used up, let's pick a new port\n LOG.info(\"Unable to bind to port %d, going to try port %d now\", relay.getPort(), relay.getPort() + 1);\n relay.setPort(relay.getPort() + 1);\n startRelayWithPortTollerance(server, relay, tries + 1);\n }\n }",
"@Override\n protected void onGraphDraw(Canvas _Canvas) {\n super.onGraphDraw(_Canvas);\n _Canvas.translate(-mCurrentViewport.left, -mCurrentViewport.top);\n drawBars(_Canvas);\n }",
"static String[] tokenize(String str) {\n char sep = '.';\n int start = 0;\n int len = str.length();\n int count = 0;\n for (int pos = 0; pos < len; pos++) {\n if (str.charAt(pos) == sep) {\n if (pos != start) {\n count++;\n }\n start = pos + 1;\n }\n }\n if (len != start) {\n count++;\n }\n String[] l = new String[count];\n\n count = 0;\n start = 0;\n for (int pos = 0; pos < len; pos++) {\n if (str.charAt(pos) == sep) {\n if (pos != start) {\n String tok = str.substring(start, pos);\n l[count++] = tok;\n }\n start = pos + 1;\n }\n }\n if (len != start) {\n String tok = str.substring(start);\n l[count/* ++ */] = tok;\n }\n return l;\n }",
"private void checkObjectCache(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (!CHECKLEVEL_STRICT.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n \r\n ObjectCacheDef objCacheDef = classDef.getObjectCache();\r\n\r\n if (objCacheDef == null)\r\n {\r\n return;\r\n }\r\n\r\n String objectCacheName = objCacheDef.getName();\r\n\r\n if ((objectCacheName == null) || (objectCacheName.length() == 0))\r\n {\r\n throw new ConstraintException(\"No class specified for the object-cache of class \"+classDef.getName());\r\n }\r\n\r\n try\r\n {\r\n InheritanceHelper helper = new InheritanceHelper();\r\n\r\n if (!helper.isSameOrSubTypeOf(objectCacheName, OBJECT_CACHE_INTERFACE))\r\n {\r\n throw new ConstraintException(\"The class \"+objectCacheName+\" specified as object-cache of class \"+classDef.getName()+\" does not implement the interface \"+OBJECT_CACHE_INTERFACE);\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"Could not find the class \"+ex.getMessage()+\" on the classpath while checking the object-cache class \"+objectCacheName+\" of class \"+classDef.getName());\r\n }\r\n }",
"public static base_responses expire(nitro_service client, cachecontentgroup resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcachecontentgroup expireresources[] = new cachecontentgroup[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\texpireresources[i] = new cachecontentgroup();\n\t\t\t\texpireresources[i].name = resources[i].name;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, expireresources,\"expire\");\n\t\t}\n\t\treturn result;\n\t}",
"public static void checkFloatNotNaNOrInfinity(String parameterName,\n float data) {\n if (Float.isNaN(data) || Float.isInfinite(data)) {\n throw Exceptions.IllegalArgument(\n \"%s should never be NaN or Infinite.\", parameterName);\n }\n }",
"public void setSeriesEndDate(Date date) {\r\n\r\n if (!Objects.equals(m_model.getSeriesEndDate(), date)) {\r\n m_model.setSeriesEndDate(date);\r\n valueChanged();\r\n }\r\n\r\n }",
"public static final Date getTimestamp(byte[] data, int offset)\n {\n Date result;\n\n long days = getShort(data, offset + 2);\n if (days < 100)\n {\n // We are seeing some files which have very small values for the number of days.\n // When the relevant field is shown in MS Project it appears as NA.\n // We try to mimic this behaviour here.\n days = 0;\n }\n\n if (days == 0 || days == 65535)\n {\n result = null;\n }\n else\n {\n long time = getShort(data, offset);\n if (time == 65535)\n {\n time = 0;\n }\n result = DateHelper.getTimestampFromLong((EPOCH + (days * DateHelper.MS_PER_DAY) + ((time * DateHelper.MS_PER_MINUTE) / 10)));\n }\n\n return (result);\n }",
"public static boolean decomposeSafe(DecompositionInterface<ZMatrixRMaj> decomposition, ZMatrixRMaj a) {\n\n if( decomposition.inputModified() ) {\n a = a.copy();\n }\n return decomposition.decompose(a);\n }"
] |
Returns the ReportModel with given name. | [
"@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 static <T> T callConstructor(Class<T> klass, Object[] args) {\n Class<?>[] klasses = new Class[args.length];\n for(int i = 0; i < args.length; i++)\n klasses[i] = args[i].getClass();\n return callConstructor(klass, klasses, args);\n }",
"public static responderpolicy_binding get(nitro_service service, String name) throws Exception{\n\t\tresponderpolicy_binding obj = new responderpolicy_binding();\n\t\tobj.set_name(name);\n\t\tresponderpolicy_binding response = (responderpolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public void waitForDeployments(@Observes(precedence = -100) AfterStart event, OpenShiftAdapter client,\n CEEnvironmentProcessor.TemplateDetails details, TestClass testClass, CubeOpenShiftConfiguration configuration, OpenShiftClient openshiftClient)\n throws Exception {\n if (testClass == null) {\n // nothing to do, since we're not in ClassScoped context\n return;\n }\n if (details == null) {\n log.warning(String.format(\"No environment for %s\", testClass.getName()));\n return;\n }\n log.info(String.format(\"Waiting for environment for %s\", testClass.getName()));\n try {\n delay(client, details.getResources());\n } catch (Throwable t) {\n throw new IllegalArgumentException(\"Error waiting for template resources to deploy: \" + testClass.getName(), t);\n }\n }",
"public Triple<Double, Integer, Integer> getAccuracyInfo()\r\n {\r\n int totalCorrect = tokensCorrect;\r\n int totalWrong = tokensCount - tokensCorrect;\r\n return new Triple<Double, Integer, Integer>((((double) totalCorrect) / tokensCount),\r\n totalCorrect, totalWrong);\r\n }",
"protected Boolean checkBoolean(Object val, Boolean def) {\n return (val == null) ? def : (Boolean) val;\n }",
"public void beforeBatch(PreparedStatement stmt) throws PlatformException\r\n {\r\n // Check for Oracle batching support\r\n final Method methodSetExecuteBatch;\r\n final Method methodSendBatch;\r\n methodSetExecuteBatch = ClassHelper.getMethod(stmt, \"setExecuteBatch\", PARAM_TYPE_INTEGER);\r\n methodSendBatch = ClassHelper.getMethod(stmt, \"sendBatch\", null);\r\n\r\n final boolean statementBatchingSupported = methodSetExecuteBatch != null && methodSendBatch != null;\r\n if (statementBatchingSupported)\r\n {\r\n try\r\n {\r\n // Set number of statements per batch\r\n methodSetExecuteBatch.invoke(stmt, PARAM_STATEMENT_BATCH_SIZE);\r\n m_batchStatementsInProgress.put(stmt, methodSendBatch);\r\n }\r\n catch (Exception e)\r\n {\r\n throw new PlatformException(e.getLocalizedMessage(), e);\r\n }\r\n }\r\n else\r\n {\r\n super.beforeBatch(stmt);\r\n }\r\n }",
"public Request option(String key, Object value) {\n this.options.put(key, value);\n return this;\n }",
"public final B accessToken(String accessToken) {\n requireNonNull(accessToken, \"accessToken\");\n checkArgument(!accessToken.isEmpty(), \"accessToken is empty.\");\n this.accessToken = accessToken;\n return self();\n }",
"private int getColor(int value) {\n\t\tif (value == 0) {\n\t\t\treturn 0;\n\t\t}\n\n\t\tdouble scale = Math.log10(value) / Math.log10(this.topValue);\n\t\tdouble lengthScale = Math.min(1.0, scale) * (colors.length - 1);\n\t\tint index = 1 + (int) lengthScale;\n\t\tif (index == colors.length) {\n\t\t\tindex--;\n\t\t}\n\t\tdouble partScale = lengthScale - (index - 1);\n\n\t\tint r = (int) (colors[index - 1][0] + partScale\n\t\t\t\t* (colors[index][0] - colors[index - 1][0]));\n\t\tint g = (int) (colors[index - 1][1] + partScale\n\t\t\t\t* (colors[index][1] - colors[index - 1][1]));\n\t\tint b = (int) (colors[index - 1][2] + partScale\n\t\t\t\t* (colors[index][2] - colors[index - 1][2]));\n\n\t\tr = Math.min(255, r);\n\t\tb = Math.min(255, b);\n\t\tg = Math.min(255, g);\n\t\treturn (r << 16) | (g << 8) | b;\n\t}"
] |
Finish initializing the service. | [
"@PostConstruct\n\tprotected void postConstruct() throws GeomajasException {\n\t\tif (null == baseTmsUrl) {\n\t\t\tthrow new GeomajasException(ExceptionCode.PARAMETER_MISSING, \"baseTmsUrl\");\n\t\t}\n\n\t\t// Make sure we have a base URL we can work with:\n\t\tif ((baseTmsUrl.startsWith(\"http://\") || baseTmsUrl.startsWith(\"https://\")) && !baseTmsUrl.endsWith(\"/\")) {\n\t\t\tbaseTmsUrl += \"/\";\n\t\t}\n\n\t\t// Make sure there is a correct RasterLayerInfo object:\n\t\tif (layerInfo == null || layerInfo == UNUSABLE_LAYER_INFO) {\n\t\t\ttry {\n\t\t\t\ttileMap = configurationService.getCapabilities(this);\n\t\t\t\tversion = tileMap.getVersion();\n\t\t\t\textension = tileMap.getTileFormat().getExtension();\n\t\t\t\tlayerInfo = configurationService.asLayerInfo(tileMap);\n\t\t\t\tusable = true;\n\t\t\t} catch (TmsLayerException e) {\n\t\t\t\t// a layer needs an info object to keep the DtoConfigurationPostProcessor happy !\n\t\t\t\tlayerInfo = UNUSABLE_LAYER_INFO;\n\t\t\t\tusable = false;\n\t\t\t\tlog.warn(\"The layer could not be correctly initialized: \" + getId(), e);\n\t\t\t}\n\t\t} else if (extension == null) {\n\t\t\tthrow new GeomajasException(ExceptionCode.PARAMETER_MISSING, \"extension\");\n\t\t}\n\n\t\tif (layerInfo != null) {\n\t\t\t// Finally prepare some often needed values:\n\t\t\tstate = new TileServiceState(geoService, layerInfo);\n\t\t\t// when proxying the real url will be resolved later on, just use a simple one for now\n\t\t\tboolean proxying = useCache || useProxy || null != authentication;\n\t\t\tif (tileMap != null && !proxying) {\n\t\t\t\turlBuilder = new TileMapUrlBuilder(tileMap);\n\t\t\t} else {\n\t\t\t\turlBuilder = new SimpleTmsUrlBuilder(extension);\n\t\t\t}\n\t\t}\n\t}"
] | [
"public ItemRequest<User> findById(String user) {\n \n String path = String.format(\"/users/%s\", user);\n return new ItemRequest<User>(this, User.class, path, \"GET\");\n }",
"public void reset(int profileId, String clientUUID) throws Exception {\n PreparedStatement statement = null;\n\n // TODO: need a better way to do this than brute force.. but the iterative approach is too slow\n try (Connection sqlConnection = sqlService.getConnection()) {\n\n // first remove all enabled overrides with this client uuid\n String queryString = \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.GENERIC_CLIENT_UUID + \"= ? \" +\n \" AND \" + Constants.GENERIC_PROFILE_ID + \" = ?\";\n statement = sqlConnection.prepareStatement(queryString);\n statement.setString(1, clientUUID);\n statement.setInt(2, profileId);\n statement.executeUpdate();\n statement.close();\n\n // clean up request response table for this uuid\n queryString = \"UPDATE \" + Constants.DB_TABLE_REQUEST_RESPONSE +\n \" SET \" + Constants.REQUEST_RESPONSE_CUSTOM_REQUEST + \"=?, \"\n + Constants.REQUEST_RESPONSE_CUSTOM_RESPONSE + \"=?, \"\n + Constants.REQUEST_RESPONSE_REPEAT_NUMBER + \"=-1, \"\n + Constants.REQUEST_RESPONSE_REQUEST_ENABLED + \"=0, \"\n + Constants.REQUEST_RESPONSE_RESPONSE_ENABLED + \"=0 \"\n + \"WHERE \" + Constants.GENERIC_CLIENT_UUID + \"=? \" +\n \" AND \" + Constants.GENERIC_PROFILE_ID + \"=?\";\n statement = sqlConnection.prepareStatement(queryString);\n statement.setString(1, \"\");\n statement.setString(2, \"\");\n statement.setString(3, clientUUID);\n statement.setInt(4, profileId);\n statement.executeUpdate();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n this.updateActive(profileId, clientUUID, false);\n }",
"public static QRDecomposition<DoubleMatrix> qr(DoubleMatrix A) {\n int minmn = min(A.rows, A.columns);\n DoubleMatrix result = A.dup();\n DoubleMatrix tau = new DoubleMatrix(minmn);\n SimpleBlas.geqrf(result, tau);\n DoubleMatrix R = new DoubleMatrix(A.rows, A.columns);\n for (int i = 0; i < A.rows; i++) {\n for (int j = i; j < A.columns; j++) {\n R.put(i, j, result.get(i, j));\n }\n }\n DoubleMatrix Q = DoubleMatrix.eye(A.rows);\n SimpleBlas.ormqr('L', 'N', result, tau, Q);\n return new QRDecomposition<DoubleMatrix>(Q, R);\n }",
"public static base_response rename(nitro_service client, nsacl6 resource, String new_acl6name) throws Exception {\n\t\tnsacl6 renameresource = new nsacl6();\n\t\trenameresource.acl6name = resource.acl6name;\n\t\treturn renameresource.rename_resource(client,new_acl6name);\n\t}",
"protected static Connection memorize(final Connection target, final ConnectionHandle connectionHandle) {\n\n\t\treturn (Connection) Proxy.newProxyInstance(\n\t\t\t\tConnectionProxy.class.getClassLoader(),\n\t\t\t\tnew Class[] {ConnectionProxy.class},\n\t\t\t\tnew MemorizeTransactionProxy(target, connectionHandle));\n\t}",
"public 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}",
"static Property getProperty(String propName, ModelNode attrs) {\n String[] arr = propName.split(\"\\\\.\");\n ModelNode attrDescr = attrs;\n for (String item : arr) {\n // Remove list part.\n if (item.endsWith(\"]\")) {\n int i = item.indexOf(\"[\");\n if (i < 0) {\n return null;\n }\n item = item.substring(0, i);\n }\n ModelNode descr = attrDescr.get(item);\n if (!descr.isDefined()) {\n if (attrDescr.has(Util.VALUE_TYPE)) {\n ModelNode vt = attrDescr.get(Util.VALUE_TYPE);\n if (vt.has(item)) {\n attrDescr = vt.get(item);\n continue;\n }\n }\n return null;\n }\n attrDescr = descr;\n }\n return new Property(propName, attrDescr);\n }",
"protected final boolean isGLThread() {\n final Thread glThread = sGLThread.get();\n return glThread != null && glThread.equals(Thread.currentThread());\n }",
"private static <T, ID> void addCreateTableStatements(DatabaseType databaseType, TableInfo<T, ID> tableInfo,\n\t\t\tList<String> statements, List<String> queriesAfter, boolean ifNotExists, boolean logDetails)\n\t\t\tthrows SQLException {\n\t\tStringBuilder sb = new StringBuilder(256);\n\t\tif (logDetails) {\n\t\t\tlogger.info(\"creating table '{}'\", tableInfo.getTableName());\n\t\t}\n\t\tsb.append(\"CREATE TABLE \");\n\t\tif (ifNotExists && databaseType.isCreateIfNotExistsSupported()) {\n\t\t\tsb.append(\"IF NOT EXISTS \");\n\t\t}\n\t\tdatabaseType.appendEscapedEntityName(sb, tableInfo.getTableName());\n\t\tsb.append(\" (\");\n\t\tList<String> additionalArgs = new ArrayList<String>();\n\t\tList<String> statementsBefore = new ArrayList<String>();\n\t\tList<String> statementsAfter = new ArrayList<String>();\n\t\t// our statement will be set here later\n\t\tboolean first = true;\n\t\tfor (FieldType fieldType : tableInfo.getFieldTypes()) {\n\t\t\t// skip foreign collections\n\t\t\tif (fieldType.isForeignCollection()) {\n\t\t\t\tcontinue;\n\t\t\t} else if (first) {\n\t\t\t\tfirst = false;\n\t\t\t} else {\n\t\t\t\tsb.append(\", \");\n\t\t\t}\n\t\t\tString columnDefinition = fieldType.getColumnDefinition();\n\t\t\tif (columnDefinition == null) {\n\t\t\t\t// we have to call back to the database type for the specific create syntax\n\t\t\t\tdatabaseType.appendColumnArg(tableInfo.getTableName(), sb, fieldType, additionalArgs, statementsBefore,\n\t\t\t\t\t\tstatementsAfter, queriesAfter);\n\t\t\t} else {\n\t\t\t\t// hand defined field\n\t\t\t\tdatabaseType.appendEscapedEntityName(sb, fieldType.getColumnName());\n\t\t\t\tsb.append(' ').append(columnDefinition).append(' ');\n\t\t\t}\n\t\t}\n\t\t// add any sql that sets any primary key fields\n\t\tdatabaseType.addPrimaryKeySql(tableInfo.getFieldTypes(), additionalArgs, statementsBefore, statementsAfter,\n\t\t\t\tqueriesAfter);\n\t\t// add any sql that sets any unique fields\n\t\tdatabaseType.addUniqueComboSql(tableInfo.getFieldTypes(), additionalArgs, statementsBefore, statementsAfter,\n\t\t\t\tqueriesAfter);\n\t\tfor (String arg : additionalArgs) {\n\t\t\t// we will have spat out one argument already so we don't have to do the first dance\n\t\t\tsb.append(\", \").append(arg);\n\t\t}\n\t\tsb.append(\") \");\n\t\tdatabaseType.appendCreateTableSuffix(sb);\n\t\tstatements.addAll(statementsBefore);\n\t\tstatements.add(sb.toString());\n\t\tstatements.addAll(statementsAfter);\n\t\taddCreateIndexStatements(databaseType, tableInfo, statements, ifNotExists, false, logDetails);\n\t\taddCreateIndexStatements(databaseType, tableInfo, statements, ifNotExists, true, logDetails);\n\t}"
] |
Generate an IKVM map file.
@param mapFileName map file name
@param jarFile jar file containing code to be mapped
@param mapClassMethods true if we want to produce .Net style class method names
@throws IOException
@throws XMLStreamException
@throws ClassNotFoundException
@throws IntrospectionException | [
"private void writeMapFile(String mapFileName, File jarFile, boolean mapClassMethods) throws IOException, XMLStreamException, ClassNotFoundException, IntrospectionException\n {\n FileWriter fw = new FileWriter(mapFileName);\n XMLOutputFactory xof = XMLOutputFactory.newInstance();\n XMLStreamWriter writer = xof.createXMLStreamWriter(fw);\n //XMLStreamWriter writer = new IndentingXMLStreamWriter(xof.createXMLStreamWriter(fw));\n\n writer.writeStartDocument();\n writer.writeStartElement(\"root\");\n writer.writeStartElement(\"assembly\");\n\n addClasses(writer, jarFile, mapClassMethods);\n\n writer.writeEndElement();\n writer.writeEndElement();\n writer.writeEndDocument();\n writer.flush();\n writer.close();\n\n fw.flush();\n fw.close();\n }"
] | [
"public ServerRedirect getRedirect(int id) throws Exception {\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_SERVERS +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n queryStatement.setInt(1, id);\n results = queryStatement.executeQuery();\n if (results.next()) {\n ServerRedirect curServer = new ServerRedirect(results.getInt(Constants.GENERIC_ID),\n results.getString(Constants.SERVER_REDIRECT_REGION),\n results.getString(Constants.SERVER_REDIRECT_SRC_URL),\n results.getString(Constants.SERVER_REDIRECT_DEST_URL),\n results.getString(Constants.SERVER_REDIRECT_HOST_HEADER));\n curServer.setProfileId(results.getInt(Constants.GENERIC_PROFILE_ID));\n\n return curServer;\n }\n logger.info(\"Did not find the ID: {}\", id);\n } catch (SQLException 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 (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n return null;\n }",
"private void setTableAliasForPath(String aPath, List hintClasses, TableAlias anAlias)\r\n {\r\n m_pathToAlias.put(buildAliasKey(aPath, hintClasses), anAlias);\r\n }",
"@RequestMapping(value = \"/api/profile\", method = RequestMethod.DELETE)\n public\n @ResponseBody\n HashMap<String, Object> deleteProfile(Model model, int id) throws Exception {\n profileService.remove(id);\n return Utils.getJQGridJSON(profileService.findAllProfiles(), \"profiles\");\n }",
"public ClosableIterator<Tuple> callStoredProcedure(EmbeddedCacheManager embeddedCacheManager, String storedProcedureName, ProcedureQueryParameters queryParameters, ClassLoaderService classLoaderService ) {\n\t\tvalidate( queryParameters );\n\t\tCache<String, String> cache = embeddedCacheManager.getCache( STORED_PROCEDURES_CACHE_NAME, true );\n\t\tString className = cache.getOrDefault( storedProcedureName, storedProcedureName );\n\t\tCallable<?> callable = instantiate( storedProcedureName, className, classLoaderService );\n\t\tsetParams( storedProcedureName, queryParameters, callable );\n\t\tObject res = execute( storedProcedureName, embeddedCacheManager, callable );\n\t\treturn extractResultSet( storedProcedureName, res );\n\t}",
"public <C extends Contextual<I>, I> C getContextual(String id) {\n return this.<C, I>getContextual(new StringBeanIdentifier(id));\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 void logAttributeWarning(PathAddress address, ModelNode operation, String message, Set<String> attributes) {\n messageQueue.add(new AttributeLogEntry(address, operation, message, attributes));\n }",
"@POST\n @Path(\"/{name}\" + ServerAPI.GET_CORPORATE_GROUPIDS)\n public Response addCorporateGroupIdPrefix(@Auth final DbCredential credential, @PathParam(\"name\") final String organizationId, final String corporateGroupId){\n LOG.info(\"Got an add a corporate groupId prefix request for organization \" + organizationId +\".\");\n if(!credential.getRoles().contains(DbCredential.AvailableRoles.DATA_UPDATER)){\n throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).build());\n }\n\n if(corporateGroupId == null || corporateGroupId.isEmpty()){\n LOG.error(\"No corporate GroupId to add!\");\n throw new WebApplicationException(Response.serverError().status(HttpStatus.BAD_REQUEST_400)\n .entity(\"CorporateGroupId to add should be in the query content.\").build());\n }\n\n getOrganizationHandler().addCorporateGroupId(organizationId, corporateGroupId);\n return Response.ok().status(HttpStatus.CREATED_201).build();\n }",
"public void write(WritableByteChannel channel) throws IOException {\n logger.debug(\"..writing> {}\", this);\n Util.writeFully(getBytes(), channel);\n }"
] |
Creates a span that covers an exact row | [
"public static Span exact(Bytes row) {\n Objects.requireNonNull(row);\n return new Span(row, true, row, true);\n }"
] | [
"private Map<Integer, List<Row>> createExceptionAssignmentMap(List<Row> rows)\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 exceptions = row.getString(\"EXCEPTIONS\");\n map.put(calendarID, createExceptionAssignmentRowList(exceptions));\n }\n return map;\n }",
"public synchronized X509Certificate getCertificateByHostname(final String hostname) throws KeyStoreException, CertificateParsingException, InvalidKeyException, CertificateExpiredException, CertificateNotYetValidException, SignatureException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException, UnrecoverableKeyException{\n\n\t\tString alias = _subjectMap.get(getSubjectForHostname(hostname));\n\n\t\tif(alias != null) {\n\t\t\treturn (X509Certificate)_ks.getCertificate(alias);\n\t\t}\n return getMappedCertificateForHostname(hostname);\n\t}",
"public static final String printTimestamp(Date value)\n {\n return (value == null ? null : TIMESTAMP_FORMAT.get().format(value));\n }",
"public PeriodicEvent runAfter(Runnable task, float delay) {\n validateDelay(delay);\n return new Event(task, delay);\n }",
"public void saveFavorites(List<CmsFavoriteEntry> favorites) throws CmsException {\n\n try {\n JSONObject json = new JSONObject();\n JSONArray array = new JSONArray();\n for (CmsFavoriteEntry entry : favorites) {\n array.put(entry.toJson());\n }\n json.put(BASE_KEY, array);\n String data = json.toString();\n CmsUser user = readUser();\n user.setAdditionalInfo(ADDINFO_KEY, data);\n m_cms.writeUser(user);\n } catch (JSONException e) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n\n }",
"public static boolean pullImage(Launcher launcher, final String imageTag, final String username, final String password, final String host)\n throws IOException, InterruptedException {\n\n return launcher.getChannel().call(new MasterToSlaveCallable<Boolean, IOException>() {\n public Boolean call() throws IOException {\n DockerUtils.pullImage(imageTag, username, password, host);\n return true;\n }\n });\n }",
"public static base_responses update(nitro_service client, nsacl6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsacl6 updateresources[] = new nsacl6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nsacl6();\n\t\t\t\tupdateresources[i].acl6name = resources[i].acl6name;\n\t\t\t\tupdateresources[i].aclaction = resources[i].aclaction;\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].icmptype = resources[i].icmptype;\n\t\t\t\tupdateresources[i].icmpcode = resources[i].icmpcode;\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].established = resources[i].established;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public static void main(String[] args) {\n CmdLine cmd = new CmdLine();\n Configuration conf = new Configuration();\n int res = 0;\n try {\n res = ToolRunner.run(conf, cmd, args);\n } catch (Exception e) {\n System.err.println(\"Error while running MR job\");\n e.printStackTrace();\n }\n System.exit(res);\n }",
"private D createAndRegisterDeclaration(Map<String, Object> metadata) {\n D declaration;\n if (klass.equals(ImportDeclaration.class)) {\n declaration = (D) ImportDeclarationBuilder.fromMetadata(metadata).build();\n } else if (klass.equals(ExportDeclaration.class)) {\n declaration = (D) ExportDeclarationBuilder.fromMetadata(metadata).build();\n } else {\n throw new IllegalStateException(\"\");\n }\n declarationRegistrationManager.registerDeclaration(declaration);\n return declaration;\n }"
] |
Must be called before any other functions. Declares and sets up internal data structures.
@param numSamples Number of samples that will be processed.
@param sampleSize Number of elements in each sample. | [
"public void setup( int numSamples , int sampleSize ) {\n mean = new double[ sampleSize ];\n A.reshape(numSamples,sampleSize,false);\n sampleIndex = 0;\n numComponents = -1;\n }"
] | [
"public Authentication getAuthentication(String token) {\n\t\tif (null != token) {\n\t\t\tTokenContainer container = tokens.get(token);\n\t\t\tif (null != container) {\n\t\t\t\tif (container.isValid()) {\n\t\t\t\t\treturn container.getAuthentication();\n\t\t\t\t} else {\n\t\t\t\t\tlogout(token);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"@SuppressWarnings(\"WeakerAccess\")\n protected void clearRmiTargetsMap(ClassLoaderLeakPreventor preventor, Map<?, ?> rmiTargetsMap) {\n try {\n final Field cclField = preventor.findFieldOfClass(\"sun.rmi.transport.Target\", \"ccl\");\n preventor.debug(\"Looping \" + rmiTargetsMap.size() + \" RMI Targets to find leaks\");\n for(Iterator<?> iter = rmiTargetsMap.values().iterator(); iter.hasNext(); ) {\n Object target = iter.next(); // sun.rmi.transport.Target\n ClassLoader ccl = (ClassLoader) cclField.get(target);\n if(preventor.isClassLoaderOrChild(ccl)) {\n preventor.warn(\"Removing RMI Target: \" + target);\n iter.remove();\n }\n }\n }\n catch (Exception ex) {\n preventor.error(ex);\n }\n }",
"public static base_responses delete(nitro_service client, String selectorname[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (selectorname != null && selectorname.length > 0) {\n\t\t\tcacheselector deleteresources[] = new cacheselector[selectorname.length];\n\t\t\tfor (int i=0;i<selectorname.length;i++){\n\t\t\t\tdeleteresources[i] = new cacheselector();\n\t\t\t\tdeleteresources[i].selectorname = selectorname[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"public void setStructuredAppendMessageId(String messageId) {\r\n if (messageId != null && !messageId.matches(\"^[\\\\x21-\\\\x7F]+$\")) {\r\n throw new IllegalArgumentException(\"Invalid Aztec Code structured append message ID: \" + messageId);\r\n }\r\n this.structuredAppendMessageId = messageId;\r\n }",
"public BoxFile.Info getFileInfo(String fileID, String... fields) {\n String queryString = new QueryStringBuilder().appendParam(\"fields\", fields).toString();\n URL url = FILE_INFO_URL_TEMPLATE.buildWithQuery(this.api.getBaseURL(), queryString, fileID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n BoxFile file = new BoxFile(this.api, jsonObject.get(\"id\").asString());\n return file.new Info(response.getJSON());\n }",
"public Object invokeMethod(String name, Object args) {\n Object val = null;\n if (args != null && Object[].class.isAssignableFrom(args.getClass())) {\n Object[] arr = (Object[]) args;\n\n if (arr.length == 1) {\n val = arr[0];\n } else if (arr.length == 2 && arr[0] instanceof Collection && arr[1] instanceof Closure) {\n Closure<?> closure = (Closure<?>) arr[1];\n Iterator<?> iterator = ((Collection) arr[0]).iterator();\n List<Object> list = new ArrayList<Object>();\n while (iterator.hasNext()) {\n list.add(curryDelegateAndGetContent(closure, iterator.next()));\n }\n val = list;\n } else {\n val = Arrays.asList(arr);\n }\n }\n content.put(name, val);\n\n return val;\n }",
"@Override\n\tpublic void visit(Rule rule) {\n\t\tRule copy = null;\n\t\tFilter filterCopy = null;\n\n\t\tif (rule.getFilter() != null) {\n\t\t\tFilter filter = rule.getFilter();\n\t\t\tfilterCopy = copy(filter);\n\t\t}\n\n\t\tList<Symbolizer> symsCopy = new ArrayList<Symbolizer>();\n\t\tfor (Symbolizer sym : rule.symbolizers()) {\n\t\t\tif (!skipSymbolizer(sym)) {\n\t\t\t\tSymbolizer symCopy = copy(sym);\n\t\t\t\tsymsCopy.add(symCopy);\n\t\t\t}\n\t\t}\n\n\t\tGraphic[] legendCopy = rule.getLegendGraphic();\n\t\tfor (int i = 0; i < legendCopy.length; i++) {\n\t\t\tlegendCopy[i] = copy(legendCopy[i]);\n\t\t}\n\n\t\tDescription descCopy = rule.getDescription();\n\t\tdescCopy = copy(descCopy);\n\n\t\tcopy = sf.createRule();\n\t\tcopy.symbolizers().addAll(symsCopy);\n\t\tcopy.setDescription(descCopy);\n\t\tcopy.setLegendGraphic(legendCopy);\n\t\tcopy.setName(rule.getName());\n\t\tcopy.setFilter(filterCopy);\n\t\tcopy.setElseFilter(rule.isElseFilter());\n\t\tcopy.setMaxScaleDenominator(rule.getMaxScaleDenominator());\n\t\tcopy.setMinScaleDenominator(rule.getMinScaleDenominator());\n\n\t\tif (STRICT && !copy.equals(rule)) {\n\t\t\tthrow new IllegalStateException(\n\t\t\t\t\t\"Was unable to duplicate provided Rule:\" + rule);\n\t\t}\n\t\tpages.push(copy);\n\t}",
"public static boolean checkDuplicateElements(DMatrixSparseCSC A ) {\n A = A.copy(); // create a copy so that it doesn't modify A\n A.sortIndices(null);\n return !checkSortedFlag(A);\n }",
"@Override\n public final boolean has(final String key) {\n String result = this.obj.optString(key, null);\n return result != null;\n }"
] |
Gets the filename from a path or URL.
@param path or url.
@return the file name. | [
"public static String getFilename(String path) throws IllegalArgumentException {\n if (Pattern.matches(sPatternUrl, path))\n return getURLFilename(path);\n\n return new File(path).getName();\n }"
] | [
"public ParallelTask getTaskFromInProgressMap(String jobId) {\n if (!inprogressTaskMap.containsKey(jobId))\n return null;\n return inprogressTaskMap.get(jobId);\n }",
"protected AbstractColumn buildExpressionColumn() {\n\t\tExpressionColumn column = new ExpressionColumn();\n\t\tpopulateCommonAttributes(column);\n\t\t\n\t\tpopulateExpressionAttributes(column);\n\t\t\n\t\tcolumn.setExpression(customExpression);\n\t\tcolumn.setExpressionToGroupBy(customExpressionToGroupBy);\n\t\tcolumn.setExpressionForCalculation(customExpressionForCalculation);\n\t\t\n\t\treturn column;\n\t}",
"public void keyboardSupportEnabled(Activity activity, boolean enable) {\n if (getContent() != null && getContent().getChildCount() > 0) {\n if (mKeyboardUtil == null) {\n mKeyboardUtil = new KeyboardUtil(activity, getContent().getChildAt(0));\n mKeyboardUtil.disable();\n }\n\n if (enable) {\n mKeyboardUtil.enable();\n } else {\n mKeyboardUtil.disable();\n }\n }\n }",
"protected String sourceLineTrimmed(ASTNode node) {\r\n return sourceCode.line(AstUtil.findFirstNonAnnotationLine(node, sourceCode) - 1);\r\n }",
"protected void sendPageBreakToBottom(JRDesignBand band) {\n\t\tJRElement[] elems = band.getElements();\n\t\tJRElement aux = null;\n\t\tfor (JRElement elem : elems) {\n\t\t\tif ((\"\" + elem.getKey()).startsWith(PAGE_BREAK_FOR_)) {\n\t\t\t\taux = elem;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (aux != null)\n\t\t\t((JRDesignElement)aux).setY(band.getHeight());\n\t}",
"public List<MapRow> readTable(TableReader reader) throws IOException\n {\n reader.read();\n return reader.getRows();\n }",
"public void setIntVec(IntBuffer data)\n {\n if (data == null)\n {\n throw new IllegalArgumentException(\"Input buffer for indices cannot be null\");\n }\n if (getIndexSize() != 4)\n {\n throw new UnsupportedOperationException(\"Cannot update integer indices with short array\");\n }\n if (data.isDirect())\n {\n if (!NativeIndexBuffer.setIntVec(getNative(), data))\n {\n throw new UnsupportedOperationException(\"Input array is wrong size\");\n }\n }\n else if (data.hasArray())\n {\n if (!NativeIndexBuffer.setIntArray(getNative(), data.array()))\n {\n throw new IllegalArgumentException(\"Data array incompatible with index buffer\");\n }\n }\n else\n {\n throw new UnsupportedOperationException(\"IntBuffer type not supported. Must be direct or have backing array\");\n }\n }",
"public static base_response add(nitro_service client, clusterinstance resource) throws Exception {\n\t\tclusterinstance addresource = new clusterinstance();\n\t\taddresource.clid = resource.clid;\n\t\taddresource.deadinterval = resource.deadinterval;\n\t\taddresource.hellointerval = resource.hellointerval;\n\t\taddresource.preemption = resource.preemption;\n\t\treturn addresource.add_resource(client);\n\t}",
"@Override\n\tpublic void set(String headerName, String headerValue) {\n\t\tList<String> headerValues = new LinkedList<String>();\n\t\theaderValues.add(headerValue);\n\t\theaders.put(headerName, headerValues);\n\t}"
] |
Get all info for the specified photo.
The calling user must have permission to view the photo.
This method does not require authentication.
@param photoId
The photo Id
@param secret
The optional secret String
@return The Photo
@throws FlickrException | [
"public Photo getInfo(String photoId, String secret) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_INFO);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n if (secret != null) {\r\n parameters.put(\"secret\", secret);\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photoElement = response.getPayload();\r\n\r\n return PhotoUtils.createPhoto(photoElement);\r\n }"
] | [
"public void flush() throws IOException {\n if (unflushed.get() == 0) return;\n\n synchronized (lock) {\n if (logger.isTraceEnabled()) {\n logger.debug(\"Flushing log '\" + name + \"' last flushed: \" + getLastFlushedTime() + \" current time: \" + System\n .currentTimeMillis());\n }\n segments.getLastView().getMessageSet().flush();\n unflushed.set(0);\n lastflushedTime.set(System.currentTimeMillis());\n }\n }",
"public static base_response add(nitro_service client, dnsview resource) throws Exception {\n\t\tdnsview addresource = new dnsview();\n\t\taddresource.viewname = resource.viewname;\n\t\treturn addresource.add_resource(client);\n\t}",
"@Override\n public void close(SocketDestination destination) {\n factory.setLastClosedTimestamp(destination);\n queuedPool.reset(destination);\n }",
"public static base_responses update(nitro_service client, onlinkipv6prefix resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tonlinkipv6prefix updateresources[] = new onlinkipv6prefix[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new onlinkipv6prefix();\n\t\t\t\tupdateresources[i].ipv6prefix = resources[i].ipv6prefix;\n\t\t\t\tupdateresources[i].onlinkprefix = resources[i].onlinkprefix;\n\t\t\t\tupdateresources[i].autonomusprefix = resources[i].autonomusprefix;\n\t\t\t\tupdateresources[i].depricateprefix = resources[i].depricateprefix;\n\t\t\t\tupdateresources[i].decrementprefixlifetimes = resources[i].decrementprefixlifetimes;\n\t\t\t\tupdateresources[i].prefixvalidelifetime = resources[i].prefixvalidelifetime;\n\t\t\t\tupdateresources[i].prefixpreferredlifetime = resources[i].prefixpreferredlifetime;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"private static void attachToDecor(Activity activity, MenuDrawer menuDrawer) {\n ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView();\n ViewGroup decorChild = (ViewGroup) decorView.getChildAt(0);\n\n decorView.removeAllViews();\n decorView.addView(menuDrawer, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);\n\n menuDrawer.mContentContainer.addView(decorChild, decorChild.getLayoutParams());\n }",
"public ViewPort then(Functions.Func1<ViewPortChange> then, ViewPortFallback fallback) {\n assert then != null : \"'then' callback cannot be null\";\n this.then = then;\n this.fallback = fallback;\n return load();\n }",
"void notifyMwRevisionProcessors(MwRevision mwRevision, boolean isCurrent) {\n\t\tif (mwRevision == null || mwRevision.getPageId() <= 0) {\n\t\t\treturn;\n\t\t}\n\t\tfor (MwRevisionProcessorBroker.RevisionSubscription rs : this.revisionSubscriptions) {\n\t\t\tif (rs.onlyCurrentRevisions == isCurrent\n\t\t\t\t\t&& (rs.model == null || mwRevision.getModel().equals(\n\t\t\t\t\t\t\trs.model))) {\n\t\t\t\trs.mwRevisionProcessor.processRevision(mwRevision);\n\t\t\t}\n\t\t}\n\t}",
"public ExecutionChain setErrorCallback(ErrorCallback callback) {\n if (state.get() == State.RUNNING) {\n throw new IllegalStateException(\n \"Invalid while ExecutionChain is running\");\n }\n errorCallback = callback;\n return this;\n }",
"public void rename(String newName) {\n URL url = FOLDER_INFO_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"PUT\");\n\n JsonObject updateInfo = new JsonObject();\n updateInfo.add(\"name\", newName);\n\n request.setBody(updateInfo.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n response.getJSON();\n }"
] |
Sets the right padding character for all cells in the table.
@param paddingRightChar new padding character, ignored if null
@return this to allow chaining | [
"public AsciiTable setPaddingRightChar(Character paddingRightChar) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingRightChar(paddingRightChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}"
] | [
"private void addIndex(IndexDescriptorDef indexDescDef, TableDef tableDef)\r\n {\r\n IndexDef indexDef = tableDef.getIndex(indexDescDef.getName());\r\n\r\n if (indexDef == null)\r\n {\r\n indexDef = new IndexDef(indexDescDef.getName(),\r\n indexDescDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_UNIQUE, false));\r\n tableDef.addIndex(indexDef);\r\n }\r\n\r\n try\r\n {\r\n String fieldNames = indexDescDef.getProperty(PropertyHelper.OJB_PROPERTY_FIELDS);\r\n ArrayList fields = ((ClassDescriptorDef)indexDescDef.getOwner()).getFields(fieldNames);\r\n FieldDescriptorDef fieldDef;\r\n\r\n for (Iterator it = fields.iterator(); it.hasNext();)\r\n {\r\n fieldDef = (FieldDescriptorDef)it.next();\r\n indexDef.addColumn(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN));\r\n }\r\n }\r\n catch (NoSuchFieldException ex)\r\n {\r\n // won't happen if we already checked the constraints\r\n }\r\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 void main(String[] args) {\r\n TreebankLanguagePack tlp = new PennTreebankLanguagePack();\r\n System.out.println(\"Start symbol: \" + tlp.startSymbol());\r\n String start = tlp.startSymbol();\r\n System.out.println(\"Should be true: \" + (tlp.isStartSymbol(start)));\r\n String[] strs = {\"-\", \"-LLB-\", \"NP-2\", \"NP=3\", \"NP-LGS\", \"NP-TMP=3\"};\r\n for (String str : strs) {\r\n System.out.println(\"String: \" + str + \" basic: \" + tlp.basicCategory(str) + \" basicAndFunc: \" + tlp.categoryAndFunction(str));\r\n }\r\n }",
"private int getClosingParenthesisPosition(String text, int opening)\n {\n if (text.charAt(opening) != '(')\n {\n return -1;\n }\n\n int count = 0;\n for (int i = opening; i < text.length(); i++)\n {\n char c = text.charAt(i);\n switch (c)\n {\n case '(':\n {\n ++count;\n break;\n }\n\n case ')':\n {\n --count;\n if (count == 0)\n {\n return i;\n }\n break;\n }\n }\n }\n\n return -1;\n }",
"public void rememberAndDisableQuota() {\n for(Integer nodeId: nodeIds) {\n boolean quotaEnforcement = Boolean.parseBoolean(adminClient.metadataMgmtOps.getRemoteMetadata(nodeId,\n MetadataStore.QUOTA_ENFORCEMENT_ENABLED_KEY)\n .getValue());\n mapNodeToQuotaEnforcingEnabled.put(nodeId, quotaEnforcement);\n }\n adminClient.metadataMgmtOps.updateRemoteMetadata(nodeIds,\n MetadataStore.QUOTA_ENFORCEMENT_ENABLED_KEY,\n Boolean.toString(false));\n }",
"public synchronized void insert(long data) {\n resetIfNeeded();\n long index = 0;\n if(data >= this.upperBound) {\n index = nBuckets - 1;\n } else if(data < 0) {\n logger.error(data + \" can't be bucketed because it is negative!\");\n return;\n } else {\n index = data / step;\n }\n if(index < 0 || index >= nBuckets) {\n // This should be dead code. Defending against code changes in\n // future.\n logger.error(data + \" can't be bucketed because index is not in range [0,nBuckets).\");\n return;\n }\n buckets[(int) index]++;\n sum += data;\n size++;\n }",
"public boolean containsIteratorForTable(String aTable)\r\n {\r\n boolean result = false;\r\n\r\n if (m_rsIterators != null)\r\n {\r\n for (int i = 0; i < m_rsIterators.size(); i++)\r\n {\r\n OJBIterator it = (OJBIterator) m_rsIterators.get(i);\r\n if (it instanceof RsIterator)\r\n {\r\n if (((RsIterator) it).getClassDescriptor().getFullTableName().equals(aTable))\r\n {\r\n result = true;\r\n break;\r\n }\r\n }\r\n else if (it instanceof ChainingIterator)\r\n {\r\n result = ((ChainingIterator) it).containsIteratorForTable(aTable);\r\n }\r\n }\r\n }\r\n\r\n return result;\r\n }",
"public static Diagram parseJson(JSONObject json,\n Boolean keepGlossaryLink) throws JSONException {\n ArrayList<Shape> shapes = new ArrayList<Shape>();\n HashMap<String, JSONObject> flatJSON = flatRessources(json);\n for (String resourceId : flatJSON.keySet()) {\n parseRessource(shapes,\n flatJSON,\n resourceId,\n keepGlossaryLink);\n }\n String id = \"canvas\";\n\n if (json.has(\"resourceId\")) {\n id = json.getString(\"resourceId\");\n shapes.remove(new Shape(id));\n }\n ;\n Diagram diagram = new Diagram(id);\n\n // remove Diagram\n // (Diagram)getShapeWithId(json.getString(\"resourceId\"), shapes);\n parseStencilSet(json,\n diagram);\n parseSsextensions(json,\n diagram);\n parseStencil(json,\n diagram);\n parseProperties(json,\n diagram,\n keepGlossaryLink);\n parseChildShapes(shapes,\n json,\n diagram);\n parseBounds(json,\n diagram);\n diagram.setShapes(shapes);\n return diagram;\n }",
"public EndpointOverride getPath(int pathId, String clientUUID, String[] filters) throws Exception {\n EndpointOverride endpoint = null;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n String queryString = this.getPathSelectString();\n queryString += \" AND \" + Constants.DB_TABLE_PATH + \".\" + Constants.GENERIC_ID + \"=\" + pathId + \";\";\n statement = sqlConnection.prepareStatement(queryString);\n statement.setString(1, clientUUID);\n\n results = statement.executeQuery();\n\n if (results.next()) {\n endpoint = this.getEndpointOverrideFromResultSet(results);\n endpoint.setFilters(filters);\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return endpoint;\n }"
] |
Parse a parameterized object from an InputStream.
@param is The InputStream, most likely from your networking library.
@param jsonObjectType The ParameterizedType describing the object. Ex: LoganSquare.parse(is, new ParameterizedType<MyModel<OtherModel>>() { }); | [
"public static <E> E parse(InputStream is, ParameterizedType<E> jsonObjectType) throws IOException {\n return mapperFor(jsonObjectType).parse(is);\n }"
] | [
"private File getDisabledMarkerFile(long version) throws PersistenceFailureException {\n File[] versionDirArray = ReadOnlyUtils.getVersionDirs(rootDir, version, version);\n if (versionDirArray.length == 0) {\n throw new PersistenceFailureException(\"getDisabledMarkerFile did not find the requested version directory\" +\n \" on disk. Version: \" + version + \", rootDir: \" + rootDir);\n }\n File disabledMarkerFile = new File(versionDirArray[0], DISABLED_MARKER_NAME);\n return disabledMarkerFile;\n }",
"private void updateToNextWorkStart(Calendar cal)\n {\n Date originalDate = cal.getTime();\n\n //\n // Find the date ranges for the current day\n //\n ProjectCalendarDateRanges ranges = getRanges(originalDate, cal, null);\n\n if (ranges != null)\n {\n //\n // Do we have a start time today?\n //\n Date calTime = DateHelper.getCanonicalTime(cal.getTime());\n Date startTime = null;\n for (DateRange range : ranges)\n {\n Date rangeStart = DateHelper.getCanonicalTime(range.getStart());\n Date rangeEnd = DateHelper.getCanonicalTime(range.getEnd());\n Date rangeStartDay = DateHelper.getDayStartDate(range.getStart());\n Date rangeEndDay = DateHelper.getDayStartDate(range.getEnd());\n\n if (rangeStartDay.getTime() != rangeEndDay.getTime())\n {\n rangeEnd = DateHelper.addDays(rangeEnd, 1);\n }\n\n if (calTime.getTime() < rangeEnd.getTime())\n {\n if (calTime.getTime() > rangeStart.getTime())\n {\n startTime = calTime;\n }\n else\n {\n startTime = rangeStart;\n }\n break;\n }\n }\n\n //\n // If we don't have a start time today - find the next working day\n // then retrieve the start time.\n //\n if (startTime == null)\n {\n Day day;\n int nonWorkingDayCount = 0;\n do\n {\n cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR) + 1);\n day = Day.getInstance(cal.get(Calendar.DAY_OF_WEEK));\n ++nonWorkingDayCount;\n if (nonWorkingDayCount > MAX_NONWORKING_DAYS)\n {\n cal.setTime(originalDate);\n break;\n }\n }\n while (!isWorkingDate(cal.getTime(), day));\n\n startTime = getStartTime(cal.getTime());\n }\n\n DateHelper.setTime(cal, startTime);\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}",
"public void setLinearLowerLimits(float limitX, float limitY, float limitZ) {\n Native3DGenericConstraint.setLinearLowerLimits(getNative(), limitX, limitY, limitZ);\n }",
"@NonNull\n @UiThread\n private HashMap<Integer, Boolean> generateExpandedStateMap() {\n HashMap<Integer, Boolean> parentHashMap = new HashMap<>();\n int childCount = 0;\n\n int listItemCount = mFlatItemList.size();\n for (int i = 0; i < listItemCount; i++) {\n if (mFlatItemList.get(i) != null) {\n ExpandableWrapper<P, C> listItem = mFlatItemList.get(i);\n if (listItem.isParent()) {\n parentHashMap.put(i - childCount, listItem.isExpanded());\n } else {\n childCount++;\n }\n }\n }\n\n return parentHashMap;\n }",
"public boolean getBoolean(FastTrackField type)\n {\n boolean result = false;\n Object value = getObject(type);\n if (value != null)\n {\n result = BooleanHelper.getBoolean((Boolean) value);\n }\n return result;\n }",
"public Step createRootStep() {\n return new Step()\n .withName(\"Root step\")\n .withTitle(\"Allure step processing error: if you see this step something went wrong.\")\n .withStart(System.currentTimeMillis())\n .withStatus(Status.BROKEN);\n }",
"public CollectionRequest<Team> findByUser(String user) {\n \n String path = String.format(\"/users/%s/teams\", user);\n return new CollectionRequest<Team>(this, Team.class, path, \"GET\");\n }",
"public static boolean containsAtLeastOneNonBlank(List<String> list){\n\t\tfor(String str : list){\n\t\t\tif(StringUtils.isNotBlank(str)){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}"
] |
Returns the index of each elem in a List.
@param elems The list of items
@return An array of indices | [
"public int[] indices(Collection<E> elems) {\r\n int[] indices = new int[elems.size()];\r\n int i = 0;\r\n for (E elem : elems) {\r\n indices[i++] = indexOf(elem);\r\n }\r\n return indices;\r\n }"
] | [
"protected void appenHtmlFooter(StringBuffer buffer) {\n\n if (m_configuredFooter != null) {\n buffer.append(m_configuredFooter);\n } else {\n buffer.append(\" </body>\\r\\n\" + \"</html>\");\n }\n }",
"public static void unregisterMbean(MBeanServer server, ObjectName name) {\n try {\n server.unregisterMBean(name);\n } catch(Exception e) {\n logger.error(\"Error unregistering mbean\", e);\n }\n }",
"public static void checkDelegateType(Decorator<?> decorator) {\n\n Set<Type> types = new HierarchyDiscovery(decorator.getDelegateType()).getTypeClosure();\n\n for (Type decoratedType : decorator.getDecoratedTypes()) {\n if(!types.contains(decoratedType)) {\n throw BeanLogger.LOG.delegateMustSupportEveryDecoratedType(decoratedType, decorator);\n }\n }\n }",
"private void emit(float[] particlePositions, float[] particleVelocities,\n float[] particleTimeStamps)\n {\n float[] allParticlePositions = new float[particlePositions.length + particleBoundingVolume.length];\n System.arraycopy(particlePositions, 0, allParticlePositions, 0, particlePositions.length);\n System.arraycopy(particleBoundingVolume, 0, allParticlePositions,\n particlePositions.length, particleBoundingVolume.length);\n\n float[] allSpawnTimes = new float[particleTimeStamps.length + BVSpawnTimes.length];\n System.arraycopy(particleTimeStamps, 0, allSpawnTimes, 0, particleTimeStamps.length);\n System.arraycopy(BVSpawnTimes, 0, allSpawnTimes, particleTimeStamps.length, BVSpawnTimes.length);\n\n float[] allParticleVelocities = new float[particleVelocities.length + BVVelocities.length];\n System.arraycopy(particleVelocities, 0, allParticleVelocities, 0, particleVelocities.length);\n System.arraycopy(BVVelocities, 0, allParticleVelocities, particleVelocities.length, BVVelocities.length);\n\n\n Particles particleMesh = new Particles(mGVRContext, mMaxAge,\n mParticleSize, mEnvironmentAcceleration, mParticleSizeRate, mFadeWithAge,\n mParticleTexture, mColor, mNoiseFactor);\n\n\n GVRSceneObject particleObject = particleMesh.makeParticleMesh(allParticlePositions,\n allParticleVelocities, allSpawnTimes);\n\n this.addChildObject(particleObject);\n meshInfo.add(Pair.create(particleObject, currTime));\n }",
"public static boolean isKeyUsed(final Jedis jedis, final String key) {\n return !NONE.equalsIgnoreCase(jedis.type(key));\n }",
"public void addFile(File file) {\n String name = \"file\";\n files.put(normalizeDuplicateName(name), file);\n }",
"protected TokenList.Token parseSubmatrixToExtract(TokenList.Token variableTarget,\n TokenList tokens, Sequence sequence) {\n\n\n List<TokenList.Token> inputs = parseParameterCommaBlock(tokens, sequence);\n\n List<Variable> variables = new ArrayList<Variable>();\n\n // for the operation, the first variable must be the matrix which is being manipulated\n variables.add(variableTarget.getVariable());\n\n addSubMatrixVariables(inputs, variables);\n if( variables.size() != 2 && variables.size() != 3 ) {\n throw new ParseError(\"Unexpected number of variables. 1 or 2 expected\");\n }\n\n // first parameter is the matrix it will be extracted from. rest specify range\n Operation.Info info;\n\n // only one variable means its referencing elements\n // two variables means its referencing a sub matrix\n if( inputs.size() == 1 ) {\n Variable varA = variables.get(1);\n if( varA.getType() == VariableType.SCALAR ) {\n info = functions.create(\"extractScalar\", variables);\n } else {\n info = functions.create(\"extract\", variables);\n }\n } else if( inputs.size() == 2 ) {\n Variable varA = variables.get(1);\n Variable varB = variables.get(2);\n\n if( varA.getType() == VariableType.SCALAR && varB.getType() == VariableType.SCALAR) {\n info = functions.create(\"extractScalar\", variables);\n } else {\n info = functions.create(\"extract\", variables);\n }\n } else {\n throw new ParseError(\"Expected 2 inputs to sub-matrix\");\n }\n\n sequence.addOperation(info.op);\n\n return new TokenList.Token(info.output);\n }",
"public T reverse() {\n String id = getId();\n String REVERSE = \"_REVERSE\";\n if (id.endsWith(REVERSE)) {\n setId(id.substring(0, id.length() - REVERSE.length()));\n }\n\n float start = mStart;\n float end = mEnd;\n mStart = end;\n mEnd = start;\n mReverse = !mReverse;\n return self();\n }",
"public static IPAddressSeqRange[] join(IPAddressSeqRange... ranges) {\n\t\tint joinedCount = 0;\n\t\tArrays.sort(ranges, Address.ADDRESS_LOW_VALUE_COMPARATOR);\n\t\tfor(int i = 0; i < ranges.length; i++) {\n\t\t\tIPAddressSeqRange range = ranges[i];\n\t\t\tif(range == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor(int j = i + 1; j < ranges.length; j++) {\n\t\t\t\tIPAddressSeqRange range2 = ranges[j];\n\t\t\t\tif(range2 == null) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tIPAddress upper = range.getUpper();\n\t\t\t\tIPAddress lower = range2.getLower();\n\t\t\t\tif(compareLowValues(upper, lower) >= 0\n\t\t\t\t\t\t|| upper.increment(1).equals(lower)) {\n\t\t\t\t\t//join them\n\t\t\t\t\tranges[i] = range = range.create(range.getLower(), range2.getUpper());\n\t\t\t\t\tranges[j] = null;\n\t\t\t\t\tjoinedCount++;\n\t\t\t\t} else break;\n\t\t\t}\n\t\t}\n\t\tif(joinedCount == 0) {\n\t\t\treturn ranges;\n\t\t}\n\t\tIPAddressSeqRange joined[] = new IPAddressSeqRange[ranges.length - joinedCount];\n\t\tfor(int i = 0, j = 0; i < ranges.length; i++) {\n\t\t\tIPAddressSeqRange range = ranges[i];\n\t\t\tif(range == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tjoined[j++] = range;\n\t\t\tif(j >= joined.length) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn joined;\n\t}"
] |
Send a channels on-air update to all registered listeners.
@param audibleChannels holds the device numbers of all channels that can currently be heard in the mixer output | [
"private void deliverOnAirUpdate(Set<Integer> audibleChannels) {\n for (final OnAirListener listener : getOnAirListeners()) {\n try {\n listener.channelsOnAir(audibleChannels);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering channels on-air update to listener\", t);\n }\n }\n }"
] | [
"public static double[][] pseudoInverse(double[][] matrix){\n\t\tif(isSolverUseApacheCommonsMath) {\n\t\t\t// Use LU from common math\n\t\t\tSingularValueDecomposition svd = new SingularValueDecomposition(new Array2DRowRealMatrix(matrix));\n\t\t\tdouble[][] matrixInverse = svd.getSolver().getInverse().getData();\n\n\t\t\treturn matrixInverse;\n\t\t}\n\t\telse {\n\t\t\treturn org.jblas.Solve.pinv(new org.jblas.DoubleMatrix(matrix)).toArray2();\n\t\t}\n\t}",
"private ProjectFile readProjectFile(ProjectReader reader, InputStream stream) throws MPXJException\n {\n addListeners(reader);\n return reader.read(stream);\n }",
"public static int mixColors(float t, int rgb1, int rgb2) {\n\t\tint a1 = (rgb1 >> 24) & 0xff;\n\t\tint r1 = (rgb1 >> 16) & 0xff;\n\t\tint g1 = (rgb1 >> 8) & 0xff;\n\t\tint b1 = rgb1 & 0xff;\n\t\tint a2 = (rgb2 >> 24) & 0xff;\n\t\tint r2 = (rgb2 >> 16) & 0xff;\n\t\tint g2 = (rgb2 >> 8) & 0xff;\n\t\tint b2 = rgb2 & 0xff;\n\t\ta1 = lerp(t, a1, a2);\n\t\tr1 = lerp(t, r1, r2);\n\t\tg1 = lerp(t, g1, g2);\n\t\tb1 = lerp(t, b1, b2);\n\t\treturn (a1 << 24) | (r1 << 16) | (g1 << 8) | b1;\n\t}",
"private void processActivities(Storepoint phoenixProject)\n {\n final AlphanumComparator comparator = new AlphanumComparator();\n List<Activity> activities = phoenixProject.getActivities().getActivity();\n Collections.sort(activities, new Comparator<Activity>()\n {\n @Override public int compare(Activity o1, Activity o2)\n {\n Map<UUID, UUID> codes1 = getActivityCodes(o1);\n Map<UUID, UUID> codes2 = getActivityCodes(o2);\n for (UUID code : m_codeSequence)\n {\n UUID codeValue1 = codes1.get(code);\n UUID codeValue2 = codes2.get(code);\n\n if (codeValue1 == null || codeValue2 == null)\n {\n if (codeValue1 == null && codeValue2 == null)\n {\n continue;\n }\n\n if (codeValue1 == null)\n {\n return -1;\n }\n\n if (codeValue2 == null)\n {\n return 1;\n }\n }\n\n if (!codeValue1.equals(codeValue2))\n {\n Integer sequence1 = m_activityCodeSequence.get(codeValue1);\n Integer sequence2 = m_activityCodeSequence.get(codeValue2);\n\n return NumberHelper.compare(sequence1, sequence2);\n }\n }\n\n return comparator.compare(o1.getId(), o2.getId());\n }\n });\n\n for (Activity activity : activities)\n {\n processActivity(activity);\n }\n }",
"public Map<Double, SingleAssetEuropeanOptionProductDescriptor> getDescriptors(LocalDate referenceDate){\n\n\t\tint numberOfStrikes = strikes.length;\n\t\tHashMap<Double, SingleAssetEuropeanOptionProductDescriptor> descriptors = new HashMap<Double, SingleAssetEuropeanOptionProductDescriptor>();\n\n\t\tLocalDate maturityDate = FloatingpointDate.getDateFromFloatingPointDate(referenceDate, maturity);\n\t\tfor(int i = 0; i< numberOfStrikes; i++) {\n\t\t\tdescriptors.put(strikes[i], new SingleAssetEuropeanOptionProductDescriptor(underlyingName, maturityDate, strikes[i]));\n\t\t}\n\n\t\treturn descriptors;\n\t}",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<InternationalFixedDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<InternationalFixedDate>) super.zonedDateTime(temporal);\n }",
"public PhotoContext getContext(String photoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_CONTEXT);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n\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 PhotoContext photoContext = new PhotoContext();\r\n Collection<Element> payload = response.getPayloadCollection();\r\n for (Element payloadElement : payload) {\r\n String tagName = payloadElement.getTagName();\r\n if (tagName.equals(\"prevphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(payloadElement.getAttribute(\"id\"));\r\n photo.setSecret(payloadElement.getAttribute(\"secret\"));\r\n photo.setTitle(payloadElement.getAttribute(\"title\"));\r\n photo.setFarm(payloadElement.getAttribute(\"farm\"));\r\n photo.setUrl(payloadElement.getAttribute(\"url\"));\r\n photoContext.setPreviousPhoto(photo);\r\n } else if (tagName.equals(\"nextphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(payloadElement.getAttribute(\"id\"));\r\n photo.setSecret(payloadElement.getAttribute(\"secret\"));\r\n photo.setTitle(payloadElement.getAttribute(\"title\"));\r\n photo.setFarm(payloadElement.getAttribute(\"farm\"));\r\n photo.setUrl(payloadElement.getAttribute(\"url\"));\r\n photoContext.setNextPhoto(photo);\r\n }\r\n }\r\n return photoContext;\r\n }",
"@SuppressWarnings(\"unchecked\")\n public static void executeCommand(String[] args) throws IOException {\n\n OptionParser parser = getParser();\n\n // declare parameters\n String url = null;\n List<Integer> nodeIds = null;\n Boolean allNodes = true;\n Boolean confirm = false;\n\n // parse command-line input\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, AdminParserUtils.OPT_URL);\n AdminParserUtils.checkOptional(options,\n AdminParserUtils.OPT_NODE,\n AdminParserUtils.OPT_ALL_NODES);\n\n // load parameters\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 if(options.has(AdminParserUtils.OPT_CONFIRM)) {\n confirm = true;\n }\n\n // print summary\n System.out.println(\"Remove metadata related to rebalancing\");\n System.out.println(\"Location:\");\n System.out.println(\" bootstrap url = \" + url);\n if(allNodes) {\n System.out.println(\" node = all nodes\");\n } else {\n System.out.println(\" node = \" + Joiner.on(\", \").join(nodeIds));\n }\n\n // execute command\n if(!AdminToolUtils.askConfirm(confirm, \"remove metadata related to rebalancing\")) {\n return;\n }\n AdminClient adminClient = AdminToolUtils.getAdminClient(url);\n\n if(allNodes) {\n nodeIds = AdminToolUtils.getAllNodeIds(adminClient);\n }\n\n AdminToolUtils.assertServerNotInRebalancingState(adminClient, nodeIds);\n\n doMetaClearRebalance(adminClient, nodeIds);\n }",
"public static BufferedImage resizeToHeight(BufferedImage originalImage, int heightOut) {\n\n int width = originalImage.getWidth();\n\n int height = originalImage.getHeight();\n\n int heightPercent = (heightOut * 100) / height;\n\n int newWidth = (width * heightPercent) / 100;\n\n BufferedImage resizedImage =\n new BufferedImage(newWidth, heightOut, BufferedImage.TYPE_INT_ARGB);\n Graphics2D g = resizedImage.createGraphics();\n g.drawImage(originalImage, 0, 0, newWidth, heightOut, null);\n g.dispose();\n\n return resizedImage;\n }"
] |
Returns the most likely class for the word at the given position. | [
"protected String classOf(List<IN> lineInfos, int pos) {\r\n Datum<String, String> d = makeDatum(lineInfos, pos, featureFactory);\r\n return classifier.classOf(d);\r\n }"
] | [
"private List<CmsResource> getDetailContainerResources(CmsObject cms, CmsResource res) throws CmsException {\n\n CmsRelationFilter filter = CmsRelationFilter.relationsFromStructureId(res.getStructureId()).filterType(\n CmsRelationType.DETAIL_ONLY);\n List<CmsResource> result = Lists.newArrayList();\n List<CmsRelation> relations = cms.readRelations(filter);\n for (CmsRelation relation : relations) {\n try {\n result.add(relation.getTarget(cms, CmsResourceFilter.ALL));\n } catch (Exception e) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n }\n return result;\n }",
"public void copyTo(int srcOffset, byte[] destArray, int destOffset, int size) {\n int cursor = destOffset;\n for (ByteBuffer bb : toDirectByteBuffers(srcOffset, size)) {\n int bbSize = bb.remaining();\n if ((cursor + bbSize) > destArray.length)\n throw new ArrayIndexOutOfBoundsException(String.format(\"cursor + bbSize = %,d\", cursor + bbSize));\n bb.get(destArray, cursor, bbSize);\n cursor += bbSize;\n }\n }",
"public void bindDelete(PreparedStatement stmt, ClassDescriptor cld, Object obj) throws SQLException\r\n {\r\n if (cld.getDeleteProcedure() != null)\r\n {\r\n this.bindProcedure(stmt, cld, obj, cld.getDeleteProcedure());\r\n }\r\n else\r\n {\r\n int index = 1;\r\n ValueContainer[] values, currentLockingValues;\r\n\r\n currentLockingValues = cld.getCurrentLockingValues(obj);\r\n // parameters for WHERE-clause pk\r\n values = getKeyValues(m_broker, cld, obj);\r\n for (int i = 0; i < values.length; i++)\r\n {\r\n setObjectForStatement(stmt, index, values[i].getValue(), values[i].getJdbcType().getType());\r\n index++;\r\n }\r\n\r\n // parameters for WHERE-clause locking\r\n values = currentLockingValues;\r\n for (int i = 0; i < values.length; i++)\r\n {\r\n setObjectForStatement(stmt, index, values[i].getValue(), values[i].getJdbcType().getType());\r\n index++;\r\n }\r\n }\r\n }",
"void processDumpFile(MwDumpFile dumpFile,\n\t\t\tMwDumpFileProcessor dumpFileProcessor) {\n\t\ttry (InputStream inputStream = dumpFile.getDumpFileStream()) {\n\t\t\tdumpFileProcessor.processDumpFileContents(inputStream, dumpFile);\n\t\t} catch (FileAlreadyExistsException e) {\n\t\t\tlogger.error(\"Dump file \"\n\t\t\t\t\t+ dumpFile.toString()\n\t\t\t\t\t+ \" could not be processed since file \"\n\t\t\t\t\t+ e.getFile()\n\t\t\t\t\t+ \" already exists. Try deleting the file or dumpfile directory to attempt a new download.\");\n\t\t} catch (IOException e) {\n\t\t\tlogger.error(\"Dump file \" + dumpFile.toString()\n\t\t\t\t\t+ \" could not be processed: \" + e.toString());\n\t\t}\n\t}",
"private static void listResourceNotes(ProjectFile file)\n {\n for (Resource resource : file.getResources())\n {\n String notes = resource.getNotes();\n\n if (notes.length() != 0)\n {\n System.out.println(\"Notes for \" + resource.getName() + \": \" + notes);\n }\n }\n\n System.out.println();\n }",
"public static boolean isKeyUsed(final Jedis jedis, final String key) {\n return !NONE.equalsIgnoreCase(jedis.type(key));\n }",
"protected String getPayload(Message message) {\n try {\n String encoding = (String) message.get(Message.ENCODING);\n if (encoding == null) {\n encoding = \"UTF-8\";\n }\n CachedOutputStream cos = message.getContent(CachedOutputStream.class);\n if (cos == null) {\n LOG.warning(\"Could not find CachedOutputStream in message.\"\n + \" Continuing without message content\");\n return \"\";\n }\n return new String(cos.getBytes(), encoding);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }",
"public @Nullable String build() {\n StringBuilder queryString = new StringBuilder();\n\n for (NameValuePair param : params) {\n if (queryString.length() > 0) {\n queryString.append(PARAM_SEPARATOR);\n }\n queryString.append(Escape.urlEncode(param.getName()));\n queryString.append(VALUE_SEPARATOR);\n queryString.append(Escape.urlEncode(param.getValue()));\n }\n\n if (queryString.length() > 0) {\n return queryString.toString();\n }\n else {\n return null;\n }\n }",
"public void start(GVRAccessibilitySpeechListener speechListener) {\n mTts.setSpeechListener(speechListener);\n mTts.getSpeechRecognizer().startListening(mTts.getSpeechRecognizerIntent());\n }"
] |
Append Join for SQL92 Syntax | [
"private void appendJoinSQL92(Join join, StringBuffer where, StringBuffer buf)\r\n {\r\n if (join.isOuter)\r\n {\r\n buf.append(\" LEFT OUTER JOIN \");\r\n }\r\n else\r\n {\r\n buf.append(\" INNER JOIN \");\r\n }\r\n if (join.right.hasJoins())\r\n {\r\n buf.append(\"(\");\r\n appendTableWithJoins(join.right, where, buf);\r\n buf.append(\")\");\r\n }\r\n else\r\n {\r\n appendTableWithJoins(join.right, where, buf);\r\n }\r\n buf.append(\" ON \");\r\n join.appendJoinEqualities(buf);\r\n }"
] | [
"public Class<? extends MonetaryAmount> getAmountType() {\n Class<?> clazz = get(AMOUNT_TYPE, Class.class);\n return clazz.asSubclass(MonetaryAmount.class);\n }",
"public void run(Configuration configuration, List<CandidateSteps> candidateSteps, Story story, MetaFilter filter,\n State beforeStories) throws Throwable {\n run(configuration, new ProvidedStepsFactory(candidateSteps), story, filter, beforeStories);\n }",
"InputStream openContentStream(final ContentItem item) throws IOException {\n final File file = getFile(item);\n if (file == null) {\n throw new IllegalStateException();\n }\n return new FileInputStream(file);\n }",
"public V get(final K1 firstKey, final K2 secondKey) {\n\t\t// existence check on inner map\n\t\tfinal HashMap<K2, V> innerMap = map.get(firstKey);\n\t\tif( innerMap == null ) {\n\t\t\treturn null;\n\t\t}\n\t\treturn innerMap.get(secondKey);\n\t}",
"public static String getChildValue(Element element, String name) {\r\n return getValue(getChild(element, name));\r\n }",
"protected String colorString(PDColor pdcolor)\n {\n String color = null;\n try\n {\n float[] rgb = pdcolor.getColorSpace().toRGB(pdcolor.getComponents());\n color = colorString(rgb[0], rgb[1], rgb[2]);\n } catch (IOException e) {\n log.error(\"colorString: IOException: {}\", e.getMessage());\n } catch (UnsupportedOperationException e) {\n log.error(\"colorString: UnsupportedOperationException: {}\", e.getMessage());\n }\n return color;\n }",
"public static cmppolicy_stats[] get(nitro_service service) throws Exception{\n\t\tcmppolicy_stats obj = new cmppolicy_stats();\n\t\tcmppolicy_stats[] response = (cmppolicy_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}",
"@SuppressWarnings(\"unchecked\")\n public T[] nextPermutationAsArray()\n {\n T[] permutation = (T[]) Array.newInstance(elements.getClass().getComponentType(),\n permutationIndices.length);\n return nextPermutationAsArray(permutation);\n }",
"private Duration convertFormat(long totalTime, TimeUnit format)\n {\n double duration = totalTime;\n\n switch (format)\n {\n case MINUTES:\n case ELAPSED_MINUTES:\n {\n duration /= (60 * 1000);\n break;\n }\n\n case HOURS:\n case ELAPSED_HOURS:\n {\n duration /= (60 * 60 * 1000);\n break;\n }\n\n case DAYS:\n {\n double minutesPerDay = getMinutesPerDay();\n if (minutesPerDay != 0)\n {\n duration /= (minutesPerDay * 60 * 1000);\n }\n else\n {\n duration = 0;\n }\n break;\n }\n\n case WEEKS:\n {\n double minutesPerWeek = getMinutesPerWeek();\n if (minutesPerWeek != 0)\n {\n duration /= (minutesPerWeek * 60 * 1000);\n }\n else\n {\n duration = 0;\n }\n break;\n }\n\n case MONTHS:\n {\n double daysPerMonth = getParentFile().getProjectProperties().getDaysPerMonth().doubleValue();\n double minutesPerDay = getMinutesPerDay();\n if (daysPerMonth != 0 && minutesPerDay != 0)\n {\n duration /= (daysPerMonth * minutesPerDay * 60 * 1000);\n }\n else\n {\n duration = 0;\n }\n break;\n }\n\n case ELAPSED_DAYS:\n {\n duration /= (24 * 60 * 60 * 1000);\n break;\n }\n\n case ELAPSED_WEEKS:\n {\n duration /= (7 * 24 * 60 * 60 * 1000);\n break;\n }\n\n case ELAPSED_MONTHS:\n {\n duration /= (30 * 24 * 60 * 60 * 1000);\n break;\n }\n\n default:\n {\n throw new IllegalArgumentException(\"TimeUnit \" + format + \" not supported\");\n }\n }\n\n return (Duration.getInstance(duration, format));\n }"
] |
Use this API to fetch all the filterhtmlinjectionparameter resources that are configured on netscaler. | [
"public static filterhtmlinjectionparameter get(nitro_service service, options option) throws Exception{\n\t\tfilterhtmlinjectionparameter obj = new filterhtmlinjectionparameter();\n\t\tfilterhtmlinjectionparameter[] response = (filterhtmlinjectionparameter[])obj.get_resources(service,option);\n\t\treturn response[0];\n\t}"
] | [
"public static sslcipher[] get(nitro_service service) throws Exception{\n\t\tsslcipher obj = new sslcipher();\n\t\tsslcipher[] response = (sslcipher[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static String getHeaders(HttpMethod method) {\n String headerString = \"\";\n Header[] headers = method.getRequestHeaders();\n for (Header header : headers) {\n String name = header.getName();\n if (name.equals(Constants.ODO_PROXY_HEADER)) {\n // skip.. don't want to log this\n continue;\n }\n\n if (headerString.length() != 0) {\n headerString += \"\\n\";\n }\n\n headerString += header.getName() + \": \" + header.getValue();\n }\n\n return headerString;\n }",
"protected void parseNegOp(TokenList tokens, Sequence sequence) {\n if( tokens.size == 0 )\n return;\n\n TokenList.Token token = tokens.first;\n\n while( token != null ) {\n TokenList.Token next = token.next;\n escape:\n if( token.getSymbol() == Symbol.MINUS ) {\n if( token.previous != null && token.previous.getType() != Type.SYMBOL)\n break escape;\n if( token.previous != null && token.previous.getType() == Type.SYMBOL &&\n (token.previous.symbol == Symbol.TRANSPOSE))\n break escape;\n if( token.next == null || token.next.getType() == Type.SYMBOL)\n break escape;\n\n if( token.next.getType() != Type.VARIABLE )\n throw new RuntimeException(\"Crap bug rethink this function\");\n\n // create the operation\n Operation.Info info = Operation.neg(token.next.getVariable(),functions.getManagerTemp());\n // add the operation to the sequence\n sequence.addOperation(info.op);\n // update the token list\n TokenList.Token t = new TokenList.Token(info.output);\n tokens.insert(token.next,t);\n tokens.remove(token.next);\n tokens.remove(token);\n next = t;\n }\n token = next;\n }\n }",
"public static boolean updatingIndexNecessesary(CmsObject cms) {\n\n // Set request to the offline project.\n setCmsOfflineProject(cms);\n\n // Check whether the spellcheck index directories are empty.\n // If they are, the index has to be built obviously.\n if (isSolrSpellcheckIndexDirectoryEmpty()) {\n return true;\n }\n\n // Compare the most recent date of a dictionary with the oldest timestamp\n // that determines when an index has been built.\n long dateMostRecentDictionary = getMostRecentDate(cms);\n long dateOldestIndexWrite = getOldestIndexDate(cms);\n\n return dateMostRecentDictionary > dateOldestIndexWrite;\n }",
"public void parseAndAddDictionaries(CmsObject cms) throws CmsRoleViolationException {\n\n OpenCms.getRoleManager().checkRole(cms, CmsRole.ROOT_ADMIN);\n CmsSpellcheckDictionaryIndexer.parseAndAddZippedDictionaries(m_solrClient, cms);\n CmsSpellcheckDictionaryIndexer.parseAndAddDictionaries(m_solrClient, cms);\n }",
"public Weld extensions(Extension... extensions) {\n this.extensions.clear();\n for (Extension extension : extensions) {\n addExtension(extension);\n }\n return this;\n }",
"public static TransactionalProtocolClient createClient(final ManagementChannelHandler channelAssociation) {\n final TransactionalProtocolClientImpl client = new TransactionalProtocolClientImpl(channelAssociation);\n channelAssociation.addHandlerFactory(client);\n return client;\n }",
"public static int cudnnSetTensor4dDescriptorEx(\n cudnnTensorDescriptor tensorDesc, \n int dataType, /** image data type */\n int n, /** number of inputs (batch size) */\n int c, /** number of input feature maps */\n int h, /** height of input section */\n int w, /** width of input section */\n int nStride, \n int cStride, \n int hStride, \n int wStride)\n {\n return checkResult(cudnnSetTensor4dDescriptorExNative(tensorDesc, dataType, n, c, h, w, nStride, cStride, hStride, wStride));\n }",
"public List<NodeValue<K, V>> getRepairs(List<NodeValue<K, V>> nodeValues) {\n int size = nodeValues.size();\n if(size <= 1)\n return Collections.emptyList();\n\n Map<K, List<NodeValue<K, V>>> keyToNodeValues = Maps.newHashMap();\n for(NodeValue<K, V> nodeValue: nodeValues) {\n List<NodeValue<K, V>> keyNodeValues = keyToNodeValues.get(nodeValue.getKey());\n if(keyNodeValues == null) {\n keyNodeValues = Lists.newArrayListWithCapacity(5);\n keyToNodeValues.put(nodeValue.getKey(), keyNodeValues);\n }\n keyNodeValues.add(nodeValue);\n }\n\n List<NodeValue<K, V>> result = Lists.newArrayList();\n for(List<NodeValue<K, V>> keyNodeValues: keyToNodeValues.values())\n result.addAll(singleKeyGetRepairs(keyNodeValues));\n return result;\n }"
] |
Infer app name from entry class
@param entryClass
the entry class
@return
app name inferred from the entry class | [
"static String from(Class<?> entryClass) {\n List<String> tokens = tokenOf(entryClass);\n return fromTokens(tokens);\n }"
] | [
"private RandomVariable getShortRate(int timeIndex) throws CalculationException {\n\t\tdouble time = getProcess().getTime(timeIndex);\n\t\tdouble timePrev = timeIndex > 0 ? getProcess().getTime(timeIndex-1) : time;\n\t\tdouble timeNext = getProcess().getTime(timeIndex+1);\n\n\t\tRandomVariable zeroRate = getZeroRateFromForwardCurve(time); //getDiscountFactorFromForwardCurve(time).div(getDiscountFactorFromForwardCurve(timeNext)).log().div(timeNext-time);\n\n\t\tRandomVariable alpha = getDV(0, time);\n\n\t\tRandomVariable value = getProcess().getProcessValue(timeIndex, 0);\n\t\tvalue = value.add(alpha);\n\t\t//\t\tvalue = value.sub(Math.log(value.exp().getAverage()));\n\n\t\tvalue = value.add(zeroRate);\n\n\t\treturn value;\n\t}",
"public void invalidate() {\n synchronized (mMeasuredChildren) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"invalidate all [%d]\", mMeasuredChildren.size());\n mMeasuredChildren.clear();\n }\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 }",
"public static authenticationlocalpolicy_authenticationvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationlocalpolicy_authenticationvserver_binding obj = new authenticationlocalpolicy_authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationlocalpolicy_authenticationvserver_binding response[] = (authenticationlocalpolicy_authenticationvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public Object getBean(String name) {\n\t\tBean bean = beans.get(name);\n\t\tif (null == bean) {\n\t\t\treturn null;\n\t\t}\n\t\treturn bean.object;\n\t}",
"private void readTasks(Project phoenixProject, Storepoint storepoint)\n {\n processLayouts(phoenixProject);\n processActivityCodes(storepoint);\n processActivities(storepoint);\n updateDates();\n }",
"OTMConnection getConnection()\r\n {\r\n if (m_connection == null)\r\n {\r\n OTMConnectionRuntimeException ex = new OTMConnectionRuntimeException(\"Connection is null.\");\r\n sendEvents(ConnectionEvent.CONNECTION_ERROR_OCCURRED, ex, null);\r\n }\r\n return m_connection;\r\n }",
"protected TokenList.Token parseSubmatrixToExtract(TokenList.Token variableTarget,\n TokenList tokens, Sequence sequence) {\n\n\n List<TokenList.Token> inputs = parseParameterCommaBlock(tokens, sequence);\n\n List<Variable> variables = new ArrayList<Variable>();\n\n // for the operation, the first variable must be the matrix which is being manipulated\n variables.add(variableTarget.getVariable());\n\n addSubMatrixVariables(inputs, variables);\n if( variables.size() != 2 && variables.size() != 3 ) {\n throw new ParseError(\"Unexpected number of variables. 1 or 2 expected\");\n }\n\n // first parameter is the matrix it will be extracted from. rest specify range\n Operation.Info info;\n\n // only one variable means its referencing elements\n // two variables means its referencing a sub matrix\n if( inputs.size() == 1 ) {\n Variable varA = variables.get(1);\n if( varA.getType() == VariableType.SCALAR ) {\n info = functions.create(\"extractScalar\", variables);\n } else {\n info = functions.create(\"extract\", variables);\n }\n } else if( inputs.size() == 2 ) {\n Variable varA = variables.get(1);\n Variable varB = variables.get(2);\n\n if( varA.getType() == VariableType.SCALAR && varB.getType() == VariableType.SCALAR) {\n info = functions.create(\"extractScalar\", variables);\n } else {\n info = functions.create(\"extract\", variables);\n }\n } else {\n throw new ParseError(\"Expected 2 inputs to sub-matrix\");\n }\n\n sequence.addOperation(info.op);\n\n return new TokenList.Token(info.output);\n }",
"public static route6[] get(nitro_service service, route6_args args) throws Exception{\n\t\troute6 obj = new route6();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\troute6[] response = (route6[])obj.get_resources(service, option);\n\t\treturn response;\n\t}"
] |
Read activities. | [
"private void readActivities()\n {\n List<MapRow> items = new ArrayList<MapRow>();\n for (MapRow row : m_tables.get(\"ACT\"))\n {\n items.add(row);\n }\n final AlphanumComparator comparator = new AlphanumComparator();\n Collections.sort(items, new Comparator<MapRow>()\n {\n @Override public int compare(MapRow o1, MapRow o2)\n {\n return comparator.compare(o1.getString(\"ACTIVITY_ID\"), o2.getString(\"ACTIVITY_ID\"));\n }\n });\n\n for (MapRow row : items)\n {\n String activityID = row.getString(\"ACTIVITY_ID\");\n\n String wbs;\n if (m_wbsFormat == null)\n {\n wbs = null;\n }\n else\n {\n m_wbsFormat.parseRawValue(row.getString(\"WBS\"));\n wbs = m_wbsFormat.getFormattedValue();\n }\n\n ChildTaskContainer parent = m_wbsMap.get(wbs);\n if (parent == null)\n {\n parent = m_projectFile;\n }\n\n Task task = parent.addTask();\n setFields(TASK_FIELDS, row, task);\n task.setStart(task.getEarlyStart());\n task.setFinish(task.getEarlyFinish());\n task.setMilestone(task.getDuration().getDuration() == 0);\n task.setWBS(wbs);\n Duration duration = task.getDuration();\n Duration remainingDuration = task.getRemainingDuration();\n task.setActualDuration(Duration.getInstance(duration.getDuration() - remainingDuration.getDuration(), TimeUnit.HOURS));\n m_activityMap.put(activityID, task);\n }\n }"
] | [
"private static <D, T> D createDaoFromConfig(ConnectionSource connectionSource, Class<T> clazz) throws SQLException {\n\t\t// no loaded configs\n\t\tif (configMap == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tDatabaseTableConfig<T> config = (DatabaseTableConfig<T>) configMap.get(clazz);\n\t\t// if we don't config information cached return null\n\t\tif (config == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// else create a DAO using configuration\n\t\tDao<T, ?> configedDao = doCreateDao(connectionSource, config);\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tD castDao = (D) configedDao;\n\t\treturn castDao;\n\t}",
"public static gslbservice get(nitro_service service, String servicename) throws Exception{\n\t\tgslbservice obj = new gslbservice();\n\t\tobj.set_servicename(servicename);\n\t\tgslbservice response = (gslbservice) obj.get_resource(service);\n\t\treturn response;\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}",
"private void processCalendarData(List<ProjectCalendar> calendars) throws SQLException\n {\n for (ProjectCalendar calendar : calendars)\n {\n processCalendarData(calendar, getRows(\"SELECT * FROM MSP_CALENDAR_DATA WHERE PROJ_ID=? AND CAL_UID=?\", m_projectID, calendar.getUniqueID()));\n }\n }",
"public Metadata createMetadata(String templateName, String scope, Metadata metadata) {\n URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), scope, templateName);\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"POST\");\n request.addHeader(\"Content-Type\", \"application/json\");\n request.setBody(metadata.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n return new Metadata(JsonObject.readFrom(response.getJSON()));\n }",
"void unbind(String key)\r\n {\r\n NamedEntry entry = new NamedEntry(key, null, false);\r\n localUnbind(key);\r\n addForDeletion(entry);\r\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 String getNotes()\n {\n String notes = (String) getCachedValue(ResourceField.NOTES);\n return (notes == null ? \"\" : notes);\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}"
] |
Map a single ResultSet row to a T instance.
@throws SQLException | [
"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 SelectStatement getPreparedSelectByPkStatement(ClassDescriptor cld)\r\n {\r\n SelectStatement sql;\r\n SqlForClass sfc = getSqlForClass(cld);\r\n sql = sfc.getSelectByPKSql();\r\n if(sql == null)\r\n {\r\n sql = new SqlSelectByPkStatement(m_platform, cld, logger);\r\n\r\n // set the sql string\r\n sfc.setSelectByPKSql(sql);\r\n\r\n if(logger.isDebugEnabled())\r\n {\r\n logger.debug(\"SQL:\" + sql.getStatement());\r\n }\r\n }\r\n return sql;\r\n }",
"public static base_response update(nitro_service client, nsrpcnode resource) throws Exception {\n\t\tnsrpcnode updateresource = new nsrpcnode();\n\t\tupdateresource.ipaddress = resource.ipaddress;\n\t\tupdateresource.password = resource.password;\n\t\tupdateresource.srcip = resource.srcip;\n\t\tupdateresource.secure = resource.secure;\n\t\treturn updateresource.update_resource(client);\n\t}",
"protected void recordPreparedOperation(final ServerIdentity identity, final TransactionalProtocolClient.PreparedOperation<ServerTaskExecutor.ServerOperation> prepared) {\n final ModelNode preparedResult = prepared.getPreparedResult();\n // Hmm do the server results need to get translated as well as the host one?\n // final ModelNode transformedResult = prepared.getOperation().transformResult(preparedResult);\n updatePolicy.recordServerResult(identity, preparedResult);\n executor.recordPreparedOperation(prepared);\n }",
"public void addRequiredBundles(Set<String> bundles) {\n\t\t// TODO manage transitive dependencies\n\t\t// don't require self\n\t\tSet<String> bundlesToMerge;\n\t\tString bundleName = (String) getMainAttributes().get(BUNDLE_SYMBOLIC_NAME);\n\t\tif (bundleName != null) {\n\t\t\tint idx = bundleName.indexOf(';');\n\t\t\tif (idx >= 0) {\n\t\t\t\tbundleName = bundleName.substring(0, idx);\n\t\t\t}\n\t\t}\n\t\tif (bundleName != null && bundles.contains(bundleName)\n\t\t\t\t|| projectName != null && bundles.contains(projectName)) {\n\t\t\tbundlesToMerge = new LinkedHashSet<String>(bundles);\n\t\t\tbundlesToMerge.remove(bundleName);\n\t\t\tbundlesToMerge.remove(projectName);\n\t\t} else {\n\t\t\tbundlesToMerge = bundles;\n\t\t}\n\t\tString s = (String) getMainAttributes().get(REQUIRE_BUNDLE);\n\t\tWrapper<Boolean> modified = Wrapper.wrap(this.modified);\n\t\tString result = mergeIntoCommaSeparatedList(s, bundlesToMerge, modified, lineDelimiter);\n\t\tthis.modified = modified.get();\n\t\tgetMainAttributes().put(REQUIRE_BUNDLE, result);\n\t}",
"public void setHtmlElementTranslator(HtmlElementTranslator htmlElementTranslator) {\r\n\t\tif(htmlElementTranslator!=null){\r\n\t\t\tthis.htmlElementTranslator = htmlElementTranslator;\r\n\t\t\tthis.charTranslator = null;\r\n\t\t\tthis.targetTranslator = null;\r\n\t\t}\r\n\t}",
"public Set<ConstraintViolation> validate(DataSetInfo info) {\r\n\t\tSet<ConstraintViolation> errors = new LinkedHashSet<ConstraintViolation>();\r\n\t\ttry {\r\n\t\t\tif (info.isMandatory() && get(info.getDataSetNumber()) == null) {\r\n\t\t\t\terrors.add(new ConstraintViolation(info, ConstraintViolation.MANDATORY_MISSING));\r\n\t\t\t}\r\n\t\t\tif (!info.isRepeatable() && getAll(info.getDataSetNumber()).size() > 1) {\r\n\t\t\t\terrors.add(new ConstraintViolation(info, ConstraintViolation.REPEATABLE_REPEATED));\r\n\t\t\t}\r\n\t\t} catch (SerializationException e) {\r\n\t\t\terrors.add(new ConstraintViolation(info, ConstraintViolation.INVALID_VALUE));\r\n\t\t}\r\n\t\treturn errors;\r\n\t}",
"public void unbind(T service, Map<String, Object> props) {\n synchronized (serviceMap) {\n serviceMap.remove(ServiceUtil.getComparableForServiceRanking(props));\n updateSortedServices();\n }\n }",
"public static <T> void filterListToMap(final Map<String, T> destinationMap, final String[] nameMapping,\n\t\tfinal List<? extends T> sourceList) {\n\t\tif( destinationMap == null ) {\n\t\t\tthrow new NullPointerException(\"destinationMap should not be null\");\n\t\t} else if( nameMapping == null ) {\n\t\t\tthrow new NullPointerException(\"nameMapping should not be null\");\n\t\t} else if( sourceList == null ) {\n\t\t\tthrow new NullPointerException(\"sourceList should not be null\");\n\t\t} else if( nameMapping.length != sourceList.size() ) {\n\t\t\tthrow new SuperCsvException(\n\t\t\t\tString\n\t\t\t\t\t.format(\n\t\t\t\t\t\t\"the nameMapping array and the sourceList should be the same size (nameMapping length = %d, sourceList size = %d)\",\n\t\t\t\t\t\tnameMapping.length, sourceList.size()));\n\t\t}\n\t\t\n\t\tdestinationMap.clear();\n\t\t\n\t\tfor( int i = 0; i < nameMapping.length; i++ ) {\n\t\t\tfinal String key = nameMapping[i];\n\t\t\t\n\t\t\tif( key == null ) {\n\t\t\t\tcontinue; // null's in the name mapping means skip column\n\t\t\t}\n\t\t\t\n\t\t\t// no duplicates allowed\n\t\t\tif( destinationMap.containsKey(key) ) {\n\t\t\t\tthrow new SuperCsvException(String.format(\"duplicate nameMapping '%s' at index %d\", key, i));\n\t\t\t}\n\t\t\t\n\t\t\tdestinationMap.put(key, sourceList.get(i));\n\t\t}\n\t}",
"@Override\n public ArtifactoryResponse restCall(ArtifactoryRequest artifactoryRequest) throws IOException {\n HttpRequestBase httpRequest;\n\n String requestPath = \"/\" + artifactoryRequest.getApiUrl();\n ContentType contentType = Util.getContentType(artifactoryRequest.getRequestType());\n\n String queryPath = \"\";\n if (!artifactoryRequest.getQueryParams().isEmpty()) {\n queryPath = Util.getQueryPath(\"?\", artifactoryRequest.getQueryParams());\n }\n\n switch (artifactoryRequest.getMethod()) {\n case GET:\n httpRequest = new HttpGet();\n\n break;\n\n case POST:\n httpRequest = new HttpPost();\n setEntity((HttpPost)httpRequest, artifactoryRequest.getBody(), contentType);\n\n break;\n\n case PUT:\n httpRequest = new HttpPut();\n setEntity((HttpPut)httpRequest, artifactoryRequest.getBody(), contentType);\n\n break;\n\n case DELETE:\n httpRequest = new HttpDelete();\n\n break;\n\n case PATCH:\n httpRequest = new HttpPatch();\n setEntity((HttpPatch)httpRequest, artifactoryRequest.getBody(), contentType);\n break;\n\n case OPTIONS:\n httpRequest = new HttpOptions();\n break;\n\n default:\n throw new IllegalArgumentException(\"Unsupported request method.\");\n }\n\n httpRequest.setURI(URI.create(url + requestPath + queryPath));\n addAccessTokenHeaderIfNeeded(httpRequest);\n\n if (contentType != null) {\n httpRequest.setHeader(\"Content-type\", contentType.getMimeType());\n }\n\n Map<String, String> headers = artifactoryRequest.getHeaders();\n for (String key : headers.keySet()) {\n httpRequest.setHeader(key, headers.get(key));\n }\n\n HttpResponse httpResponse = httpClient.execute(httpRequest);\n return new ArtifactoryResponseImpl(httpResponse);\n }"
] |
If the `invokerClass` specified is singleton, or without field or all fields are
stateless, then return an instance of the invoker class. Otherwise, return null
@param invokerClass the invoker class
@param app the app
@return an instance of the invokerClass or `null` if invoker class is stateful class | [
"public static Object tryGetSingleton(Class<?> invokerClass, App app) {\n Object singleton = app.singleton(invokerClass);\n if (null == singleton) {\n if (isGlobalOrStateless(invokerClass, new HashSet<Class>())) {\n singleton = app.getInstance(invokerClass);\n }\n }\n if (null != singleton) {\n app.registerSingleton(singleton);\n }\n return singleton;\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 void seekToSeasonYear(String seasonString, String yearString) {\n Season season = Season.valueOf(seasonString);\n assert(season != null);\n \n seekToIcsEventYear(SEASON_ICS_FILE, yearString, season.getSummary());\n }",
"public static base_response delete(nitro_service client, appfwlearningdata resource) throws Exception {\n\t\tappfwlearningdata deleteresource = new appfwlearningdata();\n\t\tdeleteresource.profilename = resource.profilename;\n\t\tdeleteresource.starturl = resource.starturl;\n\t\tdeleteresource.cookieconsistency = resource.cookieconsistency;\n\t\tdeleteresource.fieldconsistency = resource.fieldconsistency;\n\t\tdeleteresource.formactionurl_ffc = resource.formactionurl_ffc;\n\t\tdeleteresource.crosssitescripting = resource.crosssitescripting;\n\t\tdeleteresource.formactionurl_xss = resource.formactionurl_xss;\n\t\tdeleteresource.sqlinjection = resource.sqlinjection;\n\t\tdeleteresource.formactionurl_sql = resource.formactionurl_sql;\n\t\tdeleteresource.fieldformat = resource.fieldformat;\n\t\tdeleteresource.formactionurl_ff = resource.formactionurl_ff;\n\t\tdeleteresource.csrftag = resource.csrftag;\n\t\tdeleteresource.csrfformoriginurl = resource.csrfformoriginurl;\n\t\tdeleteresource.xmldoscheck = resource.xmldoscheck;\n\t\tdeleteresource.xmlwsicheck = resource.xmlwsicheck;\n\t\tdeleteresource.xmlattachmentcheck = resource.xmlattachmentcheck;\n\t\tdeleteresource.totalxmlrequests = resource.totalxmlrequests;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"public float getColorR(int vertex, int colorset) {\n if (!hasColors(colorset)) {\n throw new IllegalStateException(\"mesh has no colorset \" + colorset);\n }\n \n checkVertexIndexBounds(vertex);\n /* bound checks for colorset are done by java for us */\n \n return m_colorsets[colorset].getFloat(vertex * 4 * SIZEOF_FLOAT);\n }",
"private void countCoordinates(int xCoord, int yCoord,\n\t\t\tItemDocument itemDocument) {\n\n\t\tfor (String siteKey : itemDocument.getSiteLinks().keySet()) {\n\t\t\tInteger count = this.siteCounts.get(siteKey);\n\t\t\tif (count == null) {\n\t\t\t\tthis.siteCounts.put(siteKey, 1);\n\t\t\t} else {\n\t\t\t\tthis.siteCounts.put(siteKey, count + 1);\n\t\t\t}\n\t\t}\n\n\t\tfor (ValueMap vm : this.valueMaps) {\n\t\t\tvm.countCoordinates(xCoord, yCoord, itemDocument);\n\t\t}\n\t}",
"@Override\n public void preStateCrawling(CrawlerContext context,\n ImmutableList<CandidateElement> candidateElements, StateVertex state) {\n LOG.debug(\"preStateCrawling\");\n List<CandidateElementPosition> newElements = Lists.newLinkedList();\n LOG.info(\"Prestate found new state {} with {} candidates\", state.getName(),\n candidateElements.size());\n for (CandidateElement element : candidateElements) {\n try {\n WebElement webElement = getWebElement(context.getBrowser(), element);\n if (webElement != null) {\n newElements.add(findElement(webElement, element));\n }\n } catch (WebDriverException e) {\n LOG.info(\"Could not get position for {}\", element, e);\n }\n }\n\n StateBuilder stateOut = outModelCache.addStateIfAbsent(state);\n stateOut.addCandidates(newElements);\n LOG.trace(\"preState finished, elements added to state\");\n }",
"private boolean computeUWV() {\n bidiag.getDiagonal(diag,off);\n qralg.setMatrix(numRowsT,numColsT,diag,off);\n\n// long pointA = System.currentTimeMillis();\n // compute U and V matrices\n if( computeU )\n Ut = bidiag.getU(Ut,true,compact);\n if( computeV )\n Vt = bidiag.getV(Vt,true,compact);\n\n qralg.setFastValues(false);\n if( computeU )\n qralg.setUt(Ut);\n else\n qralg.setUt(null);\n if( computeV )\n qralg.setVt(Vt);\n else\n qralg.setVt(null);\n\n// long pointB = System.currentTimeMillis();\n\n boolean ret = !qralg.process();\n\n// long pointC = System.currentTimeMillis();\n// System.out.println(\" compute UV \"+(pointB-pointA)+\" QR = \"+(pointC-pointB));\n\n return ret;\n }",
"public WebSocketContext sendJsonToUser(Object data, String username) {\n return sendToTagged(JSON.toJSONString(data), username);\n }",
"public static org.jfrog.hudson.ArtifactoryServer prepareArtifactoryServer(String artifactoryServerID,\n ArtifactoryServer pipelineServer) {\n\n if (artifactoryServerID == null && pipelineServer == null) {\n return null;\n }\n if (artifactoryServerID != null && pipelineServer != null) {\n return null;\n }\n if (pipelineServer != null) {\n CredentialsConfig credentials = pipelineServer.createCredentialsConfig();\n\n return new org.jfrog.hudson.ArtifactoryServer(null, pipelineServer.getUrl(), credentials,\n credentials, pipelineServer.getConnection().getTimeout(), pipelineServer.isBypassProxy(), pipelineServer.getConnection().getRetry(), pipelineServer.getDeploymentThreads());\n }\n org.jfrog.hudson.ArtifactoryServer server = RepositoriesUtils.getArtifactoryServer(artifactoryServerID, RepositoriesUtils.getArtifactoryServers());\n if (server == null) {\n return null;\n }\n return server;\n }"
] |
Registers the resource to the parent deployment resource. The model returned is that of the resource parameter.
@param subsystemName the subsystem name
@param resource the resource to be used for the subsystem on the deployment
@return the model
@throws java.lang.IllegalStateException if the subsystem resource already exists | [
"public ModelNode registerDeploymentSubsystemResource(final String subsystemName, final Resource resource) {\n assert subsystemName != null : \"The subsystemName cannot be null\";\n assert resource != null : \"The resource cannot be null\";\n return registerDeploymentSubResource(subsystemName, PathAddress.EMPTY_ADDRESS, resource);\n }"
] | [
"public FilePath getModuleRoot(Map<String, String> globalEnv) throws IOException, InterruptedException {\n FilePath someWorkspace = project.getSomeWorkspace();\n if (someWorkspace == null) {\n throw new IllegalStateException(\"Couldn't find workspace\");\n }\n\n Map<String, String> workspaceEnv = Maps.newHashMap();\n workspaceEnv.put(\"WORKSPACE\", someWorkspace.getRemote());\n\n for (Builder builder : getBuilders()) {\n if (builder instanceof Gradle) {\n Gradle gradleBuilder = (Gradle) builder;\n String rootBuildScriptDir = gradleBuilder.getRootBuildScriptDir();\n if (rootBuildScriptDir != null && rootBuildScriptDir.trim().length() != 0) {\n String rootBuildScriptNormalized = Util.replaceMacro(rootBuildScriptDir.trim(), workspaceEnv);\n rootBuildScriptNormalized = Util.replaceMacro(rootBuildScriptNormalized, globalEnv);\n return new FilePath(someWorkspace, rootBuildScriptNormalized);\n } else {\n return someWorkspace;\n }\n }\n }\n\n throw new IllegalArgumentException(\"Couldn't find Gradle builder in the current builders list\");\n }",
"synchronized public void completeTask(int taskId, int partitionStoresMigrated) {\n tasksInFlight.remove(taskId);\n\n numTasksCompleted++;\n numPartitionStoresMigrated += partitionStoresMigrated;\n\n updateProgressBar();\n }",
"public void addBeanToBeanMapping(BeanToBeanMapping beanToBeanMapping) {\r\n\t\tbeanToBeanMappings.put(ClassPair.get(beanToBeanMapping\r\n\t\t\t\t.getSourceClass(), beanToBeanMapping.getDestinationClass()),\r\n\t\t\t\tbeanToBeanMapping);\r\n\t}",
"private void writeTermStatisticsToFile(UsageStatistics usageStatistics,\n\t\t\tString fileName) {\n\n\t\t// Make sure all keys are present in label count map:\n\t\tfor (String key : usageStatistics.aliasCounts.keySet()) {\n\t\t\tcountKey(usageStatistics.labelCounts, key, 0);\n\t\t}\n\t\tfor (String key : usageStatistics.descriptionCounts.keySet()) {\n\t\t\tcountKey(usageStatistics.labelCounts, key, 0);\n\t\t}\n\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(fileName))) {\n\n\t\t\tout.println(\"Language,Labels,Descriptions,Aliases\");\n\t\t\tfor (Entry<String, Integer> entry : usageStatistics.labelCounts\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tcountKey(usageStatistics.aliasCounts, entry.getKey(), 0);\n\t\t\t\tint aCount = usageStatistics.aliasCounts.get(entry.getKey());\n\t\t\t\tcountKey(usageStatistics.descriptionCounts, entry.getKey(), 0);\n\t\t\t\tint dCount = usageStatistics.descriptionCounts.get(entry\n\t\t\t\t\t\t.getKey());\n\t\t\t\tout.println(entry.getKey() + \",\" + entry.getValue() + \",\"\n\t\t\t\t\t\t+ dCount + \",\" + aCount);\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}",
"public static 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 int getPartition(byte[] key,\n byte[] value,\n int numReduceTasks) {\n try {\n /**\n * {@link partitionId} is the Voldemort primary partition that this\n * record belongs to.\n */\n int partitionId = ByteUtils.readInt(value, ByteUtils.SIZE_OF_INT);\n\n /**\n * This is the base number we will ultimately mod by {@link numReduceTasks}\n * to determine which reduce task to shuffle to.\n */\n int magicNumber = partitionId;\n\n if (getSaveKeys() && !buildPrimaryReplicasOnly) {\n /**\n * When saveKeys is enabled (which also implies we are generating\n * READ_ONLY_V2 format files), then we are generating files with\n * a replica type, with one file per replica.\n *\n * Each replica is sent to a different reducer, and thus the\n * {@link magicNumber} is scaled accordingly.\n *\n * The downside to this is that it is pretty wasteful. The files\n * generated for each replicas are identical to one another, so\n * there's no point in generating them independently in many\n * reducers.\n *\n * This is one of the reasons why buildPrimaryReplicasOnly was\n * written. In this mode, we only generate the files for the\n * primary replica, which means the number of reducers is\n * minimized and {@link magicNumber} does not need to be scaled.\n */\n int replicaType = (int) ByteUtils.readBytes(value,\n 2 * ByteUtils.SIZE_OF_INT,\n ByteUtils.SIZE_OF_BYTE);\n magicNumber = magicNumber * getStoreDef().getReplicationFactor() + replicaType;\n }\n\n if (!getReducerPerBucket()) {\n /**\n * Partition files can be split in many chunks in order to limit the\n * maximum file size downloaded and handled by Voldemort servers.\n *\n * {@link chunkId} represents which chunk of partition then current\n * record belongs to.\n */\n int chunkId = ReadOnlyUtils.chunk(key, getNumChunks());\n\n /**\n * When reducerPerBucket is disabled, all chunks are sent to a\n * different reducer. This increases parallelism at the expense\n * of adding more load on Hadoop.\n *\n * {@link magicNumber} is thus scaled accordingly, in order to\n * leverage the extra reducers available to us.\n */\n magicNumber = magicNumber * getNumChunks() + chunkId;\n }\n\n /**\n * Finally, we mod {@link magicNumber} by {@link numReduceTasks},\n * since the MapReduce framework expects the return of this function\n * to be bounded by the number of reduce tasks running in the job.\n */\n return magicNumber % numReduceTasks;\n } catch (Exception e) {\n throw new VoldemortException(\"Caught exception in getPartition()!\" +\n \" key: \" + ByteUtils.toHexString(key) +\n \", value: \" + ByteUtils.toHexString(value) +\n \", numReduceTasks: \" + numReduceTasks, e);\n }\n }",
"public static String readTextFile(Context context, int resourceId) {\n InputStream inputStream = context.getResources().openRawResource(\n resourceId);\n return readTextFile(inputStream);\n }",
"public static boolean isDiagonalPositive( DMatrixRMaj a ) {\n for( int i = 0; i < a.numRows; i++ ) {\n if( !(a.get(i,i) >= 0) )\n return false;\n }\n return true;\n }",
"public base_response clear_config(Boolean force, String level) throws Exception\n\t{\n\t\tbase_response result = null;\n\t\tnsconfig resource = new nsconfig();\n\t\tif (force)\n\t\t\tresource.set_force(force);\n\n\t\tresource.set_level(level);\n\t\toptions option = new options();\n\t\toption.set_action(\"clear\");\n\t\tresult = resource.perform_operation(this, option);\n\t\treturn result;\n\t}"
] |
Use this API to fetch tunneltrafficpolicy resource of given name . | [
"public static tunneltrafficpolicy get(nitro_service service, String name) throws Exception{\n\t\ttunneltrafficpolicy obj = new tunneltrafficpolicy();\n\t\tobj.set_name(name);\n\t\ttunneltrafficpolicy response = (tunneltrafficpolicy) obj.get_resource(service);\n\t\treturn response;\n\t}"
] | [
"void countNonZeroInV( int []parent ) {\n int []w = gwork.data;\n findMinElementIndexInRows(leftmost);\n createRowElementLinkedLists(leftmost,w);\n countNonZeroUsingLinkedList(parent,w);\n }",
"public DbInfo info() {\n return client.couchDbClient.get(new DatabaseURIHelper(db.getDBUri()).getDatabaseUri(),\n DbInfo.class);\n }",
"private void addAuthentication(HttpHost host, Credentials credentials,\n AuthScheme authScheme, HttpClientContext context) {\n AuthCache authCache = context.getAuthCache();\n if (authCache == null) {\n authCache = new BasicAuthCache();\n context.setAuthCache(authCache);\n }\n \n CredentialsProvider credsProvider = context.getCredentialsProvider();\n if (credsProvider == null) {\n credsProvider = new BasicCredentialsProvider();\n context.setCredentialsProvider(credsProvider);\n }\n \n credsProvider.setCredentials(new AuthScope(host), credentials);\n \n if (authScheme != null) {\n authCache.put(host, authScheme);\n }\n }",
"public void useNewRESTService(String address) throws Exception {\n List<Object> providers = createJAXRSProviders();\n\n org.customer.service.CustomerService customerService = JAXRSClientFactory\n .createFromModel(address, \n org.customer.service.CustomerService.class,\n \"classpath:/model/CustomerService-jaxrs.xml\", \n providers, \n null);\n\n System.out.println(\"Using new RESTful CustomerService with new client\");\n\n customer.v2.Customer customer = createNewCustomer(\"Smith New REST\");\n customerService.updateCustomer(customer);\n\n customer = customerService.getCustomerByName(\"Smith New REST\");\n printNewCustomerDetails(customer);\n }",
"public void setAll() {\n\tshowAttributes = true;\n\tshowEnumerations = true;\n\tshowEnumConstants = true;\n\tshowOperations = true;\n\tshowConstructors = true;\n\tshowVisibility = true;\n\tshowType = true;\n }",
"public static DMatrixRMaj convert(DMatrixRBlock src , DMatrixRMaj dst )\n {\n return ConvertDMatrixStruct.convert(src,dst);\n }",
"protected MappedPreparedStmt<T, ID> prepareStatement(Long limit, boolean cacheStore) throws SQLException {\n\t\tList<ArgumentHolder> argList = new ArrayList<ArgumentHolder>();\n\t\tString statement = buildStatementString(argList);\n\t\tArgumentHolder[] selectArgs = argList.toArray(new ArgumentHolder[argList.size()]);\n\t\tFieldType[] resultFieldTypes = getResultFieldTypes();\n\t\tFieldType[] argFieldTypes = new FieldType[argList.size()];\n\t\tfor (int selectC = 0; selectC < selectArgs.length; selectC++) {\n\t\t\targFieldTypes[selectC] = selectArgs[selectC].getFieldType();\n\t\t}\n\t\tif (!type.isOkForStatementBuilder()) {\n\t\t\tthrow new IllegalStateException(\"Building a statement from a \" + type + \" statement is not allowed\");\n\t\t}\n\t\treturn new MappedPreparedStmt<T, ID>(dao, tableInfo, statement, argFieldTypes, resultFieldTypes, selectArgs,\n\t\t\t\t(databaseType.isLimitSqlSupported() ? null : limit), type, cacheStore);\n\t}",
"public static List<Number> findIndexValues(Object self, Number startIndex, Closure closure) {\n List<Number> result = new ArrayList<Number>();\n long count = 0;\n long startCount = startIndex.longValue();\n BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);\n for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); count++) {\n Object value = iter.next();\n if (count < startCount) {\n continue;\n }\n if (bcw.call(value)) {\n result.add(count);\n }\n }\n return result;\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 }"
] |
Checks all data sets in a given record for constraint violations.
@param record
IIM record (1,2,3, ...) to check
@return list of constraint violations, empty set if IIM file is valid | [
"public Set<ConstraintViolation> validate(int record) {\r\n\t\tSet<ConstraintViolation> errors = new LinkedHashSet<ConstraintViolation>();\r\n\t\tfor (int ds = 0; ds < 250; ++ds) {\r\n\t\t\ttry {\r\n\t\t\t\tDataSetInfo dataSetInfo = dsiFactory.create(IIM.DS(record, ds));\r\n\t\t\t\terrors.addAll(validate(dataSetInfo));\r\n\t\t\t} catch (InvalidDataSetException ignored) {\r\n\t\t\t\t// DataSetFactory doesn't know about this ds, so will skip it\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn errors;\r\n\t}"
] | [
"String urlDecode(String name, String encoding) throws UnsupportedEncodingException {\n return URLDecoder.decode(name, encoding);\n }",
"protected void applyBanners() {\n DynamicReportOptions options = getReport().getOptions();\n if (options.getFirstPageImageBanners().isEmpty() && options.getImageBanners().isEmpty()){\n return;\n }\n\n\t\t/*\n\t\t First create image banners for the first page only\n\t\t */\n\t\tJRDesignBand title = (JRDesignBand) getDesign().getTitle();\n\t\t//if there is no title band, but there are banner images for the first page, we create a title band\n\t\tif (title == null && !options.getFirstPageImageBanners().isEmpty()){\n\t\t\ttitle = new JRDesignBand();\n\t\t\tgetDesign().setTitle(title);\n\t\t}\n\t\tapplyImageBannersToBand(title, options.getFirstPageImageBanners().values(), null, true);\n\n\t\t/*\n\t\t Now create image banner for the rest of the pages\n\t\t */\n\t\tJRDesignBand pageHeader = (JRDesignBand) getDesign().getPageHeader();\n\t\t//if there is no title band, but there are banner images for the first page, we create a title band\n\t\tif (pageHeader == null && !options.getImageBanners().isEmpty()){\n\t\t\tpageHeader = new JRDesignBand();\n\t\t\tgetDesign().setPageHeader(pageHeader);\n\t\t}\n\t\tJRDesignExpression printWhenExpression = null;\n\t\tif (!options.getFirstPageImageBanners().isEmpty()){\n\t\t\tprintWhenExpression = new JRDesignExpression();\n\t\t\tprintWhenExpression.setValueClass(Boolean.class);\n\t\t\tprintWhenExpression.setText(EXPRESSION_TRUE_WHEN_NOT_FIRST_PAGE);\n\t\t}\n\t\tapplyImageBannersToBand(pageHeader, options.getImageBanners().values(),printWhenExpression, true);\n\n\n\n\t}",
"public static Shell createConsoleShell(String prompt, String appName, Object... handlers) {\n ConsoleIO io = new ConsoleIO();\n\n List<String> path = new ArrayList<String>(1);\n path.add(prompt);\n\n MultiMap<String, Object> modifAuxHandlers = new ArrayHashMultiMap<String, Object>();\n modifAuxHandlers.put(\"!\", io);\n\n Shell theShell = new Shell(new Shell.Settings(io, io, modifAuxHandlers, false),\n new CommandTable(new DashJoinedNamer(true)), path);\n theShell.setAppName(appName);\n\n theShell.addMainHandler(theShell, \"!\");\n theShell.addMainHandler(new HelpCommandHandler(), \"?\");\n for (Object h : handlers) {\n theShell.addMainHandler(h, \"\");\n }\n\n return theShell;\n }",
"public final synchronized void shutdown() { // synchronize on 'this' to avoid races with registerStreams\n stopped = true;\n // If the cleanup task is running tell it to stop looping, and then remove it from the scheduled executor\n if (cleanupTaskFuture != null) {\n cleanupTaskFuture.cancel(false);\n }\n\n // Close remaining streams\n for (Map.Entry<InputStreamKey, TimedStreamEntry> entry : streamMap.entrySet()) {\n InputStreamKey key = entry.getKey();\n TimedStreamEntry timedStreamEntry = entry.getValue();\n //noinspection SynchronizationOnLocalVariableOrMethodParameter\n synchronized (timedStreamEntry) { // ensure there's no race with a request that got a ref before we removed it\n closeStreamEntry(timedStreamEntry, key.requestId, key.index);\n }\n }\n }",
"public static String getHeaders(HttpServletResponse response) {\n String headerString = \"\";\n Collection<String> headerNames = response.getHeaderNames();\n for (String headerName : headerNames) {\n // there may be multiple headers per header name\n for (String headerValue : response.getHeaders(headerName)) {\n if (headerString.length() != 0) {\n headerString += \"\\n\";\n }\n\n headerString += headerName + \": \" + headerValue;\n }\n }\n\n return headerString;\n }",
"public List<DbLicense> getModuleLicenses(final String moduleId,\n final LicenseMatcher licenseMatcher) {\n final DbModule module = getModule(moduleId);\n\n final List<DbLicense> licenses = new ArrayList<>();\n final FiltersHolder filters = new FiltersHolder();\n final ArtifactHandler artifactHandler = new ArtifactHandler(repositoryHandler, licenseMatcher);\n\n for (final String gavc : DataUtils.getAllArtifacts(module)) {\n licenses.addAll(artifactHandler.getArtifactLicenses(gavc, filters));\n }\n\n return licenses;\n }",
"static List<List<String>> handleNewLines( List<List<String>> tableModel ) {\n List<List<String>> result = Lists.newArrayListWithExpectedSize( tableModel.size() );\n\n for( List<String> row : tableModel ) {\n if( hasNewline( row ) ) {\n result.addAll( splitRow( row ) );\n } else {\n result.add( row );\n }\n }\n\n return result;\n }",
"final protected void putChar(char c) {\n final int clen = _internalBuffer.length;\n if (clen == _bufferPosition) {\n final char[] next = new char[2 * clen + 1];\n\n System.arraycopy(_internalBuffer, 0, next, 0, _bufferPosition);\n _internalBuffer = next;\n }\n\n _internalBuffer[_bufferPosition++] = c;\n }",
"@SuppressWarnings(\"WeakerAccess\")\n public Map<DeckReference, WaveformPreview> getLoadedPreviews() {\n ensureRunning();\n // Make a copy so callers get an immutable snapshot of the current state.\n return Collections.unmodifiableMap(new HashMap<DeckReference, WaveformPreview>(previewHotCache));\n }"
] |
Send JSON representation of a data object to all connections of a certain user
@param data the data to be sent
@param username the username
@return this context | [
"public WebSocketContext sendJsonToUser(Object data, String username) {\n return sendToTagged(JSON.toJSONString(data), username);\n }"
] | [
"public List<String> scan() {\n try {\n JarFile jar = new JarFile(jarURL.getFile());\n try {\n List<String> result = new ArrayList<>();\n Enumeration<JarEntry> en = jar.entries();\n while (en.hasMoreElements()) {\n JarEntry entry = en.nextElement();\n String path = entry.getName();\n boolean match = includes.size() == 0;\n if (!match) {\n for (String pattern : includes) {\n if ( patternMatches(pattern, path)) {\n match = true;\n break;\n }\n }\n }\n if (match) {\n for (String pattern : excludes) {\n if ( patternMatches(pattern, path)) {\n match = false;\n break;\n }\n }\n }\n if (match) {\n result.add(path);\n }\n }\n return result;\n } finally {\n jar.close();\n }\n } catch (IOException e) {\n throw new IllegalStateException(e);\n }\n }",
"public static base_responses add(nitro_service client, autoscaleaction resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tautoscaleaction addresources[] = new autoscaleaction[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new autoscaleaction();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].type = resources[i].type;\n\t\t\t\taddresources[i].profilename = resources[i].profilename;\n\t\t\t\taddresources[i].parameters = resources[i].parameters;\n\t\t\t\taddresources[i].vmdestroygraceperiod = resources[i].vmdestroygraceperiod;\n\t\t\t\taddresources[i].quiettime = resources[i].quiettime;\n\t\t\t\taddresources[i].vserver = resources[i].vserver;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"@SuppressWarnings(\"unused\")\n public static void changeCredentials(String accountID, String token) {\n changeCredentials(accountID, token, null);\n }",
"public static base_response update(nitro_service client, vridparam resource) throws Exception {\n\t\tvridparam updateresource = new vridparam();\n\t\tupdateresource.sendtomaster = resource.sendtomaster;\n\t\treturn updateresource.update_resource(client);\n\t}",
"private void handleTextWebSocketFrameInternal(TextWebSocketFrame frame, ChannelHandlerContext ctx) {\n\t\tif (logger.isTraceEnabled()) {\n\t\t\tlogger.trace(String.format(\"%s received %s\", ctx.channel(), frame.text()));\n\t\t}\n\n\t\taddTraceForFrame(frame, \"text\");\n\t\tctx.channel().write(new TextWebSocketFrame(\"Echo: \" + frame.text()));\n\t}",
"public String validationErrors() {\n\n List<String> errors = new ArrayList<>();\n for (File config : getConfigFiles()) {\n String filename = config.getName();\n try (FileInputStream stream = new FileInputStream(config)) {\n CmsXmlUtils.unmarshalHelper(CmsFileUtil.readFully(stream, false), new CmsXmlEntityResolver(null), true);\n } catch (CmsXmlException e) {\n errors.add(filename + \":\" + e.getCause().getMessage());\n } catch (Exception e) {\n errors.add(filename + \":\" + e.getMessage());\n }\n }\n if (errors.size() == 0) {\n return null;\n }\n String errString = CmsStringUtil.listAsString(errors, \"\\n\");\n JSONObject obj = new JSONObject();\n try {\n obj.put(\"err\", errString);\n } catch (JSONException e) {\n\n }\n return obj.toString();\n }",
"public void installApp(Functions.Func callback) {\n if (isPwaSupported()) {\n appInstaller = new AppInstaller(callback);\n appInstaller.prompt();\n }\n }",
"@Override\n protected URL getDefinitionsURL() {\n try {\n URL url = CustomEPSGCodes.class.getResource(CUSTOM_EPSG_CODES_FILE);\n // quickly test url\n try (InputStream stream = url.openStream()) {\n //noinspection ResultOfMethodCallIgnored\n stream.read();\n }\n return url;\n } catch (Throwable e) {\n throw new AssertionError(\"Unable to load /epsg.properties file from root of classpath.\");\n }\n }",
"public void handleChannelClosed(final Channel closed, final IOException e) {\n for(final ActiveOperationImpl<?, ?> activeOperation : activeRequests.values()) {\n if (activeOperation.getChannel() == closed) {\n // Only call cancel, to also interrupt still active threads\n activeOperation.getResultHandler().cancel();\n }\n }\n }"
] |
Decomposes a submatrix. The results are written to the submatrix
and to its internal matrix L.
@param mat A matrix which has a submatrix that needs to be inverted
@param indexStart the first index of the submatrix
@param n The width of the submatrix that is to be inverted.
@return True if it was able to finish the decomposition. | [
"public boolean decompose(DMatrixRMaj mat , int indexStart , int n ) {\n double m[] = mat.data;\n\n double el_ii;\n double div_el_ii=0;\n\n for( int i = 0; i < n; i++ ) {\n for( int j = i; j < n; j++ ) {\n double sum = m[indexStart+i*mat.numCols+j];\n\n int iEl = i*n;\n int jEl = j*n;\n int end = iEl+i;\n // k = 0:i-1\n for( ; iEl<end; iEl++,jEl++ ) {\n// sum -= el[i*n+k]*el[j*n+k];\n sum -= el[iEl]*el[jEl];\n }\n\n if( i == j ) {\n // is it positive-definate?\n if( sum <= 0.0 )\n return false;\n\n el_ii = Math.sqrt(sum);\n el[i*n+i] = el_ii;\n m[indexStart+i*mat.numCols+i] = el_ii;\n div_el_ii = 1.0/el_ii;\n } else {\n double v = sum*div_el_ii;\n el[j*n+i] = v;\n m[indexStart+j*mat.numCols+i] = v;\n }\n }\n }\n\n return true;\n }"
] | [
"private Collection<Locale> initLocales() {\n\n Collection<Locale> locales = null;\n switch (m_bundleType) {\n case DESCRIPTOR:\n locales = new ArrayList<Locale>(1);\n locales.add(Descriptor.LOCALE);\n break;\n case XML:\n case PROPERTY:\n locales = OpenCms.getLocaleManager().getAvailableLocales(m_cms, m_resource);\n break;\n default:\n throw new IllegalArgumentException();\n }\n return locales;\n\n }",
"public long addAll(final Map<String, Double> scoredMember) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.zadd(getKey(), scoredMember);\n }\n });\n }",
"public void start(String name)\n {\n GVRAnimator anim = findAnimation(name);\n\n if (name.equals(anim.getName()))\n {\n start(anim);\n return;\n }\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 }",
"protected org.apache.log4j.helpers.PatternParser createPatternParser(final String pattern) {\n\t\treturn new FoundationLoggingPatternParser(pattern);\n\t}",
"public static nsacl6_stats get(nitro_service service, String acl6name) throws Exception{\n\t\tnsacl6_stats obj = new nsacl6_stats();\n\t\tobj.set_acl6name(acl6name);\n\t\tnsacl6_stats response = (nsacl6_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"static final TimeBasedRollStrategy findRollStrategy(\n final AppenderRollingProperties properties) {\n if (properties.getDatePattern() == null) {\n LogLog.error(\"null date pattern\");\n return ROLL_ERROR;\n }\n // Strip out quoted sections so that we may safely scan the undecorated\n // pattern for characters that are meaningful to SimpleDateFormat.\n final LocalizedDateFormatPatternHelper localizedDateFormatPatternHelper = new LocalizedDateFormatPatternHelper(\n properties.getDatePatternLocale());\n final String undecoratedDatePattern = localizedDateFormatPatternHelper\n .excludeQuoted(properties.getDatePattern());\n if (ROLL_EACH_MINUTE.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_MINUTE;\n }\n if (ROLL_EACH_HOUR.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_HOUR;\n }\n if (ROLL_EACH_HALF_DAY.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_HALF_DAY;\n }\n if (ROLL_EACH_DAY.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_DAY;\n }\n if (ROLL_EACH_WEEK.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_WEEK;\n }\n if (ROLL_EACH_MONTH.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_MONTH;\n }\n return ROLL_ERROR;\n }",
"public void drawImage(Image img, Rectangle rect, Rectangle clipRect) {\n\t\tdrawImage(img, rect, clipRect, 1);\n\t}",
"public boolean shouldBeInReport(final DbDependency dependency) {\n if(dependency == null){\n return false;\n }\n if(dependency.getTarget() == null){\n return false;\n }\n if(corporateFilter != null){\n if(!decorator.getShowThirdparty() && !corporateFilter.filter(dependency)){\n return false;\n }\n if(!decorator.getShowCorporate() && corporateFilter.filter(dependency)){\n return false;\n }\n }\n\n if(!scopeHandler.filter(dependency)){\n return false;\n }\n\n return true;\n }"
] |
Builds the path for a closed arc, returning a PolygonOptions that can be
further customised before use.
@param center
@param start
@param end
@param arcType Pass in either ArcType.CHORD or ArcType.ROUND
@return PolygonOptions with the paths element populated. | [
"public static final PolygonOptions buildClosedArc(LatLong center, LatLong start, LatLong end, ArcType arcType) {\n MVCArray res = buildArcPoints(center, start, end);\n if (ArcType.ROUND.equals(arcType)) {\n res.push(center);\n }\n return new PolygonOptions().paths(res);\n }"
] | [
"public static SimpleFeatureType createGridFeatureType(\n @Nonnull final MapfishMapContext mapContext,\n @Nonnull final Class<? extends Geometry> geomClass) {\n final SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();\n CoordinateReferenceSystem projection = mapContext.getBounds().getProjection();\n typeBuilder.add(Constants.Style.Grid.ATT_GEOM, geomClass, projection);\n typeBuilder.setName(Constants.Style.Grid.NAME_LINES);\n\n return typeBuilder.buildFeatureType();\n }",
"private List<Row> getRows(String sql) throws SQLException\n {\n allocateConnection();\n\n try\n {\n List<Row> result = new LinkedList<Row>();\n\n m_ps = m_connection.prepareStatement(sql);\n m_rs = m_ps.executeQuery();\n populateMetaData();\n while (m_rs.next())\n {\n result.add(new MpdResultSetRow(m_rs, m_meta));\n }\n\n return (result);\n }\n\n finally\n {\n releaseConnection();\n }\n }",
"protected synchronized Class loadClass(final String name, boolean resolve) throws ClassNotFoundException {\n Class c = this.findLoadedClass(name);\n if (c != null) return c;\n c = (Class) customClasses.get(name);\n if (c != null) return c;\n\n try {\n c = oldFindClass(name);\n } catch (ClassNotFoundException cnfe) {\n // IGNORE\n }\n if (c == null) c = super.loadClass(name, resolve);\n\n if (resolve) resolveClass(c);\n\n return c;\n }",
"protected Violation createViolation(SourceCode sourceCode, ASTNode node, String message) {\n String sourceLine = sourceCode.line(node.getLineNumber()-1);\n return createViolation(node.getLineNumber(), sourceLine, message);\n }",
"public void setEnterpriseCost(int index, Number value)\n {\n set(selectField(AssignmentFieldLists.ENTERPRISE_COST, index), value);\n }",
"public Collection<SerialMessage> initialize() {\r\n\t\tArrayList<SerialMessage> result = new ArrayList<SerialMessage>();\r\n\t\t\r\n\t\tif (this.getNode().getManufacturer() == 0x010F && this.getNode().getDeviceType() == 0x0501) {\r\n\t\t\t\tlogger.warn(\"Detected Fibaro FGBS001 Universal Sensor - this device fails to respond to SENSOR_ALARM_GET and SENSOR_ALARM_SUPPORTED_GET.\");\r\n\t\t\t\treturn result;\r\n\t\t}\r\n\t\t\r\n\t\tresult.add(this.getSupportedMessage());\r\n\t\treturn result;\r\n\t}",
"public static int countTrue(BMatrixRMaj A) {\n int total = 0;\n\n int N = A.getNumElements();\n\n for (int i = 0; i < N; i++) {\n if( A.data[i] )\n total++;\n }\n\n return total;\n }",
"public Story storyOfPath(Configuration configuration, String storyPath) {\n String storyAsText = configuration.storyLoader().loadStoryAsText(storyPath);\n return configuration.storyParser().parseStory(storyAsText, storyPath);\n }",
"protected <C> C convert(Object object, Class<C> targetClass) {\n return this.mapper.convertValue(object, targetClass);\n }"
] |
Add a 'IS NULL' clause so the column must be null. '=' NULL does not work. | [
"public Where<T, ID> isNull(String columnName) throws SQLException {\n\t\taddClause(new IsNull(columnName, findColumnFieldType(columnName)));\n\t\treturn this;\n\t}"
] | [
"private void writeCostRateTables(Project.Resources.Resource xml, Resource mpx)\n {\n //Rates rates = m_factory.createProjectResourcesResourceRates();\n //xml.setRates(rates);\n //List<Project.Resources.Resource.Rates.Rate> ratesList = rates.getRate();\n\n List<Project.Resources.Resource.Rates.Rate> ratesList = null;\n\n for (int tableIndex = 0; tableIndex < 5; tableIndex++)\n {\n CostRateTable table = mpx.getCostRateTable(tableIndex);\n if (table != null)\n {\n Date from = DateHelper.FIRST_DATE;\n for (CostRateTableEntry entry : table)\n {\n if (costRateTableWriteRequired(entry, from))\n {\n if (ratesList == null)\n {\n Rates rates = m_factory.createProjectResourcesResourceRates();\n xml.setRates(rates);\n ratesList = rates.getRate();\n }\n\n Project.Resources.Resource.Rates.Rate rate = m_factory.createProjectResourcesResourceRatesRate();\n ratesList.add(rate);\n\n rate.setCostPerUse(DatatypeConverter.printCurrency(entry.getCostPerUse()));\n rate.setOvertimeRate(DatatypeConverter.printRate(entry.getOvertimeRate()));\n rate.setOvertimeRateFormat(DatatypeConverter.printTimeUnit(entry.getOvertimeRateFormat()));\n rate.setRatesFrom(from);\n from = entry.getEndDate();\n rate.setRatesTo(from);\n rate.setRateTable(BigInteger.valueOf(tableIndex));\n rate.setStandardRate(DatatypeConverter.printRate(entry.getStandardRate()));\n rate.setStandardRateFormat(DatatypeConverter.printTimeUnit(entry.getStandardRateFormat()));\n }\n }\n }\n }\n }",
"@SuppressWarnings(\"unused\")\n public boolean isValid() {\n Phonenumber.PhoneNumber phoneNumber = getPhoneNumber();\n return phoneNumber != null && mPhoneUtil.isValidNumber(phoneNumber);\n }",
"public static base_response update(nitro_service client, rsskeytype resource) throws Exception {\n\t\trsskeytype updateresource = new rsskeytype();\n\t\tupdateresource.rsstype = resource.rsstype;\n\t\treturn updateresource.update_resource(client);\n\t}",
"@Override\n public void close() {\n status = TrStatus.CLOSED;\n try {\n node.close();\n } catch (IOException e) {\n log.error(\"Failed to close ephemeral node\");\n throw new IllegalStateException(e);\n }\n }",
"public 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}",
"private static ResourceBundle tryBundle(String baseName, Locale locale, boolean wantBase) {\n\n I_CmsResourceBundle first = null; // The most specialized bundle.\n I_CmsResourceBundle last = null; // The least specialized bundle.\n\n List<String> bundleNames = CmsLocaleManager.getLocaleVariants(baseName, locale, true, true);\n for (String bundleName : bundleNames) {\n // break if we would try the base bundle, but we do not want it directly\n if (bundleName.equals(baseName) && !wantBase && (first == null)) {\n break;\n }\n I_CmsResourceBundle foundBundle = tryBundle(bundleName);\n if (foundBundle != null) {\n if (first == null) {\n first = foundBundle;\n }\n\n if (last != null) {\n last.setParent((ResourceBundle)foundBundle);\n }\n foundBundle.setLocale(locale);\n\n last = foundBundle;\n }\n }\n return (ResourceBundle)first;\n }",
"public static Variable upcastToGeneratedBuilder(\n SourceBuilder code, Datatype datatype, String builder) {\n return code.scope().computeIfAbsent(Declaration.UPCAST, () -> {\n Variable base = new Variable(\"base\");\n code.addLine(UPCAST_COMMENT)\n .addLine(\"%s %s = %s;\", datatype.getGeneratedBuilder(), base, builder);\n return base;\n });\n }",
"public static void resetNamedTimer(String timerName, int todoFlags,\n\t\t\tlong threadId) {\n\t\tgetNamedTimer(timerName, todoFlags, threadId).reset();\n\t}",
"public void onDrawFrame(float frameTime)\n {\n if (isEnabled() && (mScene != null) && mPickEventLock.tryLock())\n {\n // Don't call if we are in the middle of processing another pick\n try\n {\n doPick();\n }\n finally\n {\n mPickEventLock.unlock();\n }\n }\n }"
] |
Start export and check in of the selected modules.
@return The exit code of the check in procedure (like a script's exit code). | [
"public int checkIn() {\n\n try {\n synchronized (STATIC_LOCK) {\n m_logStream = new PrintStream(new FileOutputStream(DEFAULT_LOGFILE_PATH, false));\n CmsObject cms = getCmsObject();\n if (cms != null) {\n return checkInInternal();\n } else {\n m_logStream.println(\"No CmsObject given. Did you call init() first?\");\n return -1;\n }\n }\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n return -2;\n }\n }"
] | [
"public void setSeriesEndDate(Date date) {\r\n\r\n if (!Objects.equals(m_model.getSeriesEndDate(), date)) {\r\n m_model.setSeriesEndDate(date);\r\n valueChanged();\r\n }\r\n\r\n }",
"private void addException(ProjectCalendar mpxjCalendar, net.sf.mpxj.ganttproject.schema.Date date)\n {\n String year = date.getYear();\n if (year == null || year.isEmpty())\n {\n // In order to process recurring exceptions using MPXJ, we need a start and end date\n // to constrain the number of dates we generate.\n // May need to pre-process the tasks in order to calculate a start and finish date.\n // TODO: handle recurring exceptions\n }\n else\n {\n Calendar calendar = DateHelper.popCalendar();\n calendar.set(Calendar.YEAR, Integer.parseInt(year));\n calendar.set(Calendar.MONTH, NumberHelper.getInt(date.getMonth()));\n calendar.set(Calendar.DAY_OF_MONTH, NumberHelper.getInt(date.getDate()));\n Date exceptionDate = calendar.getTime();\n DateHelper.pushCalendar(calendar);\n ProjectCalendarException exception = mpxjCalendar.addCalendarException(exceptionDate, exceptionDate);\n\n // TODO: not sure how NEUTRAL should be handled\n if (\"WORKING_DAY\".equals(date.getType()))\n {\n exception.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING);\n exception.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON);\n }\n }\n }",
"public void createLinks(ServiceReference<D> declarationSRef) {\n D declaration = getDeclaration(declarationSRef);\n for (ServiceReference<S> serviceReference : linkerManagement.getMatchedBinderServiceRef()) {\n if (linkerManagement.canBeLinked(declaration, serviceReference)) {\n linkerManagement.link(declaration, serviceReference);\n }\n }\n }",
"public static String lookupIfEmpty( final String value,\n final Map<String, String> props,\n final String key ) {\n return value != null ? value : props.get(key);\n }",
"public <T extends Widget & Checkable> List<T> getCheckedWidgets() {\n List<T> checked = new ArrayList<>();\n\n for (Widget c : getChildren()) {\n if (c instanceof Checkable && ((Checkable) c).isChecked()) {\n checked.add((T) c);\n }\n }\n\n return checked;\n }",
"public void setShowOutput(String mode) {\n try {\n this.outputMode = OutputMode.valueOf(mode.toUpperCase(Locale.ROOT));\n } catch (IllegalArgumentException e) {\n throw new IllegalArgumentException(\"showOutput accepts any of: \"\n + Arrays.toString(OutputMode.values()) + \", value is not valid: \" + mode);\n }\n }",
"private void calculateSCL(double[] x) {\r\n //System.out.println(\"Checking at: \"+x[0]+\" \"+x[1]+\" \"+x[2]);\r\n value = 0.0;\r\n Arrays.fill(derivative, 0.0);\r\n double[] sums = new double[numClasses];\r\n double[] probs = new double[numClasses];\r\n double[] counts = new double[numClasses];\r\n Arrays.fill(counts, 0.0);\r\n for (int d = 0; d < data.length; d++) {\r\n // if (d == testMin) {\r\n // d = testMax - 1;\r\n // continue;\r\n // }\r\n int[] features = data[d];\r\n // activation\r\n Arrays.fill(sums, 0.0);\r\n for (int c = 0; c < numClasses; c++) {\r\n for (int f = 0; f < features.length; f++) {\r\n int i = indexOf(features[f], c);\r\n sums[c] += x[i];\r\n }\r\n }\r\n // expectation (slower routine replaced by fast way)\r\n // double total = Double.NEGATIVE_INFINITY;\r\n // for (int c=0; c<numClasses; c++) {\r\n // total = SloppyMath.logAdd(total, sums[c]);\r\n // }\r\n double total = ArrayMath.logSum(sums);\r\n int ld = labels[d];\r\n for (int c = 0; c < numClasses; c++) {\r\n probs[c] = Math.exp(sums[c] - total);\r\n for (int f = 0; f < features.length; f++) {\r\n int i = indexOf(features[f], c);\r\n derivative[i] += probs[ld] * probs[c];\r\n }\r\n }\r\n // observed\r\n for (int f = 0; f < features.length; f++) {\r\n int i = indexOf(features[f], labels[d]);\r\n derivative[i] -= probs[ld];\r\n }\r\n value -= probs[ld];\r\n }\r\n // priors\r\n if (true) {\r\n for (int i = 0; i < x.length; i++) {\r\n double k = 1.0;\r\n double w = x[i];\r\n value += k * w * w / 2.0;\r\n derivative[i] += k * w;\r\n }\r\n }\r\n }",
"private void populateCalendarHours(Record record, ProjectCalendarHours hours) throws MPXJException\n {\n hours.setDay(Day.getInstance(NumberHelper.getInt(record.getInteger(0))));\n addDateRange(hours, record.getTime(1), record.getTime(2));\n addDateRange(hours, record.getTime(3), record.getTime(4));\n addDateRange(hours, record.getTime(5), record.getTime(6));\n }",
"private float[] generateParticleTimeStamps(float totalTime)\n {\n float timeStamps[] = new float[mEmitRate * 2];\n\n if ( burstMode ) {\n for (int i = 0; i < mEmitRate * 2; i += 2) {\n timeStamps[i] = totalTime;\n timeStamps[i + 1] = 0;\n }\n }\n else {\n for (int i = 0; i < mEmitRate * 2; i += 2) {\n timeStamps[i] = totalTime + mRandom.nextFloat();\n timeStamps[i + 1] = 0;\n }\n }\n return timeStamps;\n\n }"
] |
Obtains a local date in Symmetry010 calendar system from the
era, year-of-era and day-of-year fields.
@param era the Symmetry010 era, not null
@param yearOfEra the year-of-era
@param dayOfYear the day-of-year
@return the Symmetry010 local date, not null
@throws DateTimeException if unable to create the date
@throws ClassCastException if the {@code era} is not a {@code IsoEra} | [
"@Override\n public Symmetry010Date dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\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 }",
"@Override\r\n public String upload(InputStream in, UploadMetaData metaData) throws FlickrException {\r\n Payload payload = new Payload(in);\r\n return sendUploadRequest(metaData, payload);\r\n }",
"public static Attachment fromBinaryBytes( byte[] bytes, MediaType mediaType ) {\n if( !mediaType.isBinary() ) {\n throw new IllegalArgumentException( \"MediaType must be binary\" );\n }\n return new Attachment(BaseEncoding.base64().encode( bytes ), mediaType, null );\n }",
"public boolean matches(PathElement pe) {\n return pe.key.equals(key) && (isWildcard() || pe.value.equals(value));\n }",
"public static CredentialsConfig getPreferredDeployer(DeployerOverrider deployerOverrider, ArtifactoryServer server) {\n if (deployerOverrider.isOverridingDefaultDeployer()) {\n CredentialsConfig deployerCredentialsConfig = deployerOverrider.getDeployerCredentialsConfig();\n if (deployerCredentialsConfig != null) {\n return deployerCredentialsConfig;\n }\n }\n\n if (server != null) {\n CredentialsConfig deployerCredentials = server.getDeployerCredentialsConfig();\n if (deployerCredentials != null) {\n return deployerCredentials;\n }\n }\n\n return CredentialsConfig.EMPTY_CREDENTIALS_CONFIG;\n }",
"protected String pauseMsg() throws IOException {\n final WorkerStatus status = new WorkerStatus();\n status.setRunAt(new Date());\n status.setPaused(isPaused());\n return ObjectMapperFactory.get().writeValueAsString(status);\n }",
"public static DocumentBuilder getXmlParser() {\r\n DocumentBuilder db = null;\r\n try {\r\n DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\r\n dbf.setValidating(false);\r\n\r\n //Disable DTD loading and validation\r\n //See http://stackoverflow.com/questions/155101/make-documentbuilder-parse-ignore-dtd-references\r\n dbf.setFeature(\"http://apache.org/xml/features/nonvalidating/load-dtd-grammar\", false);\r\n dbf.setFeature(\"http://apache.org/xml/features/nonvalidating/load-external-dtd\", false);\r\n\r\n db = dbf.newDocumentBuilder();\r\n db.setErrorHandler(new SAXErrorHandler());\r\n\r\n } catch (ParserConfigurationException e) {\r\n System.err.printf(\"%s: Unable to create XML parser\\n\", XMLUtils.class.getName());\r\n e.printStackTrace();\r\n\r\n } catch(UnsupportedOperationException e) {\r\n System.err.printf(\"%s: API error while setting up XML parser. Check your JAXP version\\n\", XMLUtils.class.getName());\r\n e.printStackTrace();\r\n }\r\n\r\n return db;\r\n }",
"public List<Dependency> getModuleDependencies(final String moduleName, final String moduleVersion, final Boolean fullRecursive, final Boolean corporate, final Boolean thirdParty) throws GrapesCommunicationException {\n final Client client = getClient();\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactDependencies(moduleName, moduleVersion));\n final ClientResponse response = resource.queryParam(ServerAPI.SCOPE_COMPILE_PARAM, \"true\")\n .queryParam(ServerAPI.SCOPE_PROVIDED_PARAM, \"true\")\n .queryParam(ServerAPI.SCOPE_RUNTIME_PARAM, \"true\")\n .queryParam(ServerAPI.SCOPE_TEST_PARAM, \"true\")\n .queryParam(ServerAPI.RECURSIVE_PARAM, fullRecursive.toString())\n .queryParam(ServerAPI.SHOW_CORPORATE_PARAM, corporate.toString())\n .queryParam(ServerAPI.SHOW_THIRPARTY_PARAM, thirdParty.toString())\n .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = String.format(FAILED_TO_GET_MODULE, \"get module ancestors \", moduleName, moduleVersion);\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\n return response.getEntity(new GenericType<List<Dependency>>(){});\n }",
"@SuppressWarnings(\"unchecked\")\n\tprivate void addParameters(Model model, HttpServletRequest request) {\n\t\tfor (Object objectEntry : request.getParameterMap().entrySet()) {\n\t\t\tMap.Entry<String, String[]> entry = (Map.Entry<String, String[]>) objectEntry;\n\t\t\tString key = entry.getKey();\n\t\t\tString[] values = entry.getValue();\n\t\t\tif (null != values && values.length > 0) {\n\t\t\t\tString value = values[0];\n\t\t\t\ttry {\n\t\t\t\t\tmodel.addAttribute(key, getParameter(key, value));\n\t\t\t\t} catch (ParseException pe) {\n\t\t\t\t\tlog.error(\"Could not parse parameter value {} for {}, ignoring parameter.\", key, value);\n\t\t\t\t} catch (NumberFormatException nfe) {\n\t\t\t\t\tlog.error(\"Could not parse parameter value {} for {}, ignoring parameter.\", key, value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}"
] |
Build a Count-Query based on aQuery
@param aQuery
@return The count query | [
"public Query getCountQuery(Query aQuery)\r\n {\r\n if(aQuery instanceof QueryBySQL)\r\n {\r\n return getQueryBySqlCount((QueryBySQL) aQuery);\r\n }\r\n else if(aQuery instanceof ReportQueryByCriteria)\r\n {\r\n return getReportQueryByCriteriaCount((ReportQueryByCriteria) aQuery);\r\n }\r\n else\r\n {\r\n return getQueryByCriteriaCount((QueryByCriteria) aQuery);\r\n }\r\n }"
] | [
"private void ensureNoTableInfoIfNoRepositoryInfo(ClassDescriptorDef classDef, String checkLevel)\r\n {\r\n if (!classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_REPOSITORY_INFO, true))\r\n {\r\n classDef.setProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, \"false\");\r\n }\r\n }",
"private void writeDateField(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 Date val = (Date) value;\n m_writer.writeNameValuePair(fieldName, val);\n }\n }",
"public static void scaleRow( double alpha , DMatrixRMaj A , int row ) {\n int idx = row*A.numCols;\n for (int col = 0; col < A.numCols; col++) {\n A.data[idx++] *= alpha;\n }\n }",
"private void merge(ExecutionStatistics otherStatistics) {\n for (String s : otherStatistics.executionInfo.keySet())\n {\n TimingData thisStats = this.executionInfo.get(s);\n TimingData otherStats = otherStatistics.executionInfo.get(s);\n if(thisStats == null) {\n this.executionInfo.put(s,otherStats);\n } else {\n thisStats.merge(otherStats);\n }\n\n }\n }",
"protected boolean equivalentClaims(Claim claim1, Claim claim2) {\n\t\treturn claim1.getMainSnak().equals(claim2.getMainSnak())\n\t\t\t\t&& isSameSnakSet(claim1.getAllQualifiers(),\n\t\t\t\t\t\tclaim2.getAllQualifiers());\n\t}",
"public Set<String> rangeByRankReverse(final long start, final long end) {\n return doWithJedis(new JedisCallable<Set<String>>() {\n @Override\n public Set<String> call(Jedis jedis) {\n return jedis.zrevrange(getKey(), start, end);\n }\n });\n }",
"String deriveGroupIdFromPackages(ProjectModel projectModel)\n {\n Map<Object, Long> pkgsMap = new HashMap<>();\n Set<String> pkgs = new HashSet<>(1000);\n GraphTraversal<Vertex, Vertex> pipeline = new GraphTraversalSource(graphContext.getGraph()).V(projectModel);\n\n\n pkgsMap = pipeline.out(ProjectModel.PROJECT_MODEL_TO_FILE)\n .has(WindupVertexFrame.TYPE_PROP, new P(new BiPredicate<String, String>() {\n @Override\n public boolean test(String o, String o2) {\n return o.contains(o2);\n }\n },\n GraphTypeManager.getTypeValue(JavaClassFileModel.class)))\n .hasKey(JavaClassFileModel.PROPERTY_PACKAGE_NAME)\n .groupCount()\n .by(v -> upToThirdDot(graphContext, (Vertex)v)).toList().get(0);\n\n Map.Entry<Object, Long> biggest = null;\n for (Map.Entry<Object, Long> entry : pkgsMap.entrySet())\n {\n if (biggest == null || biggest.getValue() < entry.getValue())\n biggest = entry;\n }\n // More than a half is of this package.\n if (biggest != null && biggest.getValue() > pkgsMap.size() / 2)\n return biggest.getKey().toString();\n\n return null;\n }",
"private String trim(String line) {\n char[] chars = line.toCharArray();\n int len = chars.length;\n\n while (len > 0) {\n if (!Character.isWhitespace(chars[len - 1])) {\n break;\n }\n len--;\n }\n\n return line.substring(0, len);\n }",
"public Object getProperty(Object object) {\n return java.lang.reflect.Array.getLength(object);\n }"
] |
Test a given date for being easter sunday.
The method uses the algorithms sometimes cited as Meeus,Jones, Butcher Gregorian algorithm.
Taken from http://en.wikipedia.org/wiki/Computus
@param date The date to check.
@return True, if date is easter sunday. | [
"public static boolean isEasterSunday(LocalDate date) {\n\t\tint y = date.getYear();\n\t\tint a = y % 19;\n\t\tint b = y / 100;\n\t\tint c = y % 100;\n\t\tint d = b / 4;\n\t\tint e = b % 4;\n\t\tint f = (b + 8) / 25;\n\t\tint g = (b - f + 1) / 3;\n\t\tint h = (19 * a + b - d - g + 15) % 30;\n\t\tint i = c / 4;\n\t\tint k = c % 4;\n\t\tint l = (32 + 2 * e + 2 * i - h - k) % 7;\n\t\tint m = (a + 11 * h + 22 * l) / 451;\n\t\tint easterSundayMonth\t= (h + l - 7 * m + 114) / 31;\n\t\tint easterSundayDay\t\t= ((h + l - 7 * m + 114) % 31) + 1;\n\n\t\tint month = date.getMonthValue();\n\t\tint day = date.getDayOfMonth();\n\n\t\treturn (easterSundayMonth == month) && (easterSundayDay == day);\n\t}"
] | [
"public static appfwglobal_auditsyslogpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tappfwglobal_auditsyslogpolicy_binding obj = new appfwglobal_auditsyslogpolicy_binding();\n\t\tappfwglobal_auditsyslogpolicy_binding response[] = (appfwglobal_auditsyslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public IdRange[] parseIdRange(ImapRequestLineReader request)\n throws ProtocolException {\n CharacterValidator validator = new MessageSetCharValidator();\n String nextWord = consumeWord(request, validator);\n\n int commaPos = nextWord.indexOf(',');\n if (commaPos == -1) {\n return new IdRange[]{IdRange.parseRange(nextWord)};\n }\n\n List<IdRange> rangeList = new ArrayList<>();\n int pos = 0;\n while (commaPos != -1) {\n String range = nextWord.substring(pos, commaPos);\n IdRange set = IdRange.parseRange(range);\n rangeList.add(set);\n\n pos = commaPos + 1;\n commaPos = nextWord.indexOf(',', pos);\n }\n String range = nextWord.substring(pos);\n rangeList.add(IdRange.parseRange(range));\n return rangeList.toArray(new IdRange[rangeList.size()]);\n }",
"public static base_responses add(nitro_service client, gslbservice resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tgslbservice addresources[] = new gslbservice[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new gslbservice();\n\t\t\t\taddresources[i].servicename = resources[i].servicename;\n\t\t\t\taddresources[i].cnameentry = resources[i].cnameentry;\n\t\t\t\taddresources[i].ip = resources[i].ip;\n\t\t\t\taddresources[i].servername = resources[i].servername;\n\t\t\t\taddresources[i].servicetype = resources[i].servicetype;\n\t\t\t\taddresources[i].port = resources[i].port;\n\t\t\t\taddresources[i].publicip = resources[i].publicip;\n\t\t\t\taddresources[i].publicport = resources[i].publicport;\n\t\t\t\taddresources[i].maxclient = resources[i].maxclient;\n\t\t\t\taddresources[i].healthmonitor = resources[i].healthmonitor;\n\t\t\t\taddresources[i].sitename = resources[i].sitename;\n\t\t\t\taddresources[i].state = resources[i].state;\n\t\t\t\taddresources[i].cip = resources[i].cip;\n\t\t\t\taddresources[i].cipheader = resources[i].cipheader;\n\t\t\t\taddresources[i].sitepersistence = resources[i].sitepersistence;\n\t\t\t\taddresources[i].cookietimeout = resources[i].cookietimeout;\n\t\t\t\taddresources[i].siteprefix = resources[i].siteprefix;\n\t\t\t\taddresources[i].clttimeout = resources[i].clttimeout;\n\t\t\t\taddresources[i].svrtimeout = resources[i].svrtimeout;\n\t\t\t\taddresources[i].maxbandwidth = resources[i].maxbandwidth;\n\t\t\t\taddresources[i].downstateflush = resources[i].downstateflush;\n\t\t\t\taddresources[i].maxaaausers = resources[i].maxaaausers;\n\t\t\t\taddresources[i].monthreshold = resources[i].monthreshold;\n\t\t\t\taddresources[i].hashid = resources[i].hashid;\n\t\t\t\taddresources[i].comment = resources[i].comment;\n\t\t\t\taddresources[i].appflowlog = resources[i].appflowlog;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"private double u_neg_inf(double x, double tau) {\n\t\treturn f(boundaryCondition.getValueAtLowerBoundary(model, f_t(tau), f_s(x)), x, tau);\n\t}",
"public synchronized void shutdown() {\n checkIsRunning();\n try {\n beanManager().fireEvent(new ContainerBeforeShutdown(id), BeforeDestroyed.Literal.APPLICATION);\n } finally {\n discard(id);\n // Destroy all the dependent beans correctly\n creationalContext.release();\n beanManager().fireEvent(new ContainerShutdown(id), Destroyed.Literal.APPLICATION);\n bootstrap.shutdown();\n WeldSELogger.LOG.weldContainerShutdown(id);\n }\n }",
"public Map<String, MBeanOperationInfo> getOperationMetadata() {\n\n MBeanOperationInfo[] operations = mBeanInfo.getOperations();\n\n Map<String, MBeanOperationInfo> operationMap = new TreeMap<String, MBeanOperationInfo>();\n for (MBeanOperationInfo operation: operations) {\n operationMap.put(operation.getName(), operation);\n }\n return operationMap;\n }",
"@SuppressWarnings({ \"unchecked\" })\n public static <T> T[] readArrayAttributeElement(final XMLExtendedStreamReader reader, final String attributeName,\n final Class<T> type) throws XMLStreamException {\n final List<T> list = readListAttributeElement(reader, attributeName, type);\n return list.toArray((T[]) Array.newInstance(type, list.size()));\n }",
"private Integer highlanderMode(JobDef jd, DbConn cnx)\n {\n if (!jd.isHighlander())\n {\n return null;\n }\n\n try\n {\n Integer existing = cnx.runSelectSingle(\"ji_select_existing_highlander\", Integer.class, jd.getId());\n return existing;\n }\n catch (NoResultException ex)\n {\n // Just continue, this means no existing waiting JI in queue.\n }\n\n // Now we need to actually synchronize through the database to avoid double posting\n // TODO: use a dedicated table, not the JobDef one. Will avoid locking the configuration.\n ResultSet rs = cnx.runSelect(true, \"jd_select_by_id\", jd.getId());\n\n // Now we have a lock, just retry - some other client may have created a job instance recently.\n try\n {\n Integer existing = cnx.runSelectSingle(\"ji_select_existing_highlander\", Integer.class, jd.getId());\n rs.close();\n cnx.commit(); // Do not keep the lock!\n return existing;\n }\n catch (NoResultException ex)\n {\n // Just continue, this means no existing waiting JI in queue. We keep the lock!\n }\n catch (SQLException e)\n {\n // Who cares.\n jqmlogger.warn(\"Issue when closing a ResultSet. Transaction or session leak is possible.\", e);\n }\n\n jqmlogger.trace(\"Highlander mode analysis is done: nor existing JO, must create a new one. Lock is hold.\");\n return null;\n }",
"public static long hash(final BsonDocument doc) {\n if (doc == null) {\n return 0L;\n }\n\n final byte[] docBytes = toBytes(doc);\n long hashValue = FNV_64BIT_OFFSET_BASIS;\n\n for (int offset = 0; offset < docBytes.length; offset++) {\n hashValue ^= (0xFF & docBytes[offset]);\n hashValue *= FNV_64BIT_PRIME;\n }\n\n return hashValue;\n }"
] |
Stops the playback of a sound and destroys the corresponding Sound Object or Soundfield. | [
"public void stop()\n {\n if (mAudioListener != null)\n {\n Log.d(\"SOUND\", \"stopping audio source %d %s\", getSourceId(), getSoundFile());\n mAudioListener.getAudioEngine().stopSound(getSourceId());\n }\n }"
] | [
"public 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}",
"private void readUnread(CommitData cd, Consumer<Entry<Key, Value>> locksSeen) {\n // TODO make async\n // TODO need to keep track of ranges read (not ranges passed in, but actual data read... user\n // may not iterate over entire range\n Map<Bytes, Set<Column>> columnsToRead = new HashMap<>();\n\n for (Entry<Bytes, Set<Column>> entry : cd.getRejected().entrySet()) {\n Set<Column> rowColsRead = columnsRead.get(entry.getKey());\n if (rowColsRead == null) {\n columnsToRead.put(entry.getKey(), entry.getValue());\n } else {\n HashSet<Column> colsToRead = new HashSet<>(entry.getValue());\n colsToRead.removeAll(rowColsRead);\n if (!colsToRead.isEmpty()) {\n columnsToRead.put(entry.getKey(), colsToRead);\n }\n }\n }\n\n for (Entry<Bytes, Set<Column>> entry : columnsToRead.entrySet()) {\n getImpl(entry.getKey(), entry.getValue(), locksSeen);\n }\n }",
"static String fromPackageName(String packageName) {\n List<String> tokens = tokenOf(packageName);\n return fromTokens(tokens);\n }",
"public String getUnicodeString(Integer id, Integer type)\n {\n return (getUnicodeString(m_meta.getOffset(id, type)));\n }",
"private void generateWrappingPart(WrappingHint.Builder builder) {\n builder.setWrappingMethodOwnerName(configuration.UNMODIFIABLE_METHOD_OWNER)\n .setWrappingMethodName(configuration.FIELD_TYPE_TO_UNMODIFIABLE_METHOD.get(typeAssignedToField));\n }",
"public static String getDateTimeStrStandard(Date d) {\n if (d == null)\n return \"\";\n\n if (d.getTime() == 0L)\n return \"Never\";\n\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy.MM.dd.HH.mm.ss.SSSZ\");\n\n return sdf.format(d);\n }",
"public void setCastShadow(boolean enableFlag)\n {\n GVRSceneObject owner = getOwnerObject();\n\n if (owner != null)\n {\n GVRShadowMap shadowMap = (GVRShadowMap) getComponent(GVRRenderTarget.getComponentType());\n if (enableFlag)\n {\n if (shadowMap != null)\n {\n shadowMap.setEnable(true);\n }\n else\n {\n float angle = (float) Math.acos(getFloat(\"outer_cone_angle\")) * 2.0f;\n GVRCamera shadowCam = GVRShadowMap.makePerspShadowCamera(getGVRContext().getMainScene().getMainCameraRig().getCenterCamera(), angle);\n shadowMap = new GVRShadowMap(getGVRContext(), shadowCam);\n owner.attachComponent(shadowMap);\n }\n mChanged.set(true);\n }\n else if (shadowMap != null)\n {\n shadowMap.setEnable(false);\n }\n }\n mCastShadow = enableFlag;\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 String dir = null;\n List<Integer> nodeIds = null;\n Boolean allNodes = true;\n Boolean verbose = false;\n\n // parse command-line input\n args = AdminToolUtils.copyArrayAddFirst(args, \"--\" + OPT_HEAD_META_GET);\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);\n AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);\n AdminParserUtils.checkOptional(options,\n AdminParserUtils.OPT_NODE,\n AdminParserUtils.OPT_ALL_NODES);\n\n // load parameters\n metaKeys = (List<String>) options.valuesOf(OPT_HEAD_META_GET);\n url = (String) options.valueOf(AdminParserUtils.OPT_URL);\n if(options.has(AdminParserUtils.OPT_DIR)) {\n dir = (String) options.valueOf(AdminParserUtils.OPT_DIR);\n }\n if(options.has(AdminParserUtils.OPT_NODE)) {\n nodeIds = (List<Integer>) options.valuesOf(AdminParserUtils.OPT_NODE);\n allNodes = false;\n }\n if(options.has(OPT_VERBOSE)) {\n verbose = true;\n }\n\n // execute command\n File directory = AdminToolUtils.createDir(dir);\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 for(Object key: MetadataStore.METADATA_KEYS) {\n metaKeys.add((String) key);\n }\n }\n\n doMetaGet(adminClient, nodeIds, metaKeys, directory, verbose);\n }",
"private String[] getDatePatterns(ProjectProperties properties)\n {\n String pattern = \"\";\n\n char datesep = properties.getDateSeparator();\n DateOrder dateOrder = properties.getDateOrder();\n\n switch (dateOrder)\n {\n case DMY:\n {\n pattern = \"dd\" + datesep + \"MM\" + datesep + \"yy\";\n break;\n }\n\n case MDY:\n {\n pattern = \"MM\" + datesep + \"dd\" + datesep + \"yy\";\n break;\n }\n\n case YMD:\n {\n pattern = \"yy\" + datesep + \"MM\" + datesep + \"dd\";\n break;\n }\n }\n\n return new String[]\n {\n pattern\n };\n }"
] |
Execute for result.
@param executionContext the execution context
@return the result
@throws IOException for any error | [
"private OperationResponse executeForResult(final OperationExecutionContext executionContext) throws IOException {\n try {\n return execute(executionContext).get();\n } catch(Exception e) {\n throw new IOException(e);\n }\n }"
] | [
"private AffineTransform getAlignmentTransform() {\n final int offsetX;\n switch (this.settings.getParams().getAlign()) {\n case LEFT:\n offsetX = 0;\n break;\n case RIGHT:\n offsetX = this.settings.getMaxSize().width - this.settings.getSize().width;\n break;\n case CENTER:\n default:\n offsetX = (int) Math\n .floor(this.settings.getMaxSize().width / 2.0 - this.settings.getSize().width / 2.0);\n break;\n }\n\n final int offsetY;\n switch (this.settings.getParams().getVerticalAlign()) {\n case TOP:\n offsetY = 0;\n break;\n case BOTTOM:\n offsetY = this.settings.getMaxSize().height - this.settings.getSize().height;\n break;\n case MIDDLE:\n default:\n offsetY = (int) Math.floor(this.settings.getMaxSize().height / 2.0 -\n this.settings.getSize().height / 2.0);\n break;\n }\n\n return AffineTransform.getTranslateInstance(Math.round(offsetX), Math.round(offsetY));\n }",
"public final void setConfigurationFiles(final Map<String, String> configurationFiles)\n throws URISyntaxException {\n this.configurationFiles.clear();\n this.configurationFileLastModifiedTimes.clear();\n for (Map.Entry<String, String> entry: configurationFiles.entrySet()) {\n if (!entry.getValue().contains(\":/\")) {\n // assume is a file\n this.configurationFiles.put(entry.getKey(), new File(entry.getValue()).toURI());\n } else {\n this.configurationFiles.put(entry.getKey(), new URI(entry.getValue()));\n }\n }\n\n if (this.configFileLoader != null) {\n this.validateConfigurationFiles();\n }\n }",
"public static long count(nitro_service service, Long id) throws Exception{\n\t\tbridgegroup_vlan_binding obj = new bridgegroup_vlan_binding();\n\t\tobj.set_id(id);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tbridgegroup_vlan_binding response[] = (bridgegroup_vlan_binding[]) obj.get_resources(service,option);\n\t\tif (response != null) {\n\t\t\treturn response[0].__count;\n\t\t}\n\t\treturn 0;\n\t}",
"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}",
"protected void reportWorked(int workIncrement, int currentUnitIndex) {\n if (this.progress != null) {\n if (this.progress.isCanceled()) {\n // Only AbortCompilation can stop the compiler cleanly.\n // We check cancellation again following the call to compile.\n throw new AbortCompilation(true, null);\n }\n this.progress.worked(workIncrement, (this.totalUnits* this.remainingIterations) - currentUnitIndex - 1);\n }\n }",
"public void setDates(SortedSet<Date> dates) {\n\n if (!m_model.getIndividualDates().equals(dates)) {\n m_model.setIndividualDates(dates);\n onValueChange();\n }\n\n }",
"public static CmsSolrSpellchecker getInstance(CoreContainer container) {\n\n if (null == instance) {\n synchronized (CmsSolrSpellchecker.class) {\n if (null == instance) {\n @SuppressWarnings(\"resource\")\n SolrCore spellcheckCore = container.getCore(CmsSolrSpellchecker.SPELLCHECKER_INDEX_CORE);\n if (spellcheckCore == null) {\n LOG.error(\n Messages.get().getBundle().key(\n Messages.ERR_SPELLCHECK_CORE_NOT_AVAILABLE_1,\n CmsSolrSpellchecker.SPELLCHECKER_INDEX_CORE));\n return null;\n }\n instance = new CmsSolrSpellchecker(container, spellcheckCore);\n }\n }\n }\n\n return instance;\n }",
"public static URL codeLocationFromPath(String filePath) {\n try {\n return new File(filePath).toURI().toURL();\n } catch (Exception e) {\n throw new InvalidCodeLocation(filePath);\n }\n }",
"public static <T extends HasWord> TokenizerFactory<T> factory(LexedTokenFactory<T> factory, String options) {\r\n return new PTBTokenizerFactory<T>(factory, options);\r\n\r\n }"
] |
Add the elements that all values objects require from the provided values object.
@param sourceValues the values object containing the required elements | [
"public void addRequiredValues(@Nonnull final Values sourceValues) {\n Object taskDirectory = sourceValues.getObject(TASK_DIRECTORY_KEY, Object.class);\n MfClientHttpRequestFactoryProvider requestFactoryProvider =\n sourceValues.getObject(CLIENT_HTTP_REQUEST_FACTORY_KEY,\n MfClientHttpRequestFactoryProvider.class);\n Template template = sourceValues.getObject(TEMPLATE_KEY, Template.class);\n PDFConfig pdfConfig = sourceValues.getObject(PDF_CONFIG_KEY, PDFConfig.class);\n String subReportDir = sourceValues.getString(SUBREPORT_DIR_KEY);\n\n this.values.put(TASK_DIRECTORY_KEY, taskDirectory);\n this.values.put(CLIENT_HTTP_REQUEST_FACTORY_KEY, requestFactoryProvider);\n this.values.put(TEMPLATE_KEY, template);\n this.values.put(PDF_CONFIG_KEY, pdfConfig);\n this.values.put(SUBREPORT_DIR_KEY, subReportDir);\n this.values.put(VALUES_KEY, this);\n this.values.put(JOB_ID_KEY, sourceValues.getString(JOB_ID_KEY));\n this.values.put(LOCALE_KEY, sourceValues.getObject(LOCALE_KEY, Locale.class));\n }"
] | [
"public void setFileFormat(String fileFormat) {\n\n if (fileFormat.toUpperCase().equals(FileFormat.JSON.toString())) {\n m_fileFormat = FileFormat.JSON;\n }\n }",
"@UiThread\n public int getParentAdapterPosition() {\n int flatPosition = getAdapterPosition();\n if (mExpandableAdapter == null || flatPosition == RecyclerView.NO_POSITION) {\n return RecyclerView.NO_POSITION;\n }\n\n return mExpandableAdapter.getNearestParentPosition(flatPosition);\n }",
"protected void checkProducerMethod(EnhancedAnnotatedMethod<T, ? super X> method) {\n if (method.getEnhancedParameters(Observes.class).size() > 0) {\n throw BeanLogger.LOG.inconsistentAnnotationsOnMethod(PRODUCER_ANNOTATION, \"@Observes\", this.method,\n Formats.formatAsStackTraceElement(method.getJavaMember()));\n } else if (method.getEnhancedParameters(ObservesAsync.class).size() > 0) {\n throw BeanLogger.LOG.inconsistentAnnotationsOnMethod(PRODUCER_ANNOTATION, \"@ObservesAsync\", this.method,\n Formats.formatAsStackTraceElement(method.getJavaMember()));\n } else if (method.getEnhancedParameters(Disposes.class).size() > 0) {\n throw BeanLogger.LOG.inconsistentAnnotationsOnMethod(PRODUCER_ANNOTATION, \"@Disposes\", this.method,\n Formats.formatAsStackTraceElement(method.getJavaMember()));\n } else if (getDeclaringBean() instanceof SessionBean<?> && !Modifier.isStatic(method.slim().getJavaMember().getModifiers())) {\n boolean methodDeclaredOnTypes = false;\n for (Type type : getDeclaringBean().getTypes()) {\n Class<?> clazz = Reflections.getRawType(type);\n try {\n AccessController.doPrivileged(new GetMethodAction(clazz, method.getName(), method.getParameterTypesAsArray()));\n methodDeclaredOnTypes = true;\n break;\n } catch (PrivilegedActionException ignored) {\n }\n }\n if (!methodDeclaredOnTypes) {\n throw BeanLogger.LOG.methodNotBusinessMethod(\"Producer\", this, getDeclaringBean(), Formats.formatAsStackTraceElement(method.getJavaMember()));\n }\n }\n }",
"private InputStream runSparqlQuery(String query) throws IOException {\n\t\ttry {\n\t\t\tString queryString = \"query=\" + URLEncoder.encode(query, \"UTF-8\")\n\t\t\t\t\t+ \"&format=json\";\n\t\t\tURL url = new URL(\"https://query.wikidata.org/sparql?\"\n\t\t\t\t\t+ queryString);\n\t\t\tHttpURLConnection connection = (HttpURLConnection) url\n\t\t\t\t\t.openConnection();\n\t\t\tconnection.setRequestMethod(\"GET\");\n\n\t\t\treturn connection.getInputStream();\n\t\t} catch (UnsupportedEncodingException | MalformedURLException e) {\n\t\t\tthrow new RuntimeException(e.getMessage(), e);\n\t\t}\n\t}",
"public static <T> String join(Collection<T> col, String delim) {\n StringBuilder sb = new StringBuilder();\n Iterator<T> iter = col.iterator();\n if (iter.hasNext())\n sb.append(iter.next().toString());\n while (iter.hasNext()) {\n sb.append(delim);\n sb.append(iter.next().toString());\n }\n return sb.toString();\n }",
"public T findById(Object id) throws RowNotFoundException, TooManyRowsException {\n return findWhere(eq(idColumn.getColumnName(), id)).getSingleResult();\n }",
"protected void parseIntegerLists(TokenList tokens) {\n TokenList.Token t = tokens.getFirst();\n if( t == null || t.next == null )\n return;\n\n int state = 0;\n\n TokenList.Token start = null;\n TokenList.Token prev = t;\n\n boolean last = false;\n while( true ) {\n if( state == 0 ) {\n if( isVariableInteger(t) ) {\n start = t;\n state = 1;\n }\n } else if( state == 1 ) {\n // var ?\n if( isVariableInteger(t)) { // see if its explicit number sequence\n state = 2;\n } else { // just scalar integer, skip\n state = 0;\n }\n } else if ( state == 2 ) {\n // var var ....\n if( !isVariableInteger(t) ) {\n // create explicit list sequence\n IntegerSequence sequence = new IntegerSequence.Explicit(start,prev);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(sequence);\n replaceSequence(tokens, varSequence, start, prev);\n state = 0;\n }\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 Jar setJarPrefix(String value) {\n verifyNotSealed();\n if (jos != null)\n throw new IllegalStateException(\"Really executable cannot be set after entries are added.\");\n if (value != null && jarPrefixFile != null)\n throw new IllegalStateException(\"A prefix has already been set (\" + jarPrefixFile + \")\");\n this.jarPrefixStr = value;\n return this;\n }",
"public static String entityToString(HttpEntity entity) throws IOException {\n if (entity != null) {\n InputStream is = entity.getContent();\n return IOUtils.toString(is, \"UTF-8\");\n }\n return \"\";\n }"
] |
Use this API to fetch appfwprofile_csrftag_binding resources of given name . | [
"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 final String getUnicodeString(byte[] data, int offset)\n {\n int length = getUnicodeStringLengthInBytes(data, offset);\n return length == 0 ? \"\" : new String(data, offset, length, CharsetHelper.UTF16LE);\n }",
"public void rollback()\r\n {\r\n try\r\n {\r\n Iterator iter = mvOrderOfIds.iterator();\r\n while(iter.hasNext())\r\n {\r\n ObjectEnvelope mod = (ObjectEnvelope) mhtObjectEnvelopes.get(iter.next());\r\n if(log.isDebugEnabled())\r\n log.debug(\"rollback: \" + mod);\r\n // if the Object has been modified by transaction, mark object as dirty\r\n if(mod.hasChanged(transaction.getBroker()))\r\n {\r\n mod.setModificationState(mod.getModificationState().markDirty());\r\n }\r\n mod.getModificationState().rollback(mod);\r\n }\r\n }\r\n finally\r\n {\r\n needsCommit = false;\r\n }\r\n afterWriteCleanup();\r\n }",
"protected String sourceLineTrimmed(ASTNode node) {\r\n return sourceCode.line(AstUtil.findFirstNonAnnotationLine(node, sourceCode) - 1);\r\n }",
"private String getTimeString(Date value)\n {\n Calendar cal = DateHelper.popCalendar(value);\n int hours = cal.get(Calendar.HOUR_OF_DAY);\n int minutes = cal.get(Calendar.MINUTE);\n DateHelper.pushCalendar(cal);\n \n StringBuilder sb = new StringBuilder(4);\n sb.append(m_twoDigitFormat.format(hours));\n sb.append(m_twoDigitFormat.format(minutes));\n\n return (sb.toString());\n }",
"public File getBootFile() {\n if (bootFile == null) {\n synchronized (this) {\n if (bootFile == null) {\n if (bootFileReset) {\n //Reset the done bootup and the sequence, so that the old file we are reloading from\n // overwrites the main file on successful boot, and history is reset as when booting new\n doneBootup.set(false);\n sequence.set(0);\n }\n // If it's a reload with no new boot file name and we're persisting our config, we boot from mainFile,\n // as that's where we persist\n if (bootFileReset && !interactionPolicy.isReadOnly() && newReloadBootFileName == null) {\n // we boot from mainFile\n bootFile = mainFile;\n } else {\n // It's either first boot, or a reload where we're not persisting our config or with a new boot file.\n // So we need to figure out which file we're meant to boot from\n\n String bootFileName = this.bootFileName;\n if (newReloadBootFileName != null) {\n //A non-null new boot file on reload takes precedence over the reloadUsingLast functionality\n //A new boot file was specified. Use that and reset the new name to null\n bootFileName = newReloadBootFileName;\n newReloadBootFileName = null;\n } else if (interactionPolicy.isReadOnly() && reloadUsingLast) {\n //If we were reloaded, and it is not a persistent configuration we want to use the last from the history\n bootFileName = LAST;\n }\n boolean usingRawFile = bootFileName.equals(rawFileName);\n if (usingRawFile) {\n bootFile = mainFile;\n } else {\n bootFile = determineBootFile(configurationDir, bootFileName);\n try {\n bootFile = bootFile.getCanonicalFile();\n } catch (IOException ioe) {\n throw ControllerLogger.ROOT_LOGGER.canonicalBootFileNotFound(ioe, bootFile);\n }\n }\n\n\n if (!bootFile.exists()) {\n if (!usingRawFile) { // TODO there's no reason usingRawFile should be an exception,\n // but the test infrastructure stuff is built around an assumption\n // that ConfigurationFile doesn't fail if test files are not\n // in the normal spot\n if (bootFileReset || interactionPolicy.isRequireExisting()) {\n throw ControllerLogger.ROOT_LOGGER.fileNotFound(bootFile.getAbsolutePath());\n }\n }\n // Create it for the NEW and DISCARD cases\n if (!bootFileReset && !interactionPolicy.isRequireExisting()) {\n createBootFile(bootFile);\n }\n } else if (!bootFileReset) {\n if (interactionPolicy.isRejectExisting() && bootFile.length() > 0) {\n throw ControllerLogger.ROOT_LOGGER.rejectEmptyConfig(bootFile.getAbsolutePath());\n } else if (interactionPolicy.isRemoveExisting() && bootFile.length() > 0) {\n if (!bootFile.delete()) {\n throw ControllerLogger.ROOT_LOGGER.cannotDelete(bootFile.getAbsoluteFile());\n }\n createBootFile(bootFile);\n }\n } // else after first boot we want the file to exist\n }\n }\n }\n }\n return bootFile;\n }",
"public void addItem(T value, Direction dir, String text) {\n addItem(value, dir, text, true);\n }",
"public static Field read(DataInputStream is) throws IOException {\n final byte tag = is.readByte();\n final Field result;\n switch (tag) {\n case 0x0f:\n case 0x10:\n case 0x11:\n result = new NumberField(tag, is);\n break;\n\n case 0x14:\n result = new BinaryField(is);\n break;\n\n case 0x26:\n result = new StringField(is);\n break;\n\n default:\n throw new IOException(\"Unable to read a field with type tag \" + tag);\n }\n\n logger.debug(\"..received> {}\", result);\n return result;\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<CopticDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<CopticDate>) super.zonedDateTime(temporal);\n }",
"private boolean isToIgnore(CtElement element) {\n\t\tif (element instanceof CtStatementList && !(element instanceof CtCase)) {\n\t\t\tif (element.getRoleInParent() == CtRole.ELSE || element.getRoleInParent() == CtRole.THEN) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn element.isImplicit() || element instanceof CtReference;\n\t}"
] |
Replies the elements of the given map except the pairs with the given keys.
<p>
The replied map is a view on the given map. It means that any change
in the original map is reflected to the result of this operation.
</p>
@param <K> type of the map keys.
@param <V> type of the map values.
@param map the map to update.
@param keys the keys of the pairs to remove.
@return the map with the content of the map except the pairs.
@since 2.15 | [
"@Pure\n\tpublic static <K, V> Map<K, V> operator_minus(Map<K, V> map, final Iterable<?> keys) {\n\t\treturn Maps.filterKeys(map, new Predicate<K>() {\n\t\t\t@Override\n\t\t\tpublic boolean apply(K input) {\n\t\t\t\treturn !Iterables.contains(keys, input);\n\t\t\t}\n\t\t});\n\t}"
] | [
"public static void startCheck(String extra) {\n startCheckTime = System.currentTimeMillis();\n nextCheckTime = startCheckTime;\n Log.d(Log.SUBSYSTEM.TRACING, \"FPSCounter\" , \"[%d] startCheck %s\", startCheckTime, extra);\n }",
"public static base_response add(nitro_service client, sslaction resource) throws Exception {\n\t\tsslaction addresource = new sslaction();\n\t\taddresource.name = resource.name;\n\t\taddresource.clientauth = resource.clientauth;\n\t\taddresource.clientcert = resource.clientcert;\n\t\taddresource.certheader = resource.certheader;\n\t\taddresource.clientcertserialnumber = resource.clientcertserialnumber;\n\t\taddresource.certserialheader = resource.certserialheader;\n\t\taddresource.clientcertsubject = resource.clientcertsubject;\n\t\taddresource.certsubjectheader = resource.certsubjectheader;\n\t\taddresource.clientcerthash = resource.clientcerthash;\n\t\taddresource.certhashheader = resource.certhashheader;\n\t\taddresource.clientcertissuer = resource.clientcertissuer;\n\t\taddresource.certissuerheader = resource.certissuerheader;\n\t\taddresource.sessionid = resource.sessionid;\n\t\taddresource.sessionidheader = resource.sessionidheader;\n\t\taddresource.cipher = resource.cipher;\n\t\taddresource.cipherheader = resource.cipherheader;\n\t\taddresource.clientcertnotbefore = resource.clientcertnotbefore;\n\t\taddresource.certnotbeforeheader = resource.certnotbeforeheader;\n\t\taddresource.clientcertnotafter = resource.clientcertnotafter;\n\t\taddresource.certnotafterheader = resource.certnotafterheader;\n\t\taddresource.owasupport = resource.owasupport;\n\t\treturn addresource.add_resource(client);\n\t}",
"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}",
"public synchronized boolean put(byte value) {\n if (available == capacity) {\n return false;\n }\n buffer[idxPut] = value;\n idxPut = (idxPut + 1) % capacity;\n available++;\n return true;\n }",
"private static void listTasks(ProjectFile file)\n {\n SimpleDateFormat df = new SimpleDateFormat(\"dd/MM/yyyy HH:mm z\");\n\n for (Task task : file.getTasks())\n {\n Date date = task.getStart();\n String text = task.getStartText();\n String startDate = text != null ? text : (date != null ? df.format(date) : \"(no start date supplied)\");\n\n date = task.getFinish();\n text = task.getFinishText();\n String finishDate = text != null ? text : (date != null ? df.format(date) : \"(no finish date supplied)\");\n\n Duration dur = task.getDuration();\n text = task.getDurationText();\n String duration = text != null ? text : (dur != null ? dur.toString() : \"(no duration supplied)\");\n\n dur = task.getActualDuration();\n String actualDuration = dur != null ? dur.toString() : \"(no actual duration supplied)\";\n\n String baselineDuration = task.getBaselineDurationText();\n if (baselineDuration == null)\n {\n dur = task.getBaselineDuration();\n if (dur != null)\n {\n baselineDuration = dur.toString();\n }\n else\n {\n baselineDuration = \"(no duration supplied)\";\n }\n }\n\n System.out.println(\"Task: \" + task.getName() + \" ID=\" + task.getID() + \" Unique ID=\" + task.getUniqueID() + \" (Start Date=\" + startDate + \" Finish Date=\" + finishDate + \" Duration=\" + duration + \" Actual Duration\" + actualDuration + \" Baseline Duration=\" + baselineDuration + \" Outline Level=\" + task.getOutlineLevel() + \" Outline Number=\" + task.getOutlineNumber() + \" Recurring=\" + task.getRecurring() + \")\");\n }\n System.out.println();\n }",
"protected void setupRegistration() {\n if (isServiceWorkerSupported()) {\n Navigator.serviceWorker.register(getResource()).then(object -> {\n logger.info(\"Service worker has been successfully registered\");\n registration = (ServiceWorkerRegistration) object;\n\n onRegistered(new ServiceEvent(), registration);\n\n // Observe service worker lifecycle\n observeLifecycle(registration);\n\n // Setup Service Worker events events\n setupOnControllerChangeEvent();\n setupOnMessageEvent();\n setupOnErrorEvent();\n return null;\n }, error -> {\n logger.info(\"ServiceWorker registration failed: \" + error);\n return null;\n });\n } else {\n logger.info(\"Service worker is not supported by this browser.\");\n }\n }",
"public StochasticPathwiseLevenbergMarquardt getCloneWithModifiedTargetValues(List<RandomVariable> newTargetVaues, List<RandomVariable> newWeights, boolean isUseBestParametersAsInitialParameters) throws CloneNotSupportedException {\n\t\tStochasticPathwiseLevenbergMarquardt clonedOptimizer = clone();\n\t\tclonedOptimizer.targetValues = numberListToDoubleArray(newTargetVaues);\n\t\tclonedOptimizer.weights = numberListToDoubleArray(newWeights);\n\n\t\tif(isUseBestParametersAsInitialParameters && this.done()) {\n\t\t\tclonedOptimizer.initialParameters = this.getBestFitParameters();\n\t\t}\n\n\t\treturn clonedOptimizer;\n\t}",
"public final ZoomToFeatures copy() {\n ZoomToFeatures obj = new ZoomToFeatures();\n obj.zoomType = this.zoomType;\n obj.minScale = this.minScale;\n obj.minMargin = this.minMargin;\n return obj;\n }",
"public T insert(T entity) {\n\n if (!hasPrimaryKey(entity)) {\n throw new RuntimeException(String.format(\"Tried to insert entity of type %s with null or zero primary key\",\n entity.getClass().getSimpleName()));\n }\n\n InsertCreator insert = new InsertCreator(table);\n\n insert.setValue(idColumn.getColumnName(), getPrimaryKey(entity));\n\n if (versionColumn != null) {\n insert.setValue(versionColumn.getColumnName(), 0);\n }\n\n for (Column column : columns) {\n if (!column.isReadOnly()) {\n insert.setValue(column.getColumnName(), getFieldValueAsColumn(entity, column));\n }\n }\n\n new JdbcTemplate(ormConfig.getDataSource()).update(insert);\n\n if (versionColumn != null) {\n ReflectionUtils.setFieldValue(entity, versionColumn.getFieldName(), 0);\n }\n\n return entity;\n }"
] |
Used internally to find the solution to a single column vector. | [
"private void solveInternalL() {\n // This takes advantage of the diagonal elements always being real numbers\n\n // solve L*y=b storing y in x\n TriangularSolver_ZDRM.solveL_diagReal(t, vv, n);\n\n // solve L^T*x=y\n TriangularSolver_ZDRM.solveConjTranL_diagReal(t, vv, n);\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 int executeUpdate(String query) throws Exception {\n int returnVal = 0;\n Statement queryStatement = null;\n\n try (Connection sqlConnection = getConnection()) {\n queryStatement = sqlConnection.createStatement();\n returnVal = queryStatement.executeUpdate(query);\n } catch (Exception e) {\n } finally {\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return returnVal;\n }",
"public Membership getMembership() {\n URI uri = new URIBase(getBaseUri()).path(\"_membership\").build();\n Membership membership = couchDbClient.get(uri,\n Membership.class);\n return membership;\n }",
"@Override\n\tpublic String toFullString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = getStringCache().fullString) == null) {\n\t\t\tgetStringCache().fullString = result = toNormalizedString(IPv6StringCache.fullParams);\n\t\t}\n\t\treturn result;\n\t}",
"public Label htmlLabel(String html) {\n\n Label label = new Label();\n label.setContentMode(ContentMode.HTML);\n label.setValue(html);\n return label;\n\n }",
"public boolean isUpToDate(final DbArtifact artifact) {\n final List<String> versions = repoHandler.getArtifactVersions(artifact);\n final String currentVersion = artifact.getVersion();\n\n final String lastDevVersion = getLastVersion(versions);\n final String lastReleaseVersion = getLastRelease(versions);\n\n if(lastDevVersion == null || lastReleaseVersion == null) {\n // Plain Text comparison against version \"strings\"\n for(final String version: versions){\n if(version.compareTo(currentVersion) > 0){\n return false;\n }\n }\n return true;\n } else {\n return currentVersion.equals(lastDevVersion) || currentVersion.equals(lastReleaseVersion);\n }\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 }",
"@SuppressWarnings(\"unchecked\")\n public static void executeCommand(String[] args) throws IOException {\n\n OptionParser parser = getParser();\n\n // declare parameters\n String url = null;\n List<Integer> nodeIds = null;\n Boolean allNodes = true;\n Boolean confirm = false;\n\n // parse command-line input\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, AdminParserUtils.OPT_URL);\n AdminParserUtils.checkOptional(options,\n AdminParserUtils.OPT_NODE,\n AdminParserUtils.OPT_ALL_NODES);\n\n // load parameters\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 if(options.has(AdminParserUtils.OPT_CONFIRM)) {\n confirm = true;\n }\n\n // print summary\n System.out.println(\"Remove metadata related to rebalancing\");\n System.out.println(\"Location:\");\n System.out.println(\" bootstrap url = \" + url);\n if(allNodes) {\n System.out.println(\" node = all nodes\");\n } else {\n System.out.println(\" node = \" + Joiner.on(\", \").join(nodeIds));\n }\n\n // execute command\n if(!AdminToolUtils.askConfirm(confirm, \"remove metadata related to rebalancing\")) {\n return;\n }\n AdminClient adminClient = AdminToolUtils.getAdminClient(url);\n\n if(allNodes) {\n nodeIds = AdminToolUtils.getAllNodeIds(adminClient);\n }\n\n AdminToolUtils.assertServerNotInRebalancingState(adminClient, nodeIds);\n\n doMetaClearRebalance(adminClient, nodeIds);\n }",
"private void processDefaultCurrency(Integer currencyID) throws SQLException\n {\n List<Row> rows = getRows(\"select * from \" + m_schema + \"currtype where curr_id=?\", currencyID);\n if (!rows.isEmpty())\n {\n Row row = rows.get(0);\n m_reader.processDefaultCurrency(row);\n }\n }"
] |
Extracts the column from the matrix a.
@param a Input matrix
@param column Which column is to be extracted
@param out output. Storage for the extracted column. If null then a new vector will be returned.
@return The extracted column. | [
"public static DMatrix2 extractColumn( DMatrix2x2 a , int column , DMatrix2 out ) {\n if( out == null) out = new DMatrix2();\n switch( column ) {\n case 0:\n out.a1 = a.a11;\n out.a2 = a.a21;\n break;\n case 1:\n out.a1 = a.a12;\n out.a2 = a.a22;\n break;\n default:\n throw new IllegalArgumentException(\"Out of bounds column. column = \"+column);\n }\n return out;\n }"
] | [
"public void rotateWithPivot(float w, float x, float y, float z,\n float pivotX, float pivotY, float pivotZ) {\n getTransform().rotateWithPivot(w, x, y, z, pivotX, pivotY, pivotZ);\n if (mTransformCache.rotateWithPivot(w, x, y, z, pivotX, pivotY, pivotZ)) {\n onTransformChanged();\n }\n }",
"private void readResourceBaselines(Project.Resources.Resource xmlResource, Resource mpxjResource)\n {\n for (Project.Resources.Resource.Baseline baseline : xmlResource.getBaseline())\n {\n int number = NumberHelper.getInt(baseline.getNumber());\n\n Double cost = DatatypeConverter.parseCurrency(baseline.getCost());\n Duration work = DatatypeConverter.parseDuration(m_projectFile, TimeUnit.HOURS, baseline.getWork());\n\n if (number == 0)\n {\n mpxjResource.setBaselineCost(cost);\n mpxjResource.setBaselineWork(work);\n }\n else\n {\n mpxjResource.setBaselineCost(number, cost);\n mpxjResource.setBaselineWork(number, work);\n }\n }\n }",
"@RequestMapping(value = \"api/servergroup\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getServerGroups(Model model,\n @RequestParam(value = \"profileId\", required = false) Integer profileId,\n @RequestParam(value = \"search\", required = false) String search,\n @RequestParam(value = \"profileIdentifier\", required = false) String profileIdentifier) throws Exception {\n if (profileId == null && profileIdentifier == null) {\n throw new Exception(\"profileId required\");\n }\n if (profileId == null) {\n profileId = ProfileService.getInstance().getIdFromName(profileIdentifier);\n }\n\n List<ServerGroup> serverGroups = ServerRedirectService.getInstance().tableServerGroups(profileId);\n\n if (search != null) {\n Iterator<ServerGroup> iterator = serverGroups.iterator();\n while (iterator.hasNext()) {\n ServerGroup serverGroup = iterator.next();\n if (!serverGroup.getName().toLowerCase().contains(search.toLowerCase())) {\n iterator.remove();\n }\n }\n }\n HashMap<String, Object> returnJson = Utils.getJQGridJSON(serverGroups, \"servergroups\");\n return returnJson;\n }",
"protected static void writeErrorResponse(final Channel channel, final ManagementRequestHeader header, final Throwable error) throws IOException {\n final ManagementResponseHeader response = ManagementResponseHeader.create(header, error);\n final MessageOutputStream output = channel.writeMessage();\n try {\n writeHeader(response, output);\n output.close();\n } finally {\n StreamUtils.safeClose(output);\n }\n }",
"public static String format(final String code, final Properties options, final LineEnding lineEnding) {\n\t\tCheck.notEmpty(code, \"code\");\n\t\tCheck.notEmpty(options, \"options\");\n\t\tCheck.notNull(lineEnding, \"lineEnding\");\n\n\t\tfinal CodeFormatter formatter = ToolFactory.createCodeFormatter(options);\n\t\tfinal String lineSeparator = LineEnding.find(lineEnding, code);\n\t\tTextEdit te = null;\n\t\ttry {\n\t\t\tte = formatter.format(CodeFormatter.K_COMPILATION_UNIT, code, 0, code.length(), 0, lineSeparator);\n\t\t} catch (final Exception formatFailed) {\n\t\t\tLOG.warn(\"Formatting failed\", formatFailed);\n\t\t}\n\n\t\tString formattedCode = code;\n\t\tif (te == null) {\n\t\t\tLOG.info(\"Code cannot be formatted. Possible cause is unmatched source/target/compliance version.\");\n\t\t} else {\n\n\t\t\tfinal IDocument doc = new Document(code);\n\t\t\ttry {\n\t\t\t\tte.apply(doc);\n\t\t\t} catch (final Exception e) {\n\t\t\t\tLOG.warn(e.getLocalizedMessage(), e);\n\t\t\t}\n\t\t\tformattedCode = doc.get();\n\t\t}\n\t\treturn formattedCode;\n\t}",
"public static 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}",
"public Integer getGroupIdFromName(String groupName) {\n return (Integer) sqlService.getFromTable(Constants.GENERIC_ID, Constants.GROUPS_GROUP_NAME, groupName,\n Constants.DB_TABLE_GROUPS);\n }",
"public void initialize(FragmentManager fragmentManager) {\n AirMapInterface mapInterface = (AirMapInterface)\n fragmentManager.findFragmentById(R.id.map_frame);\n\n if (mapInterface != null) {\n initialize(fragmentManager, mapInterface);\n } else {\n initialize(fragmentManager, new DefaultAirMapViewBuilder(getContext()).builder().build());\n }\n }",
"public static aaauser_aaagroup_binding[] get(nitro_service service, String username) throws Exception{\n\t\taaauser_aaagroup_binding obj = new aaauser_aaagroup_binding();\n\t\tobj.set_username(username);\n\t\taaauser_aaagroup_binding response[] = (aaauser_aaagroup_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Use this API to fetch appfwprofile_crosssitescripting_binding resources of given name . | [
"public static appfwprofile_crosssitescripting_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_crosssitescripting_binding obj = new appfwprofile_crosssitescripting_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_crosssitescripting_binding response[] = (appfwprofile_crosssitescripting_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"private void writeBufferedValsToStorage() {\n List<Versioned<byte[]>> obsoleteVals = storageEngine.multiVersionPut(currBufferedKey,\n currBufferedVals);\n // log Obsolete versions in debug mode\n if(logger.isDebugEnabled() && obsoleteVals.size() > 0) {\n logger.debug(\"updateEntries (Streaming multi-version-put) rejected these versions as obsolete : \"\n + StoreUtils.getVersions(obsoleteVals) + \" for key \" + currBufferedKey);\n }\n currBufferedVals = new ArrayList<Versioned<byte[]>>(VALS_BUFFER_EXPECTED_SIZE);\n }",
"private int getMaxHeight() {\n int result = 0;\n for (int i = 0; i < segmentCount; i++) {\n result = Math.max(result, segmentHeight(i, false));\n }\n return result;\n }",
"public static void registerParams(DynamicJasperDesign jd, Map _parameters) {\n for (Object key : _parameters.keySet()) {\n if (key instanceof String) {\n try {\n Object value = _parameters.get(key);\n if (jd.getParametersMap().get(key) != null) {\n log.warn(\"Parameter \\\"\" + key + \"\\\" already registered, skipping this one: \" + value);\n continue;\n }\n\n JRDesignParameter parameter = new JRDesignParameter();\n\n if (value == null) //There are some Map implementations that allows nulls values, just go on\n continue;\n\n//\t\t\t\t\tparameter.setValueClassName(value.getClass().getCanonicalName());\n Class clazz = value.getClass().getComponentType();\n if (clazz == null)\n clazz = value.getClass();\n parameter.setValueClass(clazz); //NOTE this is very strange\n //when using an array as subreport-data-source, I must pass the parameter class name like this: value.getClass().getComponentType()\n parameter.setName((String) key);\n jd.addParameter(parameter);\n } catch (JRException e) {\n //nothing to do\n }\n }\n\n }\n\n }",
"public static final String decodePassword(byte[] data, byte encryptionCode)\n {\n String result;\n\n if (data.length < MINIMUM_PASSWORD_DATA_LENGTH)\n {\n result = null;\n }\n else\n {\n MPPUtility.decodeBuffer(data, encryptionCode);\n\n StringBuilder buffer = new StringBuilder();\n char c;\n\n for (int i = 0; i < PASSWORD_MASK.length; i++)\n {\n int index = PASSWORD_MASK[i];\n c = (char) data[index];\n\n if (c == 0)\n {\n break;\n }\n buffer.append(c);\n }\n\n result = buffer.toString();\n }\n\n return (result);\n }",
"public static ServiceActivator create(final ModelNode endpointConfig, final URI managementURI, final String serverName, final String serverProcessName,\n final String authKey, final boolean managementSubsystemEndpoint, final Supplier<SSLContext> sslContextSupplier) {\n\n return new DomainServerCommunicationServices(endpointConfig, managementURI, serverName, serverProcessName, authKey, managementSubsystemEndpoint, sslContextSupplier);\n }",
"public void setVolume(float volume)\n {\n // Save this in case this audio source is not being played yet\n mVolume = volume;\n if (isPlaying() && (getSourceId() != GvrAudioEngine.INVALID_ID))\n {\n // This will actually work only if the sound file is being played\n mAudioListener.getAudioEngine().setSoundVolume(getSourceId(), getVolume());\n }\n }",
"private void addViews(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (View view : file.getViews())\n {\n final View v = view;\n MpxjTreeNode childNode = new MpxjTreeNode(view)\n {\n @Override public String toString()\n {\n return v.getName();\n }\n };\n parentNode.add(childNode);\n }\n }",
"public double getValue(int[] batch) {\n double value = 0.0;\n for (int i=0; i<batch.length; i++) {\n value += getValue(i);\n }\n return value;\n }",
"private static void addCauseToBacktrace(final Throwable cause, final List<String> bTrace) {\n if (cause.getMessage() == null) {\n bTrace.add(BT_CAUSED_BY_PREFIX + cause.getClass().getName());\n } else {\n bTrace.add(BT_CAUSED_BY_PREFIX + cause.getClass().getName() + \": \" + cause.getMessage());\n }\n for (final StackTraceElement ste : cause.getStackTrace()) {\n bTrace.add(BT_PREFIX + ste.toString());\n }\n if (cause.getCause() != null) {\n addCauseToBacktrace(cause.getCause(), bTrace);\n }\n }"
] |
The digits were stored as a hex value, thix switches them to an octal value.
@param currentHexValue
@param digitCount
@return | [
"private static long switchValue8(long currentHexValue, int digitCount) {\n\t\tlong result = 0x7 & currentHexValue;\n\t\tint shift = 0;\n\t\twhile(--digitCount > 0) {\n\t\t\tshift += 3;\n\t\t\tcurrentHexValue >>>= 4;\n\t\t\tresult |= (0x7 & currentHexValue) << shift;\n\t\t}\n\t\treturn result;\n\t}"
] | [
"protected Map getParametersMap(ActionInvocation _invocation) {\n \tMap map = (Map) _invocation.getStack().findValue(this.parameters);\n \tif (map == null)\n \t\tmap = new HashMap();\n\t\treturn map;\n\t}",
"public Collection<Method> getAllMethods(String name) {\n final Map<ParamList, Map<Class<?>, Method>> nameMap = methods.get(name);\n if (nameMap == null) {\n return Collections.emptySet();\n }\n final Collection<Method> methods = new ArrayList<Method>();\n for (Map<Class<?>, Method> map : nameMap.values()) {\n methods.addAll(map.values());\n }\n return methods;\n }",
"public static Stack getStack() {\n Stack stack = interceptionContexts.get();\n if (stack == null) {\n stack = new Stack(interceptionContexts);\n interceptionContexts.set(stack);\n }\n return stack;\n }",
"@Override\n public void destroy(SocketDestination dest, ClientRequestExecutor clientRequestExecutor)\n throws Exception {\n clientRequestExecutor.close();\n int numDestroyed = destroyed.incrementAndGet();\n if(stats != null) {\n stats.incrementCount(dest, ClientSocketStats.Tracked.CONNECTION_DESTROYED_EVENT);\n }\n\n if(logger.isDebugEnabled())\n logger.debug(\"Destroyed socket \" + numDestroyed + \" connection to \" + dest.getHost()\n + \":\" + dest.getPort());\n }",
"public LogStreamResponse getLogs(Log.LogRequestBuilder logRequest) {\n return connection.execute(new Log(logRequest), apiKey);\n }",
"private void processScheduleOptions()\n {\n List<Row> rows = getRows(\"schedoptions\", \"proj_id\", m_projectID);\n if (rows.isEmpty() == false)\n {\n Row row = rows.get(0);\n Map<String, Object> customProperties = new HashMap<String, Object>();\n customProperties.put(\"LagCalendar\", row.getString(\"sched_calendar_on_relationship_lag\"));\n customProperties.put(\"RetainedLogic\", Boolean.valueOf(row.getBoolean(\"sched_retained_logic\")));\n customProperties.put(\"ProgressOverride\", Boolean.valueOf(row.getBoolean(\"sched_progress_override\")));\n customProperties.put(\"IgnoreOtherProjectRelationships\", row.getString(\"sched_outer_depend_type\"));\n customProperties.put(\"StartToStartLagCalculationType\", Boolean.valueOf(row.getBoolean(\"sched_lag_early_start_flag\")));\n m_reader.getProject().getProjectProperties().setCustomProperties(customProperties);\n }\n }",
"private static Date getSentDate(MimeMessage msg, Date defaultVal) {\r\n if (msg == null) {\r\n return defaultVal;\r\n }\r\n try {\r\n Date sentDate = msg.getSentDate();\r\n if (sentDate == null) {\r\n return defaultVal;\r\n } else {\r\n return sentDate;\r\n }\r\n } catch (MessagingException me) {\r\n return new Date();\r\n }\r\n }",
"public void cleanup() {\n List<String> keys = new ArrayList<>(created.keySet());\n keys.sort(String::compareTo);\n for (String key : keys) {\n created.remove(key)\n .stream()\n .sorted(Comparator.comparing(HasMetadata::getKind))\n .forEach(metadata -> {\n log.info(String.format(\"Deleting %s : %s\", key, metadata.getKind()));\n deleteWithRetries(metadata);\n });\n }\n }",
"public <T extends Widget & Checkable> List<T> getCheckableChildren() {\n List<Widget> children = getChildren();\n ArrayList<T> result = new ArrayList<>();\n for (Widget c : children) {\n if (c instanceof Checkable) {\n result.add((T) c);\n }\n }\n return result;\n }"
] |
Calculate the finish variance.
@return finish variance | [
"public Duration getFinishVariance()\n {\n Duration variance = (Duration) getCachedValue(AssignmentField.FINISH_VARIANCE);\n if (variance == null)\n {\n TimeUnit format = getParentFile().getProjectProperties().getDefaultDurationUnits();\n variance = DateHelper.getVariance(getTask(), getBaselineFinish(), getFinish(), format);\n set(AssignmentField.FINISH_VARIANCE, variance);\n }\n return (variance);\n }"
] | [
"public void setVolume(float volume)\n {\n // Save this in case this audio source is not being played yet\n mVolume = volume;\n if (isPlaying() && (getSourceId() != GvrAudioEngine.INVALID_ID))\n {\n // This will actually work only if the sound file is being played\n mAudioListener.getAudioEngine().setSoundVolume(getSourceId(), getVolume());\n }\n }",
"public ManagementModelNode findNode(String address) {\n ManagementModelNode root = (ManagementModelNode)tree.getModel().getRoot();\n Enumeration<javax.swing.tree.TreeNode> allNodes = root.depthFirstEnumeration();\n while (allNodes.hasMoreElements()) {\n ManagementModelNode node = (ManagementModelNode)allNodes.nextElement();\n if (node.addressPath().equals(address)) return node;\n }\n\n return null;\n }",
"public void logWarning(final String message) {\n messageQueue.add(new LogEntry() {\n @Override\n public String getMessage() {\n return message;\n }\n });\n }",
"public boolean canBeLinked(D declaration, ServiceReference<S> declarationBinderRef) {\n // Evaluate the target filter of the ImporterService on the Declaration\n Filter filter = bindersManager.getTargetFilter(declarationBinderRef);\n return filter.matches(declaration.getMetadata());\n }",
"private double convertTenor(int maturityInMonths, int tenorInMonths) {\r\n\t\tSchedule schedule = fixMetaSchedule.generateSchedule(referenceDate, maturityInMonths, tenorInMonths);\r\n\t\treturn schedule.getPayment(schedule.getNumberOfPeriods()-1);\r\n\t}",
"public static MediaType binary( MediaType.Type type, String subType ) {\n return new MediaType( type, subType, true );\n }",
"public static base_responses delete(nitro_service client, String fipskeyname[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (fipskeyname != null && fipskeyname.length > 0) {\n\t\t\tsslfipskey deleteresources[] = new sslfipskey[fipskeyname.length];\n\t\t\tfor (int i=0;i<fipskeyname.length;i++){\n\t\t\t\tdeleteresources[i] = new sslfipskey();\n\t\t\t\tdeleteresources[i].fipskeyname = fipskeyname[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"public static autoscaleaction get(nitro_service service, String name) throws Exception{\n\t\tautoscaleaction obj = new autoscaleaction();\n\t\tobj.set_name(name);\n\t\tautoscaleaction response = (autoscaleaction) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static List<Integer> toIntegerList(List<String> strList, boolean failOnException){\n\t\tList<Integer> intList = new ArrayList<Integer>();\n\t\tfor(String str : strList){\n\t\t\ttry{\n\t\t\t\tintList.add(Integer.parseInt(str));\n\t\t\t}\n\t\t\tcatch(NumberFormatException nfe){\n\t\t\t\tif(failOnException){\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tintList.add(null);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn intList;\n\t}"
] |
Creates a CostRateTable instance from a block of data.
@param resource parent resource
@param index cost rate table index
@param data data block | [
"public void process(Resource resource, int index, byte[] data)\n {\n CostRateTable result = new CostRateTable();\n\n if (data != null)\n {\n for (int i = 16; i + 44 <= data.length; i += 44)\n {\n Rate standardRate = new Rate(MPPUtility.getDouble(data, i), TimeUnit.HOURS);\n TimeUnit standardRateFormat = getFormat(MPPUtility.getShort(data, i + 8));\n Rate overtimeRate = new Rate(MPPUtility.getDouble(data, i + 16), TimeUnit.HOURS);\n TimeUnit overtimeRateFormat = getFormat(MPPUtility.getShort(data, i + 24));\n Double costPerUse = NumberHelper.getDouble(MPPUtility.getDouble(data, i + 32) / 100.0);\n Date endDate = MPPUtility.getTimestampFromTenths(data, i + 40);\n CostRateTableEntry entry = new CostRateTableEntry(standardRate, standardRateFormat, overtimeRate, overtimeRateFormat, costPerUse, endDate);\n result.add(entry);\n }\n Collections.sort(result);\n }\n else\n {\n //\n // MS Project economises by not actually storing the first cost rate\n // table if it doesn't need to, so we take this into account here.\n //\n if (index == 0)\n {\n Rate standardRate = resource.getStandardRate();\n Rate overtimeRate = resource.getOvertimeRate();\n Number costPerUse = resource.getCostPerUse();\n CostRateTableEntry entry = new CostRateTableEntry(standardRate, standardRate.getUnits(), overtimeRate, overtimeRate.getUnits(), costPerUse, CostRateTableEntry.DEFAULT_ENTRY.getEndDate());\n result.add(entry);\n }\n else\n {\n result.add(CostRateTableEntry.DEFAULT_ENTRY);\n }\n }\n\n resource.setCostRateTable(index, result);\n }"
] | [
"public void addRequiredBundles(String... requiredBundles) {\n\t\tString oldBundles = mainAttributes.get(REQUIRE_BUNDLE);\n\t\tif (oldBundles == null)\n\t\t\toldBundles = \"\";\n\t\tBundleList oldResultList = BundleList.fromInput(oldBundles, newline);\n\t\tBundleList resultList = BundleList.fromInput(oldBundles, newline);\n\t\tfor (String bundle : requiredBundles) {\n\t\t\tBundle newBundle = Bundle.fromInput(bundle);\n\t\t\tif (name != null && name.equals(newBundle.getName()))\n\t\t\t\tcontinue;\n\t\t\tresultList.mergeInto(newBundle);\n\t\t}\n\t\tString result = resultList.toString();\n\t\tboolean changed = !oldResultList.toString().equals(result);\n\t\tmodified |= changed;\n\t\tif (changed)\n\t\t\tmainAttributes.put(REQUIRE_BUNDLE, result);\n\t}",
"public Response updateTemplate(String id, Map<String, Object> options)\n throws RequestException, LocalOperationException {\n Request request = new Request(this);\n return new Response(request.put(\"/templates/\" + id, options));\n }",
"public void bind(Object object, String name)\r\n throws ObjectNameNotUniqueException\r\n {\r\n /**\r\n * Is DB open? ODMG 3.0 says it has to be to call bind.\r\n */\r\n if (!this.isOpen())\r\n {\r\n throw new DatabaseClosedException(\"Database is not open. Must have an open DB to call bind.\");\r\n }\r\n /**\r\n * Is Tx open? ODMG 3.0 says it has to be to call bind.\r\n */\r\n TransactionImpl tx = getTransaction();\r\n if (tx == null || !tx.isOpen())\r\n {\r\n throw new TransactionNotInProgressException(\"Tx is not open. Must have an open TX to call bind.\");\r\n }\r\n\r\n tx.getNamedRootsMap().bind(object, name);\r\n }",
"private boolean ignoreMethod(String name)\n {\n boolean result = false;\n\n for (String ignoredName : IGNORED_METHODS)\n {\n if (name.matches(ignoredName))\n {\n result = true;\n break;\n }\n }\n\n return result;\n }",
"public static void convertTranSrc(DMatrixRMaj src , DMatrixRBlock dst )\n {\n if( src.numRows != dst.numCols || src.numCols != dst.numRows )\n throw new IllegalArgumentException(\"Incompatible matrix shapes.\");\n\n for( int i = 0; i < dst.numRows; i += dst.blockLength ) {\n int blockHeight = Math.min( dst.blockLength , dst.numRows - i);\n\n for( int j = 0; j < dst.numCols; j += dst.blockLength ) {\n int blockWidth = Math.min( dst.blockLength , dst.numCols - j);\n\n int indexDst = i*dst.numCols + blockHeight*j;\n int indexSrc = j*src.numCols + i;\n\n for( int l = 0; l < blockWidth; l++ ) {\n int rowSrc = indexSrc + l*src.numCols;\n int rowDst = indexDst + l;\n for( int k = 0; k < blockHeight; k++ , rowDst += blockWidth ) {\n dst.data[ rowDst ] = src.data[rowSrc++];\n }\n }\n }\n }\n }",
"public void addChild(final DiffNode node)\n\t{\n\t\tif (node == this)\n\t\t{\n\t\t\tthrow new IllegalArgumentException(\"Detected attempt to add a node to itself. \" +\n\t\t\t\t\t\"This would cause inifite loops and must never happen.\");\n\t\t}\n\t\telse if (node.isRootNode())\n\t\t{\n\t\t\tthrow new IllegalArgumentException(\"Detected attempt to add root node as child. \" +\n\t\t\t\t\t\"This is not allowed and must be a mistake.\");\n\t\t}\n\t\telse if (node.getParentNode() != null && node.getParentNode() != this)\n\t\t{\n\t\t\tthrow new IllegalArgumentException(\"Detected attempt to add child node that is already the \" +\n\t\t\t\t\t\"child of another node. Adding nodes multiple times is not allowed, since it could \" +\n\t\t\t\t\t\"cause infinite loops.\");\n\t\t}\n\t\tif (node.getParentNode() == null)\n\t\t{\n\t\t\tnode.setParentNode(this);\n\t\t}\n\t\tchildren.put(node.getElementSelector(), node);\n\t\tif (state == State.UNTOUCHED && node.hasChanges())\n\t\t{\n\t\t\tstate = State.CHANGED;\n\t\t}\n\t}",
"protected void processStop(Endpoint endpoint, EventTypeEnum eventType) {\n if (!sendLifecycleEvent) {\n return;\n }\n\n Event event = createEvent(endpoint, eventType);\n monitoringServiceClient.putEvents(Collections.singletonList(event));\n if (LOG.isLoggable(Level.INFO)) {\n LOG.info(\"Send \" + eventType + \" event to SAM Server successful!\");\n }\n }",
"protected static boolean createLoggingAction(final Logger logger, final Logger auditor, final TransactionLogger instance) {\n TransactionLogger oldInstance = getInstance();\n if (oldInstance == null || oldInstance.finished) {\n if(loggingKeys == null) {\n synchronized (TransactionLogger.class) {\n if (loggingKeys == null) {\n logger.info(\"Initializing 'LoggingKeysHandler' class\");\n loggingKeys = new LoggingKeysHandler(keysPropStream);\n }\n }\n }\n initInstance(instance, logger, auditor);\n setInstance(instance);\n return true;\n }\n return false; // Really not sure it can happen - since we arrive here in a new thread of transaction I think it's ThreadLocal should be empty. But leaving this code just in case...\n }",
"public final URI render(\n final MapfishMapContext mapContext,\n final ScalebarAttributeValues scalebarParams,\n final File tempFolder,\n final Template template)\n throws IOException, ParserConfigurationException {\n final double dpi = mapContext.getDPI();\n\n // get the map bounds\n final Rectangle paintArea = new Rectangle(mapContext.getMapSize());\n MapBounds bounds = mapContext.getBounds();\n\n final DistanceUnit mapUnit = getUnit(bounds);\n final Scale scale = bounds.getScale(paintArea, PDF_DPI);\n final double scaleDenominator = scale.getDenominator(scalebarParams.geodetic,\n bounds.getProjection(), dpi, bounds.getCenter());\n\n DistanceUnit scaleUnit = scalebarParams.getUnit();\n if (scaleUnit == null) {\n scaleUnit = mapUnit;\n }\n\n // adjust scalebar width and height to the DPI value\n final double maxLengthInPixel = (scalebarParams.getOrientation().isHorizontal()) ?\n scalebarParams.getSize().width : scalebarParams.getSize().height;\n\n final double maxIntervalLengthInWorldUnits = DistanceUnit.PX.convertTo(maxLengthInPixel, scaleUnit)\n * scaleDenominator / scalebarParams.intervals;\n final double niceIntervalLengthInWorldUnits =\n getNearestNiceValue(maxIntervalLengthInWorldUnits, scaleUnit, scalebarParams.lockUnits);\n\n final ScaleBarRenderSettings settings = new ScaleBarRenderSettings();\n settings.setParams(scalebarParams);\n settings.setMaxSize(scalebarParams.getSize());\n settings.setPadding(getPadding(settings));\n\n // start the rendering\n File path = null;\n if (template.getConfiguration().renderAsSvg(scalebarParams.renderAsSvg)) {\n // render scalebar as SVG\n final SVGGraphics2D graphics2D = CreateMapProcessor.createSvgGraphics(scalebarParams.getSize());\n\n try {\n tryLayout(\n graphics2D, scaleUnit, scaleDenominator,\n niceIntervalLengthInWorldUnits, settings, 0);\n\n path = File.createTempFile(\"scalebar-graphic-\", \".svg\", tempFolder);\n CreateMapProcessor.saveSvgFile(graphics2D, path);\n } finally {\n graphics2D.dispose();\n }\n } else {\n // render scalebar as raster graphic\n double dpiRatio = mapContext.getDPI() / PDF_DPI;\n final BufferedImage bufferedImage = new BufferedImage(\n (int) Math.round(scalebarParams.getSize().width * dpiRatio),\n (int) Math.round(scalebarParams.getSize().height * dpiRatio),\n TYPE_4BYTE_ABGR);\n final Graphics2D graphics2D = bufferedImage.createGraphics();\n\n try {\n AffineTransform saveAF = new AffineTransform(graphics2D.getTransform());\n graphics2D.scale(dpiRatio, dpiRatio);\n tryLayout(\n graphics2D, scaleUnit, scaleDenominator,\n niceIntervalLengthInWorldUnits, settings, 0);\n graphics2D.setTransform(saveAF);\n\n path = File.createTempFile(\"scalebar-graphic-\", \".png\", tempFolder);\n ImageUtils.writeImage(bufferedImage, \"png\", path);\n } finally {\n graphics2D.dispose();\n }\n }\n\n return path.toURI();\n }"
] |
Initializes the bean name defaulted | [
"private void initBeanNameDefaulted(EnhancedAnnotation<T> annotatedAnnotation) {\n if (annotatedAnnotation.isAnnotationPresent(Named.class)) {\n if (!\"\".equals(annotatedAnnotation.getAnnotation(Named.class).value())) {\n throw MetadataLogger.LOG.valueOnNamedStereotype(annotatedAnnotation);\n }\n beanNameDefaulted = true;\n }\n }"
] | [
"private void calculateValueTextHeight() {\n Rect valueRect = new Rect();\n Rect legendRect = new Rect();\n String str = Utils.getFloatString(mFocusedPoint.getValue(), mShowDecimal) + (!mIndicatorTextUnit.isEmpty() ? \" \" + mIndicatorTextUnit : \"\");\n\n // calculate the boundaries for both texts\n mIndicatorPaint.getTextBounds(str, 0, str.length(), valueRect);\n mLegendPaint.getTextBounds(mFocusedPoint.getLegendLabel(), 0, mFocusedPoint.getLegendLabel().length(), legendRect);\n\n // calculate string positions in overlay\n mValueTextHeight = valueRect.height();\n mValueLabelY = (int) (mValueTextHeight + mIndicatorTopPadding);\n mLegendLabelY = (int) (mValueTextHeight + mIndicatorTopPadding + legendRect.height() + Utils.dpToPx(7.f));\n\n int chosenWidth = valueRect.width() > legendRect.width() ? valueRect.width() : legendRect.width();\n\n // check if text reaches over screen\n if (mFocusedPoint.getCoordinates().getX() + chosenWidth + mIndicatorLeftPadding > -Utils.getTranslationX(mDrawMatrixValues) + mGraphWidth) {\n mValueLabelX = (int) (mFocusedPoint.getCoordinates().getX() - (valueRect.width() + mIndicatorLeftPadding));\n mLegendLabelX = (int) (mFocusedPoint.getCoordinates().getX() - (legendRect.width() + mIndicatorLeftPadding));\n } else {\n mValueLabelX = mLegendLabelX = (int) (mFocusedPoint.getCoordinates().getX() + mIndicatorLeftPadding);\n }\n }",
"public static final long getLong6(byte[] data, int offset)\n {\n long result = 0;\n int i = offset;\n for (int shiftBy = 0; shiftBy < 48; shiftBy += 8)\n {\n result |= ((long) (data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }",
"@Override\n public final String optString(final String key, final String defaultValue) {\n String result = optString(key);\n return result == null ? defaultValue : result;\n }",
"public long queryForLong(DatabaseConnection databaseConnection, PreparedStmt<T> preparedStmt) throws SQLException {\n\t\tCompiledStatement compiledStatement = preparedStmt.compile(databaseConnection, StatementType.SELECT_LONG);\n\t\tDatabaseResults results = null;\n\t\ttry {\n\t\t\tresults = compiledStatement.runQuery(null);\n\t\t\tif (results.first()) {\n\t\t\t\treturn results.getLong(0);\n\t\t\t} else {\n\t\t\t\tthrow new SQLException(\"No result found in queryForLong: \" + preparedStmt.getStatement());\n\t\t\t}\n\t\t} finally {\n\t\t\tIOUtils.closeThrowSqlException(results, \"results\");\n\t\t\tIOUtils.closeThrowSqlException(compiledStatement, \"compiled statement\");\n\t\t}\n\t}",
"@SuppressWarnings(\"UnusedDeclaration\")\n public void init() throws Exception {\n initBuilderSpecific();\n resetFields();\n if (!UserPluginInfo.NO_PLUGIN_KEY.equals(getSelectedStagingPluginName())) {\n PluginSettings selectedStagingPluginSettings = getSelectedStagingPlugin();\n try {\n stagingStrategy = getArtifactoryServer().getStagingStrategy(selectedStagingPluginSettings, Util.rawEncode(project.getName()), project);\n } catch (Exception e) {\n log.log(Level.WARNING, \"Failed to obtain staging strategy: \" + e.getMessage(), e);\n strategyRequestFailed = true;\n strategyRequestErrorMessage = \"Failed to obtain staging strategy '\" +\n selectedStagingPluginSettings.getPluginName() + \"': \" + e.getMessage() +\n \".\\nPlease review the log for further information.\";\n stagingStrategy = null;\n }\n strategyPluginExists = (stagingStrategy != null) && !stagingStrategy.isEmpty();\n }\n\n prepareDefaultVersioning();\n prepareDefaultGlobalModule();\n prepareDefaultModules();\n prepareDefaultVcsSettings();\n prepareDefaultPromotionConfig();\n }",
"@Override\r\n public void onBrowserEvent(Event event) {\r\n\r\n super.onBrowserEvent(event);\r\n\r\n switch (DOM.eventGetType(event)) {\r\n case Event.ONMOUSEUP:\r\n Event.releaseCapture(m_slider.getElement());\r\n m_capturedMouse = false;\r\n break;\r\n case Event.ONMOUSEDOWN:\r\n Event.setCapture(m_slider.getElement());\r\n m_capturedMouse = true;\r\n //$FALL-THROUGH$\r\n case Event.ONMOUSEMOVE:\r\n if (m_capturedMouse) {\r\n event.preventDefault();\r\n float x = ((event.getClientX() - (m_colorUnderlay.getAbsoluteLeft())) + Window.getScrollLeft());\r\n float y = ((event.getClientY() - (m_colorUnderlay.getAbsoluteTop())) + Window.getScrollTop());\r\n\r\n if (m_parent != null) {\r\n m_parent.onMapSelected(x, y);\r\n }\r\n\r\n setSliderPosition(x, y);\r\n }\r\n //$FALL-THROUGH$\r\n default:\r\n\r\n }\r\n }",
"public Boolean checkType(String type) {\n if (mtasPositionType == null) {\n return false;\n } else {\n return mtasPositionType.equals(type);\n }\n }",
"public synchronized void removeAllSceneObjects() {\n final GVRCameraRig rig = getMainCameraRig();\n final GVRSceneObject head = rig.getOwnerObject();\n rig.removeAllChildren();\n\n NativeScene.removeAllSceneObjects(getNative());\n for (final GVRSceneObject child : mSceneRoot.getChildren()) {\n child.getParent().removeChildObject(child);\n }\n\n if (null != head) {\n mSceneRoot.addChildObject(head);\n }\n\n final int numControllers = getGVRContext().getInputManager().clear();\n if (numControllers > 0)\n {\n getGVRContext().getInputManager().selectController();\n }\n\n getGVRContext().runOnGlThread(new Runnable() {\n @Override\n public void run() {\n NativeScene.deleteLightsAndDepthTextureOnRenderThread(getNative());\n }\n });\n }",
"public Response save() throws RequestException, LocalOperationException {\n Map<String, Object> templateData = new HashMap<String, Object>();\n templateData.put(\"name\", name);\n\n options.put(\"steps\", steps.toMap());\n\n templateData.put(\"template\", options);\n Request request = new Request(transloadit);\n return new Response(request.post(\"/templates\", templateData));\n }"
] |
Process the scheduling project property from PROJPROP. This table only seems to exist
in P6 databases, not XER files.
@throws SQLException | [
"private void processSchedulingProjectProperties() throws SQLException\n {\n List<Row> rows = getRows(\"select * from \" + m_schema + \"projprop where proj_id=? and prop_name='scheduling'\", m_projectID);\n if (!rows.isEmpty())\n {\n Row row = rows.get(0);\n Record record = Record.getRecord(row.getString(\"prop_value\"));\n if (record != null)\n {\n String[] keyValues = record.getValue().split(\"\\\\|\");\n for (int i = 0; i < keyValues.length - 1; ++i)\n {\n if (\"sched_calendar_on_relationship_lag\".equals(keyValues[i]))\n {\n Map<String, Object> customProperties = new HashMap<String, Object>();\n customProperties.put(\"LagCalendar\", keyValues[i + 1]);\n m_reader.getProject().getProjectProperties().setCustomProperties(customProperties);\n break;\n }\n }\n }\n }\n }"
] | [
"void close() {\n mIODevice = null;\n GVRSceneObject owner = getOwnerObject();\n if (owner.getParent() != null) {\n owner.getParent().removeChildObject(owner);\n }\n }",
"public ItemRequest<OrganizationExport> findById(String organizationExport) {\n \n String path = String.format(\"/organization_exports/%s\", organizationExport);\n return new ItemRequest<OrganizationExport>(this, OrganizationExport.class, path, \"GET\");\n }",
"public B importContext(AbstractContext context){\n Objects.requireNonNull(context);\n return importContext(context, false);\n }",
"public static base_response unset(nitro_service client, coparameter resource, String[] args) throws Exception{\n\t\tcoparameter unsetresource = new coparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public static String getJavaClassFromSchemaInfo(String schemaInfo) {\n final String ONLY_JAVA_CLIENTS_SUPPORTED = \"Only Java clients are supported currently, so the format of the schema-info should be: <schema-info>java=foo.Bar</schema-info> where foo.Bar is the fully qualified name of the message.\";\n\n if(StringUtils.isEmpty(schemaInfo))\n throw new IllegalArgumentException(\"This serializer requires a non-empty schema-info.\");\n\n String[] languagePairs = StringUtils.split(schemaInfo, ',');\n if(languagePairs.length > 1)\n throw new IllegalArgumentException(ONLY_JAVA_CLIENTS_SUPPORTED);\n\n String[] javaPair = StringUtils.split(languagePairs[0], '=');\n if(javaPair.length != 2 || !javaPair[0].trim().equals(\"java\"))\n throw new IllegalArgumentException(ONLY_JAVA_CLIENTS_SUPPORTED);\n\n return javaPair[1].trim();\n }",
"public boolean hasCachedValue(Key key) {\n\t\ttry {\n\t\t\treadLock.lock();\n\t\t\treturn content.containsKey(key);\n\t\t} finally {\n\t\t\treadLock.unlock();\n\t\t}\n\t}",
"public List<String> filterAddonResources(Addon addon, Predicate<String> filter)\n {\n List<String> discoveredFileNames = new ArrayList<>();\n List<File> addonResources = addon.getRepository().getAddonResources(addon.getId());\n for (File addonFile : addonResources)\n {\n if (addonFile.isDirectory())\n handleDirectory(filter, addonFile, discoveredFileNames);\n else\n handleArchiveByFile(filter, addonFile, discoveredFileNames);\n }\n return discoveredFileNames;\n }",
"private ImmutableList<Element> getNodeListForTagElement(Document dom,\n\t\t\tCrawlElement crawlElement,\n\t\t\tEventableConditionChecker eventableConditionChecker) {\n\n\t\tBuilder<Element> result = ImmutableList.builder();\n\n\t\tif (crawlElement.getTagName() == null) {\n\t\t\treturn result.build();\n\t\t}\n\n\t\tEventableCondition eventableCondition =\n\t\t\t\teventableConditionChecker.getEventableCondition(crawlElement.getId());\n\t\t// TODO Stefan; this part of the code should be re-factored, Hack-ed it this way to prevent\n\t\t// performance problems.\n\t\tImmutableList<String> expressions = getFullXpathForGivenXpath(dom, eventableCondition);\n\n\t\tNodeList nodeList = dom.getElementsByTagName(crawlElement.getTagName());\n\n\t\tfor (int k = 0; k < nodeList.getLength(); k++) {\n\n\t\t\tElement element = (Element) nodeList.item(k);\n\t\t\tboolean matchesXpath =\n\t\t\t\t\telementMatchesXpath(eventableConditionChecker, eventableCondition,\n\t\t\t\t\t\t\texpressions, element);\n\t\t\tLOG.debug(\"Element {} matches Xpath={}\", DomUtils.getElementString(element),\n\t\t\t\t\tmatchesXpath);\n\t\t\t/*\n\t\t\t * TODO Stefan This is a possible Thread-Interleaving problem, as / isChecked can return\n\t\t\t * false and when needed to add it can return true. / check if element is a candidate\n\t\t\t */\n\t\t\tString id = element.getNodeName() + \": \" + DomUtils.getAllElementAttributes(element);\n\t\t\tif (matchesXpath && !checkedElements.isChecked(id)\n\t\t\t\t\t&& !isExcluded(dom, element, eventableConditionChecker)) {\n\t\t\t\taddElement(element, result, crawlElement);\n\t\t\t} else {\n\t\t\t\tLOG.debug(\"Element {} was not added\", element);\n\t\t\t}\n\t\t}\n\t\treturn result.build();\n\t}",
"@UiThread\n private int getFlatParentPosition(int parentPosition) {\n int parentCount = 0;\n int listItemCount = mFlatItemList.size();\n for (int i = 0; i < listItemCount; i++) {\n if (mFlatItemList.get(i).isParent()) {\n parentCount++;\n\n if (parentCount > parentPosition) {\n return i;\n }\n }\n }\n\n return INVALID_FLAT_POSITION;\n }"
] |
Push an event which describes a purchase made.
@param eventName Has to be specified as "Charged". Anything other than this
will result in an {@link InvalidEventNameException} being thrown.
@param chargeDetails A {@link HashMap}, with keys as strings, and values as {@link String},
{@link Integer}, {@link Long}, {@link Boolean}, {@link Float}, {@link Double},
{@link java.util.Date}, or {@link Character}
@param items An {@link ArrayList} which contains up to 15 {@link HashMap} objects,
where each HashMap object describes a particular item purchased
@throws InvalidEventNameException Thrown if the event name is not "Charged"
@deprecated use {@link CleverTapAPI#pushChargedEvent(HashMap chargeDetails, ArrayList items)} | [
"@Deprecated\n @SuppressWarnings(\"deprecation\")\n public void push(String eventName, HashMap<String, Object> chargeDetails,\n ArrayList<HashMap<String, Object>> items)\n throws InvalidEventNameException {\n // This method is for only charged events\n if (!eventName.equals(Constants.CHARGED_EVENT)) {\n throw new InvalidEventNameException(\"Not a charged event\");\n }\n CleverTapAPI cleverTapAPI = weakReference.get();\n if(cleverTapAPI == null){\n Logger.d(\"CleverTap Instance is null.\");\n } else {\n cleverTapAPI.pushChargedEvent(chargeDetails, items);\n }\n }"
] | [
"public boolean detectBlackBerryTouch() {\r\n\r\n if (detectBlackBerry()\r\n && ((userAgent.indexOf(deviceBBStorm) != -1)\r\n || (userAgent.indexOf(deviceBBTorch) != -1)\r\n || (userAgent.indexOf(deviceBBBoldTouch) != -1)\r\n || (userAgent.indexOf(deviceBBCurveTouch) != -1))) {\r\n return true;\r\n }\r\n return false;\r\n }",
"public ProjectCalendarException getException(Date date)\n {\n ProjectCalendarException exception = null;\n\n // We're working with expanded exceptions, which includes any recurring exceptions\n // expanded into individual entries.\n populateExpandedExceptions();\n if (!m_expandedExceptions.isEmpty())\n {\n sortExceptions();\n\n int low = 0;\n int high = m_expandedExceptions.size() - 1;\n long targetDate = date.getTime();\n\n while (low <= high)\n {\n int mid = (low + high) >>> 1;\n ProjectCalendarException midVal = m_expandedExceptions.get(mid);\n int cmp = 0 - DateHelper.compare(midVal.getFromDate(), midVal.getToDate(), targetDate);\n\n if (cmp < 0)\n {\n low = mid + 1;\n }\n else\n {\n if (cmp > 0)\n {\n high = mid - 1;\n }\n else\n {\n exception = midVal;\n break;\n }\n }\n }\n }\n\n if (exception == null && getParent() != null)\n {\n // Check base calendar as well for an exception.\n exception = getParent().getException(date);\n }\n return (exception);\n }",
"public static String blur(int radius, int sigma) {\n if (radius < 1) {\n throw new IllegalArgumentException(\"Radius must be greater than zero.\");\n }\n if (radius > 150) {\n throw new IllegalArgumentException(\"Radius must be lower or equal than 150.\");\n }\n if (sigma < 0) {\n throw new IllegalArgumentException(\"Sigma must be greater than zero.\");\n }\n return FILTER_BLUR + \"(\" + radius + \",\" + sigma + \")\";\n }",
"public static Chart getTrajectoryChart(String title, Trajectory t){\n\t\tif(t.getDimension()==2){\n\t\t \tdouble[] xData = new double[t.size()];\n\t\t double[] yData = new double[t.size()];\n\t\t for(int i = 0; i < t.size(); i++){\n\t\t \txData[i] = t.get(i).x;\n\t\t \tyData[i] = t.get(i).y;\n\t\t \t\n\t\t }\n\t\t // Create Chart\n\t\t Chart chart = QuickChart.getChart(title, \"X\", \"Y\", \"y(x)\", xData, yData);\n\t\n\t\t return chart;\n\t\t //Show it\n\t\t // SwingWrapper swr = new SwingWrapper(chart);\n\t\t // swr.displayChart();\n\t\t} \n\t\treturn null;\n\t}",
"public static ModelMBean createModelMBean(Object o) {\n try {\n ModelMBean mbean = new RequiredModelMBean();\n JmxManaged annotation = o.getClass().getAnnotation(JmxManaged.class);\n String description = annotation == null ? \"\" : annotation.description();\n ModelMBeanInfo info = new ModelMBeanInfoSupport(o.getClass().getName(),\n description,\n extractAttributeInfo(o),\n new ModelMBeanConstructorInfo[0],\n extractOperationInfo(o),\n new ModelMBeanNotificationInfo[0]);\n mbean.setModelMBeanInfo(info);\n mbean.setManagedResource(o, \"ObjectReference\");\n\n return mbean;\n } catch(MBeanException e) {\n throw new VoldemortException(e);\n } catch(InvalidTargetObjectTypeException e) {\n throw new VoldemortException(e);\n } catch(InstanceNotFoundException e) {\n throw new VoldemortException(e);\n }\n }",
"protected void endPersistence(final BufferedWriter writer) throws IOException {\n // Append any additional users to the end of the file.\n for (Object currentKey : toSave.keySet()) {\n String key = (String) currentKey;\n if (!key.contains(DISABLE_SUFFIX_KEY)) {\n writeProperty(writer, key, null);\n }\n }\n\n toSave = null;\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 void insertBefore(Vertex vtx, Vertex next) {\n vtx.prev = next.prev;\n if (next.prev == null) {\n head = vtx;\n } else {\n next.prev.next = vtx;\n }\n vtx.next = next;\n next.prev = vtx;\n }",
"private boolean shouldIgnore(String typeReference)\n {\n typeReference = typeReference.replace('/', '.').replace('\\\\', '.');\n return JavaClassIgnoreResolver.singletonInstance().matches(typeReference);\n }"
] |
Returns the list of store defs as a map
@param storeDefs
@return | [
"private HashMap<String, StoreDefinition> makeStoreDefinitionMap(List<StoreDefinition> storeDefs) {\n HashMap<String, StoreDefinition> storeDefMap = new HashMap<String, StoreDefinition>();\n for(StoreDefinition storeDef: storeDefs)\n storeDefMap.put(storeDef.getName(), storeDef);\n return storeDefMap;\n }"
] | [
"private static boolean isAssignableFrom(Type from, GenericArrayType to) {\n\t\tType toGenericComponentType = to.getGenericComponentType();\n\t\tif (toGenericComponentType instanceof ParameterizedType) {\n\t\t\tType t = from;\n\t\t\tif (from instanceof GenericArrayType) {\n\t\t\t\tt = ((GenericArrayType) from).getGenericComponentType();\n\t\t\t} else if (from instanceof Class) {\n\t\t\t\tClass<?> classType = (Class<?>) from;\n\t\t\t\twhile (classType.isArray()) {\n\t\t\t\t\tclassType = classType.getComponentType();\n\t\t\t\t}\n\t\t\t\tt = classType;\n\t\t\t}\n\t\t\treturn isAssignableFrom(t,\n\t\t\t\t\t(ParameterizedType) toGenericComponentType,\n\t\t\t\t\tnew HashMap<String, Type>());\n\t\t}\n\t\t// No generic defined on \"to\"; therefore, return true and let other\n\t\t// checks determine assignability\n\t\treturn true;\n\t}",
"public Photoset create(String title, String description, String primaryPhotoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_CREATE);\r\n\r\n parameters.put(\"title\", title);\r\n parameters.put(\"description\", description);\r\n parameters.put(\"primary_photo_id\", primaryPhotoId);\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosetElement = response.getPayload();\r\n Photoset photoset = new Photoset();\r\n photoset.setId(photosetElement.getAttribute(\"id\"));\r\n photoset.setUrl(photosetElement.getAttribute(\"url\"));\r\n return photoset;\r\n }",
"private void addDownloadButton(final CmsLogFileView view) {\n\n Button button = CmsToolBar.createButton(\n FontOpenCms.DOWNLOAD,\n CmsVaadinUtils.getMessageText(Messages.GUI_LOGFILE_DOWNLOAD_0));\n button.addClickListener(new ClickListener() {\n\n private static final long serialVersionUID = 1L;\n\n public void buttonClick(ClickEvent event) {\n\n Window window = CmsBasicDialog.prepareWindow(CmsBasicDialog.DialogWidth.wide);\n window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_LOGFILE_DOWNLOAD_0));\n window.setContent(new CmsLogDownloadDialog(window, view.getCurrentFile()));\n A_CmsUI.get().addWindow(window);\n }\n });\n m_uiContext.addToolbarButton(button);\n }",
"@VisibleForTesting\n protected static String createLabelText(\n final DistanceUnit scaleUnit, final double value, final DistanceUnit intervalUnit) {\n double scaledValue = scaleUnit.convertTo(value, intervalUnit);\n\n // assume that there is no interval smaller then 0.0001\n scaledValue = Math.round(scaledValue * 10000) / 10000;\n String decimals = Double.toString(scaledValue).split(\"\\\\.\")[1];\n\n if (Double.valueOf(decimals) == 0) {\n return Long.toString(Math.round(scaledValue));\n } else {\n return Double.toString(scaledValue);\n }\n }",
"public CoordinatorConfig setBootstrapURLs(List<String> bootstrapUrls) {\n this.bootstrapURLs = Utils.notNull(bootstrapUrls);\n if(this.bootstrapURLs.size() <= 0)\n throw new IllegalArgumentException(\"Must provide at least one bootstrap URL.\");\n return this;\n }",
"public void transform(DataPipe cr) {\n Map<String, String> map = cr.getDataMap();\n\n for (String key : map.keySet()) {\n String value = map.get(key);\n\n if (value.equals(\"#{customplaceholder}\")) {\n // Generate a random number\n int ran = rand.nextInt();\n map.put(key, String.valueOf(ran));\n } else if (value.equals(\"#{divideBy2}\")) {\n String i = map.get(\"var_out_V3\");\n String result = String.valueOf(Integer.valueOf(i) / 2);\n map.put(key, result);\n }\n }\n }",
"private void clearBeatGrids(DeviceAnnouncement announcement) {\n final int player = announcement.getNumber();\n // Iterate over a copy to avoid concurrent modification issues\n for (DeckReference deck : new HashSet<DeckReference>(hotCache.keySet())) {\n if (deck.player == player) {\n hotCache.remove(deck);\n if (deck.hotCue == 0) {\n deliverBeatGridUpdate(player, null); // Inform listeners the beat grid is gone.\n }\n }\n }\n }",
"public static void setField(Object object, String field, Object value) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {\n\t\tClass<?> clazz = object.getClass();\n\t\tMethod m = clazz.getMethod( PROPERTY_ACCESSOR_PREFIX_SET + capitalize( field ), value.getClass() );\n\t\tm.invoke( object, value );\n\t}",
"private void highlightSlice(PieModel _Slice) {\n\n int color = _Slice.getColor();\n _Slice.setHighlightedColor(Color.argb(\n 0xff,\n Math.min((int) (mHighlightStrength * (float) Color.red(color)), 0xff),\n Math.min((int) (mHighlightStrength * (float) Color.green(color)), 0xff),\n Math.min((int) (mHighlightStrength * (float) Color.blue(color)), 0xff)\n ));\n }"
] |
Create an Product delivery
@throws AuthenticationException, GrapesCommunicationException, IOException | [
"public void createProductDelivery(final String productLogicalName, final Delivery delivery, final String user, final String password) throws GrapesCommunicationException, AuthenticationException { \n \tfinal Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getProductDelivery(productLogicalName));\n final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, delivery);\n\n client.destroy();\n if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){\n final String message = \"Failed to create a delivery\";\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 }"
] | [
"private void handleDirectory(final Predicate<String> filter, final File rootDir, final List<String> discoveredFiles)\n {\n try\n {\n new DirectoryWalker<String>()\n {\n private Path startDir;\n\n public void walk() throws IOException\n {\n this.startDir = rootDir.toPath();\n this.walk(rootDir, discoveredFiles);\n }\n\n @Override\n protected void handleFile(File file, int depth, Collection<String> discoveredFiles) throws IOException\n {\n String newPath = startDir.relativize(file.toPath()).toString();\n if (filter.accept(newPath))\n discoveredFiles.add(newPath);\n }\n\n }.walk();\n }\n catch (IOException ex)\n {\n LOG.log(Level.SEVERE, \"Error reading Furnace addon directory\", ex);\n }\n }",
"public void sendLoadTrackCommand(int targetPlayer, int rekordboxId,\n int sourcePlayer, CdjStatus.TrackSourceSlot sourceSlot, CdjStatus.TrackType sourceType)\n throws IOException {\n final DeviceUpdate update = getLatestStatusFor(targetPlayer);\n if (update == null) {\n throw new IllegalArgumentException(\"Device \" + targetPlayer + \" not found on network.\");\n }\n sendLoadTrackCommand(update, rekordboxId, sourcePlayer, sourceSlot, sourceType);\n }",
"public void performImplicitSingleStep(double scale , double lambda , boolean byAngle) {\n createBulge(x1,lambda,scale,byAngle);\n\n for( int i = x1; i < x2-1 && bulge != 0.0; i++ ) {\n removeBulgeLeft(i,true);\n if( bulge == 0 )\n break;\n removeBulgeRight(i);\n }\n\n if( bulge != 0 )\n removeBulgeLeft(x2-1,false);\n\n incrementSteps();\n }",
"public List<String> getArtifactVersions(final String gavc) throws GrapesCommunicationException {\n final Client client = getClient();\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactVersions(gavc));\n final ClientResponse response = resource\n .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = FAILED_TO_GET_CORPORATE_FILTERS;\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\n return response.getEntity(new GenericType<List<String>>(){});\n\n }",
"public static String rset(String input, int width)\n {\n String result; // result to return\n StringBuilder pad = new StringBuilder();\n if (input == null)\n {\n for (int i = 0; i < width - 1; i++)\n {\n pad.append(' '); // put blanks into buffer\n }\n result = \" \" + pad; // one short to use + overload\n }\n else\n {\n if (input.length() >= width)\n {\n result = input.substring(0, width); // when input is too long, truncate\n }\n else\n {\n int padLength = width - input.length(); // number of blanks to add\n for (int i = 0; i < padLength; i++)\n {\n pad.append(' '); // actually put blanks into buffer\n }\n result = pad + input; // concatenate\n }\n }\n return result;\n }",
"public void setResource(Resource resource)\n {\n m_resource = resource;\n String name = m_resource.getName();\n if (name == null || name.length() == 0)\n {\n name = \"Unnamed Resource\";\n }\n setName(name);\n }",
"public <T> void cleanNullReferencesAll() {\n\t\tfor (Map<Object, Reference<Object>> objectMap : classMaps.values()) {\n\t\t\tcleanMap(objectMap);\n\t\t}\n\t}",
"public static void main(String[] args) throws LoginFailedException,\n\t\t\tIOException, MediaWikiApiErrorException {\n\t\tExampleHelpers.configureLogging();\n\t\tprintDocumentation();\n\n\t\tSetLabelsForNumbersBot bot = new SetLabelsForNumbersBot();\n\t\tExampleHelpers.processEntitiesFromWikidataDump(bot);\n\t\tbot.finish();\n\n\t\tSystem.out.println(\"*** Done.\");\n\t}",
"@Override\n public void setValue(Boolean value, boolean fireEvents) {\n boolean oldValue = getValue();\n if (value) {\n input.getElement().setAttribute(\"checked\", \"true\");\n } else {\n input.getElement().removeAttribute(\"checked\");\n }\n\n if (fireEvents && oldValue != value) {\n ValueChangeEvent.fire(this, getValue());\n }\n }"
] |
Use this API to export appfwlearningdata. | [
"public static base_response export(nitro_service client, appfwlearningdata resource) throws Exception {\n\t\tappfwlearningdata exportresource = new appfwlearningdata();\n\t\texportresource.profilename = resource.profilename;\n\t\texportresource.securitycheck = resource.securitycheck;\n\t\texportresource.target = resource.target;\n\t\treturn exportresource.perform_operation(client,\"export\");\n\t}"
] | [
"protected Object[] escape(final Format format, Object... args) {\n // Transformer that escapes HTML,XML,JSON strings\n Transformer<Object, Object> escapingTransformer = new Transformer<Object, Object>() {\n @Override\n public Object transform(Object object) {\n return format.escapeValue(object);\n }\n };\n List<Object> list = Arrays.asList(ArrayUtils.clone(args));\n CollectionUtils.transform(list, escapingTransformer);\n return list.toArray();\n }",
"@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 ThumborUrlBuilder crop(int top, int left, int bottom, int right) {\n if (top < 0) {\n throw new IllegalArgumentException(\"Top must be greater or equal to zero.\");\n }\n if (left < 0) {\n throw new IllegalArgumentException(\"Left must be greater or equal to zero.\");\n }\n if (bottom < 1 || bottom <= top) {\n throw new IllegalArgumentException(\"Bottom must be greater than zero and top.\");\n }\n if (right < 1 || right <= left) {\n throw new IllegalArgumentException(\"Right must be greater than zero and left.\");\n }\n hasCrop = true;\n cropTop = top;\n cropLeft = left;\n cropBottom = bottom;\n cropRight = right;\n return this;\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 }",
"public static base_response Force(nitro_service client, hafailover resource) throws Exception {\n\t\thafailover Forceresource = new hafailover();\n\t\tForceresource.force = resource.force;\n\t\treturn Forceresource.perform_operation(client,\"Force\");\n\t}",
"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 }",
"protected long getUniqueLong(FieldDescriptor field) throws SequenceManagerException\r\n {\r\n long result;\r\n // lookup sequence name\r\n String sequenceName = calculateSequenceName(field);\r\n try\r\n {\r\n result = buildNextSequence(field.getClassDescriptor(), sequenceName);\r\n }\r\n catch (Throwable e)\r\n {\r\n // maybe the sequence was not created\r\n try\r\n {\r\n log.info(\"Create DB sequence key '\"+sequenceName+\"'\");\r\n createSequence(field.getClassDescriptor(), sequenceName);\r\n }\r\n catch (Exception e1)\r\n {\r\n throw new SequenceManagerException(\r\n SystemUtils.LINE_SEPARATOR +\r\n \"Could not grab next id, failed with \" + SystemUtils.LINE_SEPARATOR +\r\n e.getMessage() + SystemUtils.LINE_SEPARATOR +\r\n \"Creation of new sequence failed with \" +\r\n SystemUtils.LINE_SEPARATOR + e1.getMessage() + SystemUtils.LINE_SEPARATOR\r\n , e1);\r\n }\r\n try\r\n {\r\n result = buildNextSequence(field.getClassDescriptor(), sequenceName);\r\n }\r\n catch (Throwable e1)\r\n {\r\n throw new SequenceManagerException(\"Could not grab next id, sequence seems to exist\", e);\r\n }\r\n }\r\n return result;\r\n }",
"public static File[] getVersionDirs(File rootDir, final long minId, final long maxId) {\n return rootDir.listFiles(new FileFilter() {\n\n public boolean accept(File pathName) {\n if(checkVersionDirName(pathName)) {\n long versionId = getVersionId(pathName);\n if(versionId != -1 && versionId <= maxId && versionId >= minId) {\n return true;\n }\n }\n return false;\n }\n });\n }",
"private ProjectFile readFile(String inputFile) throws MPXJException\n {\n ProjectReader reader = new UniversalProjectReader();\n ProjectFile projectFile = reader.read(inputFile);\n if (projectFile == null)\n {\n throw new IllegalArgumentException(\"Unsupported file type\");\n }\n return projectFile;\n }"
] |
Use this API to fetch sslcipher resources of given names . | [
"public static sslcipher[] get(nitro_service service, String ciphergroupname[]) throws Exception{\n\t\tif (ciphergroupname !=null && ciphergroupname.length>0) {\n\t\t\tsslcipher response[] = new sslcipher[ciphergroupname.length];\n\t\t\tsslcipher obj[] = new sslcipher[ciphergroupname.length];\n\t\t\tfor (int i=0;i<ciphergroupname.length;i++) {\n\t\t\t\tobj[i] = new sslcipher();\n\t\t\t\tobj[i].set_ciphergroupname(ciphergroupname[i]);\n\t\t\t\tresponse[i] = (sslcipher) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}"
] | [
"private static void listResources(ProjectFile file)\n {\n for (Resource resource : file.getResources())\n {\n System.out.println(\"Resource: \" + resource.getName() + \" (Unique ID=\" + resource.getUniqueID() + \") Start=\" + resource.getStart() + \" Finish=\" + resource.getFinish());\n }\n System.out.println();\n }",
"@Override\n public Iterator<BoxItem.Info> iterator() {\n URL url = GET_COLLECTION_ITEMS_URL.build(this.getAPI().getBaseURL(), BoxCollection.this.getID());\n return new BoxItemIterator(BoxCollection.this.getAPI(), url);\n }",
"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 static IndexedTypeSet toRootEntities(ExtendedSearchIntegrator extendedIntegrator, Class<?>... selection) {\n\t\tSet<Class<?>> entities = new HashSet<Class<?>>();\n\t\t//first build the \"entities\" set containing all indexed subtypes of \"selection\".\n\t\tfor ( Class<?> entityType : selection ) {\n\t\t\tIndexedTypeSet targetedClasses = extendedIntegrator.getIndexedTypesPolymorphic( IndexedTypeSets.fromClass( entityType ) );\n\t\t\tif ( targetedClasses.isEmpty() ) {\n\t\t\t\tString msg = entityType.getName() + \" is not an indexed entity or a subclass of an indexed entity\";\n\t\t\t\tthrow new IllegalArgumentException( msg );\n\t\t\t}\n\t\t\tentities.addAll( targetedClasses.toPojosSet() );\n\t\t}\n\t\tSet<Class<?>> cleaned = new HashSet<Class<?>>();\n\t\tSet<Class<?>> toRemove = new HashSet<Class<?>>();\n\t\t//now remove all repeated types to avoid duplicate loading by polymorphic query loading\n\t\tfor ( Class<?> type : entities ) {\n\t\t\tboolean typeIsOk = true;\n\t\t\tfor ( Class<?> existing : cleaned ) {\n\t\t\t\tif ( existing.isAssignableFrom( type ) ) {\n\t\t\t\t\ttypeIsOk = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif ( type.isAssignableFrom( existing ) ) {\n\t\t\t\t\ttoRemove.add( existing );\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ( typeIsOk ) {\n\t\t\t\tcleaned.add( type );\n\t\t\t}\n\t\t}\n\t\tcleaned.removeAll( toRemove );\n\t\tlog.debugf( \"Targets for indexing job: %s\", cleaned );\n\t\treturn IndexedTypeSets.fromClasses( cleaned.toArray( new Class[cleaned.size()] ) );\n\t}",
"public boolean hasRequiredClientProps() {\n boolean valid = true;\n valid &= verifyStringPropSet(CONNECTION_APPLICATION_NAME_PROP, CLIENT_APPLICATION_NAME_PROP);\n valid &= verifyStringPropSet(ACCUMULO_USER_PROP, CLIENT_ACCUMULO_USER_PROP);\n valid &= verifyStringPropSet(ACCUMULO_PASSWORD_PROP, CLIENT_ACCUMULO_PASSWORD_PROP);\n valid &= verifyStringPropSet(ACCUMULO_INSTANCE_PROP, CLIENT_ACCUMULO_INSTANCE_PROP);\n return valid;\n }",
"public static JasperPrint generateJasperPrint(DynamicReport dr, LayoutManager layoutManager, Connection con, Map<String, Object> _parameters) throws JRException {\n log.info(\"generating JasperPrint\");\n JasperPrint jp;\n\n if (_parameters == null)\n _parameters = new HashMap<String, Object>();\n\n visitSubreports(dr, _parameters);\n compileOrLoadSubreports(dr, _parameters, \"r\");\n\n DynamicJasperDesign jd = generateJasperDesign(dr);\n Map<String, Object> params = new HashMap<String, Object>();\n if (!_parameters.isEmpty()) {\n registerParams(jd, _parameters);\n params.putAll(_parameters);\n }\n registerEntities(jd, dr, layoutManager);\n layoutManager.applyLayout(jd, dr);\n JRPropertiesUtil.getInstance(DefaultJasperReportsContext.getInstance()).setProperty(JRCompiler.COMPILER_PREFIX, DJCompilerFactory.getCompilerClassName());\n //JRProperties.setProperty(JRCompiler.COMPILER_PREFIX, DJCompilerFactory.getCompilerClassName());\n JasperReport jr = JasperCompileManager.compileReport(jd);\n params.putAll(jd.getParametersWithValues());\n jp = JasperFillManager.fillReport(jr, params, con);\n\n return jp;\n }",
"protected void doPurge(Runnable afterPurgeAction) {\n\n if (LOG.isInfoEnabled()) {\n LOG.info(\n org.opencms.flex.Messages.get().getBundle().key(\n org.opencms.flex.Messages.LOG_FLEXCACHE_WILL_PURGE_JSP_REPOSITORY_0));\n }\n\n File d;\n d = new File(getJspRepository() + CmsFlexCache.REPOSITORY_ONLINE + File.separator);\n CmsFileUtil.purgeDirectory(d);\n\n d = new File(getJspRepository() + CmsFlexCache.REPOSITORY_OFFLINE + File.separator);\n CmsFileUtil.purgeDirectory(d);\n if (afterPurgeAction != null) {\n afterPurgeAction.run();\n }\n\n if (LOG.isInfoEnabled()) {\n LOG.info(\n org.opencms.flex.Messages.get().getBundle().key(\n org.opencms.flex.Messages.LOG_FLEXCACHE_PURGED_JSP_REPOSITORY_0));\n }\n\n }",
"public static nslimitselector get(nitro_service service, String selectorname) throws Exception{\n\t\tnslimitselector obj = new nslimitselector();\n\t\tobj.set_selectorname(selectorname);\n\t\tnslimitselector response = (nslimitselector) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public TimephasedCostContainer getBaselineCost(ProjectCalendar calendar, TimephasedCostNormaliser normaliser, byte[] data, boolean raw)\n {\n TimephasedCostContainer result = null;\n\n if (data != null && data.length > 0)\n {\n LinkedList<TimephasedCost> list = null;\n\n //System.out.println(ByteArrayHelper.hexdump(data, false));\n int index = 16; // 16 byte header\n int blockSize = 20;\n double previousTotalCost = 0;\n\n Date blockStartDate = MPPUtility.getTimestampFromTenths(data, index + 16);\n index += blockSize;\n\n while (index + blockSize <= data.length)\n {\n Date blockEndDate = MPPUtility.getTimestampFromTenths(data, index + 16);\n double currentTotalCost = (double) ((long) MPPUtility.getDouble(data, index + 8)) / 100;\n if (!costEquals(previousTotalCost, currentTotalCost))\n {\n TimephasedCost cost = new TimephasedCost();\n cost.setStart(blockStartDate);\n cost.setFinish(blockEndDate);\n cost.setTotalAmount(Double.valueOf(currentTotalCost - previousTotalCost));\n\n if (list == null)\n {\n list = new LinkedList<TimephasedCost>();\n }\n list.add(cost);\n //System.out.println(cost);\n\n previousTotalCost = currentTotalCost;\n }\n\n blockStartDate = blockEndDate;\n index += blockSize;\n }\n\n if (list != null)\n {\n result = new DefaultTimephasedCostContainer(calendar, normaliser, list, raw);\n }\n }\n\n return result;\n }"
] |
Split a span into two by adding a knot in the middle.
@param n the span index | [
"public void splitSpan(int n) {\n\t\tint x = (xKnots[n] + xKnots[n+1])/2;\n\t\taddKnot(x, getColor(x/256.0f), knotTypes[n]);\n\t\trebuildGradient();\n\t}"
] | [
"public static int[] ConcatenateInt(List<int[]> arrays) {\n\n int size = 0;\n for (int i = 0; i < arrays.size(); i++) {\n size += arrays.get(i).length;\n }\n\n int[] all = new int[size];\n int idx = 0;\n\n for (int i = 0; i < arrays.size(); i++) {\n int[] v = arrays.get(i);\n for (int j = 0; j < v.length; j++) {\n all[idx++] = v[i];\n }\n }\n\n return all;\n }",
"public static void registerMbean(Object mbean, ObjectName name) {\n registerMbean(ManagementFactory.getPlatformMBeanServer(),\n JmxUtils.createModelMBean(mbean),\n name);\n }",
"private void readTasks(Document cdp)\n {\n //\n // Sort the projects into the correct order\n //\n List<Project> projects = new ArrayList<Project>(cdp.getProjects().getProject());\n final AlphanumComparator comparator = new AlphanumComparator();\n\n Collections.sort(projects, new Comparator<Project>()\n {\n @Override public int compare(Project o1, Project o2)\n {\n return comparator.compare(o1.getOutlineNumber(), o2.getOutlineNumber());\n }\n });\n\n for (Project project : cdp.getProjects().getProject())\n {\n readProject(project);\n }\n }",
"@Override\n public final Boolean optBool(final String key, final Boolean defaultValue) {\n Boolean result = optBool(key);\n return result == null ? defaultValue : result;\n }",
"public static Context getContext()\r\n {\r\n if (ctx == null)\r\n {\r\n try\r\n {\r\n setContext(null);\r\n }\r\n catch (Exception e)\r\n {\r\n log.error(\"Cannot instantiate the InitialContext\", e);\r\n throw new OJBRuntimeException(e);\r\n }\r\n }\r\n return ctx;\r\n }",
"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 String getPromotionDetailsJsonModel() throws IOException {\n final PromotionEvaluationReport sampleReport = new PromotionEvaluationReport();\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.UNPROMOTED_MSG, \"com.acme.secure-smh:core-relay:1.2.0\"), MAJOR);\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.DO_NOT_USE_MSG, \"com.google.guava:guava:20.0\"), MAJOR);\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.MISSING_LICENSE_MSG, \"org.apache.maven.wagon:wagon-webdav-jackrabbit:2.12\"), MINOR);\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.UNACCEPTABLE_LICENSE_MSG,\n \"aopaliance:aopaliance:1.0 licensed as Attribution-ShareAlike 2.5 Generic, \" +\n \"org.polyjdbc:polyjdbc0.7.1 licensed as Creative Commons Attribution-ShareAlike 3.0 Unported License\"),\n MINOR);\n\n sampleReport.addMessage(PromotionReportTranslator.SNAPSHOT_VERSION_MSG, Tag.CRITICAL);\n return JsonUtils.serialize(sampleReport);\n }",
"private void renderAsLI(Writer writer, ProjectModel project, Iterator<Link> links, boolean wrap) throws IOException\n {\n if (!links.hasNext())\n return;\n\n if (wrap)\n writer.append(\"<ul>\");\n while (links.hasNext())\n {\n Link link = links.next();\n writer.append(\"<li>\");\n renderLink(writer, project, link);\n writer.append(\"</li>\");\n }\n if (wrap)\n writer.append(\"</ul>\");\n }",
"private String escapeText(StringBuilder sb, String text)\n {\n int length = text.length();\n char c;\n\n sb.setLength(0);\n\n for (int loop = 0; loop < length; loop++)\n {\n c = text.charAt(loop);\n\n switch (c)\n {\n case '<':\n {\n sb.append(\"<\");\n break;\n }\n\n case '>':\n {\n sb.append(\">\");\n break;\n }\n\n case '&':\n {\n sb.append(\"&\");\n break;\n }\n\n default:\n {\n if (validXMLCharacter(c))\n {\n if (c > 127)\n {\n sb.append(\"&#\" + (int) c + \";\");\n }\n else\n {\n sb.append(c);\n }\n }\n\n break;\n }\n }\n }\n\n return (sb.toString());\n }"
] |
Encode a path in a manner suitable for a GET request
@param in The path to encode, eg "a/document"
@return The encoded path eg "a%2Fdocument" | [
"String encodePath(String in) {\n try {\n String encodedString = HierarchicalUriComponents.encodeUriComponent(in, \"UTF-8\",\n HierarchicalUriComponents.Type.PATH_SEGMENT);\n if (encodedString.startsWith(_design_prefix_encoded) ||\n encodedString.startsWith(_local_prefix_encoded)) {\n // we replaced the first slash in the design or local doc URL, which we shouldn't\n // so let's put it back\n return encodedString.replaceFirst(\"%2F\", \"/\");\n } else {\n return encodedString;\n }\n } catch (UnsupportedEncodingException uee) {\n // This should never happen as every implementation of the java platform is required\n // to support UTF-8.\n throw new RuntimeException(\n \"Couldn't encode ID \" + in,\n uee);\n }\n }"
] | [
"public Map<Double, SingleAssetEuropeanOptionProductDescriptor> getDescriptors(LocalDate referenceDate){\n\n\t\tint numberOfStrikes = strikes.length;\n\t\tHashMap<Double, SingleAssetEuropeanOptionProductDescriptor> descriptors = new HashMap<Double, SingleAssetEuropeanOptionProductDescriptor>();\n\n\t\tLocalDate maturityDate = FloatingpointDate.getDateFromFloatingPointDate(referenceDate, maturity);\n\t\tfor(int i = 0; i< numberOfStrikes; i++) {\n\t\t\tdescriptors.put(strikes[i], new SingleAssetEuropeanOptionProductDescriptor(underlyingName, maturityDate, strikes[i]));\n\t\t}\n\n\t\treturn descriptors;\n\t}",
"private Server setUpServer() {\n Server server = new Server(port);\n ResourceHandler handler = new ResourceHandler();\n handler.setDirectoriesListed(true);\n handler.setWelcomeFiles(new String[]{\"index.html\"});\n handler.setResourceBase(getReportDirectoryPath().toAbsolutePath().toString());\n HandlerList handlers = new HandlerList();\n handlers.setHandlers(new Handler[]{handler, new DefaultHandler()});\n server.setStopAtShutdown(true);\n server.setHandler(handlers);\n return server;\n }",
"public StandaloneCommandBuilder setDebug(final boolean suspend, final int port) {\n debugArg = String.format(DEBUG_FORMAT, (suspend ? \"y\" : \"n\"), port);\n return this;\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 }",
"public static base_response clear(nitro_service client) throws Exception {\n\t\tnssimpleacl clearresource = new nssimpleacl();\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}",
"public void setAutoClose(boolean autoClose) {\n this.autoClose = autoClose;\n\n if (autoCloseHandlerRegistration != null) {\n autoCloseHandlerRegistration.removeHandler();\n autoCloseHandlerRegistration = null;\n }\n\n if (autoClose) {\n autoCloseHandlerRegistration = registerHandler(addValueChangeHandler(event -> close()));\n }\n }",
"public void logException(Level level) {\n if (!LOG.isLoggable(level)) {\n return;\n }\n final StringBuilder builder = new StringBuilder();\n builder.append(\"\\n----------------------------------------------------\");\n builder.append(\"\\nMonitoringException\");\n builder.append(\"\\n----------------------------------------------------\");\n builder.append(\"\\nCode: \").append(code);\n builder.append(\"\\nMessage: \").append(message);\n builder.append(\"\\n----------------------------------------------------\");\n if (events != null) {\n for (Event event : events) {\n builder.append(\"\\nEvent:\");\n if (event.getMessageInfo() != null) {\n builder.append(\"\\nMessage id: \").append(event.getMessageInfo().getMessageId());\n builder.append(\"\\nFlow id: \").append(event.getMessageInfo().getFlowId());\n builder.append(\"\\n----------------------------------------------------\");\n } else {\n builder.append(\"\\nNo message id and no flow id\");\n }\n }\n }\n builder.append(\"\\n----------------------------------------------------\\n\");\n LOG.log(level, builder.toString(), this);\n }",
"@Override\n public void map(GenericData.Record record,\n AvroCollector<Pair<ByteBuffer, ByteBuffer>> collector,\n Reporter reporter) throws IOException {\n\n byte[] keyBytes = null;\n byte[] valBytes = null;\n Object keyRecord = null;\n Object valRecord = null;\n try {\n keyRecord = record.get(keyField);\n valRecord = record.get(valField);\n keyBytes = keySerializer.toBytes(keyRecord);\n valBytes = valueSerializer.toBytes(valRecord);\n\n this.collectorWrapper.setCollector(collector);\n this.mapper.map(keyBytes, valBytes, this.collectorWrapper);\n\n recordCounter++;\n } catch (OutOfMemoryError oom) {\n logger.error(oomErrorMessage(reporter));\n if (keyBytes == null) {\n logger.error(\"keyRecord caused OOM!\");\n } else {\n logger.error(\"keyRecord: \" + keyRecord);\n logger.error(\"valRecord: \" + (valBytes == null ? \"caused OOM\" : valRecord));\n }\n throw new VoldemortException(oomErrorMessage(reporter), oom);\n }\n }",
"protected Object[] escape(final Format format, Object... args) {\n // Transformer that escapes HTML,XML,JSON strings\n Transformer<Object, Object> escapingTransformer = new Transformer<Object, Object>() {\n @Override\n public Object transform(Object object) {\n return format.escapeValue(object);\n }\n };\n List<Object> list = Arrays.asList(ArrayUtils.clone(args));\n CollectionUtils.transform(list, escapingTransformer);\n return list.toArray();\n }"
] |
This method is called to alert project listeners to the fact that
a resource assignment has been written to a project file.
@param resourceAssignment resourceAssignment instance | [
"public void fireAssignmentWrittenEvent(ResourceAssignment resourceAssignment)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.assignmentWritten(resourceAssignment);\n }\n }\n }"
] | [
"public ApnsServiceBuilder withSocksProxy(String host, int port) {\n Proxy proxy = new Proxy(Proxy.Type.SOCKS,\n new InetSocketAddress(host, port));\n return withProxy(proxy);\n }",
"private void addCalendar(MpxjTreeNode parentNode, final ProjectCalendar calendar)\n {\n MpxjTreeNode calendarNode = new MpxjTreeNode(calendar, CALENDAR_EXCLUDED_METHODS)\n {\n @Override public String toString()\n {\n return calendar.getName();\n }\n };\n parentNode.add(calendarNode);\n\n MpxjTreeNode daysFolder = new MpxjTreeNode(\"Days\");\n calendarNode.add(daysFolder);\n\n for (Day day : Day.values())\n {\n addCalendarDay(daysFolder, calendar, day);\n }\n\n MpxjTreeNode exceptionsFolder = new MpxjTreeNode(\"Exceptions\");\n calendarNode.add(exceptionsFolder);\n\n for (ProjectCalendarException exception : calendar.getCalendarExceptions())\n {\n addCalendarException(exceptionsFolder, exception);\n }\n }",
"public boolean matches(String resourcePath) {\n if (!valid) {\n return false;\n }\n if (resourcePath == null) {\n return acceptsContextPathEmpty;\n }\n if (contextPathRegex != null && !contextPathRegex.matcher(resourcePath).matches()) {\n return false;\n }\n if (contextPathBlacklistRegex != null && contextPathBlacklistRegex.matcher(resourcePath).matches()) {\n return false;\n }\n return true;\n }",
"public static Span toSpan(Range range) {\n return new Span(toRowColumn(range.getStartKey()), range.isStartKeyInclusive(),\n toRowColumn(range.getEndKey()), range.isEndKeyInclusive());\n }",
"@Override\n\tpublic boolean isSinglePrefixBlock() {\n\t\tInteger networkPrefixLength = getNetworkPrefixLength();\n\t\tif(networkPrefixLength == null) {\n\t\t\treturn false;\n\t\t}\n\t\treturn containsSinglePrefixBlock(networkPrefixLength);\n\t}",
"public void process(String inputFile, String outputFile) throws Exception\n {\n System.out.println(\"Reading input file started.\");\n long start = System.currentTimeMillis();\n ProjectFile projectFile = readFile(inputFile);\n long elapsed = System.currentTimeMillis() - start;\n System.out.println(\"Reading input file completed in \" + elapsed + \"ms.\");\n\n System.out.println(\"Writing output file started.\");\n start = System.currentTimeMillis();\n ProjectWriter writer = ProjectWriterUtility.getProjectWriter(outputFile);\n writer.write(projectFile, outputFile);\n elapsed = System.currentTimeMillis() - start;\n System.out.println(\"Writing output completed in \" + elapsed + \"ms.\");\n }",
"public static String convertToSQL92(char escape, char multi, char single, String pattern)\n\t\t\tthrows IllegalArgumentException {\n\t\tif ((escape == '\\'') || (multi == '\\'') || (single == '\\'')) {\n\t\t\tthrow new IllegalArgumentException(\"do not use single quote (') as special char!\");\n\t\t}\n\t\t\n\t\tStringBuilder result = new StringBuilder(pattern.length() + 5);\n\t\tint i = 0;\n\t\twhile (i < pattern.length()) {\n\t\t\tchar chr = pattern.charAt(i);\n\t\t\tif (chr == escape) {\n\t\t\t\t// emit the next char and skip it\n\t\t\t\tif (i != (pattern.length() - 1)) {\n\t\t\t\t\tresult.append(pattern.charAt(i + 1));\n\t\t\t\t}\n\t\t\t\ti++; // skip next char\n\t\t\t} else if (chr == single) {\n\t\t\t\tresult.append('_');\n\t\t\t} else if (chr == multi) {\n\t\t\t\tresult.append('%');\n\t\t\t} else if (chr == '\\'') {\n\t\t\t\tresult.append('\\'');\n\t\t\t\tresult.append('\\'');\n\t\t\t} else {\n\t\t\t\tresult.append(chr);\n\t\t\t}\n\t\t\ti++;\n\t\t}\n\n\t\treturn result.toString();\n\t}",
"public Number getMinutesPerMonth()\n {\n return Integer.valueOf(NumberHelper.getInt(getMinutesPerDay()) * NumberHelper.getInt(getDaysPerMonth()));\n }",
"public <T extends Variable> T lookupVariable(String token) {\n Variable result = variables.get(token);\n return (T)result;\n }"
] |
Computes the unbiased standard deviation of all the elements.
@return standard deviation | [
"public double stdev() {\n double m = mean();\n\n double total = 0;\n\n final int N = getNumElements();\n if( N <= 1 )\n throw new IllegalArgumentException(\"There must be more than one element to compute stdev\");\n\n\n for( int i = 0; i < N; i++ ) {\n double x = get(i);\n\n total += (x - m)*(x - m);\n }\n\n total /= (N-1);\n\n return Math.sqrt(total);\n }"
] | [
"public static final TimeUnit getTimeUnit(int value)\n {\n TimeUnit result = null;\n\n switch (value)\n {\n case 1:\n {\n // Appears to mean \"use the document format\"\n result = TimeUnit.ELAPSED_DAYS;\n break;\n }\n\n case 2:\n {\n result = TimeUnit.HOURS;\n break;\n }\n\n case 4:\n {\n result = TimeUnit.DAYS;\n break;\n }\n\n case 6:\n {\n result = TimeUnit.WEEKS;\n break;\n }\n\n case 8:\n case 10:\n {\n result = TimeUnit.MONTHS;\n break;\n }\n\n case 12:\n {\n result = TimeUnit.YEARS;\n break;\n }\n\n default:\n {\n break;\n }\n }\n\n return result;\n }",
"protected static <E extends LogRecordHandler> boolean removeHandler(Class<E> toRemove) {\r\n boolean rtn = false;\r\n Iterator<LogRecordHandler> iter = handlers.iterator();\r\n while(iter.hasNext()){\r\n if(iter.next().getClass().equals(toRemove)){\r\n rtn = true;\r\n iter.remove();\r\n }\r\n }\r\n return rtn;\r\n }",
"@Override public Integer[] getUniqueIdentifierArray()\n {\n Integer[] result = new Integer[m_table.size()];\n int index = 0;\n for (Integer value : m_table.keySet())\n {\n result[index] = value;\n ++index;\n }\n return (result);\n }",
"public GVRAnimator animate(int animIndex, float timeInSec)\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 anim.animate(timeInSec);\n return anim;\n }",
"public void fireTaskWrittenEvent(Task task)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.taskWritten(task);\n }\n }\n }",
"public void prepareStatus() {\n globalLineCounter = new AtomicLong(0);\n time = new AtomicLong(System.currentTimeMillis());\n startTime = System.currentTimeMillis();\n lastCount = 0;\n\n // Status thread regularly reports on what is happening\n Thread statusThread = new Thread() {\n public void run() {\n while (true) {\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n System.out.println(\"Status thread interrupted\");\n }\n\n long thisTime = System.currentTimeMillis();\n long currentCount = globalLineCounter.get();\n\n if (thisTime - time.get() > 1000) {\n long oldTime = time.get();\n time.set(thisTime);\n double avgRate = 1000.0 * currentCount / (thisTime - startTime);\n double instRate = 1000.0 * (currentCount - lastCount) / (thisTime - oldTime);\n lastCount = currentCount;\n System.out.println(currentCount + \" AvgRage:\" + ((int) avgRate) + \" lines/sec instRate:\"\n + ((int) instRate) + \" lines/sec Unassigned Work: \"\n + remainingBlocks.get() + \" blocks\");\n }\n }\n }\n };\n statusThread.start();\n }",
"protected final void error(final HttpServletResponse httpServletResponse, final Throwable e) {\n httpServletResponse.setContentType(\"text/plain\");\n httpServletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());\n try (PrintWriter out = httpServletResponse.getWriter()) {\n out.println(\"Error while processing request:\");\n LOGGER.error(\"Error while processing request\", e);\n } catch (IOException ex) {\n throw ExceptionUtils.getRuntimeException(ex);\n }\n }",
"private boolean isWorkingDate(Date date, Day day)\n {\n ProjectCalendarDateRanges ranges = getRanges(date, null, day);\n return ranges.getRangeCount() != 0;\n }",
"public static void addStory(File caseManager, String storyName,\n String testPath, String user, String feature, String benefit) throws BeastException {\n FileWriter caseManagerWriter;\n\n String storyClass = SystemReader.createClassName(storyName);\n try {\n BufferedReader reader = new BufferedReader(new FileReader(\n caseManager));\n String targetLine1 = \" public void \"\n + MASReader.createFirstLowCaseName(storyName) + \"() {\";\n String targetLine2 = \" Result result = JUnitCore.runClasses(\" + testPath + \".\"\n + storyClass + \".class);\";\n String in;\n while ((in = reader.readLine()) != null) {\n if (in.equals(targetLine1)) {\n while ((in = reader.readLine()) != null) {\n if (in.equals(targetLine2)) {\n reader.close();\n // This test is already written in the case manager.\n return;\n }\n }\n reader.close();\n throw new BeastException(\"Two different stories with the same name (same method name) are being created in the same CaseManager file. That is not possible. Please, change the name of the story: \" + testPath + \".\"\n + storyClass + \".java\");\n }\n }\n reader.close();\n caseManagerWriter = new FileWriter(caseManager, true);\n caseManagerWriter.write(\" /**\\n\");\n caseManagerWriter.write(\" * This is the story: \" + storyName\n + \"\\n\");\n caseManagerWriter.write(\" * requested by: \" + user + \"\\n\");\n caseManagerWriter.write(\" * providing the feature: \" + feature\n + \"\\n\");\n caseManagerWriter.write(\" * so the user gets the benefit: \"\n + benefit + \"\\n\");\n caseManagerWriter.write(\" */\\n\");\n caseManagerWriter.write(\" @Test\\n\");\n caseManagerWriter.write(\" public void \"\n + MASReader.createFirstLowCaseName(storyName) + \"() {\\n\");\n caseManagerWriter.write(\" Result result = JUnitCore.runClasses(\" + testPath\n + \".\" + storyClass + \".class);\\n\");\n caseManagerWriter.write(\" Assert.assertTrue(result.wasSuccessful());\\n\");\n caseManagerWriter.write(\" }\\n\");\n caseManagerWriter.write(\"\\n\");\n caseManagerWriter.flush();\n caseManagerWriter.close();\n } catch (IOException e) {\n Logger logger = Logger.getLogger(\"CreateMASCaseManager.createTest\");\n logger.info(\"ERROR writing the file\");\n }\n\n }"
] |
Use this API to enable snmpalarm resources of given names. | [
"public static base_responses enable(nitro_service client, String trapname[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (trapname != null && trapname.length > 0) {\n\t\t\tsnmpalarm enableresources[] = new snmpalarm[trapname.length];\n\t\t\tfor (int i=0;i<trapname.length;i++){\n\t\t\t\tenableresources[i] = new snmpalarm();\n\t\t\t\tenableresources[i].trapname = trapname[i];\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, enableresources,\"enable\");\n\t\t}\n\t\treturn result;\n\t}"
] | [
"public void setAllowBlank(boolean allowBlank) {\n this.allowBlank = allowBlank;\n\n // Setup the allow blank validation\n if (!allowBlank) {\n if (blankValidator == null) {\n blankValidator = createBlankValidator();\n }\n setupBlurValidation();\n addValidator(blankValidator);\n } else {\n removeValidator(blankValidator);\n }\n }",
"public ItemRequest<Attachment> findById(String attachment) {\n \n String path = String.format(\"/attachments/%s\", attachment);\n return new ItemRequest<Attachment>(this, Attachment.class, path, \"GET\");\n }",
"protected StrongCounter getCounterOrCreateIt(String counterName, int initialValue) {\n\t\tCounterManager counterManager = EmbeddedCounterManagerFactory.asCounterManager( cacheManager );\n\t\tif ( !counterManager.isDefined( counterName ) ) {\n\t\t\tLOG.tracef( \"Counter %s is not defined, creating it\", counterName );\n\n\t\t\t// global configuration is mandatory in order to define\n\t\t\t// a new clustered counter with persistent storage\n\t\t\tvalidateGlobalConfiguration();\n\n\t\t\tcounterManager.defineCounter( counterName,\n\t\t\t\tCounterConfiguration.builder(\n\t\t\t\t\tCounterType.UNBOUNDED_STRONG )\n\t\t\t\t\t\t.initialValue( initialValue )\n\t\t\t\t\t\t.storage( Storage.PERSISTENT )\n\t\t\t\t\t\t.build() );\n\t\t}\n\n\t\tStrongCounter strongCounter = counterManager.getStrongCounter( counterName );\n\t\treturn strongCounter;\n\t}",
"private static void setCmsOfflineProject(CmsObject cms) {\n\n if (null == cms) {\n return;\n }\n\n final CmsRequestContext cmsContext = cms.getRequestContext();\n final CmsProject cmsProject = cmsContext.getCurrentProject();\n\n if (cmsProject.isOnlineProject()) {\n CmsProject cmsOfflineProject;\n try {\n cmsOfflineProject = cms.readProject(\"Offline\");\n cmsContext.setCurrentProject(cmsOfflineProject);\n } catch (CmsException e) {\n LOG.warn(\"Could not set the current project to \\\"Offline\\\". \");\n }\n }\n }",
"@Override public Integer getOffset(Integer id, Integer type)\n {\n Integer result = null;\n\n Map<Integer, Integer> map = m_table.get(id);\n if (map != null && type != null)\n {\n result = map.get(type);\n }\n\n return (result);\n }",
"protected <T1> void dispatchCommand(final BiConsumer<P, T1> action, final T1 routable1) {\n routingFor(routable1)\n .routees()\n .forEach(routee -> routee.receiveCommand(action, routable1));\n }",
"public static boolean hasValidContentAdditionParameterDefined(ModelNode operation) {\n for (String s : DeploymentAttributes.MANAGED_CONTENT_ATTRIBUTES.keySet()) {\n if (operation.hasDefined(s)) {\n return true;\n }\n }\n return false;\n }",
"public String getTitle(Locale locale)\n {\n String result = null;\n\n if (m_title != null)\n {\n result = m_title;\n }\n else\n {\n if (m_fieldType != null)\n {\n result = m_project.getCustomFields().getCustomField(m_fieldType).getAlias();\n if (result == null)\n {\n result = m_fieldType.getName(locale);\n }\n }\n }\n\n return (result);\n }",
"private void batchStatusLog(int batchCount,\n int numBatches,\n int partitionStoreCount,\n int numPartitionStores,\n long totalTimeMs) {\n // Calculate the estimated end time and pretty print stats\n double rate = 1;\n long estimatedTimeMs = 0;\n if(numPartitionStores > 0) {\n rate = partitionStoreCount / numPartitionStores;\n estimatedTimeMs = (long) (totalTimeMs / rate) - totalTimeMs;\n }\n\n StringBuilder sb = new StringBuilder();\n sb.append(\"Batch Complete!\")\n .append(Utils.NEWLINE)\n .append(\"\\tbatches moved: \")\n .append(batchCount)\n .append(\" out of \")\n .append(numBatches)\n .append(Utils.NEWLINE)\n .append(\"\\tPartition stores moved: \")\n .append(partitionStoreCount)\n .append(\" out of \")\n .append(numPartitionStores)\n .append(Utils.NEWLINE)\n .append(\"\\tPercent done: \")\n .append(decimalFormatter.format(rate * 100.0))\n .append(Utils.NEWLINE)\n .append(\"\\tEstimated time left: \")\n .append(estimatedTimeMs)\n .append(\" ms (\")\n .append(TimeUnit.MILLISECONDS.toHours(estimatedTimeMs))\n .append(\" hours)\");\n RebalanceUtils.printBatchLog(batchCount, logger, sb.toString());\n }"
] |
Unmark a PersistenceBroker as preferred choice for current Thread
@param key The PBKey the broker is associated to
@param broker The PersistenceBroker to unmark | [
"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 }"
] | [
"public static int cudnnCreatePersistentRNNPlan(\n cudnnRNNDescriptor rnnDesc, \n int minibatch, \n int dataType, \n cudnnPersistentRNNPlan plan)\n {\n return checkResult(cudnnCreatePersistentRNNPlanNative(rnnDesc, minibatch, dataType, plan));\n }",
"public void cross(Vector3d v1, Vector3d v2) {\n double tmpx = v1.y * v2.z - v1.z * v2.y;\n double tmpy = v1.z * v2.x - v1.x * v2.z;\n double tmpz = v1.x * v2.y - v1.y * v2.x;\n\n x = tmpx;\n y = tmpy;\n z = tmpz;\n }",
"public static Face createTriangle(Vertex v0, Vertex v1, Vertex v2, double minArea) {\n Face face = new Face();\n HalfEdge he0 = new HalfEdge(v0, face);\n HalfEdge he1 = new HalfEdge(v1, face);\n HalfEdge he2 = new HalfEdge(v2, face);\n\n he0.prev = he2;\n he0.next = he1;\n he1.prev = he0;\n he1.next = he2;\n he2.prev = he1;\n he2.next = he0;\n\n face.he0 = he0;\n\n // compute the normal and offset\n face.computeNormalAndCentroid(minArea);\n return face;\n }",
"private String formatConstraintType(ConstraintType type)\n {\n return (type == null ? null : LocaleData.getStringArray(m_locale, LocaleData.CONSTRAINT_TYPES)[type.getValue()]);\n }",
"private static void addTimePerComponent(HashMap<String, Long> mapComponentTimes,\tComponent component) {\n Long currentTimeOfComponent = 0L;\n String key = component.getComponentType();\n if (mapComponentTimes.containsKey(key)) {\n currentTimeOfComponent = mapComponentTimes.get(key);\n }\n //when transactions are run in parallel, we should log the longest transaction only to avoid that \n //for ex 'Total time' would be 100ms and transactions in parallel to hornetQ will be 2000ms \n Long maxTime = Math.max(component.getTime(), currentTimeOfComponent);\n mapComponentTimes.put(key, maxTime);\n }",
"public boolean fling(float velocityX, float velocityY, float velocityZ) {\n boolean scrolled = true;\n float viewportX = mScrollable.getViewPortWidth();\n if (Float.isNaN(viewportX)) {\n viewportX = 0;\n }\n float maxX = Math.min(MAX_SCROLLING_DISTANCE,\n viewportX * MAX_VIEWPORT_LENGTHS);\n\n float viewportY = mScrollable.getViewPortHeight();\n if (Float.isNaN(viewportY)) {\n viewportY = 0;\n }\n float maxY = Math.min(MAX_SCROLLING_DISTANCE,\n viewportY * MAX_VIEWPORT_LENGTHS);\n\n float xOffset = (maxX * velocityX)/VELOCITY_MAX;\n float yOffset = (maxY * velocityY)/VELOCITY_MAX;\n\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"fling() velocity = [%f, %f, %f] offset = [%f, %f]\",\n velocityX, velocityY, velocityZ,\n xOffset, yOffset);\n\n if (equal(xOffset, 0)) {\n xOffset = Float.NaN;\n }\n\n if (equal(yOffset, 0)) {\n yOffset = Float.NaN;\n }\n\n// TODO: Think about Z-scrolling\n mScrollable.scrollByOffset(xOffset, yOffset, Float.NaN, mInternalScrollListener);\n\n return scrolled;\n }",
"public String prepareStatementString() throws SQLException {\n\t\tList<ArgumentHolder> argList = new ArrayList<ArgumentHolder>();\n\t\treturn buildStatementString(argList);\n\t}",
"public int getHistoryCount(int profileId, String clientUUID, HashMap<String, String[]> searchFilter) {\n int count = 0;\n Statement query = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n\n String sqlQuery = \"SELECT COUNT(\" + Constants.GENERIC_ID + \") FROM \" + Constants.DB_TABLE_HISTORY + \" \";\n\n // see if profileId is set or not (-1)\n if (profileId != -1) {\n sqlQuery += \"WHERE \" + Constants.GENERIC_PROFILE_ID + \"=\" + profileId + \" \";\n }\n\n if (clientUUID != null && clientUUID.compareTo(\"\") != 0) {\n sqlQuery += \"AND \" + Constants.GENERIC_CLIENT_UUID + \"='\" + clientUUID + \"' \";\n }\n\n sqlQuery += \";\";\n\n logger.info(\"Query: {}\", sqlQuery);\n\n query = sqlConnection.createStatement();\n results = query.executeQuery(sqlQuery);\n if (results.next()) {\n count = results.getInt(1);\n }\n query.close();\n } catch (Exception e) {\n\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n\n return count;\n }",
"public static snmpalarm get(nitro_service service, String trapname) throws Exception{\n\t\tsnmpalarm obj = new snmpalarm();\n\t\tobj.set_trapname(trapname);\n\t\tsnmpalarm response = (snmpalarm) obj.get_resource(service);\n\t\treturn response;\n\t}"
] |
Select which view to display based on the state of the promotion. Will return the form if user selects to perform
promotion. Progress will be returned if the promotion is currently in progress. | [
"@SuppressWarnings({\"UnusedDeclaration\"})\n public void doIndex(StaplerRequest req, StaplerResponse resp) throws IOException, ServletException {\n req.getView(this, chooseAction()).forward(req, resp);\n }"
] | [
"public String getName() {\n if (name == null && securityIdentity != null) {\n name = securityIdentity.getPrincipal().getName();\n }\n\n return name;\n }",
"@SafeVarargs\n public static <T> Set<T> create(final T... values) {\n Set<T> result = new HashSet<>(values.length);\n Collections.addAll(result, values);\n return result;\n }",
"public void reportError(NodeT faulted, Throwable throwable) {\n faulted.setPreparer(true);\n String dependency = faulted.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.onFaultedResolution(dependency, throwable);\n if (dependent.hasAllResolved()) {\n queue.add(dependent.key());\n }\n } finally {\n dependent.lock().unlock();\n }\n }\n }",
"private static void firstDotConstellation(int[] dollarPositions, int[] dotPositions, int nestingLevel) {\n int i = 0;\n int unassigned = dotPositions.length - nestingLevel;\n\n for (; i < unassigned; ++i) {\n dotPositions[i] = -1;\n }\n\n for (; i < dotPositions.length; ++i) {\n dotPositions[i] = dollarPositions[i];\n }\n }",
"public void mark() {\n final long currentTimeMillis = clock.currentTimeMillis();\n\n synchronized (queue) {\n if (queue.size() == capacity) {\n /*\n * we're all filled up already, let's dequeue the oldest\n * timestamp to make room for this new one.\n */\n queue.removeFirst();\n }\n queue.addLast(currentTimeMillis);\n }\n }",
"public synchronized void addMapStats(\n final MapfishMapContext mapContext, final MapAttribute.MapAttributeValues mapValues) {\n this.mapStats.add(new MapStats(mapContext, mapValues));\n }",
"public static appfwprofile_xmlvalidationurl_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_xmlvalidationurl_binding obj = new appfwprofile_xmlvalidationurl_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_xmlvalidationurl_binding response[] = (appfwprofile_xmlvalidationurl_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void initKeySetForXmlBundle() {\n\n // consider only available locales\n for (Locale l : m_locales) {\n if (m_xmlBundle.hasLocale(l)) {\n Set<Object> keys = new HashSet<Object>();\n for (I_CmsXmlContentValue msg : m_xmlBundle.getValueSequence(\"Message\", l).getValues()) {\n String msgpath = msg.getPath();\n keys.add(m_xmlBundle.getStringValue(m_cms, msgpath + \"/Key\", l));\n }\n m_keyset.updateKeySet(null, keys);\n }\n }\n\n }",
"private void populateMilestone(Row row, Task task)\n {\n task.setMilestone(true);\n //PROJID\n task.setUniqueID(row.getInteger(\"MILESTONEID\"));\n task.setStart(row.getDate(\"GIVEN_DATE_TIME\"));\n task.setFinish(row.getDate(\"GIVEN_DATE_TIME\"));\n //PROGREST_PERIOD\n //SYMBOL_APPEARANCE\n //MILESTONE_TYPE\n //PLACEMENU\n task.setPercentageComplete(row.getBoolean(\"COMPLETED\") ? COMPLETE : INCOMPLETE);\n //INTERRUPTIBLE_X\n //ACTUAL_DURATIONTYPF\n //ACTUAL_DURATIONELA_MONTHS\n //ACTUAL_DURATIONHOURS\n task.setEarlyStart(row.getDate(\"EARLY_START_DATE\"));\n task.setLateStart(row.getDate(\"LATE_START_DATE\"));\n //FREE_START_DATE\n //START_CONSTRAINT_DATE\n //END_CONSTRAINT_DATE\n //EFFORT_BUDGET\n //NATURAO_ORDER\n //LOGICAL_PRECEDENCE\n //SPAVE_INTEGER\n //SWIM_LANE\n //USER_PERCENT_COMPLETE\n //OVERALL_PERCENV_COMPLETE\n //OVERALL_PERCENT_COMPL_WEIGHT\n task.setName(row.getString(\"NARE\"));\n //NOTET\n task.setText(1, row.getString(\"UNIQUE_TASK_ID\"));\n task.setCalendar(m_project.getCalendarByUniqueID(row.getInteger(\"CALENDAU\")));\n //EFFORT_TIMI_UNIT\n //WORL_UNIT\n //LATEST_ALLOC_PROGRESS_PERIOD\n //WORN\n //CONSTRAINU\n //PRIORITB\n //CRITICAM\n //USE_PARENU_CALENDAR\n //BUFFER_TASK\n //MARK_FOS_HIDING\n //OWNED_BY_TIMESHEEV_X\n //START_ON_NEX_DAY\n //LONGEST_PATH\n //DURATIOTTYPF\n //DURATIOTELA_MONTHS\n //DURATIOTHOURS\n //STARZ\n //ENJ\n //DURATION_TIMJ_UNIT\n //UNSCHEDULABLG\n //SUBPROJECT_ID\n //ALT_ID\n //LAST_EDITED_DATE\n //LAST_EDITED_BY\n task.setDuration(Duration.getInstance(0, TimeUnit.HOURS));\n }"
] |
Load the windows resize handler with initial view port detection. | [
"protected ViewPort load() {\n resize = Window.addResizeHandler(event -> {\n execute(event.getWidth(), event.getHeight());\n });\n\n execute(window().width(), (int)window().height());\n return viewPort;\n }"
] | [
"public Indexes listIndexes() {\n URI uri = new DatabaseURIHelper(db.getDBUri()).path(\"_index\").build();\n return client.couchDbClient.get(uri, Indexes.class);\n }",
"private int combineSubsetBlocks(Mode[] mode_type, int[] mode_length, int index_point) {\n /* bring together same type blocks */\n if (index_point > 1) {\n for (int i = 1; i < index_point; i++) {\n if (mode_type[i - 1] == mode_type[i]) {\n /* bring together */\n mode_length[i - 1] = mode_length[i - 1] + mode_length[i];\n /* decrease the list */\n for (int j = i + 1; j < index_point; j++) {\n mode_length[j - 1] = mode_length[j];\n mode_type[j - 1] = mode_type[j];\n }\n index_point--;\n i--;\n }\n }\n }\n return index_point;\n }",
"public static FormValidation validateEmails(String emails) {\n if (!Strings.isNullOrEmpty(emails)) {\n String[] recipients = StringUtils.split(emails, \" \");\n for (String email : recipients) {\n FormValidation validation = validateInternetAddress(email);\n if (validation != FormValidation.ok()) {\n return validation;\n }\n }\n }\n return FormValidation.ok();\n }",
"void flushLogQueue() {\n Set<String> problems = new LinkedHashSet<String>();\n synchronized (messageQueue) {\n Iterator<LogEntry> i = messageQueue.iterator();\n while (i.hasNext()) {\n problems.add(\"\\t\\t\" + i.next().getMessage() + \"\\n\");\n i.remove();\n }\n }\n if (!problems.isEmpty()) {\n logger.transformationWarnings(target.getHostName(), problems);\n }\n }",
"public static filterhtmlinjectionparameter get(nitro_service service, options option) throws Exception{\n\t\tfilterhtmlinjectionparameter obj = new filterhtmlinjectionparameter();\n\t\tfilterhtmlinjectionparameter[] response = (filterhtmlinjectionparameter[])obj.get_resources(service,option);\n\t\treturn response[0];\n\t}",
"public void addProjectListeners(List<ProjectListener> listeners)\n {\n if (listeners != null)\n {\n for (ProjectListener listener : listeners)\n {\n addProjectListener(listener);\n }\n }\n }",
"@Override\n public List<JobInstance> getJobs(Query query)\n {\n return JqmClientFactory.getClient().getJobs(query);\n }",
"private static void tryWritePreferenceOnDisk(Preferences preference) throws BackingStoreException {\n final String DUMMY_PROP=\"dummywrite\";\n instance.put(DUMMY_PROP,\"test\");\n instance.flush();\n instance.remove(DUMMY_PROP);\n instance.flush();\n }",
"public synchronized void doneTask(int stealerId, int donorId) {\n removeNodesFromWorkerList(Arrays.asList(stealerId, donorId));\n numTasksExecuting--;\n doneSignal.countDown();\n // Try and schedule more tasks now that resources may be available to do\n // so.\n scheduleMoreTasks();\n }"
] |
Gets a JsonObject containing any pending changes to this object that can be sent back to the Box API.
@return a JsonObject containing the pending changes. | [
"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 AwsServiceClient withCodecRegistry(@Nonnull final CodecRegistry codecRegistry) {\n return new AwsServiceClientImpl(proxy.withCodecRegistry(codecRegistry), dispatcher);\n }",
"public static SQLException create(String message, Throwable cause) {\n\t\tSQLException sqlException;\n\t\tif (cause instanceof SQLException) {\n\t\t\t// if the cause is another SQLException, pass alot of the SQL state\n\t\t\tsqlException = new SQLException(message, ((SQLException) cause).getSQLState());\n\t\t} else {\n\t\t\tsqlException = new SQLException(message);\n\t\t}\n\t\tsqlException.initCause(cause);\n\t\treturn sqlException;\n\t}",
"@CheckResult\n public boolean isCompatible(AbstractTransition another) {\n if (getClass().equals(another.getClass()) && mTarget == another.mTarget && mReverse == another.mReverse && ((mInterpolator == null && another.mInterpolator == null) ||\n mInterpolator.getClass().equals(another.mInterpolator.getClass()))) {\n return true;\n }\n return false;\n }",
"public static Dimension dimensionsToFit(Dimension target, Dimension source) {\n\n // if target width/height is zero then we have no preference for that, so set it to the original value,\n // since it cannot be any larger\n int maxWidth;\n if (target.getX() == 0) {\n maxWidth = source.getX();\n } else {\n maxWidth = target.getX();\n }\n\n int maxHeight;\n if (target.getY() == 0) {\n maxHeight = source.getY();\n } else {\n maxHeight = target.getY();\n }\n\n double wscale = maxWidth / (double) source.getX();\n double hscale = maxHeight / (double) source.getY();\n\n if (wscale < hscale)\n return new Dimension((int) (source.getX() * wscale), (int) (source.getY() * wscale));\n else\n return new Dimension((int) (source.getX() * hscale), (int) (source.getY() * hscale));\n }",
"public void updateShownOptions(boolean showModeSwitch, boolean showAddKeyOption) {\n\n if (showModeSwitch != m_showModeSwitch) {\n m_upperLeftComponent.removeAllComponents();\n m_upperLeftComponent.addComponent(m_languageSwitch);\n if (showModeSwitch) {\n m_upperLeftComponent.addComponent(m_modeSwitch);\n }\n m_upperLeftComponent.addComponent(m_filePathLabel);\n m_showModeSwitch = showModeSwitch;\n }\n if (showAddKeyOption != m_showAddKeyOption) {\n if (showAddKeyOption) {\n m_optionsComponent.addComponent(m_lowerLeftComponent, 0, 1);\n m_optionsComponent.addComponent(m_lowerRightComponent, 1, 1);\n } else {\n m_optionsComponent.removeComponent(0, 1);\n m_optionsComponent.removeComponent(1, 1);\n }\n m_showAddKeyOption = showAddKeyOption;\n }\n }",
"private void populateContainer(FieldType field, List<Pair<String, String>> items)\n {\n CustomField config = m_container.getCustomField(field);\n CustomFieldLookupTable table = config.getLookupTable();\n\n for (Pair<String, String> pair : items)\n {\n CustomFieldValueItem item = new CustomFieldValueItem(Integer.valueOf(0));\n item.setValue(pair.getFirst());\n item.setDescription(pair.getSecond());\n table.add(item);\n }\n }",
"public void value2x2_fast( double a11 , double a12, double a21 , double a22 )\n {\n double left = (a11+a22)/2.0;\n double inside = 4.0*a12*a21 + (a11-a22)*(a11-a22);\n\n if( inside < 0 ) {\n value0.real = value1.real = left;\n value0.imaginary = Math.sqrt(-inside)/2.0;\n value1.imaginary = -value0.imaginary;\n } else {\n double right = Math.sqrt(inside)/2.0;\n value0.real = (left+right);\n value1.real = (left-right);\n value0.imaginary = value1.imaginary = 0.0;\n }\n }",
"public DbOrganization getOrganization(final String organizationId) {\n final DbOrganization dbOrganization = repositoryHandler.getOrganization(organizationId);\n\n if(dbOrganization == null){\n throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)\n .entity(\"Organization \" + organizationId + \" does not exist.\").build());\n }\n\n return dbOrganization;\n }",
"private void parseMacro( TokenList tokens , Sequence sequence ) {\n Macro macro = new Macro();\n\n TokenList.Token t = tokens.getFirst().next;\n\n if( t.word == null ) {\n throw new ParseError(\"Expected the macro's name after \"+tokens.getFirst().word);\n }\n List<TokenList.Token> variableTokens = new ArrayList<TokenList.Token>();\n\n macro.name = t.word;\n t = t.next;\n t = parseMacroInput(variableTokens, t);\n for( TokenList.Token a : variableTokens ) {\n if( a.word == null) throw new ParseError(\"expected word in macro header\");\n macro.inputs.add(a.word);\n }\n t = t.next;\n if( t == null || t.getSymbol() != Symbol.ASSIGN)\n throw new ParseError(\"Expected assignment\");\n t = t.next;\n macro.tokens = new TokenList(t,tokens.last);\n\n sequence.addOperation(macro.createOperation(macros));\n }"
] |
Searches the set of imports to find a matching import by type name.
@param typeName
name of type (qualified or simple name allowed)
@return found import or {@code null} | [
"@Nullable\n\tpublic Import find(@Nonnull final String typeName) {\n\t\tCheck.notEmpty(typeName, \"typeName\");\n\t\tImport ret = null;\n\t\tfinal Type type = new Type(typeName);\n\t\tfor (final Import imp : imports) {\n\t\t\tif (imp.getType().getName().equals(type.getName())) {\n\t\t\t\tret = imp;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (ret == null) {\n\t\t\tfinal Type javaLangType = Type.evaluateJavaLangType(typeName);\n\t\t\tif (javaLangType != null) {\n\t\t\t\tret = Import.of(javaLangType);\n\t\t\t}\n\t\t}\n\t\treturn ret;\n\t}"
] | [
"private long interpolateTimeFromUpdate(TrackPositionUpdate lastTrackUpdate, CdjStatus newDeviceUpdate,\n BeatGrid beatGrid) {\n final int beatNumber = newDeviceUpdate.getBeatNumber();\n final boolean noLongerPlaying = !newDeviceUpdate.isPlaying();\n\n // If we have just stopped, see if we are near a cue (assuming that information is available), and if so,\n // the best assumption is that the DJ jumped to that cue.\n if (lastTrackUpdate.playing && noLongerPlaying) {\n final CueList.Entry jumpedTo = findAdjacentCue(newDeviceUpdate, beatGrid);\n if (jumpedTo != null) return jumpedTo.cueTime;\n }\n\n // Handle the special case where we were not playing either in the previous or current update, but the DJ\n // might have jumped to a different place in the track.\n if (!lastTrackUpdate.playing) {\n if (lastTrackUpdate.beatNumber == beatNumber && noLongerPlaying) { // Haven't moved\n return lastTrackUpdate.milliseconds;\n } else {\n if (noLongerPlaying) { // Have jumped without playing.\n if (beatNumber < 0) {\n return -1; // We don't know the position any more; weird to get into this state and still have a grid?\n }\n // As a heuristic, assume we are right before the beat?\n return timeOfBeat(beatGrid, beatNumber, newDeviceUpdate);\n }\n }\n }\n\n // One way or another, we are now playing.\n long elapsedMillis = (newDeviceUpdate.getTimestamp() - lastTrackUpdate.timestamp) / 1000000;\n long moved = Math.round(lastTrackUpdate.pitch * elapsedMillis);\n long interpolated = (lastTrackUpdate.reverse)?\n (lastTrackUpdate.milliseconds - moved) : lastTrackUpdate.milliseconds + moved;\n if (Math.abs(beatGrid.findBeatAtTime(interpolated) - beatNumber) < 2) {\n return interpolated; // Our calculations still look plausible\n }\n // The player has jumped or drifted somewhere unexpected, correct.\n if (newDeviceUpdate.isPlayingForwards()) {\n return timeOfBeat(beatGrid, beatNumber, newDeviceUpdate);\n } else {\n return beatGrid.getTimeWithinTrack(Math.min(beatNumber + 1, beatGrid.beatCount));\n }\n }",
"public 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}",
"public void logAttributeWarning(PathAddress address, String message, String attribute) {\n logAttributeWarning(address, null, message, attribute);\n }",
"public boolean equalId(Element otherElement) {\r\n\t\tif (getElementId() == null || otherElement.getElementId() == null) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\treturn getElementId().equalsIgnoreCase(otherElement.getElementId());\r\n\t}",
"private static char[] buildTable() {\n char[] table = new char[26];\n for (int ix = 0; ix < table.length; ix++)\n table[ix] = '0';\n table['B' - 'A'] = '1';\n table['P' - 'A'] = '1';\n table['F' - 'A'] = '1';\n table['V' - 'A'] = '1';\n table['C' - 'A'] = '2';\n table['S' - 'A'] = '2';\n table['K' - 'A'] = '2';\n table['G' - 'A'] = '2';\n table['J' - 'A'] = '2';\n table['Q' - 'A'] = '2';\n table['X' - 'A'] = '2';\n table['Z' - 'A'] = '2';\n table['D' - 'A'] = '3';\n table['T' - 'A'] = '3';\n table['L' - 'A'] = '4';\n table['M' - 'A'] = '5';\n table['N' - 'A'] = '5';\n table['R' - 'A'] = '6';\n return table;\n }",
"public Map<String, String> listConfig(String appName) {\n return connection.execute(new ConfigList(appName), apiKey);\n }",
"private RelationType getRelationType(Integer gpType)\n {\n RelationType result = null;\n if (gpType != null)\n {\n int index = NumberHelper.getInt(gpType);\n if (index > 0 && index < RELATION.length)\n {\n result = RELATION[index];\n }\n }\n\n if (result == null)\n {\n result = RelationType.FINISH_START;\n }\n\n return result;\n }",
"public boolean isWorkingDay(Day day)\n {\n DayType value = getWorkingDay(day);\n boolean result;\n\n if (value == DayType.DEFAULT)\n {\n ProjectCalendar cal = getParent();\n if (cal != null)\n {\n result = cal.isWorkingDay(day);\n }\n else\n {\n result = (day != Day.SATURDAY && day != Day.SUNDAY);\n }\n }\n else\n {\n result = (value == DayType.WORKING);\n }\n\n return (result);\n }",
"@Deprecated\n public String get(String path) {\n final JsonValue value = this.values.get(this.pathToProperty(path));\n if (value == null) {\n return null;\n }\n if (!value.isString()) {\n return value.toString();\n }\n return value.asString();\n }"
] |
Checks that a field exists and contains a non-null value.
@param fieldName the name of the field to check existence/value of.
@return true if the field exists in the result set and has a non-null value; false otherwise. | [
"public boolean hasValue(String fieldName) {\n\t\treturn resultMap.containsKey(fieldName) && resultMap.get(fieldName) != null;\n\t}"
] | [
"protected static void checkChannels(final Iterable<String> channels) {\n if (channels == null) {\n throw new IllegalArgumentException(\"channels must not be null\");\n }\n for (final String channel : channels) {\n if (channel == null || \"\".equals(channel)) {\n throw new IllegalArgumentException(\"channels' members must not be null: \" + channels);\n }\n }\n }",
"public static String unexpandLine(CharSequence self, int tabStop) {\n StringBuilder builder = new StringBuilder(self.toString());\n int index = 0;\n while (index + tabStop < builder.length()) {\n // cut original string in tabstop-length pieces\n String piece = builder.substring(index, index + tabStop);\n // count trailing whitespace characters\n int count = 0;\n while ((count < tabStop) && (Character.isWhitespace(piece.charAt(tabStop - (count + 1)))))\n count++;\n // replace if whitespace was found\n if (count > 0) {\n piece = piece.substring(0, tabStop - count) + '\\t';\n builder.replace(index, index + tabStop, piece);\n index = index + tabStop - (count - 1);\n } else\n index = index + tabStop;\n }\n return builder.toString();\n }",
"public static cachepolicylabel_binding get(nitro_service service, String labelname) throws Exception{\n\t\tcachepolicylabel_binding obj = new cachepolicylabel_binding();\n\t\tobj.set_labelname(labelname);\n\t\tcachepolicylabel_binding response = (cachepolicylabel_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public Client getClient(int clientId) throws Exception {\n Client client = null;\n\n PreparedStatement statement = null;\n ResultSet results = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n String queryString = \"SELECT * FROM \" + Constants.DB_TABLE_CLIENT +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\";\n\n statement = sqlConnection.prepareStatement(queryString);\n statement.setInt(1, clientId);\n\n results = statement.executeQuery();\n if (results.next()) {\n client = this.getClientFromResultSet(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\n return client;\n }",
"private static String findOutputPath(String[][] options) {\n\tfor (int i = 0; i < options.length; i++) {\n\t if (options[i][0].equals(\"-d\"))\n\t\treturn options[i][1];\n\t}\n\treturn \".\";\n }",
"private boolean isTileVisible(final ReferencedEnvelope tileBounds) {\n if (FloatingPointUtil.equals(this.transformer.getRotation(), 0.0)) {\n return true;\n }\n\n final GeometryFactory gfac = new GeometryFactory();\n final Optional<Geometry> rotatedMapBounds = getRotatedMapBounds(gfac);\n\n if (rotatedMapBounds.isPresent()) {\n return rotatedMapBounds.get().intersects(gfac.toGeometry(tileBounds));\n } else {\n // in case of an error, we simply load the tile\n return true;\n }\n }",
"public static <T> Collection<T> diff(Collection<T> list1, Collection<T> list2) {\r\n Collection<T> diff = new ArrayList<T>();\r\n for (T t : list1) {\r\n if (!list2.contains(t)) {\r\n diff.add(t);\r\n }\r\n }\r\n return diff;\r\n }",
"public FieldLocation getFieldLocation(FieldType type)\n {\n FieldLocation result = null;\n\n FieldItem item = m_map.get(type);\n if (item != null)\n {\n result = item.getFieldLocation();\n }\n return result;\n }",
"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 }"
] |
Apply a filter to the list of all tasks, and show the results.
@param project project file
@param filter filter | [
"private static void processTaskFilter(ProjectFile project, Filter filter)\n {\n for (Task task : project.getTasks())\n {\n if (filter.evaluate(task, null))\n {\n System.out.println(task.getID() + \",\" + task.getUniqueID() + \",\" + task.getName());\n }\n }\n }"
] | [
"public ResultSetAndStatement executeQuery(Query query, ClassDescriptor cld) throws PersistenceBrokerException\r\n {\r\n if (logger.isDebugEnabled())\r\n {\r\n logger.debug(\"executeQuery: \" + query);\r\n }\r\n /*\r\n\t\t * MBAIRD: we should create a scrollable resultset if the start at\r\n\t\t * index or end at index is set\r\n\t\t */\r\n boolean scrollable = ((query.getStartAtIndex() > Query.NO_START_AT_INDEX) || (query.getEndAtIndex() > Query.NO_END_AT_INDEX));\r\n /*\r\n\t\t * OR if the prefetching of relationships is being used.\r\n\t\t */\r\n if (query != null && query.getPrefetchedRelationships() != null && !query.getPrefetchedRelationships().isEmpty())\r\n {\r\n scrollable = true;\r\n }\r\n final StatementManagerIF sm = broker.serviceStatementManager();\r\n final SelectStatement sql = broker.serviceSqlGenerator().getPreparedSelectStatement(query, cld);\r\n PreparedStatement stmt = null;\r\n ResultSet rs = null;\r\n try\r\n {\r\n final int queryFetchSize = query.getFetchSize();\r\n final boolean isStoredProcedure = isStoredProcedure(sql.getStatement());\r\n stmt = sm.getPreparedStatement(cld, sql.getStatement() ,\r\n scrollable, queryFetchSize, isStoredProcedure);\r\n if (isStoredProcedure)\r\n {\r\n // Query implemented as a stored procedure, which must return a result set.\r\n // Query sytax is: { ?= call PROCEDURE_NAME(?,...,?)}\r\n getPlatform().registerOutResultSet((CallableStatement) stmt, 1);\r\n sm.bindStatement(stmt, query, cld, 2);\r\n\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"executeQuery: \" + stmt);\r\n\r\n stmt.execute();\r\n rs = (ResultSet) ((CallableStatement) stmt).getObject(1);\r\n }\r\n else\r\n {\r\n sm.bindStatement(stmt, query, cld, 1);\r\n\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"executeQuery: \" + stmt);\r\n\r\n rs = stmt.executeQuery();\r\n }\r\n\r\n return new ResultSetAndStatement(sm, stmt, rs, sql);\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n // release resources on exception\r\n sm.closeResources(stmt, rs);\r\n logger.error(\"PersistenceBrokerException during the execution of the query: \" + e.getMessage(), e);\r\n throw e;\r\n }\r\n catch (SQLException e)\r\n {\r\n // release resources on exception\r\n sm.closeResources(stmt, rs);\r\n throw ExceptionHelper.generateException(e, sql.getStatement(), null, logger, null);\r\n }\r\n }",
"protected Class getPrototypeClass(T content) {\n if (prototypes.size() == 1) {\n return prototypes.get(0).getClass();\n } else {\n return binding.get(content.getClass());\n }\n }",
"@PostConstruct\n public final void addMetricsAppenderToLogback() {\n final LoggerContext factory = (LoggerContext) LoggerFactory.getILoggerFactory();\n final Logger root = factory.getLogger(Logger.ROOT_LOGGER_NAME);\n\n final InstrumentedAppender metrics = new InstrumentedAppender(this.metricRegistry);\n metrics.setContext(root.getLoggerContext());\n metrics.start();\n root.addAppender(metrics);\n }",
"private String toLengthText(long bytes) {\n if (bytes < 1024) {\n return bytes + \" B\";\n } else if (bytes < 1024 * 1024) {\n return (bytes / 1024) + \" KB\";\n } else if (bytes < 1024 * 1024 * 1024) {\n return String.format(\"%.2f MB\", bytes / (1024.0 * 1024.0));\n } else {\n return String.format(\"%.2f GB\", bytes / (1024.0 * 1024.0 * 1024.0));\n }\n }",
"public MaterializeBuilder withContainer(ViewGroup container, ViewGroup.LayoutParams layoutParams) {\n this.mContainer = container;\n this.mContainerLayoutParams = layoutParams;\n return this;\n }",
"@Override\n public void invert(DMatrixRBlock A_inv) {\n int M = Math.min(QR.numRows,QR.numCols);\n if( A_inv.numRows != M || A_inv.numCols != M )\n throw new IllegalArgumentException(\"A_inv must be square an have dimension \"+M);\n\n\n // Solve for A^-1\n // Q*R*A^-1 = I\n\n // Apply householder reflectors to the identity matrix\n // y = Q^T*I = Q^T\n MatrixOps_DDRB.setIdentity(A_inv);\n decomposer.applyQTran(A_inv);\n\n // Solve using upper triangular R matrix\n // R*A^-1 = y\n // A^-1 = R^-1*y\n TriangularSolver_DDRB.solve(QR.blockLength,true,\n new DSubmatrixD1(QR,0,M,0,M),new DSubmatrixD1(A_inv),false);\n }",
"public boolean matches(HostName host) {\n\t\tif(this == host) {\n\t\t\treturn true;\n\t\t}\n\t\tif(isValid()) {\n\t\t\tif(host.isValid()) {\n\t\t\t\tif(isAddressString()) {\n\t\t\t\t\treturn host.isAddressString()\n\t\t\t\t\t\t\t&& asAddressString().equals(host.asAddressString())\n\t\t\t\t\t\t\t&& Objects.equals(getPort(), host.getPort())\n\t\t\t\t\t\t\t&& Objects.equals(getService(), host.getService());\n\t\t\t\t}\n\t\t\t\tif(host.isAddressString()) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tString thisHost = parsedHost.getHost();\n\t\t\t\tString otherHost = host.parsedHost.getHost();\n\t\t\t\tif(!thisHost.equals(otherHost)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\treturn Objects.equals(parsedHost.getEquivalentPrefixLength(), host.parsedHost.getEquivalentPrefixLength()) &&\n\t\t\t\t\t\tObjects.equals(parsedHost.getMask(), host.parsedHost.getMask()) &&\n\t\t\t\t\t\tObjects.equals(parsedHost.getPort(), host.parsedHost.getPort()) &&\n\t\t\t\t\t\tObjects.equals(parsedHost.getService(), host.parsedHost.getService());\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\treturn !host.isValid() && toString().equals(host.toString());\n\t}",
"public static void copy(byte[] in, OutputStream out) throws IOException {\n\t\tAssert.notNull(in, \"No input byte array specified\");\n\t\tAssert.notNull(out, \"No OutputStream specified\");\n\t\tout.write(in);\n\t}",
"public static base_response disable(nitro_service client, nsfeature resource) throws Exception {\n\t\tnsfeature disableresource = new nsfeature();\n\t\tdisableresource.feature = resource.feature;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}"
] |
Links the form with an HTML element which can be clicked.
@param form the collection of the input fields
@return a FormAction
@see Form | [
"public FormAction setValuesInForm(Form form) {\r\n\t\tFormAction formAction = new FormAction();\r\n\t\tform.setFormAction(formAction);\r\n\t\tthis.forms.add(form);\r\n\t\treturn formAction;\r\n\t}"
] | [
"private static JSONArray parseChildShapesRecursive(ArrayList<Shape> childShapes) throws JSONException {\n if (childShapes != null) {\n JSONArray childShapesArray = new JSONArray();\n\n for (Shape childShape : childShapes) {\n JSONObject childShapeObject = new JSONObject();\n\n childShapeObject.put(\"resourceId\",\n childShape.getResourceId().toString());\n childShapeObject.put(\"properties\",\n parseProperties(childShape.getProperties()));\n childShapeObject.put(\"stencil\",\n parseStencil(childShape.getStencilId()));\n childShapeObject.put(\"childShapes\",\n parseChildShapesRecursive(childShape.getChildShapes()));\n childShapeObject.put(\"outgoing\",\n parseOutgoings(childShape.getOutgoings()));\n childShapeObject.put(\"bounds\",\n parseBounds(childShape.getBounds()));\n childShapeObject.put(\"dockers\",\n parseDockers(childShape.getDockers()));\n\n if (childShape.getTarget() != null) {\n childShapeObject.put(\"target\",\n parseTarget(childShape.getTarget()));\n }\n\n childShapesArray.put(childShapeObject);\n }\n\n return childShapesArray;\n }\n\n return new JSONArray();\n }",
"public void performActions() {\n\t\tif (this.clientConfiguration.getActions().isEmpty()) {\n\t\t\tthis.clientConfiguration.printHelp();\n\t\t\treturn;\n\t\t}\n\n\t\tthis.dumpProcessingController.setOfflineMode(this.clientConfiguration\n\t\t\t\t.getOfflineMode());\n\n\t\tif (this.clientConfiguration.getDumpDirectoryLocation() != null) {\n\t\t\ttry {\n\t\t\t\tthis.dumpProcessingController\n\t\t\t\t\t\t.setDownloadDirectory(this.clientConfiguration\n\t\t\t\t\t\t\t\t.getDumpDirectoryLocation());\n\t\t\t} catch (IOException e) {\n\t\t\t\tlogger.error(\"Could not set download directory to \"\n\t\t\t\t\t\t+ this.clientConfiguration.getDumpDirectoryLocation()\n\t\t\t\t\t\t+ \": \" + e.getMessage());\n\t\t\t\tlogger.error(\"Aborting\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tdumpProcessingController.setLanguageFilter(this.clientConfiguration\n\t\t\t\t.getFilterLanguages());\n\t\tdumpProcessingController.setSiteLinkFilter(this.clientConfiguration\n\t\t\t\t.getFilterSiteKeys());\n\t\tdumpProcessingController.setPropertyFilter(this.clientConfiguration\n\t\t\t\t.getFilterProperties());\n\n\t\tMwDumpFile dumpFile = this.clientConfiguration.getLocalDumpFile();\n\n\t\tif (dumpFile == null) {\n\t\t\tdumpFile = dumpProcessingController\n\t\t\t\t\t.getMostRecentDump(DumpContentType.JSON);\n\t\t} else {\n\t\t\tif (!dumpFile.isAvailable()) {\n\t\t\t\tlogger.error(\"Dump file not found or not readable: \"\n\t\t\t\t\t\t+ dumpFile.toString());\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tthis.clientConfiguration.setProjectName(dumpFile.getProjectName());\n\t\tthis.clientConfiguration.setDateStamp(dumpFile.getDateStamp());\n\n\t\tboolean hasReadyProcessor = false;\n\t\tfor (DumpProcessingAction props : this.clientConfiguration.getActions()) {\n\n\t\t\tif (!props.isReady()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (props.needsSites()) {\n\t\t\t\tprepareSites();\n\t\t\t\tif (this.sites == null) { // sites unavailable\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tprops.setSites(this.sites);\n\t\t\t}\n\t\t\tprops.setDumpInformation(dumpFile.getProjectName(),\n\t\t\t\t\tdumpFile.getDateStamp());\n\t\t\tthis.dumpProcessingController.registerEntityDocumentProcessor(\n\t\t\t\t\tprops, null, true);\n\t\t\thasReadyProcessor = true;\n\t\t}\n\n\t\tif (!hasReadyProcessor) {\n\t\t\treturn; // silent; non-ready action should report its problem\n\t\t\t\t\t// directly\n\t\t}\n\n\t\tif (!this.clientConfiguration.isQuiet()) {\n\t\t\tEntityTimerProcessor entityTimerProcessor = new EntityTimerProcessor(\n\t\t\t\t\t0);\n\t\t\tthis.dumpProcessingController.registerEntityDocumentProcessor(\n\t\t\t\t\tentityTimerProcessor, null, true);\n\t\t}\n\t\topenActions();\n\t\tthis.dumpProcessingController.processDump(dumpFile);\n\t\tcloseActions();\n\n\t\ttry {\n\t\t\twriteReport();\n\t\t} catch (IOException e) {\n\t\t\tlogger.error(\"Could not print report file: \" + e.getMessage());\n\t\t}\n\n\t}",
"protected void updateFontTable()\n {\n PDResources resources = pdpage.getResources();\n if (resources != null)\n {\n try\n {\n processFontResources(resources, fontTable);\n } catch (IOException e) {\n log.error(\"Error processing font resources: \"\n + \"Exception: {} {}\", e.getMessage(), e.getClass());\n }\n }\n }",
"public final void begin() {\n this.file = this.getAppender().getIoFile();\n if (this.file == null) {\n this.getAppender().getErrorHandler()\n .error(\"Scavenger not started: missing log file name\");\n return;\n }\n if (this.getProperties().getScavengeInterval() > -1) {\n final Thread thread = new Thread(this, \"Log4J File Scavenger\");\n thread.setDaemon(true);\n thread.start();\n this.threadRef = thread;\n }\n }",
"protected boolean prepareClose() {\n synchronized (lock) {\n final State state = this.state;\n if (state == State.OPEN) {\n this.state = State.CLOSING;\n lock.notifyAll();\n return true;\n }\n }\n return false;\n }",
"public IntervalFrequency getRefreshFrequency() {\n switch (mRefreshInterval) {\n case REALTIME_REFRESH_INTERVAL:\n return IntervalFrequency.REALTIME;\n case HIGH_REFRESH_INTERVAL:\n return IntervalFrequency.HIGH;\n case LOW_REFRESH_INTERVAL:\n return IntervalFrequency.LOW;\n case MEDIUM_REFRESH_INTERVAL:\n return IntervalFrequency.MEDIUM;\n default:\n return IntervalFrequency.NONE;\n }\n }",
"private String format(Object o)\n {\n String result;\n\n if (o == null)\n {\n result = \"\";\n }\n else\n {\n if (o instanceof Boolean == true)\n {\n result = LocaleData.getString(m_locale, (((Boolean) o).booleanValue() == true ? LocaleData.YES : LocaleData.NO));\n }\n else\n {\n if (o instanceof Float == true || o instanceof Double == true)\n {\n result = (m_formats.getDecimalFormat().format(((Number) o).doubleValue()));\n }\n else\n {\n if (o instanceof Day)\n {\n result = Integer.toString(((Day) o).getValue());\n }\n else\n {\n result = o.toString();\n }\n }\n }\n\n //\n // At this point there should be no line break characters in\n // the file. If we find any, replace them with spaces\n //\n result = stripLineBreaks(result, MPXConstants.EOL_PLACEHOLDER_STRING);\n\n //\n // Finally we check to ensure that there are no embedded\n // quotes or separator characters in the value. If there are, then\n // we quote the value and escape any existing quote characters.\n //\n if (result.indexOf('\"') != -1)\n {\n result = escapeQuotes(result);\n }\n else\n {\n if (result.indexOf(m_delimiter) != -1)\n {\n result = '\"' + result + '\"';\n }\n }\n }\n\n return (result);\n }",
"private <T extends TimephasedItem<?>> int getStartIndex(DateRange range, List<T> assignments, int startIndex)\n {\n int result = -1;\n if (assignments != null)\n {\n long rangeStart = range.getStart().getTime();\n long rangeEnd = range.getEnd().getTime();\n\n for (int loop = startIndex; loop < assignments.size(); loop++)\n {\n T assignment = assignments.get(loop);\n int compareResult = DateHelper.compare(assignment.getStart(), assignment.getFinish(), rangeStart);\n\n //\n // The start of the target range falls after the assignment end -\n // move on to test the next assignment.\n //\n if (compareResult > 0)\n {\n continue;\n }\n\n //\n // The start of the target range falls within the assignment -\n // return the index of this assignment to the caller.\n //\n if (compareResult == 0)\n {\n result = loop;\n break;\n }\n\n //\n // At this point, we know that the start of the target range is before\n // the assignment start. We need to determine if the end of the\n // target range overlaps the assignment.\n //\n compareResult = DateHelper.compare(assignment.getStart(), assignment.getFinish(), rangeEnd);\n if (compareResult >= 0)\n {\n result = loop;\n break;\n }\n }\n }\n return result;\n }",
"public static XMLStreamException missingRequiredElement(final XMLExtendedStreamReader reader, final Set<?> required) {\n final StringBuilder b = new StringBuilder();\n Iterator<?> iterator = required.iterator();\n while (iterator.hasNext()) {\n final Object o = iterator.next();\n b.append(o.toString());\n if (iterator.hasNext()) {\n b.append(\", \");\n }\n }\n final XMLStreamException ex = ControllerLogger.ROOT_LOGGER.missingRequiredElements(b, reader.getLocation());\n\n Set<String> set = new HashSet<>();\n for (Object o : required) {\n String toString = o.toString();\n set.add(toString);\n }\n return new XMLStreamValidationException(ex.getMessage(),\n ValidationError.from(ex, ErrorType.REQUIRED_ELEMENTS_MISSING)\n .element(reader.getName())\n .alternatives(set),\n ex);\n }"
] |
This method computes the list of unnamed parameters, by filtering the
list of raw arguments, stripping out the named parameters. | [
"private void computeUnnamedParams() {\n unnamedParams.addAll(rawArgs.stream().filter(arg -> !isNamedParam(arg)).collect(Collectors.toList()));\n }"
] | [
"public ResourcePoolConfig setTimeout(long timeout, TimeUnit unit) {\n if(timeout < 0)\n throw new IllegalArgumentException(\"The timeout must be a non-negative number.\");\n this.timeoutNs = TimeUnit.NANOSECONDS.convert(timeout, unit);\n return this;\n }",
"@Override\r\n public void close() {\r\n // Use monitor to avoid race between external close and handler thread run()\r\n synchronized (closeMonitor) {\r\n // Close and clear streams, sockets etc.\r\n if (socket != null) {\r\n try {\r\n // Terminates thread blocking on socket read\r\n // and automatically closed depending streams\r\n socket.close();\r\n } catch (IOException e) {\r\n log.warn(\"Can not close socket\", e);\r\n } finally {\r\n socket = null;\r\n }\r\n }\r\n\r\n // Clear user data\r\n session = null;\r\n response = null;\r\n }\r\n }",
"public static appfwpolicy_stats[] get(nitro_service service) throws Exception{\n\t\tappfwpolicy_stats obj = new appfwpolicy_stats();\n\t\tappfwpolicy_stats[] response = (appfwpolicy_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}",
"public OperationTransformerRegistry resolveServer(final ModelVersion mgmtVersion, final ModelNode subsystems) {\n return resolveServer(mgmtVersion, resolveVersions(subsystems));\n }",
"public static inatparam get(nitro_service service) throws Exception{\n\t\tinatparam obj = new inatparam();\n\t\tinatparam[] response = (inatparam[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public static double Cosh(double x, int nTerms) {\r\n if (nTerms < 2) return x;\r\n if (nTerms == 2) {\r\n return 1 + (x * x) / 2D;\r\n } else {\r\n\r\n double mult = x * x;\r\n double fact = 2;\r\n int factS = 4;\r\n double result = 1 + mult / fact;\r\n for (int i = 3; i <= nTerms; i++) {\r\n mult *= x * x;\r\n fact *= factS * (factS - 1);\r\n factS += 2;\r\n result += mult / fact;\r\n }\r\n\r\n return result;\r\n }\r\n }",
"private BigInteger getDaysOfTheWeek(RecurringData data)\n {\n int value = 0;\n for (Day day : Day.values())\n {\n if (data.getWeeklyDay(day))\n {\n value = value | DAY_MASKS[day.getValue()];\n }\n }\n return BigInteger.valueOf(value);\n }",
"protected void doPurge(Runnable afterPurgeAction) {\n\n if (LOG.isInfoEnabled()) {\n LOG.info(\n org.opencms.flex.Messages.get().getBundle().key(\n org.opencms.flex.Messages.LOG_FLEXCACHE_WILL_PURGE_JSP_REPOSITORY_0));\n }\n\n File d;\n d = new File(getJspRepository() + CmsFlexCache.REPOSITORY_ONLINE + File.separator);\n CmsFileUtil.purgeDirectory(d);\n\n d = new File(getJspRepository() + CmsFlexCache.REPOSITORY_OFFLINE + File.separator);\n CmsFileUtil.purgeDirectory(d);\n if (afterPurgeAction != null) {\n afterPurgeAction.run();\n }\n\n if (LOG.isInfoEnabled()) {\n LOG.info(\n org.opencms.flex.Messages.get().getBundle().key(\n org.opencms.flex.Messages.LOG_FLEXCACHE_PURGED_JSP_REPOSITORY_0));\n }\n\n }",
"private String getJSONFromMap(Map<String, Object> propMap) {\n try {\n return new JSONObject(propMap).toString();\n } catch (Exception e) {\n return \"{}\";\n }\n }"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.