Detection of duplicate code - machine-learning

I am working on a project where i want to detect duplicate code.
Example:
function sumOfTwoNumbers(a, b){
return a + b;
}
function AddTwoNumbers(a, b){
var x = a;
var y = b;
return x + y;
}
These both function return sum of 2 numbers, as these both functions return same result, is there any way to detect that these functions are similar.
Can u please suggest what technology should i learn to solve this problem.
Thanks in advance

Related

Optional positional parameter in Dart

I'm studying recursion and I wrote this method to calculate the N° number of the Fibonacci series:
fibonacci(int n, Map memo) {
if (memo.containsKey(n)) return memo[n]; // Memo check
if (n <= 2) return 1; // base case
// calculation
memo[n] = fibonacci(n - 1, memo) + fibonacci((n - 2), memo);
return memo[n];
}
I think it doesn't need to be explained, my problem is just how to call this function from the main, avoiding providing an empty Map.
this is how I call the function now:
fibonacci(n, {});
But I would rather prefer to call it just like this:
fibonacci(n);
The canonical approach is to make memo optional, and use a fresh map if the memo argument is omitted. Because you want to change and update the map, you can't use a default value for the parameter, because default values must be constant, and constant maps are not mutable.
So, written very concisely:
int fibonacci(int n, [Map<int, int>? memo]) {
if (n <= 2) return 1;
return (memo ??= {})[n] ??= fibonacci(n - 1, memo) + fibonacci(n - 2, memo);
}
The ??= operator assigns to the right-hand side if the value is null.
It's used both to initialize memo to a new map if the argument was omitted,
and to update the map if a cached value wasn't present.
I'd actually reconsider using a map. We know that the Fibonacci computation will compute a value for every prior number down to 1, so I'd just use a list instead:
int fibonacci(int n, [List<int?>? memo]) {
if (n <= 2) return 1;
return (memo ??= List<int?>.filled(n - 2))[n - 3] ??=
fibonacci(n - 1, memo) + fibonacci(n - 2, memo);
}
That should work just like the map.
(I subtract 3 from n when doing the lookup because no value below 3 needs the list - it's handled by the prior if).
There are multiple ways to do it. This is my personal favorite, because it also limits the function that is only used for internal means and it doesn't have the need to check every recursion, as you already know there is a map provided:
int fibonacci(int n) {
return _fibonacci(n, {});
}
int _fibonacci(int n, Map<int, int> memo) {
if (n <= 2) return 1; // base case
final previouslyCalculated = memo[n]; // Memo check
if(previouslyCalculated != null) {
return previouslyCalculated;
}
// calculation
final next = _fibonacci(n - 1, memo) + _fibonacci((n - 2), memo);
memo[n] = next;
return next;
}
void main() {
print(fibonacci(4));
}
As Dart does not support overloading, if you actually need both versions to be publicly available (or want both private) you would have to pick different names.
Please note that I added proper types to your methods and cleaned them up a bit for everything that would not compile once proper types are used. Make sure you always use proper types and don't rely on dynamic to somehow works it's magic. The compiler can only help you, if you are explicit about what you want to do. Otherwise they can only nod and let you run into any mistake you may have made. Be smart, let your compiler help, it will catch a lot of errors for you at compile time that you would otherwise have to spent countless hours on debugging.
This is the solution I've found so far but looks very verbose and inelegant:
fibonacci(int n, [Map<int, int>? memo]) {
memo == null ? memo = {} : null; // null check
if (memo.containsKey(n)) return memo[n];
if (n <= 2) return 1;
memo[n] = fibonacci(n - 1, memo) + fibonacci((n - 2), memo);
return memo[n];
}
In this way I can call just:
fibonacci(n);

How to assign results of futures in Dart depending on which future produced them?

In Dart, I want to run several costly functions, which are independent of each other, and assign the results to my variables, depending on which function produced them. Roughly a parallel version of this:
double x = getX();
double y = getY();
I'm thinking of something like this:
double x, y;
Future.wait([
futureGetX(),
futureGetY()
]).then((List results) {
results.foreach((r) {
// if(r is produced by futureGetX) x = r;
// if(r is produced by futureGetY) y = r;
});
});
and I don't know how to implement this is produced by part. A way would be to wrap the result of each function in a different class and, in the then part, check the class of the result:
if(r is wrapperForX) x = r.getValue();
if(r is wrapperForY) y = r.getValue();
but this seems very inelegant to me. Any suggestions?
Untested, but I think I got this. :)
Use closures:
Future.wait([
() => { x = await futureGetX()},
() => { y = await futureGetY()},
]);
Thanks to Randal I found a solution:
Future.wait([
() async { x = await futureGetX(); } (),
() async { y = await futureGetY(); } ()
]);
To wait for Futures in parallel, you use Future.wait, as you already noticed.
The results in the list returned (asynchronously) by Future.wait are in the same order as the original futures, so instead of using forEach you can just do:
x = results[0];
y = results[1];
Another way would be to use FutureGroup from async package, FIFO behavior for the result list is documented: https://www.dartdocs.org/documentation/async/1.13.3/async/FutureGroup-class.html

