Queue Abstract Data Type - Float Elements - language-agnostic

How would you design a queue abstract data type for float elements in C (or any preferred language), with operations for enqueue, dequeue, and empty? The dequeue operation should remove the element and returns its value.

Using Java, I came up with a quick and dirty solution as follows:
public class QueueOps {
private ArrayList<Float> queueReference;
public QueueOps(){
queueReference = new ArrayList<Float>();
}
public void enqueue(float number){
queueReference.add(number);
}
public float dequeue(){
float number = queueReference.get(0);
queueReference.remove(0);
queueReference.trimToSize();
return number;
}
public void empty(){
queueReference.clear();
}
}

Related

call function of class on instance of class

I have some code that generates answers based on the user input. But in somecases i need to update the values later by calling SetAnswers But when i compile my code i get the following error:
NullReferenceException: Object reference not set to an instance of an object
I get this error on the line marked by the arrow.
See below for my code:
public class Generate_Questions : MonoBehaviour{
public Question q5, q4;
void Start(){
q4 = create_question("Select object to edit", EXTERNAL);
Visual_Question vq1 = new Visual_Question(1, q4, new vector(1,1,1), Ui, Canvas);
vq1.draw_question();
}
void Update(){
}
public class Visual_Question : Generate_Questions{
public Visual_Question(int order_id, Question q, Vector2 loc, Dictionary<string, RectTransform> ui, RectTransform canvas){
}
public void draw_question(){
q4.SetAnswers(new Answer[]{ <--------- this generates the error.
new Answer(null, "Select an option")
});
}
}
public class Question{
public string text;
public int answers_loc;
public List<Answer> answers;
public Question(string q_text, int answers_loc){
answers = new List<Answer>();
this.text = q_text;
this.answers_loc = answers_loc;
}
public void SetAnswers(Answer[] c_answers){
foreach(Answer answer in c_answers){
this.answers.Add(answer);
}
}
public bool CheckIfAnswersAvailable(){
if(answers.Count > 0){
return true;
}else{
return false;
}
}
public int QuestionLocation(){
return answers_loc;
}
}
public Question create_question(string text, int a_type){
Question Q = new Question(text, a_type);
return Q;
}
public interface IAnswer{
string GetText();
string GetDataType();
object GetValue();
Question GetNextQuestion();
}
public class Answer : IAnswer{
public string text;
public Question next = null;
public int? action = null;
public Element obj = null;
public string property = null;
public float? value = null;
public Answer(Question next, string text){
this.text = text;
this.next = next;
}
public Answer(Question next, string text, Element obj, int? action){
this.action = action;
this.text = text;
this.next = next;
this.obj = obj;
}
public Answer(Question next, string text, Element obj, int? action, string property, float? value){
this.action = action;
this.next = next;
this.text = text;
this.obj = obj;
this.property = property;
this.value = value;
}
public string GetText(){
return text;
}
public string GetDataType(){
throw new System.NotImplementedException();
}
public object GetValue(){
return value;
}
public Question GetNextQuestion(){
return next;
}
}
}
how would i go about fixing this problem? I am a complete newbie to c#. So my question may be already answered but i just dont know what i am looking for.
I assume that IAnswer[] is an interface and since you are trying to initialize an abstract object you get that runtime exception
NullReferenceException: Object reference not set to an instance of an object
if you want to create instance of IAnswer object you have to restructure it like class or structure.
Your class Visual_Question derives from Generate_Questions, so the member q4 that you use en draw_question is not initialized. This is not the member of Generated_Questions but a member of Visual_Question that is not initialized.
In Generate_Questions you are creating a new instance of Visual_Question and then immediately calling draw_question on that new instance. You now have 2 instances of a question (both derive from Generate_Questions), but only one of them has had the Start method, which initializes q4 called. If, however, you attempt to call Start from your second instance, you're going to find yourself in an infinite series of recursive calls and quickly crash with a different error (a stack overflow in this case).
One issue with the current code is that Generate_Questions sounds more like an action than a class. I'd suggest removing the inheritance from Visual_Question and make that an interface that you would implement on Question. Question should probably have the create_question method removed. That probably belongs in a MonoBehavior script (technically it's a factory method -- look up the factory pattern -- I'm not going to go into it here since this is a beginner topic).
Something like (obviously not complete):
public class Generate_Questions : MonoBehaviour
{
private IVisualQuestion q4;
void Start()
{
q4 = new Question("Select object to edit", EXTERNAL);
q4.DrawQuestion(new vector(1,1,1), Ui, Canvas)
}
void Update() {}
}
public interface IVisualQuestion
{
void DrawQuestion(Vector2 loc, Dictionary<string, RectTransform> ui, RectTransform canvas);
}
public class Question : IVisualQuestion
{
// ... insert the Question constructor and code here ...
// Implement VisualQuestion interface
public void DrawQuestion(Vector2 loc, Dictionary<string, RectTransform> ui, RectTransform canvas)
{
this.SetAnswers(new Answer[]{new Answer(null, "Select an option")});
}
}
In general, you probably don't need inheritance. As you learn more C#, you'll discover that when inheritance is going to help it will be clear. More often than not, using an interface is a far better and flexible approach. As a commenter noted, you probably don't want to inherit from MonoBehavior. You really only need that for classes that the Unity Engine is going to directly handle.
Another note: the convention in C# is to name methods, variables, etc. in PascalCase, not using underscores to separate words.

