Sonar Duplication is not working as expected? - sonarqube

Am trying to show someone over here how good I find the sonar
tool...
then I wrote a small java project and defined many intentionally smelly methods,
2 of those are exactly the same (copy+paste) do1 and do2
surprisenly, after running the sonnar, there is no duplication error nor warnings...
public void do1() {
for (int i = 0; i < 10; i++) {
if (i != 0) {
System.out.println("Hello");
System.out.println(new Date());
}
}
}
public void do2() {
for (int i = 0; i < 10; i++) {
if (i != 0) {
System.out.println(new Date());
System.out.println("Hello");
}
}
}
what is the criteria for a java project to raise a warning on duplicates then?

Your methods are too short to show up as duplicated. Per the docs,
There should be at least 10 successive and duplicated statements whatever the number of tokens and lines.

Related

Kinect Record Only When One Body/Skeleton Is in the Frame

I need to write a program that records the frames, but only when one skeleton/body is in the frame. I looked at the bodyCount method, but it always gives a value of 6 (useless). One thing I tried to do is shown below. This code basically shows the index at which the body being tracked is stored. But, I still can't figure out how to know if there is one or more bodies in the frame.
I would really appreciate any help.
Thanks in advance.
private void Reader_FrameArrived(object sender, BodyFrameArrivedEventArgs e){
using (BodyFrame bodyFrame=e.FrameReference.AquireFrame()){
if (bodyFrame!=null){
if(this.bodies==null){
this.bodies=new Body[bodyFrame.BodyCount];
}
body.Frame.GetAndRefreshBodyData(this.bodies)
for(int i=0; i<6;i++){
if(this.bodies[i].IsTracked){
Console.WriteLine("Tracked"+i)
}
}
}
}
}
Just check the IsTracked property of each body, and store the number of tracked skeleton in a single variable. If this number is equal to 1, there is just one single skeleton tracked, and you can start your recording.
private Body[] bodies = null;
[...]
private void Reader_FrameArrived(object sender, BodyFrameArrivedEventArgs e)
{
bool dataReceived = false;
using (BodyFrame bodyFrame = e.FrameReference.AcquireFrame())
{
if (bodyFrame != null)
{
if (this.bodies == null)
{
this.bodies = new Body[bodyFrame.BodyCount];
}
// The first time GetAndRefreshBodyData is called, Kinect will allocate each Body in the array.
// As long as those body objects are not disposed and not set to null in the array,
// those body objects will be re-used.
bodyFrame.GetAndRefreshBodyData(this.bodies);
dataReceived = true;
}
}
if (dataReceived)
{
int trackedBodyCount = 0;
for (int i=0; i<this.bodies.Length; ++i)
{
if(this.bodies[i].IsTracked) {
trackedBodyCount += 1;
}
}
if (trackedBodyCount == 1)
{
// One skeleton is tracked
}
}
}

Logic Error in Player Controls in Greenfoot

