How to read a float in a csv with CAPL? - csv

I have a .csv file and I want to read the data in its format, not at string.
This is the function that save the file in a readbuffer if is ok.
fileGetString(readbuffer,elcount(readbuffer),readHandle)!=0)
And I have the data is in this format:
Temperature;12.25;15.65;-25.12;80;
Time;1;2;4;7;
I want save the temperature in a buffer "Temperature[i]"
and do the same with the time "Time[i]"
How can I do this in CAPL?
I know that I can read each data like String and cast to integer or float doing some operations, but I want optimize code and read each data in its format.

You can convert an string to an float number using strtod().
Just for fun, here is complete example:
on start
{
dword fh;
char text[255];
double Temperature[4], Time[4];
int i;
/* open file */
fh = openFileRead("a.csv",0);
if (!fh) {
write ("ERROR: Open file failed!");
return;
}
/* read the 'Temperature' line */
if (!fileGetString(text, elcount(text), fh) ||
strstr(text, "Temperature;") != 0) {
write("ERROR: Wrong file format, 'Temperature' not found!");
return;
}
/* get the 'Temperature' values */
getValuesFromCsvString(text, Temperature);
/* read the 'Time' line */
if (!fileGetString(text, elcount(text), fh) ||
strstr(text, "Time;") != 0) {
write("ERROR: Wrong file format, 'Time' not found!");
return;
}
/* get the 'Time' values */
getValuesFromCsvString(text, Time);
/* output values */
for (i = 0; i < elcount(Temperature); i++)
write("Temperature[%i] = %6.2f", i, Temperature[i]);
for (i = 0; i < elcount(Time); i++)
write("Time[%i] = %2.0f", i, Time[i]);
}
int getValuesFromCsvString(char text[], double vals[])
{
long i, pos;
double res;
pos = strstr(text, ";");
str_replace(text, ";", " ");
for (i = 0; i < elcount(vals) ; i++) {
pos = strtod(text, pos, res);
if (pos >= 0)
vals[i] = res;
else
break;
}
return 0;
}
Output:
Temperature[0] = 12.25
Temperature[1] = 15.65
Temperature[2] = -25.12
Temperature[3] = 80.00
Time[0] = 1
Time[1] = 2
Time[2] = 4
Time[3] = 7

Related

How to process result set after a "SELECT *" Mysql Prepared Statement query using the C api?

