FXML using variables in labels [duplicate] - user-interface

I am getting an error with this constructor, and i have no idea how to fix? I am a beginner at java. This is from an example exercise that i was trying to learn:
/**
* Create an array of size n and store a copy of the contents of the
* input argument
* #param intArray array of elements to copy
*/
public IntArray11(int[] intArray)
{
int i = 0;
String [] Array = new String[intArray.length];
for(i=0; i<intArray.length; ++i)
{
Array[i] = intArray[i].toString();
}
}

int is not an object in java (it's a primitive), so you cannot invoke methods on it.
One simple way to solve it is using
Integer.toString(intArray[i])

I would write it more like this
public String[] convertToStrings(int... ints) {
String[] ret = new String[ints.length];
for(int i = 0; i < intArray.length; ++i)
ret[i] = "" + ints[i];
return ret;
}
Or in Java 8 you might write
public List<String> convertToStrings(int... ints) {
return IntStream.of(ints).mapToObj(Integer::toString).collect(toList());
}
This uses;
Java coding conventions,
limited scope for the variable i,
we do something with the String[],
give the method a meaningful name,
try to use consist formatting.
If we were worried about efficiency it is likely we could do away with the method entirely.
String.valueOf(int) is not faster than Integer.toString(int). From the code in String you can see that the String implementation just calls Integer.toString
/**
* Returns the string representation of the {#code int} argument.
* <p>
* The representation is exactly the one returned by the
* {#code Integer.toString} method of one argument.
*
* #param i an {#code int}.
* #return a string representation of the {#code int} argument.
* #see java.lang.Integer#toString(int, int)
*/
public static String valueOf(int i) {
return Integer.toString(i);
}

You code tries to call the toString() method of an int value. In Java, int is a primitive type and has no methods. Change the line:
Array[i] = intArray[i].toString();
to
Array[i] = String.valueOf(intArray[i]);
and the code should run. By the way, you should use lowerCamelCase for variables and fields.
Edit: For what it's worth, String.valueOf(int) is a bit faster than Integer.toString(int) on my system (Java 1.7).

Related

how can the treebin read val when the treebin is writing in concurrencthashmap in java8?

Java version: 8
read operation:
TreeBin.java
// Simplifed Code
/**
* Returns matching node or null if none. Tries to search
* using tree comparisons from root, but continues linear
* search when lock not available.
*/
final Node<K,V> find(int h, Object k)
write operation:
ConcurrencyHashmap.java
// Simplifed Code
/** Implementation for put and putIfAbsent */
final V putVal(K key, V value, boolean onlyIfAbsent) {
synchronized (f) {
p = ((TreeBin<K,V>)f).putTreeVal(hash, key, value)) != null)
}
}
The problem is: the key word synchronized, lock the treebin, so how can the function find() can be execute?
Why not to wait unlock?

append's return value in Go

After reading this article, I have some question in mind.
Basically, why we need to store the return value of append() in Go? How is the function actually implemented?
I have tried to replicate (sort of) the mechanism of append in C (which is the first language used to implements the Go language, if I'm not mistaken). I used malloc(), instead of an array as it will not deallocate the slice after the function returns.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
typedef struct SliceHeader {
int length;
int capacity;
int *zerothElement;
} SliceHeader;
void append(SliceHeader *sh, int element)
{
if (sh->length == sh->capacity) {
// grow capacity size
sh->capacity += 10;
realloc(sh->zerothElement, sh->capacity);
}
sh->zerothElement[sh->length] = element;
sh->length++;
}
SliceHeader * make(int capacity)
{
SliceHeader *sh = (SliceHeader *) malloc(sizeof(sh));
sh->length = 0;
sh->capacity = capacity;
sh->zerothElement = (int *) malloc(capacity * sizeof(int));
return sh;
}
int main()
{
SliceHeader *sh = make(3);
append(sh, 5);
append(sh, 10);
append(sh, 15);
append(sh, 20); // exceed the original capacity, should reallocate
for (int i = 0; i < sh->length; i++) {
printf("%d\n", *((sh->zerothElement)+i) );
}
free(sh->zerothElement);
free(sh);
return 0;
}
(I omit NULLs checking to show only the relevant part to the main question).
If I'm using this code, I can use append() without the need to store its return value and no needs to create a new slice header.
So how is the implementation of append() function in Golang that makes it needs to store a new slice header? Even if the zerothElement uses an array, doesn't it means that it will need to change the array only instead of the whole slice header?
What am I missing here?
Thanks :)
Basically, why we need to store the return value of append() in Go?
You only need to store this value if you intend to use the slice with the appended value.
How is the function actually implemented?
Go is open source, just consult the source code. (Btw: This is uninteresting.)