Is there anything like a struct in dart?

In javascript it always bothered me people use objects as vectors like {x: 1, y: 2} instead of using an array [1,2]. Access time for the array is much faster than the object but accessing by index is more confusing especially if you need a large array. I know dart has fixed arrays but is there a way to name the offsets of an array like you would a struct or a tuple/record in another language? Define enum/constants maybe?
I'd want something like
List<int> myVector = new List([x,y]);
myVector.x = 5;
is there an equivalent or idiomatic way to do this?
That sounds like a class.
class MyVector {
int x;
int y;
MyVector(this.x, this.y);
}
There is no simpler and more efficient way to create a name-indexed structure at runtime. For simplicity you could usually use a Map, but it's not as efficient as a real class.
A class should be at least as efficient (time and memory) as a fixed length list, after all it doesn't have to do an index bounds check.
In Dart 3.0, the language will introduce records. At that point, you can use a record with named fields instead of creating a primitive class:
var myVector = (x: 42, y: 37);
print(myVector.x);
A record is unmodifiable, so you won't be able to update the values after it has been created.
For me, i see 2 way to do this. I will sort by best in my point of view
Class based method
Here, the approach is to encapsulate your need, in a dedicated object
Pros:
It's encapsultate
You can propose several way to access variable, depend of the need
You can extend functionality without break everything
I love it :p
Cons
More time spend to create class, etc.
Do you really need what i say in pros ?
Maybe weird for js people
example :
class Vector {
int x;
int y;
static final String X = "x";
static final String Y = "y";
Vector({this.x, this.y});
Vector.fromList(List<int> listOfCoor) {
this.x = listOfCoor[0];
this.y = listOfCoor[1];
}
// Here i use String, but you can use [int] an redefine static final member
int operator[](String coor) {
if (coor == "x") {
return this.x;
} else if (coor == "y") {
return this.y;
} else {
// Need to be change by a more adapt exception :)
throw new Exception("Wrong coor");
}
}
}
void main() {
Vector v = new Vector(x: 5, y: 42);
Vector v2 = new Vector.fromList([12, 24]);
print(v.x); // print 5
print(v["y"]); // print 42
print(v2.x); // print 12
print(v2[Vector.Y]); // print 24
}
Enum based method:
You can also defined a "enum" (actually not really implement but will be in the future version) that will contains "shortcut" to your value
Pros
More simple to implement
Is more like your example ;p
Cons
Less extendable
i think is not very pretty
Not OOP think
example:
class Vector {
static final int x = 0;
static final int y = 1;
}
void main() {
List<int> myVector = new List(2);
myVector[Vector.x] = 5;
myVector[Vector.y] = 42;
}
Make your choice ;p
This is only possible with a class in Dart.
There are some open feature requests at http://dartbug.com
introduce struct (lightweight class)
Give us a way to structure Bytedata
If you have reasonably big data structure, you can use "dart:typed_data" as a model and provide lightweight view for the stored data. This way the overhead should be minimal.
For example, if you need 4X4 matrix of Uint8 values:
import "dart:typed_data";
import "dart:collection";
import "package:range/range.dart";
class Model4X4Uint8 {
final Uint8List _data;
static const int objectLength = 4 * 4;
final Queue<int> _freeSlotIndexes;
Model4X4Uint8(int length): _data = new Uint8List((length) * objectLength),
_freeSlotIndexes = new Queue<int>.from(range(0, length));
int get slotsLeft => _freeSlotIndexes.length;
num operator [](int index) => _data[index];
operator []=(int index, int val) => _data[index] = val;
int reserveSlot() =>
slotsLeft > 0 ? _freeSlotIndexes.removeFirst() : throw ("full");
void delete(int index) => _freeSlotIndexes.addFirst(index);
}
class Matrix4X4Uint8 {
final int offset;
final Model4X4Uint8 model;
const Matrix4X4Uint8(this.model, this.offset);
num operator [](int index) => model[offset + index];
operator []=(int index, int val) => model[offset + index] = val;
void delete() => model.delete(offset);
}
void main() {
final Model4X4Uint8 data = new Model4X4Uint8(100);
final Matrix4X4Uint8 mat = new Matrix4X4Uint8(data, data.reserveSlot())
..[14] = 10
..[12] = 256; //overlow;
print("${mat[0]} ${mat[4]} ${mat[8]} ${mat[12]} \n"
"${mat[1]} ${mat[5]} ${mat[9]} ${mat[13]} \n"
"${mat[2]} ${mat[6]} ${mat[10]} ${mat[14]} \n"
"${mat[3]} ${mat[7]} ${mat[11]} ${mat[15]} \n");
mat.delete();
}
But this is very low level solution and can easily create sneaky bugs with memory management and overflows.
You could also use an extension on List to create aliases to specific indexes.
Although it will be difficult to set up mutually exclusive aliases, in some cases, it may be a simple solution.
import 'package:test/test.dart';
extension Coordinates<V> on List<V> {
V get x => this[0];
V get y => this[1];
V get z => this[2];
}
void main() {
test('access by property', () {
var position = [5, 4, -2];
expect(position.x, 5);
expect(position.y, 4);
expect(position.z, -2);
});
}
The Tuple package https://pub.dev/packages/tuple might be what you are looking for when a class is too heavy.
import 'package:tuple/tuple.dart';
const point = Tuple2<int, int>(1, 2);
print(point.item1); // print 1
print(point.item2); // print 2