On the documentation page for https://dev.mysql.com/doc/c-api/8.0/en/mysql-stmt-fetch.html.
In the code sample, it mentions that separate outbound parameters have to be declared in order to have access to the columns listed in the SQL query.
Is it possible to run a "SELECT * WHERE column = ?" query via prepared statements only for the WHERE part of the clause and process the result without knowing the SELECT columns ahead of time therefore not declaring them as outbound parameters?
If so, is there an example anywhere?
Thanks
I was able to find an example which shows that the outbound bind params need to be generated. Shown here in the php -> pdo_mysql extension source code:
php-8.1.12/ext/pdo_mysql/mysql_statement.c
static bool pdo_mysql_stmt_after_execute_prepared(pdo_stmt_t *stmt) {
pdo_mysql_stmt *S = stmt->driver_data;
pdo_mysql_db_handle *H = S->H;
#ifdef PDO_USE_MYSQLND
/* For SHOW/DESCRIBE and others the column/field count is not available before execute. */
php_pdo_stmt_set_column_count(stmt, mysql_stmt_field_count(S->stmt));
for (int i = 0; i < stmt->column_count; i++) {
mysqlnd_stmt_bind_one_result(S->stmt, i);
}
S->result = mysqlnd_stmt_result_metadata(S->stmt);
if (S->result) {
S->fields = mysql_fetch_fields(S->result);
/* If buffered, pre-fetch all the data */
if (H->buffered) {
if (mysql_stmt_store_result(S->stmt)) {
pdo_mysql_error_stmt(stmt);
return false;
}
}
}
#else
/* figure out the result set format, if any */
S->result = mysql_stmt_result_metadata(S->stmt);
if (S->result) {
int calc_max_length = H->buffered && S->max_length == 1;
S->fields = mysql_fetch_fields(S->result);
php_pdo_stmt_set_column_count(stmt, (int)mysql_num_fields(S->result));
S->bound_result = ecalloc(stmt->column_count, sizeof(MYSQL_BIND));
S->out_null = ecalloc(stmt->column_count, sizeof(my_bool));
S->out_length = ecalloc(stmt->column_count, sizeof(zend_ulong));
/* summon memory to hold the row */
for (int i = 0; i < stmt->column_count; i++) {
if (calc_max_length && S->fields[i].type == FIELD_TYPE_BLOB) {
my_bool on = 1;
mysql_stmt_attr_set(S->stmt, STMT_ATTR_UPDATE_MAX_LENGTH, &on);
calc_max_length = 0;
}
switch (S->fields[i].type) {
case FIELD_TYPE_INT24:
S->bound_result[i].buffer_length = MAX_MEDIUMINT_WIDTH + 1;
break;
case FIELD_TYPE_LONG:
S->bound_result[i].buffer_length = MAX_INT_WIDTH + 1;
break;
case FIELD_TYPE_LONGLONG:
S->bound_result[i].buffer_length = MAX_BIGINT_WIDTH + 1;
break;
case FIELD_TYPE_TINY:
S->bound_result[i].buffer_length = MAX_TINYINT_WIDTH + 1;
break;
case FIELD_TYPE_SHORT:
S->bound_result[i].buffer_length = MAX_SMALLINT_WIDTH + 1;
break;
default:
S->bound_result[i].buffer_length =
S->fields[i].max_length? S->fields[i].max_length:
S->fields[i].length;
/* work-around for longtext and alike */
if (S->bound_result[i].buffer_length > H->max_buffer_size) {
S->bound_result[i].buffer_length = H->max_buffer_size;
}
}
/* there are cases where the length reported by mysql is too short.
* eg: when describing a table that contains an enum column. Since
* we have no way of knowing the true length either, we'll bump up
* our buffer size to a reasonable size, just in case */
if (S->fields[i].max_length == 0 && S->bound_result[i].buffer_length < 128 && MYSQL_TYPE_VAR_STRING) {
S->bound_result[i].buffer_length = 128;
}
S->out_length[i] = 0;
S->bound_result[i].buffer = emalloc(S->bound_result[i].buffer_length);
S->bound_result[i].is_null = &S->out_null[i];
S->bound_result[i].length = &S->out_length[i];
S->bound_result[i].buffer_type = MYSQL_TYPE_STRING;
}
if (mysql_stmt_bind_result(S->stmt, S->bound_result)) {
pdo_mysql_error_stmt(stmt);
PDO_DBG_RETURN(0);
}
/* if buffered, pre-fetch all the data */
if (H->buffered) {
if (mysql_stmt_store_result(S->stmt)) {
pdo_mysql_error_stmt(stmt);
PDO_DBG_RETURN(0);
}
}
}
#endif
pdo_mysql_stmt_set_row_count(stmt);
return true;
}

Refer to json individual objects in cpp crow

