Swift 3 xor checksum calculation - swift3

I'm trying to calculate the checksum in an NMEA sentence, but i can't get the correct value. Here is my test code.
import UIKit
//$GPGLL,5300.97914,N,00259.98174,E,125926,A*28
let str = "GPGLL,5300.97914,N,00259.98174,E,125926,A"
var xor: UInt8 = 0
for i in 0..<str.characters.count {
xor = xor ^ Array(str.utf8)[i]
}
print(xor)
This returns a checksum of 40, not the 28 i'd expected.
What am i doing wrong?

The checksum is simple, just an XOR of all the bytes between the $ and
the * (not including the delimiters themselves), and written in
hexadecimal.
let str = "$GPGLL,5300.97914,N,00259.98174,E,125926,A*"
var xor: UInt8 = 0
for i in 1..<(str.characters.count - 1){
xor = xor ^ Array(str.utf8)[i]
}
extension UnsignedInteger {
var hex: String {
var str = String(self, radix: 16, uppercase: true)
while str.characters.count < 2 * MemoryLayout<Self>.size {
str.insert("0", at: str.startIndex)
}
return str
}
}
let strWithCheckSum = str + xor.hex
print(strWithCheckSum) // GPGLL,5300.97914,N,00259.98174,E,125926,A*28

Related

PineScript formulation of condition?

Say I have 3 conditions, and I want to perform some action if 2 of these conditions are fulfilled. With a few number of combinations, like 3, the solution could be something like:
c1=...
c2=...
c3=...
if (c1==true and c2==true) then
elseif (c1==true and c3==true) then
elseif (c2==true and c3==true) then
This is not very practical with, say, 100 conditions of which 90 should be fulfilled.
Is there a more compact way to implement this in PineScript?
If you represent the boolean true/false of your condition as 1/0 ints, you could count them to see how many are true.
The shortest way I can think of, is putting them in an array, and calculate the sum of that array.
//#version=5
indicator("My Script")
var int c0 = 1
var int c1 = 0
var int c2 = 1
var int c3 = 1
var int c4 = 1
var int c5 = 0
var int c6 = 0
var int c7 = 1
var int c8 = 1
var int c9 = 1
var int[] a = array.from(c0,c1,c2,c3,c4,c5,c6,c7,c8,c9)
mySum = array.sum(a)
plot(mySum)

how to decode tickstory bi5 file in c#

I tried to export tickstory data to a file in CSV, but it came out as bi5 files.
anyways, I am trying to decode bi5 files.
I used 7zip decoding which turned out a bigger garbage.
what should I use in order to decode bi5 file? Moreover how to do it in C#?
You should find csv file in tickstory directory. It's created by default along with bi5 files.
The Bi5 format background
The size of one Tick record in bi5 file is 5 x 4 bytes.
The structure of bi5 record is following:
1st 4 bytes -> Time part of the timestamp
2nd 4 bytes -> Bid
3rd 4 bytes -> Ask
4th 4 bytes -> Bid Volume
5th 4 bytes -> Ask Volume
Code Sample
So the code, that translates Bi5 to C# primitives could look like this:
byte[] bytes = new bytes[0]; // this is placeholder for tick data
var date = DateTime.Now.AddYears(-1); // this is the tick data start date
var i = 0;
var decimals = 5; // for JPY pairs or other CFD it can be 3 or other
var milliseconds = BitConverter.ToInt32(
bytes[new Range(new Index(i), new Index(i + 4))]
.Reverse().ToArray());
var i1 = BitConverter.ToInt32(bytes[new Range(i + 4, i + 8)].Reverse().ToArray());
var i2 = BitConverter.ToInt32(bytes[new Range(i + 8, i + 12)].Reverse().ToArray());
var f1 = BitConverter.ToSingle(bytes[new Range(i + 12, i + 16)].Reverse().ToArray());
var f2 = BitConverter.ToSingle(bytes[new Range(i + 16, i + 20)].Reverse().ToArray());
// resulting data
var tickTimestamp = new DateTime(date.Year, date.Month, date.Day,
date.Hour, 0, 0).AddMilliseconds(milliseconds);
var Ask = i1 / Math.Pow(10, decimals),
var Bid = i2 / Math.Pow(10, decimals);
var AskVolume = f1,
var BidVolume = f2;
Working sample on github

spark scala pattern matching on a dataframe column

