Tuesday, May 12, 2015

Digest for comp.lang.c++@googlegroups.com - 19 updates in 5 topics

Christopher Pisz <nospam@notanaddress.com>: May 12 02:18PM -0500

http://www.boost.org/doc/libs/1_58_0/doc/html/date_time/posix_time.html#date_time.posix_time.ptime_class
 
In the section about time_duration, the doc states:
 
time_duration(hours,
minutes,
seconds,
fractional_seconds)
 
Where fractional seconds are units and are effected by the resolution
the application is compiled with. Ok, fair enough.
 
It then goes on to say, "Another way to handle this is to utilize the
ticks_per_second() method of time_duration to write code that is
portable no matter how the library is compiled. The general equation for
calculating a resolution independent count is as follows:
 
count*(time_duration_ticks_per_second / count_ticks_per_second)"
 
and gives and example:
 
"int number_of_tenths = 5;
//create a resolution independent count -- divide by 10 since there are
//10 tenths in a second.
int count = number_of_tenths*(time_duration::ticks_per_second()/10);
time_duration td(1,2,3,count); //01:02:03.5 //no matter the resolution
settings"
 
Well, that just doesn't work!
If the ticks per second for the input value are greater than the ticks
per second for the configured time_duration resolution, count will be 0.
 
 
Here is the function I am trying to make. I use a Windows function for
the time zone. Ignore that part if need be, it isn't important in the
context of the question. I also use my own exception classes. I cannot
figure out what to do with the fractional part.
 
 
//--------------------------------------------------------------------------------------------------
boost::posix_time::ptime DBDatetimeStringToLocalPtime(const std::string
& value)
{
// Expected input formats:
// "YYYY-MM-DD hh:mm:ss.nnnnnnn"
// "YYYY-MM-DDThh:mm:ss.nnnnnnn"
// "YYYY-MM-DD hh:mm:ss.nnnnnnnZ"
// "YYYY-MM-DDThh:mm:ss.nnnnnnnZ"
// "YYYY-MM-DDThh:mm:ss.nnnnnnn +06:00"
// "YYYY-MM-DDThh:mm:ss.nnnnnnn+06:00"
// "YYYY-MM-DD hh:mm:ss.nnnnnnn -06:00"
// "YYYY-MM-DD hh:mm:ss.nnnnnnn-06:00"
const std::string datePart = value.substr(0, 10);
const std::string otherPart = value.substr(11, std::string::npos);
 
std::string::size_type index = otherPart.find('+');
if( index == std::string::npos )
{
index = otherPart.find('-');
 
if( index == std::string::npos )
{
index = otherPart.find('Z');
}
}
 
const std::string timePart = otherPart.substr(0, index);
std::string timeZonePart;
 
if( index != std::string::npos )
{
timeZonePart = otherPart.substr(index, std::string::npos);
}
 
// Date
std::istringstream
converter(Shared::ReplaceAllOccurrences(datePart, "-", " "));
unsigned year;
unsigned month;
unsigned day;
 
if( (converter >> year).fail() ||
(converter >> month).fail() ||
(converter >> day).fail() )
{
std::ostringstream msg;
msg << "Could not convert string: \"" << value << "\" to ptime.";
throw Shared::Exception(__FILE__, __LINE__, msg.str());
}
 
boost::gregorian::date date(year, month, day);
 
// Time

converter.str(Shared::ReplaceAllOccurrences(Shared::ReplaceAllOccurrences(timePart,
":", " "), ".", " "));
converter.clear();
 
unsigned hour;
unsigned minute;
unsigned second;
unsigned fractional = 0;
 
if( (converter >> hour).fail() ||
(converter >> minute).fail() ||
(converter >> second).fail() )
{
std::ostringstream msg;
msg << "Could not convert string: \"" << value << "\" to ptime.";
throw Shared::Exception(__FILE__, __LINE__, msg.str());
}
 
index = timePart.find('.');
if( index != std::string::npos )
{
std::string fractionalPart = timePart.substr(index + 1,
std::string::npos);
 
if( (converter >> fractional).fail() )
{
std::ostringstream msg;
msg << "Could not convert string: \"" << value << "\" to
ptime.";
throw Shared::Exception(__FILE__, __LINE__, msg.str());
}
 
// Round to maximum supported resolution
const long long inputTicksPerSecond = std::pow<long
long>(10, fractionalPart.size());
const long long supportedTicksPerSecond =
boost::posix_time::time_duration::ticks_per_second();
 
if( supportedTicksPerSecond > inputTicksPerSecond)
{
fractional = fractional * (supportedTicksPerSecond /
inputTicksPerSecond);
}
else
{
 
}
}
 
boost::posix_time::time_duration time(hour, minute, second,
fractional);
boost::posix_time::ptime datetime(date, time);
 
// Time Zone
if( !timeZonePart.empty() )
{
if( timeZonePart[0] == 'Z' )
{
TIME_ZONE_INFORMATION timeZoneInformation;
GetTimeZoneInformation(&timeZoneInformation);
 
long offsetHours = timeZoneInformation.Bias / 60;
long offsetMinutes = timeZoneInformation.Bias % 60;
 
boost::posix_time::time_duration offset(offsetHours,
offsetMinutes, 0);
datetime = datetime - offset;
}
}
 
return datetime;
}
 
 
 