i am using a cpp crow library and i am having difficulty in accessing individual objects i am attaching my code here.
CROW_ROUTE(app,"/hello/<string>")
([](string name){
crow::json::wvalue x;
x["name"] = "llllds";
x["Town"] = "Texas";
x["nickname"] = "drax";
x["father"] = "Nethan";
if (name == "Nothing")
cout << "Bad Responce";
std::ostringstream os;
cout << name << " is the required query";
val = x[name];
return val;
And i want to return my name can anyone help me with this. Thanks in advance
I used JSON for Modern C++ within crow (https://github.com/nlohmann/json)
Here is an example CROW_ROUTE I wrote
CROW_ROUTE(app, "/palindromes/<string>/<string>")([](const request &req, response &res, string ID, string words){
palindromeHash.insert({ID, words}); //ignore this
nlohmann::json x;
x = getPalindromes(palindromeHash.at(ID));
palindromeHash.erase(ID); //ignore this
res.sendJSON(x);
});
//getPalindromesFunction()
nlohmann::json getPalindromes(string data){
nlohmann::json x;
unordered_map<string, bool> hashmap;
string word = "";
std::string::size_type i = data.find("%20");
while (i != std::string::npos){
data.erase(i, 3);
data.insert(i, " ");
i = data.find("%20", i);
}
for(int i = 0; i < data.size(); i++){
if(data[i] == ' '){
hashmap.insert({word, true});
word = "";
}
else{
word += data[i];
}
}
string temp;
vector<string> words;
int numValid = 0;
for(auto& i: hashmap){
temp = i.first;
reverse(temp.begin(), temp.end());
auto got = hashmap.find(temp);
if(got != hashmap.end()){
words.push_back(i.first);
numValid++;
}
}
x["words"] = words;
x["numValid"] = numValid;
return x;
}
As you can see it returns a JSON object x that holds palindromes. The sendJSON() function is something I added to crow_all.h. Add it under the struct response section on line 7215
void sendJSON(const nlohmann::json& data){
std::string response = data.dump();
add_header("Access-Control-Allow-Origin", "*");
add_header("Content-Type", "text/html");
write(response);
end();
}
Remember to include "json.h" in both main.cpp and crow_all.h. The res.sendJSON will send it to my JS file which can loop through the JSON with ease.
$.get("/palindromes/" + ID + "/" + curr_line, {}, function(response){
let x = JSON.parse(response); //This will allow JS to read the C++ JSON
for(let i = 0; i < x.words.length; i++){
term.write(x.words[i] + "\r\n");
}
}

how to get real direction steps using Flutter? (draw real route)

I'm working with taxi app. Is it possible to draw real route on real road using flutter?
I used this way: https://developers.google.com/maps/documentation/directions/intro#ExampleRequests
getDirectionSteps(double destinationLat, double destinationLng) {
network
.get("origin=" +
location.latitude.toString() +
"," +
location.longitude.toString() +
"&destination=" +
destinationLat.toString() +
"," +
destinationLng.toString() +
"&key=api_key")
.then((dynamic res) {
List<Steps> rr = res;
print(res.toString());
ccc = new List();
for (final i in rr) {
ccc.add(i.startLocation);
ccc.add(i.endLocation);
}
mapView.onMapReady.listen((_) {
mapView.setMarkers(getMarker(location.latitude,location.longitude,destinationLat,destinationLng));
mapView.addPolyline(new Polyline("12", ccc, width: 15.0));
});
_screenListener.dismissLoader();
showMap();
}).catchError((Exception error) => _screenListener.dismissLoader());
}
my output look like this:
But I need like this: (draw destination route on real road)
to find the exact route you have to get points out of the polylineoverview from the json from directions api.
This is how I extracted the exact route just like you show in the second image.
Its is a function that return points as a string
Future<String> getRouteCoordinates(LatLng l1, LatLng l2) async {
String url =
"https://maps.googleapis.com/maps/api/directions/json?origin=${l1.latitude},${l1.longitude}&destination=${l2.latitude},${l2.longitude}&key=${Constants.anotherApiKey}";
http.Response response = await http.get(url);
Map values = jsonDecode(response.body);
ProjectLog.logIt(TAG, "Predictions", values.toString());
return values["routes"][0]["overview_polyline"]["points"];
}
you will get a string of points somewhat similiar to this
u|umDs`gwML}A_GGgFGAWwDEm#TcFGsAAa#BeA\QDe#AYISOKHKJGFw#^?jAAnAEnOA|GAhHEx#?jA#tC?XFLLf#Bf##t#?xAA|E?dEEj_#GxMChG#tCIvl##tAK`DQlA?zBApE?lBExNAlH#rMAtGJdDJnATfB`AnEdAzEj#~B|#lEF\xAvGnAlF~#lEv#`DvAxFxAxGzCdN`H`ZnEnRr#hDnB|IhDlNvKnd#vDhPrFzUzGjYxBtH|#hCdAzBXl#fAhBtAtBjBhCfArAdAhAvBtBlB|AjGfFhLzJfEzDzCvDz#pA`BpC`ApBbAzBxCrIr#rBjNta#x#nBbAlBzCbI|R|j#hA`FBVC`ASpD?lA[FiMpCaBVgABiAPoE~#cIdBiLfCcHdBsCl#yJvBmDt#y#l#{#X_#P[VGJGZCd#r#tCf#rBTbAV`BB`#?n#GdA#XHj#bAxBl#hBPjADf#?v#Ej#Ml#Ut#[r#]h#sA`C{#lAMZGl#KjECbDGhBuGMsJKcCGw#CqJCiECAd#ALoBbKs#jDM^x#j#vPfLvCnB~DnCx#f#R#RAd#GDIbBmDv#y#LId#On#A~EJX#pDJrADb#QFC
Now you will add the polyline in the set of polylines like this
_polyLines.add(Polyline(
polylineId: PolylineId(Constants.currentRoutePolylineId),//pass any string here
width: 3,
geodesic: true,
points: Utils.convertToLatLng(Utils.decodePoly(encodedPoly)),
color: ConstantColors.PrimaryColor));
here encodedPoly is the same string that extracted from previous method.
In the function above you have to convert the points\encodedPoly into the list of latlng. Like i did using utils function.
Both functions that i used are
decodePoly :
// !DECODE POLY
static List decodePoly(String poly) {
var list = poly.codeUnits;
var lList = new List();
int index = 0;
int len = poly.length;
int c = 0;
// repeating until all attributes are decoded
do {
var shift = 0;
int result = 0;
// for decoding value of one attribute
do {
c = list[index] - 63;
result |= (c & 0x1F) << (shift * 5);
index++;
shift++;
} while (c >= 32);
/* if value is negative then bitwise not the value */
if (result & 1 == 1) {
result = ~result;
}
var result1 = (result >> 1) * 0.00001;
lList.add(result1);
} while (index < len);
/*adding to previous value as done in encoding */
for (var i = 2; i < lList.length; i++) lList[i] += lList[i - 2];
print(lList.toString());
return lList;
}
and convertToLatLng() :
static List<LatLng> convertToLatLng(List points) {
List<LatLng> result = <LatLng>[];
for (int i = 0; i < points.length; i++) {
if (i % 2 != 0) {
result.add(LatLng(points[i - 1], points[i]));
}
}
return result;
}
This would make a exact route like i did in my app :
Here is the screenshot :

In the Arduino IDE, why does the second call of a function change the previous call results?

I tried to write a function that converts a string of hex values into a string of Unicode UTF-8 characters. When this function is called once, everything is fine. But when the function is called twice in succession with the same or different arguments, both output strings are meaningless.
void HEX2String(String* HEXstr, String* str) {
String s2 = "", s3 = "";
long c, c1, c0;
char ch[2] = { 0 };
for (int i = 0; i <= HEXstr->length() - 4; i = i + 4) {
s2 = HEXstr->substring(i, i + 1) + "x" + HEXstr->substring(i + 1, i + 4);
c = (hex2long(&s2));
if (c < 255)
*str += String((char)c);
else {
c1 = (128 + (c & B111111));
c0 = (192 + (c >> 6));
ch[1] = c1;
ch[0] = c0;
str->concat(ch);
}
}
}
String str1 = "0628064700200646062706450020062E062F0627000A0633064406270645000A064806310648062F0020062806470020063306CC0633062A06450020062A064806330637";
String str = "0628064700200646062706450020062E062F0627000A0633064406270645000A064806310648062F0020062806470020063306CC0633062A06450020062A064806330637000A00730061006C0061006D0020006200610072002000730068006F006D0061";
String msg = "";
void setup() {
Serial.begin(9600);
//First call
HEX2String(&str, &msg);
Serial.println(msg);
msg = "";
//Second call
HEX2String(&str1, &msg);
Serial.println(msg);
}
void main() {
//
}
If I comment the second call, the output in the serial monitor is:
سلام
ورود به سیستم توسط
salam bar shoma
It is correct. If the second call is not commented, the output in the serial monitor is:
ب⸮⸮ه⸮⸮ ن⸮⸮ا⸮⸮م⸮⸮ خ⸮⸮د⸮⸮ا⸮⸮
س⸮⸮ل⸮⸮ا⸮⸮م⸮⸮
و⸮⸮ر⸮⸮و⸮⸮د⸮⸮ ب⸮⸮ه⸮⸮ س⸮⸮ی⸮⸮س⸮⸮ت⸮⸮م⸮⸮ ت⸮⸮و⸮⸮س⸮⸮ط⸮⸮
salam bar shomaب⸮⸮ه⸮⸮ ن⸮⸮ا⸮⸮م⸮⸮ خ⸮⸮د⸮⸮ا⸮⸮
س⸮⸮ل⸮⸮ا⸮⸮م⸮⸮
و⸮⸮ر⸮⸮و⸮⸮د⸮⸮ ب⸮⸮ه⸮⸮ س⸮⸮ی⸮⸮س⸮⸮ت⸮⸮م⸮⸮ ت⸮⸮و⸮⸮س⸮⸮ط⸮⸮
C-strings need to be null terminated. Your ch is not.
Define it as 3 characters:
char ch[3] = { 0 };
and add a null terminator:
ch[0] = c0;
ch[1] = c1;
ch[2] = 0;

tab escape sequence not working when exporting from JXTable to excel (.csv) file

i am trying to export data from a JXTable to a .csv file(excel). i am using the following code for this:
public void exportToExcel(NGAFStandardTable table, File file){
int i = 0;
int j = 0;
try{
TableModel model = table.getModel();
FileWriter excel = new FileWriter(file);
for (i = 0; i < model.getColumnCount(); i++) {
excel.write(model.getColumnName(i) + "\t");
}
excel.write("\n");
for (i = 0; i < model.getRowCount(); i++){
for (j = 0; j < (model.getColumnCount()); j++){
if(model.getValueAt(i,j) == null){
excel.write("" + "\t");
}
else {
excel.write(model.getValueAt(i,j).toString() + "\t");
}
}
excel.write("\n");
}
excel.close();
}
catch(IOException e) {
System.out.println(e);
}
}
the result is i am geting a csv file which has all the values from the table but the values for each row is in a single cell(for eg., A1, A2, A3).
i.e., all the values for row1 is in A1 cell, and so on...
i am using tab escape sequence("\t") so the data moves to next column but its not happening. kindly suggest
it worked when i used "," as the delimeter in place of "\t":
excel.write(model.getValueAt(i, j).toString() + ",");