Create function to read only from file by [] operator c++ - c++98

I was asked to create new class that adds certain features to fstream in c++.
Two of the features are [] operator that write to file and and second one is read only from file.
My header file of the class lock like that :
class RandomAccessFile{
private:
const ofstream writheFile; //Object for Writing:
const ifstream readFile; //Object for reading:
public:
RandomAccessFile(string fileName):writheFile(fileName), readFile(fileName){};
inline const char& operator[](int num) const ; // read only from file by random access
// some other functionality....
};
I try to implement the read only operator this way:
const char& RandomAccessFile::operator[](int num) const {
return readFile.get();
}
but I got the error:
no matching member function for call to 'get'
Wen I try the same this without the const in declaration it's works fine
what should I do to corrects this problem?
thanks.

Related

Simple loop inside template -- variable 'x' cannot be read at compile time

(Note that I am extremely new to DLang (first day) so I am probably doing something very stupid)
I am trying to create a mixin template to re-use in my app's domain classes, which will automatically generate a toString1() method at compile-time, which will loop through the implementing struct's properties and generate code to print them.
To accomplish this, I am getting a const array of all of the struct's properties and trying to loop through them. However, when I try to access the index inside the loop (which should be perfectly executable at compile-time -- since we are looping against a known value) it fails.
It works completely fine if I use hard-coded indexes.
template Printable() {
import std.algorithm.iteration;
import std.conv;
import std.meta;
import std.stdio;
import std.format;
import std.range;
import std.typecons;
string toString1() const {
const auto traits = __traits(allMembers, typeof(this));
const auto internalWrap = (const string s) => "`" ~ s ~ ": ` ~ this." ~ s ~ " ~ `\n`";
const auto ret = iota(0, traits.length)
.map!((const int x) => traits[x]) // Error: variable x cannot be read at compile time
.fold((a, b) => a ~ b);
pragma(msg, internalWrap(traits[0])); // WORKS GREAT
return "";
}
}
(Just a note that I also tried doing it using both for-loops as well, but it fails with the same error).
I wanted to put an answer on this so this is a code example about what we went over in the comments:
struct A {
int a;
string b;
mixin Printable; // adds the toString1 method
}
mixin template Printable() {
string toString1() const {
string s;
import std.conv;
// loop over the trait directly, don't try to feed it
// through variables to ensure still available
foreach(memberName; __traits(allMembers, typeof(this))) {
// this ensures we are only actually trying to print actual fields
// (only fields have an offsetof property) since printing member
// variables will not be helpful
static if(is(typeof(__traits(getMember, this, memberName).offsetof))) {
if(s.length)
s ~= "\n";
// name
s ~= memberName;
s ~= " = ";
// value, converted to string
s ~= to!string(__traits(getMember, this, memberName));
}
}
return s;
}
}
void main() {
import std.stdio;
A a = A(14, "string");
writeln(a.toString1());
}
prints
a = 14
b = string

How to get the name of the current and calling function in dart?