Recently, I've been using Greenfoot, and I wanted to make a simple top-down/bullet-hell shooter. Everything was going smoothly until I tried some of the movement. It's simple enough with good old "arrow keys to move, space to shoot", but the problems show up when I try to move diagonally up-left or down-right and shoot at the same time. I can only do one at a time. I noticed that the directions are related by their location in the else-if calls, but that got me no where. I've also tried moving the code around, replacing the fire() call in act; with the if check entirely, but nothing has changed it.
import greenfoot.*;
/**
* Write a description of class PlayerShip here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class PlayerShip extends SmoothMover
{
private int stepSize = 4;
private boolean tiltLeft = false;
private boolean tiltRight = false;
private int tiltFrame = 1;
private int flameFrame = 0;
private final int COOLDOWN = 20;
private int armsCool = 0;
public PlayerShip()
{
}
/**
* Act - do whatever the PlayerShip wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
setImage();
if(Greenfoot.isKeyDown("left") && Greenfoot.isKeyDown("right"))
{
tiltFrame = 1;
}
move();
fire();
armsCool ++;
}
public void setImage()
{
if(Greenfoot.isKeyDown("up"))
{
setLocation(getX(), getY() - stepSize - 2);
}
else if(Greenfoot.isKeyDown("down"))
{
setLocation(getX(), getY() + stepSize + 2);
}
if (Greenfoot.isKeyDown("left")) {
setLocation(getX() - stepSize, getY());
tiltLeft = true;
if(tiltFrame == 1)
{
setImage("LeftTilt1.png");
tiltFrame ++;
}
else if(tiltFrame == 2)
{
setImage("LeftTilt2.png");
tiltFrame++;
}
else if(tiltFrame == 3)
{
setImage("LeftTilt3.png");
tiltFrame++;
}
else
{
if(flameFrame == 1)
{
setImage("LeftTilt.png");
flameFrame --;
}
else
{
setImage("LeftTiltAlt.png");
flameFrame ++;
}
}
}
else if (Greenfoot.isKeyDown("right")) {
setLocation(getX() + stepSize,getY());
tiltRight = true;
if(tiltFrame == 1)
{
setImage("RightTilt1.png");
tiltFrame ++;
}
else if(tiltFrame == 2)
{
setImage("RightTilt2.png");
tiltFrame++;
}
else if(tiltFrame == 3)
{
setImage("RightTilt3.png");
tiltFrame++;
}
else
{
if(flameFrame == 1)
{
setImage("RightTilt.png");
flameFrame --;
}
else
{
setImage("RightTiltAlt.png");
flameFrame ++;
}
}
}
else
{
tiltFrame = 1;
tiltLeft = false;
tiltRight = false;
if(flameFrame == 1)
{
setImage("PlayerShip2.png");
flameFrame --;
}
else
{
setImage("PlayerShip.png");
flameFrame ++;
}
}
}
private void fire()
{
if(Greenfoot.isKeyDown("space") && (armsCool >= COOLDOWN))
{
getWorld().addObject(new PlayerBasicBullet(new Vector(12, 5), 251), this.getX(), this.getY());
Battleground.bulletsOnScreen ++;
armsCool = 0;
}
}
}
The move(); method and Vector class are separate and just for smoother movement. I can provide those too, but there shouldn't be anything in there that messes with the controls.
A slightly modified version of the code works fine on my machine. There's two possibilities that I can think of:
Your setImage calls (which I commented out, because I don't have those images) could be throwing an exception, in which case the fire() method wouldn't be reached. Seems unlikely, though, as this would happen even without diagonal movement, and you'd see an exception in the terminal. So, much more likely:
Your keyboard may not be able to register those particular three-key combinations. Three ways to test this:
a. Try this keyboard ghosting demo (click the keyboard at the top of the page) and see if it can register all the keys.
b. load the Asteroids scenario from the book examples and see if you can shoot bullets while accelerating and steering.
c. You could just change "space" in your code to, say, "x" and see if works with that key.
Otherwise, I'm at a loss, unless there is code elsewhere in the scenario causing a problem.

Prove OrganizationServiceProxy is not Thread Safe

I want to prove that re-using instances of OrganizationServiceProxy between threads will cause problems.
This console app does not have a problem re-using the same instance of OrganizationServiceProxy between threads:
class Program
{
private static OrganizationServiceProxy Service { get; set; }
static void Main(string[] args)
{
Connect(); // Initializes Service
for (int i = 0; i < 100; i++)
{
int index = i;
Task.Run(() =>
{
for (int i2 = 0; i2 < 10; i2++)
{
try
{
Console.WriteLine("Creating" + index);
Entity record = new Entity("account");
record.Id = new Guid("4986e130-45f7-e411-9454-00155d91de01");
record["name"] = index + " - " + i2;
Service.Update(record);
Console.WriteLine("Created" + index);
}
catch (Exception e)
{ }
}
});
}
Console.ReadLine(); // the name of the record ends up as 99 - 9, which is right
}
/* Initialize Service */
private static bool Connect()
{
try
{
ClientCredentials cred = new ClientCredentials();
cred.UserName.UserName = #"r";
cred.UserName.Password = #"";
IServiceManagement<IOrganizationService> serviceManagement = ServiceConfigurationFactory.CreateManagement<IOrganizationService>(new Uri(#"/XRMServices/2011/Organization.svc"));
Service = new OrganizationServiceProxy(serviceManagement, cred);
var who = new Microsoft.Crm.Sdk.Messages.WhoAmIRequest(); // used to test the connection
var whoResponse = (Microsoft.Crm.Sdk.Messages.WhoAmIResponse)Service.Execute(who); // this fails if not connected
}
catch (Exception e)
{
Console.WriteLine("Connecting to CRM.\n" + e.Message + ((e.InnerException != null) ? "\n" + e.InnerException.Message : ""));
return false;
}
return true;
}
}
The SDK states that any instance members of OrganizationServiceProxy are not guaranteed to be thread safe.
How can I cause a problem with an OrganizationServiceProxy shared between threads?
What kinds of problem are to be expected?
I'm not sure I know the specific answer to your question, but something that is marked as not guaranteed of being thread-safe just means exactly that: It may be safe, but the author has not tested for it or specifically written any thread-safe code for those classes, and thus cannot guarantee thread safety.
I do know that thread-safety definitely comes into play with Plugins on the server. This is why you are not supposed to use local fields in a Plugin class. The Plugin engine re-uses the instances of your Plugin class instead of re-instantiating them for each execution. This means it is possible that your Plugin could execute with "old data" in those local fields that was used by the last thread, which could obviously cause all kinds of problems.

Throughput measure

I have to implement a limitation algorithm in order to avoid to reach a throughput limit imposed by the service I'm interacting with.
The limit is specified as «N requests over 1 day» where N is of the order of magnitude of 10^6.
I have a distributed system of clients interacting with the service so they should share the measure.
An exact solution should involve to record all the events and than computing the limit «when» the event of calling the service occur: of course this approach is too expensive and so I'm looking for an approximate solution.
The first one I devised imply to discretize the detection of the events: for example maintaing 24 counters at most and recording the number of requests occurred within an hour.
Acceptable.
But I feel that a more elegant, even if leaded by different «forces», is to declinate the approach to the continuum.
Let's say recording the last N events I could easily infer the «current» throughput. Of course this algorithm suffer for missing consideration of the past events occurred the hours before. I could improve with with an aging algorithm but… and here follow my question:
Q: «There's an elegant approximate solution to the problem of estimating the throughput of a service over a long period with and high rate of events?»
As per my comments, you should use a monitor and have it sample the values every 15 minutes or something to get a reasonable guess of the number of requests.
I mocked something up here but haven't tested it, should give you a starter.
import java.util.LinkedList;
import java.util.Queue;
import java.util.Timer;
import java.util.TimerTask;
public class TestCounter {
private final Monitor monitor;
private TestCounter() {
monitor = new Monitor();
}
/** The thing you are limiting */
public void myService() {
if (monitor.isThresholdExceeded()) {
//Return error
} else {
monitor.incremenetCounter();
//do stuff
}
}
public static void main(String[] args) {
TestCounter t = new TestCounter();
for (int i = 0; i < 100000; i++) {
t.myService();
}
for (int i = 0; i < 100000; i++) {
t.myService();
}
}
private class Monitor {
private final Queue<Integer> queue = new LinkedList<Integer>();
private int counter = 1;
/** Number of 15 minute periods in a day. */
private final int numberOfSamples = 76;
private final int threshold = 1000000;
private boolean thresholdExceeded;
public Monitor() {
//Schedule a sample every 15 minutes.
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
sampleCounter();
}
}, 0l, 900000 /** ms in 15 minutes */
);
}
/** Could synchroinise */
void incremenetCounter() {
counter++;
}
/** Could synchroinise */
void sampleCounter() {
int tempCount = counter;
counter = 0;
queue.add(tempCount);
if (queue.size() > numberOfSamples) {
queue.poll();
}
int totalCount = 0;
for (Integer value : queue) {
totalCount += value;
}
if (totalCount > threshold) {
thresholdExceeded = true;
} else {
thresholdExceeded = false;
}
}
public boolean isThresholdExceeded() {
return thresholdExceeded;
}
}
}