Converting CGPoint to GLKVector2 in Objective-C

Simple question. What is the best way to turn a CGPoint into a GLKVector?
These structures are identical so it would be nice to be able to reinterpret_cast or memcpy or something like that. My solution below works but hardly seems optimum. I'm creating a GLKVector2 on the stack assigning each member then returning this as a value which is then assigned to another GLKVector.
It's not going to break the bank or anything but there must be a neater way to do this?
GLKVector2 Vector2FromPoint(CGPoint point)
{
GLKVector2 v;
v.x = point.x;
v.y = point.y;
return v;
}
You could try using memcpy in a function like this:
bool vector2ToCGPoint(GLKVector2* s, CGPoint* d) {
memcpy(d, s, sizeof(*d));
}
but then it is probably better to have:
bool copyVector2ToCGPoint(GLKVector2* s, CGPoint* d) {
d.x = s.x;
d.y = s.x;
}
if you really want optimization, you could go for a macro:
#define copyS2D(S,D) (D.x = S.x, D.y = S.y)
so you can do:
CGPoint b;
GLKVector2 a;
vector2FromCGPoint(a, b);
of course, as you know, macros will not be that much type-safe...
GLKVector2 v = GLKVector2Make(point.x, point.y);

How to assemble an array(s) of continuous points for a contour line using Conrec