C# has:
System.Reflection.MethodBase.GetCurrentMethod().Name
Does Dart have something similar but returns results for both the function that is currently being run as well as the name of the function that called the currently run function.
I wrote a simple class that gives the current function and the caller function, but also, the file name, line number and column line from the StackTrace.current property.
Heres the code:
class CustomTrace {
final StackTrace _trace;
String fileName;
String functionName;
String callerFunctionName;
int lineNumber;
int columnNumber;
CustomTrace(this._trace) {
_parseTrace();
}
String _getFunctionNameFromFrame(String frame) {
/* Just giving another nickname to the frame */
var currentTrace = frame;
/* To get rid off the #number thing, get the index of the first whitespace */
var indexOfWhiteSpace = currentTrace.indexOf(' ');
/* Create a substring from the first whitespace index till the end of the string */
var subStr = currentTrace.substring(indexOfWhiteSpace);
/* Grab the function name using reg expr */
var indexOfFunction = subStr.indexOf(RegExp(r'[A-Za-z0-9]'));
/* Create a new substring from the function name index till the end of string */
subStr = subStr.substring(indexOfFunction);
indexOfWhiteSpace = subStr.indexOf(' ');
/* Create a new substring from start to the first index of a whitespace. This substring gives us the function name */
subStr = subStr.substring(0, indexOfWhiteSpace);
return subStr;
}
void _parseTrace() {
/* The trace comes with multiple lines of strings, (each line is also known as a frame), so split the trace's string by lines to get all the frames */
var frames = this._trace.toString().split("\n");
/* The first frame is the current function */
this.functionName = _getFunctionNameFromFrame(frames[0]);
/* The second frame is the caller function */
this.callerFunctionName = _getFunctionNameFromFrame(frames[1]);
/* The first frame has all the information we need */
var traceString = frames[0];
/* Search through the string and find the index of the file name by looking for the '.dart' regex */
var indexOfFileName = traceString.indexOf(RegExp(r'[A-Za-z]+.dart'));
var fileInfo = traceString.substring(indexOfFileName);
var listOfInfos = fileInfo.split(":");
/* Splitting fileInfo by the character ":" separates the file name, the line number and the column counter nicely.
Example: main.dart:5:12
To get the file name, we split with ":" and get the first index
To get the line number, we would have to get the second index
To get the column number, we would have to get the third index
*/
this.fileName = listOfInfos[0];
this.lineNumber = int.parse(listOfInfos[1]);
var columnStr = listOfInfos[2];
columnStr = columnStr.replaceFirst(")", "");
this.columnNumber = int.parse(columnStr);
}
}
This class takes in a StackTrace object and reads its string and parse it.
How to use it (get the info):
void main() {
CustomTrace programInfo = CustomTrace(StackTrace.current);
print("Source file: ${programInfo.fileName}, function: ${programInfo.functionName}, caller function: ${programInfo.callerFunctionName}, current line of code since the instanciation/creation of the custom trace object: ${programInfo.lineNumber}, even the column(yay!): ${programInfo.columnNumber}");
}
The variable programInfo now has the function name, the caller function name, line number, column number and even the file name of the current program's execution.
You can print to the console the following:
print(StackTrace.current.toString());
And you will see how the string looks and be able to understand how i parse the string in order to get the information.
The simple benefit of this is that you dont have to install any library. I made this because i was doing a project just using Dart and i didnt want to add/install any third party library into my simple project. And you will end up with an object having all of the information by just calling the constructor. The downside of this is that it if Dart, for some reason, changes the string format of the stack trace somewhere in the future, this will no longer work BUT if this somehow happens, you can easily change how this class parses the frames*/
NOTE: This code by no means is the most optimize code, but it works :D. I would like to see some better implementations and abstractions.
There is no way to directly access the call stack in the Dart reflection library.
You can get a string representation of the stack trace, and then try to parse that:
var stack = StackTrace.current;
var stackString = "$stack"; // because the only method on StackTrace is toString.
The stack_trace package tries to do this for you for a number of known stack trace formats, so maybe:
import "package:stack_trace";
main() {
print(Trace.current().frames[0].member); // prints "main" unless minified.
}
Tidied up #LuisDev99's answer a bit, optimizing for yourself:
class LoggerStackTrace {
const LoggerStackTrace._({
required this.functionName,
required this.callerFunctionName,
required this.fileName,
required this.lineNumber,
required this.columnNumber,
});
factory LoggerStackTrace.from(StackTrace trace) {
final frames = trace.toString().split('\n');
final functionName = _getFunctionNameFromFrame(frames[0]);
final callerFunctionName = _getFunctionNameFromFrame(frames[1]);
final fileInfo = _getFileInfoFromFrame(frames[0]);
return LoggerStackTrace._(
functionName: functionName,
callerFunctionName: callerFunctionName,
fileName: fileInfo[0],
lineNumber: int.parse(fileInfo[1]),
columnNumber: int.parse(fileInfo[2].replaceFirst(')', '')),
);
}
final String functionName;
final String callerFunctionName;
final String fileName;
final int lineNumber;
final int columnNumber;
static List<String> _getFileInfoFromFrame(String trace) {
final indexOfFileName = trace.indexOf(RegExp('[A-Za-z]+.dart'));
final fileInfo = trace.substring(indexOfFileName);
return fileInfo.split(':');
}
static String _getFunctionNameFromFrame(String trace) {
final indexOfWhiteSpace = trace.indexOf(' ');
final subStr = trace.substring(indexOfWhiteSpace);
final indexOfFunction = subStr.indexOf(RegExp('[A-Za-z0-9]'));
return subStr
.substring(indexOfFunction)
.substring(0, subStr.substring(indexOfFunction).indexOf(' '));
}
#override
String toString() {
return 'LoggerStackTrace('
'functionName: $functionName, '
'callerFunctionName: $callerFunctionName, '
'fileName: $fileName, '
'lineNumber: $lineNumber, '
'columnNumber: $columnNumber)';
}
}
print(LoggerStackTrace.from(StackTrace.current).toString());
import 'dart:mirrors';
...
MethodMirror methodMirror = reflect(functionOne).function;
See also https://github.com/dart-lang/sdk/issues/11916#issuecomment-108381556
This will only work in the Dart command line VM, but not in the browser or Flutter because there reflection is not supported.
Code generation solutions like https://pub.dartlang.org/packages/reflectable might work instead where reflection is not available.
https://github.com/dart-lang/sdk/issues/28372 seems related.
LuisDev99's answer doesn't cope well with inner methods and anonymous lambda blocks, so I used a more complex regex approach.
My solution:
/*
Define regex for each entry in the stack
group 0: full line
group 1: stack index
group 2: function name
group 3: package
group 4: file name
group 5: line number
group 6: column number
*/
RegExp regExp = new RegExp(r'^#(\d+) +(.+) +\(package:([^/]+)/(.+\.\w):(\d+):(\d+)\)$');
/* Get the stack as an array of strings */
var frames = StackTrace.current.toString().split("\n");
/* The second entry in the stack is the caller function */
var matches = regExp.allMatches(frames[1])
/* The regex matches each line of the stack only once so only one match */
var match = matches.elementAt(0);
/* Print all groups. Note that "groupCount" doesn't include group 0 (the whole line) */
for (int i = 0; i <= match.groupCount; i++) {
print("group $i: " + match.group(i));
}