Any suggestions?
 
 
 
 
--
I have chosen to troll filter/ignore all subthreads containing the
words: "Rick C. Hodgins", "Flibble", and "Islam"
So, I won't be able to see or respond to any such messages
---
Juha Nieminen <nospam@thanks.invalid>: May 12 07:07AM

What exactly would be the problem in simply going through the string
in a simple loop, and counting opening and closing parentheses?
 
If you encounter an opening parenthesis, increase the counter. If you
encounter a closing parenthesis, decrease it. If the counter at any
point gets negative, it's unbalanced. If the counter is not zero at
the end, it's unbalanced.
 
--- news://freenews.netfront.net/ - complaints: news@netfront.net ---
Paul <pepstein5@gmail.com>: May 12 12:27AM -0700

On Tuesday, May 12, 2015 at 8:08:02 AM UTC+1, Juha Nieminen wrote:
> encounter a closing parenthesis, decrease it. If the counter at any
> point gets negative, it's unbalanced. If the counter is not zero at
> the end, it's unbalanced.
 
Yes, I did that here, and it's along the lines of Jorgen Grahn's code. I've become a bit obsessed with recursion. My recursion seemed to work (although actually it doesn't work) so I didn't feel a need to try something else. Many thanks to everyone on this thread. All your comments are helpful. This is my latest attempt which people are also welcome to comment on.
 
Paul
 
#include <string>
 
using namespace std;
 
// A function which returns true if the parentheses in a string are balanced and false otherwise.
bool balanced(string str)
{
int num_open_bracket = 0;
int num_closed_bracket = 0;
 
for(int i = 0; i < str.size(); i++)
{
if(str[i] == '(')
num_open_bracket++;
 
if(str[i] == ')')
num_closed_bracket++;
 
if(num_closed_bracket > num_open_bracket)
return false;
}
 
return num_open_bracket == num_closed_bracket;
}
Paul <pepstein5@gmail.com>: May 12 12:37AM -0700

On Tuesday, May 12, 2015 at 8:27:31 AM UTC+1, Paul wrote:
> }
 
> return num_open_bracket == num_closed_bracket;
> }
 
Sorry, the signature should have been bool balanced(const string& str) as others have said. I was listening to the thread commenters. Sometimes I get obsessed on some parts of the problem and ignore other elements.
 
Paul
legalize+jeeves@mail.xmission.com (Richard): May 12 05:38PM

[Please do not mail me a copy of your followup]
 
Paul <pepstein5@gmail.com> spake the secret code
 
>This is my latest attempt which people are also
>welcome to comment on.
 
This is much better. A few minor suggestions still.
 
(By the way, this sort of "do something and get feedback from peers"
is exactly what exercism.io is all about. I implemented the C++
language track there. This discussion inspired me to add a
"Balanced parenthesis" problem to exercism.)
 
>// A function which returns true if the parentheses in a string are
>balanced and false otherwise.
>bool balanced(const string &str)
 
A better name might be:
 
bool balanced_parenthesis(const string &str)
 
Then the comment is redundant because the intention is revealed in the
name of the function.
 
> }
 
> return num_open_bracket == num_closed_bracket;
>}
 
There's nothing here that really depends on the container being a
std::string, so you can generalize this algorithm with iterators:
 
