query
stringlengths
7
3.3k
positive
sequencelengths
1
1
negative
sequencelengths
9
9
Converts a submatrix into an extract matrix operation. @param variableTarget The variable in which the submatrix is extracted from
[ "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 void insertValue(int index, float[] newValue) {\n if ( newValue.length == 2) {\n try {\n value.add( index, new SFVec2f(newValue[0], newValue[1]) );\n }\n catch (IndexOutOfBoundsException e) {\n Log.e(TAG, \"X3D MFVec2f get1Value(index) out of bounds.\" + e);\n }\n catch (Exception e) {\n Log.e(TAG, \"X3D MFVec2f get1Value(index) exception \" + e);\n }\n }\n else {\n Log.e(TAG, \"X3D MFVec2f insertValue set with array length not equal to 2\");\n }\n }", "public void addAll(@NonNull final Collection<T> collection) {\n final int length = collection.size();\n if (length == 0) {\n return;\n }\n synchronized (mLock) {\n final int position = getItemCount();\n mObjects.addAll(collection);\n notifyItemRangeInserted(position, length);\n }\n }", "public static String replaceAnyOf(String value, String chars,\n char replacement) {\n char[] tmp = new char[value.length()];\n int pos = 0;\n for (int ix = 0; ix < tmp.length; ix++) {\n char ch = value.charAt(ix);\n if (chars.indexOf(ch) != -1)\n tmp[pos++] = replacement;\n else\n tmp[pos++] = ch;\n }\n return new String(tmp, 0, tmp.length);\n }", "private void removeXmlBundleFile() throws CmsException {\n\n lockLocalization(null);\n m_cms.deleteResource(m_resource, CmsResource.DELETE_PRESERVE_SIBLINGS);\n m_resource = null;\n\n }", "public synchronized X509Certificate getMappedCertificate(final X509Certificate cert)\n\tthrows CertificateEncodingException,\n\tInvalidKeyException,\n\tCertificateException,\n\tCertificateNotYetValidException,\n\tNoSuchAlgorithmException,\n\tNoSuchProviderException,\n\tSignatureException,\n\tKeyStoreException,\n\tUnrecoverableKeyException\n\t{\n\n\t\tString thumbprint = ThumbprintUtil.getThumbprint(cert);\n\n\t\tString mappedCertThumbprint = _certMap.get(thumbprint);\n\n\t\tif(mappedCertThumbprint == null)\n\t\t{\n\n\t\t\t// Check if we've already mapped this public key from a KeyValue\n\t\t\tPublicKey mappedPk = getMappedPublicKey(cert.getPublicKey());\n\t\t\tPrivateKey privKey;\n\n\t\t\tif(mappedPk == null)\n\t\t\t{\n\t\t\t\tPublicKey pk = cert.getPublicKey();\n\n\t\t\t\tString algo = pk.getAlgorithm();\n\n\t\t\t\tKeyPair kp;\n\n\t\t\t\tif(algo.equals(\"RSA\")) {\n\t\t\t\t\tkp = getRSAKeyPair();\n\t\t\t\t}\n\t\t\t\telse if(algo.equals(\"DSA\")) {\n\t\t\t\t\tkp = getDSAKeyPair();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tthrow new InvalidKeyException(\"Key algorithm \" + algo + \" not supported.\");\n\t\t\t\t}\n\t\t\t\tmappedPk = kp.getPublic();\n\t\t\t\tprivKey = kp.getPrivate();\n\n\t\t\t\tmapPublicKeys(cert.getPublicKey(), mappedPk);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tprivKey = getPrivateKey(mappedPk);\n\t\t\t}\n\n\n\t\t\tX509Certificate replacementCert =\n\t\t\t\tCertificateCreator.mitmDuplicateCertificate(\n\t\t\t\t\t\tcert,\n\t\t\t\t\t\tmappedPk,\n\t\t\t\t\t\tgetSigningCert(),\n\t\t\t\t\t\tgetSigningPrivateKey());\n\n\t\t\taddCertAndPrivateKey(null, replacementCert, privKey);\n\n\t\t\tmappedCertThumbprint = ThumbprintUtil.getThumbprint(replacementCert);\n\n\t\t\t_certMap.put(thumbprint, mappedCertThumbprint);\n\t\t\t_certMap.put(mappedCertThumbprint, thumbprint);\n\t\t\t_subjectMap.put(replacementCert.getSubjectX500Principal().getName(), thumbprint);\n\n\t\t\tif(persistImmediately) {\n\t\t\t\tpersist();\n\t\t\t}\n\t\t\treturn replacementCert;\n\t\t}\n return getCertificateByAlias(mappedCertThumbprint);\n\n\t}", "private void validatePermissions(final File dirPath, final File file) {\n\n // Check execute and read permissions for parent dirPath\n if( !dirPath.canExecute() || !dirPath.canRead() ) {\n validFilePermissions = false;\n filePermissionsProblemPath = dirPath.getAbsolutePath();\n return;\n }\n\n // Check read and write permissions for properties file\n if( !file.canRead() || !file.canWrite() ) {\n validFilePermissions = false;\n filePermissionsProblemPath = dirPath.getAbsolutePath();\n }\n\n }", "public synchronized Set<RegistrationPoint> getRegistrationPoints() {\n Set<RegistrationPoint> result = new HashSet<>();\n for (List<RegistrationPoint> registrationPoints : registrationPoints.values()) {\n result.addAll(registrationPoints);\n }\n return Collections.unmodifiableSet(result);\n }", "public void addPartialFieldAssignment(\n SourceBuilder code, Excerpt finalField, String builder) {\n addFinalFieldAssignment(code, finalField, builder);\n }", "public static Bitmap decodeStream(InputStream stream, boolean closeStream) {\n return AsyncBitmapTexture.decodeStream(stream,\n AsyncBitmapTexture.glMaxTextureSize,\n AsyncBitmapTexture.glMaxTextureSize, true, null, closeStream);\n }" ]
Add groups to the tree. @param parentNode parent tree node @param file group container
[ "private void addGroups(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (Group group : file.getGroups())\n {\n final Group g = group;\n MpxjTreeNode childNode = new MpxjTreeNode(group)\n {\n @Override public String toString()\n {\n return g.getName();\n }\n };\n parentNode.add(childNode);\n }\n }" ]
[ "public static int optionLength(String option) {\n if(matchOption(option, \"qualify\", true) ||\n matchOption(option, \"qualifyGenerics\", true) ||\n matchOption(option, \"hideGenerics\", true) ||\n matchOption(option, \"horizontal\", true) ||\n matchOption(option, \"all\") ||\n matchOption(option, \"attributes\", true) ||\n matchOption(option, \"enumconstants\", true) ||\n matchOption(option, \"operations\", true) ||\n matchOption(option, \"enumerations\", true) ||\n matchOption(option, \"constructors\", true) ||\n matchOption(option, \"visibility\", true) ||\n matchOption(option, \"types\", true) ||\n matchOption(option, \"autosize\", true) ||\n matchOption(option, \"commentname\", true) ||\n matchOption(option, \"nodefontabstractitalic\", true) ||\n matchOption(option, \"postfixpackage\", true) ||\n matchOption(option, \"noguillemot\", true) ||\n matchOption(option, \"views\", true) ||\n matchOption(option, \"inferrel\", true) ||\n matchOption(option, \"useimports\", true) ||\n matchOption(option, \"collapsible\", true) ||\n matchOption(option, \"inferdep\", true) ||\n matchOption(option, \"inferdepinpackage\", true) ||\n matchOption(option, \"hideprivateinner\", true) ||\n matchOption(option, \"compact\", true))\n\n return 1;\n else if(matchOption(option, \"nodefillcolor\") ||\n matchOption(option, \"nodefontcolor\") ||\n matchOption(option, \"nodefontsize\") ||\n matchOption(option, \"nodefontname\") ||\n matchOption(option, \"nodefontclasssize\") ||\n matchOption(option, \"nodefontclassname\") ||\n matchOption(option, \"nodefonttagsize\") ||\n matchOption(option, \"nodefonttagname\") ||\n matchOption(option, \"nodefontpackagesize\") ||\n matchOption(option, \"nodefontpackagename\") ||\n matchOption(option, \"edgefontcolor\") ||\n matchOption(option, \"edgecolor\") ||\n matchOption(option, \"edgefontsize\") ||\n matchOption(option, \"edgefontname\") ||\n matchOption(option, \"shape\") ||\n matchOption(option, \"output\") ||\n matchOption(option, \"outputencoding\") ||\n matchOption(option, \"bgcolor\") ||\n matchOption(option, \"hide\") ||\n matchOption(option, \"include\") ||\n matchOption(option, \"apidocroot\") ||\n matchOption(option, \"apidocmap\") ||\n matchOption(option, \"d\") ||\n matchOption(option, \"view\") ||\n matchOption(option, \"inferreltype\") ||\n matchOption(option, \"inferdepvis\") ||\n matchOption(option, \"collpackages\") ||\n matchOption(option, \"nodesep\") ||\n matchOption(option, \"ranksep\") ||\n matchOption(option, \"dotexecutable\") ||\n matchOption(option, \"link\"))\n return 2;\n else if(matchOption(option, \"contextPattern\") ||\n matchOption(option, \"linkoffline\"))\n return 3;\n else\n return 0;\n }", "private void setTasks(String tasks) {\n\t\tfor (String task : tasks.split(\",\")) {\n\t\t\tif (KNOWN_TASKS.containsKey(task)) {\n\t\t\t\tthis.tasks |= KNOWN_TASKS.get(task);\n\t\t\t\tthis.taskName += (this.taskName.isEmpty() ? \"\" : \"-\") + task;\n\t\t\t} else {\n\t\t\t\tlogger.warn(\"Unsupported RDF serialization task \\\"\" + task\n\t\t\t\t\t\t+ \"\\\". Run without specifying any tasks for help.\");\n\t\t\t}\n\t\t}\n\t}", "public ItemRequest<Story> delete(String story) {\n \n String path = String.format(\"/stories/%s\", story);\n return new ItemRequest<Story>(this, Story.class, path, \"DELETE\");\n }", "public static ThreadPoolExecutor newFixedThreadPool(int threads, String groupname, int queueSize) {\n\t\treturn new ThreadPoolExecutor( threads, threads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(\n\t\t\t\tqueueSize ), new SearchThreadFactory( groupname ), new BlockPolicy() );\n\t}", "@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)\n public static synchronized void register(android.app.Application application) {\n if (application == null) {\n Logger.i(\"Application instance is null/system API is too old\");\n return;\n }\n\n if (registered) {\n Logger.v(\"Lifecycle callbacks have already been registered\");\n return;\n }\n\n registered = true;\n application.registerActivityLifecycleCallbacks(\n new android.app.Application.ActivityLifecycleCallbacks() {\n\n @Override\n public void onActivityCreated(Activity activity, Bundle bundle) {\n CleverTapAPI.onActivityCreated(activity);\n }\n\n @Override\n public void onActivityStarted(Activity activity) {}\n\n @Override\n public void onActivityResumed(Activity activity) {\n CleverTapAPI.onActivityResumed(activity);\n }\n\n @Override\n public void onActivityPaused(Activity activity) {\n CleverTapAPI.onActivityPaused();\n }\n\n @Override\n public void onActivityStopped(Activity activity) {}\n\n @Override\n public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {}\n\n @Override\n public void onActivityDestroyed(Activity activity) {}\n }\n\n );\n Logger.i(\"Activity Lifecycle Callback successfully registered\");\n }", "private void logTimeTakenByPhase(GraphContext graphContext, Class<? extends RulePhase> phase, int timeTaken)\n {\n if (!timeTakenByPhase.containsKey(phase))\n {\n RulePhaseExecutionStatisticsModel model = new GraphService<>(graphContext,\n RulePhaseExecutionStatisticsModel.class).create();\n model.setRulePhase(phase.toString());\n model.setTimeTaken(timeTaken);\n model.setOrderExecuted(timeTakenByPhase.size());\n timeTakenByPhase.put(phase, model.getElement().id());\n }\n else\n {\n GraphService<RulePhaseExecutionStatisticsModel> service = new GraphService<>(graphContext,\n RulePhaseExecutionStatisticsModel.class);\n RulePhaseExecutionStatisticsModel model = service.getById(timeTakenByPhase.get(phase));\n int prevTimeTaken = model.getTimeTaken();\n model.setTimeTaken(prevTimeTaken + timeTaken);\n }\n }", "public static spilloverpolicy_stats get(nitro_service service, String name) throws Exception{\n\t\tspilloverpolicy_stats obj = new spilloverpolicy_stats();\n\t\tobj.set_name(name);\n\t\tspilloverpolicy_stats response = (spilloverpolicy_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "public void info(Throwable throwable, String msg, Object[] argArray) {\n\t\tlogIfEnabled(Level.INFO, throwable, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, argArray);\n\t}", "public static final Double parseCurrency(Number value)\n {\n return (value == null ? null : NumberHelper.getDouble(value.doubleValue() / 100));\n }" ]
Make a copy of this Area of Interest.
[ "public AreaOfInterest copy() {\n AreaOfInterest aoi = new AreaOfInterest();\n aoi.display = this.display;\n aoi.area = this.area;\n aoi.polygon = this.polygon;\n aoi.style = this.style;\n aoi.renderAsSvg = this.renderAsSvg;\n return aoi;\n }" ]
[ "public ItemRequest<Project> addMembers(String project) {\n \n String path = String.format(\"/projects/%s/addMembers\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\n }", "public ProjectFile read() throws MPXJException\n {\n MPD9DatabaseReader reader = new MPD9DatabaseReader();\n reader.setProjectID(m_projectID);\n reader.setPreserveNoteFormatting(m_preserveNoteFormatting);\n reader.setDataSource(m_dataSource);\n reader.setConnection(m_connection);\n ProjectFile project = reader.read();\n return (project);\n }", "public static String getDumpFilePostfix(DumpContentType dumpContentType) {\n\t\tif (WmfDumpFile.POSTFIXES.containsKey(dumpContentType)) {\n\t\t\treturn WmfDumpFile.POSTFIXES.get(dumpContentType);\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\"Unsupported dump type \"\n\t\t\t\t\t+ dumpContentType);\n\t\t}\n\t}", "public static void registerOgmExternalizers(GlobalConfiguration globalCfg) {\n\t\tMap<Integer, AdvancedExternalizer<?>> externalizerMap = globalCfg.serialization().advancedExternalizers();\n\t\texternalizerMap.putAll( ogmExternalizers );\n\t}", "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 List<ColumnProperty> getAllFields(){\n\t\tArrayList<ColumnProperty> l = new ArrayList<ColumnProperty>();\n\t\tfor (AbstractColumn abstractColumn : this.getColumns()) {\n\t\t\tif (abstractColumn instanceof SimpleColumn && !(abstractColumn instanceof ExpressionColumn)) {\n\t\t\t\tl.add(((SimpleColumn)abstractColumn).getColumnProperty());\n\t\t\t}\n\t\t}\n\t\tl.addAll(this.getFields());\n\n\t\treturn l;\n\t\t\n\t}", "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 synchronized void createImportationDeclaration(String deviceId, String deviceType, String deviceSubType) {\n Map<String, Object> metadata = new HashMap<String, Object>();\n metadata.put(Constants.DEVICE_ID, deviceId);\n metadata.put(Constants.DEVICE_TYPE, deviceType);\n metadata.put(Constants.DEVICE_TYPE_SUB, deviceSubType);\n metadata.put(\"scope\", \"generic\");\n ImportDeclaration declaration = ImportDeclarationBuilder.fromMetadata(metadata).build();\n\n importDeclarations.put(deviceId, declaration);\n\n registerImportDeclaration(declaration);\n }", "public static Object formatL(final String template, final Object... args) {\n return new Object() {\n @Override\n public String toString() {\n return format(template, args);\n }\n };\n }" ]
Clear the mask for a new selection
[ "public void clear() {\n if (arrMask != null) {\n for (int y = 0; y < height; y++) {\n for (int x = 0; x < width; x++) {\n arrMask[x][y] = false;\n }\n }\n }\n }" ]
[ "public void addRequiredValues(@Nonnull final Values sourceValues) {\n Object taskDirectory = sourceValues.getObject(TASK_DIRECTORY_KEY, Object.class);\n MfClientHttpRequestFactoryProvider requestFactoryProvider =\n sourceValues.getObject(CLIENT_HTTP_REQUEST_FACTORY_KEY,\n MfClientHttpRequestFactoryProvider.class);\n Template template = sourceValues.getObject(TEMPLATE_KEY, Template.class);\n PDFConfig pdfConfig = sourceValues.getObject(PDF_CONFIG_KEY, PDFConfig.class);\n String subReportDir = sourceValues.getString(SUBREPORT_DIR_KEY);\n\n this.values.put(TASK_DIRECTORY_KEY, taskDirectory);\n this.values.put(CLIENT_HTTP_REQUEST_FACTORY_KEY, requestFactoryProvider);\n this.values.put(TEMPLATE_KEY, template);\n this.values.put(PDF_CONFIG_KEY, pdfConfig);\n this.values.put(SUBREPORT_DIR_KEY, subReportDir);\n this.values.put(VALUES_KEY, this);\n this.values.put(JOB_ID_KEY, sourceValues.getString(JOB_ID_KEY));\n this.values.put(LOCALE_KEY, sourceValues.getObject(LOCALE_KEY, Locale.class));\n }", "public void addRequest(long timeNS,\n long numEmptyResponses,\n long valueBytes,\n long keyBytes,\n long getAllAggregatedCount) {\n // timing instrumentation (trace only)\n long startTimeNs = 0;\n if(logger.isTraceEnabled()) {\n startTimeNs = System.nanoTime();\n }\n\n long currentTime = time.milliseconds();\n\n timeSensor.record((double) timeNS / voldemort.utils.Time.NS_PER_MS, currentTime);\n emptyResponseKeysSensor.record(numEmptyResponses, currentTime);\n valueBytesSensor.record(valueBytes, currentTime);\n keyBytesSensor.record(keyBytes, currentTime);\n getAllKeysCountSensor.record(getAllAggregatedCount, currentTime);\n\n // timing instrumentation (trace only)\n if(logger.isTraceEnabled()) {\n logger.trace(\"addRequest took \" + (System.nanoTime() - startTimeNs) + \" ns.\");\n }\n }", "public final static String process(final String input, final Configuration configuration)\n {\n try\n {\n return process(new StringReader(input), configuration);\n }\n catch (final IOException e)\n {\n // This _can never_ happen\n return null;\n }\n }", "public static base_response update(nitro_service client, vlan resource) throws Exception {\n\t\tvlan updateresource = new vlan();\n\t\tupdateresource.id = resource.id;\n\t\tupdateresource.aliasname = resource.aliasname;\n\t\tupdateresource.ipv6dynamicrouting = resource.ipv6dynamicrouting;\n\t\treturn updateresource.update_resource(client);\n\t}", "public void updateConfig(String appName, Map<String, String> config) {\n connection.execute(new ConfigUpdate(appName, config), apiKey);\n }", "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}", "private void deliverMediaDetailsUpdate(final MediaDetails details) {\n for (MediaDetailsListener listener : getMediaDetailsListeners()) {\n try {\n listener.detailsAvailable(details);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering media details response to listener\", t);\n }\n }\n }", "public static void main(String[] args) throws Exception {\n Logger logger = Logger.getLogger(\"MASReader.main\");\n\n Properties beastConfigProperties = new Properties();\n String beastConfigPropertiesFile = null;\n if (args.length > 0) {\n beastConfigPropertiesFile = args[0];\n beastConfigProperties.load(new FileInputStream(\n beastConfigPropertiesFile));\n logger.info(\"Properties file selected -> \"\n + beastConfigPropertiesFile);\n } else {\n logger.severe(\"No properties file found. Set the path of properties file as argument.\");\n throw new BeastException(\n \"No properties file found. Set the path of properties file as argument.\");\n }\n String loggerConfigPropertiesFile;\n if (args.length > 1) {\n Properties loggerConfigProperties = new Properties();\n loggerConfigPropertiesFile = args[1];\n try {\n FileInputStream loggerConfigFile = new FileInputStream(\n loggerConfigPropertiesFile);\n loggerConfigProperties.load(loggerConfigFile);\n LogManager.getLogManager().readConfiguration(loggerConfigFile);\n logger.info(\"Logging properties configured successfully. Logger config file: \"\n + loggerConfigPropertiesFile);\n } catch (IOException ex) {\n logger.warning(\"WARNING: Could not open configuration file\");\n logger.warning(\"WARNING: Logging not configured (console output only)\");\n }\n } else {\n loggerConfigPropertiesFile = null;\n }\n\n MASReader.generateJavaFiles(\n beastConfigProperties.getProperty(\"requirementsFolder\"), \"\\\"\"\n + beastConfigProperties.getProperty(\"MASPlatform\")\n + \"\\\"\",\n beastConfigProperties.getProperty(\"srcTestRootFolder\"),\n beastConfigProperties.getProperty(\"storiesPackage\"),\n beastConfigProperties.getProperty(\"caseManagerPackage\"),\n loggerConfigPropertiesFile,\n beastConfigProperties.getProperty(\"specificationPhase\"));\n\n }", "public synchronized String requestBlock(String name) {\n if (blocks.isEmpty()) {\n return \"exit\";\n }\n\n remainingBlocks.decrementAndGet();\n return blocks.poll().createResponse();\n }" ]
Creates a ServiceFuture from an Completable object and a callback. @param completable the completable to create from @param callback the callback to call when event happen @return the created ServiceFuture
[ "public static ServiceFuture<Void> fromBody(final Completable completable, final ServiceCallback<Void> callback) {\n final ServiceFuture<Void> serviceFuture = new ServiceFuture<>();\n completable.subscribe(new Action0() {\n Void value = null;\n @Override\n public void call() {\n if (callback != null) {\n callback.success(value);\n }\n serviceFuture.set(value);\n }\n }, new Action1<Throwable>() {\n @Override\n public void call(Throwable throwable) {\n if (callback != null) {\n callback.failure(throwable);\n }\n serviceFuture.setException(throwable);\n }\n });\n return serviceFuture;\n }" ]
[ "public static MetadataTemplate updateMetadataTemplate(BoxAPIConnection api, String scope, String template,\n List<FieldOperation> fieldOperations) {\n\n JsonArray array = new JsonArray();\n\n for (FieldOperation fieldOperation : fieldOperations) {\n JsonObject jsonObject = getFieldOperationJsonObject(fieldOperation);\n array.add(jsonObject);\n }\n\n QueryStringBuilder builder = new QueryStringBuilder();\n URL url = METADATA_TEMPLATE_URL_TEMPLATE.build(api.getBaseURL(), scope, template);\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"PUT\");\n request.setBody(array.toString());\n\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJson = JsonObject.readFrom(response.getJSON());\n\n return new MetadataTemplate(responseJson);\n }", "protected String sp_createSequenceQuery(String sequenceName, long maxKey)\r\n {\r\n return \"insert into \" + SEQ_TABLE_NAME + \" (\"\r\n + SEQ_NAME_STRING + \",\" + SEQ_ID_STRING +\r\n \") values ('\" + sequenceName + \"',\" + maxKey + \")\";\r\n }", "public int removeChildObjectsByName(final String name) {\n int removed = 0;\n\n if (null != name && !name.isEmpty()) {\n removed = removeChildObjectsByNameImpl(name);\n }\n\n return removed;\n }", "private List<TaskField> getAllTaskExtendedAttributes()\n {\n ArrayList<TaskField> result = new ArrayList<TaskField>();\n result.addAll(Arrays.asList(TaskFieldLists.CUSTOM_TEXT));\n result.addAll(Arrays.asList(TaskFieldLists.CUSTOM_START));\n result.addAll(Arrays.asList(TaskFieldLists.CUSTOM_FINISH));\n result.addAll(Arrays.asList(TaskFieldLists.CUSTOM_COST));\n result.addAll(Arrays.asList(TaskFieldLists.CUSTOM_DATE));\n result.addAll(Arrays.asList(TaskFieldLists.CUSTOM_FLAG));\n result.addAll(Arrays.asList(TaskFieldLists.CUSTOM_NUMBER));\n result.addAll(Arrays.asList(TaskFieldLists.CUSTOM_DURATION));\n result.addAll(Arrays.asList(TaskFieldLists.CUSTOM_OUTLINE_CODE));\n result.addAll(Arrays.asList(TaskFieldLists.ENTERPRISE_COST));\n result.addAll(Arrays.asList(TaskFieldLists.ENTERPRISE_DATE));\n result.addAll(Arrays.asList(TaskFieldLists.ENTERPRISE_DURATION));\n result.addAll(Arrays.asList(TaskFieldLists.ENTERPRISE_FLAG));\n result.addAll(Arrays.asList(TaskFieldLists.ENTERPRISE_NUMBER));\n result.addAll(Arrays.asList(TaskFieldLists.ENTERPRISE_TEXT));\n return result;\n }", "private int[] convertBatch(int[] batch) {\n int[] conv = new int[batch.length];\n for (int i=0; i<batch.length; i++) {\n conv[i] = sample[batch[i]];\n }\n return conv;\n }", "public void startup() {\n if (config.getEnableZookeeper()) {\n serverRegister.registerBrokerInZk();\n for (String topic : getAllTopics()) {\n serverRegister.processTask(new TopicTask(TopicTask.TaskType.CREATE, topic));\n }\n startupLatch.countDown();\n }\n logger.debug(\"Starting log flusher every {} ms with the following overrides {}\", config.getFlushSchedulerThreadRate(), logFlushIntervalMap);\n logFlusherScheduler.scheduleWithRate(new Runnable() {\n\n public void run() {\n flushAllLogs(false);\n }\n }, config.getFlushSchedulerThreadRate(), config.getFlushSchedulerThreadRate());\n }", "protected void addFacetPart(CmsSolrQuery query) {\n\n query.set(\"facet\", \"true\");\n String excludes = \"\";\n if (m_config.getIgnoreAllFacetFilters()\n || (!m_state.getCheckedEntries().isEmpty() && !m_config.getIsAndFacet())) {\n excludes = \"{!ex=\" + m_config.getIgnoreTags() + \"}\";\n }\n\n for (I_CmsFacetQueryItem q : m_config.getQueryList()) {\n query.add(\"facet.query\", excludes + q.getQuery());\n }\n }", "public void createLinks(ServiceReference<S> declarationBinderRef) {\n for (D declaration : linkerManagement.getMatchedDeclaration()) {\n if (linkerManagement.canBeLinked(declaration, declarationBinderRef)) {\n linkerManagement.link(declaration, declarationBinderRef);\n }\n }\n }", "public static int isValid( DMatrixRMaj cov ) {\n if( !MatrixFeatures_DDRM.isDiagonalPositive(cov) )\n return 1;\n\n if( !MatrixFeatures_DDRM.isSymmetric(cov,TOL) )\n return 2;\n\n if( !MatrixFeatures_DDRM.isPositiveSemidefinite(cov) )\n return 3;\n\n return 0;\n }" ]
Use this API to delete sslfipskey of given name.
[ "public static base_response delete(nitro_service client, String fipskeyname) throws Exception {\n\t\tsslfipskey deleteresource = new sslfipskey();\n\t\tdeleteresource.fipskeyname = fipskeyname;\n\t\treturn deleteresource.delete_resource(client);\n\t}" ]
[ "private void addDependencyToGraph(final DbDependency dependency, final AbstractGraph graph, final int depth, final String parentId) {\n // In that case of Axway artifact we will add a module to the graph\n if (filters.getCorporateFilter().filter(dependency)) {\n final DbModule dbTarget = repoHandler.getModuleOf(dependency.getTarget());\n\n // if there is no module, add the artifact to the graph\n if(dbTarget == null){\n LOG.error(\"Got missing reference: \" + dependency.getTarget());\n final DbArtifact dbArtifact = DataUtils.createDbArtifact(dependency.getTarget());\n final String targetElementId = graph.getId(dbArtifact);\n graph.addElement(targetElementId, dbArtifact.getVersion(), false);\n graph.addDependency(parentId, targetElementId, dependency.getScope());\n return;\n }\n\n // Add the element to the graph\n addModuleToGraph(dbTarget, graph, depth + 1);\n\n //Add the dependency to the graph\n final String moduleElementId = graph.getId(dbTarget);\n graph.addDependency(parentId, moduleElementId, dependency.getScope());\n }\n // In case a third-party we will add an artifact\n else {\n final DbArtifact dbTarget = repoHandler.getArtifact(dependency.getTarget());\n if(dbTarget == null){\n LOG.error(\"Got missing artifact: \" + dependency.getTarget());\n return;\n }\n\n if(!graph.isTreated(graph.getId(dbTarget))){\n final ModelMapper modelMapper = new ModelMapper(repoHandler);\n final Artifact target = modelMapper.getArtifact(dbTarget);\n final String targetElementId = graph.getId(target);\n graph.addElement(targetElementId, target.getVersion(), false);\n graph.addDependency(parentId, targetElementId, dependency.getScope());\n }\n }\n }", "public static GVRSceneObject loadModel(final GVRContext gvrContext,\n final String modelFile) throws IOException {\n return loadModel(gvrContext, modelFile, new HashMap<String, Integer>());\n }", "void apply() {\n final FlushLog log = new FlushLog();\n store.logOperations(txn, log);\n final BlobVault blobVault = store.getBlobVault();\n if (blobVault.requiresTxn()) {\n try {\n blobVault.flushBlobs(blobStreams, blobFiles, deferredBlobsToDelete, txn);\n } catch (Exception e) {\n // out of disk space not expected there\n throw ExodusException.toEntityStoreException(e);\n }\n }\n txn.setCommitHook(new Runnable() {\n @Override\n public void run() {\n log.flushed();\n final EntityIterableCacheAdapterMutable cache = PersistentStoreTransaction.this.mutableCache;\n if (cache != null) { // mutableCache can be null if only blobs are modified\n applyAtomicCaches(cache);\n }\n }\n });\n }", "public void addBetween(Object attribute, Object value1, Object value2)\r\n {\r\n\t\t// PAW\r\n\t\t// addSelectionCriteria(ValueCriteria.buildBeweenCriteria(attribute, value1, value2, getAlias()));\r\n\t\taddSelectionCriteria(ValueCriteria.buildBeweenCriteria(attribute, value1, value2, getUserAlias(attribute)));\r\n }", "static <K, V> PageMetadata<K, V> mergeTokenAndQueryParameters(String paginationToken, final\n ViewQueryParameters<K, V> initialParameters) {\n\n // Decode the base64 token into JSON\n String json = new String(Base64.decodeBase64(paginationToken), Charset.forName(\"UTF-8\"));\n\n // Get a suitable Gson, we need any adapter registered for the K key type\n Gson paginationTokenGson = getGsonWithKeyAdapter(initialParameters);\n\n // Deserialize the pagination token JSON, using the appropriate K, V types\n PaginationToken token = paginationTokenGson.fromJson(json, PaginationToken.class);\n\n // Create new query parameters using the initial ViewQueryParameters as a starting point.\n ViewQueryParameters<K, V> tokenPageParameters = initialParameters.copy();\n\n // Merge the values from the token into the new query parameters\n tokenPageParameters.descending = token.descending;\n tokenPageParameters.endkey = token.endkey;\n tokenPageParameters.endkey_docid = token.endkey_docid;\n tokenPageParameters.inclusive_end = token.inclusive_end;\n tokenPageParameters.startkey = token.startkey;\n tokenPageParameters.startkey_docid = token.startkey_docid;\n\n return new PageMetadata<K, V>(token.direction, token\n .pageNumber, tokenPageParameters);\n }", "public Script getScript(int id) {\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = SQLService.getInstance().getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_SCRIPT +\n \" WHERE id = ?\"\n );\n statement.setInt(1, id);\n results = statement.executeQuery();\n if (results.next()) {\n return scriptFromSQLResult(results);\n }\n } catch (Exception e) {\n\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return null;\n }", "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 }", "public static responderpolicy[] get(nitro_service service) throws Exception{\n\t\tresponderpolicy obj = new responderpolicy();\n\t\tresponderpolicy[] response = (responderpolicy[])obj.get_resources(service);\n\t\treturn response;\n\t}", "private Layout getActiveLayout(Project phoenixProject)\n {\n //\n // Start with the first layout we find\n //\n Layout activeLayout = phoenixProject.getLayouts().getLayout().get(0);\n\n //\n // If this isn't active, find one which is... and if none are,\n // we'll just use the first.\n //\n if (!activeLayout.isActive().booleanValue())\n {\n for (Layout layout : phoenixProject.getLayouts().getLayout())\n {\n if (layout.isActive().booleanValue())\n {\n activeLayout = layout;\n break;\n }\n }\n }\n\n return activeLayout;\n }" ]
Iterates over the elements of an iterable collection of items and returns the index values of the items that match the condition specified in the closure. @param self the iteration object over which to iterate @param closure the filter to perform a match on the collection @return a list of numbers corresponding to the index values of all matched objects @since 1.5.2
[ "public static List<Number> findIndexValues(Object self, Closure closure) {\n return findIndexValues(self, 0, closure);\n }" ]
[ "public Rate getRate(int field) throws MPXJException\n {\n Rate result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n try\n {\n String rate = m_fields[field];\n int index = rate.indexOf('/');\n double amount;\n TimeUnit units;\n\n if (index == -1)\n {\n amount = m_formats.getCurrencyFormat().parse(rate).doubleValue();\n units = TimeUnit.HOURS;\n }\n else\n {\n amount = m_formats.getCurrencyFormat().parse(rate.substring(0, index)).doubleValue();\n units = TimeUnitUtility.getInstance(rate.substring(index + 1), m_locale);\n }\n\n result = new Rate(amount, units);\n }\n\n catch (ParseException ex)\n {\n throw new MPXJException(\"Failed to parse rate\", ex);\n }\n }\n else\n {\n result = null;\n }\n\n return (result);\n }", "public Where<T, ID> isNull(String columnName) throws SQLException {\n\t\taddClause(new IsNull(columnName, findColumnFieldType(columnName)));\n\t\treturn this;\n\t}", "public CompletableFuture<Void> stop() {\n numPendingStopRequests.incrementAndGet();\n return startStop.stop().thenRun(numPendingStopRequests::decrementAndGet);\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 void detachMetadataCache(SlotReference slot) {\n MetadataCache oldCache = metadataCacheFiles.remove(slot);\n if (oldCache != null) {\n try {\n oldCache.close();\n } catch (IOException e) {\n logger.error(\"Problem closing metadata cache\", e);\n }\n deliverCacheUpdate(slot, null);\n }\n }", "private void populateCurrencySettings(Record record, ProjectProperties properties)\n {\n properties.setCurrencySymbol(record.getString(0));\n properties.setSymbolPosition(record.getCurrencySymbolPosition(1));\n properties.setCurrencyDigits(record.getInteger(2));\n\n Character c = record.getCharacter(3);\n if (c != null)\n {\n properties.setThousandsSeparator(c.charValue());\n }\n\n c = record.getCharacter(4);\n if (c != null)\n {\n properties.setDecimalSeparator(c.charValue());\n }\n }", "public boolean getCritical()\n {\n Boolean critical = (Boolean) getCachedValue(TaskField.CRITICAL);\n if (critical == null)\n {\n Duration totalSlack = getTotalSlack();\n ProjectProperties props = getParentFile().getProjectProperties();\n int criticalSlackLimit = NumberHelper.getInt(props.getCriticalSlackLimit());\n if (criticalSlackLimit != 0 && totalSlack.getDuration() != 0 && totalSlack.getUnits() != TimeUnit.DAYS)\n {\n totalSlack = totalSlack.convertUnits(TimeUnit.DAYS, props);\n }\n critical = Boolean.valueOf(totalSlack.getDuration() <= criticalSlackLimit && NumberHelper.getInt(getPercentageComplete()) != 100 && ((getTaskMode() == TaskMode.AUTO_SCHEDULED) || (getDurationText() == null && getStartText() == null && getFinishText() == null)));\n set(TaskField.CRITICAL, critical);\n }\n return (BooleanHelper.getBoolean(critical));\n }", "static void onActivityCreated(Activity activity) {\n // make sure we have at least the default instance created here.\n if (instances == null) {\n CleverTapAPI.createInstanceIfAvailable(activity, null);\n }\n\n if (instances == null) {\n Logger.v(\"Instances is null in onActivityCreated!\");\n return;\n }\n\n boolean alreadyProcessedByCleverTap = false;\n Bundle notification = null;\n Uri deepLink = null;\n String _accountId = null;\n\n // check for launch deep link\n try {\n Intent intent = activity.getIntent();\n deepLink = intent.getData();\n if (deepLink != null) {\n Bundle queryArgs = UriHelper.getAllKeyValuePairs(deepLink.toString(), true);\n _accountId = queryArgs.getString(Constants.WZRK_ACCT_ID_KEY);\n }\n } catch (Throwable t) {\n // Ignore\n }\n\n // check for launch via notification click\n try {\n notification = activity.getIntent().getExtras();\n if (notification != null && !notification.isEmpty()) {\n try {\n alreadyProcessedByCleverTap = (notification.containsKey(Constants.WZRK_FROM_KEY) && Constants.WZRK_FROM.equals(notification.get(Constants.WZRK_FROM_KEY)));\n if (alreadyProcessedByCleverTap){\n Logger.v(\"ActivityLifecycleCallback: Notification Clicked already processed for \"+ notification.toString() +\", dropping duplicate.\");\n }\n if (notification.containsKey(Constants.WZRK_ACCT_ID_KEY)) {\n _accountId = (String) notification.get(Constants.WZRK_ACCT_ID_KEY);\n }\n } catch (Throwable t) {\n // no-op\n }\n }\n } catch (Throwable t) {\n // Ignore\n }\n\n if (alreadyProcessedByCleverTap && deepLink == null) return;\n\n for (String accountId: CleverTapAPI.instances.keySet()) {\n CleverTapAPI instance = CleverTapAPI.instances.get(accountId);\n\n boolean shouldProcess = false;\n if (instance != null) {\n shouldProcess = (_accountId == null && instance.config.isDefaultInstance()) || instance.getAccountId().equals(_accountId);\n }\n\n if (shouldProcess) {\n if (notification != null && !notification.isEmpty() && notification.containsKey(Constants.NOTIFICATION_TAG)) {\n instance.pushNotificationClickedEvent(notification);\n }\n\n if (deepLink != null) {\n try {\n instance.pushDeepLink(deepLink);\n } catch (Throwable t) {\n // no-op\n }\n }\n break;\n }\n }\n }", "protected synchronized StealerBasedRebalanceTask scheduleNextTask(boolean executeService) {\n // Make sure there is work left to do.\n if(doneSignal.getCount() == 0) {\n logger.info(\"All tasks completion signaled... returning\");\n\n return null;\n }\n // Limit number of tasks outstanding.\n if(this.numTasksExecuting >= maxParallelRebalancing) {\n logger.info(\"Executing more tasks than [\" + this.numTasksExecuting\n + \"] the parallel allowed \" + maxParallelRebalancing);\n return null;\n }\n // Shuffle list of stealer IDs each time a new task to schedule needs to\n // be found. Randomizing the order should avoid prioritizing one\n // specific stealer's work ahead of all others.\n List<Integer> stealerIds = new ArrayList<Integer>(tasksByStealer.keySet());\n Collections.shuffle(stealerIds);\n for(int stealerId: stealerIds) {\n if(nodeIdsWithWork.contains(stealerId)) {\n logger.info(\"Stealer \" + stealerId + \" is already working... continuing\");\n continue;\n }\n\n for(StealerBasedRebalanceTask sbTask: tasksByStealer.get(stealerId)) {\n int donorId = sbTask.getStealInfos().get(0).getDonorId();\n if(nodeIdsWithWork.contains(donorId)) {\n logger.info(\"Stealer \" + stealerId + \" Donor \" + donorId\n + \" is already working... continuing\");\n continue;\n }\n // Book keeping\n addNodesToWorkerList(Arrays.asList(stealerId, donorId));\n numTasksExecuting++;\n // Remove this task from list thus destroying list being\n // iterated over. This is safe because returning directly out of\n // this branch.\n tasksByStealer.get(stealerId).remove(sbTask);\n try {\n if(executeService) {\n logger.info(\"Stealer \" + stealerId + \" Donor \" + donorId\n + \" going to schedule work\");\n service.execute(sbTask);\n }\n } catch(RejectedExecutionException ree) {\n logger.error(\"Stealer \" + stealerId\n + \"Rebalancing task rejected by executor service.\", ree);\n throw new VoldemortRebalancingException(\"Stealer \"\n + stealerId\n + \"Rebalancing task rejected by executor service.\");\n }\n return sbTask;\n }\n }\n printRemainingTasks(stealerIds);\n return null;\n }" ]
Performs the transformation. @return True if the file was modified.
[ "public Boolean invoke(File pomFile, VirtualChannel channel) throws IOException, InterruptedException {\n\n org.jfrog.build.extractor.maven.reader.ModuleName current = new org.jfrog.build.extractor.maven.reader.ModuleName(\n currentModule.groupId, currentModule.artifactId);\n\n Map<org.jfrog.build.extractor.maven.reader.ModuleName, String> modules = Maps.newLinkedHashMap();\n for (Map.Entry<ModuleName, String> entry : versionsByModule.entrySet()) {\n modules.put(new org.jfrog.build.extractor.maven.reader.ModuleName(\n entry.getKey().groupId, entry.getKey().artifactId), entry.getValue());\n }\n\n org.jfrog.build.extractor.maven.transformer.PomTransformer transformer =\n new org.jfrog.build.extractor.maven.transformer.PomTransformer(current, modules, scmUrl,\n failOnSnapshot);\n\n return transformer.transform(pomFile);\n }" ]
[ "private void setUserFieldValue(UDFAssignmentType udf, DataType dataType, Object value)\n {\n switch (dataType)\n {\n case DURATION:\n {\n udf.setTextValue(((Duration) value).toString());\n break;\n }\n\n case CURRENCY:\n {\n if (!(value instanceof Double))\n {\n value = Double.valueOf(((Number) value).doubleValue());\n }\n udf.setCostValue((Double) value);\n break;\n }\n\n case BINARY:\n {\n udf.setTextValue(\"\");\n break;\n }\n\n case STRING:\n {\n udf.setTextValue((String) value);\n break;\n }\n\n case DATE:\n {\n udf.setStartDateValue((Date) value);\n break;\n }\n\n case NUMERIC:\n {\n if (!(value instanceof Double))\n {\n value = Double.valueOf(((Number) value).doubleValue());\n }\n udf.setDoubleValue((Double) value);\n break;\n }\n\n case BOOLEAN:\n {\n udf.setIntegerValue(BooleanHelper.getBoolean((Boolean) value) ? Integer.valueOf(1) : Integer.valueOf(0));\n break;\n }\n\n case INTEGER:\n case SHORT:\n {\n udf.setIntegerValue(NumberHelper.getInteger((Number) value));\n break;\n }\n\n default:\n {\n throw new RuntimeException(\"Unconvertible data type: \" + dataType);\n }\n }\n }", "public void createContainer(String container) {\n\n ContainerController controller = this.platformContainers.get(container);\n if (controller == null) {\n\n // TODO make this configurable\n Profile p = new ProfileImpl();\n p.setParameter(Profile.PLATFORM_ID, PLATFORM_ID);\n p.setParameter(Profile.MAIN_HOST, MAIN_HOST);\n p.setParameter(Profile.MAIN_PORT, MAIN_PORT);\n p.setParameter(Profile.LOCAL_HOST, MAIN_HOST);\n int port = Integer.parseInt(MAIN_PORT);\n port = port + 1 + this.platformContainers.size();\n p.setParameter(Profile.LOCAL_PORT, Integer.toString(port));\n p.setParameter(Profile.CONTAINER_NAME, container);\n logger.fine(\"Creating container \" + container + \"...\");\n ContainerController agentContainer = this.runtime\n .createAgentContainer(p);\n this.platformContainers.put(container, agentContainer);\n logger.fine(\"Container \" + container + \" created successfully.\");\n } else {\n logger.fine(\"Container \" + container + \" is already created.\");\n }\n\n }", "public boolean removeAll(Collection<?> collection) {\n boolean result = false;\n synchronized (mLock) {\n Iterator<?> it;\n if (mOriginalValues != null) {\n it = mOriginalValues.iterator();\n\n } else {\n it = mObjects.iterator();\n }\n while (it.hasNext()) {\n if (collection.contains(it.next())) {\n it.remove();\n result = true;\n }\n }\n }\n if (mNotifyOnChange) notifyDataSetChanged();\n return result;\n }", "public void registerServices(boolean force) {\n\t\tInjector injector = Guice.createInjector(getGuiceModule());\n\t\tinjector.injectMembers(this);\n\t\tregisterInRegistry(force);\n\t}", "private static Set<String> excludedMethods(String... methodNames)\n {\n Set<String> set = new HashSet<String>(MpxjTreeNode.DEFAULT_EXCLUDED_METHODS);\n set.addAll(Arrays.asList(methodNames));\n return set;\n }", "public boolean checkWrite(TransactionImpl tx, Object obj)\r\n {\r\n LockEntry writer = getWriter(obj);\r\n if (writer == null)\r\n return false;\r\n else if (writer.isOwnedBy(tx))\r\n return true;\r\n else\r\n return false;\r\n }", "private FieldType addUserDefinedField(FieldTypeClass fieldType, UserFieldDataType dataType, String name)\n {\n FieldType field = null;\n \n try\n {\n switch (fieldType)\n {\n case TASK:\n {\n do\n {\n field = m_taskUdfCounters.nextField(TaskField.class, dataType);\n }\n while (RESERVED_TASK_FIELDS.contains(field));\n\n m_projectFile.getCustomFields().getCustomField(field).setAlias(name);\n\n break;\n }\n \n case RESOURCE:\n {\n field = m_resourceUdfCounters.nextField(ResourceField.class, dataType);\n m_projectFile.getCustomFields().getCustomField(field).setAlias(name);\n break;\n }\n \n case ASSIGNMENT:\n {\n field = m_assignmentUdfCounters.nextField(AssignmentField.class, dataType);\n m_projectFile.getCustomFields().getCustomField(field).setAlias(name);\n break;\n }\n \n default:\n {\n break;\n }\n } \n }\n\n catch (Exception ex)\n {\n //\n // SF#227: If we get an exception thrown here... it's likely that\n // we've run out of user defined fields, for example\n // there are only 30 TEXT fields. We'll ignore this: the user\n // defined field won't be mapped to an alias, so we'll\n // ignore it when we read in the values.\n //\n }\n \n return field;\n }", "private CmsFavInfo createFavInfo(CmsFavoriteEntry entry) throws CmsException {\n\n String title = \"\";\n String subtitle = \"\";\n CmsFavInfo result = new CmsFavInfo(entry);\n CmsObject cms = A_CmsUI.getCmsObject();\n String project = getProject(cms, entry);\n String site = getSite(cms, entry);\n try {\n CmsUUID idToLoad = entry.getDetailId() != null ? entry.getDetailId() : entry.getStructureId();\n CmsResource resource = cms.readResource(idToLoad, CmsResourceFilter.IGNORE_EXPIRATION.addRequireVisible());\n CmsResourceUtil resutil = new CmsResourceUtil(cms, resource);\n switch (entry.getType()) {\n case explorerFolder:\n title = CmsStringUtil.isEmpty(resutil.getTitle())\n ? CmsResource.getName(resource.getRootPath())\n : resutil.getTitle();\n break;\n case page:\n title = resutil.getTitle();\n break;\n }\n subtitle = resource.getRootPath();\n CmsResourceIcon icon = result.getResourceIcon();\n icon.initContent(resutil, CmsResource.STATE_UNCHANGED, false, false);\n } catch (CmsException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n }\n result.getTopLine().setValue(title);\n result.getBottomLine().setValue(subtitle);\n result.getProjectLabel().setValue(project);\n result.getSiteLabel().setValue(site);\n\n return result;\n\n }", "boolean openStream() throws InterruptedException, IOException {\n logger.info(\"stream START\");\n final boolean isOpen;\n final Set<BsonValue> idsToWatch = nsConfig.getSynchronizedDocumentIds();\n\n if (!networkMonitor.isConnected()) {\n logger.info(\"stream END - Network disconnected\");\n return false;\n }\n\n if (idsToWatch.isEmpty()) {\n logger.info(\"stream END - No synchronized documents\");\n return false;\n }\n\n nsLock.writeLock().lockInterruptibly();\n try {\n if (!authMonitor.isLoggedIn()) {\n logger.info(\"stream END - Logged out\");\n return false;\n }\n\n final Document args = new Document();\n args.put(\"database\", namespace.getDatabaseName());\n args.put(\"collection\", namespace.getCollectionName());\n args.put(\"ids\", idsToWatch);\n\n currentStream =\n service.streamFunction(\n \"watch\",\n Collections.singletonList(args),\n ResultDecoders.changeEventDecoder(BSON_DOCUMENT_CODEC));\n\n if (currentStream != null && currentStream.isOpen()) {\n this.nsConfig.setStale(true);\n isOpen = true;\n } else {\n isOpen = false;\n }\n } finally {\n nsLock.writeLock().unlock();\n }\n return isOpen;\n }" ]
Convert a request type string to value @param requestType String value of request type GET/POST/PUT/DELETE @return Matching REQUEST_TYPE. Defaults to ALL
[ "protected int getRequestTypeFromString(String requestType) {\n if (\"GET\".equals(requestType)) {\n return REQUEST_TYPE_GET;\n }\n if (\"POST\".equals(requestType)) {\n return REQUEST_TYPE_POST;\n }\n if (\"PUT\".equals(requestType)) {\n return REQUEST_TYPE_PUT;\n }\n if (\"DELETE\".equals(requestType)) {\n return REQUEST_TYPE_DELETE;\n }\n return REQUEST_TYPE_ALL;\n }" ]
[ "public static JasperPrint generateJasperPrint(DynamicReport dr, LayoutManager layoutManager, JRDataSource ds, Map<String, Object> _parameters) throws JRException {\n log.info(\"generating JasperPrint\");\n JasperPrint jp;\n\n\n JasperReport jr = DynamicJasperHelper.generateJasperReport(dr, layoutManager, _parameters);\n jp = JasperFillManager.fillReport(jr, _parameters, ds);\n\n return jp;\n }", "public synchronized boolean tryDelegateSlop(Node node) {\n if(asyncCallbackShouldSendhint) {\n return false;\n } else {\n slopDestinations.put(node, true);\n return true;\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 }", "public Info getInfo(String ... fields) {\r\n QueryStringBuilder builder = new QueryStringBuilder();\r\n if (fields.length > 0) {\r\n builder.appendParam(\"fields\", fields);\r\n }\r\n URL url = DEVICE_PIN_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), this.getID());\r\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\r\n BoxJSONResponse response = (BoxJSONResponse) request.send();\r\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\r\n return new Info(responseJSON);\r\n }", "public BlockHeader read(byte[] buffer, int offset, int postHeaderSkipBytes)\n {\n m_offset = offset;\n\n System.arraycopy(buffer, m_offset, m_header, 0, 8);\n m_offset += 8;\n\n int nameLength = FastTrackUtility.getInt(buffer, m_offset);\n m_offset += 4;\n\n if (nameLength < 1 || nameLength > 255)\n {\n throw new UnexpectedStructureException();\n }\n\n m_name = new String(buffer, m_offset, nameLength, CharsetHelper.UTF16LE);\n m_offset += nameLength;\n\n m_columnType = FastTrackUtility.getShort(buffer, m_offset);\n m_offset += 2;\n\n m_flags = FastTrackUtility.getShort(buffer, m_offset);\n m_offset += 2;\n\n m_skip = new byte[postHeaderSkipBytes];\n System.arraycopy(buffer, m_offset, m_skip, 0, postHeaderSkipBytes);\n m_offset += postHeaderSkipBytes;\n\n return this;\n }", "public static void addInterceptors(InterceptorProvider provider) {\n PhaseManager phases = BusFactory.getDefaultBus().getExtension(PhaseManager.class);\n for (Phase p : phases.getInPhases()) {\n provider.getInInterceptors().add(new DemoInterceptor(p.getName()));\n provider.getInFaultInterceptors().add(new DemoInterceptor(p.getName()));\n }\n for (Phase p : phases.getOutPhases()) {\n provider.getOutInterceptors().add(new DemoInterceptor(p.getName()));\n provider.getOutFaultInterceptors().add(new DemoInterceptor(p.getName()));\n }\n }", "public void applyToPrimaryClassNodes(PrimaryClassNodeOperation body) throws CompilationFailedException {\n Iterator classNodes = getPrimaryClassNodes(body.needSortedInput()).iterator();\n while (classNodes.hasNext()) {\n SourceUnit context = null;\n try {\n ClassNode classNode = (ClassNode) classNodes.next();\n context = classNode.getModule().getContext();\n if (context == null || context.phase < phase || (context.phase == phase && !context.phaseComplete)) {\n int offset = 1;\n Iterator<InnerClassNode> iterator = classNode.getInnerClasses();\n while (iterator.hasNext()) {\n iterator.next();\n offset++;\n }\n body.call(context, new GeneratorContext(this.ast, offset), classNode);\n }\n } catch (CompilationFailedException e) {\n // fall through, getErrorReporter().failIfErrors() will trigger\n } catch (NullPointerException npe) {\n GroovyBugError gbe = new GroovyBugError(\"unexpected NullpointerException\", npe);\n changeBugText(gbe, context);\n throw gbe;\n } catch (GroovyBugError e) {\n changeBugText(e, context);\n throw e;\n } catch (NoClassDefFoundError e) {\n // effort to get more logging in case a dependency of a class is loaded\n // although it shouldn't have\n convertUncaughtExceptionToCompilationError(e);\n } catch (Exception e) {\n convertUncaughtExceptionToCompilationError(e);\n }\n }\n\n getErrorCollector().failIfErrors();\n }", "protected static void appendHandler(Class<? extends LogRecordHandler> parent, LogRecordHandler child){\r\n List<LogRecordHandler> toAdd = new LinkedList<LogRecordHandler>();\r\n //--Find Parents\r\n for(LogRecordHandler term : handlers){\r\n if(parent.isAssignableFrom(term.getClass())){\r\n toAdd.add(term);\r\n }\r\n }\r\n //--Add Handler\r\n for(LogRecordHandler p : toAdd){\r\n appendHandler(p, child);\r\n }\r\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}" ]
process all messages in this batch, provided there is plenty of output space.
[ "private void onRead0() {\n assert inWire.startUse();\n\n ensureCapacity();\n\n try {\n\n while (!inWire.bytes().isEmpty()) {\n\n try (DocumentContext dc = inWire.readingDocument()) {\n if (!dc.isPresent())\n return;\n\n try {\n if (YamlLogging.showServerReads())\n logYaml(dc);\n onRead(dc, outWire);\n onWrite(outWire);\n } catch (Exception e) {\n Jvm.warn().on(getClass(), \"inWire=\" + inWire.getClass() + \",yaml=\" + Wires.fromSizePrefixedBlobs(dc), e);\n }\n }\n }\n\n } finally {\n assert inWire.endUse();\n }\n }" ]
[ "public static Comparator getComparator()\r\n {\r\n return new Comparator()\r\n {\r\n public int compare(Object o1, Object o2)\r\n {\r\n FieldDescriptor fmd1 = (FieldDescriptor) o1;\r\n FieldDescriptor fmd2 = (FieldDescriptor) o2;\r\n if (fmd1.getColNo() < fmd2.getColNo())\r\n {\r\n return -1;\r\n }\r\n else if (fmd1.getColNo() > fmd2.getColNo())\r\n {\r\n return 1;\r\n }\r\n else\r\n {\r\n return 0;\r\n }\r\n }\r\n };\r\n }", "@Inject(\"struts.json.action.fileProtocols\")\n\tpublic void setFileProtocols(String fileProtocols) {\n\t\tif (StringUtils.isNotBlank(fileProtocols)) {\n\t\t\tthis.fileProtocols = TextParseUtil.commaDelimitedStringToSet(fileProtocols);\n\t\t}\n\t}", "private void computeGradientAndHessian(DMatrixRMaj param )\n {\n // residuals = f(x) - y\n function.compute(param, residuals);\n\n computeNumericalJacobian(param,jacobian);\n\n CommonOps_DDRM.multTransA(jacobian, residuals, g);\n CommonOps_DDRM.multTransA(jacobian, jacobian, H);\n\n CommonOps_DDRM.extractDiag(H,Hdiag);\n }", "protected List splitInCriteria(Object attribute, Collection values, boolean negative, int inLimit)\r\n {\r\n List result = new ArrayList();\r\n Collection inCollection = new ArrayList();\r\n\r\n if (values == null || values.isEmpty())\r\n {\r\n // OQL creates empty Criteria for late binding\r\n result.add(buildInCriteria(attribute, negative, values));\r\n }\r\n else\r\n {\r\n Iterator iter = values.iterator();\r\n\r\n while (iter.hasNext())\r\n {\r\n inCollection.add(iter.next());\r\n if (inCollection.size() == inLimit || !iter.hasNext())\r\n {\r\n result.add(buildInCriteria(attribute, negative, inCollection));\r\n inCollection = new ArrayList();\r\n }\r\n }\r\n }\r\n return result;\r\n }", "public Replication targetOauth(String consumerSecret,\r\n String consumerKey, String tokenSecret, String token) {\r\n this.replication = replication.targetOauth(consumerSecret, consumerKey,\r\n tokenSecret, token);\r\n return this;\r\n }", "public static double getDaycount(LocalDate startDate, LocalDate endDate, String convention) {\n\t\tDayCountConventionInterface daycountConvention = getDayCountConvention(convention);\n\t\treturn daycountConvention.getDaycount(startDate, endDate);\n\t}", "public static ModelNode determineHostAddress(final ModelControllerClient client) throws IOException, OperationExecutionException {\n final ModelNode op = Operations.createReadAttributeOperation(EMPTY_ADDRESS, \"local-host-name\");\n ModelNode response = client.execute(op);\n if (Operations.isSuccessfulOutcome(response)) {\n return DeploymentOperations.createAddress(\"host\", Operations.readResult(response).asString());\n }\n throw new OperationExecutionException(op, response);\n }", "protected static boolean setCustomForDefaultClient(String profileName, String pathName, Boolean isResponse, String customData) {\n try {\n Client client = new Client(profileName, false);\n client.toggleProfile(true);\n client.setCustom(isResponse, pathName, customData);\n if (isResponse) {\n client.toggleResponseOverride(pathName, true);\n } else {\n client.toggleRequestOverride(pathName, true);\n }\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }", "void bootTimeScan(final DeploymentOperations deploymentOperations) {\n // WFCORE-1579: skip the scan if deployment dir is not available\n if (!checkDeploymentDir(this.deploymentDir)) {\n DeploymentScannerLogger.ROOT_LOGGER.bootTimeScanFailed(deploymentDir.getAbsolutePath());\n return;\n }\n\n this.establishDeployedContentList(this.deploymentDir, deploymentOperations);\n deployedContentEstablished = true;\n if (acquireScanLock()) {\n try {\n scan(true, deploymentOperations);\n } finally {\n releaseScanLock();\n }\n }\n }" ]
Performs the conversion from standard XPath to xpath with parameterization support.
[ "public static String transformXPath(String originalXPath)\n {\n // use a list to maintain the multiple joined xqueries (if there are multiple queries joined with the \"|\" operator)\n List<StringBuilder> compiledXPaths = new ArrayList<>(1);\n\n int frameIdx = -1;\n boolean inQuote = false;\n int conditionLevel = 0;\n char startQuoteChar = 0;\n StringBuilder currentXPath = new StringBuilder();\n compiledXPaths.add(currentXPath);\n for (int i = 0; i < originalXPath.length(); i++)\n {\n char curChar = originalXPath.charAt(i);\n if (!inQuote && curChar == '[')\n {\n frameIdx++;\n conditionLevel++;\n currentXPath.append(\"[windup:startFrame(\").append(frameIdx).append(\") and windup:evaluate(\").append(frameIdx).append(\", \");\n }\n else if (!inQuote && curChar == ']')\n {\n conditionLevel--;\n currentXPath.append(\")]\");\n }\n else if (!inQuote && conditionLevel == 0 && curChar == '|')\n {\n // joining multiple xqueries\n currentXPath = new StringBuilder();\n compiledXPaths.add(currentXPath);\n }\n else\n {\n if (inQuote && curChar == startQuoteChar)\n {\n inQuote = false;\n startQuoteChar = 0;\n }\n else if (curChar == '\"' || curChar == '\\'')\n {\n inQuote = true;\n startQuoteChar = curChar;\n }\n\n if (!inQuote && originalXPath.startsWith(WINDUP_MATCHES_FUNCTION_PREFIX, i))\n {\n i += (WINDUP_MATCHES_FUNCTION_PREFIX.length() - 1);\n currentXPath.append(\"windup:matches(\").append(frameIdx).append(\", \");\n }\n else\n {\n currentXPath.append(curChar);\n }\n }\n }\n\n Pattern leadingAndTrailingWhitespace = Pattern.compile(\"(\\\\s*)(.*?)(\\\\s*)\");\n StringBuilder finalResult = new StringBuilder();\n for (StringBuilder compiledXPath : compiledXPaths)\n {\n if (StringUtils.isNotBlank(compiledXPath))\n {\n Matcher whitespaceMatcher = leadingAndTrailingWhitespace.matcher(compiledXPath);\n if (!whitespaceMatcher.matches())\n continue;\n\n compiledXPath = new StringBuilder();\n compiledXPath.append(whitespaceMatcher.group(1));\n compiledXPath.append(whitespaceMatcher.group(2));\n compiledXPath.append(\"/self::node()[windup:persist(\").append(frameIdx).append(\", \").append(\".)]\");\n compiledXPath.append(whitespaceMatcher.group(3));\n\n if (StringUtils.isNotBlank(finalResult))\n finalResult.append(\"|\");\n finalResult.append(compiledXPath);\n }\n }\n return finalResult.toString();\n }" ]
[ "public void setWorkingDay(Day day, DayType working)\n {\n DayType value;\n\n if (working == null)\n {\n if (isDerived())\n {\n value = DayType.DEFAULT;\n }\n else\n {\n value = DayType.WORKING;\n }\n }\n else\n {\n value = working;\n }\n\n m_days[day.getValue() - 1] = value;\n }", "public static EventLog getEnterpriseEvents(BoxAPIConnection api, Date after, Date before, BoxEvent.Type... types) {\n return getEnterpriseEvents(api, null, after, before, ENTERPRISE_LIMIT, types);\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 }", "public static CmsResource getDescriptor(CmsObject cms, String basename) {\n\n CmsSolrQuery query = new CmsSolrQuery();\n query.setResourceTypes(CmsMessageBundleEditorTypes.BundleType.DESCRIPTOR.toString());\n query.setFilterQueries(\"filename:\\\"\" + basename + CmsMessageBundleEditorTypes.Descriptor.POSTFIX + \"\\\"\");\n query.add(\"fl\", \"path\");\n CmsSolrResultList results;\n try {\n boolean isOnlineProject = cms.getRequestContext().getCurrentProject().isOnlineProject();\n String indexName = isOnlineProject\n ? CmsSolrIndex.DEFAULT_INDEX_NAME_ONLINE\n : CmsSolrIndex.DEFAULT_INDEX_NAME_OFFLINE;\n results = OpenCms.getSearchManager().getIndexSolr(indexName).search(cms, query, true, null, true, null);\n } catch (CmsSearchException e) {\n LOG.error(Messages.get().getBundle().key(Messages.ERR_BUNDLE_DESCRIPTOR_SEARCH_ERROR_0), e);\n return null;\n }\n\n switch (results.size()) {\n case 0:\n return null;\n case 1:\n return results.get(0);\n default:\n String files = \"\";\n for (CmsResource res : results) {\n files += \" \" + res.getRootPath();\n }\n LOG.warn(Messages.get().getBundle().key(Messages.ERR_BUNDLE_DESCRIPTOR_NOT_UNIQUE_1, files));\n return results.get(0);\n }\n }", "private void logMigration(DbMigration migration, boolean wasSuccessful) {\n BoundStatement boundStatement = logMigrationStatement.bind(wasSuccessful, migration.getVersion(),\n migration.getScriptName(), migration.getMigrationScript(), new Date());\n session.execute(boundStatement);\n }", "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 void await() {\n boolean intr = false;\n final Object lock = this.lock;\n try {\n synchronized (lock) {\n while (! readClosed) {\n try {\n lock.wait();\n } catch (InterruptedException e) {\n intr = true;\n }\n }\n }\n } finally {\n if (intr) {\n Thread.currentThread().interrupt();\n }\n }\n }", "public void setNewCenterColor(int color) {\n\t\tmCenterNewColor = color;\n\t\tmCenterNewPaint.setColor(color);\n\t\tif (mCenterOldColor == 0) {\n\t\t\tmCenterOldColor = color;\n\t\t\tmCenterOldPaint.setColor(color);\n\t\t}\n\t\tif (onColorChangedListener != null && color != oldChangedListenerColor ) {\n\t\t\tonColorChangedListener.onColorChanged(color);\n\t\t\toldChangedListenerColor = color;\n\t\t}\n\t\tinvalidate();\n\t}", "public static nspbr6_stats get(nitro_service service, String name) throws Exception{\n\t\tnspbr6_stats obj = new nspbr6_stats();\n\t\tobj.set_name(name);\n\t\tnspbr6_stats response = (nspbr6_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}" ]
Only converts the B matrix and passes that onto solve. Te result is then copied into the input 'X' matrix. @param B A matrix &real; <sup>m &times; p</sup>. Not modified. @param X A matrix &real; <sup>n &times; p</sup>, where the solution is written to. Modified.
[ "@Override\n public void solve(DMatrixRMaj B, DMatrixRMaj X) {\n blockB.reshape(B.numRows,B.numCols,false);\n MatrixOps_DDRB.convert(B,blockB);\n\n // since overwrite B is true X does not need to be passed in\n alg.solve(blockB,null);\n\n MatrixOps_DDRB.convert(blockB,X);\n }" ]
[ "public static Object instantiate(Constructor constructor) throws InstantiationException\r\n {\r\n if(constructor == null)\r\n {\r\n throw new ClassNotPersistenceCapableException(\r\n \"A zero argument constructor was not provided!\");\r\n }\r\n\r\n Object result = null;\r\n try\r\n {\r\n result = constructor.newInstance(NO_ARGS);\r\n }\r\n catch(InstantiationException e)\r\n {\r\n throw e;\r\n }\r\n catch(Exception e)\r\n {\r\n throw new ClassNotPersistenceCapableException(\"Can't instantiate class '\"\r\n + (constructor != null ? constructor.getDeclaringClass().getName() : \"null\")\r\n + \"' with given constructor: \" + e.getMessage(), e);\r\n }\r\n return result;\r\n }", "public Object convertJavaFieldToSqlArgValue(Object fieldVal) throws SQLException {\n\t\t/*\n\t\t * Limitation here. Some people may want to override the null with their own value in the converter but we\n\t\t * currently don't allow that. Specifying a default value I guess is a better mechanism.\n\t\t */\n\t\tif (fieldVal == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn fieldConverter.javaToSqlArg(this, fieldVal);\n\t\t}\n\t}", "public double getValue(double x)\n\t{\n\t\tsynchronized(interpolatingRationalFunctionsLazyInitLock) {\n\t\t\tif(interpolatingRationalFunctions == null) {\n\t\t\t\tdoCreateRationalFunctions();\n\t\t\t}\n\t\t}\n\n\t\t// Get interpolating rational function for the given point x\n\t\tint pointIndex = java.util.Arrays.binarySearch(points, x);\n\t\tif(pointIndex >= 0) {\n\t\t\treturn values[pointIndex];\n\t\t}\n\n\t\tint intervallIndex = -pointIndex-2;\n\n\t\t// Check for extrapolation\n\t\tif(intervallIndex < 0) {\n\t\t\t// Extrapolation\n\t\t\tif(this.extrapolationMethod == ExtrapolationMethod.CONSTANT) {\n\t\t\t\treturn values[0];\n\t\t\t} else if(this.extrapolationMethod == ExtrapolationMethod.LINEAR) {\n\t\t\t\treturn values[0]+(values[1]-values[0])/(points[1]-points[0])*(x-points[0]);\n\t\t\t} else {\n\t\t\t\tintervallIndex = 0;\n\t\t\t}\n\t\t}\n\t\telse if(intervallIndex > points.length-2) {\n\t\t\t// Extrapolation\n\t\t\tif(this.extrapolationMethod == ExtrapolationMethod.CONSTANT) {\n\t\t\t\treturn values[points.length-1];\n\t\t\t} else if(this.extrapolationMethod == ExtrapolationMethod.LINEAR) {\n\t\t\t\treturn values[points.length-1]+(values[points.length-2]-values[points.length-1])/(points[points.length-2]-points[points.length-1])*(x-points[points.length-1]);\n\t\t\t} else {\n\t\t\t\tintervallIndex = points.length-2;\n\t\t\t}\n\t\t}\n\n\t\tRationalFunction rationalFunction = interpolatingRationalFunctions[intervallIndex];\n\n\t\t// Calculate interpolating value\n\t\treturn rationalFunction.getValue(x-points[intervallIndex]);\n\t}", "public static BoxRetentionPolicyAssignment.Info createAssignmentToEnterprise(BoxAPIConnection api,\r\n String policyID) {\r\n return createAssignment(api, policyID, new JsonObject().add(\"type\", TYPE_ENTERPRISE), null);\r\n }", "public Triple<EObject, EReference, INode> decode(Resource res, String uriFragment) {\n\t\tif (isUseIndexFragment(res)) {\n\t\t\treturn getLazyProxyInformation(res, uriFragment);\n\t\t}\n\t\tList<String> split = Strings.split(uriFragment, SEP);\n\t\tEObject source = resolveShortFragment(res, split.get(1));\n\t\tEReference ref = fromShortExternalForm(source.eClass(), split.get(2));\n\t\tINode compositeNode = NodeModelUtils.getNode(source);\n\t\tif (compositeNode==null)\n\t\t\tthrow new IllegalStateException(\"Couldn't resolve lazy link, because no node model is attached.\");\n\t\tINode textNode = getNode(compositeNode, split.get(3));\n\t\treturn Tuples.create(source, ref, textNode);\n\t}", "public static void dumpClusterToFile(String outputDirName, String fileName, Cluster cluster) {\n\n if(outputDirName != null) {\n File outputDir = new File(outputDirName);\n if(!outputDir.exists()) {\n Utils.mkdirs(outputDir);\n }\n\n try {\n FileUtils.writeStringToFile(new File(outputDirName, fileName),\n new ClusterMapper().writeCluster(cluster));\n } catch(IOException e) {\n logger.error(\"IOException during dumpClusterToFile: \" + e);\n }\n }\n }", "public boolean isDeleted(Identity id)\r\n {\r\n ObjectEnvelope envelope = buffer.getByIdentity(id);\r\n\r\n return (envelope != null && envelope.needsDelete());\r\n }", "@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public Searcher addFacet(String... attributes) {\n for (String attribute : attributes) {\n final Integer value = facetRequestCount.get(attribute);\n facetRequestCount.put(attribute, value == null ? 1 : value + 1);\n if (value == null || value == 0) {\n facets.add(attribute);\n }\n }\n rebuildQueryFacets();\n return this;\n }", "private void initDatesPanel() {\n\n m_startLabel.setText(Messages.get().key(Messages.GUI_SERIALDATE_TIME_STARTTIME_0));\n m_startTime.setAllowInvalidValue(true);\n m_startTime.setValue(m_model.getStart());\n m_endLabel.setText(Messages.get().key(Messages.GUI_SERIALDATE_TIME_ENDTIME_0));\n m_endTime.setAllowInvalidValue(true);\n m_endTime.setValue(m_model.getEnd());\n m_seriesCheckBox.setText(Messages.get().key(Messages.GUI_SERIALDATE_SERIES_CHECKBOX_0));\n m_wholeDayCheckBox.setText(Messages.get().key(Messages.GUI_SERIALDATE_WHOLE_DAY_CHECKBOX_0));\n m_currentTillEndCheckBox.setText(Messages.get().key(Messages.GUI_SERIALDATE_CURRENT_TILL_END_CHECKBOX_0));\n m_currentTillEndCheckBox.getButton().setTitle(\n Messages.get().key(Messages.GUI_SERIALDATE_CURRENT_TILL_END_CHECKBOX_HELP_0));\n }" ]
Handles the response of the SerialApiGetInitData request. @param incomingMlivessage the response message to process.
[ "private void handleSerialApiGetInitDataResponse(\n\t\t\tSerialMessage incomingMessage) {\n\t\tlogger.debug(String.format(\"Got MessageSerialApiGetInitData response.\"));\n\t\tthis.isConnected = true;\n\t\tint nodeBytes = incomingMessage.getMessagePayloadByte(2);\n\t\t\n\t\tif (nodeBytes != NODE_BYTES) {\n\t\t\tlogger.error(\"Invalid number of node bytes = {}\", nodeBytes);\n\t\t\treturn;\n\t\t}\n\n\t\tint nodeId = 1;\n\t\t\n\t\t// loop bytes\n\t\tfor (int i = 3;i < 3 + nodeBytes;i++) {\n\t\t\tint incomingByte = incomingMessage.getMessagePayloadByte(i);\n\t\t\t// loop bits in byte\n\t\t\tfor (int j=0;j<8;j++) {\n\t\t\t\tint b1 = incomingByte & (int)Math.pow(2.0D, j);\n\t\t\t\tint b2 = (int)Math.pow(2.0D, j);\n\t\t\t\tif (b1 == b2) {\n\t\t\t\t\tlogger.info(String.format(\"Found node id = %d\", nodeId));\n\t\t\t\t\t// Place nodes in the local ZWave Controller \n\t\t\t\t\tthis.zwaveNodes.put(nodeId, new ZWaveNode(this.homeId, nodeId, this));\n\t\t\t\t\tthis.getNode(nodeId).advanceNodeStage();\n\t\t\t\t}\n\t\t\t\tnodeId++;\n\t\t\t}\n\t\t}\n\t\t\n\t\tlogger.info(\"------------Number of Nodes Found Registered to ZWave Controller------------\");\n\t\tlogger.info(String.format(\"# Nodes = %d\", this.zwaveNodes.size()));\n\t\tlogger.info(\"----------------------------------------------------------------------------\");\n\t\t\n\t\t// Advance node stage for the first node.\n\t}" ]
[ "public static FileOutputStream openResultFileOuputStream(\n\t\t\tPath resultDirectory, String filename) throws IOException {\n\t\tPath filePath = resultDirectory.resolve(filename);\n\t\treturn new FileOutputStream(filePath.toFile());\n\t}", "public double[] getScaleDenominators() {\n double[] dest = new double[this.scaleDenominators.length];\n System.arraycopy(this.scaleDenominators, 0, dest, 0, this.scaleDenominators.length);\n return dest;\n }", "private static String qualifiedName(Options opt, String r) {\n\tif (opt.hideGenerics)\n\t r = removeTemplate(r);\n\t// Fast path - nothing to do:\n\tif (opt.showQualified && (opt.showQualifiedGenerics || r.indexOf('<') < 0))\n\t return r;\n\tStringBuilder buf = new StringBuilder(r.length());\n\tqualifiedNameInner(opt, r, buf, 0, !opt.showQualified);\n\treturn buf.toString();\n }", "void endOfRunDb()\n {\n DbConn cnx = null;\n\n try\n {\n cnx = Helpers.getNewDbSession();\n\n // Done: put inside history & remove instance from queue.\n History.create(cnx, this.ji, this.resultStatus, endDate);\n jqmlogger.trace(\"An History was just created for job instance \" + this.ji.getId());\n cnx.runUpdate(\"ji_delete_by_id\", this.ji.getId());\n cnx.commit();\n }\n catch (RuntimeException e)\n {\n endBlockDbFailureAnalysis(e);\n }\n finally\n {\n Helpers.closeQuietly(cnx);\n }\n }", "public int[] executeBatch(PreparedStatement stmt) throws PlatformException\r\n {\r\n // Check for Oracle batching support\r\n final Method methodSendBatch = (Method) m_batchStatementsInProgress.remove(stmt);\r\n final boolean statementBatchingSupported = methodSendBatch != null;\r\n\r\n int[] retval = null;\r\n if (statementBatchingSupported)\r\n {\r\n try\r\n {\r\n // sendBatch() returns total row count as an Integer\r\n methodSendBatch.invoke(stmt, null);\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 retval = super.executeBatch(stmt);\r\n }\r\n return retval;\r\n }", "private Properties mapToProperties(Map<String, String> map) {\r\n\t\t Properties p = new Properties();\r\n\t\t for (Map.Entry<String,String> entry : map.entrySet()) {\r\n\t\t p.put(entry.getKey(), entry.getValue());\r\n\t\t }\r\n\t\t return p;\r\n\t\t }", "public Map<String, T> parseMap(JsonParser jsonParser) throws IOException {\n HashMap<String, T> map = new HashMap<String, T>();\n while (jsonParser.nextToken() != JsonToken.END_OBJECT) {\n String key = jsonParser.getText();\n jsonParser.nextToken();\n if (jsonParser.getCurrentToken() == JsonToken.VALUE_NULL) {\n map.put(key, null);\n } else{\n map.put(key, parse(jsonParser));\n }\n }\n return map;\n }", "public App on(Heroku.Stack stack) {\n App newApp = copy();\n newApp.stack = new App.Stack(stack);\n return newApp;\n }", "protected void handleINEvent(Exchange exchange, String reqFid) throws Fault {\n Message inMsg = exchange.getInMessage();\n\n EventProducerInterceptor epi = null;\n FlowIdHelper.setFlowId(inMsg, reqFid);\n\n ListIterator<Interceptor<? extends Message>> interceptors = inMsg\n .getInterceptorChain().getIterator();\n\n while (interceptors.hasNext() && epi == null) {\n Interceptor<? extends Message> interceptor = interceptors.next();\n\n if (interceptor instanceof EventProducerInterceptor) {\n epi = (EventProducerInterceptor) interceptor;\n epi.handleMessage(inMsg);\n }\n }\n }" ]
Assign to the data object the val corresponding to the fieldType.
[ "public void assignField(ConnectionSource connectionSource, Object data, Object val, boolean parentObject,\n\t\t\tObjectCache objectCache) throws SQLException {\n\n\t\tif (logger.isLevelEnabled(Level.TRACE)) {\n\t\t\tlogger.trace(\"assiging from data {}, val {}: {}\", (data == null ? \"null\" : data.getClass()),\n\t\t\t\t\t(val == null ? \"null\" : val.getClass()), val);\n\t\t}\n\t\t// if this is a foreign object then val is the foreign object's id val\n\t\tif (foreignRefField != null && val != null) {\n\t\t\t// get the current field value which is the foreign-id\n\t\t\tObject foreignRef = extractJavaFieldValue(data);\n\t\t\t/*\n\t\t\t * See if we don't need to create a new foreign object. If we are refreshing and the id field has not\n\t\t\t * changed then there is no need to create a new foreign object and maybe lose previously refreshed field\n\t\t\t * information.\n\t\t\t */\n\t\t\tif (foreignRef != null && foreignRef.equals(val)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// awhitlock: raised as OrmLite issue: bug #122\n\t\t\tObject cachedVal;\n\t\t\tObjectCache foreignCache = foreignDao.getObjectCache();\n\t\t\tif (foreignCache == null) {\n\t\t\t\tcachedVal = null;\n\t\t\t} else {\n\t\t\t\tcachedVal = foreignCache.get(getType(), val);\n\t\t\t}\n\t\t\tif (cachedVal != null) {\n\t\t\t\tval = cachedVal;\n\t\t\t} else if (!parentObject) {\n\t\t\t\t// the value we are to assign to our field is now the foreign object itself\n\t\t\t\tval = createForeignObject(connectionSource, val, objectCache);\n\t\t\t}\n\t\t}\n\n\t\tif (fieldSetMethod == null) {\n\t\t\ttry {\n\t\t\t\tfield.set(data, val);\n\t\t\t} catch (IllegalArgumentException e) {\n\t\t\t\tif (val == null) {\n\t\t\t\t\tthrow SqlExceptionUtil.create(\"Could not assign object '\" + val + \"' to field \" + this, e);\n\t\t\t\t} else {\n\t\t\t\t\tthrow SqlExceptionUtil.create(\n\t\t\t\t\t\t\t\"Could not assign object '\" + val + \"' of type \" + val.getClass() + \" to field \" + this, e);\n\t\t\t\t}\n\t\t\t} catch (IllegalAccessException e) {\n\t\t\t\tthrow SqlExceptionUtil.create(\n\t\t\t\t\t\t\"Could not assign object '\" + val + \"' of type \" + val.getClass() + \"' to field \" + this, e);\n\t\t\t}\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tfieldSetMethod.invoke(data, val);\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow SqlExceptionUtil\n\t\t\t\t\t\t.create(\"Could not call \" + fieldSetMethod + \" on object with '\" + val + \"' for \" + this, e);\n\t\t\t}\n\t\t}\n\t}" ]
[ "private List<Long> collectLongMetric(String metricGetterName) {\n List<Long> vals = new ArrayList<Long>();\n for(BdbEnvironmentStats envStats: environmentStatsTracked) {\n vals.add((Long) ReflectUtils.callMethod(envStats,\n BdbEnvironmentStats.class,\n metricGetterName,\n new Class<?>[0],\n new Object[0]));\n }\n return vals;\n }", "private void forward() {\n\n Set<String> selected = new HashSet<>();\n\n for (CheckBox checkbox : m_componentCheckboxes) {\n CmsSetupComponent component = (CmsSetupComponent)(checkbox.getData());\n if (checkbox.getValue().booleanValue()) {\n selected.add(component.getId());\n }\n }\n String error = null;\n for (String compId : selected) {\n CmsSetupComponent component = m_componentMap.get(compId);\n for (String dep : component.getDependencies()) {\n if (!selected.contains(dep)) {\n error = \"Unfulfilled dependency: The component \"\n + component.getName()\n + \" can not be installed because its dependency \"\n + m_componentMap.get(dep).getName()\n + \" is not selected\";\n break;\n }\n }\n }\n if (error == null) {\n Set<String> modules = new HashSet<>();\n\n for (CmsSetupComponent component : m_componentMap.values()) {\n\n if (selected.contains(component.getId())) {\n\n for (CmsModule module : m_context.getSetupBean().getAvailableModules().values()) {\n if (component.match(module.getName())) {\n modules.add(module.getName());\n }\n }\n }\n }\n List<String> moduleList = new ArrayList<>(modules);\n m_context.getSetupBean().setInstallModules(CmsStringUtil.listAsString(moduleList, \"|\"));\n m_context.stepForward();\n } else {\n CmsSetupErrorDialog.showErrorDialog(error, error);\n }\n }", "public String code(final String code) {\n if (this.theme == null) {\n throw new TemplateProcessingException(\"Theme cannot be resolved because RequestContext was not found. \"\n + \"Are you using a Context object without a RequestContext variable?\");\n }\n return this.theme.getMessageSource().getMessage(code, null, \"\", this.locale);\n }", "public static ExtensibleConfigurationPersister createHostXmlConfigurationPersister(final ConfigurationFile file, final HostControllerEnvironment environment,\n final ExecutorService executorService, final ExtensionRegistry hostExtensionRegistry,\n final LocalHostControllerInfo localHostControllerInfo) {\n String defaultHostname = localHostControllerInfo.getLocalHostName();\n if (environment.getRunningModeControl().isReloaded()) {\n if (environment.getRunningModeControl().getReloadHostName() != null) {\n defaultHostname = environment.getRunningModeControl().getReloadHostName();\n }\n }\n HostXml hostXml = new HostXml(defaultHostname, environment.getRunningModeControl().getRunningMode(),\n environment.isUseCachedDc(), Module.getBootModuleLoader(), executorService, hostExtensionRegistry);\n BackupXmlConfigurationPersister persister = new BackupXmlConfigurationPersister(file, new QName(Namespace.CURRENT.getUriString(), \"host\"), hostXml, hostXml, false);\n for (Namespace namespace : Namespace.domainValues()) {\n if (!namespace.equals(Namespace.CURRENT)) {\n persister.registerAdditionalRootElement(new QName(namespace.getUriString(), \"host\"), hostXml);\n }\n }\n hostExtensionRegistry.setWriterRegistry(persister);\n return persister;\n }", "public void addCell(TableLayoutCell cell) {\n GridBagConstraints constraints = cell.getConstraints();\n constraints.insets = new Insets(cellpadding, cellpadding, cellpadding, cellpadding);\n add(cell.getComponent(), constraints);\n }", "public static String analyzeInvalidMetadataRate(final Cluster currentCluster,\n List<StoreDefinition> currentStoreDefs,\n final Cluster finalCluster,\n List<StoreDefinition> finalStoreDefs) {\n StringBuilder sb = new StringBuilder();\n sb.append(\"Dump of invalid metadata rates per zone\").append(Utils.NEWLINE);\n\n HashMap<StoreDefinition, Integer> uniqueStores = StoreDefinitionUtils.getUniqueStoreDefinitionsWithCounts(currentStoreDefs);\n\n for(StoreDefinition currentStoreDef: uniqueStores.keySet()) {\n sb.append(\"Store exemplar: \" + currentStoreDef.getName())\n .append(Utils.NEWLINE)\n .append(\"\\tThere are \" + uniqueStores.get(currentStoreDef) + \" other similar stores.\")\n .append(Utils.NEWLINE);\n\n StoreRoutingPlan currentSRP = new StoreRoutingPlan(currentCluster, currentStoreDef);\n StoreDefinition finalStoreDef = StoreUtils.getStoreDef(finalStoreDefs,\n currentStoreDef.getName());\n StoreRoutingPlan finalSRP = new StoreRoutingPlan(finalCluster, finalStoreDef);\n\n // Only care about existing zones\n for(int zoneId: currentCluster.getZoneIds()) {\n int zonePrimariesCount = 0;\n int invalidMetadata = 0;\n\n // Examine nodes in current cluster in existing zone.\n for(int nodeId: currentCluster.getNodeIdsInZone(zoneId)) {\n // For every zone-primary in current cluster\n for(int zonePrimaryPartitionId: currentSRP.getZonePrimaryPartitionIds(nodeId)) {\n zonePrimariesCount++;\n // Determine if original zone-primary node is still some\n // form of n-ary in final cluster. If not,\n // InvalidMetadataException will fire.\n if(!finalSRP.getZoneNAryPartitionIds(nodeId)\n .contains(zonePrimaryPartitionId)) {\n invalidMetadata++;\n }\n }\n }\n float rate = invalidMetadata / (float) zonePrimariesCount;\n sb.append(\"\\tZone \" + zoneId)\n .append(\" : total zone primaries \" + zonePrimariesCount)\n .append(\", # that trigger invalid metadata \" + invalidMetadata)\n .append(\" => \" + rate)\n .append(Utils.NEWLINE);\n }\n }\n\n return sb.toString();\n }", "private static int findNext(boolean reverse, int pos) {\n boolean backwards = IS_BACKWARDS_CHECKBOX.isSelected();\n backwards = backwards ? !reverse : reverse;\n\n String pattern = (String) FIND_FIELD.getSelectedItem();\n if (pattern != null && pattern.length() > 0) {\n try {\n Document doc = textComponent.getDocument();\n doc.getText(0, doc.getLength(), SEGMENT);\n }\n catch (Exception e) {\n // should NEVER reach here\n e.printStackTrace();\n }\n\n pos += textComponent.getSelectedText() == null ?\n (backwards ? -1 : 1) : 0;\n\n char first = backwards ?\n pattern.charAt(pattern.length() - 1) : pattern.charAt(0);\n char oppFirst = Character.isUpperCase(first) ?\n Character.toLowerCase(first) : Character.toUpperCase(first);\n int start = pos;\n boolean wrapped = WRAP_SEARCH_CHECKBOX.isSelected();\n int end = backwards ? 0 : SEGMENT.getEndIndex();\n pos += backwards ? -1 : 1;\n\n int length = textComponent.getDocument().getLength();\n if (pos > length) {\n pos = wrapped ? 0 : length;\n }\n\n boolean found = false;\n while (!found && (backwards ? pos > end : pos < end)) {\n found = !MATCH_CASE_CHECKBOX.isSelected() && SEGMENT.array[pos] == oppFirst;\n found = found ? found : SEGMENT.array[pos] == first;\n\n if (found) {\n pos += backwards ? -(pattern.length() - 1) : 0;\n for (int i = 0; found && i < pattern.length(); i++) {\n char c = pattern.charAt(i);\n found = SEGMENT.array[pos + i] == c;\n if (!MATCH_CASE_CHECKBOX.isSelected() && !found) {\n c = Character.isUpperCase(c) ?\n Character.toLowerCase(c) :\n Character.toUpperCase(c);\n found = SEGMENT.array[pos + i] == c;\n }\n }\n }\n\n if (!found) {\n pos += backwards ? -1 : 1;\n\n if (pos == end && wrapped) {\n pos = backwards ? SEGMENT.getEndIndex() : 0;\n end = start;\n wrapped = false;\n }\n }\n }\n pos = found ? pos : -1;\n }\n\n return pos;\n }", "public static final int findValueInListBox(ListBox list, String value) {\n\tfor (int i=0; i<list.getItemCount(); i++) {\n\t if (value.equals(list.getValue(i))) {\n\t\treturn i;\n\t }\n\t}\n\treturn -1;\n }", "public void process(DMatrixSparseCSC A , int parent[], int post[], int counts[] ) {\n if( counts.length < A.numCols )\n throw new IllegalArgumentException(\"counts must be at least of length A.numCols\");\n\n initialize(A);\n\n int delta[] = counts;\n findFirstDescendant(parent, post, delta);\n\n if( ata ) {\n init_ata(post);\n }\n for (int i = 0; i < n; i++)\n w[ancestor+i] = i;\n\n int[] ATp = At.col_idx; int []ATi = At.nz_rows;\n\n for (int k = 0; k < n; k++) {\n int j = post[k];\n if( parent[j] != -1 )\n delta[parent[j]]--; // j is not a root\n for (int J = HEAD(k,j); J != -1; J = NEXT(J)) {\n for (int p = ATp[J]; p < ATp[J+1]; p++) {\n int i = ATi[p];\n int q = isLeaf(i,j);\n if( jleaf >= 1)\n delta[j]++;\n if( jleaf == 2 )\n delta[q]--;\n }\n }\n if( parent[j] != -1 )\n w[ancestor+j] = parent[j];\n }\n\n // sum up delta's of each child\n for ( int j = 0; j < n; j++) {\n if( parent[j] != -1)\n counts[parent[j]] += counts[j];\n }\n }" ]
Retrieve the default mapping between MPXJ assignment fields and Primavera assignment field names. @return mapping
[ "public static Map<FieldType, String> getDefaultAssignmentFieldMap()\n {\n Map<FieldType, String> map = new LinkedHashMap<FieldType, String>();\n\n map.put(AssignmentField.UNIQUE_ID, \"taskrsrc_id\");\n map.put(AssignmentField.GUID, \"guid\");\n map.put(AssignmentField.REMAINING_WORK, \"remain_qty\");\n map.put(AssignmentField.BASELINE_WORK, \"target_qty\");\n map.put(AssignmentField.ACTUAL_OVERTIME_WORK, \"act_ot_qty\");\n map.put(AssignmentField.BASELINE_COST, \"target_cost\");\n map.put(AssignmentField.ACTUAL_OVERTIME_COST, \"act_ot_cost\");\n map.put(AssignmentField.REMAINING_COST, \"remain_cost\");\n map.put(AssignmentField.ACTUAL_START, \"act_start_date\");\n map.put(AssignmentField.ACTUAL_FINISH, \"act_end_date\");\n map.put(AssignmentField.BASELINE_START, \"target_start_date\");\n map.put(AssignmentField.BASELINE_FINISH, \"target_end_date\");\n map.put(AssignmentField.ASSIGNMENT_DELAY, \"target_lag_drtn_hr_cnt\");\n\n return map;\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 }", "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 }", "@PostConstruct\n public void initDatabase() {\n MongoDBInit.LOGGER.info(\"initializing MongoDB\");\n String dbName = System.getProperty(\"mongodb.name\");\n if (dbName == null) {\n throw new RuntimeException(\"Missing database name; Set system property 'mongodb.name'\");\n }\n MongoDatabase db = this.mongo.getDatabase(dbName);\n\n try {\n PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();\n Resource[] resources = resolver.getResources(\"classpath*:mongodb/*.ndjson\");\n MongoDBInit.LOGGER.info(\"Scanning for collection data\");\n for (Resource res : resources) {\n String filename = res.getFilename();\n String collection = filename.substring(0, filename.length() - 7);\n MongoDBInit.LOGGER.info(\"Found collection file: {}\", collection);\n MongoCollection<DBObject> dbCollection = db.getCollection(collection, DBObject.class);\n try (Scanner scan = new Scanner(res.getInputStream(), \"UTF-8\")) {\n int lines = 0;\n while (scan.hasNextLine()) {\n String json = scan.nextLine();\n Object parse = JSON.parse(json);\n if (parse instanceof DBObject) {\n DBObject dbObject = (DBObject) parse;\n dbCollection.insertOne(dbObject);\n } else {\n MongoDBInit.LOGGER.error(\"Invalid object found: {}\", parse);\n throw new RuntimeException(\"Invalid object\");\n }\n lines++;\n }\n MongoDBInit.LOGGER.info(\"Imported {} objects into collection {}\", lines, collection);\n }\n }\n } catch (IOException e) {\n throw new RuntimeException(\"Error importing objects\", e);\n }\n }", "public static base_responses update(nitro_service client, nspbr6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnspbr6 updateresources[] = new nspbr6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nspbr6();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].action = resources[i].action;\n\t\t\t\tupdateresources[i].srcipv6 = resources[i].srcipv6;\n\t\t\t\tupdateresources[i].srcipop = resources[i].srcipop;\n\t\t\t\tupdateresources[i].srcipv6val = resources[i].srcipv6val;\n\t\t\t\tupdateresources[i].srcport = resources[i].srcport;\n\t\t\t\tupdateresources[i].srcportop = resources[i].srcportop;\n\t\t\t\tupdateresources[i].srcportval = resources[i].srcportval;\n\t\t\t\tupdateresources[i].destipv6 = resources[i].destipv6;\n\t\t\t\tupdateresources[i].destipop = resources[i].destipop;\n\t\t\t\tupdateresources[i].destipv6val = resources[i].destipv6val;\n\t\t\t\tupdateresources[i].destport = resources[i].destport;\n\t\t\t\tupdateresources[i].destportop = resources[i].destportop;\n\t\t\t\tupdateresources[i].destportval = resources[i].destportval;\n\t\t\t\tupdateresources[i].srcmac = resources[i].srcmac;\n\t\t\t\tupdateresources[i].protocol = resources[i].protocol;\n\t\t\t\tupdateresources[i].protocolnumber = resources[i].protocolnumber;\n\t\t\t\tupdateresources[i].vlan = resources[i].vlan;\n\t\t\t\tupdateresources[i].Interface = resources[i].Interface;\n\t\t\t\tupdateresources[i].priority = resources[i].priority;\n\t\t\t\tupdateresources[i].msr = resources[i].msr;\n\t\t\t\tupdateresources[i].monitor = resources[i].monitor;\n\t\t\t\tupdateresources[i].nexthop = resources[i].nexthop;\n\t\t\t\tupdateresources[i].nexthopval = resources[i].nexthopval;\n\t\t\t\tupdateresources[i].nexthopvlan = resources[i].nexthopvlan;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "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 setAttribute(final String name, final Attribute attribute) {\n if (name.equals(MAP_KEY)) {\n this.mapAttribute = (MapAttribute) attribute;\n }\n }", "private void readBitFields(MppBitFlag[] flags, FieldContainer container, byte[] data)\n {\n for (MppBitFlag flag : flags)\n {\n flag.setValue(container, data);\n }\n }", "public static double[] toDouble(int[] array) {\n double[] n = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n n[i] = (double) array[i];\n }\n return n;\n }", "public static ConstraintType getInstance(Locale locale, String type)\n {\n int index = 0;\n\n String[] constraintTypes = LocaleData.getStringArray(locale, LocaleData.CONSTRAINT_TYPES);\n for (int loop = 0; loop < constraintTypes.length; loop++)\n {\n if (constraintTypes[loop].equalsIgnoreCase(type) == true)\n {\n index = loop;\n break;\n }\n }\n\n return (ConstraintType.getInstance(index));\n }" ]
If you register a CustomExpression with the name "customExpName", then this will create the text needed to invoke it in a JRDesignExpression @param customExpName @param usePreviousFieldValues @return
[ "public static String createCustomExpressionInvocationText(CustomExpression customExpression, String customExpName, boolean usePreviousFieldValues) {\n String stringExpression;\n if (customExpression instanceof DJSimpleExpression) {\n DJSimpleExpression varexp = (DJSimpleExpression) customExpression;\n String symbol;\n switch (varexp.getType()) {\n case DJSimpleExpression.TYPE_FIELD:\n symbol = \"F\";\n break;\n case DJSimpleExpression.TYPE_VARIABLE:\n symbol = \"V\";\n break;\n case DJSimpleExpression.TYPE_PARAMATER:\n symbol = \"P\";\n break;\n default:\n throw new DJException(\"Invalid DJSimpleExpression, type must be FIELD, VARIABLE or PARAMETER\");\n }\n stringExpression = \"$\" + symbol + \"{\" + varexp.getVariableName() + \"}\";\n\n } else {\n String fieldsMap = \"((\" + DJDefaultScriptlet.class.getName() + \")$P{REPORT_SCRIPTLET}).getCurrentFields()\";\n if (usePreviousFieldValues) {\n fieldsMap = \"((\" + DJDefaultScriptlet.class.getName() + \")$P{REPORT_SCRIPTLET}).getPreviousFields()\";\n }\n\n String parametersMap = \"((\" + DJDefaultScriptlet.class.getName() + \")$P{REPORT_SCRIPTLET}).getCurrentParams()\";\n String variablesMap = \"((\" + DJDefaultScriptlet.class.getName() + \")$P{REPORT_SCRIPTLET}).getCurrentVariables()\";\n\n stringExpression = \"((\" + CustomExpression.class.getName() + \")$P{REPORT_PARAMETERS_MAP}.get(\\\"\" + customExpName + \"\\\")).\"\n + CustomExpression.EVAL_METHOD_NAME + \"( \" + fieldsMap + \", \" + variablesMap + \", \" + parametersMap + \" )\";\n }\n\n return stringExpression;\n }" ]
[ "public JsonNode wbSetClaim(String statement,\n\t\t\tboolean bot, long baserevid, String summary)\n\t\t\t\t\tthrows IOException, MediaWikiApiErrorException {\n\t\tValidate.notNull(statement,\n\t\t\t\t\"Statement parameter cannot be null when adding or changing a statement\");\n\t\t\n\t\t\n\t\tMap<String, String> parameters = new HashMap<String, String>();\n\t\tparameters.put(\"claim\", statement);\n\t\t\n\t\treturn performAPIAction(\"wbsetclaim\", null, null, null, null, parameters, summary, baserevid, bot);\n\t}", "final void waitForSizeQueue(final int queueSize) {\n synchronized (this.queue) {\n while (this.queue.size() > queueSize) {\n try {\n this.queue.wait(250L);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n }\n try {\n Thread.sleep(500L);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n this.queue.notifyAll();\n }\n }", "protected boolean computeOffset(CacheDataSet cache) {\n // offset computation: update offset for all items in the cache\n float startDataOffset = getStartingOffset((cache.getTotalSizeWithPadding()));\n float layoutOffset = getLayoutOffset();\n\n boolean inBounds = startDataOffset < -layoutOffset;\n\n for (int pos = 0; pos < cache.count(); ++pos) {\n int id = cache.getId(pos);\n if (id != -1) {\n float endDataOffset = cache.setDataAfter(id, startDataOffset);\n inBounds = inBounds &&\n endDataOffset > layoutOffset &&\n startDataOffset < -layoutOffset;\n startDataOffset = endDataOffset;\n Log.d(LAYOUT, TAG, \"computeOffset [%d] = %f\" , id, cache.getDataOffset(id));\n }\n }\n\n return inBounds;\n }", "@Override\n public List<Integer> getReplicatingPartitionList(int index) {\n List<Node> preferenceNodesList = new ArrayList<Node>(getNumReplicas());\n List<Integer> replicationPartitionsList = new ArrayList<Integer>(getNumReplicas());\n\n // Copy Zone based Replication Factor\n HashMap<Integer, Integer> requiredRepFactor = new HashMap<Integer, Integer>();\n requiredRepFactor.putAll(zoneReplicationFactor);\n\n // Cross-check if individual zone replication factor equals global\n int sum = 0;\n for(Integer zoneRepFactor: requiredRepFactor.values()) {\n sum += zoneRepFactor;\n }\n\n if(sum != getNumReplicas())\n throw new IllegalArgumentException(\"Number of zone replicas is not equal to the total replication factor\");\n\n if(getPartitionToNode().length == 0) {\n return new ArrayList<Integer>(0);\n }\n\n for(int i = 0; i < getPartitionToNode().length; i++) {\n // add this one if we haven't already, and it can satisfy some zone\n // replicationFactor\n Node currentNode = getNodeByPartition(index);\n if(!preferenceNodesList.contains(currentNode)) {\n preferenceNodesList.add(currentNode);\n if(checkZoneRequirement(requiredRepFactor, currentNode.getZoneId()))\n replicationPartitionsList.add(index);\n }\n\n // if we have enough, go home\n if(replicationPartitionsList.size() >= getNumReplicas())\n return replicationPartitionsList;\n // move to next clockwise slot on the ring\n index = (index + 1) % getPartitionToNode().length;\n }\n\n // we don't have enough, but that may be okay\n return replicationPartitionsList;\n }", "public Set<String> getSupportedUriSchemes() {\n Set<String> schemes = new HashSet<>();\n\n for (ConfigFileLoaderPlugin loaderPlugin: this.getLoaderPlugins()) {\n schemes.add(loaderPlugin.getUriScheme());\n }\n\n return schemes;\n }", "@Override\n public Symmetry454Date date(int prolepticYear, int month, int dayOfMonth) {\n return Symmetry454Date.of(prolepticYear, month, dayOfMonth);\n }", "public static String addFolderSlashIfNeeded(String folderName) {\n if (!\"\".equals(folderName) && !folderName.endsWith(\"/\")) {\n return folderName + \"/\";\n } else {\n return folderName;\n }\n }", "@UiHandler(\"m_wholeDayCheckBox\")\n void onWholeDayChange(ValueChangeEvent<Boolean> event) {\n\n //TODO: Improve - adjust time selections?\n if (handleChange()) {\n m_controller.setWholeDay(event.getValue());\n }\n }", "public RedwoodConfiguration clear(){\r\n tasks = new LinkedList<Runnable>();\r\n tasks.add(new Runnable(){ public void run(){\r\n Redwood.clearHandlers();\r\n Redwood.restoreSystemStreams();\r\n Redwood.clearLoggingClasses();\r\n } });\r\n return this;\r\n }" ]
Format event to string buffer. @param sbuf string buffer to receive formatted event, may not be null. @param event event to format, may not be null.
[ "@Override\n\tpublic void format(final StringBuffer sbuf, final LoggingEvent event) {\n\t\tfor (int i = 0; i < patternConverters.length; i++) {\n\t\t\tfinal int startField = sbuf.length();\n\t\t\tpatternConverters[i].format(event, sbuf);\n\t\t\tpatternFields[i].format(startField, sbuf);\n\t\t}\n\t}" ]
[ "@VisibleForTesting\n public static void runMain(final String[] args) throws Exception {\n final CliHelpDefinition helpCli = new CliHelpDefinition();\n\n try {\n Args.parse(helpCli, args);\n if (helpCli.help) {\n printUsage(0);\n return;\n }\n } catch (IllegalArgumentException invalidOption) {\n // Ignore because it is probably one of the non-help options.\n }\n\n final CliDefinition cli = new CliDefinition();\n try {\n List<String> unusedArguments = Args.parse(cli, args);\n\n if (!unusedArguments.isEmpty()) {\n System.out.println(\"\\n\\nThe following arguments are not recognized: \" + unusedArguments);\n printUsage(1);\n return;\n }\n } catch (IllegalArgumentException invalidOption) {\n System.out.println(\"\\n\\n\" + invalidOption.getMessage());\n printUsage(1);\n return;\n }\n configureLogs(cli.verbose);\n\n AbstractXmlApplicationContext context = new ClassPathXmlApplicationContext(DEFAULT_SPRING_CONTEXT);\n\n if (cli.springConfig != null) {\n context = new ClassPathXmlApplicationContext(DEFAULT_SPRING_CONTEXT, cli.springConfig);\n }\n try {\n context.getBean(Main.class).run(cli);\n } finally {\n context.close();\n }\n }", "public static base_responses add(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 addresources[] = new nsip6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new nsip6();\n\t\t\t\taddresources[i].ipv6address = resources[i].ipv6address;\n\t\t\t\taddresources[i].scope = resources[i].scope;\n\t\t\t\taddresources[i].type = resources[i].type;\n\t\t\t\taddresources[i].vlan = resources[i].vlan;\n\t\t\t\taddresources[i].nd = resources[i].nd;\n\t\t\t\taddresources[i].icmp = resources[i].icmp;\n\t\t\t\taddresources[i].vserver = resources[i].vserver;\n\t\t\t\taddresources[i].telnet = resources[i].telnet;\n\t\t\t\taddresources[i].ftp = resources[i].ftp;\n\t\t\t\taddresources[i].gui = resources[i].gui;\n\t\t\t\taddresources[i].ssh = resources[i].ssh;\n\t\t\t\taddresources[i].snmp = resources[i].snmp;\n\t\t\t\taddresources[i].mgmtaccess = resources[i].mgmtaccess;\n\t\t\t\taddresources[i].restrictaccess = resources[i].restrictaccess;\n\t\t\t\taddresources[i].dynamicrouting = resources[i].dynamicrouting;\n\t\t\t\taddresources[i].hostroute = resources[i].hostroute;\n\t\t\t\taddresources[i].ip6hostrtgw = resources[i].ip6hostrtgw;\n\t\t\t\taddresources[i].metric = resources[i].metric;\n\t\t\t\taddresources[i].vserverrhilevel = resources[i].vserverrhilevel;\n\t\t\t\taddresources[i].ospf6lsatype = resources[i].ospf6lsatype;\n\t\t\t\taddresources[i].ospfarea = resources[i].ospfarea;\n\t\t\t\taddresources[i].state = resources[i].state;\n\t\t\t\taddresources[i].map = resources[i].map;\n\t\t\t\taddresources[i].ownernode = resources[i].ownernode;\n\t\t\t\taddresources[i].td = resources[i].td;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public ConfigOptionBuilder setCommandLineOptionWithoutArgument( CommandLineOption commandLineOption, Object value ) {\n co.setCommandLineOption( commandLineOption );\n co.setValue( value );\n return this;\n }", "public BoxFile.Info uploadLargeFile(InputStream inputStream, String fileName, long fileSize)\n throws InterruptedException, IOException {\n URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL());\n return new LargeFileUpload().\n upload(this.getAPI(), this.getID(), inputStream, url, fileName, fileSize);\n }", "private String getDateString(Date value)\n {\n Calendar cal = DateHelper.popCalendar(value);\n int year = cal.get(Calendar.YEAR);\n int month = cal.get(Calendar.MONTH) + 1;\n int day = cal.get(Calendar.DAY_OF_MONTH);\n DateHelper.pushCalendar(cal);\n \n StringBuilder sb = new StringBuilder(8);\n sb.append(m_fourDigitFormat.format(year));\n sb.append(m_twoDigitFormat.format(month));\n sb.append(m_twoDigitFormat.format(day));\n\n return (sb.toString());\n }", "public void add(ResourceCollection rc) {\n if (rc instanceof FileSet) {\n FileSet fs = (FileSet) rc;\n fs.setProject(getProject());\n }\n resources.add(rc);\n }", "public static List<Expression> getVariableExpressions(DeclarationExpression declarationExpression) {\r\n Expression leftExpression = declarationExpression.getLeftExpression();\r\n\r\n // !important: performance enhancement\r\n if (leftExpression instanceof ArrayExpression) {\r\n List<Expression> expressions = ((ArrayExpression) leftExpression).getExpressions();\r\n return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions;\r\n } else if (leftExpression instanceof ListExpression) {\r\n List<Expression> expressions = ((ListExpression) leftExpression).getExpressions();\r\n return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions;\r\n } else if (leftExpression instanceof TupleExpression) {\r\n List<Expression> expressions = ((TupleExpression) leftExpression).getExpressions();\r\n return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions;\r\n } else if (leftExpression instanceof VariableExpression) {\r\n return Arrays.asList(leftExpression);\r\n }\r\n // todo: write warning\r\n return Collections.emptyList();\r\n }", "public static ComplexNumber Subtract(ComplexNumber z1, double scalar) {\r\n return new ComplexNumber(z1.real - scalar, z1.imaginary);\r\n }", "public static base_response update(nitro_service client, vpnclientlessaccesspolicy resource) throws Exception {\n\t\tvpnclientlessaccesspolicy updateresource = new vpnclientlessaccesspolicy();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.rule = resource.rule;\n\t\tupdateresource.profilename = resource.profilename;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
Checks if there's exactly one option that exists among all opts. @param options OptionSet to checked @param opts List of options to be checked @throws VoldemortException
[ "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 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 }", "@Subscribe\n @SuppressForbidden(\"legitimate printStackTrace().\")\n public void onSuiteResult(AggregatedSuiteResultEvent e) {\n try {\n if (jsonWriter == null)\n return;\n\n slaves.put(e.getSlave().id, e.getSlave());\n e.serialize(jsonWriter, outputStreams);\n } catch (Exception ex) {\n ex.printStackTrace();\n junit4.log(\"Error serializing to JSON file: \"\n + Throwables.getStackTraceAsString(ex), Project.MSG_WARN);\n if (jsonWriter != null) {\n try {\n jsonWriter.close();\n } catch (Throwable ignored) {\n // Ignore.\n } finally {\n jsonWriter = null;\n }\n }\n }\n }", "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 }", "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 }", "public int delete(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException {\n\t\tif (mappedDelete == null) {\n\t\t\tmappedDelete = MappedDelete.build(dao, tableInfo);\n\t\t}\n\t\tint result = mappedDelete.delete(databaseConnection, data, objectCache);\n\t\tif (dao != null && !localIsInBatchMode.get()) {\n\t\t\tdao.notifyChanges();\n\t\t}\n\t\treturn result;\n\t}", "public static base_response add(nitro_service client, inat resource) throws Exception {\n\t\tinat addresource = new inat();\n\t\taddresource.name = resource.name;\n\t\taddresource.publicip = resource.publicip;\n\t\taddresource.privateip = resource.privateip;\n\t\taddresource.tcpproxy = resource.tcpproxy;\n\t\taddresource.ftp = resource.ftp;\n\t\taddresource.tftp = resource.tftp;\n\t\taddresource.usip = resource.usip;\n\t\taddresource.usnip = resource.usnip;\n\t\taddresource.proxyip = resource.proxyip;\n\t\taddresource.mode = resource.mode;\n\t\taddresource.td = resource.td;\n\t\treturn addresource.add_resource(client);\n\t}", "public Map<String, String> getSitePath() {\n\n if (m_sitePaths == null) {\n m_sitePaths = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n public Object transform(Object rootPath) {\n\n if (rootPath instanceof String) {\n return getRequestContext().removeSiteRoot((String)rootPath);\n }\n return null;\n }\n });\n }\n return m_sitePaths;\n }", "static int excessArgumentsMatchesVargsParameter(Parameter[] params, ClassNode[] args) {\n // we already know parameter length is bigger zero and last is a vargs\n // the excess arguments are all put in an array for the vargs call\n // so check against the component type\n int dist = 0;\n ClassNode vargsBase = params[params.length - 1].getType().getComponentType();\n for (int i = params.length; i < args.length; i++) {\n if (!isAssignableTo(args[i],vargsBase)) return -1;\n else if (!args[i].equals(vargsBase)) dist+=getDistance(args[i], vargsBase);\n }\n return dist;\n }", "public static <R extends Resource<?>, U extends PaginatedResponse<R>> Flux<R> getResources(U response) {\n return Flux.fromIterable(response.getResources());\n }" ]
Process a module or bundle root. @param root the root @param layers the processed layers @param setter the bundle or module path setter @throws IOException
[ "static void processRoot(final File root, final ProcessedLayers layers, final LayerPathSetter setter) throws IOException {\n final LayersConfig layersConfig = LayersConfig.getLayersConfig(root);\n // Process layers\n final File layersDir = new File(root, layersConfig.getLayersPath());\n if (!layersDir.exists()) {\n if (layersConfig.isConfigured()) {\n // Bad config from user\n throw PatchLogger.ROOT_LOGGER.installationNoLayersConfigFound(layersDir.getAbsolutePath());\n }\n // else this isn't a root that has layers and add-ons\n } else {\n // check for a valid layer configuration\n for (final String layer : layersConfig.getLayers()) {\n File layerDir = new File(layersDir, layer);\n if (!layerDir.exists()) {\n if (layersConfig.isConfigured()) {\n // Bad config from user\n throw PatchLogger.ROOT_LOGGER.installationMissingLayer(layer, layersDir.getAbsolutePath());\n }\n // else this isn't a standard layers and add-ons structure\n return;\n }\n layers.addLayer(layer, layerDir, setter);\n }\n }\n // Finally process the add-ons\n final File addOnsDir = new File(root, layersConfig.getAddOnsPath());\n final File[] addOnsList = addOnsDir.listFiles();\n if (addOnsList != null) {\n for (final File addOn : addOnsList) {\n layers.addAddOn(addOn.getName(), addOn, setter);\n }\n }\n }" ]
[ "public static String[] allUpperCase(String... strings){\n\t\tString[] tmp = new String[strings.length];\n\t\tfor(int idx=0;idx<strings.length;idx++){\n\t\t\tif(strings[idx] != null){\n\t\t\t\ttmp[idx] = strings[idx].toUpperCase();\n\t\t\t}\n\t\t}\n\t\treturn tmp;\n\t}", "public static Collection<String> getKnownPGPSecureRingLocations() {\n final LinkedHashSet<String> locations = new LinkedHashSet<String>();\n\n final String os = System.getProperty(\"os.name\");\n final boolean runOnWindows = os == null || os.toLowerCase().contains(\"win\");\n\n if (runOnWindows) {\n // The user's roaming profile on Windows, via environment\n final String windowsRoaming = System.getenv(\"APPDATA\");\n if (windowsRoaming != null) {\n locations.add(joinLocalPath(windowsRoaming, \"gnupg\", \"secring.gpg\"));\n }\n\n // The user's local profile on Windows, via environment\n final String windowsLocal = System.getenv(\"LOCALAPPDATA\");\n if (windowsLocal != null) {\n locations.add(joinLocalPath(windowsLocal, \"gnupg\", \"secring.gpg\"));\n }\n\n // The Windows installation directory\n final String windir = System.getProperty(\"WINDIR\");\n if (windir != null) {\n // Local Profile on Windows 98 and ME\n locations.add(joinLocalPath(windir, \"Application Data\", \"gnupg\", \"secring.gpg\"));\n }\n }\n\n final String home = System.getProperty(\"user.home\");\n\n if (home != null && runOnWindows) {\n // These are for various flavours of Windows\n // if the environment variables above have failed\n\n // Roaming profile on Vista and later\n locations.add(joinLocalPath(home, \"AppData\", \"Roaming\", \"gnupg\", \"secring.gpg\"));\n // Local profile on Vista and later\n locations.add(joinLocalPath(home, \"AppData\", \"Local\", \"gnupg\", \"secring.gpg\"));\n // Roaming profile on 2000 and XP\n locations.add(joinLocalPath(home, \"Application Data\", \"gnupg\", \"secring.gpg\"));\n // Local profile on 2000 and XP\n locations.add(joinLocalPath(home, \"Local Settings\", \"Application Data\", \"gnupg\", \"secring.gpg\"));\n }\n\n // *nix, including OS X\n if (home != null) {\n locations.add(joinLocalPath(home, \".gnupg\", \"secring.gpg\"));\n }\n\n return locations;\n }", "public static rewriteglobal_binding get(nitro_service service) throws Exception{\n\t\trewriteglobal_binding obj = new rewriteglobal_binding();\n\t\trewriteglobal_binding response = (rewriteglobal_binding) 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 }", "private static void parseRessource(ArrayList<Shape> shapes,\n HashMap<String, JSONObject> flatJSON,\n String resourceId,\n Boolean keepGlossaryLink)\n throws JSONException {\n JSONObject modelJSON = flatJSON.get(resourceId);\n Shape current = getShapeWithId(modelJSON.getString(\"resourceId\"),\n shapes);\n\n parseStencil(modelJSON,\n current);\n\n parseProperties(modelJSON,\n current,\n keepGlossaryLink);\n parseOutgoings(shapes,\n modelJSON,\n current);\n parseChildShapes(shapes,\n modelJSON,\n current);\n parseDockers(modelJSON,\n current);\n parseBounds(modelJSON,\n current);\n parseTarget(shapes,\n modelJSON,\n current);\n }", "public DockerContainerObjectBuilder<T> withContainerObjectClass(Class<T> containerObjectClass) {\n if (containerObjectClass == null) {\n throw new IllegalArgumentException(\"container object class cannot be null\");\n }\n this.containerObjectClass = containerObjectClass;\n\n //First we check if this ContainerObject is defining a @CubeDockerFile in static method\n final List<Method> methodsWithCubeDockerFile =\n ReflectionUtil.getMethodsWithAnnotation(containerObjectClass, CubeDockerFile.class);\n\n if (methodsWithCubeDockerFile.size() > 1) {\n throw new IllegalArgumentException(\n String.format(\n \"More than one %s annotation found and only one was expected. Methods where annotation was found are: %s\",\n CubeDockerFile.class.getSimpleName(), methodsWithCubeDockerFile));\n }\n\n classHasMethodWithCubeDockerFile = !methodsWithCubeDockerFile.isEmpty();\n classDefinesCubeDockerFile = containerObjectClass.isAnnotationPresent(CubeDockerFile.class);\n classDefinesImage = containerObjectClass.isAnnotationPresent(Image.class);\n\n if (classHasMethodWithCubeDockerFile) {\n methodWithCubeDockerFile = methodsWithCubeDockerFile.get(0);\n boolean isMethodStatic = Modifier.isStatic(methodWithCubeDockerFile.getModifiers());\n boolean methodHasNoArguments = methodWithCubeDockerFile.getParameterCount() == 0;\n boolean methodReturnsAnArchive = Archive.class.isAssignableFrom(methodWithCubeDockerFile.getReturnType());\n if (!isMethodStatic || !methodHasNoArguments || !methodReturnsAnArchive) {\n throw new IllegalArgumentException(\n String.format(\"Method %s annotated with %s is expected to be static, no args and return %s.\",\n methodWithCubeDockerFile, CubeDockerFile.class.getSimpleName(), Archive.class.getSimpleName()));\n }\n }\n\n // User has defined @CubeDockerfile on the class and a method\n if (classHasMethodWithCubeDockerFile && classDefinesCubeDockerFile) {\n throw new IllegalArgumentException(\n String.format(\n \"More than one %s annotation found and only one was expected. Both class and method %s has the annotation.\",\n CubeDockerFile.class.getSimpleName(), methodWithCubeDockerFile));\n }\n\n // User has defined @CubeDockerfile and @Image\n if ((classHasMethodWithCubeDockerFile || classDefinesCubeDockerFile) && classDefinesImage) {\n throw new IllegalArgumentException(\n String.format(\"Container Object %s has defined %s annotation and %s annotation together.\",\n containerObjectClass.getSimpleName(), Image.class.getSimpleName(),\n CubeDockerFile.class.getSimpleName()));\n }\n\n // User has not defined either @CubeDockerfile or @Image\n if (!classDefinesCubeDockerFile && !classDefinesImage && !classHasMethodWithCubeDockerFile) {\n throw new IllegalArgumentException(\n String.format(\"Container Object %s is not annotated with either %s or %s annotations.\",\n containerObjectClass.getName(), CubeDockerFile.class.getSimpleName(), Image.class.getSimpleName()));\n }\n\n return this;\n }", "private static TransportType map2TransportType(String transportId) {\n TransportType type;\n if (CXF_HTTP_TRANSPORT_ID.equals(transportId) || SOAP_HTTP_TRANSPORT_ID.equals(transportId)) {\n type = TransportType.HTTP;\n } else {\n type = TransportType.OTHER;\n }\n return type;\n }", "public static base_responses unset(nitro_service client, bridgetable resources[], String[] args) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tbridgetable unsetresources[] = new bridgetable[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tunsetresources[i] = new bridgetable();\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}", "private List<DumpProcessingAction> handleArguments(String[] args) {\n\t\tCommandLine cmd;\n\t\tCommandLineParser parser = new GnuParser();\n\n\t\ttry {\n\t\t\tcmd = parser.parse(options, args);\n\t\t} catch (ParseException e) {\n\t\t\tlogger.error(\"Failed to parse arguments: \" + e.getMessage());\n\t\t\treturn Collections.emptyList();\n\t\t}\n\n\t\t// Stop processing if a help text is to be printed:\n\t\tif ((cmd.hasOption(CMD_OPTION_HELP)) || (args.length == 0)) {\n\t\t\treturn Collections.emptyList();\n\t\t}\n\n\t\tList<DumpProcessingAction> configuration = new ArrayList<>();\n\n\t\thandleGlobalArguments(cmd);\n\n\t\tif (cmd.hasOption(CMD_OPTION_ACTION)) {\n\t\t\tDumpProcessingAction action = handleActionArguments(cmd);\n\t\t\tif (action != null) {\n\t\t\t\tconfiguration.add(action);\n\t\t\t}\n\t\t}\n\n\t\tif (cmd.hasOption(CMD_OPTION_CONFIG_FILE)) {\n\t\t\ttry {\n\t\t\t\tList<DumpProcessingAction> configFile = readConfigFile(cmd\n\t\t\t\t\t\t.getOptionValue(CMD_OPTION_CONFIG_FILE));\n\t\t\t\tconfiguration.addAll(configFile);\n\t\t\t} catch (IOException e) {\n\t\t\t\tlogger.error(\"Failed to read configuration file \\\"\"\n\t\t\t\t\t\t+ cmd.getOptionValue(CMD_OPTION_CONFIG_FILE) + \"\\\": \"\n\t\t\t\t\t\t+ e.toString());\n\t\t\t}\n\n\t\t}\n\n\t\treturn configuration;\n\n\t}" ]
Old SOAP client uses new SOAP service with the redirection to the new endpoint and transformation on the server side
[ "public void useNewSOAPServiceWithOldClientAndRedirection() throws Exception {\n URL wsdlURL = getClass().getResource(\"/CustomerService.wsdl\");\n com.example.customerservice.CustomerServiceService service = \n new com.example.customerservice.CustomerServiceService(wsdlURL);\n \n com.example.customerservice.CustomerService customerService = \n service.getCustomerServiceRedirectPort();\n\n System.out.println(\"Using new SOAP CustomerService with old client and the redirection\");\n \n customer.v1.Customer customer = createOldCustomer(\"Barry Old to New SOAP With Redirection\");\n customerService.updateCustomer(customer);\n customer = customerService.getCustomerByName(\"Barry Old to New SOAP With Redirection\");\n printOldCustomerDetails(customer);\n }" ]
[ "private void setRecordNumber(LinkedList<String> list)\n {\n try\n {\n String number = list.remove(0);\n m_recordNumber = Integer.valueOf(number);\n }\n catch (NumberFormatException ex)\n {\n // Malformed MPX file: the record number isn't a valid integer\n // Catch the exception here, leaving m_recordNumber as null\n // so we will skip this record entirely.\n }\n }", "public static <T> T splitEachLine(File self, String regex, @ClosureParams(value=SimpleType.class, options=\"java.lang.String[]\") Closure<T> closure) throws IOException {\n return IOGroovyMethods.splitEachLine(newReader(self), regex, closure);\n }", "private void addWSAddressingInterceptors(InterceptorProvider provider) {\n MAPAggregator mapAggregator = new MAPAggregator();\n MAPCodec mapCodec = new MAPCodec();\n\n provider.getInInterceptors().add(mapAggregator);\n provider.getInInterceptors().add(mapCodec);\n\n provider.getOutInterceptors().add(mapAggregator);\n provider.getOutInterceptors().add(mapCodec);\n\n provider.getInFaultInterceptors().add(mapAggregator);\n provider.getInFaultInterceptors().add(mapCodec);\n\n provider.getOutFaultInterceptors().add(mapAggregator);\n provider.getOutFaultInterceptors().add(mapCodec);\n }", "@JsonProperty\n public String timestamp() {\n if (timestampAsText == null) {\n timestampAsText = DateTimeFormatter.ISO_INSTANT.format(timestamp);\n }\n return timestampAsText;\n }", "public <T extends CanvasWriter> T getWriter(Class<T> type, OauthToken oauthToken) {\n return getWriter(type, oauthToken, false);\n }", "private static int weekRange(int weekBasedYear) {\n LocalDate date = LocalDate.of(weekBasedYear, 1, 1);\n // 53 weeks if year starts on Thursday, or Wed in a leap year\n if (date.getDayOfWeek() == THURSDAY || (date.getDayOfWeek() == WEDNESDAY && date.isLeapYear())) {\n return 53;\n }\n return 52;\n }", "protected void reportProgress(String taskDecription) {\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.setTaskName(taskDecription);\n }\n }", "public static void main(String[] args) throws Exception {\r\n StringUtils.printErrInvocationString(\"CMMClassifier\", args);\r\n\r\n Properties props = StringUtils.argsToProperties(args);\r\n CMMClassifier cmm = new CMMClassifier<CoreLabel>(props);\r\n String testFile = cmm.flags.testFile;\r\n String textFile = cmm.flags.textFile;\r\n String loadPath = cmm.flags.loadClassifier;\r\n String serializeTo = cmm.flags.serializeTo;\r\n\r\n // cmm.crossValidateTrainAndTest(trainFile);\r\n if (loadPath != null) {\r\n cmm.loadClassifierNoExceptions(loadPath, props);\r\n } else if (cmm.flags.loadJarClassifier != null) {\r\n cmm.loadJarClassifier(cmm.flags.loadJarClassifier, props);\r\n } else if (cmm.flags.trainFile != null) {\r\n if (cmm.flags.biasedTrainFile != null) {\r\n cmm.trainSemiSup();\r\n } else {\r\n cmm.train();\r\n }\r\n } else {\r\n cmm.loadDefaultClassifier();\r\n }\r\n\r\n if (serializeTo != null) {\r\n cmm.serializeClassifier(serializeTo);\r\n }\r\n\r\n if (testFile != null) {\r\n cmm.classifyAndWriteAnswers(testFile, cmm.makeReaderAndWriter());\r\n } else if (cmm.flags.testFiles != null) {\r\n cmm.classifyAndWriteAnswers(cmm.flags.baseTestDir, cmm.flags.testFiles,\r\n cmm.makeReaderAndWriter());\r\n }\r\n\r\n if (textFile != null) {\r\n DocumentReaderAndWriter readerAndWriter =\r\n new PlainTextDocumentReaderAndWriter();\r\n cmm.classifyAndWriteAnswers(textFile, readerAndWriter);\r\n }\r\n }", "@SuppressWarnings(\"unchecked\") public Map<String, Object> getCustomProperties()\n {\n return (Map<String, Object>) getCachedValue(ProjectField.CUSTOM_PROPERTIES);\n }" ]
Determine if a CharSequence can be parsed as a BigDecimal. @param self a CharSequence @return true if the CharSequence can be parsed @see #isBigDecimal(String) @since 1.8.2
[ "public static boolean isBigDecimal(CharSequence self) {\n try {\n new BigDecimal(self.toString().trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n }" ]
[ "@SuppressWarnings(\"unchecked\")\n private static Object resolveConflictWithResolver(\n final ConflictHandler conflictResolver,\n final BsonValue documentId,\n final ChangeEvent localEvent,\n final ChangeEvent remoteEvent\n ) {\n return conflictResolver.resolveConflict(\n documentId,\n localEvent,\n remoteEvent);\n }", "@Override\n\tpublic CrawlSession call() {\n\t\tsetMaximumCrawlTimeIfNeeded();\n\t\tplugins.runPreCrawlingPlugins(config);\n\t\tCrawlTaskConsumer firstConsumer = consumerFactory.get();\n\t\tStateVertex firstState = firstConsumer.crawlIndex();\n\t\tcrawlSessionProvider.setup(firstState);\n\t\tplugins.runOnNewStatePlugins(firstConsumer.getContext(), firstState);\n\t\texecuteConsumers(firstConsumer);\n\t\treturn crawlSessionProvider.get();\n\t}", "public static <K, V, T> Map<K, List<Versioned<V>>> getAll(Store<K, V, T> storageEngine,\n Iterable<K> keys,\n Map<K, T> transforms) {\n Map<K, List<Versioned<V>>> result = newEmptyHashMap(keys);\n for(K key: keys) {\n List<Versioned<V>> value = storageEngine.get(key,\n transforms != null ? transforms.get(key)\n : null);\n if(!value.isEmpty())\n result.put(key, value);\n }\n return result;\n }", "@PostConstruct\n public void init() {\n //init Bus and LifeCycle listeners\n if (bus != null && sendLifecycleEvent ) {\n ServerLifeCycleManager slcm = bus.getExtension(ServerLifeCycleManager.class);\n if (null != slcm) {\n ServiceListenerImpl svrListener = new ServiceListenerImpl();\n svrListener.setSendLifecycleEvent(sendLifecycleEvent);\n svrListener.setQueue(queue);\n svrListener.setMonitoringServiceClient(monitoringServiceClient);\n slcm.registerListener(svrListener);\n }\n\n ClientLifeCycleManager clcm = bus.getExtension(ClientLifeCycleManager.class);\n if (null != clcm) {\n ClientListenerImpl cltListener = new ClientListenerImpl();\n cltListener.setSendLifecycleEvent(sendLifecycleEvent);\n cltListener.setQueue(queue);\n cltListener.setMonitoringServiceClient(monitoringServiceClient);\n clcm.registerListener(cltListener);\n }\n }\n\n if(executorQueueSize == 0) {\r\n \texecutor = Executors.newFixedThreadPool(this.executorPoolSize);\n }else{\r\n executor = new ThreadPoolExecutor(executorPoolSize, executorPoolSize, 0, TimeUnit.SECONDS, \r\n \t\tnew LinkedBlockingQueue<Runnable>(executorQueueSize), Executors.defaultThreadFactory(), \r\n \t\t\tnew RejectedExecutionHandlerImpl());\r\n }\r\n\n scheduler = new Timer();\n scheduler.scheduleAtFixedRate(new TimerTask() {\n public void run() {\n sendEventsFromQueue();\n }\n }, 0, getDefaultInterval());\n }", "public static float noise2(float x, float y) {\n int bx0, bx1, by0, by1, b00, b10, b01, b11;\n float rx0, rx1, ry0, ry1, q[], sx, sy, a, b, t, u, v;\n int i, j;\n\n if (start) {\n start = false;\n init();\n }\n\n t = x + N;\n bx0 = ((int)t) & BM;\n bx1 = (bx0+1) & BM;\n rx0 = t - (int)t;\n rx1 = rx0 - 1.0f;\n\n t = y + N;\n by0 = ((int)t) & BM;\n by1 = (by0+1) & BM;\n ry0 = t - (int)t;\n ry1 = ry0 - 1.0f;\n\n i = p[bx0];\n j = p[bx1];\n\n b00 = p[i + by0];\n b10 = p[j + by0];\n b01 = p[i + by1];\n b11 = p[j + by1];\n\n sx = sCurve(rx0);\n sy = sCurve(ry0);\n\n q = g2[b00]; u = rx0 * q[0] + ry0 * q[1];\n q = g2[b10]; v = rx1 * q[0] + ry0 * q[1];\n a = lerp(sx, u, v);\n\n q = g2[b01]; u = rx0 * q[0] + ry1 * q[1];\n q = g2[b11]; v = rx1 * q[0] + ry1 * q[1];\n b = lerp(sx, u, v);\n\n return 1.5f*lerp(sy, a, b);\n }", "public static 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 String getMessage(Locale locale) {\n\t\tif (getCause() != null) {\n\t\t\tString message = getShortMessage(locale) + \", \" + translate(\"ROOT_CAUSE\", locale) + \" \";\n\t\t\tif (getCause() instanceof GeomajasException) {\n\t\t\t\treturn message + ((GeomajasException) getCause()).getMessage(locale);\n\t\t\t}\n\t\t\treturn message + getCause().getMessage();\n\t\t} else {\n\t\t\treturn getShortMessage(locale);\n\t\t}\n\t}", "public static String getValue(Element element) {\r\n if (element != null) {\r\n Node dataNode = element.getFirstChild();\r\n if (dataNode != null) {\r\n return ((Text) dataNode).getData();\r\n }\r\n }\r\n return null;\r\n }", "public Duration getWork(Date startDate, Date endDate, TimeUnit format)\n {\n DateRange range = new DateRange(startDate, endDate);\n Long cachedResult = m_workingDateCache.get(range);\n long totalTime = 0;\n\n if (cachedResult == null)\n {\n //\n // We want the start date to be the earliest date, and the end date\n // to be the latest date. Set a flag here to indicate if we have swapped\n // the order of the supplied date.\n //\n boolean invert = false;\n if (startDate.getTime() > endDate.getTime())\n {\n invert = true;\n Date temp = startDate;\n startDate = endDate;\n endDate = temp;\n }\n\n Date canonicalStartDate = DateHelper.getDayStartDate(startDate);\n Date canonicalEndDate = DateHelper.getDayStartDate(endDate);\n\n if (canonicalStartDate.getTime() == canonicalEndDate.getTime())\n {\n ProjectCalendarDateRanges ranges = getRanges(startDate, null, null);\n if (ranges.getRangeCount() != 0)\n {\n totalTime = getTotalTime(ranges, startDate, endDate);\n }\n }\n else\n {\n //\n // Find the first working day in the range\n //\n Date currentDate = startDate;\n Calendar cal = Calendar.getInstance();\n cal.setTime(startDate);\n Day day = Day.getInstance(cal.get(Calendar.DAY_OF_WEEK));\n while (isWorkingDate(currentDate, day) == false && currentDate.getTime() < canonicalEndDate.getTime())\n {\n cal.add(Calendar.DAY_OF_YEAR, 1);\n currentDate = cal.getTime();\n day = day.getNextDay();\n }\n\n if (currentDate.getTime() < canonicalEndDate.getTime())\n {\n //\n // Calculate the amount of working time for this day\n //\n totalTime += getTotalTime(getRanges(currentDate, null, day), currentDate, true);\n\n //\n // Process each working day until we reach the last day\n //\n while (true)\n {\n cal.add(Calendar.DAY_OF_YEAR, 1);\n currentDate = cal.getTime();\n day = day.getNextDay();\n\n //\n // We have reached the last day\n //\n if (currentDate.getTime() >= canonicalEndDate.getTime())\n {\n break;\n }\n\n //\n // Skip this day if it has no working time\n //\n ProjectCalendarDateRanges ranges = getRanges(currentDate, null, day);\n if (ranges.getRangeCount() == 0)\n {\n continue;\n }\n\n //\n // Add the working time for the whole day\n //\n totalTime += getTotalTime(ranges);\n }\n }\n\n //\n // We are now at the last day\n //\n ProjectCalendarDateRanges ranges = getRanges(endDate, null, day);\n if (ranges.getRangeCount() != 0)\n {\n totalTime += getTotalTime(ranges, DateHelper.getDayStartDate(endDate), endDate);\n }\n }\n\n if (invert)\n {\n totalTime = -totalTime;\n }\n\n m_workingDateCache.put(range, Long.valueOf(totalTime));\n }\n else\n {\n totalTime = cachedResult.longValue();\n }\n\n return convertFormat(totalTime, format);\n }" ]
Returns a new instance of the given class, using the constructor with the specified parameter types. @param target The class to instantiate @param types The parameter types @param args The arguments @return The instance
[ "public static Object newInstance(Class target, Class[] types, Object[] args) throws InstantiationException,\r\n IllegalAccessException,\r\n IllegalArgumentException,\r\n InvocationTargetException,\r\n NoSuchMethodException,\r\n SecurityException\r\n {\r\n return newInstance(target, types, args, false);\r\n }" ]
[ "void stop() {\n try {\n dm.stop(getBundleContext());\n } catch (DirectoryMonitoringException e) {\n LOG.error(\"Failed to stop \" + DirectoryMonitor.class.getName() + \" for the directory \" + monitoredDirectory, e);\n }\n declarationsFiles.clear();\n declarationRegistrationManager.unregisterAll();\n }", "public static appfwjsoncontenttype get(nitro_service service, String jsoncontenttypevalue) throws Exception{\n\t\tappfwjsoncontenttype obj = new appfwjsoncontenttype();\n\t\tobj.set_jsoncontenttypevalue(jsoncontenttypevalue);\n\t\tappfwjsoncontenttype response = (appfwjsoncontenttype) obj.get_resource(service);\n\t\treturn response;\n\t}", "private void readResourceExtendedAttributes(Project.Resources.Resource xml, Resource mpx)\n {\n for (Project.Resources.Resource.ExtendedAttribute attrib : xml.getExtendedAttribute())\n {\n int xmlFieldID = Integer.parseInt(attrib.getFieldID()) & 0x0000FFFF;\n ResourceField mpxFieldID = MPPResourceField.getInstance(xmlFieldID);\n TimeUnit durationFormat = DatatypeConverter.parseDurationTimeUnits(attrib.getDurationFormat(), null);\n DatatypeConverter.parseExtendedAttribute(m_projectFile, mpx, attrib.getValue(), mpxFieldID, durationFormat);\n }\n }", "public Version putVersionedWithCustomTimeout(CompositeVoldemortRequest<K, V> requestWrapper)\n throws ObsoleteVersionException {\n validateTimeout(requestWrapper.getRoutingTimeoutInMs());\n for(int attempts = 0; attempts < this.metadataRefreshAttempts; attempts++) {\n try {\n String keyHexString = \"\";\n long startTimeInMs = System.currentTimeMillis();\n if(logger.isDebugEnabled()) {\n ByteArray key = (ByteArray) requestWrapper.getKey();\n keyHexString = RestUtils.getKeyHexString(key);\n debugLogStart(\"PUT_VERSION\",\n requestWrapper.getRequestOriginTimeInMs(),\n startTimeInMs,\n keyHexString);\n }\n store.put(requestWrapper);\n if(logger.isDebugEnabled()) {\n debugLogEnd(\"PUT_VERSION\",\n requestWrapper.getRequestOriginTimeInMs(),\n startTimeInMs,\n System.currentTimeMillis(),\n keyHexString,\n 0);\n }\n return requestWrapper.getValue().getVersion();\n } catch(InvalidMetadataException e) {\n logger.info(\"Received invalid metadata exception during put [ \" + e.getMessage()\n + \" ] on store '\" + storeName + \"'. Rebootstrapping\");\n bootStrap();\n }\n }\n throw new VoldemortException(this.metadataRefreshAttempts\n + \" metadata refresh attempts failed.\");\n }", "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}", "@Override\n protected void registerRequest(RestRequestValidator requestValidator,\n ChannelHandlerContext ctx,\n MessageEvent messageEvent) {\n // At this point we know the request is valid and we have a\n // error handler. So we construct the composite Voldemort\n // request object.\n CompositeVoldemortRequest<ByteArray, byte[]> requestObject = requestValidator.constructCompositeVoldemortRequestObject();\n if(requestObject != null) {\n\n // Dropping dead requests from going to next handler\n long now = System.currentTimeMillis();\n if(requestObject.getRequestOriginTimeInMs() + requestObject.getRoutingTimeoutInMs() <= now) {\n RestErrorHandler.writeErrorResponse(messageEvent,\n HttpResponseStatus.REQUEST_TIMEOUT,\n \"current time: \"\n + now\n + \"\\torigin time: \"\n + requestObject.getRequestOriginTimeInMs()\n + \"\\ttimeout in ms: \"\n + requestObject.getRoutingTimeoutInMs());\n return;\n } else {\n Store store = getStore(requestValidator.getStoreName(),\n requestValidator.getParsedRoutingType());\n if(store != null) {\n VoldemortStoreRequest voldemortStoreRequest = new VoldemortStoreRequest(requestObject,\n store,\n parseZoneId());\n Channels.fireMessageReceived(ctx, voldemortStoreRequest);\n } else {\n logger.error(\"Error when getting store. Non Existing store name.\");\n RestErrorHandler.writeErrorResponse(messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Non Existing store name. Critical error.\");\n return;\n\n }\n }\n }\n }", "public static String getSerializedVectorClocks(List<VectorClock> vectorClocks) {\n List<VectorClockWrapper> vectorClockWrappers = new ArrayList<VectorClockWrapper>();\n for(VectorClock vc: vectorClocks) {\n vectorClockWrappers.add(new VectorClockWrapper(vc));\n }\n String serializedVC = \"\";\n try {\n serializedVC = mapper.writeValueAsString(vectorClockWrappers);\n } catch(Exception e) {\n e.printStackTrace();\n }\n return serializedVC;\n }", "public ValueContainer[] getCurrentLockingValues(Object o) throws PersistenceBrokerException\r\n {\r\n FieldDescriptor[] fields = getLockingFields();\r\n ValueContainer[] result = new ValueContainer[fields.length];\r\n for (int i = 0; i < result.length; i++)\r\n {\r\n result[i] = new ValueContainer(fields[i].getPersistentField().get(o), fields[i].getJdbcType());\r\n }\r\n return result;\r\n }", "public static HikariConfig createHikariConfig(CmsParameterConfiguration config, String key) {\n\n Map<String, String> poolMap = Maps.newHashMap();\n for (Map.Entry<String, String> entry : config.entrySet()) {\n String suffix = getPropertyRelativeSuffix(KEY_DATABASE_POOL + \".\" + key, entry.getKey());\n if ((suffix != null) && !CmsStringUtil.isEmptyOrWhitespaceOnly(entry.getValue())) {\n String value = entry.getValue().trim();\n poolMap.put(suffix, value);\n }\n }\n\n // these are for backwards compatibility , all other properties not of the form db.pool.poolname.v11..... are ignored\n String jdbcUrl = poolMap.get(KEY_JDBC_URL);\n String params = poolMap.get(KEY_JDBC_URL_PARAMS);\n String driver = poolMap.get(KEY_JDBC_DRIVER);\n String user = poolMap.get(KEY_USERNAME);\n String password = poolMap.get(KEY_PASSWORD);\n String poolName = OPENCMS_URL_PREFIX + key;\n\n if ((params != null) && (jdbcUrl != null)) {\n jdbcUrl += params;\n }\n\n Properties hikariProps = new Properties();\n\n if (jdbcUrl != null) {\n hikariProps.put(\"jdbcUrl\", jdbcUrl);\n }\n if (driver != null) {\n hikariProps.put(\"driverClassName\", driver);\n }\n if (user != null) {\n user = OpenCms.getCredentialsResolver().resolveCredential(I_CmsCredentialsResolver.DB_USER, user);\n hikariProps.put(\"username\", user);\n }\n if (password != null) {\n password = OpenCms.getCredentialsResolver().resolveCredential(\n I_CmsCredentialsResolver.DB_PASSWORD,\n password);\n hikariProps.put(\"password\", password);\n }\n\n hikariProps.put(\"maximumPoolSize\", \"30\");\n\n // Properties of the form db.pool.poolname.v11.<foo> are directly passed to HikariCP as <foo>\n for (Map.Entry<String, String> entry : poolMap.entrySet()) {\n String suffix = getPropertyRelativeSuffix(\"v11\", entry.getKey());\n if (suffix != null) {\n hikariProps.put(suffix, entry.getValue());\n }\n }\n\n String configuredTestQuery = (String)(hikariProps.get(\"connectionTestQuery\"));\n String testQueryForDriver = testQueries.get(driver);\n if ((testQueryForDriver != null) && CmsStringUtil.isEmptyOrWhitespaceOnly(configuredTestQuery)) {\n hikariProps.put(\"connectionTestQuery\", testQueryForDriver);\n }\n hikariProps.put(\"registerMbeans\", \"true\");\n HikariConfig result = new HikariConfig(hikariProps);\n\n result.setPoolName(poolName.replace(\":\", \"_\"));\n return result;\n }" ]
Set the names of six images in the zip file. The default names of the six images are "posx.png", "negx.png", "posy.png", "negx.png", "posz.png", and "negz.png". If the names of the six images in the zip file are different to the default ones, this function must be called before load the zip file. @param nameArray An array containing six strings which are names of images corresponding to +x, -x, +y, -y, +z, and -z faces of the cube map texture respectively.
[ "public static void setFaceNames(String[] nameArray)\n {\n if (nameArray.length != 6)\n {\n throw new IllegalArgumentException(\"nameArray length is not 6.\");\n }\n for (int i = 0; i < 6; i++)\n {\n faceIndexMap.put(nameArray[i], i);\n }\n }" ]
[ "@Around(\"@annotation(retryableAnnotation)\")\n public Object call(final ProceedingJoinPoint pjp, Retryable retryableAnnotation) throws Throwable {\n final int maxTries = retryableAnnotation.maxTries();\n final int retryDelayMillies = retryableAnnotation.retryDelayMillis();\n final Class<? extends Throwable>[] retryOn = retryableAnnotation.retryOn();\n final boolean doubleDelay = retryableAnnotation.doubleDelay();\n final boolean throwCauseException = retryableAnnotation.throwCauseException();\n\n if (logger.isDebugEnabled()) {\n logger.debug(\"Have @Retryable method wrapping call on method {} of target object {}\",\n new Object[] {\n pjp.getSignature().getName(),\n pjp.getTarget()\n });\n }\n\n ServiceRetrier serviceRetrier =\n new ServiceRetrier(retryDelayMillies, maxTries, doubleDelay, throwCauseException, retryOn);\n\n return serviceRetrier.invoke(\n new Callable<Object>() {\n public Object call() throws Exception {\n try {\n return pjp.proceed();\n }\n catch (Exception e) {\n throw e;\n }\n catch (Error e) {\n throw e;\n }\n catch (Throwable t) {\n throw new RuntimeException(t);\n }\n }\n }\n );\n }", "private Object getConstantValue(FieldType type, byte[] block)\n {\n Object value;\n DataType dataType = type.getDataType();\n\n if (dataType == null)\n {\n value = null;\n }\n else\n {\n switch (dataType)\n {\n case DURATION:\n {\n value = MPPUtility.getAdjustedDuration(m_properties, MPPUtility.getInt(block, getValueOffset()), MPPUtility.getDurationTimeUnits(MPPUtility.getShort(block, getTimeUnitsOffset())));\n break;\n }\n\n case NUMERIC:\n {\n value = Double.valueOf(MPPUtility.getDouble(block, getValueOffset()));\n break;\n }\n\n case PERCENTAGE:\n {\n value = Double.valueOf(MPPUtility.getShort(block, getValueOffset()));\n break;\n }\n\n case CURRENCY:\n {\n value = Double.valueOf(MPPUtility.getDouble(block, getValueOffset()) / 100);\n break;\n }\n\n case STRING:\n {\n int textOffset = getTextOffset(block);\n value = MPPUtility.getUnicodeString(m_criteriaData, m_dataOffset + m_criteriaTextStart + textOffset);\n break;\n }\n\n case BOOLEAN:\n {\n int intValue = MPPUtility.getShort(block, getValueOffset());\n value = (intValue == 1 ? Boolean.TRUE : Boolean.FALSE);\n break;\n }\n\n case DATE:\n {\n value = MPPUtility.getTimestamp(block, getValueOffset());\n break;\n }\n\n default:\n {\n value = null;\n break;\n }\n }\n }\n\n return value;\n }", "public static FileOutputStream openResultFileOuputStream(\n\t\t\tPath resultDirectory, String filename) throws IOException {\n\t\tPath filePath = resultDirectory.resolve(filename);\n\t\treturn new FileOutputStream(filePath.toFile());\n\t}", "public double dot(Vector3d v1) {\n return x * v1.x + y * v1.y + z * v1.z;\n }", "public static protocolhttpband[] get(nitro_service service, protocolhttpband_args args) throws Exception{\n\t\tprotocolhttpband obj = new protocolhttpband();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tprotocolhttpband[] response = (protocolhttpband[])obj.get_resources(service, option);\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 }", "private static void alterHtmlDocs(Options opt, String outputFolder, String packageName, String className,\n\t String htmlFileName, Pattern insertPointPattern, RootDoc root) throws IOException {\n\t// setup files\n\tFile output = new File(outputFolder, packageName.replace(\".\", \"/\"));\n\tFile htmlFile = new File(output, htmlFileName);\n\tFile alteredFile = new File(htmlFile.getAbsolutePath() + \".uml\");\n\tif (!htmlFile.exists()) {\n\t System.err.println(\"Expected file not found: \" + htmlFile.getAbsolutePath());\n\t return;\n\t}\n\n\t// parse & rewrite\n\tBufferedWriter writer = null;\n\tBufferedReader reader = null;\n\tboolean matched = false;\n\ttry {\n\t writer = new BufferedWriter(new OutputStreamWriter(new\n\t\t FileOutputStream(alteredFile), opt.outputEncoding));\n\t reader = new BufferedReader(new InputStreamReader(new\n\t\t FileInputStream(htmlFile), opt.outputEncoding));\n\n\t String line;\n\t while ((line = reader.readLine()) != null) {\n\t\twriter.write(line);\n\t\twriter.newLine();\n\t\tif (!matched && insertPointPattern.matcher(line).matches()) {\n\t\t matched = true;\n\t\t\t\n\t\t String tag;\n\t\t if (opt.autoSize)\n\t\t tag = String.format(UML_AUTO_SIZED_DIV_TAG, className);\n\t\t else\n tag = String.format(UML_DIV_TAG, className);\n\t\t if (opt.collapsibleDiagrams)\n\t\t \ttag = String.format(EXPANDABLE_UML, tag, \"Show UML class diagram\", \"Hide UML class diagram\");\n\t\t writer.write(\"<!-- UML diagram added by UMLGraph version \" +\n\t\t \t\tVersion.VERSION + \n\t\t\t\t\" (http://www.spinellis.gr/umlgraph/) -->\");\n\t\t writer.newLine();\n\t\t writer.write(tag);\n\t\t writer.newLine();\n\t\t}\n\t }\n\t} finally {\n\t if (writer != null)\n\t\twriter.close();\n\t if (reader != null)\n\t\treader.close();\n\t}\n\n\t// if altered, delete old file and rename new one to the old file name\n\tif (matched) {\n\t htmlFile.delete();\n\t alteredFile.renameTo(htmlFile);\n\t} else {\n\t root.printNotice(\"Warning, could not find a line that matches the pattern '\" + insertPointPattern.pattern() \n\t\t + \"'.\\n Class diagram reference not inserted\");\n\t alteredFile.delete();\n\t}\n }", "private static boolean isBinary(InputStream in) {\n try {\n int size = in.available();\n if (size > 1024) size = 1024;\n byte[] data = new byte[size];\n in.read(data);\n in.close();\n\n int ascii = 0;\n int other = 0;\n\n for (int i = 0; i < data.length; i++) {\n byte b = data[i];\n if (b < 0x09) return true;\n\n if (b == 0x09 || b == 0x0A || b == 0x0C || b == 0x0D) ascii++;\n else if (b >= 0x20 && b <= 0x7E) ascii++;\n else other++;\n }\n\n return other != 0 && 100 * other / (ascii + other) > 95;\n\n } catch (IOException e) {\n throw E.ioException(e);\n }\n }", "public static void touch(final File folder , final String fileName) throws IOException {\n if(!folder.exists()){\n folder.mkdirs();\n }\n\n final File touchedFile = new File(folder, fileName);\n\n // The JVM will only 'touch' the file if you instantiate a\n // FileOutputStream instance for the file in question.\n // You don't actually write any data to the file through\n // the FileOutputStream. Just instantiate it and close it.\n\n try (\n FileOutputStream doneFOS = new FileOutputStream(touchedFile);\n ) {\n // Touching the file\n }\n catch (FileNotFoundException e) {\n throw new FileNotFoundException(\"Failed to the find file.\" + e);\n }\n }" ]
Returns data tree structured as Transloadit expects it. @param data @return {@link Map} @throws LocalOperationException
[ "private Map<String, String> toPayload(Map<String, Object> data) throws LocalOperationException {\n Map<String, Object> dataClone = new HashMap<String, Object>(data);\n dataClone.put(\"auth\", getAuthData());\n\n Map<String, String> payload = new HashMap<String, String>();\n payload.put(\"params\", jsonifyData(dataClone));\n\n if (transloadit.shouldSignRequest) {\n payload.put(\"signature\", getSignature(jsonifyData(dataClone)));\n }\n return payload;\n }" ]
[ "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 }", "@Nonnull\n\tprivate static Properties findDefaultProperties() {\n\t\tfinal InputStream in = SourceCodeFormatter.class.getClassLoader().getResourceAsStream(DEFAULT_PROPERTIES_PATH);\n\t\tfinal Properties p = new Properties();\n\t\ttry {\n\t\t\tp.load(in);\n\t\t} catch (final IOException e) {\n\t\t\tthrow new RuntimeException(String.format(\"Can not load resource %s\", DEFAULT_PROPERTIES_PATH));\n\t\t}\n\t\treturn p;\n\t}", "public List<String> getCorporateGroupIds(final String organizationId) {\n final DbOrganization dbOrganization = getOrganization(organizationId);\n return dbOrganization.getCorporateGroupIdPrefixes();\n }", "@Inline(value = \"$1.putAll($2)\", statementExpression = true)\n\tpublic static <K, V> void operator_add(Map<K, V> outputMap, Map<? extends K, ? extends V> inputMap) {\n\t\toutputMap.putAll(inputMap);\n\t}", "static byte[] hmacSha1(StringBuilder message, String key) {\n try {\n Mac mac = Mac.getInstance(\"HmacSHA1\");\n mac.init(new SecretKeySpec(key.getBytes(), \"HmacSHA1\"));\n return mac.doFinal(message.toString().getBytes());\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }", "public GVRRenderData setDrawMode(int drawMode) {\n if (drawMode != GL_POINTS && drawMode != GL_LINES\n && drawMode != GL_LINE_STRIP && drawMode != GL_LINE_LOOP\n && drawMode != GL_TRIANGLES && drawMode != GL_TRIANGLE_STRIP\n && drawMode != GL_TRIANGLE_FAN) {\n throw new IllegalArgumentException(\n \"drawMode must be one of GL_POINTS, GL_LINES, GL_LINE_STRIP, GL_LINE_LOOP, GL_TRIANGLES, GL_TRIANGLE_FAN, GL_TRIANGLE_STRIP.\");\n }\n NativeRenderData.setDrawMode(getNative(), drawMode);\n return this;\n }", "public ScopedToken getLowerScopedToken(List<String> scopes, String resource) {\n assert (scopes != null);\n assert (scopes.size() > 0);\n URL url = null;\n try {\n url = new URL(this.getTokenURL());\n } catch (MalformedURLException e) {\n assert false : \"An invalid refresh URL indicates a bug in the SDK.\";\n throw new RuntimeException(\"An invalid refresh URL indicates a bug in the SDK.\", e);\n }\n\n StringBuilder spaceSeparatedScopes = new StringBuilder();\n for (int i = 0; i < scopes.size(); i++) {\n spaceSeparatedScopes.append(scopes.get(i));\n if (i < scopes.size() - 1) {\n spaceSeparatedScopes.append(\" \");\n }\n }\n\n String urlParameters = null;\n\n if (resource != null) {\n //this.getAccessToken() ensures we have a valid access token\n urlParameters = String.format(\"grant_type=urn:ietf:params:oauth:grant-type:token-exchange\"\n + \"&subject_token_type=urn:ietf:params:oauth:token-type:access_token&subject_token=%s\"\n + \"&scope=%s&resource=%s\",\n this.getAccessToken(), spaceSeparatedScopes, resource);\n } else {\n //this.getAccessToken() ensures we have a valid access token\n urlParameters = String.format(\"grant_type=urn:ietf:params:oauth:grant-type:token-exchange\"\n + \"&subject_token_type=urn:ietf:params:oauth:token-type:access_token&subject_token=%s\"\n + \"&scope=%s\",\n this.getAccessToken(), spaceSeparatedScopes);\n }\n\n BoxAPIRequest request = new BoxAPIRequest(this, url, \"POST\");\n request.shouldAuthenticate(false);\n request.setBody(urlParameters);\n\n String json;\n try {\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n json = response.getJSON();\n } catch (BoxAPIException e) {\n this.notifyError(e);\n throw e;\n }\n\n JsonObject jsonObject = JsonObject.readFrom(json);\n ScopedToken token = new ScopedToken(jsonObject);\n token.setObtainedAt(System.currentTimeMillis());\n token.setExpiresIn(jsonObject.get(\"expires_in\").asLong() * 1000);\n return token;\n }", "private String appendXmlEndingTag(String value) {\r\n StringBuilder sb = new StringBuilder();\r\n sb.append(\"</\").append(value).append(\">\");\n\r\n return sb.toString();\r\n }", "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}" ]
Calls afterMaterialization on all registered listeners in the reverse order of registration.
[ "protected void afterMaterialization()\r\n\t{\r\n\t\tif (_listeners != null)\r\n\t\t{\r\n\t\t\tMaterializationListener listener;\r\n\r\n\t\t\t// listeners may remove themselves during the afterMaterialization\r\n\t\t\t// callback.\r\n\t\t\t// thus we must iterate through the listeners vector from back to\r\n\t\t\t// front\r\n\t\t\t// to avoid index problems.\r\n\t\t\tfor (int idx = _listeners.size() - 1; idx >= 0; idx--)\r\n\t\t\t{\r\n\t\t\t\tlistener = (MaterializationListener) _listeners.get(idx);\r\n\t\t\t\tlistener.afterMaterialization(this, _realSubject);\r\n\t\t\t}\r\n\t\t}\r\n\t}" ]
[ "@JsonAnySetter\n public void setUnknownField(final String name, final Object value) {\n this.unknownFields.put(name, value);\n }", "private boolean isRecyclable(View convertView, T content) {\n boolean isRecyclable = false;\n if (convertView != null && convertView.getTag() != null) {\n Class prototypeClass = getPrototypeClass(content);\n validatePrototypeClass(prototypeClass);\n isRecyclable = prototypeClass.equals(convertView.getTag().getClass());\n }\n return isRecyclable;\n }", "private static long createLongSeed(byte[] seed)\n {\n if (seed == null || seed.length != SEED_SIZE_BYTES)\n {\n throw new IllegalArgumentException(\"Java RNG requires a 64-bit (8-byte) seed.\");\n }\n return BinaryUtils.convertBytesToLong(seed, 0);\n }", "public Object copy(final Object obj, final PersistenceBroker broker)\r\n {\r\n return clone(obj, IdentityMapFactory.getIdentityMap(), broker);\r\n }", "protected static Map<String, List<Statement>> addStatementToGroups(Statement statement, Map<String, List<Statement>> claims) {\n\t\tMap<String, List<Statement>> newGroups = new HashMap<>(claims);\n\t\tString pid = statement.getMainSnak().getPropertyId().getId();\n\t\tif(newGroups.containsKey(pid)) {\n\t\t\tList<Statement> newGroup = new ArrayList<>(newGroups.get(pid).size());\n\t\t\tboolean statementReplaced = false;\n\t\t\tfor(Statement existingStatement : newGroups.get(pid)) {\n\t\t\t\tif(existingStatement.getStatementId().equals(statement.getStatementId()) &&\n\t\t\t\t\t\t!existingStatement.getStatementId().isEmpty()) {\n\t\t\t\t\tstatementReplaced = true;\n\t\t\t\t\tnewGroup.add(statement);\n\t\t\t\t} else {\n\t\t\t\t\tnewGroup.add(existingStatement);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(!statementReplaced) {\n\t\t\t\tnewGroup.add(statement);\n\t\t\t}\n\t\t\tnewGroups.put(pid, newGroup);\n\t\t} else {\n\t\t\tnewGroups.put(pid, Collections.singletonList(statement));\n\t\t}\n\t\treturn newGroups;\n\t}", "private Set<String> findResourceNamesFromFileSystem(String classPathRootOnDisk, String scanRootLocation, File folder) {\n LOGGER.debug(\"Scanning for resources in path: {} ({})\", folder.getPath(), scanRootLocation);\n\n File[] files = folder.listFiles();\n if (files == null) {\n return emptySet();\n }\n\n Set<String> resourceNames = new TreeSet<>();\n\n for (File file : files) {\n if (file.canRead()) {\n if (file.isDirectory()) {\n resourceNames.addAll(findResourceNamesFromFileSystem(classPathRootOnDisk, scanRootLocation, file));\n } else {\n resourceNames.add(toResourceNameOnClasspath(classPathRootOnDisk, file));\n }\n }\n }\n\n return resourceNames;\n }", "public void buttonClick(View v) {\n switch (v.getId()) {\n case R.id.show:\n showAppMsg();\n break;\n case R.id.cancel_all:\n AppMsg.cancelAll(this);\n break;\n default:\n return;\n }\n }", "private ColumnDef addColumnFor(FieldDescriptorDef fieldDef, TableDef tableDef)\r\n {\r\n String name = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN);\r\n ColumnDef columnDef = tableDef.getColumn(name);\r\n\r\n if (columnDef == null)\r\n {\r\n columnDef = new ColumnDef(name);\r\n tableDef.addColumn(columnDef);\r\n }\r\n if (!fieldDef.isNested())\r\n { \r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_JAVANAME, fieldDef.getName());\r\n }\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_TYPE, fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_ID, fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_ID));\r\n if (fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_PRIMARYKEY, false))\r\n {\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_PRIMARYKEY, \"true\");\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_REQUIRED, \"true\");\r\n }\r\n else if (!fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_NULLABLE, true))\r\n {\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_REQUIRED, \"true\");\r\n }\r\n if (\"database\".equals(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_AUTOINCREMENT)))\r\n {\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_AUTOINCREMENT, \"true\");\r\n }\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_SIZE, fieldDef.getSizeConstraint());\r\n if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_DOCUMENTATION))\r\n {\r\n columnDef.setProperty(PropertyHelper.OJB_PROPERTY_DOCUMENTATION,\r\n fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_DOCUMENTATION));\r\n }\r\n if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_COLUMN_DOCUMENTATION))\r\n {\r\n columnDef.setProperty(PropertyHelper.OJB_PROPERTY_COLUMN_DOCUMENTATION,\r\n fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN_DOCUMENTATION));\r\n }\r\n return columnDef;\r\n }", "public static Info ones( final Variable A , final Variable B , ManagerTempVariables manager) {\n Info ret = new Info();\n final VariableMatrix output = manager.createMatrix();\n ret.output = output;\n\n if( A instanceof VariableInteger && B instanceof VariableInteger ) {\n ret.op = new Operation(\"ones-ii\") {\n @Override\n public void process() {\n int numRows = ((VariableInteger)A).value;\n int numCols = ((VariableInteger)B).value;\n output.matrix.reshape(numRows,numCols);\n CommonOps_DDRM.fill(output.matrix, 1);\n }\n };\n } else {\n throw new RuntimeException(\"Expected two integers got \"+A+\" \"+B);\n }\n\n return ret;\n }" ]
Read all configuration files. @return the list with all available configurations
[ "private List<CmsGitConfiguration> readConfigFiles() {\n\n List<CmsGitConfiguration> configurations = new LinkedList<CmsGitConfiguration>();\n\n // Default configuration file for backwards compatibility\n addConfigurationIfValid(configurations, new File(DEFAULT_CONFIG_FILE));\n\n // All files in the config folder\n File configFolder = new File(DEFAULT_CONFIG_FOLDER);\n if (configFolder.isDirectory()) {\n for (File configFile : configFolder.listFiles()) {\n addConfigurationIfValid(configurations, configFile);\n }\n }\n return configurations;\n }" ]
[ "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}", "@Deprecated\n\tpublic List<Double> getResolutions() {\n\t\tList<Double> resolutions = new ArrayList<Double>();\n\t\tfor (ScaleInfo scale : getZoomLevels()) {\n\t\t\tresolutions.add(1. / scale.getPixelPerUnit());\n\t\t}\n\t\treturn resolutions;\n\t}", "public static base_responses update(nitro_service client, responderpolicy resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tresponderpolicy updateresources[] = new responderpolicy[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new responderpolicy();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].rule = resources[i].rule;\n\t\t\t\tupdateresources[i].action = resources[i].action;\n\t\t\t\tupdateresources[i].undefaction = resources[i].undefaction;\n\t\t\t\tupdateresources[i].comment = resources[i].comment;\n\t\t\t\tupdateresources[i].logaction = resources[i].logaction;\n\t\t\t\tupdateresources[i].appflowaction = resources[i].appflowaction;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "public static String getSerializedVectorClocks(List<VectorClock> vectorClocks) {\n List<VectorClockWrapper> vectorClockWrappers = new ArrayList<VectorClockWrapper>();\n for(VectorClock vc: vectorClocks) {\n vectorClockWrappers.add(new VectorClockWrapper(vc));\n }\n String serializedVC = \"\";\n try {\n serializedVC = mapper.writeValueAsString(vectorClockWrappers);\n } catch(Exception e) {\n e.printStackTrace();\n }\n return serializedVC;\n }", "public static Class<?> loadClass(String className, ClassLoader cl) {\n try {\n return Class.forName(className, false, cl);\n } catch(ClassNotFoundException e) {\n throw new IllegalArgumentException(e);\n }\n }", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void markReadInboxMessage(final CTInboxMessage message){\n postAsyncSafely(\"markReadInboxMessage\", new Runnable() {\n @Override\n public void run() {\n synchronized (inboxControllerLock) {\n if(ctInboxController != null){\n boolean read = ctInboxController.markReadForMessageWithId(message.getMessageId());\n if (read) {\n _notifyInboxMessagesDidUpdate();\n }\n } else {\n getConfigLogger().debug(getAccountId(),\"Notification Inbox not initialized\");\n }\n }\n }\n });\n }", "public static DeploymentReflectionIndex create() {\n final SecurityManager sm = System.getSecurityManager();\n if (sm != null) {\n sm.checkPermission(ServerPermission.CREATE_DEPLOYMENT_REFLECTION_INDEX);\n }\n return new DeploymentReflectionIndex();\n }", "static AzureAsyncOperation fromResponse(SerializerAdapter<?> serializerAdapter, Response<ResponseBody> response) throws CloudException {\n AzureAsyncOperation asyncOperation = null;\n String rawString = null;\n if (response.body() != null) {\n try {\n rawString = response.body().string();\n asyncOperation = serializerAdapter.deserialize(rawString, AzureAsyncOperation.class);\n } catch (IOException exception) {\n // Exception will be handled below\n } finally {\n response.body().close();\n }\n }\n if (asyncOperation == null || asyncOperation.status() == null) {\n throw new CloudException(\"polling response does not contain a valid body: \" + rawString, response);\n }\n else {\n asyncOperation.rawString = rawString;\n }\n return asyncOperation;\n }", "public Stats getPhotosetStats(String photosetId, Date date) throws FlickrException {\n return getStats(METHOD_GET_PHOTOSET_STATS, \"photoset_id\", photosetId, date);\n }" ]
Ask the specified player for the album art in the specified slot with the specified rekordbox ID, using cached media instead if it is available, and possibly giving up if we are in passive mode. @param artReference uniquely identifies the desired album art @param trackType the kind of track that owns the art @param failIfPassive will prevent the request from taking place if we are in passive mode, so that automatic artwork updates will use available caches only @return the album art found, if any
[ "private AlbumArt requestArtworkInternal(final DataReference artReference, final CdjStatus.TrackType trackType,\n final boolean failIfPassive) {\n\n // First check if we are using cached data for this slot.\n MetadataCache cache = MetadataFinder.getInstance().getMetadataCache(SlotReference.getSlotReference(artReference));\n if (cache != null) {\n final AlbumArt result = cache.getAlbumArt(null, artReference);\n if (result != null) {\n artCache.put(artReference, result);\n }\n return result;\n }\n\n // Then see if any registered metadata providers can offer it for us.\n final MediaDetails sourceDetails = MetadataFinder.getInstance().getMediaDetailsFor(artReference.getSlotReference());\n if (sourceDetails != null) {\n final AlbumArt provided = MetadataFinder.getInstance().allMetadataProviders.getAlbumArt(sourceDetails, artReference);\n if (provided != null) {\n return provided;\n }\n }\n\n // At this point, unless we are allowed to actively request the data, we are done. We can always actively\n // request tracks from rekordbox.\n if (MetadataFinder.getInstance().isPassive() && failIfPassive && artReference.slot != CdjStatus.TrackSourceSlot.COLLECTION) {\n return null;\n }\n\n // We have to actually request the art using the dbserver protocol.\n ConnectionManager.ClientTask<AlbumArt> task = new ConnectionManager.ClientTask<AlbumArt>() {\n @Override\n public AlbumArt useClient(Client client) throws Exception {\n return getArtwork(artReference.rekordboxId, SlotReference.getSlotReference(artReference), trackType, client);\n }\n };\n\n try {\n AlbumArt artwork = ConnectionManager.getInstance().invokeWithClientSession(artReference.player, task, \"requesting artwork\");\n if (artwork != null) { // Our cache file load or network request succeeded, so add to the level 2 cache.\n artCache.put(artReference, artwork);\n }\n return artwork;\n } catch (Exception e) {\n logger.error(\"Problem requesting album art, returning null\", e);\n }\n return null;\n }" ]
[ "public static IndexedContainer getPrincipalContainer(\n CmsObject cms,\n List<? extends I_CmsPrincipal> list,\n String captionID,\n String descID,\n String iconID,\n String ouID,\n String icon,\n List<FontIcon> iconList) {\n\n IndexedContainer res = new IndexedContainer();\n\n res.addContainerProperty(captionID, String.class, \"\");\n res.addContainerProperty(ouID, String.class, \"\");\n res.addContainerProperty(iconID, FontIcon.class, new CmsCssIcon(icon));\n if (descID != null) {\n res.addContainerProperty(descID, String.class, \"\");\n }\n\n for (I_CmsPrincipal group : list) {\n\n Item item = res.addItem(group);\n item.getItemProperty(captionID).setValue(group.getSimpleName());\n item.getItemProperty(ouID).setValue(group.getOuFqn());\n if (descID != null) {\n item.getItemProperty(descID).setValue(group.getDescription(A_CmsUI.get().getLocale()));\n }\n }\n\n for (int i = 0; i < iconList.size(); i++) {\n res.getItem(res.getIdByIndex(i)).getItemProperty(iconID).setValue(iconList.get(i));\n }\n\n return res;\n }", "private void writeAssignments(Project project)\n {\n Project.Assignments assignments = m_factory.createProjectAssignments();\n project.setAssignments(assignments);\n List<Project.Assignments.Assignment> list = assignments.getAssignment();\n\n for (ResourceAssignment assignment : m_projectFile.getResourceAssignments())\n {\n list.add(writeAssignment(assignment));\n }\n\n //\n // Check to see if we have any tasks that have a percent complete value\n // but do not have resource assignments. If any exist, then we must\n // write a dummy resource assignment record to ensure that the MSPDI\n // file shows the correct percent complete amount for the task.\n //\n ProjectConfig config = m_projectFile.getProjectConfig();\n boolean autoUniqueID = config.getAutoAssignmentUniqueID();\n if (!autoUniqueID)\n {\n config.setAutoAssignmentUniqueID(true);\n }\n\n for (Task task : m_projectFile.getTasks())\n {\n double percentComplete = NumberHelper.getDouble(task.getPercentageComplete());\n if (percentComplete != 0 && task.getResourceAssignments().isEmpty() == true)\n {\n ResourceAssignment dummy = new ResourceAssignment(m_projectFile, task);\n Duration duration = task.getDuration();\n if (duration == null)\n {\n duration = Duration.getInstance(0, TimeUnit.HOURS);\n }\n double durationValue = duration.getDuration();\n TimeUnit durationUnits = duration.getUnits();\n double actualWork = (durationValue * percentComplete) / 100;\n double remainingWork = durationValue - actualWork;\n\n dummy.setResourceUniqueID(NULL_RESOURCE_ID);\n dummy.setWork(duration);\n dummy.setActualWork(Duration.getInstance(actualWork, durationUnits));\n dummy.setRemainingWork(Duration.getInstance(remainingWork, durationUnits));\n \n // Without this, MS Project will mark a 100% complete milestone as 99% complete\n if (percentComplete == 100 && duration.getDuration() == 0)\n { \n dummy.setActualFinish(task.getActualStart());\n }\n \n list.add(writeAssignment(dummy));\n }\n }\n\n config.setAutoAssignmentUniqueID(autoUniqueID);\n }", "public int compareTo(InternalFeature o) {\n\t\tif (null == o) {\n\t\t\treturn -1; // avoid NPE, put null objects at the end\n\t\t}\n\t\tif (null != styleDefinition && null != o.getStyleInfo()) {\n\t\t\tif (styleDefinition.getIndex() > o.getStyleInfo().getIndex()) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tif (styleDefinition.getIndex() < o.getStyleInfo().getIndex()) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t\treturn 0;\n\t}", "private void validateAttributesToCreateANewRendererViewHolder() {\n if (viewType == null) {\n throw new NullContentException(\n \"RendererBuilder needs a view type to create a RendererViewHolder\");\n }\n if (layoutInflater == null) {\n throw new NullLayoutInflaterException(\n \"RendererBuilder needs a LayoutInflater to create a RendererViewHolder\");\n }\n if (parent == null) {\n throw new NullParentException(\n \"RendererBuilder needs a parent to create a RendererViewHolder\");\n }\n }", "private void processCalendars() throws SQLException\n {\n List<Row> rows = getTable(\"EXCEPTIONN\");\n Map<Integer, DayType> exceptionMap = m_reader.createExceptionTypeMap(rows);\n\n rows = getTable(\"WORK_PATTERN\");\n Map<Integer, Row> workPatternMap = m_reader.createWorkPatternMap(rows);\n\n rows = new LinkedList<Row>();// getTable(\"WORK_PATTERN_ASSIGNMENT\"); // Need to generate an example\n Map<Integer, List<Row>> workPatternAssignmentMap = m_reader.createWorkPatternAssignmentMap(rows);\n\n rows = getTable(\"EXCEPTION_ASSIGNMENT\");\n Map<Integer, List<Row>> exceptionAssignmentMap = m_reader.createExceptionAssignmentMap(rows);\n\n rows = getTable(\"TIME_ENTRY\");\n Map<Integer, List<Row>> timeEntryMap = m_reader.createTimeEntryMap(rows);\n\n rows = getTable(\"CALENDAR\");\n Collections.sort(rows, CALENDAR_COMPARATOR);\n for (Row row : rows)\n {\n m_reader.processCalendar(row, workPatternMap, workPatternAssignmentMap, exceptionAssignmentMap, timeEntryMap, exceptionMap);\n }\n\n //\n // Update unique counters at this point as we will be generating\n // resource calendars, and will need to auto generate IDs\n //\n m_reader.getProject().getProjectConfig().updateUniqueCounters();\n }", "private ProjectFile readProjectFile(ProjectReader reader, InputStream stream) throws MPXJException\n {\n addListeners(reader);\n return reader.read(stream);\n }", "private boolean isSingleMultiDay() {\n\n long duration = getEnd().getTime() - getStart().getTime();\n if (duration > I_CmsSerialDateValue.DAY_IN_MILLIS) {\n return true;\n }\n if (isWholeDay() && (duration <= I_CmsSerialDateValue.DAY_IN_MILLIS)) {\n return false;\n }\n Calendar start = new GregorianCalendar();\n start.setTime(getStart());\n Calendar end = new GregorianCalendar();\n end.setTime(getEnd());\n if (start.get(Calendar.DAY_OF_MONTH) == end.get(Calendar.DAY_OF_MONTH)) {\n return false;\n }\n return true;\n\n }", "private void renderThumbnail(Video video) {\n Picasso.with(getContext()).cancelRequest(thumbnail);\n Picasso.with(getContext())\n .load(video.getThumbnail())\n .placeholder(R.drawable.placeholder)\n .into(thumbnail);\n }", "protected String getFormattedDatatypeValue(ICompositeNode node, AbstractRule rule, String text) throws ValueConverterException {\n\t\tObject value = valueConverter.toValue(text, rule.getName(), node);\n\t\ttext = valueConverter.toString(value, rule.getName());\n\t\treturn text;\n\t}" ]
Calculates Tangent value of the complex number. @param z1 A ComplexNumber instance. @return Returns new ComplexNumber instance containing the Tangent value of the specified complex number.
[ "public static ComplexNumber Tan(ComplexNumber z1) {\r\n ComplexNumber result = new ComplexNumber();\r\n\r\n if (z1.imaginary == 0.0) {\r\n result.real = Math.tan(z1.real);\r\n result.imaginary = 0.0;\r\n } else {\r\n double real2 = 2 * z1.real;\r\n double imag2 = 2 * z1.imaginary;\r\n double denom = Math.cos(real2) + Math.cosh(real2);\r\n\r\n result.real = Math.sin(real2) / denom;\r\n result.imaginary = Math.sinh(imag2) / denom;\r\n }\r\n\r\n return result;\r\n }" ]
[ "public 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 GVRCamera shadowCam = GVRShadowMap.makeOrthoShadowCamera(\n getGVRContext().getMainScene().getMainCameraRig().getCenterCamera());\n shadowMap = new GVRShadowMap(getGVRContext(), shadowCam);\n owner.attachComponent(shadowMap);\n }\n }\n else if (shadowMap != null)\n {\n shadowMap.setEnable(false);\n }\n }\n mCastShadow = enableFlag;\n }", "private static ChangeEvent<BsonDocument> coalesceChangeEvents(\n final ChangeEvent<BsonDocument> lastUncommittedChangeEvent,\n final ChangeEvent<BsonDocument> newestChangeEvent\n ) {\n if (lastUncommittedChangeEvent == null) {\n return newestChangeEvent;\n }\n switch (lastUncommittedChangeEvent.getOperationType()) {\n case INSERT:\n switch (newestChangeEvent.getOperationType()) {\n // Coalesce replaces/updates to inserts since we believe at some point a document did not\n // exist remotely and that this replace or update should really be an insert if we are\n // still in an uncommitted state.\n case REPLACE:\n case UPDATE:\n return new ChangeEvent<>(\n newestChangeEvent.getId(),\n OperationType.INSERT,\n newestChangeEvent.getFullDocument(),\n newestChangeEvent.getNamespace(),\n newestChangeEvent.getDocumentKey(),\n null,\n newestChangeEvent.hasUncommittedWrites()\n );\n default:\n break;\n }\n break;\n case DELETE:\n switch (newestChangeEvent.getOperationType()) {\n // Coalesce inserts to replaces since we believe at some point a document existed\n // remotely and that this insert should really be an replace if we are still in an\n // uncommitted state.\n case INSERT:\n return new ChangeEvent<>(\n newestChangeEvent.getId(),\n OperationType.REPLACE,\n newestChangeEvent.getFullDocument(),\n newestChangeEvent.getNamespace(),\n newestChangeEvent.getDocumentKey(),\n null,\n newestChangeEvent.hasUncommittedWrites()\n );\n default:\n break;\n }\n break;\n case UPDATE:\n switch (newestChangeEvent.getOperationType()) {\n case UPDATE:\n return new ChangeEvent<>(\n newestChangeEvent.getId(),\n OperationType.UPDATE,\n newestChangeEvent.getFullDocument(),\n newestChangeEvent.getNamespace(),\n newestChangeEvent.getDocumentKey(),\n lastUncommittedChangeEvent.getUpdateDescription() != null\n ? lastUncommittedChangeEvent\n .getUpdateDescription()\n .merge(newestChangeEvent.getUpdateDescription())\n : newestChangeEvent.getUpdateDescription(),\n newestChangeEvent.hasUncommittedWrites()\n );\n case REPLACE:\n return new ChangeEvent<>(\n newestChangeEvent.getId(),\n OperationType.REPLACE,\n newestChangeEvent.getFullDocument(),\n newestChangeEvent.getNamespace(),\n newestChangeEvent.getDocumentKey(),\n null,\n newestChangeEvent.hasUncommittedWrites()\n );\n default:\n break;\n }\n break;\n case REPLACE:\n switch (newestChangeEvent.getOperationType()) {\n case UPDATE:\n return new ChangeEvent<>(\n newestChangeEvent.getId(),\n OperationType.REPLACE,\n newestChangeEvent.getFullDocument(),\n newestChangeEvent.getNamespace(),\n newestChangeEvent.getDocumentKey(),\n null,\n newestChangeEvent.hasUncommittedWrites()\n );\n default:\n break;\n }\n break;\n default:\n break;\n }\n return newestChangeEvent;\n }", "private void init()\r\n {\r\n jdbcProperties = new Properties();\r\n dbcpProperties = new Properties();\r\n setFetchSize(0);\r\n this.setTestOnBorrow(true);\r\n this.setTestOnReturn(false);\r\n this.setTestWhileIdle(false);\r\n this.setLogAbandoned(false);\r\n this.setRemoveAbandoned(false);\r\n }", "public void set( int row , int col , double real , double imaginary ) {\n if( imaginary == 0 ) {\n set(row,col,real);\n } else {\n ops.set(mat,row,col, real, imaginary);\n }\n }", "@Override\n public DMatrixRMaj getU(DMatrixRMaj U , boolean transpose , boolean compact ) {\n U = handleU(U, transpose, compact,m,n,min);\n CommonOps_DDRM.setIdentity(U);\n\n for( int i = 0; i < m; i++ ) u[i] = 0;\n\n for( int j = min-1; j >= 0; j-- ) {\n u[j] = 1;\n for( int i = j+1; i < m; i++ ) {\n u[i] = UBV.get(i,j);\n }\n if( transpose )\n QrHelperFunctions_DDRM.rank1UpdateMultL(U, u, gammasU[j], j, j, m);\n else\n QrHelperFunctions_DDRM.rank1UpdateMultR(U, u, gammasU[j], j, j, m, this.b);\n }\n\n return U;\n }", "public void reformatFile() throws IOException\n {\n List<LineNumberPosition> lineBrokenPositions = new ArrayList<>();\n List<String> brokenLines = breakLines(lineBrokenPositions);\n emitFormatted(brokenLines, lineBrokenPositions);\n }", "protected void setWhenNoDataBand() {\n log.debug(\"setting up WHEN NO DATA band\");\n String whenNoDataText = getReport().getWhenNoDataText();\n Style style = getReport().getWhenNoDataStyle();\n if (whenNoDataText == null || \"\".equals(whenNoDataText))\n return;\n JRDesignBand band = new JRDesignBand();\n getDesign().setNoData(band);\n\n JRDesignTextField text = new JRDesignTextField();\n JRDesignExpression expression = ExpressionUtils.createStringExpression(\"\\\"\" + whenNoDataText + \"\\\"\");\n text.setExpression(expression);\n\n if (style == null) {\n style = getReport().getOptions().getDefaultDetailStyle();\n }\n\n if (getReport().isWhenNoDataShowTitle()) {\n LayoutUtils.copyBandElements(band, getDesign().getTitle());\n LayoutUtils.copyBandElements(band, getDesign().getPageHeader());\n }\n if (getReport().isWhenNoDataShowColumnHeader())\n LayoutUtils.copyBandElements(band, getDesign().getColumnHeader());\n\n int offset = LayoutUtils.findVerticalOffset(band);\n text.setY(offset);\n applyStyleToElement(style, text);\n text.setWidth(getReport().getOptions().getPrintableWidth());\n text.setHeight(50);\n band.addElement(text);\n log.debug(\"OK setting up WHEN NO DATA band\");\n\n }", "public void createPath(String pathName, String pathValue, String requestType) {\n try {\n int type = getRequestTypeFromString(requestType);\n String url = BASE_PATH;\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"pathName\", pathName),\n new BasicNameValuePair(\"path\", pathValue),\n new BasicNameValuePair(\"requestType\", String.valueOf(type)),\n new BasicNameValuePair(\"profileIdentifier\", this._profileName)\n };\n\n JSONObject response = new JSONObject(doPost(BASE_PATH, params));\n } catch (Exception e) {\n e.printStackTrace();\n }\n }", "protected <T, A> ActiveOperation<T, A> getActiveOperation(final ManagementRequestHeader header) {\n return getActiveOperation(header.getBatchId());\n }" ]
Gets all pending collaboration invites for the current user. @param api the API connection to use. @return a collection of pending collaboration infos.
[ "public static Collection<Info> getPendingCollaborations(BoxAPIConnection api) {\n URL url = PENDING_COLLABORATIONS_URL.build(api.getBaseURL());\n\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int entriesCount = responseJSON.get(\"total_count\").asInt();\n Collection<BoxCollaboration.Info> collaborations = new ArrayList<BoxCollaboration.Info>(entriesCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue entry : entries) {\n JsonObject entryObject = entry.asObject();\n BoxCollaboration collaboration = new BoxCollaboration(api, entryObject.get(\"id\").asString());\n BoxCollaboration.Info info = collaboration.new Info(entryObject);\n collaborations.add(info);\n }\n\n return collaborations;\n }" ]
[ "public Set<DeviceAnnouncement> findUnreachablePlayers() {\n ensureRunning();\n Set<DeviceAnnouncement> result = new HashSet<DeviceAnnouncement>();\n for (DeviceAnnouncement candidate: DeviceFinder.getInstance().getCurrentDevices()) {\n if (!Util.sameNetwork(matchedAddress.getNetworkPrefixLength(), matchedAddress.getAddress(), candidate.getAddress())) {\n result.add(candidate);\n }\n }\n return Collections.unmodifiableSet(result);\n }", "public void setConnectTimeout(int millis) {\n\t\tClientHttpRequestFactory f = getRequestFactory();\n\t\tif (f instanceof SimpleClientHttpRequestFactory) {\n\t\t\t((SimpleClientHttpRequestFactory) f).setConnectTimeout(millis);\n\t\t}\n\t\telse {\n\t\t\t((HttpComponentsClientHttpRequestFactory) f).setConnectTimeout(millis);\n\t\t}\n\t}", "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 static void main(final String[] args) throws IOException\n {\n // This is just a _hack_ ...\n BufferedReader reader = null;\n if (args.length == 0)\n {\n System.err.println(\"No input file specified.\");\n System.exit(-1);\n }\n if (args.length > 1)\n {\n reader = new BufferedReader(new InputStreamReader(new FileInputStream(args[1]), \"UTF-8\"));\n String line = reader.readLine();\n while (line != null && !line.startsWith(\"<!-- ###\"))\n {\n System.out.println(line);\n line = reader.readLine();\n }\n }\n System.out.println(Processor.process(new File(args[0])));\n if (args.length > 1 && reader != null)\n {\n String line = reader.readLine();\n while (line != null)\n {\n System.out.println(line);\n line = reader.readLine();\n }\n reader.close();\n }\n }", "public NodeList getAt(String name) {\n NodeList answer = new NodeList();\n for (Object child : this) {\n if (child instanceof Node) {\n Node childNode = (Node) child;\n Object temp = childNode.get(name);\n if (temp instanceof Collection) {\n answer.addAll((Collection) temp);\n } else {\n answer.add(temp);\n }\n }\n }\n return answer;\n }", "public static base_response update(nitro_service client, ipv6 resource) throws Exception {\n\t\tipv6 updateresource = new ipv6();\n\t\tupdateresource.ralearning = resource.ralearning;\n\t\tupdateresource.routerredirection = resource.routerredirection;\n\t\tupdateresource.ndbasereachtime = resource.ndbasereachtime;\n\t\tupdateresource.ndretransmissiontime = resource.ndretransmissiontime;\n\t\tupdateresource.natprefix = resource.natprefix;\n\t\tupdateresource.dodad = resource.dodad;\n\t\treturn updateresource.update_resource(client);\n\t}", "public LogSegment getLastView() {\n List<LogSegment> views = getView();\n return views.get(views.size() - 1);\n }", "public void deletePersistent(Object object)\r\n {\r\n if (!this.isOpen())\r\n {\r\n throw new DatabaseClosedException(\"Database is not open\");\r\n }\r\n TransactionImpl tx = getTransaction();\r\n if (tx == null || !tx.isOpen())\r\n {\r\n throw new TransactionNotInProgressException(\"No transaction in progress, cannot delete persistent\");\r\n }\r\n RuntimeObject rt = new RuntimeObject(object, tx);\r\n tx.deletePersistent(rt);\r\n// tx.moveToLastInOrderList(rt.getIdentity());\r\n }", "private long interpolateTimeSinceUpdate(TrackPositionUpdate update, long currentTimestamp) {\n if (!update.playing) {\n return update.milliseconds;\n }\n long elapsedMillis = (currentTimestamp - update.timestamp) / 1000000;\n long moved = Math.round(update.pitch * elapsedMillis);\n if (update.reverse) {\n return update.milliseconds - moved;\n }\n return update.milliseconds + moved;\n }" ]
make it public for CLI interaction to reuse JobContext
[ "public static void init(String jobId) {\n JobContext parent = current_.get();\n JobContext ctx = new JobContext(parent);\n current_.set(ctx);\n // don't call setJobId(String)\n // as it will trigger listeners -- TODO fix me\n ctx.jobId = jobId;\n if (null == parent) {\n Act.eventBus().trigger(new JobContextInitialized(ctx));\n }\n }" ]
[ "private static boolean validateEndRecord(File file, FileChannel channel, long startEndRecord, long endSig) throws IOException {\n\n try {\n channel.position(startEndRecord);\n\n final ByteBuffer endDirHeader = getByteBuffer(ENDLEN);\n read(endDirHeader, channel);\n if (endDirHeader.limit() < ENDLEN) {\n // Couldn't read the full end of central directory record header\n return false;\n } else if (getUnsignedInt(endDirHeader, 0) != endSig) {\n return false;\n }\n\n long pos = getUnsignedInt(endDirHeader, END_CENSTART);\n // TODO deal with Zip64\n if (pos == ZIP64_MARKER) {\n return false;\n }\n\n ByteBuffer cdfhBuffer = getByteBuffer(CENLEN);\n read(cdfhBuffer, channel, pos);\n long header = getUnsignedInt(cdfhBuffer, 0);\n if (header == CENSIG) {\n long firstLoc = getUnsignedInt(cdfhBuffer, CEN_LOC_OFFSET);\n long firstSize = getUnsignedInt(cdfhBuffer, CENSIZ);\n if (firstLoc == 0) {\n // normal case -- first bytes are the first local file\n if (!validateLocalFileRecord(channel, 0, firstSize)) {\n return false;\n }\n } else {\n // confirm that firstLoc is indeed the first local file\n long fileFirstLoc = scanForLocSig(channel);\n if (firstLoc != fileFirstLoc) {\n if (fileFirstLoc == 0) {\n return false;\n } else {\n // scanForLocSig() found a LOCSIG, but not at position zero and not\n // at the expected position.\n // With a file like this, we can't tell if we're in a nested zip\n // or we're in an outer zip and had the bad luck to find random bytes\n // that look like LOCSIG.\n return false;\n }\n }\n }\n\n // At this point, endDirHeader points to the correct end of central dir record.\n // Just need to validate the record is complete, including any comment\n int commentLen = getUnsignedShort(endDirHeader, END_COMMENTLEN);\n long commentEnd = startEndRecord + ENDLEN + commentLen;\n return commentEnd <= channel.size();\n }\n\n return false;\n } catch (EOFException eof) {\n // pos or firstLoc weren't really positions and moved us to an invalid location\n return false;\n }\n }", "public com.squareup.okhttp.Call getCharactersCharacterIdShipCall(Integer characterId, String datasource,\n String ifNoneMatch, String token, final ApiCallback callback) throws ApiException {\n Object localVarPostBody = new Object();\n\n // create path and map variables\n String localVarPath = \"/v1/characters/{character_id}/ship/\".replaceAll(\"\\\\{\" + \"character_id\" + \"\\\\}\",\n apiClient.escapeString(characterId.toString()));\n\n List<Pair> localVarQueryParams = new ArrayList<Pair>();\n List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();\n if (datasource != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"datasource\", datasource));\n }\n\n if (token != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"token\", token));\n }\n\n Map<String, String> localVarHeaderParams = new HashMap<String, String>();\n if (ifNoneMatch != null) {\n localVarHeaderParams.put(\"If-None-Match\", apiClient.parameterToString(ifNoneMatch));\n }\n\n Map<String, Object> localVarFormParams = new HashMap<String, Object>();\n final String[] localVarAccepts = { \"application/json\" };\n final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);\n if (localVarAccept != null) {\n localVarHeaderParams.put(\"Accept\", localVarAccept);\n }\n\n final String[] localVarContentTypes = {\n\n };\n final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);\n localVarHeaderParams.put(\"Content-Type\", localVarContentType);\n\n String[] localVarAuthNames = new String[] { \"evesso\" };\n return apiClient.buildCall(localVarPath, \"GET\", localVarQueryParams, localVarCollectionQueryParams,\n localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, callback);\n }", "public static responderpolicy get(nitro_service service, String name) throws Exception{\n\t\tresponderpolicy obj = new responderpolicy();\n\t\tobj.set_name(name);\n\t\tresponderpolicy response = (responderpolicy) obj.get_resource(service);\n\t\treturn response;\n\t}", "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 doRun(Properties properties) {\n ServerSetup[] serverSetup = new PropertiesBasedServerSetupBuilder().build(properties);\n\n if (serverSetup.length == 0) {\n printUsage(System.out);\n\n } else {\n greenMail = new GreenMail(serverSetup);\n log.info(\"Starting GreenMail standalone v{} using {}\",\n BuildInfo.INSTANCE.getProjectVersion(), Arrays.toString(serverSetup));\n greenMail.withConfiguration(new PropertiesBasedGreenMailConfigurationBuilder().build(properties))\n .start();\n }\n }", "public static void validateRollbackState(final String patchID, final InstalledIdentity identity) throws PatchingException {\n final Set<String> validHistory = processRollbackState(patchID, identity);\n if (patchID != null && !validHistory.contains(patchID)) {\n throw PatchLogger.ROOT_LOGGER.patchNotFoundInHistory(patchID);\n }\n }", "public void parseRawValue(String value)\n {\n int valueIndex = 0;\n int elementIndex = 0;\n m_elements.clear();\n while (valueIndex < value.length() && elementIndex < m_elements.size())\n {\n int elementLength = m_lengths.get(elementIndex).intValue();\n if (elementIndex > 0)\n {\n m_elements.add(m_separators.get(elementIndex - 1));\n }\n int endIndex = valueIndex + elementLength;\n if (endIndex > value.length())\n {\n endIndex = value.length();\n }\n String element = value.substring(valueIndex, endIndex);\n m_elements.add(element);\n valueIndex += elementLength;\n elementIndex++;\n }\n }", "private String parseEnvelope() {\r\n List<String> response = new ArrayList<>();\r\n //1. Date ---------------\r\n response.add(LB + Q + sentDateEnvelopeString + Q + SP);\r\n //2. Subject ---------------\r\n if (subject != null && (subject.length() != 0)) {\r\n response.add(Q + escapeHeader(subject) + Q + SP);\r\n } else {\r\n response.add(NIL + SP);\r\n }\r\n //3. From ---------------\r\n addAddressToEnvelopeIfAvailable(from, response);\r\n response.add(SP);\r\n //4. Sender ---------------\r\n addAddressToEnvelopeIfAvailableWithNetscapeFeature(sender, response);\r\n response.add(SP);\r\n addAddressToEnvelopeIfAvailableWithNetscapeFeature(replyTo, response);\r\n response.add(SP);\r\n addAddressToEnvelopeIfAvailable(to, response);\r\n response.add(SP);\r\n addAddressToEnvelopeIfAvailable(cc, response);\r\n response.add(SP);\r\n addAddressToEnvelopeIfAvailable(bcc, response);\r\n response.add(SP);\r\n if (inReplyTo != null && inReplyTo.length > 0) {\r\n response.add(inReplyTo[0]);\r\n } else {\r\n response.add(NIL);\r\n }\r\n response.add(SP);\r\n if (messageID != null && messageID.length > 0) {\r\n messageID[0] = escapeHeader(messageID[0]);\r\n response.add(Q + messageID[0] + Q);\r\n } else {\r\n response.add(NIL);\r\n }\r\n response.add(RB);\r\n\r\n StringBuilder buf = new StringBuilder(16 * response.size());\r\n for (String aResponse : response) {\r\n buf.append(aResponse);\r\n }\r\n\r\n return buf.toString();\r\n }", "protected List<CmsResource> getTopFolders(List<CmsResource> folders) {\n\n List<String> folderPaths = new ArrayList<String>();\n List<CmsResource> topFolders = new ArrayList<CmsResource>();\n Map<String, CmsResource> foldersByPath = new HashMap<String, CmsResource>();\n for (CmsResource folder : folders) {\n folderPaths.add(folder.getRootPath());\n foldersByPath.put(folder.getRootPath(), folder);\n }\n Collections.sort(folderPaths);\n Set<String> topFolderPaths = new HashSet<String>(folderPaths);\n for (int i = 0; i < folderPaths.size(); i++) {\n for (int j = i + 1; j < folderPaths.size(); j++) {\n if (folderPaths.get(j).startsWith((folderPaths.get(i)))) {\n topFolderPaths.remove(folderPaths.get(j));\n } else {\n break;\n }\n }\n }\n for (String path : topFolderPaths) {\n topFolders.add(foldersByPath.get(path));\n }\n return topFolders;\n }" ]
Checks the existence of the directory. If it does not exist, the method creates it. @param dir the directory to check. @throws IOException if fails.
[ "public static void directoryCheck(String dir) throws IOException {\n\t\tfinal File file = new File(dir);\n\n\t\tif (!file.exists()) {\n\t\t\tFileUtils.forceMkdir(file);\n\t\t}\n\t}" ]
[ "public void setMat4(String key, float x1, float y1, float z1, float w1,\n float x2, float y2, float z2, float w2, float x3, float y3,\n float z3, float w3, float x4, float y4, float z4, float w4)\n {\n checkKeyIsUniform(key);\n NativeLight.setMat4(getNative(), key, x1, y1, z1, w1, x2, y2,\n z2, w2, x3, y3, z3, w3, x4, y4, z4, w4);\n }", "public Diff compare(CtElement left, CtElement right) {\n\t\tfinal SpoonGumTreeBuilder scanner = new SpoonGumTreeBuilder();\n\t\treturn new DiffImpl(scanner.getTreeContext(), scanner.getTree(left), scanner.getTree(right));\n\t}", "public String invokeOperation(String operationName, Map<String, String[]> parameterMap)\n throws JMException, UnsupportedEncodingException {\n MBeanOperationInfo operationInfo = getOperationInfo(operationName);\n MBeanOperationInvoker invoker = createMBeanOperationInvoker(mBeanServer, objectName, operationInfo);\n return sanitizer.escapeValue(invoker.invokeOperation(parameterMap));\n }", "@Override public void setID(Integer val)\n {\n ProjectFile parent = getParentFile();\n Integer previous = getID();\n\n if (previous != null)\n {\n parent.getTasks().unmapID(previous);\n }\n\n parent.getTasks().mapID(val, this);\n\n set(TaskField.ID, val);\n }", "public void setT(int t) {\r\n this.t = Math.min((radius * 2 + 1) * (radius * 2 + 1) / 2, Math.max(0, t));\r\n }", "private StepFormatter.Formatting<?, ?> getFormatting( Annotation[] annotations, Set<Class<?>> visitedTypes,\n Annotation originalAnnotation, String parameterName ) {\n List<StepFormatter.Formatting<?, ?>> foundFormatting = Lists.newArrayList();\n Table tableAnnotation = null;\n for( Annotation annotation : annotations ) {\n try {\n if( annotation instanceof Format ) {\n Format arg = (Format) annotation;\n foundFormatting.add( new StepFormatter.ArgumentFormatting( ReflectionUtil.newInstance( arg.value() ), arg.args() ) );\n } else if( annotation instanceof Table ) {\n tableAnnotation = (Table) annotation;\n } else if( annotation instanceof AnnotationFormat ) {\n AnnotationFormat arg = (AnnotationFormat) annotation;\n foundFormatting.add( new StepFormatter.ArgumentFormatting(\n new StepFormatter.AnnotationBasedFormatter( arg.value().newInstance(), originalAnnotation ) ) );\n } else {\n Class<? extends Annotation> annotationType = annotation.annotationType();\n if( !visitedTypes.contains( annotationType ) ) {\n visitedTypes.add( annotationType );\n StepFormatter.Formatting<?, ?> formatting = getFormatting( annotationType.getAnnotations(), visitedTypes,\n annotation, parameterName );\n if( formatting != null ) {\n foundFormatting.add( formatting );\n }\n }\n }\n } catch( Exception e ) {\n throw Throwables.propagate( e );\n }\n }\n\n if( foundFormatting.size() > 1 ) {\n Formatting<?, ?> innerFormatting = Iterables.getLast( foundFormatting );\n foundFormatting.remove( innerFormatting );\n\n ChainedFormatting<?> chainedFormatting = new StepFormatter.ChainedFormatting<Object>( (ObjectFormatter<Object>) innerFormatting );\n for( StepFormatter.Formatting<?, ?> formatting : Lists.reverse( foundFormatting ) ) {\n chainedFormatting.addFormatting( (StepFormatter.Formatting<?, String>) formatting );\n }\n\n foundFormatting.clear();\n foundFormatting.add( chainedFormatting );\n }\n\n if( tableAnnotation != null ) {\n ObjectFormatter<?> objectFormatter = foundFormatting.isEmpty()\n ? DefaultFormatter.INSTANCE\n : foundFormatting.get( 0 );\n return getTableFormatting( annotations, parameterName, tableAnnotation, objectFormatter );\n }\n\n if( foundFormatting.isEmpty() ) {\n return null;\n }\n\n return foundFormatting.get( 0 );\n }", "public static auditsyslogpolicy_vpnglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditsyslogpolicy_vpnglobal_binding obj = new auditsyslogpolicy_vpnglobal_binding();\n\t\tobj.set_name(name);\n\t\tauditsyslogpolicy_vpnglobal_binding response[] = (auditsyslogpolicy_vpnglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static MediaType nonBinary( MediaType.Type type, String subType, Charset charSet ) {\n ApiUtil.notNull( charSet, \"charset must not be null\" );\n return new MediaType( type, subType, charSet );\n }", "public PagedList<V> convert(final PagedList<U> uList) {\n if (uList == null || uList.isEmpty()) {\n return new PagedList<V>() {\n @Override\n public Page<V> nextPage(String s) throws RestException, IOException {\n return null;\n }\n };\n }\n Page<U> uPage = uList.currentPage();\n final PageImpl<V> vPage = new PageImpl<>();\n vPage.setNextPageLink(uPage.nextPageLink());\n vPage.setItems(new ArrayList<V>());\n loadConvertedList(uPage, vPage);\n return new PagedList<V>(vPage) {\n @Override\n public Page<V> nextPage(String nextPageLink) throws RestException, IOException {\n Page<U> uPage = uList.nextPage(nextPageLink);\n final PageImpl<V> vPage = new PageImpl<>();\n vPage.setNextPageLink(uPage.nextPageLink());\n vPage.setItems(new ArrayList<V>());\n loadConvertedList(uPage, vPage);\n return vPage;\n }\n };\n }" ]
Returns the counters with keys as the first key and count as the total count of the inner counter for that key @return counter of type K1
[ "public Counter<K1> sumInnerCounter() {\r\n Counter<K1> summed = new ClassicCounter<K1>();\r\n for (K1 key : this.firstKeySet()) {\r\n summed.incrementCount(key, this.getCounter(key).totalCount());\r\n }\r\n return summed;\r\n }" ]
[ "public void forAllIndices(String template, Properties attributes) throws XDocletException\r\n {\r\n boolean processUnique = TypeConversionUtil.stringToBoolean(attributes.getProperty(ATTRIBUTE_UNIQUE), false);\r\n\r\n // first the default index\r\n _curIndexDef = _curTableDef.getIndex(null);\r\n if ((_curIndexDef != null) && (processUnique == _curIndexDef.isUnique()))\r\n {\r\n generate(template);\r\n }\r\n for (Iterator it = _curTableDef.getIndices(); it.hasNext(); )\r\n {\r\n _curIndexDef = (IndexDef)it.next();\r\n if (!_curIndexDef.isDefault() && (processUnique == _curIndexDef.isUnique()))\r\n { \r\n generate(template);\r\n }\r\n }\r\n _curIndexDef = null;\r\n }", "public static boolean isMethodNamed(MethodCallExpression methodCall, String methodNamePattern, Integer numArguments) {\r\n Expression method = methodCall.getMethod();\r\n\r\n // !important: performance enhancement\r\n boolean IS_NAME_MATCH = false;\r\n if (method instanceof ConstantExpression) {\r\n if (((ConstantExpression) method).getValue() instanceof String) {\r\n IS_NAME_MATCH = ((String)((ConstantExpression) method).getValue()).matches(methodNamePattern);\r\n }\r\n }\r\n\r\n if (IS_NAME_MATCH && numArguments != null) {\r\n return AstUtil.getMethodArguments(methodCall).size() == numArguments;\r\n }\r\n return IS_NAME_MATCH;\r\n }", "public static String getSerializedVectorClocks(List<VectorClock> vectorClocks) {\n List<VectorClockWrapper> vectorClockWrappers = new ArrayList<VectorClockWrapper>();\n for(VectorClock vc: vectorClocks) {\n vectorClockWrappers.add(new VectorClockWrapper(vc));\n }\n String serializedVC = \"\";\n try {\n serializedVC = mapper.writeValueAsString(vectorClockWrappers);\n } catch(Exception e) {\n e.printStackTrace();\n }\n return serializedVC;\n }", "public static final Date utc2date(Long time) {\n\n // don't accept negative values\n if (time == null || time < 0) return null;\n \n // add the timezone offset\n time += timezoneOffsetMillis(new Date(time));\n\n return new Date(time);\n }", "@Override\n public boolean setA(DMatrixRBlock A) {\n if( A.numRows < A.numCols )\n throw new IllegalArgumentException(\"Number of rows must be more than or equal to the number of columns. \" +\n \"Can't solve an underdetermined system.\");\n\n if( !decomposer.decompose(A))\n return false;\n\n this.QR = decomposer.getQR();\n\n return true;\n }", "private void initDatesPanel() {\n\n m_startLabel.setText(Messages.get().key(Messages.GUI_SERIALDATE_TIME_STARTTIME_0));\n m_startTime.setAllowInvalidValue(true);\n m_startTime.setValue(m_model.getStart());\n m_endLabel.setText(Messages.get().key(Messages.GUI_SERIALDATE_TIME_ENDTIME_0));\n m_endTime.setAllowInvalidValue(true);\n m_endTime.setValue(m_model.getEnd());\n m_seriesCheckBox.setText(Messages.get().key(Messages.GUI_SERIALDATE_SERIES_CHECKBOX_0));\n m_wholeDayCheckBox.setText(Messages.get().key(Messages.GUI_SERIALDATE_WHOLE_DAY_CHECKBOX_0));\n m_currentTillEndCheckBox.setText(Messages.get().key(Messages.GUI_SERIALDATE_CURRENT_TILL_END_CHECKBOX_0));\n m_currentTillEndCheckBox.getButton().setTitle(\n Messages.get().key(Messages.GUI_SERIALDATE_CURRENT_TILL_END_CHECKBOX_HELP_0));\n }", "private void initPropertyBundle() throws CmsLoaderException, CmsException, IOException {\n\n for (Locale l : m_locales) {\n String filePath = m_sitepath + m_basename + \"_\" + l.toString();\n CmsResource resource = null;\n if (m_cms.existsResource(\n filePath,\n CmsResourceFilter.requireType(\n OpenCms.getResourceManager().getResourceType(BundleType.PROPERTY.toString())))) {\n resource = m_cms.readResource(filePath);\n SortedProperties props = new SortedProperties();\n CmsFile file = m_cms.readFile(resource);\n props.load(\n new InputStreamReader(\n new ByteArrayInputStream(file.getContents()),\n CmsFileUtil.getEncoding(m_cms, file)));\n m_keyset.updateKeySet(null, props.keySet());\n m_bundleFiles.put(l, resource);\n }\n }\n\n }", "public static String chomp(String s) {\r\n if(s.length() == 0)\r\n return s;\r\n int l_1 = s.length() - 1;\r\n if (s.charAt(l_1) == '\\n') {\r\n return s.substring(0, l_1);\r\n }\r\n return s;\r\n }", "private void checkRowReader(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (!CHECKLEVEL_STRICT.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n \r\n String rowReaderName = classDef.getProperty(PropertyHelper.OJB_PROPERTY_ROW_READER);\r\n\r\n if (rowReaderName == null)\r\n {\r\n return;\r\n }\r\n\r\n try\r\n {\r\n InheritanceHelper helper = new InheritanceHelper();\r\n\r\n if (!helper.isSameOrSubTypeOf(rowReaderName, ROW_READER_INTERFACE))\r\n {\r\n throw new ConstraintException(\"The class \"+rowReaderName+\" specified as row-reader of class \"+classDef.getName()+\" does not implement the interface \"+ROW_READER_INTERFACE);\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"Could not find the class \"+ex.getMessage()+\" on the classpath while checking the row-reader class \"+rowReaderName+\" of class \"+classDef.getName());\r\n }\r\n }" ]
Classify stdin by senteces seperated by blank line @param readerWriter @return @throws IOException
[ "public boolean classifySentenceStdin(DocumentReaderAndWriter<IN> readerWriter)\r\n throws IOException\r\n {\r\n BufferedReader is = new BufferedReader(new InputStreamReader(System.in, flags.inputEncoding));\r\n String line;\r\n String text = \"\";\r\n String eol = \"\\n\";\r\n String sentence = \"<s>\";\r\n while ((line = is.readLine()) != null) {\r\n \t\r\n if (line.trim().equals(\"\")) {\r\n \t text += sentence + eol;\r\n \t ObjectBank<List<IN>> documents = makeObjectBankFromString(text, readerWriter);\r\n classifyAndWriteAnswers(documents, readerWriter);\r\n text = \"\";\r\n } else {\r\n \t text += line + eol;\r\n }\r\n }\r\n if (text.trim().equals(\"\")) {\r\n \treturn false;\r\n }\r\n return true;\r\n }" ]
[ "protected void addFacetPart(CmsSolrQuery query) {\n\n query.set(\"facet\", \"true\");\n String excludes = \"\";\n if (m_config.getIgnoreAllFacetFilters()\n || (!m_state.getCheckedEntries().isEmpty() && !m_config.getIsAndFacet())) {\n excludes = \"{!ex=\" + m_config.getIgnoreTags() + \"}\";\n }\n\n for (I_CmsFacetQueryItem q : m_config.getQueryList()) {\n query.add(\"facet.query\", excludes + q.getQuery());\n }\n }", "public List<Index<Field>> allIndexes() {\n List<Index<Field>> indexesOfAnyType = new ArrayList<Index<Field>>();\n indexesOfAnyType.addAll(listIndexType(null, ListableIndex.class));\n return indexesOfAnyType;\n }", "public CollectionRequest<Team> users(String team) {\n \n String path = String.format(\"/teams/%s/users\", team);\n return new CollectionRequest<Team>(this, Team.class, path, \"GET\");\n }", "public static Field getDeclaredFieldWithPath(Class<?> clazz, String path) {\n\n int lastDot = path.lastIndexOf('.');\n\n if (lastDot > -1) {\n String parentPath = path.substring(0, lastDot);\n String fieldName = path.substring(lastDot + 1);\n Field parentField = getDeclaredFieldWithPath(clazz, parentPath);\n return getDeclaredFieldInHierarchy(parentField.getType(), fieldName);\n } else {\n return getDeclaredFieldInHierarchy(clazz, path);\n }\n }", "public final void setFindDetails(boolean findDetails) {\n this.findDetails.set(findDetails);\n if (findDetails) {\n primeCache(); // Get details for any tracks that were already loaded on players.\n } else {\n // Inform our listeners, on the proper thread, that the detailed waveforms are no longer available\n final Set<DeckReference> dyingCache = new HashSet<DeckReference>(detailHotCache.keySet());\n detailHotCache.clear();\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (DeckReference deck : dyingCache) {\n deliverWaveformDetailUpdate(deck.player, null);\n }\n }\n });\n }\n }", "public void setOnCloseListener(@NonNull final android.support.v7.widget.SearchView.OnCloseListener listener) {\n if (searchView != null) {\n searchView.setOnCloseListener(new SearchView.OnCloseListener() {\n @Override public boolean onClose() {\n return listener.onClose();\n }\n });\n } else if (supportView != null) {\n supportView.setOnCloseListener(listener);\n } else {\n throw new IllegalStateException(ERROR_NO_SEARCHVIEW);\n }\n }", "public static byte[] getContentBytes(String stringUrl) throws IOException {\n URL url = new URL(stringUrl);\n byte[] data = MyStreamUtils.readContentBytes(url.openStream());\n return data;\n }", "protected String generateCacheKey(\n CmsObject cms,\n String targetSiteRoot,\n String detailPagePart,\n String absoluteLink) {\n\n return cms.getRequestContext().getSiteRoot() + \":\" + targetSiteRoot + \":\" + detailPagePart + absoluteLink;\n }", "private void init()\n {\n style = new BoxStyle(UNIT);\n textLine = new StringBuilder();\n textMetrics = null;\n graphicsPath = new Vector<PathSegment>();\n startPage = 0;\n endPage = Integer.MAX_VALUE;\n fontTable = new FontTable();\n }" ]
Creates a triangular matrix where the amount of fill is randomly selected too. @param upper true for upper triangular and false for lower @param N number of rows and columns er * @param minFill minimum fill fraction @param maxFill maximum fill fraction @param rand random number generator @return Random matrix
[ "public static DMatrixSparseCSC triangle( boolean upper , int N , double minFill , double maxFill , Random rand ) {\n int nz = (int)(((N-1)*(N-1)/2)*(rand.nextDouble()*(maxFill-minFill)+minFill))+N;\n\n if( upper ) {\n return triangleUpper(N,0,nz,-1,1,rand);\n } else {\n return triangleLower(N,0,nz,-1,1,rand);\n }\n }" ]
[ "private static void parseStencil(JSONObject modelJSON,\n Shape current) throws JSONException {\n // get stencil type\n if (modelJSON.has(\"stencil\")) {\n JSONObject stencil = modelJSON.getJSONObject(\"stencil\");\n // TODO other attributes of stencil\n String stencilString = \"\";\n if (stencil.has(\"id\")) {\n stencilString = stencil.getString(\"id\");\n }\n current.setStencil(new StencilType(stencilString));\n }\n }", "private void logOriginalResponseHistory(\n PluginResponse httpServletResponse, History history) throws URIException {\n RequestInformation requestInfo = requestInformation.get();\n if (requestInfo.handle && requestInfo.client.getIsActive()) {\n logger.info(\"Storing original response history\");\n history.setOriginalResponseHeaders(HttpUtilities.getHeaders(httpServletResponse));\n history.setOriginalResponseCode(Integer.toString(httpServletResponse.getStatus()));\n history.setOriginalResponseContentType(httpServletResponse.getContentType());\n history.setOriginalResponseData(httpServletResponse.getContentString());\n logger.info(\"Done storing\");\n }\n }", "public String[] getNormalizedLabels() {\n\t\tif(isValid()) {\n\t\t\treturn parsedHost.getNormalizedLabels();\n\t\t}\n\t\tif(host.length() == 0) {\n\t\t\treturn new String[0];\n\t\t}\n\t\treturn new String[] {host};\n\t}", "private void populateLeaf(String parentName, Row row, Task task)\n {\n if (row.getInteger(\"TASKID\") != null)\n {\n populateTask(row, task);\n }\n else\n {\n populateMilestone(row, task);\n }\n\n String name = task.getName();\n if (name == null || name.isEmpty())\n {\n task.setName(parentName);\n }\n }", "public static long count(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\toptions option = new options();\n\t\toption.set_count(true);\n\t\tsslcipher_individualcipher_binding response[] = (sslcipher_individualcipher_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}", "private static boolean syncWithMaster(final Resource domain, final PathElement hostElement) {\n final Resource host = domain.getChild(hostElement);\n assert host != null;\n\n final Set<String> profiles = new HashSet<>();\n final Set<String> serverGroups = new HashSet<>();\n final Set<String> socketBindings = new HashSet<>();\n\n for (final Resource.ResourceEntry serverConfig : host.getChildren(SERVER_CONFIG)) {\n final ModelNode model = serverConfig.getModel();\n final String group = model.require(GROUP).asString();\n if (!serverGroups.contains(group)) {\n serverGroups.add(group);\n }\n if (model.hasDefined(SOCKET_BINDING_GROUP)) {\n processSocketBindingGroup(domain, model.require(SOCKET_BINDING_GROUP).asString(), socketBindings);\n }\n\n }\n\n // process referenced server-groups\n for (final Resource.ResourceEntry serverGroup : domain.getChildren(SERVER_GROUP)) {\n // If we have an unreferenced server-group\n if (!serverGroups.remove(serverGroup.getName())) {\n return true;\n }\n final ModelNode model = serverGroup.getModel();\n\n final String profile = model.require(PROFILE).asString();\n // Process the profile\n processProfile(domain, profile, profiles);\n // Process the socket-binding-group\n processSocketBindingGroup(domain, model.require(SOCKET_BINDING_GROUP).asString(), socketBindings);\n }\n // If we are missing a server group\n if (!serverGroups.isEmpty()) {\n return true;\n }\n // Process profiles\n for (final Resource.ResourceEntry profile : domain.getChildren(PROFILE)) {\n // We have an unreferenced profile\n if (!profiles.remove(profile.getName())) {\n return true;\n }\n }\n // We are missing a profile\n if (!profiles.isEmpty()) {\n return true;\n }\n // Process socket-binding groups\n for (final Resource.ResourceEntry socketBindingGroup : domain.getChildren(SOCKET_BINDING_GROUP)) {\n // We have an unreferenced socket-binding group\n if (!socketBindings.remove(socketBindingGroup.getName())) {\n return true;\n }\n }\n // We are missing a socket-binding group\n if (!socketBindings.isEmpty()) {\n return true;\n }\n // Looks good!\n return false;\n }", "protected I_CmsSearchConfigurationFacetField parseFieldFacet(JSONObject fieldFacetObject) {\n\n try {\n String field = fieldFacetObject.getString(JSON_KEY_FACET_FIELD);\n String name = parseOptionalStringValue(fieldFacetObject, JSON_KEY_FACET_NAME);\n String label = parseOptionalStringValue(fieldFacetObject, JSON_KEY_FACET_LABEL);\n Integer minCount = parseOptionalIntValue(fieldFacetObject, JSON_KEY_FACET_MINCOUNT);\n Integer limit = parseOptionalIntValue(fieldFacetObject, JSON_KEY_FACET_LIMIT);\n String prefix = parseOptionalStringValue(fieldFacetObject, JSON_KEY_FACET_PREFIX);\n String sorder = parseOptionalStringValue(fieldFacetObject, JSON_KEY_FACET_ORDER);\n I_CmsSearchConfigurationFacet.SortOrder order;\n try {\n order = I_CmsSearchConfigurationFacet.SortOrder.valueOf(sorder);\n } catch (Exception e) {\n order = null;\n }\n String filterQueryModifier = parseOptionalStringValue(fieldFacetObject, JSON_KEY_FACET_FILTERQUERYMODIFIER);\n Boolean isAndFacet = parseOptionalBooleanValue(fieldFacetObject, JSON_KEY_FACET_ISANDFACET);\n List<String> preselection = parseOptionalStringValues(fieldFacetObject, JSON_KEY_FACET_PRESELECTION);\n Boolean ignoreFilterAllFacetFilters = parseOptionalBooleanValue(\n fieldFacetObject,\n JSON_KEY_FACET_IGNOREALLFACETFILTERS);\n return new CmsSearchConfigurationFacetField(\n field,\n name,\n minCount,\n limit,\n prefix,\n label,\n order,\n filterQueryModifier,\n isAndFacet,\n preselection,\n ignoreFilterAllFacetFilters);\n } catch (JSONException e) {\n LOG.error(\n Messages.get().getBundle().key(Messages.ERR_FIELD_FACET_MANDATORY_KEY_MISSING_1, JSON_KEY_FACET_FIELD),\n e);\n return null;\n }\n }", "protected void addProcessedData(List<List<CRFDatum<Collection<String>, String>>> processedData, int[][][][] data,\r\n int[][] labels, int offset) {\r\n for (int i = 0, pdSize = processedData.size(); i < pdSize; i++) {\r\n int dataIndex = i + offset;\r\n List<CRFDatum<Collection<String>, String>> document = processedData.get(i);\r\n int dsize = document.size();\r\n labels[dataIndex] = new int[dsize];\r\n data[dataIndex] = new int[dsize][][];\r\n for (int j = 0; j < dsize; j++) {\r\n CRFDatum<Collection<String>, String> crfDatum = document.get(j);\r\n // add label, they are offset by extra context\r\n labels[dataIndex][j] = classIndex.indexOf(crfDatum.label());\r\n // add features\r\n List<Collection<String>> cliques = crfDatum.asFeatures();\r\n int csize = cliques.size();\r\n data[dataIndex][j] = new int[csize][];\r\n for (int k = 0; k < csize; k++) {\r\n Collection<String> features = cliques.get(k);\r\n\r\n // Debug only: Remove\r\n // if (j < windowSize) {\r\n // System.err.println(\"addProcessedData: Features Size: \" +\r\n // features.size());\r\n // }\r\n\r\n data[dataIndex][j][k] = new int[features.size()];\r\n\r\n int m = 0;\r\n try {\r\n for (String feature : features) {\r\n // System.err.println(\"feature \" + feature);\r\n // if (featureIndex.indexOf(feature)) ;\r\n if (featureIndex == null) {\r\n System.out.println(\"Feature is NULL!\");\r\n }\r\n data[dataIndex][j][k][m] = featureIndex.indexOf(feature);\r\n m++;\r\n }\r\n } catch (Exception e) {\r\n e.printStackTrace();\r\n System.err.printf(\"[index=%d, j=%d, k=%d, m=%d]\\n\", dataIndex, j, k, m);\r\n System.err.println(\"data.length \" + data.length);\r\n System.err.println(\"data[dataIndex].length \" + data[dataIndex].length);\r\n System.err.println(\"data[dataIndex][j].length \" + data[dataIndex][j].length);\r\n System.err.println(\"data[dataIndex][j][k].length \" + data[dataIndex][j].length);\r\n System.err.println(\"data[dataIndex][j][k][m] \" + data[dataIndex][j][k][m]);\r\n return;\r\n }\r\n }\r\n }\r\n }\r\n }", "public 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 }" ]
Groups all of the metadata cache files that are candidates for auto-attachment to player slots into lists that are keyed by the playlist ID used to create the cache file. Files that cache all tracks have a playlist ID of 0. @return a map from playlist ID to the caches holding tracks from that playlist
[ "private static Map<Integer, LinkedList<MetadataCache>> gatherCandidateAttachmentGroups() {\n Map<Integer,LinkedList<MetadataCache>> candidateGroups = new TreeMap<Integer, LinkedList<MetadataCache>>();\n final Iterator<File> iterator = MetadataFinder.getInstance().getAutoAttachCacheFiles().iterator();\n while (iterator.hasNext()) {\n final File file = iterator.next();\n try {\n final MetadataCache candidate = new MetadataCache(file);\n if (candidateGroups.get(candidate.sourcePlaylist) == null) {\n candidateGroups.put(candidate.sourcePlaylist, new LinkedList<MetadataCache>());\n }\n candidateGroups.get(candidate.sourcePlaylist).add(candidate);\n } catch (Exception e) {\n logger.error(\"Unable to open metadata cache file \" + file + \", discarding\", e);\n iterator.remove();\n }\n }\n return candidateGroups;\n }" ]
[ "private Map<Set<ServerIdentity>, ModelNode> getDeploymentOverlayOperations(ModelNode operation,\n ModelNode host) {\n final PathAddress realAddress = PathAddress.pathAddress(operation.get(OP_ADDR));\n if (realAddress.size() == 0 && COMPOSITE.equals(operation.get(OP).asString())) {\n //We have a composite operation resulting from a transformation to redeploy affected deployments\n //See redeploying deployments affected by an overlay.\n ModelNode serverOp = operation.clone();\n Map<ServerIdentity, Operations.CompositeOperationBuilder> composite = new HashMap<>();\n for (ModelNode step : serverOp.get(STEPS).asList()) {\n ModelNode newStep = step.clone();\n String groupName = PathAddress.pathAddress(step.get(OP_ADDR)).getElement(0).getValue();\n newStep.get(OP_ADDR).set(PathAddress.pathAddress(step.get(OP_ADDR)).subAddress(1).toModelNode());\n Set<ServerIdentity> servers = getServersForGroup(groupName, host, localHostName, serverProxies);\n for(ServerIdentity server : servers) {\n if(!composite.containsKey(server)) {\n composite.put(server, Operations.CompositeOperationBuilder.create());\n }\n composite.get(server).addStep(newStep);\n }\n if(!servers.isEmpty()) {\n newStep.get(OP_ADDR).set(PathAddress.pathAddress(step.get(OP_ADDR)).subAddress(1).toModelNode());\n }\n }\n if(!composite.isEmpty()) {\n Map<Set<ServerIdentity>, ModelNode> result = new HashMap<>();\n for(Entry<ServerIdentity, Operations.CompositeOperationBuilder> entry : composite.entrySet()) {\n result.put(Collections.singleton(entry.getKey()), entry.getValue().build().getOperation());\n }\n return result;\n }\n return Collections.emptyMap();\n }\n final Set<ServerIdentity> allServers = getAllRunningServers(host, localHostName, serverProxies);\n return Collections.singletonMap(allServers, operation.clone());\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 }", "public static Collection<MonetaryAmountFactory<?>> getAmountFactories(MonetaryAmountFactoryQuery query) {\n return Optional.ofNullable(monetaryAmountsSingletonQuerySpi()).orElseThrow(() -> new MonetaryException(\n \"No MonetaryAmountsSingletonQuerySpi loaded, query functionality is not available.\"))\n .getAmountFactories(query);\n }", "private static long hexdump(InputStream is, PrintWriter pw) throws Exception\n {\n byte[] buffer = new byte[BUFFER_SIZE];\n long byteCount = 0;\n\n char c;\n int loop;\n int count;\n StringBuilder sb = new StringBuilder();\n\n while (true)\n {\n count = is.read(buffer);\n if (count == -1)\n {\n break;\n }\n\n byteCount += count;\n\n sb.setLength(0);\n\n for (loop = 0; loop < count; loop++)\n {\n sb.append(\" \");\n sb.append(HEX_DIGITS[(buffer[loop] & 0xF0) >> 4]);\n sb.append(HEX_DIGITS[buffer[loop] & 0x0F]);\n }\n\n while (loop < BUFFER_SIZE)\n {\n sb.append(\" \");\n ++loop;\n }\n\n sb.append(\" \");\n\n for (loop = 0; loop < count; loop++)\n {\n c = (char) buffer[loop];\n if (c > 200 || c < 27)\n {\n c = ' ';\n }\n\n sb.append(c);\n }\n\n pw.println(sb.toString());\n }\n\n return (byteCount);\n }", "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 }", "static String toFormattedString(final String iban) {\n final StringBuilder ibanBuffer = new StringBuilder(iban);\n final int length = ibanBuffer.length();\n\n for (int i = 0; i < length / 4; i++) {\n ibanBuffer.insert((i + 1) * 4 + i, ' ');\n }\n\n return ibanBuffer.toString().trim();\n }", "protected void generateMopCalls(LinkedList<MethodNode> mopCalls, boolean useThis) {\n for (MethodNode method : mopCalls) {\n String name = getMopMethodName(method, useThis);\n Parameter[] parameters = method.getParameters();\n String methodDescriptor = BytecodeHelper.getMethodDescriptor(method.getReturnType(), method.getParameters());\n MethodVisitor mv = controller.getClassVisitor().visitMethod(ACC_PUBLIC | ACC_SYNTHETIC, name, methodDescriptor, null, null);\n controller.setMethodVisitor(mv);\n mv.visitVarInsn(ALOAD, 0);\n int newRegister = 1;\n OperandStack operandStack = controller.getOperandStack();\n for (Parameter parameter : parameters) {\n ClassNode type = parameter.getType();\n operandStack.load(parameter.getType(), newRegister);\n // increment to next register, double/long are using two places\n newRegister++;\n if (type == ClassHelper.double_TYPE || type == ClassHelper.long_TYPE) newRegister++;\n }\n operandStack.remove(parameters.length);\n ClassNode declaringClass = method.getDeclaringClass();\n // JDK 8 support for default methods in interfaces\n // this should probably be strenghtened when we support the A.super.foo() syntax\n int opcode = declaringClass.isInterface()?INVOKEINTERFACE:INVOKESPECIAL;\n mv.visitMethodInsn(opcode, BytecodeHelper.getClassInternalName(declaringClass), method.getName(), methodDescriptor, opcode == INVOKEINTERFACE);\n BytecodeHelper.doReturn(mv, method.getReturnType());\n mv.visitMaxs(0, 0);\n mv.visitEnd();\n controller.getClassNode().addMethod(name, ACC_PUBLIC | ACC_SYNTHETIC, method.getReturnType(), parameters, null, null);\n }\n }", "private IndexedContainer createContainerForDescriptorEditing() {\n\n IndexedContainer container = new IndexedContainer();\n\n // create properties\n container.addContainerProperty(TableProperty.KEY, String.class, \"\");\n container.addContainerProperty(TableProperty.DESCRIPTION, String.class, \"\");\n container.addContainerProperty(TableProperty.DEFAULT, String.class, \"\");\n\n // add entries\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 Object itemId = container.addItem();\n Item item = container.getItem(itemId);\n String key = m_descContent.getValue(prefix + Descriptor.N_KEY, Descriptor.LOCALE).getStringValue(m_cms);\n item.getItemProperty(TableProperty.KEY).setValue(key);\n item.getItemProperty(TableProperty.DESCRIPTION).setValue(\n m_descContent.getValue(prefix + Descriptor.N_DESCRIPTION, Descriptor.LOCALE).getStringValue(m_cms));\n item.getItemProperty(TableProperty.DEFAULT).setValue(\n m_descContent.getValue(prefix + Descriptor.N_DEFAULT, Descriptor.LOCALE).getStringValue(m_cms));\n }\n\n return container;\n\n }", "public static ManagementProtocolHeader parse(DataInput input) throws IOException {\n validateSignature(input);\n expectHeader(input, ManagementProtocol.VERSION_FIELD);\n int version = input.readInt();\n expectHeader(input, ManagementProtocol.TYPE);\n byte type = input.readByte();\n switch (type) {\n case ManagementProtocol.TYPE_REQUEST:\n return new ManagementRequestHeader(version, input);\n case ManagementProtocol.TYPE_RESPONSE:\n return new ManagementResponseHeader(version, input);\n case ManagementProtocol.TYPE_BYE_BYE:\n return new ManagementByeByeHeader(version);\n case ManagementProtocol.TYPE_PING:\n return new ManagementPingHeader(version);\n case ManagementProtocol.TYPE_PONG:\n return new ManagementPongHeader(version);\n default:\n throw ProtocolLogger.ROOT_LOGGER.invalidType(\"0x\" + Integer.toHexString(type));\n }\n }" ]
Get the title and read the Title property according the provided locale. @return The map from locales to the locale specific titles.
[ "public Map<String, String> getTitleLocale() {\n\n if (m_localeTitles == null) {\n m_localeTitles = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n public Object transform(Object inputLocale) {\n\n Locale locale = null;\n if (null != inputLocale) {\n if (inputLocale instanceof Locale) {\n locale = (Locale)inputLocale;\n } else if (inputLocale instanceof String) {\n try {\n locale = LocaleUtils.toLocale((String)inputLocale);\n } catch (IllegalArgumentException | NullPointerException e) {\n // do nothing, just go on without locale\n }\n }\n }\n return getLocaleSpecificTitle(locale);\n }\n\n });\n }\n return m_localeTitles;\n }" ]
[ "public static base_response flush(nitro_service client, cachecontentgroup resource) throws Exception {\n\t\tcachecontentgroup flushresource = new cachecontentgroup();\n\t\tflushresource.name = resource.name;\n\t\tflushresource.query = resource.query;\n\t\tflushresource.host = resource.host;\n\t\tflushresource.selectorvalue = resource.selectorvalue;\n\t\tflushresource.force = resource.force;\n\t\treturn flushresource.perform_operation(client,\"flush\");\n\t}", "private CmsXmlContent unmarshalXmlContent(CmsFile file) throws CmsXmlException {\n\n CmsXmlContent content = CmsXmlContentFactory.unmarshal(m_cms, file);\n content.setAutoCorrectionEnabled(true);\n content.correctXmlStructure(m_cms);\n\n return content;\n }", "public static void unzip(Path zip, Path target) throws IOException {\n try (final ZipFile zipFile = new ZipFile(zip.toFile())){\n unzip(zipFile, target);\n }\n }", "public static void writeCorrelationId(Message message, String correlationId) {\n if (!(message instanceof SoapMessage)) {\n return;\n }\n SoapMessage soapMessage = (SoapMessage) message;\n Header hdCorrelationId = soapMessage.getHeader(CORRELATION_ID_QNAME);\n if (hdCorrelationId != null) {\n LOG.warning(\"CorrelationId already existing in soap header, need not to write CorrelationId header.\");\n return;\n }\n if ((soapMessage.getContent(javax.xml.stream.XMLStreamWriter.class) != null)\n && (soapMessage.getContent(javax.xml.stream.XMLStreamWriter.class) instanceof SAAJStreamWriter)\n && (((SAAJStreamWriter) soapMessage.getContent(javax.xml.stream.XMLStreamWriter.class))\n .getDocument()\n .getElementsByTagNameNS(\"http://www.talend.com/esb/sam/correlationId/v1\",\n \"correlationId\").getLength() > 0)) {\n LOG.warning(\"CorrelationId already existing in soap header, need not to write CorrelationId header.\");\n return;\n }\n\n try {\n soapMessage.getHeaders().add(\n new Header(CORRELATION_ID_QNAME, correlationId, new JAXBDataBinding(String.class)));\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Stored correlationId '\" + correlationId + \"' in soap header: \"\n + CORRELATION_ID_QNAME);\n }\n } catch (JAXBException e) {\n LOG.log(Level.SEVERE, \"Couldn't create correlationId header.\", e);\n }\n\n }", "public static systemsession[] get(nitro_service service, Long sid[]) throws Exception{\n\t\tif (sid !=null && sid.length>0) {\n\t\t\tsystemsession response[] = new systemsession[sid.length];\n\t\t\tsystemsession obj[] = new systemsession[sid.length];\n\t\t\tfor (int i=0;i<sid.length;i++) {\n\t\t\t\tobj[i] = new systemsession();\n\t\t\t\tobj[i].set_sid(sid[i]);\n\t\t\t\tresponse[i] = (systemsession) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "public boolean ifTaskCompletedSuccessOrFailureFromResponse(\n ResponseOnSingeRequest myResponse) {\n\n boolean isCompleted = false;\n try {\n\n if (myResponse == null || myResponse.isFailObtainResponse()) {\n return isCompleted;\n }\n\n String responseBody = myResponse.getResponseBody();\n if (responseBody.matches(successRegex)\n || responseBody.matches(failureRegex)) {\n isCompleted = true;\n }\n\n } catch (Exception t) {\n logger.error(\"fail \" + t);\n\n }\n return isCompleted;\n }", "public void clear() {\n\t\tfor (Bean bean : beans.values()) {\n\t\t\tif (null != bean.destructionCallback) {\n\t\t\t\tbean.destructionCallback.run();\n\t\t\t}\n\t\t}\n\t\tbeans.clear();\n\t}", "protected void removeWatermark(URLTemplate itemUrl) {\n URL watermarkUrl = itemUrl.build(this.getAPI().getBaseURL(), this.getID());\n URL url = WATERMARK_URL_TEMPLATE.build(watermarkUrl.toString());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"DELETE\");\n BoxAPIResponse response = request.send();\n response.disconnect();\n }", "@SuppressWarnings(\"unused\")\n public Phonenumber.PhoneNumber getPhoneNumber() {\n try {\n String iso = null;\n if (mSelectedCountry != null) {\n iso = mSelectedCountry.getIso();\n }\n return mPhoneUtil.parse(mPhoneEdit.getText().toString(), iso);\n } catch (NumberParseException ignored) {\n return null;\n }\n }" ]
Converts from partitionId to nodeId. The list of partition IDs, partitionIds, is expected to be a "replicating partition list", i.e., the mapping from partition ID to node ID should be one to one. @param partitionIds List of partition IDs for which to find the Node ID for the Node that owns the partition. @return List of node ids, one for each partition ID in partitionIds @throws VoldemortException If multiple partition IDs in partitionIds map to the same Node ID.
[ "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 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 }", "private static void validateAsMongoDBCollectionName(String collectionName) {\n\t\tContracts.assertStringParameterNotEmpty( collectionName, \"requestedName\" );\n\t\t//Yes it has some strange requirements.\n\t\tif ( collectionName.startsWith( \"system.\" ) ) {\n\t\t\tthrow log.collectionNameHasInvalidSystemPrefix( collectionName );\n\t\t}\n\t\telse if ( collectionName.contains( \"\\u0000\" ) ) {\n\t\t\tthrow log.collectionNameContainsNULCharacter( collectionName );\n\t\t}\n\t\telse if ( collectionName.contains( \"$\" ) ) {\n\t\t\tthrow log.collectionNameContainsDollarCharacter( collectionName );\n\t\t}\n\t}", "public void close() throws IOException {\n\t\tSystem.out.println(\"Serialized \"\n\t\t\t\t+ this.jsonSerializer.getEntityDocumentCount()\n\t\t\t\t+ \" item documents to JSON file \" + OUTPUT_FILE_NAME + \".\");\n\t\tthis.jsonSerializer.close();\n\t}", "public Map<String, CmsJspCategoryAccessBean> getSubCategories() {\n\n if (m_subCategories == null) {\n m_subCategories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n @SuppressWarnings(\"synthetic-access\")\n public Object transform(Object pathPrefix) {\n\n return new CmsJspCategoryAccessBean(m_cms, m_categories, (String)pathPrefix);\n }\n\n });\n }\n return m_subCategories;\n }", "public static Node removePartitionFromNode(final Node node, Integer donatedPartition) {\n return UpdateClusterUtils.removePartitionsFromNode(node, Sets.newHashSet(donatedPartition));\n }", "public static nsrpcnode[] get(nitro_service service, String ipaddress[]) throws Exception{\n\t\tif (ipaddress !=null && ipaddress.length>0) {\n\t\t\tnsrpcnode response[] = new nsrpcnode[ipaddress.length];\n\t\t\tnsrpcnode obj[] = new nsrpcnode[ipaddress.length];\n\t\t\tfor (int i=0;i<ipaddress.length;i++) {\n\t\t\t\tobj[i] = new nsrpcnode();\n\t\t\t\tobj[i].set_ipaddress(ipaddress[i]);\n\t\t\t\tresponse[i] = (nsrpcnode) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "public PhotoList<Photo> getUntagged(int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_UNTAGGED);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", Integer.toString(perPage));\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", Integer.toString(page));\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n PhotoList<Photo> photos = PhotoUtils.createPhotoList(photosElement);\r\n return photos;\r\n }", "public Collection<Size> getSizes(String photoId, boolean sign) throws FlickrException {\r\n SizeList<Size> sizes = new SizeList<Size>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_SIZES);\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 Element sizesElement = response.getPayload();\r\n sizes.setIsCanBlog(\"1\".equals(sizesElement.getAttribute(\"canblog\")));\r\n sizes.setIsCanDownload(\"1\".equals(sizesElement.getAttribute(\"candownload\")));\r\n sizes.setIsCanPrint(\"1\".equals(sizesElement.getAttribute(\"canprint\")));\r\n NodeList sizeNodes = sizesElement.getElementsByTagName(\"size\");\r\n for (int i = 0; i < sizeNodes.getLength(); i++) {\r\n Element sizeElement = (Element) sizeNodes.item(i);\r\n Size size = new Size();\r\n size.setLabel(sizeElement.getAttribute(\"label\"));\r\n size.setWidth(sizeElement.getAttribute(\"width\"));\r\n size.setHeight(sizeElement.getAttribute(\"height\"));\r\n size.setSource(sizeElement.getAttribute(\"source\"));\r\n size.setUrl(sizeElement.getAttribute(\"url\"));\r\n size.setMedia(sizeElement.getAttribute(\"media\"));\r\n sizes.add(size);\r\n }\r\n return sizes;\r\n }", "public static base_responses update(nitro_service client, nspbr6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnspbr6 updateresources[] = new nspbr6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nspbr6();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].action = resources[i].action;\n\t\t\t\tupdateresources[i].srcipv6 = resources[i].srcipv6;\n\t\t\t\tupdateresources[i].srcipop = resources[i].srcipop;\n\t\t\t\tupdateresources[i].srcipv6val = resources[i].srcipv6val;\n\t\t\t\tupdateresources[i].srcport = resources[i].srcport;\n\t\t\t\tupdateresources[i].srcportop = resources[i].srcportop;\n\t\t\t\tupdateresources[i].srcportval = resources[i].srcportval;\n\t\t\t\tupdateresources[i].destipv6 = resources[i].destipv6;\n\t\t\t\tupdateresources[i].destipop = resources[i].destipop;\n\t\t\t\tupdateresources[i].destipv6val = resources[i].destipv6val;\n\t\t\t\tupdateresources[i].destport = resources[i].destport;\n\t\t\t\tupdateresources[i].destportop = resources[i].destportop;\n\t\t\t\tupdateresources[i].destportval = resources[i].destportval;\n\t\t\t\tupdateresources[i].srcmac = resources[i].srcmac;\n\t\t\t\tupdateresources[i].protocol = resources[i].protocol;\n\t\t\t\tupdateresources[i].protocolnumber = resources[i].protocolnumber;\n\t\t\t\tupdateresources[i].vlan = resources[i].vlan;\n\t\t\t\tupdateresources[i].Interface = resources[i].Interface;\n\t\t\t\tupdateresources[i].priority = resources[i].priority;\n\t\t\t\tupdateresources[i].msr = resources[i].msr;\n\t\t\t\tupdateresources[i].monitor = resources[i].monitor;\n\t\t\t\tupdateresources[i].nexthop = resources[i].nexthop;\n\t\t\t\tupdateresources[i].nexthopval = resources[i].nexthopval;\n\t\t\t\tupdateresources[i].nexthopvlan = resources[i].nexthopvlan;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}" ]
Get the value of a Annotation in a class declaration. @param classType @param annotationType @param attributeName @return the value of the annotation as String or null if something goes wrong
[ "public static <T, A extends Annotation> String getClassAnnotationValue(Class<T> classType, Class<A> annotationType, String attributeName) {\n\t\tString value = null;\n\t\tAnnotation annotation = classType.getAnnotation(annotationType);\n\t\tif (annotation != null) {\n\t\t\ttry {\n\t\t\t\tvalue = (String) annotation.annotationType().getMethod(attributeName).invoke(annotation);\n\t\t\t} catch (Exception ex) {}\n\t\t}\n\t\treturn value;\n\t}" ]
[ "protected void watchConnection(ConnectionHandle connectionHandle) {\r\n\t\tString message = captureStackTrace(UNCLOSED_EXCEPTION_MESSAGE);\r\n\t\tthis.closeConnectionExecutor.submit(new CloseThreadMonitor(Thread.currentThread(), connectionHandle, message, this.closeConnectionWatchTimeoutInMs));\r\n\t}", "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 }", "public SelectIterator<T, ID> buildIterator(BaseDaoImpl<T, ID> classDao, ConnectionSource connectionSource,\n\t\t\tint resultFlags, ObjectCache objectCache) throws SQLException {\n\t\tprepareQueryForAll();\n\t\treturn buildIterator(classDao, connectionSource, preparedQueryForAll, objectCache, resultFlags);\n\t}", "public Boolean getBoolean(int field, String falseText)\n {\n Boolean result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n result = ((m_fields[field].equalsIgnoreCase(falseText) == true) ? Boolean.FALSE : Boolean.TRUE);\n }\n else\n {\n result = null;\n }\n\n return (result);\n }", "public double computeLikelihoodP() {\n double ret = 1.0;\n\n for( int i = 0; i < r.numRows; i++ ) {\n double a = r.get(i,0);\n\n ret *= Math.exp(-a*a/2.0);\n }\n\n return ret;\n }", "private static AbstractProject<?, ?> getProject(String fullName) {\n Item item = Hudson.getInstance().getItemByFullName(fullName);\n if (item != null && item instanceof AbstractProject) {\n return (AbstractProject<?, ?>) item;\n }\n return null;\n }", "public static void main(String[] args) throws Exception {\r\n StringUtils.printErrInvocationString(\"CMMClassifier\", args);\r\n\r\n Properties props = StringUtils.argsToProperties(args);\r\n CMMClassifier cmm = new CMMClassifier<CoreLabel>(props);\r\n String testFile = cmm.flags.testFile;\r\n String textFile = cmm.flags.textFile;\r\n String loadPath = cmm.flags.loadClassifier;\r\n String serializeTo = cmm.flags.serializeTo;\r\n\r\n // cmm.crossValidateTrainAndTest(trainFile);\r\n if (loadPath != null) {\r\n cmm.loadClassifierNoExceptions(loadPath, props);\r\n } else if (cmm.flags.loadJarClassifier != null) {\r\n cmm.loadJarClassifier(cmm.flags.loadJarClassifier, props);\r\n } else if (cmm.flags.trainFile != null) {\r\n if (cmm.flags.biasedTrainFile != null) {\r\n cmm.trainSemiSup();\r\n } else {\r\n cmm.train();\r\n }\r\n } else {\r\n cmm.loadDefaultClassifier();\r\n }\r\n\r\n if (serializeTo != null) {\r\n cmm.serializeClassifier(serializeTo);\r\n }\r\n\r\n if (testFile != null) {\r\n cmm.classifyAndWriteAnswers(testFile, cmm.makeReaderAndWriter());\r\n } else if (cmm.flags.testFiles != null) {\r\n cmm.classifyAndWriteAnswers(cmm.flags.baseTestDir, cmm.flags.testFiles,\r\n cmm.makeReaderAndWriter());\r\n }\r\n\r\n if (textFile != null) {\r\n DocumentReaderAndWriter readerAndWriter =\r\n new PlainTextDocumentReaderAndWriter();\r\n cmm.classifyAndWriteAnswers(textFile, readerAndWriter);\r\n }\r\n }", "private void handleArchiveByFile(Predicate<String> filter, File archive, List<String> discoveredFiles)\n {\n try\n {\n try (ZipFile zip = new ZipFile(archive))\n {\n Enumeration<? extends ZipEntry> entries = zip.entries();\n \n while (entries.hasMoreElements())\n {\n ZipEntry entry = entries.nextElement();\n String name = entry.getName();\n if (filter.accept(name))\n discoveredFiles.add(name);\n }\n }\n }\n catch (IOException e)\n {\n throw new RuntimeException(\"Error handling file \" + archive, e);\n }\n }", "protected DateTimeException _peelDTE(DateTimeException e) {\n while (true) {\n Throwable t = e.getCause();\n if (t != null && t instanceof DateTimeException) {\n e = (DateTimeException) t;\n continue;\n }\n break;\n }\n return e;\n }" ]
Assigns this retention policy to a metadata template, optionally with certain field values. @param templateID the ID of the metadata template to apply to. @param fieldFilters optional field value filters. @return info about the created assignment.
[ "public BoxRetentionPolicyAssignment.Info assignToMetadataTemplate(String templateID,\r\n MetadataFieldFilter... fieldFilters) {\r\n return BoxRetentionPolicyAssignment.createAssignmentToMetadata(this.getAPI(), this.getID(), templateID,\r\n fieldFilters);\r\n }" ]
[ "public static int byteSizeOf(Bitmap bitmap) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {\n return bitmap.getAllocationByteCount();\n } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {\n return bitmap.getByteCount();\n } else {\n return bitmap.getRowBytes() * bitmap.getHeight();\n }\n }", "public <X> Set<DisposalMethod<X, ?>> resolveDisposalBeans(Set<Type> types, Set<Annotation> qualifiers, AbstractClassBean<X> declaringBean) {\n // We can always cache as this is only ever called by Weld where we avoid non-static inner classes for annotation literals\n Set<DisposalMethod<X, ?>> beans = cast(disposalMethodResolver.resolve(new ResolvableBuilder(manager).addTypes(types).addQualifiers(qualifiers).setDeclaringBean(declaringBean).create(), true));\n resolvedDisposalBeans.addAll(beans);\n return Collections.unmodifiableSet(beans);\n }", "public static void reset() {\n for (Object name : Collections.list(MAP_KEY_TO_SCOPE.keys())) {\n closeScope(name);\n }\n ConfigurationHolder.configuration.onScopeForestReset();\n ScopeImpl.resetUnBoundProviders();\n }", "private Task readTask(ChildTaskContainer parent, Integer id)\n {\n Table a0 = getTable(\"A0TAB\");\n Table a1 = getTable(\"A1TAB\");\n Table a2 = getTable(\"A2TAB\");\n Table a3 = getTable(\"A3TAB\");\n Table a4 = getTable(\"A4TAB\");\n\n Task task = parent.addTask();\n MapRow a1Row = a1.find(id);\n MapRow a2Row = a2.find(id);\n\n setFields(A0TAB_FIELDS, a0.find(id), task);\n setFields(A1TAB_FIELDS, a1Row, task);\n setFields(A2TAB_FIELDS, a2Row, task);\n setFields(A3TAB_FIELDS, a3.find(id), task);\n setFields(A5TAB_FIELDS, a4.find(id), task);\n\n task.setStart(task.getEarlyStart());\n task.setFinish(task.getEarlyFinish());\n if (task.getName() == null)\n {\n task.setName(task.getText(1));\n }\n\n m_eventManager.fireTaskReadEvent(task);\n\n return task;\n }", "public static clusternodegroup[] get(nitro_service service) throws Exception{\n\t\tclusternodegroup obj = new clusternodegroup();\n\t\tclusternodegroup[] response = (clusternodegroup[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public void loadModel(GVRAndroidResource avatarResource, String attachBone)\n {\n EnumSet<GVRImportSettings> settings = GVRImportSettings.getRecommendedSettingsWith(EnumSet.of(GVRImportSettings.OPTIMIZE_GRAPH, GVRImportSettings.NO_ANIMATION));\n GVRContext ctx = mAvatarRoot.getGVRContext();\n GVRResourceVolume volume = new GVRResourceVolume(ctx, avatarResource);\n GVRSceneObject modelRoot = new GVRSceneObject(ctx);\n GVRSceneObject boneObject;\n int boneIndex;\n\n if (mSkeleton == null)\n {\n throw new IllegalArgumentException(\"Cannot attach model to avatar - there is no skeleton\");\n }\n boneIndex = mSkeleton.getBoneIndex(attachBone);\n if (boneIndex < 0)\n {\n throw new IllegalArgumentException(attachBone + \" is not a bone in the avatar skeleton\");\n }\n boneObject = mSkeleton.getBone(boneIndex);\n if (boneObject == null)\n {\n throw new IllegalArgumentException(attachBone +\n \" does not have a bone object in the avatar skeleton\");\n }\n boneObject.addChildObject(modelRoot);\n ctx.getAssetLoader().loadModel(volume, modelRoot, settings, false, mLoadModelHandler);\n }", "public void installApp(Functions.Func callback) {\n if (isPwaSupported()) {\n appInstaller = new AppInstaller(callback);\n appInstaller.prompt();\n }\n }", "public static void addToListIfNotExists(List<String> list, String value) {\n boolean found = false;\n for (String item : list) {\n if (item.equalsIgnoreCase(value)) {\n found = true;\n break;\n }\n }\n if (!found) {\n list.add(value);\n }\n }", "private PersistenceBrokerException createException(final Exception ex, String message, final Object objectToIdentify, Class topLevelClass, Class realClass, Object[] pks)\r\n {\r\n final String eol = SystemUtils.LINE_SEPARATOR;\r\n StringBuffer msg = new StringBuffer();\r\n if(message == null)\r\n {\r\n msg.append(\"Unexpected error: \");\r\n }\r\n else\r\n {\r\n msg.append(message).append(\" :\");\r\n }\r\n if(topLevelClass != null) msg.append(eol).append(\"objectTopLevelClass=\").append(topLevelClass.getName());\r\n if(realClass != null) msg.append(eol).append(\"objectRealClass=\").append(realClass.getName());\r\n if(pks != null) msg.append(eol).append(\"pkValues=\").append(ArrayUtils.toString(pks));\r\n if(objectToIdentify != null) msg.append(eol).append(\"object to identify: \").append(objectToIdentify);\r\n if(ex != null)\r\n {\r\n // add causing stack trace\r\n Throwable rootCause = ExceptionUtils.getRootCause(ex);\r\n if(rootCause != null)\r\n {\r\n msg.append(eol).append(\"The root stack trace is --> \");\r\n String rootStack = ExceptionUtils.getStackTrace(rootCause);\r\n msg.append(eol).append(rootStack);\r\n }\r\n\r\n return new PersistenceBrokerException(msg.toString(), ex);\r\n }\r\n else\r\n {\r\n return new PersistenceBrokerException(msg.toString());\r\n }\r\n }" ]
Generates a module regarding the parameters. @param name String @param version String @return Module
[ "public static Module createModule(final String name,final String version){\n final Module module = new Module();\n\n module.setName(name);\n module.setVersion(version);\n module.setPromoted(false);\n\n return module;\n\n }" ]
[ "public static nsrpcnode get(nitro_service service, String ipaddress) throws Exception{\n\t\tnsrpcnode obj = new nsrpcnode();\n\t\tobj.set_ipaddress(ipaddress);\n\t\tnsrpcnode response = (nsrpcnode) obj.get_resource(service);\n\t\treturn response;\n\t}", "@Override\n protected boolean changeDirection(int currentIndex, int centerIndex, boolean inBounds) {\n boolean changed = false;\n if (getGravityInternal() == Gravity.CENTER &&\n currentIndex <= centerIndex &&\n currentIndex == 0 || !inBounds) {\n\n changed = true;\n }\n return changed;\n }", "public static base_response delete(nitro_service client, String acl6name) throws Exception {\n\t\tnsacl6 deleteresource = new nsacl6();\n\t\tdeleteresource.acl6name = acl6name;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public 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 ClassMatcher buildMatcher(String tagText) {\n\t// check there are at least @match <type> and a parameter\n\tString[] strings = StringUtil.tokenize(tagText);\n\tif (strings.length < 2) {\n\t System.err.println(\"Skipping uncomplete @match tag, type missing: \" + tagText + \" in view \" + viewDoc);\n\t return null;\n\t}\n\t\n\ttry {\n\t if (strings[0].equals(\"class\")) {\n\t\treturn new PatternMatcher(Pattern.compile(strings[1]));\n\t } else if (strings[0].equals(\"context\")) {\n\t\treturn new ContextMatcher(root, Pattern.compile(strings[1]), getGlobalOptions(), \n\t\t\tfalse);\n\t } else if (strings[0].equals(\"outgoingContext\")) {\n\t\treturn new ContextMatcher(root, Pattern.compile(strings[1]), getGlobalOptions(), \n\t\t\tfalse);\n\t } else if (strings[0].equals(\"interface\")) {\n\t\treturn new InterfaceMatcher(root, Pattern.compile(strings[1]));\n\t } else if (strings[0].equals(\"subclass\")) {\n\t\treturn new SubclassMatcher(root, Pattern.compile(strings[1]));\n\t } else {\n\t\tSystem.err.println(\"Skipping @match tag, unknown match type, in view \" + viewDoc);\n\t }\n\t} catch (PatternSyntaxException pse) {\n\t System.err.println(\"Skipping @match tag due to invalid regular expression '\" + tagText\n\t\t + \"'\" + \" in view \" + viewDoc);\n\t} catch (Exception e) {\n\t System.err.println(\"Skipping @match tag due to an internal error '\" + tagText\n\t\t + \"'\" + \" in view \" + viewDoc);\n\t e.printStackTrace();\n\t}\n\treturn null;\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 }", "private void processOutlineCodeValues() throws IOException\n {\n DirectoryEntry outlineCodeDir = (DirectoryEntry) m_projectDir.getEntry(\"TBkndOutlCode\");\n FixedMeta fm = new FixedMeta(new DocumentInputStream(((DocumentEntry) outlineCodeDir.getEntry(\"FixedMeta\"))), 10);\n FixedData fd = new FixedData(fm, new DocumentInputStream(((DocumentEntry) outlineCodeDir.getEntry(\"FixedData\"))));\n\n Map<Integer, FieldType> map = new HashMap<Integer, FieldType>();\n\n int items = fm.getItemCount();\n for (int loop = 0; loop < items; loop++)\n {\n byte[] data = fd.getByteArrayValue(loop);\n if (data.length < 18)\n {\n continue;\n }\n\n int index = MPPUtility.getShort(data, 0);\n int fieldID = MPPUtility.getInt(data, 12);\n FieldType fieldType = FieldTypeHelper.getInstance(fieldID);\n if (fieldType.getFieldTypeClass() != FieldTypeClass.UNKNOWN)\n {\n map.put(Integer.valueOf(index), fieldType);\n }\n }\n\n VarMeta outlineCodeVarMeta = new VarMeta9(new DocumentInputStream(((DocumentEntry) outlineCodeDir.getEntry(\"VarMeta\"))));\n Var2Data outlineCodeVarData = new Var2Data(outlineCodeVarMeta, new DocumentInputStream(((DocumentEntry) outlineCodeDir.getEntry(\"Var2Data\"))));\n\n Map<FieldType, List<Pair<String, String>>> valueMap = new HashMap<FieldType, List<Pair<String, String>>>();\n\n for (Integer id : outlineCodeVarMeta.getUniqueIdentifierArray())\n {\n FieldType fieldType = map.get(id);\n String value = outlineCodeVarData.getUnicodeString(id, VALUE);\n String description = outlineCodeVarData.getUnicodeString(id, DESCRIPTION);\n\n List<Pair<String, String>> list = valueMap.get(fieldType);\n if (list == null)\n {\n list = new ArrayList<Pair<String, String>>();\n valueMap.put(fieldType, list);\n }\n list.add(new Pair<String, String>(value, description));\n }\n\n for (Entry<FieldType, List<Pair<String, String>>> entry : valueMap.entrySet())\n {\n populateContainer(entry.getKey(), entry.getValue());\n }\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<InternationalFixedDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<InternationalFixedDate>) super.zonedDateTime(temporal);\n }", "public void addFkToItemClass(String column)\r\n {\r\n if (fksToItemClass == null)\r\n {\r\n fksToItemClass = new Vector();\r\n }\r\n fksToItemClass.add(column);\r\n fksToItemClassAry = null;\r\n }" ]
Set whether the WMS tiles should be cached for later use. This implies that the WMS tiles will be proxied. @param useCache true when request needs to be cached @since 1.9.0
[ "@Api\n\tpublic void setUseCache(boolean useCache) {\n\t\tif (null == cacheManagerService && useCache) {\n\t\t\tlog.warn(\"The caching plugin needs to be available to cache WMS requests. Not setting useCache.\");\n\t\t} else {\n\t\t\tthis.useCache = useCache;\n\t\t}\n\t}" ]
[ "@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 CollectionRequest<Task> stories(String task) {\n \n String path = String.format(\"/tasks/%s/stories\", task);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }", "protected synchronized void doWriteObjects(boolean isFlush) throws TransactionAbortedException, LockNotGrantedException\r\n {\r\n /*\r\n arminw:\r\n if broker isn't in PB-tx, start tx\r\n */\r\n if (!getBroker().isInTransaction())\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"call beginTransaction() on PB instance\");\r\n broker.beginTransaction();\r\n }\r\n\r\n // Notify objects of impending commits.\r\n performTransactionAwareBeforeCommit();\r\n\r\n // Now perfom the real work\r\n objectEnvelopeTable.writeObjects(isFlush);\r\n // now we have to perform the named objects\r\n namedRootsMap.performDeletion();\r\n namedRootsMap.performInsert();\r\n namedRootsMap.afterWriteCleanup();\r\n }", "protected GVRPickedObject findCollider(GVRPickedObject[] pickList, GVRCollider findme)\n {\n if (pickList == null)\n {\n return null;\n }\n for (GVRPickedObject hit : pickList)\n {\n if ((hit != null) && (hit.hitCollider == findme))\n {\n return hit;\n }\n }\n return null;\n }", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void pushInstallReferrer(Intent intent) {\n try {\n final Bundle extras = intent.getExtras();\n // Preliminary checks\n if (extras == null || !extras.containsKey(\"referrer\")) {\n return;\n }\n final String url;\n try {\n url = URLDecoder.decode(extras.getString(\"referrer\"), \"UTF-8\");\n\n getConfigLogger().verbose(getAccountId(), \"Referrer received: \" + url);\n } catch (Throwable e) {\n // Could not decode\n return;\n }\n if (url == null) {\n return;\n }\n int now = (int) (System.currentTimeMillis() / 1000);\n\n if (installReferrerMap.containsKey(url) && now - installReferrerMap.get(url) < 10) {\n getConfigLogger().verbose(getAccountId(),\"Skipping install referrer due to duplicate within 10 seconds\");\n return;\n }\n\n installReferrerMap.put(url, now);\n\n Uri uri = Uri.parse(\"wzrk://track?install=true&\" + url);\n\n pushDeepLink(uri, true);\n } catch (Throwable t) {\n // no-op\n }\n }", "private String getPropertyName(Expression expression) {\n\t\tif (!(expression instanceof PropertyName)) {\n\t\t\tthrow new IllegalArgumentException(\"Expression \" + expression + \" is not a PropertyName.\");\n\t\t}\n\t\tString name = ((PropertyName) expression).getPropertyName();\n\t\tif (name.endsWith(FilterService.ATTRIBUTE_ID)) {\n\t\t\t// replace by Hibernate id property, always refers to the id, even if named differently\n\t\t\tname = name.substring(0, name.length() - FilterService.ATTRIBUTE_ID.length()) + HIBERNATE_ID;\n\t\t}\n\t\treturn name;\n\t}", "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}", "public void build(Set<Bean<?>> beans) {\n\n if (isBuilt()) {\n throw new IllegalStateException(\"BeanIdentifier index is already built!\");\n }\n\n if (beans.isEmpty()) {\n index = new BeanIdentifier[0];\n reverseIndex = Collections.emptyMap();\n indexHash = 0;\n indexBuilt.set(true);\n return;\n }\n\n List<BeanIdentifier> tempIndex = new ArrayList<BeanIdentifier>(beans.size());\n\n for (Bean<?> bean : beans) {\n if (bean instanceof CommonBean<?>) {\n tempIndex.add(((CommonBean<?>) bean).getIdentifier());\n } else if (bean instanceof PassivationCapable) {\n tempIndex.add(new StringBeanIdentifier(((PassivationCapable) bean).getId()));\n }\n }\n\n Collections.sort(tempIndex, new Comparator<BeanIdentifier>() {\n @Override\n public int compare(BeanIdentifier o1, BeanIdentifier o2) {\n return o1.asString().compareTo(o2.asString());\n }\n });\n\n index = tempIndex.toArray(new BeanIdentifier[tempIndex.size()]);\n\n ImmutableMap.Builder<BeanIdentifier, Integer> builder = ImmutableMap.builder();\n for (int i = 0; i < index.length; i++) {\n builder.put(index[i], i);\n }\n reverseIndex = builder.build();\n\n indexHash = Arrays.hashCode(index);\n\n if(BootstrapLogger.LOG.isDebugEnabled()) {\n BootstrapLogger.LOG.beanIdentifierIndexBuilt(getDebugInfo());\n }\n indexBuilt.set(true);\n }", "public static base_response update(nitro_service client, ipv6 resource) throws Exception {\n\t\tipv6 updateresource = new ipv6();\n\t\tupdateresource.ralearning = resource.ralearning;\n\t\tupdateresource.routerredirection = resource.routerredirection;\n\t\tupdateresource.ndbasereachtime = resource.ndbasereachtime;\n\t\tupdateresource.ndretransmissiontime = resource.ndretransmissiontime;\n\t\tupdateresource.natprefix = resource.natprefix;\n\t\tupdateresource.dodad = resource.dodad;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
Set text parameters from properties @param context Valid Android {@link Context} @param properties JSON text properties
[ "public void setFromJSON(Context context, JSONObject properties) {\n String backgroundResStr = optString(properties, Properties.background);\n if (backgroundResStr != null && !backgroundResStr.isEmpty()) {\n final int backgroundResId = getId(context, backgroundResStr, \"drawable\");\n setBackGround(context.getResources().getDrawable(backgroundResId, null));\n }\n\n setBackgroundColor(getJSONColor(properties, Properties.background_color, getBackgroundColor()));\n setGravity(optInt(properties, TextContainer.Properties.gravity, getGravity()));\n setRefreshFrequency(optEnum(properties, Properties.refresh_freq, getRefreshFrequency()));\n setTextColor(getJSONColor(properties, Properties.text_color, getTextColor()));\n setText(optString(properties, Properties.text, (String) getText()));\n setTextSize(optFloat(properties, Properties.text_size, getTextSize()));\n\n final JSONObject typefaceJson = optJSONObject(properties, Properties.typeface);\n\n if (typefaceJson != null) {\n try {\n Typeface typeface = WidgetLib.getTypefaceManager().getTypeface(typefaceJson);\n setTypeface(typeface);\n } catch (Throwable e) {\n Log.e(TAG, e, \"Couldn't set typeface from properties: %s\", typefaceJson);\n }\n }\n }" ]
[ "private ClassDescriptorDef ensureClassDef(XClass original)\r\n {\r\n String name = original.getQualifiedName();\r\n ClassDescriptorDef classDef = _model.getClass(name);\r\n\r\n if (classDef == null)\r\n {\r\n classDef = new ClassDescriptorDef(original);\r\n _model.addClass(classDef);\r\n }\r\n return classDef;\r\n }", "public static base_response unset(nitro_service client, callhome resource, String[] args) throws Exception{\n\t\tcallhome unsetresource = new callhome();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "private String readOptionalString(JSONObject json, String key, String defaultValue) {\n\n try {\n String str = json.getString(key);\n if (str != null) {\n return str;\n }\n\n } catch (JSONException e) {\n LOG.debug(\"Reading optional JSON string failed. Default to provided default value.\", e);\n }\n return defaultValue;\n }", "public String processNested(Properties attributes) throws XDocletException\r\n {\r\n String name = OjbMemberTagsHandler.getMemberName();\r\n XClass type = OjbMemberTagsHandler.getMemberType();\r\n int dim = OjbMemberTagsHandler.getMemberDimension();\r\n NestedDef nestedDef = _curClassDef.getNested(name);\r\n\r\n if (type == null)\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.COULD_NOT_DETERMINE_TYPE_OF_MEMBER,\r\n new String[]{name}));\r\n }\r\n if (dim > 0)\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.MEMBER_CANNOT_BE_NESTED,\r\n new String[]{name, _curClassDef.getName()}));\r\n }\r\n\r\n ClassDescriptorDef nestedTypeDef = _model.getClass(type.getQualifiedName());\r\n\r\n if (nestedTypeDef == null)\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.COULD_NOT_DETERMINE_TYPE_OF_MEMBER,\r\n new String[]{name}));\r\n }\r\n if (nestedDef == null)\r\n {\r\n nestedDef = new NestedDef(name, nestedTypeDef);\r\n _curClassDef.addNested(nestedDef);\r\n }\r\n LogHelper.debug(false, OjbTagsHandler.class, \"processNested\", \" Processing nested object \"+nestedDef.getName()+\" of type \"+nestedTypeDef.getName());\r\n\r\n String attrName;\r\n \r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n nestedDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n return \"\";\r\n }", "public float getLayoutSize(final Layout.Axis axis) {\n float size = 0;\n for (Layout layout : mLayouts) {\n size = Math.max(size, layout.getSize(axis));\n }\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"getLayoutSize [%s] axis [%s] size [%f]\", getName(), axis, size);\n return size;\n }", "public static String analyzeInvalidMetadataRate(final Cluster currentCluster,\n List<StoreDefinition> currentStoreDefs,\n final Cluster finalCluster,\n List<StoreDefinition> finalStoreDefs) {\n StringBuilder sb = new StringBuilder();\n sb.append(\"Dump of invalid metadata rates per zone\").append(Utils.NEWLINE);\n\n HashMap<StoreDefinition, Integer> uniqueStores = StoreDefinitionUtils.getUniqueStoreDefinitionsWithCounts(currentStoreDefs);\n\n for(StoreDefinition currentStoreDef: uniqueStores.keySet()) {\n sb.append(\"Store exemplar: \" + currentStoreDef.getName())\n .append(Utils.NEWLINE)\n .append(\"\\tThere are \" + uniqueStores.get(currentStoreDef) + \" other similar stores.\")\n .append(Utils.NEWLINE);\n\n StoreRoutingPlan currentSRP = new StoreRoutingPlan(currentCluster, currentStoreDef);\n StoreDefinition finalStoreDef = StoreUtils.getStoreDef(finalStoreDefs,\n currentStoreDef.getName());\n StoreRoutingPlan finalSRP = new StoreRoutingPlan(finalCluster, finalStoreDef);\n\n // Only care about existing zones\n for(int zoneId: currentCluster.getZoneIds()) {\n int zonePrimariesCount = 0;\n int invalidMetadata = 0;\n\n // Examine nodes in current cluster in existing zone.\n for(int nodeId: currentCluster.getNodeIdsInZone(zoneId)) {\n // For every zone-primary in current cluster\n for(int zonePrimaryPartitionId: currentSRP.getZonePrimaryPartitionIds(nodeId)) {\n zonePrimariesCount++;\n // Determine if original zone-primary node is still some\n // form of n-ary in final cluster. If not,\n // InvalidMetadataException will fire.\n if(!finalSRP.getZoneNAryPartitionIds(nodeId)\n .contains(zonePrimaryPartitionId)) {\n invalidMetadata++;\n }\n }\n }\n float rate = invalidMetadata / (float) zonePrimariesCount;\n sb.append(\"\\tZone \" + zoneId)\n .append(\" : total zone primaries \" + zonePrimariesCount)\n .append(\", # that trigger invalid metadata \" + invalidMetadata)\n .append(\" => \" + rate)\n .append(Utils.NEWLINE);\n }\n }\n\n return sb.toString();\n }", "public List<? super OpenShiftResource> processTemplateResources() {\n List<? extends OpenShiftResource> resources;\n final List<? super OpenShiftResource> processedResources = new ArrayList<>();\n templates = OpenShiftResourceFactory.getTemplates(getType());\n boolean sync_instantiation = OpenShiftResourceFactory.syncInstantiation(getType());\n\n /* Instantiate templates */\n for (Template template : templates) {\n resources = processTemplate(template);\n if (resources != null) {\n if (sync_instantiation) {\n /* synchronous template instantiation */\n processedResources.addAll(resources);\n } else {\n /* asynchronous template instantiation */\n try {\n delay(openShiftAdapter, resources);\n } catch (Throwable t) {\n throw new IllegalArgumentException(asynchronousDelayErrorMessage(), t);\n }\n }\n }\n }\n\n return processedResources;\n }", "public void addAccessory(HomekitAccessory accessory) {\n if (accessory.getId() <= 1 && !(accessory instanceof Bridge)) {\n throw new IndexOutOfBoundsException(\n \"The ID of an accessory used in a bridge must be greater than 1\");\n }\n addAccessorySkipRangeCheck(accessory);\n }", "public FieldType getField()\n {\n FieldType result = null;\n if (m_index < m_fields.length)\n {\n result = m_fields[m_index++];\n }\n\n return result;\n }" ]
Convert an object to a collection. @param mapper the object mapper @param source the source object @param targetCollectionType the target collection type @param targetElementType the target collection element type @return collection
[ "public static <E> Collection<E> collectify(ObjectMapper mapper, Object source, Class<? extends Collection> targetCollectionType, Class<E> targetElementType) {\n CollectionType collectionType = mapper.getTypeFactory().constructCollectionType(targetCollectionType, targetElementType);\n return objectify(mapper, convertToCollection(source), collectionType);\n }" ]
[ "public static void main(String[] args) {\n try {\n new StartMain(args).go();\n } catch(Throwable t) {\n WeldSELogger.LOG.error(\"Application exited with an exception\", t);\n System.exit(1);\n }\n }", "public MetaClassRegistryChangeEventListener[] getMetaClassRegistryChangeEventListeners() {\n synchronized (changeListenerList) {\n ArrayList<MetaClassRegistryChangeEventListener> ret =\n new ArrayList<MetaClassRegistryChangeEventListener>(changeListenerList.size()+nonRemoveableChangeListenerList.size());\n ret.addAll(nonRemoveableChangeListenerList);\n ret.addAll(changeListenerList);\n return ret.toArray(new MetaClassRegistryChangeEventListener[ret.size()]);\n }\n }", "public synchronized boolean removeTaskFromWaitQ(ParallelTask taskTobeRemoved) {\n boolean removed = false;\n for (ParallelTask task : waitQ) {\n if (task.getTaskId() == taskTobeRemoved.getTaskId()) {\n\n task.setState(ParallelTaskState.COMPLETED_WITH_ERROR);\n task.getTaskErrorMetas().add(\n new TaskErrorMeta(TaskErrorType.USER_CANCELED, \"NA\"));\n logger.info(\n \"task {} removed from wait q. This task has been marked as USER CANCELED.\",\n task.getTaskId());\n removed = true;\n }\n }\n\n return removed;\n }", "@SuppressForbidden(\"legitimate sysstreams.\")\n public static void warn(String message, Throwable t) {\n PrintStream w = (warnings == null ? System.err : warnings);\n try {\n w.print(\"WARN: \");\n w.print(message);\n if (t != null) {\n w.print(\" -> \");\n try {\n t.printStackTrace(w);\n } catch (OutOfMemoryError e) {\n // Ignore, OOM.\n w.print(t.getClass().getName());\n w.print(\": \");\n w.print(t.getMessage());\n w.println(\" (stack unavailable; OOM)\");\n }\n } else {\n w.println();\n }\n w.flush();\n } catch (OutOfMemoryError t2) {\n w.println(\"ERROR: Couldn't even serialize a warning (out of memory).\");\n } catch (Throwable t2) {\n // Can't do anything, really. Probably an OOM?\n w.println(\"ERROR: Couldn't even serialize a warning.\");\n }\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 }", "@Override\r\n\tpublic String toCompressedString() {\r\n\t\tString result;\r\n\t\tif(hasNoStringCache() || (result = getStringCache().compressedString) == null) {\r\n\t\t\tgetStringCache().compressedString = result = toNormalizedString(MACStringCache.compressedParams);\r\n\t\t}\r\n\t\treturn result;\r\n\t}", "protected int adjustIndex(Widget child, int beforeIndex) {\n\n checkIndexBoundsForInsertion(beforeIndex);\n\n // Check to see if this widget is already a direct child.\n if (child.getParent() == this) {\n // If the Widget's previous position was left of the desired new position\n // shift the desired position left to reflect the removal\n int idx = getWidgetIndex(child);\n if (idx < beforeIndex) {\n beforeIndex--;\n }\n }\n\n return beforeIndex;\n }", "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 }", "protected synchronized void doWriteObjects(boolean isFlush) throws TransactionAbortedException, LockNotGrantedException\r\n {\r\n /*\r\n arminw:\r\n if broker isn't in PB-tx, start tx\r\n */\r\n if (!getBroker().isInTransaction())\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"call beginTransaction() on PB instance\");\r\n broker.beginTransaction();\r\n }\r\n\r\n // Notify objects of impending commits.\r\n performTransactionAwareBeforeCommit();\r\n\r\n // Now perfom the real work\r\n objectEnvelopeTable.writeObjects(isFlush);\r\n // now we have to perform the named objects\r\n namedRootsMap.performDeletion();\r\n namedRootsMap.performInsert();\r\n namedRootsMap.afterWriteCleanup();\r\n }" ]
Term value. @param term the term @return the string
[ "public static String termValue(String term) {\n int i = term.indexOf(MtasToken.DELIMITER);\n String value = null;\n if (i >= 0) {\n value = term.substring((i + MtasToken.DELIMITER.length()));\n value = (value.length() > 0) ? value : null;\n }\n return (value == null) ? null : value.replace(\"\\u0000\", \"\");\n }" ]
[ "private void setBelief(String bName, Object value) {\n introspector.setBeliefValue(this.getLocalName(), bName, value, null);\n }", "public boolean removeKey(long key) {\r\n\tint i = indexOfKey(key);\r\n\tif (i<0) return false; // key not contained\r\n\r\n\tthis.state[i]=REMOVED;\r\n\tthis.values[i]=0; // delta\r\n\tthis.distinct--;\r\n\r\n\tif (this.distinct < this.lowWaterMark) {\r\n\t\tint newCapacity = chooseShrinkCapacity(this.distinct,this.minLoadFactor, this.maxLoadFactor);\r\n\t\trehash(newCapacity);\r\n\t}\r\n\t\r\n\treturn true;\t\r\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 }", "@Deprecated\n\tpublic List<Double> getResolutions() {\n\t\tList<Double> resolutions = new ArrayList<Double>();\n\t\tfor (ScaleInfo scale : getZoomLevels()) {\n\t\t\tresolutions.add(1. / scale.getPixelPerUnit());\n\t\t}\n\t\treturn resolutions;\n\t}", "public static Node addPartitionToNode(final Node node, Integer donatedPartition) {\n return UpdateClusterUtils.addPartitionsToNode(node, Sets.newHashSet(donatedPartition));\n }", "public Jar setListAttribute(String name, Collection<?> values) {\n return setAttribute(name, join(values));\n }", "private void appendDefaultValue(StringBuilder sb, FieldType fieldType, Object defaultValue) {\n\t\tif (fieldType.isEscapedDefaultValue()) {\n\t\t\tappendEscapedWord(sb, defaultValue.toString());\n\t\t} else {\n\t\t\tsb.append(defaultValue);\n\t\t}\n\t}", "@Override\n public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {\n try {\n if (exceptionRaised.get()) {\n return;\n }\n\n if (!(msg instanceof HttpRequest)) {\n // If there is no methodInfo, it means the request was already rejected.\n // What we received here is just residue of the request, which can be ignored.\n if (methodInfo != null) {\n ReferenceCountUtil.retain(msg);\n ctx.fireChannelRead(msg);\n }\n return;\n }\n HttpRequest request = (HttpRequest) msg;\n BasicHttpResponder responder = new BasicHttpResponder(ctx.channel(), sslEnabled);\n\n // Reset the methodInfo for the incoming request error handling\n methodInfo = null;\n methodInfo = prepareHandleMethod(request, responder, ctx);\n\n if (methodInfo != null) {\n ReferenceCountUtil.retain(msg);\n ctx.fireChannelRead(msg);\n } else {\n if (!responder.isResponded()) {\n // If not yet responded, just respond with a not found and close the connection\n HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);\n HttpUtil.setContentLength(response, 0);\n HttpUtil.setKeepAlive(response, false);\n ctx.channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);\n } else {\n // If already responded, just close the connection\n ctx.channel().close();\n }\n }\n } finally {\n ReferenceCountUtil.release(msg);\n }\n }", "public static base_responses add(nitro_service client, autoscaleprofile resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tautoscaleprofile addresources[] = new autoscaleprofile[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new autoscaleprofile();\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].url = resources[i].url;\n\t\t\t\taddresources[i].apikey = resources[i].apikey;\n\t\t\t\taddresources[i].sharedsecret = resources[i].sharedsecret;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}" ]
Get a property as a double or throw an exception. @param key the property name
[ "@Override\n public final double getDouble(final String key) {\n Double result = optDouble(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }" ]
[ "public List<Gallery> getList(String userId, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIST);\r\n parameters.put(\"user_id\", userId);\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", String.valueOf(perPage));\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", String.valueOf(page));\r\n }\r\n\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element element = response.getPayload();\r\n GalleryList<Gallery> galleries = new GalleryList<Gallery>();\r\n galleries.setPage(element.getAttribute(\"page\"));\r\n galleries.setPages(element.getAttribute(\"pages\"));\r\n galleries.setPerPage(element.getAttribute(\"per_page\"));\r\n galleries.setTotal(element.getAttribute(\"total\"));\r\n\r\n NodeList galleryNodes = element.getElementsByTagName(\"gallery\");\r\n for (int i = 0; i < galleryNodes.getLength(); i++) {\r\n Element galleryElement = (Element) galleryNodes.item(i);\r\n Gallery gallery = new Gallery();\r\n gallery.setId(galleryElement.getAttribute(\"id\"));\r\n gallery.setUrl(galleryElement.getAttribute(\"url\"));\r\n\r\n User owner = new User();\r\n owner.setId(galleryElement.getAttribute(\"owner\"));\r\n gallery.setOwner(owner);\r\n gallery.setCreateDate(galleryElement.getAttribute(\"date_create\"));\r\n gallery.setUpdateDate(galleryElement.getAttribute(\"date_update\"));\r\n gallery.setPrimaryPhotoId(galleryElement.getAttribute(\"primary_photo_id\"));\r\n gallery.setPrimaryPhotoServer(galleryElement.getAttribute(\"primary_photo_server\"));\r\n gallery.setPrimaryPhotoFarm(galleryElement.getAttribute(\"primary_photo_farm\"));\r\n gallery.setPrimaryPhotoSecret(galleryElement.getAttribute(\"primary_photo_secret\"));\r\n gallery.setPhotoCount(galleryElement.getAttribute(\"count_photos\"));\r\n gallery.setVideoCount(galleryElement.getAttribute(\"count_videos\"));\r\n\r\n galleries.add(gallery);\r\n }\r\n return galleries;\r\n }", "public static String readTag(Reader r) throws IOException {\r\n if ( ! r.ready()) {\r\n return null;\r\n }\r\n StringBuilder b = new StringBuilder(\"<\");\r\n int c = r.read();\r\n while (c >= 0) {\r\n b.append((char) c);\r\n if (c == '>') {\r\n break;\r\n }\r\n c = r.read();\r\n }\r\n if (b.length() == 1) {\r\n return null;\r\n }\r\n return b.toString();\r\n }", "public static void setEnabled(Element element, boolean enabled) {\n element.setPropertyBoolean(\"disabled\", !enabled);\n\tsetStyleName(element, \"disabled\", !enabled);\n }", "private boolean keyAlreadyExists(String newKey) {\n\n Collection<?> itemIds = m_table.getItemIds();\n for (Object itemId : itemIds) {\n if (m_table.getItem(itemId).getItemProperty(TableProperty.KEY).getValue().equals(newKey)) {\n return true;\n }\n }\n return false;\n }", "private String createMethodSignature(Method method)\n {\n StringBuilder sb = new StringBuilder();\n sb.append(\"(\");\n for (Class<?> type : method.getParameterTypes())\n {\n sb.append(getTypeString(type));\n }\n sb.append(\")\");\n Class<?> type = method.getReturnType();\n if (type.getName().equals(\"void\"))\n {\n sb.append(\"V\");\n }\n else\n {\n sb.append(getTypeString(type));\n }\n return sb.toString();\n }", "public static void showErrorDialog(String message, String details) {\n\n Window window = prepareWindow(DialogWidth.wide);\n window.setCaption(\"Error\");\n window.setContent(new CmsSetupErrorDialog(message, details, null, window));\n A_CmsUI.get().addWindow(window);\n\n }", "@SuppressWarnings(\"WeakerAccess\")\n public static @Nullable CleverTapAPI getDefaultInstance(Context context) {\n // For Google Play Store/Android Studio tracking\n sdkVersion = BuildConfig.SDK_VERSION_STRING;\n if (defaultConfig == null) {\n ManifestInfo manifest = ManifestInfo.getInstance(context);\n String accountId = manifest.getAccountId();\n String accountToken = manifest.getAcountToken();\n String accountRegion = manifest.getAccountRegion();\n if(accountId == null || accountToken == null) {\n Logger.i(\"Account ID or Account token is missing from AndroidManifest.xml, unable to create default instance\");\n return null;\n }\n if (accountRegion == null) {\n Logger.i(\"Account Region not specified in the AndroidManifest - using default region\");\n }\n defaultConfig = CleverTapInstanceConfig.createDefaultInstance(context, accountId, accountToken, accountRegion);\n defaultConfig.setDebugLevel(getDebugLevel());\n }\n return instanceWithConfig(context, defaultConfig);\n }", "public static List<CompiledAutomaton> createAutomata(String prefix,\n String regexp, Map<String, Automaton> automatonMap) throws IOException {\n List<CompiledAutomaton> list = new ArrayList<>();\n Automaton automatonRegexp = null;\n if (regexp != null) {\n RegExp re = new RegExp(prefix + MtasToken.DELIMITER + regexp + \"\\u0000*\");\n automatonRegexp = re.toAutomaton();\n }\n int step = 500;\n List<String> keyList = new ArrayList<>(automatonMap.keySet());\n for (int i = 0; i < keyList.size(); i += step) {\n int localStep = step;\n boolean success = false;\n CompiledAutomaton compiledAutomaton = null;\n while (!success) {\n success = true;\n int next = Math.min(keyList.size(), i + localStep);\n List<Automaton> listAutomaton = new ArrayList<>();\n for (int j = i; j < next; j++) {\n listAutomaton.add(automatonMap.get(keyList.get(j)));\n }\n Automaton automatonList = Operations.union(listAutomaton);\n Automaton automaton;\n if (automatonRegexp != null) {\n automaton = Operations.intersection(automatonList, automatonRegexp);\n } else {\n automaton = automatonList;\n }\n try {\n compiledAutomaton = new CompiledAutomaton(automaton);\n } catch (TooComplexToDeterminizeException e) {\n log.debug(e);\n success = false;\n if (localStep > 1) {\n localStep /= 2;\n } else {\n throw new IOException(\"TooComplexToDeterminizeException\");\n }\n }\n }\n list.add(compiledAutomaton);\n }\n return list;\n }", "public static ObjectModelResolver get(String resolverId) {\n List<ObjectModelResolver> resolvers = getResolvers();\n\n for (ObjectModelResolver resolver : resolvers) {\n if (resolver.accept(resolverId)) {\n return resolver;\n }\n }\n\n return null;\n }" ]
Resolves the package type from the maven project. @param project the maven project @return the package type
[ "public static PackageType resolve(final MavenProject project) {\n final String packaging = project.getPackaging().toLowerCase(Locale.ROOT);\n if (DEFAULT_TYPES.containsKey(packaging)) {\n return DEFAULT_TYPES.get(packaging);\n }\n return new PackageType(packaging);\n }" ]
[ "private List<TimephasedCost> getTimephasedCostFixedAmount()\n {\n List<TimephasedCost> result = new LinkedList<TimephasedCost>();\n\n ProjectCalendar cal = getCalendar();\n\n double remainingCost = getRemainingCost().doubleValue();\n\n if (remainingCost > 0)\n {\n AccrueType accrueAt = getResource().getAccrueAt();\n\n if (accrueAt == AccrueType.START)\n {\n result.add(splitCostStart(cal, remainingCost, getStart()));\n }\n else\n if (accrueAt == AccrueType.END)\n {\n result.add(splitCostEnd(cal, remainingCost, getFinish()));\n }\n else\n {\n //for prorated, we have to deal with it differently depending on whether or not\n //any actual has been entered, since we want to mimic the other timephased data\n //where planned and actual values do not overlap\n double numWorkingDays = cal.getWork(getStart(), getFinish(), TimeUnit.DAYS).getDuration();\n double standardAmountPerDay = getCost().doubleValue() / numWorkingDays;\n\n if (getActualCost().intValue() > 0)\n {\n //need to get three possible blocks of data: one for the possible partial amount\n //overlap with timephased actual cost; one with all the standard amount days\n //that happen after the actual cost stops; and one with any remaining\n //partial day cost amount\n\n int numActualDaysUsed = (int) Math.ceil(getActualCost().doubleValue() / standardAmountPerDay);\n Date actualWorkFinish = cal.getDate(getStart(), Duration.getInstance(numActualDaysUsed, TimeUnit.DAYS), false);\n\n double partialDayActualAmount = getActualCost().doubleValue() % standardAmountPerDay;\n\n if (partialDayActualAmount > 0)\n {\n double dayAmount = standardAmountPerDay < remainingCost ? standardAmountPerDay - partialDayActualAmount : remainingCost;\n\n result.add(splitCostEnd(cal, dayAmount, actualWorkFinish));\n\n remainingCost -= dayAmount;\n }\n\n //see if there's anything left to work with\n if (remainingCost > 0)\n {\n //have to split up the amount into standard prorated amount days and whatever is left\n result.addAll(splitCostProrated(cal, remainingCost, standardAmountPerDay, cal.getNextWorkStart(actualWorkFinish)));\n }\n\n }\n else\n {\n //no actual cost to worry about, so just a standard split from the beginning of the assignment\n result.addAll(splitCostProrated(cal, remainingCost, standardAmountPerDay, getStart()));\n }\n }\n }\n\n return result;\n }", "private static void initInstance(final TransactionLogger instance, final Logger logger, final Logger auditor) {\n instance.logger = logger;\n instance.auditor = auditor;\n instance.components = new LinkedHashMap<>();\n instance.properties = new LinkedHashMap<>();\n instance.total = new Component(TOTAL_COMPONENT);\n instance.total.startTimer();\n instance.componentsMultiThread = new ComponentsMultiThread();\n instance.flowContext = FlowContextFactory.serializeNativeFlowContext();\n }", "private final Object getObject(String name)\n {\n if (m_map.containsKey(name) == false)\n {\n throw new IllegalArgumentException(\"Invalid column name \" + name);\n }\n\n Object result = m_map.get(name);\n\n return (result);\n }", "public Metadata getMetadata(String templateName) {\n String scope = Metadata.scopeBasedOnType(templateName);\n return this.getMetadata(templateName, scope);\n }", "@Override\n public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {\n try {\n if (exceptionRaised.get()) {\n return;\n }\n\n if (!(msg instanceof HttpRequest)) {\n // If there is no methodInfo, it means the request was already rejected.\n // What we received here is just residue of the request, which can be ignored.\n if (methodInfo != null) {\n ReferenceCountUtil.retain(msg);\n ctx.fireChannelRead(msg);\n }\n return;\n }\n HttpRequest request = (HttpRequest) msg;\n BasicHttpResponder responder = new BasicHttpResponder(ctx.channel(), sslEnabled);\n\n // Reset the methodInfo for the incoming request error handling\n methodInfo = null;\n methodInfo = prepareHandleMethod(request, responder, ctx);\n\n if (methodInfo != null) {\n ReferenceCountUtil.retain(msg);\n ctx.fireChannelRead(msg);\n } else {\n if (!responder.isResponded()) {\n // If not yet responded, just respond with a not found and close the connection\n HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);\n HttpUtil.setContentLength(response, 0);\n HttpUtil.setKeepAlive(response, false);\n ctx.channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);\n } else {\n // If already responded, just close the connection\n ctx.channel().close();\n }\n }\n } finally {\n ReferenceCountUtil.release(msg);\n }\n }", "private void renameReadOnlyV2Files(int masterPartitionId, int correctReplicaType) {\n for (int replica = 0; replica < routingStrategy.getNumReplicas(); replica++) {\n if (replica != correctReplicaType) {\n int chunkId = 0;\n while (true) {\n String fileName = Integer.toString(masterPartitionId) + \"_\"\n + Integer.toString(replica) + \"_\"\n + Integer.toString(chunkId);\n File index = getIndexFile(fileName);\n File data = getDataFile(fileName);\n\n if(index.exists() && data.exists()) {\n // We found files with the \"wrong\" replica type, so let's rename them\n\n String correctFileName = Integer.toString(masterPartitionId) + \"_\"\n + Integer.toString(correctReplicaType) + \"_\"\n + Integer.toString(chunkId);\n File indexWithCorrectReplicaType = getIndexFile(correctFileName);\n File dataWithCorrectReplicaType = getDataFile(correctFileName);\n\n Utils.move(index, indexWithCorrectReplicaType);\n Utils.move(data, dataWithCorrectReplicaType);\n\n // Maybe change this to DEBUG?\n logger.info(\"Renamed files with wrong replica type: \"\n + index.getAbsolutePath() + \"|data -> \"\n + indexWithCorrectReplicaType.getName() + \"|data\");\n } else if(index.exists() ^ data.exists()) {\n throw new VoldemortException(\"One of the following does not exist: \"\n + index.toString()\n + \" or \"\n + data.toString() + \".\");\n } else {\n // The files don't exist, or we've gone over all available chunks,\n // so let's move on.\n break;\n }\n chunkId++;\n }\n }\n }\n }", "public void setWeeklyDay(Day day, boolean value)\n {\n if (value)\n {\n m_days.add(day);\n }\n else\n {\n m_days.remove(day);\n }\n }", "private void setObjectForStatement(PreparedStatement stmt, int index, Object value, int sqlType)\r\n throws SQLException\r\n {\r\n if (value == null)\r\n {\r\n m_platform.setNullForStatement(stmt, index, sqlType);\r\n }\r\n else\r\n {\r\n m_platform.setObjectForStatement(stmt, index, value, sqlType);\r\n }\r\n }", "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 }" ]
Gets the Jensen Shannon divergence. @param p U vector. @param q V vector. @return The Jensen Shannon divergence between u and v.
[ "public static double JensenShannonDivergence(double[] p, double[] q) {\n double[] m = new double[p.length];\n for (int i = 0; i < m.length; i++) {\n m[i] = (p[i] + q[i]) / 2;\n }\n\n return (KullbackLeiblerDivergence(p, m) + KullbackLeiblerDivergence(q, m)) / 2;\n }" ]
[ "public final Template getTemplate(final String name) {\n final Template template = this.templates.get(name);\n if (template != null) {\n this.accessAssertion.assertAccess(\"Configuration\", this);\n template.assertAccessible(name);\n } else {\n throw new IllegalArgumentException(String.format(\"Template '%s' does not exist. Options are: \" +\n \"%s\", name, this.templates.keySet()));\n }\n return template;\n }", "protected void generateRoutes()\n {\n try {\n\n//\t\t\tOptional<io.sinistral.proteus.annotations.Chain> typeLevelWrapAnnotation = Optional.ofNullable(controllerClass.getAnnotation(io.sinistral.proteus.annotations.Chain.class));\n//\t\t\t\n//\t\t\ttypeLevelWrapAnnotation.ifPresent( a -> {\n//\t\t\t\t \n//\t\t\t\tio.sinistral.proteus.annotations.Chain w = typeLevelWrapAnnotation.get();\n//\n//\t\t\t\tClass<? extends HandlerWrapper> wrapperClasses[] = w.value();\n//\n//\t\t\t\tfor (int i = 0; i < wrapperClasses.length; i++)\n//\t\t\t\t{\n//\t\t\t\t\tClass<? extends HandlerWrapper> wrapperClass = wrapperClasses[i];\n//\n//\t\t\t\t\tString wrapperName = generateFieldName(wrapperClass.getCanonicalName());\n//\n//\t\t\t\t\thandlerWrapperMap.put(wrapperClass, wrapperName);\n//\t\t\t\t}\n//\t\t\t\t\n//\t\t\t});\n//\t\t\t\n//\t\t\tfor(Method m : this.controllerClass.getDeclaredMethods())\n//\t\t\t{\n//\t\t\t\n//\t\t\t\tOptional<io.sinistral.proteus.annotations.Chain> methodLevelWrapAnnotation = Optional.ofNullable(m.getAnnotation(io.sinistral.proteus.annotations.Chain.class));\n//\t\t\t\t\n//\t\t\t\tmethodLevelWrapAnnotation.ifPresent( a -> {\n//\t\t\t\t\t \n//\t\t\t\t\tio.sinistral.proteus.annotations.Chain w = methodLevelWrapAnnotation.get();\n//\t\n//\t\t\t\t\tClass<? extends HandlerWrapper> wrapperClasses[] = w.value();\n//\t\n//\t\t\t\t\tfor (int i = 0; i < wrapperClasses.length; i++)\n//\t\t\t\t\t{\n//\t\t\t\t\t\tClass<? extends HandlerWrapper> wrapperClass = wrapperClasses[i];\n//\t\n//\t\t\t\t\t\tString wrapperName = generateFieldName(wrapperClass.getCanonicalName());\n//\t\n//\t\t\t\t\t\thandlerWrapperMap.put(wrapperClass, wrapperName);\n//\t\t\t\t\t}\n//\t\t\t\t\t\n//\t\t\t\t});\n//\n//\t\t\t}\n//\t\t\t\n//\t\t\tlog.info(\"handlerWrapperMap: \" + handlerWrapperMap);\n\n TypeSpec.Builder typeBuilder = TypeSpec.classBuilder(className).addModifiers(Modifier.PUBLIC)\n .addSuperinterface(ParameterizedTypeName.get(Supplier.class, RoutingHandler.class));\n\n ClassName extractorClass = ClassName.get(\"io.sinistral.proteus.server\", \"Extractors\");\n\n ClassName injectClass = ClassName.get(\"com.google.inject\", \"Inject\");\n\n\n MethodSpec.Builder constructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addAnnotation(injectClass);\n\n String className = this.controllerClass.getSimpleName().toLowerCase() + \"Controller\";\n\n typeBuilder.addField(this.controllerClass, className, Modifier.PROTECTED, Modifier.FINAL);\n\n ClassName wrapperClass = ClassName.get(\"io.undertow.server\", \"HandlerWrapper\");\n ClassName stringClass = ClassName.get(\"java.lang\", \"String\");\n ClassName mapClass = ClassName.get(\"java.util\", \"Map\");\n\n TypeName mapOfWrappers = ParameterizedTypeName.get(mapClass, stringClass, wrapperClass);\n\n TypeName annotatedMapOfWrappers = mapOfWrappers\n .annotated(AnnotationSpec.builder(com.google.inject.name.Named.class).addMember(\"value\", \"$S\", \"registeredHandlerWrappers\").build());\n\n typeBuilder.addField(mapOfWrappers, \"registeredHandlerWrappers\", Modifier.PROTECTED, Modifier.FINAL);\n\n\n constructor.addParameter(this.controllerClass, className);\n constructor.addParameter(annotatedMapOfWrappers, \"registeredHandlerWrappers\");\n\n constructor.addStatement(\"this.$N = $N\", className, className);\n constructor.addStatement(\"this.$N = $N\", \"registeredHandlerWrappers\", \"registeredHandlerWrappers\");\n\n addClassMethodHandlers(typeBuilder, this.controllerClass);\n\n typeBuilder.addMethod(constructor.build());\n\n JavaFile javaFile = JavaFile.builder(packageName, typeBuilder.build()).addStaticImport(extractorClass, \"*\").build();\n\n StringBuilder sb = new StringBuilder();\n\n javaFile.writeTo(sb);\n\n this.sourceString = sb.toString();\n\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n }\n }", "Response delete(URI uri) {\n HttpConnection connection = Http.DELETE(uri);\n return executeToResponse(connection);\n }", "public static String flatten(String left, String right) {\n\t\treturn left == null || left.isEmpty() ? right : left + \".\" + right;\n\t}", "private static void validatePseudoScopedBean(Bean<?> bean, BeanManagerImpl beanManager) {\n if (bean.getInjectionPoints().isEmpty()) {\n // Skip validation if there are no injection points (e.g. for classes which are not intended to be used as beans)\n return;\n }\n reallyValidatePseudoScopedBean(bean, beanManager, new LinkedHashSet<Object>(), new HashSet<Bean<?>>());\n }", "private void onShow() {\n\n if (m_detailsFieldset != null) {\n m_detailsFieldset.getContentPanel().getElement().getStyle().setPropertyPx(\n \"maxHeight\",\n getAvailableHeight(m_messageWidget.getOffsetHeight()));\n }\n }", "protected static <K, T> void groupAnswer(final Map<K, List<T>> answer, T element, K value) {\n if (answer.containsKey(value)) {\n answer.get(value).add(element);\n } else {\n List<T> groupedElements = new ArrayList<T>();\n groupedElements.add(element);\n answer.put(value, groupedElements);\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}", "public void setEveryWorkingDay(final boolean isEveryWorkingDay) {\n\n if (m_model.isEveryWorkingDay() != isEveryWorkingDay) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setEveryWorkingDay(Boolean.valueOf(isEveryWorkingDay));\n m_model.setInterval(getPatternDefaultValues().getInterval());\n onValueChange();\n }\n });\n }\n }" ]
Registers an event handler in the repository shared between Javascript and Java. @param h Event handler to be registered. @return Callback key that Javascript will use to find this handler.
[ "private String registerEventHandler(GFXEventHandler h) {\n //checkInitialized();\n if (!registeredOnJS) {\n JSObject doc = (JSObject) runtime.execute(\"document\");\n doc.setMember(\"jsHandlers\", jsHandlers);\n registeredOnJS = true;\n }\n return jsHandlers.registerHandler(h);\n }" ]
[ "private void appendParameter(Object value, StringBuffer buf)\r\n {\r\n if (value instanceof Query)\r\n {\r\n appendSubQuery((Query) value, buf);\r\n }\r\n else\r\n {\r\n buf.append(\"?\");\r\n }\r\n }", "public final void setDefaultStyle(final Map<String, Style> defaultStyle) {\n this.defaultStyle = new HashMap<>(defaultStyle.size());\n for (Map.Entry<String, Style> entry: defaultStyle.entrySet()) {\n String normalizedName = GEOMETRY_NAME_ALIASES.get(entry.getKey().toLowerCase());\n\n if (normalizedName == null) {\n normalizedName = entry.getKey().toLowerCase();\n }\n\n this.defaultStyle.put(normalizedName, entry.getValue());\n }\n }", "public static Provider getCurrentProvider(boolean useSwingEventQueue) {\n Provider provider;\n if (Platform.isX11()) {\n provider = new X11Provider();\n } else if (Platform.isWindows()) {\n provider = new WindowsProvider();\n } else if (Platform.isMac()) {\n provider = new CarbonProvider();\n } else {\n LOGGER.warn(\"No suitable provider for \" + System.getProperty(\"os.name\"));\n return null;\n }\n provider.setUseSwingEventQueue(useSwingEventQueue);\n provider.init();\n return provider;\n\n }", "protected long buildNextSequence(PersistenceBroker broker, ClassDescriptor cld, String sequenceName)\r\n throws LookupException, SQLException, PlatformException\r\n {\r\n CallableStatement cs = null;\r\n try\r\n {\r\n Connection con = broker.serviceConnectionManager().getConnection();\r\n cs = getPlatform().prepareNextValProcedureStatement(con, PROCEDURE_NAME, sequenceName);\r\n cs.executeUpdate();\r\n return cs.getLong(1);\r\n }\r\n finally\r\n {\r\n try\r\n {\r\n if (cs != null)\r\n cs.close();\r\n }\r\n catch (SQLException ignore)\r\n {\r\n // ignore it\r\n }\r\n }\r\n }", "private CompiledStatement assignStatementArguments(CompiledStatement stmt) throws SQLException {\n\t\tboolean ok = false;\n\t\ttry {\n\t\t\tif (limit != null) {\n\t\t\t\t// we use this if SQL statement LIMITs are not supported by this database type\n\t\t\t\tstmt.setMaxRows(limit.intValue());\n\t\t\t}\n\t\t\t// set any arguments if we are logging our object\n\t\t\tObject[] argValues = null;\n\t\t\tif (logger.isLevelEnabled(Level.TRACE) && argHolders.length > 0) {\n\t\t\t\targValues = new Object[argHolders.length];\n\t\t\t}\n\t\t\tfor (int i = 0; i < argHolders.length; i++) {\n\t\t\t\tObject argValue = argHolders[i].getSqlArgValue();\n\t\t\t\tFieldType fieldType = argFieldTypes[i];\n\t\t\t\tSqlType sqlType;\n\t\t\t\tif (fieldType == null) {\n\t\t\t\t\tsqlType = argHolders[i].getSqlType();\n\t\t\t\t} else {\n\t\t\t\t\tsqlType = fieldType.getSqlType();\n\t\t\t\t}\n\t\t\t\tstmt.setObject(i, argValue, sqlType);\n\t\t\t\tif (argValues != null) {\n\t\t\t\t\targValues[i] = argValue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tlogger.debug(\"prepared statement '{}' with {} args\", statement, argHolders.length);\n\t\t\tif (argValues != null) {\n\t\t\t\t// need to do the (Object) cast to force args to be a single object\n\t\t\t\tlogger.trace(\"prepared statement arguments: {}\", (Object) argValues);\n\t\t\t}\n\t\t\tok = true;\n\t\t\treturn stmt;\n\t\t} finally {\n\t\t\tif (!ok) {\n\t\t\t\tIOUtils.closeThrowSqlException(stmt, \"statement\");\n\t\t\t}\n\t\t}\n\t}", "private static Document objectForInsert(Tuple tuple, Document dbObject) {\n\t\tMongoDBTupleSnapshot snapshot = (MongoDBTupleSnapshot) tuple.getSnapshot();\n\t\tfor ( TupleOperation operation : tuple.getOperations() ) {\n\t\t\tString column = operation.getColumn();\n\t\t\tif ( notInIdField( snapshot, column ) ) {\n\t\t\t\tswitch ( operation.getType() ) {\n\t\t\t\t\tcase PUT:\n\t\t\t\t\t\tMongoHelpers.setValue( dbObject, column, operation.getValue() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase PUT_NULL:\n\t\t\t\t\tcase REMOVE:\n\t\t\t\t\t\tMongoHelpers.resetValue( dbObject, column );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn dbObject;\n\t}", "public static void setTranslucentStatusFlag(Activity activity, boolean on) {\n if (Build.VERSION.SDK_INT >= 19) {\n setFlag(activity, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, on);\n }\n }", "public void deleteStoreDefinition(String storeName) {\n // acquire write lock\n writeLock.lock();\n\n try {\n // Check if store exists\n if(!this.storeNames.contains(storeName)) {\n throw new VoldemortException(\"Requested store to be deleted does not exist !\");\n }\n\n // Otherwise remove from the STORES directory. Note: The version\n // argument is not required here since the\n // ConfigurationStorageEngine simply ignores this.\n this.storeDefinitionsStorageEngine.delete(storeName, null);\n\n // Update the metadata cache\n this.metadataCache.remove(storeName);\n\n // Re-initialize the store definitions. This is primarily required\n // to re-create the value for key: 'stores.xml'. This is necessary\n // for backwards compatibility.\n initStoreDefinitions(null);\n } finally {\n writeLock.unlock();\n }\n }", "Map<String, EntityDocument> getEntityDocumentMap(int numOfEntities,\n\t\t\tWbGetEntitiesActionData properties)\n\t\t\tthrows MediaWikiApiErrorException, IOException {\n\t\tif (numOfEntities == 0) {\n\t\t\treturn Collections.emptyMap();\n\t\t}\n\t\tconfigureProperties(properties);\n\t\treturn this.wbGetEntitiesAction.wbGetEntities(properties);\n\t}" ]
Create a new file but fail if it already exists. The check for existance of the file and it's creation are an atomic operation with respect to other filesystem activities.
[ "public void createNewFile() throws SmbException {\n if( getUncPath0().length() == 1 ) {\n throw new SmbException( \"Invalid operation for workgroups, servers, or shares\" );\n }\n close( open0( O_RDWR | O_CREAT | O_EXCL, 0, ATTR_NORMAL, 0 ), 0L );\n }" ]
[ "@SuppressWarnings({\"UnusedDeclaration\"})\n public void doIndex(StaplerRequest req, StaplerResponse resp) throws IOException, ServletException {\n req.getView(this, chooseAction()).forward(req, resp);\n }", "private InterfaceAddress findMatchingAddress(DeviceAnnouncement aDevice, NetworkInterface networkInterface) {\n for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) {\n if ((address.getBroadcast() != null) &&\n Util.sameNetwork(address.getNetworkPrefixLength(), aDevice.getAddress(), address.getAddress())) {\n return address;\n }\n }\n return null;\n }", "@RequestMapping(value = \"/api/plugins\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getPluginInformation() {\n return pluginInformation();\n }", "public final Object getValue(final String id, final String property) {\n final CriteriaBuilder builder = getSession().getCriteriaBuilder();\n final CriteriaQuery<Object> criteria = builder.createQuery(Object.class);\n final Root<PrintJobStatusExtImpl> root = criteria.from(PrintJobStatusExtImpl.class);\n criteria.select(root.get(property));\n criteria.where(builder.equal(root.get(\"referenceId\"), id));\n return getSession().createQuery(criteria).uniqueResult();\n }", "public static boolean hasAnnotation(Method method, Class<? extends Annotation> annotation) {\n return !searchForAnnotation(method, annotation).isEmpty();\n }", "public static <T> ServiceFuture<T> fromResponse(final Observable<ServiceResponse<T>> observable, final ServiceCallback<T> callback) {\n final ServiceFuture<T> serviceFuture = new ServiceFuture<>();\n serviceFuture.subscription = observable\n .last()\n .subscribe(new Action1<ServiceResponse<T>>() {\n @Override\n public void call(ServiceResponse<T> t) {\n if (callback != null) {\n callback.success(t.body());\n }\n serviceFuture.set(t.body());\n }\n }, new Action1<Throwable>() {\n @Override\n public void call(Throwable throwable) {\n if (callback != null) {\n callback.failure(throwable);\n }\n serviceFuture.setException(throwable);\n }\n });\n return serviceFuture;\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 parseString(String value)\n {\n if (value != null)\n {\n // Strip angle brackets if present\n if (!value.isEmpty() && value.charAt(0) == '<')\n {\n value = value.substring(1, value.length() - 1);\n }\n\n // Strip quotes if present\n if (!value.isEmpty() && value.charAt(0) == '\"')\n {\n value = value.substring(1, value.length() - 1);\n }\n }\n return value;\n }", "private void buildMultiJoinTree(TableAlias left, ClassDescriptor cld, String name, boolean useOuterJoin)\r\n {\r\n DescriptorRepository repository = cld.getRepository();\r\n Class[] multiJoinedClasses = repository.getSubClassesMultipleJoinedTables(cld, false);\r\n\r\n for (int i = 0; i < multiJoinedClasses.length; i++)\r\n {\r\n ClassDescriptor subCld = repository.getDescriptorFor(multiJoinedClasses[i]);\r\n SuperReferenceDescriptor srd = subCld.getSuperReference();\r\n if (srd != null)\r\n {\r\n FieldDescriptor[] leftFields = subCld.getPkFields();\r\n FieldDescriptor[] rightFields = srd.getForeignKeyFieldDescriptors(subCld);\r\n TableAlias base_alias = getTableAliasForPath(name, null, null);\r\n\r\n String aliasName = String.valueOf(getAliasChar()) + m_aliasCount++;\r\n TableAlias right = new TableAlias(subCld, aliasName, false, null);\r\n\r\n Join join1to1 = new Join(left, leftFields, right, rightFields, useOuterJoin, \"subClass\");\r\n base_alias.addJoin(join1to1);\r\n\r\n buildMultiJoinTree(right, subCld, name, useOuterJoin);\r\n }\r\n }\r\n }" ]
Use this API to fetch statistics of rnatip_stats resource of given name .
[ "public static rnatip_stats get(nitro_service service, String Rnatip) throws Exception{\n\t\trnatip_stats obj = new rnatip_stats();\n\t\tobj.set_Rnatip(Rnatip);\n\t\trnatip_stats response = (rnatip_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}" ]
[ "public static authenticationvserver_binding get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_binding obj = new authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_binding response = (authenticationvserver_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static JRDesignGroup getJRDesignGroup(DynamicJasperDesign jd, LayoutManager layoutManager, DJGroup group) {\n\t\tMap references = layoutManager.getReferencesMap();\n\t\tfor (Object o : references.keySet()) {\n\t\t\tString groupName = (String) o;\n\t\t\tDJGroup djGroup = (DJGroup) references.get(groupName);\n\t\t\tif (group == djGroup) {\n\t\t\t\treturn (JRDesignGroup) jd.getGroupsMap().get(groupName);\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}", "public void addIn(Object attribute, Query subQuery)\r\n {\r\n // PAW\r\n\t\t// addSelectionCriteria(ValueCriteria.buildInCriteria(attribute, subQuery, getAlias()));\r\n\t\taddSelectionCriteria(ValueCriteria.buildInCriteria(attribute, subQuery, getUserAlias(attribute)));\r\n }", "public static void acceptsUrl(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_U, OPT_URL), \"bootstrap url\")\n .withRequiredArg()\n .describedAs(\"url\")\n .ofType(String.class);\n }", "@Override\n\tpublic Set<String> getRoundingNames(String... providers) {\n Set<String> result = new HashSet<>();\n String[] providerNames = providers;\n if (providerNames.length == 0) {\n providerNames = Monetary.getDefaultRoundingProviderChain().toArray(new String[Monetary.getDefaultRoundingProviderChain().size()]);\n }\n for (String providerName : providerNames) {\n for (RoundingProviderSpi prov : Bootstrap.getServices(RoundingProviderSpi.class)) {\n try {\n if (prov.getProviderName().equals(providerName) || prov.getProviderName().matches(providerName)) {\n result.addAll(prov.getRoundingNames());\n }\n } catch (Exception e) {\n Logger.getLogger(DefaultMonetaryRoundingsSingletonSpi.class.getName())\n .log(Level.SEVERE, \"Error loading RoundingProviderSpi from provider: \" + prov, e);\n }\n }\n }\n return result;\n }", "private int getFixedDataFieldSize(FieldType type)\n {\n int result = 0;\n DataType dataType = type.getDataType();\n if (dataType != null)\n {\n switch (dataType)\n {\n case DATE:\n case INTEGER:\n case DURATION:\n {\n result = 4;\n break;\n }\n\n case TIME_UNITS:\n case CONSTRAINT:\n case PRIORITY:\n case PERCENTAGE:\n case TASK_TYPE:\n case ACCRUE:\n case SHORT:\n case BOOLEAN:\n case DELAY:\n case WORKGROUP:\n case RATE_UNITS:\n case EARNED_VALUE_METHOD:\n case RESOURCE_REQUEST_TYPE:\n {\n result = 2;\n break;\n }\n\n case CURRENCY:\n case UNITS:\n case RATE:\n case WORK:\n {\n result = 8;\n break;\n }\n\n case WORK_UNITS:\n {\n result = 1;\n break;\n }\n\n case GUID:\n {\n result = 16;\n break;\n }\n\n default:\n {\n result = 0;\n break;\n }\n }\n }\n\n return result;\n }", "List getOrderby()\r\n {\r\n List result = _getOrderby();\r\n Iterator iter = getCriteria().iterator();\r\n Object crit;\r\n\r\n while (iter.hasNext())\r\n {\r\n crit = iter.next();\r\n if (crit instanceof Criteria)\r\n {\r\n result.addAll(((Criteria) crit).getOrderby());\r\n }\r\n }\r\n\r\n return result;\r\n }", "public static DMatrixSparseCSC rectangle(int numRows , int numCols , int nz_total ,\n double min , double max , Random rand ) {\n\n nz_total = Math.min(numCols*numRows,nz_total);\n int[] selected = UtilEjml.shuffled(numRows*numCols, nz_total, rand);\n Arrays.sort(selected,0,nz_total);\n\n DMatrixSparseCSC ret = new DMatrixSparseCSC(numRows,numCols,nz_total);\n ret.indicesSorted = true;\n\n // compute the number of elements in each column\n int hist[] = new int[ numCols ];\n for (int i = 0; i < nz_total; i++) {\n hist[selected[i]/numRows]++;\n }\n\n // define col_idx\n ret.histogramToStructure(hist);\n\n for (int i = 0; i < nz_total; i++) {\n int row = selected[i]%numRows;\n\n ret.nz_rows[i] = row;\n ret.nz_values[i] = rand.nextDouble()*(max-min)+min;\n }\n\n return ret;\n }", "public boolean ignoreOperation(final Resource domainResource, final Collection<ServerConfigInfo> serverConfigs, final PathAddress pathAddress) {\n if (pathAddress.size() == 0) {\n return false;\n }\n boolean ignore = ignoreResourceInternal(domainResource, serverConfigs, pathAddress);\n return ignore;\n }" ]
Process data for an individual calendar. @param row calendar data
[ "public void processCalendar(Row row)\n {\n ProjectCalendar calendar = m_project.addCalendar();\n\n Integer id = row.getInteger(\"clndr_id\");\n m_calMap.put(id, calendar);\n calendar.setName(row.getString(\"clndr_name\"));\n\n try\n {\n calendar.setMinutesPerDay(Integer.valueOf((int) NumberHelper.getDouble(row.getDouble(\"day_hr_cnt\")) * 60));\n calendar.setMinutesPerWeek(Integer.valueOf((int) (NumberHelper.getDouble(row.getDouble(\"week_hr_cnt\")) * 60)));\n calendar.setMinutesPerMonth(Integer.valueOf((int) (NumberHelper.getDouble(row.getDouble(\"month_hr_cnt\")) * 60)));\n calendar.setMinutesPerYear(Integer.valueOf((int) (NumberHelper.getDouble(row.getDouble(\"year_hr_cnt\")) * 60)));\n }\n catch (ClassCastException ex)\n {\n // We have seen examples of malformed calendar data where fields have been missing\n // from the record. We'll typically get a class cast exception here as we're trying\n // to process something which isn't a double.\n // We'll just return at this point as it's not clear that we can salvage anything\n // sensible from this record.\n return;\n }\n\n // Process data\n String calendarData = row.getString(\"clndr_data\");\n if (calendarData != null && !calendarData.isEmpty())\n {\n Record root = Record.getRecord(calendarData);\n if (root != null)\n {\n processCalendarDays(calendar, root);\n processCalendarExceptions(calendar, root);\n }\n }\n else\n {\n // if there is not DaysOfWeek data, Primavera seems to default to Mon-Fri, 8:00-16:00\n DateRange defaultHourRange = new DateRange(DateHelper.getTime(8, 0), DateHelper.getTime(16, 0));\n for (Day day : Day.values())\n {\n if (day != Day.SATURDAY && day != Day.SUNDAY)\n {\n calendar.setWorkingDay(day, true);\n ProjectCalendarHours hours = calendar.addCalendarHours(day);\n hours.addRange(defaultHourRange);\n }\n else\n {\n calendar.setWorkingDay(day, false);\n }\n }\n }\n\n m_eventManager.fireCalendarReadEvent(calendar);\n }" ]
[ "public void addColumn(String columnName, boolean searchable, boolean orderable,\n String searchValue) {\n this.columns.add(new Column(columnName, \"\", searchable, orderable,\n new Search(searchValue, false)));\n }", "public static nssimpleacl get(nitro_service service, String aclname) throws Exception{\n\t\tnssimpleacl obj = new nssimpleacl();\n\t\tobj.set_aclname(aclname);\n\t\tnssimpleacl response = (nssimpleacl) obj.get_resource(service);\n\t\treturn response;\n\t}", "public UseCase selectUseCase()\r\n {\r\n displayUseCases();\r\n System.out.println(\"type in number to select a use case\");\r\n String in = readLine();\r\n int index = Integer.parseInt(in);\r\n return (UseCase) useCases.get(index);\r\n }", "public ItemRequest<Story> delete(String story) {\n \n String path = String.format(\"/stories/%s\", story);\n return new ItemRequest<Story>(this, Story.class, path, \"DELETE\");\n }", "void close() {\n try {\n performTeardownExchange();\n } catch (IOException e) {\n logger.warn(\"Problem reporting our intention to close the dbserver connection\", e);\n }\n try {\n channel.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing dbserver client output channel\", e);\n }\n try {\n os.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing dbserver client output stream\", e);\n }\n try {\n is.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing dbserver client input stream\", e);\n }\n try {\n socket.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing dbserver client socket\", e);\n }\n }", "public double compute( DMatrix1Row mat ) {\n if( width != mat.numCols || width != mat.numRows ) {\n throw new RuntimeException(\"Unexpected matrix dimension\");\n }\n\n // make sure everything is in the proper state before it starts\n initStructures();\n\n// System.arraycopy(mat.data,0,minorMatrix[0],0,mat.data.length);\n\n int level = 0;\n while( true ) {\n int levelWidth = width-level;\n int levelIndex = levelIndexes[level];\n\n if( levelIndex == levelWidth ) {\n if( level == 0 ) {\n return levelResults[0];\n }\n int prevLevelIndex = levelIndexes[level-1]++;\n\n double val = mat.get((level-1)*width+levelRemoved[level-1]);\n if( prevLevelIndex % 2 == 0 ) {\n levelResults[level-1] += val * levelResults[level];\n } else {\n levelResults[level-1] -= val * levelResults[level];\n }\n\n putIntoOpen(level-1);\n\n levelResults[level] = 0;\n levelIndexes[level] = 0;\n level--;\n } else {\n int excluded = openRemove( levelIndex );\n\n levelRemoved[level] = excluded;\n\n if( levelWidth == minWidth ) {\n createMinor(mat);\n double subresult = mat.get(level*width+levelRemoved[level]);\n\n subresult *= UnrolledDeterminantFromMinor_DDRM.det(tempMat);\n\n if( levelIndex % 2 == 0 ) {\n levelResults[level] += subresult;\n } else {\n levelResults[level] -= subresult;\n }\n\n // put it back into the list\n putIntoOpen(level);\n levelIndexes[level]++;\n } else {\n level++;\n }\n }\n }\n }", "private void readCalendar(Project.Calendars.Calendar calendar, HashMap<BigInteger, ProjectCalendar> map, List<Pair<ProjectCalendar, BigInteger>> baseCalendars)\n {\n ProjectCalendar bc = m_projectFile.addCalendar();\n bc.setUniqueID(NumberHelper.getInteger(calendar.getUID()));\n bc.setName(calendar.getName());\n BigInteger baseCalendarID = calendar.getBaseCalendarUID();\n if (baseCalendarID != null)\n {\n baseCalendars.add(new Pair<ProjectCalendar, BigInteger>(bc, baseCalendarID));\n }\n\n readExceptions(calendar, bc);\n boolean readExceptionsFromDays = bc.getCalendarExceptions().isEmpty();\n\n Project.Calendars.Calendar.WeekDays days = calendar.getWeekDays();\n if (days != null)\n {\n for (Project.Calendars.Calendar.WeekDays.WeekDay weekDay : days.getWeekDay())\n {\n readDay(bc, weekDay, readExceptionsFromDays);\n }\n }\n else\n {\n bc.setWorkingDay(Day.SUNDAY, DayType.DEFAULT);\n bc.setWorkingDay(Day.MONDAY, DayType.DEFAULT);\n bc.setWorkingDay(Day.TUESDAY, DayType.DEFAULT);\n bc.setWorkingDay(Day.WEDNESDAY, DayType.DEFAULT);\n bc.setWorkingDay(Day.THURSDAY, DayType.DEFAULT);\n bc.setWorkingDay(Day.FRIDAY, DayType.DEFAULT);\n bc.setWorkingDay(Day.SATURDAY, DayType.DEFAULT);\n }\n\n readWorkWeeks(calendar, bc);\n\n map.put(calendar.getUID(), bc);\n\n m_eventManager.fireCalendarReadEvent(bc);\n }", "public String getDynamicValue(String attribute) {\n\n return null == m_dynamicValues ? null : m_dynamicValues.get(attribute);\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 }" ]
Read an element which contains only a single boolean attribute. @param reader the reader @param attributeName the attribute name, usually "value" @return the boolean value @throws javax.xml.stream.XMLStreamException if an error occurs or if the element does not contain the specified attribute, contains other attributes, or contains child elements.
[ "public static boolean readBooleanAttributeElement(final XMLExtendedStreamReader reader, final String attributeName)\n throws XMLStreamException {\n requireSingleAttribute(reader, attributeName);\n final boolean value = Boolean.parseBoolean(reader.getAttributeValue(0));\n requireNoContent(reader);\n return value;\n }" ]
[ "void stop() {\n try {\n dm.stop(getBundleContext());\n } catch (DirectoryMonitoringException e) {\n LOG.error(\"Failed to stop \" + DirectoryMonitor.class.getName() + \" for the directory \" + monitoredDirectory, e);\n }\n declarationsFiles.clear();\n declarationRegistrationManager.unregisterAll();\n }", "private ProjectFile readProjectFile(ProjectReader reader, File file) throws MPXJException\n {\n addListeners(reader);\n return reader.read(file);\n }", "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 }", "public BoxFileUploadSessionPart uploadPart(byte[] data, long offset, int partSize,\n long totalSizeOfFile) {\n URL uploadPartURL = this.sessionInfo.getSessionEndpoints().getUploadPartEndpoint();\n\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), uploadPartURL, HttpMethod.PUT);\n request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_OCTET_STREAM);\n\n MessageDigest digestInstance = null;\n try {\n digestInstance = MessageDigest.getInstance(DIGEST_ALGORITHM_SHA1);\n } catch (NoSuchAlgorithmException ae) {\n throw new BoxAPIException(\"Digest algorithm not found\", ae);\n }\n\n //Creates the digest using SHA1 algorithm. Then encodes the bytes using Base64.\n byte[] digestBytes = digestInstance.digest(data);\n String digest = Base64.encode(digestBytes);\n request.addHeader(HttpHeaders.DIGEST, DIGEST_HEADER_PREFIX_SHA + digest);\n //Content-Range: bytes offset-part/totalSize\n request.addHeader(HttpHeaders.CONTENT_RANGE,\n \"bytes \" + offset + \"-\" + (offset + partSize - 1) + \"/\" + totalSizeOfFile);\n\n //Creates the body\n request.setBody(new ByteArrayInputStream(data));\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n BoxFileUploadSessionPart part = new BoxFileUploadSessionPart((JsonObject) jsonObject.get(\"part\"));\n return part;\n }", "public AsciiTable setPaddingLeftRight(int padding){\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingLeftRight(padding);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public void rotateWithPivot(float quatW, float quatX, float quatY,\n float quatZ, float pivotX, float pivotY, float pivotZ) {\n NativeTransform.rotateWithPivot(getNative(), quatW, quatX, quatY,\n quatZ, pivotX, pivotY, pivotZ);\n }", "@Override\n public void start(String[] arguments) {\n boolean notStarted = !started.getAndSet(true);\n if (notStarted) {\n start(new MultiInstanceWorkloadStrategy(factory, name, arguments, endpointRegistry, execService));\n }\n }", "private String formatTimeUnit(TimeUnit timeUnit)\n {\n int units = timeUnit.getValue();\n String result;\n String[][] unitNames = LocaleData.getStringArrays(m_locale, LocaleData.TIME_UNITS_ARRAY);\n\n if (units < 0 || units >= unitNames.length)\n {\n result = \"\";\n }\n else\n {\n result = unitNames[units][0];\n }\n\n return (result);\n }", "public static base_response update(nitro_service client, callhome resource) throws Exception {\n\t\tcallhome updateresource = new callhome();\n\t\tupdateresource.emailaddress = resource.emailaddress;\n\t\tupdateresource.proxymode = resource.proxymode;\n\t\tupdateresource.ipaddress = resource.ipaddress;\n\t\tupdateresource.port = resource.port;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
Clones the given collection. @param collDef The collection descriptor @param prefix A prefix for the name @return The cloned collection
[ "private CollectionDescriptorDef cloneCollection(CollectionDescriptorDef collDef, String prefix)\r\n {\r\n CollectionDescriptorDef copyCollDef = new CollectionDescriptorDef(collDef, prefix);\r\n\r\n copyCollDef.setOwner(this);\r\n // we remove properties that are only relevant to the class the features are declared in\r\n copyCollDef.setProperty(PropertyHelper.OJB_PROPERTY_IGNORE, null);\r\n\r\n Properties mod = getModification(copyCollDef.getName());\r\n\r\n if (mod != null)\r\n {\r\n if (!PropertyHelper.toBoolean(mod.getProperty(PropertyHelper.OJB_PROPERTY_IGNORE), false) &&\r\n hasFeature(copyCollDef.getName()))\r\n {\r\n LogHelper.warn(true,\r\n ClassDescriptorDef.class,\r\n \"process\",\r\n \"Class \"+getName()+\" has a feature that has the same name as its included collection \"+\r\n copyCollDef.getName()+\" from class \"+collDef.getOwner().getName()); \r\n }\r\n copyCollDef.applyModifications(mod);\r\n }\r\n return copyCollDef;\r\n }" ]
[ "public static authenticationvserver_binding get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_binding obj = new authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_binding response = (authenticationvserver_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "public Configuration[] getConfigurations(String name) {\n ArrayList<Configuration> valuesList = new ArrayList<Configuration>();\n\n logger.info(\"Getting data for {}\", name);\n\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n\n String queryString = \"SELECT * FROM \" + Constants.DB_TABLE_CONFIGURATION;\n if (name != null) {\n queryString += \" WHERE \" + Constants.DB_TABLE_CONFIGURATION_NAME + \"=?\";\n }\n\n statement = sqlConnection.prepareStatement(queryString);\n if (name != null) {\n statement.setString(1, name);\n }\n\n results = statement.executeQuery();\n while (results.next()) {\n Configuration config = new Configuration();\n config.setValue(results.getString(Constants.DB_TABLE_CONFIGURATION_VALUE));\n config.setKey(results.getString(Constants.DB_TABLE_CONFIGURATION_NAME));\n config.setId(results.getInt(Constants.GENERIC_ID));\n logger.info(\"the configValue is = {}\", config.getValue());\n valuesList.add(config);\n }\n } catch (SQLException sqe) {\n logger.info(\"Exception in sql\");\n sqe.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 if (valuesList.size() == 0) {\n return null;\n }\n\n return valuesList.toArray(new Configuration[0]);\n }", "synchronized ArrayList<CTMessageDAO> getMessages(String userId){\n final String tName = Table.INBOX_MESSAGES.getName();\n Cursor cursor;\n ArrayList<CTMessageDAO> messageDAOArrayList = new ArrayList<>();\n try{\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n cursor= db.rawQuery(\"SELECT * FROM \"+tName+\" WHERE \" + USER_ID + \" = ? ORDER BY \" + KEY_CREATED_AT+ \" DESC\", new String[]{userId});\n if(cursor != null) {\n while(cursor.moveToNext()){\n CTMessageDAO ctMessageDAO = new CTMessageDAO();\n ctMessageDAO.setId(cursor.getString(cursor.getColumnIndex(_ID)));\n ctMessageDAO.setJsonData(new JSONObject(cursor.getString(cursor.getColumnIndex(KEY_DATA))));\n ctMessageDAO.setWzrkParams(new JSONObject(cursor.getString(cursor.getColumnIndex(WZRKPARAMS))));\n ctMessageDAO.setDate(cursor.getLong(cursor.getColumnIndex(KEY_CREATED_AT)));\n ctMessageDAO.setExpires(cursor.getLong(cursor.getColumnIndex(EXPIRES)));\n ctMessageDAO.setRead(cursor.getInt(cursor.getColumnIndex(IS_READ)));\n ctMessageDAO.setUserId(cursor.getString(cursor.getColumnIndex(USER_ID)));\n ctMessageDAO.setTags(cursor.getString(cursor.getColumnIndex(TAGS)));\n ctMessageDAO.setCampaignId(cursor.getString(cursor.getColumnIndex(CAMPAIGN)));\n messageDAOArrayList.add(ctMessageDAO);\n }\n cursor.close();\n }\n return messageDAOArrayList;\n }catch (final SQLiteException e){\n getConfigLogger().verbose(\"Error retrieving records from \" + tName, e);\n return null;\n } catch (JSONException e) {\n getConfigLogger().verbose(\"Error retrieving records from \" + tName, e.getMessage());\n return null;\n } finally {\n dbHelper.close();\n }\n }", "public static Info ones( final Variable A , final Variable B , ManagerTempVariables manager) {\n Info ret = new Info();\n final VariableMatrix output = manager.createMatrix();\n ret.output = output;\n\n if( A instanceof VariableInteger && B instanceof VariableInteger ) {\n ret.op = new Operation(\"ones-ii\") {\n @Override\n public void process() {\n int numRows = ((VariableInteger)A).value;\n int numCols = ((VariableInteger)B).value;\n output.matrix.reshape(numRows,numCols);\n CommonOps_DDRM.fill(output.matrix, 1);\n }\n };\n } else {\n throw new RuntimeException(\"Expected two integers got \"+A+\" \"+B);\n }\n\n return ret;\n }", "public int getInt(Integer type)\n {\n int result = 0;\n\n byte[] item = m_map.get(type);\n if (item != null)\n {\n result = MPPUtility.getInt(item, 0);\n }\n\n return (result);\n }", "public void addEmailStats(final InternetAddress[] recipients, final boolean storageUsed) {\n this.storageUsed = storageUsed;\n for (InternetAddress recipient: recipients) {\n emailDests.add(recipient.getAddress());\n }\n }", "public String getRejectionLogMessageId() {\n String id = logMessageId;\n if (id == null) {\n id = getRejectionLogMessage(Collections.<String, ModelNode>emptyMap());\n }\n logMessageId = id;\n return logMessageId;\n }", "public IndirectionHandler getIndirectionHandler(Object obj)\r\n {\r\n if(obj == null)\r\n {\r\n return null;\r\n }\r\n else if(isNormalOjbProxy(obj))\r\n {\r\n return getDynamicIndirectionHandler(obj);\r\n }\r\n else if(isVirtualOjbProxy(obj))\r\n {\r\n return VirtualProxy.getIndirectionHandler((VirtualProxy) obj);\r\n }\r\n else\r\n {\r\n return null;\r\n }\r\n\r\n }", "public String getToken() {\n String id = null == answer ? text : answer;\n return Act.app().crypto().generateToken(id);\n }" ]
Start unmarshalling using the parser. @param parser @param preProcessingData @return the root element of a bpmn2 document. @throws java.io.IOException
[ "private Bpmn2Resource unmarshall(JsonParser parser,\n String preProcessingData) throws IOException {\n try {\n parser.nextToken(); // open the object\n ResourceSet rSet = new ResourceSetImpl();\n rSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(\"bpmn2\",\n new JBPMBpmn2ResourceFactoryImpl());\n Bpmn2Resource bpmn2 = (Bpmn2Resource) rSet.createResource(URI.createURI(\"virtual.bpmn2\"));\n rSet.getResources().add(bpmn2);\n _currentResource = bpmn2;\n\n if (preProcessingData == null || preProcessingData.length() < 1) {\n preProcessingData = \"ReadOnlyService\";\n }\n\n // do the unmarshalling now:\n Definitions def = (Definitions) unmarshallItem(parser,\n preProcessingData);\n def.setExporter(exporterName);\n def.setExporterVersion(exporterVersion);\n revisitUserTasks(def);\n revisitServiceTasks(def);\n revisitMessages(def);\n revisitCatchEvents(def);\n revisitThrowEvents(def);\n revisitLanes(def);\n revisitSubProcessItemDefs(def);\n revisitArtifacts(def);\n revisitGroups(def);\n revisitTaskAssociations(def);\n revisitTaskIoSpecification(def);\n revisitSendReceiveTasks(def);\n reconnectFlows();\n revisitGateways(def);\n revisitCatchEventsConvertToBoundary(def);\n revisitBoundaryEventsPositions(def);\n createDiagram(def);\n updateIDs(def);\n revisitDataObjects(def);\n revisitAssociationsIoSpec(def);\n revisitWsdlImports(def);\n revisitMultiInstanceTasks(def);\n addSimulation(def);\n revisitItemDefinitions(def);\n revisitProcessDoc(def);\n revisitDI(def);\n revisitSignalRef(def);\n orderDiagramElements(def);\n\n // return def;\n _currentResource.getContents().add(def);\n return _currentResource;\n } catch (Exception e) {\n _logger.error(e.getMessage());\n return _currentResource;\n } finally {\n parser.close();\n _objMap.clear();\n _idMap.clear();\n _outgoingFlows.clear();\n _sequenceFlowTargets.clear();\n _bounds.clear();\n _currentResource = null;\n }\n }" ]
[ "public List<URL> scan(Predicate<String> filter)\n {\n List<URL> discoveredURLs = new ArrayList<>(128);\n\n // For each Forge addon...\n for (Addon addon : furnace.getAddonRegistry().getAddons(AddonFilters.allStarted()))\n {\n List<String> filteredResourcePaths = filterAddonResources(addon, filter);\n for (String filePath : filteredResourcePaths)\n {\n URL ruleFile = addon.getClassLoader().getResource(filePath);\n if (ruleFile != null)\n discoveredURLs.add(ruleFile);\n }\n }\n return discoveredURLs;\n }", "public final Processor.ExecutionContext print(\n final String jobId, final PJsonObject specJson, final OutputStream out)\n throws Exception {\n final OutputFormat format = getOutputFormat(specJson);\n final File taskDirectory = this.workingDirectories.getTaskDirectory();\n\n try {\n return format.print(jobId, specJson, getConfiguration(), this.configFile.getParentFile(),\n taskDirectory, out);\n } finally {\n this.workingDirectories.removeDirectory(taskDirectory);\n }\n }", "private void readHolidays()\n {\n for (MapRow row : m_tables.get(\"HOL\"))\n {\n ProjectCalendar calendar = m_calendarMap.get(row.getInteger(\"CALENDAR_ID\"));\n if (calendar != null)\n {\n Date date = row.getDate(\"DATE\");\n ProjectCalendarException exception = calendar.addCalendarException(date, date);\n if (row.getBoolean(\"ANNUAL\"))\n {\n RecurringData recurring = new RecurringData();\n recurring.setRecurrenceType(RecurrenceType.YEARLY);\n recurring.setYearlyAbsoluteFromDate(date);\n recurring.setStartDate(date);\n exception.setRecurring(recurring);\n // TODO set end date based on project end date\n }\n }\n }\n }", "private static List<CmsCategory> getCategories(CmsObject cms, CmsResource resource) {\n\n if ((null != resource) && (null != cms)) {\n try {\n return CmsCategoryService.getInstance().readResourceCategories(cms, resource);\n } catch (CmsException e) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n }\n return new ArrayList<CmsCategory>(0);\n }", "private static JSONArray parseStencilSetExtensions(ArrayList<String> extensions) {\n if (extensions != null) {\n JSONArray extensionsArray = new JSONArray();\n\n for (String extension : extensions) {\n extensionsArray.put(extension.toString());\n }\n\n return extensionsArray;\n }\n\n return new JSONArray();\n }", "public static NodeList evaluateXpathExpression(Document dom, String xpathExpr)\n\t\t\tthrows XPathExpressionException {\n\t\tXPathFactory factory = XPathFactory.newInstance();\n\t\tXPath xpath = factory.newXPath();\n\t\tXPathExpression expr = xpath.compile(xpathExpr);\n\t\tObject result = expr.evaluate(dom, XPathConstants.NODESET);\n\t\treturn (NodeList) result;\n\t}", "@SuppressWarnings(\"unchecked\") public Map<String, Object> getCustomProperties()\n {\n return (Map<String, Object>) getCachedValue(ProjectField.CUSTOM_PROPERTIES);\n }", "public static base_response unset(nitro_service client, systemuser resource, String[] args) throws Exception{\n\t\tsystemuser unsetresource = new systemuser();\n\t\tunsetresource.username = resource.username;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public final PJsonObject getJSONObject(final int i) {\n JSONObject val = this.array.optJSONObject(i);\n final String context = \"[\" + i + \"]\";\n if (val == null) {\n throw new ObjectMissingException(this, context);\n }\n return new PJsonObject(this, val, context);\n }" ]
calculate and set position to menu items
[ "private void calculateMenuItemPosition() {\n\n float itemRadius = (expandedRadius + collapsedRadius) / 2, f;\n RectF area = new RectF(\n center.x - itemRadius,\n center.y - itemRadius,\n center.x + itemRadius,\n center.y + itemRadius);\n Path path = new Path();\n path.addArc(area, (float) fromAngle, (float) (toAngle - fromAngle));\n PathMeasure measure = new PathMeasure(path, false);\n float len = measure.getLength();\n int divisor = getChildCount();\n float divider = len / divisor;\n\n for (int i = 0; i < getChildCount(); i++) {\n float[] coords = new float[2];\n measure.getPosTan(i * divider + divider * .5f, coords, null);\n FilterMenu.Item item = (FilterMenu.Item) getChildAt(i).getTag();\n item.setX((int) coords[0] - item.getView().getMeasuredWidth() / 2);\n item.setY((int) coords[1] - item.getView().getMeasuredHeight() / 2);\n }\n }" ]
[ "@SuppressWarnings({\"WeakerAccess\"})\n protected void initDeviceID() {\n getDeviceCachedInfo(); // put this here to avoid running on main thread\n\n // generate a provisional while we do the rest async\n generateProvisionalGUID();\n // grab and cache the googleAdID in any event if available\n // if we already have a deviceID we won't user ad id as the guid\n cacheGoogleAdID();\n\n // if we already have a device ID use it and just notify\n // otherwise generate one, either from ad id if available or the provisional\n String deviceID = getDeviceID();\n if (deviceID == null || deviceID.trim().length() <= 2) {\n generateDeviceID();\n }\n\n }", "public static ComplexNumber Multiply(ComplexNumber z1, ComplexNumber z2) {\r\n double z1R = z1.real, z1I = z1.imaginary;\r\n double z2R = z2.real, z2I = z2.imaginary;\r\n\r\n return new ComplexNumber(z1R * z2R - z1I * z2I, z1R * z2I + z1I * z2R);\r\n }", "public static String getAggregatedResultHuman(Map<String, LinkedHashSet<String>> aggregateResultMap){\n\n StringBuilder res = new StringBuilder();\n\n for (Entry<String, LinkedHashSet<String>> entry : aggregateResultMap\n .entrySet()) {\n LinkedHashSet<String> valueSet = entry.getValue(); \n res.append(\"[\" + entry.getKey() + \" COUNT: \" +valueSet.size() + \" ]:\\n\");\n for(String str: valueSet){\n res.append(\"\\t\" + str + \"\\n\");\n }\n res.append(\"###################################\\n\\n\");\n }\n \n return res.toString();\n \n }", "private long size(final Jedis jedis, final String queueName) {\n final String key = key(QUEUE, queueName);\n final long size;\n if (JedisUtils.isDelayedQueue(jedis, key)) { // If delayed queue, use ZCARD\n size = jedis.zcard(key);\n } else { // Else, use LLEN\n size = jedis.llen(key);\n }\n return size;\n }", "public static DatabaseFieldConfig fromReader(BufferedReader reader) throws SQLException {\n\t\tDatabaseFieldConfig config = new DatabaseFieldConfig();\n\t\tboolean anything = false;\n\t\twhile (true) {\n\t\t\tString line;\n\t\t\ttry {\n\t\t\t\tline = reader.readLine();\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow SqlExceptionUtil.create(\"Could not read DatabaseFieldConfig from stream\", e);\n\t\t\t}\n\t\t\tif (line == null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// we do this so we can support multiple class configs per file\n\t\t\tif (line.equals(CONFIG_FILE_END_MARKER)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// skip empty lines or comments\n\t\t\tif (line.length() == 0 || line.startsWith(\"#\") || line.equals(CONFIG_FILE_START_MARKER)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tString[] parts = line.split(\"=\", -2);\n\t\t\tif (parts.length != 2) {\n\t\t\t\tthrow new SQLException(\"DatabaseFieldConfig reading from stream cannot parse line: \" + line);\n\t\t\t}\n\t\t\treadField(config, parts[0], parts[1]);\n\t\t\tanything = true;\n\t\t}\n\t\t// if we got any config lines then we return the config\n\t\tif (anything) {\n\t\t\treturn config;\n\t\t} else {\n\t\t\t// otherwise we return null for none\n\t\t\treturn null;\n\t\t}\n\t}", "public static filterglobal_filterpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tfilterglobal_filterpolicy_binding obj = new filterglobal_filterpolicy_binding();\n\t\tfilterglobal_filterpolicy_binding response[] = (filterglobal_filterpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public boolean removeCustomResponse(String pathValue, String requestType) {\n try {\n JSONObject path = getPathFromEndpoint(pathValue, requestType);\n if (path == null) {\n return false;\n }\n String pathId = path.getString(\"pathId\");\n return resetResponseOverride(pathId);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }", "protected <C> C convert(Object object, Class<C> targetClass) {\n return this.mapper.convertValue(object, targetClass);\n }", "public synchronized int get(byte[] dst, int off, int len) {\n if (available == 0) {\n return 0;\n }\n\n // limit is last index to read + 1\n int limit = idxGet < idxPut ? idxPut : capacity;\n int count = Math.min(limit - idxGet, len);\n System.arraycopy(buffer, idxGet, dst, off, count);\n idxGet += count;\n\n if (idxGet == capacity) {\n // Array end reached, check if we have more\n int count2 = Math.min(len - count, idxPut);\n if (count2 > 0) {\n System.arraycopy(buffer, 0, dst, off + count, count2);\n idxGet = count2;\n count += count2;\n } else {\n idxGet = 0;\n }\n }\n available -= count;\n return count;\n }" ]
Handling out request. @param message the message @throws Fault the fault
[ "protected void handleRequestOut(T message) throws Fault {\n String flowId = FlowIdHelper.getFlowId(message);\n if (flowId == null\n && message.containsKey(PhaseInterceptorChain.PREVIOUS_MESSAGE)) {\n // Web Service consumer is acting as an intermediary\n @SuppressWarnings(\"unchecked\")\n WeakReference<Message> wrPreviousMessage = (WeakReference<Message>) message\n .get(PhaseInterceptorChain.PREVIOUS_MESSAGE);\n Message previousMessage = (Message) wrPreviousMessage.get();\n flowId = FlowIdHelper.getFlowId(previousMessage);\n if (flowId != null && LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"flowId '\" + flowId + \"' found in previous message\");\n }\n }\n\n if (flowId == null) {\n // No flowId found. Generate one.\n flowId = ContextUtils.generateUUID();\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Generate new flowId '\" + flowId + \"'\");\n }\n }\n\n FlowIdHelper.setFlowId(message, flowId);\n }" ]
[ "public <E extends Enum<E> & FieldType> E nextField(Class<E> clazz, UserFieldDataType type)\n {\n for (String name : m_names[type.ordinal()])\n {\n int i = NumberHelper.getInt(m_counters.get(name)) + 1;\n try\n {\n E e = Enum.valueOf(clazz, name + i);\n m_counters.put(name, Integer.valueOf(i));\n return e;\n }\n catch (IllegalArgumentException ex)\n {\n // try the next name\n }\n }\n\n // no more fields available\n throw new IllegalArgumentException(\"No fields for type \" + type + \" available\");\n }", "public OpenShiftAssistantTemplate parameter(String name, String value) {\n parameterValues.put(name, value);\n return this;\n }", "@Override\n public void close() throws VoldemortException {\n logger.debug(\"Close called for read-only store.\");\n this.fileModificationLock.writeLock().lock();\n\n try {\n if(isOpen) {\n this.isOpen = false;\n fileSet.close();\n } else {\n logger.debug(\"Attempt to close already closed store \" + getName());\n }\n } finally {\n this.fileModificationLock.writeLock().unlock();\n }\n }", "private void allRelation(Options opt, RelationType rt, ClassDoc from) {\n\tString tagname = rt.lower;\n\tfor (Tag tag : from.tags(tagname)) {\n\t String t[] = tokenize(tag.text()); // l-src label l-dst target\n\t t = t.length == 1 ? new String[] { \"-\", \"-\", \"-\", t[0] } : t; // Shorthand\n\t if (t.length != 4) {\n\t\tSystem.err.println(\"Error in \" + from + \"\\n\" + tagname + \" expects four fields (l-src label l-dst target): \" + tag.text());\n\t\treturn;\n\t }\n\t ClassDoc to = from.findClass(t[3]);\n\t if (to != null) {\n\t\tif(hidden(to))\n\t\t continue;\n\t\trelation(opt, rt, from, to, t[0], t[1], t[2]);\n\t } else {\n\t\tif(hidden(t[3]))\n\t\t continue;\n\t\trelation(opt, rt, from, from.toString(), to, t[3], t[0], t[1], t[2]);\n\t }\n\t}\n }", "private NodeList getNodeList(String document, XPathExpression expression) throws Exception\n {\n Document doc = m_documentBuilder.parse(new InputSource(new StringReader(document)));\n return (NodeList) expression.evaluate(doc, XPathConstants.NODESET);\n }", "public String processObjectCache(Properties attributes) throws XDocletException\r\n {\r\n ObjectCacheDef objCacheDef = _curClassDef.setObjectCache(attributes.getProperty(ATTRIBUTE_CLASS));\r\n String attrName;\r\n\r\n attributes.remove(ATTRIBUTE_CLASS);\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n objCacheDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n return \"\";\r\n }", "public static String getButtonName(String gallery) {\n\n StringBuffer sb = new StringBuffer(GUI_BUTTON_PREF);\n sb.append(gallery.toUpperCase());\n sb.append(GUI_BUTTON_SUF);\n return sb.toString();\n }", "public static int randomIntBetween(int min, int max) {\n Random rand = new Random();\n return rand.nextInt((max - min) + 1) + min;\n }", "public GeoShapeMapper transform(GeoTransformation... transformations) {\n if (this.transformations == null) {\n this.transformations = Arrays.asList(transformations);\n } else {\n this.transformations.addAll(Arrays.asList(transformations));\n }\n return this;\n }" ]
This could be a self-extracting archive. If we understand the format, expand it and check the content for files we can read. @param stream schedule data @return ProjectFile instance
[ "private ProjectFile handleDosExeFile(InputStream stream) throws Exception\n {\n File file = InputStreamHelper.writeStreamToTempFile(stream, \".tmp\");\n InputStream is = null;\n\n try\n {\n is = new FileInputStream(file);\n if (is.available() > 1350)\n {\n StreamHelper.skip(is, 1024);\n\n // Bytes at offset 1024\n byte[] data = new byte[2];\n is.read(data);\n\n if (matchesFingerprint(data, WINDOWS_NE_EXE_FINGERPRINT))\n {\n StreamHelper.skip(is, 286);\n\n // Bytes at offset 1312\n data = new byte[34];\n is.read(data);\n if (matchesFingerprint(data, PRX_FINGERPRINT))\n {\n is.close();\n is = null;\n return readProjectFile(new P3PRXFileReader(), file);\n }\n }\n\n if (matchesFingerprint(data, STX_FINGERPRINT))\n {\n StreamHelper.skip(is, 31742);\n // Bytes at offset 32768\n data = new byte[4];\n is.read(data);\n if (matchesFingerprint(data, PRX3_FINGERPRINT))\n {\n is.close();\n is = null;\n return readProjectFile(new SureTrakSTXFileReader(), file);\n }\n }\n }\n return null;\n }\n\n finally\n {\n StreamHelper.closeQuietly(is);\n FileHelper.deleteQuietly(file);\n }\n }" ]
[ "public Collection<Contact> getListRecentlyUploaded(Date lastUpload, String filter) throws FlickrException {\r\n List<Contact> contacts = new ArrayList<Contact>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIST_RECENTLY_UPLOADED);\r\n\r\n if (lastUpload != null) {\r\n parameters.put(\"date_lastupload\", String.valueOf(lastUpload.getTime() / 1000L));\r\n }\r\n if (filter != null) {\r\n parameters.put(\"filter\", filter);\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element contactsElement = response.getPayload();\r\n NodeList contactNodes = contactsElement.getElementsByTagName(\"contact\");\r\n for (int i = 0; i < contactNodes.getLength(); i++) {\r\n Element contactElement = (Element) contactNodes.item(i);\r\n Contact contact = new Contact();\r\n contact.setId(contactElement.getAttribute(\"nsid\"));\r\n contact.setUsername(contactElement.getAttribute(\"username\"));\r\n contact.setRealName(contactElement.getAttribute(\"realname\"));\r\n contact.setFriend(\"1\".equals(contactElement.getAttribute(\"friend\")));\r\n contact.setFamily(\"1\".equals(contactElement.getAttribute(\"family\")));\r\n contact.setIgnored(\"1\".equals(contactElement.getAttribute(\"ignored\")));\r\n contact.setOnline(OnlineStatus.fromType(contactElement.getAttribute(\"online\")));\r\n contact.setIconFarm(contactElement.getAttribute(\"iconfarm\"));\r\n contact.setIconServer(contactElement.getAttribute(\"iconserver\"));\r\n if (contact.getOnline() == OnlineStatus.AWAY) {\r\n contactElement.normalize();\r\n contact.setAwayMessage(XMLUtilities.getValue(contactElement));\r\n }\r\n contacts.add(contact);\r\n }\r\n return contacts;\r\n }", "public static long get1D(DMatrixRMaj A , int n ) {\n\n long before = System.currentTimeMillis();\n\n double total = 0;\n\n for( int iter = 0; iter < n; iter++ ) {\n\n int index = 0;\n for( int i = 0; i < A.numRows; i++ ) {\n int end = index+A.numCols;\n while( index != end ) {\n total += A.get(index++);\n }\n }\n }\n\n long after = System.currentTimeMillis();\n\n // print to ensure that ensure that an overly smart compiler does not optimize out\n // the whole function and to show that both produce the same results.\n System.out.println(total);\n\n return after-before;\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 }", "private static JsonObject getFieldJsonObject(Field field) {\n JsonObject fieldObj = new JsonObject();\n fieldObj.add(\"type\", field.getType());\n fieldObj.add(\"key\", field.getKey());\n fieldObj.add(\"displayName\", field.getDisplayName());\n\n String fieldDesc = field.getDescription();\n if (fieldDesc != null) {\n fieldObj.add(\"description\", field.getDescription());\n }\n\n Boolean fieldIsHidden = field.getIsHidden();\n if (fieldIsHidden != null) {\n fieldObj.add(\"hidden\", field.getIsHidden());\n }\n\n JsonArray array = new JsonArray();\n List<String> options = field.getOptions();\n if (options != null && !options.isEmpty()) {\n for (String option : options) {\n JsonObject optionObj = new JsonObject();\n optionObj.add(\"key\", option);\n\n array.add(optionObj);\n }\n fieldObj.add(\"options\", array);\n }\n\n return fieldObj;\n }", "void release() {\n\t\tif (mCurrentRequests != null) {\n\t\t\tsynchronized (mCurrentRequests) {\n\t\t\t\tmCurrentRequests.clear();\n\t\t\t\tmCurrentRequests = null;\n\t\t\t}\n\t\t}\n\n\t\tif (mDownloadQueue != null) {\n\t\t\tmDownloadQueue = null;\n\t\t}\n\n\t\tif (mDownloadDispatchers != null) {\n\t\t\tstop();\n\n\t\t\tfor (int i = 0; i < mDownloadDispatchers.length; i++) {\n\t\t\t\tmDownloadDispatchers[i] = null;\n\t\t\t}\n\t\t\tmDownloadDispatchers = null;\n\t\t}\n\n\t}", "public static base_response update(nitro_service client, csparameter resource) throws Exception {\n\t\tcsparameter updateresource = new csparameter();\n\t\tupdateresource.stateupdate = resource.stateupdate;\n\t\treturn updateresource.update_resource(client);\n\t}", "public static Cluster swapGreedyRandomPartitions(final Cluster nextCandidateCluster,\n final List<Integer> nodeIds,\n final int greedySwapMaxPartitionsPerNode,\n final int greedySwapMaxPartitionsPerZone,\n List<StoreDefinition> storeDefs) {\n\n System.out.println(\"GreedyRandom : nodeIds:\" + nodeIds);\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n double currentUtility = new PartitionBalance(returnCluster, storeDefs).getUtility();\n int nodeIdA = -1;\n int nodeIdB = -1;\n int partitionIdA = -1;\n int partitionIdB = -1;\n\n for(int nodeIdAPrime: nodeIds) {\n System.out.println(\"GreedyRandom : processing nodeId:\" + nodeIdAPrime);\n List<Integer> partitionIdsAPrime = new ArrayList<Integer>();\n partitionIdsAPrime.addAll(returnCluster.getNodeById(nodeIdAPrime).getPartitionIds());\n Collections.shuffle(partitionIdsAPrime);\n\n int maxPartitionsInAPrime = Math.min(greedySwapMaxPartitionsPerNode,\n partitionIdsAPrime.size());\n\n for(int offsetAPrime = 0; offsetAPrime < maxPartitionsInAPrime; offsetAPrime++) {\n Integer partitionIdAPrime = partitionIdsAPrime.get(offsetAPrime);\n List<Pair<Integer, Integer>> partitionIdsZone = new ArrayList<Pair<Integer, Integer>>();\n for(int nodeIdBPrime: nodeIds) {\n if(nodeIdBPrime == nodeIdAPrime)\n continue;\n for(Integer partitionIdBPrime: returnCluster.getNodeById(nodeIdBPrime)\n .getPartitionIds()) {\n partitionIdsZone.add(new Pair<Integer, Integer>(nodeIdBPrime,\n partitionIdBPrime));\n }\n }\n\n Collections.shuffle(partitionIdsZone);\n int maxPartitionsInZone = Math.min(greedySwapMaxPartitionsPerZone,\n partitionIdsZone.size());\n for(int offsetZone = 0; offsetZone < maxPartitionsInZone; offsetZone++) {\n Integer nodeIdBPrime = partitionIdsZone.get(offsetZone).getFirst();\n Integer partitionIdBPrime = partitionIdsZone.get(offsetZone).getSecond();\n Cluster swapResult = swapPartitions(returnCluster,\n nodeIdAPrime,\n partitionIdAPrime,\n nodeIdBPrime,\n partitionIdBPrime);\n double swapUtility = new PartitionBalance(swapResult, storeDefs).getUtility();\n if(swapUtility < currentUtility) {\n currentUtility = swapUtility;\n System.out.println(\" -> \" + currentUtility);\n nodeIdA = nodeIdAPrime;\n partitionIdA = partitionIdAPrime;\n nodeIdB = nodeIdBPrime;\n partitionIdB = partitionIdBPrime;\n }\n }\n }\n }\n\n if(nodeIdA == -1) {\n return returnCluster;\n }\n return swapPartitions(returnCluster, nodeIdA, partitionIdA, nodeIdB, partitionIdB);\n }", "protected void showStep(A_CmsSetupStep step) {\n\n Window window = newWindow();\n window.setContent(step);\n window.setCaption(step.getTitle());\n A_CmsUI.get().addWindow(window);\n window.center();\n }", "public History[] filterHistory(String... filters) throws Exception {\n BasicNameValuePair[] params;\n if (filters.length > 0) {\n params = new BasicNameValuePair[filters.length];\n for (int i = 0; i < filters.length; i++) {\n params[i] = new BasicNameValuePair(\"source_uri[]\", filters[i]);\n }\n } else {\n return refreshHistory();\n }\n\n return constructHistory(params);\n }" ]
Read task data from a Gantt Designer file. @param gantt Gantt Designer file
[ "private void processTasks(Gantt gantt)\n {\n ProjectCalendar calendar = m_projectFile.getDefaultCalendar();\n\n for (Gantt.Tasks.Task ganttTask : gantt.getTasks().getTask())\n {\n String wbs = ganttTask.getID();\n ChildTaskContainer parentTask = getParentTask(wbs);\n\n Task task = parentTask.addTask();\n //ganttTask.getB() // bar type\n //ganttTask.getBC() // bar color\n task.setCost(ganttTask.getC());\n task.setName(ganttTask.getContent());\n task.setDuration(ganttTask.getD());\n task.setDeadline(ganttTask.getDL());\n //ganttTask.getH() // height\n //ganttTask.getIn(); // indent\n task.setWBS(wbs);\n task.setPercentageComplete(ganttTask.getPC());\n task.setStart(ganttTask.getS());\n //ganttTask.getU(); // Unknown\n //ganttTask.getVA(); // Valign\n\n task.setFinish(calendar.getDate(task.getStart(), task.getDuration(), false));\n m_taskMap.put(wbs, task);\n }\n }" ]
[ "private ServerDetails createInitialDeployDetailsFromOldDeployDetails(ServerDetails oldDeployerDetails) {\n RepositoryConf oldDeployRepositoryConfig = oldDeployerDetails.getDeployReleaseRepository();\n RepositoryConf oldSnapshotDeployRepositoryConfig = oldDeployerDetails.getDeploySnapshotRepository();\n RepositoryConf deployReleaseRepos = oldDeployRepositoryConfig == null ? RepositoryConf.emptyRepositoryConfig : oldDeployRepositoryConfig;\n RepositoryConf deploySnapshotRepos = oldSnapshotDeployRepositoryConfig == null ? RepositoryConf.emptyRepositoryConfig : oldSnapshotDeployRepositoryConfig;\n return new ServerDetails(oldDeployerDetails.getArtifactoryName(), oldDeployerDetails.getArtifactoryUrl(),\n deployReleaseRepos, deploySnapshotRepos, null, null, null, null);\n }", "static Path resolvePath(final Path base, final String... paths) {\n return Paths.get(base.toString(), paths);\n }", "void lockInterruptibly(final Integer permit) throws InterruptedException {\n if (permit == null) {\n throw new IllegalArgumentException();\n }\n sync.acquireInterruptibly(permit);\n }", "public static vpnglobal_intranetip_binding[] get(nitro_service service) throws Exception{\n\t\tvpnglobal_intranetip_binding obj = new vpnglobal_intranetip_binding();\n\t\tvpnglobal_intranetip_binding response[] = (vpnglobal_intranetip_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "protected static void appendHandler(LogRecordHandler parent, LogRecordHandler child){\r\n RecordHandlerTree p = handlers.find(parent);\r\n if(p != null){\r\n p.addChild(child);\r\n } else {\r\n throw new IllegalArgumentException(\"No such parent handler: \" + parent);\r\n }\r\n }", "private ArrayList handleDependentCollections(Identity oid, Object obj,\r\n Object[] origCollections, Object[] newCollections,\r\n Object[] newCollectionsOfObjects)\r\n throws LockingException\r\n {\r\n ClassDescriptor mif = _pb.getClassDescriptor(obj.getClass());\r\n Collection colDescs = mif.getCollectionDescriptors();\r\n ArrayList newObjects = new ArrayList();\r\n int count = 0;\r\n\r\n for (Iterator it = colDescs.iterator(); it.hasNext(); count++)\r\n {\r\n CollectionDescriptor cds = (CollectionDescriptor) it.next();\r\n\r\n if (cds.getOtmDependent())\r\n {\r\n ArrayList origList = (origCollections == null ? null\r\n : (ArrayList) origCollections[count]);\r\n ArrayList newList = (ArrayList) newCollections[count];\r\n\r\n if (origList != null)\r\n {\r\n for (Iterator it2 = origList.iterator(); it2.hasNext(); )\r\n {\r\n Identity origOid = (Identity) it2.next();\r\n\r\n if ((newList == null) || !newList.contains(origOid))\r\n {\r\n markDelete(origOid, oid, true);\r\n }\r\n }\r\n }\r\n\r\n if (newList != null)\r\n {\r\n int countElem = 0;\r\n for (Iterator it2 = newList.iterator(); it2.hasNext(); countElem++)\r\n {\r\n Identity newOid = (Identity) it2.next();\r\n\r\n if ((origList == null) || !origList.contains(newOid))\r\n {\r\n ContextEntry entry = (ContextEntry) _objects.get(newOid);\r\n\r\n if (entry == null)\r\n {\r\n ArrayList relCol = (ArrayList)\r\n newCollectionsOfObjects[count];\r\n Object relObj = relCol.get(countElem);\r\n insertInternal(newOid, relObj, LockType.WRITE_LOCK,\r\n true, null, new Stack());\r\n newObjects.add(newOid);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n return newObjects;\r\n }", "void publish() {\n assert publishedFullRegistry != null : \"Cannot write directly to main registry\";\n\n writeLock.lock();\n try {\n if (!modified) {\n return;\n }\n publishedFullRegistry.writeLock.lock();\n try {\n publishedFullRegistry.clear(true);\n copy(this, publishedFullRegistry);\n pendingRemoveCapabilities.clear();\n pendingRemoveRequirements.clear();\n modified = false;\n } finally {\n publishedFullRegistry.writeLock.unlock();\n }\n } finally {\n writeLock.unlock();\n }\n }", "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}", "final void begin() {\n if (this.properties.isDateRollEnforced()) {\n final Thread thread = new Thread(this,\n \"Log4J Time-based File-roll Enforcer\");\n thread.setDaemon(true);\n thread.start();\n this.threadRef = thread;\n }\n }" ]
Convert an Object to a Date.
[ "public static java.sql.Date toDate(Object value) throws ParseException {\n if (value == null) {\n return null;\n }\n if (value instanceof java.sql.Date) {\n return (java.sql.Date) value;\n }\n if (value instanceof String) {\n if (\"\".equals((String) value)) {\n return null;\n }\n return new java.sql.Date(IN_DATE_FORMAT.parse((String) value).getTime());\n }\n\n return new java.sql.Date(IN_DATE_FORMAT.parse(value.toString()).getTime());\n }" ]
[ "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 }", "protected void createBulge( int x1 , double p , boolean byAngle ) {\n double a11 = diag[x1];\n double a22 = diag[x1+1];\n double a12 = off[x1];\n double a23 = off[x1+1];\n\n if( byAngle ) {\n c = Math.cos(p);\n s = Math.sin(p);\n\n c2 = c*c;\n s2 = s*s;\n cs = c*s;\n } else {\n computeRotation(a11-p, a12);\n }\n\n // multiply the rotator on the top left.\n diag[x1] = c2*a11 + 2.0*cs*a12 + s2*a22;\n diag[x1+1] = c2*a22 - 2.0*cs*a12 + s2*a11;\n off[x1] = a12*(c2-s2) + cs*(a22 - a11);\n off[x1+1] = c*a23;\n bulge = s*a23;\n\n if( Q != null )\n updateQ(x1,x1+1,c,s);\n }", "public Path getReportDirectory()\n {\n WindupConfigurationModel cfg = WindupConfigurationService.getConfigurationModel(getGraphContext());\n Path path = cfg.getOutputPath().asFile().toPath().resolve(REPORTS_DIR);\n createDirectoryIfNeeded(path);\n return path.toAbsolutePath();\n }", "public Criteria copy(boolean includeGroupBy, boolean includeOrderBy, boolean includePrefetchedRelationships)\r\n {\r\n Criteria copy = new Criteria();\r\n\r\n copy.m_criteria = new Vector(this.m_criteria);\r\n copy.m_negative = this.m_negative;\r\n\r\n if (includeGroupBy)\r\n {\r\n copy.groupby = this.groupby;\r\n }\r\n if (includeOrderBy)\r\n {\r\n copy.orderby = this.orderby;\r\n }\r\n if (includePrefetchedRelationships)\r\n {\r\n copy.prefetchedRelationships = this.prefetchedRelationships;\r\n }\r\n\r\n return copy;\r\n }", "public int createLogs(String topic, final int partitions, final boolean forceEnlarge) {\n TopicNameValidator.validate(topic);\n synchronized (logCreationLock) {\n final int configPartitions = getPartition(topic);\n if (configPartitions >= partitions || !forceEnlarge) {\n return configPartitions;\n }\n topicPartitionsMap.put(topic, partitions);\n if (config.getEnableZookeeper()) {\n if (getLogPool(topic, 0) != null) {//created already\n topicRegisterTasks.add(new TopicTask(TopicTask.TaskType.ENLARGE, topic));\n } else {\n topicRegisterTasks.add(new TopicTask(TopicTask.TaskType.CREATE, topic));\n }\n }\n return partitions;\n }\n }", "public ItemRequest<Workspace> removeUser(String workspace) {\n \n String path = String.format(\"/workspaces/%s/removeUser\", workspace);\n return new ItemRequest<Workspace>(this, Workspace.class, path, \"POST\");\n }", "public static cmppolicylabel_stats get(nitro_service service, String labelname) throws Exception{\n\t\tcmppolicylabel_stats obj = new cmppolicylabel_stats();\n\t\tobj.set_labelname(labelname);\n\t\tcmppolicylabel_stats response = (cmppolicylabel_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "public static boolean isQuotedConstant(String str) {\n if (str == null || str.isEmpty()) {\n return false;\n }\n return (str.startsWith(\"\\\"\") && str.endsWith(\"\\\"\"));\n }", "private boolean absoluteAdvanced(int row)\r\n {\r\n boolean retval = false;\r\n \r\n try\r\n {\r\n if (getRsAndStmt().m_rs != null)\r\n {\r\n if (row == 0)\r\n {\r\n getRsAndStmt().m_rs.beforeFirst();\r\n }\r\n else\r\n {\r\n retval = getRsAndStmt().m_rs.absolute(row); \r\n }\r\n m_current_row = row;\r\n setHasCalledCheck(false);\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n advancedJDBCSupport = false;\r\n }\r\n return retval;\r\n }" ]
Use this API to fetch the statistics of all nspbr6_stats resources that are configured on netscaler.
[ "public static nspbr6_stats[] get(nitro_service service, options option) throws Exception{\n\t\tnspbr6_stats obj = new nspbr6_stats();\n\t\tnspbr6_stats[] response = (nspbr6_stats[])obj.stat_resources(service,option);\n\t\treturn response;\n\t}" ]
[ "public void addRelation(RelationType relationType, RelationDirection direction) {\n\tint idx = relationType.ordinal();\n\tdirections[idx] = directions[idx].sum(direction);\n }", "private ReferenceDescriptorDef usedByReference(ModelDef modelDef, FieldDescriptorDef fieldDef)\r\n {\r\n String ownerClassName = ((ClassDescriptorDef)fieldDef.getOwner()).getQualifiedName();\r\n ClassDescriptorDef classDef;\r\n ReferenceDescriptorDef refDef;\r\n String targetClassName;\r\n\r\n // only relevant for primarykey fields\r\n if (PropertyHelper.toBoolean(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_PRIMARYKEY), false))\r\n {\r\n for (Iterator classIt = modelDef.getClasses(); classIt.hasNext();)\r\n {\r\n classDef = (ClassDescriptorDef)classIt.next();\r\n for (Iterator refIt = classDef.getReferences(); refIt.hasNext();)\r\n {\r\n refDef = (ReferenceDescriptorDef)refIt.next();\r\n targetClassName = refDef.getProperty(PropertyHelper.OJB_PROPERTY_CLASS_REF).replace('$', '.');\r\n if (ownerClassName.equals(targetClassName))\r\n {\r\n // the field is a primary key of the class referenced by this reference descriptor\r\n return refDef;\r\n }\r\n }\r\n }\r\n }\r\n return null;\r\n }", "public static ServiceName moduleResolvedServiceName(ModuleIdentifier identifier) {\n if (!isDynamicModule(identifier)) {\n throw ServerLogger.ROOT_LOGGER.missingModulePrefix(identifier, MODULE_PREFIX);\n }\n return MODULE_RESOLVED_SERVICE_PREFIX.append(identifier.getName()).append(identifier.getSlot());\n }", "public static tmsessionparameter get(nitro_service service) throws Exception{\n\t\ttmsessionparameter obj = new tmsessionparameter();\n\t\ttmsessionparameter[] response = (tmsessionparameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public boolean checkRead(TransactionImpl tx, Object obj)\r\n {\r\n if (hasReadLock(tx, obj))\r\n {\r\n return true;\r\n }\r\n LockEntry writer = getWriter(obj);\r\n if (writer.isOwnedBy(tx))\r\n {\r\n return true;\r\n }\r\n return false;\r\n }", "private Map<Integer, List<Row>> createTimeEntryMap(List<Row> rows) throws ParseException\n {\n Map<Integer, List<Row>> map = new HashMap<Integer, List<Row>>();\n for (Row row : rows)\n {\n Integer workPatternID = row.getInteger(\"ID\");\n String shifts = row.getString(\"SHIFTS\");\n map.put(workPatternID, createTimeEntryRowList(shifts));\n }\n return map;\n }", "public void createDB() throws PlatformException\r\n {\r\n if (_creationScript == null)\r\n {\r\n createCreationScript();\r\n }\r\n\r\n Project project = new Project();\r\n TorqueDataModelTask modelTask = new TorqueDataModelTask();\r\n File tmpDir = null;\r\n File scriptFile = null;\r\n \r\n try\r\n {\r\n tmpDir = new File(getWorkDir(), \"schemas\");\r\n tmpDir.mkdir();\r\n\r\n scriptFile = new File(tmpDir, CREATION_SCRIPT_NAME);\r\n\r\n writeCompressedText(scriptFile, _creationScript);\r\n\r\n project.setBasedir(tmpDir.getAbsolutePath());\r\n\r\n // we use the ant task 'sql' to perform the creation script\r\n\t SQLExec sqlTask = new SQLExec();\r\n\t SQLExec.OnError onError = new SQLExec.OnError();\r\n\t\r\n\t onError.setValue(\"continue\");\r\n\t sqlTask.setProject(project);\r\n\t sqlTask.setAutocommit(true);\r\n\t sqlTask.setDriver(_jcd.getDriver());\r\n\t sqlTask.setOnerror(onError);\r\n\t sqlTask.setUserid(_jcd.getUserName());\r\n\t sqlTask.setPassword(_jcd.getPassWord() == null ? \"\" : _jcd.getPassWord());\r\n\t sqlTask.setUrl(getDBCreationUrl());\r\n\t sqlTask.setSrc(scriptFile);\r\n\t sqlTask.execute();\r\n\r\n\t deleteDir(tmpDir);\r\n }\r\n catch (Exception ex)\r\n {\r\n // clean-up\r\n if ((tmpDir != null) && tmpDir.exists())\r\n {\r\n try\r\n {\r\n scriptFile.delete();\r\n }\r\n catch (NullPointerException e) \r\n {\r\n LoggerFactory.getLogger(this.getClass()).error(\"NPE While deleting scriptFile [\" + scriptFile.getName() + \"]\", e);\r\n }\r\n }\r\n throw new PlatformException(ex);\r\n }\r\n }", "public void install(@Observes(precedence = 90) CubeDockerConfiguration configuration,\n ArquillianDescriptor arquillianDescriptor) {\n\n DockerCompositions cubes = configuration.getDockerContainersContent();\n\n final SeleniumContainers seleniumContainers =\n SeleniumContainers.create(getBrowser(arquillianDescriptor), cubeDroneConfigurationInstance.get());\n cubes.add(seleniumContainers.getSeleniumContainerName(), seleniumContainers.getSeleniumContainer());\n\n final boolean recording = cubeDroneConfigurationInstance.get().isRecording();\n if (recording) {\n cubes.add(seleniumContainers.getVncContainerName(), seleniumContainers.getVncContainer());\n cubes.add(seleniumContainers.getVideoConverterContainerName(),\n seleniumContainers.getVideoConverterContainer());\n }\n\n seleniumContainersInstanceProducer.set(seleniumContainers);\n\n System.out.println(\"SELENIUM INSTALLED\");\n System.out.println(ConfigUtil.dump(cubes));\n }", "public static byte[] storeContentAndTransformOperation(OperationContext context, ModelNode operation, ContentRepository contentRepository) throws IOException, OperationFailedException {\n if (!operation.hasDefined(CONTENT)) {\n throw createFailureException(DomainControllerLogger.ROOT_LOGGER.invalidContentDeclaration());\n }\n final ModelNode content = operation.get(CONTENT).get(0);\n if (content.hasDefined(HASH)) {\n // This should be handled as part of the OSH\n throw createFailureException(DomainControllerLogger.ROOT_LOGGER.invalidContentDeclaration());\n }\n final byte[] hash = storeDeploymentContent(context, operation, contentRepository);\n\n // Clear the contents and update with the hash\n final ModelNode slave = operation.clone();\n slave.get(CONTENT).setEmptyList().add().get(HASH).set(hash);\n // Add the domain op transformer\n List<DomainOperationTransmuter> transformers = context.getAttachment(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS);\n if (transformers == null) {\n context.attach(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS, transformers = new ArrayList<>());\n }\n transformers.add(new CompositeOperationAwareTransmuter(slave));\n return hash;\n }" ]
Gets the a singleton reference to the SPIProvider returned by the SPIProviderResolver retrieved using the default server integration classloader. @return this class instance
[ "public static SPIProvider getInstance()\n {\n if (me == null)\n {\n final ClassLoader cl = ClassLoaderProvider.getDefaultProvider().getServerIntegrationClassLoader();\n me = SPIProviderResolver.getInstance(cl).getProvider();\n }\n return me;\n }" ]
[ "public final void end() {\n final Thread thread = threadRef;\n if (thread != null) {\n thread.interrupt();\n try {\n thread.join();\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n }\n this.threadRef = null;\n }", "public static int colorSpline(int x, int numKnots, int[] xknots, int[] yknots) {\n\t\tint span;\n\t\tint numSpans = numKnots - 3;\n\t\tfloat k0, k1, k2, k3;\n\t\tfloat c0, c1, c2, c3;\n\t\t\n\t\tif (numSpans < 1)\n\t\t\tthrow new IllegalArgumentException(\"Too few knots in spline\");\n\t\t\n\t\tfor (span = 0; span < numSpans; span++)\n\t\t\tif (xknots[span+1] > x)\n\t\t\t\tbreak;\n\t\tif (span > numKnots-3)\n\t\t\tspan = numKnots-3;\n\t\tfloat t = (float)(x-xknots[span]) / (xknots[span+1]-xknots[span]);\n\t\tspan--;\n\t\tif (span < 0) {\n\t\t\tspan = 0;\n\t\t\tt = 0;\n\t\t}\n\n\t\tint v = 0;\n\t\tfor (int i = 0; i < 4; i++) {\n\t\t\tint shift = i * 8;\n\t\t\t\n\t\t\tk0 = (yknots[span] >> shift) & 0xff;\n\t\t\tk1 = (yknots[span+1] >> shift) & 0xff;\n\t\t\tk2 = (yknots[span+2] >> shift) & 0xff;\n\t\t\tk3 = (yknots[span+3] >> shift) & 0xff;\n\t\t\t\n\t\t\tc3 = m00*k0 + m01*k1 + m02*k2 + m03*k3;\n\t\t\tc2 = m10*k0 + m11*k1 + m12*k2 + m13*k3;\n\t\t\tc1 = m20*k0 + m21*k1 + m22*k2 + m23*k3;\n\t\t\tc0 = m30*k0 + m31*k1 + m32*k2 + m33*k3;\n\t\t\tint n = (int)(((c3*t + c2)*t + c1)*t + c0);\n\t\t\tif (n < 0)\n\t\t\t\tn = 0;\n\t\t\telse if (n > 255)\n\t\t\t\tn = 255;\n\t\t\tv |= n << shift;\n\t\t}\n\t\t\n\t\treturn v;\n\t}", "private void readColumn(int startIndex, int length) throws Exception\n {\n if (m_currentTable != null)\n {\n int value = FastTrackUtility.getByte(m_buffer, startIndex);\n Class<?> klass = COLUMN_MAP[value];\n if (klass == null)\n {\n klass = UnknownColumn.class;\n }\n\n FastTrackColumn column = (FastTrackColumn) klass.newInstance();\n m_currentColumn = column;\n\n logColumnData(startIndex, length);\n\n column.read(m_currentTable.getType(), m_buffer, startIndex, length);\n FastTrackField type = column.getType();\n\n //\n // Don't try to add this data if:\n // 1. We don't know what type it is\n // 2. We have seen the type already\n //\n if (type != null && !m_currentFields.contains(type))\n {\n m_currentFields.add(type);\n m_currentTable.addColumn(column);\n updateDurationTimeUnit(column);\n updateWorkTimeUnit(column);\n\n logColumn(column);\n }\n }\n }", "private void updateSortedServices() {\n List<T> copiedList = new ArrayList<T>(serviceMap.values());\n sortedServices = Collections.unmodifiableList(copiedList);\n if (changeListener != null) {\n changeListener.changed();\n }\n }", "public BoxFileUploadSessionPart uploadPart(InputStream stream, long offset, int partSize,\n long totalSizeOfFile) {\n\n URL uploadPartURL = this.sessionInfo.getSessionEndpoints().getUploadPartEndpoint();\n\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), uploadPartURL, HttpMethod.PUT);\n request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_OCTET_STREAM);\n\n //Read the partSize bytes from the stream\n byte[] bytes = new byte[partSize];\n try {\n stream.read(bytes);\n } catch (IOException ioe) {\n throw new BoxAPIException(\"Reading data from stream failed.\", ioe);\n }\n\n return this.uploadPart(bytes, offset, partSize, totalSizeOfFile);\n }", "public String getString(Integer type)\n {\n String result = null;\n\n byte[] item = m_map.get(type);\n if (item != null)\n {\n result = m_data.getString(getOffset(item));\n }\n\n return (result);\n }", "public void identifyClasses(final String pluginDirectory) throws Exception {\n methodInformation.clear();\n jarInformation.clear();\n try {\n new FileTraversal() {\n public void onDirectory(final File d) {\n }\n\n public void onFile(final File f) {\n try {\n // loads class files\n if (f.getName().endsWith(\".class\")) {\n // get the class name for this path\n String className = f.getAbsolutePath();\n className = className.replace(pluginDirectory, \"\");\n className = getClassNameFromPath(className);\n\n logger.info(\"Storing plugin information: {}, {}\", className,\n f.getName());\n\n ClassInformation classInfo = new ClassInformation();\n classInfo.pluginPath = pluginDirectory;\n classInformation.put(className, classInfo);\n } else if (f.getName().endsWith(\".jar\")) {\n // loads JAR packages\n // open up jar and discover files\n // look for anything with /proxy/ in it\n // this may discover things we don't need but that is OK\n try {\n jarInformation.add(f.getAbsolutePath());\n JarFile jarFile = new JarFile(f);\n Enumeration<?> enumer = jarFile.entries();\n\n // Use the Plugin-Name manifest entry to match with the provided pluginName\n String pluginPackageName = jarFile.getManifest().getMainAttributes().getValue(\"plugin-package\");\n if (pluginPackageName == null) {\n return;\n }\n\n while (enumer.hasMoreElements()) {\n Object element = enumer.nextElement();\n String elementName = element.toString();\n\n if (!elementName.endsWith(\".class\")) {\n continue;\n }\n\n String className = getClassNameFromPath(elementName);\n if (className.contains(pluginPackageName)) {\n logger.info(\"Storing plugin information: {}, {}\", className,\n f.getAbsolutePath());\n\n ClassInformation classInfo = new ClassInformation();\n classInfo.pluginPath = f.getAbsolutePath();\n classInformation.put(className, classInfo);\n }\n }\n } catch (Exception e) {\n\n }\n }\n } catch (Exception e) {\n logger.warn(\"Exception caught: {}, {}\", e.getMessage(), e.getCause());\n }\n }\n }.traverse(new File(pluginDirectory));\n } catch (IOException e) {\n throw new Exception(\"Could not identify all plugins: \" + e.getMessage());\n }\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 static Calendar parseDividendDate(String date) {\n if (!Utils.isParseable(date)) {\n return null;\n }\n date = date.trim();\n SimpleDateFormat format = new SimpleDateFormat(Utils.getDividendDateFormat(date), Locale.US);\n format.setTimeZone(TimeZone.getTimeZone(YahooFinance.TIMEZONE));\n try {\n Calendar today = Calendar.getInstance(TimeZone.getTimeZone(YahooFinance.TIMEZONE));\n Calendar parsedDate = Calendar.getInstance(TimeZone.getTimeZone(YahooFinance.TIMEZONE));\n parsedDate.setTime(format.parse(date));\n\n if (parsedDate.get(Calendar.YEAR) == 1970) {\n // Not really clear which year the dividend date is... making a reasonable guess.\n int monthDiff = parsedDate.get(Calendar.MONTH) - today.get(Calendar.MONTH);\n int year = today.get(Calendar.YEAR);\n if (monthDiff > 6) {\n year -= 1;\n } else if (monthDiff < -6) {\n year += 1;\n }\n parsedDate.set(Calendar.YEAR, year);\n }\n\n return parsedDate;\n } catch (ParseException ex) {\n log.warn(\"Failed to parse dividend date: \" + date);\n log.debug(\"Failed to parse dividend date: \" + date, ex);\n return null;\n }\n }" ]
Reset the combination generator.
[ "public final void reset()\n {\n for (int i = 0; i < combinationIndices.length; i++)\n {\n combinationIndices[i] = i;\n }\n remainingCombinations = totalCombinations;\n }" ]
[ "private String stripLineBreaks(String text, String replacement)\n {\n if (text.indexOf('\\r') != -1 || text.indexOf('\\n') != -1)\n {\n StringBuilder sb = new StringBuilder(text);\n\n int index;\n\n while ((index = sb.indexOf(\"\\r\\n\")) != -1)\n {\n sb.replace(index, index + 2, replacement);\n }\n\n while ((index = sb.indexOf(\"\\n\\r\")) != -1)\n {\n sb.replace(index, index + 2, replacement);\n }\n\n while ((index = sb.indexOf(\"\\r\")) != -1)\n {\n sb.replace(index, index + 1, replacement);\n }\n\n while ((index = sb.indexOf(\"\\n\")) != -1)\n {\n sb.replace(index, index + 1, replacement);\n }\n\n text = sb.toString();\n }\n\n return (text);\n }", "@Override\n protected void registerRequest(RestRequestValidator requestValidator,\n ChannelHandlerContext ctx,\n MessageEvent messageEvent) {\n\n // At this point we know the request is valid and we have a\n // error handler. So we construct the composite Voldemort\n // request object.\n CompositeVoldemortRequest<ByteArray, byte[]> requestObject = requestValidator.constructCompositeVoldemortRequestObject();\n\n if(requestObject != null) {\n\n DynamicTimeoutStoreClient<ByteArray, byte[]> storeClient = null;\n\n if(!requestValidator.getStoreName().equalsIgnoreCase(RestMessageHeaders.SCHEMATA_STORE)) {\n\n storeClient = this.fatClientMap.get(requestValidator.getStoreName());\n if(storeClient == null) {\n logger.error(\"Error when getting store. Non Existing store client.\");\n RestErrorHandler.writeErrorResponse(messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Non Existing store client. Critical error.\");\n return;\n }\n } else {\n requestObject.setOperationType(VoldemortOpCode.GET_METADATA_OP_CODE);\n }\n\n CoordinatorStoreClientRequest coordinatorRequest = new CoordinatorStoreClientRequest(requestObject,\n storeClient);\n Channels.fireMessageReceived(ctx, coordinatorRequest);\n\n }\n }", "public static int cudnnGetActivationDescriptor(\n cudnnActivationDescriptor activationDesc, \n int[] mode, \n int[] reluNanOpt, \n double[] coef)/** ceiling for clipped RELU, alpha for ELU */\n {\n return checkResult(cudnnGetActivationDescriptorNative(activationDesc, mode, reluNanOpt, coef));\n }", "public Path getParent() {\n\t\tif (!isAbsolute())\n\t\t\tthrow new IllegalStateException(\"path is not absolute: \" + toString());\n\t\tif (segments.isEmpty())\n\t\t\treturn null;\n\t\treturn new Path(segments.subList(0, segments.size()-1), true);\n\t}", "public static csvserver_cmppolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_cmppolicy_binding obj = new csvserver_cmppolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_cmppolicy_binding response[] = (csvserver_cmppolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "protected I_CmsFacetQueryItem parseFacetQueryItem(JSONObject item) {\n\n String query;\n try {\n query = item.getString(JSON_KEY_QUERY_FACET_QUERY_QUERY);\n } catch (JSONException e) {\n // TODO: Log\n return null;\n }\n String label = parseOptionalStringValue(item, JSON_KEY_QUERY_FACET_QUERY_LABEL);\n return new CmsFacetQueryItem(query, label);\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 }", "private ProjectCalendar deriveResourceCalendar(Integer parentCalendarID)\n {\n ProjectCalendar calendar = m_project.addDefaultDerivedCalendar();\n calendar.setUniqueID(Integer.valueOf(m_project.getProjectConfig().getNextCalendarUniqueID()));\n calendar.setParent(m_project.getCalendarByUniqueID(parentCalendarID));\n return calendar;\n }", "public ReferrerList getPhotoReferrers(Date date, String domain, String photoId, int perPage, int page) throws FlickrException {\n return getReferrers(METHOD_GET_PHOTO_REFERRERS, domain, \"photo_id\", photoId, date, perPage, page);\n }" ]
Use this API to unset the properties of cmpparameter resource. Properties that need to be unset are specified in args array.
[ "public static base_response unset(nitro_service client, cmpparameter resource, String[] args) throws Exception{\n\t\tcmpparameter unsetresource = new cmpparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}" ]
[ "public boolean attachComponent(GVRComponent component) {\n if (component.getNative() != 0) {\n NativeSceneObject.attachComponent(getNative(), component.getNative());\n }\n synchronized (mComponents) {\n long type = component.getType();\n if (!mComponents.containsKey(type)) {\n mComponents.put(type, component);\n component.setOwnerObject(this);\n return true;\n }\n }\n return false;\n }", "public static <T> PollingState<T> create(Response<ResponseBody> response, LongRunningOperationOptions lroOptions, int defaultRetryTimeout, Type resourceType, SerializerAdapter<?> serializerAdapter) throws IOException {\n PollingState<T> pollingState = new PollingState<>();\n pollingState.initialHttpMethod = response.raw().request().method();\n pollingState.defaultRetryTimeout = defaultRetryTimeout;\n pollingState.withResponse(response);\n pollingState.resourceType = resourceType;\n pollingState.serializerAdapter = serializerAdapter;\n pollingState.loggingContext = response.raw().request().header(LOGGING_HEADER);\n pollingState.finalStateVia = lroOptions.finalStateVia();\n\n String responseContent = null;\n PollingResource resource = null;\n if (response.body() != null) {\n responseContent = response.body().string();\n response.body().close();\n }\n if (responseContent != null && !responseContent.isEmpty()) {\n pollingState.resource = serializerAdapter.deserialize(responseContent, resourceType);\n resource = serializerAdapter.deserialize(responseContent, PollingResource.class);\n }\n final int statusCode = pollingState.response.code();\n if (resource != null && resource.properties != null\n && resource.properties.provisioningState != null) {\n pollingState.withStatus(resource.properties.provisioningState, statusCode);\n } else {\n switch (statusCode) {\n case 202:\n pollingState.withStatus(AzureAsyncOperation.IN_PROGRESS_STATUS, statusCode);\n break;\n case 204:\n case 201:\n case 200:\n pollingState.withStatus(AzureAsyncOperation.SUCCESS_STATUS, statusCode);\n break;\n default:\n pollingState.withStatus(AzureAsyncOperation.FAILED_STATUS, statusCode);\n }\n }\n return pollingState;\n }", "public static License createLicense(final String name, final String longName, final String comments, final String regexp, final String url){\n\t\tfinal License license = new License();\n\n\t\tlicense.setName(name);\n\t\tlicense.setLongName(longName);\n\t\tlicense.setComments(comments);\n\t\tlicense.setRegexp(regexp);\n\t\tlicense.setUrl(url);\n\n\t\treturn license;\n\t}", "protected int readByte(InputStream is) throws IOException\n {\n byte[] data = new byte[1];\n if (is.read(data) != data.length)\n {\n throw new EOFException();\n }\n\n return (MPPUtility.getByte(data, 0));\n }", "public 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 static String getParentIdFromAgent(Launcher launcher, final String imageID, final String host) throws IOException, InterruptedException {\n return launcher.getChannel().call(new MasterToSlaveCallable<String, IOException>() {\n public String call() throws IOException {\n return DockerUtils.getParentId(imageID, host);\n }\n });\n }", "public static String regexFindFirst(String pattern, String str) {\n return regexFindFirst(Pattern.compile(pattern), str, 1);\n }", "public boolean add(final String member, final double score) {\n return doWithJedis(new JedisCallable<Boolean>() {\n @Override\n public Boolean call(Jedis jedis) {\n return jedis.zadd(getKey(), score, member) > 0;\n }\n });\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 }" ]
Sets the the time of day @param hours the hours to set. Must be guaranteed to parse as an integer between 0 and 23 @param minutes the minutes to set. Must be guaranteed to parse as an integer between 0 and 59 @param seconds the optional seconds to set. Must be guaranteed to parse as an integer between 0 and 59 @param amPm the meridian indicator to use. Must be either 'am' or 'pm' @param zoneString the time zone to use in one of two formats: - zoneinfo format (America/New_York, America/Los_Angeles, etc) - GMT offset (+05:00, -0500, +5, etc)
[ "public void setExplicitTime(String hours, String minutes, String seconds, String amPm, String zoneString) {\n int hoursInt = Integer.parseInt(hours);\n int minutesInt = minutes != null ? Integer.parseInt(minutes) : 0;\n assert(amPm == null || amPm.equals(AM) || amPm.equals(PM));\n assert(hoursInt >= 0);\n assert(minutesInt >= 0 && minutesInt < 60); \n \n markTimeInvocation(amPm);\n \n // reset milliseconds to 0\n _calendar.set(Calendar.MILLISECOND, 0);\n \n // if no explicit zone is given, we use our own\n TimeZone zone = null;\n if(zoneString != null) {\n if(zoneString.startsWith(PLUS) || zoneString.startsWith(MINUS)) {\n zoneString = GMT + zoneString;\n }\n zone = TimeZone.getTimeZone(zoneString);\n }\n \n _calendar.setTimeZone(zone != null ? zone : _defaultTimeZone);\n \n _calendar.set(Calendar.HOUR_OF_DAY, hoursInt);\n // hours greater than 12 are in 24-hour time\n if(hoursInt <= 12) {\n int amPmInt = amPm == null ? \n (hoursInt >= 12 ? Calendar.PM : Calendar.AM) :\n amPm.equals(PM) ? Calendar.PM : Calendar.AM;\n _calendar.set(Calendar.AM_PM, amPmInt);\n \n // calendar is whacky at 12 o'clock (must use 0)\n if(hoursInt == 12) hoursInt = 0;\n _calendar.set(Calendar.HOUR, hoursInt);\n }\n \n if(seconds != null) {\n int secondsInt = Integer.parseInt(seconds);\n assert(secondsInt >= 0 && secondsInt < 60); \n _calendar.set(Calendar.SECOND, secondsInt);\n }\n else {\n _calendar.set(Calendar.SECOND, 0);\n }\n \n _calendar.set(Calendar.MINUTE, minutesInt);\n }" ]
[ "private List<CmsGitConfiguration> readConfigFiles() {\n\n List<CmsGitConfiguration> configurations = new LinkedList<CmsGitConfiguration>();\n\n // Default configuration file for backwards compatibility\n addConfigurationIfValid(configurations, new File(DEFAULT_CONFIG_FILE));\n\n // All files in the config folder\n File configFolder = new File(DEFAULT_CONFIG_FOLDER);\n if (configFolder.isDirectory()) {\n for (File configFile : configFolder.listFiles()) {\n addConfigurationIfValid(configurations, configFile);\n }\n }\n return configurations;\n }", "public base_response enable_modes(String[] modes) throws Exception\n\t{\n\t\tbase_response result = null;\n\t\tnsmode resource = new nsmode();\n\t\tresource.set_mode(modes);\n\t\toptions option = new options();\n\t\toption.set_action(\"enable\");\n\t\tresult = resource.perform_operation(this, option);\n\t\treturn result;\n\t}", "public static MimeMultipart createMultipartWithAttachment(String msg, final byte[] attachment, final String contentType,\r\n final String filename, String description) {\r\n try {\r\n MimeMultipart multiPart = new MimeMultipart();\r\n\r\n MimeBodyPart textPart = new MimeBodyPart();\r\n multiPart.addBodyPart(textPart);\r\n textPart.setText(msg);\r\n\r\n MimeBodyPart binaryPart = new MimeBodyPart();\r\n multiPart.addBodyPart(binaryPart);\r\n\r\n DataSource ds = new DataSource() {\r\n @Override\r\n public InputStream getInputStream() throws IOException {\r\n return new ByteArrayInputStream(attachment);\r\n }\r\n\r\n @Override\r\n public OutputStream getOutputStream() throws IOException {\r\n ByteArrayOutputStream byteStream = new ByteArrayOutputStream();\r\n byteStream.write(attachment);\r\n return byteStream;\r\n }\r\n\r\n @Override\r\n public String getContentType() {\r\n return contentType;\r\n }\r\n\r\n @Override\r\n public String getName() {\r\n return filename;\r\n }\r\n };\r\n binaryPart.setDataHandler(new DataHandler(ds));\r\n binaryPart.setFileName(filename);\r\n binaryPart.setDescription(description);\r\n return multiPart;\r\n } catch (MessagingException e) {\r\n throw new IllegalArgumentException(\"Can not create multipart message with attachment\", e);\r\n }\r\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}", "protected Boolean getIgnoreQuery() {\n\n Boolean isIgnoreQuery = parseOptionalBooleanValue(m_configObject, JSON_KEY_IGNORE_QUERY);\n return (null == isIgnoreQuery) && (m_baseConfig != null)\n ? Boolean.valueOf(m_baseConfig.getGeneralConfig().getIgnoreQueryParam())\n : isIgnoreQuery;\n }", "private void validationRelations(Task task)\n {\n List<Relation> predecessors = task.getPredecessors();\n if (!predecessors.isEmpty())\n {\n ArrayList<Relation> invalid = new ArrayList<Relation>();\n for (Relation relation : predecessors)\n {\n Task sourceTask = relation.getSourceTask();\n Task targetTask = relation.getTargetTask();\n\n String sourceOutlineNumber = sourceTask.getOutlineNumber();\n String targetOutlineNumber = targetTask.getOutlineNumber();\n\n if (sourceOutlineNumber != null && targetOutlineNumber != null && sourceOutlineNumber.startsWith(targetOutlineNumber + '.'))\n {\n invalid.add(relation);\n }\n }\n\n for (Relation relation : invalid)\n {\n relation.getSourceTask().removePredecessor(relation.getTargetTask(), relation.getType(), relation.getLag());\n }\n }\n }", "public <Result, Param extends Resource> Result execWithTemporaryCaching(Param resource, IUnitOfWork<Result, Param> transaction) throws WrappedException {\n\t\tCacheAdapter cacheAdapter = getOrCreate(resource);\n\t\tIgnoreValuesMemento memento = cacheAdapter.ignoreNewValues();\n\t\ttry {\n\t\t\treturn transaction.exec(resource);\n\t\t} catch (Exception e) {\n\t\t\tthrow new WrappedException(e);\n\t\t} finally {\n\t\t\tmemento.done();\n\t\t}\n\t}", "public void setBodyFilter(int pathId, String bodyFilter) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + Constants.PATH_PROFILE_BODY_FILTER + \" = ? \" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, bodyFilter);\n statement.setInt(2, pathId);\n statement.executeUpdate();\n statement.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "public void updatePathOrder(int profileId, int[] pathOrder) {\n for (int i = 0; i < pathOrder.length; i++) {\n EditService.updatePathTable(Constants.PATH_PROFILE_PATH_ORDER, (i + 1), pathOrder[i]);\n }\n }" ]
Update artifact download url of an artifact @param gavc String @param downLoadUrl String
[ "public void updateDownLoadUrl(final String gavc, final String downLoadUrl) {\n final DbArtifact artifact = getArtifact(gavc);\n repositoryHandler.updateDownloadUrl(artifact, downLoadUrl);\n }" ]
[ "public static Properties loadProps(String filename) {\n Properties props = new Properties();\n FileInputStream fis = null;\n try {\n fis = new FileInputStream(filename);\n props.load(fis);\n return props;\n } catch (IOException ex) {\n throw new RuntimeException(ex);\n } finally {\n Closer.closeQuietly(fis);\n }\n\n }", "public String read(int numBytes) throws IOException {\n Preconditions.checkArgument(numBytes >= 0);\n Preconditions.checkArgument(numBytes <= MAX_ALLOWABLE_BUFFER_SIZE);\n int numBytesRemaining = numBytes;\n // first read whatever we need from our buffer\n if (!isReadBufferEmpty()) {\n int length = Math.min(end - offset, numBytesRemaining);\n copyToStrBuffer(buffer, offset, length);\n offset += length;\n numBytesRemaining -= length;\n }\n\n // next read the remaining chars directly into our strBuffer\n if (numBytesRemaining > 0) {\n readAmountToStrBuffer(numBytesRemaining);\n }\n\n if (strBufferIndex > 0 && strBuffer[strBufferIndex - 1] != LF) {\n // the last byte doesn't correspond to lf\n return readLine(false);\n }\n\n int strBufferLength = strBufferIndex;\n strBufferIndex = 0;\n return new String(strBuffer, 0, strBufferLength, charset);\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 void addRebalancingState(final RebalanceTaskInfo stealInfo) {\n // acquire write lock\n writeLock.lock();\n try {\n // Move into rebalancing state\n if(ByteUtils.getString(get(SERVER_STATE_KEY, null).get(0).getValue(), \"UTF-8\")\n .compareTo(VoldemortState.NORMAL_SERVER.toString()) == 0) {\n put(SERVER_STATE_KEY, VoldemortState.REBALANCING_MASTER_SERVER);\n initCache(SERVER_STATE_KEY);\n }\n\n // Add the steal information\n RebalancerState rebalancerState = getRebalancerState();\n if(!rebalancerState.update(stealInfo)) {\n throw new VoldemortException(\"Could not add steal information \" + stealInfo\n + \" since a plan for the same donor node \"\n + stealInfo.getDonorId() + \" ( \"\n + rebalancerState.find(stealInfo.getDonorId())\n + \" ) already exists\");\n }\n put(MetadataStore.REBALANCING_STEAL_INFO, rebalancerState);\n initCache(REBALANCING_STEAL_INFO);\n } finally {\n writeLock.unlock();\n }\n }", "private void configureConfigurationSelector() {\n\n if (m_checkinBean.getConfigurations().size() < 2) {\n // Do not show the configuration selection at all.\n removeComponent(m_configurationSelectionPanel);\n } else {\n for (CmsGitConfiguration configuration : m_checkinBean.getConfigurations()) {\n m_configurationSelector.addItem(configuration);\n m_configurationSelector.setItemCaption(configuration, configuration.getName());\n }\n m_configurationSelector.setNullSelectionAllowed(false);\n m_configurationSelector.setNewItemsAllowed(false);\n m_configurationSelector.setWidth(\"350px\");\n m_configurationSelector.select(m_checkinBean.getCurrentConfiguration());\n\n // There is really a choice between configurations\n m_configurationSelector.addValueChangeListener(new ValueChangeListener() {\n\n private static final long serialVersionUID = 1L;\n\n @SuppressWarnings(\"synthetic-access\")\n public void valueChange(ValueChangeEvent event) {\n\n updateForNewConfiguration((CmsGitConfiguration)event.getProperty().getValue());\n restoreFieldsFromUserInfo();\n\n }\n });\n }\n }", "private SiteRecord getSiteRecord(String siteKey) {\n\t\tSiteRecord siteRecord = this.siteRecords.get(siteKey);\n\t\tif (siteRecord == null) {\n\t\t\tsiteRecord = new SiteRecord(siteKey);\n\t\t\tthis.siteRecords.put(siteKey, siteRecord);\n\t\t}\n\t\treturn siteRecord;\n\t}", "public static final String getString(byte[] data, int offset)\n {\n StringBuilder buffer = new StringBuilder();\n char c;\n\n for (int loop = 0; offset + loop < data.length; loop++)\n {\n c = (char) data[offset + loop];\n\n if (c == 0)\n {\n break;\n }\n\n buffer.append(c);\n }\n\n return (buffer.toString());\n }", "public static List<CmsJspResourceWrapper> convertResourceList(CmsObject cms, List<CmsResource> list) {\n\n List<CmsJspResourceWrapper> result = new ArrayList<CmsJspResourceWrapper>(list.size());\n for (CmsResource res : list) {\n result.add(CmsJspResourceWrapper.wrap(cms, res));\n }\n return result;\n }", "public String getProfileIdFromClientId(int id) {\n return (String) sqlService.getFromTable(Constants.CLIENT_PROFILE_ID, Constants.GENERIC_ID, id, Constants.DB_TABLE_CLIENT);\n }" ]
Get the related tags. <p> This method does not require authentication. </p> @param tag The source tag @return A RelatedTagsList object @throws FlickrException
[ "public RelatedTagsList getRelated(String tag) throws FlickrException {\n\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_RELATED);\n\n parameters.put(\"tag\", tag);\n\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\n if (response.isError()) {\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\n }\n\n Element tagsElement = response.getPayload();\n\n RelatedTagsList tags = new RelatedTagsList();\n tags.setSource(tagsElement.getAttribute(\"source\"));\n NodeList tagElements = tagsElement.getElementsByTagName(\"tag\");\n for (int i = 0; i < tagElements.getLength(); i++) {\n Element tagElement = (Element) tagElements.item(i);\n Tag t = new Tag();\n t.setValue(XMLUtilities.getValue(tagElement));\n tags.add(t);\n }\n return tags;\n }" ]
[ "protected static String ConvertBinaryOperator(int oper)\r\n {\r\n // Convert the operator into the proper string\r\n String oper_string;\r\n switch (oper)\r\n {\r\n default:\r\n case EQUAL:\r\n oper_string = \"=\";\r\n break;\r\n case LIKE:\r\n oper_string = \"LIKE\";\r\n break;\r\n case NOT_EQUAL:\r\n oper_string = \"!=\";\r\n break;\r\n case LESS_THAN:\r\n oper_string = \"<\";\r\n break;\r\n case GREATER_THAN:\r\n oper_string = \">\";\r\n break;\r\n case GREATER_EQUAL:\r\n oper_string = \">=\";\r\n break;\r\n case LESS_EQUAL:\r\n oper_string = \"<=\";\r\n break;\r\n }\r\n return oper_string;\r\n }", "public synchronized boolean undoRoleMappingRemove(final Object removalKey) {\n HashMap<String, RoleMappingImpl> newRoles = new HashMap<String, RoleMappingImpl>(roleMappings);\n RoleMappingImpl toRestore = removedRoles.remove(removalKey);\n if (toRestore != null && newRoles.containsKey(toRestore.getName()) == false) {\n newRoles.put(toRestore.getName(), toRestore);\n roleMappings = Collections.unmodifiableMap(newRoles);\n return true;\n }\n\n return false;\n }", "private static void addCacheFormatEntry(List<Message> trackListEntries, int playlistId, ZipOutputStream zos) throws IOException {\n // Add a marker so we can recognize this as a metadata archive. I would use the ZipFile comment, but\n // that is not available until Java 7, and Beat Link is supposed to be backwards compatible with Java 6.\n // Since we are doing this anyway, we can also provide information about the nature of the cache, and\n // how many metadata entries it contains, which is useful for auto-attachment.\n zos.putNextEntry(new ZipEntry(CACHE_FORMAT_ENTRY));\n String formatEntry = CACHE_FORMAT_IDENTIFIER + \":\" + playlistId + \":\" + trackListEntries.size();\n zos.write(formatEntry.getBytes(\"UTF-8\"));\n }", "public GVRAnimation setOffset(float startOffset)\n {\n if(startOffset<0 || startOffset>mDuration){\n throw new IllegalArgumentException(\"offset should not be either negative or greater than duration\");\n }\n animationOffset = startOffset;\n mDuration = mDuration-animationOffset;\n return this;\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 }", "public Map<String, Object> getModuleFieldsFilters() {\n final Map<String, Object> params = new HashMap<String, Object>();\n\n for(final Filter filter: filters){\n params.putAll(filter.moduleFilterFields());\n }\n\n return params;\n }", "public static void extract(DMatrixRMaj src, int indexes[] , int length , DMatrixRMaj dst ) {\n if( !MatrixFeatures_DDRM.isVector(dst))\n throw new MatrixDimensionException(\"Dst must be a vector\");\n if( length != dst.getNumElements())\n throw new MatrixDimensionException(\"Unexpected number of elements in dst vector\");\n\n for (int i = 0; i < length; i++) {\n dst.data[i] = src.data[indexes[i]];\n }\n }", "public Set<String> getSupportedUriSchemes() {\n Set<String> schemes = new HashSet<>();\n\n for (ConfigFileLoaderPlugin loaderPlugin: this.getLoaderPlugins()) {\n schemes.add(loaderPlugin.getUriScheme());\n }\n\n return schemes;\n }", "private String escapeQuotes(String value)\n {\n StringBuilder sb = new StringBuilder();\n int length = value.length();\n char c;\n\n sb.append('\"');\n for (int index = 0; index < length; index++)\n {\n c = value.charAt(index);\n sb.append(c);\n\n if (c == '\"')\n {\n sb.append('\"');\n }\n }\n sb.append('\"');\n\n return (sb.toString());\n }" ]
1-D Forward Discrete Cosine Transform. @param data Data.
[ "public static void Forward(double[] data) {\n\n double[] result = new double[data.length];\n double sum;\n double scale = Math.sqrt(2.0 / data.length);\n for (int f = 0; f < data.length; f++) {\n sum = 0;\n for (int t = 0; t < data.length; t++) {\n double cos = Math.cos(((2.0 * t + 1.0) * f * Math.PI) / (2.0 * data.length));\n sum += data[t] * cos * alpha(f);\n }\n result[f] = scale * sum;\n }\n for (int i = 0; i < data.length; i++) {\n data[i] = result[i];\n }\n }" ]
[ "public static policydataset_value_binding[] get(nitro_service service, String name) throws Exception{\n\t\tpolicydataset_value_binding obj = new policydataset_value_binding();\n\t\tobj.set_name(name);\n\t\tpolicydataset_value_binding response[] = (policydataset_value_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static int lookupShaper(String name) {\r\n if (name == null) {\r\n return NOWORDSHAPE;\r\n } else if (name.equalsIgnoreCase(\"dan1\")) {\r\n return WORDSHAPEDAN1;\r\n } else if (name.equalsIgnoreCase(\"chris1\")) {\r\n return WORDSHAPECHRIS1;\r\n } else if (name.equalsIgnoreCase(\"dan2\")) {\r\n return WORDSHAPEDAN2;\r\n } else if (name.equalsIgnoreCase(\"dan2useLC\")) {\r\n return WORDSHAPEDAN2USELC;\r\n } else if (name.equalsIgnoreCase(\"dan2bio\")) {\r\n return WORDSHAPEDAN2BIO;\r\n } else if (name.equalsIgnoreCase(\"dan2bioUseLC\")) {\r\n return WORDSHAPEDAN2BIOUSELC;\r\n } else if (name.equalsIgnoreCase(\"jenny1\")) {\r\n return WORDSHAPEJENNY1;\r\n } else if (name.equalsIgnoreCase(\"jenny1useLC\")) {\r\n return WORDSHAPEJENNY1USELC;\r\n } else if (name.equalsIgnoreCase(\"chris2\")) {\r\n return WORDSHAPECHRIS2;\r\n } else if (name.equalsIgnoreCase(\"chris2useLC\")) {\r\n return WORDSHAPECHRIS2USELC;\r\n } else if (name.equalsIgnoreCase(\"chris3\")) {\r\n return WORDSHAPECHRIS3;\r\n } else if (name.equalsIgnoreCase(\"chris3useLC\")) {\r\n return WORDSHAPECHRIS3USELC;\r\n } else if (name.equalsIgnoreCase(\"chris4\")) {\r\n return WORDSHAPECHRIS4;\r\n } else if (name.equalsIgnoreCase(\"digits\")) {\r\n return WORDSHAPEDIGITS;\r\n } else {\r\n return NOWORDSHAPE;\r\n }\r\n }", "private void configureConfigurationSelector() {\n\n if (m_checkinBean.getConfigurations().size() < 2) {\n // Do not show the configuration selection at all.\n removeComponent(m_configurationSelectionPanel);\n } else {\n for (CmsGitConfiguration configuration : m_checkinBean.getConfigurations()) {\n m_configurationSelector.addItem(configuration);\n m_configurationSelector.setItemCaption(configuration, configuration.getName());\n }\n m_configurationSelector.setNullSelectionAllowed(false);\n m_configurationSelector.setNewItemsAllowed(false);\n m_configurationSelector.setWidth(\"350px\");\n m_configurationSelector.select(m_checkinBean.getCurrentConfiguration());\n\n // There is really a choice between configurations\n m_configurationSelector.addValueChangeListener(new ValueChangeListener() {\n\n private static final long serialVersionUID = 1L;\n\n @SuppressWarnings(\"synthetic-access\")\n public void valueChange(ValueChangeEvent event) {\n\n updateForNewConfiguration((CmsGitConfiguration)event.getProperty().getValue());\n restoreFieldsFromUserInfo();\n\n }\n });\n }\n }", "public static base_responses delete(nitro_service client, String sitename[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (sitename != null && sitename.length > 0) {\n\t\t\tgslbsite deleteresources[] = new gslbsite[sitename.length];\n\t\t\tfor (int i=0;i<sitename.length;i++){\n\t\t\t\tdeleteresources[i] = new gslbsite();\n\t\t\t\tdeleteresources[i].sitename = sitename[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "public File getStylesheetPath()\n {\n String path = System.getProperty(STYLESHEET_KEY);\n return path == null ? null : new File(path);\n }", "@SuppressWarnings(\"unchecked\")\n public LinkedHashMap<String, Field> getValueAsListMap() {\n return (LinkedHashMap<String, Field>) type.convert(getValue(), Type.LIST_MAP);\n }", "public static <T> IteratorFromReaderFactory<T> getFactory(String delim, Function<String,T> op) {\r\n return new DelimitRegExIteratorFactory<T>(delim, op);\r\n }", "synchronized boolean reload(int permit, boolean suspend) {\n return internalSetState(new ReloadTask(permit, suspend), InternalState.SERVER_STARTED, InternalState.RELOADING);\n }", "public static Bitmap decodeStream(InputStream stream, boolean closeStream) {\n return AsyncBitmapTexture.decodeStream(stream,\n AsyncBitmapTexture.glMaxTextureSize,\n AsyncBitmapTexture.glMaxTextureSize, true, null, closeStream);\n }" ]
binds the objects primary key and locking values to the statement, BRJ
[ "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 }" ]
[ "protected Object doInvoke(Object proxy, Method methodToBeInvoked, Object[] args)\r\n\t\tthrows Throwable\r\n\t{\r\n\t\tMethod m =\r\n\t\t\tgetRealSubject().getClass().getMethod(\r\n\t\t\t\tmethodToBeInvoked.getName(),\r\n\t\t\t\tmethodToBeInvoked.getParameterTypes());\r\n\t\treturn m.invoke(getRealSubject(), args);\r\n\t}", "void applyFreshParticleOnScreen(\n @NonNull final Scene scene,\n final int position\n ) {\n final int w = scene.getWidth();\n final int h = scene.getHeight();\n if (w == 0 || h == 0) {\n throw new IllegalStateException(\n \"Cannot generate particles if scene width or height is 0\");\n }\n\n final double direction = Math.toRadians(random.nextInt(360));\n final float dCos = (float) Math.cos(direction);\n final float dSin = (float) Math.sin(direction);\n final float x = random.nextInt(w);\n final float y = random.nextInt(h);\n final float speedFactor = newRandomIndividualParticleSpeedFactor();\n final float radius = newRandomIndividualParticleRadius(scene);\n\n scene.setParticleData(\n position,\n x,\n y,\n dCos,\n dSin,\n radius,\n speedFactor);\n }", "@SuppressForbidden(\"legitimate sysstreams.\")\n public static void warn(String message, Throwable t) {\n PrintStream w = (warnings == null ? System.err : warnings);\n try {\n w.print(\"WARN: \");\n w.print(message);\n if (t != null) {\n w.print(\" -> \");\n try {\n t.printStackTrace(w);\n } catch (OutOfMemoryError e) {\n // Ignore, OOM.\n w.print(t.getClass().getName());\n w.print(\": \");\n w.print(t.getMessage());\n w.println(\" (stack unavailable; OOM)\");\n }\n } else {\n w.println();\n }\n w.flush();\n } catch (OutOfMemoryError t2) {\n w.println(\"ERROR: Couldn't even serialize a warning (out of memory).\");\n } catch (Throwable t2) {\n // Can't do anything, really. Probably an OOM?\n w.println(\"ERROR: Couldn't even serialize a warning.\");\n }\n }", "protected ValueContainer[] getNonKeyValues(PersistenceBroker broker, ClassDescriptor cld, Object obj) throws PersistenceBrokerException\r\n {\r\n return broker.serviceBrokerHelper().getNonKeyRwValues(cld, obj);\r\n }", "private TransactionManager getTransactionManager()\r\n {\r\n TransactionManager retval = null;\r\n try\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"getTransactionManager called\");\r\n retval = TransactionManagerFactoryFactory.instance().getTransactionManager();\r\n }\r\n catch (TransactionManagerFactoryException e)\r\n {\r\n log.warn(\"Exception trying to obtain TransactionManager from Factory\", e);\r\n e.printStackTrace();\r\n }\r\n return retval;\r\n }", "private int getCostRateTableEntryIndex(Date date)\n {\n int result = -1;\n\n CostRateTable table = getCostRateTable();\n if (table != null)\n {\n if (table.size() == 1)\n {\n result = 0;\n }\n else\n {\n result = table.getIndexByDate(date);\n }\n }\n\n return result;\n }", "@JmxOperation(description = \"swapFiles changes this store to use the new data directory\")\n public void swapFiles(String newStoreDirectory) {\n logger.info(\"Swapping files for store '\" + getName() + \"' to \" + newStoreDirectory);\n File newVersionDir = new File(newStoreDirectory);\n\n if(!newVersionDir.exists())\n throw new VoldemortException(\"File \" + newVersionDir.getAbsolutePath()\n + \" does not exist.\");\n\n if(!(newVersionDir.getParentFile().compareTo(storeDir.getAbsoluteFile()) == 0 && ReadOnlyUtils.checkVersionDirName(newVersionDir)))\n throw new VoldemortException(\"Invalid version folder name '\"\n + newVersionDir\n + \"'. Either parent directory is incorrect or format(version-n) is incorrect\");\n\n // retrieve previous version for (a) check if last write is winning\n // (b) if failure, rollback use\n File previousVersionDir = ReadOnlyUtils.getCurrentVersion(storeDir);\n if(previousVersionDir == null)\n throw new VoldemortException(\"Could not find any latest directory to swap with in store '\"\n + getName() + \"'\");\n\n long newVersionId = ReadOnlyUtils.getVersionId(newVersionDir);\n long previousVersionId = ReadOnlyUtils.getVersionId(previousVersionDir);\n if(newVersionId == -1 || previousVersionId == -1)\n throw new VoldemortException(\"Unable to parse folder names (\" + newVersionDir.getName()\n + \",\" + previousVersionDir.getName()\n + \") since format(version-n) is incorrect\");\n\n // check if we're greater than latest since we want last write to win\n if(previousVersionId > newVersionId) {\n logger.info(\"No swap required since current latest version \" + previousVersionId\n + \" is greater than swap version \" + newVersionId);\n deleteBackups();\n return;\n }\n\n logger.info(\"Acquiring write lock on '\" + getName() + \"':\");\n fileModificationLock.writeLock().lock();\n boolean success = false;\n try {\n close();\n logger.info(\"Opening primary files for store '\" + getName() + \"' at \"\n + newStoreDirectory);\n\n // open the latest store\n open(newVersionDir);\n success = true;\n } finally {\n try {\n // we failed to do the swap, attempt a rollback to last version\n if(!success)\n rollback(previousVersionDir);\n\n } finally {\n fileModificationLock.writeLock().unlock();\n if(success)\n logger.info(\"Swap operation completed successfully on store \" + getName()\n + \", releasing lock.\");\n else\n logger.error(\"Swap operation failed.\");\n }\n }\n\n // okay we have released the lock and the store is now open again, it is\n // safe to do a potentially slow delete if we have one too many backups\n deleteBackups();\n }", "private ModelNode resolveExpressionStringRecursively(final String expressionString, final boolean ignoreDMRResolutionFailure,\n final boolean initial) throws OperationFailedException {\n ParseAndResolveResult resolved = parseAndResolve(expressionString, ignoreDMRResolutionFailure);\n if (resolved.recursive) {\n // Some part of expressionString resolved into a different expression.\n // So, start over, ignoring failures. Ignore failures because we don't require\n // that expressions must not resolve to something that *looks like* an expression but isn't\n return resolveExpressionStringRecursively(resolved.result, true, false);\n } else if (resolved.modified) {\n // Typical case\n return new ModelNode(resolved.result);\n } else if (initial && EXPRESSION_PATTERN.matcher(expressionString).matches()) {\n // We should only get an unmodified expression string back if there was a resolution\n // failure that we ignored.\n assert ignoreDMRResolutionFailure;\n // expressionString came from a node of type expression, so since we did nothing send it back in the same type\n return new ModelNode(new ValueExpression(expressionString));\n } else {\n // The string wasn't really an expression. Two possible cases:\n // 1) if initial == true, someone created a expression node with a non-expression string, which is legal\n // 2) if initial == false, we resolved from an ModelType.EXPRESSION to a string that looked like an\n // expression but can't be resolved. We don't require that expressions must not resolve to something that\n // *looks like* an expression but isn't, so we'll just treat this as a string\n return new ModelNode(expressionString);\n }\n }", "protected InternalHttpResponse sendInternalRequest(HttpRequest request) {\n InternalHttpResponder responder = new InternalHttpResponder();\n httpResourceHandler.handle(request, responder);\n return responder.getResponse();\n }" ]
Remove all non replica clock entries from the list of versioned values provided @param vals list of versioned values to prune replicas from @param keyReplicas list of current replicas for the given key @param didPrune flag to mark if we did actually prune something @return pruned list
[ "public static List<Versioned<byte[]>> pruneNonReplicaEntries(List<Versioned<byte[]>> vals,\n List<Integer> keyReplicas,\n MutableBoolean didPrune) {\n List<Versioned<byte[]>> prunedVals = new ArrayList<Versioned<byte[]>>(vals.size());\n for(Versioned<byte[]> val: vals) {\n VectorClock clock = (VectorClock) val.getVersion();\n List<ClockEntry> clockEntries = new ArrayList<ClockEntry>();\n for(ClockEntry clockEntry: clock.getEntries()) {\n if(keyReplicas.contains((int) clockEntry.getNodeId())) {\n clockEntries.add(clockEntry);\n } else {\n didPrune.setValue(true);\n }\n }\n prunedVals.add(new Versioned<byte[]>(val.getValue(),\n new VectorClock(clockEntries, clock.getTimestamp())));\n }\n return prunedVals;\n }" ]
[ "public void addAuxHandler(Object handler, String prefix) {\n if (handler == null) {\n throw new NullPointerException();\n }\n auxHandlers.put(prefix, handler);\n allHandlers.add(handler);\n\n addDeclaredMethods(handler, prefix);\n inputConverter.addDeclaredConverters(handler);\n outputConverter.addDeclaredConverters(handler);\n\n if (handler instanceof ShellDependent) {\n ((ShellDependent)handler).cliSetShell(this);\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 }", "public ItemRequest<Story> findById(String story) {\n \n String path = String.format(\"/stories/%s\", story);\n return new ItemRequest<Story>(this, Story.class, path, \"GET\");\n }", "protected void addSpecialMethods(ClassFile proxyClassType, ClassMethod staticConstructor) {\n try {\n // Add special methods for interceptors\n for (Method method : LifecycleMixin.class.getMethods()) {\n BeanLogger.LOG.addingMethodToProxy(method);\n MethodInformation methodInfo = new RuntimeMethodInformation(method);\n createInterceptorBody(proxyClassType.addMethod(method), methodInfo, false, staticConstructor);\n }\n Method getInstanceMethod = TargetInstanceProxy.class.getMethod(\"weld_getTargetInstance\");\n Method getInstanceClassMethod = TargetInstanceProxy.class.getMethod(\"weld_getTargetClass\");\n generateGetTargetInstanceBody(proxyClassType.addMethod(getInstanceMethod));\n generateGetTargetClassBody(proxyClassType.addMethod(getInstanceClassMethod));\n\n Method setMethodHandlerMethod = ProxyObject.class.getMethod(\"weld_setHandler\", MethodHandler.class);\n generateSetMethodHandlerBody(proxyClassType.addMethod(setMethodHandlerMethod));\n\n Method getMethodHandlerMethod = ProxyObject.class.getMethod(\"weld_getHandler\");\n generateGetMethodHandlerBody(proxyClassType.addMethod(getMethodHandlerMethod));\n } catch (Exception e) {\n throw new WeldException(e);\n }\n }", "public void alias(DMatrixRMaj variable , String name ) {\n if( isReserved(name))\n throw new RuntimeException(\"Reserved word or contains a reserved character\");\n VariableMatrix old = (VariableMatrix)variables.get(name);\n if( old == null ) {\n variables.put(name, new VariableMatrix(variable));\n }else {\n old.matrix = variable;\n }\n }", "public static BoxUser.Info createAppUser(BoxAPIConnection api, String name) {\n return createAppUser(api, name, new CreateUserParams());\n }", "public int executeUpdateSQL(\r\n String sqlStatement,\r\n ClassDescriptor cld,\r\n ValueContainer[] values1,\r\n ValueContainer[] values2)\r\n throws PersistenceBrokerException\r\n {\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"executeUpdateSQL: \" + sqlStatement);\r\n\r\n int result;\r\n int index;\r\n PreparedStatement stmt = null;\r\n final StatementManagerIF sm = broker.serviceStatementManager();\r\n try\r\n {\r\n stmt = sm.getPreparedStatement(cld, sqlStatement,\r\n Query.NOT_SCROLLABLE, StatementManagerIF.FETCH_SIZE_NOT_APPLICABLE, isStoredProcedure(sqlStatement));\r\n index = sm.bindValues(stmt, values1, 1);\r\n sm.bindValues(stmt, values2, index);\r\n result = stmt.executeUpdate();\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n logger.error(\"PersistenceBrokerException during the execution of the Update SQL query: \" + e.getMessage(), e);\r\n throw e;\r\n }\r\n catch (SQLException e)\r\n {\r\n ValueContainer[] tmp = addValues(values1, values2);\r\n throw ExceptionHelper.generateException(e, sqlStatement, cld, tmp, logger, null);\r\n }\r\n finally\r\n {\r\n sm.closeResources(stmt, null);\r\n }\r\n return result;\r\n }", "private void ensureConversion(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n // we issue a warning if we encounter a field with a java.util.Date java type without a conversion\r\n if (\"java.util.Date\".equals(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JAVA_TYPE)) &&\r\n !fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_CONVERSION))\r\n {\r\n LogHelper.warn(true,\r\n FieldDescriptorConstraints.class,\r\n \"ensureConversion\",\r\n \"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\r\n \" of type java.util.Date is directly mapped to jdbc-type \"+\r\n fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE)+\r\n \". However, most JDBC drivers can't handle java.util.Date directly so you might want to \"+\r\n \" use a conversion for converting it to a JDBC datatype like TIMESTAMP.\");\r\n }\r\n\r\n String conversionClass = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_CONVERSION);\r\n\r\n if (((conversionClass == null) || (conversionClass.length() == 0)) &&\r\n fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_CONVERSION) &&\r\n fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_JDBC_TYPE).equals(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE)))\r\n {\r\n conversionClass = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_CONVERSION);\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_CONVERSION, conversionClass);\r\n }\r\n // now checking\r\n if (CHECKLEVEL_STRICT.equals(checkLevel) && (conversionClass != null) && (conversionClass.length() > 0))\r\n {\r\n InheritanceHelper helper = new InheritanceHelper();\r\n\r\n try\r\n {\r\n if (!helper.isSameOrSubTypeOf(conversionClass, CONVERSION_INTERFACE))\r\n {\r\n throw new ConstraintException(\"The conversion class specified for field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" does not implement the necessary interface \"+CONVERSION_INTERFACE);\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"The class \"+ex.getMessage()+\" hasn't been found on the classpath while checking the conversion class specified for field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName());\r\n }\r\n }\r\n}", "private void writeResourceAssignmentWorkgroupFields(ResourceAssignmentWorkgroupFields record) throws IOException\n {\n m_buffer.setLength(0);\n\n m_buffer.append(MPXConstants.RESOURCE_ASSIGNMENT_WORKGROUP_FIELDS_RECORD_NUMBER);\n m_buffer.append(m_delimiter);\n m_buffer.append(format(record.getMessageUniqueID()));\n m_buffer.append(m_delimiter);\n m_buffer.append(record.getConfirmed() ? \"1\" : \"0\");\n m_buffer.append(m_delimiter);\n m_buffer.append(record.getResponsePending() ? \"1\" : \"0\");\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDateTimeNull(record.getUpdateStart())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDateTimeNull(record.getUpdateFinish())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(record.getScheduleID()));\n\n stripTrailingDelimiters(m_buffer);\n m_buffer.append(MPXConstants.EOL);\n\n m_writer.write(m_buffer.toString());\n }" ]
Use this API to fetch a appflowglobal_binding resource .
[ "public static appflowglobal_binding get(nitro_service service) throws Exception{\n\t\tappflowglobal_binding obj = new appflowglobal_binding();\n\t\tappflowglobal_binding response = (appflowglobal_binding) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
[ "public boolean computeDirect( DMatrixRMaj A ) {\n\n initPower(A);\n\n boolean converged = false;\n\n for( int i = 0; i < maxIterations && !converged; i++ ) {\n// q0.print();\n \n CommonOps_DDRM.mult(A,q0,q1);\n double s = NormOps_DDRM.normPInf(q1);\n CommonOps_DDRM.divide(q1,s,q2);\n\n converged = checkConverged(A);\n }\n\n return converged;\n }", "private static long hexdump(InputStream is, PrintWriter pw) throws Exception\n {\n byte[] buffer = new byte[BUFFER_SIZE];\n long byteCount = 0;\n\n char c;\n int loop;\n int count;\n StringBuilder sb = new StringBuilder();\n\n while (true)\n {\n count = is.read(buffer);\n if (count == -1)\n {\n break;\n }\n\n byteCount += count;\n\n sb.setLength(0);\n\n for (loop = 0; loop < count; loop++)\n {\n sb.append(\" \");\n sb.append(HEX_DIGITS[(buffer[loop] & 0xF0) >> 4]);\n sb.append(HEX_DIGITS[buffer[loop] & 0x0F]);\n }\n\n while (loop < BUFFER_SIZE)\n {\n sb.append(\" \");\n ++loop;\n }\n\n sb.append(\" \");\n\n for (loop = 0; loop < count; loop++)\n {\n c = (char) buffer[loop];\n if (c > 200 || c < 27)\n {\n c = ' ';\n }\n\n sb.append(c);\n }\n\n pw.println(sb.toString());\n }\n\n return (byteCount);\n }", "public void logAttributeWarning(PathAddress address, ModelNode operation, String message, Set<String> attributes) {\n messageQueue.add(new AttributeLogEntry(address, operation, message, attributes));\n }", "@Override\n public boolean commit() {\n final CoreRemoteMongoCollection<DocumentT> collection = getCollection();\n final List<WriteModel<DocumentT>> writeModels = getBulkWriteModels();\n\n // define success as any one operation succeeding for now\n boolean success = true;\n for (final WriteModel<DocumentT> write : writeModels) {\n if (write instanceof ReplaceOneModel) {\n final ReplaceOneModel<DocumentT> replaceModel = ((ReplaceOneModel) write);\n final RemoteUpdateResult result =\n collection.updateOne(replaceModel.getFilter(), (Bson) replaceModel.getReplacement());\n success = success\n && (result != null && result.getModifiedCount() == result.getMatchedCount());\n } else if (write instanceof UpdateOneModel) {\n final UpdateOneModel<DocumentT> updateModel = ((UpdateOneModel) write);\n final RemoteUpdateResult result =\n collection.updateOne(updateModel.getFilter(), updateModel.getUpdate());\n success = success\n && (result != null && result.getModifiedCount() == result.getMatchedCount());\n } else if (write instanceof UpdateManyModel) {\n final UpdateManyModel<DocumentT> updateModel = ((UpdateManyModel) write);\n final RemoteUpdateResult result =\n collection.updateMany(updateModel.getFilter(), updateModel.getUpdate());\n success = success\n && (result != null && result.getModifiedCount() == result.getMatchedCount());\n }\n }\n return success;\n }", "public void generateTracedFile(final IFileSystemAccess2 fsa, final String path, final EObject rootTrace, final StringConcatenationClient code) {\n final CompositeGeneratorNode node = this.trace(rootTrace, code);\n this.generateTracedFile(fsa, path, node);\n }", "protected static JSONObject getDefaultProfile() throws Exception {\n String uri = DEFAULT_BASE_URL + BASE_PROFILE;\n try {\n JSONObject response = new JSONObject(doGet(uri, 60000));\n JSONArray profiles = response.getJSONArray(\"profiles\");\n\n if (profiles.length() > 0) {\n return profiles.getJSONObject(0);\n }\n } catch (Exception e) {\n // some sort of error\n throw new Exception(\"Could not create a proxy client\");\n }\n\n return null;\n }", "private static TimeUnit getDurationUnits(Integer value)\n {\n TimeUnit result = null;\n\n if (value != null)\n {\n int index = value.intValue();\n if (index >= 0 && index < DURATION_UNITS.length)\n {\n result = DURATION_UNITS[index];\n }\n }\n\n if (result == null)\n {\n result = TimeUnit.DAYS;\n }\n\n return (result);\n }", "private ClassTypeSignature getClassTypeSignature(\r\n\t\t\tParameterizedType parameterizedType) {\r\n\t\tClass<?> rawType = (Class<?>) parameterizedType.getRawType();\r\n\t\tType[] typeArguments = parameterizedType.getActualTypeArguments();\r\n\t\tTypeArgSignature[] typeArgSignatures = new TypeArgSignature[typeArguments.length];\r\n\t\tfor (int i = 0; i < typeArguments.length; i++) {\r\n\t\t\ttypeArgSignatures[i] = getTypeArgSignature(typeArguments[i]);\r\n\t\t}\r\n\r\n\t\tString binaryName = rawType.isMemberClass() ? rawType.getSimpleName()\r\n\t\t\t\t: rawType.getName();\r\n\t\tClassTypeSignature ownerTypeSignature = parameterizedType\r\n\t\t\t\t.getOwnerType() == null ? null\r\n\t\t\t\t: (ClassTypeSignature) getFullTypeSignature(parameterizedType\r\n\t\t\t\t\t\t.getOwnerType());\r\n\t\tClassTypeSignature classTypeSignature = new ClassTypeSignature(\r\n\t\t\t\tbinaryName, typeArgSignatures, ownerTypeSignature);\r\n\t\treturn classTypeSignature;\r\n\t}", "public static RelationType getInstance(Locale locale, String type)\n {\n int index = -1;\n\n String[] relationTypes = LocaleData.getStringArray(locale, LocaleData.RELATION_TYPES);\n for (int loop = 0; loop < relationTypes.length; loop++)\n {\n if (relationTypes[loop].equalsIgnoreCase(type) == true)\n {\n index = loop;\n break;\n }\n }\n\n RelationType result = null;\n if (index != -1)\n {\n result = RelationType.getInstance(index);\n }\n\n return (result);\n }" ]
Make superclasses method protected??
[ "private Object initializeLazyPropertiesFromCache(\n\t\t\tfinal String fieldName,\n\t\t\tfinal Object entity,\n\t\t\tfinal SharedSessionContractImplementor session,\n\t\t\tfinal EntityEntry entry,\n\t\t\tfinal CacheEntry cacheEntry\n\t) {\n\t\tthrow new NotSupportedException( \"OGM-9\", \"Lazy properties not supported in OGM\" );\n\t}" ]
[ "public int count(String key) {\n ConcurrentMap<WebSocketConnection, WebSocketConnection> bag = registry.get(key);\n return null == bag ? 0 : bag.size();\n }", "public String getUniqueFilename(String baseFileName, String extension, boolean cleanBaseFileName, String... ancestorFolders)\n {\n if (cleanBaseFileName)\n {\n baseFileName = PathUtil.cleanFileName(baseFileName);\n }\n\n if (ancestorFolders != null)\n {\n Path pathToFile = Paths.get(\"\", Stream.of(ancestorFolders).map(ancestor -> PathUtil.cleanFileName(ancestor)).toArray(String[]::new)).resolve(baseFileName);\n baseFileName = pathToFile.toString();\n }\n String filename = baseFileName + \".\" + extension;\n\n // FIXME this looks nasty\n while (usedFilenames.contains(filename))\n {\n filename = baseFileName + \".\" + index.getAndIncrement() + \".\" + extension;\n }\n usedFilenames.add(filename);\n\n return filename;\n }", "public BoxComment.Info reply(String message) {\n JsonObject itemJSON = new JsonObject();\n itemJSON.add(\"type\", \"comment\");\n itemJSON.add(\"id\", this.getID());\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"item\", itemJSON);\n if (BoxComment.messageContainsMention(message)) {\n requestJSON.add(\"tagged_message\", message);\n } else {\n requestJSON.add(\"message\", message);\n }\n\n URL url = ADD_COMMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxComment addedComment = new BoxComment(this.getAPI(), responseJSON.get(\"id\").asString());\n return addedComment.new Info(responseJSON);\n }", "static Map<String, Set<String>> getChildAddresses(final OperationContext context, final PathAddress addr, final ImmutableManagementResourceRegistration registry, Resource resource, final String validChildType) {\n\n Map<String, Set<String>> result = new HashMap<>();\n Predicate<String> validChildTypeFilter = childType -> (validChildType == null) || validChildType.equals(childType);\n\n if (resource != null) {\n for (String childType : registry.getChildNames(PathAddress.EMPTY_ADDRESS)) {\n if (validChildTypeFilter.test(childType)) {\n List<String> list = new ArrayList<>();\n for (String child : resource.getChildrenNames(childType)) {\n if (registry.getSubModel(PathAddress.pathAddress(PathElement.pathElement(childType, child))) != null) {\n list.add(child);\n }\n }\n result.put(childType, new LinkedHashSet<>(list));\n }\n }\n }\n\n Set<PathElement> paths = registry.getChildAddresses(PathAddress.EMPTY_ADDRESS);\n for (PathElement path : paths) {\n String childType = path.getKey();\n if (validChildTypeFilter.test(childType)) {\n Set<String> children = result.get(childType);\n if (children == null) {\n // WFLY-3306 Ensure we have an entry for any valid child type\n children = new LinkedHashSet<>();\n result.put(childType, children);\n }\n ImmutableManagementResourceRegistration childRegistration = registry.getSubModel(PathAddress.pathAddress(path));\n if (childRegistration != null) {\n AliasEntry aliasEntry = childRegistration.getAliasEntry();\n if (aliasEntry != null) {\n PathAddress childAddr = addr.append(path);\n PathAddress target = aliasEntry.convertToTargetAddress(childAddr, AliasContext.create(childAddr, context));\n assert !childAddr.equals(target) : \"Alias was not translated\";\n PathAddress targetParent = target.getParent();\n Resource parentResource = context.readResourceFromRoot(targetParent, false);\n if (parentResource != null) {\n PathElement targetElement = target.getLastElement();\n if (targetElement.isWildcard()) {\n children.addAll(parentResource.getChildrenNames(targetElement.getKey()));\n } else if (parentResource.hasChild(targetElement)) {\n children.add(path.getValue());\n }\n }\n }\n if (!path.isWildcard() && childRegistration.isRemote()) {\n children.add(path.getValue());\n }\n }\n }\n }\n\n return result;\n }", "public static BoxAPIConnection getTransactionConnection(String accessToken, String scope, String resource) {\n BoxAPIConnection apiConnection = new BoxAPIConnection(accessToken);\n\n URL url;\n try {\n url = new URL(apiConnection.getTokenURL());\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;\n try {\n urlParameters = String.format(\"grant_type=%s&subject_token=%s&subject_token_type=%s&scope=%s\", GRANT_TYPE,\n URLEncoder.encode(accessToken, \"UTF-8\"), SUBJECT_TOKEN_TYPE, URLEncoder.encode(scope, \"UTF-8\"));\n\n if (resource != null) {\n urlParameters += \"&resource=\" + URLEncoder.encode(resource, \"UTF-8\");\n }\n } catch (UnsupportedEncodingException e) {\n throw new BoxAPIException(\n \"An error occurred while attempting to encode url parameters for a transactional token request\"\n );\n }\n\n BoxAPIRequest request = new BoxAPIRequest(apiConnection, url, \"POST\");\n request.shouldAuthenticate(false);\n request.setBody(urlParameters);\n\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n final String fileToken = responseJSON.get(\"access_token\").asString();\n BoxTransactionalAPIConnection transactionConnection = new BoxTransactionalAPIConnection(fileToken);\n transactionConnection.setExpires(responseJSON.get(\"expires_in\").asLong() * 1000);\n\n return transactionConnection;\n }", "public static void invert( final int blockLength ,\n final boolean upper ,\n final DSubmatrixD1 T ,\n final DSubmatrixD1 T_inv ,\n final double temp[] )\n {\n if( upper )\n throw new IllegalArgumentException(\"Upper triangular matrices not supported yet\");\n\n if( temp.length < blockLength*blockLength )\n throw new IllegalArgumentException(\"Temp must be at least blockLength*blockLength long.\");\n\n if( T.row0 != T_inv.row0 || T.row1 != T_inv.row1 || T.col0 != T_inv.col0 || T.col1 != T_inv.col1)\n throw new IllegalArgumentException(\"T and T_inv must be at the same elements in the matrix\");\n\n final int M = T.row1-T.row0;\n\n final double dataT[] = T.original.data;\n final double dataX[] = T_inv.original.data;\n\n final int offsetT = T.row0*T.original.numCols+M*T.col0;\n\n for( int i = 0; i < M; i += blockLength ) {\n int heightT = Math.min(T.row1-(i+T.row0),blockLength);\n\n int indexII = offsetT + T.original.numCols*(i+T.row0) + heightT*(i+T.col0);\n\n for( int j = 0; j < i; j += blockLength ) {\n int widthX = Math.min(T.col1-(j+T.col0),blockLength);\n\n for( int w = 0; w < temp.length; w++ ) {\n temp[w] = 0;\n }\n\n for( int k = j; k < i; k += blockLength ) {\n int widthT = Math.min(T.col1-(k+T.col0),blockLength);\n\n int indexL = offsetT + T.original.numCols*(i+T.row0) + heightT*(k+T.col0);\n int indexX = offsetT + T.original.numCols*(k+T.row0) + widthT*(j+T.col0);\n\n blockMultMinus(dataT,dataX,temp,indexL,indexX,0,heightT,widthT,widthX);\n }\n\n int indexX = offsetT + T.original.numCols*(i+T.row0) + heightT*(j+T.col0);\n\n InnerTriangularSolver_DDRB.solveL(dataT,temp,heightT,widthX,heightT,indexII,0);\n System.arraycopy(temp,0,dataX,indexX,widthX*heightT);\n }\n InnerTriangularSolver_DDRB.invertLower(dataT,dataX,heightT,indexII,indexII);\n }\n }", "public void animate(float animationTime, Matrix4f mat)\n {\n mRotInterpolator.animate(animationTime, mRotKey);\n mPosInterpolator.animate(animationTime, mPosKey);\n mSclInterpolator.animate(animationTime, mScaleKey);\n mat.translationRotateScale(mPosKey[0], mPosKey[1], mPosKey[2], mRotKey[0], mRotKey[1], mRotKey[2], mRotKey[3], mScaleKey[0], mScaleKey[1], mScaleKey[2]);\n\n }", "void portForward(final Patch patch, IdentityPatchContext context) throws PatchingException, IOException, XMLStreamException {\n assert patch.getIdentity().getPatchType() == Patch.PatchType.CUMULATIVE;\n\n final PatchingHistory history = context.getHistory();\n for (final PatchElement element : patch.getElements()) {\n\n final PatchElementProvider provider = element.getProvider();\n final String name = provider.getName();\n final boolean addOn = provider.isAddOn();\n\n final IdentityPatchContext.PatchEntry target = context.resolveForElement(element);\n final String cumulativePatchID = target.getCumulativePatchID();\n if (Constants.BASE.equals(cumulativePatchID)) {\n reenableRolledBackInBase(target);\n continue;\n }\n\n boolean found = false;\n final PatchingHistory.Iterator iterator = history.iterator();\n while (iterator.hasNextCP()) {\n final PatchingHistory.Entry entry = iterator.nextCP();\n final String patchId = addOn ? entry.getAddOnPatches().get(name) : entry.getLayerPatches().get(name);\n\n if (patchId != null && patchId.equals(cumulativePatchID)) {\n final Patch original = loadPatchInformation(entry.getPatchId(), installedImage);\n for (final PatchElement originalElement : original.getElements()) {\n if (name.equals(originalElement.getProvider().getName())\n && addOn == originalElement.getProvider().isAddOn()) {\n PatchingTasks.addMissingModifications(target, originalElement.getModifications(), ContentItemFilter.ALL_BUT_MISC);\n }\n }\n // Record a loader to have access to the current modules\n final DirectoryStructure structure = target.getDirectoryStructure();\n final File modulesRoot = structure.getModulePatchDirectory(patchId);\n final File bundlesRoot = structure.getBundlesPatchDirectory(patchId);\n final PatchContentLoader loader = PatchContentLoader.create(null, bundlesRoot, modulesRoot);\n context.recordContentLoader(patchId, loader);\n found = true;\n break;\n }\n }\n if (!found) {\n throw PatchLogger.ROOT_LOGGER.patchNotFoundInHistory(cumulativePatchID);\n }\n\n reenableRolledBackInBase(target);\n }\n }", "@Override\n public String printHelp() {\n List<CommandLineParser<CI>> parsers = getChildParsers();\n if (parsers != null && parsers.size() > 0) {\n StringBuilder sb = new StringBuilder();\n sb.append(processedCommand.printHelp(helpNames()))\n .append(Config.getLineSeparator())\n .append(processedCommand.name())\n .append(\" commands:\")\n .append(Config.getLineSeparator());\n\n int maxLength = 0;\n\n for (CommandLineParser child : parsers) {\n int length = child.getProcessedCommand().name().length();\n if (length > maxLength) {\n maxLength = length;\n }\n }\n\n for (CommandLineParser child : parsers) {\n sb.append(child.getFormattedCommand(4, maxLength + 2))\n .append(Config.getLineSeparator());\n }\n\n return sb.toString();\n }\n else\n return processedCommand.printHelp(helpNames());\n }" ]
Lookup the username for the specified User URL. @param url The user profile URL @return The username @throws FlickrException
[ "public String lookupUser(String url) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_LOOKUP_USER);\r\n\r\n parameters.put(\"url\", url);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element payload = response.getPayload();\r\n Element groupnameElement = (Element) payload.getElementsByTagName(\"username\").item(0);\r\n return ((Text) groupnameElement.getFirstChild()).getData();\r\n }" ]
[ "protected float getViewPortSize(final Axis axis) {\n float size = mViewPort == null ? 0 : mViewPort.get(axis);\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"getViewPortSize for %s %f mViewPort = %s\", axis, size, mViewPort);\n return size;\n }", "public static String getContent(String stringUrl) throws IOException {\n InputStream stream = getContentStream(stringUrl);\n return MyStreamUtils.readContent(stream);\n }", "public static sslvserver_sslcertkey_binding[] get(nitro_service service, String vservername) throws Exception{\n\t\tsslvserver_sslcertkey_binding obj = new sslvserver_sslcertkey_binding();\n\t\tobj.set_vservername(vservername);\n\t\tsslvserver_sslcertkey_binding response[] = (sslvserver_sslcertkey_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static boolean setDefaultCustomResponse(String pathValue, String requestType, String customData) {\n try {\n JSONObject profile = getDefaultProfile();\n String profileName = profile.getString(\"name\");\n PathValueClient client = new PathValueClient(profileName, false);\n return client.setCustomResponse(pathValue, requestType, customData);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }", "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}", "public static <IN extends CoreMap> CRFClassifier<IN> getJarClassifier(String resourceName, Properties props) {\r\n CRFClassifier<IN> crf = new CRFClassifier<IN>();\r\n crf.loadJarClassifier(resourceName, props);\r\n return crf;\r\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 static java.util.Date rollDateTime(java.util.Date startDate, int period, int amount) {\n GregorianCalendar gc = new GregorianCalendar();\n gc.setTime(startDate);\n gc.add(period, amount);\n return new java.util.Date(gc.getTime().getTime());\n }", "public static AT_Row createContentRow(Object[] content, TableRowStyle style){\r\n\t\tValidate.notNull(content);\r\n\t\tValidate.notNull(style);\r\n\t\tValidate.validState(style!=TableRowStyle.UNKNOWN);\r\n\r\n\t\tLinkedList<AT_Cell> cells = new LinkedList<AT_Cell>();\r\n\t\tfor(Object o : content){\r\n\t\t\tcells.add(new AT_Cell(o));\r\n\t\t}\r\n\r\n\t\treturn new AT_Row(){\r\n\t\t\t@Override\r\n\t\t\tpublic TableRowType getType(){\r\n\t\t\t\treturn TableRowType.CONTENT;\r\n\t\t\t}\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic TableRowStyle getStyle(){\r\n\t\t\t\treturn style;\r\n\t\t\t}\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic LinkedList<AT_Cell> getCells(){\r\n\t\t\t\treturn cells;\r\n\t\t\t}\r\n\t\t};\r\n\t}" ]
prevent too many refreshes happening one after the other.
[ "private void tryRefreshAccessToken(final Long reqStartedAt) {\n authLock.writeLock().lock();\n try {\n if (!isLoggedIn()) {\n throw new StitchClientException(StitchClientErrorCode.LOGGED_OUT_DURING_REQUEST);\n }\n\n try {\n final Jwt jwt = Jwt.fromEncoded(getAuthInfo().getAccessToken());\n if (jwt.getIssuedAt() >= reqStartedAt) {\n return;\n }\n } catch (final IOException e) {\n // Swallow\n }\n\n // retry\n refreshAccessToken();\n } finally {\n authLock.writeLock().unlock();\n }\n }" ]
[ "public Set<CoreDocumentSynchronizationConfig> getSynchronizedDocuments(\n final MongoNamespace namespace\n ) {\n this.waitUntilInitialized();\n try {\n ongoingOperationsGroup.enter();\n return this.syncConfig.getSynchronizedDocuments(namespace);\n } finally {\n ongoingOperationsGroup.exit();\n }\n }", "public static vpnvserver_authenticationsamlpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_authenticationsamlpolicy_binding obj = new vpnvserver_authenticationsamlpolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_authenticationsamlpolicy_binding response[] = (vpnvserver_authenticationsamlpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "@SuppressWarnings(\"unchecked\")\n public <T> Map<String, T> find(final Class<T> valueTypeToFind) {\n return (Map<String, T>) this.values.entrySet().stream()\n .filter(input -> valueTypeToFind.isInstance(input.getValue()))\n .collect(\n Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));\n }", "public ConfigBuilder withSentinels(final Set<String> sentinels) {\n if (sentinels == null || sentinels.size() < 1) {\n throw new IllegalArgumentException(\"sentinels is null or empty: \" + sentinels);\n }\n this.sentinels = sentinels;\n return this;\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 Integer getIdFromName(String profileName) {\n PreparedStatement query = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n query = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_PROFILE +\n \" WHERE \" + Constants.PROFILE_PROFILE_NAME + \" = ?\");\n query.setString(1, profileName);\n results = query.executeQuery();\n if (results.next()) {\n Object toReturn = results.getObject(Constants.GENERIC_ID);\n query.close();\n return (Integer) toReturn;\n }\n query.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n return null;\n }", "private void processWorkPattern(ProjectCalendarWeek week, Integer workPatternID, Map<Integer, Row> workPatternMap, Map<Integer, List<Row>> timeEntryMap, Map<Integer, DayType> exceptionTypeMap)\n {\n Row workPatternRow = workPatternMap.get(workPatternID);\n if (workPatternRow != null)\n {\n week.setName(workPatternRow.getString(\"NAMN\"));\n\n List<Row> timeEntryRows = timeEntryMap.get(workPatternID);\n if (timeEntryRows != null)\n {\n long lastEndTime = Long.MIN_VALUE;\n Day currentDay = Day.SUNDAY;\n ProjectCalendarHours hours = week.addCalendarHours(currentDay);\n Arrays.fill(week.getDays(), DayType.NON_WORKING);\n\n for (Row row : timeEntryRows)\n {\n Date startTime = row.getDate(\"START_TIME\");\n Date endTime = row.getDate(\"END_TIME\");\n if (startTime == null)\n {\n startTime = DateHelper.getDayStartDate(new Date(0));\n }\n\n if (endTime == null)\n {\n endTime = DateHelper.getDayEndDate(new Date(0));\n }\n\n if (startTime.getTime() > endTime.getTime())\n {\n endTime = DateHelper.addDays(endTime, 1);\n }\n\n if (startTime.getTime() < lastEndTime)\n {\n currentDay = currentDay.getNextDay();\n hours = week.addCalendarHours(currentDay);\n }\n\n DayType type = exceptionTypeMap.get(row.getInteger(\"EXCEPTIOP\"));\n if (type == DayType.WORKING)\n {\n hours.addRange(new DateRange(startTime, endTime));\n week.setWorkingDay(currentDay, DayType.WORKING);\n }\n\n lastEndTime = endTime.getTime();\n }\n }\n }\n }", "public static boolean requiresReload(final Set<Flag> flags) {\n return flags.contains(Flag.RESTART_ALL_SERVICES) || flags.contains(Flag.RESTART_RESOURCE_SERVICES);\n }", "public boolean deleteWithCustomTimeout(CompositeVoldemortRequest<K, V> deleteRequestObject) {\n List<Versioned<V>> versionedValues;\n\n validateTimeout(deleteRequestObject.getRoutingTimeoutInMs());\n boolean hasVersion = deleteRequestObject.getVersion() == null ? false : true;\n String keyHexString = \"\";\n if(!hasVersion) {\n long startTimeInMs = System.currentTimeMillis();\n if(logger.isDebugEnabled()) {\n ByteArray key = (ByteArray) deleteRequestObject.getKey();\n keyHexString = RestUtils.getKeyHexString(key);\n logger.debug(\"DELETE without version requested for key: \" + keyHexString\n + \" , for store: \" + this.storeName + \" at time(in ms): \"\n + startTimeInMs + \" . Nested GET and DELETE requests to follow ---\");\n }\n // We use the full timeout for doing the Get. In this, we're being\n // optimistic that the subsequent delete might be faster all the\n // steps might finish within the allotted time\n deleteRequestObject.setResolveConflicts(true);\n versionedValues = getWithCustomTimeout(deleteRequestObject);\n Versioned<V> versioned = getItemOrThrow(deleteRequestObject.getKey(),\n null,\n versionedValues);\n\n if(versioned == null) {\n return false;\n }\n\n long timeLeft = deleteRequestObject.getRoutingTimeoutInMs()\n - (System.currentTimeMillis() - startTimeInMs);\n\n // This should not happen unless there's a bug in the\n // getWithCustomTimeout\n if(timeLeft < 0) {\n throw new StoreTimeoutException(\"DELETE request timed out\");\n }\n\n // Update the version and the new timeout\n deleteRequestObject.setVersion(versioned.getVersion());\n deleteRequestObject.setRoutingTimeoutInMs(timeLeft);\n\n }\n long deleteVersionStartTimeInNs = System.currentTimeMillis();\n if(logger.isDebugEnabled()) {\n ByteArray key = (ByteArray) deleteRequestObject.getKey();\n keyHexString = RestUtils.getKeyHexString(key);\n debugLogStart(\"DELETE\",\n deleteRequestObject.getRequestOriginTimeInMs(),\n deleteVersionStartTimeInNs,\n keyHexString);\n }\n boolean result = store.delete(deleteRequestObject);\n if(logger.isDebugEnabled()) {\n debugLogEnd(\"DELETE\",\n deleteRequestObject.getRequestOriginTimeInMs(),\n deleteVersionStartTimeInNs,\n System.currentTimeMillis(),\n keyHexString,\n 0);\n }\n if(!hasVersion && logger.isDebugEnabled()) {\n logger.debug(\"DELETE without version response received for key: \" + keyHexString\n + \", for store: \" + this.storeName + \" at time(in ms): \"\n + System.currentTimeMillis());\n }\n return result;\n }" ]
Ensures that the primary keys required by the given collection with indirection table are present in the element class. @param modelDef The model @param collDef The collection @throws ConstraintException If there is a problem with the fitting collection (if any) or the primary keys
[ "private void ensureReferencedPKs(ModelDef modelDef, CollectionDescriptorDef collDef) throws ConstraintException\r\n {\r\n String elementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF);\r\n ClassDescriptorDef elementClassDef = modelDef.getClass(elementClassName);\r\n String indirTable = collDef.getProperty(PropertyHelper.OJB_PROPERTY_INDIRECTION_TABLE);\r\n String localKey = collDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY);\r\n String remoteKey = collDef.getProperty(PropertyHelper.OJB_PROPERTY_REMOTE_FOREIGNKEY);\r\n boolean hasRemoteKey = remoteKey != null;\r\n ArrayList fittingCollections = new ArrayList();\r\n\r\n // we're checking for the fitting remote collection(s) and also\r\n // use their foreignkey as remote-foreignkey in the original collection definition\r\n for (Iterator it = elementClassDef.getAllExtentClasses(); it.hasNext();)\r\n {\r\n ClassDescriptorDef subTypeDef = (ClassDescriptorDef)it.next();\r\n\r\n // find the collection in the element class that has the same indirection table\r\n for (Iterator collIt = subTypeDef.getCollections(); collIt.hasNext();)\r\n {\r\n CollectionDescriptorDef curCollDef = (CollectionDescriptorDef)collIt.next();\r\n\r\n if (indirTable.equals(curCollDef.getProperty(PropertyHelper.OJB_PROPERTY_INDIRECTION_TABLE)) &&\r\n (collDef != curCollDef) &&\r\n (!hasRemoteKey || CommaListIterator.sameLists(remoteKey, curCollDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY))) &&\r\n (!curCollDef.hasProperty(PropertyHelper.OJB_PROPERTY_REMOTE_FOREIGNKEY) ||\r\n CommaListIterator.sameLists(localKey, curCollDef.getProperty(PropertyHelper.OJB_PROPERTY_REMOTE_FOREIGNKEY))))\r\n {\r\n fittingCollections.add(curCollDef);\r\n }\r\n }\r\n }\r\n if (!fittingCollections.isEmpty())\r\n {\r\n // if there is more than one, check that they match, i.e. that they all have the same foreignkeys\r\n if (!hasRemoteKey && (fittingCollections.size() > 1))\r\n {\r\n CollectionDescriptorDef firstCollDef = (CollectionDescriptorDef)fittingCollections.get(0);\r\n String foreignKey = firstCollDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY);\r\n\r\n for (int idx = 1; idx < fittingCollections.size(); idx++)\r\n {\r\n CollectionDescriptorDef curCollDef = (CollectionDescriptorDef)fittingCollections.get(idx);\r\n\r\n if (!CommaListIterator.sameLists(foreignKey, curCollDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY)))\r\n {\r\n throw new ConstraintException(\"Cannot determine the element-side collection that corresponds to the collection \"+\r\n collDef.getName()+\" in type \"+collDef.getOwner().getName()+\r\n \" because there are at least two different collections that would fit.\"+\r\n \" Specifying remote-foreignkey in the original collection \"+collDef.getName()+\r\n \" will perhaps help\");\r\n }\r\n }\r\n // store the found keys at the collections\r\n collDef.setProperty(PropertyHelper.OJB_PROPERTY_REMOTE_FOREIGNKEY, foreignKey);\r\n for (int idx = 0; idx < fittingCollections.size(); idx++)\r\n {\r\n CollectionDescriptorDef curCollDef = (CollectionDescriptorDef)fittingCollections.get(idx);\r\n\r\n curCollDef.setProperty(PropertyHelper.OJB_PROPERTY_REMOTE_FOREIGNKEY, localKey);\r\n }\r\n }\r\n }\r\n\r\n // copy subclass pk fields into target class (if not already present)\r\n ensurePKsFromHierarchy(elementClassDef);\r\n }" ]
[ "@Override\n public void registerChildren(ManagementResourceRegistration resourceRegistration) {\n // Register wildcard children last to prevent duplicate registration errors when override definitions exist\n for (ResourceDefinition rd : singletonChildren) {\n resourceRegistration.registerSubModel(rd);\n }\n for (ResourceDefinition rd : wildcardChildren) {\n resourceRegistration.registerSubModel(rd);\n }\n }", "public static Chart getMSDLineWithActiveTransportModelChart(Trajectory t, int lagMin,\n\t\t\tint lagMax, double timelag, double diffusionCoefficient, double velocity) {\n\n\t\tdouble[] xData = new double[lagMax - lagMin + 1];\n\t\tdouble[] yData = new double[lagMax - lagMin + 1];\n\t\tdouble[] modelData = new double[lagMax - lagMin + 1];\n\t\tMeanSquaredDisplacmentFeature msdeval = new MeanSquaredDisplacmentFeature(\n\t\t\t\tt, lagMin);\n\t\tmsdeval.setTrajectory(t);\n\t\tmsdeval.setTimelag(lagMin);\n\t\tfor (int i = lagMin; i < lagMax + 1; i++) {\n\t\t\tmsdeval.setTimelag(i);\n\t\t\tdouble msdhelp = msdeval.evaluate()[0];\n\t\t\txData[i - lagMin] = i;\n\t\t\tyData[i - lagMin] = msdhelp;\n\t\t\tmodelData[i - lagMin] = Math.pow(velocity*(i*timelag), 2) + 4*diffusionCoefficient*(i*timelag);//4 * D * Math.pow(i * timelag, a);\n\t\t}\n\n\t\t// Create Chart\n\t\tChart chart = QuickChart.getChart(\"MSD Line\", \"LAG\", \"MSD\", \"MSD\",\n\t\t\t\txData, yData);\n\t\tchart.addSeries(\"y=4*D*t + (v*t)^2\", xData, modelData);\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}", "public static void resize(GVRMesh mesh, float size) {\n float dim[] = getBoundingSize(mesh);\n float maxsize = 0.0f;\n\n if (dim[0] > maxsize) maxsize = dim[0];\n if (dim[1] > maxsize) maxsize = dim[1];\n if (dim[2] > maxsize) maxsize = dim[2];\n\n scale(mesh, size / maxsize);\n }", "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 }", "private boolean checkDeploymentDir(File directory) {\n if (!directory.exists()) {\n if (deploymentDirAccessible) {\n deploymentDirAccessible = false;\n ROOT_LOGGER.directoryIsNonexistent(deploymentDir.getAbsolutePath());\n }\n }\n else if (!directory.isDirectory()) {\n if (deploymentDirAccessible) {\n deploymentDirAccessible = false;\n ROOT_LOGGER.isNotADirectory(deploymentDir.getAbsolutePath());\n }\n }\n else if (!directory.canRead()) {\n if (deploymentDirAccessible) {\n deploymentDirAccessible = false;\n ROOT_LOGGER.directoryIsNotReadable(deploymentDir.getAbsolutePath());\n }\n }\n else if (!directory.canWrite()) {\n if (deploymentDirAccessible) {\n deploymentDirAccessible = false;\n ROOT_LOGGER.directoryIsNotWritable(deploymentDir.getAbsolutePath());\n }\n } else {\n deploymentDirAccessible = true;\n }\n\n return deploymentDirAccessible;\n }", "public List<Integer> getAsyncOperationList(boolean showCompleted) {\n /**\n * Create a copy using an immutable set to avoid a\n * {@link java.util.ConcurrentModificationException}\n */\n Set<Integer> keySet = ImmutableSet.copyOf(operations.keySet());\n\n if(showCompleted)\n return new ArrayList<Integer>(keySet);\n\n List<Integer> keyList = new ArrayList<Integer>();\n for(int key: keySet) {\n AsyncOperation operation = operations.get(key);\n if(operation != null && !operation.getStatus().isComplete())\n keyList.add(key);\n }\n return keyList;\n }", "protected static void appendHandler(LogRecordHandler parent, LogRecordHandler child){\r\n RecordHandlerTree p = handlers.find(parent);\r\n if(p != null){\r\n p.addChild(child);\r\n } else {\r\n throw new IllegalArgumentException(\"No such parent handler: \" + parent);\r\n }\r\n }", "public void deployApplication(String applicationName, String... classpathLocations) throws IOException {\n\n final List<URL> classpathElements = Arrays.stream(classpathLocations)\n .map(classpath -> Thread.currentThread().getContextClassLoader().getResource(classpath))\n .collect(Collectors.toList());\n\n deployApplication(applicationName, classpathElements.toArray(new URL[classpathElements.size()]));\n }", "public void generateMapFile(File jarFile, String mapFileName, boolean mapClassMethods) throws XMLStreamException, IOException, ClassNotFoundException, IntrospectionException\n {\n m_responseList = new LinkedList<String>();\n writeMapFile(mapFileName, jarFile, mapClassMethods);\n }" ]
Generate the next combination and return an array containing the appropriate elements. @see #nextCombinationAsArray(Object[]) @see #nextCombinationAsList() @return An array containing the elements that make up the next combination.
[ "@SuppressWarnings(\"unchecked\")\n public T[] nextCombinationAsArray()\n {\n T[] combination = (T[]) Array.newInstance(elements.getClass().getComponentType(),\n combinationIndices.length);\n return nextCombinationAsArray(combination);\n }" ]
[ "protected static void error(\n final HttpServletResponse httpServletResponse, final String message, final HttpStatus code) {\n try {\n httpServletResponse.setContentType(\"text/plain\");\n httpServletResponse.setStatus(code.value());\n setNoCache(httpServletResponse);\n try (PrintWriter out = httpServletResponse.getWriter()) {\n out.println(\"Error while processing request:\");\n out.println(message);\n }\n\n LOGGER.error(\"Error while processing request: {}\", message);\n } catch (IOException ex) {\n throw ExceptionUtils.getRuntimeException(ex);\n }\n }", "public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {\n switch (requestCode) {\n case REQUEST_PERMISSIONS_CODE:\n if (listener != null) {\n boolean granted = grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED;\n listener.onPermissionResult(granted);\n }\n break;\n default:\n // Ignored\n }\n }", "@Override\n public final int getInt(final int i) {\n int val = this.array.optInt(i, Integer.MIN_VALUE);\n if (val == Integer.MIN_VALUE) {\n throw new ObjectMissingException(this, \"[\" + i + \"]\");\n }\n return val;\n }", "private void updateLetsEncrypt() {\n\n getReport().println(Messages.get().container(Messages.RPT_STARTING_LETSENCRYPT_UPDATE_0));\n\n CmsLetsEncryptConfiguration config = OpenCms.getLetsEncryptConfig();\n if ((config == null) || !config.isValidAndEnabled()) {\n return;\n }\n CmsSiteConfigToLetsEncryptConfigConverter converter = new CmsSiteConfigToLetsEncryptConfigConverter(config);\n boolean ok = converter.run(getReport(), OpenCms.getSiteManager());\n if (ok) {\n getReport().println(\n org.opencms.ui.apps.Messages.get().container(org.opencms.ui.apps.Messages.RPT_LETSENCRYPT_FINISHED_0),\n I_CmsReport.FORMAT_OK);\n }\n\n }", "private void readPage(byte[] buffer, Table table)\n {\n int magicNumber = getShort(buffer, 0);\n if (magicNumber == 0x4400)\n {\n //System.out.println(ByteArrayHelper.hexdump(buffer, 0, 6, true, 16, \"\"));\n int recordSize = m_definition.getRecordSize();\n RowValidator rowValidator = m_definition.getRowValidator();\n String primaryKeyColumnName = m_definition.getPrimaryKeyColumnName();\n\n int index = 6;\n while (index + recordSize <= buffer.length)\n {\n //System.out.println(ByteArrayHelper.hexdump(buffer, index, recordSize, true, 16, \"\"));\n int btrieveValue = getShort(buffer, index);\n if (btrieveValue != 0)\n {\n Map<String, Object> row = new HashMap<String, Object>();\n row.put(\"ROW_VERSION\", Integer.valueOf(btrieveValue));\n for (ColumnDefinition column : m_definition.getColumns())\n {\n Object value = column.read(index, buffer);\n //System.out.println(column.getName() + \": \" + value);\n row.put(column.getName(), value);\n }\n\n if (rowValidator == null || rowValidator.validRow(row))\n {\n table.addRow(primaryKeyColumnName, row);\n }\n }\n index += recordSize;\n }\n }\n }", "private static CustomInfoType convertCustomInfo(Map<String, String> customInfo) {\n if (customInfo == null) {\n return null;\n }\n\n CustomInfoType ciType = new CustomInfoType();\n for (Entry<String, String> entry : customInfo.entrySet()) {\n CustomInfoType.Item cItem = new CustomInfoType.Item();\n cItem.setKey(entry.getKey());\n cItem.setValue(entry.getValue());\n ciType.getItem().add(cItem);\n }\n\n return ciType;\n }", "private void processCalendarDays(ProjectCalendar calendar, Record root)\n {\n // Retrieve working hours ...\n Record daysOfWeek = root.getChild(\"DaysOfWeek\");\n if (daysOfWeek != null)\n {\n for (Record dayRecord : daysOfWeek.getChildren())\n {\n processCalendarHours(calendar, dayRecord);\n }\n }\n }", "private void computeGradientAndHessian(DMatrixRMaj param )\n {\n // residuals = f(x) - y\n function.compute(param, residuals);\n\n computeNumericalJacobian(param,jacobian);\n\n CommonOps_DDRM.multTransA(jacobian, residuals, g);\n CommonOps_DDRM.multTransA(jacobian, jacobian, H);\n\n CommonOps_DDRM.extractDiag(H,Hdiag);\n }", "private List<Rule> getStyleRules(final String styleProperty) {\n final List<Rule> styleRules = new ArrayList<>(this.json.size());\n\n for (Iterator<String> iterator = this.json.keys(); iterator.hasNext(); ) {\n String styleKey = iterator.next();\n if (styleKey.equals(JSON_STYLE_PROPERTY) ||\n styleKey.equals(MapfishStyleParserPlugin.JSON_VERSION)) {\n continue;\n }\n PJsonObject styleJson = this.json.getJSONObject(styleKey);\n final List<Rule> currentRules = createStyleRule(styleKey, styleJson, styleProperty);\n for (Rule currentRule: currentRules) {\n if (currentRule != null) {\n styleRules.add(currentRule);\n }\n }\n }\n\n return styleRules;\n }" ]
Derive a calendar for a resource. @param parentCalendarID calendar from which resource calendar is derived @return new calendar for a resource
[ "private ProjectCalendar deriveResourceCalendar(Integer parentCalendarID)\n {\n ProjectCalendar calendar = m_project.addDefaultDerivedCalendar();\n calendar.setUniqueID(Integer.valueOf(m_project.getProjectConfig().getNextCalendarUniqueID()));\n calendar.setParent(m_project.getCalendarByUniqueID(parentCalendarID));\n return calendar;\n }" ]
[ "private CmsCheckBox generateCheckBox(Date date, boolean checkState) {\n\n CmsCheckBox cb = new CmsCheckBox();\n cb.setText(m_dateFormat.format(date));\n cb.setChecked(checkState);\n cb.getElement().setPropertyObject(\"date\", date);\n return cb;\n\n }", "public void init(ServletContext context) {\n if (profiles != null) {\n for (IDiagramProfile profile : profiles) {\n profile.init(context);\n _registry.put(profile.getName(),\n profile);\n }\n }\n }", "private JSONArray datesToJson(Collection<Date> individualDates) {\n\n if (null != individualDates) {\n JSONArray result = new JSONArray();\n for (Date d : individualDates) {\n result.put(dateToJson(d));\n }\n return result;\n }\n return null;\n }", "private void addPropertyCounters(UsageStatistics usageStatistics,\n\t\t\tPropertyIdValue property) {\n\t\tif (!usageStatistics.propertyCountsMain.containsKey(property)) {\n\t\t\tusageStatistics.propertyCountsMain.put(property, 0);\n\t\t\tusageStatistics.propertyCountsQualifier.put(property, 0);\n\t\t\tusageStatistics.propertyCountsReferences.put(property, 0);\n\t\t}\n\t}", "@Override public void process(MPPReader reader, ProjectFile file, DirectoryEntry root) throws MPXJException, IOException\n {\n try\n {\n populateMemberData(reader, file, root);\n processProjectProperties();\n\n if (!reader.getReadPropertiesOnly())\n {\n processSubProjectData();\n processGraphicalIndicators();\n processCustomValueLists();\n processCalendarData();\n processResourceData();\n processTaskData();\n processConstraintData();\n processAssignmentData();\n postProcessTasks();\n\n if (reader.getReadPresentationData())\n {\n processViewPropertyData();\n processTableData();\n processViewData();\n processFilterData();\n processGroupData();\n processSavedViewState();\n }\n }\n }\n\n finally\n {\n clearMemberData();\n }\n }", "private static String wordShapeDigits(final String s) {\r\n char[] outChars = null;\r\n\r\n for (int i = 0; i < s.length(); i++) {\r\n char c = s.charAt(i);\r\n if (Character.isDigit(c)) {\r\n if (outChars == null) {\r\n outChars = s.toCharArray();\r\n }\r\n outChars[i] = '9';\r\n }\r\n }\r\n if (outChars == null) {\r\n // no digit found\r\n return s;\r\n } else {\r\n return new String(outChars);\r\n }\r\n }", "public UriComponentsBuilder pathSegment(String... pathSegments) throws IllegalArgumentException {\n\t\tAssert.notNull(pathSegments, \"'segments' must not be null\");\n\t\tthis.pathBuilder.addPathSegments(pathSegments);\n\t\tresetSchemeSpecificPart();\n\t\treturn this;\n\t}", "public static Integer convertPathIdentifier(String identifier, Integer profileId) throws Exception {\n Integer pathId = -1;\n try {\n pathId = Integer.parseInt(identifier);\n } catch (NumberFormatException ne) {\n // this is OK.. just means it's not a #\n if (profileId == null)\n throw new Exception(\"A profileId must be specified\");\n\n pathId = PathOverrideService.getInstance().getPathId(identifier, profileId);\n }\n\n return pathId;\n }", "public ApnsServiceBuilder withDelegate(ApnsDelegate delegate) {\n this.delegate = delegate == null ? ApnsDelegate.EMPTY : delegate;\n return this;\n }" ]
Resolves the base directory. If the system property is set that value will be used. Otherwise the path is resolved from the home directory. @param name the system property name @param dirName the directory name relative to the base directory @return the resolved base directory
[ "Path resolveBaseDir(final String name, final String dirName) {\n final String currentDir = SecurityActions.getPropertyPrivileged(name);\n if (currentDir == null) {\n return jbossHomeDir.resolve(dirName);\n }\n return Paths.get(currentDir);\n }" ]
[ "protected Object buildOrRefreshObject(Map row, ClassDescriptor targetClassDescriptor, Object targetObject)\r\n {\r\n Object result = targetObject;\r\n FieldDescriptor fmd;\r\n FieldDescriptor[] fields = targetClassDescriptor.getFieldDescriptor(true);\r\n\r\n if(targetObject == null)\r\n {\r\n // 1. create new object instance if needed\r\n result = ClassHelper.buildNewObjectInstance(targetClassDescriptor);\r\n }\r\n\r\n // 2. fill all scalar attributes of the new object\r\n for (int i = 0; i < fields.length; i++)\r\n {\r\n fmd = fields[i];\r\n fmd.getPersistentField().set(result, row.get(fmd.getColumnName()));\r\n }\r\n\r\n if(targetObject == null)\r\n {\r\n // 3. for new build objects, invoke the initialization method for the class if one is provided\r\n Method initializationMethod = targetClassDescriptor.getInitializationMethod();\r\n if (initializationMethod != null)\r\n {\r\n try\r\n {\r\n initializationMethod.invoke(result, NO_ARGS);\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new PersistenceBrokerException(\"Unable to invoke initialization method:\" + initializationMethod.getName() + \" for class:\" + m_cld.getClassOfObject(), ex);\r\n }\r\n }\r\n }\r\n return result;\r\n }", "public synchronized void start() throws SocketException {\n\n if (!isRunning()) {\n socket.set(new DatagramSocket(ANNOUNCEMENT_PORT));\n startTime.set(System.currentTimeMillis());\n deliverLifecycleAnnouncement(logger, true);\n\n final byte[] buffer = new byte[512];\n final DatagramPacket packet = new DatagramPacket(buffer, buffer.length);\n Thread receiver = new Thread(null, new Runnable() {\n @Override\n public void run() {\n boolean received;\n while (isRunning()) {\n try {\n if (getCurrentDevices().isEmpty()) {\n socket.get().setSoTimeout(60000); // We have no devices to check for timeout; block for a whole minute to check for shutdown\n } else {\n socket.get().setSoTimeout(1000); // Check every second to see if a device has vanished\n }\n socket.get().receive(packet);\n received = !ignoredAddresses.contains(packet.getAddress());\n } catch (SocketTimeoutException ste) {\n received = false;\n } catch (IOException e) {\n // Don't log a warning if the exception was due to the socket closing at shutdown.\n if (isRunning()) {\n // We did not expect to have a problem; log a warning and shut down.\n logger.warn(\"Problem reading from DeviceAnnouncement socket, stopping\", e);\n stop();\n }\n received = false;\n }\n try {\n if (received && (packet.getLength() == 54)) {\n final Util.PacketType kind = Util.validateHeader(packet, ANNOUNCEMENT_PORT);\n if (kind == Util.PacketType.DEVICE_KEEP_ALIVE) {\n // Looks like the kind of packet we need\n if (packet.getLength() < 54) {\n logger.warn(\"Ignoring too-short \" + kind.name + \" packet; expected 54 bytes, but only got \" +\n packet.getLength() + \".\");\n } else {\n if (packet.getLength() > 54) {\n logger.warn(\"Processing too-long \" + kind.name + \" packet; expected 54 bytes, but got \" +\n packet.getLength() + \".\");\n }\n DeviceAnnouncement announcement = new DeviceAnnouncement(packet);\n final boolean foundNewDevice = isDeviceNew(announcement);\n updateDevices(announcement);\n if (foundNewDevice) {\n deliverFoundAnnouncement(announcement);\n }\n }\n }\n }\n expireDevices();\n } catch (Throwable t) {\n logger.warn(\"Problem processing DeviceAnnouncement packet\", t);\n }\n }\n }\n }, \"beat-link DeviceFinder receiver\");\n receiver.setDaemon(true);\n receiver.start();\n }\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 }", "private boolean isReadRequired(ValueGeneration valueGeneration, GenerationTiming matchTiming) {\n\t\treturn valueGeneration != null && valueGeneration.getValueGenerator() == null &&\n\t\t\t\ttimingsMatch( valueGeneration.getGenerationTiming(), matchTiming );\n\t}", "public CollectionDescriptorDef getCollection(String name)\r\n {\r\n CollectionDescriptorDef collDef = null;\r\n\r\n for (Iterator it = _collections.iterator(); it.hasNext(); )\r\n {\r\n collDef = (CollectionDescriptorDef)it.next();\r\n if (collDef.getName().equals(name))\r\n {\r\n return collDef;\r\n }\r\n }\r\n return null;\r\n }", "public CollectionRequest<Section> findByProject(String project) {\n \n String path = String.format(\"/projects/%s/sections\", project);\n return new CollectionRequest<Section>(this, Section.class, path, \"GET\");\n }", "public static nsacl6 get(nitro_service service, String acl6name) throws Exception{\n\t\tnsacl6 obj = new nsacl6();\n\t\tobj.set_acl6name(acl6name);\n\t\tnsacl6 response = (nsacl6) obj.get_resource(service);\n\t\treturn response;\n\t}", "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 }", "public static base_response Import(nitro_service client, responderhtmlpage resource) throws Exception {\n\t\tresponderhtmlpage Importresource = new responderhtmlpage();\n\t\tImportresource.src = resource.src;\n\t\tImportresource.name = resource.name;\n\t\tImportresource.comment = resource.comment;\n\t\tImportresource.overwrite = resource.overwrite;\n\t\treturn Importresource.perform_operation(client,\"Import\");\n\t}" ]
Creates a new InternetPrintWriter for given charset encoding. @param outputStream the wrapped output stream. @param charset the charset. @return a new InternetPrintWriter.
[ "public static InternetPrintWriter createForEncoding(OutputStream outputStream, boolean autoFlush, Charset charset) {\r\n return new InternetPrintWriter(new OutputStreamWriter(outputStream, charset), autoFlush);\r\n }" ]
[ "public void addAliasToConfigSite(String alias, String redirect, String offset) {\n\n long timeOffset = 0;\n try {\n timeOffset = Long.parseLong(offset);\n } catch (Throwable e) {\n // ignore\n }\n CmsSiteMatcher siteMatcher = new CmsSiteMatcher(alias, timeOffset);\n boolean redirectVal = new Boolean(redirect).booleanValue();\n siteMatcher.setRedirect(redirectVal);\n m_aliases.add(siteMatcher);\n }", "public static String soundex(String str) {\n if (str.length() < 1)\n return \"\"; // no soundex key for the empty string (could use 000)\n \n char[] key = new char[4];\n key[0] = str.charAt(0);\n int pos = 1;\n char prev = '0';\n for (int ix = 1; ix < str.length() && pos < 4; ix++) {\n char ch = str.charAt(ix);\n int charno;\n if (ch >= 'A' && ch <= 'Z')\n charno = ch - 'A';\n else if (ch >= 'a' && ch <= 'z')\n charno = ch - 'a';\n else\n continue;\n\n if (number[charno] != '0' && number[charno] != prev)\n key[pos++] = number[charno];\n prev = number[charno];\n }\n\n for ( ; pos < 4; pos++)\n key[pos] = '0';\n\n return new String(key);\n }", "public NamespacesList<Value> getValues(String namespace, String predicate, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n NamespacesList<Value> valuesList = new NamespacesList<Value>();\r\n parameters.put(\"method\", METHOD_GET_VALUES);\r\n\r\n if (namespace != null) {\r\n parameters.put(\"namespace\", namespace);\r\n }\r\n if (predicate != null) {\r\n parameters.put(\"predicate\", predicate);\r\n }\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element nsElement = response.getPayload();\r\n NodeList nsNodes = nsElement.getElementsByTagName(\"value\");\r\n valuesList.setPage(nsElement.getAttribute(\"page\"));\r\n valuesList.setPages(nsElement.getAttribute(\"pages\"));\r\n valuesList.setPerPage(nsElement.getAttribute(\"perPage\"));\r\n valuesList.setTotal(\"\" + nsNodes.getLength());\r\n for (int i = 0; i < nsNodes.getLength(); i++) {\r\n Element element = (Element) nsNodes.item(i);\r\n Value value = parseValue(element);\r\n value.setNamespace(namespace);\r\n value.setPredicate(predicate);\r\n valuesList.add(value);\r\n }\r\n return valuesList;\r\n }", "public void hide() {\n div.removeFromParent();\n if (scrollDisabled) {\n RootPanel.get().getElement().getStyle().setOverflow(Style.Overflow.AUTO);\n }\n if (type == LoaderType.CIRCULAR) {\n preLoader.removeFromParent();\n } else if (type == LoaderType.PROGRESS) {\n progress.removeFromParent();\n }\n }", "private static CmsObject adjustSiteRootIfNecessary(final CmsObject cms, final CmsModule module)\n throws CmsException {\n\n CmsObject cmsClone;\n if ((null == module.getSite()) || cms.getRequestContext().getSiteRoot().equals(module.getSite())) {\n cmsClone = cms;\n } else {\n cmsClone = OpenCms.initCmsObject(cms);\n cmsClone.getRequestContext().setSiteRoot(module.getSite());\n }\n\n return cmsClone;\n }", "public void handleConnectOriginal(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws HttpException, IOException {\n URI uri = request.getURI();\n\n try {\n LOG.fine(\"CONNECT: \" + uri);\n InetAddrPort addrPort;\n // When logging, we'll attempt to send messages to hosts that don't exist\n if (uri.toString().endsWith(\".selenium.doesnotexist:443\")) {\n // so we have to do set the host to be localhost (you can't new up an IAP with a non-existent hostname)\n addrPort = new InetAddrPort(443);\n } else {\n addrPort = new InetAddrPort(uri.toString());\n }\n\n if (isForbidden(HttpMessage.__SSL_SCHEME, addrPort.getHost(), addrPort.getPort(), false)) {\n sendForbid(request, response, uri);\n } else {\n HttpConnection http_connection = request.getHttpConnection();\n http_connection.forceClose();\n\n HttpServer server = http_connection.getHttpServer();\n\n SslListener listener = getSslRelayOrCreateNewOdo(uri, addrPort, server);\n\n int port = listener.getPort();\n\n // Get the timeout\n int timeoutMs = 30000;\n Object maybesocket = http_connection.getConnection();\n if (maybesocket instanceof Socket) {\n Socket s = (Socket) maybesocket;\n timeoutMs = s.getSoTimeout();\n }\n\n // Create the tunnel\n HttpTunnel tunnel = newHttpTunnel(request, response, InetAddress.getByName(null), port, timeoutMs);\n\n if (tunnel != null) {\n // TODO - need to setup semi-busy loop for IE.\n if (_tunnelTimeoutMs > 0) {\n tunnel.getSocket().setSoTimeout(_tunnelTimeoutMs);\n if (maybesocket instanceof Socket) {\n Socket s = (Socket) maybesocket;\n s.setSoTimeout(_tunnelTimeoutMs);\n }\n }\n tunnel.setTimeoutMs(timeoutMs);\n\n customizeConnection(pathInContext, pathParams, request, tunnel.getSocket());\n request.getHttpConnection().setHttpTunnel(tunnel);\n response.setStatus(HttpResponse.__200_OK);\n response.setContentLength(0);\n }\n request.setHandled(true);\n }\n } catch (Exception e) {\n LOG.fine(\"error during handleConnect\", e);\n response.sendError(HttpResponse.__500_Internal_Server_Error, e.toString());\n }\n }", "private int getBeliefCount() {\n Integer count = (Integer)introspector.getBeliefBase(ListenerMockAgent.this).get(Definitions.RECEIVED_MESSAGE_COUNT);\n if (count == null) count = 0; // Just in case, not really sure if this is necessary.\n return count;\n }", "@Override\n public void handleExceptions(MessageEvent messageEvent, Exception exception) {\n\n if(exception instanceof InvalidMetadataException) {\n logger.error(\"Exception when deleting. The requested key does not exist in this partition\",\n exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE,\n \"The requested key does not exist in this partition\");\n } else if(exception instanceof PersistenceFailureException) {\n logger.error(\"Exception when deleting. Operation failed\", exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.INTERNAL_SERVER_ERROR,\n \"Operation failed\");\n } else if(exception instanceof UnsupportedOperationException) {\n logger.error(\"Exception when deleting. Operation not supported in read-only store \",\n exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.METHOD_NOT_ALLOWED,\n \"Operation not supported in read-only store\");\n } else if(exception instanceof StoreTimeoutException) {\n String errorDescription = \"DELETE Request timed out: \" + exception.getMessage();\n logger.error(errorDescription);\n writeErrorResponse(messageEvent, HttpResponseStatus.REQUEST_TIMEOUT, errorDescription);\n } else if(exception instanceof InsufficientOperationalNodesException) {\n String errorDescription = \"DELETE Request failed: \" + exception.getMessage();\n logger.error(errorDescription);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.INTERNAL_SERVER_ERROR,\n errorDescription);\n } else {\n super.handleExceptions(messageEvent, exception);\n }\n }", "public DiffNode getChild(final NodePath nodePath)\n\t{\n\t\tif (parentNode != null)\n\t\t{\n\t\t\treturn parentNode.getChild(nodePath.getElementSelectors());\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn getChild(nodePath.getElementSelectors());\n\t\t}\n\t}" ]
Vend a SessionVar with the function to create the default value
[ "public static<T> SessionVar<T> vendSessionVar(Callable<T> defFunc) {\n\treturn (new VarsJBridge()).vendSessionVar(defFunc, new Exception());\n }" ]
[ "public T addContentModification(final ContentModification modification) {\n if (itemFilter.accepts(modification.getItem())) {\n internalAddModification(modification);\n }\n return returnThis();\n }", "public void postConstruct() throws URISyntaxException {\n WmsVersion.lookup(this.version);\n Assert.isTrue(validateBaseUrl(), \"invalid baseURL\");\n\n Assert.isTrue(this.layers.length > 0, \"There must be at least one layer defined for a WMS request\" +\n \" to make sense\");\n\n // OpenLayers 2 compatibility. It will post a single empty style no matter how many layers there are\n\n if (this.styles != null && this.styles.length != this.layers.length && this.styles.length == 1 &&\n this.styles[0].trim().isEmpty()) {\n this.styles = null;\n } else {\n Assert.isTrue(this.styles == null || this.layers.length == this.styles.length,\n String.format(\n \"If styles are defined then there must be one for each layer. Number of\" +\n \" layers: %s\\nStyles: %s\", this.layers.length,\n Arrays.toString(this.styles)));\n }\n\n if (this.imageFormat.indexOf('/') < 0) {\n LOGGER.warn(\"The format {} should be a mime type\", this.imageFormat);\n this.imageFormat = \"image/\" + this.imageFormat;\n }\n\n Assert.isTrue(this.method == HttpMethod.GET || this.method == HttpMethod.POST,\n String.format(\"Unsupported method %s for WMS layer\", this.method.toString()));\n }", "public double getSpread(double bondPrice, Curve referenceCurve, AnalyticModel model) {\n\t\tGoldenSectionSearch search = new GoldenSectionSearch(-2.0, 2.0);\n\t\twhile(search.getAccuracy() > 1E-11 && !search.isDone()) {\n\t\t\tdouble x = search.getNextPoint();\n\t\t\tdouble fx=getValueWithGivenSpreadOverCurve(0.0,referenceCurve,x,model);\n\t\t\tdouble y = (bondPrice-fx)*(bondPrice-fx);\n\n\t\t\tsearch.setValue(y);\n\t\t}\n\t\treturn search.getBestPoint();\n\t}", "public synchronized int getPartitionStoreCount() {\n int count = 0;\n for (String store : storeToPartitionIds.keySet()) {\n count += storeToPartitionIds.get(store).size();\n }\n return count;\n }", "@Override\n public void prettyPrint(StringBuffer sb, int indent)\n {\n sb.append(Log.getSpaces(indent));\n sb.append(GVRBone.class.getSimpleName());\n sb.append(\" [name=\" + getName() + \", boneId=\" + getBoneId()\n + \", offsetMatrix=\" + getOffsetMatrix()\n + \", finalTransformMatrix=\" + getFinalTransformMatrix() // crashes debugger\n + \"]\");\n sb.append(System.lineSeparator());\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<AccountingDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<AccountingDate>) super.localDateTime(temporal);\n }", "protected LayoutManager getLayOutManagerObj(ActionInvocation _invocation) {\n\t\tif (layoutManager == null || \"\".equals(layoutManager)){\n\t\t\tLOG.warn(\"No valid LayoutManager, using ClassicLayoutManager\");\n\t\t\treturn new ClassicLayoutManager();\n\t\t}\n\n\t\tObject los = conditionalParse(layoutManager, _invocation);\n\n\t\tif (los instanceof LayoutManager){\n\t\t\treturn (LayoutManager) los;\n\t\t}\n\n\t\tLayoutManager lo = null;\n\t\tif (los instanceof String){\n\t\t\tif (LAYOUT_CLASSIC.equalsIgnoreCase((String) los))\n\t\t\t\tlo = new ClassicLayoutManager();\n\t\t\telse if (LAYOUT_LIST.equalsIgnoreCase((String) los))\n\t\t\t\tlo = new ListLayoutManager();\n\t\t\telse {\n\t\t\t\ttry {\n\t\t\t\t\tlo = (LayoutManager) Class.forName((String) los).newInstance();\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tLOG.warn(\"No valid LayoutManager: \" + e.getMessage(),e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn lo;\n\t}", "public static Calendar popCalendar()\n {\n Calendar result;\n Deque<Calendar> calendars = CALENDARS.get();\n if (calendars.isEmpty())\n {\n result = Calendar.getInstance();\n }\n else\n {\n result = calendars.pop();\n }\n return result;\n }", "@SuppressWarnings(\"unused\")\n public boolean isValid() {\n Phonenumber.PhoneNumber phoneNumber = getPhoneNumber();\n return phoneNumber != null && mPhoneUtil.isValidNumber(phoneNumber);\n }" ]
Returns the classDescriptor. @return ClassDescriptor
[ "protected ClassDescriptor getClassDescriptor()\r\n {\r\n ClassDescriptor cld = (ClassDescriptor) m_classDescriptor.get();\r\n if(cld == null)\r\n {\r\n throw new OJBRuntimeException(\"Requested ClassDescriptor instance was already GC by JVM\");\r\n }\r\n return cld;\r\n }" ]
[ "public void createPdfLayout(Dimension dim)\n {\n if (pdfdocument != null) //processing a PDF document\n {\n try {\n if (createImage)\n img = new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_RGB);\n Graphics2D ig = img.createGraphics();\n \n log.info(\"Creating PDF boxes\");\n VisualContext ctx = new VisualContext(null, null);\n \n boxtree = new CSSBoxTree(ig, ctx, dim, baseurl);\n boxtree.setConfig(config);\n boxtree.processDocument(pdfdocument, startPage, endPage);\n viewport = boxtree.getViewport();\n root = boxtree.getDocument().getDocumentElement();\n log.info(\"We have \" + boxtree.getLastId() + \" boxes\");\n viewport.initSubtree();\n \n log.info(\"Layout for \"+dim.width+\"px\");\n viewport.doLayout(dim.width, true, true);\n log.info(\"Resulting size: \" + viewport.getWidth() + \"x\" + viewport.getHeight() + \" (\" + viewport + \")\");\n \n log.info(\"Updating viewport size\");\n viewport.updateBounds(dim);\n log.info(\"Resulting size: \" + viewport.getWidth() + \"x\" + viewport.getHeight() + \" (\" + viewport + \")\");\n \n if (createImage && (viewport.getWidth() > dim.width || viewport.getHeight() > dim.height))\n {\n img = new BufferedImage(Math.max(viewport.getWidth(), dim.width),\n Math.max(viewport.getHeight(), dim.height),\n BufferedImage.TYPE_INT_RGB);\n ig = img.createGraphics();\n }\n \n log.info(\"Positioning for \"+img.getWidth()+\"x\"+img.getHeight()+\"px\");\n viewport.absolutePositions();\n \n clearCanvas();\n viewport.draw(new GraphicsRenderer(ig));\n setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));\n revalidate();\n } catch (ParserConfigurationException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n else if (root != null) //processing a DOM tree\n {\n super.createLayout(dim);\n }\n }", "public static boolean isArray(Type type) {\n return (type instanceof GenericArrayType) || (type instanceof Class<?> && ((Class<?>) type).isArray());\n }", "public List<GVRAtlasInformation> getAtlasInformation()\n {\n if ((mImage != null) && (mImage instanceof GVRImageAtlas))\n {\n return ((GVRImageAtlas) mImage).getAtlasInformation();\n }\n return null;\n }", "@Override\n public InternationalFixedDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }", "public List<EndpointOverride> getSelectedPaths(int overrideType, Client client, Profile profile, String uri,\n Integer requestType, boolean pathTest) throws Exception {\n List<EndpointOverride> selectPaths = new ArrayList<EndpointOverride>();\n\n // get the paths for the current active client profile\n // this returns paths in priority order\n List<EndpointOverride> paths = new ArrayList<EndpointOverride>();\n\n if (client.getIsActive()) {\n paths = getPaths(\n profile.getId(),\n client.getUUID(), null);\n }\n\n boolean foundRealPath = false;\n logger.info(\"Checking uri: {}\", uri);\n\n // it should now be ordered by priority, i updated tableOverrides to\n // return the paths in priority order\n for (EndpointOverride path : paths) {\n // first see if the request types match..\n // and if the path request type is not ALL\n // if they do not then skip this path\n // If requestType is -1 we evaluate all(probably called by the path tester)\n if (requestType != -1 && path.getRequestType() != requestType && path.getRequestType() != Constants.REQUEST_TYPE_ALL) {\n continue;\n }\n\n // first see if we get a match\n try {\n Pattern pattern = Pattern.compile(path.getPath());\n Matcher matcher = pattern.matcher(uri);\n\n // we won't select the path if there aren't any enabled endpoints in it\n // this works since the paths are returned in priority order\n if (matcher.find()) {\n // now see if this path has anything enabled in it\n // Only go into the if:\n // 1. There are enabled items in this path\n // 2. Caller was looking for ResponseOverride and Response is enabled OR looking for RequestOverride\n // 3. If pathTest is true then the rest of the conditions are not evaluated. The path tester ignores enabled states so everything is returned.\n // and request is enabled\n if (pathTest ||\n (path.getEnabledEndpoints().size() > 0 &&\n ((overrideType == Constants.OVERRIDE_TYPE_RESPONSE && path.getResponseEnabled()) ||\n (overrideType == Constants.OVERRIDE_TYPE_REQUEST && path.getRequestEnabled())))) {\n // if we haven't already seen a non global path\n // or if this is a global path\n // then add it to the list\n if (!foundRealPath || path.getGlobal()) {\n selectPaths.add(path);\n }\n }\n\n // we set this no matter what if a path matched and it was not the global path\n // this stops us from adding further non global matches to the list\n if (!path.getGlobal()) {\n foundRealPath = true;\n }\n }\n } catch (PatternSyntaxException pse) {\n // nothing to do but keep iterating over the list\n // this indicates an invalid regex\n }\n }\n\n return selectPaths;\n }", "@Override\n public HandlerRegistration addSearchNoResultHandler(final SearchNoResultEvent.SearchNoResultHandler handler) {\n return addHandler(handler, SearchNoResultEvent.TYPE);\n }", "public void add(final String source, final T destination) {\n\n // replace multiple slashes with a single slash.\n String path = source.replaceAll(\"/+\", \"/\");\n\n path = (path.endsWith(\"/\") && path.length() > 1)\n ? path.substring(0, path.length() - 1) : path;\n\n\n String[] parts = path.split(\"/\", maxPathParts + 2);\n if (parts.length - 1 > maxPathParts) {\n throw new IllegalArgumentException(String.format(\"Number of parts of path %s exceeds allowed limit %s\",\n source, maxPathParts));\n }\n StringBuilder sb = new StringBuilder();\n List<String> groupNames = new ArrayList<>();\n\n for (String part : parts) {\n Matcher groupMatcher = GROUP_PATTERN.matcher(part);\n if (groupMatcher.matches()) {\n groupNames.add(groupMatcher.group(1));\n sb.append(\"([^/]+?)\");\n } else if (WILD_CARD_PATTERN.matcher(part).matches()) {\n sb.append(\".*?\");\n } else {\n sb.append(part);\n }\n sb.append(\"/\");\n }\n\n //Ignore the last \"/\"\n sb.setLength(sb.length() - 1);\n\n Pattern pattern = Pattern.compile(sb.toString());\n patternRouteList.add(ImmutablePair.of(pattern, new RouteDestinationWithGroups(destination, groupNames)));\n }", "public Collection<BoxGroupMembership.Info> getMemberships() {\n final BoxAPIConnection api = this.getAPI();\n final String groupID = this.getID();\n\n Iterable<BoxGroupMembership.Info> iter = new Iterable<BoxGroupMembership.Info>() {\n public Iterator<BoxGroupMembership.Info> iterator() {\n URL url = MEMBERSHIPS_URL_TEMPLATE.build(api.getBaseURL(), groupID);\n return new BoxGroupMembershipIterator(api, url);\n }\n };\n\n // We need to iterate all results because this method must return a Collection. This logic should be removed in\n // the next major version, and instead return the Iterable directly.\n Collection<BoxGroupMembership.Info> memberships = new ArrayList<BoxGroupMembership.Info>();\n for (BoxGroupMembership.Info membership : iter) {\n memberships.add(membership);\n }\n return memberships;\n }", "public void setSize(ButtonSize size) {\n if (this.size != null) {\n removeStyleName(this.size.getCssName());\n }\n this.size = size;\n\n if (size != null) {\n addStyleName(size.getCssName());\n }\n }" ]
Generates a JSON patch for transforming the source node into the target node. @param source the node to be patched @param target the expected result after applying the patch @param replaceMode the replace mode to be used @return the patch as a {@link JsonPatch}
[ "public static JsonPatch generate(final JsonNode source, final JsonNode target, ReplaceMode replaceMode) {\n requireNonNull(source, \"source\");\n requireNonNull(target, \"target\");\n final DiffProcessor processor = new DiffProcessor(replaceMode, () -> unchangedValues(source, target));\n generateDiffs(processor, EMPTY_JSON_POINTER, source, target);\n return processor.getPatch();\n }" ]
[ "public int readInt(int offset, byte[] data)\n {\n int result = 0;\n int i = offset + m_offset;\n for (int shiftBy = 0; shiftBy < 32; shiftBy += 8)\n {\n result |= ((data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }", "private static EventTypeEnum mapEventTypeEnum(EventEnumType eventType) {\n if (eventType != null) {\n return EventTypeEnum.valueOf(eventType.name());\n }\n return EventTypeEnum.UNKNOWN;\n }", "public void releaseDbResources()\r\n {\r\n Iterator it = m_rsIterators.iterator();\r\n while (it.hasNext())\r\n {\r\n ((OJBIterator) it.next()).releaseDbResources();\r\n }\r\n }", "public PayloadBuilder category(final String category) {\n if (category != null) {\n aps.put(\"category\", category);\n } else {\n aps.remove(\"category\");\n }\n return this;\n }", "public void ifHasName(String template, Properties attributes) throws XDocletException\r\n {\r\n String name = getDefForLevel(attributes.getProperty(ATTRIBUTE_LEVEL)).getName();\r\n\r\n if ((name != null) && (name.length() > 0))\r\n {\r\n generate(template);\r\n }\r\n }", "private ProjectFile read() throws Exception\n {\n m_project = new ProjectFile();\n m_eventManager = m_project.getEventManager();\n\n ProjectConfig config = m_project.getProjectConfig();\n config.setAutoCalendarUniqueID(false);\n config.setAutoTaskID(false);\n config.setAutoTaskUniqueID(false);\n config.setAutoResourceUniqueID(false);\n config.setAutoWBS(false);\n config.setAutoOutlineNumber(false);\n\n m_project.getProjectProperties().setFileApplication(\"FastTrack\");\n m_project.getProjectProperties().setFileType(\"FTS\");\n\n m_eventManager.addProjectListeners(m_projectListeners);\n\n // processProject();\n // processCalendars();\n processResources();\n processTasks();\n processDependencies();\n processAssignments();\n\n return m_project;\n }", "public static csvserver_copolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_copolicy_binding obj = new csvserver_copolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_copolicy_binding response[] = (csvserver_copolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public <T> Method getSetMethod(final Object object, final String fieldName, final Class<?> argumentType) {\n\t\tif( object == null ) {\n\t\t\tthrow new NullPointerException(\"object should not be null\");\n\t\t} else if( fieldName == null ) {\n\t\t\tthrow new NullPointerException(\"fieldName should not be null\");\n\t\t} else if( argumentType == null ) {\n\t\t\tthrow new NullPointerException(\"argumentType should not be null\");\n\t\t}\n\t\t\n\t\tMethod method = setMethodsCache.get(object.getClass(), argumentType, fieldName);\n\t\tif( method == null ) {\n\t\t\tmethod = ReflectionUtils.findSetter(object, fieldName, argumentType);\n\t\t\tsetMethodsCache.set(object.getClass(), argumentType, fieldName, method);\n\t\t}\n\t\treturn method;\n\t}", "private void clearQueues(final Context context) {\n synchronized (eventLock) {\n\n DBAdapter adapter = loadDBAdapter(context);\n DBAdapter.Table tableName = DBAdapter.Table.EVENTS;\n\n adapter.removeEvents(tableName);\n tableName = DBAdapter.Table.PROFILE_EVENTS;\n adapter.removeEvents(tableName);\n\n clearUserContext(context);\n }\n }" ]
Set the occurrences. If the String is invalid, the occurrences will be set to "-1" to cause server-side validation to fail. @param occurrences the interval to set.
[ "public void setOccurrences(String occurrences) {\r\n\r\n int o = CmsSerialDateUtil.toIntWithDefault(occurrences, -1);\r\n if (m_model.getOccurrences() != o) {\r\n m_model.setOccurrences(o);\r\n valueChanged();\r\n }\r\n }" ]
[ "protected void loadEntries(final StorageAwareResource resource, final ZipInputStream zipIn) throws IOException {\n zipIn.getNextEntry();\n BufferedInputStream _bufferedInputStream = new BufferedInputStream(zipIn);\n this.readContents(resource, _bufferedInputStream);\n zipIn.getNextEntry();\n BufferedInputStream _bufferedInputStream_1 = new BufferedInputStream(zipIn);\n this.readResourceDescription(resource, _bufferedInputStream_1);\n if (this.storeNodeModel) {\n zipIn.getNextEntry();\n BufferedInputStream _bufferedInputStream_2 = new BufferedInputStream(zipIn);\n this.readNodeModel(resource, _bufferedInputStream_2);\n }\n }", "public static ServiceName channelServiceName(final ServiceName endpointName, final String channelName) {\n return endpointName.append(\"channel\").append(channelName);\n }", "public static String eachMatch(String self, String regex, @ClosureParams(value=FromString.class, options={\"List<String>\",\"String[]\"}) Closure closure) {\n return eachMatch(self, Pattern.compile(regex), closure);\n }", "@Override\n public void onClick(View v) {\n String tag = (String) v.getTag();\n mContentTextView.setText(String.format(\"%s clicked.\", tag));\n mMenuDrawer.setActiveView(v);\n }", "public static Range toRange(Span span) {\n return new Range(toKey(span.getStart()), span.isStartInclusive(), toKey(span.getEnd()),\n span.isEndInclusive());\n }", "public static 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}", "public final static int readMdLink(final StringBuilder out, final String in, final int start)\n {\n int pos = start;\n int counter = 1;\n while (pos < in.length())\n {\n final char ch = in.charAt(pos);\n if (ch == '\\\\' && pos + 1 < in.length())\n {\n pos = escape(out, in.charAt(pos + 1), pos);\n }\n else\n {\n boolean endReached = false;\n switch (ch)\n {\n case '(':\n counter++;\n break;\n case ' ':\n if (counter == 1)\n {\n endReached = true;\n }\n break;\n case ')':\n counter--;\n if (counter == 0)\n {\n endReached = true;\n }\n break;\n }\n if (endReached)\n {\n break;\n }\n out.append(ch);\n }\n pos++;\n }\n\n return (pos == in.length()) ? -1 : pos;\n }", "public static BoxRetentionPolicyAssignment.Info createAssignmentToMetadata(BoxAPIConnection api,\r\n String policyID,\r\n String templateID,\r\n MetadataFieldFilter... filter) {\r\n JsonObject assignTo = new JsonObject().add(\"type\", TYPE_METADATA).add(\"id\", templateID);\r\n JsonArray filters = null;\r\n if (filter.length > 0) {\r\n filters = new JsonArray();\r\n for (MetadataFieldFilter f : filter) {\r\n filters.add(f.getJsonObject());\r\n }\r\n }\r\n return createAssignment(api, policyID, assignTo, filters);\r\n }", "public void setDiffuseIntensity(float r, float g, float b, float a) {\n setVec4(\"diffuse_intensity\", r, g, b, a);\n }" ]
Returns true if the given item document lacks a label for at least one of the languages covered. @param itemDocument @return true if some label is missing
[ "protected boolean lacksSomeLanguage(ItemDocument itemDocument) {\n\t\tfor (int i = 0; i < arabicNumeralLanguages.length; i++) {\n\t\t\tif (!itemDocument.getLabels()\n\t\t\t\t\t.containsKey(arabicNumeralLanguages[i])) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}" ]
[ "protected void destroyConnection(ConnectionHandle conn) {\r\n\t\tpostDestroyConnection(conn);\r\n\t\tconn.setInReplayMode(true); // we're dead, stop attempting to replay anything\r\n\t\ttry {\r\n\t\t\t\tconn.internalClose();\r\n\t\t} catch (SQLException e) {\r\n\t\t\tlogger.error(\"Error in attempting to close connection\", e);\r\n\t\t}\r\n\t}", "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 }", "@Override\n public final Map<String, OperationEntry> getOperationDescriptions(final PathAddress address, boolean inherited) {\n\n if (parent != null) {\n RootInvocation ri = getRootInvocation();\n return ri.root.getOperationDescriptions(ri.pathAddress.append(address), inherited);\n }\n // else we are the root\n Map<String, OperationEntry> providers = new TreeMap<String, OperationEntry>();\n getOperationDescriptions(address.iterator(), providers, inherited);\n return providers;\n }", "private MavenProjectModel getMavenStubProject(MavenProjectService mavenProjectService, String groupId, String artifactId, String version)\n {\n Iterable<MavenProjectModel> mavenProjectModels = mavenProjectService.findByGroupArtifactVersion(groupId, artifactId, version);\n if (!mavenProjectModels.iterator().hasNext())\n {\n return null;\n }\n for (MavenProjectModel mavenProjectModel : mavenProjectModels)\n {\n if (mavenProjectModel.getRootFileModel() == null)\n {\n // this is a stub... we can fill it in with details\n return mavenProjectModel;\n }\n }\n return null;\n }", "public static void closeScope(Object name) {\n //we remove the scope first, so that other threads don't see it, and see the next snapshot of the tree\n ScopeNode scope = (ScopeNode) MAP_KEY_TO_SCOPE.remove(name);\n if (scope != null) {\n ScopeNode parentScope = scope.getParentScope();\n if (parentScope != null) {\n parentScope.removeChild(scope);\n } else {\n ConfigurationHolder.configuration.onScopeForestReset();\n }\n removeScopeAndChildrenFromMap(scope);\n }\n }", "public double Function1D(double x) {\n return Math.exp(x * x / (-2 * sqrSigma)) / (Math.sqrt(2 * Math.PI) * sigma);\n }", "public void addItem(T value, Direction dir, String text) {\n addItem(value, dir, text, true);\n }", "private Table buildTable(CmsSqlConsoleResults results) {\n\n IndexedContainer container = new IndexedContainer();\n int numCols = results.getColumns().size();\n for (int c = 0; c < numCols; c++) {\n container.addContainerProperty(Integer.valueOf(c), results.getColumnType(c), null);\n }\n int r = 0;\n for (List<Object> row : results.getData()) {\n Item item = container.addItem(Integer.valueOf(r));\n for (int c = 0; c < numCols; c++) {\n item.getItemProperty(Integer.valueOf(c)).setValue(row.get(c));\n }\n r += 1;\n }\n Table table = new Table();\n table.setContainerDataSource(container);\n for (int c = 0; c < numCols; c++) {\n String col = (results.getColumns().get(c));\n table.setColumnHeader(Integer.valueOf(c), col);\n }\n table.setWidth(\"100%\");\n table.setHeight(\"100%\");\n table.setColumnCollapsingAllowed(true);\n return table;\n }", "public static final Integer parseMinutesFromHours(String value)\n {\n Integer result = null;\n if (value != null)\n {\n result = Integer.valueOf(Integer.parseInt(value) * 60);\n }\n return result;\n }" ]
Sets an argument to the collection of arguments. This guarantees only one value will be assigned to the argument key. @param argument the argument to add
[ "public void set(final Argument argument) {\n if (argument != null) {\n map.put(argument.getKey(), Collections.singleton(argument));\n }\n }" ]
[ "public com.groupon.odo.proxylib.models.Method getMethodForOverrideId(int overrideId) {\n com.groupon.odo.proxylib.models.Method method = null;\n\n // special case for IDs < 0\n if (overrideId < 0) {\n method = new com.groupon.odo.proxylib.models.Method();\n method.setId(overrideId);\n\n if (method.getId() == Constants.PLUGIN_RESPONSE_OVERRIDE_CUSTOM ||\n method.getId() == Constants.PLUGIN_RESPONSE_HEADER_OVERRIDE_ADD ||\n method.getId() == Constants.PLUGIN_RESPONSE_HEADER_OVERRIDE_REMOVE) {\n method.setMethodType(Constants.PLUGIN_TYPE_RESPONSE_OVERRIDE);\n } else {\n method.setMethodType(Constants.PLUGIN_TYPE_REQUEST_OVERRIDE);\n }\n } else {\n // get method information from the database\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_OVERRIDE +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n queryStatement.setInt(1, overrideId);\n results = queryStatement.executeQuery();\n\n if (results.next()) {\n method = new com.groupon.odo.proxylib.models.Method();\n method.setClassName(results.getString(Constants.OVERRIDE_CLASS_NAME));\n method.setMethodName(results.getString(Constants.OVERRIDE_METHOD_NAME));\n }\n } catch (SQLException e) {\n e.printStackTrace();\n return null;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n // if method is still null then just return\n if (method == null) {\n return method;\n }\n\n // now get the rest of the data from the plugin manager\n // this gets all of the actual method data\n try {\n method = PluginManager.getInstance().getMethod(method.getClassName(), method.getMethodName());\n method.setId(overrideId);\n } catch (Exception e) {\n // there was some problem.. return null\n return null;\n }\n }\n\n return method;\n }", "public static JRDesignGroup getJRDesignGroup(DynamicJasperDesign jd, LayoutManager layoutManager, DJGroup group) {\n\t\tMap references = layoutManager.getReferencesMap();\n\t\tfor (Object o : references.keySet()) {\n\t\t\tString groupName = (String) o;\n\t\t\tDJGroup djGroup = (DJGroup) references.get(groupName);\n\t\t\tif (group == djGroup) {\n\t\t\t\treturn (JRDesignGroup) jd.getGroupsMap().get(groupName);\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}", "public RemoteMongoCollection<Document> getCollection(final String collectionName) {\n return new RemoteMongoCollectionImpl<>(proxy.getCollection(collectionName), dispatcher);\n }", "public static void dumpClusters(Cluster currentCluster,\n Cluster finalCluster,\n String outputDirName) {\n dumpClusters(currentCluster, finalCluster, outputDirName, \"\");\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 }", "public static AbstractBuild<?, ?> getRootBuild(AbstractBuild<?, ?> currentBuild) {\n AbstractBuild<?, ?> rootBuild = null;\n AbstractBuild<?, ?> parentBuild = getUpstreamBuild(currentBuild);\n while (parentBuild != null) {\n if (isPassIdentifiedDownstream(parentBuild)) {\n rootBuild = parentBuild;\n }\n parentBuild = getUpstreamBuild(parentBuild);\n }\n if (rootBuild == null && isPassIdentifiedDownstream(currentBuild)) {\n return currentBuild;\n }\n return rootBuild;\n }", "public void initialize(BinaryPackageControlFile packageControlFile) {\n set(\"Binary\", packageControlFile.get(\"Package\"));\n set(\"Source\", Utils.defaultString(packageControlFile.get(\"Source\"), packageControlFile.get(\"Package\")));\n set(\"Architecture\", packageControlFile.get(\"Architecture\"));\n set(\"Version\", packageControlFile.get(\"Version\"));\n set(\"Maintainer\", packageControlFile.get(\"Maintainer\"));\n set(\"Changed-By\", packageControlFile.get(\"Maintainer\"));\n set(\"Distribution\", packageControlFile.get(\"Distribution\"));\n\n for (Entry<String, String> entry : packageControlFile.getUserDefinedFields().entrySet()) {\n set(entry.getKey(), entry.getValue());\n }\n\n StringBuilder description = new StringBuilder();\n description.append(packageControlFile.get(\"Package\"));\n if (packageControlFile.get(\"Description\") != null) {\n description.append(\" - \");\n description.append(packageControlFile.getShortDescription());\n }\n set(\"Description\", description.toString());\n }", "protected static final String formatUsingFormat(Long value, DateTimeFormat fmt) {\n if (value == null) {\n return \"\";\n }\n else {\n // midnight GMT\n Date date = new Date(0);\n // offset by timezone and value\n date.setTime(UTCDateBox.timezoneOffsetMillis(date) + value.longValue());\n // format it\n return fmt.format(date);\n }\n }", "private JSONArray getApplicablePathNames (String requestUrl, Integer requestType) throws Exception {\n RequestInformation requestInfo = requestInformation.get();\n List<EndpointOverride> applicablePaths;\n JSONArray pathNames = new JSONArray();\n // Get all paths that match the request\n applicablePaths = PathOverrideService.getInstance().getSelectedPaths(Constants.OVERRIDE_TYPE_REQUEST, requestInfo.client,\n requestInfo.profile,\n requestUrl + \"?\" + requestInfo.originalRequestInfo.getQueryString(),\n requestType, true);\n // Extract just the path name from each path\n for (EndpointOverride path : applicablePaths) {\n JSONObject pathName = new JSONObject();\n pathName.put(\"name\", path.getPathName());\n pathNames.put(pathName);\n }\n\n return pathNames;\n }" ]
m is more generic than a
[ "private static boolean isEqual(Method m, Method a) {\n if (m.getName().equals(a.getName()) && m.getParameterTypes().length == a.getParameterTypes().length && m.getReturnType().isAssignableFrom(a.getReturnType())) {\n for (int i = 0; i < m.getParameterTypes().length; i++) {\n if (!(m.getParameterTypes()[i].isAssignableFrom(a.getParameterTypes()[i]))) {\n return false;\n }\n }\n return true;\n }\n return false;\n }" ]
[ "public BoxFileUploadSession.Info getStatus() {\n URL statusURL = this.sessionInfo.getSessionEndpoints().getStatusEndpoint();\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), statusURL, HttpMethod.GET);\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n this.sessionInfo.update(jsonObject);\n\n return this.sessionInfo;\n }", "public void visitExport(String packaze, int access, String... modules) {\n if (mv != null) {\n mv.visitExport(packaze, access, modules);\n }\n }", "public final void notifyContentItemRemoved(int position) {\n if (position < 0 || position >= contentItemCount) {\n throw new IndexOutOfBoundsException(\"The given position \" + position\n + \" is not within the position bounds for content items [0 - \"\n + (contentItemCount - 1) + \"].\");\n }\n notifyItemRemoved(position + headerItemCount);\n }", "public boolean checkWrite(TransactionImpl tx, Object obj)\r\n {\r\n LockEntry writer = getWriter(obj);\r\n if (writer == null)\r\n return false;\r\n else if (writer.isOwnedBy(tx))\r\n return true;\r\n else\r\n return false;\r\n }", "private void processTasks() throws IOException\n {\n TaskReader reader = new TaskReader(m_data.getTableData(\"Tasks\"));\n reader.read();\n for (MapRow row : reader.getRows())\n {\n processTask(m_project, row);\n }\n updateDates();\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}", "private List<Map<Class<? extends Annotation>, ParameterInfo<?>>> createParametersInfos(Method method) {\n if (method.getParameterTypes().length <= 2) {\n return Collections.emptyList();\n }\n\n List<Map<Class<? extends Annotation>, ParameterInfo<?>>> result = new ArrayList<>();\n Type[] parameterTypes = method.getGenericParameterTypes();\n Annotation[][] parameterAnnotations = method.getParameterAnnotations();\n\n for (int i = 2; i < parameterAnnotations.length; i++) {\n Annotation[] annotations = parameterAnnotations[i];\n Map<Class<? extends Annotation>, ParameterInfo<?>> paramAnnotations = new IdentityHashMap<>();\n\n for (Annotation annotation : annotations) {\n Class<? extends Annotation> annotationType = annotation.annotationType();\n ParameterInfo<?> parameterInfo;\n\n if (PathParam.class.isAssignableFrom(annotationType)) {\n parameterInfo = ParameterInfo.create(annotation,\n ParamConvertUtils.createPathParamConverter(parameterTypes[i]));\n } else if (QueryParam.class.isAssignableFrom(annotationType)) {\n parameterInfo = ParameterInfo.create(annotation,\n ParamConvertUtils.createQueryParamConverter(parameterTypes[i]));\n } else if (HeaderParam.class.isAssignableFrom(annotationType)) {\n parameterInfo = ParameterInfo.create(annotation,\n ParamConvertUtils.createHeaderParamConverter(parameterTypes[i]));\n } else {\n parameterInfo = ParameterInfo.create(annotation, null);\n }\n\n paramAnnotations.put(annotationType, parameterInfo);\n }\n\n // Must have either @PathParam, @QueryParam or @HeaderParam, but not two or more.\n int presence = 0;\n for (Class<? extends Annotation> annotationClass : paramAnnotations.keySet()) {\n if (SUPPORTED_PARAM_ANNOTATIONS.contains(annotationClass)) {\n presence++;\n }\n }\n if (presence != 1) {\n throw new IllegalArgumentException(\n String.format(\"Must have exactly one annotation from %s for parameter %d in method %s\",\n SUPPORTED_PARAM_ANNOTATIONS, i, method));\n }\n\n result.add(Collections.unmodifiableMap(paramAnnotations));\n }\n\n return Collections.unmodifiableList(result);\n }", "public static String encodeQueryParam(String queryParam, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(queryParam, encoding, HierarchicalUriComponents.Type.QUERY_PARAM);\n\t}", "@Override\n public EthiopicDate date(int prolepticYear, int month, int dayOfMonth) {\n return EthiopicDate.of(prolepticYear, month, dayOfMonth);\n }" ]
generate a message for loglevel INFO @param pObject the message Object
[ "public final void info(Object pObject)\r\n\t{\r\n\t\tgetLogger().log(FQCN, Level.INFO, pObject, null);\r\n\t}" ]
[ "public static sslcertkey[] get(nitro_service service) throws Exception{\n\t\tsslcertkey obj = new sslcertkey();\n\t\tsslcertkey[] response = (sslcertkey[])obj.get_resources(service);\n\t\treturn response;\n\t}", "private FieldDescriptorDef cloneField(FieldDescriptorDef fieldDef, String prefix)\r\n {\r\n FieldDescriptorDef copyFieldDef = new FieldDescriptorDef(fieldDef, prefix);\r\n\r\n copyFieldDef.setOwner(this);\r\n // we remove properties that are only relevant to the class the features are declared in\r\n copyFieldDef.setProperty(PropertyHelper.OJB_PROPERTY_IGNORE, null);\r\n\r\n Properties mod = getModification(copyFieldDef.getName());\r\n\r\n if (mod != null)\r\n {\r\n if (!PropertyHelper.toBoolean(mod.getProperty(PropertyHelper.OJB_PROPERTY_IGNORE), false) &&\r\n hasFeature(copyFieldDef.getName()))\r\n {\r\n LogHelper.warn(true,\r\n ClassDescriptorDef.class,\r\n \"process\",\r\n \"Class \"+getName()+\" has a feature that has the same name as its included field \"+\r\n copyFieldDef.getName()+\" from class \"+fieldDef.getOwner().getName()); \r\n }\r\n copyFieldDef.applyModifications(mod);\r\n }\r\n return copyFieldDef;\r\n }", "private void parseMetadataItem(Message item) {\n switch (item.getMenuItemType()) {\n case TRACK_TITLE:\n title = ((StringField) item.arguments.get(3)).getValue();\n artworkId = (int) ((NumberField) item.arguments.get(8)).getValue();\n break;\n\n case ARTIST:\n artist = buildSearchableItem(item);\n break;\n\n case ORIGINAL_ARTIST:\n originalArtist = buildSearchableItem(item);\n break;\n\n case REMIXER:\n remixer = buildSearchableItem(item);\n\n case ALBUM_TITLE:\n album = buildSearchableItem(item);\n break;\n\n case LABEL:\n label = buildSearchableItem(item);\n break;\n\n case DURATION:\n duration = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n case TEMPO:\n tempo = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n case COMMENT:\n comment = ((StringField) item.arguments.get(3)).getValue();\n break;\n\n case KEY:\n key = buildSearchableItem(item);\n break;\n\n case RATING:\n rating = (int) ((NumberField)item.arguments.get(1)).getValue();\n break;\n\n case COLOR_NONE:\n case COLOR_AQUA:\n case COLOR_BLUE:\n case COLOR_GREEN:\n case COLOR_ORANGE:\n case COLOR_PINK:\n case COLOR_PURPLE:\n case COLOR_RED:\n case COLOR_YELLOW:\n color = buildColorItem(item);\n break;\n\n case GENRE:\n genre = buildSearchableItem(item);\n break;\n\n case DATE_ADDED:\n dateAdded = ((StringField) item.arguments.get(3)).getValue();\n break;\n\n case YEAR:\n year = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n case BIT_RATE:\n bitRate = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n default:\n logger.warn(\"Ignoring track metadata item with unknown type: {}\", item);\n }\n }", "protected void mergeSameCost(LinkedList<TimephasedCost> list)\n {\n LinkedList<TimephasedCost> result = new LinkedList<TimephasedCost>();\n\n TimephasedCost previousAssignment = null;\n for (TimephasedCost assignment : list)\n {\n if (previousAssignment == null)\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n result.add(assignment);\n }\n else\n {\n Number previousAssignmentCost = previousAssignment.getAmountPerDay();\n Number assignmentCost = assignment.getTotalAmount();\n\n if (NumberHelper.equals(previousAssignmentCost.doubleValue(), assignmentCost.doubleValue(), 0.01))\n {\n Date assignmentStart = previousAssignment.getStart();\n Date assignmentFinish = assignment.getFinish();\n double total = previousAssignment.getTotalAmount().doubleValue();\n total += assignmentCost.doubleValue();\n\n TimephasedCost merged = new TimephasedCost();\n merged.setStart(assignmentStart);\n merged.setFinish(assignmentFinish);\n merged.setAmountPerDay(assignmentCost);\n merged.setTotalAmount(Double.valueOf(total));\n\n result.removeLast();\n assignment = merged;\n }\n else\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n }\n result.add(assignment);\n }\n\n previousAssignment = assignment;\n }\n\n list.clear();\n list.addAll(result);\n }", "private void createResultSubClassesMultipleJoinedTables(List result, ClassDescriptor cld, boolean wholeTree)\r\n {\r\n List tmp = (List) superClassMultipleJoinedTablesMap.get(cld.getClassOfObject());\r\n if(tmp != null)\r\n {\r\n result.addAll(tmp);\r\n if(wholeTree)\r\n {\r\n for(int i = 0; i < tmp.size(); i++)\r\n {\r\n Class subClass = (Class) tmp.get(i);\r\n ClassDescriptor subCld = getDescriptorFor(subClass);\r\n createResultSubClassesMultipleJoinedTables(result, subCld, wholeTree);\r\n }\r\n }\r\n }\r\n }", "public Date toDate(String dateString) {\n Date date = null;\n DateFormat df = new SimpleDateFormat(\"yyyy-MM-dd\");\n try {\n date = df.parse(dateString);\n } catch (ParseException ex) {\n System.out.println(ex.fillInStackTrace());\n }\n return date;\n }", "@SuppressWarnings(\"deprecation\")\n\tpublic static boolean timeEquals(java.util.Date d1, java.util.Date d2) {\n if (d1 == null || d2 == null) {\n return false;\n }\n\n return d1.getHours() == d2.getHours()\n && d1.getMinutes() == d2.getMinutes()\n && d1.getSeconds() == d2.getSeconds();\n }", "public static boolean isFinalVariable(DeclarationExpression declarationExpression, SourceCode sourceCode) {\r\n if (isFromGeneratedSourceCode(declarationExpression)) {\r\n return false;\r\n }\r\n List<Expression> variableExpressions = getVariableExpressions(declarationExpression);\r\n if (!variableExpressions.isEmpty()) {\r\n Expression variableExpression = variableExpressions.get(0);\r\n int startOfDeclaration = declarationExpression.getColumnNumber();\r\n int startOfVariableName = variableExpression.getColumnNumber();\r\n int sourceLineNumber = findFirstNonAnnotationLine(declarationExpression, sourceCode);\r\n String sourceLine = sourceCode.getLines().get(sourceLineNumber-1);\r\n\r\n String modifiers = (startOfDeclaration >= 0 && startOfVariableName >= 0 && sourceLine.length() >= startOfVariableName) ?\r\n sourceLine.substring(startOfDeclaration - 1, startOfVariableName - 1) : \"\";\r\n return modifiers.contains(\"final\");\r\n }\r\n return false;\r\n }", "public final void notifyContentItemRemoved(int position) {\n if (position < 0 || position >= contentItemCount) {\n throw new IndexOutOfBoundsException(\"The given position \" + position\n + \" is not within the position bounds for content items [0 - \"\n + (contentItemCount - 1) + \"].\");\n }\n notifyItemRemoved(position + headerItemCount);\n }" ]
Get the last non-white X point @param img Image in memory @return the trimmed width
[ "private static int getTrimmedWidth(BufferedImage img) {\n int height = img.getHeight();\n int width = img.getWidth();\n int trimmedWidth = 0;\n\n for (int i = 0; i < height; i++) {\n for (int j = width - 1; j >= 0; j--) {\n if (img.getRGB(j, i) != Color.WHITE.getRGB() && j > trimmedWidth) {\n trimmedWidth = j;\n break;\n }\n }\n }\n\n return trimmedWidth;\n }" ]
[ "public static Class<?> determineCommonAncestor(Class<?> clazz1, Class<?> clazz2) {\n\t\tif (clazz1 == null) {\n\t\t\treturn clazz2;\n\t\t}\n\t\tif (clazz2 == null) {\n\t\t\treturn clazz1;\n\t\t}\n\t\tif (clazz1.isAssignableFrom(clazz2)) {\n\t\t\treturn clazz1;\n\t\t}\n\t\tif (clazz2.isAssignableFrom(clazz1)) {\n\t\t\treturn clazz2;\n\t\t}\n\t\tClass<?> ancestor = clazz1;\n\t\tdo {\n\t\t\tancestor = ancestor.getSuperclass();\n\t\t\tif (ancestor == null || Object.class.equals(ancestor)) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\twhile (!ancestor.isAssignableFrom(clazz2));\n\t\treturn ancestor;\n\t}", "public void startup() {\n if (config.getEnableZookeeper()) {\n serverRegister.registerBrokerInZk();\n for (String topic : getAllTopics()) {\n serverRegister.processTask(new TopicTask(TopicTask.TaskType.CREATE, topic));\n }\n startupLatch.countDown();\n }\n logger.debug(\"Starting log flusher every {} ms with the following overrides {}\", config.getFlushSchedulerThreadRate(), logFlushIntervalMap);\n logFlusherScheduler.scheduleWithRate(new Runnable() {\n\n public void run() {\n flushAllLogs(false);\n }\n }, config.getFlushSchedulerThreadRate(), config.getFlushSchedulerThreadRate());\n }", "public static String compressedListOfPartitionsInZone(final Cluster cluster, int zoneId) {\n Map<Integer, Integer> idToRunLength = PartitionBalanceUtils.getMapOfContiguousPartitions(cluster,\n zoneId);\n\n StringBuilder sb = new StringBuilder();\n sb.append(\"[\");\n boolean first = true;\n Set<Integer> sortedInitPartitionIds = new TreeSet<Integer>(idToRunLength.keySet());\n for(int initPartitionId: sortedInitPartitionIds) {\n if(!first) {\n sb.append(\", \");\n } else {\n first = false;\n }\n\n int runLength = idToRunLength.get(initPartitionId);\n if(runLength == 1) {\n sb.append(initPartitionId);\n } else {\n int endPartitionId = (initPartitionId + runLength - 1)\n % cluster.getNumberOfPartitions();\n sb.append(initPartitionId).append(\"-\").append(endPartitionId);\n }\n }\n sb.append(\"]\");\n\n return sb.toString();\n }", "@Deprecated\n\tpublic List<Double> getResolutions() {\n\t\tList<Double> resolutions = new ArrayList<Double>();\n\t\tfor (ScaleInfo scale : getZoomLevels()) {\n\t\t\tresolutions.add(1. / scale.getPixelPerUnit());\n\t\t}\n\t\treturn resolutions;\n\t}", "public List<CmsCategory> getTopItems() {\n\n List<CmsCategory> categories = new ArrayList<CmsCategory>();\n String matcher = Pattern.quote(m_mainCategoryPath) + \"[^/]*/\";\n for (CmsCategory category : m_categories) {\n if (category.getPath().matches(matcher)) {\n categories.add(category);\n }\n }\n return categories;\n }", "private void parseResponse(InputStream inputStream) {\n\n try {\n DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();\n DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();\n Document doc = dBuilder.parse(inputStream);\n doc.getDocumentElement().normalize();\n\n NodeList nodes = doc.getElementsByTagName(\"place\");\n\n for (int i = 0; i < nodes.getLength(); i++) {\n Node node = nodes.item(i);\n\n if (node.getNodeType() == Node.ELEMENT_NODE) {\n Element element = (Element) node;\n _woeid = getValue(\"woeid\", element);\n }\n }\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n }", "private Object tryConvert(\n final MfClientHttpRequestFactory clientHttpRequestFactory,\n final Object rowValue) throws URISyntaxException, IOException {\n if (this.converters.isEmpty()) {\n return rowValue;\n }\n\n String value = String.valueOf(rowValue);\n for (TableColumnConverter<?> converter: this.converters) {\n if (converter.canConvert(value)) {\n return converter.resolve(clientHttpRequestFactory, value);\n }\n }\n\n return rowValue;\n }", "public PhotoList<Photo> getRecent(Set<String> extras, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_RECENT);\r\n\r\n if (extras != null && !extras.isEmpty()) {\r\n parameters.put(Extras.KEY_EXTRAS, StringUtilities.join(extras, \",\"));\r\n }\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", Integer.toString(perPage));\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", Integer.toString(page));\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n PhotoList<Photo> photos = PhotoUtils.createPhotoList(photosElement);\r\n return photos;\r\n }", "private ReferenceDescriptorDef cloneReference(ReferenceDescriptorDef refDef, String prefix)\r\n {\r\n ReferenceDescriptorDef copyRefDef = new ReferenceDescriptorDef(refDef, prefix);\r\n\r\n copyRefDef.setOwner(this);\r\n // we remove properties that are only relevant to the class the features are declared in\r\n copyRefDef.setProperty(PropertyHelper.OJB_PROPERTY_IGNORE, null);\r\n \r\n Properties mod = getModification(copyRefDef.getName());\r\n\r\n if (mod != null)\r\n {\r\n if (!PropertyHelper.toBoolean(mod.getProperty(PropertyHelper.OJB_PROPERTY_IGNORE), false) &&\r\n hasFeature(copyRefDef.getName()))\r\n {\r\n LogHelper.warn(true,\r\n ClassDescriptorDef.class,\r\n \"process\",\r\n \"Class \"+getName()+\" has a feature that has the same name as its included reference \"+\r\n copyRefDef.getName()+\" from class \"+refDef.getOwner().getName()); \r\n }\r\n copyRefDef.applyModifications(mod);\r\n }\r\n return copyRefDef;\r\n }" ]
Update the value of an embedded node property. @param executionEngine the {@link GraphDatabaseService} used to run the query @param keyValues the columns representing the identifier in the entity owning the embedded @param embeddedColumn the column on the embedded node (dot-separated properties) @param value the new value for the property
[ "public void updateEmbeddedColumn(GraphDatabaseService executionEngine, Object[] keyValues, String embeddedColumn, Object value) {\n\t\tString query = getUpdateEmbeddedColumnQuery( keyValues, embeddedColumn );\n\t\tMap<String, Object> params = params( ArrayHelper.concat( keyValues, value, value ) );\n\t\texecutionEngine.execute( query, params );\n\t}" ]
[ "public static base_response update(nitro_service client, lbsipparameters resource) throws Exception {\n\t\tlbsipparameters updateresource = new lbsipparameters();\n\t\tupdateresource.rnatsrcport = resource.rnatsrcport;\n\t\tupdateresource.rnatdstport = resource.rnatdstport;\n\t\tupdateresource.retrydur = resource.retrydur;\n\t\tupdateresource.addrportvip = resource.addrportvip;\n\t\tupdateresource.sip503ratethreshold = resource.sip503ratethreshold;\n\t\treturn updateresource.update_resource(client);\n\t}", "ArgumentsBuilder param(String param, String value) {\n if (value != null) {\n args.add(param);\n args.add(value);\n }\n return this;\n }", "@Override\n\tpublic void format(final StringBuffer sbuf, final LoggingEvent event) {\n\t\tfor (int i = 0; i < patternConverters.length; i++) {\n\t\t\tfinal int startField = sbuf.length();\n\t\t\tpatternConverters[i].format(event, sbuf);\n\t\t\tpatternFields[i].format(startField, sbuf);\n\t\t}\n\t}", "public static int Maximum(ImageSource fastBitmap, int startX, int startY, int width, int height) {\r\n int max = 0;\r\n\r\n if (fastBitmap.isGrayscale()) {\r\n for (int i = startX; i < height; i++) {\r\n for (int j = startY; j < width; j++) {\r\n int gray = fastBitmap.getRGB(j, i);\r\n if (gray > max) {\r\n max = gray;\r\n }\r\n }\r\n }\r\n } else {\r\n for (int i = startX; i < height; i++) {\r\n for (int j = startY; j < width; j++) {\r\n int gray = fastBitmap.getG(j, i);\r\n if (gray > max) {\r\n max = gray;\r\n }\r\n }\r\n }\r\n }\r\n\r\n return max;\r\n }", "private static void mergeBlocks(List< Block > blocks) {\r\n for (int i = 1; i < blocks.size(); i++) {\r\n Block b1 = blocks.get(i - 1);\r\n Block b2 = blocks.get(i);\r\n if ((b1.mode == b2.mode) &&\r\n (b1.mode != EncodingMode.NUM || b1.length + b2.length <= MAX_NUMERIC_COMPACTION_BLOCK_SIZE)) {\r\n b1.length += b2.length;\r\n blocks.remove(i);\r\n i--;\r\n }\r\n }\r\n }", "private void processCalendarHours(ProjectCalendar calendar, Record dayRecord)\n {\n // ... for each day of the week\n Day day = Day.getInstance(Integer.parseInt(dayRecord.getField()));\n // Get hours\n List<Record> recHours = dayRecord.getChildren();\n if (recHours.size() == 0)\n {\n // No data -> not working\n calendar.setWorkingDay(day, false);\n }\n else\n {\n calendar.setWorkingDay(day, true);\n // Read hours\n ProjectCalendarHours hours = calendar.addCalendarHours(day);\n for (Record recWorkingHours : recHours)\n {\n addHours(hours, recWorkingHours);\n }\n }\n }", "@Nonnull\n public static Builder builder(Revapi revapi) {\n List<String> knownExtensionIds = new ArrayList<>();\n\n addExtensionIds(revapi.getPipelineConfiguration().getApiAnalyzerTypes(), knownExtensionIds);\n addExtensionIds(revapi.getPipelineConfiguration().getTransformTypes(), knownExtensionIds);\n addExtensionIds(revapi.getPipelineConfiguration().getFilterTypes(), knownExtensionIds);\n addExtensionIds(revapi.getPipelineConfiguration().getReporterTypes(), knownExtensionIds);\n\n return new Builder(knownExtensionIds);\n }", "protected Boolean parseOptionalBooleanValue(final String path) {\n\n final I_CmsXmlContentValue value = m_xml.getValue(path, m_locale);\n if (value == null) {\n return null;\n } else {\n final String stringValue = value.getStringValue(null);\n try {\n final Boolean boolValue = Boolean.valueOf(stringValue);\n return boolValue;\n } catch (final NumberFormatException e) {\n LOG.info(Messages.get().getBundle().key(Messages.LOG_OPTIONAL_BOOLEAN_MISSING_1, path), e);\n return null;\n }\n }\n }", "public SimplifySpanBuild append(String text) {\n if (TextUtils.isEmpty(text)) return this;\n\n mNormalSizeText.append(text);\n mStringBuilder.append(text);\n return this;\n }" ]
Gets the site label for the entry. @param cms the current CMS context @param entry the entry @return the site label for the entry
[ "private String getSite(CmsObject cms, CmsFavoriteEntry entry) {\n\n CmsSite site = OpenCms.getSiteManager().getSiteForRootPath(entry.getSiteRoot());\n Item item = m_sitesContainer.getItem(entry.getSiteRoot());\n if (item != null) {\n return (String)(item.getItemProperty(\"caption\").getValue());\n }\n String result = entry.getSiteRoot();\n if (site != null) {\n if (!CmsStringUtil.isEmpty(site.getTitle())) {\n result = site.getTitle();\n }\n }\n return result;\n }" ]
[ "private void writeMap(String fieldName, Object value) throws IOException\n {\n @SuppressWarnings(\"unchecked\")\n Map<String, Object> map = (Map<String, Object>) value;\n m_writer.writeStartObject(fieldName);\n for (Map.Entry<String, Object> entry : map.entrySet())\n {\n Object entryValue = entry.getValue();\n if (entryValue != null)\n {\n DataType type = TYPE_MAP.get(entryValue.getClass().getName());\n if (type == null)\n {\n type = DataType.STRING;\n entryValue = entryValue.toString();\n }\n writeField(entry.getKey(), type, entryValue);\n }\n }\n m_writer.writeEndObject();\n }", "private void addFilters(MpxjTreeNode parentNode, List<Filter> filters)\n {\n for (Filter field : filters)\n {\n final Filter f = field;\n MpxjTreeNode childNode = new MpxjTreeNode(field)\n {\n @Override public String toString()\n {\n return f.getName();\n }\n };\n parentNode.add(childNode);\n }\n }", "private void useSearchService() throws Exception {\n\n System.out.println(\"Searching...\");\n\n WebClient wc = WebClient.create(\"http://localhost:\" + port + \"/services/personservice/search\");\n WebClient.getConfig(wc).getHttpConduit().getClient().setReceiveTimeout(10000000L);\n wc.accept(MediaType.APPLICATION_XML);\n \n // Moves to \"/services/personservice/search\"\n wc.path(\"person\");\n \n SearchConditionBuilder builder = SearchConditionBuilder.instance(); \n \n System.out.println(\"Find people with the name Fred or Lorraine:\");\n \n String query = builder.is(\"name\").equalTo(\"Fred\").or()\n .is(\"name\").equalTo(\"Lorraine\")\n .query();\n findPersons(wc, query);\n \n System.out.println(\"Find all people who are no more than 30 years old\");\n query = builder.is(\"age\").lessOrEqualTo(30)\n \t\t.query();\n \n findPersons(wc, query);\n \n System.out.println(\"Find all people who are older than 28 and whose father name is John\");\n query = builder.is(\"age\").greaterThan(28)\n \t\t.and(\"fatherName\").equalTo(\"John\")\n \t\t.query();\n \n findPersons(wc, query);\n\n System.out.println(\"Find all people who have children with name Fred\");\n query = builder.is(\"childName\").equalTo(\"Fred\")\n \t\t.query();\n \n findPersons(wc, query);\n \n //Moves to \"/services/personservice/personinfo\"\n wc.reset().accept(MediaType.APPLICATION_XML);\n wc.path(\"personinfo\");\n \n System.out.println(\"Find all people younger than 40 using JPA2 Tuples\");\n query = builder.is(\"age\").lessThan(40).query();\n \n // Use URI path component to capture the query expression\n wc.path(query);\n \n \n Collection<? extends PersonInfo> personInfos = wc.getCollection(PersonInfo.class);\n for (PersonInfo pi : personInfos) {\n \tSystem.out.println(\"ID : \" + pi.getId());\n }\n\n wc.close();\n }", "public static BufferedImage cloneImage( BufferedImage image ) {\n\t\tBufferedImage newImage = new BufferedImage( image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB );\n\t\tGraphics2D g = newImage.createGraphics();\n\t\tg.drawRenderedImage( image, null );\n\t\tg.dispose();\n\t\treturn newImage;\n\t}", "public static void applyToOrTransparent(ColorHolder colorHolder, Context ctx, GradientDrawable gradientDrawable) {\n if (colorHolder != null && gradientDrawable != null) {\n colorHolder.applyTo(ctx, gradientDrawable);\n } else if (gradientDrawable != null) {\n gradientDrawable.setColor(Color.TRANSPARENT);\n }\n }", "private ModelNode createOSNode() throws OperationFailedException {\n String osName = getProperty(\"os.name\");\n final ModelNode os = new ModelNode();\n if (osName != null && osName.toLowerCase().contains(\"linux\")) {\n try {\n os.set(GnuLinuxDistribution.discover());\n } catch (IOException ex) {\n throw new OperationFailedException(ex);\n }\n } else {\n os.set(osName);\n }\n return os;\n }", "private void processProperties(XMLStreamWriter writer, Set<Method> methodSet, Class<?> aClass) throws IntrospectionException, XMLStreamException\n {\n BeanInfo beanInfo = Introspector.getBeanInfo(aClass, aClass.getSuperclass());\n PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();\n\n for (int i = 0; i < propertyDescriptors.length; i++)\n {\n PropertyDescriptor propertyDescriptor = propertyDescriptors[i];\n if (propertyDescriptor.getPropertyType() != null)\n {\n String name = propertyDescriptor.getName();\n Method readMethod = propertyDescriptor.getReadMethod();\n Method writeMethod = propertyDescriptor.getWriteMethod();\n\n String readMethodName = readMethod == null ? null : readMethod.getName();\n String writeMethodName = writeMethod == null ? null : writeMethod.getName();\n addProperty(writer, name, propertyDescriptor.getPropertyType(), readMethodName, writeMethodName);\n\n if (readMethod != null)\n {\n methodSet.add(readMethod);\n }\n\n if (writeMethod != null)\n {\n methodSet.add(writeMethod);\n }\n }\n else\n {\n processAmbiguousProperty(writer, methodSet, aClass, propertyDescriptor);\n }\n }\n }", "private Iterable<BoxRetentionPolicyAssignment.Info> getAssignments(String type, int limit, String ... fields) {\r\n QueryStringBuilder queryString = new QueryStringBuilder();\r\n if (type != null) {\r\n queryString.appendParam(\"type\", type);\r\n }\r\n if (fields.length > 0) {\r\n queryString.appendParam(\"fields\", fields);\r\n }\r\n URL url = ASSIGNMENTS_URL_TEMPLATE.buildWithQuery(getAPI().getBaseURL(), queryString.toString(), getID());\r\n return new BoxResourceIterable<BoxRetentionPolicyAssignment.Info>(getAPI(), url, limit) {\r\n\r\n @Override\r\n protected BoxRetentionPolicyAssignment.Info factory(JsonObject jsonObject) {\r\n BoxRetentionPolicyAssignment assignment\r\n = new BoxRetentionPolicyAssignment(getAPI(), jsonObject.get(\"id\").asString());\r\n return assignment.new Info(jsonObject);\r\n }\r\n\r\n };\r\n }", "private void handleRequestNodeInfoResponse(SerialMessage incomingMessage) {\n\t\tlogger.trace(\"Handle RequestNodeInfo Response\");\n\t\tif(incomingMessage.getMessageBuffer()[2] != 0x00)\n\t\t\tlogger.debug(\"Request node info successfully placed on stack.\");\n\t\telse\n\t\t\tlogger.error(\"Request node info not placed on stack due to error.\");\n\t}" ]
Expensive. Creates the plan for the specific settings.
[ "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 PromotionEvaluationReport getModulePromotionReport(final String name, final String version) throws GrapesCommunicationException {\n return getModulePromotionReportRaw(name, version, false, PromotionEvaluationReport.class);\n }", "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 }", "public static void permutationInverse( int []original , int []inverse , int length ) {\n for (int i = 0; i < length; i++) {\n inverse[original[i]] = i;\n }\n }", "public void init(Configuration configuration) {\n if (devMode && reload && !listeningToDispatcher) {\n // this is the only way I found to be able to get added to to\n // ConfigurationProvider list\n // listening to events in Dispatcher\n listeningToDispatcher = true;\n Dispatcher.addDispatcherListener(this);\n }\n }", "public boolean isFinished(final ProcessorGraphNode processorGraphNode) {\n this.processorLock.lock();\n try {\n return this.executedProcessors.containsKey(processorGraphNode.getProcessor());\n } finally {\n this.processorLock.unlock();\n }\n }", "public void finishFlow(final String code, final String state) throws ApiException {\n if (account == null)\n throw new IllegalArgumentException(\"Auth is not set\");\n if (codeVerifier == null)\n throw new IllegalArgumentException(\"code_verifier is not set\");\n if (account.getClientId() == null)\n throw new IllegalArgumentException(\"client_id is not set\");\n StringBuilder builder = new StringBuilder();\n builder.append(\"grant_type=\");\n builder.append(encode(\"authorization_code\"));\n builder.append(\"&client_id=\");\n builder.append(encode(account.getClientId()));\n builder.append(\"&code=\");\n builder.append(encode(code));\n builder.append(\"&code_verifier=\");\n builder.append(encode(codeVerifier));\n update(account, builder.toString());\n }", "public static URI createRestURI(\n final String matrixId, final int row, final int col,\n final WMTSLayerParam layerParam) throws URISyntaxException {\n String path = layerParam.baseURL;\n if (layerParam.dimensions != null) {\n for (int i = 0; i < layerParam.dimensions.length; i++) {\n String dimension = layerParam.dimensions[i];\n String value = layerParam.dimensionParams.optString(dimension);\n if (value == null) {\n value = layerParam.dimensionParams.getString(dimension.toUpperCase());\n }\n path = path.replace(\"{\" + dimension + \"}\", value);\n }\n }\n path = path.replace(\"{TileMatrixSet}\", layerParam.matrixSet);\n path = path.replace(\"{TileMatrix}\", matrixId);\n path = path.replace(\"{TileRow}\", String.valueOf(row));\n path = path.replace(\"{TileCol}\", String.valueOf(col));\n path = path.replace(\"{style}\", layerParam.style);\n path = path.replace(\"{Layer}\", layerParam.layer);\n\n return new URI(path);\n }", "protected void setJsonValue(JsonObjectBuilder builder, T value) {\n // I don't like this - there should really be a way to construct a disconnected JSONValue...\n if (value instanceof Boolean) {\n builder.add(\"value\", (Boolean) value);\n } else if (value instanceof Double) {\n builder.add(\"value\", (Double) value);\n } else if (value instanceof Integer) {\n builder.add(\"value\", (Integer) value);\n } else if (value instanceof Long) {\n builder.add(\"value\", (Long) value);\n } else if (value instanceof BigInteger) {\n builder.add(\"value\", (BigInteger) value);\n } else if (value instanceof BigDecimal) {\n builder.add(\"value\", (BigDecimal) value);\n } else if (value == null) {\n builder.addNull(\"value\");\n } else {\n builder.add(\"value\", value.toString());\n }\n }", "static void loadFromOrigin(JobContext origin) {\n if (origin.bag_.isEmpty()) {\n return;\n }\n ActContext<?> actContext = ActContext.Base.currentContext();\n if (null != actContext) {\n Locale locale = (Locale) origin.bag_.get(\"locale\");\n if (null != locale) {\n actContext.locale(locale);\n }\n H.Session session = (H.Session) origin.bag_.get(\"session\");\n if (null != session) {\n actContext.attribute(\"__session\", session);\n }\n }\n }" ]
Returns the count of all inbox messages for the user @return int - count of all inbox messages
[ "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public int getInboxMessageCount(){\n synchronized (inboxControllerLock) {\n if (this.ctInboxController != null) {\n return ctInboxController.count();\n } else {\n getConfigLogger().debug(getAccountId(),\"Notification Inbox not initialized\");\n return -1;\n }\n }\n }" ]
[ "public boolean preHandle(HttpServletRequest request,\n HttpServletResponse response, Object handler) throws Exception {\n\n String queryString = request.getQueryString() == null ? \"\" : request.getQueryString();\n\n if (ConfigurationService.getInstance().isValid()\n || request.getServletPath().startsWith(\"/configuration\")\n || request.getServletPath().startsWith(\"/resources\")\n || queryString.contains(\"requestFromConfiguration=true\")) {\n return true;\n } else {\n response.sendRedirect(\"configuration\");\n return false;\n }\n }", "private void adjustVisibleColumns() {\n\n if (m_table.isColumnCollapsingAllowed()) {\n if ((m_model.hasDefaultValues()) || m_model.getBundleType().equals(BundleType.DESCRIPTOR)) {\n m_table.setColumnCollapsed(TableProperty.DEFAULT, false);\n } else {\n m_table.setColumnCollapsed(TableProperty.DEFAULT, true);\n }\n\n if (((m_model.getEditMode().equals(EditMode.MASTER) || m_model.hasDescriptionValues()))\n || m_model.getBundleType().equals(BundleType.DESCRIPTOR)) {\n m_table.setColumnCollapsed(TableProperty.DESCRIPTION, false);\n } else {\n m_table.setColumnCollapsed(TableProperty.DESCRIPTION, true);\n }\n }\n }", "@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 void deploy(InputStream inputStream) throws IOException {\n final List<? extends HasMetadata> entities = deploy(\"application\", inputStream);\n\n if (this.applicationName == null) {\n\n Optional<String> deployment = entities.stream()\n .filter(hm -> hm instanceof Deployment)\n .map(hm -> (Deployment) hm)\n .map(rc -> rc.getMetadata().getName()).findFirst();\n\n deployment.ifPresent(name -> this.applicationName = name);\n }\n }", "private void deleteByQuery(Query query, ClassDescriptor cld) throws PersistenceBrokerException\n {\n if (logger.isDebugEnabled())\n {\n logger.debug(\"deleteByQuery \" + cld.getClassNameOfObject() + \", \" + query);\n }\n\n if (query instanceof QueryBySQL)\n {\n String sql = ((QueryBySQL) query).getSql();\n this.dbAccess.executeUpdateSQL(sql, cld);\n }\n else\n {\n // if query is Identity based transform it to a criteria based query first\n if (query instanceof QueryByIdentity)\n {\n QueryByIdentity qbi = (QueryByIdentity) query;\n Object oid = qbi.getExampleObject();\n // make sure it's an Identity\n if (!(oid instanceof Identity))\n {\n oid = serviceIdentity().buildIdentity(oid);\n }\n query = referencesBroker.getPKQuery((Identity) oid);\n }\n\n if (!cld.isInterface())\n {\n this.dbAccess.executeDelete(query, cld);\n }\n\n // if class is an extent, we have to delete all extent classes too\n String lastUsedTable = cld.getFullTableName();\n if (cld.isExtent())\n {\n Iterator extents = getDescriptorRepository().getAllConcreteSubclassDescriptors(cld).iterator();\n\n while (extents.hasNext())\n {\n ClassDescriptor extCld = (ClassDescriptor) extents.next();\n\n // read same table only once\n if (!extCld.getFullTableName().equals(lastUsedTable))\n {\n lastUsedTable = extCld.getFullTableName();\n this.dbAccess.executeDelete(query, extCld);\n }\n }\n }\n\n }\n }", "public static double normP1( DMatrixRMaj A ) {\n if( MatrixFeatures_DDRM.isVector(A)) {\n return CommonOps_DDRM.elementSumAbs(A);\n } else {\n return inducedP1(A);\n }\n }", "public static final void getByteArray(byte[] data, int offset, int size, byte[] buffer, int bufferOffset)\n {\n System.arraycopy(data, offset, buffer, bufferOffset, size);\n }", "public void reportCompletion(NodeT completed) {\n completed.setPreparer(true);\n String dependency = completed.key();\n for (String dependentKey : nodeTable.get(dependency).dependentKeys()) {\n DAGNode<DataT, NodeT> dependent = nodeTable.get(dependentKey);\n dependent.lock().lock();\n try {\n dependent.onSuccessfulResolution(dependency);\n if (dependent.hasAllResolved()) {\n queue.add(dependent.key());\n }\n } finally {\n dependent.lock().unlock();\n }\n }\n }", "private void validateAttributesToCreateANewRendererViewHolder() {\n if (viewType == null) {\n throw new NullContentException(\n \"RendererBuilder needs a view type to create a RendererViewHolder\");\n }\n if (layoutInflater == null) {\n throw new NullLayoutInflaterException(\n \"RendererBuilder needs a LayoutInflater to create a RendererViewHolder\");\n }\n if (parent == null) {\n throw new NullParentException(\n \"RendererBuilder needs a parent to create a RendererViewHolder\");\n }\n }" ]
Returns a string that should be used as a label for the given property. @param propertyIdValue the property to label @return the label
[ "private String getPropertyLabel(PropertyIdValue propertyIdValue) {\n\t\tPropertyRecord propertyRecord = this.propertyRecords\n\t\t\t\t.get(propertyIdValue);\n\t\tif (propertyRecord == null || propertyRecord.propertyDocument == null) {\n\t\t\treturn propertyIdValue.getId();\n\t\t} else {\n\t\t\treturn getLabel(propertyIdValue, propertyRecord.propertyDocument);\n\t\t}\n\t}" ]
[ "public static final Duration parseDuration(String value)\n {\n return value == null ? null : Duration.getInstance(Double.parseDouble(value), TimeUnit.DAYS);\n }", "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 }", "public int compareTo(InternalFeature o) {\n\t\tif (null == o) {\n\t\t\treturn -1; // avoid NPE, put null objects at the end\n\t\t}\n\t\tif (null != styleDefinition && null != o.getStyleInfo()) {\n\t\t\tif (styleDefinition.getIndex() > o.getStyleInfo().getIndex()) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tif (styleDefinition.getIndex() < o.getStyleInfo().getIndex()) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t\treturn 0;\n\t}", "public static String resolveProxyUrl(String relativeUrl, TileMap tileMap, String baseTmsUrl) {\n\t\tTileCode tc = parseTileCode(relativeUrl);\n\t\treturn buildUrl(tc, tileMap, baseTmsUrl);\n\t}", "private String checkinScriptCommand() {\n\n String exportModules = \"\";\n if ((m_modulesToExport != null) && !m_modulesToExport.isEmpty()) {\n StringBuffer exportModulesParam = new StringBuffer();\n for (String moduleName : m_modulesToExport) {\n exportModulesParam.append(\" \").append(moduleName);\n }\n exportModulesParam.replace(0, 1, \" \\\"\");\n exportModulesParam.append(\"\\\" \");\n exportModules = \" --modules \" + exportModulesParam.toString();\n\n }\n String commitMessage = \"\";\n if (m_commitMessage != null) {\n commitMessage = \" -msg \\\"\" + m_commitMessage.replace(\"\\\"\", \"\\\\\\\"\") + \"\\\"\";\n }\n String gitUserName = \"\";\n if (m_gitUserName != null) {\n if (m_gitUserName.trim().isEmpty()) {\n gitUserName = \" --ignore-default-git-user-name\";\n } else {\n gitUserName = \" --git-user-name \\\"\" + m_gitUserName + \"\\\"\";\n }\n }\n String gitUserEmail = \"\";\n if (m_gitUserEmail != null) {\n if (m_gitUserEmail.trim().isEmpty()) {\n gitUserEmail = \" --ignore-default-git-user-email\";\n } else {\n gitUserEmail = \" --git-user-email \\\"\" + m_gitUserEmail + \"\\\"\";\n }\n }\n String autoPullBefore = \"\";\n if (m_autoPullBefore != null) {\n autoPullBefore = m_autoPullBefore.booleanValue() ? \" --pull-before \" : \" --no-pull-before\";\n }\n String autoPullAfter = \"\";\n if (m_autoPullAfter != null) {\n autoPullAfter = m_autoPullAfter.booleanValue() ? \" --pull-after \" : \" --no-pull-after\";\n }\n String autoPush = \"\";\n if (m_autoPush != null) {\n autoPush = m_autoPush.booleanValue() ? \" --push \" : \" --no-push\";\n }\n String exportFolder = \" --export-folder \\\"\" + m_currentConfiguration.getModuleExportPath() + \"\\\"\";\n String exportMode = \" --export-mode \" + m_currentConfiguration.getExportMode();\n String excludeLibs = \"\";\n if (m_excludeLibs != null) {\n excludeLibs = m_excludeLibs.booleanValue() ? \" --exclude-libs\" : \" --no-exclude-libs\";\n }\n String commitMode = \"\";\n if (m_commitMode != null) {\n commitMode = m_commitMode.booleanValue() ? \" --commit\" : \" --no-commit\";\n }\n String ignoreUncleanMode = \"\";\n if (m_ignoreUnclean != null) {\n ignoreUncleanMode = m_ignoreUnclean.booleanValue() ? \" --ignore-unclean\" : \" --no-ignore-unclean\";\n }\n String copyAndUnzip = \"\";\n if (m_copyAndUnzip != null) {\n copyAndUnzip = m_copyAndUnzip.booleanValue() ? \" --copy-and-unzip\" : \" --no-copy-and-unzip\";\n }\n\n String configFilePath = m_currentConfiguration.getFilePath();\n\n return \"\\\"\"\n + DEFAULT_SCRIPT_FILE\n + \"\\\"\"\n + exportModules\n + commitMessage\n + gitUserName\n + gitUserEmail\n + autoPullBefore\n + autoPullAfter\n + autoPush\n + exportFolder\n + exportMode\n + excludeLibs\n + commitMode\n + ignoreUncleanMode\n + copyAndUnzip\n + \" \\\"\"\n + configFilePath\n + \"\\\"\";\n }", "public static <OutT, InT> PagedList<OutT> toPagedList(List<InT> list, final Func1<InT, OutT> mapper) {\n PageImpl<InT> page = new PageImpl<>();\n page.setItems(list);\n page.setNextPageLink(null);\n PagedList<InT> pagedList = new PagedList<InT>(page) {\n @Override\n public Page<InT> nextPage(String nextPageLink) {\n return null;\n }\n };\n PagedListConverter<InT, OutT> converter = new PagedListConverter<InT, OutT>() {\n @Override\n public Observable<OutT> typeConvertAsync(InT inner) {\n return Observable.just(mapper.call(inner));\n }\n };\n return converter.convert(pagedList);\n }", "public static <T> Set<T> toSet(Iterator<? extends T> iterator) {\n\t\treturn Sets.newLinkedHashSet(toIterable(iterator));\n\t}", "public BlurBuilder brightness(float brightness) {\n data.preProcessors.add(new RenderscriptBrightnessProcessor(data.contextWrapper.getRenderScript(), brightness, data.contextWrapper.getResources()));\n return this;\n }", "public static int byteSizeOf(Bitmap bitmap) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {\n return bitmap.getAllocationByteCount();\n } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {\n return bitmap.getByteCount();\n } else {\n return bitmap.getRowBytes() * bitmap.getHeight();\n }\n }" ]
Iterates over all tags of current member and evaluates the template for each one. @param template The template to be evaluated @param attributes The attributes of the template tag @exception XDocletException If an error occurs @doc.tag type="block" @doc.param name="tagName" optional="false" description="The tag name." @doc.param name="paramName" optional="true" description="The parameter name."
[ "public void forAllMemberTags(String template, Properties attributes) throws XDocletException\r\n {\r\n if (getCurrentField() != null) {\r\n forAllMemberTags(template, attributes, FOR_FIELD, XDocletTagshandlerMessages.ONLY_CALL_FIELD_NOT_NULL, new String[]{\"forAllMemberTags\"});\r\n }\r\n else if (getCurrentMethod() != null) {\r\n forAllMemberTags(template, attributes, FOR_METHOD, XDocletTagshandlerMessages.ONLY_CALL_METHOD_NOT_NULL, new String[]{\"forAllMemberTags\"});\r\n }\r\n }" ]
[ "public static boolean isVector(DMatrixSparseCSC a) {\n return (a.numCols == 1 && a.numRows > 1) || (a.numRows == 1 && a.numCols>1);\n }", "public BlurBuilder brightness(float brightness) {\n data.preProcessors.add(new RenderscriptBrightnessProcessor(data.contextWrapper.getRenderScript(), brightness, data.contextWrapper.getResources()));\n return this;\n }", "public ClassDescriptor getDescriptorFor(String strClassName) throws ClassNotPersistenceCapableException\r\n {\r\n ClassDescriptor result = discoverDescriptor(strClassName);\r\n if (result == null)\r\n {\r\n throw new ClassNotPersistenceCapableException(strClassName + \" not found in OJB Repository\");\r\n }\r\n else\r\n {\r\n return result;\r\n }\r\n }", "private static int checkResult(int result)\n {\n if (exceptionsEnabled && result !=\n cudnnStatus.CUDNN_STATUS_SUCCESS)\n {\n throw new CudaException(cudnnStatus.stringFor(result));\n }\n return result;\n }", "public static String readCorrelationId(Message message) {\n if (!(message instanceof SoapMessage)) {\n return null;\n }\n String correlationId = null;\n Header hdCorrelationId = ((SoapMessage) message).getHeader(CORRELATION_ID_QNAME);\n if (hdCorrelationId != null) {\n if (hdCorrelationId.getObject() instanceof String) {\n correlationId = (String) hdCorrelationId.getObject();\n } else if (hdCorrelationId.getObject() instanceof Node) {\n Node headerNode = (Node) hdCorrelationId.getObject();\n correlationId = headerNode.getTextContent();\n } else {\n LOG.warning(\"Found CorrelationId soap header but value is not a String or a Node! Value: \"\n + hdCorrelationId.getObject().toString());\n }\n }\n return correlationId;\n }", "protected CDI11Deployment createDeployment(ServletContext context, CDI11Bootstrap bootstrap) {\n\n ImmutableSet.Builder<Metadata<Extension>> extensionsBuilder = ImmutableSet.builder();\n extensionsBuilder.addAll(bootstrap.loadExtensions(WeldResourceLoader.getClassLoader()));\n if (isDevModeEnabled) {\n extensionsBuilder.add(new MetadataImpl<Extension>(DevelopmentMode.getProbeExtension(resourceLoader), \"N/A\"));\n }\n\n final Iterable<Metadata<Extension>> extensions = extensionsBuilder.build();\n final TypeDiscoveryConfiguration typeDiscoveryConfiguration = bootstrap.startExtensions(extensions);\n final EEModuleDescriptor eeModule = new EEModuleDescriptorImpl(context.getContextPath(), ModuleType.WEB);\n\n final DiscoveryStrategy strategy = DiscoveryStrategyFactory.create(resourceLoader, bootstrap, typeDiscoveryConfiguration.getKnownBeanDefiningAnnotations(),\n Boolean.parseBoolean(context.getInitParameter(Jandex.DISABLE_JANDEX_DISCOVERY_STRATEGY)));\n\n if (Jandex.isJandexAvailable(resourceLoader)) {\n try {\n Class<? extends BeanArchiveHandler> handlerClass = Reflections.loadClass(resourceLoader, JANDEX_SERVLET_CONTEXT_BEAN_ARCHIVE_HANDLER);\n strategy.registerHandler((SecurityActions.newConstructorInstance(handlerClass, new Class<?>[] { ServletContext.class }, context)));\n } catch (Exception e) {\n throw CommonLogger.LOG.unableToInstantiate(JANDEX_SERVLET_CONTEXT_BEAN_ARCHIVE_HANDLER, Arrays.toString(new Object[] { context }), e);\n }\n } else {\n strategy.registerHandler(new ServletContextBeanArchiveHandler(context));\n }\n strategy.setScanner(new WebAppBeanArchiveScanner(resourceLoader, bootstrap, context));\n Set<WeldBeanDeploymentArchive> beanDeploymentArchives = strategy.performDiscovery();\n\n String isolation = context.getInitParameter(CONTEXT_PARAM_ARCHIVE_ISOLATION);\n\n if (isolation == null || Boolean.valueOf(isolation)) {\n CommonLogger.LOG.archiveIsolationEnabled();\n } else {\n CommonLogger.LOG.archiveIsolationDisabled();\n Set<WeldBeanDeploymentArchive> flatDeployment = new HashSet<WeldBeanDeploymentArchive>();\n flatDeployment.add(WeldBeanDeploymentArchive.merge(bootstrap, beanDeploymentArchives));\n beanDeploymentArchives = flatDeployment;\n }\n\n for (BeanDeploymentArchive archive : beanDeploymentArchives) {\n archive.getServices().add(EEModuleDescriptor.class, eeModule);\n }\n\n CDI11Deployment deployment = new WeldDeployment(resourceLoader, bootstrap, beanDeploymentArchives, extensions) {\n @Override\n protected WeldBeanDeploymentArchive createAdditionalBeanDeploymentArchive() {\n WeldBeanDeploymentArchive archive = super.createAdditionalBeanDeploymentArchive();\n archive.getServices().add(EEModuleDescriptor.class, eeModule);\n return archive;\n }\n };\n\n if (strategy.getClassFileServices() != null) {\n deployment.getServices().add(ClassFileServices.class, strategy.getClassFileServices());\n }\n return deployment;\n }", "@Override\n public ModelNode resolveValue(ExpressionResolver resolver, ModelNode value) throws OperationFailedException {\n\n // Pass non-LIST values through the superclass so it can reject weird values and, in the odd chance\n // that's how this object is set up, turn undefined into a default list value.\n ModelNode superResult = value.getType() == ModelType.LIST ? value : super.resolveValue(resolver, value);\n\n // If it's not a LIST (almost certainly UNDEFINED), then nothing more we can do\n if (superResult.getType() != ModelType.LIST) {\n return superResult;\n }\n // Resolve each element.\n // Don't mess with the original value\n ModelNode clone = superResult == value ? value.clone() : superResult;\n ModelNode result = new ModelNode();\n result.setEmptyList();\n for (ModelNode element : clone.asList()) {\n result.add(valueType.resolveValue(resolver, element));\n }\n // Validate the entire list\n getValidator().validateParameter(getName(), result);\n return result;\n }", "public static TaskField getMpxjField(int value)\n {\n TaskField result = null;\n\n if (value >= 0 && value < MPX_MPXJ_ARRAY.length)\n {\n result = MPX_MPXJ_ARRAY[value];\n }\n\n return (result);\n }", "public static ExtensibleConfigurationPersister createTransientDomainXmlConfigurationPersister(ExecutorService executorService, ExtensionRegistry extensionRegistry) {\n DomainXml domainXml = new DomainXml(Module.getBootModuleLoader(), executorService, extensionRegistry);\n ExtensibleConfigurationPersister persister = new NullConfigurationPersister(domainXml);\n extensionRegistry.setWriterRegistry(persister);\n return persister;\n }" ]
Watches specified IDs in a collection. @param ids the ids to watch. @return the stream of change events.
[ "@Override\n @SuppressWarnings(\"unchecked\")\n public Stream<ChangeEvent<DocumentT>> watch(final BsonValue... ids)\n throws InterruptedException, IOException {\n return operations.watch(\n new HashSet<>(Arrays.asList(ids)),\n false,\n documentClass\n ).execute(service);\n }" ]
[ "private Pair<Cluster, List<StoreDefinition>> getCurrentClusterState() {\n\n // Retrieve the latest cluster metadata from the existing nodes\n Versioned<Cluster> currentVersionedCluster = adminClient.rebalanceOps.getLatestCluster(Utils.nodeListToNodeIdList(Lists.newArrayList(adminClient.getAdminClientCluster()\n .getNodes())));\n Cluster cluster = currentVersionedCluster.getValue();\n List<StoreDefinition> storeDefs = adminClient.rebalanceOps.getCurrentStoreDefinitions(cluster);\n return new Pair<Cluster, List<StoreDefinition>>(cluster, storeDefs);\n }", "public void setEnable(boolean flag) {\n if (flag == mIsEnabled)\n return;\n\n mIsEnabled = flag;\n\n if (getNative() != 0)\n {\n NativeComponent.setEnable(getNative(), flag);\n }\n if (flag)\n {\n onEnable();\n }\n else\n {\n onDisable();\n }\n }", "public static String expandLine(CharSequence self, int tabStop) {\n String s = self.toString();\n int index;\n while ((index = s.indexOf('\\t')) != -1) {\n StringBuilder builder = new StringBuilder(s);\n int count = tabStop - index % tabStop;\n builder.deleteCharAt(index);\n for (int i = 0; i < count; i++) builder.insert(index, \" \");\n s = builder.toString();\n }\n return s;\n }", "public static int getScreenHeight(Context context) {\n DisplayMetrics metrics = context.getResources().getDisplayMetrics();\n return metrics.heightPixels;\n }", "public DynamicReportBuilder setTemplateFile(String path, boolean importFields, boolean importVariables, boolean importParameters, boolean importDatasets) {\n report.setTemplateFileName(path);\n report.setTemplateImportFields(importFields);\n report.setTemplateImportParameters(importParameters);\n report.setTemplateImportVariables(importVariables);\n report.setTemplateImportDatasets(importDatasets);\n return this;\n }", "public CollectionDescriptorDef getCollection(String name)\r\n {\r\n CollectionDescriptorDef collDef = null;\r\n\r\n for (Iterator it = _collections.iterator(); it.hasNext(); )\r\n {\r\n collDef = (CollectionDescriptorDef)it.next();\r\n if (collDef.getName().equals(name))\r\n {\r\n return collDef;\r\n }\r\n }\r\n return null;\r\n }", "public void loadAnimation(GVRAndroidResource animResource, String boneMap)\n {\n String filePath = animResource.getResourcePath();\n GVRContext ctx = mAvatarRoot.getGVRContext();\n GVRResourceVolume volume = new GVRResourceVolume(ctx, animResource);\n\n if (filePath.endsWith(\".bvh\"))\n {\n GVRAnimator animator = new GVRAnimator(ctx);\n animator.setName(filePath);\n try\n {\n BVHImporter importer = new BVHImporter(ctx);\n GVRSkeletonAnimation skelAnim;\n\n if (boneMap != null)\n {\n GVRSkeleton skel = importer.importSkeleton(animResource);\n skelAnim = importer.readMotion(skel);\n animator.addAnimation(skelAnim);\n\n GVRPoseMapper retargeter = new GVRPoseMapper(mSkeleton, skel, skelAnim.getDuration());\n retargeter.setBoneMap(boneMap);\n animator.addAnimation(retargeter);\n }\n else\n {\n skelAnim = importer.importAnimation(animResource, mSkeleton);\n animator.addAnimation(skelAnim);\n }\n addAnimation(animator);\n ctx.getEventManager().sendEvent(this,\n IAvatarEvents.class,\n \"onAnimationLoaded\",\n GVRAvatar.this,\n animator,\n filePath,\n null);\n }\n catch (IOException ex)\n {\n ctx.getEventManager().sendEvent(this,\n IAvatarEvents.class,\n \"onAnimationLoaded\",\n GVRAvatar.this,\n null,\n filePath,\n ex.getMessage());\n }\n }\n else\n {\n EnumSet<GVRImportSettings> settings = GVRImportSettings.getRecommendedSettingsWith(EnumSet.of(GVRImportSettings.OPTIMIZE_GRAPH, GVRImportSettings.NO_TEXTURING));\n\n GVRSceneObject animRoot = new GVRSceneObject(ctx);\n ctx.getAssetLoader().loadModel(volume, animRoot, settings, false, mLoadAnimHandler);\n }\n }", "public List<ResourceRequestType.ResourceRequestCriterion> getResourceRequestCriterion()\n {\n if (resourceRequestCriterion == null)\n {\n resourceRequestCriterion = new ArrayList<ResourceRequestType.ResourceRequestCriterion>();\n }\n return this.resourceRequestCriterion;\n }", "public GetSingleConversationOptions filters(List<String> filters) {\n if(filters.size() == 1) { //Canvas API doesn't want the [] if it is only one value\n addSingleItem(\"filter\", filters.get(0));\n } else {\n optionsMap.put(\"filter[]\", filters);\n }\n return this;\n }" ]
Adds the download button. @param view layout which displays the log file
[ "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 }" ]
[ "@Pure\n\tpublic static <T> Iterator<T> filterNull(Iterator<T> unfiltered) {\n\t\treturn Iterators.filter(unfiltered, Predicates.notNull());\n\t}", "@SuppressWarnings(\"deprecation\")\n private void cancelRequestAndWorkerOnHost(List<String> targetHosts) {\n\n List<String> validTargetHosts = new ArrayList<String>(workers.keySet());\n validTargetHosts.retainAll(targetHosts);\n logger.info(\"targetHosts for cancel: Total: {}\"\n + \" Valid in current manager with worker threads: {}\",\n targetHosts.size(), validTargetHosts.size());\n\n for (String targetHost : validTargetHosts) {\n\n ActorRef worker = workers.get(targetHost);\n\n if (worker != null && !worker.isTerminated()) {\n worker.tell(OperationWorkerMsgType.CANCEL, getSelf());\n logger.info(\"Submitted CANCEL request on Host {}\", targetHost);\n } else {\n logger.info(\n \"Did NOT Submitted \"\n + \"CANCEL request on Host {} as worker on this host is null or already killed\",\n targetHost);\n }\n\n }\n\n }", "public LinearInterpolatedTimeDiscreteProcess add(LinearInterpolatedTimeDiscreteProcess process) throws CalculationException {\n\t\tMap<Double, RandomVariable> sum = new HashMap<>();\n\n\t\tfor(double time: timeDiscretization) {\n\t\t\tsum.put(time, realizations.get(time).add(process.getProcessValue(time, 0)));\n\t\t}\n\n\t\treturn new LinearInterpolatedTimeDiscreteProcess(timeDiscretization, sum);\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 final PJsonObject optJSONObject(final String key) {\n final JSONObject val = this.obj.optJSONObject(key);\n return val != null ? new PJsonObject(this, val, key) : null;\n }", "static void sendFailedResponse(final ManagementRequestContext<RegistrationContext> context, final byte errorCode, final String message) throws IOException {\n final ManagementResponseHeader header = ManagementResponseHeader.create(context.getRequestHeader());\n final FlushableDataOutput output = context.writeMessage(header);\n try {\n // This is an error\n output.writeByte(DomainControllerProtocol.PARAM_ERROR);\n // send error code\n output.writeByte(errorCode);\n // error message\n if (message == null) {\n output.writeUTF(\"unknown error\");\n } else {\n output.writeUTF(message);\n }\n // response end\n output.writeByte(ManagementProtocol.RESPONSE_END);\n output.close();\n } finally {\n StreamUtils.safeClose(output);\n }\n }", "private String getActivityID(Task task)\n {\n String result = null;\n if (m_activityIDField != null)\n {\n Object value = task.getCachedValue(m_activityIDField);\n if (value != null)\n {\n result = value.toString();\n }\n }\n return result;\n }", "public ItemRequest<Task> dependents(String task) {\n \n String path = String.format(\"/tasks/%s/dependents\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"GET\");\n }", "public void makePickable(GVRSceneObject sceneObject) {\n try {\n GVRMeshCollider collider = new GVRMeshCollider(sceneObject.getGVRContext(), false);\n sceneObject.attachComponent(collider);\n } catch (Exception e) {\n // Possible that some objects (X3D panel nodes) are without mesh\n Log.e(Log.SUBSYSTEM.INPUT, TAG, \"makePickable(): possible that some objects (X3D panel nodes) are without mesh!\");\n }\n }" ]
Returns the matrix's rank. Automatic selection of threshold @param A Matrix. Not modified. @return The rank of the decomposed matrix.
[ "public static int rank( DMatrixRMaj A ) {\n SingularValueDecomposition_F64<DMatrixRMaj> svd = DecompositionFactory_DDRM.svd(A.numRows,A.numCols,false,true,true);\n\n if( svd.inputModified() ) {\n A = A.copy();\n }\n if( !svd.decompose(A)) {\n throw new RuntimeException(\"SVD Failed!\");\n }\n\n int N = svd.numberOfSingularValues();\n double sv[] = svd.getSingularValues();\n\n double threshold = singularThreshold(sv,N);\n int count = 0;\n for (int i = 0; i < sv.length; i++) {\n if( sv[i] >= threshold ) {\n count++;\n }\n }\n return count;\n }" ]
[ "public B importContext(AbstractContext context, boolean overwriteDuplicates){\n for (Map.Entry<String, Object> en : context.data.entrySet()) {\n if (overwriteDuplicates) {\n this.data.put(en.getKey(), en.getValue());\n }else{\n this.data.putIfAbsent(en.getKey(), en.getValue());\n }\n }\n return (B) this;\n }", "public static Properties loadProps(String filename) {\n Properties props = new Properties();\n FileInputStream fis = null;\n try {\n fis = new FileInputStream(filename);\n props.load(fis);\n return props;\n } catch (IOException ex) {\n throw new RuntimeException(ex);\n } finally {\n Closer.closeQuietly(fis);\n }\n\n }", "@GET\n @Produces(MediaType.APPLICATION_JSON)\n @Path(\"/graph/{name}/{version}\")\n public Response getModuleGraph(@PathParam(\"name\") final String moduleName,\n @PathParam(\"version\") final String moduleVersion,\n @Context final UriInfo uriInfo){\n\n LOG.info(\"Dependency Checker got a get module graph export request.\");\n\n if(moduleName == null || moduleVersion == null){\n return Response.serverError().status(HttpStatus.NOT_ACCEPTABLE_406).build();\n }\n\n final FiltersHolder filters = new FiltersHolder();\n filters.init(uriInfo.getQueryParameters());\n\n final String moduleId = DbModule.generateID(moduleName, moduleVersion);\n final AbstractGraph moduleGraph = getGraphsHandler(filters).getModuleGraph(moduleId);\n\n return Response.ok(moduleGraph).build();\n }", "public static ipset_nsip6_binding[] get(nitro_service service, String name) throws Exception{\n\t\tipset_nsip6_binding obj = new ipset_nsip6_binding();\n\t\tobj.set_name(name);\n\t\tipset_nsip6_binding response[] = (ipset_nsip6_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private long getTime(Date start1, Date end1, Date start2, Date end2)\n {\n long total = 0;\n\n if (start1 != null && end1 != null && start2 != null && end2 != null)\n {\n long start;\n long end;\n\n if (start1.getTime() < start2.getTime())\n {\n start = start2.getTime();\n }\n else\n {\n start = start1.getTime();\n }\n\n if (end1.getTime() < end2.getTime())\n {\n end = end1.getTime();\n }\n else\n {\n end = end2.getTime();\n }\n\n if (start < end)\n {\n total = end - start;\n }\n }\n\n return (total);\n }", "public Module generateBuildInfoModule(Run build, TaskListener listener, ArtifactoryConfigurator config, String buildName, String buildNumber, String timestamp) throws IOException {\n if (artifactsProps == null) {\n artifactsProps = ArrayListMultimap.create();\n }\n artifactsProps.put(\"build.name\", buildName);\n artifactsProps.put(\"build.number\", buildNumber);\n artifactsProps.put(\"build.timestamp\", timestamp);\n String artifactsPropsStr = ExtractorUtils.buildPropertiesString(artifactsProps);\n\n Properties buildInfoItemsProps = new Properties();\n buildInfoItemsProps.setProperty(\"build.name\", buildName);\n buildInfoItemsProps.setProperty(\"build.number\", buildNumber);\n buildInfoItemsProps.setProperty(\"build.timestamp\", timestamp);\n\n ArtifactoryServer server = config.getArtifactoryServer();\n CredentialsConfig preferredResolver = server.getDeployerCredentialsConfig();\n ArtifactoryDependenciesClient dependenciesClient = null;\n ArtifactoryBuildInfoClient propertyChangeClient = null;\n\n try {\n dependenciesClient = server.createArtifactoryDependenciesClient(\n preferredResolver.provideUsername(build.getParent()), preferredResolver.providePassword(build.getParent()),\n server.createProxyConfiguration(Jenkins.getInstance().proxy), listener);\n\n CredentialsConfig preferredDeployer = CredentialManager.getPreferredDeployer(config, server);\n propertyChangeClient = server.createArtifactoryClient(\n preferredDeployer.provideUsername(build.getParent()), preferredDeployer.providePassword(build.getParent()),\n server.createProxyConfiguration(Jenkins.getInstance().proxy));\n\n Module buildInfoModule = new Module();\n buildInfoModule.setId(imageTag.substring(imageTag.indexOf(\"/\") + 1));\n\n // If manifest and imagePath not found, return.\n if ((StringUtils.isEmpty(manifest) || StringUtils.isEmpty(imagePath)) && !findAndSetManifestFromArtifactory(server, dependenciesClient, listener)) {\n return buildInfoModule;\n }\n\n listener.getLogger().println(\"Fetching details of published docker layers from Artifactory...\");\n boolean includeVirtualReposSupported = propertyChangeClient.getArtifactoryVersion().isAtLeast(VIRTUAL_REPOS_SUPPORTED_VERSION);\n DockerLayers layers = createLayers(dependenciesClient, includeVirtualReposSupported);\n\n listener.getLogger().println(\"Tagging published docker layers with build properties in Artifactory...\");\n setDependenciesAndArtifacts(buildInfoModule, layers, artifactsPropsStr, buildInfoItemsProps,\n dependenciesClient, propertyChangeClient, server);\n setBuildInfoModuleProps(buildInfoModule);\n return buildInfoModule;\n } finally {\n if (dependenciesClient != null) {\n dependenciesClient.close();\n }\n if (propertyChangeClient != null) {\n propertyChangeClient.close();\n }\n }\n }", "public NodeInfo getNode(String name) {\n final URI uri = uriWithPath(\"./nodes/\" + encodePathSegment(name));\n return this.rt.getForObject(uri, NodeInfo.class);\n }", "public void write(WritableByteChannel channel) throws IOException {\n logger.debug(\"Writing> {}\", this);\n for (Field field : fields) {\n field.write(channel);\n }\n }", "public List<ConnectionInfo> getConnections() {\n final URI uri = uriWithPath(\"./connections/\");\n return Arrays.asList(this.rt.getForObject(uri, ConnectionInfo[].class));\n }" ]
Expand a macro. This will look up the macro definition from {@link #macros} map. If not found then return passed in `macro` itself, otherwise return the macro definition found. **note** if macro definition is not found and the string {@link #isMacro(String) comply to macro name convention}, then a warn level message will be logged. @param macro the macro name @return macro definition or macro itself if no definition found.
[ "public String expand(String macro) {\n if (!isMacro(macro)) {\n return macro;\n }\n String definition = macros.get(Config.canonical(macro));\n if (null == definition) {\n warn(\"possible missing definition of macro[%s]\", macro);\n }\n return null == definition ? macro : definition;\n }" ]
[ "public SignedJWT verifyToken(String jwtString) throws ParseException {\n try {\n SignedJWT jwt = SignedJWT.parse(jwtString);\n if (jwt.verify(new MACVerifier(this.jwtSharedSecret))) {\n return jwt;\n }\n return null;\n } catch (JOSEException e) {\n throw new RuntimeException(\"Error verifying JSON Web Token\", e);\n }\n }", "private static void verifyJUnit4Present() {\n try {\n Class<?> clazz = Class.forName(\"org.junit.runner.Description\");\n if (!Serializable.class.isAssignableFrom(clazz)) {\n JvmExit.halt(SlaveMain.ERR_OLD_JUNIT);\n }\n } catch (ClassNotFoundException e) {\n JvmExit.halt(SlaveMain.ERR_NO_JUNIT);\n }\n }", "private static Collection<String> addOtherClasses(Collection<String> feats, List<? extends CoreLabel> info,\r\n int loc, Clique c) {\r\n String addend = null;\r\n String pAnswer = info.get(loc - 1).get(AnswerAnnotation.class);\r\n String p2Answer = info.get(loc - 2).get(AnswerAnnotation.class);\r\n String p3Answer = info.get(loc - 3).get(AnswerAnnotation.class);\r\n String p4Answer = info.get(loc - 4).get(AnswerAnnotation.class);\r\n String p5Answer = info.get(loc - 5).get(AnswerAnnotation.class);\r\n String nAnswer = info.get(loc + 1).get(AnswerAnnotation.class);\r\n // cdm 2009: Is this really right? Do we not need to differentiate names that would collide???\r\n if (c == FeatureFactory.cliqueCpC) {\r\n addend = '|' + pAnswer;\r\n } else if (c == FeatureFactory.cliqueCp2C) {\r\n addend = '|' + p2Answer;\r\n } else if (c == FeatureFactory.cliqueCp3C) {\r\n addend = '|' + p3Answer;\r\n } else if (c == FeatureFactory.cliqueCp4C) {\r\n addend = '|' + p4Answer;\r\n } else if (c == FeatureFactory.cliqueCp5C) {\r\n addend = '|' + p5Answer;\r\n } else if (c == FeatureFactory.cliqueCpCp2C) {\r\n addend = '|' + pAnswer + '-' + p2Answer;\r\n } else if (c == FeatureFactory.cliqueCpCp2Cp3C) {\r\n addend = '|' + pAnswer + '-' + p2Answer + '-' + p3Answer;\r\n } else if (c == FeatureFactory.cliqueCpCp2Cp3Cp4C) {\r\n addend = '|' + pAnswer + '-' + p2Answer + '-' + p3Answer + '-' + p4Answer;\r\n } else if (c == FeatureFactory.cliqueCpCp2Cp3Cp4Cp5C) {\r\n addend = '|' + pAnswer + '-' + p2Answer + '-' + p3Answer + '-' + p4Answer + '-' + p5Answer;\r\n } else if (c == FeatureFactory.cliqueCnC) {\r\n addend = '|' + nAnswer;\r\n } else if (c == FeatureFactory.cliqueCpCnC) {\r\n addend = '|' + pAnswer + '-' + nAnswer;\r\n }\r\n if (addend == null) {\r\n return feats;\r\n }\r\n Collection<String> newFeats = new HashSet<String>();\r\n for (String feat : feats) {\r\n String newFeat = feat + addend;\r\n newFeats.add(newFeat);\r\n }\r\n return newFeats;\r\n }", "public static base_responses update(nitro_service client, nd6ravariables resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnd6ravariables updateresources[] = new nd6ravariables[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nd6ravariables();\n\t\t\t\tupdateresources[i].vlan = resources[i].vlan;\n\t\t\t\tupdateresources[i].ceaserouteradv = resources[i].ceaserouteradv;\n\t\t\t\tupdateresources[i].sendrouteradv = resources[i].sendrouteradv;\n\t\t\t\tupdateresources[i].srclinklayeraddroption = resources[i].srclinklayeraddroption;\n\t\t\t\tupdateresources[i].onlyunicastrtadvresponse = resources[i].onlyunicastrtadvresponse;\n\t\t\t\tupdateresources[i].managedaddrconfig = resources[i].managedaddrconfig;\n\t\t\t\tupdateresources[i].otheraddrconfig = resources[i].otheraddrconfig;\n\t\t\t\tupdateresources[i].currhoplimit = resources[i].currhoplimit;\n\t\t\t\tupdateresources[i].maxrtadvinterval = resources[i].maxrtadvinterval;\n\t\t\t\tupdateresources[i].minrtadvinterval = resources[i].minrtadvinterval;\n\t\t\t\tupdateresources[i].linkmtu = resources[i].linkmtu;\n\t\t\t\tupdateresources[i].reachabletime = resources[i].reachabletime;\n\t\t\t\tupdateresources[i].retranstime = resources[i].retranstime;\n\t\t\t\tupdateresources[i].defaultlifetime = resources[i].defaultlifetime;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<EthiopicDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<EthiopicDate>) super.localDateTime(temporal);\n }", "public EventBus emitSync(String event, Object... args) {\n return _emitWithOnceBus(eventContextSync(event, args));\n }", "public void writeFinalResults() {\n\t\tprintStatus();\n\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(\"gender-ratios.csv\"))) {\n\n\t\t\tout.print(\"Site key,pages total,pages on humans,pages on humans with gender\");\n\t\t\tfor (EntityIdValue gender : this.genderNamesList) {\n\t\t\t\tout.print(\",\" + this.genderNames.get(gender) + \" (\"\n\t\t\t\t\t\t+ gender.getId() + \")\");\n\t\t\t}\n\t\t\tout.println();\n\n\t\t\tList<SiteRecord> siteRecords = new ArrayList<>(\n\t\t\t\t\tthis.siteRecords.values());\n\t\t\tCollections.sort(siteRecords, new SiteRecordComparator());\n\t\t\tfor (SiteRecord siteRecord : siteRecords) {\n\t\t\t\tout.print(siteRecord.siteKey + \",\" + siteRecord.pageCount + \",\"\n\t\t\t\t\t\t+ siteRecord.humanPageCount + \",\"\n\t\t\t\t\t\t+ siteRecord.humanGenderPageCount);\n\n\t\t\t\tfor (EntityIdValue gender : this.genderNamesList) {\n\t\t\t\t\tif (siteRecord.genderCounts.containsKey(gender)) {\n\t\t\t\t\t\tout.print(\",\" + siteRecord.genderCounts.get(gender));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tout.print(\",0\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tout.println();\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}", "public static Cluster dropZone(Cluster intermediateCluster, int dropZoneId) {\n // Filter out nodes that don't belong to the zone being dropped\n Set<Node> survivingNodes = new HashSet<Node>();\n for(int nodeId: intermediateCluster.getNodeIds()) {\n if(intermediateCluster.getNodeById(nodeId).getZoneId() != dropZoneId) {\n survivingNodes.add(intermediateCluster.getNodeById(nodeId));\n }\n }\n\n // Filter out dropZoneId from all zones\n Set<Zone> zones = new HashSet<Zone>();\n for(int zoneId: intermediateCluster.getZoneIds()) {\n if(zoneId == dropZoneId) {\n continue;\n }\n List<Integer> proximityList = intermediateCluster.getZoneById(zoneId)\n .getProximityList();\n proximityList.remove(new Integer(dropZoneId));\n zones.add(new Zone(zoneId, proximityList));\n }\n\n return new Cluster(intermediateCluster.getName(),\n Utils.asSortedList(survivingNodes),\n Utils.asSortedList(zones));\n }", "public static final FieldType getInstance(int fieldID)\n {\n FieldType result;\n int prefix = fieldID & 0xFFFF0000;\n int index = fieldID & 0x0000FFFF;\n\n switch (prefix)\n {\n case MPPTaskField.TASK_FIELD_BASE:\n {\n result = MPPTaskField.getInstance(index);\n if (result == null)\n {\n result = getPlaceholder(TaskField.class, index);\n }\n break;\n }\n\n case MPPResourceField.RESOURCE_FIELD_BASE:\n {\n result = MPPResourceField.getInstance(index);\n if (result == null)\n {\n result = getPlaceholder(ResourceField.class, index);\n }\n break;\n }\n\n case MPPAssignmentField.ASSIGNMENT_FIELD_BASE:\n {\n result = MPPAssignmentField.getInstance(index);\n if (result == null)\n {\n result = getPlaceholder(AssignmentField.class, index);\n }\n break;\n }\n\n case MPPConstraintField.CONSTRAINT_FIELD_BASE:\n {\n result = MPPConstraintField.getInstance(index);\n if (result == null)\n {\n result = getPlaceholder(ConstraintField.class, index);\n }\n break;\n }\n\n default:\n {\n result = getPlaceholder(null, index);\n break;\n }\n }\n\n return result;\n }" ]
returns a unique String for given field. the returned uid is unique accross all tables.
[ "protected String getUniqueString(FieldDescriptor field) throws SequenceManagerException\r\n {\r\n ResultSetAndStatement rsStmt = null;\r\n String returnValue = null;\r\n try\r\n {\r\n rsStmt = getBrokerForClass().serviceJdbcAccess().executeSQL(\r\n \"select newid()\", field.getClassDescriptor(), Query.NOT_SCROLLABLE);\r\n if (rsStmt.m_rs.next())\r\n {\r\n returnValue = rsStmt.m_rs.getString(1);\r\n }\r\n else\r\n {\r\n LoggerFactory.getDefaultLogger().error(this.getClass()\r\n + \": Can't lookup new oid for field \" + field);\r\n }\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n throw new SequenceManagerException(e);\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new SequenceManagerException(e);\r\n }\r\n\r\n finally\r\n {\r\n // close the used resources\r\n if (rsStmt != null) rsStmt.close();\r\n }\r\n return returnValue;\r\n }" ]
[ "private long getTotalUploadSize() throws IOException {\n long size = 0;\n for (Map.Entry<String, File> entry : files.entrySet()) {\n size += entry.getValue().length();\n }\n\n for (Map.Entry<String, InputStream> entry : fileStreams.entrySet()) {\n size += entry.getValue().available();\n }\n return size;\n }", "private void writeExceptions(Project.Calendars.Calendar calendar, List<Project.Calendars.Calendar.WeekDays.WeekDay> dayList, List<ProjectCalendarException> exceptions)\n {\n // Always write legacy exception data:\n // Powerproject appears not to recognise new format data at all,\n // and legacy data is ignored in preference to new data post MSP 2003\n writeExceptions9(dayList, exceptions);\n\n if (m_saveVersion.getValue() > SaveVersion.Project2003.getValue())\n {\n writeExceptions12(calendar, exceptions);\n }\n }", "private static JsonObject getFieldJsonObject(Field field) {\n JsonObject fieldObj = new JsonObject();\n fieldObj.add(\"type\", field.getType());\n fieldObj.add(\"key\", field.getKey());\n fieldObj.add(\"displayName\", field.getDisplayName());\n\n String fieldDesc = field.getDescription();\n if (fieldDesc != null) {\n fieldObj.add(\"description\", field.getDescription());\n }\n\n Boolean fieldIsHidden = field.getIsHidden();\n if (fieldIsHidden != null) {\n fieldObj.add(\"hidden\", field.getIsHidden());\n }\n\n JsonArray array = new JsonArray();\n List<String> options = field.getOptions();\n if (options != null && !options.isEmpty()) {\n for (String option : options) {\n JsonObject optionObj = new JsonObject();\n optionObj.add(\"key\", option);\n\n array.add(optionObj);\n }\n fieldObj.add(\"options\", array);\n }\n\n return fieldObj;\n }", "void createDirectory(Path path) throws IOException {\n\t\tif (Files.exists(path) && Files.isDirectory(path)) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.readOnly) {\n\t\t\tthrow new FileNotFoundException(\n\t\t\t\t\t\"The requested directory \\\"\"\n\t\t\t\t\t\t\t+ path.toString()\n\t\t\t\t\t\t\t+ \"\\\" does not exist and we are in read-only mode, so it cannot be created.\");\n\t\t}\n\n\t\tFiles.createDirectory(path);\n\t}", "@SuppressWarnings(\"deprecation\")\n public BUILDER setAllowedValues(String ... allowedValues) {\n assert allowedValues!= null;\n this.allowedValues = new ModelNode[allowedValues.length];\n for (int i = 0; i < allowedValues.length; i++) {\n this.allowedValues[i] = new ModelNode(allowedValues[i]);\n }\n return (BUILDER) this;\n }", "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 }", "private GraphicsDocument createLabelDocument(StringWriter writer, LabelStyleInfo labelStyleInfo)\n\t\t\tthrows RenderException {\n\n\t\tif (TileMetadata.PARAM_SVG_RENDERER.equalsIgnoreCase(renderer)) {\n\t\t\tDefaultSvgDocument document = new DefaultSvgDocument(writer, false);\n\t\t\tdocument.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS);\n\t\t\tdocument.registerWriter(InternalTileImpl.class, new SvgLabelTileWriter(getTransformer(), labelStyleInfo,\n\t\t\t\t\tgeoService, textService));\n\t\t\treturn document;\n\t\t} else if (TileMetadata.PARAM_VML_RENDERER.equalsIgnoreCase(renderer)) {\n\t\t\tDefaultVmlDocument document = new DefaultVmlDocument(writer);\n\t\t\tint coordWidth = tile.getScreenWidth();\n\t\t\tint coordHeight = tile.getScreenHeight();\n\t\t\tdocument.registerWriter(InternalFeatureImpl.class, new VmlFeatureWriter(getTransformer(), coordWidth,\n\t\t\t\t\tcoordHeight));\n\t\t\tdocument.registerWriter(InternalTileImpl.class, new VmlLabelTileWriter(coordWidth, coordHeight,\n\t\t\t\t\tgetTransformer(), labelStyleInfo, geoService, textService));\n\t\t\tdocument.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS);\n\t\t\treturn document;\n\t\t} else {\n\t\t\tthrow new RenderException(ExceptionCode.RENDERER_TYPE_NOT_SUPPORTED, renderer);\n\t\t}\n\t}", "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 }", "static Resource getOrCreateSubDeployment(final String deploymentName, final DeploymentUnit parent) {\n final Resource root = parent.getAttachment(DEPLOYMENT_RESOURCE);\n return getOrCreate(root, PathElement.pathElement(SUBDEPLOYMENT, deploymentName));\n }" ]
Creates a timespan from a list of other timespans. @return a timespan representing the sum of all the timespans provided
[ "public static Timespan create(Timespan... timespans) {\n if (timespans == null) {\n return null;\n }\n\n if (timespans.length == 0) {\n return ZERO_MILLISECONDS;\n }\n\n Timespan res = timespans[0];\n\n for (int i = 1; i < timespans.length; i++) {\n Timespan timespan = timespans[i];\n res = res.add(timespan);\n }\n\n return res;\n }" ]
[ "public DesignDocument get(String id) {\r\n assertNotEmpty(id, \"id\");\r\n return db.find(DesignDocument.class, ensureDesignPrefix(id));\r\n }", "public void save() throws CmsException {\n\n if (hasChanges()) {\n switch (m_bundleType) {\n case PROPERTY:\n saveLocalization();\n saveToPropertyVfsBundle();\n break;\n\n case XML:\n saveLocalization();\n saveToXmlVfsBundle();\n\n break;\n\n case DESCRIPTOR:\n break;\n default:\n throw new IllegalArgumentException();\n }\n if (null != m_descFile) {\n saveToBundleDescriptor();\n }\n\n resetChanges();\n }\n\n }", "private void parseMetadataItem(Message item) {\n switch (item.getMenuItemType()) {\n case TRACK_TITLE:\n title = ((StringField) item.arguments.get(3)).getValue();\n artworkId = (int) ((NumberField) item.arguments.get(8)).getValue();\n break;\n\n case ARTIST:\n artist = buildSearchableItem(item);\n break;\n\n case ORIGINAL_ARTIST:\n originalArtist = buildSearchableItem(item);\n break;\n\n case REMIXER:\n remixer = buildSearchableItem(item);\n\n case ALBUM_TITLE:\n album = buildSearchableItem(item);\n break;\n\n case LABEL:\n label = buildSearchableItem(item);\n break;\n\n case DURATION:\n duration = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n case TEMPO:\n tempo = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n case COMMENT:\n comment = ((StringField) item.arguments.get(3)).getValue();\n break;\n\n case KEY:\n key = buildSearchableItem(item);\n break;\n\n case RATING:\n rating = (int) ((NumberField)item.arguments.get(1)).getValue();\n break;\n\n case COLOR_NONE:\n case COLOR_AQUA:\n case COLOR_BLUE:\n case COLOR_GREEN:\n case COLOR_ORANGE:\n case COLOR_PINK:\n case COLOR_PURPLE:\n case COLOR_RED:\n case COLOR_YELLOW:\n color = buildColorItem(item);\n break;\n\n case GENRE:\n genre = buildSearchableItem(item);\n break;\n\n case DATE_ADDED:\n dateAdded = ((StringField) item.arguments.get(3)).getValue();\n break;\n\n case YEAR:\n year = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n case BIT_RATE:\n bitRate = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n default:\n logger.warn(\"Ignoring track metadata item with unknown type: {}\", item);\n }\n }", "public static List<String> createBacktrace(final Throwable t) {\n final List<String> bTrace = new LinkedList<String>();\n for (final StackTraceElement ste : t.getStackTrace()) {\n bTrace.add(BT_PREFIX + ste.toString());\n }\n if (t.getCause() != null) {\n addCauseToBacktrace(t.getCause(), bTrace);\n }\n return bTrace;\n }", "private void deliverDeviceUpdate(final DeviceUpdate update) {\n for (DeviceUpdateListener listener : getUpdateListeners()) {\n try {\n listener.received(update);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering device update to listener\", t);\n }\n }\n }", "public void addBasicSentence(MtasCQLParserBasicSentenceCondition s)\n throws ParseException {\n if (!simplified) {\n List<MtasCQLParserBasicSentencePartCondition> newWordList = s\n .getPartList();\n partList.addAll(newWordList);\n } else {\n throw new ParseException(\"already simplified\");\n }\n }", "private boolean isDebug(CmsObject cms, CmsSolrQuery query) {\r\n\r\n String[] debugSecretValues = query.remove(REQUEST_PARAM_DEBUG_SECRET);\r\n String debugSecret = (debugSecretValues == null) || (debugSecretValues.length < 1)\r\n ? null\r\n : debugSecretValues[0];\r\n if ((null != debugSecret) && !debugSecret.trim().isEmpty() && (null != m_handlerDebugSecretFile)) {\r\n try {\r\n CmsFile secretFile = cms.readFile(m_handlerDebugSecretFile);\r\n String secret = new String(secretFile.getContents(), CmsFileUtil.getEncoding(cms, secretFile));\r\n return secret.trim().equals(debugSecret.trim());\r\n } catch (Exception e) {\r\n LOG.info(\r\n \"Failed to read secret file for index \\\"\"\r\n + getName()\r\n + \"\\\" at path \\\"\"\r\n + m_handlerDebugSecretFile\r\n + \"\\\".\");\r\n }\r\n }\r\n return false;\r\n }", "private String listToCSV(List<String> list) {\n String csvStr = \"\";\n for (String item : list) {\n csvStr += \",\" + item;\n }\n\n return csvStr.length() > 1 ? csvStr.substring(1) : csvStr;\n }", "public static BoxItem.Info getSharedItem(BoxAPIConnection api, String sharedLink, String password) {\n BoxAPIConnection newAPI = new SharedLinkAPIConnection(api, sharedLink, password);\n URL url = SHARED_ITEM_URL_TEMPLATE.build(newAPI.getBaseURL());\n BoxAPIRequest request = new BoxAPIRequest(newAPI, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject json = JsonObject.readFrom(response.getJSON());\n return (BoxItem.Info) BoxResource.parseInfo(newAPI, json);\n }" ]
Handle a change in the weeks of month. @param week the changed weeks checkbox's internal value. @param value the new value of the changed checkbox.
[ "public void weeksChange(String week, Boolean value) {\n\n final WeekOfMonth changedWeek = WeekOfMonth.valueOf(week);\n boolean newValue = (null != value) && value.booleanValue();\n boolean currentValue = m_model.getWeeksOfMonth().contains(changedWeek);\n if (newValue != currentValue) {\n if (newValue) {\n setPatternScheme(true, false);\n m_model.addWeekOfMonth(changedWeek);\n onValueChange();\n } else {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.removeWeekOfMonth(changedWeek);\n onValueChange();\n }\n });\n }\n }\n }" ]
[ "public History[] refreshHistory(int limit, int offset) throws Exception {\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"limit\", String.valueOf(limit)),\n new BasicNameValuePair(\"offset\", String.valueOf(offset))\n };\n return constructHistory(params);\n }", "public static BoxLegalHoldAssignment.Info create(BoxAPIConnection api,\n String policyID, String resourceType, String resourceID) {\n URL url = ASSIGNMENTS_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n\n JsonObject requestJSON = new JsonObject()\n .add(\"policy_id\", policyID)\n .add(\"assign_to\", new JsonObject()\n .add(\"type\", resourceType)\n .add(\"id\", resourceID));\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n BoxLegalHoldAssignment createdAssignment = new BoxLegalHoldAssignment(api, responseJSON.get(\"id\").asString());\n return createdAssignment.new Info(responseJSON);\n }", "public void recordServerGroupResult(final String serverGroup, final boolean failed) {\n\n synchronized (this) {\n if (groups.contains(serverGroup)) {\n responseCount++;\n if (failed) {\n this.failed = true;\n }\n DomainControllerLogger.HOST_CONTROLLER_LOGGER.tracef(\"Recorded group result for '%s': failed = %s\",\n serverGroup, failed);\n notifyAll();\n }\n else {\n throw DomainControllerLogger.HOST_CONTROLLER_LOGGER.unknownServerGroup(serverGroup);\n }\n }\n }", "@Override\n public void addVariable(String varName, Object value) {\n synchronized (mGlobalVariables) {\n mGlobalVariables.put(varName, value);\n }\n refreshGlobalBindings();\n }", "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}", "private Map<String, Integer> runSampling(\n final ProctorContext proctorContext,\n final Set<String> targetTestNames,\n final TestType testType,\n final int determinationsToRun\n ) {\n final Set<String> targetTestGroups = getTargetTestGroups(targetTestNames);\n final Map<String, Integer> testGroupToOccurrences = Maps.newTreeMap();\n for (final String testGroup : targetTestGroups) {\n testGroupToOccurrences.put(testGroup, 0);\n }\n\n for (int i = 0; i < determinationsToRun; ++i) {\n final Identifiers identifiers = TestType.RANDOM.equals(testType)\n ? new Identifiers(Collections.<TestType, String>emptyMap(), /* randomEnabled */ true)\n : Identifiers.of(testType, Long.toString(random.nextLong()));\n final AbstractGroups groups = supplier.getRandomGroups(proctorContext, identifiers);\n for (final Entry<String, TestBucket> e : groups.getProctorResult().getBuckets().entrySet()) {\n final String testName = e.getKey();\n if (targetTestNames.contains(testName)) {\n final int group = e.getValue().getValue();\n final String testGroup = testName + group;\n testGroupToOccurrences.put(testGroup, testGroupToOccurrences.get(testGroup) + 1);\n }\n }\n }\n\n return testGroupToOccurrences;\n }", "public void render(OutputStream outputStream, Format format, int dpi) throws PrintingException {\n\t\ttry {\n\t\t\tif (baos == null) {\n\t\t\t\tprepare();\n\t\t\t}\n\t\t\twriteDocument(outputStream, format, dpi);\n\t\t} catch (Exception e) { // NOSONAR\n\t\t\tthrow new PrintingException(e, PrintingException.DOCUMENT_RENDER_PROBLEM);\n\t\t}\n\t}", "public static base_responses save(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 saveresources[] = new cachecontentgroup[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tsaveresources[i] = new cachecontentgroup();\n\t\t\t\tsaveresources[i].name = resources[i].name;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, saveresources,\"save\");\n\t\t}\n\t\treturn result;\n\t}", "public IndexDef getIndex(String name)\r\n {\r\n String realName = (name == null ? \"\" : name);\r\n IndexDef def = null;\r\n\r\n for (Iterator it = getIndices(); it.hasNext();)\r\n {\r\n def = (IndexDef)it.next();\r\n if (def.getName().equals(realName))\r\n {\r\n return def;\r\n }\r\n }\r\n return null;\r\n }" ]