hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cd61f999a60a7d86ff92a819e7ad00b810dabbbb | 22,190 | cc | C++ | hackt_docker/hackt/src/main/compile.cc | broken-wheel/hacktist | 36e832ae7dd38b27bca9be7d0889d06054dc2806 | [
"MIT"
] | null | null | null | hackt_docker/hackt/src/main/compile.cc | broken-wheel/hacktist | 36e832ae7dd38b27bca9be7d0889d06054dc2806 | [
"MIT"
] | null | null | null | hackt_docker/hackt/src/main/compile.cc | broken-wheel/hacktist | 36e832ae7dd38b27bca9be7d0889d06054dc2806 | [
"MIT"
] | null | null | null | /**
\file "main/compile.cc"
Converts HAC source code to an object file (pre-unrolled).
This file was born from "art++2obj.cc" in earlier revision history.
$Id: compile.cc,v 1.25 2010/08/05 18:25:31 fang Exp $
*/
#define ENABLE_STACKTRACE 0
#include <iostream>
#include <list>
#include <string>
#include <map>
#include <cstdio>
#include "common/config.hh"
#include "main/compile.hh"
#include "main/main_funcs.hh"
#include "main/compile_options.hh"
#include "main/global_options.hh"
#include "lexer/file_manager.hh"
#if COMPILE_USE_OPTPARSE
#include "util/optparse.tcc"
#endif
#include "util/getopt_portable.h"
#include "util/getopt_mapped.hh"
#include "util/attributes.h"
#include "util/stacktrace.hh"
extern HAC::lexer::file_manager
hackt_parse_file_manager;
namespace HAC {
#include "util/using_ostream.hh"
using entity::module;
using std::list;
using std::string;
using lexer::file_manager;
using util::good_bool;
//=============================================================================
#if !COMPILE_USE_OPTPARSE
/**
Entry for options.
*/
struct compile::options_modifier_info {
options_modifier op;
string brief;
options_modifier_info() : op(NULL), brief() { }
options_modifier_info(const options_modifier o, const char* b) :
op(o), brief(b) { }
operator bool () const { return op; }
good_bool
operator () (options& o) const {
NEVER_NULL(op);
return (*op)(o);
}
}; // end struct options_modifier_info
#endif
//=============================================================================
// class compile static initializers
const char
compile::name[] = "compile";
const char
compile::brief_str[] = "Compiles HACKT source to object file.";
#if COMPILE_USE_OPTPARSE
typedef util::options_map_impl<compile_options> options_map_impl_type;
typedef options_map_impl_type::opt_map_type opt_map_type;
static options_map_impl_type options_map_wrapper;
#else
/**
Options modifier map must be initialized before any registrations.
*/
const compile::options_modifier_map_type
compile::options_modifier_map;
#endif
//=============================================================================
static const char default_options_brief[] = "Needs description.";
#if COMPILE_USE_OPTPARSE
class compile::register_options_modifier {
typedef options_map_impl_type::opt_entry opt_entry;
typedef options_map_impl_type::opt_func modifier_type;
const opt_entry& receipt;
public:
register_options_modifier(const string& Mode,
const modifier_type COM,
const string& h = default_options_brief) :
receipt(options_map_wrapper.options_map[Mode] =
opt_entry(COM, NULL, NULL, h)) {
}
register_options_modifier(const string& Mode,
const modifier_type COM,
const char* h) :
receipt(options_map_wrapper.options_map[Mode] =
opt_entry(COM, NULL, NULL, h)) {
}
} __ATTRIBUTE_UNUSED__ ;
#else
/**
Options modification registration interface.
*/
class compile::register_options_modifier {
public:
register_options_modifier(const string& optname,
const options_modifier om,
const char* b = default_options_brief) {
options_modifier_map_type&
omm(const_cast<options_modifier_map_type&>(
options_modifier_map));
NEVER_NULL(om);
options_modifier_info& i(omm[optname]);
INVARIANT(!i);
i.op = om;
i.brief = b;
}
} __ATTRIBUTE_UNUSED__; // end class register_options_modifier
#endif // COMPILE_USE_OPTPARSE
//=============================================================================
// compile::options_modifier declarations and definitions
// Texinfo documentation is below, under -f option.
#if COMPILE_USE_OPTPARSE
#define OPTARG const util::option_value& v,
#define OPTARG_UNUSED const util::option_value&,
#define OPTARG_FWD v,
typedef bool optfun_return_type;
#define OPTFUN_RETURN return false;
#else
#define OPTARG
#define OPTARG_UNUSED
#define OPTARG_FWD
typedef good_bool optfun_return_type;
#define OPTFUN_RETURN return good_bool(true);
#endif
using HAC::parser::parse_options;
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#if COMPILE_USE_OPTPARSE
#define SET_OPT(t,m,v) \
options_map_impl_type::set_member_constant<t, &compile_options::m, v>
#define SET_OPT2(t1,m1,t2,m2,v) \
options_map_impl_type::set_member_member_constant< \
t1, t2, &compile_options::m1, &t1::m2, v>
#define SET_BOOL_OPT(m,v) SET_OPT(bool, m, v)
#define SET_BOOL_OPT2(t1,m1,t2,m2,v) SET_OPT2(t1, m1, bool, m2, v)
#define SET_PARSE_OPT2(t2,m2,v) \
SET_OPT2(parse_options, parse_opts, t2, m2, v)
#endif
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#if COMPILE_USE_OPTPARSE
#define DEFINE_OPTION(type, mem, key, val, str) \
static const compile::register_options_modifier \
compile_opt_mod_ ## mem(key, &SET_OPT(type, mem, val), str);
#define DEFINE_BOOL_OPTION(mem, key, val, str) \
DEFINE_OPTION(bool, mem, key, val, str)
#define DEFINE_OPTION2(type1, mem1, type2, mem2, key, val, str) \
static const compile::register_options_modifier \
compile_opt_mod_ ## mem2 ## _ ## val(key, \
&SET_OPT2(type1, mem1, type2, mem2, val), str);
#define DEFINE_PARSE_OPTION2(type2, mem2, key, val, str) \
DEFINE_OPTION2(parse_options, parse_opts, \
type2, mem2, key, val, str)
#define DEFINE_CREATE_OPTION2(type2, mem2, key, val, str) \
DEFINE_OPTION2(create_options, create_opts, \
type2, mem2, key, val, str)
#endif
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#if COMPILE_USE_OPTPARSE
#define DEFINE_BOOL_OPTION_PAIR(mem, key, truestr, falsestr) \
static const compile::register_options_modifier \
compile_opt_mod_ ## mem(key, &SET_BOOL_OPT(mem, true), truestr), \
compile_opt_mod_no_## mem("no-" key, &SET_BOOL_OPT(mem, false), \
falsestr);
#define DEFINE_BOOL_PARSE_OPTION_PAIR(mem, key, truestr, falsestr) \
DEFINE_PARSE_OPTION2(bool, mem, key, true, truestr) \
DEFINE_PARSE_OPTION2(bool, mem, "no-" key, false, falsestr)
#else
#define DEFINE_BOOL_OPTION_PAIR(mem, key, truestr, falsestr) \
static \
optfun_return_type \
__compile_ ## mem(OPTARG_UNUSED compile::options& cf) { \
cf.mem = true; \
OPTFUN_RETURN \
} \
static \
optfun_return_type \
__compile_no_ ## mem(OPTARG_UNUSED compile::options& cf) { \
cf.mem = false; \
OPTFUN_RETURN \
} \
static const compile::register_options_modifier \
compile_opt_mod_ ## mem(key, &__compile_ ## mem, truestr), \
compile_opt_mod_no_## mem("no-" key, &__compile_no_ ## mem, falsestr);
#endif
//-----------------------------------------------------------------------------
DEFINE_BOOL_OPTION_PAIR(dump_include_paths, "dump-include-paths",
"dumps -I include paths as they are processed",
"suppress feedback of -I include paths")
//-----------------------------------------------------------------------------
DEFINE_BOOL_OPTION_PAIR(dump_object_header, "dump-object-header",
"dumps persistent object header before saving",
"suppress persistent object header dump")
//-----------------------------------------------------------------------------
// dialect flags
// texinfo documentation is below under option-f
DEFINE_PARSE_OPTION2(bool, export_all, "export-all", true,
"treat all definitions as exported")
DEFINE_PARSE_OPTION2(bool, export_all, "export-strict", false,
"only export definitions that are marked as such (default, ACT)")
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// the following are create-phase options forwarded to the create phase
DEFINE_CREATE_OPTION2(canonicalize_policy, canonicalize_mode,
"canonical-shortest-hier", SHORTEST_HIER_NO_LENGTH,
"prefer aliases by number of hierarchy levels only (default)")
DEFINE_CREATE_OPTION2(canonicalize_policy, canonicalize_mode,
"canonical-shortest-length", SHORTEST_HIER_MIN_LENGTH,
"prefer aliases using overall length as tie-breaker")
DEFINE_CREATE_OPTION2(canonicalize_policy, canonicalize_mode,
"canonical-shortest-stage", SHORTEST_EMULATE_ACT,
"prefer aliases using per-member length as tie-breaker (ACT, unimplemented)")
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
DEFINE_BOOL_PARSE_OPTION_PAIR(namespace_instances, "namespace-instances",
"allow instance management outside global namespace (default)",
"forbid instance management outside global namespace (ACT)")
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
DEFINE_BOOL_PARSE_OPTION_PAIR(array_internal_nodes, "array-internal-nodes",
"allow implicit arrays of internal nodes in PRS (default)",
"reject implicit arrays of internal nodes in PRS (ACT)")
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#if COMPILE_USE_OPTPARSE
template <error_policy parse_options::*mem>
static
bool
__set_policy_member(const util::option_value& opt,
compile_options& c_opt) {
const size_t s = opt.values.size();
if (s >= 1) {
if (s > 1) {
cerr << "Warning: extra arguments passed to \'" << opt.key
<< "\' option ignored." << endl;
}
const string& p(opt.values.front());
if (p == "ignore") {
c_opt.parse_opts.*mem = OPTION_IGNORE;
} else if (p == "warn") {
c_opt.parse_opts.*mem = OPTION_WARN;
} else if (p == "error") {
c_opt.parse_opts.*mem = OPTION_ERROR;
} else {
cerr << "Error: error policy values for option " <<
opt.key << " are [ignore|warn|error]." << endl;
return true;
}
}
return false;
}
static const compile::register_options_modifier
__compile_om_case_collision("case-collision",
&__set_policy_member<&parse_options::case_collision_policy>,
"handle case-insensitive collisions (= ignore|[warn]|error)");
#else
static
good_bool
__compile_case_collision_ignore(compile::options& o) {
o.parse_opts.case_collision_policy = OPTION_IGNORE;
return good_bool(true);
}
static
good_bool
__compile_case_collision_warn(compile::options& o) {
o.parse_opts.case_collision_policy = OPTION_WARN;
return good_bool(true);
}
static
good_bool
__compile_case_collision_error(compile::options& o) {
o.parse_opts.case_collision_policy = OPTION_ERROR;
return good_bool(true);
}
// TODO: actually parse the policy argument using optparse()
static const compile::register_options_modifier
__compile_om_case_collision_ignore("case-collision=ignore",
&__compile_case_collision_ignore,
"ignore case-insensitive collisions"),
__compile_om_case_collision_warn("case-collision=warn",
&__compile_case_collision_warn,
"warn about case-insensitive collisions (default)"),
__compile_om_case_collision_error("case-collision=error",
&__compile_case_collision_error,
"reject case-insensitive collisions");
#endif // COMPILE_USE_OPTPARSE
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
static const compile::register_options_modifier
__compile_om_unknown_spec("unknown-spec",
&__set_policy_member<&parse_options::unknown_spec_policy>,
"handle unknown spec directives (= ignore|warn|[error])");
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
static
optfun_return_type
__compile_ACT(OPTARG_UNUSED compile::options& o) {
#if COMPILE_USE_OPTPARSE
o.parse_opts.export_all = false;
o.parse_opts.namespace_instances = false;
o.parse_opts.array_internal_nodes = false;
#else
__compile_export_strict(o);
__compile_no_namespace_instances(o);
__compile_no_array_internal_nodes(o);
#endif
OPTFUN_RETURN
}
static const compile::register_options_modifier
__compile_om_ACT("ACT", &__compile_ACT,
"preset: all ACT-mode flags maximum compatibility");
//=============================================================================
// class compile method definitions
compile::compile() { }
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/**
The main program for compiling source to object.
Also parses options and sets flags.
\return negative number for non-error 'exit-now' status,
0 for success, positive number for other error.
TODO: is there a way to return the number of arguments parsed,
or just optind?
*/
int
compile::make_module(int argc, char* argv[], options& opt,
count_ptr<module>& ret) {
STACKTRACE_VERBOSE;
if (parse_command_options(argc, argv, opt)) {
usage();
return 1;
}
argv += optind; // shift
argc -= optind;
const int max_args = opt.use_stdin ? 1 : 2;
const int target_ind = max_args -1;
if (argc > max_args || argc <= 0) {
usage();
return 1;
}
if (!opt.use_stdin) {
opt.source_file = argv[0];
// or use util::memory::excl_ptr<FILE, fclose_tag>
FILE* f = open_source_file(opt.source_file.c_str());
if (!f)
return 1;
fclose(f);
}
// dependency generation setup
if (!opt.have_target()) {
// if not already named by -o, use next non-option argument
if (argc >= max_args) {
opt.target_object = argv[target_ind];
} else {
// default: append 'o' to get object file name
// problem: doesn't automatically strip srcdir
// opt.target_object = opt.source_file + 'o';
}
} // else ignore argv[1], use whatever was set before
// have target by now
if (opt.have_target()) {
if (!check_file_writeable(opt.target_object.c_str()).good)
return 1;
}
// parse it
ret = parse_and_check(
opt.use_stdin ? NULL : opt.source_file.c_str(), opt);
if (!ret) {
return 1;
}
return 0;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int
compile::main(const int argc, char* argv[], const global_options&) {
options opt;
count_ptr<module> mod;
const int err = make_module(argc, argv, opt, mod);
if (err < 0) {
return 1;
} else if (err > 0) {
return err;
}
if (!mod) {
return 1;
}
// if (argc -optind >= 2)
if (opt.have_target()) {
// save_module(*mod, opt.target_object);
// save_module_debug(*mod, opt.target_object);
save_module_debug(*mod, opt.target_object.c_str(),
opt.dump_object_header);
}
if (opt.dump_module)
mod->dump(cerr);
return 0;
}
//-----------------------------------------------------------------------------
/**
\return 0 if is ok to continue, anything else will signal early
termination, an error will cause exit(1).
Set global variable optind to the number of initial tokens to
skip (default = 1).
NOTE: the getopt option string begins with '+' to enforce
POSIXLY correct termination at the first non-option argument.
*/
int
compile::parse_command_options(const int argc, char* argv[], options& opt) {
STACKTRACE_VERBOSE;
static const char* optstring = "+df:hi:I:M:o:pv";
int c;
while ((c = getopt(argc, argv, optstring)) != -1) {
switch (c) {
/***
@texinfo compile/option-d.texi
@defopt -d
Produces text dump of compiled module,
like @command{hacobjdump} in @ref{Objdump}.
@end defopt
@end texinfo
***/
case 'd':
opt.dump_module = true;
break;
// TODO: summarize ACT-compatibility in form of a table
/***
@texinfo compile/option-f.texi
@defopt -f optname
general compile flags (repeatable) where @var{optname} is one of the following:
@itemize
@item @option{dump-include-paths}:
dumps @option{-I} include paths as they are processed
@item @option{dump-object-header}:
(diagnostic) dumps persistent object header before saving
@item @option{no-dump-include-paths}:
suppress feedback of @option{-I} include paths
@item @option{no-dump-object-header}:
suppress persistent object header dump
@item @option{case-collision=[ignore|warn|error]}:
Set the error handling policy for case-insensitive collisions.
@itemize
@item @option{ignore} skips the check altogether
@item @option{warn} issues a warning but continues
@item @option{error} rejects and aborts compiling
@end itemize
@item @option{unknown-spec=[ignore|warn|error]}:
Sets the error handling policy for unknown spec directives.
@end itemize
Dialect flags (for ACT-compatibility):
@itemize
@item @option{export-all}:
Treat all definitions as exported, i.e. no export checking.
@item @option{export-strict}:
Check that definitions are exported for use outside their
respective home namespaces (default, ACT).
@item @option{namespace-instances}
Allow instance management outside global namespace (default).
Negatable with @t{no-} prefixed.
ACT mode: @option{no-namespace-instances}.
@item @option{array-internal-nodes}
Allow implicit arrays of internal nodes in PRS (default).
Negatable with @t{no-} prefixed.
ACT mode: @option{no-array-internal-nodes}.
@end itemize
@option{ACT} is a preset that activates all ACT-mode flags for compatibility.
The following options are forwarded to the create-phase of compilation
by the driver. That is, they do not have any affect until the create phase.
These options must be specified up-front at compile-time and cannot be
overriden at create-time on the command line.
@itemize
@item @option{canonical-shortest-hier}:
Only consider hierarchical depth (number of member-dots) for
choosing canonical alias, no further tiebreaker.
@item @option{canonical-shortest-length}:
In addition to minimizing the hierarchy depth, also use overall
string length as a tiebreaker.
@item @option{canonical-shortest-stage}: (unimplemented)
Considers length of identifiers stage-by-stage when hierarchical
depths are equal.
This is for best compatibility with ACT mode.
@end itemize
@end defopt
@end texinfo
***/
case 'f': {
#if COMPILE_USE_OPTPARSE
typedef opt_map_type::const_iterator const_iterator;
const opt_map_type&
options_modifier_map(options_map_wrapper.options_map);
const util::option_value ov(util::optparse(optarg));
const const_iterator mi(options_modifier_map.find(ov.key));
#else
typedef options_modifier_map_type::mapped_type mapped_type;
typedef options_modifier_map_type::const_iterator const_iterator;
const const_iterator mi(options_modifier_map.find(optarg));
#endif
if (mi == options_modifier_map.end()
#if !COMPILE_USE_OPTPARSE
|| !mi->second
#endif
) {
cerr << "Invalid option argument: " << optarg << endl;
return 1;
}
#if COMPILE_USE_OPTPARSE
else if ((mi->second.func)(ov, opt))
#else
else if (!((mi->second)(opt).good))
#endif
{
return 1;
}
break;
}
/***
@texinfo compile/option-h.texi
@defopt -h
Show usage and exit.
@end defopt
@end texinfo
***/
case 'h':
// return 1;
usage();
exit(0);
break;
/***
@texinfo compile/option-I-upper.texi
@defopt -I path
Adds include path @var{path} for importing other source files (repeatable).
@end defopt
@end texinfo
***/
case 'I':
// no need to check validity of paths yet
opt.include_paths.push_back(optarg);
break;
/***
@texinfo compile/option-i.texi
@defopt -i file
Import @var{file}(s) before processing the main top-level file (repeatable).
All @option{-I} search paths take effect before any of these
files are imported.
@end defopt
@end texinfo
***/
case 'i':
// no need to check validity of paths yet
opt.prepend_files.push_back(optarg);
break;
/***
@texinfo compile/option-M-upper.texi
@defopt -M depfile
Emit import dependencies in file @var{depfile} as a side-effect.
Useful for automatic dynamic dependency-tracking in Makefiles.
@end defopt
@end texinfo
***/
case 'M':
opt.make_depend = true;
opt.make_depend_target = optarg;
break;
/***
@texinfo compile/option-o.texi
@defopt -o objfile
Names @var{objfile} as the output object file to save.
This is an alternative to naming the object file as the second
non-option argument.
@end defopt
@end texinfo
***/
case 'o':
opt.target_object = optarg;
break;
/***
@texinfo compile/option-p.texi
@defopt -p
Expect input to be piped from stdin rather than a named file.
Since the name of the input file is omitted in this case,
the only non-option argument (if any) is interpreted as the name
of the output object file.
@end defopt
@end texinfo
***/
case 'p':
opt.use_stdin = true;
break;
/***
@texinfo compile/option-v.texi
@defopt -v
Show version and build information and exit.
@end defopt
@end texinfo
***/
case 'v':
config::dump_all(cout);
exit(0);
break;
case ':':
cerr << "Expected but missing non-option argument." << endl;
return 1;
case '?':
util::unknown_option(cerr, optopt);
return 1;
default:
abort();
} // end switch
} // end while
/***
Now would be a good time to add include paths
to the parser's file manager.
Don't use a global file_manager, use local variables
and pass as arguments, to allow these main subprograms
to be re-entrant.
Q: Should file_manager be a member of module?
Caution: calling this function multiple times with the
same options object will accumulate duplicate paths.
***/
opt.export_include_paths(hackt_parse_file_manager);
return 0;
}
//-----------------------------------------------------------------------------
/**
Prints summary of options and arguments.
*/
void
compile::usage(void) {
cerr << "compile: compiles input file to module object file" << endl;
cerr << "usage: compile [options] <hackt-source-file> [hackt-obj-file]"
<< endl;
cerr << "options:" << endl;
cerr << " -d: produces text dump of compiled module" << endl <<
" -f <opt> : general compile flags (repeatable)" << endl;
{
#if COMPILE_USE_OPTPARSE
options_map_wrapper.help(cerr, false, false);
#else
typedef options_modifier_map_type::const_iterator const_iterator;
const_iterator i(options_modifier_map.begin());
const const_iterator e(options_modifier_map.end());
for ( ; i!=e; ++i) {
cerr << " " << i->first << ": " <<
i->second.brief << endl;
}
#endif
}
cerr << " -h: gives this usage message and exits" << endl <<
" -I <path> : adds include path (repeatable)" << endl <<
" -i <file> : prepends import file (repeatable)" << endl;
cerr << " -M <dependfile> : produces make dependency to file" << endl;
cerr << " -o <objfile> : option to name output object file" << endl;
cerr << " -p : pipe in source from stdin" << endl;
cerr << " -v : print version information and exit" << endl;
cerr << "If no output object file is given, compiled module will not be saved."
<< endl;
}
//=============================================================================
} // end namespace HAC
| 30.819444 | 80 | 0.672105 | [
"object"
] |
cd68866a7b05112659ad897107233759dac740ed | 12,142 | cpp | C++ | messungen/server_client/corr_client_opencl_17/corr_client_opencl/CorrWorker.cpp | tihmstar/gido_public | dcc523603b9a27b37752211715a10e30b51ce812 | [
"Unlicense"
] | 16 | 2021-04-10T16:28:00.000Z | 2021-12-12T10:15:23.000Z | messungen/server_client/corr_client_opencl_17/corr_client_opencl/CorrWorker.cpp | tihmstar/gido_public | dcc523603b9a27b37752211715a10e30b51ce812 | [
"Unlicense"
] | null | null | null | messungen/server_client/corr_client_opencl_17/corr_client_opencl/CorrWorker.cpp | tihmstar/gido_public | dcc523603b9a27b37752211715a10e30b51ce812 | [
"Unlicense"
] | 2 | 2021-04-10T16:32:36.000Z | 2021-04-11T14:13:45.000Z | //
// CorrWorker.cpp
// corr_client_opencl
//
// Created by tihmstar on 19.03.20.
// Copyright © 2020 tihmstar. All rights reserved.
//
#include "CorrWorker.hpp"
#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <stdio.h>
#include <signal.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "CPULoader.hpp"
#include <stdlib.h>
//#warning custom point_per_trace
//#define NUMBER_OF_POINTS_OVERWRITE 2000
#define assure(cond) do {if (!(cond)) {printf("ERROR: CorrWorker ASSURE FAILED ON LINE=%d\n",__LINE__); throw(__LINE__); }}while (0)
#define assure_(cond) do {cl_int clret = 0; if ((clret = cond)) {printf("ERROR: CorrWorker ASSURE FAILED ON LINE=%d with err=%d\n",__LINE__,clret); throw(__LINE__);}}while (0)
#ifndef ntohll
uint64_t ntohll(uint64_t in){
volatile uint64_t out[1] = {1};
if ((*(uint8_t*)out) == 1){
//little endian, do swap
((uint8_t*)out)[7] = (in >> 0x00) & 0xff;
((uint8_t*)out)[6] = (in >> 0x08) & 0xff;
((uint8_t*)out)[5] = (in >> 0x10) & 0xff;
((uint8_t*)out)[4] = (in >> 0x18) & 0xff;
((uint8_t*)out)[3] = (in >> 0x20) & 0xff;
((uint8_t*)out)[2] = (in >> 0x28) & 0xff;
((uint8_t*)out)[1] = (in >> 0x30) & 0xff;
((uint8_t*)out)[0] = (in >> 0x38) & 0xff;
}else{
out[0] = in;
}
return out[0];
}
#endif
#define senduint32_t(num) do { uint32_t s = htonl(num);assure(write(_serverFd, &s, sizeof(s)) == sizeof(s)); }while(0)
#define receiveuint32_t() [this]()->uint32_t{ uint32_t s = 0; assure(doread(_serverFd, &s, sizeof(s)) == sizeof(s)); s = htonl(s); return s;}()
#define senduint64_t(num) do { uint64_t s = ntohll(num);assure(write(_serverFd, &s, sizeof(s)) == sizeof(s)); }while(0)
#define receiveuint64_t() [this]()->uint64_t{ uint64_t s = 0; assure(doread(_serverFd, &s, sizeof(s)) == sizeof(s)); s = ntohll(s); return s;}()
using namespace std;
static ssize_t doread(int fd, void *buf, ssize_t size){
ssize_t didread = 0;
do{
ssize_t curdidread = read(fd, static_cast<uint8_t*>(buf)+didread, size-didread);
assure(curdidread>0);
didread += curdidread;
}while (didread<size);
return didread;
}
CorrWorker::CorrWorker(std::string tracesIndir, const char *serverAddress, uint16_t port, std::vector<int> gpus, std::string kernelsource, size_t availableRamSize, float workermultiplier)
: _serverFd(-1), _tracesIndir(tracesIndir), _kernelsource(kernelsource), _availableRamSize(availableRamSize), _point_per_trace(0), _workerThread(NULL),
_workerShouldStop(false), _workerIsRunning(false)
{
struct sockaddr_in servaddr = {};
uint32_t num_of_powermodels = 0;
if (_tracesIndir.c_str()[_tracesIndir.size()-1] != '/') {
_tracesIndir += '/';
}
printf("[CorrWorker] init\n");
assure((_serverFd = socket(AF_INET, SOCK_STREAM, 0)) != -1);
// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr(serverAddress);
servaddr.sin_port = htons(port);
printf("[CorrWorker] connecting to server=%s:%u ...\n",serverAddress,port);
assure(!connect(_serverFd, (struct sockaddr *)&servaddr, sizeof(servaddr)));
printf("[CorrWorker] connected!\n");
/*
init sequence:
--- Server -> Cient ---
send point_per_trace //uint32_t
send num_of_powermodels //uint32_t
send power models seperated by \x00 byte
[
model\x00
model\x00 ...
]
--- Cient -> Server ---
send num_of_gpus //uint32_t
*/
_point_per_trace = receiveuint32_t();
num_of_powermodels = receiveuint32_t();
#ifdef NUMBER_OF_POINTS_OVERWRITE
assure(_point_per_trace == NUMBER_OF_POINTS_OVERWRITE);
#endif
for (int i=0; i<num_of_powermodels; i++) {
char c = 0;
std::string curstr;
do{
read(_serverFd, &c, 1);
curstr += c;
}while(c);
_powermodels.push_back(curstr.substr(0,curstr.size()-1));
}
for (auto &m : _powermodels) {
printf("[CorrWorker] Model=%s\n",m.c_str());
}
printf("[CorrWorker] Got %3lu powerModels!\n",_powermodels.size());
#pragma mark init GPUS
// Get platform and device information
cl_platform_id platform_id = NULL;
cl_uint num_platforms = 0;
cl_uint num_devices = 0;
assure_(clGetPlatformIDs(1, &platform_id, &num_platforms));
assure_(clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU, 0, NULL, &num_devices));
{
cl_device_id device_ids[num_devices];
assure_(clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU, num_devices, device_ids, &num_devices));
for (int index : gpus) {
printf("[CorrWorker] Init GPU %d!\n",index);
assure(index < num_devices);
_gpus.push_back(new GPUDevice(index,device_ids[index],kernelsource, _point_per_trace, _powermodels));
}
}
printf("[CorrWorker] All GPUs initialized\n");
uint32_t workers = (uint32_t)gpus.size();
workers *= workermultiplier;
assure(workers != 0);
printf("[CorrWorker] workers=%u\n",workers);
senduint32_t(workers);
}
CorrWorker::~CorrWorker(){
_workerShouldStop = true;
{
int fd = _serverFd;_serverFd = -1;
close(fd);
}
if (_workerThread) _workerThread->join();
if (!_workerIsRunning) raise(SIGINT); //sanity check
if (_workerThread) {
delete _workerThread;
_workerThread = NULL;
}
}
void CorrWorker::worker(uint16_t maxLoaderThreads){
_workerIsRunning = true;
while (!_workerShouldStop) {
uint32_t batchSize = 0;
batchSize = receiveuint32_t();
printf("[CorrWorker] Got batchsize=%u\n",batchSize);
std::vector<std::string> bachFilenames;
for (int i=0; i<batchSize; i++) {
char c = 0;
std::string curstr;
do{
read(_serverFd, &c, 1);
curstr += c;
}while(c);
bachFilenames.push_back(_tracesIndir + curstr.substr(0,curstr.size()-1));
}
for (auto &f : bachFilenames) {
printf("[CorrWorker] Batch Filename=%s\n",f.c_str());
}
senduint32_t(batchSize);
#pragma mark doGPUComputation
CPULoader cloader(bachFilenames, _availableRamSize, maxLoaderThreads);
std::queue<std::thread *> gpuTransferThreads;
#define MIN_TRANSFER_CNT 0
#define MAX_TRANSFER_CNT 25000
for (auto &gpu : _gpus) {
gpuTransferThreads.push(new std::thread([&cloader](GPUDevice *gpu)->void{
LoadFile *toTransfer = NULL;
while (LoadFile *file = cloader.dequeue()) {
if (toTransfer) { //if we have "toTransfer"
if (
toTransfer->tracesInFile() >= MIN_TRANSFER_CNT //if "toTransfer" already large enough
|| toTransfer->tracesInFile() + file->tracesInFile() > MAX_TRANSFER_CNT //or combination would exceed MAX limit
) {
//then transfer the pendin trace
gpu->transferTrace(toTransfer);
delete toTransfer;
toTransfer = NULL;
}
}
if (!toTransfer) { //if we don't have a pending trace anymore, make "file" be our new pending trace
toTransfer = file; file = NULL;
continue;
}
//if we have both: "transferTrace" and "file", then we should combine them now
printf("[DW-%u] combining traces (%5u + %5u = %5u)\n",gpu->deviceNum(),toTransfer->tracesInFile(), file->tracesInFile(), toTransfer->tracesInFile() + file->tracesInFile());
*toTransfer += *file;
//once we combined traces, we can discard "file"
if (file) {
delete file; file = NULL;
}
}
//final transfer
if (toTransfer) {
gpu->transferTrace(toTransfer);
delete toTransfer;
toTransfer = NULL;
}
printf("GPU %d done transfer!\n",gpu->deviceNum());
},gpu));
}
printf("Waiting for gpu transfers to finish (%lu threads)!\n",gpuTransferThreads.size());
while (gpuTransferThreads.size()) {
auto t = gpuTransferThreads.front();
gpuTransferThreads.pop();
t->join();
delete t;
}
printf("All GPU transfers finished, getting results...\n");
std::map<std::string,std::map<std::string,CPUModelResults*>> allmodelresults;
for (auto &gpu : _gpus) {
gpu->getResults(allmodelresults);
}
#pragma mark sendBackResults
/*
Protocol:
--- Client -> Server ---
send allmodelresults.size() //uint32_t
send models
[
modelresultcategory\x00 //terminated by zero byte
[
send allmodelresults[x].size() //uint32_t
modelresultname\x00 //terminated by zero byte
cpumodelresultsize //uint64_t
< raw data >
]
....
]
send 00000000 //uint32_t
*/
srand((unsigned int)time(NULL) ^ rand());
uint32_t myrand = rand();
uint32_t remoteRand = 0;
senduint32_t(myrand);
remoteRand = receiveuint32_t();
senduint32_t(allmodelresults.size());
int allmodelresultsCounter = 0;
for (auto &category : allmodelresults) {
assure(allmodelresultsCounter++ < allmodelresults.size()); //don't send more than we announced
assure(write(_serverFd, category.first.c_str(), category.first.size()+1) == category.first.size()+1); //modelresultcategory\x00 //terminated by zero byte
senduint32_t(category.second.size()); //send allmodelresults[x].size() //uint32_t
int modelresultcategorycounter = 0;
for (auto &mr : category.second) {
assure(modelresultcategorycounter++ < category.second.size()); //don't send more than we announced
assure(write(_serverFd, mr.first.c_str(), mr.first.size()+1) == mr.first.size()+1); // modelresultname\x00 //terminated by zero byte
void *data = NULL;
size_t dataSize = 0;
mr.second->serialize(&data, &dataSize);
uint64_t dataSizeSend = (uint64_t)dataSize;
assure(dataSizeSend == dataSize); //no casting issues here
senduint64_t(dataSizeSend); //cpumodelresultsize //uint64_t
assure(write(_serverFd, data, dataSizeSend) == dataSizeSend); // < raw data >
free(data);
}
}
senduint32_t(myrand ^ remoteRand); //final check
for (auto &gpu : _gpus) {
gpu->resetDevice();
}
for (auto & category : allmodelresults) {
for (auto &model: category.second) {
delete model.second; model.second = NULL;
}
}
}
_workerIsRunning = false;
}
void CorrWorker::startWorker(uint16_t maxLoaderThreads){
_workerThread = new std::thread([this](uint16_t loadthreads){
worker(loadthreads);
}, maxLoaderThreads);
}
void CorrWorker::stopWorker(){
_workerShouldStop = true;
}
| 32.816216 | 192 | 0.558887 | [
"vector",
"model"
] |
cd6c6cfb3c4f8f77fe4b027bf3a3ebf4709db7a6 | 7,814 | cc | C++ | tensorflow/lite/tools/evaluation/tasks/imagenet_image_classification/run_eval.cc | NeerajBhadani/tensorflow | 8c849c65503fef22f49f7ab843803fca9c439bdf | [
"Apache-2.0"
] | 4 | 2020-04-19T11:30:20.000Z | 2020-07-02T07:13:15.000Z | tensorflow/lite/tools/evaluation/tasks/imagenet_image_classification/run_eval.cc | NeerajBhadani/tensorflow | 8c849c65503fef22f49f7ab843803fca9c439bdf | [
"Apache-2.0"
] | 2 | 2021-08-25T16:01:49.000Z | 2022-02-10T01:13:06.000Z | tensorflow/lite/tools/evaluation/tasks/imagenet_image_classification/run_eval.cc | NeerajBhadani/tensorflow | 8c849c65503fef22f49f7ab843803fca9c439bdf | [
"Apache-2.0"
] | 1 | 2021-08-29T09:37:58.000Z | 2021-08-29T09:37:58.000Z | /* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <cstdlib>
#include <fstream>
#include <string>
#include <vector>
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/tools/command_line_flags.h"
#include "tensorflow/lite/tools/evaluation/evaluation_delegate_provider.h"
#include "tensorflow/lite/tools/evaluation/proto/evaluation_config.pb.h"
#include "tensorflow/lite/tools/evaluation/proto/evaluation_stages.pb.h"
#include "tensorflow/lite/tools/evaluation/stages/image_classification_stage.h"
#include "tensorflow/lite/tools/evaluation/utils.h"
namespace tflite {
namespace evaluation {
constexpr char kModelFileFlag[] = "model_file";
constexpr char kGroundTruthImagesPathFlag[] = "ground_truth_images_path";
constexpr char kGroundTruthLabelsFlag[] = "ground_truth_labels";
constexpr char kOutputFilePathFlag[] = "output_file_path";
constexpr char kModelOutputLabelsFlag[] = "model_output_labels";
constexpr char kBlacklistFilePathFlag[] = "blacklist_file_path";
constexpr char kNumImagesFlag[] = "num_images";
constexpr char kInterpreterThreadsFlag[] = "num_interpreter_threads";
constexpr char kDelegateFlag[] = "delegate";
template <typename T>
std::vector<T> GetFirstN(const std::vector<T>& v, int n) {
if (n >= v.size()) return v;
std::vector<T> result(v.begin(), v.begin() + n);
return result;
}
bool EvaluateModel(const std::string& model_file_path,
const std::vector<ImageLabel>& image_labels,
const std::vector<std::string>& model_labels,
std::string delegate, std::string output_file_path,
int num_interpreter_threads,
const DelegateProviders& delegate_providers) {
EvaluationStageConfig eval_config;
eval_config.set_name("image_classification");
auto* classification_params = eval_config.mutable_specification()
->mutable_image_classification_params();
auto* inference_params = classification_params->mutable_inference_params();
inference_params->set_model_file_path(model_file_path);
inference_params->set_num_threads(num_interpreter_threads);
inference_params->set_delegate(ParseStringToDelegateType(delegate));
if (!delegate.empty() &&
inference_params->delegate() == TfliteInferenceParams::NONE) {
LOG(WARNING) << "Unsupported TFLite delegate: " << delegate;
return false;
}
classification_params->mutable_topk_accuracy_eval_params()->set_k(10);
ImageClassificationStage eval(eval_config);
eval.SetAllLabels(model_labels);
if (eval.Init(&delegate_providers) != kTfLiteOk) return false;
const int step = image_labels.size() / 100;
for (int i = 0; i < image_labels.size(); ++i) {
if (step > 1 && i % step == 0) {
LOG(INFO) << "Evaluated: " << i / step << "%";
}
eval.SetInputs(image_labels[i].image, image_labels[i].label);
if (eval.Run() != kTfLiteOk) return false;
}
std::ofstream metrics_ofile;
metrics_ofile.open(output_file_path, std::ios::out);
metrics_ofile << eval.LatestMetrics().DebugString();
metrics_ofile.close();
return true;
}
int Main(int argc, char* argv[]) {
// Command Line Flags.
std::string model_file_path;
std::string ground_truth_images_path;
std::string ground_truth_labels_path;
std::string model_output_labels_path;
std::string blacklist_file_path;
std::string output_file_path;
std::string delegate;
int num_images = 0;
int num_interpreter_threads = 1;
std::vector<tflite::Flag> flag_list = {
tflite::Flag::CreateFlag(kModelFileFlag, &model_file_path,
"Path to test tflite model file."),
tflite::Flag::CreateFlag(
kModelOutputLabelsFlag, &model_output_labels_path,
"Path to labels that correspond to output of model."
" E.g. in case of mobilenet, this is the path to label "
"file where each label is in the same order as the output"
" of the model."),
tflite::Flag::CreateFlag(
kGroundTruthImagesPathFlag, &ground_truth_images_path,
"Path to ground truth images. These will be evaluated in "
"alphabetical order of filename"),
tflite::Flag::CreateFlag(
kGroundTruthLabelsFlag, &ground_truth_labels_path,
"Path to ground truth labels, corresponding to alphabetical ordering "
"of ground truth images."),
tflite::Flag::CreateFlag(
kBlacklistFilePathFlag, &blacklist_file_path,
"Path to blacklist file (optional) where each line is a single "
"integer that is "
"equal to index number of blacklisted image."),
tflite::Flag::CreateFlag(kOutputFilePathFlag, &output_file_path,
"File to output metrics proto to."),
tflite::Flag::CreateFlag(kNumImagesFlag, &num_images,
"Number of examples to evaluate, pass 0 for all "
"examples. Default: 0"),
tflite::Flag::CreateFlag(
kInterpreterThreadsFlag, &num_interpreter_threads,
"Number of interpreter threads to use for inference."),
tflite::Flag::CreateFlag(kDelegateFlag, &delegate,
"Delegate to use for inference, if available. "
"Must be one of {'nnapi', 'gpu'}"),
};
tflite::Flags::Parse(&argc, const_cast<const char**>(argv), flag_list);
DelegateProviders delegate_providers;
delegate_providers.InitFromCmdlineArgs(&argc, const_cast<const char**>(argv));
// Process images in filename-sorted order.
std::vector<std::string> image_files, ground_truth_image_labels;
TF_LITE_ENSURE_STATUS(GetSortedFileNames(
StripTrailingSlashes(ground_truth_images_path), &image_files));
if (!ReadFileLines(ground_truth_labels_path, &ground_truth_image_labels)) {
LOG(ERROR) << "Could not read ground truth labels file";
return EXIT_FAILURE;
}
if (image_files.size() != ground_truth_image_labels.size()) {
LOG(ERROR) << "Number of images and ground truth labels is not same";
return EXIT_FAILURE;
}
std::vector<ImageLabel> image_labels;
image_labels.reserve(image_files.size());
for (int i = 0; i < image_files.size(); i++) {
image_labels.push_back({image_files[i], ground_truth_image_labels[i]});
}
// Filter out blacklisted/unwanted images.
TF_LITE_ENSURE_STATUS(
FilterBlackListedImages(blacklist_file_path, &image_labels));
if (num_images > 0) {
image_labels = GetFirstN(image_labels, num_images);
}
std::vector<std::string> model_labels;
if (!ReadFileLines(model_output_labels_path, &model_labels)) {
LOG(ERROR) << "Could not read model output labels file";
return EXIT_FAILURE;
}
if (!EvaluateModel(model_file_path, image_labels, model_labels, delegate,
output_file_path, num_interpreter_threads,
delegate_providers)) {
LOG(ERROR) << "Could not evaluate model";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
} // namespace evaluation
} // namespace tflite
int main(int argc, char* argv[]) {
return tflite::evaluation::Main(argc, argv);
}
| 41.343915 | 80 | 0.695163 | [
"vector",
"model"
] |
cd703d4b3bb4f7a8e28b01d75e02d24a879ef29d | 7,411 | cpp | C++ | third_party/WebKit/Source/modules/bluetooth/BluetoothError.cpp | xzhan96/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-01-07T18:51:03.000Z | 2021-01-07T18:51:03.000Z | third_party/WebKit/Source/modules/bluetooth/BluetoothError.cpp | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/modules/bluetooth/BluetoothError.cpp | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "modules/bluetooth/BluetoothError.h"
#include "core/dom/DOMException.h"
#include "core/dom/ExceptionCode.h"
#include "third_party/WebKit/public/platform/modules/bluetooth/web_bluetooth.mojom-blink.h"
namespace blink {
DOMException* BluetoothError::take(
ScriptPromiseResolver*,
int32_t
webError /* Corresponds to WebBluetoothResult in web_bluetooth.mojom */) {
switch (static_cast<mojom::blink::WebBluetoothResult>(webError)) {
case mojom::blink::WebBluetoothResult::SUCCESS:
ASSERT_NOT_REACHED();
return DOMException::create(UnknownError);
#define MAP_ERROR(enumeration, name, message) \
case mojom::blink::WebBluetoothResult::enumeration: \
return DOMException::create(name, message)
// InvalidModificationErrors:
MAP_ERROR(GATT_INVALID_ATTRIBUTE_LENGTH, InvalidModificationError,
"GATT Error: invalid attribute length.");
// InvalidStateErrors:
MAP_ERROR(SERVICE_NO_LONGER_EXISTS, InvalidStateError,
"GATT Service no longer exists.");
MAP_ERROR(CHARACTERISTIC_NO_LONGER_EXISTS, InvalidStateError,
"GATT Characteristic no longer exists.");
// NetworkErrors:
MAP_ERROR(CONNECT_ALREADY_IN_PROGRESS, NetworkError,
"Connection already in progress.");
MAP_ERROR(CONNECT_ATTRIBUTE_LENGTH_INVALID, NetworkError,
"Write operation exceeds the maximum length of the attribute.");
MAP_ERROR(CONNECT_AUTH_CANCELED, NetworkError,
"Authentication canceled.");
MAP_ERROR(CONNECT_AUTH_FAILED, NetworkError, "Authentication failed.");
MAP_ERROR(CONNECT_AUTH_REJECTED, NetworkError,
"Authentication rejected.");
MAP_ERROR(CONNECT_AUTH_TIMEOUT, NetworkError, "Authentication timeout.");
MAP_ERROR(CONNECT_CONNECTION_CONGESTED, NetworkError,
"Remote device connection is congested.");
MAP_ERROR(CONNECT_INSUFFICIENT_ENCRYPTION, NetworkError,
"Insufficient encryption for a given operation");
MAP_ERROR(
CONNECT_OFFSET_INVALID, NetworkError,
"Read or write operation was requested with an invalid offset.");
MAP_ERROR(CONNECT_READ_NOT_PERMITTED, NetworkError,
"GATT read operation is not permitted.");
MAP_ERROR(CONNECT_REQUEST_NOT_SUPPORTED, NetworkError,
"The given request is not supported.");
MAP_ERROR(CONNECT_UNKNOWN_ERROR, NetworkError,
"Unknown error when connecting to the device.");
MAP_ERROR(CONNECT_UNKNOWN_FAILURE, NetworkError,
"Connection failed for unknown reason.");
MAP_ERROR(CONNECT_UNSUPPORTED_DEVICE, NetworkError,
"Unsupported device.");
MAP_ERROR(CONNECT_WRITE_NOT_PERMITTED, NetworkError,
"GATT write operation is not permitted.");
MAP_ERROR(DEVICE_NO_LONGER_IN_RANGE, NetworkError,
"Bluetooth Device is no longer in range.");
MAP_ERROR(GATT_NOT_PAIRED, NetworkError, "GATT Error: Not paired.");
MAP_ERROR(GATT_OPERATION_IN_PROGRESS, NetworkError,
"GATT operation already in progress.");
MAP_ERROR(UNTRANSLATED_CONNECT_ERROR_CODE, NetworkError,
"Unknown ConnectErrorCode.");
// NotFoundErrors:
MAP_ERROR(WEB_BLUETOOTH_NOT_SUPPORTED, NotFoundError,
"Web Bluetooth is not supported on this platform. For a list "
"of supported platforms see: https://goo.gl/J6ASzs");
MAP_ERROR(NO_BLUETOOTH_ADAPTER, NotFoundError,
"Bluetooth adapter not available.");
MAP_ERROR(CHOSEN_DEVICE_VANISHED, NotFoundError,
"User selected a device that doesn't exist anymore.");
MAP_ERROR(CHOOSER_CANCELLED, NotFoundError,
"User cancelled the requestDevice() chooser.");
MAP_ERROR(CHOOSER_NOT_SHOWN_API_GLOBALLY_DISABLED, NotFoundError,
"Web Bluetooth API globally disabled.");
MAP_ERROR(CHOOSER_NOT_SHOWN_API_LOCALLY_DISABLED, NotFoundError,
"User or their enterprise policy has disabled Web Bluetooth.");
MAP_ERROR(
CHOOSER_NOT_SHOWN_USER_DENIED_PERMISSION_TO_SCAN, NotFoundError,
"User denied the browser permission to scan for Bluetooth devices.");
MAP_ERROR(SERVICE_NOT_FOUND, NotFoundError,
"No Services with specified UUID found in Device.");
MAP_ERROR(NO_SERVICES_FOUND, NotFoundError,
"No Services found in device.");
MAP_ERROR(CHARACTERISTIC_NOT_FOUND, NotFoundError,
"No Characteristics with specified UUID found in Service.");
MAP_ERROR(NO_CHARACTERISTICS_FOUND, NotFoundError,
"No Characteristics found in service.");
MAP_ERROR(BLUETOOTH_LOW_ENERGY_NOT_AVAILABLE, NotFoundError,
"Bluetooth Low Energy not available.");
// NotSupportedErrors:
MAP_ERROR(GATT_UNKNOWN_ERROR, NotSupportedError, "GATT Error Unknown.");
MAP_ERROR(GATT_UNKNOWN_FAILURE, NotSupportedError,
"GATT operation failed for unknown reason.");
MAP_ERROR(GATT_NOT_PERMITTED, NotSupportedError,
"GATT operation not permitted.");
MAP_ERROR(GATT_NOT_SUPPORTED, NotSupportedError,
"GATT Error: Not supported.");
MAP_ERROR(GATT_UNTRANSLATED_ERROR_CODE, NotSupportedError,
"GATT Error: Unknown GattErrorCode.");
// SecurityErrors:
MAP_ERROR(GATT_NOT_AUTHORIZED, SecurityError,
"GATT operation not authorized.");
MAP_ERROR(BLOCKLISTED_CHARACTERISTIC_UUID, SecurityError,
"getCharacteristic(s) called with blocklisted UUID. "
"https://goo.gl/4NeimX");
MAP_ERROR(BLOCKLISTED_READ, SecurityError,
"readValue() called on blocklisted object marked "
"exclude-reads. https://goo.gl/4NeimX");
MAP_ERROR(BLOCKLISTED_WRITE, SecurityError,
"writeValue() called on blocklisted object marked "
"exclude-writes. https://goo.gl/4NeimX");
MAP_ERROR(NOT_ALLOWED_TO_ACCESS_ANY_SERVICE, SecurityError,
"Origin is not allowed to access any service. Tip: Add the "
"service UUID to 'optionalServices' in requestDevice() "
"options. https://goo.gl/HxfxSQ");
MAP_ERROR(NOT_ALLOWED_TO_ACCESS_SERVICE, SecurityError,
"Origin is not allowed to access the service. Tip: Add the "
"service UUID to 'optionalServices' in requestDevice() "
"options. https://goo.gl/HxfxSQ");
MAP_ERROR(REQUEST_DEVICE_WITH_BLOCKLISTED_UUID, SecurityError,
"requestDevice() called with a filter containing a blocklisted "
"UUID. https://goo.gl/4NeimX");
MAP_ERROR(REQUEST_DEVICE_FROM_CROSS_ORIGIN_IFRAME, SecurityError,
"requestDevice() called from cross-origin iframe.");
MAP_ERROR(REQUEST_DEVICE_WITHOUT_FRAME, SecurityError,
"No window to show the requestDevice() dialog.");
#undef MAP_ERROR
}
ASSERT_NOT_REACHED();
return DOMException::create(UnknownError);
}
} // namespace blink
| 50.074324 | 91 | 0.682229 | [
"object"
] |
cd7126406416831a88870677389fb78cb50c9023 | 5,337 | cpp | C++ | mlir/lib/Dialect/Linalg/Transforms/ComprehensiveBufferizePass.cpp | MikeDvorskiy/llvm | 8213321ebb90110bf4f3d04fa0dc8e131a464a19 | [
"Apache-2.0"
] | null | null | null | mlir/lib/Dialect/Linalg/Transforms/ComprehensiveBufferizePass.cpp | MikeDvorskiy/llvm | 8213321ebb90110bf4f3d04fa0dc8e131a464a19 | [
"Apache-2.0"
] | null | null | null | mlir/lib/Dialect/Linalg/Transforms/ComprehensiveBufferizePass.cpp | MikeDvorskiy/llvm | 8213321ebb90110bf4f3d04fa0dc8e131a464a19 | [
"Apache-2.0"
] | null | null | null | //===- ComprehensiveBufferize.cpp - Single pass bufferization -------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "PassDetail.h"
#include "mlir/Dialect/Arithmetic/Transforms/BufferizableOpInterfaceImpl.h"
#include "mlir/Dialect/Bufferization/IR/BufferizableOpInterface.h"
#include "mlir/Dialect/Bufferization/IR/Bufferization.h"
#include "mlir/Dialect/Bufferization/Transforms/OneShotAnalysis.h"
#include "mlir/Dialect/Linalg/ComprehensiveBufferize/AffineInterfaceImpl.h"
#include "mlir/Dialect/Linalg/ComprehensiveBufferize/LinalgInterfaceImpl.h"
#include "mlir/Dialect/Linalg/ComprehensiveBufferize/ModuleBufferization.h"
#include "mlir/Dialect/Linalg/Passes.h"
#include "mlir/Dialect/SCF/BufferizableOpInterfaceImpl.h"
#include "mlir/Dialect/Tensor/Transforms/BufferizableOpInterfaceImpl.h"
#include "mlir/Dialect/Vector/Transforms/BufferizableOpInterfaceImpl.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Pass/PassManager.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
#include "mlir/Transforms/Passes.h"
using namespace mlir;
using namespace mlir::bufferization;
using namespace mlir::linalg;
using namespace mlir::linalg::comprehensive_bufferize;
namespace {
struct LinalgComprehensiveModuleBufferize
: public LinalgComprehensiveModuleBufferizeBase<
LinalgComprehensiveModuleBufferize> {
LinalgComprehensiveModuleBufferize() = default;
LinalgComprehensiveModuleBufferize(
const LinalgComprehensiveModuleBufferize &p) = default;
explicit LinalgComprehensiveModuleBufferize(
AnalysisBufferizationOptions options)
: options(options) {}
void runOnOperation() override;
void getDependentDialects(DialectRegistry ®istry) const override {
registry
.insert<bufferization::BufferizationDialect, linalg::LinalgDialect,
memref::MemRefDialect, tensor::TensorDialect,
vector::VectorDialect, scf::SCFDialect,
arith::ArithmeticDialect, StandardOpsDialect, AffineDialect>();
affine_ext::registerBufferizableOpInterfaceExternalModels(registry);
arith::registerBufferizableOpInterfaceExternalModels(registry);
linalg_ext::registerBufferizableOpInterfaceExternalModels(registry);
scf::registerBufferizableOpInterfaceExternalModels(registry);
std_ext::registerModuleBufferizationExternalModels(registry);
tensor::registerBufferizableOpInterfaceExternalModels(registry);
vector::registerBufferizableOpInterfaceExternalModels(registry);
}
private:
llvm::Optional<AnalysisBufferizationOptions> options;
};
} // namespace
static void applyEnablingTransformations(ModuleOp moduleOp) {
RewritePatternSet patterns(moduleOp.getContext());
patterns.add<GeneralizePadOpPattern>(moduleOp.getContext());
(void)applyPatternsAndFoldGreedily(moduleOp, std::move(patterns));
}
static FailureOr<Value> allocationFnUsingAlloca(OpBuilder &b, Location loc,
MemRefType type,
ValueRange dynShape,
unsigned int bufferAlignment) {
Value allocated = b.create<memref::AllocaOp>(
loc, type, dynShape, b.getI64IntegerAttr(bufferAlignment));
return allocated;
}
void LinalgComprehensiveModuleBufferize::runOnOperation() {
AnalysisBufferizationOptions opt;
if (!options) {
// Make new bufferization options if none were provided when creating the
// pass.
if (useAlloca) {
opt.allocationFn = allocationFnUsingAlloca;
opt.deallocationFn = [](OpBuilder &b, Location loc, Value v) {
return success();
};
}
opt.allowReturnMemref = allowReturnMemref;
opt.allowUnknownOps = allowUnknownOps;
opt.analysisFuzzerSeed = analysisFuzzerSeed;
opt.createDeallocs = createDeallocs;
opt.fullyDynamicLayoutMaps = fullyDynamicLayoutMaps;
opt.printConflicts = printConflicts;
opt.testAnalysisOnly = testAnalysisOnly;
if (initTensorElimination) {
opt.addPostAnalysisStep(
linalg_ext::insertSliceAnchoredInitTensorEliminationStep);
}
} else {
opt = *options;
}
// Only certain scf.for ops are supported by the analysis.
opt.addPostAnalysisStep(scf::assertScfForAliasingProperties);
ModuleOp moduleOp = getOperation();
applyEnablingTransformations(moduleOp);
if (failed(runModuleBufferize(moduleOp, opt))) {
signalPassFailure();
return;
}
if (opt.testAnalysisOnly)
return;
OpPassManager cleanupPipeline("builtin.module");
cleanupPipeline.addPass(createCanonicalizerPass());
cleanupPipeline.addPass(createCSEPass());
cleanupPipeline.addPass(createLoopInvariantCodeMotionPass());
(void)runPipeline(cleanupPipeline, moduleOp);
}
std::unique_ptr<Pass> mlir::createLinalgComprehensiveModuleBufferizePass() {
return std::make_unique<LinalgComprehensiveModuleBufferize>();
}
std::unique_ptr<Pass> mlir::createLinalgComprehensiveModuleBufferizePass(
const AnalysisBufferizationOptions &options) {
return std::make_unique<LinalgComprehensiveModuleBufferize>(options);
}
| 38.956204 | 80 | 0.746674 | [
"vector"
] |
cd7271cd465ddee611a44c24ab018ccf55dcd357 | 33,798 | cpp | C++ | 10.02_devices/2_src/uda.cpp | jks-prv/QUniBone | 090b400db2d00694873e0f268a18b8ccf662386e | [
"BSD-2-Clause"
] | null | null | null | 10.02_devices/2_src/uda.cpp | jks-prv/QUniBone | 090b400db2d00694873e0f268a18b8ccf662386e | [
"BSD-2-Clause"
] | null | null | null | 10.02_devices/2_src/uda.cpp | jks-prv/QUniBone | 090b400db2d00694873e0f268a18b8ccf662386e | [
"BSD-2-Clause"
] | null | null | null | /*
uda.cpp: Implementation of the MSCP port (qunibus interface).
Copyright Vulcan Inc. 2019 via Living Computers: Museum + Labs, Seattle, WA.
Contributed under the BSD 2-clause license.
This provides logic for the UDA50's SA and IP registers,
the four-step initialization handshake, DMA transfers to and
from the Qbus/Unibus, and the command/response ring protocols.
While the name "UDA" is used here, this is not a strict emulation
of a real UDA50 -- it is a general MSCP implementation and can be
thought of as the equivalent of the third-party MSCP controllers
from Emulex, CMD, etc. that were available.
At this time this class acts as the port for an MSCP controller.
It would be trivial to extend this to TMSCP at a future date.
*/
#include <string.h>
#include <assert.h>
#include "logger.hpp"
#include "gpios.hpp" // debug pin
#include "qunibus.h"
#include "qunibusadapter.hpp"
#include "qunibusdevice.hpp"
#include "storagecontroller.hpp"
#include "mscp_drive.hpp"
#include "uda.hpp"
uda_c::uda_c() :
storagecontroller_c(),
_server(nullptr),
_ringBase(0),
_commandRingLength(0),
_responseRingLength(0),
_commandRingPointer(0),
_responseRingPointer(0),
_interruptVector(0),
_interruptEnable(false),
_purgeInterruptEnable(false),
_step1Value(0),
_initStep(InitializationStep::Uninitialized),
_next_step(false)
{
name.value = "uda";
type_name.value = "UDA50";
log_label = "uda";
// base addr, intr-vector, intr level
set_default_bus_params(0772150, 20, 0154, 5) ;
// The UDA50 controller has two registers.
register_count = 2;
IP_reg = &(this->registers[0]); // @ base addr
strcpy(IP_reg->name, "IP");
IP_reg->active_on_dati = true;
IP_reg->active_on_dato = true;
IP_reg->reset_value = 0;
IP_reg->writable_bits = 0xffff;
SA_reg = &(this->registers[1]); // @ base addr + 2
strcpy(SA_reg->name, "SA");
SA_reg->active_on_dati = false;
SA_reg->active_on_dato = true;
SA_reg->reset_value = 0;
SA_reg->writable_bits = 0xffff;
_server.reset(new mscp_server(this));
//
// Initialize drives. We support up to eight attached drives.
//
drivecount = DRIVE_COUNT;
for (uint32_t i=0; i<drivecount; i++)
{
mscp_drive_c *drive = new mscp_drive_c(this, i);
drive->unitno.value = i;
drive->name.value = name.value + std::to_string(i);
drive->log_label = drive->name.value;
drive->parent = this;
storagedrives.push_back(drive);
}
}
uda_c::~uda_c()
{
for(uint32_t i=0; i<drivecount; i++)
{
delete storagedrives[i];
}
storagedrives.clear();
}
bool uda_c::on_param_changed(parameter_c *param) {
// no own parameter or "enable" logic
if (param == &priority_slot) {
dma_request.set_priority_slot(priority_slot.new_value);
intr_request.set_priority_slot(priority_slot.new_value);
} else if (param == &intr_level) {
intr_request.set_level(intr_level.new_value);
} else if (param == &intr_vector) {
intr_request.set_vector(intr_vector.new_value);
}
return storagecontroller_c::on_param_changed(param) ; // more actions (for enable)
}
//
// Reset():
// Resets the UDA controller state.
// Resets the attached MSCP server, which may take
// significant time.
//
void uda_c::Reset(void)
{
DEBUG("UDA reset");
_server->Reset();
_ringBase = 0;
_commandRingLength = 0;
_responseRingLength = 0;
_commandRingPointer = 0;
_responseRingPointer = 0;
_interruptVector = 0;
intr_vector.value = 0;
_interruptEnable = false;
_purgeInterruptEnable = false;
}
//
// GetDriveCount():
// Returns the number of drives that can be attached to this controller.
//
uint32_t uda_c::GetDriveCount(void)
{
return drivecount;
}
//
// GetDrive():
// Returns a pointer to an mscp_drive_c object for the specified drive number.
// This pointer is owned by the UDA class.
//
mscp_drive_c* uda_c::GetDrive(
uint32_t driveNumber)
{
assert(driveNumber < drivecount);
return dynamic_cast<mscp_drive_c*>(storagedrives[driveNumber]);
}
//
// StateTransition():
// Transitions the UDA initialization state machine to the specified step,
// atomically.
//
void uda_c::StateTransition(
InitializationStep nextStep)
{
pthread_mutex_lock(&on_after_register_access_mutex);
_initStep = nextStep;
_next_step = true;
pthread_cond_signal(&on_after_register_access_cond);
pthread_mutex_unlock(&on_after_register_access_mutex);
}
//
// worker():
// Implements the initialization state machine.
//
void uda_c::worker(unsigned instance)
{
UNUSED(instance) ; // only one
worker_init_realtime_priority(rt_device);
timeout_c timeout;
while (!workers_terminate)
{
//
// Wait to be awoken.
//
pthread_mutex_lock(&on_after_register_access_mutex);
while (!_next_step)
{
pthread_cond_wait(
&on_after_register_access_cond,
&on_after_register_access_mutex);
}
_next_step = false;
pthread_mutex_unlock(&on_after_register_access_mutex);
switch (_initStep)
{
case InitializationStep::Uninitialized:
DEBUG("Transition to Init state Uninitialized.");
// SA should already be zero but we'll be extra sure here.
update_SA(0x0);
// Reset the controller: This may take some time as we must
// wait for the MSCP server to wrap up its current workitem.
Reset();
StateTransition(InitializationStep::Step1);
break;
case InitializationStep::Step1:
timeout.wait_us(500);
DEBUG("Transition to Init state S1.");
//
// S1 is set, all other bits zero. This indicates that we
// support a host-settable interrupt vector, that we do not
// implement enhanced diagnostics, and that no errors have
// occurred.
//
update_SA(0x0800);
break;
case InitializationStep::Step2:
timeout.wait_us(500);
DEBUG("Transition to Init state S2.");
// Update the SA read value for step 2:
// S2 is set, qunibus port type (0), SA bits 15-8 written
// by the host in step 1.
Interrupt(0x1000 | ((_step1Value >> 8) & 0xff));
break;
case InitializationStep::Step3:
timeout.wait_us(500);
DEBUG("Transition to Init state S3.");
// Update the SA read value for step 3:
// S3 set, plus SA bits 7-0 written by the host in step 1.
Interrupt(0x2000 | (_step1Value & 0xff));
break;
case InitializationStep::Step4:
timeout.wait_us(100);
// Clear communications area, set SA
DEBUG("Clearing comm area at 0x%x. Purge header: %d", _ringBase, _purgeInterruptEnable);
DEBUG("resp 0x%x comm 0x%x", _responseRingLength, _commandRingLength);
{
int headerSize = _purgeInterruptEnable ? 8 : 4;
for(uint32_t i = 0;
i < (_responseRingLength + _commandRingLength) * sizeof(Descriptor) + headerSize;
i += 2)
{
DMAWriteWord(_ringBase + i - headerSize, 0x0);
}
}
//
// Set the ownership bit on all descriptors in the response ring
// to indicate that the port owns them.
//
Descriptor blankDescriptor;
blankDescriptor.Word0.Word0 = 0;
blankDescriptor.Word1.Word1 = 0;
blankDescriptor.Word1.Fields.Ownership = 1;
for(uint32_t i = 0; i < _responseRingLength; i++)
{
DMAWrite(
GetResponseDescriptorAddress(i),
sizeof(Descriptor),
reinterpret_cast<uint8_t*>(&blankDescriptor));
}
DEBUG("Transition to Init state S4, comm area initialized.");
// Update the SA read value for step 4:
// Bits 7-0 indicating our control microcode version.
Interrupt(UDA50_ID); // UDA50 ID, makes RSTS happy
break;
case InitializationStep::Complete:
DEBUG("Initialization complete.");
break;
}
}
}
//
// on_after_register_access():
// Handles register accesses for the IP and SA registers.
//
void
uda_c::on_after_register_access(
qunibusdevice_register_t *device_reg,
uint8_t unibus_control
)
{
switch (device_reg->index)
{
case 0: // IP - read / write
if (QUNIBUS_CYCLE_DATO == unibus_control)
{
// "When written with any value, it causes a hard initialization
// of the port and the device controller."
DEBUG("Reset due to IP read");
update_SA(0x0);
StateTransition(InitializationStep::Uninitialized);
}
else
{
// "When read while the port is operating, it causes the controller
// to initiate polling..."
if (_initStep == InitializationStep::Complete)
{
DEBUG("Request to start polling.");
_server->InitPolling();
}
}
break;
case 1: // SA - write only
uint16_t value = SA_reg->active_dato_flipflops;
switch (_initStep)
{
case InitializationStep::Uninitialized:
// Should not occur, we treat it like step1 here.
DEBUG("Write to SA in Uninitialized state.");
case InitializationStep::Step1:
// Host writes the following:
// 15 13 11 10 8 7 6 0
// +-+-+-----+-----+-+-------------+
// |1|W|c rng|r rng|I| int vector |
// | |R| lng | lng |E|(address / 4)|
// +-+-+-----+-----+-+-------------+
// WR = 1 tells the port to enter diagnostic wrap
// mode (which we ignore).
//
// c rng lng is the number of slots (32 bits each)
// in the command ring, expressed as a power of two.
//
// r rng lng is as above, but for the response ring.
//
// IE=1 means the host is requesting an interrupt
// at the end of the completion of init steps 1-3.
//
// int vector determines if interrupts will be generated
// by the port. If this field is non-zero, interupts will
// be generated during normal operation and, if IE=1,
// during initialization.
_step1Value = value;
_interruptVector = ((value & 0x7f) << 2);
intr_request.set_vector(_interruptVector);
_interruptEnable = !!(value & 0x80);
_responseRingLength = (1 << ((value & 0x700) >> 8));
_commandRingLength = (1 << ((value & 0x3800) >> 11));
DEBUG("Step1: 0x%x", value);
DEBUG("resp ring 0x%x", _responseRingLength);
DEBUG("cmd ring 0x%x", _commandRingLength);
DEBUG("vector 0x%x", _interruptVector);
DEBUG("ie %d", _interruptEnable);
// Move to step 2.
StateTransition(InitializationStep::Step2);
break;
case InitializationStep::Step2:
// Host writes the following:
// 15 1 0
// +-----------------------------+-+
// | ringbase low |P|
// | (address) |I|
// +-----------------------------+-+
// ringbase low is the low-order portion of word
// [ringbase+0] of the communications area. This is a
// 16-bit byte address whose low-order bit is zero implicitly.
//
_ringBase = value & 0xfffe;
_purgeInterruptEnable = !!(value & 0x1);
DEBUG("Step2: rb 0x%x pi %d", _ringBase, _purgeInterruptEnable);
// Move to step 3 and interrupt as necessary.
StateTransition(InitializationStep::Step3);
break;
case InitializationStep::Step3:
// Host writes the following:
// 15 0
// +-+-----------------------------+
// |P| ringbase hi |
// |P| (address) |
// +-+-----------------------------+
// PP = 1 means the host is requesting execution of
// purge and poll tests, which we ignore because we can.
//
// ringbase hi is the high-order portion of the address
// [ringbase+0].
_ringBase |= ((value & 0x7fff) << 16);
DEBUG("Step3: ringbase 0x%x", _ringBase);
// Move to step 4 and interrupt as necessary.
StateTransition(InitializationStep::Step4);
break;
case InitializationStep::Step4:
// Host writes the following:
// 15 8 7 1 0
// +---------------+-----------+-+-+
// | reserved | burst |L|G|
// | | |F|O|
// +---------------+-----------+-+-+
// Burst is one less than the max. number of longwords
// the host is willing to allow per DMA transfer.
// If zero, the port uses its default burst count.
//
// LF=1 means that the host wants a "last fail" response
// packet when initialization is complete.
//
// GO=1 means that the controller should enter its functional
// microcode as soon as initialization completes.
//
// Note that if GO=0 when initialization completes, the port
// will continue to read SA until the host forces SA bit 0 to
// make the transition 0->1.
//
// There is no explicit interrupt at the end of Step 4.
//
// TODO: For now we ignore burst settings.
// We also ignore Last Fail report requests since we aren't
// supporting onboard diagnostics and there's nothing to
// report.
//
DEBUG("Step4: 0x%x", value);
if (value & 0x1)
{
//
// GO is set, move to the Complete state. The worker will
// start the controller running.
//
StateTransition(InitializationStep::Complete);
// The VMS bootstrap expects SA to be zero IMMEDIATELY
// after completion.
update_SA(0x0);
}
else
{
// GO unset, wait until it is.
}
break;
case InitializationStep::Complete:
// "When zeroed by the host during both initialization and normal
// operation, it signals the port that the host has successfully
// completed a bus adapter purge in response to a port-initiated
// purge request.
// We don't deal with bus adapter purges, yet.
break;
}
break;
}
}
//
// update_SA():
// Updates the SA register value exposed by the Unibone.
//
void
uda_c::update_SA(uint16_t value)
{
set_register_dati_value(
SA_reg,
value,
"update_SA");
}
//
// GetNextCommand():
// Attempts to pull the next command from the command ring, if any
// are available.
// If successful, returns a pointer to a Message struct; this pointer
// is owned by the caller.
// On failure, nullptr is returned. This indicates that the ring is
// empty or that an attempt to access non-existent memory occurred.
// TODO: Need to handle NXM cases properly.
//
Message*
uda_c::GetNextCommand(void)
{
timeout_c timer;
// Grab the next descriptor being pointed to
uint32_t descriptorAddress =
GetCommandDescriptorAddress(_commandRingPointer);
DEBUG("Next descriptor (ring ptr 0x%x) address is o%o",
_commandRingPointer,
descriptorAddress);
std::unique_ptr<Descriptor> cmdDescriptor(
reinterpret_cast<Descriptor*>(
DMARead(
descriptorAddress,
sizeof(Descriptor),
sizeof(Descriptor))));
// TODO: if NULL is returned after retry assume a bus error and handle it appropriately.
assert(cmdDescriptor != nullptr);
// Check owner bit: if set, ownership has been passed to us, in which case
// we can attempt to pull the actual message from memory.
if (cmdDescriptor->Word1.Fields.Ownership)
{
bool doInterrupt = false;
uint32_t messageAddress =
cmdDescriptor->Word0.EnvelopeLow |
(cmdDescriptor->Word1.Fields.EnvelopeHigh << 16);
DEBUG("Next message address is o%o, flag %d",
messageAddress, cmdDescriptor->Word1.Fields.Flag);
//
// Grab the message length; this is at messageAddress - 4
//
bool success = false;
uint16_t messageLength =
DMAReadWord(
messageAddress - 4,
success);
assert(messageLength > 0 && messageLength < MAX_MESSAGE_LENGTH);
std::unique_ptr<Message> cmdMessage(
reinterpret_cast<Message*>(
DMARead(
messageAddress - 4,
messageLength + 4,
sizeof(Message))));
//
// Handle Ring Transitions (from full to not-full) and associated
// interrupts.
// If the previous entry in the ring is owned by the Port then that indicates
// that the ring was previously full (i.e. the descriptor we're now returning
// is the first free entry.)
//
if (cmdDescriptor->Word1.Fields.Flag)
{
//
// Flag is set, host is requesting a transition interrupt.
// Check the previous entry in the ring.
//
if (_commandRingLength == 1)
{
// Degenerate case: If the ring is of size 1 we always interrupt.
doInterrupt = true;
}
else
{
uint32_t previousDescriptorAddress =
GetCommandDescriptorAddress(
(_commandRingPointer - 1) % _commandRingLength);
std::unique_ptr<Descriptor> previousDescriptor(
reinterpret_cast<Descriptor*>(
DMARead(
previousDescriptorAddress,
sizeof(Descriptor),
sizeof(Descriptor))));
if (previousDescriptor->Word1.Fields.Ownership)
{
// We own the previous descriptor, so the ring was previously
// full.
doInterrupt = true;
}
}
}
//
// Message retrieved; reset the Owner bit of the command descriptor,
// set the Flag bit (to indicate that we've processed it)
// and return a pointer to the message.
//
cmdDescriptor->Word1.Fields.Ownership = 0;
cmdDescriptor->Word1.Fields.Flag = 1;
DMAWrite(
descriptorAddress,
sizeof(Descriptor),
reinterpret_cast<uint8_t*>(cmdDescriptor.get()));
//
// Move to the next descriptor in the ring for next time.
_commandRingPointer = (_commandRingPointer + 1) % _commandRingLength;
// Post an interrupt as necessary.
if (doInterrupt)
{
//
// Set ring base - 4 to non-zero to indicate a transition.
//
DMAWriteWord(_ringBase - 4, 0x1);
Interrupt();
}
return cmdMessage.release();
}
DEBUG("No descriptor found. 0x%x 0x%x", cmdDescriptor->Word0.Word0, cmdDescriptor->Word1.Word1);
// No descriptor available.
return nullptr;
}
//
// PostResponse():
// Posts the provided Message to the response ring.
// Returns true on success, false otherwise.
// TODO: Need to handle NXM, as above.
//
bool
uda_c::PostResponse(
Message* response
)
{
bool res = false;
// Grab the next descriptor.
uint32_t descriptorAddress = GetResponseDescriptorAddress(_responseRingPointer);
std::unique_ptr<Descriptor> cmdDescriptor(
reinterpret_cast<Descriptor*>(
DMARead(
descriptorAddress,
sizeof(Descriptor),
sizeof(Descriptor))));
// TODO: if NULL is returned assume a bus error and handle it appropriately.
//
// Check owner bit: if set, ownership has been passed to us, in which case
// we can use this descriptor and fill in the response buffer it points to.
// If not, we return false to indicate to the caller the need to try again later.
//
if (cmdDescriptor->Word1.Fields.Ownership)
{
bool doInterrupt = false;
uint32_t messageAddress =
cmdDescriptor->Word0.EnvelopeLow |
(cmdDescriptor->Word1.Fields.EnvelopeHigh << 16);
//
// Read the buffer length the host has allocated for this response.
//
// TODO:
// If it is shorter than the buffer we're writing then we will need to
// split the response into multiple responses. I have never seen this happen,
// however and I'm curious if the documentation (AA-L621A-TK) is simply incorrect:
// "Note that if a controller's responses are less than or equal to 60 bytes,
// then the controller need not check the size of the response slot."
// All of the MSCP response messages are shorter than 60 bytes, so this is always
// the case. I'll also note that the spec states "The minimum acceptable size
// is 60 bytes of message text" for the response buffer set up by the host and this
// is *definitely* not followed by host drivers.
//
// The doc is also not exactly clear what a fragmented set of responses looks like...
//
// Message length is at messageAddress - 4 -- this is the size of the command
// not including the two header words.
//
bool success = false;
uint16_t messageLength =
DMAReadWord(
messageAddress - 4,
success);
DEBUG("response address o%o length o%o", messageAddress, response->MessageLength);
assert(reinterpret_cast<uint16_t*>(response)[0] > 0);
if (messageLength == 0)
{
// A lot of bootstraps appear to set up response buffers of length 0.
// We just log the behavior.
DEBUG("Host response buffer size is zero.");
}
else if (messageLength < response->MessageLength)
{
//
// If this happens it's likely fatal since we're not fragmenting responses (see the big comment
// block above). So eat flaming death.
// Note: the VMS bootstrap does this, so we'll just log the issue.
//
DEBUG("Response buffer 0x%x > host buffer length 0x%x", response->MessageLength, messageLength);
}
//
// This will fit; simply copy the response message over the top
// of the buffer allocated on the host -- this updates the header fields
// as necessary and provides the actual response data to the host.
//
DMAWrite(
messageAddress - 4,
response->MessageLength + 4,
reinterpret_cast<uint8_t*>(response));
//
// Check if a transition from empty to non-empty occurred, interrupt if requested.
//
// If the previous entry in the ring is owned by the Port then that indicates
// that the ring was previously empty (i.e. the descriptor we're now returning
// is the first entry returned to the ring by the Port.)
//
if (cmdDescriptor->Word1.Fields.Flag)
{
//
// Flag is set, host is requesting a transition interrupt.
// Check the previous entry in the ring.
//
if (_responseRingLength == 1)
{
// Degenerate case: If the ring is of size 1 we always interrupt.
doInterrupt = true;
}
else
{
uint32_t previousDescriptorAddress =
GetResponseDescriptorAddress(
(_responseRingPointer - 1) % _responseRingLength);
std::unique_ptr<Descriptor> previousDescriptor(
reinterpret_cast<Descriptor*>(
DMARead(
previousDescriptorAddress,
sizeof(Descriptor),
sizeof(Descriptor))));
if (previousDescriptor->Word1.Fields.Ownership)
{
// We own the previous descriptor, so the ring was previously
// full.
doInterrupt = true;
}
}
}
//
// Message posted; reset the Owner bit of the response descriptor,
// and set the Flag bit (to indicate that we've processed it).
//
cmdDescriptor->Word1.Fields.Ownership = 0;
cmdDescriptor->Word1.Fields.Flag = 1;
DMAWrite(
descriptorAddress,
sizeof(Descriptor),
reinterpret_cast<uint8_t*>(cmdDescriptor.get()));
// Post an interrupt as necessary.
if (doInterrupt)
{
DEBUG("Response ring no longer empty, interrupting.");
//
// Set ring base - 2 to non-zero to indicate a transition.
//
DMAWriteWord(_ringBase - 2, 0x1);
Interrupt();
}
res = true;
// Move to the next descriptor in the ring for next time.
_responseRingPointer = (_responseRingPointer + 1) % _responseRingLength;
}
return res;
}
//
// GetControllerIdentifier():
// Returns the ID used by SET CONTROLLER CHARACTERISTICS.
// This should be unique per controller.
//
uint32_t
uda_c::GetControllerIdentifier()
{
// TODO: make this not hardcoded
// ID 0x12345678
return 0x12345678;
}
//
// GetControllerClassModel():
// Returns the Class and Model information used by SET CONTROLLER CHARACTERISTICS.
//
uint16_t
uda_c::GetControllerClassModel()
{
return 0x0102; // Class 1 (mass storage), model 2 (UDA50)
}
//
// Interrupt():
// Invokes a Qbus/Unibus interrupt if interrupts are enabled and the interrupt
// vector is non-zero. Updates SA to the specified value atomically.
//
void
uda_c::Interrupt(uint16_t sa_value)
{
if ((_interruptEnable || _initStep == InitializationStep::Complete) && _interruptVector != 0)
{
qunibusadapter->INTR(intr_request, SA_reg, sa_value);
}
else
{
update_SA(sa_value);
}
}
//
// Interrupt():
// Invokes a Qbus/Unibus interrupt if interrupts are enabled and the interrupt
// vector is non-zero.
//
void
uda_c::Interrupt(void)
{
if ((_interruptEnable || _initStep == InitializationStep::Complete) && _interruptVector != 0)
{
qunibusadapter->INTR(intr_request, NULL, 0);
}
}
//
// on_power_changed():
// Resets the controller and all attached drives.
//
// after QBUS/UNIBUS install, device is reset by DCLO/DCOK cycle
void
uda_c::on_power_changed(signal_edge_enum aclo_edge, signal_edge_enum dclo_edge)
{
storagecontroller_c::on_power_changed(aclo_edge, dclo_edge);
if (dclo_edge == SIGNAL_EDGE_RAISING)
{
DEBUG("Reset due to power change");
StateTransition(InitializationStep::Uninitialized);
}
}
//
// on_init_changed():
// Resets the controller and all attached drives.
//
void
uda_c::on_init_changed(void)
{
if (init_asserted)
{
DEBUG("Reset due to INIT");
StateTransition(InitializationStep::Uninitialized);
}
storagecontroller_c::on_init_changed();
}
//
// on_drive_status_changed():
// A no-op. The controller doesn't require any drive notifications.
//
void
uda_c::on_drive_status_changed(storagedrive_c *drive)
{
UNUSED(drive);
}
//
// GetCommandDescriptorAddress():
// Returns the address of the given command descriptor in the command ring.
//
uint32_t
uda_c::GetCommandDescriptorAddress(
size_t index
)
{
return _ringBase + _responseRingLength * sizeof(Descriptor) +
index * sizeof(Descriptor);
}
//
// GetResponseDescriptorAddress():
// Returns the address of the given response descriptor in the response ring.
//
uint32_t
uda_c::GetResponseDescriptorAddress(
size_t index
)
{
return _ringBase + index * sizeof(Descriptor);
}
//
// DMAWriteWord():
// Writes a single word to Qbus/Unibus memory. Returns true
// on success; if false is returned this is due to an NXM condition.
//
bool
uda_c::DMAWriteWord(
uint32_t address,
uint16_t word)
{
return DMAWrite(
address,
sizeof(uint16_t),
reinterpret_cast<uint8_t*>(&word));
}
//
// DMAReadWord():
// Read a single word from Qbus/Unibus memory. Returns the word read on success.
// the success field indicates the success or failure of the read.
//
uint16_t
uda_c::DMAReadWord(
uint32_t address,
bool& success)
{
uint8_t* buffer = DMARead(
address,
sizeof(uint16_t),
sizeof(uint16_t));
if (buffer)
{
success = true;
uint16_t retval = *reinterpret_cast<uint16_t *>(buffer);
delete[] buffer;
return retval;
}
else
{
success = false;
return 0;
}
}
//
// DMAWrite():
// Write data from the provided buffer to Qbus/Unibus memory. Returns true
// on success; if false is returned this is due to an NXM condition.
// The address specified in 'address' must be word-aligned and the
// length must be even.
//
bool
uda_c::DMAWrite(
uint32_t address,
size_t lengthInBytes,
uint8_t* buffer)
{
assert ((lengthInBytes % 2) == 0);
// if (address >= 0x40000)
// logger->dump(logger->default_filepath) ;
assert (address < 2* qunibus->addr_space_word_count); // exceeds address space? test for IOpage too?
// assert (address < 0x40000);
qunibusadapter->DMA(dma_request, true,
QUNIBUS_CYCLE_DATO,
address,
reinterpret_cast<uint16_t*>(buffer),
lengthInBytes >> 1);
return dma_request.success ;
}
//
// DMARead():
// Read data from Qbus/Unibus memory into the returned buffer.
// Buffer returned is nullptr if memory could not be read.
// Caller is responsible for freeing the buffer when done.
// The address specified in 'address' must be word-aligned
// and the length must be even.
//
uint8_t*
uda_c::DMARead(
uint32_t address,
size_t lengthInBytes,
size_t bufferSize)
{
assert (bufferSize >= lengthInBytes);
assert((lengthInBytes % 2) == 0);
assert (address < 2* qunibus->addr_space_word_count); // exceeds address space? test for IOpage too?
// assert (address < 0x40000);
uint16_t* buffer = new uint16_t[bufferSize >> 1];
assert(buffer);
memset(reinterpret_cast<uint8_t*>(buffer), 0xc3, bufferSize);
qunibusadapter->DMA(dma_request, true,
QUNIBUS_CYCLE_DATI,
address,
buffer,
lengthInBytes >> 1);
if (dma_request.success)
{
return reinterpret_cast<uint8_t*>(buffer);
}
else
{
return nullptr;
}
}
| 33.005859 | 108 | 0.553287 | [
"object",
"vector",
"model"
] |
cd73302619a9061162fa3559d39677c452c24197 | 12,115 | hpp | C++ | src/benchmarks/clsparse-bench/functions/clfunc_xSpMSpM.hpp | xfong/clSPARSE | fa026dcb99a374678624530dff041322d67e0630 | [
"Apache-2.0"
] | 164 | 2015-08-03T21:53:40.000Z | 2022-03-31T14:58:11.000Z | src/benchmarks/clsparse-bench/functions/clfunc_xSpMSpM.hpp | xfong/clSPARSE | fa026dcb99a374678624530dff041322d67e0630 | [
"Apache-2.0"
] | 94 | 2015-08-04T15:49:30.000Z | 2021-02-01T14:28:35.000Z | src/benchmarks/clsparse-bench/functions/clfunc_xSpMSpM.hpp | xfong/clSPARSE | fa026dcb99a374678624530dff041322d67e0630 | [
"Apache-2.0"
] | 76 | 2015-08-04T00:00:44.000Z | 2021-09-17T17:53:06.000Z | /* ************************************************************************
* Copyright 2015 Advanced Micro Devices, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ************************************************************************ */
#pragma once
#ifndef CLSPARSE_BENCHMARK_SpM_SpM_HXX
#define CLSPARSE_BENCHMARK_SpM_SpM_HXX
#include "clSPARSE.h"
#include "clfunc_common.hpp"
// Dummy Code to be deleted later
clsparseStatus clsparseDcsrSpGemm(const clsparseCsrMatrix* sparseMatA, const clsparseCsrMatrix* sparseMatB, clsparseCsrMatrix* sparseMatC, const clsparseControl control)
{
std::cout << "sparseMat A dimensions = \n";
std::cout << " rows = " << sparseMatA->num_rows << std::endl;
std::cout << " cols = " << sparseMatA->num_cols << std::endl;
std::cout << "nnz = " << sparseMatA->num_nonzeros << std::endl;
std::cout << "sparseMat B dimensions = \n";
std::cout << " rows = " << sparseMatB->num_rows << std::endl;
std::cout << " cols = " << sparseMatB->num_cols << std::endl;
std::cout << "nnz = " << sparseMatB->num_nonzeros << std::endl;
return clsparseSuccess;
}//
// Dummy code ends
template <typename T>
class xSpMSpM : public clsparseFunc {
public:
xSpMSpM(PFCLSPARSETIMER sparseGetTimer, size_t profileCount, cl_device_type devType, cl_bool keep_explicit_zeroes = true) : clsparseFunc(devType, CL_QUEUE_PROFILING_ENABLE), gpuTimer(nullptr), cpuTimer(nullptr)
{
// Create and initialize our timer class, if the external timer shared library loaded
if (sparseGetTimer)
{
gpuTimer = sparseGetTimer(CLSPARSE_GPU);
gpuTimer->Reserve(1, profileCount);
gpuTimer->setNormalize(true);
cpuTimer = sparseGetTimer(CLSPARSE_CPU);
cpuTimer->Reserve(1, profileCount);
cpuTimer->setNormalize(true);
gpuTimerID = gpuTimer->getUniqueID("GPU xSpMSpM", 0);
cpuTimerID = cpuTimer->getUniqueID("CPU xSpMSpM", 0);
}
clsparseEnableAsync(control, false);
explicit_zeroes = keep_explicit_zeroes;
}
~xSpMSpM() {}
void call_func()
{
if (gpuTimer && cpuTimer)
{
gpuTimer->Start(gpuTimerID);
cpuTimer->Start(cpuTimerID);
xSpMSpM_Function(false);
cpuTimer->Stop(cpuTimerID);
gpuTimer->Stop(gpuTimerID);
}
else
{
xSpMSpM_Function(false);
}
}//
double gflops()
{
return 0.0;
}
std::string gflops_formula()
{
return "N/A";
}
double bandwidth() // Need to modify this later **********
{
// Assuming that accesses to the vector always hit in the cache after the first access
// There are NNZ integers in the cols[ ] array
// You access each integer value in row_delimiters[ ] once.
// There are NNZ float_types in the vals[ ] array
// You read num_cols floats from the vector, afterwards they cache perfectly.
// Finally, you write num_rows floats out to DRAM at the end of the kernel.
return (sizeof(clsparseIdx_t)*(csrMtx.num_nonzeros + csrMtx.num_rows) + sizeof(T) * (csrMtx.num_nonzeros + csrMtx.num_cols + csrMtx.num_rows)) / time_in_ns();
} // end of function
std::string bandwidth_formula()
{
return "GiB/s";
}// end of function
void setup_buffer(double pAlpha, double pBeta, const std::string& path)
{
sparseFile = path;
alpha = static_cast<T>(pAlpha);
beta = static_cast<T>(pBeta);
// Read sparse data from file and construct a COO matrix from it
clsparseIdx_t nnz, row, col;
clsparseStatus fileError = clsparseHeaderfromFile(&nnz, &row, &col, sparseFile.c_str());
if (fileError != clsparseSuccess)
throw clsparse::io_exception("Could not read matrix market header from disk");
// Now initialize a CSR matrix from the COO matrix
clsparseInitCsrMatrix(&csrMtx);
csrMtx.num_nonzeros = nnz;
csrMtx.num_rows = row;
csrMtx.num_cols = col;
//clsparseCsrMetaSize(&csrMtx, control);
cl_int status;
csrMtx.values = ::clCreateBuffer(ctx, CL_MEM_READ_ONLY,
csrMtx.num_nonzeros * sizeof(T), NULL, &status);
CLSPARSE_V(status, "::clCreateBuffer csrMtx.values");
csrMtx.col_indices = ::clCreateBuffer(ctx, CL_MEM_READ_ONLY,
csrMtx.num_nonzeros * sizeof(clsparseIdx_t), NULL, &status);
CLSPARSE_V(status, "::clCreateBuffer csrMtx.col_indices");
csrMtx.row_pointer = ::clCreateBuffer(ctx, CL_MEM_READ_ONLY,
(csrMtx.num_rows + 1) * sizeof(clsparseIdx_t), NULL, &status);
CLSPARSE_V(status, "::clCreateBuffer csrMtx.row_pointer");
#if 0
csrMtx.rowBlocks = ::clCreateBuffer(ctx, CL_MEM_READ_ONLY,
csrMtx.rowBlockSize * sizeof(cl_ulong), NULL, &status);
CLSPARSE_V(status, "::clCreateBuffer csrMtx.rowBlocks");
#endif
if (typeid(T) == typeid(float))
fileError = clsparseSCsrMatrixfromFile( &csrMtx, sparseFile.c_str(), control, explicit_zeroes );
else if (typeid(T) == typeid(double))
fileError = clsparseDCsrMatrixfromFile( &csrMtx, sparseFile.c_str(), control, explicit_zeroes );
else
fileError = clsparseInvalidType;
if (fileError != clsparseSuccess)
throw clsparse::io_exception("Could not read matrix market data from disk");
// Initilize the output CSR Matrix
clsparseInitCsrMatrix(&csrMtxC);
// Initialize the scalar alpha & beta parameters
clsparseInitScalar(&a);
a.value = ::clCreateBuffer(ctx, CL_MEM_READ_ONLY,
1 * sizeof(T), NULL, &status);
CLSPARSE_V(status, "::clCreateBuffer a.value");
clsparseInitScalar(&b);
b.value = ::clCreateBuffer(ctx, CL_MEM_READ_ONLY,
1 * sizeof(T), NULL, &status);
CLSPARSE_V(status, "::clCreateBuffer b.value");
//std::cout << "Flops = " << xSpMSpM_Getflopcount() << std::endl;
flopCnt = xSpMSpM_Getflopcount();
}// end of function
void initialize_cpu_buffer()
{
}
void initialize_gpu_buffer()
{
CLSPARSE_V(::clEnqueueFillBuffer(queue, a.value, &alpha, sizeof(T), 0,
sizeof(T) * 1, 0, NULL, NULL), "::clEnqueueFillBuffer alpha.value");
CLSPARSE_V(::clEnqueueFillBuffer(queue, b.value, &beta, sizeof(T), 0,
sizeof(T) * 1, 0, NULL, NULL), "::clEnqueueFillBuffer beta.value");
}// end of function
void reset_gpu_write_buffer()
{
// Every call to clsparseScsrSpGemm() allocates memory to csrMtxC, therefore freeing the memory
CLSPARSE_V(::clReleaseMemObject(csrMtxC.values), "clReleaseMemObject csrMtxC.values");
CLSPARSE_V(::clReleaseMemObject(csrMtxC.col_indices), "clReleaseMemObject csrMtxC.col_indices");
CLSPARSE_V(::clReleaseMemObject(csrMtxC.row_pointer), "clReleaseMemObject csrMtxC.row_pointer");
// Initilize the output CSR Matrix
clsparseInitCsrMatrix(&csrMtxC);
}// end of function
void read_gpu_buffer()
{
}
void cleanup()
{
if (gpuTimer && cpuTimer)
{
std::cout << "clSPARSE matrix: " << sparseFile << std::endl;
cpuTimer->pruneOutliers(3.0);
cpuTimer->Print(flopCnt, "GFlop/s");
cpuTimer->Reset();
gpuTimer->pruneOutliers(3.0);
gpuTimer->Print(flopCnt, "GFlop/s");
gpuTimer->Reset();
}
//this is necessary since we are running a iteration of tests and calculate the average time. (in client.cpp)
//need to do this before we eventually hit the destructor
CLSPARSE_V(::clReleaseMemObject(csrMtx.values), "clReleaseMemObject csrMtx.values");
CLSPARSE_V(::clReleaseMemObject(csrMtx.col_indices), "clReleaseMemObject csrMtx.col_indices");
CLSPARSE_V(::clReleaseMemObject(csrMtx.row_pointer), "clReleaseMemObject csrMtx.row_pointer");
//CLSPARSE_V(::clReleaseMemObject(csrMtx.rowBlocks), "clReleaseMemObject csrMtx.rowBlocks");
if (csrMtxC.values != nullptr)
CLSPARSE_V(::clReleaseMemObject(csrMtxC.values), "clReleaseMemObject csrMtxC.values");
if (csrMtxC.col_indices != nullptr)
CLSPARSE_V(::clReleaseMemObject(csrMtxC.col_indices), "clReleaseMemObject csrMtxC.col_indices");
if (csrMtxC.row_pointer != nullptr)
CLSPARSE_V(::clReleaseMemObject(csrMtxC.row_pointer), "clReleaseMemObject csrMtxC.row_pointer");
//CLSPARSE_V(::clReleaseMemObject(csrMtxC.rowBlocks), "clReleaseMemObject csrMtxC.rowBlocks");
CLSPARSE_V(::clReleaseMemObject(a.value), "clReleaseMemObject alpha.value");
CLSPARSE_V(::clReleaseMemObject(b.value), "clReleaseMemObject beta.value");
}
private:
void xSpMSpM_Function(bool flush);
clsparseIdx_t xSpMSpM_Getflopcount(void)
{
// C = A * B
// But here C = A* A, the A & B matrices are same
clsparseIdx_t nnzA = csrMtx.num_nonzeros;
clsparseIdx_t Browptrlen = csrMtx.num_rows + 1; // Number of row offsets
std::vector<clsparseIdx_t> colIdxA(nnzA, 0);
std::vector<clsparseIdx_t> rowptrB(Browptrlen, 0);
cl_int run_status = 0;
run_status = clEnqueueReadBuffer(queue,
csrMtx.col_indices,
CL_TRUE, 0,
nnzA*sizeof(clsparseIdx_t),
colIdxA.data(), 0, nullptr, nullptr);
CLSPARSE_V(run_status, "Reading col_indices from GPU failed");
// copy rowptrs
run_status = clEnqueueReadBuffer(queue,
csrMtx.row_pointer,
CL_TRUE, 0,
Browptrlen*sizeof(clsparseIdx_t),
rowptrB.data(), 0, nullptr, nullptr);
CLSPARSE_V(run_status, "Reading row offsets from GPU failed");
clsparseIdx_t flop = 0;
for (clsparseIdx_t i = 0; i < nnzA; i++)
{
clsparseIdx_t colIdx = colIdxA[i]; // Get colIdx of A
flop += rowptrB[colIdx + 1] - rowptrB[colIdx]; // nnz in 'colIdx'th row of B
}
flop = 2 * flop; // Two operations - Multiply & Add
return flop;
}// end of function
// Timers we want to keep
clsparseTimer* gpuTimer;
clsparseTimer* cpuTimer;
size_t gpuTimerID;
size_t cpuTimerID;
std::string sparseFile;
//device values
clsparseCsrMatrix csrMtx; // input matrix
clsparseCsrMatrix csrMtxC; // Output CSR MAtrix
clsparseScalar a;
clsparseScalar b;
// host values
T alpha;
T beta;
clsparseIdx_t flopCnt; // Indicates total number of floating point operations
cl_bool explicit_zeroes;
// OpenCL state
//cl_command_queue_properties cqProp;
}; // class xSpMSpM
template<> void
xSpMSpM<float>::xSpMSpM_Function(bool flush)
{
clsparseStatus status = clsparseScsrSpGemm(&csrMtx, &csrMtx, &csrMtxC, control);
if (flush)
clFinish(queue);
}// end of single precision function
template<> void
xSpMSpM<double>::xSpMSpM_Function(bool flush)
{
clsparseStatus status = clsparseDcsrSpGemm(&csrMtx, &csrMtx, &csrMtxC, control);
if (flush)
clFinish(queue);
}
#endif // CLSPARSE_BENCHMARK_SpM_SpM_HXX
| 36.935976 | 214 | 0.625175 | [
"vector"
] |
cd768c1fbd80cfd522bb710bdaf8d2865ec27434 | 1,290 | hpp | C++ | src/webots/user_commands/WbResizeCommand.hpp | yjf18340/webots | 60d441c362031ab8fde120cc0cd97bdb1a31a3d5 | [
"Apache-2.0"
] | 1 | 2019-11-13T08:12:02.000Z | 2019-11-13T08:12:02.000Z | src/webots/user_commands/WbResizeCommand.hpp | chinakwy/webots | 7c35a359848bafe81fe0229ac2ed587528f4c73e | [
"Apache-2.0"
] | null | null | null | src/webots/user_commands/WbResizeCommand.hpp | chinakwy/webots | 7c35a359848bafe81fe0229ac2ed587528f4c73e | [
"Apache-2.0"
] | 1 | 2020-09-25T02:01:45.000Z | 2020-09-25T02:01:45.000Z | // Copyright 1996-2019 Cyberbotics Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef WB_RESIZE_COMMAND_HPP
#define WB_RESIZE_COMMAND_HPP
//
// Description: Representation of 'resize' and 'rescale' actions on geometries
// and definition of respective undo and redo functions
//
#include "WbVector3.hpp"
#include <QtWidgets/QUndoCommand>
class WbGeometry;
class WbResizeCommand : public QUndoCommand {
public:
WbResizeCommand(WbGeometry *geometry, const WbVector3 &scale, QUndoCommand *parent = 0);
~WbResizeCommand() {}
void undo() override;
void redo() override;
protected:
bool mIsFirstCall;
WbGeometry *mGeometry;
const WbVector3 mScale;
const WbVector3 mInvScale;
private:
void resetValue(const WbVector3 &scale);
};
#endif
| 26.875 | 90 | 0.747287 | [
"geometry"
] |
cd77d471ba082206c95bac673127485ad8d035ff | 5,643 | cc | C++ | example/speech-demo/python_wrap/ctypes.cc | axbaretto/mxnet | 5f593885356ff6d14f5519fa18e79b944beb51cd | [
"Apache-2.0"
] | 36 | 2018-02-10T07:14:27.000Z | 2021-09-03T09:11:59.000Z | example/speech-demo/python_wrap/ctypes.cc | yanghaojin/BMXNet | 102f8d0ed59529bbd162c37bf07ae58ad6c4caa1 | [
"Apache-2.0"
] | 3 | 2017-07-10T21:49:18.000Z | 2017-07-12T22:40:06.000Z | example/speech-demo/python_wrap/ctypes.cc | yanghaojin/BMXNet | 102f8d0ed59529bbd162c37bf07ae58ad6c4caa1 | [
"Apache-2.0"
] | 15 | 2017-09-20T15:24:53.000Z | 2018-01-11T11:14:03.000Z | #include <iostream>
#include "util/table-types.h"
#include "hmm/posterior.h"
#include "nnet/nnet-nnet.h"
#include "cudamatrix/cu-device.h"
class Foo{
public:
Foo() {
x[0] = 0.5f;
x[1] = 1.5f;
x[2] = 2.5f;
x[3] = 3.5f;
x[4] = 4.5f;
}
void bar(){
std::cout << "Hello" << std::endl;
}
float * getx() {
return x;
}
int sizex() {
return sizeof(x) / sizeof(float);
}
private:
float x[5];
};
namespace kaldi {
typedef SequentialBaseFloatMatrixReader SBFMReader;
typedef Matrix<BaseFloat> MatrixF;
typedef RandomAccessPosteriorReader RAPReader;
namespace nnet1 {
typedef class Nnet_t_ {
public:
Nnet nnet_transf;
CuMatrix<BaseFloat> feats_transf;
MatrixF buf;
} Nnet_t;
}
}
extern "C" {
Foo* Foo_new(){ return new Foo(); }
void Foo_bar(Foo* foo){ foo->bar(); }
float * Foo_getx(Foo* foo) { return foo->getx(); }
int Foo_sizex(Foo* foo) { return foo->sizex(); }
using namespace kaldi;
using namespace kaldi::nnet1;
/****************************** SBFMReader ******************************/
//SequentialTableReader(): impl_(NULL) { }
SBFMReader* SBFMReader_new() {
return new SBFMReader();
}
//SequentialTableReader(const std::string &rspecifier);
SBFMReader* SBFMReader_new_char(char * rspecifier) {
return new SBFMReader(rspecifier);
}
//bool Open(const std::string &rspecifier);
int SBFMReader_Open(SBFMReader* r, char * rspecifier) {
return r->Open(rspecifier);
}
//inline bool Done();
int SBFMReader_Done(SBFMReader* r) {
return r->Done();
}
//inline std::string Key();
const char * SBFMReader_Key(SBFMReader* r) {
return r->Key().c_str();
}
//void FreeCurrent();
void SBFMReader_FreeCurrent(SBFMReader* r) {
r->FreeCurrent();
}
//const T &Value();
const MatrixF * SBFMReader_Value(SBFMReader* r) {
return &r->Value(); //despite how dangerous this looks, this is safe because holder maintains object (it's not stack allocated)
}
//void Next();
void SBFMReader_Next(SBFMReader* r) {
r->Next();
}
//bool IsOpen() const;
int SBFMReader_IsOpen(SBFMReader* r) {
return r->IsOpen();
}
//bool Close();
int SBFMReader_Close(SBFMReader* r) {
return r->Close();
}
//~SequentialTableReader();
void SBFMReader_Delete(SBFMReader* r) {
delete r;
}
/****************************** MatrixF ******************************/
//NumRows ()
int MatrixF_NumRows(MatrixF *m) {
return m->NumRows();
}
//NumCols ()
int MatrixF_NumCols(MatrixF *m) {
return m->NumCols();
}
//Stride ()
int MatrixF_Stride(MatrixF *m) {
return m->Stride();
}
void MatrixF_cpy_to_ptr(MatrixF *m, float * dst, int dst_stride) {
int num_rows = m->NumRows();
int num_cols = m->NumCols();
int src_stride = m->Stride();
int bytes_per_row = num_cols * sizeof(float);
float * src = m->Data();
for (int r=0; r<num_rows; r++) {
memcpy(dst, src, bytes_per_row);
src += src_stride;
dst += dst_stride;
}
}
//SizeInBytes ()
int MatrixF_SizeInBytes(MatrixF *m) {
return m->SizeInBytes();
}
//Data (), Real is usually float32
const float * MatrixF_Data(MatrixF *m) {
return m->Data();
}
/****************************** RAPReader ******************************/
RAPReader* RAPReader_new_char(char * rspecifier) {
return new RAPReader(rspecifier);
}
//bool HasKey (const std::string &key)
int RAPReader_HasKey(RAPReader* r, char * key) {
return r->HasKey(key);
}
//const T & Value (const std::string &key)
int * RAPReader_Value(RAPReader* r, char * key) {
//return &r->Value(key);
const Posterior p = r->Value(key);
int num_rows = p.size();
if (num_rows == 0) {
return NULL;
}
//std::cout << "num_rows " << num_rows << std::endl;
int * vals = new int[num_rows];
for (int row=0; row<num_rows; row++) {
int num_cols = p.at(row).size();
if (num_cols != 1) {
std::cout << "num_cols != 1: " << num_cols << std::endl;
delete vals;
return NULL;
}
std::pair<int32, BaseFloat> pair = p.at(row).at(0);
if (pair.second != 1) {
std::cout << "pair.second != 1: " << pair.second << std::endl;
delete vals;
return NULL;
}
vals[row] = pair.first;
}
return vals;
}
void RAPReader_DeleteValue(RAPReader* r, int * vals) {
delete vals;
}
//~RandomAccessTableReader ()
void RAPReader_Delete(RAPReader* r) {
delete r;
}
/****************************** Nnet_t ******************************/
Nnet_t* Nnet_new(char * filename, float dropout_retention, int crossvalidate) {
//std::cout << "dropout_retention " << dropout_retention << " crossvalidate " << crossvalidate << std::endl;
Nnet_t * nnet = new Nnet_t();
if(strcmp(filename, "") != 0) {
nnet->nnet_transf.Read(filename);
}
if (dropout_retention > 0.0) {
nnet->nnet_transf.SetDropoutRate(dropout_retention);
}
if (crossvalidate) {
nnet->nnet_transf.SetDropoutRate(1.0);
}
return nnet;
}
const MatrixF * Nnet_Feedforward(Nnet_t* nnet, MatrixF * inputs) {
nnet->nnet_transf.Feedforward(CuMatrix<BaseFloat>(*inputs), &nnet->feats_transf);
nnet->buf.Resize(nnet->feats_transf.NumRows(), nnet->feats_transf.NumCols());
nnet->feats_transf.CopyToMat(&nnet->buf);
return &nnet->buf;
}
void Nnet_Delete(Nnet_t* nnet) {
delete nnet;
}
}
| 24.969027 | 131 | 0.57434 | [
"object"
] |
cd7a7a7bef202c9d9f11519a1b7527bf2de69561 | 14,417 | cpp | C++ | cpp-restsdk/model/Supply.cpp | thracesystems/powermeter-api | 7bdab034ff916ee49e986de88f157bd044e981c1 | [
"Apache-2.0"
] | null | null | null | cpp-restsdk/model/Supply.cpp | thracesystems/powermeter-api | 7bdab034ff916ee49e986de88f157bd044e981c1 | [
"Apache-2.0"
] | null | null | null | cpp-restsdk/model/Supply.cpp | thracesystems/powermeter-api | 7bdab034ff916ee49e986de88f157bd044e981c1 | [
"Apache-2.0"
] | null | null | null | /**
* PowerMeter API
* API
*
* The version of the OpenAPI document: 2021.4.1
*
* NOTE: This class is auto generated by OpenAPI-Generator 4.3.1.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "Supply.h"
namespace powermeter {
namespace model {
Supply::Supply()
{
m_Id = 0;
m_IdIsSet = false;
m_Name = utility::conversions::to_string_t("");
m_NameIsSet = false;
m_Voltage = 0.0;
m_VoltageIsSet = false;
m_Type = utility::conversions::to_string_t("");
m_TypeIsSet = false;
m_Is_power = false;
m_Is_powerIsSet = false;
m_Is_ground = false;
m_Is_groundIsSet = false;
m_Switchable = false;
m_SwitchableIsSet = false;
m_Master_supply = 0;
m_Master_supplyIsSet = false;
m_Color = utility::conversions::to_string_t("");
m_ColorIsSet = false;
m_Instance_count = 0;
m_Instance_countIsSet = false;
}
Supply::~Supply()
{
}
void Supply::validate()
{
// TODO: implement validation
}
web::json::value Supply::toJson() const
{
web::json::value val = web::json::value::object();
if(m_IdIsSet)
{
val[utility::conversions::to_string_t("id")] = ModelBase::toJson(m_Id);
}
if(m_NameIsSet)
{
val[utility::conversions::to_string_t("name")] = ModelBase::toJson(m_Name);
}
if(m_VoltageIsSet)
{
val[utility::conversions::to_string_t("voltage")] = ModelBase::toJson(m_Voltage);
}
if(m_TypeIsSet)
{
val[utility::conversions::to_string_t("type")] = ModelBase::toJson(m_Type);
}
if(m_Is_powerIsSet)
{
val[utility::conversions::to_string_t("is_power")] = ModelBase::toJson(m_Is_power);
}
if(m_Is_groundIsSet)
{
val[utility::conversions::to_string_t("is_ground")] = ModelBase::toJson(m_Is_ground);
}
if(m_SwitchableIsSet)
{
val[utility::conversions::to_string_t("switchable")] = ModelBase::toJson(m_Switchable);
}
if(m_Master_supplyIsSet)
{
val[utility::conversions::to_string_t("master_supply")] = ModelBase::toJson(m_Master_supply);
}
if(m_ColorIsSet)
{
val[utility::conversions::to_string_t("color")] = ModelBase::toJson(m_Color);
}
if(m_Instance_countIsSet)
{
val[utility::conversions::to_string_t("instance_count")] = ModelBase::toJson(m_Instance_count);
}
return val;
}
bool Supply::fromJson(const web::json::value& val)
{
bool ok = true;
if(val.has_field(utility::conversions::to_string_t("id")))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("id"));
if(!fieldValue.is_null())
{
int32_t refVal_id;
ok &= ModelBase::fromJson(fieldValue, refVal_id);
setId(refVal_id);
}
}
if(val.has_field(utility::conversions::to_string_t("name")))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("name"));
if(!fieldValue.is_null())
{
utility::string_t refVal_name;
ok &= ModelBase::fromJson(fieldValue, refVal_name);
setName(refVal_name);
}
}
if(val.has_field(utility::conversions::to_string_t("voltage")))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("voltage"));
if(!fieldValue.is_null())
{
double refVal_voltage;
ok &= ModelBase::fromJson(fieldValue, refVal_voltage);
setVoltage(refVal_voltage);
}
}
if(val.has_field(utility::conversions::to_string_t("type")))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("type"));
if(!fieldValue.is_null())
{
utility::string_t refVal_type;
ok &= ModelBase::fromJson(fieldValue, refVal_type);
setType(refVal_type);
}
}
if(val.has_field(utility::conversions::to_string_t("is_power")))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("is_power"));
if(!fieldValue.is_null())
{
bool refVal_is_power;
ok &= ModelBase::fromJson(fieldValue, refVal_is_power);
setIsPower(refVal_is_power);
}
}
if(val.has_field(utility::conversions::to_string_t("is_ground")))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("is_ground"));
if(!fieldValue.is_null())
{
bool refVal_is_ground;
ok &= ModelBase::fromJson(fieldValue, refVal_is_ground);
setIsGround(refVal_is_ground);
}
}
if(val.has_field(utility::conversions::to_string_t("switchable")))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("switchable"));
if(!fieldValue.is_null())
{
bool refVal_switchable;
ok &= ModelBase::fromJson(fieldValue, refVal_switchable);
setSwitchable(refVal_switchable);
}
}
if(val.has_field(utility::conversions::to_string_t("master_supply")))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("master_supply"));
if(!fieldValue.is_null())
{
int32_t refVal_master_supply;
ok &= ModelBase::fromJson(fieldValue, refVal_master_supply);
setMasterSupply(refVal_master_supply);
}
}
if(val.has_field(utility::conversions::to_string_t("color")))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("color"));
if(!fieldValue.is_null())
{
utility::string_t refVal_color;
ok &= ModelBase::fromJson(fieldValue, refVal_color);
setColor(refVal_color);
}
}
if(val.has_field(utility::conversions::to_string_t("instance_count")))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("instance_count"));
if(!fieldValue.is_null())
{
int32_t refVal_instance_count;
ok &= ModelBase::fromJson(fieldValue, refVal_instance_count);
setInstanceCount(refVal_instance_count);
}
}
return ok;
}
void Supply::toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) const
{
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t("."))
{
namePrefix += utility::conversions::to_string_t(".");
}
if(m_IdIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("id"), m_Id));
}
if(m_NameIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("name"), m_Name));
}
if(m_VoltageIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("voltage"), m_Voltage));
}
if(m_TypeIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("type"), m_Type));
}
if(m_Is_powerIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("is_power"), m_Is_power));
}
if(m_Is_groundIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("is_ground"), m_Is_ground));
}
if(m_SwitchableIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("switchable"), m_Switchable));
}
if(m_Master_supplyIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("master_supply"), m_Master_supply));
}
if(m_ColorIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("color"), m_Color));
}
if(m_Instance_countIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("instance_count"), m_Instance_count));
}
}
bool Supply::fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix)
{
bool ok = true;
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t("."))
{
namePrefix += utility::conversions::to_string_t(".");
}
if(multipart->hasContent(utility::conversions::to_string_t("id")))
{
int32_t refVal_id;
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("id")), refVal_id );
setId(refVal_id);
}
if(multipart->hasContent(utility::conversions::to_string_t("name")))
{
utility::string_t refVal_name;
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("name")), refVal_name );
setName(refVal_name);
}
if(multipart->hasContent(utility::conversions::to_string_t("voltage")))
{
double refVal_voltage;
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("voltage")), refVal_voltage );
setVoltage(refVal_voltage);
}
if(multipart->hasContent(utility::conversions::to_string_t("type")))
{
utility::string_t refVal_type;
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("type")), refVal_type );
setType(refVal_type);
}
if(multipart->hasContent(utility::conversions::to_string_t("is_power")))
{
bool refVal_is_power;
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("is_power")), refVal_is_power );
setIsPower(refVal_is_power);
}
if(multipart->hasContent(utility::conversions::to_string_t("is_ground")))
{
bool refVal_is_ground;
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("is_ground")), refVal_is_ground );
setIsGround(refVal_is_ground);
}
if(multipart->hasContent(utility::conversions::to_string_t("switchable")))
{
bool refVal_switchable;
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("switchable")), refVal_switchable );
setSwitchable(refVal_switchable);
}
if(multipart->hasContent(utility::conversions::to_string_t("master_supply")))
{
int32_t refVal_master_supply;
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("master_supply")), refVal_master_supply );
setMasterSupply(refVal_master_supply);
}
if(multipart->hasContent(utility::conversions::to_string_t("color")))
{
utility::string_t refVal_color;
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("color")), refVal_color );
setColor(refVal_color);
}
if(multipart->hasContent(utility::conversions::to_string_t("instance_count")))
{
int32_t refVal_instance_count;
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("instance_count")), refVal_instance_count );
setInstanceCount(refVal_instance_count);
}
return ok;
}
int32_t Supply::getId() const
{
return m_Id;
}
void Supply::setId(int32_t value)
{
m_Id = value;
m_IdIsSet = true;
}
bool Supply::idIsSet() const
{
return m_IdIsSet;
}
void Supply::unsetId()
{
m_IdIsSet = false;
}
utility::string_t Supply::getName() const
{
return m_Name;
}
void Supply::setName(const utility::string_t& value)
{
m_Name = value;
m_NameIsSet = true;
}
bool Supply::nameIsSet() const
{
return m_NameIsSet;
}
void Supply::unsetName()
{
m_NameIsSet = false;
}
double Supply::getVoltage() const
{
return m_Voltage;
}
void Supply::setVoltage(double value)
{
m_Voltage = value;
m_VoltageIsSet = true;
}
bool Supply::voltageIsSet() const
{
return m_VoltageIsSet;
}
void Supply::unsetVoltage()
{
m_VoltageIsSet = false;
}
utility::string_t Supply::getType() const
{
return m_Type;
}
void Supply::setType(const utility::string_t& value)
{
m_Type = value;
m_TypeIsSet = true;
}
bool Supply::typeIsSet() const
{
return m_TypeIsSet;
}
void Supply::unsetType()
{
m_TypeIsSet = false;
}
bool Supply::isIsPower() const
{
return m_Is_power;
}
void Supply::setIsPower(bool value)
{
m_Is_power = value;
m_Is_powerIsSet = true;
}
bool Supply::isPowerIsSet() const
{
return m_Is_powerIsSet;
}
void Supply::unsetIs_power()
{
m_Is_powerIsSet = false;
}
bool Supply::isIsGround() const
{
return m_Is_ground;
}
void Supply::setIsGround(bool value)
{
m_Is_ground = value;
m_Is_groundIsSet = true;
}
bool Supply::isGroundIsSet() const
{
return m_Is_groundIsSet;
}
void Supply::unsetIs_ground()
{
m_Is_groundIsSet = false;
}
bool Supply::isSwitchable() const
{
return m_Switchable;
}
void Supply::setSwitchable(bool value)
{
m_Switchable = value;
m_SwitchableIsSet = true;
}
bool Supply::switchableIsSet() const
{
return m_SwitchableIsSet;
}
void Supply::unsetSwitchable()
{
m_SwitchableIsSet = false;
}
int32_t Supply::getMasterSupply() const
{
return m_Master_supply;
}
void Supply::setMasterSupply(int32_t value)
{
m_Master_supply = value;
m_Master_supplyIsSet = true;
}
bool Supply::masterSupplyIsSet() const
{
return m_Master_supplyIsSet;
}
void Supply::unsetMaster_supply()
{
m_Master_supplyIsSet = false;
}
utility::string_t Supply::getColor() const
{
return m_Color;
}
void Supply::setColor(const utility::string_t& value)
{
m_Color = value;
m_ColorIsSet = true;
}
bool Supply::colorIsSet() const
{
return m_ColorIsSet;
}
void Supply::unsetColor()
{
m_ColorIsSet = false;
}
int32_t Supply::getInstanceCount() const
{
return m_Instance_count;
}
void Supply::setInstanceCount(int32_t value)
{
m_Instance_count = value;
m_Instance_countIsSet = true;
}
bool Supply::instanceCountIsSet() const
{
return m_Instance_countIsSet;
}
void Supply::unsetInstance_count()
{
m_Instance_countIsSet = false;
}
}
}
| 26.897388 | 141 | 0.658944 | [
"object",
"model"
] |
cd7fc19bca89aa8e11c22b70a11fdcb794b7d405 | 8,926 | cc | C++ | thirdparty/glog/src/vlog_is_on.cc | vinben/Rotopp | f0c25db5bd25074c55ff0f67539a2452d92aaf72 | [
"Unlicense"
] | 47 | 2016-07-27T07:22:06.000Z | 2021-08-17T13:08:19.000Z | src/third_party/glog/src/vlog_is_on.cc | rgkoo/libmv-blender | cdf65edbb80d8904e2df9a20116d02546df93a81 | [
"MIT"
] | 1 | 2016-09-24T06:04:39.000Z | 2016-09-25T10:34:19.000Z | src/third_party/glog/src/vlog_is_on.cc | rgkoo/libmv-blender | cdf65edbb80d8904e2df9a20116d02546df93a81 | [
"MIT"
] | 13 | 2016-07-27T10:44:35.000Z | 2020-07-01T21:08:33.000Z | // Copyright (c) 1999, 2007, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: Ray Sidney and many others
//
// Broken out from logging.cc by Soren Lassen
// logging_unittest.cc covers the functionality herein
#include "utilities.h"
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <cstdio>
#include <string>
#include "base/commandlineflags.h"
#include "glog/logging.h"
#include "glog/raw_logging.h"
#include "base/googleinit.h"
// glog doesn't have annotation
#define ANNOTATE_BENIGN_RACE(address, description)
using std::string;
GLOG_DEFINE_int32(v, 0, "Show all VLOG(m) messages for m <= this."
" Overridable by --vmodule.");
GLOG_DEFINE_string(vmodule, "", "per-module verbose level."
" Argument is a comma-separated list of <module name>=<log level>."
" <module name> is a glob pattern, matched against the filename base"
" (that is, name ignoring .cc/.h./-inl.h)."
" <log level> overrides any value given by --v.");
_START_GOOGLE_NAMESPACE_
namespace glog_internal_namespace_ {
namespace {
// Implementation of fnmatch that does not need 0-termination
// of arguments and does not allocate any memory,
// but we only support "*" and "?" wildcards, not the "[...]" patterns.
// It's not a static function for the unittest.
GOOGLE_GLOG_DLL_DECL bool SafeFNMatch_(const char* pattern,
size_t patt_len,
const char* str,
size_t str_len) {
size_t p = 0;
size_t s = 0;
while (1) {
if (p == patt_len && s == str_len) return true;
if (p == patt_len) return false;
if (s == str_len) return p+1 == patt_len && pattern[p] == '*';
if (pattern[p] == str[s] || pattern[p] == '?') {
p += 1;
s += 1;
continue;
}
if (pattern[p] == '*') {
if (p+1 == patt_len) return true;
do {
if (SafeFNMatch_(pattern+(p+1), patt_len-(p+1), str+s, str_len-s)) {
return true;
}
s += 1;
} while (s != str_len);
return false;
}
return false;
}
}
} // namespace
} // namespace glog_internal_namespace_
using glog_internal_namespace_::SafeFNMatch_;
int32 kLogSiteUninitialized = 1000;
// List of per-module log levels from FLAGS_vmodule.
// Once created each element is never deleted/modified
// except for the vlog_level: other threads will read VModuleInfo blobs
// w/o locks and we'll store pointers to vlog_level at VLOG locations
// that will never go away.
// We can't use an STL struct here as we wouldn't know
// when it's safe to delete/update it: other threads need to use it w/o locks.
struct VModuleInfo {
string module_pattern;
mutable int32 vlog_level; // Conceptually this is an AtomicWord, but it's
// too much work to use AtomicWord type here
// w/o much actual benefit.
const VModuleInfo* next;
};
// This protects the following global variables.
static Mutex vmodule_lock;
// Pointer to head of the VModuleInfo list.
// It's a map from module pattern to logging level for those module(s).
static VModuleInfo* vmodule_list = 0;
// Boolean initialization flag.
static bool inited_vmodule = false;
// L >= vmodule_lock.
static void VLOG2Initializer() {
vmodule_lock.AssertHeld();
// Can now parse --vmodule flag and initialize mapping of module-specific
// logging levels.
inited_vmodule = false;
const char* vmodule = FLAGS_vmodule.c_str();
const char* sep;
VModuleInfo* head = NULL;
VModuleInfo* tail = NULL;
while ((sep = strchr(vmodule, '=')) != NULL) {
string pattern(vmodule, sep - vmodule);
int module_level;
if (sscanf(sep, "=%d", &module_level) == 1) {
VModuleInfo* info = new VModuleInfo;
info->module_pattern = pattern;
info->vlog_level = module_level;
if (head) tail->next = info;
else head = info;
tail = info;
}
// Skip past this entry
vmodule = strchr(sep, ',');
if (vmodule == NULL) break;
vmodule++; // Skip past ","
}
if (head) { // Put them into the list at the head:
tail->next = vmodule_list;
vmodule_list = head;
}
inited_vmodule = true;
}
// This can be called very early, so we use SpinLock and RAW_VLOG here.
int SetVLOGLevel(const char* module_pattern, int log_level) {
int result = FLAGS_v;
int const pattern_len = strlen(module_pattern);
bool found = false;
MutexLock l(&vmodule_lock); // protect whole read-modify-write
for (const VModuleInfo* info = vmodule_list;
info != NULL; info = info->next) {
if (info->module_pattern == module_pattern) {
if (!found) {
result = info->vlog_level;
found = true;
}
info->vlog_level = log_level;
} else if (!found &&
SafeFNMatch_(info->module_pattern.c_str(),
info->module_pattern.size(),
module_pattern, pattern_len)) {
result = info->vlog_level;
found = true;
}
}
if (!found) {
VModuleInfo* info = new VModuleInfo;
info->module_pattern = module_pattern;
info->vlog_level = log_level;
info->next = vmodule_list;
vmodule_list = info;
}
RAW_VLOG(1, "Set VLOG level for \"%s\" to %d", module_pattern, log_level);
return result;
}
// NOTE: Individual VLOG statements cache the integer log level pointers.
// NOTE: This function must not allocate memory or require any locks.
bool InitVLOG3__(int32** site_flag, int32* site_default,
const char* fname, int32 verbose_level) {
MutexLock l(&vmodule_lock);
bool read_vmodule_flag = inited_vmodule;
if (!read_vmodule_flag) {
VLOG2Initializer();
}
// protect the errno global in case someone writes:
// VLOG(..) << "The last error was " << strerror(errno)
int old_errno = errno;
// site_default normally points to FLAGS_v
int32* site_flag_value = site_default;
// Get basename for file
const char* base = strrchr(fname, '/');
base = base ? (base+1) : fname;
const char* base_end = strchr(base, '.');
size_t base_length = base_end ? size_t(base_end - base) : strlen(base);
// Trim out trailing "-inl" if any
if (base_length >= 4 && (memcmp(base+base_length-4, "-inl", 4) == 0)) {
base_length -= 4;
}
// TODO: Trim out _unittest suffix? Perhaps it is better to have
// the extra control and just leave it there.
// find target in vector of modules, replace site_flag_value with
// a module-specific verbose level, if any.
for (const VModuleInfo* info = vmodule_list;
info != NULL; info = info->next) {
if (SafeFNMatch_(info->module_pattern.c_str(), info->module_pattern.size(),
base, base_length)) {
site_flag_value = &info->vlog_level;
// value at info->vlog_level is now what controls
// the VLOG at the caller site forever
break;
}
}
// Cache the vlog value pointer if --vmodule flag has been parsed.
ANNOTATE_BENIGN_RACE(site_flag,
"*site_flag may be written by several threads,"
" but the value will be the same");
if (read_vmodule_flag) *site_flag = site_flag_value;
// restore the errno in case something recoverable went wrong during
// the initialization of the VLOG mechanism (see above note "protect the..")
errno = old_errno;
return *site_flag_value >= verbose_level;
}
_END_GOOGLE_NAMESPACE_
| 35.141732 | 79 | 0.667488 | [
"vector"
] |
cd811c1e0ec64b95c93a564db4154e0d92450911 | 12,428 | cpp | C++ | DWriteCore/DWriteCoreGallery/DWriteCoreGallery/TextRenderer.cpp | pmpurifoy/Project-Reunion-Samples | 23015cf649c98eaa305921e41eef21e8fe2e48e9 | [
"MIT"
] | 1 | 2021-07-06T14:30:29.000Z | 2021-07-06T14:30:29.000Z | DWriteCore/DWriteCoreGallery/DWriteCoreGallery/TextRenderer.cpp | pmpurifoy/Project-Reunion-Samples | 23015cf649c98eaa305921e41eef21e8fe2e48e9 | [
"MIT"
] | null | null | null | DWriteCore/DWriteCoreGallery/DWriteCoreGallery/TextRenderer.cpp | pmpurifoy/Project-Reunion-Samples | 23015cf649c98eaa305921e41eef21e8fe2e48e9 | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include "Main.h"
#include "Helpers.h"
#include "TextRenderer.h"
TextRenderer::TextRenderer(HWND hwnd)
{
auto hdc = wil::GetDC(hwnd);
THROW_LAST_ERROR_IF_NULL(hdc);
int dpi = GetDeviceCaps(hdc.get(), LOGPIXELSY);
m_dpiScale = dpi * (1.0f / 96);
THROW_IF_FAILED(g_factory->CreateRenderingParams(&m_renderingParams));
wil::com_ptr<IDWriteGdiInterop> gdiInterop;
THROW_IF_FAILED(g_factory->GetGdiInterop(&gdiInterop));
constexpr SIZE initialSize = { 1024, 256 };
wil::com_ptr<IDWriteBitmapRenderTarget> renderTarget;
THROW_IF_FAILED(gdiInterop->CreateBitmapRenderTarget(hdc.get(), initialSize.cx, initialSize.cy, &renderTarget));
renderTarget.query_to(&m_renderTarget);
m_targetHdc = renderTarget->GetMemoryDC();
m_targetPixelSize = initialSize;
}
IDWriteTextAnalyzer2* TextRenderer::GetTextAnalyzer()
{
if (m_textAnalyzer == nullptr)
{
wil::com_ptr<IDWriteTextAnalyzer> textAnalyzer;
THROW_IF_FAILED(g_factory->CreateTextAnalyzer(&textAnalyzer));
textAnalyzer.query_to(&m_textAnalyzer);
}
return m_textAnalyzer.get();
}
void TextRenderer::Resize(SIZE pixelSize)
{
if (pixelSize.cx > m_targetPixelSize.cx || pixelSize.cy > m_targetPixelSize.cy)
{
int width = std::max(pixelSize.cx, m_targetPixelSize.cx);
int height = std::max(pixelSize.cy, m_targetPixelSize.cy);
THROW_IF_FAILED(m_renderTarget->Resize(width, height));
m_targetPixelSize = { width, height };
}
m_logicalPixelSize = pixelSize;
}
void TextRenderer::Clear(int sysColorIndex)
{
RECT rect = { 0, 0, m_logicalPixelSize.cx, m_logicalPixelSize.cy };
FillRect(m_targetHdc, &rect, GetSysColorBrush(sysColorIndex));
}
void TextRenderer::CopyTo(HDC hdcDest, POINT topLeft)
{
BitBlt(hdcDest, topLeft.x, topLeft.y, m_logicalPixelSize.cx, m_logicalPixelSize.cy, m_targetHdc, 0, 0, SRCCOPY);
}
// IUnknown method
HRESULT STDMETHODCALLTYPE TextRenderer::QueryInterface(REFIID riid, _COM_Outptr_ void** ppvObject) noexcept
{
if (riid == __uuidof(IDWriteTextRenderer1) ||
riid == __uuidof(IDWriteTextRenderer) ||
riid == __uuidof(IDWritePixelSnapping) ||
riid == __uuidof(IUnknown))
{
AddRef();
*ppvObject = this;
return S_OK;
}
else
{
*ppvObject = nullptr;
return E_NOINTERFACE;
}
}
// IUnknown method
ULONG STDMETHODCALLTYPE TextRenderer::AddRef() noexcept
{
return ++m_refCount;
}
// IUnknown method
ULONG STDMETHODCALLTYPE TextRenderer::Release() noexcept
{
uint32_t newCount = --m_refCount;
if (newCount == 0)
{
delete this;
}
return newCount;
}
DWRITE_MATRIX TextRenderer::CombineTransform(DWRITE_MATRIX a, DWRITE_MATRIX b) noexcept
{
return
{
a.m11 * b.m11 + a.m12 * b.m21,
a.m11 * b.m12 + a.m12 * b.m22,
a.m21 * b.m11 + a.m22 * b.m21,
a.m21 * b.m12 + a.m22 * b.m22,
a.dx * b.m11 + a.dy * b.m21 + b.dx,
a.dx * b.m12 + a.dy * b.m22 + b.dy
};
}
TextRenderer::OrientationTransform::OrientationTransform(TextRenderer* renderer,
DWRITE_GLYPH_ORIENTATION_ANGLE orientationAngle,
bool isSideways,
D2D_POINT_2F origin
)
{
if (orientationAngle != DWRITE_GLYPH_ORIENTATION_ANGLE_0_DEGREES)
{
m_renderTarget = renderer->GetRenderTarget();
THROW_IF_FAILED(m_renderTarget->GetCurrentTransform(&m_oldTransform));
DWRITE_MATRIX orientationTransform;
THROW_IF_FAILED(renderer->GetTextAnalyzer()->GetGlyphOrientationTransform(orientationAngle, isSideways, origin.x, origin.y, &orientationTransform));
DWRITE_MATRIX finalTransform = CombineTransform(m_oldTransform, orientationTransform);
THROW_IF_FAILED(m_renderTarget->SetCurrentTransform(&finalTransform));
}
}
TextRenderer::OrientationTransform::~OrientationTransform()
{
if (m_renderTarget != nullptr)
{
m_renderTarget->SetCurrentTransform(&m_oldTransform);
}
}
// IDWritePixelSnapping method
HRESULT STDMETHODCALLTYPE TextRenderer::IsPixelSnappingDisabled(
_In_opt_ void* clientDrawingContext,
_Out_ BOOL* isDisabled
) noexcept
{
*isDisabled = false;
return S_OK;
}
// IDWritePixelSnapping method
HRESULT STDMETHODCALLTYPE TextRenderer::GetCurrentTransform(
_In_opt_ void* clientDrawingContext,
_Out_ DWRITE_MATRIX* transform
) noexcept
{
*transform = DWRITE_MATRIX{ 1, 0, 0, 1, 0, 0 };
return S_OK;
}
// IDWritePixelSnapping method
HRESULT STDMETHODCALLTYPE TextRenderer::GetPixelsPerDip(
_In_opt_ void* clientDrawingContext,
_Out_ FLOAT* pixelsPerDip
) noexcept
{
*pixelsPerDip = m_dpiScale;
return S_OK;
}
inline BYTE FloatToColorByte(float c)
{
return static_cast<BYTE>(floorf(c * 255 + 0.5f));
}
COLORREF ToCOLORREF(DWRITE_COLOR_F color)
{
return RGB(
FloatToColorByte(color.r),
FloatToColorByte(color.g),
FloatToColorByte(color.b)
);
}
// IDWriteTextRenderer method
HRESULT STDMETHODCALLTYPE TextRenderer::DrawGlyphRun(
_In_opt_ void* clientDrawingContext,
FLOAT baselineOriginX,
FLOAT baselineOriginY,
DWRITE_MEASURING_MODE measuringMode,
_In_ DWRITE_GLYPH_RUN const* glyphRun,
_In_ DWRITE_GLYPH_RUN_DESCRIPTION const* glyphRunDescription,
_In_opt_ IUnknown* clientDrawingEffect
) noexcept
{
return DrawGlyphRun(
clientDrawingContext,
baselineOriginX,
baselineOriginY,
DWRITE_GLYPH_ORIENTATION_ANGLE_0_DEGREES,
measuringMode,
glyphRun,
glyphRunDescription,
clientDrawingEffect
);
}
// IDWriteTextRenderer1 method
HRESULT STDMETHODCALLTYPE TextRenderer::DrawGlyphRun(
_In_opt_ void* clientDrawingContext,
FLOAT baselineOriginX,
FLOAT baselineOriginY,
DWRITE_GLYPH_ORIENTATION_ANGLE orientationAngle,
DWRITE_MEASURING_MODE measuringMode,
_In_ DWRITE_GLYPH_RUN const* glyphRun,
_In_ DWRITE_GLYPH_RUN_DESCRIPTION const* glyphRunDescription,
_In_opt_ IUnknown* clientDrawingEffect
) noexcept
{
try
{
OrientationTransform orentation(
this,
orientationAngle,
!!glyphRun->isSideways,
D2D_POINT_2F{ baselineOriginX, baselineOriginY }
);
HRESULT hr = DWRITE_E_NOCOLOR;
wil::com_ptr<IDWriteColorGlyphRunEnumerator> colorLayers;
wil::com_ptr<IDWriteFontFace2> fontFace2;
if (SUCCEEDED(glyphRun->fontFace->QueryInterface(&fontFace2)))
{
uint32_t paletteCount = fontFace2->GetColorPaletteCount();
if (paletteCount > 0)
{
DWRITE_MATRIX transform;
hr = m_renderTarget->GetCurrentTransform(&transform);
if (FAILED(hr))
{
return hr;
}
transform.m11 *= m_dpiScale;
transform.m12 *= m_dpiScale;
transform.m21 *= m_dpiScale;
transform.m22 *= m_dpiScale;
transform.dx *= m_dpiScale;
transform.dy *= m_dpiScale;
// Perform color translation.
// Fall back to the default palette if the current palette index is out of range.
hr = g_factory->TranslateColorGlyphRun(
baselineOriginX,
baselineOriginY,
glyphRun,
nullptr,
measuringMode,
&transform,
m_colorPaletteIndex < paletteCount ? m_colorPaletteIndex : 0,
& colorLayers
);
}
}
if (hr == DWRITE_E_NOCOLOR)
{
THROW_IF_FAILED(m_renderTarget->DrawGlyphRun(
baselineOriginX,
baselineOriginY,
measuringMode,
glyphRun,
m_renderingParams.get(),
m_textColor
));
}
else
{
THROW_IF_FAILED(hr);
for (;;)
{
BOOL haveRun;
THROW_IF_FAILED(colorLayers->MoveNext(&haveRun));
if (!haveRun)
{
break;
}
DWRITE_COLOR_GLYPH_RUN const* colorRun;
THROW_IF_FAILED(colorLayers->GetCurrentRun(&colorRun));
COLORREF runColor = (colorRun->paletteIndex == 0xFFFF) ? m_textColor : ToCOLORREF(colorRun->runColor);
THROW_IF_FAILED(m_renderTarget->DrawGlyphRun(
colorRun->baselineOriginX,
colorRun->baselineOriginY,
measuringMode,
&colorRun->glyphRun,
m_renderingParams.get(),
runColor
));
}
}
return S_OK;
}
catch (wil::ResultException& e)
{
return e.GetErrorCode();
}
}
// IDWriteTextRenderer method
HRESULT STDMETHODCALLTYPE TextRenderer::DrawUnderline(
_In_opt_ void* clientDrawingContext,
FLOAT baselineOriginX,
FLOAT baselineOriginY,
_In_ DWRITE_UNDERLINE const* underline,
_In_opt_ IUnknown* clientDrawingEffect
) noexcept
{
// TODO - text decorations
return E_NOTIMPL;
}
// IDWriteTextRenderer1 method
HRESULT STDMETHODCALLTYPE TextRenderer::DrawUnderline(
_In_opt_ void* clientDrawingContext,
FLOAT baselineOriginX,
FLOAT baselineOriginY,
DWRITE_GLYPH_ORIENTATION_ANGLE orientationAngle,
_In_ DWRITE_UNDERLINE const* underline,
_In_opt_ IUnknown* clientDrawingEffect
) noexcept
{
// TODO - text decorations
return E_NOTIMPL;
}
// IDWriteTextRenderer method
HRESULT STDMETHODCALLTYPE TextRenderer::DrawStrikethrough(
_In_opt_ void* clientDrawingContext,
FLOAT baselineOriginX,
FLOAT baselineOriginY,
_In_ DWRITE_STRIKETHROUGH const* strikethrough,
_In_opt_ IUnknown* clientDrawingEffect
) noexcept
{
// TODO - text decorations
return E_NOTIMPL;
}
// IDWriteTextRenderer1 method
HRESULT STDMETHODCALLTYPE TextRenderer::DrawStrikethrough(
_In_opt_ void* clientDrawingContext,
FLOAT baselineOriginX,
FLOAT baselineOriginY,
DWRITE_GLYPH_ORIENTATION_ANGLE orientationAngle,
_In_ DWRITE_STRIKETHROUGH const* strikethrough,
_In_opt_ IUnknown* clientDrawingEffect
) noexcept
{
// TODO - text decorations
return E_NOTIMPL;
}
// IDWriteTextRenderer method
HRESULT STDMETHODCALLTYPE TextRenderer::DrawInlineObject(
_In_opt_ void* clientDrawingContext,
FLOAT originX,
FLOAT originY,
_In_ IDWriteInlineObject* inlineObject,
BOOL isSideways,
BOOL isRightToLeft,
_In_opt_ IUnknown* clientDrawingEffect
) noexcept
{
return DrawInlineObject(
clientDrawingContext,
originX,
originY,
DWRITE_GLYPH_ORIENTATION_ANGLE_0_DEGREES,
inlineObject,
isSideways,
isRightToLeft,
clientDrawingEffect
);
}
// IDWriteTextRenderer1 method
HRESULT STDMETHODCALLTYPE TextRenderer::DrawInlineObject(
_In_opt_ void* clientDrawingContext,
FLOAT originX,
FLOAT originY,
DWRITE_GLYPH_ORIENTATION_ANGLE orientationAngle,
_In_ IDWriteInlineObject* inlineObject,
BOOL isSideways,
BOOL isRightToLeft,
_In_opt_ IUnknown* clientDrawingEffect
) noexcept
{
try
{
OrientationTransform orentation(
this,
orientationAngle,
!!isSideways,
D2D_POINT_2F{ originX, originY }
);
THROW_IF_FAILED(inlineObject->Draw(
clientDrawingContext,
this,
originX,
originY,
isSideways,
isRightToLeft,
clientDrawingEffect
));
return S_OK;
}
catch (wil::ResultException& e)
{
return e.GetErrorCode();
}
}
| 28.702079 | 157 | 0.630914 | [
"transform"
] |
cd87e3cb30d456a01375e5bc61a0e2e171c166b7 | 724 | cpp | C++ | AcWing/LeetCode究极班/210.cpp | LauZyHou/- | 66c047fe68409c73a077eae561cf82b081cf8e45 | [
"MIT"
] | 7 | 2019-02-25T13:15:00.000Z | 2021-12-21T22:08:39.000Z | AcWing/LeetCode究极班/210.cpp | LauZyHou/- | 66c047fe68409c73a077eae561cf82b081cf8e45 | [
"MIT"
] | null | null | null | AcWing/LeetCode究极班/210.cpp | LauZyHou/- | 66c047fe68409c73a077eae561cf82b081cf8e45 | [
"MIT"
] | 1 | 2019-04-03T06:12:46.000Z | 2019-04-03T06:12:46.000Z | class Solution {
public:
vector<int> findOrder(int n, vector<vector<int>>& edges) {
vector<vector<int>> g(n);
vector<int> d(n);
for (auto& e: edges) {
int b = e[0], a = e[1];
g[a].emplace_back(b);
d[b] ++;
}
queue<int> q;
for (int i = 0; i < n; i ++ )
if (!d[i])
q.push(i);
vector<int> res;
while (q.size()) {
int t = q.front();
q.pop();
res.emplace_back(t);
for (int i: g[t]) {
if (-- d[i] == 0)
q.push(i);
}
}
if (res.size() < n) res = {};
return res;
}
}; | 24.133333 | 62 | 0.348066 | [
"vector"
] |
cd8c48cb0671b4bd5edd352d8ce9cb77f5a0cf27 | 4,361 | cc | C++ | internal/ceres/preprocessor.cc | hitxiaomi/ceres-solver | c3129c3d4a4830d23a310bd78c240898c82b36e9 | [
"Apache-2.0"
] | 2,425 | 2015-01-23T00:02:03.000Z | 2022-03-31T22:15:00.000Z | internal/ceres/preprocessor.cc | hitxiaomi/ceres-solver | c3129c3d4a4830d23a310bd78c240898c82b36e9 | [
"Apache-2.0"
] | 624 | 2015-03-18T14:36:29.000Z | 2022-03-31T16:06:14.000Z | internal/ceres/preprocessor.cc | hitxiaomi/ceres-solver | c3129c3d4a4830d23a310bd78c240898c82b36e9 | [
"Apache-2.0"
] | 989 | 2015-01-14T14:50:27.000Z | 2022-03-30T15:20:06.000Z | // Ceres Solver - A fast non-linear least squares minimizer
// Copyright 2015 Google Inc. All rights reserved.
// http://ceres-solver.org/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Author: sameragarwal@google.com (Sameer Agarwal)
#include "ceres/preprocessor.h"
#include "ceres/callbacks.h"
#include "ceres/gradient_checking_cost_function.h"
#include "ceres/line_search_preprocessor.h"
#include "ceres/parallel_for.h"
#include "ceres/problem_impl.h"
#include "ceres/solver.h"
#include "ceres/trust_region_preprocessor.h"
namespace ceres {
namespace internal {
Preprocessor* Preprocessor::Create(MinimizerType minimizer_type) {
if (minimizer_type == TRUST_REGION) {
return new TrustRegionPreprocessor;
}
if (minimizer_type == LINE_SEARCH) {
return new LineSearchPreprocessor;
}
LOG(FATAL) << "Unknown minimizer_type: " << minimizer_type;
return NULL;
}
Preprocessor::~Preprocessor() {}
void ChangeNumThreadsIfNeeded(Solver::Options* options) {
if (options->num_threads == 1) {
return;
}
const int num_threads_available = MaxNumThreadsAvailable();
if (options->num_threads > num_threads_available) {
LOG(WARNING) << "Specified options.num_threads: " << options->num_threads
<< " exceeds maximum available from the threading model Ceres "
<< "was compiled with: " << num_threads_available
<< ". Bounding to maximum number available.";
options->num_threads = num_threads_available;
}
}
void SetupCommonMinimizerOptions(PreprocessedProblem* pp) {
const Solver::Options& options = pp->options;
Program* program = pp->reduced_program.get();
// Assuming that the parameter blocks in the program have been
// reordered as needed, extract them into a contiguous vector.
pp->reduced_parameters.resize(program->NumParameters());
double* reduced_parameters = pp->reduced_parameters.data();
program->ParameterBlocksToStateVector(reduced_parameters);
Minimizer::Options& minimizer_options = pp->minimizer_options;
minimizer_options = Minimizer::Options(options);
minimizer_options.evaluator = pp->evaluator;
if (options.logging_type != SILENT) {
pp->logging_callback.reset(new LoggingCallback(
options.minimizer_type, options.minimizer_progress_to_stdout));
minimizer_options.callbacks.insert(minimizer_options.callbacks.begin(),
pp->logging_callback.get());
}
if (options.update_state_every_iteration) {
pp->state_updating_callback.reset(
new StateUpdatingCallback(program, reduced_parameters));
// This must get pushed to the front of the callbacks so that it
// is run before any of the user callbacks.
minimizer_options.callbacks.insert(minimizer_options.callbacks.begin(),
pp->state_updating_callback.get());
}
}
} // namespace internal
} // namespace ceres
| 41.141509 | 80 | 0.737904 | [
"vector",
"model"
] |
cd8d6e0e10c0df19c6732a0e0934658dd94776cb | 4,478 | cpp | C++ | cnippet/Configuration_C.cpp | ludanpr/psychec | 3b4e057995e103c62d72b50e8fac1088f2b19727 | [
"BSD-3-Clause"
] | null | null | null | cnippet/Configuration_C.cpp | ludanpr/psychec | 3b4e057995e103c62d72b50e8fac1088f2b19727 | [
"BSD-3-Clause"
] | null | null | null | cnippet/Configuration_C.cpp | ludanpr/psychec | 3b4e057995e103c62d72b50e8fac1088f2b19727 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2016/17/18/19/20/21/22 Leandro T. C. Melo <ltcmelo@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "Configuration_C.h"
namespace {
const char* const kCStd = "c-std";
const char* const kHostCCompiler = "host-cc";
const char* const kExpandCPPIncludeDirectives = "cpp-includes";
const char* const kDefineCPPMacro = "cpp-D";
const char* const KUndefineCPPMacro = "cpp-U";
const char* const kAddDirToCPPSearchPath = "cpp-I";
}
using namespace cnip;
void ConfigurationForC::extend(cxxopts::Options& cmdLineOpts)
{
cmdLineOpts.add_options()
// https://gcc.gnu.org/onlinedocs/gcc/C-Dialect-Options.html#C-Dialect-Options
(kCStd,
"Specify the C standard.",
cxxopts::value<std::string>()->default_value("c11"),
"<c89|c90|c99|c11|c17>")
(kHostCCompiler,
"Specify a host C compiler.",
cxxopts::value<std::string>()->default_value("gcc"),
"<gcc|clang>")
// https://gcc.gnu.org/onlinedocs/cpp/Include-Syntax.html
(kExpandCPPIncludeDirectives,
"Expand `#include' directives of the C preprocessor.",
cxxopts::value<bool>()->default_value("false"))
// https://gcc.gnu.org/onlinedocs/gcc/Directory-Options.html
(kAddDirToCPPSearchPath,
"Add a directory to the `#include' search path of the C preprocessor.",
cxxopts::value<std::vector<std::string>>(),
"path")
// https://gcc.gnu.org/onlinedocs/gcc/Preprocessor-Options.html
(kDefineCPPMacro,
"Predefine a C preprocessor macro.",
cxxopts::value<std::vector<std::string>>(),
"<name|name=definition>")
(KUndefineCPPMacro,
"Undefine a C preprocessor macro.",
cxxopts::value<std::vector<std::string>>(),
"<name>")
/* Type inference */
("C-infer", "Infer the definition of missing types.")
("o,output", "Specify output file",
cxxopts::value<std::string>()->default_value("a.cstr"))
;
}
ConfigurationForC::ConfigurationForC(const cxxopts::ParseResult& parsedCmdLine)
: Configuration(parsedCmdLine)
{
auto cc_std = parsedCmdLine[kCStd].as<std::string>();
std::for_each(cc_std.begin(),
cc_std.end(),
[] (char& c) { c = ::tolower(c); });
if (cc_std == "c89" || cc_std == "c90")
langStd = LanguageDialect::Std::C89_90;
else if (cc_std == "c99")
langStd = LanguageDialect::Std::C99;
else if (cc_std == "c17" || cc_std == "c18")
langStd = LanguageDialect::Std::C17_18;
else
langStd = LanguageDialect::Std::C11;
hostCompiler = parsedCmdLine[kHostCCompiler].as<std::string>();
expandIncludes = parsedCmdLine[kExpandCPPIncludeDirectives].as<bool>();
if (parsedCmdLine.count(kDefineCPPMacro))
macrosToDefine = parsedCmdLine[kDefineCPPMacro].as<std::vector<std::string>>();
if (parsedCmdLine.count(KUndefineCPPMacro))
macrosToUndef = parsedCmdLine[KUndefineCPPMacro].as<std::vector<std::string>>();
if (parsedCmdLine.count(kAddDirToCPPSearchPath))
headerSearchPaths = parsedCmdLine[kAddDirToCPPSearchPath].as<std::vector<std::string>>();
inferMissingTypes = parsedCmdLine.count("infer");
}
| 42.647619 | 97 | 0.646494 | [
"vector"
] |
cd92b632432d8da8c8c3d3e41c96231cf22efab2 | 6,267 | hpp | C++ | drivers/sick_ldmrs_driver/src/driver/src/tools/SickThread.hpp | alanjclark/autoware.ai | ba97edbbffb6f22e78912bf96400a59ef6a13daf | [
"Apache-2.0"
] | 64 | 2018-11-19T02:34:05.000Z | 2021-12-27T06:19:48.000Z | ros/src/sensing/drivers/lidar/packages/sick/ldmrs/sick_ldmrs_driver/src/driver/src/tools/SickThread.hpp | anhnv3991/autoware | d5b2ed9dc309193c8a2a7c77a2b6c88104c28328 | [
"Apache-2.0"
] | 40 | 2019-06-24T16:56:15.000Z | 2022-02-28T13:41:58.000Z | ros/src/sensing/drivers/lidar/packages/sick/ldmrs/sick_ldmrs_driver/src/driver/src/tools/SickThread.hpp | anhnv3991/autoware | d5b2ed9dc309193c8a2a7c77a2b6c88104c28328 | [
"Apache-2.0"
] | 34 | 2018-11-27T08:57:32.000Z | 2022-02-18T08:06:04.000Z | //
// SickThread.hpp
//
#ifndef SICKTHREAD_HPP
#define SICKTHREAD_HPP
#include "../BasicDatatypes.hpp"
#include <pthread.h>
#include <unistd.h>
extern "C" void* wrapper_prerun(void*);
class ThreadWrapperBase
{
pthread_t t_id;
friend void* wrapper_prerun(void*);
virtual void thread_entry() = 0;
protected:
void* pthis;
public:
ThreadWrapperBase() {pthis = NULL;};
virtual ~ThreadWrapperBase() {};
void run(void* classptr)
{
if (pthis == NULL)
{
pthis = classptr;
pthread_create(&t_id, NULL, wrapper_prerun, this);
}
}
bool isRunning()
{
if (pthis == NULL)
{
return false;
}
return true;
}
void join()
{
pthread_join(t_id, NULL);
pthis = NULL;
}
pthread_t* get_thread_id()
{
return &t_id;
}
};
/// Wrapper class for posix threads
/**
* Usage: Using object must create an instance of this class, and then
* call start() with its callback function as argument (see start()
* for more details). To stop the thread execution, call stop().
*
* Setting the parameter m_beVerbose to true (e.g. via
* enableVerboseDebugOutput in function start()) will turn on *very*
* verbose output that should be useful for debugging.
*
* The thread callback function itself has 2 parameters:
*
* endThisThread: A bool flag that may be set by the callback function
* to "false" in case the thread function decides this thread
* needs to end.
*
* sleepTimeMs: The sleep time, in ms, that will be spent between
* subsequent calls to the callback function. Default is 10 ms, but
* other times may be set. Note that not all operating systems may be
* able to schedule very short sleep times.
*/
template <typename T, void (T::*M)(bool&, UINT16&)>
class SickThread : public ThreadWrapperBase
{
void thread_entry()
{
T* pt = static_cast<T*>(pthis);
m_threadShouldRun = true;
bool endThread = false;
UINT16 sleepTimeMs = 0;
while ((m_threadShouldRun == true) && (endThread == false))
{
usleep(((UINT32)sleepTimeMs) * 1000);
(pt->*M)(endThread, sleepTimeMs);
}
}
public:
void join()
{
m_threadShouldRun = false;
ThreadWrapperBase::join();
}
SickThread(){m_threadShouldRun = true;}
virtual ~SickThread(){};
bool m_threadShouldRun;
};
/*
template <typename T, void (T::*M)()>
class SickThread : public ThreadWrapperBase
{
void thread_entry()
{
T* pt = static_cast<T*>(pthis);
(pt->*M)();
}
public:
SickThread(){}
virtual ~SickThread(){};
};
*/
// class SickThread
// {
// public:
// /**
// * The thread callback function.
// *
// * \param endThisThread A bool flag that may be set by the callback function
// * to "false" in case the thread function decides this thread
// * needs to end.
// *
// * \param sleepTimeMs The sleep time, in ms, that will be spent between
// * subsequent calls to the callback function. Default is 10 ms, but
// * other times may be set. Note that not all operating systems may be
// * able to schedule very short sleep times.
// */
// // int (*comp)(const void *, const void *)
// typedef void (*ThreadFunction) (bool& endThisThread, UINT16& sleepTimeMs);
//
// /**
// * The thread callback function (simpler version).
// *
// * \return True if the thread should continue to run and
// * continuously call this function (after potentially some waiting
// * time). False if this thread should end now.
// */
// // typedef boost::function < bool (void) > ThreadFunctionSimple;
//
// /// Default constructor.
// SickThread();
//
// /// Destructor. Will call stop() if thread is not yet stopped, and
// /// wait for its completion before destructing this object.
// ~SickThread();
//
// /// Start the thread.
// bool start();
//
// /// Start the thread and also set the thread function. \sa start()
// bool start(ThreadFunction function);
//
// /// Returns true if this thread was started and is running.
// bool isRunning() const;
//
// /// Stops this thread and waits for its completion.
// void stop();
//
// /// Set whether we want verbose debug output
// void setVerboseDebugOutput(bool enableVerboseDebugOutput);
//
// /// Set the thread's "run" function
// void setFunction(ThreadFunction threadFunction);
//
// /// Set the thread's "run" function, simpler version
// // void setFunctionSimple(ThreadFunctionSimple threadFunctionSimple);
//
// /// Set the sleep time between subsequent ThreadFunctionSimple calls in [milliseconds]
// void setSleepTimeMilliseconds(unsigned v);
//
// /// Returns the sleep time between subsequent ThreadFunctionSimple
// /// calls in [milliseconds]. (Default value is zero.)
// unsigned getSleepTimeMilliseconds() const { return m_sleepTimeMilliseconds; }
//
// private:
// static void* thread(void* ptr); // The thread function
// void thread2(); // The member thread function
//
// // typedef boost::mutex Mutex;
//
// pthread_mutex_t m_mutex; // = PTHREAD_MUTEX_INITIALIZER;
// // mutable Mutex m_threadMutex;
// // boost::condition m_threadCondition;
// ThreadFunction m_function;
// // ThreadFunctionSimple m_functionSimple;
//
// // boost::scoped_ptr<boost::thread> m_threadPtr;
// bool m_threadShouldRun;
// bool m_threadIsRunning;
// bool m_beVerbose;
// unsigned m_sleepTimeMilliseconds;
//
// // The thread
// pthread_t m_thread;
//
// };
/*
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define NUM_THREADS 5
void *TaskCode(void *argument)
{
int tid;
tid = *((int *) argument);
printf("Hello World! It's me, thread %d!\n", tid);
// optionally: insert more useful stuff here
return NULL;
}
int main(void)
{
pthread_t threads[NUM_THREADS];
int thread_args[NUM_THREADS];
int rc, i;
// create all threads
for (i=0; i<NUM_THREADS; ++i) {
thread_args[i] = i;
printf("In main: creating thread %d\n", i);
rc = pthread_create(&threads[i], NULL, TaskCode, (void *) &thread_args[i]);
assert(0 == rc);
}
// wait for all threads to complete
for (i=0; i<NUM_THREADS; ++i) {
rc = pthread_join(threads[i], NULL);
assert(0 == rc);
}
exit(EXIT_SUCCESS);
}
*/
#endif // SICKTHREAD_HPP
| 24.196911 | 90 | 0.657252 | [
"object"
] |
cd96871c70f0128ffd49c7f20e8b2d4f701b446d | 3,666 | hpp | C++ | SpaceNotificationsMain.hpp | TerabyteForever/SpaceNotifications | 2f733dc43a23180b9d17de289fc651807e0655d0 | [
"MIT"
] | 1 | 2020-09-28T19:36:43.000Z | 2020-09-28T19:36:43.000Z | SpaceNotificationsMain.hpp | TerabyteForever/SpaceNotifications | 2f733dc43a23180b9d17de289fc651807e0655d0 | [
"MIT"
] | null | null | null | SpaceNotificationsMain.hpp | TerabyteForever/SpaceNotifications | 2f733dc43a23180b9d17de289fc651807e0655d0 | [
"MIT"
] | null | null | null | //This header is the client side API of the SpaceNotifications. It is designed for the client applications that uses SpaceNotifications.
#include <string>
#include <tuple>
#include <vector>
#include <iostream>
#include <fstream>
#include <exception>
#include <ctime>
#include "include/Colorized.hpp"
//Shared memory support
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <cstdlib>
#include <algorithm>
#include <utility>
using namespace boost::interprocess;
struct NotificationType{
int key;
char title[100];
char notificationItself[1000];
};
typedef allocator<NotificationType, managed_shared_memory::segment_manager> ShmemAllocator;
typedef vector<NotificationType, ShmemAllocator> MainVector;
managed_shared_memory segment(open_or_create,"spacenotifications",65536);
const ShmemAllocator alloc_inst (segment.get_segment_manager());
MainVector *notification_holder = segment.find_or_construct<MainVector>("spaceshared")(alloc_inst);
int notificationCounter = 0;
int readNotificationCounter = 0;
std::ofstream outputFile("SpaceNotificationLog.txt",std::ios::trunc);
class SpaceNotifications{
std::string getDateTime(){
struct tm CurTime;
char datetime[80];
time_t CurrentEpoch = time(NULL);
CurTime = *localtime(&CurrentEpoch);
strftime(datetime, sizeof(datetime), "%d-%m-%Y %H:%M:%S", &CurTime);
return datetime;
}
public:
int getNotificationsCount(){
return notification_holder->size();
}
int getUnreadNotificationsCount(){
return notification_holder->size() - readNotificationCounter;
}
void PushNotification(bool isDebug, char title[], char text[]){
NotificationType a;
a.key = notificationCounter;
strcpy(a.title,title);
strcpy(a.notificationItself,text);
notification_holder->push_back(a);
if(isDebug){
outputFile<<"[ "<<getDateTime()<<" ] "<<"Notification has written to the queue "<<notificationCounter<<"."<<std::endl;
outputFile.eof();
}
notificationCounter++;
}
void ReadNotification(int elementKey){
try{
if(elementKey > notification_holder->size()){
throw std::invalid_argument("Invalid key.");
}
else{
std::cout<<std::endl<<std::endl<<WBOLD_YELLOW_COLOR<<notification_holder->at(elementKey).title<<std::endl<<std::endl<<WBOLD_WHITE_COLOR<<notification_holder->at(elementKey).notificationItself<<std::endl;
readNotificationCounter++;
}
}
catch(std::invalid_argument& inv_arg){
std::cout<<std::endl<<inv_arg.what()<<std::endl;
}
}
}; | 25.458333 | 243 | 0.528914 | [
"vector"
] |
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- 7