template <typename Iter>
bool balanced_parenthesis(Iter begin, Iter end)
{
int num_open_bracket = 0;
int num_closed_bracket = 0;
 
for (; begin != end; ++begin)
{
if (*begin == '(')
{
num_open_bracket++;
}
 
if (*begin == ')')
{
num_closed_bracket++;
}
 
if (num_closed_bracket > num_open_bracket)
{
return false;
}
}
 
return num_open_bracket == num_closed_bracket;
}
 
I've modified the formatting slightly: control structures are not
function calls, so don't write them like function calls and statement
blocks should always be enclosed in {}'s as per CERT security
guidelines.
<https://www.securecoding.cert.org/confluence/pages/viewpage.action?pageId=42729941>
 
You can collapse the two local variables into one:
 
template <typename Iter>
bool balanced_parenthesis(Iter begin, Iter end)
{
int depth = 0;
 
for (; begin != end; ++begin)
{
if (*begin == '(')
{
depth++;
}
 
if (*begin == ')')
{
depth--;
}
 
if (depth < 0)
{
return false;
}
}
 
return depth == 0;
}
 
As a general rule, we should prefer prefix increment and decrement
operators over postfix operators when we don't need the old value:
 
template <typename Iter>
bool balanced_parenthesis(Iter begin, Iter end)
{
int depth = 0;
 
for (; begin != end; ++begin)
{
if (*begin == '(')
{
++depth;
}
 
if (*begin == ')')
{
--depth;
}
 
if (depth < 0)
{
return false;
}
}
 
return depth == 0;
}
 
The current character can never be both an open paren and a closing
paren, so testing both of these one after another is redundant:
 
template <typename Iter>
bool balanced_parenthesis(Iter begin, Iter end)
{
int depth = 0;
 
for (; begin != end; ++begin)
{
if (*begin == '(')
{
++depth;
}
else if (*begin == ')')
{
--depth;
}
 
if (depth < 0)
{
return false;
}
}
 
return depth == 0;
}
 
The depth can only be negative if we just decremented it:
 
template <typename Iter>
bool balanced_parenthesis(Iter begin, Iter end)
{
int depth = 0;
 
for (; begin != end; ++begin)
{
if (*begin == '(')
{
++depth;
}
else if (*begin == ')')
{
--depth;
if (depth < 0)
{
return false;
}
}
}
 
return depth == 0;
}
--
"The Direct3D Graphics Pipeline" free book <http://tinyurl.com/d3d-pipeline>
The Computer Graphics Museum <http://computergraphicsmuseum.org>
The Terminals Wiki <http://terminals.classiccmp.org>
Legalize Adulthood! (my blog) <http://legalizeadulthood.wordpress.com>
Victor Bazarov <v.bazarov@comcast.invalid>: May 12 02:32PM -0400

On 5/12/2015 1:38 PM, Richard wrote:
>> bool balanced(const string &str)
 
> A better name might be:
 
> bool balanced_parenthesis(const string &str)
 
[..]
 
Just a nit-pick. A single parenthesis is never balanced. The plural
form is better:
 
bool balanced_parentheses(cosnt string &str)
 
V
--
I do not respond to top-posted replies, please don't ask
scott@slp53.sl.home (Scott Lurndal): May 12 06:40PM


> services to mirror the article via the web (HTTP). But Stefan Ram
 
> hereby allows to keep this article within a Usenet archive server
 
> with only NNTP access without any time limitation.
 
What is all this double-spaced scheisse?
 
 
>bool is_balanced( ::std::basic_string< C, T, A >const & s )
>...
 
> (untested). Maybe it should be preceded by »constexpr«?
 
This is far more readable, yet untested.
 
bool balanced(std::string &str, char open = '(');
 
/**
* Return true if the enclosing characters are
* balanced.
*
* @note: A character will be considered regardless of
* whether or not it is quoted (with ', ", \, », or «).
*
* @param str A reference to the string to analyze
* @param open The opening character (one of '(', '[', or '{')
* @returns true if the character represented by 'open' is balanced.
*/
bool balanced(std::string &str, char open)
{
char closed = (open == '(')?open+1:open+2;
size_t count = 0ul;
 
if ((open != '(') && (open != '[') && (open != '{')) return false;
 
for(auto i: str) {
if (i == open) count++, continue;
if (i == closed) {
if (count == 0) return false;
--count;
}
}
return count == 0;
}
 