how to mock "this" of a class using powermock or mockito

Class that i want to mock:
TestClass.java
public class testClass(){
public String getDescription(String input){
String value = this.getDetails(input); // i am not going to change this line, hence want to mock this.
//below this i have some complexity logic, which i would like to fix cyclomatic complexity issue
}
private String getDetails(String input){
return "More details for the "+input;
}
}
My questions is how do i mock "this.getDetails(input)" to return some string for testing purpose?
If you've got a class that is big and complex enough that you need to mock a small piece of it, take that as a hint that you're violating the Single Responsibility Principle and properly split up the classes. If you use dependency injection, you can then supply whatever implementation you'd like.
public class TestClass {
/**
* Computes a detail string based on an input. Supply this in the constructor
* for full DI, relax visibility, or add a setter.
*/
private final Function<String, String> detailFunction;
public String getDescription(String input){
String value = detailFunction.apply(input);
// ...
}
}
As a lightweight alternative, you can test an override or spy of your actual class.
#Test public void testTestClassWithOverride() {
TestClass instanceUnderTest = new TestClass() {
#Override public String getDescription(String input) {
return "Predictable value";
}
};
// test your instanceUnderTest here
}
#Test public void testTestClassWithSpy() {
TestClass spyUnderTest = Mockito.spy(new TestClass());
doReturn("Predictable value").when(spyUnderTest).getDescription(anyString());
// test your spyUnderTest here
}
Bear in mind that, though this is an option for you, it shouldn't be your first option: Rather than testing your actual class, you're testing a one-off variant of it, and you've made it so other consumers can subclass your TestClass as well. If possible, write the flexibility you need into the class itself and treat your test as a consumer that plays by the same rules.
First of all, it is a bad practice to make a so-called "partials mocks". This illustrates that your code doesn't follow single responsibility principle that leads to your code being not (or hardly) testable.
I would suggest you to extract getDescription method from your class and use it indirectly via dependency inversion or more concrete - dependency injection (for instance by employing Spring Framework):
public class TestClass() {
private DetailsServiceProvider detailsServiceProvider;
public TestClass(DetailsServiceProvider detailsServiceProvider) {
this.detailsServiceProvider = detailsServiceProvider;
}
public String getDescription(String input) {
String value = detailsServiceProvider.getDetails(input); // i am not going to change this line, hence want to mock this.
//below this i have some complexity logic, which i would like to fix cyclomatic complexity issue
}
}
public interface DetailsServiceProvider {
String getDetails(String input);
}
public class DetailsServiceProviderImpl implements DetailsServiceProvider{
#Override
public String getDetails(String input) {
return "More details for the "+input;
}
}
Then in your test, you could simply:
#Test
public void test() {
DetailsServiceProvider mockedProvider = Mockito.mock(DetailsServiceProvider.class);
//TODO: add scenarios for the mocked object
TestClass target = new TestClass(mockedProvider);
String description = target.getDescription();
//TODO: add assertions
}
If you do not want to struggle with the preferred approach you could use #Spy in Mockito. This will create exactly what you want - a partial mock for your object where part of the methods will be real and another part - mocks:
#Test
public void test() {
TestClass partialMockedObject = Mockito.spy(new TestClass());
Mockito.doReturn("test details").when(partialMockedObject).getDetails();
String description = partialMockedObject.getDescription();
//TODO: add assertions
}
Again, this method is not desired but can be used if no other options are given. Note that this requires getDetails() to be visible in tests, meaning that the private modifier won't work here.

Hibernate: Storing an fixed length array in one database table row

