query
stringlengths 7
3.3k
| positive
sequencelengths 1
1
| negative
sequencelengths 9
9
|
---|---|---|
If the column name is a dotted column, returns the first part.
Returns null otherwise.
@param column the column that might have a prefix
@return the first part of the prefix of the column or {@code null} if the column does not have a prefix. | [
"public static String getPrefix(String column) {\n\t\treturn column.contains( \".\" ) ? DOT_SEPARATOR_PATTERN.split( column )[0] : null;\n\t}"
] | [
"public void readLock(EntityKey key, int timeout) {\n\t\tReadWriteLock lock = getLock( key );\n\t\tLock readLock = lock.readLock();\n\t\tacquireLock( key, timeout, readLock );\n\t}",
"public static int[] Unique(int[] values) {\r\n HashSet<Integer> lst = new HashSet<Integer>();\r\n for (int i = 0; i < values.length; i++) {\r\n lst.add(values[i]);\r\n }\r\n\r\n int[] v = new int[lst.size()];\r\n Iterator<Integer> it = lst.iterator();\r\n for (int i = 0; i < v.length; i++) {\r\n v[i] = it.next();\r\n }\r\n\r\n return v;\r\n }",
"@Override\n public String getPartialFilterSelector() {\n return (def.selector != null) ? def.selector.toString() : null;\n }",
"public static List<Object> listOfEntities(SharedSessionContractImplementor session, Type[] resultTypes, ClosableIterator<Tuple> tuples) {\n\t\tClass<?> returnedClass = resultTypes[0].getReturnedClass();\n\t\tTupleBasedEntityLoader loader = getLoader( session, returnedClass );\n\t\tOgmLoadingContext ogmLoadingContext = new OgmLoadingContext();\n\t\togmLoadingContext.setTuples( getTuplesAsList( tuples ) );\n\t\treturn loader.loadEntitiesFromTuples( session, LockOptions.NONE, ogmLoadingContext );\n\t}",
"public static void Forward(double[][] data) {\n double[][] result = new double[data.length][data[0].length];\n\n for (int m = 0; m < data.length; m++) {\n for (int n = 0; n < data[0].length; n++) {\n double sum = 0;\n for (int i = 0; i < result.length; i++) {\n for (int k = 0; k < data.length; k++) {\n sum += data[i][k] * cas(((2.0 * Math.PI) / data.length) * (i * m + k * n));\n }\n result[m][n] = (1.0 / data.length) * sum;\n }\n }\n }\n\n for (int i = 0; i < data.length; i++) {\n for (int j = 0; j < data[0].length; j++) {\n data[i][j] = result[i][j];\n }\n }\n }",
"private static long daysBetween(Date date1, Date date2) {\n long diff;\n if (date2.after(date1)) {\n diff = date2.getTime() - date1.getTime();\n } else {\n diff = date1.getTime() - date2.getTime();\n }\n return diff / (24 * 60 * 60 * 1000);\n }",
"@Override\n public void run()\n {\n try {\n startBarrier.await();\n\n int idleCount = 0;\n while (!isRunning.compareAndSet(idleCount > lingerIterations && pidToProcessMap.isEmpty(), false)) {\n idleCount = (!shutdown && process()) ? 0 : (idleCount + 1);\n }\n }\n catch (Exception e) {\n // TODO: how to handle this error?\n isRunning.set(false);\n }\n }",
"public static Result get(XmlFileModel key)\n {\n String cacheKey = getKey(key);\n\n Result result = null;\n CacheDocument reference = map.get(cacheKey);\n\n if (reference == null)\n return new Result(false, null);\n\n if (reference.parseFailure)\n return new Result(true, null);\n\n Document document = reference.getDocument();\n if (document == null)\n LOG.info(\"Cache miss on XML document: \" + cacheKey);\n\n return new Result(false, document);\n }",
"public void unlock() {\n\n for (Locale l : m_lockedBundleFiles.keySet()) {\n LockedFile f = m_lockedBundleFiles.get(l);\n f.tryUnlock();\n }\n if (null != m_descFile) {\n m_descFile.tryUnlock();\n }\n }"
] |
Update the given resource in the persistent configuration model based on the values in the given operation.
@param operation the operation
@param resource the resource that corresponds to the address of {@code operation}
@throws OperationFailedException if {@code operation} is invalid or populating the model otherwise fails | [
"protected void updateModel(final ModelNode operation, final Resource resource) throws OperationFailedException {\n updateModel(operation, resource.getModel());\n }"
] | [
"public static base_response save(nitro_service client, cachecontentgroup resource) throws Exception {\n\t\tcachecontentgroup saveresource = new cachecontentgroup();\n\t\tsaveresource.name = resource.name;\n\t\treturn saveresource.perform_operation(client,\"save\");\n\t}",
"public static final void deleteQuietly(File file)\n {\n if (file != null)\n {\n if (file.isDirectory())\n {\n File[] children = file.listFiles();\n if (children != null)\n {\n for (File child : children)\n {\n deleteQuietly(child);\n }\n }\n }\n file.delete();\n }\n }",
"protected void recordContentLoader(final String patchID, final PatchContentLoader contentLoader) {\n if (contentLoaders.containsKey(patchID)) {\n throw new IllegalStateException(\"Content loader already registered for patch \" + patchID); // internal wrong usage, no i18n\n }\n contentLoaders.put(patchID, contentLoader);\n }",
"public static double HighAccuracyComplemented(double x) {\n double[] R =\n {\n 1.25331413731550025, 0.421369229288054473, 0.236652382913560671,\n 0.162377660896867462, 0.123131963257932296, 0.0990285964717319214,\n 0.0827662865013691773, 0.0710695805388521071, 0.0622586659950261958\n };\n\n int j = (int) (0.5 * (Math.abs(x) + 1));\n\n double a = R[j];\n double z = 2 * j;\n double b = a * z - 1;\n\n double h = Math.abs(x) - z;\n double q = h * h;\n double pwr = 1;\n\n double sum = a + h * b;\n double term = a;\n\n\n for (int i = 2; sum != term; i += 2) {\n term = sum;\n\n a = (a + z * b) / (i);\n b = (b + z * a) / (i + 1);\n pwr *= q;\n\n sum = term + pwr * (a + h * b);\n }\n\n sum *= Math.exp(-0.5 * (x * x) - 0.5 * Constants.Log2PI);\n\n return (x >= 0) ? sum : (1.0 - sum);\n }",
"@SuppressWarnings(\"rawtypes\") public static final Map getMap(Locale locale, String key)\n {\n ResourceBundle bundle = ResourceBundle.getBundle(LocaleData.class.getName(), locale);\n return ((Map) bundle.getObject(key));\n }",
"public void setKnotType(int n, int type) {\n\t\tknotTypes[n] = (byte)((knotTypes[n] & ~COLOR_MASK) | type);\n\t\trebuildGradient();\n\t}",
"public static float calculateMaxTextHeight(Paint _Paint, String _Text) {\n Rect height = new Rect();\n String text = _Text == null ? \"MgHITasger\" : _Text;\n _Paint.getTextBounds(text, 0, text.length(), height);\n return height.height();\n }",
"public static RemoteProxyController create(final TransactionalProtocolClient client, final PathAddress pathAddress,\n final ProxyOperationAddressTranslator addressTranslator,\n final ModelVersion targetKernelVersion) {\n return new RemoteProxyController(client, pathAddress, addressTranslator, targetKernelVersion);\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 }"
] |
Method called when the renderer is going to be created. This method has the responsibility of
inflate the xml layout using the layoutInflater and the parent ViewGroup, set itself to the
tag and call setUpView and hookListeners methods.
@param content to render. If you are using Renderers with RecyclerView widget the content will
be null in this method.
@param layoutInflater used to inflate the view.
@param parent used to inflate the view. | [
"public void onCreate(T content, LayoutInflater layoutInflater, ViewGroup parent) {\n this.content = content;\n this.rootView = inflate(layoutInflater, parent);\n if (rootView == null) {\n throw new NotInflateViewException(\n \"Renderer instances have to return a not null view in inflateView method\");\n }\n this.rootView.setTag(this);\n setUpView(rootView);\n hookListeners(rootView);\n }"
] | [
"public static boolean isAvroSchema(String serializerName) {\n if(serializerName.equals(AVRO_GENERIC_VERSIONED_TYPE_NAME)\n || serializerName.equals(AVRO_GENERIC_TYPE_NAME)\n || serializerName.equals(AVRO_REFLECTIVE_TYPE_NAME)\n || serializerName.equals(AVRO_SPECIFIC_TYPE_NAME)) {\n return true;\n } else {\n return false;\n }\n }",
"private void getYearlyDates(Calendar calendar, List<Date> dates)\n {\n if (m_relative)\n {\n getYearlyRelativeDates(calendar, dates);\n }\n else\n {\n getYearlyAbsoluteDates(calendar, dates);\n }\n }",
"DeleteResult deleteMany(final MongoNamespace namespace,\n final Bson filter) {\n this.waitUntilInitialized();\n\n try {\n ongoingOperationsGroup.enter();\n final List<ChangeEvent<BsonDocument>> eventsToEmit = new ArrayList<>();\n final DeleteResult result;\n final NamespaceSynchronizationConfig nsConfig = this.syncConfig.getNamespaceConfig(namespace);\n final Lock lock = nsConfig.getLock().writeLock();\n lock.lock();\n try {\n final MongoCollection<BsonDocument> localCollection = getLocalCollection(namespace);\n final MongoCollection<BsonDocument> undoCollection = getUndoCollection(namespace);\n final Set<BsonValue> idsToDelete =\n localCollection\n .find(filter)\n .map(new Function<BsonDocument, BsonValue>() {\n @Override\n @NonNull\n public BsonValue apply(@NonNull final BsonDocument bsonDocument) {\n undoCollection.insertOne(bsonDocument);\n return BsonUtils.getDocumentId(bsonDocument);\n }\n }).into(new HashSet<>());\n\n result = localCollection.deleteMany(filter);\n\n for (final BsonValue documentId : idsToDelete) {\n final CoreDocumentSynchronizationConfig config =\n syncConfig.getSynchronizedDocument(namespace, documentId);\n\n if (config == null) {\n continue;\n }\n\n final ChangeEvent<BsonDocument> event =\n ChangeEvents.changeEventForLocalDelete(namespace, documentId, true);\n\n // this block is to trigger coalescence for a delete after insert\n if (config.getLastUncommittedChangeEvent() != null\n && config.getLastUncommittedChangeEvent().getOperationType()\n == OperationType.INSERT) {\n desyncDocumentsFromRemote(nsConfig, config.getDocumentId())\n .commitAndClear();\n undoCollection.deleteOne(getDocumentIdFilter(documentId));\n continue;\n }\n\n config.setSomePendingWritesAndSave(logicalT, event);\n undoCollection.deleteOne(getDocumentIdFilter(documentId));\n eventsToEmit.add(event);\n }\n checkAndDeleteNamespaceListener(namespace);\n } finally {\n lock.unlock();\n }\n for (final ChangeEvent<BsonDocument> event : eventsToEmit) {\n eventDispatcher.emitEvent(nsConfig, event);\n }\n return result;\n } finally {\n ongoingOperationsGroup.exit();\n }\n }",
"public static void showChannels(Object... channels){\r\n // TODO this could share more code with the other show/hide(Only)Channels methods\r\n for(LogRecordHandler handler : handlers){\r\n if(handler instanceof VisibilityHandler){\r\n VisibilityHandler visHandler = (VisibilityHandler) handler;\r\n for (Object channel : channels) {\r\n visHandler.alsoShow(channel);\r\n }\r\n }\r\n }\r\n }",
"public static void dumpClusters(Cluster currentCluster,\n Cluster finalCluster,\n String outputDirName) {\n dumpClusters(currentCluster, finalCluster, outputDirName, \"\");\n }",
"public static sslvserver_sslcertkey_binding[] get(nitro_service service, String vservername) throws Exception{\n\t\tsslvserver_sslcertkey_binding obj = new sslvserver_sslcertkey_binding();\n\t\tobj.set_vservername(vservername);\n\t\tsslvserver_sslcertkey_binding response[] = (sslvserver_sslcertkey_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static <K, V> QueuedKeyedResourcePool<K, V> create(ResourceFactory<K, V> factory,\n ResourcePoolConfig config) {\n return new QueuedKeyedResourcePool<K, V>(factory, config);\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}",
"public static double getRadiusToBoundedness(double D, int N, double timelag, double B){\n\t\tdouble cov_area = a(N)*D*timelag;\n\t\tdouble radius = Math.sqrt(cov_area/(4*B));\n\t\treturn radius;\n\t}"
] |
Adds the correct load instruction based on the type descriptor
@param code the bytecode to add the instruction to
@param type the type of the variable
@param variable the variable number | [
"public static void addLoadInstruction(CodeAttribute code, String type, int variable) {\n char tp = type.charAt(0);\n if (tp != 'L' && tp != '[') {\n // we have a primitive type\n switch (tp) {\n case 'J':\n code.lload(variable);\n break;\n case 'D':\n code.dload(variable);\n break;\n case 'F':\n code.fload(variable);\n break;\n default:\n code.iload(variable);\n }\n } else {\n code.aload(variable);\n }\n }"
] | [
"public void onSplashScreenCreated(GVRSceneObject splashScreen) {\n GVRTransform transform = splashScreen.getTransform();\n transform.setPosition(0, 0, DEFAULT_SPLASH_Z);\n }",
"public Date toDate(Object date) {\n\n Date d = null;\n if (null != date) {\n if (date instanceof Date) {\n d = (Date)date;\n } else if (date instanceof Long) {\n d = new Date(((Long)date).longValue());\n } else {\n try {\n long l = Long.parseLong(date.toString());\n d = new Date(l);\n } catch (Exception e) {\n // do nothing, just let d remain null\n }\n }\n }\n return d;\n }",
"public static I_CmsSearchConfigurationPagination create(\n String pageParam,\n List<Integer> pageSizes,\n Integer pageNavLength) {\n\n return (pageParam != null) || (pageSizes != null) || (pageNavLength != null)\n ? new CmsSearchConfigurationPagination(pageParam, pageSizes, pageNavLength)\n : null;\n\n }",
"protected void createSetterMethod(ClassNode declaringClass, PropertyNode propertyNode, String setterName, Statement setterBlock) {\r\n MethodNode setter = new MethodNode(\r\n setterName,\r\n propertyNode.getModifiers(),\r\n ClassHelper.VOID_TYPE,\r\n params(param(propertyNode.getType(), \"value\")),\r\n ClassNode.EMPTY_ARRAY,\r\n setterBlock);\r\n setter.setSynthetic(true);\r\n // add it to the class\r\n declaringClass.addMethod(setter);\r\n }",
"public void initSize(Rectangle rectangle) {\n\t\ttemplate = writer.getDirectContent().createTemplate(rectangle.getWidth(), rectangle.getHeight());\n\t}",
"public void updateStructure()\n {\n if (size() > 1)\n {\n Collections.sort(this);\n m_projectFile.getChildTasks().clear();\n\n Task lastTask = null;\n int lastLevel = -1;\n boolean autoWbs = m_projectFile.getProjectConfig().getAutoWBS();\n boolean autoOutlineNumber = m_projectFile.getProjectConfig().getAutoOutlineNumber();\n\n for (Task task : this)\n {\n task.clearChildTasks();\n Task parent = null;\n if (!task.getNull())\n {\n int level = NumberHelper.getInt(task.getOutlineLevel());\n\n if (lastTask != null)\n {\n if (level == lastLevel || task.getNull())\n {\n parent = lastTask.getParentTask();\n level = lastLevel;\n }\n else\n {\n if (level > lastLevel)\n {\n parent = lastTask;\n }\n else\n {\n while (level <= lastLevel)\n {\n parent = lastTask.getParentTask();\n\n if (parent == null)\n {\n break;\n }\n\n lastLevel = NumberHelper.getInt(parent.getOutlineLevel());\n lastTask = parent;\n }\n }\n }\n }\n\n lastTask = task;\n lastLevel = level;\n\n if (autoWbs || task.getWBS() == null)\n {\n task.generateWBS(parent);\n }\n\n if (autoOutlineNumber)\n {\n task.generateOutlineNumber(parent);\n }\n }\n\n if (parent == null)\n {\n m_projectFile.getChildTasks().add(task);\n }\n else\n {\n parent.addChildTask(task);\n }\n }\n }\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 T build() throws IllegalAccessException, IOException, InvocationTargetException {\n generatedConfigutation = new CubeContainer();\n\n findContainerName();\n // if needed, prepare prepare resources required to build a docker image\n prepareImageBuild();\n // instantiate container object\n instantiateContainerObject();\n // enrich container object (without cube instance)\n enrichContainerObjectBeforeCube();\n // extract configuration from container object class\n extractConfigurationFromContainerObject();\n // merge received configuration with extracted configuration\n mergeContainerObjectConfiguration();\n // create/start/register associated cube\n initializeCube();\n // enrich container object (with cube instance)\n enrichContainerObjectWithCube();\n // return created container object\n return containerObjectInstance;\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 }"
] |
Function to perform the forward pass for batch convolution | [
"public static int cudnnConvolutionForward(\n cudnnHandle handle, \n Pointer alpha, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n cudnnFilterDescriptor wDesc, \n Pointer w, \n cudnnConvolutionDescriptor convDesc, \n int algo, \n Pointer workSpace, \n long workSpaceSizeInBytes, \n Pointer beta, \n cudnnTensorDescriptor yDesc, \n Pointer y)\n {\n return checkResult(cudnnConvolutionForwardNative(handle, alpha, xDesc, x, wDesc, w, convDesc, algo, workSpace, workSpaceSizeInBytes, beta, yDesc, y));\n }"
] | [
"public CollectionRequest<Task> projects(String task) {\n \n String path = String.format(\"/tasks/%s/projects\", task);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }",
"@Override\n public EthiopicDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }",
"public static boolean any(Object self, Closure closure) {\n BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);\n for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {\n if (bcw.call(iter.next())) return true;\n }\n return false;\n }",
"public int getFixedDataOffset(FieldType type)\n {\n int result;\n FieldItem item = m_map.get(type);\n if (item != null)\n {\n result = item.getFixedDataOffset();\n }\n else\n {\n result = -1;\n }\n return result;\n }",
"public static String readTextFile(Context context, int resourceId) {\n InputStream inputStream = context.getResources().openRawResource(\n resourceId);\n return readTextFile(inputStream);\n }",
"private org.apache.tools.ant.types.Path addSlaveClasspath() {\n org.apache.tools.ant.types.Path path = new org.apache.tools.ant.types.Path(getProject());\n\n String [] REQUIRED_SLAVE_CLASSES = {\n SlaveMain.class.getName(),\n Strings.class.getName(),\n MethodGlobFilter.class.getName(),\n TeeOutputStream.class.getName()\n };\n\n for (String clazz : Arrays.asList(REQUIRED_SLAVE_CLASSES)) {\n String resource = clazz.replace(\".\", \"/\") + \".class\";\n File f = LoaderUtils.getResourceSource(getClass().getClassLoader(), resource);\n if (f != null) {\n path.createPath().setLocation(f);\n } else {\n throw new BuildException(\"Could not locate classpath for resource: \" + resource);\n }\n }\n return path;\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 }",
"protected org.apache.log4j.helpers.PatternParser createPatternParser(final String pattern) {\n\t\treturn new FoundationLoggingPatternParser(pattern);\n\t}",
"public String getString(Integer id, Integer type)\n {\n return (getString(m_meta.getOffset(id, type)));\n }"
] |
Update the context session to mark a user logged in
@param userIdentifier
the user identifier, could be either userId or username | [
"public void login(Object userIdentifier) {\n session().put(config().sessionKeyUsername(), userIdentifier);\n app().eventBus().trigger(new LoginEvent(userIdentifier.toString()));\n }"
] | [
"public double computeLikelihoodP() {\n double ret = 1.0;\n\n for( int i = 0; i < r.numRows; i++ ) {\n double a = r.get(i,0);\n\n ret *= Math.exp(-a*a/2.0);\n }\n\n return ret;\n }",
"protected List<Integer> cancelAllActiveOperations() {\n final List<Integer> operations = new ArrayList<Integer>();\n for(final ActiveOperationImpl<?, ?> activeOperation : activeRequests.values()) {\n activeOperation.asyncCancel(false);\n operations.add(activeOperation.getOperationId());\n }\n return operations;\n }",
"protected synchronized void handleCompleted() {\n latch.countDown();\n for (final ShutdownListener listener : listeners) {\n listener.handleCompleted();\n }\n listeners.clear();\n }",
"public static Broker createBroker(int id, String brokerInfoString) {\n String[] brokerInfo = brokerInfoString.split(\":\");\n String creator = brokerInfo[0].replace('#', ':');\n String hostname = brokerInfo[1].replace('#', ':');\n String port = brokerInfo[2];\n boolean autocreated = Boolean.valueOf(brokerInfo.length > 3 ? brokerInfo[3] : \"true\");\n return new Broker(id, creator, hostname, Integer.parseInt(port), autocreated);\n }",
"protected OJBIterator getIteratorFromQuery(Query query, ClassDescriptor cld) throws PersistenceBrokerException\n {\n RsIteratorFactory factory = RsIteratorFactoryImpl.getInstance();\n OJBIterator result = getRsIteratorFromQuery(query, cld, factory);\n\n if (query.usePaging())\n {\n result = new PagingIterator(result, query.getStartAtIndex(), query.getEndAtIndex());\n }\n return result;\n }",
"final public void addOffset(Integer start, Integer end) {\n if (tokenOffset == null) {\n setOffset(start, end);\n } else if ((start == null) || (end == null)) {\n // do nothing\n } else if (start > end) {\n throw new IllegalArgumentException(\"Start offset after end offset\");\n } else {\n tokenOffset.add(start, end);\n }\n }",
"public Shard getShard(String docId) {\n assertNotEmpty(docId, \"docId\");\n return client.couchDbClient.get(new DatabaseURIHelper(db.getDBUri()).path(\"_shards\")\n .path(docId).build(),\n Shard.class);\n }",
"private void writeMapFile(String mapFileName, File jarFile, boolean mapClassMethods) throws IOException, XMLStreamException, ClassNotFoundException, IntrospectionException\n {\n FileWriter fw = new FileWriter(mapFileName);\n XMLOutputFactory xof = XMLOutputFactory.newInstance();\n XMLStreamWriter writer = xof.createXMLStreamWriter(fw);\n //XMLStreamWriter writer = new IndentingXMLStreamWriter(xof.createXMLStreamWriter(fw));\n\n writer.writeStartDocument();\n writer.writeStartElement(\"root\");\n writer.writeStartElement(\"assembly\");\n\n addClasses(writer, jarFile, mapClassMethods);\n\n writer.writeEndElement();\n writer.writeEndElement();\n writer.writeEndDocument();\n writer.flush();\n writer.close();\n\n fw.flush();\n fw.close();\n }",
"public 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 }"
] |
Create an instance from the given config.
@param param Grid param from the request. | [
"public static GridLabelFormat fromConfig(final GridParam param) {\n if (param.labelFormat != null) {\n return new GridLabelFormat.Simple(param.labelFormat);\n } else if (param.valueFormat != null) {\n return new GridLabelFormat.Detailed(\n param.valueFormat, param.unitFormat,\n param.formatDecimalSeparator, param.formatGroupingSeparator);\n }\n return null;\n }"
] | [
"public static ComponentsMultiThread getComponentsMultiThread() {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return null;\n }\n\n return instance.componentsMultiThread;\n }",
"public void clear() {\n if (arrMask != null) {\n for (int y = 0; y < height; y++) {\n for (int x = 0; x < width; x++) {\n arrMask[x][y] = false;\n }\n }\n }\n }",
"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 void recordServerResult(ServerIdentity server, ModelNode response) {\n\n if (!serverGroupName.equals(server.getServerGroupName()) || !servers.contains(server)) {\n throw DomainControllerLogger.HOST_CONTROLLER_LOGGER.unknownServer(server);\n }\n\n boolean serverFailed = response.has(FAILURE_DESCRIPTION);\n\n\n DomainControllerLogger.HOST_CONTROLLER_LOGGER.tracef(\"Recording server result for '%s': failed = %s\",\n server, server);\n\n synchronized (this) {\n int previousFailed = failureCount;\n if (serverFailed) {\n failureCount++;\n }\n else {\n successCount++;\n }\n if (previousFailed <= maxFailed) {\n if (!serverFailed && (successCount + failureCount) == servers.size()) {\n // All results are in; notify parent of success\n parent.recordServerGroupResult(serverGroupName, false);\n }\n else if (serverFailed && failureCount > maxFailed) {\n parent.recordServerGroupResult(serverGroupName, true);\n }\n }\n }\n }",
"public static base_response add(nitro_service client, nslimitselector resource) throws Exception {\n\t\tnslimitselector addresource = new nslimitselector();\n\t\taddresource.selectorname = resource.selectorname;\n\t\taddresource.rule = resource.rule;\n\t\treturn addresource.add_resource(client);\n\t}",
"public static String[] addStringToArray(String[] array, String str) {\n if (isEmpty(array)) {\n return new String[]{str};\n }\n String[] newArr = new String[array.length + 1];\n System.arraycopy(array, 0, newArr, 0, array.length);\n newArr[array.length] = str;\n return newArr;\n }",
"private boolean isAllOrDirtyOptLocking() {\n\t\tEntityMetamodel entityMetamodel = getEntityMetamodel();\n\t\treturn entityMetamodel.getOptimisticLockStyle() == OptimisticLockStyle.DIRTY\n\t\t\t\t|| entityMetamodel.getOptimisticLockStyle() == OptimisticLockStyle.ALL;\n\t}",
"private String getActivityID(Task task)\n {\n String result = null;\n if (m_activityIDField != null)\n {\n Object value = task.getCachedValue(m_activityIDField);\n if (value != null)\n {\n result = value.toString();\n }\n }\n return result;\n }",
"private Map<Integer, Integer> getNodeIdToPrimaryCount(Cluster cluster) {\n Map<Integer, Integer> nodeIdToPrimaryCount = Maps.newHashMap();\n for(Node node: cluster.getNodes()) {\n nodeIdToPrimaryCount.put(node.getId(), node.getPartitionIds().size());\n }\n\n return nodeIdToPrimaryCount;\n }"
] |
There is a race condition that is not handled properly by the DialogFragment class.
If we don't check that this onDismiss callback isn't for the old progress dialog from before
the device orientation change, then this will cause the newly created dialog after the
orientation change to be dismissed immediately. | [
"@Override\n public void onDismiss(DialogInterface dialog) {\n if (mOldDialog != null && mOldDialog == dialog) {\n // This is the callback from the old progress dialog that was already dismissed before\n // the device orientation change, so just ignore it.\n return;\n }\n super.onDismiss(dialog);\n }"
] | [
"public static MapBounds adjustBoundsToScaleAndMapSize(\n final GenericMapAttributeValues mapValues,\n final Rectangle paintArea,\n final MapBounds bounds,\n final double dpi) {\n MapBounds newBounds = bounds;\n if (mapValues.isUseNearestScale()) {\n newBounds = newBounds.adjustBoundsToNearestScale(\n mapValues.getZoomLevels(),\n mapValues.getZoomSnapTolerance(),\n mapValues.getZoomLevelSnapStrategy(),\n mapValues.getZoomSnapGeodetic(),\n paintArea, dpi);\n }\n\n newBounds = new BBoxMapBounds(newBounds.toReferencedEnvelope(paintArea));\n\n if (mapValues.isUseAdjustBounds()) {\n newBounds = newBounds.adjustedEnvelope(paintArea);\n }\n return newBounds;\n }",
"public void initSize(Rectangle rectangle) {\n\t\ttemplate = writer.getDirectContent().createTemplate(rectangle.getWidth(), rectangle.getHeight());\n\t}",
"private boolean markAsObsolete(ContentReference ref) {\n if (obsoleteContents.containsKey(ref.getHexHash())) { //This content is already marked as obsolete\n if (obsoleteContents.get(ref.getHexHash()) + obsolescenceTimeout < System.currentTimeMillis()) {\n DeploymentRepositoryLogger.ROOT_LOGGER.obsoleteContentCleaned(ref.getContentIdentifier());\n removeContent(ref);\n return true;\n }\n } else {\n obsoleteContents.put(ref.getHexHash(), System.currentTimeMillis()); //Mark content as obsolete\n }\n return false;\n }",
"public static Processor<DataSourceTask> source(DataSource source, int parallelism, String description, UserConfig taskConf, ActorSystem system) {\n io.gearpump.streaming.Processor<DataSourceTask<Object, Object>> p =\n DataSourceProcessor.apply(source, parallelism, description, taskConf, system);\n return new Processor(p);\n }",
"public void validate() throws PackagingException {\n if (control == null || !control.isDirectory()) {\n throw new PackagingException(\"The 'control' attribute doesn't point to a directory. \" + control);\n }\n\n if (changesIn != null) {\n\n if (changesIn.exists() && (!changesIn.isFile() || !changesIn.canRead())) {\n throw new PackagingException(\"The 'changesIn' setting needs to point to a readable file. \" + changesIn + \" was not found/readable.\");\n }\n\n if (changesOut != null && !isWritableFile(changesOut)) {\n throw new PackagingException(\"Cannot write the output for 'changesOut' to \" + changesOut);\n }\n\n if (changesSave != null && !isWritableFile(changesSave)) {\n throw new PackagingException(\"Cannot write the output for 'changesSave' to \" + changesSave);\n }\n\n } else {\n if (changesOut != null || changesSave != null) {\n throw new PackagingException(\"The 'changesOut' or 'changesSave' settings may only be used when there is a 'changesIn' specified.\");\n }\n }\n\n if (Compression.toEnum(compression) == null) {\n throw new PackagingException(\"The compression method '\" + compression + \"' is not supported (expected 'none', 'gzip', 'bzip2' or 'xz')\");\n }\n\n if (deb == null) {\n throw new PackagingException(\"You need to specify where the deb file is supposed to be created.\");\n }\n\n getDigestCode(digest);\n }",
"public String getPromotionDetailsJsonModel() throws IOException {\n final PromotionEvaluationReport sampleReport = new PromotionEvaluationReport();\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.UNPROMOTED_MSG, \"com.acme.secure-smh:core-relay:1.2.0\"), MAJOR);\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.DO_NOT_USE_MSG, \"com.google.guava:guava:20.0\"), MAJOR);\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.MISSING_LICENSE_MSG, \"org.apache.maven.wagon:wagon-webdav-jackrabbit:2.12\"), MINOR);\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.UNACCEPTABLE_LICENSE_MSG,\n \"aopaliance:aopaliance:1.0 licensed as Attribution-ShareAlike 2.5 Generic, \" +\n \"org.polyjdbc:polyjdbc0.7.1 licensed as Creative Commons Attribution-ShareAlike 3.0 Unported License\"),\n MINOR);\n\n sampleReport.addMessage(PromotionReportTranslator.SNAPSHOT_VERSION_MSG, Tag.CRITICAL);\n return JsonUtils.serialize(sampleReport);\n }",
"public void remove(RowKey key) {\n\t\tcurrentState.put( key, new AssociationOperation( key, null, REMOVE ) );\n\t}",
"public PreparedStatement getPreparedStatement(ClassDescriptor cds, String sql,\r\n boolean scrollable, int explicitFetchSizeHint, boolean callableStmt)\r\n throws PersistenceBrokerException\r\n {\r\n try\r\n {\r\n return cds.getStatementsForClass(m_conMan).getPreparedStmt(m_conMan.getConnection(), sql, scrollable, explicitFetchSizeHint, callableStmt);\r\n }\r\n catch (LookupException e)\r\n {\r\n throw new PersistenceBrokerException(\"Used ConnectionManager instance could not obtain a connection\", e);\r\n }\r\n }",
"private long interpolateTimeFromUpdate(TrackPositionUpdate lastTrackUpdate, CdjStatus newDeviceUpdate,\n BeatGrid beatGrid) {\n final int beatNumber = newDeviceUpdate.getBeatNumber();\n final boolean noLongerPlaying = !newDeviceUpdate.isPlaying();\n\n // If we have just stopped, see if we are near a cue (assuming that information is available), and if so,\n // the best assumption is that the DJ jumped to that cue.\n if (lastTrackUpdate.playing && noLongerPlaying) {\n final CueList.Entry jumpedTo = findAdjacentCue(newDeviceUpdate, beatGrid);\n if (jumpedTo != null) return jumpedTo.cueTime;\n }\n\n // Handle the special case where we were not playing either in the previous or current update, but the DJ\n // might have jumped to a different place in the track.\n if (!lastTrackUpdate.playing) {\n if (lastTrackUpdate.beatNumber == beatNumber && noLongerPlaying) { // Haven't moved\n return lastTrackUpdate.milliseconds;\n } else {\n if (noLongerPlaying) { // Have jumped without playing.\n if (beatNumber < 0) {\n return -1; // We don't know the position any more; weird to get into this state and still have a grid?\n }\n // As a heuristic, assume we are right before the beat?\n return timeOfBeat(beatGrid, beatNumber, newDeviceUpdate);\n }\n }\n }\n\n // One way or another, we are now playing.\n long elapsedMillis = (newDeviceUpdate.getTimestamp() - lastTrackUpdate.timestamp) / 1000000;\n long moved = Math.round(lastTrackUpdate.pitch * elapsedMillis);\n long interpolated = (lastTrackUpdate.reverse)?\n (lastTrackUpdate.milliseconds - moved) : lastTrackUpdate.milliseconds + moved;\n if (Math.abs(beatGrid.findBeatAtTime(interpolated) - beatNumber) < 2) {\n return interpolated; // Our calculations still look plausible\n }\n // The player has jumped or drifted somewhere unexpected, correct.\n if (newDeviceUpdate.isPlayingForwards()) {\n return timeOfBeat(beatGrid, beatNumber, newDeviceUpdate);\n } else {\n return beatGrid.getTimeWithinTrack(Math.min(beatNumber + 1, beatGrid.beatCount));\n }\n }"
] |
Return the number of days between startDate and endDate given the
specific daycount convention.
@param startDate The start date given as a {@link org.threeten.bp.LocalDate}.
@param endDate The end date given as a {@link org.threeten.bp.LocalDate}.
@param convention A convention string.
@return The number of days within the given period. | [
"public static double getDaycount(LocalDate startDate, LocalDate endDate, String convention) {\n\t\tDayCountConventionInterface daycountConvention = getDayCountConvention(convention);\n\t\treturn daycountConvention.getDaycount(startDate, endDate);\n\t}"
] | [
"public static snmpalarm[] get(nitro_service service, String trapname[]) throws Exception{\n\t\tif (trapname !=null && trapname.length>0) {\n\t\t\tsnmpalarm response[] = new snmpalarm[trapname.length];\n\t\t\tsnmpalarm obj[] = new snmpalarm[trapname.length];\n\t\t\tfor (int i=0;i<trapname.length;i++) {\n\t\t\t\tobj[i] = new snmpalarm();\n\t\t\t\tobj[i].set_trapname(trapname[i]);\n\t\t\t\tresponse[i] = (snmpalarm) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}",
"public void onDrawFrame(float frameTime)\n {\n if (!isEnabled() || (owner == null) || (getFloat(\"enabled\") <= 0.0f))\n {\n return;\n }\n float[] odir = getVec3(\"world_direction\");\n float[] opos = getVec3(\"world_position\");\n GVRSceneObject parent = owner;\n Matrix4f worldmtx = parent.getTransform().getModelMatrix4f();\n\n mOldDir.x = odir[0];\n mOldDir.y = odir[1];\n mOldDir.z = odir[2];\n mOldPos.x = opos[0];\n mOldPos.y = opos[1];\n mOldPos.z = opos[2];\n mNewDir.x = 0.0f;\n mNewDir.y = 0.0f;\n mNewDir.z = -1.0f;\n worldmtx.getTranslation(mNewPos);\n worldmtx.mul(mLightRot);\n worldmtx.transformDirection(mNewDir);\n if ((mOldDir.x != mNewDir.x) || (mOldDir.y != mNewDir.y) || (mOldDir.z != mNewDir.z))\n {\n setVec4(\"world_direction\", mNewDir.x, mNewDir.y, mNewDir.z, 0);\n }\n if ((mOldPos.x != mNewPos.x) || (mOldPos.y != mNewPos.y) || (mOldPos.z != mNewPos.z))\n {\n setPosition(mNewPos.x, mNewPos.y, mNewPos.z);\n }\n }",
"public static GVRSceneObject loadModel(final GVRContext gvrContext,\n final String modelFile) throws IOException {\n return loadModel(gvrContext, modelFile, new HashMap<String, Integer>());\n }",
"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 }",
"public static base_responses flush(nitro_service client, cacheobject resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcacheobject flushresources[] = new cacheobject[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tflushresources[i] = new cacheobject();\n\t\t\t\tflushresources[i].locator = resources[i].locator;\n\t\t\t\tflushresources[i].url = resources[i].url;\n\t\t\t\tflushresources[i].host = resources[i].host;\n\t\t\t\tflushresources[i].port = resources[i].port;\n\t\t\t\tflushresources[i].groupname = resources[i].groupname;\n\t\t\t\tflushresources[i].httpmethod = resources[i].httpmethod;\n\t\t\t\tflushresources[i].force = resources[i].force;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, flushresources,\"flush\");\n\t\t}\n\t\treturn result;\n\t}",
"public int getPathId(String pathName, int profileId) {\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n // first get the pathId for the pathName/profileId\n int pathId = -1;\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT \" + Constants.GENERIC_ID + \" FROM \" + Constants.DB_TABLE_PATH\n + \" WHERE \" + Constants.PATH_PROFILE_PATHNAME + \"= ? \"\n + \" AND \" + Constants.GENERIC_PROFILE_ID + \"= ?\"\n );\n queryStatement.setString(1, pathName);\n queryStatement.setInt(2, profileId);\n results = queryStatement.executeQuery();\n if (results.next()) {\n pathId = results.getInt(Constants.GENERIC_ID);\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 (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return pathId;\n }",
"public float getLayoutSize(final Layout.Axis axis) {\n float size = 0;\n for (Layout layout : mLayouts) {\n size = Math.max(size, layout.getSize(axis));\n }\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"getLayoutSize [%s] axis [%s] size [%f]\", getName(), axis, size);\n return size;\n }",
"@PostConstruct\n\tprotected void buildCopyrightMap() {\n\t\tif (null == declaredPlugins) {\n\t\t\treturn;\n\t\t}\n\t\t// go over all plug-ins, adding copyright info, avoiding duplicates (on object key)\n\t\tfor (PluginInfo plugin : declaredPlugins.values()) {\n\t\t\tfor (CopyrightInfo copyright : plugin.getCopyrightInfo()) {\n\t\t\t\tString key = copyright.getKey();\n\t\t\t\tString msg = copyright.getKey() + \": \" + copyright.getCopyright() + \" : licensed as \" +\n\t\t\t\t\t\tcopyright.getLicenseName() + \", see \" + copyright.getLicenseUrl();\n\t\t\t\tif (null != copyright.getSourceUrl()) {\n\t\t\t\t\tmsg += \" source \" + copyright.getSourceUrl();\n\t\t\t\t}\n\t\t\t\tif (!copyrightMap.containsKey(key)) {\n\t\t\t\t\tlog.info(msg);\n\t\t\t\t\tcopyrightMap.put(key, copyright);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"public static csvserver_copolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_copolicy_binding obj = new csvserver_copolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_copolicy_binding response[] = (csvserver_copolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Specify a specific index to run the query against
@param designDocument set the design document to use
@param indexName set the index name to use
@return this to set additional options | [
"public FindByIndexOptions useIndex(String designDocument, String indexName) {\r\n assertNotNull(designDocument, \"designDocument\");\r\n assertNotNull(indexName, \"indexName\");\r\n JsonArray index = new JsonArray();\r\n index.add(new JsonPrimitive(designDocument));\r\n index.add(new JsonPrimitive(indexName));\r\n this.useIndex = index;\r\n return this;\r\n }"
] | [
"public static String transformXPath(String originalXPath)\n {\n // use a list to maintain the multiple joined xqueries (if there are multiple queries joined with the \"|\" operator)\n List<StringBuilder> compiledXPaths = new ArrayList<>(1);\n\n int frameIdx = -1;\n boolean inQuote = false;\n int conditionLevel = 0;\n char startQuoteChar = 0;\n StringBuilder currentXPath = new StringBuilder();\n compiledXPaths.add(currentXPath);\n for (int i = 0; i < originalXPath.length(); i++)\n {\n char curChar = originalXPath.charAt(i);\n if (!inQuote && curChar == '[')\n {\n frameIdx++;\n conditionLevel++;\n currentXPath.append(\"[windup:startFrame(\").append(frameIdx).append(\") and windup:evaluate(\").append(frameIdx).append(\", \");\n }\n else if (!inQuote && curChar == ']')\n {\n conditionLevel--;\n currentXPath.append(\")]\");\n }\n else if (!inQuote && conditionLevel == 0 && curChar == '|')\n {\n // joining multiple xqueries\n currentXPath = new StringBuilder();\n compiledXPaths.add(currentXPath);\n }\n else\n {\n if (inQuote && curChar == startQuoteChar)\n {\n inQuote = false;\n startQuoteChar = 0;\n }\n else if (curChar == '\"' || curChar == '\\'')\n {\n inQuote = true;\n startQuoteChar = curChar;\n }\n\n if (!inQuote && originalXPath.startsWith(WINDUP_MATCHES_FUNCTION_PREFIX, i))\n {\n i += (WINDUP_MATCHES_FUNCTION_PREFIX.length() - 1);\n currentXPath.append(\"windup:matches(\").append(frameIdx).append(\", \");\n }\n else\n {\n currentXPath.append(curChar);\n }\n }\n }\n\n Pattern leadingAndTrailingWhitespace = Pattern.compile(\"(\\\\s*)(.*?)(\\\\s*)\");\n StringBuilder finalResult = new StringBuilder();\n for (StringBuilder compiledXPath : compiledXPaths)\n {\n if (StringUtils.isNotBlank(compiledXPath))\n {\n Matcher whitespaceMatcher = leadingAndTrailingWhitespace.matcher(compiledXPath);\n if (!whitespaceMatcher.matches())\n continue;\n\n compiledXPath = new StringBuilder();\n compiledXPath.append(whitespaceMatcher.group(1));\n compiledXPath.append(whitespaceMatcher.group(2));\n compiledXPath.append(\"/self::node()[windup:persist(\").append(frameIdx).append(\", \").append(\".)]\");\n compiledXPath.append(whitespaceMatcher.group(3));\n\n if (StringUtils.isNotBlank(finalResult))\n finalResult.append(\"|\");\n finalResult.append(compiledXPath);\n }\n }\n return finalResult.toString();\n }",
"public void renumberUniqueIDs()\n {\n int uid = firstUniqueID();\n for (T entity : this)\n {\n entity.setUniqueID(Integer.valueOf(uid++));\n }\n }",
"public synchronized static <D extends Dao<T, ?>, T> D lookupDao(ConnectionSource connectionSource,\n\t\t\tDatabaseTableConfig<T> tableConfig) {\n\t\tif (connectionSource == null) {\n\t\t\tthrow new IllegalArgumentException(\"connectionSource argument cannot be null\");\n\t\t}\n\t\tTableConfigConnectionSource key = new TableConfigConnectionSource(connectionSource, tableConfig);\n\t\tDao<?, ?> dao = lookupDao(key);\n\t\tif (dao == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\t@SuppressWarnings(\"unchecked\")\n\t\t\tD castDao = (D) dao;\n\t\t\treturn castDao;\n\t\t}\n\t}",
"private SpellCheckResponse performSpellcheckQuery(CmsSpellcheckingRequest request) {\n\n if ((null == request) || !request.isInitialized()) {\n return null;\n }\n\n final String[] wordsToCheck = request.m_wordsToCheck;\n\n final ModifiableSolrParams params = new ModifiableSolrParams();\n params.set(\"spellcheck\", \"true\");\n params.set(\"spellcheck.dictionary\", request.m_dictionaryToUse);\n params.set(\"spellcheck.extendedResults\", \"true\");\n\n // Build one string from array of words and use it as query.\n final StringBuilder builder = new StringBuilder();\n for (int i = 0; i < wordsToCheck.length; i++) {\n builder.append(wordsToCheck[i] + \" \");\n }\n\n params.set(\"spellcheck.q\", builder.toString());\n\n final SolrQuery query = new SolrQuery();\n query.setRequestHandler(\"/spell\");\n query.add(params);\n\n try {\n QueryResponse qres = m_solrClient.query(query);\n return qres.getSpellCheckResponse();\n } catch (Exception e) {\n LOG.debug(\"Exception while performing spellcheck query...\", e);\n }\n\n return null;\n }",
"public static Method getStaticMethod(Class<?> clazz, String methodName, Class<?>... args) {\n\t\tAssert.notNull(clazz, \"Class must not be null\");\n\t\tAssert.notNull(methodName, \"Method name must not be null\");\n\t\ttry {\n\t\t\tMethod method = clazz.getMethod(methodName, args);\n\t\t\treturn Modifier.isStatic(method.getModifiers()) ? method : null;\n\t\t}\n\t\tcatch (NoSuchMethodException ex) {\n\t\t\treturn null;\n\t\t}\n\t}",
"public static base_response Force(nitro_service client, clustersync resource) throws Exception {\n\t\tclustersync Forceresource = new clustersync();\n\t\treturn Forceresource.perform_operation(client,\"Force\");\n\t}",
"protected Element createRectangleElement(float x, float y, float width, float height, boolean stroke, boolean fill)\n {\n float lineWidth = transformWidth(getGraphicsState().getLineWidth());\n \tfloat wcor = stroke ? lineWidth : 0.0f;\n float strokeOffset = wcor == 0 ? 0 : wcor / 2;\n width = width - wcor < 0 ? 1 : width - wcor;\n height = height - wcor < 0 ? 1 : height - wcor;\n\n StringBuilder pstyle = new StringBuilder(50);\n \tpstyle.append(\"left:\").append(style.formatLength(x - strokeOffset)).append(';');\n pstyle.append(\"top:\").append(style.formatLength(y - strokeOffset)).append(';');\n pstyle.append(\"width:\").append(style.formatLength(width)).append(';');\n pstyle.append(\"height:\").append(style.formatLength(height)).append(';');\n \t \n \tif (stroke)\n \t{\n String color = colorString(getGraphicsState().getStrokingColor());\n \tpstyle.append(\"border:\").append(style.formatLength(lineWidth)).append(\" solid \").append(color).append(';');\n \t}\n \t\n \tif (fill)\n \t{\n String fcolor = colorString(getGraphicsState().getNonStrokingColor());\n \t pstyle.append(\"background-color:\").append(fcolor).append(';');\n \t}\n \t\n Element el = doc.createElement(\"div\");\n el.setAttribute(\"class\", \"r\");\n el.setAttribute(\"style\", pstyle.toString());\n el.appendChild(doc.createEntityReference(\"nbsp\"));\n return el;\n }",
"private void addClass(URLClassLoader loader, JarEntry jarEntry, XMLStreamWriter writer, boolean mapClassMethods) throws ClassNotFoundException, XMLStreamException, IntrospectionException\n {\n String className = jarEntry.getName().replaceAll(\"\\\\.class\", \"\").replaceAll(\"/\", \".\");\n writer.writeStartElement(\"class\");\n writer.writeAttribute(\"name\", className);\n\n Set<Method> methodSet = new HashSet<Method>();\n Class<?> aClass = loader.loadClass(className);\n\n processProperties(writer, methodSet, aClass);\n\n if (mapClassMethods && !Modifier.isInterface(aClass.getModifiers()))\n {\n processClassMethods(writer, aClass, methodSet);\n }\n writer.writeEndElement();\n }",
"public static String find(CharSequence self, CharSequence regex, @ClosureParams(value=SimpleType.class, options=\"java.lang.String[]\") Closure closure) {\n return find(self.toString(), Pattern.compile(regex.toString()), closure);\n }"
] |
Register child resources associated with this resource.
@param resourceRegistration a {@link org.jboss.as.controller.registry.ManagementResourceRegistration} created from this definition | [
"@Override\n public void registerChildren(ManagementResourceRegistration resourceRegistration) {\n // Register wildcard children last to prevent duplicate registration errors when override definitions exist\n for (ResourceDefinition rd : singletonChildren) {\n resourceRegistration.registerSubModel(rd);\n }\n for (ResourceDefinition rd : wildcardChildren) {\n resourceRegistration.registerSubModel(rd);\n }\n }"
] | [
"@SuppressWarnings(\"unchecked\")\n public <T extends ReportModel> T getReportByName(String name, Class<T> clazz)\n {\n WindupVertexFrame model = this.getUniqueByProperty(ReportModel.REPORT_NAME, name);\n try\n {\n return (T) model;\n }\n catch (ClassCastException ex)\n {\n throw new WindupException(\"The vertex is not of expected frame type \" + clazz.getName() + \": \" + model.toPrettyString());\n }\n }",
"public static boolean validate(Statement stmt) {\n try {\n Connection conn = stmt.getConnection();\n if (conn == null)\n return false;\n\n if (!conn.isClosed() && conn.isValid(10))\n return true;\n\n stmt.close();\n conn.close();\n } catch (SQLException e) {\n // this may well fail. that doesn't matter. we're just making an\n // attempt to clean up, and if we can't, that's just too bad.\n }\n return false;\n }",
"public Map<String, MBeanOperationInfo> getOperationMetadata() {\n\n MBeanOperationInfo[] operations = mBeanInfo.getOperations();\n\n Map<String, MBeanOperationInfo> operationMap = new TreeMap<String, MBeanOperationInfo>();\n for (MBeanOperationInfo operation: operations) {\n operationMap.put(operation.getName(), operation);\n }\n return operationMap;\n }",
"private void putEvent(EventType eventType) throws Exception {\n List<EventType> eventTypes = Collections.singletonList(eventType);\n\n int i;\n for (i = 0; i < retryNum; ++i) {\n try {\n monitoringService.putEvents(eventTypes);\n break;\n } catch (Exception e) {\n LOG.log(Level.SEVERE, e.getMessage(), e);\n }\n Thread.sleep(retryDelay);\n }\n\n if (i == retryNum) {\n LOG.warning(\"Could not send events to monitoring service after \" + retryNum + \" retries.\");\n throw new Exception(\"Send SERVER_START/SERVER_STOP event to SAM Server failed\");\n }\n\n }",
"public static String getJsonDatatypeFromDatatypeIri(String datatypeIri) {\n\t\tswitch (datatypeIri) {\n\t\t\tcase DatatypeIdValue.DT_ITEM:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_ITEM;\n\t\t\tcase DatatypeIdValue.DT_GLOBE_COORDINATES:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_GLOBE_COORDINATES;\n\t\t\tcase DatatypeIdValue.DT_URL:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_URL;\n\t\t\tcase DatatypeIdValue.DT_COMMONS_MEDIA:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_COMMONS_MEDIA;\n\t\t\tcase DatatypeIdValue.DT_TIME:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_TIME;\n\t\t\tcase DatatypeIdValue.DT_QUANTITY:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_QUANTITY;\n\t\t\tcase DatatypeIdValue.DT_STRING:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_STRING;\n\t\t\tcase DatatypeIdValue.DT_MONOLINGUAL_TEXT:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_MONOLINGUAL_TEXT;\n\t\t\tcase DatatypeIdValue.DT_PROPERTY:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_PROPERTY;\n\t\t\tdefault:\n\t\t\t\t//We apply the reverse algorithm of JacksonDatatypeId::getDatatypeIriFromJsonDatatype\n\t\t\t\tMatcher matcher = DATATYPE_ID_PATTERN.matcher(datatypeIri);\n\t\t\t\tif(!matcher.matches()) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"Unknown datatype: \" + datatypeIri);\n\t\t\t\t}\n\t\t\n\t\t\t\tStringBuilder jsonDatatypeBuilder = new StringBuilder();\n\t\t\t\tfor(char ch : StringUtils.uncapitalize(matcher.group(1)).toCharArray()) {\n\t\t\t\t\tif(Character.isUpperCase(ch)) {\n\t\t\t\t\t\tjsonDatatypeBuilder\n\t\t\t\t\t\t\t\t.append('-')\n\t\t\t\t\t\t\t\t.append(Character.toLowerCase(ch));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tjsonDatatypeBuilder.append(ch);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn jsonDatatypeBuilder.toString();\n\t\t}\n\t}",
"public static authenticationvserver_auditnslogpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_auditnslogpolicy_binding obj = new authenticationvserver_auditnslogpolicy_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_auditnslogpolicy_binding response[] = (authenticationvserver_auditnslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"@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 }",
"private List<Object> doQuery(\n\t\t\tSharedSessionContractImplementor session,\n\t\t\tQueryParameters qp,\n\t\t\tOgmLoadingContext ogmLoadingContext,\n\t\t\tboolean returnProxies) {\n\t\t//TODO support lock timeout\n\n\t\tint entitySpan = entityPersisters.length;\n\t\tfinal List<Object> hydratedObjects = entitySpan == 0 ? null : new ArrayList<Object>( entitySpan * 10 );\n\t\t//TODO yuk! Is there a cleaner way to access the id?\n\t\tfinal Serializable id;\n\t\t// see if we use batching first\n\t\t// then look for direct id\n\t\t// then for a tuple based result set we could extract the id\n\t\t// otherwise that's a collection so we use the collection key\n\t\tboolean loadSeveralIds = loadSeveralIds( qp );\n\t\tboolean isCollectionLoader;\n\t\tif ( loadSeveralIds ) {\n\t\t\t// need to be set to null otherwise the optionalId has precedence\n\t\t\t// and is used for all tuples regardless of their actual ids\n\t\t\tid = null;\n\t\t\tisCollectionLoader = false;\n\t\t}\n\t\telse if ( qp.getOptionalId() != null ) {\n\t\t\tid = qp.getOptionalId();\n\t\t\tisCollectionLoader = false;\n\t\t}\n\t\telse if ( ogmLoadingContext.hasResultSet() ) {\n\t\t\t// extract the ids from the tuples directly\n\t\t\tid = null;\n\t\t\tisCollectionLoader = false;\n\t\t}\n\t\telse {\n\t\t\tid = qp.getCollectionKeys()[0];\n\t\t\tisCollectionLoader = true;\n\t\t}\n\t\tTupleAsMapResultSet resultset = getResultSet( id, qp, ogmLoadingContext, session );\n\n\t\t//Todo implement lockmode\n\t\t//final LockMode[] lockModesArray = getLockModes( queryParameters.getLockOptions() );\n\t\t//FIXME should we use subselects as it's closer to this process??\n\n\t\t//TODO is resultset a good marker, or should it be an ad-hoc marker??\n\t\t//It likely all depends on what resultset ends up being\n\t\thandleEmptyCollections( qp.getCollectionKeys(), resultset, session );\n\n\t\tfinal org.hibernate.engine.spi.EntityKey[] keys = new org.hibernate.engine.spi.EntityKey[entitySpan];\n\n\t\t//for each element in resultset\n\t\t//TODO should we collect List<Object> as result? Not necessary today\n\t\tObject result = null;\n\t\tList<Object> results = new ArrayList<Object>();\n\n\t\tif ( isCollectionLoader ) {\n\t\t\tpreLoadBatchFetchingQueue( session, resultset );\n\n\t\t}\n\n\t\ttry {\n\t\t\twhile ( resultset.next() ) {\n\t\t\t\tresult = getRowFromResultSet(\n\t\t\t\t\t\tresultset,\n\t\t\t\t\t\tsession,\n\t\t\t\t\t\tqp,\n\t\t\t\t\t\togmLoadingContext,\n\t\t\t\t\t\t//lockmodeArray,\n\t\t\t\t\t\tid,\n\t\t\t\t\t\thydratedObjects,\n\t\t\t\t\t\tkeys,\n\t\t\t\t\t\treturnProxies );\n\t\t\t\tresults.add( result );\n\t\t\t}\n\t\t\t//TODO collect subselect result key\n\t\t}\n\t\tcatch ( SQLException e ) {\n\t\t\t//never happens this is not a regular ResultSet\n\t\t}\n\n\t\t//end of for each element in resultset\n\n\t\tinitializeEntitiesAndCollections( hydratedObjects, resultset, session, qp.isReadOnly( session ) );\n\t\t//TODO create subselects\n\t\treturn results;\n\t}",
"public synchronized void stop() {\n if (isRunning()) {\n running.set(false);\n DeviceFinder.getInstance().removeDeviceAnnouncementListener(announcementListener);\n dbServerPorts.clear();\n for (Client client : openClients.values()) {\n try {\n client.close();\n } catch (Exception e) {\n logger.warn(\"Problem closing \" + client + \" when stopping\", e);\n }\n }\n openClients.clear();\n useCounts.clear();\n deliverLifecycleAnnouncement(logger, false);\n }\n }"
] |
Retrieves the real subject from the underlying RDBMS. Override this
method if the object is to be materialized in a specific way.
@return The real subject of the proxy | [
"protected synchronized Object materializeSubject() throws PersistenceBrokerException\r\n\t{\r\n\t\tTemporaryBrokerWrapper tmp = getBroker();\r\n try\r\n\t\t{\r\n\t\t\tObject realSubject = tmp.broker.getObjectByIdentity(_id);\r\n\t\t\tif (realSubject == null)\r\n\t\t\t{\r\n\t\t\t\tLoggerFactory.getLogger(IndirectionHandler.class).warn(\r\n\t\t\t\t\t\t\"Can not materialize object for Identity \" + _id + \" - using PBKey \" + getBrokerKey());\r\n\t\t\t}\r\n\t\t\treturn realSubject;\r\n\t\t} catch (Exception ex)\r\n\t\t{\r\n\t\t\tthrow new PersistenceBrokerException(ex);\r\n\t\t} finally\r\n\t\t{\r\n\t\t\ttmp.close();\r\n\t\t}\r\n\t}"
] | [
"public static vpnvserver_aaapreauthenticationpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_aaapreauthenticationpolicy_binding obj = new vpnvserver_aaapreauthenticationpolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_aaapreauthenticationpolicy_binding response[] = (vpnvserver_aaapreauthenticationpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static String resolveOrOriginal(String input) {\n try {\n return resolve(input, true);\n } catch (UnresolvedExpressionException e) {\n return input;\n }\n }",
"public OTMConnection acquireConnection(PBKey pbKey)\r\n {\r\n TransactionFactory txFactory = getTransactionFactory();\r\n return txFactory.acquireConnection(pbKey);\r\n }",
"private String getContentFromPath(String sourcePath,\n HostsSourceType sourceType) throws IOException {\n\n String res = \"\";\n\n if (sourceType == HostsSourceType.LOCAL_FILE) {\n res = PcFileNetworkIoUtils.readFileContentToString(sourcePath);\n } else if (sourceType == HostsSourceType.URL) {\n res = PcFileNetworkIoUtils.readStringFromUrlGeneric(sourcePath);\n }\n return res;\n\n }",
"public Node createEmbedded(GraphDatabaseService executionEngine, Object[] columnValues) {\n\t\tMap<String, Object> params = params( columnValues );\n\t\tResult result = executionEngine.execute( getCreateEmbeddedNodeQuery(), params );\n\t\treturn singleResult( result );\n\t}",
"public void prepareForEnumeration() {\n if (isPreparer()) {\n for (NodeT node : nodeTable.values()) {\n // Prepare each node for traversal\n node.initialize();\n if (!this.isRootNode(node)) {\n // Mark other sub-DAGs as non-preparer\n node.setPreparer(false);\n }\n }\n initializeDependentKeys();\n initializeQueue();\n }\n }",
"public Class getPersistentFieldClass()\r\n {\r\n if (m_persistenceClass == null)\r\n {\r\n Properties properties = new Properties();\r\n try\r\n {\r\n this.logWarning(\"Loading properties file: \" + getPropertiesFile());\r\n properties.load(new FileInputStream(getPropertiesFile()));\r\n }\r\n catch (IOException e)\r\n {\r\n this.logWarning(\"Could not load properties file '\" + getPropertiesFile()\r\n + \"'. Using PersistentFieldDefaultImpl.\");\r\n e.printStackTrace();\r\n }\r\n try\r\n {\r\n String className = properties.getProperty(\"PersistentFieldClass\");\r\n\r\n m_persistenceClass = loadClass(className);\r\n }\r\n catch (ClassNotFoundException e)\r\n {\r\n e.printStackTrace();\r\n m_persistenceClass = PersistentFieldPrivilegedImpl.class;\r\n }\r\n logWarning(\"PersistentFieldClass: \" + m_persistenceClass.toString());\r\n }\r\n return m_persistenceClass;\r\n }",
"private boolean interpolationsDisagree(TrackPositionUpdate lastUpdate, TrackPositionUpdate currentUpdate) {\n long now = System.nanoTime();\n return Math.abs(interpolateTimeSinceUpdate(lastUpdate, now) - interpolateTimeSinceUpdate(currentUpdate, now)) >\n slack.get();\n }",
"private void initialize(Handler callbackHandler) {\n\t\tint processors = Runtime.getRuntime().availableProcessors();\n\t\tmDownloadDispatchers = new DownloadDispatcher[processors];\n\t\tmDelivery = new CallBackDelivery(callbackHandler);\n\t}"
] |
Command-line version of the classifier. See the class
comments for examples of use, and SeqClassifierFlags
for more information on supported flags. | [
"public static void main(String[] args) throws Exception {\r\n StringUtils.printErrInvocationString(\"CMMClassifier\", args);\r\n\r\n Properties props = StringUtils.argsToProperties(args);\r\n CMMClassifier cmm = new CMMClassifier<CoreLabel>(props);\r\n String testFile = cmm.flags.testFile;\r\n String textFile = cmm.flags.textFile;\r\n String loadPath = cmm.flags.loadClassifier;\r\n String serializeTo = cmm.flags.serializeTo;\r\n\r\n // cmm.crossValidateTrainAndTest(trainFile);\r\n if (loadPath != null) {\r\n cmm.loadClassifierNoExceptions(loadPath, props);\r\n } else if (cmm.flags.loadJarClassifier != null) {\r\n cmm.loadJarClassifier(cmm.flags.loadJarClassifier, props);\r\n } else if (cmm.flags.trainFile != null) {\r\n if (cmm.flags.biasedTrainFile != null) {\r\n cmm.trainSemiSup();\r\n } else {\r\n cmm.train();\r\n }\r\n } else {\r\n cmm.loadDefaultClassifier();\r\n }\r\n\r\n if (serializeTo != null) {\r\n cmm.serializeClassifier(serializeTo);\r\n }\r\n\r\n if (testFile != null) {\r\n cmm.classifyAndWriteAnswers(testFile, cmm.makeReaderAndWriter());\r\n } else if (cmm.flags.testFiles != null) {\r\n cmm.classifyAndWriteAnswers(cmm.flags.baseTestDir, cmm.flags.testFiles,\r\n cmm.makeReaderAndWriter());\r\n }\r\n\r\n if (textFile != null) {\r\n DocumentReaderAndWriter readerAndWriter =\r\n new PlainTextDocumentReaderAndWriter();\r\n cmm.classifyAndWriteAnswers(textFile, readerAndWriter);\r\n }\r\n }"
] | [
"@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 }",
"@JmxOperation(description = \"Retrieve operation status\")\n public String getStatus(int id) {\n try {\n return getOperationStatus(id).toString();\n } catch(VoldemortException e) {\n return \"No operation with id \" + id + \" found\";\n }\n }",
"private void deliverSyncCommand(byte command) {\n for (final SyncListener listener : getSyncListeners()) {\n try {\n switch (command) {\n\n case 0x01:\n listener.becomeMaster();\n\n case 0x10:\n listener.setSyncMode(true);\n break;\n\n case 0x20:\n listener.setSyncMode(false);\n break;\n\n }\n } catch (Throwable t) {\n logger.warn(\"Problem delivering sync command to listener\", t);\n }\n }\n }",
"public static String changeFirstLetterToLowerCase(String word) {\n char[] letras = word.toCharArray();\n char a = letras[0];\n letras[0] = Character.toLowerCase(a);\n return new String(letras);\n }",
"public String urlEncode(String s) {\n if (s == null || s.isEmpty()) {\n return s;\n }\n\n return URL.encodeQueryString(s);\n }",
"private ClassLoaderInterface getClassLoader() {\n\t\tMap<String, Object> application = ActionContext.getContext().getApplication();\n\t\tif (application != null) {\n\t\t\treturn (ClassLoaderInterface) application.get(ClassLoaderInterface.CLASS_LOADER_INTERFACE);\n\t\t}\n\t\treturn null;\n\t}",
"@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 }",
"public void putBeanDeployments(BeanDeploymentArchiveMapping bdaMapping) {\n for (Entry<BeanDeploymentArchive, BeanManagerImpl> entry : bdaMapping.getBdaToBeanManagerMap().entrySet()) {\n beanDeploymentArchives.put(entry.getKey(), entry.getValue());\n addBeanManager(entry.getValue());\n }\n }",
"public 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}"
] |
Get the collection of the server groups
@return Collection of active server groups | [
"public List<ServerGroup> getServerGroups() {\n ArrayList<ServerGroup> groups = new ArrayList<ServerGroup>();\n try {\n JSONObject response = new JSONObject(doGet(BASE_SERVERGROUP, null));\n JSONArray serverArray = response.getJSONArray(\"servergroups\");\n\n for (int i = 0; i < serverArray.length(); i++) {\n JSONObject jsonServerGroup = serverArray.getJSONObject(i);\n ServerGroup group = getServerGroupFromJSON(jsonServerGroup);\n groups.add(group);\n }\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n return groups;\n }"
] | [
"public double dot(Vector3d v1) {\n return x * v1.x + y * v1.y + z * v1.z;\n }",
"protected PrintResult withOpenOutputStream(final PrintAction function) throws Exception {\n final File reportFile = getReportFile();\n final Processor.ExecutionContext executionContext;\n try (FileOutputStream out = new FileOutputStream(reportFile);\n BufferedOutputStream bout = new BufferedOutputStream(out)) {\n executionContext = function.run(bout);\n }\n return new PrintResult(reportFile.length(), executionContext);\n }",
"public long getStartTime(List<IInvokedMethod> methods)\n {\n long startTime = System.currentTimeMillis();\n for (IInvokedMethod method : methods)\n {\n startTime = Math.min(startTime, method.getDate());\n }\n return startTime;\n }",
"public AsciiTable setPaddingBottomChar(Character paddingBottomChar) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingBottomChar(paddingBottomChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"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 void strokeRectangle(Rectangle rect, Color color, float linewidth) {\n\t\tstrokeRectangle(rect, color, linewidth, null);\n\t}",
"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}",
"public ItemRequest<User> findById(String user) {\n \n String path = String.format(\"/users/%s\", user);\n return new ItemRequest<User>(this, User.class, path, \"GET\");\n }",
"public static String movePath( final String file,\n final String target ) {\n final String name = new File(file).getName();\n return target.endsWith(\"/\") ? target + name : target + '/' + name;\n }"
] |
Set source url for a server
@param newUrl new URL
@param id Server ID | [
"public void setSourceUrl(String newUrl, int id) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_SERVERS +\n \" SET \" + Constants.SERVER_REDIRECT_SRC_URL + \" = ?\" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, newUrl);\n statement.setInt(2, id);\n statement.executeUpdate();\n statement.close();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }"
] | [
"public String setClassification(String classificationType) {\n Metadata metadata = new Metadata().add(Metadata.CLASSIFICATION_KEY, classificationType);\n Metadata classification = null;\n\n try {\n classification = this.createMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, \"enterprise\", metadata);\n } catch (BoxAPIException e) {\n if (e.getResponseCode() == 409) {\n metadata = new Metadata(\"enterprise\", Metadata.CLASSIFICATION_TEMPLATE_KEY);\n metadata.replace(Metadata.CLASSIFICATION_KEY, classificationType);\n classification = this.updateMetadata(metadata);\n } else {\n throw e;\n }\n }\n\n return classification.getString(Metadata.CLASSIFICATION_KEY);\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 void rotatorPushRight( int m )\n {\n double b11 = off[m];\n double b21 = diag[m+1];\n\n computeRotator(b21,-b11);\n\n // apply rotator on the right\n off[m] = 0;\n diag[m+1] = b21*c-b11*s;\n\n if( m+2 < N) {\n double b22 = off[m+1];\n off[m+1] = b22*c;\n bulge = b22*s;\n } else {\n bulge = 0;\n }\n\n// SimpleMatrix Q = createQ(m,m+1, c, s, true);\n// B=Q.mult(B);\n//\n// B.print();\n// printMatrix();\n// System.out.println(\" bulge = \"+bulge);\n// System.out.println();\n\n if( Ut != null ) {\n updateRotator(Ut,m,m+1,c,s);\n\n// SimpleMatrix.wrap(Ut).mult(B).mult(SimpleMatrix.wrap(Vt).transpose()).print();\n// printMatrix();\n// System.out.println(\"bulge = \"+bulge);\n// System.out.println();\n }\n }",
"public static scala.collection.Iterable linkedListToScalaIterable(LinkedList<?> linkedList) {\n return JavaConverters.asScalaIterableConverter(linkedList).asScala();\n }",
"public Map<String, String> resolve(Map<String, String> config) {\n config = resolveSystemEnvironmentVariables(config);\n config = resolveSystemDefaultSetup(config);\n config = resolveDockerInsideDocker(config);\n config = resolveDownloadDockerMachine(config);\n config = resolveAutoStartDockerMachine(config);\n config = resolveDefaultDockerMachine(config);\n config = resolveServerUriByOperativeSystem(config);\n config = resolveServerIp(config);\n config = resolveTlsVerification(config);\n return config;\n }",
"public static final String printDuration(Duration duration)\n {\n String result = null;\n if (duration != null)\n {\n result = duration.getDuration() + \" \" + printTimeUnits(duration.getUnits());\n }\n return result;\n }",
"public static void putUnsignedInt(ByteBuffer buffer, int index, long value) {\n buffer.putInt(index, (int) (value & 0xffffffffL));\n }",
"public static MarvinImage rgbToBinary(MarvinImage img, int threshold) {\n MarvinImage resultImage = new MarvinImage(img.getWidth(), img.getHeight(), MarvinImage.COLOR_MODEL_BINARY);\n\n for (int y = 0; y < img.getHeight(); y++) {\n for (int x = 0; x < img.getWidth(); x++) {\n int gray = (int) ((img.getIntComponent0(x, y) * 0.3) + (img.getIntComponent1(x, y) * 0.59) + (img.getIntComponent2(x, y) * 0.11));\n\n if (gray <= threshold) {\n resultImage.setBinaryColor(x, y, true);\n } else {\n resultImage.setBinaryColor(x, y, false);\n }\n }\n }\n return resultImage;\n }",
"public synchronized void start() throws SocketException {\n\n if (!isRunning()) {\n socket.set(new DatagramSocket(ANNOUNCEMENT_PORT));\n startTime.set(System.currentTimeMillis());\n deliverLifecycleAnnouncement(logger, true);\n\n final byte[] buffer = new byte[512];\n final DatagramPacket packet = new DatagramPacket(buffer, buffer.length);\n Thread receiver = new Thread(null, new Runnable() {\n @Override\n public void run() {\n boolean received;\n while (isRunning()) {\n try {\n if (getCurrentDevices().isEmpty()) {\n socket.get().setSoTimeout(60000); // We have no devices to check for timeout; block for a whole minute to check for shutdown\n } else {\n socket.get().setSoTimeout(1000); // Check every second to see if a device has vanished\n }\n socket.get().receive(packet);\n received = !ignoredAddresses.contains(packet.getAddress());\n } catch (SocketTimeoutException ste) {\n received = false;\n } catch (IOException e) {\n // Don't log a warning if the exception was due to the socket closing at shutdown.\n if (isRunning()) {\n // We did not expect to have a problem; log a warning and shut down.\n logger.warn(\"Problem reading from DeviceAnnouncement socket, stopping\", e);\n stop();\n }\n received = false;\n }\n try {\n if (received && (packet.getLength() == 54)) {\n final Util.PacketType kind = Util.validateHeader(packet, ANNOUNCEMENT_PORT);\n if (kind == Util.PacketType.DEVICE_KEEP_ALIVE) {\n // Looks like the kind of packet we need\n if (packet.getLength() < 54) {\n logger.warn(\"Ignoring too-short \" + kind.name + \" packet; expected 54 bytes, but only got \" +\n packet.getLength() + \".\");\n } else {\n if (packet.getLength() > 54) {\n logger.warn(\"Processing too-long \" + kind.name + \" packet; expected 54 bytes, but got \" +\n packet.getLength() + \".\");\n }\n DeviceAnnouncement announcement = new DeviceAnnouncement(packet);\n final boolean foundNewDevice = isDeviceNew(announcement);\n updateDevices(announcement);\n if (foundNewDevice) {\n deliverFoundAnnouncement(announcement);\n }\n }\n }\n }\n expireDevices();\n } catch (Throwable t) {\n logger.warn(\"Problem processing DeviceAnnouncement packet\", t);\n }\n }\n }\n }, \"beat-link DeviceFinder receiver\");\n receiver.setDaemon(true);\n receiver.start();\n }\n }"
] |
Set the name of the schema containing the Primavera tables.
@param schema schema name. | [
"public void setSchema(String schema)\n {\n if (schema == null)\n {\n schema = \"\";\n }\n else\n {\n if (!schema.isEmpty() && !schema.endsWith(\".\"))\n {\n schema = schema + '.';\n }\n }\n m_schema = schema;\n }"
] | [
"public static dnssuffix get(nitro_service service, String Dnssuffix) throws Exception{\n\t\tdnssuffix obj = new dnssuffix();\n\t\tobj.set_Dnssuffix(Dnssuffix);\n\t\tdnssuffix response = (dnssuffix) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static void checkRequired(OptionSet options, List<String> opts)\n throws VoldemortException {\n List<String> optCopy = Lists.newArrayList();\n for(String opt: opts) {\n if(options.has(opt)) {\n optCopy.add(opt);\n }\n }\n if(optCopy.size() < 1) {\n System.err.println(\"Please specify one of the following options:\");\n for(String opt: opts) {\n System.err.println(\"--\" + opt);\n }\n Utils.croak(\"Missing required option.\");\n }\n if(optCopy.size() > 1) {\n System.err.println(\"Conflicting options:\");\n for(String opt: optCopy) {\n System.err.println(\"--\" + opt);\n }\n Utils.croak(\"Conflicting options detected.\");\n }\n }",
"public final ReadOnlyObjectProperty<LatLongBounds> boundsProperty() {\n if (bounds == null) {\n bounds = new ReadOnlyObjectWrapper<>(getBounds());\n addStateEventHandler(MapStateEventType.idle, () -> {\n bounds.set(getBounds());\n });\n }\n return bounds.getReadOnlyProperty();\n }",
"private Duration getDuration(String value)\n {\n Duration result = null;\n\n if (value != null && value.length() != 0)\n {\n double seconds = getLong(value);\n double hours = seconds / (60 * 60);\n double days = hours / 8;\n\n if (days < 1)\n {\n result = Duration.getInstance(hours, TimeUnit.HOURS);\n }\n else\n {\n double durationDays = hours / 8;\n result = Duration.getInstance(durationDays, TimeUnit.DAYS);\n }\n }\n\n return (result);\n }",
"private void updateCurrencyFormats(ProjectProperties properties, char decimalSeparator, char thousandsSeparator)\n {\n String prefix = \"\";\n String suffix = \"\";\n String currencySymbol = quoteFormatCharacters(properties.getCurrencySymbol());\n\n switch (properties.getSymbolPosition())\n {\n case AFTER:\n {\n suffix = currencySymbol;\n break;\n }\n\n case BEFORE:\n {\n prefix = currencySymbol;\n break;\n }\n\n case AFTER_WITH_SPACE:\n {\n suffix = \" \" + currencySymbol;\n break;\n }\n\n case BEFORE_WITH_SPACE:\n {\n prefix = currencySymbol + \" \";\n break;\n }\n }\n\n StringBuilder pattern = new StringBuilder(prefix);\n pattern.append(\"#0\");\n\n int digits = properties.getCurrencyDigits().intValue();\n if (digits > 0)\n {\n pattern.append('.');\n for (int i = 0; i < digits; i++)\n {\n pattern.append(\"0\");\n }\n }\n\n pattern.append(suffix);\n\n String primaryPattern = pattern.toString();\n\n String[] alternativePatterns = new String[7];\n alternativePatterns[0] = primaryPattern + \";(\" + primaryPattern + \")\";\n pattern.insert(prefix.length(), \"#,#\");\n String secondaryPattern = pattern.toString();\n alternativePatterns[1] = secondaryPattern;\n alternativePatterns[2] = secondaryPattern + \";(\" + secondaryPattern + \")\";\n\n pattern.setLength(0);\n pattern.append(\"#0\");\n\n if (digits > 0)\n {\n pattern.append('.');\n for (int i = 0; i < digits; i++)\n {\n pattern.append(\"0\");\n }\n }\n\n String noSymbolPrimaryPattern = pattern.toString();\n alternativePatterns[3] = noSymbolPrimaryPattern;\n alternativePatterns[4] = noSymbolPrimaryPattern + \";(\" + noSymbolPrimaryPattern + \")\";\n pattern.insert(0, \"#,#\");\n String noSymbolSecondaryPattern = pattern.toString();\n alternativePatterns[5] = noSymbolSecondaryPattern;\n alternativePatterns[6] = noSymbolSecondaryPattern + \";(\" + noSymbolSecondaryPattern + \")\";\n\n m_currencyFormat.applyPattern(primaryPattern, alternativePatterns, decimalSeparator, thousandsSeparator);\n }",
"void recordOperationPrepareTimeout(final BlockingQueueOperationListener.FailedOperation<ServerOperation> failedOperation) {\n recordPreparedTask(new ServerTaskExecutor.ServerPreparedResponse(failedOperation));\n // Swap out the submitted task so we don't wait for the final result. Use a future the returns\n // prepared response\n ServerIdentity identity = failedOperation.getOperation().getIdentity();\n AsyncFuture<OperationResponse> finalResult = failedOperation.getFinalResult();\n synchronized (submittedTasks) {\n submittedTasks.put(identity, new ServerTaskExecutor.ExecutedServerRequest(identity, finalResult));\n }\n }",
"public static final PatchOperationTarget createHost(final String hostName, final ModelControllerClient client) {\n final PathElement host = PathElement.pathElement(HOST, hostName);\n final PathAddress address = PathAddress.EMPTY_ADDRESS.append(host, CORE_SERVICES);\n return new RemotePatchOperationTarget(address, client);\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 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 }"
] |
Change contrast of the image
@param contrast default is 0, pos values increase contrast, neg. values decrease contrast | [
"public BlurBuilder contrast(float contrast) {\n data.preProcessors.add(new ContrastProcessor(data.contextWrapper.getRenderScript(), Math.max(Math.min(1500.f, contrast), -1500.f)));\n return this;\n }"
] | [
"public static DMatrixRMaj symmetric(int length, double min, double max, Random rand) {\n DMatrixRMaj A = new DMatrixRMaj(length,length);\n\n symmetric(A,min,max,rand);\n\n return A;\n }",
"@NonNull\n @SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public Searcher reset() {\n lastResponsePage = 0;\n lastRequestPage = 0;\n lastResponseId = 0;\n endReached = false;\n clearFacetRefinements();\n cancelPendingRequests();\n numericRefinements.clear();\n return this;\n }",
"private String validateDuration() {\n\n if (!isValidEndTypeForPattern()) {\n return Messages.ERR_SERIALDATE_INVALID_END_TYPE_FOR_PATTERN_0;\n }\n switch (getEndType()) {\n case DATE:\n return (getStart().getTime() < (getSeriesEndDate().getTime() + DAY_IN_MILLIS))\n ? null\n : Messages.ERR_SERIALDATE_SERIES_END_BEFORE_START_0;\n case TIMES:\n return getOccurrences() > 0 ? null : Messages.ERR_SERIALDATE_INVALID_OCCURRENCES_0;\n default:\n return null;\n }\n\n }",
"public String getDbProperty(String key) {\n\n // extract the database key out of the entire key\n String databaseKey = key.substring(0, key.indexOf('.'));\n Properties databaseProperties = getDatabaseProperties().get(databaseKey);\n\n return databaseProperties.getProperty(key, \"\");\n }",
"public CustomHeadersInterceptor replaceHeader(String name, String value) {\n this.headers.put(name, new ArrayList<String>());\n this.headers.get(name).add(value);\n return this;\n }",
"private void sortFileList() {\n if (this.size() > 1) {\n Collections.sort(this.fileList, new Comparator() {\n\n public final int compare(final Object o1, final Object o2) {\n final File f1 = (File) o1;\n final File f2 = (File) o2;\n final Object[] f1TimeAndCount = backupSuffixHelper\n .backupTimeAndCount(f1.getName(), baseFile);\n final Object[] f2TimeAndCount = backupSuffixHelper\n .backupTimeAndCount(f2.getName(), baseFile);\n final long f1TimeSuffix = ((Long) f1TimeAndCount[0]).longValue();\n final long f2TimeSuffix = ((Long) f2TimeAndCount[0]).longValue();\n if ((0L == f1TimeSuffix) && (0L == f2TimeSuffix)) {\n final long f1Time = f1.lastModified();\n final long f2Time = f2.lastModified();\n if (f1Time < f2Time) {\n return -1;\n }\n if (f1Time > f2Time) {\n return 1;\n }\n return 0;\n }\n if (f1TimeSuffix < f2TimeSuffix) {\n return -1;\n }\n if (f1TimeSuffix > f2TimeSuffix) {\n return 1;\n }\n final int f1Count = ((Integer) f1TimeAndCount[1]).intValue();\n final int f2Count = ((Integer) f2TimeAndCount[1]).intValue();\n if (f1Count < f2Count) {\n return -1;\n }\n if (f1Count > f2Count) {\n return 1;\n }\n if (f1Count == f2Count) {\n if (fileHelper.isCompressed(f1)) {\n return -1;\n }\n if (fileHelper.isCompressed(f2)) {\n return 1;\n }\n }\n return 0;\n }\n });\n }\n }",
"public static cachepolicylabel get(nitro_service service, String labelname) throws Exception{\n\t\tcachepolicylabel obj = new cachepolicylabel();\n\t\tobj.set_labelname(labelname);\n\t\tcachepolicylabel response = (cachepolicylabel) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private void addAssignments(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (ResourceAssignment assignment : file.getResourceAssignments())\n {\n final ResourceAssignment a = assignment;\n MpxjTreeNode childNode = new MpxjTreeNode(a)\n {\n @Override public String toString()\n {\n Resource resource = a.getResource();\n String resourceName = resource == null ? \"(unknown resource)\" : resource.getName();\n Task task = a.getTask();\n String taskName = task == null ? \"(unknown task)\" : task.getName();\n return resourceName + \"->\" + taskName;\n }\n };\n parentNode.add(childNode);\n }\n }",
"public static String getVcsRevision(Map<String, String> env) {\n String revision = env.get(\"SVN_REVISION\");\n if (StringUtils.isBlank(revision)) {\n revision = env.get(GIT_COMMIT);\n }\n if (StringUtils.isBlank(revision)) {\n revision = env.get(\"P4_CHANGELIST\");\n }\n return revision;\n }"
] |
Find a toBuilder method, if the user has provided one. | [
"private boolean hasToBuilderMethod(\n DeclaredType builder,\n boolean isExtensible,\n Iterable<ExecutableElement> methods) {\n for (ExecutableElement method : methods) {\n if (isToBuilderMethod(builder, method)) {\n if (!isExtensible) {\n messager.printMessage(ERROR,\n \"No accessible no-args Builder constructor available to implement toBuilder\",\n method);\n }\n return true;\n }\n }\n return false;\n }"
] | [
"public static Chart getMSDLineWithActiveTransportModelChart(Trajectory t, int lagMin,\n\t\t\tint lagMax, double timelag, double diffusionCoefficient, double velocity) {\n\n\t\tdouble[] xData = new double[lagMax - lagMin + 1];\n\t\tdouble[] yData = new double[lagMax - lagMin + 1];\n\t\tdouble[] modelData = new double[lagMax - lagMin + 1];\n\t\tMeanSquaredDisplacmentFeature msdeval = new MeanSquaredDisplacmentFeature(\n\t\t\t\tt, lagMin);\n\t\tmsdeval.setTrajectory(t);\n\t\tmsdeval.setTimelag(lagMin);\n\t\tfor (int i = lagMin; i < lagMax + 1; i++) {\n\t\t\tmsdeval.setTimelag(i);\n\t\t\tdouble msdhelp = msdeval.evaluate()[0];\n\t\t\txData[i - lagMin] = i;\n\t\t\tyData[i - lagMin] = msdhelp;\n\t\t\tmodelData[i - lagMin] = Math.pow(velocity*(i*timelag), 2) + 4*diffusionCoefficient*(i*timelag);//4 * D * Math.pow(i * timelag, a);\n\t\t}\n\n\t\t// Create Chart\n\t\tChart chart = QuickChart.getChart(\"MSD Line\", \"LAG\", \"MSD\", \"MSD\",\n\t\t\t\txData, yData);\n\t\tchart.addSeries(\"y=4*D*t + (v*t)^2\", xData, modelData);\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}",
"public static Broker createBroker(int id, String brokerInfoString) {\n String[] brokerInfo = brokerInfoString.split(\":\");\n String creator = brokerInfo[0].replace('#', ':');\n String hostname = brokerInfo[1].replace('#', ':');\n String port = brokerInfo[2];\n boolean autocreated = Boolean.valueOf(brokerInfo.length > 3 ? brokerInfo[3] : \"true\");\n return new Broker(id, creator, hostname, Integer.parseInt(port), autocreated);\n }",
"private void deliverMasterYieldResponse(int fromPlayer, boolean yielded) {\n for (final MasterHandoffListener listener : getMasterHandoffListeners()) {\n try {\n listener.yieldResponse(fromPlayer, yielded);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering master yield response to listener\", t);\n }\n }\n }",
"public static clusterinstance get(nitro_service service, Long clid) throws Exception{\n\t\tclusterinstance obj = new clusterinstance();\n\t\tobj.set_clid(clid);\n\t\tclusterinstance response = (clusterinstance) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private static <T, ID> void addDropTableStatements(DatabaseType databaseType, TableInfo<T, ID> tableInfo,\n\t\t\tList<String> statements, boolean logDetails) {\n\t\tList<String> statementsBefore = new ArrayList<String>();\n\t\tList<String> statementsAfter = new ArrayList<String>();\n\t\tfor (FieldType fieldType : tableInfo.getFieldTypes()) {\n\t\t\tdatabaseType.dropColumnArg(fieldType, statementsBefore, statementsAfter);\n\t\t}\n\t\tStringBuilder sb = new StringBuilder(64);\n\t\tif (logDetails) {\n\t\t\tlogger.info(\"dropping table '{}'\", tableInfo.getTableName());\n\t\t}\n\t\tsb.append(\"DROP TABLE \");\n\t\tdatabaseType.appendEscapedEntityName(sb, tableInfo.getTableName());\n\t\tsb.append(' ');\n\t\tstatements.addAll(statementsBefore);\n\t\tstatements.add(sb.toString());\n\t\tstatements.addAll(statementsAfter);\n\t}",
"public static String workDays(ProjectCalendar input)\n {\n StringBuilder result = new StringBuilder();\n DayType[] test = input.getDays(); // get the array from MPXJ ProjectCalendar\n for (DayType i : test)\n { // go through every day in the given array\n if (i == DayType.NON_WORKING)\n {\n result.append(\"N\"); // only put N for non-working day of the week\n }\n else\n {\n result.append(\"Y\"); // Assume WORKING day unless NON_WORKING\n }\n }\n return result.toString(); // According to USACE specs., exceptions will be specified in HOLI records\n }",
"public DockerContainerObjectBuilder<T> withContainerObjectClass(Class<T> containerObjectClass) {\n if (containerObjectClass == null) {\n throw new IllegalArgumentException(\"container object class cannot be null\");\n }\n this.containerObjectClass = containerObjectClass;\n\n //First we check if this ContainerObject is defining a @CubeDockerFile in static method\n final List<Method> methodsWithCubeDockerFile =\n ReflectionUtil.getMethodsWithAnnotation(containerObjectClass, CubeDockerFile.class);\n\n if (methodsWithCubeDockerFile.size() > 1) {\n throw new IllegalArgumentException(\n String.format(\n \"More than one %s annotation found and only one was expected. Methods where annotation was found are: %s\",\n CubeDockerFile.class.getSimpleName(), methodsWithCubeDockerFile));\n }\n\n classHasMethodWithCubeDockerFile = !methodsWithCubeDockerFile.isEmpty();\n classDefinesCubeDockerFile = containerObjectClass.isAnnotationPresent(CubeDockerFile.class);\n classDefinesImage = containerObjectClass.isAnnotationPresent(Image.class);\n\n if (classHasMethodWithCubeDockerFile) {\n methodWithCubeDockerFile = methodsWithCubeDockerFile.get(0);\n boolean isMethodStatic = Modifier.isStatic(methodWithCubeDockerFile.getModifiers());\n boolean methodHasNoArguments = methodWithCubeDockerFile.getParameterCount() == 0;\n boolean methodReturnsAnArchive = Archive.class.isAssignableFrom(methodWithCubeDockerFile.getReturnType());\n if (!isMethodStatic || !methodHasNoArguments || !methodReturnsAnArchive) {\n throw new IllegalArgumentException(\n String.format(\"Method %s annotated with %s is expected to be static, no args and return %s.\",\n methodWithCubeDockerFile, CubeDockerFile.class.getSimpleName(), Archive.class.getSimpleName()));\n }\n }\n\n // User has defined @CubeDockerfile on the class and a method\n if (classHasMethodWithCubeDockerFile && classDefinesCubeDockerFile) {\n throw new IllegalArgumentException(\n String.format(\n \"More than one %s annotation found and only one was expected. Both class and method %s has the annotation.\",\n CubeDockerFile.class.getSimpleName(), methodWithCubeDockerFile));\n }\n\n // User has defined @CubeDockerfile and @Image\n if ((classHasMethodWithCubeDockerFile || classDefinesCubeDockerFile) && classDefinesImage) {\n throw new IllegalArgumentException(\n String.format(\"Container Object %s has defined %s annotation and %s annotation together.\",\n containerObjectClass.getSimpleName(), Image.class.getSimpleName(),\n CubeDockerFile.class.getSimpleName()));\n }\n\n // User has not defined either @CubeDockerfile or @Image\n if (!classDefinesCubeDockerFile && !classDefinesImage && !classHasMethodWithCubeDockerFile) {\n throw new IllegalArgumentException(\n String.format(\"Container Object %s is not annotated with either %s or %s annotations.\",\n containerObjectClass.getName(), CubeDockerFile.class.getSimpleName(), Image.class.getSimpleName()));\n }\n\n return this;\n }",
"private String formatPercentage(Number value)\n {\n return (value == null ? null : m_formats.getPercentageDecimalFormat().format(value) + \"%\");\n }",
"public Where<T, ID> exists(QueryBuilder<?, ?> subQueryBuilder) {\n\t\t// we do this to turn off the automatic addition of the ID column in the select column list\n\t\tsubQueryBuilder.enableInnerQuery();\n\t\taddClause(new Exists(new InternalQueryBuilderWrapper(subQueryBuilder)));\n\t\treturn this;\n\t}"
] |
Calling EventProducerInterceptor in case of logging faults.
@param exchange
the message exchange
@param reqFid
the FlowId
@throws Fault
the fault | [
"protected void handleINEvent(Exchange exchange, String reqFid) throws Fault {\n Message inMsg = exchange.getInMessage();\n\n EventProducerInterceptor epi = null;\n FlowIdHelper.setFlowId(inMsg, reqFid);\n\n ListIterator<Interceptor<? extends Message>> interceptors = inMsg\n .getInterceptorChain().getIterator();\n\n while (interceptors.hasNext() && epi == null) {\n Interceptor<? extends Message> interceptor = interceptors.next();\n\n if (interceptor instanceof EventProducerInterceptor) {\n epi = (EventProducerInterceptor) interceptor;\n epi.handleMessage(inMsg);\n }\n }\n }"
] | [
"final void dispatchToAppender(final LoggingEvent customLoggingEvent) {\n // wrap the LoggingEvent in a FileRollEvent to prevent recursion bug\n final FoundationFileRollingAppender appender = this.getSource();\n if (appender != null) {\n appender.append(new FileRollEvent(customLoggingEvent, this));\n }\n }",
"private static void setupFlowId(SoapMessage message) {\n String flowId = FlowIdHelper.getFlowId(message);\n\n if (flowId == null) {\n flowId = FlowIdProtocolHeaderCodec.readFlowId(message);\n }\n\n if (flowId == null) {\n flowId = FlowIdSoapCodec.readFlowId(message);\n }\n\n if (flowId == null) {\n Exchange ex = message.getExchange();\n if (null!=ex){\n Message reqMsg = ex.getOutMessage();\n if ( null != reqMsg) {\n flowId = FlowIdHelper.getFlowId(reqMsg);\n }\n }\n }\n\n if (flowId != null && !flowId.isEmpty()) {\n FlowIdHelper.setFlowId(message, flowId);\n }\n }",
"private static String getScheme(Service service, Annotation... qualifiers) {\n for (Annotation q : qualifiers) {\n if (q instanceof Scheme) {\n return ((Scheme) q).value();\n }\n }\n\n if (service.getMetadata() != null && service.getMetadata().getAnnotations() != null) {\n String s = service.getMetadata().getAnnotations().get(SERVICE_SCHEME);\n if (s != null && s.isEmpty()) {\n return s;\n }\n }\n\n return DEFAULT_SCHEME;\n }",
"private static void multBlockAdd( double []blockA, double []blockB, double []blockC,\n final int m, final int n, final int o,\n final int blockLength ) {\n// for( int i = 0; i < m; i++ ) {\n// for( int j = 0; j < o; j++ ) {\n// double val = 0;\n// for( int k = 0; k < n; k++ ) {\n// val += blockA[ i*blockLength + k]*blockB[ k*blockLength + j];\n// }\n//\n// blockC[ i*blockLength + j] += val;\n// }\n// }\n\n// int rowA = 0;\n// for( int i = 0; i < m; i++ , rowA += blockLength) {\n// for( int j = 0; j < o; j++ ) {\n// double val = 0;\n// int indexB = j;\n// int indexA = rowA;\n// int end = indexA + n;\n// for( ; indexA != end; indexA++ , indexB += blockLength ) {\n// val += blockA[ indexA ]*blockB[ indexB ];\n// }\n//\n// blockC[ rowA + j] += val;\n// }\n// }\n\n// for( int k = 0; k < n; k++ ) {\n// for( int i = 0; i < m; i++ ) {\n// for( int j = 0; j < o; j++ ) {\n// blockC[ i*blockLength + j] += blockA[ i*blockLength + k]*blockB[ k*blockLength + j];\n// }\n// }\n// }\n\n for( int k = 0; k < n; k++ ) {\n int rowB = k*blockLength;\n int endB = rowB+o;\n for( int i = 0; i < m; i++ ) {\n int indexC = i*blockLength;\n double valA = blockA[ indexC + k];\n int indexB = rowB;\n \n while( indexB != endB ) {\n blockC[ indexC++ ] += valA*blockB[ indexB++];\n }\n }\n }\n }",
"public void set(float val, Layout.Axis axis) {\n switch (axis) {\n case X:\n x = val;\n break;\n case Y:\n y = val;\n break;\n case Z:\n z = val;\n break;\n default:\n throw new RuntimeAssertion(\"Bad axis specified: %s\", axis);\n }\n }",
"public static String paramMapToString(final Map<String, String[]> parameters) {\n\n final StringBuffer result = new StringBuffer();\n for (final String key : parameters.keySet()) {\n String[] values = parameters.get(key);\n if (null == values) {\n result.append(key).append('&');\n } else {\n for (final String value : parameters.get(key)) {\n result.append(key).append('=').append(CmsEncoder.encode(value)).append('&');\n }\n }\n }\n // remove last '&'\n if (result.length() > 0) {\n result.setLength(result.length() - 1);\n }\n return result.toString();\n }",
"public void promote() {\n URL url = VERSION_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.fileID, \"current\");\n\n JsonObject jsonObject = new JsonObject();\n jsonObject.add(\"type\", \"file_version\");\n jsonObject.add(\"id\", this.getID());\n\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n request.setBody(jsonObject.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n this.parseJSON(JsonObject.readFrom(response.getJSON()));\n }",
"private String[] getColumnNames(ResultSetMetaData rsmd) throws Exception {\n ArrayList<String> names = new ArrayList<String>();\n\n // Get result set meta data\n int numColumns = rsmd.getColumnCount();\n\n // Get the column names; column indices start from 1\n for (int i = 1; i < numColumns + 1; i++) {\n String columnName = rsmd.getColumnName(i);\n\n names.add(columnName);\n }\n\n return names.toArray(new String[0]);\n }",
"@SuppressWarnings(\"unchecked\")\n public Map<String, Field> getValueAsMap() {\n return (Map<String, Field>) type.convert(getValue(), Type.MAP);\n }"
] |
This method returns the value it is passed, or null if the value
matches the nullValue argument.
@param value value under test
@param nullValue return null if value under test matches this value
@return value or null | [
"private Integer getNullOnValue(Integer value, int nullValue)\n {\n return (NumberHelper.getInt(value) == nullValue ? null : value);\n }"
] | [
"private void clearArt(DeviceAnnouncement announcement) {\n final int player = announcement.getNumber();\n // Iterate over a copy to avoid concurrent modification issues\n for (DeckReference deck : new HashSet<DeckReference>(hotCache.keySet())) {\n if (deck.player == player) {\n hotCache.remove(deck);\n if (deck.hotCue == 0) {\n deliverAlbumArtUpdate(player, null); // Inform listeners that the artwork is gone.\n }\n }\n }\n // Again iterate over a copy to avoid concurrent modification issues\n for (DataReference art : new HashSet<DataReference>(artCache.keySet())) {\n if (art.player == player) {\n artCache.remove(art);\n }\n }\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 }",
"public StitchEvent<T> nextEvent() throws IOException {\n final Event nextEvent = eventStream.nextEvent();\n if (nextEvent == null) {\n return null;\n }\n\n return StitchEvent.fromEvent(nextEvent, this.decoder);\n }",
"private void setRequestSitefilter(WbGetEntitiesActionData properties) {\n\t\tif (this.filter.excludeAllSiteLinks()\n\t\t\t\t|| this.filter.getSiteLinkFilter() == null) {\n\t\t\treturn;\n\t\t}\n\t\tproperties.sitefilter = ApiConnection.implodeObjects(this.filter\n\t\t\t\t.getSiteLinkFilter());\n\t}",
"public static int bilinearInterpolate(float x, float y, int nw, int ne, int sw, int se) {\n\t\tfloat m0, m1;\n\t\tint a0 = (nw >> 24) & 0xff;\n\t\tint r0 = (nw >> 16) & 0xff;\n\t\tint g0 = (nw >> 8) & 0xff;\n\t\tint b0 = nw & 0xff;\n\t\tint a1 = (ne >> 24) & 0xff;\n\t\tint r1 = (ne >> 16) & 0xff;\n\t\tint g1 = (ne >> 8) & 0xff;\n\t\tint b1 = ne & 0xff;\n\t\tint a2 = (sw >> 24) & 0xff;\n\t\tint r2 = (sw >> 16) & 0xff;\n\t\tint g2 = (sw >> 8) & 0xff;\n\t\tint b2 = sw & 0xff;\n\t\tint a3 = (se >> 24) & 0xff;\n\t\tint r3 = (se >> 16) & 0xff;\n\t\tint g3 = (se >> 8) & 0xff;\n\t\tint b3 = se & 0xff;\n\n\t\tfloat cx = 1.0f-x;\n\t\tfloat cy = 1.0f-y;\n\n\t\tm0 = cx * a0 + x * a1;\n\t\tm1 = cx * a2 + x * a3;\n\t\tint a = (int)(cy * m0 + y * m1);\n\n\t\tm0 = cx * r0 + x * r1;\n\t\tm1 = cx * r2 + x * r3;\n\t\tint r = (int)(cy * m0 + y * m1);\n\n\t\tm0 = cx * g0 + x * g1;\n\t\tm1 = cx * g2 + x * g3;\n\t\tint g = (int)(cy * m0 + y * m1);\n\n\t\tm0 = cx * b0 + x * b1;\n\t\tm1 = cx * b2 + x * b3;\n\t\tint b = (int)(cy * m0 + y * m1);\n\n\t\treturn (a << 24) | (r << 16) | (g << 8) | b;\n\t}",
"public ReferrerList getPhotostreamReferrers(Date date, String domain, int perPage, int page) throws FlickrException {\n return getReferrers(METHOD_GET_PHOTOSTREAM_REFERRERS, domain, null, null, date, perPage, page);\n }",
"public String getStatement() throws SQLException {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tappendSql(null, sb, new ArrayList<ArgumentHolder>());\n\t\treturn sb.toString();\n\t}",
"public static GregorianCalendar millisToCalendar(long millis) {\r\n\r\n GregorianCalendar result = new GregorianCalendar();\r\n result.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\r\n result.setTimeInMillis((long)(Math.ceil(millis / 1000) * 1000));\r\n return result;\r\n }",
"public static auditsyslogpolicy_lbvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditsyslogpolicy_lbvserver_binding obj = new auditsyslogpolicy_lbvserver_binding();\n\t\tobj.set_name(name);\n\t\tauditsyslogpolicy_lbvserver_binding response[] = (auditsyslogpolicy_lbvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Use this API to fetch authenticationradiuspolicy_authenticationvserver_binding resources of given name . | [
"public static authenticationradiuspolicy_authenticationvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationradiuspolicy_authenticationvserver_binding obj = new authenticationradiuspolicy_authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationradiuspolicy_authenticationvserver_binding response[] = (authenticationradiuspolicy_authenticationvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"private Component createConvertToPropertyBundleButton() {\n\n Button addDescriptorButton = CmsToolBar.createButton(\n FontOpenCms.SETTINGS,\n m_messages.key(Messages.GUI_CONVERT_TO_PROPERTY_BUNDLE_0));\n\n addDescriptorButton.setDisableOnClick(true);\n\n addDescriptorButton.addClickListener(new ClickListener() {\n\n private static final long serialVersionUID = 1L;\n\n public void buttonClick(ClickEvent event) {\n\n try {\n m_model.saveAsPropertyBundle();\n Notification.show(\"Conversion successful.\");\n } catch (CmsException | IOException e) {\n CmsVaadinUtils.showAlert(\"Conversion failed\", e.getLocalizedMessage(), null);\n }\n }\n });\n addDescriptorButton.setDisableOnClick(true);\n return addDescriptorButton;\n }",
"protected float computeUniformPadding(final CacheDataSet cache) {\n float axisSize = getViewPortSize(getOrientationAxis());\n float totalPadding = axisSize - cache.getTotalSize();\n float uniformPadding = totalPadding > 0 && cache.count() > 1 ?\n totalPadding / (cache.count() - 1) : 0;\n return uniformPadding;\n }",
"public void performImplicitDoubleStep(int x1, int x2 , double real , double img ) {\n double a11 = A.get(x1,x1);\n double a21 = A.get(x1+1,x1);\n double a12 = A.get(x1,x1+1);\n double a22 = A.get(x1+1,x1+1);\n double a32 = A.get(x1+2,x1+1);\n\n double p_plus_t = 2.0*real;\n double p_times_t = real*real + img*img;\n\n double b11,b21,b31;\n if( useStandardEq ) {\n b11 = (a11*a11 - p_plus_t*a11+p_times_t)/a21 + a12;\n b21 = a11+a22-p_plus_t;\n b31 = a32;\n } else {\n // this is different from the version in the book and seems in my testing to be more resilient to\n // over flow issues\n b11 = (a11*a11 - p_plus_t*a11+p_times_t) + a12*a21;\n b21 = (a11+a22-p_plus_t)*a21;\n b31 = a32*a21;\n }\n\n performImplicitDoubleStep(x1, x2, b11, b21, b31);\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<EthiopicDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<EthiopicDate>) super.localDateTime(temporal);\n }",
"private void deliverBeatAnnouncement(final Beat beat) {\n for (final MasterListener listener : getMasterListeners()) {\n try {\n listener.newBeat(beat);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering master beat announcement to listener\", t);\n }\n }\n }",
"private void setFields(Map<String, FieldType> map, MapRow row, FieldContainer container)\n {\n if (row != null)\n {\n for (Map.Entry<String, FieldType> entry : map.entrySet())\n {\n container.set(entry.getValue(), row.getObject(entry.getKey()));\n }\n }\n }",
"private void saveToPropertyVfsBundle() throws CmsException {\n\n for (Locale l : m_changedTranslations) {\n SortedProperties props = m_localizations.get(l);\n LockedFile f = m_lockedBundleFiles.get(l);\n if ((null != props) && (null != f)) {\n try {\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\n Writer writer = new OutputStreamWriter(outputStream, f.getEncoding());\n props.store(writer, null);\n byte[] contentBytes = outputStream.toByteArray();\n CmsFile file = f.getFile();\n file.setContents(contentBytes);\n String contentEncodingProperty = m_cms.readPropertyObject(\n file,\n CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING,\n false).getValue();\n if ((null == contentEncodingProperty) || !contentEncodingProperty.equals(f.getEncoding())) {\n m_cms.writePropertyObject(\n m_cms.getSitePath(file),\n new CmsProperty(\n CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING,\n f.getEncoding(),\n f.getEncoding()));\n }\n m_cms.writeFile(file);\n } catch (IOException e) {\n LOG.error(\n Messages.get().getBundle().key(\n Messages.ERR_READING_FILE_UNSUPPORTED_ENCODING_2,\n f.getFile().getRootPath(),\n f.getEncoding()),\n e);\n\n }\n }\n }\n }",
"private void deliverTrackMetadataUpdate(int player, TrackMetadata metadata) {\n if (!getTrackMetadataListeners().isEmpty()) {\n final TrackMetadataUpdate update = new TrackMetadataUpdate(player, metadata);\n for (final TrackMetadataListener listener : getTrackMetadataListeners()) {\n try {\n listener.metadataChanged(update);\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering track metadata update to listener\", t);\n }\n }\n }\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 }"
] |
Use to generate a file based on generator node. | [
"public void generateTracedFile(final IFileSystemAccess2 fsa, final String path, final CompositeGeneratorNode rootNode) {\n final GeneratorNodeProcessor.Result result = this.processor.process(rootNode);\n fsa.generateFile(path, result);\n }"
] | [
"@Override\n\tpublic IPAddress toAddress() throws UnknownHostException, HostNameException {\n\t\tIPAddress addr = resolvedAddress;\n\t\tif(addr == null && !resolvedIsNull) {\n\t\t\t//note that validation handles empty address resolution\n\t\t\tvalidate();\n\t\t\tsynchronized(this) {\n\t\t\t\taddr = resolvedAddress;\n\t\t\t\tif(addr == null && !resolvedIsNull) {\n\t\t\t\t\tif(parsedHost.isAddressString()) {\n\t\t\t\t\t\taddr = parsedHost.asAddress();\n\t\t\t\t\t\tresolvedIsNull = (addr == null);\n\t\t\t\t\t\t//note there is no need to apply prefix or mask here, it would have been applied to the address already\n\t\t\t\t\t} else {\n\t\t\t\t\t\tString strHost = parsedHost.getHost();\n\t\t\t\t\t\tif(strHost.length() == 0 && !validationOptions.emptyIsLoopback) {\n\t\t\t\t\t\t\taddr = null;\n\t\t\t\t\t\t\tresolvedIsNull = true;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t//Note we do not set resolvedIsNull, so we will attempt to resolve again if the previous attempt threw an exception\n\t\t\t\t\t\t\tInetAddress inetAddress = InetAddress.getByName(strHost);\n\t\t\t\t\t\t\tbyte bytes[] = inetAddress.getAddress();\n\t\t\t\t\t\t\tInteger networkPrefixLength = parsedHost.getNetworkPrefixLength();\n\t\t\t\t\t\t\tif(networkPrefixLength == null) {\n\t\t\t\t\t\t\t\tIPAddress mask = parsedHost.getMask();\n\t\t\t\t\t\t\t\tif(mask != null) {\n\t\t\t\t\t\t\t\t\tbyte maskBytes[] = mask.getBytes();\n\t\t\t\t\t\t\t\t\tif(maskBytes.length != bytes.length) {\n\t\t\t\t\t\t\t\t\t\tthrow new HostNameException(host, \"ipaddress.error.ipMismatch\");\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tfor(int i = 0; i < bytes.length; i++) {\n\t\t\t\t\t\t\t\t\t\tbytes[i] &= maskBytes[i];\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tnetworkPrefixLength = mask.getBlockMaskPrefixLength(true);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tIPAddressStringParameters addressParams = validationOptions.addressOptions;\n\t\t\t\t\t\t\tif(bytes.length == IPv6Address.BYTE_COUNT) {\n\t\t\t\t\t\t\t\tIPv6AddressCreator creator = addressParams.getIPv6Parameters().getNetwork().getAddressCreator();\n\t\t\t\t\t\t\t\taddr = creator.createAddressInternal(bytes, networkPrefixLength, null, this); /* address creation */\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tIPv4AddressCreator creator = addressParams.getIPv4Parameters().getNetwork().getAddressCreator();\n\t\t\t\t\t\t\t\taddr = creator.createAddressInternal(bytes, networkPrefixLength, this); /* address creation */\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tresolvedAddress = addr;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn addr;\n\t}",
"public static Message create( String text, Object data, ProcessingUnit owner )\n {\n return new SimpleMessage( text, data, owner);\n }",
"public void setAccordion(boolean accordion) {\n getElement().setAttribute(\"data-collapsible\", accordion ? CssName.ACCORDION : CssName.EXPANDABLE);\n reload();\n }",
"public static base_response update(nitro_service client, rnatparam resource) throws Exception {\n\t\trnatparam updateresource = new rnatparam();\n\t\tupdateresource.tcpproxy = resource.tcpproxy;\n\t\treturn updateresource.update_resource(client);\n\t}",
"private void updateBundleDescriptorContent() throws CmsXmlException {\n\n if (m_descContent.hasLocale(Descriptor.LOCALE)) {\n m_descContent.removeLocale(Descriptor.LOCALE);\n }\n m_descContent.addLocale(m_cms, Descriptor.LOCALE);\n\n int i = 0;\n Property<Object> descProp;\n String desc;\n Property<Object> defaultValueProp;\n String defaultValue;\n Map<String, Item> keyItemMap = getKeyItemMap();\n List<String> keys = new ArrayList<String>(keyItemMap.keySet());\n Collections.sort(keys, CmsCaseInsensitiveStringComparator.getInstance());\n for (Object key : keys) {\n if ((null != key) && !key.toString().isEmpty()) {\n\n m_descContent.addValue(m_cms, Descriptor.N_MESSAGE, Descriptor.LOCALE, i);\n i++;\n String messagePrefix = Descriptor.N_MESSAGE + \"[\" + i + \"]/\";\n\n m_descContent.getValue(messagePrefix + Descriptor.N_KEY, Descriptor.LOCALE).setStringValue(\n m_cms,\n (String)key);\n descProp = keyItemMap.get(key).getItemProperty(TableProperty.DESCRIPTION);\n if ((null != descProp) && (null != descProp.getValue())) {\n desc = descProp.getValue().toString();\n m_descContent.getValue(messagePrefix + Descriptor.N_DESCRIPTION, Descriptor.LOCALE).setStringValue(\n m_cms,\n desc);\n }\n\n defaultValueProp = keyItemMap.get(key).getItemProperty(TableProperty.DEFAULT);\n if ((null != defaultValueProp) && (null != defaultValueProp.getValue())) {\n defaultValue = defaultValueProp.getValue().toString();\n m_descContent.getValue(messagePrefix + Descriptor.N_DEFAULT, Descriptor.LOCALE).setStringValue(\n m_cms,\n defaultValue);\n }\n\n }\n }\n\n }",
"private void validate(Object object) {\n\t\tSet<ConstraintViolation<Object>> viols = validator.validate(object);\n\t\tfor (ConstraintViolation<Object> constraintViolation : viols) {\n\t\t\tif (Null.class.isAssignableFrom(constraintViolation.getConstraintDescriptor().getAnnotation().getClass())) {\n\t\t\t\tObject o = constraintViolation.getLeafBean();\n\t\t\t\tIterator<Node> iterator = constraintViolation.getPropertyPath().iterator();\n\t\t\t\tString propertyName = null;\n\t\t\t\twhile (iterator.hasNext()) {\n\t\t\t\t\tpropertyName = iterator.next().getName();\n\t\t\t\t}\n\t\t\t\tif (propertyName != null) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tPropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(o.getClass(), propertyName);\n\t\t\t\t\t\tdescriptor.getWriteMethod().invoke(o, new Object[] { null });\n\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"private void setTasks(String tasks) {\n\t\tfor (String task : tasks.split(\",\")) {\n\t\t\tif (KNOWN_TASKS.containsKey(task)) {\n\t\t\t\tthis.tasks |= KNOWN_TASKS.get(task);\n\t\t\t\tthis.taskName += (this.taskName.isEmpty() ? \"\" : \"-\") + task;\n\t\t\t} else {\n\t\t\t\tlogger.warn(\"Unsupported RDF serialization task \\\"\" + task\n\t\t\t\t\t\t+ \"\\\". Run without specifying any tasks for help.\");\n\t\t\t}\n\t\t}\n\t}",
"public static MetadataTemplate getMetadataTemplateByID(BoxAPIConnection api, String templateID) {\n\n URL url = METADATA_TEMPLATE_BY_ID_URL_TEMPLATE.build(api.getBaseURL(), templateID);\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n return new MetadataTemplate(response.getJSON());\n }",
"public void useXopAttachmentServiceWithProxy() throws Exception {\n\n final String serviceURI = \"http://localhost:\" + port + \"/services/attachments\";\n \n XopAttachmentService proxy = JAXRSClientFactory.create(serviceURI, \n XopAttachmentService.class);\n \n XopBean xop = createXopBean();\n \n System.out.println();\n System.out.println(\"Posting a XOP attachment with a proxy\");\n \n XopBean xopResponse = proxy.echoXopAttachment(xop);\n \n verifyXopResponse(xop, xopResponse);\n }"
] |
Resets all override settings for the clientUUID and disables it
@param profileId profile ID of the client
@param clientUUID UUID of the client
@throws Exception exception | [
"public void reset(int profileId, String clientUUID) throws Exception {\n PreparedStatement statement = null;\n\n // TODO: need a better way to do this than brute force.. but the iterative approach is too slow\n try (Connection sqlConnection = sqlService.getConnection()) {\n\n // first remove all enabled overrides with this client uuid\n String queryString = \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.GENERIC_CLIENT_UUID + \"= ? \" +\n \" AND \" + Constants.GENERIC_PROFILE_ID + \" = ?\";\n statement = sqlConnection.prepareStatement(queryString);\n statement.setString(1, clientUUID);\n statement.setInt(2, profileId);\n statement.executeUpdate();\n statement.close();\n\n // clean up request response table for this uuid\n queryString = \"UPDATE \" + Constants.DB_TABLE_REQUEST_RESPONSE +\n \" SET \" + Constants.REQUEST_RESPONSE_CUSTOM_REQUEST + \"=?, \"\n + Constants.REQUEST_RESPONSE_CUSTOM_RESPONSE + \"=?, \"\n + Constants.REQUEST_RESPONSE_REPEAT_NUMBER + \"=-1, \"\n + Constants.REQUEST_RESPONSE_REQUEST_ENABLED + \"=0, \"\n + Constants.REQUEST_RESPONSE_RESPONSE_ENABLED + \"=0 \"\n + \"WHERE \" + Constants.GENERIC_CLIENT_UUID + \"=? \" +\n \" AND \" + Constants.GENERIC_PROFILE_ID + \"=?\";\n statement = sqlConnection.prepareStatement(queryString);\n statement.setString(1, \"\");\n statement.setString(2, \"\");\n statement.setString(3, clientUUID);\n statement.setInt(4, profileId);\n statement.executeUpdate();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n this.updateActive(profileId, clientUUID, false);\n }"
] | [
"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 String generateDigest(InputStream stream) {\n MessageDigest digest = null;\n try {\n digest = MessageDigest.getInstance(DIGEST_ALGORITHM_SHA1);\n } catch (NoSuchAlgorithmException ae) {\n throw new BoxAPIException(\"Digest algorithm not found\", ae);\n }\n\n //Calcuate the digest using the stream.\n DigestInputStream dis = new DigestInputStream(stream, digest);\n try {\n int value = dis.read();\n while (value != -1) {\n value = dis.read();\n }\n } catch (IOException ioe) {\n throw new BoxAPIException(\"Reading the stream failed.\", ioe);\n }\n\n //Get the calculated digest for the stream\n byte[] digestBytes = digest.digest();\n return Base64.encode(digestBytes);\n }",
"public static int brightnessNTSC(int rgb) {\n\t\tint r = (rgb >> 16) & 0xff;\n\t\tint g = (rgb >> 8) & 0xff;\n\t\tint b = rgb & 0xff;\n\t\treturn (int)(r*0.299f + g*0.587f + b*0.114f);\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 }",
"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 }",
"public static java.sql.Time newTime() {\n return new java.sql.Time(System.currentTimeMillis() % DAY_MILLIS);\n }",
"public void updateBuildpackInstallations(String appName, List<String> buildpacks) {\n connection.execute(new BuildpackInstallationUpdate(appName, buildpacks), apiKey);\n }",
"public ConfigBuilder withHost(final String host) {\n if (host == null || \"\".equals(host)) {\n throw new IllegalArgumentException(\"host must not be null or empty: \" + host);\n }\n this.host = host;\n return this;\n }",
"public Token add( String word ) {\n Token t = new Token(word);\n push( t );\n return t;\n }"
] |
Starts closing the keyboard when the hits are scrolled. | [
"@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public void enableKeyboardAutoHiding() {\n keyboardListener = new OnScrollListener() {\n @Override\n public void onScrolled(RecyclerView recyclerView, int dx, int dy) {\n if (dx != 0 || dy != 0) {\n imeManager.hideSoftInputFromWindow(\n Hits.this.getWindowToken(),\n InputMethodManager.HIDE_NOT_ALWAYS);\n }\n super.onScrolled(recyclerView, dx, dy);\n }\n };\n addOnScrollListener(keyboardListener);\n }"
] | [
"protected final StyleSupplier<FeatureSource> createStyleFunction(\n final Template template,\n final String styleString) {\n return new StyleSupplier<FeatureSource>() {\n @Override\n public Style load(\n final MfClientHttpRequestFactory requestFactory,\n final FeatureSource featureSource) {\n if (featureSource == null) {\n throw new IllegalArgumentException(\"Feature source cannot be null\");\n }\n\n final String geomType = featureSource.getSchema() == null ?\n Geometry.class.getSimpleName().toLowerCase() :\n featureSource.getSchema().getGeometryDescriptor().getType().getBinding()\n .getSimpleName();\n final String styleRef = styleString != null ? styleString : geomType;\n\n final StyleParser styleParser = AbstractFeatureSourceLayerPlugin.this.parser;\n return OptionalUtils.or(\n () -> template.getStyle(styleRef),\n () -> styleParser.loadStyle(template.getConfiguration(), requestFactory, styleRef))\n .orElseGet(() -> template.getConfiguration().getDefaultStyle(geomType));\n }\n };\n }",
"public static long bytesToNumber(byte[] buffer, int start, int length) {\n long result = 0;\n for (int index = start; index < start + length; index++) {\n result = (result << 8) + unsign(buffer[index]);\n }\n return result;\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 }",
"private Map<String, String> toPayload(Map<String, Object> data) throws LocalOperationException {\n Map<String, Object> dataClone = new HashMap<String, Object>(data);\n dataClone.put(\"auth\", getAuthData());\n\n Map<String, String> payload = new HashMap<String, String>();\n payload.put(\"params\", jsonifyData(dataClone));\n\n if (transloadit.shouldSignRequest) {\n payload.put(\"signature\", getSignature(jsonifyData(dataClone)));\n }\n return payload;\n }",
"protected boolean hasContentLength() {\n boolean result = false;\n String contentLength = this.request.getHeader(RestMessageHeaders.CONTENT_LENGTH);\n if(contentLength != null) {\n try {\n Long.parseLong(contentLength);\n result = true;\n } catch(NumberFormatException nfe) {\n logger.error(\"Exception when validating put request. Incorrect content length parameter. Cannot parse this to long: \"\n + contentLength + \". Details: \" + nfe.getMessage(),\n nfe);\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Incorrect content length parameter. Cannot parse this to long: \"\n + contentLength + \". Details: \"\n + nfe.getMessage());\n }\n } else {\n logger.error(\"Error when validating put request. Missing Content-Length header.\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Missing Content-Length header\");\n }\n\n return result;\n }",
"private List<String> parseRssFeedForeCast(String feed) {\n String[] result = feed.split(\"<br />\");\n List<String> returnList = new ArrayList<String>();\n String[] result2 = result[2].split(\"<BR />\");\n\n returnList.add(result2[3] + \"\\n\");\n returnList.add(result[3] + \"\\n\");\n returnList.add(result[4] + \"\\n\");\n returnList.add(result[5] + \"\\n\");\n returnList.add(result[6] + \"\\n\");\n\n return returnList;\n }",
"public final ProcessorDependencyGraph getProcessorGraph() {\n if (this.processorGraph == null) {\n synchronized (this) {\n if (this.processorGraph == null) {\n final Map<String, Class<?>> attcls = new HashMap<>();\n for (Map.Entry<String, Attribute> attribute: this.attributes.entrySet()) {\n attcls.put(attribute.getKey(), attribute.getValue().getValueType());\n }\n this.processorGraph = this.processorGraphFactory.build(this.processors, attcls);\n }\n }\n }\n return this.processorGraph;\n }",
"public static ManagerFunctions.InputN createMultTransA() {\n return (inputs, manager) -> {\n if( inputs.size() != 2 )\n throw new RuntimeException(\"Two inputs required\");\n\n final Variable varA = inputs.get(0);\n final Variable varB = inputs.get(1);\n\n Operation.Info ret = new Operation.Info();\n\n if( varA instanceof VariableMatrix && varB instanceof VariableMatrix ) {\n\n // The output matrix or scalar variable must be created with the provided manager\n final VariableMatrix output = manager.createMatrix();\n ret.output = output;\n ret.op = new Operation(\"multTransA-mm\") {\n @Override\n public void process() {\n DMatrixRMaj mA = ((VariableMatrix)varA).matrix;\n DMatrixRMaj mB = ((VariableMatrix)varB).matrix;\n\n CommonOps_DDRM.multTransA(mA,mB,output.matrix);\n }\n };\n } else {\n throw new IllegalArgumentException(\"Expected both inputs to be a matrix\");\n }\n\n return ret;\n };\n }",
"public static void plotCharts(List<Chart> charts){\n\t\tint numRows =1;\n\t\tint numCols =1;\n\t\tif(charts.size()>1){\n\t\t\tnumRows = (int) Math.ceil(charts.size()/2.0);\n\t\t\tnumCols = 2;\n\t\t}\n\t\t\n\t final JFrame frame = new JFrame(\"\");\n\t frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);\n frame.getContentPane().setLayout(new GridLayout(numRows, numCols));\n\t for (Chart chart : charts) {\n\t if (chart != null) {\n\t JPanel chartPanel = new XChartPanel(chart);\n\t frame.add(chartPanel);\n\t }\n\t else {\n\t JPanel chartPanel = new JPanel();\n\t frame.getContentPane().add(chartPanel);\n\t }\n\n\t }\n\t // Display the window.\n frame.pack();\n frame.setVisible(true);\n\t}"
] |
Make a comparison where the operator is specified by the caller. It is up to the caller to specify an appropriate
operator for the database and that it be formatted correctly. | [
"public Where<T, ID> rawComparison(String columnName, String rawOperator, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value, rawOperator));\n\t\treturn this;\n\t}"
] | [
"public void addJobType(final String jobName, final Class<?> jobType) {\n checkJobType(jobName, jobType);\n this.jobTypes.put(jobName, jobType);\n }",
"public static base_response unset(nitro_service client, nsspparams resource, String[] args) throws Exception{\n\t\tnsspparams unsetresource = new nsspparams();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public static TestSuiteResult unmarshal(File testSuite) throws IOException {\n try (InputStream stream = new FileInputStream(testSuite)) {\n return unmarshal(stream);\n }\n }",
"public String astring(ImapRequestLineReader request) throws ProtocolException {\n char next = request.nextWordChar();\n switch (next) {\n case '\"':\n return consumeQuoted(request);\n case '{':\n return consumeLiteral(request);\n default:\n return atom(request);\n }\n }",
"public TopicList<Topic> getTopicsList(String groupId, int perPage, int page) throws FlickrException {\r\n TopicList<Topic> topicList = new TopicList<Topic>();\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_TOPICS_GET_LIST);\r\n\r\n parameters.put(\"group_id\", groupId);\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\r\n Element topicElements = response.getPayload();\r\n topicList.setPage(topicElements.getAttribute(\"page\"));\r\n topicList.setPages(topicElements.getAttribute(\"pages\"));\r\n topicList.setPerPage(topicElements.getAttribute(\"perpage\"));\r\n topicList.setTotal(topicElements.getAttribute(\"total\"));\r\n topicList.setGroupId(topicElements.getAttribute(\"group_id\"));\r\n topicList.setIconServer(Integer.parseInt(topicElements.getAttribute(\"iconserver\")));\r\n topicList.setIconFarm(Integer.parseInt(topicElements.getAttribute(\"iconfarm\")));\r\n topicList.setName(topicElements.getAttribute(\"name\"));\r\n topicList.setMembers(Integer.parseInt(topicElements.getAttribute(\"members\")));\r\n topicList.setPrivacy(Integer.parseInt(topicElements.getAttribute(\"privacy\")));\r\n topicList.setLanguage(topicElements.getAttribute(\"lang\"));\r\n topicList.setIsPoolModerated(\"1\".equals(topicElements.getAttribute(\"ispoolmoderated\")));\r\n\r\n NodeList topicNodes = topicElements.getElementsByTagName(\"topic\");\r\n for (int i = 0; i < topicNodes.getLength(); i++) {\r\n Element element = (Element) topicNodes.item(i);\r\n topicList.add(parseTopic(element));\r\n }\r\n return topicList;\r\n }",
"public static gslbvserver_spilloverpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tgslbvserver_spilloverpolicy_binding obj = new gslbvserver_spilloverpolicy_binding();\n\t\tobj.set_name(name);\n\t\tgslbvserver_spilloverpolicy_binding response[] = (gslbvserver_spilloverpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static FullTypeSignature getTypeSignature(Class<?> clazz, Class<?>[] typeArgs) {\n\t\tClassTypeSignature rawClassTypeSignature = (ClassTypeSignature) javaTypeToTypeSignature\n\t\t\t\t.getTypeSignature(clazz);\n\t\tTypeArgSignature[] typeArgSignatures = new TypeArgSignature[typeArgs.length];\n\t\tfor (int i = 0; i < typeArgs.length; i++) {\n\t\t\ttypeArgSignatures[i] = new TypeArgSignature(\n\t\t\t\t\tTypeArgSignature.NO_WILDCARD,\n\t\t\t\t\t(FieldTypeSignature) javaTypeToTypeSignature\n\t\t\t\t\t\t\t.getTypeSignature(typeArgs[i]));\n\t\t}\n\t\tClassTypeSignature classTypeSignature = new ClassTypeSignature(\n\t\t\t\trawClassTypeSignature.getBinaryName(), typeArgSignatures,\n\t\t\t\trawClassTypeSignature.getOwnerTypeSignature());\n\n\t\treturn classTypeSignature;\n\t}",
"private void deliverMediaDetailsUpdate(final MediaDetails details) {\n for (MediaDetailsListener listener : getMediaDetailsListeners()) {\n try {\n listener.detailsAvailable(details);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering media details response to listener\", t);\n }\n }\n }",
"private TimeUnit getFormat(int format)\n {\n TimeUnit result;\n if (format == 0xFFFF)\n {\n result = TimeUnit.HOURS;\n }\n else\n {\n result = MPPUtility.getWorkTimeUnits(format);\n }\n return result;\n }"
] |
add trace information for received frame | [
"private void addTraceForFrame(WebSocketFrame frame, String type) {\n\t\tMap<String, Object> trace = new LinkedHashMap<>();\n\t\ttrace.put(\"type\", type);\n\t\ttrace.put(\"direction\", \"in\");\n\t\tif (frame instanceof TextWebSocketFrame) {\n\t\t\ttrace.put(\"payload\", ((TextWebSocketFrame) frame).text());\n\t\t}\n\n\t\tif (traceEnabled) {\n\t\t\twebsocketTraceRepository.add(trace);\n\t\t}\n\t}"
] | [
"private void processOutlineCodeFields(Row parentRow) throws SQLException\n {\n Integer entityID = parentRow.getInteger(\"CODE_REF_UID\");\n Integer outlineCodeEntityID = parentRow.getInteger(\"CODE_UID\");\n\n for (ResultSetRow row : getRows(\"SELECT * FROM MSP_OUTLINE_CODES WHERE CODE_UID=?\", outlineCodeEntityID))\n {\n processOutlineCodeField(entityID, row);\n }\n }",
"public void addNotification(@Observes final DesignerNotificationEvent event) {\n if (user.getIdentifier().equals(event.getUserId())) {\n\n if (event.getNotification() != null && !event.getNotification().equals(\"openinxmleditor\")) {\n final NotificationPopupView view = new NotificationPopupView();\n activeNotifications.add(view);\n view.setPopupPosition(getMargin(),\n activeNotifications.size() * SPACING);\n\n view.setNotification(event.getNotification());\n view.setType(event.getType());\n view.setNotificationWidth(getWidth() + \"px\");\n view.show(new Command() {\n\n @Override\n public void execute() {\n //The notification has been shown and can now be removed\n deactiveNotifications.add(view);\n remove();\n }\n });\n }\n }\n }",
"void endOfRunDb()\n {\n DbConn cnx = null;\n\n try\n {\n cnx = Helpers.getNewDbSession();\n\n // Done: put inside history & remove instance from queue.\n History.create(cnx, this.ji, this.resultStatus, endDate);\n jqmlogger.trace(\"An History was just created for job instance \" + this.ji.getId());\n cnx.runUpdate(\"ji_delete_by_id\", this.ji.getId());\n cnx.commit();\n }\n catch (RuntimeException e)\n {\n endBlockDbFailureAnalysis(e);\n }\n finally\n {\n Helpers.closeQuietly(cnx);\n }\n }",
"public void checkAllRequirementsSatisfied(final String currentPath) {\n StringBuilder errors = new StringBuilder();\n\n for (Field field: this.dependantsInJson) {\n final Collection<String> requirements = this.dependantToRequirementsMap.get(field);\n if (!requirements.isEmpty()) {\n errors.append(\"\\n\");\n String type = field.getType().getName();\n if (field.getType().isArray()) {\n type = field.getType().getComponentType().getName() + \"[]\";\n }\n errors.append(\"\\t* \").append(type).append(' ').append(field.getName()).append(\" depends on \")\n .append(requirements);\n }\n }\n Assert.equals(0, errors.length(),\n \"\\nErrors were detected when analysing the @Requires dependencies of '\" +\n currentPath + \"': \" + errors);\n }",
"public String getController() {\n final StringBuilder controller = new StringBuilder();\n if (getProtocol() != null) {\n controller.append(getProtocol()).append(\"://\");\n }\n if (getHost() != null) {\n controller.append(getHost());\n } else {\n controller.append(\"localhost\");\n }\n if (getPort() > 0) {\n controller.append(':').append(getPort());\n }\n return controller.toString();\n }",
"public static servicegroup_stats[] get(nitro_service service, options option) throws Exception{\n\t\tservicegroup_stats obj = new servicegroup_stats();\n\t\tservicegroup_stats[] response = (servicegroup_stats[])obj.stat_resources(service,option);\n\t\treturn response;\n\t}",
"protected void emitWithBurstCheck(float[] particlePositions, float[] particleVelocities,\n float[] particleTimeStamps)\n {\n if ( burstMode )\n {\n if ( executeOnce )\n {\n emit(particlePositions, particleVelocities, particleTimeStamps);\n executeOnce = false;\n }\n }\n else\n {\n emit(particlePositions, particleVelocities, particleTimeStamps);\n }\n\n }",
"@Nonnull\n public static Builder builder(Revapi revapi) {\n List<String> knownExtensionIds = new ArrayList<>();\n\n addExtensionIds(revapi.getPipelineConfiguration().getApiAnalyzerTypes(), knownExtensionIds);\n addExtensionIds(revapi.getPipelineConfiguration().getTransformTypes(), knownExtensionIds);\n addExtensionIds(revapi.getPipelineConfiguration().getFilterTypes(), knownExtensionIds);\n addExtensionIds(revapi.getPipelineConfiguration().getReporterTypes(), knownExtensionIds);\n\n return new Builder(knownExtensionIds);\n }",
"public PreparedStatementCreator count(final Dialect dialect) {\n return new PreparedStatementCreator() {\n public PreparedStatement createPreparedStatement(Connection con)\n throws SQLException {\n return getPreparedStatementCreator()\n .setSql(dialect.createCountSelect(builder.toString()))\n .createPreparedStatement(con);\n }\n };\n }"
] |
Push docker image using the docker java client.
@param imageTag
@param username
@param password
@param host | [
"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 Integer convertOverrideIdentifier(String overrideIdentifier) throws Exception {\n Integer overrideId = -1;\n\n try {\n // there is an issue with parseInt where it does not parse negative values correctly\n boolean isNegative = false;\n if (overrideIdentifier.startsWith(\"-\")) {\n isNegative = true;\n overrideIdentifier = overrideIdentifier.substring(1);\n }\n overrideId = Integer.parseInt(overrideIdentifier);\n\n if (isNegative) {\n overrideId = 0 - overrideId;\n }\n } catch (NumberFormatException ne) {\n // this is OK.. just means it's not a #\n\n // split into two parts\n String className = null;\n String methodName = null;\n int lastDot = overrideIdentifier.lastIndexOf(\".\");\n className = overrideIdentifier.substring(0, lastDot);\n methodName = overrideIdentifier.substring(lastDot + 1);\n\n overrideId = OverrideService.getInstance().getOverrideIdForMethod(className, methodName);\n }\n\n return overrideId;\n }",
"@Override\n public void process() {\n if (client.isDone() || executorService.isTerminated()) {\n throw new IllegalStateException(\"Client is already stopped\");\n }\n Runnable runner = new Runnable() {\n @Override\n public void run() {\n try {\n while (!client.isDone()) {\n String msg = messageQueue.take();\n try {\n parseMessage(msg);\n } catch (Exception e) {\n logger.warn(\"Exception thrown during parsing msg \" + msg, e);\n onException(e);\n }\n }\n } catch (Exception e) {\n onException(e);\n }\n }\n };\n\n executorService.execute(runner);\n }",
"public static boolean isFolderExist(String directoryPath) {\r\n if (StringUtils.isEmpty(directoryPath)) {\r\n return false;\r\n }\r\n\r\n File dire = new File(directoryPath);\r\n return (dire.exists() && dire.isDirectory());\r\n }",
"private void fillWeekPanel() {\r\n\r\n addCheckBox(WeekOfMonth.FIRST.toString(), Messages.GUI_SERIALDATE_WEEKDAYNUMBER_1_0);\r\n addCheckBox(WeekOfMonth.SECOND.toString(), Messages.GUI_SERIALDATE_WEEKDAYNUMBER_2_0);\r\n addCheckBox(WeekOfMonth.THIRD.toString(), Messages.GUI_SERIALDATE_WEEKDAYNUMBER_3_0);\r\n addCheckBox(WeekOfMonth.FOURTH.toString(), Messages.GUI_SERIALDATE_WEEKDAYNUMBER_4_0);\r\n addCheckBox(WeekOfMonth.LAST.toString(), Messages.GUI_SERIALDATE_WEEKDAYNUMBER_5_0);\r\n }",
"private static MBeanServer setQueryExpServer(QueryExp query, MBeanServer toSet) {\n // We assume the QueryExp is a QueryEval subclass or uses the QueryEval thread local\n // mechanism to store any existing MBeanServer. If that's not the case we have no\n // way to access the old mbeanserver to let us restore it\n MBeanServer result = QueryEval.getMBeanServer();\n query.setMBeanServer(toSet);\n return result;\n }",
"public static Face createTriangle(Vertex v0, Vertex v1, Vertex v2, double minArea) {\n Face face = new Face();\n HalfEdge he0 = new HalfEdge(v0, face);\n HalfEdge he1 = new HalfEdge(v1, face);\n HalfEdge he2 = new HalfEdge(v2, face);\n\n he0.prev = he2;\n he0.next = he1;\n he1.prev = he0;\n he1.next = he2;\n he2.prev = he1;\n he2.next = he0;\n\n face.he0 = he0;\n\n // compute the normal and offset\n face.computeNormalAndCentroid(minArea);\n return face;\n }",
"@Nonnull\n public String getBody() {\n if (body == null) {\n return storage == null ? DEFAULT_BODY : DEFAULT_BODY_STORAGE;\n } else {\n return body;\n }\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 ColumnBuilder addFieldProperty(String propertyName, String value) {\n\t\tfieldProperties.put(propertyName, value);\n\t\treturn this;\n\t}"
] |
Use this API to add dnsview resources. | [
"public static base_responses add(nitro_service client, dnsview resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdnsview addresources[] = new dnsview[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dnsview();\n\t\t\t\taddresources[i].viewname = resources[i].viewname;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}"
] | [
"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 void onAttach(GVRSceneObject sceneObj)\n {\n super.onAttach(sceneObj);\n GVRComponent comp = getComponent(GVRRenderData.getComponentType());\n\n if (comp == null)\n {\n throw new IllegalStateException(\"Cannot attach a morph to a scene object without a base mesh\");\n }\n\n GVRMesh mesh = ((GVRRenderData) comp).getMesh();\n if (mesh == null)\n {\n throw new IllegalStateException(\"Cannot attach a morph to a scene object without a base mesh\");\n }\n GVRShaderData mtl = getMaterial();\n\n if ((mtl == null) ||\n !mtl.getTextureDescriptor().contains(\"blendshapeTexture\"))\n {\n throw new IllegalStateException(\"Scene object shader does not support morphing\");\n }\n copyBaseShape(mesh.getVertexBuffer());\n mtl.setInt(\"u_numblendshapes\", mNumBlendShapes);\n mtl.setFloatArray(\"u_blendweights\", mWeights);\n }",
"public static ObjectName registerMbean(String typeName, Object obj) {\n MBeanServer server = ManagementFactory.getPlatformMBeanServer();\n ObjectName name = JmxUtils.createObjectName(JmxUtils.getPackageName(obj.getClass()),\n typeName);\n registerMbean(server, JmxUtils.createModelMBean(obj), name);\n return name;\n }",
"public Map<String, Table> process(File directory, String prefix) throws IOException\n {\n String filePrefix = prefix.toUpperCase();\n Map<String, Table> tables = new HashMap<String, Table>();\n File[] files = directory.listFiles();\n if (files != null)\n {\n for (File file : files)\n {\n String name = file.getName().toUpperCase();\n if (!name.startsWith(filePrefix))\n {\n continue;\n }\n\n int typeIndex = name.lastIndexOf('.') - 3;\n String type = name.substring(typeIndex, typeIndex + 3);\n TableDefinition definition = TABLE_DEFINITIONS.get(type);\n if (definition != null)\n {\n Table table = new Table();\n TableReader reader = new TableReader(definition);\n reader.read(file, table);\n tables.put(type, table);\n //dumpCSV(type, definition, table);\n }\n }\n }\n return tables;\n }",
"private GraphicalIndicatorCriteria processCriteria(FieldType type)\n {\n GraphicalIndicatorCriteria criteria = new GraphicalIndicatorCriteria(m_properties);\n criteria.setLeftValue(type);\n\n int indicatorType = MPPUtility.getInt(m_data, m_dataOffset);\n m_dataOffset += 4;\n criteria.setIndicator(indicatorType);\n\n if (m_dataOffset + 4 < m_data.length)\n {\n int operatorValue = MPPUtility.getInt(m_data, m_dataOffset);\n m_dataOffset += 4;\n TestOperator operator = (operatorValue == 0 ? TestOperator.IS_ANY_VALUE : TestOperator.getInstance(operatorValue - 0x3E7));\n criteria.setOperator(operator);\n\n if (operator != TestOperator.IS_ANY_VALUE)\n {\n processOperandValue(0, type, criteria);\n\n if (operator == TestOperator.IS_WITHIN || operator == TestOperator.IS_NOT_WITHIN)\n {\n processOperandValue(1, type, criteria);\n }\n }\n }\n\n return (criteria);\n }",
"protected View postDeclineView() {\n\t\treturn new TopLevelWindowRedirect() {\n\t\t\t@Override\n\t\t\tprotected String getRedirectUrl(Map<String, ?> model) {\n\t\t\t\treturn postDeclineUrl;\n\t\t\t}\n\t\t};\n\t}",
"public static base_response delete(nitro_service client, String labelname) throws Exception {\n\t\tdnspolicylabel deleteresource = new dnspolicylabel();\n\t\tdeleteresource.labelname = labelname;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"public static void setIndex(Matcher matcher, int idx) {\n int count = getCount(matcher);\n if (idx < -count || idx >= count) {\n throw new IndexOutOfBoundsException(\"index is out of range \" + (-count) + \"..\" + (count - 1) + \" (index = \" + idx + \")\");\n }\n if (idx == 0) {\n matcher.reset();\n } else if (idx > 0) {\n matcher.reset();\n for (int i = 0; i < idx; i++) {\n matcher.find();\n }\n } else if (idx < 0) {\n matcher.reset();\n idx += getCount(matcher);\n for (int i = 0; i < idx; i++) {\n matcher.find();\n }\n }\n }",
"@Override\n public boolean shouldRetry(int retryCount, Response response) {\n int code = response.code();\n //CHECKSTYLE IGNORE MagicNumber FOR NEXT 2 LINES\n return retryCount < this.retryCount\n && (code == 408 || (code >= 500 && code != 501 && code != 505));\n }"
] |
Transforms the category path of a category to the category.
@return a map from root or site path to category. | [
"public Map<String, CmsCategory> getReadCategory() {\n\n if (null == m_categories) {\n m_categories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n public Object transform(Object categoryPath) {\n\n try {\n CmsCategoryService catService = CmsCategoryService.getInstance();\n return catService.localizeCategory(\n m_cms,\n catService.readCategory(m_cms, (String)categoryPath, getRequestContext().getUri()),\n m_cms.getRequestContext().getLocale());\n } catch (CmsException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n return null;\n }\n }\n\n });\n }\n return m_categories;\n }"
] | [
"public void addExtraInfo(String key, Object value) {\n // Turn extraInfo into map\n Map<String, Object> infoMap = (HashMap<String, Object>)getMapFromJSON(extraInfo);\n // Add value\n infoMap.put(key, value);\n\n // Turn back into string\n extraInfo = getJSONFromMap(infoMap);\n }",
"protected boolean hasContentType() {\n\n boolean result = false;\n if(this.request.getHeader(RestMessageHeaders.CONTENT_TYPE) != null) {\n result = true;\n } else {\n logger.error(\"Error when validating put request. Missing Content-Type header.\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Missing Content-Type header\");\n }\n return result;\n }",
"public static void logLong(String TAG, String longString) {\n InputStream is = new ByteArrayInputStream( longString.getBytes() );\n @SuppressWarnings(\"resource\")\n Scanner scan = new Scanner(is);\n while (scan.hasNextLine()) {\n Log.v(TAG, scan.nextLine());\n }\n }",
"protected Connection newConnectionFromDataSource(JdbcConnectionDescriptor jcd)\r\n throws LookupException\r\n {\r\n Connection retval = null;\r\n // use JNDI lookup\r\n DataSource ds = jcd.getDataSource();\r\n\r\n if (ds == null)\r\n {\r\n // [tomdz] Would it suffice to store the datasources only at the JCDs ?\r\n // Only possible problem would be serialization of the JCD because\r\n // the data source object in the JCD does not 'survive' this\r\n ds = (DataSource) dataSourceCache.get(jcd.getDatasourceName());\r\n }\r\n try\r\n {\r\n if (ds == null)\r\n {\r\n /**\r\n * this synchronization block won't be a big deal as we only look up\r\n * new datasources not found in the map.\r\n */\r\n synchronized (dataSourceCache)\r\n {\r\n InitialContext ic = new InitialContext();\r\n ds = (DataSource) ic.lookup(jcd.getDatasourceName());\r\n /**\r\n * cache the datasource lookup.\r\n */\r\n dataSourceCache.put(jcd.getDatasourceName(), ds);\r\n }\r\n }\r\n if (jcd.getUserName() == null)\r\n {\r\n retval = ds.getConnection();\r\n }\r\n else\r\n {\r\n retval = ds.getConnection(jcd.getUserName(), jcd.getPassWord());\r\n }\r\n }\r\n catch (SQLException sqlEx)\r\n {\r\n log.error(\"SQLException thrown while trying to get Connection from Datasource (\" +\r\n jcd.getDatasourceName() + \")\", sqlEx);\r\n throw new LookupException(\"SQLException thrown while trying to get Connection from Datasource (\" +\r\n jcd.getDatasourceName() + \")\", sqlEx);\r\n }\r\n catch (NamingException namingEx)\r\n {\r\n log.error(\"Naming Exception while looking up DataSource (\" + jcd.getDatasourceName() + \")\", namingEx);\r\n throw new LookupException(\"Naming Exception while looking up DataSource (\" + jcd.getDatasourceName() +\r\n \")\", namingEx);\r\n }\r\n // initialize connection\r\n initializeJdbcConnection(retval, jcd);\r\n if(log.isDebugEnabled()) log.debug(\"Create new connection using DataSource: \"+retval);\r\n return retval;\r\n }",
"private String getHostHeaderForHost(String hostName) {\n List<ServerRedirect> servers = serverRedirectService.tableServers(requestInformation.get().client.getId());\n for (ServerRedirect server : servers) {\n if (server.getSrcUrl().compareTo(hostName) == 0) {\n String hostHeader = server.getHostHeader();\n if (hostHeader == null || hostHeader.length() == 0) {\n return null;\n }\n return hostHeader;\n }\n }\n return null;\n }",
"private static void listHierarchy(ProjectFile file)\n {\n for (Task task : file.getChildTasks())\n {\n System.out.println(\"Task: \" + task.getName() + \"\\t\" + task.getStart() + \"\\t\" + task.getFinish());\n listHierarchy(task, \" \");\n }\n\n System.out.println();\n }",
"public static base_response update(nitro_service client, snmpmanager resource) throws Exception {\n\t\tsnmpmanager updateresource = new snmpmanager();\n\t\tupdateresource.ipaddress = resource.ipaddress;\n\t\tupdateresource.netmask = resource.netmask;\n\t\tupdateresource.domainresolveretry = resource.domainresolveretry;\n\t\treturn updateresource.update_resource(client);\n\t}",
"private InputStream prepareInputStream(InputStream stream) throws IOException\n {\n InputStream result;\n BufferedInputStream bis = new BufferedInputStream(stream);\n readHeaderProperties(bis);\n if (isCompressed())\n {\n result = new InflaterInputStream(bis);\n }\n else\n {\n result = bis;\n }\n return result;\n }",
"private void createPropertyVfsBundleFiles() throws CmsIllegalArgumentException, CmsLoaderException, CmsException {\n\n String bundleFileBasePath = m_sitepath + m_basename + \"_\";\n for (Locale l : m_localizations.keySet()) {\n CmsResource res = m_cms.createResource(\n bundleFileBasePath + l.toString(),\n OpenCms.getResourceManager().getResourceType(\n CmsMessageBundleEditorTypes.BundleType.PROPERTY.toString()));\n m_bundleFiles.put(l, res);\n LockedFile file = LockedFile.lockResource(m_cms, res);\n file.setCreated(true);\n m_lockedBundleFiles.put(l, file);\n m_changedTranslations.add(l);\n }\n\n }"
] |
Add the set with given bundles to the "Require-Bundle" main attribute.
@param requiredBundles The set with all bundles to add. | [
"public void addRequiredBundles(Set<String> requiredBundles) {\n\t\taddRequiredBundles(requiredBundles.toArray(new String[requiredBundles.size()]));\n\t}"
] | [
"public static BoxRetentionPolicyAssignment.Info createAssignmentToEnterprise(BoxAPIConnection api,\r\n String policyID) {\r\n return createAssignment(api, policyID, new JsonObject().add(\"type\", TYPE_ENTERPRISE), null);\r\n }",
"public static Boolean assertFalse(Boolean value, String message) {\n if (Boolean.valueOf(value))\n throw new IllegalStateException(message);\n return value;\n }",
"public void identifyNode(int nodeId) throws SerialInterfaceException {\n\t\tSerialMessage newMessage = new SerialMessage(nodeId, SerialMessage.SerialMessageClass.IdentifyNode, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.IdentifyNode, SerialMessage.SerialMessagePriority.High);\n \tbyte[] newPayload = { (byte) nodeId };\n \tnewMessage.setMessagePayload(newPayload);\n \tthis.enqueue(newMessage);\n\t}",
"private void deleteByQuery(Query query, ClassDescriptor cld) throws PersistenceBrokerException\n {\n if (logger.isDebugEnabled())\n {\n logger.debug(\"deleteByQuery \" + cld.getClassNameOfObject() + \", \" + query);\n }\n\n if (query instanceof QueryBySQL)\n {\n String sql = ((QueryBySQL) query).getSql();\n this.dbAccess.executeUpdateSQL(sql, cld);\n }\n else\n {\n // if query is Identity based transform it to a criteria based query first\n if (query instanceof QueryByIdentity)\n {\n QueryByIdentity qbi = (QueryByIdentity) query;\n Object oid = qbi.getExampleObject();\n // make sure it's an Identity\n if (!(oid instanceof Identity))\n {\n oid = serviceIdentity().buildIdentity(oid);\n }\n query = referencesBroker.getPKQuery((Identity) oid);\n }\n\n if (!cld.isInterface())\n {\n this.dbAccess.executeDelete(query, cld);\n }\n\n // if class is an extent, we have to delete all extent classes too\n String lastUsedTable = cld.getFullTableName();\n if (cld.isExtent())\n {\n Iterator extents = getDescriptorRepository().getAllConcreteSubclassDescriptors(cld).iterator();\n\n while (extents.hasNext())\n {\n ClassDescriptor extCld = (ClassDescriptor) extents.next();\n\n // read same table only once\n if (!extCld.getFullTableName().equals(lastUsedTable))\n {\n lastUsedTable = extCld.getFullTableName();\n this.dbAccess.executeDelete(query, extCld);\n }\n }\n }\n\n }\n }",
"public void abortExternalTx(TransactionImpl odmgTrans)\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"abortExternTransaction was called\");\r\n if (odmgTrans == null) return;\r\n TxBuffer buf = (TxBuffer) txRepository.get();\r\n Transaction extTx = buf != null ? buf.getExternTx() : null;\r\n try\r\n {\r\n if (extTx != null && extTx.getStatus() == Status.STATUS_ACTIVE)\r\n {\r\n if(log.isDebugEnabled())\r\n {\r\n log.debug(\"Set extern transaction to rollback\");\r\n }\r\n extTx.setRollbackOnly();\r\n }\r\n }\r\n catch (Exception ignore)\r\n {\r\n }\r\n txRepository.set(null);\r\n }",
"public void release(Contextual<T> contextual, T instance) {\n synchronized (dependentInstances) {\n for (ContextualInstance<?> dependentInstance : dependentInstances) {\n // do not destroy contextual again, since it's just being destroyed\n if (contextual == null || !(dependentInstance.getContextual().equals(contextual))) {\n destroy(dependentInstance);\n }\n }\n }\n if (resourceReferences != null) {\n for (ResourceReference<?> reference : resourceReferences) {\n reference.release();\n }\n }\n }",
"@Override\n public ImageSource apply(ImageSource input) {\n int w = input.getWidth();\n int h = input.getHeight();\n\n MatrixSource output = new MatrixSource(input);\n\n Vector3 n = new Vector3(0, 0, 1);\n\n for (int y = 0; y < h; y++) {\n for (int x = 0; x < w; x++) {\n\n if (x < border || x == w - border || y < border || y == h - border) {\n output.setRGB(x, y, VectorHelper.Z_NORMAL);\n continue;\n }\n\n float s0 = input.getR(x - 1, y + 1);\n float s1 = input.getR(x, y + 1);\n float s2 = input.getR(x + 1, y + 1);\n float s3 = input.getR(x - 1, y);\n float s5 = input.getR(x + 1, y);\n float s6 = input.getR(x - 1, y - 1);\n float s7 = input.getR(x, y - 1);\n float s8 = input.getR(x + 1, y - 1);\n\n float nx = -(s2 - s0 + 2 * (s5 - s3) + s8 - s6);\n float ny = -(s6 - s0 + 2 * (s7 - s1) + s8 - s2);\n\n n.set(nx, ny, scale);\n n.nor();\n\n int rgb = VectorHelper.vectorToColor(n);\n output.setRGB(x, y, rgb);\n }\n }\n\n return new MatrixSource(output);\n }",
"public static Map<FieldType, String> getDefaultResourceFieldMap()\n {\n Map<FieldType, String> map = new LinkedHashMap<FieldType, String>();\n\n map.put(ResourceField.UNIQUE_ID, \"rsrc_id\");\n map.put(ResourceField.GUID, \"guid\");\n map.put(ResourceField.NAME, \"rsrc_name\");\n map.put(ResourceField.CODE, \"employee_code\");\n map.put(ResourceField.EMAIL_ADDRESS, \"email_addr\");\n map.put(ResourceField.NOTES, \"rsrc_notes\");\n map.put(ResourceField.CREATED, \"create_date\");\n map.put(ResourceField.TYPE, \"rsrc_type\");\n map.put(ResourceField.INITIALS, \"rsrc_short_name\");\n map.put(ResourceField.PARENT_ID, \"parent_rsrc_id\");\n\n return map;\n }",
"protected void setColumnsFinalWidth() {\n log.debug(\"Setting columns final width.\");\n float factor;\n int printableArea = report.getOptions().getColumnWidth();\n\n //Create a list with only the visible columns.\n List visibleColums = getVisibleColumns();\n\n\n if (report.getOptions().isUseFullPageWidth()) {\n int columnsWidth = 0;\n int notRezisableWidth = 0;\n\n //Store in a variable the total with of all visible columns\n for (Object visibleColum : visibleColums) {\n AbstractColumn col = (AbstractColumn) visibleColum;\n columnsWidth += col.getWidth();\n if (col.isFixedWidth())\n notRezisableWidth += col.getWidth();\n }\n\n\n factor = (float) (printableArea - notRezisableWidth) / (float) (columnsWidth - notRezisableWidth);\n\n log.debug(\"printableArea = \" + printableArea\n + \", columnsWidth = \" + columnsWidth\n + \", columnsWidth = \" + columnsWidth\n + \", notRezisableWidth = \" + notRezisableWidth\n + \", factor = \" + factor);\n\n int acumulated = 0;\n int colFinalWidth;\n\n //Select the non-resizable columns\n Collection resizableColumns = CollectionUtils.select(visibleColums, new Predicate() {\n public boolean evaluate(Object arg0) {\n return !((AbstractColumn) arg0).isFixedWidth();\n }\n\n });\n\n //Finally, set the new width to the resizable columns\n for (Iterator iter = resizableColumns.iterator(); iter.hasNext(); ) {\n AbstractColumn col = (AbstractColumn) iter.next();\n\n if (!iter.hasNext()) {\n col.setWidth(printableArea - notRezisableWidth - acumulated);\n } else {\n colFinalWidth = (new Float(col.getWidth() * factor)).intValue();\n acumulated += colFinalWidth;\n col.setWidth(colFinalWidth);\n }\n }\n }\n\n // If the columns width changed, the X position must be setted again.\n int posx = 0;\n for (Object visibleColum : visibleColums) {\n AbstractColumn col = (AbstractColumn) visibleColum;\n col.setPosX(posx);\n posx += col.getWidth();\n }\n }"
] |
Convert a geometry class to a layer type.
@param geometryClass
JTS geometry class
@return Geomajas layer type | [
"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}"
] | [
"public static boolean hasValidContentAdditionParameterDefined(ModelNode operation) {\n for (String s : DeploymentAttributes.MANAGED_CONTENT_ATTRIBUTES.keySet()) {\n if (operation.hasDefined(s)) {\n return true;\n }\n }\n return false;\n }",
"public static void writeShortString(ByteBuffer buffer, String s) {\n if (s == null) {\n buffer.putShort((short) -1);\n } else if (s.length() > Short.MAX_VALUE) {\n throw new IllegalArgumentException(\"String exceeds the maximum size of \" + Short.MAX_VALUE + \".\");\n } else {\n byte[] data = getBytes(s); //topic support non-ascii character\n buffer.putShort((short) data.length);\n buffer.put(data);\n }\n }",
"protected Renderer build() {\n validateAttributes();\n\n Renderer renderer;\n if (isRecyclable(convertView, content)) {\n renderer = recycle(convertView, content);\n } else {\n renderer = createRenderer(content, parent);\n }\n return renderer;\n }",
"public static CuratorFramework newAppCurator(FluoConfiguration config) {\n return newCurator(config.getAppZookeepers(), config.getZookeeperTimeout(),\n config.getZookeeperSecret());\n }",
"private CostRateTableEntry getCostRateTableEntry(Date date)\n {\n CostRateTableEntry result;\n\n CostRateTable table = getCostRateTable();\n if (table == null)\n {\n Resource resource = getResource();\n result = new CostRateTableEntry(resource.getStandardRate(), TimeUnit.HOURS, resource.getOvertimeRate(), TimeUnit.HOURS, resource.getCostPerUse(), null);\n }\n else\n {\n if (table.size() == 1)\n {\n result = table.get(0);\n }\n else\n {\n result = table.getEntryByDate(date);\n }\n }\n\n return result;\n }",
"public static List<Integer> asList(int[] a) {\r\n List<Integer> result = new ArrayList<Integer>(a.length);\r\n for (int i = 0; i < a.length; i++) {\r\n result.add(Integer.valueOf(a[i]));\r\n }\r\n return result;\r\n }",
"private final void replyErrors(final String errorMessage,\n final String stackTrace, final String statusCode,\n final int statusCodeInt) {\n reply(true, errorMessage, stackTrace, statusCode, statusCodeInt,\n PcConstants.NA, null);\n\n }",
"public static LuaCondition isNull(LuaValue value) {\n LuaAstExpression expression;\n if (value instanceof LuaLocal) {\n expression = new LuaAstLocal(((LuaLocal) value).getName());\n } else {\n throw new IllegalArgumentException(\"Unexpected value type: \" + value.getClass().getName());\n }\n return new LuaCondition(new LuaAstNot(expression));\n }",
"public String getWrappingHint(String fieldName) {\n if (isEmpty()) {\n return \"\";\n }\n\n return String.format(\" You can use this expression: %s(%s(%s))\",\n formatMethod(wrappingMethodOwnerName, wrappingMethodName, \"\"),\n formatMethod(copyMethodOwnerName, copyMethodName, copyTypeParameterName),\n fieldName);\n }"
] |
Add a source and destination.
@param source Source path to be routed. Routed path can have named wild-card pattern with braces "{}".
@param destination Destination of the path. | [
"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 }"
] | [
"@Override\n public DiscordianDate date(int prolepticYear, int month, int dayOfMonth) {\n return DiscordianDate.of(prolepticYear, month, dayOfMonth);\n }",
"public PhotoContext getContext(String photoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_CONTEXT);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n PhotoContext photoContext = new PhotoContext();\r\n Collection<Element> payload = response.getPayloadCollection();\r\n for (Element payloadElement : payload) {\r\n String tagName = payloadElement.getTagName();\r\n if (tagName.equals(\"prevphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(payloadElement.getAttribute(\"id\"));\r\n photo.setSecret(payloadElement.getAttribute(\"secret\"));\r\n photo.setTitle(payloadElement.getAttribute(\"title\"));\r\n photo.setFarm(payloadElement.getAttribute(\"farm\"));\r\n photo.setUrl(payloadElement.getAttribute(\"url\"));\r\n photoContext.setPreviousPhoto(photo);\r\n } else if (tagName.equals(\"nextphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(payloadElement.getAttribute(\"id\"));\r\n photo.setSecret(payloadElement.getAttribute(\"secret\"));\r\n photo.setTitle(payloadElement.getAttribute(\"title\"));\r\n photo.setFarm(payloadElement.getAttribute(\"farm\"));\r\n photo.setUrl(payloadElement.getAttribute(\"url\"));\r\n photoContext.setNextPhoto(photo);\r\n }\r\n }\r\n return photoContext;\r\n }",
"public static void checkFloatNotNaNOrInfinity(String parameterName,\n float data) {\n if (Float.isNaN(data) || Float.isInfinite(data)) {\n throw Exceptions.IllegalArgument(\n \"%s should never be NaN or Infinite.\", parameterName);\n }\n }",
"protected void removeInvalidChildren() {\n\n if (getLoadState() == LoadState.LOADED) {\n List<CmsSitemapTreeItem> toDelete = new ArrayList<CmsSitemapTreeItem>();\n for (int i = 0; i < getChildCount(); i++) {\n CmsSitemapTreeItem item = (CmsSitemapTreeItem)getChild(i);\n CmsUUID id = item.getEntryId();\n if ((id != null) && (CmsSitemapView.getInstance().getController().getEntryById(id) == null)) {\n toDelete.add(item);\n }\n }\n for (CmsSitemapTreeItem deleteItem : toDelete) {\n m_children.removeItem(deleteItem);\n }\n }\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 synchronized void withTransaction(Closure closure) throws SQLException {\n boolean savedCacheConnection = cacheConnection;\n cacheConnection = true;\n Connection connection = null;\n boolean savedAutoCommit = true;\n try {\n connection = createConnection();\n savedAutoCommit = connection.getAutoCommit();\n connection.setAutoCommit(false);\n callClosurePossiblyWithConnection(closure, connection);\n connection.commit();\n } catch (SQLException e) {\n handleError(connection, e);\n throw e;\n } catch (RuntimeException e) {\n handleError(connection, e);\n throw e;\n } catch (Error e) {\n handleError(connection, e);\n throw e;\n } catch (Exception e) {\n handleError(connection, e);\n throw new SQLException(\"Unexpected exception during transaction\", e);\n } finally {\n if (connection != null) {\n try {\n connection.setAutoCommit(savedAutoCommit);\n }\n catch (SQLException e) {\n LOG.finest(\"Caught exception resetting auto commit: \" + e.getMessage() + \" - continuing\");\n }\n }\n cacheConnection = false;\n closeResources(connection, null);\n cacheConnection = savedCacheConnection;\n if (dataSource != null && !cacheConnection) {\n useConnection = null;\n }\n }\n }",
"public static Processor<DataSinkTask> sink(DataSink dataSink, int parallelism, String description, UserConfig taskConf, ActorSystem system) {\n io.gearpump.streaming.Processor<DataSinkTask> p = DataSinkProcessor.apply(dataSink, parallelism, description, taskConf, system);\n return new Processor(p);\n }",
"public ItemRequest<Task> dependencies(String task) {\n \n String path = String.format(\"/tasks/%s/dependencies\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"GET\");\n }",
"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 }"
] |
Generate a weighted score based on position for matches of URI parts.
The matches are weighted in descending order from left to right.
Exact match is weighted higher than group match, and group match is weighted higher than wildcard match.
@param requestUriParts the parts of request URI
@param destUriParts the parts of destination URI
@return weighted score | [
"private long getWeightedMatchScore(Iterable<String> requestUriParts, Iterable<String> destUriParts) {\n // The score calculated below is a base 5 number\n // The score will have one digit for one part of the URI\n // This will allow for 27 parts in the path since log (Long.MAX_VALUE) to base 5 = 27.13\n // We limit the number of parts in the path to 25 using MAX_PATH_PARTS constant above to avoid overflow during\n // score calculation\n long score = 0;\n for (Iterator<String> rit = requestUriParts.iterator(), dit = destUriParts.iterator();\n rit.hasNext() && dit.hasNext(); ) {\n String requestPart = rit.next();\n String destPart = dit.next();\n if (requestPart.equals(destPart)) {\n score = (score * 5) + 4;\n } else if (PatternPathRouterWithGroups.GROUP_PATTERN.matcher(destPart).matches()) {\n score = (score * 5) + 3;\n } else {\n score = (score * 5) + 2;\n }\n }\n return score;\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 boolean isMaterialized(Object object)\r\n {\r\n IndirectionHandler handler = getIndirectionHandler(object);\r\n\r\n return handler == null || handler.alreadyMaterialized();\r\n }",
"private static void validateIfAvroSchema(SerializerDefinition serializerDef) {\n if(serializerDef.getName().equals(AVRO_GENERIC_VERSIONED_TYPE_NAME)\n || serializerDef.getName().equals(AVRO_GENERIC_TYPE_NAME)) {\n SchemaEvolutionValidator.validateAllAvroSchemas(serializerDef);\n // check backwards compatibility if needed\n if(serializerDef.getName().equals(AVRO_GENERIC_VERSIONED_TYPE_NAME)) {\n SchemaEvolutionValidator.checkSchemaCompatibility(serializerDef);\n }\n }\n }",
"public static nsrollbackcmd get(nitro_service service) throws Exception{\n\t\tnsrollbackcmd obj = new nsrollbackcmd();\n\t\tnsrollbackcmd[] response = (nsrollbackcmd[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public static void init(Context cx, Scriptable scope, boolean sealed)\n throws RhinoException {\n JSAdapter obj = new JSAdapter(cx.newObject(scope));\n obj.setParentScope(scope);\n obj.setPrototype(getFunctionPrototype(scope));\n obj.isPrototype = true;\n ScriptableObject.defineProperty(scope, \"JSAdapter\", obj,\n ScriptableObject.DONTENUM);\n }",
"public Tokenizer<Tree> getTokenizer(final Reader r) {\r\n return new AbstractTokenizer<Tree>() {\r\n TreeReader tr = trf.newTreeReader(r);\r\n @Override\r\n public Tree getNext() {\r\n try {\r\n return tr.readTree();\r\n }\r\n catch(IOException e) {\r\n System.err.println(\"Error in reading tree.\");\r\n return null;\r\n }\r\n }\r\n };\r\n }",
"public static base_response unset(nitro_service client, sslocspresponder resource, String[] args) throws Exception{\n\t\tsslocspresponder unsetresource = new sslocspresponder();\n\t\tunsetresource.name = resource.name;\n\t\tunsetresource.insertclientcert = resource.insertclientcert;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public ILog getOrCreateLog(String topic, int partition) throws IOException {\n final int configPartitionNumber = getPartition(topic);\n if (partition >= configPartitionNumber) {\n throw new IOException(\"partition is bigger than the number of configuration: \" + configPartitionNumber);\n }\n boolean hasNewTopic = false;\n Pool<Integer, Log> parts = getLogPool(topic, partition);\n if (parts == null) {\n Pool<Integer, Log> found = logs.putIfNotExists(topic, new Pool<Integer, Log>());\n if (found == null) {\n hasNewTopic = true;\n }\n parts = logs.get(topic);\n }\n //\n Log log = parts.get(partition);\n if (log == null) {\n log = createLog(topic, partition);\n Log found = parts.putIfNotExists(partition, log);\n if (found != null) {\n Closer.closeQuietly(log, logger);\n log = found;\n } else {\n logger.info(format(\"Created log for [%s-%d], now create other logs if necessary\", topic, partition));\n final int configPartitions = getPartition(topic);\n for (int i = 0; i < configPartitions; i++) {\n getOrCreateLog(topic, i);\n }\n }\n }\n if (hasNewTopic && config.getEnableZookeeper()) {\n topicRegisterTasks.add(new TopicTask(TopicTask.TaskType.CREATE, topic));\n }\n return log;\n }",
"public static Bitmap decodeStream(InputStream stream, boolean closeStream) {\n return AsyncBitmapTexture.decodeStream(stream,\n AsyncBitmapTexture.glMaxTextureSize,\n AsyncBitmapTexture.glMaxTextureSize, true, null, closeStream);\n }"
] |
Unlock the given region. Does not report failures. | [
"public static void munlock(Pointer addr, long len) {\n\n if(Delegate.munlock(addr, new NativeLong(len)) != 0) {\n if(logger.isDebugEnabled())\n logger.debug(\"munlocking failed with errno:\" + errno.strerror());\n } else {\n if(logger.isDebugEnabled())\n logger.debug(\"munlocking region\");\n }\n }"
] | [
"public static lbroute[] get(nitro_service service) throws Exception{\n\t\tlbroute obj = new lbroute();\n\t\tlbroute[] response = (lbroute[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static void closeWithWarning(Closeable c) {\n if (c != null) {\n try {\n c.close();\n } catch (IOException e) {\n LOG.warning(\"Caught exception during close(): \" + e);\n }\n }\n }",
"public final Iterator<AbstractTraceRegion> leafIterator() {\n\t\tif (nestedRegions == null)\n\t\t\treturn Collections.<AbstractTraceRegion> singleton(this).iterator();\n\t\treturn new LeafIterator(this);\n\t}",
"public static bridgegroup_vlan_binding[] get(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\tbridgegroup_vlan_binding response[] = (bridgegroup_vlan_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void update(int width, int height, byte[] grayscaleData)\n {\n NativeBitmapImage.updateFromMemory(getNative(), width, height, grayscaleData);\n }",
"public List<Task> getActiveTasks() {\n InputStream response = null;\n URI uri = new URIBase(getBaseUri()).path(\"_active_tasks\").build();\n try {\n response = couchDbClient.get(uri);\n return getResponseList(response, couchDbClient.getGson(), DeserializationTypes.TASKS);\n } finally {\n close(response);\n }\n }",
"public Integer getOverrideIdForMethod(String className, String methodName) {\n Integer overrideId = null;\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_OVERRIDE +\n \" WHERE \" + Constants.OVERRIDE_CLASS_NAME + \" = ?\" +\n \" AND \" + Constants.OVERRIDE_METHOD_NAME + \" = ?\"\n );\n query.setString(1, className);\n query.setString(2, methodName);\n results = query.executeQuery();\n\n if (results.next()) {\n overrideId = results.getInt(Constants.GENERIC_ID);\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 (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n\n return overrideId;\n }",
"public static base_response delete(nitro_service client, String domain) throws Exception {\n\t\tdnstxtrec deleteresource = new dnstxtrec();\n\t\tdeleteresource.domain = domain;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"private void allClustersEqual(final List<String> clusterUrls) {\n Validate.notEmpty(clusterUrls, \"clusterUrls cannot be null\");\n // If only one clusterUrl return immediately\n if (clusterUrls.size() == 1)\n return;\n AdminClient adminClientLhs = adminClientPerCluster.get(clusterUrls.get(0));\n Cluster clusterLhs = adminClientLhs.getAdminClientCluster();\n for (int index = 1; index < clusterUrls.size(); index++) {\n AdminClient adminClientRhs = adminClientPerCluster.get(clusterUrls.get(index));\n Cluster clusterRhs = adminClientRhs.getAdminClientCluster();\n if (!areTwoClustersEqual(clusterLhs, clusterRhs))\n throw new VoldemortException(\"Cluster \" + clusterLhs.getName()\n + \" is not the same as \" + clusterRhs.getName());\n }\n }"
] |
Set the week days the events should occur.
@param weekDays the week days to set. | [
"public final void setWeekDays(SortedSet<WeekDay> weekDays) {\n\n m_weekDays.clear();\n if (null != weekDays) {\n m_weekDays.addAll(weekDays);\n }\n }"
] | [
"public static gslbservice_stats[] get(nitro_service service) throws Exception{\n\t\tgslbservice_stats obj = new gslbservice_stats();\n\t\tgslbservice_stats[] response = (gslbservice_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}",
"public List<ColumnProperty> getAllFields(){\n\t\tArrayList<ColumnProperty> l = new ArrayList<ColumnProperty>();\n\t\tfor (AbstractColumn abstractColumn : this.getColumns()) {\n\t\t\tif (abstractColumn instanceof SimpleColumn && !(abstractColumn instanceof ExpressionColumn)) {\n\t\t\t\tl.add(((SimpleColumn)abstractColumn).getColumnProperty());\n\t\t\t}\n\t\t}\n\t\tl.addAll(this.getFields());\n\n\t\treturn l;\n\t\t\n\t}",
"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 }",
"private ArrayList handleDependentCollections(Identity oid, Object obj,\r\n Object[] origCollections, Object[] newCollections,\r\n Object[] newCollectionsOfObjects)\r\n throws LockingException\r\n {\r\n ClassDescriptor mif = _pb.getClassDescriptor(obj.getClass());\r\n Collection colDescs = mif.getCollectionDescriptors();\r\n ArrayList newObjects = new ArrayList();\r\n int count = 0;\r\n\r\n for (Iterator it = colDescs.iterator(); it.hasNext(); count++)\r\n {\r\n CollectionDescriptor cds = (CollectionDescriptor) it.next();\r\n\r\n if (cds.getOtmDependent())\r\n {\r\n ArrayList origList = (origCollections == null ? null\r\n : (ArrayList) origCollections[count]);\r\n ArrayList newList = (ArrayList) newCollections[count];\r\n\r\n if (origList != null)\r\n {\r\n for (Iterator it2 = origList.iterator(); it2.hasNext(); )\r\n {\r\n Identity origOid = (Identity) it2.next();\r\n\r\n if ((newList == null) || !newList.contains(origOid))\r\n {\r\n markDelete(origOid, oid, true);\r\n }\r\n }\r\n }\r\n\r\n if (newList != null)\r\n {\r\n int countElem = 0;\r\n for (Iterator it2 = newList.iterator(); it2.hasNext(); countElem++)\r\n {\r\n Identity newOid = (Identity) it2.next();\r\n\r\n if ((origList == null) || !origList.contains(newOid))\r\n {\r\n ContextEntry entry = (ContextEntry) _objects.get(newOid);\r\n\r\n if (entry == null)\r\n {\r\n ArrayList relCol = (ArrayList)\r\n newCollectionsOfObjects[count];\r\n Object relObj = relCol.get(countElem);\r\n insertInternal(newOid, relObj, LockType.WRITE_LOCK,\r\n true, null, new Stack());\r\n newObjects.add(newOid);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n return newObjects;\r\n }",
"public static BoxAPIConnection getTransactionConnection(String accessToken, String scope, String resource) {\n BoxAPIConnection apiConnection = new BoxAPIConnection(accessToken);\n\n URL url;\n try {\n url = new URL(apiConnection.getTokenURL());\n } catch (MalformedURLException e) {\n assert false : \"An invalid token URL indicates a bug in the SDK.\";\n throw new RuntimeException(\"An invalid token URL indicates a bug in the SDK.\", e);\n }\n\n String urlParameters;\n try {\n urlParameters = String.format(\"grant_type=%s&subject_token=%s&subject_token_type=%s&scope=%s\", GRANT_TYPE,\n URLEncoder.encode(accessToken, \"UTF-8\"), SUBJECT_TOKEN_TYPE, URLEncoder.encode(scope, \"UTF-8\"));\n\n if (resource != null) {\n urlParameters += \"&resource=\" + URLEncoder.encode(resource, \"UTF-8\");\n }\n } catch (UnsupportedEncodingException e) {\n throw new BoxAPIException(\n \"An error occurred while attempting to encode url parameters for a transactional token request\"\n );\n }\n\n BoxAPIRequest request = new BoxAPIRequest(apiConnection, url, \"POST\");\n request.shouldAuthenticate(false);\n request.setBody(urlParameters);\n\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n final String fileToken = responseJSON.get(\"access_token\").asString();\n BoxTransactionalAPIConnection transactionConnection = new BoxTransactionalAPIConnection(fileToken);\n transactionConnection.setExpires(responseJSON.get(\"expires_in\").asLong() * 1000);\n\n return transactionConnection;\n }",
"public void putEvents(List<Event> events) {\n List<Event> filteredEvents = filterEvents(events);\n executeHandlers(filteredEvents);\n for (Event event : filteredEvents) {\n persistenceHandler.writeEvent(event);\n }\n }",
"private void deliverDeviceUpdate(final DeviceUpdate update) {\n for (DeviceUpdateListener listener : getUpdateListeners()) {\n try {\n listener.received(update);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering device update to listener\", t);\n }\n }\n }",
"@Deprecated\n @SuppressWarnings(\"deprecation\")\n public void push(String eventName, HashMap<String, Object> chargeDetails,\n ArrayList<HashMap<String, Object>> items)\n throws InvalidEventNameException {\n // This method is for only charged events\n if (!eventName.equals(Constants.CHARGED_EVENT)) {\n throw new InvalidEventNameException(\"Not a charged event\");\n }\n CleverTapAPI cleverTapAPI = weakReference.get();\n if(cleverTapAPI == null){\n Logger.d(\"CleverTap Instance is null.\");\n } else {\n cleverTapAPI.pushChargedEvent(chargeDetails, items);\n }\n }",
"public String getPromotionDetailsJsonModel() throws IOException {\n final PromotionEvaluationReport sampleReport = new PromotionEvaluationReport();\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.UNPROMOTED_MSG, \"com.acme.secure-smh:core-relay:1.2.0\"), MAJOR);\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.DO_NOT_USE_MSG, \"com.google.guava:guava:20.0\"), MAJOR);\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.MISSING_LICENSE_MSG, \"org.apache.maven.wagon:wagon-webdav-jackrabbit:2.12\"), MINOR);\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.UNACCEPTABLE_LICENSE_MSG,\n \"aopaliance:aopaliance:1.0 licensed as Attribution-ShareAlike 2.5 Generic, \" +\n \"org.polyjdbc:polyjdbc0.7.1 licensed as Creative Commons Attribution-ShareAlike 3.0 Unported License\"),\n MINOR);\n\n sampleReport.addMessage(PromotionReportTranslator.SNAPSHOT_VERSION_MSG, Tag.CRITICAL);\n return JsonUtils.serialize(sampleReport);\n }"
] |
Expects a height mat as input
@param input - A grayscale height map
@return edges | [
"@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 }"
] | [
"public static server_service_binding[] get(nitro_service service, String name) throws Exception{\n\t\tserver_service_binding obj = new server_service_binding();\n\t\tobj.set_name(name);\n\t\tserver_service_binding response[] = (server_service_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public double dot(Vector3d v1) {\n return x * v1.x + y * v1.y + z * v1.z;\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 }",
"public static appfwprofile_stats get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_stats obj = new appfwprofile_stats();\n\t\tobj.set_name(name);\n\t\tappfwprofile_stats response = (appfwprofile_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"public void mergeSubtree(final OperationTransformerRegistry targetRegistry, final Map<PathAddress, ModelVersion> subTree) {\n for(Map.Entry<PathAddress, ModelVersion> entry: subTree.entrySet()) {\n mergeSubtree(targetRegistry, entry.getKey(), entry.getValue());\n }\n }",
"@AsParameterConverter\n\tpublic Trader retrieveTrader(String name) {\n\t\tfor (Trader trader : traders) {\n\t\t\tif (trader.getName().equals(name)) {\n\t\t\t\treturn trader;\n\t\t\t}\n\t\t}\n\t\treturn mockTradePersister().retrieveTrader(name);\n\t}",
"public boolean equivalent(Element otherElement, boolean logging) {\n\t\tif (eventable.getElement().equals(otherElement)) {\n\t\t\tif (logging) {\n\t\t\t\tLOGGER.info(\"Element equal\");\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tif (eventable.getElement().equalAttributes(otherElement)) {\n\t\t\tif (logging) {\n\t\t\t\tLOGGER.info(\"Element attributes equal\");\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tif (eventable.getElement().equalId(otherElement)) {\n\t\t\tif (logging) {\n\t\t\t\tLOGGER.info(\"Element ID equal\");\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tif (!eventable.getElement().getText().equals(\"\")\n\t\t\t\t&& eventable.getElement().equalText(otherElement)) {\n\n\t\t\tif (logging) {\n\t\t\t\tLOGGER.info(\"Element text equal\");\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}",
"public void clearSelections() {\n for (CheckableViewHolder vh : mCheckedVisibleViewHolders) {\n vh.checkbox.setChecked(false);\n }\n mCheckedVisibleViewHolders.clear();\n mCheckedItems.clear();\n }",
"protected String addDependency(TaskGroup.HasTaskGroup dependency) {\n Objects.requireNonNull(dependency);\n this.taskGroup().addDependencyTaskGroup(dependency.taskGroup());\n return dependency.taskGroup().key();\n }"
] |
Assign float value within allowed range of [0,infinity) to initializeOnly SFFloat field named spacing.
@param newValue | [
"public void setString(String[] newValue) {\n if ( newValue != null ) {\n this.string.setValue(newValue.length, newValue);\n }\n }"
] | [
"@Inject(\"struts.json.action.fileProtocols\")\n\tpublic void setFileProtocols(String fileProtocols) {\n\t\tif (StringUtils.isNotBlank(fileProtocols)) {\n\t\t\tthis.fileProtocols = TextParseUtil.commaDelimitedStringToSet(fileProtocols);\n\t\t}\n\t}",
"public HiveShellContainer evaluateStatement(List<? extends Script> scripts, Object target, TemporaryFolder temporaryFolder, Statement base) throws Throwable {\n container = null;\n FileUtil.setPermission(temporaryFolder.getRoot(), FsPermission.getDirDefault());\n try {\n LOGGER.info(\"Setting up {} in {}\", getName(), temporaryFolder.getRoot().getAbsolutePath());\n container = createHiveServerContainer(scripts, target, temporaryFolder);\n base.evaluate();\n return container;\n } finally {\n tearDown();\n }\n }",
"public ClassDescriptor getSuperClassDescriptor()\r\n {\r\n if (!m_superCldSet)\r\n {\r\n if(getBaseClass() != null)\r\n {\r\n m_superCld = getRepository().getDescriptorFor(getBaseClass());\r\n if(m_superCld.isAbstract() || m_superCld.isInterface())\r\n {\r\n throw new MetadataException(\"Super class mapping only work for real class, but declared super class\" +\r\n \" is an interface or is abstract. Declared class: \" + m_superCld.getClassNameOfObject());\r\n }\r\n }\r\n m_superCldSet = true;\r\n }\r\n\r\n return m_superCld;\r\n }",
"public static long get1D(DMatrixRMaj A , int n ) {\n\n long before = System.currentTimeMillis();\n\n double total = 0;\n\n for( int iter = 0; iter < n; iter++ ) {\n\n int index = 0;\n for( int i = 0; i < A.numRows; i++ ) {\n int end = index+A.numCols;\n while( index != end ) {\n total += A.get(index++);\n }\n }\n }\n\n long after = System.currentTimeMillis();\n\n // print to ensure that ensure that an overly smart compiler does not optimize out\n // the whole function and to show that both produce the same results.\n System.out.println(total);\n\n return after-before;\n }",
"private void processCalendarHours(byte[] data, ProjectCalendar defaultCalendar, ProjectCalendar cal, boolean isBaseCalendar)\n {\n // Dump out the calendar related data and fields.\n //MPPUtility.dataDump(data, true, false, false, false, true, false, true);\n\n int offset;\n ProjectCalendarHours hours;\n int periodIndex;\n int index;\n int defaultFlag;\n int periodCount;\n Date start;\n long duration;\n Day day;\n List<DateRange> dateRanges = new ArrayList<DateRange>(5);\n\n for (index = 0; index < 7; index++)\n {\n offset = getCalendarHoursOffset() + (60 * index);\n defaultFlag = data == null ? 1 : MPPUtility.getShort(data, offset);\n day = Day.getInstance(index + 1);\n\n if (defaultFlag == 1)\n {\n if (isBaseCalendar)\n {\n if (defaultCalendar == null)\n {\n cal.setWorkingDay(day, DEFAULT_WORKING_WEEK[index]);\n if (cal.isWorkingDay(day))\n {\n hours = cal.addCalendarHours(Day.getInstance(index + 1));\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING);\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON);\n }\n }\n else\n {\n boolean workingDay = defaultCalendar.isWorkingDay(day);\n cal.setWorkingDay(day, workingDay);\n if (workingDay)\n {\n hours = cal.addCalendarHours(Day.getInstance(index + 1));\n for (DateRange range : defaultCalendar.getHours(day))\n {\n hours.addRange(range);\n }\n }\n }\n }\n else\n {\n cal.setWorkingDay(day, DayType.DEFAULT);\n }\n }\n else\n {\n dateRanges.clear();\n\n periodIndex = 0;\n periodCount = MPPUtility.getShort(data, offset + 2);\n while (periodIndex < periodCount)\n {\n int startOffset = offset + 8 + (periodIndex * 2);\n start = MPPUtility.getTime(data, startOffset);\n int durationOffset = offset + 20 + (periodIndex * 4);\n duration = MPPUtility.getDuration(data, durationOffset);\n Date end = new Date(start.getTime() + duration);\n dateRanges.add(new DateRange(start, end));\n ++periodIndex;\n }\n\n if (dateRanges.isEmpty())\n {\n cal.setWorkingDay(day, false);\n }\n else\n {\n cal.setWorkingDay(day, true);\n hours = cal.addCalendarHours(Day.getInstance(index + 1));\n\n for (DateRange range : dateRanges)\n {\n hours.addRange(range);\n }\n }\n }\n }\n }",
"public static String[] slice(String[] strings, int begin, int length) {\n\t\tString[] result = new String[length];\n\t\tSystem.arraycopy( strings, begin, result, 0, length );\n\t\treturn result;\n\t}",
"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 }",
"public static Status from(Set<ServiceReference> serviceReferencesBound, Set<ServiceReference> serviceReferencesHandled) {\n if (serviceReferencesBound == null && serviceReferencesHandled == null) {\n throw new IllegalArgumentException(\"Cannot create a status with serviceReferencesBound == null\" +\n \"and serviceReferencesHandled == null\");\n } else if (serviceReferencesBound == null) {\n throw new IllegalArgumentException(\"Cannot create a status with serviceReferencesBound == null\");\n } else if (serviceReferencesHandled == null) {\n throw new IllegalArgumentException(\"Cannot create a status with serviceReferencesHandled == null\");\n }\n return new Status(serviceReferencesBound, serviceReferencesHandled);\n }",
"@SuppressWarnings(\"unchecked\") private Object formatType(DataType type, Object value)\n {\n switch (type)\n {\n case DATE:\n {\n value = formatDateTime(value);\n break;\n }\n\n case CURRENCY:\n {\n value = formatCurrency((Number) value);\n break;\n }\n\n case UNITS:\n {\n value = formatUnits((Number) value);\n break;\n }\n\n case PERCENTAGE:\n {\n value = formatPercentage((Number) value);\n break;\n }\n\n case ACCRUE:\n {\n value = formatAccrueType((AccrueType) value);\n break;\n }\n\n case CONSTRAINT:\n {\n value = formatConstraintType((ConstraintType) value);\n break;\n }\n\n case WORK:\n case DURATION:\n {\n value = formatDuration(value);\n break;\n }\n\n case RATE:\n {\n value = formatRate((Rate) value);\n break;\n }\n\n case PRIORITY:\n {\n value = formatPriority((Priority) value);\n break;\n }\n\n case RELATION_LIST:\n {\n value = formatRelationList((List<Relation>) value);\n break;\n }\n\n case TASK_TYPE:\n {\n value = formatTaskType((TaskType) value);\n break;\n }\n\n default:\n {\n break;\n }\n }\n\n return (value);\n }"
] |
all objects in list1 that are not in list2
@param <T>
@param list1
First collection
@param list2
Second collection
@return The collection difference list1 - list2 | [
"public static <T> Collection<T> diff(Collection<T> list1, Collection<T> list2) {\r\n Collection<T> diff = new ArrayList<T>();\r\n for (T t : list1) {\r\n if (!list2.contains(t)) {\r\n diff.add(t);\r\n }\r\n }\r\n return diff;\r\n }"
] | [
"public RangeInfo subListBorders(int size) {\n if (inclusive == null) throw new IllegalStateException(\"Should not call subListBorders on a non-inclusive aware IntRange\");\n int tempFrom = from;\n if (tempFrom < 0) {\n tempFrom += size;\n }\n int tempTo = to;\n if (tempTo < 0) {\n tempTo += size;\n }\n if (tempFrom > tempTo) {\n return new RangeInfo(inclusive ? tempTo : tempTo + 1, tempFrom + 1, true);\n }\n return new RangeInfo(tempFrom, inclusive ? tempTo + 1 : tempTo, false);\n }",
"public static int getProfileIdFromPathID(int path_id) throws Exception {\n return (Integer) SQLService.getInstance().getFromTable(Constants.GENERIC_PROFILE_ID, Constants.GENERIC_ID, path_id, Constants.DB_TABLE_PATH);\n }",
"@Api\n\tpublic void setUrl(String url) throws LayerException {\n\t\ttry {\n\t\t\tthis.url = url;\n\t\t\tMap<String, Object> params = new HashMap<String, Object>();\n\t\t\tparams.put(\"url\", url);\n\t\t\tDataStore store = DataStoreFactory.create(params);\n\t\t\tsetDataStore(store);\n\t\t} catch (IOException ioe) {\n\t\t\tthrow new LayerException(ioe, ExceptionCode.INVALID_SHAPE_FILE_URL, url);\n\t\t}\n\t}",
"public void addValue(double value)\n {\n if (dataSetSize == dataSet.length)\n {\n // Increase the capacity of the array.\n int newLength = (int) (GROWTH_RATE * dataSetSize);\n double[] newDataSet = new double[newLength];\n System.arraycopy(dataSet, 0, newDataSet, 0, dataSetSize);\n dataSet = newDataSet;\n }\n dataSet[dataSetSize] = value;\n updateStatsWithNewValue(value);\n ++dataSetSize;\n }",
"public static sslocspresponder[] get(nitro_service service) throws Exception{\n\t\tsslocspresponder obj = new sslocspresponder();\n\t\tsslocspresponder[] response = (sslocspresponder[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void readRelationships()\n {\n for (MapRow row : m_tables.get(\"REL\"))\n {\n Task predecessor = m_activityMap.get(row.getString(\"PREDECESSOR_ACTIVITY_ID\"));\n Task successor = m_activityMap.get(row.getString(\"SUCCESSOR_ACTIVITY_ID\"));\n if (predecessor != null && successor != null)\n {\n Duration lag = row.getDuration(\"LAG_VALUE\");\n RelationType type = row.getRelationType(\"LAG_TYPE\");\n\n successor.addPredecessor(predecessor, type, lag);\n }\n }\n }",
"protected static void sendInitSQL(Connection connection, String initSQL) throws SQLException{\r\n\t\t// fetch any configured setup sql.\r\n\t\tif (initSQL != null){\r\n\t\t\tStatement stmt = null;\r\n\t\t\ttry{\r\n\t\t\t\tstmt = connection.createStatement();\r\n\t\t\t\tstmt.execute(initSQL);\r\n\t\t\t\tif (testSupport){ // only to aid code coverage, normally set to false\r\n\t\t\t\t\tstmt = null;\r\n\t\t\t\t}\r\n\t\t\t} finally{\r\n\t\t\t\tif (stmt != null){\r\n\t\t\t\t\tstmt.close();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"@Override\n public void map(GenericData.Record record,\n AvroCollector<Pair<ByteBuffer, ByteBuffer>> collector,\n Reporter reporter) throws IOException {\n\n byte[] keyBytes = null;\n byte[] valBytes = null;\n Object keyRecord = null;\n Object valRecord = null;\n try {\n keyRecord = record.get(keyField);\n valRecord = record.get(valField);\n keyBytes = keySerializer.toBytes(keyRecord);\n valBytes = valueSerializer.toBytes(valRecord);\n\n this.collectorWrapper.setCollector(collector);\n this.mapper.map(keyBytes, valBytes, this.collectorWrapper);\n\n recordCounter++;\n } catch (OutOfMemoryError oom) {\n logger.error(oomErrorMessage(reporter));\n if (keyBytes == null) {\n logger.error(\"keyRecord caused OOM!\");\n } else {\n logger.error(\"keyRecord: \" + keyRecord);\n logger.error(\"valRecord: \" + (valBytes == null ? \"caused OOM\" : valRecord));\n }\n throw new VoldemortException(oomErrorMessage(reporter), oom);\n }\n }",
"protected void\t\tcalcLocal(Bone bone, int parentId)\n {\n if (parentId < 0)\n {\n bone.LocalMatrix.set(bone.WorldMatrix);\n return;\n }\n\t/*\n\t * WorldMatrix = WorldMatrix(parent) * LocalMatrix\n\t * LocalMatrix = INVERSE[ WorldMatrix(parent) ] * WorldMatrix\n\t */\n getWorldMatrix(parentId, mTempMtxA);\t// WorldMatrix(par)\n mTempMtxA.invert();\t\t\t\t\t // INVERSE[ WorldMatrix(parent) ]\n mTempMtxA.mul(bone.WorldMatrix, bone.LocalMatrix); // LocalMatrix = INVERSE[ WorldMatrix(parent) ] * WorldMatrix\n }"
] |
Gets an enhanced protection domain for a proxy based on the given protection domain.
@param domain the given protection domain
@return protection domain enhanced with "accessDeclaredMembers" runtime permission | [
"ProtectionDomain getProtectionDomainForProxy(ProtectionDomain domain) {\n if (domain.getCodeSource() == null) {\n // no codesource to cache on\n return create(domain);\n }\n ProtectionDomain proxyProtectionDomain = proxyProtectionDomains.get(domain.getCodeSource());\n if (proxyProtectionDomain == null) {\n // as this is not atomic create() may be called multiple times for the same domain\n // we ignore that\n proxyProtectionDomain = create(domain);\n ProtectionDomain existing = proxyProtectionDomains.putIfAbsent(domain.getCodeSource(), proxyProtectionDomain);\n if (existing != null) {\n proxyProtectionDomain = existing;\n }\n }\n return proxyProtectionDomain;\n }"
] | [
"public Map<Double, SingleAssetEuropeanOptionProductDescriptor> getDescriptors(LocalDate referenceDate){\n\n\t\tint numberOfStrikes = strikes.length;\n\t\tHashMap<Double, SingleAssetEuropeanOptionProductDescriptor> descriptors = new HashMap<Double, SingleAssetEuropeanOptionProductDescriptor>();\n\n\t\tLocalDate maturityDate = FloatingpointDate.getDateFromFloatingPointDate(referenceDate, maturity);\n\t\tfor(int i = 0; i< numberOfStrikes; i++) {\n\t\t\tdescriptors.put(strikes[i], new SingleAssetEuropeanOptionProductDescriptor(underlyingName, maturityDate, strikes[i]));\n\t\t}\n\n\t\treturn descriptors;\n\t}",
"private static List<Class<?>> getClassHierarchy(Class<?> clazz) {\n\t\tList<Class<?>> hierarchy = new ArrayList<Class<?>>( 4 );\n\n\t\tfor ( Class<?> current = clazz; current != null; current = current.getSuperclass() ) {\n\t\t\thierarchy.add( current );\n\t\t}\n\n\t\treturn hierarchy;\n\t}",
"public OpenShiftAssistantTemplate parameter(String name, String value) {\n parameterValues.put(name, value);\n return this;\n }",
"public synchronized Set<RegistrationPoint> getRegistrationPoints() {\n Set<RegistrationPoint> result = new HashSet<>();\n for (List<RegistrationPoint> registrationPoints : registrationPoints.values()) {\n result.addAll(registrationPoints);\n }\n return Collections.unmodifiableSet(result);\n }",
"@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n\tprivate IntegrationFlowBuilder getFlowBuilder() {\n\n\t\tIntegrationFlowBuilder flowBuilder;\n\t\tURLName urlName = this.properties.getUrl();\n\n\t\tif (this.properties.isIdleImap()) {\n\t\t\tflowBuilder = getIdleImapFlow(urlName);\n\t\t}\n\t\telse {\n\n\t\t\tMailInboundChannelAdapterSpec adapterSpec;\n\t\t\tswitch (urlName.getProtocol().toUpperCase()) {\n\t\t\t\tcase \"IMAP\":\n\t\t\t\tcase \"IMAPS\":\n\t\t\t\t\tadapterSpec = getImapFlowBuilder(urlName);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"POP3\":\n\t\t\t\tcase \"POP3S\":\n\t\t\t\t\tadapterSpec = getPop3FlowBuilder(urlName);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\t\"Unsupported mail protocol: \" + urlName.getProtocol());\n\t\t\t}\n\t\t\tflowBuilder = IntegrationFlows.from(\n\t\t\t\t\tadapterSpec.javaMailProperties(getJavaMailProperties(urlName))\n\t\t\t\t\t\t\t.selectorExpression(this.properties.getExpression())\n\t\t\t\t\t\t\t.shouldDeleteMessages(this.properties.isDelete()),\n\t\t\t\t\tnew Consumer<SourcePollingChannelAdapterSpec>() {\n\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void accept(\n\t\t\t\t\t\t\t\tSourcePollingChannelAdapterSpec sourcePollingChannelAdapterSpec) {\n\t\t\t\t\t\t\tsourcePollingChannelAdapterSpec.poller(MailSourceConfiguration.this.defaultPoller);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t});\n\n\t\t}\n\t\treturn flowBuilder;\n\t}",
"private void processProperties() {\n state = true;\n try {\n importerServiceFilter = getFilter(importerServiceFilterProperty);\n } catch (InvalidFilterException invalidFilterException) {\n LOG.debug(\"The value of the Property \" + FILTER_IMPORTERSERVICE_PROPERTY + \" is invalid,\"\n + \" the recuperation of the Filter has failed. The instance gonna stop.\", invalidFilterException);\n state = false;\n return;\n }\n\n try {\n importDeclarationFilter = getFilter(importDeclarationFilterProperty);\n } catch (InvalidFilterException invalidFilterException) {\n LOG.debug(\"The value of the Property \" + FILTER_IMPORTDECLARATION_PROPERTY + \" is invalid,\"\n + \" the recuperation of the Filter has failed. The instance gonna stop.\", invalidFilterException);\n state = false;\n return;\n }\n }",
"public static float[][] toFloat(int[][] array) {\n float[][] n = new float[array.length][array[0].length];\n for (int i = 0; i < array.length; i++) {\n for (int j = 0; j < array[0].length; j++) {\n n[i][j] = (float) array[i][j];\n }\n }\n return n;\n }",
"private void processTask(ChildTaskContainer parent, MapRow row) throws IOException\n {\n Task task = parent.addTask();\n task.setName(row.getString(\"NAME\"));\n task.setGUID(row.getUUID(\"UUID\"));\n task.setText(1, row.getString(\"ID\"));\n task.setDuration(row.getDuration(\"PLANNED_DURATION\"));\n task.setRemainingDuration(row.getDuration(\"REMAINING_DURATION\"));\n task.setHyperlink(row.getString(\"URL\"));\n task.setPercentageComplete(row.getDouble(\"PERCENT_COMPLETE\"));\n task.setNotes(getNotes(row.getRows(\"COMMENTARY\")));\n task.setMilestone(task.getDuration().getDuration() == 0);\n\n ProjectCalendar calendar = m_calendarMap.get(row.getUUID(\"CALENDAR_UUID\"));\n if (calendar != m_project.getDefaultCalendar())\n {\n task.setCalendar(calendar);\n }\n\n switch (row.getInteger(\"STATUS\").intValue())\n {\n case 1: // Planned\n {\n task.setStart(row.getDate(\"PLANNED_START\"));\n task.setFinish(task.getEffectiveCalendar().getDate(task.getStart(), task.getDuration(), false));\n break;\n }\n\n case 2: // Started\n {\n task.setActualStart(row.getDate(\"ACTUAL_START\"));\n task.setStart(task.getActualStart());\n task.setFinish(row.getDate(\"ESTIMATED_FINISH\"));\n if (task.getFinish() == null)\n {\n task.setFinish(row.getDate(\"PLANNED_FINISH\"));\n }\n break;\n }\n\n case 3: // Finished\n {\n task.setActualStart(row.getDate(\"ACTUAL_START\"));\n task.setActualFinish(row.getDate(\"ACTUAL_FINISH\"));\n task.setPercentageComplete(Double.valueOf(100.0));\n task.setStart(task.getActualStart());\n task.setFinish(task.getActualFinish());\n break;\n }\n }\n\n setConstraints(task, row);\n\n processChildTasks(task, row);\n\n m_taskMap.put(task.getGUID(), task);\n\n List<MapRow> predecessors = row.getRows(\"PREDECESSORS\");\n if (predecessors != null && !predecessors.isEmpty())\n {\n m_predecessorMap.put(task, predecessors);\n }\n\n List<MapRow> resourceAssignmnets = row.getRows(\"RESOURCE_ASSIGNMENTS\");\n if (resourceAssignmnets != null && !resourceAssignmnets.isEmpty())\n {\n processResourceAssignments(task, resourceAssignmnets);\n }\n }",
"public static IndexedContainer getPrincipalContainer(\n CmsObject cms,\n List<? extends I_CmsPrincipal> list,\n String captionID,\n String descID,\n String iconID,\n String ouID,\n String icon,\n List<FontIcon> iconList) {\n\n IndexedContainer res = new IndexedContainer();\n\n res.addContainerProperty(captionID, String.class, \"\");\n res.addContainerProperty(ouID, String.class, \"\");\n res.addContainerProperty(iconID, FontIcon.class, new CmsCssIcon(icon));\n if (descID != null) {\n res.addContainerProperty(descID, String.class, \"\");\n }\n\n for (I_CmsPrincipal group : list) {\n\n Item item = res.addItem(group);\n item.getItemProperty(captionID).setValue(group.getSimpleName());\n item.getItemProperty(ouID).setValue(group.getOuFqn());\n if (descID != null) {\n item.getItemProperty(descID).setValue(group.getDescription(A_CmsUI.get().getLocale()));\n }\n }\n\n for (int i = 0; i < iconList.size(); i++) {\n res.getItem(res.getIdByIndex(i)).getItemProperty(iconID).setValue(iconList.get(i));\n }\n\n return res;\n }"
] |
Set the pattern scheme to either "by weekday" or "by day of month".
@param isByWeekDay flag, indicating if the pattern "by weekday" should be set.
@param fireChange flag, indicating if a value change event should be fired. | [
"public void setPatternScheme(final boolean isByWeekDay, final boolean fireChange) {\n\n if (isByWeekDay ^ (null != m_model.getWeekDay())) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n if (isByWeekDay) {\n m_model.setWeekOfMonth(getPatternDefaultValues().getWeekOfMonth());\n m_model.setWeekDay(getPatternDefaultValues().getWeekDay());\n } else {\n m_model.clearWeekDays();\n m_model.clearWeeksOfMonth();\n m_model.setDayOfMonth(getPatternDefaultValues().getDayOfMonth());\n }\n m_model.setInterval(getPatternDefaultValues().getInterval());\n if (fireChange) {\n onValueChange();\n }\n }\n });\n }\n\n }"
] | [
"public boolean merge(AbstractTransition another) {\n if (!isCompatible(another)) {\n return false;\n }\n if (another.mId != null) {\n if (mId == null) {\n mId = another.mId;\n } else {\n StringBuilder sb = new StringBuilder(mId.length() + another.mId.length());\n sb.append(mId);\n sb.append(\"_MERGED_\");\n sb.append(another.mId);\n mId = sb.toString();\n }\n }\n mUpdateStateAfterUpdateProgress |= another.mUpdateStateAfterUpdateProgress;\n mSetupList.addAll(another.mSetupList);\n Collections.sort(mSetupList, new Comparator<S>() {\n @Override\n public int compare(S lhs, S rhs) {\n if (lhs instanceof AbstractTransitionBuilder && rhs instanceof AbstractTransitionBuilder) {\n AbstractTransitionBuilder left = (AbstractTransitionBuilder) lhs;\n AbstractTransitionBuilder right = (AbstractTransitionBuilder) rhs;\n float startLeft = left.mReverse ? left.mEnd : left.mStart;\n float startRight = right.mReverse ? right.mEnd : right.mStart;\n return (int) ((startRight - startLeft) * 1000);\n }\n return 0;\n }\n });\n\n return true;\n }",
"public static Boolean assertFalse(Boolean value, String message) {\n if (Boolean.valueOf(value))\n throw new IllegalArgumentException(message);\n return value;\n }",
"public static <E> Set<E> intersection(Set<E> s1, Set<E> s2) {\r\n Set<E> s = new HashSet<E>();\r\n s.addAll(s1);\r\n s.retainAll(s2);\r\n return s;\r\n }",
"private TypeArgSignature getTypeArgSignature(Type type) {\r\n\t\tif (type instanceof WildcardType) {\r\n\t\t\tWildcardType wildcardType = (WildcardType) type;\r\n\t\t\tType lowerBound = wildcardType.getLowerBounds().length == 0 ? null\r\n\t\t\t\t\t: wildcardType.getLowerBounds()[0];\r\n\t\t\tType upperBound = wildcardType.getUpperBounds().length == 0 ? null\r\n\t\t\t\t\t: wildcardType.getUpperBounds()[0];\r\n\r\n\t\t\tif (lowerBound == null && Object.class.equals(upperBound)) {\r\n\t\t\t\treturn new TypeArgSignature(\r\n\t\t\t\t\t\tTypeArgSignature.UNBOUNDED_WILDCARD,\r\n\t\t\t\t\t\t(FieldTypeSignature) getFullTypeSignature(upperBound));\r\n\t\t\t} else if (lowerBound == null && upperBound != null) {\r\n\t\t\t\treturn new TypeArgSignature(\r\n\t\t\t\t\t\tTypeArgSignature.UPPERBOUND_WILDCARD,\r\n\t\t\t\t\t\t(FieldTypeSignature) getFullTypeSignature(upperBound));\r\n\t\t\t} else if (lowerBound != null) {\r\n\t\t\t\treturn new TypeArgSignature(\r\n\t\t\t\t\t\tTypeArgSignature.LOWERBOUND_WILDCARD,\r\n\t\t\t\t\t\t(FieldTypeSignature) getFullTypeSignature(lowerBound));\r\n\t\t\t} else {\r\n\t\t\t\tthrow new RuntimeException(\"Invalid type\");\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\treturn new TypeArgSignature(TypeArgSignature.NO_WILDCARD,\r\n\t\t\t\t\t(FieldTypeSignature) getFullTypeSignature(type));\r\n\t\t}\r\n\t}",
"public static void extractHouseholderRow( ZMatrixRMaj A ,\n int row ,\n int col0, int col1 , double u[], int offsetU )\n {\n int indexU = (offsetU+col0)*2;\n u[indexU] = 1;\n u[indexU+1] = 0;\n\n int indexA = (row*A.numCols + (col0+1))*2;\n System.arraycopy(A.data,indexA,u,indexU+2,(col1-col0-1)*2);\n }",
"PollingState<T> withResponse(Response<ResponseBody> response) {\n this.response = response;\n withPollingUrlFromResponse(response);\n withPollingRetryTimeoutFromResponse(response);\n return this;\n }",
"public float getNormalY(int vertex) {\n if (!hasNormals()) {\n throw new IllegalStateException(\"mesh has no normals\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_normals.getFloat((vertex * 3 + 1) * SIZEOF_FLOAT);\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}",
"protected static int calculateShift(int minimumValue, int maximumValue) {\n\t\tint shift = 0;\n\t\tint value = 1;\n\t\twhile (value < minimumValue && value < maximumValue) {\n\t\t\tvalue <<= 1;\n\t\t\tshift++;\n\t\t}\n\t\treturn shift;\n\t}"
] |
End building the prepared script, adding a return value statement
@param value the value to return
@param config the configuration for the script to build
@return the new {@link LuaPreparedScript} instance | [
"public LuaPreparedScript endPreparedScriptReturn(LuaValue value, LuaScriptConfig config) {\n add(new LuaAstReturnStatement(argument(value)));\n return endPreparedScript(config);\n }"
] | [
"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 }",
"public String buildRadio(String propName) throws CmsException {\n\n String propVal = readProperty(propName);\n StringBuffer result = new StringBuffer(\"<table border=\\\"0\\\"><tr>\");\n result.append(\"<td><input type=\\\"radio\\\" value=\\\"true\\\" onClick=\\\"checkNoIntern()\\\" name=\\\"\").append(\n propName).append(\"\\\" \").append(Boolean.valueOf(propVal).booleanValue() ? \"checked=\\\"checked\\\"\" : \"\").append(\n \"/></td><td id=\\\"tablelabel\\\">\").append(key(Messages.GUI_LABEL_TRUE_0)).append(\"</td>\");\n result.append(\"<td><input type=\\\"radio\\\" value=\\\"false\\\" onClick=\\\"checkNoIntern()\\\" name=\\\"\").append(\n propName).append(\"\\\" \").append(Boolean.valueOf(propVal).booleanValue() ? \"\" : \"checked=\\\"checked\\\"\").append(\n \"/></td><td id=\\\"tablelabel\\\">\").append(key(Messages.GUI_LABEL_FALSE_0)).append(\"</td>\");\n result.append(\"<td><input type=\\\"radio\\\" value=\\\"\\\" onClick=\\\"checkNoIntern()\\\" name=\\\"\").append(\n propName).append(\"\\\" \").append(CmsStringUtil.isEmpty(propVal) ? \"checked=\\\"checked\\\"\" : \"\").append(\n \"/></td><td id=\\\"tablelabel\\\">\").append(getPropertyInheritanceInfo(propName)).append(\n \"</td></tr></table>\");\n return result.toString();\n }",
"static String from(Class<?> entryClass) {\n List<String> tokens = tokenOf(entryClass);\n return fromTokens(tokens);\n }",
"public boolean matchesWithMask(long lowerValue, long upperValue, long mask) {\n\t\tif(lowerValue == upperValue) {\n\t\t\treturn matchesWithMask(lowerValue, mask);\n\t\t}\n\t\tif(!isMultiple()) {\n\t\t\t//we know lowerValue and upperValue are not the same, so impossible to match those two values with a single value\n\t\t\treturn false;\n\t\t}\n\t\tlong thisValue = getDivisionValue();\n\t\tlong thisUpperValue = getUpperDivisionValue();\n\t\tif(!isMaskCompatibleWithRange(thisValue, thisUpperValue, mask, getMaxValue())) {\n\t\t\treturn false;\n\t\t}\n\t\treturn lowerValue == (thisValue & mask) && upperValue == (thisUpperValue & mask);\n\t}",
"private void stereotype(Options opt, Doc c, Align align) {\n\tfor (Tag tag : c.tags(\"stereotype\")) {\n\t String t[] = tokenize(tag.text());\n\t if (t.length != 1) {\n\t\tSystem.err.println(\"@stereotype expects one field: \" + tag.text());\n\t\tcontinue;\n\t }\n\t tableLine(align, guilWrap(opt, t[0]));\n\t}\n }",
"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 static service_stats get(nitro_service service, String name) throws Exception{\n\t\tservice_stats obj = new service_stats();\n\t\tobj.set_name(name);\n\t\tservice_stats response = (service_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"public static <T> DatabaseTableConfig<T> fromClass(DatabaseType databaseType, Class<T> clazz) throws SQLException {\n\t\tString tableName = extractTableName(databaseType, clazz);\n\t\tif (databaseType.isEntityNamesMustBeUpCase()) {\n\t\t\ttableName = databaseType.upCaseEntityName(tableName);\n\t\t}\n\t\treturn new DatabaseTableConfig<T>(databaseType, clazz, tableName,\n\t\t\t\textractFieldTypes(databaseType, clazz, tableName));\n\t}",
"private void processRedirect(String stringStatusCode,\n HttpMethod httpMethodProxyRequest,\n HttpServletRequest httpServletRequest,\n HttpServletResponse httpServletResponse) throws Exception {\n // Check if the proxy response is a redirect\n // The following code is adapted from\n // org.tigris.noodle.filters.CheckForRedirect\n // Hooray for open source software\n\n String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();\n if (stringLocation == null) {\n throw new ServletException(\"Received status code: \"\n + stringStatusCode + \" but no \"\n + STRING_LOCATION_HEADER\n + \" header was found in the response\");\n }\n // Modify the redirect to go to this proxy servlet rather than the proxied host\n String stringMyHostName = httpServletRequest.getServerName();\n if (httpServletRequest.getServerPort() != 80) {\n stringMyHostName += \":\" + httpServletRequest.getServerPort();\n }\n stringMyHostName += httpServletRequest.getContextPath();\n httpServletResponse.sendRedirect(stringLocation.replace(\n getProxyHostAndPort() + this.getProxyPath(),\n stringMyHostName));\n }"
] |
Writes triples which conect properties with there corresponding rdf
properties for statements, simple statements, qualifiers, reference
attributes and values.
@param document
@throws RDFHandlerException | [
"void writeInterPropertyLinks(PropertyDocument document)\n\t\t\tthrows RDFHandlerException {\n\t\tResource subject = this.rdfWriter.getUri(document.getEntityId()\n\t\t\t\t.getIri());\n\t\tthis.rdfWriter.writeTripleUriObject(subject, this.rdfWriter\n\t\t\t\t.getUri(Vocabulary.WB_DIRECT_CLAIM_PROP), Vocabulary\n\t\t\t\t.getPropertyUri(document.getEntityId(),\n\t\t\t\t\t\tPropertyContext.DIRECT));\n\n\t\tthis.rdfWriter.writeTripleUriObject(subject, this.rdfWriter\n\t\t\t\t.getUri(Vocabulary.WB_CLAIM_PROP), Vocabulary.getPropertyUri(\n\t\t\t\tdocument.getEntityId(), PropertyContext.STATEMENT));\n\n\t\tthis.rdfWriter.writeTripleUriObject(subject, this.rdfWriter\n\t\t\t\t.getUri(Vocabulary.WB_STATEMENT_PROP), Vocabulary\n\t\t\t\t.getPropertyUri(document.getEntityId(),\n\t\t\t\t\t\tPropertyContext.VALUE_SIMPLE));\n\n\t\tthis.rdfWriter.writeTripleUriObject(subject, this.rdfWriter\n\t\t\t\t.getUri(Vocabulary.WB_STATEMENT_VALUE_PROP),\n\t\t\t\tVocabulary.getPropertyUri(document.getEntityId(),\n\t\t\t\t\t\tPropertyContext.VALUE));\n\n\t\tthis.rdfWriter.writeTripleUriObject(subject, this.rdfWriter\n\t\t\t\t.getUri(Vocabulary.WB_QUALIFIER_PROP), Vocabulary\n\t\t\t\t.getPropertyUri(document.getEntityId(),\n\t\t\t\t\t\tPropertyContext.QUALIFIER_SIMPLE));\n\n\t\tthis.rdfWriter.writeTripleUriObject(subject, this.rdfWriter\n\t\t\t\t.getUri(Vocabulary.WB_QUALIFIER_VALUE_PROP), Vocabulary\n\t\t\t\t.getPropertyUri(document.getEntityId(),\n\t\t\t\t\t\tPropertyContext.QUALIFIER));\n\n\t\tthis.rdfWriter.writeTripleUriObject(subject, this.rdfWriter\n\t\t\t\t.getUri(Vocabulary.WB_REFERENCE_PROP), Vocabulary\n\t\t\t\t.getPropertyUri(document.getEntityId(),\n\t\t\t\t\t\tPropertyContext.REFERENCE_SIMPLE));\n\n\t\tthis.rdfWriter.writeTripleUriObject(subject, this.rdfWriter\n\t\t\t\t.getUri(Vocabulary.WB_REFERENCE_VALUE_PROP), Vocabulary\n\t\t\t\t.getPropertyUri(document.getEntityId(),\n\t\t\t\t\t\tPropertyContext.REFERENCE));\n\n\t\tthis.rdfWriter.writeTripleUriObject(subject, this.rdfWriter\n\t\t\t\t.getUri(Vocabulary.WB_NO_VALUE_PROP), Vocabulary\n\t\t\t\t.getPropertyUri(document.getEntityId(),\n\t\t\t\t\t\tPropertyContext.NO_VALUE));\n\t\tthis.rdfWriter.writeTripleUriObject(subject, this.rdfWriter\n\t\t\t\t.getUri(Vocabulary.WB_NO_QUALIFIER_VALUE_PROP), Vocabulary\n\t\t\t\t.getPropertyUri(document.getEntityId(),\n\t\t\t\t\t\tPropertyContext.NO_QUALIFIER_VALUE));\n\t\t// TODO something more with NO_VALUE\n\t}"
] | [
"public static String transformXPath(String originalXPath)\n {\n // use a list to maintain the multiple joined xqueries (if there are multiple queries joined with the \"|\" operator)\n List<StringBuilder> compiledXPaths = new ArrayList<>(1);\n\n int frameIdx = -1;\n boolean inQuote = false;\n int conditionLevel = 0;\n char startQuoteChar = 0;\n StringBuilder currentXPath = new StringBuilder();\n compiledXPaths.add(currentXPath);\n for (int i = 0; i < originalXPath.length(); i++)\n {\n char curChar = originalXPath.charAt(i);\n if (!inQuote && curChar == '[')\n {\n frameIdx++;\n conditionLevel++;\n currentXPath.append(\"[windup:startFrame(\").append(frameIdx).append(\") and windup:evaluate(\").append(frameIdx).append(\", \");\n }\n else if (!inQuote && curChar == ']')\n {\n conditionLevel--;\n currentXPath.append(\")]\");\n }\n else if (!inQuote && conditionLevel == 0 && curChar == '|')\n {\n // joining multiple xqueries\n currentXPath = new StringBuilder();\n compiledXPaths.add(currentXPath);\n }\n else\n {\n if (inQuote && curChar == startQuoteChar)\n {\n inQuote = false;\n startQuoteChar = 0;\n }\n else if (curChar == '\"' || curChar == '\\'')\n {\n inQuote = true;\n startQuoteChar = curChar;\n }\n\n if (!inQuote && originalXPath.startsWith(WINDUP_MATCHES_FUNCTION_PREFIX, i))\n {\n i += (WINDUP_MATCHES_FUNCTION_PREFIX.length() - 1);\n currentXPath.append(\"windup:matches(\").append(frameIdx).append(\", \");\n }\n else\n {\n currentXPath.append(curChar);\n }\n }\n }\n\n Pattern leadingAndTrailingWhitespace = Pattern.compile(\"(\\\\s*)(.*?)(\\\\s*)\");\n StringBuilder finalResult = new StringBuilder();\n for (StringBuilder compiledXPath : compiledXPaths)\n {\n if (StringUtils.isNotBlank(compiledXPath))\n {\n Matcher whitespaceMatcher = leadingAndTrailingWhitespace.matcher(compiledXPath);\n if (!whitespaceMatcher.matches())\n continue;\n\n compiledXPath = new StringBuilder();\n compiledXPath.append(whitespaceMatcher.group(1));\n compiledXPath.append(whitespaceMatcher.group(2));\n compiledXPath.append(\"/self::node()[windup:persist(\").append(frameIdx).append(\", \").append(\".)]\");\n compiledXPath.append(whitespaceMatcher.group(3));\n\n if (StringUtils.isNotBlank(finalResult))\n finalResult.append(\"|\");\n finalResult.append(compiledXPath);\n }\n }\n return finalResult.toString();\n }",
"public void fireCalendarWrittenEvent(ProjectCalendar calendar)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.calendarWritten(calendar);\n }\n }\n }",
"public static void showOnlyChannels(Object... channels){\r\n for(LogRecordHandler handler : handlers){\r\n if(handler instanceof VisibilityHandler){\r\n VisibilityHandler visHandler = (VisibilityHandler) handler;\r\n visHandler.hideAll();\r\n for (Object channel : channels) {\r\n visHandler.alsoShow(channel);\r\n }\r\n }\r\n }\r\n }",
"static ReadMasterDomainModelUtil readMasterDomainResourcesForInitialConnect(final Transformers transformers,\n final Transformers.TransformationInputs transformationInputs,\n final Transformers.ResourceIgnoredTransformationRegistry ignoredTransformationRegistry,\n final Resource domainRoot) throws OperationFailedException {\n\n Resource transformedResource = transformers.transformRootResource(transformationInputs, domainRoot, ignoredTransformationRegistry);\n ReadMasterDomainModelUtil util = new ReadMasterDomainModelUtil();\n util.describedResources = util.describeAsNodeList(PathAddress.EMPTY_ADDRESS, transformedResource, false);\n return util;\n }",
"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 void setSpecularIntensity(float r, float g, float b, float a) {\n setVec4(\"specular_intensity\", r, g, b, a);\n }",
"public void getElevationAlongPath(PathElevationRequest req, ElevationServiceCallback callback) {\n \n this.callback = callback;\n \n JSObject doc = (JSObject) getJSObject().eval(\"document\");\n doc.setMember(getVariableName(), this);\n \n StringBuilder r = new StringBuilder(getVariableName())\n .append(\".\")\n .append(\"getElevationAlongPath(\")\n .append(req.getVariableName())\n .append(\", \")\n .append(\"function(results, status) {document.\")\n .append(getVariableName())\n .append(\".processResponse(results, status);});\");\n \n getJSObject().eval(r.toString());\n \n }",
"public static void setFaceNames(String[] nameArray)\n {\n if (nameArray.length != 6)\n {\n throw new IllegalArgumentException(\"nameArray length is not 6.\");\n }\n for (int i = 0; i < 6; i++)\n {\n faceIndexMap.put(nameArray[i], i);\n }\n }",
"public static void doBatchEnqueue(final Jedis jedis, final String namespace, final String queue, final List<String> jobJsons) {\n Pipeline pipelined = jedis.pipelined();\n pipelined.sadd(JesqueUtils.createKey(namespace, QUEUES), queue);\n for (String jobJson : jobJsons) {\n pipelined.rpush(JesqueUtils.createKey(namespace, QUEUE, queue), jobJson);\n }\n pipelined.sync();\n }"
] |
Read the header data for a single file.
@param header header data
@return SynchroTable instance | [
"private SynchroTable readTableHeader(byte[] header)\n {\n SynchroTable result = null;\n String tableName = DatatypeConverter.getSimpleString(header, 0);\n if (!tableName.isEmpty())\n {\n int offset = DatatypeConverter.getInt(header, 40);\n result = new SynchroTable(tableName, offset);\n }\n return result;\n }"
] | [
"private void harvestReturnValues(\r\n ProcedureDescriptor proc,\r\n Object obj,\r\n PreparedStatement stmt)\r\n throws PersistenceBrokerSQLException\r\n {\r\n // If the procedure descriptor is null or has no return values or\r\n // if the statement is not a callable statment, then we're done.\r\n if ((proc == null) || (!proc.hasReturnValues()))\r\n {\r\n return;\r\n }\r\n\r\n // Set up the callable statement\r\n CallableStatement callable = (CallableStatement) stmt;\r\n\r\n // This is the index that we'll use to harvest the return value(s).\r\n int index = 0;\r\n\r\n // If the proc has a return value, then try to harvest it.\r\n if (proc.hasReturnValue())\r\n {\r\n\r\n // Increment the index\r\n index++;\r\n\r\n // Harvest the value.\r\n this.harvestReturnValue(obj, callable, proc.getReturnValueFieldRef(), index);\r\n }\r\n\r\n // Check each argument. If it's returned by the procedure,\r\n // then harvest the value.\r\n Iterator iter = proc.getArguments().iterator();\r\n while (iter.hasNext())\r\n {\r\n index++;\r\n ArgumentDescriptor arg = (ArgumentDescriptor) iter.next();\r\n if (arg.getIsReturnedByProcedure())\r\n {\r\n this.harvestReturnValue(obj, callable, arg.getFieldRef(), index);\r\n }\r\n }\r\n }",
"public static String getPunctClass(String punc) {\r\n if(punc.equals(\"%\") || punc.equals(\"-PLUS-\"))//-PLUS- is an escape for \"+\" in the ATB\r\n return \"perc\";\r\n else if(punc.startsWith(\"*\"))\r\n return \"bullet\";\r\n else if(sfClass.contains(punc))\r\n return \"sf\";\r\n else if(colonClass.contains(punc) || pEllipsis.matcher(punc).matches())\r\n return \"colon\";\r\n else if(commaClass.contains(punc))\r\n return \"comma\";\r\n else if(currencyClass.contains(punc))\r\n return \"curr\";\r\n else if(slashClass.contains(punc))\r\n return \"slash\";\r\n else if(lBracketClass.contains(punc))\r\n return \"lrb\";\r\n else if(rBracketClass.contains(punc))\r\n return \"rrb\";\r\n else if(quoteClass.contains(punc))\r\n return \"quote\";\r\n \r\n return \"\";\r\n }",
"private File getDisabledMarkerFile(long version) throws PersistenceFailureException {\n File[] versionDirArray = ReadOnlyUtils.getVersionDirs(rootDir, version, version);\n if (versionDirArray.length == 0) {\n throw new PersistenceFailureException(\"getDisabledMarkerFile did not find the requested version directory\" +\n \" on disk. Version: \" + version + \", rootDir: \" + rootDir);\n }\n File disabledMarkerFile = new File(versionDirArray[0], DISABLED_MARKER_NAME);\n return disabledMarkerFile;\n }",
"private String tail(String moduleName) {\n if (moduleName.indexOf(MODULE_NAME_SEPARATOR) > 0) {\n return moduleName.substring(moduleName.indexOf(MODULE_NAME_SEPARATOR) + 1);\n } else {\n return \"\";\n }\n }",
"public GVRAnimation setOffset(float startOffset)\n {\n if(startOffset<0 || startOffset>mDuration){\n throw new IllegalArgumentException(\"offset should not be either negative or greater than duration\");\n }\n animationOffset = startOffset;\n mDuration = mDuration-animationOffset;\n return this;\n }",
"public ModelNode registerDeploymentSubsystemResource(final String subsystemName, final Resource resource) {\n assert subsystemName != null : \"The subsystemName cannot be null\";\n assert resource != null : \"The resource cannot be null\";\n return registerDeploymentSubResource(subsystemName, PathAddress.EMPTY_ADDRESS, resource);\n }",
"public static List<DbModule> getAllSubmodules(final DbModule module) {\n final List<DbModule> submodules = new ArrayList<DbModule>();\n submodules.addAll(module.getSubmodules());\n\n for(final DbModule submodule: module.getSubmodules()){\n submodules.addAll(getAllSubmodules(submodule));\n }\n\n return submodules;\n }",
"public List<T> nextPermutationAsList()\n {\n List<T> permutation = new ArrayList<T>(elements.length);\n return nextPermutationAsList(permutation);\n }",
"public static void fillHermitian(ZMatrixRMaj A, double min, double max, Random rand) {\n if( A.numRows != A.numCols )\n throw new IllegalArgumentException(\"A must be a square matrix\");\n\n double range = max-min;\n\n int length = A.numRows;\n\n for( int i = 0; i < length; i++ ) {\n A.set(i,i,rand.nextDouble()*range + min,0);\n\n for( int j = i+1; j < length; j++ ) {\n double real = rand.nextDouble()*range + min;\n double imaginary = rand.nextDouble()*range + min;\n A.set(i,j,real,imaginary);\n A.set(j,i,real,-imaginary);\n }\n }\n }"
] |
Put features in a tile. This will assure all features are only added in one tile. When a feature's unique tile
is different from this one a link is added in the tile.
@param tile
tile to put features in
@param maxTileExtent
the maximum tile extent
@throws GeomajasException oops | [
"public void fillTile(InternalTile tile, Envelope maxTileExtent)\n\t\t\tthrows GeomajasException {\n\t\tList<InternalFeature> origFeatures = tile.getFeatures();\n\t\ttile.setFeatures(new ArrayList<InternalFeature>());\n\t\tfor (InternalFeature feature : origFeatures) {\n\t\t\tif (!addTileCode(tile, maxTileExtent, feature.getGeometry())) {\n\t\t\t\tlog.debug(\"add feature\");\n\t\t\t\ttile.addFeature(feature);\n\t\t\t}\n\t\t}\n\t}"
] | [
"protected static void statistics(int from, int to) {\r\n\t// check that primes contain no accidental errors\r\n\tfor (int i=0; i<primeCapacities.length-1; i++) {\r\n\t\tif (primeCapacities[i] >= primeCapacities[i+1]) throw new RuntimeException(\"primes are unsorted or contain duplicates; detected at \"+i+\"@\"+primeCapacities[i]);\r\n\t}\r\n\t\r\n\tdouble accDeviation = 0.0;\r\n\tdouble maxDeviation = - 1.0;\r\n\r\n\tfor (int i=from; i<=to; i++) {\r\n\t\tint primeCapacity = nextPrime(i);\r\n\t\t//System.out.println(primeCapacity);\r\n\t\tdouble deviation = (primeCapacity - i) / (double)i;\r\n\t\t\r\n\t\tif (deviation > maxDeviation) {\r\n\t\t\tmaxDeviation = deviation;\r\n\t\t\tSystem.out.println(\"new maxdev @\"+i+\"@dev=\"+maxDeviation);\r\n\t\t}\r\n\r\n\t\taccDeviation += deviation;\r\n\t}\r\n\tlong width = 1 + (long)to - (long)from;\r\n\t\r\n\tdouble meanDeviation = accDeviation/width;\r\n\tSystem.out.println(\"Statistics for [\"+ from + \",\"+to+\"] are as follows\");\r\n\tSystem.out.println(\"meanDeviation = \"+(float)meanDeviation*100+\" %\");\r\n\tSystem.out.println(\"maxDeviation = \"+(float)maxDeviation*100+\" %\");\r\n}",
"private void processUDF(UDFTypeType udf)\n {\n FieldTypeClass fieldType = FIELD_TYPE_MAP.get(udf.getSubjectArea());\n if (fieldType != null)\n {\n UserFieldDataType dataType = UserFieldDataType.getInstanceFromXmlName(udf.getDataType());\n String name = udf.getTitle();\n FieldType field = addUserDefinedField(fieldType, dataType, name);\n if (field != null)\n {\n m_fieldTypeMap.put(udf.getObjectId(), field);\n }\n }\n }",
"public static String getSerializedVectorClock(VectorClock vc) {\n VectorClockWrapper vcWrapper = new VectorClockWrapper(vc);\n String serializedVC = \"\";\n try {\n serializedVC = mapper.writeValueAsString(vcWrapper);\n } catch(Exception e) {\n e.printStackTrace();\n }\n return serializedVC;\n }",
"public void addFieldDescriptor(FieldDescriptor fld)\r\n {\r\n fld.setClassDescriptor(this); // BRJ\r\n if (m_FieldDescriptions == null)\r\n {\r\n m_FieldDescriptions = new FieldDescriptor[1];\r\n m_FieldDescriptions[0] = fld;\r\n }\r\n else\r\n {\r\n int size = m_FieldDescriptions.length;\r\n FieldDescriptor[] tmpArray = new FieldDescriptor[size + 1];\r\n System.arraycopy(m_FieldDescriptions, 0, tmpArray, 0, size);\r\n tmpArray[size] = fld;\r\n m_FieldDescriptions = tmpArray;\r\n // 2. Sort fields according to their getOrder() Property\r\n Arrays.sort(m_FieldDescriptions, FieldDescriptor.getComparator());\r\n }\r\n\r\n m_fieldDescriptorNameMap = null;\r\n m_PkFieldDescriptors = null;\r\n m_nonPkFieldDescriptors = null;\r\n m_lockingFieldDescriptors = null;\r\n m_RwFieldDescriptors = null;\r\n m_RwNonPkFieldDescriptors = null;\r\n }",
"public void setColorForTotal(int row, int column, Color color){\r\n\t\tint mapC = (colors.length-1) - column;\r\n\t\tint mapR = (colors[0].length-1) - row;\r\n\t\tcolors[mapC][mapR]=color;\t\t\r\n\t}",
"private void updateScheduleSource(ProjectProperties properties)\n {\n // Rudimentary identification of schedule source\n if (properties.getCompany() != null && properties.getCompany().equals(\"Synchro Software Ltd\"))\n {\n properties.setFileApplication(\"Synchro\");\n }\n else\n {\n if (properties.getAuthor() != null && properties.getAuthor().equals(\"SG Project\"))\n {\n properties.setFileApplication(\"Simple Genius\");\n }\n else\n {\n properties.setFileApplication(\"Microsoft\");\n }\n }\n properties.setFileType(\"MSPDI\");\n }",
"protected void processOutlineCodeField(Integer entityID, Row row)\n {\n processField(row, \"OC_FIELD_ID\", entityID, row.getString(\"OC_NAME\"));\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 }",
"private void deliverAlbumArtUpdate(int player, AlbumArt art) {\n if (!getAlbumArtListeners().isEmpty()) {\n final AlbumArtUpdate update = new AlbumArtUpdate(player, art);\n for (final AlbumArtListener listener : getAlbumArtListeners()) {\n try {\n listener.albumArtChanged(update);\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering album art update to listener\", t);\n }\n }\n }\n }"
] |
Iterates through the given CharSequence line by line, splitting each line using
the given separator Pattern. The list of tokens for each line is then passed to
the given closure.
@param self a CharSequence
@param pattern the regular expression Pattern for the delimiter
@param closure a closure
@return the last value returned by the closure
@throws java.io.IOException if an error occurs
@since 1.8.2 | [
"public static <T> T splitEachLine(CharSequence self, Pattern pattern, @ClosureParams(value=FromString.class,options=\"List<String>\") Closure<T> closure) throws IOException {\n final List<String> list = readLines(self);\n T result = null;\n for (String line : list) {\n List vals = Arrays.asList(pattern.split(line));\n result = closure.call(vals);\n }\n return result;\n }"
] | [
"private void registerPackageInTypeInterestFactory(String pkg)\n {\n TypeInterestFactory.registerInterest(pkg + \"_pkg\", pkg.replace(\".\", \"\\\\.\"), pkg, TypeReferenceLocation.IMPORT);\n // TODO: Finish the implementation\n }",
"private void ensureElementClassRef(CollectionDescriptorDef collDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n String arrayElementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ARRAY_ELEMENT_CLASS_REF);\r\n\r\n if (!collDef.hasProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF))\r\n {\r\n if (arrayElementClassName != null)\r\n {\r\n // we use the array element type\r\n collDef.setProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF, arrayElementClassName);\r\n }\r\n else\r\n {\r\n throw new ConstraintException(\"Collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" does not specify its element class\");\r\n }\r\n }\r\n\r\n // now checking the element type\r\n ModelDef model = (ModelDef)collDef.getOwner().getOwner();\r\n String elementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF);\r\n ClassDescriptorDef elementClassDef = model.getClass(elementClassName);\r\n\r\n if (elementClassDef == null)\r\n {\r\n throw new ConstraintException(\"Collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" references an unknown class \"+elementClassName);\r\n }\r\n if (!elementClassDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_OJB_PERSISTENT, false))\r\n {\r\n throw new ConstraintException(\"The element class \"+elementClassName+\" of the collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" is not persistent\");\r\n }\r\n if (CHECKLEVEL_STRICT.equals(checkLevel) && (arrayElementClassName != null))\r\n {\r\n // specified element class must be a subtype of the element type\r\n try\r\n {\r\n InheritanceHelper helper = new InheritanceHelper();\r\n\r\n if (!helper.isSameOrSubTypeOf(elementClassDef, arrayElementClassName, true))\r\n {\r\n throw new ConstraintException(\"The element class \"+elementClassName+\" of the collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" is not the same or a subtype of the array base type \"+arrayElementClassName);\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"Could not find the class \"+ex.getMessage()+\" on the classpath while checking the collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName());\r\n }\r\n }\r\n // we're adjusting the property to use the classloader-compatible form\r\n collDef.setProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF, elementClassDef.getName());\r\n }",
"public void removePrefetchingListeners()\r\n {\r\n if (prefetchingListeners != null)\r\n {\r\n for (Iterator it = prefetchingListeners.iterator(); it.hasNext(); )\r\n {\r\n PBPrefetchingListener listener = (PBPrefetchingListener) it.next();\r\n listener.removeThisListener();\r\n }\r\n prefetchingListeners.clear();\r\n }\r\n }",
"@Nullable\n public ByteIterable get(@NotNull final Transaction txn, @NotNull final ByteIterable first) {\n return this.first.get(txn, first);\n }",
"private GregorianCalendar getLastReleventDate(GregorianCalendar currentDate) {\n\t\tint age=this.getProperties().getMaxFileAge();\n\t\tGregorianCalendar result=new GregorianCalendar(currentDate.get(Calendar.YEAR),currentDate.get(Calendar.MONTH),currentDate.get(Calendar.DAY_OF_MONTH));\n\t\tresult.add(Calendar.DAY_OF_MONTH, -age);\n\t\treturn result;\n\t}",
"private void addWSAddressingInterceptors(InterceptorProvider provider) {\n MAPAggregator mapAggregator = new MAPAggregator();\n MAPCodec mapCodec = new MAPCodec();\n\n provider.getInInterceptors().add(mapAggregator);\n provider.getInInterceptors().add(mapCodec);\n\n provider.getOutInterceptors().add(mapAggregator);\n provider.getOutInterceptors().add(mapCodec);\n\n provider.getInFaultInterceptors().add(mapAggregator);\n provider.getInFaultInterceptors().add(mapCodec);\n\n provider.getOutFaultInterceptors().add(mapAggregator);\n provider.getOutFaultInterceptors().add(mapCodec);\n }",
"private void readResources(Project ganttProject)\n {\n Resources resources = ganttProject.getResources();\n readResourceCustomPropertyDefinitions(resources);\n readRoleDefinitions(ganttProject);\n\n for (net.sf.mpxj.ganttproject.schema.Resource gpResource : resources.getResource())\n {\n readResource(gpResource);\n }\n }",
"public void setMaxConnectionAge(long maxConnectionAge, TimeUnit timeUnit) {\n\t\tthis.maxConnectionAgeInSeconds = TimeUnit.SECONDS.convert(maxConnectionAge, timeUnit);\n\t}",
"protected float computeUniformPadding(final CacheDataSet cache) {\n float axisSize = getViewPortSize(getOrientationAxis());\n float totalPadding = axisSize - cache.getTotalSize();\n float uniformPadding = totalPadding > 0 && cache.count() > 1 ?\n totalPadding / (cache.count() - 1) : 0;\n return uniformPadding;\n }"
] |
Creates a metadata cache archive file of all tracks in the specified slot on the specified player. Any
previous contents of the specified file will be replaced.
@param slot the slot in which the media to be cached can be found
@param playlistId the id of playlist to be cached, or 0 of all tracks should be cached
@param cache the file into which the metadata cache should be written
@throws Exception if there is a problem communicating with the player or writing the cache file. | [
"public static void createMetadataCache(SlotReference slot, int playlistId, File cache) throws Exception {\n createMetadataCache(slot, playlistId, cache, null);\n }"
] | [
"public static void setEnabled(Element element, boolean enabled) {\n element.setPropertyBoolean(\"disabled\", !enabled);\n\tsetStyleName(element, \"disabled\", !enabled);\n }",
"@Override\n public EthiopicDate date(Era era, int yearOfEra, int month, int dayOfMonth) {\n return date(prolepticYear(era, yearOfEra), month, dayOfMonth);\n }",
"public DbOrganization getMatchingOrganization(final DbModule dbModule) {\n if(dbModule.getOrganization() != null\n && !dbModule.getOrganization().isEmpty()){\n return getOrganization(dbModule.getOrganization());\n }\n\n for(final DbOrganization organization: repositoryHandler.getAllOrganizations()){\n final CorporateFilter corporateFilter = new CorporateFilter(organization);\n if(corporateFilter.matches(dbModule)){\n return organization;\n }\n }\n\n return null;\n }",
"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 }",
"@Deprecated\n public static PersistentResourceXMLBuilder decorator(final String elementName) {\n return new PersistentResourceXMLBuilder(PathElement.pathElement(elementName), null).setDecoratorGroup(elementName);\n }",
"public static Type boxedType(Type type) {\n if (type instanceof Class<?>) {\n return boxedClass((Class<?>) type);\n } else {\n return type;\n }\n }",
"public static dbdbprofile[] get(nitro_service service) throws Exception{\n\t\tdbdbprofile obj = new dbdbprofile();\n\t\tdbdbprofile[] response = (dbdbprofile[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"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 }",
"private String tail(String moduleName) {\n if (moduleName.indexOf(MODULE_NAME_SEPARATOR) > 0) {\n return moduleName.substring(moduleName.indexOf(MODULE_NAME_SEPARATOR) + 1);\n } else {\n return \"\";\n }\n }"
] |
Use this API to fetch all the authenticationradiusaction resources that are configured on netscaler. | [
"public static authenticationradiusaction[] get(nitro_service service) throws Exception{\n\t\tauthenticationradiusaction obj = new authenticationradiusaction();\n\t\tauthenticationradiusaction[] response = (authenticationradiusaction[])obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"public Session startSshSessionAndObtainSession() {\n\n Session session = null;\n try {\n\n JSch jsch = new JSch();\n if (sshMeta.getSshLoginType() == SshLoginType.KEY) {\n\n String workingDir = System.getProperty(\"user.dir\");\n String privKeyAbsPath = workingDir + \"/\"\n + sshMeta.getPrivKeyRelativePath();\n logger.debug(\"use privkey: path: \" + privKeyAbsPath);\n\n if (!PcFileNetworkIoUtils.isFileExist(privKeyAbsPath)) {\n throw new RuntimeException(\"file not found at \"\n + privKeyAbsPath);\n }\n\n if (sshMeta.isPrivKeyUsePassphrase()\n && sshMeta.getPassphrase() != null) {\n jsch.addIdentity(privKeyAbsPath, sshMeta.getPassphrase());\n } else {\n jsch.addIdentity(privKeyAbsPath);\n }\n }\n\n session = jsch.getSession(sshMeta.getUserName(), targetHost,\n sshMeta.getSshPort());\n if (sshMeta.getSshLoginType() == SshLoginType.PASSWORD) {\n session.setPassword(sshMeta.getPassword());\n }\n\n session.setConfig(\"StrictHostKeyChecking\", \"no\");\n } catch (Exception t) {\n throw new RuntimeException(t);\n }\n return session;\n }",
"private ProjectFile handleSQLiteFile(InputStream stream) throws Exception\n {\n File file = InputStreamHelper.writeStreamToTempFile(stream, \".sqlite\");\n\n try\n {\n Class.forName(\"org.sqlite.JDBC\");\n String url = \"jdbc:sqlite:\" + file.getCanonicalPath();\n Set<String> tableNames = populateTableNames(url);\n\n if (tableNames.contains(\"EXCEPTIONN\"))\n {\n return readProjectFile(new AstaDatabaseFileReader(), file);\n }\n\n if (tableNames.contains(\"PROJWBS\"))\n {\n Connection connection = null;\n try\n {\n Properties props = new Properties();\n props.setProperty(\"date_string_format\", \"yyyy-MM-dd HH:mm:ss\");\n connection = DriverManager.getConnection(url, props);\n PrimaveraDatabaseReader reader = new PrimaveraDatabaseReader();\n reader.setConnection(connection);\n addListeners(reader);\n return reader.read();\n }\n finally\n {\n if (connection != null)\n {\n connection.close();\n }\n }\n }\n\n if (tableNames.contains(\"ZSCHEDULEITEM\"))\n {\n return readProjectFile(new MerlinReader(), file);\n }\n\n return null;\n }\n\n finally\n {\n FileHelper.deleteQuietly(file);\n }\n }",
"public Where<T, ID> in(String columnName, Object... objects) throws SQLException {\n\t\treturn in(true, columnName, objects);\n\t}",
"private org.apache.tools.ant.types.Path addSlaveClasspath() {\n org.apache.tools.ant.types.Path path = new org.apache.tools.ant.types.Path(getProject());\n\n String [] REQUIRED_SLAVE_CLASSES = {\n SlaveMain.class.getName(),\n Strings.class.getName(),\n MethodGlobFilter.class.getName(),\n TeeOutputStream.class.getName()\n };\n\n for (String clazz : Arrays.asList(REQUIRED_SLAVE_CLASSES)) {\n String resource = clazz.replace(\".\", \"/\") + \".class\";\n File f = LoaderUtils.getResourceSource(getClass().getClassLoader(), resource);\n if (f != null) {\n path.createPath().setLocation(f);\n } else {\n throw new BuildException(\"Could not locate classpath for resource: \" + resource);\n }\n }\n return path;\n }",
"public AsciiTable setTextAlignment(TextAlignment textAlignment){\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setTextAlignment(textAlignment);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"protected void parseCombineIntegerLists(TokenList tokens) {\n TokenList.Token t = tokens.getFirst();\n if( t == null || t.next == null )\n return;\n\n int numFound = 0;\n\n TokenList.Token start = null;\n TokenList.Token end = null;\n\n while( t != null ) {\n if( t.getType() == Type.VARIABLE && (isVariableInteger(t) ||\n t.getVariable().getType() == VariableType.INTEGER_SEQUENCE )) {\n if( numFound == 0 ) {\n numFound = 1;\n start = end = t;\n } else {\n numFound++;\n end = t;\n }\n } else if( numFound > 1 ) {\n IntegerSequence sequence = new IntegerSequence.Combined(start,end);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(sequence);\n replaceSequence(tokens, varSequence, start, end);\n numFound = 0;\n } else {\n numFound = 0;\n }\n t = t.next;\n }\n\n if( numFound > 1 ) {\n IntegerSequence sequence = new IntegerSequence.Combined(start,end);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(sequence);\n replaceSequence(tokens, varSequence, start, end);\n }\n }",
"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 }",
"private void deliverMasterChangedAnnouncement(final DeviceUpdate update) {\n for (final MasterListener listener : getMasterListeners()) {\n try {\n listener.masterChanged(update);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering master changed announcement to listener\", t);\n }\n }\n }",
"public BoxFolder.Info getFolderInfo(String folderID) {\n URL url = FOLDER_INFO_URL_TEMPLATE.build(this.api.getBaseURL(), folderID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n BoxFolder folder = new BoxFolder(this.api, jsonObject.get(\"id\").asString());\n return folder.new Info(response.getJSON());\n }"
] |
Exceptions specific to each operation is handled in the corresponding
subclass. At this point we don't know the reason behind this exception.
@param exception | [
"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 static float smoothStep(float a, float b, float x) {\n\t\tif (x < a)\n\t\t\treturn 0;\n\t\tif (x >= b)\n\t\t\treturn 1;\n\t\tx = (x - a) / (b - a);\n\t\treturn x*x * (3 - 2*x);\n\t}",
"protected boolean lacksSomeLanguage(ItemDocument itemDocument) {\n\t\tfor (int i = 0; i < arabicNumeralLanguages.length; i++) {\n\t\t\tif (!itemDocument.getLabels()\n\t\t\t\t\t.containsKey(arabicNumeralLanguages[i])) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"@Override\n\tprotected void doLinking() {\n\t\tIParseResult parseResult = getParseResult();\n\t\tif (parseResult == null || parseResult.getRootASTElement() == null)\n\t\t\treturn;\n\n\t\tXtextLinker castedLinker = (XtextLinker) getLinker();\n\t\tcastedLinker.discardGeneratedPackages(parseResult.getRootASTElement());\n\t}",
"@Override\n public final String getString(final int i) {\n String val = this.array.optString(i, null);\n if (val == null) {\n throw new ObjectMissingException(this, \"[\" + i + \"]\");\n }\n return val;\n }",
"private void updateScheduleSource(ProjectProperties properties)\n {\n // Rudimentary identification of schedule source\n if (properties.getCompany() != null && properties.getCompany().equals(\"Synchro Software Ltd\"))\n {\n properties.setFileApplication(\"Synchro\");\n }\n else\n {\n if (properties.getAuthor() != null && properties.getAuthor().equals(\"SG Project\"))\n {\n properties.setFileApplication(\"Simple Genius\");\n }\n else\n {\n properties.setFileApplication(\"Microsoft\");\n }\n }\n properties.setFileType(\"MSPDI\");\n }",
"protected static final String formatUsingFormat(Long value, DateTimeFormat fmt) {\n if (value == null) {\n return \"\";\n }\n else {\n // midnight GMT\n Date date = new Date(0);\n // offset by timezone and value\n date.setTime(UTCDateBox.timezoneOffsetMillis(date) + value.longValue());\n // format it\n return fmt.format(date);\n }\n }",
"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 }",
"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 Duration getWork(FastTrackField type)\n {\n Double value = (Double) getObject(type);\n return value == null ? null : Duration.getInstance(value.doubleValue(), m_table.getWorkTimeUnit());\n }"
] |
Ask the specified player for the specified artwork from the specified media slot, first checking if we have a
cached copy.
@param artReference uniquely identifies the desired artwork
@param trackType the kind of track that owns the artwork
@return the artwork, if it was found, or {@code null}
@throws IllegalStateException if the ArtFinder is not running | [
"public AlbumArt requestArtworkFrom(final DataReference artReference, final CdjStatus.TrackType trackType) {\n ensureRunning();\n AlbumArt artwork = findArtInMemoryCaches(artReference); // First check the in-memory artwork caches.\n if (artwork == null) {\n artwork = requestArtworkInternal(artReference, trackType, false);\n }\n return artwork;\n }"
] | [
"public double[] getZeroRates(double[] maturities)\n\t{\n\t\tdouble[] values = new double[maturities.length];\n\n\t\tfor(int i=0; i<maturities.length; i++) {\n\t\t\tvalues[i] = getZeroRate(maturities[i]);\n\t\t}\n\n\t\treturn values;\n\t}",
"protected void parseIntegerLists(TokenList tokens) {\n TokenList.Token t = tokens.getFirst();\n if( t == null || t.next == null )\n return;\n\n int state = 0;\n\n TokenList.Token start = null;\n TokenList.Token prev = t;\n\n boolean last = false;\n while( true ) {\n if( state == 0 ) {\n if( isVariableInteger(t) ) {\n start = t;\n state = 1;\n }\n } else if( state == 1 ) {\n // var ?\n if( isVariableInteger(t)) { // see if its explicit number sequence\n state = 2;\n } else { // just scalar integer, skip\n state = 0;\n }\n } else if ( state == 2 ) {\n // var var ....\n if( !isVariableInteger(t) ) {\n // create explicit list sequence\n IntegerSequence sequence = new IntegerSequence.Explicit(start,prev);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(sequence);\n replaceSequence(tokens, varSequence, start, prev);\n state = 0;\n }\n }\n\n if( last ) {\n break;\n } else if( t.next == null ) {\n // handle the case where it is the last token in the sequence\n last = true;\n }\n prev = t;\n t = t.next;\n }\n }",
"public final void setValue(String value) {\n\n if ((null == value) || value.isEmpty()) {\n setDefaultValue();\n } else {\n try {\n tryToSetParsedValue(value);\n } catch (@SuppressWarnings(\"unused\") Exception e) {\n CmsDebugLog.consoleLog(\"Could not set invalid serial date value: \" + value);\n setDefaultValue();\n }\n }\n notifyOnValueChange();\n }",
"private void handleDirectory(final Predicate<String> filter, final File rootDir, final List<String> discoveredFiles)\n {\n try\n {\n new DirectoryWalker<String>()\n {\n private Path startDir;\n\n public void walk() throws IOException\n {\n this.startDir = rootDir.toPath();\n this.walk(rootDir, discoveredFiles);\n }\n\n @Override\n protected void handleFile(File file, int depth, Collection<String> discoveredFiles) throws IOException\n {\n String newPath = startDir.relativize(file.toPath()).toString();\n if (filter.accept(newPath))\n discoveredFiles.add(newPath);\n }\n\n }.walk();\n }\n catch (IOException ex)\n {\n LOG.log(Level.SEVERE, \"Error reading Furnace addon directory\", ex);\n }\n }",
"public 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}",
"void updateFromResponseOnPutPatch(Response<ResponseBody> response) throws CloudException, IOException {\n String responseContent = null;\n if (response.body() != null) {\n responseContent = response.body().string();\n response.body().close();\n }\n\n if (responseContent == null || responseContent.isEmpty()) {\n throw new CloudException(\"polling response does not contain a valid body\", response);\n }\n\n PollingResource resource = serializerAdapter.deserialize(responseContent, PollingResource.class);\n final int statusCode = response.code();\n if (resource != null && resource.properties != null && resource.properties.provisioningState != null) {\n this.withStatus(resource.properties.provisioningState, statusCode);\n } else {\n this.withStatus(AzureAsyncOperation.SUCCESS_STATUS, statusCode);\n }\n\n CloudError error = new CloudError();\n this.withErrorBody(error);\n error.withCode(this.status());\n error.withMessage(\"Long running operation failed\");\n this.withResponse(response);\n this.withResource(serializerAdapter.<T>deserialize(responseContent, resourceType));\n }",
"public String[] getUrl() {\n String[] valueDestination = new String[ url.size() ];\n this.url.getValue(valueDestination);\n return valueDestination;\n }",
"public static String decodeUrlIso(String stringToDecode) {\n try {\n return URLDecoder.decode(stringToDecode, \"ISO-8859-1\");\n } catch (UnsupportedEncodingException e1) {\n throw new RuntimeException(e1);\n }\n }",
"public void addStep(String name, String robot, Map<String, Object> options){\n steps.addStep(name, robot, options);\n }"
] |
Pretty prints a task list of rebalancing tasks.
@param infos list of rebalancing tasks (RebalancePartitionsInfo)
@return pretty-printed string | [
"public static String taskListToString(List<RebalanceTaskInfo> infos) {\n StringBuffer sb = new StringBuffer();\n for (RebalanceTaskInfo info : infos) {\n sb.append(\"\\t\").append(info.getDonorId()).append(\" -> \").append(info.getStealerId()).append(\" : [\");\n for (String storeName : info.getPartitionStores()) {\n sb.append(\"{\").append(storeName).append(\" : \").append(info.getPartitionIds(storeName)).append(\"}\");\n }\n sb.append(\"]\").append(Utils.NEWLINE);\n }\n return sb.toString();\n }"
] | [
"public static inatparam get(nitro_service service) throws Exception{\n\t\tinatparam obj = new inatparam();\n\t\tinatparam[] response = (inatparam[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public boolean uploadConfigurationAndProfile(String fileName, String odoImport) {\n File file = new File(fileName);\n MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();\n FileBody fileBody = new FileBody(file, ContentType.MULTIPART_FORM_DATA);\n multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);\n multipartEntityBuilder.addPart(\"fileData\", fileBody);\n multipartEntityBuilder.addTextBody(\"odoImport\", odoImport);\n try {\n JSONObject response = new JSONObject(doMultipartPost(BASE_BACKUP_PROFILE + \"/\" + uriEncode(this._profileName) + \"/\" + this._clientId, multipartEntityBuilder));\n if (response.length() == 0) {\n return true;\n } else {\n return false;\n }\n } catch (Exception e) {\n return false;\n }\n }",
"public JavadocComment toComment(String indentation) {\n for (char c : indentation.toCharArray()) {\n if (!Character.isWhitespace(c)) {\n throw new IllegalArgumentException(\"The indentation string should be composed only by whitespace characters\");\n }\n }\n StringBuilder sb = new StringBuilder();\n sb.append(EOL);\n final String text = toText();\n if (!text.isEmpty()) {\n for (String line : text.split(EOL)) {\n sb.append(indentation);\n sb.append(\" * \");\n sb.append(line);\n sb.append(EOL);\n }\n }\n sb.append(indentation);\n sb.append(\" \");\n return new JavadocComment(sb.toString());\n }",
"public Group lookupGroup(String url) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_LOOKUP_GROUP);\r\n\r\n parameters.put(\"url\", url);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Group group = new Group();\r\n Element payload = response.getPayload();\r\n Element groupnameElement = (Element) payload.getElementsByTagName(\"groupname\").item(0);\r\n group.setId(payload.getAttribute(\"id\"));\r\n group.setName(((Text) groupnameElement.getFirstChild()).getData());\r\n return group;\r\n }",
"public static Object xmlToObject(String fileName) throws FileNotFoundException {\r\n\t\tFileInputStream fi = new FileInputStream(fileName);\r\n\t\tXMLDecoder decoder = new XMLDecoder(fi);\r\n\t\tObject object = decoder.readObject();\r\n\t\tdecoder.close();\r\n\t\treturn object;\r\n\t}",
"private void processLayouts(Project phoenixProject)\n {\n //\n // Find the active layout\n //\n Layout activeLayout = getActiveLayout(phoenixProject);\n\n //\n // Create a list of the visible codes in the correct order\n //\n for (CodeOption option : activeLayout.getCodeOptions().getCodeOption())\n {\n if (option.isShown().booleanValue())\n {\n m_codeSequence.add(getUUID(option.getCodeUuid(), option.getCode()));\n }\n }\n }",
"public static ipseccounters_stats get(nitro_service service) throws Exception{\n\t\tipseccounters_stats obj = new ipseccounters_stats();\n\t\tipseccounters_stats[] response = (ipseccounters_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}",
"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 }",
"@AfterThrowing(pointcut = \"execution(* org.apache.cassandra.thrift.CassandraServer.doInsert(..))\", throwing = \"throwable\")\n public void logErrorFromThrownException(final JoinPoint joinPoint, final Throwable throwable) {\n final String className = joinPoint.getTarget().getClass().getName();\n final String methodName = joinPoint.getSignature().getName();\n\n logger.error(\"Could not write to cassandra! Method: \" + className + \".\"+ methodName + \"()\", throwable);\n }"
] |
Get the AuthInterface.
@return The AuthInterface | [
"@Override\n public AuthInterface getAuthInterface() {\n if (authInterface == null) {\n authInterface = new AuthInterface(apiKey, sharedSecret, transport);\n }\n return authInterface;\n }"
] | [
"public static void doBatchEnqueue(final Jedis jedis, final String namespace, final String queue, final List<String> jobJsons) {\n Pipeline pipelined = jedis.pipelined();\n pipelined.sadd(JesqueUtils.createKey(namespace, QUEUES), queue);\n for (String jobJson : jobJsons) {\n pipelined.rpush(JesqueUtils.createKey(namespace, QUEUE, queue), jobJson);\n }\n pipelined.sync();\n }",
"void attachMetadataCacheInternal(SlotReference slot, MetadataCache cache) {\n MetadataCache oldCache = metadataCacheFiles.put(slot, cache);\n if (oldCache != null) {\n try {\n oldCache.close();\n } catch (IOException e) {\n logger.error(\"Problem closing previous metadata cache\", e);\n }\n }\n\n deliverCacheUpdate(slot, cache);\n }",
"ValidationResult isRestrictedEventName(String name) {\n ValidationResult error = new ValidationResult();\n if (name == null) {\n error.setErrorCode(510);\n error.setErrorDesc(\"Event Name is null\");\n return error;\n }\n for (String x : restrictedNames)\n if (name.equalsIgnoreCase(x)) {\n // The event name is restricted\n\n error.setErrorCode(513);\n error.setErrorDesc(name + \" is a restricted event name. Last event aborted.\");\n Logger.v(name + \" is a restricted system event name. Last event aborted.\");\n return error;\n }\n return error;\n }",
"@SuppressWarnings({ \"unchecked\" })\n public static <T> T[] readArrayAttributeElement(final XMLExtendedStreamReader reader, final String attributeName,\n final Class<T> type) throws XMLStreamException {\n final List<T> list = readListAttributeElement(reader, attributeName, type);\n return list.toArray((T[]) Array.newInstance(type, list.size()));\n }",
"private 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 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 execute()\n {\n Runnable task = new Runnable()\n {\n public void run()\n {\n final V result = performTask();\n SwingUtilities.invokeLater(new Runnable()\n {\n public void run()\n {\n postProcessing(result);\n latch.countDown();\n }\n });\n }\n };\n new Thread(task, \"SwingBackgroundTask-\" + id).start();\n }",
"protected String getExpectedMessage() {\r\n StringBuilder syntax = new StringBuilder(\"<tag> \");\r\n syntax.append(getName());\r\n\r\n String args = getArgSyntax();\r\n if (args != null && args.length() > 0) {\r\n syntax.append(' ');\r\n syntax.append(args);\r\n }\r\n\r\n return syntax.toString();\r\n }",
"public static int Minimum(ImageSource fastBitmap, int startX, int startY, int width, int height) {\r\n int min = 255;\r\n if (fastBitmap.isGrayscale()) {\r\n for (int i = startX; i < height; i++) {\r\n for (int j = startY; j < width; j++) {\r\n int gray = fastBitmap.getRGB(j, i);\r\n if (gray < min) {\r\n min = gray;\r\n }\r\n }\r\n }\r\n } else {\r\n for (int i = startX; i < height; i++) {\r\n for (int j = startY; j < width; j++) {\r\n int gray = fastBitmap.getG(j, i);\r\n if (gray < min) {\r\n min = gray;\r\n }\r\n }\r\n }\r\n }\r\n return min;\r\n }"
] |
Adds an additional description to the constructed document.
@param text
the text of the description
@param languageCode
the language code of the description
@return builder object to continue construction | [
"public T withDescription(String text, String languageCode) {\n\t\twithDescription(factory.getMonolingualTextValue(text, languageCode));\n\t\treturn getThis();\n\t}"
] | [
"private void setW() {\n if( saveW ) {\n W.col0 = Y.col0;\n W.col1 = Y.col1;\n W.row0 = Y.row0;\n W.row1 = Y.row1;\n } else {\n W.col1 = Y.col1 - Y.col0;\n W.row0 = Y.row0;\n }\n }",
"private boolean readNextRow() {\n while (!stop) {\n String row = getLineWrapped();\n // end of stream - null indicates end of stream before we see last_seq which shouldn't\n // be possible but we should handle it\n if (row == null || row.startsWith(\"{\\\"last_seq\\\":\")) {\n terminate();\n return false;\n } else if (row.isEmpty()) {\n // heartbeat\n continue;\n }\n setNextRow(gson.fromJson(row, ChangesResult.Row.class));\n return true;\n }\n // we were stopped, end of changes feed\n terminate();\n return false;\n }",
"public static CmsUUID readId(JSONObject obj, String key) {\n\n String strValue = obj.optString(key);\n if (!CmsUUID.isValidUUID(strValue)) {\n return null;\n }\n return new CmsUUID(strValue);\n }",
"public static <T> void filterListToMap(final Map<String, T> destinationMap, final String[] nameMapping,\n\t\tfinal List<? extends T> sourceList) {\n\t\tif( destinationMap == null ) {\n\t\t\tthrow new NullPointerException(\"destinationMap should not be null\");\n\t\t} else if( nameMapping == null ) {\n\t\t\tthrow new NullPointerException(\"nameMapping should not be null\");\n\t\t} else if( sourceList == null ) {\n\t\t\tthrow new NullPointerException(\"sourceList should not be null\");\n\t\t} else if( nameMapping.length != sourceList.size() ) {\n\t\t\tthrow new SuperCsvException(\n\t\t\t\tString\n\t\t\t\t\t.format(\n\t\t\t\t\t\t\"the nameMapping array and the sourceList should be the same size (nameMapping length = %d, sourceList size = %d)\",\n\t\t\t\t\t\tnameMapping.length, sourceList.size()));\n\t\t}\n\t\t\n\t\tdestinationMap.clear();\n\t\t\n\t\tfor( int i = 0; i < nameMapping.length; i++ ) {\n\t\t\tfinal String key = nameMapping[i];\n\t\t\t\n\t\t\tif( key == null ) {\n\t\t\t\tcontinue; // null's in the name mapping means skip column\n\t\t\t}\n\t\t\t\n\t\t\t// no duplicates allowed\n\t\t\tif( destinationMap.containsKey(key) ) {\n\t\t\t\tthrow new SuperCsvException(String.format(\"duplicate nameMapping '%s' at index %d\", key, i));\n\t\t\t}\n\t\t\t\n\t\t\tdestinationMap.put(key, sourceList.get(i));\n\t\t}\n\t}",
"private 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 }",
"public static float distance(final float ax, final float ay,\n final float bx, final float by) {\n return (float) Math.sqrt(\n (ax - bx) * (ax - bx) +\n (ay - by) * (ay - by)\n );\n }",
"public ParallelTask getTaskFromInProgressMap(String jobId) {\n if (!inprogressTaskMap.containsKey(jobId))\n return null;\n return inprogressTaskMap.get(jobId);\n }",
"public void setTargetDirectory(String directory) {\n if (directory != null && directory.length() > 0) {\n this.targetDirectory = new File(directory);\n } else {\n this.targetDirectory = null;\n }\n }",
"public <T> T fetchObject(String objectId, Class<T> type) {\n\t\tURI uri = URIBuilder.fromUri(getBaseGraphApiUrl() + objectId).build();\n\t\treturn getRestTemplate().getForObject(uri, type);\n\t}"
] |
Call the Yahoo! PlaceFinder service for a result.
@param q
search string
@param maxRows
max number of rows in result, or 0 for all
@param locale
locale for strings
@return list of found results
@throws Exception
oops
@see <a
href="http://developer.yahoo.com/boss/geo/docs/free_YQL.html#table_pf">Yahoo!
Boss Geo PlaceFinder</a> | [
"public List<GetLocationResult> search(String q, int maxRows, Locale locale)\n\t\t\tthrows Exception {\n\t\tList<GetLocationResult> searchResult = new ArrayList<GetLocationResult>();\n\n\t\tString url = URLEncoder.encode(q, \"UTF8\");\n\t\turl = \"q=select%20*%20from%20geo.placefinder%20where%20text%3D%22\"\n\t\t\t\t+ url + \"%22\";\n\t\tif (maxRows > 0) {\n\t\t\turl = url + \"&count=\" + maxRows;\n\t\t}\n\t\turl = url + \"&flags=GX\";\n\t\tif (null != locale) {\n\t\t\turl = url + \"&locale=\" + locale;\n\t\t}\n\t\tif (appId != null) {\n\t\t\turl = url + \"&appid=\" + appId;\n\t\t}\n\n\t\tInputStream inputStream = connect(url);\n\t\tif (null != inputStream) {\n\t\t\tSAXBuilder parser = new SAXBuilder();\n\t\t\tDocument doc = parser.build(inputStream);\n\n\t\t\tElement root = doc.getRootElement();\n\n\t\t\t// check code for exception\n\t\t\tString message = root.getChildText(\"Error\");\n\t\t\t// Integer errorCode = Integer.parseInt(message);\n\t\t\tif (message != null && Integer.parseInt(message) != 0) {\n\t\t\t\tthrow new Exception(root.getChildText(\"ErrorMessage\"));\n\t\t\t}\n\t\t\tElement results = root.getChild(\"results\");\n\t\t\tfor (Object obj : results.getChildren(\"Result\")) {\n\t\t\t\tElement toponymElement = (Element) obj;\n\t\t\t\tGetLocationResult location = getLocationFromElement(toponymElement);\n\t\t\t\tsearchResult.add(location);\n\t\t\t}\n\t\t}\n\t\treturn searchResult;\n\t}"
] | [
"public String getBaselineDurationText(int baselineNumber)\n {\n Object result = getCachedValue(selectField(TaskFieldLists.BASELINE_DURATIONS, baselineNumber));\n if (result == null)\n {\n result = getCachedValue(selectField(TaskFieldLists.BASELINE_ESTIMATED_DURATIONS, baselineNumber));\n }\n\n if (!(result instanceof String))\n {\n result = null;\n }\n return (String) result;\n }",
"public void setLocale(String locale) {\n\n try {\n m_locale = LocaleUtils.toLocale(locale);\n } catch (IllegalArgumentException e) {\n LOG.error(Messages.get().getBundle().key(Messages.ERR_TAG_INVALID_LOCALE_1, \"cms:navigation\"), e);\n m_locale = null;\n }\n }",
"private static void parseBounds(JSONObject modelJSON,\n Shape current) throws JSONException {\n if (modelJSON.has(\"bounds\")) {\n JSONObject boundsObject = modelJSON.getJSONObject(\"bounds\");\n current.setBounds(new Bounds(new Point(boundsObject.getJSONObject(\"lowerRight\").getDouble(\"x\"),\n boundsObject.getJSONObject(\"lowerRight\").getDouble(\n \"y\")),\n new Point(boundsObject.getJSONObject(\"upperLeft\").getDouble(\"x\"),\n boundsObject.getJSONObject(\"upperLeft\").getDouble(\"y\"))));\n }\n }",
"public void setValueSelected(T value, boolean selected) {\n int idx = getIndex(value);\n if (idx >= 0) {\n setItemSelectedInternal(idx, selected);\n }\n }",
"private Proctor getProctorNotNull() {\n final Proctor proctor = proctorLoader.get();\n if (proctor == null) {\n throw new IllegalStateException(\"Proctor specification and/or text matrix has not been loaded\");\n }\n return proctor;\n }",
"private ServerDetails createInitialDeployDetailsFromOldDeployDetails(ServerDetails oldDeployerDetails) {\n RepositoryConf oldDeployRepositoryConfig = oldDeployerDetails.getDeployReleaseRepository();\n RepositoryConf oldSnapshotDeployRepositoryConfig = oldDeployerDetails.getDeploySnapshotRepository();\n RepositoryConf deployReleaseRepos = oldDeployRepositoryConfig == null ? RepositoryConf.emptyRepositoryConfig : oldDeployRepositoryConfig;\n RepositoryConf deploySnapshotRepos = oldSnapshotDeployRepositoryConfig == null ? RepositoryConf.emptyRepositoryConfig : oldSnapshotDeployRepositoryConfig;\n return new ServerDetails(oldDeployerDetails.getArtifactoryName(), oldDeployerDetails.getArtifactoryUrl(),\n deployReleaseRepos, deploySnapshotRepos, null, null, null, null);\n }",
"private void solveInternalL() {\n // This takes advantage of the diagonal elements always being real numbers\n\n // solve L*y=b storing y in x\n TriangularSolver_ZDRM.solveL_diagReal(t, vv, n);\n\n // solve L^T*x=y\n TriangularSolver_ZDRM.solveConjTranL_diagReal(t, vv, n);\n }",
"public final static int readUntil(final StringBuilder out, final String in, final int start, final char end)\n {\n int pos = start;\n while (pos < in.length())\n {\n final char ch = in.charAt(pos);\n if (ch == '\\\\' && pos + 1 < in.length())\n {\n pos = escape(out, in.charAt(pos + 1), pos);\n }\n else\n {\n if (ch == end)\n {\n break;\n }\n out.append(ch);\n }\n pos++;\n }\n\n return (pos == in.length()) ? -1 : pos;\n }",
"public static void copy(String in, Writer out) throws IOException {\n\t\tAssert.notNull(in, \"No input String specified\");\n\t\tAssert.notNull(out, \"No Writer specified\");\n\t\ttry {\n\t\t\tout.write(in);\n\t\t}\n\t\tfinally {\n\t\t\ttry {\n\t\t\t\tout.close();\n\t\t\t}\n\t\t\tcatch (IOException ex) {\n\t\t\t}\n\t\t}\n\t}"
] |
Resolves the path relative to the parent and normalizes it.
@param parent the parent path
@param path the path
@return the normalized path | [
"protected Path normalizePath(final Path parent, final String path) {\n return parent.resolve(path).toAbsolutePath().normalize();\n }"
] | [
"@DELETE\n @Path(\"/{name}\" + ServerAPI.GET_CORPORATE_GROUPIDS)\n public Response removeCorporateGroupIdPrefix(@Auth final DbCredential credential, @PathParam(\"name\") final String organizationId, final String corporateGroupId){\n LOG.info(\"Got an remove a corporate groupId prefix request for organization \" + organizationId +\".\");\n if(!credential.getRoles().contains(DbCredential.AvailableRoles.DATA_UPDATER)){\n throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).build());\n }\n\n if(corporateGroupId == null || corporateGroupId.isEmpty()){\n LOG.error(\"No corporate GroupId to remove!\");\n return Response.serverError().status(HttpStatus.BAD_REQUEST_400).build();\n }\n\n getOrganizationHandler().removeCorporateGroupId(organizationId, corporateGroupId);\n\n return Response.ok(\"done\").build();\n }",
"public static final Double getDouble(InputStream is) throws IOException\n {\n double result = Double.longBitsToDouble(getLong(is));\n if (Double.isNaN(result))\n {\n result = 0;\n }\n return Double.valueOf(result);\n }",
"public static appfwpolicy_csvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwpolicy_csvserver_binding obj = new appfwpolicy_csvserver_binding();\n\t\tobj.set_name(name);\n\t\tappfwpolicy_csvserver_binding response[] = (appfwpolicy_csvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"@SuppressWarnings({\"WeakerAccess\"})\n protected void initDeviceID() {\n getDeviceCachedInfo(); // put this here to avoid running on main thread\n\n // generate a provisional while we do the rest async\n generateProvisionalGUID();\n // grab and cache the googleAdID in any event if available\n // if we already have a deviceID we won't user ad id as the guid\n cacheGoogleAdID();\n\n // if we already have a device ID use it and just notify\n // otherwise generate one, either from ad id if available or the provisional\n String deviceID = getDeviceID();\n if (deviceID == null || deviceID.trim().length() <= 2) {\n generateDeviceID();\n }\n\n }",
"public void initialize() {\n if (isClosed.get()) {\n logger.info(\"Initialing Parallel Client Resources: actor system, HttpClientStore, Task Manager ....\");\n ActorConfig.createAndGetActorSystem();\n httpClientStore.init();\n tcpSshPingResourceStore.init();\n isClosed.set(false);\n logger.info(\"Parallel Client Resources has been initialized.\");\n } else {\n logger.debug(\"NO OP. Parallel Client Resources has already been initialized.\");\n }\n }",
"public static boolean isFileExist(String filePath) {\n\n File f = new File(filePath);\n\n return f.exists() && !f.isDirectory();\n }",
"Map<Object, Object> getFilters() {\n\n Map<Object, Object> result = new HashMap<Object, Object>(4);\n result.put(TableProperty.KEY, m_table.getFilterFieldValue(TableProperty.KEY));\n result.put(TableProperty.DEFAULT, m_table.getFilterFieldValue(TableProperty.DEFAULT));\n result.put(TableProperty.DESCRIPTION, m_table.getFilterFieldValue(TableProperty.DESCRIPTION));\n result.put(TableProperty.TRANSLATION, m_table.getFilterFieldValue(TableProperty.TRANSLATION));\n return result;\n }",
"public List<Dependency> getModuleAncestors(final String moduleName, final String moduleVersion) throws GrapesCommunicationException {\n final Client client = getClient();\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactAncestors(moduleName, moduleVersion));\n final ClientResponse response = resource.queryParam(ServerAPI.SCOPE_COMPILE_PARAM, \"true\")\n .queryParam(ServerAPI.SCOPE_PROVIDED_PARAM, \"true\")\n .queryParam(ServerAPI.SCOPE_RUNTIME_PARAM, \"true\")\n .queryParam(ServerAPI.SCOPE_TEST_PARAM, \"true\")\n .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = String.format(FAILED_TO_GET_MODULE, \"get module ancestors\", moduleName, moduleVersion);\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n\n return response.getEntity(new GenericType<List<Dependency>>(){});\n }",
"static PatchingResult executeTasks(final IdentityPatchContext context, final IdentityPatchContext.FinalizeCallback callback) throws Exception {\n final List<PreparedTask> tasks = new ArrayList<PreparedTask>();\n final List<ContentItem> conflicts = new ArrayList<ContentItem>();\n // Identity\n prepareTasks(context.getIdentityEntry(), context, tasks, conflicts);\n // Layers\n for (final IdentityPatchContext.PatchEntry layer : context.getLayers()) {\n prepareTasks(layer, context, tasks, conflicts);\n }\n // AddOns\n for (final IdentityPatchContext.PatchEntry addOn : context.getAddOns()) {\n prepareTasks(addOn, context, tasks, conflicts);\n }\n // If there were problems report them\n if (!conflicts.isEmpty()) {\n throw PatchLogger.ROOT_LOGGER.conflictsDetected(conflicts);\n }\n // Execute the tasks\n for (final PreparedTask task : tasks) {\n // Unless it's excluded by the user\n final ContentItem item = task.getContentItem();\n if (item != null && context.isExcluded(item)) {\n continue;\n }\n // Run the task\n task.execute();\n }\n return context.finalize(callback);\n }"
] |
Returns a canonical type for a given class.
If the class is a raw type of a parameterized class, the matching {@link ParameterizedType} (with unresolved type
variables) is resolved.
If the class is an array then the component type of the array is canonicalized
Otherwise, the class is returned.
@return | [
"public static Type getCanonicalType(Class<?> clazz) {\n if (clazz.isArray()) {\n Class<?> componentType = clazz.getComponentType();\n Type resolvedComponentType = getCanonicalType(componentType);\n if (componentType != resolvedComponentType) {\n // identity check intentional\n // a different identity means that we actually replaced the component Class with a ParameterizedType\n return new GenericArrayTypeImpl(resolvedComponentType);\n }\n }\n if (clazz.getTypeParameters().length > 0) {\n Type[] actualTypeParameters = clazz.getTypeParameters();\n return new ParameterizedTypeImpl(clazz, actualTypeParameters, clazz.getDeclaringClass());\n }\n return clazz;\n }"
] | [
"public void seekToDayOfMonth(String dayOfMonth) {\n int dayOfMonthInt = Integer.parseInt(dayOfMonth);\n assert(dayOfMonthInt >= 1 && dayOfMonthInt <= 31);\n \n markDateInvocation();\n \n dayOfMonthInt = Math.min(dayOfMonthInt, _calendar.getActualMaximum(Calendar.DAY_OF_MONTH));\n _calendar.set(Calendar.DAY_OF_MONTH, dayOfMonthInt);\n }",
"private void uncheckAll(CmsList<? extends I_CmsListItem> list) {\r\n\r\n for (Widget it : list) {\r\n CmsTreeItem treeItem = (CmsTreeItem)it;\r\n treeItem.getCheckBox().setChecked(false);\r\n uncheckAll(treeItem.getChildren());\r\n }\r\n }",
"public void moveDown(I_CmsEditableGroupRow row) {\n\n int index = m_container.getComponentIndex(row);\n if ((index >= 0) && (index < (m_container.getComponentCount() - 1))) {\n m_container.removeComponent(row);\n m_container.addComponent(row, index + 1);\n }\n updateButtonBars();\n }",
"private void addJoinInfo(JoinType type, String localColumnName, String joinedColumnName,\n\t\t\tQueryBuilder<?, ?> joinedQueryBuilder, JoinWhereOperation operation) throws SQLException {\n\t\tJoinInfo joinInfo = new JoinInfo(type, joinedQueryBuilder, operation);\n\t\tif (localColumnName == null) {\n\t\t\tmatchJoinedFields(joinInfo, joinedQueryBuilder);\n\t\t} else {\n\t\t\tmatchJoinedFieldsByName(joinInfo, localColumnName, joinedColumnName, joinedQueryBuilder);\n\t\t}\n\t\tif (joinList == null) {\n\t\t\tjoinList = new ArrayList<JoinInfo>();\n\t\t}\n\t\tjoinList.add(joinInfo);\n\t}",
"public List<TimephasedWork> getCompleteWork(ProjectCalendar calendar, ResourceAssignment resourceAssignment, byte[] data)\n {\n LinkedList<TimephasedWork> list = new LinkedList<TimephasedWork>();\n\n if (calendar != null && data != null && data.length > 2 && MPPUtility.getShort(data, 0) > 0)\n {\n Date startDate = resourceAssignment.getStart();\n double finishTime = MPPUtility.getInt(data, 24);\n\n int blockCount = MPPUtility.getShort(data, 0);\n double previousCumulativeWork = 0;\n TimephasedWork previousAssignment = null;\n\n int index = 32;\n int currentBlock = 0;\n while (currentBlock < blockCount && index + 20 <= data.length)\n {\n double time = MPPUtility.getInt(data, index + 0);\n\n // If the start of this block is before the start of the assignment, or after the end of the assignment\n // the values don't make sense, so we'll just set the start of this block to be the start of the assignment.\n // This deals with an issue where odd timephased data like this was causing an MPP file to be read\n // extremely slowly.\n if (time < 0 || time > finishTime)\n {\n time = 0;\n }\n else\n {\n time /= 80;\n }\n Duration startWork = Duration.getInstance(time, TimeUnit.MINUTES);\n\n double currentCumulativeWork = (long) MPPUtility.getDouble(data, index + 4);\n double assignmentDuration = currentCumulativeWork - previousCumulativeWork;\n previousCumulativeWork = currentCumulativeWork;\n assignmentDuration /= 1000;\n Duration totalWork = Duration.getInstance(assignmentDuration, TimeUnit.MINUTES);\n time = (long) MPPUtility.getDouble(data, index + 12);\n time /= 125;\n time *= 6;\n Duration workPerDay = Duration.getInstance(time, TimeUnit.MINUTES);\n\n Date start;\n if (startWork.getDuration() == 0)\n {\n start = startDate;\n }\n else\n {\n start = calendar.getDate(startDate, startWork, true);\n }\n\n TimephasedWork assignment = new TimephasedWork();\n assignment.setStart(start);\n assignment.setAmountPerDay(workPerDay);\n assignment.setTotalAmount(totalWork);\n\n if (previousAssignment != null)\n {\n Date finish = calendar.getDate(startDate, startWork, false);\n previousAssignment.setFinish(finish);\n if (previousAssignment.getStart().getTime() == previousAssignment.getFinish().getTime())\n {\n list.removeLast();\n }\n }\n\n list.add(assignment);\n previousAssignment = assignment;\n\n index += 20;\n ++currentBlock;\n }\n\n if (previousAssignment != null)\n {\n Duration finishWork = Duration.getInstance(finishTime / 80, TimeUnit.MINUTES);\n Date finish = calendar.getDate(startDate, finishWork, false);\n previousAssignment.setFinish(finish);\n if (previousAssignment.getStart().getTime() == previousAssignment.getFinish().getTime())\n {\n list.removeLast();\n }\n }\n }\n\n return list;\n }",
"public static <T> void write(BufferedWriter writer, DatabaseTableConfig<T> config) throws SQLException {\n\t\ttry {\n\t\t\twriteConfig(writer, config);\n\t\t} catch (IOException e) {\n\t\t\tthrow SqlExceptionUtil.create(\"Could not write config to writer\", e);\n\t\t}\n\t}",
"@SuppressWarnings(\"WeakerAccess\")\n public int getPlayerDBServerPort(int player) {\n ensureRunning();\n Integer result = dbServerPorts.get(player);\n if (result == null) {\n return -1;\n }\n return result;\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 }",
"@Override\n public void addVariable(String varName, Object value) {\n synchronized (mGlobalVariables) {\n mGlobalVariables.put(varName, value);\n }\n refreshGlobalBindings();\n }"
] |
Read a text file into a single string
@param file
The file to read
@return The contents, or null on error. | [
"public static String readTextFile(File file) {\n try {\n return readTextFile(new FileReader(file));\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n return null;\n }\n }"
] | [
"@Override\n public <E> DynamicType.Builder<E> processMethod(final DynamicType.Builder<E> builder, final Method method, final Annotation annotation)\n {\n String methodName = method.getName();\n if (ReflectionUtility.isGetMethod(method))\n return createInterceptor(builder, method);\n else if (ReflectionUtility.isSetMethod(method))\n return createInterceptor(builder, method);\n else if (methodName.startsWith(\"addAll\"))\n return createInterceptor(builder, method);\n else if (methodName.startsWith(\"add\"))\n return createInterceptor(builder, method);\n else\n throw new WindupException(\"Only get*, set*, add*, and addAll* method names are supported for @\"\n + SetInProperties.class.getSimpleName() + \", found at: \" + method.getName());\n }",
"public boolean contains(String column) {\n\t\tfor ( String columnName : columnNames ) {\n\t\t\tif ( columnName.equals( column ) ) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"public void showToast(final String message, float duration) {\n final float quadWidth = 1.2f;\n final GVRTextViewSceneObject toastSceneObject = new GVRTextViewSceneObject(this, quadWidth, quadWidth / 5,\n message);\n\n toastSceneObject.setTextSize(6);\n toastSceneObject.setTextColor(Color.WHITE);\n toastSceneObject.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.TOP);\n toastSceneObject.setBackgroundColor(Color.DKGRAY);\n toastSceneObject.setRefreshFrequency(GVRTextViewSceneObject.IntervalFrequency.REALTIME);\n\n final GVRTransform t = toastSceneObject.getTransform();\n t.setPositionZ(-1.5f);\n\n final GVRRenderData rd = toastSceneObject.getRenderData();\n final float finalOpacity = 0.7f;\n rd.getMaterial().setOpacity(0);\n rd.setRenderingOrder(2 * GVRRenderData.GVRRenderingOrder.OVERLAY);\n rd.setDepthTest(false);\n\n final GVRCameraRig rig = getMainScene().getMainCameraRig();\n rig.addChildObject(toastSceneObject);\n\n final GVRMaterialAnimation fadeOut = new GVRMaterialAnimation(rd.getMaterial(), duration / 4.0f) {\n @Override\n protected void animate(GVRHybridObject target, float ratio) {\n final GVRMaterial material = (GVRMaterial) target;\n material.setOpacity(finalOpacity - ratio * finalOpacity);\n }\n };\n fadeOut.setOnFinish(new GVROnFinish() {\n @Override\n public void finished(GVRAnimation animation) {\n rig.removeChildObject(toastSceneObject);\n }\n });\n\n final GVRMaterialAnimation fadeIn = new GVRMaterialAnimation(rd.getMaterial(), 3.0f * duration / 4.0f) {\n @Override\n protected void animate(GVRHybridObject target, float ratio) {\n final GVRMaterial material = (GVRMaterial) target;\n material.setOpacity(ratio * finalOpacity);\n }\n };\n fadeIn.setOnFinish(new GVROnFinish() {\n @Override\n public void finished(GVRAnimation animation) {\n getAnimationEngine().start(fadeOut);\n }\n });\n\n getAnimationEngine().start(fadeIn);\n }",
"private void storeToDb(Object obj, ClassDescriptor cld, Identity oid, boolean insert, boolean ignoreReferences)\n {\n // 1. link and store 1:1 references\n storeReferences(obj, cld, insert, ignoreReferences);\n\n Object[] pkValues = oid.getPrimaryKeyValues();\n if (!serviceBrokerHelper().assertValidPksForStore(cld.getPkFields(), pkValues))\n {\n // BRJ: fk values may be part of pk, but the are not known during\n // creation of Identity. so we have to get them here\n pkValues = serviceBrokerHelper().getKeyValues(cld, obj);\n if (!serviceBrokerHelper().assertValidPksForStore(cld.getPkFields(), pkValues))\n {\n String append = insert ? \" on insert\" : \" on update\" ;\n throw new PersistenceBrokerException(\"assertValidPkFields failed for Object of type: \" + cld.getClassNameOfObject() + append);\n }\n }\n\n // get super class cld then store it with the object\n /*\n now for multiple table inheritance\n 1. store super classes, topmost parent first\n 2. go down through heirarchy until current class\n 3. todo: store to full extent?\n\n// arminw: TODO: The extend-attribute feature dosn't work, should we remove this stuff?\n This if-clause will go up the inheritance heirarchy to store all the super classes.\n The id for the top most super class will be the id for all the subclasses too\n */\n if(cld.getSuperClass() != null)\n {\n\n ClassDescriptor superCld = getDescriptorRepository().getDescriptorFor(cld.getSuperClass());\n storeToDb(obj, superCld, oid, insert);\n // arminw: why this?? I comment out this section\n // storeCollections(obj, cld.getCollectionDescriptors(), insert);\n }\n\n // 2. store primitive typed attributes (Or is THIS step 3 ?)\n // if obj not present in db use INSERT\n if (insert)\n {\n dbAccess.executeInsert(cld, obj);\n if(oid.isTransient())\n {\n // Create a new Identity based on the current set of primary key values.\n oid = serviceIdentity().buildIdentity(cld, obj);\n }\n }\n // else use UPDATE\n else\n {\n try\n {\n dbAccess.executeUpdate(cld, obj);\n }\n catch(OptimisticLockException e)\n {\n // ensure that the outdated object be removed from cache\n objectCache.remove(oid);\n throw e;\n }\n }\n // cache object for symmetry with getObjectByXXX()\n // Add the object to the cache.\n objectCache.doInternalCache(oid, obj, ObjectCacheInternal.TYPE_WRITE);\n // 3. store 1:n and m:n associations\n if(!ignoreReferences) storeCollections(obj, cld, insert);\n }",
"public void handle(HttpRequest request, HttpResponder responder) {\n if (urlRewriter != null) {\n try {\n request.setUri(URI.create(request.uri()).normalize().toString());\n if (!urlRewriter.rewrite(request, responder)) {\n return;\n }\n } catch (Throwable t) {\n responder.sendString(HttpResponseStatus.INTERNAL_SERVER_ERROR,\n String.format(\"Caught exception processing request. Reason: %s\",\n t.getMessage()));\n LOG.error(\"Exception thrown during rewriting of uri {}\", request.uri(), t);\n return;\n }\n }\n\n try {\n String path = URI.create(request.uri()).normalize().getPath();\n\n List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>> routableDestinations\n = patternRouter.getDestinations(path);\n\n PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel> matchedDestination =\n getMatchedDestination(routableDestinations, request.method(), path);\n\n if (matchedDestination != null) {\n //Found a httpresource route to it.\n HttpResourceModel httpResourceModel = matchedDestination.getDestination();\n\n // Call preCall method of handler hooks.\n boolean terminated = false;\n HandlerInfo info = new HandlerInfo(httpResourceModel.getMethod().getDeclaringClass().getName(),\n httpResourceModel.getMethod().getName());\n for (HandlerHook hook : handlerHooks) {\n if (!hook.preCall(request, responder, info)) {\n // Terminate further request processing if preCall returns false.\n terminated = true;\n break;\n }\n }\n\n // Call httpresource method\n if (!terminated) {\n // Wrap responder to make post hook calls.\n responder = new WrappedHttpResponder(responder, handlerHooks, request, info);\n if (httpResourceModel.handle(request, responder, matchedDestination.getGroupNameValues()).isStreaming()) {\n responder.sendString(HttpResponseStatus.METHOD_NOT_ALLOWED,\n String.format(\"Body Consumer not supported for internalHttpResponder: %s\",\n request.uri()));\n }\n }\n } else if (routableDestinations.size() > 0) {\n //Found a matching resource but could not find the right HttpMethod so return 405\n responder.sendString(HttpResponseStatus.METHOD_NOT_ALLOWED,\n String.format(\"Problem accessing: %s. Reason: Method Not Allowed\", request.uri()));\n } else {\n responder.sendString(HttpResponseStatus.NOT_FOUND, String.format(\"Problem accessing: %s. Reason: Not Found\",\n request.uri()));\n }\n } catch (Throwable t) {\n responder.sendString(HttpResponseStatus.INTERNAL_SERVER_ERROR,\n String.format(\"Caught exception processing request. Reason: %s\", t.getMessage()));\n LOG.error(\"Exception thrown during request processing for uri {}\", request.uri(), t);\n }\n }",
"public void forAllColumns(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _curTableDef.getColumns(); it.hasNext(); )\r\n {\r\n _curColumnDef = (ColumnDef)it.next();\r\n generate(template);\r\n }\r\n _curColumnDef = null;\r\n }",
"@JsonProperty(\"labels\")\n @JsonInclude(Include.NON_EMPTY)\n public Map<String, TermImpl> getLabelUpdates() {\n \treturn getMonolingualUpdatedValues(newLabels);\n }",
"public static String defaultHtml(HttpServletRequest request) {\n\n CmsObject cms = CmsFlexController.getController(request).getCmsObject();\n\n // We only want the big red warning in Offline mode\n if (cms.getRequestContext().getCurrentProject().isOnlineProject()) {\n return \"<div><!--Dynamic function not configured--></div>\";\n } else {\n Locale locale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms);\n String message = Messages.get().getBundle(locale).key(Messages.GUI_FUNCTION_DEFAULT_HTML_0);\n return \"<div style=\\\"border: 2px solid red; padding: 10px;\\\">\" + message + \"</div>\";\n }\n }",
"public static int findLastIndexOf(Object self, int startIndex, Closure closure) {\n int result = -1;\n int i = 0;\n BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);\n for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); i++) {\n Object value = iter.next();\n if (i < startIndex) {\n continue;\n }\n if (bcw.call(value)) {\n result = i;\n }\n }\n return result;\n }"
] |
Handle an end time change.
@param event the change event. | [
"@UiHandler(\"m_endTime\")\n void onEndTimeChange(CmsDateBoxEvent event) {\n\n if (handleChange() && !event.isUserTyping()) {\n m_controller.setEndTime(event.getDate());\n }\n }"
] | [
"public Map<String, Object> getValues(double evaluationTime, MonteCarloSimulationInterface model) throws CalculationException\n\t{\n\t\tRandomVariableInterface values = getValue(evaluationTime, model);\n\n\t\tif(values == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// Sum up values on path\n\t\tdouble value = values.getAverage();\n\t\tdouble error = values.getStandardError();\n\n\t\tMap<String, Object> results = new HashMap<String, Object>();\n\t\tresults.put(\"value\", value);\n\t\tresults.put(\"error\", error);\n\n\t\treturn results;\n\t}",
"public boolean addMethodToResponseOverride(String pathName, String methodName) {\n // need to find out the ID for the method\n // TODO: change api for adding methods to take the name instead of ID\n try {\n Integer overrideId = getOverrideIdForMethodName(methodName);\n\n // now post to path api to add this is a selected override\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"addOverride\", overrideId.toString()),\n new BasicNameValuePair(\"profileIdentifier\", this._profileName)\n };\n JSONObject response = new JSONObject(doPost(BASE_PATH + uriEncode(pathName), params));\n // check enabled endpoints array to see if this overrideID exists\n JSONArray enabled = response.getJSONArray(\"enabledEndpoints\");\n for (int x = 0; x < enabled.length(); x++) {\n if (enabled.getJSONObject(x).getInt(\"overrideId\") == overrideId) {\n return true;\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return false;\n }",
"public final Object getValue(final String id, final String property) {\n final CriteriaBuilder builder = getSession().getCriteriaBuilder();\n final CriteriaQuery<Object> criteria = builder.createQuery(Object.class);\n final Root<PrintJobStatusExtImpl> root = criteria.from(PrintJobStatusExtImpl.class);\n criteria.select(root.get(property));\n criteria.where(builder.equal(root.get(\"referenceId\"), id));\n return getSession().createQuery(criteria).uniqueResult();\n }",
"public int compare(Object objA, Object objB)\r\n {\r\n String idAStr = ((FieldDescriptorDef)_fields.get(objA)).getProperty(\"id\");\r\n String idBStr = ((FieldDescriptorDef)_fields.get(objB)).getProperty(\"id\");\r\n int idA;\r\n int idB;\r\n\r\n try\r\n {\r\n idA = Integer.parseInt(idAStr);\r\n }\r\n catch (Exception ex)\r\n {\r\n return 1;\r\n }\r\n try\r\n {\r\n idB = Integer.parseInt(idBStr);\r\n }\r\n catch (Exception ex)\r\n {\r\n return -1;\r\n }\r\n return idA < idB ? -1 : (idA > idB ? 1 : 0);\r\n }",
"synchronized boolean deleteMessageForId(String messageId, String userId){\n if(messageId == null || userId == null) return false;\n\n final String tName = Table.INBOX_MESSAGES.getName();\n\n try {\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n db.delete(tName, _ID + \" = ? AND \" + USER_ID + \" = ?\", new String[]{messageId,userId});\n return true;\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Error removing stale records from \" + tName, e);\n return false;\n } finally {\n dbHelper.close();\n }\n }",
"private SortedSet<Date> filterExceptions(SortedSet<Date> dates) {\n\n SortedSet<Date> result = new TreeSet<Date>();\n for (Date d : dates) {\n if (!m_exceptions.contains(d)) {\n result.add(d);\n }\n }\n return result;\n }",
"public static <T> MetaTinyType<T> metaFor(Class<?> candidate) {\n for (MetaTinyType meta : metas) {\n if (meta.isMetaOf(candidate)) {\n return meta;\n }\n }\n throw new IllegalArgumentException(String.format(\"not a tinytype: %s\", candidate == null ? \"null\" : candidate.getCanonicalName()));\n }",
"public static void main(String[] args) {\n try {\n new StartMain(args).go();\n } catch(Throwable t) {\n WeldSELogger.LOG.error(\"Application exited with an exception\", t);\n System.exit(1);\n }\n }",
"@Pure\n\tpublic static <P1, P2, P3, P4, P5> Procedure4<P2, P3, P4, P5> curry(final Procedure5<? super P1, ? super P2, ? super P3, ? super P4, ? super P5> procedure,\n\t\t\tfinal P1 argument) {\n\t\tif (procedure == null)\n\t\t\tthrow new NullPointerException(\"procedure\");\n\t\treturn new Procedure4<P2, P3, P4, P5>() {\n\t\t\t@Override\n\t\t\tpublic void apply(P2 p2, P3 p3, P4 p4, P5 p5) {\n\t\t\t\tprocedure.apply(argument, p2, p3, p4, p5);\n\t\t\t}\n\t\t};\n\t}"
] |
Does the headset the device is docked into have a dedicated home key
@return | [
"public boolean isHomeKeyPresent() {\n final GVRApplication application = mApplication.get();\n if (null != application) {\n final String model = getHmtModel();\n if (null != model && model.contains(\"R323\")) {\n return true;\n }\n }\n return false;\n }"
] | [
"public static Module unserializeModule(final String module) throws IOException {\n final ObjectMapper mapper = new ObjectMapper();\n mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);\n return mapper.readValue(module, Module.class);\n }",
"public Duration getFinishVariance()\n {\n Duration variance = (Duration) getCachedValue(AssignmentField.FINISH_VARIANCE);\n if (variance == null)\n {\n TimeUnit format = getParentFile().getProjectProperties().getDefaultDurationUnits();\n variance = DateHelper.getVariance(getTask(), getBaselineFinish(), getFinish(), format);\n set(AssignmentField.FINISH_VARIANCE, variance);\n }\n return (variance);\n }",
"@JmxOperation(description = \"swapFiles changes this store to use the new data directory\")\n public void swapFiles(String newStoreDirectory) {\n logger.info(\"Swapping files for store '\" + getName() + \"' to \" + newStoreDirectory);\n File newVersionDir = new File(newStoreDirectory);\n\n if(!newVersionDir.exists())\n throw new VoldemortException(\"File \" + newVersionDir.getAbsolutePath()\n + \" does not exist.\");\n\n if(!(newVersionDir.getParentFile().compareTo(storeDir.getAbsoluteFile()) == 0 && ReadOnlyUtils.checkVersionDirName(newVersionDir)))\n throw new VoldemortException(\"Invalid version folder name '\"\n + newVersionDir\n + \"'. Either parent directory is incorrect or format(version-n) is incorrect\");\n\n // retrieve previous version for (a) check if last write is winning\n // (b) if failure, rollback use\n File previousVersionDir = ReadOnlyUtils.getCurrentVersion(storeDir);\n if(previousVersionDir == null)\n throw new VoldemortException(\"Could not find any latest directory to swap with in store '\"\n + getName() + \"'\");\n\n long newVersionId = ReadOnlyUtils.getVersionId(newVersionDir);\n long previousVersionId = ReadOnlyUtils.getVersionId(previousVersionDir);\n if(newVersionId == -1 || previousVersionId == -1)\n throw new VoldemortException(\"Unable to parse folder names (\" + newVersionDir.getName()\n + \",\" + previousVersionDir.getName()\n + \") since format(version-n) is incorrect\");\n\n // check if we're greater than latest since we want last write to win\n if(previousVersionId > newVersionId) {\n logger.info(\"No swap required since current latest version \" + previousVersionId\n + \" is greater than swap version \" + newVersionId);\n deleteBackups();\n return;\n }\n\n logger.info(\"Acquiring write lock on '\" + getName() + \"':\");\n fileModificationLock.writeLock().lock();\n boolean success = false;\n try {\n close();\n logger.info(\"Opening primary files for store '\" + getName() + \"' at \"\n + newStoreDirectory);\n\n // open the latest store\n open(newVersionDir);\n success = true;\n } finally {\n try {\n // we failed to do the swap, attempt a rollback to last version\n if(!success)\n rollback(previousVersionDir);\n\n } finally {\n fileModificationLock.writeLock().unlock();\n if(success)\n logger.info(\"Swap operation completed successfully on store \" + getName()\n + \", releasing lock.\");\n else\n logger.error(\"Swap operation failed.\");\n }\n }\n\n // okay we have released the lock and the store is now open again, it is\n // safe to do a potentially slow delete if we have one too many backups\n deleteBackups();\n }",
"public void addFkToThisClass(String column)\r\n {\r\n if (fksToThisClass == null)\r\n {\r\n fksToThisClass = new Vector();\r\n }\r\n fksToThisClass.add(column);\r\n fksToThisClassAry = null;\r\n }",
"public static String readContent(InputStream is) {\n String ret = \"\";\n try {\n String line;\n BufferedReader in = new BufferedReader(new InputStreamReader(is));\n StringBuffer out = new StringBuffer();\n\n while ((line = in.readLine()) != null) {\n out.append(line).append(CARRIAGE_RETURN);\n }\n ret = out.toString();\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return ret;\n }",
"public boolean assertValidPkForDelete(ClassDescriptor cld, Object obj)\r\n {\r\n if(!ProxyHelper.isProxy(obj))\r\n {\r\n FieldDescriptor fieldDescriptors[] = cld.getPkFields();\r\n int fieldDescriptorSize = fieldDescriptors.length;\r\n for(int i = 0; i < fieldDescriptorSize; i++)\r\n {\r\n FieldDescriptor fd = fieldDescriptors[i];\r\n Object pkValue = fd.getPersistentField().get(obj);\r\n if (representsNull(fd, pkValue))\r\n {\r\n return false;\r\n }\r\n }\r\n }\r\n return true;\r\n }",
"public Object getRealKey()\r\n {\r\n if(keyRealSubject != null)\r\n {\r\n return keyRealSubject;\r\n }\r\n else\r\n {\r\n TransactionExt tx = getTransaction();\r\n\r\n if((tx != null) && tx.isOpen())\r\n {\r\n prepareKeyRealSubject(tx.getBroker());\r\n }\r\n else\r\n {\r\n if(getPBKey() != null)\r\n {\r\n PBCapsule capsule = new PBCapsule(getPBKey(), null);\r\n\r\n try\r\n {\r\n prepareKeyRealSubject(capsule.getBroker());\r\n }\r\n finally\r\n {\r\n capsule.destroy();\r\n }\r\n }\r\n else\r\n {\r\n getLog().warn(\"No tx, no PBKey - can't materialise key with Identity \" + getKeyOid());\r\n }\r\n }\r\n }\r\n return keyRealSubject;\r\n }",
"public static boolean hasPermission(Permission permission) {\n SecurityManager security = System.getSecurityManager();\n if (security != null) {\n try {\n security.checkPermission(permission);\n } catch (java.security.AccessControlException e) {\n return false;\n }\n }\n return true;\n }",
"public static final BigInteger printPriority(Priority priority)\n {\n int result = Priority.MEDIUM;\n\n if (priority != null)\n {\n result = priority.getValue();\n }\n\n return (BigInteger.valueOf(result));\n }"
] |
Calls a function script associated with this component.
The function is called even if the component
is not enabled and not attached to a scene object.
@param funcName name of script function to call.
@param args function parameters as an array of objects.
@return true if function was called, false if no such function
@see org.gearvrf.script.GVRScriptFile#invokeFunction(String, Object[]) invokeFunction | [
"public boolean invokeFunction(String funcName, Object[] args)\n {\n mLastError = null;\n if (mScriptFile != null)\n {\n if (mScriptFile.invokeFunction(funcName, args))\n {\n return true;\n }\n }\n mLastError = mScriptFile.getLastError();\n if ((mLastError != null) && !mLastError.contains(\"is not defined\"))\n {\n getGVRContext().logError(mLastError, this);\n }\n return false;\n }"
] | [
"public static gslbdomain_stats[] get(nitro_service service) throws Exception{\n\t\tgslbdomain_stats obj = new gslbdomain_stats();\n\t\tgslbdomain_stats[] response = (gslbdomain_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}",
"public static gslbservice_stats[] get(nitro_service service) throws Exception{\n\t\tgslbservice_stats obj = new gslbservice_stats();\n\t\tgslbservice_stats[] response = (gslbservice_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}",
"public static <T> List<T> toList(Iterator<? extends T> iterator) {\n\t\treturn Lists.newArrayList(iterator);\n\t}",
"public double stdev() {\n double m = mean();\n\n double total = 0;\n\n final int N = getNumElements();\n if( N <= 1 )\n throw new IllegalArgumentException(\"There must be more than one element to compute stdev\");\n\n\n for( int i = 0; i < N; i++ ) {\n double x = get(i);\n\n total += (x - m)*(x - m);\n }\n\n total /= (N-1);\n\n return Math.sqrt(total);\n }",
"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 void start() {\n nsLock.writeLock().lock();\n try {\n if (runnerThread != null) {\n return;\n }\n runnerThread =\n new Thread(new NamespaceChangeStreamRunner(\n new WeakReference<>(this), networkMonitor, logger));\n runnerThread.start();\n } finally {\n nsLock.writeLock().unlock();\n }\n }",
"public PerformUsage getJVMMemoryUsage() {\n int mb = 1024 * 1024;\n Runtime rt = Runtime.getRuntime();\n PerformUsage usage = new PerformUsage();\n usage.totalMemory = (double) rt.totalMemory() / mb;\n usage.freeMemory = (double) rt.freeMemory() / mb;\n usage.usedMemory = (double) rt.totalMemory() / mb - rt.freeMemory()\n / mb;\n usage.maxMemory = (double) rt.maxMemory() / mb;\n usage.memoryUsagePercent = usage.usedMemory / usage.maxMemory * 100.0;\n\n // update current\n currentJvmPerformUsage = usage;\n return usage;\n }",
"public static gslbdomain_stats get(nitro_service service, String name) throws Exception{\n\t\tgslbdomain_stats obj = new gslbdomain_stats();\n\t\tobj.set_name(name);\n\t\tgslbdomain_stats response = (gslbdomain_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"public static void changeSign(DMatrixSparseCSC A , DMatrixSparseCSC B ) {\n if( A != B ) {\n B.copyStructure(A);\n }\n\n for (int i = 0; i < A.nz_length; i++) {\n B.nz_values[i] = -A.nz_values[i];\n }\n }"
] |
Adds and returns a document with a new version to the given document.
@param document the document to attach a new version to.
@param newVersion the version to attach to the document
@return a document with a new version to the given document. | [
"private static BsonDocument withNewVersion(\n final BsonDocument document,\n final BsonDocument newVersion\n ) {\n final BsonDocument newDocument = BsonUtils.copyOfDocument(document);\n newDocument.put(DOCUMENT_VERSION_FIELD, newVersion);\n return newDocument;\n }"
] | [
"public boolean contains(Date date)\n {\n boolean result = false;\n\n if (date != null)\n {\n result = (DateHelper.compare(getFromDate(), getToDate(), date) == 0);\n }\n\n return (result);\n }",
"public static IPAddressSeqRange[] join(IPAddressSeqRange... ranges) {\n\t\tint joinedCount = 0;\n\t\tArrays.sort(ranges, Address.ADDRESS_LOW_VALUE_COMPARATOR);\n\t\tfor(int i = 0; i < ranges.length; i++) {\n\t\t\tIPAddressSeqRange range = ranges[i];\n\t\t\tif(range == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor(int j = i + 1; j < ranges.length; j++) {\n\t\t\t\tIPAddressSeqRange range2 = ranges[j];\n\t\t\t\tif(range2 == null) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tIPAddress upper = range.getUpper();\n\t\t\t\tIPAddress lower = range2.getLower();\n\t\t\t\tif(compareLowValues(upper, lower) >= 0\n\t\t\t\t\t\t|| upper.increment(1).equals(lower)) {\n\t\t\t\t\t//join them\n\t\t\t\t\tranges[i] = range = range.create(range.getLower(), range2.getUpper());\n\t\t\t\t\tranges[j] = null;\n\t\t\t\t\tjoinedCount++;\n\t\t\t\t} else break;\n\t\t\t}\n\t\t}\n\t\tif(joinedCount == 0) {\n\t\t\treturn ranges;\n\t\t}\n\t\tIPAddressSeqRange joined[] = new IPAddressSeqRange[ranges.length - joinedCount];\n\t\tfor(int i = 0, j = 0; i < ranges.length; i++) {\n\t\t\tIPAddressSeqRange range = ranges[i];\n\t\t\tif(range == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tjoined[j++] = range;\n\t\t\tif(j >= joined.length) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn joined;\n\t}",
"public void showToast(final String message, float duration) {\n final float quadWidth = 1.2f;\n final GVRTextViewSceneObject toastSceneObject = new GVRTextViewSceneObject(this, quadWidth, quadWidth / 5,\n message);\n\n toastSceneObject.setTextSize(6);\n toastSceneObject.setTextColor(Color.WHITE);\n toastSceneObject.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.TOP);\n toastSceneObject.setBackgroundColor(Color.DKGRAY);\n toastSceneObject.setRefreshFrequency(GVRTextViewSceneObject.IntervalFrequency.REALTIME);\n\n final GVRTransform t = toastSceneObject.getTransform();\n t.setPositionZ(-1.5f);\n\n final GVRRenderData rd = toastSceneObject.getRenderData();\n final float finalOpacity = 0.7f;\n rd.getMaterial().setOpacity(0);\n rd.setRenderingOrder(2 * GVRRenderData.GVRRenderingOrder.OVERLAY);\n rd.setDepthTest(false);\n\n final GVRCameraRig rig = getMainScene().getMainCameraRig();\n rig.addChildObject(toastSceneObject);\n\n final GVRMaterialAnimation fadeOut = new GVRMaterialAnimation(rd.getMaterial(), duration / 4.0f) {\n @Override\n protected void animate(GVRHybridObject target, float ratio) {\n final GVRMaterial material = (GVRMaterial) target;\n material.setOpacity(finalOpacity - ratio * finalOpacity);\n }\n };\n fadeOut.setOnFinish(new GVROnFinish() {\n @Override\n public void finished(GVRAnimation animation) {\n rig.removeChildObject(toastSceneObject);\n }\n });\n\n final GVRMaterialAnimation fadeIn = new GVRMaterialAnimation(rd.getMaterial(), 3.0f * duration / 4.0f) {\n @Override\n protected void animate(GVRHybridObject target, float ratio) {\n final GVRMaterial material = (GVRMaterial) target;\n material.setOpacity(ratio * finalOpacity);\n }\n };\n fadeIn.setOnFinish(new GVROnFinish() {\n @Override\n public void finished(GVRAnimation animation) {\n getAnimationEngine().start(fadeOut);\n }\n });\n\n getAnimationEngine().start(fadeIn);\n }",
"private void createResultSubClassesMultipleJoinedTables(List result, ClassDescriptor cld, boolean wholeTree)\r\n {\r\n List tmp = (List) superClassMultipleJoinedTablesMap.get(cld.getClassOfObject());\r\n if(tmp != null)\r\n {\r\n result.addAll(tmp);\r\n if(wholeTree)\r\n {\r\n for(int i = 0; i < tmp.size(); i++)\r\n {\r\n Class subClass = (Class) tmp.get(i);\r\n ClassDescriptor subCld = getDescriptorFor(subClass);\r\n createResultSubClassesMultipleJoinedTables(result, subCld, wholeTree);\r\n }\r\n }\r\n }\r\n }",
"public String getNextDay(String dateString, boolean onlyBusinessDays) {\n DateTimeFormatter parser = ISODateTimeFormat.date();\n DateTime date = parser.parseDateTime(dateString).plusDays(1);\n Calendar cal = Calendar.getInstance();\n cal.setTime(date.toDate());\n\n if (onlyBusinessDays) {\n if (cal.get(Calendar.DAY_OF_WEEK) == 1 || cal.get(Calendar.DAY_OF_WEEK) == 7\n || isHoliday(date.toString().substring(0, 10))) {\n return getNextDay(date.toString().substring(0, 10), true);\n } else {\n return parser.print(date);\n }\n } else {\n return parser.print(date);\n }\n }",
"private void map(Resource root) {\n\n for (Resource.ResourceEntry serverGroup : root.getChildren(SERVER_GROUP)) {\n String serverGroupName = serverGroup.getName();\n ModelNode serverGroupModel = serverGroup.getModel();\n String profile = serverGroupModel.require(PROFILE).asString();\n store(serverGroupName, profile, profilesToGroups);\n String socketBindingGroup = serverGroupModel.require(SOCKET_BINDING_GROUP).asString();\n store(serverGroupName, socketBindingGroup, socketsToGroups);\n\n for (Resource.ResourceEntry deployment : serverGroup.getChildren(DEPLOYMENT)) {\n store(serverGroupName, deployment.getName(), deploymentsToGroups);\n }\n\n for (Resource.ResourceEntry overlay : serverGroup.getChildren(DEPLOYMENT_OVERLAY)) {\n store(serverGroupName, overlay.getName(), overlaysToGroups);\n }\n\n }\n\n for (Resource.ResourceEntry host : root.getChildren(HOST)) {\n String hostName = host.getPathElement().getValue();\n for (Resource.ResourceEntry serverConfig : host.getChildren(SERVER_CONFIG)) {\n ModelNode serverConfigModel = serverConfig.getModel();\n String serverGroupName = serverConfigModel.require(GROUP).asString();\n store(serverGroupName, hostName, hostsToGroups);\n }\n }\n }",
"public ConfigurableMessages getConfigurableMessages(CmsMessages defaultMessages, Locale locale) {\n\n return new ConfigurableMessages(defaultMessages, locale, m_configuredBundle);\n\n }",
"public static appfwprofile_crosssitescripting_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_crosssitescripting_binding obj = new appfwprofile_crosssitescripting_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_crosssitescripting_binding response[] = (appfwprofile_crosssitescripting_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public String addPostRunDependent(FunctionalTaskItem dependentTaskItem) {\n IndexableTaskItem taskItem = IndexableTaskItem.create(dependentTaskItem);\n this.addPostRunDependent(taskItem);\n return taskItem.key();\n }"
] |
Calculate the value of a CMS strike using the Black-Scholes model for the swap rate together with
the Hunt-Kennedy convexity adjustment.
@param forwardSwaprate The forward swap rate
@param volatility Volatility of the log of the swap rate
@param swapAnnuity The swap annuity
@param optionMaturity The option maturity
@param swapMaturity The swap maturity
@param payoffUnit The payoff unit, e.g., the discount factor corresponding to the payment date
@param optionStrike The option strike
@return Value of the CMS strike | [
"public static double huntKennedyCMSFloorValue(\n\t\t\tdouble forwardSwaprate,\n\t\t\tdouble volatility,\n\t\t\tdouble swapAnnuity,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble swapMaturity,\n\t\t\tdouble payoffUnit,\n\t\t\tdouble optionStrike)\n\t{\n\t\tdouble huntKennedyCMSOptionValue = huntKennedyCMSOptionValue(forwardSwaprate, volatility, swapAnnuity, optionMaturity, swapMaturity, payoffUnit, optionStrike);\n\n\t\t// A floor is an option plus the strike (max(X,K) = max(X-K,0) + K)\n\t\treturn huntKennedyCMSOptionValue + optionStrike * payoffUnit;\n\t}"
] | [
"public void process(String name) throws Exception\n {\n ProjectFile file = new UniversalProjectReader().read(name);\n for (Task task : file.getTasks())\n {\n if (!task.getSummary())\n {\n System.out.print(task.getWBS());\n System.out.print(\"\\t\");\n System.out.print(task.getName());\n System.out.print(\"\\t\");\n System.out.print(format(task.getStart()));\n System.out.print(\"\\t\");\n System.out.print(format(task.getActualStart()));\n System.out.print(\"\\t\");\n System.out.print(format(task.getFinish()));\n System.out.print(\"\\t\");\n System.out.print(format(task.getActualFinish()));\n System.out.println();\n }\n }\n }",
"private void processDestructionQueue(HttpServletRequest request) {\n Object contextsAttribute = request.getAttribute(DESTRUCTION_QUEUE_ATTRIBUTE_NAME);\n if (contextsAttribute instanceof Map) {\n Map<String, List<ContextualInstance<?>>> contexts = cast(contextsAttribute);\n synchronized (contexts) {\n FastEvent<String> beforeDestroyedEvent = FastEvent.of(String.class, beanManager, BeforeDestroyed.Literal.CONVERSATION);\n FastEvent<String> destroyedEvent = FastEvent.of(String.class, beanManager, Destroyed.Literal.CONVERSATION);\n for (Iterator<Entry<String, List<ContextualInstance<?>>>> iterator = contexts.entrySet().iterator(); iterator.hasNext();) {\n Entry<String, List<ContextualInstance<?>>> entry = iterator.next();\n beforeDestroyedEvent.fire(entry.getKey());\n for (ContextualInstance<?> contextualInstance : entry.getValue()) {\n destroyContextualInstance(contextualInstance);\n }\n // Note that for the attached/current conversation we fire the destroyed event twice because we can't reliably identify such a conversation\n destroyedEvent.fire(entry.getKey());\n iterator.remove();\n }\n }\n }\n }",
"@Override\n\tpublic String toNormalizedString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = getStringCache().normalizedString) == null) {\n\t\t\tgetStringCache().normalizedString = result = toNormalizedString(IPv6StringCache.normalizedParams);\n\t\t}\n\t\treturn result;\n\t}",
"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 }",
"@RequestMapping(value = \"api/servergroup\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getServerGroups(Model model,\n @RequestParam(value = \"profileId\", required = false) Integer profileId,\n @RequestParam(value = \"search\", required = false) String search,\n @RequestParam(value = \"profileIdentifier\", required = false) String profileIdentifier) throws Exception {\n if (profileId == null && profileIdentifier == null) {\n throw new Exception(\"profileId required\");\n }\n if (profileId == null) {\n profileId = ProfileService.getInstance().getIdFromName(profileIdentifier);\n }\n\n List<ServerGroup> serverGroups = ServerRedirectService.getInstance().tableServerGroups(profileId);\n\n if (search != null) {\n Iterator<ServerGroup> iterator = serverGroups.iterator();\n while (iterator.hasNext()) {\n ServerGroup serverGroup = iterator.next();\n if (!serverGroup.getName().toLowerCase().contains(search.toLowerCase())) {\n iterator.remove();\n }\n }\n }\n HashMap<String, Object> returnJson = Utils.getJQGridJSON(serverGroups, \"servergroups\");\n return returnJson;\n }",
"@Override\n public ConfigurableRequest createRequest(\n @Nonnull final URI uri,\n @Nonnull final HttpMethod httpMethod) throws IOException {\n HttpRequestBase httpRequest = (HttpRequestBase) createHttpUriRequest(httpMethod, uri);\n return new Request(getHttpClient(), httpRequest, createHttpContext(httpMethod, uri));\n }",
"public static int bilinearInterpolate(float x, float y, int nw, int ne, int sw, int se) {\n\t\tfloat m0, m1;\n\t\tint a0 = (nw >> 24) & 0xff;\n\t\tint r0 = (nw >> 16) & 0xff;\n\t\tint g0 = (nw >> 8) & 0xff;\n\t\tint b0 = nw & 0xff;\n\t\tint a1 = (ne >> 24) & 0xff;\n\t\tint r1 = (ne >> 16) & 0xff;\n\t\tint g1 = (ne >> 8) & 0xff;\n\t\tint b1 = ne & 0xff;\n\t\tint a2 = (sw >> 24) & 0xff;\n\t\tint r2 = (sw >> 16) & 0xff;\n\t\tint g2 = (sw >> 8) & 0xff;\n\t\tint b2 = sw & 0xff;\n\t\tint a3 = (se >> 24) & 0xff;\n\t\tint r3 = (se >> 16) & 0xff;\n\t\tint g3 = (se >> 8) & 0xff;\n\t\tint b3 = se & 0xff;\n\n\t\tfloat cx = 1.0f-x;\n\t\tfloat cy = 1.0f-y;\n\n\t\tm0 = cx * a0 + x * a1;\n\t\tm1 = cx * a2 + x * a3;\n\t\tint a = (int)(cy * m0 + y * m1);\n\n\t\tm0 = cx * r0 + x * r1;\n\t\tm1 = cx * r2 + x * r3;\n\t\tint r = (int)(cy * m0 + y * m1);\n\n\t\tm0 = cx * g0 + x * g1;\n\t\tm1 = cx * g2 + x * g3;\n\t\tint g = (int)(cy * m0 + y * m1);\n\n\t\tm0 = cx * b0 + x * b1;\n\t\tm1 = cx * b2 + x * b3;\n\t\tint b = (int)(cy * m0 + y * m1);\n\n\t\treturn (a << 24) | (r << 16) | (g << 8) | b;\n\t}",
"public void commandContinuationRequest()\r\n throws ProtocolException {\r\n try {\r\n output.write('+');\r\n output.write(' ');\r\n output.write('O');\r\n output.write('K');\r\n output.write('\\r');\r\n output.write('\\n');\r\n output.flush();\r\n } catch (IOException e) {\r\n throw new ProtocolException(\"Unexpected exception in sending command continuation request.\", e);\r\n }\r\n }",
"public void onThrowable(Throwable cause) {\n this.cause = cause;\n getSelf().tell(RequestWorkerMsgType.PROCESS_ON_EXCEPTION, getSelf());\n\n }"
] |
Resolve a path from the rootPath checking that it doesn't go out of the rootPath.
@param rootPath the starting point for resolution.
@param path the path we want to resolve.
@return the resolved path.
@throws IllegalArgumentException if the resolved path is out of the rootPath or if the resolution failed. | [
"public static final Path resolveSecurely(Path rootPath, String path) {\n Path resolvedPath;\n if(path == null || path.isEmpty()) {\n resolvedPath = rootPath.normalize();\n } else {\n String relativePath = removeSuperflousSlashes(path);\n resolvedPath = rootPath.resolve(relativePath).normalize();\n }\n if(!resolvedPath.startsWith(rootPath)) {\n throw DeploymentRepositoryLogger.ROOT_LOGGER.forbiddenPath(path);\n }\n return resolvedPath;\n }"
] | [
"public static List<Map<String, Object>> listify(ObjectMapper mapper, Object source) {\n return (List<Map<String, Object>>) collectify(mapper, source, List.class);\n }",
"public void setJdbcLevel(String jdbcLevel)\r\n {\r\n if (jdbcLevel != null)\r\n {\r\n try\r\n {\r\n double intLevel = Double.parseDouble(jdbcLevel);\r\n setJdbcLevel(intLevel);\r\n }\r\n catch(NumberFormatException nfe)\r\n {\r\n setJdbcLevel(2.0);\r\n logger.info(\"Specified JDBC level was not numeric (Value=\" + jdbcLevel + \"), used default jdbc level of 2.0 \");\r\n }\r\n }\r\n else\r\n {\r\n setJdbcLevel(2.0);\r\n logger.info(\"Specified JDBC level was null, used default jdbc level of 2.0 \");\r\n }\r\n }",
"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 remove(IConverter converter, Object sourceObject,\n\t\t\tTypeReference<?> destinationType) {\n\t\tconvertedObjects.remove(new ConvertedObjectsKey(converter,\n\t\t\t\tsourceObject, destinationType));\n\t}",
"public static String formatAsStackTraceElement(InjectionPoint ij) {\n Member member;\n if (ij.getAnnotated() instanceof AnnotatedField) {\n AnnotatedField<?> annotatedField = (AnnotatedField<?>) ij.getAnnotated();\n member = annotatedField.getJavaMember();\n } else if (ij.getAnnotated() instanceof AnnotatedParameter<?>) {\n AnnotatedParameter<?> annotatedParameter = (AnnotatedParameter<?>) ij.getAnnotated();\n member = annotatedParameter.getDeclaringCallable().getJavaMember();\n } else {\n // Not throwing an exception, because this method is invoked when an exception is already being thrown.\n // Throwing an exception here would hide the original exception.\n return \"-\";\n }\n return formatAsStackTraceElement(member);\n }",
"private String parseRssFeed(String feed) {\n String[] result = feed.split(\"<br />\");\n String[] result2 = result[2].split(\"<BR />\");\n\n return result2[0];\n }",
"public void ifMemberTagValueEquals(String template, Properties attributes) throws XDocletException\r\n {\r\n if (getCurrentField() != null) {\r\n if (isTagValueEqual(attributes, FOR_FIELD)) {\r\n generate(template);\r\n }\r\n }\r\n else if (getCurrentMethod() != null) {\r\n if (isTagValueEqual(attributes, FOR_METHOD)) {\r\n generate(template);\r\n }\r\n }\r\n }",
"public void addAll(OptionsContainerBuilder container) {\n\t\tfor ( Entry<Class<? extends Option<?, ?>>, ValueContainerBuilder<?, ?>> entry : container.optionValues.entrySet() ) {\n\t\t\taddAll( entry.getKey(), entry.getValue().build() );\n\t\t}\n\t}",
"public static Deployment of(final Path content) {\n final DeploymentContent deploymentContent = DeploymentContent.of(Assert.checkNotNullParam(\"content\", content));\n return new Deployment(deploymentContent, null);\n }"
] |
Allow for the use of text shading and auto formatting. | [
"protected String ensureTextColorFormat(String textColor) {\n String formatted = \"\";\n boolean mainColor = true;\n for (String style : textColor.split(\" \")) {\n if (mainColor) {\n // the main color\n if (!style.endsWith(\"-text\")) {\n style += \"-text\";\n }\n mainColor = false;\n } else {\n // the shading type\n if (!style.startsWith(\"text-\")) {\n style = \" text-\" + style;\n }\n }\n formatted += style;\n }\n return formatted;\n }"
] | [
"public void alias( Object ...args ) {\n if( args.length % 2 == 1 )\n throw new RuntimeException(\"Even number of arguments expected\");\n\n for (int i = 0; i < args.length; i += 2) {\n aliasGeneric( args[i], (String)args[i+1]);\n }\n }",
"public static CentralDogma forConfig(File configFile) throws IOException {\n requireNonNull(configFile, \"configFile\");\n return new CentralDogma(Jackson.readValue(configFile, CentralDogmaConfig.class));\n }",
"private void writeProperties() throws IOException\n {\n writeAttributeTypes(\"property_types\", ProjectField.values());\n writeFields(\"property_values\", m_projectFile.getProjectProperties(), ProjectField.values());\n }",
"protected void setBandsFinalHeight() {\n log.debug(\"Setting bands final height...\");\n\n List<JRBand> bands = new ArrayList<JRBand>();\n\n Utils.addNotNull(bands, design.getPageHeader());\n Utils.addNotNull(bands, design.getPageFooter());\n Utils.addNotNull(bands, design.getColumnHeader());\n Utils.addNotNull(bands, design.getColumnFooter());\n Utils.addNotNull(bands, design.getSummary());\n Utils.addNotNull(bands, design.getBackground());\n bands.addAll(((JRDesignSection) design.getDetailSection()).getBandsList());\n Utils.addNotNull(bands, design.getLastPageFooter());\n Utils.addNotNull(bands, design.getTitle());\n Utils.addNotNull(bands, design.getPageFooter());\n Utils.addNotNull(bands, design.getNoData());\n\n for (JRGroup jrgroup : design.getGroupsList()) {\n DJGroup djGroup = (DJGroup) getReferencesMap().get(jrgroup.getName());\n JRDesignSection headerSection = (JRDesignSection) jrgroup.getGroupHeaderSection();\n JRDesignSection footerSection = (JRDesignSection) jrgroup.getGroupFooterSection();\n if (djGroup != null) {\n for (JRBand headerBand : headerSection.getBandsList()) {\n setBandFinalHeight((JRDesignBand) headerBand, djGroup.getHeaderHeight(), djGroup.isFitHeaderHeightToContent());\n\n }\n for (JRBand footerBand : footerSection.getBandsList()) {\n setBandFinalHeight((JRDesignBand) footerBand, djGroup.getFooterHeight(), djGroup.isFitFooterHeightToContent());\n\n }\n } else {\n bands.addAll(headerSection.getBandsList());\n bands.addAll(footerSection.getBandsList());\n }\n }\n\n for (JRBand jrDesignBand : bands) {\n setBandFinalHeight((JRDesignBand) jrDesignBand);\n }\n }",
"private static void updateSniffingLoggersLevel(Logger logger) {\n\n\t\tInputStream settingIS = FoundationLogger.class\n\t\t\t\t.getResourceAsStream(\"/sniffingLogger.xml\");\n\t\tif (settingIS == null) {\n\t\t\tlogger.debug(\"file sniffingLogger.xml not found in classpath\");\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tSAXBuilder builder = new SAXBuilder();\n\t\t\t\tDocument document = builder.build(settingIS);\n\t\t\t\tsettingIS.close();\n\t\t\t\tElement rootElement = document.getRootElement();\n\t\t\t\tList<Element> sniffingloggers = rootElement\n\t\t\t\t\t\t.getChildren(\"sniffingLogger\");\n\t\t\t\tfor (Element sniffinglogger : sniffingloggers) {\n\t\t\t\t\tString loggerName = sniffinglogger.getAttributeValue(\"id\");\n\t\t\t\t\tLogger.getLogger(loggerName).setLevel(Level.TRACE);\n\t\t\t\t}\n\t\t\t} catch (Exception e) {\n\t\t\t\tlogger.error(\n\t\t\t\t\t\t\"cannot load the sniffing logger configuration file. error is: \"\n\t\t\t\t\t\t\t\t+ e, e);\n\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\"Problem parsing sniffingLogger.xml\", e);\n\t\t\t}\n\t\t}\n\n\t}",
"protected String consumeWord(ImapRequestLineReader request,\n CharacterValidator validator)\n throws ProtocolException {\n StringBuilder atom = new StringBuilder();\n\n char next = request.nextWordChar();\n while (!isWhitespace(next)) {\n if (validator.isValid(next)) {\n atom.append(next);\n request.consume();\n } else {\n throw new ProtocolException(\"Invalid character: '\" + next + '\\'');\n }\n next = request.nextChar();\n }\n return atom.toString();\n }",
"public void recordResourceRequestQueueLength(SocketDestination dest, int queueLength) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordResourceRequestQueueLength(null, queueLength);\n recordResourceRequestQueueLength(null, queueLength);\n } else {\n this.resourceRequestQueueLengthHistogram.insert(queueLength);\n checkMonitoringInterval();\n }\n }",
"public int getPrivacy() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PRIVACY);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element personElement = response.getPayload();\r\n return Integer.parseInt(personElement.getAttribute(\"privacy\"));\r\n }",
"public static Object toObject(Class<?> clazz, Object value) throws ParseException {\n if (value == null) {\n return null;\n }\n if (clazz == null) {\n return value;\n }\n\n if (java.sql.Date.class.isAssignableFrom(clazz)) {\n return toDate(value);\n }\n if (java.sql.Time.class.isAssignableFrom(clazz)) {\n return toTime(value);\n }\n if (java.sql.Timestamp.class.isAssignableFrom(clazz)) {\n return toTimestamp(value);\n }\n if (java.util.Date.class.isAssignableFrom(clazz)) {\n return toDateTime(value);\n }\n\n return value;\n }"
] |
Removes the specified entry point
@param controlPoint The entry point | [
"public synchronized void removeControlPoint(ControlPoint controlPoint) {\n if (controlPoint.decreaseReferenceCount() == 0) {\n ControlPointIdentifier id = new ControlPointIdentifier(controlPoint.getDeployment(), controlPoint.getEntryPoint());\n entryPoints.remove(id);\n }\n }"
] | [
"public static void setFieldValue(Object object, String fieldName, Object value) {\n try {\n getDeclaredFieldInHierarchy(object.getClass(), fieldName).set(object, value);\n } catch (IllegalArgumentException e) {\n throw new RuntimeException(e);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n }\n }",
"public MaterialSection getSectionByTitle(String title) {\n\n for(MaterialSection section : sectionList) {\n if(section.getTitle().equals(title)) {\n return section;\n }\n }\n\n for(MaterialSection section : bottomSectionList) {\n if(section.getTitle().equals(title))\n return section;\n }\n\n return null;\n }",
"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 synchronized void mapPublicKeys(final PublicKey original, final PublicKey substitute)\n\t{\n\t\t_mappedPublicKeys.put(original, substitute);\n\t\tif(persistImmediately) { persistPublicKeyMap(); }\n\t}",
"public static boolean isFileExist(String filePath) {\n\n File f = new File(filePath);\n\n return f.exists() && !f.isDirectory();\n }",
"@Override\n\tpublic T next() {\n\t\tSQLException sqlException = null;\n\t\ttry {\n\t\t\tT result = nextThrow();\n\t\t\tif (result != null) {\n\t\t\t\treturn result;\n\t\t\t}\n\t\t} catch (SQLException e) {\n\t\t\tsqlException = e;\n\t\t}\n\t\t// we have to throw if there is no next or on a SQLException\n\t\tlast = null;\n\t\tcloseQuietly();\n\t\tthrow new IllegalStateException(\"Could not get next result for \" + dataClass, sqlException);\n\t}",
"public static final Date getTimestamp(byte[] data, int offset)\n {\n Date result;\n\n long days = getShort(data, offset + 2);\n if (days < 100)\n {\n // We are seeing some files which have very small values for the number of days.\n // When the relevant field is shown in MS Project it appears as NA.\n // We try to mimic this behaviour here.\n days = 0;\n }\n\n if (days == 0 || days == 65535)\n {\n result = null;\n }\n else\n {\n long time = getShort(data, offset);\n if (time == 65535)\n {\n time = 0;\n }\n result = DateHelper.getTimestampFromLong((EPOCH + (days * DateHelper.MS_PER_DAY) + ((time * DateHelper.MS_PER_MINUTE) / 10)));\n }\n\n return (result);\n }",
"private boolean compareBytes(byte[] lhs, byte[] rhs, int rhsOffset)\n {\n boolean result = true;\n for (int loop = 0; loop < lhs.length; loop++)\n {\n if (lhs[loop] != rhs[rhsOffset + loop])\n {\n result = false;\n break;\n }\n }\n return (result);\n }",
"public void stop() {\n if (accelerometer != null) {\n queue.clear();\n sensorManager.unregisterListener(this, accelerometer);\n sensorManager = null;\n accelerometer = null;\n }\n }"
] |
Use this API to fetch all the responderparam resources that are configured on netscaler. | [
"public static responderparam get(nitro_service service) throws Exception{\n\t\tresponderparam obj = new responderparam();\n\t\tresponderparam[] response = (responderparam[])obj.get_resources(service);\n\t\treturn response[0];\n\t}"
] | [
"public static int getJSONColor(final JSONObject json, String elementName) throws JSONException {\n Object raw = json.get(elementName);\n return convertJSONColor(raw);\n }",
"protected int getCenterChild(CacheDataSet cache) {\n if (cache.count() == 0)\n return -1;\n\n int id = cache.getId(0);\n switch (getGravityInternal()) {\n case TOP:\n case LEFT:\n case FRONT:\n case FILL:\n break;\n case BOTTOM:\n case RIGHT:\n case BACK:\n id = cache.getId(cache.count() - 1);\n break;\n case CENTER:\n int i = cache.count() / 2;\n while (i < cache.count() && i >= 0) {\n id = cache.getId(i);\n if (cache.getStartDataOffset(id) <= 0) {\n if (cache.getEndDataOffset(id) >= 0) {\n break;\n } else {\n i++;\n }\n } else {\n i--;\n }\n }\n break;\n default:\n break;\n }\n\n Log.d(LAYOUT, TAG, \"getCenterChild = %d \", id);\n return id;\n }",
"@Override\n public Collection<EnhancedAnnotatedConstructor<T>> getEnhancedConstructors(Class<? extends Annotation> annotationType) {\n Set<EnhancedAnnotatedConstructor<T>> ret = new HashSet<EnhancedAnnotatedConstructor<T>>();\n for (EnhancedAnnotatedConstructor<T> constructor : constructors) {\n if (constructor.isAnnotationPresent(annotationType)) {\n ret.add(constructor);\n }\n }\n return ret;\n }",
"private static long createLongSeed(byte[] seed)\n {\n if (seed == null || seed.length != SEED_SIZE_BYTES)\n {\n throw new IllegalArgumentException(\"Java RNG requires a 64-bit (8-byte) seed.\");\n }\n return BinaryUtils.convertBytesToLong(seed, 0);\n }",
"private void validateFilter(Filter filter) throws IllegalArgumentException {\n switch (filter.getFilterTypeCase()) {\n case COMPOSITE_FILTER:\n for (Filter subFilter : filter.getCompositeFilter().getFiltersList()) {\n validateFilter(subFilter);\n }\n break;\n case PROPERTY_FILTER:\n if (UNSUPPORTED_OPERATORS.contains(filter.getPropertyFilter().getOp())) {\n throw new IllegalArgumentException(\"Query cannot have any inequality filters.\");\n }\n break;\n default:\n throw new IllegalArgumentException(\n \"Unsupported filter type: \" + filter.getFilterTypeCase());\n }\n }",
"private void initEditorStates() {\n\n m_editorState = new HashMap<CmsMessageBundleEditorTypes.EditMode, EditorState>();\n List<TableProperty> cols = null;\n switch (m_bundleType) {\n case PROPERTY:\n case XML:\n if (hasDescriptor()) { // bundle descriptor is present, keys are not editable in default mode, maybe master mode is available\n m_editorState.put(CmsMessageBundleEditorTypes.EditMode.DEFAULT, getDefaultState());\n if (hasMasterMode()) { // the bundle descriptor is editable\n m_editorState.put(CmsMessageBundleEditorTypes.EditMode.MASTER, getMasterState());\n }\n } else { // no bundle descriptor given - implies no master mode\n cols = new ArrayList<TableProperty>(1);\n cols.add(TableProperty.KEY);\n cols.add(TableProperty.TRANSLATION);\n m_editorState.put(CmsMessageBundleEditorTypes.EditMode.DEFAULT, new EditorState(cols, true));\n }\n break;\n case DESCRIPTOR:\n cols = new ArrayList<TableProperty>(3);\n cols.add(TableProperty.KEY);\n cols.add(TableProperty.DESCRIPTION);\n cols.add(TableProperty.DEFAULT);\n m_editorState.put(CmsMessageBundleEditorTypes.EditMode.DEFAULT, new EditorState(cols, true));\n break;\n default:\n throw new IllegalArgumentException();\n }\n\n }",
"static <T> StitchEvent<T> fromEvent(final Event event,\n final Decoder<T> decoder) {\n return new StitchEvent<>(event.getEventName(), event.getData(), decoder);\n }",
"private static String getPath(Service service, Annotation... qualifiers) {\n for (Annotation q : qualifiers) {\n if (q instanceof Scheme) {\n return ((Scheme) q).value();\n }\n }\n\n if (service.getMetadata() != null && service.getMetadata().getAnnotations() != null) {\n String s = service.getMetadata().getAnnotations().get(SERVICE_SCHEME);\n if (s != null && s.isEmpty()) {\n return s;\n }\n }\n return DEFAULT_PATH;\n }",
"public 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 }"
] |
Decode the String from Base64 into a byte array.
@param value the string to be decoded
@return the decoded bytes as an array
@since 1.0 | [
"public static byte[] decodeBase64(String value) {\n int byteShift = 4;\n int tmp = 0;\n boolean done = false;\n final StringBuilder buffer = new StringBuilder();\n\n for (int i = 0; i != value.length(); i++) {\n final char c = value.charAt(i);\n final int sixBit = (c < 123) ? EncodingGroovyMethodsSupport.TRANSLATE_TABLE[c] : 66;\n\n if (sixBit < 64) {\n if (done)\n throw new RuntimeException(\"= character not at end of base64 value\"); // TODO: change this exception type\n\n tmp = (tmp << 6) | sixBit;\n\n if (byteShift-- != 4) {\n buffer.append((char) ((tmp >> (byteShift * 2)) & 0XFF));\n }\n\n } else if (sixBit == 64) {\n\n byteShift--;\n done = true;\n\n } else if (sixBit == 66) {\n // RFC 2045 says that I'm allowed to take the presence of\n // these characters as evidence of data corruption\n // So I will\n throw new RuntimeException(\"bad character in base64 value\"); // TODO: change this exception type\n }\n\n if (byteShift == 0) byteShift = 4;\n }\n\n try {\n return buffer.toString().getBytes(\"ISO-8859-1\");\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(\"Base 64 decode produced byte values > 255\"); // TODO: change this exception type\n }\n }"
] | [
"private void calculateValueTextHeight() {\n Rect valueRect = new Rect();\n Rect legendRect = new Rect();\n String str = Utils.getFloatString(mFocusedPoint.getValue(), mShowDecimal) + (!mIndicatorTextUnit.isEmpty() ? \" \" + mIndicatorTextUnit : \"\");\n\n // calculate the boundaries for both texts\n mIndicatorPaint.getTextBounds(str, 0, str.length(), valueRect);\n mLegendPaint.getTextBounds(mFocusedPoint.getLegendLabel(), 0, mFocusedPoint.getLegendLabel().length(), legendRect);\n\n // calculate string positions in overlay\n mValueTextHeight = valueRect.height();\n mValueLabelY = (int) (mValueTextHeight + mIndicatorTopPadding);\n mLegendLabelY = (int) (mValueTextHeight + mIndicatorTopPadding + legendRect.height() + Utils.dpToPx(7.f));\n\n int chosenWidth = valueRect.width() > legendRect.width() ? valueRect.width() : legendRect.width();\n\n // check if text reaches over screen\n if (mFocusedPoint.getCoordinates().getX() + chosenWidth + mIndicatorLeftPadding > -Utils.getTranslationX(mDrawMatrixValues) + mGraphWidth) {\n mValueLabelX = (int) (mFocusedPoint.getCoordinates().getX() - (valueRect.width() + mIndicatorLeftPadding));\n mLegendLabelX = (int) (mFocusedPoint.getCoordinates().getX() - (legendRect.width() + mIndicatorLeftPadding));\n } else {\n mValueLabelX = mLegendLabelX = (int) (mFocusedPoint.getCoordinates().getX() + mIndicatorLeftPadding);\n }\n }",
"public float getSphereBound(float[] sphere)\n {\n if ((sphere == null) || (sphere.length != 4) ||\n ((NativeVertexBuffer.getBoundingVolume(getNative(), sphere)) < 0))\n {\n throw new IllegalArgumentException(\"Cannot copy sphere bound into array provided\");\n }\n return sphere[0];\n }",
"public Diff compare(String left, String right) {\n\t\treturn compare(getCtType(left), getCtType(right));\n\t}",
"public RgbaColor opacify(float amount) {\n return new RgbaColor(r, g, b, alphaCheck(a + amount));\n }",
"private int determineForkedJvmCount(TestsCollection testCollection) {\n int cores = Runtime.getRuntime().availableProcessors();\n int jvmCount;\n if (this.parallelism.equals(PARALLELISM_AUTO)) {\n if (cores >= 8) {\n // Maximum parallel jvms is 4, conserve some memory and memory bandwidth.\n jvmCount = 4;\n } else if (cores >= 4) {\n // Make some space for the aggregator.\n jvmCount = 3;\n } else if (cores == 3) {\n // Yes, three-core chips are a thing.\n jvmCount = 2;\n } else {\n // even for dual cores it usually makes no sense to fork more than one\n // JVM.\n jvmCount = 1;\n }\n } else if (this.parallelism.equals(PARALLELISM_MAX)) {\n jvmCount = Runtime.getRuntime().availableProcessors();\n } else {\n try {\n jvmCount = Math.max(1, Integer.parseInt(parallelism));\n } catch (NumberFormatException e) {\n throw new BuildException(\"parallelism must be 'auto', 'max' or a valid integer: \"\n + parallelism);\n }\n }\n\n if (!testCollection.hasReplicatedSuites()) {\n jvmCount = Math.min(testCollection.testClasses.size(), jvmCount);\n }\n return jvmCount;\n }",
"public static String entityToString(HttpEntity entity) throws IOException {\n if (entity != null) {\n InputStream is = entity.getContent();\n return IOUtils.toString(is, \"UTF-8\");\n }\n return \"\";\n }",
"public void setWeekDay(String dayString) {\n\n final WeekDay day = WeekDay.valueOf(dayString);\n if (m_model.getWeekDay() != day) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setWeekDay(day);\n onValueChange();\n }\n });\n }\n\n }",
"public static ServiceName channelServiceName(final ServiceName endpointName, final String channelName) {\n return endpointName.append(\"channel\").append(channelName);\n }",
"private WeekDay readWeekDay(JSONValue val) throws IllegalArgumentException {\n\n String str = readOptionalString(val);\n if (null != str) {\n return WeekDay.valueOf(str);\n }\n throw new IllegalArgumentException();\n }"
] |
Function to perform backward activation | [
"public static int cudnnActivationBackward(\n cudnnHandle handle, \n cudnnActivationDescriptor activationDesc, \n Pointer alpha, \n cudnnTensorDescriptor yDesc, \n Pointer y, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor dxDesc, \n Pointer dx)\n {\n return checkResult(cudnnActivationBackwardNative(handle, activationDesc, alpha, yDesc, y, dyDesc, dy, xDesc, x, beta, dxDesc, dx));\n }"
] | [
"public static auditsyslogpolicy_vpnglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditsyslogpolicy_vpnglobal_binding obj = new auditsyslogpolicy_vpnglobal_binding();\n\t\tobj.set_name(name);\n\t\tauditsyslogpolicy_vpnglobal_binding response[] = (auditsyslogpolicy_vpnglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static long crc32(byte[] bytes, int offset, int size) {\n CRC32 crc = new CRC32();\n crc.update(bytes, offset, size);\n return crc.getValue();\n }",
"public static boolean hasAnnotation(Method method, Class<? extends Annotation> annotation) {\n return !searchForAnnotation(method, annotation).isEmpty();\n }",
"public void addPathToRequestResponseTable(int profileId, String clientUUID, int pathId) throws Exception {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection\n .prepareStatement(\"INSERT INTO \" + Constants.DB_TABLE_REQUEST_RESPONSE +\n \"(\" + Constants.REQUEST_RESPONSE_PATH_ID + \",\"\n + Constants.GENERIC_PROFILE_ID + \",\"\n + Constants.GENERIC_CLIENT_UUID + \",\"\n + Constants.REQUEST_RESPONSE_REPEAT_NUMBER + \",\"\n + Constants.REQUEST_RESPONSE_RESPONSE_ENABLED + \",\"\n + Constants.REQUEST_RESPONSE_REQUEST_ENABLED + \",\"\n + Constants.REQUEST_RESPONSE_CUSTOM_RESPONSE + \",\"\n + Constants.REQUEST_RESPONSE_CUSTOM_REQUEST + \")\"\n + \" VALUES (?, ?, ?, ?, ?, ?, ?, ?);\");\n statement.setInt(1, pathId);\n statement.setInt(2, profileId);\n statement.setString(3, clientUUID);\n statement.setInt(4, -1);\n statement.setInt(5, 0);\n statement.setInt(6, 0);\n statement.setString(7, \"\");\n statement.setString(8, \"\");\n statement.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }",
"@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}",
"public static<T> Vendor<T> vendor(Func0<T> f) {\n\treturn j.vendor(f);\n }",
"public final void updateLastCheckTime(final String id, final long lastCheckTime) {\n final CriteriaBuilder builder = getSession().getCriteriaBuilder();\n final CriteriaUpdate<PrintJobStatusExtImpl> update =\n builder.createCriteriaUpdate(PrintJobStatusExtImpl.class);\n final Root<PrintJobStatusExtImpl> root = update.from(PrintJobStatusExtImpl.class);\n update.where(builder.equal(root.get(\"referenceId\"), id));\n update.set(root.get(\"lastCheckTime\"), lastCheckTime);\n getSession().createQuery(update).executeUpdate();\n }",
"public void process(Resource resource, int index, byte[] data)\n {\n CostRateTable result = new CostRateTable();\n\n if (data != null)\n {\n for (int i = 16; i + 44 <= data.length; i += 44)\n {\n Rate standardRate = new Rate(MPPUtility.getDouble(data, i), TimeUnit.HOURS);\n TimeUnit standardRateFormat = getFormat(MPPUtility.getShort(data, i + 8));\n Rate overtimeRate = new Rate(MPPUtility.getDouble(data, i + 16), TimeUnit.HOURS);\n TimeUnit overtimeRateFormat = getFormat(MPPUtility.getShort(data, i + 24));\n Double costPerUse = NumberHelper.getDouble(MPPUtility.getDouble(data, i + 32) / 100.0);\n Date endDate = MPPUtility.getTimestampFromTenths(data, i + 40);\n CostRateTableEntry entry = new CostRateTableEntry(standardRate, standardRateFormat, overtimeRate, overtimeRateFormat, costPerUse, endDate);\n result.add(entry);\n }\n Collections.sort(result);\n }\n else\n {\n //\n // MS Project economises by not actually storing the first cost rate\n // table if it doesn't need to, so we take this into account here.\n //\n if (index == 0)\n {\n Rate standardRate = resource.getStandardRate();\n Rate overtimeRate = resource.getOvertimeRate();\n Number costPerUse = resource.getCostPerUse();\n CostRateTableEntry entry = new CostRateTableEntry(standardRate, standardRate.getUnits(), overtimeRate, overtimeRate.getUnits(), costPerUse, CostRateTableEntry.DEFAULT_ENTRY.getEndDate());\n result.add(entry);\n }\n else\n {\n result.add(CostRateTableEntry.DEFAULT_ENTRY);\n }\n }\n\n resource.setCostRateTable(index, result);\n }",
"public ParallelTaskBuilder setSshPrivKeyRelativePathWtihPassphrase(\n String privKeyRelativePath, String passphrase) {\n this.sshMeta.setPrivKeyRelativePath(privKeyRelativePath);\n this.sshMeta.setPrivKeyUsePassphrase(true);\n this.sshMeta.setPassphrase(passphrase);\n this.sshMeta.setSshLoginType(SshLoginType.KEY);\n return this;\n }"
] |
Boyer Moore scan that proceeds backwards from the end of the file looking for endsig
@param file the file being checked
@param channel the channel
@param context the scan context
@return
@throws IOException | [
"private static long scanForEndSig(final File file, final FileChannel channel, final ScanContext context) throws IOException {\n\n\n\n // TODO Consider just reading in MAX_REVERSE_SCAN bytes -- increased peak memory cost but less complex\n\n ByteBuffer bb = getByteBuffer(CHUNK_SIZE);\n long start = channel.size();\n long end = Math.max(0, start - MAX_REVERSE_SCAN);\n long channelPos = Math.max(0, start - CHUNK_SIZE);\n long lastChannelPos = channelPos;\n while (lastChannelPos >= end) {\n\n read(bb, channel, channelPos);\n\n int actualRead = bb.limit();\n int bufferPos = actualRead - 1;\n while (bufferPos >= SIG_PATTERN_LENGTH) {\n\n // Following is based on the Boyer Moore algorithm but simplified to reflect\n // a) the pattern is static\n // b) the pattern has no repeating bytes\n\n int patternPos;\n for (patternPos = SIG_PATTERN_LENGTH - 1;\n patternPos >= 0 && context.matches(patternPos, bb.get(bufferPos - patternPos));\n --patternPos) {\n // empty loop while bytes match\n }\n\n // Switch gives same results as checking the \"good suffix array\" in the Boyer Moore algorithm\n switch (patternPos) {\n case -1: {\n final State state = context.state;\n // Pattern matched. Confirm is this is the start of a valid end of central dir record\n long startEndRecord = channelPos + bufferPos - SIG_PATTERN_LENGTH + 1;\n if (validateEndRecord(file, channel, startEndRecord, context.getSig())) {\n if (state == State.FOUND) {\n return startEndRecord;\n } else {\n return -1;\n }\n }\n // wasn't a valid end record; continue scan\n bufferPos -= 4;\n break;\n }\n case 3: {\n // No bytes matched; the common case.\n // With our pattern, this is the only case where the Boyer Moore algorithm's \"bad char array\" may\n // produce a shift greater than the \"good suffix array\" (which would shift 1 byte)\n int idx = bb.get(bufferPos - patternPos) - Byte.MIN_VALUE;\n bufferPos -= BAD_BYTE_SKIP[idx];\n break;\n }\n default:\n // 1 or more bytes matched\n bufferPos -= 4;\n }\n }\n\n // Move back a full chunk. If we didn't read a full chunk, that's ok,\n // it means we read all data and the outer while loop will terminate\n if (channelPos <= bufferPos) {\n break;\n }\n lastChannelPos = channelPos;\n channelPos -= Math.min(channelPos - bufferPos, CHUNK_SIZE - bufferPos);\n }\n\n return -1;\n }"
] | [
"public static final String printExtendedAttribute(MSPDIWriter writer, Object value, DataType type)\n {\n String result;\n\n if (type == DataType.DATE)\n {\n result = printExtendedAttributeDate((Date) value);\n }\n else\n {\n if (value instanceof Boolean)\n {\n result = printExtendedAttributeBoolean((Boolean) value);\n }\n else\n {\n if (value instanceof Duration)\n {\n result = printDuration(writer, (Duration) value);\n }\n else\n {\n if (type == DataType.CURRENCY)\n {\n result = printExtendedAttributeCurrency((Number) value);\n }\n else\n {\n if (value instanceof Number)\n {\n result = printExtendedAttributeNumber((Number) value);\n }\n else\n {\n result = value.toString();\n }\n }\n }\n }\n }\n\n return (result);\n }",
"public String getCmdLineArg() {\n StringBuilder builder = new StringBuilder(\" --server-groups=\");\n boolean foundSelected = false;\n for (JCheckBox serverGroup : serverGroups) {\n if (serverGroup.isSelected()) {\n foundSelected = true;\n builder.append(serverGroup.getText());\n builder.append(\",\");\n }\n }\n builder.deleteCharAt(builder.length() - 1); // remove trailing comma\n\n if (!foundSelected) return \"\";\n return builder.toString();\n }",
"public Where<T, ID> like(String columnName, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,\n\t\t\t\tSimpleComparison.LIKE_OPERATION));\n\t\treturn this;\n\t}",
"public static String copyToString(InputStream in, Charset charset) throws IOException {\n\t\tAssert.notNull(in, \"No InputStream specified\");\n\t\tStringBuilder out = new StringBuilder();\n\t\tInputStreamReader reader = new InputStreamReader(in, charset);\n\t\tchar[] buffer = new char[BUFFER_SIZE];\n\t\tint bytesRead = -1;\n\t\twhile ((bytesRead = reader.read(buffer)) != -1) {\n\t\t\tout.append(buffer, 0, bytesRead);\n\t\t}\n\t\treturn out.toString();\n\t}",
"@SuppressWarnings(\"StringEquality\")\n public static MatchInfo fromAuthScope(final AuthScope authscope) {\n String newScheme = StringUtils.equals(authscope.getScheme(), AuthScope.ANY_SCHEME) ? ANY_SCHEME :\n authscope.getScheme();\n String newHost = StringUtils.equals(authscope.getHost(), AuthScope.ANY_HOST) ? ANY_HOST :\n authscope.getHost();\n int newPort = authscope.getPort() == AuthScope.ANY_PORT ? ANY_PORT : authscope.getPort();\n String newRealm = StringUtils.equals(authscope.getRealm(), AuthScope.ANY_REALM) ? ANY_REALM :\n authscope.getRealm();\n\n return new MatchInfo(newScheme, newHost, newPort, ANY_PATH, ANY_QUERY,\n ANY_FRAGMENT, newRealm, ANY_METHOD);\n }",
"public static long count(nitro_service service, String ciphergroupname) throws Exception{\n\t\tsslcipher_individualcipher_binding obj = new sslcipher_individualcipher_binding();\n\t\tobj.set_ciphergroupname(ciphergroupname);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tsslcipher_individualcipher_binding response[] = (sslcipher_individualcipher_binding[]) obj.get_resources(service,option);\n\t\tif (response != null) {\n\t\t\treturn response[0].__count;\n\t\t}\n\t\treturn 0;\n\t}",
"public static base_responses add(nitro_service client, sslocspresponder resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslocspresponder addresources[] = new sslocspresponder[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new sslocspresponder();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].url = resources[i].url;\n\t\t\t\taddresources[i].cache = resources[i].cache;\n\t\t\t\taddresources[i].cachetimeout = resources[i].cachetimeout;\n\t\t\t\taddresources[i].batchingdepth = resources[i].batchingdepth;\n\t\t\t\taddresources[i].batchingdelay = resources[i].batchingdelay;\n\t\t\t\taddresources[i].resptimeout = resources[i].resptimeout;\n\t\t\t\taddresources[i].respondercert = resources[i].respondercert;\n\t\t\t\taddresources[i].trustresponder = resources[i].trustresponder;\n\t\t\t\taddresources[i].producedattimeskew = resources[i].producedattimeskew;\n\t\t\t\taddresources[i].signingcert = resources[i].signingcert;\n\t\t\t\taddresources[i].usenonce = resources[i].usenonce;\n\t\t\t\taddresources[i].insertclientcert = resources[i].insertclientcert;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"private void handleArchiveByFile(Predicate<String> filter, File archive, List<String> discoveredFiles)\n {\n try\n {\n try (ZipFile zip = new ZipFile(archive))\n {\n Enumeration<? extends ZipEntry> entries = zip.entries();\n \n while (entries.hasMoreElements())\n {\n ZipEntry entry = entries.nextElement();\n String name = entry.getName();\n if (filter.accept(name))\n discoveredFiles.add(name);\n }\n }\n }\n catch (IOException e)\n {\n throw new RuntimeException(\"Error handling file \" + archive, e);\n }\n }",
"public static auditnslogpolicy_authenticationvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditnslogpolicy_authenticationvserver_binding obj = new auditnslogpolicy_authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauditnslogpolicy_authenticationvserver_binding response[] = (auditnslogpolicy_authenticationvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Removes old entries in the history table for the given profile and client UUID
@param profileId ID of profile
@param clientUUID UUID of client
@param limit Maximum number of history entries to remove
@throws Exception exception | [
"public void cullHistory(final int profileId, final String clientUUID, final int limit) throws Exception {\n\n //Allow only 1 delete thread to run\n if (threadActive) {\n return;\n }\n\n threadActive = true;\n //Create a thread so proxy will continue to work during long delete\n Thread t1 = new Thread(new Runnable() {\n @Override\n public void run() {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n String sqlQuery = \"SELECT COUNT(\" + Constants.GENERIC_ID + \") FROM \" + Constants.DB_TABLE_HISTORY + \" \";\n\n // see if profileId is set or not (-1)\n if (profileId != -1) {\n sqlQuery += \"WHERE \" + Constants.GENERIC_PROFILE_ID + \"=\" + profileId + \" \";\n }\n\n if (clientUUID != null && clientUUID.compareTo(\"\") != 0) {\n sqlQuery += \"AND \" + Constants.GENERIC_CLIENT_UUID + \"='\" + clientUUID + \"' \";\n }\n sqlQuery += \";\";\n\n Statement query = sqlConnection.createStatement();\n ResultSet results = query.executeQuery(sqlQuery);\n if (results.next()) {\n if (results.getInt(\"COUNT(\" + Constants.GENERIC_ID + \")\") < (limit + 10000)) {\n return;\n }\n }\n //Find the last item in the table\n statement = sqlConnection.prepareStatement(\"SELECT \" + Constants.GENERIC_ID + \" FROM \" + Constants.DB_TABLE_HISTORY +\n \" WHERE \" + Constants.CLIENT_CLIENT_UUID + \" = \\'\" + clientUUID + \"\\'\" +\n \" AND \" + Constants.CLIENT_PROFILE_ID + \" = \" + profileId +\n \" ORDER BY \" + Constants.GENERIC_ID + \" ASC LIMIT 1\");\n\n ResultSet resultSet = statement.executeQuery();\n if (resultSet.next()) {\n int currentSpot = resultSet.getInt(Constants.GENERIC_ID) + 100;\n int finalDelete = currentSpot + 10000;\n //Delete 100 items at a time until 10000 are deleted\n //Do this so table is unlocked frequently to allow other proxy items to access it\n while (currentSpot < finalDelete) {\n PreparedStatement deleteStatement = sqlConnection.prepareStatement(\"DELETE FROM \" + Constants.DB_TABLE_HISTORY +\n \" WHERE \" + Constants.CLIENT_CLIENT_UUID + \" = \\'\" + clientUUID + \"\\'\" +\n \" AND \" + Constants.CLIENT_PROFILE_ID + \" = \" + profileId +\n \" AND \" + Constants.GENERIC_ID + \" < \" + currentSpot);\n deleteStatement.executeUpdate();\n currentSpot += 100;\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n threadActive = false;\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }\n });\n\n t1.start();\n }"
] | [
"@Deprecated\r\n public static URL buildUrl(String host, int port, String path, Map<String, String> parameters) throws MalformedURLException {\r\n return buildUrl(\"http\", port, path, parameters);\r\n }",
"@Override\n public void process(TestCaseResult context) {\n context.getParameters().add(new Parameter()\n .withName(getName())\n .withValue(getValue())\n .withKind(ParameterKind.valueOf(getKind()))\n );\n }",
"public double getValue(int[] batch) {\n double value = 0.0;\n for (int i=0; i<batch.length; i++) {\n value += getValue(i);\n }\n return value;\n }",
"public void setPromoted(final boolean promoted) {\n this.promoted = promoted;\n\n for (final Artifact artifact : artifacts) {\n artifact.setPromoted(promoted);\n }\n\n for (final Module suModule : submodules) {\n suModule.setPromoted(promoted);\n }\n }",
"public NRShape makeShape(Date from, Date to) {\n UnitNRShape fromShape = tree.toUnitShape(from);\n UnitNRShape toShape = tree.toUnitShape(to);\n return tree.toRangeShape(fromShape, toShape);\n }",
"private double getConstraint(double x1, double x2)\n {\n double c1,c2,h;\n c1 = -x1*x1-x2*x2+1+0.1*Math.cos(16*Math.atan(x1/x2));\n c2 = (x1-0.5)*(x1-0.5)+(x2-0.5)*(x2-0.5)-0.5;\n if(c1>c2)\n h = (c1>0)?c1:0;\n else\n h = (c2>0)?c2:0;\n return h;\n }",
"private static byte calculateChecksum(byte[] buffer) {\n\t\tbyte checkSum = (byte)0xFF;\n\t\tfor (int i=1; i<buffer.length-1; i++) {\n\t\t\tcheckSum = (byte) (checkSum ^ buffer[i]);\n\t\t}\n\t\tlogger.trace(String.format(\"Calculated checksum = 0x%02X\", checkSum));\n\t\treturn checkSum;\n\t}",
"public boolean handleKeyDeletion(final String key) {\n\n if (m_keyset.getKeySet().contains(key)) {\n if (removeKeyForAllLanguages(key)) {\n m_keyset.removeKey(key);\n return true;\n } else {\n return false;\n }\n }\n return true;\n }",
"public <Ex extends Throwable> Try<R,Ex> execute(T input,Class<Ex> classes){\n\t\t\n\t\treturn Try.withCatch( ()->transactionTemplate.execute(status-> transaction.apply(input)),classes);\n\t\t \n\t}"
] |
Parses a raw WBS value from the database and breaks it into
component parts ready for formatting.
@param value raw WBS value | [
"public void parseRawValue(String value)\n {\n int valueIndex = 0;\n int elementIndex = 0;\n m_elements.clear();\n while (valueIndex < value.length() && elementIndex < m_elements.size())\n {\n int elementLength = m_lengths.get(elementIndex).intValue();\n if (elementIndex > 0)\n {\n m_elements.add(m_separators.get(elementIndex - 1));\n }\n int endIndex = valueIndex + elementLength;\n if (endIndex > value.length())\n {\n endIndex = value.length();\n }\n String element = value.substring(valueIndex, endIndex);\n m_elements.add(element);\n valueIndex += elementLength;\n elementIndex++;\n }\n }"
] | [
"private void flushHotCacheSlot(SlotReference slot) {\n // Iterate over a copy to avoid concurrent modification issues\n for (Map.Entry<DeckReference, TrackMetadata> entry : new HashMap<DeckReference,TrackMetadata>(hotCache).entrySet()) {\n if (slot == SlotReference.getSlotReference(entry.getValue().trackReference)) {\n logger.debug(\"Evicting cached metadata in response to unmount report {}\", entry.getValue());\n hotCache.remove(entry.getKey());\n }\n }\n }",
"public int getCrossZonePartitionStoreMoves() {\n int xzonePartitionStoreMoves = 0;\n for (RebalanceTaskInfo info : batchPlan) {\n Node donorNode = finalCluster.getNodeById(info.getDonorId());\n Node stealerNode = finalCluster.getNodeById(info.getStealerId());\n\n if(donorNode.getZoneId() != stealerNode.getZoneId()) {\n xzonePartitionStoreMoves += info.getPartitionStoreMoves();\n }\n }\n\n return xzonePartitionStoreMoves;\n }",
"public boolean uploadConfigurationAndProfile(String fileName, String odoImport) {\n File file = new File(fileName);\n MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();\n FileBody fileBody = new FileBody(file, ContentType.MULTIPART_FORM_DATA);\n multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);\n multipartEntityBuilder.addPart(\"fileData\", fileBody);\n multipartEntityBuilder.addTextBody(\"odoImport\", odoImport);\n try {\n JSONObject response = new JSONObject(doMultipartPost(BASE_BACKUP_PROFILE + \"/\" + uriEncode(this._profileName) + \"/\" + this._clientId, multipartEntityBuilder));\n if (response.length() == 0) {\n return true;\n } else {\n return false;\n }\n } catch (Exception e) {\n return false;\n }\n }",
"private void updateRemoveQ( int rowIndex ) {\n Qm.set(Q);\n Q.reshape(m_m,m_m, false);\n\n for( int i = 0; i < rowIndex; i++ ) {\n for( int j = 1; j < m; j++ ) {\n double sum = 0;\n for( int k = 0; k < m; k++ ) {\n sum += Qm.data[i*m+k]* U_tran.data[j*m+k];\n }\n Q.data[i*m_m+j-1] = sum;\n }\n }\n\n for( int i = rowIndex+1; i < m; i++ ) {\n for( int j = 1; j < m; j++ ) {\n double sum = 0;\n for( int k = 0; k < m; k++ ) {\n sum += Qm.data[i*m+k]* U_tran.data[j*m+k];\n }\n Q.data[(i-1)*m_m+j-1] = sum;\n }\n }\n }",
"private final boolean parseBoolean(String value)\n {\n return value != null && (value.equalsIgnoreCase(\"true\") || value.equalsIgnoreCase(\"y\") || value.equalsIgnoreCase(\"yes\"));\n }",
"public ManagementModelNode getSelectedNode() {\n if (tree.getSelectionPath() == null) return null;\n return (ManagementModelNode)tree.getSelectionPath().getLastPathComponent();\n }",
"public final Object getRealObject(Object objectOrProxy)\r\n {\r\n if(isNormalOjbProxy(objectOrProxy))\r\n {\r\n String msg;\r\n\r\n try\r\n {\r\n return getIndirectionHandler(objectOrProxy).getRealSubject();\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 catch(PersistenceBrokerException e)\r\n {\r\n log.error(\"Could not retrieve real object for given Proxy: \" + objectOrProxy);\r\n throw e;\r\n }\r\n }\r\n else if(isVirtualOjbProxy(objectOrProxy))\r\n {\r\n try\r\n {\r\n return ((VirtualProxy) objectOrProxy).getRealSubject();\r\n }\r\n catch(PersistenceBrokerException e)\r\n {\r\n log.error(\"Could not retrieve real object for VirtualProxy: \" + objectOrProxy);\r\n throw e;\r\n }\r\n }\r\n else\r\n {\r\n return objectOrProxy;\r\n }\r\n }",
"public static byte[] removeContentFromExplodedAndTransformOperation(OperationContext context, ModelNode operation, ContentRepository contentRepository) throws OperationFailedException, ExplodedContentException {\n final Resource deploymentResource = context.readResource(PathAddress.EMPTY_ADDRESS);\n ModelNode contentItemNode = getContentItem(deploymentResource);\n final byte[] oldHash = CONTENT_HASH.resolveModelAttribute(context, contentItemNode).asBytes();\n final List<String> paths = REMOVED_PATHS.unwrap(context, operation);\n final byte[] hash = contentRepository.removeContentFromExploded(oldHash, paths);\n\n // Clear the contents and update with the hash\n final ModelNode slave = operation.clone();\n slave.get(CONTENT).setEmptyList().add().get(HASH).set(hash);\n slave.get(CONTENT).add().get(ARCHIVE).set(false);\n // Add the domain op transformer\n List<DomainOperationTransmuter> transformers = context.getAttachment(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS);\n if (transformers == null) {\n context.attach(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS, transformers = new ArrayList<>());\n }\n transformers.add(new CompositeOperationAwareTransmuter(slave));\n return hash;\n }",
"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 }"
] |
Gets the date time str concise.
@param d
the d
@return the date time str concise | [
"public static String getDateTimeStrConcise(Date d) {\n if (d == null)\n return \"\";\n\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyyMMddHHmmssSSSZ\");\n return sdf.format(d);\n }"
] | [
"private void addHours(ProjectCalendarDateRanges ranges, Record hoursRecord)\n {\n if (hoursRecord.getValue() != null)\n {\n String[] wh = hoursRecord.getValue().split(\"\\\\|\");\n try\n {\n String startText;\n String endText;\n\n if (wh[0].equals(\"s\"))\n {\n startText = wh[1];\n endText = wh[3];\n }\n else\n {\n startText = wh[3];\n endText = wh[1];\n }\n\n // for end time treat midnight as midnight next day\n if (endText.equals(\"00:00\"))\n {\n endText = \"24:00\";\n }\n Date start = m_calendarTimeFormat.parse(startText);\n Date end = m_calendarTimeFormat.parse(endText);\n\n ranges.addRange(new DateRange(start, end));\n }\n catch (ParseException e)\n {\n // silently ignore date parse exceptions\n }\n }\n }",
"private void writeAssignmentBaselines(Project.Assignments.Assignment xml, ResourceAssignment mpxj)\n {\n Project.Assignments.Assignment.Baseline baseline = m_factory.createProjectAssignmentsAssignmentBaseline();\n boolean populated = false;\n\n Number cost = mpxj.getBaselineCost();\n if (cost != null && cost.intValue() != 0)\n {\n populated = true;\n baseline.setCost(DatatypeConverter.printExtendedAttributeCurrency(cost));\n }\n\n Date date = mpxj.getBaselineFinish();\n if (date != null)\n {\n populated = true;\n baseline.setFinish(DatatypeConverter.printExtendedAttributeDate(date));\n }\n\n date = mpxj.getBaselineStart();\n if (date != null)\n {\n populated = true;\n baseline.setStart(DatatypeConverter.printExtendedAttributeDate(date));\n }\n\n Duration duration = mpxj.getBaselineWork();\n if (duration != null && duration.getDuration() != 0)\n {\n populated = true;\n baseline.setWork(DatatypeConverter.printDuration(this, duration));\n }\n\n if (populated)\n {\n baseline.setNumber(\"0\");\n xml.getBaseline().add(baseline);\n }\n\n for (int loop = 1; loop <= 10; loop++)\n {\n baseline = m_factory.createProjectAssignmentsAssignmentBaseline();\n populated = false;\n\n cost = mpxj.getBaselineCost(loop);\n if (cost != null && cost.intValue() != 0)\n {\n populated = true;\n baseline.setCost(DatatypeConverter.printExtendedAttributeCurrency(cost));\n }\n\n date = mpxj.getBaselineFinish(loop);\n if (date != null)\n {\n populated = true;\n baseline.setFinish(DatatypeConverter.printExtendedAttributeDate(date));\n }\n\n date = mpxj.getBaselineStart(loop);\n if (date != null)\n {\n populated = true;\n baseline.setStart(DatatypeConverter.printExtendedAttributeDate(date));\n }\n\n duration = mpxj.getBaselineWork(loop);\n if (duration != null && duration.getDuration() != 0)\n {\n populated = true;\n baseline.setWork(DatatypeConverter.printDuration(this, duration));\n }\n\n if (populated)\n {\n baseline.setNumber(Integer.toString(loop));\n xml.getBaseline().add(baseline);\n }\n }\n }",
"private void checkModifications(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n HashMap features = new HashMap();\r\n FeatureDescriptorDef def;\r\n\r\n for (Iterator it = classDef.getFields(); it.hasNext();)\r\n {\r\n def = (FeatureDescriptorDef)it.next();\r\n features.put(def.getName(), def);\r\n }\r\n for (Iterator it = classDef.getReferences(); it.hasNext();)\r\n {\r\n def = (FeatureDescriptorDef)it.next();\r\n features.put(def.getName(), def);\r\n }\r\n for (Iterator it = classDef.getCollections(); it.hasNext();)\r\n {\r\n def = (FeatureDescriptorDef)it.next();\r\n features.put(def.getName(), def);\r\n }\r\n\r\n // now checking the modifications\r\n Properties mods;\r\n String modName;\r\n String propName;\r\n\r\n for (Iterator it = classDef.getModificationNames(); it.hasNext();)\r\n {\r\n modName = (String)it.next();\r\n if (!features.containsKey(modName))\r\n {\r\n throw new ConstraintException(\"Class \"+classDef.getName()+\" contains a modification for an unknown feature \"+modName);\r\n }\r\n def = (FeatureDescriptorDef)features.get(modName);\r\n if (def.getOriginal() == null)\r\n {\r\n throw new ConstraintException(\"Class \"+classDef.getName()+\" contains a modification for a feature \"+modName+\" that is not inherited but defined in the same class\");\r\n }\r\n // checking modification\r\n mods = classDef.getModification(modName);\r\n for (Iterator propIt = mods.keySet().iterator(); propIt.hasNext();)\r\n {\r\n propName = (String)propIt.next();\r\n if (!PropertyHelper.isPropertyAllowed(def.getClass(), propName))\r\n {\r\n throw new ConstraintException(\"The modification of attribute \"+propName+\" in class \"+classDef.getName()+\" is not applicable to the feature \"+modName);\r\n }\r\n }\r\n }\r\n }",
"public void showTrajectoryAndSpline(){\n\t\t\n\t\tif(t.getDimension()==2){\n\t\t \tdouble[] xData = new double[rotatedTrajectory.size()];\n\t\t double[] yData = new double[rotatedTrajectory.size()];\n\t\t for(int i = 0; i < rotatedTrajectory.size(); i++){\n\t\t \txData[i] = rotatedTrajectory.get(i).x;\n\t\t \tyData[i] = rotatedTrajectory.get(i).y;\t\t \t\n\t\t }\n\t\t // Create Chart\n\t\t Chart chart = QuickChart.getChart(\"Spline+Track\", \"X\", \"Y\", \"y(x)\", xData, yData);\n\t\t \n\t\t //Add spline support points\n\t\t double[] subxData = new double[splineSupportPoints.size()];\n\t\t double[] subyData = new double[splineSupportPoints.size()];\n\t\t \n\t\t for(int i = 0; i < splineSupportPoints.size(); i++){\n\t\t \tsubxData[i] = splineSupportPoints.get(i).x;\n\t\t \tsubyData[i] = splineSupportPoints.get(i).y;\n\t\t }\n\t\t Series s = chart.addSeries(\"Spline Support Points\", subxData, subyData);\n\t\t s.setLineStyle(SeriesLineStyle.NONE);\n\t\t s.setSeriesType(SeriesType.Line);\n\t\t \n\t\t //ADd spline points\n\t\t int numberInterpolatedPointsPerSegment = 20;\n\t\t int numberOfSplines = spline.getN();\n\t\t double[] sxData = new double[numberInterpolatedPointsPerSegment*numberOfSplines];\n\t\t \n\t\t double[] syData = new double[numberInterpolatedPointsPerSegment*numberOfSplines];\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 \n\t\t \tdouble stopx = knots[i+1];\n\t\t \tdouble dx = (stopx-x)/numberInterpolatedPointsPerSegment;\n\t\t \t\n\t\t \tfor(int j = 0; j < numberInterpolatedPointsPerSegment; j++){\n\n\t\t \t\tsxData[i*numberInterpolatedPointsPerSegment+j] = x;\n\t\t \t\tsyData[i*numberInterpolatedPointsPerSegment+j] = spline.value(x);\n\t\t \t\tx += dx;\n\t\t \t}\n\t\t \t\n\t\t }\n\t\t s = chart.addSeries(\"Spline\", sxData, syData);\n\t\t s.setLineStyle(SeriesLineStyle.DASH_DASH);\n\t\t s.setMarker(SeriesMarker.NONE);\n\t\t s.setSeriesType(SeriesType.Line);\n\t\t \n\t\t \n\t\t //Show it\n\t\t new SwingWrapper(chart).displayChart();\n\t\t} \n\t}",
"public static Cluster createUpdatedCluster(Cluster currentCluster,\n int stealerNodeId,\n List<Integer> donatedPartitions) {\n Cluster updatedCluster = Cluster.cloneCluster(currentCluster);\n // Go over every donated partition one by one\n for(int donatedPartition: donatedPartitions) {\n\n // Gets the donor Node that owns this donated partition\n Node donorNode = updatedCluster.getNodeForPartitionId(donatedPartition);\n Node stealerNode = updatedCluster.getNodeById(stealerNodeId);\n\n if(donorNode == stealerNode) {\n // Moving to the same location = No-op\n continue;\n }\n\n // Update the list of partitions for this node\n donorNode = removePartitionFromNode(donorNode, donatedPartition);\n stealerNode = addPartitionToNode(stealerNode, donatedPartition);\n\n // Sort the nodes\n updatedCluster = updateCluster(updatedCluster,\n Lists.newArrayList(donorNode, stealerNode));\n\n }\n\n return updatedCluster;\n }",
"private void updateWorkTimeUnit(FastTrackColumn column)\n {\n if (m_workTimeUnit == null && isWorkColumn(column))\n {\n int value = ((DurationColumn) column).getTimeUnitValue();\n if (value != 1)\n {\n m_workTimeUnit = FastTrackUtility.getTimeUnit(value);\n }\n }\n }",
"public static ZMatrixRMaj hermitian(int length, double min, double max, Random rand) {\n ZMatrixRMaj A = new ZMatrixRMaj(length,length);\n\n fillHermitian(A, min, max, rand);\n\n return A;\n }",
"private void readZookeeperConfig() {\n\n try (CuratorFramework curator = CuratorUtil.newAppCurator(config)) {\n curator.start();\n\n accumuloInstance =\n new String(curator.getData().forPath(ZookeeperPath.CONFIG_ACCUMULO_INSTANCE_NAME),\n StandardCharsets.UTF_8);\n accumuloInstanceID =\n new String(curator.getData().forPath(ZookeeperPath.CONFIG_ACCUMULO_INSTANCE_ID),\n StandardCharsets.UTF_8);\n fluoApplicationID =\n new String(curator.getData().forPath(ZookeeperPath.CONFIG_FLUO_APPLICATION_ID),\n StandardCharsets.UTF_8);\n\n table = new String(curator.getData().forPath(ZookeeperPath.CONFIG_ACCUMULO_TABLE),\n StandardCharsets.UTF_8);\n\n observers = ObserverUtil.load(curator);\n\n config = FluoAdminImpl.mergeZookeeperConfig(config);\n\n // make sure not to include config passed to env, only want config from zookeeper\n appConfig = config.getAppConfiguration();\n } catch (Exception e) {\n throw new IllegalStateException(e);\n }\n }",
"private void readColumn(int startIndex, int length) throws Exception\n {\n if (m_currentTable != null)\n {\n int value = FastTrackUtility.getByte(m_buffer, startIndex);\n Class<?> klass = COLUMN_MAP[value];\n if (klass == null)\n {\n klass = UnknownColumn.class;\n }\n\n FastTrackColumn column = (FastTrackColumn) klass.newInstance();\n m_currentColumn = column;\n\n logColumnData(startIndex, length);\n\n column.read(m_currentTable.getType(), m_buffer, startIndex, length);\n FastTrackField type = column.getType();\n\n //\n // Don't try to add this data if:\n // 1. We don't know what type it is\n // 2. We have seen the type already\n //\n if (type != null && !m_currentFields.contains(type))\n {\n m_currentFields.add(type);\n m_currentTable.addColumn(column);\n updateDurationTimeUnit(column);\n updateWorkTimeUnit(column);\n\n logColumn(column);\n }\n }\n }"
] |
Applies the kubernetes json url to the configuration.
@param map
The arquillian configuration. | [
"public static URL getKubernetesConfigurationUrl(Map<String, String> map) throws MalformedURLException {\n if (Strings.isNotNullOrEmpty(Utils.getSystemPropertyOrEnvVar(ENVIRONMENT_CONFIG_URL, \"\"))) {\n return new URL(Utils.getSystemPropertyOrEnvVar(ENVIRONMENT_CONFIG_URL, \"\"));\n } else if (Strings.isNotNullOrEmpty(Utils.getSystemPropertyOrEnvVar(ENVIRONMENT_CONFIG_RESOURCE_NAME, \"\"))) {\n String resourceName = Utils.getSystemPropertyOrEnvVar(ENVIRONMENT_CONFIG_RESOURCE_NAME, \"\");\n return findConfigResource(resourceName);\n } else if (map.containsKey(ENVIRONMENT_CONFIG_URL)) {\n return new URL(map.get(ENVIRONMENT_CONFIG_URL));\n } else if (map.containsKey(ENVIRONMENT_CONFIG_RESOURCE_NAME)) {\n String resourceName = map.get(ENVIRONMENT_CONFIG_RESOURCE_NAME);\n return findConfigResource(resourceName);\n } else {\n // Let the resource locator find the resource\n return null;\n }\n }"
] | [
"private String parseLayerId(HttpServletRequest request) {\n\t\tStringTokenizer tokenizer = new StringTokenizer(request.getRequestURI(), \"/\");\n\t\tString token = \"\";\n\t\twhile (tokenizer.hasMoreTokens()) {\n\t\t\ttoken = tokenizer.nextToken();\n\t\t}\n\t\treturn token;\n\t}",
"public final PrintJobResultExtImpl getResult(final URI reportURI) {\n final CriteriaBuilder builder = getSession().getCriteriaBuilder();\n final CriteriaQuery<PrintJobResultExtImpl> criteria =\n builder.createQuery(PrintJobResultExtImpl.class);\n final Root<PrintJobResultExtImpl> root = criteria.from(PrintJobResultExtImpl.class);\n criteria.where(builder.equal(root.get(\"reportURI\"), reportURI.toString()));\n return getSession().createQuery(criteria).uniqueResult();\n }",
"public static File copyResourceToLocalFile(String sourceResource, String destFileName) throws Exception {\n try {\n Resource keystoreFile = new ClassPathResource(sourceResource);\n InputStream in = keystoreFile.getInputStream();\n\n File outKeyStoreFile = new File(destFileName);\n FileOutputStream fop = new FileOutputStream(outKeyStoreFile);\n byte[] buf = new byte[512];\n int num;\n while ((num = in.read(buf)) != -1) {\n fop.write(buf, 0, num);\n }\n fop.flush();\n fop.close();\n in.close();\n return outKeyStoreFile;\n } catch (IOException ioe) {\n throw new Exception(\"Could not copy keystore file: \" + ioe.getMessage());\n }\n }",
"public static double elementSum( DMatrixSparseCSC A ) {\n if( A.nz_length == 0)\n return 0;\n\n double sum = 0;\n for(int i = 0; i < A.nz_length; i++ ) {\n sum += A.nz_values[i];\n }\n\n return sum;\n }",
"public int getGeoPerms() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_GEO_PERMS);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n int perm = -1;\r\n Element personElement = response.getPayload();\r\n String geoPerms = personElement.getAttribute(\"geoperms\");\r\n try {\r\n perm = Integer.parseInt(geoPerms);\r\n } catch (NumberFormatException e) {\r\n throw new FlickrException(\"0\", \"Unable to parse geoPermission\");\r\n }\r\n return perm;\r\n }",
"private void addFoldersToSearchIn(final List<String> folders) {\n\n if (null == folders) {\n return;\n }\n\n for (String folder : folders) {\n if (!CmsResource.isFolder(folder)) {\n folder += \"/\";\n }\n\n m_foldersToSearchIn.add(folder);\n }\n }",
"public ApnsServiceBuilder withDelegate(ApnsDelegate delegate) {\n this.delegate = delegate == null ? ApnsDelegate.EMPTY : delegate;\n return this;\n }",
"public Filter geoSearch(String value) {\n GeopositionComparator comp = (GeopositionComparator) prop.getComparator();\n double dist = comp.getMaxDistance();\n double degrees = DistanceUtils.dist2Degrees(dist, DistanceUtils.EARTH_MEAN_RADIUS_KM * 1000.0);\n Shape circle = spatialctx.makeCircle(parsePoint(value), degrees);\n SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, circle);\n return strategy.makeFilter(args);\n }",
"private Set<QualifierInstance> getRequiredQualifiers(EnhancedAnnotatedParameter<?, ? super X> enhancedDisposedParameter) {\n Set<Annotation> disposedParameterQualifiers = enhancedDisposedParameter.getMetaAnnotations(Qualifier.class);\n if (disposedParameterQualifiers.isEmpty()) {\n disposedParameterQualifiers = Collections.<Annotation> singleton(Default.Literal.INSTANCE);\n }\n return beanManager.getServices().get(MetaAnnotationStore.class).getQualifierInstances(disposedParameterQualifiers);\n }"
] |
Get a property as an long or default value.
@param key the property name
@param defaultValue the default value | [
"@Override\n public final long optLong(final String key, final long defaultValue) {\n Long result = optLong(key);\n return result == null ? defaultValue : result;\n }"
] | [
"@Override\n public final long getLong(final String key) {\n Long result = optLong(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }",
"private Double zeroIsNull(Double value)\n {\n if (value != null && value.doubleValue() == 0)\n {\n value = null;\n }\n return value;\n }",
"String escapeValue(Object value) {\n return HtmlUtils.htmlEscape(value != null ? value.toString() : \"<null>\");\n }",
"protected String getClasspath() throws IOException {\n List<String> classpath = new ArrayList<>();\n classpath.add(getBundleJarPath());\n classpath.addAll(getPluginsPath());\n return StringUtils.toString(classpath.toArray(new String[classpath.size()]), \" \");\n }",
"public void updateSequenceElement(int[] sequence, int pos, int oldVal) {\r\n if(models != null){\r\n for(int i = 0; i < models.length; i++)\r\n models[i].updateSequenceElement(sequence, pos, oldVal);\r\n return; \r\n }\r\n model1.updateSequenceElement(sequence, pos, 0);\r\n model2.updateSequenceElement(sequence, pos, 0);\r\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 }",
"public static String find(CharSequence self, CharSequence regex, @ClosureParams(value=SimpleType.class, options=\"java.lang.String[]\") Closure closure) {\n return find(self.toString(), Pattern.compile(regex.toString()), closure);\n }",
"private void init() {\n logger.info(\"metadata init().\");\n\n writeLock.lock();\n try {\n // Required keys\n initCache(CLUSTER_KEY);\n\n // If stores definition storage engine is not null, initialize metadata\n // Add the mapping from key to the storage engine used\n if(this.storeDefinitionsStorageEngine != null) {\n initStoreDefinitions(null);\n } else {\n initCache(STORES_KEY);\n }\n\n // Initialize system store in the metadata cache\n initSystemCache();\n initSystemRoutingStrategies(getCluster());\n\n // Initialize with default if not present\n initCache(SLOP_STREAMING_ENABLED_KEY, true);\n initCache(PARTITION_STREAMING_ENABLED_KEY, true);\n initCache(READONLY_FETCH_ENABLED_KEY, true);\n initCache(QUOTA_ENFORCEMENT_ENABLED_KEY, true);\n initCache(REBALANCING_STEAL_INFO, new RebalancerState(new ArrayList<RebalanceTaskInfo>()));\n initCache(SERVER_STATE_KEY, VoldemortState.NORMAL_SERVER.toString());\n initCache(REBALANCING_SOURCE_CLUSTER_XML, null);\n initCache(REBALANCING_SOURCE_STORES_XML, null);\n\n\n } finally {\n writeLock.unlock();\n }\n }",
"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 }"
] |
Get the JSON string representation of the selector configured for this index.
@return selector JSON as string | [
"@Override\n public String getPartialFilterSelector() {\n return (def.selector != null) ? def.selector.toString() : null;\n }"
] | [
"public Where<T, ID> idEq(ID id) throws SQLException {\n\t\tif (idColumnName == null) {\n\t\t\tthrow new SQLException(\"Object has no id column specified\");\n\t\t}\n\t\taddClause(new SimpleComparison(idColumnName, idFieldType, id, SimpleComparison.EQUAL_TO_OPERATION));\n\t\treturn this;\n\t}",
"public AT_Context setFrameLeftRightMargin(int frameLeft, int frameRight){\r\n\t\tif(frameRight>-1 && frameLeft>-1){\r\n\t\t\tthis.frameLeftMargin = frameLeft;\r\n\t\t\tthis.frameRightMargin = frameRight;\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public void setDateOnly(boolean dateOnly) {\n\n if (m_dateOnly != dateOnly) {\n m_dateOnly = dateOnly;\n if (m_dateOnly) {\n m_time.removeFromParent();\n m_am.removeFromParent();\n m_pm.removeFromParent();\n } else {\n m_timeField.add(m_time);\n m_timeField.add(m_am);\n m_timeField.add(m_pm);\n }\n }\n }",
"private FieldDescriptor getFldFromJoin(TableAlias aTableAlias, String aColName)\r\n {\r\n FieldDescriptor fld = null;\r\n\r\n // Search Join Structure for attribute\r\n if (aTableAlias.joins != null)\r\n {\r\n Iterator itr = aTableAlias.joins.iterator();\r\n while (itr.hasNext())\r\n {\r\n Join join = (Join) itr.next();\r\n ClassDescriptor cld = join.right.cld;\r\n\r\n if (cld != null)\r\n {\r\n fld = cld.getFieldDescriptorByName(aColName);\r\n if (fld != null)\r\n {\r\n break;\r\n }\r\n\r\n }\r\n }\r\n }\r\n return fld;\r\n }",
"private void readLeafTasks(Task parent, Integer id)\n {\n Integer currentID = id;\n Table table = getTable(\"A1TAB\");\n while (currentID.intValue() != 0)\n {\n if (m_projectFile.getTaskByUniqueID(currentID) == null)\n {\n readTask(parent, currentID);\n }\n currentID = table.find(currentID).getInteger(\"NEXT_TASK_ID\");\n }\n }",
"public static byte[] hashPath(MessageDigest messageDigest, Path path) throws IOException {\n try (InputStream in = getRecursiveContentStream(path)) {\n return hashContent(messageDigest, in);\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 }",
"private InputStream runSparqlQuery(String query) throws IOException {\n\t\ttry {\n\t\t\tString queryString = \"query=\" + URLEncoder.encode(query, \"UTF-8\")\n\t\t\t\t\t+ \"&format=json\";\n\t\t\tURL url = new URL(\"https://query.wikidata.org/sparql?\"\n\t\t\t\t\t+ queryString);\n\t\t\tHttpURLConnection connection = (HttpURLConnection) url\n\t\t\t\t\t.openConnection();\n\t\t\tconnection.setRequestMethod(\"GET\");\n\n\t\t\treturn connection.getInputStream();\n\t\t} catch (UnsupportedEncodingException | MalformedURLException e) {\n\t\t\tthrow new RuntimeException(e.getMessage(), e);\n\t\t}\n\t}",
"public void start(GVRAccessibilitySpeechListener speechListener) {\n mTts.setSpeechListener(speechListener);\n mTts.getSpeechRecognizer().startListening(mTts.getSpeechRecognizerIntent());\n }"
] |
Use this API to fetch vpnvserver_cachepolicy_binding resources of given name . | [
"public static vpnvserver_cachepolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_cachepolicy_binding obj = new vpnvserver_cachepolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_cachepolicy_binding response[] = (vpnvserver_cachepolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"public static GlobalParameter create(DbConn cnx, String key, String value)\n {\n QueryResult r = cnx.runUpdate(\"globalprm_insert\", key, value);\n GlobalParameter res = new GlobalParameter();\n res.id = r.getGeneratedId();\n res.key = key;\n res.value = value;\n return res;\n }",
"@Override\r\n public void close() {\r\n // Use monitor to avoid race between external close and handler thread run()\r\n synchronized (closeMonitor) {\r\n // Close and clear streams, sockets etc.\r\n if (socket != null) {\r\n try {\r\n // Terminates thread blocking on socket read\r\n // and automatically closed depending streams\r\n socket.close();\r\n } catch (IOException e) {\r\n log.warn(\"Can not close socket\", e);\r\n } finally {\r\n socket = null;\r\n }\r\n }\r\n\r\n // Clear user data\r\n session = null;\r\n response = null;\r\n }\r\n }",
"@Deprecated\n public FluoConfiguration addObservers(Iterable<ObserverSpecification> observers) {\n int next = getNextObserverId();\n for (ObserverSpecification oconf : observers) {\n addObserver(oconf, next++);\n }\n return this;\n }",
"public float getPositionZ(int vertex) {\n if (!hasPositions()) {\n throw new IllegalStateException(\"mesh has no positions\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_vertices.getFloat((vertex * 3 + 2) * SIZEOF_FLOAT);\n }",
"private String getPropertyName(Method method)\n {\n String result = method.getName();\n if (result.startsWith(\"get\"))\n {\n result = result.substring(3);\n }\n return result;\n }",
"public static Map<String, List<String>> getResponseHeaders(String stringUrl,\n boolean followRedirects) throws IOException {\n URL url = new URL(stringUrl);\n HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n conn.setInstanceFollowRedirects(followRedirects);\n \n InputStream is = conn.getInputStream();\n if (\"gzip\".equals(conn.getContentEncoding())) {\n is = new GZIPInputStream(is);\n }\n\n Map<String, List<String>> headers = new LinkedHashMap<String, List<String>>(conn.getHeaderFields());\n headers.put(\"X-Content\", Arrays.asList(MyStreamUtils.readContent(is)));\n headers.put(\"X-URL\", Arrays.asList(conn.getURL().toString()));\n headers.put(\"X-Status\", Arrays.asList(String.valueOf(conn.getResponseCode())));\n \n return headers;\n }",
"protected List<TokenList.Token> parseParameterCommaBlock( TokenList tokens, Sequence sequence ) {\n // find all the comma tokens\n List<TokenList.Token> commas = new ArrayList<TokenList.Token>();\n TokenList.Token token = tokens.first;\n\n int numBracket = 0;\n while( token != null ) {\n if( token.getType() == Type.SYMBOL ) {\n switch( token.getSymbol() ) {\n case COMMA:\n if( numBracket == 0)\n commas.add(token);\n break;\n\n case BRACKET_LEFT: numBracket++; break;\n case BRACKET_RIGHT: numBracket--; break;\n }\n }\n token = token.next;\n }\n\n List<TokenList.Token> output = new ArrayList<TokenList.Token>();\n if( commas.isEmpty() ) {\n output.add(parseBlockNoParentheses(tokens, sequence, false));\n } else {\n TokenList.Token before = tokens.first;\n for (int i = 0; i < commas.size(); i++) {\n TokenList.Token after = commas.get(i);\n if( before == after )\n throw new ParseError(\"No empty function inputs allowed!\");\n TokenList.Token tmp = after.next;\n TokenList sublist = tokens.extractSubList(before,after);\n sublist.remove(after);// remove the comma\n output.add(parseBlockNoParentheses(sublist, sequence, false));\n before = tmp;\n }\n\n // if the last character is a comma then after.next above will be null and thus before is null\n if( before == null )\n throw new ParseError(\"No empty function inputs allowed!\");\n\n TokenList.Token after = tokens.last;\n TokenList sublist = tokens.extractSubList(before, after);\n output.add(parseBlockNoParentheses(sublist, sequence, false));\n }\n\n return output;\n }",
"public static Variable deserialize(String s,\n VariableType variableType) {\n return deserialize(s,\n variableType,\n null);\n }",
"public Where<T, ID> isNull(String columnName) throws SQLException {\n\t\taddClause(new IsNull(columnName, findColumnFieldType(columnName)));\n\t\treturn this;\n\t}"
] |
Updates the indices in the index buffer from a Java IntBuffer.
All of the entries of the input int buffer are copied into
the storage for the index buffer. The new indices must be the
same size as the old indices - the index buffer size cannot be changed.
@param data char array containing the new values
@throws IllegalArgumentException if int buffer is wrong size | [
"public void setIntVec(IntBuffer data)\n {\n if (data == null)\n {\n throw new IllegalArgumentException(\"Input buffer for indices cannot be null\");\n }\n if (getIndexSize() != 4)\n {\n throw new UnsupportedOperationException(\"Cannot update integer indices with short array\");\n }\n if (data.isDirect())\n {\n if (!NativeIndexBuffer.setIntVec(getNative(), data))\n {\n throw new UnsupportedOperationException(\"Input array is wrong size\");\n }\n }\n else if (data.hasArray())\n {\n if (!NativeIndexBuffer.setIntArray(getNative(), data.array()))\n {\n throw new IllegalArgumentException(\"Data array incompatible with index buffer\");\n }\n }\n else\n {\n throw new UnsupportedOperationException(\"IntBuffer type not supported. Must be direct or have backing array\");\n }\n }"
] | [
"public 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 ParallelTaskBuilder setReplacementVarMapNodeSpecific(\n Map<String, StrStrMap> replacementVarMapNodeSpecific) {\n this.replacementVarMapNodeSpecific.clear();\n this.replacementVarMapNodeSpecific\n .putAll(replacementVarMapNodeSpecific);\n\n this.requestReplacementType = RequestReplacementType.TARGET_HOST_SPECIFIC_VAR_REPLACEMENT;\n logger.info(\"Set requestReplacementType as {}\"\n + requestReplacementType.toString());\n return this;\n }",
"public ItemRequest<Section> insertInProject(String project) {\n \n String path = String.format(\"/projects/%s/sections/insert\", project);\n return new ItemRequest<Section>(this, Section.class, path, \"POST\");\n }",
"public void addNotBetween(Object attribute, Object value1, Object value2)\r\n {\r\n // PAW\r\n\t\t// addSelectionCriteria(ValueCriteria.buildNotBeweenCriteria(attribute, value1, value2, getAlias()));\r\n\t\taddSelectionCriteria(ValueCriteria.buildNotBeweenCriteria(attribute, value1, value2, getUserAlias(attribute)));\r\n }",
"public List<ConnectionInfo> getConnections() {\n final URI uri = uriWithPath(\"./connections/\");\n return Arrays.asList(this.rt.getForObject(uri, ConnectionInfo[].class));\n }",
"public CollectionRequest<Section> findByProject(String project) {\n \n String path = String.format(\"/projects/%s/sections\", project);\n return new CollectionRequest<Section>(this, Section.class, path, \"GET\");\n }",
"public static base_responses add(nitro_service client, gslbsite resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tgslbsite addresources[] = new gslbsite[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new gslbsite();\n\t\t\t\taddresources[i].sitename = resources[i].sitename;\n\t\t\t\taddresources[i].sitetype = resources[i].sitetype;\n\t\t\t\taddresources[i].siteipaddress = resources[i].siteipaddress;\n\t\t\t\taddresources[i].publicip = resources[i].publicip;\n\t\t\t\taddresources[i].metricexchange = resources[i].metricexchange;\n\t\t\t\taddresources[i].nwmetricexchange = resources[i].nwmetricexchange;\n\t\t\t\taddresources[i].sessionexchange = resources[i].sessionexchange;\n\t\t\t\taddresources[i].triggermonitor = resources[i].triggermonitor;\n\t\t\t\taddresources[i].parentsite = resources[i].parentsite;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"public Slice newSlice(long address, int size)\n {\n if (address <= 0) {\n throw new IllegalArgumentException(\"Invalid address: \" + address);\n }\n if (size == 0) {\n return Slices.EMPTY_SLICE;\n }\n return new Slice(null, address, size, 0, null);\n }",
"public void setEnterpriseText(int index, String value)\n {\n set(selectField(AssignmentFieldLists.ENTERPRISE_TEXT, index), value);\n }"
] |
Initialize elements of the panel displayed for the deactivated widget. | [
"private void initDeactivationPanel() {\n\n m_deactivationPanel.setVisible(false);\n m_deactivationText.setText(Messages.get().key(Messages.GUI_SERIALDATE_DEACTIVE_TEXT_0));\n\n }"
] | [
"private Observable<Response<ResponseBody>> pollAsync(String url, String loggingContext) {\n URL endpoint;\n try {\n endpoint = new URL(url);\n } catch (MalformedURLException e) {\n return Observable.error(e);\n }\n AsyncService service = restClient().retrofit().create(AsyncService.class);\n if (loggingContext != null && !loggingContext.endsWith(\" (poll)\")) {\n loggingContext += \" (poll)\";\n }\n return service.get(endpoint.getFile(), serviceClientUserAgent, loggingContext)\n .flatMap(new Func1<Response<ResponseBody>, Observable<Response<ResponseBody>>>() {\n @Override\n public Observable<Response<ResponseBody>> call(Response<ResponseBody> response) {\n RuntimeException exception = createExceptionFromResponse(response, 200, 201, 202, 204);\n if (exception != null) {\n return Observable.error(exception);\n } else {\n return Observable.just(response);\n }\n }\n });\n }",
"private ModelNode resolveSubsystems(final List<ModelNode> extensions) {\n\n HostControllerLogger.ROOT_LOGGER.debug(\"Applying extensions provided by master\");\n final ModelNode result = operationExecutor.installSlaveExtensions(extensions);\n if (!SUCCESS.equals(result.get(OUTCOME).asString())) {\n throw HostControllerLogger.ROOT_LOGGER.failedToAddExtensions(result.get(FAILURE_DESCRIPTION));\n }\n final ModelNode subsystems = new ModelNode();\n for (final ModelNode extension : extensions) {\n extensionRegistry.recordSubsystemVersions(extension.asString(), subsystems);\n }\n return subsystems;\n }",
"public Collection<SerialMessage> initialize() {\r\n\t\tArrayList<SerialMessage> result = new ArrayList<SerialMessage>();\r\n\t\t\r\n\t\tif (this.getNode().getManufacturer() == 0x010F && this.getNode().getDeviceType() == 0x0501) {\r\n\t\t\t\tlogger.warn(\"Detected Fibaro FGBS001 Universal Sensor - this device fails to respond to SENSOR_ALARM_GET and SENSOR_ALARM_SUPPORTED_GET.\");\r\n\t\t\t\treturn result;\r\n\t\t}\r\n\t\t\r\n\t\tresult.add(this.getSupportedMessage());\r\n\t\treturn result;\r\n\t}",
"public static final String printFinishDateTime(Date value)\n {\n if (value != null)\n {\n value = DateHelper.addDays(value, 1);\n }\n return (value == null ? null : DATE_FORMAT.get().format(value));\n }",
"public void set(String name, Object value) {\n hashAttributes.put(name, value);\n\n if (plugin != null) {\n plugin.invalidate();\n }\n }",
"@Override\n public void onKeyDown(KeyDownEvent event) {\n\tchar c = MiscUtils.getCharCode(event.getNativeEvent());\n\tonKeyCodeEvent(event, box.getValue()+c);\n }",
"private static void multBlockAdd( double []blockA, double []blockB, double []blockC,\n final int m, final int n, final int o,\n final int blockLength ) {\n// for( int i = 0; i < m; i++ ) {\n// for( int j = 0; j < o; j++ ) {\n// double val = 0;\n// for( int k = 0; k < n; k++ ) {\n// val += blockA[ i*blockLength + k]*blockB[ k*blockLength + j];\n// }\n//\n// blockC[ i*blockLength + j] += val;\n// }\n// }\n\n// int rowA = 0;\n// for( int i = 0; i < m; i++ , rowA += blockLength) {\n// for( int j = 0; j < o; j++ ) {\n// double val = 0;\n// int indexB = j;\n// int indexA = rowA;\n// int end = indexA + n;\n// for( ; indexA != end; indexA++ , indexB += blockLength ) {\n// val += blockA[ indexA ]*blockB[ indexB ];\n// }\n//\n// blockC[ rowA + j] += val;\n// }\n// }\n\n// for( int k = 0; k < n; k++ ) {\n// for( int i = 0; i < m; i++ ) {\n// for( int j = 0; j < o; j++ ) {\n// blockC[ i*blockLength + j] += blockA[ i*blockLength + k]*blockB[ k*blockLength + j];\n// }\n// }\n// }\n\n for( int k = 0; k < n; k++ ) {\n int rowB = k*blockLength;\n int endB = rowB+o;\n for( int i = 0; i < m; i++ ) {\n int indexC = i*blockLength;\n double valA = blockA[ indexC + k];\n int indexB = rowB;\n \n while( indexB != endB ) {\n blockC[ indexC++ ] += valA*blockB[ indexB++];\n }\n }\n }\n }",
"public ItemRequest<Project> addMembers(String project) {\n \n String path = String.format(\"/projects/%s/addMembers\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\n }",
"private static void listTasks(ProjectFile file)\n {\n SimpleDateFormat df = new SimpleDateFormat(\"dd/MM/yyyy HH:mm z\");\n\n for (Task task : file.getTasks())\n {\n Date date = task.getStart();\n String text = task.getStartText();\n String startDate = text != null ? text : (date != null ? df.format(date) : \"(no start date supplied)\");\n\n date = task.getFinish();\n text = task.getFinishText();\n String finishDate = text != null ? text : (date != null ? df.format(date) : \"(no finish date supplied)\");\n\n Duration dur = task.getDuration();\n text = task.getDurationText();\n String duration = text != null ? text : (dur != null ? dur.toString() : \"(no duration supplied)\");\n\n dur = task.getActualDuration();\n String actualDuration = dur != null ? dur.toString() : \"(no actual duration supplied)\";\n\n String baselineDuration = task.getBaselineDurationText();\n if (baselineDuration == null)\n {\n dur = task.getBaselineDuration();\n if (dur != null)\n {\n baselineDuration = dur.toString();\n }\n else\n {\n baselineDuration = \"(no duration supplied)\";\n }\n }\n\n System.out.println(\"Task: \" + task.getName() + \" ID=\" + task.getID() + \" Unique ID=\" + task.getUniqueID() + \" (Start Date=\" + startDate + \" Finish Date=\" + finishDate + \" Duration=\" + duration + \" Actual Duration\" + actualDuration + \" Baseline Duration=\" + baselineDuration + \" Outline Level=\" + task.getOutlineLevel() + \" Outline Number=\" + task.getOutlineNumber() + \" Recurring=\" + task.getRecurring() + \")\");\n }\n System.out.println();\n }"
] |
Generates a vector clock with the provided values
@param serverIds servers in the clock
@param clockValue value of the clock for each server entry
@param timestamp ts value to be set for the clock
@return | [
"public static VectorClock makeClock(Set<Integer> serverIds, long clockValue, long timestamp) {\n List<ClockEntry> clockEntries = new ArrayList<ClockEntry>(serverIds.size());\n for(Integer serverId: serverIds) {\n clockEntries.add(new ClockEntry(serverId.shortValue(), clockValue));\n }\n return new VectorClock(clockEntries, timestamp);\n }"
] | [
"public ProjectCalendar getDefaultCalendar()\n {\n String calendarName = m_properties.getDefaultCalendarName();\n ProjectCalendar calendar = getCalendarByName(calendarName);\n if (calendar == null)\n {\n if (m_calendars.isEmpty())\n {\n calendar = addDefaultBaseCalendar();\n }\n else\n {\n calendar = m_calendars.get(0);\n }\n }\n return calendar;\n }",
"void commitTempFile(File temp) throws ConfigurationPersistenceException {\n if (!doneBootup.get()) {\n return;\n }\n if (!interactionPolicy.isReadOnly()) {\n FilePersistenceUtils.moveTempFileToMain(temp, mainFile);\n } else {\n FilePersistenceUtils.moveTempFileToMain(temp, lastFile);\n }\n }",
"public void setIndexBuffer(GVRIndexBuffer ibuf)\n {\n mIndices = ibuf;\n NativeMesh.setIndexBuffer(getNative(), (ibuf != null) ? ibuf.getNative() : 0L);\n }",
"@Deprecated\n public void validateOperation(final ModelNode operation) throws OperationFailedException {\n if (operation.hasDefined(ModelDescriptionConstants.OPERATION_NAME) && deprecationData != null && deprecationData.isNotificationUseful()) {\n ControllerLogger.DEPRECATED_LOGGER.operationDeprecated(getName(),\n PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR)).toCLIStyleString());\n }\n for (AttributeDefinition ad : this.parameters) {\n ad.validateOperation(operation);\n }\n }",
"public ProjectCalendarWeek addWorkWeek()\n {\n ProjectCalendarWeek week = new ProjectCalendarWeek();\n week.setParent(this);\n m_workWeeks.add(week);\n m_weeksSorted = false;\n clearWorkingDateCache();\n return week;\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 }",
"private void clearWaveforms(DeviceAnnouncement announcement) {\n final int player = announcement.getNumber();\n // Iterate over a copy to avoid concurrent modification issues\n for (DeckReference deck : new HashSet<DeckReference>(previewHotCache.keySet())) {\n if (deck.player == player) {\n previewHotCache.remove(deck);\n if (deck.hotCue == 0) {\n deliverWaveformPreviewUpdate(player, null); // Inform listeners that preview is gone.\n }\n }\n }\n // Again iterate over a copy to avoid concurrent modification issues\n for (DeckReference deck : new HashSet<DeckReference>(detailHotCache.keySet())) {\n if (deck.player == player) {\n detailHotCache.remove(deck);\n if (deck.hotCue == 0) {\n deliverWaveformDetailUpdate(player, null); // Inform listeners that detail is gone.\n }\n }\n }\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}",
"private void _handleMultiValues(ArrayList<String> values, String key, String command) {\n if (key == null) return;\n\n if (values == null || values.isEmpty()) {\n _generateEmptyMultiValueError(key);\n return;\n }\n\n ValidationResult vr;\n\n // validate the key\n vr = validator.cleanMultiValuePropertyKey(key);\n\n // Check for an error\n if (vr.getErrorCode() != 0) {\n pushValidationResult(vr);\n }\n\n // reset the key\n Object _key = vr.getObject();\n String cleanKey = (_key != null) ? vr.getObject().toString() : null;\n\n // if key is empty generate an error and return\n if (cleanKey == null || cleanKey.isEmpty()) {\n _generateInvalidMultiValueKeyError(key);\n return;\n }\n\n key = cleanKey;\n\n try {\n JSONArray currentValues = _constructExistingMultiValue(key, command);\n JSONArray newValues = _cleanMultiValues(values, key);\n _validateAndPushMultiValue(currentValues, newValues, values, key, command);\n\n } catch (Throwable t) {\n getConfigLogger().verbose(getAccountId(), \"Error handling multi value operation for key \" + key, t);\n }\n }"
] |
Finish initialization of the configuration. | [
"@PostConstruct\n\tprotected void postConstruct() {\n\t\tif (null == authenticationServices) {\n\t\t\tauthenticationServices = new ArrayList<AuthenticationService>();\n\t\t}\n\t\tif (!excludeDefault) {\n\t\t\tauthenticationServices.add(staticAuthenticationService);\n\t\t}\n\t}"
] | [
"public static wisite_binding[] get(nitro_service service, String sitepath[]) throws Exception{\n\t\tif (sitepath !=null && sitepath.length>0) {\n\t\t\twisite_binding response[] = new wisite_binding[sitepath.length];\n\t\t\twisite_binding obj[] = new wisite_binding[sitepath.length];\n\t\t\tfor (int i=0;i<sitepath.length;i++) {\n\t\t\t\tobj[i] = new wisite_binding();\n\t\t\t\tobj[i].set_sitepath(sitepath[i]);\n\t\t\t\tresponse[i] = (wisite_binding) 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 String format(String format) {\n\n if (format == null) {\n format = DEFAULT_FORMAT;\n } else {\n if (format.contains(\"M\")) {\n format = format.replace(\"M\", \"m\");\n }\n\n if (format.contains(\"Y\")) {\n format = format.replace(\"Y\", \"y\");\n }\n\n if (format.contains(\"D\")) {\n format = format.replace(\"D\", \"d\");\n }\n }\n return format;\n }",
"public static base_response renumber(nitro_service client) throws Exception {\n\t\tnspbr6 renumberresource = new nspbr6();\n\t\treturn renumberresource.perform_operation(client,\"renumber\");\n\t}",
"public void reset( int N ) {\n this.N = N;\n\n this.diag = null;\n this.off = null;\n\n if( splits.length < N ) {\n splits = new int[N];\n }\n\n numSplits = 0;\n\n x1 = 0;\n x2 = N-1;\n\n steps = numExceptional = lastExceptional = 0;\n\n this.Q = null;\n }",
"private void destroyRequestQueue(Queue<AsyncResourceRequest<V>> requestQueue) {\n if(requestQueue != null) {\n AsyncResourceRequest<V> resourceRequest = requestQueue.poll();\n while(resourceRequest != null) {\n destroyRequest(resourceRequest);\n resourceRequest = requestQueue.poll();\n }\n }\n }",
"public static String detokenize(List<String> tokens) {\n return TwitterKoreanProcessor.detokenize(JavaConversions.iterableAsScalaIterable(tokens));\n }",
"public static base_response clear(nitro_service client, bridgetable resource) throws Exception {\n\t\tbridgetable clearresource = new bridgetable();\n\t\tclearresource.vlan = resource.vlan;\n\t\tclearresource.ifnum = resource.ifnum;\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}",
"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 auditmessages[] get(nitro_service service, auditmessages_args args) throws Exception{\n\t\tauditmessages obj = new auditmessages();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tauditmessages[] response = (auditmessages[])obj.get_resources(service, option);\n\t\treturn response;\n\t}"
] |
Read task baseline values.
@param row result set row | [
"protected void processTaskBaseline(Row row)\n {\n Integer id = row.getInteger(\"TASK_UID\");\n Task task = m_project.getTaskByUniqueID(id);\n if (task != null)\n {\n int index = row.getInt(\"TB_BASE_NUM\");\n\n task.setBaselineDuration(index, MPDUtility.getAdjustedDuration(m_project, row.getInt(\"TB_BASE_DUR\"), MPDUtility.getDurationTimeUnits(row.getInt(\"TB_BASE_DUR_FMT\"))));\n task.setBaselineStart(index, row.getDate(\"TB_BASE_START\"));\n task.setBaselineFinish(index, row.getDate(\"TB_BASE_FINISH\"));\n task.setBaselineWork(index, row.getDuration(\"TB_BASE_WORK\"));\n task.setBaselineCost(index, row.getCurrency(\"TB_BASE_COST\"));\n }\n }"
] | [
"public UniqueEntityLoader buildLoader(\n\t\t\tOuterJoinLoadable persister,\n\t\t\tint batchSize,\n\t\t\tLockOptions lockOptions,\n\t\t\tSessionFactoryImplementor factory,\n\t\t\tLoadQueryInfluencers influencers,\n\t\t\tBatchableEntityLoaderBuilder innerEntityLoaderBuilder) {\n\t\tif ( batchSize <= 1 ) {\n\t\t\t// no batching\n\t\t\treturn buildNonBatchingLoader( persister, lockOptions, factory, influencers, innerEntityLoaderBuilder );\n\t\t}\n\t\treturn buildBatchingLoader( persister, batchSize, lockOptions, factory, influencers, innerEntityLoaderBuilder );\n\t}",
"public void load(IAssetEvents handler)\n {\n GVRAssetLoader loader = getGVRContext().getAssetLoader();\n\n if (mReplaceScene)\n {\n loader.loadScene(getOwnerObject(), mVolume, mImportSettings, getGVRContext().getMainScene(), handler);\n }\n else\n {\n loader.loadModel(mVolume, getOwnerObject(), mImportSettings, true, handler);\n }\n }",
"public static DatabaseFieldConfig fromReader(BufferedReader reader) throws SQLException {\n\t\tDatabaseFieldConfig config = new DatabaseFieldConfig();\n\t\tboolean anything = false;\n\t\twhile (true) {\n\t\t\tString line;\n\t\t\ttry {\n\t\t\t\tline = reader.readLine();\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow SqlExceptionUtil.create(\"Could not read DatabaseFieldConfig from stream\", e);\n\t\t\t}\n\t\t\tif (line == null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// we do this so we can support multiple class configs per file\n\t\t\tif (line.equals(CONFIG_FILE_END_MARKER)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// skip empty lines or comments\n\t\t\tif (line.length() == 0 || line.startsWith(\"#\") || line.equals(CONFIG_FILE_START_MARKER)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tString[] parts = line.split(\"=\", -2);\n\t\t\tif (parts.length != 2) {\n\t\t\t\tthrow new SQLException(\"DatabaseFieldConfig reading from stream cannot parse line: \" + line);\n\t\t\t}\n\t\t\treadField(config, parts[0], parts[1]);\n\t\t\tanything = true;\n\t\t}\n\t\t// if we got any config lines then we return the config\n\t\tif (anything) {\n\t\t\treturn config;\n\t\t} else {\n\t\t\t// otherwise we return null for none\n\t\t\treturn null;\n\t\t}\n\t}",
"public void 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 setRotation(String rotation) {\r\n if (rotation != null) {\r\n try {\r\n setRotation(Integer.parseInt(rotation));\r\n } catch (NumberFormatException e) {\r\n setRotation(-1);\r\n }\r\n }\r\n }",
"private void setExceptions(ProjectCalendar mpxjCalendar, Calendars gpCalendar)\n {\n List<net.sf.mpxj.ganttproject.schema.Date> dates = gpCalendar.getDate();\n for (net.sf.mpxj.ganttproject.schema.Date date : dates)\n {\n addException(mpxjCalendar, date);\n }\n }",
"public static final int getInt(String value)\n {\n return (value == null || value.length() == 0 ? 0 : Integer.parseInt(value));\n }",
"public static HttpConnection connect(String requestMethod,\n URL url,\n String contentType) {\n return new HttpConnection(requestMethod, url, contentType);\n }",
"public static void setTime(Calendar cal, Date time)\n {\n if (time != null)\n {\n Calendar startCalendar = popCalendar(time);\n cal.set(Calendar.HOUR_OF_DAY, startCalendar.get(Calendar.HOUR_OF_DAY));\n cal.set(Calendar.MINUTE, startCalendar.get(Calendar.MINUTE));\n cal.set(Calendar.SECOND, startCalendar.get(Calendar.SECOND));\n pushCalendar(startCalendar);\n }\n }"
] |
Get logs for an app.
@param appName App name. See {@link #listApps} for a list of apps that can be used.
@return log stream response | [
"public LogStreamResponse getLogs(String appName, Boolean tail) {\n return connection.execute(new Log(appName, tail), apiKey);\n }"
] | [
"public Range<Dyno> listDynos(String appName) {\n return connection.execute(new DynoList(appName), apiKey);\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 boolean retainAll(Collection<?> collection) {\n\t\tif (dao == null) {\n\t\t\treturn false;\n\t\t}\n\t\tboolean changed = false;\n\t\tCloseableIterator<T> iterator = closeableIterator();\n\t\ttry {\n\t\t\twhile (iterator.hasNext()) {\n\t\t\t\tT data = iterator.next();\n\t\t\t\tif (!collection.contains(data)) {\n\t\t\t\t\titerator.remove();\n\t\t\t\t\tchanged = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn changed;\n\t\t} finally {\n\t\t\tIOUtils.closeQuietly(iterator);\n\t\t}\n\t}",
"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 Profile getProfileFromResultSet(ResultSet result) throws Exception {\n Profile profile = new Profile();\n profile.setId(result.getInt(Constants.GENERIC_ID));\n Clob clobProfileName = result.getClob(Constants.PROFILE_PROFILE_NAME);\n String profileName = clobProfileName.getSubString(1, (int) clobProfileName.length());\n profile.setName(profileName);\n return profile;\n }",
"public static boolean isSymmetric( DMatrixSparseCSC A , double tol ) {\n if( A.numRows != A.numCols )\n return false;\n\n int N = A.numCols;\n\n for (int i = 0; i < N; i++) {\n int idx0 = A.col_idx[i];\n int idx1 = A.col_idx[i+1];\n\n for (int index = idx0; index < idx1; index++) {\n int j = A.nz_rows[index];\n double value_ji = A.nz_values[index];\n double value_ij = A.get(i,j);\n\n if( Math.abs(value_ij-value_ji) > tol )\n return false;\n }\n }\n\n return true;\n }",
"public boolean isDuplicateName(String name) {\n if (name == null || name.trim().isEmpty()) {\n return false;\n }\n List<AssignmentRow> as = view.getAssignmentRows();\n if (as != null && !as.isEmpty()) {\n int nameCount = 0;\n for (AssignmentRow row : as) {\n if (name.trim().compareTo(row.getName()) == 0) {\n nameCount++;\n if (nameCount > 1) {\n return true;\n }\n }\n }\n }\n return false;\n }",
"public boolean perform(Run<?, ?> build, Launcher launcher, TaskListener listener, EnvVars env, FilePath workDir, FilePath tempDir)\n throws InterruptedException, IOException {\n listener.getLogger().println(\"Jenkins Artifactory Plugin version: \" + ActionableHelper.getArtifactoryPluginVersion());\n FilePath mavenHome = getMavenHome(listener, env, launcher);\n\n if (!mavenHome.exists()) {\n listener.getLogger().println(\"Couldn't find Maven home at \" + mavenHome.getRemote() + \" on agent \" + Utils.getAgentName(workDir) +\n \". This could be because this build is running inside a Docker container.\");\n }\n ArgumentListBuilder cmdLine = buildMavenCmdLine(build, listener, env, launcher, mavenHome, workDir, tempDir);\n String[] cmds = cmdLine.toCommandArray();\n return RunMaven(build, launcher, listener, env, workDir, cmds);\n }",
"public static synchronized void clearDaoCache() {\n\t\tif (classMap != null) {\n\t\t\tclassMap.clear();\n\t\t\tclassMap = null;\n\t\t}\n\t\tif (tableConfigMap != null) {\n\t\t\ttableConfigMap.clear();\n\t\t\ttableConfigMap = null;\n\t\t}\n\t}"
] |
Creates a statement with parameters that should work with most RDBMS. | [
"private Statement createStatement(Connection con, boolean scrollable, int explicitFetchSizeHint)\r\n throws java.sql.SQLException\r\n {\r\n Statement result;\r\n try\r\n {\r\n // if necessary use JDBC1.0 methods\r\n if (!FORCEJDBC1_0)\r\n {\r\n result =\r\n con.createStatement(\r\n scrollable\r\n ? ResultSet.TYPE_SCROLL_INSENSITIVE\r\n : ResultSet.TYPE_FORWARD_ONLY,\r\n ResultSet.CONCUR_READ_ONLY);\r\n afterJdbc2CapableStatementCreate(result, explicitFetchSizeHint);\r\n }\r\n else\r\n {\r\n result = con.createStatement();\r\n }\r\n }\r\n catch (AbstractMethodError err)\r\n {\r\n // if a JDBC1.0 driver is used, the signature\r\n // createStatement(int, int) is not defined.\r\n // we then call the JDBC1.0 variant createStatement()\r\n log.warn(\"Used driver seems not JDBC 2.0 compatible, use the JDBC 1.0 mode\", err);\r\n result = con.createStatement();\r\n FORCEJDBC1_0 = true;\r\n }\r\n catch (SQLException eSql)\r\n {\r\n // there are JDBC Driver that nominally implement JDBC 2.0, but\r\n // throw DriverNotCapableExceptions. If we catch one of these\r\n // we force usage of JDBC 1.0\r\n if (eSql.getClass().getName()\r\n .equals(\"interbase.interclient.DriverNotCapableException\"))\r\n {\r\n log.warn(\"JDBC 2.0 problems with this interbase driver, we use the JDBC 1.0 mode\");\r\n FORCEJDBC1_0 = true;\r\n result = con.createStatement();\r\n }\r\n else\r\n {\r\n throw eSql;\r\n }\r\n }\r\n try\r\n {\r\n platform.afterStatementCreate(result);\r\n }\r\n catch (PlatformException e)\r\n {\r\n log.error(\"Platform dependend failure\", e);\r\n }\r\n return result;\r\n }"
] | [
"private void gobble(Iterator iter)\n {\n if (eatTheRest)\n {\n while (iter.hasNext())\n {\n tokens.add(iter.next());\n }\n }\n }",
"public static boolean doAcquireLock(final Jedis jedis, final String namespace, final String lockName, final String lockHolder, final int timeout) {\n final String key = JesqueUtils.createKey(namespace, lockName);\n // If lock already exists, extend it\n String existingLockHolder = jedis.get(key);\n if ((existingLockHolder != null) && existingLockHolder.equals(lockHolder)) {\n if (jedis.expire(key, timeout) == 1) {\n existingLockHolder = jedis.get(key);\n if ((existingLockHolder != null) && existingLockHolder.equals(lockHolder)) {\n return true;\n }\n }\n }\n // Check to see if the key exists and is expired for cleanup purposes\n if (jedis.exists(key) && (jedis.ttl(key) < 0)) {\n // It is expired, but it may be in the process of being created, so\n // sleep and check again\n try {\n Thread.sleep(2000);\n } catch (InterruptedException ie) {\n } // Ignore interruptions\n if (jedis.ttl(key) < 0) {\n existingLockHolder = jedis.get(key);\n // If it is our lock mark the time to live\n if ((existingLockHolder != null) && existingLockHolder.equals(lockHolder)) {\n if (jedis.expire(key, timeout) == 1) {\n existingLockHolder = jedis.get(key);\n if ((existingLockHolder != null) && existingLockHolder.equals(lockHolder)) {\n return true;\n }\n }\n } else { // The key is expired, whack it!\n jedis.del(key);\n }\n } else { // Someone else locked it while we were sleeping\n return false;\n }\n }\n // Ignore the cleanup steps above, start with no assumptions test\n // creating the key\n if (jedis.setnx(key, lockHolder) == 1) {\n // Created the lock, now set the expiration\n if (jedis.expire(key, timeout) == 1) { // Set the timeout\n existingLockHolder = jedis.get(key);\n if ((existingLockHolder != null) && existingLockHolder.equals(lockHolder)) {\n return true;\n }\n } else { // Don't know why it failed, but for now just report failed\n // acquisition\n return false;\n }\n }\n // Failed to create the lock\n return false;\n }",
"public void set(int index, T object) {\n synchronized (mLock) {\n if (mOriginalValues != null) {\n mOriginalValues.set(index, object);\n } else {\n mObjects.set(index, object);\n }\n }\n if (mNotifyOnChange) notifyDataSetChanged();\n }",
"private TreeMap<Integer, Integer> createResourceMap(FieldMap fieldMap, FixedMeta rscFixedMeta, FixedData rscFixedData)\n {\n TreeMap<Integer, Integer> resourceMap = new TreeMap<Integer, Integer>();\n int itemCount = rscFixedMeta.getAdjustedItemCount();\n\n for (int loop = 0; loop < itemCount; loop++)\n {\n byte[] data = rscFixedData.getByteArrayValue(loop);\n if (data == null || data.length < fieldMap.getMaxFixedDataSize(0))\n {\n continue;\n }\n\n Integer uniqueID = Integer.valueOf(MPPUtility.getShort(data, 0));\n resourceMap.put(uniqueID, Integer.valueOf(loop));\n }\n\n return (resourceMap);\n }",
"public static base_response disable(nitro_service client, String id) throws Exception {\n\t\tInterface disableresource = new Interface();\n\t\tdisableresource.id = id;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}",
"public Boolean verifySubscriberRequestedSubscription(SubscriptionRequest sr) throws SubscriptionOriginVerificationException {\n\n LOG.info(\"(Hub) -> Subscriber, sending notification to verify the origin of the subscription {}.\", sr.getCallback());\n\n SubscriptionConfirmationRequest sc = new SubscriptionConfirmationRequest(sr.getMode(),\n sr.getTopic(), \"challenge\", \"0\");\n\n URI uri;\n try {\n uri = new URIBuilder(sr.getCallback()).setParameters(sc.toRequestParameters()).build();\n } catch (URISyntaxException e) {\n throw new SubscriptionOriginVerificationException(\"URISyntaxException while sending a confirmation of subscription\", e);\n }\n\n HttpGet httpGet = new HttpGet(uri);\n\n CloseableHttpClient httpclient = HttpClients.createDefault();\n\n CloseableHttpResponse response;\n try {\n response = httpclient.execute(httpGet);\n } catch (IOException e) {\n throw new SubscriptionOriginVerificationException(\"IOException while sending a confirmation of subscription\", e);\n }\n\n LOG.info(\"Subscriber replied with the http code {}.\", response.getStatusLine().getStatusCode());\n\n Integer returnedCode = response.getStatusLine().getStatusCode();\n\n // if code is a success code return true, else false\n return (199 < returnedCode) && (returnedCode < 300);\n }",
"@Override\n\tpublic String toFullString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = getStringCache().fullString) == null) {\n\t\t\tgetStringCache().fullString = result = toNormalizedString(IPv6StringCache.fullParams);\n\t\t}\n\t\treturn result;\n\t}",
"public CompletableFuture<Void> stop() {\n numPendingStopRequests.incrementAndGet();\n return startStop.stop().thenRun(numPendingStopRequests::decrementAndGet);\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}"
] |
Creates an object from the given JSON data.
@param data the JSON data
@param clazz the class object for the content of the JSON data
@param <T> the type of the class object extending {@link InterconnectObject}
@return the object contained in the given JSON data
@throws JsonParseException if a the JSON data could not be parsed
@throws JsonMappingException if the mapping of the JSON data to the IVO failed
@throws IOException if an I/O related problem occurred | [
"public static <T extends InterconnectObject> T fromJson(String data, Class<T> clazz) throws IOException {\n return InterconnectMapper.mapper.readValue(data, clazz);\n }"
] | [
"public ByteArray readBytes(int size) throws IOException\n {\n byte[] data = new byte[size];\n m_stream.read(data);\n return new ByteArray(data);\n }",
"public Date getStartTime(Date date)\n {\n Date result = m_startTimeCache.get(date);\n if (result == null)\n {\n ProjectCalendarDateRanges ranges = getRanges(date, null, null);\n if (ranges == null)\n {\n result = getParentFile().getProjectProperties().getDefaultStartTime();\n }\n else\n {\n result = ranges.getRange(0).getStart();\n }\n result = DateHelper.getCanonicalTime(result);\n m_startTimeCache.put(new Date(date.getTime()), result);\n }\n return result;\n }",
"private Logger createLoggerInstance(String loggerName) throws Exception\r\n {\r\n Class loggerClass = getConfiguration().getLoggerClass();\r\n Logger log = (Logger) ClassHelper.newInstance(loggerClass, String.class, loggerName);\r\n log.configure(getConfiguration());\r\n return log;\r\n }",
"public static Cluster vacateZone(Cluster currentCluster, int dropZoneId) {\n Cluster returnCluster = Cluster.cloneCluster(currentCluster);\n // Go over each node in the zone being dropped\n for(Integer nodeId: currentCluster.getNodeIdsInZone(dropZoneId)) {\n // For each node grab all the partitions it hosts\n for(Integer partitionId: currentCluster.getNodeById(nodeId).getPartitionIds()) {\n // Now for each partition find a new home..which would be a node\n // in one of the existing zones\n int finalZoneId = -1;\n int finalNodeId = -1;\n int adjacentPartitionId = partitionId;\n do {\n adjacentPartitionId = (adjacentPartitionId + 1)\n % currentCluster.getNumberOfPartitions();\n finalNodeId = currentCluster.getNodeForPartitionId(adjacentPartitionId).getId();\n finalZoneId = currentCluster.getZoneForPartitionId(adjacentPartitionId).getId();\n if(adjacentPartitionId == partitionId) {\n logger.error(\"PartitionId \" + partitionId + \"stays unchanged \\n\");\n } else {\n logger.info(\"PartitionId \" + partitionId\n + \" goes together with partition \" + adjacentPartitionId\n + \" on node \" + finalNodeId + \" in zone \" + finalZoneId);\n returnCluster = UpdateClusterUtils.createUpdatedCluster(returnCluster,\n finalNodeId,\n Lists.newArrayList(partitionId));\n }\n } while(finalZoneId == dropZoneId);\n }\n }\n return returnCluster;\n }",
"public static InputStream getContentStream(String stringUrl) throws MalformedURLException, IOException {\n URL url = new URL(stringUrl);\n \n URLConnection urlConnection = url.openConnection();\n \n InputStream is = urlConnection.getInputStream();\n if (\"gzip\".equals(urlConnection.getContentEncoding())) {\n is = new GZIPInputStream(is);\n }\n\n return is;\n }",
"PollingState<T> withStatus(String status, int statusCode) throws IllegalArgumentException {\n if (status == null) {\n throw new IllegalArgumentException(\"Status is null.\");\n }\n this.status = status;\n this.statusCode = statusCode;\n return this;\n }",
"private void readBitFields(MppBitFlag[] flags, FieldContainer container, byte[] data)\n {\n for (MppBitFlag flag : flags)\n {\n flag.setValue(container, data);\n }\n }",
"public float getLayoutSize(final Layout.Axis axis) {\n float size = 0;\n for (Layout layout : mLayouts) {\n size = Math.max(size, layout.getSize(axis));\n }\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"getLayoutSize [%s] axis [%s] size [%f]\", getName(), axis, size);\n return size;\n }",
"public MetaClassRegistryChangeEventListener[] getMetaClassRegistryChangeEventListeners() {\n synchronized (changeListenerList) {\n ArrayList<MetaClassRegistryChangeEventListener> ret =\n new ArrayList<MetaClassRegistryChangeEventListener>(changeListenerList.size()+nonRemoveableChangeListenerList.size());\n ret.addAll(nonRemoveableChangeListenerList);\n ret.addAll(changeListenerList);\n return ret.toArray(new MetaClassRegistryChangeEventListener[ret.size()]);\n }\n }"
] |
Note that the index can only be built once.
@param beans The set of beans the index should be built from, only instances of {@link CommonBean} and implementations of {@link PassivationCapable} are
included
@throws IllegalStateException If the index is built already | [
"public void build(Set<Bean<?>> beans) {\n\n if (isBuilt()) {\n throw new IllegalStateException(\"BeanIdentifier index is already built!\");\n }\n\n if (beans.isEmpty()) {\n index = new BeanIdentifier[0];\n reverseIndex = Collections.emptyMap();\n indexHash = 0;\n indexBuilt.set(true);\n return;\n }\n\n List<BeanIdentifier> tempIndex = new ArrayList<BeanIdentifier>(beans.size());\n\n for (Bean<?> bean : beans) {\n if (bean instanceof CommonBean<?>) {\n tempIndex.add(((CommonBean<?>) bean).getIdentifier());\n } else if (bean instanceof PassivationCapable) {\n tempIndex.add(new StringBeanIdentifier(((PassivationCapable) bean).getId()));\n }\n }\n\n Collections.sort(tempIndex, new Comparator<BeanIdentifier>() {\n @Override\n public int compare(BeanIdentifier o1, BeanIdentifier o2) {\n return o1.asString().compareTo(o2.asString());\n }\n });\n\n index = tempIndex.toArray(new BeanIdentifier[tempIndex.size()]);\n\n ImmutableMap.Builder<BeanIdentifier, Integer> builder = ImmutableMap.builder();\n for (int i = 0; i < index.length; i++) {\n builder.put(index[i], i);\n }\n reverseIndex = builder.build();\n\n indexHash = Arrays.hashCode(index);\n\n if(BootstrapLogger.LOG.isDebugEnabled()) {\n BootstrapLogger.LOG.beanIdentifierIndexBuilt(getDebugInfo());\n }\n indexBuilt.set(true);\n }"
] | [
"public void addBetween(Object attribute, Object value1, Object value2)\r\n {\r\n\t\t// PAW\r\n\t\t// addSelectionCriteria(ValueCriteria.buildBeweenCriteria(attribute, value1, value2, getAlias()));\r\n\t\taddSelectionCriteria(ValueCriteria.buildBeweenCriteria(attribute, value1, value2, getUserAlias(attribute)));\r\n }",
"public static base_response update(nitro_service client, autoscaleprofile resource) throws Exception {\n\t\tautoscaleprofile updateresource = new autoscaleprofile();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.url = resource.url;\n\t\tupdateresource.apikey = resource.apikey;\n\t\tupdateresource.sharedsecret = resource.sharedsecret;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public static auditsyslogpolicy_aaauser_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditsyslogpolicy_aaauser_binding obj = new auditsyslogpolicy_aaauser_binding();\n\t\tobj.set_name(name);\n\t\tauditsyslogpolicy_aaauser_binding response[] = (auditsyslogpolicy_aaauser_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static boolean isSinglePositionPrefix(FieldInfo fieldInfo,\n String prefix) throws IOException {\n if (fieldInfo == null) {\n throw new IOException(\"no fieldInfo\");\n } else {\n String info = fieldInfo.getAttribute(\n MtasCodecPostingsFormat.MTAS_FIELDINFO_ATTRIBUTE_PREFIX_SINGLE_POSITION);\n if (info == null) {\n throw new IOException(\"no \"\n + MtasCodecPostingsFormat.MTAS_FIELDINFO_ATTRIBUTE_PREFIX_SINGLE_POSITION);\n } else {\n return Arrays.asList(info.split(Pattern.quote(MtasToken.DELIMITER)))\n .contains(prefix);\n }\n }\n }",
"private void cascadeMarkedForInsert()\r\n {\r\n // This list was used to avoid endless recursion on circular references\r\n List alreadyPrepared = new ArrayList();\r\n for(int i = 0; i < markedForInsertList.size(); i++)\r\n {\r\n ObjectEnvelope mod = (ObjectEnvelope) markedForInsertList.get(i);\r\n // only if a new object was found we cascade to register the dependent objects\r\n if(mod.needsInsert())\r\n {\r\n cascadeInsertFor(mod, alreadyPrepared);\r\n alreadyPrepared.clear();\r\n }\r\n }\r\n markedForInsertList.clear();\r\n }",
"public static final Integer getInteger(Number value)\n {\n Integer result = null;\n if (value != null)\n {\n if (value instanceof Integer)\n {\n result = (Integer) value;\n }\n else\n {\n result = Integer.valueOf((int) Math.round(value.doubleValue()));\n }\n }\n return (result);\n }",
"public void processField(String template, Properties attributes) throws XDocletException\r\n {\r\n String name = OjbMemberTagsHandler.getMemberName();\r\n String defaultType = getDefaultJdbcTypeForCurrentMember();\r\n String defaultConversion = getDefaultJdbcConversionForCurrentMember();\r\n FieldDescriptorDef fieldDef = _curClassDef.getField(name);\r\n String attrName;\r\n\r\n if (fieldDef == null)\r\n {\r\n fieldDef = new FieldDescriptorDef(name);\r\n _curClassDef.addField(fieldDef);\r\n }\r\n LogHelper.debug(false, OjbTagsHandler.class, \"processField\", \" Processing field \"+fieldDef.getName());\r\n\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n fieldDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n // storing additional info for later use\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_JAVA_TYPE,\r\n OjbMemberTagsHandler.getMemberType().getQualifiedName());\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_JDBC_TYPE, defaultType);\r\n if (defaultConversion != null)\r\n { \r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_CONVERSION, defaultConversion);\r\n }\r\n\r\n _curFieldDef = fieldDef;\r\n generate(template);\r\n _curFieldDef = null;\r\n }",
"public void printInferredRelations(ClassDoc c) {\n\t// check if the source is excluded from inference\n\tif (hidden(c))\n\t return;\n\n\tOptions opt = optionProvider.getOptionsFor(c);\n\n\tfor (FieldDoc field : c.fields(false)) {\n\t if(hidden(field))\n\t\tcontinue;\n\t // skip statics\n\t if(field.isStatic())\n\t\tcontinue;\n\t // skip primitives\n\t FieldRelationInfo fri = getFieldRelationInfo(field);\n\t if (fri == null)\n\t\tcontinue;\n\t // check if the destination is excluded from inference\n\t if (hidden(fri.cd))\n\t\tcontinue;\n\n\t // if source and dest are not already linked, add a dependency\n\t RelationPattern rp = getClassInfo(c, true).getRelation(fri.cd.toString());\n\t if (rp == null) {\n\t\tString destAdornment = fri.multiple ? \"*\" : \"\";\n\t\trelation(opt, opt.inferRelationshipType, c, fri.cd, \"\", \"\", destAdornment);\n }\n\t}\n }",
"public static InputStream toStream(String content, Charset charset) {\n byte[] bytes = content.getBytes(charset);\n return new ByteArrayInputStream(bytes);\n }"
] |
This method permanently removes a webhook. Note that it may be possible
to receive a request that was already in flight after deleting the
webhook, but no further requests will be issued.
@param webhook The webhook to delete.
@return Request object | [
"public ItemRequest<Webhook> deleteById(String webhook) {\n \n String path = String.format(\"/webhooks/%s\", webhook);\n return new ItemRequest<Webhook>(this, Webhook.class, path, \"DELETE\");\n }"
] | [
"public static ModelNode createBootUpdates(final String serverName, final ModelNode domainModel, final ModelNode hostModel,\n final DomainController domainController, final ExpressionResolver expressionResolver) {\n final ManagedServerOperationsFactory factory = new ManagedServerOperationsFactory(serverName, domainModel,\n hostModel, domainController, expressionResolver);\n\n\n return factory.getBootUpdates();\n }",
"public ItemRequest<Story> delete(String story) {\n \n String path = String.format(\"/stories/%s\", story);\n return new ItemRequest<Story>(this, Story.class, path, \"DELETE\");\n }",
"private String formatRelationList(List<Relation> value)\n {\n String result = null;\n\n if (value != null && value.size() != 0)\n {\n StringBuilder sb = new StringBuilder();\n for (Relation relation : value)\n {\n if (sb.length() != 0)\n {\n sb.append(m_delimiter);\n }\n\n sb.append(formatRelation(relation));\n }\n\n result = sb.toString();\n }\n\n return (result);\n }",
"public static sslglobal_sslpolicy_binding[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tsslglobal_sslpolicy_binding obj = new sslglobal_sslpolicy_binding();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tsslglobal_sslpolicy_binding[] response = (sslglobal_sslpolicy_binding[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}",
"public AT_Row setPaddingTop(int paddingTop) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingTop(paddingTop);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public static int cudnnConvolutionBackwardBias(\n cudnnHandle handle, \n Pointer alpha, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n Pointer beta, \n cudnnTensorDescriptor dbDesc, \n Pointer db)\n {\n return checkResult(cudnnConvolutionBackwardBiasNative(handle, alpha, dyDesc, dy, beta, dbDesc, db));\n }",
"public static <T> T buildInstanceForMap(Class<T> clazz, Map<String, Object> values)\n throws InstantiationException, IllegalAccessException, IntrospectionException,\n IllegalArgumentException, InvocationTargetException {\n return buildInstanceForMap(clazz, values, new MyDefaultReflectionDifferenceHandler());\n }",
"public void openReport(String newState, A_CmsReportThread thread, String label) {\n\n setReport(newState, thread);\n m_labels.put(thread, label);\n openSubView(newState, true);\n }",
"private long getTotalUploadSize() throws IOException {\n long size = 0;\n for (Map.Entry<String, File> entry : files.entrySet()) {\n size += entry.getValue().length();\n }\n\n for (Map.Entry<String, InputStream> entry : fileStreams.entrySet()) {\n size += entry.getValue().available();\n }\n return size;\n }"
] |
Use this API to delete nsip6 resources. | [
"public static base_responses delete(nitro_service client, nsip6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsip6 deleteresources[] = new nsip6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new nsip6();\n\t\t\t\tdeleteresources[i].ipv6address = resources[i].ipv6address;\n\t\t\t\tdeleteresources[i].td = resources[i].td;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}"
] | [
"public static CharSequence getAt(CharSequence text, IntRange range) {\n return getAt(text, (Range) range);\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 static Object getParam(final Object param) {\n\t\tfinal StringBuilder sb = new StringBuilder();\n\t\tif(param instanceof String){\n\t\t\tsb.append(\"'\");\n\t\t\tsb.append((String)param);\n\t\t\tsb.append(\"'\");\n\t\t}\n\t\telse if(param instanceof Boolean){\n\t\t\tsb.append(String.valueOf((Boolean)param));\t\t\t\n\t\t}\n else if(param instanceof Integer){\n sb.append(String.valueOf((Integer)param));\n }\n else if(param instanceof DBRegExp){\n sb.append('/');\n sb.append(((DBRegExp) param).toString());\n sb.append('/');\n }\n\t\t\n\t\treturn sb.toString();\n\t}",
"public int removeChildObjectsByName(final String name) {\n int removed = 0;\n\n if (null != name && !name.isEmpty()) {\n removed = removeChildObjectsByNameImpl(name);\n }\n\n return removed;\n }",
"public int getPropertyId(@NotNull final PersistentStoreTransaction txn, @NotNull final String propertyName, final boolean allowCreate) {\n return allowCreate ? propertyIds.getOrAllocateId(txn, propertyName) : propertyIds.getId(txn, propertyName);\n }",
"public static base_response update(nitro_service client, route6 resource) throws Exception {\n\t\troute6 updateresource = new route6();\n\t\tupdateresource.network = resource.network;\n\t\tupdateresource.gateway = resource.gateway;\n\t\tupdateresource.vlan = resource.vlan;\n\t\tupdateresource.weight = resource.weight;\n\t\tupdateresource.distance = resource.distance;\n\t\tupdateresource.cost = resource.cost;\n\t\tupdateresource.advertise = resource.advertise;\n\t\tupdateresource.msr = resource.msr;\n\t\tupdateresource.monitor = resource.monitor;\n\t\tupdateresource.td = resource.td;\n\t\treturn updateresource.update_resource(client);\n\t}",
"private void readContents(int maxFrames) {\n // Read GIF file content blocks.\n boolean done = false;\n while (!(done || err() || header.frameCount > maxFrames)) {\n int code = read();\n switch (code) {\n // Image separator.\n case 0x2C:\n // The graphics control extension is optional, but will always come first if it exists.\n // If one did\n // exist, there will be a non-null current frame which we should use. However if one\n // did not exist,\n // the current frame will be null and we must create it here. See issue #134.\n if (header.currentFrame == null) {\n header.currentFrame = new GifFrame();\n }\n readBitmap();\n break;\n // Extension.\n case 0x21:\n code = read();\n switch (code) {\n // Graphics control extension.\n case 0xf9:\n // Start a new frame.\n header.currentFrame = new GifFrame();\n readGraphicControlExt();\n break;\n // Application extension.\n case 0xff:\n readBlock();\n String app = \"\";\n for (int i = 0; i < 11; i++) {\n app += (char) block[i];\n }\n if (app.equals(\"NETSCAPE2.0\")) {\n readNetscapeExt();\n } else {\n // Don't care.\n skip();\n }\n break;\n // Comment extension.\n case 0xfe:\n skip();\n break;\n // Plain text extension.\n case 0x01:\n skip();\n break;\n // Uninteresting extension.\n default:\n skip();\n }\n break;\n // Terminator.\n case 0x3b:\n done = true;\n break;\n // Bad byte, but keep going and see what happens break;\n case 0x00:\n default:\n header.status = GifDecoder.STATUS_FORMAT_ERROR;\n }\n }\n }",
"public ParallelTask getTaskFromInProgressMap(String jobId) {\n if (!inprogressTaskMap.containsKey(jobId))\n return null;\n return inprogressTaskMap.get(jobId);\n }",
"public static String convertToFileSystemChar(String name) {\n String erg = \"\";\n Matcher m = Pattern.compile(\"[a-z0-9 _#&@\\\\[\\\\(\\\\)\\\\]\\\\-\\\\.]\", Pattern.CASE_INSENSITIVE).matcher(name);\n while (m.find()) {\n erg += name.substring(m.start(), m.end());\n }\n if (erg.length() > 200) {\n erg = erg.substring(0, 200);\n System.out.println(\"cut filename: \" + erg);\n }\n return erg;\n }"
] |
Populate the properties indicating the source of this schedule.
@param properties project properties | [
"private void updateScheduleSource(ProjectProperties properties)\n {\n // Rudimentary identification of schedule source\n if (properties.getCompany() != null && properties.getCompany().equals(\"Synchro Software Ltd\"))\n {\n properties.setFileApplication(\"Synchro\");\n }\n else\n {\n if (properties.getAuthor() != null && properties.getAuthor().equals(\"SG Project\"))\n {\n properties.setFileApplication(\"Simple Genius\");\n }\n else\n {\n properties.setFileApplication(\"Microsoft\");\n }\n }\n properties.setFileType(\"MSPDI\");\n }"
] | [
"public static final Date getTime(byte[] data, int offset)\n {\n int time = getShort(data, offset) / 10;\n Calendar cal = DateHelper.popCalendar(EPOCH_DATE);\n cal.set(Calendar.HOUR_OF_DAY, (time / 60));\n cal.set(Calendar.MINUTE, (time % 60));\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MILLISECOND, 0);\n DateHelper.pushCalendar(cal);\n return (cal.getTime());\n }",
"public void removeEntity(GraphDatabaseService executionEngine, Object[] columnValues) {\n\t\tMap<String, Object> params = params( columnValues );\n\t\texecutionEngine.execute( getRemoveEntityQuery(), params );\n\t}",
"public static void startMockJadexAgent(String agent_name,\n String agent_path, MockConfiguration configuration,\n BeastTestCase story) {\n\n story.startAgent(agent_name, agent_path);\n story.sendMessageToAgent(agent_name, SFipa.INFORM, configuration);\n story.setExecutionTime(2000); // To get time to execute the DF rename goal\n }",
"private static Version getDockerVersion(String serverUrl) {\n try {\n DockerClient client = DockerClientBuilder.getInstance(serverUrl).build();\n return client.versionCmd().exec();\n } catch (Exception e) {\n return null;\n }\n }",
"final void end() {\n final Thread thread = this.threadRef;\n this.keepRunning.set(false);\n if (thread != null) {\n // thread.interrupt();\n try {\n thread.join();\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n }\n this.threadRef = null;\n }",
"public static Session getSession(final ServerSetup setup, Properties mailProps) {\r\n Properties props = setup.configureJavaMailSessionProperties(mailProps, false);\r\n\r\n log.debug(\"Mail session properties are {}\", props);\r\n\r\n return Session.getInstance(props, null);\r\n }",
"private void populateDateTimeSettings(Record record, ProjectProperties properties)\n {\n properties.setDateOrder(record.getDateOrder(0));\n properties.setTimeFormat(record.getTimeFormat(1));\n\n Date time = getTimeFromInteger(record.getInteger(2));\n if (time != null)\n {\n properties.setDefaultStartTime(time);\n }\n\n Character c = record.getCharacter(3);\n if (c != null)\n {\n properties.setDateSeparator(c.charValue());\n }\n\n c = record.getCharacter(4);\n if (c != null)\n {\n properties.setTimeSeparator(c.charValue());\n }\n\n properties.setAMText(record.getString(5));\n properties.setPMText(record.getString(6));\n properties.setDateFormat(record.getDateFormat(7));\n properties.setBarTextDateFormat(record.getDateFormat(8));\n }",
"public static ServiceController<InstallationManager> installService(ServiceTarget serviceTarget) {\n final InstallationManagerService service = new InstallationManagerService();\n return serviceTarget.addService(InstallationManagerService.NAME, service)\n .addDependency(JBOSS_PRODUCT_CONFIG_SERVICE, ProductConfig.class, service.productConfig)\n .setInitialMode(ServiceController.Mode.ACTIVE)\n .install();\n }",
"@Override\n protected void onDataChanged() {\n super.onDataChanged();\n\n int currentAngle = 0;\n int index = 0;\n int size = mPieData.size();\n\n for (PieModel model : mPieData) {\n int endAngle = (int) (currentAngle + model.getValue() * 360.f / mTotalValue);\n if(index == size-1) {\n endAngle = 360;\n }\n\n model.setStartAngle(currentAngle);\n model.setEndAngle(endAngle);\n currentAngle = model.getEndAngle();\n index++;\n }\n calcCurrentItem();\n onScrollFinished();\n }"
] |
Gets a static resource from a plugin
@param pluginName - Name of the plugin(defined in the plugin manifest)
@param fileName - Filename to fetch
@return byte array of the resource
@throws Exception exception | [
"public byte[] getResource(String pluginName, String fileName) throws Exception {\n // TODO: This is going to be slow.. future improvement is to cache the data instead of searching all jars\n for (String jarFilename : jarInformation) {\n JarFile jarFile = new JarFile(new File(jarFilename));\n Enumeration<?> enumer = jarFile.entries();\n\n // Use the Plugin-Name manifest entry to match with the provided pluginName\n String jarPluginName = jarFile.getManifest().getMainAttributes().getValue(\"Plugin-Name\");\n\n if (!jarPluginName.equals(pluginName)) {\n continue;\n }\n\n while (enumer.hasMoreElements()) {\n Object element = enumer.nextElement();\n String elementName = element.toString();\n\n // Skip items in the jar that don't start with \"resources/\"\n if (!elementName.startsWith(\"resources/\")) {\n continue;\n }\n\n elementName = elementName.replace(\"resources/\", \"\");\n if (elementName.equals(fileName)) {\n // get the file from the jar\n ZipEntry ze = jarFile.getEntry(element.toString());\n\n InputStream fileStream = jarFile.getInputStream(ze);\n byte[] data = new byte[(int) ze.getSize()];\n DataInputStream dataIs = new DataInputStream(fileStream);\n dataIs.readFully(data);\n dataIs.close();\n return data;\n }\n }\n }\n throw new FileNotFoundException(\"Could not find resource\");\n }"
] | [
"private void readAvailabilityTable(Resource resource, AvailabilityPeriods periods)\n {\n if (periods != null)\n {\n AvailabilityTable table = resource.getAvailability();\n List<AvailabilityPeriod> list = periods.getAvailabilityPeriod();\n for (AvailabilityPeriod period : list)\n {\n Date start = period.getAvailableFrom();\n Date end = period.getAvailableTo();\n Number units = DatatypeConverter.parseUnits(period.getAvailableUnits());\n Availability availability = new Availability(start, end, units);\n table.add(availability);\n }\n Collections.sort(table);\n }\n }",
"private void writeCalendars(List<ProjectCalendar> records)\n {\n\n //\n // Write project calendars\n //\n for (ProjectCalendar record : records)\n {\n m_buffer.setLength(0);\n m_buffer.append(\"CLDR \");\n m_buffer.append(SDEFmethods.lset(record.getUniqueID().toString(), 2)); // 2 character used, USACE allows 1\n String workDays = SDEFmethods.workDays(record); // custom line, like NYYYYYN for a week\n m_buffer.append(SDEFmethods.lset(workDays, 8));\n m_buffer.append(SDEFmethods.lset(record.getName(), 30));\n m_writer.println(m_buffer);\n }\n }",
"protected void processTaskBaseline(Row row)\n {\n Integer id = row.getInteger(\"TASK_UID\");\n Task task = m_project.getTaskByUniqueID(id);\n if (task != null)\n {\n int index = row.getInt(\"TB_BASE_NUM\");\n\n task.setBaselineDuration(index, MPDUtility.getAdjustedDuration(m_project, row.getInt(\"TB_BASE_DUR\"), MPDUtility.getDurationTimeUnits(row.getInt(\"TB_BASE_DUR_FMT\"))));\n task.setBaselineStart(index, row.getDate(\"TB_BASE_START\"));\n task.setBaselineFinish(index, row.getDate(\"TB_BASE_FINISH\"));\n task.setBaselineWork(index, row.getDuration(\"TB_BASE_WORK\"));\n task.setBaselineCost(index, row.getCurrency(\"TB_BASE_COST\"));\n }\n }",
"public Object getBean(String name) {\n\t\tBean bean = beans.get(name);\n\t\tif (null == bean) {\n\t\t\treturn null;\n\t\t}\n\t\treturn bean.object;\n\t}",
"public DomainList getPhotosetDomains(Date date, String photosetId, int perPage, int page) throws FlickrException {\n return getDomains(METHOD_GET_PHOTOSET_DOMAINS, \"photoset_id\", photosetId, date, perPage, page);\n }",
"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 }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<AccountingDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<AccountingDate>) super.localDateTime(temporal);\n }",
"private void readResources(Document cdp)\n {\n for (Document.Resources.Resource resource : cdp.getResources().getResource())\n {\n readResource(resource);\n }\n }",
"public synchronized void insert(long data) {\n resetIfNeeded();\n long index = 0;\n if(data >= this.upperBound) {\n index = nBuckets - 1;\n } else if(data < 0) {\n logger.error(data + \" can't be bucketed because it is negative!\");\n return;\n } else {\n index = data / step;\n }\n if(index < 0 || index >= nBuckets) {\n // This should be dead code. Defending against code changes in\n // future.\n logger.error(data + \" can't be bucketed because index is not in range [0,nBuckets).\");\n return;\n }\n buckets[(int) index]++;\n sum += data;\n size++;\n }"
] |
common utility method for adding a statement to a record | [
"private void addStatement(RecordImpl record,\n String subject,\n String property,\n String object) {\n Collection<Column> cols = columns.get(property);\n if (cols == null) {\n if (property.equals(RDF_TYPE) && !types.isEmpty())\n addValue(record, subject, property, object);\n return;\n }\n \n for (Column col : cols) {\n String cleaned = object;\n if (col.getCleaner() != null)\n cleaned = col.getCleaner().clean(object);\n if (cleaned != null && !cleaned.equals(\"\"))\n addValue(record, subject, col.getProperty(), cleaned);\n }\n }"
] | [
"public static base_response add(nitro_service client, route6 resource) throws Exception {\n\t\troute6 addresource = new route6();\n\t\taddresource.network = resource.network;\n\t\taddresource.gateway = resource.gateway;\n\t\taddresource.vlan = resource.vlan;\n\t\taddresource.weight = resource.weight;\n\t\taddresource.distance = resource.distance;\n\t\taddresource.cost = resource.cost;\n\t\taddresource.advertise = resource.advertise;\n\t\taddresource.msr = resource.msr;\n\t\taddresource.monitor = resource.monitor;\n\t\taddresource.td = resource.td;\n\t\treturn addresource.add_resource(client);\n\t}",
"private static int weekRange(int weekBasedYear) {\n LocalDate date = LocalDate.of(weekBasedYear, 1, 1);\n // 53 weeks if year starts on Thursday, or Wed in a leap year\n if (date.getDayOfWeek() == THURSDAY || (date.getDayOfWeek() == WEDNESDAY && date.isLeapYear())) {\n return 53;\n }\n return 52;\n }",
"private void highlightSlice(PieModel _Slice) {\n\n int color = _Slice.getColor();\n _Slice.setHighlightedColor(Color.argb(\n 0xff,\n Math.min((int) (mHighlightStrength * (float) Color.red(color)), 0xff),\n Math.min((int) (mHighlightStrength * (float) Color.green(color)), 0xff),\n Math.min((int) (mHighlightStrength * (float) Color.blue(color)), 0xff)\n ));\n }",
"private void addCheckBox(Date date, boolean checkState) {\n\n CmsCheckBox cb = generateCheckBox(date, checkState);\n m_checkBoxes.add(cb);\n reInitLayoutElements();\n\n }",
"@SuppressWarnings(\"unchecked\")\n public Map<BsonValue, ChangeEvent<BsonDocument>> getEvents() {\n nsLock.readLock().lock();\n final Map<BsonValue, ChangeEvent<BsonDocument>> events;\n try {\n events = new HashMap<>(this.events);\n } finally {\n nsLock.readLock().unlock();\n }\n\n nsLock.writeLock().lock();\n try {\n this.events.clear();\n return events;\n } finally {\n nsLock.writeLock().unlock();\n }\n }",
"public static nsfeature get(nitro_service service) throws Exception{\n\t\tnsfeature obj = new nsfeature();\n\t\tnsfeature[] response = (nsfeature[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public static final Long date2utc(Date date) {\n\n // use null for a null date\n if (date == null) return null;\n \n long time = date.getTime();\n \n // remove the timezone offset \n time -= timezoneOffsetMillis(date);\n \n return time;\n }",
"private boolean isSecuredByProperty(Server server) {\n boolean isSecured = false;\n Object value = server.getEndpoint().get(\"org.talend.tesb.endpoint.secured\"); //Property name TBD\n\n if (value instanceof String) {\n try {\n isSecured = Boolean.valueOf((String) value);\n } catch (Exception ex) {\n }\n }\n\n return isSecured;\n }",
"public String toStringByValue() {\r\n\tIntArrayList theKeys = new IntArrayList();\r\n\tkeysSortedByValue(theKeys);\r\n\r\n\tStringBuffer buf = new StringBuffer();\r\n\tbuf.append(\"[\");\r\n\tint maxIndex = theKeys.size() - 1;\r\n\tfor (int i = 0; i <= maxIndex; i++) {\r\n\t\tint key = theKeys.get(i);\r\n\t buf.append(String.valueOf(key));\r\n\t\tbuf.append(\"->\");\r\n\t buf.append(String.valueOf(get(key)));\r\n\t\tif (i < maxIndex) buf.append(\", \");\r\n\t}\r\n\tbuf.append(\"]\");\r\n\treturn buf.toString();\r\n}"
] |
Add server redirect to a profile, using current active ServerGroup
@param region region
@param srcUrl source URL
@param destUrl destination URL
@param hostHeader host header
@param profileId profile ID
@return ID of added ServerRedirect
@throws Exception exception | [
"public int addServerRedirectToProfile(String region, String srcUrl, String destUrl, String hostHeader,\n int profileId, int clientId) throws Exception {\n int serverId = -1;\n\n try {\n Client client = ClientService.getInstance().getClient(clientId);\n serverId = addServerRedirect(region, srcUrl, destUrl, hostHeader, profileId, client.getActiveServerGroup());\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return serverId;\n }"
] | [
"private CostRateTableEntry getCostRateTableEntry(Date date)\n {\n CostRateTableEntry result;\n\n CostRateTable table = getCostRateTable();\n if (table == null)\n {\n Resource resource = getResource();\n result = new CostRateTableEntry(resource.getStandardRate(), TimeUnit.HOURS, resource.getOvertimeRate(), TimeUnit.HOURS, resource.getCostPerUse(), null);\n }\n else\n {\n if (table.size() == 1)\n {\n result = table.get(0);\n }\n else\n {\n result = table.getEntryByDate(date);\n }\n }\n\n return result;\n }",
"public static String determineMutatorName(@Nonnull final String fieldName) {\n\t\tCheck.notEmpty(fieldName, \"fieldName\");\n\t\tfinal Matcher m = PATTERN.matcher(fieldName);\n\t\tCheck.stateIsTrue(m.find(), \"passed field name '%s' is not applicable\", fieldName);\n\t\tfinal String name = m.group();\n\t\treturn METHOD_SET_PREFIX + name.substring(0, 1).toUpperCase() + name.substring(1);\n\t}",
"private void performDynamicStep() {\n // initially look for singular values of zero\n if( findingZeros ) {\n if( steps > 6 ) {\n findingZeros = false;\n } else {\n double scale = computeBulgeScale();\n performImplicitSingleStep(scale,0,false);\n }\n } else {\n // For very large and very small numbers the only way to prevent overflow/underflow\n // is to have a common scale between the wilkinson shift and the implicit single step\n // What happens if you don't is that when the wilkinson shift returns the value it\n // computed it multiplies it by the scale twice, which will cause an overflow\n double scale = computeBulgeScale();\n // use the wilkinson shift to perform a step\n double lambda = selectWilkinsonShift(scale);\n\n performImplicitSingleStep(scale,lambda,false);\n }\n }",
"public static IndexableTaskItem create(final FunctionalTaskItem taskItem) {\n return new IndexableTaskItem() {\n @Override\n protected Observable<Indexable> invokeTaskAsync(TaskGroup.InvocationContext context) {\n FunctionalTaskItem.Context fContext = new FunctionalTaskItem.Context(this);\n fContext.setInnerContext(context);\n return taskItem.call(fContext);\n }\n };\n }",
"public ItemRequest<Task> update(String task) {\n \n String path = String.format(\"/tasks/%s\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"PUT\");\n }",
"public static DMatrixRMaj convert(DMatrixRBlock src , DMatrixRMaj dst )\n {\n return ConvertDMatrixStruct.convert(src,dst);\n }",
"public void remove( Token token ) {\n if( token == first ) {\n first = first.next;\n }\n if( token == last ) {\n last = last.previous;\n }\n if( token.next != null ) {\n token.next.previous = token.previous;\n }\n if( token.previous != null ) {\n token.previous.next = token.next;\n }\n\n token.next = token.previous = null;\n size--;\n }",
"private String getDynamicAttributeValue(\n CmsFile file,\n I_CmsXmlContentValue value,\n String attributeName,\n CmsEntity editedLocalEntity) {\n\n if ((null != editedLocalEntity) && (editedLocalEntity.getAttribute(attributeName) != null)) {\n getSessionCache().setDynamicValue(\n attributeName,\n editedLocalEntity.getAttribute(attributeName).getSimpleValue());\n }\n String currentValue = getSessionCache().getDynamicValue(attributeName);\n if (null != currentValue) {\n return currentValue;\n }\n if (null != file) {\n if (value.getTypeName().equals(CmsXmlDynamicCategoryValue.TYPE_NAME)) {\n List<CmsCategory> categories = new ArrayList<CmsCategory>(0);\n try {\n categories = CmsCategoryService.getInstance().readResourceCategories(getCmsObject(), file);\n } catch (CmsException e) {\n LOG.error(Messages.get().getBundle().key(Messages.ERROR_FAILED_READING_CATEGORIES_1), e);\n }\n I_CmsWidget widget = null;\n widget = CmsWidgetUtil.collectWidgetInfo(value).getWidget();\n if ((null != widget) && (widget instanceof CmsCategoryWidget)) {\n String mainCategoryPath = ((CmsCategoryWidget)widget).getStartingCategory(\n getCmsObject(),\n getCmsObject().getSitePath(file));\n StringBuffer pathes = new StringBuffer();\n for (CmsCategory category : categories) {\n if (category.getPath().startsWith(mainCategoryPath)) {\n String path = category.getBasePath() + category.getPath();\n path = getCmsObject().getRequestContext().removeSiteRoot(path);\n pathes.append(path).append(',');\n }\n }\n String dynamicConfigString = pathes.length() > 0 ? pathes.substring(0, pathes.length() - 1) : \"\";\n getSessionCache().setDynamicValue(attributeName, dynamicConfigString);\n return dynamicConfigString;\n }\n }\n }\n return \"\";\n\n }",
"private static EndpointReferenceType createEPR(Server server, String address, SLProperties props) {\n EndpointReferenceType sourceEPR = server.getEndpoint().getEndpointInfo().getTarget();\n EndpointReferenceType targetEPR = WSAEndpointReferenceUtils.duplicate(sourceEPR);\n WSAEndpointReferenceUtils.setAddress(targetEPR, address);\n\n if (props != null) {\n addProperties(targetEPR, props);\n }\n return targetEPR;\n }"
] |
Constructs the convex hull of a set of points whose coordinates are given
by an array of doubles.
@param coords
x, y, and z coordinates of each input point. The length of
this array must be at least three times <code>nump</code>.
@param nump
number of input points
@throws IllegalArgumentException
the number of input points is less than four or greater than
1/3 the length of <code>coords</code>, or the points appear
to be coincident, colinear, or coplanar. | [
"public void build(double[] coords, int nump) throws IllegalArgumentException {\n if (nump < 4) {\n throw new IllegalArgumentException(\"Less than four input points specified\");\n }\n if (coords.length / 3 < nump) {\n throw new IllegalArgumentException(\"Coordinate array too small for specified number of points\");\n }\n initBuffers(nump);\n setPoints(coords, nump);\n buildHull();\n }"
] | [
"public void openReport(String newState, A_CmsReportThread thread, String label) {\n\n setReport(newState, thread);\n m_labels.put(thread, label);\n openSubView(newState, true);\n }",
"public void set(String name, Object value) {\n hashAttributes.put(name, value);\n\n if (plugin != null) {\n plugin.invalidate();\n }\n }",
"public Map getPathClasses()\r\n\t{\r\n\t\tif (m_pathClasses.isEmpty())\r\n\t\t{\r\n\t\t\tif (m_parentCriteria == null)\r\n\t\t\t{\r\n\t\t\t\tif (m_query == null)\r\n\t\t\t\t{\r\n\t\t\t\t\treturn m_pathClasses;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\treturn m_query.getPathClasses();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\treturn m_parentCriteria.getPathClasses();\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn m_pathClasses;\r\n\t\t}\r\n\t}",
"public <T> Method getSetMethod(final Object object, final String fieldName, final Class<?> argumentType) {\n\t\tif( object == null ) {\n\t\t\tthrow new NullPointerException(\"object should not be null\");\n\t\t} else if( fieldName == null ) {\n\t\t\tthrow new NullPointerException(\"fieldName should not be null\");\n\t\t} else if( argumentType == null ) {\n\t\t\tthrow new NullPointerException(\"argumentType should not be null\");\n\t\t}\n\t\t\n\t\tMethod method = setMethodsCache.get(object.getClass(), argumentType, fieldName);\n\t\tif( method == null ) {\n\t\t\tmethod = ReflectionUtils.findSetter(object, fieldName, argumentType);\n\t\t\tsetMethodsCache.set(object.getClass(), argumentType, fieldName, method);\n\t\t}\n\t\treturn method;\n\t}",
"public static boolean isFloat(CharSequence self) {\n try {\n Float.valueOf(self.toString().trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n }",
"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 }",
"public void abortExternalTx(TransactionImpl odmgTrans)\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"abortExternTransaction was called\");\r\n if (odmgTrans == null) return;\r\n TxBuffer buf = (TxBuffer) txRepository.get();\r\n Transaction extTx = buf != null ? buf.getExternTx() : null;\r\n try\r\n {\r\n if (extTx != null && extTx.getStatus() == Status.STATUS_ACTIVE)\r\n {\r\n if(log.isDebugEnabled())\r\n {\r\n log.debug(\"Set extern transaction to rollback\");\r\n }\r\n extTx.setRollbackOnly();\r\n }\r\n }\r\n catch (Exception ignore)\r\n {\r\n }\r\n txRepository.set(null);\r\n }",
"public static void unregisterMbean(MBeanServer server, ObjectName name) {\n try {\n server.unregisterMBean(name);\n } catch(Exception e) {\n logger.error(\"Error unregistering mbean\", e);\n }\n }",
"public BoxFile.Info commit(String digest, List<BoxFileUploadSessionPart> parts,\n Map<String, String> attributes, String ifMatch, String ifNoneMatch) {\n\n URL commitURL = this.sessionInfo.getSessionEndpoints().getCommitEndpoint();\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), commitURL, HttpMethod.POST);\n request.addHeader(HttpHeaders.DIGEST, DIGEST_HEADER_PREFIX_SHA + digest);\n request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON);\n\n if (ifMatch != null) {\n request.addHeader(HttpHeaders.IF_MATCH, ifMatch);\n }\n\n if (ifNoneMatch != null) {\n request.addHeader(HttpHeaders.IF_NONE_MATCH, ifNoneMatch);\n }\n\n //Creates the body of the request\n String body = this.getCommitBody(parts, attributes);\n request.setBody(body);\n\n BoxAPIResponse response = request.send();\n //Retry the commit operation after the given number of seconds if the HTTP response code is 202.\n if (response.getResponseCode() == 202) {\n String retryInterval = response.getHeaderField(\"retry-after\");\n if (retryInterval != null) {\n try {\n Thread.sleep(new Integer(retryInterval) * 1000);\n } catch (InterruptedException ie) {\n throw new BoxAPIException(\"Commit retry failed. \", ie);\n }\n\n return this.commit(digest, parts, attributes, ifMatch, ifNoneMatch);\n }\n }\n\n if (response instanceof BoxJSONResponse) {\n //Create the file instance from the response\n return this.getFile((BoxJSONResponse) response);\n } else {\n throw new BoxAPIException(\"Commit response content type is not application/json. The response code : \"\n + response.getResponseCode());\n }\n }"
] |
Runs a Story with the given configuration and steps, applying the given
meta filter, and staring from given state.
@param configuration the Configuration used to run story
@param candidateSteps the List of CandidateSteps containing the candidate
steps methods
@param story the Story to run
@param filter the Filter to apply to the story Meta
@param beforeStories the State before running any of the stories, if not
<code>null</code>
@throws Throwable if failures occurred and FailureStrategy dictates it to
be re-thrown. | [
"public void run(Configuration configuration, List<CandidateSteps> candidateSteps, Story story, MetaFilter filter,\n State beforeStories) throws Throwable {\n run(configuration, new ProvidedStepsFactory(candidateSteps), story, filter, beforeStories);\n }"
] | [
"protected void validateRIBean(CommonBean<?> bean, BeanManagerImpl beanManager, Collection<CommonBean<?>> specializedBeans) {\n validateGeneralBean(bean, beanManager);\n if (bean instanceof NewBean) {\n return;\n }\n if (bean instanceof DecorableBean) {\n validateDecorators(beanManager, (DecorableBean<?>) bean);\n }\n if ((bean instanceof AbstractClassBean<?>)) {\n AbstractClassBean<?> classBean = (AbstractClassBean<?>) bean;\n // validate CDI-defined interceptors\n if (classBean.hasInterceptors()) {\n validateInterceptors(beanManager, classBean);\n }\n }\n // for each producer bean validate its disposer method\n if (bean instanceof AbstractProducerBean<?, ?, ?>) {\n AbstractProducerBean<?, ?, ?> producerBean = Reflections.<AbstractProducerBean<?, ?, ?>> cast(bean);\n if (producerBean.getProducer() instanceof AbstractMemberProducer<?, ?>) {\n AbstractMemberProducer<?, ?> producer = Reflections.<AbstractMemberProducer<?, ?>> cast(producerBean\n .getProducer());\n if (producer.getDisposalMethod() != null) {\n for (InjectionPoint ip : producer.getDisposalMethod().getInjectionPoints()) {\n // pass the producer bean instead of the disposal method bean\n validateInjectionPointForDefinitionErrors(ip, null, beanManager);\n validateMetadataInjectionPoint(ip, null, ValidatorLogger.INJECTION_INTO_DISPOSER_METHOD);\n validateEventMetadataInjectionPoint(ip);\n validateInjectionPointForDeploymentProblems(ip, null, beanManager);\n }\n }\n }\n }\n }",
"private void executeResult() throws Exception {\n\t\tresult = createResult();\n\n\t\tString timerKey = \"executeResult: \" + getResultCode();\n\t\ttry {\n\t\t\tUtilTimerStack.push(timerKey);\n\t\t\tif (result != null) {\n\t\t\t\tresult.execute(this);\n\t\t\t} else if (resultCode != null && !Action.NONE.equals(resultCode)) {\n\t\t\t\tthrow new ConfigurationException(\"No result defined for action \" + getAction().getClass().getName()\n\t\t\t\t\t\t+ \" and result \" + getResultCode(), proxy.getConfig());\n\t\t\t} else {\n\t\t\t\tif (LOG.isDebugEnabled()) {\n\t\t\t\t\tLOG.debug(\"No result returned for action \" + getAction().getClass().getName() + \" at \"\n\t\t\t\t\t\t\t+ proxy.getConfig().getLocation());\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tUtilTimerStack.pop(timerKey);\n\t\t}\n\t}",
"public int getNumWeights() {\r\n if (weights == null) return 0;\r\n int numWeights = 0;\r\n for (double[] wts : weights) {\r\n numWeights += wts.length;\r\n }\r\n return numWeights;\r\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 Build getBuildInfo(String appName, String buildId) {\n return connection.execute(new BuildInfo(appName, buildId), apiKey);\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 String buildRadio(String propName) throws CmsException {\n\n String propVal = readProperty(propName);\n StringBuffer result = new StringBuffer(\"<table border=\\\"0\\\"><tr>\");\n result.append(\"<td><input type=\\\"radio\\\" value=\\\"true\\\" onClick=\\\"checkNoIntern()\\\" name=\\\"\").append(\n propName).append(\"\\\" \").append(Boolean.valueOf(propVal).booleanValue() ? \"checked=\\\"checked\\\"\" : \"\").append(\n \"/></td><td id=\\\"tablelabel\\\">\").append(key(Messages.GUI_LABEL_TRUE_0)).append(\"</td>\");\n result.append(\"<td><input type=\\\"radio\\\" value=\\\"false\\\" onClick=\\\"checkNoIntern()\\\" name=\\\"\").append(\n propName).append(\"\\\" \").append(Boolean.valueOf(propVal).booleanValue() ? \"\" : \"checked=\\\"checked\\\"\").append(\n \"/></td><td id=\\\"tablelabel\\\">\").append(key(Messages.GUI_LABEL_FALSE_0)).append(\"</td>\");\n result.append(\"<td><input type=\\\"radio\\\" value=\\\"\\\" onClick=\\\"checkNoIntern()\\\" name=\\\"\").append(\n propName).append(\"\\\" \").append(CmsStringUtil.isEmpty(propVal) ? \"checked=\\\"checked\\\"\" : \"\").append(\n \"/></td><td id=\\\"tablelabel\\\">\").append(getPropertyInheritanceInfo(propName)).append(\n \"</td></tr></table>\");\n return result.toString();\n }",
"private void renameReadOnlyV2Files(int masterPartitionId, int correctReplicaType) {\n for (int replica = 0; replica < routingStrategy.getNumReplicas(); replica++) {\n if (replica != correctReplicaType) {\n int chunkId = 0;\n while (true) {\n String fileName = Integer.toString(masterPartitionId) + \"_\"\n + Integer.toString(replica) + \"_\"\n + Integer.toString(chunkId);\n File index = getIndexFile(fileName);\n File data = getDataFile(fileName);\n\n if(index.exists() && data.exists()) {\n // We found files with the \"wrong\" replica type, so let's rename them\n\n String correctFileName = Integer.toString(masterPartitionId) + \"_\"\n + Integer.toString(correctReplicaType) + \"_\"\n + Integer.toString(chunkId);\n File indexWithCorrectReplicaType = getIndexFile(correctFileName);\n File dataWithCorrectReplicaType = getDataFile(correctFileName);\n\n Utils.move(index, indexWithCorrectReplicaType);\n Utils.move(data, dataWithCorrectReplicaType);\n\n // Maybe change this to DEBUG?\n logger.info(\"Renamed files with wrong replica type: \"\n + index.getAbsolutePath() + \"|data -> \"\n + indexWithCorrectReplicaType.getName() + \"|data\");\n } else if(index.exists() ^ data.exists()) {\n throw new VoldemortException(\"One of the following does not exist: \"\n + index.toString()\n + \" or \"\n + data.toString() + \".\");\n } else {\n // The files don't exist, or we've gone over all available chunks,\n // so let's move on.\n break;\n }\n chunkId++;\n }\n }\n }\n }",
"private EndpointOverride getEndpointOverrideFromResultSet(ResultSet results) throws Exception {\n EndpointOverride endpoint = new EndpointOverride();\n endpoint.setPathId(results.getInt(Constants.GENERIC_ID));\n endpoint.setPath(results.getString(Constants.PATH_PROFILE_ACTUAL_PATH));\n endpoint.setBodyFilter(results.getString(Constants.PATH_PROFILE_BODY_FILTER));\n endpoint.setPathName(results.getString(Constants.PATH_PROFILE_PATHNAME));\n endpoint.setContentType(results.getString(Constants.PATH_PROFILE_CONTENT_TYPE));\n endpoint.setRequestType(results.getInt(Constants.PATH_PROFILE_REQUEST_TYPE));\n endpoint.setRepeatNumber(results.getInt(Constants.REQUEST_RESPONSE_REPEAT_NUMBER));\n endpoint.setGroupIds(results.getString(Constants.PATH_PROFILE_GROUP_IDS));\n endpoint.setRequestEnabled(results.getBoolean(Constants.REQUEST_RESPONSE_REQUEST_ENABLED));\n endpoint.setResponseEnabled(results.getBoolean(Constants.REQUEST_RESPONSE_RESPONSE_ENABLED));\n endpoint.setClientUUID(results.getString(Constants.GENERIC_CLIENT_UUID));\n endpoint.setProfileId(results.getInt(Constants.GENERIC_PROFILE_ID));\n endpoint.setGlobal(results.getBoolean(Constants.PATH_PROFILE_GLOBAL));\n return endpoint;\n }"
] |
Obtain the path ID for a profile
@param identifier Can be the path ID, or friendly name
@param profileId
@return
@throws Exception | [
"public static Integer convertPathIdentifier(String identifier, Integer profileId) throws Exception {\n Integer pathId = -1;\n try {\n pathId = Integer.parseInt(identifier);\n } catch (NumberFormatException ne) {\n // this is OK.. just means it's not a #\n if (profileId == null)\n throw new Exception(\"A profileId must be specified\");\n\n pathId = PathOverrideService.getInstance().getPathId(identifier, profileId);\n }\n\n return pathId;\n }"
] | [
"Map<Object, Object> getFilters() {\n\n Map<Object, Object> result = new HashMap<Object, Object>(4);\n result.put(TableProperty.KEY, m_table.getFilterFieldValue(TableProperty.KEY));\n result.put(TableProperty.DEFAULT, m_table.getFilterFieldValue(TableProperty.DEFAULT));\n result.put(TableProperty.DESCRIPTION, m_table.getFilterFieldValue(TableProperty.DESCRIPTION));\n result.put(TableProperty.TRANSLATION, m_table.getFilterFieldValue(TableProperty.TRANSLATION));\n return result;\n }",
"public static <T> T[] concat(T firstElement, T... array) {\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tT[] result = (T[]) Array.newInstance( firstElement.getClass(), 1 + array.length );\n\t\tresult[0] = firstElement;\n\t\tSystem.arraycopy( array, 0, result, 1, array.length );\n\n\t\treturn result;\n\t}",
"private void processCalendarHours(ProjectCalendar calendar, Row row, int dayIndex)\n {\n Day day = Day.getInstance(dayIndex);\n boolean working = row.getInt(\"CD_WORKING\") != 0;\n calendar.setWorkingDay(day, working);\n if (working == true)\n {\n ProjectCalendarHours hours = calendar.addCalendarHours(day);\n\n Date start = row.getDate(\"CD_FROM_TIME1\");\n Date end = row.getDate(\"CD_TO_TIME1\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME2\");\n end = row.getDate(\"CD_TO_TIME2\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME3\");\n end = row.getDate(\"CD_TO_TIME3\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME4\");\n end = row.getDate(\"CD_TO_TIME4\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME5\");\n end = row.getDate(\"CD_TO_TIME5\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n }\n }",
"static Path resolvePath(final Path base, final String... paths) {\n return Paths.get(base.toString(), paths);\n }",
"private void initStoreDefinitions(Version storesXmlVersion) {\n if(this.storeDefinitionsStorageEngine == null) {\n throw new VoldemortException(\"The store definitions directory is empty\");\n }\n\n String allStoreDefinitions = \"<stores>\";\n Version finalStoresXmlVersion = null;\n if(storesXmlVersion != null) {\n finalStoresXmlVersion = storesXmlVersion;\n }\n this.storeNames.clear();\n\n ClosableIterator<Pair<String, Versioned<String>>> storesIterator = this.storeDefinitionsStorageEngine.entries();\n\n // Some test setups may result in duplicate entries for 'store' element.\n // Do the de-dup here\n Map<String, Versioned<String>> storeNameToDefMap = new HashMap<String, Versioned<String>>();\n Version maxVersion = null;\n while(storesIterator.hasNext()) {\n Pair<String, Versioned<String>> storeDetail = storesIterator.next();\n String storeName = storeDetail.getFirst();\n Versioned<String> versionedStoreDef = storeDetail.getSecond();\n storeNameToDefMap.put(storeName, versionedStoreDef);\n Version curVersion = versionedStoreDef.getVersion();\n\n // Get the highest version from all the store entries\n if(maxVersion == null) {\n maxVersion = curVersion;\n } else if(maxVersion.compare(curVersion) == Occurred.BEFORE) {\n maxVersion = curVersion;\n }\n }\n\n // If the specified version is null, assign highest Version to\n // 'stores.xml' key\n if(finalStoresXmlVersion == null) {\n finalStoresXmlVersion = maxVersion;\n }\n\n // Go through all the individual stores and update metadata\n for(Entry<String, Versioned<String>> storeEntry: storeNameToDefMap.entrySet()) {\n String storeName = storeEntry.getKey();\n Versioned<String> versionedStoreDef = storeEntry.getValue();\n\n // Add all the store names to the list of storeNames\n this.storeNames.add(storeName);\n\n this.metadataCache.put(storeName, new Versioned<Object>(versionedStoreDef.getValue(),\n versionedStoreDef.getVersion()));\n }\n\n Collections.sort(this.storeNames);\n for(String storeName: this.storeNames) {\n Versioned<String> versionedStoreDef = storeNameToDefMap.get(storeName);\n // Stitch together to form the complete store definition list.\n allStoreDefinitions += versionedStoreDef.getValue();\n\n }\n\n allStoreDefinitions += \"</stores>\";\n\n // Update cache with the composite store definition list.\n metadataCache.put(STORES_KEY,\n convertStringToObject(STORES_KEY,\n new Versioned<String>(allStoreDefinitions,\n finalStoresXmlVersion)));\n }",
"public void setVec3(String key, float x, float y, float z)\n {\n checkKeyIsUniform(key);\n NativeLight.setVec3(getNative(), key, x, y, z);\n }",
"public static void forceDelete(final Path path) throws IOException {\n\t\tif (!java.nio.file.Files.isDirectory(path)) {\n\t\t\tjava.nio.file.Files.delete(path);\n\t\t} else {\n\t\t\tjava.nio.file.Files.walkFileTree(path, DeleteDirVisitor.getInstance());\n\t\t}\n\t}",
"public static final String printFinishDateTime(Date value)\n {\n if (value != null)\n {\n value = DateHelper.addDays(value, 1);\n }\n return (value == null ? null : DATE_FORMAT.get().format(value));\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 }"
] |
Convert the Values using the FieldConversion.sqlToJava
@param fcs
@param values | [
"private Object[] convert(FieldConversion[] fcs, Object[] values)\r\n {\r\n Object[] convertedValues = new Object[values.length];\r\n \r\n for (int i= 0; i < values.length; i++)\r\n {\r\n convertedValues[i] = fcs[i].sqlToJava(values[i]);\r\n }\r\n\r\n return convertedValues;\r\n }"
] | [
"void invoke(HttpRequest request) throws Exception {\n bodyConsumer = null;\n Object invokeResult;\n try {\n args[0] = this.request = request;\n invokeResult = method.invoke(handler, args);\n } catch (InvocationTargetException e) {\n exceptionHandler.handle(e.getTargetException(), request, responder);\n return;\n } catch (Throwable t) {\n exceptionHandler.handle(t, request, responder);\n return;\n }\n\n if (isStreaming) {\n // Casting guarantee to be succeeded.\n bodyConsumer = (BodyConsumer) invokeResult;\n }\n }",
"private void init(AttributeSet attrs) {\n inflate(getContext(), R.layout.intl_phone_input, this);\n\n /**+\n * Country spinner\n */\n mCountrySpinner = (Spinner) findViewById(R.id.intl_phone_edit__country);\n mCountrySpinnerAdapter = new CountrySpinnerAdapter(getContext());\n mCountrySpinner.setAdapter(mCountrySpinnerAdapter);\n\n mCountries = CountriesFetcher.getCountries(getContext());\n mCountrySpinnerAdapter.addAll(mCountries);\n mCountrySpinner.setOnItemSelectedListener(mCountrySpinnerListener);\n\n setFlagDefaults(attrs);\n\n /**\n * Phone text field\n */\n mPhoneEdit = (EditText) findViewById(R.id.intl_phone_edit__phone);\n mPhoneEdit.addTextChangedListener(mPhoneNumberWatcher);\n\n setDefault();\n setEditTextDefaults(attrs);\n }",
"protected int getDonorId(StoreRoutingPlan currentSRP,\n StoreRoutingPlan finalSRP,\n int stealerZoneId,\n int stealerNodeId,\n int stealerPartitionId) {\n int stealerZoneNAry = finalSRP.getZoneNaryForNodesPartition(stealerZoneId,\n stealerNodeId,\n stealerPartitionId);\n\n int donorZoneId;\n if(currentSRP.zoneNAryExists(stealerZoneId, stealerZoneNAry, stealerPartitionId)) {\n // Steal from local n-ary (since one exists).\n donorZoneId = stealerZoneId;\n } else {\n // Steal from zone that hosts primary partition Id.\n int currentMasterNodeId = currentSRP.getNodeIdForPartitionId(stealerPartitionId);\n donorZoneId = currentCluster.getNodeById(currentMasterNodeId).getZoneId();\n }\n\n return currentSRP.getNodeIdForZoneNary(donorZoneId, stealerZoneNAry, stealerPartitionId);\n\n }",
"private double getConstraint(double x1, double x2)\n {\n double c1,c2,h;\n c1 = -x1*x1-x2*x2+1+0.1*Math.cos(16*Math.atan(x1/x2));\n c2 = (x1-0.5)*(x1-0.5)+(x2-0.5)*(x2-0.5)-0.5;\n if(c1>c2)\n h = (c1>0)?c1:0;\n else\n h = (c2>0)?c2:0;\n return h;\n }",
"public static String fancyStringF(double value, DecimalFormat format, int length, int significant) {\n\n String formatted = fancyString(value, format, length, significant);\n\n int n = length-formatted.length();\n if( n > 0 ) {\n StringBuilder builder = new StringBuilder(n);\n for (int i = 0; i < n; i++) {\n builder.append(' ');\n }\n return formatted + builder.toString();\n } else {\n return formatted;\n }\n }",
"@Override\n\tpublic String getInputToParse(String completeInput, int offset, int completionOffset) {\n\t\tint fixedOffset = getOffsetIncludingWhitespace(completeInput, offset, Math.min(completeInput.length(), completionOffset));\n\t\treturn super.getInputToParse(completeInput, fixedOffset, completionOffset);\n\t}",
"public RangeInfo subListBorders(int size) {\n if (inclusive == null) throw new IllegalStateException(\"Should not call subListBorders on a non-inclusive aware IntRange\");\n int tempFrom = from;\n if (tempFrom < 0) {\n tempFrom += size;\n }\n int tempTo = to;\n if (tempTo < 0) {\n tempTo += size;\n }\n if (tempFrom > tempTo) {\n return new RangeInfo(inclusive ? tempTo : tempTo + 1, tempFrom + 1, true);\n }\n return new RangeInfo(tempFrom, inclusive ? tempTo + 1 : tempTo, false);\n }",
"private static <T, ID> void addCreateTableStatements(DatabaseType databaseType, TableInfo<T, ID> tableInfo,\n\t\t\tList<String> statements, List<String> queriesAfter, boolean ifNotExists, boolean logDetails)\n\t\t\tthrows SQLException {\n\t\tStringBuilder sb = new StringBuilder(256);\n\t\tif (logDetails) {\n\t\t\tlogger.info(\"creating table '{}'\", tableInfo.getTableName());\n\t\t}\n\t\tsb.append(\"CREATE TABLE \");\n\t\tif (ifNotExists && databaseType.isCreateIfNotExistsSupported()) {\n\t\t\tsb.append(\"IF NOT EXISTS \");\n\t\t}\n\t\tdatabaseType.appendEscapedEntityName(sb, tableInfo.getTableName());\n\t\tsb.append(\" (\");\n\t\tList<String> additionalArgs = new ArrayList<String>();\n\t\tList<String> statementsBefore = new ArrayList<String>();\n\t\tList<String> statementsAfter = new ArrayList<String>();\n\t\t// our statement will be set here later\n\t\tboolean first = true;\n\t\tfor (FieldType fieldType : tableInfo.getFieldTypes()) {\n\t\t\t// skip foreign collections\n\t\t\tif (fieldType.isForeignCollection()) {\n\t\t\t\tcontinue;\n\t\t\t} else if (first) {\n\t\t\t\tfirst = false;\n\t\t\t} else {\n\t\t\t\tsb.append(\", \");\n\t\t\t}\n\t\t\tString columnDefinition = fieldType.getColumnDefinition();\n\t\t\tif (columnDefinition == null) {\n\t\t\t\t// we have to call back to the database type for the specific create syntax\n\t\t\t\tdatabaseType.appendColumnArg(tableInfo.getTableName(), sb, fieldType, additionalArgs, statementsBefore,\n\t\t\t\t\t\tstatementsAfter, queriesAfter);\n\t\t\t} else {\n\t\t\t\t// hand defined field\n\t\t\t\tdatabaseType.appendEscapedEntityName(sb, fieldType.getColumnName());\n\t\t\t\tsb.append(' ').append(columnDefinition).append(' ');\n\t\t\t}\n\t\t}\n\t\t// add any sql that sets any primary key fields\n\t\tdatabaseType.addPrimaryKeySql(tableInfo.getFieldTypes(), additionalArgs, statementsBefore, statementsAfter,\n\t\t\t\tqueriesAfter);\n\t\t// add any sql that sets any unique fields\n\t\tdatabaseType.addUniqueComboSql(tableInfo.getFieldTypes(), additionalArgs, statementsBefore, statementsAfter,\n\t\t\t\tqueriesAfter);\n\t\tfor (String arg : additionalArgs) {\n\t\t\t// we will have spat out one argument already so we don't have to do the first dance\n\t\t\tsb.append(\", \").append(arg);\n\t\t}\n\t\tsb.append(\") \");\n\t\tdatabaseType.appendCreateTableSuffix(sb);\n\t\tstatements.addAll(statementsBefore);\n\t\tstatements.add(sb.toString());\n\t\tstatements.addAll(statementsAfter);\n\t\taddCreateIndexStatements(databaseType, tableInfo, statements, ifNotExists, false, logDetails);\n\t\taddCreateIndexStatements(databaseType, tableInfo, statements, ifNotExists, true, logDetails);\n\t}",
"private void openBrowser(URI url) throws IOException {\n if (Desktop.isDesktopSupported()) {\n Desktop.getDesktop().browse(url);\n } else {\n LOGGER.error(\"Can not open browser because this capability is not supported on \" +\n \"your platform. You can use the link below to open the report manually.\");\n }\n }"
] |
Gets an item that was shared with a shared link.
@param api the API connection to be used by the shared item.
@param sharedLink the shared link to the item.
@return info about the shared item. | [
"public static BoxItem.Info getSharedItem(BoxAPIConnection api, String sharedLink) {\n return getSharedItem(api, sharedLink, null);\n }"
] | [
"public static String encodeUrlIso(String stringToEncode) {\n try {\n return URLEncoder.encode(stringToEncode, \"ISO-8859-1\");\n } catch (UnsupportedEncodingException e1) {\n throw new RuntimeException(e1);\n }\n }",
"public File getStylesheetPath()\n {\n String path = System.getProperty(STYLESHEET_KEY);\n return path == null ? null : new File(path);\n }",
"public static String[] removeDuplicateStrings(String[] array) {\n if (isEmpty(array)) {\n return array;\n }\n Set<String> set = new TreeSet<String>();\n Collections.addAll(set, array);\n return toStringArray(set);\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}",
"public static tmtrafficpolicy_lbvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\ttmtrafficpolicy_lbvserver_binding obj = new tmtrafficpolicy_lbvserver_binding();\n\t\tobj.set_name(name);\n\t\ttmtrafficpolicy_lbvserver_binding response[] = (tmtrafficpolicy_lbvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public QueryBuilder<T, ID> groupBy(String columnName) {\n\t\tFieldType fieldType = verifyColumnName(columnName);\n\t\tif (fieldType.isForeignCollection()) {\n\t\t\tthrow new IllegalArgumentException(\"Can't groupBy foreign collection field: \" + columnName);\n\t\t}\n\t\taddGroupBy(ColumnNameOrRawSql.withColumnName(columnName));\n\t\treturn this;\n\t}",
"public static base_responses delete(nitro_service client, String jsoncontenttypevalue[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (jsoncontenttypevalue != null && jsoncontenttypevalue.length > 0) {\n\t\t\tappfwjsoncontenttype deleteresources[] = new appfwjsoncontenttype[jsoncontenttypevalue.length];\n\t\t\tfor (int i=0;i<jsoncontenttypevalue.length;i++){\n\t\t\t\tdeleteresources[i] = new appfwjsoncontenttype();\n\t\t\t\tdeleteresources[i].jsoncontenttypevalue = jsoncontenttypevalue[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"protected MethodVisitor makeDelegateCall(final String name, final String desc, final String signature, final String[] exceptions, final int accessFlags) {\n MethodVisitor mv = super.visitMethod(accessFlags, name, desc, signature, exceptions);\n mv.visitVarInsn(ALOAD, 0); // load this\n mv.visitFieldInsn(GETFIELD, proxyName, DELEGATE_OBJECT_FIELD, BytecodeHelper.getTypeDescription(delegateClass)); // load delegate\n // using InvokerHelper to allow potential intercepted calls\n int size;\n mv.visitLdcInsn(name); // method name\n Type[] args = Type.getArgumentTypes(desc);\n BytecodeHelper.pushConstant(mv, args.length);\n mv.visitTypeInsn(ANEWARRAY, \"java/lang/Object\");\n size = 6;\n int idx = 1;\n for (int i = 0; i < args.length; i++) {\n Type arg = args[i];\n mv.visitInsn(DUP);\n BytecodeHelper.pushConstant(mv, i);\n // primitive types must be boxed\n if (isPrimitive(arg)) {\n mv.visitIntInsn(getLoadInsn(arg), idx);\n String wrappedType = getWrappedClassDescriptor(arg);\n mv.visitMethodInsn(INVOKESTATIC, wrappedType, \"valueOf\", \"(\" + arg.getDescriptor() + \")L\" + wrappedType + \";\", false);\n } else {\n mv.visitVarInsn(ALOAD, idx); // load argument i\n }\n size = Math.max(size, 5+registerLen(arg));\n idx += registerLen(arg);\n mv.visitInsn(AASTORE); // store value into array\n }\n mv.visitMethodInsn(INVOKESTATIC, \"org/codehaus/groovy/runtime/InvokerHelper\", \"invokeMethod\", \"(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;\", false);\n unwrapResult(mv, desc);\n mv.visitMaxs(size, registerLen(args) + 1);\n\n return mv;\n }",
"public void updateMetadataVersions() {\n Properties versionProps = MetadataVersionStoreUtils.getProperties(this.systemStoreRepository.getMetadataVersionStore());\n Long newVersion = fetchNewVersion(SystemStoreConstants.CLUSTER_VERSION_KEY,\n null,\n versionProps);\n if(newVersion != null) {\n this.currentClusterVersion = newVersion;\n }\n }"
] |
Get the relative path.
@return the relative path | [
"public String getRelativePath() {\n final StringBuilder builder = new StringBuilder();\n for(final String p : path) {\n builder.append(p).append(\"/\");\n }\n builder.append(getName());\n return builder.toString();\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 static ipseccounters_stats get(nitro_service service) throws Exception{\n\t\tipseccounters_stats obj = new ipseccounters_stats();\n\t\tipseccounters_stats[] response = (ipseccounters_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}",
"private String swapStore(String storeName, String directory) throws VoldemortException {\n\n ReadOnlyStorageEngine store = getReadOnlyStorageEngine(metadataStore,\n storeRepository,\n storeName);\n\n if(!Utils.isReadableDir(directory))\n throw new VoldemortException(\"Store directory '\" + directory\n + \"' is not a readable directory.\");\n\n String currentDirPath = store.getCurrentDirPath();\n\n logger.info(\"Swapping RO store '\" + storeName + \"' to version directory '\" + directory\n + \"'\");\n store.swapFiles(directory);\n logger.info(\"Swapping swapped RO store '\" + storeName + \"' to version directory '\"\n + directory + \"'\");\n\n return currentDirPath;\n }",
"public static boolean propertyExists(Class<?> clazz, String property, ElementType elementType) {\n\t\tif ( ElementType.FIELD.equals( elementType ) ) {\n\t\t\treturn getDeclaredField( clazz, property ) != null;\n\t\t}\n\t\telse {\n\t\t\tString capitalizedPropertyName = capitalize( property );\n\n\t\t\tMethod method = getMethod( clazz, PROPERTY_ACCESSOR_PREFIX_GET + capitalizedPropertyName );\n\t\t\tif ( method != null && method.getReturnType() != void.class ) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tmethod = getMethod( clazz, PROPERTY_ACCESSOR_PREFIX_IS + capitalizedPropertyName );\n\t\t\tif ( method != null && method.getReturnType() == boolean.class ) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}",
"private 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 }",
"public F resolve(R resolvable, boolean cache) {\n R wrappedResolvable = wrap(resolvable);\n if (cache) {\n return resolved.getValue(wrappedResolvable);\n } else {\n return resolverFunction.apply(wrappedResolvable);\n }\n }",
"public int millisecondsToX(long milliseconds) {\n if (autoScroll.get()) {\n int playHead = (getWidth() / 2) + 2;\n long offset = milliseconds - getFurthestPlaybackPosition();\n return playHead + (Util.timeToHalfFrame(offset) / scale.get());\n }\n return Util.timeToHalfFrame(milliseconds) / scale.get();\n }",
"public Label htmlLabel(String html) {\n\n Label label = new Label();\n label.setContentMode(ContentMode.HTML);\n label.setValue(html);\n return label;\n\n }",
"private ProjectFile readProjectFile(ProjectReader reader, File file) throws MPXJException\n {\n addListeners(reader);\n return reader.read(file);\n }"
] |
Generates a download id for the request and adds the download request to the download request queue for the dispatchers pool to act on immediately.
@param request
@return downloadId | [
"int add(DownloadRequest request) {\n\t\tint downloadId = getDownloadId();\n\t\t// Tag the request as belonging to this queue and add it to the set of current requests.\n\t\trequest.setDownloadRequestQueue(this);\n\n\t\tsynchronized (mCurrentRequests) {\n\t\t\tmCurrentRequests.add(request);\n\t\t}\n\n\t\t// Process requests in the order they are added.\n\t\trequest.setDownloadId(downloadId);\n\t\tmDownloadQueue.add(request);\n\n\t\treturn downloadId;\n\t}"
] | [
"@Pure\n\tpublic static <P1, P2, P3, P4, RESULT> Function3<P2, P3, P4, RESULT> curry(\n\t\t\tfinal Function4<? super P1, ? super P2, ? super P3, ? super P4, ? extends RESULT> function, final P1 argument) {\n\t\tif (function == null)\n\t\t\tthrow new NullPointerException(\"function\");\n\t\treturn new Function3<P2, P3, P4, RESULT>() {\n\t\t\t@Override\n\t\t\tpublic RESULT apply(P2 p2, P3 p3, P4 p4) {\n\t\t\t\treturn function.apply(argument, p2, p3, p4);\n\t\t\t}\n\t\t};\n\t}",
"@Nullable\n public StitchUserT getUser() {\n authLock.readLock().lock();\n try {\n return activeUser;\n } finally {\n authLock.readLock().unlock();\n }\n }",
"public static boolean isSinglePositionPrefix(FieldInfo fieldInfo,\n String prefix) throws IOException {\n if (fieldInfo == null) {\n throw new IOException(\"no fieldInfo\");\n } else {\n String info = fieldInfo.getAttribute(\n MtasCodecPostingsFormat.MTAS_FIELDINFO_ATTRIBUTE_PREFIX_SINGLE_POSITION);\n if (info == null) {\n throw new IOException(\"no \"\n + MtasCodecPostingsFormat.MTAS_FIELDINFO_ATTRIBUTE_PREFIX_SINGLE_POSITION);\n } else {\n return Arrays.asList(info.split(Pattern.quote(MtasToken.DELIMITER)))\n .contains(prefix);\n }\n }\n }",
"public final void notifyHeaderItemRangeChanged(int positionStart, int itemCount) {\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount >= headerItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \" + (positionStart + itemCount - 1) + \"] is not within the position bounds for header items [0 - \" + (headerItemCount - 1) + \"].\");\n }\n notifyItemRangeChanged(positionStart, itemCount);\n }",
"public static ServiceName moduleResolvedServiceName(ModuleIdentifier identifier) {\n if (!isDynamicModule(identifier)) {\n throw ServerLogger.ROOT_LOGGER.missingModulePrefix(identifier, MODULE_PREFIX);\n }\n return MODULE_RESOLVED_SERVICE_PREFIX.append(identifier.getName()).append(identifier.getSlot());\n }",
"protected static void captureSystemStreams(boolean captureOut, boolean captureErr){\r\n if(captureOut){\r\n System.setOut(new RedwoodPrintStream(STDOUT, realSysOut));\r\n }\r\n if(captureErr){\r\n System.setErr(new RedwoodPrintStream(STDERR, realSysErr));\r\n }\r\n }",
"public InsertIntoTable addRowsFrom(File file, FileParser fileParser) {\n builder.addRowsFrom(file, fileParser);\n return this;\n }",
"public void setWorkDir(String dir) throws IOException\r\n {\r\n File workDir = new File(dir);\r\n\r\n if (!workDir.exists() || !workDir.canWrite() || !workDir.canRead())\r\n {\r\n throw new IOException(\"Cannot access directory \"+dir);\r\n }\r\n _workDir = workDir;\r\n }",
"public void setup( int numSamples , int sampleSize ) {\n mean = new double[ sampleSize ];\n A.reshape(numSamples,sampleSize,false);\n sampleIndex = 0;\n numComponents = -1;\n }"
] |
Calculates the bar width and bar margin based on the _DataSize and settings and starts the boundary
calculation in child classes.
@param _DataSize Amount of data sets | [
"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 }"
] | [
"public static <K,V> Map<K,V> minus(Map<K,V> self, Map removeMe) {\n final Map<K,V> ansMap = createSimilarMap(self);\n ansMap.putAll(self);\n if (removeMe != null && removeMe.size() > 0) {\n for (Map.Entry<K, V> e1 : self.entrySet()) {\n for (Object e2 : removeMe.entrySet()) {\n if (DefaultTypeTransformation.compareEqual(e1, e2)) {\n ansMap.remove(e1.getKey());\n }\n }\n }\n }\n return ansMap;\n }",
"private void processPredecessors(Gantt gantt)\n {\n for (Gantt.Tasks.Task ganttTask : gantt.getTasks().getTask())\n {\n String predecessors = ganttTask.getP();\n if (predecessors != null && !predecessors.isEmpty())\n {\n String wbs = ganttTask.getID();\n Task task = m_taskMap.get(wbs);\n for (String predecessor : predecessors.split(\";\"))\n {\n Task predecessorTask = m_projectFile.getTaskByID(Integer.valueOf(predecessor));\n task.addPredecessor(predecessorTask, RelationType.FINISH_START, ganttTask.getL());\n }\n }\n }\n }",
"private void writePredecessors(Task mpxjTask, net.sf.mpxj.planner.schema.Task plannerTask)\n {\n Predecessors plannerPredecessors = m_factory.createPredecessors();\n plannerTask.setPredecessors(plannerPredecessors);\n List<Predecessor> predecessorList = plannerPredecessors.getPredecessor();\n int id = 0;\n\n List<Relation> predecessors = mpxjTask.getPredecessors();\n for (Relation rel : predecessors)\n {\n Integer taskUniqueID = rel.getTargetTask().getUniqueID();\n Predecessor plannerPredecessor = m_factory.createPredecessor();\n plannerPredecessor.setId(getIntegerString(++id));\n plannerPredecessor.setPredecessorId(getIntegerString(taskUniqueID));\n plannerPredecessor.setLag(getDurationString(rel.getLag()));\n plannerPredecessor.setType(RELATIONSHIP_TYPES.get(rel.getType()));\n predecessorList.add(plannerPredecessor);\n m_eventManager.fireRelationWrittenEvent(rel);\n }\n }",
"private static boolean mayBeIPv6Address(String input) {\n if (input == null) {\n return false;\n }\n\n boolean result = false;\n int colonsCounter = 0;\n int length = input.length();\n for (int i = 0; i < length; i++) {\n char c = input.charAt(i);\n if (c == '.' || c == '%') {\n // IPv4 in IPv6 or Zone ID detected, end of checking.\n break;\n }\n if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')\n || (c >= 'A' && c <= 'F') || c == ':')) {\n return false;\n } else if (c == ':') {\n colonsCounter++;\n }\n }\n if (colonsCounter >= 2) {\n result = true;\n }\n return result;\n }",
"public List<Versioned<V>> getWithCustomTimeout(CompositeVoldemortRequest<K, V> requestWrapper) {\n validateTimeout(requestWrapper.getRoutingTimeoutInMs());\n for(int attempts = 0; attempts < this.metadataRefreshAttempts; attempts++) {\n try {\n long startTimeInMs = System.currentTimeMillis();\n String keyHexString = \"\";\n if(logger.isDebugEnabled()) {\n ByteArray key = (ByteArray) requestWrapper.getKey();\n keyHexString = RestUtils.getKeyHexString(key);\n debugLogStart(\"GET\",\n requestWrapper.getRequestOriginTimeInMs(),\n startTimeInMs,\n keyHexString);\n }\n List<Versioned<V>> items = store.get(requestWrapper);\n if(logger.isDebugEnabled()) {\n int vcEntrySize = 0;\n for(Versioned<V> vc: items) {\n vcEntrySize += ((VectorClock) vc.getVersion()).getVersionMap().size();\n }\n debugLogEnd(\"GET\",\n requestWrapper.getRequestOriginTimeInMs(),\n startTimeInMs,\n System.currentTimeMillis(),\n keyHexString,\n vcEntrySize);\n }\n return items;\n } catch(InvalidMetadataException e) {\n logger.info(\"Received invalid metadata exception during get [ \" + e.getMessage()\n + \" ] on store '\" + storeName + \"'. Rebootstrapping\");\n bootStrap();\n }\n }\n throw new VoldemortException(this.metadataRefreshAttempts\n + \" metadata refresh attempts failed.\");\n }",
"public void setNewCenterColor(int color) {\n\t\tmCenterNewColor = color;\n\t\tmCenterNewPaint.setColor(color);\n\t\tif (mCenterOldColor == 0) {\n\t\t\tmCenterOldColor = color;\n\t\t\tmCenterOldPaint.setColor(color);\n\t\t}\n\t\tif (onColorChangedListener != null && color != oldChangedListenerColor ) {\n\t\t\tonColorChangedListener.onColorChanged(color);\n\t\t\toldChangedListenerColor = color;\n\t\t}\n\t\tinvalidate();\n\t}",
"@Override\n\tpublic String toNormalizedString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = stringCache.normalizedString) == null) {\n\t\t\tif(hasZone()) {\n\t\t\t\tstringCache.normalizedString = result = toNormalizedString(IPv6StringCache.normalizedParams);\n\t\t\t} else {\n\t\t\t\tresult = getSection().toNormalizedString();//the cache is shared so no need to update it here\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}",
"private List<DumpProcessingAction> handleArguments(String[] args) {\n\t\tCommandLine cmd;\n\t\tCommandLineParser parser = new GnuParser();\n\n\t\ttry {\n\t\t\tcmd = parser.parse(options, args);\n\t\t} catch (ParseException e) {\n\t\t\tlogger.error(\"Failed to parse arguments: \" + e.getMessage());\n\t\t\treturn Collections.emptyList();\n\t\t}\n\n\t\t// Stop processing if a help text is to be printed:\n\t\tif ((cmd.hasOption(CMD_OPTION_HELP)) || (args.length == 0)) {\n\t\t\treturn Collections.emptyList();\n\t\t}\n\n\t\tList<DumpProcessingAction> configuration = new ArrayList<>();\n\n\t\thandleGlobalArguments(cmd);\n\n\t\tif (cmd.hasOption(CMD_OPTION_ACTION)) {\n\t\t\tDumpProcessingAction action = handleActionArguments(cmd);\n\t\t\tif (action != null) {\n\t\t\t\tconfiguration.add(action);\n\t\t\t}\n\t\t}\n\n\t\tif (cmd.hasOption(CMD_OPTION_CONFIG_FILE)) {\n\t\t\ttry {\n\t\t\t\tList<DumpProcessingAction> configFile = readConfigFile(cmd\n\t\t\t\t\t\t.getOptionValue(CMD_OPTION_CONFIG_FILE));\n\t\t\t\tconfiguration.addAll(configFile);\n\t\t\t} catch (IOException e) {\n\t\t\t\tlogger.error(\"Failed to read configuration file \\\"\"\n\t\t\t\t\t\t+ cmd.getOptionValue(CMD_OPTION_CONFIG_FILE) + \"\\\": \"\n\t\t\t\t\t\t+ e.toString());\n\t\t\t}\n\n\t\t}\n\n\t\treturn configuration;\n\n\t}",
"@Override\n public com.flickr4java.flickr.Response get(String path, Map<String, Object> parameters, String apiKey, String sharedSecret) throws FlickrException {\n\n OAuthRequest request = new OAuthRequest(Verb.GET, buildUrl(path));\n for (Map.Entry<String, Object> entry : parameters.entrySet()) {\n request.addQuerystringParameter(entry.getKey(), String.valueOf(entry.getValue()));\n }\n\n if (proxyAuth) {\n request.addHeader(\"Proxy-Authorization\", \"Basic \" + getProxyCredentials());\n }\n\n RequestContext requestContext = RequestContext.getRequestContext();\n Auth auth = requestContext.getAuth();\n OAuth10aService service = createOAuthService(apiKey, sharedSecret);\n if (auth != null) {\n OAuth1AccessToken requestToken = new OAuth1AccessToken(auth.getToken(), auth.getTokenSecret());\n service.signRequest(requestToken, request);\n } else {\n // For calls that do not require authorization e.g. flickr.people.findByUsername which could be the\n // first call if the user did not supply the user-id (i.e. nsid).\n if (!parameters.containsKey(Flickr.API_KEY)) {\n request.addQuerystringParameter(Flickr.API_KEY, apiKey);\n }\n }\n\n if (Flickr.debugRequest) {\n logger.debug(\"GET: \" + request.getCompleteUrl());\n }\n\n try {\n return handleResponse(request, service);\n } catch (IllegalAccessException | InstantiationException | SAXException | IOException | InterruptedException | ExecutionException | ParserConfigurationException e) {\n throw new FlickrRuntimeException(e);\n }\n }"
] |
Implement this to do your drawing.
@param canvas the canvas on which the background will be drawn | [
"@Override\n protected void onDraw(Canvas canvas) {\n super.onDraw(canvas);\n\n // If the API level is less than 11, we can't rely on the view animation system to\n // do the scrolling animation. Need to tick it here and call postInvalidate() until the scrolling is done.\n if (Build.VERSION.SDK_INT < 11) {\n tickScrollAnimation();\n if (!mScroller.isFinished()) {\n mGraph.postInvalidate();\n }\n }\n }"
] | [
"public static void validateClusterStores(final Cluster cluster,\n final List<StoreDefinition> storeDefs) {\n // Constructing a StoreRoutingPlan has the (desirable in this\n // case) side-effect of verifying that the store definition is congruent\n // with the cluster definition. If there are issues, exceptions are\n // thrown.\n for(StoreDefinition storeDefinition: storeDefs) {\n new StoreRoutingPlan(cluster, storeDefinition);\n }\n return;\n }",
"public Iterator getAllExtentClasses()\r\n {\r\n ArrayList subTypes = new ArrayList();\r\n\r\n subTypes.addAll(_extents);\r\n\r\n for (int idx = 0; idx < subTypes.size(); idx++)\r\n {\r\n ClassDescriptorDef curClassDef = (ClassDescriptorDef)subTypes.get(idx);\r\n\r\n for (Iterator it = curClassDef.getExtentClasses(); it.hasNext();)\r\n {\r\n ClassDescriptorDef curSubTypeDef = (ClassDescriptorDef)it.next();\r\n\r\n if (!subTypes.contains(curSubTypeDef))\r\n {\r\n subTypes.add(curSubTypeDef);\r\n }\r\n }\r\n }\r\n return subTypes.iterator();\r\n }",
"@SuppressWarnings(\"unused\")\n public String getDevicePushToken(final PushType type) {\n switch (type) {\n case GCM:\n return getCachedGCMToken();\n case FCM:\n return getCachedFCMToken();\n default:\n return null;\n }\n }",
"public void loadWithTimeout(int timeout) {\n\n for (String stylesheet : m_stylesheets) {\n boolean alreadyLoaded = checkStylesheet(stylesheet);\n if (alreadyLoaded) {\n m_loadCounter += 1;\n } else {\n appendStylesheet(stylesheet, m_jsCallback);\n }\n }\n checkAllLoaded();\n if (timeout > 0) {\n Timer timer = new Timer() {\n\n @SuppressWarnings(\"synthetic-access\")\n @Override\n public void run() {\n\n callCallback();\n }\n };\n\n timer.schedule(timeout);\n }\n }",
"public static void addStory(File caseManager, String storyName,\n String testPath, String user, String feature, String benefit) throws BeastException {\n FileWriter caseManagerWriter;\n\n String storyClass = SystemReader.createClassName(storyName);\n try {\n BufferedReader reader = new BufferedReader(new FileReader(\n caseManager));\n String targetLine1 = \" public void \"\n + MASReader.createFirstLowCaseName(storyName) + \"() {\";\n String targetLine2 = \" Result result = JUnitCore.runClasses(\" + testPath + \".\"\n + storyClass + \".class);\";\n String in;\n while ((in = reader.readLine()) != null) {\n if (in.equals(targetLine1)) {\n while ((in = reader.readLine()) != null) {\n if (in.equals(targetLine2)) {\n reader.close();\n // This test is already written in the case manager.\n return;\n }\n }\n reader.close();\n throw new BeastException(\"Two different stories with the same name (same method name) are being created in the same CaseManager file. That is not possible. Please, change the name of the story: \" + testPath + \".\"\n + storyClass + \".java\");\n }\n }\n reader.close();\n caseManagerWriter = new FileWriter(caseManager, true);\n caseManagerWriter.write(\" /**\\n\");\n caseManagerWriter.write(\" * This is the story: \" + storyName\n + \"\\n\");\n caseManagerWriter.write(\" * requested by: \" + user + \"\\n\");\n caseManagerWriter.write(\" * providing the feature: \" + feature\n + \"\\n\");\n caseManagerWriter.write(\" * so the user gets the benefit: \"\n + benefit + \"\\n\");\n caseManagerWriter.write(\" */\\n\");\n caseManagerWriter.write(\" @Test\\n\");\n caseManagerWriter.write(\" public void \"\n + MASReader.createFirstLowCaseName(storyName) + \"() {\\n\");\n caseManagerWriter.write(\" Result result = JUnitCore.runClasses(\" + testPath\n + \".\" + storyClass + \".class);\\n\");\n caseManagerWriter.write(\" Assert.assertTrue(result.wasSuccessful());\\n\");\n caseManagerWriter.write(\" }\\n\");\n caseManagerWriter.write(\"\\n\");\n caseManagerWriter.flush();\n caseManagerWriter.close();\n } catch (IOException e) {\n Logger logger = Logger.getLogger(\"CreateMASCaseManager.createTest\");\n logger.info(\"ERROR writing the file\");\n }\n\n }",
"public ItemDocument updateTermsStatements(ItemIdValue itemIdValue,\n\t\t\tList<MonolingualTextValue> addLabels,\n\t\t\tList<MonolingualTextValue> addDescriptions,\n\t\t\tList<MonolingualTextValue> addAliases,\n\t\t\tList<MonolingualTextValue> deleteAliases,\n\t\t\tList<Statement> addStatements,\n\t\t\tList<Statement> deleteStatements,\n\t\t\tString summary) throws MediaWikiApiErrorException, IOException {\n\t\tItemDocument currentDocument = (ItemDocument) this.wikibaseDataFetcher\n\t\t\t\t.getEntityDocument(itemIdValue.getId());\n\t\t\n\t\treturn updateTermsStatements(currentDocument, addLabels,\n\t\t\t\taddDescriptions, addAliases, deleteAliases,\n\t\t\t\taddStatements, deleteStatements, summary);\n\t}",
"protected static String createDotStoryName(String scenarioName) {\n String[] words = scenarioName.trim().split(\" \");\n String result = \"\";\n for (int i = 0; i < words.length; i++) {\n String word1 = words[i];\n String word2 = word1.toLowerCase();\n if (!word1.equals(word2)) {\n String finalWord = \"\";\n for (int j = 0; j < word1.length(); j++) {\n if (i != 0) {\n char c = word1.charAt(j);\n if (Character.isUpperCase(c)) {\n if (j==0) {\n finalWord += Character.toLowerCase(c);\n } else {\n finalWord += \"_\" + Character.toLowerCase(c); \n }\n } else {\n finalWord += c;\n }\n } else {\n finalWord = word2;\n break;\n }\n }\n\n result += finalWord;\n } else {\n result += word2;\n }\n // I don't add the '_' to the last word.\n if (!(i == words.length - 1))\n result += \"_\";\n }\n return result;\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 boolean absoluteAdvanced(int row)\r\n {\r\n boolean retval = false;\r\n \r\n try\r\n {\r\n if (getRsAndStmt().m_rs != null)\r\n {\r\n if (row == 0)\r\n {\r\n getRsAndStmt().m_rs.beforeFirst();\r\n }\r\n else\r\n {\r\n retval = getRsAndStmt().m_rs.absolute(row); \r\n }\r\n m_current_row = row;\r\n setHasCalledCheck(false);\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n advancedJDBCSupport = false;\r\n }\r\n return retval;\r\n }"
] |
Set the html as value inside the tooltip. | [
"public void setHtml(String html) {\n this.html = html;\n\n if (widget != null) {\n if (widget.isAttached()) {\n tooltipElement.find(\"span\")\n .html(html != null ? html : \"\");\n } else {\n widget.addAttachHandler(event ->\n tooltipElement.find(\"span\")\n .html(html != null ? html : \"\"));\n }\n } else {\n GWT.log(\"Please initialize the Target widget.\", new IllegalStateException());\n }\n }"
] | [
"public T execute(DatabaseConnection databaseConnection, ID id, ObjectCache objectCache) throws SQLException {\n\t\tif (objectCache != null) {\n\t\t\tT result = objectCache.get(clazz, id);\n\t\t\tif (result != null) {\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t\tObject[] args = new Object[] { convertIdToFieldObject(id) };\n\t\t// @SuppressWarnings(\"unchecked\")\n\t\tObject result = databaseConnection.queryForOne(statement, args, argFieldTypes, this, objectCache);\n\t\tif (result == null) {\n\t\t\tlogger.debug(\"{} using '{}' and {} args, got no results\", label, statement, args.length);\n\t\t} else if (result == DatabaseConnection.MORE_THAN_ONE) {\n\t\t\tlogger.error(\"{} using '{}' and {} args, got >1 results\", label, statement, args.length);\n\t\t\tlogArgs(args);\n\t\t\tthrow new SQLException(label + \" got more than 1 result: \" + statement);\n\t\t} else {\n\t\t\tlogger.debug(\"{} using '{}' and {} args, got 1 result\", label, statement, args.length);\n\t\t}\n\t\tlogArgs(args);\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tT castResult = (T) result;\n\t\treturn castResult;\n\t}",
"@Override\n protected void onLoad() {\n\tsuper.onLoad();\n\n\t// these styles need to be the same for the box and shadow so\n\t// that we can measure properly\n\tmatchStyles(\"display\");\n\tmatchStyles(\"fontSize\");\n\tmatchStyles(\"fontFamily\");\n\tmatchStyles(\"fontWeight\");\n\tmatchStyles(\"lineHeight\");\n\tmatchStyles(\"paddingTop\");\n\tmatchStyles(\"paddingRight\");\n\tmatchStyles(\"paddingBottom\");\n\tmatchStyles(\"paddingLeft\");\n\n\tadjustSize();\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 }",
"public static SpinXmlElement XML(Object input) {\n return SpinFactory.INSTANCE.createSpin(input, DataFormats.xml());\n }",
"public int evaluate(FieldContainer container)\n {\n //\n // First step - determine the list of criteria we are should use\n //\n List<GraphicalIndicatorCriteria> criteria;\n if (container instanceof Task)\n {\n Task task = (Task) container;\n if (NumberHelper.getInt(task.getUniqueID()) == 0)\n {\n if (m_projectSummaryInheritsFromSummaryRows == false)\n {\n criteria = m_projectSummaryCriteria;\n }\n else\n {\n if (m_summaryRowsInheritFromNonSummaryRows == false)\n {\n criteria = m_summaryRowCriteria;\n }\n else\n {\n criteria = m_nonSummaryRowCriteria;\n }\n }\n }\n else\n {\n if (task.getSummary() == true)\n {\n if (m_summaryRowsInheritFromNonSummaryRows == false)\n {\n criteria = m_summaryRowCriteria;\n }\n else\n {\n criteria = m_nonSummaryRowCriteria;\n }\n }\n else\n {\n criteria = m_nonSummaryRowCriteria;\n }\n }\n }\n else\n {\n // It is possible to have a resource summary row, but at the moment\n // I can't see how you can determine this.\n criteria = m_nonSummaryRowCriteria;\n }\n\n //\n // Now we have the criteria, evaluate each one until we get a result\n //\n int result = -1;\n for (GraphicalIndicatorCriteria gic : criteria)\n {\n result = gic.evaluate(container);\n if (result != -1)\n {\n break;\n }\n }\n\n //\n // If we still don't have a result at the end, return the\n // default value, which is 0\n //\n if (result == -1)\n {\n result = 0;\n }\n\n return (result);\n }",
"private boolean addType(TypeDefinition type) {\n\n if (type == null) {\n return false;\n }\n\n if (type.getBaseTypeId() == null) {\n return false;\n }\n\n // find base type\n TypeDefinition baseType = null;\n if (type.getBaseTypeId() == BaseTypeId.CMIS_DOCUMENT) {\n baseType = copyTypeDefintion(m_types.get(DOCUMENT_TYPE_ID).getTypeDefinition());\n } else if (type.getBaseTypeId() == BaseTypeId.CMIS_FOLDER) {\n baseType = copyTypeDefintion(m_types.get(FOLDER_TYPE_ID).getTypeDefinition());\n } else if (type.getBaseTypeId() == BaseTypeId.CMIS_RELATIONSHIP) {\n baseType = copyTypeDefintion(m_types.get(RELATIONSHIP_TYPE_ID).getTypeDefinition());\n } else if (type.getBaseTypeId() == BaseTypeId.CMIS_POLICY) {\n baseType = copyTypeDefintion(m_types.get(POLICY_TYPE_ID).getTypeDefinition());\n } else {\n return false;\n }\n\n AbstractTypeDefinition newType = (AbstractTypeDefinition)copyTypeDefintion(type);\n\n // copy property definition\n for (PropertyDefinition<?> propDef : baseType.getPropertyDefinitions().values()) {\n ((AbstractPropertyDefinition<?>)propDef).setIsInherited(Boolean.TRUE);\n newType.addPropertyDefinition(propDef);\n }\n\n // add it\n addTypeInternal(newType);\n return true;\n }",
"public List<Module> getModules(final Map<String, String> filters) throws GrapesCommunicationException {\n final Client client = getClient();\n WebResource resource = client.resource(serverURL).path(RequestUtils.getAllModulesPath());\n for(final Map.Entry<String,String> queryParam: filters.entrySet()){\n resource = resource.queryParam(queryParam.getKey(), queryParam.getValue());\n }\n\n final ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = \"Failed to get filtered modules.\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n\n return response.getEntity(new GenericType<List<Module>>(){});\n }",
"public TreeNode getModuleTree(final String moduleId) {\n final ModuleHandler moduleHandler = new ModuleHandler(repoHandler);\n final DbModule module = moduleHandler.getModule(moduleId);\n\n final TreeNode tree = new TreeNode();\n tree.setName(module.getName());\n\n // Add submodules\n for (final DbModule submodule : module.getSubmodules()) {\n addModuleToTree(submodule, tree);\n }\n\n return tree;\n }",
"public float get(int row, int col) {\n if (row < 0 || row > 3) {\n throw new IndexOutOfBoundsException(\"Index: \" + row + \", Size: 4\");\n }\n if (col < 0 || col > 3) {\n throw new IndexOutOfBoundsException(\"Index: \" + col + \", Size: 4\");\n }\n\n return m_data[row * 4 + col];\n }"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.