query
stringlengths
7
3.3k
positive
sequencelengths
1
1
negative
sequencelengths
9
9
Add a post-effect to this camera's render chain. Post-effects are GL shaders, applied to the texture (hardware bitmap) containing the rendered scene graph. Each post-effect combines a shader selector with a set of parameters: This lets you pass different parameters to the shaders for each eye. @param postEffectData Post-effect to append to this camera's render chain
[ "public void addPostEffect(GVRMaterial postEffectData) {\n GVRContext ctx = getGVRContext();\n\n if (mPostEffects == null)\n {\n mPostEffects = new GVRRenderData(ctx, postEffectData);\n GVRMesh dummyMesh = new GVRMesh(getGVRContext(),\"float3 a_position float2 a_texcoord\");\n mPostEffects.setMesh(dummyMesh);\n NativeCamera.setPostEffect(getNative(), mPostEffects.getNative());\n mPostEffects.setCullFace(GVRRenderPass.GVRCullFaceEnum.None);\n }\n else\n {\n GVRRenderPass rpass = new GVRRenderPass(ctx, postEffectData);\n rpass.setCullFace(GVRRenderPass.GVRCullFaceEnum.None);\n mPostEffects.addPass(rpass);\n }\n }" ]
[ "public static JmsDestinationType getTypeFromClass(String aClass)\n {\n if (StringUtils.equals(aClass, \"javax.jms.Queue\") || StringUtils.equals(aClass, \"javax.jms.QueueConnectionFactory\"))\n {\n return JmsDestinationType.QUEUE;\n }\n else if (StringUtils.equals(aClass, \"javax.jms.Topic\") || StringUtils.equals(aClass, \"javax.jms.TopicConnectionFactory\"))\n {\n return JmsDestinationType.TOPIC;\n }\n else\n {\n return null;\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 }", "public static BoxTermsOfService.Info create(BoxAPIConnection api,\n BoxTermsOfService.TermsOfServiceStatus termsOfServiceStatus,\n BoxTermsOfService.TermsOfServiceType termsOfServiceType, String text) {\n URL url = ALL_TERMS_OF_SERVICES_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n JsonObject requestJSON = new JsonObject()\n .add(\"status\", termsOfServiceStatus.toString())\n .add(\"tos_type\", termsOfServiceType.toString())\n .add(\"text\", text);\n\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n BoxTermsOfService createdTermsOfServices = new BoxTermsOfService(api, responseJSON.get(\"id\").asString());\n\n return createdTermsOfServices.new Info(responseJSON);\n }", "public static <T_Result, T_Source> List<T_Result> map(Collection<T_Source> source,\n Mapper<T_Result, T_Source> mapper) {\n List<T_Result> result = new LinkedList<T_Result>();\n for (T_Source element : source) {\n result.add(mapper.map(element));\n }\n return result;\n }", "@SuppressWarnings(\"deprecation\")\n @Deprecated\n public final void validateAndSet(ModelNode operationObject, final ModelNode model) throws OperationFailedException {\n validateOperation(operationObject);\n for (AttributeDefinition ad : this.parameters) {\n ad.validateAndSet(operationObject, model);\n }\n }", "private AssignmentField selectField(AssignmentField[] fields, int index)\n {\n if (index < 1 || index > fields.length)\n {\n throw new IllegalArgumentException(index + \" is not a valid field index\");\n }\n return (fields[index - 1]);\n }", "protected List<Reference> mergeReferences(\n\t\t\tList<? extends Reference> references1,\n\t\t\tList<? extends Reference> references2) {\n\t\tList<Reference> result = new ArrayList<>();\n\t\tfor (Reference reference : references1) {\n\t\t\taddBestReferenceToList(reference, result);\n\t\t}\n\t\tfor (Reference reference : references2) {\n\t\t\taddBestReferenceToList(reference, result);\n\t\t}\n\t\treturn result;\n\t}", "@Override\n protected void reset() {\n super.reset();\n mapClassesToNamedBoundProviders.clear();\n mapClassesToUnNamedBoundProviders.clear();\n hasTestModules = false;\n installBindingForScope();\n }", "static GVRCollider lookup(long nativePointer)\n {\n synchronized (sColliders)\n {\n WeakReference<GVRCollider> weakReference = sColliders.get(nativePointer);\n return weakReference == null ? null : weakReference.get();\n }\n }" ]
Typically this is transparently handled by using the Protostream codecs but be aware of it when bypassing Protostream.
[ "public void deploySchema(String generatedProtobufName, RemoteCache<String, String> protobufCache, SchemaCapture schemaCapture, SchemaOverride schemaOverrideService,\n\t\t\tURL schemaOverrideResource) {\n\t\t// user defined schema\n\t\tif ( schemaOverrideService != null || schemaOverrideResource != null ) {\n\t\t\tcachedSchema = new SchemaValidator( this, schemaOverrideService, schemaOverrideResource, generatedProtobufName ).provideSchema();\n\t\t}\n\n\t\t// or generate them\n\t\tgenerateProtoschema();\n\n\t\ttry {\n\t\t\tprotobufCache.put( generatedProtobufName, cachedSchema );\n\t\t\tString errors = protobufCache.get( generatedProtobufName + \".errors\" );\n\t\t\tif ( errors != null ) {\n\t\t\t\tthrow LOG.errorAtSchemaDeploy( generatedProtobufName, errors );\n\t\t\t}\n\t\t\tLOG.successfulSchemaDeploy( generatedProtobufName );\n\t\t}\n\t\tcatch (HotRodClientException hrce) {\n\t\t\tthrow LOG.errorAtSchemaDeploy( generatedProtobufName, hrce );\n\t\t}\n\t\tif ( schemaCapture != null ) {\n\t\t\tschemaCapture.put( generatedProtobufName, cachedSchema );\n\t\t}\n\t}" ]
[ "private String writeSchemata(File dir) throws IOException\r\n {\r\n writeCompressedTexts(dir, _torqueSchemata);\r\n\r\n StringBuffer includes = new StringBuffer();\r\n\r\n for (Iterator it = _torqueSchemata.keySet().iterator(); it.hasNext();)\r\n {\r\n includes.append((String)it.next());\r\n if (it.hasNext())\r\n {\r\n includes.append(\",\");\r\n }\r\n }\r\n return includes.toString();\r\n }", "private byte[] getBytes(String value, boolean unicode)\n {\n byte[] result;\n if (unicode)\n {\n int start = 0;\n // Get the bytes in UTF-16\n byte[] bytes;\n\n try\n {\n bytes = value.getBytes(\"UTF-16\");\n }\n catch (UnsupportedEncodingException e)\n {\n bytes = value.getBytes();\n }\n\n if (bytes.length > 2 && bytes[0] == -2 && bytes[1] == -1)\n {\n // Skip the unicode identifier\n start = 2;\n }\n result = new byte[bytes.length - start];\n for (int loop = start; loop < bytes.length - 1; loop += 2)\n {\n // Swap the order here\n result[loop - start] = bytes[loop + 1];\n result[loop + 1 - start] = bytes[loop];\n }\n }\n else\n {\n result = new byte[value.length() + 1];\n System.arraycopy(value.getBytes(), 0, result, 0, value.length());\n }\n return (result);\n }", "public static PipelineConfiguration.Builder parse(ModelNode json) {\n ModelNode analyzerIncludeNode = json.get(\"analyzers\").get(\"include\");\n ModelNode analyzerExcludeNode = json.get(\"analyzers\").get(\"exclude\");\n ModelNode filterIncludeNode = json.get(\"filters\").get(\"include\");\n ModelNode filterExcludeNode = json.get(\"filters\").get(\"exclude\");\n ModelNode transformIncludeNode = json.get(\"transforms\").get(\"include\");\n ModelNode transformExcludeNode = json.get(\"transforms\").get(\"exclude\");\n ModelNode reporterIncludeNode = json.get(\"reporters\").get(\"include\");\n ModelNode reporterExcludeNode = json.get(\"reporters\").get(\"exclude\");\n\n return builder()\n .withTransformationBlocks(json.get(\"transformBlocks\"))\n .withAnalyzerExtensionIdsInclude(asStringList(analyzerIncludeNode))\n .withAnalyzerExtensionIdsExclude(asStringList(analyzerExcludeNode))\n .withFilterExtensionIdsInclude(asStringList(filterIncludeNode))\n .withFilterExtensionIdsExclude(asStringList(filterExcludeNode))\n .withTransformExtensionIdsInclude(asStringList(transformIncludeNode))\n .withTransformExtensionIdsExclude(asStringList(transformExcludeNode))\n .withReporterExtensionIdsInclude(asStringList(reporterIncludeNode))\n .withReporterExtensionIdsExclude(asStringList(reporterExcludeNode));\n }", "private String searchForPersistentSubType(XClass type)\r\n {\r\n ArrayList queue = new ArrayList();\r\n XClass subType;\r\n\r\n queue.add(type);\r\n while (!queue.isEmpty())\r\n {\r\n subType = (XClass)queue.get(0);\r\n queue.remove(0);\r\n if (_model.hasClass(subType.getQualifiedName()))\r\n {\r\n return subType.getQualifiedName();\r\n }\r\n addDirectSubTypes(subType, queue);\r\n }\r\n return null;\r\n }", "public boolean isEUI64(boolean partial) {\n\t\tint segmentCount = getSegmentCount();\n\t\tint endIndex = addressSegmentIndex + segmentCount;\n\t\tif(addressSegmentIndex <= 5) {\n\t\t\tif(endIndex > 6) {\n\t\t\t\tint index3 = 5 - addressSegmentIndex;\n\t\t\t\tIPv6AddressSegment seg3 = getSegment(index3);\n\t\t\t\tIPv6AddressSegment seg4 = getSegment(index3 + 1);\n\t\t\t\treturn seg4.matchesWithMask(0xfe00, 0xff00) && seg3.matchesWithMask(0xff, 0xff);\n\t\t\t} else if(partial && endIndex == 6) {\n\t\t\t\tIPv6AddressSegment seg3 = getSegment(5 - addressSegmentIndex);\n\t\t\t\treturn seg3.matchesWithMask(0xff, 0xff);\n\t\t\t}\n\t\t} else if(partial && addressSegmentIndex == 6 && endIndex > 6) {\n\t\t\tIPv6AddressSegment seg4 = getSegment(6 - addressSegmentIndex);\n\t\t\treturn seg4.matchesWithMask(0xfe00, 0xff00);\n\t\t}\n\t\treturn partial;\n\t}", "public void _solveVectorInternal( double []vv )\n {\n // Solve L*Y = B\n int ii = 0;\n\n for( int i = 0; i < n; i++ ) {\n int ip = indx[i];\n double sum = vv[ip];\n vv[ip] = vv[i];\n if( ii != 0 ) {\n// for( int j = ii-1; j < i; j++ )\n// sum -= dataLU[i* n +j]*vv[j];\n int index = i*n + ii-1;\n for( int j = ii-1; j < i; j++ )\n sum -= dataLU[index++]*vv[j];\n } else if( sum != 0.0 ) {\n ii=i+1;\n }\n vv[i] = sum;\n }\n\n // Solve U*X = Y;\n TriangularSolver_DDRM.solveU(dataLU,vv,n);\n }", "public static base_response unset(nitro_service client, snmpoption resource, String[] args) throws Exception{\n\t\tsnmpoption unsetresource = new snmpoption();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public static appfwprofile_stats[] get(nitro_service service) throws Exception{\n\t\tappfwprofile_stats obj = new appfwprofile_stats();\n\t\tappfwprofile_stats[] response = (appfwprofile_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}", "public boolean perform(Run<?, ?> build, Launcher launcher, TaskListener listener, EnvVars env, FilePath workDir, FilePath tempDir)\n throws InterruptedException, IOException {\n listener.getLogger().println(\"Jenkins Artifactory Plugin version: \" + ActionableHelper.getArtifactoryPluginVersion());\n FilePath mavenHome = getMavenHome(listener, env, launcher);\n\n if (!mavenHome.exists()) {\n listener.getLogger().println(\"Couldn't find Maven home at \" + mavenHome.getRemote() + \" on agent \" + Utils.getAgentName(workDir) +\n \". This could be because this build is running inside a Docker container.\");\n }\n ArgumentListBuilder cmdLine = buildMavenCmdLine(build, listener, env, launcher, mavenHome, workDir, tempDir);\n String[] cmds = cmdLine.toCommandArray();\n return RunMaven(build, launcher, listener, env, workDir, cmds);\n }" ]
Look up all recorded playback state information. @return the playback state recorded for any player @since 0.5.0
[ "public Set<PlaybackState> getPlaybackState() {\n Set<PlaybackState> result = new HashSet<PlaybackState>(playbackStateMap.values());\n return Collections.unmodifiableSet(result);\n }" ]
[ "public void loadModel(GVRAndroidResource avatarResource)\n {\n EnumSet<GVRImportSettings> settings = GVRImportSettings.getRecommendedSettingsWith(EnumSet.of(GVRImportSettings.OPTIMIZE_GRAPH, GVRImportSettings.NO_ANIMATION));\n GVRContext ctx = mAvatarRoot.getGVRContext();\n GVRResourceVolume volume = new GVRResourceVolume(ctx, avatarResource);\n GVRSceneObject modelRoot = new GVRSceneObject(ctx);\n\n mAvatarRoot.addChildObject(modelRoot);\n ctx.getAssetLoader().loadModel(volume, modelRoot, settings, false, mLoadModelHandler);\n }", "public static void finishThread(){\r\n //--Create Task\r\n final long threadId = Thread.currentThread().getId();\r\n Runnable finish = new Runnable(){\r\n public void run(){\r\n releaseThreadControl(threadId);\r\n }\r\n };\r\n //--Run Task\r\n if(isThreaded){\r\n //(case: multithreaded)\r\n attemptThreadControl( threadId, finish );\r\n } else {\r\n //(case: no threading)\r\n throw new IllegalStateException(\"finishThreads() called outside of threaded environment\");\r\n }\r\n }", "private boolean includeDocument(ItemDocument itemDocument) {\n\t\tfor (StatementGroup sg : itemDocument.getStatementGroups()) {\n\t\t\t// \"P19\" is \"place of birth\" on Wikidata\n\t\t\tif (!\"P19\".equals(sg.getProperty().getId())) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (Statement s : sg) {\n\t\t\t\tif (s.getMainSnak() instanceof ValueSnak) {\n\t\t\t\t\tValue v = s.getValue();\n\t\t\t\t\t// \"Q1731\" is \"Dresden\" on Wikidata\n\t\t\t\t\tif (v instanceof ItemIdValue\n\t\t\t\t\t\t\t&& \"Q1731\".equals(((ItemIdValue) v).getId())) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "public int size(final K1 firstKey) {\n\t\t// existence check on inner map\n\t\tfinal HashMap<K2, HashMap<K3, V>> innerMap = map.get(firstKey);\n\t\tif( innerMap == null ) {\n\t\t\treturn 0;\n\t\t}\n\t\treturn innerMap.size();\n\t}", "private boolean activityIsStartMilestone(Activity activity)\n {\n String type = activity.getType();\n return type != null && type.indexOf(\"StartMilestone\") != -1;\n }", "public static base_response update(nitro_service client, sslparameter resource) throws Exception {\n\t\tsslparameter updateresource = new sslparameter();\n\t\tupdateresource.quantumsize = resource.quantumsize;\n\t\tupdateresource.crlmemorysizemb = resource.crlmemorysizemb;\n\t\tupdateresource.strictcachecks = resource.strictcachecks;\n\t\tupdateresource.ssltriggertimeout = resource.ssltriggertimeout;\n\t\tupdateresource.sendclosenotify = resource.sendclosenotify;\n\t\tupdateresource.encrypttriggerpktcount = resource.encrypttriggerpktcount;\n\t\tupdateresource.denysslreneg = resource.denysslreneg;\n\t\tupdateresource.insertionencoding = resource.insertionencoding;\n\t\tupdateresource.ocspcachesize = resource.ocspcachesize;\n\t\tupdateresource.pushflag = resource.pushflag;\n\t\tupdateresource.dropreqwithnohostheader = resource.dropreqwithnohostheader;\n\t\tupdateresource.pushenctriggertimeout = resource.pushenctriggertimeout;\n\t\tupdateresource.undefactioncontrol = resource.undefactioncontrol;\n\t\tupdateresource.undefactiondata = resource.undefactiondata;\n\t\treturn updateresource.update_resource(client);\n\t}", "@Override\n public void setActive(boolean active) {\n this.active = active;\n\n if (parent != null) {\n fireCollapsibleHandler();\n removeStyleName(CssName.ACTIVE);\n if (header != null) {\n header.removeStyleName(CssName.ACTIVE);\n }\n if (active) {\n if (parent != null && parent.isAccordion()) {\n parent.clearActive();\n }\n addStyleName(CssName.ACTIVE);\n\n if (header != null) {\n header.addStyleName(CssName.ACTIVE);\n }\n }\n\n if (body != null) {\n body.setDisplay(active ? Display.BLOCK : Display.NONE);\n }\n } else {\n GWT.log(\"Please make sure that the Collapsible parent is attached or existed.\", new IllegalStateException());\n }\n }", "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 }", "public List<String> invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {\n MavenProject mavenProject = getMavenProject(f.getAbsolutePath());\n return mavenProject.getModel().getModules();\n }" ]
This adds database table configurations to the internal cache which can be used to speed up DAO construction. This is especially true of Android and other mobile platforms.
[ "public static synchronized void addCachedDatabaseConfigs(Collection<DatabaseTableConfig<?>> configs) {\n\t\tMap<Class<?>, DatabaseTableConfig<?>> newMap;\n\t\tif (configMap == null) {\n\t\t\tnewMap = new HashMap<Class<?>, DatabaseTableConfig<?>>();\n\t\t} else {\n\t\t\tnewMap = new HashMap<Class<?>, DatabaseTableConfig<?>>(configMap);\n\t\t}\n\t\tfor (DatabaseTableConfig<?> config : configs) {\n\t\t\tnewMap.put(config.getDataClass(), config);\n\t\t\tlogger.info(\"Loaded configuration for {}\", config.getDataClass());\n\t\t}\n\t\tconfigMap = newMap;\n\t}" ]
[ "public static DMatrixRMaj insideSpan(DMatrixRMaj[] span , double min , double max , Random rand ) {\n DMatrixRMaj A = new DMatrixRMaj(span.length,1);\n\n DMatrixRMaj B = new DMatrixRMaj(span[0].getNumElements(),1);\n\n for( int i = 0; i < span.length; i++ ) {\n B.set(span[i]);\n double val = rand.nextDouble()*(max-min)+min;\n CommonOps_DDRM.scale(val,B);\n\n CommonOps_DDRM.add(A,B,A);\n\n }\n\n return A;\n }", "public static void doPublish(final Jedis jedis, final String namespace, final String channel, final String jobJson) {\n jedis.publish(JesqueUtils.createKey(namespace, CHANNEL, channel), jobJson);\n }", "private static List<Path> expandMultiAppInputDirs(List<Path> input)\n {\n List<Path> expanded = new LinkedList<>();\n for (Path path : input)\n {\n if (Files.isRegularFile(path))\n {\n expanded.add(path);\n continue;\n }\n if (!Files.isDirectory(path))\n {\n String pathString = (path == null) ? \"\" : path.toString(); \n log.warning(\"Neither a file or directory found in input: \" + pathString);\n continue;\n }\n\n try\n {\n try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path))\n {\n for (Path subpath : directoryStream)\n {\n\n if (isJavaArchive(subpath))\n {\n expanded.add(subpath);\n }\n }\n }\n }\n catch (IOException e)\n {\n throw new WindupException(\"Failed to read directory contents of: \" + path);\n }\n }\n return expanded;\n }", "public static String readTextFile(InputStream inputStream) {\n InputStreamReader streamReader = new InputStreamReader(inputStream);\n return readTextFile(streamReader);\n }", "public com.groupon.odo.proxylib.models.Method getMethodForOverrideId(int overrideId) {\n com.groupon.odo.proxylib.models.Method method = null;\n\n // special case for IDs < 0\n if (overrideId < 0) {\n method = new com.groupon.odo.proxylib.models.Method();\n method.setId(overrideId);\n\n if (method.getId() == Constants.PLUGIN_RESPONSE_OVERRIDE_CUSTOM ||\n method.getId() == Constants.PLUGIN_RESPONSE_HEADER_OVERRIDE_ADD ||\n method.getId() == Constants.PLUGIN_RESPONSE_HEADER_OVERRIDE_REMOVE) {\n method.setMethodType(Constants.PLUGIN_TYPE_RESPONSE_OVERRIDE);\n } else {\n method.setMethodType(Constants.PLUGIN_TYPE_REQUEST_OVERRIDE);\n }\n } else {\n // get method information from the database\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_OVERRIDE +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n queryStatement.setInt(1, overrideId);\n results = queryStatement.executeQuery();\n\n if (results.next()) {\n method = new com.groupon.odo.proxylib.models.Method();\n method.setClassName(results.getString(Constants.OVERRIDE_CLASS_NAME));\n method.setMethodName(results.getString(Constants.OVERRIDE_METHOD_NAME));\n }\n } catch (SQLException e) {\n e.printStackTrace();\n return null;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n // if method is still null then just return\n if (method == null) {\n return method;\n }\n\n // now get the rest of the data from the plugin manager\n // this gets all of the actual method data\n try {\n method = PluginManager.getInstance().getMethod(method.getClassName(), method.getMethodName());\n method.setId(overrideId);\n } catch (Exception e) {\n // there was some problem.. return null\n return null;\n }\n }\n\n return method;\n }", "private 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 }", "private List<String> processAllListeners(View rootView) {\n List<String> refinementAttributes = new ArrayList<>();\n\n // Register any AlgoliaResultsListener (unless it has a different variant than searcher)\n final List<AlgoliaResultsListener> resultListeners = LayoutViews.findByClass((ViewGroup) rootView, AlgoliaResultsListener.class);\n if (resultListeners.isEmpty()) {\n throw new IllegalStateException(Errors.LAYOUT_MISSING_RESULT_LISTENER);\n }\n for (AlgoliaResultsListener listener : resultListeners) {\n if (!this.resultListeners.contains(listener)) {\n final String variant = BindingHelper.getVariantForView((View) listener);\n if (variant == null || searcher.variant.equals(variant)) {\n this.resultListeners.add(listener);\n searcher.registerResultListener(listener);\n prepareWidget(listener, refinementAttributes);\n }\n }\n }\n\n // Register any AlgoliaErrorListener (unless it has a different variant than searcher)\n final List<AlgoliaErrorListener> errorListeners = LayoutViews.findByClass((ViewGroup) rootView, AlgoliaErrorListener.class);\n for (AlgoliaErrorListener listener : errorListeners) {\n if (!this.errorListeners.contains(listener)) {\n final String variant = BindingHelper.getVariantForView((View) listener);\n if (variant == null || searcher.variant.equals(variant)) {\n this.errorListeners.add(listener);\n }\n }\n searcher.registerErrorListener(listener);\n prepareWidget(listener, refinementAttributes);\n }\n\n // Register any AlgoliaSearcherListener (unless it has a different variant than searcher)\n final List<AlgoliaSearcherListener> searcherListeners = LayoutViews.findByClass((ViewGroup) rootView, AlgoliaSearcherListener.class);\n for (AlgoliaSearcherListener listener : searcherListeners) {\n final String variant = BindingHelper.getVariantForView((View) listener);\n if (variant == null || searcher.variant.equals(variant)) {\n listener.initWithSearcher(searcher);\n prepareWidget(listener, refinementAttributes);\n }\n }\n\n return refinementAttributes;\n }", "public byte[] keyToStorageFormat(byte[] key) {\n\n switch(getReadOnlyStorageFormat()) {\n case READONLY_V0:\n case READONLY_V1:\n return ByteUtils.md5(key);\n case READONLY_V2:\n return ByteUtils.copy(ByteUtils.md5(key), 0, 2 * ByteUtils.SIZE_OF_INT);\n default:\n throw new VoldemortException(\"Unknown read-only storage format\");\n }\n }", "public void addColumnIsNull(String column)\r\n {\r\n\t\t// PAW\r\n\t\t//SelectionCriteria c = ValueCriteria.buildNullCriteria(column, getAlias());\r\n\t\tSelectionCriteria c = ValueCriteria.buildNullCriteria(column, getUserAlias(column));\r\n c.setTranslateAttribute(false);\r\n addSelectionCriteria(c);\r\n }" ]
Use this API to fetch the statistics of all rnat_stats resources that are configured on netscaler.
[ "public static rnat_stats get(nitro_service service) throws Exception{\n\t\trnat_stats obj = new rnat_stats();\n\t\trnat_stats[] response = (rnat_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}" ]
[ "public static <K, V> QueuedKeyedResourcePool<K, V> create(ResourceFactory<K, V> factory) {\n return create(factory, new ResourcePoolConfig());\n }", "public List<GanttDesignerRemark.Task> getTask()\n {\n if (task == null)\n {\n task = new ArrayList<GanttDesignerRemark.Task>();\n }\n return this.task;\n }", "protected <T, A> ActiveOperation<T, A> getActiveOperation(final ManagementRequestHeader header) {\n return getActiveOperation(header.getBatchId());\n }", "public List<LogSegment> trunc(int newStart) {\n if (newStart < 0) {\n throw new IllegalArgumentException(\"Starting index must be positive.\");\n }\n while (true) {\n List<LogSegment> curr = contents.get();\n int newLength = Math.max(curr.size() - newStart, 0);\n List<LogSegment> updatedList = new ArrayList<LogSegment>(curr.subList(Math.min(newStart, curr.size() - 1),\n curr.size()));\n if (contents.compareAndSet(curr, updatedList)) {\n return curr.subList(0, curr.size() - newLength);\n }\n }\n }", "public static String getStatementUri(Statement statement) {\n\t\tint i = statement.getStatementId().indexOf('$') + 1;\n\t\treturn PREFIX_WIKIDATA_STATEMENT\n\t\t\t\t+ statement.getSubject().getId() + \"-\"\n\t\t\t\t+ statement.getStatementId().substring(i);\n\t}", "public void afterMaterialization(IndirectionHandler handler, Object materializedObject)\r\n {\r\n try\r\n {\r\n Identity oid = handler.getIdentity();\r\n if (log.isDebugEnabled())\r\n log.debug(\"deferred registration: \" + oid);\r\n if(!isOpen())\r\n {\r\n log.error(\"Proxy object materialization outside of a running tx, obj=\" + oid);\r\n try{throw new Exception(\"Proxy object materialization outside of a running tx, obj=\" + oid);}catch(Exception e)\r\n {\r\n e.printStackTrace();\r\n }\r\n }\r\n ClassDescriptor cld = getBroker().getClassDescriptor(materializedObject.getClass());\r\n RuntimeObject rt = new RuntimeObject(materializedObject, oid, cld, false, false);\r\n lockAndRegister(rt, Transaction.READ, isImplicitLocking(), getRegistrationList());\r\n }\r\n catch (Throwable t)\r\n {\r\n log.error(\"Register materialized object with this tx failed\", t);\r\n throw new LockNotGrantedException(t.getMessage());\r\n }\r\n unregisterFromIndirectionHandler(handler);\r\n }", "public void performImplicitSingleStep(double scale , double lambda , boolean byAngle) {\n createBulge(x1,lambda,scale,byAngle);\n\n for( int i = x1; i < x2-1 && bulge != 0.0; i++ ) {\n removeBulgeLeft(i,true);\n if( bulge == 0 )\n break;\n removeBulgeRight(i);\n }\n\n if( bulge != 0 )\n removeBulgeLeft(x2-1,false);\n\n incrementSteps();\n }", "public Map<String, MBeanAttributeInfo> getAttributeMetadata() {\n\n MBeanAttributeInfo[] attributeList = mBeanInfo.getAttributes();\n\n Map<String, MBeanAttributeInfo> attributeMap = new TreeMap<String, MBeanAttributeInfo>();\n for (MBeanAttributeInfo attribute: attributeList) {\n attributeMap.put(attribute.getName(), attribute);\n }\n return attributeMap;\n }", "public static RgbaColor fromHex(String hex) {\n if (hex.length() == 0 || hex.charAt(0) != '#') return getDefaultColor();\n\n // #rgb\n if (hex.length() == 4) {\n\n return new RgbaColor(parseHex(hex, 1, 2),\n parseHex(hex, 2, 3),\n parseHex(hex, 3, 4));\n\n }\n // #rrggbb\n else if (hex.length() == 7) {\n\n return new RgbaColor(parseHex(hex, 1, 3),\n parseHex(hex, 3, 5),\n parseHex(hex, 5, 7));\n\n }\n else {\n return getDefaultColor();\n }\n }" ]
Clones the given reference. @param refDef The reference descriptor @param prefix A prefix for the name @return The cloned reference
[ "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 }" ]
[ "private Map<UUID, FieldType> populateCustomFieldMap()\n {\n byte[] data = m_taskProps.getByteArray(Props.CUSTOM_FIELDS);\n int length = MPPUtility.getInt(data, 0);\n int index = length + 36;\n\n // 4 byte record count\n int recordCount = MPPUtility.getInt(data, index);\n index += 4;\n\n // 8 bytes per record\n index += (8 * recordCount);\n \n Map<UUID, FieldType> map = new HashMap<UUID, FieldType>();\n while (index < data.length)\n {\n int blockLength = MPPUtility.getInt(data, index); \n if (blockLength <= 0 || index + blockLength > data.length)\n {\n break;\n }\n \n int fieldID = MPPUtility.getInt(data, index + 4);\n FieldType field = FieldTypeHelper.getInstance(fieldID);\n UUID guid = MPPUtility.getGUID(data, index + 160);\n map.put(guid, field);\n index += blockLength;\n }\n return map;\n }", "public static void downloadUrl(String stringUrl, Map<String, String> parameters, File fileToSave)\n throws IOException {\n URL url = new URL(stringUrl);\n HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n conn.setFollowRedirects(true);\n \n if (parameters != null) {\n for (Entry<String, String> entry : parameters.entrySet()) {\n conn.addRequestProperty(entry.getKey(), entry.getValue());\n }\n }\n\n\n boolean redirect = false;\n\n // normally, 3xx is redirect\n int status = conn.getResponseCode();\n if (status != HttpURLConnection.HTTP_OK) {\n if (status == HttpURLConnection.HTTP_MOVED_TEMP\n || status == HttpURLConnection.HTTP_MOVED_PERM\n || status == HttpURLConnection.HTTP_SEE_OTHER)\n redirect = true;\n }\n\n if (redirect) {\n\n // get redirect url from \"location\" header field\n String newUrl = conn.getHeaderField(\"Location\");\n\n // get the cookie if need, for login\n String cookies = conn.getHeaderField(\"Set-Cookie\");\n\n // open the new connnection again\n conn = (HttpURLConnection) new URL(newUrl).openConnection();\n conn.setRequestProperty(\"Cookie\", cookies);\n\n }\n \n byte[] data = MyStreamUtils.readContentBytes(conn.getInputStream());\n FileOutputStream fos = new FileOutputStream(fileToSave);\n fos.write(data);\n fos.close();\n }", "public void process(String driverClass, String connectionString, String projectID, String outputFile) throws Exception\n {\n System.out.println(\"Reading Primavera database started.\");\n\n Class.forName(driverClass);\n Properties props = new Properties();\n\n //\n // This is not a very robust way to detect that we're working with SQLlite...\n // If you are trying to grab data from\n // a standalone P6 using SQLite, the SQLite JDBC driver needs this property\n // in order to correctly parse timestamps.\n //\n if (driverClass.equals(\"org.sqlite.JDBC\"))\n {\n props.setProperty(\"date_string_format\", \"yyyy-MM-dd HH:mm:ss\");\n }\n\n Connection c = DriverManager.getConnection(connectionString, props);\n PrimaveraDatabaseReader reader = new PrimaveraDatabaseReader();\n reader.setConnection(c);\n\n processProject(reader, Integer.parseInt(projectID), outputFile);\n }", "public static int cudnnPoolingForward(\n cudnnHandle handle, \n cudnnPoolingDescriptor poolingDesc, \n Pointer alpha, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor yDesc, \n Pointer y)\n {\n return checkResult(cudnnPoolingForwardNative(handle, poolingDesc, alpha, xDesc, x, beta, yDesc, y));\n }", "public void getDataDTD(Writer output) throws DataTaskException\r\n {\r\n try\r\n {\r\n output.write(\"<!ELEMENT dataset (\\n\");\r\n for (Iterator it = _preparedModel.getElementNames(); it.hasNext();)\r\n {\r\n String elementName = (String)it.next();\r\n\r\n output.write(\" \");\r\n output.write(elementName);\r\n output.write(\"*\");\r\n output.write(it.hasNext() ? \" |\\n\" : \"\\n\");\r\n }\r\n output.write(\")>\\n<!ATTLIST dataset\\n name CDATA #REQUIRED\\n>\\n\");\r\n for (Iterator it = _preparedModel.getElementNames(); it.hasNext();)\r\n {\r\n String elementName = (String)it.next();\r\n List classDescs = _preparedModel.getClassDescriptorsMappingTo(elementName);\r\n\r\n if (classDescs == null)\r\n {\r\n output.write(\"\\n<!-- Indirection table\");\r\n }\r\n else\r\n {\r\n output.write(\"\\n<!-- Mapped to : \");\r\n for (Iterator classDescIt = classDescs.iterator(); classDescIt.hasNext();)\r\n {\r\n ClassDescriptor classDesc = (ClassDescriptor)classDescIt.next();\r\n \r\n output.write(classDesc.getClassNameOfObject());\r\n if (classDescIt.hasNext())\r\n {\r\n output.write(\"\\n \");\r\n }\r\n }\r\n }\r\n output.write(\" -->\\n<!ELEMENT \");\r\n output.write(elementName);\r\n output.write(\" EMPTY>\\n<!ATTLIST \");\r\n output.write(elementName);\r\n output.write(\"\\n\");\r\n\r\n for (Iterator attrIt = _preparedModel.getAttributeNames(elementName); attrIt.hasNext();)\r\n {\r\n String attrName = (String)attrIt.next();\r\n\r\n output.write(\" \");\r\n output.write(attrName);\r\n output.write(\" CDATA #\");\r\n output.write(_preparedModel.isRequired(elementName, attrName) ? \"REQUIRED\" : \"IMPLIED\");\r\n output.write(\"\\n\");\r\n }\r\n output.write(\">\\n\");\r\n }\r\n }\r\n catch (IOException ex)\r\n {\r\n throw new DataTaskException(ex);\r\n }\r\n }", "protected void beforeLoading()\r\n {\r\n if (_listeners != null)\r\n {\r\n CollectionProxyListener listener;\r\n\r\n if (_perThreadDescriptorsEnabled) {\r\n loadProfileIfNeeded();\r\n }\r\n for (int idx = _listeners.size() - 1; idx >= 0; idx--)\r\n {\r\n listener = (CollectionProxyListener)_listeners.get(idx);\r\n listener.beforeLoading(this);\r\n }\r\n }\r\n }", "public void setPerms(String photoId, Permissions permissions) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SET_PERMS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"is_public\", permissions.isPublicFlag() ? \"1\" : \"0\");\r\n parameters.put(\"is_friend\", permissions.isFriendFlag() ? \"1\" : \"0\");\r\n parameters.put(\"is_family\", permissions.isFamilyFlag() ? \"1\" : \"0\");\r\n parameters.put(\"perm_comment\", Integer.toString(permissions.getComment()));\r\n parameters.put(\"perm_addmeta\", Integer.toString(permissions.getAddmeta()));\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 }", "@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 }", "protected void appendWhereClause(ClassDescriptor cld, boolean useLocking, StringBuffer stmt)\r\n {\r\n FieldDescriptor[] pkFields = cld.getPkFields();\r\n FieldDescriptor[] fields;\r\n\r\n fields = pkFields;\r\n if(useLocking)\r\n {\r\n FieldDescriptor[] lockingFields = cld.getLockingFields();\r\n if(lockingFields.length > 0)\r\n {\r\n fields = new FieldDescriptor[pkFields.length + lockingFields.length];\r\n System.arraycopy(pkFields, 0, fields, 0, pkFields.length);\r\n System.arraycopy(lockingFields, 0, fields, pkFields.length, lockingFields.length);\r\n }\r\n }\r\n\r\n appendWhereClause(fields, stmt);\r\n }" ]
Generate Allure report data from directories with allure report results. @param args a list of directory paths. First (args.length - 1) arguments - results directories, last argument - the folder to generated data
[ "public static void main(String[] args) {\n if (args.length < 2) { // NOSONAR\n LOGGER.error(\"There must be at least two arguments\");\n return;\n }\n int lastIndex = args.length - 1;\n AllureReportGenerator reportGenerator = new AllureReportGenerator(\n getFiles(Arrays.copyOf(args, lastIndex))\n );\n reportGenerator.generate(new File(args[lastIndex]));\n }" ]
[ "public ModelSource resolveModel( Parent parent )\r\n throws UnresolvableModelException {\r\n\r\n Dependency parentDependency = new Dependency();\r\n parentDependency.setGroupId(parent.getGroupId());\r\n parentDependency.setArtifactId(parent.getArtifactId());\r\n parentDependency.setVersion(parent.getVersion());\r\n parentDependency.setClassifier(\"\");\r\n parentDependency.setType(\"pom\");\r\n\r\n Artifact parentArtifact = null;\r\n try\r\n {\r\n Iterable<ArtifactResult> artifactResults = depencencyResolver.resolveDependencies(\r\n projectBuildingRequest, singleton(parentDependency), null, null );\r\n Iterator<ArtifactResult> iterator = artifactResults.iterator();\r\n if (iterator.hasNext()) {\r\n parentArtifact = iterator.next().getArtifact();\r\n }\r\n } catch (DependencyResolverException e) {\r\n throw new UnresolvableModelException( e.getMessage(), parent.getGroupId(), parent.getArtifactId(),\r\n parent.getVersion(), e );\r\n }\r\n\r\n return resolveModel( parentArtifact.getGroupId(), parentArtifact.getArtifactId(), parentArtifact.getVersion() );\r\n }", "public void addNotIn(String attribute, Query subQuery)\r\n {\r\n\t\t// PAW\r\n\t\t// addSelectionCriteria(ValueCriteria.buildNotInCriteria(attribute, subQuery, getAlias()));\r\n\t\taddSelectionCriteria(ValueCriteria.buildNotInCriteria(attribute, subQuery, getUserAlias(attribute)));\r\n }", "public static String lookupIfEmpty( final String value,\n final Map<String, String> props,\n final String key ) {\n return value != null ? value : props.get(key);\n }", "public AT_Row setPaddingTopBottom(int padding){\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingTopBottom(padding);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "private int getItemViewType(Class prototypeClass) {\n int itemViewType = -1;\n for (Renderer renderer : prototypes) {\n if (renderer.getClass().equals(prototypeClass)) {\n itemViewType = getPrototypeIndex(renderer);\n break;\n }\n }\n if (itemViewType == -1) {\n throw new PrototypeNotFoundException(\n \"Review your RendererBuilder implementation, you are returning one\"\n + \" prototype class not found in prototypes collection\");\n }\n return itemViewType;\n }", "public void remove(Identity oid)\r\n {\r\n if (oid == null) return;\r\n\r\n ObjectCache cache = getCache(oid, null, METHOD_REMOVE);\r\n if (cache != null)\r\n {\r\n cache.remove(oid);\r\n }\r\n }", "private void populateMetaData() throws SQLException\n {\n m_meta.clear();\n\n ResultSetMetaData meta = m_rs.getMetaData();\n int columnCount = meta.getColumnCount() + 1;\n for (int loop = 1; loop < columnCount; loop++)\n {\n String name = meta.getColumnName(loop);\n Integer type = Integer.valueOf(meta.getColumnType(loop));\n m_meta.put(name, type);\n }\n }", "public static void initialize(final Context context) {\n if (!initialized.compareAndSet(false, true)) {\n return;\n }\n\n applicationContext = context.getApplicationContext();\n\n final String packageName = applicationContext.getPackageName();\n localAppName = packageName;\n\n final PackageManager manager = applicationContext.getPackageManager();\n try {\n final PackageInfo pkgInfo = manager.getPackageInfo(packageName, 0);\n localAppVersion = pkgInfo.versionName;\n } catch (final NameNotFoundException e) {\n Log.d(TAG, \"Failed to get version of application, will not send in device info.\");\n }\n\n Log.d(TAG, \"Initialized android SDK\");\n }", "public List getFeedback()\n\t {\n\t List<?> messages = new ArrayList();\n\t for ( ValueSource vs : valueSources )\n\t {\n\t List feedback = vs.getFeedback();\n\t if ( feedback != null && !feedback.isEmpty() )\n\t {\n\t messages.addAll( feedback );\n\t }\n\t }\n\n\t return messages;\n\t }" ]
Sets the time warp. @param l the new time warp
[ "public void setTimeWarp(String l) {\n\n long warp = CmsContextInfo.CURRENT_TIME;\n try {\n warp = Long.parseLong(l);\n } catch (NumberFormatException e) {\n // if parsing the time warp fails, it will be set to -1 (i.e. disabled)\n }\n m_settings.setTimeWarp(warp);\n }" ]
[ "public static base_response unset(nitro_service client, nsacl6 resource, String[] args) throws Exception{\n\t\tnsacl6 unsetresource = new nsacl6();\n\t\tunsetresource.acl6name = resource.acl6name;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "synchronized long storeUserProfile(String id, JSONObject obj) {\n\n if (id == null) return DB_UPDATE_ERROR;\n\n if (!this.belowMemThreshold()) {\n getConfigLogger().verbose(\"There is not enough space left on the device to store data, data discarded\");\n return DB_OUT_OF_MEMORY_ERROR;\n }\n\n final String tableName = Table.USER_PROFILES.getName();\n\n long ret = DB_UPDATE_ERROR;\n\n try {\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n final ContentValues cv = new ContentValues();\n cv.put(KEY_DATA, obj.toString());\n cv.put(\"_id\", id);\n ret = db.insertWithOnConflict(tableName, null, cv, SQLiteDatabase.CONFLICT_REPLACE);\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Error adding data to table \" + tableName + \" Recreating DB\");\n dbHelper.deleteDatabase();\n } finally {\n dbHelper.close();\n }\n return ret;\n }", "private void parseValue() {\n ChannelBuffer content = this.request.getContent();\n this.parsedValue = new byte[content.capacity()];\n content.readBytes(parsedValue);\n }", "private static Map<String, Integer> findClasses(Path path)\n {\n List<String> paths = findPaths(path, true);\n Map<String, Integer> results = new HashMap<>();\n for (String subPath : paths)\n {\n if (subPath.endsWith(\".java\") || subPath.endsWith(\".class\"))\n {\n String qualifiedName = PathUtil.classFilePathToClassname(subPath);\n addClassToMap(results, qualifiedName);\n }\n }\n return results;\n }", "public static ServiceName moduleSpecServiceName(ModuleIdentifier identifier) {\n if (!isDynamicModule(identifier)) {\n throw ServerLogger.ROOT_LOGGER.missingModulePrefix(identifier, MODULE_PREFIX);\n }\n return MODULE_SPEC_SERVICE_PREFIX.append(identifier.getName()).append(identifier.getSlot());\n }", "@UiHandler(\"m_atDay\")\r\n void onWeekDayChange(ValueChangeEvent<String> event) {\r\n\r\n if (handleChange()) {\r\n m_controller.setWeekDay(event.getValue());\r\n }\r\n }", "public IPv4AddressSection getEmbeddedIPv4AddressSection(int startIndex, int endIndex) {\n\t\tif(startIndex == ((IPv6Address.MIXED_ORIGINAL_SEGMENT_COUNT - this.addressSegmentIndex) << 1) && endIndex == (getSegmentCount() << 1)) {\n\t\t\treturn getEmbeddedIPv4AddressSection();\n\t\t}\n\t\tIPv4AddressCreator creator = getIPv4Network().getAddressCreator();\n\t\tIPv4AddressSegment[] segments = creator.createSegmentArray((endIndex - startIndex) >> 1);\n\t\tint i = startIndex, j = 0;\n\t\tif(i % IPv6Address.BYTES_PER_SEGMENT == 1) {\n\t\t\tIPv6AddressSegment ipv6Segment = getSegment(i >> 1);\n\t\t\ti++;\n\t\t\tipv6Segment.getSplitSegments(segments, j - 1, creator);\n\t\t\tj++;\n\t\t}\n\t\tfor(; i < endIndex; i <<= 1, j <<= 1) {\n\t\t\tIPv6AddressSegment ipv6Segment = getSegment(i >> 1);\n\t\t\tipv6Segment.getSplitSegments(segments, j, creator);\n\t\t}\n\t\treturn createEmbeddedSection(creator, segments, this);\n\t}", "private boolean contains(ArrayList defs, DefBase obj)\r\n {\r\n for (Iterator it = defs.iterator(); it.hasNext();)\r\n {\r\n if (obj.getName().equals(((DefBase)it.next()).getName()))\r\n {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }", "public F resolve(R resolvable, boolean cache) {\n R wrappedResolvable = wrap(resolvable);\n if (cache) {\n return resolved.getValue(wrappedResolvable);\n } else {\n return resolverFunction.apply(wrappedResolvable);\n }\n }" ]
fetch correct array index if index is less than 0 ArrayNode will convert all negative integers into 0... @param index wanted index @return {@link Integer} new index
[ "protected Integer getCorrectIndex(Integer index) {\n Integer size = jsonNode.size();\n Integer newIndex = index;\n\n // reverse walking through the array\n if(index < 0) {\n newIndex = size + index;\n }\n\n // the negative index would be greater than the size a second time!\n if(newIndex < 0) {\n throw LOG.indexOutOfBounds(index, size);\n }\n\n // the index is greater as the actual size\n if(index > size) {\n throw LOG.indexOutOfBounds(index, size);\n }\n\n return newIndex;\n }" ]
[ "public static boolean blockAligned( int blockLength , DSubmatrixD1 A ) {\n if( A.col0 % blockLength != 0 )\n return false;\n if( A.row0 % blockLength != 0 )\n return false;\n\n if( A.col1 % blockLength != 0 && A.col1 != A.original.numCols ) {\n return false;\n }\n\n if( A.row1 % blockLength != 0 && A.row1 != A.original.numRows) {\n return false;\n }\n\n return true;\n }", "public static ComplexNumber Subtract(ComplexNumber z1, ComplexNumber z2) {\r\n return new ComplexNumber(z1.real - z2.real, z1.imaginary - z2.imaginary);\r\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 VectorClock incremented(int nodeId, long time) {\n VectorClock copyClock = this.clone();\n copyClock.incrementVersion(nodeId, time);\n return copyClock;\n }", "public boolean isIPv4Mapped() {\n\t\t//::ffff:x:x/96 indicates IPv6 address mapped to IPv4\n\t\tif(getSegment(5).matches(IPv6Address.MAX_VALUE_PER_SEGMENT)) {\n\t\t\tfor(int i = 0; i < 5; i++) {\n\t\t\t\tif(!getSegment(i).isZero()) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}", "public String createTorqueSchema(Properties attributes) throws XDocletException\r\n {\r\n String dbName = (String)getDocletContext().getConfigParam(CONFIG_PARAM_DATABASENAME);\r\n\r\n _torqueModel = new TorqueModelDef(dbName, _model);\r\n return \"\";\r\n }", "static void initSingleParam(String key, String initValue, DbConn cnx)\n {\n try\n {\n cnx.runSelectSingle(\"globalprm_select_by_key\", 2, String.class, key);\n return;\n }\n catch (NoResultException e)\n {\n GlobalParameter.create(cnx, key, initValue);\n }\n catch (NonUniqueResultException e)\n {\n // It exists! Nothing to do...\n }\n }", "@SuppressWarnings(\"serial\")\n private Component createCloseButton() {\n\n Button closeBtn = CmsToolBar.createButton(\n FontOpenCms.CIRCLE_INV_CANCEL,\n m_messages.key(Messages.GUI_BUTTON_CANCEL_0));\n closeBtn.addClickListener(new ClickListener() {\n\n public void buttonClick(ClickEvent event) {\n\n closeAction();\n }\n\n });\n return closeBtn;\n }", "public void addNavigationalInformationForInverseSide() {\n\t\tif ( log.isTraceEnabled() ) {\n\t\t\tlog.trace( \"Adding inverse navigational information for entity: \" + MessageHelper.infoString( persister, id, persister.getFactory() ) );\n\t\t}\n\n\t\tfor ( int propertyIndex = 0; propertyIndex < persister.getEntityMetamodel().getPropertySpan(); propertyIndex++ ) {\n\t\t\tif ( persister.isPropertyOfTable( propertyIndex, tableIndex ) ) {\n\t\t\t\tAssociationKeyMetadata associationKeyMetadata = getInverseAssociationKeyMetadata( propertyIndex );\n\n\t\t\t\t// there is no inverse association for the given property\n\t\t\t\tif ( associationKeyMetadata == null ) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tObject[] newColumnValues = LogicalPhysicalConverterHelper.getColumnValuesFromResultset(\n\t\t\t\t\t\tresultset,\n\t\t\t\t\t\tpersister.getPropertyColumnNames( propertyIndex )\n\t\t\t\t);\n\n\t\t\t\t//don't index null columns, this means no association\n\t\t\t\tif ( ! CollectionHelper.isEmptyOrContainsOnlyNull( ( newColumnValues ) ) ) {\n\t\t\t\t\taddNavigationalInformationForInverseSide( propertyIndex, associationKeyMetadata, newColumnValues );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}" ]
Do not call this method outside of activity!!!
[ "public static String retrieveVendorId() {\n if (MapboxTelemetry.applicationContext == null) {\n return updateVendorId();\n }\n\n SharedPreferences sharedPreferences = obtainSharedPreferences(MapboxTelemetry.applicationContext);\n String mapboxVendorId = sharedPreferences.getString(MAPBOX_SHARED_PREFERENCE_KEY_VENDOR_ID, \"\");\n if (TelemetryUtils.isEmpty(mapboxVendorId)) {\n mapboxVendorId = TelemetryUtils.updateVendorId();\n }\n return mapboxVendorId;\n }" ]
[ "public static BoxUser.Info createAppUser(BoxAPIConnection api, String name) {\n return createAppUser(api, name, new CreateUserParams());\n }", "private static Future<?> spawn(final int priority, final Runnable threadProc) {\n return threadPool.submit(new Runnable() {\n\n @Override\n public void run() {\n Thread current = Thread.currentThread();\n int defaultPriority = current.getPriority();\n\n try {\n current.setPriority(priority);\n\n /*\n * We yield to give the foreground process a chance to run.\n * This also means that the new priority takes effect RIGHT\n * AWAY, not after the next blocking call or quantum\n * timeout.\n */\n Thread.yield();\n\n try {\n threadProc.run();\n } catch (Exception e) {\n logException(TAG, e);\n }\n } finally {\n current.setPriority(defaultPriority);\n }\n\n }\n\n });\n }", "public void addRowAfter(I_CmsEditableGroupRow row) {\n\n int index = m_container.getComponentIndex(row);\n if (index >= 0) {\n Component component = m_newComponentFactory.get();\n I_CmsEditableGroupRow newRow = m_rowBuilder.buildRow(this, component);\n m_container.addComponent(newRow, index + 1);\n }\n updatePlaceholder();\n updateButtonBars();\n updateGroupValidation();\n }", "public AbstractGraph getModuleGraph(final String moduleId) {\n final ModuleHandler moduleHandler = new ModuleHandler(repoHandler);\n final DbModule module = moduleHandler.getModule(moduleId);\n final DbOrganization organization = moduleHandler.getOrganization(module);\n\n filters.setCorporateFilter(new CorporateFilter(organization));\n\n final AbstractGraph graph = new ModuleGraph();\n addModuleToGraph(module, graph, 0);\n\n return graph;\n }", "public static String getShortClassName(Object o) {\r\n String name = o.getClass().getName();\r\n int index = name.lastIndexOf('.');\r\n if (index >= 0) {\r\n name = name.substring(index + 1);\r\n }\r\n return name;\r\n }", "@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public Searcher deleteFacet(String... attributes) {\n for (String attribute : attributes) {\n facetRequestCount.put(attribute, 0);\n facets.remove(attribute);\n }\n rebuildQueryFacets();\n return this;\n }", "public static systemsession[] get(nitro_service service) throws Exception{\n\t\tsystemsession obj = new systemsession();\n\t\tsystemsession[] response = (systemsession[])obj.get_resources(service);\n\t\treturn response;\n\t}", "protected void calculateBarPositions(int _DataSize) {\n\n int dataSize = mScrollEnabled ? mVisibleBars : _DataSize;\n float barWidth = mBarWidth;\n float margin = mBarMargin;\n\n if (!mFixedBarWidth) {\n // calculate the bar width if the bars should be dynamically displayed\n barWidth = (mAvailableScreenSize / _DataSize) - margin;\n } else {\n\n if(_DataSize < mVisibleBars) {\n dataSize = _DataSize;\n }\n\n // calculate margin between bars if the bars have a fixed width\n float cumulatedBarWidths = barWidth * dataSize;\n float remainingScreenSize = mAvailableScreenSize - cumulatedBarWidths;\n\n margin = remainingScreenSize / dataSize;\n }\n\n boolean isVertical = this instanceof VerticalBarChart;\n\n int calculatedSize = (int) ((barWidth * _DataSize) + (margin * _DataSize));\n int contentWidth = isVertical ? mGraphWidth : calculatedSize;\n int contentHeight = isVertical ? calculatedSize : mGraphHeight;\n\n mContentRect = new Rect(0, 0, contentWidth, contentHeight);\n mCurrentViewport = new RectF(0, 0, mGraphWidth, mGraphHeight);\n\n calculateBounds(barWidth, margin);\n mLegend.invalidate();\n mGraph.invalidate();\n }", "private void stripCommas(TokenList tokens) {\n TokenList.Token t = tokens.getFirst();\n\n while( t != null ) {\n TokenList.Token next = t.next;\n if( t.getSymbol() == Symbol.COMMA ) {\n tokens.remove(t);\n }\n t = next;\n }\n }" ]
Merge a new subsystem from the global registration. @param registry the global registry @param subsystemName the subsystem name @param version the subsystem version
[ "public void mergeSubsystem(final GlobalTransformerRegistry registry, String subsystemName, ModelVersion version) {\n final PathElement element = PathElement.pathElement(SUBSYSTEM, subsystemName);\n registry.mergeSubtree(this, PathAddress.EMPTY_ADDRESS.append(element), version);\n }" ]
[ "public static ModelNode createRemoveOperation(final ModelNode address, final boolean recursive) {\n final ModelNode op = createRemoveOperation(address);\n op.get(RECURSIVE).set(recursive);\n return op;\n }", "public static long stopNamedTimer(String timerName, int todoFlags) {\n\t\treturn stopNamedTimer(timerName, todoFlags, Thread.currentThread()\n\t\t\t\t.getId());\n\t}", "protected String pauseMsg() throws IOException {\n final WorkerStatus status = new WorkerStatus();\n status.setRunAt(new Date());\n status.setPaused(isPaused());\n return ObjectMapperFactory.get().writeValueAsString(status);\n }", "static boolean isEmptyWhitespace(@Nullable final String s) {\n if (s == null) {\n return true;\n }\n return CharMatcher.WHITESPACE.matchesAllOf(s);\n }", "public void checkpoint(ObjectEnvelope mod)\r\n throws org.apache.ojb.broker.PersistenceBrokerException\r\n {\r\n mod.doDelete();\r\n mod.setModificationState(StateTransient.getInstance());\r\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 }", "private static String resolveJavaCommand(final Path javaHome) {\n final String exe;\n if (javaHome == null) {\n exe = \"java\";\n } else {\n exe = javaHome.resolve(\"bin\").resolve(\"java\").toString();\n }\n if (exe.contains(\" \")) {\n return \"\\\"\" + exe + \"\\\"\";\n }\n return exe;\n }", "public String getElementId() {\r\n\t\tfor (Entry<String, String> attribute : attributes.entrySet()) {\r\n\t\t\tif (attribute.getKey().equalsIgnoreCase(\"id\")) {\r\n\t\t\t\treturn attribute.getValue();\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn null;\r\n\t}", "public static appfwglobal_auditnslogpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tappfwglobal_auditnslogpolicy_binding obj = new appfwglobal_auditnslogpolicy_binding();\n\t\tappfwglobal_auditnslogpolicy_binding response[] = (appfwglobal_auditnslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
Converts a list of dates to a Json array with the long representation of the dates as strings. @param individualDates the list to convert. @return Json array with long values of dates as string
[ "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 }" ]
[ "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 }", "protected void initValid(EnhancedAnnotation<T> annotatedAnnotation) {\n this.valid = false;\n for (Class<? extends Annotation> annotationType : getMetaAnnotationTypes()) {\n if (annotatedAnnotation.isAnnotationPresent(annotationType)) {\n this.valid = true;\n }\n }\n }", "public static String getString(Properties props, String name, String defaultValue) {\n return props.containsKey(name) ? props.getProperty(name) : defaultValue;\n }", "public String readSnippet(String name) {\n\n String path = CmsStringUtil.joinPaths(\n m_context.getSetupBean().getWebAppRfsPath(),\n CmsSetupBean.FOLDER_SETUP,\n \"html\",\n name);\n try (InputStream stream = new FileInputStream(path)) {\n byte[] data = CmsFileUtil.readFully(stream, false);\n String result = new String(data, \"UTF-8\");\n return result;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }", "public final PJsonArray optJSONArray(final String key, final PJsonArray defaultValue) {\n PJsonArray result = optJSONArray(key);\n return result != null ? result : defaultValue;\n }", "private void addDateRange(ProjectCalendarHours hours, Date start, Date end)\n {\n if (start != null && end != null)\n {\n Calendar cal = DateHelper.popCalendar(end);\n // If the time ends on midnight, the date should be the next day. Otherwise problems occur.\n if (cal.get(Calendar.HOUR_OF_DAY) == 0 && cal.get(Calendar.MINUTE) == 0 && cal.get(Calendar.SECOND) == 0 && cal.get(Calendar.MILLISECOND) == 0)\n {\n cal.add(Calendar.DAY_OF_YEAR, 1);\n }\n end = cal.getTime();\n DateHelper.pushCalendar(cal);\n \n hours.addRange(new DateRange(start, end));\n }\n }", "public void addStep(String name, String robot, Map<String, Object> options) {\n all.put(name, new Step(name, robot, options));\n }", "public static HashMap<String, String> getMapFromJSONPath(JSONObject record, String path) {\n return getObjectFromJSONPath(record, path);\n }", "public static Method[] getUniqueDeclaredMethods(Class<?> leafClass) throws IllegalArgumentException {\n final List<Method> methods = new ArrayList<Method>(32);\n doWithMethods(leafClass, new MethodCallback() {\n @Override\n public void doWith(Method method) {\n boolean knownSignature = false;\n Method methodBeingOverriddenWithCovariantReturnType = null;\n for (Method existingMethod : methods) {\n if (method.getName().equals(existingMethod.getName()) &&\n Arrays.equals(method.getParameterTypes(), existingMethod.getParameterTypes())) {\n // Is this a covariant return type situation?\n if (existingMethod.getReturnType() != method.getReturnType() &&\n existingMethod.getReturnType().isAssignableFrom(method.getReturnType())) {\n methodBeingOverriddenWithCovariantReturnType = existingMethod;\n } else {\n knownSignature = true;\n }\n break;\n }\n }\n if (methodBeingOverriddenWithCovariantReturnType != null) {\n methods.remove(methodBeingOverriddenWithCovariantReturnType);\n }\n if (!knownSignature) {\n methods.add(method);\n }\n }\n });\n return methods.toArray(new Method[methods.size()]);\n }" ]
Get interfaces implemented by clazz @param clazz @return
[ "private Class[] getInterfaces(Class clazz) {\r\n Class superClazz = clazz;\r\n Class[] interfaces = clazz.getInterfaces();\r\n\r\n // clazz can be an interface itself and when getInterfaces()\r\n // is called on an interface it returns only the extending\r\n // interfaces, not the interface itself.\r\n if (clazz.isInterface()) {\r\n Class[] tempInterfaces = new Class[interfaces.length + 1];\r\n tempInterfaces[0] = clazz;\r\n\r\n System.arraycopy(interfaces, 0, tempInterfaces, 1, interfaces.length);\r\n interfaces = tempInterfaces;\r\n }\r\n\r\n // add all interfaces implemented by superclasses to the interfaces array\r\n while ((superClazz = superClazz.getSuperclass()) != null) {\r\n Class[] superInterfaces = superClazz.getInterfaces();\r\n Class[] combInterfaces = new Class[interfaces.length + superInterfaces.length];\r\n System.arraycopy(interfaces, 0, combInterfaces, 0, interfaces.length);\r\n System.arraycopy(superInterfaces, 0, combInterfaces, interfaces.length, superInterfaces.length);\r\n interfaces = combInterfaces;\r\n }\r\n\r\n /**\r\n * Must remove duplicate interfaces before calling Proxy.getProxyClass().\r\n * Duplicates can occur if a subclass re-declares that it implements\r\n * the same interface as one of its ancestor classes.\r\n **/\r\n HashMap unique = new HashMap();\r\n for (int i = 0; i < interfaces.length; i++) {\r\n unique.put(interfaces[i].getName(), interfaces[i]);\r\n }\r\n /* Add the OJBProxy interface as well */\r\n unique.put(OJBProxy.class.getName(), OJBProxy.class);\r\n\r\n interfaces = (Class[])unique.values().toArray(new Class[unique.size()]);\r\n\r\n return interfaces;\r\n }" ]
[ "public int bindShader(GVRContext context, GVRShaderData material, String vertexDesc)\n {\n String signature = getClass().getSimpleName();\n GVRShaderManager shaderManager = context.getShaderManager();\n\n synchronized (shaderManager)\n {\n int nativeShader = shaderManager.getShader(signature);\n if (nativeShader == 0)\n {\n nativeShader = addShader(shaderManager, signature, material);\n }\n return nativeShader;\n }\n }", "public PhotoList<Photo> getClusterPhotos(String tag, String clusterId) throws FlickrException {\n\n PhotoList<Photo> photos = new PhotoList<Photo>();\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_CLUSTER_PHOTOS);\n\n parameters.put(\"tag\", tag);\n parameters.put(\"cluster_id\", clusterId);\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 photosElement = response.getPayload();\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\n photos.setPage(\"1\");\n photos.setPages(\"1\");\n photos.setPerPage(\"\" + photoNodes.getLength());\n photos.setTotal(\"\" + photoNodes.getLength());\n for (int i = 0; i < photoNodes.getLength(); i++) {\n Element photoElement = (Element) photoNodes.item(i);\n photos.add(PhotoUtils.createPhoto(photoElement));\n }\n return photos;\n }", "protected boolean isMultimedia(File file) {\n //noinspection SimplifiableIfStatement\n if (isDir(file)) {\n return false;\n }\n\n String path = file.getPath().toLowerCase();\n for (String ext : MULTIMEDIA_EXTENSIONS) {\n if (path.endsWith(ext)) {\n return true;\n }\n }\n\n return false;\n }", "private void addChildrenForGroupsNode(I_CmsOuTreeType type, String ouItem) {\n\n try {\n // Cut of type-specific prefix from ouItem with substring()\n List<CmsGroup> groups = m_app.readGroupsForOu(m_cms, ouItem.substring(1), type, false);\n for (CmsGroup group : groups) {\n Pair<String, CmsUUID> key = Pair.of(type.getId(), group.getId());\n Item groupItem = m_treeContainer.addItem(key);\n if (groupItem == null) {\n groupItem = getItem(key);\n }\n groupItem.getItemProperty(PROP_SID).setValue(group.getId());\n groupItem.getItemProperty(PROP_NAME).setValue(getIconCaptionHTML(group, CmsOuTreeType.GROUP));\n groupItem.getItemProperty(PROP_TYPE).setValue(type);\n setChildrenAllowed(key, false);\n m_treeContainer.setParent(key, ouItem);\n }\n } catch (CmsException e) {\n LOG.error(\"Can not read group\", e);\n }\n }", "private void addProperties(final PropertyDescriptor[] _properties) throws ColumnBuilderException, ClassNotFoundException {\n for (final PropertyDescriptor property : _properties) {\n if (isValidProperty(property)) {\n addColumn(getColumnTitle(property), property.getName(), property.getPropertyType().getName(), getColumnWidth(property));\n }\n }\n setUseFullPageWidth(true);\n }", "public static double I0(double x) {\r\n double ans;\r\n double ax = Math.abs(x);\r\n\r\n if (ax < 3.75) {\r\n double y = x / 3.75;\r\n y = y * y;\r\n ans = 1.0 + y * (3.5156229 + y * (3.0899424 + y * (1.2067492\r\n + y * (0.2659732 + y * (0.360768e-1 + y * 0.45813e-2)))));\r\n } else {\r\n double y = 3.75 / ax;\r\n ans = (Math.exp(ax) / Math.sqrt(ax)) * (0.39894228 + y * (0.1328592e-1\r\n + y * (0.225319e-2 + y * (-0.157565e-2 + y * (0.916281e-2\r\n + y * (-0.2057706e-1 + y * (0.2635537e-1 + y * (-0.1647633e-1\r\n + y * 0.392377e-2))))))));\r\n }\r\n\r\n return ans;\r\n }", "public static String getAt(String text, Range range) {\n RangeInfo info = subListBorders(text.length(), range);\n String answer = text.substring(info.from, info.to);\n if (info.reverse) {\n answer = reverse(answer);\n }\n return answer;\n }", "public void rename(String newName) {\n URL url = FILE_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"PUT\");\n\n JsonObject updateInfo = new JsonObject();\n updateInfo.add(\"name\", newName);\n\n request.setBody(updateInfo.toString());\n BoxAPIResponse response = request.send();\n response.disconnect();\n }", "void countNonZeroInR( int[] parent ) {\n TriangularSolver_DSCC.postorder(parent,n,post,gwork);\n columnCounts.process(A,parent,post,countsR);\n nz_in_R = 0;\n for (int k = 0; k < n; k++) {\n nz_in_R += countsR[k];\n }\n if( nz_in_R < 0)\n throw new RuntimeException(\"Too many elements. Numerical overflow in R counts\");\n }" ]
Use this API to update lbsipparameters.
[ "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}" ]
[ "boolean processUnstable() {\n boolean change = !unstable;\n if (change) { // Only once until the process is removed. A process is unstable until removed.\n unstable = true;\n HostControllerLogger.ROOT_LOGGER.managedServerUnstable(serverName);\n }\n return change;\n }", "public String getNotes()\n {\n String notes = (String) getCachedValue(ResourceField.NOTES);\n return (notes == null ? \"\" : notes);\n }", "private String swapStore(String storeName, String directory) throws VoldemortException {\n\n ReadOnlyStorageEngine store = getReadOnlyStorageEngine(metadataStore,\n storeRepository,\n storeName);\n\n if(!Utils.isReadableDir(directory))\n throw new VoldemortException(\"Store directory '\" + directory\n + \"' is not a readable directory.\");\n\n String currentDirPath = store.getCurrentDirPath();\n\n logger.info(\"Swapping RO store '\" + storeName + \"' to version directory '\" + directory\n + \"'\");\n store.swapFiles(directory);\n logger.info(\"Swapping swapped RO store '\" + storeName + \"' to version directory '\"\n + directory + \"'\");\n\n return currentDirPath;\n }", "protected static Map<String, List<Statement>> removeStatements(Set<String> statementIds, Map<String, List<Statement>> claims) {\n\t\tMap<String, List<Statement>> newClaims = new HashMap<>(claims.size());\n\t\tfor(Entry<String, List<Statement>> entry : claims.entrySet()) {\n\t\t\tList<Statement> filteredStatements = new ArrayList<>();\n\t\t\tfor(Statement s : entry.getValue()) {\n\t\t\t\tif(!statementIds.contains(s.getStatementId())) {\n\t\t\t\t\tfilteredStatements.add(s);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(!filteredStatements.isEmpty()) {\n\t\t\t\tnewClaims.put(entry.getKey(),\n\t\t\t\t\tfilteredStatements);\n\t\t\t}\n\t\t}\n\t\treturn newClaims;\n\t}", "private void writeAllEnvelopes(boolean reuse)\r\n {\r\n // perform remove of m:n indirection table entries first\r\n performM2NUnlinkEntries();\r\n\r\n Iterator iter;\r\n // using clone to avoid ConcurentModificationException\r\n iter = ((List) mvOrderOfIds.clone()).iterator();\r\n while(iter.hasNext())\r\n {\r\n ObjectEnvelope mod = (ObjectEnvelope) mhtObjectEnvelopes.get(iter.next());\r\n boolean insert = false;\r\n if(needsCommit)\r\n {\r\n insert = mod.needsInsert();\r\n mod.getModificationState().commit(mod);\r\n if(reuse && insert)\r\n {\r\n getTransaction().doSingleLock(mod.getClassDescriptor(), mod.getObject(), mod.getIdentity(), Transaction.WRITE);\r\n }\r\n }\r\n /*\r\n arminw: important to call this cleanup method for each registered\r\n ObjectEnvelope, because this method will e.g. remove proxy listener\r\n objects for registered objects.\r\n */\r\n mod.cleanup(reuse, insert);\r\n }\r\n // add m:n indirection table entries\r\n performM2NLinkEntries();\r\n }", "@Override\r\n public String upload(File file, UploadMetaData metaData) throws FlickrException {\r\n Payload payload = new Payload(file);\r\n return sendUploadRequest(metaData, payload);\r\n }", "public URI build() {\n try {\n String uriString = String.format(\"%s%s\", baseUri.toASCIIString(),\n (path.isEmpty() ? \"\" : path));\n if(qParams != null && qParams.size() > 0) {\n //Add queries together if both exist\n if(!completeQuery.isEmpty()) {\n uriString = String.format(\"%s?%s&%s\", uriString,\n getJoinedQuery(qParams.getParams()),\n completeQuery);\n } else {\n uriString = String.format(\"%s?%s\", uriString,\n getJoinedQuery(qParams.getParams()));\n }\n } else if(!completeQuery.isEmpty()) {\n uriString = String.format(\"%s?%s\", uriString, completeQuery);\n }\n\n return new URI(uriString);\n } catch (URISyntaxException e) {\n throw new IllegalArgumentException(e);\n }\n }", "private static long getVersionId(String versionDir) {\n try {\n return Long.parseLong(versionDir.replace(\"version-\", \"\"));\n } catch(NumberFormatException e) {\n logger.trace(\"Cannot parse version directory to obtain id \" + versionDir);\n return -1;\n }\n }", "public List<PPVItemsType.PPVItem> getPPVItem()\n {\n if (ppvItem == null)\n {\n ppvItem = new ArrayList<PPVItemsType.PPVItem>();\n }\n return this.ppvItem;\n }" ]
when divisionPrefixLen is null, isAutoSubnets has no effect
[ "protected static boolean isMaskCompatibleWithRange(long value, long upperValue, long maskValue, long maxValue) {\n\t\tif(value == upperValue || maskValue == maxValue || maskValue == 0) {\n\t\t\treturn true;\n\t\t}\n\n\t\t//algorithm:\n\t\t//here we find the highest bit that is part of the range, highestDifferingBitInRange (ie changes from lower to upper)\n\t\t//then we find the highest bit in the mask that is 1 that is the same or below highestDifferingBitInRange (if such a bit exists)\n\t\t\n\t\t//this gives us the highest bit that is part of the masked range (ie changes from lower to upper after applying the mask)\n\t\t//if this latter bit exists, then any bit below it in the mask must be 1 to include the entire range.\n\t\t\n\t\tlong differing = value ^ upperValue;\n\t\tboolean foundDiffering = (differing != 0);\n\t\tboolean differingIsLowestBit = (differing == 1);\n\t\tif(foundDiffering && !differingIsLowestBit) {\n\t\t\tint highestDifferingBitInRange = Long.numberOfLeadingZeros(differing);\n\t\t\tlong maskMask = ~0L >>> highestDifferingBitInRange;\n\t\t\tlong differingMasked = maskValue & maskMask;\n\t\t\tfoundDiffering = (differingMasked != 0);\n\t\t\tdifferingIsLowestBit = (differingMasked == 1);\n\t\t\tif(foundDiffering && !differingIsLowestBit) {\n\t\t\t\t//anything below highestDifferingBitMasked in the mask must be ones\n\t\t\t\t//Also, if we have masked out any 1 bit in the original, then anything that we do not mask out that follows must be all 1s\n\t\t\t\tint highestDifferingBitMasked = Long.numberOfLeadingZeros(differingMasked);\n\t\t\t\tlong hostMask = ~0L >>> (highestDifferingBitMasked + 1);//for the first mask bit that is 1, all bits that follow must also be 1\n\t\t\t\tif((maskValue & hostMask) != hostMask) { //check if all ones below\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif(highestDifferingBitMasked > highestDifferingBitInRange) {\n\t\t\t\t\t//We have masked out a 1 bit, so we need to check that all bits in upper value that we do not mask out are also 1 bits, otherwise we end up missing values in the masked range\n\t\t\t\t\t//This check is unnecessary for prefix-length subnets, only non-standard ranges might fail this check.\n\t\t\t\t\t//For instance, if we have range 0000 to 1010\n\t\t\t\t\t//and we mask upper and lower with 0111\n\t\t\t\t\t//we get 0000 to 0010, but 0111 was in original range, and the mask of that value retains that value\n\t\t\t\t\t//so that value needs to be in final range, and it's not.\n\t\t\t\t\t//What went wrong is that we masked out the top bit, and any other bit that is not masked out must be 1.\n\t\t\t\t\t//To work, our original range needed to be 0000 to 1111, with the three 1s following the first masked-out 1\n\t\t\t\t\tlong hostMaskUpper = ~0L >>> highestDifferingBitMasked;\n\t\t\t\t\tif((upperValue & hostMaskUpper) != hostMaskUpper) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}" ]
[ "public void rotate(String photoId, int degrees) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ROTATE);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"degrees\", String.valueOf(degrees));\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }", "public static base_response update(nitro_service client, nsdiameter resource) throws Exception {\n\t\tnsdiameter updateresource = new nsdiameter();\n\t\tupdateresource.identity = resource.identity;\n\t\tupdateresource.realm = resource.realm;\n\t\tupdateresource.serverclosepropagation = resource.serverclosepropagation;\n\t\treturn updateresource.update_resource(client);\n\t}", "public URI withEmptyAuthority(final URI uri) {\n URI _xifexpression = null;\n if ((uri.isFile() && (uri.authority() == null))) {\n _xifexpression = URI.createHierarchicalURI(uri.scheme(), \"\", uri.device(), uri.segments(), uri.query(), uri.fragment());\n } else {\n _xifexpression = uri;\n }\n return _xifexpression;\n }", "public final void notifyFooterItemRangeChanged(int positionStart, int itemCount) {\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > footerItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for footer items [0 - \"\n + (footerItemCount - 1) + \"].\");\n }\n notifyItemRangeChanged(positionStart + headerItemCount + contentItemCount, itemCount);\n }", "public DJCrosstab build(){\r\n\t\tif (crosstab.getMeasures().isEmpty()){\r\n\t\t\tthrow new LayoutException(\"Crosstabs must have at least one measure\");\r\n\t\t}\r\n\t\tif (crosstab.getColumns().isEmpty()){\r\n\t\t\tthrow new LayoutException(\"Crosstabs must have at least one column\");\r\n\t\t}\r\n\t\tif (crosstab.getRows().isEmpty()){\r\n\t\t\tthrow new LayoutException(\"Crosstabs must have at least one row\");\r\n\t\t}\r\n\t\t\r\n\t\t\r\n\t\t//Ensure default dimension values\r\n\t\tfor (DJCrosstabColumn col : crosstab.getColumns()) {\r\n\t\t\tif (col.getWidth() == -1 && cellWidth != -1)\r\n\t\t\t\tcol.setWidth(cellWidth);\r\n\r\n\t\t\tif (col.getWidth() == -1 )\r\n\t\t\t\tcol.setWidth(DEFAULT_CELL_WIDTH);\r\n\r\n\t\t\tif (col.getHeaderHeight() == -1 && columnHeaderHeight != -1)\r\n\t\t\t\tcol.setHeaderHeight(columnHeaderHeight);\r\n\r\n\t\t\tif (col.getHeaderHeight() == -1)\r\n\t\t\t\tcol.setHeaderHeight(DEFAULT_COLUMN_HEADER_HEIGHT);\r\n\t\t}\r\n\r\n\t\tfor (DJCrosstabRow row : crosstab.getRows()) {\r\n\t\t\tif (row.getHeight() == -1 && cellHeight != -1)\r\n\t\t\t\trow.setHeight(cellHeight);\r\n\r\n\t\t\tif (row.getHeight() == -1 )\r\n\t\t\t\trow.setHeight(DEFAULT_CELL_HEIGHT);\r\n\r\n\t\t\tif (row.getHeaderWidth() == -1 && rowHeaderWidth != -1)\r\n\t\t\t\trow.setHeaderWidth(rowHeaderWidth);\r\n\r\n\t\t\tif (row.getHeaderWidth() == -1)\r\n\t\t\t\trow.setHeaderWidth(DEFAULT_ROW_HEADER_WIDTH);\r\n\r\n\t\t}\r\n\t\treturn crosstab;\r\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 String getParentDirectory(String filePath) throws IllegalArgumentException {\n if (Pattern.matches(sPatternUrl, filePath))\n return getURLParentDirectory(filePath);\n\n return new File(filePath).getParent();\n }", "private void updateDefaultTimeAndSizeRollingAppender(final FoundationFileRollingAppender appender) {\n\n\t\tif (appender.getDatePattern().trim().length() == 0) {\n\t\t\tappender.setDatePattern(FoundationLoggerConstants.DEFAULT_DATE_PATTERN.toString());\n\t\t}\n\t\t\n\t\tString maxFileSizeKey = \"log4j.appender.\"+appender.getName()+\".MaxFileSize\";\n\t\tappender.setMaxFileSize(FoundationLogger.log4jConfigProps.getProperty(maxFileSizeKey, FoundationLoggerConstants.Foundation_MAX_FILE_SIZE.toString()));\n\n//\t\tif (appender.getMaxFileSize() == null || appender.getMaxFileSize().equals(FoundationLoggerConstants.DEFAULT_FILE_SIZE.toString())) {\n//\t\t\tappender.setMaxFileSize(FoundationLoggerConstants.Foundation_MAX_FILE_SIZE.toString());\n//\t\t}\n\n\t\tString maxRollCountKey = \"log4j.appender.\"+appender.getName()+\".MaxRollFileCount\";\n\t\tappender.setMaxRollFileCount(Integer.parseInt(FoundationLogger.log4jConfigProps.getProperty(maxRollCountKey,\"100\")));\n\t}", "public static List<BoxTermsOfService.Info> getAllTermsOfServices(final BoxAPIConnection api,\n BoxTermsOfService.TermsOfServiceType\n termsOfServiceType) {\n QueryStringBuilder builder = new QueryStringBuilder();\n if (termsOfServiceType != null) {\n builder.appendParam(\"tos_type\", termsOfServiceType.toString());\n }\n\n URL url = ALL_TERMS_OF_SERVICES_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString());\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int totalCount = responseJSON.get(\"total_count\").asInt();\n List<BoxTermsOfService.Info> termsOfServices = new ArrayList<BoxTermsOfService.Info>(totalCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : entries) {\n JsonObject termsOfServiceJSON = value.asObject();\n BoxTermsOfService termsOfService = new BoxTermsOfService(api, termsOfServiceJSON.get(\"id\").asString());\n BoxTermsOfService.Info info = termsOfService.new Info(termsOfServiceJSON);\n termsOfServices.add(info);\n }\n\n return termsOfServices;\n }" ]
Gets the invalid message. @param key the key @return the invalid message
[ "public String getInvalidMessage(String key) {\n return invalidMessageOverride == null ? messageMixin.lookup(key, messageValueArgs) : MessageFormat.format(\n invalidMessageOverride, messageValueArgs);\n }" ]
[ "public static DesignDocument fromFile(File file) throws FileNotFoundException {\r\n assertNotEmpty(file, \"Design js file\");\r\n DesignDocument designDocument;\r\n Gson gson = new Gson();\r\n InputStreamReader reader = null;\r\n try {\r\n reader = new InputStreamReader(new FileInputStream(file),\"UTF-8\");\r\n //Deserialize JS file contents into DesignDocument object\r\n designDocument = gson.fromJson(reader, DesignDocument.class);\r\n return designDocument;\r\n } catch (UnsupportedEncodingException e) {\r\n //UTF-8 should be supported on all JVMs\r\n throw new RuntimeException(e);\r\n } finally {\r\n IOUtils.closeQuietly(reader);\r\n }\r\n }", "MongoCollection<BsonDocument> getUndoCollection(final MongoNamespace namespace) {\n return localClient\n .getDatabase(String.format(\"sync_undo_%s\", namespace.getDatabaseName()))\n .getCollection(namespace.getCollectionName(), BsonDocument.class)\n .withCodecRegistry(MongoClientSettings.getDefaultCodecRegistry());\n }", "private String getCacheFormatEntry() throws IOException {\n ZipEntry zipEntry = zipFile.getEntry(CACHE_FORMAT_ENTRY);\n InputStream is = zipFile.getInputStream(zipEntry);\n try {\n Scanner s = new Scanner(is, \"UTF-8\").useDelimiter(\"\\\\A\");\n String tag = null;\n if (s.hasNext()) tag = s.next();\n return tag;\n } finally {\n is.close();\n }\n }", "static Type parseType(String value, ResourceLoader resourceLoader) {\n value = value.trim();\n // Wildcards\n if (value.equals(WILDCARD)) {\n return WildcardTypeImpl.defaultInstance();\n }\n if (value.startsWith(WILDCARD_EXTENDS)) {\n Type upperBound = parseType(value.substring(WILDCARD_EXTENDS.length(), value.length()), resourceLoader);\n if (upperBound == null) {\n return null;\n }\n return WildcardTypeImpl.withUpperBound(upperBound);\n }\n if (value.startsWith(WILDCARD_SUPER)) {\n Type lowerBound = parseType(value.substring(WILDCARD_SUPER.length(), value.length()), resourceLoader);\n if (lowerBound == null) {\n return null;\n }\n return WildcardTypeImpl.withLowerBound(lowerBound);\n }\n // Array\n if (value.contains(ARRAY)) {\n Type componentType = parseType(value.substring(0, value.indexOf(ARRAY)), resourceLoader);\n if (componentType == null) {\n return null;\n }\n return new GenericArrayTypeImpl(componentType);\n }\n int chevLeft = value.indexOf(CHEVRONS_LEFT);\n String rawValue = chevLeft < 0 ? value : value.substring(0, chevLeft);\n Class<?> rawRequiredType = tryLoadClass(rawValue, resourceLoader);\n if (rawRequiredType == null) {\n return null;\n }\n if (rawRequiredType.getTypeParameters().length == 0) {\n return rawRequiredType;\n }\n // Parameterized type\n int chevRight = value.lastIndexOf(CHEVRONS_RIGHT);\n if (chevRight < 0) {\n return null;\n }\n List<String> parts = split(value.substring(chevLeft + 1, chevRight), ',', CHEVRONS_LEFT.charAt(0), CHEVRONS_RIGHT.charAt(0));\n Type[] typeParameters = new Type[parts.size()];\n for (int i = 0; i < typeParameters.length; i++) {\n Type typeParam = parseType(parts.get(i), resourceLoader);\n if (typeParam == null) {\n return null;\n }\n typeParameters[i] = typeParam;\n }\n return new ParameterizedTypeImpl(rawRequiredType, typeParameters);\n }", "public String getNotes()\n {\n String notes = (String) getCachedValue(ResourceField.NOTES);\n return (notes == null ? \"\" : notes);\n }", "public long queryForCountStar(DatabaseConnection databaseConnection) throws SQLException {\n\t\tif (countStarQuery == null) {\n\t\t\tStringBuilder sb = new StringBuilder(64);\n\t\t\tsb.append(\"SELECT COUNT(*) FROM \");\n\t\t\tdatabaseType.appendEscapedEntityName(sb, tableInfo.getTableName());\n\t\t\tcountStarQuery = sb.toString();\n\t\t}\n\t\tlong count = databaseConnection.queryForLong(countStarQuery);\n\t\tlogger.debug(\"query of '{}' returned {}\", countStarQuery, count);\n\t\treturn count;\n\t}", "public static <T> List<T> toList(Iterator<? extends T> iterator) {\n\t\treturn Lists.newArrayList(iterator);\n\t}", "@Deprecated\r\n public Location resolvePlaceURL(String flickrPlacesUrl) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_RESOLVE_PLACE_URL);\r\n\r\n parameters.put(\"url\", flickrPlacesUrl);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element locationElement = response.getPayload();\r\n return parseLocation(locationElement);\r\n }", "public void process(String driverClass, String connectionString, String projectID, String outputFile) throws Exception\n {\n System.out.println(\"Reading Primavera database started.\");\n\n Class.forName(driverClass);\n Properties props = new Properties();\n\n //\n // This is not a very robust way to detect that we're working with SQLlite...\n // If you are trying to grab data from\n // a standalone P6 using SQLite, the SQLite JDBC driver needs this property\n // in order to correctly parse timestamps.\n //\n if (driverClass.equals(\"org.sqlite.JDBC\"))\n {\n props.setProperty(\"date_string_format\", \"yyyy-MM-dd HH:mm:ss\");\n }\n\n Connection c = DriverManager.getConnection(connectionString, props);\n PrimaveraDatabaseReader reader = new PrimaveraDatabaseReader();\n reader.setConnection(c);\n\n processProject(reader, Integer.parseInt(projectID), outputFile);\n }" ]
Standard doclet entry point @param root @return
[ "public static boolean start(RootDoc root) {\n\troot.printNotice(\"UmlGraphDoc version \" + Version.VERSION + \", running the standard doclet\");\n\tStandard.start(root);\n\troot.printNotice(\"UmlGraphDoc version \" + Version.VERSION + \", altering javadocs\");\n\ttry {\n\t String outputFolder = findOutputPath(root.options());\n\n Options opt = UmlGraph.buildOptions(root);\n\t opt.setOptions(root.options());\n\t // in javadoc enumerations are always printed\n\t opt.showEnumerations = true;\n\t opt.relativeLinksForSourcePackages = true;\n\t // enable strict matching for hide expressions\n\t opt.strictMatching = true;\n//\t root.printNotice(opt.toString());\n\n\t generatePackageDiagrams(root, opt, outputFolder);\n\t generateContextDiagrams(root, opt, outputFolder);\n\t} catch(Throwable t) {\n\t root.printWarning(\"Error: \" + t.toString());\n\t t.printStackTrace();\n\t return false;\n\t}\n\treturn true;\n }" ]
[ "public static boolean promoteAndCheckResponse(Promotion promotion, ArtifactoryBuildInfoClient client, TaskListener listener,\n String buildName, String buildNumber) throws IOException {\n // If failFast is true, perform dry run first\n if (promotion.isFailFast()) {\n promotion.setDryRun(true);\n listener.getLogger().println(\"Performing dry run promotion (no changes are made during dry run) ...\");\n HttpResponse dryResponse = client.stageBuild(buildName, buildNumber, promotion);\n try {\n validatePromotionSuccessful(dryResponse, true, promotion.isFailFast(), listener);\n } catch (IOException e) {\n listener.error(e.getMessage());\n return false;\n }\n listener.getLogger().println(\"Dry run finished successfully.\\nPerforming promotion ...\");\n }\n\n // Perform promotion\n promotion.setDryRun(false);\n HttpResponse response = client.stageBuild(buildName, buildNumber, promotion);\n try {\n validatePromotionSuccessful(response, false, promotion.isFailFast(), listener);\n } catch (IOException e) {\n listener.error(e.getMessage());\n return false;\n }\n listener.getLogger().println(\"Promotion completed successfully!\");\n\n return true;\n }", "public static String parseRoot(String zookeepers) {\n int slashIndex = zookeepers.indexOf(\"/\");\n if (slashIndex != -1) {\n return zookeepers.substring(slashIndex).trim();\n }\n return \"/\";\n }", "public static void extractHouseholderColumn( ZMatrixRMaj A ,\n int row0 , int row1 ,\n int col , double u[], int offsetU )\n {\n int indexU = (row0+offsetU)*2;\n u[indexU++] = 1;\n u[indexU++] = 0;\n\n for (int row = row0+1; row < row1; row++) {\n int indexA = A.getIndex(row,col);\n u[indexU++] = A.data[indexA];\n u[indexU++] = A.data[indexA+1];\n }\n }", "public double getValue(int[] batch) {\n double value = 0.0;\n for (int i=0; i<batch.length; i++) {\n value += getValue(i);\n }\n return value;\n }", "private static void listTimephasedWork(ResourceAssignment assignment)\n {\n Task task = assignment.getTask();\n int days = (int) ((task.getFinish().getTime() - task.getStart().getTime()) / (1000 * 60 * 60 * 24)) + 1;\n if (days > 1)\n {\n SimpleDateFormat df = new SimpleDateFormat(\"dd/MM/yy\");\n\n TimescaleUtility timescale = new TimescaleUtility();\n ArrayList<DateRange> dates = timescale.createTimescale(task.getStart(), TimescaleUnits.DAYS, days);\n TimephasedUtility timephased = new TimephasedUtility();\n\n ArrayList<Duration> durations = timephased.segmentWork(assignment.getCalendar(), assignment.getTimephasedWork(), TimescaleUnits.DAYS, dates);\n for (DateRange range : dates)\n {\n System.out.print(df.format(range.getStart()) + \"\\t\");\n }\n System.out.println();\n for (Duration duration : durations)\n {\n System.out.print(duration.toString() + \" \".substring(0, 7) + \"\\t\");\n }\n System.out.println();\n }\n }", "public void commitWorkingCopy(final String commitMessage) throws IOException, InterruptedException {\n build.getWorkspace().act(new SVNCommitWorkingCopyCallable(commitMessage, getLocation(),\n getSvnAuthenticationProvider(build), buildListener));\n }", "public static <R extends Resource<?>, U extends PaginatedResponse<R>> Flux<R> getResources(U response) {\n return Flux.fromIterable(response.getResources());\n }", "private static boolean typeEquals(ParameterizedType from,\n\t\t\tParameterizedType to, Map<String, Type> typeVarMap) {\n\t\tif (from.getRawType().equals(to.getRawType())) {\n\t\t\tType[] fromArgs = from.getActualTypeArguments();\n\t\t\tType[] toArgs = to.getActualTypeArguments();\n\t\t\tfor (int i = 0; i < fromArgs.length; i++) {\n\t\t\t\tif (!matches(fromArgs[i], toArgs[i], typeVarMap)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}", "protected void checkForPrimaryKeys(final Object realObject) throws ClassNotPersistenceCapableException\r\n {\r\n // if no PKs are specified OJB can't handle this class !\r\n if (m_pkValues == null || m_pkValues.length == 0)\r\n {\r\n throw createException(\"OJB needs at least one primary key attribute for class: \", realObject, null);\r\n }\r\n// arminw: should never happen\r\n// if(m_pkValues[0] instanceof ValueContainer)\r\n// throw new OJBRuntimeException(\"Can't handle pk values of type \"+ValueContainer.class.getName());\r\n }" ]
Returns the total count of the specified event @param event The event for which you want to get the total count @return Total count in int
[ "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public int getCount(String event) {\n EventDetail eventDetail = getLocalDataStore().getEventDetail(event);\n if (eventDetail != null) return eventDetail.getCount();\n\n return -1;\n }" ]
[ "public void delete() {\r\n URL url = DEVICE_PIN_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\r\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"DELETE\");\r\n BoxAPIResponse response = request.send();\r\n response.disconnect();\r\n }", "public PortComponentMetaData getPortComponentByWsdlPort(String name)\n {\n ArrayList<String> pcNames = new ArrayList<String>();\n for (PortComponentMetaData pc : portComponents)\n {\n String wsdlPortName = pc.getWsdlPort().getLocalPart();\n if (wsdlPortName.equals(name))\n return pc;\n\n pcNames.add(wsdlPortName);\n }\n\n Loggers.METADATA_LOGGER.cannotGetPortComponentName(name, pcNames);\n return null;\n }", "public static Map<String, String> mapStringToMap(String map) {\r\n String[] m = map.split(\"[,;]\");\r\n Map<String, String> res = new HashMap<String, String>();\r\n for (String str : m) {\r\n int index = str.lastIndexOf('=');\r\n String key = str.substring(0, index);\r\n String val = str.substring(index + 1);\r\n res.put(key.trim(), val.trim());\r\n }\r\n return res;\r\n }", "public boolean hasNullPKField(ClassDescriptor cld, Object obj)\r\n {\r\n FieldDescriptor[] fields = cld.getPkFields();\r\n boolean hasNull = false;\r\n // an unmaterialized proxy object can never have nullified PK's\r\n IndirectionHandler handler = ProxyHelper.getIndirectionHandler(obj);\r\n if(handler == null || handler.alreadyMaterialized())\r\n {\r\n if(handler != null) obj = handler.getRealSubject();\r\n FieldDescriptor fld;\r\n for(int i = 0; i < fields.length; i++)\r\n {\r\n fld = fields[i];\r\n hasNull = representsNull(fld, fld.getPersistentField().get(obj));\r\n if(hasNull) break;\r\n }\r\n }\r\n return hasNull;\r\n }", "@ArgumentsChecked\n\t@Throws(IllegalNullArgumentException.class)\n\tpublic static double checkDouble(@Nonnull final Number number) {\n\t\tCheck.notNull(number, \"number\");\n\t\tif (!isInDoubleRange(number)) {\n\t\t\tthrow new IllegalNumberRangeException(number.toString(), DOUBLE_MIN, DOUBLE_MAX);\n\t\t}\n\n\t\treturn number.doubleValue();\n\t}", "public static Configuration getDefaultFreemarkerConfiguration()\n {\n freemarker.template.Configuration configuration = new freemarker.template.Configuration(Configuration.VERSION_2_3_26);\n DefaultObjectWrapperBuilder objectWrapperBuilder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_26);\n objectWrapperBuilder.setUseAdaptersForContainers(true);\n objectWrapperBuilder.setIterableSupport(true);\n configuration.setObjectWrapper(objectWrapperBuilder.build());\n configuration.setAPIBuiltinEnabled(true);\n\n configuration.setTemplateLoader(new FurnaceFreeMarkerTemplateLoader());\n configuration.setTemplateUpdateDelayMilliseconds(3600);\n return configuration;\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 }", "private void checkTexRange(AiTextureType type, int index) {\n if (index < 0 || index > m_numTextures.get(type)) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Size: \" +\n m_numTextures.get(type));\n }\n }", "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 }" ]
Creates a check box and adds it to the week panel and the checkboxes. @param internalValue the internal value of the checkbox @param labelMessageKey key for the label of the checkbox
[ "private void addCheckBox(final String internalValue, String labelMessageKey) {\r\n\r\n CmsCheckBox box = new CmsCheckBox(Messages.get().key(labelMessageKey));\r\n box.setInternalValue(internalValue);\r\n box.addValueChangeHandler(new ValueChangeHandler<Boolean>() {\r\n\r\n public void onValueChange(ValueChangeEvent<Boolean> event) {\r\n\r\n if (handleChange()) {\r\n m_controller.weeksChange(internalValue, event.getValue());\r\n }\r\n }\r\n });\r\n m_weekPanel.add(box);\r\n m_checkboxes.add(box);\r\n\r\n }" ]
[ "private String getCurrencyFormat(CurrencySymbolPosition position)\n {\n String result;\n\n switch (position)\n {\n case AFTER:\n {\n result = \"1.1#\";\n break;\n }\n\n case AFTER_WITH_SPACE:\n {\n result = \"1.1 #\";\n break;\n }\n\n case BEFORE_WITH_SPACE:\n {\n result = \"# 1.1\";\n break;\n }\n\n default:\n case BEFORE:\n {\n result = \"#1.1\";\n break;\n }\n }\n\n return result;\n }", "public String isChecked(String value1, String value2) {\n\n if ((value1 == null) || (value2 == null)) {\n return \"\";\n }\n\n if (value1.trim().equalsIgnoreCase(value2.trim())) {\n return \"checked\";\n }\n\n return \"\";\n }", "public String createTorqueSchema(Properties attributes) throws XDocletException\r\n {\r\n String dbName = (String)getDocletContext().getConfigParam(CONFIG_PARAM_DATABASENAME);\r\n\r\n _torqueModel = new TorqueModelDef(dbName, _model);\r\n return \"\";\r\n }", "public final void draw() {\n AffineTransform transform = new AffineTransform(this.transform);\n transform.concatenate(getAlignmentTransform());\n\n // draw the background box\n this.graphics2d.setTransform(transform);\n this.graphics2d.setColor(this.params.getBackgroundColor());\n this.graphics2d.fillRect(0, 0, this.settings.getSize().width, this.settings.getSize().height);\n\n //draw the labels\n this.graphics2d.setColor(this.params.getFontColor());\n drawLabels(transform, this.params.getOrientation(), this.params.getLabelRotation());\n\n //sets the transformation for drawing the bar and do it\n final AffineTransform lineTransform = new AffineTransform(transform);\n setLineTranslate(lineTransform);\n\n if (this.params.getOrientation() == Orientation.VERTICAL_LABELS_LEFT ||\n this.params.getOrientation() == Orientation.VERTICAL_LABELS_RIGHT) {\n final AffineTransform rotate = AffineTransform.getQuadrantRotateInstance(1);\n lineTransform.concatenate(rotate);\n }\n\n this.graphics2d.setTransform(lineTransform);\n this.graphics2d.setStroke(new BasicStroke(this.settings.getLineWidth()));\n this.graphics2d.setColor(this.params.getColor());\n drawBar();\n }", "private void requestPlayerDBServerPort(DeviceAnnouncement announcement) {\n Socket socket = null;\n try {\n InetSocketAddress address = new InetSocketAddress(announcement.getAddress(), DB_SERVER_QUERY_PORT);\n socket = new Socket();\n socket.connect(address, socketTimeout.get());\n InputStream is = socket.getInputStream();\n OutputStream os = socket.getOutputStream();\n socket.setSoTimeout(socketTimeout.get());\n os.write(DB_SERVER_QUERY_PACKET);\n byte[] response = readResponseWithExpectedSize(is, 2, \"database server port query packet\");\n if (response.length == 2) {\n setPlayerDBServerPort(announcement.getNumber(), (int)Util.bytesToNumber(response, 0, 2));\n }\n } catch (java.net.ConnectException ce) {\n logger.info(\"Player \" + announcement.getNumber() +\n \" doesn't answer rekordbox port queries, connection refused. Won't attempt to request metadata.\");\n } catch (Exception e) {\n logger.warn(\"Problem requesting database server port number\", e);\n } finally {\n if (socket != null) {\n try {\n socket.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing database server port request socket\", e);\n }\n }\n }\n }", "@VisibleForTesting\n protected static String createLabelText(\n final DistanceUnit scaleUnit, final double value, final DistanceUnit intervalUnit) {\n double scaledValue = scaleUnit.convertTo(value, intervalUnit);\n\n // assume that there is no interval smaller then 0.0001\n scaledValue = Math.round(scaledValue * 10000) / 10000;\n String decimals = Double.toString(scaledValue).split(\"\\\\.\")[1];\n\n if (Double.valueOf(decimals) == 0) {\n return Long.toString(Math.round(scaledValue));\n } else {\n return Double.toString(scaledValue);\n }\n }", "public BoxFolder.Info restoreFolder(String folderID, String newName, String newParentID) {\n JsonObject requestJSON = new JsonObject();\n\n if (newName != null) {\n requestJSON.add(\"name\", newName);\n }\n\n if (newParentID != null) {\n JsonObject parent = new JsonObject();\n parent.add(\"id\", newParentID);\n requestJSON.add(\"parent\", parent);\n }\n\n URL url = RESTORE_FOLDER_URL_TEMPLATE.build(this.api.getBaseURL(), folderID);\n BoxJSONRequest request = new BoxJSONRequest(this.api, url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxFolder restoredFolder = new BoxFolder(this.api, responseJSON.get(\"id\").asString());\n return restoredFolder.new Info(responseJSON);\n }", "public void 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 long count(nitro_service service, String certkey) throws Exception{\n\t\tsslcertkey_crldistribution_binding obj = new sslcertkey_crldistribution_binding();\n\t\tobj.set_certkey(certkey);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tsslcertkey_crldistribution_binding response[] = (sslcertkey_crldistribution_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}" ]
Given a HTTPResponce, process it, throwing an error if needed and return a Token for the next request.
[ "GcsRestCreationToken handlePutResponse(final GcsRestCreationToken token,\n final boolean isFinalChunk,\n final int length,\n final HTTPRequestInfo reqInfo,\n HTTPResponse resp) throws Error, IOException {\n switch (resp.getResponseCode()) {\n case 200:\n if (!isFinalChunk) {\n throw new RuntimeException(\"Unexpected response code 200 on non-final chunk. Request: \\n\"\n + URLFetchUtils.describeRequestAndResponse(reqInfo, resp));\n } else {\n return null;\n }\n case 308:\n if (isFinalChunk) {\n throw new RuntimeException(\"Unexpected response code 308 on final chunk: \"\n + URLFetchUtils.describeRequestAndResponse(reqInfo, resp));\n } else {\n return new GcsRestCreationToken(token.filename, token.uploadId, token.offset + length);\n }\n default:\n throw HttpErrorHandler.error(resp.getResponseCode(),\n URLFetchUtils.describeRequestAndResponse(reqInfo, resp));\n }\n }" ]
[ "public static base_responses update(nitro_service client, dospolicy resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdospolicy updateresources[] = new dospolicy[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new dospolicy();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].qdepth = resources[i].qdepth;\n\t\t\t\tupdateresources[i].cltdetectrate = resources[i].cltdetectrate;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "public <T extends Variable> T lookupVariable(String token) {\n Variable result = variables.get(token);\n return (T)result;\n }", "protected void onNewParentObject(GVRSceneObject parent) {\n for (GVRComponent comp : mComponents.values()) {\n comp.onNewOwnersParent(parent);\n }\n }", "public void forAllCollectionDefinitions(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _curClassDef.getCollections(); it.hasNext(); )\r\n {\r\n _curCollectionDef = (CollectionDescriptorDef)it.next();\r\n if (!isFeatureIgnored(LEVEL_COLLECTION) &&\r\n !_curCollectionDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))\r\n {\r\n generate(template);\r\n }\r\n }\r\n _curCollectionDef = null;\r\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 }", "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 }", "public static AiScene importFile(String filename) throws IOException {\n \n return importFile(filename, EnumSet.noneOf(AiPostProcessSteps.class));\n }", "public static InstalledIdentity load(final File jbossHome, final ProductConfig productConfig, final File... repoRoots) throws IOException {\n final InstalledImage installedImage = installedImage(jbossHome);\n return load(installedImage, productConfig, Arrays.<File>asList(repoRoots), Collections.<File>emptyList());\n }", "public E setById(final int id, final E element) {\n VListKey<K> key = new VListKey<K>(_key, id);\n UpdateElementById<K, E> updateElementAction = new UpdateElementById<K, E>(key, element);\n\n if(!_storeClient.applyUpdate(updateElementAction))\n throw new ObsoleteVersionException(\"update failed\");\n\n return updateElementAction.getResult();\n }" ]
characters callback.
[ "public void characters(char ch[], int start, int length)\r\n {\r\n if (m_CurrentString == null)\r\n m_CurrentString = new String(ch, start, length);\r\n else\r\n m_CurrentString += new String(ch, start, length);\r\n }" ]
[ "private void initModeSwitch(final EditMode current) {\n\n FormLayout modes = new FormLayout();\n modes.setHeight(\"100%\");\n modes.setDefaultComponentAlignment(Alignment.MIDDLE_LEFT);\n\n m_modeSelect = new ComboBox();\n m_modeSelect.setCaption(m_messages.key(Messages.GUI_VIEW_SWITCHER_LABEL_0));\n\n // add Modes\n m_modeSelect.addItem(CmsMessageBundleEditorTypes.EditMode.DEFAULT);\n m_modeSelect.setItemCaption(\n CmsMessageBundleEditorTypes.EditMode.DEFAULT,\n m_messages.key(Messages.GUI_VIEW_SWITCHER_EDITMODE_DEFAULT_0));\n m_modeSelect.addItem(CmsMessageBundleEditorTypes.EditMode.MASTER);\n m_modeSelect.setItemCaption(\n CmsMessageBundleEditorTypes.EditMode.MASTER,\n m_messages.key(Messages.GUI_VIEW_SWITCHER_EDITMODE_MASTER_0));\n\n // set current mode as selected\n m_modeSelect.setValue(current);\n\n m_modeSelect.setNewItemsAllowed(false);\n m_modeSelect.setTextInputAllowed(false);\n m_modeSelect.setNullSelectionAllowed(false);\n\n m_modeSelect.addValueChangeListener(new ValueChangeListener() {\n\n private static final long serialVersionUID = 1L;\n\n public void valueChange(ValueChangeEvent event) {\n\n m_listener.handleModeChange((EditMode)event.getProperty().getValue());\n\n }\n });\n\n modes.addComponent(m_modeSelect);\n m_modeSwitch = modes;\n }", "public void notifyEventListeners(ZWaveEvent event) {\n\t\tlogger.debug(\"Notifying event listeners\");\n\t\tfor (ZWaveEventListener listener : this.zwaveEventListeners) {\n\t\t\tlogger.trace(\"Notifying {}\", listener.toString());\n\t\t\tlistener.ZWaveIncomingEvent(event);\n\t\t}\n\t}", "public void addColumnIsNull(String column)\r\n {\r\n\t\t// PAW\r\n\t\t//SelectionCriteria c = ValueCriteria.buildNullCriteria(column, getAlias());\r\n\t\tSelectionCriteria c = ValueCriteria.buildNullCriteria(column, getUserAlias(column));\r\n c.setTranslateAttribute(false);\r\n addSelectionCriteria(c);\r\n }", "private void populateResourceAssignment(Record record, ResourceAssignment assignment) throws MPXJException\n {\n //\n // Handle malformed MPX files - ensure that we can locate the resource\n // using either the Unique ID attribute or the ID attribute.\n //\n Resource resource = m_projectFile.getResourceByUniqueID(record.getInteger(12));\n if (resource == null)\n {\n resource = m_projectFile.getResourceByID(record.getInteger(0));\n }\n\n assignment.setUnits(record.getUnits(1));\n assignment.setWork(record.getDuration(2));\n assignment.setBaselineWork(record.getDuration(3));\n assignment.setActualWork(record.getDuration(4));\n assignment.setOvertimeWork(record.getDuration(5));\n assignment.setCost(record.getCurrency(6));\n assignment.setBaselineCost(record.getCurrency(7));\n assignment.setActualCost(record.getCurrency(8));\n assignment.setStart(record.getDateTime(9));\n assignment.setFinish(record.getDateTime(10));\n assignment.setDelay(record.getDuration(11));\n\n //\n // Calculate the remaining work\n //\n Duration work = assignment.getWork();\n Duration actualWork = assignment.getActualWork();\n if (work != null && actualWork != null)\n {\n if (work.getUnits() != actualWork.getUnits())\n {\n actualWork = actualWork.convertUnits(work.getUnits(), m_projectFile.getProjectProperties());\n }\n\n assignment.setRemainingWork(Duration.getInstance(work.getDuration() - actualWork.getDuration(), work.getUnits()));\n }\n\n if (resource != null)\n {\n assignment.setResourceUniqueID(resource.getUniqueID());\n resource.addResourceAssignment(assignment);\n }\n\n m_eventManager.fireAssignmentReadEvent(assignment);\n }", "public static Identity fromByteArray(final byte[] anArray) throws PersistenceBrokerException\r\n {\r\n // reverse of the serialize() algorithm:\r\n // read from byte[] with a ByteArrayInputStream, decompress with\r\n // a GZIPInputStream and then deserialize by reading from the ObjectInputStream\r\n try\r\n {\r\n final ByteArrayInputStream bais = new ByteArrayInputStream(anArray);\r\n final GZIPInputStream gis = new GZIPInputStream(bais);\r\n final ObjectInputStream ois = new ObjectInputStream(gis);\r\n final Identity result = (Identity) ois.readObject();\r\n ois.close();\r\n gis.close();\r\n bais.close();\r\n return result;\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new PersistenceBrokerException(ex);\r\n }\r\n }", "public static Collection<CurrencyUnit> getCurrencies(String... providers) {\n return Optional.ofNullable(MONETARY_CURRENCIES_SINGLETON_SPI()).orElseThrow(\n () -> new MonetaryException(\"No MonetaryCurrenciesSingletonSpi loaded, check your system setup.\"))\n .getCurrencies(providers);\n }", "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 }", "protected Violation createViolation(Integer lineNumber, String sourceLine, String message) {\n Violation violation = new Violation();\n violation.setRule(this);\n violation.setSourceLine(sourceLine);\n violation.setLineNumber(lineNumber);\n violation.setMessage(message);\n return violation;\n }", "private Integer getOutlineLevel(Task task)\n {\n String value = task.getWBS();\n Integer result = Integer.valueOf(1);\n if (value != null && value.length() > 0)\n {\n String[] path = WBS_SPLIT_REGEX.split(value);\n result = Integer.valueOf(path.length);\n }\n return result;\n }" ]
Sets the provided filters. @param filters a map "column id -> filter".
[ "void setFilters(Map<Object, Object> filters) {\n\n for (Object column : filters.keySet()) {\n Object filterValue = filters.get(column);\n if ((filterValue != null) && !filterValue.toString().isEmpty() && !m_table.isColumnCollapsed(column)) {\n m_table.setFilterFieldValue(column, filterValue);\n }\n }\n }" ]
[ "@NonNull public Context getContext() {\n if (searchView != null) {\n return searchView.getContext();\n } else if (supportView != null) {\n return supportView.getContext();\n }\n throw new IllegalStateException(ERROR_NO_SEARCHVIEW);\n }", "public History getHistoryForID(int id) {\n History history = null;\n PreparedStatement query = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n query = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_HISTORY +\n \" WHERE \" + Constants.GENERIC_ID + \"=?\");\n query.setInt(1, id);\n\n logger.info(\"Query: {}\", query.toString());\n results = query.executeQuery();\n if (results.next()) {\n history = historyFromSQLResult(results, true, ScriptService.getInstance().getScripts(Constants.SCRIPT_TYPE_HISTORY));\n }\n query.close();\n } catch (Exception e) {\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 history;\n }", "static ProcessedLayers process(final InstalledConfiguration conf, final List<File> moduleRoots, final List<File> bundleRoots) throws IOException {\n final ProcessedLayers layers = new ProcessedLayers(conf);\n // Process module roots\n final LayerPathSetter moduleSetter = new LayerPathSetter() {\n @Override\n public boolean setPath(final LayerPathConfig pending, final File root) {\n if (pending.modulePath == null) {\n pending.modulePath = root;\n return true;\n }\n return false;\n }\n };\n for (final File moduleRoot : moduleRoots) {\n processRoot(moduleRoot, layers, moduleSetter);\n }\n // Process bundle root\n final LayerPathSetter bundleSetter = new LayerPathSetter() {\n @Override\n public boolean setPath(LayerPathConfig pending, File root) {\n if (pending.bundlePath == null) {\n pending.bundlePath = root;\n return true;\n }\n return false;\n }\n };\n for (final File bundleRoot : bundleRoots) {\n processRoot(bundleRoot, layers, bundleSetter);\n }\n// if (conf.getInstalledLayers().size() != layers.getLayers().size()) {\n// throw processingError(\"processed layers don't match expected %s, but was %s\", conf.getInstalledLayers(), layers.getLayers().keySet());\n// }\n// if (conf.getInstalledAddOns().size() != layers.getAddOns().size()) {\n// throw processingError(\"processed add-ons don't match expected %s, but was %s\", conf.getInstalledAddOns(), layers.getAddOns().keySet());\n// }\n return layers;\n }", "public static base_response clear(nitro_service client, nsconfig resource) throws Exception {\n\t\tnsconfig clearresource = new nsconfig();\n\t\tclearresource.force = resource.force;\n\t\tclearresource.level = resource.level;\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}", "public static void installManagementChannelServices(\n final ServiceTarget serviceTarget,\n final ServiceName endpointName,\n final AbstractModelControllerOperationHandlerFactoryService operationHandlerService,\n final ServiceName modelControllerName,\n final String channelName,\n final ServiceName executorServiceName,\n final ServiceName scheduledExecutorServiceName) {\n\n final OptionMap options = OptionMap.EMPTY;\n final ServiceName operationHandlerName = endpointName.append(channelName).append(ModelControllerClientOperationHandlerFactoryService.OPERATION_HANDLER_NAME_SUFFIX);\n\n serviceTarget.addService(operationHandlerName, operationHandlerService)\n .addDependency(modelControllerName, ModelController.class, operationHandlerService.getModelControllerInjector())\n .addDependency(executorServiceName, ExecutorService.class, operationHandlerService.getExecutorInjector())\n .addDependency(scheduledExecutorServiceName, ScheduledExecutorService.class, operationHandlerService.getScheduledExecutorInjector())\n .setInitialMode(ACTIVE)\n .install();\n\n installManagementChannelOpenListenerService(serviceTarget, endpointName, channelName, operationHandlerName, options, false);\n }", "public ModelNode toModelNode() {\n final ModelNode node = new ModelNode().setEmptyList();\n for (PathElement element : pathAddressList) {\n final String value;\n if (element.isMultiTarget() && !element.isWildcard()) {\n value = '[' + element.getValue() + ']';\n } else {\n value = element.getValue();\n }\n node.add(element.getKey(), value);\n }\n return node;\n }", "public static String getChildValue(Element element, String name) {\r\n return getValue(getChild(element, name));\r\n }", "private void performScriptedStep() {\n double scale = computeBulgeScale();\n if( steps > giveUpOnKnown ) {\n // give up on the script\n followScript = false;\n } else {\n // use previous singular value to step\n double s = values[x2]/scale;\n performImplicitSingleStep(scale,s*s,false);\n }\n }", "private void skip() {\n try {\n int blockSize;\n do {\n blockSize = read();\n rawData.position(rawData.position() + blockSize);\n } while (blockSize > 0);\n } catch (IllegalArgumentException ex) {\n }\n }" ]
Delivers the correct JSON Object for the Stencilset Extensions @param extensions
[ "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 int cudnnOpTensor(\n cudnnHandle handle, \n cudnnOpTensorDescriptor opTensorDesc, \n Pointer alpha1, \n cudnnTensorDescriptor aDesc, \n Pointer A, \n Pointer alpha2, \n cudnnTensorDescriptor bDesc, \n Pointer B, \n Pointer beta, \n cudnnTensorDescriptor cDesc, \n Pointer C)\n {\n return checkResult(cudnnOpTensorNative(handle, opTensorDesc, alpha1, aDesc, A, alpha2, bDesc, B, beta, cDesc, C));\n }", "public String toText() {\n StringBuilder sb = new StringBuilder();\n if (!description.isEmpty()) {\n sb.append(description.toText());\n sb.append(EOL);\n }\n if (!blockTags.isEmpty()) {\n sb.append(EOL);\n }\n for (JavadocBlockTag tag : blockTags) {\n sb.append(tag.toText()).append(EOL);\n }\n return sb.toString();\n }", "public ItemRequest<ProjectStatus> findById(String projectStatus) {\n\n String path = String.format(\"/project_statuses/%s\", projectStatus);\n return new ItemRequest<ProjectStatus>(this, ProjectStatus.class, path, \"GET\");\n }", "protected void processLink(Row row)\n {\n Task predecessorTask = m_project.getTaskByUniqueID(row.getInteger(\"LINK_PRED_UID\"));\n Task successorTask = m_project.getTaskByUniqueID(row.getInteger(\"LINK_SUCC_UID\"));\n if (predecessorTask != null && successorTask != null)\n {\n RelationType type = RelationType.getInstance(row.getInt(\"LINK_TYPE\"));\n TimeUnit durationUnits = MPDUtility.getDurationTimeUnits(row.getInt(\"LINK_LAG_FMT\"));\n Duration duration = MPDUtility.getDuration(row.getDouble(\"LINK_LAG\").doubleValue(), durationUnits);\n Relation relation = successorTask.addPredecessor(predecessorTask, type, duration);\n relation.setUniqueID(row.getInteger(\"LINK_UID\"));\n m_eventManager.fireRelationReadEvent(relation);\n }\n }", "public static base_responses restore(nitro_service client, appfwprofile resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tappfwprofile restoreresources[] = new appfwprofile[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\trestoreresources[i] = new appfwprofile();\n\t\t\t\trestoreresources[i].archivename = resources[i].archivename;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, restoreresources,\"restore\");\n\t\t}\n\t\treturn result;\n\t}", "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 }", "@Override\n public CopticDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }", "protected CompletableFuture<JsonObjectBuilder> makeBuilder(int instanceId) {\n CompletableFuture<T> futureValue = getValue();\n\n if (futureValue == null) {\n logger.error(\"Could not retrieve value \" + this.getClass().getName());\n return null;\n }\n\n return futureValue\n .exceptionally(\n t -> {\n logger.error(\"Could not retrieve value \" + this.getClass().getName(), t);\n return null;\n })\n .thenApply(\n value -> {\n JsonArrayBuilder perms = Json.createArrayBuilder();\n if (isWritable) {\n perms.add(\"pw\");\n }\n if (isReadable) {\n perms.add(\"pr\");\n }\n if (isEventable) {\n perms.add(\"ev\");\n }\n JsonObjectBuilder builder =\n Json.createObjectBuilder()\n .add(\"iid\", instanceId)\n .add(\"type\", shortType)\n .add(\"perms\", perms.build())\n .add(\"format\", format)\n .add(\"ev\", false)\n .add(\"description\", description);\n setJsonValue(builder, value);\n return builder;\n });\n }", "private Map<ConfigurationKey, Object> getObsoleteSystemProperties() {\n Map<ConfigurationKey, Object> found = new EnumMap<ConfigurationKey, Object>(ConfigurationKey.class);\n String concurrentDeployment = getSystemProperty(\"org.jboss.weld.bootstrap.properties.concurrentDeployment\");\n if (concurrentDeployment != null) {\n processKeyValue(found, ConfigurationKey.CONCURRENT_DEPLOYMENT, concurrentDeployment);\n found.put(ConfigurationKey.CONCURRENT_DEPLOYMENT, ConfigurationKey.CONCURRENT_DEPLOYMENT.convertValue(concurrentDeployment));\n }\n String preloaderThreadPoolSize = getSystemProperty(\"org.jboss.weld.bootstrap.properties.preloaderThreadPoolSize\");\n if (preloaderThreadPoolSize != null) {\n found.put(ConfigurationKey.PRELOADER_THREAD_POOL_SIZE, ConfigurationKey.PRELOADER_THREAD_POOL_SIZE.convertValue(preloaderThreadPoolSize));\n }\n return found;\n }" ]
Gets the current Stack. If the stack is not set, a new empty instance is created and set. @return
[ "public static Stack getStack() {\n Stack stack = interceptionContexts.get();\n if (stack == null) {\n stack = new Stack(interceptionContexts);\n interceptionContexts.set(stack);\n }\n return stack;\n }" ]
[ "private String getIntegerString(Number value)\n {\n return (value == null ? null : Integer.toString(value.intValue()));\n }", "private File getDisabledMarkerFile(long version) throws PersistenceFailureException {\n File[] versionDirArray = ReadOnlyUtils.getVersionDirs(rootDir, version, version);\n if (versionDirArray.length == 0) {\n throw new PersistenceFailureException(\"getDisabledMarkerFile did not find the requested version directory\" +\n \" on disk. Version: \" + version + \", rootDir: \" + rootDir);\n }\n File disabledMarkerFile = new File(versionDirArray[0], DISABLED_MARKER_NAME);\n return disabledMarkerFile;\n }", "protected ValueContainer[] getNonKeyValues(PersistenceBroker broker, ClassDescriptor cld, Object obj) throws PersistenceBrokerException\r\n {\r\n return broker.serviceBrokerHelper().getNonKeyRwValues(cld, obj);\r\n }", "protected int readByte(InputStream is) throws IOException\n {\n byte[] data = new byte[1];\n if (is.read(data) != data.length)\n {\n throw new EOFException();\n }\n\n return (MPPUtility.getByte(data, 0));\n }", "public Date getFinish()\n {\n Date result = (Date) getCachedValue(AssignmentField.FINISH);\n if (result == null)\n {\n result = getTask().getFinish();\n }\n return result;\n }", "public static String generateQuery(final String key, final Object value) {\n\t\tfinal Map<String, Object> params = new HashMap<>();\n\t\tparams.put(key, value);\n\t\treturn generateQuery(params);\n\t}", "public Set<Class<?>> getPrevented() {\n if (this.prevent == null) {\n return Collections.emptySet();\n }\n return Collections.unmodifiableSet(this.prevent);\n }", "@Subscribe\n public void onQuit(AggregatedQuitEvent e) {\n if (jsonWriter == null)\n return;\n\n try {\n jsonWriter.endArray();\n\n jsonWriter.name(\"slaves\");\n jsonWriter.beginObject();\n for (Map.Entry<Integer, ForkedJvmInfo> entry : slaves.entrySet()) {\n jsonWriter.name(Integer.toString(entry.getKey()));\n entry.getValue().serialize(jsonWriter);\n }\n jsonWriter.endObject();\n\n jsonWriter.endObject();\n jsonWriter.flush();\n\n if (!Strings.isNullOrEmpty(jsonpMethod)) {\n writer.write(\");\");\n }\n\n jsonWriter.close();\n jsonWriter = null;\n writer = null;\n\n if (method == OutputMethod.HTML) {\n copyScaffolding(targetFile);\n }\n } catch (IOException x) {\n junit4.log(x, Project.MSG_ERR);\n }\n }", "public void setRegularExpression(String regularExpression) {\n\t\tif (regularExpression != null)\n\t\t\tthis.regularExpression = Pattern.compile(regularExpression);\n\t\telse\n\t\t\tthis.regularExpression = null;\n\t}" ]
Removes the given key with its associated element from the receiver, if present. @param key the key to be removed from the receiver. @return <tt>true</tt> if the receiver contained the specified key, <tt>false</tt> otherwise.
[ "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 int getBlockLength(String text, int offset)\n {\n int startIndex = offset;\n boolean finished = false;\n char c;\n\n while (finished == false)\n {\n c = text.charAt(offset);\n switch (c)\n {\n case '\\r':\n case '\\n':\n case '}':\n {\n finished = true;\n break;\n }\n\n default:\n {\n ++offset;\n break;\n }\n }\n }\n\n int length = offset - startIndex;\n\n return (length);\n }", "protected X509Certificate wireUpSslWithCyberVilliansCAOdo(String host, SslListener listener) {\n host = requestOriginalHostName.get();\n\n // Add cybervillians CA(from browsermob)\n try {\n // see https://github.com/webmetrics/browsermob-proxy/issues/105\n String escapedHost = host.replace('*', '_');\n\n KeyStoreManager keyStoreManager = Utils.getKeyStoreManager(escapedHost);\n keyStoreManager.getKeyStore().deleteEntry(KeyStoreManager._caPrivKeyAlias);\n keyStoreManager.persist();\n listener.setKeystore(new File(\"seleniumSslSupport\" + File.separator + escapedHost + File.separator + \"cybervillainsCA.jks\").getAbsolutePath());\n\n return keyStoreManager.getCertificateByAlias(escapedHost);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }", "public T transitInt(int propertyId, int... vals) {\n String property = getPropertyName(propertyId);\n mHolders.put(propertyId, PropertyValuesHolder.ofInt(property, vals));\n mShadowHolders.put(propertyId, ShadowValuesHolder.ofInt(property, vals));\n return self();\n }", "private static void validate(String name, Collection<Geometry> geometries, int extent) {\n if (name == null) {\n throw new IllegalArgumentException(\"layer name is null\");\n }\n if (geometries == null) {\n throw new IllegalArgumentException(\"geometry collection is null\");\n }\n if (extent <= 0) {\n throw new IllegalArgumentException(\"extent is less than or equal to 0\");\n }\n }", "public CollectionValuedMap<K, V> deltaClone() {\r\n CollectionValuedMap<K, V> result = new CollectionValuedMap<K, V>(null, cf, true);\r\n result.map = new DeltaMap<K, Collection<V>>(this.map);\r\n return result;\r\n }", "@SuppressWarnings(\"WeakerAccess\")\n public synchronized void stop() {\n if (isRunning()) {\n final Set<DeviceAnnouncement> lastDevices = getCurrentDevices();\n socket.get().close();\n socket.set(null);\n devices.clear();\n firstDeviceTime.set(0);\n // Report the loss of all our devices, on the proper thread, outside our lock\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (DeviceAnnouncement announcement : lastDevices) {\n deliverLostAnnouncement(announcement);\n }\n }\n });\n deliverLifecycleAnnouncement(logger, false);\n }\n }", "public Map<String, Integer> getAggregateResultCountSummary() {\n\n Map<String, Integer> summaryMap = new LinkedHashMap<String, Integer>();\n\n for (Entry<String, LinkedHashSet<String>> entry : aggregateResultMap\n .entrySet()) {\n summaryMap.put(entry.getKey(), entry.getValue().size());\n }\n\n return summaryMap;\n }", "public ItemRequest<Task> removeDependents(String task) {\n \n String path = String.format(\"/tasks/%s/removeDependents\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }", "public static long stopNamedTimer(String timerName, int todoFlags) {\n\t\treturn stopNamedTimer(timerName, todoFlags, Thread.currentThread()\n\t\t\t\t.getId());\n\t}" ]
Use this API to fetch cacheselector resources of given names .
[ "public static cacheselector[] get(nitro_service service, String selectorname[]) throws Exception{\n\t\tif (selectorname !=null && selectorname.length>0) {\n\t\t\tcacheselector response[] = new cacheselector[selectorname.length];\n\t\t\tcacheselector obj[] = new cacheselector[selectorname.length];\n\t\t\tfor (int i=0;i<selectorname.length;i++) {\n\t\t\t\tobj[i] = new cacheselector();\n\t\t\t\tobj[i].set_selectorname(selectorname[i]);\n\t\t\t\tresponse[i] = (cacheselector) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}" ]
[ "public final void configureAccess(final Template template, final ApplicationContext context) {\n final Configuration configuration = template.getConfiguration();\n\n AndAccessAssertion accessAssertion = context.getBean(AndAccessAssertion.class);\n accessAssertion.setPredicates(configuration.getAccessAssertion(), template.getAccessAssertion());\n this.access = accessAssertion;\n }", "public void put(@NotNull final Transaction txn, final long localId,\n final int blobId, @NotNull final ByteIterable value) {\n primaryStore.put(txn, PropertyKey.propertyKeyToEntry(new PropertyKey(localId, blobId)), value);\n allBlobsIndex.put(txn, IntegerBinding.intToCompressedEntry(blobId), LongBinding.longToCompressedEntry(localId));\n }", "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 }", "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 static void saveContentMap(Map<String, String> map, File file) throws IOException {\n\n FileWriter out = new FileWriter(file);\n for (String key : map.keySet()) {\n if (map.get(key) != null) {\n out.write(key.replace(\":\", \"#escapedtwodots#\") + \":\"\n + map.get(key).replace(\":\", \"#escapedtwodots#\") + \"\\r\\n\");\n }\n }\n out.close();\n }", "private void onClickAdd() {\n\n if (m_currentLocation.isPresent()) {\n CmsFavoriteEntry entry = m_currentLocation.get();\n List<CmsFavoriteEntry> entries = getEntries();\n entries.add(entry);\n try {\n m_favDao.saveFavorites(entries);\n } catch (Exception e) {\n CmsErrorDialog.showErrorDialog(e);\n }\n m_context.close();\n }\n }", "protected void clearStatementCaches(boolean internalClose) {\r\n\r\n\t\tif (this.statementCachingEnabled){ // safety\r\n\r\n\t\t\tif (internalClose){\r\n\t\t\t\tthis.callableStatementCache.clear();\r\n\t\t\t\tthis.preparedStatementCache.clear();\r\n\t\t\t} else {\r\n\t\t\t\tif (this.pool.closeConnectionWatch){ // debugging enabled?\r\n\t\t\t\t\tthis.callableStatementCache.checkForProperClosure();\r\n\t\t\t\t\tthis.preparedStatementCache.checkForProperClosure();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}", "public static long count(nitro_service service, Long id) throws Exception{\n\t\tbridgegroup_vlan_binding obj = new bridgegroup_vlan_binding();\n\t\tobj.set_id(id);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tbridgegroup_vlan_binding response[] = (bridgegroup_vlan_binding[]) obj.get_resources(service,option);\n\t\tif (response != null) {\n\t\t\treturn response[0].__count;\n\t\t}\n\t\treturn 0;\n\t}", "public static void unregisterContextualInstance(EjbDescriptor<?> descriptor) {\n Set<Class<?>> classes = CONTEXTUAL_SESSION_BEANS.get();\n classes.remove(descriptor.getBeanClass());\n if (classes.isEmpty()) {\n CONTEXTUAL_SESSION_BEANS.remove();\n }\n }" ]
Links the given widget to InstantSearch according to the interfaces it implements. @param widget a widget implementing ({@link AlgoliaResultsListener} || {@link AlgoliaErrorListener} || {@link AlgoliaSearcherListener}).
[ "@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public void registerWidget(View widget) {\n prepareWidget(widget);\n\n if (widget instanceof AlgoliaResultsListener) {\n AlgoliaResultsListener listener = (AlgoliaResultsListener) widget;\n if (!this.resultListeners.contains(listener)) {\n this.resultListeners.add(listener);\n }\n searcher.registerResultListener(listener);\n }\n if (widget instanceof AlgoliaErrorListener) {\n AlgoliaErrorListener listener = (AlgoliaErrorListener) widget;\n if (!this.errorListeners.contains(listener)) {\n this.errorListeners.add(listener);\n }\n searcher.registerErrorListener(listener);\n }\n if (widget instanceof AlgoliaSearcherListener) {\n AlgoliaSearcherListener listener = (AlgoliaSearcherListener) widget;\n listener.initWithSearcher(searcher);\n }\n }" ]
[ "static InternationalFixedDate create(int prolepticYear, int month, int dayOfMonth) {\n YEAR_RANGE.checkValidValue(prolepticYear, ChronoField.YEAR_OF_ERA);\n MONTH_OF_YEAR_RANGE.checkValidValue(month, ChronoField.MONTH_OF_YEAR);\n DAY_OF_MONTH_RANGE.checkValidValue(dayOfMonth, ChronoField.DAY_OF_MONTH);\n\n if (dayOfMonth == DAYS_IN_LONG_MONTH && month != 6 && month != MONTHS_IN_YEAR) {\n throw new DateTimeException(\"Invalid date: \" + prolepticYear + '/' + month + '/' + dayOfMonth);\n }\n if (month == 6 && dayOfMonth == DAYS_IN_LONG_MONTH && !INSTANCE.isLeapYear(prolepticYear)) {\n throw new DateTimeException(\"Invalid Leap Day as '\" + prolepticYear + \"' is not a leap year\");\n }\n return new InternationalFixedDate(prolepticYear, month, dayOfMonth);\n }", "@PrefMetadata(type = CmsHiddenBuiltinPreference.class)\n public String getExplorerFileEntryOptions() {\n\n if (m_settings.getExplorerFileEntryOptions() == null) {\n return \"\";\n } else {\n return \"\" + m_settings.getExplorerFileEntryOptions();\n }\n }", "public void setDividerPadding(float padding, final Axis axis) {\n if (axis == getOrientationAxis()) {\n super.setDividerPadding(padding, axis);\n } else {\n Log.w(TAG, \"Cannot apply divider padding for wrong axis [%s], orientation = %s\",\n axis, getOrientation());\n }\n }", "private List<UDFAssignmentType> writeUDFType(FieldTypeClass type, FieldContainer mpxj)\n {\n List<UDFAssignmentType> out = new ArrayList<UDFAssignmentType>();\n for (CustomField cf : m_sortedCustomFieldsList)\n {\n FieldType fieldType = cf.getFieldType();\n if (fieldType != null && type == fieldType.getFieldTypeClass())\n {\n Object value = mpxj.getCachedValue(fieldType);\n if (FieldTypeHelper.valueIsNotDefault(fieldType, value))\n {\n UDFAssignmentType udf = m_factory.createUDFAssignmentType();\n udf.setTypeObjectId(FieldTypeHelper.getFieldID(fieldType));\n setUserFieldValue(udf, fieldType.getDataType(), value);\n out.add(udf);\n }\n }\n }\n return out;\n }", "public static String truncate(int n, int smallestDigit, int biggestDigit) {\r\n int numDigits = biggestDigit - smallestDigit + 1;\r\n char[] result = new char[numDigits];\r\n for (int j = 1; j < smallestDigit; j++) {\r\n n = n / 10;\r\n }\r\n for (int j = numDigits - 1; j >= 0; j--) {\r\n result[j] = Character.forDigit(n % 10, 10);\r\n n = n / 10;\r\n }\r\n return new String(result);\r\n }", "public Conditionals ifModifiedSince(LocalDateTime time) {\n Preconditions.checkArgument(match.isEmpty(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MODIFIED_SINCE, HeaderConstants.IF_MATCH));\n Preconditions.checkArgument(!unModifiedSince.isPresent(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MODIFIED_SINCE, HeaderConstants.IF_UNMODIFIED_SINCE));\n time = time.withNano(0);\n return new Conditionals(empty(), noneMatch, Optional.of(time), Optional.empty());\n }", "public Class<T> getProxyClass() {\n String suffix = \"_$$_Weld\" + getProxyNameSuffix();\n String proxyClassName = getBaseProxyName();\n if (!proxyClassName.endsWith(suffix)) {\n proxyClassName = proxyClassName + suffix;\n }\n if (proxyClassName.startsWith(JAVA)) {\n proxyClassName = proxyClassName.replaceFirst(JAVA, \"org.jboss.weld\");\n }\n Class<T> proxyClass = null;\n Class<?> originalClass = bean != null ? bean.getBeanClass() : proxiedBeanType;\n BeanLogger.LOG.generatingProxyClass(proxyClassName);\n try {\n // First check to see if we already have this proxy class\n proxyClass = cast(classLoader == null? proxyServices.loadClass(originalClass, proxyClassName) : classLoader.loadClass(proxyClassName));\n } catch (ClassNotFoundException e) {\n // Create the proxy class for this instance\n try {\n proxyClass = createProxyClass(originalClass, proxyClassName);\n } catch (Throwable e1) {\n //attempt to load the class again, just in case another thread\n //defined it between the check and the create method\n try {\n proxyClass = cast(classLoader == null? proxyServices.loadClass(originalClass, proxyClassName) : classLoader.loadClass(proxyClassName));\n } catch (ClassNotFoundException e2) {\n BeanLogger.LOG.catchingDebug(e1);\n throw BeanLogger.LOG.unableToLoadProxyClass(bean, proxiedBeanType, e1);\n }\n }\n }\n return proxyClass;\n }", "public static <ObjType, Hashable> Collection<ObjType> uniqueNonhashableObjects(Collection<ObjType> objects, Function<ObjType, Hashable> customHasher) {\r\n Map<Hashable, ObjType> hashesToObjects = new HashMap<Hashable, ObjType>();\r\n for (ObjType object : objects) {\r\n hashesToObjects.put(customHasher.apply(object), object);\r\n }\r\n return hashesToObjects.values();\r\n }", "private Options getOptions() {\n\t\tOptions options = new Options();\n\t\toptions.addOption(\"h\", HELP, false, \"print this message\");\n\t\toptions.addOption(VERSION, false, \"print the version information and exit\");\n\n\t\toptions.addOption(\"b\", BROWSER, true,\n\t\t \"browser type: \" + availableBrowsers() + \". Default is Firefox\");\n\n\t\toptions.addOption(BROWSER_REMOTE_URL, true,\n\t\t \"The remote url if you have configured a remote browser\");\n\n\t\toptions.addOption(\"d\", DEPTH, true, \"crawl depth level. Default is 2\");\n\n\t\toptions.addOption(\"s\", MAXSTATES, true,\n\t\t \"max number of states to crawl. Default is 0 (unlimited)\");\n\n\t\toptions.addOption(\"p\", PARALLEL, true,\n\t\t \"Number of browsers to use for crawling. Default is 1\");\n\t\toptions.addOption(\"o\", OVERRIDE, false, \"Override the output directory if non-empty\");\n\n\t\toptions.addOption(\"a\", CRAWL_HIDDEN_ANCHORS, false,\n\t\t \"Crawl anchors even if they are not visible in the browser.\");\n\n\t\toptions.addOption(\"t\", TIME_OUT, true,\n\t\t \"Specify the maximum crawl time in minutes\");\n\n\t\toptions.addOption(CLICK, true,\n\t\t \"a comma separated list of HTML tags that should be clicked. Default is A and BUTTON\");\n\n\t\toptions.addOption(WAIT_AFTER_EVENT, true,\n\t\t \"the time to wait after an event has been fired in milliseconds. Default is \"\n\t\t + CrawlRules.DEFAULT_WAIT_AFTER_EVENT);\n\n\t\toptions.addOption(WAIT_AFTER_RELOAD, true,\n\t\t \"the time to wait after an URL has been loaded in milliseconds. Default is \"\n\t\t + CrawlRules.DEFAULT_WAIT_AFTER_RELOAD);\n\n\t\toptions.addOption(\"v\", VERBOSE, false, \"Be extra verbose\");\n\t\toptions.addOption(LOG_FILE, true, \"Log to this file instead of the console\");\n\n\t\treturn options;\n\t}" ]
Used when setting the "visible" field in the response. See the "List Conversations" docs for details @param filters Filter strings to be applied to the visibility of conversations @return this to continue building options
[ "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 }" ]
[ "public String login(Authentication authentication) {\n\t\tString token = getToken();\n\t\treturn login(token, authentication);\n\t}", "String getQueryString(Map<String, String> params) {\n\t\tStringBuilder builder = new StringBuilder();\n\t\ttry {\n\t\t\tboolean first = true;\n\t\t\tfor (Map.Entry<String,String> entry : params.entrySet()) {\n\t\t\t\tif (first) {\n\t\t\t\t\tfirst = false;\n\t\t\t\t} else {\n\t\t\t\t\tbuilder.append(\"&\");\n\t\t\t\t}\n\t\t\t\tbuilder.append(URLEncoder.encode(entry.getKey(), \"UTF-8\"));\n\t\t\t\tbuilder.append(\"=\");\n\t\t\t\tbuilder.append(URLEncoder.encode(entry.getValue(), \"UTF-8\"));\n\t\t\t}\n\t\t} catch (UnsupportedEncodingException e) {\n\t\t\tthrow new RuntimeException(\n\t\t\t\t\t\"Your Java version does not support UTF-8 encoding.\");\n\t\t}\n\n\t\treturn builder.toString();\n\t}", "public String processProcedureArgument(Properties attributes) throws XDocletException\r\n {\r\n String id = attributes.getProperty(ATTRIBUTE_NAME);\r\n ProcedureArgumentDef argDef = _curClassDef.getProcedureArgument(id);\r\n String attrName;\r\n \r\n if (argDef == null)\r\n { \r\n argDef = new ProcedureArgumentDef(id);\r\n _curClassDef.addProcedureArgument(argDef);\r\n }\r\n\r\n attributes.remove(ATTRIBUTE_NAME);\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n argDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n return \"\";\r\n }", "private void addListeners(ProjectReader reader)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n reader.addProjectListener(listener);\n }\n }\n }", "Document convertSelectorToDocument(Document selector) {\n Document document = new Document();\n for (String key : selector.keySet()) {\n if (key.startsWith(\"$\")) {\n continue;\n }\n\n Object value = selector.get(key);\n if (!Utils.containsQueryExpression(value)) {\n Utils.changeSubdocumentValue(document, key, value, (AtomicReference<Integer>) null);\n }\n }\n return document;\n }", "@Programmatic\n public <T> Blob toExcelPivot(\n final List<T> domainObjects,\n final Class<T> cls,\n final String fileName) throws ExcelService.Exception {\n return toExcelPivot(domainObjects, cls, null, fileName);\n }", "public boolean unlink(Object source, String attributeName, Object target)\r\n {\r\n return linkOrUnlink(false, source, attributeName, false);\r\n }", "public static FormValidation validateEmails(String emails) {\n if (!Strings.isNullOrEmpty(emails)) {\n String[] recipients = StringUtils.split(emails, \" \");\n for (String email : recipients) {\n FormValidation validation = validateInternetAddress(email);\n if (validation != FormValidation.ok()) {\n return validation;\n }\n }\n }\n return FormValidation.ok();\n }", "@Override\n public void writeText(PDDocument doc, Writer outputStream) throws IOException\n {\n try\n {\n DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();\n DOMImplementationLS impl = (DOMImplementationLS)registry.getDOMImplementation(\"LS\");\n LSSerializer writer = impl.createLSSerializer();\n LSOutput output = impl.createLSOutput();\n writer.getDomConfig().setParameter(\"format-pretty-print\", true);\n output.setCharacterStream(outputStream);\n createDOM(doc);\n writer.write(getDocument(), output);\n } catch (ClassCastException e) {\n throw new IOException(\"Error: cannot initialize the DOM serializer\", e);\n } catch (ClassNotFoundException e) {\n throw new IOException(\"Error: cannot initialize the DOM serializer\", e);\n } catch (InstantiationException e) {\n throw new IOException(\"Error: cannot initialize the DOM serializer\", e);\n } catch (IllegalAccessException e) {\n throw new IOException(\"Error: cannot initialize the DOM serializer\", e);\n }\n }" ]
Sets the bottom padding for all cells in the table. @param paddingBottom new padding, ignored if smaller than 0 @return this to allow chaining
[ "public AsciiTable setPaddingBottom(int paddingBottom) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingBottom(paddingBottom);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}" ]
[ "public PhotoList<Photo> getPublicPhotos(String userId, Set<String> extras, int perPage, int page) throws FlickrException {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PUBLIC_PHOTOS);\r\n\r\n parameters.put(\"user_id\", userId);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n\r\n if (extras != null) {\r\n parameters.put(Extras.KEY_EXTRAS, StringUtilities.join(extras, \",\"));\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n photos.setPage(photosElement.getAttribute(\"page\"));\r\n photos.setPages(photosElement.getAttribute(\"pages\"));\r\n photos.setPerPage(photosElement.getAttribute(\"perpage\"));\r\n photos.setTotal(photosElement.getAttribute(\"total\"));\r\n\r\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element photoElement = (Element) photoNodes.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement));\r\n }\r\n return photos;\r\n }", "public Task<RemoteInsertOneResult> insertOne(final DocumentT document) {\n return dispatcher.dispatchTask(new Callable<RemoteInsertOneResult>() {\n @Override\n public RemoteInsertOneResult call() {\n return proxy.insertOne(document);\n }\n });\n }", "private int[] changeColor() {\n int[] changedPixels = new int[pixels.length];\n double frequenz = 2 * Math.PI / 1020;\n\n for (int i = 0; i < pixels.length; i++) {\n int argb = pixels[i];\n int a = (argb >> 24) & 0xff;\n int r = (argb >> 16) & 0xff;\n int g = (argb >> 8) & 0xff;\n int b = argb & 0xff;\n\n r = (int) (255 * Math.sin(frequenz * r));\n b = (int) (-255 * Math.cos(frequenz * b) + 255);\n\n changedPixels[i] = (a << 24) | (r << 16) | (g << 8) | b;\n }\n\n return changedPixels;\n }", "private synchronized JsonSchema getInputPathJsonSchema() throws IOException {\n if (inputPathJsonSchema == null) {\n // No need to query Hadoop more than once as this shouldn't change mid-run,\n // thus, we can lazily initialize and cache the result.\n inputPathJsonSchema = HadoopUtils.getSchemaFromPath(getInputPath());\n }\n return inputPathJsonSchema;\n }", "private boolean relevant(File currentLogFile, GregorianCalendar lastRelevantDate) {\n\t\tString fileName=currentLogFile.getName();\n\t\tPattern p = Pattern.compile(APPENER_DATE_DEFAULT_PATTERN);\n\t\tMatcher m = p.matcher(fileName);\n\t\tif(m.find()){\n\t\t\tint year=Integer.parseInt(m.group(1));\n\t\t\tint month=Integer.parseInt(m.group(2));\n\t\t\tint dayOfMonth=Integer.parseInt(m.group(3));\n\t\t\tGregorianCalendar fileDate=new GregorianCalendar(year, month, dayOfMonth);\n\t\t\tfileDate.add(Calendar.MONTH,-1); //Because of Calendar save the month such that January is 0\n\t\t\treturn fileDate.compareTo(lastRelevantDate)>0;\n\t\t}\n\t\telse{\n\t\t\treturn false;\n\t\t}\n\t}", "public static String getPostString(InputStream is, String encoding) {\n try {\n StringWriter sw = new StringWriter();\n IOUtils.copy(is, sw, encoding);\n\n return sw.toString();\n } catch (IOException e) {\n // no op\n return null;\n } finally {\n IOUtils.closeQuietly(is);\n }\n }", "static GVRPickedObject makeHitMesh(long colliderPointer, float distance, float hitx, float hity, float hitz,\n int faceIndex, float barycentricx, float barycentricy, float barycentricz,\n float texu, float texv, float normalx, float normaly, float normalz)\n {\n GVRCollider collider = GVRCollider.lookup(colliderPointer);\n if (collider == null)\n {\n Log.d(TAG, \"makeHit: cannot find collider for %x\", colliderPointer);\n return null;\n }\n return new GVRPicker.GVRPickedObject(collider, new float[] { hitx, hity, hitz }, distance, faceIndex,\n new float[] {barycentricx, barycentricy, barycentricz},\n new float[]{ texu, texv },\n new float[]{normalx, normaly, normalz});\n }", "private static void checkPreconditions(List<String> requiredSubStrings) {\n\t\tif( requiredSubStrings == null ) {\n\t\t\tthrow new NullPointerException(\"requiredSubStrings List should not be null\");\n\t\t} else if( requiredSubStrings.isEmpty() ) {\n\t\t\tthrow new IllegalArgumentException(\"requiredSubStrings List should not be empty\");\n\t\t}\n\t}", "@Override\n protected StatisticsMatrix createMatrix(int numRows, int numCols, MatrixType type) {\n return new StatisticsMatrix(numRows,numCols);\n }" ]
Looks up the EJB in the container and executes the method on it @param self the proxy instance. @param method the overridden method declared in the super class or interface. @param proceed the forwarder method for invoking the overridden method. It is null if the overridden method is abstract or declared in the interface. @param args an array of objects containing the values of the arguments passed in the method invocation on the proxy instance. If a parameter type is a primitive type, the type of the array element is a wrapper class. @return the resulting value of the method invocation. @throws Throwable if the method invocation fails.
[ "@Override\n public Object invoke(Object self, Method method, Method proceed, Object[] args) throws Throwable {\n if (\"destroy\".equals(method.getName()) && Marker.isMarker(0, method, args)) {\n if (bean.getEjbDescriptor().isStateful()) {\n if (!reference.isRemoved()) {\n reference.remove();\n }\n }\n return null;\n }\n\n if (!bean.isClientCanCallRemoveMethods() && isRemoveMethod(method)) {\n throw BeanLogger.LOG.invalidRemoveMethodInvocation(method);\n }\n Class<?> businessInterface = getBusinessInterface(method);\n if (reference.isRemoved() && isToStringMethod(method)) {\n return businessInterface.getName() + \" [REMOVED]\";\n }\n Object proxiedInstance = reference.getBusinessObject(businessInterface);\n\n if (!Modifier.isPublic(method.getModifiers())) {\n throw new EJBException(\"Not a business method \" + method.toString() +\". Do not call non-public methods on EJB's.\");\n }\n Object returnValue = Reflections.invokeAndUnwrap(proxiedInstance, method, args);\n BeanLogger.LOG.callProxiedMethod(method, proxiedInstance, args, returnValue);\n return returnValue;\n }" ]
[ "@Override\n public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {\n final ServletRequest r1 = request;\n chain.doFilter(request, new HttpServletResponseWrapper((HttpServletResponse) response) {\n @SuppressWarnings(\"unchecked\")\n public void setHeader(String name, String value) {\n ArrayList<String> headersToRemove = new ArrayList<String>();\n \n if (r1.getAttribute(\"com.groupon.odo.removeHeaders\") != null)\n headersToRemove = (ArrayList<String>) r1.getAttribute(\"com.groupon.odo.removeHeaders\");\n\n boolean removeHeader = false;\n // need to loop through removeHeaders to make things case insensitive\n for (String headerToRemove : headersToRemove) {\n if (headerToRemove.toLowerCase().equals(name.toLowerCase())) {\n removeHeader = true;\n break;\n }\n }\n\n if (! removeHeader) {\n super.setHeader(name, value);\n }\n }\n });\n }", "private void populateEntityMap() throws SQLException\n {\n for (Row row : getRows(\"select * from z_primarykey\"))\n {\n m_entityMap.put(row.getString(\"Z_NAME\"), row.getInteger(\"Z_ENT\"));\n }\n }", "@SuppressWarnings(\"WeakerAccess\")\n public Color segmentColor(final int segment, final boolean front) {\n final ByteBuffer bytes = getData();\n if (isColor) {\n final int base = segment * 6;\n final int backHeight = segmentHeight(segment, false);\n if (backHeight == 0) {\n return Color.BLACK;\n }\n final int maxLevel = front? 255 : 191;\n final int red = Util.unsign(bytes.get(base + 3)) * maxLevel / backHeight;\n final int green = Util.unsign(bytes.get(base + 4)) * maxLevel / backHeight;\n final int blue = Util.unsign(bytes.get(base + 5)) * maxLevel / backHeight;\n return new Color(red, green, blue);\n } else {\n final int intensity = getData().get(segment * 2 + 1) & 0x07;\n return (intensity >= 5) ? INTENSE_COLOR : NORMAL_COLOR;\n }\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 }", "public List<File> getAutoAttachCacheFiles() {\n ArrayList<File> currentFiles = new ArrayList<File>(autoAttachCacheFiles);\n Collections.sort(currentFiles, new Comparator<File>() {\n @Override\n public int compare(File o1, File o2) {\n return o1.getName().compareTo(o2.getName());\n }\n });\n return Collections.unmodifiableList(currentFiles);\n }", "public AT_Row setHtmlElementTranslator(HtmlElementTranslator htmlElementTranslator) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setHtmlElementTranslator(htmlElementTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public static boolean isFileExist(String filePath) {\n\n File f = new File(filePath);\n\n return f.exists() && !f.isDirectory();\n }", "public static void addToString(\n SourceBuilder code,\n Datatype datatype,\n Map<Property, PropertyCodeGenerator> generatorsByProperty,\n boolean forPartial) {\n String typename = (forPartial ? \"partial \" : \"\") + datatype.getType().getSimpleName();\n Predicate<PropertyCodeGenerator> isOptional = generator -> {\n Initially initially = generator.initialState();\n return (initially == Initially.OPTIONAL || (initially == Initially.REQUIRED && forPartial));\n };\n boolean anyOptional = generatorsByProperty.values().stream().anyMatch(isOptional);\n boolean allOptional = generatorsByProperty.values().stream().allMatch(isOptional)\n && !generatorsByProperty.isEmpty();\n\n code.addLine(\"\")\n .addLine(\"@%s\", Override.class)\n .addLine(\"public %s toString() {\", String.class);\n if (allOptional) {\n bodyWithBuilderAndSeparator(code, datatype, generatorsByProperty, typename);\n } else if (anyOptional) {\n bodyWithBuilder(code, datatype, generatorsByProperty, typename, isOptional);\n } else {\n bodyWithConcatenation(code, generatorsByProperty, typename);\n }\n code.addLine(\"}\");\n }", "public T transitInt(int propertyId, int... vals) {\n String property = getPropertyName(propertyId);\n mHolders.put(propertyId, PropertyValuesHolder.ofInt(property, vals));\n mShadowHolders.put(propertyId, ShadowValuesHolder.ofInt(property, vals));\n return self();\n }" ]
Returns the name of the class to be instantiated. @param rs the Resultset @return null if the column is not available
[ "public static String getOjbClassName(ResultSet rs)\r\n {\r\n try\r\n {\r\n return rs.getString(OJB_CLASS_COLUMN);\r\n }\r\n catch (SQLException e)\r\n {\r\n return null;\r\n }\r\n }" ]
[ "public static boolean isResourceTypeIdFree(int id) {\n\n try {\n OpenCms.getResourceManager().getResourceType(id);\n } catch (CmsLoaderException e) {\n return true;\n }\n return false;\n }", "public static int getDayAsReadableInt(Calendar calendar) {\n int day = calendar.get(Calendar.DAY_OF_MONTH);\n int month = calendar.get(Calendar.MONTH) + 1;\n int year = calendar.get(Calendar.YEAR);\n return year * 10000 + month * 100 + day;\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 final void begin() {\n this.file = this.getAppender().getIoFile();\n if (this.file == null) {\n this.getAppender().getErrorHandler()\n .error(\"Scavenger not started: missing log file name\");\n return;\n }\n if (this.getProperties().getScavengeInterval() > -1) {\n final Thread thread = new Thread(this, \"Log4J File Scavenger\");\n thread.setDaemon(true);\n thread.start();\n this.threadRef = thread;\n }\n }", "public static void main(String[] args) {\n CmdLine cmd = new CmdLine();\n Configuration conf = new Configuration();\n int res = 0;\n try {\n res = ToolRunner.run(conf, cmd, args);\n } catch (Exception e) {\n System.err.println(\"Error while running MR job\");\n e.printStackTrace();\n }\n System.exit(res);\n }", "public static cacheselector get(nitro_service service, String selectorname) throws Exception{\n\t\tcacheselector obj = new cacheselector();\n\t\tobj.set_selectorname(selectorname);\n\t\tcacheselector response = (cacheselector) obj.get_resource(service);\n\t\treturn response;\n\t}", "@Beta(SinceVersion.V1_1_0)\n public void close() {\n httpClient.dispatcher().executorService().shutdown();\n httpClient.connectionPool().evictAll();\n synchronized (httpClient.connectionPool()) {\n httpClient.connectionPool().notifyAll();\n }\n synchronized (AsyncTimeout.class) {\n AsyncTimeout.class.notifyAll();\n }\n }", "public static clusternodegroup_nslimitidentifier_binding[] get(nitro_service service, String name) throws Exception{\n\t\tclusternodegroup_nslimitidentifier_binding obj = new clusternodegroup_nslimitidentifier_binding();\n\t\tobj.set_name(name);\n\t\tclusternodegroup_nslimitidentifier_binding response[] = (clusternodegroup_nslimitidentifier_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private void updateHostingEntityIfRequired() {\n\t\tif ( hostingEntity != null && hostingEntityRequiresReadAfterUpdate() ) {\n\t\t\tOgmEntityPersister entityPersister = getHostingEntityPersister();\n\n\t\t\tif ( GridDialects.hasFacet( gridDialect, GroupingByEntityDialect.class ) ) {\n\t\t\t\t( (GroupingByEntityDialect) gridDialect ).flushPendingOperations( getAssociationKey().getEntityKey(),\n\t\t\t\t\t\tentityPersister.getTupleContext( session ) );\n\t\t\t}\n\n\t\t\tentityPersister.processUpdateGeneratedProperties(\n\t\t\t\t\tentityPersister.getIdentifier( hostingEntity, session ),\n\t\t\t\t\thostingEntity,\n\t\t\t\t\tnew Object[entityPersister.getPropertyNames().length],\n\t\t\t\t\tsession\n\t\t\t);\n\t\t}\n\t}" ]
set the textColor of the ColorHolder to an drawable @param ctx @param drawable
[ "public void applyTo(Context ctx, GradientDrawable drawable) {\n if (mColorInt != 0) {\n drawable.setColor(mColorInt);\n } else if (mColorRes != -1) {\n drawable.setColor(ContextCompat.getColor(ctx, mColorRes));\n }\n }" ]
[ "protected String createGlobalStyle()\n {\n StringBuilder ret = new StringBuilder();\n ret.append(createFontFaces());\n ret.append(\"\\n\");\n ret.append(defaultStyle);\n return ret.toString();\n }", "private SearchableItem buildSearchableItem(Message menuItem) {\n return new SearchableItem((int) ((NumberField) menuItem.arguments.get(1)).getValue(),\n ((StringField) menuItem.arguments.get(3)).getValue());\n }", "public static final boolean isInside(int x, int y, Rect box) {\n return (box.x < x && x < box.x + box.w && box.y < y && y < box.y + box.h);\n }", "protected <T> T fromJsonString(String json, Class<T> clazz) {\n\t\treturn _gsonParser.fromJson(json, clazz);\n\t}", "protected static <E extends LogRecordHandler> boolean removeHandler(Class<E> toRemove) {\r\n boolean rtn = false;\r\n Iterator<LogRecordHandler> iter = handlers.iterator();\r\n while(iter.hasNext()){\r\n if(iter.next().getClass().equals(toRemove)){\r\n rtn = true;\r\n iter.remove();\r\n }\r\n }\r\n return rtn;\r\n }", "public static base_response add(nitro_service client, snmpuser resource) throws Exception {\n\t\tsnmpuser addresource = new snmpuser();\n\t\taddresource.name = resource.name;\n\t\taddresource.group = resource.group;\n\t\taddresource.authtype = resource.authtype;\n\t\taddresource.authpasswd = resource.authpasswd;\n\t\taddresource.privtype = resource.privtype;\n\t\taddresource.privpasswd = resource.privpasswd;\n\t\treturn addresource.add_resource(client);\n\t}", "public void fit( double samplePoints[] , double[] observations ) {\n // Create a copy of the observations and put it into a matrix\n y.reshape(observations.length,1,false);\n System.arraycopy(observations,0, y.data,0,observations.length);\n\n // reshape the matrix to avoid unnecessarily declaring new memory\n // save values is set to false since its old values don't matter\n A.reshape(y.numRows, coef.numRows,false);\n\n // set up the A matrix\n for( int i = 0; i < observations.length; i++ ) {\n\n double obs = 1;\n\n for( int j = 0; j < coef.numRows; j++ ) {\n A.set(i,j,obs);\n obs *= samplePoints[i];\n }\n }\n\n // process the A matrix and see if it failed\n if( !solver.setA(A) )\n throw new RuntimeException(\"Solver failed\");\n\n // solver the the coefficients\n solver.solve(y,coef);\n }", "public boolean checkPrefixes(String uri, String[] patterns) {\n\t\tfor (String pattern : patterns) {\n\t\t\tif (pattern.length() > 0) {\n\t\t\t\tif (uri.startsWith(pattern)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "private static void addCauseToBacktrace(final Throwable cause, final List<String> bTrace) {\n if (cause.getMessage() == null) {\n bTrace.add(BT_CAUSED_BY_PREFIX + cause.getClass().getName());\n } else {\n bTrace.add(BT_CAUSED_BY_PREFIX + cause.getClass().getName() + \": \" + cause.getMessage());\n }\n for (final StackTraceElement ste : cause.getStackTrace()) {\n bTrace.add(BT_PREFIX + ste.toString());\n }\n if (cause.getCause() != null) {\n addCauseToBacktrace(cause.getCause(), bTrace);\n }\n }" ]
Returns redirect information for the given ID @param id ID of redirect @return ServerRedirect @throws Exception exception
[ "public ServerRedirect getRedirect(int id) throws Exception {\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_SERVERS +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n queryStatement.setInt(1, id);\n results = queryStatement.executeQuery();\n if (results.next()) {\n ServerRedirect curServer = new ServerRedirect(results.getInt(Constants.GENERIC_ID),\n results.getString(Constants.SERVER_REDIRECT_REGION),\n results.getString(Constants.SERVER_REDIRECT_SRC_URL),\n results.getString(Constants.SERVER_REDIRECT_DEST_URL),\n results.getString(Constants.SERVER_REDIRECT_HOST_HEADER));\n curServer.setProfileId(results.getInt(Constants.GENERIC_PROFILE_ID));\n\n return curServer;\n }\n logger.info(\"Did not find the ID: {}\", id);\n } catch (SQLException e) {\n throw e;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n return null;\n }" ]
[ "public void fireCalendarWrittenEvent(ProjectCalendar calendar)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.calendarWritten(calendar);\n }\n }\n }", "public int[] getTenors() {\r\n\t\tSet<Integer> setTenors\t= new HashSet<>();\r\n\r\n\t\tfor(int moneyness : getGridNodesPerMoneyness().keySet()) {\r\n\t\t\tsetTenors.addAll(Arrays.asList((IntStream.of(keyMap.get(moneyness)[1]).boxed().toArray(Integer[]::new))));\r\n\t\t}\r\n\t\treturn setTenors.stream().sorted().mapToInt(Integer::intValue).toArray();\r\n\t}", "public static base_responses update(nitro_service client, dospolicy resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdospolicy updateresources[] = new dospolicy[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new dospolicy();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].qdepth = resources[i].qdepth;\n\t\t\t\tupdateresources[i].cltdetectrate = resources[i].cltdetectrate;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "private void initAdapter()\n {\n Connection tmp = null;\n DatabaseMetaData meta = null;\n try\n {\n tmp = _ds.getConnection();\n meta = tmp.getMetaData();\n product = meta.getDatabaseProductName().toLowerCase();\n }\n catch (SQLException e)\n {\n throw new DatabaseException(\"Cannot connect to the database\", e);\n }\n finally\n {\n try\n {\n if (tmp != null)\n {\n tmp.close();\n }\n }\n catch (SQLException e)\n {\n // Nothing to do.\n }\n }\n\n DbAdapter newAdpt = null;\n for (String s : ADAPTERS)\n {\n try\n {\n Class<? extends DbAdapter> clazz = Db.class.getClassLoader().loadClass(s).asSubclass(DbAdapter.class);\n newAdpt = clazz.newInstance();\n if (newAdpt.compatibleWith(meta))\n {\n adapter = newAdpt;\n break;\n }\n }\n catch (Exception e)\n {\n throw new DatabaseException(\"Issue when loading database adapter named: \" + s, e);\n }\n }\n\n if (adapter == null)\n {\n throw new DatabaseException(\"Unsupported database! There is no JQM database adapter compatible with product name \" + product);\n }\n else\n {\n jqmlogger.info(\"Using database adapter {}\", adapter.getClass().getCanonicalName());\n }\n }", "public void put(String key, String value) {\n synchronized (this.cache) {\n this.cache.put(key, value);\n }\n }", "protected static boolean isOperatorLR( Symbol s ) {\n if( s == null )\n return false;\n\n switch( s ) {\n case ELEMENT_DIVIDE:\n case ELEMENT_TIMES:\n case ELEMENT_POWER:\n case RDIVIDE:\n case LDIVIDE:\n case TIMES:\n case POWER:\n case PLUS:\n case MINUS:\n case ASSIGN:\n return true;\n }\n return false;\n }", "public static base_response unset(nitro_service client, nstimeout resource, String[] args) throws Exception{\n\t\tnstimeout unsetresource = new nstimeout();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "@JsonProperty(\"aliases\")\n @JsonInclude(Include.NON_EMPTY)\n public Map<String, List<TermImpl>> getAliasUpdates() {\n \t\n \tMap<String, List<TermImpl>> updatedValues = new HashMap<>();\n \tfor(Map.Entry<String,AliasesWithUpdate> entry : newAliases.entrySet()) {\n \t\tAliasesWithUpdate update = entry.getValue();\n \t\tif (!update.write) {\n \t\t\tcontinue;\n \t\t}\n \t\tList<TermImpl> convertedAliases = new ArrayList<>();\n \t\tfor(MonolingualTextValue alias : update.aliases) {\n \t\t\tconvertedAliases.add(monolingualToJackson(alias));\n \t\t}\n \t\tupdatedValues.put(entry.getKey(), convertedAliases);\n \t}\n \treturn updatedValues;\n }", "public static <InnerT> Observable<InnerT> convertPageToInnerAsync(Observable<Page<InnerT>> innerPage) {\n return innerPage.flatMap(new Func1<Page<InnerT>, Observable<InnerT>>() {\n @Override\n public Observable<InnerT> call(Page<InnerT> pageInner) {\n return Observable.from(pageInner.items());\n }\n });\n }" ]
Main entry point when called to process constraint data. @param projectDir project directory @param file parent project file @param inputStreamFactory factory to create input stream
[ "public void process(DirectoryEntry projectDir, ProjectFile file, DocumentInputStreamFactory inputStreamFactory) throws IOException\n {\n DirectoryEntry consDir;\n try\n {\n consDir = (DirectoryEntry) projectDir.getEntry(\"TBkndCons\");\n }\n\n catch (FileNotFoundException ex)\n {\n consDir = null;\n }\n\n if (consDir != null)\n {\n FixedMeta consFixedMeta = new FixedMeta(new DocumentInputStream(((DocumentEntry) consDir.getEntry(\"FixedMeta\"))), 10);\n FixedData consFixedData = new FixedData(consFixedMeta, 20, inputStreamFactory.getInstance(consDir, \"FixedData\"));\n // FixedMeta consFixed2Meta = new FixedMeta(new DocumentInputStream(((DocumentEntry) consDir.getEntry(\"Fixed2Meta\"))), 9);\n // FixedData consFixed2Data = new FixedData(consFixed2Meta, 48, getEncryptableInputStream(consDir, \"Fixed2Data\"));\n\n int count = consFixedMeta.getAdjustedItemCount();\n int lastConstraintID = -1;\n\n ProjectProperties properties = file.getProjectProperties();\n EventManager eventManager = file.getEventManager();\n\n boolean project15 = NumberHelper.getInt(properties.getMppFileType()) == 14 && NumberHelper.getInt(properties.getApplicationVersion()) > ApplicationVersion.PROJECT_2010;\n int durationUnitsOffset = project15 ? 18 : 14;\n int durationOffset = project15 ? 14 : 16;\n\n for (int loop = 0; loop < count; loop++)\n {\n byte[] metaData = consFixedMeta.getByteArrayValue(loop);\n\n //\n // SourceForge bug 2209477: we were reading an int here, but\n // it looks like the deleted flag is just a short.\n //\n if (MPPUtility.getShort(metaData, 0) != 0)\n {\n continue;\n }\n\n int index = consFixedData.getIndexFromOffset(MPPUtility.getInt(metaData, 4));\n if (index == -1)\n {\n continue;\n }\n\n //\n // Do we have enough data?\n //\n byte[] data = consFixedData.getByteArrayValue(index);\n if (data.length < 14)\n {\n continue;\n }\n\n int constraintID = MPPUtility.getInt(data, 0);\n if (constraintID <= lastConstraintID)\n {\n continue;\n }\n\n lastConstraintID = constraintID;\n int taskID1 = MPPUtility.getInt(data, 4);\n int taskID2 = MPPUtility.getInt(data, 8);\n\n if (taskID1 == taskID2)\n {\n continue;\n }\n\n // byte[] metaData2 = consFixed2Meta.getByteArrayValue(loop);\n // int index2 = consFixed2Data.getIndexFromOffset(MPPUtility.getInt(metaData2, 4));\n // byte[] data2 = consFixed2Data.getByteArrayValue(index2);\n\n Task task1 = file.getTaskByUniqueID(Integer.valueOf(taskID1));\n Task task2 = file.getTaskByUniqueID(Integer.valueOf(taskID2));\n if (task1 != null && task2 != null)\n {\n RelationType type = RelationType.getInstance(MPPUtility.getShort(data, 12));\n TimeUnit durationUnits = MPPUtility.getDurationTimeUnits(MPPUtility.getShort(data, durationUnitsOffset));\n Duration lag = MPPUtility.getAdjustedDuration(properties, MPPUtility.getInt(data, durationOffset), durationUnits);\n Relation relation = task2.addPredecessor(task1, type, lag);\n relation.setUniqueID(Integer.valueOf(constraintID));\n eventManager.fireRelationReadEvent(relation);\n }\n }\n }\n }" ]
[ "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 }", "@Override\n public EthiopicDate date(Era era, int yearOfEra, int month, int dayOfMonth) {\n return date(prolepticYear(era, yearOfEra), month, dayOfMonth);\n }", "public void addWord(MtasCQLParserWordFullCondition w) throws ParseException {\n assert w.getCondition()\n .not() == false : \"condition word should be positive in sentence definition\";\n if (!simplified) {\n partList.add(w);\n } else {\n throw new ParseException(\"already simplified\");\n }\n }", "protected void appendGroupByClause(List groupByFields, StringBuffer buf)\r\n {\r\n if (groupByFields == null || groupByFields.size() == 0)\r\n {\r\n return;\r\n }\r\n\r\n buf.append(\" GROUP BY \");\r\n for (int i = 0; i < groupByFields.size(); i++)\r\n {\r\n FieldHelper cf = (FieldHelper) groupByFields.get(i);\r\n \r\n if (i > 0)\r\n {\r\n buf.append(\",\");\r\n }\r\n\r\n appendColName(cf.name, false, null, buf);\r\n }\r\n }", "public void registerDropPasteWorker(DropPasteWorkerInterface worker)\r\n {\r\n this.dropPasteWorkerSet.add(worker);\r\n defaultDropTarget.setDefaultActions( \r\n defaultDropTarget.getDefaultActions() \r\n | worker.getAcceptableActions(defaultDropTarget.getComponent())\r\n );\r\n }", "public static java.sql.Time newTime() {\n return new java.sql.Time(System.currentTimeMillis() % DAY_MILLIS);\n }", "public AnalyticProductInterface getCalibrationProductForSymbol(String symbol) {\n\n\t\t/*\n\t\t * The internal data structure is not optimal here (a map would make more sense here),\n\t\t * if the user does not require access to the products, we would allow non-unique symbols.\n\t\t * Hence we store both in two side by side vectors.\n\t\t */\n\t\tfor(int i=0; i<calibrationProductsSymbols.size(); i++) {\n\t\t\tString calibrationProductSymbol = calibrationProductsSymbols.get(i);\n\t\t\tif(calibrationProductSymbol.equals(symbol)) {\n\t\t\t\treturn calibrationProducts.get(i);\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}", "public static String writeMultipleClientConfigAvro(Map<String, Properties> mapStoreToProps) {\n // TODO: Use a dedicated json lib. We shouldn't be manually manipulating json...\n String avroConfig = \"\";\n Boolean firstStore = true;\n for(String storeName: mapStoreToProps.keySet()) {\n if(firstStore) {\n firstStore = false;\n } else {\n avroConfig = avroConfig + \",\\n\";\n }\n Properties props = mapStoreToProps.get(storeName);\n avroConfig = avroConfig + \"\\t\\\"\" + storeName + \"\\\": \"\n + writeSingleClientConfigAvro(props);\n\n }\n return \"{\\n\" + avroConfig + \"\\n}\";\n }", "@Override\n public ImageSource apply(ImageSource input) {\n final int[][] pixelMatrix = new int[3][3];\n\n int w = input.getWidth();\n int h = input.getHeight();\n\n int[][] output = new int[h][w];\n\n for (int j = 1; j < h - 1; j++) {\n for (int i = 1; i < w - 1; i++) {\n pixelMatrix[0][0] = input.getR(i - 1, j - 1);\n pixelMatrix[0][1] = input.getRGB(i - 1, j);\n pixelMatrix[0][2] = input.getRGB(i - 1, j + 1);\n pixelMatrix[1][0] = input.getRGB(i, j - 1);\n pixelMatrix[1][2] = input.getRGB(i, j + 1);\n pixelMatrix[2][0] = input.getRGB(i + 1, j - 1);\n pixelMatrix[2][1] = input.getRGB(i + 1, j);\n pixelMatrix[2][2] = input.getRGB(i + 1, j + 1);\n\n int edge = (int) convolution(pixelMatrix);\n int rgb = (edge << 16 | edge << 8 | edge);\n output[j][i] = rgb;\n }\n }\n\n MatrixSource source = new MatrixSource(output);\n return source;\n }" ]
Obtain the IDs of profile and path as Identifiers @param profileIdentifier actual ID or friendly name of profile @param pathIdentifier actual ID or friendly name of path @return @throws Exception
[ "public static Identifiers convertProfileAndPathIdentifier(String profileIdentifier, String pathIdentifier) throws Exception {\n Identifiers id = new Identifiers();\n\n Integer profileId = null;\n try {\n profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n } catch (Exception e) {\n // this is OK for this since it isn't always needed\n }\n Integer pathId = convertPathIdentifier(pathIdentifier, profileId);\n\n id.setProfileId(profileId);\n id.setPathId(pathId);\n\n return id;\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 }", "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 String common() {\n String common = SysProps.get(KEY_COMMON_CONF_TAG);\n if (S.blank(common)) {\n common = \"common\";\n }\n return common;\n }", "@Override\n public FileModel resolvePayload(GraphRewrite event, EvaluationContext context, WindupVertexFrame payload)\n {\n checkVariableName(event, context);\n if (payload instanceof FileReferenceModel)\n {\n return ((FileReferenceModel) payload).getFile();\n }\n if (payload instanceof FileModel)\n {\n return (FileModel) payload;\n }\n return null;\n }", "public void addCommandClass(ZWaveCommandClass commandClass)\n\t{\n\t\tZWaveCommandClass.CommandClass key = commandClass.getCommandClass();\n\t\t\n\t\tif (!supportedCommandClasses.containsKey(key)) {\n\t\t\tsupportedCommandClasses.put(key, commandClass);\n\t\t\t\n\t\t\tif (commandClass instanceof ZWaveEventListener)\n\t\t\t\tthis.controller.addEventListener((ZWaveEventListener)commandClass);\n\t\t\t\n\t\t\tthis.lastUpdated = Calendar.getInstance().getTime();\n\t\t}\n\t}", "private void debugLogStart(String operationType,\n Long originTimeInMS,\n Long requestReceivedTimeInMs,\n String keyString) {\n long durationInMs = requestReceivedTimeInMs - originTimeInMS;\n logger.debug(\"Received a new request. Operation Type: \" + operationType + \" , key(s): \"\n + keyString + \" , Store: \" + this.storeName + \" , Origin time (in ms): \"\n + originTimeInMS + \" . Request received at time(in ms): \"\n + requestReceivedTimeInMs\n + \" , Duration from RESTClient to CoordinatorFatClient(in ms): \"\n + durationInMs);\n\n }", "public static Method findSetMethod(Field field, DatabaseType databaseType, boolean throwExceptions)\n\t\t\tthrows IllegalArgumentException {\n\t\tMethod fieldSetMethod = findMethodFromNames(field, false, throwExceptions,\n\t\t\t\tmethodFromField(field, \"set\", databaseType, true), methodFromField(field, \"set\", databaseType, false));\n\t\tif (fieldSetMethod == null) {\n\t\t\treturn null;\n\t\t}\n\t\tif (fieldSetMethod.getReturnType() != void.class) {\n\t\t\tif (throwExceptions) {\n\t\t\t\tthrow new IllegalArgumentException(\"Return type of set method \" + fieldSetMethod.getName() + \" returns \"\n\t\t\t\t\t\t+ fieldSetMethod.getReturnType() + \" instead of void\");\n\t\t\t} else {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\treturn fieldSetMethod;\n\t}", "public static 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 Metadata createMetadata(String templateName, String scope, Metadata metadata) {\n URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), scope, templateName);\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"POST\");\n request.addHeader(\"Content-Type\", \"application/json\");\n request.setBody(metadata.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n return new Metadata(JsonObject.readFrom(response.getJSON()));\n }" ]
Use this API to fetch sslcertkey resource of given name .
[ "public static sslcertkey get(nitro_service service, String certkey) throws Exception{\n\t\tsslcertkey obj = new sslcertkey();\n\t\tobj.set_certkey(certkey);\n\t\tsslcertkey response = (sslcertkey) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
[ "private Method getPropertySourceMethod(Object sourceObject,\r\n\t\t\tObject destinationObject, String destinationProperty) {\r\n\t\tBeanToBeanMapping beanToBeanMapping = beanToBeanMappings.get(ClassPair\r\n\t\t\t\t.get(sourceObject.getClass(), destinationObject\r\n\t\t\t\t\t\t.getClass()));\r\n\t\tString sourceProperty = null;\r\n\t\tif (beanToBeanMapping != null) {\r\n\t\t\tsourceProperty = beanToBeanMapping\r\n\t\t\t\t\t.getSourceProperty(destinationProperty);\r\n\t\t}\r\n\t\tif (sourceProperty == null) {\r\n\t\t\tsourceProperty = destinationProperty;\r\n\t\t}\r\n\r\n\t\treturn BeanUtils.getGetterPropertyMethod(sourceObject.getClass(),\r\n\t\t\t\tsourceProperty);\r\n\t}", "private boolean shouldWrapMethodCall(String methodName) {\n if (methodList == null) {\n return true; // Wrap all by default\n }\n\n if (methodList.contains(methodName)) {\n return true; //Wrap a specific method\n }\n\n // If I get to this point, I should not wrap the call.\n return false;\n }", "private static void attachToContent(Activity activity, MenuDrawer menuDrawer) {\n /**\n * Do not call mActivity#setContentView.\n * E.g. if using with a ListActivity, Activity#setContentView is overridden and dispatched to\n * MenuDrawer#setContentView, which then again would call Activity#setContentView.\n */\n ViewGroup content = (ViewGroup) activity.findViewById(android.R.id.content);\n content.removeAllViews();\n content.addView(menuDrawer, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);\n }", "private String getParentOutlineNumber(String outlineNumber)\n {\n String result;\n int index = outlineNumber.lastIndexOf('.');\n if (index == -1)\n {\n result = \"\";\n }\n else\n {\n result = outlineNumber.substring(0, index);\n }\n return result;\n }", "public static List<int[]> createList( int N )\n {\n int data[] = new int[ N ];\n for( int i = 0; i < data.length; i++ ) {\n data[i] = -1;\n }\n\n List<int[]> ret = new ArrayList<int[]>();\n\n createList(data,0,-1,ret);\n\n return ret;\n }", "public Operation.Info create( char op , Variable input ) {\n switch( op ) {\n case '\\'':\n return Operation.transpose(input, managerTemp);\n\n default:\n throw new RuntimeException(\"Unknown operation \" + op);\n }\n }", "protected Patch createProcessedPatch(final Patch original) {\n\n // Process elements\n final List<PatchElement> elements = new ArrayList<PatchElement>();\n // Process layers\n for (final PatchEntry entry : getLayers()) {\n final PatchElement element = createPatchElement(entry, entry.element.getId(), entry.modifications);\n elements.add(element);\n }\n // Process add-ons\n for (final PatchEntry entry : getAddOns()) {\n final PatchElement element = createPatchElement(entry, entry.element.getId(), entry.modifications);\n elements.add(element);\n }\n\n // Swap the patch element modifications, keep the identity ones since we don't need to fix the misc modifications\n return new PatchImpl(original.getPatchId(), original.getDescription(), original.getLink(), original.getIdentity(), elements, identityEntry.modifications);\n }", "private Duration getDuration(Double duration)\n {\n Duration result = null;\n\n if (duration != null)\n {\n result = Duration.getInstance(NumberHelper.getDouble(duration), TimeUnit.HOURS);\n }\n\n return result;\n }", "private BasicCredentialsProvider getCredentialsProvider() {\n return new BasicCredentialsProvider() {\n private Set<AuthScope> authAlreadyTried = Sets.newHashSet();\n\n @Override\n public Credentials getCredentials(AuthScope authscope) {\n if (authAlreadyTried.contains(authscope)) {\n return null;\n }\n authAlreadyTried.add(authscope);\n return super.getCredentials(authscope);\n }\n };\n }" ]
Inserts a CharSequence value into the mapping of the underlying Bundle, replacing any existing value for the given key. Either key or value may be null. @param key a String, or null @param value a CharSequence, or null @return this bundler instance to chain method calls
[ "public Bundler put(String key, CharSequence value) {\n delegate.putCharSequence(key, value);\n return this;\n }" ]
[ "public static String getTitleGalleryKey(String gallery) {\n\n StringBuffer sb = new StringBuffer(GUI_TITLE_PREFIX);\n sb.append(gallery.toUpperCase());\n sb.append(GUI_TITLE_POSTFIX);\n return sb.toString();\n }", "public static autoscaleaction[] get(nitro_service service) throws Exception{\n\t\tautoscaleaction obj = new autoscaleaction();\n\t\tautoscaleaction[] response = (autoscaleaction[])obj.get_resources(service);\n\t\treturn response;\n\t}", "private boolean checkConverged(DMatrixRMaj A) {\n double worst = 0;\n double worst2 = 0;\n for( int j = 0; j < A.numRows; j++ ) {\n double val = Math.abs(q2.data[j] - q0.data[j]);\n if( val > worst ) worst = val;\n val = Math.abs(q2.data[j] + q0.data[j]);\n if( val > worst2 ) worst2 = val;\n }\n\n // swap vectors\n DMatrixRMaj temp = q0;\n q0 = q2;\n q2 = temp;\n\n if( worst < tol )\n return true;\n else if( worst2 < tol )\n return true;\n else\n return false;\n }", "protected boolean checkActionPackages(String classPackageName) {\n\t\tif (actionPackages != null) {\n\t\t\tfor (String packageName : actionPackages) {\n\t\t\t\tString strictPackageName = packageName + \".\";\n\t\t\t\tif (classPackageName.equals(packageName) || classPackageName.startsWith(strictPackageName))\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "public static CountryList getCountries(Context context) {\n if (mCountries != null) {\n return mCountries;\n }\n mCountries = new CountryList();\n try {\n JSONArray countries = new JSONArray(getJsonFromRaw(context, R.raw.countries));\n for (int i = 0; i < countries.length(); i++) {\n try {\n JSONObject country = (JSONObject) countries.get(i);\n mCountries.add(new Country(country.getString(\"name\"), country.getString(\"iso2\"), country.getInt(\"dialCode\")));\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n return mCountries;\n }", "public static NbtAddress[] getAllByAddress( NbtAddress addr )\n throws UnknownHostException {\n try {\n NbtAddress[] addrs = CLIENT.getNodeStatus( addr );\n cacheAddressArray( addrs );\n return addrs;\n } catch( UnknownHostException uhe ) {\n throw new UnknownHostException( \"no name with type 0x\" +\n Hexdump.toHexString( addr.hostName.hexCode, 2 ) +\n ((( addr.hostName.scope == null ) ||\n ( addr.hostName.scope.length() == 0 )) ?\n \" with no scope\" : \" with scope \" + addr.hostName.scope ) +\n \" for host \" + addr.getHostAddress() );\n }\n }", "public boolean handleKeyDeletion(final String key) {\n\n if (m_keyset.getKeySet().contains(key)) {\n if (removeKeyForAllLanguages(key)) {\n m_keyset.removeKey(key);\n return true;\n } else {\n return false;\n }\n }\n return true;\n }", "private Class<?> beanType(String name) {\n\t\tClass<?> type = context.getType(name);\n\t\tif (ClassUtils.isCglibProxyClass(type)) {\n\t\t\treturn AopProxyUtils.ultimateTargetClass(context.getBean(name));\n\t\t}\n\t\treturn type;\n\t}", "public Class<E> getEventClass() {\n if (cachedClazz != null) {\n return cachedClazz;\n }\n Class<?> clazz = this.getClass();\n while (clazz != Object.class) {\n try {\n Type mySuperclass = clazz.getGenericSuperclass();\n Type tType = ((ParameterizedType) mySuperclass).getActualTypeArguments()[0];\n cachedClazz = (Class<E>) Class.forName(tType.getTypeName());\n return cachedClazz;\n } catch (Exception e) {\n }\n clazz = clazz.getSuperclass();\n }\n throw new IllegalStateException(\"Failed to load event class - \" + this.getClass().getCanonicalName());\n }" ]
Test to determine if this is a split task. @param calendar current calendar @param list timephased resource assignment list @return boolean flag
[ "private boolean isSplit(ProjectCalendar calendar, List<TimephasedWork> list)\n {\n boolean result = false;\n for (TimephasedWork assignment : list)\n {\n if (calendar != null && assignment.getTotalAmount().getDuration() == 0)\n {\n Duration calendarWork = calendar.getWork(assignment.getStart(), assignment.getFinish(), TimeUnit.MINUTES);\n if (calendarWork.getDuration() != 0)\n {\n result = true;\n break;\n }\n }\n }\n return result;\n }" ]
[ "public void revertWorkingCopy() throws IOException, InterruptedException {\n build.getWorkspace()\n .act(new RevertWorkingCopyCallable(getLocation(), getSvnAuthenticationProvider(build), buildListener));\n }", "private boolean hasBidirectionalAssociation(Class clazz)\r\n {\r\n ClassDescriptor cdesc;\r\n Collection refs;\r\n boolean hasBidirAssc;\r\n\r\n if (_withoutBidirAssc.contains(clazz))\r\n {\r\n return false;\r\n }\r\n\r\n if (_withBidirAssc.contains(clazz))\r\n {\r\n return true;\r\n }\r\n\r\n // first time we meet this class, let's look at metadata\r\n cdesc = _pb.getClassDescriptor(clazz);\r\n refs = cdesc.getObjectReferenceDescriptors();\r\n hasBidirAssc = false;\r\n REFS_CYCLE:\r\n for (Iterator it = refs.iterator(); it.hasNext(); )\r\n {\r\n ObjectReferenceDescriptor ord;\r\n ClassDescriptor relCDesc;\r\n Collection relRefs;\r\n\r\n ord = (ObjectReferenceDescriptor) it.next();\r\n relCDesc = _pb.getClassDescriptor(ord.getItemClass());\r\n relRefs = relCDesc.getObjectReferenceDescriptors();\r\n for (Iterator relIt = relRefs.iterator(); relIt.hasNext(); )\r\n {\r\n ObjectReferenceDescriptor relOrd;\r\n\r\n relOrd = (ObjectReferenceDescriptor) relIt.next();\r\n if (relOrd.getItemClass().equals(clazz))\r\n {\r\n hasBidirAssc = true;\r\n break REFS_CYCLE;\r\n }\r\n }\r\n }\r\n if (hasBidirAssc)\r\n {\r\n _withBidirAssc.add(clazz);\r\n }\r\n else\r\n {\r\n _withoutBidirAssc.add(clazz);\r\n }\r\n\r\n return hasBidirAssc;\r\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 }", "public static double volatilityConversionLognormalATMtoNormalATM(double forward, double displacement, double maturity, double lognormalVolatiltiy) {\n\t\tdouble x = lognormalVolatiltiy * Math.sqrt(maturity / 8);\n\t\tdouble y = org.apache.commons.math3.special.Erf.erf(x);\n\t\tdouble normalVol = Math.sqrt(2*Math.PI / maturity) * (forward+displacement) * y;\n\n\t\treturn normalVol;\n\t}", "public Metadata getMetadata(String templateName) {\n String scope = Metadata.scopeBasedOnType(templateName);\n return this.getMetadata(templateName, scope);\n }", "public static void pushImage(String imageTag, String username, String password, String host) throws IOException {\n final AuthConfig authConfig = new AuthConfig();\n authConfig.withUsername(username);\n authConfig.withPassword(password);\n\n DockerClient dockerClient = null;\n try {\n dockerClient = getDockerClient(host);\n dockerClient.pushImageCmd(imageTag).withAuthConfig(authConfig).exec(new PushImageResultCallback()).awaitSuccess();\n } finally {\n closeQuietly(dockerClient);\n }\n }", "public static wisite_farmname_binding[] get(nitro_service service, String sitepath) throws Exception{\n\t\twisite_farmname_binding obj = new wisite_farmname_binding();\n\t\tobj.set_sitepath(sitepath);\n\t\twisite_farmname_binding response[] = (wisite_farmname_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static ServiceController<DeploymentScanner> addService(final OperationContext context, final PathAddress resourceAddress, final String relativeTo, final String path,\n final int scanInterval, TimeUnit unit, final boolean autoDeployZip,\n final boolean autoDeployExploded, final boolean autoDeployXml, final boolean scanEnabled, final long deploymentTimeout, boolean rollbackOnRuntimeFailure,\n final FileSystemDeploymentService bootTimeService, final ScheduledExecutorService scheduledExecutorService) {\n final DeploymentScannerService service = new DeploymentScannerService(resourceAddress, relativeTo, path, scanInterval, unit, autoDeployZip,\n autoDeployExploded, autoDeployXml, scanEnabled, deploymentTimeout, rollbackOnRuntimeFailure, bootTimeService);\n final ServiceName serviceName = getServiceName(resourceAddress.getLastElement().getValue());\n service.scheduledExecutorValue.inject(scheduledExecutorService);\n final ServiceBuilder<DeploymentScanner> sb = context.getServiceTarget().addService(serviceName, service);\n sb.addDependency(context.getCapabilityServiceName(PATH_MANAGER_CAPABILITY, PathManager.class), PathManager.class, service.pathManagerValue);\n sb.addDependency(context.getCapabilityServiceName(\"org.wildfly.management.notification-handler-registry\", null),\n NotificationHandlerRegistry.class, service.notificationRegistryValue);\n sb.addDependency(context.getCapabilityServiceName(\"org.wildfly.management.model-controller-client-factory\", null),\n ModelControllerClientFactory.class, service.clientFactoryValue);\n sb.requires(org.jboss.as.server.deployment.Services.JBOSS_DEPLOYMENT_CHAINS);\n sb.addDependency(ControlledProcessStateService.SERVICE_NAME, ControlledProcessStateService.class, service.controlledProcessStateServiceValue);\n return sb.install();\n }", "public static List<String> getChildrenParentMayNotExist(ZkClient zkClient, String path) {\n try {\n return zkClient.getChildren(path);\n } catch (ZkNoNodeException e) {\n return null;\n }\n }" ]
Add the given entries of the input map into the output map. <p> If a key in the inputMap already exists in the outputMap, its value is replaced in the outputMap by the value from the inputMap. </p> @param <K> type of the map keys. @param <V> type of the map values. @param outputMap the map to update. @param inputMap the entries to add. @since 2.15
[ "@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}" ]
[ "private static synchronized FileOutputWriter createFileWriter(final TypeDefinition type, final DecompilerSettings settings)\n throws IOException\n {\n final String outputDirectory = settings.getOutputDirectory();\n\n final String fileName = type.getName() + settings.getLanguage().getFileExtension();\n final String packageName = type.getPackageName();\n\n // foo.Bar -> foo/Bar.java\n final String subDir = StringUtils.defaultIfEmpty(packageName, \"\").replace('.', File.separatorChar);\n final String outputPath = PathHelper.combine(outputDirectory, subDir, fileName);\n\n final File outputFile = new File(outputPath);\n final File parentDir = outputFile.getParentFile();\n\n if (parentDir != null && !parentDir.exists() && !parentDir.mkdirs())\n {\n throw new IllegalStateException(\"Could not create directory:\" + parentDir);\n }\n\n if (!outputFile.exists() && !outputFile.createNewFile())\n {\n throw new IllegalStateException(\"Could not create output file: \" + outputPath);\n }\n\n return new FileOutputWriter(outputFile, settings);\n }", "private void initPixelsArray(BufferedImage image) {\n int width = image.getWidth();\n int height = image.getHeight();\n pixels = new int[width * height];\n image.getRGB(0, 0, width, height, pixels, 0, width);\n\n }", "public static String unexpandLine(CharSequence self, int tabStop) {\n StringBuilder builder = new StringBuilder(self.toString());\n int index = 0;\n while (index + tabStop < builder.length()) {\n // cut original string in tabstop-length pieces\n String piece = builder.substring(index, index + tabStop);\n // count trailing whitespace characters\n int count = 0;\n while ((count < tabStop) && (Character.isWhitespace(piece.charAt(tabStop - (count + 1)))))\n count++;\n // replace if whitespace was found\n if (count > 0) {\n piece = piece.substring(0, tabStop - count) + '\\t';\n builder.replace(index, index + tabStop, piece);\n index = index + tabStop - (count - 1);\n } else\n index = index + tabStop;\n }\n return builder.toString();\n }", "public double nonNormalizedTreeDist(LblTree t1, LblTree t2) {\n\t\tinit(t1, t2);\n\t\tSTR = new int[size1][size2];\n\t\tcomputeOptimalStrategy();\n\t\treturn computeDistUsingStrArray(it1, it2);\n\t}", "public List<EnabledEndpoint> getEnabledEndpoints(int pathId, String clientUUID, String[] filters) throws Exception {\n ArrayList<EnabledEndpoint> enabledOverrides = new ArrayList<EnabledEndpoint>();\n PreparedStatement query = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n query = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \"=?\" +\n \" AND \" + Constants.GENERIC_CLIENT_UUID + \"=?\" +\n \" ORDER BY \" + Constants.ENABLED_OVERRIDES_PRIORITY\n );\n query.setInt(1, pathId);\n query.setString(2, clientUUID);\n results = query.executeQuery();\n\n while (results.next()) {\n EnabledEndpoint endpoint = this.getPartialEnabledEndpointFromResultset(results);\n com.groupon.odo.proxylib.models.Method m = PathOverrideService.getInstance().getMethodForOverrideId(endpoint.getOverrideId());\n\n // this is an errant entry.. perhaps a method got deleted from a plugin\n // we'll also remove it from the endpoint\n if (m == null) {\n PathOverrideService.getInstance().removeOverride(endpoint.getOverrideId());\n continue;\n }\n\n // check filters and see if any match\n boolean addOverride = false;\n if (filters != null) {\n for (String filter : filters) {\n if (m.getMethodType().endsWith(filter)) {\n addOverride = true;\n break;\n }\n }\n } else {\n // if there are no filters then we assume that the requester wants all enabled overrides\n addOverride = true;\n }\n\n if (addOverride) {\n enabledOverrides.add(endpoint);\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n\n // now go through the ArrayList and get the method for all of the endpoints\n // have to do this so we don't have overlapping SQL queries\n ArrayList<EnabledEndpoint> enabledOverridesWithMethods = new ArrayList<EnabledEndpoint>();\n for (EnabledEndpoint endpoint : enabledOverrides) {\n if (endpoint.getOverrideId() >= 0) {\n com.groupon.odo.proxylib.models.Method m = PathOverrideService.getInstance().getMethodForOverrideId(endpoint.getOverrideId());\n endpoint.setMethodInformation(m);\n }\n enabledOverridesWithMethods.add(endpoint);\n }\n\n return enabledOverridesWithMethods;\n }", "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 static <T> SessionBean<T> of(BeanAttributes<T> attributes, InternalEjbDescriptor<T> ejbDescriptor, BeanManagerImpl beanManager, EnhancedAnnotatedType<T> type) {\n return new SessionBeanImpl<T>(attributes, type, ejbDescriptor, new StringBeanIdentifier(SessionBeans.createIdentifier(type, ejbDescriptor)), beanManager);\n }", "@SuppressWarnings(\"WeakerAccess\")\n public int findBeatAtTime(long milliseconds) {\n int found = Arrays.binarySearch(timeWithinTrackValues, milliseconds);\n if (found >= 0) { // An exact match, just change 0-based array index to 1-based beat number\n return found + 1;\n } else if (found == -1) { // We are before the first beat\n return found;\n } else { // We are after some beat, report its beat number\n return -(found + 1);\n }\n }", "public void growMaxColumns( int desiredColumns , boolean preserveValue ) {\n if( col_idx.length < desiredColumns+1 ) {\n int[] c = new int[ desiredColumns+1 ];\n if( preserveValue )\n System.arraycopy(col_idx,0,c,0,col_idx.length);\n col_idx = c;\n }\n }" ]
Use this API to fetch statistics of tunnelip_stats resource of given name .
[ "public static tunnelip_stats get(nitro_service service, String tunnelip) throws Exception{\n\t\ttunnelip_stats obj = new tunnelip_stats();\n\t\tobj.set_tunnelip(tunnelip);\n\t\ttunnelip_stats response = (tunnelip_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}" ]
[ "protected void doConfigure() {\n if (config != null) {\n for (UserBean user : config.getUsersToCreate()) {\n setUser(user.getEmail(), user.getLogin(), user.getPassword());\n }\n getManagers().getUserManager().setAuthRequired(!config.isAuthenticationDisabled());\n }\n }", "public static Iterable<BoxFileVersionRetention.Info> getAll(BoxAPIConnection api, String ... fields) {\n return getRetentions(api, new QueryFilter(), fields);\n }", "public static String[] sortStringArray(String[] array) {\n if (isEmpty(array)) {\n return new String[0];\n }\n Arrays.sort(array);\n return array;\n }", "@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 }", "private void writeBooleanField(String fieldName, Object value) throws IOException\n {\n boolean val = ((Boolean) value).booleanValue();\n if (val)\n {\n m_writer.writeNameValuePair(fieldName, val);\n }\n }", "public ArrayList<Double> segmentBaselineCost(ProjectFile file, List<TimephasedCost> cost, TimescaleUnits rangeUnits, ArrayList<DateRange> dateList)\n {\n return segmentCost(file.getBaselineCalendar(), cost, rangeUnits, dateList);\n }", "@Override\n public synchronized void stop(final StopContext context) {\n final boolean shutdownServers = runningModeControl.getRestartMode() == RestartMode.SERVERS;\n if (shutdownServers) {\n Runnable task = new Runnable() {\n @Override\n public void run() {\n try {\n serverInventory.shutdown(true, -1, true); // TODO graceful shutdown\n serverInventory = null;\n // client.getValue().setServerInventory(null);\n } finally {\n serverCallback.getValue().setCallbackHandler(null);\n context.complete();\n }\n }\n };\n try {\n executorService.getValue().execute(task);\n } catch (RejectedExecutionException e) {\n task.run();\n } finally {\n context.asynchronous();\n }\n } else {\n // We have to set the shutdown flag in any case\n serverInventory.shutdown(false, -1, true);\n serverInventory = null;\n }\n }", "private long getEndTime(ISuite suite, IInvokedMethod method)\n {\n // Find the latest end time for all tests in the suite.\n for (Map.Entry<String, ISuiteResult> entry : suite.getResults().entrySet())\n {\n ITestContext testContext = entry.getValue().getTestContext();\n for (ITestNGMethod m : testContext.getAllTestMethods())\n {\n if (method == m)\n {\n return testContext.getEndDate().getTime();\n }\n }\n // If we can't find a matching test method it must be a configuration method.\n for (ITestNGMethod m : testContext.getPassedConfigurations().getAllMethods())\n {\n if (method == m)\n {\n return testContext.getEndDate().getTime();\n }\n }\n for (ITestNGMethod m : testContext.getFailedConfigurations().getAllMethods())\n {\n if (method == m)\n {\n return testContext.getEndDate().getTime();\n }\n }\n }\n throw new IllegalStateException(\"Could not find matching end time.\");\n }", "public Point2D.Double minDistancePointSpline(Point2D.Double p, int nPointsPerSegment){\n\t\t\tdouble minDistance = Double.MAX_VALUE;\n\t\t\tPoint2D.Double minDistancePoint = null;\n\t\t int numberOfSplines = spline.getN();\n\t\t double[] knots = spline.getKnots();\n\t\t for(int i = 0; i < numberOfSplines; i++){\n\t\t \tdouble x = knots[i];\n\t\t \tdouble stopx = knots[i+1];\n\t\t \tdouble dx = (stopx-x)/nPointsPerSegment;\n\t\t \t\n\t\t \tfor(int j = 0; j < nPointsPerSegment; j++){\n\t\t \t\tPoint2D.Double candidate = new Point2D.Double(x, spline.value(x));\n\t\t \t\tdouble d = p.distance(candidate);\n\t\t \t\tif(d<minDistance){\n\t\t \t\t\tminDistance = d;\n\t\t \t\t\tminDistancePoint = candidate;\n\t\t \t\t}\n\t\t \t\tx += dx;\n\t\t \t}\n\t\t \t\n\t\t }\n\t\t return minDistancePoint;\n\t}" ]
Search for the attribute "id" and return the value. @return the id of this element or null when not found
[ "public String getElementId() {\r\n\t\tfor (Entry<String, String> attribute : attributes.entrySet()) {\r\n\t\t\tif (attribute.getKey().equalsIgnoreCase(\"id\")) {\r\n\t\t\t\treturn attribute.getValue();\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn null;\r\n\t}" ]
[ "private void attributes(Options opt, FieldDoc fd[]) {\n\tfor (FieldDoc f : fd) {\n\t if (hidden(f))\n\t\tcontinue;\n\t stereotype(opt, f, Align.LEFT);\n\t String att = visibility(opt, f) + f.name();\n\t if (opt.showType)\n\t\tatt += typeAnnotation(opt, f.type());\n\t tableLine(Align.LEFT, att);\n\t tagvalue(opt, f);\n\t}\n }", "public static String getRelativePathName(Path root, Path path) {\n Path relative = root.relativize(path);\n return Files.isDirectory(path) && !relative.toString().endsWith(\"/\") ? String.format(\"%s/\", relative.toString()) : relative.toString();\n }", "@SuppressWarnings({\"UnusedDeclaration\"})\n public void doIndex(StaplerRequest req, StaplerResponse resp) throws IOException, ServletException {\n req.getView(this, chooseAction()).forward(req, resp);\n }", "static ChangeEvent<BsonDocument> changeEventForLocalUpdate(\n final MongoNamespace namespace,\n final BsonValue documentId,\n final UpdateDescription update,\n final BsonDocument fullDocumentAfterUpdate,\n final boolean writePending\n ) {\n return new ChangeEvent<>(\n new BsonDocument(),\n OperationType.UPDATE,\n fullDocumentAfterUpdate,\n namespace,\n new BsonDocument(\"_id\", documentId),\n update,\n writePending);\n }", "public void postConstruct(GeoService geoService, DtoConverterService converterService) throws GeomajasException {\n\t\tif (null == layerInfo) {\n\t\t\tlayerInfo = new RasterLayerInfo();\n\t\t}\n\t\tlayerInfo.setCrs(TiledRasterLayerService.MERCATOR);\n\t\tcrs = geoService.getCrs2(TiledRasterLayerService.MERCATOR);\n\t\tlayerInfo.setTileWidth(tileSize);\n\t\tlayerInfo.setTileHeight(tileSize);\n\t\tBbox bbox = new Bbox(-TiledRasterLayerService.HALF_EQUATOR_IN_METERS,\n\t\t\t\t-TiledRasterLayerService.HALF_EQUATOR_IN_METERS, TiledRasterLayerService.EQUATOR_IN_METERS,\n\t\t\t\tTiledRasterLayerService.EQUATOR_IN_METERS);\n\t\tlayerInfo.setMaxExtent(bbox);\n\t\tmaxBounds = converterService.toInternal(bbox);\n\n\t\tresolutions = new double[maxZoomLevel + 1];\n\t\tdouble powerOfTwo = 1;\n\t\tfor (int zoomLevel = 0; zoomLevel <= maxZoomLevel; zoomLevel++) {\n\t\t\tdouble resolution = (TiledRasterLayerService.EQUATOR_IN_METERS) / (tileSize * powerOfTwo);\n\t\t\tresolutions[zoomLevel] = resolution;\n\t\t\tpowerOfTwo *= 2;\n\t\t}\n\t}", "protected void addImage(PdfContext context, ImageResult imageResult) throws BadElementException, IOException {\n\t\tBbox imageBounds = imageResult.getRasterImage().getBounds();\n\t\tfloat scaleFactor = (float) (72 / getMap().getRasterResolution());\n\t\tfloat width = (float) imageBounds.getWidth() * scaleFactor;\n\t\tfloat height = (float) imageBounds.getHeight() * scaleFactor;\n\t\t// subtract screen position of lower-left corner\n\t\tfloat x = (float) (imageBounds.getX() - rasterScale * bbox.getMinX()) * scaleFactor;\n\t\t// shift y to lowerleft corner, flip y to user space and subtract\n\t\t// screen position of lower-left\n\t\t// corner\n\t\tfloat y = (float) (-imageBounds.getY() - imageBounds.getHeight() - rasterScale * bbox.getMinY()) * scaleFactor;\n\t\tif (log.isDebugEnabled()) {\n\t\t\tlog.debug(\"adding image, width=\" + width + \",height=\" + height + \",x=\" + x + \",y=\" + y);\n\t\t}\n\t\t// opacity\n\t\tlog.debug(\"before drawImage\");\n\t\tcontext.drawImage(Image.getInstance(imageResult.getImage()), new Rectangle(x, y, x + width, y + height),\n\t\t\t\tgetSize(), getOpacity());\n\t\tlog.debug(\"after drawImage\");\n\t}", "public float getSize(final Axis axis) {\n float size = 0;\n if (mViewPort != null && mViewPort.isClippingEnabled(axis)) {\n size = mViewPort.get(axis);\n } else if (mContainer != null) {\n size = getSizeImpl(axis);\n }\n return size;\n }", "private void writeName(String name) throws IOException\n {\n m_writer.write('\"');\n m_writer.write(name);\n m_writer.write('\"');\n m_writer.write(\":\");\n }", "public <T extends Widget & Checkable> List<Integer> getCheckedWidgetIndexes() {\n List<Integer> checked = new ArrayList<>();\n List<Widget> children = getChildren();\n\n final int size = children.size();\n for (int i = 0, j = -1; i < size; ++i) {\n Widget c = children.get(i);\n if (c instanceof Checkable) {\n ++j;\n if (((Checkable) c).isChecked()) {\n checked.add(j);\n }\n }\n }\n\n return checked;\n }" ]
Adds any listeners attached to this reader to the reader created internally. @param reader internal project reader
[ "private void addListeners(ProjectReader reader)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n reader.addProjectListener(listener);\n }\n }\n }" ]
[ "static InstalledIdentity load(final InstalledImage image, final ProductConfig productConfig, final List<File> moduleRoots, final List<File> bundleRoots) throws IOException {\n\n // build the identity information\n final String productVersion = productConfig.resolveVersion();\n final String productName = productConfig.resolveName();\n final Identity identity = new AbstractLazyIdentity() {\n @Override\n public String getName() {\n return productName;\n }\n\n @Override\n public String getVersion() {\n return productVersion;\n }\n\n @Override\n public InstalledImage getInstalledImage() {\n return image;\n }\n };\n\n final Properties properties = PatchUtils.loadProperties(identity.getDirectoryStructure().getInstallationInfo());\n final List<String> allPatches = PatchUtils.readRefs(properties, Constants.ALL_PATCHES);\n\n // Step 1 - gather the installed layers data\n final InstalledConfiguration conf = createInstalledConfig(image);\n // Step 2 - process the actual module and bundle roots\n final ProcessedLayers processedLayers = process(conf, moduleRoots, bundleRoots);\n final InstalledConfiguration config = processedLayers.getConf();\n\n // Step 3 - create the actual config objects\n // Process layers\n final InstalledIdentityImpl installedIdentity = new InstalledIdentityImpl(identity, allPatches, image);\n for (final LayerPathConfig layer : processedLayers.getLayers().values()) {\n final String name = layer.name;\n installedIdentity.putLayer(name, createPatchableTarget(name, layer, config.getLayerMetadataDir(name), image));\n }\n // Process add-ons\n for (final LayerPathConfig addOn : processedLayers.getAddOns().values()) {\n final String name = addOn.name;\n installedIdentity.putAddOn(name, createPatchableTarget(name, addOn, config.getAddOnMetadataDir(name), image));\n }\n return installedIdentity;\n }", "public static base_response unset(nitro_service client, sslparameter resource, String[] args) throws Exception{\n\t\tsslparameter unsetresource = new sslparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public static void numberToBytes(int number, byte[] buffer, int start, int length) {\n for (int index = start + length - 1; index >= start; index--) {\n buffer[index] = (byte)(number & 0xff);\n number = number >> 8;\n }\n }", "public boolean isEmbeddedProperty(String targetTypeName, List<String> namesWithoutAlias) {\n\t\tOgmEntityPersister persister = getPersister( targetTypeName );\n\t\tType propertyType = persister.getPropertyType( namesWithoutAlias.get( 0 ) );\n\t\tif ( propertyType.isComponentType() ) {\n\t\t\t// Embedded\n\t\t\treturn true;\n\t\t}\n\t\telse if ( propertyType.isAssociationType() ) {\n\t\t\tJoinable associatedJoinable = ( (AssociationType) propertyType ).getAssociatedJoinable( persister.getFactory() );\n\t\t\tif ( associatedJoinable.isCollection() ) {\n\t\t\t\tOgmCollectionPersister collectionPersister = (OgmCollectionPersister) associatedJoinable;\n\t\t\t\treturn collectionPersister.getType().isComponentType();\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "public void takeNoteOfGradient(IntDoubleVector gradient) {\n gradient.iterate(new FnIntDoubleToVoid() { \n @Override\n public void call(int index, double value) {\n gradSumSquares[index] += value * value;\n assert !Double.isNaN(gradSumSquares[index]);\n }\n });\n }", "@Override\n public boolean parseAndValidateRequest() {\n boolean result = false;\n if(!super.parseAndValidateRequest() || !hasVectorClock(this.isVectorClockOptional)\n || !hasContentLength() || !hasContentType()) {\n result = false;\n } else {\n result = true;\n }\n\n return result;\n }", "public static String getCountryCodeAndCheckDigit(final String iban) {\n return iban.substring(COUNTRY_CODE_INDEX,\n COUNTRY_CODE_INDEX + COUNTRY_CODE_LENGTH + CHECK_DIGIT_LENGTH);\n }", "public static void validate(final Module module) {\n if (null == module) {\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Module cannot be null!\")\n .build());\n }\n if(module.getName() == null ||\n module.getName().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Module name cannot be null or empty!\")\n .build());\n }\n if(module.getVersion()== null ||\n module.getVersion().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Module version cannot be null or empty!\")\n .build());\n }\n\n // Check artifacts\n for(final Artifact artifact: DataUtils.getAllArtifacts(module)){\n validate(artifact);\n }\n\n // Check dependencies\n for(final Dependency dependency: DataUtils.getAllDependencies(module)){\n validate(dependency.getTarget());\n }\n }", "@SuppressWarnings(\"unchecked\")\n public <T extends WindupVertexFrame> Iterable<T> findVariableOfType(Class<T> type)\n {\n for (Map<String, Iterable<? extends WindupVertexFrame>> topOfStack : deque)\n {\n for (Iterable<? extends WindupVertexFrame> frames : topOfStack.values())\n {\n boolean empty = true;\n for (WindupVertexFrame frame : frames)\n {\n if (!type.isAssignableFrom(frame.getClass()))\n {\n break;\n }\n else\n {\n empty = false;\n }\n }\n // now we know all the frames are of the chosen type\n if (!empty)\n return (Iterable<T>) frames;\n }\n }\n return null;\n }" ]
Computes eigenvalues only @return
[ "private boolean computeEigenValues() {\n // make a copy of the internal tridiagonal matrix data for later use\n diagSaved = helper.copyDiag(diagSaved);\n offSaved = helper.copyOff(offSaved);\n\n vector.setQ(null);\n vector.setFastEigenvalues(true);\n\n // extract the eigenvalues\n if( !vector.process(-1,null,null) )\n return false;\n\n // save a copy of them since this data structure will be recycled next\n values = helper.copyEigenvalues(values);\n return true;\n }" ]
[ "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 base_response add(nitro_service client, appfwjsoncontenttype resource) throws Exception {\n\t\tappfwjsoncontenttype addresource = new appfwjsoncontenttype();\n\t\taddresource.jsoncontenttypevalue = resource.jsoncontenttypevalue;\n\t\taddresource.isregex = resource.isregex;\n\t\treturn addresource.add_resource(client);\n\t}", "public static Map<String,String> unserializeBuildInfo(final String buildInfo) throws IOException {\n final ObjectMapper mapper = new ObjectMapper();\n mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);\n return mapper.readValue(buildInfo, new TypeReference<Map<String, Object>>(){});\n }", "private RelationType getRelationType(int type)\n {\n RelationType result;\n if (type > 0 && type < RELATION_TYPES.length)\n {\n result = RELATION_TYPES[type];\n }\n else\n {\n result = RelationType.FINISH_START;\n }\n return result;\n }", "public void delete(Object element, boolean testForEquality) {\r\n\tint index = indexOfFromTo(element, 0, size-1, testForEquality);\r\n\tif (index>=0) removeFromTo(index,index);\r\n}", "private void lockOnChange(Object propertyId) throws CmsException {\n\n if (isDescriptorProperty(propertyId)) {\n lockDescriptor();\n } else {\n Locale l = m_bundleType.equals(BundleType.PROPERTY) ? m_locale : null;\n lockLocalization(l);\n }\n\n }", "public void setWeeklyDaysFromBitmap(Integer days, int[] masks)\n {\n if (days != null)\n {\n int value = days.intValue();\n for (Day day : Day.values())\n {\n setWeeklyDay(day, ((value & masks[day.getValue()]) != 0));\n }\n }\n }", "public WebSocketContext messageReceived(String receivedMessage) {\n this.stringMessage = S.string(receivedMessage).trim();\n isJson = stringMessage.startsWith(\"{\") || stringMessage.startsWith(\"]\");\n tryParseQueryParams();\n return this;\n }", "public static BuildRetention createBuildRetention(Run build, boolean discardOldArtifacts) {\n BuildRetention buildRetention = new BuildRetention(discardOldArtifacts);\n LogRotator rotator = null;\n BuildDiscarder buildDiscarder = build.getParent().getBuildDiscarder();\n if (buildDiscarder != null && buildDiscarder instanceof LogRotator) {\n rotator = (LogRotator) buildDiscarder;\n }\n if (rotator == null) {\n return buildRetention;\n }\n if (rotator.getNumToKeep() > -1) {\n buildRetention.setCount(rotator.getNumToKeep());\n }\n if (rotator.getDaysToKeep() > -1) {\n Calendar calendar = Calendar.getInstance();\n calendar.add(Calendar.DAY_OF_YEAR, -rotator.getDaysToKeep());\n buildRetention.setMinimumBuildDate(new Date(calendar.getTimeInMillis()));\n }\n List<String> notToBeDeleted = ExtractorUtils.getBuildNumbersNotToBeDeleted(build);\n buildRetention.setBuildNumbersNotToBeDiscarded(notToBeDeleted);\n return buildRetention;\n }" ]
Utility function to validate if the given store name exists in the store name list managed by MetadataStore. This is used by the Admin service for validation before serving a get-metadata request. @param name Name of the store to validate @return True if the store name exists in the 'storeNames' list. False otherwise.
[ "public boolean isValidStore(String name) {\n readLock.lock();\n try {\n if(this.storeNames.contains(name)) {\n return true;\n }\n return false;\n } finally {\n readLock.unlock();\n }\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 }", "boolean hasNoAlternativeWildcardRegistration() {\n return parent == null || PathElement.WILDCARD_VALUE.equals(valueString) || !parent.getChildNames().contains(PathElement.WILDCARD_VALUE);\n }", "protected void checkForPrimaryKeys(final Object realObject) throws ClassNotPersistenceCapableException\r\n {\r\n // if no PKs are specified OJB can't handle this class !\r\n if (m_pkValues == null || m_pkValues.length == 0)\r\n {\r\n throw createException(\"OJB needs at least one primary key attribute for class: \", realObject, null);\r\n }\r\n// arminw: should never happen\r\n// if(m_pkValues[0] instanceof ValueContainer)\r\n// throw new OJBRuntimeException(\"Can't handle pk values of type \"+ValueContainer.class.getName());\r\n }", "public Class getRealClass(Object objectOrProxy)\r\n {\r\n IndirectionHandler handler;\r\n\r\n if(isNormalOjbProxy(objectOrProxy))\r\n {\r\n String msg;\r\n\r\n try\r\n {\r\n handler = getIndirectionHandler(objectOrProxy);\r\n /*\r\n arminw:\r\n think we should return the real class\r\n */\r\n // return handler.getIdentity().getObjectsTopLevelClass();\r\n return handler.getIdentity().getObjectsRealClass();\r\n }\r\n catch(ClassCastException e)\r\n {\r\n // shouldn't happen but still ...\r\n msg = \"The InvocationHandler for the provided Proxy was not an instance of \" + IndirectionHandler.class.getName();\r\n log.error(msg);\r\n throw new PersistenceBrokerException(msg, e);\r\n }\r\n catch(IllegalArgumentException e)\r\n {\r\n msg = \"Could not retrieve real object for given Proxy: \" + objectOrProxy;\r\n log.error(msg);\r\n throw new PersistenceBrokerException(msg, e);\r\n }\r\n }\r\n else if(isVirtualOjbProxy(objectOrProxy))\r\n {\r\n handler = VirtualProxy.getIndirectionHandler((VirtualProxy) objectOrProxy);\r\n /*\r\n arminw:\r\n think we should return the real class\r\n */\r\n // return handler.getIdentity().getObjectsTopLevelClass();\r\n return handler.getIdentity().getObjectsRealClass();\r\n }\r\n else\r\n {\r\n return objectOrProxy.getClass();\r\n }\r\n }", "private Event createEvent(Endpoint endpoint, EventTypeEnum type) {\n\n Event event = new Event();\n MessageInfo messageInfo = new MessageInfo();\n Originator originator = new Originator();\n event.setMessageInfo(messageInfo);\n event.setOriginator(originator);\n\n Date date = new Date();\n event.setTimestamp(date);\n event.setEventType(type);\n\n messageInfo.setPortType(\n endpoint.getBinding().getBindingInfo().getService().getInterface().getName().toString());\n\n String transportType = null;\n if (endpoint.getBinding() instanceof SoapBinding) {\n SoapBinding soapBinding = (SoapBinding)endpoint.getBinding();\n if (soapBinding.getBindingInfo() instanceof SoapBindingInfo) {\n SoapBindingInfo soapBindingInfo = (SoapBindingInfo)soapBinding.getBindingInfo();\n transportType = soapBindingInfo.getTransportURI();\n }\n }\n messageInfo.setTransportType((transportType != null) ? transportType : \"Unknown transport type\");\n\n originator.setProcessId(Converter.getPID());\n try {\n InetAddress inetAddress = InetAddress.getLocalHost();\n originator.setIp(inetAddress.getHostAddress());\n originator.setHostname(inetAddress.getHostName());\n } catch (UnknownHostException e) {\n originator.setHostname(\"Unknown hostname\");\n originator.setIp(\"Unknown ip address\");\n }\n\n String address = endpoint.getEndpointInfo().getAddress();\n event.getCustomInfo().put(\"address\", address);\n\n return event;\n }", "private boolean verify(String key, BoxSignatureAlgorithm actualAlgorithm, String actualSignature,\n String webHookPayload, String deliveryTimestamp) {\n if (actualSignature == null) {\n return false;\n }\n\n byte[] actual = Base64.decode(actualSignature);\n byte[] expected = this.signRaw(actualAlgorithm, key, webHookPayload, deliveryTimestamp);\n\n return Arrays.equals(expected, actual);\n }", "public Object putNodeMetaData(Object key, Object value) {\n if (key == null) throw new GroovyBugError(\"Tried to set meta data with null key on \" + this + \".\");\n if (metaDataMap == null) {\n metaDataMap = new ListHashMap();\n }\n return metaDataMap.put(key, value);\n }", "private void sendOneAsyncHint(final ByteArray slopKey,\n final Versioned<byte[]> slopVersioned,\n final List<Node> nodesToTry) {\n Node nodeToHostHint = null;\n boolean foundNode = false;\n while(nodesToTry.size() > 0) {\n nodeToHostHint = nodesToTry.remove(0);\n if(!failedNodes.contains(nodeToHostHint) && failureDetector.isAvailable(nodeToHostHint)) {\n foundNode = true;\n break;\n }\n }\n if(!foundNode) {\n Slop slop = slopSerializer.toObject(slopVersioned.getValue());\n logger.error(\"Trying to send an async hint but used up all nodes. key: \"\n + slop.getKey() + \" version: \" + slopVersioned.getVersion().toString());\n return;\n }\n final Node node = nodeToHostHint;\n int nodeId = node.getId();\n\n NonblockingStore nonblockingStore = nonblockingSlopStores.get(nodeId);\n Utils.notNull(nonblockingStore);\n\n final Long startNs = System.nanoTime();\n NonblockingStoreCallback callback = new NonblockingStoreCallback() {\n\n @Override\n public void requestComplete(Object result, long requestTime) {\n Slop slop = null;\n boolean loggerDebugEnabled = logger.isDebugEnabled();\n if(loggerDebugEnabled) {\n slop = slopSerializer.toObject(slopVersioned.getValue());\n }\n Response<ByteArray, Object> response = new Response<ByteArray, Object>(node,\n slopKey,\n result,\n requestTime);\n if(response.getValue() instanceof Exception\n && !(response.getValue() instanceof ObsoleteVersionException)) {\n if(!failedNodes.contains(node))\n failedNodes.add(node);\n if(response.getValue() instanceof UnreachableStoreException) {\n UnreachableStoreException use = (UnreachableStoreException) response.getValue();\n\n if(loggerDebugEnabled) {\n logger.debug(\"Write of key \" + slop.getKey() + \" for \"\n + slop.getNodeId() + \" to node \" + node\n + \" failed due to unreachable: \" + use.getMessage());\n }\n\n failureDetector.recordException(node, (System.nanoTime() - startNs)\n / Time.NS_PER_MS, use);\n }\n sendOneAsyncHint(slopKey, slopVersioned, nodesToTry);\n }\n\n if(loggerDebugEnabled)\n logger.debug(\"Slop write of key \" + slop.getKey() + \" for node \"\n + slop.getNodeId() + \" to node \" + node + \" succeeded in \"\n + (System.nanoTime() - startNs) + \" ns\");\n\n failureDetector.recordSuccess(node, (System.nanoTime() - startNs) / Time.NS_PER_MS);\n\n }\n };\n nonblockingStore.submitPutRequest(slopKey, slopVersioned, null, callback, timeoutMs);\n }", "public void setEnd(Date endDate) {\n\n if ((null == endDate) || getStart().after(endDate)) {\n m_explicitEnd = null;\n } else {\n m_explicitEnd = endDate;\n }\n }" ]
Before cluster management operations, i.e. remember and disable quota enforcement settings
[ "public void rememberAndDisableQuota() {\n for(Integer nodeId: nodeIds) {\n boolean quotaEnforcement = Boolean.parseBoolean(adminClient.metadataMgmtOps.getRemoteMetadata(nodeId,\n MetadataStore.QUOTA_ENFORCEMENT_ENABLED_KEY)\n .getValue());\n mapNodeToQuotaEnforcingEnabled.put(nodeId, quotaEnforcement);\n }\n adminClient.metadataMgmtOps.updateRemoteMetadata(nodeIds,\n MetadataStore.QUOTA_ENFORCEMENT_ENABLED_KEY,\n Boolean.toString(false));\n }" ]
[ "public float getColorR(int vertex, int colorset) {\n if (!hasColors(colorset)) {\n throw new IllegalStateException(\"mesh has no colorset \" + colorset);\n }\n \n checkVertexIndexBounds(vertex);\n /* bound checks for colorset are done by java for us */\n \n return m_colorsets[colorset].getFloat(vertex * 4 * SIZEOF_FLOAT);\n }", "private void processEncodedPayload() throws IOException {\n if (!readPayload) {\n payloadSpanCollector.reset();\n collect(payloadSpanCollector);\n Collection<byte[]> originalPayloadCollection = payloadSpanCollector\n .getPayloads();\n if (originalPayloadCollection.iterator().hasNext()) {\n byte[] payload = originalPayloadCollection.iterator().next();\n if (payload == null) {\n throw new IOException(\"no payload\");\n }\n MtasPayloadDecoder payloadDecoder = new MtasPayloadDecoder();\n payloadDecoder.init(startPosition(), payload);\n mtasPosition = payloadDecoder.getMtasPosition();\n } else {\n throw new IOException(\"no payload\");\n }\n }\n }", "public final Set<String> getOutputFormatsNames() {\n SortedSet<String> formats = new TreeSet<>();\n for (String formatBeanName: this.outputFormat.keySet()) {\n int endingIndex = formatBeanName.indexOf(MAP_OUTPUT_FORMAT_BEAN_NAME_ENDING);\n if (endingIndex < 0) {\n endingIndex = formatBeanName.indexOf(OUTPUT_FORMAT_BEAN_NAME_ENDING);\n }\n formats.add(formatBeanName.substring(0, endingIndex));\n }\n return formats;\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 }", "public static long getVisibilityCacheWeight(FluoConfiguration conf) {\n long size = conf.getLong(VISIBILITY_CACHE_WEIGHT, VISIBILITY_CACHE_WEIGHT_DEFAULT);\n if (size <= 0) {\n throw new IllegalArgumentException(\n \"Cache size must be positive for \" + VISIBILITY_CACHE_WEIGHT);\n }\n return size;\n }", "public void setOuterConeAngle(float angle)\n {\n setFloat(\"outer_cone_angle\", (float) Math.cos(Math.toRadians(angle)));\n mChanged.set(true);\n }", "private String getDestinationHostName(String hostName) {\n List<ServerRedirect> servers = serverRedirectService\n .tableServers(requestInformation.get().client.getId());\n for (ServerRedirect server : servers) {\n if (server.getSrcUrl().compareTo(hostName) == 0) {\n if (server.getDestUrl() != null && server.getDestUrl().compareTo(\"\") != 0) {\n return server.getDestUrl();\n } else {\n logger.warn(\"Using source URL as destination URL since no destination was specified for: {}\",\n server.getSrcUrl());\n }\n\n // only want to apply the first host name change found\n break;\n }\n }\n\n return hostName;\n }", "private void updateRoutingStrategies(Cluster cluster, List<StoreDefinition> storeDefs) {\n // acquire write lock\n writeLock.lock();\n try {\n VectorClock clock = new VectorClock();\n if(metadataCache.containsKey(ROUTING_STRATEGY_KEY))\n clock = (VectorClock) metadataCache.get(ROUTING_STRATEGY_KEY).getVersion();\n\n logger.info(\"Updating routing strategy for all stores\");\n HashMap<String, StoreDefinition> storeDefMap = makeStoreDefinitionMap(storeDefs);\n HashMap<String, RoutingStrategy> routingStrategyMap = createRoutingStrategyMap(cluster,\n storeDefMap);\n this.metadataCache.put(ROUTING_STRATEGY_KEY,\n new Versioned<Object>(routingStrategyMap,\n clock.incremented(getNodeId(),\n System.currentTimeMillis())));\n\n for(String storeName: storeNameTolisteners.keySet()) {\n RoutingStrategy updatedRoutingStrategy = routingStrategyMap.get(storeName);\n if(updatedRoutingStrategy != null) {\n try {\n for(MetadataStoreListener listener: storeNameTolisteners.get(storeName)) {\n listener.updateRoutingStrategy(updatedRoutingStrategy);\n listener.updateStoreDefinition(storeDefMap.get(storeName));\n }\n } catch(Exception e) {\n if(logger.isEnabledFor(Level.WARN))\n logger.warn(e, e);\n }\n }\n\n }\n } finally {\n writeLock.unlock();\n }\n }", "public WebSocketContext sendJsonToUser(Object data, String username) {\n return sendToTagged(JSON.toJSONString(data), username);\n }" ]
Performs the BFS and gives the results to a distributor to distribute @param distributor the distributor
[ "public void process(SearchDistributor distributor) {\r\n List<PossibleState> bootStrap;\r\n try {\r\n bootStrap = bfs(bootStrapMin);\r\n } catch (ModelException e) {\r\n bootStrap = new LinkedList<>();\r\n }\n\r\n List<Frontier> frontiers = new LinkedList<>();\r\n for (PossibleState p : bootStrap) {\r\n SCXMLFrontier dge = new SCXMLFrontier(p, model, tagExtensionList);\r\n frontiers.add(dge);\r\n }\n\r\n distributor.distribute(frontiers);\r\n }" ]
[ "public GVRAnimationChannel findChannel(String boneName)\n {\n int boneId = mSkeleton.getBoneIndex(boneName);\n if (boneId >= 0)\n {\n return mBoneChannels[boneId];\n }\n return null;\n }", "private void writeTasks(Project project)\n {\n Project.Tasks tasks = m_factory.createProjectTasks();\n project.setTasks(tasks);\n List<Project.Tasks.Task> list = tasks.getTask();\n\n for (Task task : m_projectFile.getTasks())\n {\n list.add(writeTask(task));\n }\n }", "@Override\n public T getById(Object id)\n {\n return context.getFramed().getFramedVertex(this.type, id);\n }", "public int addServerGroup(String groupName, int profileId) throws Exception {\n int groupId = -1;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\"INSERT INTO \" + Constants.DB_TABLE_SERVER_GROUPS\n + \"(\" + Constants.GENERIC_NAME + \",\" +\n Constants.GENERIC_PROFILE_ID + \")\"\n + \" VALUES (?, ?);\", PreparedStatement.RETURN_GENERATED_KEYS);\n statement.setString(1, groupName);\n statement.setInt(2, profileId);\n statement.executeUpdate();\n\n results = statement.getGeneratedKeys();\n\n if (results.next()) {\n groupId = results.getInt(1);\n } else {\n // something went wrong\n throw new Exception(\"Could not add group\");\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return groupId;\n }", "public static String wordShape(String inStr, int wordShaper, Collection<String> knownLCWords) {\r\n // this first bit is for backwards compatibility with how things were first\r\n // implemented, where the word shaper name encodes whether to useLC.\r\n // If the shaper is in the old compatibility list, then a specified\r\n // list of knownLCwords is ignored\r\n if (knownLCWords != null && dontUseLC(wordShaper)) {\r\n knownLCWords = null;\r\n }\r\n switch (wordShaper) {\r\n case NOWORDSHAPE:\r\n return inStr;\r\n case WORDSHAPEDAN1:\r\n return wordShapeDan1(inStr);\r\n case WORDSHAPECHRIS1:\r\n return wordShapeChris1(inStr);\r\n case WORDSHAPEDAN2:\r\n return wordShapeDan2(inStr, knownLCWords);\r\n case WORDSHAPEDAN2USELC:\r\n return wordShapeDan2(inStr, knownLCWords);\r\n case WORDSHAPEDAN2BIO:\r\n return wordShapeDan2Bio(inStr, knownLCWords);\r\n case WORDSHAPEDAN2BIOUSELC:\r\n return wordShapeDan2Bio(inStr, knownLCWords);\r\n case WORDSHAPEJENNY1:\r\n return wordShapeJenny1(inStr, knownLCWords);\r\n case WORDSHAPEJENNY1USELC:\r\n return wordShapeJenny1(inStr, knownLCWords);\r\n case WORDSHAPECHRIS2:\r\n return wordShapeChris2(inStr, false, knownLCWords);\r\n case WORDSHAPECHRIS2USELC:\r\n return wordShapeChris2(inStr, false, knownLCWords);\r\n case WORDSHAPECHRIS3:\r\n return wordShapeChris2(inStr, true, knownLCWords);\r\n case WORDSHAPECHRIS3USELC:\r\n return wordShapeChris2(inStr, true, knownLCWords);\r\n case WORDSHAPECHRIS4:\r\n return wordShapeChris4(inStr, false, knownLCWords);\r\n case WORDSHAPEDIGITS:\r\n return wordShapeDigits(inStr);\r\n default:\r\n throw new IllegalStateException(\"Bad WordShapeClassifier\");\r\n }\r\n }", "public synchronized void persistProperties() throws IOException {\n beginPersistence();\n\n // Read the properties file into memory\n // Shouldn't be so bad - it's a small file\n List<String> content = readFile(propertiesFile);\n\n BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(propertiesFile), StandardCharsets.UTF_8));\n\n try {\n for (String line : content) {\n String trimmed = line.trim();\n if (trimmed.length() == 0) {\n bw.newLine();\n } else {\n Matcher matcher = PROPERTY_PATTERN.matcher(trimmed);\n if (matcher.matches()) {\n final String key = cleanKey(matcher.group(1));\n if (toSave.containsKey(key) || toSave.containsKey(key + DISABLE_SUFFIX_KEY)) {\n writeProperty(bw, key, matcher.group(2));\n toSave.remove(key);\n toSave.remove(key + DISABLE_SUFFIX_KEY);\n } else if (trimmed.startsWith(COMMENT_PREFIX)) {\n // disabled user\n write(bw, line, true);\n }\n } else {\n write(bw, line, true);\n }\n }\n }\n\n endPersistence(bw);\n } finally {\n safeClose(bw);\n }\n }", "private void processActivity(Activity activity)\n {\n Task task = getParentTask(activity).addTask();\n task.setText(1, activity.getId());\n\n task.setActualDuration(activity.getActualDuration());\n task.setActualFinish(activity.getActualFinish());\n task.setActualStart(activity.getActualStart());\n //activity.getBaseunit()\n //activity.getBilled()\n //activity.getCalendar()\n //activity.getCostAccount()\n task.setCreateDate(activity.getCreationTime());\n task.setFinish(activity.getCurrentFinish());\n task.setStart(activity.getCurrentStart());\n task.setName(activity.getDescription());\n task.setDuration(activity.getDurationAtCompletion());\n task.setEarlyFinish(activity.getEarlyFinish());\n task.setEarlyStart(activity.getEarlyStart());\n task.setFreeSlack(activity.getFreeFloat());\n task.setLateFinish(activity.getLateFinish());\n task.setLateStart(activity.getLateStart());\n task.setNotes(activity.getNotes());\n task.setBaselineDuration(activity.getOriginalDuration());\n //activity.getPathFloat()\n task.setPhysicalPercentComplete(activity.getPhysicalPercentComplete());\n task.setRemainingDuration(activity.getRemainingDuration());\n task.setCost(activity.getTotalCost());\n task.setTotalSlack(activity.getTotalFloat());\n task.setMilestone(activityIsMilestone(activity));\n //activity.getUserDefined()\n task.setGUID(activity.getUuid());\n\n if (task.getMilestone())\n {\n if (activityIsStartMilestone(activity))\n {\n task.setFinish(task.getStart());\n }\n else\n {\n task.setStart(task.getFinish());\n }\n }\n\n if (task.getActualStart() == null)\n {\n task.setPercentageComplete(Integer.valueOf(0));\n }\n else\n {\n if (task.getActualFinish() != null)\n {\n task.setPercentageComplete(Integer.valueOf(100));\n }\n else\n {\n Duration remaining = activity.getRemainingDuration();\n Duration total = activity.getDurationAtCompletion();\n if (remaining != null && total != null && total.getDuration() != 0)\n {\n double percentComplete = ((total.getDuration() - remaining.getDuration()) * 100.0) / total.getDuration();\n task.setPercentageComplete(Double.valueOf(percentComplete));\n }\n }\n }\n\n m_activityMap.put(activity.getId(), task);\n }", "public static void checkDirectory(File directory) {\n if (!(directory.exists() || directory.mkdirs())) {\n throw new ReportGenerationException(\n String.format(\"Can't create data directory <%s>\", directory.getAbsolutePath())\n );\n }\n }", "public VALUE get(KEY key) {\n CacheEntry<VALUE> entry;\n synchronized (this) {\n entry = values.get(key);\n }\n VALUE value;\n if (entry != null) {\n if (isExpiring) {\n long age = System.currentTimeMillis() - entry.timeCreated;\n if (age < expirationMillis) {\n value = getValue(key, entry);\n } else {\n countExpired++;\n synchronized (this) {\n values.remove(key);\n }\n value = null;\n }\n } else {\n value = getValue(key, entry);\n }\n } else {\n value = null;\n }\n if (value != null) {\n countHit++;\n } else {\n countMiss++;\n }\n return value;\n }" ]
Create a Date instance representing a specific time. @param hour hour 0-23 @param minutes minutes 0-59 @return new Date instance
[ "public static Date getTime(int hour, int minutes)\n {\n Calendar cal = popCalendar();\n cal.set(Calendar.HOUR_OF_DAY, hour);\n cal.set(Calendar.MINUTE, minutes);\n cal.set(Calendar.SECOND, 0);\n Date result = cal.getTime();\n pushCalendar(cal);\n return result;\n }" ]
[ "public static String nextWord(String string) {\n int index = 0;\n while (index < string.length() && !Character.isWhitespace(string.charAt(index))) {\n index++;\n }\n return string.substring(0, index);\n }", "List getGroupby()\r\n {\r\n List result = _getGroupby();\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).getGroupby());\r\n }\r\n }\r\n\r\n return result;\r\n }", "protected void generateTitleBand() {\n\t\tlog.debug(\"Generating title band...\");\n\t\tJRDesignBand band = (JRDesignBand) getDesign().getPageHeader();\n\t\tint yOffset = 0;\n\n\t\t//If title is not present then subtitle will be ignored\n\t\tif (getReport().getTitle() == null)\n\t\t\treturn;\n\n\t\tif (band != null && !getDesign().isTitleNewPage()){\n\t\t\t//Title and subtitle comes afer the page header\n\t\t\tyOffset = band.getHeight();\n\n\t\t} else {\n\t\t\tband = (JRDesignBand) getDesign().getTitle();\n\t\t\tif (band == null){\n\t\t\t\tband = new JRDesignBand();\n\t\t\t\tgetDesign().setTitle(band);\n\t\t\t}\n\t\t}\n\n\t\tJRDesignExpression printWhenExpression = new JRDesignExpression();\n\t\tprintWhenExpression.setValueClass(Boolean.class);\n\t\tprintWhenExpression.setText(EXPRESSION_TRUE_WHEN_FIRST_PAGE);\n\n\t\tJRDesignTextField title = new JRDesignTextField();\n\t\tJRDesignExpression exp = new JRDesignExpression();\n\t\tif (getReport().isTitleIsJrExpression()){\n\t\t\texp.setText(getReport().getTitle());\n\t\t}else {\n\t\t\texp.setText(\"\\\"\" + Utils.escapeTextForExpression( getReport().getTitle()) + \"\\\"\");\n\t\t}\n\t\texp.setValueClass(String.class);\n\t\ttitle.setExpression(exp);\n\t\ttitle.setWidth(getReport().getOptions().getPrintableWidth());\n\t\ttitle.setHeight(getReport().getOptions().getTitleHeight());\n\t\ttitle.setY(yOffset);\n\t\ttitle.setPrintWhenExpression(printWhenExpression);\n\t\ttitle.setRemoveLineWhenBlank(true);\n\t\tapplyStyleToElement(getReport().getTitleStyle(), title);\n\t\ttitle.setStretchType( StretchTypeEnum.NO_STRETCH );\n\t\tband.addElement(title);\n\n\t\tJRDesignTextField subtitle = new JRDesignTextField();\n\t\tif (getReport().getSubtitle() != null) {\n\t\t\tJRDesignExpression exp2 = new JRDesignExpression();\n\t\t\texp2.setText(\"\\\"\" + getReport().getSubtitle() + \"\\\"\");\n\t\t\texp2.setValueClass(String.class);\n\t\t\tsubtitle.setExpression(exp2);\n\t\t\tsubtitle.setWidth(getReport().getOptions().getPrintableWidth());\n\t\t\tsubtitle.setHeight(getReport().getOptions().getSubtitleHeight());\n\t\t\tsubtitle.setY(title.getY() + title.getHeight());\n\t\t\tsubtitle.setPrintWhenExpression(printWhenExpression);\n\t\t\tsubtitle.setRemoveLineWhenBlank(true);\n\t\t\tapplyStyleToElement(getReport().getSubtitleStyle(), subtitle);\n\t\t\ttitle.setStretchType( StretchTypeEnum.NO_STRETCH );\n\t\t\tband.addElement(subtitle);\n\t\t}\n\n\n\t}", "private static boolean isWideningPrimitive(Class<?> argumentClass, Class<?> targetClass) {\n return WIDENING_TABLE.containsKey(argumentClass) && WIDENING_TABLE.get(argumentClass).contains(targetClass);\n }", "public static int queryForInt(Statement stmt, String sql, int nullvalue) {\n try {\n ResultSet rs = stmt.executeQuery(sql);\n try {\n if (!rs.next())\n return nullvalue;\n \n return rs.getInt(1);\n } finally {\n rs.close();\n }\n } catch (SQLException e) {\n throw new DukeException(e);\n }\n }", "public void setPermissions(Permissions permissions) {\n if (this.permissions == permissions) {\n return;\n }\n\n this.removeChildObject(\"permissions\");\n this.permissions = permissions;\n this.addChildObject(\"permissions\", permissions);\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 void setPatternScheme(final boolean isWeekDayBased) {\n\n if (isWeekDayBased ^ (null != m_model.getWeekDay())) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n if (isWeekDayBased) {\n m_model.setWeekDay(getPatternDefaultValues().getWeekDay());\n m_model.setWeekOfMonth(getPatternDefaultValues().getWeekOfMonth());\n } else {\n m_model.setWeekDay(null);\n m_model.setWeekOfMonth(null);\n }\n m_model.setMonth(getPatternDefaultValues().getMonth());\n m_model.setDayOfMonth(getPatternDefaultValues().getDayOfMonth());\n m_model.setInterval(getPatternDefaultValues().getInterval());\n onValueChange();\n }\n });\n }\n }", "public static Region create(String name, String label) {\n Region region = VALUES_BY_NAME.get(name.toLowerCase());\n if (region != null) {\n return region;\n } else {\n return new Region(name, label);\n }\n }" ]
Returns the text for the JSONObject of Link provided The JSONObject of Link provided should be of the type "copy" @param jsonObject of Link @return String
[ "public String getLinkCopyText(JSONObject jsonObject){\n if(jsonObject == null) return \"\";\n try {\n JSONObject copyObject = jsonObject.has(\"copyText\") ? jsonObject.getJSONObject(\"copyText\") : null;\n if(copyObject != null){\n return copyObject.has(\"text\") ? copyObject.getString(\"text\") : \"\";\n }else{\n return \"\";\n }\n } catch (JSONException e) {\n Logger.v(\"Unable to get Link Text with JSON - \"+e.getLocalizedMessage());\n return \"\";\n }\n }" ]
[ "public static Deployment of(final File content) {\n final DeploymentContent deploymentContent = DeploymentContent.of(Assert.checkNotNullParam(\"content\", content).toPath());\n return new Deployment(deploymentContent, null);\n }", "public static RgbaColor fromHsl(float H, float S, float L) {\n\n // convert to [0-1]\n H /= 360f;\n S /= 100f;\n L /= 100f;\n\n float R, G, B;\n\n if (S == 0) {\n // grey\n R = G = B = L;\n }\n else {\n float m2 = L <= 0.5 ? L * (S + 1f) : L + S - L * S;\n float m1 = 2f * L - m2;\n R = hue2rgb(m1, m2, H + 1 / 3f);\n G = hue2rgb(m1, m2, H);\n B = hue2rgb(m1, m2, H - 1 / 3f);\n }\n\n // convert [0-1] to [0-255]\n int r = Math.round(R * 255f);\n int g = Math.round(G * 255f);\n int b = Math.round(B * 255f);\n\n return new RgbaColor(r, g, b, 1);\n }", "@Override\n public void setValue(String value, boolean fireEvents) {\n\tboolean added = setSelectedValue(this, value, addMissingValue);\n\tif (added && fireEvents) {\n\t ValueChangeEvent.fire(this, getValue());\n\t}\n }", "public static byte[] concat(Bytes... listOfBytes) {\n int offset = 0;\n int size = 0;\n\n for (Bytes b : listOfBytes) {\n size += b.length() + checkVlen(b.length());\n }\n\n byte[] data = new byte[size];\n for (Bytes b : listOfBytes) {\n offset = writeVint(data, offset, b.length());\n b.copyTo(0, b.length(), data, offset);\n offset += b.length();\n }\n return data;\n }", "@Override\n public EthiopicDate date(Era era, int yearOfEra, int month, int dayOfMonth) {\n return date(prolepticYear(era, yearOfEra), month, dayOfMonth);\n }", "@Override\n public void postCrawling(CrawlSession session, ExitStatus exitStatus) {\n LOG.debug(\"postCrawling\");\n StateFlowGraph sfg = session.getStateFlowGraph();\n checkSFG(sfg);\n // TODO: call state abstraction function to get distance matrix and run rscript on it to\n // create clusters\n String[][] clusters = null;\n // generateClusters(session);\n\n result = outModelCache.close(session, exitStatus, clusters);\n\n outputBuilder.write(result, session.getConfig(), clusters);\n StateWriter writer =\n new StateWriter(outputBuilder, sfg, ImmutableMap.copyOf(visitedStates));\n for (State state : result.getStates().values()) {\n try {\n writer.writeHtmlForState(state);\n } catch (Exception Ex) {\n LOG.info(\"couldn't write state :\" + state.getName());\n }\n }\n LOG.info(\"Crawl overview plugin has finished\");\n }", "protected Violation createViolationForImport(SourceCode sourceCode, ImportNode importNode, String message) {\n Map importInfo = ImportUtil.sourceLineAndNumberForImport(sourceCode, importNode);\n Violation violation = new Violation();\n violation.setRule(this);\n violation.setSourceLine((String) importInfo.get(\"sourceLine\"));\n violation.setLineNumber((Integer) importInfo.get(\"lineNumber\"));\n violation.setMessage(message);\n return violation;\n }", "public long nextUniqueTransaction(long timeMs) {\n long id = timeMs;\n for (; ; ) {\n long old = transactionID.get();\n if (old >= id)\n id = old + 1;\n if (transactionID.compareAndSet(old, id))\n break;\n }\n return id;\n }", "public static base_response update(nitro_service client, snmpuser resource) throws Exception {\n\t\tsnmpuser updateresource = new snmpuser();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.group = resource.group;\n\t\tupdateresource.authtype = resource.authtype;\n\t\tupdateresource.authpasswd = resource.authpasswd;\n\t\tupdateresource.privtype = resource.privtype;\n\t\tupdateresource.privpasswd = resource.privpasswd;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
Gets the info for a running build @param appName See {@link #listApps} for a list of apps that can be used. @param buildId the unique identifier of the build
[ "public Build getBuildInfo(String appName, String buildId) {\n return connection.execute(new BuildInfo(appName, buildId), apiKey);\n }" ]
[ "public static String ellipsize(String text, int maxLength, String end) {\n if (text != null && text.length() > maxLength) {\n return text.substring(0, maxLength - end.length()) + end;\n }\n return text;\n }", "public Date getStartDate()\n {\n Date result = (Date) getCachedValue(ProjectField.START_DATE);\n if (result == null)\n {\n result = getParentFile().getStartDate();\n }\n return (result);\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 }", "public static void zeroTriangle( boolean upper , DMatrixRBlock A )\n {\n int blockLength = A.blockLength;\n\n if( upper ) {\n for( int i = 0; i < A.numRows; i += blockLength ) {\n int h = Math.min(blockLength,A.numRows-i);\n\n for( int j = i; j < A.numCols; j += blockLength ) {\n int w = Math.min(blockLength,A.numCols-j);\n\n int index = i*A.numCols + h*j;\n\n if( j == i ) {\n for( int k = 0; k < h; k++ ) {\n for( int l = k+1; l < w; l++ ) {\n A.data[index + w*k+l ] = 0;\n }\n }\n } else {\n for( int k = 0; k < h; k++ ) {\n for( int l = 0; l < w; l++ ) {\n A.data[index + w*k+l ] = 0;\n }\n }\n }\n }\n }\n } else {\n for( int i = 0; i < A.numRows; i += blockLength ) {\n int h = Math.min(blockLength,A.numRows-i);\n\n for( int j = 0; j <= i; j += blockLength ) {\n int w = Math.min(blockLength,A.numCols-j);\n\n int index = i*A.numCols + h*j;\n\n if( j == i ) {\n for( int k = 0; k < h; k++ ) {\n int z = Math.min(k,w);\n for( int l = 0; l < z; l++ ) {\n A.data[index + w*k+l ] = 0;\n }\n }\n } else {\n for( int k = 0; k < h; k++ ) {\n for( int l = 0; l < w; l++ ) {\n A.data[index + w*k+l ] = 0;\n }\n }\n }\n }\n }\n }\n }", "private void recoverNamespace(final NamespaceSynchronizationConfig nsConfig) {\n final MongoCollection<BsonDocument> undoCollection =\n getUndoCollection(nsConfig.getNamespace());\n final MongoCollection<BsonDocument> localCollection =\n getLocalCollection(nsConfig.getNamespace());\n final List<BsonDocument> undoDocs = undoCollection.find().into(new ArrayList<>());\n final Set<BsonValue> recoveredIds = new HashSet<>();\n\n\n // Replace local docs with undo docs. Presence of an undo doc implies we had a system failure\n // during a write. This covers updates and deletes.\n for (final BsonDocument undoDoc : undoDocs) {\n final BsonValue documentId = BsonUtils.getDocumentId(undoDoc);\n final BsonDocument filter = getDocumentIdFilter(documentId);\n localCollection.findOneAndReplace(\n filter, undoDoc, new FindOneAndReplaceOptions().upsert(true));\n recoveredIds.add(documentId);\n }\n\n // If we recovered a document, but its pending writes are set to do something else, then the\n // failure occurred after the pending writes were set, but before the undo document was\n // deleted. In this case, we should restore the document to the state that the pending\n // write indicates. There is a possibility that the pending write is from before the failed\n // operation, but in that case, the findOneAndReplace or delete is a no-op since restoring\n // the document to the state of the change event would be the same as recovering the undo\n // document.\n for (final CoreDocumentSynchronizationConfig docConfig : nsConfig.getSynchronizedDocuments()) {\n final BsonValue documentId = docConfig.getDocumentId();\n final BsonDocument filter = getDocumentIdFilter(documentId);\n\n if (recoveredIds.contains(docConfig.getDocumentId())) {\n final ChangeEvent<BsonDocument> pendingWrite = docConfig.getLastUncommittedChangeEvent();\n if (pendingWrite != null) {\n switch (pendingWrite.getOperationType()) {\n case INSERT:\n case UPDATE:\n case REPLACE:\n localCollection.findOneAndReplace(\n filter,\n pendingWrite.getFullDocument(),\n new FindOneAndReplaceOptions().upsert(true)\n );\n break;\n case DELETE:\n localCollection.deleteOne(filter);\n break;\n default:\n // There should never be pending writes with an unknown event type, but if someone\n // is messing with the config collection we want to stop the synchronizer to prevent\n // further data corruption.\n throw new IllegalStateException(\n \"there should not be a pending write with an unknown event type\"\n );\n }\n }\n }\n }\n\n // Delete all of our undo documents. If we've reached this point, we've recovered the local\n // collection to the state we want with respect to all of our undo documents. If we fail before\n // these deletes or while carrying out the deletes, but after recovering the documents to\n // their desired state, that's okay because the next recovery pass will be effectively a no-op\n // up to this point.\n for (final BsonValue recoveredId : recoveredIds) {\n undoCollection.deleteOne(getDocumentIdFilter(recoveredId));\n }\n\n // Find local documents for which there are no document configs and delete them. This covers\n // inserts, upserts, and desync deletes. This will occur on any recovery pass regardless of\n // the documents in the undo collection, so it's fine that we do this after deleting the undo\n // documents.\n localCollection.deleteMany(new BsonDocument(\n \"_id\",\n new BsonDocument(\n \"$nin\",\n new BsonArray(new ArrayList<>(\n this.syncConfig.getSynchronizedDocumentIds(nsConfig.getNamespace()))))));\n }", "private void clearDeckPreview(TrackMetadataUpdate update) {\n if (previewHotCache.remove(DeckReference.getDeckReference(update.player, 0)) != null) {\n deliverWaveformPreviewUpdate(update.player, null);\n }\n }", "public void setManyToOneAttribute(String name, AssociationValue value) {\n\t\tensureAttributes();\n\t\tAttribute attribute = new ManyToOneAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetAllAttributes().put(name, attribute);\n\n\t}", "private void processCalendarData(List<ProjectCalendar> calendars) throws SQLException\n {\n for (ProjectCalendar calendar : calendars)\n {\n processCalendarData(calendar, getRows(\"SELECT * FROM MSP_CALENDAR_DATA WHERE PROJ_ID=? AND CAL_UID=?\", m_projectID, calendar.getUniqueID()));\n }\n }", "public 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 }" ]
Reads a combined date and time value expressed in tenths of a minute. @param data byte array of data @param offset location of data as offset into the array @return time value
[ "public static final Date getTimestampFromTenths(byte[] data, int offset)\n {\n long ms = ((long) getInt(data, offset)) * 6000;\n return (DateHelper.getTimestampFromLong(EPOCH + ms));\n }" ]
[ "public void hideKeyboard() {\n InputMethodManager inputMethodManager = (InputMethodManager) getContext().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);\n inputMethodManager.hideSoftInputFromWindow(mPhoneEdit.getWindowToken(), 0);\n }", "@Override\n\tpublic RandomVariable getValue(double evaluationTime, AssetModelMonteCarloSimulationModel model) throws CalculationException {\n\t\tif(exerciseMethod == ExerciseMethod.UPPER_BOUND_METHOD) {\n\t\t\t// Find optimal lambda\n\t\t\tGoldenSectionSearch optimizer = new GoldenSectionSearch(-1.0, 1.0);\n\t\t\twhile(!optimizer.isDone()) {\n\t\t\t\tdouble lambda = optimizer.getNextPoint();\n\t\t\t\tdouble value = this.getValues(evaluationTime, model, lambda).getAverage();\n\t\t\t\toptimizer.setValue(value);\n\t\t\t}\n\t\t\treturn getValues(evaluationTime, model, optimizer.getBestPoint());\n\t\t}\n\t\telse {\n\t\t\treturn getValues(evaluationTime, model, 0.0);\n\t\t}\n\t}", "public TokenList extractSubList( Token begin , Token end ) {\n if( begin == end ) {\n remove(begin);\n return new TokenList(begin,begin);\n } else {\n if( first == begin ) {\n first = end.next;\n }\n if( last == end ) {\n last = begin.previous;\n }\n if( begin.previous != null ) {\n begin.previous.next = end.next;\n }\n if( end.next != null ) {\n end.next.previous = begin.previous;\n }\n begin.previous = null;\n end.next = null;\n\n TokenList ret = new TokenList(begin,end);\n size -= ret.size();\n return ret;\n }\n }", "private ProjectCalendar getResourceCalendar(Integer calendarID)\n {\n ProjectCalendar result = null;\n if (calendarID != null)\n {\n ProjectCalendar calendar = m_calMap.get(calendarID);\n if (calendar != null)\n {\n //\n // If the resource is linked to a base calendar, derive\n // a default calendar from the base calendar.\n //\n if (!calendar.isDerived())\n {\n ProjectCalendar resourceCalendar = m_project.addCalendar();\n resourceCalendar.setParent(calendar);\n resourceCalendar.setWorkingDay(Day.MONDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.TUESDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.WEDNESDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.THURSDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.FRIDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.SATURDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.SUNDAY, DayType.DEFAULT);\n result = resourceCalendar;\n }\n else\n {\n //\n // Primavera seems to allow a calendar to be shared between resources\n // whereas in the MS Project model there is a one-to-one\n // relationship. If we find a shared calendar, take a copy of it\n //\n if (calendar.getResource() == null)\n {\n result = calendar;\n }\n else\n {\n ProjectCalendar copy = m_project.addCalendar();\n copy.copy(calendar);\n result = copy;\n }\n }\n }\n }\n\n return result;\n }", "public static void endThreads(String check){\r\n //(error check)\r\n if(currentThread != -1L){\r\n throw new IllegalStateException(\"endThreads() called, but thread \" + currentThread + \" has not finished (exception in thread?)\");\r\n }\r\n //(end threaded environment)\r\n assert !control.isHeldByCurrentThread();\r\n isThreaded = false;\r\n //(write remaining threads)\r\n boolean cleanPass = false;\r\n while(!cleanPass){\r\n cleanPass = true;\r\n for(long thread : threadedLogQueue.keySet()){\r\n assert currentThread < 0L;\r\n if(threadedLogQueue.get(thread) != null && !threadedLogQueue.get(thread).isEmpty()){\r\n //(mark queue as unclean)\r\n cleanPass = false;\r\n //(variables)\r\n Queue<Runnable> backlog = threadedLogQueue.get(thread);\r\n currentThread = thread;\r\n //(clear buffer)\r\n while(currentThread >= 0){\r\n if(currentThread != thread){ throw new IllegalStateException(\"Redwood control shifted away from flushing thread\"); }\r\n if(backlog.isEmpty()){ throw new IllegalStateException(\"Forgot to call finishThread() on thread \" + currentThread); }\r\n assert !control.isHeldByCurrentThread();\r\n backlog.poll().run();\r\n }\r\n //(unregister thread)\r\n threadsWaiting.remove(thread);\r\n }\r\n }\r\n }\r\n while(threadsWaiting.size() > 0){\r\n assert currentThread < 0L;\r\n assert control.tryLock();\r\n assert !threadsWaiting.isEmpty();\r\n control.lock();\r\n attemptThreadControlThreadsafe(-1);\r\n control.unlock();\r\n }\r\n //(clean up)\r\n for(long threadId : threadedLogQueue.keySet()){\r\n assert threadedLogQueue.get(threadId).isEmpty();\r\n }\r\n assert threadsWaiting.isEmpty();\r\n assert currentThread == -1L;\r\n endTrack(\"Threads( \"+check+\" )\");\r\n }", "private byte[] readStreamCompressed(InputStream stream) throws IOException\r\n {\r\n ByteArrayOutputStream bao = new ByteArrayOutputStream();\r\n GZIPOutputStream gos = new GZIPOutputStream(bao);\r\n OutputStreamWriter output = new OutputStreamWriter(gos);\r\n BufferedReader input = new BufferedReader(new InputStreamReader(stream));\r\n String line;\r\n\r\n while ((line = input.readLine()) != null)\r\n {\r\n output.write(line);\r\n output.write('\\n');\r\n }\r\n input.close();\r\n stream.close();\r\n output.close();\r\n gos.close();\r\n bao.close();\r\n return bao.toByteArray();\r\n }", "public void add(Map<String, Object> map) throws SQLException {\n if (withinDataSetBatch) {\n if (batchData.size() == 0) {\n batchKeys = map.keySet();\n } else {\n if (!map.keySet().equals(batchKeys)) {\n throw new IllegalArgumentException(\"Inconsistent keys found for batch add!\");\n }\n }\n batchData.add(map);\n return;\n }\n int answer = executeUpdate(buildListQuery(map), new ArrayList<Object>(map.values()));\n if (answer != 1) {\n LOG.warning(\"Should have updated 1 row not \" + answer + \" when trying to add: \" + map);\n }\n }", "public void rename(String newName) {\n URL url = FILE_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"PUT\");\n\n JsonObject updateInfo = new JsonObject();\n updateInfo.add(\"name\", newName);\n\n request.setBody(updateInfo.toString());\n BoxAPIResponse response = request.send();\n response.disconnect();\n }", "public final void begin() {\n this.file = this.getAppender().getIoFile();\n if (this.file == null) {\n this.getAppender().getErrorHandler()\n .error(\"Scavenger not started: missing log file name\");\n return;\n }\n if (this.getProperties().getScavengeInterval() > -1) {\n final Thread thread = new Thread(this, \"Log4J File Scavenger\");\n thread.setDaemon(true);\n thread.start();\n this.threadRef = thread;\n }\n }" ]
Tries to load the custom error page at the given rootPath. @param cms {@link CmsObject} used for reading the resource (site root and uri get adjusted!) @param req the current request @param res the current response @param rootPath the VFS root path to the error page resource @return a flag, indicating if the error page could be loaded
[ "private boolean loadCustomErrorPage(\n CmsObject cms,\n HttpServletRequest req,\n HttpServletResponse res,\n String rootPath) {\n\n try {\n\n // get the site of the error page resource\n CmsSite errorSite = OpenCms.getSiteManager().getSiteForRootPath(rootPath);\n cms.getRequestContext().setSiteRoot(errorSite.getSiteRoot());\n String relPath = cms.getRequestContext().removeSiteRoot(rootPath);\n if (cms.existsResource(relPath)) {\n cms.getRequestContext().setUri(relPath);\n OpenCms.getResourceManager().loadResource(cms, cms.readResource(relPath), req, res);\n return true;\n } else {\n return false;\n }\n } catch (Throwable e) {\n // something went wrong log the exception and return false\n LOG.error(e.getMessage(), e);\n return false;\n }\n }" ]
[ "public static void acceptsDir(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_D, OPT_DIR), \"directory path for input/output\")\n .withRequiredArg()\n .describedAs(\"dir-path\")\n .ofType(String.class);\n }", "public static int findVerticalOffset(JRDesignBand band) {\n\t\tint finalHeight = 0;\n\t\tif (band != null) {\n\t\t\tfor (JRChild jrChild : band.getChildren()) {\n\t\t\t\tJRDesignElement element = (JRDesignElement) jrChild;\n\t\t\t\tint currentHeight = element.getY() + element.getHeight();\n\t\t\t\tif (currentHeight > finalHeight) finalHeight = currentHeight;\n\t\t\t}\n\t\t\treturn finalHeight;\n\t\t}\n\t\treturn finalHeight;\n\t}", "public void exceptionShift() {\n numExceptional++;\n double mag = 0.05 * numExceptional;\n if (mag > 1.0) mag = 1.0;\n\n double angle = 2.0 * UtilEjml.PI * (rand.nextDouble() - 0.5) * mag;\n performImplicitSingleStep(0, angle, true);\n\n // allow more convergence time\n nextExceptional = steps + exceptionalThresh; // (numExceptional+1)*\n }", "private boolean isCacheable(PipelineContext context) throws GeomajasException {\n\t\tVectorLayer layer = context.get(PipelineCode.LAYER_KEY, VectorLayer.class);\n\t\treturn !(layer instanceof VectorLayerLazyFeatureConversionSupport &&\n\t\t\t\t((VectorLayerLazyFeatureConversionSupport) layer).useLazyFeatureConversion());\n\t}", "public DiffNode getChild(final NodePath nodePath)\n\t{\n\t\tif (parentNode != null)\n\t\t{\n\t\t\treturn parentNode.getChild(nodePath.getElementSelectors());\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn getChild(nodePath.getElementSelectors());\n\t\t}\n\t}", "public void setPattern(String patternType) {\r\n\r\n final PatternType type = PatternType.valueOf(patternType);\r\n if (type != m_model.getPatternType()) {\r\n removeExceptionsOnChange(new Command() {\r\n\r\n public void execute() {\r\n\r\n EndType oldEndType = m_model.getEndType();\r\n m_model.setPatternType(type);\r\n m_model.setIndividualDates(null);\r\n m_model.setInterval(getPatternDefaultValues().getInterval());\r\n m_model.setEveryWorkingDay(Boolean.FALSE);\r\n m_model.clearWeekDays();\r\n m_model.clearIndividualDates();\r\n m_model.clearWeeksOfMonth();\r\n m_model.clearExceptions();\r\n if (type.equals(PatternType.NONE) || type.equals(PatternType.INDIVIDUAL)) {\r\n m_model.setEndType(EndType.SINGLE);\r\n } else if (oldEndType.equals(EndType.SINGLE)) {\r\n m_model.setEndType(EndType.TIMES);\r\n m_model.setOccurrences(10);\r\n m_model.setSeriesEndDate(null);\r\n }\r\n m_model.setDayOfMonth(getPatternDefaultValues().getDayOfMonth());\r\n m_model.setMonth(getPatternDefaultValues().getMonth());\r\n if (type.equals(PatternType.WEEKLY)) {\r\n m_model.setWeekDay(getPatternDefaultValues().getWeekDay());\r\n }\r\n valueChanged();\r\n }\r\n });\r\n }\r\n\r\n }", "protected String getQueryModifier() {\n\n String queryModifier = parseOptionalStringValue(m_configObject, JSON_KEY_QUERY_MODIFIER);\n return (null == queryModifier) && (null != m_baseConfig)\n ? m_baseConfig.getGeneralConfig().getQueryModifier()\n : queryModifier;\n }", "public AT_Row setPaddingTopChar(Character paddingTopChar) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingTopChar(paddingTopChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public static boolean isDelayedQueue(final Jedis jedis, final String key) {\n return ZSET.equalsIgnoreCase(jedis.type(key));\n }" ]
This is the main entry point used to convert the internal representation of timephased work into an external form which can be displayed to the user. @param projectCalendar calendar used by the resource assignment @param work timephased resource assignment data @param rangeUnits timescale units @param dateList timescale date ranges @return list of durations, one per timescale date range
[ "public ArrayList<Duration> segmentWork(ProjectCalendar projectCalendar, List<TimephasedWork> work, TimescaleUnits rangeUnits, List<DateRange> dateList)\n {\n ArrayList<Duration> result = new ArrayList<Duration>(dateList.size());\n int lastStartIndex = 0;\n\n //\n // Iterate through the list of dates range we are interested in.\n // Each date range in this list corresponds to a column\n // shown on the \"timescale\" view by MS Project\n //\n for (DateRange range : dateList)\n {\n //\n // If the current date range does not intersect with any of the\n // assignment date ranges in the list, then we show a zero\n // duration for this date range.\n //\n int startIndex = lastStartIndex == -1 ? -1 : getStartIndex(range, work, lastStartIndex);\n if (startIndex == -1)\n {\n result.add(Duration.getInstance(0, TimeUnit.HOURS));\n }\n else\n {\n //\n // We have found an assignment which intersects with the current\n // date range, call the method below to determine how\n // much time from this resource assignment can be allocated\n // to the current date range.\n //\n result.add(getRangeDuration(projectCalendar, rangeUnits, range, work, startIndex));\n lastStartIndex = startIndex;\n }\n }\n\n return result;\n }" ]
[ "private Table getTable(String name)\n {\n Table table = m_tables.get(name);\n if (table == null)\n {\n table = EMPTY_TABLE;\n }\n return table;\n }", "public Method getMethod(Method method) {\n return getMethod(method.getReturnType(), method.getName(), method.getParameterTypes());\n }", "private void onScrollImpl(final Vector3Axis offset, final LayoutScroller.OnScrollListener listener) {\n if (!isScrolling()) {\n mScroller = new ScrollingProcessor(offset, listener);\n mScroller.scroll();\n }\n }", "public final void setWeekDay(WeekDay weekDay) {\n\n SortedSet<WeekDay> wds = new TreeSet<>();\n if (null != weekDay) {\n wds.add(weekDay);\n }\n setWeekDays(wds);\n\n }", "public static <T extends WindupVertexFrame> WindupVertexFrame removeTypeFromModel(GraphContext graphContext, WindupVertexFrame frame, Class<T> type)\n {\n Vertex vertex = frame.getElement();\n graphContext.getGraphTypeManager().removeTypeFromElement(type, vertex);\n return graphContext.getFramed().frameElement(vertex, WindupVertexFrame.class);\n }", "public static Boolean assertFalse(Boolean value, String message) {\n if (Boolean.valueOf(value))\n throw new IllegalArgumentException(message);\n return value;\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 }", "protected final boolean isValidEndTypeForPattern() {\n\n if (getEndType() == null) {\n return false;\n }\n switch (getPatternType()) {\n case DAILY:\n case WEEKLY:\n case MONTHLY:\n case YEARLY:\n return (getEndType().equals(EndType.DATE) || getEndType().equals(EndType.TIMES));\n case INDIVIDUAL:\n case NONE:\n return getEndType().equals(EndType.SINGLE);\n default:\n return false;\n }\n }", "@Override\n public InternationalFixedDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }" ]
Delete inactive contents.
[ "public void deleteInactiveContent() throws PatchingException {\n List<File> dirs = getInactiveHistory();\n if (!dirs.isEmpty()) {\n for (File dir : dirs) {\n deleteDir(dir, ALL);\n }\n }\n dirs = getInactiveOverlays();\n if (!dirs.isEmpty()) {\n for (File dir : dirs) {\n deleteDir(dir, ALL);\n }\n }\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 JavadocLink javadocMethodLink(String memberName, Type... types) {\n return new JavadocLink(\"%s#%s(%s)\",\n getQualifiedName(),\n memberName,\n (Excerpt) code -> {\n String separator = \"\";\n for (Type type : types) {\n code.add(\"%s%s\", separator, type.getQualifiedName());\n separator = \", \";\n }\n });\n }", "public static Artifact withArtifactId(String artifactId)\n {\n Artifact artifact = new Artifact();\n artifact.artifactId = new RegexParameterizedPatternParser(artifactId);\n return artifact;\n }", "synchronized void removeServerProcess() {\n this.requiredState = InternalState.STOPPED;\n internalSetState(new ProcessRemoveTask(), InternalState.STOPPED, InternalState.PROCESS_REMOVING);\n }", "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 LayerType toDto(Class<? extends com.vividsolutions.jts.geom.Geometry> geometryClass) {\n\t\tif (geometryClass == LineString.class) {\n\t\t\treturn LayerType.LINESTRING;\n\t\t} else if (geometryClass == MultiLineString.class) {\n\t\t\treturn LayerType.MULTILINESTRING;\n\t\t} else if (geometryClass == Point.class) {\n\t\t\treturn LayerType.POINT;\n\t\t} else if (geometryClass == MultiPoint.class) {\n\t\t\treturn LayerType.MULTIPOINT;\n\t\t} else if (geometryClass == Polygon.class) {\n\t\t\treturn LayerType.POLYGON;\n\t\t} else if (geometryClass == MultiPolygon.class) {\n\t\t\treturn LayerType.MULTIPOLYGON;\n\t\t} else {\n\t\t\treturn LayerType.GEOMETRY;\n\t\t}\n\t}", "@SuppressWarnings(\"unchecked\") public Map<String, Object> getCustomProperties()\n {\n return (Map<String, Object>) getCachedValue(ProjectField.CUSTOM_PROPERTIES);\n }", "public static int color(ColorHolder colorHolder, Context ctx) {\n if (colorHolder == null) {\n return 0;\n } else {\n return colorHolder.color(ctx);\n }\n }", "public static Chart getMSDLineChart(Trajectory t, int lagMin, int lagMax,\n\t\t\tAbstractMeanSquaredDisplacmentEvaluator msdeval) {\n\n\t\tdouble[] xData = new double[lagMax - lagMin + 1];\n\t\tdouble[] yData = new double[lagMax - lagMin + 1];\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}\n\n\t\t// Create Chart\n\t\tChart chart = QuickChart.getChart(\"MSD Line\", \"LAG\", \"MSD\", \"MSD\",\n\t\t\t\txData, yData);\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}" ]
When using a map rotation, there might be tiles that are outside the rotated map area. To avoid to load these tiles, this method checks if a tile is really required to draw the map.
[ "private boolean isTileVisible(final ReferencedEnvelope tileBounds) {\n if (FloatingPointUtil.equals(this.transformer.getRotation(), 0.0)) {\n return true;\n }\n\n final GeometryFactory gfac = new GeometryFactory();\n final Optional<Geometry> rotatedMapBounds = getRotatedMapBounds(gfac);\n\n if (rotatedMapBounds.isPresent()) {\n return rotatedMapBounds.get().intersects(gfac.toGeometry(tileBounds));\n } else {\n // in case of an error, we simply load the tile\n return true;\n }\n }" ]
[ "private static boolean isDisabledHandler(final LogContext logContext, final String handlerName) {\n final Map<String, String> disableHandlers = logContext.getAttachment(CommonAttributes.ROOT_LOGGER_NAME, DISABLED_HANDLERS_KEY);\n return disableHandlers != null && disableHandlers.containsKey(handlerName);\n }", "public static void checkStringNotNullOrEmpty(String parameterName,\n String value) {\n if (TextUtils.isEmpty(value)) {\n throw Exceptions.IllegalArgument(\"Current input string %s is %s.\",\n parameterName, value == null ? \"null\" : \"empty\");\n }\n }", "public Relationship createRelationshipForEmbeddedAssociation(GraphDatabaseService executionEngine, AssociationKey associationKey, EntityKey embeddedKey) {\n\t\tString query = initCreateEmbeddedAssociationQuery( associationKey, embeddedKey );\n\t\tObject[] queryValues = createRelationshipForEmbeddedQueryValues( associationKey, embeddedKey );\n\t\treturn executeQuery( executionEngine, query, queryValues );\n\t}", "public Object remove(String name) {\n\t\tBean bean = beans.get(name);\n\t\tif (null != bean) {\n\t\t\tbeans.remove(name);\n\t\t\tbean.destructionCallback.run();\n\t\t\treturn bean.object;\n\t\t}\n\t\treturn null;\n\t}", "public static appfwprofile_xmlvalidationurl_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_xmlvalidationurl_binding obj = new appfwprofile_xmlvalidationurl_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_xmlvalidationurl_binding response[] = (appfwprofile_xmlvalidationurl_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void setConnectTimeout(int connectTimeout) {\n\t\tthis.client = this.client.newBuilder()\n\t\t\t\t.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)\n\t\t\t\t.build();\n\t}", "public ParallelTaskBuilder setReplaceVarMapToSingleTargetFromMap(\n Map<String, StrStrMap> replacementVarMapNodeSpecific,\n String uniformTargetHost) {\n setReplacementVarMapNodeSpecific(replacementVarMapNodeSpecific);\n\n if (Strings.isNullOrEmpty(uniformTargetHost)) {\n logger.error(\"uniform target host is empty or null. skip setting.\");\n return this;\n }\n for (Entry<String, StrStrMap> entry : replacementVarMapNodeSpecific\n .entrySet()) {\n\n if (entry.getValue() != null) {\n entry.getValue().addPair(PcConstants.UNIFORM_TARGET_HOST_VAR,\n uniformTargetHost);\n }\n }\n return this;\n }", "private static MonetaryFormatsSingletonSpi loadMonetaryFormatsSingletonSpi() {\n try {\n return Optional.ofNullable(Bootstrap.getService(MonetaryFormatsSingletonSpi.class))\n .orElseGet(DefaultMonetaryFormatsSingletonSpi::new);\n } catch (Exception e) {\n Logger.getLogger(MonetaryFormats.class.getName())\n .log(Level.WARNING, \"Failed to load MonetaryFormatsSingletonSpi, using default.\", e);\n return new DefaultMonetaryFormatsSingletonSpi();\n }\n }", "public void setGroupName(String name, int id) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_SERVER_GROUPS +\n \" SET \" + Constants.GENERIC_NAME + \" = ?\" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, name);\n statement.setInt(2, id);\n statement.executeUpdate();\n statement.close();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }" ]
Call commit on the underlying connection.
[ "public void localCommit()\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"commit was called\");\r\n if (!this.isInLocalTransaction)\r\n {\r\n throw new TransactionNotInProgressException(\"Not in transaction, call begin() before commit()\");\r\n }\r\n try\r\n {\r\n if(!broker.isManaged())\r\n {\r\n if (batchCon != null)\r\n {\r\n batchCon.commit();\r\n }\r\n else if (con != null)\r\n {\r\n con.commit();\r\n }\r\n }\r\n else\r\n {\r\n if(log.isDebugEnabled()) log.debug(\r\n \"Found managed environment setting in PB, will skip Connection.commit() call\");\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n log.error(\"Commit on underlying connection failed, try to rollback connection\", e);\r\n this.localRollback();\r\n throw new TransactionAbortedException(\"Commit on connection failed\", e);\r\n }\r\n finally\r\n {\r\n this.isInLocalTransaction = false;\r\n restoreAutoCommitState();\r\n this.releaseConnection();\r\n }\r\n }" ]
[ "private String getTaskField(int key)\n {\n String result = null;\n\n if ((key > 0) && (key < m_taskNames.length))\n {\n result = m_taskNames[key];\n }\n\n return (result);\n }", "private void readResource(net.sf.mpxj.planner.schema.Resource plannerResource) throws MPXJException\n {\n Resource mpxjResource = m_projectFile.addResource();\n\n //mpxjResource.setResourceCalendar(m_projectFile.getBaseCalendarByUniqueID(getInteger(plannerResource.getCalendar())));\n mpxjResource.setEmailAddress(plannerResource.getEmail());\n mpxjResource.setUniqueID(getInteger(plannerResource.getId()));\n mpxjResource.setName(plannerResource.getName());\n mpxjResource.setNotes(plannerResource.getNote());\n mpxjResource.setInitials(plannerResource.getShortName());\n mpxjResource.setType(getInt(plannerResource.getType()) == 2 ? ResourceType.MATERIAL : ResourceType.WORK);\n //plannerResource.getStdRate();\n //plannerResource.getOvtRate();\n //plannerResource.getUnits();\n //plannerResource.getProperties();\n\n ProjectCalendar calendar = mpxjResource.addResourceCalendar();\n\n calendar.setWorkingDay(Day.SUNDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.MONDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.TUESDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.WEDNESDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.THURSDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.FRIDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.SATURDAY, DayType.DEFAULT);\n\n ProjectCalendar baseCalendar = m_projectFile.getCalendarByUniqueID(getInteger(plannerResource.getCalendar()));\n if (baseCalendar == null)\n {\n baseCalendar = m_defaultCalendar;\n }\n calendar.setParent(baseCalendar);\n\n m_eventManager.fireResourceReadEvent(mpxjResource);\n }", "public static vpnclientlessaccesspolicy get(nitro_service service, String name) throws Exception{\n\t\tvpnclientlessaccesspolicy obj = new vpnclientlessaccesspolicy();\n\t\tobj.set_name(name);\n\t\tvpnclientlessaccesspolicy response = (vpnclientlessaccesspolicy) obj.get_resource(service);\n\t\treturn response;\n\t}", "protected void solveL(double[] vv) {\n\n int ii = 0;\n\n for( int i = 0; i < n; i++ ) {\n int ip = indx[i];\n double sumReal = vv[ip*2];\n double sumImg = vv[ip*2+1];\n\n vv[ip*2] = vv[i*2];\n vv[ip*2+1] = vv[i*2+1];\n\n if( ii != 0 ) {\n// for( int j = ii-1; j < i; j++ )\n// sum -= dataLU[i* n +j]*vv[j];\n int index = i*stride + (ii-1)*2;\n for( int j = ii-1; j < i; j++ ){\n double luReal = dataLU[index++];\n double luImg = dataLU[index++];\n\n double vvReal = vv[j*2];\n double vvImg = vv[j*2+1];\n\n sumReal -= luReal*vvReal - luImg*vvImg;\n sumImg -= luReal*vvImg + luImg*vvReal;\n }\n } else if( sumReal*sumReal + sumImg*sumImg != 0.0 ) {\n ii=i+1;\n }\n vv[i*2] = sumReal;\n vv[i*2+1] = sumImg;\n }\n }", "protected static void validateSignature(final DataInput input) throws IOException {\n final byte[] signatureBytes = new byte[4];\n input.readFully(signatureBytes);\n if (!Arrays.equals(ManagementProtocol.SIGNATURE, signatureBytes)) {\n throw ProtocolLogger.ROOT_LOGGER.invalidSignature(Arrays.toString(signatureBytes));\n }\n }", "private int synchroizeTaskIDToHierarchy(Task parentTask, int currentID)\n {\n for (Task task : parentTask.getChildTasks())\n {\n task.setID(Integer.valueOf(currentID++));\n add(task);\n currentID = synchroizeTaskIDToHierarchy(task, currentID);\n }\n return currentID;\n }", "@Override\n public View getView(int position, View convertView, ViewGroup parent) {\n if (position == super.getCount() && isEnableRefreshing()) {\n return (mFooter);\n }\n return (super.getView(position, convertView, parent));\n }", "public List<Class<?>> scanClasses(Predicate<String> filter)\n {\n List<Class<?>> discoveredClasses = new ArrayList<>(128);\n\n // For each Forge addon...\n for (Addon addon : furnace.getAddonRegistry().getAddons(AddonFilters.allStarted()))\n {\n List<String> discoveredFileNames = filterAddonResources(addon, filter);\n\n // Then try to load the classes.\n for (String discoveredFilename : discoveredFileNames)\n {\n String clsName = PathUtil.classFilePathToClassname(discoveredFilename);\n try\n {\n Class<?> clazz = addon.getClassLoader().loadClass(clsName);\n discoveredClasses.add(clazz);\n }\n catch (ClassNotFoundException ex)\n {\n LOG.log(Level.WARNING, \"Failed to load class for name '\" + clsName + \"':\\n\" + ex.getMessage(), ex);\n }\n }\n }\n return discoveredClasses;\n }", "protected T createInstance() {\n try {\n Constructor<T> ctor = clazz.getDeclaredConstructor();\n ctor.setAccessible(true);\n return ctor.newInstance();\n } catch (InstantiationException e) {\n throw new RuntimeException(e);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n } catch (SecurityException e) {\n throw new RuntimeException(e);\n } catch (NoSuchMethodException e) {\n throw new RuntimeException(e);\n } catch (IllegalArgumentException e) {\n throw new RuntimeException(e);\n } catch (InvocationTargetException e) {\n throw new RuntimeException(e);\n }\n }" ]
Get result of one of the task that belongs to this task's task group. @param key the task key @param <T> the actual type of the task result @return the task result, null will be returned if task has not produced a result yet
[ "@SuppressWarnings(\"unchecked\")\n protected <T extends Indexable> T taskResult(String key) {\n Indexable result = this.taskGroup.taskResult(key);\n if (result == null) {\n return null;\n } else {\n T castedResult = (T) result;\n return castedResult;\n }\n }" ]
[ "public List<Pair<int[][][], int[]>> documentsToDataAndLabelsList(Collection<List<IN>> documents) {\r\n int numDatums = 0;\r\n\r\n List<Pair<int[][][], int[]>> docList = new ArrayList<Pair<int[][][], int[]>>();\r\n for (List<IN> doc : documents) {\r\n Pair<int[][][], int[]> docPair = documentToDataAndLabels(doc);\r\n docList.add(docPair);\r\n numDatums += doc.size();\r\n }\r\n\r\n System.err.println(\"numClasses: \" + classIndex.size() + ' ' + classIndex);\r\n System.err.println(\"numDocuments: \" + docList.size());\r\n System.err.println(\"numDatums: \" + numDatums);\r\n System.err.println(\"numFeatures: \" + featureIndex.size());\r\n return docList;\r\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 }", "private boolean isForGerritHost(HttpRequest request) {\n if (!(request instanceof HttpRequestWrapper)) return false;\n HttpRequest originalRequest = ((HttpRequestWrapper) request).getOriginal();\n if (!(originalRequest instanceof HttpRequestBase)) return false;\n URI uri = ((HttpRequestBase) originalRequest).getURI();\n URI authDataUri = URI.create(authData.getHost());\n if (uri == null || uri.getHost() == null) return false;\n boolean hostEquals = uri.getHost().equals(authDataUri.getHost());\n boolean portEquals = uri.getPort() == authDataUri.getPort();\n return hostEquals && portEquals;\n }", "public void reportError(NodeT faulted, Throwable throwable) {\n faulted.setPreparer(true);\n String dependency = faulted.key();\n for (String dependentKey : nodeTable.get(dependency).dependentKeys()) {\n DAGNode<DataT, NodeT> dependent = nodeTable.get(dependentKey);\n dependent.lock().lock();\n try {\n dependent.onFaultedResolution(dependency, throwable);\n if (dependent.hasAllResolved()) {\n queue.add(dependent.key());\n }\n } finally {\n dependent.lock().unlock();\n }\n }\n }", "public char pollChar() {\n if(hasNextChar()) {\n if(hasNextWord() &&\n character+1 >= parsedLine.words().get(word).lineIndex()+\n parsedLine.words().get(word).word().length())\n word++;\n return parsedLine.line().charAt(character++);\n }\n return '\\u0000';\n }", "public void reportError(NodeT faulted, Throwable throwable) {\n faulted.setPreparer(true);\n String dependency = faulted.key();\n for (String dependentKey : nodeTable.get(dependency).dependentKeys()) {\n DAGNode<DataT, NodeT> dependent = nodeTable.get(dependentKey);\n dependent.lock().lock();\n try {\n dependent.onFaultedResolution(dependency, throwable);\n if (dependent.hasAllResolved()) {\n queue.add(dependent.key());\n }\n } finally {\n dependent.lock().unlock();\n }\n }\n }", "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 void copyTo(int srcOffset, byte[] destArray, int destOffset, int size) {\n int cursor = destOffset;\n for (ByteBuffer bb : toDirectByteBuffers(srcOffset, size)) {\n int bbSize = bb.remaining();\n if ((cursor + bbSize) > destArray.length)\n throw new ArrayIndexOutOfBoundsException(String.format(\"cursor + bbSize = %,d\", cursor + bbSize));\n bb.get(destArray, cursor, bbSize);\n cursor += bbSize;\n }\n }", "protected String statusMsg(final String queue, final Job job) throws IOException {\n final WorkerStatus status = new WorkerStatus();\n status.setRunAt(new Date());\n status.setQueue(queue);\n status.setPayload(job);\n return ObjectMapperFactory.get().writeValueAsString(status);\n }" ]
Use this API to fetch appfwlearningsettings resource of given name .
[ "public static appfwlearningsettings get(nitro_service service, String profilename) throws Exception{\n\t\tappfwlearningsettings obj = new appfwlearningsettings();\n\t\tobj.set_profilename(profilename);\n\t\tappfwlearningsettings response = (appfwlearningsettings) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
[ "private void verifyOrAddStore(String clusterURL,\n String keySchema,\n String valueSchema) {\n String newStoreDefXml = VoldemortUtils.getStoreDefXml(\n storeName,\n props.getInt(BUILD_REPLICATION_FACTOR, 2),\n props.getInt(BUILD_REQUIRED_READS, 1),\n props.getInt(BUILD_REQUIRED_WRITES, 1),\n props.getNullableInt(BUILD_PREFERRED_READS),\n props.getNullableInt(BUILD_PREFERRED_WRITES),\n props.getString(PUSH_FORCE_SCHEMA_KEY, keySchema),\n props.getString(PUSH_FORCE_SCHEMA_VALUE, valueSchema),\n description,\n owners);\n\n log.info(\"Verifying store against cluster URL: \" + clusterURL + \"\\n\" + newStoreDefXml.toString());\n StoreDefinition newStoreDef = VoldemortUtils.getStoreDef(newStoreDefXml);\n\n try {\n adminClientPerCluster.get(clusterURL).storeMgmtOps.verifyOrAddStore(newStoreDef, \"BnP config/data\",\n enableStoreCreation, this.storeVerificationExecutorService);\n } catch (UnreachableStoreException e) {\n log.info(\"verifyOrAddStore() failed on some nodes for clusterURL: \" + clusterURL + \" (this is harmless).\", e);\n // When we can't reach some node, we just skip it and won't create the store on it.\n // Next time BnP is run while the node is up, it will get the store created.\n } // Other exceptions need to bubble up!\n\n storeDef = newStoreDef;\n }", "private void processPredecessors()\n {\n for (Map.Entry<Task, List<MapRow>> entry : m_predecessorMap.entrySet())\n {\n Task task = entry.getKey();\n List<MapRow> predecessors = entry.getValue();\n for (MapRow predecessor : predecessors)\n {\n processPredecessor(task, predecessor);\n }\n }\n }", "public void transform(DataPipe cr) {\n Map<String, String> map = cr.getDataMap();\n\n for (String key : map.keySet()) {\n String value = map.get(key);\n\n if (value.equals(\"#{customplaceholder}\")) {\n // Generate a random number\n int ran = rand.nextInt();\n map.put(key, String.valueOf(ran));\n } else if (value.equals(\"#{divideBy2}\")) {\n String i = map.get(\"var_out_V3\");\n String result = String.valueOf(Integer.valueOf(i) / 2);\n map.put(key, result);\n }\n }\n }", "private 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 static String getDefaultConversionFor(String javaType)\r\n {\r\n return _jdbcConversions.containsKey(javaType) ? (String)_jdbcConversions.get(javaType) : null;\r\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 }", "@CheckResult\n public boolean isCompatible(AbstractTransition another) {\n if (getClass().equals(another.getClass()) && mTarget == another.mTarget && mReverse == another.mReverse && ((mInterpolator == null && another.mInterpolator == null) ||\n mInterpolator.getClass().equals(another.mInterpolator.getClass()))) {\n return true;\n }\n return false;\n }", "public static void convolveHV(Kernel kernel, int[] inPixels, int[] outPixels, int width, int height, boolean alpha, int edgeAction) {\n\t\tint index = 0;\n\t\tfloat[] matrix = kernel.getKernelData( null );\n\t\tint rows = kernel.getHeight();\n\t\tint cols = kernel.getWidth();\n\t\tint rows2 = rows/2;\n\t\tint cols2 = cols/2;\n\n\t\tfor (int y = 0; y < height; y++) {\n\t\t\tfor (int x = 0; x < width; x++) {\n\t\t\t\tfloat r = 0, g = 0, b = 0, a = 0;\n\n\t\t\t\tfor (int row = -rows2; row <= rows2; row++) {\n\t\t\t\t\tint iy = y+row;\n\t\t\t\t\tint ioffset;\n\t\t\t\t\tif (0 <= iy && iy < height)\n\t\t\t\t\t\tioffset = iy*width;\n\t\t\t\t\telse if ( edgeAction == CLAMP_EDGES )\n\t\t\t\t\t\tioffset = y*width;\n\t\t\t\t\telse if ( edgeAction == WRAP_EDGES )\n\t\t\t\t\t\tioffset = ((iy+height) % height) * width;\n\t\t\t\t\telse\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tint moffset = cols*(row+rows2)+cols2;\n\t\t\t\t\tfor (int col = -cols2; col <= cols2; col++) {\n\t\t\t\t\t\tfloat f = matrix[moffset+col];\n\n\t\t\t\t\t\tif (f != 0) {\n\t\t\t\t\t\t\tint ix = x+col;\n\t\t\t\t\t\t\tif (!(0 <= ix && ix < width)) {\n\t\t\t\t\t\t\t\tif ( edgeAction == CLAMP_EDGES )\n\t\t\t\t\t\t\t\t\tix = x;\n\t\t\t\t\t\t\t\telse if ( edgeAction == WRAP_EDGES )\n\t\t\t\t\t\t\t\t\tix = (x+width) % width;\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tint rgb = inPixels[ioffset+ix];\n\t\t\t\t\t\t\ta += f * ((rgb >> 24) & 0xff);\n\t\t\t\t\t\t\tr += f * ((rgb >> 16) & 0xff);\n\t\t\t\t\t\t\tg += f * ((rgb >> 8) & 0xff);\n\t\t\t\t\t\t\tb += f * (rgb & 0xff);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tint ia = alpha ? PixelUtils.clamp((int)(a+0.5)) : 0xff;\n\t\t\t\tint ir = PixelUtils.clamp((int)(r+0.5));\n\t\t\t\tint ig = PixelUtils.clamp((int)(g+0.5));\n\t\t\t\tint ib = PixelUtils.clamp((int)(b+0.5));\n\t\t\t\toutPixels[index++] = (ia << 24) | (ir << 16) | (ig << 8) | ib;\n\t\t\t}\n\t\t}\n\t}", "public void cross(Vector3d v1, Vector3d v2) {\n double tmpx = v1.y * v2.z - v1.z * v2.y;\n double tmpy = v1.z * v2.x - v1.x * v2.z;\n double tmpz = v1.x * v2.y - v1.y * v2.x;\n\n x = tmpx;\n y = tmpy;\n z = tmpz;\n }" ]
Add component processing time to given map @param mapComponentTimes @param component
[ "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 void close() throws IOException {\n for (CloseableHttpClient c : cachedClients.values()) {\n c.close();\n }\n cachedClients.clear();\n }", "public void removePathnameFromProfile(int path_id, int profileId) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \" = ?\"\n );\n statement.setInt(1, path_id);\n statement.executeUpdate();\n statement.close();\n\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_PATH +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, path_id);\n statement.executeUpdate();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "protected static PatchElement createPatchElement(final PatchEntry entry, String patchId, final List<ContentModification> modifications) {\n final PatchElement patchElement = entry.element;\n final PatchElementImpl element = new PatchElementImpl(patchId);\n element.setProvider(patchElement.getProvider());\n // Add all the rollback actions\n element.getModifications().addAll(modifications);\n element.setDescription(patchElement.getDescription());\n return element;\n }", "private List<Row> createWorkPatternAssignmentRowList(String workPatterns) throws ParseException\n {\n List<Row> list = new ArrayList<Row>();\n String[] patterns = workPatterns.split(\",|:\");\n int index = 1;\n while (index < patterns.length)\n {\n Integer workPattern = Integer.valueOf(patterns[index + 1]);\n Date startDate = DatatypeConverter.parseBasicTimestamp(patterns[index + 3]);\n Date endDate = DatatypeConverter.parseBasicTimestamp(patterns[index + 4]);\n\n Map<String, Object> map = new HashMap<String, Object>();\n map.put(\"WORK_PATTERN\", workPattern);\n map.put(\"START_DATE\", startDate);\n map.put(\"END_DATE\", endDate);\n\n list.add(new MapRow(map));\n\n index += 5;\n }\n\n return list;\n }", "public void clearHandlers() {\r\n\r\n for (Map<String, CmsAttributeHandler> handlers : m_handlers) {\r\n for (CmsAttributeHandler handler : handlers.values()) {\r\n handler.clearHandlers();\r\n }\r\n handlers.clear();\r\n }\r\n m_handlers.clear();\r\n m_handlers.add(new HashMap<String, CmsAttributeHandler>());\r\n m_handlerById.clear();\r\n }", "public static List<String> parse(final String[] args, final Object... objs) throws IOException\n {\n final List<String> ret = Colls.list();\n\n final List<Arg> allArgs = Colls.list();\n final HashMap<String, Arg> shortArgs = new HashMap<String, Arg>();\n final HashMap<String, Arg> longArgs = new HashMap<String, Arg>();\n\n parseArgs(objs, allArgs, shortArgs, longArgs);\n\n for (int i = 0; i < args.length; i++)\n {\n final String s = args[i];\n\n final Arg a;\n\n if (s.startsWith(\"--\"))\n {\n a = longArgs.get(s.substring(2));\n if (a == null)\n {\n throw new IOException(\"Unknown switch: \" + s);\n }\n }\n else if (s.startsWith(\"-\"))\n {\n a = shortArgs.get(s.substring(1));\n if (a == null)\n {\n throw new IOException(\"Unknown switch: \" + s);\n }\n }\n else\n {\n a = null;\n ret.add(s);\n }\n\n if (a != null)\n {\n if (a.isSwitch)\n {\n a.setField(\"true\");\n }\n else\n {\n if (i + 1 >= args.length)\n {\n System.out.println(\"Missing parameter for: \" + s);\n }\n if (a.isCatchAll())\n {\n final List<String> ca = Colls.list();\n for (++i; i < args.length; ++i)\n {\n ca.add(args[i]);\n }\n a.setCatchAll(ca);\n }\n else\n {\n ++i;\n a.setField(args[i]);\n }\n }\n a.setPresent();\n }\n }\n\n for (final Arg a : allArgs)\n {\n if (!a.isOk())\n {\n throw new IOException(\"Missing mandatory argument: \" + a);\n }\n }\n\n return ret;\n }", "public static OptionalString ofNullable(ResourceKey key, String value) {\n return new GenericOptionalString(RUNTIME_SOURCE, key, value);\n }", "public static String getXPathExpression(Node node) {\n\t\tObject xpathCache = node.getUserData(FULL_XPATH_CACHE);\n\t\tif (xpathCache != null) {\n\t\t\treturn xpathCache.toString();\n\t\t}\n\t\tNode parent = node.getParentNode();\n\n\t\tif ((parent == null) || parent.getNodeName().contains(\"#document\")) {\n\t\t\tString xPath = \"/\" + node.getNodeName() + \"[1]\";\n\t\t\tnode.setUserData(FULL_XPATH_CACHE, xPath, null);\n\t\t\treturn xPath;\n\t\t}\n\n\t\tif (node.hasAttributes() && node.getAttributes().getNamedItem(\"id\") != null) {\n\t\t\tString xPath = \"//\" + node.getNodeName() + \"[@id = '\"\n\t\t\t\t\t+ node.getAttributes().getNamedItem(\"id\").getNodeValue() + \"']\";\n\t\t\tnode.setUserData(FULL_XPATH_CACHE, xPath, null);\n\t\t\treturn xPath;\n\t\t}\n\n\t\tStringBuffer buffer = new StringBuffer();\n\n\t\tif (parent != node) {\n\t\t\tbuffer.append(getXPathExpression(parent));\n\t\t\tbuffer.append(\"/\");\n\t\t}\n\n\t\tbuffer.append(node.getNodeName());\n\n\t\tList<Node> mySiblings = getSiblings(parent, node);\n\n\t\tfor (int i = 0; i < mySiblings.size(); i++) {\n\t\t\tNode el = mySiblings.get(i);\n\n\t\t\tif (el.equals(node)) {\n\t\t\t\tbuffer.append('[').append(Integer.toString(i + 1)).append(']');\n\t\t\t\t// Found so break;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tString xPath = buffer.toString();\n\t\tnode.setUserData(FULL_XPATH_CACHE, xPath, null);\n\t\treturn xPath;\n\t}", "public String getEditedFilePath() {\n\n switch (getBundleType()) {\n case DESCRIPTOR:\n return m_cms.getSitePath(m_desc);\n case PROPERTY:\n return null != m_lockedBundleFiles.get(getLocale())\n ? m_cms.getSitePath(m_lockedBundleFiles.get(getLocale()).getFile())\n : m_cms.getSitePath(m_resource);\n case XML:\n return m_cms.getSitePath(m_resource);\n default:\n throw new IllegalArgumentException();\n }\n }" ]
Updates the statements of the item document identified by the given item id. The updates are computed with respect to the current data found online, making sure that no redundant deletions or duplicate insertions happen. The references of duplicate statements will be merged. @param itemIdValue id of the document to be updated @param addStatements the list of statements to be added or updated; statements with empty statement id will be added; statements with non-empty statement id will be updated (if such a statement exists) @param deleteStatements the list of statements to be deleted; statements will only be deleted if they are present in the current document (in exactly the same form, with the same id) @param summary short edit summary @return the updated document @throws MediaWikiApiErrorException if the API returns errors @throws IOException if there are IO problems, such as missing network connection
[ "public ItemDocument updateStatements(ItemIdValue itemIdValue,\n\t\t\tList<Statement> addStatements, List<Statement> deleteStatements,\n\t\t\tString summary) throws MediaWikiApiErrorException, IOException {\n\n\t\tItemDocument currentDocument = (ItemDocument) this.wikibaseDataFetcher\n\t\t\t\t.getEntityDocument(itemIdValue.getId());\n\n\t\treturn updateStatements(currentDocument, addStatements,\n\t\t\t\tdeleteStatements, summary);\n\t}" ]
[ "public void setRequestType(int pathId, Integer requestType) {\n if (requestType == null) {\n requestType = Constants.REQUEST_TYPE_GET;\n }\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + Constants.PATH_PROFILE_REQUEST_TYPE + \" = ?\" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, requestType);\n statement.setInt(2, pathId);\n statement.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "public void sortIndices(SortCoupledArray_F64 sorter ) {\n if( sorter == null )\n sorter = new SortCoupledArray_F64();\n\n sorter.quick(col_idx,numCols+1,nz_rows,nz_values);\n indicesSorted = true;\n }", "public static Map<String, Object> findFreeMarkerContextVariables(Variables variables, String... varNames)\n {\n Map<String, Object> results = new HashMap<>();\n\n for (String varName : varNames)\n {\n WindupVertexFrame payload = null;\n try\n {\n payload = Iteration.getCurrentPayload(variables, null, varName);\n }\n catch (IllegalStateException | IllegalArgumentException e)\n {\n // oh well\n }\n\n if (payload != null)\n {\n results.put(varName, payload);\n }\n else\n {\n Iterable<? extends WindupVertexFrame> var = variables.findVariable(varName);\n if (var != null)\n {\n results.put(varName, var);\n }\n }\n }\n return results;\n }", "public static vlan_interface_binding[] get(nitro_service service, Long id) throws Exception{\n\t\tvlan_interface_binding obj = new vlan_interface_binding();\n\t\tobj.set_id(id);\n\t\tvlan_interface_binding response[] = (vlan_interface_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static BufferedImage resizeToHeight(BufferedImage originalImage, int heightOut) {\n\n int width = originalImage.getWidth();\n\n int height = originalImage.getHeight();\n\n int heightPercent = (heightOut * 100) / height;\n\n int newWidth = (width * heightPercent) / 100;\n\n BufferedImage resizedImage =\n new BufferedImage(newWidth, heightOut, BufferedImage.TYPE_INT_ARGB);\n Graphics2D g = resizedImage.createGraphics();\n g.drawImage(originalImage, 0, 0, newWidth, heightOut, null);\n g.dispose();\n\n return resizedImage;\n }", "private static int[] getMode2PrimaryCodewords(String postcode, int country, int service) {\r\n\r\n for (int i = 0; i < postcode.length(); i++) {\r\n if (postcode.charAt(i) < '0' || postcode.charAt(i) > '9') {\r\n postcode = postcode.substring(0, i);\r\n break;\r\n }\r\n }\r\n\r\n int postcodeNum = Integer.parseInt(postcode);\r\n\r\n int[] primary = new int[10];\r\n primary[0] = ((postcodeNum & 0x03) << 4) | 2;\r\n primary[1] = ((postcodeNum & 0xfc) >> 2);\r\n primary[2] = ((postcodeNum & 0x3f00) >> 8);\r\n primary[3] = ((postcodeNum & 0xfc000) >> 14);\r\n primary[4] = ((postcodeNum & 0x3f00000) >> 20);\r\n primary[5] = ((postcodeNum & 0x3c000000) >> 26) | ((postcode.length() & 0x3) << 4);\r\n primary[6] = ((postcode.length() & 0x3c) >> 2) | ((country & 0x3) << 4);\r\n primary[7] = (country & 0xfc) >> 2;\r\n primary[8] = ((country & 0x300) >> 8) | ((service & 0xf) << 2);\r\n primary[9] = ((service & 0x3f0) >> 4);\r\n\r\n return primary;\r\n }", "private Integer getIntegerTimeInMinutes(Date date)\n {\n Integer result = null;\n if (date != null)\n {\n Calendar cal = DateHelper.popCalendar(date);\n int time = cal.get(Calendar.HOUR_OF_DAY) * 60;\n time += cal.get(Calendar.MINUTE);\n DateHelper.pushCalendar(cal);\n result = Integer.valueOf(time); \n }\n return (result);\n }", "public Weld property(String key, Object value) {\n properties.put(key, value);\n return this;\n }", "public WaveformDetail requestWaveformDetailFrom(final DataReference dataReference) {\n ensureRunning();\n for (WaveformDetail cached : detailHotCache.values()) {\n if (cached.dataReference.equals(dataReference)) { // Found a hot cue hit, use it.\n return cached;\n }\n }\n return requestDetailInternal(dataReference, false);\n }" ]
takes the pixels from a BufferedImage and stores them in an array
[ "private void initPixelsArray(BufferedImage image) {\n int width = image.getWidth();\n int height = image.getHeight();\n pixels = new int[width * height];\n image.getRGB(0, 0, width, height, pixels, 0, width);\n\n }" ]
[ "public static sslcertlink[] get(nitro_service service) throws Exception{\n\t\tsslcertlink obj = new sslcertlink();\n\t\tsslcertlink[] response = (sslcertlink[])obj.get_resources(service);\n\t\treturn response;\n\t}", "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 synchronized ExecutionStatistics get()\n {\n Thread currentThread = Thread.currentThread();\n if (stats.get(currentThread) == null)\n {\n stats.put(currentThread, new ExecutionStatistics());\n }\n return stats.get(currentThread);\n }", "private void processActivityCodes(Storepoint storepoint)\n {\n for (Code code : storepoint.getActivityCodes().getCode())\n {\n int sequence = 0;\n for (Value value : code.getValue())\n {\n UUID uuid = getUUID(value.getUuid(), value.getName());\n m_activityCodeValues.put(uuid, value.getName());\n m_activityCodeSequence.put(uuid, Integer.valueOf(++sequence));\n }\n }\n }", "public static Span prefix(Bytes rowPrefix) {\n Objects.requireNonNull(rowPrefix);\n Bytes fp = followingPrefix(rowPrefix);\n return new Span(rowPrefix, true, fp == null ? Bytes.EMPTY : fp, false);\n }", "public List<FailedEventInvocation> getFailedInvocations() {\n synchronized (this.mutex) {\n if (this.failedEvents == null) {\n return Collections.emptyList();\n }\n return Collections.unmodifiableList(this.failedEvents);\n }\n }", "public void setWorkingDay(Day day, boolean working)\n {\n setWorkingDay(day, (working ? DayType.WORKING : DayType.NON_WORKING));\n }", "private String getNotes(List<MapRow> rows)\n {\n String result = null;\n if (rows != null && !rows.isEmpty())\n {\n StringBuilder sb = new StringBuilder();\n for (MapRow row : rows)\n {\n sb.append(row.getString(\"TITLE\"));\n sb.append('\\n');\n sb.append(row.getString(\"TEXT\"));\n sb.append(\"\\n\\n\");\n }\n result = sb.toString();\n }\n return result;\n }", "public synchronized Message simpleRequest(Message.KnownType requestType, Message.KnownType responseType,\n Field... arguments)\n throws IOException {\n final NumberField transaction = assignTransactionNumber();\n final Message request = new Message(transaction, new NumberField(requestType.protocolValue, 2), arguments);\n sendMessage(request);\n final Message response = Message.read(is);\n if (response.transaction.getValue() != transaction.getValue()) {\n throw new IOException(\"Received response with wrong transaction ID. Expected: \" + transaction.getValue() +\n \", got: \" + response);\n }\n if (responseType != null && response.knownType != responseType) {\n throw new IOException(\"Received response with wrong type. Expected: \" + responseType +\n \", got: \" + response);\n }\n return response;\n }" ]
Set the attributes for the associated object. @param attributes attributes for associated objects @deprecated replaced by {@link #setAllAttributes(Map)} after introduction of nested associations
[ "@Deprecated\n\t@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n\tpublic void setAttributes(Map<String, PrimitiveAttribute<?>> attributes) {\n\t\tif (!isPrimitiveOnly()) {\n\t\t\tthrow new UnsupportedOperationException(\"Primitive API not supported for nested association values\");\n\t\t}\n\t\tthis.attributes = (Map) attributes;\n\t}" ]
[ "public static 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 static List<StoreDefinition> filterStores(List<StoreDefinition> storeDefs,\n final boolean isReadOnly) {\n List<StoreDefinition> filteredStores = Lists.newArrayList();\n for(StoreDefinition storeDef: storeDefs) {\n if(storeDef.getType().equals(ReadOnlyStorageConfiguration.TYPE_NAME) == isReadOnly) {\n filteredStores.add(storeDef);\n }\n }\n return filteredStores;\n }", "public static Map<String, String> parseProperties(String s) {\n\t\tMap<String, String> properties = new HashMap<String, String>();\n\t\tif (!StringUtils.isEmpty(s)) {\n\t\t\tMatcher matcher = PROPERTIES_PATTERN.matcher(s);\n\t\t\tint start = 0;\n\t\t\twhile (matcher.find()) {\n\t\t\t\taddKeyValuePairAsProperty(s.substring(start, matcher.start()), properties);\n\t\t\t\tstart = matcher.start() + 1;\n\t\t\t}\n\t\t\taddKeyValuePairAsProperty(s.substring(start), properties);\n\t\t}\n\t\treturn properties;\n\t}", "private void handleApplicationCommandRequest(SerialMessage incomingMessage) {\n\t\tlogger.trace(\"Handle Message Application Command Request\");\n\t\tint nodeId = incomingMessage.getMessagePayloadByte(1);\n\t\tlogger.debug(\"Application Command Request from Node \" + nodeId);\n\t\tZWaveNode node = getNode(nodeId);\n\t\t\n\t\tif (node == null) {\n\t\t\tlogger.warn(\"Node {} not initialized yet, ignoring message.\", nodeId);\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tnode.resetResendCount();\n\t\t\n\t\tint commandClassCode = incomingMessage.getMessagePayloadByte(3);\n\t\tZWaveCommandClass.CommandClass commandClass = ZWaveCommandClass.CommandClass.getCommandClass(commandClassCode);\n\n\t\tif (commandClass == null) {\n\t\t\tlogger.error(String.format(\"Unsupported command class 0x%02x\", commandClassCode));\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tlogger.debug(String.format(\"Incoming command class %s (0x%02x)\", commandClass.getLabel(), commandClass.getKey()));\n\t\tZWaveCommandClass zwaveCommandClass = node.getCommandClass(commandClass);\n\t\t\n\t\t// We got an unsupported command class, return.\n\t\tif (zwaveCommandClass == null) {\n\t\t\tlogger.error(String.format(\"Unsupported command class %s (0x%02x)\", commandClass.getLabel(), commandClassCode));\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tlogger.trace(\"Found Command Class {}, passing to handleApplicationCommandRequest\", zwaveCommandClass.getCommandClass().getLabel());\n\t\tzwaveCommandClass.handleApplicationCommandRequest(incomingMessage, 4, 1);\n\n\t\tif (incomingMessage.getMessageClass() == this.lastSentMessage.getExpectedReply() && nodeId == this.lastSentMessage.getMessageNode() && !incomingMessage.isTransActionCanceled()) {\n\t\t\t\tnotifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));\n\t\t\t\ttransactionCompleted.release();\n\t\t\t\tlogger.trace(\"Released. Transaction completed permit count -> {}\", transactionCompleted.availablePermits());\n\t\t}\n\t}", "public static <T, X> ObserverMethodImpl<T, X> create(EnhancedAnnotatedMethod<T, ? super X> method, RIBean<X> declaringBean, BeanManagerImpl manager, boolean isAsync) {\n if (declaringBean instanceof ExtensionBean) {\n return new ExtensionObserverMethodImpl<T, X>(method, declaringBean, manager, isAsync);\n }\n return new ObserverMethodImpl<T, X>(method, declaringBean, manager, isAsync);\n }", "public static <T, U extends Closeable> T withCloseable(U self, @ClosureParams(value=FirstParam.class) Closure<T> action) throws IOException {\n try {\n T result = action.call(self);\n\n Closeable temp = self;\n self = null;\n temp.close();\n\n return result;\n } finally {\n DefaultGroovyMethodsSupport.closeWithWarning(self);\n }\n }", "private void readException(ProjectCalendar bc, Project.Calendars.Calendar.Exceptions.Exception exception)\n {\n Date fromDate = exception.getTimePeriod().getFromDate();\n Date toDate = exception.getTimePeriod().getToDate();\n\n // Vico Schedule Planner seems to write start and end dates to FromTime and ToTime\n // rather than FromDate and ToDate. This is plain wrong, and appears to be ignored by MS Project\n // so we will ignore it too!\n if (fromDate != null && toDate != null)\n {\n ProjectCalendarException bce = bc.addCalendarException(fromDate, toDate);\n bce.setName(exception.getName());\n readRecurringData(bce, exception);\n Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes times = exception.getWorkingTimes();\n if (times != null)\n {\n List<Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes.WorkingTime> time = times.getWorkingTime();\n for (Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes.WorkingTime period : time)\n {\n Date startTime = period.getFromTime();\n Date endTime = period.getToTime();\n\n if (startTime != null && endTime != null)\n {\n if (startTime.getTime() >= endTime.getTime())\n {\n endTime = DateHelper.addDays(endTime, 1);\n }\n\n bce.addRange(new DateRange(startTime, endTime));\n }\n }\n }\n }\n }", "public static appfwprofile_cookieconsistency_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_cookieconsistency_binding obj = new appfwprofile_cookieconsistency_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_cookieconsistency_binding response[] = (appfwprofile_cookieconsistency_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private static void close(Closeable closeable) {\n\t\tif (closeable != null) {\n\t\t\ttry {\n\t\t\t\tcloseable.close();\n\t\t\t} catch (IOException ignored) {\n\t\t\t\tlogger.error(\"Failed to close output stream: \"\n\t\t\t\t\t\t+ ignored.getMessage());\n\t\t\t}\n\t\t}\n\t}" ]
Determines the partition ID that replicates the key on the given node. @param nodeId of the node @param key to look up. @return partitionId if found, otherwise null.
[ "public Integer getNodesPartitionIdForKey(int nodeId, final byte[] key) {\n // this is all the partitions the key replicates to.\n List<Integer> partitionIds = getReplicatingPartitionList(key);\n for(Integer partitionId: partitionIds) {\n // check which of the replicating partitions belongs to the node in\n // question\n if(getNodeIdForPartitionId(partitionId) == nodeId) {\n return partitionId;\n }\n }\n return null;\n }" ]
[ "public Task<RemoteInsertOneResult> insertOne(final DocumentT document) {\n return dispatcher.dispatchTask(new Callable<RemoteInsertOneResult>() {\n @Override\n public RemoteInsertOneResult call() {\n return proxy.insertOne(document);\n }\n });\n }", "public PayloadBuilder customField(final String key, final Object value) {\n root.put(key, value);\n return this;\n }", "public static base_responses delete(nitro_service client, String Dnssuffix[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (Dnssuffix != null && Dnssuffix.length > 0) {\n\t\t\tdnssuffix deleteresources[] = new dnssuffix[Dnssuffix.length];\n\t\t\tfor (int i=0;i<Dnssuffix.length;i++){\n\t\t\t\tdeleteresources[i] = new dnssuffix();\n\t\t\t\tdeleteresources[i].Dnssuffix = Dnssuffix[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "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 }", "public String getScopes() {\n final StringBuilder sb = new StringBuilder();\n for (final Scope scope : Scope.values()) {\n sb.append(scope);\n sb.append(\", \");\n }\n final String scopes = sb.toString().trim();\n return scopes.substring(0, scopes.length() - 1);\n }", "public static void setFilterBoxStyle(TextField searchBox) {\n\n searchBox.setIcon(FontOpenCms.FILTER);\n\n searchBox.setPlaceholder(\n org.opencms.ui.apps.Messages.get().getBundle(UI.getCurrent().getLocale()).key(\n org.opencms.ui.apps.Messages.GUI_EXPLORER_FILTER_0));\n searchBox.addStyleName(ValoTheme.TEXTFIELD_INLINE_ICON);\n }", "protected Collection provideStateManagers(Collection pojos)\r\n {\r\n \tPersistenceCapable pc;\r\n \tint [] fieldNums;\r\n \tIterator iter = pojos.iterator();\r\n \tCollection result = new ArrayList();\r\n \t\r\n \twhile (iter.hasNext())\r\n \t{\r\n \t\t// obtain a StateManager\r\n \t\tpc = (PersistenceCapable) iter.next();\r\n \t\tIdentity oid = new Identity(pc, broker);\r\n \t\tStateManagerInternal smi = pmi.getStateManager(oid, pc.getClass()); \r\n \t\t\r\n \t\t// fetch attributes into StateManager\r\n\t\t\tJDOClass jdoClass = Helper.getJDOClass(pc.getClass());\r\n\t\t\tfieldNums = jdoClass.getManagedFieldNumbers();\r\n\r\n\t\t\tFieldManager fm = new OjbFieldManager(pc, broker);\r\n\t\t\tsmi.replaceFields(fieldNums, fm);\r\n\t\t\tsmi.retrieve();\r\n\t\t\t\r\n\t\t\t// get JDO PersistencecCapable instance from SM and add it to result collection\r\n\t\t\tObject instance = smi.getObject();\r\n\t\t\tresult.add(instance);\r\n \t}\r\n \treturn result; \r\n\t}", "@SuppressWarnings(\"boxing\")\r\n public OAuth1Token getAccessToken(OAuth1RequestToken oAuthRequestToken, String verifier) {\r\n OAuth10aService service = new ServiceBuilder(apiKey)\r\n .apiSecret(sharedSecret)\r\n .build(FlickrApi.instance());\r\n\r\n // Flickr seems to return invalid token sometimes so retry a few times.\r\n // See http://www.flickr.com/groups/api/discuss/72157628028927244/\r\n OAuth1Token accessToken = null;\r\n boolean success = false;\r\n for (int i = 0; i < maxGetTokenRetries && !success; i++) {\r\n try {\r\n accessToken = service.getAccessToken(oAuthRequestToken, verifier);\r\n success = true;\r\n } catch (OAuthException | IOException | InterruptedException | ExecutionException e) {\r\n if (i == maxGetTokenRetries - 1) {\r\n logger.error(String.format(\"OAuthService.getAccessToken failing after %d tries, re-throwing exception\", i), e);\r\n throw new FlickrRuntimeException(e);\r\n } else {\r\n logger.warn(String.format(\"OAuthService.getAccessToken failed, try number %d: %s\", i, e.getMessage()));\r\n try {\r\n Thread.sleep(500);\r\n } catch (InterruptedException ie) {\r\n // Do nothing\r\n }\r\n }\r\n }\r\n }\r\n\r\n return accessToken;\r\n }", "@SafeVarargs\n public static <K> Set<K> set(final K... keys) {\n return new LinkedHashSet<K>(Arrays.asList(keys));\n }" ]
Deletes an organization @param organizationId String
[ "public void deleteOrganization(final String organizationId) {\n final DbOrganization dbOrganization = getOrganization(organizationId);\n repositoryHandler.deleteOrganization(dbOrganization.getName());\n repositoryHandler.removeModulesOrganization(dbOrganization);\n }" ]
[ "private void setCorrectDay(Calendar date) {\n\n if (monthHasNotDay(date)) {\n date.set(Calendar.DAY_OF_MONTH, date.getActualMaximum(Calendar.DAY_OF_MONTH));\n } else {\n date.set(Calendar.DAY_OF_MONTH, m_dayOfMonth);\n }\n }", "public static <T, C extends Comparable<? super C>> List<T> sortInplaceBy(List<T> list,\n\t\t\tfinal Functions.Function1<? super T, C> key) {\n\t\tif (key == null)\n\t\t\tthrow new NullPointerException(\"key\");\n\t\tCollections.sort(list, new KeyComparator<T, C>(key));\n\t\treturn list;\n\t}", "public void addComparator(Comparator<T> comparator, boolean ascending) {\n\t\tthis.comparators.add(new InvertibleComparator<T>(comparator, ascending));\n\t}", "protected static boolean isOperatorLR( Symbol s ) {\n if( s == null )\n return false;\n\n switch( s ) {\n case ELEMENT_DIVIDE:\n case ELEMENT_TIMES:\n case ELEMENT_POWER:\n case RDIVIDE:\n case LDIVIDE:\n case TIMES:\n case POWER:\n case PLUS:\n case MINUS:\n case ASSIGN:\n return true;\n }\n return false;\n }", "@Override\n public Object invoke(Object self, Method method, Method proceed, Object[] args) throws Throwable {\n if (\"destroy\".equals(method.getName()) && Marker.isMarker(0, method, args)) {\n if (bean.getEjbDescriptor().isStateful()) {\n if (!reference.isRemoved()) {\n reference.remove();\n }\n }\n return null;\n }\n\n if (!bean.isClientCanCallRemoveMethods() && isRemoveMethod(method)) {\n throw BeanLogger.LOG.invalidRemoveMethodInvocation(method);\n }\n Class<?> businessInterface = getBusinessInterface(method);\n if (reference.isRemoved() && isToStringMethod(method)) {\n return businessInterface.getName() + \" [REMOVED]\";\n }\n Object proxiedInstance = reference.getBusinessObject(businessInterface);\n\n if (!Modifier.isPublic(method.getModifiers())) {\n throw new EJBException(\"Not a business method \" + method.toString() +\". Do not call non-public methods on EJB's.\");\n }\n Object returnValue = Reflections.invokeAndUnwrap(proxiedInstance, method, args);\n BeanLogger.LOG.callProxiedMethod(method, proxiedInstance, args, returnValue);\n return returnValue;\n }", "public static int nullity(SingularValueDecomposition_F64 svd , double threshold ) {\n int ret = 0;\n\n double w[]= svd.getSingularValues();\n\n int N = svd.numberOfSingularValues();\n\n int numCol = svd.numCols();\n\n for( int j = 0; j < N; j++ ) {\n if( w[j] <= threshold) ret++;\n }\n return ret + numCol-N;\n }", "protected EObject forceCreateModelElementAndSet(Action action, EObject value) {\n \tEObject result = semanticModelBuilder.create(action.getType().getClassifier());\n \tsemanticModelBuilder.set(result, action.getFeature(), value, null /* ParserRule */, currentNode);\n \tinsertCompositeNode(action);\n \tassociateNodeWithAstElement(currentNode, result);\n \treturn result;\n }", "public PhotoList<Photo> getContactsPhotos(int count, boolean justFriends, boolean singlePhoto, boolean includeSelf) throws FlickrException {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_CONTACTS_PHOTOS);\r\n\r\n if (count > 0) {\r\n parameters.put(\"count\", Integer.toString(count));\r\n }\r\n if (justFriends) {\r\n parameters.put(\"just_friends\", \"1\");\r\n }\r\n if (singlePhoto) {\r\n parameters.put(\"single_photo\", \"1\");\r\n }\r\n if (includeSelf) {\r\n parameters.put(\"include_self\", \"1\");\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\r\n photos.setPage(\"1\");\r\n photos.setPages(\"1\");\r\n photos.setPerPage(\"\" + photoNodes.getLength());\r\n photos.setTotal(\"\" + photoNodes.getLength());\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element photoElement = (Element) photoNodes.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement));\r\n }\r\n return photos;\r\n }", "@SuppressWarnings({\"unchecked\", \"WeakerAccess\"})\n public static <T> List<T> readListAttributeElement(final XMLExtendedStreamReader reader, final String attributeName,\n final Class<T> type) throws XMLStreamException {\n requireSingleAttribute(reader, attributeName);\n // todo: fix this when this method signature is corrected\n final List<T> value = (List<T>) reader.getListAttributeValue(0, type);\n requireNoContent(reader);\n return value;\n }" ]
Returns the right string representation of the effort level based on given number of points.
[ "public static String getEffortLevelDescription(Verbosity verbosity, int points)\n {\n EffortLevel level = EffortLevel.forPoints(points);\n\n switch (verbosity)\n {\n case ID:\n return level.name();\n case VERBOSE:\n return level.getVerboseDescription();\n case SHORT:\n default:\n return level.getShortDescription();\n }\n }" ]
[ "public int getModifiers() {\n MetaMethod getter = getGetter();\n MetaMethod setter = getSetter();\n if (setter != null && getter == null) return setter.getModifiers();\n if (getter != null && setter == null) return getter.getModifiers();\n int modifiers = getter.getModifiers() | setter.getModifiers();\n int visibility = 0;\n if (Modifier.isPublic(modifiers)) visibility = Modifier.PUBLIC;\n if (Modifier.isProtected(modifiers)) visibility = Modifier.PROTECTED;\n if (Modifier.isPrivate(modifiers)) visibility = Modifier.PRIVATE;\n int states = getter.getModifiers() & setter.getModifiers();\n states &= ~(Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE);\n states |= visibility;\n return states;\n }", "protected FieldDescriptor resolvePayloadField(Message message) {\n for (FieldDescriptor field : message.getDescriptorForType().getFields()) {\n if (message.hasField(field)) {\n return field;\n }\n }\n\n throw new RuntimeException(\"No payload found in message \" + message);\n }", "public static ProjectWriter getProjectWriter(String name) throws InstantiationException, IllegalAccessException\n {\n int index = name.lastIndexOf('.');\n if (index == -1)\n {\n throw new IllegalArgumentException(\"Filename has no extension: \" + name);\n }\n\n String extension = name.substring(index + 1).toUpperCase();\n\n Class<? extends ProjectWriter> fileClass = WRITER_MAP.get(extension);\n if (fileClass == null)\n {\n throw new IllegalArgumentException(\"Cannot write files of type: \" + name);\n }\n\n ProjectWriter file = fileClass.newInstance();\n\n return (file);\n }", "public static Object unmarshal(String message, Class<?> childClass) {\n try {\n Class<?>[] reverseAndToArray = Iterables.toArray(Lists.reverse(getAllSuperTypes(childClass)), Class.class);\n JAXBContext jaxbCtx = JAXBContext.newInstance(reverseAndToArray);\n Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller();\n\n return unmarshaller.unmarshal(new StringReader(message));\n } catch (Exception e) {\n }\n\n return null;\n }", "public static String readCorrelationId(Message message) {\n String correlationId = null;\n Map<String, List<String>> headers = getOrCreateProtocolHeader(message);\n List<String> correlationIds = headers.get(CORRELATION_ID_KEY);\n if (correlationIds != null && correlationIds.size() > 0) {\n correlationId = correlationIds.get(0);\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"HTTP header '\" + CORRELATION_ID_KEY + \"' found: \" + correlationId);\n }\n } else {\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"No HTTP header '\" + CORRELATION_ID_KEY + \"' found\");\n }\n }\n\n return correlationId;\n }", "ServerStatus getState() {\n final InternalState requiredState = this.requiredState;\n final InternalState state = internalState;\n if(requiredState == InternalState.FAILED) {\n return ServerStatus.FAILED;\n }\n switch (state) {\n case STOPPED:\n return ServerStatus.STOPPED;\n case SERVER_STARTED:\n return ServerStatus.STARTED;\n default: {\n if(requiredState == InternalState.SERVER_STARTED) {\n return ServerStatus.STARTING;\n } else {\n return ServerStatus.STOPPING;\n }\n }\n }\n }", "public static <T> void notNull(final String name, final T value) {\n if (value == null) {\n throw new IllegalArgumentException(name + \" can not be null\");\n }\n }", "public void 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 Map<Integer, TableDefinition> tableDefinitions()\n {\n Map<Integer, TableDefinition> result = new HashMap<Integer, TableDefinition>();\n\n result.put(Integer.valueOf(2), new TableDefinition(\"PROJECT_SUMMARY\", columnDefinitions(PROJECT_SUMMARY_COLUMNS, projectSummaryColumnsOrder())));\n result.put(Integer.valueOf(7), new TableDefinition(\"BAR\", columnDefinitions(BAR_COLUMNS, barColumnsOrder())));\n result.put(Integer.valueOf(11), new TableDefinition(\"CALENDAR\", columnDefinitions(CALENDAR_COLUMNS, calendarColumnsOrder())));\n result.put(Integer.valueOf(12), new TableDefinition(\"EXCEPTIONN\", columnDefinitions(EXCEPTIONN_COLUMNS, exceptionColumnsOrder())));\n result.put(Integer.valueOf(14), new TableDefinition(\"EXCEPTION_ASSIGNMENT\", columnDefinitions(EXCEPTION_ASSIGNMENT_COLUMNS, exceptionAssignmentColumnsOrder())));\n result.put(Integer.valueOf(15), new TableDefinition(\"TIME_ENTRY\", columnDefinitions(TIME_ENTRY_COLUMNS, timeEntryColumnsOrder())));\n result.put(Integer.valueOf(17), new TableDefinition(\"WORK_PATTERN\", columnDefinitions(WORK_PATTERN_COLUMNS, workPatternColumnsOrder()))); \n result.put(Integer.valueOf(18), new TableDefinition(\"TASK_COMPLETED_SECTION\", columnDefinitions(TASK_COMPLETED_SECTION_COLUMNS, taskCompletedSectionColumnsOrder()))); \n result.put(Integer.valueOf(21), new TableDefinition(\"TASK\", columnDefinitions(TASK_COLUMNS, taskColumnsOrder())));\n result.put(Integer.valueOf(22), new TableDefinition(\"MILESTONE\", columnDefinitions(MILESTONE_COLUMNS, milestoneColumnsOrder())));\n result.put(Integer.valueOf(23), new TableDefinition(\"EXPANDED_TASK\", columnDefinitions(EXPANDED_TASK_COLUMNS, expandedTaskColumnsOrder())));\n result.put(Integer.valueOf(25), new TableDefinition(\"LINK\", columnDefinitions(LINK_COLUMNS, linkColumnsOrder())));\n result.put(Integer.valueOf(61), new TableDefinition(\"CONSUMABLE_RESOURCE\", columnDefinitions(CONSUMABLE_RESOURCE_COLUMNS, consumableResourceColumnsOrder())));\n result.put(Integer.valueOf(62), new TableDefinition(\"PERMANENT_RESOURCE\", columnDefinitions(PERMANENT_RESOURCE_COLUMNS, permanentResourceColumnsOrder())));\n result.put(Integer.valueOf(63), new TableDefinition(\"PERM_RESOURCE_SKILL\", columnDefinitions(PERMANENT_RESOURCE_SKILL_COLUMNS, permanentResourceSkillColumnsOrder())));\n result.put(Integer.valueOf(67), new TableDefinition(\"PERMANENT_SCHEDUL_ALLOCATION\", columnDefinitions(PERMANENT_SCHEDULE_ALLOCATION_COLUMNS, permanentScheduleAllocationColumnsOrder())));\n result.put(Integer.valueOf(190), new TableDefinition(\"WBS_ENTRY\", columnDefinitions(WBS_ENTRY_COLUMNS, wbsEntryColumnsOrder())));\n\n return result;\n }" ]
Inserts the provided document. If the document is missing an identifier, the client should generate one. @param document the document to insert @return a task containing the result of the insert one operation
[ "public Task<RemoteInsertOneResult> insertOne(final DocumentT document) {\n return dispatcher.dispatchTask(new Callable<RemoteInsertOneResult>() {\n @Override\n public RemoteInsertOneResult call() {\n return proxy.insertOne(document);\n }\n });\n }" ]
[ "public ProjectCalendarException addCalendarException(Date fromDate, Date toDate)\n {\n ProjectCalendarException bce = new ProjectCalendarException(fromDate, toDate);\n m_exceptions.add(bce);\n m_expandedExceptions.clear();\n m_exceptionsSorted = false;\n clearWorkingDateCache();\n return bce;\n }", "public static int randomIntBetween(int min, int max) {\n Random rand = new Random();\n return rand.nextInt((max - min) + 1) + min;\n }", "public void forAllTables(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _torqueModel.getTables(); it.hasNext(); )\r\n {\r\n _curTableDef = (TableDef)it.next();\r\n generate(template);\r\n }\r\n _curTableDef = null;\r\n }", "public static double[] computeSeasonalAdjustments(double[] realizedCPIValues, int lastMonth, int numberOfYearsToAverage) {\n\n\t\t/*\n\t\t * Cacluate average log returns\n\t\t */\n\t\tdouble[] averageLogReturn = new double[12];\n\t\tArrays.fill(averageLogReturn, 0.0);\n\t\tfor(int arrayIndex = 0; arrayIndex < 12*numberOfYearsToAverage; arrayIndex++){\n\n\t\t\tint month = (((((lastMonth-1 - arrayIndex) % 12) + 12) % 12));\n\n\t\t\tdouble logReturn = Math.log(realizedCPIValues[realizedCPIValues.length - 1 - arrayIndex] / realizedCPIValues[realizedCPIValues.length - 2 - arrayIndex]);\n\t\t\taverageLogReturn[month] += logReturn/numberOfYearsToAverage;\n\t\t}\n\n\t\t/*\n\t\t * Normalize\n\t\t */\n\t\tdouble sum = 0.0;\n\t\tfor(int index = 0; index < averageLogReturn.length; index++){\n\t\t\tsum += averageLogReturn[index];\n\t\t}\n\t\tdouble averageSeasonal = sum / averageLogReturn.length;\n\n\t\tdouble[] seasonalAdjustments = new double[averageLogReturn.length];\n\t\tfor(int index = 0; index < seasonalAdjustments.length; index++){\n\t\t\tseasonalAdjustments[index] = averageLogReturn[index] - averageSeasonal;\n\t\t}\n\n\t\t// Annualize seasonal adjustments\n\t\tfor(int index = 0; index < seasonalAdjustments.length; index++){\n\t\t\tseasonalAdjustments[index] = seasonalAdjustments[index] * 12;\n\t\t}\n\n\t\treturn seasonalAdjustments;\n\t}", "private void addUDFValue(FieldTypeClass fieldType, FieldContainer container, Row row)\n {\n Integer fieldId = row.getInteger(\"udf_type_id\");\n String fieldName = m_udfFields.get(fieldId);\n\n Object value = null;\n FieldType field = m_project.getCustomFields().getFieldByAlias(fieldType, fieldName);\n if (field != null)\n {\n DataType fieldDataType = field.getDataType();\n\n switch (fieldDataType)\n {\n case DATE:\n {\n value = row.getDate(\"udf_date\");\n break;\n }\n\n case CURRENCY:\n case NUMERIC:\n {\n value = row.getDouble(\"udf_number\");\n break;\n }\n\n case GUID:\n case INTEGER:\n {\n value = row.getInteger(\"udf_code_id\");\n break;\n }\n\n case BOOLEAN:\n {\n String text = row.getString(\"udf_text\");\n if (text != null)\n {\n // before a normal boolean parse, we try to lookup the text as a P6 static type indicator UDF\n value = STATICTYPE_UDF_MAP.get(text);\n if (value == null)\n {\n value = Boolean.valueOf(row.getBoolean(\"udf_text\"));\n }\n }\n else\n {\n value = Boolean.valueOf(row.getBoolean(\"udf_number\"));\n }\n break;\n }\n\n default:\n {\n value = row.getString(\"udf_text\");\n break;\n }\n }\n\n container.set(field, value);\n }\n }", "public static long access2d(DMatrixRMaj a , DMatrixRMaj b , DMatrixRMaj c )\n {\n long timeBefore = System.currentTimeMillis();\n\n for( int i = 0; i < a.numRows; i++ ) {\n\n for( int j = 0; j < b.numCols; j++ ) {\n c.set(i,j,a.get(i,0)*b.get(0,j));\n }\n\n for( int k = 1; k < b.numRows; k++ ) {\n for( int j = 0; j < b.numCols; j++ ) {\n// c.set(i,j, c.get(i,j) + a.get(i,k)*b.get(k,j));\n c.data[i*b.numCols+j] +=a.get(i,k)*b.get(k,j);\n }\n }\n }\n\n return System.currentTimeMillis() - timeBefore;\n }", "public ItemRequest<Task> findById(String task) {\n \n String path = String.format(\"/tasks/%s\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"GET\");\n }", "private CoreLabel makeCoreLabel(String line) {\r\n CoreLabel wi = new CoreLabel();\r\n // wi.line = line;\r\n String[] bits = line.split(\"\\\\s+\");\r\n switch (bits.length) {\r\n case 0:\r\n case 1:\r\n wi.setWord(BOUNDARY);\r\n wi.set(AnswerAnnotation.class, OTHER);\r\n break;\r\n case 2:\r\n wi.setWord(bits[0]);\r\n wi.set(AnswerAnnotation.class, bits[1]);\r\n break;\r\n case 3:\r\n wi.setWord(bits[0]);\r\n wi.setTag(bits[1]);\r\n wi.set(AnswerAnnotation.class, bits[2]);\r\n break;\r\n case 4:\r\n wi.setWord(bits[0]);\r\n wi.setTag(bits[1]);\r\n wi.set(ChunkAnnotation.class, bits[2]);\r\n wi.set(AnswerAnnotation.class, bits[3]);\r\n break;\r\n case 5:\r\n if (flags.useLemmaAsWord) {\r\n wi.setWord(bits[1]);\r\n } else {\r\n wi.setWord(bits[0]);\r\n }\r\n wi.set(LemmaAnnotation.class, bits[1]);\r\n wi.setTag(bits[2]);\r\n wi.set(ChunkAnnotation.class, bits[3]);\r\n wi.set(AnswerAnnotation.class, bits[4]);\r\n break;\r\n default:\r\n throw new RuntimeIOException(\"Unexpected input (many fields): \" + line);\r\n }\r\n wi.set(OriginalAnswerAnnotation.class, wi.get(AnswerAnnotation.class));\r\n return wi;\r\n }", "private void processClientId(HttpServletRequest httpServletRequest, History history) {\n // get the client id from the request header if applicable.. otherwise set to default\n // also set the client uuid in the history object\n if (httpServletRequest.getHeader(Constants.PROFILE_CLIENT_HEADER_NAME) != null &&\n !httpServletRequest.getHeader(Constants.PROFILE_CLIENT_HEADER_NAME).equals(\"\")) {\n history.setClientUUID(httpServletRequest.getHeader(Constants.PROFILE_CLIENT_HEADER_NAME));\n } else {\n history.setClientUUID(Constants.PROFILE_CLIENT_DEFAULT_ID);\n }\n logger.info(\"Client UUID is: {}\", history.getClientUUID());\n }" ]
Special multiplication that takes in account the zeros and one in Y, which is the matrix that stores the householder vectors.
[ "public static void multAdd_zeros(final int blockLength ,\n final DSubmatrixD1 Y , final DSubmatrixD1 B ,\n final DSubmatrixD1 C )\n {\n int widthY = Y.col1 - Y.col0;\n\n for( int i = Y.row0; i < Y.row1; i += blockLength ) {\n int heightY = Math.min( blockLength , Y.row1 - i );\n\n for( int j = B.col0; j < B.col1; j += blockLength ) {\n int widthB = Math.min( blockLength , B.col1 - j );\n\n int indexC = (i-Y.row0+C.row0)*C.original.numCols + (j-B.col0+C.col0)*heightY;\n\n for( int k = Y.col0; k < Y.col1; k += blockLength ) {\n int indexY = i*Y.original.numCols + k*heightY;\n int indexB = (k-Y.col0+B.row0)*B.original.numCols + j*widthY;\n\n if( i == Y.row0 ) {\n multBlockAdd_zerosone(Y.original.data,B.original.data,C.original.data,\n indexY,indexB,indexC,heightY,widthY,widthB);\n } else {\n InnerMultiplication_DDRB.blockMultPlus(Y.original.data,B.original.data,C.original.data,\n indexY,indexB,indexC,heightY,widthY,widthB);\n }\n }\n }\n }\n }" ]
[ "private static int getBinaryLength(int version, QrMode[] inputModeUnoptimized, int[] inputData, boolean gs1, int eciMode) {\n\n int i, j;\n QrMode currentMode;\n int inputLength = inputModeUnoptimized.length;\n int count = 0;\n int alphaLength;\n int percent = 0;\n\n // ZINT NOTE: in Zint, this call modifies the input mode array directly; here, we leave\n // the original array alone so that subsequent binary length checks don't irrevocably\n // optimize the mode array for the wrong QR Code version\n QrMode[] inputMode = applyOptimisation(version, inputModeUnoptimized);\n\n currentMode = QrMode.NULL;\n\n if (gs1) {\n count += 4;\n }\n\n if (eciMode != 3) {\n count += 12;\n }\n\n for (i = 0; i < inputLength; i++) {\n if (inputMode[i] != currentMode) {\n count += 4;\n switch (inputMode[i]) {\n case KANJI:\n count += tribus(version, 8, 10, 12);\n count += (blockLength(i, inputMode) * 13);\n break;\n case BINARY:\n count += tribus(version, 8, 16, 16);\n for (j = i; j < (i + blockLength(i, inputMode)); j++) {\n if (inputData[j] > 0xff) {\n count += 16;\n } else {\n count += 8;\n }\n }\n break;\n case ALPHANUM:\n count += tribus(version, 9, 11, 13);\n alphaLength = blockLength(i, inputMode);\n // In alphanumeric mode % becomes %%\n if (gs1) {\n for (j = i; j < (i + alphaLength); j++) { // TODO: need to do this only if in GS1 mode? or is the other code wrong? https://sourceforge.net/p/zint/tickets/104/#227b\n if (inputData[j] == '%') {\n percent++;\n }\n }\n }\n alphaLength += percent;\n switch (alphaLength % 2) {\n case 0:\n count += (alphaLength / 2) * 11;\n break;\n case 1:\n count += ((alphaLength - 1) / 2) * 11;\n count += 6;\n break;\n }\n break;\n case NUMERIC:\n count += tribus(version, 10, 12, 14);\n switch (blockLength(i, inputMode) % 3) {\n case 0:\n count += (blockLength(i, inputMode) / 3) * 10;\n break;\n case 1:\n count += ((blockLength(i, inputMode) - 1) / 3) * 10;\n count += 4;\n break;\n case 2:\n count += ((blockLength(i, inputMode) - 2) / 3) * 10;\n count += 7;\n break;\n }\n break;\n }\n currentMode = inputMode[i];\n }\n }\n\n return count;\n }", "public static StoreDefinition getStoreDef(List<StoreDefinition> list, String name) {\n for(StoreDefinition def: list)\n if(def.getName().equals(name))\n return def;\n return null;\n }", "public void clearHandlers() {\r\n\r\n for (Map<String, CmsAttributeHandler> handlers : m_handlers) {\r\n for (CmsAttributeHandler handler : handlers.values()) {\r\n handler.clearHandlers();\r\n }\r\n handlers.clear();\r\n }\r\n m_handlers.clear();\r\n m_handlers.add(new HashMap<String, CmsAttributeHandler>());\r\n m_handlerById.clear();\r\n }", "public static base_responses add(nitro_service client, inat resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tinat addresources[] = new inat[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new inat();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].publicip = resources[i].publicip;\n\t\t\t\taddresources[i].privateip = resources[i].privateip;\n\t\t\t\taddresources[i].tcpproxy = resources[i].tcpproxy;\n\t\t\t\taddresources[i].ftp = resources[i].ftp;\n\t\t\t\taddresources[i].tftp = resources[i].tftp;\n\t\t\t\taddresources[i].usip = resources[i].usip;\n\t\t\t\taddresources[i].usnip = resources[i].usnip;\n\t\t\t\taddresources[i].proxyip = resources[i].proxyip;\n\t\t\t\taddresources[i].mode = resources[i].mode;\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 static final String[] getRequiredSolrFields() {\n\n if (null == m_requiredSolrFields) {\n List<Locale> locales = OpenCms.getLocaleManager().getAvailableLocales();\n m_requiredSolrFields = new String[14 + (locales.size() * 6)];\n int count = 0;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_PATH;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_TYPE;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_DATE_CREATED;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_DATE_LASTMODIFIED;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_DATE_EXPIRED;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_DATE_RELEASED;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_SIZE;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_STATE;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_USER_CREATED;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_ID;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_USER_LAST_MODIFIED;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_ADDITIONAL_INFO;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_CONTAINER_TYPES;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_RESOURCE_LOCALES;\n for (Locale locale : locales) {\n m_requiredSolrFields[count++] = CmsSearchFieldConfiguration.getLocaleExtendedName(\n CmsSearchField.FIELD_TITLE_UNSTORED,\n locale.toString()) + \"_s\";\n m_requiredSolrFields[count++] = CmsSearchFieldConfiguration.getLocaleExtendedName(\n CmsPropertyDefinition.PROPERTY_TITLE,\n locale.toString()) + CmsSearchField.FIELD_DYNAMIC_PROPERTIES_DIRECT + \"_s\";\n m_requiredSolrFields[count++] = CmsPropertyDefinition.PROPERTY_TITLE\n + CmsSearchField.FIELD_DYNAMIC_PROPERTIES_DIRECT\n + \"_s\";\n m_requiredSolrFields[count++] = CmsSearchFieldConfiguration.getLocaleExtendedName(\n CmsSearchField.FIELD_DESCRIPTION,\n locale.toString()) + \"_s\";\n m_requiredSolrFields[count++] = CmsSearchFieldConfiguration.getLocaleExtendedName(\n CmsPropertyDefinition.PROPERTY_DESCRIPTION,\n locale.toString()) + CmsSearchField.FIELD_DYNAMIC_PROPERTIES + \"_s\";\n m_requiredSolrFields[count++] = CmsPropertyDefinition.PROPERTY_DESCRIPTION\n + CmsSearchField.FIELD_DYNAMIC_PROPERTIES\n + \"_s\";\n }\n }\n return m_requiredSolrFields;\n }", "protected DatabaseConnection getSavedConnection() {\n\t\tNestedConnection nested = specialConnection.get();\n\t\tif (nested == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn nested.connection;\n\t\t}\n\t}", "public final Object copy(final Object toCopy, PersistenceBroker broker)\r\n\t{\r\n\t\treturn clone(toCopy, IdentityMapFactory.getIdentityMap(), new HashMap());\r\n\t}", "public void addExportedPackages(Set<String> packages) {\n\t\tString s = (String) getMainAttributes().get(EXPORT_PACKAGE);\n\t\tWrapper<Boolean> modified = Wrapper.wrap(this.modified);\n\t\tString result = mergeIntoCommaSeparatedList(s, packages, modified, lineDelimiter);\n\t\tthis.modified = modified.get();\n\t\tgetMainAttributes().put(EXPORT_PACKAGE, result);\n\t}", "private boolean isWorkingDay(ProjectCalendar mpxjCalendar, Day day)\n {\n boolean result = false;\n net.sf.mpxj.DayType type = mpxjCalendar.getWorkingDay(day);\n if (type == null)\n {\n type = net.sf.mpxj.DayType.DEFAULT;\n }\n\n switch (type)\n {\n case WORKING:\n {\n result = true;\n break;\n }\n\n case NON_WORKING:\n {\n result = false;\n break;\n }\n\n case DEFAULT:\n {\n if (mpxjCalendar.getParent() == null)\n {\n result = false;\n }\n else\n {\n result = isWorkingDay(mpxjCalendar.getParent(), day);\n }\n break;\n }\n }\n\n return (result);\n }" ]
For a cert we have generated, return the private key. @param cert @return @throws CertificateEncodingException @throws KeyStoreException @throws UnrecoverableKeyException @throws NoSuchAlgorithmException
[ "public synchronized PrivateKey getPrivateKeyForLocalCert(final X509Certificate cert)\n\tthrows CertificateEncodingException, KeyStoreException, UnrecoverableKeyException,\n\tNoSuchAlgorithmException\n\t{\n\t\tString thumbprint = ThumbprintUtil.getThumbprint(cert);\n\n\t\treturn (PrivateKey)_ks.getKey(thumbprint, _keypassword);\n\t}" ]
[ "private Object instanceNotYetLoaded(\n\t\tfinal Tuple resultset,\n\t\tfinal int i,\n\t\tfinal Loadable persister,\n\t\tfinal String rowIdAlias,\n\t\tfinal org.hibernate.engine.spi.EntityKey key,\n\t\tfinal LockMode lockMode,\n\t\tfinal org.hibernate.engine.spi.EntityKey optionalObjectKey,\n\t\tfinal Object optionalObject,\n\t\tfinal List hydratedObjects,\n\t\tfinal SharedSessionContractImplementor session)\n\tthrows HibernateException {\n\t\tfinal String instanceClass = getInstanceClass(\n\t\t\t\tresultset,\n\t\t\t\ti,\n\t\t\t\tpersister,\n\t\t\t\tkey.getIdentifier(),\n\t\t\t\tsession\n\t\t\t);\n\n\t\tfinal Object object;\n\t\tif ( optionalObjectKey != null && key.equals( optionalObjectKey ) ) {\n\t\t\t//its the given optional object\n\t\t\tobject = optionalObject;\n\t\t}\n\t\telse {\n\t\t\t// instantiate a new instance\n\t\t\tobject = session.instantiate( instanceClass, key.getIdentifier() );\n\t\t}\n\n\t\t//need to hydrate it.\n\n\t\t// grab its state from the ResultSet and keep it in the Session\n\t\t// (but don't yet initialize the object itself)\n\t\t// note that we acquire LockMode.READ even if it was not requested\n\t\tLockMode acquiredLockMode = lockMode == LockMode.NONE ? LockMode.READ : lockMode;\n\t\tloadFromResultSet(\n\t\t\t\tresultset,\n\t\t\t\ti,\n\t\t\t\tobject,\n\t\t\t\tinstanceClass,\n\t\t\t\tkey,\n\t\t\t\trowIdAlias,\n\t\t\t\tacquiredLockMode,\n\t\t\t\tpersister,\n\t\t\t\tsession\n\t\t\t);\n\n\t\t//materialize associations (and initialize the object) later\n\t\thydratedObjects.add( object );\n\n\t\treturn object;\n\t}", "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 }", "public static java.util.Date getDateTime(Object value) {\n try {\n return toDateTime(value);\n } catch (ParseException pe) {\n pe.printStackTrace();\n return null;\n }\n }", "public static synchronized void resetAndSetNewConfig(Context ctx, Config config) {\n GLOBAL_CONFIG = config;\n\n if (DISK_CACHE_MANAGER != null) {\n DISK_CACHE_MANAGER.clear();\n DISK_CACHE_MANAGER = null;\n createCache(ctx);\n }\n\n if (EXECUTOR_MANAGER != null) {\n EXECUTOR_MANAGER.shutDown();\n EXECUTOR_MANAGER = null;\n }\n Log.i(TAG, \"New config set\");\n }", "public void actionPerformed(java.awt.event.ActionEvent actionEvent)\r\n {\r\n new Thread()\r\n {\r\n public void run()\r\n {\r\n final java.sql.Connection conn = new JDlgDBConnection(containingFrame, false).showAndReturnConnection();\r\n if (conn != null)\r\n {\r\n javax.swing.SwingUtilities.invokeLater(new Runnable()\r\n {\r\n public void run()\r\n {\r\n JIFrmDatabase frm = new JIFrmDatabase(conn);\r\n containingFrame.getContentPane().add(frm);\r\n frm.setVisible(true);\r\n }\r\n });\r\n }\r\n }\r\n }.start();\r\n }", "private T getWrappedPublisher(Publisher flexiblePublisher, Class<T> type) {\n if (!(flexiblePublisher instanceof FlexiblePublisher)) {\n throw new IllegalArgumentException(String.format(\"Publisher should be of type: '%s'. Found type: '%s'\",\n FlexiblePublisher.class, flexiblePublisher.getClass()));\n }\n\n List<ConditionalPublisher> conditions = ((FlexiblePublisher) flexiblePublisher).getPublishers();\n for (ConditionalPublisher condition : conditions) {\n if (type.isInstance(condition.getPublisher())) {\n return type.cast(condition.getPublisher());\n }\n }\n\n return null;\n }", "private ProjectFile readDatabaseFile(InputStream inputStream) throws MPXJException\n {\n ProjectReader reader = new AstaDatabaseFileReader();\n addListeners(reader);\n return reader.read(inputStream);\n }", "public List<String> getCorporateGroupIds(final String organizationId) {\n final DbOrganization dbOrganization = getOrganization(organizationId);\n return dbOrganization.getCorporateGroupIdPrefixes();\n }", "BsonDocument getNextVersion() {\n if (!this.hasVersion() || this.getVersionDoc() == null) {\n return getFreshVersionDocument();\n }\n final BsonDocument nextVersion = BsonUtils.copyOfDocument(this.getVersionDoc());\n nextVersion.put(\n Fields.VERSION_COUNTER_FIELD,\n new BsonInt64(this.getVersion().getVersionCounter() + 1));\n return nextVersion;\n }" ]
Prepare a parallel HTTP HEAD Task. @param url the UrlPostfix: e.g. in http://localhost:8080/index.html.,the url is "/index.html" @return the parallel task builder
[ "public ParallelTaskBuilder prepareHttpHead(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.getHttpMeta().setHttpMethod(HttpMethod.HEAD);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\n }" ]
[ "public static int compare(double a, double b, double delta) {\n if (equals(a, b, delta)) {\n return 0;\n }\n return Double.compare(a, b);\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}", "public static scpolicy_stats get(nitro_service service, String name) throws Exception{\n\t\tscpolicy_stats obj = new scpolicy_stats();\n\t\tobj.set_name(name);\n\t\tscpolicy_stats response = (scpolicy_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "private Set<String> populateTableNames(String url) throws SQLException\n {\n Set<String> tableNames = new HashSet<String>();\n Connection connection = null;\n ResultSet rs = null;\n\n try\n {\n connection = DriverManager.getConnection(url);\n DatabaseMetaData dmd = connection.getMetaData();\n rs = dmd.getTables(null, null, null, null);\n while (rs.next())\n {\n tableNames.add(rs.getString(\"TABLE_NAME\").toUpperCase());\n }\n }\n\n finally\n {\n if (rs != null)\n {\n rs.close();\n }\n\n if (connection != null)\n {\n connection.close();\n }\n }\n\n return tableNames;\n }", "private int findYOffsetForGroupLabel(JRDesignBand band) {\n\t\tint offset = 0;\n\t\tfor (JRChild jrChild : band.getChildren()) {\n\t\t\tJRDesignElement elem = (JRDesignElement) jrChild;\n\t\t\tif (elem.getKey() != null && elem.getKey().startsWith(\"variable_for_column_\")) {\n\t\t\t\toffset = elem.getY();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn offset;\n\t}", "private double goldenMean(double a, double b) {\r\n if (geometric) {\r\n return a * Math.pow(b / a, GOLDEN_SECTION);\r\n } else {\r\n return a + (b - a) * GOLDEN_SECTION;\r\n }\r\n }", "public Set<URI> collectOutgoingReferences(IResourceDescription description) {\n\t\tURI resourceURI = description.getURI();\n\t\tSet<URI> result = null;\n\t\tfor(IReferenceDescription reference: description.getReferenceDescriptions()) {\n\t\t\tURI targetResource = reference.getTargetEObjectUri().trimFragment();\n\t\t\tif (!resourceURI.equals(targetResource)) {\n\t\t\t\tif (result == null)\n\t\t\t\t\tresult = Sets.newHashSet(targetResource);\n\t\t\t\telse\n\t\t\t\t\tresult.add(targetResource);\n\t\t\t}\n\t\t}\n\t\tif (result != null)\n\t\t\treturn result;\n\t\treturn Collections.emptySet();\n\t}", "public Script updateName(int id, String name) throws Exception {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = SQLService.getInstance().getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_SCRIPT +\n \" SET \" + Constants.SCRIPT_NAME + \" = ? \" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, name);\n statement.setInt(2, id);\n statement.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return this.getScript(id);\n }", "public String validationErrors() {\n\n List<String> errors = new ArrayList<>();\n for (File config : getConfigFiles()) {\n String filename = config.getName();\n try (FileInputStream stream = new FileInputStream(config)) {\n CmsXmlUtils.unmarshalHelper(CmsFileUtil.readFully(stream, false), new CmsXmlEntityResolver(null), true);\n } catch (CmsXmlException e) {\n errors.add(filename + \":\" + e.getCause().getMessage());\n } catch (Exception e) {\n errors.add(filename + \":\" + e.getMessage());\n }\n }\n if (errors.size() == 0) {\n return null;\n }\n String errString = CmsStringUtil.listAsString(errors, \"\\n\");\n JSONObject obj = new JSONObject();\n try {\n obj.put(\"err\", errString);\n } catch (JSONException e) {\n\n }\n return obj.toString();\n }" ]
Exports json encoded content to CrashReport object @param json valid json body. @return new instance of CrashReport
[ "public static CrashReport fromJson(String json) throws IllegalArgumentException {\n try {\n return new CrashReport(json);\n } catch (JSONException je) {\n throw new IllegalArgumentException(je.toString());\n }\n }" ]
[ "public void createEnterpriseCustomFieldMap(Props props, Class<?> c)\n {\n byte[] fieldMapData = null;\n for (Integer key : ENTERPRISE_CUSTOM_KEYS)\n {\n fieldMapData = props.getByteArray(key);\n if (fieldMapData != null)\n {\n break;\n }\n }\n\n if (fieldMapData != null)\n {\n int index = 4;\n while (index < fieldMapData.length)\n {\n //Looks like the custom fields have varying types, it may be that the last byte of the four represents the type?\n //System.out.println(ByteArrayHelper.hexdump(fieldMapData, index, 4, false));\n int typeValue = MPPUtility.getInt(fieldMapData, index);\n FieldType type = getFieldType(typeValue);\n if (type != null && type.getClass() == c && type.toString().startsWith(\"Enterprise Custom Field\"))\n {\n int varDataKey = (typeValue & 0xFFFF);\n FieldItem item = new FieldItem(type, FieldLocation.VAR_DATA, 0, 0, varDataKey, 0, 0);\n m_map.put(type, item);\n //System.out.println(item);\n }\n //System.out.println((type == null ? \"?\" : type.getClass().getSimpleName() + \".\" + type) + \" \" + Integer.toHexString(typeValue));\n\n index += 4;\n }\n }\n }", "public final boolean getBoolean(String name)\n {\n boolean result = false;\n Boolean value = (Boolean) getObject(name);\n if (value != null)\n {\n result = BooleanHelper.getBoolean(value);\n }\n return result;\n }", "@Override\n\tpublic void Invoke(final String method, JSONArray args,\n\t\t\tHubInvokeCallback callback) {\n\n\t\tif (method == null)\n {\n throw new IllegalArgumentException(\"method\");\n }\n\n if (args == null)\n {\n throw new IllegalArgumentException(\"args\");\n }\n\n final String callbackId = mConnection.RegisterCallback(callback);\n\n HubInvocation hubData = new HubInvocation(mHubName, method, args, callbackId);\n\n String value = hubData.Serialize();\n\n mConnection.Send(value, new SendCallback() \n {\n\t\t\t@Override\n\t\t\tpublic void OnSent(CharSequence messageSent) {\n\t\t\t\tLog.v(TAG, \"Invoke of \" + method + \"sent to \" + mHubName);\n\t\t\t\t// callback.OnSent() ??!?!?\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void OnError(Exception ex) {\n\t\t\t\t// TODO Cancel the callback\n\t\t\t\tLog.e(TAG, \"Failed to invoke \" + method + \"on \" + mHubName);\n\t\t\t\tmConnection.RemoveCallback(callbackId);\n\t\t\t\t// callback.OnError() ?!?!?\n\t\t\t}\n });\n }", "@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 }", "void handleFacebookError(HttpStatus statusCode, FacebookError error) {\n\t\tif (error != null && error.getCode() != null) {\n\t\t\tint code = error.getCode();\n\t\t\t\n\t\t\tif (code == UNKNOWN) {\n\t\t\t\tthrow new UncategorizedApiException(FACEBOOK_PROVIDER_ID, error.getMessage(), null);\n\t\t\t} else if (code == SERVICE) {\n\t\t\t\tthrow new ServerException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == TOO_MANY_CALLS || code == USER_TOO_MANY_CALLS || code == EDIT_FEED_TOO_MANY_USER_CALLS || code == EDIT_FEED_TOO_MANY_USER_ACTION_CALLS) {\n\t\t\t\tthrow new RateLimitExceededException(FACEBOOK_PROVIDER_ID);\n\t\t\t} else if (code == PERMISSION_DENIED || isUserPermissionError(code)) {\n\t\t\t\tthrow new InsufficientPermissionException(FACEBOOK_PROVIDER_ID);\n\t\t\t} else if (code == PARAM_SESSION_KEY || code == PARAM_SIGNATURE) {\n\t\t\t\tthrow new InvalidAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == PARAM_ACCESS_TOKEN && error.getSubcode() == null) {\n\t\t\t\tthrow new InvalidAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == PARAM_ACCESS_TOKEN && error.getSubcode() == 463) {\n\t\t\t\tthrow new ExpiredAuthorizationException(FACEBOOK_PROVIDER_ID);\n\t\t\t} else if (code == PARAM_ACCESS_TOKEN) {\n\t\t\t\tthrow new RevokedAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == MESG_DUPLICATE) { \n\t\t\t\tthrow new DuplicateStatusException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == DATA_OBJECT_NOT_FOUND || code == PATH_UNKNOWN) {\n\t\t\t\tthrow new ResourceNotFoundException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else {\n\t\t\t\tthrow new UncategorizedApiException(FACEBOOK_PROVIDER_ID, error.getMessage(), null);\n\t\t\t}\n\t\t}\n\n\t}", "public static void validate(final ArtifactQuery artifactQuery) {\n final Pattern invalidChars = Pattern.compile(\"[^A-Fa-f0-9]\");\n if(artifactQuery.getUser() == null ||\n \t\tartifactQuery.getUser().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [user] missing\")\n .build());\n }\n if( artifactQuery.getStage() != 0 && artifactQuery.getStage() !=1 ){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Invalid [stage] value (supported 0 | 1)\")\n .build());\n }\n if(artifactQuery.getName() == null ||\n \t\tartifactQuery.getName().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [name] missing, it should be the file name\")\n .build());\n }\n if(artifactQuery.getSha256() == null ||\n artifactQuery.getSha256().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [sha256] missing\")\n .build());\n }\n if(artifactQuery.getSha256().length() < 64 || invalidChars.matcher(artifactQuery.getSha256()).find()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Invalid file checksum value\")\n .build());\n }\n if(artifactQuery.getType() == null ||\n \t\tartifactQuery.getType().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [type] missing\")\n .build());\n }\n }", "private void readResource(net.sf.mpxj.planner.schema.Resource plannerResource) throws MPXJException\n {\n Resource mpxjResource = m_projectFile.addResource();\n\n //mpxjResource.setResourceCalendar(m_projectFile.getBaseCalendarByUniqueID(getInteger(plannerResource.getCalendar())));\n mpxjResource.setEmailAddress(plannerResource.getEmail());\n mpxjResource.setUniqueID(getInteger(plannerResource.getId()));\n mpxjResource.setName(plannerResource.getName());\n mpxjResource.setNotes(plannerResource.getNote());\n mpxjResource.setInitials(plannerResource.getShortName());\n mpxjResource.setType(getInt(plannerResource.getType()) == 2 ? ResourceType.MATERIAL : ResourceType.WORK);\n //plannerResource.getStdRate();\n //plannerResource.getOvtRate();\n //plannerResource.getUnits();\n //plannerResource.getProperties();\n\n ProjectCalendar calendar = mpxjResource.addResourceCalendar();\n\n calendar.setWorkingDay(Day.SUNDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.MONDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.TUESDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.WEDNESDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.THURSDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.FRIDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.SATURDAY, DayType.DEFAULT);\n\n ProjectCalendar baseCalendar = m_projectFile.getCalendarByUniqueID(getInteger(plannerResource.getCalendar()));\n if (baseCalendar == null)\n {\n baseCalendar = m_defaultCalendar;\n }\n calendar.setParent(baseCalendar);\n\n m_eventManager.fireResourceReadEvent(mpxjResource);\n }", "public static String constructSerializerInfoXml(StoreDefinition storeDefinition) {\n Element store = new Element(StoreDefinitionsMapper.STORE_ELMT);\n store.addContent(new Element(StoreDefinitionsMapper.STORE_NAME_ELMT).setText(storeDefinition.getName()));\n Element keySerializer = new Element(StoreDefinitionsMapper.STORE_KEY_SERIALIZER_ELMT);\n StoreDefinitionsMapper.addSerializer(keySerializer, storeDefinition.getKeySerializer());\n store.addContent(keySerializer);\n\n Element valueSerializer = new Element(StoreDefinitionsMapper.STORE_VALUE_SERIALIZER_ELMT);\n StoreDefinitionsMapper.addSerializer(valueSerializer, storeDefinition.getValueSerializer());\n store.addContent(valueSerializer);\n\n XMLOutputter serializer = new XMLOutputter(Format.getPrettyFormat());\n return serializer.outputString(store);\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}" ]
Adds a qualifier with the given property and value to the constructed statement. @param propertyIdValue the property of the qualifier @param value the value of the qualifier @return builder object to continue construction
[ "public StatementBuilder withQualifierValue(PropertyIdValue propertyIdValue,\n\t\t\tValue value) {\n\t\twithQualifier(factory.getValueSnak(propertyIdValue, value));\n\t\treturn getThis();\n\t}" ]
[ "private void removeTimedOutLocks(long timeout)\r\n {\r\n int count = 0;\r\n long maxAge = System.currentTimeMillis() - timeout;\r\n boolean breakFromLoop = false;\r\n ObjectLocks temp = null;\r\n \tsynchronized (locktable)\r\n \t{\r\n\t Iterator it = locktable.values().iterator();\r\n\t /**\r\n\t * run this loop while:\r\n\t * - we have more in the iterator\r\n\t * - the breakFromLoop flag hasn't been set\r\n\t * - we haven't removed more than the limit for this cleaning iteration.\r\n\t */\r\n\t while (it.hasNext() && !breakFromLoop && (count <= MAX_LOCKS_TO_CLEAN))\r\n\t {\r\n\t \ttemp = (ObjectLocks) it.next();\r\n\t \tif (temp.getWriter() != null)\r\n\t \t{\r\n\t\t \tif (temp.getWriter().getTimestamp() < maxAge)\r\n\t\t \t{\r\n\t\t \t\t// writer has timed out, set it to null\r\n\t\t \t\ttemp.setWriter(null);\r\n\t\t \t}\r\n\t \t}\r\n\t \tif (temp.getYoungestReader() < maxAge)\r\n\t \t{\r\n\t \t\t// all readers are older than timeout.\r\n\t \t\ttemp.getReaders().clear();\r\n\t \t\tif (temp.getWriter() == null)\r\n\t \t\t{\r\n\t \t\t\t// all readers and writer are older than timeout,\r\n\t \t\t\t// remove the objectLock from the iterator (which\r\n\t \t\t\t// is backed by the map, so it will be removed.\r\n\t \t\t\tit.remove();\r\n\t \t\t}\r\n\t \t}\r\n\t \telse\r\n\t \t{\r\n\t \t\t// we need to walk each reader.\r\n\t \t\tIterator readerIt = temp.getReaders().values().iterator();\r\n\t \t\tLockEntry readerLock = null;\r\n\t \t\twhile (readerIt.hasNext())\r\n\t \t\t{\r\n\t \t\t\treaderLock = (LockEntry) readerIt.next();\r\n\t \t\t\tif (readerLock.getTimestamp() < maxAge)\r\n\t \t\t\t{\r\n\t \t\t\t\t// this read lock is old, remove it.\r\n\t \t\t\t\treaderIt.remove();\r\n\t \t\t\t}\r\n\t \t\t}\r\n\t \t}\r\n\t \tcount++;\r\n\t }\r\n \t}\r\n }", "Map<UUID, UUID> getActivityCodes(Activity activity)\n {\n Map<UUID, UUID> map = m_activityCodeCache.get(activity);\n if (map == null)\n {\n map = new HashMap<UUID, UUID>();\n m_activityCodeCache.put(activity, map);\n for (CodeAssignment ca : activity.getCodeAssignment())\n {\n UUID code = getUUID(ca.getCodeUuid(), ca.getCode());\n UUID value = getUUID(ca.getValueUuid(), ca.getValue());\n map.put(code, value);\n }\n }\n return map;\n }", "public Map<String, Object> getArtifactFieldsFilters() {\n\t\tfinal Map<String, Object> params = new HashMap<String, Object>();\n\n for(final Filter filter: filters){\n params.putAll(filter.artifactFilterFields());\n }\n\n\t\treturn params;\n\t}", "public void setCycleInterval(float newCycleInterval) {\n if ( (this.cycleInterval != newCycleInterval) && (newCycleInterval > 0) ) {\n for (GVRNodeAnimation gvrKeyFrameAnimation : gvrKeyFrameAnimations) {\n //TODO Cannot easily change the GVRAnimation's GVRChannel once set.\n }\n this.cycleInterval = newCycleInterval;\n }\n }", "@SuppressWarnings({\"unchecked\", \"unused\"})\n public static <T> T[] object2Array(final Class<T> clazz, final Object obj) {\n return (T[]) obj;\n }", "public String getMethodSignature() {\n if (method != null) {\n String methodSignature = method.toString();\n return methodSignature.replaceFirst(\"public void \", \"\");\n }\n return null;\n }", "public void addDateTimeHelper(int ds, Date date) throws SerializationException, InvalidDataSetException {\r\n\t\tif (date == null) {\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tDataSetInfo dsi = dsiFactory.create(ds);\r\n\r\n\t\tSimpleDateFormat df = new SimpleDateFormat(dsi.getSerializer().toString());\r\n\t\tString value = df.format(date);\r\n\t\tbyte[] data = dsi.getSerializer().serialize(value, activeSerializationContext);\r\n\t\tDataSet dataSet = new DefaultDataSet(dsi, data);\r\n\t\tadd(dataSet);\r\n\t}", "public IExternalAccess getAgentsExternalAccess(String agent_name) {\n\n return cmsService.getExternalAccess(getAgentID(agent_name)).get(\n new ThreadSuspendable());\n }", "public static DiscountCurveInterface createDiscountCurveFromMonteCarloLiborModel(String forwardCurveName, LIBORModelMonteCarloSimulationModel model, double startTime) throws CalculationException{\n\t\t// Check if the LMM uses a discount curve which is created from a forward curve\n\t\tif(model.getModel().getDiscountCurve()==null || model.getModel().getDiscountCurve().getName().toLowerCase().contains(\"DiscountCurveFromForwardCurve\".toLowerCase())){\n\t\t\treturn new DiscountCurveFromForwardCurve(ForwardCurveInterpolation.createForwardCurveFromMonteCarloLiborModel(forwardCurveName, model, startTime));\n\t\t}\n\t\telse {\n\t\t\t// i.e. forward curve of Libor Model not OIS. In this case return the OIS curve.\n\t\t\t// Only at startTime 0!\n\t\t\treturn (DiscountCurveInterface) model.getModel().getDiscountCurve();\n\t\t}\n\n\t}" ]
Get the current stack trace element, skipping anything from known logging classes. @return The current stack trace for this thread
[ "private static StackTraceElement getStackTrace() {\r\n StackTraceElement[] stack = Thread.currentThread().getStackTrace();\r\n\r\n int i = 2; // we can skip the first two (first is getStackTrace(), second is this method)\r\n while (i < stack.length) {\r\n boolean isLoggingClass = false;\r\n for (String loggingClass : loggingClasses) {\r\n String className = stack[i].getClassName();\r\n if (className.startsWith(loggingClass)) {\r\n isLoggingClass = true;\r\n break;\r\n }\r\n }\r\n if (!isLoggingClass) {\r\n break;\r\n }\r\n\r\n i += 1;\r\n }\r\n\r\n // if we didn't find anything, keep last element (probably shouldn't happen, but could if people add too many logging classes)\r\n if (i >= stack.length) {\r\n i = stack.length - 1;\r\n }\r\n return stack[i];\r\n }" ]
[ "public static vpnvserver_vpnsessionpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_vpnsessionpolicy_binding obj = new vpnvserver_vpnsessionpolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_vpnsessionpolicy_binding response[] = (vpnvserver_vpnsessionpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "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 int getChunkId(String fileName) {\n Pattern pattern = Pattern.compile(\"_[\\\\d]+\\\\.\");\n Matcher matcher = pattern.matcher(fileName);\n\n if(matcher.find()) {\n return new Integer(fileName.substring(matcher.start() + 1, matcher.end() - 1));\n } else {\n throw new VoldemortException(\"Could not extract out chunk id from \" + fileName);\n }\n }", "public static int cudnnCreatePersistentRNNPlan(\n cudnnRNNDescriptor rnnDesc, \n int minibatch, \n int dataType, \n cudnnPersistentRNNPlan plan)\n {\n return checkResult(cudnnCreatePersistentRNNPlanNative(rnnDesc, minibatch, dataType, plan));\n }", "private void populateMap(byte[] data, Integer previousItemOffset, Integer previousItemKey, Integer itemOffset)\n {\n if (previousItemOffset != null)\n {\n int itemSize = itemOffset.intValue() - previousItemOffset.intValue();\n byte[] itemData = new byte[itemSize];\n System.arraycopy(data, previousItemOffset.intValue(), itemData, 0, itemSize);\n m_map.put(previousItemKey, itemData);\n }\n }", "static void writePatch(final Patch rollbackPatch, final File file) throws IOException {\n final File parent = file.getParentFile();\n if (!parent.isDirectory()) {\n if (!parent.mkdirs() && !parent.exists()) {\n throw PatchLogger.ROOT_LOGGER.cannotCreateDirectory(file.getAbsolutePath());\n }\n }\n try {\n try (final OutputStream os = new FileOutputStream(file)){\n PatchXml.marshal(os, rollbackPatch);\n }\n } catch (XMLStreamException e) {\n throw new IOException(e);\n }\n }", "private static void writeNumber(Class<?> numberClass, Number value, CharBuf buffer) {\n if (numberClass == Integer.class) {\n buffer.addInt((Integer) value);\n } else if (numberClass == Long.class) {\n buffer.addLong((Long) value);\n } else if (numberClass == BigInteger.class) {\n buffer.addBigInteger((BigInteger) value);\n } else if (numberClass == BigDecimal.class) {\n buffer.addBigDecimal((BigDecimal) value);\n } else if (numberClass == Double.class) {\n Double doubleValue = (Double) value;\n if (doubleValue.isInfinite()) {\n throw new JsonException(\"Number \" + value + \" can't be serialized as JSON: infinite are not allowed in JSON.\");\n }\n if (doubleValue.isNaN()) {\n throw new JsonException(\"Number \" + value + \" can't be serialized as JSON: NaN are not allowed in JSON.\");\n }\n\n buffer.addDouble(doubleValue);\n } else if (numberClass == Float.class) {\n Float floatValue = (Float) value;\n if (floatValue.isInfinite()) {\n throw new JsonException(\"Number \" + value + \" can't be serialized as JSON: infinite are not allowed in JSON.\");\n }\n if (floatValue.isNaN()) {\n throw new JsonException(\"Number \" + value + \" can't be serialized as JSON: NaN are not allowed in JSON.\");\n }\n\n buffer.addFloat(floatValue);\n } else if (numberClass == Byte.class) {\n buffer.addByte((Byte) value);\n } else if (numberClass == Short.class) {\n buffer.addShort((Short) value);\n } else { // Handle other Number implementations\n buffer.addString(value.toString());\n }\n }", "public ProteusApplication addDefaultRoutes(RoutingHandler router)\n {\n\n if (config.hasPath(\"health.statusPath\")) {\n try {\n final String statusPath = config.getString(\"health.statusPath\");\n\n router.add(Methods.GET, statusPath, (final HttpServerExchange exchange) ->\n {\n exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, MediaType.TEXT_PLAIN);\n exchange.getResponseSender().send(\"OK\");\n });\n\n this.registeredEndpoints.add(EndpointInfo.builder().withConsumes(\"*/*\").withProduces(\"text/plain\").withPathTemplate(statusPath).withControllerName(\"Internal\").withMethod(Methods.GET).build());\n\n } catch (Exception e) {\n log.error(\"Error adding health status route.\", e.getMessage());\n }\n }\n\n if (config.hasPath(\"application.favicon\")) {\n try {\n\n final ByteBuffer faviconImageBuffer;\n\n final File faviconFile = new File(config.getString(\"application.favicon\"));\n\n if (!faviconFile.exists()) {\n try (final InputStream stream = this.getClass().getResourceAsStream(config.getString(\"application.favicon\"))) {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n\n byte[] buffer = new byte[4096];\n int read = 0;\n while (read != -1) {\n read = stream.read(buffer);\n if (read > 0) {\n baos.write(buffer, 0, read);\n }\n }\n\n faviconImageBuffer = ByteBuffer.wrap(baos.toByteArray());\n }\n\n } else {\n try (final InputStream stream = Files.newInputStream(Paths.get(config.getString(\"application.favicon\")))) {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n\n byte[] buffer = new byte[4096];\n int read = 0;\n while (read != -1) {\n read = stream.read(buffer);\n if (read > 0) {\n baos.write(buffer, 0, read);\n }\n }\n\n faviconImageBuffer = ByteBuffer.wrap(baos.toByteArray());\n }\n }\n\n router.add(Methods.GET, \"favicon.ico\", (final HttpServerExchange exchange) ->\n {\n exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, io.sinistral.proteus.server.MediaType.IMAGE_X_ICON.toString());\n exchange.getResponseSender().send(faviconImageBuffer);\n });\n\n } catch (Exception e) {\n log.error(\"Error adding favicon route.\", e.getMessage());\n }\n }\n\n return this;\n }", "protected Map<String, AbstractServer> createServices(ServerSetup[] config, Managers mgr) {\r\n Map<String, AbstractServer> srvc = new HashMap<>();\r\n for (ServerSetup setup : config) {\r\n if (srvc.containsKey(setup.getProtocol())) {\r\n throw new IllegalArgumentException(\"Server '\" + setup.getProtocol() + \"' was found at least twice in the array\");\r\n }\r\n final String protocol = setup.getProtocol();\r\n if (protocol.startsWith(ServerSetup.PROTOCOL_SMTP)) {\r\n srvc.put(protocol, new SmtpServer(setup, mgr));\r\n } else if (protocol.startsWith(ServerSetup.PROTOCOL_POP3)) {\r\n srvc.put(protocol, new Pop3Server(setup, mgr));\r\n } else if (protocol.startsWith(ServerSetup.PROTOCOL_IMAP)) {\r\n srvc.put(protocol, new ImapServer(setup, mgr));\r\n }\r\n }\r\n return srvc;\r\n }" ]
Loads the schemas associated to this catalog.
[ "protected boolean _load ()\r\n {\r\n java.sql.ResultSet rs = null;\r\n try\r\n {\r\n \r\n // This synchronization is necessary for Oracle JDBC drivers 8.1.7, 9.0.1, 9.2.0.1\r\n // The documentation says synchronization is done within the driver, but they\r\n // must have overlooked something. Without the lock we'd get mysterious error\r\n // messages. \r\n synchronized(getDbMeta())\r\n {\r\n \r\n getDbMetaTreeModel().setStatusBarMessage(\"Reading schemas for catalog \" \r\n + this.getAttribute(ATT_CATALOG_NAME));\r\n rs = getDbMeta().getSchemas();\r\n final java.util.ArrayList alNew = new java.util.ArrayList();\r\n int count = 0;\r\n while (rs.next())\r\n {\r\n getDbMetaTreeModel().setStatusBarMessage(\"Creating schema \" + getCatalogName() + \".\" + rs.getString(\"TABLE_SCHEM\"));\r\n alNew.add(new DBMetaSchemaNode(getDbMeta(),\r\n getDbMetaTreeModel(),\r\n DBMetaCatalogNode.this, \r\n rs.getString(\"TABLE_SCHEM\")));\r\n count++;\r\n }\r\n if (count == 0) \r\n alNew.add(new DBMetaSchemaNode(getDbMeta(), \r\n getDbMetaTreeModel(),\r\n DBMetaCatalogNode.this, null));\r\n alChildren = alNew; \r\n javax.swing.SwingUtilities.invokeLater(new Runnable()\r\n {\r\n public void run()\r\n {\r\n getDbMetaTreeModel().nodeStructureChanged(DBMetaCatalogNode.this);\r\n }\r\n });\r\n rs.close();\r\n }\r\n }\r\n catch (java.sql.SQLException sqlEx)\r\n {\r\n getDbMetaTreeModel().reportSqlError(\"Error retrieving schemas\", sqlEx);\r\n try\r\n {\r\n if (rs != null) rs.close ();\r\n }\r\n catch (java.sql.SQLException sqlEx2)\r\n {\r\n this.getDbMetaTreeModel().reportSqlError(\"Error retrieving schemas\", sqlEx2);\r\n } \r\n return false;\r\n }\r\n return true;\r\n }" ]
[ "public String computeTrackSignature(final String title, final SearchableItem artist, final int duration,\n final WaveformDetail waveformDetail, final BeatGrid beatGrid) {\n final String safeTitle = (title == null)? \"\" : title;\n final String artistName = (artist == null)? \"[no artist]\" : artist.label;\n try {\n // Compute the SHA-1 hash of our fields\n MessageDigest digest = MessageDigest.getInstance(\"SHA1\");\n digest.update(safeTitle.getBytes(\"UTF-8\"));\n digest.update((byte) 0);\n digest.update(artistName.getBytes(\"UTF-8\"));\n digest.update((byte) 0);\n digestInteger(digest, duration);\n digest.update(waveformDetail.getData());\n for (int i = 1; i <= beatGrid.beatCount; i++) {\n digestInteger(digest, beatGrid.getBeatWithinBar(i));\n digestInteger(digest, (int)beatGrid.getTimeWithinTrack(i));\n }\n byte[] result = digest.digest();\n\n // Create a hex string representation of the hash\n StringBuilder hex = new StringBuilder(result.length * 2);\n for (byte aResult : result) {\n hex.append(Integer.toString((aResult & 0xff) + 0x100, 16).substring(1));\n }\n\n return hex.toString();\n\n } catch (NullPointerException e) {\n logger.info(\"Returning null track signature because an input element was null.\", e);\n } catch (NoSuchAlgorithmException e) {\n logger.error(\"Unable to obtain SHA-1 MessageDigest instance for computing track signatures.\", e);\n } catch (UnsupportedEncodingException e) {\n logger.error(\"Unable to work with UTF-8 string encoding for computing track signatures.\", e);\n }\n return null; // We were unable to compute a signature\n }", "public String calculateLabelUnit(final CoordinateReferenceSystem mapCrs) {\n String unit;\n if (this.labelProjection != null) {\n unit = this.labelCRS.getCoordinateSystem().getAxis(0).getUnit().toString();\n } else {\n unit = mapCrs.getCoordinateSystem().getAxis(0).getUnit().toString();\n }\n\n return unit;\n }", "public Duration getDuration(int field) throws MPXJException\n {\n Duration result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n result = DurationUtility.getInstance(m_fields[field], m_formats.getDurationDecimalFormat(), m_locale);\n }\n else\n {\n result = null;\n }\n\n return (result);\n }", "private void populateMap(byte[] data, Integer previousItemOffset, Integer previousItemKey, Integer itemOffset)\n {\n if (previousItemOffset != null)\n {\n int itemSize = itemOffset.intValue() - previousItemOffset.intValue();\n byte[] itemData = new byte[itemSize];\n System.arraycopy(data, previousItemOffset.intValue(), itemData, 0, itemSize);\n m_map.put(previousItemKey, itemData);\n }\n }", "public void setKnots(int[] x, int[] y, byte[] types, int offset, int count) {\n\t\tnumKnots = count;\n\t\txKnots = new int[numKnots];\n\t\tyKnots = new int[numKnots];\n\t\tknotTypes = new byte[numKnots];\n\t\tSystem.arraycopy(x, offset, xKnots, 0, numKnots);\n\t\tSystem.arraycopy(y, offset, yKnots, 0, numKnots);\n\t\tSystem.arraycopy(types, offset, knotTypes, 0, numKnots);\n\t\tsortKnots();\n\t\trebuildGradient();\n\t}", "@Override\n public ArtifactoryResponse restCall(ArtifactoryRequest artifactoryRequest) throws IOException {\n HttpRequestBase httpRequest;\n\n String requestPath = \"/\" + artifactoryRequest.getApiUrl();\n ContentType contentType = Util.getContentType(artifactoryRequest.getRequestType());\n\n String queryPath = \"\";\n if (!artifactoryRequest.getQueryParams().isEmpty()) {\n queryPath = Util.getQueryPath(\"?\", artifactoryRequest.getQueryParams());\n }\n\n switch (artifactoryRequest.getMethod()) {\n case GET:\n httpRequest = new HttpGet();\n\n break;\n\n case POST:\n httpRequest = new HttpPost();\n setEntity((HttpPost)httpRequest, artifactoryRequest.getBody(), contentType);\n\n break;\n\n case PUT:\n httpRequest = new HttpPut();\n setEntity((HttpPut)httpRequest, artifactoryRequest.getBody(), contentType);\n\n break;\n\n case DELETE:\n httpRequest = new HttpDelete();\n\n break;\n\n case PATCH:\n httpRequest = new HttpPatch();\n setEntity((HttpPatch)httpRequest, artifactoryRequest.getBody(), contentType);\n break;\n\n case OPTIONS:\n httpRequest = new HttpOptions();\n break;\n\n default:\n throw new IllegalArgumentException(\"Unsupported request method.\");\n }\n\n httpRequest.setURI(URI.create(url + requestPath + queryPath));\n addAccessTokenHeaderIfNeeded(httpRequest);\n\n if (contentType != null) {\n httpRequest.setHeader(\"Content-type\", contentType.getMimeType());\n }\n\n Map<String, String> headers = artifactoryRequest.getHeaders();\n for (String key : headers.keySet()) {\n httpRequest.setHeader(key, headers.get(key));\n }\n\n HttpResponse httpResponse = httpClient.execute(httpRequest);\n return new ArtifactoryResponseImpl(httpResponse);\n }", "public Task<Void> registerWithEmail(@NonNull final String email, @NonNull final String password) {\n return dispatcher.dispatchTask(\n new Callable<Void>() {\n @Override\n public Void call() {\n registerWithEmailInternal(email, password);\n return null;\n }\n });\n }", "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 }", "Map<String, String> packageNameMap() {\n if (packageNames == null) {\n return emptyMap();\n }\n\n Map<String, String> names = new LinkedHashMap<String, String>();\n for (PackageName name : packageNames) {\n names.put(name.getUri(), name.getPackage());\n }\n return names;\n }" ]
Get the short exception message using the requested locale. This does not include the cause exception message. @param locale locale for message @return (short) exception message
[ "public String getShortMessage(Locale locale) {\n\t\tString message;\n\t\tmessage = translate(Integer.toString(exceptionCode), locale);\n\t\tif (message != null && msgParameters != null && msgParameters.length > 0) {\n\t\t\tfor (int i = 0; i < msgParameters.length; i++) {\n\t\t\t\tboolean isIncluded = false;\n\t\t\t\tString needTranslationParam = \"$${\" + i + \"}\";\n\t\t\t\tif (message.contains(needTranslationParam)) {\n\t\t\t\t\tString translation = translate(msgParameters[i], locale);\n\t\t\t\t\tif (null == translation && null != msgParameters[i]) {\n\t\t\t\t\t\ttranslation = msgParameters[i].toString();\n\t\t\t\t\t}\n\t\t\t\t\tif (null == translation) {\n\t\t\t\t\t\ttranslation = \"[null]\";\n\t\t\t\t\t}\n\t\t\t\t\tmessage = message.replace(needTranslationParam, translation);\n\t\t\t\t\tisIncluded = true;\n\t\t\t\t}\n\t\t\t\tString verbatimParam = \"${\" + i + \"}\";\n\t\t\t\tString rs = null == msgParameters[i] ? \"[null]\" : msgParameters[i].toString();\n\t\t\t\tif (message.contains(verbatimParam)) {\n\t\t\t\t\tmessage = message.replace(verbatimParam, rs);\n\t\t\t\t\tisIncluded = true;\n\t\t\t\t}\n\t\t\t\tif (!isIncluded) {\n\t\t\t\t\tmessage = message + \" (\" + rs + \")\"; // NOSONAR replace/contains makes StringBuilder use difficult\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn message;\n\t}" ]
[ "public void setResourceCalendar(ProjectCalendar calendar)\n {\n set(ResourceField.CALENDAR, calendar);\n if (calendar == null)\n {\n setResourceCalendarUniqueID(null);\n }\n else\n {\n calendar.setResource(this);\n setResourceCalendarUniqueID(calendar.getUniqueID());\n }\n }", "public void setModelByInputFileStream(InputStream inputFileStream) {\r\n try {\r\n this.model = SCXMLParser.parse(new InputSource(inputFileStream), null, customActionsFromTagExtensions());\r\n this.setStateMachine(this.model);\r\n } catch (IOException | SAXException | ModelException e) {\r\n e.printStackTrace();\r\n }\r\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 }", "public boolean isEmpty() {\n\t\tint snapshotSize = cleared ? 0 : snapshot.size();\n\t\t//nothing in both\n\t\tif ( snapshotSize == 0 && currentState.isEmpty() ) {\n\t\t\treturn true;\n\t\t}\n\t\t//snapshot bigger than changeset\n\t\tif ( snapshotSize > currentState.size() ) {\n\t\t\treturn false;\n\t\t}\n\t\treturn size() == 0;\n\t}", "public void writeFinalResults() {\n\t\tprintStatus();\n\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers\n\t\t\t\t\t\t.openExampleFileOuputStream(\"life-expectancies.csv\"))) {\n\n\t\t\tfor (int i = 0; i < lifeSpans.length; i++) {\n\t\t\t\tif (peopleCount[i] != 0) {\n\t\t\t\t\tout.println(i + \",\" + (double) lifeSpans[i]\n\t\t\t\t\t\t\t/ peopleCount[i] + \",\" + peopleCount[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}", "public void check(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n ensureNoTableInfoIfNoRepositoryInfo(classDef, checkLevel);\r\n checkModifications(classDef, checkLevel);\r\n checkExtents(classDef, checkLevel);\r\n ensureTableIfNecessary(classDef, checkLevel);\r\n checkFactoryClassAndMethod(classDef, checkLevel);\r\n checkInitializationMethod(classDef, checkLevel);\r\n checkPrimaryKey(classDef, checkLevel);\r\n checkProxyPrefetchingLimit(classDef, checkLevel);\r\n checkRowReader(classDef, checkLevel);\r\n checkObjectCache(classDef, checkLevel);\r\n checkProcedures(classDef, checkLevel);\r\n }", "private ChildTaskContainer getParentTask(String wbs)\n {\n ChildTaskContainer result;\n String parentWbs = getParentWBS(wbs);\n if (parentWbs == null)\n {\n result = m_projectFile;\n }\n else\n {\n result = m_taskMap.get(parentWbs);\n }\n return result;\n }", "public static int getLineNumber(Member member) {\n\n if (!(member instanceof Method || member instanceof Constructor)) {\n // We are not able to get this info for fields\n return 0;\n }\n\n // BCEL is an optional dependency, if we cannot load it, simply return 0\n if (!Reflections.isClassLoadable(BCEL_CLASS, WeldClassLoaderResourceLoader.INSTANCE)) {\n return 0;\n }\n\n String classFile = member.getDeclaringClass().getName().replace('.', '/');\n ClassLoaderResourceLoader classFileResourceLoader = new ClassLoaderResourceLoader(member.getDeclaringClass().getClassLoader());\n InputStream in = null;\n\n try {\n URL classFileUrl = classFileResourceLoader.getResource(classFile + \".class\");\n\n if (classFileUrl == null) {\n // The class file is not available\n return 0;\n }\n in = classFileUrl.openStream();\n\n ClassParser cp = new ClassParser(in, classFile);\n JavaClass javaClass = cp.parse();\n\n // First get all declared methods and constructors\n // Note that in bytecode constructor is translated into a method\n org.apache.bcel.classfile.Method[] methods = javaClass.getMethods();\n org.apache.bcel.classfile.Method match = null;\n\n String signature;\n String name;\n if (member instanceof Method) {\n signature = DescriptorUtils.methodDescriptor((Method) member);\n name = member.getName();\n } else if (member instanceof Constructor) {\n signature = DescriptorUtils.makeDescriptor((Constructor<?>) member);\n name = INIT_METHOD_NAME;\n } else {\n return 0;\n }\n\n for (org.apache.bcel.classfile.Method method : methods) {\n // Matching method must have the same name, modifiers and signature\n if (method.getName().equals(name)\n && member.getModifiers() == method.getModifiers()\n && method.getSignature().equals(signature)) {\n match = method;\n }\n }\n if (match != null) {\n // If a method is found, try to obtain the optional LineNumberTable attribute\n LineNumberTable lineNumberTable = match.getLineNumberTable();\n if (lineNumberTable != null) {\n int line = lineNumberTable.getSourceLine(0);\n return line == -1 ? 0 : line;\n }\n }\n // No suitable method found\n return 0;\n\n } catch (Throwable t) {\n return 0;\n } finally {\n if (in != null) {\n try {\n in.close();\n } catch (Exception e) {\n return 0;\n }\n }\n }\n }", "public Optional<Project> findProject(String name) throws IllegalArgumentException {\n if (name == null || name.isEmpty()) {\n throw new IllegalArgumentException(\"Project name cannot be empty\");\n }\n return getProject(name);\n }" ]
Read the file header data. @param is input stream
[ "private void readHeader(InputStream is) throws IOException\n {\n byte[] header = new byte[20];\n is.read(header);\n m_offset += 20;\n SynchroLogger.log(\"HEADER\", header); \n }" ]
[ "public static double KumarJohnsonDivergence(double[] p, double[] q) {\n double r = 0;\n for (int i = 0; i < p.length; i++) {\n if (p[i] != 0 && q[i] != 0) {\n r += Math.pow(p[i] * p[i] - q[i] * q[i], 2) / 2 * Math.pow(p[i] * q[i], 1.5);\n }\n }\n return r;\n }", "private String getTaskField(int key)\n {\n String result = null;\n\n if ((key > 0) && (key < m_taskNames.length))\n {\n result = m_taskNames[key];\n }\n\n return (result);\n }", "public static AppDescriptor of(String appName, String packageName) {\n String[] packages = packageName.split(S.COMMON_SEP);\n return of(appName, packageName, Version.ofPackage(packages[0]));\n }", "@Override\n protected Deque<Step> childValue(Deque<Step> parentValue) {\n Deque<Step> queue = new LinkedList<>();\n queue.add(parentValue.getFirst());\n return queue;\n }", "public boolean canLockBecauseOfInactivity(CmsObject cms, CmsUser user) {\n\n return !user.isManaged()\n && !user.isWebuser()\n && !OpenCms.getDefaultUsers().isDefaultUser(user.getName())\n && !OpenCms.getRoleManager().hasRole(cms, user.getName(), CmsRole.ROOT_ADMIN);\n }", "public static void copyThenClose(InputStream input, OutputStream output)\r\n throws IOException {\r\n copy(input, output);\r\n input.close();\r\n output.close();\r\n }", "public Collection<BoxFileVersion> getVersions() {\n URL url = VERSIONS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n JsonArray entries = jsonObject.get(\"entries\").asArray();\n Collection<BoxFileVersion> versions = new ArrayList<BoxFileVersion>();\n for (JsonValue entry : entries) {\n versions.add(new BoxFileVersion(this.getAPI(), entry.asObject(), this.getID()));\n }\n\n return versions;\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 DataSetInfo create(int dataSet) throws InvalidDataSetException {\r\n\t\tDataSetInfo info = dataSets.get(createKey(dataSet));\r\n\t\tif (info == null) {\r\n\t\t\tint recordNumber = (dataSet >> 8) & 0xFF;\r\n\t\t\tint dataSetNumber = dataSet & 0xFF;\r\n\t\t\tthrow new UnsupportedDataSetException(recordNumber + \":\" + dataSetNumber);\r\n\t\t\t// info = super.create(dataSet);\r\n\t\t}\r\n\t\treturn info;\r\n\t}" ]
Remove all scene objects.
[ "public synchronized void removeAllSceneObjects() {\n final GVRCameraRig rig = getMainCameraRig();\n final GVRSceneObject head = rig.getOwnerObject();\n rig.removeAllChildren();\n\n NativeScene.removeAllSceneObjects(getNative());\n for (final GVRSceneObject child : mSceneRoot.getChildren()) {\n child.getParent().removeChildObject(child);\n }\n\n if (null != head) {\n mSceneRoot.addChildObject(head);\n }\n\n final int numControllers = getGVRContext().getInputManager().clear();\n if (numControllers > 0)\n {\n getGVRContext().getInputManager().selectController();\n }\n\n getGVRContext().runOnGlThread(new Runnable() {\n @Override\n public void run() {\n NativeScene.deleteLightsAndDepthTextureOnRenderThread(getNative());\n }\n });\n }" ]
[ "public DbInfo info() {\n return client.couchDbClient.get(new DatabaseURIHelper(db.getDBUri()).getDatabaseUri(),\n DbInfo.class);\n }", "public void terminateAllConnections(){\r\n\t\tthis.terminationLock.lock();\r\n\t\ttry{\r\n\t\t\t// close off all connections.\r\n\t\t\tfor (int i=0; i < this.pool.partitionCount; i++) {\r\n\t\t\t\tthis.pool.partitions[i].setUnableToCreateMoreTransactions(false); // we can create new ones now, this is an optimization\r\n\t\t\t\tList<ConnectionHandle> clist = new LinkedList<ConnectionHandle>(); \r\n\t\t\t\tthis.pool.partitions[i].getFreeConnections().drainTo(clist);\r\n\t\t\t\tfor (ConnectionHandle c: clist){\r\n\t\t\t\t\tthis.pool.destroyConnection(c);\r\n\t\t\t\t}\r\n\r\n\t\t\t}\r\n\t\t} finally {\r\n\t\t\tthis.terminationLock.unlock();\r\n\t\t}\r\n\t}", "private void appendClazzColumnForSelect(StringBuffer buf)\r\n {\r\n ClassDescriptor cld = getSearchClassDescriptor();\r\n ClassDescriptor[] clds = getMultiJoinedClassDescriptors(cld);\r\n\r\n if (clds.length == 0)\r\n {\r\n return;\r\n }\r\n \r\n buf.append(\",CASE\");\r\n\r\n for (int i = clds.length; i > 0; i--)\r\n {\r\n buf.append(\" WHEN \");\r\n\r\n ClassDescriptor subCld = clds[i - 1];\r\n FieldDescriptor[] fieldDescriptors = subCld.getPkFields();\r\n\r\n TableAlias alias = getTableAliasForClassDescriptor(subCld);\r\n for (int j = 0; j < fieldDescriptors.length; j++)\r\n {\r\n FieldDescriptor field = fieldDescriptors[j];\r\n if (j > 0)\r\n {\r\n buf.append(\" AND \");\r\n }\r\n appendColumn(alias, field, buf);\r\n buf.append(\" IS NOT NULL\");\r\n }\r\n buf.append(\" THEN '\").append(subCld.getClassNameOfObject()).append(\"'\");\r\n }\r\n buf.append(\" ELSE '\").append(cld.getClassNameOfObject()).append(\"'\");\r\n buf.append(\" END AS \" + SqlHelper.OJB_CLASS_COLUMN);\r\n }", "public static appfwsignatures get(nitro_service service) throws Exception{\n\t\tappfwsignatures obj = new appfwsignatures();\n\t\tappfwsignatures[] response = (appfwsignatures[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public static <T extends JsonRtn> T parseJsonRtn(String jsonRtn, Class<T> jsonRtnClazz) {\n T rtn = JSONObject.parseObject(jsonRtn, jsonRtnClazz);\n appendErrorHumanMsg(rtn);\n return rtn;\n }", "public String toDecodedString(final java.net.URI uri) {\n final String scheme = uri.getScheme();\n final String part = uri.getSchemeSpecificPart();\n if ((scheme == null)) {\n return part;\n }\n return ((scheme + \":\") + part);\n }", "public ItemRequest<Workspace> findById(String workspace) {\n \n String path = String.format(\"/workspaces/%s\", workspace);\n return new ItemRequest<Workspace>(this, Workspace.class, path, \"GET\");\n }", "public static ipset get(nitro_service service, String name) throws Exception{\n\t\tipset obj = new ipset();\n\t\tobj.set_name(name);\n\t\tipset response = (ipset) obj.get_resource(service);\n\t\treturn response;\n\t}", "public void setTextureBufferSize(final int size) {\n mRootViewGroup.post(new Runnable() {\n @Override\n public void run() {\n mRootViewGroup.setTextureBufferSize(size);\n }\n });\n }" ]
Update a note. @param note The Note to update @throws FlickrException
[ "public void edit(Note note) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT);\r\n\r\n parameters.put(\"note_id\", note.getId());\r\n Rectangle bounds = note.getBounds();\r\n if (bounds != null) {\r\n parameters.put(\"note_x\", String.valueOf(bounds.x));\r\n parameters.put(\"note_y\", String.valueOf(bounds.y));\r\n parameters.put(\"note_w\", String.valueOf(bounds.width));\r\n parameters.put(\"note_h\", String.valueOf(bounds.height));\r\n }\r\n String text = note.getText();\r\n if (text != null) {\r\n parameters.put(\"note_text\", text);\r\n }\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }" ]
[ "public static Integer getDays(String days)\n {\n Integer result = null;\n if (days != null)\n {\n result = Integer.valueOf(Integer.parseInt(days, 2));\n }\n return (result);\n }", "protected <T> Request doInvoke(ResponseReader responseReader,\n String methodName, RpcStatsContext statsContext, String requestData,\n AsyncCallback<T> callback) {\n\n RequestBuilder rb = doPrepareRequestBuilderImpl(responseReader, methodName,\n statsContext, requestData, callback);\n\n try {\n return rb.send();\n } catch (RequestException ex) {\n InvocationException iex = new InvocationException(\n \"Unable to initiate the asynchronous service invocation (\" +\n methodName + \") -- check the network connection\",\n ex);\n callback.onFailure(iex);\n } finally {\n if (statsContext.isStatsAvailable()) {\n statsContext.stats(statsContext.bytesStat(methodName,\n requestData.length(), \"requestSent\"));\n }\n }\n return null;\n }", "@SuppressWarnings(\"unchecked\")\n protected <T extends Indexable> T taskResult(String key) {\n Indexable result = this.taskGroup.taskResult(key);\n if (result == null) {\n return null;\n } else {\n T castedResult = (T) result;\n return castedResult;\n }\n }", "public static final Integer parseInteger(String value)\n {\n return (value == null || value.length() == 0 ? null : Integer.valueOf(Integer.parseInt(value)));\n }", "public static Trajectory addPositionNoise(Trajectory t, double sd){\n\t\tCentralRandomNumberGenerator r = CentralRandomNumberGenerator.getInstance();\n\t\tTrajectory newt = new Trajectory(t.getDimension());\n\t\t\n\t\tfor(int i = 0; i < t.size(); i++){\n\t\t\tnewt.add(t.get(i));\n\t\t\tfor(int j = 1; j <= t.getDimension(); j++){\n\t\t\t\tswitch (j) {\n\t\t\t\tcase 1:\n\t\t\t\t\tnewt.get(i).setX(newt.get(i).x + r.nextGaussian()*sd);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tnewt.get(i).setY(newt.get(i).y + r.nextGaussian()*sd);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3:\n\t\t\t\t\tnewt.get(i).setZ(newt.get(i).z + r.nextGaussian()*sd);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn newt;\n\t\t\n\t}", "public synchronized void setSynced(boolean sync) {\n if (synced.get() != sync) {\n // We are changing sync state, so add or remove our master listener as appropriate.\n if (sync && isSendingStatus()) {\n addMasterListener(ourSyncMasterListener);\n } else {\n removeMasterListener(ourSyncMasterListener);\n }\n\n // Also, if there is a tempo master, and we just got synced, adopt its tempo.\n if (!isTempoMaster() && getTempoMaster() != null) {\n setTempo(getMasterTempo());\n }\n }\n synced.set(sync);\n }", "private AssignmentField selectField(AssignmentField[] fields, int index)\n {\n if (index < 1 || index > fields.length)\n {\n throw new IllegalArgumentException(index + \" is not a valid field index\");\n }\n return (fields[index - 1]);\n }", "static PathAddress toPathAddress(String domain, ImmutableManagementResourceRegistration registry, ObjectName name) {\n if (!name.getDomain().equals(domain)) {\n return PathAddress.EMPTY_ADDRESS;\n }\n if (name.equals(ModelControllerMBeanHelper.createRootObjectName(domain))) {\n return PathAddress.EMPTY_ADDRESS;\n }\n final Hashtable<String, String> properties = name.getKeyPropertyList();\n return searchPathAddress(PathAddress.EMPTY_ADDRESS, registry, properties);\n }", "public static void registerDataPersisters(DataPersister... dataPersisters) {\n\t\t// we build the map and replace it to lower the chance of concurrency issues\n\t\tList<DataPersister> newList = new ArrayList<DataPersister>();\n\t\tif (registeredPersisters != null) {\n\t\t\tnewList.addAll(registeredPersisters);\n\t\t}\n\t\tfor (DataPersister persister : dataPersisters) {\n\t\t\tnewList.add(persister);\n\t\t}\n\t\tregisteredPersisters = newList;\n\t}" ]
Deletes an entity by its primary key. @param id Primary key of the entity.
[ "public void deleteById(Object id) {\n\n int count = beginDelete().whereEquals(idColumn.getColumnName(), id).delete();\n\n if (count == 0) {\n throw new RowNotFoundException(table, id);\n }\n }" ]
[ "private FormInput formInputMatchingNode(Node element) {\n\t\tNamedNodeMap attributes = element.getAttributes();\n\t\tIdentification id;\n\n\t\tif (attributes.getNamedItem(\"id\") != null\n\t\t\t\t&& formFillMode != FormFillMode.XPATH_TRAINING) {\n\t\t\tid = new Identification(Identification.How.id,\n\t\t\t\t\tattributes.getNamedItem(\"id\").getNodeValue());\n\t\t\tFormInput input = this.formInputs.get(id);\n\t\t\tif (input != null) {\n\t\t\t\treturn input;\n\t\t\t}\n\t\t}\n\n\t\tif (attributes.getNamedItem(\"name\") != null\n\t\t\t\t&& formFillMode != FormFillMode.XPATH_TRAINING) {\n\t\t\tid = new Identification(Identification.How.name,\n\t\t\t\t\tattributes.getNamedItem(\"name\").getNodeValue());\n\t\t\tFormInput input = this.formInputs.get(id);\n\t\t\tif (input != null) {\n\t\t\t\treturn input;\n\t\t\t}\n\t\t}\n\n\t\tString xpathExpr = XPathHelper.getXPathExpression(element);\n\t\tif (xpathExpr != null && !xpathExpr.equals(\"\")) {\n\t\t\tid = new Identification(Identification.How.xpath, xpathExpr);\n\t\t\tFormInput input = this.formInputs.get(id);\n\t\t\tif (input != null) {\n\t\t\t\treturn input;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}", "public CSTNode set( int index, CSTNode element ) \n {\n \n if( elements == null ) \n {\n throw new GroovyBugError( \"attempt to set() on a EMPTY Reduction\" );\n }\n\n if( index == 0 && !(element instanceof Token) ) \n {\n\n //\n // It's not the greatest of design that the interface allows this, but it\n // is a tradeoff with convenience, and the convenience is more important.\n\n throw new GroovyBugError( \"attempt to set() a non-Token as root of a Reduction\" );\n }\n\n\n //\n // Fill slots with nulls, if necessary.\n\n int count = elements.size();\n if( index >= count ) \n {\n for( int i = count; i <= index; i++ ) \n {\n elements.add( null );\n }\n }\n\n //\n // Then set in the element.\n\n elements.set( index, element );\n\n return element;\n }", "public static<A, B, Z> Function2<A, B, Z> lift(Func2<A, B, Z> f) {\n\treturn bridge.lift(f);\n }", "public static List<String> getArgumentNames(MethodCallExpression methodCall) {\r\n ArrayList<String> result = new ArrayList<String>();\r\n\r\n Expression arguments = methodCall.getArguments();\r\n List<Expression> argExpressions = null;\r\n if (arguments instanceof ArrayExpression) {\r\n argExpressions = ((ArrayExpression) arguments).getExpressions();\r\n } else if (arguments instanceof ListExpression) {\r\n argExpressions = ((ListExpression) arguments).getExpressions();\r\n } else if (arguments instanceof TupleExpression) {\r\n argExpressions = ((TupleExpression) arguments).getExpressions();\r\n } else {\r\n LOG.warn(\"getArgumentNames arguments is not an expected type\");\r\n }\r\n\r\n if (argExpressions != null) {\r\n for (Expression exp : argExpressions) {\r\n if (exp instanceof VariableExpression) {\r\n result.add(((VariableExpression) exp).getName());\r\n }\r\n }\r\n }\r\n return result;\r\n }", "public void setCategoryDisplayOptions(\n String displayCategoriesByRepository,\n String displayCategorySelectionCollapsed) {\n\n m_displayCategoriesByRepository = Boolean.parseBoolean(displayCategoriesByRepository);\n m_displayCategorySelectionCollapsed = Boolean.parseBoolean(displayCategorySelectionCollapsed);\n }", "public ItemRequest<CustomField> updateEnumOption(String enumOption) {\n \n String path = String.format(\"/enum_options/%s\", enumOption);\n return new ItemRequest<CustomField>(this, CustomField.class, path, \"PUT\");\n }", "public final void notifyHeaderItemRangeInserted(int positionStart, int itemCount) {\n int newHeaderItemCount = getHeaderItemCount();\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > newHeaderItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \" + (positionStart + itemCount - 1) + \"] is not within the position bounds for header items [0 - \" + (newHeaderItemCount - 1) + \"].\");\n }\n notifyItemRangeInserted(positionStart, itemCount);\n }", "public static void validateInterimFinalCluster(final Cluster interimCluster,\n final Cluster finalCluster) {\n validateClusterPartitionCounts(interimCluster, finalCluster);\n validateClusterZonesSame(interimCluster, finalCluster);\n validateClusterNodeCounts(interimCluster, finalCluster);\n validateClusterNodeState(interimCluster, finalCluster);\n return;\n }", "protected static InstallationModificationImpl.InstallationState load(final InstalledIdentity installedIdentity) throws IOException {\n final InstallationModificationImpl.InstallationState state = new InstallationModificationImpl.InstallationState();\n for (final Layer layer : installedIdentity.getLayers()) {\n state.putLayer(layer);\n }\n for (final AddOn addOn : installedIdentity.getAddOns()) {\n state.putAddOn(addOn);\n }\n return state;\n }" ]
Use this API to add onlinkipv6prefix resources.
[ "public static base_responses add(nitro_service client, onlinkipv6prefix resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tonlinkipv6prefix addresources[] = new onlinkipv6prefix[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new onlinkipv6prefix();\n\t\t\t\taddresources[i].ipv6prefix = resources[i].ipv6prefix;\n\t\t\t\taddresources[i].onlinkprefix = resources[i].onlinkprefix;\n\t\t\t\taddresources[i].autonomusprefix = resources[i].autonomusprefix;\n\t\t\t\taddresources[i].depricateprefix = resources[i].depricateprefix;\n\t\t\t\taddresources[i].decrementprefixlifetimes = resources[i].decrementprefixlifetimes;\n\t\t\t\taddresources[i].prefixvalidelifetime = resources[i].prefixvalidelifetime;\n\t\t\t\taddresources[i].prefixpreferredlifetime = resources[i].prefixpreferredlifetime;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}" ]
[ "private void populateRecurringException(ProjectCalendarException mpxjException, Exceptions.Exception xmlException)\n {\n RecurringData data = mpxjException.getRecurring();\n xmlException.setEnteredByOccurrences(Boolean.TRUE);\n xmlException.setOccurrences(NumberHelper.getBigInteger(data.getOccurrences()));\n\n switch (data.getRecurrenceType())\n {\n case DAILY:\n {\n xmlException.setType(BigInteger.valueOf(7));\n xmlException.setPeriod(NumberHelper.getBigInteger(data.getFrequency()));\n break;\n }\n\n case WEEKLY:\n {\n xmlException.setType(BigInteger.valueOf(6));\n xmlException.setPeriod(NumberHelper.getBigInteger(data.getFrequency()));\n xmlException.setDaysOfWeek(getDaysOfTheWeek(data));\n break;\n }\n\n case MONTHLY:\n {\n xmlException.setPeriod(NumberHelper.getBigInteger(data.getFrequency()));\n if (data.getRelative())\n {\n xmlException.setType(BigInteger.valueOf(5));\n xmlException.setMonthItem(BigInteger.valueOf(data.getDayOfWeek().getValue() + 2));\n xmlException.setMonthPosition(BigInteger.valueOf(NumberHelper.getInt(data.getDayNumber()) - 1));\n }\n else\n {\n xmlException.setType(BigInteger.valueOf(4));\n xmlException.setMonthDay(NumberHelper.getBigInteger(data.getDayNumber()));\n }\n break;\n }\n\n case YEARLY:\n {\n xmlException.setMonth(BigInteger.valueOf(NumberHelper.getInt(data.getMonthNumber()) - 1));\n if (data.getRelative())\n {\n xmlException.setType(BigInteger.valueOf(3));\n xmlException.setMonthItem(BigInteger.valueOf(data.getDayOfWeek().getValue() + 2));\n xmlException.setMonthPosition(BigInteger.valueOf(NumberHelper.getInt(data.getDayNumber()) - 1));\n }\n else\n {\n xmlException.setType(BigInteger.valueOf(2));\n xmlException.setMonthDay(NumberHelper.getBigInteger(data.getDayNumber()));\n }\n }\n }\n }", "private void updateDevices(DeviceAnnouncement announcement) {\n firstDeviceTime.compareAndSet(0, System.currentTimeMillis());\n devices.put(announcement.getAddress(), announcement);\n }", "public NamespacesList<Namespace> getNamespaces(String predicate, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n NamespacesList<Namespace> nsList = new NamespacesList<Namespace>();\r\n parameters.put(\"method\", METHOD_GET_NAMESPACES);\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(\"namespace\");\r\n nsList.setPage(\"1\");\r\n nsList.setPages(\"1\");\r\n nsList.setPerPage(\"\" + nsNodes.getLength());\r\n nsList.setTotal(\"\" + nsNodes.getLength());\r\n for (int i = 0; i < nsNodes.getLength(); i++) {\r\n Element element = (Element) nsNodes.item(i);\r\n nsList.add(parseNamespace(element));\r\n }\r\n return nsList;\r\n }", "public Object copy(final Object obj, final PersistenceBroker broker)\r\n {\r\n return clone(obj, IdentityMapFactory.getIdentityMap(), broker);\r\n }", "public void ifHasProperty(String template, Properties attributes) throws XDocletException\r\n {\r\n String value = getPropertyValue(attributes.getProperty(ATTRIBUTE_LEVEL), attributes.getProperty(ATTRIBUTE_NAME));\r\n\r\n if (value != null)\r\n {\r\n generate(template);\r\n }\r\n }", "public static nslimitidentifier_stats get(nitro_service service, String name) throws Exception{\n\t\tnslimitidentifier_stats obj = new nslimitidentifier_stats();\n\t\tobj.set_name(name);\n\t\tnslimitidentifier_stats response = (nslimitidentifier_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "protected void handleResponse(int responseCode, InputStream inputStream) {\n BufferedReader rd = null;\n try {\n // Buffer the result into a string\n rd = new BufferedReader(new InputStreamReader(inputStream));\n StringBuilder sb = new StringBuilder();\n String line;\n while((line = rd.readLine()) != null) {\n sb.append(line);\n }\n log.info(\"HttpHook [\" + hookName + \"] received \" + responseCode + \" response: \" + sb);\n } catch (IOException e) {\n log.error(\"Error while reading response for HttpHook [\" + hookName + \"]\", e);\n } finally {\n if (rd != null) {\n try {\n rd.close();\n } catch (IOException e) {\n // no-op\n }\n }\n }\n }", "public AsciiTable setPaddingBottom(int paddingBottom) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingBottom(paddingBottom);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public void setCalendar(ProjectCalendar calendar)\n {\n set(TaskField.CALENDAR, calendar);\n setCalendarUniqueID(calendar == null ? null : calendar.getUniqueID());\n }" ]
Get a property as a boolean or null. @param key the property name
[ "@Override\n public final Boolean optBool(final String key) {\n if (this.obj.optString(key, null) == null) {\n return null;\n } else {\n return this.obj.optBoolean(key);\n }\n }" ]
[ "protected String classOf(List<IN> lineInfos, int pos) {\r\n Datum<String, String> d = makeDatum(lineInfos, pos, featureFactory);\r\n return classifier.classOf(d);\r\n }", "public void execute() {\n try {\n while(true) {\n Event event = null;\n\n try {\n event = eventQueue.poll(timeout, unit);\n } catch(InterruptedException e) {\n throw new InsufficientOperationalNodesException(operation.getSimpleName()\n + \" operation interrupted!\", e);\n }\n\n if(event == null)\n throw new VoldemortException(operation.getSimpleName()\n + \" returned a null event\");\n\n if(event.equals(Event.ERROR)) {\n if(logger.isTraceEnabled())\n logger.trace(operation.getSimpleName()\n + \" request, events complete due to error\");\n\n break;\n } else if(event.equals(Event.COMPLETED)) {\n if(logger.isTraceEnabled())\n logger.trace(operation.getSimpleName() + \" request, events complete\");\n\n break;\n }\n\n Action action = eventActions.get(event);\n\n if(action == null)\n throw new IllegalStateException(\"action was null for event \" + event);\n\n if(logger.isTraceEnabled())\n logger.trace(operation.getSimpleName() + \" request, action \"\n + action.getClass().getSimpleName() + \" to handle \" + event\n + \" event\");\n\n action.execute(this);\n }\n } finally {\n finished = true;\n }\n }", "private 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 writeCustomInfo(Event event) {\n // insert customInfo (key/value) into DB\n for (Map.Entry<String, String> customInfo : event.getCustomInfo().entrySet()) {\n long cust_id = dbDialect.getIncrementer().nextLongValue();\n getJdbcTemplate()\n .update(\"insert into EVENTS_CUSTOMINFO (ID, EVENT_ID, CUST_KEY, CUST_VALUE)\"\n + \" values (?,?,?,?)\",\n cust_id, event.getPersistedId(), customInfo.getKey(), customInfo.getValue());\n }\n }", "public ResourceAssignment addResourceAssignment(Resource resource)\n {\n ResourceAssignment assignment = getExistingResourceAssignment(resource);\n\n if (assignment == null)\n {\n assignment = new ResourceAssignment(getParentFile(), this);\n m_assignments.add(assignment);\n getParentFile().getResourceAssignments().add(assignment);\n\n assignment.setTaskUniqueID(getUniqueID());\n assignment.setWork(getDuration());\n assignment.setUnits(ResourceAssignment.DEFAULT_UNITS);\n\n if (resource != null)\n {\n assignment.setResourceUniqueID(resource.getUniqueID());\n resource.addResourceAssignment(assignment);\n }\n }\n\n return (assignment);\n }", "private static XMLStreamException unexpectedElement(final XMLStreamReader reader) {\n return SecurityManagerLogger.ROOT_LOGGER.unexpectedElement(reader.getName(), reader.getLocation());\n }", "public T copy() {\n T ret = createLike();\n ret.getMatrix().set(this.getMatrix());\n return ret;\n }", "private void processChildTasks(Task task, MapRow row) throws IOException\n {\n List<MapRow> tasks = row.getRows(\"TASKS\");\n if (tasks != null)\n {\n for (MapRow childTask : tasks)\n {\n processTask(task, childTask);\n }\n }\n }", "public Logger getLogger(String loggerName)\r\n {\r\n Logger logger;\r\n //lookup in the cache first\r\n logger = (Logger) cache.get(loggerName);\r\n\r\n if(logger == null)\r\n {\r\n try\r\n {\r\n // get the configuration (not from the configurator because this is independent)\r\n logger = createLoggerInstance(loggerName);\r\n if(getBootLogger().isDebugEnabled())\r\n {\r\n getBootLogger().debug(\"Using logger class '\"\r\n + (getConfiguration() != null ? getConfiguration().getLoggerClass() : null)\r\n + \"' for \" + loggerName);\r\n }\r\n // configure the logger\r\n getBootLogger().debug(\"Initializing logger instance \" + loggerName);\r\n logger.configure(conf);\r\n }\r\n catch(Throwable t)\r\n {\r\n // do reassign check and signal logger creation failure\r\n reassignBootLogger(true);\r\n logger = getBootLogger();\r\n getBootLogger().error(\"[\" + this.getClass().getName()\r\n + \"] Could not initialize logger \" + (conf != null ? conf.getLoggerClass() : null), t);\r\n }\r\n //cache it so we can get it faster the next time\r\n cache.put(loggerName, logger);\r\n // do reassign check\r\n reassignBootLogger(false);\r\n }\r\n return logger;\r\n }" ]
Waits for the timeout duration until the url responds with correct status code @param routeUrl URL to check (usually a route one) @param timeout Max timeout value to await for route readiness. If not set, default timeout value is set to 5. @param timeoutUnit TimeUnit used for timeout duration. If not set, Minutes is used as default TimeUnit. @param repetitions How many times in a row the route must respond successfully to be considered available. @param statusCodes list of status code that might return that service is up and running. It is used as OR, so if one returns true, then the route is considered valid. If not set, then only 200 status code is used.
[ "public static void awaitRoute(URL routeUrl, int timeout, TimeUnit timeoutUnit, int repetitions, int... statusCodes) {\n AtomicInteger successfulAwaitsInARow = new AtomicInteger(0);\n await().atMost(timeout, timeoutUnit).until(() -> {\n if (tryConnect(routeUrl, statusCodes)) {\n successfulAwaitsInARow.incrementAndGet();\n } else {\n successfulAwaitsInARow.set(0);\n }\n return successfulAwaitsInARow.get() >= repetitions;\n });\n }" ]
[ "public static <T, ID> int dropTable(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig,\n\t\t\tboolean ignoreErrors) throws SQLException {\n\t\tDatabaseType databaseType = connectionSource.getDatabaseType();\n\t\tDao<T, ID> dao = DaoManager.createDao(connectionSource, tableConfig);\n\t\tif (dao instanceof BaseDaoImpl<?, ?>) {\n\t\t\treturn doDropTable(databaseType, connectionSource, ((BaseDaoImpl<?, ?>) dao).getTableInfo(), ignoreErrors);\n\t\t} else {\n\t\t\ttableConfig.extractFieldTypes(databaseType);\n\t\t\tTableInfo<T, ID> tableInfo = new TableInfo<T, ID>(databaseType, tableConfig);\n\t\t\treturn doDropTable(databaseType, connectionSource, tableInfo, ignoreErrors);\n\t\t}\n\t}", "public float getSize(final Axis axis) {\n float size = 0;\n if (mViewPort != null && mViewPort.isClippingEnabled(axis)) {\n size = mViewPort.get(axis);\n } else if (mContainer != null) {\n size = getSizeImpl(axis);\n }\n return size;\n }", "public PlaybackState getFurthestPlaybackState() {\n PlaybackState result = null;\n for (PlaybackState state : playbackStateMap.values()) {\n if (result == null || (!result.playing && state.playing) ||\n (result.position < state.position) && (state.playing || !result.playing)) {\n result = state;\n }\n }\n return result;\n }", "public Task<Void> sendResetPasswordEmail(@NonNull final String email) {\n return dispatcher.dispatchTask(\n new Callable<Void>() {\n @Override\n public Void call() {\n sendResetPasswordEmailInternal(email);\n return null;\n }\n });\n }", "private void updateDurationTimeUnit(FastTrackColumn column)\n {\n if (m_durationTimeUnit == null && isDurationColumn(column))\n {\n int value = ((DurationColumn) column).getTimeUnitValue();\n if (value != 1)\n {\n m_durationTimeUnit = FastTrackUtility.getTimeUnit(value);\n }\n }\n }", "public int expect(String pattern) throws MalformedPatternException, Exception {\n logger.trace(\"Searching for '\" + pattern + \"' in the reader stream\");\n return expect(pattern, null);\n }", "@Override\n public final Integer optInt(final String key, final Integer defaultValue) {\n Integer result = optInt(key);\n return result == null ? defaultValue : result;\n }", "public static sslcertkey[] get(nitro_service service, String certkey[]) throws Exception{\n\t\tif (certkey !=null && certkey.length>0) {\n\t\t\tsslcertkey response[] = new sslcertkey[certkey.length];\n\t\t\tsslcertkey obj[] = new sslcertkey[certkey.length];\n\t\t\tfor (int i=0;i<certkey.length;i++) {\n\t\t\t\tobj[i] = new sslcertkey();\n\t\t\t\tobj[i].set_certkey(certkey[i]);\n\t\t\t\tresponse[i] = (sslcertkey) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "public static final 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 }" ]
Instantiates the templates specified by @Template within @Templates
[ "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 }" ]
[ "private void writeCustomField(CustomField field) throws IOException\n {\n if (field.getAlias() != null)\n {\n m_writer.writeStartObject(null);\n m_writer.writeNameValuePair(\"field_type_class\", field.getFieldType().getFieldTypeClass().name().toLowerCase());\n m_writer.writeNameValuePair(\"field_type\", field.getFieldType().name().toLowerCase());\n m_writer.writeNameValuePair(\"field_alias\", field.getAlias());\n m_writer.writeEndObject();\n }\n }", "public <T> T cached(String key) {\n H.Session sess = session();\n if (null != sess) {\n return sess.cached(key);\n } else {\n return app().cache().get(key);\n }\n }", "public static base_response update(nitro_service client, sslocspresponder resource) throws Exception {\n\t\tsslocspresponder updateresource = new sslocspresponder();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.url = resource.url;\n\t\tupdateresource.cache = resource.cache;\n\t\tupdateresource.cachetimeout = resource.cachetimeout;\n\t\tupdateresource.batchingdepth = resource.batchingdepth;\n\t\tupdateresource.batchingdelay = resource.batchingdelay;\n\t\tupdateresource.resptimeout = resource.resptimeout;\n\t\tupdateresource.respondercert = resource.respondercert;\n\t\tupdateresource.trustresponder = resource.trustresponder;\n\t\tupdateresource.producedattimeskew = resource.producedattimeskew;\n\t\tupdateresource.signingcert = resource.signingcert;\n\t\tupdateresource.usenonce = resource.usenonce;\n\t\tupdateresource.insertclientcert = resource.insertclientcert;\n\t\treturn updateresource.update_resource(client);\n\t}", "private void recordRollbackLoader(final String patchId, PatchableTarget.TargetInfo target) {\n // setup the content loader paths\n final DirectoryStructure structure = target.getDirectoryStructure();\n final InstalledImage image = structure.getInstalledImage();\n final File historyDir = image.getPatchHistoryDir(patchId);\n final File miscRoot = new File(historyDir, PatchContentLoader.MISC);\n final File modulesRoot = structure.getModulePatchDirectory(patchId);\n final File bundlesRoot = structure.getBundlesPatchDirectory(patchId);\n final PatchContentLoader loader = PatchContentLoader.create(miscRoot, bundlesRoot, modulesRoot);\n //\n recordContentLoader(patchId, loader);\n }", "static void handleNotificationClicked(Context context,Bundle notification) {\n if (notification == null) return;\n\n String _accountId = null;\n try {\n _accountId = notification.getString(Constants.WZRK_ACCT_ID_KEY);\n } catch (Throwable t) {\n // no-op\n }\n\n if (instances == null) {\n CleverTapAPI instance = createInstanceIfAvailable(context, _accountId);\n if (instance != null) {\n instance.pushNotificationClickedEvent(notification);\n }\n return;\n }\n\n for (String accountId: instances.keySet()) {\n CleverTapAPI instance = CleverTapAPI.instances.get(accountId);\n boolean shouldProcess = false;\n if (instance != null) {\n shouldProcess = (_accountId == null && instance.config.isDefaultInstance()) || instance.getAccountId().equals(_accountId);\n }\n if (shouldProcess) {\n instance.pushNotificationClickedEvent(notification);\n break;\n }\n }\n }", "private static boolean isValidPropertyClass(final PropertyDescriptor _property) {\n final Class type = _property.getPropertyType();\n return Number.class.isAssignableFrom(type) || type == String.class || Date.class.isAssignableFrom(type) || type == Boolean.class;\n }", "public Set<String> getConfiguredWorkplaceBundles() {\n\n CmsADEConfigData configData = internalLookupConfiguration(null, null);\n return configData.getConfiguredWorkplaceBundles();\n }", "public void put(@NotNull final Transaction txn, final long localId,\n final int blobId, @NotNull final ByteIterable value) {\n primaryStore.put(txn, PropertyKey.propertyKeyToEntry(new PropertyKey(localId, blobId)), value);\n allBlobsIndex.put(txn, IntegerBinding.intToCompressedEntry(blobId), LongBinding.longToCompressedEntry(localId));\n }", "@Override\n public void accept(IBinaryType binaryType, PackageBinding packageBinding, AccessRestriction accessRestriction) {\n if (this.options.verbose) {\n this.out.println(\n Messages.bind(Messages.compilation_loadBinary, new String(binaryType.getName())));\n//\t\t\tnew Exception(\"TRACE BINARY\").printStackTrace(System.out);\n//\t\t System.out.println();\n }\n LookupEnvironment env = packageBinding.environment;\n env.createBinaryTypeFrom(binaryType, packageBinding, accessRestriction);\n }" ]
Convert from an internal Spring bean definition to a DTO. @param beanDefinition The internal Spring bean definition. @return Returns a DTO representation.
[ "public BeanDefinitionInfo toDto(BeanDefinition beanDefinition) {\n\t\tif (beanDefinition instanceof GenericBeanDefinition) {\n\t\t\tGenericBeanDefinitionInfo info = new GenericBeanDefinitionInfo();\n\t\t\tinfo.setClassName(beanDefinition.getBeanClassName());\n\n\t\t\tif (beanDefinition.getPropertyValues() != null) {\n\t\t\t\tMap<String, BeanMetadataElementInfo> propertyValues = new HashMap<String, BeanMetadataElementInfo>();\n\t\t\t\tfor (PropertyValue value : beanDefinition.getPropertyValues().getPropertyValueList()) {\n\t\t\t\t\tObject obj = value.getValue();\n\t\t\t\t\tif (obj instanceof BeanMetadataElement) {\n\t\t\t\t\t\tpropertyValues.put(value.getName(), toDto((BeanMetadataElement) obj));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthrow new IllegalArgumentException(\"Type \" + obj.getClass().getName()\n\t\t\t\t\t\t\t\t+ \" is not a BeanMetadataElement for property: \" + value.getName());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tinfo.setPropertyValues(propertyValues);\n\t\t\t}\n\t\t\treturn info;\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\"Conversion to DTO of \" + beanDefinition.getClass().getName()\n\t\t\t\t\t+ \" not implemented\");\n\t\t}\n\t}" ]
[ "protected byte[] getBytesInternal() {\n\t\tbyte cached[];\n\t\tif(hasNoValueCache() || (cached = valueCache.lowerBytes) == null) {\n\t\t\tvalueCache.lowerBytes = cached = getBytesImpl(true);\n\t\t}\n\t\treturn cached;\n\t}", "public static final List<String> listProjectNames(File directory)\n {\n List<String> result = new ArrayList<String>();\n\n File[] files = directory.listFiles(new FilenameFilter()\n {\n @Override public boolean accept(File dir, String name)\n {\n return name.toUpperCase().endsWith(\"STR.P3\");\n }\n });\n\n if (files != null)\n {\n for (File file : files)\n {\n String fileName = file.getName();\n String prefix = fileName.substring(0, fileName.length() - 6);\n result.add(prefix);\n }\n }\n\n Collections.sort(result);\n\n return result;\n }", "public static base_response unset(nitro_service client, tmsessionparameter resource, String[] args) throws Exception{\n\t\ttmsessionparameter unsetresource = new tmsessionparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "@OnClick(R.id.navigateToModule1Service)\n public void onNavigationServiceCTAClick() {\n Intent intentService = HensonNavigator.gotoModule1Service(this)\n .stringExtra(\"foo\")\n .build();\n\n startService(intentService);\n }", "public void loadClassifier(InputStream in, Properties props) throws IOException, ClassCastException,\r\n ClassNotFoundException {\r\n loadClassifier(new ObjectInputStream(in), props);\r\n }", "private void remove(String directoryName) {\n if ((directoryName == null) || (conn == null))\n return;\n\n String key = S3Util.sanitize(directoryName) + \"/\" + S3Util.sanitize(DC_FILE_NAME);\n try {\n Map headers = new TreeMap();\n headers.put(\"Content-Type\", Arrays.asList(\"text/plain\"));\n if (usingPreSignedUrls()) {\n conn.delete(pre_signed_delete_url).connection.getResponseMessage();\n } else {\n conn.delete(location, key, headers).connection.getResponseMessage();\n }\n }\n catch(Exception e) {\n ROOT_LOGGER.cannotRemoveS3File(e);\n }\n }", "private void ensureNoTableInfoIfNoRepositoryInfo(ClassDescriptorDef classDef, String checkLevel)\r\n {\r\n if (!classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_REPOSITORY_INFO, true))\r\n {\r\n classDef.setProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, \"false\");\r\n }\r\n }", "public boolean matches(Property property) {\n return property.getName().equals(key) && (value == WILDCARD_VALUE || property.getValue().asString().equals(value));\n }", "private String getParentWBS(String wbs)\n {\n String result;\n int index = wbs.lastIndexOf('.');\n if (index == -1)\n {\n result = null;\n }\n else\n {\n result = wbs.substring(0, index);\n }\n return result;\n }" ]
Returns the value of the identified field as a String. @param fieldName the name of the field @return the value of the field as a String
[ "public String getString(String fieldName) {\n\t\treturn hasValue(fieldName) ? String.valueOf(resultMap.get(fieldName)) : null;\n\t}" ]
[ "public boolean detectMobileQuick() {\r\n\r\n //Let's exclude tablets\r\n if (isTierTablet) {\r\n return false;\r\n }\r\n //Most mobile browsing is done on smartphones\r\n if (detectSmartphone()) {\r\n return true;\r\n }\r\n\r\n //Catch-all for many mobile devices\r\n if (userAgent.indexOf(mobile) != -1) {\r\n return true;\r\n }\r\n\r\n if (detectOperaMobile()) {\r\n return true;\r\n }\r\n\r\n //We also look for Kindle devices\r\n if (detectKindle() || detectAmazonSilk()) {\r\n return true;\r\n }\r\n\r\n if (detectWapWml() || detectMidpCapable() || detectBrewDevice()) {\r\n return true;\r\n }\r\n\r\n if ((userAgent.indexOf(engineNetfront) != -1) || (userAgent.indexOf(engineUpBrowser) != -1)) {\r\n return true;\r\n }\r\n\r\n return false;\r\n }", "@Override\n public void clear() {\n values.clear();\n listBox.clear();\n\n clearStatusText();\n if (emptyPlaceHolder != null) {\n insertEmptyPlaceHolder(emptyPlaceHolder);\n }\n reload();\n if (isAllowBlank()) {\n addBlankItemIfNeeded();\n }\n }", "private boolean addDeploymentTypeBasedDependencies(ProjectModel projectModel, Pom modulePom)\n {\n if (projectModel.getProjectType() == null)\n return true;\n switch (projectModel.getProjectType()){\n case \"ear\":\n break;\n case \"war\":\n modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_SERVLET_31));\n break;\n case \"ejb\":\n modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_EJB_32));\n modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_CDI));\n modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_JAVAX_ANN));\n break;\n case \"ejb-client\":\n modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_EJB_CLIENT));\n break;\n }\n return false;\n }", "@Override\n public Scenario<GIVEN, WHEN, THEN> startScenario( String description ) {\n super.startScenario( description );\n return this;\n\n }", "void awaitStabilityUninterruptibly(long timeout, TimeUnit timeUnit) throws TimeoutException {\n boolean interrupted = false;\n try {\n long toWait = timeUnit.toMillis(timeout);\n long msTimeout = System.currentTimeMillis() + toWait;\n while (true) {\n if (interrupted) {\n toWait = msTimeout - System.currentTimeMillis();\n }\n try {\n if (toWait <= 0 || !monitor.awaitStability(toWait, TimeUnit.MILLISECONDS, failed, problems)) {\n throw new TimeoutException();\n }\n break;\n } catch (InterruptedException e) {\n interrupted = true;\n }\n }\n } finally {\n if (interrupted) {\n Thread.currentThread().interrupt();\n }\n }\n }", "protected String getKey(final String ref, final String filename, final String extension) {\n return prefix + ref + \"/\" + filename + \".\" + extension;\n }", "public List<Formation> listFormation(String appName) {\n return connection.execute(new FormationList(appName), apiKey);\n }", "public static List<String> getAllUserStoreNamesOnNode(AdminClient adminClient, Integer nodeId) {\n List<String> storeNames = Lists.newArrayList();\n List<StoreDefinition> storeDefinitionList = adminClient.metadataMgmtOps.getRemoteStoreDefList(nodeId)\n .getValue();\n\n for(StoreDefinition storeDefinition: storeDefinitionList) {\n storeNames.add(storeDefinition.getName());\n }\n return storeNames;\n }", "@Override\n public void perform(Rewrite event, EvaluationContext context)\n {\n perform((GraphRewrite) event, context);\n }" ]
Parses a string that contains multiple fat client configs in avro format @param configAvro Input string of avro format, that contains config for multiple stores @return Map of store names to store config properties
[ "@SuppressWarnings(\"unchecked\")\n public static Map<String, Properties> readMultipleClientConfigAvro(String configAvro) {\n Map<String, Properties> mapStoreToProps = Maps.newHashMap();\n try {\n JsonDecoder decoder = new JsonDecoder(CLIENT_CONFIGS_AVRO_SCHEMA, configAvro);\n GenericDatumReader<Object> datumReader = new GenericDatumReader<Object>(CLIENT_CONFIGS_AVRO_SCHEMA);\n\n Map<Utf8, Map<Utf8, Utf8>> storeConfigs = (Map<Utf8, Map<Utf8, Utf8>>) datumReader.read(null,\n decoder);\n // Store config props to return back\n for(Utf8 storeName: storeConfigs.keySet()) {\n Properties props = new Properties();\n Map<Utf8, Utf8> singleConfig = storeConfigs.get(storeName);\n\n for(Utf8 key: singleConfig.keySet()) {\n props.put(key.toString(), singleConfig.get(key).toString());\n }\n\n if(storeName == null || storeName.length() == 0) {\n throw new Exception(\"Invalid store name found!\");\n }\n\n mapStoreToProps.put(storeName.toString(), props);\n }\n } catch(Exception e) {\n e.printStackTrace();\n }\n return mapStoreToProps;\n }" ]
[ "public final static void appendCode(final StringBuilder out, final String in, final int start, final int end)\n {\n for (int i = start; i < end; i++)\n {\n final char c;\n switch (c = in.charAt(i))\n {\n case '&':\n out.append(\"&amp;\");\n break;\n case '<':\n out.append(\"&lt;\");\n break;\n case '>':\n out.append(\"&gt;\");\n break;\n default:\n out.append(c);\n break;\n }\n }\n }", "@SuppressWarnings(\"unchecked\")\n public <V3, M4, C, N, Q> N getSceneRoot(AiWrapperProvider<V3, M4, C, N, Q> \n wrapperProvider) {\n\n return (N) m_sceneRoot;\n }", "public String getPrototypeName() {\n\t\tString name = getClass().getName();\n\t\tif (name.startsWith(ORG_GEOMAJAS)) {\n\t\t\tname = name.substring(ORG_GEOMAJAS.length());\n\t\t}\n\t\tname = name.replace(\".dto.\", \".impl.\");\n\t\treturn name.substring(0, name.length() - 4) + \"Impl\";\n\t}", "private JsonArray formatBoxMetadataFilterRequest() {\n JsonArray boxMetadataFilterRequestArray = new JsonArray();\n\n JsonObject boxMetadataFilter = new JsonObject()\n .add(\"templateKey\", this.metadataFilter.getTemplateKey())\n .add(\"scope\", this.metadataFilter.getScope())\n .add(\"filters\", this.metadataFilter.getFiltersList());\n boxMetadataFilterRequestArray.add(boxMetadataFilter);\n\n return boxMetadataFilterRequestArray;\n }", "public int indexOfKey(Object key) {\n return key == null ? indexOfNull() : indexOf(key, key.hashCode());\n }", "public static double blackScholesDigitalOptionVega(\n\t\t\tdouble initialStockValue,\n\t\t\tdouble riskFreeRate,\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike)\n\t{\n\t\tif(optionStrike <= 0.0 || optionMaturity <= 0.0)\n\t\t{\n\t\t\t// The Black-Scholes model does not consider it being an option\n\t\t\treturn 0.0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Calculate vega\n\t\t\tdouble dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));\n\t\t\tdouble dMinus = dPlus - volatility * Math.sqrt(optionMaturity);\n\n\t\t\tdouble vega = - Math.exp(-riskFreeRate * optionMaturity) * Math.exp(-0.5*dMinus*dMinus) / Math.sqrt(2.0 * Math.PI) * dPlus / volatility;\n\n\t\t\treturn vega;\n\t\t}\n\t}", "public Collection<FieldNode> removeAndGetCandidatesWithoutInitialisingMethod() {\n final List<FieldNode> result = new ArrayList<FieldNode>();\n for (final Map.Entry<FieldNode, Initialisers> entry : candidatesAndInitialisers.entrySet()) {\n final Initialisers setters = entry.getValue();\n final List<MethodNode> initialisingMethods = setters.getMethods();\n if (initialisingMethods.isEmpty()) {\n result.add(entry.getKey());\n }\n }\n for (final FieldNode unassociatedVariable : result) {\n candidatesAndInitialisers.remove(unassociatedVariable);\n }\n return result;\n }", "public static JRDesignExpression getReportConnectionExpression() {\n JRDesignExpression connectionExpression = new JRDesignExpression();\n connectionExpression.setText(\"$P{\" + JRDesignParameter.REPORT_CONNECTION + \"}\");\n connectionExpression.setValueClass(Connection.class);\n return connectionExpression;\n }", "public static java.sql.Timestamp toTimestamp(Object value) throws ParseException {\n if (value == null) {\n return null;\n }\n if (value instanceof java.sql.Timestamp) {\n return (java.sql.Timestamp) value;\n }\n if (value instanceof String) {\n\n if (\"\".equals((String) value)) {\n return null;\n }\n return new java.sql.Timestamp(IN_TIMESTAMP_FORMAT.parse((String) value).getTime());\n }\n\n return new java.sql.Timestamp(IN_TIMESTAMP_FORMAT.parse(value.toString()).getTime());\n }" ]
This static method calculated the rho of a call option under a Black-Scholes model @param initialStockValue The initial value of the underlying, i.e., the spot. @param riskFreeRate The risk free rate of the bank account numerarie. @param volatility The Black-Scholes volatility. @param optionMaturity The option maturity T. @param optionStrike The option strike. @return The rho of the option
[ "public static double blackScholesOptionRho(\n\t\t\tdouble initialStockValue,\n\t\t\tdouble riskFreeRate,\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike)\n\t{\n\t\tif(optionStrike <= 0.0 || optionMaturity <= 0.0)\n\t\t{\n\t\t\t// The Black-Scholes model does not consider it being an option\n\t\t\treturn 0.0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Calculate rho\n\t\t\tdouble dMinus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate - 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));\n\n\t\t\tdouble rho = optionStrike * optionMaturity * Math.exp(-riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus);\n\n\t\t\treturn rho;\n\t\t}\n\t}" ]
[ "public synchronized void shutdownTaskScheduler(){\n if (scheduler != null && !scheduler.isShutdown()) {\n scheduler.shutdown();\n logger.info(\"shutdowned the task scheduler. No longer accepting new tasks\");\n scheduler = null;\n }\n }", "protected Class<?> classForName(String name) {\n try {\n return resourceLoader.classForName(name);\n } catch (ResourceLoadingException cnfe) {\n return DUMMY_CLASS;\n }\n }", "private void checkDuplicateStdOutOutput(DumpProcessingAction newAction) {\n\t\tif (newAction.useStdOut()) {\n\t\t\tif (this.quiet) {\n\t\t\t\tlogger.warn(\"Multiple actions are using stdout as output destination.\");\n\t\t\t}\n\t\t\tthis.quiet = true;\n\t\t}\n\t}", "@Override\n protected void updateState(final String name, final InstallationModificationImpl modification, final InstallationModificationImpl.InstallationState state) {\n final PatchableTarget.TargetInfo identityInfo = modification.getModifiedState();\n this.identity = new Identity() {\n @Override\n public String getVersion() {\n return modification.getVersion();\n }\n\n @Override\n public String getName() {\n return name;\n }\n\n @Override\n public TargetInfo loadTargetInfo() throws IOException {\n return identityInfo;\n }\n\n @Override\n public DirectoryStructure getDirectoryStructure() {\n return modification.getDirectoryStructure();\n }\n };\n\n this.allPatches = Collections.unmodifiableList(modification.getAllPatches());\n this.layers.clear();\n for (final Map.Entry<String, MutableTargetImpl> entry : state.getLayers().entrySet()) {\n final String layerName = entry.getKey();\n final MutableTargetImpl target = entry.getValue();\n putLayer(layerName, new LayerInfo(layerName, target.getModifiedState(), target.getDirectoryStructure()));\n }\n this.addOns.clear();\n for (final Map.Entry<String, MutableTargetImpl> entry : state.getAddOns().entrySet()) {\n final String addOnName = entry.getKey();\n final MutableTargetImpl target = entry.getValue();\n putAddOn(addOnName, new LayerInfo(addOnName, target.getModifiedState(), target.getDirectoryStructure()));\n }\n }", "public void readFrom(IIMReader reader, int recover) throws IOException, InvalidDataSetException {\r\n\t\tfinal boolean doLog = log != null;\r\n\t\tfor (;;) {\r\n\t\t\ttry {\r\n\t\t\t\tDataSet ds = reader.read();\r\n\t\t\t\tif (ds == null) {\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (doLog) {\r\n\t\t\t\t\tlog.debug(\"Read data set \" + ds);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tDataSetInfo info = ds.getInfo();\r\n\t\t\t\tSerializer s = info.getSerializer();\r\n\t\t\t\tif (s != null) {\r\n\t\t\t\t\tif (info.getDataSetNumber() == IIM.DS(1, 90)) {\r\n\t\t\t\t\t\tsetCharacterSet((String) s.deserialize(ds.getData(), activeSerializationContext));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tdataSets.add(ds);\r\n\r\n\t\t\t\tif (stopAfter9_10 && info.getDataSetNumber() == IIM.DS(9, 10))\r\n\t\t\t\t\tbreak;\r\n\t\t\t} catch (IIMFormatException e) {\r\n\t\t\t\tif (recoverFromIIMFormat && recover-- > 0) {\r\n\t\t\t\t\tboolean r = reader.recover();\r\n\t\t\t\t\tif (doLog) {\r\n\t\t\t\t\t\tlog.debug(r ? \"Recoved from \" + e : \"Failed to recover from \" + e);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (!r)\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tthrow e;\r\n\t\t\t\t}\r\n\t\t\t} catch (UnsupportedDataSetException e) {\r\n\t\t\t\tif (recoverFromUnsupportedDataSet && recover-- > 0) {\r\n\t\t\t\t\tboolean r = reader.recover();\r\n\t\t\t\t\tif (doLog) {\r\n\t\t\t\t\t\tlog.debug(r ? \"Recoved from \" + e : \"Failed to recover from \" + e);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (!r)\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tthrow e;\r\n\t\t\t\t}\r\n\t\t\t} catch (InvalidDataSetException e) {\r\n\t\t\t\tif (recoverFromInvalidDataSet && recover-- > 0) {\r\n\t\t\t\t\tboolean r = reader.recover();\r\n\t\t\t\t\tif (doLog) {\r\n\t\t\t\t\t\tlog.debug(r ? \"Recoved from \" + e : \"Failed to recover from \" + e);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (!r)\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tthrow e;\r\n\t\t\t\t}\r\n\t\t\t} catch (IOException e) {\r\n\t\t\t\tif (recover-- > 0 && !dataSets.isEmpty()) {\r\n\t\t\t\t\tif (doLog) {\r\n\t\t\t\t\t\tlog.error(\"IOException while reading, however some data sets where recovered, \" + e);\r\n\t\t\t\t\t}\r\n\t\t\t\t\treturn;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tthrow e;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}", "private String filterTag(String tag) {\r\n\t AttributeValues answerAV = TagSet.getTagSet().fromTag(tag);\r\n\t answerAV.removeNonlexicalAttributes();\r\n\t return TagSet.getTagSet().toTag(answerAV);\r\n }", "public static int restrictRange(int value, int min, int max)\n {\n return Math.min((Math.max(value, min)), max);\n }", "private void readHours(ProjectCalendar calendar, Day day, Integer hours)\n {\n int value = hours.intValue();\n int startHour = 0;\n ProjectCalendarHours calendarHours = null;\n\n Calendar cal = DateHelper.popCalendar();\n cal.set(Calendar.HOUR_OF_DAY, 0);\n cal.set(Calendar.MINUTE, 0);\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MILLISECOND, 0);\n\n calendar.setWorkingDay(day, false);\n\n while (value != 0)\n {\n // Move forward until we find a working hour\n while (startHour < 24 && (value & 0x1) == 0)\n {\n value = value >> 1;\n ++startHour;\n }\n\n // No more working hours, bail out\n if (startHour >= 24)\n {\n break;\n }\n\n // Move forward until we find the end of the working hours\n int endHour = startHour;\n while (endHour < 24 && (value & 0x1) != 0)\n {\n value = value >> 1;\n ++endHour;\n }\n\n cal.set(Calendar.HOUR_OF_DAY, startHour);\n Date startDate = cal.getTime();\n cal.set(Calendar.HOUR_OF_DAY, endHour);\n Date endDate = cal.getTime();\n\n if (calendarHours == null)\n {\n calendarHours = calendar.addCalendarHours(day);\n calendar.setWorkingDay(day, true);\n }\n calendarHours.addRange(new DateRange(startDate, endDate));\n startHour = endHour;\n }\n \n DateHelper.pushCalendar(cal);\n }", "public static DatagramPacket buildPacket(PacketType type, ByteBuffer deviceName, ByteBuffer payload) {\n ByteBuffer content = ByteBuffer.allocate(0x1f + payload.remaining());\n content.put(getMagicHeader());\n content.put(type.protocolValue);\n content.put(deviceName);\n content.put(payload);\n return new DatagramPacket(content.array(), content.capacity());\n }" ]
prefix the this class fk columns with the indirection table
[ "private String[] getFksToThisClass()\r\n {\r\n String indTable = getCollectionDescriptor().getIndirectionTable();\r\n String[] fks = getCollectionDescriptor().getFksToThisClass();\r\n String[] result = new String[fks.length];\r\n\r\n for (int i = 0; i < result.length; i++)\r\n {\r\n result[i] = indTable + \".\" + fks[i];\r\n }\r\n\r\n return result;\r\n }" ]
[ "@Override\n\tpublic Trajectory subList(int fromIndex, int toIndex) {\n\t\tTrajectory t = new Trajectory(dimension);\n\t\t\n\t\tfor(int i = fromIndex; i < toIndex; i++){\n\t\t\tt.add(this.get(i));\n\t\t}\n\t\treturn t;\n\t}", "public byte[] getByteArray(int offset)\n {\n byte[] result = null;\n\n if (offset > 0 && offset < m_data.length)\n {\n int nextBlockOffset = MPPUtility.getInt(m_data, offset);\n offset += 4;\n\n int itemSize = MPPUtility.getInt(m_data, offset);\n offset += 4;\n\n if (itemSize > 0 && itemSize < m_data.length)\n {\n int blockRemainingSize = 28;\n\n if (nextBlockOffset != -1 || itemSize <= blockRemainingSize)\n {\n int itemRemainingSize = itemSize;\n result = new byte[itemSize];\n int resultOffset = 0;\n\n while (nextBlockOffset != -1)\n {\n MPPUtility.getByteArray(m_data, offset, blockRemainingSize, result, resultOffset);\n resultOffset += blockRemainingSize;\n offset += blockRemainingSize;\n itemRemainingSize -= blockRemainingSize;\n\n if (offset != nextBlockOffset)\n {\n offset = nextBlockOffset;\n }\n\n nextBlockOffset = MPPUtility.getInt(m_data, offset);\n offset += 4;\n blockRemainingSize = 32;\n }\n\n MPPUtility.getByteArray(m_data, offset, itemRemainingSize, result, resultOffset);\n }\n }\n }\n\n return (result);\n }", "public void setScale(final float scale) {\n if (equal(mScale, scale) != true) {\n Log.d(TAG, \"setScale(): old: %.2f, new: %.2f\", mScale, scale);\n mScale = scale;\n setScale(mSceneRootObject, scale);\n setScale(mMainCameraRootObject, scale);\n setScale(mLeftCameraRootObject, scale);\n setScale(mRightCameraRootObject, scale);\n for (OnScaledListener listener : mOnScaledListeners) {\n try {\n listener.onScaled(scale);\n } catch (Exception e) {\n e.printStackTrace();\n Log.e(TAG, e, \"setScale()\");\n }\n }\n }\n }", "public static authenticationvserver_authenticationradiuspolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_authenticationradiuspolicy_binding obj = new authenticationvserver_authenticationradiuspolicy_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_authenticationradiuspolicy_binding response[] = (authenticationvserver_authenticationradiuspolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public DomainList getPhotoDomains(Date date, String photoId, int perPage, int page) throws FlickrException {\n return getDomains(METHOD_GET_PHOTO_DOMAINS, \"photo_id\", photoId, date, perPage, page);\n }", "public void sub(Vector3d v1) {\n x -= v1.x;\n y -= v1.y;\n z -= v1.z;\n }", "private void writeIntegerField(String fieldName, Object value) throws IOException\n {\n int val = ((Number) value).intValue();\n if (val != 0)\n {\n m_writer.writeNameValuePair(fieldName, val);\n }\n }", "public static List<String> getChildrenParentMayNotExist(ZkClient zkClient, String path) {\n try {\n return zkClient.getChildren(path);\n } catch (ZkNoNodeException e) {\n return null;\n }\n }", "private String toSQLClause(FieldCriteria c, ClassDescriptor cld)\r\n {\r\n String colName = toSqlClause(c.getAttribute(), cld);\r\n return colName + c.getClause() + c.getValue();\r\n }" ]
Adds all edges for a given object envelope vertex. All edges are added to the edgeList map. @param vertex the Vertex object to find edges for
[ "private void addEdgesForVertex(Vertex vertex)\r\n {\r\n ClassDescriptor cld = vertex.getEnvelope().getClassDescriptor();\r\n Iterator rdsIter = cld.getObjectReferenceDescriptors(true).iterator();\r\n while (rdsIter.hasNext())\r\n {\r\n ObjectReferenceDescriptor rds = (ObjectReferenceDescriptor) rdsIter.next();\r\n addObjectReferenceEdges(vertex, rds);\r\n }\r\n Iterator cdsIter = cld.getCollectionDescriptors(true).iterator();\r\n while (cdsIter.hasNext())\r\n {\r\n CollectionDescriptor cds = (CollectionDescriptor) cdsIter.next();\r\n addCollectionEdges(vertex, cds);\r\n }\r\n }" ]
[ "public static <T> Object callMethod(Object obj,\n Class<T> c,\n String name,\n Class<?>[] classes,\n Object[] args) {\n try {\n Method m = getMethod(c, name, classes);\n return m.invoke(obj, args);\n } catch(InvocationTargetException e) {\n throw getCause(e);\n } catch(IllegalAccessException e) {\n throw new IllegalStateException(e);\n }\n }", "public static int rank( DMatrixRMaj A ) {\n SingularValueDecomposition_F64<DMatrixRMaj> svd = DecompositionFactory_DDRM.svd(A.numRows,A.numCols,false,true,true);\n\n if( svd.inputModified() ) {\n A = A.copy();\n }\n if( !svd.decompose(A)) {\n throw new RuntimeException(\"SVD Failed!\");\n }\n\n int N = svd.numberOfSingularValues();\n double sv[] = svd.getSingularValues();\n\n double threshold = singularThreshold(sv,N);\n int count = 0;\n for (int i = 0; i < sv.length; i++) {\n if( sv[i] >= threshold ) {\n count++;\n }\n }\n return count;\n }", "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 }", "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 void fatal(Throwable throwable, String msg, Object[] argArray) {\n\t\tlogIfEnabled(Level.FATAL, throwable, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, argArray);\n\t}", "public static base_responses update(nitro_service client, bridgetable resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tbridgetable updateresources[] = new bridgetable[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new bridgetable();\n\t\t\t\tupdateresources[i].bridgeage = resources[i].bridgeage;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "public static final Double parseCurrency(Number value)\n {\n return (value == null ? null : NumberHelper.getDouble(value.doubleValue() / 100));\n }", "public static void checkArrayLength(String parameterName, int actualLength,\n int expectedLength) {\n if (actualLength != expectedLength) {\n throw Exceptions.IllegalArgument(\n \"Array %s should have %d elements, not %d\", parameterName,\n expectedLength, actualLength);\n }\n }", "public void printRelations(ClassDoc c) {\n\tOptions opt = optionProvider.getOptionsFor(c);\n\tif (hidden(c) || c.name().equals(\"\")) // avoid phantom classes, they may pop up when the source uses annotations\n\t return;\n\t// Print generalization (through the Java superclass)\n\tType s = c.superclassType();\n\tClassDoc sc = s != null && !s.qualifiedTypeName().equals(Object.class.getName()) ? s.asClassDoc() : null;\n\tif (sc != null && !c.isEnum() && !hidden(sc))\n\t relation(opt, RelationType.EXTENDS, c, sc, null, null, null);\n\t// Print generalizations (through @extends tags)\n\tfor (Tag tag : c.tags(\"extends\"))\n\t if (!hidden(tag.text()))\n\t\trelation(opt, RelationType.EXTENDS, c, c.findClass(tag.text()), null, null, null);\n\t// Print realizations (Java interfaces)\n\tfor (Type iface : c.interfaceTypes()) {\n\t ClassDoc ic = iface.asClassDoc();\n\t if (!hidden(ic))\n\t\trelation(opt, RelationType.IMPLEMENTS, c, ic, null, null, null);\n\t}\n\t// Print other associations\n\tallRelation(opt, RelationType.COMPOSED, c);\n\tallRelation(opt, RelationType.NAVCOMPOSED, c);\n\tallRelation(opt, RelationType.HAS, c);\n\tallRelation(opt, RelationType.NAVHAS, c);\n\tallRelation(opt, RelationType.ASSOC, c);\n\tallRelation(opt, RelationType.NAVASSOC, c);\n\tallRelation(opt, RelationType.DEPEND, c);\n }" ]
Returns the time elapsed by the user on the app @return Time elapsed by user on the app in int
[ "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public int getTimeElapsed() {\n int currentSession = getCurrentSession();\n if (currentSession == 0) return -1;\n\n int now = (int) (System.currentTimeMillis() / 1000);\n return now - currentSession;\n }" ]
[ "protected void updateModel(final ModelNode operation, final Resource resource) throws OperationFailedException {\n updateModel(operation, resource.getModel());\n }", "public static int validateGeohashMaxLevels(Integer userMaxLevels, int defaultMaxLevels) {\n int maxLevels = userMaxLevels == null ? defaultMaxLevels : userMaxLevels;\n if (maxLevels < 1 || maxLevels > GeohashPrefixTree.getMaxLevelsPossible()) {\n throw new IndexException(\"max_levels must be in range [1, {}], but found {}\",\n GeohashPrefixTree.getMaxLevelsPossible(),\n maxLevels);\n }\n return maxLevels;\n }", "public static Date getYearlyAbsoluteAsDate(RecurringData data)\n {\n Date result;\n Integer yearlyAbsoluteDay = data.getDayNumber();\n Integer yearlyAbsoluteMonth = data.getMonthNumber();\n Date startDate = data.getStartDate();\n\n if (yearlyAbsoluteDay == null || yearlyAbsoluteMonth == null || startDate == null)\n {\n result = null;\n }\n else\n {\n Calendar cal = DateHelper.popCalendar(startDate);\n cal.set(Calendar.MONTH, yearlyAbsoluteMonth.intValue() - 1);\n cal.set(Calendar.DAY_OF_MONTH, yearlyAbsoluteDay.intValue());\n result = cal.getTime();\n DateHelper.pushCalendar(cal);\n }\n return result;\n }", "private void initDeactivationPanel() {\n\n m_deactivationPanel.setVisible(false);\n m_deactivationText.setText(Messages.get().key(Messages.GUI_SERIALDATE_DEACTIVE_TEXT_0));\n\n }", "public Task<RemoteInsertOneResult> insertOne(final DocumentT document) {\n return dispatcher.dispatchTask(new Callable<RemoteInsertOneResult>() {\n @Override\n public RemoteInsertOneResult call() {\n return proxy.insertOne(document);\n }\n });\n }", "public ThreadInfo[] getThreadDump() {\n ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();\n return threadMxBean.dumpAllThreads(true, true);\n }", "List<String> getRuleFlowNames(HttpServletRequest req) {\n final String[] projectAndBranch = getProjectAndBranchNames(req);\n\n // Query RuleFlowGroups for asset project and branch\n List<RefactoringPageRow> results = queryService.query(\n DesignerFindRuleFlowNamesQuery.NAME,\n new HashSet<ValueIndexTerm>() {{\n add(new ValueSharedPartIndexTerm(\"*\",\n PartType.RULEFLOW_GROUP,\n TermSearchType.WILDCARD));\n add(new ValueModuleNameIndexTerm(projectAndBranch[0]));\n if (projectAndBranch[1] != null) {\n add(new ValueBranchNameIndexTerm(projectAndBranch[1]));\n }\n }});\n\n final List<String> ruleFlowGroupNames = new ArrayList<String>();\n for (RefactoringPageRow row : results) {\n ruleFlowGroupNames.add((String) row.getValue());\n }\n Collections.sort(ruleFlowGroupNames);\n\n // Query RuleFlowGroups for all projects and branches\n results = queryService.query(\n DesignerFindRuleFlowNamesQuery.NAME,\n new HashSet<ValueIndexTerm>() {{\n add(new ValueSharedPartIndexTerm(\"*\",\n PartType.RULEFLOW_GROUP,\n TermSearchType.WILDCARD));\n }});\n final List<String> otherRuleFlowGroupNames = new LinkedList<String>();\n for (RefactoringPageRow row : results) {\n String ruleFlowGroupName = (String) row.getValue();\n if (!ruleFlowGroupNames.contains(ruleFlowGroupName)) {\n // but only add the new ones\n otherRuleFlowGroupNames.add(ruleFlowGroupName);\n }\n }\n Collections.sort(otherRuleFlowGroupNames);\n\n ruleFlowGroupNames.addAll(otherRuleFlowGroupNames);\n\n return ruleFlowGroupNames;\n }", "public static String getPrettyMapOfContiguousPartitionRunLengths(final Cluster cluster,\n int zoneId) {\n Map<Integer, Integer> runLengthToCount = getMapOfContiguousPartitionRunLengths(cluster,\n zoneId);\n String prettyHistogram = \"[\";\n boolean first = true;\n Set<Integer> runLengths = new TreeSet<Integer>(runLengthToCount.keySet());\n for(int runLength: runLengths) {\n if(first) {\n first = false;\n } else {\n prettyHistogram += \", \";\n }\n prettyHistogram += \"{\" + runLength + \" : \" + runLengthToCount.get(runLength) + \"}\";\n }\n prettyHistogram += \"]\";\n return prettyHistogram;\n }", "public static Priority getInstance(Locale locale, String priority)\n {\n int index = DEFAULT_PRIORITY_INDEX;\n\n if (priority != null)\n {\n String[] priorityTypes = LocaleData.getStringArray(locale, LocaleData.PRIORITY_TYPES);\n for (int loop = 0; loop < priorityTypes.length; loop++)\n {\n if (priorityTypes[loop].equalsIgnoreCase(priority) == true)\n {\n index = loop;\n break;\n }\n }\n }\n\n return (Priority.getInstance((index + 1) * 100));\n }" ]
Checks if a newly created action wants to write output to stdout, and logs a warning if other actions are doing the same. @param newAction the new action to be checked
[ "private void checkDuplicateStdOutOutput(DumpProcessingAction newAction) {\n\t\tif (newAction.useStdOut()) {\n\t\t\tif (this.quiet) {\n\t\t\t\tlogger.warn(\"Multiple actions are using stdout as output destination.\");\n\t\t\t}\n\t\t\tthis.quiet = true;\n\t\t}\n\t}" ]
[ "private ResourceAssignment getExistingResourceAssignment(Resource resource)\n {\n ResourceAssignment assignment = null;\n Integer resourceUniqueID = null;\n\n if (resource != null)\n {\n Iterator<ResourceAssignment> iter = m_assignments.iterator();\n resourceUniqueID = resource.getUniqueID();\n\n while (iter.hasNext() == true)\n {\n assignment = iter.next();\n Integer uniqueID = assignment.getResourceUniqueID();\n if (uniqueID != null && uniqueID.equals(resourceUniqueID) == true)\n {\n break;\n }\n assignment = null;\n }\n }\n\n return assignment;\n }", "public void setModificationState(ModificationState newModificationState)\r\n {\r\n if(newModificationState != modificationState)\r\n {\r\n if(log.isDebugEnabled())\r\n {\r\n log.debug(\"object state transition for object \" + this.oid + \" (\"\r\n + modificationState + \" --> \" + newModificationState + \")\");\r\n// try{throw new Exception();}catch(Exception e)\r\n// {\r\n// e.printStackTrace();\r\n// }\r\n }\r\n modificationState = newModificationState;\r\n }\r\n }", "public static authenticationradiuspolicy_vpnglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationradiuspolicy_vpnglobal_binding obj = new authenticationradiuspolicy_vpnglobal_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationradiuspolicy_vpnglobal_binding response[] = (authenticationradiuspolicy_vpnglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void load(InputStream in) {\n try {\n PropertiesConfiguration config = new PropertiesConfiguration();\n // disabled to prevent accumulo classpath value from being shortened\n config.setDelimiterParsingDisabled(true);\n config.load(in);\n ((CompositeConfiguration) internalConfig).addConfiguration(config);\n } catch (ConfigurationException e) {\n throw new IllegalArgumentException(e);\n }\n }", "public boolean detectTierIphone() {\r\n\r\n if (detectIphoneOrIpod()\r\n || detectAndroidPhone()\r\n || detectWindowsPhone()\r\n || detectBlackBerry10Phone()\r\n || (detectBlackBerryWebKit() && detectBlackBerryTouch())\r\n || detectPalmWebOS()\r\n || detectBada()\r\n || detectTizen()\r\n || detectFirefoxOSPhone()\r\n || detectSailfishPhone()\r\n || detectUbuntuPhone()\r\n || detectGamingHandheld()) {\r\n return true;\r\n }\r\n return false;\r\n }", "public static base_response Import(nitro_service client, application resource) throws Exception {\n\t\tapplication Importresource = new application();\n\t\tImportresource.apptemplatefilename = resource.apptemplatefilename;\n\t\tImportresource.appname = resource.appname;\n\t\tImportresource.deploymentfilename = resource.deploymentfilename;\n\t\treturn Importresource.perform_operation(client,\"Import\");\n\t}", "public int sum() {\n int total = 0;\n int N = getNumElements();\n for (int i = 0; i < N; i++) {\n if( data[i] )\n total += 1;\n }\n return total;\n }", "public Date getFinishDate()\n {\n Date result = (Date) getCachedValue(ProjectField.FINISH_DATE);\n if (result == null)\n {\n result = getParentFile().getFinishDate();\n }\n return (result);\n }", "private IndexedContainer createContainerForBundleWithDescriptor() throws IOException, CmsException {\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 container.addContainerProperty(TableProperty.TRANSLATION, String.class, \"\");\n\n // add entries\n SortedProperties localization = getLocalization(m_locale);\n CmsXmlContentValueSequence messages = m_descContent.getValueSequence(Descriptor.N_MESSAGE, Descriptor.LOCALE);\n String descValue;\n boolean hasDescription = false;\n String defaultValue;\n boolean hasDefault = false;\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 String translation = localization.getProperty(key);\n item.getItemProperty(TableProperty.TRANSLATION).setValue(null == translation ? \"\" : translation);\n descValue = m_descContent.getValue(prefix + Descriptor.N_DESCRIPTION, Descriptor.LOCALE).getStringValue(\n m_cms);\n item.getItemProperty(TableProperty.DESCRIPTION).setValue(descValue);\n hasDescription = hasDescription || !descValue.isEmpty();\n defaultValue = m_descContent.getValue(prefix + Descriptor.N_DEFAULT, Descriptor.LOCALE).getStringValue(\n m_cms);\n item.getItemProperty(TableProperty.DEFAULT).setValue(defaultValue);\n hasDefault = hasDefault || !defaultValue.isEmpty();\n }\n\n m_hasDefault = hasDefault;\n m_hasDescription = hasDescription;\n return container;\n\n }" ]
Get the names of all current registered providers. @return the names of all current registered providers, never null.
[ "@Override\n public Set<String> getProviderNames() {\n Set<String> result = new HashSet<>();\n for (RoundingProviderSpi prov : Bootstrap.getServices(RoundingProviderSpi.class)) {\n try {\n result.add(prov.getProviderName());\n } catch (Exception e) {\n Logger.getLogger(Monetary.class.getName())\n .log(Level.SEVERE, \"Error loading RoundingProviderSpi from provider: \" + prov, e);\n }\n }\n return result;\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}", "private void processRanges(List<DateRange> ranges, ProjectCalendarDateRanges container)\n {\n if (ranges != null)\n {\n for (DateRange range : ranges)\n {\n container.addRange(range);\n }\n }\n }", "public static rewritepolicy_csvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\trewritepolicy_csvserver_binding obj = new rewritepolicy_csvserver_binding();\n\t\tobj.set_name(name);\n\t\trewritepolicy_csvserver_binding response[] = (rewritepolicy_csvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "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}", "public static final String hexdump(byte[] buffer, int offset, int length, boolean ascii, int columns, String prefix)\n {\n StringBuilder sb = new StringBuilder();\n if (buffer != null)\n {\n int index = offset;\n DecimalFormat df = new DecimalFormat(\"00000\");\n\n while (index < (offset + length))\n {\n if (index + columns > (offset + length))\n {\n columns = (offset + length) - index;\n }\n\n sb.append(prefix);\n sb.append(df.format(index - offset));\n sb.append(\":\");\n sb.append(hexdump(buffer, index, columns, ascii));\n sb.append('\\n');\n\n index += columns;\n }\n }\n\n return (sb.toString());\n }", "public Set<String> postProcessingFields() {\n Set<String> fields = new LinkedHashSet<>();\n query.forEach(condition -> fields.addAll(condition.postProcessingFields()));\n sort.forEach(condition -> fields.addAll(condition.postProcessingFields()));\n return fields;\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 }", "public void ifPropertyValueEquals(String template, Properties attributes) throws XDocletException\r\n {\r\n String value = getPropertyValue(attributes.getProperty(ATTRIBUTE_LEVEL), attributes.getProperty(ATTRIBUTE_NAME));\r\n String expected = attributes.getProperty(ATTRIBUTE_VALUE);\r\n\r\n if (value == null)\r\n {\r\n value = attributes.getProperty(ATTRIBUTE_DEFAULT);\r\n }\r\n if (expected.equals(value))\r\n {\r\n generate(template);\r\n }\r\n }", "synchronized void storeUninstallTimestamp() {\n\n if (!this.belowMemThreshold()) {\n getConfigLogger().verbose(\"There is not enough space left on the device to store data, data discarded\");\n return ;\n }\n final String tableName = Table.UNINSTALL_TS.getName();\n\n try {\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n final ContentValues cv = new ContentValues();\n cv.put(KEY_CREATED_AT, System.currentTimeMillis());\n db.insert(tableName, null, cv);\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Error adding data to table \" + tableName + \" Recreating DB\");\n dbHelper.deleteDatabase();\n } finally {\n dbHelper.close();\n }\n\n }" ]
Measure all children from container if needed @param measuredChildren the list of measured children measuredChildren list can be passed as null if it's not needed to create the list of the measured items @return true if the layout was recalculated, otherwise - false
[ "public boolean measureAll(List<Widget> measuredChildren) {\n boolean changed = false;\n for (int i = 0; i < mContainer.size(); ++i) {\n\n if (!isChildMeasured(i)) {\n Widget child = measureChild(i, false);\n if (child != null) {\n if (measuredChildren != null) {\n measuredChildren.add(child);\n }\n changed = true;\n }\n }\n }\n if (changed) {\n postMeasurement();\n }\n return changed;\n }" ]
[ "void setState(final WidgetState.State state) {\n Log.d(TAG, \"setState(%s): state is %s, setting to %s\", mWidget.getName(), mState, state);\n if (state != mState) {\n final WidgetState.State nextState = getNextState(state);\n Log.d(TAG, \"setState(%s): next state '%s'\", mWidget.getName(), nextState);\n if (nextState != mState) {\n Log.d(TAG, \"setState(%s): setting state to '%s'\", mWidget.getName(), nextState);\n setCurrentState(false);\n mState = nextState;\n setCurrentState(true);\n }\n }\n }", "public String getArtifactLastVersion(final String gavc) {\n final List<String> versions = getArtifactVersions(gavc);\n\n final VersionsHandler versionHandler = new VersionsHandler(repositoryHandler);\n final String viaCompare = versionHandler.getLastVersion(versions);\n\n if (viaCompare != null) {\n return viaCompare;\n }\n\n //\n // These versions cannot be compared\n // Let's use the Collection.max() method by default, so goingo for a fallback\n // mechanism.\n //\n LOG.info(\"The versions cannot be compared\");\n return Collections.max(versions);\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 ArrayList getFields(String fieldNames) throws NoSuchFieldException\r\n {\r\n ArrayList result = new ArrayList();\r\n FieldDescriptorDef fieldDef;\r\n String name;\r\n\r\n for (CommaListIterator it = new CommaListIterator(fieldNames); it.hasNext();)\r\n {\r\n name = it.getNext();\r\n fieldDef = getField(name);\r\n if (fieldDef == null)\r\n {\r\n throw new NoSuchFieldException(name);\r\n }\r\n result.add(fieldDef);\r\n }\r\n return result;\r\n }", "private boolean pathMatches(Path path, SquigglyContext context) {\n List<SquigglyNode> nodes = context.getNodes();\n Set<String> viewStack = null;\n SquigglyNode viewNode = null;\n\n int pathSize = path.getElements().size();\n int lastIdx = pathSize - 1;\n\n for (int i = 0; i < pathSize; i++) {\n PathElement element = path.getElements().get(i);\n\n if (viewNode != null && !viewNode.isSquiggly()) {\n Class beanClass = element.getBeanClass();\n\n if (beanClass != null && !Map.class.isAssignableFrom(beanClass)) {\n Set<String> propertyNames = getPropertyNamesFromViewStack(element, viewStack);\n\n if (!propertyNames.contains(element.getName())) {\n return false;\n }\n }\n\n } else if (nodes.isEmpty()) {\n return false;\n } else {\n\n SquigglyNode match = findBestSimpleNode(element, nodes);\n\n if (match == null) {\n match = findBestViewNode(element, nodes);\n\n if (match != null) {\n viewNode = match;\n viewStack = addToViewStack(viewStack, viewNode);\n }\n } else if (match.isAnyShallow()) {\n viewNode = match;\n } else if (match.isAnyDeep()) {\n return true;\n }\n\n if (match == null) {\n if (isJsonUnwrapped(element)) {\n continue;\n }\n\n return false;\n }\n\n if (match.isNegated()) {\n return false;\n }\n\n nodes = match.getChildren();\n\n if (i < lastIdx && nodes.isEmpty() && !match.isEmptyNested() && SquigglyConfig.isFilterImplicitlyIncludeBaseFields()) {\n nodes = BASE_VIEW_NODES;\n }\n }\n }\n\n return true;\n }", "public BoxAPIResponse send(ProgressListener listener) {\n if (this.api == null) {\n this.backoffCounter.reset(BoxGlobalSettings.getMaxRequestAttempts());\n } else {\n this.backoffCounter.reset(this.api.getMaxRequestAttempts());\n }\n\n while (this.backoffCounter.getAttemptsRemaining() > 0) {\n try {\n return this.trySend(listener);\n } catch (BoxAPIException apiException) {\n if (!this.backoffCounter.decrement() || !isResponseRetryable(apiException.getResponseCode())) {\n throw apiException;\n }\n\n try {\n this.resetBody();\n } catch (IOException ioException) {\n throw apiException;\n }\n\n try {\n this.backoffCounter.waitBackoff();\n } catch (InterruptedException interruptedException) {\n Thread.currentThread().interrupt();\n throw apiException;\n }\n }\n }\n\n throw new RuntimeException();\n }", "private <T> CoreRemoteMongoCollection<T> getRemoteCollection(\n final MongoNamespace namespace,\n final Class<T> resultClass\n ) {\n return remoteClient\n .getDatabase(namespace.getDatabaseName())\n .getCollection(namespace.getCollectionName(), resultClass);\n }", "public static boolean isLogDownloadAvailable(CliGuiContext cliGuiCtx) {\n ModelNode readOps = null;\n try {\n readOps = cliGuiCtx.getExecutor().doCommand(\"/subsystem=logging:read-children-types\");\n } catch (CommandFormatException | IOException e) {\n return false;\n }\n if (!readOps.get(\"result\").isDefined()) return false;\n for (ModelNode op: readOps.get(\"result\").asList()) {\n if (\"log-file\".equals(op.asString())) return true;\n }\n return false;\n }", "static Type parseType(String value, ResourceLoader resourceLoader) {\n value = value.trim();\n // Wildcards\n if (value.equals(WILDCARD)) {\n return WildcardTypeImpl.defaultInstance();\n }\n if (value.startsWith(WILDCARD_EXTENDS)) {\n Type upperBound = parseType(value.substring(WILDCARD_EXTENDS.length(), value.length()), resourceLoader);\n if (upperBound == null) {\n return null;\n }\n return WildcardTypeImpl.withUpperBound(upperBound);\n }\n if (value.startsWith(WILDCARD_SUPER)) {\n Type lowerBound = parseType(value.substring(WILDCARD_SUPER.length(), value.length()), resourceLoader);\n if (lowerBound == null) {\n return null;\n }\n return WildcardTypeImpl.withLowerBound(lowerBound);\n }\n // Array\n if (value.contains(ARRAY)) {\n Type componentType = parseType(value.substring(0, value.indexOf(ARRAY)), resourceLoader);\n if (componentType == null) {\n return null;\n }\n return new GenericArrayTypeImpl(componentType);\n }\n int chevLeft = value.indexOf(CHEVRONS_LEFT);\n String rawValue = chevLeft < 0 ? value : value.substring(0, chevLeft);\n Class<?> rawRequiredType = tryLoadClass(rawValue, resourceLoader);\n if (rawRequiredType == null) {\n return null;\n }\n if (rawRequiredType.getTypeParameters().length == 0) {\n return rawRequiredType;\n }\n // Parameterized type\n int chevRight = value.lastIndexOf(CHEVRONS_RIGHT);\n if (chevRight < 0) {\n return null;\n }\n List<String> parts = split(value.substring(chevLeft + 1, chevRight), ',', CHEVRONS_LEFT.charAt(0), CHEVRONS_RIGHT.charAt(0));\n Type[] typeParameters = new Type[parts.size()];\n for (int i = 0; i < typeParameters.length; i++) {\n Type typeParam = parseType(parts.get(i), resourceLoader);\n if (typeParam == null) {\n return null;\n }\n typeParameters[i] = typeParam;\n }\n return new ParameterizedTypeImpl(rawRequiredType, typeParameters);\n }" ]
Returns an array of the enabled endpoints as Integer IDs @param pathId ID of path @param clientUUID UUID of client @param filters If supplied, only endpoints ending with values in filters are returned @return Collection of endpoints @throws Exception exception
[ "public List<EnabledEndpoint> getEnabledEndpoints(int pathId, String clientUUID, String[] filters) throws Exception {\n ArrayList<EnabledEndpoint> enabledOverrides = new ArrayList<EnabledEndpoint>();\n PreparedStatement query = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n query = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \"=?\" +\n \" AND \" + Constants.GENERIC_CLIENT_UUID + \"=?\" +\n \" ORDER BY \" + Constants.ENABLED_OVERRIDES_PRIORITY\n );\n query.setInt(1, pathId);\n query.setString(2, clientUUID);\n results = query.executeQuery();\n\n while (results.next()) {\n EnabledEndpoint endpoint = this.getPartialEnabledEndpointFromResultset(results);\n com.groupon.odo.proxylib.models.Method m = PathOverrideService.getInstance().getMethodForOverrideId(endpoint.getOverrideId());\n\n // this is an errant entry.. perhaps a method got deleted from a plugin\n // we'll also remove it from the endpoint\n if (m == null) {\n PathOverrideService.getInstance().removeOverride(endpoint.getOverrideId());\n continue;\n }\n\n // check filters and see if any match\n boolean addOverride = false;\n if (filters != null) {\n for (String filter : filters) {\n if (m.getMethodType().endsWith(filter)) {\n addOverride = true;\n break;\n }\n }\n } else {\n // if there are no filters then we assume that the requester wants all enabled overrides\n addOverride = true;\n }\n\n if (addOverride) {\n enabledOverrides.add(endpoint);\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n\n // now go through the ArrayList and get the method for all of the endpoints\n // have to do this so we don't have overlapping SQL queries\n ArrayList<EnabledEndpoint> enabledOverridesWithMethods = new ArrayList<EnabledEndpoint>();\n for (EnabledEndpoint endpoint : enabledOverrides) {\n if (endpoint.getOverrideId() >= 0) {\n com.groupon.odo.proxylib.models.Method m = PathOverrideService.getInstance().getMethodForOverrideId(endpoint.getOverrideId());\n endpoint.setMethodInformation(m);\n }\n enabledOverridesWithMethods.add(endpoint);\n }\n\n return enabledOverridesWithMethods;\n }" ]
[ "public String p(double value ) {\n return UtilEjml.fancyString(value,format,false,length,significant);\n }", "public void setStatusBarMessage(final String message)\r\n {\r\n // Guaranteed to return a non-null array\r\n Object[] listeners = listenerList.getListenerList();\r\n // Process the listeners last to first, notifying\r\n // those that are interested in this event\r\n for (int i = listeners.length-2; i>=0; i-=2) {\r\n if (listeners[i]==StatusMessageListener.class) \r\n {\r\n ((StatusMessageListener)listeners[i+1]).statusMessageReceived(message);\r\n } \r\n } \r\n }", "public static int restrictRange(int value, int min, int max)\n {\n return Math.min((Math.max(value, min)), max);\n }", "protected void handleExceptions(MessageEvent messageEvent, Exception exception) {\n logger.error(\"Unknown exception. Internal Server Error.\", exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.INTERNAL_SERVER_ERROR,\n \"Internal Server Error\");\n }", "public void setOnKeyboardDone(final IntlPhoneInputListener listener) {\n mPhoneEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n @Override\n public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {\n if (actionId == EditorInfo.IME_ACTION_DONE) {\n listener.done(IntlPhoneInput.this, isValid());\n }\n return false;\n }\n });\n }", "private static Set<ProjectModel> getAllApplications(GraphContext graphContext)\n {\n Set<ProjectModel> apps = new HashSet<>();\n Iterable<ProjectModel> appProjects = graphContext.findAll(ProjectModel.class);\n for (ProjectModel appProject : appProjects)\n apps.add(appProject);\n return apps;\n }", "public static base_response add(nitro_service client, authenticationradiusaction resource) throws Exception {\n\t\tauthenticationradiusaction addresource = new authenticationradiusaction();\n\t\taddresource.name = resource.name;\n\t\taddresource.serverip = resource.serverip;\n\t\taddresource.serverport = resource.serverport;\n\t\taddresource.authtimeout = resource.authtimeout;\n\t\taddresource.radkey = resource.radkey;\n\t\taddresource.radnasip = resource.radnasip;\n\t\taddresource.radnasid = resource.radnasid;\n\t\taddresource.radvendorid = resource.radvendorid;\n\t\taddresource.radattributetype = resource.radattributetype;\n\t\taddresource.radgroupsprefix = resource.radgroupsprefix;\n\t\taddresource.radgroupseparator = resource.radgroupseparator;\n\t\taddresource.passencoding = resource.passencoding;\n\t\taddresource.ipvendorid = resource.ipvendorid;\n\t\taddresource.ipattributetype = resource.ipattributetype;\n\t\taddresource.accounting = resource.accounting;\n\t\taddresource.pwdvendorid = resource.pwdvendorid;\n\t\taddresource.pwdattributetype = resource.pwdattributetype;\n\t\taddresource.defaultauthenticationgroup = resource.defaultauthenticationgroup;\n\t\taddresource.callingstationid = resource.callingstationid;\n\t\treturn addresource.add_resource(client);\n\t}", "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}", "@Override\n public Symmetry454Date dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }" ]
Gets the name of the vertex attribute containing the texture coordinates for the named texture. @param texName name of texture @return name of texture coordinate vertex attribute
[ "public String getTexCoordAttr(String texName)\n {\n GVRTexture tex = textures.get(texName);\n if (tex != null)\n {\n return tex.getTexCoordAttr();\n }\n return null;\n }" ]
[ "protected int complete(CommandContext ctx, ParsedCommandLine parsedCmd, OperationCandidatesProvider candidatesProvider, final String buffer, int cursor, List<String> candidates) {\n\n if(parsedCmd.isRequestComplete()) {\n return -1;\n }\n\n // Headers completion\n if(parsedCmd.endsOnHeaderListStart() || parsedCmd.hasHeaders()) {\n return completeHeaders(ctx, parsedCmd, candidatesProvider, buffer, cursor, candidates);\n }\n\n // Completed.\n if(parsedCmd.endsOnPropertyListEnd()) {\n return buffer.length();\n }\n\n // Complete properties\n if (parsedCmd.hasProperties() || parsedCmd.endsOnPropertyListStart()\n || parsedCmd.endsOnNotOperator()) {\n return completeProperties(ctx, parsedCmd, candidatesProvider, buffer, candidates);\n }\n\n // Complete Operation name\n if (parsedCmd.hasOperationName() || parsedCmd.endsOnAddressOperationNameSeparator()) {\n return completeOperationName(ctx, parsedCmd, candidatesProvider, buffer, candidates);\n }\n\n // Finally Complete address\n return completeAddress(ctx, parsedCmd, candidatesProvider, buffer, candidates);\n }", "public static TextEncryptor queryableText(CharSequence password, CharSequence salt) {\n\t\treturn new HexEncodingTextEncryptor(new AndroidAesBytesEncryptor(password.toString(), salt, AndroidKeyGenerators.shared(16)));\n\t}", "public ItemRequest<Tag> findById(String tag) {\n \n String path = String.format(\"/tags/%s\", tag);\n return new ItemRequest<Tag>(this, Tag.class, path, \"GET\");\n }", "public void setAmbientIntensity(float r, float g, float b, float a) {\n setVec4(\"ambient_intensity\", r, g, b, a);\n }", "@RequestMapping(value=\"/{subscription}\", method=GET, params=\"hub.mode=subscribe\")\n\tpublic @ResponseBody String verifySubscription(\n\t\t\t@PathVariable(\"subscription\") String subscription,\n\t\t\t@RequestParam(\"hub.challenge\") String challenge,\n\t\t\t@RequestParam(\"hub.verify_token\") String verifyToken) {\n\t\tlogger.debug(\"Received subscription verification request for '\" + subscription + \"'.\");\n\t\treturn tokens.containsKey(subscription) && tokens.get(subscription).equals(verifyToken) ? challenge : \"\";\n\t}", "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 boolean inArea(Point point, Rect area, float offsetRatio) {\n int offset = (int) (area.width() * offsetRatio);\n return point.x >= area.left - offset && point.x <= area.right + offset &&\n point.y >= area.top - offset && point.y <= area.bottom + offset;\n }", "public GVRShader getTemplate(GVRContext ctx)\n {\n if (mShaderTemplate == null)\n {\n mShaderTemplate = makeTemplate(ID, ctx);\n ctx.getShaderManager().addShaderID(this);\n }\n return mShaderTemplate;\n }", "public static base_response unset(nitro_service client, coparameter resource, String[] args) throws Exception{\n\t\tcoparameter unsetresource = new coparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}" ]
Return true if the connection being released is the one that has been saved.
[ "protected boolean isSavedConnection(DatabaseConnection connection) {\n\t\tNestedConnection currentSaved = specialConnection.get();\n\t\tif (currentSaved == null) {\n\t\t\treturn false;\n\t\t} else if (currentSaved.connection == connection) {\n\t\t\t// ignore the release when we have a saved connection\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}" ]
[ "private void checkCollectionForeignkeys(ModelDef modelDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n ClassDescriptorDef classDef;\r\n CollectionDescriptorDef collDef;\r\n\r\n for (Iterator it = modelDef.getClasses(); it.hasNext();)\r\n {\r\n classDef = (ClassDescriptorDef)it.next();\r\n for (Iterator collIt = classDef.getCollections(); collIt.hasNext();)\r\n {\r\n collDef = (CollectionDescriptorDef)collIt.next();\r\n if (!collDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))\r\n {\r\n if (collDef.hasProperty(PropertyHelper.OJB_PROPERTY_INDIRECTION_TABLE))\r\n {\r\n checkIndirectionTable(modelDef, collDef);\r\n }\r\n else\r\n { \r\n checkCollectionForeignkeys(modelDef, collDef);\r\n }\r\n }\r\n }\r\n }\r\n }", "private static void writeCharSequence(CharSequence seq, CharBuf buffer) {\n if (seq.length() > 0) {\n buffer.addJsonEscapedString(seq.toString());\n } else {\n buffer.addChars(EMPTY_STRING_CHARS);\n }\n }", "@NonNull\n @Override\n public Loader<SortedList<File>> getLoader() {\n return new AsyncTaskLoader<SortedList<File>>(getActivity()) {\n\n FileObserver fileObserver;\n\n @Override\n public SortedList<File> loadInBackground() {\n File[] listFiles = mCurrentPath.listFiles();\n final int initCap = listFiles == null ? 0 : listFiles.length;\n\n SortedList<File> files = new SortedList<>(File.class, new SortedListAdapterCallback<File>(getDummyAdapter()) {\n @Override\n public int compare(File lhs, File rhs) {\n return compareFiles(lhs, rhs);\n }\n\n @Override\n public boolean areContentsTheSame(File file, File file2) {\n return file.getAbsolutePath().equals(file2.getAbsolutePath()) && (file.isFile() == file2.isFile());\n }\n\n @Override\n public boolean areItemsTheSame(File file, File file2) {\n return areContentsTheSame(file, file2);\n }\n }, initCap);\n\n\n files.beginBatchedUpdates();\n if (listFiles != null) {\n for (java.io.File f : listFiles) {\n if (isItemVisible(f)) {\n files.add(f);\n }\n }\n }\n files.endBatchedUpdates();\n\n return files;\n }\n\n /**\n * Handles a request to start the Loader.\n */\n @Override\n protected void onStartLoading() {\n super.onStartLoading();\n\n // handle if directory does not exist. Fall back to root.\n if (mCurrentPath == null || !mCurrentPath.isDirectory()) {\n mCurrentPath = getRoot();\n }\n\n // Start watching for changes\n fileObserver = new FileObserver(mCurrentPath.getPath(),\n FileObserver.CREATE |\n FileObserver.DELETE\n | FileObserver.MOVED_FROM | FileObserver.MOVED_TO\n ) {\n\n @Override\n public void onEvent(int event, String path) {\n // Reload\n onContentChanged();\n }\n };\n fileObserver.startWatching();\n\n forceLoad();\n }\n\n /**\n * Handles a request to completely reset the Loader.\n */\n @Override\n protected void onReset() {\n super.onReset();\n\n // Stop watching\n if (fileObserver != null) {\n fileObserver.stopWatching();\n fileObserver = null;\n }\n }\n };\n }", "public void growMaxColumns( int desiredColumns , boolean preserveValue ) {\n if( col_idx.length < desiredColumns+1 ) {\n int[] c = new int[ desiredColumns+1 ];\n if( preserveValue )\n System.arraycopy(col_idx,0,c,0,col_idx.length);\n col_idx = c;\n }\n }", "public void applyXMLDSigAsFirstChild (@Nonnull final PrivateKey aPrivateKey,\n @Nonnull final X509Certificate aCertificate,\n @Nonnull final Document aDocument) throws Exception\n {\n ValueEnforcer.notNull (aPrivateKey, \"privateKey\");\n ValueEnforcer.notNull (aCertificate, \"certificate\");\n ValueEnforcer.notNull (aDocument, \"document\");\n ValueEnforcer.notNull (aDocument.getDocumentElement (), \"Document is missing a document element\");\n if (aDocument.getDocumentElement ().getChildNodes ().getLength () == 0)\n throw new IllegalArgumentException (\"Document element has no children!\");\n\n // Check that the document does not contain another Signature element\n final NodeList aNodeList = aDocument.getElementsByTagNameNS (XMLSignature.XMLNS, XMLDSigSetup.ELEMENT_SIGNATURE);\n if (aNodeList.getLength () > 0)\n throw new IllegalArgumentException (\"Document already contains an XMLDSig Signature element!\");\n\n // Create the XMLSignature, but don't sign it yet.\n final XMLSignature aXMLSignature = createXMLSignature (aCertificate);\n\n // Create a DOMSignContext and specify the RSA PrivateKey and\n // location of the resulting XMLSignature's parent element.\n // -> The signature is always the first child element of the document\n // element for ebInterface\n final DOMSignContext aDOMSignContext = new DOMSignContext (aPrivateKey,\n aDocument.getDocumentElement (),\n aDocument.getDocumentElement ().getFirstChild ());\n\n // The namespace prefix to be used for the signed XML\n aDOMSignContext.setDefaultNamespacePrefix (DEFAULT_NS_PREFIX);\n\n // Marshal, generate, and sign the enveloped signature.\n aXMLSignature.sign (aDOMSignContext);\n }", "public synchronized void resumeControlPoint(final String entryPoint) {\n for (ControlPoint ep : entryPoints.values()) {\n if (ep.getEntryPoint().equals(entryPoint)) {\n ep.resume();\n }\n }\n }", "public ArrayList<IntPoint> process(ImageSource fastBitmap) {\r\n //FastBitmap l = new FastBitmap(fastBitmap);\r\n if (points == null) {\r\n apply(fastBitmap);\r\n }\r\n\r\n int width = fastBitmap.getWidth();\r\n int height = fastBitmap.getHeight();\r\n points = new ArrayList<IntPoint>();\r\n\r\n if (fastBitmap.isGrayscale()) {\r\n for (int x = 0; x < height; x++) {\r\n for (int y = 0; y < width; y++) {\r\n if (fastBitmap.getRGB(y, x) == 255) points.add(new IntPoint(y, x));\r\n }\r\n }\r\n } else {\r\n for (int x = 0; x < height; x++) {\r\n for (int y = 0; y < width; y++) {\r\n // TODO Check for green and blue?\r\n if (fastBitmap.getR(y, x) == 255) points.add(new IntPoint(y, x));\r\n }\r\n }\r\n }\r\n\r\n return points;\r\n }", "public static void acceptsJson(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_J, OPT_JSON),\n \"fetch key/entry by key value of json type\")\n .withRequiredArg()\n .describedAs(\"key-list\")\n .withValuesSeparatedBy(',')\n .ofType(String.class);\n }", "private void addAllProjectModels(ApplicationReportIndexModel navIdx, ProjectModel projectModel)\n {\n navIdx.addProjectModel(projectModel);\n for (ProjectModel childProject : projectModel.getChildProjects())\n {\n if (!Iterators.asSet(navIdx.getProjectModels()).contains(childProject))\n addAllProjectModels(navIdx, childProject);\n }\n }" ]
Set the query parameter values overriding all existing query values for the same parameter. If no values are given, the query parameter is removed. @param name the query parameter name @param values the query parameter values @return this UriComponentsBuilder
[ "public UriComponentsBuilder replaceQueryParam(String name, Object... values) {\n\t\tAssert.notNull(name, \"'name' must not be null\");\n\t\tthis.queryParams.remove(name);\n\t\tif (!ObjectUtils.isEmpty(values)) {\n\t\t\tqueryParam(name, values);\n\t\t}\n\t\tresetSchemeSpecificPart();\n\t\treturn this;\n\t}" ]
[ "public static ModelNode validateRequest(CommandContext ctx, ModelNode request) throws CommandFormatException {\n\n final Set<String> keys = request.keys();\n if (keys.size() == 2) { // no props\n return null;\n }\n ModelNode outcome = (ModelNode) ctx.get(Scope.REQUEST, DESCRIPTION_RESPONSE);\n if (outcome == null) {\n outcome = retrieveDescription(ctx, request, true);\n if (outcome == null) {\n return null;\n } else {\n ctx.set(Scope.REQUEST, DESCRIPTION_RESPONSE, outcome);\n }\n }\n if(!outcome.has(Util.RESULT)) {\n throw new CommandFormatException(\"Failed to perform \" + Util.READ_OPERATION_DESCRIPTION + \" to validate the request: result is not available.\");\n }\n\n final String operationName = request.get(Util.OPERATION).asString();\n\n final ModelNode result = outcome.get(Util.RESULT);\n final Set<String> definedProps = result.hasDefined(Util.REQUEST_PROPERTIES) ? result.get(Util.REQUEST_PROPERTIES).keys() : Collections.emptySet();\n if(definedProps.isEmpty()) {\n if(!(keys.size() == 3 && keys.contains(Util.OPERATION_HEADERS))) {\n throw new CommandFormatException(\"Operation '\" + operationName + \"' does not expect any property.\");\n }\n } else {\n int skipped = 0;\n for(String prop : keys) {\n if(skipped < 2 && (prop.equals(Util.ADDRESS) || prop.equals(Util.OPERATION))) {\n ++skipped;\n continue;\n }\n if(!definedProps.contains(prop)) {\n if(!Util.OPERATION_HEADERS.equals(prop)) {\n throw new CommandFormatException(\"'\" + prop + \"' is not found among the supported properties: \" + definedProps);\n }\n }\n }\n }\n return outcome;\n }", "private void processCalendarData(ProjectCalendar calendar, List<ResultSetRow> calendarData)\n {\n for (ResultSetRow row : calendarData)\n {\n processCalendarData(calendar, row);\n }\n }", "public byte byteAt(int i) {\n\n if (i < 0) {\n throw new IndexOutOfBoundsException(\"i < 0, \" + i);\n }\n\n if (i >= length) {\n throw new IndexOutOfBoundsException(\"i >= length, \" + i + \" >= \" + length);\n }\n\n return data[offset + i];\n }", "public static scala.collection.Iterable linkedListToScalaIterable(LinkedList<?> linkedList) {\n return JavaConverters.asScalaIterableConverter(linkedList).asScala();\n }", "public boolean detectSonyMylo() {\r\n\r\n if ((userAgent.indexOf(manuSony) != -1)\r\n && ((userAgent.indexOf(qtembedded) != -1) || (userAgent.indexOf(mylocom2) != -1))) {\r\n return true;\r\n }\r\n return false;\r\n }", "private int slopSize(Versioned<Slop> slopVersioned) {\n int nBytes = 0;\n Slop slop = slopVersioned.getValue();\n nBytes += slop.getKey().length();\n nBytes += ((VectorClock) slopVersioned.getVersion()).sizeInBytes();\n switch(slop.getOperation()) {\n case PUT: {\n nBytes += slop.getValue().length;\n break;\n }\n case DELETE: {\n break;\n }\n default:\n logger.error(\"Unknown slop operation: \" + slop.getOperation());\n }\n return nBytes;\n }", "@Override\n public Object[] getAgentPlans(String agent_name, Connector connector) {\n // Not supported in JADE\n connector.getLogger().warning(\"Non suported method for Jade Platform. There is no plans in Jade platform.\");\n throw new java.lang.UnsupportedOperationException(\"Non suported method for Jade Platform. There is no extra properties.\");\n }", "protected void setProperty(String propertyName, JavascriptObject propertyValue) {\n jsObject.setMember(propertyName, propertyValue.getJSObject());\n }", "private String filterTag(String tag) {\r\n\t AttributeValues answerAV = TagSet.getTagSet().fromTag(tag);\r\n\t answerAV.removeNonlexicalAttributes();\r\n\t return TagSet.getTagSet().toTag(answerAV);\r\n }" ]
Check real offset. @return the boolean
[ "final public Boolean checkRealOffset() {\n if ((tokenRealOffset == null) || !provideRealOffset) {\n return false;\n } else if (tokenOffset == null) {\n return true;\n } else if (tokenOffset.getStart() == tokenRealOffset.getStart()\n && tokenOffset.getEnd() == tokenRealOffset.getEnd()) {\n return false;\n } else {\n return true;\n }\n }" ]
[ "private static void checkPreconditions(final String dateFormat, final Locale locale) {\n\t\tif( dateFormat == null ) {\n\t\t\tthrow new NullPointerException(\"dateFormat should not be null\");\n\t\t} else if( locale == null ) {\n\t\t\tthrow new NullPointerException(\"locale should not be null\");\n\t\t}\n\t}", "public static Optional<Variable> freshBuilder(SourceBuilder code, Datatype datatype) {\n if (!datatype.getBuilderFactory().isPresent()) {\n return Optional.empty();\n }\n return Optional.of(code.scope().computeIfAbsent(Declaration.FRESH_BUILDER, () -> {\n Variable defaults = new Variable(\"defaults\");\n code.addLine(\"%s %s = %s;\",\n datatype.getGeneratedBuilder(),\n defaults,\n datatype.getBuilderFactory().get()\n .newBuilder(datatype.getBuilder(), TypeInference.INFERRED_TYPES));\n return defaults;\n }));\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}", "public synchronized void abortTransaction() throws TransactionNotInProgressException\n {\n if(isInTransaction())\n {\n fireBrokerEvent(BEFORE_ROLLBACK_EVENT);\n setInTransaction(false);\n clearRegistrationLists();\n referencesBroker.removePrefetchingListeners();\n /*\n arminw:\n check if we in local tx, before do local rollback\n Necessary, because ConnectionManager may do a rollback by itself\n or in managed environments the used connection is already be closed\n */\n if(connectionManager.isInLocalTransaction()) this.connectionManager.localRollback();\n fireBrokerEvent(AFTER_ROLLBACK_EVENT);\n }\n }", "@SuppressWarnings(\"unchecked\")\n public static <E> String serialize(E object, ParameterizedType<E> parameterizedType) throws IOException {\n return mapperFor(parameterizedType).serialize(object);\n }", "protected static boolean numericEquals(Field vector1, Field vector2) {\n\t\tif (vector1.size() != vector2.size())\n\t\t\treturn false;\n\t\tif (vector1.isEmpty())\n\t\t\treturn true;\n\n\t\tIterator<Object> it1 = vector1.iterator();\n\t\tIterator<Object> it2 = vector2.iterator();\n\n\t\twhile (it1.hasNext()) {\n\t\t\tObject obj1 = it1.next();\n\t\t\tObject obj2 = it2.next();\n\n\t\t\tif (!(obj1 instanceof Number && obj2 instanceof Number))\n\t\t\t\treturn false;\n\n\t\t\tif (((Number) obj1).doubleValue() != ((Number) obj2).doubleValue())\n\t\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}", "public static rsskeytype get(nitro_service service) throws Exception{\n\t\trsskeytype obj = new rsskeytype();\n\t\trsskeytype[] response = (rsskeytype[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "private void writeTasks() throws IOException\n {\n writeAttributeTypes(\"task_types\", TaskField.values());\n\n m_writer.writeStartList(\"tasks\");\n for (Task task : m_projectFile.getChildTasks())\n {\n writeTask(task);\n }\n m_writer.writeEndList();\n }", "public static int color(ColorHolder colorHolder, Context ctx) {\n if (colorHolder == null) {\n return 0;\n } else {\n return colorHolder.color(ctx);\n }\n }" ]
This static method calculated the vega of a call option under a Black-Scholes model @param initialStockValue The initial value of the underlying, i.e., the spot. @param riskFreeRate The risk free rate of the bank account numerarie. @param volatility The Black-Scholes volatility. @param optionMaturity The option maturity T. @param optionStrike The option strike. @return The vega of the option
[ "public static double blackScholesOptionTheta(\n\t\t\tdouble initialStockValue,\n\t\t\tdouble riskFreeRate,\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike)\n\t{\n\t\tif(optionStrike <= 0.0 || optionMaturity <= 0.0)\n\t\t{\n\t\t\t// The Black-Scholes model does not consider it being an option\n\t\t\treturn 0.0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Calculate theta\n\t\t\tdouble dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));\n\t\t\tdouble dMinus = dPlus - volatility * Math.sqrt(optionMaturity);\n\n\t\t\tdouble theta = volatility * Math.exp(-0.5*dPlus*dPlus) / Math.sqrt(2.0 * Math.PI) / Math.sqrt(optionMaturity) / 2 * initialStockValue + riskFreeRate * optionStrike * Math.exp(-riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus);\n\n\t\t\treturn theta;\n\t\t}\n\t}" ]
[ "public 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 static String objectToColumnString(Object object, String delimiter, String[] fieldNames)\r\n throws IllegalAccessException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException\r\n {\r\n StringBuilder sb = new StringBuilder();\r\n for (int i = 0; i < fieldNames.length; i++) {\r\n if (sb.length() > 0) {\r\n sb.append(delimiter);\r\n }\r\n try {\r\n Field field = object.getClass().getDeclaredField(fieldNames[i]);\r\n sb.append(field.get(object)) ;\r\n } catch (IllegalAccessException ex) {\r\n Method method = object.getClass().getDeclaredMethod(\"get\" + StringUtils.capitalize(fieldNames[i]));\r\n sb.append(method.invoke(object));\r\n }\r\n }\r\n return sb.toString();\r\n }", "private static boolean isPredefinedConstant(Expression expression) {\r\n if (expression instanceof PropertyExpression) {\r\n Expression object = ((PropertyExpression) expression).getObjectExpression();\r\n Expression property = ((PropertyExpression) expression).getProperty();\r\n\r\n if (object instanceof VariableExpression) {\r\n List<String> predefinedConstantNames = PREDEFINED_CONSTANTS.get(((VariableExpression) object).getName());\r\n if (predefinedConstantNames != null && predefinedConstantNames.contains(property.getText())) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n }", "@Override\n\tpublic Result getResult() throws Exception {\n\t\tResult returnResult = result;\n\n\t\t// If we've chained to other Actions, we need to find the last result\n\t\twhile (returnResult instanceof ActionChainResult) {\n\t\t\tActionProxy aProxy = ((ActionChainResult) returnResult).getProxy();\n\n\t\t\tif (aProxy != null) {\n\t\t\t\tResult proxyResult = aProxy.getInvocation().getResult();\n\n\t\t\t\tif ((proxyResult != null) && (aProxy.getExecuteResult())) {\n\t\t\t\t\treturnResult = proxyResult;\n\t\t\t\t} else {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn returnResult;\n\t}", "public void rollback() throws GitAPIException {\n try (Git git = getGit()) {\n git.reset().setMode(ResetCommand.ResetType.HARD).setRef(HEAD).call();\n }\n }", "public static boolean setCustomResponseForDefaultClient(String profileName, String pathName, String customData) {\n try {\n return setCustomForDefaultClient(profileName, pathName, true, customData);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\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 BoxConfig readFrom(Reader reader) throws IOException {\n JsonObject config = JsonObject.readFrom(reader);\n JsonObject settings = (JsonObject) config.get(\"boxAppSettings\");\n String clientId = settings.get(\"clientID\").asString();\n String clientSecret = settings.get(\"clientSecret\").asString();\n JsonObject appAuth = (JsonObject) settings.get(\"appAuth\");\n String publicKeyId = appAuth.get(\"publicKeyID\").asString();\n String privateKey = appAuth.get(\"privateKey\").asString();\n String passphrase = appAuth.get(\"passphrase\").asString();\n String enterpriseId = config.get(\"enterpriseID\").asString();\n return new BoxConfig(clientId, clientSecret, enterpriseId, publicKeyId, privateKey, passphrase);\n }", "public ValueContainer[] getKeyValues(ClassDescriptor cld, Identity oid, boolean convertToSql) throws PersistenceBrokerException\r\n {\r\n FieldDescriptor[] pkFields = cld.getPkFields();\r\n ValueContainer[] result = new ValueContainer[pkFields.length];\r\n Object[] pkValues = oid.getPrimaryKeyValues();\r\n\r\n try\r\n {\r\n for(int i = 0; i < result.length; i++)\r\n {\r\n FieldDescriptor fd = pkFields[i];\r\n Object cv = pkValues[i];\r\n if(convertToSql)\r\n {\r\n // BRJ : apply type and value mapping\r\n cv = fd.getFieldConversion().javaToSql(cv);\r\n }\r\n result[i] = new ValueContainer(cv, fd.getJdbcType());\r\n }\r\n }\r\n catch(Exception e)\r\n {\r\n throw new PersistenceBrokerException(\"Can't generate primary key values for given Identity \" + oid, e);\r\n }\r\n return result;\r\n }" ]
Creates the node corresponding to an entity. @param executionEngine the {@link GraphDatabaseService} used to run the query @param columnValues the values in {@link org.hibernate.ogm.model.key.spi.EntityKey#getColumnValues()} @return the corresponding node
[ "public Node insertEntity(GraphDatabaseService executionEngine, Object[] columnValues) {\n\t\tMap<String, Object> params = params( columnValues );\n\t\tResult result = executionEngine.execute( getCreateEntityQuery(), params );\n\t\treturn singleResult( result );\n\t}" ]
[ "public void deleteIndex(String indexName, String designDocId, String type) {\n assertNotEmpty(indexName, \"indexName\");\n assertNotEmpty(designDocId, \"designDocId\");\n assertNotNull(type, \"type\");\n if (!designDocId.startsWith(\"_design\")) {\n designDocId = \"_design/\" + designDocId;\n }\n URI uri = new DatabaseURIHelper(db.getDBUri()).path(\"_index\").path(designDocId)\n .path(type).path(indexName).build();\n InputStream response = null;\n try {\n HttpConnection connection = Http.DELETE(uri);\n response = client.couchDbClient.executeToInputStream(connection);\n getResponse(response, Response.class, client.getGson());\n } finally {\n close(response);\n }\n }", "public static <T> List<T> flatten(Collection<List<T>> nestedList) {\r\n List<T> result = new ArrayList<T>();\r\n for (List<T> list : nestedList) {\r\n result.addAll(list);\r\n }\r\n return result;\r\n }", "public Location getInfo(String placeId, String woeId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_INFO);\r\n\r\n if (placeId != null) {\r\n parameters.put(\"place_id\", placeId);\r\n }\r\n if (woeId != null) {\r\n parameters.put(\"woe_id\", woeId);\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 locationElement = response.getPayload();\r\n return parseLocation(locationElement);\r\n }", "public T copy() {\n T ret = createLike();\n ret.getMatrix().set(this.getMatrix());\n return ret;\n }", "private static String handleRichError(final Response response, final String body) {\n if (!response.getHeaders().containsKey(Headers.CONTENT_TYPE)\n || !response.getHeaders().get(Headers.CONTENT_TYPE).equals(ContentTypes.APPLICATION_JSON)) {\n return body;\n }\n\n final Document doc;\n try {\n doc = BsonUtils.parseValue(body, Document.class);\n } catch (Exception e) {\n return body;\n }\n\n if (!doc.containsKey(Fields.ERROR)) {\n return body;\n }\n final String errorMsg = doc.getString(Fields.ERROR);\n if (!doc.containsKey(Fields.ERROR_CODE)) {\n return errorMsg;\n }\n\n final String errorCode = doc.getString(Fields.ERROR_CODE);\n throw new StitchServiceException(errorMsg, StitchServiceErrorCode.fromCodeName(errorCode));\n }", "private List<UDFAssignmentType> writeUDFType(FieldTypeClass type, FieldContainer mpxj)\n {\n List<UDFAssignmentType> out = new ArrayList<UDFAssignmentType>();\n for (CustomField cf : m_sortedCustomFieldsList)\n {\n FieldType fieldType = cf.getFieldType();\n if (fieldType != null && type == fieldType.getFieldTypeClass())\n {\n Object value = mpxj.getCachedValue(fieldType);\n if (FieldTypeHelper.valueIsNotDefault(fieldType, value))\n {\n UDFAssignmentType udf = m_factory.createUDFAssignmentType();\n udf.setTypeObjectId(FieldTypeHelper.getFieldID(fieldType));\n setUserFieldValue(udf, fieldType.getDataType(), value);\n out.add(udf);\n }\n }\n }\n return out;\n }", "public static String getFilename(String path) throws IllegalArgumentException {\n if (Pattern.matches(sPatternUrl, path))\n return getURLFilename(path);\n\n return new File(path).getName();\n }", "public static 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 void deleteProduct(final String name) {\n final DbProduct dbProduct = getProduct(name);\n repositoryHandler.deleteProduct(dbProduct.getName());\n }" ]
Find out which method to call on the service bean.
[ "protected Method resolveTargetMethod(Message message,\n FieldDescriptor payloadField) {\n Method targetMethod = fieldToMethod.get(payloadField);\n\n if (targetMethod == null) {\n // look up and cache target method; this block is called only once\n // per target method, so synchronized is ok\n synchronized (this) {\n targetMethod = fieldToMethod.get(payloadField);\n if (targetMethod == null) {\n String name = payloadField.getName();\n for (Method method : service.getClass().getMethods()) {\n if (method.getName().equals(name)) {\n try {\n method.setAccessible(true);\n } catch (Exception ex) {\n log.log(Level.SEVERE,\"Error accessing RPC method\",ex);\n }\n\n targetMethod = method;\n fieldToMethod.put(payloadField, targetMethod);\n break;\n }\n }\n }\n }\n }\n\n if (targetMethod != null) {\n return targetMethod;\n } else {\n throw new RuntimeException(\"No matching method found by the name '\"\n + payloadField.getName() + \"'\");\n }\n }" ]
[ "public boolean matches(PathElement pe) {\n return pe.key.equals(key) && (isWildcard() || pe.value.equals(value));\n }", "public String getLinkColor(JSONObject jsonObject){\n if(jsonObject == null) return null;\n try {\n return jsonObject.has(\"color\") ? jsonObject.getString(\"color\") : \"\";\n } catch (JSONException e) {\n Logger.v(\"Unable to get Link Text Color with JSON - \"+e.getLocalizedMessage());\n return null;\n }\n }", "@Override\n public List<String> getDefaultProviderChain() {\n List<String> result = new ArrayList<>(Monetary.getRoundingProviderNames());\n Collections.sort(result);\n return result;\n }", "public static <T, ID> int dropTable(Dao<T, ID> dao, boolean ignoreErrors) throws SQLException {\n\t\tConnectionSource connectionSource = dao.getConnectionSource();\n\t\tClass<T> dataClass = dao.getDataClass();\n\t\tDatabaseType databaseType = connectionSource.getDatabaseType();\n\t\tif (dao instanceof BaseDaoImpl<?, ?>) {\n\t\t\treturn doDropTable(databaseType, connectionSource, ((BaseDaoImpl<?, ?>) dao).getTableInfo(), ignoreErrors);\n\t\t} else {\n\t\t\tTableInfo<T, ID> tableInfo = new TableInfo<T, ID>(databaseType, dataClass);\n\t\t\treturn doDropTable(databaseType, connectionSource, tableInfo, ignoreErrors);\n\t\t}\n\t}", "public PayloadBuilder customField(final String key, final Object value) {\n root.put(key, value);\n return this;\n }", "private Map<Integer, Integer> getNodeIdToZonePrimaryCount(Cluster cluster,\n StoreRoutingPlan storeRoutingPlan) {\n Map<Integer, Integer> nodeIdToZonePrimaryCount = Maps.newHashMap();\n for(Integer nodeId: cluster.getNodeIds()) {\n nodeIdToZonePrimaryCount.put(nodeId,\n storeRoutingPlan.getZonePrimaryPartitionIds(nodeId).size());\n }\n\n return nodeIdToZonePrimaryCount;\n }", "public final void notifyFooterItemRangeInserted(int positionStart, int itemCount) {\n int newHeaderItemCount = getHeaderItemCount();\n int newContentItemCount = getContentItemCount();\n int newFooterItemCount = getFooterItemCount();\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > newFooterItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for footer items [0 - \"\n + (newFooterItemCount - 1) + \"].\");\n }\n notifyItemRangeInserted(positionStart + newHeaderItemCount + newContentItemCount, itemCount);\n }", "public static double blackModelSwaptionValue(\n\t\t\tdouble forwardSwaprate,\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike,\n\t\t\tdouble swapAnnuity)\n\t{\n\t\t// May be interpreted as a special version of the Black-Scholes Formula\n\t\treturn AnalyticFormulas.blackScholesGeneralizedOptionValue(forwardSwaprate, volatility, optionMaturity, optionStrike, swapAnnuity);\n\t}", "protected VelocityContext createContext()\n {\n VelocityContext context = new VelocityContext();\n context.put(META_KEY, META);\n context.put(UTILS_KEY, UTILS);\n context.put(MESSAGES_KEY, MESSAGES);\n return context;\n }" ]
Runs Crawljax with the given configuration. @return The {@link CrawlSession} once the Crawl is done.
[ "@Override\n\tpublic CrawlSession call() {\n\t\tInjector injector = Guice.createInjector(new CoreModule(config));\n\t\tcontroller = injector.getInstance(CrawlController.class);\n\t\tCrawlSession session = controller.call();\n\t\treason = controller.getReason();\n\t\treturn session;\n\t}" ]
[ "@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 }", "public List<List<IN>> classify(String str) {\r\n ObjectBank<List<IN>> documents =\r\n makeObjectBankFromString(str, plainTextReaderAndWriter);\r\n List<List<IN>> result = new ArrayList<List<IN>>();\r\n\r\n for (List<IN> document : documents) {\r\n classify(document);\r\n\r\n List<IN> sentence = new ArrayList<IN>();\r\n for (IN wi : document) {\r\n // TaggedWord word = new TaggedWord(wi.word(), wi.answer());\r\n // sentence.add(word);\r\n sentence.add(wi);\r\n }\r\n result.add(sentence);\r\n }\r\n return result;\r\n }", "private void countPropertyMain(UsageStatistics usageStatistics,\n\t\t\tPropertyIdValue property, int count) {\n\t\taddPropertyCounters(usageStatistics, property);\n\t\tusageStatistics.propertyCountsMain.put(property,\n\t\t\t\tusageStatistics.propertyCountsMain.get(property) + count);\n\t}", "private <T> void deferNotification(T event, final EventMetadata metadata, final ObserverMethod<? super T> observer,\n final List<DeferredEventNotification<?>> notifications) {\n TransactionPhase transactionPhase = observer.getTransactionPhase();\n boolean before = transactionPhase.equals(TransactionPhase.BEFORE_COMPLETION);\n Status status = Status.valueOf(transactionPhase);\n notifications.add(new DeferredEventNotification<T>(contextId, event, metadata, observer, currentEventMetadata, status, before));\n }", "public static base_response unset(nitro_service client, nsconfig resource, String[] args) throws Exception{\n\t\tnsconfig unsetresource = new nsconfig();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "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 }", "private void setSearchScopeFilter(CmsObject cms) {\n\n final List<String> searchRoots = CmsSearchUtil.computeScopeFolders(cms, this);\n\n // If the resource types contain the type \"function\" also\n // add \"/system/modules/\" to the search path\n\n if ((null != getResourceTypes()) && containsFunctionType(getResourceTypes())) {\n searchRoots.add(\"/system/modules/\");\n }\n\n addFoldersToSearchIn(searchRoots);\n }", "public void login(Object userIdentifier) {\n session().put(config().sessionKeyUsername(), userIdentifier);\n app().eventBus().trigger(new LoginEvent(userIdentifier.toString()));\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 }" ]