I have a Conrec nightmare. I am trying to implement contour lines in ActionScript using Conrec. I have looked at both the java and javascript implementation and am still stuck. These are found here: http://paulbourke.net/papers/conrec/
Conrec will take grid data and assemble continuous contour lines. The problem is that it does not necessarily draw those lines in a continuous fashion. For example, it will draw A->B and then C->B and then C->D instead of A, B, C, D, etc.
The javascript implementation seems to be accounting for this and serializing the instructions into an array of draw points. Which is what I too want to accomplish in the end. That is it takes the instructions from the core Conrec logic (eg: A->B, C->B, C->D, etc) and organizes it into an A, B, C, D series. I think it will also return the series as a multi-dimensional array to accommodate broken lines (eg: [[A, B, C, D], [E, F, G]]). This last functionality is what I need to do in Actionscript.
This last part is where I am stuck. Ignore Conrec for now (I have given up on finding an Actionscript implementation), how can I organize these instructions into a collection of serial points? When Conrec gives me "draw point from X->Y" how can I first check if X or Y are already in a series and append either X or Y (whichever is not in the series) into the series? AND if neither are in the series, start a NEW series with X, Y as the starting set. Then check subsequent instructions against all existing series and connect series if they now start and stop on the same point? Also, I need to be able to allow for a series to close itself (eg: A, B, C, A) -- a loop (is that even possible?!).
I hope this makes sense. I'm not sure if there is a technical term for what I want to do beyond "concatenation". I also hope someone out there has done this with Conrec and can give me some pointers.
In the meantime, I am going to continue to plug away at this and see if I can come up with something but I am not confident in my abilities. I would really be thankful for some veteran or professional advice.
PS:
If you know another way to draw contour lines from grid data, I am open to alternatives. But I have to be able to implement it in Actionscript.
Ok, here is my first attempt at getting what I need done. I am not terribly happy with the result, but it seems to work.
package {
import flash.display.Sprite;
public class lineSeriesPointConcat extends Sprite {
public function lineSeriesPointConcat() {
init();
}
//directions [X -> Y]
//case 1: both counterclockwise, result is counterclockwise
private var case1:Array = [
["G1", "F1"],
["F1", "E1"],
["D1", "C1"],
["C1", "B1"],
["B1", "A1"],
["E1", "D1"], //link
["G1", "A1"] //loop
];
//case 2: clockwise, counterclockwise, result is clockwise
private var case2:Array = [
["E2", "F2"],
["F2", "G2"],
["D2", "C2"],
["C2", "B2"],
["B2", "A2"],
["E2", "D2"], //link
["G2", "A2"] //loop
];
//case 3: both clockwise, result is clockwise
private var case3:Array = [
["E3", "F3"],
["F3", "G3"],
["A3", "B3"],
["B3", "C3"],
["C3", "D3"],
["E3", "D3"], //link
["G3", "A3"] //loop
];
//case 4: counterclockwise, clockwise, result is clockwise
private var case4:Array = [
["G4", "F4"],
["F4", "E4"],
["A4", "B4"],
["B4", "C4"],
["C4", "D4"],
["E4", "D4"], //link
["G4", "A4"] //loop
];
private var collectedSeries:Array = [];
private function init():void {
var directions:Array = case1.concat(case2.concat(case3.concat(case4)));
for each (var direction:Array in directions) {
connect(direction[0], direction[1]);
}
trace ("final series:\n\t" + collectedSeries.join("\n\t"));
}
private function connect(from:String, to:String):void {
var series:Array;
var seriesStart:String;
var seriesEnd:String;
var seriesIndex:int;
var n:int = collectedSeries.length;
var i:int;
for (i = 0; i < n; i++) {
series = collectedSeries[i];
seriesStart = series[0];
seriesEnd = series[series.length - 1];
if (seriesStart == to) {
seriesStart = from;
series.unshift(from);
break;
} else if (seriesStart == from) {
seriesStart = to;
series.unshift(to);
break;
} else if (seriesEnd == to) {
seriesEnd = from;
series.push(from);
break;
} else if (seriesEnd == from) {
seriesEnd = to;
series.push(to);
break;
}
}
if (i == n) {
//this is a new series segment
series = [from, to];
seriesStart = from;
seriesEnd = to;
collectedSeries.push(series);
}
for (var j:int = 0; j < n; j++) {
var compareSeries:Array = collectedSeries[j];
if (compareSeries == series) {
//don't compare the series to itself.
continue;
}
var compSeriesStart:String = compareSeries[0];
var compSeriesEnd:String = compareSeries[compareSeries.length - 1];
if (compSeriesStart == compSeriesEnd) {
//this series loops on itself, it will not concatenate further
continue;
}
if (compSeriesStart == seriesEnd) {
trace ("case 1");
series = series.concat(compareSeries.slice(1));
} else if (compSeriesStart == seriesStart) {
trace ("case 2");
series = compareSeries.reverse().concat(series.slice(1));
} else if (compSeriesEnd == seriesStart) {
trace ("case 3");
series = compareSeries.concat(series.slice(1));
} else if (compSeriesEnd == seriesEnd) {
trace ("case 4");
series = compareSeries.concat(series.reverse().slice(1));
} else {
//no linkage between these two series
continue;
}
collectedSeries[i] = series; //replace one of the two segements
collectedSeries.splice(j, 1); //splice out the other
break;
}
trace ("series: " + series + (i == n ? " new" : ""));
}
}
}
This will give the following results:
A1,G1,F1,E1,D1,C1,B1,A1
G2,A2,B2,C2,D2,E2,F2,G2
G3,A3,B3,C3,D3,E3,F3,G3
G4,A4,B4,C4,D4,E4,F4,G4
I would still really appreciate any advice/feedback I can get. Does no one use Conrec?!
Edit: woops! I had a bug with the original splice()! sorry! fixed now
I just ported ConRec to Actionscript3 and seems to work fine, I haven't tested it thoroughly,
but it draws my contours the way I expect. Try it out if you will, I'm curious if it's a correct port. it's here:
http://www.jvanderspek.com/DEV/ConRec/ConRec.as
Ok, so there may be a much better alternative for Flash. I just found this link and it looks impressive. If this works, it obviates the original problem...
isolining package for ActionScript 3

Resources