function to remove object from vector passing in a pointer

i have two vectors. one is a (1) vector which contains all objects im using and works with that. the other vector is a (2) vector which after a function adds an object from (1) into (2). once this happens i want to remove the object from (1). the problem is that the function i made to remove it takes in a object * obj. the actual object still has pointers pointing to it and i dont want to fully wipe the obj, just remove it from (1). any help would be appreciated.
`
void removeObject(const Object * obj) {
int index;
for (int i = 0; i < size(); i++) {
if (obj == & objectVector[i] ) {
index = i;
}
}
objectVector.erase(objectVector.begin() + index);
}
`
im sure this is the problem because when i dont comment out the line using this function i get a sigtrap error

Where BigDecimal "/" is defined?

I thought '3.0'.to_d.div(2) is same as '3.0'.to_d / 2, but the former return 1 while latter returns 1.5.
I searched by def / in Bigdecimal's github repository, but I couldn't find it.
https://github.com/ruby/bigdecimal/search?utf8=%E2%9C%93&q=def+%2F&type=Code
Where can I find the definition? And which method is a equivalent to / in Bigdecimal?
In Float there is a fdiv method. Is there similar one in Bigdecimal?
You can find it in the source code of the bigdecimal library, in the repository you linked to. On line 3403 of ext/bigdecimal/bigdecimal.c, BigDecimal#/ is bound to the function BigDecimal_div:
rb_define_method(rb_cBigDecimal, "/", BigDecimal_div, 1);
This function looks like this:
static VALUE
BigDecimal_div(VALUE self, VALUE r)
/* For c = self/r: with round operation */
{
ENTER(5);
Real *c=NULL, *res=NULL, *div = NULL;
r = BigDecimal_divide(&c, &res, &div, self, r);
if (!NIL_P(r)) return r; /* coerced by other */
SAVE(c); SAVE(res); SAVE(div);
/* a/b = c + r/b */
/* c xxxxx
r 00000yyyyy ==> (y/b)*BASE >= HALF_BASE
*/
/* Round */
if (VpHasVal(div)) { /* frac[0] must be zero for NaN,INF,Zero */
VpInternalRound(c, 0, c->frac[c->Prec-1], (BDIGIT)(VpBaseVal() * (BDIGIT_DBL)res->frac[0] / div->frac[0]));
}
return ToValue(c);
}
This is because BigDecimal#div takes a second argument, precision, which defaults to 1.
irb(main):017:0> '3.0'.to_d.div(2, 2)
=> 0.15e1
However, when / is defined on BigDecimal,
rb_define_method(rb_cBigDecimal, "/", BigDecimal_div, 1);
They used 1 for the # of arguments, rather than -1 which means "variable number of arguments". So BigDecimal#div thinks it takes one required argument and one optional argument, whereas BigDecimal#/ takes one required argument and the optional arg is ignored. Because the optional argument is ignored, it's not initialized correctly, it gets an empty int or 0.
This may be considered a bug. You should consider opening an issue with the ruby devs.

Is there an easier way to set/get values in a gSOAP request/response?