On an EBCDIC system:
 
uint8_t closed = (open == '[')?open+1:open+16;
scott@slp53.sl.home (Scott Lurndal): May 12 06:44PM

>legalize+jeeves@mail.xmission.com (Richard) writes:
>>statement blocks should always be enclosed in {}'s
 
> What is a »statement block«?
 
AKA a compound statement. Richard is putting forth
a style guideline; don't cheat and eliminate the {}
when there is only a single statement.
 
e.g. He prefers:
if (fred)
{
i++;
}
 
instead of
if (fred) i++;
 
 
While I agree, generally, there is a large community of
developers (linux kernel engineers) who vociferously disagree.
 
(My preference comes from the punched card days when it was
easier to insert a statement when the {} (BEGIN/END in the day) were already there;
one wouldn't need to re-punch the control statement).
 
It does also make patches (diffs) look cleaner.
legalize+jeeves@mail.xmission.com (Richard): May 12 07:09PM

[Please do not mail me a copy of your followup]
 
Victor Bazarov <v.bazarov@comcast.invalid> spake the secret code
 
>Just a nit-pick. A single parenthesis is never balanced. The plural
>form is better:
 
> bool balanced_parentheses(cosnt string &str)
 
I like it!
--
"The Direct3D Graphics Pipeline" free book <http://tinyurl.com/d3d-pipeline>
The Computer Graphics Museum <http://computergraphicsmuseum.org>
The Terminals Wiki <http://terminals.classiccmp.org>
Legalize Adulthood! (my blog) <http://legalizeadulthood.wordpress.com>
legalize+jeeves@mail.xmission.com (Richard): May 12 07:10PM

[Please do not mail me a copy of your followup]
 
slp53@pacbell.net spake the secret code
 
> AKA a compound statement. Richard is putting forth
>a style guideline; don't cheat and eliminate the {}
>when there is only a single statement.
 
In the CERT coding standard, it is a recommendation. However, it is a
recommendation because there are actual security bugs that have been
caused by omitting the braces.
--
"The Direct3D Graphics Pipeline" free book <http://tinyurl.com/d3d-pipeline>
The Computer Graphics Museum <http://computergraphicsmuseum.org>
The Terminals Wiki <http://terminals.classiccmp.org>
Legalize Adulthood! (my blog) <http://legalizeadulthood.wordpress.com>
drew@furrfu.invalid (Drew Lawson): May 12 07:14PM

In article <aOr4x.47715$cX.34760@fx28.iad>
 
>> hereby allows to keep this article within a Usenet archive server
 
>> with only NNTP access without any time limitation.
 
>What is all this double-spaced scheisse?
 
It is stuff that was in the message headers, and is not double
spaced at all. It is a Header line with continuation lines.
 
What client are you using that displays unimportant (i.e., X-)
headers?
 
--
Drew Lawson So risk all or don't risk anything
You can lose all the same
Doug Mika <dougmmika@gmail.com>: May 12 11:48AM -0700

I got the following line from my book:
 
"ios_base::failure - thrown by the functions and methods in the iostream library."
 
the question I have is, is there a difference between functions and methods in C++? I always thought they were two words used to describe the same thing!
Melzzzzz <mel@zzzzz.com>: May 12 08:54PM +0200

On Tue, 12 May 2015 11:48:57 -0700 (PDT)
 
> the question I have is, is there a difference between functions and
> methods in C++? I always thought they were two words used to
> describe the same thing!
 
methods are member functions. Everybody calls them methods ;)
Marcel Mueller <news.5.maazl@spamgourmet.org>: May 12 08:59PM +0200

On 12.05.15 20.48, Doug Mika wrote:
> I got the following line from my book:
 
> "ios_base::failure - thrown by the functions and methods in the iostream library."
 
> the question I have is, is there a difference between functions and methods in C++? I always thought they were two words used to describe the same thing!
 
There is no real difference. Depending on the language and the personal
flavor the one the other might be preferred. The term method is more
likely used in conjunction with object orientation and member functions,
while free functions are rarely called methods. However, both identify
basically the same thing. There are significantly larger differences
between static and non static member functions.
 
 
Marcel
legalize+jeeves@mail.xmission.com (Richard): May 12 07:14PM