Java for loop doesnt execute

I am having problems with my remote device discovery code for bluetooth scanning.
It scans, and prints the MAC addresses if i uncomment the "system.out.print(devicesDiscovered);
But i want to be able to extract each MAC address from the Vector and place it in a String.
I have two differant FOR loops to do this, but neither of them seem to be executing.
Code:
import java.io.IOException;
import java.util.List;
import java.util.Vector;
import javax.bluetooth.*;
public class BluetoothDeviceDiscovery {
public static final Vector/*<RemoteDevice>*/ devicesDiscovered = new Vector();
public static void main() throws IOException, InterruptedException {
final Object inquiryCompletedEvent = new Object();
devicesDiscovered.clear();
final DiscoveryListener listener = new DiscoveryListener() {
public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
devicesDiscovered.addElement(btDevice);
//
String testingAgain = devicesDiscovered.toString();
System.out.println("What?? : " + testingAgain);
/*
* As far as i know, the following two FOR loops do the same thing
* But both of them are not being executed...
*/
//Its not executing this...
for(int i=0; i< devicesDiscovered.size(); i++) {
System.out.println("test if this gets output");
String test = (String) devicesDiscovered.elementAt(i);
System.out.println("Test: " + test);
}
//Its not executing this....
for(int i=0; i> ((List) btDevice).size(); i++){
System.out.println("test if this gets output 1");
String testing = (String) devicesDiscovered.toString();
System.out.print("Test1: " + testing);
}
//Prints the MAC addresses [macaddress, macaddress, macaddress, etc]
// System.out.println(devicesDiscovered);
/*
* Now need to extract each macaddress from devicesDiscovered
* and convert from a Vector to a String
*/
}
public void inquiryCompleted(int discType) {
System.out.println("Device Inquiry completed!");
synchronized(inquiryCompletedEvent){
inquiryCompletedEvent.notifyAll();
}
}
public void serviceSearchCompleted(int transID, int respCode) {
}
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
}
};
synchronized(inquiryCompletedEvent) {
boolean started = LocalDevice.getLocalDevice().getDiscoveryAgent().startInquiry(DiscoveryAgent.GIAC, listener);
if (started) {
System.out.println("wait for device inquiry to complete...");
inquiryCompletedEvent.wait();
System.out.println(devicesDiscovered.size() + " device(s) found");
}
}
}
}
Can anyone spot any reason(s) as to why these two for loops are not working?
Thanks a lot
- Ryan
In this line
//Its not executing this....
for(int i=0; i > ((List) btDevice).size(); i++) {
You have turned the > the wrong way... try
for(int i=0; i < ((List) btDevice).size(); i++) {
instead.
(The reason it doesn't iterate, is because the initial value, 0, is not greater than the size of the list!)
In your first loop:
//Its not executing this...
for(int i=0; i< devicesDiscovered.size(); i++) {
System.out.println("test if this gets output");
it must be the case that devicesDiscovered is empty. I suggest you do
System.out.println(devicesDiscovered.size());
before the loop to debug.
The execution of your code in my machine is the following:
BlueCove version 2.1.0 on bluez
wait for device inquiry to complete...
What?? : [...]
test if this gets output
Test: ...
Device Inquiry completed!
1 device(s) found
BlueCove stack shutdown completed
With the following for loop:
for(int i=0; i< devicesDiscovered.size(); i++)
{
System.out.println("test if this gets output");
String test = (String) devicesDiscovered.elementAt(i).toString();
System.out.println("Test: " + test);
}
I've noticed that you were testing which one of the for loops was generating the output that you wanted. I can say that the above one works but the second generates an exception. You are trying to cast a RemoteDevice object to a List and iterate through it (for(int i=0; i < ((List) btDevice).size(); i++)). That's the reason for not working and therefore the exception.

Resources