I am coming from R background. I could able to implement the pattern search on a Dataframe col in R. But now struggling to do it in spark scala. Any help would be appreciated
problem statement is broken down into details just to describe it appropriately
DF :
Case Freq
135322 265
183201,135322 36
135322,135322 18
135322,121200 11
121200,135322 8
112107,112107 7
183201,135322,135322 4
112107,135322,183201,121200,80000 2
I am looking for a pattern search UDF, which gives me back all the matches of the pattern and then corresponding Freq value from the second col.
example : for pattern 135322 , i would like to find out all the matches in first col Case.It should return corresponding Freq number from Freq col.
Like 265,36,18,11,8,4,2
for pattern 112107,112107 it should return just 7 because there is one matching pattern.
This is how the end result should look
Case Freq results
135322 265 256+36+18+11+8+4+2
183201,135322 36 36+4+2
135322,135322 18 18+4
135322,121200 11 11+2
121200,135322 8 8+2
112107,112107 7 7
183201,135322,135322 4 4
112107,135322,183201,121200,80000 2 2
what i tried so far:
val text= DF.select("case").collect().map(_.getString(0)).mkString("|")
//search function for pattern search
val valsum = udf((txt: String, pattern : String)=> {
txt.split("\\|").count(_.contains(pattern))
} )
//apply the UDF on the first col
val dfValSum = DF.withColumn("results", valsum( lit(text),DF("case")))
This one works
import common.Spark.sparkSession
import java.util.regex.Pattern
import util.control.Breaks._
object playground extends App {
import org.apache.spark.sql.functions._
val pattern = "135322,121200" // Pattern you want to search for
// udf declaration
val coder: ((String, String) => Boolean) = (caseCol: String, pattern: String) =>
{
var result = true
val splitPattern = pattern.split(",")
val splitCaseCol = caseCol.split(",")
var foundAtIndex = -1
for (i <- 0 to splitPattern.length - 1) {
breakable {
for (j <- 0 to splitCaseCol.length - 1) {
if (j > foundAtIndex) {
println(splitCaseCol(j))
if (splitCaseCol(j) == splitPattern(i)) {
result = true
foundAtIndex = j
break
} else result = false
} else result = false
}
}
}
println(caseCol, result)
(result)
}
// registering the udf
val udfFilter = udf(coder)
//reading the input file
val df = sparkSession.read.option("delimiter", "\t").option("header", "true").csv("output.txt")
//calling the function and aggregating
df.filter(udfFilter(col("Case"), lit(pattern))).agg(lit(pattern), sum("Freq")).toDF("pattern","sum").show
}
if input is
135322,121200
Output is
+-------------+----+
| pattern| sum|
+-------------+----+
|135322,121200|13.0|
+-------------+----+
if input is
135322,135322
Output is
+-------------+----+
| pattern| sum|
+-------------+----+
|135322,135322|22.0|
+-------------+----+

Output GNU Octave (or Matlab) matrix into a file with C array syntax

I have a big matrix in octave which I need it's data to be imported into my C++ code. The matrix is all numbers and I would like to save it as a C array in a header file.
example :
> # octave:
results =
-3.3408e+01 -5.0227e+00 4.3760e+01 3.2487e+01 1.0167e+01 4.1076e+01 6.3226e+00 -3.7095e+01 1.3318e+01 3.8582e+01
-2.1087e+01 -6.1606e+00 4.8704e+01 3.1324e+01 3.0287e+01 4.0114e+01 1.5457e+01 -3.6283e+01 2.6035e+01 4.0112e+01
Needed output:
/* In some foo.h */
static const float results = {
3.3408e+01,-5.0227e+00,4.3760e+01,3.2487e+01,1.0167e+01,4.1076e+01,6.3226e+00,-3.7095e+01,1.3318e+01,3.8582e+01,
2.1087e+01,-6.1606e+00,4.8704e+01,3.1324e+01,3.0287e+01,4.0114e+01,1.5457e+01,-3.6283e+01,2.6035e+01,4.0112e+01,
};
For vectors, try this function
function str = convertarraytoc(B, type, precision, varName)
if nargin < 2
type = 'float';
end
if nargin < 3
precision = 35;
end
if nargin < 4
varName = 'B';
end
str = sprintf('%s %s[%d] = {', type, varName, length(B));
for iB=1:length(B)
if strcmpi(type, 'float')
str = [ str sprintf( ['%1.' int2str(precision) 'ff'], B(iB)) ];
else
str = [ str sprintf('%d', B(iB)) ];
end
if iB ~= length(B)
str = [ str sprintf(',') ];
end
if mod(iB, 501) == 0, str = [ str sprintf('\n') ]; end
end
str = [ str sprintf('};\n') ];
fprintf('%s', str);
For example
convertarraytoc(rand(1,5), 'float', 8, 'test')
ans =
'float test[5] ={0.84627244f,0.63743734f,0.19773495f,0.85582346f,0.24452902f};'
The function would need to be adapted to process Matlab arrays.

How can I have all the integers in a string that has a combination of alphanumeric characters using RegEx

For example I have: 1|2|3,4|5|6,7|8|10;
How can I output it like this:
A: 1 2 3
B: 4 5 6
C: 7 8 10
And how can I do this:
Array A = {1,2,3}
Array B = {4,5,6}
Array C = {7,8,10}
var reg = /(\d+)\|(\d+)\|(\d+)[,;]/g;
var str = "1|2|3,4|5|6,7|8|10;";
var index = 0;
str.replace(reg,function myfun(g,g1,g2,g3){
var ch = String.fromCharCode(65 + (index++));
return ch+": "+g1+" "+g2+" "+g3+"\n";
});
the second case should update myfun return string:
"Array "+ch+" = {"+g1+","+g2+","+g3+"}\n";