[Please do not mail me a copy of your followup]
 
Doug Mika <dougmmika@gmail.com> spake the secret code
>library."
 
>the question I have is, is there a difference between functions and
>methods in C++?
 
The standard library implements features through functions and classes
with methods.
 
Functions are not attached to an instance of an object and therefore
do not have a 'this' pointer. Functions can't see internal details of
a class (unless they are friends[*]). Functions are declared outside
of a class, but possibly within a namespace.
 
Methods are attached to an object and are declared within a class. If
the method is not a static method, then it has access to instance data
of the associated object on which it is invoked. If it is a static
method, then it has access to other static methods and data for that
class.
 
[*] My advice is to use friend as a last resort. There are times when
it is necessary but most of the time it is used to paper over a hole
in your design.
--
"The Direct3D Graphics Pipeline" free book <http://tinyurl.com/d3d-pipeline>
The Computer Graphics Museum <http://computergraphicsmuseum.org>
The Terminals Wiki <http://terminals.classiccmp.org>
Legalize Adulthood! (my blog) <http://legalizeadulthood.wordpress.com>
ram@zedat.fu-berlin.de (Stefan Ram): May 12 03:13PM

>> }
 
>> return num_open_bracket == num_closed_bracket;
>> }
 
The second == is evaluated even if the first one was true.
I'd use an »else« there.
 
bool is_balanced( ::std::string const & s )
{ auto top = s.size(); signed long long c{ 0 };
for( int i = 0; i < top; ++i )
{ switch( s[ i ]){ case '(': ++c; break; case ')': --c; }
if( c == LLONG_MAX || c == LLONG_MIN )
throw ::std::overflow_error( "too many parentheses" );
if( c < 0 )return 0; } return !c; }
 
(untested). The optimizer might have accomplished this before,
but not we can be sure that »s.size()« is only evaluated once
and »s[ i ]« is only evaluated once per loop.
 
Use s.at( i ) for an additional layer of security.
 
Or using a pointer:
 
bool is_balanced( ::std::string const & s )
{ auto top = s.size(); signed long long c{ 0 };
char const * b = s.c_str(); char const * e = b + top;
for( char const * p = b; p < e; ++p )
{ switch( *p ){ '(': ++c; break; ')': --c; }
if( c == LLONG_MAX || c == LLONG_MIN )
throw ::std::overflow_error( "too many parentheses" );
if( c < 0 )return 0; } return !c; }
 
(untested). But this pointer style might be too low-level in C++.
 
Maybe it should be a template?
 
templace< typename C, typename T, typename A >
bool is_balanced( ::std::basic_string< C, T, A >const & s )
...
 
(untested). Maybe it should be preceded by »constexpr«?
ram@zedat.fu-berlin.de (Stefan Ram): May 12 05:54PM

>statement blocks should always be enclosed in {}'s
 
What is a »statement block«?
ram@zedat.fu-berlin.de (Stefan Ram): May 12 06:56PM

>the iostream library."
>the question I have is, is there a difference between
>functions and methods in C++?
 
The C++-specific meaning of »function« is defined by the
standard.
 
The meaning of »method« is defined by the English language
or by third parties.
 
(However, there is FLT_EVAL_METHOD (from C): if
FLT_EVAL_METHOD is 1, then the product of two float _Complex
operands is represented in the double _Complex format, and
its parts are evaluated to double.)
Juha Nieminen <nospam@thanks.invalid>: May 12 07:11AM

> The std::search function is a template function, however to invoke it,
> we do NOT need to specify the template parameters!!
 
With template functions you don't need to specify the template
parameters if these parameters appear in the function's parameter
list, and the compiler can deduce the template parameters from the
call. However, with template classes you have to explicitly tell
the template parameter because there's nothing in the instantiation
of the class that would tell it otherwise. (Also if a template
function does not use the template parameters anywhere in the
function parameters, you also have to say it explicitly.)
 
--- news://freenews.netfront.net/ - complaints: news@netfront.net ---
You received this digest because you're subscribed to updates for this group. You can change your settings on the group membership page.
To unsubscribe from this group and stop receiving emails from it send an email to comp.lang.c+++unsubscribe@googlegroups.com.

No comments: