text
string
No. 24; Updated March 2011 Click here to download and print a PDF version of this document. Parents are usually the first to recognize that their child has a problem with emotions or behavior. Still, the decision to seek professional help can be difficult and painful for a parent. The first step is to gently try to talk to the child. An honest open talk about feelings can often help. Parents may choose to consult with the child's physicians, teachers, members of the clergy, or other adults who know the child well. These steps may resolve the problems for the child and family. Following are a few signs which may indicate that a child and adolescent psychiatric evaluation will be useful. - Marked fall in school performance - Poor grades in school despite trying very hard - Severe worry or anxiety, as shown by regular refusal to go to school, go to sleep or take part in activities that are normal for the child's age - Frequent physical complaints - Hyperactivity; fidgeting; constant movement beyond regular playing with or without difficulty paying attention - Persistent nightmares - Persistent disobedience or aggression (longer than 6 months) and provocative opposition to authority figures - Frequent, unexplainable temper tantrums - Threatens to harm or kill oneself - Marked decline in school performance - Inability to cope with problems and daily activities - Marked changes in sleeping and/or eating habits - Extreme difficulties in concentrating that get in the way at school or at home - Sexual acting out - Depression shown by sustained, prolonged negative mood and attitude, often accompanied by poor appetite, difficulty sleeping or thoughts of death - Severe mood swings - Strong worries or anxieties that get in the way of daily life, such as at school or socializing - Repeated use of alcohol and/or drugs - Intense fear of becoming obese with no relationship to actual body weight, excessive dieting, throwing up or using laxatives to loose weight - Persistent nightmares - Threats of self-harm or harm to others - Self-injury or self destructive behavior - Frequent outbursts of anger, aggression - Repeated threats to run away - Aggressive or non-aggressive consistent violation of rights of others; opposition to authority, truancy, thefts, or vandalism - Strange thoughts, beliefs, feelings, or unusual behaviors See other Facts for Families: #25 Where to Seek Help for Your Child #52 Comprehensive Psychiatric Evaluation #57 Normal Adolescent Development, Middle School, and Early High School Years #58 Normal Adolescent Development, Late High School Year and Beyond #00 Definition of a Child and Adolescent Psychiatrist The American Academy of Child and Adolescent Psychiatry (AACAP) represents over 8,500 child and adolescent psychiatrists who are physicians with at least five years of additional training beyond medical school in general (adult) and child and adolescent psychiatry. Facts for Families© information sheets are developed, owned and distributed by AACAP. Hard copies of Facts sheets may be reproduced for personal or educational use without written permission, but cannot be included in material presented for sale or profit. All Facts can be viewed and printed from the AACAP website (www.aacap.org). Facts sheets may not be reproduced, duplicated or posted on any other website without written consent from AACAP. Organizations are permitted to create links to AACAP's website and specific Facts sheets. For all questions please contact the AACAP Communications & Marketing Coordinator, ext. 154. If you need immediate assistance, please dial 911. Copyright © 2012 by the American Academy of Child and Adolescent Psychiatry.
/** \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
Previous abstract Next abstract Session 40 - The Interstellar Medium. Display session, Tuesday, June 09 Gamma Ray Burst (GRB) explosions can make kpc-size shells and holes in the interstellar media (ISM) of spiral galaxies if much of the energy heats the local gas to above 10^7 K. Disk blowout is probably the major cause for energy loss in this case, but the momentum acquired during the pressurized expansion phase can be large enough that the bubble still snowplows to a kpc diameter. This differs from the standard model for the origin of such shells by multiple supernovae, which may have problems with radiative cooling, evaporative losses, and disk blow-out. Evidence for giant shells with energies of \sim10^53 ergs are summarized. Some contain no obvious central star clusters and may be GRB remnants, although sufficiently old clusters would be hard to detect. The expected frequency of GRBs in normal galaxies can account for the number of such shells. Program listing for Tuesday
Books  Palaeontology  Palaeozoology & Extinctions  Popular Science By: WJT Mitchell(Author) 321 pages, Col and b/w photos, col and b/w illus University of Chicago Press Hardback | Oct 1998 | #84743 | ISBN: 0226532046 Availability: Usually dispatched within 4 days Details NHBS Price: £24.50 $32/€27 approx About this book For animals that have been dead millions of years, dinosaurs are extraordinarily pervasive in our everyday lives. Appearing in ads, books, movies, museums, television, toy stores, and novels, they continually fascinate both adults and children. How did they move from natural extinction to pop culture resurrection? What is the source of their powerful appeal? Until now, no one has addressed this question in a comprehensive way. In this lively and engrossing exploration of the animal's place in our lives, W.J.T. Mitchell shows why we are so attached to the myth and the reality of the "terrible lizards." Mitchell aims to trace the cultural family tree of the dinosaur, and what he discovers is a creature of striking flexibility, linked to dragons and mammoths, skyscrapers and steam engines, cowboys and Indians. In the vast territory between the cunning predators of Jurassic Park and the mawkishly sweet Barney, from political leviathans to corporate icons, from paleontology to Barnum and Bailey, Mitchell finds a cultural symbol whose plurality of meaning and often contradictory nature is emblematic of modern society itself. As a scientific entity, the dinosaur endured a near-eclipse for over a century, but as an image it is enjoying its widest circulation. And it endures, according to Mitchell, because it is uniquely malleable, a figure of both innovation and obsolescence, massive power and pathetic failure – the totem animal of modernity. Drawing unforeseen and unusual connections at every turn between dinosaurs real and imagined, The Last Dinosaur Book is the first to delve so deeply, so insightfully, and so enjoyably into our modern dino-obsession. ""[...] brilliant and truly original. It is the first serious attempt by a cultural historian to understand the extraordinarily strong hold that dinosaurs have taken on the imagination of whole sections of the population, not just children. Mitchell has wonderfully mastered the field of dinosaurs, from systematics to science fiction, and the delight of the book is in the interpretations." - Keith Thomson, Director, Oxford University Museum of Natural History 1: Reptilicus erectus 2: Big, Fierce, Extinct 3: A Stegosaurus Made of Money 4: The End of Dinosaurology 5: The Last Thunder Horse West of the Mississippi 6: Dinotopia: The Newt World Order 7: The Last Dinostory: As Told by Himself 8: Seeing Saurians 9: Sorting Species 10: Monsters and Dinomania 11: Big MacDino 12: The Totem Animal of Modernity 13: The Way of Dragons 14: Dry Bones 15: On the Evolution of Images 16: Thomas Jefferson, Paleontologist 17: Frames, Skeletons, Constitutions 18: The Victorian Dinosaur 19: Coming to America 20: Bones for Darwin's Bulldog 21: Schizosaur 22: Dinosaurs Moralized 23: Pale-Ontology, or It's Not Easy Being Green 24: Potlatch and Purity 25: Diplodocus carnegii 26: Totems and Bones 27: Indiana Jones and Barnum Bones 28: Worlds Well Lost 29: Bringing Down Baby 30: Miner's Canary or Trojan Horse? 31: The Age of Reptiles 32: The Hundred Story Beast 33: Structure, Energy, Information 34: Catastrophe, Entropy, Chaos 35: The Age of Biocybernetic Reproduction 36: Carnosaurs and Consumption 37: Why Children Hate Dinosaurs 38: Dinos R Us: Identification and Fantasy 39: Calvinosaurus: From T. rex to O. Rex 40: Transitional Objects: From Breast to Brontosaurus Paleoart 265 A: Scrotum Humanum: The True Name of the Dinosaur B: Science and Culture Selected Bibliography Write a review Bestsellers in this subject Extinct Birds Avian Evolution NHBS Price: £64.99 $84/€71 approx Discovering the Mammoth NHBS Price: £21.99 $28/€24 approx The Princeton Field Guide to Dinosaurs Pterosaurs: Natural History, Evolution, Anatomy NHBS Price: £27.95 $36/€31 approx VAT: GB 407 4846 44 NHBS Ltd is registered in England and Wales: 1875194
#ifndef CLI_DEV_PCB_H #define CLI_DEV_PCB_H #include <stdio.h> #include <sstream> #include "command/param_comple/behavior_base.h" namespace clidevt { class FileListBehavior : public ParameterBehavior { class SpecialCharEscaper { public: std::string operator()(std::string str) { std::string ret; std::string::iterator ite = str.begin(); for(; ite != str.end(); ++ite) { switch(*ite) { case ' ': ret += "\\ "; break; case '\\': ret += "\\\\"; break; case '|': ret += "\\|"; break; case '<': ret += "\\<"; break; case '>': ret += "\\>"; break; case '\"': ret += "\\\""; break; case '\'': ret += "\\\'"; break; default: ret += *ite; break; } } return ret; } }; public: enum CandidateType { DIRECTORY = 1, EXECUTABLE = 2, NON_EXECUTABLE = 4, SYMBOLIC_LINK = 8, ALL = 15 }; FileListBehavior() : candidateType_(ALL) {} virtual ~FileListBehavior() {} void setCandidatesType(int type) { candidateType_ = type; } virtual void getParamCandidates(std::vector<std::string>& inputtedList, std::string inputting, std::vector<std::string>& candidates) const; virtual void afterCompletionHook(std::vector<std::string>& candidates) const { stripParentPath(candidates); } virtual void stripParentPath(std::vector<std::string>& candidates) const; virtual void stripFile(std::vector<std::string>& candidates) const; private: int candidateType_; }; } #endif /* end of include guard */
A land whose rich cultural heritage is discovered not only from within the walls of numerous museums, galleries and churches, many of which today, as zero category monuments are included in a part of the UNESCO World Heritage List, but also in that magical place on the Mediterranean, where even the shortest stroll becomes a journey down a staircase thousands of years old, which takes one through a history that is at the same time turbulent, exciting and glorious. With as many as seven cultural phenomena- The Festivity of Saint Blaise, lace-making in Lepoglava, Hvar and Pag, the bell ringers from the Kastav region, the Hvar Procession Za Križem, (‘following the Cross’), two-part singing in the Istrian scale, in Istria and Hrvatsko Primorje, the spring procession of ‘Ljelje’ and traditional manufacture of wooden toys in the Hrvatsko zagorje region, Croatia is among the countries with the most protected intangible cultural heritage elements, recorded on the UNESCO List. The famous scientist Nikola Tesla (1856-1943), inventor of alternating current. Was born in Smiljan, Croatia, died in New York, USA. Dog breed Dalmatian originates from these areas? In a small Franciscan monastery in Zaostrog, there is a painting from 1724 which for the first time depicts a Dalmatian dog… Slavoljub Eduard Penkala In 1906, a Croat Slavoljub Eduard Penkala for the first time applied for a patent for a ballpoint (penkala) and a holder for a fountain pen. From time immemorial, the tie has been a part of the Croatian national costume, which was preserved by the Croats to the more recent times, who moved to central Europe in the 16th century. It was later taken over by the Croatian soldiers who were fighting in Europe, and a part of their uniform was assumed by the French in the 17th century. Under the leadership of the French „God of Sun" Louis XIV there was a horsemen unit, the so-called Royal cravate, who wore mostly red collar ribbons. The custom of wearing ribbons from the Croats dates back to this time, which was later expanded around Europe and the world, and today is inevitably the most important detail in men's fashion, and also an original Croatian souvenir. The word «kravata» (tie) originates from the word «Kroate»... The world traveler and explorer Marco Polo was born in 1254, most probably on the island of Korčula. Even today, there are people living on the island with the same last name.. Island of Vrnik is situated in the archipelago of the Pelješac canal in front of the east coast of Korčula island, widely known for its stone-pit of quality lime-stone (marble) from which Aia Sofia (Istanbul) and the While House (Washington) were partly built as were some palaces-town halls in Dubrovnik, Stockholm, Venice, Vienna. Visit to the fertile plains of Baranja where the grapes have been cultivated for centuries, is not complete if you do not taste the "golden drops" of Baranja's vineyards. According to the old manuscripts, vine was a usual drink at the royal court of Maria Teresa, and the ancient Romans, delighted with its bouquet and with the sun rises and sunsets of that region, called it the "Golden hill"... There is a Ulysses' cave on the island of Mljet. It was named after a story which says that a famous adventurer stranded on the nearby cliff Ogiron, where he met the nymph Calypso with whom he fell in love, and spent unforgettable moments in her company... Red-white coat of arms Recognizable all over the world, and related only to Croats - characteristic cube-shaped red-white coat of arms which is believed to originate from the Persian original homeland of Croats (red signifies south and white signifies north). That is where the name for two Croatias derives from, i.e. White in north and Red in south. When the Croats have selected Ferdinand Habsburg to be their King in Cetine in 1527, they confirmed that choice with some seals, and one of them was Croatian coat of arms, but with 64 fields, i.e. the complete chess-board. That is where the popular term „šahovnica" derives from, and Šah (chess) in Persian means the Ruler - Tsar. Did you know that there is a world rarity in the Archeological museum in Zagreb? Of course, we are talking about the Zagreb mummy. Nesi-hensu, the wife of Aher-hensu, „the divine tailor" from Thebes, is the name of a mummified woman who was wrapped in cut ribbons of Zagreb linen book which represents the longest preserved text in Etruscan language and the only preserved sample of linen book in the entire Ancient world. Top seven world getaways The American magazine "In Style" has included Croatia on its list of seven top world destinations ("Top seven world getaways"). The article authors recommend a visit to Croatia for its very rich historical-cultural heritage, natural beauties and clean sea. In addition to Croatia, the list of top seven places includes Kenya, South Africa, London, Greek island Santorini and three American destinations - Aspen, Napa Valley and Nantucket. Every day, for over hundred and ten years, the cannon fires from the top of tower Lotrščak exactly at noon in memory of an event from Zagreb history. According to the legend, exactly at noon, the Grič canon fired a discharge from Lotrščak to the Turkish camp located across Sava and blew out a rooster (or a turkey) which the cook was taking to Pasha on a platter. After this event, the Turks scattered and did not attack Zagreb...
Nuclear Energy in France Nuclear energy is the cornerstone of french energy policy. In the ‘70s France chose to develop nuclear as its base load electricity source as a response to the oil crisis and assure its energy independence. Nuclear Electricity Production: France currently counts 58 commercial nuclear reactors in operation responsible for producing 80% of French domestic electricity. As a comparison, the 104 US reactors produces 20% of US electricity.Despite scarce natural resources, France has reached an energy independence of 50% thanks to its strategic choice for nuclear energy. Environment: As well as providing safe and reliable energy, nuclear helps to reduce French greenhouse gas emissions by avoiding the release of 31 billions tones of carbon dioxide (contrary to coal or gas generation) and making France the less carbon emitting country within the OECD. As a leader in nuclear energy, France has developed clean technology for radioactive waste disposal. Reprocessing currently allows France to recover valuable elements from spent fuels and permit a significant reduction of high level waste and lead to safer and optimized containment, for final radioactive waste disposition. French nuclear power plants produces only 10 g/year/inhabitant of highly radioactive waste. International Cooperation and research: France is one of the forerunner in nuclear research and participates in numerous international cooperation programs alongside the United States such as the development of the next generation of nuclear power plants (Gen IV) and the International Thermonuclear Experimental Reactor (ITER) that will be built in Cadarache, South of France. The French Atomic Energy Commission (CEA) The French Atomic Energy Commission is a public body established in October 1945 by General de Gaulle. It constitutes a power of expertise and proposition for the authorities. A leader in research, development and innovation, the CEA is involved in three main fields: It develops and acquires the technological building blocks necessary to the development of the nuclear reactors of the future (Contribution to Generation IV and GNEP research), It contributes to reducing greenhouse gas emission with its research on hydrogen, fuel cells, biomass, energy storage…, It supports the nuclear utilities in France by optimizing the nuclear power plants of the French nuclear fleet and by optimizing the fuel cycle, It offers safe and economically viable technical solutions for managing nuclear waste, It conducts fundamental research in climate and environmental sciences, high energy physics, astrophysics, fusion, nanosciences… Information and Health technologies: It tackles micro and nano-technologies for telecommunication and nuclear medicine for radiotherapy and medical imaging, It researches programs on biotechnology, molecular labelling, biomolecular engineering and structural biology, It shares its knowledge and know-how through education and training through the National Institute for Nuclear Sciences and Technologies (INSTN), It manages over 300 priority patents and is active in the creation of clusters. Defense and National Security: It conceives, builds, maintains then dismantles the nuclear warhead of the French deterrence force, It helps to fight against nuclear, biological and chemical weapons (NRBC program). The missions of the CEA are similar to the Department of Energy in the United States. The CEA has a network of counselor or representatives in French Embassies around the world (see joint map). The French Nuclear Safety Authority (ASN) Created in 2006, from the former DSIN (Directorate for the Safety of Nuclear Facilities), the French Nuclear Safety Authority is an independent administrative authority which is tasked with regulating nuclear safety and radiation protection in order to protect workers, patients, the public and the environment from the risks involved in nuclear activities. It also contributes to informing the public. Like the Nuclear Regulatory Commission in the United States, it carries out inspections and may pronounce sanctions, up to and including suspension of operation of an installation. French Institute for Radioprotection and Nuclear Safety (IRSN) Created in 2001 by merging the Protection and Nuclear Safety Institute (IPSN) and the Ionizing radiations Protection Office (OPRI), the Institute for Radioprotection and Nuclear Safety is a public establishment of an industrial and commercial nature placed under the joint authority of the Ministries of the Environment, Health, Industry, Research and Defense. It is the expert in safety research and specialized assessments into nuclear and radiological risk serving public authorities whose work is complementary to the ASN. Its scope of activities includes: environment and response, human radiological protection, research on the prevention of major accidents, power reactor safety, fuel cycle facility safety, research installation safety, waste management safety; nuclear defense expertise. National radioactive Waste Management Agency (ANDRA) Created in 1991, the French National Agency for Radioactive Waste Management is a public industrial and commercial organization that operates independently of waste producers. It is responsible for the long-term management of radioactive waste produced in France under the supervision of the French Ministries for Energy, Research and the Environment. It can be compared to a certain extent to the Office for Nuclear Waste of the Department of Energy in the United States. Andra also pursues industrial, research, and information activities as it designs and implements disposal solutions suited to each category of radioactive waste: the collection, conditioning, disposal of radioactive waste from small producers (hospitals, research centers, industry), specification of waste packages for disposal, disposal in suited sites, monitoring of closed disposal facilities, research programs for long-lived and high level activity waste, especially through the operation of an underground research laboratory in a deep clay formation… General Directorate for Energy and Climate (DGEC) The General Directorate for Energy and Climate represents the government and is part of the Office of the Department for Ecology and Sustainable Development. It defines the French nuclear policy. The DGEC takes care of the energy supply, the security of supply, oil refining and logistics, nuclear industry, and coal and mines. Consequently, its activities include: the design and implement energy and raw material supply policy, to ensure opening of electricity and gas markets, track key energy and raw material sectors, to oversee enterprises and public institutions in energy sector, to ensure compliance with rules and regulations governing energy sector, to participate in European and international energy projects and working groups, to provide economic, environmental, and fiscal expertise on energy matters. The Rise of Nuclear Power Generation in France.
Mexican America - Introduction "Mexican America" is a sampling of objects from the collections of the National Museum of American History. The stories behind these objects reflect the history of the Mexican presence in the United States. They illustrate a fundamentally American story about the centuries-old encounter between distinct (yet sometimes overlapping) communities that have coexisted but also clashed over land, culture, and livelihood. Who, where, and what is Mexico? Over time, the definitions and boundaries of Mexico have changed. The Aztec Empire and the area where Náhautl was spoken—today the region surrounding modern Mexico City—was known as Mexico. For 300 years, the Spanish colonizers renamed it New Spain. When Mexico was reborn in 1821 as a sovereign nation, its borders stretched from California to Guatemala. It was a huge and ancient land of ethnically, linguistically, and economically diverse regions that struggled for national unity. Texas, (then part of the Mexican state of Coahuila y Tejas) was a frontier region far from the dense cities and fertile valleys of central Mexico, a place where immigrants were recruited from the United States. The immigrants in turn declared the Mexican territory an independent republic in 1836 (later a U.S. state), making the state the first cauldron of Mexican American culture. By 1853, the government of Mexico, the weaker neighbor of an expansionist United States, had lost what are today the states of California, Nevada, Utah, Arizona, New Mexico, Texas, and parts of Colorado and Wyoming. In spite of the imposition of a new border, the historical and living presence of Spaniards, Mexicans, indigenous peoples, and their mixed descendants remained a defining force in the creation of the American West. “La América Mexicana” es una muestra conformada por objetos provenientes de las distintas colecciones del Museo Nacional de Historia Americana. Estos objetos reflejan la historia de la presencia mexicana en los Estados Unidos e ilustran una crónica fundamentalmente americana acerca del encuentro centenario entre comunidades diferentes que han coexistido, pero que también se han enfrentado, en la pugna por la tierra, la cultura y el sustento. ¿Quién, dónde y qué es México? Con el transcurso del tiempo, las definiciones y los límites de México han ido cambiando. Se conocía como México al Imperio Azteca y toda el área donde se hablaba náhuatl —actualmente la región circundante a la ciudad de México. Durante 300 años los colonizadores españoles se refirieron a ella como Nueva España. Cuando en 1821 México resurgió como una nación soberana, sus fronteras se extendían desde California a Guatemala. En ese entonces era un antiguo e inmenso territorio conformado por regiones étnica, lingüística y económicamente diversas que luchaban por adquirir unidad nacional. Texas (en ese entonces parte de los estados mexicanos de Coahuila y Tejas) era una región fronteriza lejos de las densas urbes y de los fértiles valles de México central, donde se reclutaban inmigrantes de los Estados Unidos. En el año 1836 este territorio mexicano se declaró como república independiente (y más tarde, estado de EE.UU.), convirtiéndose en el primer calderón de la cultura mexicoamericana. Hacia 1853, el gobierno de México, el vecino débil de un Estados Unidos en expansión, había perdido el territorio de los actuales estados de California, Nevada, Utah, Arizona, Nuevo México, Texas y partes de Colorado y Wyoming. A pesar de la imposición de un nuevo límite fronterizo, la presencia histórica y ocupacional de los españoles, mexicanos y pueblos indígenas, junto a sus descendientes mestizos, constituiría a lo largo del tiempo una influencia determinante para el desarrollo del Oeste Americano. "Mexican America - Introduction" showing 1 items. - This print depicts American forces attacking the fortress palace of Chapultepec on Sept. 13th, 1847. General Winfield Scott, in the lower left on a white horse, led the southern division of the U.S. Army that successfully captured Mexico City during the Mexican American War. The outcome of American victory was the loss of Mexico's northern territories, from California to New Mexico, by the terms set in the Treaty of Guadalupe Hidalgo. It should be noted that the two countries ratified different versions of the same peace treaty, with the United States ultimately eliminating provisions for honoring the land titles of its newly absorbed Mexican citizens. Despite notable opposition to the war from Americans like Abraham Lincoln, John Quincy Adams, and Henry David Thoreau, the Mexican-American War proved hugely popular. The United States' victory boosted American patriotism and the country's belief in Manifest Destiny. - This large chromolithograph was first distributed in 1848 by Nathaniel Currier of Currier and Ives, who served as the "sole agent." The lithographers, Sarony & Major of New York (1846-1857) copied it from a painting by "Walker." Unfortunately, the current location of original painting is unknown, however, when the print was made the original painting was owned by a Captain B. S. Roberts of the Mounted Rifles. The original artist has previously been attributed to William Aiken Walker as well as to Henry A. Walke. William Aiken Walker (ca 1838-1921) of Charleston did indeed do work for Currier and Ives, though not until the 1880's and he would have only have been only 10 years old when this print was copyrighted. Henry Walke (1808/9-1896) was a naval combat artist during the Mexican American War who also worked with Sarony & Major and is best known for his Naval Portfolio. - Most likely the original painting was done by James Walker (1819-1889) who created the "Battle of Chapultepec" 1857-1862 for the U.S. Capitol. This image differs from the painting commissioned for the U. S. Capitol by depicting the troops in regimented battle lines with General Scott in a more prominent position in the foreground. James Walker was living in Mexico City at the outbreak of the Mexican War and joined the American forces as an interpreter. He was attached to General Worth's staff and was present at the battles of Contreras, Churubusco, and Chapultepec. The original painting's owner, Captain Roberts was assigned General Winfield Scott to assist Walker with recreating the details of the battle of Chapultepec. When the painting was complete, Roberts purchased the painting. By 1848, James Walker had returned to New York and had a studio in New York City in the same neighborhood as the print's distributor Nathaniel Currier as well as the lithographer's Napoleon Sarony and Henry B. Major. - This popular lithograph was one of several published to visually document the war while engaging the imagination of the public. Created prior to photography, these prints were meant to inform the public, while generally eliminating the portrayal of the more gory details. Historians have been able to use at least some prints of the Mexican War for study and to corroborate with the traditional literary forms of documentation. As an eyewitness, Walker could claim accuracy of detail within the narrative in his painting. The battle is presented in the grand, historic, heroic style with the brutality of war not portrayed. The print depiction is quite large for a chromo of the period. In creating the chromolithographic interpretation of the painting, Sarony & Major used at least four large stones to produce the print "in colours," making the most of their use of color. They also defined each figure with precision by outlining each in black. This print was considered by expert/collector Harry T. Peters as one of the finest ever produced by Sarony & Major. - Currently not on view - Date made - associated date - Currier, Nathaniel - Scott, Winfield - Sarony & Major - Walker, James - ID Number - catalog number - accession number - Data Source - National Museum of American History, Kenneth E. Behring Center
// Copyright (c) 2006-2008 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. #ifndef CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_ #define CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_ #include <string> #include <map> #include <vector> #include "base/basictypes.h" #include "base/file_path.h" #include "base/observer_list.h" #include "base/scoped_ptr.h" #include "chrome/browser/bookmarks/bookmark_model.h" #include "chrome/browser/google_service_auth_error.h" #include "chrome/browser/profile.h" #include "chrome/browser/sync/glue/change_processor.h" #include "chrome/browser/sync/glue/model_associator.h" #include "chrome/browser/sync/glue/sync_backend_host.h" #include "chrome/browser/sync/sync_setup_wizard.h" #include "chrome/common/notification_registrar.h" #include "googleurl/src/gurl.h" class CommandLine; class MessageLoop; class Profile; namespace browser_sync { class UnrecoverableErrorHandler { public: // Call this when normal operation detects that the bookmark model and the // syncer model are inconsistent, or similar. The ProfileSyncService will // try to avoid doing any work to avoid crashing or corrupting things // further, and will report an error status if queried. virtual void OnUnrecoverableError() = 0; protected: virtual ~UnrecoverableErrorHandler() { } }; } // Various UI components such as the New Tab page can be driven by observing // the ProfileSyncService through this interface. class ProfileSyncServiceObserver { public: // When one of the following events occurs, OnStateChanged() is called. // Observers should query the service to determine what happened. // - We initialized successfully. // - There was an authentication error and the user needs to reauthenticate. // - The sync servers are unavailable at this time. // - Credentials are now in flight for authentication. virtual void OnStateChanged() = 0; protected: virtual ~ProfileSyncServiceObserver() { } }; // ProfileSyncService is the layer between browser subsystems like bookmarks, // and the sync backend. class ProfileSyncService : public NotificationObserver, public browser_sync::SyncFrontend, public browser_sync::UnrecoverableErrorHandler { public: typedef ProfileSyncServiceObserver Observer; typedef browser_sync::SyncBackendHost::Status Status; enum SyncEventCodes { MIN_SYNC_EVENT_CODE = 0, // Events starting the sync service. START_FROM_NTP = 1, // Sync was started from the ad in NTP START_FROM_WRENCH = 2, // Sync was started from the Wrench menu. START_FROM_OPTIONS = 3, // Sync was started from Wrench->Options. START_FROM_BOOKMARK_MANAGER = 4, // Sync was started from Bookmark manager. // Events regarding cancelation of the signon process of sync. CANCEL_FROM_SIGNON_WITHOUT_AUTH = 10, // Cancelled before submitting // username and password. CANCEL_DURING_SIGNON = 11, // Cancelled after auth. CANCEL_DURING_SIGNON_AFTER_MERGE = 12, // Cancelled during merge. // Events resulting in the stoppage of sync service. STOP_FROM_OPTIONS = 20, // Sync was stopped from Wrench->Options. // Miscellaneous events caused by sync service. MERGE_AND_SYNC_NEEDED = 30, MAX_SYNC_EVENT_CODE }; explicit ProfileSyncService(Profile* profile); virtual ~ProfileSyncService(); // Initializes the object. This should be called every time an object of this // class is constructed. void Initialize(); // Enables/disables sync for user. virtual void EnableForUser(); virtual void DisableForUser(); // Whether sync is enabled by user or not. bool HasSyncSetupCompleted() const; void SetSyncSetupCompleted(); // NotificationObserver implementation. virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details); // SyncFrontend implementation. virtual void OnBackendInitialized(); virtual void OnSyncCycleCompleted(); virtual void OnAuthError(); // Called when a user enters credentials through UI. virtual void OnUserSubmittedAuth(const std::string& username, const std::string& password, const std::string& captcha); // Called when a user decides whether to merge and sync or abort. virtual void OnUserAcceptedMergeAndSync(); // Called when a user cancels any setup dialog (login, merge and sync, etc). virtual void OnUserCancelledDialog(); // Get various information for displaying in the user interface. browser_sync::SyncBackendHost::StatusSummary QuerySyncStatusSummary(); browser_sync::SyncBackendHost::Status QueryDetailedSyncStatus(); const GoogleServiceAuthError& GetAuthError() const { return last_auth_error_; } // Displays a dialog for the user to enter GAIA credentials and attempt // re-authentication, and returns true if it actually opened the dialog. // Returns false if a dialog is already showing, an auth attempt is in // progress, the sync system is already authenticated, or some error // occurred preventing the action. We make it the duty of ProfileSyncService // to open the dialog to easily ensure only one is ever showing. bool SetupInProgress() const { return !HasSyncSetupCompleted() && WizardIsVisible(); } bool WizardIsVisible() const { return wizard_.IsVisible(); } void ShowLoginDialog(); // Pretty-printed strings for a given StatusSummary. static std::wstring BuildSyncStatusSummaryText( const browser_sync::SyncBackendHost::StatusSummary& summary); // Returns true if the SyncBackendHost has told us it's ready to accept // changes. // TODO(timsteele): What happens if the bookmark model is loaded, a change // takes place, and the backend isn't initialized yet? bool sync_initialized() const { return backend_initialized_; } bool unrecoverable_error_detected() const { return unrecoverable_error_detected_; } bool UIShouldDepictAuthInProgress() const { return is_auth_in_progress_; } // A timestamp marking the last time the service observed a transition from // the SYNCING state to the READY state. Note that this does not reflect the // last time we polled the server to see if there were any changes; the // timestamp is only snapped when syncing takes place and we download or // upload some bookmark entity. const base::Time& last_synced_time() const { return last_synced_time_; } // Returns a user-friendly string form of last synced time (in minutes). std::wstring GetLastSyncedTimeString() const; // Returns the authenticated username of the sync user, or empty if none // exists. It will only exist if the authentication service provider (e.g // GAIA) has confirmed the username is authentic. virtual string16 GetAuthenticatedUsername() const; const std::string& last_attempted_user_email() const { return last_attempted_user_email_; } // The profile we are syncing for. Profile* profile() { return profile_; } // Adds/removes an observer. ProfileSyncService does not take ownership of // the observer. void AddObserver(Observer* observer); void RemoveObserver(Observer* observer); // Record stats on various events. static void SyncEvent(SyncEventCodes code); // Returns whether sync is enabled. Sync can be enabled/disabled both // at compile time (e.g., on a per-OS basis) or at run time (e.g., // command-line switches). static bool IsSyncEnabled(); // UnrecoverableErrorHandler implementation. virtual void OnUnrecoverableError(); browser_sync::SyncBackendHost* backend() { return backend_.get(); } protected: // Call this after any of the subsystems being synced (the bookmark // model and the sync backend) finishes its initialization. When everything // is ready, this function will bootstrap the subsystems so that they are // initially in sync, and start forwarding changes between the two models. void StartProcessingChangesIfReady(); // Returns whether processing changes is allowed. Check this before doing // any model-modifying operations. bool ShouldPushChanges(); // Starts up the backend sync components. void StartUp(); // Shuts down the backend sync components. // |sync_disabled| indicates if syncing is being disabled or not. void Shutdown(bool sync_disabled); // Methods to register and remove preferences. void RegisterPreferences(); void ClearPreferences(); // Tests need to override this. virtual void InitializeBackend(); template <class AssociatorImpl, class ChangeProcessorImpl> void InstallGlue() { model_associator_->CreateAndRegisterPerDataTypeImpl<AssociatorImpl>(); // TODO(tim): Keep a map instead of a set so we can register/unregister // data type specific ChangeProcessors, once we have more than one. STLDeleteElements(processors()); ChangeProcessorImpl* processor = new ChangeProcessorImpl(this); change_processors_.insert(processor); processor->set_model_associator( model_associator_->GetImpl<AssociatorImpl>()); } browser_sync::ModelAssociator* associator() { return model_associator_.get(); } std::set<browser_sync::ChangeProcessor*>* processors() { return &change_processors_; } // We keep track of the last auth error observed so we can cover up the first // "expected" auth failure from observers. // TODO(timsteele): Same as expecting_first_run_auth_needed_event_. Remove // this! GoogleServiceAuthError last_auth_error_; // Cache of the last name the client attempted to authenticate. std::string last_attempted_user_email_; private: friend class ProfileSyncServiceTest; friend class ProfileSyncServiceTestHarness; friend class TestModelAssociator; FRIEND_TEST(ProfileSyncServiceTest, UnrecoverableErrorSuspendsService); // Initializes the various settings from the command line. void InitSettings(); // Whether the sync merge warning should be shown. bool MergeAndSyncAcceptanceNeeded() const; // Sets the last synced time to the current time. void UpdateLastSyncedTime(); // When running inside Chrome OS, extract the LSID cookie from the cookie // store to bootstrap the authentication process. std::string GetLsidForAuthBootstraping(); // Time at which we begin an attempt a GAIA authorization. base::TimeTicks auth_start_time_; // Time at which error UI is presented for the new tab page. base::TimeTicks auth_error_time_; // The profile whose data we are synchronizing. Profile* profile_; // TODO(ncarter): Put this in a profile, once there is UI for it. // This specifies where to find the sync server. GURL sync_service_url_; // The last time we detected a successful transition from SYNCING state. // Our backend notifies us whenever we should take a new snapshot. base::Time last_synced_time_; // Our asynchronous backend to communicate with sync components living on // other threads. scoped_ptr<browser_sync::SyncBackendHost> backend_; // Model association manager instance. scoped_ptr<browser_sync::ModelAssociator> model_associator_; // The change processors that handle the different data types. std::set<browser_sync::ChangeProcessor*> change_processors_; NotificationRegistrar registrar_; // Whether the SyncBackendHost has been initialized. bool backend_initialized_; // Set to true when the user first enables sync, and we are waiting for // syncapi to give us the green light on providing credentials for the first // time. It is set back to false as soon as we get this message, and is // false all other times so we don't have to persist this value as it will // get initialized to false. // TODO(timsteele): Remove this by way of starting the wizard when enabling // sync *before* initializing the backend. syncapi will need to change, but // it means we don't have to wait for the first AuthError; if we ever get // one, it is actually an error and this bool isn't needed. bool expecting_first_run_auth_needed_event_; // Various pieces of UI query this value to determine if they should show // an "Authenticating.." type of message. We are the only central place // all auth attempts funnel through, so it makes sense to provide this. // As its name suggests, this should NOT be used for anything other than UI. bool is_auth_in_progress_; SyncSetupWizard wizard_; // True if an unrecoverable error (e.g. violation of an assumed invariant) // occurred during syncer operation. This value should be checked before // doing any work that might corrupt things further. bool unrecoverable_error_detected_; ObserverList<Observer> observers_; DISALLOW_COPY_AND_ASSIGN(ProfileSyncService); }; #endif // CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_
// // 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; }
/* 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); }
Octodon degus is generally considered endemic to west central Chile, where it inhabits the lower slopes of the Andes. Although some have argued that its range may extend north into Peru, this is not well supported. It is common in the international pet trade, however, and is often used in laboratory studies outside of its native range. (Contreras, et al., 1987; Woods and Boraker, 1975) Octodon degus inhabits a mediterranean-type semi-arid shrubland ecosystem called "matorral", which is found on the western slopes of the Andes between 28 and 35 degrees south latitude. Further north the climate becomes too arid to support this plant community, and further south it is too wet. Degus appear to be limited to elevations below 1200 meters, both by the distribution of their habitat and by their intolerance of low oxygen partial pressure. Degus are well able to inhabit lands influenced by cattle grazing, and are agricultural pests in some areas. (Contreras, et al., 1987; Fulk, 1976) Octodon degus superficially resembles a gerbil, but is much larger. Degus typically weigh between 170 and 300 g, and measure between 325 and 440 mm in length, including the tail. The fur is yellow-brown on the back and head, and the underparts and feet are cream colored. There is a pale band around the eye and, in some individuals, the neck. The tail is moderately long and conspicuously tufted. The ears are large and darkly pigmented. The fifth digit is reduced, and on the forefeet it has a nail instead of a claw. The cheekteeth are hypsodont and their biting surfaces resemble a figure of eight. Sexes are difficult to distinguish, but males tend to be about 10% larger than females. Pups are born furred and able to see, and begin exploring within hours of birth. Octodon degus can be distinguished from the two other members of the genus Octodon by slight differences in dental morphology. It is also smaller than its relatives and its tail is said to be more noticeably tufted. (Fulk, 1976; Lee, 2004) During the annual breeding season, male-male aggression temporarily increases. Males exclude other males from their burrow and monopolize the females (usually 2 to 4) who live there. Dustbathing and urine marking may be used in the defense of territory by both sexes, but these behaviors particularly increase in the male during the breeding season. Courting males often engage in mutual grooming with females, and frequently perform a courtship ritual which involves wagging of the tail and trembling of the body. The male then raises a hind leg and sprays urine onto the female. This may serve to familiarize her with his scent and perhaps make her more receptive to his advances in the future. Receptive females may sometimes enurinate males in a similar fashion. Related female degus may nurse each other's young. (Ebensperger and Caiozzi, 2002; Fulk, 1976; Kleiman, 1974; Soto-Gamboa, 2005) In the wild degus tend to breed once per year. The breeding season usually begins in late May (autumn in Chile), and the young are conceived in late winter to early spring (September to October). In wet years, degus may produce second litters. It has been suggested that degus may be induced ovulators, but this has not been established for certain. There is also some evidence that male reproductive organs may be sensitive to changes in photoperiod. The gestation period is 90 days, and litter size is typically 4-6 pups. The young are precocial. They are born with fur and teeth; their eyes are open and they are able to move about the nest on their own. Pups are weaned at 4 to 5 weeks, and become sexually mature between 12 and 16 weeks of age. Degus do not reach adult size until about 6 months of age, however, and they generally live in same-sex social groups until they are about 9 months old and their first breeding season occurs. It has been reported that pups raised in isolation in the laboratory experience severe neural and behavioral abnormalities. (Ebensperger and Hurtado, 2005; Lee, 2004; Woods and Boraker, 1975) Before conception can occur, the male degu must invest considerable energy in the defense of his territory and harem from other males. The female subsequently expends considerable energy in gestation and lactation. The pregnancy is relatively long for a rodent, and the young are born well developed. After birth, both parents protect and provision the pups. Degus nest communally, and groups of related females nurse one another's young. In the laboratory, the female remains close to the pups until two weeks after birth, and males have been observed to huddle with the young during this period without instances of infanticide. In the wild, male degus may spend as much time feeding and huddling with the young as females do. Pups begin to eat solid food at about two weeks of age, and venture out of the burrow at three weeks. Upon weaning at four to six weeks, the pups are able to live independently of the parents and form same-sex social groups until their first breeding season. (Ebensperger and Hurtado, 2005; Fulk, 1976; Lee, 2004; Woods and Boraker, 1975) In laboratory conditions, degus typically live five to eight years. Degus are social and tend to live in groups of one to two males and two to five related females. Females participate in rearing on another's young. Groups maintain territories throughout much of the year. Degus are semi-fossorial, digging extensive communal burrow systems. These burrows are often shared by Bennett's chinchilla rat (Abrocoma bennettii). Degus feed exclusively above ground, however, and have been observed climbing into the low branches of shrubs while foraging. Dustbathing is an important social behavior among degus. Groups repeatedly mark favorite wallows with urine and anal gland secretions. This may help the group identify each other by scent as well as delineating territorial boundaries. Degus are mainly diurnal, and are most active during the morning and evening. (Ebensperger, et al., 2004; Fulk, 1976; Woods and Boraker, 1975) Fulk (1976) estimated that social groups of degus occupy home areas of roughly 200 square meters, and that their density is about 75 degus per hectare. This may be an underestimate, however, due to the trapping methods used. (Fulk, 1976) Degus have well-developed sight, smell, and hearing. They are highly vocal and use various calls to communicate with one another, including alarm calls, mating calls, and communication between parents and young. Vision is very important in avoidance of predators and in foraging. It has been shown that degus are able to see ultraviolet wavelengths, and that their urine reflects in the UV range when fresh. It has therefore been suggested that degus' urine scent marks are also visual cues. These scent marks are also used as dust wallows, allowing members of a social group to identify each other by scent. (Chavez, et al., 2003; Fulk, 1976; Woods and Boraker, 1975) Degus are generalist herbivores. They feed on the leaves, bark, and seeds of shrubs and forbs. Among their favorite foods are the bark of Cestrum palqui and Mimosa cavenia, leaves and bark of Proustia cuneifolia, Atriplex repunda, and Acacia caven, annuals such as Erodium cicutarum when in season, green grasses, and thistle seeds. Degus choose food items that reduce fiber and increase nitrogen and moisture in the diet, and thus prefer young leaves and avoid woodier shrubs. Degus rely on microbial fermentation in their enlarged cecum (they are "hindgut fermenters") to digest their food. They reingest a large percentage of their feces, usually during the night. This allows them to maximize their digestion. Degus store food in the winter, and it has been reported that they occasionally eat meat in old age. (Gutierrez and Bozinovic, 1998; Kenagy, et al., 1999; Veloso and Kenagy, 2005; Woods and Boraker, 1975) Octodon degus is subject to predation by larger mammals such as culpeo foxes (Lycalopex culpaeus), and from the air by raptors such as barn owls (Tyto alba), short-eared owls (Asio flammeus), and black-chested buzzard eagles (Geranoaetus melanoleucus). Degus use vigilance and cover to avoid predators. Their pelage is also counter-shaded and matches the soil color, which reduces visibility to predators. Degus live socially and use alarm calls to warn others of danger. When a predator is spotted, they take cover in shrubby areas and may retreat to the communal burrow. (Ebensperger and Wallem, 2002; Woods and Boraker, 1975) Octodon degus affects the plant community in its habitat by selective browsing. Degus behaviorally reduce the fiber content of their diet, preferrentially eating shrubs such as Adesmia bedwellii, Baccharis paniculata, and Chenopodium petioare, which are less fibrous and less thorny than others. These species have been shown to increase their foliage area upon exclusion of degus. As degus are very common, they are themselves an important food source for their predators. (Gutierrez and Bozinovic, 1998) Degus often live in association with Bennett's chinchilla rats (Abrocoma bennettii). The two species are known to share burrow systems and have even been observed in the same chamber within a burrow. This is believed to be a mutualistic relationship, but it is not well understood. (Fulk, 1976; Woods and Boraker, 1975) Degus are frequently kept as pets, and are used extensively in laboratory research. Because they are largely diurnal, they are useful in research on circadian rhythms, and their intolerance of sugars makes them ideal models for diabetes research. (Lee, 2004) Degus are significant agricultural pests in some areas. They take advantage of cultivated prickly pear cactus, wheat, vineyards, and orchards as abundant food sources, and can do considerable damage. They are also known to host three species of parasites that can infect humans. (Fulk, 1976) Tanya Dewey (editor), Animal Diversity Web. Mary Hejna (author), University of Michigan-Ann Arbor, Phil Myers (editor, instructor), Museum of Zoology, University of Michigan-Ann Arbor. living in the southern part of the New World. In other words, Central and South America. uses sound to communicate living in landscapes dominated by human agriculture. having body symmetry such that the animal can be divided in one plane into two mirror-image halves. Animals with bilateral symmetry have dorsal and ventral sides, as well as anterior and posterior ends. Synapomorphy of the Bilateria. Found in coastal areas between 30 and 40 degrees latitude, in areas with a Mediterranean climate. Vegetation is dominated by stands of dense, spiny shrubs with tough (hard or waxy) evergreen leaves. May be maintained by periodic fire. In South America it includes the scrub ecotone between forest and paramo. uses smells or other chemicals to communicate helpers provide assistance in raising young that are not their own an animal that mainly eats the dung of other animals active at dawn and dusk having markings, coloration, shapes, or other features that cause an animal to be camouflaged in its natural environment; being difficult to see or otherwise detect. animals that use metabolically generated heat to regulate body temperature independently of ambient temperature. Endothermy is a synapomorphy of the Mammalia, although it may have arisen in a (now extinct) synapsid ancestor; the fossil record does not distinguish these possibilities. Convergent in birds. an animal that mainly eats leaves. Referring to a burrowing life-style or behavior, specialized for digging or burrowing. an animal that mainly eats seeds An animal that eats mainly plants or parts of plants. offspring are produced in more than one group (litters, clutches, etc.) and across multiple seasons (or other periods hospitable to reproduction). Iteroparous animals must, by definition, survive over multiple seasons (or periodic condition changes). having the capacity to move from one place to another. the area in which the animal is naturally found, the region in which it is endemic. the business of buying and selling animals for people to keep in their homes as pets. having more than one female as a mate at one time specialized for leaping or bounding locomotion; jumps or hops. communicates by producing scents from special gland(s) and placing them on a surface whether others can smell or taste them breeding is confined to a particular season remains in the same area reproduction that includes combining the genetic contribution of two individuals, a male and a female associates with others of its species; forms social groups. places a food item in a special place to be eaten later. Also called "hoarding" uses touch to communicate that region of the Earth between 23.5 degrees North and 60 degrees North (between the Tropic of Cancer and the Arctic Circle) and between 23.5 degrees South and 60 degrees South (between the Tropic of Capricorn and the Antarctic Circle). Living on the ground. defends an area within the home range, occupied by a single animals or group of animals of the same species and held through overt defense, display, or advertisement uses sight to communicate reproduction in which fertilization and development take place within the female body and the developing embryo derives nourishment from the female. young are relatively well-developed when born Chavez, A., F. Bozinovic, L. Peichl, A. Palacios. 2003. Retinal spectral sensitivity, fur coloration, and urine reflectance in the genus Octodon (Rodentia): implications for visual ecology. Investigative Opthalmology & Visual Science, 44/5: 2290-2296. Contreras, L., J. Torres-Mura, J. Yanez. 1987. Biogeography of Octodontid rodents: An eco-evolutionary hypothesis. Fieldiana: Zoology, New Series, 39: 401-411. Ebensperger, L., F. Bozinovic. 2000. Energetics and burrowing behaviour in the semifossorial degu Octadon degus (Rodentia: Octodontidae). Journal of Zoology, 252: 179-186. Ebensperger, L., A. Caiozzi. 2002. Male degus, Octodon degus, modify their dustbathing behavior in response to social familiarity of previous dustbathing marks. Revista Chilena de Historia Natural, 75: 157-163. Ebensperger, L., M. Hurtado. 2005. On the relationship between herbaceous cover and vigilance activity of degus (Octodon degus). Ethology, 111/6: 593-608. Ebensperger, L., M. Hurtado. 2005. Seasonal changes in the time budget of degus, Octadon degus.. Behaviour, 142: 91-112. Ebensperger, L., M. Hurtado, M. Soto-Gamboa, E. Lacey, A. Chang. 2004. Communal nesting and kinship in degus (Octodon degus). Naturwissenschaften, 91: 391-395. Ebensperger, L., P. Wallem. 2002. Grouping increases the ability of the social rodent, Octodon degus, to detect predators when using exposed microhabitats. Oikos, 98: 491-497. Fulk, G. 1976. Notes on the activity, reproduction, and social behavior of Octodon degus. Journal of Mammalogy, 57/3: 495-505. Gutierrez, J., F. Bozinovic. 1998. Diet selection in captivity by a generalist herbivorous rodent (Octodon degus) from the Chilean coastal desert. Journal of Arid Environments, 39: 601-607. Kenagy, G., R. Nespolo, R. Vasquez, F. Bozinovic. 2002. Daily and seasonal limits of time and temperature to activity of degus. Revista Chilena de Historia Natural, 75: 567-581. Kenagy, G., C. Veloso, F. Bozinovic. 1999. Daily rhythms of food intake and feces reingestion in the degu, an herbivorous Chilean rodent: optimizing digestion through coprophagy. Physiological and Biochemical Zoology, 72/1: 78-86. Kleiman, D. 1974. Patterns of behaviour in hystricomorph rodents. Symposium of the Zoological Society (London), 34: 171-209. Lee, T. 2004. Octodon degus: A diurnal, social, and long-lived rodent. ILAR Journal, 45/1: 14-24. Soto-Gamboa, M., M. Villalon, F. Bozinovic. 2005. Social cues and hormone levels in male Octadon degus (Rodentia): a field test of the Challange Hypothesis. Hormones and Behavior, 47/3: 311-318. Soto-Gamboa, M. 2005. Free and total testosterone levels in field males of Octodon degus (Rodentia, Octodontidae): accuracy of the hormonal regulation of behavior. Revista Chilena de Historia Natural, 78/2: 229-238. Tokimoto, N., K. Okanoya. 2004. Spontaneous construction of "Chines boxes" by Degus (Octodon degus): A rudiment of recursive intelligence?. Japanese Psychological Research, 46/3: 255-261. Veloso, C., G. Kenagy. 2005. Temporal dynamics of milk composition of the precocial caviomorph Octodon degus (Rodentia : Octodontidae). Revista Chilena de Historia Natural, 78/2: 247-252. Woods, C., D. Boraker. 1975. Octodon degus. Mammalian Species, 67: 1-5.
Around the South Jamaica housing projects in Queens, young men with pit bulls guard street corners and rap music blares from car stereos. But one house, on 110th Avenue, seems to openly defy its gritty surroundings. Its owner, Milford Graves, has covered it with an ornate mosaic of stones, reflective metal and hunks of discarded marble, arranged in cheery patterns. The yard is a lush garden, dense with citrus trees, herbs and exotic plants. Continue reading the main story In 1967, Mr. Graves was honored in a Down Beat magazine critics' poll as the year's bright new talent. He had offers of lucrative gigs from artists like Miles Davis and the South African singer Miriam Makeba. In his basement, he converted the heartbeats to a higher register and dissected them. Behind the basic binary thum-THUMP beat, he heard other rhythms -- more spontaneous and complex patterns in less-regular time intervals -- akin to a drummer using his four limbs independently. "A lot of it was like free jazz," Mr. Graves said one day last week in his basement. "There were rhythms I had only heard in Cuban and Nigerian music." He demonstrated by thumping a steady bum-BUM rhythm on a conga with his right hand, while delivering with his left a series of unconnected rhythms on an hourglass-shaped talking drum. Mr. Graves created computer programs to analyze the heart's rhythms and pitches, which are caused by muscle and valve movement. The pitches correspond to actual notes on the Western musical scale. Raised several octaves, the cardiac sounds became rather melodic. "When I hooked up to the four chambers of the heart, it sounded like four-part harmony," Mr. Graves said. He began composing with the sounds -- both by transcribing heartbeat melodies and by using recorded fragments. He also realized he could help detect heart problems, maybe even cure them. "A healthy heart has strong, supple walls, so the sound usually has a nice flow," he said. "You hear it and say, 'Ah, now that's hip.' But an unhealthy heart has stiff and brittle muscles. There's less compliance, and sounds can come out up to three octaves higher than normal. "You can pinpoint things by the melody. You can hear something and say, 'Ah, sounds like a problem in the right atrium."' In 2000, Mr. Graves received a grant from the John Simon Guggenheim Memorial Foundation, which he said gave him money to buy essential equipment. Dr. Baruch Krauss, who teaches pediatrics at Harvard Medical School and is an emergency physician at Boston Children's Hospital, said the medical establishment has only recently begun to appreciate the rhythmic and tonal complexities of the heartbeat and speak about it in terms of syncopation and polyrhythms. "This is what a Renaissance man looks like today," said Dr. Krauss, who studied acupuncture with Mr. Graves and follows his research. "To see this guy tinkering with stuff in a basement in Queens, you wonder how it could be legitimate. But Milford is right on the cutting edge of this stuff. He brings to it what doctors can't, because he approaches it as a musician." Dr. Ram Jadonath, director of electrophysiology at North Shore University Hospital in Manhasset, N.Y., said Mr. Graves's theories sounded plausible but should not replace a standard medical assessment from a doctor. "The heartbeat is a form of musical rhythm, and if you have a musical ear, you can hear heart problems a lot easier," he said. "Many heart rhythm disturbances are stress-related, and you have cells misfiring. It is possible to redirect or retrain them with musical therapy. They do respond to suggestion. That's the area where his biofeedback could correct those type of problems." Mr. Graves said he brings unusual strengths to his medical work. "To hear if a melody sounds right or not, you've got to look at it as an artist, not a doctor," he said. "If you're trying to listen to a musical sound with no musical ability, you're not feeling it, man." Mr. Graves claims he can help a flawed heartbeat through biofeedback. He creates what he calls a "corrected heartbeat" using an algorhythmic formula, or by old-fashioned composing, and then feeds it back to the patient, whose heart is then trained to adopt the healthy beat. The patient can listen to a recording of the corrected heartbeat, or it can be imparted directly through a speaker that vibrates a needle stuck into acupuncture points. "If they don't want that," he added, "I can give them a CD." Last week, Dennis Thomas, 49, visited Mr. Graves in his basement complaining of severe chest congestion. Mr. Thomas said his doctor had diagnosed bronchial asthma and given him medication that had not been effective. Mr. Graves said the problem might be related to Mr. Thomas's heart and recorded his heartbeat. With the help of a computer program, Mr. Graves tinkered with the rhythm and amplitude and then attempted to stimulate Mr. Thomas's heart by playing the "corrected" beat both through a speaker and through a wire stuck into an acupuncture point in his wrist. "I gave him a double shot," Mr. Graves explained. After 10 minutes of treatment, Mr. Thomas's heart rate had risen about 10 beats per minute, according to a monitor. Mr. Thomas, a city bus driver from Jamaica who used to study martial arts with Mr. Graves, said that he felt improvement afterward. "I started breathing easier and felt more relaxed," he said. In addition to his medical work, Mr. Graves analyzes the heartbeats of his music students, hoping to help them play deeper and more personal music. The idea, he said, is to find their most prevalent rhythms and pitches and incorporate them into their playing. The composer and saxophonist John Zorn called Mr. Graves "basically a 20th-century shaman." "He's taken traditional drum technique so far that there's no further place to go, so he's going to the source, his heart," Mr. Zorn said. "This culture is not equipped to appreciate someone like Milford," he said. "In Korea, he'd be a national treasure. Here, he's just some weird guy who lives in Queens." Continue reading the main story
Discover the cosmos! Each day a different image or photograph of our fascinating universe is featured, along with a brief explanation written by a professional astronomer. 2010 August 12 Explanation: Each August, as planet Earth swings through dust trailing along the orbit of periodic comet Swift-Tuttle, skygazers can enjoy the Perseid Meteor Shower. The shower should build to its peak now, best seen from later tonight after moonset, until dawn tomorrow morning when Earth moves through the denser part of the wide dust trail. But shower meteors have been spotted for many days, like this bright Perseid streaking through skies near Lake Balaton, Hungary on August 8. In the foreground is the region's Church of St. Andrew ruin, with bright Jupiter dominating the sky to its right. Two galaxies lie in the background of the wide-angle, 3 frame panorama; our own Milky Way's luminous arc, and the faint smudge of the more distant Andromeda Galaxy just above the ruin's leftmost wall. If you watch for Perseid meteors tonight, be sure and check out the early evening sky show too, featuring bright planets and a young crescent Moon near the western horizon after sunset. Authors & editors: Jerry Bonnell (UMCP) NASA Official: Phillip Newman Specific rights apply. A service of: ASD at NASA / GSFC & Michigan Tech. U.
// 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
//===- 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 &registry) 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); }
Environment in emerging and transition economies EaP GREEN: Reform of environmentally harmful subsidies Reforming environmentally harmful subsidies (EHS) is a fundamental element of green growth strategies and confers a range of benefits to countries that undertale such reforms. These include, among others, reducing the use of resource intensive inputs (e.g. energy) and subsequent decrease in pollution levels, fixing market distrortions by making resource prices reflect resource value, and polluters pay for their pollution; releasing and/or relallocating public funding to other areas, such as education, energy saving or reducing debt. Determining the environmental impact of different subsidies is often complicated because specific policy measures do not take place in isolation, but within a broad and evolving socio-economic and technological context. Due to very patchy data and information but also because of the lack of a harmonised methodology for recording and reporting subsidies, identifying and calculating the size of EHS schemes is not easy and will require the concerted efforts of many different parties in a given government. Objectives and activities 1. Develop policy guidance tools to prepare EHS reform action plans. The guidance will be based on tools and methods for identifying, measuring and evaluating subsidies that are environmentally-harmful and economically wasteful. The experience with applying these analytical tools in preparing EHS reform plans, including from the EU countries, will be presented in several regional meetings with the participation of key stakeholders from the EaP countries. 2. Implement country projects. The OECD will work in three countries to develop action plans to reform EHS in selected sectors (such as energy, agriculture or water). Each project will aim at facilitating a national-level policy dialogue to generate political support for the adoption and implementation of the actions plan proposed for the country. 3. Build capacity and political support in other EaP countries to develop action plans to reform EHS. Organisation of stakeholder meetings in the EaP countries other than those hosting the pilot projects to disseminate policy recommendations and lessons learned from other countries in the region. DID YOU KNOW? ....that there is some evidence that fossil fuel consumer subsidies in the EaP countries might be large. The International Energy Agency estimated that, in 2011, fossil fuel subsidies for consumers (oil, coal, gas, electricity) totalled about USD 2 billion in Azerbaijan (about 3% of GDP), about USD 6 billion (3.3% of GDP) in Kazakhstan and about USD 9 billion in Ukraine (about 6% of its GDP).
#ifndef __ELASTOS_IMICROSERVICE_H__ #define __ELASTOS_IMICROSERVICE_H__ #include <string> #include <vector> #include <memory> namespace elastos { class IMicroService { public: enum OperationType { OperationType_Encrypt = 0, OperationType_Decrypt, OperationType_Sign, OperationType_Verify }; class DataHandler { public: virtual std::shared_ptr<std::vector<uint8_t>> EncryptData(const std::vector<uint8_t>& data) = 0; virtual std::shared_ptr<std::vector<uint8_t>> DecryptData(const std::vector<uint8_t>& cipherData) = 0; virtual std::shared_ptr<std::vector<uint8_t>> SignData(const std::vector<uint8_t>& data) = 0; virtual bool VerifyData(const std::vector<uint8_t>& data, const std::vector<uint8_t>& signedData) = 0; }; public: virtual int Start() = 0; virtual int Stop() = 0; virtual int HandleMessage(const std::string& did, const std::string& msg) = 0; virtual std::shared_ptr<std::vector<uint8_t>> HandleData(int type, const std::vector<uint8_t>& data) = 0; virtual void SetDataHandler(std::shared_ptr<DataHandler>& handler) = 0; }; } #endif //__ELASTOS_IMICROSERVICE_H__
1. Why is extremism an issue in prisons? Extremist groups often pose special security risks in prisons. They may encourage the overthrow of the government, and prison officials can be targeted as agents of "illegal" government authority. Further, their literature often encourages ethnic hatred, promoting a violent and racially charged prison atmosphere. Since the 1980s, white supremacist organizations have spread throughout the American prison system, beginning with the growth of Aryan Brotherhood.1 Aryan Nations, although not permitting inmates to become members, has engaged in "prison outreach" since 1979. In 1987, it began publishing a "prison outreach newsletter" called The Way to facilitate recruitment. Aryan Nations also disseminates its literature and letters to inmates. The World Church of the Creator and some Identity Church groups engage in similar outreach activity, as do other racist groups, such as Nation of Islam. The situation is further complicated by the fact that nonideological criminal prison gangs are often organized based on race, which increases racial polarization. Imprisoned extremists also pose a security threat by continuing their activities while incarcerated. They recruit inmates, and teach other inmates extremist tactics. Some imprisoned extremists also have attempted to continue to influence adherents outside of prison by, for instance, publishing newsletters from the prison to maintain their outside following. Prison officials have responded in various ways, reflecting the fact that each state has its own prison system (as do cities, counties and the federal government), and that prisons have varying populations. At times, prison officials have tried to limit access to extremist literature, and these responses have occasionally given rise to litigation because they potentially impinge upon inmates' First Amendment rights. The questions are especially complicated when the censored material comes from a group that claims to be religious. 1 Aryan Brotherhood, at one time associated with Aryan Nations, began as a virulent racist and anti-Semitic prison gang, and has since developed into a crime gang associated with extortion, drug operations and prison violence. 2. Do inmates have the same First Amendment rights as everybody else? The United States Supreme Court has said that "prison walls do not form a barrier separating prison inmates from the protections of the Constitution." Nevertheless, inmates' First Amendment rights are less extensive than other citizens' and their rights can be limited due to security or other penological concerns. Because of the particular challenges administrators face running prisons, the Supreme Court has acknowledged there is a compelling government interest which warrants limiting prisoners' rights. Courts have been deferential to prison officials' assessments of security threats, and sensitive to their related regulatory decisions, even if such decisions impact inmates' First Amendment rights. A prison regulation that impinges on an inmate's constitutional rights will be upheld in court if that regulation is reasonably related to legitimate penological objectives. This means that, generally, prison officials can ban extremist materials from prisons because of concerns that the distribution of such material will undermine prison security. Extremist books, leaflets, and magazines have been forbidden to prisoners on this basis. Such material has not been allowed through the mail and has not been kept in the prison library. However, prisons have less discretion to limit inmates' religious practices than other First Amendment rights due to a new federal law. Because of the Religious Land Use and Institutionalized Persons Act (RLUIPA), prison officials' discretion in limiting access to extremist material may depend in part on whether such material is related to an inmate's religious exercise. Therefore, prison regulations that affect religious exercise, including access to religious literature, will be reviewed carefully if challenged in court. 3. What legal standard is used to determine the constitutionality of prison regulations? The Supreme Court announced the standard under which it would review the constitutionality of prison regulations in Turner v. Safley, a case involving a challenge to a complete prohibition on inmate marriage. As noted earlier, a prison regulation is constitutional if it is reasonably related to legitimate penological objectives. Under this standard, courts have upheld regulations based on the consideration of certain factors: - Is there a valid, rational connection between the prison regulation and the legitimate governmental interest put forward to justify it? - Are there alternative means of exercising the assert- ed right that remain open to inmates? - How great a negative impact will accommodating the inmates' rights have on guards, other inmates,a nd on the allocation of prison resources? Courts will consider the existence of obvious and easy alternatives to a challenged regulation as evidence of a regulation's arbitrariness. 4. Is the same legal standard used to determine the constitutionality of prison regulations that implicate an inmate's right to free exercise of religion? No, the same standard is not applicable to determining the constitutionality of prison regulations alleged to violate inmates' free exercise rights. The constitutionality of such regulations is determined under the more stringent standard set forth in RLUIPA. RLUIPA says that the government cannot impose a substantial burden on the religious exercise of an inmate, even if the inmate's religious exercise is being limited by a generally applicable rule. However, an inmate's religious practices can be limited if the prison official demonstrates that the regulations in question (i) further a compelling interest and (ii) the same interest cannot be served in a manner that is less restrictive of the inmate's free exercise rights. Since RLUIPA was enacted in September 2000, it has not yet been interpreted by the courts. Therefore, how this statute will impact prison regulations that affect inmates' religious exercise remains unclear. 5. How should prison officials evaluate whether particular material can be withheld from inmates? Generally, the First Amendment does not allow speech to be censored by the government because of the content of that speech. The government can only limit the time, place, and manner of speech. However, because inmates have more limited First Amendment rights than other citizens, some content-based discrimination is allowed for security reasons. For example, the United States Court of Appeals for the 10th Circuit upheld a prison official's decision to withhold entire issues of the magazine, Muhammad Speaks, because certain articles in the magazine created a danger of violence by advocating racial, religious, or national hatred. This decision was prior to the passage of RLUIPA, and therefore the Court's analysis might be somewhat different today. Under current law, if having the entire magazine withheld was determined to be a substantial burden on inmates' free exercise rights, the Court might require that the offending material be removed rather than the entire issue being withheld. Regulations that exclude publications from a prison because of security concerns have been found constitutional when the regulations have required individualized review of any material before it is banned, notification to inmates that the material has been denied, and the possibility of review of such decisions. Courts have tended to find prison regulations that ban all literature from particular groups unconstitutional. However, the determination of the constitutionality of a given regulation or the implementation of the regulation has tended to be very fact-specific. Courts look not only at the regulation at issue but also consider the nature of the prison (high, medium, or low security) and the particular administrative challenges faced by the prison (such as crowding and quantity of incoming mail) in determining reasonableness, or the practical existence of less restrictive alternative measures. 6. Can prison officials apply the same restrictions to outgoing prison material? The Supreme Court does not allow content regulation with respect to outgoing mail from inmates. While outgoing mail can be searched for contraband,2 content regulation of outgoing mail is also more restricted because it implicates the First Amendment rights of non-prisoner addressees.3 In addition, outgoing material does not pose a threat to internal prison security; therefore content limitations have been considered less urgent. However, regulations can limit the content of outgoing mail categorically. For example, escape plans, threats, running a business, and blackmail are categories that have been disallowed. Therefore, correspondence from prisoners to extremist groups cannot be banned outright because of its content. However, inmates can be prevented from distributing a newsletter from prison when doing so constitutes running a business. 2 Special rules exist with respect to attorney-client correspondence or mail that implicates an inmate's right to access the courts that are beyond the scope of this discussion. 3 However, prison officials can forbid all correspondence between incarcerated individuals. 7. Can extremist "missionaries" be prevented from visiting prisons? Prison officials can ban categories of prison visitors, such as former inmates or visitors who have previously broken visiting rules. An extremist "missionary" can be barred from a prison because of generally applicable rules. In addition, prisons can create procedures for requesting visiting ministers, and impose conditions on the selection of the ministers, such as sponsorship by an outside religious organization. Prison officials can also exclude prison "missionaries" if they are advocating violence or otherwise fomenting prison unrest by encouraging racial tension. However, under RLUIPA, the prison would have to show that any restrictions on visiting clergy are the least restrictive means of achieving its end. Prison officials do not have a responsibility to hire a minister for each religious denomination represented in the prison population. However, if visiting ministers of one denomination are compensated, visiting ministers of other denominations must be equally compensated. Security limitations can be placed on inmate-led prayer or services, but again, under RLUIPA, the prison would have to show that any restrictions on such gatherings is the least restrictive means of achieving its end. For example, it is more likely that the prison could limit the frequency of such meetings, the number of attendees and require supervision than that such gatherings could be banned outright. 8. Under what circumstances must prisons accommodate prisoners' religious dietary requirements? Accommodating religiously based dietary rules has become an issue when dealing with extremists because incidents have raised concern that extremists "adopt" religious practices that are not based on sincere beliefs in order to obtain special privileges, such as specialized diets. Generally, if an inmate's request for a special diet is because of a sincerely held belief and religious in nature, the inmate has a constitutionally protected interest. Under RLUIPA, a request for a special religious diet can only be refused based on a compelling prison interest and if it is the least restrictive means possible for the prison protecting that interest. Prisons may offer more limited food selection to prisoners with religious dietary limitations, such as providing only cold kosher meals rather than hot food. In the past, when determining whether a prison was required to provided a special diet for a prisoner, courts have considered whether the dietary restrictions were central to the prisoner's religious observance. Under RLUIPA, such a determination would probably not be relevant. The threshold question in evaluating the prison's obligation to accommodate a request would still be whether the inmate's dietary request arose out of sincerely held beliefs that were religious in nature.
Be prepared with our Hurricane Guide, forecasts and latest storm news Henry M: The Day One Man's Memory Died The Hartford Courant Henry M. was awake as the surgeon inserted a metal straw deep within his brain and suctioned out a piece of tissue the length of an index finger. The surgeon, William Beecher Scoville of West Hartford, talked to the 27-year-old Hartford man during the experimental operation, which he hoped would end his patient's epileptic seizures. But a reduction in seizures came at a catastrophic cost: Henry no longer could make new memories. From that summer day in 1953, Henry M. never again retained a conscious recollection of people, places or things he encountered. His intelligence remained intact, but his memory turned into a sort of Etch A Sketch, perpetually erased seconds after he turns his attention elsewhere. Today, Henry M. is by most accounts a genial old man who lives in a Hartford area nursing home, unable to recognize aides who have cared for him for years. His most recent memories date to when Eisenhower was president. His full name and residence are secrets, jealously guarded by a few neuroscientists who have dubbed him H.M. and built their careers studying his profound loss. The precisely carved hole in Henry's brain has turned out to be a treasure trove of information about the multiple facets of memory. Over the decades, dozens of scientists have made a pilgrimage to meet Henry, seeking to mine meaning from the man who lost his ability to hold a half-century of his personal history. Henry is unaware that he has become one of the most famous subjects in the history of psychology -- a textbook example of the importance of memory in the formation of identity -- or that his story still spurs questions about medical ethics and patients' rights. Dr. James Duffy, an associate professor of psychiatry at the University of Connecticut and director of psychiatric consultation services at Hartford Hospital, says he has not met Henry but suspects the man has become an afterthought in science's relentless pursuit of knowledge. ``Scientists are good at slicing off pieces of patients and manipulating them under a microscope,'' Duffy said, ``but we don't want to take responsibility for their well-being.'' Wiped Away What the world knows of Henry M. is limited mostly to lifeless prose of psychology textbooks and scientific papers, which devote many more pages to the incisions that removed most of Henry's medial temporal lobe than to his likes and dislikes, his hopes and dreams. Scientists who have worked with Henry say his memories of childhood, adolescence and young adulthood -- the only conscious memories he has -- have a brittle, worn quality to them. For Henry, the people he talks with are always strangers. And his stories are invariably the same, lacking the sinew, blood and muscle with which memory infuses experience. ``The stories he tells are incredibly similar each time he tells them,'' said John Gabrieli, a neuroscientist at Stanford University who studied Henry extensively during the 1980s. ``There is a bland, stereotyped quality to his conversations. What are you going to say when everyone is a stranger?'' Henry is a big man who has become bigger and softer after years of a sedentary lifestyle. He likes to eat. He is going bald and wears glasses. He still takes medication to control epileptic seizures, which were reduced but not eliminated by the operation. Today, he has osteoporosis and recently has had to depend on a wheelchair to get around. He will need cataract surgery soon. Apparently, Henry was always good-natured, which makes it difficult to determine just how much his gentle, agreeable demeanor is the result of his operation. Henry seldom expresses any interest in the topic of sex, but he also had no serious girlfriends before the operation. So scientists don't know if Henry's sex drive, like his memory, was a casualty of the surgery. There is little biographical information available on Henry and much of it he has supplied himself. Henry M.'s father was an electrician who migrated from Louisiana in the 1920s to Hartford, where Henry was born in 1926. The family attended church in Hartford and moved to East Hartford by the time Henry was a teenager. Later, they moved to a more rural part of Hartford County. Henry remembers roller-skating. He remembers shooting his father's gun in the woods. But unless he is coached, he doesn't remember that his parents are dead. Unofficial Guardian The person who knows as much about Henry as anyone is Suzanne Corkin, a neuroscientist at the Massachusetts Institute of Technology who has worked with Henry since 1962. Corkin acts as a sort of unofficial guardian of Henry's interests, along with Montreal scientist Brenda Milner. It was Milner who, with Scoville, in 1957 co-authored the first scientific paper describing the extent of Henry's memory loss. Corkin and Milner decided that instead of conducting tests on Henry in Montreal, it would be easier to work with Henry at MIT, closer to his Hartford home. Corkin's connection to Henry's case actually reaches back into her childhood. She was Scoville's neighbor growing up on North Steele Road in West Hartford and remains friends with the surgeon's daughter. Corkin said she and Milner decided long ago not to allow the media to interview Henry and actively discouraged efforts to write about him. She said that it would be unethical to discuss his medical records and that there are few details of his life before the surgery. Misinformation about Henry is rampant, including reports that he may suffer from depression, she added. But other scientific researchers say that when it comes to controlling information about Henry, Corkin is as zealous with them as she is with reporters. Endel Tulving, a memory researcher and retired professor of psychology at the University of Toronto, said Corkin refused to allow him to tape-record an interview with Henry. ``It's just silliness,'' said Tulving. He said he has worked with a Canadian amnesiac with a similar devastating memory loss who has been interviewed on several television shows. Corkin said more than 100 scientists have worked with Henry during the past 50 years. One fact is almost universally reported about Henry. At the age of 9, Henry was knocked unconscious after he was hit by a bicyclist. Soon after, he experienced his first minor epileptic seizures. On his 16th birthday, he suffered a grand mal seizure. James Bond In Scrubs Henry was 27 -- and having as many as 10 minor seizures a day and at least one major seizure a week -- when his case came to the attention of Dr. William Beecher Scoville, a flamboyant descendant of the illustrious Connecticut family that produced ``Uncle Tom's Cabin'' author Harriet Beecher Stowe. Scoville was a fearless -- some say reckless -- pioneer in developing surgical remedies for a variety of intractable psychological conditions. He was best known internationally for his technical improvements in the performance of lobotomies, which then were regularly conducted at Hartford Hospital and the Institute of Living, one of the world's top centers for the treatment of mental illness. He received many awards for his work. He founded an international society of brain surgeons that still gives out an annual award in his name. The University of Connecticut Health Center has an endowed chair that bears his name. No one who met Scoville forgot him. While Henry M. is genial, meek and eager to please, Scoville was a sort of James Bond in scrubs who loved fast, expensive cars and motorcycles, a demanding dynamo in the operating room, brilliant at his craft. ``Bill drove fast, lived hard and operated where angels feared to tread,'' said Dr. David Crombie, former chief of surgery at Hartford Hospital who met Scoville in the early 1960s as an intern at the hospital and became friends with his son. Scoville was an early advocate of helmets for motorcyclists, but never wore one himself, despite riding at speeds that terrified friends and colleagues, Crombie recalled. ``He said you had to wear a helmet -- unless you were keenly aware,'' Crombie said. ``He had a sense of invincibility about him.'' Scoville typically operated on people with intractable schizophrenia or severe depression. But in 1953, Scoville thought he might be able to alleviate Henry's epilepsy. Epilepsy can originate within the medial temporal lobe, a structure that extends on both sides of the brain roughly under the temples. Scoville decided to remove a greater area of brain tissue from Henry than had been removed from patients who had undergone similar surgeries. A half-century ago, doctors did not need to get a hospital's permission to try innovative operations. They were under no obligation to conduct trials before they tried new procedures on a patient. Henry and other patients did not have to sign informed-consent papers saying they knew the risks involved, although it is unlikely Henry or his working-class parents would have questioned the advice of a famous surgeon. ``In those days, the doctor's word was God,'' said Al Herzog, a psychiatrist and vice president of medical affairs at Hartford Hospital. ``In an odd way, people like Scoville helped create the ethical standards in use today. By pushing the boundaries of surgical practice, Scoville and others led hospitals to establish institutional review boards, patient protocols, things like that.'' A `Successful' Operation Late in the summer of 1953, either at Hartford Hospital or at the nearby Institute of Living in the single operating room where lobotomies were performed, Scoville took out most of Henry's medial temporal lobe, including all or parts of the hippocampus and amygdala. Scoville originally dubbed the operation a success, although Henry couldn't remember the way to the bathroom or the names of the nurses who cared for him. A few years later in a research paper, Scoville would strongly urge surgeons not to duplicate his ``experimental'' operation because of its devastating effects on Henry's memory. ``It bothered him. You could see it in his eyes,'' recalls Dr. Robert Correll, director of psychology testing services at Hartford Hospital who came to Connecticut from Iowa University in 1958 to try with Scoville to duplicate the effects of the operation in monkeys. ``Bill's goal was to be perfect. He didn't make mistakes.'' In the decades that followed, Henry often told researchers that as a child he had wanted to be a brain surgeon. Henry seems to mingle the recollection of his childhood dream and his own operation, the last memory he would ever preserve, in a sort of never-ending loop. During one interview, Henry told a researcher that he nixed the idea of becoming a surgeon because he wore glasses, ``and you could make the wrong movement then ... and that person could be dead, or paralyzed.'' He was then asked if he remembered his own operation. ``Well, I think I was, ah, well, I'm having an argument with myself right away. I'm the third or fourth person who had it, and I think that they, well, possibly didn't make the right movement at the right time, themselves. But they learned something.'' They did, indeed, the researcher told Henry, who then again brought up Henry's childhood. ``A funny part, I always thought of being a brain surgeon myself. ... And then I said no to myself. ... An attendant might move your glasses over and you would make the wrong movement.'' Do you remember who the surgeon was who did your operation, the researcher asked. ``No, I don't.'' ``Sc--,'' the researcher hinted. ``Scoville,'' Henry said. Understanding The Mind Scoville was killed in 1984, at the age of 78, when he backed up his car on the highway to get to an exit he had missed. Renowned in his time for innovative improvements to a surgical procedure now held in disrepute, the confident, perfectionist surgeon is best remembered for obliterating the memory of a young working-class Hartford man. Science's understanding of the brain changed dramatically after Scoville and Milner published their paper in 1957 describing the effects of the operation. It had been impossible for scientists to determine how specific areas of the brain created the richness of the human mind -- most often understood in abstract terms, such as Sigmund Freud's id, ego and superego. ``Freud was stuck; he couldn't make those connections,'' Herzog said. ``But with cases like H.M., the connections became more obvious. You can't run away from the importance of H.M.'' One of the first lessons Henry taught scientists was that intelligence and memory are separate entities. Henry would have flunked out of any class in which he had to learn new information because of his inability to recall new facts. Yet his IQ remained slightly above average and his ability to solve problems was unaffected by the operation. ``We now know from 30 years of animal studies that it was the most devastating surgical resection you can possibly make, but it also stopped at the border of all the important areas of the brain associated with intelligence,'' Gabrieli said. And because Henry could retain memories for very short periods of time, it became clear that different structures of the brain perform different functions in the storage and retrieval of memories. The brain structures removed by Scoville turned out to be crucial in converting experience into long-term memories, but not in storing them. ``Until H.M., memory was viewed as essentially a unitary faculty,'' said Larry Squire, a neuroscientist at the University of California at San Diego and a leading memory researcher. Scientists knew during the 1950s, for instance, that motor and muscle skill memories were processed differently than, say, how we recall that Bismarck is the capital of North Dakota. ``But that proved to be tip of the iceberg,'' Squire said. One of the major hurdles that confronted scientists studying Henry is that the medial temporal lobe contains several brain structures. In the decades since Scoville operated, scientists such as Squire have worked with animals to try to tease out the specific function of each of these individual structures. The discipline known as cognitive neuroscience emerged to describe how various parts of the brain cooperate and allow humans to accomplish complex tasks such as memorization. ``He is the most dramatic example of a patient who tragically became an experiment of nature,'' said Eric Kandel, Nobel laureate and professor of physiology and psychology at Columbia University. ``That single case enlightened a whole body of knowledge.'' Learning Vs. Remembering Scientists became so infatuated with Henry, Tulving said, that they missed evidence that other areas of the brain also contribute to memory. ``I think H.M. was a bad thing for our science. Everyone got mesmerized by H.M.,'' Tulving said. ``The whole world revolved around one case, and other cases were not followed up.'' Experiments with Henry and other amnesiacs and, more recently, various brain-imaging studies have revealed that memory is a multilayered set of processes. In some cases, such as in our recall of emotionally charged events, those processes can be at work without our conscious awareness. In one early study, Henry showed that he could learn new skills, even though he had no conscious recollection of having previously performed the task. Henry got better at copying shapes he viewed through a mirror, even though he told researchers he had never done it before. Gabrieli's research showed Henry can do the same thing with some word tasks. Gabrieli provided Henry with a list of words such as tangerine, apple and bazooka. When asked minutes later, Henry could not remember any of the words on the list. ``But when you ask him, `Can you name a weapon?' he will say, `Bazooka.' And then he says, `Why, that's an odd weapon. I wonder why I picked that one?''' Gabrieli said. Such studies have shown that different types of memory are compartmentalized in different areas -- and also that the brain has the flexibility to compensate for some deficits. For instance, Lawrence Weiskrantz of the experimental psychology department at Oxford University has studied a phenomenon he calls ``blindsight.'' Weiskrantz, who coincidentally was working at Hartford Hospital on his thesis when Scoville operated on Henry, worked with subjects who are blind because of damage in their brain. Despite the damage to their visual cortex, they can ``see'' objects. When asked to grab for flashing bars projected onto a screen, the subjects protested they could not see the bars. But, when asked to ``guess,'' they reached toward the flashing bars with great accuracy. Henry knows nothing of his legacy. Time essentially stopped for him 50 years ago. His last conscious memories are of the years before 1953, although his image in the mirror and other evidence seem to convince him that time has passed which he can't account for. Asked where he lives, Henry often gives the address of a house where he lived before the operation. Pressed to recall if he had met a visitor before, he might guess he or she was someone he knew in his youth. ``He thinks we went to high school together,'' Corkin said. Since 1980, Henry has lived in a nursing home, where he likes to do crossword puzzles. While doctors have treated Henry for a variety of ailments, Corkin said, ``there is no treatment for memory impairment.'' As Kandel said: ``It's hard for us to conceive what he really experiences.'' Waking From A Dream Henry used to travel three times a year to MIT, where scientists conducted experiments on him. But Henry has become frail enough in recent years that the scientists now come to him, Corkin said. When Henry is asked whether he is willing to participate in such studies, he invariably agrees, always saying other people may be helped by such knowledge. Where does that belief come from? ``That's puzzled me, too,'' Gabrieli said. Henry has no way of knowing that the research of the past 50 years has helped people. And such an idea couldn't be planted in his mind because he lacks the parts of his brain necessary to store and retrieve such a suggestion. Gabrieli speculates that Henry might be reaching back to one of his last memories, when Scoville or another doctor might have told him that other epileptics could benefit from the lessons learned from his surgery. So, again and again for the past half-century, Henry has agreed to be the subject of experiments, just as he did before surgery robbed him of his memory. Corkin offers a different explanation: ``I think he was just well brought up.'' Today, Henry is still the subject of experiments, although other amnesiacs with related memory deficits have been discovered and studied. New imaging technologies also have revolutionized the study of memory by allowing scientists to view the brain working in healthy subjects. Yet Henry's life continues to fascinate. ``Whenever I give a talk about H.M., the questions never stop,'' Corkin said. ``The audience asks questions; people come up and ask me questions afterwards. It happens every time. He is a national treasure.'' As the 50th anniversary of the operation approaches, Dr. James Duffy has come to believe that society, which has learned so much from Henry, owes him something more. ``What is my responsibility as a scientist? Is it to just generate knowledge, or is it something else?'' Duffy asked. ``Henry presents us with questions larger than the mechanics of the memory system. We need to understand what he has become in the absence of memory. ``Why is it that we only ask about his memory,'' Duffy said, ``not about who he has become?'' Corkin cautioned against drawing any universal conclusions from Henry's situation. ``Henry is an `n' of one,'' she said, using a mathematical symbol to stress his singularity. ``It is not clear how his experience can generalize to anyone.'' Every moment, as his past disappears into an abyss, Henry asks his own set of questions. ``Right now, I am wondering if I have done or said anything amiss,'' Henry once told a researcher. ``You see, at this moment everything looks clear to me, but what happened just before, that's what worries me. It's like waking from a dream I just don't remember.'' Copyright © 2017, Orlando Sentinel
Wikipedia sobre física de partículas Rapidinho. Me falaram que a definição de física de partículas da Wikipedia era muito ruim. E de fato, era assim: Particle physics is a branch of physics that studies the elementary particle|elementary subatomic constituents of matter and radiation, and their interactions. The field is also called high energy physics, because many elementary particles do not occur under ambient conditions on Earth. They can only be created artificially during high energy collisions with other particles in particle accelerators. Particle physics has evolved out of its parent field of nuclear physics and is typically still taught in close association with it. Scientific research in this area has produced a long list of particles. Mas hein? Partículas que só podem ser criadas em aceleradores? Física de partículas é ensinada junto com física nuclear? A pesquisa produz partículas (essa é ótima!)? Em que mundo essa pessoa vive? Reescrevi: Particle Physics is a branch of physics that studies the existence and interactions of particles, which are the constituents of what is usually referred as matter or radiation. In our current understanding, particles are excitations of quantum fields and interact following their dynamics. Most of the interest in this area is in fundamental fields, those that cannot be described as a bound state of other fields. The set of fundamental fields and their dynamics are summarized in a model called the Standard Model and, therefore, Particle Physics is largely the study of the Standard Model particle content and its possible extensions. Eu acho que ficou bem melhor. Vamos ver em quanto tempo algum editor esquentado da Wikipedia vai demorar para reverter. Atualmente está um saco participar da Wikipedia por causa dessas pessoas.
/* 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; } }
- published: 19 Mar 2013 - views: 42 - author: T.A. B possibly testing on weans, that worries me http://www.bbc.co.uk/news/world-us-canada-21849808. A vaccine is a biological preparation that improves immunity to a particular disease. A vaccine typically contains an agent that resembles a disease-causing microorganism, and is often made from weakened or killed forms of the microbe, its toxins or one of its surface proteins. The agent stimulates the body's immune system to recognize the agent as foreign, destroy it, and "remember" it, so that the immune system can more easily recognize and destroy any of these microorganisms that it later encounters. Vaccines can be prophylactic (example: to prevent or ameliorate the effects of a future infection by any natural or "wild" pathogen), or therapeutic (e.g. vaccines against cancer are also being investigated; see cancer vaccine). The term vaccine derives from Edward Jenner's 1796 use of cow pox (Latin variola vaccinia, adapted from the Latin vaccīn-us, from vacca, cow), to inoculate humans, providing them protection against smallpox. Vaccines do not guarantee complete protection from a disease. Sometimes, this is because the host's immune system simply does not respond adequately or at all. This may be due to a lowered immunity in general (diabetes, steroid use, HIV infection, age) or because the host's immune system does not have a B cell capable of generating antibodies to that antigen. Even if the host develops antibodies, the human immune system is not perfect and in any case the immune system might still not be able to defeat the infection immediately. In this case, the infection will be less severe and heal faster. Adjuvants are typically used to boost immune response. Most often aluminium adjuvants are used, but adjuvants like squalene are also used in some vaccines and more vaccines with squalene and phosphate adjuvants are being tested. Larger doses are used in some cases for older people (50–75 years and up), whose immune response to a given vaccine is not as strong. The efficacy or performance of the vaccine is dependent on a number of factors: When a vaccinated individual does develop the disease vaccinated against, the disease is likely to be milder than without vaccination. The following are important considerations in the effectiveness of a vaccination program: In 1958 there were 763,094 cases of measles and 552 deaths in the United States. With the help of new vaccines, the number of cases dropped to fewer than 150 per year (median of 56). In early 2008, there were 64 suspected cases of measles. 54 out of 64 infections were associated with importation from another country, although only 13% were actually acquired outside of the United States; 63 of these 64 individuals either had never been vaccinated against measles, or were uncertain whether they had been vaccinated. Vaccines are dead or inactivated organisms or purified products derived from them. There are several types of vaccines in use. These represent different strategies used to try to reduce risk of illness, while retaining the ability to induce a beneficial immune response. Some vaccines contain killed, but previously virulent, micro-organisms that have been destroyed with chemicals, heat, radioactivity or antibiotics. Examples are the influenza vaccine, cholera vaccine, bubonic plague vaccine, polio vaccine, hepatitis A vaccine, and rabies vaccine. Some vaccines contain live, attenuated microorganisms. Many of these are live viruses that have been cultivated under conditions that disable their virulent properties, or which use closely related but less dangerous organisms to produce a broad immune response. Although most attenuated vaccines are viral, some are bacterial in nature. They typically provoke more durable immunological responses and are the preferred type for healthy adults. Examples include the viral diseases yellow fever, measles, rubella, and mumps and the bacterial disease typhoid. The live Mycobacterium tuberculosis vaccine developed by Calmette and Guérin is not made of a contagious strain, but contains a virulently modified strain called "BCG" used to elicit an immune response to the vaccine. The live attenuated vaccine containing strain Yersinia pestis EV is used for plague immunization. Attenuated vaccines have some advantages and disadvantages. They have the capacity of transient growth so they give prolonged protection, and no booster dose is required. But they may get reverted to the virulent form and cause the disease. Toxoid vaccines are made from inactivated toxic compounds that cause illness rather than the micro-organism. Examples of toxoid-based vaccines include tetanus and diphtheria. Toxoid vaccines are known for their efficacy. Not all toxoids are for micro-organisms; for example, Crotalus atrox toxoid is used to vaccinate dogs against rattlesnake bites. Protein subunit – rather than introducing an inactivated or attenuated micro-organism to an immune system (which would constitute a "whole-agent" vaccine), a fragment of it can create an immune response. Examples include the subunit vaccine against Hepatitis B virus that is composed of only the surface proteins of the virus (previously extracted from the blood serum of chronically infected patients, but now produced by recombination of the viral genes into yeast), the virus-like particle (VLP) vaccine against human papillomavirus (HPV) that is composed of the viral major capsid protein, and the hemagglutinin and neuraminidase subunits of the influenza virus. Subunit vaccine is being used for plague immunization. Conjugate – certain bacteria have polysaccharide outer coats that are poorly immunogenic. By linking these outer coats to proteins (e.g. toxins), the immune system can be led to recognize the polysaccharide as if it were a protein antigen. This approach is used in the Haemophilus influenzae type B vaccine. A number of innovative vaccines are also in development and in use: While most vaccines are created using inactivated or attenuated compounds from micro-organisms, synthetic vaccines are composed mainly or wholly of synthetic peptides, carbohydrates or antigens. Vaccines may be monovalent (also called univalent) or multivalent (also called polyvalent). A monovalent vaccine is designed to immunize against a single antigen or single microorganism. A multivalent or polyvalent vaccine is designed to immunize against two or more strains of the same microorganism, or against two or more microorganisms. In certain cases a monovalent vaccine may be preferable for rapidly developing a strong immune response. The immune system recognizes vaccine agents as foreign, destroys them, and "remembers" them. When the virulent version of an agent comes along the body recognizes the protein coat on the virus, and thus is prepared to respond, by (1) neutralizing the target agent before it can enter cells, and (2) by recognizing and destroying infected cells before that agent can multiply to vast numbers. When two or more vaccines are mixed together in the same formulation, the two vaccines can interfere. This most frequently occurs with live attenuated vaccines, where one of the vaccine components is more robust than the others and suppresses the growth and immune response to the other components. This phenomenon was first noted in the trivalent Sabin polio vaccine, where the amount of serotype 2 virus in the vaccine had to be reduced to stop it from interfering with the "take" of the serotype 1 and 3 viruses in the vaccine. This phenomenon has also been found to be a problem with the dengue vaccines currently being researched,[when?] where the DEN-3 serotype was found to predominate and suppress the response to DEN-1, -2 and -4 serotypes. Vaccines have contributed to the eradication of smallpox, one of the most contagious and deadly diseases known to man. Other diseases such as rubella, polio, measles, mumps, chickenpox, and typhoid are nowhere near as common as they were a hundred years ago. As long as the vast majority of people are vaccinated, it is much more difficult for an outbreak of disease to occur, let alone spread. This effect is called herd immunity. Polio, which is transmitted only between humans, is targeted by an extensive eradication campaign that has seen endemic polio restricted to only parts of four countries (Afghanistan, India, Nigeria and Pakistan). The difficulty of reaching all children as well as cultural misunderstandings, however, have caused the anticipated eradication date to be missed several times. In order to provide best protection, children are recommended to receive vaccinations as soon as their immune systems are sufficiently developed to respond to particular vaccines, with additional "booster" shots often required to achieve "full immunity". This has led to the development of complex vaccination schedules. In the United States, the Advisory Committee on Immunization Practices, which recommends schedule additions for the Centers for Disease Control and Prevention, recommends routine vaccination of children against: hepatitis A, hepatitis B, polio, mumps, measles, rubella, diphtheria, pertussis, tetanus, HiB, chickenpox, rotavirus, influenza, meningococcal disease and pneumonia. The large number of vaccines and boosters recommended (up to 24 injections by age two) has led to problems with achieving full compliance. In order to combat declining compliance rates, various notification systems have been instituted and a number of combination injections are now marketed (e.g., Pneumococcal conjugate vaccine and MMRV vaccine), which provide protection against multiple diseases. Besides recommendations for infant vaccinations and boosters, many specific vaccines are recommended at other ages or for repeated injections throughout life—most commonly for measles, tetanus, influenza, and pneumonia. Pregnant women are often screened for continued resistance to rubella. The human papillomavirus vaccine is recommended in the U.S. (as of 2011) and UK (as of 2009). Vaccine recommendations for the elderly concentrate on pneumonia and influenza, which are more deadly to that group. In 2006, a vaccine was introduced against shingles, a disease caused by the chickenpox virus, which usually affects the elderly. Sometime during the 1770s Edward Jenner heard a milkmaid boast that she would never have the often-fatal or disfiguring disease smallpox, because she had already had cowpox, which has a very mild effect in humans. In 1796, Jenner took pus from the hand of a milkmaid with cowpox, inoculated an 8-year-old boy with it, and six weeks later variolated the boy's arm with smallpox, afterwards observing that the boy did not catch smallpox. Further experimentation demonstrated the efficacy of the procedure on an infant. Since vaccination with cowpox was much safer than smallpox inoculation, the latter, though still widely practiced in England, was banned in 1840. Louis Pasteur generalized Jenner's idea by developing what he called a rabies vaccine, and in the nineteenth century vaccines were considered a matter of national prestige, and compulsory vaccination laws were passed. The twentieth century saw the introduction of several successful vaccines, including those against diphtheria, measles, mumps, and rubella. Major achievements included the development of the polio vaccine in the 1950s and the eradication of smallpox during the 1960s and 1970s. Maurice Hilleman was the most prolific of the developers of the vaccines in the twentieth century. As vaccines became more common, many people began taking them for granted. However, vaccines remain elusive for many important diseases, including malaria and HIV. ||The neutrality of this section is disputed. Please see the discussion on the talk page. Please do not remove this message until the dispute is resolved. (October 2011)| ||This article is missing information about Scientific rebuttal to the attacks. This concern has been noted on the talk page where whether or not to include such information may be discussed. (October 2011)| Opposition to vaccination, from a wide array of vaccine critics, has existed since the earliest vaccination campaigns. Although the benefits of preventing suffering and death from serious infectious diseases greatly outweigh the risks of rare adverse effects following immunization, disputes have arisen over the morality, ethics, effectiveness, and safety of vaccination. Some vaccination critics say that vaccines are ineffective against disease or that vaccine safety studies are inadequate. Some religious groups do not allow vaccination, and some political groups oppose mandatory vaccination on the grounds of individual liberty. In response, concern has been raised that spreading unfounded information about the medical risks of vaccines increases rates of life-threatening infections, not only in the children whose parents refused vaccinations, but also in other children, perhaps too young for vaccines, who could contract infections from unvaccinated carriers (see herd immunity). One challenge in vaccine development is economic: many of the diseases most demanding a vaccine, including HIV, malaria and tuberculosis, exist principally in poor countries. Pharmaceutical firms and biotechnology companies have little incentive to develop vaccines for these diseases, because there is little revenue potential. Even in more affluent countries, financial returns are usually minimal and the financial and other risks are great. Most vaccine development to date has relied on "push" funding by government, universities and non-profit organizations. Many vaccines have been highly cost effective and beneficial for public health. The number of vaccines actually administered has risen dramatically in recent decades.[when?] This increase, particularly in the number of different vaccines administered to children before entry into schools may be due to government mandates and support, rather than economic incentive. The filing of patents on vaccine development processes can also be viewed as an obstacle to the development of new vaccines. Because of the weak protection offered through a patent on the final product, the protection of the innovation regarding vaccines is often made through the patent of processes used on the development of new vaccines as well as the protection of secrecy. Vaccine production has several stages. First, the antigen itself is generated. Viruses are grown either on primary cells such as chicken eggs (e.g., for influenza), or on continuous cell lines such as cultured human cells (e.g., for hepatitis A). Bacteria are grown in bioreactors (e.g., Haemophilus influenzae type b). Alternatively, a recombinant protein derived from the viruses or bacteria can be generated in yeast, bacteria, or cell cultures. After the antigen is generated, it is isolated from the cells used to generate it. A virus may need to be inactivated, possibly with no further purification required. Recombinant proteins need many operations involving ultrafiltration and column chromatography. Finally, the vaccine is formulated by adding adjuvant, stabilizers, and preservatives as needed. The adjuvant enhances the immune response of the antigen, stabilizers increase the storage life, and preservatives allow the use of multidose vials. Combination vaccines are harder to develop and produce, because of potential incompatibilities and interactions among the antigens and other ingredients involved. Vaccine production techniques are evolving. Cultured mammalian cells are expected to become increasingly important, compared to conventional options such as chicken eggs, due to greater productivity and low incidence of problems with contamination. Recombination technology that produces genetically detoxified vaccine is expected to grow in popularity for the production of bacterial vaccines that use toxoids. Combination vaccines are expected to reduce the quantities of antigens they contain, and thereby decrease undesirable interactions, by using pathogen-associated molecular patterns. In 2010, India produced 60 percent of world's vaccine worth about $900 million. Many vaccines need preservatives to prevent serious adverse effects such as Staphylococcus infection that, in one 1928 incident, killed 12 of 21 children inoculated with a diphtheria vaccine that lacked a preservative. Several preservatives are available, including thiomersal, phenoxyethanol, and formaldehyde. Thiomersal is more effective against bacteria, has better shelf life, and improves vaccine stability, potency, and safety, but in the U.S., the European Union, and a few other affluent countries, it is no longer used as a preservative in childhood vaccines, as a precautionary measure due to its mercury content. Although controversial claims have been made that thiomersal contributes to autism, no convincing scientific evidence supports these claims. There are several new delivery systems in development[when?] that will hopefully make vaccines more efficient to deliver. Possible methods include liposomes and ISCOM (immune stimulating complex). The latest developments[when?] in vaccine delivery technologies have resulted in oral vaccines. A polio vaccine was developed and tested by volunteer vaccinations with no formal training; the results were positive in that the ease of the vaccines increased. With an oral vaccine, there is no risk of blood contamination. Oral vaccines are likely to be solid which have proven to be more stable and less likely to freeze; this stability reduces the need for a "cold chain": the resources required to keep vaccines within a restricted temperature range from the manufacturing stage to the point of administration, which, in turn, may decrease costs of vaccines. A microneedle approach, which is still in stages of development, uses "pointed projections fabricated into arrays that can create vaccine delivery pathways through the skin". A nanopatch is a needle free vaccine delivery system which is under development. A stamp-sized patch similar to an adhesive bandage contains about 20,000 microscopic projections per square inch. When worn on the skin, it will deliver vaccine directly to the skin, which has a higher concentration of immune cells than that in the muscles, where needles and syringes deliver. It thus increases the effectiveness of the vaccination using a lower amount of vaccine used in traditional syringe delivery system. The use of plasmids has been validated in preclinical studies as a protective vaccine strategy for cancer and infectious diseases. However, in human studies this approach has failed to provide clinically relevant benefit. The overall efficacy of plasmid DNA immunization depends on increasing the plasmid's immunogenicity while also correcting for factors involved in the specific activation of immune effector cells. Vaccinations of animals are used both to prevent their contracting diseases and to prevent transmission of disease to humans. Both animals kept as pets and animals raised as livestock are routinely vaccinated. In some instances, wild populations may be vaccinated. This is sometimes accomplished with vaccine-laced food spread in a disease-prone area and has been used to attempt to control rabies in raccoons. Where rabies occurs, rabies vaccination of dogs may be required by law. Other canine vaccines include canine distemper, canine parvovirus, infectious canine hepatitis, adenovirus-2, leptospirosis, bordatella, canine parainfluenza virus, and Lyme disease among others. Vaccine development has several trends: Principles that govern the immune response can now be used in tailor-made vaccines against many noninfectious human diseases, such as cancers and autoimmune disorders. For example, the experimental vaccine CYT006-AngQb has been investigated as a possible treatment for high blood pressure. Factors that have impact on the trends of vaccine development include progress in translatory medicine, demographics, regulatory science, political, cultural, and social responses. |Modern Vaccine and Adjuvant Production and Characterization, Genetic Engineering & Biotechnology News| The World News (WN) Network, has created this privacy statement in order to demonstrate our firm commitment to user privacy. The following discloses our information gathering and dissemination practices for wn.com, as well as e-mail newsletters. We do not collect personally identifiable information about you, except when you provide it to us. For example, if you submit an inquiry to us or sign up for our newsletter, you may be asked to provide certain information such as your contact details (name, e-mail address, mailing address, etc.). We may retain other companies and individuals to perform functions on our behalf. Such third parties may be provided with access to personally identifiable information needed to perform their functions, but may not use such information for any other purpose. In addition, we may disclose any information, including personally identifiable information, we deem necessary, in our sole discretion, to comply with any applicable law, regulation, legal proceeding or governmental request. We do not want you to receive unwanted e-mail from us. We try to make it easy to opt-out of any service you have asked to receive. If you sign-up to our e-mail newsletters we do not sell, exchange or give your e-mail address to a third party. E-mail addresses are collected via the wn.com web site. Users have to physically opt-in to receive the wn.com newsletter and a verification e-mail is sent. wn.com is clearly and conspicuously named at the point ofcollection. If you no longer wish to receive our newsletter and promotional communications, you may opt-out of receiving them by following the instructions included in each newsletter or communication or by e-mailing us at michaelw(at)wn.com The security of your personal information is important to us. We follow generally accepted industry standards to protect the personal information submitted to us, both during registration and once we receive it. No method of transmission over the Internet, or method of electronic storage, is 100 percent secure, however. Therefore, though we strive to use commercially acceptable means to protect your personal information, we cannot guarantee its absolute security. If we decide to change our e-mail practices, we will post those changes to this privacy statement, the homepage, and other places we think appropriate so that you are aware of what information we collect, how we use it, and under what circumstances, if any, we disclose it. If we make material changes to our e-mail practices, we will notify you here, by e-mail, and by means of a notice on our home page. The advertising banners and other forms of advertising appearing on this Web site are sometimes delivered to you, on our behalf, by a third party. In the course of serving advertisements to this site, the third party may place or recognize a unique cookie on your browser. For more information on cookies, you can visit www.cookiecentral.com. As we continue to develop our business, we might sell certain aspects of our entities or assets. In such transactions, user information, including personally identifiable information, generally is one of the transferred business assets, and by submitting your personal information on Wn.com you agree that your data may be transferred to such parties in these circumstances.
Wars have given us the Jeep, the computer and even the microwave. Will the war in Iraq give us the Tiger? Military scientists at Edgewood Chemical Biological Center at Aberdeen Proving Ground hope so. The machine - its full name is the Tactical Garbage to Energy Refinery - combines a chute, an engine, chemical tanks and other components, giving it the appearance of a lunar rover. It's designed to turn food and waste into fuel. If it works, it could save scores of American and Iraqi lives. Among the biggest threats that soldiers face in the war in Iraq are the roadside bombs that have killed or maimed thousands since the U.S.-led invasion in 2003. Because some military bases lack a landfill, transporting garbage to dumps miles away in the desert has become a potentially fatal routine for U.S. troops and military contractors. The Tiger would attempt to solve two problems at once: It would sharply reduce those trash hauls and provide the military with an alternative source of fuel. It is the latest in a long line of wartime innovations, from can openers to desert boots. The conflict in Iraq has produced innovations such as "warlocks," which jam electronic signals from cell phones, garage door openers and other electronic devices that insurgents use to detonate roadside bombs, according to Inventors Digest. "In wartime, you're not worried about making a profit necessarily. You're worried about getting the latest technology on the street," said Peter Kindsvatter, a military historian at Aberdeen Proving Ground, who added that money is spent more freely for research when a nation is at war. "Basically, you find yourself in a technology race with your enemy." The Tiger, now being tested in Baghdad, would not be the first device to turn garbage into energy - a large incinerator near Baltimore's downtown stadiums does it. But it would be among the first to attempt to do it on a small scale. Its creators say it could one day become widely used in civilian life, following the lead of other wartime innovations. During World War II, contractors developed the Jeep to meet the military's desire for a light, all-purpose vehicle that could transport supplies. The development of radar technology to spot Nazi planes led to the microwave, according to historians. The World War II era also gave birth to the first electronic digital computer, the Electronic Numerical Integrator and Computer, or ENIAC. Funded by the Defense Department, the machine was built to compute ballistics tables that soldiers used to mechanically aim large guns. For years it was located at Aberdeen Proving Ground. This decade, the Pentagon determined that garbage on military bases poses a serious logistical problem. "When you're over in a combat area and people are shooting at you, you still have to deal with your trash," said John Spiller, project officer with the Army's Rapid Equipping Force, which is funding the Tiger project. "How would you feel if somebody was shooting at you every other time you pushed it down the curb?" He and other Army officials said they could not recall any specific attacks against troops or contractors heading to dumpsites.For years, large incinerators have burned trash to generate power. Baltimore Refuse Energy Systems Co., the waste-to-energy plant near the stadiums, consumes up to 2,250 tons of refuse a day while producing steam and electricity. The process is so expensive that it has only made sense to do it on a large scale, scientists say. The military has spent almost $3 million on two Tiger prototypes, each weighing nearly 5 tons and small enough to fit into a 20- to 40-foot wide container. The project is being developed by scientists from the Edgewood, Va.-based Defense Life Sciences LLC and Indiana's Purdue University. The biggest challenge was getting the parts to work together, said Donald Kennedy, an Edgewood spokesman. Because the Tiger is a hybrid consisting of a gasifier, bioreactor and generator, much of it is built with off-the-shelf items, including a grinder. Another big challenge: expectations. "When we would initially talk to people about the Tiger system, a large percentage would refuse to believe it could actually work," Kennedy wrote in an e-mail. "Alternatively, a similar percentage would be so intrigued by the idea that they would demand to know when they could buy one for their neighborhood." The Tiger works like this: A shredder rips up waste and soaks it in water. A bioreactor metabolizes the sludge into ethanol. A pelletizer compresses undigested waste into pellets that are fed into a gasification unit, which produces composite gas. The ethanol, composite gas and a 10-percent diesel drip are injected into a diesel generator to produce electricity, according to scientists. It takes about six hours for the Tiger to power up. When it works, the device can power a 60-kilowatt generator. The prototypes are being tested at Camp Victory in Baghdad Initial runs proved successful. The prototypes have been used to power an office trailer. At their peak, they could power two to three trailers. In recent weeks, the scientists suffered a setback: The above-100 degree temperatures caused a chiller device to overheat and shut off occasionally. A new chiller from Edgewood just arrived at the site, Kennedy said. After the 90-day testing phase that ends Aug. 10, the Army will decide whether to fund the project further. Its developers envision the device being used to respond to crises such as Hurricane Katrina, when there is no lack of garbage but a great need for electricity. Spiller, of the Army's Rapid Equipping Force, said he is optimistic. "The mere fact we wrote a check means we think it's got a high chance of success," Spiller said.
Then and now, there is ample proof that Americans do take Supreme Court nominations seriously. With good reason. Sooner or later, the nation's most vexing disagreements over our most vital issues wind up before the Supreme Court. None quite penetrates to the core of our democratic being more than those involving First Amendment rights and values. Each term, the nine justices must grapple with profound questions involving freedom of speech, freedom of thought and freedom to participate in political discourse: Just how free is freedom of speech? What is the role of religion in public life? Does national security trump the public's right to know? During the Court's last three terms, the First Amendment has not fared well. The high court has accepted for review far fewer free-expression-related cases than usual and it has been unusually stingy in recognizing First Amendment claims. In only two of the 15 decisions rendered in free-expression cases did the Court sustain those claims. How the First Amendment will fare in the future depends on how Chief Justice John Roberts differs from his predecessor, William Rehnquist, and how Miers, if confirmed, differs from O'Connor. During his 33 years on the Court as an associate justice and chief justice, Rehnquist consistently voted against free-speech and free-press claims. O'Connor, however, played a pivotal role during her time as justice, frequently casting the decisive fifth vote in religion cases and occasionally in expression cases. The justices over the next 12 months will hear arguments, review briefs and render opinions in several cases that have direct bearing on whether we have full or constricted freedoms when we wish to play a role in the crucial political, cultural or religious issues that confront us. In five cases, the Court will once more take up the question of whether state laws regulating campaign contributions and expenditures pose an unconstitutional threat to political expression: Is money speech? The issues of compelled speech and government funding of speech are raised in another case. A coalition of university law schools which object to the military's ban against acknowledged homosexuals contends that requiring them to allow military recruiters on campus violates their rights. Another case tests the limits of the free exercise of religion. The justices will decide whether the federal government can prohibit a small group of followers of a Brazilian religious sect in New Mexico from importing a banned substance, a hallucinogenic tea, for use in its ceremonies. In a case involving anti-abortion protests appearing before the Court for the third time since 1986, the justices' ruling could affect protest and picketing rights and practices. And a Los Angeles deputy district attorney wants the Court to declare that his free-speech rights were violated when he was disciplined for informing a defense attorney about ethical problems in a pending case. The confirmation process for Miers should be complete by the end of the year. At present, chances seem good that she will be confirmed. Since 1789, the Senate has rejected only 34 of 155 nominations to the Supreme Court. Not much is known about Roberts' views on these issues; even less about Miers'. First Amendment advocates, of course, hope they set the new Court on a new course as far as free expression is concerned. In that regard, Justice Brandeis set a great example as a First Amendment champion during his 23 years on the Supreme Court. "Those who won our independence," he wrote in 1927, "believed liberty to be the secret of happiness and courage to be the secret of liberty. They believed that freedom to think as you will and to speak as you think are means indispensable to the discovery and spread of political truth." The cause of liberty would be better served if this Court's future rulings transcend individual temperament and ideology to embrace the freedom for speech and the tolerance for belief that define a vital democracy. Editor's note: Paul K. McMasters is First Amendment ombudsman at the First Amendment Center, 1101 Wilson Blvd., Arlington, Va. 22209. Web: www.firstamendmentcenter.org. E-mail: email@example.com.
/* ************************************************************************ * 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
// 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
#pragma once #include "geometrycentral/pointcloud/point_cloud.h" #include "geometrycentral/pointcloud/point_position_geometry.h" namespace geometrycentral { namespace pointcloud { // === Readers === // Read from a file by name. Type can be optionally inferred from filename. std::tuple<std::unique_ptr<PointCloud>, std::unique_ptr<PointPositionGeometry>> readPointCloud(std::string filename, std::string type = ""); // Same as above, but from an istream. Must specify type. std::tuple<std::unique_ptr<PointCloud>, std::unique_ptr<PointPositionGeometry>> readPointCloud(std::istream& in, std::string type); // === Writers === // Write to file by name. Type can be optionally inferred from filename. void writePointCloud(PointCloud& cloud, PointPositionGeometry& geometry, std::string filename, std::string type = ""); // Same as above, to to an ostream. Must specify type. void writePointCloud(PointCloud& cloud, PointPositionGeometry& geometry, std::ostream& out, std::string type); } // namespace pointcloud } // namespace geometrycentral
/** * @file lv_tab.c * */ /********************* * INCLUDES *********************/ #include "../../lv_conf.h" #if USE_LV_TABVIEW != 0 #include "lv_tabview.h" #include "lv_btnm.h" #include "../lv_themes/lv_theme.h" #include "../lv_misc/lv_anim.h" /********************* * DEFINES *********************/ #if USE_LV_ANIMATION #ifndef LV_TABVIEW_ANIM_TIME #define LV_TABVIEW_ANIM_TIME \ 300 /*Animation time of focusing to the a list element [ms] (0: no \ animation) */ #endif #else #undef LV_TABVIEW_ANIM_TIME #define LV_TABVIEW_ANIM_TIME 0 /*No animations*/ #endif /********************** * TYPEDEFS **********************/ /********************** * STATIC PROTOTYPES **********************/ static lv_res_t lv_tabview_signal(lv_obj_t *tabview, lv_signal_t sign, void *param); static lv_res_t tabpage_signal(lv_obj_t *tab_page, lv_signal_t sign, void *param); static lv_res_t tabpage_scrl_signal(lv_obj_t *tab_scrl, lv_signal_t sign, void *param); static void tabpage_pressed_handler(lv_obj_t *tabview, lv_obj_t *tabpage); static void tabpage_pressing_handler(lv_obj_t *tabview, lv_obj_t *tabpage); static void tabpage_press_lost_handler(lv_obj_t *tabview, lv_obj_t *tabpage); static lv_res_t tab_btnm_action(lv_obj_t *tab_btnm, const char *tab_name); static void tabview_realign(lv_obj_t *tabview); /********************** * STATIC VARIABLES **********************/ static lv_signal_func_t ancestor_signal; static lv_signal_func_t page_signal; static lv_signal_func_t page_scrl_signal; static const char *tab_def[] = { "" }; /********************** * MACROS **********************/ /********************** * GLOBAL FUNCTIONS **********************/ /** * Create a Tab view object * @param par pointer to an object, it will be the parent of the new tab * @param copy pointer to a tab object, if not NULL then the new object will be * copied from it * @return pointer to the created tab */ lv_obj_t *lv_tabview_create(lv_obj_t *par, lv_obj_t *copy) { /*Create the ancestor of tab*/ lv_obj_t *new_tabview = lv_obj_create(par, copy); lv_mem_assert(new_tabview); if (ancestor_signal == NULL) ancestor_signal = lv_obj_get_signal_func(new_tabview); /*Allocate the tab type specific extended data*/ lv_tabview_ext_t *ext = lv_obj_allocate_ext_attr(new_tabview, sizeof(lv_tabview_ext_t)); lv_mem_assert(ext); /*Initialize the allocated 'ext' */ ext->drag_hor = 0; ext->draging = 0; ext->slide_enable = 1; ext->tab_cur = 0; ext->point_last.x = 0; ext->point_last.y = 0; ext->content = NULL; ext->indic = NULL; ext->btns = NULL; ext->tab_load_action = NULL; ext->anim_time = LV_TABVIEW_ANIM_TIME; ext->tab_name_ptr = lv_mem_alloc(sizeof(char *)); ext->tab_name_ptr[0] = ""; ext->tab_cnt = 0; /*The signal and design functions are not copied so set them here*/ lv_obj_set_signal_func(new_tabview, lv_tabview_signal); /*Init the new tab tab*/ if (copy == NULL) { lv_obj_set_size(new_tabview, LV_HOR_RES, LV_VER_RES); ext->btns = lv_btnm_create(new_tabview, NULL); lv_obj_set_height(ext->btns, 3 * LV_DPI / 4); lv_btnm_set_map(ext->btns, tab_def); lv_btnm_set_action(ext->btns, tab_btnm_action); lv_btnm_set_toggle(ext->btns, true, 0); ext->indic = lv_obj_create(ext->btns, NULL); lv_obj_set_width(ext->indic, LV_DPI); lv_obj_align(ext->indic, ext->btns, LV_ALIGN_IN_BOTTOM_LEFT, 0, 0); lv_obj_set_click(ext->indic, false); ext->content = lv_cont_create(new_tabview, NULL); lv_cont_set_fit(ext->content, true, false); lv_cont_set_layout(ext->content, LV_LAYOUT_ROW_T); lv_cont_set_style(ext->content, &lv_style_transp_tight); lv_obj_set_height(ext->content, LV_VER_RES - lv_obj_get_height(ext->btns)); lv_obj_align(ext->content, ext->btns, LV_ALIGN_OUT_BOTTOM_LEFT, 0, 0); /*Set the default styles*/ lv_theme_t *th = lv_theme_get_current(); if (th) { lv_tabview_set_style(new_tabview, LV_TABVIEW_STYLE_BG, th->tabview.bg); lv_tabview_set_style(new_tabview, LV_TABVIEW_STYLE_INDIC, th->tabview.indic); lv_tabview_set_style(new_tabview, LV_TABVIEW_STYLE_BTN_BG, th->tabview.btn.bg); lv_tabview_set_style(new_tabview, LV_TABVIEW_STYLE_BTN_REL, th->tabview.btn.rel); lv_tabview_set_style(new_tabview, LV_TABVIEW_STYLE_BTN_PR, th->tabview.btn.pr); lv_tabview_set_style(new_tabview, LV_TABVIEW_STYLE_BTN_TGL_REL, th->tabview.btn.tgl_rel); lv_tabview_set_style(new_tabview, LV_TABVIEW_STYLE_BTN_TGL_PR, th->tabview.btn.tgl_pr); } else { lv_tabview_set_style(new_tabview, LV_TABVIEW_STYLE_BG, &lv_style_plain); lv_tabview_set_style(new_tabview, LV_TABVIEW_STYLE_BTN_BG, &lv_style_transp); lv_tabview_set_style(new_tabview, LV_TABVIEW_STYLE_INDIC, &lv_style_plain_color); } } /*Copy an existing tab view*/ else { lv_tabview_ext_t *copy_ext = lv_obj_get_ext_attr(copy); ext->point_last.x = 0; ext->point_last.y = 0; ext->btns = lv_btnm_create(new_tabview, copy_ext->btns); ext->indic = lv_obj_create(ext->btns, copy_ext->indic); ext->content = lv_cont_create(new_tabview, copy_ext->content); ext->anim_time = copy_ext->anim_time; ext->tab_load_action = copy_ext->tab_load_action; ext->tab_name_ptr = lv_mem_alloc(sizeof(char *)); ext->tab_name_ptr[0] = ""; lv_btnm_set_map(ext->btns, ext->tab_name_ptr); uint16_t i; lv_obj_t *new_tab; lv_obj_t *copy_tab; for (i = 0; i < copy_ext->tab_cnt; i++) { new_tab = lv_tabview_add_tab(new_tabview, copy_ext->tab_name_ptr[i]); copy_tab = lv_tabview_get_tab(copy, i); lv_page_set_style(new_tab, LV_PAGE_STYLE_BG, lv_page_get_style(copy_tab, LV_PAGE_STYLE_BG)); lv_page_set_style(new_tab, LV_PAGE_STYLE_SCRL, lv_page_get_style(copy_tab, LV_PAGE_STYLE_SCRL)); lv_page_set_style(new_tab, LV_PAGE_STYLE_SB, lv_page_get_style(copy_tab, LV_PAGE_STYLE_SB)); } /*Refresh the style with new signal function*/ lv_obj_refresh_style(new_tabview); } return new_tabview; } /*====================== * Add/remove functions *=====================*/ /** * Add a new tab with the given name * @param tabview pointer to Tab view object where to ass the new tab * @param name the text on the tab button * @return pointer to the created page object (lv_page). You can create your * content here */ lv_obj_t *lv_tabview_add_tab(lv_obj_t *tabview, const char *name) { lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview); /*Create the container page*/ lv_obj_t *h = lv_page_create(ext->content, NULL); lv_obj_set_size(h, lv_obj_get_width(tabview), lv_obj_get_height(ext->content)); lv_page_set_sb_mode(h, LV_SB_MODE_AUTO); lv_page_set_style(h, LV_PAGE_STYLE_BG, &lv_style_transp); lv_page_set_style(h, LV_PAGE_STYLE_SCRL, &lv_style_transp); if (page_signal == NULL) page_signal = lv_obj_get_signal_func(h); if (page_scrl_signal == NULL) page_scrl_signal = lv_obj_get_signal_func(lv_page_get_scrl(h)); lv_obj_set_signal_func(h, tabpage_signal); lv_obj_set_signal_func(lv_page_get_scrl(h), tabpage_scrl_signal); /*Extend the button matrix map with the new name*/ char *name_dm; if ((name[0] & LV_BTNM_CTRL_MASK) == LV_BTNM_CTRL_CODE) { /*If control byte presented let is*/ name_dm = lv_mem_alloc(strlen(name) + 1); /*+1 for the the closing '\0' */ strcpy(name_dm, name); } else { /*Set a no long press control byte is not presented*/ name_dm = lv_mem_alloc( strlen(name) + 2); /*+1 for the the closing '\0' and +1 for the control byte */ name_dm[0] = '\221'; strcpy(&name_dm[1], name); } ext->tab_cnt++; ext->tab_name_ptr = lv_mem_realloc(ext->tab_name_ptr, sizeof(char *) * (ext->tab_cnt + 1)); ext->tab_name_ptr[ext->tab_cnt - 1] = name_dm; ext->tab_name_ptr[ext->tab_cnt] = ""; lv_btnm_set_map(ext->btns, ext->tab_name_ptr); /*Modify the indicator size*/ lv_style_t *style_tabs = lv_obj_get_style(ext->btns); lv_coord_t indic_width = (lv_obj_get_width(tabview) - style_tabs->body.padding.inner * (ext->tab_cnt - 1) - 2 * style_tabs->body.padding.hor) / ext->tab_cnt; lv_obj_set_width(ext->indic, indic_width); lv_obj_set_x(ext->indic, indic_width * ext->tab_cur + style_tabs->body.padding.inner * ext->tab_cur + style_tabs->body.padding.hor); /*Set the first btn as active*/ if (ext->tab_cnt == 1) { ext->tab_cur = 0; lv_tabview_set_tab_act(tabview, 0, false); tabview_realign(tabview); /*To set the proper btns height*/ } return h; } /*===================== * Setter functions *====================*/ /** * Set a new tab * @param tabview pointer to Tab view object * @param id index of a tab to load * @param anim_en true: set with sliding animation; false: set immediately */ void lv_tabview_set_tab_act(lv_obj_t *tabview, uint16_t id, bool anim_en) { #if USE_LV_ANIMATION == 0 anim_en = false; #endif lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview); lv_style_t *style = lv_obj_get_style(ext->content); if (id >= ext->tab_cnt) id = ext->tab_cnt - 1; if (ext->tab_load_action) ext->tab_load_action(tabview, id); ext->tab_cur = id; lv_coord_t cont_x = -(lv_obj_get_width(tabview) * id + style->body.padding.inner * id + style->body.padding.hor); if (ext->anim_time == 0 || anim_en == false) { lv_obj_set_x(ext->content, cont_x); } else { #if USE_LV_ANIMATION lv_anim_t a; a.var = ext->content; a.start = lv_obj_get_x(ext->content); a.end = cont_x; a.fp = (lv_anim_fp_t)lv_obj_set_x; a.path = lv_anim_path_linear; a.end_cb = NULL; a.act_time = 0; a.time = ext->anim_time; a.playback = 0; a.playback_pause = 0; a.repeat = 0; a.repeat_pause = 0; lv_anim_create(&a); #endif } /*Move the indicator*/ lv_coord_t indic_width = lv_obj_get_width(ext->indic); lv_style_t *tabs_style = lv_obj_get_style(ext->btns); lv_coord_t indic_x = indic_width * id + tabs_style->body.padding.inner * id + tabs_style->body.padding.hor; if (ext->anim_time == 0 || anim_en == false) { lv_obj_set_x(ext->indic, indic_x); } else { #if USE_LV_ANIMATION lv_anim_t a; a.var = ext->indic; a.start = lv_obj_get_x(ext->indic); a.end = indic_x; a.fp = (lv_anim_fp_t)lv_obj_set_x; a.path = lv_anim_path_linear; a.end_cb = NULL; a.act_time = 0; a.time = ext->anim_time; a.playback = 0; a.playback_pause = 0; a.repeat = 0; a.repeat_pause = 0; lv_anim_create(&a); #endif } lv_btnm_set_toggle(ext->btns, true, ext->tab_cur); } /** * Set an action to call when a tab is loaded (Good to create content only if * required) lv_tabview_get_act() still gives the current (old) tab (to remove * content from here) * @param tabview pointer to a tabview object * @param action pointer to a function to call when a btn is loaded */ void lv_tabview_set_tab_load_action(lv_obj_t *tabview, lv_tabview_action_t action) { lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview); ext->tab_load_action = action; } /** * Enable horizontal sliding with touch pad * @param tabview pointer to Tab view object * @param en true: enable sliding; false: disable sliding */ void lv_tabview_set_sliding(lv_obj_t *tabview, bool en) { lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview); ext->slide_enable = en == false ? 0 : 1; } /** * Set the animation time of tab view when a new tab is loaded * @param tabview pointer to Tab view object * @param anim_time_ms time of animation in milliseconds */ void lv_tabview_set_anim_time(lv_obj_t *tabview, uint16_t anim_time) { lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview); #if USE_LV_ANIMATION == 0 anim_time = 0; #endif ext->anim_time = anim_time; } /** * Set the style of a tab view * @param tabview pointer to a tan view object * @param type which style should be set * @param style pointer to the new style */ void lv_tabview_set_style(lv_obj_t *tabview, lv_tabview_style_t type, lv_style_t *style) { lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview); switch (type) { case LV_TABVIEW_STYLE_BG: lv_obj_set_style(tabview, style); break; case LV_TABVIEW_STYLE_BTN_BG: lv_btnm_set_style(ext->btns, LV_BTNM_STYLE_BG, style); tabview_realign(tabview); break; case LV_TABVIEW_STYLE_BTN_REL: lv_btnm_set_style(ext->btns, LV_BTNM_STYLE_BTN_REL, style); tabview_realign(tabview); break; case LV_TABVIEW_STYLE_BTN_PR: lv_btnm_set_style(ext->btns, LV_BTNM_STYLE_BTN_PR, style); break; case LV_TABVIEW_STYLE_BTN_TGL_REL: lv_btnm_set_style(ext->btns, LV_BTNM_STYLE_BTN_TGL_REL, style); break; case LV_TABVIEW_STYLE_BTN_TGL_PR: lv_btnm_set_style(ext->btns, LV_BTNM_STYLE_BTN_TGL_PR, style); break; case LV_TABVIEW_STYLE_INDIC: lv_obj_set_style(ext->indic, style); lv_obj_set_height(ext->indic, style->body.padding.inner); tabview_realign(tabview); break; } } /*===================== * Getter functions *====================*/ /** * Get the index of the currently active tab * @param tabview pointer to Tab view object * @return the active btn index */ uint16_t lv_tabview_get_tab_act(lv_obj_t *tabview) { lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview); return ext->tab_cur; } /** * Get the number of tabs * @param tabview pointer to Tab view object * @return btn count */ uint16_t lv_tabview_get_tab_count(lv_obj_t *tabview) { lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview); return ext->tab_cnt; } /** * Get the page (content area) of a tab * @param tabview pointer to Tab view object * @param id index of the btn (>= 0) * @return pointer to page (lv_page) object */ lv_obj_t *lv_tabview_get_tab(lv_obj_t *tabview, uint16_t id) { lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview); uint16_t i = 0; lv_obj_t *page = lv_obj_get_child_back(ext->content, NULL); while (page != NULL && i != id) { i++; page = lv_obj_get_child_back(ext->content, page); } if (i == id) return page; return NULL; } /** * Get the tab load action * @param tabview pointer to a tabview object * @param return the current btn load action */ lv_tabview_action_t lv_tabview_get_tab_load_action(lv_obj_t *tabview) { lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview); return ext->tab_load_action; } /** * Get horizontal sliding is enabled or not * @param tabview pointer to Tab view object * @return true: enable sliding; false: disable sliding */ bool lv_tabview_get_sliding(lv_obj_t *tabview) { lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview); return ext->slide_enable ? true : false; } /** * Get the animation time of tab view when a new tab is loaded * @param tabview pointer to Tab view object * @return time of animation in milliseconds */ uint16_t lv_tabview_get_anim_time(lv_obj_t *tabview) { lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview); return ext->anim_time; } /** * Get a style of a tab view * @param tabview pointer to a ab view object * @param type which style should be get * @return style pointer to a style */ lv_style_t *lv_tabview_get_style(lv_obj_t *tabview, lv_tabview_style_t type) { lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview); switch (type) { case LV_TABVIEW_STYLE_BG: return lv_obj_get_style(tabview); case LV_TABVIEW_STYLE_BTN_BG: return lv_btnm_get_style(ext->btns, LV_BTNM_STYLE_BG); case LV_TABVIEW_STYLE_BTN_REL: return lv_btnm_get_style(ext->btns, LV_BTNM_STYLE_BTN_REL); case LV_TABVIEW_STYLE_BTN_PR: return lv_btnm_get_style(ext->btns, LV_BTNM_STYLE_BTN_PR); case LV_TABVIEW_STYLE_BTN_TGL_REL: return lv_btnm_get_style(ext->btns, LV_BTNM_STYLE_BTN_TGL_REL); case LV_TABVIEW_STYLE_BTN_TGL_PR: return lv_btnm_get_style(ext->btns, LV_BTNM_STYLE_BTN_TGL_PR); default: return NULL; } /*To avoid warning*/ return NULL; } /********************** * STATIC FUNCTIONS **********************/ /** * Signal function of the Tab view * @param tabview pointer to a Tab view object * @param sign a signal type from lv_signal_t enum * @param param pointer to a signal specific variable * @return LV_RES_OK: the object is not deleted in the function; LV_RES_INV: the * object is deleted */ static lv_res_t lv_tabview_signal(lv_obj_t *tabview, lv_signal_t sign, void *param) { lv_res_t res; /* Include the ancient signal function */ res = ancestor_signal(tabview, sign, param); if (res != LV_RES_OK) return res; lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview); if (sign == LV_SIGNAL_CLEANUP) { uint8_t i; for (i = 0; ext->tab_name_ptr[i][0] != '\0'; i++) lv_mem_free(ext->tab_name_ptr[i]); lv_mem_free(ext->tab_name_ptr); ext->tab_name_ptr = NULL; ext->btns = NULL; /*These objects were children so they are already invalid*/ ext->content = NULL; } else if (sign == LV_SIGNAL_CORD_CHG) { if (ext->content != NULL && (lv_obj_get_width(tabview) != lv_area_get_width(param) || lv_obj_get_height(tabview) != lv_area_get_height(param))) { tabview_realign(tabview); } } else if (sign == LV_SIGNAL_FOCUS || sign == LV_SIGNAL_DEFOCUS || sign == LV_SIGNAL_CONTROLL) { if (ext->btns) { ext->btns->signal_func(ext->btns, sign, param); } } else if (sign == LV_SIGNAL_GET_TYPE) { lv_obj_type_t *buf = param; uint8_t i; for (i = 0; i < LV_MAX_ANCESTOR_NUM - 1; i++) { /*Find the last set data*/ if (buf->type[i] == NULL) break; } buf->type[i] = "lv_tabview"; } return res; } /** * Signal function of a tab's page * @param tab pointer to a tab page object * @param sign a signal type from lv_signal_t enum * @param param pointer to a signal specific variable * @return LV_RES_OK: the object is not deleted in the function; LV_RES_INV: the * object is deleted */ static lv_res_t tabpage_signal(lv_obj_t *tab_page, lv_signal_t sign, void *param) { lv_res_t res; /* Include the ancient signal function */ res = page_signal(tab_page, sign, param); if (res != LV_RES_OK) return res; lv_obj_t *cont = lv_obj_get_parent(tab_page); lv_obj_t *tabview = lv_obj_get_parent(cont); if (lv_tabview_get_sliding(tabview) == false) return res; if (sign == LV_SIGNAL_PRESSED) { tabpage_pressed_handler(tabview, tab_page); } else if (sign == LV_SIGNAL_PRESSING) { tabpage_pressing_handler(tabview, tab_page); } else if (sign == LV_SIGNAL_RELEASED || sign == LV_SIGNAL_PRESS_LOST) { tabpage_press_lost_handler(tabview, tab_page); } return res; } /** * Signal function of the tab page's scrollable object * @param tab_scrl pointer to a tab page's scrollable object * @param sign a signal type from lv_signal_t enum * @param param pointer to a signal specific variable * @return LV_RES_OK: the object is not deleted in the function; LV_RES_INV: the * object is deleted */ static lv_res_t tabpage_scrl_signal(lv_obj_t *tab_scrl, lv_signal_t sign, void *param) { lv_res_t res; /* Include the ancient signal function */ res = page_scrl_signal(tab_scrl, sign, param); if (res != LV_RES_OK) return res; lv_obj_t *tab_page = lv_obj_get_parent(tab_scrl); lv_obj_t *cont = lv_obj_get_parent(tab_page); lv_obj_t *tabview = lv_obj_get_parent(cont); if (lv_tabview_get_sliding(tabview) == false) return res; if (sign == LV_SIGNAL_PRESSED) { tabpage_pressed_handler(tabview, tab_page); } else if (sign == LV_SIGNAL_PRESSING) { tabpage_pressing_handler(tabview, tab_page); } else if (sign == LV_SIGNAL_RELEASED || sign == LV_SIGNAL_PRESS_LOST) { tabpage_press_lost_handler(tabview, tab_page); } return res; } /** * Called when a tab's page or scrollable object is pressed * @param tabview pointer to the btn view object * @param tabpage pointer to the page of a btn */ static void tabpage_pressed_handler(lv_obj_t *tabview, lv_obj_t *tabpage) { (void)tabpage; lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview); lv_indev_t *indev = lv_indev_get_act(); lv_indev_get_point(indev, &ext->point_last); } /** * Called when a tab's page or scrollable object is being pressed * @param tabview pointer to the btn view object * @param tabpage pointer to the page of a btn */ static void tabpage_pressing_handler(lv_obj_t *tabview, lv_obj_t *tabpage) { lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview); lv_indev_t *indev = lv_indev_get_act(); lv_point_t point_act; lv_indev_get_point(indev, &point_act); lv_coord_t x_diff = point_act.x - ext->point_last.x; lv_coord_t y_diff = point_act.y - ext->point_last.y; if (ext->draging == 0) { if (x_diff >= LV_INDEV_DRAG_LIMIT || x_diff <= -LV_INDEV_DRAG_LIMIT) { ext->drag_hor = 1; ext->draging = 1; lv_obj_set_drag(lv_page_get_scrl(tabpage), false); } else if (y_diff >= LV_INDEV_DRAG_LIMIT || y_diff <= -LV_INDEV_DRAG_LIMIT) { ext->drag_hor = 0; ext->draging = 1; } } if (ext->drag_hor) { lv_obj_set_x(ext->content, lv_obj_get_x(ext->content) + point_act.x - ext->point_last.x); ext->point_last.x = point_act.x; ext->point_last.y = point_act.y; /*Move the indicator*/ lv_coord_t indic_width = lv_obj_get_width(ext->indic); lv_style_t *tabs_style = lv_obj_get_style(ext->btns); lv_style_t *indic_style = lv_obj_get_style(ext->indic); lv_coord_t p = ((tabpage->coords.x1 - tabview->coords.x1) * (indic_width + tabs_style->body.padding.inner)) / lv_obj_get_width(tabview); lv_obj_set_x(ext->indic, indic_width * ext->tab_cur + tabs_style->body.padding.inner * ext->tab_cur + indic_style->body.padding.hor - p); } } /** * Called when a tab's page or scrollable object is released or the press id * lost * @param tabview pointer to the btn view object * @param tabpage pointer to the page of a btn */ static void tabpage_press_lost_handler(lv_obj_t *tabview, lv_obj_t *tabpage) { lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview); ext->drag_hor = 0; ext->draging = 0; lv_obj_set_drag(lv_page_get_scrl(tabpage), true); lv_indev_t *indev = lv_indev_get_act(); lv_point_t point_act; lv_indev_get_point(indev, &point_act); lv_point_t vect; lv_indev_get_vect(indev, &vect); lv_coord_t x_predict = 0; while (vect.x != 0) { x_predict += vect.x; vect.x = vect.x * (100 - LV_INDEV_DRAG_THROW) / 100; } lv_coord_t page_x1 = tabpage->coords.x1 - tabview->coords.x1 + x_predict; lv_coord_t page_x2 = page_x1 + lv_obj_get_width(tabpage); lv_coord_t treshold = lv_obj_get_width(tabview) / 2; uint16_t tab_cur = ext->tab_cur; if (page_x1 > treshold) { if (tab_cur != 0) tab_cur--; } else if (page_x2 < treshold) { if (tab_cur < ext->tab_cnt - 1) tab_cur++; } lv_tabview_set_tab_act(tabview, tab_cur, true); } /** * Called when a tab button is released * @param tab_btnm pointer to the tab's button matrix object * @param id the id of the tab (>= 0) * @return LV_ACTION_RES_OK because the button matrix in not deleted in the * function */ static lv_res_t tab_btnm_action(lv_obj_t *tab_btnm, const char *tab_name) { lv_obj_t *tab = lv_obj_get_parent(tab_btnm); const char **tabs_map = lv_btnm_get_map(tab_btnm); uint8_t i = 0; while (tabs_map[i][0] != '\0') { if (strcmp(&tabs_map[i][1], tab_name) == 0) break; /*[1] to skip the control byte*/ i++; } lv_tabview_set_tab_act(tab, i, true); return LV_RES_OK; } /** * Realign and resize the elements of Tab view * @param tabview pointer to a Tab view object */ static void tabview_realign(lv_obj_t *tabview) { lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview); lv_obj_set_width(ext->btns, lv_obj_get_width(tabview)); if (ext->tab_cnt != 0) { lv_style_t *style_btn_bg = lv_tabview_get_style(tabview, LV_TABVIEW_STYLE_BTN_BG); lv_style_t *style_btn_rel = lv_tabview_get_style(tabview, LV_TABVIEW_STYLE_BTN_REL); /*Set the indicator widths*/ lv_coord_t indic_width = (lv_obj_get_width(tabview) - style_btn_bg->body.padding.inner * (ext->tab_cnt - 1) - 2 * style_btn_bg->body.padding.hor) / ext->tab_cnt; lv_obj_set_width(ext->indic, indic_width); /*Set the tabs height*/ lv_coord_t btns_height = lv_font_get_height(style_btn_rel->text.font) + 2 * style_btn_rel->body.padding.ver + 2 * style_btn_bg->body.padding.ver; lv_obj_set_height(ext->btns, btns_height); } lv_obj_set_height(ext->content, lv_obj_get_height(tabview) - lv_obj_get_height(ext->btns)); lv_obj_align(ext->content, ext->btns, LV_ALIGN_OUT_BOTTOM_LEFT, 0, 0); lv_obj_t *pages = lv_obj_get_child(ext->content, NULL); while (pages != NULL) { if (lv_obj_get_signal_func(pages) == tabpage_signal) { /*Be sure adjust only the pages (user can other things)*/ lv_obj_set_size(pages, lv_obj_get_width(tabview), lv_obj_get_height(ext->content)); } pages = lv_obj_get_child(ext->content, pages); } lv_obj_align(ext->indic, ext->btns, LV_ALIGN_IN_BOTTOM_LEFT, 0, 0); lv_tabview_set_tab_act(tabview, ext->tab_cur, false); } #endif
Plaza Cinema Field Trips The Plaza is offering a variety of field trips suitable for grade school children to high school adolescents. If you enjoy films and believe this exceptional art form can be a fun and educational tool to teach history, social sciences, natural sciences, languages, art and culture - then partner with The Plaza. By coming to The Plaza students are able to experience the Arthouse Cinema environment and learn about how it differs from the multiplex cinema. Every field trip includes a short presentation on what we do as a not-for-profit, and how we enrich the community culture through film.  SEED: The Untold Story Directed by Jon Betz and Taggart Siegel Featuring Vandana Shiva, Dr. Jane Goodall, Andrew Kimbrell, Winona Laduke, and Raj Patel The Eagle Huntress Directed by Otto Bell Featuring Daisy Ridley, Aisholpan Nurgaiv, Rhys Nurgaiv Persepolis (NR) This uniquely styled graphic novel traces the biographical history of its author, Marjane Satrapi as she depicts her progression from childhood to becoming an adult. Satrapi grew up at a pivotal point in Iranian history, spending her adolescence in the depths of the Islamic revolution. Told from her perspective, she moves back and forth between Iran and Iraq, facing societal clashes, losing loved ones to the revolution, and being consistently separated from her family both physically and in shared ideologies. The non-fiction graphic novel was ranked by Newsweek as the fifth on its list of the best non-fiction books of the last decade. PERSEPOLIS was adapted into a film in 2007, following the same artistic style as the graphic novel, but with some color added. A team of twenty animators were given the task of transforming Satrapi's graphic novel into a moving animation, a project that emphasized traditional animation techniques as well as the capabilities of only using two solid colors (black and white) to achieve depth. In 2007, the film was a co-winner of the Jury Prize at Cannes and nominated for an Oscar. Directed by Marjane Satrapi, Vincent Paronnaud To Kill a Mockingbird In great depression era Alabama young “Scout” comes of age while her father Atticus takes on a racially charged court case. Spanning over about three years of her life, the novel Follows Scout, her father Atticus, and brother Jem through the trials and tribulations of growing up in the Deep South in the 1930s. The Pulitzer prize winning novel was adapted into a film by director Robert Mulligan in 1962, for which he received critical acclaim and several Academy Awards. As a part of the National Film Registry this film remains a symbolic icon of American Culture, much like Harper Lee’s classic novel. Directed By Robert Mulligan Starring Gregory Peck, Mary Badham Academy Award nominee Benedict Cumberbatch (BBC’s Sherlock, The Imitation Game, Frankenstein at the National Theatre) takes on the title role of Shakespeare’s great tragedy. Directed by Lyndsey Turner (Posh, Chimerica) and produced by Sonia Friedman Productions, National Theatre brings this eagerly awaited production live to the cinema screen from its sold-out run at the Barbican. As a country arms itself for war, a family tears itself apart. Forced to avenge his father’s death, but paralyzed by the task ahead, Hamlet rages against the impossibility of his predicament, threatening both his sanity and the security of the state. Directed by Robin Lough Starring Benedict Cumberbatch, Sian Brooke Romeo and Juliet The Kenneth Branagh Theatre Company Live cinema season continues with a new vision of Shakespeare’s heartbreaking tale of forbidden love. Branagh and his creative team present a modern passionate version of the classic tragedy. A longstanding feud between Verona’s Montague and Capulet families brings about devastating consequences for two young lovers caught in the conflict. Kenneth Branagh co-directs with Rob Ashford, reuniting with the stars of his celebrated film of Cinderella, Richard Madden and Lily James, as Romeo and Juliet. Also featuring Sir Derek Jacobi as Mercutio and Meera Syal as The Nurse. Romeo and Juliet will be screened in high definition black and white. Directed by Kenneth Branagh and Rob Ashford Starring Derek Jacobi and Lily James KUS4Nexternal250 (2).jpeg Killing us Softly 4 Filmmaker Sut Jhally Production Year 2010 Tough Guise Filmmaker Sut Jhally Production Year 1999 Field Trips for Elementary School Students The Plaza offers a variety of field trips that are appropriate for grades 3 - 5 focusing on the fundamentals of storytelling and animation. In the past students have participated in interactive lessons where they watch animated films, learn about the fundamentals of animation and gain hands on experience creating heir own stop motion films.  Boxcar Children In past years 3rd, 4th and 5th graders from River Elementary enjoyed interactive field trips where they saw the animated film BOXCAR CHILDREN (based on the franchised book by the same name), learned about different animation techniques and created their own stop-motion films. Based on a 1924 novel of the same name, The Boxcar Children has been adapted into a franchise including over 150 adventures in film and novel form. In the original premise, four siblings take to the road after their parents die and make a home in an abandoned boxcar. Directed by Daniel Chuba Starring Illenan Douglas, Martin Sheen, Zachary Gordon, Mackenzie Foy
The vaunted protection that intellectually active adults get from Alzheimer’s disease has a dark downside, a study released Wednesday has found. Once dementia symptoms become evident and Alzheimer’s disease is diagnosed in such patients, their mental decline can come with frightening speed. That finding, published in the journal Neurology, comes from a study of 1,157 Chicago-based seniors who were followed for an average of just over 11 years. Six years after gauging the extent to which the study participants engaged in activities that challenged their mental capacities, researchers from Rush University Medical Center Alzheimer’s Disease Center made periodic assessments of the study participants’ cognitive health and traced the trajectories of their brain health. All told, 148 of the participants were diagnosed with Alzheimer’s disease during the follow-up period, and 395 were found to have mild cognitive impairment—intellectual problems that are less severe than Alzheimer’s disease, but which often precede such a diagnosis. While all participants’ mental function showed yearly declines, the steepest downward trajectories belonged to those who had been diagnosed with Alzheimer’s disease, but who had reported high levels of mental engagement at the outset of the study. Fellow Alzheimer’s sufferers who had not sought out much intellectual stimulation at the study’s outset showed a more gradual decline in their function. “In effect, the results of this study suggest that the benefit of delaying the initial appearance of cognitive impairment [in Alzheimer’s disease] comes at the cost of more rapid dementia progression,” the author wrote. The findings support a common observation of those who treat intellectually minded patients who go on to be diagnosed with Alzheimer’s disease—that once diagnosed, their decline is rapid. It also underscores a growing body of evidence that the bright and mentally-active may not beat Alzheimer’s disease, but can hold off its ravages for months or years longer than those who are not so engaged. Dr. John M. Ringman, a UCLA neurologist and assistant director of the Mary S. Easton Center for Alzheimer’s Disease Research, said he sees regular evidence of the phenomenonen in his clinical work, as well as in brain-imaging scans that can detect the physical signs of Alzheimer’s disease while a patient is still alive: Patients with a history of intensive mental engagement seem to develop a “cognitive reserve,” said Dr. Ringman. That mental strength frequently allows them to function almost normally, he said, even as the amyloid plaques and neurofibrillary tangles that are the hallmarks of the disease have advanced upon the brain. By the time such a patient comes to his office complaining that his memory and mental function are not what they used to be, the disease has progressed significantly, said Ringman. The decline from that point can be precipitous. In a disease that evidence now suggests takes years, perhaps decades, to show up in everyday behavior, Ringman said “it’s hard to quantify this cognitive reserve.” The strength of the study published Wednesday is that it gathered copious evidence of participants’ mental status and activity at the outset and followed them for more than a decade, he added. --Melissa Healy/Los Angeles Times
Belgian physicist Francois Englert, left, speaks with British physicist… (Fabrice Coffrini / AFP/Getty…) For physicists, it was a moment like landing on the moon or the discovery of DNA. The focus was the Higgs boson, a subatomic particle that exists for a mere fraction of a second. Long theorized but never glimpsed, the so-called God particle is thought to be key to understanding the existence of all mass in the universe. The revelation Wednesday that it -- or some version of it -- had almost certainly been detected amid more than hundreds of trillions of high-speed collisions in a 17-mile track near Geneva prompted a group of normally reserved scientists to erupt with joy. For The Record Los Angeles Times Friday, July 06, 2012 Home Edition Main News Part A Page 4 News Desk 1 inches; 48 words Type of Material: Correction Large Hadron Collider: In some copies of the July 5 edition, an article in Section A about the machine used by physicists at the European Organization for Nuclear Research to search for the Higgs boson referred to the $5-billion Large Hadron Collider. The correct amount is $10 billion. Peter Higgs, one of the scientists who first hypothesized the existence of the particle, reportedly shed tears as the data were presented in a jampacked and applause-heavy seminar at CERN, the European Organization for Nuclear Research. "It's a gigantic triumph for physics," said Frank Wilczek, an MIT physicist and Nobel laureate. "It's a tremendous demonstration of a community dedicated to understanding nature." The achievement, nearly 50 years in the making, confirms physicists' understanding of how mass -- the stuff that makes stars, planets and even people -- arose in the universe, they said. It also points the way toward a new path of scientific inquiry into the mass-generating mechanism that was never before possible, said UCLA physicist Robert Cousins, a member of one of the two research teams that has been chasing the Higgs boson at CERN. "I compare it to turning the corner and walking around a building -- there's a whole new set of things you can look at," he said. "It is a beginning, not an end." Leaders of the two teams reported independent results that suggested the existence of a previously unseen subatomic particle with a mass of about 125 to 126 billion electron volts. Both groups got results at a "five sigma" level of confidence -- the statistical requirement for declaring a scientific "discovery." "The chance that either of the two experiments had seen a fluke is less than three parts in 10 million," said UC San Diego physicist Vivek Sharma, a former leader of one of the Higgs research groups. "There is no doubt that we have found something." But he and others stopped just shy of saying that this new particle was indeed the long-sought Higgs boson. "All we can tell right now is that it quacks like a duck and it walks like a duck," Sharma said. In this case, quacking was enough for most. "If it looks like a duck and quacks like a duck, it's probably at least a bird," said Wilczek, who stayed up past 3 a.m. to watch the seminar live over the Web while vacationing in New Hampshire. Certainly CERN leaders in Geneva, even as they referred to their discovery simply as "a new particle," didn't bother hiding their excitement. The original plan had been to present the latest results on the Higgs search at the International Conference on High Energy Physics, a big scientific meeting that began Wednesday in Melbourne. But as it dawned on CERN scientists that they were on the verge of "a big announcement," Cousins said, officials decided to honor tradition and instead present the results on CERN's turf. The small number of scientists who theorized the existence of the Higgs boson in the 1960s -- including Higgs of the University of Edinburgh -- were invited to fly to Geneva. For the non-VIP set, lines to get into the auditorium began forming late Tuesday. Many spent the night in sleeping bags. All the hubbub was due to the fact that the discovery of the Higgs boson is the last piece of the puzzle needed to complete the so-called Standard Model of particle physics -- the big picture that describes the subatomic particles that make up everything in the universe, and the forces that work between them. Over the course of the 20th century, as physicists learned more about the Standard Model, they struggled to answer one very basic question: Why does matter exist? Higgs and others came up with a possible explanation: that particles gain mass by traveling through an energy field. One way to think about it is that the field sticks to the particles, slowing them down and imparting mass. That energy field came to be known as the Higgs field. The particle associated with the field was dubbed the Higgs boson. Higgs published his theory in 1964. In the 48 years since, physicists have eagerly chased the Higgs boson. Finding it would provide the experimental confirmation they needed to show that their current understanding of the Standard Model was correct. On the other hand, ruling it out would mean a return to the drawing board to look for an alternative Higgs particle, or several alternative Higgs particles, or perhaps to rethink the Standard Model from the bottom up. Either outcome would be monumental, scientists said.
#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; } }
/** * 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; } } }
// 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_
// 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(); } }
#pragma once /* The MIT License (MIT) Copyright (c) 2015 Dennis Wandschura 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 <vxLib/types.h> class Material; namespace Graphics { class Texture; } template<typename T> class ResourceManager; namespace vx { template<typename K, typename T,typename C> class sorted_array; struct StringID; class FileEntry; } #include <vxEngineLib/FileEntry.h> #include <vector> struct MaterialFactoryLoadDescription { const char *fileNameWithPath; const vx::sorted_array<vx::StringID, const Graphics::Texture*, std::less<vx::StringID>>* textureFiles; std::vector<vx::FileEntry>* missingFiles; Material* material; }; struct MissingTextureFile { vx::FileEntry fileEntry; bool srgb; }; struct MaterialFactoryLoadDescNew { const char *fileNameWithPath; const ResourceManager<Graphics::Texture>* m_textureManager; MissingTextureFile* missingFiles; u32* missingFilesCount; Material* material; }; class MaterialFactory { public: static bool load(const MaterialFactoryLoadDescription &desc); static bool load(const MaterialFactoryLoadDescNew &desc); };
Numerous industries utilize solid metal parts made of powdered metal. Powdered metal components, which are made from powdered metal via powder metallurgy, can be found in applications spanning across industries such as lawn and garden, computer, electronics, hardware, and automotive. More specifically, powder metal parts include magnetic assemblies, filtration systems, structural parts, and automobile components. Powder metal gears are inherently porous and they naturally reduce sound, making them a suitable component to the sintering process. Bearings and bushings can simply be produced by way of sintering, however, they may require a secondary sizing operation because their fabrication leaves little room for error. Powder metal is soft and can be formed in a variety of shapes with proper sintering; however, this variety is very limited. Powder metal is a popular choice of material for parts with magnetic properties, and its magnetism can be enhanced through the sintering process. Two processes can be utilized to make powder metal parts: sintering and metal injection molding. Both of these processes are used to produce powder metal parts made of aluminum, copper, and iron. Sintered metal parts include sintered steel and sintered bronze parts, and they are made by melting metal powder and forming it into a shape. The metal injection molding process involves adding wax, resin, or polymers to powdered metal, heating the mixture to a pliable state, and formed within a mold. Read More… Leading Manufacturers Perry Tool & Research, Inc. Hayward, CA | 510-782-9226 Comtec Mfg., Inc. St. Marys, PA | 814-834-9300 MetalKraft Industries, Inc. Wellsboro, PA | 570-724-6800 Proform Powdered Metals. Inc.. Punxsutawney, PA | 814-938-7411 Powder metallurgy is a process in which metal is formed and fabricated from powder to a finished part. The raw metal material is made into powder by way of atomization, mechanical alloying, electrolytic techniques, chemical reduction, and pulverization. The powder is then mixed with a lubricant, which assists in reducing friction between the powder material and the pressing dies. The next step involves forming, in which the material is molded, forged, or pressed. Sintering is a crucial step in the process, as it develops the products finished properties, such as regulating its porosity and increasing its strength. In the high-temperature process of sintering, the compacted raw materials, also known as green parts, are melted down in a furnace. When the green parts are melted, the particles are bonded together while still retaining the part’s shape. Sometimes, the product requires secondary operations such as machining, deburring, sizing, or heating. The finished parts may appear solid, but they are actually made up of tiny capillaries that are interconnected with each other. Thus, the parts have a porosity of 25%. Sintered metal products have many advantages over parts that are fabricated through other processes. Sintering uses roughly 97% of materials, and therefore does not produce as much waste. Sintered products are not sensitive to the shapes in which they are formed, and they frequently do not need to undergo any secondary operations. Powder metal parts have controlled porosity, enabling them to self-lubricate and filter gases and liquids. Because of all of these benefits, powder metallurgy is a highly recommended process in fabricating parts that require intricate bends, depressions, and projections. A wide variety of composites, alloys, and other materials can be used in the sintering process to fabricate products of numerous designs and shapes. Metal injection molding is a powder metallurgy process which is frequently used to produce metal parts that are smaller, more complex, high density, and high in performance. The process of metal injection combines powder metallurgy and plastic injection molding, and is commonly used for parts used in industries such as electronics, computer, hardware, firearms, dental, medical, and automotive. Metal injection molding allows for more freedom in detailing and design, reduces waste, and offers products that are magnetic, more corrosion-resistant, stronger, and denser. However, this process is only used in making thinner, smaller parts, and is more costly than regular powder metallurgy. Metal injection molding differs in a few ways. First, the metal powder is not only mixed with lubricants, but also with thermoplastics. The parts are only formed by molding using standard plastic injection molding machines. The next step involves using chemicals or thermal energy and an open pore network to remove the thermoplastics from the parts. Finally, the parts are sintered and undergo secondary procedures if necessary. Bronze, steel, iron, brass, copper, and aluminum are just a few of the many metals that can be converted to powder and undergo the metallurgy process. Aluminum is frequently used because it is highly flammable, highly conductive, and light in weight. Aluminum is a popular materials to use in structural applications and pyrotechnics. Copper is highly conductive both electrically and thermally, and are thus popular for use in electrical contractor or heat sink applications. Iron contains a graphite additive and is frequently used to fabricate bearings, filters, and structural parts. Steel is used for tool steel or stainless steel powders, are very high in strength. Thus, one application for which it is frequently used is automobile weight reduction. Finally, bronze is a metal that is higher in density and has a higher mechanical performance than brass, and bronze metal parts are commonly utilized to fabricate self-lubricating bearings. Powder Metal Part Informational Video
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; } };
What to Do If Your Pilot Light Goes Out January 19, 2017 Pilot lights are commonly found on older model furnaces, and while they serve a very important purpose, also pose a safety hazard in the event they should go out. Instructions on how to relight the pilot light are typically found affixed to the appliance itself, or in the original owner’s manual. Knowing what to do if your pilot light goes out, and when to call for service or repair, can help keep your home and family safe and comfortable throughout heating season. Contact Rick’s Heating & Cooling for assistance, or around the clock emergency repair in the event you are unable to keep the flame lit or if you have any other questions or concerns with your heating or cooling system. How Does A Pilot Light Work? A number of components work together in older model furnaces, to maintain the flow of natural gas to the appliance as needed. When heat is called for and the furnace turns “on,” a valve releases gas to the main burner, and the pilot light ignites the gas. This small, blue, perpetually burning flame is created when a small amount of gas is channeled through a small tube in the gas pipe. In the event that the pilot light should blow out, the tube has a valve which, when shut off by the thermocouple, stops the flow of gas to prevent it from building up in side your home. What Causes A Pilot Light To Go Out? There are a number of reasons why your pilot light may blow out. Some you may be able to rectify yourself, while others require the services of a professional. • Draft. A sudden or steady rush of air can easily blow out the standing pilot light. Once it is relit, check the surrounding area for the source of a draft to prevent it from reoccurring. • Dirty pilot orifice. If, upon reigniting the pilot light, the flame burns a weak yellow instead of blue, the pilot orifice may be dirty. Call Rick’s Heating & Cooling for professional service. What Should You Do If Your Pilot Light Goes Out? The pilot light controls, assembly, and instructions for lighting, are typically located at the front of the unit for easy access. If you are unable to locate the manufacturers instructions, general instructions are as follows: 1. Locate the pilot light assembly, including the gas valve with “On,” “Off,” and “Pilot” settings, and pilot reset button 2. Rotate the valve to the “Off” position, and wait several minutes 3. Rotate the valve to the “Pilot” position, and hold a barbecue lighter or long match to the pilot opening while pushing the pilot reset button. 4. Keep the button pressed until the flame is lit and burning strongly, then release and turn the gas valve to the “On” position. 5. In the event the flame will not remain lit, rotate the gas valve to the “Off” position and call for service. Emergency Furnace Repair In Morrow, OH The skilled technicians at Rick’s Heating & Cooling can provide expert assistance with all your heating concerns, including issues with your pilot light. Give us a call today at 513-899-6005, or contact us online to request service.
// 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
"Helplessness" and "confusion" are words that easily come to mind when the issue of sick building syndrome is mentioned. It is a problem that does not have a regulatory solution, and is bound with engineering, medicine and emotions that will challenge the best of school administrators. A careful management style and knowledgeable use of technologies in medicine, toxicology and property maintenance are a school administrator's best allies in preparing to deal with or prevent this new generation of health and safety challenges. Defining sick building syndrome There is no regulatory definition for sick building syndrome. Although it often relates to indoor-air-quality problems, it simply means that the environment of a building is inspiring complaints of discomfort and/or disease. Fundamentally, the causes of sick buildings relate to architecture and engineering patterns institutionalized in school construction following World War II. Schools of glass, rock and wood, with high ceilings, cross-ventilation via a transom over the door, and windows and radiators that could be adjusted by teachers no longer were built. These schools were being replaced with new, factory-like buildings featuring a temperamental, eccentric system of master controls for indoor environment. Buildings were constructed with no regard to the environment around them or to people within the property. Today, allowing for the ambiguity in defining sick buildings, somewhere between 1-in-5 and 1-in-15 school facilities are in a situation where discomfort and disease can be attributed to operations of the building. Health symptoms in a sick building are highly variable, but generally split into three categories: -Radical reaction--a number of people clearly and suddenly ill. This usually involves limited air exchange combined with a "smoking gun," which can include a new chemical cleaner, misbatched chlorine in a pool area, a weather inversion preventing a kiln from venting properly or a failure of a mechanical air-exchange system. -Unhealthy atmosphere--many people experiencing ongoing subtle illness or discomfort. The most common symptoms involve the dehydration of sensitive tissue, including sore eyes, throat or nasal membranes; a feeling of lethargy; a higher incidence of upper-respiratory infection; asthmatic reactions; low-grade headaches; and a continuum of muscle pain and general discomfort among building occupants. Much of this relates to oxygen deprivation typically caused by oxygen being displaced by other compounds, and occasionally by infestation of microbes as a result of excessive moisture remaining within the property. -Hypersensitive reaction or multiple chemical sensitivity reaction--one or two individuals extremely ill. This can result if even tiny exposures occur to anyone that has a highly sensitive reaction to certain chemicals. Typically, these complaints should be viewed as warnings that some low-level toxin is in the area. Although sick building syndrome usually relates to the general nature of the building itself, there are some specifics that account for most indoor-air problems: *Combustibles; any possible introduction of carbon monoxide. *Moisture as it may relate to mold (look for growths on drywall). *Moisture as it may relate to airborne infectious agents (standing water and consequent growths). *Volatile organic compounds (VOCs), usually cleaning agents or building materials, which may give off unpleasant, sometimes toxic gases. *Formaldehydes in new carpet, pressed wood or other building products. *Any new or newly exposed particleboard. *Applied poisons (pesticides, insecticides, rodenticides, herbicides). A proactive approach Administrators are dealing with a generation of post-World War II properties prone to indoor-air-quality problems, particularly buildings constructed or remodeled during the 1970s energy crisis. A school district should take several steps before a problem strikes. First, initiate patterns for preventing air-quality problems. Second, establish baseline information that will profile the building to facilitate an efficient, inexpensive and confidence-inspiring response. Building occupants and the community need to see a clear and confident administrative approach should a problem arise in the future. The proactive investigation of the building should involve a limited amount of basic testing, particularly a professional review of the microbial matrix within the building--the number of colony-forming units or what kinds of microbes presently are nesting in the building. Understanding what is living in the ambient air can help administrators understand if there is a problem or, more importantly, can help to quickly isolate the exact nature of a problem. Similarly, administrators should consider hiring an outside contractor to review how air-handling and mechanical-engineering systems are managed. A knowledgeable person should walk the area and observe the mechanical systems to see how the filtering system, the air-dispersion system and the air-dilution patterns of the building are operating. Finally, a reliable epidemiological profile of comparative absenteeism should be archived. Administrators also need to be ready to implement a smooth, confidence-building reporting system for occupants regarding air-quality or sick-building concerns. How fast and capably the district responds can be the key to getting the issue under control. The costs for responding to indoor-air problems decrease dramatically if there is baseline data and a plan in place.
Term 3 Week 10 posted 19 Jun 2016, 12:59 by Primary 2 Teacher   [ updated 19 Jun 2016, 13:00 ] Literacy - Information Texts Children will continue to practise spelling patterns in their spelling teams. This week we will be looking at both fiction and non-fiction books about tigers. Recognising questions and answers. Writing a conversation using questions and answers. Using correct punctuation in a sentence, using question marks. Read and understand factual sentences. Write factual sentences. Read understand and sort facts. Create a non-fiction text. Write questions and answers in a non-fiction text. Maths - Measures and Shape Children will  Practise the order of the months of the year Say the month before/after a given month Find times 1 hour/1/2 an hour later than a given time Recognise 3D shapes Describe direction and  position of 3D shapes IPC-Water World We will continue with our Geography learning, children will Learn how to follow and give directions Be given the opportunity to express views on attractive and unattractive features of the environment Communicate their geographical knowlege and understanding in a variety of ways.
// 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"); }
"GOT NOTHING BUT BLUE SKIES" It is September 19,1783. The place, Lyons, France. Preparations are being made for a journey. A journey that will eventually take man from his secure environment of terra firma, and place him in a hostile environment called the atmosphere. The vehicle to be used is a hot air balloon. The brainchild behind this trek is a wealthy paper maker named Joseph Montgolfier. There has been much speculation over just how Montgolfier made the discovery of the hot air balloon. The most commonly-believed story is that his wife was standing too close to a fire and that the smoke caused her skirt to be inflated and lifted above her knees. This caused Montgolfier to wonder-if this smoke, and its magical lifting powers, could be captured in a very large container, it might rise and lift a passenger along with it. So, Montgolfier went about building the first hot air balloon. In 1783, not much was known about the atmosphere and its effects on human beings. Upon examination of the occupants for any ill effects caused by this lofty height, it was discovered that the duck had a broken wing. Could this have been an effect of exposure to altitude? Actually, several observers noted that as the balloon left the ground, the sheep had an anxiety attack and kicked the duck. Montgolfier reasoned that it would be safe for humans to ascend to altitude. So on November 21, 1783, Jean Francois Pilatre de Rozier (a surgeon) became the first aeronaut and flight surgeon. Over 200 years have passed since that first flight. Technology has allowed us to ascend through the atmosphere and into space, but the hazards of high altitude flight (hypoxia, altitude-induced decompression sickness, and trapped gases) will always be present. That is because humans are best suited to live in what is known as the "physiological efficient zone". This zone extends from sea level to 12,000 feet. When humans are exposed to altitudes above this zone, they are subjected to physiological hazards beyond their natural ability to adapt. One thing to keep in mind is that everything that occupies space and exerts weight is considered to be matter. All matter is made up of atoms and molecules in varying densities. These particles within the matter are kinetic and in constant motion. The slower the motion of the particles, the more dense the matter becomes. Also, as the particles are pushed closer together, the matter also becomes more dense. The best way to slow down kinetic molecules is to cool the matter. The best way to get them to move closer together is to add pressure to the matter. Inversely, when you remove the pressure or heat any material, the molecules within the material moves faster and further apart, thus making the material less dense. The least dense form of matter is, of course, gas. If a gas is cooled and compressed, at some point it will become a liquid. If that liquid is then cooled further, then at some point it will become a solid. Also, when you take the pressure off any gas or liquid, that material will grow less dense and expand. This is essentially what happens to the gaseous molecules of our atmosphere. Our atmosphere contains approximately 79% nitrogen and 21% oxygen, a constant ratio until you reach an altitude of about 270,000 feet. So the question that always comes up is; "If I have 21% oxygen at sea level and 21% at 40,000 feet, why do I succumb to the effects of hypoxia within 20 seconds at that altitude?" The answer is, ATMOSPHERIC PRESSURE! If you could picture all the gaseous nitrogen and oxygen molecules in the atmosphere, they would stack up from the surface of the earth to the fringe of space. All these molecules stacking on top each other create a great deal of weight, or pressure. At sea level, one square-inch of any surface has about 15 pounds of air sitting on top of it. At 18,000 feet, that same square inch has only 7.5 pounds per square-inch (psi) exerted on it. What has caused this atmospheric pressure drop? The answer is simple: There is more air stacked up at sea level than above 18,000 feet, and therefore, more weight. As you recall, when molecules are subjected to this pressure, they are going to move closer together. This will make the air more dense with oxygen and nitrogen molecules. For example, if at sea level you take in a breath of air that has an atmospheric pressure of 15 psi, then that air may contain 500 billion molecules of oxygen (this a fictitious number to be used only as an example); if you go to 18,000 feet and take the same breath where atmospheric pressure is 7.5 psi, then you will pull in only 250 billion molecules of oxygen. But, you require 500 billion per breath to function normally, and you're getting only half of what you need. That's HYPOXIA! Not only do gaseous molecules in the atmosphere expand with reduced total pressure, gases in the human body are also subject to the same expansion. There are several areas in the body- ears, sinuses, lungs, gastro-intestinal tract, and teeth - where these gases can expand and cause a variety of problems. As long as the gas can expand and escape, there will be no problem. But if the gas becomes trapped, then pain will be the usual result. As we have discussed earlier, the air we breathe contains about 79% nitrogen. Nitrogen is inhaled into the lungs and distributed and stored throughout the body. According to gas laws, gases of higher pressure always exert force towards areas of low pressure. When you inhale nitrogen, it will be stored at a pressure of about 12 psi (79% nitrogen) of 15 psi (total atmospheric pressure), equal to about 12 psi). When you ascend to altitude and the pressure around your body begins to drop, this creates a pressure gradient (higher nitrogen in the body than outside the body) and the nitrogen will try to equalize and escape outside the body. Sometimes this nitrogen can leave so quickly and in such quantify that it may form a bubble. If this bubble forms at a body joint, the pain it causes is know as "the bends." These are just a few of the problems that can occur when the human body is exposed to high altitude conditions. These problems will always be there for aviation. But through education and knowledge of the mechanisms that cause these problems, we can take steps toward protection and prevention so that your BLUE SKIES won't give you a case of the blues. by J.R. Brown |ŠAvStop Online Magazine Contact Us Return Home| Grab this Headline Animator
Here to There: A History of Mapping From the 16th to 18th centuries, many European mapmakers were convinced that California was an island — an Edenic paradise populated by black Amazons. The error persisted for over a hundred years after expeditions had proven that California was, in fact, firmly attached to the mainland. The idea of California as a fierce paradise appealed to Europeans, who were reluctant to let the mundane reality interfere with their vision of the world. So in that spirit, we’re devoting this episode of BackStory to maps — asking what they show us about who we are and and where we want to go. How do maps shape the way we see our communities and our world? What do they tell us about the kind of information we value? And what do they distort, or ignore? Please help us shape this show! Share your questions, ideas and stories below. Have opinions on New York vs. D.C. subway maps? On the merits or shortcomings of Google Maps? And do you even still use old-fashioned, ink-and-paper maps? Leave us a comment!
// // 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
//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; } } };
How True Capitalism Kills Racism Bigotry carries a cost. For decades, agitators aligned with the Democratic Party have argued that the only way to right the "historic wrong" of slavery is to enforce affirmative action - that is, to give unearned preferences to blacks or other minorities simply because they are black or minority.  The thought is that, because black people were oppressed for hundreds of years primarily because of their skin color, it's only right for them to enjoy the opposite treatment for a while. As we've discussed before, this notion flies in the face of anything resembling ordinary justice or ethics.  Yes, slavery was a terrible wrong, but the slaveowners are all dead and so are all the slaves.  Today's black people never suffered under slavery or even Jim Crow save for a few elderly; today's white people overwhelmingly have never participated in official bigotry.  Why should the innocent be punished for the betterment of the never-harmed? Let us set aside the philosophical arguments against affirmative action, for there's an even better reason not to do it: It does not work.  Decades of official discrimination have merely made matters worse, as a few nights' viewing of TV news amply demonstrates. Does this make the cause of racial justice a hopeless one?  Actually, no.  There is a proven means of achieving equality of liberty, which was fought for by early civil rights leaders like Frederick Douglass and Booker T. Washington, but has been forgotten by today's venal, race-baiting leeches. What's more, it's been accidentally tried in powerfully racist environments far worse than anything we see today.  This magic elixir was so effective at destroying discrimination that the racists had to legally ban it. This magic wand?  Free and open capitalism. The Power of Cheap Consider a fair-sized town in the Jim Crow South, one large enough to have several competing stores of major types.  No doubt the main street would contain a store run by a bigot, offering goods "For Whites Only."  He'd have a good business selling to other bigots. In the South, however, at least a third of the population was black.  By refusing to serve an entire race, this bigot shrank his potential market by a third. Now consider another greedy, bigoted individual.  In this case, his greed outweighs his bigotry: he doesn't like black people either, but he can't resist the color of their money.  Unlike his competitor, his store is willing to serve blacks. This lesser bigot may accept black customers, but he doesn't like them; he may treat them rudely.  In a town of any size, though, there's bound to be another store run by someone who acts polite to customers of any color.  Where will the black people shop?  At the store that a) is willing to deal with them and b) that treats them like human beings - obviously. The bottom line?  There is a significant business advantage to a store owner who does not discriminate against customers and who treats everyone well.  Over time, the non-racist businessman will do better than the racist one. This advantage isn't just seen with customers.  It's even more powerful with employees. Like anything else, employment is subject to the laws of supply and demand.  If there are more workers available, wages go down; fewer workers around, and they go up. A business which refuses to hire blacks has cut itself off from a fair-sized pool of potential employees.  The laws of economics dictate that the employees it does hire will, on average, be paid more than if the pool were not artificially restricted. Again, over time, the non-bigoted business will have higher profit margins, lower prices, better employees, or some combination of the three than the bigoted one; naturally, more and more customers will gravitate to it as their greed overpowers their bigotry.  Each bigot will suffer the penalty of his own folly, with no government intervention whatsoever. This all sounds nice in theory, but does it work in practice?  Yes, it does. The Flawed Economics of Racism If the South was as racist as generally portrayed, why were the Jim Crow laws necessary?  After all, if all the white folks were racist, they wouldn't want to do business with blacks anyway.  No legal requirements would be required. No, the laws were put into place by powerful racists who were being undercut by thopse who acted non-bigoted just as described here.  The only way to make bigotry pay is to make it the law of the land, enforced upon all equally whether they want it or not. The apartheid South African government had the same problem.  The racist authorities fought a constant running battle against companies and employers who wanted to save money by hiring blacks who were just as skilled as whites to fill jobs that were "reserved" for whites.  This didn't apply merely to janitors or line management; as the Washington Post reported in an obituary a few years back: Hamilton Naki, a former gardener who was so skilled in complicated surgery that he helped in the world's first human heart transplant -- but had to keep this secret in apartheid South Africa -- died May 29 at his home near Cape Town. He had heart- and asthma-related problems. He was in his seventies. "He has skills I don't have," Dr. Christiaan Barnard, who performed the heart operation, told the Associated Press in 1993. "If Hamilton had had the opportunity to perform, he would have probably become a brilliant surgeon." Barnard asked Mr. Naki to be part of the backup team in what became the world's first successful heart transplant, in December 1967. This was in violation of the country's laws on racial segregation, which, among other things, dictated that blacks should not be given medical training nor work in whites-only operating theaters nor have contact with white patients.  [emphasis added] The first heart transplant recipient, Louis Washkansky, received extra days of life thanks to Mr. Naki's illegal skill.  What's more important societally, though, is that the hospital received decades of services from a brilliant surgeon for the price of a gardener - Mr. Naki's role had to be hidden from the authorities until the end of apartheid. It was only because of the law that Mr. Naki was not able to practice medicine publicly, but he was able to perform surgery on a white person in what was supposedly the most racist society on Earth!  Money trumped dogma; money trumped bigotry, in this case and in how many more lesser-known ones! - money trumped the law.  It usually does.  Funny about that. Time's Up for Legal Racism The evil laws of Jim Crow died decades ago, and far more evil slavery long before that.  Today, we suffer under the less vicious but still damaging racism of affirmative action. It's easy to understand why: it's in the interests of powerful racists like Jesse Jackson and Al Sharpton to continue to con black Americans into believing that they're being kept down by "The Man."  They are, but not by the white man; today's white men and women couldn't care less what color you are if you do the work well for a decent price, as witness the hordes of illegal Mexican immigrants doing all manner of things for low pay under the table. No, America's blacks are being kept down by self-appointed black leaders who've managed to get put in place an insidious system that promotes the incompetent and devalues the competent.  This is bad for competent blacks who don't get the respect they deserve; bad for incompetent blacks who perpetuate old stereotypes; bad for other races who see their rightful jobs go to less qualified members of preferred races; and bad for America because it makes us hate and fear each other. The blunt hand of government is no solution to our racial problems; it only makes problems worse.  Government can and must only be entirely color-blind in every way; in a free society, no governmental preference or discrimination based on race can be tolerated. Then, let's trust to the invisible hand of the market to take care of racist bigotry.  It works wherever it's tried, even where it's not welcome.  The only trouble is, that wouldn't empower or enrich our greedy elites who can't stand competent competition. Reader Comments The men and women in government, those with a little power and are called "The Government" want the hate and fear to continue. Al Sharpton, Jesse Jackson, Barry Soetoro, Louis Farakhan, and their like, need the hate and fear so that they can continue to collect "checks in the mail" money from the people who think the hate and fear comes from someone other than the likes of Reverend Wright. Thank you, Robert Walker June 13, 2011 10:25 AM This is good: June 13, 2011 10:31 AM I think this article makes a lot of sense. I agree with the general theme, and agree to a large extent. However, I have lived in the south. Louisiana in the 1960, and then deep southern Georgia, Thomasville from 2003 until 2008. From personal experience I can tell you that the "Plantation mentality" still dominates there. Not only is the racism deep and still powerful, but the entire 'serf/class' social structure is still prevalent. The natives to the area may be polite and all smiles on the surface, but they are a deeply traumatized people, still longing for antibellum heritage, still deeply racist against any but whites. They are in effect still fighting the Civil War. One has to live there and become close with these people before it comes out. Perhaps in another ten generations this will fade away--but it certainly hasn't yet. June 13, 2011 11:41 AM Where these people such strong racists that they wouldn't buy from a black merchant who had the best goods? Or were there no black vendors around? June 13, 2011 12:33 PM There was only one "black merchant" in the town, a fried chicken lunch place at the end of town. It had a good business--proving Petrarch economic theory. There were of course hard core Dixienuts that wouldn't be caught dead there. The racism was subtle from the outside...they would refer to blacks as "Democrats" {Lol}, but in more private conversations with people you knew well the N-word would flow like a Mark Twain novel. June 13, 2011 1:10 PM Saw this via Reddit and had to respond though I shouldn't waste my time on you racist <expletive deleted>. Since it's obvious I have to teach Affirmative Action 101, here's the FACTS you need to know about it before applying your perception to it. Because as with anything, if a debate is to happen, all parties need to at least have a basic understanding of it. You believe that the whole point of affirmative action is to give jobs to people who do not have the credentials to get them otherwise. Affirmative Action does not give jobs to unqualified people. It gives jobs to EQUALLY qualified minorities to offset the bias and discrimination inherent in hiring practices. Some facts: Whites hold over ninety percent of all the management level jobs (these are the people who do the hiring) in this country (1) Whites receive about 94% of government contract dollars (2) Whites hold 90% of tenured faculty positions on college campuses (3) White men with only a high school diploma are more likely to have a job than black and Latino men with college degrees (5) - just to translate this into idiot-speak, this means that lesser qualified white men are more likely to have a job than black and Latino men with college degrees. How anyone could know this information and STILL RAIL AGAINST affirmative action is beyond me. It's either a profound ignorance of the actual data that illustrates why affirmative action is so important, or it is a blatantly racist belief that despite these facts, minorities aren't as deservince as whites. Either way it nauseates me that so many white folks are so ignorant of the data, yet they constantly think their opinion on affirmative action actually makes sense. Most whites who have your opinion watched American History X, heard Ed Norton's fathers speech about affirmative action at the dinner table, and thinks it makes total sense! Well, it does if you don't know a <expletive deleted> thing about the data behind affirmative action. Next time you want to have an opinion about something, try having an educated opinion and read a <expletive deleted> book first. (4) Sylvia Hurtado and Christine Navia, "Reconciling College Access and the Affirmative Action Debate," in Affirmative Action’s Testament of Hope, ed. Mildred Garcia (Albany, NY: SUNY Press, 1997) (6) Devah Pager, "The Mark of a Criminal Record," American Journal of Sociology 108, 5 (March 2003) (8) "Young White Offenders get lighter treatment," The Tennesseean. April 26, 2000 June 13, 2011 1:30 PM <expletive deleted>That is an interesting set of information, facts and opinion to get from you. I find it curious to be called a racist as a poster on this site. Isn't it rather a quick off hand 'pre-judgment'on your part? You are part of a counter social engineering operation, it would therefore be educational on your part to understand social engineering on a larger frame. The heat of your post tells me that you don't have such a larger perspective. Part of what you fail to comprehend is the way inwhich affirmative action has been put to work has been as a purposeful divide and conquer operation by the High Cabal, using the Hegelian dialectic. This is a deep subject, one that you no doubt fail to grasp, as you have been so quick to throw out the term "racist" and to flame with your <expletive deleted><expletive deleted><expletive deleted>, showing an emotional attatchment and a lack of rhetorical skill. You have valid points, ones that you have now wasted by this jejune attack on perhaps would be converts to some of your points. June 13, 2011 1:57 PM ~Rod Serling's closing narration for, the Twilight Zone episode, "The Monsters Are Due On Maple Street". June 13, 2011 2:09 PM "This magic wand? Free and open capitalism."~Petrarch This is a huge and complex debate, the actual meaning of 'Capitalism'. Technically "capitalism" is making money off of money. It has nothing to do with trading money for goods in place of barter. The Capitalists are the bankers and the speculators, not the merchants. The US is considered a 'Capitalist Society' because of its banking and trade in stocks and bonds on Wall Street. This is the engine that runs the 'capitalism' aspect of the economy. The use of fiat currency by the merchants does not make them 'capitalist', they remain merchants until they too join in on the casino that is 'Capitalism'. 'Capital' means 'money'--in this instance that is the fiat currency borrowed from the Federal Reserve--a private corporation. Very few have any deep understanding of money in the US, as very few have any deep understanding of history, because this is a Public Relations Regime run by the High Cabal, and what is taught is simply a mythos to keep everyone ignorant and divided. June 13, 2011 5:44 PM So Sansdiety...from your post...I am not sure what to take away from it....are you advocating equal rights or extra rights? Because I am really confused. Here are some mantras I want you to incorporate into your thought the next time you try to make a counter point, you do not come off as some true believer....(you can never have a discussion with a true believer) (1) Correlation is not causation (2) Absence of evidence, is not evidence of absence. (3) You attract more flies with honey than vinegar, so make your points accordingly (calling people racists... Perhaps there are more white people are applying for jobs...I mean there are more white it makes sense that there would be more OF THEM in the workplace. Perhaps in white culture you are not considered a chump, sucker, oreo, a "sell out to the man" or an "uncle tom" for wanting to get a job. I would be curious to your insight on the NBA and the hip-hop music industry then. I see the ranks of the whites, native americans, and asians grossly under represented in those fields. June 13, 2011 7:14 PM His/her moniker, "Sansdiety" would seem an attempt at sansdeity, which would say a lot about his view of theologhy as well...unless he/she is without a diet...which would be quite thin in itself. All of the "<expletive deleted>" was 'clever' though, reminded me of the Nixon Tapes transcriptions. A hit and run driver no doubt. June 13, 2011 8:50 PM All very interesting, although none of that proves racism from the information that you presented, granted I did not look into the details of the studies which may indeed prove racism, there are simply alternative explanations that could result in those statistics. All of that data however is in no way related to the argument presented in the article. At no point did the article attempt to argue that racism does not exist in the world. Therefore arguing that racism exists is arguing an agreed upon premise. That premise being that racism does exist. Secondly I saw nothing in the article that can be described as racist. Racism is the belief that a person is less good, intelligent, ect due to ones race. The article in fact is the opposite of racist. It states that if given an even playing field blacks would show themselves too be equal in ability. The point of the article which you seem to have missed is that only through equality of law can one achieve equality of society. Inequality of law, in either direction, causes resentment and, eventually, hatred. It goes on to argue that inequality of society between races can be broken down by simple greed. People that are actively racist will lose economically to those that are passively racist and those that aren't racist. Once that happens racist people, both active and passive, will be around blacks that are earning their way in life on their own. They can no longer believe that the blacks are only there because of legal support. They will be forced to confront the fact that blacks are capable of earning their way equally well as whites. Thereby slowly decreasing racism until it is a thing of the past. Under the current systems many blacks believe they are owed something and that whites are holding them down. This results in many blacks not believing that they can not succeed. Which causes many blacks to not try as hard, after all why play if you can't win. Those blacks that do succeed are seen by many whites as having gained an unfair advantage. This causes many whites to see their opportunity as being stolen from them, not due to superior ability but rather due to legal favoritism. Thereby perpetuating the belief of white superiority by many whites as they see data showing blacks failing, in their eyes, despite of unfair legal protection. It may feel good to 'do something' about inequality but as with so many well intended actions it frequently only makes things worse. June 13, 2011 9:21 PM Thomas Sowell, a black columnist, wrote: June 13, 2011 9:55 PM jonyfries, very good comment. It seems it can be summed up with that old saw. The road to Hell is paved with good intentions." I would add that the road signs on that road are often purposely manipulated by those who fawn good intentions, misdirecting those who do have good intentions. These people are often called 'politicians', and most politicians are lawyers, and most of these lawyers have connections with bankers, and that it is the bankers banker that has been seen as the hand that holds the strings to this whole system. June 14, 2011 12:24 AM "Third World countries are poorer today than they were when they were ruled by Western countries, generations ago."~Fred Pray tell, what thrid world nation today is not still under the grip of Neo-Colonialism? In fact what nation of any sort is not ruled by BIS, IMF, and the global financial oligarchy? The ballance of an indigenous culture, once fragmented and spun out of control by Malthusian attack can never right itself again, while the present paradigm is maintained. June 14, 2011 11:14 PM So Willie, you think that global poverty in places like Africa which were once colonized is the fault of the Westyern powers who did the colonizing? That if they'd been left alone, they'd be rich today? June 14, 2011 11:53 PM "That if they'd been left alone, they'd be rich today?" "Rich"? By what standard? Western materialist standards? A rich and fulfilling life of ballance and sanity, is not what I see in the empire the west has created. I would note that this pathological system is about to explode in your face. Good luck when the proverial fit hits the shan. June 15, 2011 12:15 AM Despite the joy that people take in thinking about 'what might have been's, there is no way to know what Africa would be like today with European colonization. All that we can be certain of is that Africa is different than it otherwise would have been. It does not matter if Africa would have been better or not. History followed a different course, instead of finding long dead persons to blame worry about the future and how we move from the present to a more equal and prosperous future. June 15, 2011 10:17 AM jonyfries, Africa is not in anyway free of western colonialism yet even today. All the worlds nations today are still under the grip of Noe-Colonialism.All ruled by BIS, IMF, and the global financial oligarchy. This is the NOW point you urge us to look at. History isn't dead, it is sitting heavily on everyone of our shoulders. June 15, 2011 12:30 PM A point on REAL HISTORY, and the architecture of modern political power, compared to the lollipop history in textbooks and entertainment: A Study in the Hegemony of Parasitism By Eustace Mullins 1984 [small portion] It explains the secret writing of the Federal Reserve Act by Paul Warburg of Kuhn, Loeb & Co., and the even more secret deals which caused it to be enacted into law by Congress. It explains how the United States could fight World War I with Paul Warburg in charge of its banking system through the vice chairmanship of the Federal Reserve Board; Bernard Baruch as dictator of American industry as Chairman of the War Industries Board; and Eugene Meyer financing the war through his position as chairman of the War Finance Corporation (printing government bonds in duplicate); Kuhn, Loeb partner Sir William Wiseman with Col. House correlated British and American intelligence operations; Kuhn, Loeb partner Lewis L. Strauss was acting head of the U.S. Food Administration under Herbert Hoover. Meanwhile, Paul’s brother, Max Warburg, headed the German espionage system; another brother was German commercial attache in Stockholm, traditional listening post for warring nations, and Jacob Schiff had two brothers in Germany who were financing the German war effort. It was a classic case of a “managed conflict”, with the Rothschilds manipulating both sides from behind the scenes. At the Versailles Peace Conference, Bernard Baruch was head of the Reparations Commission; Max Warburg, on behalf of Germany, accepted the reparations terms, while Paul Warburg, Thomas Lamont and other Wall Street bankers advised Wilson and the Dulles brothers on how “American” interests should be handled at this all-important diplomatic conference. June 15, 2011 8:24 PM Well, as a South African, I feel obliged to stick an oar in here. I'm afraid to say that this article totally misunderstands how South Africa operated, and misunderstands racism generally. Racism isn't just a "bad thought"; it's a tool, a mechanism for justifying exploitation. Pretty much all whites in South Africa ate food prepared by black people, lived in houses built by black people, used products made by black people, shopped in stores staffed by black, and had black maids and servants in their homes. With the exception of a tiny minority of radical Afrikaaners who wanted an all-white society, total separation was not the goal, economic exploitation was. Getting a heart surgeon for the price of a gardner wasn't a failure of apartheid, that was the whole point. And the reason he was barred from being actually employed as heart surgeon was precisely so that he would stay cheap. Basically this argument is complete bollocks, but as it is accompanied by the description of the likes of Sharpton as "powerful racists", I don't think the author of this "article" is really much interested in reality. It makes a bogus argument and draws a bogus conlusion right out of the stock material used by apologists for racism. Petrarch, whoever you are, you would have been right at home in apartheid South Africa. Everyone one of the arguments you've deployed about how blacks are being kep down by black leaders was used by the old National Party state. Capitalism is not the enemy of racism, it is it's ally and partner. South Africa was an extremely capitalist state; it had no public health and very limited social services, for example. And apartheid was just a method for suppressing labour costs. South Africa was just a compressed version of the same exploitative relationship that exists between thre West and the Third World today. June 16, 2011 4:50 PM Well now, this is interesting indeed. But we need to understand where you're coming from in order to evaluate your argument, and I'm frankly a bit suspicious. For one thing, are you arguing that Sharpton is not powerful? Or that he's not a racist? He's not powerful compared to (say) Obama himself, but he's pretty darn influential compared to you or me. At the very least, he gets an audience whenever he pleases. And you've totally ignored Petrarch's primary argument: OF COURSE apartheid was racist, it was the LAW, put in place by racists for the purpose of exploiting blacks. Just like Jim Crow. Yes, the heart surgeon was exploited - but that was possible ONLY because he was legally repressed. If the racist laws weren't there, his skills would have been bid over and his compensation would have wound up where it properly belonged, along with anyone else's willing to work and improve themselves. In both apartheid South Africa and the Jim Crow South, it wasn't illegal for blacks to work - they were expected to. It was simply illegal, explicitly or implictly, for them to hold any jobs above the most menial. Nothing capitalistic about that. In fact, it's the epitome of socialist exploitation, forcing people to work for the benefit of others without proper negotiated compensation. June 16, 2011 5:08 PM Sharpton is not a racist. That claim is simply absurd polemic. I have not ignored Petrarch's argument in any respect. It is absolutely true that if Mr Naki had been an equal citizen of the state he would have been economically better off. But you're missing the point: that fact that he WAS discriminated against was not only perfectly viable within the capitalist system, but that system actively benefitted from it. In exactly the same way that it benefits from poverty wages in the Third World today to produce cheap products for Western consumers. Furthermore, Petrarchs argument goes further, asserting that capitalism is inhenrently antagonistic to the sort of repression exhibited by apartheid. But this is not true, because although it did mean that white workers were paid much more, that didn't really matter because there were so many black workers. Overall, capitalism thrived because apartheid reduced labour costs; all that money paid as high wages to white workers was simply cycled back to the companies in return for the products manufactured on the cheap by black labour. The companies made fat profits; the white workers lived relatively high lifestyles; the only people who suffered were the blacks, and seeing as they couldn't vote that didn't matter. It was a win-win system for capitalism. There was no demand by capitalist activists or agitators to dispose of apartheid, that was totally driven by the socialist Left. Contrary to your final claim, it is not socialism that is an exploitative system, but capitalism. Socialists regard everyone has having due right to the product of their labour, while capitalism transfers ownership of that product to the provider of capital. Advocates of capitalism were the heart and soul of the apartheid system. Don't forget that South Africa was originally Dutch colony, and that the Dutch were amongst the earliest and most zealous exponents of capitalism. South African state was absolutely committed to capitalism in theory and practice, and at no point did this ever translate into a hostility to apartheid. Indeed it regarded itself, more or less correctly, as one of the hot zones in the Cold War between capitalism and communism. Petrarch's argument is just plain wrong. I am a Marxist, and proudly so, and it was seeing capitalism exposed for what it really was in Soth Africa that made me so. Capitalism is nothing more than systematic exploitation, and apartheid was merely one of the its tools. June 16, 2011 5:39 PM @SharpFish said: "Sharpton is not a racist. That claim is simply absurd polemic" Surely you jest. Here's an overview on Sharpton's (recent) racism: That should get you started. June 16, 2011 5:43 PM And 'round and 'round goes the Left/Right carousel...ridiculous fairytale BS--both Marxism and Capitalism. One who gets to the bottom of the history of this realizes that "Capitalism" created "Marxism" as the 'Controlled Opposition'. SharpFish should look into Milner and Rhodes, and the "conservatives" here should equally--as well as to the machinations of the Rothschild interlink with the Rockefellers in the Anglo-fication of the Eastern Establishment in the US. While you people throw stones at one another the High Cabal is sewing up the loose ends of their global gulag, where it matters not what color you are--you all end up slaves. June 16, 2011 6:21 PM Michelle Malkin is a raging lunatic, and while you can take exception to some of what Sharpton says, to describe it as "racist" is to abuse the term. And indeed it is a matter of substantial irony that you should call on anything by Malkin as if she had any kind of credible position on racism, given her support for apartheid in Israel. I know I'm not going to make any headway here because I know that this is really just a case of blaming the victim, and those of you who are committed to it aren't going to be persuaded by anything I say. But I will point out that exactly the same charges were levelled at Nelson Mandela, for example, and so as far as I'm concerned this is just a standard set of apologia for bigotry. And I'm not at all surprised that this article has attracted such apologists, as that's basically what it was for. But I don't have to stand by and let the reality of South Africa be exploited for that purpose. You do not have the right to hijack our history and distort it to fit some odious right wing agenda. June 16, 2011 6:30 PM Netanyahu's Rabbi charged with raping 12-year-old girl Now if this does not reflect on Nutenyahoo's character—How do you atone for the charges against the Kenyan for his association with Reverend Wright? June 16, 2011 6:35 PM It is ludicrous, and would be laughable if the issues weren't at a critical point, that neither the Left nor the Right has a reasonable responce to the questions and assertions outside of their mainstream boxes. Both the "Right" lunatics here, and the "Left" passerbys that happen onto the sight have the same reaction...their eyes roll back in their sockets and their brains flatline. Of course this will mean that the real crisis, that of the global elite agenda will hit both of these 'sides' as an utter surprise, even though it is happening in plain sight. What? Do you actually believe the economy is crashing by mistake? By incompetence? The cynical "we won't do it again," is a bit of a stretch. Don't you think? Don't you think? That seems to need repeating here... June 16, 2011 7:16 PM "I am a Marxist, and proudly so" No point in arguing with someone who is "proudly" Marxist. They are either too incompetent to understand the argument or too evil to care. He said he was Marxist. Debate over, he lost. June 16, 2011 7:39 PM Ben, that is a simpleton's non-argument. Now you both "lost". June 16, 2011 7:45 PM You're right of course. Anyone that is proudly Marxist and believes that Capitalism is the *cause* of racism is hopeless. But it's fun to yank their chain and watch them fumble around. June 16, 2011 7:47 PM Being proudly Marxist is like being proudly flat-earther. And yes, those idiots still exist too: If you're proud of something that is a universal failure, only life itself can convince you otherwise. So we'll wait and let life change DullFish's mind. June 16, 2011 7:50 PM You "conservatives" here are the Synthesis. Synthetic, plastic, immitation, not real. Such is life within a false paradigm. June 16, 2011 8:26 PM And yet you stay, Willy, and continue to convince us of our ignorance and "false paradigms" over and over again. So what does that make you? Lonely, I guess. Give it up. The intelligence of this community is far higher than the normal dregs that you're used to brainwashing. Move along. Sites like InfoWars exist for people just like you. June 16, 2011 8:29 PM Fishy, you clearly don't understand either Marxism or capitalism. "Under capitalism, man exploits man. Under Marxism, the opposite is true." What's more, capitalism and Marxism/socialism are not a black/white dichotomy, they are a continuum. There was nothing whatsoever free-market-capitalistic about either apartheid or Jim Crow, because they were legal interference in the free market: they prevented certain individuals (black people) from freely offering whatever goods or services they wished to provide, and prevented their customers from freely purchasing them. Nothing free about that market - an unfree market was the whole POINT. Obviously there were free market aspects to the old South Africa, such as between white people. There are also free market aspects of Communist China, pretty significant ones, just as there are increasingly Marxist aspects of the increasingly controlled and regulated American economy. Neither are purely free market or purely Marxist; they are passing each other in opposite directions. But to the extent that apartheid and Jim Crow interfered in the ability of free individuals of whatever race to participate in whatever economic transactions they freely chose to do, they were ANTI-free-market. June 16, 2011 8:31 PM "The intelligence of this community is far higher than the normal dregs that you're used to brainwashing."~twibi "Intelligence" is what you call it aye twibi? No, hardly "lonely," I have a blog, we share in our ideas like those of you here. But I find "preaching to the choir," is not enough. You would be a fish out of water on any other site without your backup squad. And the only "argument" I ever get is the same zip/nothing you just laid on me. Why, because you have no valid counter. So you want me to leave you alone. The obvious ignorance of the architecture of modern political power is obvious here. That is the reason you can only counter "the Left." You have no overview of both the left and the right. Naivete is not innocence. And going along to get along is fine... ..until you get where they are taking you. That destination lies straight ahead. I guarantee you aren't going to like it. You can puff yourselves up with your false bravado until then. You won't have the luxury of saying you were not warned. June 16, 2011 8:47 PM When every question put on the table comes down to a Left/Right dogfight, or a Demoskunk/Repukelikan tango, it is obvious that the divide and conquer scheme of the oligarchs ruling this nation is working like a charm. It's like reading the rantings of Pavlovian dogs. The Petro-Dollar is dying a slow death. With its disappearance will come the Third World to the United States.~Jim Willie David Rockefeller, Memoirs, page 405 June 16, 2011 11:09 PM Although many fail to realize it, all is not well in Wonderland. Most are still lulled by TV and mindless entertainment, whizzbang gadgetry, and delusional mantras of “recovery”... Meanwhile on the croquette lawn, shock and awe austerity rises in the purple face of the enraged Red Queen. When this austerity finally bursts the over inflated bubble of some 1 and a half Quadrillion dollars, will you keep your head? June 16, 2011 11:48 PM Ben wrote: "Being proudly Marxist is like being proudly flat-earther." Hahahaha. You guys are so living in the past, and the really funny part is that you are so oblivious to the fact. Patience wrote: Patience, I understand them both extremely well. Where you make your mistake is here: CAPITALISM ITSELF is anti-free market. Because it systematically appropriates the product of labour from those who produce. Capitalism is not an expression of human freedom, it is a system of exploitative class rule. The fact that apartheid and Jim Crow could work so well with capitalism absolutely confirm this. There is absolutely nothing in capitalism which contributes to human liberty or autonomy. Capitalist ideology just uses "free market" as a slogan for the untramelled right of capitalists to exploit labour. Both apartheid and Jim Crow assisted in that exploitation and were therefore perfectly in line with capitalism. If you want a real free market, a society of free people, freely trading, and freely entering into voluntary transactions, the first thing you need to do is kill capitalism. What you in fact need is a communist mode of production. June 17, 2011 6:08 AM "CAPITALISM ITSELF is anti-free market" Ha! Patience, are you *really* going to keep arguing with this clown? "CAPITALISM ITSELF is anti-free market" I had to read that again just to get another good laugh out of it. June 17, 2011 7:58 AM "CAPITALISM ITSELF is anti-free market. If you want a real free market... What you in fact need is a communist mode of production." Hmm. OK, I declare myself a Marxist - and therefore, in favor of a capitalist economy. In other news, black is white, up is down, and left is right. Oh, wait a minute - Willie already believes that last one. Welcome to Bizarro World! June 17, 2011 8:23 AM You lack of comprehension is truly astounding Patience. Your argumentation is sixth grade playground level. While I have an argument against socialism, I also understand that "Capitalism" is NOT 'free market', the Capitalism of that las hundred years has been monopolism, and centrally controlled--like your brainwashed mind. What utter chumps. June 17, 2011 9:06 AM The interesting thing about capitalism is that it actually achieved what Marxism set out to do: allow the laborers to share in the fruits of production. For example, the wealth of Walmart is owned by millions of middle-class shareholders as part of their 401k or retirement funds. This includes both the people that "give" their money to Walmart, by buying its products, and those that work there. Additionally, the low costs that Walmart's capitalism created is realized by its laborers and customers. Here's a great article explaining why capitalism, and free enterprise in general, has beaten Marxism at its own game: June 17, 2011 9:14 AM Is this REALLY where you meant to send us with that URL Sam? May 2007 Socialism, Free Enterprise, and the Common Good Rev. Robert A. Sirico President, Acton Institute for the Study of Religion and Liberty At any rate, using Walmart as an example for anything positive is the biggest load of tripe I have ever read. What a collection of nimrods... June 17, 2011 9:57 AM Hi Willy, Yes. Now do yourself a favor and _read it_. June 17, 2011 10:19 AM Hi Sam, I did. June 17, 2011 12:22 PM Lol. But at least, Sam, I give you credit for acknowledging what "Marxism set out to do". That's a much greater degree of insight than that exhibited by anyone else here. Of course, I would still say it's ridiculous to argue that capitalism has "beaten" Marxism at anything - indeed, given the recent crisis, Marx' critique of capitalism has been reaffirmed for the umpteenth time. But what really sticks out from this claim is that apparently workers are only to be allowed a SHARE in the fruits of production. Why should that be, when all of production rests on their labour? It's not enough to have a share; we want it all. We made it all, why shouldn't we have it? Why should a parasitical, noncontributive capitalist class have any claim? I have read the article you linked; to provide a proper counter-argument probably wouldn't be worthwhile. But while this article is much better informed than most, it is still completely mistaken. For example, the depiction of Bernstein, while not faulty is as such, is incomplete, and it fails to acknowledge the critiques to which his position were subject. Bernstein's argument was destroyed by Rosa Luxembourg, and Sirico is therefore not entitled to use it as a sort of uncompleted realisation of the invalidity of the socialist position. I commend you though on finding something as detailed and serious as this, rather than depending on the shrill mouthpieces and stereotypes that so many rely on for the substance of their argument, and which we see above. But my challenge to you now is to go out and read Marxist material yourself, and to draw your conclusions rather than relying on the analyses of others. June 17, 2011 12:43 PM "what "Marxism set out to do".~SharpFish What Marxism set out to do is a much deeper subject than simply analyzing the works of Marx. Marx after all is not all that original in his work Das Capital. What is more beneficial in understanding "Marxism" is the understanding of who was in the background promoting him, and what their motives were, and are. When such an analysis is made, we find lurking in the background a combine of secret societies interlocking in a most complex matrix, and ultimately leading to the Perfectibles, who infiltrated the European Masonic lodges of the 18th century. At any rate, after years of research by many from that era forward, it can be said with a great degree of certainty that it is high financial capital, in particular the House of Rothschild which is the hand pulling the strings and funding these movements. In the final analysis, what "Marxism" set out to do was to generate a 'controlled opposition" to this high international finance. One that could be manipulated into unwittingly serving the interests of high finance and coopting any real resistance that was to come along. For some clues into this look into the Left and Right schools of Hegelianism, a split manufactured by Hegel's own teachings and his star students. June 17, 2011 1:22 PM Hi again to Sam, I am quite familiar with Hillsdale College. Whether you are aware of it or not Hillsdale is part of Neocon think tank activities. One with the purpose of demonizing Islam for the benefit of the fraudulant "war on terror". It's luminaries are in the main the usual suspects behind PNAC and the Rand corporation, the Crystal's and thier Daily Standard, etc. These people come from a Marxist background themselves--all deciples of Trotsky and his 3rd Internationale. Almost all of this leads back to Leo Strause. They are all 'Statists'--Hegelians, who believe that the "state in the footsteps of 'God' on earth." This means that any "Christians" involved with this cult have been duped. Not that I expect anyone to follow leads and take anything seriously here, as all on this site seem to have swallowed the MSM kool-aid. But the history is in the open record for any with some slight bit of curiosity left in their head. June 17, 2011 1:35 PM Normalcy Bias Normalcy Bias; this is the psychological pathos of the conformists, the bean-counters, and those who go along to get along. It is indicated by extreme naivete and a dearth of imagination. Such personalities crave empty entertainment, convenience, and unfettered certainty. The words, “tinfoil conspiracy nut” are set like a trigger, to be repeated like a Chatty Cathy doll at the slightest hint of suspicion of the system they float around in like party balloons at a kids birthday at Chuckie-Cheese. Lack of imagination creates a type of memory loss, the inability to imagine what it was like before one became adjusted to the present. This creates a type of mental compartmentalization. In-congruent information is isolated from itself to prevent cognitive dissonance. The information is still there subconsciously however, which results in neurosis. And it is that neurosis which is acted out as denial. “Lack of curiosity in otherwise intelligent people is caused by fear. This fear is of finding out something that on might not want to know and face. It is an attendant effect of long term normalcy bias, in the case of the US it is caused by the strategy of tension generated by social engineering.~ww “The normalcy bias is also known as the ostrich effect. It is also sometimes known as the incredulity response and analysis paralysis. In situations of extreme danger, some people enter a mental state that is known as the normalcy bias. In this state, people deny that what is happening to them is really taking place.” June 17, 2011 2:21 PM To the ones that espouse communist ideals, I only have one thing to say: F U! I grew up in a communist country, and it was complete state control. Fear of the state was the way of life. Communism is great, it means some "chosen" ones at the top control the state-owned industries and the workers truly are slaves, because the state and the bureaucrats reap all the benefits. And let's not forget the brainwashing, since you have to be constantly reminded your hard work is for the "good" of the country, while you live off food rations. Meanwhile, the politicians are running around in luxury cars and living in mansions, while you get thrown in jail for daring to ask for more food. Seriously, do you actually mean this? Maybe because if they don't make any money off our work, they don't need to employ us. Why would anyone give me a job if not for them to make more money as well? I am sure you think that the state should own the industry, but like I already pointed out, it just means someone else would get rich off my labor. Communism fails on so many aspects, that if you look at history all it has created is poverty and authoritarian states. And really wealthy state-sponsored oligarchs. June 17, 2011 4:18 PM If it is the private sector which is employing as well as being employed, what is the need of a financial class 'providing'the "money" as debt. Creating just the amount of fiat script to cover that "money" itself--but not the amount to cover the INTREST on that debt? I think if you had a better grasp on how the ponzi scheme of fractional banking works that you would have an entirely different opinion of "Capitalism." Rather than think in the duality manner of the dialectic of Capitalism/Comminism, why not think back to the concept that "money" is just a conveinience to barter--actual free-trade, not the Newspeak version propagated by the financial elite. June 17, 2011 4:39 PM My last comment is directed at Alin_S, and the first quote is from his post. June 17, 2011 4:41 PM Again addressing Alin_S, What needs to be parsed is the distinction between the entrepreneur and a capitalist. Between 'finance' and 'trade'. By 'trade' I do not refer to the casino of Wall Street. I am talking about actual trade between owners and buyers of goods and services. June 17, 2011 4:50 PM Willy, I know you constantly have to mention the financial conspiracy and a international nefarious cabal, but my post had nothing to do with finance. Capitalism has nothing to do with banks, but banks are necessary to provide capital to those who need it. Now imagine a world where I save money or raise capital through other means, and then I open a business. No debt for me, and no Rockefellers making money off me. Here is an easy definition: An economic system that is based on PRIVATE OWNERSHIP of the means of production and distribution. Prices for goods and services are determined by the free market, and businesses are operated for the economic gain of the OWNERS. (I would like to think that I can be an owner one day, and I guess perhaps I am biased by such an ideal and you might even say a bit foolish for believing such things). I have never disagreed with you on the federal reserve, which encourages fractional lending and has hijacked our money plus our government. I think your point was also trying to hint at the creation of money, but again, my point had nothing to do with that. My point is simply this: communism sucks! And I will never ever live under communist oppression. You can take those as fighting words if you prefer... June 17, 2011 5:01 PM Alin_S, you say: Read your first sentence here. It defeats itself in a circle. In effect it is self cancelling. And the second is true, you have to “imagine” such a world because the “capital” you speak of is fiat debt based “money”. There is NO OTHER form of capital available in 'This World'...only the one you wish for the reader to imagine. I can indeed 'imagine' such a world. But know that one will not exist until one faces the realities of this on we exist in now and change it. By making the circular arguments you have above you are simply denying the real world, and playing make-believe, ie, “imagining.” June 17, 2011 7:06 PM But Alin, as you should realize the “prices for goods and services “are NOT determined by the free market. They are determined by a central controlled market—the Stock Market, which has manifold instruments of manipulation to play the prices. The 'derivatives' scheme, 'hedge funds', the casino techniques of betting on prices without even buying stocks: Spread betting on stocks and shares allows you to go long or short on a stock without owning. And these are only a few of the tools the elites have implemented to control the market. Again, it gets down to who the “OWNERS” are. The Owners are, again; the private banking cartel that you keep dismissing—they own the ability to write an amount on a ledger sheet and pronounce it “money”. June 17, 2011 7:22 PM Willy, I know it's hard to admit you are wrong, but you continue to go in a a circle and refuse to see the forest for the trees. Read the definition of capitalism that I provided. Based on this definition, this is how I CHOOSE to see it. Capitalism to me means private ownership (not state-owned), prices determined by free market (not monopolies), and benefits the owners (not the state or bureaucrats). Therefore, capitalism does not need banks. Additionally, the structure of the finance system is a whole different topic. However, since I have to say this again, banks are needed to provide money to those WHO NEED IT. Now, if you want to get into the nuances of my statements, go ahead and over-analyze. I don't have to imagine a world where I don't need to take on debt. Here is another scenario for you: I inherit a bunch of money and put that into a business, I become a business owner and by default I would be called a capitalist. Now I would be an evil business owner who would hire other people so I could make more money, or I don't hire any and they can all go unemployed. I think you and I both agree that we need to push the govt off our backs, but the grim realities of the world you live in have got you down. I simply choose to believe that capitalism works and corporations are not evil, but it's when they collude with govt that our lives are impacted typically for the worse. But I will not paint capitalism or all corporations with such a broad brush. I agree with you, I am aware of how our money is nothing more than govt debt which we have to pay back to this private bank called the FED. I think you assume that the readers of this blog are dunces, and have been living under a rock. We are all well aware of the illegitimacy of the FED, the unconstitutionality of the income tax, the military industrial complex, etc. I really wish you wouldn't think that you are the only one who has seen the light. June 17, 2011 7:43 PM Willy, this is becoming a debate less about capitalism and more about manipulation. Commodities and currency trading can absolutely affect our everyday lives, I don't think a wise person would really try to disagree with that. I don't think I ever said that I "dismiss" the banking cartel, I only said that you bring it up in every post even though we are simply discussing capitalism and the positive effects it has on our society. Just like anything else, in the wrong hands it can be abused and misused. I would like for you to admit that capitalism works, and then you can get into how certain factions are trying to gain power and wealth underhandedly. It seems that you are dismissing capitalism as this evil system simply because some people have decided to hijack it for their own benefit. For me, capitalism means that I can go open up an ice cream shop in my neighborhood, and I have the freedom to do so. For you, it means that some wealthy bankers are getting richer. I would like to see your solution to this problem, my solution is simply to get it while the getting is good. (That's a joke Willy) June 17, 2011 8:09 PM But that is my whole point in the first place. What you have been taught the definition of capitalism is not what is put in place and called capitalism. The ideal system you have in your head that you call capitalism, is a worthy concept and a reasonable way to do business, regardless of what you name it. What I am saying is that what has been CALLED capitalism from the inception on the use of the word has always been the manipulatory aspect we have discussed, with the Rhetorical cover story being the system that makes the best sense. All cons are sold that way, in economic law this is called a "Fraudulent Conveyance Racket". The historical record proves that the entire Federal Reserve System can by shown to be a Fraudulent Conveyance racket. The Federal Reserve System is obviously a centrally planned economy. This is NOT a “free market,” as their Newspeak rhetoric claims. Playing it for what it is worth is all any of us can do as far as personal survival tactics. However I think that trying to educated people as to the scam being played on them is worthwhile. That is my whole reason for posting. There are a lot of misconceptions being propagated, and that needs countering.~ww June 17, 2011 8:56 PM More simply put: The dictionary definition of "Capitalism" that the "Capitalists" have used is a commercial advertizement. That is how they explain their operation. But this is False Advertizement. Again history shows it to be a con racket. That is the reason, I dispute the advertized definition. Because it is their Sales Pitch but not what you are sold. June 17, 2011 9:04 PM Now, as far as Communism; the very same historical record I refer to proves that it is a created "controled opposition"... In other words Alvin, the very same financial power that runs this nation, runs the socialist opposition. The real enemy then is the International Banking Cartel: Capitalism/Communism/Total State = Totalitarian State June 17, 2011 9:09 PM The Final and Urgent Point: To move further into the present situation is to observe that there can be no reasonable argument against that the US is a totalitarian police state. It is no secret but for putting it so bluntly. This is a Panoptic Maximum Security State based on the openly announced strategy of FULL SPECTRUM DOMINANCE. That term, 'full spectrum dominance” is as in your face as is possible. What does full spectrum mean? It means it is total , total dominance. How much clearer does this have to be made out. This is not my language this is the state's language. You have received your invitation to the ball. You have been absorbed under its umbrella. Since 9/11 and the PATRIOT Act, the superstructure of this panoptic police state has been constructed over the head of the population. If one chose to pay attention the reality is out there everyday testifying to this. It is only turning away into denial that can make one blind to the so very obvious. All it will take to kick this machine on to full draconian force will be the shock of drastic austerity measures imposed. This will be an 'event', and it will ripple around the globe quickly. Many well researched analysts are saying this is not long in coming. How long? Not long, for "ye reap what ye sow." June 17, 2011 9:38 PM And a final comment to Sharpfish: Marx and Bakunin are both wrong, and their arguments between themselves irrelevant but as a historical footnote. Marx is wrong. The only thing that has ever changed about human beings is their technologies, and unless technology is allowed to “win” over the human being, and create the cyborg which eliminates the natural humans—mankind will always be the human being he is. All consensus is synthetic and temporary.~ww June 20, 2011 11:12 AM Alin S, You're confusing communism with state capitalism. Obviously, if that's where you grew up, you'll have been denied this critique, even though it goes as far back as the earliest days of those state capitalist societies. Politicians in luxury cars and ordinary workers in jail for asking for food, that's capitalism in essence. Can you think of any capitalist society that hasn't produced precisely this outcome? You say yourself, its a society organised by and for the interest of OWNERS, and that you aspire, one day, to being an owner yourself. Isn't that a confession that any capitalist society is the antithesis of democracy, that it is rule by the rich and for the rich? You admit that the only out you can see is to one day join their number. And in the meanwhile, like the vast majority of us, you can only be servant and a slave. You ask, why should they employ us? Fatuously you assert "they don't make money of us". Of course they do, why else would they employ us, according to your own logic? Only becuase they benefit. Running through your account of capitalism is a truth you won't acknowledge: that we are only allowed to support ourselves when it is in the interests of capitalists. We are no more free than any feudal serf subordinate to their local warlord, paying tithe and rent to someone who, fundamentally, does not work to support themselves. All value arises from human labour. As Adam Smith said, it is the original commodity from which all others are got. Capitalism cannot exist without workers; it exists for no other purpose than to seize the product of workers labour and channel it into private profit. Just like your state capitalisms, the few benefit from the labour of the many. Willy Whitten, I don't really want to respond to you, your brand of conpiratorial theory is essentially nonsense, and ironically, precisely what you denounce us for, a "false opposition". So long as you continue to believe in these shadowy conpiratorial groups you'll never do anything to actually change the real, material, world. But your last point I must address, your argument about technology. No political philosophy is as science- and tech-friendly as Marxism. It appears, after all, as an attempt to form a scientific theory about how societies change and develop. It is a specific scientific antidote to the pre-industrial, superstitious cult of capitalist theology. There is so much historical evidence against your wilder claims I won't bother going into it. Nobody who takes the topic seriously will be convinced by your garbage. June 20, 2011 7:54 PM Add Your Comment... 4000 characters remaining Loading question...
#ifndef FILEHANDLER_H #define FILEHANDLER_H #include <vector> #include <string> #include <fstream> #include <boost/bimap/bimap.hpp> #include "graph.h" namespace facebook{ typedef std::vector<std::vector<std::string> > Data; typedef std::map<std::string, int> ID2INT; typedef boost::bimaps::bimap<int, std::string> Map; typedef std::vector<std::string> Name; Data readFile(std::ifstream &fin, Name &name); Map createMap(Data data); socialgraph::Edges createEdges(Data data, Map map); socialgraph::Graph createGraph(Data data, Map map); } #endif
#include <iostream> #include <iomanip> #include <thread> #include <chrono> #include "icsneo/icsneocpp.h" int main() { // Print version std::cout << "Running libicsneo " << icsneo::GetVersion() << std::endl; std::cout<< "Supported devices:" << std::endl; for(auto& dev : icsneo::GetSupportedDevices()) std::cout << '\t' << dev << std::endl; std::cout << "\nFinding devices... " << std::flush; auto devices = icsneo::FindAllDevices(); // This is type std::vector<std::shared_ptr<icsneo::Device>> // You now hold the shared_ptrs for these devices, you are considered to "own" these devices from a memory perspective std::cout << "OK, " << devices.size() << " device" << (devices.size() == 1 ? "" : "s") << " found" << std::endl; // List off the devices for(auto& device : devices) std::cout << '\t' << device->getType() << " - " << device->getSerial() << " @ Handle " << device->getNeoDevice().handle << std::endl; std::cout << std::endl; for(auto& device : devices) { std::cout << "Connecting to " << device->getType() << ' ' << device->getSerial() << "... "; bool ret = device->open(); if(!ret) { // Failed to open std::cout << "FAIL" << std::endl; std::cout << icsneo::GetLastError() << std::endl << std::endl; continue; } std::cout << "OK" << std::endl; std::cout << "\tGetting HSCAN Baudrate... "; int64_t baud = device->settings->getBaudrateFor(icsneo::Network::NetID::HSCAN); if(baud < 0) std::cout << "FAIL" << std::endl; else std::cout << "OK, " << (baud/1000) << "kbit/s" << std::endl; std::cout << "\tSetting HSCAN to operate at 125kbit/s... "; ret = device->settings->setBaudrateFor(icsneo::Network::NetID::HSCAN, 125000); std::cout << (ret ? "OK" : "FAIL") << std::endl; // Changes to the settings do not take affect until you call settings->apply()! // When you get the baudrate here, you're reading what the device is currently operating on std::cout << "\tGetting HSCAN Baudrate... (expected to be unchanged) "; baud = device->settings->getBaudrateFor(icsneo::Network::NetID::HSCAN); if(baud < 0) std::cout << "FAIL" << std::endl; else std::cout << "OK, " << (baud/1000) << "kbit/s" << std::endl; std::cout << "\tGetting HSCANFD Baudrate... "; baud = device->settings->getFDBaudrateFor(icsneo::Network::NetID::HSCAN); if(baud < 0) std::cout << "FAIL" << std::endl; else std::cout << "OK, " << (baud/1000) << "kbit/s" << std::endl; std::cout << "\tSetting HSCANFD to operate at 8Mbit/s... "; ret = device->settings->setFDBaudrateFor(icsneo::Network::NetID::HSCAN, 8000000); std::cout << (ret ? "OK" : "FAIL") << std::endl; std::cout << "\tGetting HSCANFD Baudrate... (expected to be unchanged) "; baud = device->settings->getFDBaudrateFor(icsneo::Network::NetID::HSCAN); if(baud < 0) std::cout << "FAIL" << std::endl; else std::cout << "OK, " << (baud/1000) << "kbit/s" << std::endl; // Setting settings temporarily does not need to be done before committing to device EEPROM // It's done here to test both functionalities // Setting temporarily will keep these settings until another send/commit is called or a power cycle occurs std::cout << "\tSetting settings temporarily... "; ret = device->settings->apply(true); std::cout << (ret ? "OK" : "FAIL") << std::endl; // Now that we have applied, we expect that our operating baudrates have changed std::cout << "\tGetting HSCAN Baudrate... "; baud = device->settings->getBaudrateFor(icsneo::Network::NetID::HSCAN); if(baud < 0) std::cout << "FAIL" << std::endl; else std::cout << "OK, " << (baud/1000) << "kbit/s" << std::endl; std::cout << "\tGetting HSCANFD Baudrate... "; baud = device->settings->getFDBaudrateFor(icsneo::Network::NetID::HSCAN); if(baud < 0) std::cout << "FAIL" << std::endl; else std::cout << "OK, " << (baud/1000) << "kbit/s" << std::endl; std::cout << "\tSetting settings permanently... "; ret = device->settings->apply(); std::cout << (ret ? "OK\n\n" : "FAIL\n\n"); // The concept of going "online" tells the connected device to start listening, i.e. ACKing traffic and giving it to us std::cout << "\tGoing online... "; ret = device->goOnline(); if(!ret) { std::cout << "FAIL" << std::endl; device->close(); continue; } std::cout << "OK" << std::endl; // A real application would just check the result of icsneo_goOnline() rather than calling this // This function is intended to be called later on if needed std::cout << "\tChecking online status... "; ret = device->isOnline(); if(!ret) { std::cout << "FAIL\n" << std::endl; device->close(); continue; } std::cout << "OK" << std::endl; // Now we can either register a handler (or multiple) for messages coming in // or we can enable message polling, and then call device->getMessages periodically // We're actually going to do both here, so first enable message polling device->enableMessagePolling(); device->setPollingMessageLimit(100000); // Feel free to set a limit if you like, the default is a conservative 20k // Keep in mind that 20k messages comes quickly at high bus loads! // We can also register a handler std::cout << "\tStreaming messages in for 3 seconds... " << std::endl; // MessageCallbacks are powerful, and can filter on things like ArbID for you. See the documentation auto handler = device->addMessageCallback(icsneo::MessageCallback([](std::shared_ptr<icsneo::Message> message) { switch(message->network.getType()) { case icsneo::Network::Type::CAN: { // A message of type CAN is guaranteed to be a CANMessage, so we can static cast safely auto canMessage = std::static_pointer_cast<icsneo::CANMessage>(message); std::cout << "\t\tCAN "; if(canMessage->isCANFD) { std::cout << "FD "; if(!canMessage->baudrateSwitch) std::cout << "(No BRS) "; } // Print the Arbitration ID std::cout << "0x" << std::hex << std::setw(canMessage->isExtended ? 8 : 3) << std::setfill('0') << canMessage->arbid; // Print the DLC std::cout << std::dec << " [" << canMessage->data.size() << "] "; // Print the data for(auto& databyte : canMessage->data) std::cout << std::hex << std::setw(2) << (uint32_t)databyte << ' '; // Print the timestamp std::cout << std::dec << '(' << canMessage->timestamp << " ns since 1/1/2007)\n"; break; } case icsneo::Network::Type::Ethernet: { auto ethMessage = std::static_pointer_cast<icsneo::EthernetMessage>(message); std::cout << "\t\t" << ethMessage->network << " Frame - " << std::dec << ethMessage->data.size() << " bytes on wire\n"; std::cout << "\t\t Timestamped:\t"<< ethMessage->timestamp << " ns since 1/1/2007\n"; // The MACAddress may be printed directly or accessed with the `data` member std::cout << "\t\t Source:\t" << ethMessage->getSourceMAC() << "\n"; std::cout << "\t\t Destination:\t" << ethMessage->getDestinationMAC(); // Print the data for(size_t i = 0; i < ethMessage->data.size(); i++) { if(i % 8 == 0) std::cout << "\n\t\t " << std::hex << std::setw(4) << std::setfill('0') << i << '\t'; std::cout << std::hex << std::setw(2) << (uint32_t)ethMessage->data[i] << ' '; } std::cout << std::dec << std::endl; break; } default: // Ignoring non-network messages break; } })); std::this_thread::sleep_for(std::chrono::seconds(3)); device->removeMessageCallback(handler); // Removing the callback means it will not be called anymore // Since we're using message polling, we can also get the messages which have come in for the past 3 seconds that way // We could simply call getMessages and it would return a vector of message pointers to us //auto messages = device->getMessages(); // For speed when calling repeatedly, we can also preallocate and continually reuse a vector std::vector<std::shared_ptr<icsneo::Message>> messages; messages.reserve(100000); device->getMessages(messages); std::cout << "\t\tGot " << messages.size() << " messages while polling" << std::endl; // If we wanted to make sure it didn't grow and reallocate, we could also pass in a limit // If there are more messages than the limit, we can call getMessages repeatedly //device->getMessages(messages, 100); // You are now the owner (or one of the owners, if multiple handlers are registered) of the shared_ptrs to the messages // This means that when you let them go out of scope or reuse the vector, the messages will be freed automatically // We can transmit messages std::cout << "\tTransmitting an extended CAN FD frame... "; auto txMessage = std::make_shared<icsneo::CANMessage>(); txMessage->network = icsneo::Network::NetID::HSCAN; txMessage->arbid = 0x1C5001C5; txMessage->data.insert(txMessage->data.end(), {0xaa, 0xbb, 0xcc}); // The DLC will come from the length of the data vector txMessage->isExtended = true; txMessage->isCANFD = true; ret = device->transmit(txMessage); // This will return false if the device does not support CAN FD, or does not have HSCAN std::cout << (ret ? "OK" : "FAIL") << std::endl; std::cout << "\tTransmitting an ethernet frame on OP (BR) Ethernet 2... "; auto ethTxMessage = std::make_shared<icsneo::EthernetMessage>(); ethTxMessage->network = icsneo::Network::NetID::OP_Ethernet2; ethTxMessage->data.insert(ethTxMessage->data.end(), { 0x00, 0xFC, 0x70, 0x00, 0x01, 0x02, /* Destination MAC */ 0x00, 0xFC, 0x70, 0x00, 0x01, 0x01, /* Source MAC */ 0x00, 0x00, /* Ether Type */ 0x01, 0xC5, 0x01, 0xC5 /* Payload (will automatically be padded on transmit unless you set `ethTxMessage->noPadding`) */ }); ret = device->transmit(ethTxMessage); // This will return false if the device does not support OP (BR) Ethernet 2 std::cout << (ret ? "OK" : "FAIL") << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(50)); // Go offline, stop sending and receiving traffic std::cout << "\tGoing offline... "; ret = device->goOffline(); std::cout << (ret ? "OK" : "FAIL") << std::endl; // Apply default settings std::cout << "\tSetting default settings... "; ret = device->settings->applyDefaults(); // This will also write to the device std::cout << (ret ? "OK" : "FAIL") << std::endl; std::cout << "\tDisconnecting... "; ret = device->close(); std::cout << (ret ? "OK\n" : "FAIL\n") << std::endl; } std::cout << "Press any key to continue..." << std::endl; std::cin.get(); return 0; }
#ifndef __CBUILDINGMENU_H__ #define __CBUILDINGMENU_H__ #include "Defines.h" #include "EditorObjects.h" #include "CInputListener.h" #include "MyGui/MyGUI.h" namespace Core { class CBuilding; class CGameObject; class CInputKeyEvent; class CInputMouseEvent; enum MouseButtonID; namespace GUI { class CGuiStrategy_MyGui; } namespace Editor { class CBuildingMenu : public CInputKeyListener, public CInputMouseListener { public: CBuildingMenu(GUI::CGuiStrategy_MyGui* Strategy); ~CBuildingMenu(); void SetVisible(bool Visible); void SetVisible(bool Visible, const SELECTED& Selected, CBuilding* Building = nullptr); MyGUI::Widget* GetForm() { return frmBuilding; } private: bool MouseMoved(const CInputMouseEvent &arg); bool MousePressed(const CInputMouseEvent &arg, MouseButtonID id); bool MouseReleased(const CInputMouseEvent &arg, MouseButtonID id); bool KeyPressed(const CInputKeyEvent &arg); bool KeyReleased(const CInputKeyEvent &arg); void cmbBuildingList_ComboAccept(MyGUI::ComboBox* _sender, size_t _index); void rdoBuildingSphereObstacle_Click(MyGUI::WidgetPtr _sender); void rdoBuildingBoxObstacle_Click(MyGUI::WidgetPtr _sender); void btnBuildingPlace_Click(MyGUI::WidgetPtr _sender); void btnBuildingClose_Click(MyGUI::WidgetPtr _sender); void cmbBuildingType_ComboAccept(MyGUI::ComboBox* _sender, size_t _index); void btnBuildingCancel_Click(MyGUI::WidgetPtr _sender); void btnBuildingSave_Click(MyGUI::WidgetPtr _sender); void cmbBuildingTeam_ComboAccept(MyGUI::ComboBox* _sender, size_t _index); void Close(); void Save(); void PopulateMeshList(); void PopulateTypeList(); void PlaceMesh(f32 Width, f32 Height); void ResetControls(); bool isPlaceMesh; // Is the place mesh btn pressed and shift held down CBuilding* m_Building; // Currently selected object SELECTED m_Selected; // The selected object type GUI::CGuiStrategy_MyGui* m_Strategy; MyGUI::Widget* frmBuilding; MyGUI::ComboBoxPtr cmbBuildingList; MyGUI::ButtonPtr rdoBuildingSphereObstacle; MyGUI::ButtonPtr rdoBuildingBoxObstacle; MyGUI::ButtonPtr btnBuildingPlace; MyGUI::ButtonPtr btnBuildingClose; MyGUI::ComboBoxPtr cmbBuildingType; MyGUI::EditPtr txtBuildingName; MyGUI::ButtonPtr btnBuildingCancel; MyGUI::ButtonPtr btnBuildingSave; MyGUI::EditPtr txtBuildingPosX; MyGUI::EditPtr txtBuildingPosY; MyGUI::EditPtr txtBuildingPosZ; MyGUI::EditPtr txtBuildingScaleX; MyGUI::EditPtr txtBuildingScaleY; MyGUI::EditPtr txtBuildingScaleZ; MyGUI::ComboBoxPtr cmbBuildingTeam; }; } } #endif // __CBUILDINGMENU_H__
Nursing a critically ill state back to health |Indranill Basu Ray highlights the core problems that afflict Bengal's health sector and suggests a few ways to improve the situation| Despite many technological and other achievements that have propelled India from being a developing nation to one of the top economies of the world, one field that India continues to lag behind in is health. This is why stories of babies dying in large numbers haunt newspaper headlines. India is behind Bangladesh and Sri Lanka in life expectancy at birth or under-five mortality level. India accounts for about 17 per cent of the world population, but it contribute to a fifth of the world's share of diseases. A third of all diarrhoeal diseases in the world occurs in India. The country has the second largest number of HIV/AIDS cases after South Africa. It is home to one-fifth of the world's population afflicted with diabetes and cardiovascular diseases. A common excuse that I often hear is that we have limited resources to tackle the huge and burgeoning health problems. But even the richest country on earth, the United States of America, has failed to provide appropriate health services to a large section of the populace. The problem in India is quite different. Apart from being a poor nation with limited resources, it also has a sizeable population in need of basic health services. Furthermore, the lack of appropriate sanitary measures and education ensures an ever increasing presence of communicable disease that have been controlled and even eradicated in the developed nations. India's list of woes does not stop here. Lack of foresight on the part of successive governments and selective and fragmented strategies to counter daily problems without a definite public health goal have been the mainstay of India's health policies. Resource allocation to this sector is influenced by the prevailing fiscal situation as well as by the priorities of the reigning government. Unfortunately, in Bengal — a state that faces a dismal fiscal situation — the government's priorities have been skewed as a result of political necessities. Although we have a new government at the helm, it is important to realize that gross changes at the practical level cannot be initiated without having a team with experience and knowledge define a well-thought-out strategy. It is also essential to have a government that is willing to fulfil the financial needs necessary for the strategy to work. It is difficult, if not impossible, to paint a picture of the present state of public health in West Bengal and to suggest measures to rectify the same in a short article like this. My intention is to highlight the core problems plaguing the system and to suggest solutions based on accepted principles of public health and healthcare management. The steps that need to be taken are as follows: reducing disease burden, including infectious diseases as well as non-communicable epidemics like diabetes mellitus and coronary heart disease; restructuring the existing primary healthcare system to make it more accountable; creating a skilled and professional workforce which is quality driven; financial planning to bring more investment to the health sector. Reducing disease burden is the cornerstone of any good health policy. The factors that help reduce communicable diseases are clean drinking water, improved sanitation and an effective vaccination programme. A paradigm shift, from the prevalent curative approach to a preventive approach, including health promotion by inculcating behavioural changes, is imperative to reduce disease burden. West Bengal is one of four states that urgently needs high investment in safe drinking water and toilet facilities. It is estimated that Rs 18,000 crore is required to provide effective drinking water and sanitation facilities for the entire country. Kerala, Maharashtra, West Bengal and Odisha would account for more than 60 per cent of the total outlay. Similarly, a huge investment is required to provide nutritional supplements to malnourished children and pregnant and lactating mothers living below the poverty line. According to a report by the national commission on macroeconomics and health, West Bengal would need to harness an additional resource requirement of rupees (in crore) 1,286, 2,459, 4,693, 13,811 and 8,485 in sectors such as health, water and sanitation, nutrition, primary schooling and roads. It has been projected that in the next five years West Bengal will spend a large portion of its revenues on wages and salaries, interest payments and pensions, leaving very little for discretionary expenditure in the field of health. It is imperative that the present government rethink and strategize in collaboration with the Centre to ensure the appropriate funding necessary to make the state healthy. Restructuring the present healthcare delivery system is also equally important. Most primary healthcare centres are old, dilapidated buildings with few or no facilities. Some do not even have basic resources like healthcare workers or pharmacists. What is required is a radical overhaul of the existing system. There are differences in health systems of different countries. A State-run health system, such as the one in Canada, suffers from delayed medical care. A privately-run health system like the one in the US provides only limited health services to its poor. India's healthcare should carve out the best of both systems. Private healthcare is thriving in India. It is uncontrolled and aimed at profit-making. Government-run hospitals are poorly managed, providing few or no facilities to those living below the poverty line. Different models have been suggested to take care of this disparity. While private investment will always be geared towards profit-making, it is mandatory to rein in these bodies under well-defined rules. Large private hospitals in the US are non-profit bodies, which have to follow stringent rules in patient care. At the other end of the spectrum is the National Health Service in Britain in which small, medium and even a few large hospitals are making way for a more competent and accountable government-controlled health system with fewer hospitals. Human resource management is very important in running an effective health system. One of the biggest lacunae of government health service is its poor human-resource management. Many physicians are not paid appropriate salaries or are posted in places that are not of their choice. Political intervention and favouritism play a big role in posting physicians. Consequently, dedicated physicians who want to serve the public or work in the academic setting found in government hospitals are forced to remain in private hospitals. To boost morale and efficacy, discipline needs to be instituted in the system and a transparent posting policy adopted. The doctor-population ratio needs to be improved by filling up vacancies in the West Bengal health service. It is important to free postings from the grip of bureaucrats to ensure the registration of quality candidates. Physicians failing to report to duty or indulging in indiscipline must be punished. Doctors who do sign up need to provide relevant and quality medical care. This can only be done if some form of recertification of doctors is made mandatory once every 10 years. Physicians' salaries in the state health service must be made on a par with those of the Central government to make sure that it remains a lucrative option. Senior physicians providing exemplary public service must be rewarded for the same. A commonly-held notion is that most physicians run after the lucrative salaries that are offered in private hospitals. Hence it is difficult to retain them in the government sector. This, however, is true of a minority. The majority of physicians are willing to work in a healthy, progressive and academic environment if there are appropriate non-financial incentives. Let us take the example of Christian Medical College, Vellore. Most of the faculty there are paid salaries that are much lower than those of the private sector. However, physicians are provided with other facilities such as good housing, free schools, free-to-highly-subsidized college education and, most importantly, a progressive and research oriented work environment. West Bengal lags behind many other states when it comes to medical education. There is an urgent need to increase the number of medical colleges in the state. Private investment for the same should be welcomed but appropriate laws must be instituted so that huge capitation fees are not charged for seats. Furthermore, selection should be made through competitive examinations. A certain percentage of seats can be reserved for the economically weaker sections. Students passing out of such medical colleges must be given postings in rural hospitals. This has been true on paper for many decades now, but the rule has been poorly implemented even in government-run medical colleges. Innovative schemes ought to be thought of to involve the cash-rich private sector to service the medical needs of the state. Private institutions using government money or land must be asked to provide free service to 20 per cent of their capacity. Appropriate punitive measures — such as temporarily withholding or cancelling licences — can be taken when a private institution fails to honour this commitment. Institutions willing to set up large hospitals, particularly around Calcutta, must be helped through the provision of low-cost land. But in return, promises to set up satellite hospitals in far-flung district headquarters have to be met. The biggest challenge to the rejuvenation of the healthcare system is the garnering of funds. West Bengal is financially broke, thanks to the misrule of the communists. Unlike most other communist rulers, our home-grown variants failed to provide basic sanitation, good roads, a working healthcare system and appropriate nutritional supplements to women and children. The lack of social services resulted in poor health and in increased mortality among the vulnerable sections of society. Government efforts to improve basic health services must fund programmes that provide sanitation, nutritional supplements, and daily meals for school-going children. Substantial investments in these sectors can reduce mortality in children. It is popular to blame doctors for not being able to save severely ill, malnourished children. But things won't change unless determined steps are taken to root out the problems, such as poor funds, minimal resources and an incompetent workforce, that affect the West Bengal health service. In the next five years, in collaboration with the Centre and the non-government organizations involved in public health, the state government must chalk out a definitive strategy to improve the supply of clean drinking water, provide better sanitation and one full meal to school-going children and arrange for nutritional supplements to pregnant women. Private investment should be wooed in the health sector to set up hospitals in large metropolitan areas as well as in small district towns. While government land is needed at an appropriate price to help investors build hospitals, steps must be taken to bring about the inclusion of the deprived sections in their service plans. Strong regulatory bodies that can monitor private hospitals and nursing homes must be instituted. Many of the profiteering health institutions do not provide basic facilities, lack trained nurses and paramedical staff, and some are even run by quacks without medical degrees. It is of utmost importance that a regulatory body conducts surprise checks on these institutions, registers complaints and takes remedial steps. Many NGOs have been able to set up large projects benefiting thousands of people. They have also succeeded in bringing foreign aid to tackle malaria and HIV. The state government should help these NGOs achieve their goals while exercising control to prevent financial irregularities. Their services ought to be applauded and single-window processing of applications instituted to help them tackle bureaucratic delays. Health is a service industry and not a lucrative business. Unfortunately, in Bengal, most large hospitals are owned by corporates. Only a few are owned or run by doctors. There is thus a sustained effort to make profit. Poor consumer protection makes the man on the street vulnerable to substandard service at high prices. These are trying times for Bengal, after years of mismanagement in the health sector. It is important for the present rulers to rectify the situation by laying down the stepping stones for a better tomorrow. Tuesday, November 22, 2011 Nursing a critically ill state back to health Indranill Basu Ray highlights the core problems that afflict Bengal’s health sector and suggests a few ways to improve the situation
Enterprise Software SolutionBase: Using the Dsquery command in Windows Server 2003 Microsoft includes some handy GUI tools with Windows Server 2003 to help you manage Active Directory. Sometimes, however, command-line tools such as Dsquery can give you more flexibility and control. Here's a detailed look at the Dsquery command. In the article "Getting started with Windows Server 2003's directory service command-line tools," I introduced you to the six basic directory service command-line tools and provided an expanded list showing you the particular objects that each tool is designed to work with. I also got you started with a basic understanding of distinguished names and the Lightweight Directory Access Protocol (LDAP) attribute tags. The directory service command-line tools rely on these names to locate and work with objects in Active Directory. As I closed out that article, I briefly showed you how to use the Dsquery command to look at the distinguished names assigned to the objects in your Active Directory structure. In this article, I'll pick up with the Dsquery command and examine its features. I'll then show you some cool search techniques you can perform with the Dsquery command to quickly and easily reveal information that would be a bit tricky to get out of GUI interface tools. The commands While the Dsquery command is one of the six main directory service command-line tools, it actually consists of 11 separate commands, as shown in Table A. Ten of these commands are designed to find objects of a specific type, and one is designed to find any object type in Active Directory. Table A Command Description Dsquery * Finds any object Dsquery computer Finds computer accounts Dsquery contact Finds contacts Dsquery group Finds group accounts Dsquery ou Finds organizational units Dsquery partition Finds Active Directory partitions Dsquery quota Finds object quotas Dsquery server Finds domain controllers Dsquery site Finds Active Directory sites Dsquery subnet Finds subnet objects Dsquery user Finds user accounts The Dsquery commands Of course, each of these commands comes with a set of object-specific parameters that allow you to define the search criteria for each object. However, the majority of the parameters are common to most of the Dsquery commands. The common parameters Let's examine the common parameters and see how they work. Once you understand their function, you'll be able to look at the overly complex syntax layouts for each command and more easily pick out the object-specific parameters. Targeting your search The first set of common search parameters allows you to specify where you want your search operation to begin: [{StartNode | forestroot | domainroot}] To more narrowly focus your search, you can use a node's distinguished name (StartNode). To broaden your search, use the forestroot parameter, in which case the search is done using the global catalog. The default value is domainroot; while it's implied, if you don't type anything else, you can enter it on the command line if you really like to type out long command strings. The second set of parameters in this category allows you to specify the scope of your search: [-scope {subtree | onelevel | base}] If you use the ï¿?scope base parameter, you target the search on a single object specified by command and the start node. In other words, you prevent the search from progressing down to child objects. Now, if you use the ï¿?scope onelevel parameter, you target the search on the object specified by command, the start node, and the object's immediate children. The ï¿?scope subtree parameter is the default, and it allows the search to freely progress down the tree from the start node. As I mentioned, you can use the forestroot parameter in order to search the global catalog. You can also use the ï¿?gc parameter to require that your search specifically use the Active Directory global catalog. One more way that you can target your search is by using the ï¿?r parameter. In this case, the r stands for recursion. This parameter allows you to specify that your search use recursionï¿?also described as following referrals during a search. As I understand it, this parameter allows you to extend your search to multiple servers. Formatting output The next set of common parameters lets you specify the output format for the search results: [-o {dn | rdn}] The default output is the distinguished name and uses the -o dn parameter. If you want to see the relative distinguished name, you'd use the -o rdn parameter. As I said in the previous article, the Dsquery command will display only 100 objects by default. The next parameter allows you to expand the number of items displayed in the output: -limit NumberofObjects Essentially, you can use any number you want here. While it may seem a bit weird at first glance, if you want to see all of the objects, follow the -limit parameter with a zero. However, be careful when changing the limit because Microsoft's goal in limiting the output to 100 objects is to prevent the domain controller from being unnecessarily taxed by an exhaustive Active Directory search operation. The last set of output format parameters also double as input format parameters and are designed to allow you to specify Unicode format: {-uc | -uco | -uci} The -uc parameter specifies a Unicode format for input from or output to a pipe (|). The -uco parameter specifies a Unicode format for output to a pipe (|) or a file. The -uci parameter is used to specify a Unicode format for input from a pipe (|) or a file. While I'm on the topic of output, should you ever decide to run the Dsquery command and not see the results, you can use the -q parameter (a.k.a. Quiet Mode), which will suppress all output to the console. At first, this seemed like an odd thing to do, but then I thought it might be useful when you're redirecting output to a file. However, I've not had any luck getting the -q parameter to work at all. Remote connection The final set of common parameters that we'll look at are the remote connection parameters. By default, the Dsquery command assumes that you're running the command in the domain to which you're logged in. However, you can also run the Dsquery command on a remote server or domain. {-s Server | -d Domain} Using these parameters, you can connect to a specified remote server or domain. You might also need to specify a username and password, in which case you'd use these parameters: -u UserName -p {Password | *} If you use the asterisk, you'll be prompted for a password. Dsquery examples Now that you have a good idea of how the Dsquery command works with its common parameters, let's look at some examples of where using this command will come in handy. Tracking down servers Suppose that while troubleshooting a problem, you discover that you need to quickly identify the domain controller that is performing one of the five Flexible Single Master Operation (FSMO) roles for a forest. What if you need to quickly identify which domain controllers are performing all five FSMO roles: the Schema Master, Domain Naming Master, RID Master, PDC Emulator, and Infrastructure Master? To perform this operation, you'll use the command: Dsquery server along with the parameters: -hasfsmo {schema | name | infr | pdc | rid} If you wanted to find only the Schema Master, you'd use the command: Dsquery server -forest -hasfsmo schema If you wanted to find all five, you'd use the command: For %x in (schema name infr pdc rid) do Dsquery server -forest -hasfsmo %x Here, I've simply incorporated the Dsquery server command in a pretty standard For In Do loop. To use this command line, you might want to type it in Notepad and save it as a batch file. You might also want to capture the output in a file. If so, you can add the following to the end of the command line: >> FSMO-Query.txt Tracking down inactive or disabled accounts Suppose you've just taken a new job as a systems administrator. After a couple of days on the job, you discover that your predecessor wasn't very conscientious about cleaning up inactive and disabled user and computer accounts of employees who either left the company or were there only on a temporary contract basis. You've already changed the name and passwords on all the Administrative accounts, and you want to plug any potential security breaches that have been left open by your predecessor. You need a way to quickly ascertain the magnitude of the problem. Fortunately, you can quickly gather the information you need with a few simple Dsquery commands. To find all user accounts that have been inactive for at least the last week or longer, you'd use the command: dsquery user - inactive 1 To find all user accounts that have been disabled, but never dealt with further, you'd use the command: dsquery user -disabled To find all computers whose accounts have been inactive for the last week or more, you'd use the command: dsquery computer - inactive 1 To track down all computers whose accounts are disabled, you'd use the command: dsquery computer -disabled Performing an inventory on the fly! Now imagine this scenario: As a young network administrator, you learned the importance of documenting a network. Over the years, you've become very diligent when it comes to filling in the Description fields for every object account in Active Directory. The Description field for each computer account in your Active Directory structure contains a very detailed string of information that begins with a three-letter acronym specifying the operating system. Suppose that your colleague asks you to find out how many computers in the Laptops organizational unit are still running Windows 2000 Professional. You could quickly open a command prompt window and type the command: Dsquery computer OU=Laptops,DC=gcs,DC=com -desc W2K* Similarly, you could find out how many computers in the Laptops organizational unit are now running Windows XP Professional by using the command: Dsquery computer OU=Laptops,DC=gcs,DC=com -desc WXP* Stay tuned You should now have a pretty good handle on how to use the Dsquery command; you can use my examples as a starting point in your own explorations. In fact, if you come up with any cool examples of using the Dsquery command, please take a moment to share your command line by dropping a note in the Discussion area. In the next article, I'll focus on the Dsget command as I continue examining the directory service command-line tools. About Greg Shultz Editor's Picks Free Newsletters, In your Inbox
Where Is Kosovo? Kosovo is a landlocked region in the Balkan Mountains in Europe. It borders Central Serbia to the east and Albania to the west. The region is a disputed territory. It declared independence on 17 February, 2008. The case, whether to grant the request for a new nation or not, is still pending with the United Nations. Serbia considers the region a part of the Serbian nation and strongly opposes the independence move of Kosovo. KosovoThe name of the region comes from the Serbian language and it means ‘a field of the blackbirds’. Within Kosovo, the term ‘Kosovo’ refers to the eastern part of the region and the western part is known as ‘Metohija’. Both parts are sometimes collectively called ‘Kosovo and Metohija’. The largest city in Kosovo is Pristina, where approximately half a million people live. Most of the terrain of the region is mountainous and the highest peak, Djeravica (Đeravica), is 2656 meters high. About 39% of Kosovo is covered by forests and there is only one national park in Kosovo, Šar Mountains National Park. Islam is the predominant religion in Kosovo. Both Serbia and Kosovo were once a part of Yugoslavia and the secular socialist government of Yugoslavia did its best to prevent any ethnic or religious tensions arising. The iron grip of the Yugoslav president Josip Broz Tito held Yugoslavia together for decades but within 10 years after his death the nation broke up into several smaller countries. Kosovo became a part of Serbia after the dissolution of Yugoslavia but it wasn’t long before ethnic tensions began to rise and a war broke out. About 92% of the Kosovon population is ethnically Albanian and the Serbs are the largest minority comprising approximately 4% of the population. The relations between the Albanians and the Serbians are most of the time unfriendly. The war dampened down after a UN intervention but things have been simmering again since Kosovo declared its independence in 2008. Category: Geography
How To Win At Science Fairs (Dec, 1960) How To Win At Science Fairs by Ronald Benrey YOU CAN WIN at a Science Fair as long as one thing interests you more than winning does. This is your project itself. It is going to be judged on scientific thought, creative ability, and presentation. You will really have to know the field your project is concerned with. This takes effort. Since you lack the means of a professional laboratory, you will have to do much with little. This takes trial and error and just plain work. Your presentation must be attractive and clear. This means good workmanship, which takes time and care. You are going to have to show some originality. After all, there is no use doing what everybody else is doing: be different. For this, you have to have the other three under control. By the way, the “laymen” who see your exhibit will ask all kinds of questions. Have good answers at your fingertips. The judges won’t be laymen, and any double-talk will scream to them that you don’t know your subject. It may also make them suspect that the best parts of your project are not your work. This would be unjust, perhaps, but deadly. Now, whether your entry covers a large table top or can just be tucked under your arm, it is going to be a big job. It can’t be left for a “crash program” in the last few weeks before the Fair. It is going to eat up big portions of your time, energy, and spending money for the next several months. All this demands your interest. But it isn’t simply a matter of “fun. ” Licking this challenge may be a turning point in your life. With or without a scholarship prize, your career may begin with it. As a reader of Electronics Illustrated your project will probably deal with electronics or applied physics rather than with biological or earth sciences. Select your topic carefully from a broad subject that really interests you. A massive effort in the direction of a passing fancy will result in a mediocre project at best. Take a limited subtopic that you think worth investigating and that you feel able to handle. To ease financial strain, plan now to build your project over a long period of time, say six months, on a pay-as-you-build basis. Once you have a rough idea of your project’s general form, don’t dash into construction. Visit technical libraries and learn all you can about current professional work in the field, and its technical jargon. This will give you much important information and helpful hints, and when you finally face the judges, you will know your subject. Here is a prickly question. It is up to you to be realistic and honest with yourself when you choose a topic. Your science teachers and advisers will certainly be helpful, but the final decision must be yours. In other words, if you have never handled a soldering iron before, don’t take on a project requiring elaborate electronic instrumentation. If you have enough time you can work up to a complex project by building a few simpler devices, like many described in EI. This is another reason for starting NOW. – Why not get your feet wet by assembling some test equipment from kits? You will certainly need a multimeter anyway, for any project, and it will be something you can use “forever. ” Another touchy subject: discussion of this often scares off good potential science fairers. Nobody requires or expects a science fair project to produce a radical new scientific discovery. However, this does not imply that an entrant can’t find a new angle on an old problem. Merely duplicating a project described in a magazine shows the judges only one thing: the builder can follow directions. The main benefit of entering a science fair is the challenge of thinking a real problem out, all the way through. Your project can be for “demonstration” rather than “research, ” but make sure you come up with fresh, clear, meaningful ways to present your material. Stay away from last year’s winning project: it was good last year. Avoid “staples” (like Tesla coils) unless they are only part of a ‘wider original project. Your project should be well presented and look impressive, but impressive need not mean expensive. Judges seldom look twice at an exhibit loaded down with excess and borrowed equipment when the same results could have been obtained more economically and without false show. Novel use of common materials shows creative ability, and this is an important judging criterion. Remember, how you solved your problem is what counts at a science fair, and not merely that you solved it. Also, neatness counts! Aside from being impossible to troubleshoot, a rat’s nest of wiring is typical of losing projects. Time spent color-coding leads, installing wire harness and cable clamps will result in a much more attractive and more reliable project. But know what you are doing! Don’t harness leads in a circuit that demands point-to-point wiring, or cable grid and plate leads together in an amplifier circuit. Read up on layout and construction techniques, and allow yourself time to make and correct mistakes. Prior planning will also pay off in dollars and cents, since you can save by purchasing some components (like resistors) in quantity, and if you live near a big city you can shop around for some items in the military surplus stores, modifying your design if necessary to take odd-value components. Now, sit back and start your thinking. The time to start is right now. IS YOUR WINNING PROJECT HERE? RADIO TELESCOPE: Home-built sensitive low-noise receiver, simple antenna system. Try to make simple “radio map.” GUIDANCE SYSTEM: For model ear. Can be programmed to run around science fair grounds without hitting anything, or to reach pre-chosen destination. SOLAR CELLS: Home-built unit as part of demonstration of basic physics of solar cells: display on recent professional research results: off-beat practical applications (eyeglass type hearing aid?). MOON MOUSE: “To be landed on the Moon. ” Self-propelled, radio controlled from Earth, instrumented and transmitter equipped. Some functions solar powered ? These are only suggestions. You may come up with ideas regarding fuel cells, space communications, navigation, etc.
#include <Python.h> // this has to be the first included header #include <iostream> #include <cstdlib> #include <fstream> #include "gtest/gtest.h" #include "arg.h" #include "opendihu.h" #include "../utility.h" // 2D regular fixed TEST(DiffusionTest, SerialEqualsParallelRegular2DLinear) { // run serial problem std::string pythonConfig = R"( # Diffusion 2D nx = 5 # number of elements in x direction ny = 8 # number of elements in y direction # initial values iv = {} iv[22] = 5. iv[23] = 4. iv[27] = 4. iv[28] = 3. config = { "MultipleInstances": { "nInstances": 1, "instances": [{ "ranks": [0], "ExplicitEuler": { "initialValues": iv, "numberTimeSteps": 50, "endTime": 1.0, "FiniteElementMethod": { "inputMeshIsGlobal": True, "nElements": [nx, ny], "physicalExtent": [2*nx, 2*ny], "relativeTolerance": 1e-15, }, "OutputWriter" : [ {"format": "PythonFile", "filename": "out2", "outputInterval": 1, "binary": False} ] } }] } } )"; DihuContext settings(argc, argv, pythonConfig); typedef Control::MultipleInstances< TimeSteppingScheme::ExplicitEuler< SpatialDiscretization::FiniteElementMethod< Mesh::StructuredRegularFixedOfDimension<2>, BasisFunction::LagrangeOfOrder<1>, Quadrature::Gauss<2>, Equation::Dynamic::IsotropicDiffusion > > > ProblemType; ProblemType problemSerial(settings); problemSerial.run(); // run parallel problem std::string pythonConfig2 = R"( # Diffusion 2D nx = 5 # number of elements in x direction ny = 8 # number of elements in y direction # initial values iv = {} iv[22] = 5. iv[23] = 4. iv[27] = 4. iv[28] = 3. config = { "MultipleInstances": { "nInstances": 1, "instances": [{ "ranks": [0,1], "ExplicitEuler": { "initialValues": iv, "numberTimeSteps": 50, "endTime": 1.0, "FiniteElementMethod": { "inputMeshIsGlobal": True, "nElements": [nx, ny], "physicalExtent": [2*nx, 2*ny], "relativeTolerance": 1e-15, }, "OutputWriter" : [ {"format": "PythonFile", "filename": "out2", "outputInterval": 1, "binary": False} ] } }] } } )"; DihuContext settings2(argc, argv, pythonConfig2); ProblemType problemParallel(settings2); problemParallel.run(); std::vector<std::string> outputFilesToCheck = {"out2_0000010.py", "out2_0000010.0.py", "out2_0000010.1.py"}; assertParallelEqualsSerialOutputFiles(outputFilesToCheck); nFails += ::testing::Test::HasFailure(); } // 2D structured deformable TEST(DiffusionTest, SerialEqualsParallelDeformable2DLinear) { // run serial problem std::string pythonConfig = R"( # Diffusion 2D nx = 2 # number of elements in x direction ny = 2 # number of elements in y direction # initial values iv = {} iv[2] = 5. iv[3] = 4. iv[7] = 4. iv[8] = 3. config = { "MultipleInstances": { "nInstances": 1, "instances": [{ "ranks": [0], "ExplicitEuler": { "initialValues": iv, "numberTimeSteps": 50, "endTime": 1.0, "FiniteElementMethod": { "inputMeshIsGlobal": True, "nElements": [nx, ny], "physicalExtent": [2*nx, 2*ny], "relativeTolerance": 1e-15, }, "OutputWriter" : [ {"format": "PythonFile", "filename": "out3", "outputInterval": 1, "binary": False} ] } }] } } )"; DihuContext settings(argc, argv, pythonConfig); typedef Control::MultipleInstances< TimeSteppingScheme::ExplicitEuler< SpatialDiscretization::FiniteElementMethod< Mesh::StructuredDeformableOfDimension<2>, BasisFunction::LagrangeOfOrder<1>, Quadrature::Gauss<2>, Equation::Dynamic::IsotropicDiffusion > > > ProblemType; ProblemType problemSerial(settings); problemSerial.run(); // run parallel problem std::string pythonConfig2 = R"( # Diffusion 2D nx = 2 # number of elements in x direction ny = 2 # number of elements in y direction # initial values iv = {} iv[2] = 5. iv[3] = 4. iv[7] = 4. iv[8] = 3. config = { "MultipleInstances": { "nInstances": 1, "instances": [{ "ranks": [0,1], "ExplicitEuler": { "initialValues": iv, "numberTimeSteps": 50, "endTime": 1.0, "FiniteElementMethod": { "inputMeshIsGlobal": True, "nElements": [nx, ny], "physicalExtent": [2*nx, 2*ny], "relativeTolerance": 1e-15, }, "OutputWriter" : [ {"format": "PythonFile", "filename": "out3", "outputInterval": 1, "binary": False} ] } }] } } )"; DihuContext settings2(argc, argv, pythonConfig2); ProblemType problemParallel(settings2); problemParallel.run(); std::vector<std::string> outputFilesToCheck = {"out3_0000010.py", "out3_0000010.0.py", "out3_0000010.1.py"}; assertParallelEqualsSerialOutputFiles(outputFilesToCheck); nFails += ::testing::Test::HasFailure(); }
Summer in the City by Cristiana Strava Cooling off in the Bronx (2011). Source: Charles Brigand In 1927, the Times reported that more than three thousand people had spent the night sleeping on the sand at Coney Island in order to escape the stifling heat of their tenements. Patrolmen had been assigned to stand guard over the sleepers. Many more spent their nights in Central Park, while others piled up on fire escapes to survive the sweltering heat of New York in July. Over the years, the image of children cooling off in the spray of a fire hydrant has become synonymous with summer in the city. Too poor to escape to the Hamptons, working class New Yorkers transformed available public spaces into impromptu vacation spots. Sleeping on a fire escape in New York (1938). Source: Weegee Collection Today, city officials and entrepreneurs attempt to provide options aimed at both locals and potential tourists. Capitalizing on a certain fetishistic obsession with "authenticity," they appropriate working class spaces and practices and regulate them or present them as fashionable. Sharon Zukin, an urban sociologist and staunch critic of New York's gentrification, refers to this process as "pacification by cappuccino," a scenario in which urban space is "imagineered" as an entertainment event for the consumption of those who can afford it. This phenomenon is taking place worldwide, and what better season than summer to capitalize on people's use of city space? Paris Plages on the Rive Droite. Source: Choblet et Associés An urban summer staple, Paris Plages is perhaps the most famous and chic of European city beaches. Many Parisians abandon the city in summer for the South of France or countryside vacations. Since  2002, the month-long transformation of the Seine's banks (with the recent addition of La Villete) has aimed to offer a comfortable recreation space for those who remain in the city. The attractions of Paris Plages are mostly free and open to all. An "open air drinking ban," however, has meant that those who once brought a home-made picnic and bottle of wine might now be forced to avail themselves of the many and, according to some, overpriced Paris Plage brasseries instead. Amsterdam City "Beach" on the roof of the NEMO Museum. Source: Tino Morchel Beyond the issues raised by the commodification of public space, critics have questioned the environmental impact of carting in large amounts of sand for such a brief period of time. However, several European capitals now proudly present their summer residents and visitors with at least one man-made beach. Amsterdam, Berlin, Copenhagen, Moscow, Prague and Vienna — to name just a few — are converting city spaces into sandy urban oases for a few weeks every summer. Amsterdam boasts no less than four city beaches, while Copenhagen's most famous summer splash spot is a riff off Copacabana, at least in name. While London has so far resisted the trend, one can still enjoy sand in the shape of a couch in front of the Globe Theatre on the South Bank — before the tide of the mighty Thames wipes it away. Alternatively, during those brief spells of good weather, for £1.50 you can lounge for an hour in a Hyde Park deck chair. Sculpting the sand on London's South Bank. Source: Normco Deck chairs in London's Hyde Park. Source: Andy Pallister In Moscow, known for turning into a boiling cauldron in summer, the range of choices is also rich. Until recently, most sunbathing and swimming spots were appropriations of existing river banks and parks rather than eventified realms. Now from Kirovsk and Strogino to Serebryany Bor (a longtime favorite for nudists), Muskovites can enjoy refurbished sporting and barbecue areas equipped with WiFi. Serebryany Bor sunbathers. Source: In Moskau There is nothing evil about providing city dwellers with options for an urban vacation. However, there is something disconcerting about government officials allowing corporations to reap financial benefits from social activities that were once free and improvised, as public space becomes more and more scarce. + share 1. Very nice article and overview of the different types of public spaces, and urban vacation spots. I appreciate the range of modifications presented from capital intensive concrete steps for chairs to the simple lawn chair in a park. The question I have is whether or not the presence of corporate/business interests makes these types of spaces more sustainable in the long term? What were the conditions 5, 10 or 50 years prior, and has the influence of money undermined the experience of a place? It would be nice to see a follow up showing a comparative case study that demonstrates the pro's and con's of infusing private interests in public space. If this is a trend, it would be best to identify best practices to promote a sensitive and appropriate marriage between public and private agendas. Living briefly in NYC, I am aware of the transformation of Bryant Park, and the dramatic changes that have taken place over the past fifty years. From a derelict space, the park has seen vast improvements from it's previous condition. The public now experiences many free events and activities at the expense of subtle advertising and the presence of businesses such as a sandwich shop. It's not unreasonable, and in contrast to the rampant advertising in the street, I applaud the care taken to make the advertising in Bryant Park subtle. 2. I see the decreasing public character of public spaces as a huge con of involving the private, Bland. And corporate interests do tend to result in just this, also in Bryant Park. Many governments are unaware of the possible effect of private interests on public spaces and the public character of city centers. Undesirables (appointed by commercial stakeholders) are often pushed from city centers which affects, among other things, the sense of community. You may some like classics from Fainstein, Sorkin and good old Sennett..
/********************************************************************** * * Source File Name = sample_typedef.h * * (C) COPYRIGHT International Business Machines Corp. 2003,2004 * All Rights Reserved * Licensed Materials - Property of IBM * * US Government Users Restricted Rights - Use, duplication or * disclosure restricted by GSA ADP Schedule Contract with IBM Corp. * * Function = Include File defining:Structures and macros used in sample wrapper * * Operating System = All * ***********************************************************************/ #ifndef __SAMPLE_TYPEDEFS_H__ #define __SAMPLE_TYPEDEFS_H__ #include "sqlcli.h" // Wrapper Defines #define SAMPLE_WRAPPER_TYPE 'N' // 'N' For Non-Relational (Generic) #define SAMPLE_WRAPPER_VERSION 1 // Nickname Defines #define FILE_PATH_OPTION "FILE_PATH" // Misc. Defines #define NULL_WRAPPER "Cannot get wrapper object" #define NULL_PATH "Data source path is NULL" #define LSTAT_ERROR "STAT Failed on data source" #define COLUMN_ERROR "No column info found" #define ACCESS_ERROR "Unable to read file" #define DATA_ERROR "Data Error" #define NOT_FILE_ERROR "Data source is a non-standard file" #define OPEN_ERROR "File open error" #define BAD_PRED_OP "Unsupported operator" #define BAD_COLUMN "Column not found" #define KEY_EXCEEDS_SIZE "Key exceeds definition size" #define FILE_SIZE_ERROR "Line in data file exceeds 32k" // Constants #define MAX_DECIMAL_SIZE 34 #define MAX_VARCHAR_LENGTH 32672 // enums and structs needed by the different classes. enum myboolean {NO,YES}; struct columnData { sqlint32 type; // This structure is used to sqluint8 *name; // contain the information about void *data; // a data element sqlint32 len; int precision; // Used with decimal data type int scale; // Used with decimal data type }; enum relOperator { SQL_EQ, ALL_ROWS }; // This is a subset of Sample_Query that is generated by plan_request() struct Sample_Exec_Descriptor { relOperator mPredOperator; int mNumColumns; int mKeyVector; int mBindIndex; }; #endif
// -*- mode:c++; c-basic-offset:4 -*- #if !defined __BENDERRMQ_H #define __BENDERRMQ_H #include <iostream> #include <vector> #include <utility> #include <algorithm> #include <stack> #include <stdio.h> #include <sstream> #include <assert.h> #include "types.h" #include "utils.h" #include "sparsetable.h" #include "lookuptables.h" #include "simplefixedobjectallocator.h" using namespace std; #define MIN_SIZE_FOR_BENDER_RMQ 16 class BenderRMQ { /* For inputs < MIN_SIZE_FOR_BENDER_RMQ in size, we use just the * sparse table. * * For inputs > MIN_SIZE_FOR_BENDER_RMQ in size, we use perform a * Euler Tour of the input and potentially blow it up to 2x. Let * the size of the blown up input be 'n' elements. We use 'st' for * 2n/lg n of the elements and for each block of size (1/2)lg n, * we use 'lt'. Since 'n' can be at most 2^32, (1/2)lg n can be at * most 16. * */ SparseTable st; LookupTables lt; /* The data after euler tour computation (for +-RMQ) */ vui_t euler; /* mapping stores the mapping of original indexes to indexes * within our re-written (using euler tour) structure). */ vui_t mapping; /* Stores the bitmask corresponding to a block of size (1/2)(lg n) */ vui_t table_map; /* Stores the mapping from +-RMQ indexes to actual indexes */ vui_t rev_mapping; /* The real length of input that the user gave us */ uint_t len; int lgn_by_2; int _2n_lgn; public: std::string toGraphViz(BinaryTreeNode* par, BinaryTreeNode *n); /* This is a destructive function - one which deletes the tree rooted * at node n */ void euler_tour(BinaryTreeNode *n, vui_t &output, /* Where the output is written. Should be empty */ vui_t &levels, /* Where the level for each node is written. Should be empty */ vui_t &mapping /* mapping stores representative indexes which maps from the original index to the index into the euler tour array, which is a +- RMQ */, vui_t &rev_mapping /* Reverse mapping to go from +-RMQ indexes to user provided indexes */, int level = 1); BinaryTreeNode* make_cartesian_tree(vui_t const &input, SimpleFixedObjectAllocator<BinaryTreeNode> &alloc); void initialize(vui_t const& elems); // qf & ql are indexes; both inclusive. // Return: first -> value, second -> index pui_t query_max(uint_t qf, uint_t ql); pui_t naive_query_max(vui_t const& v, int i, int j); }; #endif // __BENDERRMQ_H
If you are worried about not speaking Spanish for your upcoming trip to Costa Rica, you’re not alone. We remember those days too and hear from lots of others who are unsure of how they’ll get by without much or any Spanish. The good news is that many Ticos (Costa Ricans) have some English skills, and others, especially those working in the tourism industry, are quite fluent. Costa Rica is a Spanish-speaking country, however, and you are bound to get some blank stares in certain situations. In this post, we’ll give you some of the most common Spanish words and phrases for your visit to Costa Rica. Simple Spanish for Visiting Costa Rica | Two Weeks in Costa Rica Talking with the Locals Before we start in on the specifics, there is something you should know about talking Spanish to Ticos. Costa Ricans are in general some of the friendliest people on earth. For this reason, they will usually go out of their way to help you. This applies to speaking Spanish as well so don’t feel stupid if the person you are talking to is correcting your pronunciation or word choice. In most instances, they really appreciate that you are trying and only want to help. Another thing that goes along with this is that many Ticos are just as shy about their English skills as you are about your Spanish. If you have the confidence to try speaking some Spanish, you might find that suddenly they get up the courage to use their English too. If you both sound bad but somehow figure it out, everyone wins! Different Scenarios Below are some of the situations you’re likely to encounter on your next trip to Costa Rica. Saying Hello Hola = Hello. This is the basic way to say hello. Buenos días = Good morning Buenas tardes = Good afternoon Buenas noches = Good evening Buenas = Shorthand way of saying hello, any time of day. It is more casual and works in the morning, afternoon, or evening. You’ll hear the locals use this all the time. Saying Goodbye Chao = Bye. The basic way to say goodbye. Adiós = A slightly more formal way of saying goodbye. We have also heard adiós used as a sort of greeting and goodbye. For example, if you are driving past someone walking on the street and want to greet them, you could say adiós instead of hola. The idea is that you aren’t staying around to chat. Hasta luego = See you later, or literally, until later. Hasta mañana = See you tomorrow (“until tomorrow”). Asking for Things Discúlpe = Excuse me (when you need to get someone’s attention). Quiero… = I would like… Necesito… = I need… ¿Tiene…? = Do you have…? Good to use if you’re looking for a certain item at a store (e.g., ¿Tiene Tylenol?) ¿Puedo…? = Can I…? ¿Puede…? = Can you…? ¿Dónde? = Where? ¿Dónde está…? = Where is…? Useful when asking for directions or where something is (¿Dónde está el baño? Where is the bathroom?) ¿Cuanto cuesta? = How much does it cost? ¿Acepta tarjetas de crédito? = Do you accept credit cards? ¿Habla Inglés? = Do you speak English? Some Ticos might reply un poco (a little). ¿De donde eres? = Where are you from? Los Estados Unidos is the United States; Canadá is Canada. Remember that America is used to describe North, Central, and South America. = Yes No = No Tal vez = Maybe Claro = Of course In a Restaurant ¿Para tomar? = What would you like to drink? This is usually the first thing a server will ask you. Agua = Water. You might want una botella de agua (a bottle of water) or agua del tubo (tap water). Una cerveza = A beer. Check out our post about the most popular local beers. Vino = Wine. Vino tinto is red wine and vino blanco is white wine. Café = Coffee. The server will ask you ¿Café con leche o negro? (Coffee with milk or black). Don’t worry, they always bring sugar packets. Refresco naturale = A fruit drink with ice (hielo). Batido = A fruit smoothie. Con agua means blended with ice and con leche means blended with ice and milk (milk shake). Popular Local Dishes Gallo pinto = Breakfast dish of rice and beans mixed together, served alongside eggs and fried plantain. Sometimes comes with fried local cheese (queso), toast (tostadas) or tortillas, and fruit (frutas). Gallo pinto literally translates to painted rooster.          Huevos fritos = Fried eggs          Huevos revueltos = Scrambled eggs Casado = Lunch Plate. Casado translates to “married” and this traditional lunch dish truly has a marriage of flavors. The dish usually consists of rice (arroz) and beans (frijoles), a protein like meat (bistec/steak; chuleta de cerdo/pork chop; or pollo/chicken) or fish (pescado), and several side salads like green salad (ensalada verde), pasta salad (ensalada pasta), etc. Arroz con pollo = Rice with chicken. This is a fried rice dish that is very flavorful. Instead of chicken (pollo), you might also see rice with shrimp (arroz con camarones) and other variations. Sopa = Soup. Common soups are olla de carne (similar to beef stew), sopa de mariscos (seafood soup), and sopa negra (black bean soup, usually with a poached egg). Soups are typically served with a side of white rice. Cashing Out Para llevar = To go (for your leftovers) La cuenta, por favor = The bill, please. In Costa Rica, the server won’t bring this unless you ask for it. Servicio = Service. This is the 10% added to the bill for tip. You can add more if you like. Impuestos ventas = Sales tax (13%) Estación de buses = Bus station Parada de bus = Bus stop Tiquete = Ticket (for the bus, ferry, etc). Not all buses use tickets but it is good to ask. ¿Necesito un tiquete? (Do I need a ticket?). Taxi = Taxi ¿A donde va? = Where are you going? What’s your destination? Voy a… = I am going to… Pare aquí = Stop here ¿Esta es la calle a…? = Is this the road to…? Lleno con regular, por favor = Fill it with regular (gas) please. Gas stations in Costa Rica are always full service. La llanta necesita aire = The tire needs air. We hope these simple Spanish words and phrases will help you feel more comfortable while traveling to Costa Rica. When we first visited almost ten years ago, we had zero knowledge of Spanish and got along fine. Just remember, the one term you need to learn is Pura Vida. This can mean hello, goodbye, and that’s great, but the real meaning is more of an attitude that you will discover once you arrive and will never forget. If you’re looking for a lot more helpful words and phrases, we highly recommend the pocket-sized Costa Rican Spanish Phrasebook by Lonely Planet. This is what we used to carry with us when we were newbies and it got us out of a lot of jams. Notice anything essential missing from our list? Add it to the comments below! Looking for more resources for your upcoming trip? Check out these posts:
Prevent Direct Execution of EXE The sample code here is pretty simple: #include "mainwindow.h" #include <QApplication> int main(int argc, char *argv[]) QApplication a(argc, argv); if (argc <= 1) return 0; if (argv[1] != "yourpassword") return 0; MainWindow w;; return a.exec(); In the example above, your EXE will simply pop out an error message that says “Please run MyGame.exe instead.” if you double click on it directly. This is because the argc variable is either 0 or 1 (depending on platform, which means no additional input argument during launch) if you run it directly. However, if there is one or more arguments being dumped to the program during launch, check (within the argv array) whether the second argument (the first argument is usually the program’s name) matches your secret phrase or password before allowing the program to launch. Usually there will be input arguments if the user drag one or more files to the EXE to make it launch, as this is very useful for programs like text editors or image editors. That’s why we must check if the argument matches your password or not. Now that your program can no longer be run directly, what about the updater? How to ask the updater to execute your main program with an input argument? It’s actually pretty easy as well. In the following example I will be using C/C++ and Qt, but it should be similar across different programming languages and platforms: QProcess *process = new QProcess(this); delete process; That’s all, it’s very simple to achieve. The tutorial above is by no mean professional: Technical names and phrases are not necessarily accurate, and the method used is not necessarily the standard way. I’m just trying to share what I know and what I did with my own projects. Peace. Gigabyte BRIX (Intel NUC) GB-XM12-3227 Review So… the other day I bought this Gigabyte BRIX barebone which is basically an Intel NUC system, but manufactured by Gigabyte. I’ve tried the vanilla Intel NUC systems before and it worked great, except the older generation which had over-heating issue but resolved after adding a thermal pad to it as well as a firmware upgrade, but overall still pretty okay I guess. Now, back to Gigabyte BRIX, specifically the GB-XM12-3227 model. I can’t talk about the other models as I have never used it before, so let’s just stick to this one. All-and-all, it worked fine at first. It booted up Windows 10 without any problem, HDMI connected to the monitor without any problem, great resolution, etc. UNTIL I tried to use the web browser. Even though the internet status is “connected”, I still couldn’t use the damn internet on my browser. After hours and hours of research and trials, I realized that the issue is the firmware. Not only it’s old (from 2013), but it’s supposedly for Windows 8.1, and not Windows 10. Went to Gibabyte’s website to look for the latest drivers, and guess what, they only have firmware updates up to 2014, so still, no Windows 10 support. Further more, I downloaded the latest BIOS and tried to flash it, only to realize the BIOS utility doesn’t support 64-bit Windows, because it is a god-damn Windows XP Service Pack 2 executable file! Then, I went to Windows 10’s Device Manager and check out my wireless network adapter’s properties. This is when I realized the WiFi adapter only supports up to IEEE 802.11b/g and not the newer IEEE 802.11b/g/n, which unfortunately is what I set on my router. So then I moved over to my router’s admin page and changed the Transmission Mode to the appropriate setting. I have no idea what’s causing this. Outdated BIOS? Outdated drivers? I have no idea. However, despite able to connect to the internet now, the speed is still very limited. Often time it took roughly 20 seconds or more just to load a web page. Then, I used a Chinese software called 360安全卫士 (translated as “360 Safety Guard”) and went to the “Optimization and Speed-up” page. That particular page contains an automated scan-and-fix feature which includes “network speed-up” option. After running the optimization process, my wireless network is finally back to usable state! What sorcery is that?? (However, IEEE 802.11b/g/n is still not supported). Overall, the Gigabyte BRIX works okay except the BIOS and drivers are really outdated and urgently need an update. That’s all for today, have a nice day folks. OpenGL Side Project At the moment my prototype does the following: • Running OpenGL 3.2 core profile and GLSL 150 • Loads OBJ files and PNG/JPEG textures • Move, rotate, scale model • Skybox Some Quick Update Stay tuned. Easter Egg
Fixing bugs like it's 1988 I grew up in the 80's, the decade home computers went from curiosity to mainstream. In primary school we had several Philips P2000T home computers and a pair of Apple Macintosh — ehm, Macintoshes? Two of those, anyway. A friend had a C64 we used to play games on, and at some point my dad bought a C128 for his financial administration. (What I really love is the fact that, to this day, he is still doing his financial administration on a C128, albeit an emulated one. He is an "if it ain't broke don't fix it" kinda guy.) Soon after the C128, we got a C64. Where the C128 was for business, the C64 was for fun. I have fond memories playing games such as Space Taxi, Super Cycle, Velicopede, Last Ninja II, and Electrix, to name a few. It was also the computer that got me into programming. With the invention of the World Wide Web still a couple of years off, learning to program mostly involved reading books and magazines. Computer magazines would often publish source code listings which the reader could type in. The result could be anything: A game, a disk copy tool, a drawing program for GEOS, or, more often than not, something that didn't quite work because of typos. At some point, magazines started publishing listings with a checksum added to each line. They offered special tools that would compute the checksum of each line you typed, and checked it against the checksum you typed in at the end of the line. This helped a lot. Still, it must have been one of the slowest and most error prone ways to copy a computer program in the history of computer programs. It was fun though, or at least, that's what I thought. One such magazine was Commodore Dossier, a "practical magazine for the active Commodore owner", which ran from 1984 until 1988. The 17th issue, which was also the last issue, featured a type-in listing for a rather interesting game. It was called Blindganger, which translates to dud, but was used to mean blind person (ganger literally means go-er, someone who goes). The cover of Commodore Dossier, issue 17. In the aftermath of what one can only imagine must have been a proper night on the town, the blind guy in question somehow wakes up inside the city sewers. It's the player's job to guide him back to the streets using only the sounds created by his white cane for guidance. The city's wastewater division, being exceptionally keen on sewer hygiene, flushes the sewers every five minutes. Each flush lands our blind guy someplace else inside the sewers, from where he has to restart his search for the exit. On the third flush the game ends. A map of the sewers is displayed, showing the location of the exit as well as the locations visited by the player. Having typed-in the listing sometime in the fall of 1988, I started the game. It had a sprite animation of a bat flying in front of the full moon on an otherwise completely black screen, which I thought was pretty cool. However, I couldn't figure out the controls. The sewer map should have helped, of course, but something was wrong with it. The locations marked as visited on the map did not seem to match the path I thought I had taken. Also, sections of wall would often be marked as visited. An example of a sewer map produced by the original game. After a couple of tries I gave up and went on to do other things, but this business with the sewer map and the incomprehensible controls somehow stuck with me. And so, when I came across a scan of this particular issue of Commodore Dossier I knew it was time to sort it out once and for all. Of course, before I could start, I had to type in the listing again. Back in 1988, I lacked the checksum tool published by Commodore Dossier. Maybe the map of the sewers was messed up just because of my not-quite-touch-typing skills? A quick Google search turned up a disk image that contained a program called "CHECKSUM DOSSIER". This sounded promising! To confirm, I ran the program and typed a short line from the Blindganger listing: "240 RETURN", followed by the checksum "7E". Then I tried inserting a typo either in the line itself or in the checksum. In both cases, this resulted in the message "FOUT IN REGEL", or "ERROR IN LINE", being printed on the screen. Oh yeah! Ain't that cute, BUT IT'S WRONG!! I typed in the listing using the checksum tool. Parts of the scan were of rather low quality and here the tool really helped a lot. I often found myself trying variants of some line and its checksum until I found a combination that matched. So far, so good. Now I had a copy of the original that was guaranteed to be free of typos. Surely, this copy would not produce the same sewer maps as the copy I typed in back in 1988. But... it did! To find out why, I needed to locate the code that displays the map of the sewers. The sewer map is displayed when the game ends, which happens when the player finds the exit or when the sewers are flushed for the third time. Concentrating on the second case, I looked through the BASIC listing of the game for a check on zero or three. Sure enough, on line 1780, the variable MAAL is compared to zero. This variable is initialized to three on line 1550 and counts down on each flush of the sewers. The block of code on lines 1810 – 1840 is executed if MAAL equals zero. Line 1840 is an endless loop. Looking at the other three lines of BASIC, our next target is the machine code subroutine located at memory address 16540 ($409C). 1810 POKECROSS+4096,1 :REM MARK EXIT ON THE MAP 1820 SYS16540 :REM COPY MAP TO SCREEN 1840 GOTO1840 :REM ENDLESS LOOP This subroutine consists of two parts. The first part copies 1000 bytes from the memory region starting a $6000 to screen memory ($0400 – $07E7). This fills the entire screen (40 columns times 25 rows = 1000 bytes) with a map of the sewers. As it turns out, this part does not contain any bugs. The map of the sewers may look strange, until you notice that all of the blocky bits are walls, '@' marks a horizontal section of pipe, 'A' marks a vertical section of pipe, 'B' through 'J' mark different types of corners and crossings, 'K' marks a pit, and 'L' marks the exit. These characters are not random. They correspond to screen codes 0 through 12. The map is just a dump to the screen of the internal representation of the sewers used in the game. The second part of the subroutine copies 1000 bytes from the memory region starting at $7000 to color RAM ($D800 – $DBE7). This marks all visited locations with the color yellow. L40CB: LDA #$FF ; >-- initialization -- STA $FB ; | LDA #$6F ; | STA $FC ; | LDA #$F4 ; | STA $FD ; | LDA #$D7 ; | STA $FE ; <-------------------- LDX #$04 ; >-- outer loop ----------------- L40DD: LDY #$FA ; >-- inner loop I --- | L40DF: LDA ($FB),Y ; (copy bytes) | | STA ($FD),Y ; | | DEY ; | | LDY #$FA ; >-- inner loop II ----------- | L40E8: INC $FB ; (update base addresses) | | BNE L40EE ; | | INC $FC ; | | L40EE: INC $FD ; | | BNE L40F4 ; | | INC $FE ; | | L40F4: DEY ; | | DEX ; | The bytes are copied in four blocks of 250 bytes. The outer loop uses the X-register to count from 4 down to 0. LDX #$04 ; inner loop BNE L40DD The first inner loop uses the Y-register to count from #$FA (250) down to 0. L40DD: LDY #$FA L40DF: LDA ($FB),Y STA ($FD),Y BNE L40DF Indirect-indexed addressing is used to copy bytes in the inner loop. In this addressing mode, the Y-register is used as an offset that is added to a 16-bit base address stored in zeropage. For example, the instruction LDA ($FB),Y is executed as follows: • Read the litte-endian 16-bit base address stored in zeropage locations $FB and $FC. Little endian byte order means the least significant byte is stored at the lowest address ($FB). $FB is initialized to #$FF and $FC to #$6F, so the 16-bit base address is $6FFF. • Add the value of the Y-register to the base address to compute the effective address. The Y-register is initialized to #$FA at the beginning of the loop. Adding to $6FFF yields $70F9 as the effective address. • Load a byte from the effective address into the accumulator (A-register). The Y-register counts down from 250 to 0. Note that the smallest value of Y used as an index is 1. (When the DEY instruction decreases Y to zero, the following BNE branch instruction will fall through, exiting the inner loop.) The first byte to load is located at $7000. Because the minimal value of Y is 1, the source base address needs to be initialized to $7000 - 1 = $6FFF. Similarly, the first byte to store is located at $D800, so the target base address should be initialized to $D800 - 1 = $D7FF. Instead, it is initialized to $D7F4! Accidentally typing #$F4 instead of #$FF is not very likely. But in decimal, this corresponds to typing 244 instead of 255. It seems the original author accidentally hit the 4 instead of the 5 while typing the constant 255! This shifts the colors used in the sewer map by 11 positions relative to the map itself. In turn, this means the locations marked as visited on the map are wrong. The offending byte resides in a data statement on line 3670 of the BASIC listing: 3670 DATA 252,169,244,133,253 After changing it to the correct value of 255, the sewer map displays correctly. And that's that.... bug fixed after 29 years! To celebrate, I've put together a 2017 version of the original game that includes this fix, as well as fixes for several other issues I came across while going over the code: • Visited locations are correctly displayed on the sewer map shown at the end of the game. • The time penalty for falling down a pit is taken into account when computing the amount of time left. • The street noise volume is set such that it depends on the distance to the exit (as intended by the original authors). • English translation. (Press and hold the H-key during the game to view the online help.) Blindganger 2017 is also available as a BASIC listing including checksums. For the authentic 80's experience, just download and run the Commodore Dossier checksum tool (see link below) and start typing! In the next episode, we will make some improvements to the (now correct) sewer map to make it easier to understand (see the example below). X marks the spot! Related links: 1. Very interesting! BTW what software package is your father using for finances? I'm a sucker for CBM retro. 1. You probably won't be familiar with it. The program is called Bookspeed. My father is a general practitioner. Bookspeed was written by J.L van Geijlswijk, another GP. It was specifically written for GPs to do their accounting. It was fairly comprehensive, featuring double entry accounting, annual balance sheet generation, et cetera. It stored the data entered by the user as part of the program itself as DATA statements. I remember having to fix the disk image by hand from inside the emulator using Disk Doctor, because my dad had closed the emulator in the middle of a write. Fun times! 2. Very nice story! Had similar experiences with my ZX Spectrum and badly printed, hard to read source code listings found in various magazines. On a related note: I also used the Spectrum for some of my homework in highschool - calculating parabolas and such. Back then it was called chaeting, where as today, I might have been considered the next Bill Gates or something... 3. I echo Marc Carson's sentiment: would be great to know what finance app your dad uses for the C128. Also, that is one hell of a cool debugging project, well done! 4. Wow. I love this. It'd be nice to see/hear a video of the game in all its fixed glory. 1. Thanks! Actually, I think a video would get pretty boring pretty fast. You really have to play it to get into it. The game needs (plenty of) your imagination. Like Rogue on the PC, if you're familiar with that. Unless you can convince yourself that 'B' is a ferocious bat and 'Z' really is a zombie, it stays rather dull. 5. Fun read, nostalgia warming the heart. Thanks! And I too would be curious to know what software your father is still using... 6. Crying from nostalgia here. Think it was more like 1983, writing self-taught machine code directly to memory.... and programming the sound chip from the register list that was in the printed manual YOU GOT WITH THE MACHINE! 7. Wow. What incredible commitment to revising the imperfect past. Have some groovy 80's-ish music on us: Also, capital L Love Commodore, but came much later to the party. Amigas were my introduction to computers. Post a Comment
By Jason Kohn, Contributing Columnist Like many of us, scientific researchers tend to be creatures of habit. This includes research teams working for the National Oceanic and Atmospheric Administration (NOAA), the U.S. government agency charged with measuring the behavior of oceans, atmosphere, and weather. Many of these climate scientists work with massive amounts of data – for example, the National Weather Service collecting up-to-the-minute temperature, humidity, and barometric readings from thousands of sites across the United States to help forecast weather. Research teams then rely on some the largest, most powerful high-performance computing (HPC) systems in the world to run models, forecasts, and other research computations. Given the reliance on HPC resources, NOAA climate researchers have traditionally worked onsite at major supercomputing facilities, such as Oak Ridge National Laboratory in Tennessee, where access to supercomputers are just steps away. As researchers crate ever more sophisticated models of ocean and atmospheric behavior, however, the HPC requirements have become truly staggering. Now, NOAA is using a super-high-speed network called “n-wave” to connect research sites across the United States with the computing resources they need. The network has been operating for several years, and today transports enough data to fill a 10-Gbps network to full capacity, all day, every day. NOAA is now upgrading this network to allow even more data traffic, with the goal of ultimately supporting 100-Gbps data rates. “Our scientists were really used to having a computer in their basement,” says Jerry Janssen, manager, n-wave Network, NOAA, in a video about the project. “When that computer moved a couple thousand miles away, we had to give them a lot of assurances that, one, the data would actually move at the speed they needed it to move, but also that they could rely on it to be there. The amount of data that will be generated under this model will exceed 80-100 Terabits per day.” The n-wave project means much more than just a massive new data pipe. It represents a fundamental shift in the way that scientists can conduct their research, allowing them to perform hugely demanding supercomputer runs of their data from dozens of remote locations. As a result, it gives NOAA climate scientists much more flexibility in where and how they work. “For the first time, NOAA scientists and engineers in completely separate parts of the country, all the way to places like Alaska and Hawaii and Puerto Rico, will have the bandwidth they need, without restriction,” says Janssen. “NOAA will now be able to do things it never thought it could do before.” In addition to providing fast, stable access to HPC resources, n-wave is also allowing NOAA climate scientists to share resources much more easily with scientists in the U.S. Department of Energy and other government agencies. Ideally, this level of collaboration and access to supercomputing resources will help climate scientists continue to develop more effective climate models, improve weather forecasts, and allow us to better understand our climate. Powering Vital Climate Research The high-speed nationwide HPC connectivity capability provided by n-wave is now enabling a broad range of NOAA basic science and research activities. Examples include: - Basic data dissemination, allowing research teams to collect up-to-the-minute data on ocean, atmosphere, and weather from across the country, and make that data available to other research teams and agencies nationwide. - Ensemble forecasting, where researchers run multiple HPC simulations using different initial conditions and modeling techniques, in order to refine their atmospheric forecasts and minimize errors. - Severe weather modeling, where scientists draw on HPC simulations, real-time atmospheric data, and archived storm data to better understand and predict the behavior of storms. - Advancing understanding of the environment to be able to better predict short-term and long-term environmental changes, mitigate threats, and provide the most accurate data to inform policy decisions. All of this work is important, and will help advance our understanding of Earth’s climate. And it is all a testament to the amazing networking technologies and infrastructure that scientists now have at their disposal, which puts the most powerful supercomputing resources in the world at their fingertips – even when they are thousands of miles away.
We gratefully acknowledge support from the Simons Foundation and member institutions Full-text links: Current browse context: Change to browse by: References & Citations (what is this?) General Relativity and Quantum Cosmology Title: Constant-roll Inflation in $F(R)$ Gravity Abstract: We propose the study of constant-roll inflation in $F(R)$ gravity. We use two different approaches, one that relates an $F(R)$ gravity to well known scalar models of constant-roll and a second that examines directly the constant-roll condition in $F(R)$ gravity. With regards to the first approach, by using well known techniques, we find the $F(R)$ gravity which realizes a given constant-roll evolution in the scalar-tensor theory. We also perform a conformal transformation in the resulting $F(R)$ gravity and we find the Einstein frame counterpart theory. As we demonstrate, the resulting scalar potential is different in comparison to the original scalar constant-roll case, and the same applies for the corresponding observational indices. Moreover, we discuss how cosmological evolutions that can realize constant-roll to constant-roll eras transitions in the scalar-tensor description, can be realized by vacuum $F(R)$ gravity. With regards to the second approach, we examine directly the effects of the constant-roll condition on the inflationary dynamics of vacuum $F(R)$ gravity. We present in detail the formalism of constant-roll $F(R)$ gravity inflationary dynamics and we discuss how the inflationary indices become in this case. We use two well known $F(R)$ gravities in order to illustrate our findings, the $R^2$ model and a power-law $F(R)$ gravity in vacuum. As we demonstrate, in both cases the parameter space is enlarged in comparison to the slow-roll counterparts of the models, and in effect, the models can also be compatible with the observational data. Finally, we briefly address the graceful exit issue. Comments: minor revision, typos corrected Cite as: arXiv:1704.05945 [gr-qc]   (or arXiv:1704.05945v2 [gr-qc] for this version) Submission history From: Vasilis Oikonomou [view email] [v1] Wed, 19 Apr 2017 22:13:21 GMT (415kb) [v2] Sun, 25 Jun 2017 18:35:12 GMT (414kb)
The power of math can be exponential When I was in elementary school, my parents made sure that I learned. They knew that all of my subjects were important, certainly. But I have special memories of discussing literature and history over the dinner table. They made sure that I really LEARNED my math. I had some terrific teachers in all of those subjects. Somewhere along the line, though, I developed a special appreciation for math. As a result, I majored in business in college. It is certainly not a leap, since business is full of math. For the past 5 years, I have been a professional tutor, and have loved it. Although I tutor MANY subjects, the one that is in the most demand is math. I have a special love for tutoring pre-algebra and algebra. I practically skip through my day on the days I will be teaching math. I make it a special goal to help my students not only understand math, but perhaps to even fall in love with it. It used to be that I would comb book sale tables at the library and garage sales for novels. But these days, I scour them for math textbooks. I am on the lookout for innovative explanations and examples that will help my students. I am quite enamored with Khan academy, as he explains so many things so well. I always let my families know about his resource.  It is a terrific site to visit. You don’t have to be a student ~ he has tutorials on all kinds of things. Here is the site ~ go ahead, take a look. I will wait. Many of my competitors think that I am crazy to tell them about a free resource. MY goal is to turn my students into independent learners, so that they can soar like eagles at some point. Through my tutoring, and multiple resources, they can learn every day, even when they are not in a session with me. To those students who ask the typical question “Why do I have to learn this? When will I EVER have to use it in REAL life?” I smile and tell them a story. When I took Algebra 2/Trigonometry in high school, I had a fabulous math teacher. His name (really and truly) was Mr. John Wayne. He was the tennis coach, and he was a great math teacher. One day I was particularly frustrated. I raised my hand and  asked him those very questions. He just smiled at me. He tossed his chalk up and down, catching it every time. Then he said, “some day, years from now, you will be using algebra in ways you cannot even begin to imagine today. When you do, I hope you will think of me”. Believe me, I do think of him. After all, I walk in his magnificent footsteps when I tutor math. I raise my eyes to the heavens, and I say, “thanks.  I LOVE algebra, and I completely understand why you taught it”. I tell my students that learning is SO important. It IS worthwhile. I loved this article that I have included at the end of this post. First person: Math has power over all else By Kevin Levine Friday January 10, 2014 9:03 PM For as  long as I can remember, I’ve liked numbers. I like math. That puts me in a powerful minority. People who understand and embrace math wield the most powerful weapon ever made. Let’s dispense with the obvious reasons that math is powerful. The most effective (destructive) weapons rely on physics, or the science of equations, and chemistry. (Try making a stable mixture of chemicals without math.) Some of the constructive uses are equally powerful: Medicines, medical equipment, roller coasters, air travel and cellular technology all rely on math. Yet the true power of math comes from the ignorance and fear of it. One of my earliest memories of math’s potency stems from this: “Four out of 5 dentists recommend sugarless gum for their patients who chew gum.” Anyone of a certain age knows the saying from a Trident gum commercial. I remember thinking as a child that Trident gum must be good for me. That’s power. Before long, I started asking questions: Which doctors? Why didn’t the fifth doctor recommend sugarless gum? How many doctor s were asked? A few years later: Do these dentists work for Trident? Why would dentists recommend gum at all? How often is a statistic presented as fact, in a vacuum, without supporting documentation or an understanding of the source of the statistic? A statistic is used as a club to hammer home a message. When one doesn’t understand all that went into generating the statistic, its power becomes immense — a blunt instrument that relies on the general population’s dislike, and ignorance, of math. How about math as an economic weapon? Isn’t it wonderful that tuna fish (or peanut butter or jelly) hasn’t gone up in price in years? Thank math. The tuna can contained 8 ounces, then 6 ounces, then 5 ounces. Incremental changes in volume go unnoticed because the price remains constant. Consumers think: “Wow, tuna prices are stable.” The tuna company thinks: “Wow, consumers are ignorant.” Politicians love math, too. They cherry-pick one statistic from an obscure report commissioned by an obscure group whose agenda might not be to the betterment of humanity. Politicians use math to convince us that everything would be OK if we just cut fraud and abuse in the welfare system. They use math to confirm that the American education system is failing. They use math to justify increased spending in their districts while bemoaning the spending everywhere else. Politicians thrive on the public’s fear and ignorance of math. The only way to weaken math’s destructive capabilities is to embrace math. Instead of telling our children we weren’t good in math, we should tell them that math is the secret to power — that it will make them creative, competitive, powerful, less prone to scams and more valuable in the workplace. We should tell our children to respectfully question authority, especially when numbers are used as weapons. Mastering math, our children should learn, is akin to mastering the most powerful weapon on Earth. Kevin Levine, 48, of Bexley teaches sixth-grade math at Karrer Middle School in Dublin. About Kate Kresse This entry was posted in education and career, faith/courage/miracles/hope and tagged , , , , , . Bookmark the permalink. 7 Responses to The power of math can be exponential 1. Kathy says: Love it! Texas has decided to drop Algebra II as a graduation requirement. I have very mixed feelings about this change in our curriculum.While some students are not going to go to college and their trade school won’t require it others may be sadly surprised when they find that the school of their choice requires it even though Texas doesn’t. • Kate Kresse says: i have mixed feelings about that too, Kathy. there is such a feeling of mastery/accomplishment when you complete Algebra II. There are som many ways for them to learn it, and it robs them of something valuable to cancel the requirement. That is regardless of who “requires” it at the next level. {sorry it took me so long to reply!] 2. Kathy says: Reblogged this on To Talk of Many Things and commented: 3. And it all begins with learning to count, add, multiply, etc. They want to skip that part, these days, the part that even as a math-unappreciative, I KNEW I would always need. Amazing, eh? • Kate Kresse says: In addition to the drilling of math facts, through repetition and competitively racing to the blackboard, we had so many other ways that we practiced math facts. We skip counted when we did jump rope, we skip counted when we walked, we counted and regrouped when we played jacks, and my folks would play math games. Math enriched us.We cooked and measured things with our moms (sewing, buttons, etc). We measured things and grouped things with our dads.{A number of my students have never even seen a yardstick, or used a measuring cup}. By doing those things, we had an ingrained “number sense” that many of my students lack. A number of my students don’t connect the integers and fractions to any real meaning. The integer and the word for a number doesn’t necessarily represent a group or a quantity to them at all. This is similar to a student I had that had reading difficulties. He could read flawlessly, even if you gave him a 12th grade novel. The mechanics, the sentence pauses, the pronunciation, those were all done flawlessly. But he had NO idea what he had just read. This was true whether he read silently or aloud. If I asked him questions about it, he would have to re-check at least a half dozen times, even if I had him read just one sentence, and asked him a basic question about that sentence. There was no meaning attached to the words. This is something that he sort of “outgrew” a couple of years later. Some of my students have a major disconnect in math, as I described. This makes it nearly impossible for them to memorize their math facts. We are working with counters and charts, so that they can begin to understand and retain the patterns. It mystifies me, it truly does. It frustrates my students! 4. It is no mystery to me, how they got this way, but surely is a mystery why caring adults are sending them this way. I understand, on a governmental level, why we’d want the next generation unable to function, but it seems every teacher out there just doesn’t get it. Well, almost every… Leave a Reply You are commenting using your account. Log Out / Change ) Twitter picture Facebook photo Google+ photo Connecting to %s
publisher Rodney Buike and Virtualization When I was in Winnipeg, I had the good fortune to meet Rodney Buike at the Winnipeg IT Pro UserGroup.  I also killed his Dell Laptop harddrive (which he fixed by smacking it on the desk a few times) and shared some pints of the local Fort Gary brew while debating virtualization technologies and various other topics.  Rodney is a Microsoft MVP for Windows Server and the publisher of (Great Site!).  He also provides content for and is working on a book on Virtual Server 2005. He took up my challenge to provide content for the Canadian IT Pro team blog as a guest blogger - so please welcome him and his first post: Virtualization technologies have been around for years.  Vmware was one of the first to begin selling virtualization software in 1999 and in early 2003 Microsoft purchased virtual machine technologies from a company called Connectix. This purchase led to the development of Virtual PC 2004 and Virtual Server 2005.  In the past, when a user needed to use or test an application on a certain operating system (OS), the user would require a computer on which the OS could be installed which would allow them to test the application. Having to test the application on a number of different OS would require the hardware and time to install the desired operating system.  At the same time systems were becoming more and more powerful and utilized less and less. Today’s multi-GHz and multi-core CPUs, large hard disks and abundance of cheap memory provide more power than most users require.  Typically, today’s computers run at about 10-15 percent utilization.  By leveraging virtualization technologies, users can harness the extra power and reduce the amount of physical hardware required and instead, install multiple virtual machines with whichever combination of operating systems and applications they require. The benefits of virtualization are easy to see.  Software developers no longer need multiple physical machines, or ghosted images in order to test their applications in different operating system environments, students don’t need a pile of donated computers in order to build a lab environment and get hands on experience with new technologies and IT departments can benefit by consolidating servers and migrating legacy systems to new hardware. Corporate system administrators can reduce costs by running multiple virtual machines, performing different tasks, on a single physical machine. By doing this, costs are reduced for both the physical hardware requirements as well as the operating system licensing needs. This also allows system administrators to utilize all the power available to them in a physical machine. For example, if an application running on a physical machine only utilizes 15% of machine resources, it would be possible to run 6 virtual machines at 90% utilization. This is a much more economical use of hardware resources. Today more and more IT departments are looking to leverage the befits of virtualization in an effort to consolidate servers.  Improvements in Virtual Server 2005 R2, such as virtual server host clustering, make the idea of virtualizing the corporate infrastructure more acceptable and appealing.  If you are (or are not) using virtualization technologies drop me a line with a comment.  I am very interested in hearing your reasons why (or why not) and your experiences. Comments (2) 1. Anonymous says: I posted my first guest post on the Canadian IT Professionals blog over at TechNet Canada.  The article is a brief summary on the benfits of virtualization.  Go check it out and add it to your RSS aggregator as there are some great guest bloggers over 2. Anonymous says: Well time flies when you are having fun, and being an MVP this last year has been a blast.  I got notified my term was up and that I am re-nominated and had to send in some information on what I did last year as an MVP.  It got me thinking and boy was Skip to main content
// Copyright 2013 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 "libcef/browser/devtools/devtools_frontend.h" #include <stddef.h> #include <iomanip> #include <utility> #include "libcef/browser/browser_context.h" #include "libcef/browser/devtools/devtools_manager_delegate.h" #include "libcef/browser/net/devtools_scheme_handler.h" #include "libcef/common/cef_switches.h" #include "libcef/common/task_runner_manager.h" #include "base/base64.h" #include "base/command_line.h" #include "base/files/file_util.h" #include "base/guid.h" #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/json/string_escape.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/task/post_task.h" #include "base/values.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/pref_names.h" #include "components/prefs/scoped_user_pref_update.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/file_url_loader.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/shared_cors_origin_access_list.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "content/public/common/content_client.h" #include "content/public/common/url_constants.h" #include "content/public/common/url_utils.h" #include "ipc/ipc_channel.h" #include "net/base/completion_once_callback.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" #include "net/http/http_response_headers.h" #include "net/traffic_annotation/network_traffic_annotation.h" #include "services/network/public/cpp/simple_url_loader.h" #include "services/network/public/cpp/simple_url_loader_stream_consumer.h" #include "services/network/public/cpp/wrapper_shared_url_loader_factory.h" #include "services/network/public/mojom/url_response_head.mojom.h" #include "storage/browser/file_system/native_file_util.h" #if defined(OS_WIN) #include <windows.h> #elif defined(OS_POSIX) #include <time.h> #endif namespace { // This constant should be in sync with the constant in // chrome/browser/devtools/devtools_ui_bindings.cc. constexpr size_t kMaxMessageChunkSize = IPC::Channel::kMaximumMessageSize / 4; constexpr int kMaxLogLineLength = 1024; static std::string GetFrontendURL() { return base::StringPrintf("%s://%s/devtools_app.html", content::kChromeDevToolsScheme, scheme::kChromeDevToolsHost); } base::DictionaryValue BuildObjectForResponse(const net::HttpResponseHeaders* rh, bool success, int net_error) { base::DictionaryValue response; int responseCode = 200; if (rh) { responseCode = rh->response_code(); } else if (!success) { // In case of no headers, assume file:// URL and failed to load responseCode = 404; } response.SetInteger("statusCode", responseCode); response.SetInteger("netError", net_error); response.SetString("netErrorName", net::ErrorToString(net_error)); auto headers = std::make_unique<base::DictionaryValue>(); size_t iterator = 0; std::string name; std::string value; // TODO(caseq): this probably needs to handle duplicate header names // correctly by folding them. while (rh && rh->EnumerateHeaderLines(&iterator, &name, &value)) headers->SetString(name, value); response.Set("headers", std::move(headers)); return response; } void WriteTimestamp(std::stringstream& stream) { #if defined(OS_WIN) SYSTEMTIME local_time; GetLocalTime(&local_time); stream << std::setfill('0') << std::setw(2) << local_time.wMonth << std::setw(2) << local_time.wDay << '/' << std::setw(2) << local_time.wHour << std::setw(2) << local_time.wMinute << std::setw(2) << local_time.wSecond << '.' << std::setw(3) << local_time.wMilliseconds; #elif defined(OS_POSIX) timeval tv; gettimeofday(&tv, nullptr); time_t t = tv.tv_sec; struct tm local_time; localtime_r(&t, &local_time); struct tm* tm_time = &local_time; stream << std::setfill('0') << std::setw(2) << 1 + tm_time->tm_mon << std::setw(2) << tm_time->tm_mday << '/' << std::setw(2) << tm_time->tm_hour << std::setw(2) << tm_time->tm_min << std::setw(2) << tm_time->tm_sec << '.' << std::setw(6) << tv.tv_usec; #else #error Unsupported platform #endif } void LogProtocolMessage(const base::FilePath& log_file, ProtocolMessageType type, std::string to_log) { // Track if logging has failed, in which case we don't keep trying. static bool log_error = false; if (log_error) return; if (storage::NativeFileUtil::EnsureFileExists(log_file, nullptr) != base::File::FILE_OK) { LOG(ERROR) << "Failed to create file " << log_file.value(); log_error = true; return; } std::string type_label; switch (type) { case ProtocolMessageType::METHOD: type_label = "METHOD"; break; case ProtocolMessageType::RESULT: type_label = "RESULT"; break; case ProtocolMessageType::EVENT: type_label = "EVENT"; break; } std::stringstream stream; WriteTimestamp(stream); stream << ": " << type_label << ": " << to_log << "\n"; const std::string& str = stream.str(); if (!base::AppendToFile(log_file, base::StringPiece(str))) { LOG(ERROR) << "Failed to write file " << log_file.value(); log_error = true; } } } // namespace class CefDevToolsFrontend::NetworkResourceLoader : public network::SimpleURLLoaderStreamConsumer { public: NetworkResourceLoader(int stream_id, CefDevToolsFrontend* bindings, std::unique_ptr<network::SimpleURLLoader> loader, network::mojom::URLLoaderFactory* url_loader_factory, int request_id) : stream_id_(stream_id), bindings_(bindings), loader_(std::move(loader)), request_id_(request_id) { loader_->SetOnResponseStartedCallback(base::BindOnce( &NetworkResourceLoader::OnResponseStarted, base::Unretained(this))); loader_->DownloadAsStream(url_loader_factory, this); } private: void OnResponseStarted(const GURL& final_url, const network::mojom::URLResponseHead& response_head) { response_headers_ = response_head.headers; } void OnDataReceived(base::StringPiece chunk, base::OnceClosure resume) override { base::Value chunkValue; bool encoded = !base::IsStringUTF8(chunk); if (encoded) { std::string encoded_string; base::Base64Encode(chunk, &encoded_string); chunkValue = base::Value(std::move(encoded_string)); } else { chunkValue = base::Value(chunk); } base::Value id(stream_id_); base::Value encodedValue(encoded); bindings_->CallClientFunction("DevToolsAPI", "streamWrite", std::move(id), std::move(chunkValue), std::move(encodedValue)); std::move(resume).Run(); } void OnComplete(bool success) override { auto response = BuildObjectForResponse(response_headers_.get(), success, loader_->NetError()); bindings_->SendMessageAck(request_id_, std::move(response)); bindings_->loaders_.erase(bindings_->loaders_.find(this)); } void OnRetry(base::OnceClosure start_retry) override { NOTREACHED(); } const int stream_id_; CefDevToolsFrontend* const bindings_; std::unique_ptr<network::SimpleURLLoader> loader_; int request_id_; scoped_refptr<net::HttpResponseHeaders> response_headers_; DISALLOW_COPY_AND_ASSIGN(NetworkResourceLoader); }; // static CefDevToolsFrontend* CefDevToolsFrontend::Show( AlloyBrowserHostImpl* inspected_browser, const CefWindowInfo& windowInfo, CefRefPtr<CefClient> client, const CefBrowserSettings& settings, const CefPoint& inspect_element_at, base::OnceClosure frontend_destroyed_callback) { CefBrowserSettings new_settings = settings; if (!windowInfo.windowless_rendering_enabled && CefColorGetA(new_settings.background_color) != SK_AlphaOPAQUE) { // Use white as the default background color for windowed DevTools instead // of the CefSettings.background_color value. new_settings.background_color = SK_ColorWHITE; } CefBrowserCreateParams create_params; if (!inspected_browser->is_views_hosted()) create_params.window_info.reset(new CefWindowInfo(windowInfo)); create_params.client = client; create_params.settings = new_settings; create_params.devtools_opener = inspected_browser; create_params.request_context = inspected_browser->GetRequestContext(); create_params.extra_info = inspected_browser->browser_info()->extra_info(); CefRefPtr<AlloyBrowserHostImpl> frontend_browser = AlloyBrowserHostImpl::Create(create_params); content::WebContents* inspected_contents = inspected_browser->web_contents(); // CefDevToolsFrontend will delete itself when the frontend WebContents is // destroyed. CefDevToolsFrontend* devtools_frontend = new CefDevToolsFrontend( static_cast<AlloyBrowserHostImpl*>(frontend_browser.get()), inspected_contents, inspect_element_at, std::move(frontend_destroyed_callback)); // Need to load the URL after creating the DevTools objects. frontend_browser->GetMainFrame()->LoadURL(GetFrontendURL()); return devtools_frontend; } void CefDevToolsFrontend::Activate() { frontend_browser_->ActivateContents(web_contents()); } void CefDevToolsFrontend::Focus() { frontend_browser_->SetFocus(true); } void CefDevToolsFrontend::InspectElementAt(int x, int y) { if (inspect_element_at_.x != x || inspect_element_at_.y != y) inspect_element_at_.Set(x, y); if (agent_host_) agent_host_->InspectElement(inspected_contents_->GetFocusedFrame(), x, y); } void CefDevToolsFrontend::Close() { base::PostTask(FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&AlloyBrowserHostImpl::CloseBrowser, frontend_browser_.get(), true)); } CefDevToolsFrontend::CefDevToolsFrontend( AlloyBrowserHostImpl* frontend_browser, content::WebContents* inspected_contents, const CefPoint& inspect_element_at, base::OnceClosure frontend_destroyed_callback) : content::WebContentsObserver(frontend_browser->web_contents()), frontend_browser_(frontend_browser), inspected_contents_(inspected_contents), inspect_element_at_(inspect_element_at), frontend_destroyed_callback_(std::move(frontend_destroyed_callback)), file_manager_(frontend_browser, GetPrefs()), protocol_log_file_( base::CommandLine::ForCurrentProcess()->GetSwitchValuePath( switches::kDevToolsProtocolLogFile)), weak_factory_(this) { DCHECK(!frontend_destroyed_callback_.is_null()); } CefDevToolsFrontend::~CefDevToolsFrontend() {} void CefDevToolsFrontend::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { content::RenderFrameHost* frame = navigation_handle->GetRenderFrameHost(); if (navigation_handle->IsInMainFrame()) { frontend_host_ = content::DevToolsFrontendHost::Create( frame, base::BindRepeating( &CefDevToolsFrontend::HandleMessageFromDevToolsFrontend, base::Unretained(this))); return; } std::string origin = navigation_handle->GetURL().GetOrigin().spec(); auto it = extensions_api_.find(origin); if (it == extensions_api_.end()) return; std::string script = base::StringPrintf("%s(\"%s\")", it->second.c_str(), base::GenerateGUID().c_str()); content::DevToolsFrontendHost::SetupExtensionsAPI(frame, script); } void CefDevToolsFrontend::DocumentAvailableInMainFrame( content::RenderFrameHost* render_frame_host) { // Don't call AttachClient multiple times for the same DevToolsAgentHost. // Otherwise it will call AgentHostClosed which closes the DevTools window. // This may happen in cases where the DevTools content fails to load. scoped_refptr<content::DevToolsAgentHost> agent_host = content::DevToolsAgentHost::GetOrCreateFor(inspected_contents_); if (agent_host != agent_host_) { if (agent_host_) agent_host_->DetachClient(this); agent_host_ = agent_host; agent_host_->AttachClient(this); if (!inspect_element_at_.IsEmpty()) { agent_host_->InspectElement(inspected_contents_->GetFocusedFrame(), inspect_element_at_.x, inspect_element_at_.y); } } } void CefDevToolsFrontend::WebContentsDestroyed() { if (agent_host_) { agent_host_->DetachClient(this); agent_host_ = nullptr; } std::move(frontend_destroyed_callback_).Run(); delete this; } void CefDevToolsFrontend::HandleMessageFromDevToolsFrontend( base::Value message) { if (!message.is_dict()) return; const std::string* method = message.FindStringKey("method"); if (!method) return; int request_id = message.FindIntKey("id").value_or(0); base::Value* params_value = message.FindListKey("params"); // Since we've received message by value, we can take the list. base::Value::ListStorage params; if (params_value) { params = std::move(*params_value).TakeList(); } if (*method == "dispatchProtocolMessage") { if (params.size() < 1) return; const std::string* protocol_message = params[0].GetIfString(); if (!agent_host_ || !protocol_message) return; if (ProtocolLoggingEnabled()) { LogProtocolMessage(ProtocolMessageType::METHOD, *protocol_message); } agent_host_->DispatchProtocolMessage( this, base::as_bytes(base::make_span(*protocol_message))); } else if (*method == "loadCompleted") { web_contents()->GetMainFrame()->ExecuteJavaScriptForTests( u"DevToolsAPI.setUseSoftMenu(true);", base::NullCallback()); } else if (*method == "loadNetworkResource") { if (params.size() < 3) return; // TODO(pfeldman): handle some of the embedder messages in content. const std::string* url = params[0].GetIfString(); const std::string* headers = params[1].GetIfString(); absl::optional<const int> stream_id = params[2].GetIfInt(); if (!url || !headers || !stream_id.has_value()) { return; } GURL gurl(*url); if (!gurl.is_valid()) { base::DictionaryValue response; response.SetInteger("statusCode", 404); response.SetBoolean("urlValid", false); SendMessageAck(request_id, std::move(response)); return; } net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation( "devtools_handle_front_end_messages", R"( semantics { sender: "Developer Tools" description: "When user opens Developer Tools, the browser may fetch " "additional resources from the network to enrich the debugging " "experience (e.g. source map resources)." trigger: "User opens Developer Tools to debug a web page." data: "Any resources requested by Developer Tools." destination: OTHER } policy { cookies_allowed: YES cookies_store: "user" setting: "It's not possible to disable this feature from settings." chrome_policy { DeveloperToolsAvailability { policy_options {mode: MANDATORY} DeveloperToolsAvailability: 2 } } })"); // Based on DevToolsUIBindings::LoadNetworkResource. auto resource_request = std::make_unique<network::ResourceRequest>(); resource_request->url = gurl; // TODO(caseq): this preserves behavior of URLFetcher-based // implementation. We really need to pass proper first party origin from // the front-end. resource_request->site_for_cookies = net::SiteForCookies::FromUrl(gurl); resource_request->headers.AddHeadersFromString(*headers); scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory; if (gurl.SchemeIsFile()) { mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote = content::CreateFileURLLoaderFactory( base::FilePath() /* profile_path */, nullptr /* shared_cors_origin_access_list */); url_loader_factory = network::SharedURLLoaderFactory::Create( std::make_unique<network::WrapperPendingSharedURLLoaderFactory>( std::move(pending_remote))); } else if (content::HasWebUIScheme(gurl)) { base::DictionaryValue response; response.SetInteger("statusCode", 403); SendMessageAck(request_id, std::move(response)); return; } else { auto* partition = web_contents()->GetBrowserContext()->GetStoragePartitionForUrl(gurl); url_loader_factory = partition->GetURLLoaderFactoryForBrowserProcess(); } auto simple_url_loader = network::SimpleURLLoader::Create( std::move(resource_request), traffic_annotation); auto resource_loader = std::make_unique<NetworkResourceLoader>( *stream_id, this, std::move(simple_url_loader), url_loader_factory.get(), request_id); loaders_.insert(std::move(resource_loader)); return; } else if (*method == "getPreferences") { SendMessageAck( request_id, GetPrefs()->GetDictionary(prefs::kDevToolsPreferences)->Clone()); return; } else if (*method == "setPreference") { if (params.size() < 2) return; const std::string* name = params[0].GetIfString(); // We're just setting params[1] as a value anyways, so just make sure it's // the type we want, but don't worry about getting it. if (!name || !params[1].is_string()) return; DictionaryPrefUpdate update(GetPrefs(), prefs::kDevToolsPreferences); update.Get()->SetKey(*name, std::move(params[1])); } else if (*method == "removePreference") { const std::string* name = params[0].GetIfString(); if (!name) return; DictionaryPrefUpdate update(GetPrefs(), prefs::kDevToolsPreferences); update.Get()->RemoveKey(*name); } else if (*method == "requestFileSystems") { web_contents()->GetMainFrame()->ExecuteJavaScriptForTests( u"DevToolsAPI.fileSystemsLoaded([]);", base::NullCallback()); } else if (*method == "reattach") { if (!agent_host_) return; agent_host_->DetachClient(this); agent_host_->AttachClient(this); } else if (*method == "registerExtensionsAPI") { if (params.size() < 2) return; const std::string* origin = params[0].GetIfString(); const std::string* script = params[1].GetIfString(); if (!origin || !script) return; extensions_api_[*origin + "/"] = *script; } else if (*method == "save") { if (params.size() < 3) return; const std::string* url = params[0].GetIfString(); const std::string* content = params[1].GetIfString(); absl::optional<bool> save_as = params[2].GetIfBool(); if (!url || !content || !save_as.has_value()) return; file_manager_.SaveToFile(*url, *content, *save_as); } else if (*method == "append") { if (params.size() < 2) return; const std::string* url = params[0].GetIfString(); const std::string* content = params[1].GetIfString(); if (!url || !content) return file_manager_.AppendToFile(*url, *content); } else { return; } if (request_id) SendMessageAck(request_id, base::Value()); } void CefDevToolsFrontend::DispatchProtocolMessage( content::DevToolsAgentHost* agent_host, base::span<const uint8_t> message) { if (!frontend_browser_->GetWebContents() || frontend_browser_->GetWebContents()->IsBeingDestroyed()) { return; } base::StringPiece str_message(reinterpret_cast<const char*>(message.data()), message.size()); if (ProtocolLoggingEnabled()) { // Quick check to avoid parsing the JSON object. Events begin with a // "method" value whereas method results begin with an "id" value. LogProtocolMessage(base::StartsWith(str_message, "{\"method\":") ? ProtocolMessageType::EVENT : ProtocolMessageType::RESULT, str_message); } if (str_message.length() < kMaxMessageChunkSize) { CallClientFunction("DevToolsAPI", "dispatchMessage", base::Value(std::string(str_message))); } else { size_t total_size = str_message.length(); for (size_t pos = 0; pos < str_message.length(); pos += kMaxMessageChunkSize) { base::StringPiece str_message_chunk = str_message.substr(pos, kMaxMessageChunkSize); CallClientFunction( "DevToolsAPI", "dispatchMessageChunk", base::Value(std::string(str_message_chunk)), base::Value(base::NumberToString(pos ? 0 : total_size))); } } } void CefDevToolsFrontend::CallClientFunction( const std::string& object_name, const std::string& method_name, base::Value arg1, base::Value arg2, base::Value arg3, base::OnceCallback<void(base::Value)> cb) { std::string javascript; web_contents()->GetMainFrame()->AllowInjectingJavaScript(); base::Value arguments(base::Value::Type::LIST); if (!arg1.is_none()) { arguments.Append(std::move(arg1)); if (!arg2.is_none()) { arguments.Append(std::move(arg2)); if (!arg3.is_none()) { arguments.Append(std::move(arg3)); } } } web_contents()->GetMainFrame()->ExecuteJavaScriptMethod( base::ASCIIToUTF16(object_name), base::ASCIIToUTF16(method_name), std::move(arguments), std::move(cb)); } void CefDevToolsFrontend::SendMessageAck(int request_id, base::Value arg) { CallClientFunction("DevToolsAPI", "embedderMessageAck", base::Value(request_id), std::move(arg)); } bool CefDevToolsFrontend::ProtocolLoggingEnabled() const { return !protocol_log_file_.empty(); } void CefDevToolsFrontend::LogProtocolMessage(ProtocolMessageType type, const base::StringPiece& message) { DCHECK(ProtocolLoggingEnabled()); std::string to_log(message.substr(0, kMaxLogLineLength)); // Execute in an ordered context that allows blocking. auto task_runner = CefTaskRunnerManager::Get()->GetBackgroundTaskRunner(); task_runner->PostTask( FROM_HERE, base::BindOnce(::LogProtocolMessage, protocol_log_file_, type, std::move(to_log))); } void CefDevToolsFrontend::AgentHostClosed( content::DevToolsAgentHost* agent_host) { DCHECK(agent_host == agent_host_.get()); agent_host_ = nullptr; Close(); } PrefService* CefDevToolsFrontend::GetPrefs() const { return CefBrowserContext::FromBrowserContext( frontend_browser_->web_contents()->GetBrowserContext()) ->AsProfile() ->GetPrefs(); }
#pragma once // Automatically generated header file #include "lwm2m/objects.h" namespace KnownObjects { namespace id3358 { // Custom, overrideable types for Opaque and String resources /* \brief Class for object 3358 - rrcTimerExpiryEvent * RRC timer expiry event information */ class instance : public Lwm2mObjectInstance { public: // 0 - 1 = t3002 = t3013 = t3024 = t3035 = t3046 = t3057 = t3118 = t3209 = t32110 = other int RrcTimerExpiryEvent; }; enum class RESID { RrcTimerExpiryEvent = 0, }; /* \brief Class for object 3358 - rrcTimerExpiryEvent * RRC timer expiry event information */ class object : public Lwm2mObject<3358, object, instance> { public: // 0 - 1 = t3002 = t3013 = t3024 = t3035 = t3046 = t3057 = t3118 = t3209 = t32110 = other Resource(0, &instance::RrcTimerExpiryEvent, O_RES_R) RrcTimerExpiryEvent; }; } // end of id namespace } // end of KnownObjects namespace inline bool operator== (KnownObjects::id3358::RESID c1, uint16_t c2) { return (uint16_t) c1 == c2; } inline bool operator== (uint16_t c2, KnownObjects::id3358::RESID c1) { return (uint16_t) c1 == c2; }
/** * @file oglplus/imports/blend_file/block_data.hpp * @brief Helper class providing access to .blend file block data * * @author Matus Chochlik * * Copyright 2010-2019 Matus Chochlik. Distributed under the Boost * Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #pragma once #ifndef OGLPLUS_IMPORTS_BLEND_FILE_BLOCK_DATA_1107121519_HPP #define OGLPLUS_IMPORTS_BLEND_FILE_BLOCK_DATA_1107121519_HPP #include <oglplus/imports/blend_file/flattened.hpp> #include <oglplus/imports/blend_file/type.hpp> #include <oglplus/imports/blend_file/visitor.hpp> namespace oglplus { namespace imports { /// Class wrapping the data of a file block class BlendFileBlockData { private: // TODO: some kind of caching in BlendFile or BlendFileBlock // and only a reference to the buffer here // to make this class more lightweight std::vector<char> _block_data; Endian _byte_order; std::size_t _ptr_size; std::size_t _struct_size; friend class BlendFile; BlendFileBlockData( std::vector<char>&& block_data, Endian byte_order, std::size_t ptr_size, std::size_t struct_size) : _block_data(block_data) , _byte_order(byte_order) , _ptr_size(ptr_size) , _struct_size(struct_size) { } template <unsigned Level> BlendFilePointerTpl<Level> _do_make_pointer( const char* pos, std::size_t type_index) const; template <unsigned Level> BlendFilePointerTpl<Level> _do_get_pointer( std::size_t type_index, std::size_t field_offset, std::size_t block_element, std::size_t field_element, std::size_t data_offset) const; template <unsigned Level> BlendFilePointerTpl<Level> _get_pointer( const BlendFileFlattenedStructField& flat_field, std::size_t block_element, std::size_t field_element, std::size_t data_offset) const; public: BlendFileBlockData(BlendFileBlockData&& tmp) : _block_data(tmp._block_data) , _byte_order(tmp._byte_order) , _ptr_size(tmp._ptr_size) , _struct_size(tmp._struct_size) { } /// Returns the raw data of the block const char* RawData() const { return _block_data.data(); } /// Returns the i-th byte in the block char RawByte(std::size_t i) const { assert(i < _block_data.size()); return _block_data[i]; } /// returns the size (in bytes) of the raw data std::size_t DataSize() const { return _block_data.size(); } /// Returns a pointer at the specified index BlendFilePointer AsPointerTo( const BlendFileType& type, std::size_t index = 0, std::size_t data_offset = 0) const; /// Returns the value of the specified field as a pointer BlendFilePointer GetPointer( const BlendFileFlattenedStructField& flat_field, std::size_t block_element = 0, std::size_t field_element = 0, std::size_t data_offset = 0) const; /// Returns the value of the specified field as a pointer to pointer BlendFilePointerToPointer GetPointerToPointer( const BlendFileFlattenedStructField& flat_field, std::size_t block_element = 0, std::size_t field_element = 0, std::size_t data_offset = 0) const; /// Returns the value at the specified offset as an integer template <typename Int> Int GetInt( std::size_t field_offset, std::size_t block_element, std::size_t field_element, std::size_t data_offset) const { const char* pos = _block_data.data() + data_offset + block_element * _struct_size + field_element * sizeof(Int) + field_offset; return aux::ReorderToNative( _byte_order, *reinterpret_cast<const Int*>(pos)); } /// Returns the value of the specified field as an integer template <typename Int> Int GetInt( const BlendFileFlattenedStructField& flat_field, std::size_t block_element = 0, std::size_t field_element = 0, std::size_t data_offset = 0) const { assert(sizeof(Int) == flat_field.Field().BaseType().Size()); return GetInt<Int>( flat_field.Offset(), block_element, field_element, data_offset); } /// Returns the value at the specified offset as a floating point value template <typename Float> Float GetFloat( std::size_t field_offset, std::size_t block_element, std::size_t field_element, std::size_t data_offset) const { const char* pos = _block_data.data() + data_offset + block_element * _struct_size + field_element * sizeof(Float) + field_offset; return *reinterpret_cast<const Float*>(pos); } /// Returns the value of the specified field as a floating point value template <typename Float> Float GetFloat( const BlendFileFlattenedStructField& flat_field, std::size_t block_element = 0, std::size_t field_element = 0, std::size_t data_offset = 0) const { assert(sizeof(Float) == flat_field.Field().BaseType().Size()); return GetFloat<Float>( flat_field.Offset(), block_element, field_element, data_offset); } /// Returns the value at the specified offset as a string std::string GetString( std::size_t field_size, std::size_t field_offset, std::size_t block_element, std::size_t field_element, std::size_t data_offset) const; /// Returns the value of the specified field as a string std::string GetString( const BlendFileFlattenedStructField& flat_field, std::size_t block_element = 0, std::size_t field_element = 0, std::size_t data_offset = 0) const { return GetString( flat_field.Size(), flat_field.Offset(), block_element, field_element, data_offset); } /// Visits the value of the specified field by a visitor void ValueVisitRef( BlendFileVisitor& visitor, const BlendFileFlattenedStructField& flat_field, std::size_t block_element = 0, std::size_t field_element = 0, std::size_t data_offset = 0) const; template <typename Visitor> void ValueVisit( Visitor visitor, const BlendFileFlattenedStructField& flat_field, std::size_t block_element = 0, std::size_t field_element = 0) const { ValueVisitRef(visitor, flat_field, block_element, field_element); } }; } // namespace imports } // namespace oglplus #if !OGLPLUS_LINK_LIBRARY || defined(OGLPLUS_IMPLEMENTING_LIBRARY) #include <oglplus/imports/blend_file/block_data.ipp> #endif // OGLPLUS_LINK_LIBRARY #endif // include guard
/** * This file is part of the LePi Project: * https://github.com/cosmac/LePi * * MIT License * * Copyright (c) 2017 Andrei Claudiu Cosma * * 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. */ // LePi #include <LeptonCommon.h> #include <LeptonUtils.h> #include <LeptonAPI.h> #include <LeptonCamera.h> // C/C++ #include <vector> #include <thread> #include <mutex> #include <iostream> LeptonCamera::LeptonCamera() : grabber_thread_(), run_thread_{false}, has_frame_{false}, lePi_(), sensor_temperature_{0.0} { // Open communication with the sensor if (!lePi_.OpenConnection()) { std::cerr << "Unable to open communication with the sensor" << std::endl; throw std::runtime_error("Connection failed."); } // Check lepton type lepton_type_ = lePi_.GetType(); if (LEPTON_UNKNOWN == lepton_type_) { throw std::runtime_error("Unknown lepton type."); } // Prepare buffers lepton_config_ = LeptonCameraConfig(lepton_type_); frame_to_read_.resize(lepton_config_.width * lepton_config_.height); frame_to_write_.resize(lepton_config_.width * lepton_config_.height); }; LeptonCamera::~LeptonCamera() { // Stop thread stop(); // Close communication with the sensor if (!lePi_.CloseConnection()) { std::cerr << "Unable to close communication with the sensor" << std::endl; } }; void LeptonCamera::start() { // Avoid starting the thread if already runs if (false == run_thread_) { run_thread_ = true; grabber_thread_ = std::thread(&LeptonCamera::run, this); } } void LeptonCamera::stop() { // Stop the thread only if there is a thread running if (true == run_thread_) { run_thread_ = false; if (grabber_thread_.joinable()) { grabber_thread_.join(); } } } void LeptonCamera::run() { while (run_thread_) { // Get new frame try { sensor_temperature_ = leptonI2C_InternalTemp(); if (!lePi_.GetFrame(frame_to_write_.data(), FRAME_U16)) { continue; } } catch (...) { lePi_.RebootSensor(); continue; } // Lock resources and swap buffers lock_.lock(); std::swap(frame_to_write_, frame_to_read_); has_frame_ = true; lock_.unlock(); } } void LeptonCamera::getFrameU8(std::vector <uint8_t> &frame) { // Resize output frame frame.resize(frame_to_read_.size()); // Lock resources lock_.lock(); // Find frame min and max uint16_t minValue = 65535; uint16_t maxValue = 0; for (size_t i = 0; i < frame_to_read_.size(); i++) { if (frame_to_read_[i] > maxValue) { maxValue = frame_to_read_[i]; } if (frame_to_read_[i] < minValue) { minValue = frame_to_read_[i]; } } // Scale frame range and copy to output float scale = 255.f / static_cast<float>(maxValue - minValue); for (size_t i = 0; i < frame_to_read_.size(); i++) { frame[i] = static_cast<uint8_t>((frame_to_read_[i] - minValue) * scale); } has_frame_ = false; // Release resources lock_.unlock(); } void LeptonCamera::getFrameU16(std::vector <uint16_t> &frame) { // Lock resources lock_.lock(); std::copy(frame_to_read_.begin(), frame_to_read_.end(), frame.begin()); has_frame_ = false; // Release resources lock_.unlock(); } bool LeptonCamera::sendCommand(LeptonI2CCmd cmd, void *buffer) { return lePi_.SendCommand(cmd, buffer); }
/** * Copyright 2020-2021 Huawei Technologies Co., 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. */ #include "minddata/dataset/engine/datasetops/filter_op.h" #include <algorithm> #include <cstring> #include <iostream> #include <memory> #include <vector> #include "minddata/dataset/core/config_manager.h" #include "minddata/dataset/core/global_context.h" #include "minddata/dataset/core/tensor.h" #include "minddata/dataset/kernels/tensor_op.h" #include "minddata/dataset/util/log_adapter.h" #include "minddata/dataset/util/task_manager.h" namespace mindspore { namespace dataset { FilterOp::FilterOp(const std::vector<std::string> &in_col_names, int32_t num_workers, int32_t op_queue_size, std::shared_ptr<TensorOp> predicate_func) : ParallelOp(num_workers, op_queue_size), predicate_func_(std::move(predicate_func)), in_columns_(in_col_names) { worker_in_queues_.Init(num_workers, op_queue_size); } Status FilterOp::operator()() { RETURN_IF_NOT_OK(RegisterAndLaunchThreads()); // Synchronize with TaskManager. TaskManager::FindMe()->Post(); child_iterator_ = std::make_unique<ChildIterator>(this, 0, 0); TensorRow new_row; RETURN_IF_NOT_OK(child_iterator_->FetchNextTensorRow(&new_row)); int64_t cnt = 0; while (child_iterator_->EofHandled() == false) { while (new_row.empty() == false) { RETURN_IF_NOT_OK(worker_in_queues_[cnt % num_workers_]->EmplaceBack(new_row)); cnt++; RETURN_IF_NOT_OK(child_iterator_->FetchNextTensorRow(&new_row)); } RETURN_IF_NOT_OK(worker_in_queues_[cnt++ % num_workers_]->EmplaceBack(std::move(TensorRow(TensorRow::kFlagEOE)))); RETURN_IF_NOT_OK(child_iterator_->FetchNextTensorRow(&new_row)); } RETURN_IF_NOT_OK(worker_in_queues_[cnt++ % num_workers_]->EmplaceBack(std::move(TensorRow(TensorRow::kFlagEOF)))); // EOF received, send quit signal to all workers for (int32_t ind = 0; ind < num_workers_; ind++) { RETURN_IF_NOT_OK(worker_in_queues_[cnt++ % num_workers_]->EmplaceBack(std::move(TensorRow(TensorRow::kFlagQuit)))); } return Status::OK(); } Status FilterOp::EofReceived(int32_t) { return Status::OK(); } Status FilterOp::EoeReceived(int32_t) { return Status::OK(); } // Validating if each of the input_columns exists in the column_name_id_map_. Status FilterOp::ValidateInColumns(const std::vector<std::string> &input_columns) { for (const auto &inCol : input_columns) { bool found = column_name_id_map_.find(inCol) != column_name_id_map_.end() ? true : false; if (!found) { std::string err_msg = "Invalid parameter, column name: " + inCol + " does not exist in the dataset columns."; RETURN_STATUS_UNEXPECTED(err_msg); } } return Status::OK(); } // A print method typically used for debugging. void FilterOp::Print(std::ostream &out, bool show_all) const { if (!show_all) { // Call the super class for displaying any common 1-liner info ParallelOp::Print(out, show_all); // Then show any custom derived-internal 1-liner info for this op out << "\n"; } else { // Call the super class for displaying any common detailed info ParallelOp::Print(out, show_all); // Then show any custom derived-internal stuff out << "\nInput column names:"; for (size_t i = 0; i < in_columns_.size(); i++) { out << " " << in_columns_[i]; } out << "\n\n"; } } Status FilterOp::WorkerEntry(int32_t worker_id) { TaskManager::FindMe()->Post(); TensorRow new_row; RETURN_IF_NOT_OK(worker_in_queues_[worker_id]->PopFront(&new_row)); while (!new_row.quit()) { // Getting a TensorRow to work on. if (new_row.eoe()) { RETURN_IF_NOT_OK(worker_out_queues_[worker_id]->EmplaceBack(new_row)); } else if (new_row.eof()) { RETURN_IF_NOT_OK(worker_out_queues_[worker_id]->EmplaceBack(new_row)); } else { RETURN_IF_NOT_OK(ValidateInColumns(in_columns_)); bool result = false; RETURN_IF_NOT_OK(WorkerCompute(new_row, &result)); if (result) { RETURN_IF_NOT_OK(worker_out_queues_[worker_id]->EmplaceBack(new_row)); } else { RETURN_IF_NOT_OK(worker_out_queues_[worker_id]->EmplaceBack(TensorRow(TensorRow::TensorRowFlags::kFlagSkip))); } } RETURN_IF_NOT_OK(worker_in_queues_[worker_id]->PopFront(&new_row)); } return Status::OK(); } Status FilterOp::WorkerCompute(const TensorRow &in_row, bool *out_predicate) { TensorRow to_process; if (in_columns_.empty() == true) { MS_LOG(INFO) << "Input columns in filter operator is empty, will apply to the all column in the current table."; to_process = in_row; } else { (void)std::transform( in_columns_.begin(), in_columns_.end(), std::back_inserter(to_process), [&in_row, this](const auto &it) -> std::shared_ptr<Tensor> { return in_row[column_name_id_map_[it]]; }); } RETURN_IF_NOT_OK(InvokePredicateFunc(to_process, out_predicate)); return Status::OK(); } Status FilterOp::CheckInput(const TensorRow &input) const { for (auto &item : input) { if (item == nullptr) { RETURN_STATUS_UNEXPECTED("Invalid data, input tensor is null."); } } return Status::OK(); } Status FilterOp::InvokePredicateFunc(const TensorRow &input, bool *out_predicate) { RETURN_IF_NOT_OK(CheckInput(input)); TensorRow output; RETURN_IF_NOT_OK(predicate_func_->Compute(input, &output)); RETURN_IF_NOT_OK(output.at(0)->GetItemAt(out_predicate, {})); return Status(StatusCode::kSuccess, "FilterOp predicate func call succeed"); } } // namespace dataset } // namespace mindspore
The bacterium Micavibrio aeruginosavorus (yellow), leeching on a Pseudomonas aeruginosa bacterium (purple). What’s the news: If bacteria had blood, the predatory microbe Micavibrio aeruginosavorus would essentially be a vampire: it subsists by hunting down other bugs, attaching to them, and sucking their life out. For the first time, researchers have sequenced the genome of this strange microorganism, which was first identified decades ago in sewage water. The sequence will help better understand the unique bacterium, which has potential to be used as a “living antibiotic” due to its ability to attack drug-resistant biofilms and its apparent fondness for dining on pathogens. Anatomy of a Vampire: - The bacterium has an interesting multi-stage life history. During its migratory phase it sprouts a single flagellum and goes hunting for prey. Once it find a delectable morsel of bacterium, it attacks and irreversibly attaches to the surface, and sucks out all of the good stuff: carbohydrates, amino acids, proteins, DNA, etc. - Sated, the cell divides in two via binary fission, and the now-depleted host is left for dead. Hungry for Pathogens: - M. aeruginosavorus cannot be grown by itself; it must be cultured along with another bacteria to feed upon. A 2006 study found that it only grew upon three bacterial species, all of which can cause pneumonia-like disease in humans. A more recent study showed that it can prey upon a wider variety of microbes, most of them potentially pathogenic, like E. coli. - These studies also found that M. aeruginosavorus has a knack for disrupting biofilms, the dense collection of bacteria that cause harmful plaques on teeth and medical implants alike, and can be up to 1,000 more resistant to antibiotics than free-swimming bugs. - The bacteria can also swim through viscous fluids like mucous and kills Pseudomonas aeruginosa, the bacterium that can colonize lungs of cystic fibrosis patients and form a glue-like film. - These qualities have caught the eye of researchers who think it could be used as a living antibiotic to treat biofilms and various types of drug-resistant bacteria, which are a growing problem in medicine. Sequencing the organism’s genome is an important step in understanding its biochemistry and how it preys on other microbes. Clues From the Vampire Code: - The new study found that each phase of life involves the use (or expression) of different sets of genes. The migratory/hunting phase involves many segments that code for flagellum formation and genes involved in quorum sensing. The attachment phase involves a wide variety of secreted chemicals and enzymes that facilitate the flow of materials from the host. - Micavibrio aeruginosavorus possesses no genes for amino acid transporters, a rather rare trait only seen in a few other bacterial species that depend heavily upon their host to help them shuttle these vital protein building-blocks. This absence helps explain the bacterium’s dependence on a narrow range of prey, from which it directly steals amino acids. Although it remains unclear exactly how the microbe attaches to and infiltrates other cells. The Future Holds: - The range of microbes upon which Micavibrio aeruginosavorus can survive is expanding; after being kept in laboratory conditions for years it has apparently evolved a more diverse diet. If this expansion continues, that could be a real problem for its use as an antibiotic; it could begin to eat beneficial gut bacteria, for example. - Researchers claim it is harmless to friendly gut microbes, but it hasn’t been tested on all the varieties of bacteria present in humans. - Several important steps must be taken before testing in people, like learning more about what traits makes another bacteria tasty to Micavibrio aeruginosavorus. Researchers speculate the bacterium may need to be genetically altered in order to go after specific pathogens, or to reduce the risk of it causing unforeseen complications. Reference: Zhang Wang, Daniel E Kadouri, Martin Wu. Genomic insights into an obligate epibiotic bacterial predator: Micavibrio aeruginosavorus ARL-13. BMC Genomics, 2011; 12 (1): 453 DOI: 10.1186/1471-2164-12-453 Image credit: University of Virginia
#include "popr_types.hpp" #include <stdexcept> /* ========================================== Individual ========================================== */ Individual::Individual(int pid, bool is_male) { m_pid = pid; m_is_male = is_male; m_children = new std::vector<Individual*>(); } Individual::~Individual() { delete m_children; } int Individual::get_pid() const { return m_pid; } /* int Individual::get_pid_m() const { return m_pid_m; } int Individual::get_pid_f() const { return m_pid_f; } */ bool Individual::get_is_male() const { return m_is_male; } void Individual::add_child(Individual* child) { m_children->push_back(child); } void Individual::set_mother(Individual* i) { // FIXME: Check sex of i? m_mother = i; } void Individual::set_father(Individual* i) { // FIXME: Check sex of i? m_father = i; } Individual* Individual::get_mother() const { return m_mother; } Individual* Individual::get_father() const { return m_father; } std::vector<Individual*>* Individual::get_children() const { return m_children; } bool Individual::pedigree_is_set() const { return (m_pedigree_id != 0); } int Individual::get_pedigree_id() const { return m_pedigree_id; } Pedigree* Individual::get_pedigree() const { return m_pedigree; } void Individual::set_pedigree_id(int id, Pedigree* ped, int* pedigree_size) { if (this->pedigree_is_set()) { return; } m_pedigree = ped; m_pedigree_id = id; *pedigree_size += 1; ped->add_member(this); if (m_mother != NULL) { m_mother->set_pedigree_id(id, ped, pedigree_size); } if (m_father != NULL) { m_father->set_pedigree_id(id, ped, pedigree_size); } for (auto &child : (*m_children)) { ped->add_relation(this, child); child->set_pedigree_id(id, ped, pedigree_size); } } void Individual::set_alive_status(bool is_alive) { m_is_alive = is_alive; } bool Individual::get_alive_status() const { return m_is_alive; } void Individual::set_birth_year(int birth_year) { m_birth_year = birth_year; } int Individual::get_birth_year() const { return m_birth_year; } void Individual::set_location(double etrs89e, double etrs89n) { m_etrs89e = etrs89e; m_etrs89n = etrs89n; m_etrs89set = true; } double Individual::get_etrs89e() const { return m_etrs89e; } double Individual::get_etrs89n() const { return m_etrs89n; } bool Individual::location_is_set() const { return m_etrs89set; } void Individual::dijkstra_reset() { m_dijkstra_visited = false; m_dijkstra_distance = 0; } void Individual::dijkstra_tick_distance(int step) { m_dijkstra_distance += step; } void Individual::dijkstra_set_distance_if_less(int dist) { if (m_dijkstra_distance < dist) { m_dijkstra_distance = dist; } } void Individual::dijkstra_mark_visited() { m_dijkstra_visited = true; } int Individual::dijkstra_get_distance() const { return m_dijkstra_distance; } bool Individual::dijkstra_was_visited() const { return m_dijkstra_visited; } /* void Individual::set_pedigree_id_f(int id, Pedigree* ped, int* pedigree_size) { if (!(this->get_is_male())) { return; } if (m_pedigree_id_f != 0) { return; } m_pedigree_id_f = id; *pedigree_size += 1; ped->add_member(this); if (m_father != NULL) { m_father->set_pedigree_id_f(id, ped, pedigree_size); } for (auto &child : (*m_children)) { ped->add_relation(this, child); child->set_pedigree_id_f(id, ped, pedigree_size); } } */ // ASSUMES TREE! //FIXME: Heavily relies on it being a tree, hence there is only one path connecting every pair of nodes void Individual::meiosis_dist_tree_internal(Individual* dest, int* dist) const { if (this->get_pid() == dest->get_pid()) { //FIXME: Heavily relies on it being a tree, hence there is only one path connecting every pair of nodes *dist = dest->dijkstra_get_distance(); return; } if (dest->get_mother() != NULL) { throw std::invalid_argument("meiosis_dist_tree_internal assumes tree (e.g. Ychr)!"); } if (dest->dijkstra_was_visited()) { return; } dest->dijkstra_mark_visited(); dest->dijkstra_tick_distance(1); int m = dest->dijkstra_get_distance(); // FIXME: If not tree, then distance must be somehow checked if shorter and then adjusted Individual* father = dest->get_father(); if (father != NULL) { //tree: ok father->dijkstra_tick_distance(m); // general? FIXME Correct? //father->dijkstra_set_distance_if_less(m); this->meiosis_dist_tree_internal(father, dist); } std::vector<Individual*>* children = dest->get_children(); for (auto child : *children) { //tree: ok child->dijkstra_tick_distance(m); // general? FIXME Correct? //child->dijkstra_set_distance_if_less(m); this->meiosis_dist_tree_internal(child, dist); } } // ASSUMES TREE! int Individual::meiosis_dist_tree(Individual* dest) const { if (!(this->pedigree_is_set())) { throw std::invalid_argument("!(this->pedigree_is_set())"); } if (dest == NULL) { throw std::invalid_argument("dest is NULL"); } if (!(dest->pedigree_is_set())) { throw std::invalid_argument("!(dest->pedigree_is_set())"); } if (this->get_pedigree_id() != dest->get_pedigree_id()) { return -1; } std::vector<Individual*>* inds = this->get_pedigree()->get_all_individuals(); for (auto child : *inds) { child->dijkstra_reset(); } // At this point, the individuals this and dest belong to same pedigree int dist = 0; this->meiosis_dist_tree_internal(dest, &dist); return dist; } /* Father haplotype FIXME mutation_model? */ void Individual::father_haplotype_mutate(double mutation_rate) { if (!m_father_haplotype_set) { Rcpp::stop("Father haplotype not set yet, so cannot mutate"); } if (m_father_haplotype_mutated) { Rcpp::stop("Father haplotype already set and mutated"); } for (int loc = 0; loc < m_father_haplotype.size(); ++loc) { if (R::runif(0.0, 1.0) < mutation_rate) { if (R::runif(0.0, 1.0) < 0.5) { m_father_haplotype[loc] = m_father_haplotype[loc] - 1; } else { m_father_haplotype[loc] = m_father_haplotype[loc] + 1; } } } } bool Individual::is_father_haplotype_set() const { return m_father_haplotype_set; } void Individual::set_father_haplotype(std::vector<int> h) { m_father_haplotype = h; m_father_haplotype_set = true; } std::vector<int> Individual::get_father_haplotype() const { return m_father_haplotype; } void Individual::pass_haplotype_to_children(bool recursive, double mutation_rate) { for (auto &child : (*m_children)) { child->set_father_haplotype(m_father_haplotype); child->father_haplotype_mutate(mutation_rate); if (recursive) { child->pass_haplotype_to_children(recursive, mutation_rate); } } } void Individual::set_include_meioses_dist(bool status) { m_include_meioses_dist = status; } bool Individual::get_include_meioses_dist() const { return m_include_meioses_dist; }
/* * json_JsonUtilities.h */ #ifndef MUTGOS_JSON_JSONUTILITIES_H #define MUTGOS_JSON_JSONUTILITIES_H #include <unistd.h> #include <string> #include <string.h> #include <rapidjson/document.h> #include "osinterface/osinterface_OsTypes.h" /** * Creates a JSON array root node, named varname. * Example: JSON_MAKE_ARRAY_ROOT(my_array); */ #ifndef JSON_MAKE_ARRAY_ROOT #define JSON_MAKE_ARRAY_ROOT(varname) \ mutgos::json::JSONRoot varname(rapidjson::kArrayType) #endif /** * Creates a JSON array root node pointer. * Example: JSON_MAKE_ARRAY_ROOT_PTR(); */ #ifndef JSON_MAKE_ARRAY_ROOT_PTR #define JSON_MAKE_ARRAY_ROOT_PTR() \ new mutgos::json::JSONRoot(rapidjson::kArrayType) #endif /** * Creates a JSON array node, named varname. * Example: JSON_MAKE_ARRAY_NODE(my_array); */ #ifndef JSON_MAKE_ARRAY_NODE #define JSON_MAKE_ARRAY_NODE(varname) \ mutgos::json::JSONNode varname(rapidjson::kArrayType) #endif /** * Creates a JSON array node pointer. * Example: JSON_MAKE_ARRAY_NODE(); */ #ifndef JSON_MAKE_ARRAY_NODE_PTR #define JSON_MAKE_ARRAY_NODE_PTR() \ new mutgos::json::JSONNode(rapidjson::kArrayType) #endif /** * Creates a JSON map (object) node, named varname. * Example: JSON_MAKE_MAP_NODE(my_object); */ #ifndef JSON_MAKE_MAP_NODE #define JSON_MAKE_MAP_NODE(varname) \ mutgos::json::JSONNode varname(rapidjson::kObjectType) #endif /** * Creates a JSON map (object) node pointer. * Example: JSON_MAKE_MAP_NODE(); */ #ifndef JSON_MAKE_MAP_NODE_PTR #define JSON_MAKE_MAP_NODE_PTR() \ new mutgos::json::JSONNode(rapidjson::kObjectType) #endif /** * Creates a JSON map (object) root node, named varname. * Example: JSON_MAKE_MAP_ROOT(my_object); */ #ifndef JSON_MAKE_MAP_ROOT #define JSON_MAKE_MAP_ROOT(varname) \ mutgos::json::JSONRoot varname(rapidjson::kObjectType) #endif /** * Creates a JSON map (object) root node pointer. * Example: JSON_MAKE_MAP_NODE(); */ #ifndef JSON_MAKE_MAP_ROOT_PTR #define JSON_MAKE_MAP_ROOT_PTR() \ new mutgos::json::JSONRoot(rapidjson::kObjectType) #endif /** * Creates a standard JSON node (non-array, non-map), named varname. * This is not normally needed, since the add_* methods auto-create these. * Example: JSON_MAKE_NODE(my_node); */ #ifndef JSON_MAKE_NODE #define JSON_MAKE_NODE(varname) \ mutgos::json::JSONNode varname #endif // TODO Nulls in strings are not well supported when parsing. Will need to add new methods here, and modify any callers of existing, affected methods. namespace mutgos { namespace json { // Forward declarations // class JsonParsedObject; // // Use these typedefs when referring to any JSON object; never refer to // the underlying JSON parser library directly to maintain portability. // /** A JSON Node, which could be any type */ typedef rapidjson::Value JSONNode; /** The root of the JSON document tree */ typedef rapidjson::Document JSONRoot; // // Static methods to make working with the JSON library easier and portable. // /** * Parses the provided string as JSON. * @param data_ptr[in] Pointer to the JSON data as a string. Ownership * of the pointer will pass to this method. The data will be modified. * @return A pointer to the parsed JSON, or null if error or invalid JSON * string. Caller must manage the pointer. */ JsonParsedObject *parse_json(char * const data_ptr); /** * Converts the document into a JSON string. * @param root[in] The document root to convert to a JSON string. * @return The document as a JSON string. */ std::string write_json(JSONRoot &root); /** * Clears an array or map of all contents. * @param array[out] The array or map to clear. */ static void json_clear(JSONNode &json) { if (json.IsObject()) { json.RemoveAllMembers(); } else if (json.IsArray()) { json.Clear(); } } /** * Adds key value pair to json. The value must be static and never * modified (in other words, a program constant). * @param key[in] The key. Must be const static. * @param value[in] The const static value. * @param json[out] The section of JSON being added to. * @param root[in] The document root. * @return True if success, false if json isn't a map/object type * or key is empty. */ static bool add_static_key_static_value( const std::string &key, const std::string &value, JSONNode &json, JSONRoot &root) { const bool success = json.IsObject() and (not key.empty()); if (success) { json.AddMember( rapidjson::StringRef(key.c_str(), key.size()), rapidjson::StringRef(value.c_str(), value.size()), root.GetAllocator()); } return success; } /** * Adds key value pair to json. * @param key[in] The key. Must be const static. * @param value[in] The value (will be copied). * @param json[out] The section of JSON being added to. * @param root[in] The document root. * @return True if success, false if json isn't a map/object type * or key is empty. */ static bool add_static_key_value( const std::string &key, const std::string &value, JSONNode &json, JSONRoot &root) { const bool success = json.IsObject() and (not key.empty()); if (success) { rapidjson::Value val; val.SetString(value.c_str(), value.size(), root.GetAllocator()); json.AddMember( rapidjson::StringRef(key.c_str(), key.size()), val, root.GetAllocator()); } return success; } /** * Adds key value pair to json. * @param key[in] The key (will be copied). * @param value[in] The value (will be copied). * @param json[out] The section of JSON being added to. * @param root[in] The document root. * @return True if success, false if json isn't a map/object type * or key is empty. */ static bool add_key_value( const std::string &key, const std::string &value, JSONNode &json, JSONRoot &root) { const bool success = json.IsObject() and (not key.empty()); if (success) { rapidjson::Value keyVal; rapidjson::Value val; keyVal.SetString(key.c_str(), key.size()); val.SetString(value.c_str(), value.size()); json.AddMember(keyVal, val, root.GetAllocator()); } return success; } /** * Adds key value pair to json. * @param key[in] The key (will be copied). * @param value[in,out] The value (will be moved into json). When done, * this will be empty/unset. * @param json[out] The section of JSON being added to. * @param root[in] The document root. * @return True if success, false if json isn't a map/object type or value * is unset, or key is empty. */ static bool add_key_value( const std::string &key, JSONNode &value, JSONNode &json, JSONRoot &root) { const bool success = json.IsObject() and (not key.empty()) and (not value.IsNull()); if (success) { rapidjson::Value keyVal; keyVal.SetString(key.c_str(), key.size()); json.AddMember(keyVal, value, root.GetAllocator()); } return success; } /** * Adds key value pair to json. * @param key[in] The key (will be copied). * @param value[in,out] The value (will be moved into json). When done, * this will be empty/unset. * @param json[out] The section of JSON being added to. * @param root[in] The document root. * @return True if success, false if json isn't a map/object type or value * is unset, or key is empty. */ static bool add_static_key_value( const std::string &key, JSONNode &value, JSONNode &json, JSONRoot &root) { const bool success = json.IsObject() and (not key.empty()) and (not value.IsNull()); if (success) { json.AddMember( rapidjson::StringRef(key.c_str(), key.size()), value, root.GetAllocator()); } return success; } /** * Adds key value pair to json. * @param key[in] The key. Must be const static. * @param value[in] The value (will be copied). * @param json[out] The section of JSON being added to. * @param root[in] The document root. * @return True if success, false if json isn't a map/object type * or key is empty. */ static bool add_static_key_value( const std::string &key, const bool value, JSONNode &json, JSONRoot &root) { const bool success = json.IsObject() and (not key.empty()); if (success) { rapidjson::Value val; val.SetBool(value); json.AddMember( rapidjson::StringRef(key.c_str(), key.size()), val, root.GetAllocator()); } return success; } /** * Adds key value pair to json. * @param key[in] The key. Must be const static. * @param value[in] The value (will be copied). * @param json[out] The section of JSON being added to. * @param root[in] The document root. * @return True if success, false if json isn't a map/object type * or key is empty. */ static bool add_static_key_value( const std::string &key, const MG_UnsignedInt value, JSONNode &json, JSONRoot &root) { const bool success = json.IsObject() and (not key.empty()); if (success) { rapidjson::Value val; val.SetUint(value); json.AddMember( rapidjson::StringRef(key.c_str(), key.size()), val, root.GetAllocator()); } return success; } /** * Adds key value pair to json. * @param key[in] The key. Must be const static. * @param value[in] The value (will be copied). * @param json[out] The section of JSON being added to. * @param root[in] The document root. * @return True if success, false if json isn't a map/object type * or key is empty. */ static bool add_static_key_value( const std::string &key, const MG_VeryLongUnsignedInt value, JSONNode &json, JSONRoot &root) { const bool success = json.IsObject() and (not key.empty()); if (success) { rapidjson::Value val; val.SetInt64(value); json.AddMember( rapidjson::StringRef(key.c_str(), key.size()), val, root.GetAllocator()); } return success; } /** * Adds key value pair to json. * @param key[in] The key. Must be const static. * @param value[in] The value (will be copied). * @param json[out] The section of JSON being added to. * @param root[in] The document root. * @return True if success, false if json isn't a map/object type * or key is empty. */ static bool add_static_key_value( const std::string &key, const MG_SignedInt value, JSONNode &json, JSONRoot &root) { const bool success = json.IsObject() and (not key.empty()); if (success) { rapidjson::Value val; val.SetInt(value); json.AddMember( rapidjson::StringRef(key.c_str(), key.size()), val, root.GetAllocator()); } return success; } /** * Gets a string from json. * @param key[in] The key to retrieve. * @param json[in] The JSON the key is retrieved from. * @param value[out] The value associated with the key. It will * be empty if the return value is false. * @return True if found and able to retrieve the value, false if * not found or of the wrong type. */ static bool get_key_value( const std::string &key, const JSONNode &json, std::string &value) { bool success = false; value.clear(); if (json.IsObject()) { rapidjson::Value::ConstMemberIterator iter = json.FindMember(key.c_str()); if ((iter != json.MemberEnd()) and iter->value.IsString()) { value.assign( iter->value.GetString(), iter->value.GetStringLength()); success = true; } } return success; } /** * Gets an unsigned int from json. * @param key[in] The key to retrieve. * @param json[in] The JSON the key is retrieved from. * @param value[out] The value associated with the key. It will * be 0 if the return value is false. * @return True if found and able to retrieve the value, false if * not found or of the wrong type. */ static bool get_key_value( const std::string &key, const JSONNode &json, MG_UnsignedInt &value) { bool success = false; value = 0; if (json.IsObject()) { rapidjson::Value::ConstMemberIterator iter = json.FindMember(key.c_str()); if ((iter != json.MemberEnd()) and iter->value.IsUint()) { value = iter->value.GetUint(); success = true; } } return success; } /** * Gets a very long unsigned int from json. * @param key[in] The key to retrieve. * @param json[in] The JSON the key is retrieved from. * @param value[out] The value associated with the key. It will * be 0 if the return value is false. * @return True if found and able to retrieve the value, false if * not found or of the wrong type. */ static bool get_key_value( const std::string &key, const JSONNode &json, MG_VeryLongUnsignedInt &value) { bool success = false; value = 0; if (json.IsObject()) { rapidjson::Value::ConstMemberIterator iter = json.FindMember(key.c_str()); if ((iter != json.MemberEnd()) and iter->value.IsUint64()) { value = iter->value.GetUint64(); success = true; } } return success; } /** * Gets an int from a json. * @param key[in] The key to retrieve. * @param json[in] The JSON the key is retrieved from. * @param value[out] The value associated with the key. It will * be 0 if the return value is false. * @return True if found and able to retrieve the value, false if * not found or of the wrong type. */ static bool get_key_value( const std::string &key, const JSONNode &json, MG_SignedInt &value) { bool success = false; value = 0; if (json.IsObject()) { rapidjson::Value::ConstMemberIterator iter = json.FindMember(key.c_str()); if ((iter != json.MemberEnd()) and iter->value.IsInt()) { value = iter->value.GetInt(); success = true; } } return success; } /** * Gets a bool from json. * @param key[in] The key to retrieve. * @param json[in] The JSON the key is retrieved from. * @param value[out] The value associated with the key. It will * be false if the return value is false. * @return True if found and able to retrieve the value, false if * not found or of the wrong type. */ static bool get_key_value( const std::string &key, const JSONNode &json, bool &value) { bool success = false; value = false; if (json.IsObject()) { rapidjson::Value::ConstMemberIterator iter = json.FindMember(key.c_str()); if ((iter != json.MemberEnd()) and iter->value.IsBool()) { value = iter->value.GetBool(); success = true; } } return success; } /** * Gets a node from json. This is generally used to retrieve arrays * or objects/maps. * @param key[in] The key to retrieve. * @param json[in] The JSON the key is retrieved from. * @param value[out] The pointer to the node. Ownership of the pointer * does NOT transfer to the caller (do not delete it). It will be set * to null if this method returns null. * @return True if found and able to retrieve the value, false if * not found or of the wrong type. */ static bool get_key_value( const std::string &key, const JSONNode &json, const JSONNode *&value) { bool success = false; value = 0; if (json.IsObject()) { rapidjson::Value::ConstMemberIterator iter = json.FindMember(key.c_str()); if (iter != json.MemberEnd()) { value = &(iter->value); success = true; } } return success; } /** * @param json[in] The JSON node to check. * @return True if node is a map. */ static bool is_map(const JSONNode &json) { return json.IsObject(); } /** * @param json[in] The JSON node to check. * @return True if node is an array. */ static bool is_array(const JSONNode &json) { return json.IsArray(); } /** * @param array[in] The array to check. * @return True if JSON array is empty. */ static bool array_empty(const JSONNode &array) { bool empty = true; if (is_array(array)) { empty = array.Empty(); } return empty; } /** * @param array[in] The array to check. * @return The size of the JSON array. */ static MG_UnsignedInt array_size(const JSONNode &array) { MG_UnsignedInt size = 0; if (is_array(array)) { size = array.Size(); } return size; } /** * Adds non-static string value to an array. * @param value[in] The value to add. * @param array[out] The JSON Array to add the value to. * @param root[in] The document root. * @return True if success, or false if not an array. */ static bool array_add_value( const std::string &value, JSONNode &array, JSONRoot &root) { const bool success = array.IsArray(); if (success) { rapidjson::Value val; val.SetString(value.c_str(), value.size()); array.PushBack(val, root.GetAllocator()); } return success; } /** * Adds non-static string values to an array. * @tparam Container std::list of std::string, std::set, and the like. * @param values[in] The string values to add. * @param array[out] The JSON Array to add the values to. * @param root[in] The document root. * @return True if success, or false if not an array. */ template <typename Container> static bool array_add_value( const Container &values, JSONNode &array, JSONRoot &root) { const bool success = array.IsArray(); if (success) { rapidjson::Value val; for (typename Container::const_iterator iter = values.begin(); iter != values.end(); ++iter) { val.SetString(iter->c_str(), iter->size()); array.PushBack(val, root.GetAllocator()); } } return success; } /** * Adds a non-static JSON node to the array. * @param value[in,out] The value to add. The value itself will be cleared. * @param array[out] The array to add the value to. * @param root[in] The document root. * @return True if success, or false if not an array or unable to add value. */ static bool array_add_node( JSONNode &value, JSONNode &array, JSONRoot &root) { const bool success = array.IsArray() and not value.IsNull(); if (success) { array.PushBack(value, root.GetAllocator()); } return success; } /** * Adds static (never changes, program constant) string value to an array. * @param value[in] The value to add. * @param array[out] The JSON Array to add the value to. * @param root[in] The document root. * @return True if success, or false if not an array. */ static bool array_add_static_value( const std::string &value, JSONNode &array, JSONRoot &root) { const bool success = array.IsArray(); if (success) { array.PushBack( rapidjson::StringRef(value.c_str(), value.size()), root.GetAllocator()); } return success; } /** * Adds const static string values to an array. * @tparam Container std::list of std::string *, std::set, and the like. * @param values[in] The pointers to const static string values to add. * Pointer ownership does NOT transfer to this method. * @param array[out] The JSON Array to add the values to. * @param root[in] The document root. * @return True if success, or false if not an array. */ template <typename Container> static bool array_add_static_value( const Container &values, JSONNode &array, JSONRoot &root) { const bool success = array.IsArray(); if (success) { for (typename Container::const_iterator iter = values.begin(); iter != values.end(); ++iter) { array.PushBack( rapidjson::StringRef((*iter)->c_str(), (*iter)->size()), root.GetAllocator()); } } return success; } /** * Gets an array of strings from a JSON array. The strings will be copied. * Non-string elements will be filtered out. * @tparam Container std::list of std::string, std::set, and the like. * @param array[in] The array to retrieve the strings from. * @param value[out] Where to place the strings retrieved from array. * The contents will NOT be cleared success or fail. * @return True if an array and able to retrieve values. Note this will * return true even if the array is empty. */ template <typename Container> static bool array_get_value( const JSONNode &array, Container &value) { const bool success = array.IsArray(); if (success) { for (JSONNode::ConstValueIterator iter = array.Begin(); iter != array.End(); ++iter) { if (iter->IsString()) { value.push_back(std::string( iter->GetString(), iter->GetStringLength())); } } } return success; } /** * Gets a string from a specific location in an array. The string will * be copied. * @param array[in] The array to retrieve the string from. * @param index[in] The index of the string in the array to retrieve. * @param value[out] The value of the array element. The value will be * cleared before populating, success or fail. * @return True if an array, the index is within range, the value is * of type string, and able to retrieve the value. False otherwise. */ static bool array_get_value( const JSONNode &array, const ssize_t index, std::string &value) { bool success = array.IsArray() and (array.Size() > index); value.clear(); if (success) { const JSONNode &element = array[index]; if (element.IsString()) { value.assign(element.GetString(), element.GetStringLength()); } else { success = false; } } return success; } /** * Gets a string from a specific location in an array. The string will * be copied. * Note this method is generally used for specific performance reasons; * the standard std::string variant is preferred for most use cases. * @param array[in] The array to retrieve the string from. * @param index[in] The index of the string in the array to retrieve. * @param value_ptr[out] If returning true, this will contain a pointer * to the string data. Caller must manage the pointer! If false is * returned, this will be null. * @param value_size[out] The length of value, excluding the final null. * As strings are permitted to contain nulls, this is the most accurate * size of the string. * @return True if an array, the index is within range, the value is * of type string, and able to retrieve the value. False otherwise. */ static bool array_get_value( const JSONNode &array, const ssize_t index, char *&value_ptr, size_t &value_size) { bool success = array.IsArray() and (array.Size() > index); value_ptr = 0; if (success) { const JSONNode &element = array[index]; if (element.IsString()) { value_size = element.GetStringLength(); value_ptr = new char[value_size + 1]; memcpy(value_ptr, element.GetString(), value_size); value_ptr[value_size] = 0; } else { success = false; } } return success; } /** * Gets a JSON node from a specific location in an array. * @param array[in] The array to retrieve the node from. * @param index[in] The index of the node in the array to retrieve. * @param value[out] The pointer to the node. Ownership of the pointer * does NOT transfer to the caller (do not delete it). It will be set * to null if this method returns null. * @return True if an array and the index is within range, and able to * retrieve the value. False otherwise. */ static bool array_get_node( const JSONNode &array, const ssize_t index, const JSONNode *&value) { const bool success = array.IsArray() and (array.Size() > index); value = 0; if (success) { value = &array[index]; } return success; } // TODO array get/add bool, uint, int, ID // TODO array helpers for list/set of IDs } } #endif //MUTGOS_JSON_JSONUTILITIES_H
/* -*-C++-*- */ /* (c) Copyright 2008-2012, Hewlett-Packard Development Company, LP See the file named COPYING for license details */ /** @file \brief Some help with testing things that throw invariants */ #ifndef LINTEL_TESTUTIL_HPP #define LINTEL_TESTUTIL_HPP #include <vector> #include <string> #include <Lintel/AssertBoost.hpp> #include <Lintel/StringUtil.hpp> /// Macro to test whether a particular chunk of code has an invariant /// with any of a vector of messages; Assumes that you have not set up any /// AssertBoost functions #define TEST_INVARIANT_MSGVEC(code, messages) \ AssertBoostFnBefore(AssertBoostThrowExceptionFn); \ try { \ code; \ FATAL_ERROR("no invariant happened"); \ } catch (AssertBoostException &e) { \ AssertBoostClearFns(); \ bool found = false; \ for (std::vector<std::string>::iterator i = messages.begin(); \ i != messages.end(); ++i) { \ if (e.msg == *i) { found = true; break; } \ } \ INVARIANT(found, boost::format("unexpected error message '%s'") % e.msg); \ } /// One possibility variant of TEST_INVARIANT_MSGVEC #define TEST_INVARIANT_MSG1(code, message) { \ std::vector<std::string> msgs; msgs.push_back(message); \ TEST_INVARIANT_MSGVEC(code, msgs); \ } // TODO: remove uses and purge /// Deprecated, old version of MSG1 #define TEST_INVARIANTMSG(code, message) TEST_INVARIANT_MSG1(code, message) /// Two possibility variant of TEST_INVARIANT_MSGVEC #define TEST_INVARIANT_MSG2(code, msg1, msg2) { \ std::vector<std::string> msgs; msgs.push_back(msg1); msgs.push_back(msg2); \ TEST_INVARIANT_MSGVEC(code, msgs); \ } /// Three possibility variant of TEST_INVARIANT_MSGVEC #define TEST_INVARIANT_MSG3(code, msg1, msg2, msg3) { \ std::vector<std::string> msgs; msgs.push_back(msg1); msgs.push_back(msg2); msgs.push_back(msg3); \ TEST_INVARIANT_MSGVEC(code, msgs); \ } namespace lintel { struct DeptoolInfo { std::string os; // e.g. debian, ubuntu, centos, fedora, opensuse, scilinux std::string version; // e.g. 7.0, 11.10, 5.3, 16, 12.1, 6.2 std::string arch; // e.g. i386, x86_64 std::string osVersion() { return os + "-" + version; } std::string osVersionArch() { return os + "-" + version + "-" + arch; } bool haveAllInfo() { return !(os.empty() || version.empty() || arch.empty()); } }; // If $BUILD_OS/$UNAME_M are present in the environment, use those values and convert them // into os/version/arch. Otherwise, run deptool to get those values and return them in the // structure. If deptool is not present, a structure of all empty strings will be returned. // This function is useful for whitelisting tests that fail on particular combinations of // os/version/arch DeptoolInfo getDeptoolInfo(); } #endif
#include <iostream> #include <string> #include <iomanip> #include <vector> #include <tuple> #include <algorithm> using namespace std; // need to use operating system calls to access file information #include <windows.h> // this contains the size of a file, we could simply convert the // file size to a unsigned long long, but using this structure // means that we have to write operators for it struct file_size { unsigned int high; unsigned int low; }; using file_info = tuple<string, file_size>; // print a file_size object on the console ostream& operator<<(ostream& os, const file_size fs) { int flags = os.flags(); unsigned long long ll = fs.low + ((unsigned long long)fs.high << 32); os << hex << ll; os.setf(flags); return os; } // compare two file_size objects bool operator>(const file_size& lhs, const file_size& rhs) { if (lhs.high > rhs.high) return true; if (lhs.high == rhs.high) { if (lhs.low > rhs.low) return true; } return false; } // for the folder folderPath put each file in files and // recurse for each subfolder void files_in_folder( const char *folderPath, vector<file_info>& files) { // find all items in the folder string folder(folderPath); folder += "\\*"; WIN32_FIND_DATAA findfiledata {}; void* hFind = FindFirstFileA(folder.c_str(), &findfiledata); if (hFind != INVALID_HANDLE_VALUE) { do { // get the full name string findItem(folderPath); findItem += "\\"; findItem += findfiledata.cFileName; if ((findfiledata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) { // this is a folder so recurse string folder(findfiledata.cFileName); // ignore . and .. directories if (folder != "." && folder != "..") { // get the files the subfolder contains files_in_folder(findItem.c_str(), files); } } else { // this is a file so store information file_size fs{}; fs.high = findfiledata.nFileSizeHigh; fs.low = findfiledata.nFileSizeLow; files.push_back(make_tuple(findItem, fs)); } } while (FindNextFileA(hFind, &findfiledata)); FindClose(hFind); } } int main(int argc, char* argv[]) { if (argc < 2) return 1; // get the files in the specified folder and subfolders vector<file_info> files; files_in_folder(argv[1], files); // sort by file size, smallest first sort(files.begin(), files.end(), [](const file_info& lhs, const file_info& rhs) { return get<1>(rhs) > get<1>(lhs); } ); for (auto file : files) { cout << setw(16) << get<1>(file) << " " << get<0>(file) << endl; } return 0; }
Open Access • Rajkumar Tulsawani1, • Lorena S Kelly2, • Nigar Fatma1, • Bhavanaben Chhunchha1, • Eri Kubo3, • Anil Kumar4 and • Dhirendra P Singh1Email author BMC Neuroscience201011:125 Received: 10 April 2010 Accepted: 5 October 2010 Published: 5 October 2010 The ability to respond to changes in the extra-intracellular environment is prerequisite for cell survival. Cellular responses to the environment include elevating defense systems, such as the antioxidant defense system. Hypoxia-evoked reactive oxygen species (ROS)-driven oxidative stress is an underlying mechanism of retinal ganglion cell (RGC) death that leads to blinding disorders. The protein peroxiredoxin 6 (PRDX6) plays a pleiotropic role in negatively regulating death signaling in response to stressors, and thereby stabilizes cellular homeostasis. We have shown that RGCs exposed to hypoxia (1%) or hypoxia mimetic cobalt chloride display reduced expression of PRDX6 with higher ROS expression and activation of NF-κB. These cells undergo apoptosis, while cells with over-expression of PRDX6 demonstrate resistance against hypoxia-driven RGC death. The RGCs exposed to hypoxia either with 1% oxygen or cobalt chloride (0-400 μM), revealed ~30%-70% apoptotic cell death after 48 and 72 h of exposure. Western analysis and real-time PCR showed elevated expression of PRDX6 during hypoxia at 24 h, while PRDX6 protein and mRNA expression declined from 48 h onwards following hypoxia exposure. Concomitant with this, RGCs showed increased ROS expression and activation of NF-κB with IkB phosphorylation/degradation, as examined with H2DCF-DA and transactivation assays. These hypoxia-induced adverse reactions could be reversed by over-expression of PRDX6. Because an abundance of PRDX6 in cells was able to attenuate hypoxia-induced RGC death, the protein could possibly be developed as a novel therapeutic agent acting to postpone RGC injury and delay the progression of glaucoma and other disorders caused by the increased-ROS-generated death signaling related to hypoxia. Uncontrolled rises in intracellular reactive oxygen species (ROS) are triggered by downregulation of expression and activity of protective molecules in response to changes in the extracellular environment. Such changes often include hypoxia, the scarcity of oxygen can lead to cell injury and death by apoptosis. Recent evidence has shown an increase of intracellular ROS expression in cells during hypoxia, with the source of the increase being the mitochondria [1, 2]. Mammalian cells respond to fluctuations in their micro environmental oxygen by regulating defense genes such as stress response genes, heat shock factor, NF-κB, and HIFα-1. These factors play a decisive role in the fate of cells by activating protective molecules such as PRDX6. However, a scarcity of oxygen to cells also results in functional or adaptive responses [36]. Conversely, prolonged hypoxia can induce genes involved in cell death [7, 8]. The increased levels of ROS during hypoxia and ROS-driven-oxidative stress induce deleterious effects by activating/deactivating genes and deregulating normal survival signaling [9, 10]. This process results in pathophysiology of cells and tissues, such as stroke, cardiovascular disease, tumorigenesis, and development of various blinding eye conditions [11, 12]. The death of retinal ganglion cells (RGCs) is a major blinding event, and RGC death has been reported to occur during retinal hypoxia/ischemia [13, 14]. Retinal cells that are highly active require a regular supply of oxygen [11, 15]. Any interruption in oxygen supply due to an abnormality in circulation such as retinal artery occlusion or retinal vein thrombosis or atherosclerosis results in retinal hypoxia/ischemia. An extended period of hypoxia leads to the development of complications such as glaucoma, optic neuropathies, diabetic retinopathies, and retinal vein occlusions [1619]. It has been found that the inner retina is more susceptible to hypoxia, in contrast to outer one [20]. To cope with oxidation-induced adverse effect one natural protective characteristic of eye is that intra-ocular O2 tensions are low however, many other cellular defense systems are evolved such as glycolysis, angiogenesis, vasodilation, and erythropoiesis in response to hypoxia [21], but these protective phenomenon are momentary [22], following which cell death and tissue damage occur [11]. Hypoxia-induced generation of ROS results in imbalance of the cellular oxidant-antioxidant status that leads to failure of cellular homeostasis. ROS-driven oxidative stress is a known cause of lipid peroxidation, protein oxidation, and DNA oxidation, which contribute to neurodegeneration [21, 23, 24]. Oxidative stress also has been reported to be cytotoxic to RGCs [10, 25], causing necrotic or apoptotic death [10, 22, 26, 27]. In addition, the generation of ROS is associated with activation or deactivation of several survival factors [28]. NF-κB is a transcription factor which is activated by various stimuli including oxidative stress. NF-κB plays multiple roles in cell survival, proliferation, and differentiation and also in cell death as a pro- or anti-apoptotic transcription factor, depending on cell type or the nature of injury [29, 30]. A wealth of information documents that RelA containing NF-κB complex has an antiapoptotic effect [31]. In glaucoma, NF-κB is highly activated in RGCs and has been suggested to be proapoptotic and implicated in retinal neuronal cell death [32, 33]. Initiation of apoptotic response to a variety of stress signals via NF-κB requires its translocation into nucleus from the cytoplasm. Under normal circumstances, in cell cytoplasm an association between IkB, an inhibitor protein, and NF-κB dimers renders NF-κB inactive. IkB is a member of a family of regulator proteins, viz. IkB-α, IkB-β, and Bcl3. However, in response to stress signals, IkB undergoes phosphorylation, which releases its inhibition of NF-κB. NF-κB translocates to the nucleus and binds to DNA [10, 34]. Moreover, the over-expression of intracellular ROS caused by extracellular stressors is controlled by antioxidant defenses such as catalase, SOD, glutathione peroxidase, and, most importantly, the newly discovered peroxiredoxins [3539]. The peroxiredoxin (Prdx) family includes six known members (Prdx 1-6). Of particular interest is PRDX6 cloned by our group from human lens epithelial cells cDNA library [40]. This agent has GSH peroxidase as well as acidic Ca2+-independent phospholipase A2 activities [37, 3944]. Recently, our group has shown that PRDX6 has protective potential in saving RGCs against glutamate and TNF-α induced cytotoxicity. It acts by limiting ROS and maintaining calcium homeostasis [10, 37, 42, 43, 4548]. The unique ability to regulate signaling and to maintain phospholipid turnover distinguishes PRDX6 from the other five peroxiredoxins (Prdx1 to 5). This molecule is widely expressed, occurring in high levels in the liver, lung, eye lens, and keratinocytes [37, 40, 4850] including RGCs [9], and its reduced expression can lead to cell death and tissue degeneration [47, 48, 51]. Recently, PRDX6 has been implicated in maintaining blood vessel integrity in wounded skin [52, 53] and in development and progression of several diseases, including oxidative-induced cataractogenesis [43, 54], psoriasis [55, 56], atherosclerosis [51], and parkinsonian dementia [57]. Thus, accumulating evidence indicates that underexpression of PRDX6 contributes to pathophysiology of cells and tissues, and this involves an increase in ROS levels. The increase leads to declines in a number of physiological functions because of overmodulation of ROS-mediated gene expression and activation of factors, including NF-κB. Stimulation of such factors in RGC has been implicated as a cause of the initiation of death signaling [58, 59]. However, given the role of PRDX6 in maintaining cellular homeostasis by blocking death signaling and thereby regulating ROS expression [9, 10, 37], we think that a supply of PRDX6 will attenuate the hypoxia-evoked ROS-induced deleterious signaling in RGCs. In the study described here, we used RGCs exposed to 1% O2 and/or CoCl2, a hypoxia mimetic, as a model system to explore the underlying event(s) of hypoxia-induced RGC death. We have shown that RGCs facing hypoxia for longer periods display elevated expression of ROS and reduced levels of PRDX6, and that RGCs over-expressing PRDX6 gain resistance against hypoxia-evoked generation of ROS and ROS-induced cellular insults, by negatively regulating death signaling. In this study, we investigated whether chronic hypoxia evoked the production of ROS in RGCs, and whether over-expression of ROS initiated NF-κB-mediated death signaling by phosphorylation/degradation of IkB, resulting in RGC death. In addition, by using transfection and transactivation assays, we showed that ROS-mediated suppression of Prdx6 mRNA and protein expression in RGCs bearing higher levels of ROS could be attenuated by the over-expression of PRDX6. Collectively, these findings provide a foundation for rational use of antioxidant-based therapeutics for treating or preventing/delaying RGC death from ROS driven oxidative stress under hypoxic conditions. Culture of the retinal ganglion cell RGC-5 (a kind gift from Neeraj Agarwal, University of North Texas Health Science, Fort Worth, TX, USA) were maintained in Dulbecco's modified Eagle's medium (DMEM) containing 10% fetal bovine serum (FBS), 100 U/ml penicillin and 100 μl/ml streptomycin at 37°C with 5% CO2. The cells reaching confluency were trypsinized and subcultured using 1:20 split. RGCs of 5 to 7 passages were used to carry out the experiments. Generation of Hypoxic conditions Cells were either exposed to 1% oxygen using hypoxic chamber or they were treated with cobalt chloride, a hypoxia mimic [60, 61] at various concentrations and for various time intervals. Cell survival assays: MTS and TUNEL assays Cells (1 × 104) were grown in 48 well plates and treated with 50, 100, 150, 200 or 400 μM of CoCl2 for 24, 48 or 72 h. After treatment period, a colorimetric MTS assay (Promega) was performed as described earlier [37]. This assay of cellular proliferation uses 3-(4,5-dimethylthiazol-2-yl)-5-(3-carboxymethoxyphenyl)-2 to 4-sulfophenyl)-2H-tetrazo-lium salt (MTS; Promega, Madison, MI). Upon being added to medium containing viable cells, MTS is reduced to a water-soluble formazan salt. The A490 nm value was measured after cobalt chloride treatment at specified duration with an ELISA reader. The values are represented as a percent change to matched controls within cell types. A TUNEL assay was employed to assess and validate apoptotic cell death. TUNEL staining was performed using an in situ cell death detection kit, Fluorescein (Roche Diagnostics GmbH, Germany), following the company's protocol. Briefly, cells were grown in 4 chambered slide, washed with PBS and fixed in freshly prepared 4% paraformaldehyde in PBS (pH 7.4), followed by incubation in permeabilization solution (0.1% Triton X-100, 0.1% sodium citrate) for 2 min on ice. Cells were rinsed twice with PBS, and incubated in a TUNEL reaction mixture for 60 min at 37°C in the dark. Cells were rinsed three times with PBS. After mounting, samples were microphotographed using a micro-scope (Nikon, ECLIPSE TE 300), and analyzed. To determine the total dead cells, other than only the apoptotic cells, RGCs were stained with trypan blue solution (0.4%), where non viable cells are stained with trypan blue which is normally excluded by the live cells. Construction of Prdx6 Promoter-Chloramphenicol Acetyl-transferase (CAT) Reporter Vector The 5'-flanking region from - 1139 to +109 bp was isolated from mouse genomic DNA and sequenced [10]. A construct of -1139 bp was prepared by ligating it to basic pCAT vector (Promega) using the SacI and XhoI sites. Similarly, construct of deletion mutants of different sizes (- 839 to + 109 bp, construct B; -430 to + 109 bp, construct C) of the Prdx6 promoter with appropriate sense primers bearing SacI and reverse primer with XhoI were made [10]. The plasmid was amplified and used for the CAT assay. Primers were as follows: Construct Afor, 5'-CTGAGAGCTC CTGCCATGTTC-3'; Construct Bfor, 5' CTTCCTCTGGAGCTC AGAATTTAC-3'; Construct Cfor, 5'-CACAG-AGCTC GTTCTTGCCACATC-3'; Constructs A, B, and Crev, 5'-CAGGAACTCGAGG AAGCGGAT-3'. We used construct B in the present study. Assay for intracellular redox state Intracellular redox state levels were measured using the fluorescent dye, H2-DCFH-DA as described earlier [37, 43]. Briefly, cells were washed once with HBSS and incubated in the same buffer containing 5-10 μg of DCFH-DA for 30 min at 37°C. Intracellular fluorescence was detected with Ex485/Em530 using Spectra Max Gemini EM (Molecular Devices, CA). Western analysis Nuclear, cytoplasmic extracts and total Cell lysates were prepared as described previously [10]. Equal amounts of protein samples were loaded onto a 10% SDS gel, blotted onto PVDF membrane, and immune-stained with primary antibodies; PRDX6 monoclonal antibody (1:1000) (Lab Frontier, S. Korea), NF- κB (p65) (Santa Cruz Biotech) and β-actin antibody (Sigma) (1:2000). The membranes were further incubated with horseradish peroxidase-conjugated secondary antibodies (1:1500 dilution) following washing. Specific protein bands were visualized by incubating the membrane with luminol reagent (Santa Cruz Biotechnology) and exposing to film (X-OMAT; Eastman Kodak). Real-time PCR To monitor the levels of Prdx6, NF- κB (p65), and β-actin mRNA in RGCs, total RNA was isolated using the single-step guanidine thiocyanate/phenol/chloroform extraction method (Trizol Reagent; Invitrogen) and converted to cDNA using Superscript II RNAase H-Reverse Transcriptase. Quantitative real-time PCR was performed with SYBR Green Master Mix (Roche Diagnostic Corporation, Indianapolis, IN) in a Roche® LC480 Sequence detector system (Roche Diagnostic Corporation). We used primers specific for Prdx6 (forward 5'-TTGATGATAAGGGCAGGGAC-3' and reverse, 5'-CTACCATCACGCTCTCTCCC-3'), NF-κB (forward 5'-TTTCCCCTCATCTTTCCCTC-3' and reverse 5'-TGTGCTTCTCTCCCCAGG-3') and β-actin (forward 5'-CGTGGGCCGCCCTAGGCACCA-3' and reverse 5'-TTGGCCTTAGGGTTCAGGGGGG-3'). The primers were synthesized at University of Nebraska Medical Center, DNA Facility, Omaha, NE, USA. The comparative Ct method was used to calculate relative fold expression levels using the e-Roche software. The Cts of target genes were normalized to the levels of β-actin as an endogenous control in each group. Expression and purification of GFP-PRDX6 fusion protein A full length cDNA of Prdx6 was isolated from human lens epithelial cell cDNA library using sense (5'-ATGCCCGGAGGTCTGCTTCTCGGGG-3') and antisense (3'-AATTGGCAG CTGACATCCTCTGGCTC-3') primers, and the resultant amplified product was cloned in pcDNA3.1/NT-GFP-TOPO vector procured from Invitrogen [40]. This construct was used for over-expressing PRDX6 in RGCs. Cells transfected with empty GFP vector served as control. Statistical method Data are presented as Mean ± S.D. of the indicated number of experiments. Data were analyzed by Student's t-test when appropriate. A p value of < 0.05 was defined as indicating a statistically significant difference. Hypoxia induced RGC death with apoptosis, and these cells harbored elevated ROS, reduced PRDX6, and increased NF-κB expression Recently reports have documented that hypoxia-induced elevation in intracellular ROS is a cause of pathophysiology in cells and tissues [62]. However, hypoxia exerts both proapoptotic and antiapoptotic biphasic effects that seem to be associated with cell types and conditions surrounding the cells. In the present study, we initially used the hypoxia-mimetic agent cobalt chloride (CoCl2) to expose RGCs to hypoxic stress. We examined whether RGCs exposed to such stress showed reduced survival and died with apoptosis and displayed higher ROS levels. Results from cells exposed to cobalt chloride were compared with those from RGCs exposed to 1% O2. Cells exposed to cobalt chloride showed decrease in cell survival, with levels depending on concentration and exposure time (Figure 1A; black bars). Exposure of RGCs to 1% oxygen for 24 h or 48 h resulted in cell death in a time-dependent manner (Figure 1B; black bars). With both types of exposure, the cellular effects produced by hypoxia were associated with concentration as well as the duration of exposure. These cells were photomicrographed and recorded (Figures 2A-C. arrow; dead cells). The mode of RGC death was apoptosis following treatment with CoCl2 (Figure 2B) or 1% O2 exposure (Figure 2C) after 48 h when compared to unexposed cells (Figure 2A), as shown by TUNEL assay (Figure 2insets). Figure 1 MTS assay showing effect of hypoxia on the viability of RGCs. Cells (1 × 104) were cultured in 48-well plate containing DMEM supplemented with 10% FBS. 24 h later, cells were washed and treated with variable concentrations of cobalt chloride (A; black bars 50, 100, 200 or 400 μM) or exposed to 1% O2 (B; black bar) for a period of 24, 48 or 72 h. Results are means ± SE of three individual experiments. *p < 0.05. Figure 2 Photomicrograph of RGCs without (A) or with CoCl 2 (B) or exposed to 1% O 2 (C). Arrow heads denote dead cells. TUNEL staining was performed as described in 'Methods' section to determine apoptotic RGC death following treatment. Insets: Photomicrograph of TUNEL-positive cells (green fluorescent) treated without (A) or with (B) or exposed to 1% O2 (C). Next, to determine whether RGCs exposed to either CoCl2 or 1% O2 bore higher levels of ROS, we monitored the levels with the fluorescent dye, H2-DCFH-DA. Consistent with earlier reports, an increase in ROS levels was observed in cells exposed to hypoxic stress, and the levels of ROS were increased with increased time of exposure (Figures 3A and 3B; black bars). Figure 3 Histogram showing intracellular ROS expression in RGCs following CoCl 2 treatment or 1% O 2 exposure. Cells were treated with different concentrations of cobalt chloride (50, 100, 200 or 400 μM) (A) or exposed to1% oxygen (B) for a period of 24, 48 or 72 h. ROS were measured with H2-DCFH-DA dye. Results are means ± SE of 3 experiments. *p < 0.05 Because reduced expression of intracellular PRDX6 is causally related to increase expression of ROS, and NF-κB is a regulator of PRDX6 in cells in the redox state [9, 10, 43, 45], we next examined whether levels of these two molecules were altered in cells under conditions of hypoxia. We conducted Western analysis with PRDX6-specific antibody, and the same blotted membrane was reprobed with NF-κB antibody following restriping. As expected, reduced expression of PRDX6 (Figure 4, PRDX6, 48 h or 72 h, lanes 2-4; Figure 5, PRDX6, 48 h, lane 2) and elevated expression of NF-κB (Figure 4, NF-κB, 24, 48 or 72 h, lanes 2-4; Figure 5, NF-κB, 24 or 48 h, lanes 2 and 4) were observed in cells exposed to hypoxia (48 h onwards) (Because the higher dose of cobalt chloride [400 μM] caused ~ 70% of the RGC death, that dose was excluded). Levels of PRDX6 were found to be increased when analyzed after 24 h of hypoxia exposure generated by cobalt chloride (50, 100 or 200 μM) or 1% oxygen (Figure 4, PRDX6, 24 h, lanes 2-4; Figure 5, PRDX6, 24 h, lane 2). The data illustrate the role of PRDX6 in RGC survival under hypoxia exposure. Figure 4 Figure 5 Effect of Hypoxic stress on regulation of PRDX6 and NF-κB proteins in RGCs exposed to 1% O 2 . Cells (4 × 105) were cultured in 100 mm culture plates, and after 24 h these cells were exposed to 1% O2 for a period of 24 and 48 h. After treatment, cell extracts were prepared for Western analysis. A significant increase in PRDX6 protein expression was observed after 24 h and reduced after 48 h of 1% O2 exposure (lane 2). In contrast, an increase in NF-κB protein level was observed (middle panel) while no change was detected in the expression of β-actin level (lower panel), suggesting hypoxia specifically reduced the expression of PRDX6. Histogram shows relative density (Pixels) of protein bands. *p < 0.05. Modulation of PRDX6 and NF-κB in RGCs during hypoxia was due to repression of their transcription Although it was confirmed at the protein level that the expression of PRDX6 and NF-κB was modulated under hypoxia, it was not clear whether the changes in expression were due to modulation in the translation or in the transcription of these molecules. To clarify the regulation of PRDX6 and/or NF-κB by hypoxic stress at the transcriptional level, the cells were exposed to cobalt chloride (50, 100 or 200 μM) or to 1% O2 as described above for 24 h, and the mRNA from these cells was used to conduct real time PCR. Results demonstrated that RGCs exposed to hypoxia had an abundance of Prdx6 mRNA, but levels of NF-κB mRNA were not found to be dramatically high when compared to the controls (Figure 6A; black bars). To validate further activation of PRDX6 during hypoxia, we performed transactivation assays as described in Methods. RGCs were transfected with Prdx6 promoter linked to CAT construct B [10], and were exposed to hypoxia either by treating the cells with cobalt chloride (50, 100 or 200 μM) or by exposing to 1% oxygen. After exposure to various concentrations of cobalt chloride (Figure 6B; black bars) or 1% oxygen (Figure 6C; black bar) a pronounced activation in Prdx6 promoter activity could be observed, suggesting that Prdx6 is transcriptionally regulated in RGCs under hypoxia. This finding indicates that Prdx6 is upregulated to counteract hypoxia-induced cellular damage mediated via NF-κB, which plays an apoptotic role in RGC death. Figure 6 Quantitative PCR showing differential expression of Prdx6 and NF-κB mRNA in RGCs with or without treatment with CoCl 2 or exposed to 1% O 2 . Total RNA was isolated and transcribed into cDNA. PCR was performed using specific primers as described in 'Methods' section. mRNA expression of each Prdx6 and NF-κB was adjusted to the mRNA copies of β-actin. Results indicate that mRNA expression level of Prdx6 was significantly increased after 24 h of exposure to different concentrations of CoCl2 (A; 50, 100 or 200 μM) with an increase of NF-κB mRNA. (B) CAT assay showing promoter activity of Prdx6 following hypoxia. Cells were transiently transfected with Prdx6-CAT (B & C). After 24 h of transfection, cells were either treated with cobalt chloride (50, 100 or 200 μM) (B) or exposed to 1% O2 (C; black bar). Transactivation assay was performed after 72 h of transfection. Results indicate that Prdx6 transcription (B and C) was up-regulated following cobalt chloride or 1% O2 exposure, respectively. *p < 0.05. Hypoxia induced activation of NF-κB and its translocation into nucleus was associated with IkB phosphorylation/degradation To examine the dynamics of NF-κB and IkB interactions under hypoxia, cells were exposed to 200 μM of cobalt chloride and subcellular fractions were assayed by Western blot NF-κB (p65) nuclear translocation (Figure 7A) and IkB phosphorylation/degradation (Figure 7C). Under normal circumstances, cytoplasmic NF-κB is inactive through interactions with an inhibitor protein IkB. The phosphorylation of IkB unmasks the nuclear translocation signal on the NF-κB. In the present study, cells treated with cobalt chloride showed decreased expression of IkB (Figure 7C; IkB; lane 2), with an increase in phospho-IkB levels (Figure 7D; pIkB, lane 2). The results revealed that kinetics of the increase in p65 in nucleus mirrors the kinetics for phosphorylation and degradation of IkB in cytoplasmic fraction. Further activation of NF-κB was confirmed by transactivation assay; RGCs transfected with pLTR-CAT construct, which consists of two NF-κB sites [43], were subjected to hypoxic stress (1% O2) for 24 h. CAT activity assessed with CAT-ELISA as described in Methods revealed activation of NF-κB (Figure 9C, dark gray bar). Collectively, the findings demonstrate activation of NF-κB by hypoxia. Figure 7 Western analysis showing NF-κB translocation in nucleus from cytoplasm and phosphorylation of IkBα in RGCs facing hypoxic stress. Cell (4 × 105) were cultured in 10 mm culture plates and were treated with 200 μM of CoCl2 for 2 h. After treatment, cytoplasmic and nuclear extracts were prepared for western analysis. Cells treated with CoCl2 showed increased expression of NF-κB in nucleus (A, NF-κB, lane 2) with concomitant decrease in cytoplasmic expression (B, NF-κB, lane 2). These cells showed reduced expression of IkB (C; lane 2) and enhanced expression of its phosphorylated form pIkB in cytoplasm (D; lane 2). PRDX6 over-expression attenuated hypoxia-induced RGC death, by reducing ROS production and optimizing NF-κB activation PRDX6 exerts its protective function by regulating ROS expression and blocking cell death signaling. To determine the efficacy of PRDX6 in abolishing hypoxia-evoked ROS-driven damage to and death of RGCs, we transfected RGCs with pGFP-PRDX6 (2, 4 and 6 μg) as described in Experimental Procedures, and transfection efficiency was equalized with OD obtained from GFP fluorescence at Ex485/Em530. We also confirmed over-expression of pGFP-PRDX6 using Western analysis (Figure 8A) As expected, RGCs over-expressing PRDX6 showed reduced levels of ROS when they were exposed to either cobalt chloride (Figure 8B; 50, 100 or 200 μM; black bars) or 1% oxygen (Figure 8C; black bars). Cell death was reduced by ~20% to 30% as observed in these cells treated with various concentrations of the agents compared to controls transfected with empty GFP vector (Figure 9A; black bars). Similar results were obtained when PRDX6 over-expressed cells were exposed to 1% oxygen (Figure 9B; black bars). To test whether PRDX6 administration attenuated NF-κB activation in RGCs following hypoxia treatment, we did transactivation assay in RGCs using pLTR-CAT construct (Figure 9C). Results showed an increase in the promoter activity following hypoxia (1% oxygen) and the increase could be inhibited by a supply of PRDX6 (Figure 9C; black bar). Western analysis further confirmed that extrinsic supply of PRDX6 reduced expression of NF-κB in RGCs exposed to hypoxia (Figure 9D; NF-κB; lane 3). Taken together, the results demonstrated that PRDX6 protects against hypoxia-evoked oxidative stress mediated cell death by restoring survival signaling, at least in RGCs, and it does so by optimizing ROS expression and NF-κB activation and expression. Figure 8 Effect of over-expression of GFP-PRDX6 on ROS levels in RGCs following hypoxic stress. Cellular extract was prepared and resolved on SDS-PAGE, and Western analysis was performed using antibody specific to PRDX6, to assess both exogenous and endogenous expression of PRDX6. ~55 kDa protein band was detected as recombinant GFP-PRDX6 protein (A, right lane). Histogram showing ROS levels in RGCs after exposure to hypoxia (B&C). Cells over-expressed with GFP-PRDX6 prevented excessive generation of ROS against CoCl2 (50, 100 or 200 μM). Cells were transiently transfected with either GFP vector or GFP-PRDX6. After 24 h cells treated with CoCl2 (50, 100 or 200 μM). Figure 9 PRDX6 regulation of NF-kB expression and cellular survival during hypoxia (A). MTS assay showing protective effect of over-expression of PRDX6 on RGCs survival. Cells were transiently transfected with either GFP vector or GFP-PRDX6. After 24 h cells were either treated with CoCl2 (50, 100 or 200 μM) or exposed to 1% O2. Results indicate that GFP-PRDX6 over-expression significantly reduced death of RGCs exposed to CoCl2 (A; 50, 100 or 200 μM) or 1% O2 (B). To monitor the activation of NF-κB, cells were transfected with GFP vector or GFP-PRDX6. These cells were co-transfected with HIV-1LTR-CAT construct (C) having NF-κB sites [37] and were exposed to 1% O2. Results showed the repression of NF-κB-dependent transcriptional activation of HIV-1LTR in cells over-expressing PRDX6 (C; black bar). In parallel experiments, cell extracts was prepared and Western analysis performed to confirm whether GFP-PRDX6 over-expression reduced the expression of NF-κB (D). Upper panel showing decreased expression of NF-κB in nuclear extract of RGCs over-expressing PRDX6. Changes in oxidant and antioxidant balance may alter cellular homeostasis; cells may go through survival or death pathways, depending upon expression of ROS and antioxidant defense capacity. Eye tissues are constantly exposed to external and internal environmental stresses such as sunlight, chemical irritations, and hypoxia. These stressors may lead to blinding disorders of the eye by inducing abnormalities in the homeostatic system of cells. Interruption of normal blood flow to an organ causes ischemia-hypoxia, which can result in tissue injury in many organs, including the heart, liver, lungs, and retina, all physiologically active tissues. Stresses or deficiency of O2 (hypoxia) in retinal tissues may cause severe damage, subsequently leading to blinding disease. The manner in which chronic hypoxia causes cell or tissue damage or cell death has been described in several recent reports documenting that the hypoxia evokes overproduction of ROS, which are a major culprit in cell damage [11]. Moreover, as a physiologically active tissue, the retina requires large quantities of oxygen [11], and fluctuations in oxygen level may alter the entire retinal physiology and lead to failure of homeostasis [11]. Systemic hypoxemia caused by lung or heart disease or a vascular disease in the retina can also cause retinal hypoxia and be a major cause of RGC loss. Recent evidence reveals that chronic hypoxia attenuates the cellular prooxidant-antioxidant balance by accumulation of ROS [63], and this condition has been implicated in progressive neurodegenerative diseases. We believe that chronic hypoxia may be associated with reduced expression and activity of survival molecules and antioxidants such as PRDX6 [9, 10, 37, 42, 43, 64]. In the present study, we found that RGCs exposed to hypoxia displayed elevated expression of ROS, which was associated with reduced expression of PRDX6 (Figures 3, 4 and 5), and these cells underwent apoptosis (Figure 2). These results are consistent with earlier findings that human pulmonary and coronary artery smooth muscle cells bear higher levels of ROS, and the elevated levels of ROS are a major damaging factor [65]. Moreover, ROS is source of oxidative stress, has gained more and more attention recently because of its role as a cellular signaling for a various molecules released from activated glia or microglia such as glutamate [9], cytokines such as TNF-α and growth factors [9, 10]. The production of ROS by these molecules has been associated with activation or deactivation of several transcription factors [810, 12, 43]. We think that elevated levels of inflammatory cytokines in the microenvironment of RGCs are responsible for further elevation of ROS in RGCs that leads RGCs death. Recently, we reported that PRDX6 delivery to RGCs can protect against glutamate or TNF-α mediated cytotoxicity, and that the PRDX6 acts by removing ROS and stabilizing NF-κB activation. Notably, both PRDX6 and NF-κB are producers of ROS. While there is much discussion in the research community about increase or decrease of ROS expression during hypoxia, the present study provides evidence that longer periods of hypoxia generate ROS, and ROS-induced abnormal signaling is a major cause of RGC damage or death (Figures 1, 2 and 3). Our data further support our hypothesis that hypoxia induces ROS; RGCs that over-expressed PRDX6 showed resistance against hypoxic stress, reduced ROS expression, and improved survival. Along with others, we have shown that PRDX6 blocks ROS-mediated pathophysiology that occurs during cataractogenesis, neurological disorders, and diabetic-associated disorders [9, 42, 43], and plays a pivotal role in maintaining lung cell homeostasis [44, 48, 6668]. Moreover, our current study revealed that (i) hypoxia evokes intracellular ROS accumulation, which increases with an increase in time, (ii) ROS elevation is causally related to RGC death, and (iii) PRDX6 can attenuate hypoxia-generated oxidative stress-induced RGC death. Recently, several reports have shown that hypoxic stress induces ROS production, which, if not quenched, leads to cellular pathophysiology [63, 65, 69, 70]. Using a cell culture system, we found that RGCs exposed to either 1% oxygen (physiological hypoxia) or treated with cobalt chloride, a hypoxia mimetic (chemical hypoxia), display elevated expression of ROS (Figure 2) We observed ~30%-60% RGC death in cells with physiological hypoxia (1% oxygen) and ~30%-70% death with cobalt chloride treatment (Figure 1). These data are consistent with previous studies which observed ~25% RGC death after 12 h of exposure to 5% oxygen [71], ~30% cell death after 24 h of 200 μM CoCl2 treatment and found that RGC death following hypoxia was predominantly apoptotic, although both apoptotic and necrotic cell death have been observed [71, 72]. Furthermore, in glaucomatous eyes, selective loss of RGCs occurs [73], and these cells are particularly sensitive to systemic hypoxic stress [74] as a result of long-term oxidative damage induced by ROS [75]. Interestingly, our present study found increased expression of PRDX6 for the first 24 h of hypoxia exposure (Figures 4 and 5), but when hypoxia exposure was prolonged, the expression of PRDX6 was reduced, and the reduction was related to cell death. Thus our results demonstrate a novel mechanism of hypoxia regulation of PRDX6, in which concentration and time of exposure of RGCs to hypoxia play pivotal roles in determining the fate of the RGCs, which is dependent upon PRDX6 expression. Our study further demonstrated that elevated levels of ROS in RGCs caused by hypoxia are a major cause of cell death, and that the increase in ROS can be eliminated by over-expression of PRDX6 (Figures 8 and 9). As other Prdxs did not counteract the changes in RGCs, we consider the role of PRDX6 to be pivotal, at least in those cells. Interestingly, we also found that acute hypoxia is beneficial to RGCs, as the acute condition may attenuate the extent of cellular ROS and provide an adaptive control mechanism. If that is the case, RGC death during eye disorders including glaucoma is probably caused by the cumulative effect of hypoxia over time, which produces ROS-driven oxidative damage. Moreover, elevated ROS expression has been observed in rabbit retinal cells during ischemia induced by high IOP [76]. We have reported that lens epithelial cells (LECs) deficient in PRDX6 bear higher levels of ROS, are vulnerable to oxidative stress, and undergo spontaneous apoptosis [37]. Collectively, our results suggest that the reduced expression of PRDX6 in RGCs exposed to hypoxia may be one cause of RGC death. Moreover, ROS-driven oxidative stress has been related to a number of diseases and disorders. In fact, it is possible that most pathology involves oxidative stress, at least to some extent, and this may occur due to suppression of antioxidants such as PRDX6. Our present work has demonstrated that hypoxia suppresses PRDX6 expression, leading in turn to RGC death. The identification of genes or their products involved in etiology of oxidant-mediated pathology has already led to important insights into the cellular response to stress and mechanisms of oxidant damage. In previous reports, we described the regulation of PRDX6 gene expression by NF-κB [9, 10], and the dependence of PRDX6 expression level upon cellular redox state. However, when expression levels of ROS exceed the control of cellular antioxidants, cells die by apoptosis or necrosis. We believe that optimizing the level of ROS by the delivery of PRDX6 should prevent or delay ROS-induced deleterious signaling. Furthermore, the generation of ROS has been associated with the activation and deactivation of the transcriptional protein NF-κB [77, 78]. Modulation in the activity of NF-κB in neuronal cells is strongly associated with cellular fate, and NF-κB can have either an antiapoptotic or proapoptotic function [79, 80], depending on cell type or cellular microenvironment [29, 30, 81, 82]. Importantly, in RGCs, activation of NF-κB has been found to induce apoptotic signaling, and suppression of its activation significantly enhances the viability of RGCs [30]. Our results also vividly demonstrate that addition of PRDX6 in RGCs attenuates NF-κB activation induced by hypoxia, suggesting that PRDX6 can block the NF-κB-induced death pathway in RGCs. We believe the survival of RGCs is associated with of NF-κB activation in acute hypoxia, since upregulation of PRDX6 would be able to remove ROS, while hyperactivation or inadequate activation of NF-κB in RGCs may be disastrous. Thus, modulation of NF-κB activation should be an important strategy for reducing cellular injury. Overall, it appears that RGC death induced by hypoxia should also be associated with hyper-activation of NF-κB due to higher levels of ROS during glaucoma or other neurological diseases. The activation of NF-κB is seen in various cell types in response to hypoxia. Hypoxia induced activation of NF-κB occurs through IkB activation and its phosphorylation [83, 84]. In this study, we found that hypoxia exposure activates NF-κB with its subsequent translocation into nucleus. We also found increased phosphorylation of IkB in RGCs following hypoxia. These findings suggest that NF-κB activation in RGCs under hypoxic conditions involves the activation of the canonical pathway through degradation/phosphorylation of the IkBα. Our data demonstrate that cells over-expressed with PRDX6 protect the RGCs from hypoxia-induced oxidative stress by removing ROS and thereby normalizing NF-κB activation. We have found that hypoxia induces ROS-driven RGC death caused by down regulation of PRDX6 in cells under prolonged hypoxia, and ROS expression is causally associated with PRDX6 expression level. Results further revealed that ROS are differentially regulated during hypoxia; however, increased expression of ROS, due to deficiency of PRDX6, indeed reflects pathophysiology of RGCs. Because delivery of PRDX6 may attenuate RGC death by optimizing intracellular ROS and NF-κB activation, PRDX6 should be considered as therapeutic agent for hypoxia-induced disorders. Further detailed research will be needed to elucidate the mechanisms involved in the PRDX6-mediated protection of RGCs. Grants provided by the National Eye Institute, NIH (EY-13394 and EY-017613) (to DPS) and Research to Prevent Blindness (R.P.B.) is gratefully acknowledged. Grant support by American Health Assistance Foundation (AHAF) (to NF) is gratefully acknowledged. Authors’ Affiliations Department of Ophthalmology and Visual Sciences, University of Nebraska Medical Center Department of Neurosurgery, University of Nebraska Medical Center Department of Ophthalmology, University of Fukui Department of Pharmacology and Toxicology, University of Missouri- Kansas City 1. Brunelle JK, Bell EL, Quesada NM, Vercauteren K, Tiranti V, Zeviani M, Scarpulla RC, Chandel NS: Oxygen sensing requires mitochondrial ROS but not oxidative phosphorylation. Cell Metab. 2005, 1 (6): 409-414. 10.1016/j.cmet.2005.05.002.View ArticlePubMedGoogle Scholar 2. Chandel NS, McClintock DS, Feliciano CE, Wood TM, Melendez JA, Rodriguez AM, Schumacker PT: Reactive oxygen species generated at mitochondrial complex III stabilize hypoxia-inducible factor-1alpha during hypoxia: a mechanism of O2 sensing. J Biol Chem. 2000, 275 (33): 25130-25138. 10.1074/jbc.M001914200.View ArticlePubMedGoogle Scholar 3. Maltepe E, Simon MC: Oxygen, genes, and development: an analysis of the role of hypoxic gene regulation during murine vascular development. J Mol Med. 1998, 76 (6): 391-401. 10.1007/s001090050231.View ArticlePubMedGoogle Scholar 4. Bunn HF, Poyton RO: Oxygen sensing and molecular adaptation to hypoxia. Physiol Rev. 1996, 76 (3): 839-885.PubMedGoogle Scholar 5. Li H, Ko HP, Whitlock JP: Induction of phosphoglycerate kinase 1 gene expression by hypoxia. Roles of Arnt and HIF1alpha. J Biol Chem. 1996, 271 (35): 21262-21267. 10.1074/jbc.271.35.21262.View ArticlePubMedGoogle Scholar 7. Bruick RK: Expression of the gene encoding the proapoptotic Nip3 protein is induced by hypoxia. Proc Natl Acad Sci USA. 2000, 97 (16): 9082-9087. 10.1073/pnas.97.16.9082.PubMed CentralView ArticlePubMedGoogle Scholar 8. Guo K, Searfoss G, Krolikowski D, Pagnoni M, Franks C, Clark K, Yu KT, Jaye M, Ivashchenko Y: Hypoxia induces the expression of the pro-apoptotic gene BNIP3. Cell Death Differ. 2001, 8 (4): 367-376. 10.1038/sj.cdd.4400810.View ArticlePubMedGoogle Scholar 9. Fatma N, Kubo E, Sen M, Agarwal N, Thoreson WB, Camras CB, Singh DP: Peroxiredoxin 6 delivery attenuates TNF-alpha-and glutamate-induced retinal ganglion cell death by limiting ROS levels and maintaining Ca2+ homeostasis. Brain Res. 2008, 1233: 63-78. 10.1016/j.brainres.2008.07.076.PubMed CentralView ArticlePubMedGoogle Scholar 10. Fatma N, Kubo E, Takamura Y, Ishihara K, Garcia C, Beebe DC, Singh DP: Loss of NF-k B Control and repression of Prdx6 Gene transcription by Reactive Oxygen Species-driven SMAD3-mediated Transforming Growth Factor β Signaling. J Biol Chem. 2009, 284 (34): 22758-22772. 10.1074/jbc.M109.016071.PubMed CentralView ArticlePubMedGoogle Scholar 11. Kaur C, Foulds WS, Ling EA: Hypoxia-ischemia and retinal ganglion cell damage. Clin Ophthalmol. 2008, 2 (4): 879-889. 10.2147/OPTH.S3361.PubMed CentralView ArticlePubMedGoogle Scholar 12. Giaccia A, Siim BG, Johnson RS: HIF-1 as a target for drug development. Nat Rev Drug Discov. 2003, 2 (10): 803-811. 10.1038/nrd1199.View ArticlePubMedGoogle Scholar 13. Adachi M, Takahashi K, Nishikawa M, Miki H, Uyama M: High intraocular pressure-induced ischemia and reperfusion injury in the optic nerve and retina in rats. Graefes Arch Clin Exp Ophthalmol. 1996, 234 (7): 445-451. 10.1007/BF02539411.View ArticlePubMedGoogle Scholar 14. Chidlow G, Osborne NN: Rat retinal ganglion cell loss caused by kainate, NMDA and ischemia correlates with a reduction in mRNA and protein of Thy-1 and neurofilament light. Brain Res. 2003, 963 (1-2): 298-306. 10.1016/S0006-8993(02)04052-0.View ArticlePubMedGoogle Scholar 15. Cohen LH, Noell WK: Relationships between visual function and metabolism. 1965, Orlando, Fla: Academic Press IncGoogle Scholar 16. Chung HS, Harris A, Evans DW, Kagemann L, Garzozi HJ, Martin B: Vascular aspects in the pathophysiology of glaucomatous optic neuropathy. Surv Ophthalmol. 1999, 43 (Suppl 1): S43-50. 10.1016/S0039-6257(99)00050-8.View ArticlePubMedGoogle Scholar 17. Osborne NN, Ugarte M, Chao M, Chidlow G, Bae JH, Wood JP, Nash MS: Neuroprotection in relation to retinal ischemia and relevance to glaucoma. Surv Ophthalmol. 1999, 43 (Suppl 1): S102-128. 10.1016/S0039-6257(99)00044-2.View ArticlePubMedGoogle Scholar 18. Costa VP, Harris A, Stefansson E, Flammer J, Krieglstein GK, Orzalesi N, Heijl A, Renard JP, Serra LM: The effects of antiglaucoma and systemic medications on ocular blood flow. Prog Retin Eye Res. 2003, 22 (6): 769-805. 10.1016/S1350-9462(03)00064-8.View ArticlePubMedGoogle Scholar 19. Tezel G, Yang X: Caspase-independent component of retinal ganglion cell death, in vitro. Invest Ophthalmol Vis Sci. 2004, 45 (11): 4049-4059. 10.1167/iovs.04-0490.View ArticlePubMedGoogle Scholar 20. Tinjust D, Kergoat H, Lovasik JV: Neuroretinal function during mild systemic hypoxia. Aviat Space Environ Med. 2002, 73 (12): 1189-1194.PubMedGoogle Scholar 21. Hall ED, Braughler JM: Central nervous system trauma and stroke. II. Physiological and pharmacological evidence for involvement of oxygen radicals and lipid peroxidation. Free Radic Biol Med. 1989, 6 (3): 303-313. 10.1016/0891-5849(89)90057-9.View ArticlePubMedGoogle Scholar 22. Lieven CJ, Vrabec JP, Levin LA: The effects of oxidative stress on mitochondrial transmembrane potential in retinal ganglion cells. Antioxid Redox Signal. 2003, 5 (5): 641-646. 10.1089/152308603770310310.View ArticlePubMedGoogle Scholar 23. Chan PH: Oxygen radicals in focal cerebral ischemia. Brain Pathol. 1994, 4 (1): 59-65. 10.1111/j.1750-3639.1994.tb00811.x.View ArticlePubMedGoogle Scholar 24. Chan PH: Role of oxidants in ischemic brain damage. Stroke. 1996, 27 (6): 1124-1129.View ArticlePubMedGoogle Scholar 25. Tezel G, Wax MB: Hypoxia-inducible factor 1alpha in the glaucomatous retina and optic nerve head. Arch Ophthalmol. 2004, 122 (9): 1348-1356. 10.1001/archopht.122.9.1348.View ArticlePubMedGoogle Scholar 26. Lieven CJ, Hoegger MJ, Schlieve CR, Levin LA: Retinal ganglion cell axotomy induces an increase in intracellular superoxide anion. Invest Ophthalmol Vis Sci. 2006, 47 (4): 1477-1485. 10.1167/iovs.05-0921.View ArticlePubMedGoogle Scholar 27. Nguyen SM, Alexejun CN, Levin LA: Amplification of a reactive oxygen species signal in axotomized retinal ganglion cells. Antioxid Redox Signal. 2003, 5 (5): 629-634. 10.1089/152308603770310293.View ArticlePubMedGoogle Scholar 28. Rhee SG: Redox signaling: hydrogen peroxide as intracellular messenger. Exp Mol Med. 1999, 31 (2): 53-59.View ArticlePubMedGoogle Scholar 29. Nurmi A, Lindsberg PJ, Koistinaho M, Zhang W, Juettler E, Karjalainen-Lindsberg ML, Weih F, Frank N, Schwaninger M, Koistinaho J: Nuclear factor-kappaB contributes to infarction after permanent focal ischemia. Stroke. 2004, 35 (4): 987-991. 10.1161/01.STR.0000120732.45951.26.View ArticlePubMedGoogle Scholar 30. Charles I, Khalyfa A, Kumar DM, Krishnamoorthy RR, Roque RS, Cooper N, Agarwal N: Serum deprivation induces apoptotic cell death of transformed rat retinal ganglion cells via mitochondrial signaling pathways. Invest Ophthalmol Vis Sci. 2005, 46 (4): 1330-1338. 10.1167/iovs.04-0363.View ArticlePubMedGoogle Scholar 31. Barkett M, Gilmore TD: Control of apoptosis by Rel/NF-kappaB transcription factors. Oncogene. 1999, 18 (49): 6910-6924. 10.1038/sj.onc.1203238.View ArticlePubMedGoogle Scholar 32. Kitaoka Y, Kumai T, Lam TT, Munemasa Y, Isenoumi K, Motoki M, Kuribayashi K, Kogo J, Kobayashi S, Ueno S: Nuclear factor-kappa B p65 in NMDA-induced retinal neurotoxicity. Brain Res Mol Brain Res. 2004, 131 (1-2): 8-16. 10.1016/j.molbrainres.2004.07.021.View ArticlePubMedGoogle Scholar 33. Kucharczak J, Simmons MJ, Fan Y, Gelinas C: To be, or not to be: NF-kappaB is the answer--role of Rel/NF-kappaB in the regulation of apoptosis. Oncogene. 2003, 22 (56): 8961-8982. 10.1038/sj.onc.1207230.View ArticlePubMedGoogle Scholar 35. Spector A, Kuszak JR, Ma W, Wang RR: The effect of aging on glutathione peroxidase-i knockout mice-resistance of the lens to oxidative stress. Exp Eye Res. 2001, 72 (5): 533-545. 10.1006/exer.2001.0980.View ArticlePubMedGoogle Scholar 36. Reddy VN, Kasahara E, Hiraoka M, Lin LR, Ho YS: Effects of variation in superoxide dismutases (SOD) on oxidative stress and apoptosis in lens epithelium. Exp Eye Res. 2004, 79 (6): 859-868. 10.1016/j.exer.2004.04.005.View ArticlePubMedGoogle Scholar 37. Fatma N, Kubo E, Sharma P, Beier DR, Singh DP: Impaired homeostasis and phenotypic abnormalities in Prdx6-/-mice lens epithelial cells by reactive oxygen species: increased expression and activation of TGFbeta. Cell Death Differ. 2005, 12 (7): 734-750. 10.1038/sj.cdd.4401597.View ArticlePubMedGoogle Scholar 38. Ma W, Nunes I, Young CS, Spector A: Catalase enrichment using recombinant adenovirus protects alphaTN4-1 cells from H2O2. Free Radic Biol Med. 2006, 40 (2): 335-340. 10.1016/j.freeradbiomed.2005.08.032.View ArticlePubMedGoogle Scholar 39. Kubo E, Miyazawa T, Fatma N, Akagi Y, Singh DP: Development- and age-associated expression pattern of peroxiredoxin 6, and its regulation in murine ocular lens. Mech Ageing Dev. 2006, 127 (3): 249-256. 10.1016/j.mad.2005.10.003.View ArticlePubMedGoogle Scholar 40. Fatma N, Singh DP, Shinohara T, Chylack LT: Transcriptional regulation of the antioxidant protein 2 gene, a thiol-specific antioxidant, by lens epithelium-derived growth factor to protect cells from oxidative stress. J Biol Chem. 2001, 276 (52): 48899-48907. 10.1074/jbc.M100733200.View ArticlePubMedGoogle Scholar 41. Fisher AB, Dodia C, Manevich Y, Chen JW, Feinstein SI: Phospholipid hydroperoxides are substrates for non-selenium glutathione peroxidase. J Biol Chem. 1999, 274 (30): 21326-21334. 10.1074/jbc.274.30.21326.View ArticlePubMedGoogle Scholar 42. Kubo E, Urakami T, Fatma N, Akagi Y, Singh DP: Polyol pathway-dependent osmotic and oxidative stresses in aldose reductase-mediated apoptosis in human lens epithelial cells: role of AOP2. Biochem Biophys Res Commun. 2004, 314 (4): 1050-1056. 10.1016/j.bbrc.2004.01.002.View ArticlePubMedGoogle Scholar 43. Kubo E, Fatma N, Akagi Y, Beier DR, Singh SP, Singh DP: TAT-mediated PRDX6 protein transduction protects against eye lens epithelial cell death and delays lens opacity. Am J Physiol Cell Physiol. 2008, 294 (3): C842-855. 10.1152/ajpcell.00540.2007.View ArticlePubMedGoogle Scholar 44. Manevich Y, Fisher AB: Peroxiredoxin 6, a 1-Cys peroxiredoxin, functions in antioxidant defense and lung phospholipid metabolism. Free Radic Biol Med. 2005, 38 (11): 1422-1432. 10.1016/j.freeradbiomed.2005.02.011.View ArticlePubMedGoogle Scholar 45. Kubo E, Singh DP, Fatma N, Akagi Y: TAT-mediated peroxiredoxin 5 and 6 protein transduction protects against high-glucose-induced cytotoxicity in retinal pericytes. Life Sci. 2009, 84 (23-24): 857-864. 10.1016/j.lfs.2009.03.019.View ArticlePubMedGoogle Scholar 46. Phelan SA, Wang X, Wallbrandt P, Forsman-Semb K, Paigen B: Overexpression of Prdx6 reduces H2O2 but does not prevent diet-induced atherosclerosis in the aortic root. Free Radic Biol Med. 2003, 35 (9): 1110-1120. 10.1016/S0891-5849(03)00462-3.View ArticlePubMedGoogle Scholar 47. Wang X, Phelan SA, Forsman-Semb K, Taylor EF, Petros C, Brown A, Lerner CP, Paigen B: Mice with targeted mutation of peroxiredoxin 6 develop normally but are susceptible to oxidative stress. J Biol Chem. 2003, 278 (27): 25179-25190. 10.1074/jbc.M302706200.View ArticlePubMedGoogle Scholar 48. Wang Y, Feinstein SI, Manevich Y, Ho YS, Fisher AB: Peroxiredoxin 6 gene-targeted mice show increased lung injury with paraquat-induced oxidative stress. Antioxid Redox Signal. 2006, 8 (1-2): 229-237. 10.1089/ars.2006.8.229.View ArticlePubMedGoogle Scholar 49. Chang XZ, Li DQ, Hou YF, Wu J, Lu JS, Di GH, Jin W, Ou ZL, Shen ZZ, Shao ZM: Identification of the functional role of peroxiredoxin 6 in the progression of breast cancer. Breast Cancer Res. 2007, 9 (6): R76-10.1186/bcr1789.PubMed CentralView ArticlePubMedGoogle Scholar 50. Sparling NE, Phelan SA: Identification of multiple transcripts for antioxidant protein 2 (Aop2): differential regulation by oxidative stress and growth factors. Redox Rep. 2003, 8 (2): 87-94. 10.1179/135100003125001404.View ArticlePubMedGoogle Scholar 51. Wang X, Phelan SA, Petros C, Taylor EF, Ledinski G, Jurgens G, Forsman-Semb K, Paigen B: Peroxiredoxin 6 deficiency and atherosclerosis susceptibility in mice: significance of genetic background for assessing atherosclerosis. Atherosclerosis. 2004, 177 (1): 61-70. 10.1016/j.atherosclerosis.2004.06.007.View ArticlePubMedGoogle Scholar 52. Kumin A, Huber C, Rulicke T, Wolf E, Werner S: Peroxiredoxin 6 is a potent cytoprotective enzyme in the epidermis. Am J Pathol. 2006, 169 (4): 1194-1205. 10.2353/ajpath.2006.060119.PubMed CentralView ArticlePubMedGoogle Scholar 53. Kumin A, Schafer M, Epp N, Bugnon P, Born-Berclaz C, Oxenius A, Klippel A, Bloch W, Werner S: Peroxiredoxin 6 is required for blood vessel integrity in wounded skin. J Cell Biol. 2007, 179 (4): 747-760. 10.1083/jcb.200706090.PubMed CentralView ArticlePubMedGoogle Scholar 54. Pak JH, Kim TI, Joon Kim M, Yong Kim J, Choi HJ, Kim SA, Tchah H: Reduced expression of 1-cys peroxiredoxin in oxidative stress-induced cataracts. Exp Eye Res. 2006, 82 (5): 899-906. 10.1016/j.exer.2005.10.017.View ArticlePubMedGoogle Scholar 55. Frank S, Munz B, Werner S: The human homologue of a bovine non-selenium glutathione peroxidase is a novel keratinocyte growth factor-regulated gene. Oncogene. 1997, 14 (8): 915-921. 10.1038/sj.onc.1200905.View ArticlePubMedGoogle Scholar 56. Munz B, Frank S, Hubner G, Olsen E, Werner S: A novel type of glutathione peroxidase: expression and regulation during wound repair. Biochem J. 1997, 326 (Pt 2): 579-585.PubMed CentralView ArticlePubMedGoogle Scholar 57. Power JH, Shannon JM, Blumbergs PC, Gai WP: Nonselenium glutathione peroxidase in human brain: elevated levels in Parkinson's disease and dementia with lewy bodies. Am J Pathol. 2002, 161 (3): 885-894.PubMed CentralView ArticlePubMedGoogle Scholar 58. Higuchi M, Shirotani K, Higashi N, Toyoshima S, Osawa T: Damage to mitochondrial respiration chain is related to phospholipase A2 activation caused by tumor necrosis factor. J Immunother. 1992, 12 (1): 41-49. 10.1097/00002371-199207000-00005.View ArticlePubMedGoogle Scholar 59. Stadtman ER, Berlett BS: Reactive oxygen-mediated protein oxidation in aging and disease. Chem Res Toxicol. 1997, 10 (5): 485-494. 10.1021/tx960133r.View ArticlePubMedGoogle Scholar 60. Kim KS, Rajagopal V, Gonsalves C, Johnson C, Kalra VK: A novel role of hypoxia-inducible factor in cobalt chloride- and hypoxia-mediated expression of IL-8 chemokine in human endothelial cells. J Immunol. 2006, 177 (10): 7211-7224.View ArticlePubMedGoogle Scholar 62. Bell EL, Klimova TA, Eisenbart J, Schumacker PT, Chandel NS: Mitochondrial reactive oxygen species trigger hypoxia-inducible factor-dependent extension of the replicative life span during hypoxia. Mol Cell Biol. 2007, 27 (16): 5737-5745. 10.1128/MCB.02265-06.PubMed CentralView ArticlePubMedGoogle Scholar 63. Abramov AY, Scorziello A, Duchen MR: Three distinct mechanisms generate oxygen free radicals in neurons and contribute to cell death during anoxia and reoxygenation. J Neurosci. 2007, 27 (5): 1129-1138. 10.1523/JNEUROSCI.4468-06.2007.View ArticlePubMedGoogle Scholar 64. Kubo E, Hasanova N, Tanaka Y, Fatma N, Takamura Y, Singh DP, Akagi Y: Protein expression profiling of lens epithelial cells from Prdx6-depleted mice and their vulnerability to UV radiation exposure. Am J Physiol Cell Physiol. 2010, 298 (2): C342-354. 10.1152/ajpcell.00336.2009.PubMed CentralView ArticlePubMedGoogle Scholar 65. Wu W, Platoshyn O, Firth AL, Yuan JX: Hypoxia divergently regulates production of reactive oxygen species in human pulmonary and coronary artery smooth muscle cells. Am J Physiol Lung Cell Mol Physiol. 2007, 293 (4): L952-959. 10.1152/ajplung.00203.2007.View ArticlePubMedGoogle Scholar 66. Fisher AB, Al-Mehdi AB, Muzykantov V: Activation of endothelial NADPH oxidase as the source of a reactive oxygen species in lung ischemia. Chest. 1999, 116 (1 Suppl): 25S-26S. 10.1378/chest.116.suppl_1.25S.View ArticlePubMedGoogle Scholar 67. Kim TS, Dodia C, Chen X, Hennigan BB, Jain M, Feinstein SI, Fisher AB: Cloning and expression of rat lung acidic Ca(2+)-independent PLA2 and its organ distribution. Am J Physiol. 1998, 274 (5 Pt 1): L750-761.PubMedGoogle Scholar 68. Chowdhury I, Mo Y, Gao L, Kazi A, Fisher AB, Feinstein SI: Oxidant stress stimulates expression of the human peroxiredoxin 6 gene by a transcriptional mechanism involving an antioxidant response element. Free Radic Biol Med. 2009, 46 (2): 146-153. 10.1016/j.freeradbiomed.2008.09.027.PubMed CentralView ArticlePubMedGoogle Scholar 69. Millar TM, Phan V, Tibbles LA: ROS generation in endothelial hypoxia and reoxygenation stimulates MAP kinase signaling and kinase-dependent neutrophil recruitment. Free Radic Biol Med. 2007, 42 (8): 1165-1177. 10.1016/j.freeradbiomed.2007.01.015.View ArticlePubMedGoogle Scholar 70. Saitoh Y, Ouchida R, Miwa N: Bcl-2 prevents hypoxia/reoxygenation-induced cell death through suppressed generation of reactive oxygen species and upregulation of Bcl-2 proteins. J Cell Biochem. 2003, 90 (5): 914-924. 10.1002/jcb.10723.View ArticlePubMedGoogle Scholar 71. Chen YN, Yamada H, Mao W, Matsuyama S, Aihara M, Araie M: Hypoxia-induced retinal ganglion cell death and the neuroprotective effects of beta-adrenergic antagonists. Brain Res. 2007, 1148: 28-37. 10.1016/j.brainres.2007.02.027.View ArticlePubMedGoogle Scholar 72. Zhu X, Zhou W, Cui Y, Zhu L, Li J, Feng X, Shao B, Qi H, Zheng J, Wang H, Chen : Pilocarpine protects cobalt chloride-induced apoptosis of RGC-5 cells: involvement of muscarinic receptors and HIF-1 alpha pathway. Cell Mol Neurobiol. 2009, 30 (3): 427-435. 10.1007/s10571-009-9467-2.View ArticlePubMedGoogle Scholar 73. Sucher NJ, Lipton SA, Dreyer EB: Molecular basis of glutamate toxicity in retinal ganglion cells. Vision Res. 1997, 37 (24): 3483-3493. 10.1016/S0042-6989(97)00047-3.View ArticlePubMedGoogle Scholar 74. Kergoat H, Herard ME, Lemay M: RGC sensitivity to mild systemic hypoxia. Invest Ophthalmol Vis Sci. 2006, 47 (12): 5423-5427. 10.1167/iovs.06-0602.View ArticlePubMedGoogle Scholar 75. Okuno T, Oku H, Sugiyama T, Ikeda T: Glutamate level in optic nerve head is increased by artificial elevation of intraocular pressure in rabbits. Exp Eye Res. 2006, 82 (3): 465-470. 10.1016/j.exer.2005.08.004.View ArticlePubMedGoogle Scholar 76. Nucci C, Tartaglione R, Rombola L, Morrone LA, Fazzi E, Bagetta G: Neurochemical evidence to implicate elevated glutamate in the mechanisms of high intraocular pressure (IOP)-induced retinal ganglion cell death in rat. Neurotoxicology. 2005, 26 (5): 935-941. 10.1016/j.neuro.2005.06.002.View ArticlePubMedGoogle Scholar 77. Kaltschmidt B, Widera D, Kaltschmidt C: Signaling via NF-kappaB in the nervous system. Biochim Biophys Acta. 2005, 1745 (3): 287-299. 10.1016/j.bbamcr.2005.05.009.View ArticlePubMedGoogle Scholar 78. Mattson MP, Meffert MK: Roles for NF-kappaB in nerve cell survival, plasticity, and disease. Cell Death Differ. 2006, 13 (5): 852-860. 10.1038/sj.cdd.4401837.View ArticlePubMedGoogle Scholar 79. Tamatani M, Che YH, Matsuzaki H, Ogawa S, Okado H, Miyake S, Mizuno T, Tohyama : Tumor necrosis factor induces Bcl-2 and Bcl-x expression through NFkappaB activation in primary hippocampal neurons. J Biol Chem. 1999, 274 (13): 8531-8538. 10.1074/jbc.274.13.8531.View ArticlePubMedGoogle Scholar 80. Marchetti L, Klein M, Schlett K, Pfizenmaier K, Eisel UL: Tumor necrosis factor (TNF)-mediated neuroprotection against glutamate-induced excitotoxicity is enhanced by N-methyl-D-aspartate receptor activation. Essential role of a TNF receptor 2-mediated phosphatidylinositol 3-kinase-dependent NF-kappa B pathway. J Biol Chem. 2004, 279 (31): 32869-32881. 10.1074/jbc.M311766200.View ArticlePubMedGoogle Scholar 81. Schneider A, Martin-Villalba A, Weih F, Vogel J, Wirth T, Schwaninger M: NF-kappaB is activated and promotes cell death in focal cerebral ischemia. Nat Med. 1999, 5 (5): 554-559. 10.1038/8432.View ArticlePubMedGoogle Scholar 82. Shou Y, Gunasekar PG, Borowitz JL, Isom GE: Cyanide-induced apoptosis involves oxidative-stress-activated NF-kappaB in cortical neurons. Toxicol Appl Pharmacol. 2000, 164 (2): 196-205. 10.1006/taap.2000.8900.View ArticlePubMedGoogle Scholar 83. Cummins EP, Taylor CT: Hypoxia-responsive transcription factors. Pflugers Arch. 2005, 450 (6): 363-371. 10.1007/s00424-005-1413-7.View ArticlePubMedGoogle Scholar 84. Cummins EP, Seeballuck F, Keely SJ, Mangan NE, Callanan JJ, Fallon PG, Taylor CT: The hydroxylase inhibitor dimethyloxalylglycine is protective in a murine model of colitis. Gastroenterology. 2008, 134 (1): 156-165. 10.1053/j.gastro.2007.10.012.View ArticlePubMedGoogle Scholar © Tulsawani et al; licensee BioMed Central Ltd. 2010
Life beyond the automobile in Southern California Archive for the month “July, 2013” Cars and the Environment Pt. 2 In my review of Tom McCarthy’s Auto Mania (Cars and the Environment pt. 1), we explored the unprecedented environmental harm resulting from the mass production and use of motor vehicles.  Whereas McCarthy argues that consumer decision-making drove the automobile to its apex in modern American life, our next author, Christopher Wells, places those consumer decisions in the context of local and national government policies that created a physical environment that virtually required car ownership for full membership in society. Wells’s book, Car Country: An Environmental History (University of Washington Press, 2012) provides a context for those consumer decisions.  If, after all, one is dependent on the automobile because of an infrastructure designed primarily for automobility, how free are those consumer decisions?  And how did this infrastructure come to be so dominant?  Wells sets his interpretation apart from what he calls the “love affair thesis” (i.e., that America’s love affair with cars is the primary explanation for our car-dominant society) and what he calls the “conspiracy thesis” (i.e., that automobile dominance occurred as a result of a cabal of automobile manufacturers and oil companies removing streetcars and weakening public transportation). Wells argues that we must look at the broader patterns of land use and development that shape people’s transportation needs and choices.  Put bluntly, when developers and government agencies design a landscape to be accessed primarily by automobiles, they create a “car country” that virtually requires automobile ownership.  If, on the other hand, a society designs mixed-use landscapes that are conveniently accessible by walking, bicycling, and transit, people will find it easier to get along without a car.  He contrasts his own experience growing up in car-centric suburban Atlanta, where he was dependent on a car, and where he cherished his beloved Toyota pickup with his later experience living in Switzerland, where he found it easy (and inexpensive) to get around without a car and where, he notes, “I never really missed having a car.”  When he returned to the US, he tried cycling for transportation but it “felt dangerous” once he got beyond the confines of his own neighborhood where “a crush of traffic had enveloped the city in the 1980s.”  He concluded from his own experience that “How I felt about cars had little bearing on whether or not I needed one.”  Thus, he seeks to understand how people’s need for a car influenced how they felt about cars, and he provides a social and environmental context for Americans’ widespread use of the car by the end of the 20th century.  Wells makes a persuasive case that land-use patterns, not attitudes (i.e., the “love affair”) are the strongest determinant of a transportation system’s success, whether it is transit-based or car-based. (pp. xx-xxv)  Critics of the car have tended, he says, to focus on cars rather than roads and on the behavior of drivers rather than the powerful forces shaping American land-use patterns.  (xxxiv) Wells is at his best getting us to “think about landscapes,” and the impact they have on people’s decisions about driving.  He contrasts older “streetcar neighborhoods” of the pre-automobile era that were organized around streetcar routes with walkable distances between housing, shopping, and other neighborhood destinations, and the post-WWII “exit ramp neighborhoods” zoned as single-use, geographically separated areas designed to be conveniently accessed only by automobile.  The process did not happen by itself, but was facilitated and accelerated by government policies that drove highway design and funding while neglecting public transit and FHA loan guidelines that favored suburban housing and retail developments zoned for single-use.  Meanwhile older, mixed-use streetcar neighborhoods were frequently neglected or destroyed by freeway construction and “urban renewal.”  Wells shows that the postwar drive to the suburbs was indeed a “choice,” but it was a choice that was virtually the only rational one for many people, given the fact that its immense costs were effectively socialized by federal, state, and local policies.   Once the process began, it locked in the auto-centered lifestyle, leaving people few convenient alternatives to the car. streetcar vs. car design Wells reiterates the tremendously destructive environmental impact of the automobile highlighted by Tom McCarthy, underscoring the imperative to change the policies that lead to car-dependence for millions.  He also highlights the immense challenge this will pose, for the costs of car-dependence are often invisible on an individual level: Both smog and climate change illustrate a persistent theme in environmental politics: problems that seem negligible or unimportant on an individual scale can, once aggregated, have national or even global environmental implications.  Because the problems do not become clear until after large numbers of people are involved, the damaging behaviors have often accrued both widespread social acceptance and economic importance.  Moreover, the causal linkage between seemingly harmless behaviors … and environmental problems … frequently requires elaborate scientific explanation.  This creates opportunities for entrenched interests to challenge the science … which often take time and study to disprove.  As a result, “attack, delay, and ask for more research” has proven a fruitful strategy for those hoping to avoid new environmental regulations.  Moreover, because such problems frequently necessitate sweeping changes in established behaviors, effective regulations are frequently intrusive and perceived as onerous. (p. 351) Applied to the effort to move people away from auto-dependence, this theme suggests a daunting challenge lies ahead for those of us who seek to build a new infrastructure around alternatives to the automobile.  Nevertheless, Wells’s study proves that Americans are not hard-wired to love cars, and that creating more compact, mixed-use developments in cities and even suburbs around good transit and safe streets for bicycling and walking can wean Americans from their environmentally destructive and unhealthy auto habit.  It also suggests that for many people changing attitudes are likely to follow, rather than precede, a change in our infrastructure. Cars and the Environment (Pt 1) As an historian, my summer reading lists lean heavily toward nonfiction history.  As an advocate for bicycling, transit, and complete streets, it may strike some as odd that I’m interested in the history of the automobile, but there’s no question that, for better or worse, the automobile has reshaped our world and it behooves those of us who are critical of the car-centered transportation system to understand it in all its complexity.  To that end, I will be reviewing two recent scholarly histories on my summer reading list that explore the social and environmental impact of the automobile and my reflection on what this means for moving our culture away from its auto dependency.  I’ll provide these reviews serially, so that I can give sufficient attention to each. The first study under review is Tom McCarthy’s Auto Mania: Cars, Consumers, and the Environment (Yale University Press, 2007), which explores what McCarthy sees as Americans’ “love affair” with the automobile from an environmental standpoint.  According to McCarthy, this “love affair” was the result of millions of consumer decisions, and the car as a medium for Americans’ psychological and social desires.  In other words, the car has played a central role in 20th century American society, McCarthy argues, because it has been much more than a mode of transportation, it has been an expression of economic success and social identity, Americans’ “chief talisman of successful belonging.” (p. 47)  While McCarthy thinks Americans’ consumer-driven car culture has been significantly  influenced by the auto industry’s marketing strategies, he argues that consumers have not always been passive recipients of industry marketing.  He provides examples of consumers acting in ways that auto manufacturers did not expect, such as the rise of the simple Volkswagen in the 1950s and 1960s as a counterpoint to Detroit’s “bigger is better” mentality.  Thus, he sees cars as providing consumers with important cultural capital, beyond the utilitarian aspect.  As such, any effort to shift toward a multi-modal transportation system must grapple with the deep psychological attachment Americans have to their cars. McCarthy’s assessment of the environmental consequences of the “love affair” with cars is the strength of this study.  By the 1940s, the environmental impact of the use of automobiles and the burning of gasoline for personal propulsion became obvious and prompted an unprecedented government regulatory apparatus to deal with it.  Los Angeles, “car capital” of the nation, not only had some of the nation’s worst smog, but led the effort to regulate it when it became apparent that the smog was negatively affecting the region’s carefully crafted image as a tourist destination. (pp. 116-17)  It is sobering to realize that the industry resisted smog controls for decades, meaning that effective reduction of smog in US cities did not occur until the 1970s following the mobilization of the environmental movement.  Ultimately, it was a mobilized citizenry demanding government regulation, rather than consumer choice and the free market that cleaned the air in Los Angeles. (p. 254-55)  There are important lessons in McCarthy’s book for the effort to regulate carbon emissions today, since it can be argued we don’t have the luxury to wait decades for the industry to shift away from business as usual. Where McCarthy is at his most trenchant, is his unpacking of a major portion of the oversized environmental footprint of the automobile, from raw material extraction through manufacturing, use, and disposal.  While consumer demand may have driven the industry, McCarthy argues, that demand created unprecedented environmental problems.  By the 1920s, auto manufacturers were (and still are) among the world’s largest consumers of raw materials such as iron, steel, rubber, plate glass, leather, lead, zinc, and aluminum.  Modern strip-mining techniques were pioneered and expanded in order to meet the insatiable demand of the auto industry, deeply scarring the land.  Manufacturing cars produced unprecedented levels of industrial pollution: Fly ash, iron oxide, heavy metals, sulfur dioxide, and or course, millions of tons of carbon dioxide belched from the smokestacks of the coke ovens, blast furnaces, foundries, steel mills, and plants of American steel and auto industries.  Iron, sulfuric acid, cyanide, phenols, and heavy metals poured into the sewers and rivers that served as liquid waste conduits away from the plants.  (p. 46)   A full environmental accounting of the automobile industry would indeed be a vast undertaking, involving an assessment of the environmental impacts not only of the major manufacturers, but the thousands of smaller suppliers the industry relies upon.  A total environmental accounting is beyond the scope of McCarthy’s study, but even focusing on one manufacturing plant, Ford’s River Rouge plant in Dearborn, MI, offers evidence of the profoundly troubling environmental legacy of the industry.  McCarthy helps us see that a major portion of the automobile’s environmental footprint came from its raw material extraction and refining.  That relative environmental impact remains true today whether the car burns gasoline or uses electricity to power its engine. Consider the amount of strip mining that will be necessary to provide lithium ion batteries for literally hundreds of millions—perhaps billions—of electric vehicles and the toxic legacy of their inevitable disposal.  McCarthy’s historical analysis provides an opportunity for us to see why it simply may not be possible to manufacture cars on the massive scale necessary for even a fraction of the world’s population to drive and not cause serious damage to the earth and its climate, even if they don’t burn gasoline (and this doesn’t take into account the carbon footprint of sprawl attendant to the automobile lifestyle).  McCarthy traces the efforts over the decades after World War II to reduce the industrial pollutants flowing from smokestacks, but large quantities of pollutants and tremendous energy consumption (often fossil-fuel derived) will continue to be an inevitable by-product of large scale automobile manufacturing.  Viewed as an entire system of resource extraction, energy intensive mass production, distribution, use, and disposal, we might reasonably conclude that there is no such thing as a “green” car. McCarthy helps us see the larger environmental impact of the car beyond tailpipe emissions, helps us understand that we shouldn’t expect these environmental consequences to be addressed by consumer choice alone, and suggests that our society may need to rethink its “auto mania.”  If there is a blind spot in McCarthy’s analysis, it is that by placing so much emphasis on consumer choice as a driving force for automobility, he leaves little room for analyzing the way in which the radical redesign of the built environment around the automobile in the 20th century provided the context for those consumer decisions and eventually precluded virtually any “choice” not to drive. It is to that aspect we shall turn in my next review. A Sea Change Something Happening Here Pasadena Complete Streets Forum discusses Pasadena's Bike Plan. Photo courtesy DPNA Pasadena Complete Streets Forum discusses Pasadena’s Bike Plan. Photo courtesy DPNA Post Navigation %d bloggers like this:
Efforts to incorporate Bowmanstown as a borough occurred as early as 1892. The village contained about 300 inhabitants in 1896 but the nearby New Jersey Zinc Company soon added to its growth. Bowmanstown was incorporated as a Borough on November 29, 1913 for the purpose of providing general local government services to residents of the community. Upon incorporation of Bowmanstown as a borough its boundaries encompassed lands measuring 0.75 square mile. The borough's assessed valuation in 1918 was $279,000.00. The population of 834 in 1920 remained relatively constant for decades. The Bowmanstown Borough Municipal Building (Borough Hall) is a converted school building that was constructed in 1903 to serve the youths of the community. In 1958, the Palmerton School District was established and combined several local schools in order to create a regional school thus making the Bowmanstown campus obsolete. In 1964, the Borough acquired the old brick school building and has been using it as offices ever since. The borough kept the building in its original condition. The Bowmanstown Borough Authority was incorporated August 24, 1997 and was created for the purpose of owning and operating the Bowmanstown Public Water System. On February 11, 2002 the Authority began construction of its water system improvement project which included a new chlorine building, looping numerous water mains, installing new services, erection of a new 250,000 gallon Standpipe and a new liner to the one Reservoir. In 2009, the Authority replaced their two roofs at the Reservoirs with metal roofs. Ongoing water projects will continue to transpire throughout the years.
Home » X-Ray Full-Body Scanners X-Ray Full-Body Scanners for Airport Security X-Ray Full-Body Scanners home Context - To improve airport security in the light of terrorist threats new full-body scanners have been developed to complement existing metal detectors and hand searches. Scanner types that do not use X-rays - "millimeter wave scanners" are already allowed in the EU and deployed in some airports. Other types of scanners already used in the USA expose passengers to low levels of X-rays. They are not yet authorised in the EU because of concern about potential health risks. How safe are such X-ray security scanners for passengers, in particular for frequent flyers? • Source document:SCENIHR (2012) • Summary & Details: GreenFacts Latest update: 30 September 2013 How do those full-body scanners work? Whole body scanners provide a picture of the person's body through the clothes to reveal hidden objects. Four technologies are currently on the market: Millimeter-wave scanners, that don't use X-rays: X-ray scanners: How much radiation are people exposed to in x-ray scanners? When exposed to X-rays our body absorbs energy, the amount of energy effectively absorbed over time is expressed in "sievert" (Sv). Over the course of one year, a person should not be exposed to more than a total of 1 millisievert from man-made sources such as medical diagnostic devices or security scanners. This is the maximum acceptable limit set for the general public and is roughly equivalent to the amount of natural radiation we are also exposed to. Transmission scanners that see into the body use higher energy X-rays than Backscatter scanner that only view the surface and as a result the dose absorbed is 10 times greater. A single scan is roughly the equivalent of one hour of background radiation at ground level, or 10 minutes at cruising altitude in an airplane. In the worst case scenario, of a person being scanned three times a day every working day throughout the year, a backscatter scanner would contribute 0,3 millisievert to their annual dose. A transmission scanner, however, would contribute 3 millisievert and exceed the tolerable limit. In practice, most passengers would not be exposed so frequently to these scanners. This may however be a concern for airline crew or people who fly very frequently. Does exposure to x-rays from scanners present health risks? Exposure to high levels of X-rays can increase the risk of cancer and cardiovascular diseases, lead to cloudiness of the lens of the eye and hereditary effects. However, there is no evidence that the low radiation doses received from full- body scanners would induce any health problems. Nonetheless, each exposure adds to the overall radiation dose we receive in the course of our life and in the long term, the risk of developing cancer increases with radiation dose. While no dose can be considered completely safe, it is likely that the increased cancer risk from exposure to radiation from security scanners is so low that it cannot be distinguished from the effects of natural radiation or the background risk due to other factors. Direct evidence of an increased cancer risk has only been found for cumulative doses higher than 100 millisievert. Is the use of full-body x-ray scanners justified? To decide whether or not the use of X-ray scanners is acceptable, it is necessary to weigh the benefits and risks but this is not straightforward. The main benefit is improved flight safety but there are economic costs and low health risks. So, whether or not X-ray scanners are acceptable for passenger screening is ultimately not a scientific, but a political decision that needs to take into account various factors. This fact sheet is based on the scientific opinion "Health effects of security scanners for passenger screening (based on X-ray technology)" adopted on 26 April 2012 by the independent European Scientific Committee on Emerging and Newly Identified Health Risk. FacebookTwitterEmailDownload (1 page, 0.4 MB) Themes covered Publications A-Z
#ifdef _DEBUG #include "../../../library/src/debug_template.hpp" #define DMP(...) dump(#__VA_ARGS__, __VA_ARGS__) #else #define DMP(...) ((void)0) #endif #include <cassert> #include <cstdio> #include <cmath> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <set> #include <map> #include <unordered_map> #include <queue> #include <numeric> #include <algorithm> #include <bitset> #include <functional> using namespace std; using lint = long long; constexpr int INF = 1010101010; constexpr lint LINF = 1LL << 60; struct init { init() { cin.tie(nullptr); ios::sync_with_stdio(false); cout << fixed << setprecision(10); } } init_; template<const int &Modulo> struct Mint { lint val; constexpr Mint(lint v = 0) noexcept: val(v % Modulo) { if (val < 0) val += Modulo; } constexpr Mint &operator+=(const Mint &r) noexcept { val += r.val; if (val >= Modulo) val -= Modulo; return *this; } constexpr Mint &operator-=(const Mint &r) noexcept { val -= r.val; if (val < 0) val += Modulo; return *this; } constexpr Mint &operator*=(const Mint &r) noexcept { val = val * r.val % Modulo; return *this; } constexpr Mint &operator/=(const Mint &r) noexcept { lint a{r.val}, b{Modulo}, u{1}, v{0}; assert(gcd(a, b) == 1 && "a and b must be co-prime"); while (b) { lint t = a / b; a -= t * b; a ^= b, b ^= a, a ^= b; u -= t * v; u ^= v, v ^= u, u ^= v; } val = val * u % Modulo; if (val < 0) val += Modulo; return *this; } constexpr Mint operator+(const Mint &r) const noexcept { return Mint(*this) += r; } constexpr Mint operator-(const Mint &r) const noexcept { return Mint(*this) -= r; } constexpr Mint operator*(const Mint &r) const noexcept { return Mint(*this) *= r; } constexpr Mint operator/(const Mint &r) const noexcept { return Mint(*this) /= r; } constexpr Mint operator-() const noexcept { return Mint(-val); } constexpr bool operator==(const Mint &r) const noexcept { return val == r.val; } constexpr bool operator!=(const Mint &r) const noexcept { return !((*this) == r); } constexpr bool operator<(const Mint &r) const noexcept { return val < r.val; } constexpr friend ostream &operator<<(ostream &os, const Mint<Modulo> &x) noexcept { return os << x.val; } constexpr friend istream &operator>>(istream &is, Mint<Modulo> &x) noexcept { lint tmp{}; is >> tmp; x = Mint(tmp); return is; } [[nodiscard]] constexpr Mint pow(lint n) const noexcept { Mint res{1}, tmp{*this}; while (n > 0) { if (n & 1) res *= tmp; tmp *= tmp; n >>= 1; } return res; } }; constexpr int MOD = 1000000007; using mint = Mint<MOD>; class UnionFind { private: vector<int> data; public: explicit UnionFind(int size) : data(size, -1) {} [[nodiscard]] int root(int x) { return data[x] < 0 ? x : data[x] = root(data[x]); } [[nodiscard]] bool is_same(int x, int y) { return root(x) == root(y); } [[nodiscard]] int size(int x) { return -data[root(x)]; } bool unify(int x, int y) { x = root(x); y = root(y); if (x != y) { if (data[y] < data[x]) swap(x, y); data[x] += data[y]; data[y] = x; return true; } return false; } }; int main() { int H, W, K = 0; cin >> H >> W; vector<vector<char>> grid(H, vector<char>(W)); for (int i = 0; i < H; i++) for (int j = 0; j < W; j++) cin >> grid[i][j]; for (int i = 0; i < H; i++) for (int j = 0; j < W; j++) K += '.' == grid[i][j]; UnionFind ufH(H * W), ufW(H * W); for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { const int now = i * W + j; if (j + 1 < W && grid[i][j] == grid[i][j + 1]) ufH.unify(now, now + 1); if (i + 1 < H && grid[i][j] == grid[i + 1][j]) ufW.unify(now, now + W); } } vector<mint> pow2(H * W + 1); pow2[0] = 1; for (int i = 0; i < H * W; i++) pow2[i + 1] = pow2[i] * 2; mint ans = 0; for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { if (grid[i][j] == '#') continue; const int now = i * W + j; int cnt = (int)ufH.size(now) + (int)ufW.size(now) - 2; ans += pow2[K - 1] + (pow2[cnt] - 1) * pow2[K - cnt - 1]; } } cout << ans << '\n'; return 0; }
Common Core Catholic Identity Initiative A national working group has begun the Common Core Catholic Identity Initiative (CCCII) to develop and disseminate resources and guidelines to assist Catholic elementary and secondary schools in integrating elements of Catholic identity (Catholic values, Scripture, Church social teachings, encyclicals, etc.) into curriculum and instruction based on the Common Core State Standards. The initial phase of CCCII focuses on K-8 English/Language Arts/ Literacy. Resources for other subjects and for 9-12 curriculum will be developed in later phases. Forty-six states have agreed to adopt the Common Core State Standards, a set of high quality K-12 learning standards that includes rigorous content and application of knowledge using higher-order thinking skills, leading students to college and career readiness. Currently, Catholic schools are assessing what the implications of the standards and accompanying assessments may be for them. While Catholic schools have their own local or diocesan standards, their ability to continue to provide high-quality education for their students is compelling them to consider adoption of the common core standards. Catholic schools will be impacted as curriculum resources and professional development opportunities become aligned with Common Core State Standards by producers of instructional materials, college teacher preparation programs, or regulations for participation in the federal programs that currently benefit their students and teachers. Within this environment, maintaining the uniqueness and integrity of the Catholic school will require integrating the demands of their mission and the academic expectations of their constituents and the wider education community. To assist Catholic schools with enhancing Catholic identity integrated into the curriculum, the Common Core Catholic Identity Initiative (CCCII) has been launched as a collaborative project involving Catholic universities, corporations and sponsors invested in Catholic education, and the National Catholic Educational Association (NCEA). The Common Core Catholic Identity Initiative has two goals: - to empower Catholic schools and dioceses to design and direct the implementation of the Common Core standards within the culture and context of a Catholic school curriculum - to infuse the Common Core standards with the faith/principles/values/social justice themes inherent in the mission and Catholic identity of the school. The CCCII project aims to accomplish its goals by creating a process and a product: Phase 1: Gather approximately 35 practitioners and curriculum and catechetics experts to pilot a CCCII ELA Unit development process to be shared with the larger Catholic educational community. (June 2012) Phase 2: Revise and refine the unit development process so that it can be replicated in dioceses around the country. Phase 3: Invite participation in development of additional CCCII ELA Units by Catholic educators around the country. Phase 1: Utilize the expertise and strength of experienced and innovative teachers to develop complete units/exemplars that join Catholic identify with the Common Core curriculum standards. Utilize the expertise of CCCII leaders to develop supporting resources and guidelines. (June 2012) Phase 2: Post exemplar units, guidelines, and resources developed in for the June 2012 launch for open access by Catholic educators on the Catholic School Standards Project Website www.catholicschoolsstandards.org) . (July 2012) Phase 3: Expand exemplar units and Catholic Identity resources available for use by local Catholic schools. Tailor the CCCII Unit development process for Catholic secondary schools. Expand CCCII to include additional subject areas. Meet the CCCII Leadership and Planning Teams
#include <advent.h> #include <advent/map.h> #include <advent/pcre.h> #include <advent/set.h> #include <advent/vector.h> #include <assert.h> #include <config.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "advent/permute.h" typedef struct { char* s; size_t l; } string_t; string_t string_from_cstr(char* s) { return (string_t){ .s = s, .l = strlen(s), }; } void string_free(string_t s) { free(s.s); } DECLARE_MAP(happiness_catalog_entry_t, long); DEFINE_MAP(happiness_catalog_entry_t, long); DECLARE_MAP(happiness_catalog_t, happiness_catalog_entry_t); DEFINE_MAP(happiness_catalog_t, happiness_catalog_entry_t); typedef struct { string_t a; string_t b; long happiness; } happiness_catalog_pair_t; DECLARE_VECTOR(happiness_catalog_pair_vec_t, happiness_catalog_pair_t); DEFINE_VECTOR(happiness_catalog_pair_vec_t, happiness_catalog_pair_t); DECLARE_VECTOR(string_vec_t, string_t); DEFINE_VECTOR(string_vec_t, string_t); int main(void) { FILE* fp = fopen(ADVENT_INPUT, "r"); if (fp == NULL) { fprintf(stderr, "Failed to open %s\n", ADVENT_INPUT); return 1; } int err; size_t errofs; pcre2_code* code = pcre2_compile((PCRE2_SPTR) "(\\w+) would (gain|lose) (\\d+) happiness " "units by sitting next to (\\w+)\\.", PCRE2_ZERO_TERMINATED, 0, &err, &errofs, NULL); if (code == NULL) { PCRE2_UCHAR buffer[256]; pcre2_get_error_message(err, buffer, sizeof(buffer)); fprintf(stderr, "PCRE2 compilation failed at offset %d: %s\n", (int)errofs, buffer); return 1; } pcre2_match_data* match_data = pcre2_match_data_create_from_pattern(code, NULL); if (match_data == NULL) { fprintf(stderr, "Failed to create match data\n"); return 1; } char* line = NULL; size_t line_length = 0; Set names; Set_init(&names); happiness_catalog_pair_vec_t pairs; happiness_catalog_pair_vec_t_init(&pairs); while (getline(&line, &line_length, fp) != -1) { line_length = strlen(line); if (line[line_length - 1] == '\n') { --line_length; line[line_length] = '\0'; } int ret = pcre2_match(code, (PCRE2_SPTR)line, line_length, 0, 0, match_data, NULL); if (ret < 0) { fprintf(stderr, "Failed to match line: %s\n", line); return 1; } PCRE2_SIZE* ovector = pcre2_get_ovector_pointer(match_data); Set_insert(&names, line + ovector[2], ovector[3] - ovector[2]); long happiness = strtol(line + ovector[6], NULL, 10); if (strncmp(line + ovector[4], "lose", ovector[5] - ovector[4]) == 0) { happiness = -happiness; } happiness_catalog_pair_t pair = { .a = string_from_cstr( advent_strndup(line + ovector[2], ovector[3] - ovector[2])), .b = string_from_cstr( advent_strndup(line + ovector[8], ovector[9] - ovector[8])), .happiness = happiness, }; happiness_catalog_pair_vec_t_push(&pairs, pair); free(line); line = NULL; } happiness_catalog_t catalog; happiness_catalog_t_init(&catalog); for (size_t i = 0; i < names.capacity; ++i) { if (names.data[i].value == NULL) { continue; } happiness_catalog_entry_t entry; happiness_catalog_entry_t_init(&entry); happiness_catalog_t_insert(&catalog, names.data[i].value, names.data[i].valueLength, entry); } for (size_t i = 0; i < pairs.length; ++i) { happiness_catalog_entry_t* entry; assert(happiness_catalog_t_get(&catalog, pairs.data[i].a.s, pairs.data[i].a.l, &entry) && "faulty logic"); happiness_catalog_entry_t_insert(entry, pairs.data[i].b.s, pairs.data[i].b.l, pairs.data[i].happiness); } string_vec_t names_vec; string_vec_t_init(&names_vec); for (size_t i = 0; i < names.capacity; ++i) { if (names.data[i].value == NULL) { continue; } string_vec_t_push(&names_vec, string_from_cstr(advent_strndup( names.data[i].value, names.data[i].valueLength))); } happiness_catalog_entry_t entry; happiness_catalog_entry_t_init(&entry); for (size_t i = 0; i < names_vec.length; ++i) { happiness_catalog_entry_t_insert(&entry, names_vec.data[i].s, names_vec.data[i].l, 0); } for (size_t i = 0; i < catalog.bucketCount; ++i) { if (catalog.buckets[i].key == NULL) { continue; } happiness_catalog_entry_t* entry; assert(happiness_catalog_t_get(&catalog, catalog.buckets[i].key, catalog.buckets[i].keyLen, &entry) && "faulty logic"); happiness_catalog_entry_t_insert(entry, "Me", 2, 0); } happiness_catalog_t_insert(&catalog, "Me", 2, entry); string_vec_t_push(&names_vec, string_from_cstr(advent_strdup("Me"))); permutation_t perm = first_permutation(names_vec.length); permutation_t optimal_permutation = perm; long optimal_happiness = 0; bool first = true; do { long total_happiness = 0; for (size_t i = 0; i < perm.length; ++i) { string_t name = names_vec.data[perm.data[i].index]; happiness_catalog_entry_t* entry; assert(happiness_catalog_t_get(&catalog, name.s, name.l, &entry) && "faulty logic"); string_t name2; if (i == 0) { name2 = names_vec.data[perm.data[perm.length - 1].index]; } else { name2 = names_vec.data[perm.data[i - 1].index]; } long* happiness; assert(happiness_catalog_entry_t_get(entry, name2.s, name2.l, &happiness) && "faulty logic"); total_happiness += *happiness; if (i == perm.length - 1) { name2 = names_vec.data[perm.data[0].index]; } else { name2 = names_vec.data[perm.data[i + 1].index]; } assert(happiness_catalog_entry_t_get(entry, name2.s, name2.l, &happiness) && "faulty logic"); total_happiness += *happiness; } if (first || total_happiness > optimal_happiness) { first = false; optimal_happiness = total_happiness; optimal_permutation = perm; } } while (next_permutation(&perm)); for (size_t i = 0; i < optimal_permutation.length; ++i) { string_t name = names_vec.data[optimal_permutation.data[i].index]; printf("%s%s", i == 0 ? "" : " - ", name.s); } printf(" (happiness : %ld)\n", optimal_happiness); for (size_t i = 0; i < names_vec.length; ++i) { string_free(names_vec.data[i]); } string_vec_t_deinit(&names_vec); free(line); for (size_t i = 0; i < catalog.bucketCount; ++i) { if (catalog.buckets[i].key == NULL) { continue; } happiness_catalog_entry_t_deinit(&catalog.buckets[i].value); } happiness_catalog_t_deinit(&catalog); for (size_t i = 0; i < pairs.length; ++i) { string_free(pairs.data[i].a); string_free(pairs.data[i].b); } happiness_catalog_pair_vec_t_deinit(&pairs); fclose(fp); pcre2_match_data_free(match_data); pcre2_code_free(code); return 0; }
#ifndef _GRAPHICS_H_ #define _GRAPHICS_H_ #include <math/Matrix4f.h> #include <math/Rect2i.h> #include <math/Vector2f.h> #include <math/Vector3f.h> #include <math/Vector4f.h> #include <math/Quaternion.h> #include <math/Rect2f.h> #include "Color.h" #include "SpriteFont.h" #include <assert.h> #include <string> //------------------------------------------------------------------------- // Viewport - integer rectangle class. //------------------------------------------------------------------------- struct Viewport { int x; int y; int width; int height; Viewport() {} Viewport(int x, int y, int width, int height) : x(x), y(y), width(width), height(height) {} float GetAspectRatio() const { assert(height != 0); return ((float) width / (float) height); } void Inset(int amount) { x += amount; y += amount; width -= amount * 2; height -= amount * 2; } void Inset(int left, int top, int right, int bottom) { x += left; y += top; width -= left + right; height -= top + bottom; } bool Contains(int x, int y) { return (x >= this->x && y >= this->y && x < this->x + this->width && y < this->y + this->height); } }; //------------------------------------------------------------------------- // TextAlign - bit flags for text alignment. //------------------------------------------------------------------------- struct TextAlign { enum { CENTER = 0x0, MIDDLE = 0x0, TOP = 0x1, BOTTOM = 0x2, LEFT = 0x4, RIGHT = 0x8, TOP_LEFT = TOP | LEFT, TOP_RIGHT = TOP | RIGHT, TOP_CENTER = TOP | CENTER, BOTTOM_LEFT = BOTTOM | LEFT, BOTTOM_RIGHT = BOTTOM | RIGHT, BOTTOM_CENTER = BOTTOM | CENTER, MIDDLE_LEFT = MIDDLE | LEFT, MIDDLE_RIGHT = MIDDLE | RIGHT, CENTERED = MIDDLE | CENTER, }; }; //------------------------------------------------------------------------- // Graphics - Used for drawing 2D graphics. //------------------------------------------------------------------------- class Graphics { public: Graphics(); //--------------------------------------------------------------------- // General void Clear(const Color& color); void SetupCanvas2D(int width, int height); void SetCanvasSize(int width, int height); void SetViewportToCanvas(); void SetViewport(const Rect2i& viewport, bool scissor); void SetViewport(const Viewport& viewport, bool scissor); //--------------------------------------------------------------------- // Lines void DrawLine(float x1, float y1, float x2, float y2, const Color& color); void DrawLine(const Vector2f& from, const Vector2f& to, const Color& color); //--------------------------------------------------------------------- // Rectangles void DrawRect(const Rect2f& rect, const Color& color); void DrawRect(const Viewport& rect, const Color& color); void DrawRect(const Vector2f& pos, const Vector2f& size, const Color& color); void DrawRect(float x, float y, float width, float height, const Color& color); void FillRect(const Rect2f& rect, const Color& color); void FillRect(const Viewport& rect, const Color& color); void FillRect(const Vector2f& pos, const Vector2f& size, const Color& color); void FillRect(float x, float y, float width, float height, const Color& color); //--------------------------------------------------------------------- // Circles void DrawCircle(const Vector2f& pos, float radius, const Color& color, int numEdges = 20); void FillCircle(const Vector2f& pos, float radius, const Color& color, int numEdges = 20); //--------------------------------------------------------------------- // Text void DrawString(const Font* font, const std::string& text, float x, float y, const Color& color, int align = TextAlign::TOP_LEFT); void DrawString(const Font* font, const std::string& text, const Vector2f& position, const Color& color, int align = TextAlign::TOP_LEFT); Vector2f MeasureString(const Font* font, const std::string& text); //--------------------------------------------------------------------- // Transformations void SetProjection(const Matrix4f& projection); void SetCanvasProjection(); void ResetTransform(); void SetTransform(const Matrix4f& transform); void Transform(const Matrix4f& transform); void Rotate(const Vector3f& axis, float angle); void Rotate(const Quaternion& rotation); void Translate(const Vector2f& translation); void Translate(const Vector3f& translation); void Scale(float scale); void Scale(const Vector3f& scale); void EnableCull(bool cull); void EnableDepthTest(bool depthTest); private: void gl_Vertex(const Vector2f& v); void gl_Vertex(const Vector3f& v); void gl_Color(const Color& color); int m_canvasWidth; int m_canvasHeight; }; #endif // _GRAPHICS_H_
#ifndef STRING_H #define STRING_H #include <vector> #include <string> #include <algorithm> #include <cstring> #include "default.h" using namespace std; namespace slackerz{ class str{ public: string v; str(string s){ v = s; } string upper(){ string data = v; std::for_each(data.begin(), data.end(), [](char & c){ c = ::toupper(c); }); return data; } string lower(){ string data = v; std::for_each(data.begin(), data.end(), [](char & c){ c = ::tolower(c); }); return data; } operator std::string () const { // C++ verison of __repr__ return v; } std::vector<std::string> split(string x = " "){ std::vector<std::string> so {}; string s = v; string delim = x; auto start = 0U; auto end = s.find(delim); while (end != std::string::npos) { string m = s.substr(start, end - start); so.push_back(m); start = end + delim.length(); end = s.find(delim, start); } so.push_back(s.substr(start, end)); return so; } string capitilize(){ string a = v; a[0] = toupper(a[0]); return a; } bool isupper(){ string m = v; for (int i = 0; i < m.length(); i++) { if(::isupper(m[i])){ }else{ return false; } } return true; } bool islower(){ string m = v; for (int i = 0; i < m.length(); i++) { if(::islower(m[i])){ }else{ return false; } } return true; } string convstr(){ return v; } string center(int s, string a = " "){ int spaces = s - v.length() ; spaces = spaces/2; string returnval = v; for(int i = 0; i<spaces; i++){ returnval = a + returnval; } for(int i = 0; i<spaces; i++){ returnval = returnval+a; } return returnval; } string zfill(int length){ string l = v; int zeros = length - v.length(); for(int i = 0; i< zeros; i++){ l = "0" + l; } return l; } string swapcase(){ string a = v; for(int i = 0; i < a.length(); i++){ if(::islower(a[i])){ a[i] = toupper(a[i]); }else{ a[i] = tolower(a[i]); } } return a; } bool startswith(string a, int b = 0, int c = 0){ string l = v; int x = c; if (x== 0){ x = a.length(); } for (int i = 0; i< a.length(); i++){ if (a[i+b] != l[i+b]){ return false; } } return true; } }; } #endif
Young Kids May Be Able to Unbuckle Car Seats Survey of Parents Finds Some Kids May Be Unbuckling While Car Is in Motion May 2, 2011 -- Children as young as 1 year old can unbuckle themselves from car safety seats, a new survey of parents finds. "We found that children can unbuckle from their child car safety seats by their fourth birthday, and there is an alarming 43% who do so when the car is in motion," says researcher Lilia Reyes, MD, a clinical fellow in pediatric emergency medicine at the Yale School of Medicine in New Haven. "It was reported as early as 12 months." The findings are being presented at the Pediatric Academic Societies annual meeting in Denver. Child Car Seats: How Secure? While working in the pediatric emergency room at Yale, Reyes encountered two different mothers who had minor car accidents. They told her it happened when they turned their heads around after discovering their kids had unbuckled themselves. Trying to determine how frequently it happened, she and her colleagues from Yale surveyed 378 parents of young children. Among the other findings: - 51% or about 191 families reported that at least one of their children had unbuckled their car seats. Of these, 75% were age 3 or younger. The youngest was 12 months old. - Boys unbuckled more than girls; 59% of the kids who unbuckled were boys. Parents were not asked if they were sure they had buckled correctly, Reyes tells WebMD. So there is a possibility the children weren't buckled in correctly. But parents do typically hear a click, like a seat safety belt, when the buckle latches, she says. The problem, she says, is that while children may be able to physically unbuckle the seat, they are just beginning, at around age 3, to develop reasoning skills to appreciate the consequences of unbuckling. Parents used seats of various types. They included the five-point harness, convertible seats, and booster seats, depending on their child's age and weight. Are Car Seats Really Buckled? ''This study raises questions about how the child restraint was used," says Lorrie Walker, training manager and technical advisor for Safe Kids USA, an advocacy group. "Federal motor vehicle safety standard 213 requires the buckle to release using between 9 and 14 pounds of pressure," she says. "It is often challenging for an adult to unbuckle the harness." She wonders if the buckle was not adequately locked in some cases. "A buckle may give the appearance of being buckled when it has not completely latched," she tells WebMD. Among the mistakes many parents make when placing a child in a car seat she says, is to loosely attach the harness straps or place the straps in the wrong harness slots. If these mistakes occur, she says, it makes it easy for a child to climb out. The finding that a child as young as age 1 could unbuckle the seat is a surprise to Jennifer Stockburger, program manager of vehicle and child safety for Consumer Reports. She reviewed the findings for WebMD but was not involved in the study.
#include "curly.h" #include "../stdai.h" #include "../ai.h" #include "../sym/smoke.h" #include "../../ObjManager.h" #include "../../map.h" #include "../../p_arms.h" #include "../../game.h" #include "../../player.h" #define CURLY_STAND 0 #define CURLY_WALK 3 #define CURLY_WALKING 4 INITFUNC(AIRoutines) { ONTICK(OBJ_CURLY, ai_curly); AFTERMOVE(OBJ_CURLY_CARRIED, aftermove_curly_carried); ONTICK(OBJ_CURLY_CARRIED_SHOOTING, ai_curly_carried_shooting); ONTICK(OBJ_CCS_GUN, ai_ccs_gun); } /* void c------------------------------() {} */ // regular NPC curly void ai_curly(Object *o) { switch(o->state) { case 0: // state 0: stand and do nothing o->frame = 0; o->flags |= FLAG_SCRIPTONACTIVATE; // needed for after Almond battle case 1: // important that state 1 does not change look-away frame for Drain cutscene if (o->frame != 12) o->frame = 0; o->xinertia = 0; break; case 3: // state 3: walk forward case 10: // state 10: walk to player and stop { if (o->state == 10) FACEPLAYER; o->state++; o->animtimer = 0; o->frame = 0; } case 4: case 11: { if (o->state == 11 && pdistlx(20 * CSFI)) { o->state = 0; break; } ANIMATE(5, 0, 3); if (!o->blockd) o->frame = 3; XMOVE(0x200); } break; // state 5: curly makes a "kaboom", then looks sad. case 5: o->state = 6; SmokeClouds(o, 8, 0, 0); case 6: o->frame = 16; break; case 20: // face away o->xinertia = 0; o->frame = 12; break; case 21: // look up o->xinertia = 0; o->frame = 4; break; case 30: // state 30: curly goes flying through the air and is knocked out { o->state = 31; o->frame = 14; o->timer2 = 0; o->yinertia = -0x400; XMOVE(-0x200); } case 31: { if (o->blockd && o->yinertia >= 0) o->state = 32; else break; } case 32: // state 32: curly is laying knocked out { o->frame = 15; o->xinertia = 0; } break; // walk backwards from collapsing wall during final cutscene case 70: { o->state = 71; o->timer = 0; o->frame = 1; o->animtimer = 0; } case 71: { XMOVE(-0x100); ANIMATE(8, 0, 3); } break; } o->yinertia += 0x40; LIMITY(0x5ff); } // curly being carried by Tow Rope void aftermove_curly_carried(Object *o) { switch(o->state) { case 0: { o->state = 1; o->frame = 17; o->flags &= ~FLAG_SCRIPTONACTIVATE; // turn on the HVTrigger in Waterway that kills Curly if you haven't // drained the water out of her if (game.curmap == STAGE_WATERWAY) { Object *t = FindObjectByID2(220); if (t) t->ChangeType(OBJ_HVTRIGGER); } } case 1: { // carried by player StickToPlayer(o, -2, -13, -18); } break; // floating away after Ironhead battle case 10: { o->xinertia = 0x40; o->yinertia = -0x20; o->state = 11; } case 11: { if (o->y < MAPY(4)) // if in top part of screen, reverse before hitting wall o->yinertia = 0x20; } break; case 20: { o->Delete(); } break; } } /* void c------------------------------() {} */ void ai_curly_carried_shooting(Object *o) { if (o->state == 0) { o->x = player->CenterX(); o->y = player->CenterY(); o->state = 1; o->BringToFront(); Object *gun; gun = CreateObject(0, 0, OBJ_CCS_GUN); gun->linkedobject = o; gun->PushBehind(o); } // get player center position-- // coordinates make more sense when figured this way int px = player->x + (8 * CSFI); int py = player->y + (8 * CSFI); o->dir = player->dir ^ 1; if (player->look) { o->xmark = px; if (player->look == UP) { if (player->blockd) { o->ymark = py - (12 * CSFI); o->frame = 1; } else { o->ymark = py + (8 * CSFI); o->frame = 2; } } else { // player looking down (and implicitly, not blockd) o->ymark = py - (8 * CSFI); o->frame = 1; } } else // normal/horizontal { if (player->dir == LEFT) o->xmark = px + (7 * CSFI); else o->xmark = px - (7 * CSFI); o->ymark = py - (3 * CSFI); o->frame = 0; } o->x += (o->xmark - o->x) / 2; o->y += (o->ymark - o->y) / 2; // bounce as player walks if (player->walking && (player->walkanimframe & 1)) o->y -= (1 * CSFI); } void ai_ccs_gun(Object *o) { Object *curly = o->linkedobject; if (!curly) return; o->dir = curly->dir; o->frame = curly->frame; switch(o->frame) { case 0: // horizontal/normal { if (curly->dir == RIGHT) o->x = curly->x + (8 * CSFI); else o->x = curly->x - (8 * CSFI); o->y = curly->y; } break; case 1: // looking up { o->x = curly->x; o->y = curly->y - (10 * CSFI); } break; case 2: // looking down { o->x = curly->x; o->y = curly->y + (10 * CSFI); } break; } if (pinputs[FIREKEY] != o->timer2) { o->timer2 = pinputs[FIREKEY]; if (pinputs[FIREKEY]) { if (CountObjectsOfType(OBJ_NEMESIS_SHOT_CURLY) < 2) { int shotdir = curly->dir; if (curly->frame == 1) shotdir = UP; if (curly->frame == 2) shotdir = DOWN; Object *shot = CreateObject(0, 0, OBJ_NEMESIS_SHOT_CURLY); SetupBullet(shot, curly->x, curly->y, B_CURLYS_NEMESIS, shotdir); } } } }
#include <stddef.h> // calculate the inner (dot) product of vectors Y and Y, returns the result (Sxy) double c_dot(size_t n, double *Y, double *X) { double Sxy = 0.0; for (size_t i = 0; i < n; ++i) { Sxy += X[i]*Y[i]; } return Sxy; } // calculate a simple regression, Y = a + b*X + u, puts (a,b) in vector ab, returns nothing void c_ols(size_t n, double *Y, double *X, double *ab) { double Sx = 0.0, Sy = 0.0, Sxx = 0.0, Sxy = 0.0; for (size_t i = 0; i < n; ++i) { Sx += X[i]; Sy += Y[i]; Sxx += X[i]*X[i]; Sxy += X[i]*Y[i]; } ab[1] = (Sxy-Sx*Sy/n)/(Sxx-Sx*Sx/n); //slope ab[0] = (Sy - ab[1]*Sx)/n; //intercept }
Widely known in Southeast Asia as the “king of fruits”, the Durian fruit  is distinctive for its large size, unique odour, and formidable thorn-covered husk. The fruit can grow as large as 30 centimetres long and 20 centimetres in diameter, and it typically weighs one to four kilograms. Its shape ranges from oblong to round, the colour of its husk green to brown, and its flesh pale yellow to red, depending on the species. The edible flesh emits a distinctive offensive odour, strong and penetrating even when the husk is intact but to many durian lovers, the soft flesh are tastefully pleasant. Some people regard the durian as fragrant while others find the aroma overpowering and offensive. The smell evokes reactions from deep appreciation to intense disgust, and has been described variously as almonds, rotten onions, turpentine, Limburger cheese, gym socks and stinky smell. The odour has led to the fruit’s banishment from certain hotels and public transportation in Southeast Asia. However, it is perhaps the most popular local fruit and if given choices on fruits, a Malaysian would take the durian first. Many people especially Europeans are hesitant at first to eat the fruit because of its odour, but once they do, they find it delicious and irresistible. In Malaysia durian are cultivated in orchards like farms in Pahang, Johore, Perak and Penang. Most of the peninsular states are suitable for durian cultivation especially around the hilly areas of Pahang, Perak and Johore. While durian fruit is not native to Thailand, the country has become the largest exporter of the fruit. It was introduced to Thailand during the 18th century. There are many different durian species in Thailand. Prices range from 100 Baht up to 2000 Baht. The “Mon Thong” species commands a higher price with bigger sized flesh and small pits. Species “Kadum”, “Chanee”, “Kan Yao” have bigger pits and less flesh. The durian fruit, is rich in energy, minerals and vitamins.The fruit is made of soft, easily digestible flesh with simple sugars like fructose and sucrose and some amount of simple fats when eaten replenished energy and revitalize the body instantly. Although it contains a relatively high amount of fats among fruits, but it is free from cholesterol. It is also a good source of antioxidant vitamin-C (about 33% of RDA). Consumption of foods rich in vitamin C helps body develop resistance against infectious agents and scavenge harmful free radicals. While there are many durian lovers who would be willing to pay more just to have the satisfaction of tasting the best flavoured durian in their life time, still there are people who would rather be at a distance away from the smell of it. It is just a matter of preference. Each individual taste buds and sense of smell trigger different messages to their brains. Thus, not everybody likes what you like. Some even hesitate their first try in tasting a durian but many find it irresistible and enjoyable. So, durians anyone? Just like blogging and having your own website, you will never know unless you try.
/** * @file MotionDetector_GMM2.h * @author guoqing (1337841346@qq.com) * @brief 通过自己的方式来实现的GMM * @details 也是用这种方式来实现前景检测 * @version 0.1 * @date 2019-01-08 * * @copyright Copyright (c) 2019 * */ #ifndef __MOTION_DETETCTOR_GMM_2_H__ #define __MOTION_DETETCTOR_GMM_2_H__ #include "common.h" #include "MotionDetector_DiffBase.h" using namespace std; using namespace cv; /** @brief GMM模型的最多数目,这个数值是定死的,不能够在运行时改变 */ #define GMM_MAX_COMPONT 2 //学习速率 #define DEFAULT_GMM_LEARN_ALPHA 0.005 //该学习率越大的话,学习速度太快,效果不好 //阈值 #define DEFALUT_GMM_THRESHOD_SUMW 0.7 //如果取值太大了的话,则更多部分都被检测出来了 //学习帧数 #define DEFAULT_END_FRAME 20 //几个用来加速操作的宏 #define W(index,x,y) (mmWeight[index].at<float>(x,y)) #define U(index,x,y) (mmU[index].at<unsigned char>(x,y)) #define Sigma(index,x,y) (mmSigma[index].at<float>(x,y)) #define IMG(x,y) (img.at<unsigned char>(x,y)) class MotionDetector_GMM2 : public MotionDetector_DiffBase { public: /** * @brief Construct a new MotionDetector_GMM2 object * */ MotionDetector_GMM2(); /** * @brief Destroy the MotionDetector_GMM2 object * */ ~MotionDetector_GMM2(); public: /** * @brief 使用高斯混合模型的方式来的到差分图像 * * @param[in] frame 当前时刻的帧 * @return cv::Mat 计算得到的差分图像 */ cv::Mat calcuDiffImg(cv::Mat frame); /** * @brief 重设本基类所有参数、清空所有图像缓存 * @details 清空图像缓存不是删除图片而是设置全黑的图片 */ void resetDetector(void); private: //私有函数 /** * @brief 初始化高斯模型的所有参数 * * @param img 第一帧图像 */ void gmmInit(cv::Mat img); /** * @brief 处理第一帧的函数 * * @param img 第一帧图像 */ void gmmDealFirstFrame(cv::Mat img); /** * @brief 对GMM模型进行训练的函数 * * @param img 当前帧图像 */ void gmmTrain(cv::Mat img); /** * @brief 根据当前帧确定每个像素最适合使用的高斯模型是多少个 * * @param img 当前帧图像 */ void gmmCalFitNum(cv::Mat img); /** * @brief 使用GMM来进行前景检测 * * @param img 当前帧图像 */ void gmmTest(cv::Mat img); public: //参数设置函数,现在先不写 //TODO private: private: /** * @name 高斯模型参数 * @{ */ //私有变量 /** 每个像素的每个高斯模型的权值 */ cv::Mat mmWeight[GMM_MAX_COMPONT]; /** 每个像素的每个高斯模型的均值 */ cv::Mat mmU[GMM_MAX_COMPONT]; /** 每个像素的每个高斯模型的 协方差矩阵 */ cv::Mat mmSigma[GMM_MAX_COMPONT]; /** @} */ /** * @brief 其他 * @{ */ /** 表示某个像素最实用的高斯模型的数目 */ cv::Mat mmFitNum; /** 学习率 */ float mfLearnRate; /** 判断 fitNum 时的权重累加和阈值 */ float mfThreshod; /** 学习帧数 */ int mnLearnFrameNumber; /** 当前视频帧数 */ int mnFrameCnt; /** @} */ /** 最后生成的掩摸图像 */ cv::Mat mmGMMMask; }; #endif //__MOTION_DETETCTOR_GMM_2_H__
Saltation (geology) From Wikipedia, the free encyclopedia Jump to: navigation, search Saltation of sand In geology, saltation (from Latin saltus, "leap") is a specific type of particle transport by fluids such as wind or water. It occurs when loose material is removed from a bed and carried by the fluid, before being transported back to the surface. Examples include pebble transport by rivers, sand drift over desert surfaces, soil blowing over fields, and snow drift over smooth surfaces such as those in the Arctic or Canadian Prairies. Saltation process[edit] At low fluid velocities, loose material rolls downstream, staying in contact with the surface. This is called creep or reptation. Here the forces exerted by the fluid on the particle are only enough to roll the particle around the point of contact with the surface. Once the wind speed reaches a certain critical value, termed the impact or fluid threshold,[1] the drag and lift forces exerted by the fluid are sufficient to lift some particles from the surface. These particles are accelerated by the fluid, and pulled downward by gravity, causing them to travel in roughly ballistic trajectories.[2] If a particle has obtained sufficient speed from the acceleration by the fluid, it can eject, or splash, other particles in saltation,[3] which propagates the process.[4] Depending on the surface, the particle could also disintegrate on impact, or eject much finer sediment from the surface. In air, this process of saltation bombardment creates most of the dust in dust storms.[5] In rivers, this process repeats continually, gradually eroding away the river bed, but also transporting-in fresh material from upstream. Suspension generally affects small particles ('small' means ~70 micrometres or less for particles in air[5]). For these particles, vertical drag forces due to turbulent fluctuations in the fluid are similar in magnitude to the weight of the particle. These smaller particles are carried by the fluid in suspension, and advected downstream. The smaller the particle, the less important the downward pull of gravity, and the longer the particle is likely to stay in suspension. Saltating dune sand in a wind tunnel. (Photo credit: Wind Erosion Research Unit, USDA-ARS, Manhattan, Kansas) Saltation layers can also form in avalanches. See also[edit] External links[edit] 1. ^ Bagnold, Ralph (1941). The physics of wind-blown sand and desert dunes. New York: Methuen. ISBN 0486439313. [page needed] 2. ^ Kok, Jasper; Parteli, Eric; Michaels, Timothy I; Karam, Diana Bou (2012). "The physics of wind-blown sand and dust". Reports on Progress in Physics. 75 (10): 106901. Bibcode:2012RPPh...75j6901K. PMID 22982806. doi:10.1088/0034-4885/75/10/106901.  3. ^ Rice, M. A.; Willetts, B. B.; McEwan, I. K. (1995). "An experimental study of multiple grain-size ejecta produced by collisions of saltating grains with a flat bed". Sedimentology. 42 (4): 695–706. Bibcode:1995Sedim..42..695R. doi:10.1111/j.1365-3091.1995.tb00401.x.  5. ^ a b Shao, Yaping, ed. (2008). Physics and Modelling of Wind Erosion. Heidelberg: Springer. ISBN 9781402088957. [page needed] 6. ^ Electric Sand Findings, University of Michigan Jan. 6, 2008
/* * The MIT License (MIT) * * Copyright (c) 2019 Ke Yang, Tsinghua University * * 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 <stdio.h> #include <stdlib.h> #include <fstream> #include <vector> #include <utility> #include <map> #include <set> #include <type_traits> #include <gtest/gtest.h> #include "storage.hpp" #include "graph.hpp" #include "walk.hpp" #include "util.hpp" #include "test.hpp" #include "test_walk.hpp" #include "../apps/node2vec.hpp" template<typename edge_data_t> void get_node2vec_trans_matrix(vertex_id_t v_num, Edge<edge_data_t> *edges, edge_id_t e_num, double p, double q, std::vector<std::vector<double> > &trans_mat) { std::vector<std::vector<Edge<edge_data_t> > > graph(v_num); for (edge_id_t e_i = 0; e_i < e_num; e_i++) { graph[edges[e_i].src].push_back(edges[e_i]); } for (vertex_id_t v_i = 0; v_i < v_num; v_i++) { std::sort(graph[v_i].begin(), graph[v_i].end(), [](const Edge<edge_data_t> a, const Edge<edge_data_t> b){return a.dst < b.dst;}); } for (edge_id_t e_i = 0; e_i < e_num; e_i++) { vertex_id_t src = edges[e_i].src; vertex_id_t dst = edges[e_i].dst; assert(src != dst); //must be undirected graph assert(graph[dst].size() != 0); for (auto e : graph[dst]) { if (e.dst == src) { trans_mat[e_i][e.dst] += 1 / p * get_edge_trans_weight(e); } else if (std::binary_search(graph[src].begin(), graph[src].end(), e, [](const Edge<edge_data_t> a, const Edge<edge_data_t> b){return a.dst < b.dst;})) { trans_mat[e_i][e.dst] += 1 * get_edge_trans_weight(e); } else { trans_mat[e_i][e.dst] += 1 / q * get_edge_trans_weight(e); } } } mat_normalization(trans_mat); } template<typename edge_data_t> void check_node2vec_random_walk(vertex_id_t v_num, Edge<edge_data_t> *edges, edge_id_t e_num, double p, double q, std::vector<std::vector<vertex_id_t> > rw_sequences) { std::vector<std::vector<double> > trans_mat(e_num); for (auto &vec : trans_mat) { vec.resize(v_num, 0.0); } get_node2vec_trans_matrix(v_num, edges, e_num, p, q, trans_mat); //check if sequences are legal std::vector<vertex_id_t> out_degree(v_num, 0); std::vector<std::vector<bool> > adj_mat(v_num); for (auto &vec : adj_mat) { vec.resize(v_num, false); } for (edge_id_t e_i = 0; e_i < e_num; e_i++) { adj_mat[edges[e_i].src][edges[e_i].dst] = true; out_degree[edges[e_i].src]++; } for (auto &s : rw_sequences) { if (out_degree[s[0]] == 0) { for (auto v : s) { ASSERT_EQ(v, s[0]); } } else { for (size_t v_i = 0; v_i + 1 < s.size(); v_i++) { if (adj_mat[s[v_i]][s[v_i + 1]] == false) { printf("fault %u %u\n", s[v_i], s[v_i + 1]); } ASSERT_TRUE(adj_mat[s[v_i]][s[v_i + 1]]); } } } std::map<std::pair<vertex_id_t, vertex_id_t>, edge_id_t> dict; for (edge_id_t e_i = 0; e_i < e_num; e_i++) { std::pair<vertex_id_t, vertex_id_t> key = std::pair<vertex_id_t, vertex_id_t>(edges[e_i].src, edges[e_i].dst); assert(dict.find(key) == dict.end()); dict[key] = e_i; } std::vector<std::vector<double> > real_trans_mat(e_num); for (auto &vec : real_trans_mat) { vec.resize(v_num, 0.0); } for (auto &s : rw_sequences) { if (out_degree[s[0]] != 0) { for (size_t v_i = 0; v_i + 2 < s.size(); v_i++) { real_trans_mat[dict[std::pair<vertex_id_t, vertex_id_t>(s[v_i], s[v_i + 1])]][s[v_i + 2]] += 1; } } } mat_normalization(real_trans_mat); cmp_trans_matrix(real_trans_mat, trans_mat, 10.0); } template<typename edge_data_t> void test_node2vec(vertex_id_t v_num, int worker_number) { WalkEngine<edge_data_t, Node2vecState> graph; graph.set_concurrency(worker_number); graph.load_graph(v_num, test_data_file); Node2vecConf n2v_conf; n2v_conf.walk_length = 80 + rand() % 20; n2v_conf.walker_num = graph.get_vertex_num() * 500 + graph.get_edge_num() * 100 + rand() % 100; n2v_conf.p = rand() % 4 + 1; n2v_conf.q = rand() % 4 + 1; if (rand() % 2 == 0) { n2v_conf.p = 1.0 / n2v_conf.p; } if (rand() % 2 == 0) { n2v_conf.q = 1.0 / n2v_conf.q; } MPI_Bcast(&n2v_conf, sizeof(n2v_conf), get_mpi_data_type<char>(), 0, MPI_COMM_WORLD); node2vec(&graph, n2v_conf); std::vector<std::vector<vertex_id_t> > rw_sequences; graph.collect_walk_sequence(rw_sequences); if (get_mpi_rank() == 0) { Edge<edge_data_t> *std_edges; edge_id_t std_edge_num; read_graph(test_data_file, 0, 1, std_edges, std_edge_num); check_node2vec_random_walk(v_num, std_edges, std_edge_num, n2v_conf.p, n2v_conf.q, rw_sequences); } } template<typename edge_data_t> void test_node2vec() { edge_id_t e_nums_arr[] = {100, 200, 400, 556, 888, 1000, 1200, 1500}; vertex_id_t v_num = 100 + rand() % 50; std::vector<edge_id_t> e_nums(e_nums_arr, e_nums_arr + 8); /* size_t e_nums_arr[] = {30}; vertex_id_t v_num = 10; std::vector<size_t> e_nums(e_nums_arr, e_nums_arr + 1); */ MPI_Bcast(&v_num, 1, get_mpi_data_type<vertex_id_t>(), 0, MPI_COMM_WORLD); for (auto &e_num : e_nums_arr) { if (get_mpi_rank() == 0) { gen_undirected_graph_file<edge_data_t>(v_num, e_num); } MPI_Barrier(MPI_COMM_WORLD); int worker_number = rand() % 8 + 1; MPI_Bcast(&worker_number, 1, get_mpi_data_type<int>(), 0, MPI_COMM_WORLD); test_node2vec<edge_data_t>(v_num, worker_number); } if (get_mpi_rank() == 0) { rm_test_graph_temp_file(); } } TEST(Node2vec, Unbiased) { test_node2vec<EmptyData>(); } TEST(Node2vec, Biased) { Node2vecConf n2v_conf; test_node2vec<real_t>(); } GTEST_API_ int main(int argc, char *argv[]) { MPI_Instance mpi_instance(&argc, &argv); ::testing::InitGoogleTest(&argc, argv); mute_nonroot_gtest_events(); int result = RUN_ALL_TESTS(); return result; }
#include "vex_adx_cp_server.h" int vex_adx_cp_server::find_closest_cp(uint32_t num) { int closest = 0; for (int i = 0; i < cp_; ++i) { if ((uint32_t) (MAX_BID/cp_) * i <= num) closest = i; else break; } return closest; } uint32_t vex_adx_cp_server::find_remaining(uint32_t num, int closest) { uint32_t remaining = num - (closest * (MAX_BID/cp_)); if (closest == 0) remaining++; return remaining; } void vex_adx_cp_server::init_checkpoint_vault() { for (int i = 0; i < cp_num_; ++i) { std::vector<uint8_t> seed; std::vector<uint8_t> c; // 1 checkpoint checkpoints cps; // list of checkpoints seed.resize(SEED_SIZE); c.resize(HASH_SIZE); cps.reserve(cp_); vex::setup(HASH_SIZE, g_prefix, seed.data(), c.data()); cps.push_back(seed); // idx 0 = seed for (int j = 0; j < cp_-1; ++j) { vex::gen_commit((MAX_BID / cp_), c.data(), HASH_SIZE, c.data()); cps.push_back(c); // add checkpoint to list } // add list to vault checkpoint_vault_.push_back(cps); } } void vex_adx_cp_server::process_va_req(int conn_idx, const va_req &req) { // c_req needs to include seed (potentially 1 cp) c_req creq; // Create auction context auction_context ctx; ctx.id = req.id; ctx.sig_id = req.sig_id; ctx.seed_base_idx = vault_idx_; auctions_ctx_.insert(std::pair<std::vector<uint8_t>, auction_context>(req.id, ctx)); vault_idx_+= conn_.size()-1; // increment the vault idx counter creq.id = req.id; creq.sig_id = req.sig_id; creq.url = req.url; creq.width = req.width; creq.height = req.height; creq.reserve_price = req.reserve_price; creq.cookie_version = req.cookie_version; creq.cookie_age_seconds = req.cookie_age_seconds; creq.cookie_id = req.cookie_id; creq.user_agent = req.user_agent; creq.geo_criteria_id = req.geo_criteria_id; creq.postal_code = req.postal_code; creq.timezone_offset = req.timezone_offset; creq.timestamp = req.timestamp; creq.ip = rand(); creq.seller_network_id = rand(); creq.detected_language = rand(); for (int i = 1; i < (int) conn_.size(); ++i) { creq.seed = checkpoint_vault_.at((ctx.seed_base_idx + (i-1)) % cp_num_).at(0); a_write(i, C_REQ, creq); } } bool vex_adx_cp_server::consistency_check(auction_context *ctx) { uint8_t htag[HASH_SIZE]; bool ret = 1; int seed_idx = ctx->seed_base_idx; for (int i = 1; i <= (int) ctx->vos.size(); ++i){ // Get checkpoint closest checkpoint vex_decommitment *dec = &(ctx->vds.at(i)); vex_object *com = &(ctx->vos.at(i)); HASH((uint8_t*) dec->ad_tag.c_str(), dec->ad_tag.size(), htag); int closest = find_closest_cp(MAX_BID - dec->bid); uint32_t remaining = find_remaining(MAX_BID - dec->bid, closest); std::vector<uint8_t> closest_cp = checkpoint_vault_.at(seed_idx % cp_num_).at(closest); // treat dec->sprime as if it were a salt instead of a seed. if (!vex::verify_salted_proof(remaining, com->c.data(), com->c.size(), closest_cp.data(), closest_cp.size(), dec->sprime.data(), dec->sprime.size()) || memcmp(com->htag.data(), htag, HASH_SIZE) != 0) { ctx->invalid.insert(std::pair<int, bool>(i, 1)); // 1 implies wrong ret = 0; } seed_idx++; } return ret; }
#include <bits/stdc++.h> using namespace std; template <typename T> ostream& operator<<(ostream &os, const vector<T> &v) { os << '{'; string sep; for (const auto &x : v) os << sep << x, sep = ", "; return os << '}'; } template <typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; } using i64 = long long int; const int INF = INT_MAX, MOD = 1e9 + 7; const double EPS = 1e-9, PI = acos(-1); const int dx[] = {0, 0, 0, -1, 1, -1, 1, 1, -1}; const int dy[] = {0, -1, 1, 0, 0, -1, 1, -1, 1}; /** * Author: Neeecu * Data structure: Segment Tree (min) */ template<typename T> struct min_segment_tree { vector<T> tree, lazy, arr; vector<int> now; int n; void init(int l, int r, int pos) { if (l == r) tree[pos] = arr[l]; else { int mid = l + (r - l) / 2; init(l, mid, 2 * pos + 1); init(mid + 1, r, 2 * pos + 2); tree[pos] = min(tree[2 * pos + 1], tree[2 * pos + 2]); } } min_segment_tree(vector<T> _arr) : arr(_arr), n(arr.size()) { tree.resize(4 * n); lazy.resize(4 * n, 0); init(0, n - 1, 0); } void add(int idx, T val) { _update(val, idx, idx, 0, n - 1, 0); } void add(int l, int r, T val) { _update(val, l, r, 0, n - 1, 0); } void update(int idx, T val) { _update(val - query(idx, idx), idx, idx, 0, n - 1, 0); } void _update(int val, int l, int r, int li, int ri, int pos) { if (lazy[pos] != 0) { tree[pos] += lazy[pos]; if (li != ri) { lazy[2 * pos + 1] += lazy[pos]; lazy[2 * pos + 2] += lazy[pos]; } lazy[pos] = 0; } if (ri < l or r < li) return; else if (l <= li and ri <= r) { tree[pos] = val; if (li != ri) { lazy[2 * pos + 1] += val; lazy[2 * pos + 2] += val; } } else { int mi = li + (ri - li) / 2; _update(val, l, r, li, mi, 2 * pos + 1); _update(val, l, r, mi + 1, ri, 2 * pos + 2); tree[pos] = min(tree[2 * pos + 1], tree[2 * pos + 2]); } } T query(int l, int r) { return _query(l, r, 0, n - 1, 0); } T _query(int l, int r, int li, int ri, int pos) { if (lazy[pos] != 0) { tree[pos] += lazy[pos]; if (li != ri) { lazy[2 * pos + 1] += lazy[pos]; lazy[2 * pos + 2] += lazy[pos]; } lazy[pos] = 0; } if (r < li or ri < l) return LLONG_MAX; else if (l <= li and ri <= r) return tree[pos]; else { int mi = li + (ri - li) / 2; return min(_query(l, r, li, mi, 2 * pos + 1), _query(l, r, mi + 1, ri, 2 * pos + 2)); } } pair<i64, int> query_index(int l, int r) { return _query_index(l, r, 0, n - 1, 0); } pair<i64, int> _query_index(int l, int r, int li, int ri, int pos) { if (lazy[pos] != 0) { tree[pos] += lazy[pos]; if (li != ri) { lazy[2 * pos + 1] += lazy[pos]; lazy[2 * pos + 2] += lazy[pos]; } lazy[pos] = 0; } if (r < li or ri < l) return {LLONG_MAX, INF}; else if (l <= li and ri <= r and li == ri) return {li, tree[pos]}; else { int mi = li + (ri - li) / 2; pair<i64, int> lo = _query_index(l, r, li, mi, 2 * pos + 1); pair<i64, int> hi = _query_index(l, r, mi + 1, ri, 2 * pos + 2); return ((lo.second <= hi.second) ? lo : hi); } } pair<i64, int> _query_needed(int l, int r, int conc) { if (conc == 0) return {-1, -1}; pair<i64, int> idx = query_index(l, r); pair<i64, int> i1 = _query_needed(l, idx.first - 1, conc - 1); pair<i64, int> i2 = _query_needed(idx.first + 1, r, conc - 1); now.push_back(((i1.second < i2.second and i1.second != -1) ? i1.first : i2.first)); return idx; } void query_needed(int l, int r, int conc) { int last = _query_needed(l, r, conc).first; now.push_back(last); } }; struct Task { i64 id, pw, a, b; vector<pair<i64, i64>> ans; Task(int _id, int _pw, int _a, int _b) : id(_id), pw(_pw), a(_a), b(_b) { ans.resize(0); } bool operator<(const Task& other) const { if (other.b - other.a + 1 == this->b - this->a + 1) return pw < other.pw; else return ((b - a + 1) < (other.b - other.a + 1)); } }; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); /// mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); ifstream cin("../level5_example.txt"); //ifstream cin("../level4_5.in"); ofstream cout("../answer.txt"); i64 n, m, maxPow, maxBill, maxConc, curBill = 0; cin >> maxPow >> maxBill >> maxConc; cin >> n; vector<i64> v(n), used(n, maxPow); for (int i = 0; i < n; i++) cin >> v[i]; min_segment_tree<i64> seg(v); cin >> m; vector<Task> tasks; vector<vector<pair<i64, i64>>> ans(m + 1); for (int i = 0; i < m; i++) { i64 t, pw, a, b; cin >> t >> pw >> a >> b; tasks.push_back(Task(t, pw, a, b)); } sort(tasks.begin(), tasks.end()); for (int t = 0; t < m; t++) { auto cur = tasks[t]; seg.now.clear(); i64 nowDoing = min(maxConc, cur.pw); seg.query_needed(cur.a, cur.b, nowDoing); cout << t << " " << seg.now << "\n"; /*while (cur.pw > 0) { seg.now.clear(); i64 nowDoing = min(maxConc, cur.pw); i64 idx = seg.query_index(cur.a, cur.b); i64 l = 0, r = min(cur.pw + 1, used[idx] + 1); while (l < r) { i64 mid = (l + r) >> 1; if (mid * v[idx] + curBill <= maxBill) l = mid + 1; else r = mid; } ans[cur.id].push_back({idx, l - 1}); cur.pw -= (l - 1); used[idx] -= (l - 1); curBill += (l - 1) * v[idx]; if (used[idx] == 0) seg.update(idx, INF); }*/ } /* cout << m << "\n"; for (int task = 1; task <= m; task++) { cout << task << " "; for (auto it: ans[task]) cout << it.first << " " << it.second << " "; cout << "\n"; }*/ //cout << curBill; return 0; }
Leaves of Grass/Book XXXIV From Wikisource Jump to: navigation, search My city's fit and noble name resumed, Choice aboriginal name, with marvellous beauty, meaning, A rocky founded island—shores where ever gayly dash the coming,       going, hurrying sea waves. Sea-beauty! stretch'd and basking!       steamers, sails, And one the Atlantic's wind caressing, fierce or gentle—mighty hulls       dark-gliding in the distance. Isle of the salty shore and breeze and brine! From Montauk Point[edit] I stand as on some mighty eagle's beak, The wild unrest, the snowy, curling caps—that inbound urge and urge       of waves, Seeking the shores forever. To Those Who've Fail'd[edit] To those who've fail'd, in aspiration vast, To unnam'd soldiers fallen in front on the lead,       their ships, To many a lofty song and picture without recognition—I'd rear       laurel-cover'd monument, Possess'd by some strange spirit of fire, Quench'd by an early death. A Carol Closing Sixty-Nine[edit] A carol closing sixty-nine—a resume—a repetition, My lines in joy and hope continuing on the same, Of you, my Land—your rivers, prairies, States—you, mottled Flag I love, Your aggregate retain'd entire—Of north, south, east and west, your       items all; Of me myself—the jocund heart yet beating in my breast, The body wreck'd, old, poor and paralyzed—the strange inertia       falling pall-like round me, The burning fires down in my sluggish blood not yet extinct, The undiminish'd faith—the groups of loving friends. The Bravest Soldiers[edit]       the fight; A Font of Type[edit] This latent mine—these unlaunch'd voices—passionate powers, These ocean waves arousable to fury and to death, Or sooth'd to ease and sheeny sun and sleep, Within the pallid slivers slumbering. As I Sit Writing Here[edit] As I sit writing here, sick and grown old, Ungracious glooms, aches, lethargy, constipation, whimpering ennui, May filter in my dally songs. My Canary Bird[edit] Absorbing deep and full from thoughts, plays, speculations? Filling the air, the lonesome room, the long forenoon, Is it not just as great, O soul? Queries to My Seventieth Year[edit] Approaching, nearing, curious, Thou dim, uncertain spectre—bringest thou life or death? Strength, weakness, blindness, more paralysis and heavier? Or placid skies and sun? Wilt stir the waters yet? The Wallabout Martyrs[edit] Greater than memory of Achilles or Ulysses, More, more by far to thee than tomb of Alexander, Once living men—once resolute courage, aspiration, strength, The First Dandelion[edit] Simple and fresh and fair from winter's close emerging, Forth from its sunny nook of shelter'd grass—innocent, golden, calm       as the dawn, The spring's first dandelion shows its trustful face. Centre of equal daughters, equal sons, Strong, ample, fair, enduring, capable, rich, Perennial with the Earth, with Freedom, Law and Love, A grand, sane, towering, seated Mother, Chair'd in the adamant of Time. How sweet the silent backward tracings! The wanderings as in dreams—the meditation of old times resumed       —their loves, joys, persons, voyages. To-Day and Thee[edit] The appointed winners in a long-stretch'd game; The course of Time and nations—Egypt, India, Greece and Rome; Garner'd for now and thee—To think of it! The heirdom all converged in thee! After the Dazzle of Day[edit] After the dazzle of day is gone, Silent, athwart my soul, moves the symphony true. Abraham Lincoln, Born Feb. 12, 1809[edit] To memory of Him—to birth of Him. Out of May's Shows Selected[edit] Apple orchards, the trees all cover'd with blossoms; Wheat fields carpeted far and near in vital emerald green; The eternal, exhaustless freshness of each early morning; The aspiring lilac bushes with profuse purple or white flowers. Halcyon Days[edit] Not from successful love alone, But as life wanes, and all the turbulent passions calm, As gorgeous, vapory, silent hues cover the evening sky,       really finish'd and indolent-ripe on the tree, Then for the teeming quietest, happiest days of all! The brooding and blissful halcyon days! Fancies at Navesink[edit] [I] The Pilot in the Mist[edit] Here waiting for the sunrise, gazing from this hill;) Again 'tis just at morning—a heavy haze contends with daybreak, Again the trembling, laboring vessel veers me—I press through       foam-dash'd rocks that almost touch me, Again I mark where aft the small thin Indian helmsman Looms in the mist, with brow elate and governing hand. [II] Had I The Choice[edit] Had I the choice to tally greatest bards, Or Shakspere's woe-entangled Hamlet, Lear, Othello—Tennyson's fair ladies,       delight of singers; Or breathe one breath of yours upon my verse, And leave its odor there. [III] You Tides with Ceaseless Swell[edit] You unseen force, centripetal, centrifugal, through space's spread,       what Capella's?       aggregate of all?       you? what fluid, vast identity, [IV] Last of Ebb, and Daylight Waning[edit] Last of ebb, and daylight waning, Many a muffled confession—many a sob and whisper'd word, As of speakers far or hid. How they sweep down and out! how they mutter! Poets unnamed—artists greatest of any, with cherish'd lost designs, Love's unresponse—a chorus of age's complaints—hope's last words, Some suicide's despairing cry, Away to the boundless waste, and       never again return. On to oblivion then! On for your time, ye furious debouche! [V] And Yet Not You Alone[edit] And yet not you alone, twilight and burying ebb, I know, divine deceitful ones, your glamour's seeming; Duly the needed discord-parts offsetting, blending, Weaving from you, from Sleep, Night, Death itself, The rhythmus of Birth eternal. [VI] Proudly the Flood Comes In[edit] Proudly the flood comes in, shouting, foaming, advancing, Long it holds at the high, with bosom broad outswelling, Mainsails, topsails, jibs, appear in the offing—steamers' pennants       of smoke—and under the forenoon sun, Freighted with human lives, gaily the outward bound, gaily the       inward bound, Flaunting from many a spar the flag I love. [VII] By That Long Scan of Waves[edit] In every crest some undulating light or shade—some retrospect, Joys, travels, studies, silent panoramas—scenes ephemeral, And haply yet some drop within God's scheme's ensemble—some       wave, or part of wave, Like one of yours, ye multitudinous ocean. [VIII] Then Last Of All[edit] Of you O tides, the mystic human meaning: The brain that shapes, the voice that chants this song. Election Day, November, 1884[edit]       your huge rifts of canyons, Colorado, Nor you, Yosemite—nor Yellowstone, with all its spasmic       geyser-loops ascending to the skies, appearing and disappearing,       Mississippi's stream:       small voice vibrating—America's choosing day,       quadriennial choosing,) The countless snow-flakes falling—(a swordless conflict,       peaceful choice of all,       pants, life glows: These stormy gusts and winds waft precious ships, Swell'd Washington's, Jefferson's, Lincoln's sails. With Husky-Haughty Lips, O Sea![edit] With husky-haughty lips, O sea! Where day and night I wend thy surf-beat shore, Imaging to my sense thy varied strange suggestions, Thy troops of white-maned racers racing to the goal, Thy brooding scowl and murk—thy unloos'd hurricanes, Thy unsubduedness, caprices, wilfulness; Great as thou art above the rest, thy many tears—a lack from all       eternity in thy content,       greatest—no less could make thee,) Thy lonely state—something thou ever seek'st and seek'st, yet       never gain'st, Surely some right withheld—some voice, in huge monotonous rage, of       freedom-lover pent, By lengthen'd swell, and spasm, and panting breath, And rhythmic rasping of thy sands and waves, And serpent hiss, and savage peals of laughter, And undertones of distant lion roar, (Sounding, appealing to the sky's deaf ear—but now, rapport for once, A phantom in the night thy confidant for once,) The first and last confession of the globe, Outsurging, muttering from thy soul's abysms, The tale of cosmic elemental passion, Thou tellest to a kindred soul. Death of General Grant[edit] As one by one withdraw the lofty actors, From that great play on history's stage eterne, Man of the mighty days—and equal to the days! To admiration has it been enacted! Red Jacket (From Aloft)[edit] Upon this scene, this show, Yielded to-day by fashion, learning, wealth,       smile curving its phantom lips, Like one of Ossian's ghosts looks down. Washington's Monument February, 1885[edit] Ah, not this marble, dead and cold:       yours alone, America, Old Asia's there with venerable smile, seated amid her ruins;       legitimate, continued ever,       defeated not, the same:) Wherever Freedom, pois'd by Toleration, sway'd by Law, Stands or is rising thy true monument. Of That Blithe Throat of Thine[edit] Of that blithe throat of thine from arctic bleak and blank, I'll mind the lesson, solitary bird—let me too welcome chilling drifts, E'en the profoundest chill, as now—a torpid pulse, a brain unnerv'd, Old age land-lock'd within its winter bay—(cold, cold, O cold!) These snowy hairs, my feeble arm, my frozen feet, Not summer's zones alone—not chants of youth, or south's warm tides alone,       of years, These with gay heart I also sing. What hurrying human tides, or day or night! What whirls of evil, bliss and sorrow, stem thee! What curious questioning glances—glints of love! Leer, envy, scorn, contempt, hope, aspiration! Thou portal—thou arena—thou of the myriad long-drawn lines and groups! Thy windows rich, and huge hotels—thy side-walks wide;) Thou of the endless sliding, mincing, shuffling feet!       mocking life! Thou visor'd, vast, unspeakable show and lesson! To Get the Final Lilt of Songs[edit] To get the final lilt of songs, To penetrate the inmost lore of poets—to know the mighty ones, To diagnose the shifting-delicate tints of love and pride and doubt—       to truly understand, Old Salt Kossabone[edit] Far back, related on my mother's side, Old Salt Kossabone, I'll tell you how he died: (Had been a sailor all his life—was nearly 90—lived with his       married grandchild, Jenny;       stretch to open sea;)       regular custom, In his great arm chair by the window seated, (Sometimes, indeed, through half the day,) Watching the coming, going of the vessels, he mutters to himself—       And now the close of all: One struggling outbound brig, one day, baffled for long—cross-tides       and much wrong going, And swiftly bending round the cape, the darkness proudly entering,       cleaving, as he watches, "She's free—she's on her destination"—these the last words—when       Jenny came, he sat there dead, The Dead Tenor[edit] As down the stage again, With Spanish hat and plumes, and gait inimitable,       and test of all:) How through those strains distill'd—how the rapt ears, the soul of       me, absorbing Fernando's heart, Manrico's passionate call, Ernani's, sweet Gennaro's, Freedom's and Love's and Faith's unloos'd cantabile, (As perfume's, color's, sunlight's correlation:) To memory of thee. Nothing is ever really lost, or can be lost, Nor life, nor force, nor any visible thing; Appearance must not foil, nor shifted sphere confuse thy brain. Ample are time and space—ample the fields of Nature. To frozen clods ever the spring's invisible law returns, With grass and flowers and summer fruits and corn. A song, a poem of itself—the word itself a dirge, To me such misty, strange tableaux the syllables calling up; Yonnondio—I see, far in the west or north, a limitless ravine, with       plains and mountains dark, Yonnondio! Yonnondio!—unlimn'd they disappear; To-day gives place, and fades—the cities, farms, factories fade;       for a moment, Then blank and gone and still, and utterly lost. Ever the undiscouraged, resolute, struggling soul of man; (Have former armies fail'd? then we send fresh armies—and fresh again;) Ever the grappled mystery of all earth's ages old or new; Ever the soul dissatisfied, curious, unconvinced at last; Struggling to-day the same—battling the same. "Going Somewhere"[edit] My science-friend, my noblest woman-friend, (Now buried in an English grave—and this a memory-leaf for her dear sake,) Ended our talk—"The sum, concluding all we know of old or modern       learning, intuitions deep, "Of all Geologies—Histories—of all Astronomy—of Evolution,       Metaphysics all,       duly over,) "The world, the race, the soul—in space and time the universes, "All bound as is befitting each—all surely going somewhere." Small the Theme of My Chant[edit]       modern, the word En-Masse.       link'd together let us go.) True Conquerors[edit] Enough that they've survived at all—long life's unflinching ones! Forth from their struggles, trials, fights, to have emerged at all—       in that alone, True conquerors o'er all the rest. The United States to Old World Critics[edit] Wealth, order, travel, shelter, products, plenty; The solid-planted spires tall shooting to the stars. The Calming Thought of All[edit] That coursing on, whate'er men's speculations, Amid the changing schools, theologies, philosophies, Amid the bawling presentations new and old, The round earth's silent vital laws, facts, modes continue. Thanks in Old Age[edit] Thanks in old age—thanks ere I go, For health, the midday sun, the impalpable air—for life, mere life, For precious ever-lingering memories, (of you my mother dear—you,       father—you, brothers, sisters, friends,) For all my days—not those of peace alone—the days of war the same, For gentle words, caresses, gifts from foreign lands, For shelter, wine and meat—for sweet appreciation, (You distant, dim unknown—or young or old—countless, unspecified,       readers belov'd, We never met, and neer shall meet—and yet our souls embrace, long,       close and long;) For beings, groups, love, deeds, words, books—for colors, forms, For all the brave strong men—devoted, hardy men—who've forward       sprung in freedom's help, all years, all lands For braver, stronger, more devoted men—(a special laurel ere I go,       to life's war's chosen ones, The cannoneers of song and thought—the great artillerists—the       foremost leaders, captains of the soul:) As soldier from an ended war return'd—As traveler out of myriads,       to the long procession retrospective, Thanks—joyful thanks!—a soldier's, traveler's thanks. Life and Death[edit] The two old, simple problems ever intertwined, Close home, elusive, present, baffled, grappled. By each successive age insoluble, pass'd on, To ours to-day—and we pass on the same. The Voice of the Rain[edit]       yet the same,       and make pure and beautify it; Reck'd or unreck'd, duly with love returns.) Soon Shall the Winter's Foil Be Here[edit] Soon shall the winter's foil be here; Soon shall these icy ligatures unbind and melt—A little while,       growth—a thousand forms shall rise From these dead clods and chills as from low burial graves. Thine eyes, ears—all thy best attributes—all that takes cognizance       of natural beauty,       delicate miracles of earth,       plum and cherry; With these the robin, lark and thrush, singing their songs—the       flitting bluebird; For such the scenes the annual play brings on. While Not the Past Forgetting[edit] While not the past forgetting, To-day, at least, contention sunk entire—peace, brotherhood uprisen; For sign reciprocal our Northern, Southern hands, (Nor for the past alone—for meanings to the future,) Wreaths of roses and branches of palm. The Dying Veteran[edit] Amid these days of order, ease, prosperity, Amid the current songs of beauty, peace, decorum, I cast a reminiscence—(likely 'twill offend you, I heard it in my boyhood;)—More than a generation since, A queer old savage man, a fighter under Washington himself, Had fought in the ranks—fought well—had been all through the       Revolutionary war,) Lay dying—sons, daughters, church-deacons, lovingly tending him, "Let me return again to my war-days, To the sights and scenes—to forming the line of battle, To the scouts ahead reconnoitering, To the cannons, the grim artillery, To the galloping aides, carrying orders, The perfume strong, the smoke, the deafening noise; Away with your life of peace!—your joys of peace! Give me my old wild battle-life again!" Stronger Lessons[edit]       tender with you, and stood aside for you?       brace themselves against you? or who treat you with contempt,       or dispute the passage with you? A Prairie Sunset[edit] The earth's whole amplitude and Nature's multiform power consign'd       for once to colors;       North, South, all, Pure luminous color fighting the silent shadows to the last. Twenty Years[edit]       vehement notion;) Since, twenty years and more have circled round and round, Dress'd in its russet suit of good Scotch cloth: Orange Buds by Mail from Florida[edit] A lesser proof than old Voltaire's, yet greater, To my plain Northern hut, in outside clouds and snow, Brought safely for a thousand miles o'er land and tide, Some three days since on their own soil live-sprouting, Now here their sweetness through my room unfolding, A bunch of orange buds by mall from Florida. The soft voluptuous opiate shades, The sun just gone, the eager light dispell'd—(I too will soon be       gone, dispell'd,) A haze—nirwana—rest and night—oblivion. You Lingering Sparse Leaves of Me[edit] You lingering sparse leaves of me on winter-nearing boughs, You tokens diminute and lorn—(not now the flush of May, or July       clover-bloom—no grain of August now;) You pallid banner-staves—you pennants valueless—you overstay'd of time, Yet my soul-dearest leaves confirming all the rest, The faithfulest—hardiest—last. Not Meagre, Latent Boughs Alone[edit]       eagles' talons,)       summer—bursting forth, To verdant leaves, or sheltering shade—to nourishing fruit, Apples and grapes—the stalwart limbs of trees emerging—the fresh,       free, open air, And love and faith, like scented roses blooming. The Dead Emperor[edit] Mourning a good old man—a faithful shepherd, patriot. As the Greek's Signal Flame[edit] As the Greek's signal flame, by antique records told, Rose from the hill-top, like applause and glory, Welcoming in fame some special veteran, hero, With rosy tinge reddening the land he'd served, So I aloft from Mannahatta's ship-fringed shore, Lift high a kindled brand for thee, Old Poet. The Dismantled Ship[edit] In some unused lagoon, some nameless bay, On sluggish, lonesome waters, anchor'd near the shore,       hawser'd tight, Lies rusting, mouldering. Now Precedent Songs, Farewell[edit] Now precedent songs, farewell—by every name farewell, Or Paumanok, Song of Myself, Calamus, or Adam, From fibre heart of mine—from throat and tongue—(My life's hot       pulsing blood,       and ink,)       indeed to that! What wretched shred e'en at the best of all!) An Evening Lull[edit] After a week of physical anguish, Unrest and pain, and feverish heat, Toward the ending day a calm and lull comes on, Three hours of peace and soothing rest of brain. Old Age's Lambent Peaks[edit] Objects and groups, bearings, faces, reminiscences; The calmer sight—the golden setting, clear and broad:       we scan, Bro't out by them alone—so much (perhaps the best) unreck'd before; The lights indeed from them—old age's lambent peaks. After the Supper and Talk[edit] After the supper and talk—after the day is done, As a friend from friends his final withdrawal prolonging, Good-bye and Good-bye with emotional lips repeating, (So hard for his hand to release those hands—no more will they meet, Shunning, postponing severance—seeking to ward off the last word       ever so little,       e'en as he descends the steps, Farewells, messages lessening—dimmer the forthgoer's visage and form, Garrulous to the very last.
#include "DlgComapreEngine.h" #include "ui_GetPtarrenFileInfo.h" #include "CompareEngineThread.h" #include "QCompareEngineModel.h" //------------------------------------------------------------------------------------------------- DlgComapreEngine::DlgComapreEngine(QDialog *parent , QSqlDatabase &i_qSqlDatabase ,JString &Path ,JString &strDatFile):QDialog (parent) ,ui (new Ui::DlgGetPatternFileInfo) { ui->setupUi(this); m_posQCompareEngineModel = new QCompareEngineModel(this); ui->TblFileInfo->setModel(m_posQCompareEngineModel); m_pCompareEngineThread = new CompareEngineThread (i_qSqlDatabase , Path , strDatFile); connect(m_pCompareEngineThread , SIGNAL(Report( QString , QString ,QString )) , this , SLOT (GetReport( QString , QString ,QString ))); m_pCompareEngineThread->start(); } //------------------------------------------------------------------------------------------------- DlgComapreEngine::~DlgComapreEngine(void) { } //------------------------------------------------------------------------------------------------- void DlgComapreEngine::GetReport(QString FileName , QString SetNamedat ,QString SetNameDb) { m_posQCompareEngineModel->insertRows(ui->TblFileInfo->model()->rowCount(),1,QModelIndex()); m_posQCompareEngineModel->setData(m_posQCompareEngineModel->index(ui->TblFileInfo->model()->rowCount()-1,0) ,FileName); m_posQCompareEngineModel->setData(m_posQCompareEngineModel->index(ui->TblFileInfo->model()->rowCount()-1,1) ,SetNamedat); m_posQCompareEngineModel->setData(m_posQCompareEngineModel->index(ui->TblFileInfo->model()->rowCount()-1,2) ,SetNameDb); } //-------------------------------------------------------------------------------------------------
/************************************************* * * GOMP Implementation for multiple measurement vectors * *************************************************/ #include <mex.h> #include <math.h> #include "omp.h" #include "omp_profile.h" #include "spxblas.h" #include "spxalg.h" #include "spxla.h" #include "argcheck.h" #define MAX_M 4096 mxArray* gomp_mmv_chol(const double m_dict[], const double m_x[], mwSize M, mwSize N, mwSize S, mwSize K, mwSize L, mwSize T, double res_norm_bnd, int sparse_output, int verbose){ // List of indices of selected atoms mwIndex *selected_atoms = 0; // Atom indices needed during selection mwIndex* atom_indices = 0; // Storage for the Cholesky decomposition of D_I' D_I double *m_lt = 0; // The submatrix of selected atoms double* m_subdict = 0; // The proxy D' x double* m_proxy = 0; // The inner product of residual with atoms H = D' * R double* m_h = 0; // Absolute sum of inner products in each column double* v_h = 0; // The residual double* m_r = 0; // b = D_I' d_k in the Cholesky decomposition updates double* v_b = 0; // New vector in the Cholesky decomposition updates double* v_w = 0; // Result of orthogonal projection LL' c = p_I double* m_c = 0; // Pointer to new atom const double* wv_new_atom; // residual norm squared double res_norm_sqr = 1; // square of upper bound on residual norm double res_norm_bnd_sqr = SQR(res_norm_bnd); // Expected sparsity of signal mwSize sparsity = K; /// Output array mxArray* p_alpha; double* m_alpha; // row indices for non-zero entries in Alpha mwIndex *ir_alpha; // indices for first non-zero entry in column mwIndex *jc_alpha; /// Index for non-zero entries in alpha mwIndex nz_index; // counters int i, j , k, s; // index of new atom mwIndex new_atom_index; // Maximum number of columns to be used in representations mwSize max_atoms; if(verbose > 1){ mexPrintf("M: %d, N:%d, S: %d, K: %d, L: %d, T: %d, eps: %e, sparse: %d, verbose: %d\n", M, N, S, K, L, T, res_norm_bnd, sparse_output, verbose); } // structure for tracking time spent. omp_profile profile; // K is now the iteration count. // If it is larger than acceptable, we will cut it down here. if (K < 0 || K * L > M) { // K cannot be greater than M / L. K = M / L; } max_atoms = K*L; // Memory allocations // Number of selected atoms cannot exceed M selected_atoms = (mwIndex*) mxMalloc(M*sizeof(mwIndex)); // Total number of atoms is N atom_indices = (mwIndex*) mxMalloc(N*sizeof(mwIndex)); // Number of rows and columns in L cannot exceed max_atoms. // We still allocate M elements per column as // this is what the chol update function assumes m_lt = (double*) mxMalloc(M*max_atoms*sizeof (double)); // Number of entries in new line for L cannot exceed N. v_b = (double*)mxMalloc(N*sizeof(double)); v_w = (double*)mxMalloc(N*sizeof(double)); // h is in R^N. We need to store it separately for each vector in MMV set m_h = (double*)mxMalloc(T*N*sizeof(double)); v_h = (double*)mxMalloc(N*sizeof(double)); // Residual is in signal space R^M. We need to store it separately for each vector in MMV set m_r = (double*)mxMalloc(T*M*sizeof(double)); // The non-zero approximation coefficients. We need to store it separately for each vector in MMV set m_c = (double*)mxMalloc(T*M*sizeof(double)); // Proxy vector is in R^N. We need to store it separately for each vector in MMV set m_proxy = (double*)mxMalloc(T*N*sizeof(double)); // Keeping max_atoms space for subdictionary. m_subdict = (double*)mxMalloc(max_atoms*M*sizeof(double)); // Allocation of space for the result vector if (sparse_output == 0){ p_alpha = mxCreateDoubleMatrix(N, S, mxREAL); m_alpha = mxGetPr(p_alpha); ir_alpha = 0; jc_alpha = 0; }else{ p_alpha = mxCreateSparse(N, S, max_atoms*S, mxREAL); m_alpha = mxGetPr(p_alpha); ir_alpha = mxGetIr(p_alpha); jc_alpha = mxGetJc(p_alpha); nz_index = 0; jc_alpha[0] = 0; } if (M > MAX_M){ error_msg("gomp_mmv", "Too large M."); return p_alpha; } omp_profile_init(&profile); // We process one MMV set in each iteration. // Each MMV set contains at most T vectors // All except last set contain T vectors // Last set may contain less vectors // s indicates the index of first vector in the MMV set for(s=0; s<S; s+= T){ // Pointer to current MMV set const double *wm_x = m_x + M*s; int dummy; // Counter for selected atoms int kk = 0; // Number of atoms in next MMV set mwSize tt = T; if (S -s < T){ tt = S - s; } if (verbose > 1){ mexPrintf("Processing %d vectors \n", tt); } // Initialization if (res_norm_bnd_sqr > 0){ // Cool trick to compute Frobenius norm of residual res_norm_sqr = inner_product(wm_x, wm_x, M*tt); } //Compute proxy P = D' * X for the MMV set mult_mat_t_mat(1, m_dict, wm_x, m_proxy, N, tt, M); omp_profile_toctic(&profile, TIME_DtR); // h = p = D' * r copy_vec_vec(m_proxy, m_h, N*tt); // Iteration counter for selecting bunch of atoms in each iteration. k = 0; // In each iteration we select up to L atoms while (k < K && res_norm_sqr > res_norm_bnd_sqr){ // Number of atoms added during this cycle. int added_atoms = 0; if (verbose > 1){ mexPrintf("k: %d :: ", k+1); } omp_profile_tic(&profile); // Sum of absolute correlations in each row (i.e. for all vectors in MMV set) mat_row_asum(m_h, v_h, N, tt); // Remove the entries for already selected atoms for(i=0; i < kk; ++i){ v_h[selected_atoms[i]] = 0; } //Assign atom indices for (i=0; i<N; ++i){ // Assign indices to atoms atom_indices[i] = i; } // Search for L largest atoms quickselect_desc(v_h, atom_indices, N, L); omp_profile_toctic(&profile, TIME_MaxAbs); // Store the indices and update Cholesky decomposition for (i=0; i < L; ++i){ if (v_h[i] < 1e-6*tt){ // The contribution of atom is too small to consider continue; } new_atom_index = atom_indices[i]; selected_atoms[kk] = new_atom_index; // One more atom was added ++added_atoms; // Copy the new atom to the sub-dictionary wv_new_atom = m_dict + new_atom_index*M; copy_vec_vec(wv_new_atom, m_subdict+kk*M, M); if (verbose > 1){ mexPrintf("%d ", new_atom_index+1); } // Cholesky update if (kk == 0){ // Simply initialize the L matrix *m_lt = 1; }else{ wv_new_atom = m_subdict+kk*M; // Incremental Cholesky decomposition if (chol_update(m_subdict, wv_new_atom, m_lt, v_b, v_w, M, kk) != 0){ // We will ignore this atom // as it is linearly dependent on previous atoms continue; } } ++kk; } if(0 == added_atoms){ if (verbose > 1){ mexPrintf("No new atoms were added. Stopping.\n"); break; } } omp_profile_toctic(&profile, TIME_LCholUpdate); // We can increase the iteration count ++k; // We will now solve the equation L L' alpha_I = p_I mat_row_extract(m_proxy, selected_atoms, m_c, N, tt, kk); spd_lt_trtrs_multi(m_lt, m_c, M, kk, tt); if (verbose > 2){ print_matrix(m_c, kk, tt, "c"); } omp_profile_toctic(&profile, TIME_LLtSolve); // Compute residual // r = x - D_I c mult_mat_mat(-1, m_subdict, m_c, m_r, M, tt, kk); sum_vec_vec(1, wm_x, m_r, M*tt); omp_profile_toctic(&profile, TIME_RUpdate); // Update h = D' r mult_mat_t_mat(1, m_dict, m_r, m_h, N, tt, M); if (res_norm_bnd_sqr > 0){ // Update residual norm squared res_norm_sqr = inner_product(m_r, m_r, M*tt); if(verbose > 1){ mexPrintf(" \\| r \\|_2^2 : %.4f.\n", res_norm_sqr); } }else{ if (verbose > 1){ mexPrintf("\n"); } } omp_profile_toctic(&profile, TIME_DtR); } // Write the output vector if(sparse_output == 0){ // Iterate over MMV set for (int j=0; j < tt; ++j){ double* wv_alpha = m_alpha + N*(s + j); double* wv_c = m_c + kk*j; // Write the output vector fill_vec_sparse_vals(wv_c, selected_atoms, wv_alpha, N, kk); } } else{ // First sort the indices mwIndex indices1[MAX_M]; double indices2[MAX_M]; for (int j=0; j < kk; ++j){ indices2[j] = j; } // Sort the row indices quicksort_indices(selected_atoms, indices2, kk); for (int j=0; j < kk; ++j){ indices1[j] = (mwIndex) indices2[j]; } // Iterate over MMV set for(int i=0; i < tt; ++i){ // Coefficients for current vector in MMV set double* wv_c = m_c + kk*i; // add the non-zero entries for this column for(j=0; j <kk; ++j){ m_alpha[nz_index] = wv_c[indices1[j]]; ir_alpha[nz_index] = selected_atoms[j]; ++nz_index; } // fill in the total number of nonzero entries in the end. jc_alpha[s+i+1] = jc_alpha[s+i] + kk; } } } if(verbose){ omp_profile_print(&profile); } if (sparse_output && verbose > 2){ mexPrintf("nnz : %d\n", nz_index); // print_index_vector(jc_alpha, S, "jc_alpha"); // print_vector(m_alpha, nz_index, "pr_alpha"); } // Memory cleanup mxFree(selected_atoms); mxFree(atom_indices); mxFree(m_lt); mxFree(v_b); mxFree(v_w); mxFree(m_c); mxFree(m_subdict); mxFree(m_proxy); mxFree(m_h); mxFree(v_h); mxFree(m_r); // Return the result return p_alpha; }
// Copyright © 1996-2018, Valve Corporation, All rights reserved. // // Purpose: Client side CTFTeam class #ifndef PARTICLE_ITERATORS_H #define PARTICLE_ITERATORS_H #include "materialsystem/imesh.h" #include "particledraw.h" #define NUM_PARTICLES_PER_BATCH 200 #define MAX_TOTAL_PARTICLES 4096 // Max particles in the world // // Iterate the particles like this: // // Particle *pCur = pIterator->GetFirst(); // while ( pCur ) // { // ... render the particle here and figure out the sort key and position // pCur = pIterator->GetNext( sortKey, pCur->m_Pos ); // } // class CParticleRenderIterator { friend class CParticleMgr; friend class CParticleEffectBinding; public: CParticleRenderIterator(); // The sort key is used to sort the particles incrementally as they're // rendered. They only get sorted in the main rendered view (ie: not in // reflections or monitors). These return const because you should only modify // particles during their simulation. const Particle *GetFirst(); const Particle *GetNext(float sortKey); // Use this to render. This can return NULL, in which case you shouldn't // render. This being NULL is a carryover from when particles rendered and // simulated together and it should GO AWAY SOON! ParticleDraw *GetParticleDraw() const; private: void TestFlushBatch(); private: // Set by CParticleMgr. CParticleEffectBinding *m_pEffectBinding; CEffectMaterial *m_pMaterial; ParticleDraw *m_pParticleDraw; CMeshBuilder *m_pMeshBuilder; IMesh *m_pMesh; bool m_bBucketSort; // Output after rendering. float m_MinZ; float m_MaxZ; float m_zCoords[MAX_TOTAL_PARTICLES]; int m_nZCoords; Particle *m_pCur; bool m_bGotFirst; float m_flPrevZ; int m_nParticlesInCurrentBatch; }; // // Iterate the particles like this: // // Particle *pCur = pIterator->GetFirst(); // while ( pCur ) // { // ... simulate here.. call pIterator->RemoveParticle if you want the // particle to go away pCur = pIterator->GetNext(); // } // class CParticleSimulateIterator { friend class CParticleMgr; friend class CParticleEffectBinding; public: CParticleSimulateIterator(); // Iterate through the particles, simulate them, and remove them if necessary. Particle *GetFirst(); Particle *GetNext(); float GetTimeDelta() const; void RemoveParticle(Particle *pParticle); void RemoveAllParticles(); private: CParticleEffectBinding *m_pEffectBinding; CEffectMaterial *m_pMaterial; float m_flTimeDelta; bool m_bGotFirst; Particle *m_pNextParticle; }; // -------------------------------------------------------------------------------------------------------- // // CParticleRenderIterator inlines // -------------------------------------------------------------------------------------------------------- // // inline CParticleRenderIterator::CParticleRenderIterator() { m_pCur = NULL; m_bGotFirst = false; m_flPrevZ = 0; m_nParticlesInCurrentBatch = 0; m_MinZ = 1e24f; m_MaxZ = -1e24f; m_nZCoords = 0; } inline const Particle *CParticleRenderIterator::GetFirst() { Assert(!m_bGotFirst); m_bGotFirst = true; m_pCur = m_pMaterial->m_Particles.m_pNext; if (m_pCur == &m_pMaterial->m_Particles) return NULL; m_pParticleDraw->m_pSubTexture = m_pCur->m_pSubTexture; return m_pCur; } inline void CParticleRenderIterator::TestFlushBatch() { ++m_nParticlesInCurrentBatch; if (m_nParticlesInCurrentBatch >= NUM_PARTICLES_PER_BATCH) { m_pMeshBuilder->End(false, true); m_pMeshBuilder->Begin(m_pMesh, MATERIAL_QUADS, NUM_PARTICLES_PER_BATCH * 4); m_nParticlesInCurrentBatch = 0; } } inline const Particle *CParticleRenderIterator::GetNext(float sortKey) { Assert(m_bGotFirst); Assert(m_pCur); TestFlushBatch(); Particle *pNext = m_pCur->m_pNext; // Update the incremental sort. if (m_bBucketSort) { m_MinZ = std::min(sortKey, m_MinZ); m_MaxZ = std::max(sortKey, m_MaxZ); m_zCoords[m_nZCoords] = sortKey; ++m_nZCoords; } else { // Swap with the previous particle (incremental sort)? if (m_pCur != m_pMaterial->m_Particles.m_pNext && m_flPrevZ > sortKey) { SwapParticles(m_pCur->m_pPrev, m_pCur); } else { m_flPrevZ = sortKey; } } m_pCur = pNext; if (m_pCur == &m_pMaterial->m_Particles) return NULL; m_pParticleDraw->m_pSubTexture = m_pCur->m_pSubTexture; return m_pCur; } inline ParticleDraw *CParticleRenderIterator::GetParticleDraw() const { return m_pParticleDraw; } // -------------------------------------------------------------------------------------------------------- // // CParticleSimulateIterator inlines // -------------------------------------------------------------------------------------------------------- // // inline CParticleSimulateIterator::CParticleSimulateIterator() { m_pNextParticle = NULL; #ifdef _DEBUG m_bGotFirst = false; #endif } inline Particle *CParticleSimulateIterator::GetFirst() { #ifdef _DEBUG // Make sure they're either starting out fresh or that the previous guy // iterated through all the particles. if (m_bGotFirst) { Assert(m_pNextParticle == &m_pMaterial->m_Particles); } #endif Particle *pRet = m_pMaterial->m_Particles.m_pNext; if (pRet == &m_pMaterial->m_Particles) return NULL; #ifdef _DEBUG m_bGotFirst = true; #endif m_pNextParticle = pRet->m_pNext; return pRet; } inline Particle *CParticleSimulateIterator::GetNext() { Particle *pRet = m_pNextParticle; if (pRet == &m_pMaterial->m_Particles) return NULL; m_pNextParticle = pRet->m_pNext; return pRet; } inline void CParticleSimulateIterator::RemoveParticle(Particle *pParticle) { m_pEffectBinding->RemoveParticle(pParticle); } inline void CParticleSimulateIterator::RemoveAllParticles() { Particle *pParticle = GetFirst(); while (pParticle) { RemoveParticle(pParticle); pParticle = GetNext(); } } inline float CParticleSimulateIterator::GetTimeDelta() const { return m_flTimeDelta; } #endif // PARTICLE_ITERATORS_H
GEF and UNEP Launch Global Platform for Efficient Lighting 25 September 2009: The Global Environment Facility (GEF) and the United Nations Environment Programme (UNEP) have launched the “Global Market Transformation for Efficient Lighting Platform,” a public-private partnership directed at reducing global energy demand for lighting. The Platform aims to transform lighting markets, primarily in developing countries, by fostering the usage and production of energy efficient lighting while gradually discontinuing use of incandescent lighting, and substituting traditional fuel-based lighting with modern, efficient alternatives such as solid-state lighting (SSL) and Light Emitting Diode (LED) lamps. It is hoped that, through these efforts, global demand for lighting energy can eventually be reduced by up to 18 percent. In attendance for the event was UNEP Executive Director Achim Steiner, who noted that “in terms of climate change, this is among the lowest of low-hanging fruit. Eight percent of global greenhouse gas emissions are linked with lighting; this project can by 2014 make a big dent in these while saving people money too.” [UN News Centre] [GEF press release]