I have been trying to find a solution to store a fixed length array as a property of an object using hibernate in the same DB table as the object not using a BLOB for the array.
I currently have a class ProductionQCSession which looks like
#Entity
public class ProductionQCSession extends IdEntity {
private Long id;
private Float velocity;
private Float velocityTarget;
private Float[] velocityProfile;
public ProductionQCSession() {
}
#Id #GeneratedValue(strategy=GenerationType.AUTO)
#Override
public Long getId() {
return id;
}
#SuppressWarnings("unused")
public void setId(Long id) {
this.id = id;
}
#Basic
public Float getVelocity() {
return velocity;
}
public void setVelocity(Float velocity) {
this.velocity = velocity;
}
#Basic
public Float[] getVelocityProfile() {
return velocityProfile;
}
public void setVelocityProfile(Float[] velocityProfile) {
this.velocityProfile = velocityProfile;
}
}
Ideally I would like the DB structure to be
id|velocity|VPValue0|VPValue1|VPValue2|VPValue3|...
21| 2.1| 0.1| 0.2| -0.1| 0.3|...
I know with a high certainty that we always have 15 items in the velocityProfile array and those values as just as much properties of the object as any other property therefore I think it makes sense to add them to the database table schema, if it's possible. I would prefer to have it this way as it would be easy to get a overview of the data just doing a raw table print.
The current code just stores the array data as a BLOB.
I have looked http://ndpsoftware.com/HibernateMappingCheatSheet.html mapping cheat sheet, but could not seem to find any good solution.
I'm I just trying to do something nobody else would do?
Essentially, you're trying to have a multi-value field, which is not a relational database concept. A normalized solution would put those into a child table, which Hibernate would let you access directly from the parent row (and return it as a collection).
If you are adamant that it should be in a single table, then you'll need to create 15 individual columns....and hope that in the future you don't suddenly need 16.
The solution ended up being using the standardised method of using a child table even though it makes the data analysis slightly more complicated. The following code was used.
#ElementCollection
#CollectionTable(name ="QCVelocityProfile")
public List<Float> getVelocityProfile() {
return velocityProfile;
}
public void setVelocityProfile(List<Float> velocityProfile) {
this.velocityProfile = velocityProfile;
}

sequentially deserialize using Jackson

I have a value object serialized and deserialized using Jackson.
The VO has two fields: x and y. But invoking setY makes sense only when x is set. Is there any way I can make sure that setX is invoked earlier than setY during de-serialization?
You can do it only by implementing custom deserializer for your POJO (VO) class. Let assume that you POJO class looks like this:
class Point {
private int x;
private int y;
//getters, setters, toString
}
Now, you can implement deserializer. You can do it in this way:
class PointJsonDeserializer extends JsonDeserializer<Point> {
#Override
public Point deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
InnerPoint root = jp.readValueAs(InnerPoint.class);
Point point = new Point();
point.setX(root.x);
point.setY(root.y);
return point;
}
private static class InnerPoint {
public int x;
public int y;
}
}
After that, you have to tell Jackson to use above deserializer. For example, in this way:
#JsonDeserialize(using = PointJsonDeserializer.class)
class Point {
...
}
For me, your setY brakes setter method responsibility. You should avoid situation like that where you hide class logic in setter method. Better solution is creating new method for calculations:
point.setX(10);
point.setY(11);
point.calculateSomething();

How to use the same #jsonproperty name int following example?

At any point of time i will be setting only one setter method but the JsonProperty name should be same for both . when i am compiling this i am getting an exception. How to set the same name for both .?
public String getType() {
return type;
}
#JsonProperty("Json")
public void setType(String type) {
this.type = type;
}
public List<TwoDArrayItem> getItems() {
return items;
}
#JsonProperty("Json")
public void setItems(List<TwoDArrayItem> items) {
this.items = items;
}
Jackson tends to favor common scenarios and good design choices for annotation support.
Your case represents a very uncommon scenario. You have one field having two different meanings in different contexts. Typically this would not be a favourable data format since it adds messy logic to the consumer on the other end...they need to divine what the "Json" property should mean in each case. It would be cleaner for the consumer if you just used two different property names. Then it would be sufficient to simply check for the presence of each property to know which alternative it's getting.
Your Java class also seems poorly designed. Classes should not have this type of context or modes, where in one context a field is allowed, but in another context it's not.
Since this is primarily a smell with your design, and not serialization logic, the best approach would probably be to correct your Java class hierarchy:
class BaseClass {
}
class SubClassWithItems {
public List<TwoDArrayItem> getItems() {
return items;
}
#JsonProperty("Json")
public void setItems(List<TwoDArrayItem> items) {
this.items = items;
}
}
class SubClassWithType {
public String getType() {
return type;
}
#JsonProperty("Json")
public void setType(String type) {
this.type = type;
}
}
That way your class does not have a different set of fields based on some runtime state. If runtime state is driving what fields your class contains, you're not much better off than with just a Map.
If you can't change that, you're left with custom serialization.