How to create node.js module using Typescript

The very simple module that I've created to test the viability of this endeavor. Here is the beginning of SPServerApp.ts:
class SPServerApp {
public AllUsersDict: any;
public AllRoomsDict: any;
constructor () {
this.AllUsersDict = {};
this.AllRoomsDict = {};
}
}
module.exports = SPServerApp();
Then in my app, I have this require statement:
var serverapp = require('./SPServerApp');
I then try to access one of the dictionaries like so:
serverapp.AllUsersDict.hasOwnProperty(nickname)
But get the error:
TypeError: Cannot read property 'hasOwnProperty' of undefined
Can anybody see what I am doing wrong here?
Thanks, E.
The problem is that you forgot the 'new' keyword when calling the constructor. The line should read:
module.exports = new SPServerApp();
If you don't use new your constructor will be treated as a normal function and will just return undefined (since you did not return anything explicitly). Also 'this' will not point to what you expect within the constructor.
Omitting new in Node is actually quite common. But for this to work you have to explicitly guard against new-less calls in the constructor like so:
constructor () {
if (! (this instanceof SPServerApp)) {
return new SPServerApp();
}
this.AllUsersDict = {};
this.AllRoomsDict = {};
}
BTW, in TypeScript you can also use module syntax. The TS compiler will translate this into the export/require statements. With ES6 style modules your example would look like this:
export class SPServerApp {
public AllUsersDict: any;
public AllRoomsDict: any;
constructor () {
this.AllUsersDict = {};
this.AllRoomsDict = {};
}
}
export var serverapp = new SPServerApp();
In your other TS file you just import:
import { serverapp } from './SPServerApp';
serverapp.AllUsersDict.hasOwnProperty('something');

How to upload a Google Docs document in Haskell?

I want to create a Google Docs document from within Haskell, so basically I want to do in Haskell what this little C# program does (adapted from a Google sample program):
using Google.GData.Documents;
using Google.GData.Client;
namespace DocListUploader
{
public class GDocConsole
{
static void Main()
{
var user = "...";
var passwd = "...";
var file = "...";
service = new DocumentsService("DocListUploader");
service.setUserCredentials(user, passwd);
service.UploadDocument(file, null);
}
}
}
From the Google Docs API description here
and this SO answer here I understood it's "only" a matter of sending a couple of HTTP POSTs and getting the OAuth authentification done, but just how? Has anybody already done it and has some code samples for me...?
EDIT: Still could not figure out how to use the oauth libraries, so I just wrote a little C# wrapper:
using Google.GData.Documents;
using Google.GData.Client;
public class GoogleDoc
{
public static int Upload(string user, string passwd, string file)
{
try
{
var service = new DocumentsService("DocListUploader");
service.setUserCredentials(user, passwd);
service.UploadDocument(file, null);
return 0;
}
catch
{
return -1;
}
}
}
and called this wrapper from Haskell via hs-dotnet:
module Upload where
import NET
upload :: String -> String -> String -> IO (Int)
upload user passed file =
invokeStatic "[GoogleDoc.dll]GoogleDoc" "Upload" (user, passed, file)
testLocal :: IO ()
testLocal = do
let user = "..."
let passwd = "..."
let file = "..."
returnCode <- upload user passwd file
putStrLn (show returnCode)
You can use the haskell-oauth library to do the oauth and to upload the documentation, like mentioned already, you can try the http package from Haskell.

How to use stdext::hash_map?

I would like to see a simple example of how to override stdext::hash_compare properly, in order to define a new hash function and comparison operator for my own user-defined type. I'm using Visual C++ (2008).
This is how you can do it
class MyClass_Hasher {
const size_t bucket_size = 10; // mean bucket size that the container should try not to exceed
const size_t min_buckets = (1 << 10); // minimum number of buckets, power of 2, >0
MyClass_Hasher() {
// should be default-constructible
}
size_t operator()(const MyClass &key) {
size_t hash_value;
// do fancy stuff here with hash_value
// to create the hash value. There's no specific
// requirement on the value.
return hash_value;
}
bool operator()(const MyClass &left, const MyClass &right) {
// this should implement a total ordering on MyClass, that is
// it should return true if "left" precedes "right" in the ordering
}
};
Then, you can just use
stdext::hash_map my_map<MyClass, MyValue, MyClass_Hasher>
Here you go, example from MSDN
I prefer using a non-member function.
The method expained in the Boost documentation article Extending boost::hash for a custom data type seems to work.

Resources