I am using gSOAP to configure an ONVIF compatible camera.
Currently, I am manually setting all the parameters in the request by doing something like this. This is for the SetVideEncoderConfiguration
MediaBindingProxy mediaDevice (uri);
AUTHENTICATE (mediaDevice);
_trt__SetVideoEncoderConfiguration req;
_trt__SetVideoEncoderConfigurationResponse resp;
struct tt__VideoEncoderConfiguration encoderConfig;
struct tt__VideoResolution resolutionConfig;
encoderConfig.Name = strdup (name);
encoderConfig.UseCount = 1;
encoderConfig.Quality = 50;
if (strcmp (encoding, "H264") == 0)
encoderConfig.Encoding = tt__VideoEncoding__H264;
else if (strcmp (encoding, "JPEG") == 0)
encoderConfig.Encoding = tt__VideoEncoding__JPEG;
encoderConfig.token = strdup (profileToken);
encoderConfig.SessionTimeout = (LONG64)"PT0S";
resolutionConfig.Width=1280;
resolutionConfig.Height=720;
encoderConfig.Resolution = &resolutionConfig;
tt__VideoRateControl rateControl;
rateControl.FrameRateLimit = 15;
rateControl.EncodingInterval = 1;
rateControl.BitrateLimit = 4500;
encoderConfig.RateControl = &rateControl;
struct tt__H264Configuration h264;
h264.GovLength = 30;
h264.H264Profile = tt__H264Profile__Baseline;
encoderConfig.H264 = &h264;
struct tt__MulticastConfiguration multicast;
struct tt__IPAddress address;
address.IPv4Address = strdup ("0.0.0.0");
multicast.Address = &address;
encoderConfig.Multicast = &multicast;
req.Configuration = &encoderConfig;
req.ForcePersistence = true;
int ret = mediaDevice.SetVideoEncoderConfiguration (&req, resp);
qDebug () << "Set Encoder: " << ret;
Is there an easier way to do this? May be some function calls that set the request parameters? Another way I found with GetMediaUri was to use something like
soap_new_req__trt__GetStreamUri (mediaDevice.soap,soap_new_req_tt__StreamSetup (mediaDevice.soap, (enum tt__StreamType)0, soap_new_tt__Transport(mediaDevice.soap), 1, NULL), "profile1");
Are these the only two ways for client side code with gSOAP?
-Mandar Joshi
There are four variations of soap_new_T() to allocate data of type T in C++ with gSOAP:
T * soap_new_T(struct soap*) returns a new instance of T that is default
initialized and allocated on the heap managed by the soap context.
T * soap_new_T(struct soap*, int n) returns an array of n new instances of
T on the managed heap. The instances in the array are default initialized as described above.
T * soap_new_req_T(struct soap*, ...) (structs and classes only) returns a
new instance of T allocated on the managed heap and sets the required data members to the values specified in the other arguments ....
T * soap_new_set_T(struct soap*, ...) (structs and classes only) returns a
new instance of T on the managed heap and sets the public/serializable data members to the values specified in the other arguments ....
Use soap_strdup(struct soap*, const char*) instead of strdup to dup strings onto the managed heap.
All data on the managed heap is mass-deleted with soap_destroy(soap) and
soap_end(soap) (call these in that order) which must be called before soap_done(soap) or soap_free(soap).
To allocate pointers to data, use templates:
template<class T>
T * soap_make(struct soap *soap, T val)
{
T *p = (T*)soap_malloc(soap, sizeof(T));
if (p)
*p = val;
return p;
}
template<class T>
T **soap_make_array(struct soap *soap, T* array, int n)
{
T **p = (T**)soap_malloc(soap, n * sizeof(T*));
for (int i = 0; i < n; ++i)
p[i] = &array[i];
return p;
}
Then use soap_make<int>(soap, 123) to create a pointer to the value 123 on the managed heap and soap_make_array(soap, soap_new_CLASSNAME(soap, 100), 100) to create 100 pointers to 100 instances of CLASSNAME.
The gSOAP tools also generate deep copy operations for you: CLASSNAME::soap_dup(struct soap*) creates a deep copy of the object and allocates it in a another soap context that you provide as argument. Use NULL as this argument to allocate unmanaged deep copies (but these cannot have pointer cycles!). Then delete unmanaged copies with CLASSNAME::soap_del() for deep deletion of all members and then delete the object itself.
See Memory management in C++ for more details. Use gSOAP 2.8.39 and greater.

Resources