I'm sure it's something simple, but I can't seem to figure it out. I am basically trying to use c++ to produce an HTML string and to return it to be stored in an objective c model class to be used later in a web view.
The c++ side of it seems to run fine. here's the method that's called in a cpp file:
const char *SqliteConnection::htmlTest(){
HtmlItemValueTableBuilder htmlBuilder = HtmlItemValueTableBuilder();
std::string s = htmlBuilder.test();
cout << "TEST RESULT: " <<s;
return s.c_str();
}
The cout produces the following output (which is what I want):
TEST RESULT: <!doctype html><html><head></head><div><STYLE type="text/css"> body { margin: 10%; } table { border-spacing: 5px; } td { background-color: #EFEFEF; font-size: 20px; padding: 4px; padding-left: 4px; padding-right: 4px; } tr { margin-bottom: 10px; margin-top: 10px; } </STYLE><table><thead></thead><tbody>
<tr><td>hello</td><td>world</td></tr>
</tbody></table></div></html>
The below is the code the calls it in a separate Objective c++ (.mm) file:
-(NSString *)getFieldsMapAsHtmlForResult:(Result *)result {
const char *s = _sqliteConnection->htmlTest();
NSLog(#"Before Conversion: %s", s);
NSString *htmlString = [NSString stringWithUTF8String:s];
NSLog(#"After Conversion: %#",htmlString);
return htmlString;
}
I have seen a lot of people recommend using stringWithUTF8String to convert a c string to an NString. This has worked for me in the past but for some reason, in both the NSLog outputs, I get nothing returned. The string just mysteriously disappears.
Could you recommend what might be causing this?
----- UPDATE ----
Following Retired Ninja's Advice, I tried to make sure that the pointer referenced wasn't to a variable that fell out of scope. I had a Result model c++ class that I was passing on to my obj c++ code successfully. I decided to add a data member, fields_map_as_html, and have the function pass to that instead of to my obj-C++ code.
SqliteConnection::htmlTest() is returning a pointer to a local variable that goes out of scope so it is no longer valid. You could return a `std::string instead and extract the data in the calling function or use some other method to make sure the data hangs around until you use it.
Related
I have this on Friday evening which I've stacked with. Trying to add quotes around the current item $breakpoint and produce output like
a[data-x="bp1"]
a[data-x="bp2"]
... and so on
but instead, as you guess I'm having a[data-x=bp2]
$spacings: "8%", "9%", "10%", "11%", "13%", "14%";
#each $breakpoint in $breakpoints {
a[data-x=#{$breakpoint}] {
.span {
margin-left: nth($spacings, index($breakpoints, $breakpoint));
}
}
}
any help will be highly appreciated!
You need to escape your quotation marks with \ to keep them in the compiled CSS.
You can either write the names of your breakpoints as:
$breakpoints: "\"bp1\"", "\"bp2\"", "\"bp3\"", "\"bp4\"", ...;
Or simply write your selector as a[data-x=#{"\"#{$breakpoint}\""}]:
$spacings: "8%", "9%", "10%", "11%", "13%", "14%";
$breakpoints: bp1, bp2, bp3, bp4, pb5, bp6; // Quotation marks not needed
#each $breakpoint in $breakpoints {
a[data-x=#{"\"#{$breakpoint}\""}] {
.span {
margin-left: nth($spacings, index($breakpoints, $breakpoint));
}
}
}
Another solution is to use single quotations marks around your variable (or breakpoints names) and then unquote():
a[data-x=#{unquote('"#{ $breakpoint }"')}]
I have the following function piece of code in my ESP8266 based NodeMCU:
snprintf ( temp, 800,
"<html>\
<head>\
<meta http-equiv='refresh' content='25'/>\
<title>NodeMCU DHT11 Sensor \and Relay Board</title>\
<style>\
body { background-color: #cccccc; font-family: Arial, Helvetica, Sans-Serif; Color: #000088; }\
li { margin: 10px 0;}\
</style>\
</head>\
<body>\
<h1>Hello from NodeMCU!</h1>\
<p>Temperature: %02d ℃<br>\
Humidity: %2d %<br></p><ol>\
<li><a href='/control?relay=5&state=%d'>Turn Relay 1 On\/Off</a>\
<li><a href='/control?relay=4&state=%d'>Turn Relay 2 On\/Off</a></ol>\
<p> Uptime: %02d:%02d:%02d </p>\
</body>\
</html>",
t, h, !digitalRead(5), !digitalRead(4), hr, min % 60, sec % 60
);
I want to be able to replace text on with off and vice versa based on the state of pin which comes from digitalRead(5). So I don't have to write Turn Relay 1 On/Off and instead I should get the state using digitalRead(pinNum) and set the text on or off based on state.
The ternary (conditional) operator is your friend here. You could treat it as an inline if-statement. The syntax looks like this
condition ? val1 : val2
The expression will yield a result depending on condition. If the condition is true it will yield val1, otherwise it will yield val2.
You can use this inside of sprintfs argument list to return a string depending on the pin state.
snprintf(temp, 800,
"... <li><a href='/control?relay=5&state=%d'>Turn Relay 1 %s</a><li> ... ",
!digitalRead(5), (digitalRead(5) ? "Off" : "On");
%s is a placeholder for a string and depending on the state of the pin 5 it will be replaced by "On" or "Off"
I got a simple grid used like this :
<div id="planningGridDiv"
class="gridPatientContent"
style="height: 450px;min-height: 300px;"
ng-style="{height: showScores ? '150px': '450px'}"
ui-grid-resize-columns
ui-grid-selection
ui-grid-cellNav
ui-grid-pinning
ui-grid="myData"
class="grid">
</div>
But when showScores is true and height pass from 450 to 150 px, the grid itself doesn't shrink.
The first container see its height changed, but this part no :
<div role="grid" ui-grid-one-bind-id-grid="'grid-container'" class="ui-grid-render-container ng-isolate-scope ui-grid-render-container-body" ng-style="{ 'margin-left': colContainer.getMargin('left') + 'px', 'margin-right': colContainer.getMargin('right') + 'px' }" ui-grid-render-container="" container-id="'body'" col-container-name="'body'" row-container-name="'body'" bind-scroll-horizontal="true" bind-scroll-vertical="true" enable-horizontal-scrollbar="grid.options.enableHorizontalScrollbar" enable-vertical-scrollbar="grid.options.enableVerticalScrollbar" aria-multiselectable="true" id="1490734763451-grid-container" style="margin-left: 180px; margin-right: 80px;">
I can't find any solution on doc nor stack overflow, but it seems to me that it should. I can use some help for some pointers.
FYI, I found a solution on another stackoverflow question, but I changed it a bit to fit my needs :
$scope.showScoreDiv = function()
{
$scope.showScores = !$scope.showScores;
$timeout(function(){
$scope.gridApi.grid.handleWindowResize();
}, 1);
};
So the main idea is to change the height via ng-style on the grid div, and when you fire your event, here showScores = true called by showScoreDiv(), you have to call gridApi.grid.handleWindowResize().
The timeout is just here to give some time to the div to be set to the good height before calling handleWindowResize().
Since mysql_* is going deprecated, I was thinking of an easy way to replace all deprecated code.
Here is my regex; whereas find is what I want to find and repl is what I want to replace it with.
$__db is my declared mysqli_connect-variable
Change MySQL into MySQLi
--
find: mysql_select_db\(([\$"a-zA-Z0-9_]+)\)
repl: \$__db->select_db($1)
--
find: mysql_fetch_object\((\$[a-zA-Z0-9_]+)\)
repl: $1->fetch_object()
--
find: mysql_fetch_array\((\$[a-zA-Z0-9_]+)\)
repl: $1->fetch_array()
--
find: mysql_num_rows\((\$[a-zA-Z0-9_]+)\)
repl: $1->num_rows
--
find: mysql_free_result\((\$[a-zA-Z0-9_]+)\)
repl:
--
find: mysql_query
repl: \$__db->query
--
find: mysql_error\(\)
repl: mysqli_error\(\)
--
find: ([\$a-zA-Z0-9_]+) = mysql_result\(([\$a-zA-Z0-9_]+), (\d+)\)
repl: \$row = $2->fetch_array();\r\n$1 = \$row[$3]
And my question would be, can I run multiple regex-replaces (so that I can replace all code at the same time)?
I know that I can use pipe | to separate the find-part, but how does it work with the replace-part?
I haven't found a way to make a macro in Aptana Studio 3.
This became my solution, with tips from HamZa (Thanks!)
I created a script, that iterates over a directory of choosing (Specified in $dir)
We also get to say what we're looking for in the files with $lookFor
I added some comments in the code, so you can follow what I do. This WON'T solve function-db's though.
So if you have classes with DB-connections you'll have to add something for functions.
Right now this script won't change your files (I commented it out, so you can use it to just browse through your code with the "recommended" changes)
And also.. I haven't made it so the script prepares statements.
(That is step two, this was just to fix things that would break when mysql_* gets removed)
The result will look something like this: (Actually showing that missing function I talked about.. I'll have to add global $__db; into each function
And then finally! Here's the code.
<?
/*IGNORE-MYSQL*/
function startsWith($haystack, $needle)
{
return strpos($haystack, $needle) === 0;
}
function endsWith($haystack, $needle)
{
return substr($haystack, -strlen($needle)) == $needle;
}
function doFlush()
{
#flush();
#ob_flush();
}
function runMySQLToMySQLi_replace($str, $useBoldShow = false, $replace = true)
{
$catchVars = '\$"\'a-zA-Z0-9_\.\*\->,\[\] ';
$regexTests = Array();
$regexTests['(?:['.$catchVars.']+\s?=\s?)?mysql_connect\((['.$catchVars.']+),\s?(['.$catchVars.']+),\s?(['.$catchVars.']+)\)'] = '\$__db = mysqli_connect($1, $2, $3)';
$regexTests['mysql_select_db\((['.$catchVars.']+)(?:,\s?['.$catchVars.']+)?\)'] = '\$__db->select_db($1)';
$regexTests['mysql_query\((['.$catchVars.'\(\)=]+)(?:,\s?['.$catchVars.']+)?\)'] = '\$__db->query($1)';
$regexTests['mysql_errno\(\)'] = '\$__db->errno';
$regexTests['mysql_error\(\)'] = '\$__db->error';
$regexTests['mysql_error\((['.$catchVars.']+)\)'] = '\$__db->error';
$regexTests['mysql_fetch_object\((['.$catchVars.']+)\)'] = '$1->fetch_object()';
$regexTests['mysql_fetch_row\((['.$catchVars.']+)\)'] = '$1->fetch_array()';
$regexTests['mysql_fetch_array\((['.$catchVars.']+)\)'] = '$1->fetch_array()';
$regexTests['mysql_fetch_assoc\((['.$catchVars.']+)\)'] = '$1->fetch_assoc()';
$regexTests['mysql_num_rows\((['.$catchVars.']+)\)'] = '$1->num_rows';
$regexTests['mysql_free_result\((['.$catchVars.']+)\)'] = '$1->free()';
$regexTests['mysql_insert_id\(\)'] = '\$__db->insert_id';
$regexTests['(['.$catchVars.']+) = mysql_result\((['.$catchVars.']+), (\d+)\)'] = "\$row = $2->fetch_array(); $1 = \$row[$3]";
$tmpVal = $str;
foreach($regexTests as $reg => $rep)
{
$match = preg_match("/" . $reg . "/i", $tmpVal);
if($match)
{
if($replace)
$tmpVal = preg_replace("/" . $reg . "/i", ($useBoldShow ? "[{b}]" : "") . $rep . ($useBoldShow ? "[/{b}]" : ""), $tmpVal);
else
$tmpVal = preg_replace("/" . $reg . "/i", ($useBoldShow ? "[{b}]" : "") . "$0" . ($useBoldShow ? "[/{b}]" : ""), $tmpVal);
}
}
return $tmpVal;
}
?>
<html>
<head>
<style>
body { margin: 0; padding: 0; }
.mysql_found { background-color: mistyrose; padding: 10px; border: 1px solid #c9c9c9; border-radius: 5px; margin: 10px; }
.no_select {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: moz-none;
-ms-user-select: none;
user-select: none;
display: inline-block;
}
</style>
</head>
<body>
<pre><?
// Directory to search in
$dir = "/dir/to/search/in/";
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::SELF_FIRST);
// What we are looking for in all files
$lookFor = "mysql_";
foreach($objects as $name => $object)
{
// Ensure that it is PHP-files we're going through
if(endsWith($object->getFilename(), '.php'))
{
// Get all contents
$contents = file_get_contents($object->getPathname());
// Split it into rows
$rowSplit = preg_split('/$\R?^/m', $contents);
// Check the contents for $lookFor
if(strpos($contents, $lookFor) > 0 && strpos($contents, "/*IGNORE-MYSQL*/") === false)
{
echo "<div class=\"mysql_found\">\"" . $lookFor . "\" found in: " . $object->getPathname() . "\n";
echo "<hr noshade=\"noshade\" />\n";
echo "Source code:\n";
$lCount = 1;
foreach($rowSplit as $row)
{
echo "<div class=\"no_select\" unselectable=\"on\">" . str_pad($lCount++, strlen(count($rowSplit)), " ", STR_PAD_LEFT) . ": </div>" . str_replace(Array("[{b}]", "[/{b}]"), Array("<b style=\"background-color: #cfaaaa;\">", "</b>"), htmlentities(runMySQLToMySQLi_replace($row, true, false))) . "\n";
}
echo "\n\n";
$lCount = 1;
echo "Fixed code:<br /><br />";
$doneCode = "";
foreach($rowSplit as $row)
{
echo "<div class=\"no_select\" unselectable=\"on\">" . str_pad($lCount++, strlen(count($rowSplit)), " ", STR_PAD_LEFT) . ": </div>" . str_replace(Array("[{b}]", "[/{b}]"), Array("<b style=\"background-color: #cfaaaa;\">", "</b>"), htmlentities(runMySQLToMySQLi_replace($row, true))) . "\n";
// This is the code that actually does the replacing.
$doneCode .= runMySQLToMySQLi_replace($row) . "\n";
}
// This is commented out, since I want to make sure it works before I accept some changes.
// I actually tried it on 3 files without problems.
//if(isset($_GET['Accepted']))
// file_put_contents($object->getPathname(), $doneCode);
echo "</div>";
}
}
doFlush();
}
?></pre>
</body>
</html>
If you want to ask me something about this code, do it. :)
How could we use regexp (replace) to find all occurrences of the following CSS
code in a long string and remove them (the XMP code is what I added)? Thanks.
<xmp>
body { font-family : "Courier New", Courier, monospace; font-size : 9pt; valign : top; text-align : left; line-height: 9pt }
td {
font-family : "Courier New", Courier, monospace; font-size : 9pt; valign : top; text-align : left; line-height: 9pt }
</xmp>
Assuming that the string you provided is inside myString and all the css code is inside cssString.
cssString = cssString.replace(myString, '');
If you want to remove the "\\ \\" along with the content contained within it ! This is how you do in python:
s="<xmp> your css code</xmp>"
s=re.sub("<xmp>.*</xmp>", " ",s)
output:
>>>s
''
In the code above i am substituting everything that starts with tag and $'.*' basically tells the python interpreter to include all the characters until the end tag and substitutes the entire thing with $" ".
if you want to remove just the content of the tags then:
s="<xmp> your css code</xmp>"
code_inside_xmptag=re.search("<xmp>(*.)</xmp>",string)
s=re.sub(code_inside_xmptag.group(1)," ",string)
Output:
>>>s
<xmp> </xmp>
Over here i am basically searching for the tags and creating a group for the content contained.
I am passing that as the string to be replaced/substituted.
You can read more about Regular Expressions in python : Here