text
stringlengths
54
60.6k
<commit_before>#include <iostream> #include <set> #include <sstream> #include <algorithm> #include "Lower.h" #include "AddImageChecks.h" #include "AddParameterChecks.h" #include "AllocationBoundsInference.h" #include "Bounds.h" #include "BoundsInference.h" #include "CSE.h" #include "Debug.h" #include "DebugToFile.h" #include "DeepCopy.h" #include "Deinterleave.h" #include "EarlyFree.h" #include "FindCalls.h" #include "Function.h" #include "FuseGPUThreadLoops.h" #include "HexagonOffload.h" #include "InjectHostDevBufferCopies.h" #include "InjectImageIntrinsics.h" #include "InjectOpenGLIntrinsics.h" #include "Inline.h" #include "IRMutator.h" #include "IROperator.h" #include "IRPrinter.h" #include "LoopCarry.h" #include "Memoization.h" #include "PartitionLoops.h" #include "Profiling.h" #include "Qualify.h" #include "RealizationOrder.h" #include "RemoveDeadAllocations.h" #include "RemoveTrivialForLoops.h" #include "RemoveUndef.h" #include "ScheduleFunctions.h" #include "SelectGPUAPI.h" #include "SkipStages.h" #include "SlidingWindow.h" #include "Simplify.h" #include "SimplifySpecializations.h" #include "StorageFlattening.h" #include "StorageFolding.h" #include "Substitute.h" #include "Tracing.h" #include "TrimNoOps.h" #include "UnifyDuplicateLets.h" #include "UniquifyVariableNames.h" #include "UnrollLoops.h" #include "VaryingAttributes.h" #include "VectorizeLoops.h" #include "WrapCalls.h" namespace Halide { namespace Internal { using std::set; using std::ostringstream; using std::string; using std::vector; using std::map; Stmt lower(vector<Function> outputs, const string &pipeline_name, const Target &t, const vector<IRMutator *> &custom_passes) { // Compute an environment map<string, Function> env; for (Function f : outputs) { map<string, Function> more_funcs = find_transitive_calls(f); env.insert(more_funcs.begin(), more_funcs.end()); } // Create a deep-copy of the entire graph of Funcs. std::tie(outputs, env) = deep_copy(outputs, env); // Substitute in wrapper Funcs env = wrap_func_calls(env); // Compute a realization order vector<string> order = realization_order(outputs, env); // Try to simplify the RHS/LHS of a function definition by propagating its // specializations' conditions simplify_specializations(env); bool any_memoized = false; debug(1) << "Creating initial loop nests...\n"; Stmt s = schedule_functions(outputs, order, env, t, any_memoized); debug(2) << "Lowering after creating initial loop nests:\n" << s << '\n'; if (any_memoized) { debug(1) << "Injecting memoization...\n"; s = inject_memoization(s, env, pipeline_name, outputs); debug(2) << "Lowering after injecting memoization:\n" << s << '\n'; } else { debug(1) << "Skipping injecting memoization...\n"; } debug(1) << "Injecting tracing...\n"; s = inject_tracing(s, pipeline_name, env, outputs); debug(2) << "Lowering after injecting tracing:\n" << s << '\n'; debug(1) << "Adding checks for parameters\n"; s = add_parameter_checks(s, t); debug(2) << "Lowering after injecting parameter checks:\n" << s << '\n'; // Compute the maximum and minimum possible value of each // function. Used in later bounds inference passes. debug(1) << "Computing bounds of each function's value\n"; FuncValueBounds func_bounds = compute_function_value_bounds(order, env); // The checks will be in terms of the symbols defined by bounds // inference. debug(1) << "Adding checks for images\n"; s = add_image_checks(s, outputs, t, order, env, func_bounds); debug(2) << "Lowering after injecting image checks:\n" << s << '\n'; // This pass injects nested definitions of variable names, so we // can't simplify statements from here until we fix them up. (We // can still simplify Exprs). debug(1) << "Performing computation bounds inference...\n"; s = bounds_inference(s, outputs, order, env, func_bounds); debug(2) << "Lowering after computation bounds inference:\n" << s << '\n'; debug(1) << "Performing sliding window optimization...\n"; s = sliding_window(s, env); debug(2) << "Lowering after sliding window:\n" << s << '\n'; debug(1) << "Performing allocation bounds inference...\n"; s = allocation_bounds_inference(s, env, func_bounds); debug(2) << "Lowering after allocation bounds inference:\n" << s << '\n'; debug(1) << "Removing code that depends on undef values...\n"; s = remove_undef(s); debug(2) << "Lowering after removing code that depends on undef values:\n" << s << "\n\n"; // This uniquifies the variable names, so we're good to simplify // after this point. This lets later passes assume syntactic // equivalence means semantic equivalence. debug(1) << "Uniquifying variable names...\n"; s = uniquify_variable_names(s); debug(2) << "Lowering after uniquifying variable names:\n" << s << "\n\n"; debug(1) << "Performing storage folding optimization...\n"; s = storage_folding(s, env); debug(2) << "Lowering after storage folding:\n" << s << '\n'; debug(1) << "Injecting debug_to_file calls...\n"; s = debug_to_file(s, outputs, env); debug(2) << "Lowering after injecting debug_to_file calls:\n" << s << '\n'; debug(1) << "Simplifying...\n"; // without removing dead lets, because storage flattening needs the strides s = simplify(s, false); debug(2) << "Lowering after first simplification:\n" << s << "\n\n"; debug(1) << "Dynamically skipping stages...\n"; s = skip_stages(s, order); debug(2) << "Lowering after dynamically skipping stages:\n" << s << "\n\n"; if (t.has_feature(Target::OpenGL) || t.has_feature(Target::Renderscript)) { debug(1) << "Injecting image intrinsics...\n"; s = inject_image_intrinsics(s, env); debug(2) << "Lowering after image intrinsics:\n" << s << "\n\n"; } debug(1) << "Performing storage flattening...\n"; s = storage_flattening(s, outputs, env, t); debug(2) << "Lowering after storage flattening:\n" << s << "\n\n"; if (any_memoized) { debug(1) << "Rewriting memoized allocations...\n"; s = rewrite_memoized_allocations(s, env); debug(2) << "Lowering after rewriting memoized allocations:\n" << s << "\n\n"; } else { debug(1) << "Skipping rewriting memoized allocations...\n"; } if (t.has_gpu_feature() || t.has_feature(Target::OpenGLCompute) || t.has_feature(Target::OpenGL) || t.has_feature(Target::Renderscript) || (t.arch != Target::Hexagon && (t.features_any_of({Target::HVX_64, Target::HVX_128})))) { debug(1) << "Selecting a GPU API for GPU loops...\n"; s = select_gpu_api(s, t); debug(2) << "Lowering after selecting a GPU API:\n" << s << "\n\n"; debug(1) << "Injecting host <-> dev buffer copies...\n"; s = inject_host_dev_buffer_copies(s, t); debug(2) << "Lowering after injecting host <-> dev buffer copies:\n" << s << "\n\n"; } if (t.has_feature(Target::OpenGL)) { debug(1) << "Injecting OpenGL texture intrinsics...\n"; s = inject_opengl_intrinsics(s); debug(2) << "Lowering after OpenGL intrinsics:\n" << s << "\n\n"; } if (t.has_gpu_feature() || t.has_feature(Target::OpenGLCompute) || t.has_feature(Target::Renderscript)) { debug(1) << "Injecting per-block gpu synchronization...\n"; s = fuse_gpu_thread_loops(s); debug(2) << "Lowering after injecting per-block gpu synchronization:\n" << s << "\n\n"; } debug(1) << "Simplifying...\n"; s = simplify(s); s = unify_duplicate_lets(s); s = remove_trivial_for_loops(s); debug(2) << "Lowering after second simplifcation:\n" << s << "\n\n"; debug(1) << "Unrolling...\n"; s = unroll_loops(s); s = simplify(s); debug(2) << "Lowering after unrolling:\n" << s << "\n\n"; debug(1) << "Vectorizing...\n"; s = vectorize_loops(s); s = simplify(s); debug(2) << "Lowering after vectorizing:\n" << s << "\n\n"; debug(1) << "Detecting vector interleavings...\n"; s = rewrite_interleavings(s); s = simplify(s); debug(2) << "Lowering after rewriting vector interleavings:\n" << s << "\n\n"; debug(1) << "Partitioning loops to simplify boundary conditions...\n"; s = partition_loops(s); s = simplify(s); debug(2) << "Lowering after partitioning loops:\n" << s << "\n\n"; debug(1) << "Trimming loops to the region over which they do something...\n"; s = trim_no_ops(s); debug(2) << "Lowering after loop trimming:\n" << s << "\n\n"; debug(1) << "Injecting early frees...\n"; s = inject_early_frees(s); debug(2) << "Lowering after injecting early frees:\n" << s << "\n\n"; if (t.has_feature(Target::Profile)) { debug(1) << "Injecting profiling...\n"; s = inject_profiling(s, pipeline_name); debug(2) << "Lowering after injecting profiling:\n" << s << '\n'; } debug(1) << "Simplifying...\n"; s = common_subexpression_elimination(s); if (t.has_feature(Target::OpenGL)) { debug(1) << "Detecting varying attributes...\n"; s = find_linear_expressions(s); debug(2) << "Lowering after detecting varying attributes:\n" << s << "\n\n"; debug(1) << "Moving varying attribute expressions out of the shader...\n"; s = setup_gpu_vertex_buffer(s); debug(2) << "Lowering after removing varying attributes:\n" << s << "\n\n"; } s = remove_dead_allocations(s); s = remove_trivial_for_loops(s); s = simplify(s); debug(1) << "Lowering after final simplification:\n" << s << "\n\n"; debug(1) << "Splitting off Hexagon offload...\n"; s = inject_hexagon_rpc(s, t); debug(2) << "Lowering after splitting off Hexagon offload:\n" << s << '\n'; if (!custom_passes.empty()) { for (size_t i = 0; i < custom_passes.size(); i++) { debug(1) << "Running custom lowering pass " << i << "...\n"; s = custom_passes[i]->mutate(s); debug(1) << "Lowering after custom pass " << i << ":\n" << s << "\n\n"; } } return s; } } } <commit_msg>fixed bugs in predicated store/load to handle and added more tests<commit_after>#include <iostream> #include <set> #include <sstream> #include <algorithm> #include "Lower.h" #include "AddImageChecks.h" #include "AddParameterChecks.h" #include "AllocationBoundsInference.h" #include "Bounds.h" #include "BoundsInference.h" #include "CSE.h" #include "Debug.h" #include "DebugToFile.h" #include "DeepCopy.h" #include "Deinterleave.h" #include "EarlyFree.h" #include "FindCalls.h" #include "Function.h" #include "FuseGPUThreadLoops.h" #include "HexagonOffload.h" #include "InjectHostDevBufferCopies.h" #include "InjectImageIntrinsics.h" #include "InjectOpenGLIntrinsics.h" #include "Inline.h" #include "IRMutator.h" #include "IROperator.h" #include "IRPrinter.h" #include "LoopCarry.h" #include "Memoization.h" #include "PartitionLoops.h" #include "Profiling.h" #include "Qualify.h" #include "RealizationOrder.h" #include "RemoveDeadAllocations.h" #include "RemoveTrivialForLoops.h" #include "RemoveUndef.h" #include "ScheduleFunctions.h" #include "SelectGPUAPI.h" #include "SkipStages.h" #include "SlidingWindow.h" #include "Simplify.h" #include "SimplifySpecializations.h" #include "StorageFlattening.h" #include "StorageFolding.h" #include "Substitute.h" #include "Tracing.h" #include "TrimNoOps.h" #include "UnifyDuplicateLets.h" #include "UniquifyVariableNames.h" #include "UnrollLoops.h" #include "VaryingAttributes.h" #include "VectorizeLoops.h" #include "WrapCalls.h" namespace Halide { namespace Internal { using std::set; using std::ostringstream; using std::string; using std::vector; using std::map; Stmt lower(vector<Function> outputs, const string &pipeline_name, const Target &t, const vector<IRMutator *> &custom_passes) { // Compute an environment map<string, Function> env; for (Function f : outputs) { map<string, Function> more_funcs = find_transitive_calls(f); env.insert(more_funcs.begin(), more_funcs.end()); } // Create a deep-copy of the entire graph of Funcs. std::tie(outputs, env) = deep_copy(outputs, env); // Substitute in wrapper Funcs env = wrap_func_calls(env); // Compute a realization order vector<string> order = realization_order(outputs, env); // Try to simplify the RHS/LHS of a function definition by propagating its // specializations' conditions simplify_specializations(env); bool any_memoized = false; debug(1) << "Creating initial loop nests...\n"; Stmt s = schedule_functions(outputs, order, env, t, any_memoized); debug(2) << "Lowering after creating initial loop nests:\n" << s << '\n'; if (any_memoized) { debug(1) << "Injecting memoization...\n"; s = inject_memoization(s, env, pipeline_name, outputs); debug(2) << "Lowering after injecting memoization:\n" << s << '\n'; } else { debug(1) << "Skipping injecting memoization...\n"; } debug(1) << "Injecting tracing...\n"; s = inject_tracing(s, pipeline_name, env, outputs); debug(2) << "Lowering after injecting tracing:\n" << s << '\n'; debug(1) << "Adding checks for parameters\n"; s = add_parameter_checks(s, t); debug(2) << "Lowering after injecting parameter checks:\n" << s << '\n'; // Compute the maximum and minimum possible value of each // function. Used in later bounds inference passes. debug(1) << "Computing bounds of each function's value\n"; FuncValueBounds func_bounds = compute_function_value_bounds(order, env); // The checks will be in terms of the symbols defined by bounds // inference. debug(1) << "Adding checks for images\n"; s = add_image_checks(s, outputs, t, order, env, func_bounds); debug(2) << "Lowering after injecting image checks:\n" << s << '\n'; // This pass injects nested definitions of variable names, so we // can't simplify statements from here until we fix them up. (We // can still simplify Exprs). debug(1) << "Performing computation bounds inference...\n"; s = bounds_inference(s, outputs, order, env, func_bounds); debug(2) << "Lowering after computation bounds inference:\n" << s << '\n'; debug(1) << "Performing sliding window optimization...\n"; s = sliding_window(s, env); debug(2) << "Lowering after sliding window:\n" << s << '\n'; debug(1) << "Performing allocation bounds inference...\n"; s = allocation_bounds_inference(s, env, func_bounds); debug(2) << "Lowering after allocation bounds inference:\n" << s << '\n'; debug(1) << "Removing code that depends on undef values...\n"; s = remove_undef(s); debug(2) << "Lowering after removing code that depends on undef values:\n" << s << "\n\n"; // This uniquifies the variable names, so we're good to simplify // after this point. This lets later passes assume syntactic // equivalence means semantic equivalence. debug(1) << "Uniquifying variable names...\n"; s = uniquify_variable_names(s); debug(2) << "Lowering after uniquifying variable names:\n" << s << "\n\n"; debug(1) << "Performing storage folding optimization...\n"; s = storage_folding(s, env); debug(2) << "Lowering after storage folding:\n" << s << '\n'; debug(1) << "Injecting debug_to_file calls...\n"; s = debug_to_file(s, outputs, env); debug(2) << "Lowering after injecting debug_to_file calls:\n" << s << '\n'; debug(1) << "Simplifying...\n"; // without removing dead lets, because storage flattening needs the strides s = simplify(s, false); debug(2) << "Lowering after first simplification:\n" << s << "\n\n"; debug(1) << "Dynamically skipping stages...\n"; s = skip_stages(s, order); debug(2) << "Lowering after dynamically skipping stages:\n" << s << "\n\n"; if (t.has_feature(Target::OpenGL) || t.has_feature(Target::Renderscript)) { debug(1) << "Injecting image intrinsics...\n"; s = inject_image_intrinsics(s, env); debug(2) << "Lowering after image intrinsics:\n" << s << "\n\n"; } debug(1) << "Performing storage flattening...\n"; s = storage_flattening(s, outputs, env, t); debug(2) << "Lowering after storage flattening:\n" << s << "\n\n"; if (any_memoized) { debug(1) << "Rewriting memoized allocations...\n"; s = rewrite_memoized_allocations(s, env); debug(2) << "Lowering after rewriting memoized allocations:\n" << s << "\n\n"; } else { debug(1) << "Skipping rewriting memoized allocations...\n"; } if (t.has_gpu_feature() || t.has_feature(Target::OpenGLCompute) || t.has_feature(Target::OpenGL) || t.has_feature(Target::Renderscript) || (t.arch != Target::Hexagon && (t.features_any_of({Target::HVX_64, Target::HVX_128})))) { debug(1) << "Selecting a GPU API for GPU loops...\n"; s = select_gpu_api(s, t); debug(2) << "Lowering after selecting a GPU API:\n" << s << "\n\n"; debug(1) << "Injecting host <-> dev buffer copies...\n"; s = inject_host_dev_buffer_copies(s, t); debug(2) << "Lowering after injecting host <-> dev buffer copies:\n" << s << "\n\n"; } if (t.has_feature(Target::OpenGL)) { debug(1) << "Injecting OpenGL texture intrinsics...\n"; s = inject_opengl_intrinsics(s); debug(2) << "Lowering after OpenGL intrinsics:\n" << s << "\n\n"; } if (t.has_gpu_feature() || t.has_feature(Target::OpenGLCompute) || t.has_feature(Target::Renderscript)) { debug(1) << "Injecting per-block gpu synchronization...\n"; s = fuse_gpu_thread_loops(s); debug(2) << "Lowering after injecting per-block gpu synchronization:\n" << s << "\n\n"; } debug(1) << "Simplifying...\n"; s = simplify(s); s = unify_duplicate_lets(s); s = remove_trivial_for_loops(s); debug(2) << "Lowering after second simplifcation:\n" << s << "\n\n"; debug(1) << "Unrolling...\n"; s = unroll_loops(s); s = simplify(s); debug(2) << "Lowering after unrolling:\n" << s << "\n\n"; debug(1) << "Vectorizing...\n"; s = vectorize_loops(s); s = simplify(s); debug(0) << "Lowering after vectorizing:\n" << s << "\n\n"; debug(1) << "Detecting vector interleavings...\n"; s = rewrite_interleavings(s); s = simplify(s); debug(2) << "Lowering after rewriting vector interleavings:\n" << s << "\n\n"; debug(1) << "Partitioning loops to simplify boundary conditions...\n"; s = partition_loops(s); s = simplify(s); debug(2) << "Lowering after partitioning loops:\n" << s << "\n\n"; debug(1) << "Trimming loops to the region over which they do something...\n"; s = trim_no_ops(s); debug(2) << "Lowering after loop trimming:\n" << s << "\n\n"; debug(1) << "Injecting early frees...\n"; s = inject_early_frees(s); debug(2) << "Lowering after injecting early frees:\n" << s << "\n\n"; if (t.has_feature(Target::Profile)) { debug(1) << "Injecting profiling...\n"; s = inject_profiling(s, pipeline_name); debug(2) << "Lowering after injecting profiling:\n" << s << '\n'; } debug(1) << "Simplifying...\n"; s = common_subexpression_elimination(s); if (t.has_feature(Target::OpenGL)) { debug(1) << "Detecting varying attributes...\n"; s = find_linear_expressions(s); debug(2) << "Lowering after detecting varying attributes:\n" << s << "\n\n"; debug(1) << "Moving varying attribute expressions out of the shader...\n"; s = setup_gpu_vertex_buffer(s); debug(2) << "Lowering after removing varying attributes:\n" << s << "\n\n"; } s = remove_dead_allocations(s); s = remove_trivial_for_loops(s); s = simplify(s); debug(1) << "Lowering after final simplification:\n" << s << "\n\n"; debug(1) << "Splitting off Hexagon offload...\n"; s = inject_hexagon_rpc(s, t); debug(2) << "Lowering after splitting off Hexagon offload:\n" << s << '\n'; if (!custom_passes.empty()) { for (size_t i = 0; i < custom_passes.size(); i++) { debug(1) << "Running custom lowering pass " << i << "...\n"; s = custom_passes[i]->mutate(s); debug(1) << "Lowering after custom pass " << i << ":\n" << s << "\n\n"; } } return s; } } } <|endoftext|>
<commit_before>#include "Parse.h" #include <iostream> #include <string> #include <sstream> #include <sys/stat.h> #include <dirent.h> #include <stdio.h> #include <string.h> #include <stack> #include <sys/types.h> #include <unistd.h> //#define delimitor ";#" // token separators using namespace std; Parse::Parse() { } void Parse::run() { string input; Runcmd* inputCommand = NULL; while(true) { cout << "$ "; getline(cin, input); inputCommand = parse(input); if (inputCommand != NULL) { inputCommand->run(); inputCommand = NULL; } } } Runcmd* Parse::parse(string& s) { if (s.size() == 0) return NULL; if (s.find_first_not_of(" ") == string::npos) return NULL; if (s.find('#') != string::npos) { int loc = s.find('#'); s = s.substr(0,loc); return parse(s); } bool par = false; string parenth_part = ""; for (unsigned i = 0; i < s.length(); i++) { if (s.at(i) == '(' ) { if (s.find(')') == string::npos) { cout << "Error, could not find matching ')'" << endl; return NULL; } stack<int> p; int end; p.push(i); for (unsigned int j = i + 1; p.size() > 0; j++ ) { if (s.at(j) == '(') p.push(j); if (s.at(j) == ')') p.pop(); end = j; } parenth_part = s.substr(i+1, end - i - 1); par = true; i = end; } if(s.at(i) == ';' ) { int size = s.length(); string lhs = s.substr(0,i); string rhs = s.substr(i+1,size); Semicolon* b; if (par) b = new Semicolon(parse(rhs),parse(parenth_part)); else b = new Semicolon(parse(rhs),parse(lhs)); return b; } if (s.at(i) == '|' && s.at(i+1) == '|') { int size = s.length(); string lhs = s.substr(0,i); string rhs = s.substr(i+2,size); Or* c; if (par) c = new Or(parse(rhs),parse(parenth_part)); else c = new Or(parse(rhs),parse(lhs)); return c; } if (s.at(i) == '&' && s.at(i+1) == '&') { int size = s.length(); string lhs = s.substr(0,i); string rhs = s.substr(i+2,size); And* d; if (par) d = new And(parse(rhs),parse(parenth_part)); else d = new And(parse(rhs),parse(lhs)); return d; } if (s.substr(i,4) == "exit" && (s.length() == i+4 || s.at(i+4) == ' ')) { Exit* ex = new Exit(); return ex; } } Runcmd* g; if (par) g = parse(parenth_part); else g = new Execvpcmd(s); return g; } <commit_msg>Create Parse.cpp<commit_after>#include "Parse.h" #include <iostream> #include <string> #include <sstream> #include <sys/stat.h> #include <dirent.h> #include <stdio.h> #include <string.h> #include <stack> #include <sys/types.h> #include <unistd.h> using namespace std; Parse::Parse() { } void Parse::run() { string input; Runcmd* inputCommand = NULL; while(true) { cout << "$ "; getline(cin, input); inputCommand = parse(input); if (inputCommand != NULL) { inputCommand->run(); inputCommand = NULL; } } } Runcmd* Parse::parse(string& s) { if (s.size() == 0) return NULL; if (s.find_first_not_of(" ") == string::npos) return NULL; if (s.find('#') != string::npos) { int loc = s.find('#'); s = s.substr(0,loc); return parse(s); } bool par = false; string parenth_part = ""; for (unsigned i = 0; i < s.length(); i++) { if (s.at(i) == '(' ) { if (s.find(')') == string::npos) { cout << "Error, could not find matching ')'" << endl; return NULL; } stack<int> p; int end; p.push(i); for (unsigned int j = i + 1; p.size() > 0; j++ ) { if (s.at(j) == '(') p.push(j); if (s.at(j) == ')') p.pop(); end = j; } parenth_part = s.substr(i+1, end - i - 1); par = true; i = end; } if(s.at(i) == ';' ) //checks for semi colon { int size = s.length(); string lhs = s.substr(0,i); string rhs = s.substr(i+1,size); Semicolon* b; if (par) b = new Semicolon(parse(rhs),parse(parenth_part)); else b = new Semicolon(parse(rhs),parse(lhs)); return b; } if (s.at(i) == '|' && s.at(i+1) == '|') // checks of or is inputed { int size = s.length(); string lhs = s.substr(0,i); string rhs = s.substr(i+2,size); Or* c; if (par) c = new Or(parse(rhs),parse(parenth_part)); else c = new Or(parse(rhs),parse(lhs)); return c; } if (s.at(i) == '|' && s.at(i+1) != '|') // checks of piping is inputed { int size = s.length(); string lhs = s.substr(0,i); string rhs = s.substr(i+1,size); Stick* x; if (par) x = new Stick(parse(rhs),parse(parenth_part)); else x = new Stick(parse(rhs),parse(lhs)); return x; } if(s.at(i) == '<' ) // checks if input redirection is inputted { int size = s.length(); string lhs = s.substr(0,i); string rhs = s.substr(i+1,size); LessThan* y; if (par) y = new LessThan(parse(rhs),parse(parenth_part)); else y = new LessThan(parse(rhs),parse(lhs)); return y; } if (s.at(i) == '>' && s.at(i+1) == '>') //check double >> for output redirection { int size = s.length(); string lhs = s.substr(0,i); string rhs = s.substr(i+2,size); DoubleGreaterThan* z; if (par) z = new DoubleGreaterThan(parse(rhs),parse(parenth_part)); else z = new DoubleGreaterThan(parse(rhs),parse(lhs)); return z; } if (s.at(i) == '>' && s.at(i+1) != '>') //checks for > for output redirection { int size = s.length(); string lhs = s.substr(0,i); string rhs = s.substr(i+1,size); stringstream ss (lhs); string file; ss >> file; GreaterThan* w; if (par) w = new GreaterThan(parse(rhs),parse(parenth_part)); else w = new GreaterThan(parse(rhs),parse(lhs)); return w; } if (s.at(i) == '&' && s.at(i+1) == '&') //checks for and { int size = s.length(); string lhs = s.substr(0,i); string rhs = s.substr(i+2,size); And* d; if (par) d = new And(parse(rhs),parse(parenth_part)); else d = new And(parse(rhs),parse(lhs)); return d; } if (s.substr(i,4) == "exit" && (s.length() == i+4 || s.at(i+4) == ' ')) //checks for exit { Exit* ex = new Exit(); return ex; } } Runcmd* g; if (par) g = parse(parenth_part); else g = new Execvpcmd(s); return g; } <|endoftext|>
<commit_before>// (C) 2014 Arek Olek #include <functional> #include <iostream> #include <vector> #include <boost/graph/adjacency_list.hpp> #include "bfs.hpp" #include "dfs.hpp" #include "lost.hpp" #include "rdfs.hpp" #include "test_suite.hpp" #include "debug.hpp" #include "options.hpp" #include "range.hpp" #include "timing.hpp" using namespace std; boost::property<boost::edge_color_t, boost::default_color_type> typedef color; boost::adjacency_list< boost::hash_setS, boost::vecS, boost::undirectedS, boost::no_property, color> typedef graph; template <class Graph> double eval(Graph const & T) { int n = num_vertices(T) - 2; int internal = 0; for(auto v : range(vertices(T))) internal += degree(v, T) > 1; return 100 * internal / (double)n; } template <class Graph> float average_degree(Graph const & G) { float sum = 0; for(auto v : range(vertices(G))) sum += degree(v, G); return sum / num_vertices(G); } function<graph(graph&)> typedef solution; class dummy { public: template<class Graph> int operator()(Graph& G, Graph& T) { return 0; } }; template <class Improvement> void run(int z, int n, vector<float> ps, vector<string> name, vector<solution> algo, Improvement improve, string iname) { timing timer; cout << endl << iname << endl; cout << "\t\t"; for(auto n : name) cout << n << "\t\t\t\t\t"; cout << "\np\tE[deg]"; for(auto n : name) cout << "\tmin\tE[|I|]\tmax\ttime\tsteps"; cout << endl; for(auto p : ps) { test_suite<graph> suite(z, n, p); double degree = 0; vector<double> steps(algo.size(), 0), quality(algo.size(), 0), time(algo.size(), 0); vector<double> minimum(algo.size(), n), maximum(algo.size(), 0); for(auto G : suite) { degree += average_degree(G); for(unsigned i = 0; i < algo.size(); ++i) { timer.start(); auto T = algo[i](G); steps[i] += improve(G, T); time[i] += timer.stop(); double q = eval(T); quality[i] += q; minimum[i] = min(minimum[i], q); maximum[i] = max(maximum[i], q); //show("graph" + to_string(i) + ".dot", G, T); } } int count = suite.size(); cout << std::setprecision(6) << p << '\t' << degree / count; for(unsigned i = 0; i < algo.size(); ++i) cout << '\t' << minimum[i] << '\t' << quality[i] / count << '\t' << maximum[i] << '\t' << time[i] / count << '\t' << steps[i] / count ; cout << endl; } } int main(int argc, char** argv){ ios_base::sync_with_stdio(0); options opt(argc, argv); int z = opt.get<int>("-z", 1); int n = opt.get<int>("-n", 5); float p = opt.get<float>("-p", -1); string a = opt.get<string>("-a"); vector<float> ps {0.0001, 0.0005, 0.001, 0.003, 0.005, 0.008, 0.01, 0.03, 0.05, 0.08, 0.1, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.7, 0.8, 0.9, 0.95, 0.99}; //~ vector<float> ps {0.0002, 0.0105, 0.021, 0.0312, 0.0415, 0.0518, 0.062, 0.0725, 0.0827}; if(p >= 0 && p <= 1) { ps.clear(); ps.push_back(p); } vector<string> name {/*"bfs", */"dfs", "rdfs"}; vector<solution> algo {/*bfs_tree<graph>, */dfs_tree<graph>, rdfs_tree<graph>}; //run(z, n, ps, name, algo, dummy(), "no improvement"); //run(z, n, ps, name, algo, prieto(), "prieto"); run(z, n, ps, name, algo, lost_light(), "lost-light"); run(z, n, ps, name, algo, lost(), "lost"); return 0; } <commit_msg>narrow probabilities<commit_after>// (C) 2014 Arek Olek #include <functional> #include <iostream> #include <vector> #include <boost/graph/adjacency_list.hpp> #include "bfs.hpp" #include "dfs.hpp" #include "lost.hpp" #include "rdfs.hpp" #include "test_suite.hpp" #include "debug.hpp" #include "options.hpp" #include "range.hpp" #include "timing.hpp" using namespace std; boost::property<boost::edge_color_t, boost::default_color_type> typedef color; boost::adjacency_list< boost::hash_setS, boost::vecS, boost::undirectedS, boost::no_property, color> typedef graph; template <class Graph> double eval(Graph const & T) { int n = num_vertices(T) - 2; int internal = 0; for(auto v : range(vertices(T))) internal += degree(v, T) > 1; return 100 * internal / (double)n; } template <class Graph> float average_degree(Graph const & G) { float sum = 0; for(auto v : range(vertices(G))) sum += degree(v, G); return sum / num_vertices(G); } function<graph(graph&)> typedef solution; class dummy { public: template<class Graph> int operator()(Graph& G, Graph& T) { return 0; } }; template <class Improvement> void run(int z, int n, vector<float> ps, vector<string> name, vector<solution> algo, Improvement improve, string iname) { timing timer; cout << endl << iname << endl; cout << "\t\t"; for(auto n : name) cout << n << "\t\t\t\t\t"; cout << "\np\tE[deg]"; for(auto n : name) cout << "\tmin\tE[|I|]\tmax\ttime\tsteps"; cout << endl; for(auto p : ps) { test_suite<graph> suite(z, n, p); double degree = 0; vector<double> steps(algo.size(), 0), quality(algo.size(), 0), time(algo.size(), 0); vector<double> minimum(algo.size(), n), maximum(algo.size(), 0); for(auto G : suite) { degree += average_degree(G); for(unsigned i = 0; i < algo.size(); ++i) { timer.start(); auto T = algo[i](G); steps[i] += improve(G, T); time[i] += timer.stop(); double q = eval(T); quality[i] += q; minimum[i] = min(minimum[i], q); maximum[i] = max(maximum[i], q); //show("graph" + to_string(i) + ".dot", G, T); } } int count = suite.size(); cout << std::setprecision(6) << p << '\t' << degree / count; for(unsigned i = 0; i < algo.size(); ++i) cout << '\t' << minimum[i] << '\t' << quality[i] / count << '\t' << maximum[i] << '\t' << time[i] / count << '\t' << steps[i] / count ; cout << endl; } } int main(int argc, char** argv){ ios_base::sync_with_stdio(0); options opt(argc, argv); int z = opt.get<int>("-z", 1); int n = opt.get<int>("-n", 5); float p = opt.get<float>("-p", -1); string a = opt.get<string>("-a"); vector<float> ps {0.0001, 0.0005, 0.001, 0.003, 0.005, 0.008, 0.01, 0.03, 0.05, 0.08, 0.1, 0.2//, 0.25, 0.3, 0.35, 0.4, 0.45, //0.5, 0.55, 0.6, 0.7, 0.8, 0.9, 0.95, 0.99 }; //~ vector<float> ps {0.0002, 0.0105, 0.021, 0.0312, 0.0415, 0.0518, 0.062, 0.0725, 0.0827}; if(p >= 0 && p <= 1) { ps.clear(); ps.push_back(p); } vector<string> name {/*"bfs", */"dfs", "rdfs"}; vector<solution> algo {/*bfs_tree<graph>, */dfs_tree<graph>, rdfs_tree<graph>}; //run(z, n, ps, name, algo, dummy(), "no improvement"); //run(z, n, ps, name, algo, prieto(), "prieto"); //run(z, n, ps, name, algo, lost_light(), "lost-light"); run(z, n, ps, name, algo, lost(), "lost"); return 0; } <|endoftext|>
<commit_before>#include "Tiler.h" #include "cinder/gl/gl.h" #include "cinder/app/App.h" #include "cinder/Rand.h" #include <algorithm> #include <sstream> using namespace reza::tiler; using namespace cinder; using namespace glm; using namespace std; Tiler::Tiler( int32_t imageWidth, int32_t imageHeight, int32_t tileWidth, int32_t tileHeight, ci::app::WindowRef window, bool alpha ) : mImageWidth( app::toPixels( imageWidth ) ), mImageHeight( app::toPixels( imageHeight ) ), mWindowRef( window ), mDrawFn( nullptr ), mDrawBgFn( nullptr ), mDrawHudFn( nullptr ), mAlpha( alpha ) { mWindowWidth = app::toPixels( mWindowRef->getWidth() ); mWindowHeight = app::toPixels( mWindowRef->getHeight() ); mTileWidth = std::min( ( int32_t ) app::toPixels( tileWidth ), mWindowWidth ); mTileHeight = std::min( ( int32_t ) app::toPixels( tileHeight ), mWindowHeight ); mNumTilesX = ( int32_t ) ceil( mImageWidth / (float)mTileWidth ); mNumTilesY = ( int32_t ) ceil( mImageHeight / (float)mTileHeight ); mCurrentTile = -1; if( mAlpha ) { mFboRef = gl::Fbo::create( mWindowWidth, mWindowHeight, mAlpha ); mFboRef->bindFramebuffer(); gl::clear( ColorA( 0.0f, 0.0f, 0.0f, 0.0f ) ); mFboRef->unbindFramebuffer(); } } bool Tiler::nextTile() { if( mCurrentTile >= mNumTilesX * mNumTilesY ) { if( mAlpha ) { mSurface.copyFrom( mFboRef->readPixels8u( Area( ivec2( 0 ) , ci::app::toPixels( mWindowRef->getSize() ) ), mCurrentArea.getHeight() ), Area( 0, 0, mCurrentArea.getWidth(), mCurrentArea.getHeight() ), mCurrentArea.getUL() ); } else { mSurface.copyFrom( mWindowRef->getRenderer()->copyWindowSurface( Area( ivec2( 0 ) , mWindowRef->getSize() ), mCurrentArea.getHeight() ), Area( 0, 0, mCurrentArea.getWidth(), mCurrentArea.getHeight() ), mCurrentArea.getUL() ); } mCurrentTile = -1; return false; } if( mCurrentTile == -1 ) { mCurrentTile = 0; mSurface = Surface( mImageWidth, mImageHeight, mAlpha ); } else { if( mAlpha ) { mSurface.copyFrom( mFboRef->readPixels8u( Area( ivec2( 0 ) , ci::app::toPixels( mWindowRef->getSize() ) ), mCurrentArea.getHeight() ), Area( 0, 0, mCurrentArea.getWidth(), mCurrentArea.getHeight() ), mCurrentArea.getUL() ); } else { mSurface.copyFrom( mWindowRef->getRenderer()->copyWindowSurface( Area( ivec2( 0 ) , ci::app::toPixels( mWindowRef->getSize() ) ), mCurrentArea.getHeight() ), Area( 0, 0, mCurrentArea.getWidth(), mCurrentArea.getHeight() ), mCurrentArea.getUL() ); } } int tileX = mCurrentTile % mNumTilesX; int tileY = mCurrentTile / mNumTilesX; int currentTileWidth = ( ( tileX == mNumTilesX - 1 ) && ( mImageWidth != mTileWidth * mNumTilesX ) ) ? ( mImageWidth % mTileWidth ) : mTileWidth; int currentTileHeight = ( ( tileY == mNumTilesY - 1 ) && ( mImageHeight != mTileHeight * mNumTilesY ) ) ? ( mImageHeight % mTileHeight ) : mTileHeight; mCurrentArea.x1 = tileX * mTileWidth; mCurrentArea.x2 = mCurrentArea.x1 + currentTileWidth; mCurrentArea.y1 = tileY * mTileHeight; mCurrentArea.y2 = mCurrentArea.y1 + currentTileHeight; update(); mCurrentTile++; return true; } void Tiler::setMatricesWindowPersp( int screenWidth, int screenHeight, float fovDegrees, float nearPlane, float farPlane ) { CameraPersp cam( screenWidth, screenHeight, fovDegrees, nearPlane, farPlane ); setMatrices( cam ); } void Tiler::setMatricesWindow( int32_t windowWidth, int32_t windowHeight ) { ortho( 0, (float)windowWidth, (float)windowHeight, 0, -1.0f, 1.0f ); } void Tiler::frustum( float left, float right, float bottom, float top, float nearPlane, float farPlane ) { mCurrentFrustumCoords = Rectf( vec2( left, top ), vec2( right, bottom ) ); mCurrentFrustumNear = nearPlane; mCurrentFrustumFar = farPlane; mCurrentFrustumPersp = true; } void Tiler::ortho( float left, float right, float bottom, float top, float nearPlane, float farPlane ) { mCurrentFrustumCoords = Rectf( vec2( left, top ), vec2( right, bottom ) ); mCurrentFrustumNear = nearPlane; mCurrentFrustumFar = farPlane; mCurrentFrustumPersp = false; } bool Tiler::getAlpha() { return mAlpha; } ci::Surface Tiler::getSurface() { while ( nextTile() ) { } return mSurface; } void Tiler::setDrawBgFn( const std::function<void( glm::vec2, glm::vec2, glm::vec2, glm::vec2 )> &drawBgFn ) { mDrawBgFn = drawBgFn; } void Tiler::setDrawFn( const std::function<void()> &drawFn ) { mDrawFn = drawFn; } void Tiler::setDrawHudFn( const std::function<void( glm::vec2, glm::vec2, glm::vec2, glm::vec2 )> &drawHudFn ) { mDrawHudFn = drawHudFn; } void Tiler::setMatrices( const CameraPersp &camera ) { mCamera = camera; float left, top, right, bottom, nearPlane, farPlane; camera.getFrustum( &left, &top, &right, &bottom, &nearPlane, &farPlane ); if( camera.isPersp() ) { frustum( left, right, bottom, top, nearPlane, farPlane ); } else { ortho( left, right, bottom, top, nearPlane, farPlane ); } } void Tiler::update() { if( mAlpha ) { mFboRef->bindFramebuffer(); gl::clear( ColorA( 0.0f, 0.0f, 0.0f, 0.0f ) ); } float sx = (float) mCurrentArea.x1 / (float) mImageWidth; float sy = (float) mCurrentArea.y1 / (float) mImageHeight; float ex = (float) mCurrentArea.x2 / (float) mImageWidth; float ey = (float) mCurrentArea.y2 / (float) mImageHeight; vec2 ul = vec2(sx, sy); vec2 ur = vec2(ex, sy); vec2 lr = vec2(ex, ey); vec2 ll = vec2(sx, ey); float left = mCurrentFrustumCoords.x1 + mCurrentArea.x1 / (float)mImageWidth * mCurrentFrustumCoords.getWidth(); float right = left + mCurrentArea.getWidth() / (float)mImageWidth * mCurrentFrustumCoords.getWidth(); float top = mCurrentFrustumCoords.y1 + mCurrentArea.y1 / (float)mImageHeight * mCurrentFrustumCoords.getHeight(); float bottom = top + mCurrentArea.getHeight() / (float)mImageHeight * mCurrentFrustumCoords.getHeight(); if( mDrawBgFn ) { gl::pushMatrices(); gl::pushViewport(); gl::viewport( mCurrentArea.getSize() ); mDrawBgFn( ul, ur, lr, ll ); gl::popViewport(); gl::popMatrices(); } CameraPersp cam = mCamera; gl::pushMatrices(); gl::pushViewport(); gl::viewport( mCurrentArea.getSize() ); gl::pushProjectionMatrix(); if( mCurrentFrustumPersp ) { gl::setProjectionMatrix( glm::frustum( left, right, bottom, top, mCurrentFrustumNear, mCurrentFrustumFar ) ); } else { gl::setProjectionMatrix( glm::ortho( left, right, bottom, top, mCurrentFrustumNear, mCurrentFrustumFar ) ); } gl::pushViewMatrix(); gl::setViewMatrix( cam.getViewMatrix() ); if( mDrawFn ) { mDrawFn(); } gl::popViewMatrix(); gl::popProjectionMatrix(); gl::popViewport(); gl::popMatrices(); if( mDrawHudFn ) { mDrawHudFn( ul, ur, lr, ll ); } if( mAlpha ) { mFboRef->unbindFramebuffer(); } }<commit_msg>fixed bug: tiler without alpha was not capturing the last tile<commit_after>#include "Tiler.h" #include "cinder/gl/gl.h" #include "cinder/app/App.h" #include "cinder/Rand.h" #include <algorithm> #include <sstream> using namespace reza::tiler; using namespace cinder; using namespace glm; using namespace std; Tiler::Tiler( int32_t imageWidth, int32_t imageHeight, int32_t tileWidth, int32_t tileHeight, ci::app::WindowRef window, bool alpha ) : mImageWidth( app::toPixels( imageWidth ) ), mImageHeight( app::toPixels( imageHeight ) ), mWindowRef( window ), mDrawFn( nullptr ), mDrawBgFn( nullptr ), mDrawHudFn( nullptr ), mAlpha( alpha ) { mWindowWidth = app::toPixels( mWindowRef->getWidth() ); mWindowHeight = app::toPixels( mWindowRef->getHeight() ); mTileWidth = std::min( ( int32_t ) app::toPixels( tileWidth ), mWindowWidth ); mTileHeight = std::min( ( int32_t ) app::toPixels( tileHeight ), mWindowHeight ); mNumTilesX = ( int32_t ) ceil( mImageWidth / (float)mTileWidth ); mNumTilesY = ( int32_t ) ceil( mImageHeight / (float)mTileHeight ); mCurrentTile = -1; if( mAlpha ) { mFboRef = gl::Fbo::create( mWindowWidth, mWindowHeight, mAlpha ); mFboRef->bindFramebuffer(); gl::clear( ColorA( 0.0f, 0.0f, 0.0f, 0.0f ) ); mFboRef->unbindFramebuffer(); } } bool Tiler::nextTile() { if( mCurrentTile == mNumTilesX * mNumTilesY ) { if( mAlpha ) { mSurface.copyFrom( mFboRef->readPixels8u( Area( ivec2( 0 ) , ci::app::toPixels( mWindowRef->getSize() ) ), mCurrentArea.getHeight() ), Area( 0, 0, mCurrentArea.getWidth(), mCurrentArea.getHeight() ), mCurrentArea.getUL() ); } else { mSurface.copyFrom( mWindowRef->getRenderer()->copyWindowSurface( Area( ivec2( 0 ) , ci::app::toPixels( mWindowRef->getSize() ) ), mCurrentArea.getHeight() ), Area( 0, 0, mCurrentArea.getWidth(), mCurrentArea.getHeight() ), mCurrentArea.getUL() ); } mCurrentTile = -1; return false; } if( mCurrentTile == -1 ) { mCurrentTile = 0; mSurface = Surface( mImageWidth, mImageHeight, mAlpha ); } else { if( mAlpha ) { mSurface.copyFrom( mFboRef->readPixels8u( Area( ivec2( 0 ) , ci::app::toPixels( mWindowRef->getSize() ) ), mCurrentArea.getHeight() ), Area( 0, 0, mCurrentArea.getWidth(), mCurrentArea.getHeight() ), mCurrentArea.getUL() ); } else { mSurface.copyFrom( mWindowRef->getRenderer()->copyWindowSurface( Area( ivec2( 0 ) , ci::app::toPixels( mWindowRef->getSize() ) ), mCurrentArea.getHeight() ), Area( 0, 0, mCurrentArea.getWidth(), mCurrentArea.getHeight() ), mCurrentArea.getUL() ); } } int tileX = mCurrentTile % mNumTilesX; int tileY = mCurrentTile / mNumTilesX; int currentTileWidth = ( ( tileX == mNumTilesX - 1 ) && ( mImageWidth != mTileWidth * mNumTilesX ) ) ? ( mImageWidth % mTileWidth ) : mTileWidth; int currentTileHeight = ( ( tileY == mNumTilesY - 1 ) && ( mImageHeight != mTileHeight * mNumTilesY ) ) ? ( mImageHeight % mTileHeight ) : mTileHeight; mCurrentArea.x1 = tileX * mTileWidth; mCurrentArea.x2 = mCurrentArea.x1 + currentTileWidth; mCurrentArea.y1 = tileY * mTileHeight; mCurrentArea.y2 = mCurrentArea.y1 + currentTileHeight; update(); mCurrentTile++; return true; } void Tiler::setMatricesWindowPersp( int screenWidth, int screenHeight, float fovDegrees, float nearPlane, float farPlane ) { CameraPersp cam( screenWidth, screenHeight, fovDegrees, nearPlane, farPlane ); setMatrices( cam ); } void Tiler::setMatricesWindow( int32_t windowWidth, int32_t windowHeight ) { ortho( 0, (float)windowWidth, (float)windowHeight, 0, -1.0f, 1.0f ); } void Tiler::frustum( float left, float right, float bottom, float top, float nearPlane, float farPlane ) { mCurrentFrustumCoords = Rectf( vec2( left, top ), vec2( right, bottom ) ); mCurrentFrustumNear = nearPlane; mCurrentFrustumFar = farPlane; mCurrentFrustumPersp = true; } void Tiler::ortho( float left, float right, float bottom, float top, float nearPlane, float farPlane ) { mCurrentFrustumCoords = Rectf( vec2( left, top ), vec2( right, bottom ) ); mCurrentFrustumNear = nearPlane; mCurrentFrustumFar = farPlane; mCurrentFrustumPersp = false; } bool Tiler::getAlpha() { return mAlpha; } ci::Surface Tiler::getSurface() { while ( nextTile() ) { } return mSurface; } void Tiler::setDrawBgFn( const std::function<void( glm::vec2, glm::vec2, glm::vec2, glm::vec2 )> &drawBgFn ) { mDrawBgFn = drawBgFn; } void Tiler::setDrawFn( const std::function<void()> &drawFn ) { mDrawFn = drawFn; } void Tiler::setDrawHudFn( const std::function<void( glm::vec2, glm::vec2, glm::vec2, glm::vec2 )> &drawHudFn ) { mDrawHudFn = drawHudFn; } void Tiler::setMatrices( const CameraPersp &camera ) { mCamera = camera; float left, top, right, bottom, nearPlane, farPlane; camera.getFrustum( &left, &top, &right, &bottom, &nearPlane, &farPlane ); if( camera.isPersp() ) { frustum( left, right, bottom, top, nearPlane, farPlane ); } else { ortho( left, right, bottom, top, nearPlane, farPlane ); } } void Tiler::update() { if( mAlpha ) { mFboRef->bindFramebuffer(); gl::clear( ColorA( 0.0f, 0.0f, 0.0f, 0.0f ) ); } float sx = (float) mCurrentArea.x1 / (float) mImageWidth; float sy = (float) mCurrentArea.y1 / (float) mImageHeight; float ex = (float) mCurrentArea.x2 / (float) mImageWidth; float ey = (float) mCurrentArea.y2 / (float) mImageHeight; vec2 ul = vec2(sx, sy); vec2 ur = vec2(ex, sy); vec2 lr = vec2(ex, ey); vec2 ll = vec2(sx, ey); float left = mCurrentFrustumCoords.x1 + mCurrentArea.x1 / (float)mImageWidth * mCurrentFrustumCoords.getWidth(); float right = left + mCurrentArea.getWidth() / (float)mImageWidth * mCurrentFrustumCoords.getWidth(); float top = mCurrentFrustumCoords.y1 + mCurrentArea.y1 / (float)mImageHeight * mCurrentFrustumCoords.getHeight(); float bottom = top + mCurrentArea.getHeight() / (float)mImageHeight * mCurrentFrustumCoords.getHeight(); if( mDrawBgFn ) { gl::pushMatrices(); gl::pushViewport(); gl::viewport( mCurrentArea.getSize() ); mDrawBgFn( ul, ur, lr, ll ); gl::popViewport(); gl::popMatrices(); } CameraPersp cam = mCamera; gl::pushMatrices(); gl::pushViewport(); gl::viewport( mCurrentArea.getSize() ); gl::pushProjectionMatrix(); if( mCurrentFrustumPersp ) { gl::setProjectionMatrix( glm::frustum( left, right, bottom, top, mCurrentFrustumNear, mCurrentFrustumFar ) ); } else { gl::setProjectionMatrix( glm::ortho( left, right, bottom, top, mCurrentFrustumNear, mCurrentFrustumFar ) ); } gl::pushViewMatrix(); gl::setViewMatrix( cam.getViewMatrix() ); if( mDrawFn ) { mDrawFn(); } gl::popViewMatrix(); gl::popProjectionMatrix(); gl::popViewport(); gl::popMatrices(); if( mDrawHudFn ) { mDrawHudFn( ul, ur, lr, ll ); } if( mAlpha ) { mFboRef->unbindFramebuffer(); } }<|endoftext|>
<commit_before>#ifndef OBJSDL_EVENT_HH #define OBJSDL_EVENT_HH #include <exception> #include <boost/exception/all.hpp> #include <boost/any.hpp> #include <boost/variant.hpp> #include <typeinfo> #include <SDL.h> #include <chrono> #include <unordered_map> #include <functional> struct Window { // TODO: Remove in favour of the real class }; namespace SDL { class Event; namespace _implementation { namespace event { template <typename Variant, typename T, typename... V> Variant get_variant(const Event& ev); } } class OtherEventType : public boost::exception, public std::exception { const char* what() const noexcept; }; struct VoidType { }; class Event { protected: SDL_Event underlying_event; public: Event(); Event(const SDL_Event& ev); Event(SDL_Event&& ev); template <typename T> T* get() { T* casted = dynamic_cast<T*>(*this); if (casted == nullptr) throw OtherEventType{}; return casted; } template <typename... V> boost::variant<V...> get_variant() { return _implementation::event::get_variant<boost::variant<V...>, V...>(*this); } template <typename T> const T* get() const { const T* casted = dynamic_cast<T*>(*this); if (casted == nullptr) throw OtherEventType{}; return casted; } template <typename T> bool holds() const { return dynamic_cast<T*>(*this) != nullptr; } SDL_Event& get(); const SDL_Event& get() const; std::chrono::system_clock::time_point timestamp() const; Window& window() const; size_t window_id() const; virtual bool is_user_defined() const = 0; void push(); }; namespace _implementation { namespace event { template <typename Variant, typename T, typename U, typename... V> Variant get_variant(const Event& ev) { try { return Variant(ev.get<T>()); } catch (OtherEventType) { return get_variant<Variant, U, V...>(ev); } } template <typename Variant, typename T> Variant get_variant(const Event& ev) { return Variant(ev.get<T>()); // can throw } } } template <typename T, typename U=VoidType> class UserEvent : public Event { protected: T& data; U& additional_data; public: UserEvent(const T& data) { this->data = data; } UserEvent(T&& data) { this->data = data; } UserEvent(const T& data, const U& additional_data) { this->data = data; this->additional_data = additional_data; } UserEvent(T&& data, const U& additional_data) { this->data = data; this->additional_data = additional_data; } UserEvent(const T& data, U&& additional_data) { this->data = data; this->additional_data = additional_data; } UserEvent(T&& data, U&& additional_data) { this->data = data; this->additional_data = additional_data; } UserEvent(const SDL_Event& ev) { if (ev.user.data1 != nullptr) this->data = *((T*) ev.user.data1); if (typeid(U) != typeid(VoidType) && ev.user.data2 != nullptr) this->additional_data = *((T*) ev.user.data2); } bool is_user_defined() const { return true; } }; class BuiltinEvent : public Event { using Event::Event; bool is_user_defined() const; }; namespace events { class QuitEvent : public BuiltinEvent { using BuiltinEvent::BuiltinEvent; QuitEvent(); }; } extern const std::unordered_map<size_t, std::function<Event*(SDL_Event)>> event_types; extern std::unordered_map<size_t, std::function<Event*(SDL_Event)>> user_types; template <typename T> size_t register_user_event( std::function<Event*(SDL_Event)> f = [](SDL_Event ev){ return new T(ev); } ) { for (size_t id = 0; true; ++id) if (user_types.find(id) == user_types.end()) user_types[id] = f; } } // includes to special event types; they follow here to guarantee that the BuiltinEvent type is existent. #endif <commit_msg>Linked window_event in event<commit_after>#ifndef OBJSDL_EVENT_HH #define OBJSDL_EVENT_HH #include <exception> #include <boost/exception/all.hpp> #include <boost/any.hpp> #include <boost/variant.hpp> #include <typeinfo> #include <SDL.h> #include <chrono> #include <unordered_map> #include <functional> struct Window { // TODO: Remove in favour of the real class }; namespace SDL { class Event; namespace _implementation { namespace event { template <typename Variant, typename T, typename... V> Variant get_variant(const Event& ev); } } class OtherEventType : public boost::exception, public std::exception { const char* what() const noexcept; }; struct VoidType { }; class Event { protected: SDL_Event underlying_event; public: Event(); Event(const SDL_Event& ev); Event(SDL_Event&& ev); template <typename T> T* get() { T* casted = dynamic_cast<T*>(*this); if (casted == nullptr) throw OtherEventType{}; return casted; } template <typename... V> boost::variant<V...> get_variant() { return _implementation::event::get_variant<boost::variant<V...>, V...>(*this); } template <typename T> const T* get() const { const T* casted = dynamic_cast<T*>(*this); if (casted == nullptr) throw OtherEventType{}; return casted; } template <typename T> bool holds() const { return dynamic_cast<T*>(*this) != nullptr; } SDL_Event& get(); const SDL_Event& get() const; std::chrono::system_clock::time_point timestamp() const; Window& window() const; size_t window_id() const; virtual bool is_user_defined() const = 0; void push(); }; namespace _implementation { namespace event { template <typename Variant, typename T, typename U, typename... V> Variant get_variant(const Event& ev) { try { return Variant(ev.get<T>()); } catch (OtherEventType) { return get_variant<Variant, U, V...>(ev); } } template <typename Variant, typename T> Variant get_variant(const Event& ev) { return Variant(ev.get<T>()); // can throw } } } template <typename T, typename U=VoidType> class UserEvent : public Event { protected: T& data; U& additional_data; public: UserEvent(const T& data) { this->data = data; } UserEvent(T&& data) { this->data = data; } UserEvent(const T& data, const U& additional_data) { this->data = data; this->additional_data = additional_data; } UserEvent(T&& data, const U& additional_data) { this->data = data; this->additional_data = additional_data; } UserEvent(const T& data, U&& additional_data) { this->data = data; this->additional_data = additional_data; } UserEvent(T&& data, U&& additional_data) { this->data = data; this->additional_data = additional_data; } UserEvent(const SDL_Event& ev) { if (ev.user.data1 != nullptr) this->data = *((T*) ev.user.data1); if (typeid(U) != typeid(VoidType) && ev.user.data2 != nullptr) this->additional_data = *((T*) ev.user.data2); } bool is_user_defined() const { return true; } }; class BuiltinEvent : public Event { using Event::Event; bool is_user_defined() const; }; namespace events { class QuitEvent : public BuiltinEvent { using BuiltinEvent::BuiltinEvent; QuitEvent(); }; } extern const std::unordered_map<size_t, std::function<Event*(SDL_Event)>> event_types; extern std::unordered_map<size_t, std::function<Event*(SDL_Event)>> user_types; template <typename T> size_t register_user_event( std::function<Event*(SDL_Event)> f = [](SDL_Event ev){ return new T(ev); } ) { for (size_t id = 0; true; ++id) if (user_types.find(id) == user_types.end()) user_types[id] = f; } } // includes to special event types; they follow here to guarantee that the BuiltinEvent type is existent. #include "window_event.hh" #endif <|endoftext|>
<commit_before>#include "fileIndex.h" #include "utils/logger.h" #include <locale> #include <algorithm> #include <physfs.h> #include <cstring> #include "../lib/physfs/extras/ignorecase.h" using namespace VDFS; FileIndex::FileIndex() { } FileIndex::~FileIndex() { if (PHYSFS_isInit()) PHYSFS_deinit(); } void FileIndex::Init(const char *argv0) { if (!PHYSFS_isInit()) PHYSFS_init(argv0); } /** * @brief Loads a VDF-File and initializes everything */ bool FileIndex::loadVDF(const std::string& vdf, uint32_t priority, const std::string& mountPoint) { if (!PHYSFS_mount(vdf.c_str(), mountPoint.c_str(), 1)) { LogInfo() << "Couldn't load VDF-Archive " << vdf << ": " << PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode()); return false; } return true; } /** * @brief Fills a vector with the data of the given file */ bool FileIndex::getFileData(const std::string& file, std::vector<uint8_t>& data) const { char* filePathBuffer = new char[file.length() + 1]; memcpy(filePathBuffer, file.c_str(), file.length() + 1); bool exists = PHYSFSEXT_locateCorrectCase(filePathBuffer) == 0; if (!exists) { delete filePathBuffer; return false; } PHYSFS_File *handle = PHYSFS_openRead(filePathBuffer); if (!handle) { LogInfo() << "Cannot read file " << file << ": " << PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode()); delete filePathBuffer; return false; } auto length = PHYSFS_fileLength(handle); data.resize(length); if (PHYSFS_readBytes(handle, data.data(), length) < length) { LogInfo() << "Cannot read file " << file << ": " << PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode()); PHYSFS_close(handle); delete filePathBuffer; return false; } delete filePathBuffer; PHYSFS_close(handle); return true; } bool FileIndex::hasFile(const std::string& name) const { char* filePathBuffer = new char[name.length() + 1]; memcpy(filePathBuffer, name.c_str(), name.length() + 1); bool exists = PHYSFSEXT_locateCorrectCase(filePathBuffer) == 0; delete filePathBuffer; return exists; } std::vector<std::string> FileIndex::getKnownFiles(const std::string& path) const { std::vector<std::string> vec; char* filePathBuffer = new char[path.length() + 1]; memcpy(filePathBuffer, path.c_str(), path.length() + 1); bool exists = PHYSFSEXT_locateCorrectCase(filePathBuffer) == 0; if (!exists) { delete filePathBuffer; return vec; } char **files = PHYSFS_enumerateFiles(filePathBuffer); char **i; for (i = files; *i != NULL; i++) vec.push_back(*i); PHYSFS_freeList(files); delete filePathBuffer; return vec; } <commit_msg>Use vectors instead of `new`<commit_after>#include "fileIndex.h" #include "utils/logger.h" #include <locale> #include <algorithm> #include <physfs.h> #include "../lib/physfs/extras/ignorecase.h" using namespace VDFS; FileIndex::FileIndex() { } FileIndex::~FileIndex() { if (PHYSFS_isInit()) PHYSFS_deinit(); } void FileIndex::Init(const char *argv0) { if (!PHYSFS_isInit()) PHYSFS_init(argv0); } /** * @brief Loads a VDF-File and initializes everything */ bool FileIndex::loadVDF(const std::string& vdf, uint32_t priority, const std::string& mountPoint) { if (!PHYSFS_mount(vdf.c_str(), mountPoint.c_str(), 1)) { LogInfo() << "Couldn't load VDF-Archive " << vdf << ": " << PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode()); return false; } return true; } /** * @brief Fills a vector with the data of the given file */ bool FileIndex::getFileData(const std::string& file, std::vector<uint8_t>& data) const { std::vector<char> filePath(file.begin(), file.end()); filePath.push_back('\0'); bool exists = PHYSFSEXT_locateCorrectCase(filePath.data()) == 0; if (!exists) return false; PHYSFS_File *handle = PHYSFS_openRead(filePath.data()); if (!handle) { LogInfo() << "Cannot read file " << file << ": " << PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode()); return false; } auto length = PHYSFS_fileLength(handle); data.resize(length); if (PHYSFS_readBytes(handle, data.data(), length) < length) { LogInfo() << "Cannot read file " << file << ": " << PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode()); PHYSFS_close(handle); return false; } PHYSFS_close(handle); return true; } bool FileIndex::hasFile(const std::string& name) const { std::vector<char> filePath(name.begin(), name.end()); filePath.push_back('\0'); bool exists = PHYSFSEXT_locateCorrectCase(filePath.data()) == 0; return exists; } std::vector<std::string> FileIndex::getKnownFiles(const std::string& path) const { std::vector<std::string> vec; std::vector<char> filePath(path.begin(), path.end()); filePath.push_back('\0'); bool exists = PHYSFSEXT_locateCorrectCase(filePath.data()) == 0; if (!exists) return vec; char **files = PHYSFS_enumerateFiles(filePath.data()); char **i; for (i = files; *i != NULL; i++) vec.push_back(*i); PHYSFS_freeList(files); return vec; } <|endoftext|>
<commit_before>#pragma once #include <cstdint> #include <string> #include <boost/asio.hpp> #include "backend.hpp" #include "blackhole/utils/unique.hpp" #include "connect.hpp" namespace blackhole { namespace sink { namespace socket { template<> class boost_backend_t<boost::asio::ip::udp> { typedef boost::asio::ip::udp Protocol; const std::string m_host; boost::asio::io_service m_io_service; std::unique_ptr<Protocol::socket> m_socket; public: boost_backend_t(const std::string& host, std::uint16_t port) : m_host(host), m_socket(initialize(m_io_service, host, port)) { } static const char* name() { return "udp"; } ssize_t write(const std::string& message) { return m_socket->send(boost::asio::buffer(message.data(), message.size())); } private: static inline std::unique_ptr<Protocol::socket> initialize(boost::asio::io_service& io_service, const std::string& host, std::uint16_t port) { auto socket = utils::make_unique<Protocol::socket>(io_service); connect<Protocol>(io_service, *socket.get(), host, port); return socket; } }; } // namespace socket } // namespace sink } // namespace blackhole <commit_msg>[Code Clean] The similar refactoring over udp backend.<commit_after>#pragma once #include <cstdint> #include <string> #include <boost/asio.hpp> #include "backend.hpp" #include "blackhole/utils/unique.hpp" #include "connect.hpp" namespace blackhole { namespace sink { namespace socket { template<> class boost_backend_t<boost::asio::ip::udp> { public: typedef boost::asio::ip::udp protocol_type; typedef protocol_type::socket socket_type; private: const std::string host; boost::asio::io_service service; std::unique_ptr<socket_type> socket; public: boost_backend_t(std::string host, std::uint16_t port) : host(std::move(host)), socket(initialize(service, this->host, port)) { } static const char* name() { return "udp"; } ssize_t write(const std::string& message) { return socket->send(boost::asio::buffer(message.data(), message.size())); } private: static inline std::unique_ptr<protocol_type::socket> initialize(boost::asio::io_service& service, const std::string& host, std::uint16_t port) { auto socket = utils::make_unique<protocol_type::socket>(service); connect<protocol_type>(service, *socket, host, port); return socket; } }; } // namespace socket } // namespace sink } // namespace blackhole <|endoftext|>
<commit_before>/********************************************************************* * * Condor ClassAd library * Copyright (C) 1990-2001, CONDOR Team, Computer Sciences Department, * University of Wisconsin-Madison, WI, and Rajesh Raman. * * This library is free software; you can redistribute it and/or * modify it under the terms of version 2.1 of the GNU Lesser General * Public License as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * *********************************************************************/ #include "common.h" #include "xmlSource.h" #include "xmlLexer.h" #include "classad.h" #include "source.h" BEGIN_NAMESPACE( classad ) ClassAdXMLParser:: ClassAdXMLParser () { return; } ClassAdXMLParser:: ~ClassAdXMLParser () { return; } bool ClassAdXMLParser:: ParseClassAd( const string &buffer, ClassAd &classad, int &offset) { return false; } ClassAd *ClassAdXMLParser:: ParseClassAd( const string &buffer, int &offset) { ClassAd *classad; lexer.SetLexText(buffer); classad = ParseClassAd(); return classad; } ClassAd *ClassAdXMLParser:: ParseClassAd(void) { bool in_classad; ClassAd *classad; XMLLexer::Token token; classad = NULL; in_classad = false; while (lexer.PeekToken(&token)) { if (!in_classad) { lexer.ConsumeToken(NULL); if ( token.token_type == XMLLexer::tokenType_Tag && token.tag_id == XMLLexer::tagID_ClassAd) { // We have a ClassAd tag if (token.tag_type == XMLLexer::tagType_Start) { in_classad = true; classad = new ClassAd(); } else { // We're done, return the ClassAd we got, if any. break; } } } else { if ( token.token_type == XMLLexer::tokenType_Tag) { if ( token.tag_id == XMLLexer::tagID_Attribute && token.tag_type == XMLLexer::tagType_Start) { string attribute_name; ExprTree *tree; tree = ParseAttribute(attribute_name); if (tree != NULL) { classad->Insert(attribute_name, tree); } } else if ( token.tag_id != XMLLexer::tagID_XML && token.tag_id != XMLLexer::tagID_XMLStylesheet && token.tag_id != XMLLexer::tagID_Doctype) { // We got a non-attribute, non-xml thingy within a // ClassAd. That must be an error, but we'll just skip // it in the hopes of recovering. lexer.ConsumeToken(NULL); break; } } } } return classad; } ExprTree *ClassAdXMLParser:: ParseAttribute( string &attribute_name) { bool have_token; ExprTree *tree; XMLLexer::Token token; tree = NULL; lexer.ConsumeToken(&token); assert(token.tag_id == XMLLexer::tagID_Attribute); if (token.tag_type != XMLLexer::tagType_Start) { attribute_name = ""; } else { attribute_name = token.attributes["n"]; if (attribute_name != "") { tree = ParseThing(); } have_token = lexer.PeekToken(&token); if (have_token && token.token_type == XMLLexer::tokenType_Tag && token.tag_id == XMLLexer::tagID_Attribute && token.tag_type == XMLLexer::tagType_End) { lexer.ConsumeToken(&token); } else { // It's probably invalid XML, but we'll keep on going in // the hope of figuring out something reasonable. } } return tree; } ExprTree *ClassAdXMLParser:: ParseThing(void) { ExprTree *tree; XMLLexer::Token token; lexer.PeekToken(&token); if (token.token_type == XMLLexer::tokenType_Tag) { switch (token.tag_id) { case XMLLexer::tagID_ClassAd: tree = ParseClassAd(); break; case XMLLexer::tagID_List: tree = ParseList(); break; case XMLLexer::tagID_Number: case XMLLexer::tagID_String: tree = ParseNumberOrString(token.tag_id); break; case XMLLexer::tagID_Bool: tree = ParseBool(); break; case XMLLexer::tagID_Undefined: case XMLLexer::tagID_Error: tree = ParseUndefinedOrError(token.tag_id); break; case XMLLexer::tagID_Time: tree = ParseTime(); break; case XMLLexer::tagID_Expr: tree = ParseExpr(); break; default: break; } } return tree; } ExprTree *ClassAdXMLParser:: ParseList(void) { bool have_token; ExprTree *tree; ExprTree *subtree; XMLLexer::Token token; vector<ExprTree*> expressions; tree = NULL; have_token = lexer.ConsumeToken(&token); assert(have_token && token.tag_id == XMLLexer::tagID_List); while (lexer.PeekToken(&token)) { if ( token.token_type == XMLLexer::tokenType_Tag && token.tag_type == XMLLexer::tagType_End && token.tag_id == XMLLexer::tagID_List) { // We're at the end of the list lexer.ConsumeToken(NULL); break; } else if ( token.token_type == XMLLexer::tokenType_Tag && token.tag_type != XMLLexer::tagType_End) { subtree = ParseThing(); expressions.push_back(subtree); } } tree = ExprList::MakeExprList(expressions); return tree; } ExprTree *ClassAdXMLParser:: ParseNumberOrString(XMLLexer::TagID tag_id) { bool have_token; ExprTree *tree; XMLLexer::Token token; // Get start tag tree = NULL; have_token = lexer.ConsumeToken(&token); assert(have_token && token.tag_id == tag_id); // Get text of number or string have_token = lexer.PeekToken(&token); if (have_token && token.token_type == XMLLexer::tokenType_Text) { lexer.ConsumeToken(&token); Value value; if (tag_id == XMLLexer::tagID_Number) { if (strchr(token.text.c_str(), '.')) { // This is a floating point number float number; sscanf(token.text.c_str(), "%g", &number); value.SetRealValue(number); } else { // This is an integer. int number; sscanf(token.text.c_str(), "%d", &number); value.SetIntegerValue(number); } } else { value.SetStringValue(token.text); } tree = Literal::MakeLiteral(value); } // Get end tag have_token = lexer.PeekToken(&token); if (have_token && token.token_type == XMLLexer::tokenType_Tag && token.tag_id == tag_id && token.tag_type == XMLLexer::tagType_End) { lexer.ConsumeToken(&token); } else { // It's probably invalid XML, but we'll keep on going in // the hope of figuring out something reasonable. } return tree; } ExprTree *ClassAdXMLParser:: ParseBool(void) { bool have_token; ExprTree *tree; XMLLexer::Token token; tree = NULL; lexer.ConsumeToken(&token); assert(token.tag_id == XMLLexer::tagID_Bool); Value value; string truth_value = token.attributes["v"]; if (truth_value == "t" || truth_value == "T") { value.SetBooleanValue(true); } else { value.SetBooleanValue(false); } tree = Literal::MakeLiteral(value); if (token.tag_type == XMLLexer::tagType_Start) { // They had a start token, so swallow the // end token. have_token = lexer.PeekToken(&token); if (have_token && token.token_type == XMLLexer::tokenType_Tag && token.tag_id == XMLLexer::tagID_Bool && token.tag_type == XMLLexer::tagType_End) { lexer.ConsumeToken(&token); } else { // It's probably invalid XML, but we'll keep on going in // the hope of figuring out something reasonable. } } return tree; } ExprTree *ClassAdXMLParser:: ParseUndefinedOrError(XMLLexer::TagID tag_id) { bool have_token; ExprTree *tree; XMLLexer::Token token; tree = NULL; lexer.ConsumeToken(&token); assert(token.tag_id == tag_id); Value value; if (tag_id == XMLLexer::tagID_Undefined) { value.SetUndefinedValue(); } else { value.SetErrorValue(); } tree = Literal::MakeLiteral(value); if (token.tag_type == XMLLexer::tagType_Start) { // They had a start token, so swallow the // end token. have_token = lexer.PeekToken(&token); if (have_token && token.token_type == XMLLexer::tokenType_Tag && token.tag_id == tag_id && token.tag_type == XMLLexer::tagType_End) { lexer.ConsumeToken(&token); } else { // It's probably invalid XML, but we'll keep on going in // the hope of figuring out something reasonable. } } return tree; } ExprTree *ClassAdXMLParser:: ParseTime(void) { ExprTree *tree; XMLLexer::Token token; tree = NULL; lexer.ConsumeToken(&token); assert(token.tag_id == XMLLexer::tagID_Time); // We haven't yet finished this functionality. assert(0); return tree; } ExprTree *ClassAdXMLParser:: ParseExpr(void) { bool have_token; ExprTree *tree; XMLLexer::Token token; // Get start tag tree = NULL; have_token = lexer.ConsumeToken(&token); assert(have_token && token.tag_id == XMLLexer::tagID_Expr); // Get text of expression have_token = lexer.PeekToken(&token); if (have_token && token.token_type == XMLLexer::tokenType_Text) { lexer.ConsumeToken(&token); ClassAdParser parser; tree = parser.ParseExpression(token.text, true); } // Get end tag have_token = lexer.PeekToken(&token); if (have_token && token.token_type == XMLLexer::tokenType_Tag && token.tag_id == XMLLexer::tagID_Expr && token.tag_type == XMLLexer::tagType_End) { lexer.ConsumeToken(&token); } else { // It's probably invalid XML, but we'll keep on going in // the hope of figuring out something reasonable. } return tree; } END_NAMESPACE // classad <commit_msg>Now ignore <classads> tag.<commit_after>/********************************************************************* * * Condor ClassAd library * Copyright (C) 1990-2001, CONDOR Team, Computer Sciences Department, * University of Wisconsin-Madison, WI, and Rajesh Raman. * * This library is free software; you can redistribute it and/or * modify it under the terms of version 2.1 of the GNU Lesser General * Public License as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * *********************************************************************/ #include "common.h" #include "xmlSource.h" #include "xmlLexer.h" #include "classad.h" #include "source.h" BEGIN_NAMESPACE( classad ) ClassAdXMLParser:: ClassAdXMLParser () { return; } ClassAdXMLParser:: ~ClassAdXMLParser () { return; } bool ClassAdXMLParser:: ParseClassAd( const string &buffer, ClassAd &classad, int &offset) { return false; } ClassAd *ClassAdXMLParser:: ParseClassAd( const string &buffer, int &offset) { ClassAd *classad; lexer.SetLexText(buffer); classad = ParseClassAd(); return classad; } ClassAd *ClassAdXMLParser:: ParseClassAd(void) { bool in_classad; ClassAd *classad; XMLLexer::Token token; classad = NULL; in_classad = false; while (lexer.PeekToken(&token)) { if (!in_classad) { lexer.ConsumeToken(NULL); if ( token.token_type == XMLLexer::tokenType_Tag && token.tag_id == XMLLexer::tagID_ClassAd) { // We have a ClassAd tag if (token.tag_type == XMLLexer::tagType_Start) { in_classad = true; classad = new ClassAd(); } else { // We're done, return the ClassAd we got, if any. break; } } } else { if ( token.token_type == XMLLexer::tokenType_Tag) { if ( token.tag_id == XMLLexer::tagID_Attribute && token.tag_type == XMLLexer::tagType_Start) { string attribute_name; ExprTree *tree; tree = ParseAttribute(attribute_name); if (tree != NULL) { classad->Insert(attribute_name, tree); } } else if ( token.tag_id != XMLLexer::tagID_XML && token.tag_id != XMLLexer::tagID_XMLStylesheet && token.tag_id != XMLLexer::tagID_Doctype && token.tag_id != XMLLexer::tagID_ClassAds) { // We got a non-attribute, non-xml thingy within a // ClassAd. That must be an error, but we'll just skip // it in the hopes of recovering. lexer.ConsumeToken(NULL); break; } } } } return classad; } ExprTree *ClassAdXMLParser:: ParseAttribute( string &attribute_name) { bool have_token; ExprTree *tree; XMLLexer::Token token; tree = NULL; lexer.ConsumeToken(&token); assert(token.tag_id == XMLLexer::tagID_Attribute); if (token.tag_type != XMLLexer::tagType_Start) { attribute_name = ""; } else { attribute_name = token.attributes["n"]; if (attribute_name != "") { tree = ParseThing(); } have_token = lexer.PeekToken(&token); if (have_token && token.token_type == XMLLexer::tokenType_Tag && token.tag_id == XMLLexer::tagID_Attribute && token.tag_type == XMLLexer::tagType_End) { lexer.ConsumeToken(&token); } else { // It's probably invalid XML, but we'll keep on going in // the hope of figuring out something reasonable. } } return tree; } ExprTree *ClassAdXMLParser:: ParseThing(void) { ExprTree *tree; XMLLexer::Token token; lexer.PeekToken(&token); if (token.token_type == XMLLexer::tokenType_Tag) { switch (token.tag_id) { case XMLLexer::tagID_ClassAd: tree = ParseClassAd(); break; case XMLLexer::tagID_List: tree = ParseList(); break; case XMLLexer::tagID_Number: case XMLLexer::tagID_String: tree = ParseNumberOrString(token.tag_id); break; case XMLLexer::tagID_Bool: tree = ParseBool(); break; case XMLLexer::tagID_Undefined: case XMLLexer::tagID_Error: tree = ParseUndefinedOrError(token.tag_id); break; case XMLLexer::tagID_Time: tree = ParseTime(); break; case XMLLexer::tagID_Expr: tree = ParseExpr(); break; default: break; } } return tree; } ExprTree *ClassAdXMLParser:: ParseList(void) { bool have_token; ExprTree *tree; ExprTree *subtree; XMLLexer::Token token; vector<ExprTree*> expressions; tree = NULL; have_token = lexer.ConsumeToken(&token); assert(have_token && token.tag_id == XMLLexer::tagID_List); while (lexer.PeekToken(&token)) { if ( token.token_type == XMLLexer::tokenType_Tag && token.tag_type == XMLLexer::tagType_End && token.tag_id == XMLLexer::tagID_List) { // We're at the end of the list lexer.ConsumeToken(NULL); break; } else if ( token.token_type == XMLLexer::tokenType_Tag && token.tag_type != XMLLexer::tagType_End) { subtree = ParseThing(); expressions.push_back(subtree); } } tree = ExprList::MakeExprList(expressions); return tree; } ExprTree *ClassAdXMLParser:: ParseNumberOrString(XMLLexer::TagID tag_id) { bool have_token; ExprTree *tree; XMLLexer::Token token; // Get start tag tree = NULL; have_token = lexer.ConsumeToken(&token); assert(have_token && token.tag_id == tag_id); // Get text of number or string have_token = lexer.PeekToken(&token); if (have_token && token.token_type == XMLLexer::tokenType_Text) { lexer.ConsumeToken(&token); Value value; if (tag_id == XMLLexer::tagID_Number) { if (strchr(token.text.c_str(), '.')) { // This is a floating point number float number; sscanf(token.text.c_str(), "%g", &number); value.SetRealValue(number); } else { // This is an integer. int number; sscanf(token.text.c_str(), "%d", &number); value.SetIntegerValue(number); } } else { value.SetStringValue(token.text); } tree = Literal::MakeLiteral(value); } // Get end tag have_token = lexer.PeekToken(&token); if (have_token && token.token_type == XMLLexer::tokenType_Tag && token.tag_id == tag_id && token.tag_type == XMLLexer::tagType_End) { lexer.ConsumeToken(&token); } else { // It's probably invalid XML, but we'll keep on going in // the hope of figuring out something reasonable. } return tree; } ExprTree *ClassAdXMLParser:: ParseBool(void) { bool have_token; ExprTree *tree; XMLLexer::Token token; tree = NULL; lexer.ConsumeToken(&token); assert(token.tag_id == XMLLexer::tagID_Bool); Value value; string truth_value = token.attributes["v"]; if (truth_value == "t" || truth_value == "T") { value.SetBooleanValue(true); } else { value.SetBooleanValue(false); } tree = Literal::MakeLiteral(value); if (token.tag_type == XMLLexer::tagType_Start) { // They had a start token, so swallow the // end token. have_token = lexer.PeekToken(&token); if (have_token && token.token_type == XMLLexer::tokenType_Tag && token.tag_id == XMLLexer::tagID_Bool && token.tag_type == XMLLexer::tagType_End) { lexer.ConsumeToken(&token); } else { // It's probably invalid XML, but we'll keep on going in // the hope of figuring out something reasonable. } } return tree; } ExprTree *ClassAdXMLParser:: ParseUndefinedOrError(XMLLexer::TagID tag_id) { bool have_token; ExprTree *tree; XMLLexer::Token token; tree = NULL; lexer.ConsumeToken(&token); assert(token.tag_id == tag_id); Value value; if (tag_id == XMLLexer::tagID_Undefined) { value.SetUndefinedValue(); } else { value.SetErrorValue(); } tree = Literal::MakeLiteral(value); if (token.tag_type == XMLLexer::tagType_Start) { // They had a start token, so swallow the // end token. have_token = lexer.PeekToken(&token); if (have_token && token.token_type == XMLLexer::tokenType_Tag && token.tag_id == tag_id && token.tag_type == XMLLexer::tagType_End) { lexer.ConsumeToken(&token); } else { // It's probably invalid XML, but we'll keep on going in // the hope of figuring out something reasonable. } } return tree; } ExprTree *ClassAdXMLParser:: ParseTime(void) { ExprTree *tree; XMLLexer::Token token; tree = NULL; lexer.ConsumeToken(&token); assert(token.tag_id == XMLLexer::tagID_Time); // We haven't yet finished this functionality. assert(0); return tree; } ExprTree *ClassAdXMLParser:: ParseExpr(void) { bool have_token; ExprTree *tree; XMLLexer::Token token; // Get start tag tree = NULL; have_token = lexer.ConsumeToken(&token); assert(have_token && token.tag_id == XMLLexer::tagID_Expr); // Get text of expression have_token = lexer.PeekToken(&token); if (have_token && token.token_type == XMLLexer::tokenType_Text) { lexer.ConsumeToken(&token); ClassAdParser parser; tree = parser.ParseExpression(token.text, true); } // Get end tag have_token = lexer.PeekToken(&token); if (have_token && token.token_type == XMLLexer::tokenType_Tag && token.tag_id == XMLLexer::tagID_Expr && token.tag_type == XMLLexer::tagType_End) { lexer.ConsumeToken(&token); } else { // It's probably invalid XML, but we'll keep on going in // the hope of figuring out something reasonable. } return tree; } END_NAMESPACE // classad <|endoftext|>
<commit_before>/* ** Copyright 1993 by Miron Livny, and Mike Litzkow ** ** Permission to use, copy, modify, and distribute this software and its ** documentation for any purpose and without fee is hereby granted, ** provided that the above copyright notice appear in all copies and that ** both that copyright notice and this permission notice appear in ** supporting documentation, and that the names of the University of ** Wisconsin and the copyright holders not be used in advertising or ** publicity pertaining to distribution of the software without specific, ** written prior permission. The University of Wisconsin and the ** copyright holders make no representations about the suitability of this ** software for any purpose. It is provided "as is" without express ** or implied warranty. ** ** THE UNIVERSITY OF WISCONSIN AND THE COPYRIGHT HOLDERS DISCLAIM ALL ** WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES ** OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE UNIVERSITY OF ** WISCONSIN OR THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT ** OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS ** OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE ** OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE ** OR PERFORMANCE OF THIS SOFTWARE. ** ** Author: Mike Litzkow ** */ /* Portability The code in this file is not POSIX.1 conforming, and is therefore not generally portable. However, this code is generally portable across UNIX platforms with little or no modification. */ #define _POSIX_SOURCE #if defined(ULTRIX42) || defined(ULTRIX43) typedef char * caddr_t; #endif #include "condor_common.h" #include "condor_debug.h" #include "condor_jobqueue.h" #include "condor_sys.h" #include <signal.h> #include <sys/stat.h> #if defined(LINUX) #include <unistd.h> typedef long rlim_t; #endif extern "C" { int SetSyscalls( int ); } static char *_FileName_ = __FILE__; /* Used by EXCEPT (see except.h) */ /* Controlling any of these limits is problematic because the system calls setrlimit() and getrlimit() do not appear in POSIX.1, but leaving them to chance in environments where they appear is unacceptable. Defaults limits will frequently be handed down by some shell whose initialization file has been set up by the system administrator. These will often not be appropriate for condor operation. For example the administrator may have set the limit for COREDUMPSIZE to 0. Additional complication results from the fact that various platforms define different sets of limits which may be set. Here we define a routine for setting an individual limit. Code in platform specific files will call this routine to set up limits as appropriate for that platform. */ void limit( int resource, rlim_t new_limit ) { int scm; struct rlimit lim; scm = SetSyscalls( SYS_LOCAL | SYS_RECORDED ); /* Find out current limits */ if( getrlimit(resource,&lim) < 0 ) { EXCEPT( "getrlimit(%d,0x%x)", resource, &lim ); } /* Don't try to exceed the max */ if( new_limit > lim.rlim_max ) { new_limit = lim.rlim_max; } /* Set the new limit */ lim.rlim_cur = new_limit; if( setrlimit(resource,&lim) < 0 ) { EXCEPT( "setrlimit(%d,0x%x)", resource, &lim ); } (void)SetSyscalls( scm ); } /* ** Return physical file size in 1024 byte units. This is the number of ** 1024 byte blocks required to store the file. This could be more than the ** number of blocks of data due to overhead imposed by the file system ** structure (indirect blocks). It could also be less than the ** number of data blocks if the filesystem implements "gaps" in the file ** without allocating real disk blocks to them. This is a traditional ** behavior for UNIX file systems, but is optional in POSIX. ** ** The POSIX definition of "struct stat" does not define any member ** which describes the physical storage requirements of the file, but ** many UNIX systems do have such a member in their stat structure. ** Generally the name of this member is "st_blocks", but the size of ** the blocks is not often documented. I have seen some code that uses ** the "st_blocksize" member for this value, but that turns out not to ** be generally correct. The following interpretations come from comparing ** the stat structures associated with actual files against the storage ** requirements of those files as reported by "ls -ls". */ off_t physical_file_size( char *name ) { struct stat buf; if( stat(name,&buf) < 0 ) { return (off_t)-1; } #if defined(AIX32) || defined(ULTRIX42) || defined(ULTRIX43) || defined(SUNOS41)|| defined(OSF1) || defined(Solaris) || defined(IRIX53) /* On these systems struct stat member st_blocks is defined, and appears to be in 512 byte blocks. */ return buf.st_blocks / 2; #elif defined(HPUX9) || defined(LINUX) /* On this systems struct stat member st_blocks is defined, and appears to be in 1024 byte blocks. */ return buf.st_blocks; #elif defined(IRIX401) /* On this system struct stat member st_blocks is not defined. Also, it appears that gaps take up real blocks here. We just return the number of blocks to store the data. Probably there will be some overhead, but it's not clear how to determine what it is, so we ignore it. */ return (buf.st_size + 1023 ) / 1024; #else # error "Don't know how to determine file size on this platform." #endif } #include "condor_fix_wait.h" #include <errno.h> #include "condor_constants.h" #include "startup.h" #include "user_proc.h" #ifdef __cplusplus extern "C" { #endif /* * macros for setting stat */ #if !defined(_POSIX_C_SOURCE) && !defined(_XOPEN_SOURCE) #define SETCOREDUMP(stat, flag) ((int)((flag) ? ((stat) | WCOREFLG) \ : ((stat) & (~(WCOREFLG))))) #endif /* !defined(_POSIX_C_SOURCE) && !defined(_XOPEN_SOURCE) */ #define SETEXITSTATUS(stat, flag) ((int)(((stat) & 0xFFFF00FF) | \ ((flag) << 8))) #define SETTERMSIG(stat, flag) ((int)(((stat) & 0xFFFFFF80) | \ ((flag) & 0x7F))) #ifdef __cplusplus } #endif /* Encode the status of a user process in the way the shadow is expecting it. The encoding is a BSD style "union wait" structure with the exit status of the process and a few goodies thrown in for special cases. We keep the encoding in a static memory area and return a pointer to it as a "void *" so that POSIX code doesn't have to know about it. Changed the union wait to int to be POSIX conformant - 12/01/97 */ void * bsd_status( int posix_st, PROC_STATE state, int ckpt_trans, int core_trans ) { static int bsd_status; memcpy( &bsd_status, &posix_st, sizeof(bsd_status) ); switch( state ) { case EXECUTING: EXCEPT( "Tried to generate BSD status, but state is EXECUTING\n" ); break; case SUSPENDED: EXCEPT( "Tried to generate BSD status, but state is SUSPENDED\n" ); break; case NORMAL_EXIT: dprintf( D_ALWAYS, "STATUS encoded as NORMAL\n" ); break; case NEW: case RUNNABLE: case NON_RUNNABLE: case CHECKPOINTING: case CANT_FETCH: if( ckpt_trans ) { bsd_status = SETTERMSIG(bsd_status, SIGQUIT); dprintf( D_ALWAYS, "STATUS encoded as CKPT, *IS* TRANSFERRED\n" ); } else { bsd_status = SETTERMSIG(bsd_status, SIGKILL); dprintf( D_ALWAYS, "STATUS encoded as CKPT, *NOT* TRANSFERRED\n" ); } break; case ABNORMAL_EXIT: if( core_trans ) { bsd_status = SETCOREDUMP(bsd_status, 1); dprintf( D_ALWAYS, "STATUS encoded as ABNORMAL, WITH CORE\n" ); } else { bsd_status = SETCOREDUMP(bsd_status, 0); dprintf( D_ALWAYS, "STATUS encoded as ABNORMAL, NO CORE\n" ); } break; case BAD_MAGIC: bsd_status = SETTERMSIG(bsd_status, 0); bsd_status = SETCOREDUMP(bsd_status, 1); bsd_status = SETEXITSTATUS(bsd_status, ENOEXEC); dprintf( D_ALWAYS, "STATUS encoded as BAD MAGIC\n" ); break; case BAD_LINK: bsd_status = SETTERMSIG(bsd_status, 0); bsd_status = SETCOREDUMP(bsd_status, 1); bsd_status = SETEXITSTATUS(bsd_status, 0); dprintf( D_ALWAYS, "STATUS encoded as BAD LINK\n" ); break; /* case CANT_FETCH: bsd_status = SETTERMSIG(bsd_status, 0); bsd_status = SETCOREDUMP(bsd_status, 1); bsd_status = SETEXITSTATUS(bsd_status, posix_st); */ } return (void *)&bsd_status; } #include <sys/resource.h> #define _POSIX_SOURCE #include <time.h> // to get CLK_TCK #undef _POSIX_SOURCE /* Convert a time value from the POSIX style "clock_t" to a BSD style "struct timeval". */ void clock_t_to_timeval( clock_t ticks, struct timeval &tv ) { static long clock_tick; if( !clock_tick ) { clock_tick = sysconf( _SC_CLK_TCK ); } tv.tv_sec = ticks / clock_tick; tv.tv_usec = ticks % clock_tick; tv.tv_usec *= 1000000 / clock_tick; } /* Encode the CPU usage statistics in a BSD style "rusage" structure. The structure contains much more information than just CPU times, but we zero everything except the CPU information because POSIX doesn't provide it. We return a pointer to a static data area as a "void *" so POSIX code doesn't have to know about it. */ void * bsd_rusage( clock_t user, clock_t sys ) { static struct rusage bsd_rusage; int sec, usec; memset( &bsd_rusage, '\0', sizeof(bsd_rusage) ); clock_t_to_timeval( user, bsd_rusage.ru_utime ); clock_t_to_timeval( sys, bsd_rusage.ru_stime ); dprintf( D_ALWAYS, "User time = %d.%06d seconds\n", bsd_rusage.ru_utime.tv_sec, bsd_rusage.ru_utime.tv_usec ); dprintf( D_ALWAYS, "System time = %d.%06d seconds\n", bsd_rusage.ru_stime.tv_sec, bsd_rusage.ru_stime.tv_usec ); return (void *)&bsd_rusage; } /* Tell the operating system that we want to operate in "POSIX conforming mode". Isn't it ironic that such a request is itself non-POSIX conforming? */ #if defined(ULTRIX42) || defined(ULTRIX43) #include <sys/sysinfo.h> #define A_POSIX 2 // from exec.h, which I prefer not to include here... extern "C" { int setsysinfo( unsigned, char *, unsigned, unsigned, unsigned ); } void set_posix_environment() { int name_value[2]; name_value[0] = SSIN_PROG_ENV; name_value[1] = A_POSIX; if( setsysinfo(SSI_NVPAIRS,(char *)name_value,1,0,0) < 0 ) { EXCEPT( "setsysinfo" ); } } #else void set_posix_environment() {} #endif <commit_msg>Removed the checks for !POSIX_SOURCE around the definition of SETCOREDUMP since they're not needed (and cause problems)<commit_after>/* ** Copyright 1993 by Miron Livny, and Mike Litzkow ** ** Permission to use, copy, modify, and distribute this software and its ** documentation for any purpose and without fee is hereby granted, ** provided that the above copyright notice appear in all copies and that ** both that copyright notice and this permission notice appear in ** supporting documentation, and that the names of the University of ** Wisconsin and the copyright holders not be used in advertising or ** publicity pertaining to distribution of the software without specific, ** written prior permission. The University of Wisconsin and the ** copyright holders make no representations about the suitability of this ** software for any purpose. It is provided "as is" without express ** or implied warranty. ** ** THE UNIVERSITY OF WISCONSIN AND THE COPYRIGHT HOLDERS DISCLAIM ALL ** WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES ** OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE UNIVERSITY OF ** WISCONSIN OR THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT ** OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS ** OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE ** OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE ** OR PERFORMANCE OF THIS SOFTWARE. ** ** Author: Mike Litzkow ** */ /* Portability The code in this file is not POSIX.1 conforming, and is therefore not generally portable. However, this code is generally portable across UNIX platforms with little or no modification. */ #define _POSIX_SOURCE #if defined(ULTRIX42) || defined(ULTRIX43) typedef char * caddr_t; #endif #include "condor_common.h" #include "condor_debug.h" #include "condor_jobqueue.h" #include "condor_sys.h" #include <signal.h> #include <sys/stat.h> #if defined(LINUX) #include <unistd.h> typedef long rlim_t; #endif extern "C" { int SetSyscalls( int ); } static char *_FileName_ = __FILE__; /* Used by EXCEPT (see except.h) */ /* Controlling any of these limits is problematic because the system calls setrlimit() and getrlimit() do not appear in POSIX.1, but leaving them to chance in environments where they appear is unacceptable. Defaults limits will frequently be handed down by some shell whose initialization file has been set up by the system administrator. These will often not be appropriate for condor operation. For example the administrator may have set the limit for COREDUMPSIZE to 0. Additional complication results from the fact that various platforms define different sets of limits which may be set. Here we define a routine for setting an individual limit. Code in platform specific files will call this routine to set up limits as appropriate for that platform. */ void limit( int resource, rlim_t new_limit ) { int scm; struct rlimit lim; scm = SetSyscalls( SYS_LOCAL | SYS_RECORDED ); /* Find out current limits */ if( getrlimit(resource,&lim) < 0 ) { EXCEPT( "getrlimit(%d,0x%x)", resource, &lim ); } /* Don't try to exceed the max */ if( new_limit > lim.rlim_max ) { new_limit = lim.rlim_max; } /* Set the new limit */ lim.rlim_cur = new_limit; if( setrlimit(resource,&lim) < 0 ) { EXCEPT( "setrlimit(%d,0x%x)", resource, &lim ); } (void)SetSyscalls( scm ); } /* ** Return physical file size in 1024 byte units. This is the number of ** 1024 byte blocks required to store the file. This could be more than the ** number of blocks of data due to overhead imposed by the file system ** structure (indirect blocks). It could also be less than the ** number of data blocks if the filesystem implements "gaps" in the file ** without allocating real disk blocks to them. This is a traditional ** behavior for UNIX file systems, but is optional in POSIX. ** ** The POSIX definition of "struct stat" does not define any member ** which describes the physical storage requirements of the file, but ** many UNIX systems do have such a member in their stat structure. ** Generally the name of this member is "st_blocks", but the size of ** the blocks is not often documented. I have seen some code that uses ** the "st_blocksize" member for this value, but that turns out not to ** be generally correct. The following interpretations come from comparing ** the stat structures associated with actual files against the storage ** requirements of those files as reported by "ls -ls". */ off_t physical_file_size( char *name ) { struct stat buf; if( stat(name,&buf) < 0 ) { return (off_t)-1; } #if defined(AIX32) || defined(ULTRIX42) || defined(ULTRIX43) || defined(SUNOS41)|| defined(OSF1) || defined(Solaris) || defined(IRIX53) /* On these systems struct stat member st_blocks is defined, and appears to be in 512 byte blocks. */ return buf.st_blocks / 2; #elif defined(HPUX9) || defined(LINUX) /* On this systems struct stat member st_blocks is defined, and appears to be in 1024 byte blocks. */ return buf.st_blocks; #elif defined(IRIX401) /* On this system struct stat member st_blocks is not defined. Also, it appears that gaps take up real blocks here. We just return the number of blocks to store the data. Probably there will be some overhead, but it's not clear how to determine what it is, so we ignore it. */ return (buf.st_size + 1023 ) / 1024; #else # error "Don't know how to determine file size on this platform." #endif } #include "condor_fix_wait.h" #include <errno.h> #include "condor_constants.h" #include "startup.h" #include "user_proc.h" #ifdef __cplusplus extern "C" { #endif /* * macros for setting stat */ #define SETCOREDUMP(stat, flag) ((int)((flag) ? ((stat) | WCOREFLG) \ : ((stat) & (~(WCOREFLG))))) #define SETEXITSTATUS(stat, flag) ((int)(((stat) & 0xFFFF00FF) | \ ((flag) << 8))) #define SETTERMSIG(stat, flag) ((int)(((stat) & 0xFFFFFF80) | \ ((flag) & 0x7F))) #ifdef __cplusplus } #endif /* Encode the status of a user process in the way the shadow is expecting it. The encoding is a BSD style "union wait" structure with the exit status of the process and a few goodies thrown in for special cases. We keep the encoding in a static memory area and return a pointer to it as a "void *" so that POSIX code doesn't have to know about it. Changed the union wait to int to be POSIX conformant - 12/01/97 */ void * bsd_status( int posix_st, PROC_STATE state, int ckpt_trans, int core_trans ) { static int bsd_status; memcpy( &bsd_status, &posix_st, sizeof(bsd_status) ); switch( state ) { case EXECUTING: EXCEPT( "Tried to generate BSD status, but state is EXECUTING\n" ); break; case SUSPENDED: EXCEPT( "Tried to generate BSD status, but state is SUSPENDED\n" ); break; case NORMAL_EXIT: dprintf( D_ALWAYS, "STATUS encoded as NORMAL\n" ); break; case NEW: case RUNNABLE: case NON_RUNNABLE: case CHECKPOINTING: case CANT_FETCH: if( ckpt_trans ) { bsd_status = SETTERMSIG(bsd_status, SIGQUIT); dprintf( D_ALWAYS, "STATUS encoded as CKPT, *IS* TRANSFERRED\n" ); } else { bsd_status = SETTERMSIG(bsd_status, SIGKILL); dprintf( D_ALWAYS, "STATUS encoded as CKPT, *NOT* TRANSFERRED\n" ); } break; case ABNORMAL_EXIT: if( core_trans ) { bsd_status = SETCOREDUMP(bsd_status, 1); dprintf( D_ALWAYS, "STATUS encoded as ABNORMAL, WITH CORE\n" ); } else { bsd_status = SETCOREDUMP(bsd_status, 0); dprintf( D_ALWAYS, "STATUS encoded as ABNORMAL, NO CORE\n" ); } break; case BAD_MAGIC: bsd_status = SETTERMSIG(bsd_status, 0); bsd_status = SETCOREDUMP(bsd_status, 1); bsd_status = SETEXITSTATUS(bsd_status, ENOEXEC); dprintf( D_ALWAYS, "STATUS encoded as BAD MAGIC\n" ); break; case BAD_LINK: bsd_status = SETTERMSIG(bsd_status, 0); bsd_status = SETCOREDUMP(bsd_status, 1); bsd_status = SETEXITSTATUS(bsd_status, 0); dprintf( D_ALWAYS, "STATUS encoded as BAD LINK\n" ); break; /* case CANT_FETCH: bsd_status = SETTERMSIG(bsd_status, 0); bsd_status = SETCOREDUMP(bsd_status, 1); bsd_status = SETEXITSTATUS(bsd_status, posix_st); */ } return (void *)&bsd_status; } #include <sys/resource.h> #define _POSIX_SOURCE #include <time.h> // to get CLK_TCK #undef _POSIX_SOURCE /* Convert a time value from the POSIX style "clock_t" to a BSD style "struct timeval". */ void clock_t_to_timeval( clock_t ticks, struct timeval &tv ) { static long clock_tick; if( !clock_tick ) { clock_tick = sysconf( _SC_CLK_TCK ); } tv.tv_sec = ticks / clock_tick; tv.tv_usec = ticks % clock_tick; tv.tv_usec *= 1000000 / clock_tick; } /* Encode the CPU usage statistics in a BSD style "rusage" structure. The structure contains much more information than just CPU times, but we zero everything except the CPU information because POSIX doesn't provide it. We return a pointer to a static data area as a "void *" so POSIX code doesn't have to know about it. */ void * bsd_rusage( clock_t user, clock_t sys ) { static struct rusage bsd_rusage; int sec, usec; memset( &bsd_rusage, '\0', sizeof(bsd_rusage) ); clock_t_to_timeval( user, bsd_rusage.ru_utime ); clock_t_to_timeval( sys, bsd_rusage.ru_stime ); dprintf( D_ALWAYS, "User time = %d.%06d seconds\n", bsd_rusage.ru_utime.tv_sec, bsd_rusage.ru_utime.tv_usec ); dprintf( D_ALWAYS, "System time = %d.%06d seconds\n", bsd_rusage.ru_stime.tv_sec, bsd_rusage.ru_stime.tv_usec ); return (void *)&bsd_rusage; } /* Tell the operating system that we want to operate in "POSIX conforming mode". Isn't it ironic that such a request is itself non-POSIX conforming? */ #if defined(ULTRIX42) || defined(ULTRIX43) #include <sys/sysinfo.h> #define A_POSIX 2 // from exec.h, which I prefer not to include here... extern "C" { int setsysinfo( unsigned, char *, unsigned, unsigned, unsigned ); } void set_posix_environment() { int name_value[2]; name_value[0] = SSIN_PROG_ENV; name_value[1] = A_POSIX; if( setsysinfo(SSI_NVPAIRS,(char *)name_value,1,0,0) < 0 ) { EXCEPT( "setsysinfo" ); } } #else void set_posix_environment() {} #endif <|endoftext|>
<commit_before>#include <libgen.h> #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #include <algorithm> #include <iostream> #include "configurator.hpp" #include "common/foreach.hpp" #include "common/params.hpp" #include "common/string_utils.hpp" using namespace mesos::internal; const char* Configurator::DEFAULT_CONFIG_DIR = "conf"; const char* Configurator::CONFIG_FILE_NAME = "mesos.conf"; const char* Configurator::ENV_VAR_PREFIX = "MESOS_"; // Define a function for accessing the list of environment variables // in a platform-independent way. // On Mac OS X, the environ symbol isn't visible to shared libraries, // so we must use the _NSGetEnviron() function (see man environ on OS X). // On other platforms, it's fine to access environ from shared libraries. #ifdef __APPLE__ #include "crt_externs.h" namespace { char** getEnviron() { return *_NSGetEnviron(); } } #else extern char** environ; namespace { char** getEnviron() { return environ; } } #endif /* __APPLE__ */ Configurator::Configurator() { addOption<string>("conf", "Specifies a config directory from which to\n" "read Mesos config files. The Mesos binaries\n" "use <install location>src/conf by default"); } void Configurator::validate() { foreachpair (const string& key, const Option& opt, options) { if (params.contains(key) && opt.validator && !opt.validator->isValid(params[key])) { string msg = "Invalid value for '" + key + "' option: " + params[key]; throw ConfigurationException(msg.c_str()); } } } Params& Configurator::load(int argc, char** argv, bool inferMesosHomeFromArg0) { loadEnv(); loadCommandLine(argc, argv, inferMesosHomeFromArg0); loadConfigFileIfGiven(); loadDefaults(); validate(); return params; } Params& Configurator::load() { loadEnv(); loadConfigFileIfGiven(); loadDefaults(); validate(); return params; } Params& Configurator::load(const map<string, string>& _params) { loadEnv(); params.loadMap(_params); loadConfigFileIfGiven(); loadDefaults(); validate(); return params; } void Configurator::loadConfigFileIfGiven(bool overwrite) { if (params.contains("conf")) { // If conf param is given, always look for a config file in that directory string confDir = params["conf"]; loadConfigFile(confDir + "/" + CONFIG_FILE_NAME, overwrite); } else if (params.contains("home")) { // Grab config file in MESOS_HOME/conf, if it exists string confDir = params["home"] + "/" + DEFAULT_CONFIG_DIR; string confFile = confDir + "/" + CONFIG_FILE_NAME; struct stat st; if (stat(confFile.c_str(), &st) == 0) { loadConfigFile(confFile, overwrite); } } } void Configurator::loadEnv(bool overwrite) { char** environ = getEnviron(); int i = 0; while (environ[i] != NULL) { string line = environ[i]; if (line.find(ENV_VAR_PREFIX) == 0) { string key, val; size_t eq = line.find_first_of("="); if (eq == string::npos) continue; // ignore malformed lines (they shouldn't occur in environ!) key = line.substr(strlen(ENV_VAR_PREFIX), eq - strlen(ENV_VAR_PREFIX)); std::transform(key.begin(), key.end(), key.begin(), ::tolower); val = line.substr(eq + 1); // Disallow setting home through the environment, because it should // always be resolved from the running Mesos binary (if any) if ((overwrite || !params.contains(key)) && key != "home") { params[key] = val; } } i++; } } void Configurator::loadCommandLine(int argc, char** argv, bool inferMesosHomeFromArg0, bool overwrite) { // Set home based on argument 0 if asked to do so if (inferMesosHomeFromArg0) { // Copy argv[0] because dirname can modify it int lengthOfArg0 = strlen(argv[0]); char* copyOfArg0 = new char[lengthOfArg0 + 1]; strncpy(copyOfArg0, argv[0], lengthOfArg0 + 1); // Get its directory, and then the parent of that directory string myDir = string(dirname(copyOfArg0)); string parentDir = myDir + "/.."; // Get the real name of this parent directory char path[PATH_MAX]; if (realpath(parentDir.c_str(), path) == 0) { throw ConfigurationException( "Could not resolve MESOS_HOME from argv[0] -- realpath failed"); } params["home"] = path; delete[] copyOfArg0; } // Convert args 1 and above to STL strings vector<string> args; for (int i=1; i < argc; i++) { args.push_back(string(argv[i])); } for (int i = 0; i < args.size(); i++) { string key, val; bool set = false; if (args[i].find("--", 0) == 0) { // handle "--" case size_t eq = args[i].find_first_of("="); if (eq == string::npos && args[i].find("--no-", 0) == 0) { // handle --no-blah key = args[i].substr(5); val = "0"; set = true; checkCommandLineParamFormat(key, true); } else if (eq == string::npos) { // handle --blah key = args[i].substr(2); val = "1"; set = true; checkCommandLineParamFormat(key, true); } else { // handle --blah=25 key = args[i].substr(2, eq-2); val = args[i].substr(eq+1); set = true; checkCommandLineParamFormat(key, false); } } else if (args[i].find_first_of("-", 0) == 0 && args[i].size() > 1) { // handle "-" case char shortName = '\0'; if (args[i].find("-no-",0) == 0 && args[i].size() == 5) { shortName = args[i][4]; } else if (args[i].size() == 2) { shortName = args[i][1]; } if (shortName == '\0' || getLongName(shortName) == "") { string message = "Short option '" + args[i] + "' unrecognized "; throw ConfigurationException(message.c_str()); } key = getLongName(shortName); if (args[i].find("-no-",0) == 0) { // handle -no-b val = "0"; set = true; checkCommandLineParamFormat(key, true); } else if (options[key].validator->isBool() || i+1 == args.size() ) { // handle -b val = "1"; set = true; checkCommandLineParamFormat(key, true); } else { // handle -b 25 val = args[i+1]; set = true; i++; // we've consumed next parameter as a "value"-parameter } } std::transform(key.begin(), key.end(), key.begin(), ::tolower); // Disallow setting "home" since it should only be inferred from // the location of the running Mesos binary (if any) if (set && (overwrite || !params.contains(key)) && key != "home") { params[key] = val; } } } void Configurator::loadConfigFile(const string& fname, bool overwrite) { ifstream cfg(fname.c_str(), std::ios::in); if (!cfg.is_open()) { string message = "Couldn't read Mesos config file: " + fname; throw ConfigurationException(message.c_str()); } string line, originalLine; while (!cfg.eof()) { getline(cfg, line); originalLine = line; // Strip any comment at end of line size_t hash = line.find_first_of("#"); // strip comments if (hash != string::npos) { line = line.substr(0, hash); } // Check for empty line line = StringUtils::trim(line); if (line == "") { continue; } // Split line by = and trim to get key and value vector<string> tokens; StringUtils::split(line, "=", &tokens); if (tokens.size() != 2) { string message = "Malformed line in config file: '" + StringUtils::trim(originalLine) + "'"; throw ConfigurationException(message.c_str()); } string key = StringUtils::trim(tokens[0]); string value = StringUtils::trim(tokens[1]); // Disallow setting "home" since it should only be inferred from // the location of the running Mesos binary (if any) if ((overwrite || !params.contains(key)) && key != "home") { params[key] = value; } } cfg.close(); } string Configurator::getUsage() const { const int PAD = 5; string usage; map<string,string> col1; // key -> col 1 string int maxLen = 0; // construct string for the first column and get size of column foreachpair (const string& key, const Option& opt, options) { string val = " --" + key; if (!opt.validator->isBool()) val += "=VAL"; if (opt.hasShortName) { if (opt.validator->isBool()) val += string(" (or -") + opt.shortName + " or -no-" + opt.shortName + ")"; else val += string(" (or -") + opt.shortName + " VAL)"; } else if (opt.validator->isBool()) val += " (--no-" + key + ")"; col1[key] = val; maxLen = val.size() > maxLen ? val.size() : maxLen; } foreachpair (const string& key, const Option& opt, options) { string helpStr = opt.helpString; string line = col1[key]; if (opt.defaultValue != "") { // add default value // Place a space between help string and (default: VAL) if the // help string does not end with a newline itself size_t lastNewLine = helpStr.find_last_of("\n\r"); if (helpStr.size() > 0 && lastNewLine != helpStr.size() - 1) { helpStr += " "; } string defval = opt.defaultValue; if (opt.validator->isBool()) defval = opt.defaultValue == "0" ? "false" : "true"; helpStr += "(default: " + defval + ")"; } string pad(PAD + maxLen - line.size(), ' '); line += pad; size_t pos1 = 0, pos2 = 0; pos2 = helpStr.find_first_of("\n\r", pos1); line += helpStr.substr(pos1, pos2 - pos1) + "\n"; usage += line; while(pos2 != string::npos) { // handle multi line help strings line = ""; pos1 = pos2 + 1; string pad2(PAD + maxLen, ' '); line += pad2; pos2 = helpStr.find_first_of("\n\r", pos1); line += helpStr.substr(pos1, pos2 - pos1) + "\n"; usage += line; } } return usage; } void Configurator::loadDefaults() { foreachpair (const string& key, const Option& option, options) { if (option.hasDefault && !params.contains(key)) { params[key] = option.defaultValue; } } } vector<string> Configurator::getOptions() const { vector<string> ret; foreachpair (const string& key, _, options) { ret.push_back(key); } return ret; } Params& Configurator::getParams() { return params; } string Configurator::getLongName(char shortName) const { foreachpair (const string& key, const Option& opt, options) { if (opt.hasShortName && opt.shortName == shortName) return key; } return ""; } void Configurator::clearMesosEnvironmentVars() { char** environ = getEnviron(); int i = 0; vector<string> toRemove; while (environ[i] != NULL) { string line = environ[i]; if (line.find(ENV_VAR_PREFIX) == 0) { string key; size_t eq = line.find_first_of("="); if (eq == string::npos) continue; // ignore malformed lines (they shouldn't occur in environ!) key = line.substr(strlen(ENV_VAR_PREFIX), eq - strlen(ENV_VAR_PREFIX)); toRemove.push_back(key); } i++; } foreach (string& str, toRemove) { unsetenv(str.c_str()); } } void Configurator::checkCommandLineParamFormat(const string& key, bool gotBool) throw(ConfigurationException) { if (options.find(key) != options.end() && options[key].validator->isBool() != gotBool) { string message = "Option '" + key + "' should "; if (gotBool) message += "not "; message += "be a boolean."; throw ConfigurationException(message.c_str()); } } void Configurator::dumpToGoogleLog() { LOG(INFO) << "Dumping configuration options:"; const map<string, string>& paramsMap = params.getMap(); foreachpair (const string& key, const string& val, paramsMap) { LOG(INFO) << " " << key << " = " << val; } LOG(INFO) << "End configuration dump"; } <commit_msg>Random syntax fix.<commit_after>#include <libgen.h> #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #include <algorithm> #include <iostream> #include "configurator.hpp" #include "common/foreach.hpp" #include "common/params.hpp" #include "common/string_utils.hpp" using namespace mesos::internal; const char* Configurator::DEFAULT_CONFIG_DIR = "conf"; const char* Configurator::CONFIG_FILE_NAME = "mesos.conf"; const char* Configurator::ENV_VAR_PREFIX = "MESOS_"; // Define a function for accessing the list of environment variables // in a platform-independent way. // On Mac OS X, the environ symbol isn't visible to shared libraries, // so we must use the _NSGetEnviron() function (see man environ on OS X). // On other platforms, it's fine to access environ from shared libraries. #ifdef __APPLE__ #include "crt_externs.h" namespace { char** getEnviron() { return *_NSGetEnviron(); } } #else extern char** environ; namespace { char** getEnviron() { return environ; } } #endif /* __APPLE__ */ Configurator::Configurator() { addOption<string>("conf", "Specifies a config directory from which to\n" "read Mesos config files. The Mesos binaries\n" "use <install location>src/conf by default"); } void Configurator::validate() { foreachpair (const string& key, const Option& opt, options) { if (params.contains(key) && opt.validator && !opt.validator->isValid(params[key])) { string msg = "Invalid value for '" + key + "' option: " + params[key]; throw ConfigurationException(msg.c_str()); } } } Params& Configurator::load(int argc, char** argv, bool inferMesosHomeFromArg0) { loadEnv(); loadCommandLine(argc, argv, inferMesosHomeFromArg0); loadConfigFileIfGiven(); loadDefaults(); validate(); return params; } Params& Configurator::load() { loadEnv(); loadConfigFileIfGiven(); loadDefaults(); validate(); return params; } Params& Configurator::load(const map<string, string>& _params) { loadEnv(); params.loadMap(_params); loadConfigFileIfGiven(); loadDefaults(); validate(); return params; } void Configurator::loadConfigFileIfGiven(bool overwrite) { if (params.contains("conf")) { // If conf param is given, always look for a config file in that directory string confDir = params["conf"]; loadConfigFile(confDir + "/" + CONFIG_FILE_NAME, overwrite); } else if (params.contains("home")) { // Grab config file in MESOS_HOME/conf, if it exists string confDir = params["home"] + "/" + DEFAULT_CONFIG_DIR; string confFile = confDir + "/" + CONFIG_FILE_NAME; struct stat st; if (stat(confFile.c_str(), &st) == 0) { loadConfigFile(confFile, overwrite); } } } void Configurator::loadEnv(bool overwrite) { char** environ = getEnviron(); int i = 0; while (environ[i] != NULL) { string line = environ[i]; if (line.find(ENV_VAR_PREFIX) == 0) { string key, val; size_t eq = line.find_first_of("="); if (eq == string::npos) continue; // ignore malformed lines (they shouldn't occur in environ!) key = line.substr(strlen(ENV_VAR_PREFIX), eq - strlen(ENV_VAR_PREFIX)); std::transform(key.begin(), key.end(), key.begin(), ::tolower); val = line.substr(eq + 1); // Disallow setting home through the environment, because it should // always be resolved from the running Mesos binary (if any) if ((overwrite || !params.contains(key)) && key != "home") { params[key] = val; } } i++; } } void Configurator::loadCommandLine(int argc, char** argv, bool inferMesosHomeFromArg0, bool overwrite) { // Set home based on argument 0 if asked to do so if (inferMesosHomeFromArg0) { // Copy argv[0] because dirname can modify it int lengthOfArg0 = strlen(argv[0]); char* copyOfArg0 = new char[lengthOfArg0 + 1]; strncpy(copyOfArg0, argv[0], lengthOfArg0 + 1); // Get its directory, and then the parent of that directory string myDir = string(dirname(copyOfArg0)); string parentDir = myDir + "/.."; // Get the real name of this parent directory char path[PATH_MAX]; if (realpath(parentDir.c_str(), path) == 0) { throw ConfigurationException( "Could not resolve MESOS_HOME from argv[0] -- realpath failed"); } params["home"] = path; delete[] copyOfArg0; } // Convert args 1 and above to STL strings vector<string> args; for (int i=1; i < argc; i++) { args.push_back(string(argv[i])); } for (int i = 0; i < args.size(); i++) { string key, val; bool set = false; if (args[i].find("--", 0) == 0) { // handle "--" case size_t eq = args[i].find_first_of("="); if (eq == string::npos && args[i].find("--no-", 0) == 0) { // handle --no-blah key = args[i].substr(5); val = "0"; set = true; checkCommandLineParamFormat(key, true); } else if (eq == string::npos) { // handle --blah key = args[i].substr(2); val = "1"; set = true; checkCommandLineParamFormat(key, true); } else { // handle --blah=25 key = args[i].substr(2, eq-2); val = args[i].substr(eq+1); set = true; checkCommandLineParamFormat(key, false); } } else if (args[i].find_first_of("-", 0) == 0 && args[i].size() > 1) { // handle "-" case char shortName = '\0'; if (args[i].find("-no-",0) == 0 && args[i].size() == 5) { shortName = args[i][4]; } else if (args[i].size() == 2) { shortName = args[i][1]; } if (shortName == '\0' || getLongName(shortName) == "") { string message = "Short option '" + args[i] + "' unrecognized "; throw ConfigurationException(message.c_str()); } key = getLongName(shortName); if (args[i].find("-no-",0) == 0) { // handle -no-b val = "0"; set = true; checkCommandLineParamFormat(key, true); } else if (options[key].validator->isBool() || i+1 == args.size() ) { // handle -b val = "1"; set = true; checkCommandLineParamFormat(key, true); } else { // handle -b 25 val = args[i+1]; set = true; i++; // we've consumed next parameter as a "value"-parameter } } std::transform(key.begin(), key.end(), key.begin(), ::tolower); // Disallow setting "home" since it should only be inferred from // the location of the running Mesos binary (if any) if (set && (overwrite || !params.contains(key)) && key != "home") { params[key] = val; } } } void Configurator::loadConfigFile(const string& fname, bool overwrite) { ifstream cfg(fname.c_str(), std::ios::in); if (!cfg.is_open()) { string message = "Couldn't read Mesos config file: " + fname; throw ConfigurationException(message.c_str()); } string line, originalLine; while (!cfg.eof()) { getline(cfg, line); originalLine = line; // Strip any comment at end of line size_t hash = line.find_first_of("#"); // strip comments if (hash != string::npos) { line = line.substr(0, hash); } // Check for empty line line = StringUtils::trim(line); if (line == "") { continue; } // Split line by = and trim to get key and value vector<string> tokens; StringUtils::split(line, "=", &tokens); if (tokens.size() != 2) { string message = "Malformed line in config file: '" + StringUtils::trim(originalLine) + "'"; throw ConfigurationException(message.c_str()); } string key = StringUtils::trim(tokens[0]); string value = StringUtils::trim(tokens[1]); // Disallow setting "home" since it should only be inferred from // the location of the running Mesos binary (if any) if ((overwrite || !params.contains(key)) && key != "home") { params[key] = value; } } cfg.close(); } string Configurator::getUsage() const { const int PAD = 5; string usage; map<string,string> col1; // key -> col 1 string int maxLen = 0; // construct string for the first column and get size of column foreachpair (const string& key, const Option& opt, options) { string val = " --" + key; if (!opt.validator->isBool()) val += "=VAL"; if (opt.hasShortName) { if (opt.validator->isBool()) val += string(" (or -") + opt.shortName + " or -no-" + opt.shortName + ")"; else val += string(" (or -") + opt.shortName + " VAL)"; } else if (opt.validator->isBool()) val += " (--no-" + key + ")"; col1[key] = val; maxLen = val.size() > maxLen ? val.size() : maxLen; } foreachpair (const string& key, const Option& opt, options) { string helpStr = opt.helpString; string line = col1[key]; if (opt.defaultValue != "") { // add default value // Place a space between help string and (default: VAL) if the // help string does not end with a newline itself size_t lastNewLine = helpStr.find_last_of("\n\r"); if (helpStr.size() > 0 && lastNewLine != helpStr.size() - 1) { helpStr += " "; } string defval = opt.defaultValue; if (opt.validator->isBool()) defval = opt.defaultValue == "0" ? "false" : "true"; helpStr += "(default: " + defval + ")"; } string pad(PAD + maxLen - line.size(), ' '); line += pad; size_t pos1 = 0, pos2 = 0; pos2 = helpStr.find_first_of("\n\r", pos1); line += helpStr.substr(pos1, pos2 - pos1) + "\n"; usage += line; while(pos2 != string::npos) { // handle multi line help strings line = ""; pos1 = pos2 + 1; string pad2(PAD + maxLen, ' '); line += pad2; pos2 = helpStr.find_first_of("\n\r", pos1); line += helpStr.substr(pos1, pos2 - pos1) + "\n"; usage += line; } } return usage; } void Configurator::loadDefaults() { foreachpair (const string& key, const Option& option, options) { if (option.hasDefault && !params.contains(key)) { params[key] = option.defaultValue; } } } vector<string> Configurator::getOptions() const { vector<string> ret; foreachpair (const string& key, _, options) { ret.push_back(key); } return ret; } Params& Configurator::getParams() { return params; } string Configurator::getLongName(char shortName) const { foreachpair (const string& key, const Option& opt, options) { if (opt.hasShortName && opt.shortName == shortName) return key; } return ""; } void Configurator::clearMesosEnvironmentVars() { char** environ = getEnviron(); int i = 0; vector<string> toRemove; while (environ[i] != NULL) { string line = environ[i]; if (line.find(ENV_VAR_PREFIX) == 0) { string key; size_t eq = line.find_first_of("="); if (eq == string::npos) continue; // ignore malformed lines (they shouldn't occur in environ!) key = line.substr(strlen(ENV_VAR_PREFIX), eq - strlen(ENV_VAR_PREFIX)); toRemove.push_back(key); } i++; } foreach (string& str, toRemove) { unsetenv(str.c_str()); } } void Configurator::checkCommandLineParamFormat(const string& key, bool gotBool) throw(ConfigurationException) { if (options.find(key) != options.end() && options[key].validator->isBool() != gotBool) { string message = "Option '" + key + "' should "; if (gotBool) message += "not "; message += "be a boolean."; throw ConfigurationException(message.c_str()); } } void Configurator::dumpToGoogleLog() { LOG(INFO) << "Dumping configuration options:"; const map<string, string>& paramsMap = params.getMap(); foreachpair (const string& key, const string& val, paramsMap) { LOG(INFO) << " " << key << " = " << val; } LOG(INFO) << "End configuration dump"; } <|endoftext|>
<commit_before>#include <controller/pid_controller.hpp> PIDController::PIDController(float kp, float ki, float kd) : kp(kp), ki(ki), kd(kd), currError(0.0), prevError(0.0), accumError(0.0) { } float PIDController::calculate(float sp, float pv, float dt) { this->prevError = this->currError; this->currError = sp - pv; this->accumError += currError; float p = this->kp * this->currError; float i = this->ki * this->accumError; float d = this->kd * (this->currError - this->prevError) / dt; return p + i + d; } <commit_msg>Remove `this` references in `pid_controller`.<commit_after>#include <controller/pid_controller.hpp> PIDController::PIDController(float kp, float ki, float kd) : kp(kp), ki(ki), kd(kd), currError(0.0), prevError(0.0), accumError(0.0) { } float PIDController::calculate(float sp, float pv, float dt) { prevError = currError; currError = sp - pv; accumError += currError; float p = kp * currError; float i = ki * accumError; float d = kd * (currError - prevError) / dt; return p + i + d; } <|endoftext|>
<commit_before>/* * Copyright (c) 2016-2017, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of the copyright holder 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 HOLDER 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. */ /** * @file * This file implements MechCop TLV helper functions. */ #include "meshcop_tlvs.hpp" #include "common/debug.hpp" #include "common/string.hpp" #include "meshcop/meshcop.hpp" namespace ot { namespace MeshCoP { bool Tlv::IsValid(const Tlv &aTlv) { bool rval = true; switch (aTlv.GetType()) { case Tlv::kChannel: rval = static_cast<const ChannelTlv &>(aTlv).IsValid(); break; case Tlv::kPanId: rval = static_cast<const PanIdTlv &>(aTlv).IsValid(); break; case Tlv::kExtendedPanId: rval = static_cast<const ExtendedPanIdTlv &>(aTlv).IsValid(); break; case Tlv::kNetworkName: rval = static_cast<const NetworkNameTlv &>(aTlv).IsValid(); break; case Tlv::kNetworkMasterKey: rval = static_cast<const NetworkMasterKeyTlv &>(aTlv).IsValid(); break; case Tlv::kPskc: rval = static_cast<const PskcTlv &>(aTlv).IsValid(); break; case Tlv::kMeshLocalPrefix: rval = static_cast<const MeshLocalPrefixTlv &>(aTlv).IsValid(); break; case Tlv::kSecurityPolicy: rval = static_cast<const SecurityPolicyTlv &>(aTlv).IsValid(); break; case Tlv::kChannelMask: rval = static_cast<const ChannelMaskTlv &>(aTlv).IsValid(); break; default: break; } return rval; } const Tlv *Tlv::FindTlv(const uint8_t *aTlvsStart, uint16_t aTlvsLength, Type aType) { const Tlv *tlv; const Tlv *end = reinterpret_cast<const Tlv *>(aTlvsStart + aTlvsLength); for (tlv = reinterpret_cast<const Tlv *>(aTlvsStart); tlv < end; tlv = tlv->GetNext()) { VerifyOrExit((tlv + 1) <= end, tlv = nullptr); VerifyOrExit(!tlv->IsExtended() || (reinterpret_cast<const ExtendedTlv *>(tlv) + 1 <= reinterpret_cast<const ExtendedTlv *>(end)), tlv = nullptr); VerifyOrExit(tlv->GetNext() <= end, tlv = nullptr); if (tlv->GetType() == aType) { ExitNow(); } } tlv = nullptr; exit: return tlv; } Mac::NameData NetworkNameTlv::GetNetworkName(void) const { uint8_t len = GetLength(); if (len > sizeof(mNetworkName)) { len = sizeof(mNetworkName); } return Mac::NameData(mNetworkName, len); } void NetworkNameTlv::SetNetworkName(const Mac::NameData &aNameData) { uint8_t len; len = aNameData.CopyTo(mNetworkName, sizeof(mNetworkName)); SetLength(len); } bool NetworkNameTlv::IsValid(void) const { return IsValidUtf8String(mNetworkName, GetLength()); } void SteeringDataTlv::CopyTo(SteeringData &aSteeringData) const { aSteeringData.Init(GetSteeringDataLength()); memcpy(aSteeringData.GetData(), mSteeringData, GetSteeringDataLength()); } bool ChannelTlv::IsValid(void) const { bool ret = false; VerifyOrExit(GetLength() == sizeof(*this) - sizeof(Tlv)); VerifyOrExit(mChannelPage <= OT_RADIO_CHANNEL_PAGE_MAX); VerifyOrExit((1U << mChannelPage) & Radio::kSupportedChannelPages); VerifyOrExit(Radio::kChannelMin <= GetChannel() && GetChannel() <= Radio::kChannelMax); ret = true; exit: return ret; } void ChannelTlv::SetChannel(uint16_t aChannel) { uint8_t channelPage = OT_RADIO_CHANNEL_PAGE_0; #if OPENTHREAD_CONFIG_RADIO_2P4GHZ_OQPSK_SUPPORT if ((OT_RADIO_2P4GHZ_OQPSK_CHANNEL_MIN <= aChannel) && (aChannel <= OT_RADIO_2P4GHZ_OQPSK_CHANNEL_MAX)) { channelPage = OT_RADIO_CHANNEL_PAGE_0; } #endif #if OPENTHREAD_CONFIG_RADIO_915MHZ_OQPSK_SUPPORT if ((OT_RADIO_915MHZ_OQPSK_CHANNEL_MIN <= aChannel) && (aChannel <= OT_RADIO_915MHZ_OQPSK_CHANNEL_MAX)) { channelPage = OT_RADIO_CHANNEL_PAGE_2; } #endif SetChannelPage(channelPage); mChannel = HostSwap16(aChannel); } bool ChannelMaskBaseTlv::IsValid(void) const { const ChannelMaskEntryBase *entry = GetFirstEntry(); const uint8_t * end = reinterpret_cast<const uint8_t *>(GetNext()); bool ret = false; VerifyOrExit(entry != nullptr); while (reinterpret_cast<const uint8_t *>(entry) + sizeof(ChannelMaskEntryBase) <= end) { entry = entry->GetNext(); VerifyOrExit(reinterpret_cast<const uint8_t *>(entry) <= end); } ret = true; exit: return ret; } const ChannelMaskEntryBase *ChannelMaskBaseTlv::GetFirstEntry(void) const { const ChannelMaskEntryBase *entry = nullptr; VerifyOrExit(GetLength() >= sizeof(ChannelMaskEntryBase)); entry = reinterpret_cast<const ChannelMaskEntryBase *>(GetValue()); VerifyOrExit(GetLength() >= entry->GetEntrySize(), entry = nullptr); exit: return entry; } ChannelMaskEntryBase *ChannelMaskBaseTlv::GetFirstEntry(void) { return const_cast<ChannelMaskEntryBase *>(static_cast<const ChannelMaskBaseTlv *>(this)->GetFirstEntry()); } void ChannelMaskTlv::SetChannelMask(uint32_t aChannelMask) { uint8_t length = 0; ChannelMaskEntry *entry; entry = static_cast<ChannelMaskEntry *>(GetFirstEntry()); #if OPENTHREAD_CONFIG_RADIO_915MHZ_OQPSK_SUPPORT if (aChannelMask & OT_RADIO_915MHZ_OQPSK_CHANNEL_MASK) { OT_ASSERT(entry != nullptr); entry->Init(); entry->SetChannelPage(OT_RADIO_CHANNEL_PAGE_2); entry->SetMask(aChannelMask & OT_RADIO_915MHZ_OQPSK_CHANNEL_MASK); length += sizeof(MeshCoP::ChannelMaskEntry); entry = static_cast<MeshCoP::ChannelMaskEntry *>(entry->GetNext()); } #endif #if OPENTHREAD_CONFIG_RADIO_2P4GHZ_OQPSK_SUPPORT if (aChannelMask & OT_RADIO_2P4GHZ_OQPSK_CHANNEL_MASK) { OT_ASSERT(entry != nullptr); entry->Init(); entry->SetChannelPage(OT_RADIO_CHANNEL_PAGE_0); entry->SetMask(aChannelMask & OT_RADIO_2P4GHZ_OQPSK_CHANNEL_MASK); length += sizeof(MeshCoP::ChannelMaskEntry); } #endif SetLength(length); } uint32_t ChannelMaskTlv::GetChannelMask(void) const { uint32_t mask = 0; const ChannelMaskEntry *cur = static_cast<const ChannelMaskEntry *>(GetFirstEntry()); const ChannelMaskEntry *end = reinterpret_cast<const ChannelMaskEntry *>(GetValue() + GetLength()); for (; cur < end; cur = static_cast<const ChannelMaskEntry *>(cur->GetNext())) { VerifyOrExit((cur + 1) <= end && cur->GetNext() <= end); #if OPENTHREAD_CONFIG_RADIO_915MHZ_OQPSK_SUPPORT if (cur->GetChannelPage() == OT_RADIO_CHANNEL_PAGE_2) { mask |= cur->GetMask() & OT_RADIO_915MHZ_OQPSK_CHANNEL_MASK; } #endif #if OPENTHREAD_CONFIG_RADIO_2P4GHZ_OQPSK_SUPPORT if (cur->GetChannelPage() == OT_RADIO_CHANNEL_PAGE_0) { mask |= cur->GetMask() & OT_RADIO_2P4GHZ_OQPSK_CHANNEL_MASK; } #endif } exit: return mask; } uint32_t ChannelMaskTlv::GetChannelMask(const Message &aMessage) { uint32_t mask = 0; uint16_t offset; uint16_t end; SuccessOrExit(FindTlvValueOffset(aMessage, kChannelMask, offset, end)); end += offset; while (offset + sizeof(ChannelMaskEntryBase) <= end) { ChannelMaskEntry entry; IgnoreError(aMessage.Read(offset, entry)); VerifyOrExit(offset + entry.GetEntrySize() <= end); switch (entry.GetChannelPage()) { #if OPENTHREAD_CONFIG_RADIO_2P4GHZ_OQPSK_SUPPORT case OT_RADIO_CHANNEL_PAGE_0: IgnoreError(aMessage.Read(offset, entry)); mask |= entry.GetMask() & OT_RADIO_2P4GHZ_OQPSK_CHANNEL_MASK; break; #endif #if OPENTHREAD_CONFIG_RADIO_915MHZ_OQPSK_SUPPORT case OT_RADIO_CHANNEL_PAGE_2: IgnoreError(aMessage.Read(offset, entry)); mask |= entry.GetMask() & OT_RADIO_915MHZ_OQPSK_CHANNEL_MASK; break; #endif } offset += entry.GetEntrySize(); } exit: return mask; } } // namespace MeshCoP } // namespace ot <commit_msg>[meshcop-tlv] fix ChannelMaskTlv::GetChannelMask() (#5947)<commit_after>/* * Copyright (c) 2016-2017, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of the copyright holder 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 HOLDER 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. */ /** * @file * This file implements MechCop TLV helper functions. */ #include "meshcop_tlvs.hpp" #include "common/debug.hpp" #include "common/string.hpp" #include "meshcop/meshcop.hpp" namespace ot { namespace MeshCoP { bool Tlv::IsValid(const Tlv &aTlv) { bool rval = true; switch (aTlv.GetType()) { case Tlv::kChannel: rval = static_cast<const ChannelTlv &>(aTlv).IsValid(); break; case Tlv::kPanId: rval = static_cast<const PanIdTlv &>(aTlv).IsValid(); break; case Tlv::kExtendedPanId: rval = static_cast<const ExtendedPanIdTlv &>(aTlv).IsValid(); break; case Tlv::kNetworkName: rval = static_cast<const NetworkNameTlv &>(aTlv).IsValid(); break; case Tlv::kNetworkMasterKey: rval = static_cast<const NetworkMasterKeyTlv &>(aTlv).IsValid(); break; case Tlv::kPskc: rval = static_cast<const PskcTlv &>(aTlv).IsValid(); break; case Tlv::kMeshLocalPrefix: rval = static_cast<const MeshLocalPrefixTlv &>(aTlv).IsValid(); break; case Tlv::kSecurityPolicy: rval = static_cast<const SecurityPolicyTlv &>(aTlv).IsValid(); break; case Tlv::kChannelMask: rval = static_cast<const ChannelMaskTlv &>(aTlv).IsValid(); break; default: break; } return rval; } const Tlv *Tlv::FindTlv(const uint8_t *aTlvsStart, uint16_t aTlvsLength, Type aType) { const Tlv *tlv; const Tlv *end = reinterpret_cast<const Tlv *>(aTlvsStart + aTlvsLength); for (tlv = reinterpret_cast<const Tlv *>(aTlvsStart); tlv < end; tlv = tlv->GetNext()) { VerifyOrExit((tlv + 1) <= end, tlv = nullptr); VerifyOrExit(!tlv->IsExtended() || (reinterpret_cast<const ExtendedTlv *>(tlv) + 1 <= reinterpret_cast<const ExtendedTlv *>(end)), tlv = nullptr); VerifyOrExit(tlv->GetNext() <= end, tlv = nullptr); if (tlv->GetType() == aType) { ExitNow(); } } tlv = nullptr; exit: return tlv; } Mac::NameData NetworkNameTlv::GetNetworkName(void) const { uint8_t len = GetLength(); if (len > sizeof(mNetworkName)) { len = sizeof(mNetworkName); } return Mac::NameData(mNetworkName, len); } void NetworkNameTlv::SetNetworkName(const Mac::NameData &aNameData) { uint8_t len; len = aNameData.CopyTo(mNetworkName, sizeof(mNetworkName)); SetLength(len); } bool NetworkNameTlv::IsValid(void) const { return IsValidUtf8String(mNetworkName, GetLength()); } void SteeringDataTlv::CopyTo(SteeringData &aSteeringData) const { aSteeringData.Init(GetSteeringDataLength()); memcpy(aSteeringData.GetData(), mSteeringData, GetSteeringDataLength()); } bool ChannelTlv::IsValid(void) const { bool ret = false; VerifyOrExit(GetLength() == sizeof(*this) - sizeof(Tlv)); VerifyOrExit(mChannelPage <= OT_RADIO_CHANNEL_PAGE_MAX); VerifyOrExit((1U << mChannelPage) & Radio::kSupportedChannelPages); VerifyOrExit(Radio::kChannelMin <= GetChannel() && GetChannel() <= Radio::kChannelMax); ret = true; exit: return ret; } void ChannelTlv::SetChannel(uint16_t aChannel) { uint8_t channelPage = OT_RADIO_CHANNEL_PAGE_0; #if OPENTHREAD_CONFIG_RADIO_2P4GHZ_OQPSK_SUPPORT if ((OT_RADIO_2P4GHZ_OQPSK_CHANNEL_MIN <= aChannel) && (aChannel <= OT_RADIO_2P4GHZ_OQPSK_CHANNEL_MAX)) { channelPage = OT_RADIO_CHANNEL_PAGE_0; } #endif #if OPENTHREAD_CONFIG_RADIO_915MHZ_OQPSK_SUPPORT if ((OT_RADIO_915MHZ_OQPSK_CHANNEL_MIN <= aChannel) && (aChannel <= OT_RADIO_915MHZ_OQPSK_CHANNEL_MAX)) { channelPage = OT_RADIO_CHANNEL_PAGE_2; } #endif SetChannelPage(channelPage); mChannel = HostSwap16(aChannel); } bool ChannelMaskBaseTlv::IsValid(void) const { const ChannelMaskEntryBase *cur = GetFirstEntry(); const ChannelMaskEntryBase *end = reinterpret_cast<const ChannelMaskEntryBase *>(GetNext()); bool ret = false; VerifyOrExit(cur != nullptr); while (cur < end) { uint8_t channelPage; VerifyOrExit((cur + 1) <= end && cur->GetNext() <= end); channelPage = cur->GetChannelPage(); if ((channelPage == OT_RADIO_CHANNEL_PAGE_0) || (channelPage == OT_RADIO_CHANNEL_PAGE_2)) { VerifyOrExit(static_cast<const ChannelMaskEntry *>(cur)->IsValid()); } cur = cur->GetNext(); } ret = true; exit: return ret; } const ChannelMaskEntryBase *ChannelMaskBaseTlv::GetFirstEntry(void) const { const ChannelMaskEntryBase *entry = nullptr; VerifyOrExit(GetLength() >= sizeof(ChannelMaskEntryBase)); entry = reinterpret_cast<const ChannelMaskEntryBase *>(GetValue()); VerifyOrExit(GetLength() >= entry->GetEntrySize(), entry = nullptr); exit: return entry; } ChannelMaskEntryBase *ChannelMaskBaseTlv::GetFirstEntry(void) { return const_cast<ChannelMaskEntryBase *>(static_cast<const ChannelMaskBaseTlv *>(this)->GetFirstEntry()); } void ChannelMaskTlv::SetChannelMask(uint32_t aChannelMask) { uint8_t length = 0; ChannelMaskEntry *entry; entry = static_cast<ChannelMaskEntry *>(GetFirstEntry()); #if OPENTHREAD_CONFIG_RADIO_915MHZ_OQPSK_SUPPORT if (aChannelMask & OT_RADIO_915MHZ_OQPSK_CHANNEL_MASK) { OT_ASSERT(entry != nullptr); entry->Init(); entry->SetChannelPage(OT_RADIO_CHANNEL_PAGE_2); entry->SetMask(aChannelMask & OT_RADIO_915MHZ_OQPSK_CHANNEL_MASK); length += sizeof(MeshCoP::ChannelMaskEntry); entry = static_cast<MeshCoP::ChannelMaskEntry *>(entry->GetNext()); } #endif #if OPENTHREAD_CONFIG_RADIO_2P4GHZ_OQPSK_SUPPORT if (aChannelMask & OT_RADIO_2P4GHZ_OQPSK_CHANNEL_MASK) { OT_ASSERT(entry != nullptr); entry->Init(); entry->SetChannelPage(OT_RADIO_CHANNEL_PAGE_0); entry->SetMask(aChannelMask & OT_RADIO_2P4GHZ_OQPSK_CHANNEL_MASK); length += sizeof(MeshCoP::ChannelMaskEntry); } #endif SetLength(length); } uint32_t ChannelMaskTlv::GetChannelMask(void) const { const ChannelMaskEntryBase *cur = GetFirstEntry(); const ChannelMaskEntryBase *end = reinterpret_cast<const ChannelMaskEntryBase *>(GetNext()); uint32_t mask = 0; VerifyOrExit(cur != nullptr); while (cur < end) { uint8_t channelPage; VerifyOrExit((cur + 1) <= end && cur->GetNext() <= end); channelPage = cur->GetChannelPage(); #if OPENTHREAD_CONFIG_RADIO_915MHZ_OQPSK_SUPPORT if (channelPage == OT_RADIO_CHANNEL_PAGE_2) { mask |= static_cast<const ChannelMasEntry *>(cur)->GetMask() & OT_RADIO_915MHZ_OQPSK_CHANNEL_MASK; } #endif #if OPENTHREAD_CONFIG_RADIO_2P4GHZ_OQPSK_SUPPORT if (channelPage == OT_RADIO_CHANNEL_PAGE_0) { mask |= static_cast<const ChannelMaskEntry *>(cur)->GetMask() & OT_RADIO_2P4GHZ_OQPSK_CHANNEL_MASK; } #endif cur = cur->GetNext(); } exit: return mask; } uint32_t ChannelMaskTlv::GetChannelMask(const Message &aMessage) { uint32_t mask = 0; uint16_t offset; uint16_t end; SuccessOrExit(FindTlvValueOffset(aMessage, kChannelMask, offset, end)); end += offset; while (offset + sizeof(ChannelMaskEntryBase) <= end) { ChannelMaskEntry entry; IgnoreError(aMessage.Read(offset, entry)); VerifyOrExit(offset + entry.GetEntrySize() <= end); switch (entry.GetChannelPage()) { #if OPENTHREAD_CONFIG_RADIO_2P4GHZ_OQPSK_SUPPORT case OT_RADIO_CHANNEL_PAGE_0: IgnoreError(aMessage.Read(offset, entry)); mask |= entry.GetMask() & OT_RADIO_2P4GHZ_OQPSK_CHANNEL_MASK; break; #endif #if OPENTHREAD_CONFIG_RADIO_915MHZ_OQPSK_SUPPORT case OT_RADIO_CHANNEL_PAGE_2: IgnoreError(aMessage.Read(offset, entry)); mask |= entry.GetMask() & OT_RADIO_915MHZ_OQPSK_CHANNEL_MASK; break; #endif } offset += entry.GetEntrySize(); } exit: return mask; } } // namespace MeshCoP } // namespace ot <|endoftext|>
<commit_before>/* * Copyright 2017 deepstreamHub GmbH * * 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. */ #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> #include <cstdint> #include <cstring> #include <arpa/inet.h> #include <deepstream/core/buffer.hpp> #include <deepstream/core/client.hpp> #include <deepstream/core/error_handler.hpp> #include <deepstream/core/ws.hpp> #include "../connection.hpp" #include "../message_builder.hpp" #include "../parser.hpp" #include "../state.hpp" #include <cassert> namespace deepstream { struct FailHandler : public ErrorHandler { virtual void on_error(const std::string &) const override { BOOST_FAIL("There should be no errors"); } }; struct EventMock : public Event { EventMock(const SendFn &send_fn) : Event(send_fn) { } }; struct PresenceMock : public Presence { PresenceMock(const SendFn &send_fn) : Presence(send_fn) { } }; /* *struct SimpleClient : public websockets::pseudo::Client { * typedef std::unique_ptr<websockets::Frame> FramePtr; * * SimpleClient() * : state_(State::AWAIT_CONNECTION) * { * } * * virtual std::unique_ptr<websockets::WebSocketClient> * construct_impl(const std::string&) const override * { * BOOST_FAIL("This method should not be called"); * return nullptr; * } * * std::pair<websockets::State, FramePtr> f(Topic t, Action a, * bool ack = false) * { * Message::Header header(t, a, ack); * auto expected_num_args = Message::num_arguments(header); * * MessageBuilder builder(header); * * for (std::size_t i = 0; i < expected_num_args.first; ++i) * builder.add_argument("arg"); * * state_ = transition_incoming(state_, builder); * * return std::make_pair(websockets::State::OPEN, * builder.to_binary()); * }; * * virtual std::pair<websockets::State, FramePtr> receive_frame_impl() override * { * if (state_ == State::AWAIT_CONNECTION) * return f(Topic::CONNECTION, Action::CHALLENGE); * if (state_ == State::CHALLENGING_WAIT) * return f(Topic::CONNECTION, Action::CHALLENGE_RESPONSE, true); * if (state_ == State::AUTHENTICATING) * return f(Topic::AUTH, Action::REQUEST, true); * if (state_ == State::CONNECTED) { * using Frame = websockets::Frame; * * const std::uint16_t NORMAL_CLOSE = 1006; * const std::size_t size = sizeof(std::uint16_t); * * union { * std::uint16_t as_uint16_t; * char as_char[size]; * } payload; * payload.as_uint16_t = htons(NORMAL_CLOSE); * * return std::make_pair( * websockets::State::OPEN, * FramePtr( * new Frame(Frame::Bit::FIN | Frame::Opcode::CONNECTION_CLOSE_FRAME, * payload.as_char, size))); * } * * BOOST_FAIL("Improper state transition detected"); * return std::make_pair(websockets::State::ERROR, nullptr); * } * * virtual websockets::State send_frame_impl(const Buffer& frame, * websockets::Frame::Flags) override * { * Buffer input(frame); * input.push_back(0); * input.push_back(0); * * auto parser_retvals = parser::execute(input.data(), input.size()); * const parser::MessageList& messages = parser_retvals.first; * const parser::ErrorList& errors = parser_retvals.second; * * BOOST_REQUIRE(errors.empty()); * * std::for_each(messages.cbegin(), messages.cend(), * [this](const Message& msg) { * State old_state = this->state_; * State new_state = transition_outgoing(old_state, msg); * * this->state_ = new_state; * }); * * return websockets::State::OPEN; * } * * State state_; *}; */ struct SimpleWSHandler : public WSHandler { SimpleWSHandler() : WSHandler() { } ~SimpleWSHandler() { } void process_messages() { } std::string URI() const override { return "test_uri"; } void URI(std::string) override {} bool send(const Buffer&) override {} void open() override {} void close() override {} void reconnect() override {} void shutdown() override {} }; BOOST_AUTO_TEST_CASE(simple) { SimpleWSHandler wsh; FailHandler errh; EventMock evt([](const Message &){ return true; }); PresenceMock pres([](const Message &){ return true; }); Connection conn("ws://uri", wsh, errh, evt, pres); conn.login("auth", [](const std::unique_ptr<Buffer> &){}); BOOST_CHECK_EQUAL(conn.state(), ConnectionState::OPEN); } /* *struct RedirectionClient : public websockets::pseudo::Client { * typedef std::unique_ptr<websockets::Frame> FramePtr; * * static constexpr const char DEFAULT_URI[] = "ws://default-url"; * static constexpr const char REDIRECTION_URI[] = "ws://redirect-url"; * * RedirectionClient(const std::string& uri = DEFAULT_URI, * bool do_redirect = true) * : state_(ConnectionState::AWAIT_CONNECTION) * , do_redirect_(do_redirect) * , uri_(uri) * { * } * * virtual std::string uri_impl() const override { return uri_; } * * virtual std::unique_ptr<websockets::WebSocketClient> * construct_impl(const std::string& uri) const override * { * BOOST_CHECK(do_redirect_); * BOOST_CHECK_EQUAL(uri, REDIRECTION_URI); * * return std::unique_ptr<websockets::WebSocketClient>( * new RedirectionClient(REDIRECTION_URI, false)); * } * * std::pair<websockets::State, FramePtr> f(Topic t, Action a, * bool ack = false) * { * Message::Header header(t, a, ack); * * MessageBuilder builder(header); * * if (a == Action::REDIRECT) * builder.add_argument(REDIRECTION_URI); * * state_ = transition_incoming(state_, builder); * * return std::make_pair(websockets::State::OPEN, * make_frame(builder.to_binary())); * }; * * virtual std::pair<websockets::State, FramePtr> receive_frame_impl() override * { * if (state_ == ConnectionState::AWAIT_CONNECTION) * return f(Topic::CONNECTION, Action::CHALLENGE); * if (state_ == ConnectionState::CHALLENGING_WAIT && do_redirect_) * return f(Topic::CONNECTION, Action::REDIRECT); * if (state_ == ConnectionState::CHALLENGING_WAIT && !do_redirect_) * return f(Topic::CONNECTION, Action::CHALLENGE_RESPONSE, true); * if (state_ == ConnectionState::AUTHENTICATING) * return f(Topic::AUTH, Action::REQUEST, true); * if (state_ == ConnectionState::CONNECTED) { * using Frame = websockets::Frame; * * const std::uint16_t NORMAL_CLOSE = 1006; * const std::size_t size = sizeof(std::uint16_t); * * union { * std::uint16_t as_uint16_t; * char as_char[size]; * } payload; * payload.as_uint16_t = htons(NORMAL_CLOSE); * * return std::make_pair( * websockets::State::OPEN, * FramePtr( * new Frame(Frame::Bit::FIN | Frame::Opcode::CONNECTION_CLOSE_FRAME, * payload.as_char, size))); * } * * BOOST_FAIL("Improper state transition detected"); * return std::make_pair(websockets::State::ERROR, nullptr); * } * * virtual websockets::State send_frame_impl(const Buffer& frame, * websockets::Frame::Flags) override * { * Buffer input(frame); * input.push_back(0); * input.push_back(0); * * auto parser_retvals = parser::execute(input.data(), input.size()); * const parser::MessageList& messages = parser_retvals.first; * const parser::ErrorList& errors = parser_retvals.second; * * BOOST_REQUIRE(errors.empty()); * * std::for_each(messages.cbegin(), messages.cend(), * [this](const Message& msg) { * ConnectionState old_state = this->state_; * ConnectionState new_state = transition_outgoing(old_state, msg); * * this->state_ = new_state; * }); * * return websockets::State::OPEN; * } * * ConnectionState state_; * bool do_redirect_; * std::string uri_; *}; */ struct RedirectionWSHandler : public WSHandler { RedirectionWSHandler() : WSHandler() { } ~RedirectionWSHandler() { } void process_messages() {} std::string URI() const override { return "test_uri"; } void URI(std::string) override {} bool send(const Buffer&) override {} void open() override {} void close() override {} void reconnect() override {} void shutdown() override {} }; /* *constexpr const char RedirectionClient::DEFAULT_URI[]; *constexpr const char RedirectionClient::REDIRECTION_URI[]; */ BOOST_AUTO_TEST_CASE(redirections) { RedirectionWSHandler wsh; FailHandler errh; EventMock evt([](const Message &){ return true; }); PresenceMock pres([](const Message &){ return true; }); Connection conn("ws://initial.uri", wsh, errh, evt, pres); conn.login("auth", [](const std::unique_ptr<Buffer> &){}); BOOST_CHECK_EQUAL(conn.state(), ConnectionState::OPEN); BOOST_CHECK_EQUAL(wsh.URI(), "ws://redirection.uri"); } BOOST_AUTO_TEST_CASE(lifetime) { auto make_msg = [](Topic topic, Action action) { return MessageBuilder(topic, action); }; auto make_ack_msg = [](Topic topic, Action action) { return MessageBuilder(topic, action, true); }; ConnectionState s0 = ConnectionState::AWAIT_CONNECTION; auto msg0 = make_msg(Topic::CONNECTION, Action::CHALLENGE); ConnectionState s1 = transition_incoming(s0, msg0); BOOST_CHECK_EQUAL(s1, ConnectionState::CHALLENGING); auto msg1 = make_msg(Topic::CONNECTION, Action::CHALLENGE_RESPONSE); msg1.add_argument(Buffer("URL")); ConnectionState s2 = transition_outgoing(s1, msg1); BOOST_CHECK_EQUAL(s2, ConnectionState::AWAIT_AUTHENTICATION); auto msg2 = make_ack_msg(Topic::CONNECTION, Action::CHALLENGE_RESPONSE); ConnectionState s3 = transition_incoming(s2, msg2); BOOST_CHECK_EQUAL(s3, ConnectionState::AWAIT_AUTHENTICATION); auto msg3 = make_msg(Topic::AUTH, Action::REQUEST); msg3.add_argument(Buffer("{\"username\":\"u\",\"password\":\"p\"}")); ConnectionState s4 = transition_outgoing(s3, msg3); BOOST_CHECK_EQUAL(s4, ConnectionState::AUTHENTICATING); auto msg4 = make_ack_msg(Topic::AUTH, Action::REQUEST); ConnectionState s5 = transition_incoming(s4, msg4); BOOST_CHECK_EQUAL(s5, ConnectionState::OPEN); } } <commit_msg>test: repair connection tests to use new wshandler<commit_after>/* * Copyright 2017 deepstreamHub GmbH * * 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. */ #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> #include <cstdint> #include <cstring> #include <iostream> #include <arpa/inet.h> #include <deepstream/core/buffer.hpp> #include <deepstream/core/client.hpp> #include <deepstream/core/error_handler.hpp> #include <deepstream/core/ws.hpp> #include "../connection.hpp" #include "../message_builder.hpp" #include "../parser.hpp" #include "../state.hpp" #include <cassert> namespace deepstream { std::ostream &operator<< (std::ostream &os, WSState state) { const char* states[] = { "ERROR", "OPEN", "CLOSED" }; os << states[static_cast<int>(state)]; return os; } struct FailHandler : public ErrorHandler { virtual void on_error(const std::string &) const override { BOOST_FAIL("There should be no errors"); } }; struct EventMock : public Event { EventMock(const SendFn &send_fn) : Event(send_fn) { } }; struct PresenceMock : public Presence { PresenceMock(const SendFn &send_fn) : Presence(send_fn) { } }; struct SimpleWSHandler : public WSHandler { SimpleWSHandler() : WSHandler() { } ~SimpleWSHandler() { } void process_messages() { } std::string URI() const override { return uri_; } void URI(std::string uri) override { uri_ = uri; } bool send(const Buffer &message) override { if (message == Message::from_human_readable("C|CHR+")) { const Buffer input = Message::from_human_readable("C|A|CHR+"); (*on_message_)(std::move(input)); } else if (message == Message::from_human_readable("C|CHR|ws://uri+")) { const Buffer input = Message::from_human_readable("C|A+"); (*on_message_)(std::move(input)); } else if (message == Message::from_human_readable("A|REQ|auth+")) { const Buffer input = Message::from_human_readable("A|A+"); (*on_message_)(std::move(input)); } else { std::cout << "unknown msg: " << std::string(message.cbegin(), message.cend()) << std::endl; assert(false); } return true; } void open() override { (*on_open_)(); const Buffer input = Message::from_human_readable("C|CH+"); (*on_message_)(std::move(input)); } void close() override {} void reconnect() override {} void shutdown() override {} std::string uri_; }; BOOST_AUTO_TEST_CASE(simple) { SimpleWSHandler wsh; FailHandler errh; EventMock evt([](const Message &){ return true; }); PresenceMock pres([](const Message &){ return true; }); Connection conn("ws://uri", wsh, errh, evt, pres); conn.login("auth", [](const std::unique_ptr<Buffer> &){}); BOOST_CHECK_EQUAL(conn.state(), ConnectionState::OPEN); } struct RedirectionWSHandler : public WSHandler { RedirectionWSHandler() : WSHandler() { } ~RedirectionWSHandler() { } void process_messages() {} std::string URI() const override { return uri_; } void URI(std::string uri) override { uri_ = uri; } bool send(const Buffer &message) override { if (message == Message::from_human_readable("C|CHR+")) { const Buffer input = Message::from_human_readable("C|A|CHR+"); (*on_message_)(std::move(input)); } else if (message == Message::from_human_readable("C|CHR|ws://initial.uri+")) { const Buffer input = Message::from_human_readable("C|RED|ws://redirection.uri+"); (*on_message_)(std::move(input)); } else { std::cout << "unknown msg: " << std::string(message.cbegin(), message.cend()) << std::endl; assert(false); } return true; } void open() override { (*on_open_)(); const Buffer input = Message::from_human_readable("C|CH+"); (*on_message_)(std::move(input)); } void close() override {} void reconnect() override {} void shutdown() override {} std::string uri_; }; /* *constexpr const char RedirectionClient::DEFAULT_URI[]; *constexpr const char RedirectionClient::REDIRECTION_URI[]; */ BOOST_AUTO_TEST_CASE(redirections) { RedirectionWSHandler wsh; FailHandler errh; EventMock evt([](const Message &){ return true; }); PresenceMock pres([](const Message &){ return true; }); Connection conn("ws://initial.uri", wsh, errh, evt, pres); conn.login("auth", [](const std::unique_ptr<Buffer> &){}); BOOST_CHECK_EQUAL(conn.state(), ConnectionState::AWAIT_CONNECTION); BOOST_CHECK_EQUAL(wsh.URI(), "ws://redirection.uri"); } BOOST_AUTO_TEST_CASE(lifetime) { auto make_msg = [](Topic topic, Action action) { return MessageBuilder(topic, action); }; auto make_ack_msg = [](Topic topic, Action action) { return MessageBuilder(topic, action, true); }; ConnectionState s0 = ConnectionState::AWAIT_CONNECTION; auto msg0 = make_msg(Topic::CONNECTION, Action::CHALLENGE); ConnectionState s1 = transition_incoming(s0, msg0); BOOST_CHECK_EQUAL(s1, ConnectionState::CHALLENGING); auto msg1 = make_msg(Topic::CONNECTION, Action::CHALLENGE_RESPONSE); msg1.add_argument(Buffer("URL")); ConnectionState s2 = transition_outgoing(s1, msg1); BOOST_CHECK_EQUAL(s2, ConnectionState::CHALLENGING_WAIT); auto msg2 = make_ack_msg(Topic::CONNECTION, Action::CHALLENGE_RESPONSE); ConnectionState s3 = transition_incoming(s2, msg2); BOOST_CHECK_EQUAL(s3, ConnectionState::AWAIT_AUTHENTICATION); auto msg3 = make_msg(Topic::AUTH, Action::REQUEST); msg3.add_argument(Buffer("{\"username\":\"u\",\"password\":\"p\"}")); ConnectionState s4 = transition_outgoing(s3, msg3); BOOST_CHECK_EQUAL(s4, ConnectionState::AUTHENTICATING); auto msg4 = make_ack_msg(Topic::AUTH, Action::REQUEST); ConnectionState s5 = transition_incoming(s4, msg4); BOOST_CHECK_EQUAL(s5, ConnectionState::OPEN); } } <|endoftext|>
<commit_before>#include "doofit/plotting/Plot/Plot.h" // STL #include <string> #include <sstream> #include <vector> // boost #include <boost/regex.hpp> // ROOT #include "TIterator.h" // from RooFit #include "RooArgList.h" #include "RooAbsRealLValue.h" #include "RooAbsData.h" #include "RooAbsPdf.h" #include "RooPlot.h" // from Project #include "doocore/io/MsgStream.h" #include "doocore/lutils/lutils.h" #include "doofit/plotting/Plot/PlotConfig.h" using namespace ROOT; using namespace RooFit; using namespace doocore::io; namespace doofit { namespace plotting { Plot::Plot(const PlotConfig& cfg_plot, const RooAbsRealLValue& dimension, const RooAbsData& dataset, const RooArgList& pdfs, const std::string& plot_name) : config_plot_(cfg_plot), dimension_(dimension), datasets_(), plot_name_(plot_name) { datasets_.push_back(&dataset); pdf_ = dynamic_cast<RooAbsPdf*>(pdfs.first()); if (&dimension_ == NULL) { serr << "Plot::Plot(): Dimension is invalid." << endmsg; throw 1; } if (datasets_.front() == NULL) { serr << "Plot::Plot(): Dataset is invalid." << endmsg; throw 1; } if (plot_name_ == "") { plot_name_ = dimension_.GetName(); } for (int i=1; i<pdfs.getSize(); ++i) { RooAbsArg* sub_arg = pdfs.at(i); const RooAbsPdf* sub_pdf = dynamic_cast<RooAbsPdf*>(sub_arg); if (sub_pdf != NULL) { components_.push_back(RooArgSet(*sub_pdf)); } } } Plot::Plot(const PlotConfig& cfg_plot, const RooAbsRealLValue& dimension, const RooAbsData& dataset, const RooAbsPdf& pdf, const std::vector<std::string>& components, const std::string& plot_name) : config_plot_(cfg_plot), dimension_(dimension), datasets_(), plot_name_(plot_name) { datasets_.push_back(&dataset); pdf_ = &pdf; if (pdf_ == NULL) { serr << "Plot::Plot(): Main PDF is invalid." << endmsg; throw 1; } if (&dimension_ == NULL) { serr << "Plot::Plot(): Dimension is invalid." << endmsg; throw 1; } if (datasets_.front() == NULL) { serr << "Plot::Plot(): Dataset is invalid." << endmsg; throw 1; } if (plot_name_ == "") { plot_name_ = dimension_.GetName(); } // iterate over sub PDFs and match supplied regular expressions RooArgSet nodes; pdf.branchNodeServerList(&nodes); for (std::vector<std::string>::const_iterator it = components.begin(); it != components.end(); ++it) { boost::regex r(*it); components_.push_back(RooArgSet()); TIterator* it_nodes = nodes.createIterator(); RooAbsArg* node = NULL; while ((node = dynamic_cast<RooAbsArg*>(it_nodes->Next()))) { RooAbsPdf* pdf_node = dynamic_cast<RooAbsPdf*>(node); if (pdf_node != NULL) { std::string pdf_name = pdf_node->GetName(); // exclude resolution models generated by RooFit and match the rest if (pdf_name.find("_conv_") == -1 && regex_match(pdf_name,r)) { components_.back().add(*pdf_node); } } } delete it_nodes; } } void Plot::PlotHandler(ScaleType sc_y, std::string suffix) const { if (suffix == "") suffix = "_log"; std::string plot_name = plot_name_; std::stringstream log_plot_name_sstr; log_plot_name_sstr << plot_name << suffix; std::string log_plot_name = log_plot_name_sstr.str(); std::stringstream pull_plot_sstr; pull_plot_sstr << plot_name << "_pull"; std::string pull_plot_name = pull_plot_sstr.str(); std::stringstream log_pull_plot_sstr; log_pull_plot_sstr << plot_name << "_pull" << suffix; std::string log_pull_plot_name = log_pull_plot_sstr.str(); sinfo << "Plotting " << dimension_.GetName() << " into " << config_plot_.plot_directory() << plot_name << endmsg; doocore::lutils::setStyle("LHCb"); RooCmdArg range_arg; if (!dimension_.hasMin() && !dimension_.hasMax()) { double min, max; // ugly const_cast because RooFit is stupid (RooDataSet::getRange needs non-const RooRealVar) RooRealVar* dimension_non_const = const_cast<RooRealVar*>(dynamic_cast<const RooRealVar*>(&dimension_)); datasets_.front()->getRange(*dimension_non_const, min, max); double min_t, max_t; for (std::vector<const RooAbsData*>::const_iterator it = datasets_.begin()+1; it != datasets_.end(); ++it) { (*it)->getRange(*dimension_non_const, min_t, max_t); if (min_t < min) min = min_t; if (max_t > max) max = max_t; } range_arg = Range(min, max); } RooPlot* plot_frame = dimension_.frame(range_arg); for (std::vector<const RooAbsData*>::const_iterator it = datasets_.begin(); it != datasets_.end(); ++it) { (*it)->plotOn(plot_frame/*, Rescale(1.0/(*it)->sumEntries())*/); } TLatex label(0.5,0.5,"LHCb"); config_plot_.OnDemandOpenPlotStack(); if (pdf_ != NULL) { RooPlot* plot_frame_pull = dimension_.frame(range_arg); for (std::vector<const RooAbsData*>::const_iterator it = datasets_.begin(); it != datasets_.end(); ++it) { (*it)->plotOn(plot_frame_pull); } // I feel so tupid doing this but apparently RooFit leaves me no other way... RooCmdArg arg1, arg2, arg3, arg4, arg5, arg6, arg7; if (plot_args_.size() > 0) arg1 = plot_args_[0]; if (plot_args_.size() > 1) arg2 = plot_args_[1]; if (plot_args_.size() > 2) arg3 = plot_args_[2]; if (plot_args_.size() > 3) arg4 = plot_args_[3]; if (plot_args_.size() > 4) arg5 = plot_args_[4]; if (plot_args_.size() > 5) arg6 = plot_args_[5]; if (plot_args_.size() > 6) arg7 = plot_args_[6]; int i=1; for (std::vector<RooArgSet>::const_iterator it = components_.begin(); it != components_.end(); ++it) { if (it->getSize() > 0) { sinfo << "Plotting component " << it->first()->GetName() << endmsg; pdf_->plotOn(plot_frame, Components(*it), LineColor(config_plot_.GetPdfLineColor(i)), LineStyle(config_plot_.GetPdfLineStyle(i)), arg1, arg2, arg3, arg4, arg5, arg6, arg7); pdf_->plotOn(plot_frame_pull, Components(*it), LineColor(config_plot_.GetPdfLineColor(i)), LineStyle(config_plot_.GetPdfLineStyle(i)), arg1, arg2, arg3, arg4, arg5, arg6, arg7); ++i; } } pdf_->plotOn(plot_frame, LineColor(config_plot_.GetPdfLineColor(0)), LineStyle(config_plot_.GetPdfLineStyle(0)), arg1, arg2, arg3, arg4, arg5, arg6, arg7); pdf_->plotOn(plot_frame_pull, LineColor(config_plot_.GetPdfLineColor(0)), LineStyle(config_plot_.GetPdfLineStyle(0)), arg1, arg2, arg3, arg4, arg5, arg6, arg7); plot_frame_pull->SetMinimum(0.5); plot_frame_pull->SetMaximum(1.3*plot_frame_pull->GetMaximum()); if (sc_y == kLinear || sc_y == kBoth) { doocore::lutils::PlotPulls(pull_plot_name, plot_frame_pull, label, config_plot_.plot_directory(), false, false, true); doocore::lutils::PlotPulls("AllPlots", plot_frame_pull, label, config_plot_.plot_directory(), false, false, true, ""); } if (sc_y == kLogarithmic || sc_y == kBoth) { doocore::lutils::PlotPulls(log_pull_plot_name, plot_frame_pull, label, config_plot_.plot_directory(), true, false, true); doocore::lutils::PlotPulls("AllPlots", plot_frame_pull, label, config_plot_.plot_directory(), true, false, true, ""); } delete plot_frame_pull; } plot_frame->SetMinimum(0.5); plot_frame->SetMaximum(1.3*plot_frame->GetMaximum()); if (sc_y == kLinear || sc_y == kBoth) { doocore::lutils::PlotSimple(plot_name, plot_frame, label, config_plot_.plot_directory(), false); doocore::lutils::PlotSimple("AllPlots", plot_frame, label, config_plot_.plot_directory(), false); } if (sc_y == kLogarithmic || sc_y == kBoth) { doocore::lutils::PlotSimple(log_plot_name, plot_frame, label, config_plot_.plot_directory(), true); doocore::lutils::PlotSimple("AllPlots", plot_frame, label, config_plot_.plot_directory(), true); } delete plot_frame; } Plot::~Plot() {} } // namespace plotting } // namespace doofit <commit_msg>Plot: adjusting location of label<commit_after>#include "doofit/plotting/Plot/Plot.h" // STL #include <string> #include <sstream> #include <vector> // boost #include <boost/regex.hpp> // ROOT #include "TIterator.h" // from RooFit #include "RooArgList.h" #include "RooAbsRealLValue.h" #include "RooAbsData.h" #include "RooAbsPdf.h" #include "RooPlot.h" // from Project #include "doocore/io/MsgStream.h" #include "doocore/lutils/lutils.h" #include "doofit/plotting/Plot/PlotConfig.h" using namespace ROOT; using namespace RooFit; using namespace doocore::io; namespace doofit { namespace plotting { Plot::Plot(const PlotConfig& cfg_plot, const RooAbsRealLValue& dimension, const RooAbsData& dataset, const RooArgList& pdfs, const std::string& plot_name) : config_plot_(cfg_plot), dimension_(dimension), datasets_(), plot_name_(plot_name) { datasets_.push_back(&dataset); pdf_ = dynamic_cast<RooAbsPdf*>(pdfs.first()); if (&dimension_ == NULL) { serr << "Plot::Plot(): Dimension is invalid." << endmsg; throw 1; } if (datasets_.front() == NULL) { serr << "Plot::Plot(): Dataset is invalid." << endmsg; throw 1; } if (plot_name_ == "") { plot_name_ = dimension_.GetName(); } for (int i=1; i<pdfs.getSize(); ++i) { RooAbsArg* sub_arg = pdfs.at(i); const RooAbsPdf* sub_pdf = dynamic_cast<RooAbsPdf*>(sub_arg); if (sub_pdf != NULL) { components_.push_back(RooArgSet(*sub_pdf)); } } } Plot::Plot(const PlotConfig& cfg_plot, const RooAbsRealLValue& dimension, const RooAbsData& dataset, const RooAbsPdf& pdf, const std::vector<std::string>& components, const std::string& plot_name) : config_plot_(cfg_plot), dimension_(dimension), datasets_(), plot_name_(plot_name) { datasets_.push_back(&dataset); pdf_ = &pdf; if (pdf_ == NULL) { serr << "Plot::Plot(): Main PDF is invalid." << endmsg; throw 1; } if (&dimension_ == NULL) { serr << "Plot::Plot(): Dimension is invalid." << endmsg; throw 1; } if (datasets_.front() == NULL) { serr << "Plot::Plot(): Dataset is invalid." << endmsg; throw 1; } if (plot_name_ == "") { plot_name_ = dimension_.GetName(); } // iterate over sub PDFs and match supplied regular expressions RooArgSet nodes; pdf.branchNodeServerList(&nodes); for (std::vector<std::string>::const_iterator it = components.begin(); it != components.end(); ++it) { boost::regex r(*it); components_.push_back(RooArgSet()); TIterator* it_nodes = nodes.createIterator(); RooAbsArg* node = NULL; while ((node = dynamic_cast<RooAbsArg*>(it_nodes->Next()))) { RooAbsPdf* pdf_node = dynamic_cast<RooAbsPdf*>(node); if (pdf_node != NULL) { std::string pdf_name = pdf_node->GetName(); // exclude resolution models generated by RooFit and match the rest if (pdf_name.find("_conv_") == -1 && regex_match(pdf_name,r)) { components_.back().add(*pdf_node); } } } delete it_nodes; } } void Plot::PlotHandler(ScaleType sc_y, std::string suffix) const { if (suffix == "") suffix = "_log"; std::string plot_name = plot_name_; std::stringstream log_plot_name_sstr; log_plot_name_sstr << plot_name << suffix; std::string log_plot_name = log_plot_name_sstr.str(); std::stringstream pull_plot_sstr; pull_plot_sstr << plot_name << "_pull"; std::string pull_plot_name = pull_plot_sstr.str(); std::stringstream log_pull_plot_sstr; log_pull_plot_sstr << plot_name << "_pull" << suffix; std::string log_pull_plot_name = log_pull_plot_sstr.str(); sinfo << "Plotting " << dimension_.GetName() << " into " << config_plot_.plot_directory() << plot_name << endmsg; doocore::lutils::setStyle("LHCb"); RooCmdArg range_arg; if (!dimension_.hasMin() && !dimension_.hasMax()) { double min, max; // ugly const_cast because RooFit is stupid (RooDataSet::getRange needs non-const RooRealVar) RooRealVar* dimension_non_const = const_cast<RooRealVar*>(dynamic_cast<const RooRealVar*>(&dimension_)); datasets_.front()->getRange(*dimension_non_const, min, max); double min_t, max_t; for (std::vector<const RooAbsData*>::const_iterator it = datasets_.begin()+1; it != datasets_.end(); ++it) { (*it)->getRange(*dimension_non_const, min_t, max_t); if (min_t < min) min = min_t; if (max_t > max) max = max_t; } range_arg = Range(min, max); } RooPlot* plot_frame = dimension_.frame(range_arg); for (std::vector<const RooAbsData*>::const_iterator it = datasets_.begin(); it != datasets_.end(); ++it) { (*it)->plotOn(plot_frame/*, Rescale(1.0/(*it)->sumEntries())*/); } TLatex label(0.6,0.88,"LHCb"); config_plot_.OnDemandOpenPlotStack(); if (pdf_ != NULL) { RooPlot* plot_frame_pull = dimension_.frame(range_arg); for (std::vector<const RooAbsData*>::const_iterator it = datasets_.begin(); it != datasets_.end(); ++it) { (*it)->plotOn(plot_frame_pull); } // I feel so tupid doing this but apparently RooFit leaves me no other way... RooCmdArg arg1, arg2, arg3, arg4, arg5, arg6, arg7; if (plot_args_.size() > 0) arg1 = plot_args_[0]; if (plot_args_.size() > 1) arg2 = plot_args_[1]; if (plot_args_.size() > 2) arg3 = plot_args_[2]; if (plot_args_.size() > 3) arg4 = plot_args_[3]; if (plot_args_.size() > 4) arg5 = plot_args_[4]; if (plot_args_.size() > 5) arg6 = plot_args_[5]; if (plot_args_.size() > 6) arg7 = plot_args_[6]; int i=1; for (std::vector<RooArgSet>::const_iterator it = components_.begin(); it != components_.end(); ++it) { if (it->getSize() > 0) { sinfo << "Plotting component " << it->first()->GetName() << endmsg; pdf_->plotOn(plot_frame, Components(*it), LineColor(config_plot_.GetPdfLineColor(i)), LineStyle(config_plot_.GetPdfLineStyle(i)), arg1, arg2, arg3, arg4, arg5, arg6, arg7); pdf_->plotOn(plot_frame_pull, Components(*it), LineColor(config_plot_.GetPdfLineColor(i)), LineStyle(config_plot_.GetPdfLineStyle(i)), arg1, arg2, arg3, arg4, arg5, arg6, arg7); ++i; } } pdf_->plotOn(plot_frame, LineColor(config_plot_.GetPdfLineColor(0)), LineStyle(config_plot_.GetPdfLineStyle(0)), arg1, arg2, arg3, arg4, arg5, arg6, arg7); pdf_->plotOn(plot_frame_pull, LineColor(config_plot_.GetPdfLineColor(0)), LineStyle(config_plot_.GetPdfLineStyle(0)), arg1, arg2, arg3, arg4, arg5, arg6, arg7); plot_frame_pull->SetMinimum(0.5); plot_frame_pull->SetMaximum(1.3*plot_frame_pull->GetMaximum()); if (sc_y == kLinear || sc_y == kBoth) { doocore::lutils::PlotPulls(pull_plot_name, plot_frame_pull, label, config_plot_.plot_directory(), false, false, true); doocore::lutils::PlotPulls("AllPlots", plot_frame_pull, label, config_plot_.plot_directory(), false, false, true, ""); } if (sc_y == kLogarithmic || sc_y == kBoth) { doocore::lutils::PlotPulls(log_pull_plot_name, plot_frame_pull, label, config_plot_.plot_directory(), true, false, true); doocore::lutils::PlotPulls("AllPlots", plot_frame_pull, label, config_plot_.plot_directory(), true, false, true, ""); } delete plot_frame_pull; } plot_frame->SetMinimum(0.5); plot_frame->SetMaximum(1.3*plot_frame->GetMaximum()); if (sc_y == kLinear || sc_y == kBoth) { doocore::lutils::PlotSimple(plot_name, plot_frame, label, config_plot_.plot_directory(), false); doocore::lutils::PlotSimple("AllPlots", plot_frame, label, config_plot_.plot_directory(), false); } if (sc_y == kLogarithmic || sc_y == kBoth) { doocore::lutils::PlotSimple(log_plot_name, plot_frame, label, config_plot_.plot_directory(), true); doocore::lutils::PlotSimple("AllPlots", plot_frame, label, config_plot_.plot_directory(), true); } delete plot_frame; } Plot::~Plot() {} } // namespace plotting } // namespace doofit <|endoftext|>
<commit_before>/************************************************************************** The MIT License (MIT) Copyright (c) 2015 Dmitry Sovetov https://github.com/dmsovetov 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 "Renderer.h" #include "SceneObject.h" #include "Component.h" #include "Mesh.h" #define GLSL( ... ) #__VA_ARGS__ DC_BEGIN_DREEMCHEST namespace scene { // ** Renderer::Renderer Renderer::Renderer( renderer::Hal* hal ) : m_hal( hal ) { // ** Create the solid lightmap shader m_shaders[Material::Solid] = m_hal->createShader( GLSL( uniform mat4 u_mvp; varying vec2 v_tex0; varying vec2 v_tex1; void main() { v_tex0 = gl_MultiTexCoord0.xy; v_tex1 = gl_MultiTexCoord1.xy; gl_Position = u_mvp * gl_Vertex; } ), GLSL( uniform sampler2D u_diffuse; uniform sampler2D u_lightmap; uniform vec4 u_diffuseColor; varying vec2 v_tex0; varying vec2 v_tex1; void main() { vec4 light = texture2D( u_lightmap, v_tex1 ); gl_FragColor = texture2D( u_diffuse, v_tex0 ) * (light * 2.0) * u_diffuseColor + vec4( 0.5254902, 0.80392157, 0.91764706, 1.0 ); } ) ); // ** Create the colored & textured shader m_shaders[Material::Transparent] = m_hal->createShader( GLSL( uniform mat4 u_mvp; varying vec2 v_tex0; varying vec2 v_tex1; void main() { v_tex0 = gl_MultiTexCoord0.xy; v_tex1 = gl_MultiTexCoord1.xy; gl_Position = u_mvp * gl_Vertex; } ), GLSL( uniform sampler2D u_diffuse; uniform sampler2D u_lightmap; uniform vec4 u_diffuseColor; varying vec2 v_tex0; varying vec2 v_tex1; void main() { gl_FragColor = texture2D( u_diffuse, v_tex0 ) * texture2D( u_lightmap, v_tex1 ) * u_diffuseColor; } ) ); // ** Create the colored & textured shader m_shaders[Material::Additive] = m_hal->createShader( GLSL( uniform mat4 u_mvp; varying vec2 v_tex0; void main() { v_tex0 = gl_MultiTexCoord0.xy; gl_Position = u_mvp * gl_Vertex; } ), GLSL( uniform sampler2D u_diffuse; uniform vec4 u_diffuseColor; uniform vec4 u_tintColor; varying vec2 v_tex0; void main() { gl_FragColor = texture2D( u_diffuse, v_tex0 ) * u_diffuseColor * u_tintColor * u_tintColor.a; } ) ); } // ** Renderer::render void Renderer::render( const Matrix4& view, const Matrix4& proj, renderer::Shader* shader, const SceneObjectPtr& sceneObject ) { StrongPtr<MeshRenderer> meshRenderer = sceneObject->get<MeshRenderer>(); StrongPtr<Transform> transform = sceneObject->get<Transform>(); const MeshPtr& mesh = meshRenderer->mesh(); m_hal->setShader( shader ); shader->setMatrix( shader->findUniformLocation( "u_mvp" ), proj * view * transform->affine() ); for( s32 j = 0, n = mesh->chunkCount(); j < n; j++ ) { const Mesh::Chunk& chunk = mesh->chunk( j ); MaterialPtr material = meshRenderer->material( j ); if( material != MaterialPtr() ) { Rgba diffuseColor = material->color( Material::Diffuse ); Rgba tintColor = material->color( Material::Tint ); shader->setInt( shader->findUniformLocation( "u_diffuse" ), 0 ); shader->setInt( shader->findUniformLocation( "u_lightmap" ), 1 ); shader->setVec4( shader->findUniformLocation( "u_diffuseColor" ), Vec4( diffuseColor.r, diffuseColor.g, diffuseColor.b, diffuseColor.a ) ); shader->setVec4( shader->findUniformLocation( "u_tintColor" ), Vec4( tintColor.r, tintColor.g, tintColor.b, tintColor.a ) ); m_hal->setTexture( 0, material->texture( Material::Diffuse ).get() ); m_hal->setTexture( 1, meshRenderer->lightmap().get() ); } else { m_hal->setTexture( 0, NULL ); m_hal->setTexture( 1, NULL ); } m_hal->setVertexBuffer( chunk.m_vertexBuffer.get() ); m_hal->renderIndexed( renderer::PrimTriangles, chunk.m_indexBuffer.get(), 0, chunk.m_indexBuffer->size() ); } } // ** Renderer::render void Renderer::render( const Matrix4& view, const Matrix4& proj, const ScenePtr& scene ) { const SceneObjects& sceneObjects = scene->sceneObjects(); SceneObjects objects[Material::TotalMaterialShaders]; for( SceneObjects::const_iterator i = sceneObjects.begin(), end = sceneObjects.end(); i != end; ++i ) { const SceneObjectPtr& sceneObject = *i; if( !sceneObject->has<MeshRenderer>() ) { continue; } StrongPtr<MeshRenderer> meshRenderer = sceneObject->get<MeshRenderer>(); MaterialPtr material = meshRenderer->material( 0 ); if( material == MaterialPtr() ) { continue; } objects[material->shader()].push_back( sceneObject ); } { for( SceneObjects::const_iterator i = objects[Material::Solid].begin(), end = objects[Material::Solid].end(); i != end; ++i ) { render( view, proj, m_shaders[Material::Solid], *i ); } } { m_hal->setAlphaTest( renderer::Greater, 0.5f ); for( SceneObjects::const_iterator i = objects[Material::Transparent].begin(), end = objects[Material::Transparent].end(); i != end; ++i ) { render( view, proj, m_shaders[Material::Transparent], *i ); } m_hal->setAlphaTest( renderer::CompareDisabled ); } { m_hal->setDepthTest( false, renderer::Less ); m_hal->setBlendFactors( renderer::BlendOne, renderer::BlendOne ); for( SceneObjects::const_iterator i = objects[Material::Additive].begin(), end = objects[Material::Additive].end(); i != end; ++i ) { render( view, proj, m_shaders[Material::Additive], *i ); } m_hal->setDepthTest( true, renderer::Less ); m_hal->setBlendFactors( renderer::BlendDisabled, renderer::BlendDisabled ); } m_hal->setShader( NULL ); } } // namespace scene DC_END_DREEMCHEST<commit_msg>Fixed shader<commit_after>/************************************************************************** The MIT License (MIT) Copyright (c) 2015 Dmitry Sovetov https://github.com/dmsovetov 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 "Renderer.h" #include "SceneObject.h" #include "Component.h" #include "Mesh.h" #define GLSL( ... ) #__VA_ARGS__ DC_BEGIN_DREEMCHEST namespace scene { // ** Renderer::Renderer Renderer::Renderer( renderer::Hal* hal ) : m_hal( hal ) { // ** Create the solid lightmap shader m_shaders[Material::Solid] = m_hal->createShader( GLSL( uniform mat4 u_mvp; varying vec2 v_tex0; varying vec2 v_tex1; void main() { v_tex0 = gl_MultiTexCoord0.xy; v_tex1 = gl_MultiTexCoord1.xy; gl_Position = u_mvp * gl_Vertex; } ), GLSL( uniform sampler2D u_diffuse; uniform sampler2D u_lightmap; uniform vec4 u_diffuseColor; varying vec2 v_tex0; varying vec2 v_tex1; void main() { vec4 light = texture2D( u_lightmap, v_tex1 ); vec4 diffuse = texture2D( u_diffuse, v_tex0 ) * u_diffuseColor; gl_FragColor = diffuse * (light * 1.0) + diffuse * vec4( 0.5254902, 0.80392157, 0.91764706, 1.0 ); } ) ); // ** Create the colored & textured shader m_shaders[Material::Transparent] = m_hal->createShader( GLSL( uniform mat4 u_mvp; varying vec2 v_tex0; varying vec2 v_tex1; void main() { v_tex0 = gl_MultiTexCoord0.xy; v_tex1 = gl_MultiTexCoord1.xy; gl_Position = u_mvp * gl_Vertex; } ), GLSL( uniform sampler2D u_diffuse; uniform sampler2D u_lightmap; uniform vec4 u_diffuseColor; varying vec2 v_tex0; varying vec2 v_tex1; void main() { gl_FragColor = texture2D( u_diffuse, v_tex0 ) * texture2D( u_lightmap, v_tex1 ) * u_diffuseColor; } ) ); // ** Create the colored & textured shader m_shaders[Material::Additive] = m_hal->createShader( GLSL( uniform mat4 u_mvp; varying vec2 v_tex0; void main() { v_tex0 = gl_MultiTexCoord0.xy; gl_Position = u_mvp * gl_Vertex; } ), GLSL( uniform sampler2D u_diffuse; uniform vec4 u_diffuseColor; uniform vec4 u_tintColor; varying vec2 v_tex0; void main() { gl_FragColor = texture2D( u_diffuse, v_tex0 ) * u_diffuseColor * u_tintColor * u_tintColor.a; } ) ); } // ** Renderer::render void Renderer::render( const Matrix4& view, const Matrix4& proj, renderer::Shader* shader, const SceneObjectPtr& sceneObject ) { StrongPtr<MeshRenderer> meshRenderer = sceneObject->get<MeshRenderer>(); StrongPtr<Transform> transform = sceneObject->get<Transform>(); const MeshPtr& mesh = meshRenderer->mesh(); m_hal->setShader( shader ); shader->setMatrix( shader->findUniformLocation( "u_mvp" ), proj * view * transform->affine() ); for( s32 j = 0, n = mesh->chunkCount(); j < n; j++ ) { const Mesh::Chunk& chunk = mesh->chunk( j ); MaterialPtr material = meshRenderer->material( j ); if( material != MaterialPtr() ) { Rgba diffuseColor = material->color( Material::Diffuse ); Rgba tintColor = material->color( Material::Tint ); shader->setInt( shader->findUniformLocation( "u_diffuse" ), 0 ); shader->setInt( shader->findUniformLocation( "u_lightmap" ), 1 ); shader->setVec4( shader->findUniformLocation( "u_diffuseColor" ), Vec4( diffuseColor.r, diffuseColor.g, diffuseColor.b, diffuseColor.a ) ); shader->setVec4( shader->findUniformLocation( "u_tintColor" ), Vec4( tintColor.r, tintColor.g, tintColor.b, tintColor.a ) ); m_hal->setTexture( 0, material->texture( Material::Diffuse ).get() ); m_hal->setTexture( 1, meshRenderer->lightmap().get() ); } else { m_hal->setTexture( 0, NULL ); m_hal->setTexture( 1, NULL ); } m_hal->setVertexBuffer( chunk.m_vertexBuffer.get() ); m_hal->renderIndexed( renderer::PrimTriangles, chunk.m_indexBuffer.get(), 0, chunk.m_indexBuffer->size() ); } } // ** Renderer::render void Renderer::render( const Matrix4& view, const Matrix4& proj, const ScenePtr& scene ) { const SceneObjects& sceneObjects = scene->sceneObjects(); SceneObjects objects[Material::TotalMaterialShaders]; for( SceneObjects::const_iterator i = sceneObjects.begin(), end = sceneObjects.end(); i != end; ++i ) { const SceneObjectPtr& sceneObject = *i; if( !sceneObject->has<MeshRenderer>() ) { continue; } StrongPtr<MeshRenderer> meshRenderer = sceneObject->get<MeshRenderer>(); MaterialPtr material = meshRenderer->material( 0 ); if( material == MaterialPtr() ) { continue; } objects[material->shader()].push_back( sceneObject ); } { for( SceneObjects::const_iterator i = objects[Material::Solid].begin(), end = objects[Material::Solid].end(); i != end; ++i ) { render( view, proj, m_shaders[Material::Solid], *i ); } } { m_hal->setAlphaTest( renderer::Greater, 0.5f ); for( SceneObjects::const_iterator i = objects[Material::Transparent].begin(), end = objects[Material::Transparent].end(); i != end; ++i ) { render( view, proj, m_shaders[Material::Transparent], *i ); } m_hal->setAlphaTest( renderer::CompareDisabled ); } { m_hal->setDepthTest( false, renderer::Less ); m_hal->setBlendFactors( renderer::BlendOne, renderer::BlendOne ); for( SceneObjects::const_iterator i = objects[Material::Additive].begin(), end = objects[Material::Additive].end(); i != end; ++i ) { render( view, proj, m_shaders[Material::Additive], *i ); } m_hal->setDepthTest( true, renderer::Less ); m_hal->setBlendFactors( renderer::BlendDisabled, renderer::BlendDisabled ); } m_hal->setShader( NULL ); } } // namespace scene DC_END_DREEMCHEST<|endoftext|>
<commit_before>#include "btcwif.h" #include <cassert> #include <ecdsa/base58.h> #include "utils.h" namespace btc { namespace wif { std::string PrivateKeyToWif(const std::vector<uint8_t> &priv_key) { // 0. Preparing... std::vector<uint8_t> pk2(priv_key.size() + 1); // 1. 0x80 to front. pk2[0] = 0x80; memcpy(pk2.data() + 1, priv_key.data(), priv_key.size()); // 2. 0x01 to back. pk2.push_back(0x01); // 3. Perform SHA256 on extended key. std::vector<uint8_t> check_sum_half = utils::sha256(pk2.data(), pk2.size()); std::vector<uint8_t> check_sum = utils::sha256(check_sum_half.data(), check_sum_half.size()); // 4. Add 4 bytes from check sum to pk2. std::vector<uint8_t> pk4(pk2.size() + 4); memcpy(pk4.data(), pk2.data(), pk2.size()); memcpy(pk4.data() + pk2.size(), check_sum.data(), 4); // 5. Base58 return base58::EncodeBase58(pk4); } std::vector<uint8_t> WifToPrivateKey(const std::string &priv_key_str) { // 1. Revert base58 to data. std::vector<uint8_t> pk1; assert(base58::DecodeBase58(priv_key_str, pk1)); // 2. Calculate size. size_t size; size_t add_index = pk1.size() - 4; if (pk1[add_index] == 0x01) { size = pk1.size() - 6; } else { size = pk1.size() - 5; } // 3. Remove first 1 byte, last 4 byte(s) and // last 1 byte if it equals to 0x01. std::vector<uint8_t> pk2(size); memcpy(pk2.data(), pk1.data() + 1, size); return pk2; } bool VerifyWifString(const std::string &priv_key_str) { std::vector<uint8_t> priv_key_data; bool succ = base58::DecodeBase58(priv_key_str, priv_key_data); if (!succ) return false; std::vector<uint8_t> last_4_bytes(4); memcpy(last_4_bytes.data(), priv_key_data.data() + (priv_key_data.size() - 4), 4); std::vector<uint8_t> priv_key_data_to_hash(priv_key_data.size() - 4); memcpy(priv_key_data_to_hash.data(), priv_key_data.data(), priv_key_data.size()); std::vector<uint8_t> check_sum_half = utils::sha256(priv_key_data_to_hash.data(), priv_key_data_to_hash.size()); std::vector<uint8_t> check_sum = utils::sha256(check_sum_half.data(), check_sum_half.size()); return memcmp(check_sum.data(), last_4_bytes.data(), 4) == 0; } } // namespace wif } // namespace btc <commit_msg>Fix problems in `WifToPrivate` function.<commit_after>#include "btcwif.h" #include <cassert> #include <ecdsa/base58.h> #include "utils.h" namespace btc { namespace wif { std::string PrivateKeyToWif(const std::vector<uint8_t> &priv_key) { // 0. Preparing... std::vector<uint8_t> pk2(priv_key.size() + 1); // 1. 0x80 to front. pk2[0] = 0x80; memcpy(pk2.data() + 1, priv_key.data(), priv_key.size()); // 2. 0x01 to back. pk2.push_back(0x01); // 3. Perform SHA256 on extended key. std::vector<uint8_t> check_sum_half = utils::sha256(pk2.data(), pk2.size()); std::vector<uint8_t> check_sum = utils::sha256(check_sum_half.data(), check_sum_half.size()); // 4. Add 4 bytes from check sum to pk2. std::vector<uint8_t> pk4(pk2.size() + 4); memcpy(pk4.data(), pk2.data(), pk2.size()); memcpy(pk4.data() + pk2.size(), check_sum.data(), 4); // 5. Base58 return base58::EncodeBase58(pk4); } std::vector<uint8_t> WifToPrivateKey(const std::string &priv_key_str) { // 1. Revert base58 to data. std::vector<uint8_t> pk1; assert(base58::DecodeBase58(priv_key_str, pk1)); // 2. Calculate size. size_t size; size_t add_index = pk1.size() - 5; if (pk1[add_index] == 0x01) { size = pk1.size() - 6; } else { size = pk1.size() - 5; } // 3. Remove first 1 byte, last 4 byte(s) and // last 1 byte if it equals to 0x01. std::vector<uint8_t> pk2(size); memcpy(pk2.data(), pk1.data() + 1, size); return pk2; } bool VerifyWifString(const std::string &priv_key_str) { std::vector<uint8_t> priv_key_data; bool succ = base58::DecodeBase58(priv_key_str, priv_key_data); if (!succ) return false; std::vector<uint8_t> last_4_bytes(4); memcpy(last_4_bytes.data(), priv_key_data.data() + (priv_key_data.size() - 4), 4); std::vector<uint8_t> priv_key_data_to_hash(priv_key_data.size() - 4); memcpy(priv_key_data_to_hash.data(), priv_key_data.data(), priv_key_data_to_hash.size()); std::vector<uint8_t> check_sum_half = utils::sha256(priv_key_data_to_hash.data(), priv_key_data_to_hash.size()); std::vector<uint8_t> check_sum = utils::sha256(check_sum_half.data(), check_sum_half.size()); return memcmp(check_sum.data(), last_4_bytes.data(), 4) == 0; } } // namespace wif } // namespace btc <|endoftext|>
<commit_before>/* * 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 <fstream> #include <iostream> #include <sstream> #include "../include/data/constructs/KeyValue.h" #include "../include/data/constructs/security/Authorizations.h" #include "../include/scanner/constructs/Results.h" #include "../include/scanner/impl/Scanner.h" #include "../include/data/constructs/client/zookeeperinstance.h" #include "../include/interconnect/Master.h" #include "../include/interconnect/tableOps/TableOperations.h" #include "../include/data/constructs/rfile/SequentialRFile.h" #include "../include/data/constructs/compressor/compressor.h" #include "../include/data/constructs/compressor/zlibCompressor.h" #include "../include/data/streaming/input/MemorymappedInputStream.h" #include "data/streaming/input/ReadAheadInputStream.h" #include "../include/data/streaming/OutputStream.h" #include "data/iterators/MultiIterator.h" #include "data/streaming/accumulo/KeyValueIterator.h" #include "data/constructs/rfile/RFileOperations.h" #include "data/streaming/input/HdfsInputStream.h" #include "logging/Logger.h" #include "logging/LoggerConfiguration.h" #define BOOST_IOSTREAMS_NO_LIB 1 bool keyCompare(std::shared_ptr<cclient::data::KeyValue> a, std::shared_ptr<cclient::data::KeyValue> b) { return *(a->getKey()) < *(b->getKey()); } std::ifstream::pos_type filesize(const char *filename) { std::ifstream in(filename, std::ifstream::ate | std::ifstream::binary); return in.tellg(); } std::unique_ptr<cclient::data::streams::KeyValueIterator> createMultiReader(std::vector<std::string> rfiles) { std::vector<std::shared_ptr<cclient::data::streams::KeyValueIterator>> iters; for (const auto &path : rfiles) { size_t size = 0; std::unique_ptr<cclient::data::streams::InputStream> stream; if (path.find("hdfs://") != std::string::npos) { auto str = std::make_unique<cclient::data::streams::HdfsInputStream>(path); size = str->getFileSize(); stream = std::move(str); } else { size = filesize(path.c_str()); auto in = std::make_unique<std::ifstream>(path, std::ifstream::ate | std::ifstream::binary); stream = std::make_unique<cclient::data::streams::InputStream>(std::move(in), 0); } auto endstream = std::make_unique<cclient::data::streams::ReadAheadInputStream>(std::move(stream), 128 * 1024, 1024 * 1024, size); if (rfiles.size() == 1) { return std::make_unique<cclient::data::SequentialRFile>(std::move(endstream), size); } else { auto newRFile = std::make_shared<cclient::data::SequentialRFile>(std::move(endstream), size); iters.emplace_back(newRFile); } } return std::make_unique<cclient::data::MultiIterator>(iters); } void readRfile(std::vector<std::string> &rfiles, uint16_t port, bool print, const std::string &visibility) { std::atomic<int64_t> cntr; cntr = 1; auto start = chrono::steady_clock::now(); std::shared_ptr<cclient::data::streams::KeyValueIterator> multi_iter = cclient::data::RFileOperations::openManySequential(rfiles); std::vector<std::string> cf; cclient::data::Range rng; cclient::data::security::Authorizations auths; if (!visibility.empty()) { auths.addAuthorization(visibility); } cclient::data::streams::StreamSeekable seekable(rng, cf, auths, false); multi_iter->relocate(&seekable); long count = 0; uint64_t total_size = 0; while (multi_iter->hasNext()) { if (print) { std::cout << "has next " << (**multi_iter).first << std::endl; std::stringstream ss; ss << (**multi_iter).first; total_size += ss.str().size(); } multi_iter->next(); count++; if ((count % 100000) == 0) cntr.fetch_add(100000, std::memory_order_relaxed); } if (print) { std::cout << "Bytes accessed " << total_size << std::endl; } auto end = chrono::steady_clock::now(); std::cout << "we done at " << count << " " << chrono::duration_cast<chrono::milliseconds>(end - start).count() << std::endl; std::cout << "Skipped " << multi_iter->getEntriesFiltered() << std::endl; return; } int main(int argc, char **argv) { if (argc < 2) { std::cout << "Arguments required: ./RfileReadExample" << " -r <input rfile(s) can be more than one> " << std::endl; std::cout << "Optional arguments: -p -- print keys " << std::endl; std::cout << "Optional arguments: -v <visibility> -- visibility " << std::endl; exit(1); } logging::LoggerConfiguration::enableTraceLogger(); std::vector<std::string> rfiles; std::string visibility; bool print = false; if (argc >= 2) { for (int i = 1; i < argc; i++) { // always assume big endian std::string key = argv[i]; if (key == "-p") { print = true; } if (key == "-v") { if (i + 1 < argc) { visibility = argv[i + 1]; i++; } else { throw std::runtime_error("Invalid number of arguments. Must supply visibility"); } } if (key == "-r") { if (i + 1 < argc) { rfiles.push_back(argv[i + 1]); i++; } else { throw std::runtime_error("Invalid number of arguments. Must supply rfile"); } } if (key == "-r") { if (i + 1 < argc) { rfiles.push_back(argv[i + 1]); i++; } else { throw std::runtime_error("Invalid number of arguments. Must supply rfile"); } } } } if (!rfiles.empty()) { readRfile(rfiles, 0, print, visibility); } return 0; } <commit_msg>update<commit_after>/* * 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 <fstream> #include <iostream> #include <sstream> #include "../include/data/constructs/KeyValue.h" #include "../include/data/constructs/security/Authorizations.h" #include "../include/scanner/constructs/Results.h" #include "../include/scanner/impl/Scanner.h" #include "../include/data/constructs/client/zookeeperinstance.h" #include "../include/interconnect/Master.h" #include "../include/interconnect/tableOps/TableOperations.h" #include "../include/data/constructs/rfile/SequentialRFile.h" #include "../include/data/constructs/compressor/compressor.h" #include "../include/data/constructs/compressor/zlibCompressor.h" #include "../include/data/streaming/input/MemorymappedInputStream.h" #include "data/streaming/input/ReadAheadInputStream.h" #include "../include/data/streaming/OutputStream.h" #include "data/iterators/MultiIterator.h" #include "data/streaming/accumulo/KeyValueIterator.h" #include "data/constructs/rfile/RFileOperations.h" #include "data/streaming/input/HdfsInputStream.h" #include "logging/Logger.h" #include "logging/LoggerConfiguration.h" #define BOOST_IOSTREAMS_NO_LIB 1 bool keyCompare(std::shared_ptr<cclient::data::KeyValue> a, std::shared_ptr<cclient::data::KeyValue> b) { return *(a->getKey()) < *(b->getKey()); } std::ifstream::pos_type filesize(const char *filename) { std::ifstream in(filename, std::ifstream::ate | std::ifstream::binary); return in.tellg(); } std::unique_ptr<cclient::data::streams::KeyValueIterator> createMultiReader(std::vector<std::string> rfiles) { std::vector<std::shared_ptr<cclient::data::streams::KeyValueIterator>> iters; for (const auto &path : rfiles) { size_t size = 0; std::unique_ptr<cclient::data::streams::InputStream> stream; if (path.find("hdfs://") != std::string::npos) { auto str = std::make_unique<cclient::data::streams::HdfsInputStream>(path); size = str->getFileSize(); stream = std::move(str); } else { size = filesize(path.c_str()); auto in = std::make_unique<std::ifstream>(path, std::ifstream::ate | std::ifstream::binary); stream = std::make_unique<cclient::data::streams::InputStream>(std::move(in), 0); } auto endstream = std::make_unique<cclient::data::streams::ReadAheadInputStream>(std::move(stream), 128 * 1024, 1024 * 1024, size); if (rfiles.size() == 1) { return std::make_unique<cclient::data::SequentialRFile>(std::move(endstream), size); } else { auto newRFile = std::make_shared<cclient::data::SequentialRFile>(std::move(endstream), size); iters.emplace_back(newRFile); } } return std::make_unique<cclient::data::MultiIterator>(iters); } void readRfile(std::vector<std::string> &rfiles, uint16_t port, bool print, const std::string &visibility) { std::atomic<int64_t> cntr; cntr = 1; auto start = chrono::steady_clock::now(); std::shared_ptr<cclient::data::streams::KeyValueIterator> multi_iter = cclient::data::RFileOperations::openManySequential(rfiles); std::vector<std::string> cf; cclient::data::Range rng; cclient::data::security::Authorizations auths; if (!visibility.empty()) { auths.addAuthorization(visibility); } cclient::data::streams::StreamSeekable seekable(rng, cf, auths, false); multi_iter->relocate(&seekable); long count = 0; uint64_t total_size = 0; while (multi_iter->hasNext()) { if (print) { std::cout << "has next " << (**multi_iter).first << std::endl; std::stringstream ss; ss << (**multi_iter).first; total_size += ss.str().size(); } multi_iter->next(); count++; if ((count % 100000) == 0) cntr.fetch_add(100000, std::memory_order_relaxed); } if (print) { std::cout << "Bytes accessed " << total_size << std::endl; } auto end = chrono::steady_clock::now(); std::cout << "we done at " << count << " " << chrono::duration_cast<chrono::milliseconds>(end - start).count() << std::endl; std::cout << "Skipped " << multi_iter->getEntriesFiltered() << std::endl; return; } int main(int argc, char **argv) { if (argc < 2) { std::cout << "Arguments required: ./RfileReadExample" << " -r <input rfile(s) can be more than one> " << std::endl; std::cout << "Optional arguments: -p -- print keys " << std::endl; std::cout << "Optional arguments: -v <visibility> -- visibility " << std::endl; exit(1); } logging::LoggerConfiguration::enableTraceLogger(); std::vector<std::string> rfiles; std::string visibility; bool print = false; long iterations = 1; if (argc >= 2) { for (int i = 1; i < argc; i++) { // always assume big endian std::string key = argv[i]; if (key == "-p") { print = true; } if (key == "-v") { if (i + 1 < argc) { visibility = argv[i + 1]; i++; } else { throw std::runtime_error("Invalid number of arguments. Must supply visibility"); } } if (key == "-r") { if (i + 1 < argc) { rfiles.push_back(argv[i + 1]); i++; } else { throw std::runtime_error("Invalid number of arguments. Must supply rfile"); } } if (key == "-i") { if (i + 1 < argc) { iterations = std::stoi(argv[i + 1]); i++; } else { throw std::runtime_error("Invalid number of arguments. Must supply nmumber of iterations"); } } } } if (!rfiles.empty()) { for(long i=0; i < iterations; i++){ readRfile(rfiles, 0, print, visibility); } } return 0; } <|endoftext|>
<commit_before>#include <rleahylib/rleahylib.hpp> #include <world/world.hpp> #include <mod.hpp> #include <cstring> #include <limits> #include <utility> static const String name("Super Flat World Generator"); static const Word priority=2; static const SByte dimensions []={0}; // Key used in the backing store for the // super flat code static const String key("superflat_preset_code"); // The world type string which identifies // this generator static const String world_type("FLAT"); // Default preset code used in the absence // of a code from the database static const String default_preset("2;7,2x3,2"); static const Regex preset_parse("(?<=^|;).*?(?=$|;)"); static const Regex block_parse( "(?<=^|,)\\s*(?:(\\d+)\\s*x\\s*)?(\\d+)(?:\\s*\\:\\s*(\\d+))?\\s*(?=$|,)", RegexOptions().SetIgnoreCase() ); // Presets ripped directly from vanilla // Minecraft static const Vector<Tuple<String,String>> presets={ { "Classic Flat", default_preset }, { "Tunneler's Dream", "2;7,230x1,5x3,2;3" }, { "Water World", "2;7,5x1,5x3,5x12,90x9;1" }, { "Overworld", "2;7,59x1,3x3,2;1" }, { "Snowy Kingdom", "2;7,59x1,3x3,2,78;12" }, { "Bottomless Pit", "2;2x4,3x3,2;1" }, { "Desert", "2;7,3x1,52x24,8x12;2" }, { "Redstone Ready", "2;7,3x1,52x24;2" } }; // Parses the preset code into a tuple specifying // blocks on a per layer basis (from zero up) and // biome static Nullable<Tuple<Vector<Block>,Biome>> parse (const String & code) { Nullable< Tuple< Vector<Block>, Biome > > retr; // Attempt to do a high level parse, extracting // each of the semicolon-delimited substrings auto matches=preset_parse.Matches(code); Word version; // Version number if (!( // We need at least two matches -- the // version number and the layers // specification (matches.Count()>=2) && // We need to attempt to extract the // version number from the first match. // If this isn't an integer, we cannot // proceed matches[0].Value().Trim().ToInteger(&version) && // Only supported version at the moment // is version 2 (version==2) )) return retr; // Default biome is plains Biome biome=Biome::Plains; // If there are three or more semicolon-delimited // substrings, the third one specifies a biome if (matches.Count()>=3) { Byte biome_byte; // Check to make sure the third match is // // A. A valid byte. // B. A valid biome. // // If it is not, fail out. if (!( matches[2].Value().Trim().ToInteger(&biome_byte) && IsValidBiome(biome_byte) )) return retr; // Biome byte has been validated, assign biome=static_cast<Biome>(biome_byte); } // Attempt to match layer specifications Vector<Block> layers; for (auto & match : block_parse.Matches(matches[1].Value())) { // If we've added enough layers already, // abort if (layers.Count()>256) return retr; // Number of times this layer will // be repeated -- defaults to 1 Word multiplier=1; // ID of the block to fill this layer // with UInt16 id; // Metadata to use for the blocks // making up this layer -- defaults // to zero Byte metadata=0; // Attempt to extract data from // regular expression match if (!( // Extract multiplier if it's // specified ( (match[1].Count()==0) || ( match[1].Value().ToInteger(&multiplier) && // Sanity check on the multiplier ((layers.Count()+multiplier)<=256) ) ) && // Extract block ID match[2].Value().ToInteger(&id) && // Sanity check block ID -- valid // block IDs are 0-4095 (inclusive) (id<4096) && // Extract metadata if it's // specified ( (match[3].Count()==0) || ( match[3].Value().ToInteger(&metadata) && // Valid metadata values are // 0-15 (inclusive) (metadata<16) ) ) )) return retr; // VALID -- add layers Block block(id); block.SetMetadata(metadata); for (Word i=0;i<multiplier;++i) layers.Add(block); } // If no layers were specified, abort if (layers.Count()==0) return retr; retr.Construct( std::move(layers), biome ); return retr; } class SuperFlatGenerator : public Module, public WorldGenerator { private: // A template of the column that // will be repeatedly "generated" // via memcpy Block blocks [16*16*16*16]; // The biome that will be set on // all columns Biome biome; public: virtual const String & Name () const noexcept override { return name; } virtual Word Priority () const noexcept override { return priority; } virtual void Install () override { // Attempt to get a preset code from // the backing store auto code=Server::Get().Data().GetSetting(key); // The spec to which we'll build the // template column decltype(parse(*code)) spec; // Attempt to get a spec from the code // loaded from the backing store if (!code.IsNull()) { // Check to see if the code is one // of the presets bool found=false; for (auto & t : presets) if (*code==t.Item<0>()) { spec=parse(t.Item<1>()); found=true; break; } // If it wasn't a preset, attempt // to parse if (!found) spec=parse(*code); } // If that fails, attempt to get a spec // from the default preset if (spec.IsNull()) spec=parse(default_preset); // If that fails, PANIC if (spec.IsNull()) { Server::Get().Panic(); // DO NOT EXECUTE THE REMAINDER // OF THIS FUNCTION return; } const auto & layers=spec->Item<0>(); biome=spec->Item<1>(); // Loop over the template column in memory // order (for locality's sake) Word offset=0; // Offset within the template column for (Byte y=0;;++y) { for (Word z=0;z<16;++z) for (Word x=0;x<16;++x) { // If we're within range of the specified // blocks, set the specified block, otherwise // use air blocks[offset++]=(y<layers.Count()) ? layers[y] : Block(); } // Check for end of loop if (y==std::numeric_limits<Byte>::max()) break; } // Install ourselves into the // world container auto & world=World::Get(); for (auto d : dimensions) world.Add( this, world_type, d ); } virtual void operator () (ColumnContainer & column) const override { // Ensure that the copy operation // is safe static_assert( (sizeof(column.Blocks)==sizeof(blocks)), "Layout incompatible" ); // Since all superflat generated // columns are identical, we just // have to memcpy std::memcpy( column.Blocks, blocks, sizeof(column.Blocks) ); // Loop and set all biomes for (auto & b : column.Biomes) b=biome; } }; INSTALL_MODULE(SuperFlatGenerator) <commit_msg>Superflat Generator Fixes<commit_after>#include <rleahylib/rleahylib.hpp> #include <world/world.hpp> #include <mod.hpp> #include <server.hpp> #include <cstring> #include <limits> #include <utility> using namespace MCPP; static const String name("Super Flat World Generator"); static const Word priority=2; static const SByte dimensions []={0}; // Key used in the backing store for the // super flat code static const String key("superflat_preset_code"); // The world type string which identifies // this generator static const String world_type("FLAT"); // Default preset code used in the absence // of a code from the database static const String default_preset("2;7,2x3,2"); static const Regex preset_parse("(?<=^|;).*?(?=$|;)"); static const Regex block_parse( "(?<=^|,)\\s*(?:(\\d+)\\s*x\\s*)?(\\d+)(?:\\s*\\:\\s*(\\d+))?\\s*(?=$|,)", RegexOptions().SetIgnoreCase() ); // Presets ripped directly from vanilla // Minecraft static const Vector<Tuple<String,String>> presets={ { "Classic Flat", default_preset }, { "Tunneler's Dream", "2;7,230x1,5x3,2;3" }, { "Water World", "2;7,5x1,5x3,5x12,90x9;1" }, { "Overworld", "2;7,59x1,3x3,2;1" }, { "Snowy Kingdom", "2;7,59x1,3x3,2,78;12" }, { "Bottomless Pit", "2;2x4,3x3,2;1" }, { "Desert", "2;7,3x1,52x24,8x12;2" }, { "Redstone Ready", "2;7,3x1,52x24;2" } }; // Parses the preset code into a tuple specifying // blocks on a per layer basis (from zero up) and // biome static Nullable<Tuple<Vector<Block>,Biome>> parse (const String & code) { Nullable< Tuple< Vector<Block>, Biome > > retr; // Attempt to do a high level parse, extracting // each of the semicolon-delimited substrings auto matches=preset_parse.Matches(code); Word version; // Version number if (!( // We need at least two matches -- the // version number and the layers // specification (matches.Count()>=2) && // We need to attempt to extract the // version number from the first match. // If this isn't an integer, we cannot // proceed matches[0].Value().Trim().ToInteger(&version) && // Only supported version at the moment // is version 2 (version==2) )) return retr; // Default biome is plains Biome biome=Biome::Plains; // If there are three or more semicolon-delimited // substrings, the third one specifies a biome if (matches.Count()>=3) { Byte biome_byte; // Check to make sure the third match is // // A. A valid byte. // B. A valid biome. // // If it is not, fail out. if (!( matches[2].Value().Trim().ToInteger(&biome_byte) && IsValidBiome(biome_byte) )) return retr; // Biome byte has been validated, assign biome=static_cast<Biome>(biome_byte); } // Attempt to match layer specifications Vector<Block> layers; for (auto & match : block_parse.Matches(matches[1].Value())) { // If we've added enough layers already, // abort if (layers.Count()>256) return retr; // Number of times this layer will // be repeated -- defaults to 1 Word multiplier=1; // ID of the block to fill this layer // with UInt16 id; // Metadata to use for the blocks // making up this layer -- defaults // to zero Byte metadata=0; // Attempt to extract data from // regular expression match if (!( // Extract multiplier if it's // specified ( (match[1].Count()==0) || ( match[1].Value().ToInteger(&multiplier) && // Sanity check on the multiplier ((layers.Count()+multiplier)<=256) ) ) && // Extract block ID match[2].Value().ToInteger(&id) && // Sanity check block ID -- valid // block IDs are 0-4095 (inclusive) (id<4096) && // Extract metadata if it's // specified ( (match[3].Count()==0) || ( match[3].Value().ToInteger(&metadata) && // Valid metadata values are // 0-15 (inclusive) (metadata<16) ) ) )) return retr; // VALID -- add layers Block block(id); block.SetMetadata(metadata); for (Word i=0;i<multiplier;++i) layers.Add(block); } // If no layers were specified, abort if (layers.Count()==0) return retr; retr.Construct( std::move(layers), biome ); return retr; } class SuperFlatGenerator : public Module, public WorldGenerator { private: // A template of the column that // will be repeatedly "generated" // via memcpy Block blocks [16*16*16*16]; // The biome that will be set on // all columns Biome biome; public: virtual const String & Name () const noexcept override { return name; } virtual Word Priority () const noexcept override { return priority; } virtual void Install () override { // Attempt to get a preset code from // the backing store auto code=Server::Get().Data().GetSetting(key); // The spec to which we'll build the // template column decltype(parse(*code)) spec; // Attempt to get a spec from the code // loaded from the backing store if (!code.IsNull()) { // Check to see if the code is one // of the presets bool found=false; for (auto & t : presets) if (*code==t.Item<0>()) { spec=parse(t.Item<1>()); found=true; break; } // If it wasn't a preset, attempt // to parse if (!found) spec=parse(*code); } // If that fails, attempt to get a spec // from the default preset if (spec.IsNull()) spec=parse(default_preset); // If that fails, PANIC if (spec.IsNull()) { Server::Get().Panic(); // DO NOT EXECUTE THE REMAINDER // OF THIS FUNCTION return; } const auto & layers=spec->Item<0>(); biome=spec->Item<1>(); // Loop over the template column in memory // order (for locality's sake) Word offset=0; // Offset within the template column for (Byte y=0;;++y) { for (Word z=0;z<16;++z) for (Word x=0;x<16;++x) { // If we're within range of the specified // blocks, set the specified block, otherwise // use air blocks[offset++]=(y<layers.Count()) ? layers[y] : Block(); } // Check for end of loop if (y==std::numeric_limits<Byte>::max()) break; } // Install ourselves into the // world container auto & world=World::Get(); for (auto d : dimensions) world.Add( this, world_type, d ); } virtual void operator () (ColumnContainer & column) const override { // Ensure that the copy operation // is safe static_assert( (sizeof(column.Blocks)==sizeof(blocks)), "Layout incompatible" ); // Since all superflat generated // columns are identical, we just // have to memcpy std::memcpy( column.Blocks, blocks, sizeof(column.Blocks) ); // Loop and set all biomes for (auto & b : column.Biomes) b=biome; } }; INSTALL_MODULE(SuperFlatGenerator) <|endoftext|>
<commit_before><commit_msg>Bin dead and commented-out code<commit_after><|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // BSD 3-Clause License // // Copyright (c) 2019, OpenROAD // 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 the copyright holder 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 HOLDER 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. #include "tclCmdInputWidget.h" #include <tcl.h> #include <QMimeData> #include <QTextStream> #include <QMenu> namespace gui { TclCmdInputWidget::TclCmdInputWidget(QWidget* parent) : QPlainTextEdit(parent) { setObjectName("tcl_scripting"); // for settings setPlaceholderText("TCL commands"); setAcceptDrops(true); max_height_ = QWIDGETSIZE_MAX; determineLineHeight(); highlighter_ = nullptr; // add option to default context menu to enable or disable syntax highlighting context_menu_.reset(createStandardContextMenu()); context_menu_->addSeparator(); enable_highlighting_ = std::make_unique<QAction>("Syntax highlighting", this); enable_highlighting_->setCheckable(true); enable_highlighting_->setChecked(true); context_menu_->addAction(enable_highlighting_.get()); connect(enable_highlighting_.get(), SIGNAL(triggered()), this, SLOT(updateHighlighting())); // precompute size for updating text box size document_margins_ = 2 * (document()->documentMargin() + 3); connect(this, SIGNAL(textChanged()), this, SLOT(updateSize())); updateSize(); } TclCmdInputWidget::~TclCmdInputWidget() { } void TclCmdInputWidget::setFont(const QFont& font) { QPlainTextEdit::setFont(font); determineLineHeight(); } void TclCmdInputWidget::determineLineHeight() { QFontMetrics font_metrics = fontMetrics(); line_height_ = font_metrics.lineSpacing(); double tab_indent_width = 2 * font_metrics.averageCharWidth(); #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)) // setTabStopWidth deprecated in 5.10 setTabStopDistance(tab_indent_width); #else setTabStopWidth(tab_indent_width); #endif } void TclCmdInputWidget::keyPressEvent(QKeyEvent* e) { bool forward_key_press = true; bool has_control = e->modifiers().testFlag(Qt::ControlModifier); int key = e->key(); if (key == Qt::Key_Enter || key == Qt::Key_Return) { // Handle enter if (has_control) { // don't execute just insert the newline // does not get inserted by Qt, so manually inserting insertPlainText("\n"); } else { // Check if command complete and attempt to execute, otherwise do nothing if (isCommandComplete(toPlainText().simplified().toStdString())) { emit completeCommand(); if (toPlainText().isEmpty()) { // if successful, contents was cleared forward_key_press = false; } } } } else if (key == Qt::Key_Down) { // Handle down through history // control+down immediate if ((!textCursor().hasSelection() && !textCursor().movePosition(QTextCursor::Down)) || has_control) { emit historyGoForward(); } } else if (key == Qt::Key_Up) { // Handle up through history // control+up immediate if ((!textCursor().hasSelection() && !textCursor().movePosition(QTextCursor::Up)) || has_control) { emit historyGoBack(); } } if (forward_key_press) { QPlainTextEdit::keyPressEvent(e); } } void TclCmdInputWidget::keyReleaseEvent(QKeyEvent* e) { int key = e->key(); if (key == Qt::Key_Enter || key == Qt::Key_Return) { // announce that text might have changed due to enter key // to ensure resizing is processed emit textChanged(); } QPlainTextEdit::keyReleaseEvent(e); } bool TclCmdInputWidget::isCommandComplete(const std::string& cmd) { if (cmd.empty()) { return false; } // check if last character is \, then assume it is multiline if (cmd.at(cmd.size() - 1) == '\\') { return false; } return Tcl_CommandComplete(cmd.c_str()); } // Slot to announce command executed void TclCmdInputWidget::commandExecuted(int return_code) { if (return_code == TCL_OK) { clear(); } } // Update the size of the widget to match text void TclCmdInputWidget::updateSize() { int height = document()->size().toSize().height(); if (height < 1) { height = 1; // ensure minimum is 1 line } // in px int desired_height = height * line_height_ + document_margins_; if (desired_height > max_height_) { desired_height = max_height_; // ensure maximum from Qt suggestion } setFixedHeight(desired_height); ensureCursorVisible(); } // Handle dragged and drop script files void TclCmdInputWidget::dragEnterEvent(QDragEnterEvent* event) { if (event->mimeData()->text().startsWith("file://")) { event->accept(); } } void TclCmdInputWidget::dropEvent(QDropEvent* event) { if (event->mimeData()->text().startsWith("file://")) { event->accept(); // replace the content in the text area with the file QFile drop_file(event->mimeData()->text().remove(0, 7).simplified()); if (drop_file.open(QIODevice::ReadOnly)) { QTextStream file_data(&drop_file); setText(file_data.readAll()); drop_file.close(); } } } // setup syntax highlighter void TclCmdInputWidget::init(Tcl_Interp* interp) { highlighter_ = std::make_unique<TclCmdHighlighter>(document(), interp); updateHighlighting(); } // replicate QLineEdit function QString TclCmdInputWidget::text() { return toPlainText(); } // replicate QLineEdit function void TclCmdInputWidget::setText(const QString& text) { setPlainText(text); emit textChanged(); } void TclCmdInputWidget::setMaximumHeight(int height) { int min_height = line_height_ + document_margins_; // atleast one line if (height < min_height) { height = min_height; } // save max height, since it's overwritten by setFixedHeight max_height_ = height; QPlainTextEdit::setMaximumHeight(height); updateSize(); } void TclCmdInputWidget::contextMenuEvent(QContextMenuEvent *event) { context_menu_->exec(event->globalPos()); } void TclCmdInputWidget::updateHighlighting() { if (highlighter_ != nullptr) { if (enable_highlighting_->isChecked()) { highlighter_->setDocument(document()); } else { highlighter_->setDocument(nullptr); } } } void TclCmdInputWidget::readSettings(QSettings* settings) { settings->beginGroup(objectName()); enable_highlighting_->setChecked(settings->value(enable_highlighting_keyword_, true).toBool()); settings->endGroup(); } void TclCmdInputWidget::writeSettings(QSettings* settings) { settings->beginGroup(objectName()); settings->setValue(enable_highlighting_keyword_, enable_highlighting_->isChecked()); settings->endGroup(); } } // namespace gui <commit_msg>gui: only add new lines to commands if they are incomplete<commit_after>/////////////////////////////////////////////////////////////////////////////// // BSD 3-Clause License // // Copyright (c) 2019, OpenROAD // 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 the copyright holder 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 HOLDER 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. #include "tclCmdInputWidget.h" #include <tcl.h> #include <QMimeData> #include <QTextStream> #include <QMenu> namespace gui { TclCmdInputWidget::TclCmdInputWidget(QWidget* parent) : QPlainTextEdit(parent) { setObjectName("tcl_scripting"); // for settings setPlaceholderText("TCL commands"); setAcceptDrops(true); max_height_ = QWIDGETSIZE_MAX; determineLineHeight(); highlighter_ = nullptr; // add option to default context menu to enable or disable syntax highlighting context_menu_.reset(createStandardContextMenu()); context_menu_->addSeparator(); enable_highlighting_ = std::make_unique<QAction>("Syntax highlighting", this); enable_highlighting_->setCheckable(true); enable_highlighting_->setChecked(true); context_menu_->addAction(enable_highlighting_.get()); connect(enable_highlighting_.get(), SIGNAL(triggered()), this, SLOT(updateHighlighting())); // precompute size for updating text box size document_margins_ = 2 * (document()->documentMargin() + 3); connect(this, SIGNAL(textChanged()), this, SLOT(updateSize())); updateSize(); } TclCmdInputWidget::~TclCmdInputWidget() { } void TclCmdInputWidget::setFont(const QFont& font) { QPlainTextEdit::setFont(font); determineLineHeight(); } void TclCmdInputWidget::determineLineHeight() { QFontMetrics font_metrics = fontMetrics(); line_height_ = font_metrics.lineSpacing(); double tab_indent_width = 2 * font_metrics.averageCharWidth(); #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)) // setTabStopWidth deprecated in 5.10 setTabStopDistance(tab_indent_width); #else setTabStopWidth(tab_indent_width); #endif } void TclCmdInputWidget::keyPressEvent(QKeyEvent* e) { bool has_control = e->modifiers().testFlag(Qt::ControlModifier); int key = e->key(); if (key == Qt::Key_Enter || key == Qt::Key_Return) { // Handle enter if (has_control) { // don't execute just insert the newline // does not get inserted by Qt, so manually inserting insertPlainText("\n"); return; } else { // Check if command complete and attempt to execute, otherwise do nothing if (isCommandComplete(toPlainText().simplified().toStdString())) { // execute command emit completeCommand(); return; } } } else if (key == Qt::Key_Down) { // Handle down through history // control+down immediate if ((!textCursor().hasSelection() && !textCursor().movePosition(QTextCursor::Down)) || has_control) { emit historyGoForward(); } } else if (key == Qt::Key_Up) { // Handle up through history // control+up immediate if ((!textCursor().hasSelection() && !textCursor().movePosition(QTextCursor::Up)) || has_control) { emit historyGoBack(); } } QPlainTextEdit::keyPressEvent(e); } void TclCmdInputWidget::keyReleaseEvent(QKeyEvent* e) { int key = e->key(); if (key == Qt::Key_Enter || key == Qt::Key_Return) { // announce that text might have changed due to enter key // to ensure resizing is processed emit textChanged(); } QPlainTextEdit::keyReleaseEvent(e); } bool TclCmdInputWidget::isCommandComplete(const std::string& cmd) { if (cmd.empty()) { return false; } // check if last character is \, then assume it is multiline if (cmd.at(cmd.size() - 1) == '\\') { return false; } return Tcl_CommandComplete(cmd.c_str()); } // Slot to announce command executed void TclCmdInputWidget::commandExecuted(int return_code) { if (return_code == TCL_OK) { clear(); } } // Update the size of the widget to match text void TclCmdInputWidget::updateSize() { int height = document()->size().toSize().height(); if (height < 1) { height = 1; // ensure minimum is 1 line } // in px int desired_height = height * line_height_ + document_margins_; if (desired_height > max_height_) { desired_height = max_height_; // ensure maximum from Qt suggestion } setFixedHeight(desired_height); ensureCursorVisible(); } // Handle dragged and drop script files void TclCmdInputWidget::dragEnterEvent(QDragEnterEvent* event) { if (event->mimeData()->text().startsWith("file://")) { event->accept(); } } void TclCmdInputWidget::dropEvent(QDropEvent* event) { if (event->mimeData()->text().startsWith("file://")) { event->accept(); // replace the content in the text area with the file QFile drop_file(event->mimeData()->text().remove(0, 7).simplified()); if (drop_file.open(QIODevice::ReadOnly)) { QTextStream file_data(&drop_file); setText(file_data.readAll()); drop_file.close(); } } } // setup syntax highlighter void TclCmdInputWidget::init(Tcl_Interp* interp) { highlighter_ = std::make_unique<TclCmdHighlighter>(document(), interp); updateHighlighting(); } // replicate QLineEdit function QString TclCmdInputWidget::text() { return toPlainText(); } // replicate QLineEdit function void TclCmdInputWidget::setText(const QString& text) { setPlainText(text); emit textChanged(); } void TclCmdInputWidget::setMaximumHeight(int height) { int min_height = line_height_ + document_margins_; // atleast one line if (height < min_height) { height = min_height; } // save max height, since it's overwritten by setFixedHeight max_height_ = height; QPlainTextEdit::setMaximumHeight(height); updateSize(); } void TclCmdInputWidget::contextMenuEvent(QContextMenuEvent *event) { context_menu_->exec(event->globalPos()); } void TclCmdInputWidget::updateHighlighting() { if (highlighter_ != nullptr) { if (enable_highlighting_->isChecked()) { highlighter_->setDocument(document()); } else { highlighter_->setDocument(nullptr); } } } void TclCmdInputWidget::readSettings(QSettings* settings) { settings->beginGroup(objectName()); enable_highlighting_->setChecked(settings->value(enable_highlighting_keyword_, true).toBool()); settings->endGroup(); } void TclCmdInputWidget::writeSettings(QSettings* settings) { settings->beginGroup(objectName()); settings->setValue(enable_highlighting_keyword_, enable_highlighting_->isChecked()); settings->endGroup(); } } // namespace gui <|endoftext|>
<commit_before>// Copyright 2015 PDFium 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 <limits> #include <string> #include "../../public/fpdfview.h" #include "../../testing/embedder_test.h" #include "fpdfview_c_api_test.h" #include "testing/gtest/include/gtest/gtest.h" TEST(fpdf, CApiTest) { EXPECT_TRUE(CheckPDFiumCApi()); } class FPDFViewEmbeddertest : public EmbedderTest {}; TEST_F(FPDFViewEmbeddertest, Document) { EXPECT_TRUE(OpenDocument("testing/resources/about_blank.pdf")); EXPECT_EQ(1, GetPageCount()); EXPECT_EQ(0, GetFirstPageNum()); int version; EXPECT_TRUE(FPDF_GetFileVersion(document(), &version)); EXPECT_EQ(14, version); EXPECT_EQ(0xFFFFFFFF, FPDF_GetDocPermissions(document())); EXPECT_EQ(-1, FPDF_GetSecurityHandlerRevision(document())); } TEST_F(FPDFViewEmbeddertest, Page) { EXPECT_TRUE(OpenDocument("testing/resources/about_blank.pdf")); FPDF_PAGE page = LoadPage(0); EXPECT_NE(nullptr, page); EXPECT_EQ(612.0, FPDF_GetPageWidth(page)); EXPECT_EQ(792.0, FPDF_GetPageHeight(page)); UnloadPage(page); EXPECT_EQ(nullptr, LoadPage(1)); } TEST_F(FPDFViewEmbeddertest, ViewerRef) { EXPECT_TRUE(OpenDocument("testing/resources/about_blank.pdf")); EXPECT_TRUE(FPDF_VIEWERREF_GetPrintScaling(document())); EXPECT_EQ(1, FPDF_VIEWERREF_GetNumCopies(document())); EXPECT_EQ(DuplexUndefined, FPDF_VIEWERREF_GetDuplex(document())); } TEST_F(FPDFViewEmbeddertest, NamedDests) { EXPECT_TRUE(OpenDocument("testing/resources/named_dests.pdf")); long buffer_size; char fixed_buffer[512]; FPDF_DEST dest; // Query the size of the first item. buffer_size = 2000000; // Absurdly large, check not used for this case. dest = FPDF_GetNamedDest(document(), 0, nullptr, &buffer_size); EXPECT_NE(nullptr, dest); EXPECT_EQ(12u, buffer_size); // Try to retrieve the first item with too small a buffer. buffer_size = 10; dest = FPDF_GetNamedDest(document(), 0, fixed_buffer, &buffer_size); EXPECT_NE(nullptr, dest); EXPECT_EQ(-1, buffer_size); // Try to retrieve the first item with correctly sized buffer. Item is // taken from Dests NameTree in named_dests.pdf. buffer_size = 12; dest = FPDF_GetNamedDest(document(), 0, fixed_buffer, &buffer_size); EXPECT_NE(nullptr, dest); EXPECT_EQ(12u, buffer_size); EXPECT_EQ(std::string("F\0i\0r\0s\0t\0\0\0", 12), std::string(fixed_buffer, buffer_size)); // Try to retrieve the second item with ample buffer. Item is taken // from Dests NameTree but has a sub-dictionary in named_dests.pdf. buffer_size = sizeof(fixed_buffer); dest = FPDF_GetNamedDest(document(), 1, fixed_buffer, &buffer_size); EXPECT_NE(nullptr, dest); EXPECT_EQ(10u, buffer_size); EXPECT_EQ(std::string("N\0e\0x\0t\0\0\0", 10), std::string(fixed_buffer, buffer_size)); // Try to retrieve third item with ample buffer. Item is taken // from Dests NameTree but has a bad sub-dictionary in named_dests.pdf. // in named_dests.pdf). buffer_size = sizeof(fixed_buffer); dest = FPDF_GetNamedDest(document(), 2, fixed_buffer, &buffer_size); EXPECT_EQ(nullptr, dest); EXPECT_EQ(sizeof(fixed_buffer), buffer_size); // unmodified. // Try to retrieve the forth item with ample buffer. Item is taken // from Dests NameTree but has a vale of the wrong type in named_dests.pdf. buffer_size = sizeof(fixed_buffer); dest = FPDF_GetNamedDest(document(), 3, fixed_buffer, &buffer_size); EXPECT_EQ(nullptr, dest); EXPECT_EQ(sizeof(fixed_buffer), buffer_size); // unmodified. // Try to retrieve fifth item with ample buffer. Item taken from the // old-style Dests dictionary object in named_dests.pdf. buffer_size = sizeof(fixed_buffer); dest = FPDF_GetNamedDest(document(), 4, fixed_buffer, &buffer_size); EXPECT_NE(nullptr, dest); EXPECT_EQ(30u, buffer_size); EXPECT_EQ(std::string("F\0i\0r\0s\0t\0A\0l\0t\0e\0r\0n\0a\0t\0e\0\0\0", 30), std::string(fixed_buffer, buffer_size)); // Try to retrieve sixth item with ample buffer. Item istaken from the // old-style Dests dictionary object but has a sub-dictionary in // named_dests.pdf. buffer_size = sizeof(fixed_buffer); dest = FPDF_GetNamedDest(document(), 5, fixed_buffer, &buffer_size); EXPECT_NE(nullptr, dest); EXPECT_EQ(28u, buffer_size); EXPECT_EQ(std::string("L\0a\0s\0t\0A\0l\0t\0e\0r\0n\0a\0t\0e\0\0\0", 28), std::string(fixed_buffer, buffer_size)); // Try to retrieve non-existent item with ample buffer. buffer_size = sizeof(fixed_buffer); dest = FPDF_GetNamedDest(document(), 6, fixed_buffer, &buffer_size); EXPECT_EQ(nullptr, dest); EXPECT_EQ(sizeof(fixed_buffer), buffer_size); // unmodified. // Try to underflow/overflow the integer index. buffer_size = sizeof(fixed_buffer); dest = FPDF_GetNamedDest(document(), std::numeric_limits<int>::max(), fixed_buffer, &buffer_size); EXPECT_EQ(nullptr, dest); EXPECT_EQ(sizeof(fixed_buffer), buffer_size); // unmodified. buffer_size = sizeof(fixed_buffer); dest = FPDF_GetNamedDest(document(), std::numeric_limits<int>::min(), fixed_buffer, &buffer_size); EXPECT_EQ(nullptr, dest); EXPECT_EQ(sizeof(fixed_buffer), buffer_size); // unmodified. buffer_size = sizeof(fixed_buffer); dest = FPDF_GetNamedDest(document(), -1, fixed_buffer, &buffer_size); EXPECT_EQ(nullptr, dest); EXPECT_EQ(sizeof(fixed_buffer), buffer_size); // unmodified. } TEST_F(FPDFViewEmbeddertest, NamedDestsByName) { EXPECT_TRUE(OpenDocument("testing/resources/named_dests.pdf")); // Null pointer returns NULL. FPDF_DEST dest = FPDF_GetNamedDestByName(document(), nullptr); EXPECT_EQ(nullptr, dest); // Empty string returns NULL. dest = FPDF_GetNamedDestByName(document(), ""); EXPECT_EQ(nullptr, dest); // Item from Dests NameTree. dest = FPDF_GetNamedDestByName(document(), "First"); EXPECT_NE(nullptr, dest); long ignore_len = 0; FPDF_DEST dest_by_index = FPDF_GetNamedDest(document(), 0, nullptr, &ignore_len); EXPECT_EQ(dest_by_index, dest); // Item from Dests dictionary. dest = FPDF_GetNamedDestByName(document(), "FirstAlternate"); EXPECT_NE(nullptr, dest); ignore_len = 0; dest_by_index = FPDF_GetNamedDest(document(), 4, nullptr, &ignore_len); EXPECT_EQ(dest_by_index, dest); // Bad value type for item from Dests NameTree array. dest = FPDF_GetNamedDestByName(document(), "WrongType"); EXPECT_EQ(nullptr, dest); // No such destination in either Dest NameTree or dictionary. dest = FPDF_GetNamedDestByName(document(), "Bogus"); EXPECT_EQ(nullptr, dest); } // The following tests pass if the document opens without crashing. TEST_F(FPDFViewEmbeddertest, Crasher_113) { EXPECT_TRUE(OpenDocument("testing/resources/bug_113.pdf")); } TEST_F(FPDFViewEmbeddertest, Crasher_451830) { // Document is damaged and can't be opened. EXPECT_FALSE(OpenDocument("testing/resources/bug_451830.pdf")); } TEST_F(FPDFViewEmbeddertest, Crasher_452455) { EXPECT_TRUE(OpenDocument("testing/resources/bug_452455.pdf")); FPDF_PAGE page = LoadPage(0); EXPECT_NE(nullptr, page); UnloadPage(page); } TEST_F(FPDFViewEmbeddertest, Crasher3) { // Document is damanged and can't be opened. EXPECT_FALSE(OpenDocument("testing/resources/bug_454695.pdf")); } <commit_msg>Make fpdfview_embeddertest.cpp test names match XFA<commit_after>// Copyright 2015 PDFium 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 <limits> #include <string> #include "../../public/fpdfview.h" #include "../../testing/embedder_test.h" #include "fpdfview_c_api_test.h" #include "testing/gtest/include/gtest/gtest.h" TEST(fpdf, CApiTest) { EXPECT_TRUE(CheckPDFiumCApi()); } class FPDFViewEmbeddertest : public EmbedderTest {}; TEST_F(FPDFViewEmbeddertest, Document) { EXPECT_TRUE(OpenDocument("testing/resources/about_blank.pdf")); EXPECT_EQ(1, GetPageCount()); EXPECT_EQ(0, GetFirstPageNum()); int version; EXPECT_TRUE(FPDF_GetFileVersion(document(), &version)); EXPECT_EQ(14, version); EXPECT_EQ(0xFFFFFFFF, FPDF_GetDocPermissions(document())); EXPECT_EQ(-1, FPDF_GetSecurityHandlerRevision(document())); } TEST_F(FPDFViewEmbeddertest, Page) { EXPECT_TRUE(OpenDocument("testing/resources/about_blank.pdf")); FPDF_PAGE page = LoadPage(0); EXPECT_NE(nullptr, page); EXPECT_EQ(612.0, FPDF_GetPageWidth(page)); EXPECT_EQ(792.0, FPDF_GetPageHeight(page)); UnloadPage(page); EXPECT_EQ(nullptr, LoadPage(1)); } TEST_F(FPDFViewEmbeddertest, ViewerRef) { EXPECT_TRUE(OpenDocument("testing/resources/about_blank.pdf")); EXPECT_TRUE(FPDF_VIEWERREF_GetPrintScaling(document())); EXPECT_EQ(1, FPDF_VIEWERREF_GetNumCopies(document())); EXPECT_EQ(DuplexUndefined, FPDF_VIEWERREF_GetDuplex(document())); } TEST_F(FPDFViewEmbeddertest, NamedDests) { EXPECT_TRUE(OpenDocument("testing/resources/named_dests.pdf")); long buffer_size; char fixed_buffer[512]; FPDF_DEST dest; // Query the size of the first item. buffer_size = 2000000; // Absurdly large, check not used for this case. dest = FPDF_GetNamedDest(document(), 0, nullptr, &buffer_size); EXPECT_NE(nullptr, dest); EXPECT_EQ(12u, buffer_size); // Try to retrieve the first item with too small a buffer. buffer_size = 10; dest = FPDF_GetNamedDest(document(), 0, fixed_buffer, &buffer_size); EXPECT_NE(nullptr, dest); EXPECT_EQ(-1, buffer_size); // Try to retrieve the first item with correctly sized buffer. Item is // taken from Dests NameTree in named_dests.pdf. buffer_size = 12; dest = FPDF_GetNamedDest(document(), 0, fixed_buffer, &buffer_size); EXPECT_NE(nullptr, dest); EXPECT_EQ(12u, buffer_size); EXPECT_EQ(std::string("F\0i\0r\0s\0t\0\0\0", 12), std::string(fixed_buffer, buffer_size)); // Try to retrieve the second item with ample buffer. Item is taken // from Dests NameTree but has a sub-dictionary in named_dests.pdf. buffer_size = sizeof(fixed_buffer); dest = FPDF_GetNamedDest(document(), 1, fixed_buffer, &buffer_size); EXPECT_NE(nullptr, dest); EXPECT_EQ(10u, buffer_size); EXPECT_EQ(std::string("N\0e\0x\0t\0\0\0", 10), std::string(fixed_buffer, buffer_size)); // Try to retrieve third item with ample buffer. Item is taken // from Dests NameTree but has a bad sub-dictionary in named_dests.pdf. // in named_dests.pdf). buffer_size = sizeof(fixed_buffer); dest = FPDF_GetNamedDest(document(), 2, fixed_buffer, &buffer_size); EXPECT_EQ(nullptr, dest); EXPECT_EQ(sizeof(fixed_buffer), buffer_size); // unmodified. // Try to retrieve the forth item with ample buffer. Item is taken // from Dests NameTree but has a vale of the wrong type in named_dests.pdf. buffer_size = sizeof(fixed_buffer); dest = FPDF_GetNamedDest(document(), 3, fixed_buffer, &buffer_size); EXPECT_EQ(nullptr, dest); EXPECT_EQ(sizeof(fixed_buffer), buffer_size); // unmodified. // Try to retrieve fifth item with ample buffer. Item taken from the // old-style Dests dictionary object in named_dests.pdf. buffer_size = sizeof(fixed_buffer); dest = FPDF_GetNamedDest(document(), 4, fixed_buffer, &buffer_size); EXPECT_NE(nullptr, dest); EXPECT_EQ(30u, buffer_size); EXPECT_EQ(std::string("F\0i\0r\0s\0t\0A\0l\0t\0e\0r\0n\0a\0t\0e\0\0\0", 30), std::string(fixed_buffer, buffer_size)); // Try to retrieve sixth item with ample buffer. Item istaken from the // old-style Dests dictionary object but has a sub-dictionary in // named_dests.pdf. buffer_size = sizeof(fixed_buffer); dest = FPDF_GetNamedDest(document(), 5, fixed_buffer, &buffer_size); EXPECT_NE(nullptr, dest); EXPECT_EQ(28u, buffer_size); EXPECT_EQ(std::string("L\0a\0s\0t\0A\0l\0t\0e\0r\0n\0a\0t\0e\0\0\0", 28), std::string(fixed_buffer, buffer_size)); // Try to retrieve non-existent item with ample buffer. buffer_size = sizeof(fixed_buffer); dest = FPDF_GetNamedDest(document(), 6, fixed_buffer, &buffer_size); EXPECT_EQ(nullptr, dest); EXPECT_EQ(sizeof(fixed_buffer), buffer_size); // unmodified. // Try to underflow/overflow the integer index. buffer_size = sizeof(fixed_buffer); dest = FPDF_GetNamedDest(document(), std::numeric_limits<int>::max(), fixed_buffer, &buffer_size); EXPECT_EQ(nullptr, dest); EXPECT_EQ(sizeof(fixed_buffer), buffer_size); // unmodified. buffer_size = sizeof(fixed_buffer); dest = FPDF_GetNamedDest(document(), std::numeric_limits<int>::min(), fixed_buffer, &buffer_size); EXPECT_EQ(nullptr, dest); EXPECT_EQ(sizeof(fixed_buffer), buffer_size); // unmodified. buffer_size = sizeof(fixed_buffer); dest = FPDF_GetNamedDest(document(), -1, fixed_buffer, &buffer_size); EXPECT_EQ(nullptr, dest); EXPECT_EQ(sizeof(fixed_buffer), buffer_size); // unmodified. } TEST_F(FPDFViewEmbeddertest, NamedDestsByName) { EXPECT_TRUE(OpenDocument("testing/resources/named_dests.pdf")); // Null pointer returns NULL. FPDF_DEST dest = FPDF_GetNamedDestByName(document(), nullptr); EXPECT_EQ(nullptr, dest); // Empty string returns NULL. dest = FPDF_GetNamedDestByName(document(), ""); EXPECT_EQ(nullptr, dest); // Item from Dests NameTree. dest = FPDF_GetNamedDestByName(document(), "First"); EXPECT_NE(nullptr, dest); long ignore_len = 0; FPDF_DEST dest_by_index = FPDF_GetNamedDest(document(), 0, nullptr, &ignore_len); EXPECT_EQ(dest_by_index, dest); // Item from Dests dictionary. dest = FPDF_GetNamedDestByName(document(), "FirstAlternate"); EXPECT_NE(nullptr, dest); ignore_len = 0; dest_by_index = FPDF_GetNamedDest(document(), 4, nullptr, &ignore_len); EXPECT_EQ(dest_by_index, dest); // Bad value type for item from Dests NameTree array. dest = FPDF_GetNamedDestByName(document(), "WrongType"); EXPECT_EQ(nullptr, dest); // No such destination in either Dest NameTree or dictionary. dest = FPDF_GetNamedDestByName(document(), "Bogus"); EXPECT_EQ(nullptr, dest); } // The following tests pass if the document opens without crashing. TEST_F(FPDFViewEmbeddertest, Crasher_113) { EXPECT_TRUE(OpenDocument("testing/resources/bug_113.pdf")); } TEST_F(FPDFViewEmbeddertest, Crasher_451830) { // Document is damaged and can't be opened. EXPECT_FALSE(OpenDocument("testing/resources/bug_451830.pdf")); } TEST_F(FPDFViewEmbeddertest, Crasher_452455) { EXPECT_TRUE(OpenDocument("testing/resources/bug_452455.pdf")); FPDF_PAGE page = LoadPage(0); EXPECT_NE(nullptr, page); UnloadPage(page); } TEST_F(FPDFViewEmbeddertest, Crasher_454695) { // Document is damanged and can't be opened. EXPECT_FALSE(OpenDocument("testing/resources/bug_454695.pdf")); } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////// // // Copyright 2017 Realm 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. // //////////////////////////////////////////////////////////////////////////// #ifndef REALM_OS_OBJECT_ACCESSOR_IMPL_HPP #define REALM_OS_OBJECT_ACCESSOR_IMPL_HPP #include "object_accessor.hpp" #include "util/any.hpp" namespace realm { using AnyDict = std::map<std::string, util::Any>; using AnyVector = std::vector<util::Any>; // An object accessor context which can be used to create and access objects // using util::Any as the type-erased value type. In addition, this serves as // the reference implementation of an accessor context that must be implemented // by each binding. class CppContext { public: // This constructor is the only one used by the object accessor code, and is // used when recurring into a link or array property during object creation // (i.e. prop.type will always be Object or Array). CppContext(CppContext& c, Property const& prop) : realm(c.realm) , object_schema(&*realm->schema().find(prop.object_type)) { } CppContext() = default; CppContext(std::shared_ptr<Realm> realm, const ObjectSchema* os=nullptr) : realm(std::move(realm)), object_schema(os) { } // The use of util::Optional for the following two functions is not a hard // requirement; only that it be some type which can be evaluated in a // boolean context to determine if it contains a value, and if it does // contain a value it must be dereferencable to obtain that value. // Get the value for a property in an input object, or `util::none` if no // value present. The property is identified both by the name of the // property and its index within the ObjectScehma's persisted_properties // array. util::Optional<util::Any> value_for_property(util::Any& dict, std::string const& prop_name, size_t /* property_index */) const { auto const& v = any_cast<AnyDict&>(dict); auto it = v.find(prop_name); return it == v.end() ? util::none : util::make_optional(it->second); } // Get the default value for the given property in the given object schema, // or `util::none` if there is none (which is distinct from the default // being `null`). // // This implementation does not support default values; see the default // value tests for an example of one which does. util::Optional<util::Any> default_value_for_property(ObjectSchema const&, std::string const&) const { return util::none; } // Invoke `fn` with each of the values from an enumerable type template<typename Func> void enumerate_list(util::Any& value, Func&& fn) { for (auto&& v : any_cast<AnyVector&>(value)) fn(v); } // Convert from core types to the boxed type util::Any box(BinaryData v) const { return std::string(v); } util::Any box(List v) const { return v; } util::Any box(Object v) const { return v; } util::Any box(Results v) const { return v; } util::Any box(StringData v) const { return std::string(v); } util::Any box(Timestamp v) const { return v; } util::Any box(bool v) const { return v; } util::Any box(double v) const { return v; } util::Any box(float v) const { return v; } util::Any box(long long v) const { return v; } util::Any box(RowExpr) const; // Any properties are only supported by the Cocoa binding to enable reading // old Realm files that may have used them. Other bindings can safely not // implement this. util::Any box(Mixed) const { REALM_TERMINATE("not supported"); } // Convert from the boxed type to core types. This needs to be implemented // for all of the types which `box()` can take, plus `RowExpr` and optional // versions of the numeric types, minus `List` and `Results`. // // `create` and `update` are only applicable to `unbox<RowExpr>`. If // `create` is false then when given something which is not a managed Realm // object `unbox()` should simply return a detached row expr, while if it's // true then `unbox()` should create a new object in the context's Realm // using the provided value. If `update` is true then upsert semantics // should be used for this. template<typename T> T unbox(util::Any& v, bool /*create*/= false, bool /*update*/= false) const { return any_cast<T>(v); } bool is_null(util::Any const& v) const noexcept { return !v.has_value(); } util::Any null_value() const noexcept { return {}; } util::Optional<util::Any> no_value() const noexcept { return {}; } // KVO hooks which will be called before and after modying a property from // within Object::create(). void will_change(Object const&, Property const&) {} void did_change() {} // Get a string representation of the given value for use in error messages. std::string print(util::Any const&) const { return "not implemented"; } // Cocoa allows supplying fewer values than there are properties when // creating objects using an array of values. Other bindings should not // mimick this behavior so just return false here. bool allow_missing(util::Any const&) const { return false; } private: std::shared_ptr<Realm> realm; const ObjectSchema* object_schema = nullptr; }; inline util::Any CppContext::box(RowExpr row) const { return Object(realm, *object_schema, row); } template<> inline StringData CppContext::unbox(util::Any& v, bool, bool) const { if (!v.has_value()) return StringData(); auto& value = any_cast<std::string&>(v); return StringData(value.c_str(), value.size()); } template<> inline BinaryData CppContext::unbox(util::Any& v, bool, bool) const { if (!v.has_value()) return BinaryData(); auto& value = any_cast<std::string&>(v); return BinaryData(value.c_str(), value.size()); } template<> inline RowExpr CppContext::unbox(util::Any& v, bool create, bool update) const { if (auto object = any_cast<Object>(&v)) return object->row(); if (auto row = any_cast<RowExpr>(&v)) return *row; if (!create) return RowExpr(); REALM_ASSERT(object_schema); return Object::create(const_cast<CppContext&>(*this), realm, *object_schema, v, update).row(); } template<> inline util::Optional<bool> CppContext::unbox(util::Any& v, bool, bool) const { return v.has_value() ? util::make_optional(unbox<bool>(v)) : util::none; } template<> inline util::Optional<int64_t> CppContext::unbox(util::Any& v, bool, bool) const { return v.has_value() ? util::make_optional(unbox<int64_t>(v)) : util::none; } template<> inline util::Optional<double> CppContext::unbox(util::Any& v, bool, bool) const { return v.has_value() ? util::make_optional(unbox<double>(v)) : util::none; } template<> inline util::Optional<float> CppContext::unbox(util::Any& v, bool, bool) const { return v.has_value() ? util::make_optional(unbox<float>(v)) : util::none; } template<> inline Mixed CppContext::unbox(util::Any&, bool, bool) const { throw std::logic_error("'Any' type is unsupported"); } } #endif // REALM_OS_OBJECT_ACCESSOR_IMPL_HPP <commit_msg>Maybe fix linux compilation<commit_after>//////////////////////////////////////////////////////////////////////////// // // Copyright 2017 Realm 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. // //////////////////////////////////////////////////////////////////////////// #ifndef REALM_OS_OBJECT_ACCESSOR_IMPL_HPP #define REALM_OS_OBJECT_ACCESSOR_IMPL_HPP #include "object_accessor.hpp" #include "util/any.hpp" namespace realm { using AnyDict = std::map<std::string, util::Any>; using AnyVector = std::vector<util::Any>; // An object accessor context which can be used to create and access objects // using util::Any as the type-erased value type. In addition, this serves as // the reference implementation of an accessor context that must be implemented // by each binding. class CppContext { public: // This constructor is the only one used by the object accessor code, and is // used when recurring into a link or array property during object creation // (i.e. prop.type will always be Object or Array). CppContext(CppContext& c, Property const& prop) : realm(c.realm) , object_schema(&*realm->schema().find(prop.object_type)) { } CppContext() = default; CppContext(std::shared_ptr<Realm> realm, const ObjectSchema* os=nullptr) : realm(std::move(realm)), object_schema(os) { } // The use of util::Optional for the following two functions is not a hard // requirement; only that it be some type which can be evaluated in a // boolean context to determine if it contains a value, and if it does // contain a value it must be dereferencable to obtain that value. // Get the value for a property in an input object, or `util::none` if no // value present. The property is identified both by the name of the // property and its index within the ObjectScehma's persisted_properties // array. util::Optional<util::Any> value_for_property(util::Any& dict, std::string const& prop_name, size_t /* property_index */) const { auto const& v = any_cast<AnyDict&>(dict); auto it = v.find(prop_name); return it == v.end() ? util::none : util::make_optional(it->second); } // Get the default value for the given property in the given object schema, // or `util::none` if there is none (which is distinct from the default // being `null`). // // This implementation does not support default values; see the default // value tests for an example of one which does. util::Optional<util::Any> default_value_for_property(ObjectSchema const&, std::string const&) const { return util::none; } // Invoke `fn` with each of the values from an enumerable type template<typename Func> void enumerate_list(util::Any& value, Func&& fn) { for (auto&& v : any_cast<AnyVector&>(value)) fn(v); } // Convert from core types to the boxed type util::Any box(BinaryData v) const { return std::string(v); } util::Any box(List v) const { return v; } util::Any box(Object v) const { return v; } util::Any box(Results v) const { return v; } util::Any box(StringData v) const { return std::string(v); } util::Any box(Timestamp v) const { return v; } util::Any box(bool v) const { return v; } util::Any box(double v) const { return v; } util::Any box(float v) const { return v; } util::Any box(int64_t v) const { return v; } util::Any box(RowExpr) const; // Any properties are only supported by the Cocoa binding to enable reading // old Realm files that may have used them. Other bindings can safely not // implement this. util::Any box(Mixed) const { REALM_TERMINATE("not supported"); } // Convert from the boxed type to core types. This needs to be implemented // for all of the types which `box()` can take, plus `RowExpr` and optional // versions of the numeric types, minus `List` and `Results`. // // `create` and `update` are only applicable to `unbox<RowExpr>`. If // `create` is false then when given something which is not a managed Realm // object `unbox()` should simply return a detached row expr, while if it's // true then `unbox()` should create a new object in the context's Realm // using the provided value. If `update` is true then upsert semantics // should be used for this. template<typename T> T unbox(util::Any& v, bool /*create*/= false, bool /*update*/= false) const { return any_cast<T>(v); } bool is_null(util::Any const& v) const noexcept { return !v.has_value(); } util::Any null_value() const noexcept { return {}; } util::Optional<util::Any> no_value() const noexcept { return {}; } // KVO hooks which will be called before and after modying a property from // within Object::create(). void will_change(Object const&, Property const&) {} void did_change() {} // Get a string representation of the given value for use in error messages. std::string print(util::Any const&) const { return "not implemented"; } // Cocoa allows supplying fewer values than there are properties when // creating objects using an array of values. Other bindings should not // mimick this behavior so just return false here. bool allow_missing(util::Any const&) const { return false; } private: std::shared_ptr<Realm> realm; const ObjectSchema* object_schema = nullptr; }; inline util::Any CppContext::box(RowExpr row) const { return Object(realm, *object_schema, row); } template<> inline StringData CppContext::unbox(util::Any& v, bool, bool) const { if (!v.has_value()) return StringData(); auto& value = any_cast<std::string&>(v); return StringData(value.c_str(), value.size()); } template<> inline BinaryData CppContext::unbox(util::Any& v, bool, bool) const { if (!v.has_value()) return BinaryData(); auto& value = any_cast<std::string&>(v); return BinaryData(value.c_str(), value.size()); } template<> inline RowExpr CppContext::unbox(util::Any& v, bool create, bool update) const { if (auto object = any_cast<Object>(&v)) return object->row(); if (auto row = any_cast<RowExpr>(&v)) return *row; if (!create) return RowExpr(); REALM_ASSERT(object_schema); return Object::create(const_cast<CppContext&>(*this), realm, *object_schema, v, update).row(); } template<> inline util::Optional<bool> CppContext::unbox(util::Any& v, bool, bool) const { return v.has_value() ? util::make_optional(unbox<bool>(v)) : util::none; } template<> inline util::Optional<int64_t> CppContext::unbox(util::Any& v, bool, bool) const { return v.has_value() ? util::make_optional(unbox<int64_t>(v)) : util::none; } template<> inline util::Optional<double> CppContext::unbox(util::Any& v, bool, bool) const { return v.has_value() ? util::make_optional(unbox<double>(v)) : util::none; } template<> inline util::Optional<float> CppContext::unbox(util::Any& v, bool, bool) const { return v.has_value() ? util::make_optional(unbox<float>(v)) : util::none; } template<> inline Mixed CppContext::unbox(util::Any&, bool, bool) const { throw std::logic_error("'Any' type is unsupported"); } } #endif // REALM_OS_OBJECT_ACCESSOR_IMPL_HPP <|endoftext|>
<commit_before>#include "skin_generator.hpp" #include <QtCore/QFile> #include <QtGui/QApplication> #include <QtXml/QXmlSimpleReader> #include <QtXml/QXmlInputSource> #include "../3party/gflags/src/gflags/gflags.h" DEFINE_string(fontFileName, "../../data/01_dejavusans.ttf", "path to TrueType font file"); DEFINE_string(symbolsFile, "../../data/results.unicode", "file with 2bytes symbols for which the skin should be generated"); DEFINE_string(symbolsDir, "../../data/styles/symbols", "directory with svg symbol files"); DEFINE_int32(symbolWidth, 24, "width of the rendered symbol"); DEFINE_int32(symbolHeight, 24, "height of the rendered symbol"); DEFINE_string(skinName, "../../data/basic", "prefix for the skin and skinImage file name"); DEFINE_string(skinSuffix, "ldpi", "suffix for skinName<suffix>.skn and symbols<suffix>.png"); DEFINE_string(searchIconsOutPath, "../../data/search-icons/png", "output path for search category icons"); DEFINE_string(searchCategories, "../../data/search-icons/categories-icons.txt", "path to file that contains mapping between category and icon names"); DEFINE_string(searchIconsSrcPath, "../../data/search-icons/svg", "input path for search category icons"); DEFINE_int32(searchIconWidth, 24, "width of the search category icon"); DEFINE_int32(searchIconHeight, 24, "height of the search category icon"); DEFINE_bool(colorCorrection, false, "apply color correction for yota"); int main(int argc, char *argv[]) { google::ParseCommandLineFlags(&argc, &argv, true); QApplication app(argc, argv); tools::SkinGenerator gen(FLAGS_colorCorrection); std::vector<QSize> symbolSizes; symbolSizes.push_back(QSize(FLAGS_symbolWidth, FLAGS_symbolHeight)); std::vector<std::string> suffixes; suffixes.push_back(FLAGS_skinSuffix); /* gen.processSearchIcons(FLAGS_searchIconsSrcPath, FLAGS_searchCategories, FLAGS_searchIconsOutPath, FLAGS_searchIconWidth, FLAGS_searchIconHeight); */ gen.processSymbols(FLAGS_symbolsDir, FLAGS_skinName, symbolSizes, suffixes); gen.renderPages(); gen.writeToFile(FLAGS_skinName + FLAGS_skinSuffix); return 0; } <commit_msg>[styles] Fixed skin generator compilation<commit_after>#include "skin_generator.hpp" #include <QtCore/QFile> #include <QApplication> #include <QtXml/QXmlSimpleReader> #include <QtXml/QXmlInputSource> #include "../3party/gflags/src/gflags/gflags.h" DEFINE_string(fontFileName, "../../data/01_dejavusans.ttf", "path to TrueType font file"); DEFINE_string(symbolsFile, "../../data/results.unicode", "file with 2bytes symbols for which the skin should be generated"); DEFINE_string(symbolsDir, "../../data/styles/symbols", "directory with svg symbol files"); DEFINE_int32(symbolWidth, 24, "width of the rendered symbol"); DEFINE_int32(symbolHeight, 24, "height of the rendered symbol"); DEFINE_string(skinName, "../../data/basic", "prefix for the skin and skinImage file name"); DEFINE_string(skinSuffix, "ldpi", "suffix for skinName<suffix>.skn and symbols<suffix>.png"); DEFINE_string(searchIconsOutPath, "../../data/search-icons/png", "output path for search category icons"); DEFINE_string(searchCategories, "../../data/search-icons/categories-icons.txt", "path to file that contains mapping between category and icon names"); DEFINE_string(searchIconsSrcPath, "../../data/search-icons/svg", "input path for search category icons"); DEFINE_int32(searchIconWidth, 24, "width of the search category icon"); DEFINE_int32(searchIconHeight, 24, "height of the search category icon"); DEFINE_bool(colorCorrection, false, "apply color correction for yota"); int main(int argc, char *argv[]) { google::ParseCommandLineFlags(&argc, &argv, true); QApplication app(argc, argv); tools::SkinGenerator gen(FLAGS_colorCorrection); std::vector<QSize> symbolSizes; symbolSizes.push_back(QSize(FLAGS_symbolWidth, FLAGS_symbolHeight)); std::vector<std::string> suffixes; suffixes.push_back(FLAGS_skinSuffix); /* gen.processSearchIcons(FLAGS_searchIconsSrcPath, FLAGS_searchCategories, FLAGS_searchIconsOutPath, FLAGS_searchIconWidth, FLAGS_searchIconHeight); */ gen.processSymbols(FLAGS_symbolsDir, FLAGS_skinName, symbolSizes, suffixes); gen.renderPages(); gen.writeToFile(FLAGS_skinName + FLAGS_skinSuffix); return 0; } <|endoftext|>
<commit_before>#ifndef INC_OBJDETECT_HPP__ #define INC_OBJDETECT_HPP__ #include <opencv2/core/core.hpp> #include <opencv2/gpu/gpu.hpp> #include <vector> // Base class for detector. Doesn't really do much - all of the heavy lifting is // in the derived classes class ObjDetect { public : ObjDetect() : init_(false) {} //pass in value of false to cascadeLoaded virtual ~ObjDetect() {} //empty destructor virtual void Detect(const cv::Mat &frame, std::vector<cv::Rect> &imageRects) = 0; //pure virtual function, must be defined by CPU and GPU detect virtual void Detect(const cv::gpu::GpuMat &frameGPUInput, std::vector<cv::Rect> &imageRects) { imageRects.clear(); } bool initialized(void) { return init_; } protected: bool init_; }; // CPU version of cascade classifier class CPU_CascadeDetect : public ObjDetect { public : CPU_CascadeDetect(const char *cascadeName) : ObjDetect() // call default constructor of base class { init_ = classifier_.load(cascadeName); } ~CPU_CascadeDetect(void) { } void Detect(const cv::Mat &frame, std::vector<cv::Rect> &imageRects); //defined elsewhere private : cv::CascadeClassifier classifier_; }; // CPU version of cascade classifier. Pretty much the same interface // as the CPU version, but with an added method to handle data // which is already moved to a GpuMat class GPU_CascadeDetect : public ObjDetect { public : GPU_CascadeDetect(const char *cascadeName) : ObjDetect() { init_ = classifier_.load(cascadeName); } ~GPU_CascadeDetect(void) { classifier_.release(); } void Detect (const cv::Mat &frame, std::vector<cv::Rect> &imageRects); void Detect (const cv::gpu::GpuMat &frameGPUInput, std::vector<cv::Rect> &imageRects); private : cv::gpu::CascadeClassifier_GPU classifier_; // Declare GPU Mat elements once here instead of every single // call to the functions which use them cv::gpu::GpuMat frameEq; cv::gpu::GpuMat frameGray; cv::gpu::GpuMat detectResultsGPU; cv::gpu::GpuMat uploadFrame; }; extern int scale; extern int neighbors; extern int minDetectSize; extern int maxDetectSize; #endif <commit_msg>Check that input filename exists - print error if not<commit_after>#ifndef INC_OBJDETECT_HPP__ #define INC_OBJDETECT_HPP__ #include <iostream> #include <sys/stat.h> #include <opencv2/core/core.hpp> #include <opencv2/gpu/gpu.hpp> #include <vector> // Base class for detector. Doesn't really do much - all of the heavy lifting is // in the derived classes class ObjDetect { public : ObjDetect() : init_(false) {} //pass in value of false to cascadeLoaded virtual ~ObjDetect() {} //empty destructor virtual void Detect(const cv::Mat &frame, std::vector<cv::Rect> &imageRects) = 0; //pure virtual function, must be defined by CPU and GPU detect virtual void Detect(const cv::gpu::GpuMat &frameGPUInput, std::vector<cv::Rect> &imageRects) { imageRects.clear(); } bool initialized(void) { return init_; } protected: bool init_; }; // CPU version of cascade classifier class CPU_CascadeDetect : public ObjDetect { public : CPU_CascadeDetect(const char *cascadeName) : ObjDetect() // call default constructor of base class { struct stat statbuf; if (stat(cascadeName, &statbuf) != 0) { std::cerr << "Can not open classifier input " << cascadeName << std::endl; std::cerr << "Try to point to a different one with --classifierBase= ?" << std::endl; return; } init_ = classifier_.load(cascadeName); } ~CPU_CascadeDetect(void) { } void Detect(const cv::Mat &frame, std::vector<cv::Rect> &imageRects); //defined elsewhere private : cv::CascadeClassifier classifier_; }; // CPU version of cascade classifier. Pretty much the same interface // as the CPU version, but with an added method to handle data // which is already moved to a GpuMat class GPU_CascadeDetect : public ObjDetect { public : GPU_CascadeDetect(const char *cascadeName) : ObjDetect() { struct stat statbuf; if (stat(cascadeName, &statbuf) != 0) { std::cerr << "Can not open classifier input " << cascadeName << std::endl; std::cerr << "Try to point to a different one with --classifierBase= ?" << std::endl; return; } init_ = classifier_.load(cascadeName); } ~GPU_CascadeDetect(void) { classifier_.release(); } void Detect (const cv::Mat &frame, std::vector<cv::Rect> &imageRects); void Detect (const cv::gpu::GpuMat &frameGPUInput, std::vector<cv::Rect> &imageRects); private : cv::gpu::CascadeClassifier_GPU classifier_; // Declare GPU Mat elements once here instead of every single // call to the functions which use them cv::gpu::GpuMat frameEq; cv::gpu::GpuMat frameGray; cv::gpu::GpuMat detectResultsGPU; cv::gpu::GpuMat uploadFrame; }; extern int scale; extern int neighbors; extern int minDetectSize; extern int maxDetectSize; #endif <|endoftext|>
<commit_before>/* * Copyright 2011 Esrille 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. */ #include "StackingContext.h" // TODO: Do not inlcude GL in this file #include <GL/gl.h> #include <GL/glu.h> #include <new> #include <iostream> #include "Box.h" #include "ViewCSSImp.h" namespace org { namespace w3c { namespace dom { namespace bootstrap { StackingContext* StackingContext::removeChild(StackingContext* item) { StackingContext* next = item->nextSibling; StackingContext* prev = item->previousSibling; if (!next) lastChild = prev; else next->previousSibling = prev; if (!prev) firstChild = next; else prev->nextSibling = next; item->parent = 0; --childCount; return item; } StackingContext* StackingContext::insertBefore(StackingContext* item, StackingContext* after) { if (!after) return appendChild(item); item->previousSibling = after->previousSibling; item->nextSibling = after; after->previousSibling = item; if (!item->previousSibling) firstChild = item; else item->previousSibling->nextSibling = item; item->parent = this; ++childCount; return item; } StackingContext* StackingContext::appendChild(StackingContext* item) { StackingContext* prev = lastChild; if (!prev) firstChild = item; else prev->nextSibling = item; item->previousSibling = prev; item->nextSibling = 0; lastChild = item; item->parent = this; ++childCount; return item; } StackingContext::StackingContext(bool auto_, int zIndex) : auto_(auto_), zIndex(zIndex), parent(0), firstChild(0), lastChild(0), previousSibling(0), nextSibling(0), childCount(0), firstBase(0), lastBase(0), firstFloat(0), lastFloat(0), currentFloat(0) { } StackingContext::~StackingContext() { if (parent) parent->removeChild(this); while (0 < childCount) { StackingContext* child = removeChild(firstChild); delete child; } } StackingContext* StackingContext::addContext(bool auto_, int zIndex) { if (isAuto()) return parent->addContext(auto_, zIndex); StackingContext* after = 0; for (auto i = getFirstChild(); i; i = i->getNextSibling()) { if (zIndex < i->zIndex) { after = i; break; } } StackingContext* item = new(std::nothrow) StackingContext(auto_, zIndex); if (item) insertBefore(item, after); return item; } void StackingContext::render(ViewCSSImp* view) { currentFloat = 0; for (Box* base = firstBase; base; base = base->nextBase) { if (base->clipBox) { // TODO: Support the cumulative clip intersection. BlockLevelBox* clip = base->clipBox; // TODO: if (base->isAbsolutelyPositioned()) ... else ... float left = clip->x + clip->marginLeft + clip->borderLeft; float top = clip->y + clip->marginTop + clip->borderTop; float right = left + clip->getPaddingWidth(); float bottom = top + clip->getPaddingHeight(); glViewport(left, view->getInitialContainingBlock()->getHeight() - bottom, right - left, bottom - top); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(left, right, bottom, top, -1000.0, 1.0); glMatrixMode(GL_MODELVIEW); } BlockLevelBox* block = dynamic_cast<BlockLevelBox*>(base); unsigned overflow = CSSOverflowValueImp::Visible; if (block) overflow = block->renderBegin(view); StackingContext* childContext = getFirstChild(); for (; childContext && childContext->zIndex < 0; childContext = childContext->getNextSibling()) childContext->render(view); if (!block) base->render(view, this); else block->renderContent(view, this); for (currentFloat = firstFloat; currentFloat; currentFloat = currentFloat->nextBase) currentFloat ->render(view, this); for (; childContext; childContext = childContext->getNextSibling()) childContext->render(view); if (block) block->renderEnd(view, overflow); if (base->clipBox) { float w = view->getInitialContainingBlock()->getWidth(); float h = view->getInitialContainingBlock()->getHeight(); glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, w, h, 0, -1000.0, 1.0); glMatrixMode(GL_MODELVIEW); } } } void StackingContext::addBase(Box* box) { if (!firstBase) firstBase = lastBase = box; else { lastBase->nextBase = box; lastBase = box; } box->nextBase = 0; } void StackingContext::addFloat(Box* box) { if (currentFloat) { box->nextBase = currentFloat->nextBase; currentFloat->nextBase = box; return; } if (!firstFloat) firstFloat = lastFloat = box; else { lastFloat->nextBase = box; lastFloat = box; } box->nextBase = 0; } void StackingContext::dump(std::string indent) { std::cout << indent << "z-index: " << zIndex << '\n'; indent += " "; for (auto child = getFirstChild(); child; child = child->getNextSibling()) child->dump(indent); } }}}} // org::w3c::dom::bootstrap<commit_msg>(StackingContext::render) : Adjust the viewport position as the widow is scrolled.<commit_after>/* * Copyright 2011 Esrille 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. */ #include "StackingContext.h" // TODO: Do not inlcude GL in this file #include <GL/gl.h> #include <GL/glu.h> #include <new> #include <iostream> #include "Box.h" #include "ViewCSSImp.h" namespace org { namespace w3c { namespace dom { namespace bootstrap { StackingContext* StackingContext::removeChild(StackingContext* item) { StackingContext* next = item->nextSibling; StackingContext* prev = item->previousSibling; if (!next) lastChild = prev; else next->previousSibling = prev; if (!prev) firstChild = next; else prev->nextSibling = next; item->parent = 0; --childCount; return item; } StackingContext* StackingContext::insertBefore(StackingContext* item, StackingContext* after) { if (!after) return appendChild(item); item->previousSibling = after->previousSibling; item->nextSibling = after; after->previousSibling = item; if (!item->previousSibling) firstChild = item; else item->previousSibling->nextSibling = item; item->parent = this; ++childCount; return item; } StackingContext* StackingContext::appendChild(StackingContext* item) { StackingContext* prev = lastChild; if (!prev) firstChild = item; else prev->nextSibling = item; item->previousSibling = prev; item->nextSibling = 0; lastChild = item; item->parent = this; ++childCount; return item; } StackingContext::StackingContext(bool auto_, int zIndex) : auto_(auto_), zIndex(zIndex), parent(0), firstChild(0), lastChild(0), previousSibling(0), nextSibling(0), childCount(0), firstBase(0), lastBase(0), firstFloat(0), lastFloat(0), currentFloat(0) { } StackingContext::~StackingContext() { if (parent) parent->removeChild(this); while (0 < childCount) { StackingContext* child = removeChild(firstChild); delete child; } } StackingContext* StackingContext::addContext(bool auto_, int zIndex) { if (isAuto()) return parent->addContext(auto_, zIndex); StackingContext* after = 0; for (auto i = getFirstChild(); i; i = i->getNextSibling()) { if (zIndex < i->zIndex) { after = i; break; } } StackingContext* item = new(std::nothrow) StackingContext(auto_, zIndex); if (item) insertBefore(item, after); return item; } void StackingContext::render(ViewCSSImp* view) { float scrollX = view->getWindow()->getScrollX(); float scrollY = view->getWindow()->getScrollY(); currentFloat = 0; for (Box* base = firstBase; base; base = base->nextBase) { if (base->clipBox) { // TODO: Support the cumulative clip intersection. BlockLevelBox* clip = base->clipBox; // TODO: if (base->isAbsolutelyPositioned()) ... else ... float left = clip->x + clip->marginLeft + clip->borderLeft - scrollX; float top = clip->y + clip->marginTop + clip->borderTop - scrollY; float right = left + clip->getPaddingWidth(); float bottom = top + clip->getPaddingHeight(); glViewport(left, view->getInitialContainingBlock()->getHeight() - bottom, right - left, bottom - top); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(left, right, bottom, top, -1000.0, 1.0); glMatrixMode(GL_MODELVIEW); } BlockLevelBox* block = dynamic_cast<BlockLevelBox*>(base); unsigned overflow = CSSOverflowValueImp::Visible; if (block) overflow = block->renderBegin(view); StackingContext* childContext = getFirstChild(); for (; childContext && childContext->zIndex < 0; childContext = childContext->getNextSibling()) childContext->render(view); if (!block) base->render(view, this); else block->renderContent(view, this); for (currentFloat = firstFloat; currentFloat; currentFloat = currentFloat->nextBase) currentFloat ->render(view, this); for (; childContext; childContext = childContext->getNextSibling()) childContext->render(view); if (block) block->renderEnd(view, overflow); if (base->clipBox) { float w = view->getInitialContainingBlock()->getWidth(); float h = view->getInitialContainingBlock()->getHeight(); glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, w, h, 0, -1000.0, 1.0); glMatrixMode(GL_MODELVIEW); } } } void StackingContext::addBase(Box* box) { if (!firstBase) firstBase = lastBase = box; else { lastBase->nextBase = box; lastBase = box; } box->nextBase = 0; } void StackingContext::addFloat(Box* box) { if (currentFloat) { box->nextBase = currentFloat->nextBase; currentFloat->nextBase = box; return; } if (!firstFloat) firstFloat = lastFloat = box; else { lastFloat->nextBase = box; lastFloat = box; } box->nextBase = 0; } void StackingContext::dump(std::string indent) { std::cout << indent << "z-index: " << zIndex << '\n'; indent += " "; for (auto child = getFirstChild(); child; child = child->getNextSibling()) child->dump(indent); } }}}} // org::w3c::dom::bootstrap<|endoftext|>
<commit_before> // Event.cpp // Implements the cEvent object representing an OS-specific synchronization primitive that can be waited-for // Implemented as an Event on Win and as a 1-semaphore on *nix #include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules #include "Event.h" #include "Errors.h" cEvent::cEvent(void) : m_ShouldWait(true) { } void cEvent::Wait(void) { std::unique_lock<std::mutex> Lock(m_Mutex); while (m_ShouldWait) { m_CondVar.wait(Lock); } m_ShouldWait = true; } bool cEvent::Wait(int a_TimeoutMSec) { std::chrono::system_clock::time_point dst = std::chrono::system_clock::now() + std::chrono::milliseconds(a_TimeoutMSec); std::unique_lock<std::mutex> Lock(m_Mutex); // We assume that this lock is acquired without much delay - we are the only user of the mutex while (m_ShouldWait && (std::chrono::system_clock::now() < dst)) { switch (m_CondVar.wait_until(Lock, dst)) { case std::cv_status::no_timeout: { // The wait was successful, check for spurious wakeup: if (!m_ShouldWait) { m_ShouldWait = true; return true; } // This was a spurious wakeup, wait again: continue; } case std::cv_status::timeout: { // The wait timed out, return failure: return false; } } // switch (wait_until()) } // while (m_ShouldWait && not timeout) // The wait timed out in the while() condition: return false; } void cEvent::Set(void) { { std::unique_lock<std::mutex> Lock(m_Mutex); m_ShouldWait = false; } m_CondVar.notify_one(); } <commit_msg>cEvent: Changed chrono duration resolution.<commit_after> // Event.cpp // Implements the cEvent object representing an OS-specific synchronization primitive that can be waited-for // Implemented as an Event on Win and as a 1-semaphore on *nix #include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules #include "Event.h" #include "Errors.h" cEvent::cEvent(void) : m_ShouldWait(true) { } void cEvent::Wait(void) { std::unique_lock<std::mutex> Lock(m_Mutex); while (m_ShouldWait) { m_CondVar.wait(Lock); } m_ShouldWait = true; } bool cEvent::Wait(int a_TimeoutMSec) { std::chrono::system_clock::time_point dst = std::chrono::system_clock::now() + std::chrono::microseconds(a_TimeoutMSec * 1000); std::unique_lock<std::mutex> Lock(m_Mutex); // We assume that this lock is acquired without much delay - we are the only user of the mutex while (m_ShouldWait && (std::chrono::system_clock::now() < dst)) { switch (m_CondVar.wait_until(Lock, dst)) { case std::cv_status::no_timeout: { // The wait was successful, check for spurious wakeup: if (!m_ShouldWait) { m_ShouldWait = true; return true; } // This was a spurious wakeup, wait again: continue; } case std::cv_status::timeout: { // The wait timed out, return failure: return false; } } // switch (wait_until()) } // while (m_ShouldWait && not timeout) // The wait timed out in the while() condition: return false; } void cEvent::Set(void) { { std::unique_lock<std::mutex> Lock(m_Mutex); m_ShouldWait = false; } m_CondVar.notify_one(); } <|endoftext|>
<commit_before>#include "petriproperties.h" #include "ui_petriproperties.h" #include "diagram/arcs/ipetriarc.h" PetriProperties::PetriProperties(QWidget *parent) : QWidget(parent), ui(new Ui::PetriProperties) { ui->setupUi(this); this->itemDataID = ""; this->netData = nullptr; this->currentPetriItem = nullptr; } PetriProperties::~PetriProperties() { delete ui; } void PetriProperties::setCurrentNet(spnp::Net *net) { this->netData = net; } void PetriProperties::onItemSelected(QGraphicsItem *item) { if(item == nullptr) { this->ui->stackedWidget->setCurrentIndex(7); this->itemDataID = ""; } else if(item->type() == IPetriItem::Type) { IPetriItem *other = qgraphicsitem_cast<IPetriItem *>(item); this->currentPetriItem = other; this->setData(other->getPetriItemId()); switch (other->petriType()) { case IPetriItem::Place: this->ui->stackedWidget->setCurrentIndex(0); this->loadPlace(); break; case IPetriItem::FPlace: this->ui->stackedWidget->setCurrentIndex(1); break; case IPetriItem::ITrans: this->ui->stackedWidget->setCurrentIndex(2); break; case IPetriItem::TTrans: this->ui->stackedWidget->setCurrentIndex(3); break; default: break; } } else if(item->type() == IPetriArc::Type) { IPetriArc *arc = qgraphicsitem_cast<IPetriArc *>(item); this->setData(arc->getArcId()); switch (arc->arcType()) { case IPetriArc::Activator: this->ui->stackedWidget->setCurrentIndex(4); break; case IPetriArc::FActivator: this->ui->stackedWidget->setCurrentIndex(5); break; case IPetriArc::Inhibitor: this->ui->stackedWidget->setCurrentIndex(6); break; default: break; } } } void PetriProperties::on_le_place_name_textEdited(const QString &arg1) { spnp::Place* p = this->netData->getPlace(itemDataID); if(p != nullptr) { p->setName(arg1.toStdString()); } this->currentPetriItem->updateLabel(p); } void PetriProperties::on_le_place_tokens_textEdited(const QString &arg1) { spnp::Place* p = this->netData->getPlace(itemDataID); if(p != nullptr) { p->setToken(arg1.toStdString()); } } void PetriProperties::setData(std::string itemId) { this->itemDataID = itemId; } void PetriProperties::loadPlace() { spnp::Place* place = this->netData->getPlace(this->itemDataID); this->ui->le_place_name->setText(QString::fromStdString(place->getName())); this->ui->le_place_tokens->setText(QString::fromStdString(place->getToken())); } void PetriProperties::on_le_itrans_name_textEdited(const QString &arg1) { spnp::ImmediateTransition *it = this->netData->getTransition(itemDataID); if(it != nullptr) { it->setName(arg1.toStdString()); } } void PetriProperties::on_le_itrans_prior_textEdited(const QString &arg1) { //TODO (void)arg1; } void PetriProperties::on_le_itrans_guard_textEdited(const QString &arg1) { //TODO (void)arg1; } <commit_msg>Ponteiro corrigido<commit_after>#include "petriproperties.h" #include "ui_petriproperties.h" #include "diagram/arcs/ipetriarc.h" PetriProperties::PetriProperties(QWidget *parent) : QWidget(parent), ui(new Ui::PetriProperties) { ui->setupUi(this); this->itemDataID = ""; this->netData = nullptr; this->currentPetriItem = nullptr; } PetriProperties::~PetriProperties() { delete ui; } void PetriProperties::setCurrentNet(spnp::Net *net) { this->netData = net; } void PetriProperties::onItemSelected(QGraphicsItem *item) { if(item == nullptr) { this->ui->stackedWidget->setCurrentIndex(7); this->itemDataID = ""; } else if(item->type() == IPetriItem::Type) { IPetriItem *other = qgraphicsitem_cast<IPetriItem *>(item); this->currentPetriItem = other; this->setData(other->getPetriItemId()); switch (other->petriType()) { case IPetriItem::Place: this->ui->stackedWidget->setCurrentIndex(0); this->loadPlace(); break; case IPetriItem::FPlace: this->ui->stackedWidget->setCurrentIndex(1); break; case IPetriItem::ITrans: this->ui->stackedWidget->setCurrentIndex(2); break; case IPetriItem::TTrans: this->ui->stackedWidget->setCurrentIndex(3); break; default: break; } } else if(item->type() == IPetriArc::Type) { IPetriArc *arc = qgraphicsitem_cast<IPetriArc *>(item); this->setData(arc->getArcId()); switch (arc->arcType()) { case IPetriArc::Activator: this->ui->stackedWidget->setCurrentIndex(4); break; case IPetriArc::FActivator: this->ui->stackedWidget->setCurrentIndex(5); break; case IPetriArc::Inhibitor: this->ui->stackedWidget->setCurrentIndex(6); break; default: break; } } } void PetriProperties::on_le_place_name_textEdited(const QString &arg1) { spnp::Place* p = this->netData->getPlace(itemDataID); if(p != nullptr) { p->setName(arg1.toStdString()); } this->currentPetriItem->updateLabel(p); } void PetriProperties::on_le_place_tokens_textEdited(const QString &arg1) { spnp::Place* p = this->netData->getPlace(itemDataID); if(p != nullptr) { p->setToken(arg1.toStdString()); } } void PetriProperties::setData(std::string itemId) { this->itemDataID = itemId; } void PetriProperties::loadPlace() { spnp::Place* place = this->netData->getPlace(this->itemDataID); if(place != nullptr) { this->ui->le_place_name->setText(QString::fromStdString(place->getName())); this->ui->le_place_tokens->setText(QString::fromStdString(place->getToken())); } } void PetriProperties::on_le_itrans_name_textEdited(const QString &arg1) { spnp::ImmediateTransition *it = this->netData->getTransition(itemDataID); if(it != nullptr) { it->setName(arg1.toStdString()); } } void PetriProperties::on_le_itrans_prior_textEdited(const QString &arg1) { //TODO (void)arg1; } void PetriProperties::on_le_itrans_guard_textEdited(const QString &arg1) { //TODO (void)arg1; } <|endoftext|>
<commit_before>// // PlaylistChooser.cpp // Kepler // // Created by Tom Carden on 7/10/11. // Copyright 2011 __MyCompanyName__. All rights reserved. // #include <string> #include "cinder/Vector.h" #include "cinder/PolyLine.h" #include "cinder/ImageIo.h" #include "cinder/Rand.h" #include "cinder/Path2d.h" #include "PlaylistChooser.h" #include "NodeArtist.h" #include "BloomScene.h" #include "Globals.h" using namespace ci; using namespace ci::app; using namespace std; void PlaylistChooser::setup( const Font &font, UiLayerRef uiLayer, WheelOverlayRef wheelOverlay ) { mFont = font; mTouchDragId = 0; mTouchDragStartPos = Vec2i( 0, 0 ); mTouchDragStartOffset = 0.0f; mTouchDragPlaylistIndex = -1; mTouchVel = 0.0f; mTouchPos = Vec2i( 0, 0 ); mTouchPrevPos = Vec2i( 0, 0 ); mOffsetX = -200.0f; mOffsetXLocked = -200.0f; mNumPlaylists = 0; mIsDragging = false; mPlaylistSize = Vec2f( 120.f, 30.0f ); mSpacerWidth = 30.0f; mStartY = 350.0f; mPrevIndex = -1; mCurrentIndex = 0; mWheelOverlay = wheelOverlay; mUiLayer = uiLayer; } bool PlaylistChooser::touchBegan( ci::app::TouchEvent::Touch touch ) { if( mData == NULL || mTouchDragPlaylistIndex >= 0 ) return false; mIsDragging = false; mTouchPrevPos = mTouchPos; mTouchPos = globalToLocal( touch.getPos() ); mTouchVel = 0.0f; for( int i = 0; i < mPlaylistRects.size(); i++ ){ if( mPlaylistRects[i].contains( mTouchPos ) ){ // remember the id and dispatch this event on touchesEnded if it hasn't moved much (otherwise just drag) mTouchDragId = touch.getId(); mTouchDragStartPos = mTouchPos; mTouchDragStartOffset = mOffsetX; mTouchDragPlaylistIndex = i; return true; } } // if we didn't already return... // capture all touches inside wheel so we can dismiss a tap inside the world Vec2f dir = globalToLocal( touch.getPos() ); float distToCenter = dir.length(); float maxDiam = mWheelOverlay->getRadius() + 25.0f; return distToCenter < maxDiam; } bool PlaylistChooser::touchMoved( ci::app::TouchEvent::Touch touch ) { if (mData == NULL || mTouchDragPlaylistIndex < 0) return false; mIsDragging = true; mTouchPrevPos = mTouchPos; mTouchPos = globalToLocal( touch.getPos() ); mOffsetX = mTouchDragStartOffset + ( mTouchDragStartPos.x - mTouchPos.x ); mTouchVel = mTouchPos.x - mTouchPrevPos.x; return true; } bool PlaylistChooser::touchEnded( ci::app::TouchEvent::Touch touch ) { if (mData == NULL) return false; mIsDragging = false; mTouchPos = globalToLocal( touch.getPos() ); if (mTouchDragPlaylistIndex >= 0) { float movement = mTouchDragStartPos.distance( mTouchPos ); mOffsetX = mTouchDragStartOffset + (mTouchDragStartPos.x - mTouchPos.x); if (movement < 15.0f) { // TODO: also measure time and don't allow long selection gaps mCurrentIndex = mTouchDragPlaylistIndex; mPrevIndex = mCurrentIndex; // set this so that we won't fire the callback twice mCbPlaylistSelected.call( mData->mPlaylists[mTouchDragPlaylistIndex] ); mCbPlaylistTouched.call( mData->mPlaylists[mTouchDragPlaylistIndex] ); mOffsetX = mTouchDragPlaylistIndex * ( mPlaylistSize.x + mSpacerWidth ); mTouchDragId = 0; mTouchDragPlaylistIndex = -1; mWheelOverlay->setShowWheel(false); return true; } mTouchDragId = 0; mTouchDragPlaylistIndex = -1; mTouchDragStartPos = mTouchPos; mTouchDragStartOffset = mOffsetX; } // if we didn't already return... // so we can dismiss the wheel if we tapped inside the world Vec2f dir = globalToLocal( touch.getPos() ); float distToCenter = dir.length(); float maxDiam = mWheelOverlay->getRadius() + 25.0f; if (distToCenter < maxDiam) { mWheelOverlay->setShowWheel(false); return true; } return false; } void PlaylistChooser::update() { if (mData == NULL) return; mInterfaceSize = getRoot()->getInterfaceSize(); // wheel is already centered, so we have to subtract half of interface height mStartY = = mUiLayer->getPanelYPos() - (mInterfaceSize.y / 2.0f) - 100.0f; float maxOffsetX = (mPlaylistSize.x * (mNumPlaylists+0.5f)) + (mSpacerWidth * (mNumPlaylists-1)); float minOffsetX = -mPlaylistSize.x * 0.5f; ///////////// if( !mIsDragging ){ // carry on with inertia/momentum scrolling... mOffsetX -= mTouchVel; // spring back if we've gone too far... if( mOffsetX < minOffsetX ){ mTouchVel = 0.0f; mOffsetX -= ( mOffsetX - minOffsetX ) * 0.2f; } else if( mOffsetX > maxOffsetX ){ mTouchVel = 0.0f; mOffsetX -= ( mOffsetX - maxOffsetX ) * 0.2f; } if( abs( mTouchVel ) < 10.0f ){ // how far through are we? float offsetPer = (mOffsetX-mPlaylistSize.x/2.0) / (mPlaylistSize.x + mSpacerWidth); // round that for index in mData->mPlaylists int chosenIndex = constrain( (int)round( offsetPer ), 0, mNumPlaylists-1 ); // ease to exact position (centered) float lockOffset = chosenIndex * (mPlaylistSize.x + mSpacerWidth) + mPlaylistSize.x/2.0; mOffsetXLocked -= ( mOffsetXLocked - lockOffset ) * 0.2f; mOffsetX = lockOffset; // cancel momentum mTouchVel = 0.0f; // if we're done easing, check if we settled on a new selection... if( abs( mOffsetXLocked - lockOffset ) < 1.0f ){ mPrevIndex = mCurrentIndex; mCurrentIndex = chosenIndex; if( mPrevIndex != mCurrentIndex ){ mCbPlaylistSelected.call( mData->mPlaylists[mCurrentIndex] ); } } } else { mOffsetXLocked = mOffsetX; mTouchVel *= 0.95f; // slow down } } else { mOffsetXLocked = mOffsetX; } } void PlaylistChooser::draw() { if( mData == NULL ) return; gl::disableDepthRead(); gl::disableDepthWrite(); gl::enableAlphaBlending(); gl::color( Color::white() ); mPlaylistRects.clear(); float border = mPlaylistSize.x * 0.5f; float startX = -mInterfaceSize.x / 2.0 + border; float endX = mInterfaceSize.x / 2.0 - border; Vec2f pos( -mOffsetXLocked, mStartY ); gl::enableAdditiveBlending(); for( int i = 0; i < mNumPlaylists; i++ ) { ipod::PlaylistRef playlist = mData->mPlaylists[i]; if( pos.x < endX && pos.x + mPlaylistSize.x > startX ) { float x = pos.x + mPlaylistSize.x * 0.5f; // x center of the rect float alpha = getAlpha( x ); if (!mTextures[i]) { makeTexture( i, playlist ); } if ( i == mCurrentIndex ) { gl::color( ColorA( 1, 1, 1, alpha ) ); } else if ( i == mTouchDragPlaylistIndex ) { gl::color( ColorA( BRIGHT_BLUE, alpha ) ); } else { gl::color( ColorA( BLUE, alpha ) ); } float w = mTextures[i].getWidth() * 0.5f; float h = mFont.getAscent() + mFont.getDescent(); float padding = 10.0f; Rectf rect = Rectf( x - w - padding, mStartY - padding, x + w + padding, mStartY + h + padding ); mPlaylistRects.push_back( rect ); gl::draw( mTextures[i], Vec2f( x - w, mStartY ) ); // debuggenrectankles // gl::drawStrokedRect( rect ); // gl::drawStrokedRect( Rectf( x - w, mStartY, x + w, mStartY + h ) ); // gl::drawStrokedRect( Rectf( x - mPlaylistSize.x/2.0, mStartY, x + mPlaylistSize.x/2.0, mStartY + h ) ); } else { // STUPID FIX: // Making sure all rects are made, even ones that are offscreen. mPlaylistRects.push_back( Rectf( Vec2f( -500.0f, 0.0f ), Vec2f( -400.0f, 0.0f ) ) ); } pos.x += mSpacerWidth + mPlaylistSize.x; if( pos.x > endX ){ break; } } // highlight the region things will settle into... float w = mPlaylistSize.x/2.0; Path2d path; path.moveTo( -w, mStartY - 8.0f); path.curveTo( Vec2f( -w * 0.8f, mStartY - 14.0f), Vec2f( -w * 0.1f, mStartY - 16.0f), Vec2f( 0.0f, mStartY - 20.0f) ); path.curveTo( Vec2f( w * 0.1f, mStartY - 16.0f), Vec2f( w * 0.8f, mStartY - 14.0f), Vec2f( w, mStartY - 8.0f) ); gl::color( ColorA( 1.0f, 1.0f, 1.0f, 0.2f ) ); gl::draw(path); // gl::drawStrokedRect( Rectf( -w, mStartY, w, mStartY + h ) ); gl::color( ColorA( 1.0f, 1.0f, 1.0f, 1.0f ) ); gl::disableDepthRead(); gl::disableDepthWrite(); gl::enableAlphaBlending(); } void PlaylistChooser::makeTexture( int index, ipod::PlaylistRef playlist ) { string name = playlist->getPlaylistName(); if( name.length() > 20 ){ name = name.substr( 0, 20 ); name += "..."; } TextLayout layout; layout.setFont( mFont ); layout.setColor( BRIGHT_BLUE ); layout.addLine( name ); mTextures[index] = gl::Texture( layout.render( true, false ) ); } float PlaylistChooser::getAlpha( float x ) { float per = (x + mInterfaceSize.x/2.0f) / mInterfaceSize.x; float invCos = ( 1.0f - (float)cos( per * M_PI * 2.0f ) ) * 0.5f; float cosPer = pow( invCos, 0.5f ); return cosPer; } float PlaylistChooser::getScale( float x ) { float per = (x + mInterfaceSize.x/2.0f) / mInterfaceSize.x; float invCos = ( 1.0f - (float)cos( per * M_PI * 2.0f ) ) * 0.5f; float cosPer = max( pow( invCos, 3.5f ) + 0.4f, 0.5f ); return cosPer; } float PlaylistChooser::getNewX( float x ) { float per = (x + mInterfaceSize.x/2.0f) / mInterfaceSize.x; per *= 0.7f; per += 0.15f; float cosPer = ( 1.0f - cos( per * M_PI ) ) * 0.5f; return cosPer * mInterfaceSize.x; } float PlaylistChooser::getNewY( float x ) { float per = (x + mInterfaceSize.x/2.0f) / mInterfaceSize.x; float sinPer = sin( per * M_PI ); return sinPer; } void PlaylistChooser::setDataWorldCam( Data *data, World *world, CameraPersp *cam ) { mData = data; mWorld = world; mCam = cam; mNumPlaylists = mData->mPlaylists.size(); mTextures.resize(mNumPlaylists); } <commit_msg>fix playlistchooser update<commit_after>// // PlaylistChooser.cpp // Kepler // // Created by Tom Carden on 7/10/11. // Copyright 2011 __MyCompanyName__. All rights reserved. // #include <string> #include "cinder/Vector.h" #include "cinder/PolyLine.h" #include "cinder/ImageIo.h" #include "cinder/Rand.h" #include "cinder/Path2d.h" #include "PlaylistChooser.h" #include "NodeArtist.h" #include "BloomScene.h" #include "Globals.h" using namespace ci; using namespace ci::app; using namespace std; void PlaylistChooser::setup( const Font &font, UiLayerRef uiLayer, WheelOverlayRef wheelOverlay ) { mFont = font; mTouchDragId = 0; mTouchDragStartPos = Vec2i( 0, 0 ); mTouchDragStartOffset = 0.0f; mTouchDragPlaylistIndex = -1; mTouchVel = 0.0f; mTouchPos = Vec2i( 0, 0 ); mTouchPrevPos = Vec2i( 0, 0 ); mOffsetX = -200.0f; mOffsetXLocked = -200.0f; mNumPlaylists = 0; mIsDragging = false; mPlaylistSize = Vec2f( 120.f, 30.0f ); mSpacerWidth = 30.0f; mStartY = 350.0f; mPrevIndex = -1; mCurrentIndex = 0; mWheelOverlay = wheelOverlay; mUiLayer = uiLayer; } bool PlaylistChooser::touchBegan( ci::app::TouchEvent::Touch touch ) { if( mData == NULL || mTouchDragPlaylistIndex >= 0 ) return false; mIsDragging = false; mTouchPrevPos = mTouchPos; mTouchPos = globalToLocal( touch.getPos() ); mTouchVel = 0.0f; for( int i = 0; i < mPlaylistRects.size(); i++ ){ if( mPlaylistRects[i].contains( mTouchPos ) ){ // remember the id and dispatch this event on touchesEnded if it hasn't moved much (otherwise just drag) mTouchDragId = touch.getId(); mTouchDragStartPos = mTouchPos; mTouchDragStartOffset = mOffsetX; mTouchDragPlaylistIndex = i; return true; } } // if we didn't already return... // capture all touches inside wheel so we can dismiss a tap inside the world Vec2f dir = globalToLocal( touch.getPos() ); float distToCenter = dir.length(); float maxDiam = mWheelOverlay->getRadius() + 25.0f; return distToCenter < maxDiam; } bool PlaylistChooser::touchMoved( ci::app::TouchEvent::Touch touch ) { if (mData == NULL || mTouchDragPlaylistIndex < 0) return false; mIsDragging = true; mTouchPrevPos = mTouchPos; mTouchPos = globalToLocal( touch.getPos() ); mOffsetX = mTouchDragStartOffset + ( mTouchDragStartPos.x - mTouchPos.x ); mTouchVel = mTouchPos.x - mTouchPrevPos.x; return true; } bool PlaylistChooser::touchEnded( ci::app::TouchEvent::Touch touch ) { if (mData == NULL) return false; mIsDragging = false; mTouchPos = globalToLocal( touch.getPos() ); if (mTouchDragPlaylistIndex >= 0) { float movement = mTouchDragStartPos.distance( mTouchPos ); mOffsetX = mTouchDragStartOffset + (mTouchDragStartPos.x - mTouchPos.x); if (movement < 15.0f) { // TODO: also measure time and don't allow long selection gaps mCurrentIndex = mTouchDragPlaylistIndex; mPrevIndex = mCurrentIndex; // set this so that we won't fire the callback twice mCbPlaylistSelected.call( mData->mPlaylists[mTouchDragPlaylistIndex] ); mCbPlaylistTouched.call( mData->mPlaylists[mTouchDragPlaylistIndex] ); mOffsetX = mTouchDragPlaylistIndex * ( mPlaylistSize.x + mSpacerWidth ); mTouchDragId = 0; mTouchDragPlaylistIndex = -1; mWheelOverlay->setShowWheel(false); return true; } mTouchDragId = 0; mTouchDragPlaylistIndex = -1; mTouchDragStartPos = mTouchPos; mTouchDragStartOffset = mOffsetX; } // if we didn't already return... // so we can dismiss the wheel if we tapped inside the world Vec2f dir = globalToLocal( touch.getPos() ); float distToCenter = dir.length(); float maxDiam = mWheelOverlay->getRadius() + 25.0f; if (distToCenter < maxDiam) { mWheelOverlay->setShowWheel(false); return true; } return false; } void PlaylistChooser::update() { if (mData == NULL) return; mInterfaceSize = getRoot()->getInterfaceSize(); // wheel is already centered, so we have to subtract half of interface height mStartY = mUiLayer->getPanelYPos() - (mInterfaceSize.y / 2.0f) - 100.0f; float maxOffsetX = (mPlaylistSize.x * (mNumPlaylists+0.5f)) + (mSpacerWidth * (mNumPlaylists-1)); float minOffsetX = -mPlaylistSize.x * 0.5f; ///////////// if( !mIsDragging ){ // carry on with inertia/momentum scrolling... mOffsetX -= mTouchVel; // spring back if we've gone too far... if( mOffsetX < minOffsetX ){ mTouchVel = 0.0f; mOffsetX -= ( mOffsetX - minOffsetX ) * 0.2f; } else if( mOffsetX > maxOffsetX ){ mTouchVel = 0.0f; mOffsetX -= ( mOffsetX - maxOffsetX ) * 0.2f; } if( abs( mTouchVel ) < 10.0f ){ // how far through are we? float offsetPer = (mOffsetX-mPlaylistSize.x/2.0) / (mPlaylistSize.x + mSpacerWidth); // round that for index in mData->mPlaylists int chosenIndex = constrain( (int)round( offsetPer ), 0, mNumPlaylists-1 ); // ease to exact position (centered) float lockOffset = chosenIndex * (mPlaylistSize.x + mSpacerWidth) + mPlaylistSize.x/2.0; mOffsetXLocked -= ( mOffsetXLocked - lockOffset ) * 0.2f; mOffsetX = lockOffset; // cancel momentum mTouchVel = 0.0f; // if we're done easing, check if we settled on a new selection... if( abs( mOffsetXLocked - lockOffset ) < 1.0f ){ mPrevIndex = mCurrentIndex; mCurrentIndex = chosenIndex; if( mPrevIndex != mCurrentIndex ){ mCbPlaylistSelected.call( mData->mPlaylists[mCurrentIndex] ); } } } else { mOffsetXLocked = mOffsetX; mTouchVel *= 0.95f; // slow down } } else { mOffsetXLocked = mOffsetX; } } void PlaylistChooser::draw() { if( mData == NULL ) return; gl::disableDepthRead(); gl::disableDepthWrite(); gl::enableAlphaBlending(); gl::color( Color::white() ); mPlaylistRects.clear(); float border = mPlaylistSize.x * 0.5f; float startX = -mInterfaceSize.x / 2.0 + border; float endX = mInterfaceSize.x / 2.0 - border; Vec2f pos( -mOffsetXLocked, mStartY ); gl::enableAdditiveBlending(); for( int i = 0; i < mNumPlaylists; i++ ) { ipod::PlaylistRef playlist = mData->mPlaylists[i]; if( pos.x < endX && pos.x + mPlaylistSize.x > startX ) { float x = pos.x + mPlaylistSize.x * 0.5f; // x center of the rect float alpha = getAlpha( x ); if (!mTextures[i]) { makeTexture( i, playlist ); } if ( i == mCurrentIndex ) { gl::color( ColorA( 1, 1, 1, alpha ) ); } else if ( i == mTouchDragPlaylistIndex ) { gl::color( ColorA( BRIGHT_BLUE, alpha ) ); } else { gl::color( ColorA( BLUE, alpha ) ); } float w = mTextures[i].getWidth() * 0.5f; float h = mFont.getAscent() + mFont.getDescent(); float padding = 10.0f; Rectf rect = Rectf( x - w - padding, mStartY - padding, x + w + padding, mStartY + h + padding ); mPlaylistRects.push_back( rect ); gl::draw( mTextures[i], Vec2f( x - w, mStartY ) ); // debuggenrectankles // gl::drawStrokedRect( rect ); // gl::drawStrokedRect( Rectf( x - w, mStartY, x + w, mStartY + h ) ); // gl::drawStrokedRect( Rectf( x - mPlaylistSize.x/2.0, mStartY, x + mPlaylistSize.x/2.0, mStartY + h ) ); } else { // STUPID FIX: // Making sure all rects are made, even ones that are offscreen. mPlaylistRects.push_back( Rectf( Vec2f( -500.0f, 0.0f ), Vec2f( -400.0f, 0.0f ) ) ); } pos.x += mSpacerWidth + mPlaylistSize.x; if( pos.x > endX ){ break; } } // highlight the region things will settle into... float w = mPlaylistSize.x/2.0; Path2d path; path.moveTo( -w, mStartY - 8.0f); path.curveTo( Vec2f( -w * 0.8f, mStartY - 14.0f), Vec2f( -w * 0.1f, mStartY - 16.0f), Vec2f( 0.0f, mStartY - 20.0f) ); path.curveTo( Vec2f( w * 0.1f, mStartY - 16.0f), Vec2f( w * 0.8f, mStartY - 14.0f), Vec2f( w, mStartY - 8.0f) ); gl::color( ColorA( 1.0f, 1.0f, 1.0f, 0.2f ) ); gl::draw(path); // gl::drawStrokedRect( Rectf( -w, mStartY, w, mStartY + h ) ); gl::color( ColorA( 1.0f, 1.0f, 1.0f, 1.0f ) ); gl::disableDepthRead(); gl::disableDepthWrite(); gl::enableAlphaBlending(); } void PlaylistChooser::makeTexture( int index, ipod::PlaylistRef playlist ) { string name = playlist->getPlaylistName(); if( name.length() > 20 ){ name = name.substr( 0, 20 ); name += "..."; } TextLayout layout; layout.setFont( mFont ); layout.setColor( BRIGHT_BLUE ); layout.addLine( name ); mTextures[index] = gl::Texture( layout.render( true, false ) ); } float PlaylistChooser::getAlpha( float x ) { float per = (x + mInterfaceSize.x/2.0f) / mInterfaceSize.x; float invCos = ( 1.0f - (float)cos( per * M_PI * 2.0f ) ) * 0.5f; float cosPer = pow( invCos, 0.5f ); return cosPer; } float PlaylistChooser::getScale( float x ) { float per = (x + mInterfaceSize.x/2.0f) / mInterfaceSize.x; float invCos = ( 1.0f - (float)cos( per * M_PI * 2.0f ) ) * 0.5f; float cosPer = max( pow( invCos, 3.5f ) + 0.4f, 0.5f ); return cosPer; } float PlaylistChooser::getNewX( float x ) { float per = (x + mInterfaceSize.x/2.0f) / mInterfaceSize.x; per *= 0.7f; per += 0.15f; float cosPer = ( 1.0f - cos( per * M_PI ) ) * 0.5f; return cosPer * mInterfaceSize.x; } float PlaylistChooser::getNewY( float x ) { float per = (x + mInterfaceSize.x/2.0f) / mInterfaceSize.x; float sinPer = sin( per * M_PI ); return sinPer; } void PlaylistChooser::setDataWorldCam( Data *data, World *world, CameraPersp *cam ) { mData = data; mWorld = world; mCam = cam; mNumPlaylists = mData->mPlaylists.size(); mTextures.resize(mNumPlaylists); } <|endoftext|>
<commit_before>/* Copyright (C) 2010 George Kiagiadakis <kiagiadakis.george@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "urihandler.h" #include "element.h" #include <gst/gsturi.h> #include <QtCore/QUrl> #include <QtCore/QStringList> namespace QGst { //static bool UriHandler::protocolIsSupported(UriType type, const char *protocol) { return gst_uri_protocol_is_supported(static_cast<GstURIType>(type), protocol); } //static ElementPtr UriHandler::makeFromUri(UriType type, const QUrl & uri, const char *elementName) { GstElement *e = gst_element_make_from_uri(static_cast<GstURIType>(type), uri.toEncoded(), elementName); if (e) { gst_object_ref_sink(e); } return ElementPtr::wrap(e, false); } UriType UriHandler::uriType() const { return static_cast<UriType>(gst_uri_handler_get_uri_type(object<GstURIHandler>())); } QStringList UriHandler::supportedProtocols() const { QStringList result; char **protocols = gst_uri_handler_get_protocols(object<GstURIHandler>()); if (protocols) { for (char **p = protocols; p && *p; ++p) { result.append(QString::fromUtf8(*p)); } } return result; } QUrl UriHandler::uri() const { //QUrl::fromEncoded doesn't work because the returned URI //is encoded using percent encoding even for slashes. return QUrl::fromPercentEncoding(gst_uri_handler_get_uri(object<GstURIHandler>())); } bool UriHandler::setUri(const QUrl & uri) { return gst_uri_handler_set_uri(object<GstURIHandler>(), uri.toEncoded()); } } //namespace QGst <commit_msg>src/QGst/urihandler.cpp add #include <gst/gstelementfactory.h><commit_after>/* Copyright (C) 2010 George Kiagiadakis <kiagiadakis.george@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "urihandler.h" #include "element.h" #include <gst/gstelementfactory.h> #include <gst/gsturi.h> #include <QtCore/QUrl> #include <QtCore/QStringList> namespace QGst { //static bool UriHandler::protocolIsSupported(UriType type, const char *protocol) { return gst_uri_protocol_is_supported(static_cast<GstURIType>(type), protocol); } //static ElementPtr UriHandler::makeFromUri(UriType type, const QUrl & uri, const char *elementName) { GstElement *e = gst_element_make_from_uri(static_cast<GstURIType>(type), uri.toEncoded(), elementName); if (e) { gst_object_ref_sink(e); } return ElementPtr::wrap(e, false); } UriType UriHandler::uriType() const { return static_cast<UriType>(gst_uri_handler_get_uri_type(object<GstURIHandler>())); } QStringList UriHandler::supportedProtocols() const { QStringList result; char **protocols = gst_uri_handler_get_protocols(object<GstURIHandler>()); if (protocols) { for (char **p = protocols; p && *p; ++p) { result.append(QString::fromUtf8(*p)); } } return result; } QUrl UriHandler::uri() const { //QUrl::fromEncoded doesn't work because the returned URI //is encoded using percent encoding even for slashes. return QUrl::fromPercentEncoding(gst_uri_handler_get_uri(object<GstURIHandler>())); } bool UriHandler::setUri(const QUrl & uri) { return gst_uri_handler_set_uri(object<GstURIHandler>(), uri.toEncoded()); } } //namespace QGst <|endoftext|>
<commit_before>//-------------------------------------------------- // file: RPN+UnitTests.cpp //------------------------------------------------- #define CATCH_CONFIG_MAIN #include "catch.hpp" #include "RPNCalc.h" #include "RPNTestHelper.h" using namespace P4_RPNCALC; TEST_CASE("Operation Methods") { RPNTestHelper test; SECTION("Sanity Tests") { for (int n = 0; n < 100; n++) { REQUIRE(test.expectedStackOutput(to_string(n), to_string(n))); } } SECTION("Method: clearAll()") { REQUIRE(test.expectedStackOutput("50", "50")); REQUIRE(test.expectedOutput("c", "")); REQUIRE(test.expectedStackOutput("50 100 +", "150")); REQUIRE(test.expectedOutput("c", "")); REQUIRE(test.expectedStackOutput("50 100 + 200", "200")); REQUIRE(test.expectedOutput("c", "")); REQUIRE(test.expectedStackOutput("50", "50")); REQUIRE(test.expectedOutput("C", "")); REQUIRE(test.expectedStackOutput("50 100 +", "150")); REQUIRE(test.expectedOutput("C", "")); REQUIRE(test.expectedStackOutput("50 100 + 200", "200")); REQUIRE(test.expectedOutput("C", "")); } SECTION("Method: clearEntry()") { REQUIRE(test.expectedStackOutput("50", "50")); REQUIRE(test.expectedOutput("ce", "")); REQUIRE(test.expectedStackOutput("50 100 +", "150")); REQUIRE(test.expectedOutput("ce", "")); REQUIRE(test.expectedStackOutput("50 100 + 200", "200")); REQUIRE(test.expectedStackOutput("ce", "150")); REQUIRE(test.expectedOutput("ce", "")); REQUIRE(test.expectedStackOutput("50", "50")); REQUIRE(test.expectedOutput("CE", "")); REQUIRE(test.expectedStackOutput("50 100 +", "150")); REQUIRE(test.expectedOutput("CE", "")); REQUIRE(test.expectedStackOutput("50 100 + 200", "200")); REQUIRE(test.expectedStackOutput("CE", "150")); REQUIRE(test.expectedOutput("CE", "")); } SECTION("Method: add()") { REQUIRE(test.expectedStackOutput("3 5+", "8")); REQUIRE(test.expectedStackOutput("2 4 3 +", "7")); REQUIRE(test.expectedOutput("c", "")); REQUIRE(test.expectedStackOutput("3 4 + 6", "6")); REQUIRE(test.expectedStackOutput("4 +", "10")); REQUIRE(test.expectedStackOutput("-12 +", "-2")); REQUIRE(test.expectedStackOutput("5 +", "3")); REQUIRE(test.expectedStackOutput("3 +", "6")); REQUIRE(test.getStackOutput("10 100 +") == "110"); REQUIRE(test.getStackOutput("10 100+") == "110"); } SECTION("Method: combinations of add() & subtract()") { REQUIRE(test.getStackOutput("4.4 5.5 + 60 -") == "-50.1"); REQUIRE(test.expectedStackOutput("4.4 5.5 - 60 +", "58.9")); REQUIRE(test.expectedStackOutput("40 50 + 60 -", "30")); REQUIRE(test.expectedStackOutput("40 50 - 60 +", "50")); REQUIRE(test.expectedStackOutput("40 50 60 + -", "-70")); REQUIRE(test.expectedStackOutput("40 50 60 - +", "30")); REQUIRE(test.expectedStackOutput("-40 -50 + 60 -", "-150")); REQUIRE(test.expectedStackOutput("-40 -50 + -60 -", "-30")); REQUIRE(test.expectedStackOutput("-40 -50 - 60 +", "70")); REQUIRE(test.expectedStackOutput("-40 -50 - -60 +", "-50")); } SECTION("Method: subtract()") { REQUIRE(test.expectedStackOutput("5 6 -", "-1")); REQUIRE(test.expectedStackOutput("3 9 4 -", "5")); REQUIRE(test.expectedStackOutput("-", "-2")); REQUIRE(test.expectedOutput("c", "")); REQUIRE(test.expectedStackOutput("-1 5 -", "-6")); REQUIRE(test.expectedStackOutput("10 100 -", "-90")); REQUIRE(test.expectedStackOutput("10 100-", "-90")); REQUIRE(test.expectedStackOutput("-", "0")); } SECTION("Method: multiply()") { REQUIRE(test.expectedStackOutput("3 9 7 2 4 *", "8")); REQUIRE(test.expectedStackOutput("*", "56")); REQUIRE(test.expectedStackOutput("*", "504")); REQUIRE(test.expectedStackOutput("*", "1512")); REQUIRE(test.expectError("*")); REQUIRE(test.getOutput("c") == ""); REQUIRE(test.expectedStackOutput("-4 -6 *", "24")); REQUIRE(test.expectedStackOutput("-2 *", "-48")); REQUIRE(test.expectedStackOutput("10 100 *", "1000")); REQUIRE(test.expectedStackOutput("10 100*", "1000")); REQUIRE(test.expectedStackOutput("5.5 2.2*", "12.1")); } SECTION("Method: divide()") { REQUIRE(test.expectedStackOutput("16 4 2 /", "2")); REQUIRE(test.expectedStackOutput("/", "8")); REQUIRE(test.expectedOutput("c", "")); REQUIRE(test.expectedStackOutput("2 5 /", "0.4")); REQUIRE(test.expectedStackOutput("9 3 7 /", "0.428571")); REQUIRE(test.expectedStackOutput("-1 /", "-0.428571")); REQUIRE(test.expectedStackOutput("-1 / ", "0.428571")); REQUIRE(test.expectedStackOutput("100 10 /", "10")); REQUIRE(test.expectedStackOutput("100 10/", "10")); REQUIRE(test.expectedStackOutput("/", "1")); REQUIRE(test.expectedStackOutput("/", "0.428571")); REQUIRE(test.expectedStackOutput("/", "21")); REQUIRE(test.expectedStackOutput("/", "0.0190476")); REQUIRE(test.expectedStackOutput("/", "0.0190476")); REQUIRE(test.expectError("/")); } SECTION("Method: mod()") { REQUIRE(test.expectedStackOutput("16 8 6 %", "2")); REQUIRE(test.expectedStackOutput("%", "0")); REQUIRE(test.expectedOutput("c", "")); REQUIRE(test.expectError("%")); REQUIRE(test.expectedStackOutput("10 1 %", "0")); REQUIRE(test.expectedStackOutput("10 2 %", "0")); REQUIRE(test.expectedStackOutput("10 3 %", "1")); REQUIRE(test.expectedStackOutput("10 4 %", "2")); REQUIRE(test.expectedStackOutput("10 5 %", "0")); REQUIRE(test.expectedStackOutput("10 6 %", "4")); REQUIRE(test.expectedStackOutput("10 7 %", "3")); REQUIRE(test.expectedStackOutput("10 8 %", "2")); REQUIRE(test.expectedStackOutput("10 9 %", "1")); REQUIRE(test.expectedStackOutput("10 10 %", "0")); REQUIRE(test.expectedStackOutput("100 70 %", "30")); REQUIRE(test.expectedStackOutput("100 70%", "30")); } /* SECTION("Method: exp()") { REQUIRE(test.expectedInputOutput("10 2 ^", "100")); REQUIRE(test.expectedInputOutput("10 2 2 ^", "4")); REQUIRE(test.expectedInputOutput("^", "10000")); REQUIRE(test.expectedInputOutput("-10 2 ^", "100")); REQUIRE(test.expectedInputOutput("-10 3 ^", "-1000")); REQUIRE(test.expectedInputOutput("-10 3^", "-1000")); REQUIRE(test.expectedInputOutput("0^", "1")); REQUIRE(test.expectedInputOutput("^", "<<error>>")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("100 100^", "1e+200")); } SECTION("Method: neg()") { REQUIRE(test.expectedInputOutput("-1000", "-1000")); REQUIRE(test.expectedInputOutput("M", "1000")); REQUIRE(test.expectedInputOutput("-1000 -1*", "1000")); REQUIRE(test.expectedInputOutput("M", "-1000")); REQUIRE(test.expectedInputOutput("-4/", "-250")); REQUIRE(test.expectedInputOutput("m", "250")); REQUIRE(test.expectedInputOutput("-2*", "-500")); REQUIRE(test.expectedInputOutput("m", "500")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("m", "<<error>>")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("M", "<<error>>")); } SECTION("Method: rotateDown()") { REQUIRE(test.expectedInputOutput("100 200", "200")); REQUIRE(test.expectedInputOutput("D", "100")); REQUIRE(test.expectedInputOutput("D", "200")); REQUIRE(test.expectedInputOutput("d", "100")); REQUIRE(test.expectedInputOutput("d", "200")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("D", "<<error>>")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("d", "<<error>>")); } SECTION("Method: rotateUp()") { REQUIRE(test.expectedInputOutput("300 500", "500")); REQUIRE(test.expectedInputOutput("U", "300")); REQUIRE(test.expectedInputOutput("U", "500")); REQUIRE(test.expectedInputOutput("u", "300")); REQUIRE(test.expectedInputOutput("u", "500")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("U", "<<error>>")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("u", "<<error>>")); } SECTION("Methods: saveToFile(), loadProgram(), recordProgram(), runProgram()") { REQUIRE(test.expectedInputOutput("R", "<<error>>")); REQUIRE(test.expectedInputOutput("F", "<<error>>")); REQUIRE(test.expectedInputOutput("p", "0>")); REQUIRE(test.expectedInputOutput("5 10 +", "1>")); REQUIRE(test.expectedInputOutput("20 30 -", "2>")); //REQUIRE(test.expectedInputOutput("P", "")); //REQUIRE(test.expectedInputOutput("f", "Enter a filename:")); REQUIRE(test.expectedInputOutput("test1", "")); //REQUIRE(test.expectedInputOutput("l", "Enter a filename:")); REQUIRE(test.expectedInputOutput("test", "error")); //REQUIRE(test.expectedInputOutput("L", "Enter a filename:")); REQUIRE(test.expectedInputOutput("test1", "")); REQUIRE(test.expectedInputOutput("r", "-10")); REQUIRE(test.expectedInputOutput("c", "")); } SECTION("Methods: getReg(), setReg()") { REQUIRE(test.expectedInputOutput("s0", "<<error>>")); REQUIRE(test.expectedInputOutput("S1", "<<error>>")); REQUIRE(test.expectedInputOutput("s5", "<<error>>")); REQUIRE(test.expectedInputOutput("G0", "0")); REQUIRE(test.expectedInputOutput("g1", "0")); REQUIRE(test.expectedInputOutput("G5", "0")); REQUIRE(test.expectedInputOutput("1000", "1000")); REQUIRE(test.expectedInputOutput("s5", "1000")); REQUIRE(test.expectedInputOutput("2.5", "2.5")); REQUIRE(test.expectedInputOutput("S0", "2.5")); REQUIRE(test.expectedInputOutput("G5", "1000")); REQUIRE(test.expectedInputOutput("g0", "2.5")); } // */ } //*/<commit_msg>correct exp tests<commit_after>//-------------------------------------------------- // file: RPN+UnitTests.cpp //------------------------------------------------- #define CATCH_CONFIG_MAIN #include "catch.hpp" #include "RPNCalc.h" #include "RPNTestHelper.h" using namespace P4_RPNCALC; TEST_CASE("Operation Methods") { RPNTestHelper test; SECTION("Sanity Tests") { for (int n = 0; n < 100; n++) { REQUIRE(test.expectedStackOutput(to_string(n), to_string(n))); } } SECTION("Method: clearAll()") { REQUIRE(test.expectedStackOutput("50", "50")); REQUIRE(test.expectedOutput("c", "")); REQUIRE(test.expectedStackOutput("50 100 +", "150")); REQUIRE(test.expectedOutput("c", "")); REQUIRE(test.expectedStackOutput("50 100 + 200", "200")); REQUIRE(test.expectedOutput("c", "")); REQUIRE(test.expectedStackOutput("50", "50")); REQUIRE(test.expectedOutput("C", "")); REQUIRE(test.expectedStackOutput("50 100 +", "150")); REQUIRE(test.expectedOutput("C", "")); REQUIRE(test.expectedStackOutput("50 100 + 200", "200")); REQUIRE(test.expectedOutput("C", "")); } SECTION("Method: clearEntry()") { REQUIRE(test.expectedStackOutput("50", "50")); REQUIRE(test.expectedOutput("ce", "")); REQUIRE(test.expectedStackOutput("50 100 +", "150")); REQUIRE(test.expectedOutput("ce", "")); REQUIRE(test.expectedStackOutput("50 100 + 200", "200")); REQUIRE(test.expectedStackOutput("ce", "150")); REQUIRE(test.expectedOutput("ce", "")); REQUIRE(test.expectedStackOutput("50", "50")); REQUIRE(test.expectedOutput("CE", "")); REQUIRE(test.expectedStackOutput("50 100 +", "150")); REQUIRE(test.expectedOutput("CE", "")); REQUIRE(test.expectedStackOutput("50 100 + 200", "200")); REQUIRE(test.expectedStackOutput("CE", "150")); REQUIRE(test.expectedOutput("CE", "")); } SECTION("Method: add()") { REQUIRE(test.expectedStackOutput("3 5+", "8")); REQUIRE(test.expectedStackOutput("2 4 3 +", "7")); REQUIRE(test.expectedOutput("c", "")); REQUIRE(test.expectedStackOutput("3 4 + 6", "6")); REQUIRE(test.expectedStackOutput("4 +", "10")); REQUIRE(test.expectedStackOutput("-12 +", "-2")); REQUIRE(test.expectedStackOutput("5 +", "3")); REQUIRE(test.expectedStackOutput("3 +", "6")); REQUIRE(test.getStackOutput("10 100 +") == "110"); REQUIRE(test.getStackOutput("10 100+") == "110"); } SECTION("Method: combinations of add() & subtract()") { REQUIRE(test.getStackOutput("4.4 5.5 + 60 -") == "-50.1"); REQUIRE(test.expectedStackOutput("4.4 5.5 - 60 +", "58.9")); REQUIRE(test.expectedStackOutput("40 50 + 60 -", "30")); REQUIRE(test.expectedStackOutput("40 50 - 60 +", "50")); REQUIRE(test.expectedStackOutput("40 50 60 + -", "-70")); REQUIRE(test.expectedStackOutput("40 50 60 - +", "30")); REQUIRE(test.expectedStackOutput("-40 -50 + 60 -", "-150")); REQUIRE(test.expectedStackOutput("-40 -50 + -60 -", "-30")); REQUIRE(test.expectedStackOutput("-40 -50 - 60 +", "70")); REQUIRE(test.expectedStackOutput("-40 -50 - -60 +", "-50")); } SECTION("Method: subtract()") { REQUIRE(test.expectedStackOutput("5 6 -", "-1")); REQUIRE(test.expectedStackOutput("3 9 4 -", "5")); REQUIRE(test.expectedStackOutput("-", "-2")); REQUIRE(test.expectedOutput("c", "")); REQUIRE(test.expectedStackOutput("-1 5 -", "-6")); REQUIRE(test.expectedStackOutput("10 100 -", "-90")); REQUIRE(test.expectedStackOutput("10 100-", "-90")); REQUIRE(test.expectedStackOutput("-", "0")); } SECTION("Method: multiply()") { REQUIRE(test.expectedStackOutput("3 9 7 2 4 *", "8")); REQUIRE(test.expectedStackOutput("*", "56")); REQUIRE(test.expectedStackOutput("*", "504")); REQUIRE(test.expectedStackOutput("*", "1512")); REQUIRE(test.expectError("*")); REQUIRE(test.getOutput("c") == ""); REQUIRE(test.expectedStackOutput("-4 -6 *", "24")); REQUIRE(test.expectedStackOutput("-2 *", "-48")); REQUIRE(test.expectedStackOutput("10 100 *", "1000")); REQUIRE(test.expectedStackOutput("10 100*", "1000")); REQUIRE(test.expectedStackOutput("5.5 2.2*", "12.1")); } SECTION("Method: divide()") { REQUIRE(test.expectedStackOutput("16 4 2 /", "2")); REQUIRE(test.expectedStackOutput("/", "8")); REQUIRE(test.expectedOutput("c", "")); REQUIRE(test.expectedStackOutput("2 5 /", "0.4")); REQUIRE(test.expectedStackOutput("9 3 7 /", "0.428571")); REQUIRE(test.expectedStackOutput("-1 /", "-0.428571")); REQUIRE(test.expectedStackOutput("-1 / ", "0.428571")); REQUIRE(test.expectedStackOutput("100 10 /", "10")); REQUIRE(test.expectedStackOutput("100 10/", "10")); REQUIRE(test.expectedStackOutput("/", "1")); REQUIRE(test.expectedStackOutput("/", "0.428571")); REQUIRE(test.expectedStackOutput("/", "21")); REQUIRE(test.expectedStackOutput("/", "0.0190476")); REQUIRE(test.expectedStackOutput("/", "0.0190476")); REQUIRE(test.expectError("/")); } SECTION("Method: mod()") { REQUIRE(test.expectedStackOutput("16 8 6 %", "2")); REQUIRE(test.expectedStackOutput("%", "0")); REQUIRE(test.expectedOutput("c", "")); REQUIRE(test.expectError("%")); REQUIRE(test.expectedStackOutput("10 1 %", "0")); REQUIRE(test.expectedStackOutput("10 2 %", "0")); REQUIRE(test.expectedStackOutput("10 3 %", "1")); REQUIRE(test.expectedStackOutput("10 4 %", "2")); REQUIRE(test.expectedStackOutput("10 5 %", "0")); REQUIRE(test.expectedStackOutput("10 6 %", "4")); REQUIRE(test.expectedStackOutput("10 7 %", "3")); REQUIRE(test.expectedStackOutput("10 8 %", "2")); REQUIRE(test.expectedStackOutput("10 9 %", "1")); REQUIRE(test.expectedStackOutput("10 10 %", "0")); REQUIRE(test.expectedStackOutput("100 70 %", "30")); REQUIRE(test.expectedStackOutput("100 70%", "30")); } SECTION("Method: exp()") { REQUIRE(test.expectedStackOutput("10 2 ^", "100")); REQUIRE(test.expectedStackOutput("10 2 2 ^", "4")); REQUIRE(test.expectedStackOutput("^", "10000")); REQUIRE(test.expectedStackOutput("-10 2 ^", "100")); REQUIRE(test.expectedStackOutput("-10 3 ^", "-1000")); REQUIRE(test.expectedStackOutput("-10 3^", "-1000")); REQUIRE(test.expectedStackOutput("0^", "1")); REQUIRE(test.expectedStackOutput("^", "-1000")); REQUIRE(test.expectedStackOutput("^", "0")); REQUIRE(test.expectedStackOutput("^", "1")); REQUIRE(test.expectedStackOutput("^", "100")); REQUIRE(test.expectError("^")); REQUIRE(test.expectedOutput("c", "")); REQUIRE(test.expectError("^")); REQUIRE(test.expectedStackOutput("100 100^", "1e+200")); } /* SECTION("Method: neg()") { REQUIRE(test.expectedInputOutput("-1000", "-1000")); REQUIRE(test.expectedInputOutput("M", "1000")); REQUIRE(test.expectedInputOutput("-1000 -1*", "1000")); REQUIRE(test.expectedInputOutput("M", "-1000")); REQUIRE(test.expectedInputOutput("-4/", "-250")); REQUIRE(test.expectedInputOutput("m", "250")); REQUIRE(test.expectedInputOutput("-2*", "-500")); REQUIRE(test.expectedInputOutput("m", "500")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("m", "<<error>>")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("M", "<<error>>")); } SECTION("Method: rotateDown()") { REQUIRE(test.expectedInputOutput("100 200", "200")); REQUIRE(test.expectedInputOutput("D", "100")); REQUIRE(test.expectedInputOutput("D", "200")); REQUIRE(test.expectedInputOutput("d", "100")); REQUIRE(test.expectedInputOutput("d", "200")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("D", "<<error>>")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("d", "<<error>>")); } SECTION("Method: rotateUp()") { REQUIRE(test.expectedInputOutput("300 500", "500")); REQUIRE(test.expectedInputOutput("U", "300")); REQUIRE(test.expectedInputOutput("U", "500")); REQUIRE(test.expectedInputOutput("u", "300")); REQUIRE(test.expectedInputOutput("u", "500")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("U", "<<error>>")); REQUIRE(test.expectedInputOutput("c", "")); REQUIRE(test.expectedInputOutput("u", "<<error>>")); } SECTION("Methods: saveToFile(), loadProgram(), recordProgram(), runProgram()") { REQUIRE(test.expectedInputOutput("R", "<<error>>")); REQUIRE(test.expectedInputOutput("F", "<<error>>")); REQUIRE(test.expectedInputOutput("p", "0>")); REQUIRE(test.expectedInputOutput("5 10 +", "1>")); REQUIRE(test.expectedInputOutput("20 30 -", "2>")); //REQUIRE(test.expectedInputOutput("P", "")); //REQUIRE(test.expectedInputOutput("f", "Enter a filename:")); REQUIRE(test.expectedInputOutput("test1", "")); //REQUIRE(test.expectedInputOutput("l", "Enter a filename:")); REQUIRE(test.expectedInputOutput("test", "error")); //REQUIRE(test.expectedInputOutput("L", "Enter a filename:")); REQUIRE(test.expectedInputOutput("test1", "")); REQUIRE(test.expectedInputOutput("r", "-10")); REQUIRE(test.expectedInputOutput("c", "")); } SECTION("Methods: getReg(), setReg()") { REQUIRE(test.expectedInputOutput("s0", "<<error>>")); REQUIRE(test.expectedInputOutput("S1", "<<error>>")); REQUIRE(test.expectedInputOutput("s5", "<<error>>")); REQUIRE(test.expectedInputOutput("G0", "0")); REQUIRE(test.expectedInputOutput("g1", "0")); REQUIRE(test.expectedInputOutput("G5", "0")); REQUIRE(test.expectedInputOutput("1000", "1000")); REQUIRE(test.expectedInputOutput("s5", "1000")); REQUIRE(test.expectedInputOutput("2.5", "2.5")); REQUIRE(test.expectedInputOutput("S0", "2.5")); REQUIRE(test.expectedInputOutput("G5", "1000")); REQUIRE(test.expectedInputOutput("g0", "2.5")); } // */ } //*/<|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkChooserPainter.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkChooserPainter.h" #include "vtkCommand.h" #include "vtkConfigure.h" #include "vtkGarbageCollector.h" #include "vtkInformation.h" #include "vtkLinesPainter.h" #include "vtkObjectFactory.h" #include "vtkPointsPainter.h" #include "vtkPolyData.h" #include "vtkPolygonsPainter.h" #include "vtkProperty.h" #include "vtkRenderer.h" #include "vtkStandardPolyDataPainter.h" #include "vtkTStripsPainter.h" vtkCxxRevisionMacro(vtkChooserPainter, "1.8"); vtkStandardNewMacro(vtkChooserPainter); vtkCxxSetObjectMacro(vtkChooserPainter, VertPainter, vtkPolyDataPainter); vtkCxxSetObjectMacro(vtkChooserPainter, LinePainter, vtkPolyDataPainter); vtkCxxSetObjectMacro(vtkChooserPainter, PolyPainter, vtkPolyDataPainter); vtkCxxSetObjectMacro(vtkChooserPainter, StripPainter, vtkPolyDataPainter); //----------------------------------------------------------------------------- vtkChooserPainter::vtkChooserPainter() { this->VertPainter = NULL; this->LinePainter = NULL; this->PolyPainter = NULL; this->StripPainter = NULL; this->LastRenderer = NULL; this->UseLinesPainterForWireframes = 0; #if defined(__APPLE__) && (defined(VTK_USE_CARBON) || defined(VTK_USE_COCOA)) /* * On some apples, glPolygonMode(*,GL_LINE) does not render anything * for polys. To fix this, we use the GL_LINE_LOOP to render the polygons. */ this->UseLinesPainterForWireframes = 1; #endif } //----------------------------------------------------------------------------- vtkChooserPainter::~vtkChooserPainter() { if (this->VertPainter) this->VertPainter->Delete(); if (this->LinePainter) this->LinePainter->Delete(); if (this->PolyPainter) this->PolyPainter->Delete(); if (this->StripPainter) this->StripPainter->Delete(); } /* //----------------------------------------------------------------------------- void vtkChooserPainter::ReleaseGraphicsResources(vtkWindow* w) { if (this->VertPainter) { this->VertPainter->ReleaseGraphicsResources(w); } if (this->LinePainter) { this->LinePainter->ReleaseGraphicsResources(w); } if (this->PolyPainter) { this->PolyPainter->ReleaseGraphicsResources(w); } if (this->StripPainter) { this->StripPainter->ReleaseGraphicsResources(w); } this->Superclass::ReleaseGraphicsResources(w); } */ //----------------------------------------------------------------------------- void vtkChooserPainter::ReportReferences(vtkGarbageCollector *collector) { this->Superclass::ReportReferences(collector); vtkGarbageCollectorReport(collector, this->VertPainter, "Vert Painter"); vtkGarbageCollectorReport(collector, this->LinePainter, "Line Painter"); vtkGarbageCollectorReport(collector, this->PolyPainter, "Poly Painter"); vtkGarbageCollectorReport(collector, this->StripPainter, "Strip Painter"); } //----------------------------------------------------------------------------- void vtkChooserPainter::PrepareForRendering(vtkRenderer* ren, vtkActor* actor) { // Ensure that the renderer chain is up-to-date. if (this->PaintersChoiceTime < this->MTime || this->PaintersChoiceTime < this->Information->GetMTime() || this->LastRenderer != ren || this->PaintersChoiceTime < this->GetInput()->GetMTime()) { this->LastRenderer = ren; // Choose the painters. this->ChoosePainters(ren, actor); // Pass them the information and poly data we have. this->UpdateChoosenPainters(); this->PaintersChoiceTime.Modified(); } this->Superclass::PrepareForRendering(ren, actor); } //----------------------------------------------------------------------------- void vtkChooserPainter::UpdateChoosenPainters() { if (this->VertPainter) { this->PassInformation(this->VertPainter); } if (this->LinePainter) { this->PassInformation(this->LinePainter); } if (this->PolyPainter) { this->PassInformation(this->PolyPainter); } if (this->StripPainter) { this->PassInformation(this->StripPainter); } } //----------------------------------------------------------------------------- void vtkChooserPainter::ChoosePainters(vtkRenderer *renderer, vtkActor* actor) { const char *vertpaintertype; const char *linepaintertype; const char *polypaintertype; const char *strippaintertype; vtkPolyDataPainter* painter; this->SelectPainters(renderer, actor, vertpaintertype, linepaintertype, polypaintertype, strippaintertype); vtkDebugMacro(<< "Selected " << vertpaintertype << ", " << linepaintertype << ", " << polypaintertype << ", " << strippaintertype); if (!this->VertPainter || !this->VertPainter->IsA(vertpaintertype)) { painter = this->CreatePainter(vertpaintertype); if (painter) { this->SetVertPainter(painter); painter->Delete(); vtkStandardPolyDataPainter* sp = vtkStandardPolyDataPainter::New(); painter->SetDelegatePainter(sp); sp->Delete(); } } if (!this->LinePainter || !this->LinePainter->IsA(linepaintertype)) { if (strcmp(vertpaintertype, linepaintertype) == 0) { this->SetLinePainter(this->VertPainter); } else { painter = this->CreatePainter(linepaintertype); if (painter) { this->SetLinePainter(painter); painter->Delete(); vtkStandardPolyDataPainter* sp = vtkStandardPolyDataPainter::New(); painter->SetDelegatePainter(sp); sp->Delete(); } } } if (!this->PolyPainter || !this->PolyPainter->IsA(polypaintertype)) { if (strcmp(vertpaintertype, polypaintertype) == 0) { this->SetPolyPainter(this->VertPainter); } else if (strcmp(linepaintertype, polypaintertype) == 0) { this->SetPolyPainter(this->LinePainter); } else { painter = this->CreatePainter(polypaintertype); if (painter) { this->SetPolyPainter(painter); painter->Delete(); vtkStandardPolyDataPainter* sp = vtkStandardPolyDataPainter::New(); painter->SetDelegatePainter(sp); sp->Delete(); } } } if (!this->StripPainter || !this->StripPainter->IsA(strippaintertype)) { if (strcmp(vertpaintertype, strippaintertype) == 0) { this->SetStripPainter(this->VertPainter); } else if (strcmp(linepaintertype, strippaintertype) == 0) { this->SetStripPainter(this->LinePainter); } else if (strcmp(polypaintertype, strippaintertype) == 0) { this->SetStripPainter(this->PolyPainter); } else { painter = this->CreatePainter(strippaintertype); if (painter) { this->SetStripPainter(painter); painter->Delete(); vtkStandardPolyDataPainter* sp = vtkStandardPolyDataPainter::New(); painter->SetDelegatePainter(sp); sp->Delete(); } } } } //----------------------------------------------------------------------------- void vtkChooserPainter::SelectPainters(vtkRenderer *vtkNotUsed(renderer), vtkActor* vtkNotUsed(actor), const char *&vertptype, const char *&lineptype, const char *&polyptype, const char *&stripptype) { vertptype = "vtkPointsPainter"; lineptype = "vtkLinesPainter"; polyptype = "vtkPolygonsPainter"; stripptype = "vtkTStripsPainter"; // No elaborate selection as yet. // Merely create the pipeline as the vtkOpenGLPolyDataMapper. } //----------------------------------------------------------------------------- vtkPolyDataPainter* vtkChooserPainter::CreatePainter(const char *paintertype) { vtkPolyDataPainter* p = 0; if (strcmp(paintertype, "vtkPointsPainter") == 0) { p = vtkPointsPainter::New(); } else if (strcmp(paintertype, "vtkLinesPainter") == 0) { p = vtkLinesPainter::New(); } else if (strcmp(paintertype, "vtkPolygonsPainter") == 0) { p = vtkPolygonsPainter::New(); } else if (strcmp(paintertype, "vtkTStripsPainter") == 0) { p = vtkTStripsPainter::New(); } else { vtkErrorMacro("Cannot create painter " << paintertype); return 0; } this->ObserverPainterProgress(p); return p; } //----------------------------------------------------------------------------- void vtkChooserPainter::RenderInternal(vtkRenderer* renderer, vtkActor* actor, unsigned long typeflags, bool forceCompileOnly) { vtkPolyData* pdInput = this->GetInputAsPolyData(); vtkIdType numVerts = pdInput->GetNumberOfVerts(); vtkIdType numLines = pdInput->GetNumberOfLines(); vtkIdType numPolys = pdInput->GetNumberOfPolys(); vtkIdType numStrips = pdInput->GetNumberOfStrips(); vtkIdType total_cells = (typeflags & vtkPainter::VERTS)? pdInput->GetNumberOfVerts() : 0; total_cells += (typeflags & vtkPainter::LINES)? pdInput->GetNumberOfLines() : 0; total_cells += (typeflags & vtkPainter::POLYS)? pdInput->GetNumberOfPolys() : 0; total_cells += (typeflags & vtkPainter::STRIPS)? pdInput->GetNumberOfStrips() : 0; if (total_cells == 0) { // nothing to render. return; } this->ProgressOffset = 0.0; this->TimeToDraw = 0.0; if ((typeflags & vtkPainter::VERTS) && numVerts>0 ) { //cout << this << "Verts" << endl; this->ProgressScaleFactor = static_cast<double>(numVerts)/total_cells; this->VertPainter->Render(renderer, actor, vtkPainter::VERTS, forceCompileOnly); this->TimeToDraw += this->VertPainter->GetTimeToDraw(); this->ProgressOffset += this->ProgressScaleFactor; } if ((typeflags & vtkPainter::LINES) && numLines>0 ) { //cout << this << "Lines" << endl; this->ProgressScaleFactor = static_cast<double>(numLines)/total_cells; this->LinePainter->Render(renderer, actor, vtkPainter::LINES, forceCompileOnly); this->TimeToDraw += this->LinePainter->GetTimeToDraw(); this->ProgressOffset += this->ProgressScaleFactor; } if ((typeflags & vtkPainter::POLYS) && numPolys>0 ) { //cout << this << "Polys" << endl; this->ProgressScaleFactor = static_cast<double>(numPolys)/total_cells; if (this->UseLinesPainterForWireframes && actor->GetProperty()->GetRepresentation() == VTK_WIREFRAME) { this->LinePainter->Render(renderer, actor, vtkPainter::POLYS, forceCompileOnly); this->TimeToDraw += this->LinePainter->GetTimeToDraw(); } else { this->PolyPainter->Render(renderer, actor, vtkPainter::POLYS, forceCompileOnly); this->TimeToDraw += this->PolyPainter->GetTimeToDraw(); } this->ProgressOffset += this->ProgressScaleFactor; } if ((typeflags & vtkPainter::STRIPS) && numStrips>0 ) { //cout << this << "Strips" << endl; this->ProgressScaleFactor = static_cast<double>(numStrips)/total_cells; this->StripPainter->Render(renderer, actor, vtkPainter::STRIPS, forceCompileOnly); this->TimeToDraw += this->StripPainter->GetTimeToDraw(); } this->Superclass::RenderInternal(renderer, actor, typeflags,forceCompileOnly); } //----------------------------------------------------------------------------- void vtkChooserPainter::PrintSelf(ostream &os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "VertPainter: " << this->VertPainter << endl; os << indent << "LinePainter: " << this->LinePainter << endl; os << indent << "PolyPainter: " << this->PolyPainter << endl; os << indent << "StripPainter: " << this->StripPainter << endl; os << indent << "UseLinesPainterForWireframes: " << this->UseLinesPainterForWireframes << endl; } <commit_msg>ENH: Ignore the UseLinesPainterForWireframes flag when culling is on. This flag is a work around for some platforms that do not properly support the GL_LINE polygon mode, but is enabled on some platforms that do support it correctly. Since the wireframe + culling will always look wrong unless using the GL_LINE polygon mode, there is no point trying to work around the problem when culling is on.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkChooserPainter.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkChooserPainter.h" #include "vtkCommand.h" #include "vtkConfigure.h" #include "vtkGarbageCollector.h" #include "vtkInformation.h" #include "vtkLinesPainter.h" #include "vtkObjectFactory.h" #include "vtkPointsPainter.h" #include "vtkPolyData.h" #include "vtkPolygonsPainter.h" #include "vtkProperty.h" #include "vtkRenderer.h" #include "vtkStandardPolyDataPainter.h" #include "vtkTStripsPainter.h" vtkCxxRevisionMacro(vtkChooserPainter, "1.9"); vtkStandardNewMacro(vtkChooserPainter); vtkCxxSetObjectMacro(vtkChooserPainter, VertPainter, vtkPolyDataPainter); vtkCxxSetObjectMacro(vtkChooserPainter, LinePainter, vtkPolyDataPainter); vtkCxxSetObjectMacro(vtkChooserPainter, PolyPainter, vtkPolyDataPainter); vtkCxxSetObjectMacro(vtkChooserPainter, StripPainter, vtkPolyDataPainter); //----------------------------------------------------------------------------- vtkChooserPainter::vtkChooserPainter() { this->VertPainter = NULL; this->LinePainter = NULL; this->PolyPainter = NULL; this->StripPainter = NULL; this->LastRenderer = NULL; this->UseLinesPainterForWireframes = 0; #if defined(__APPLE__) && (defined(VTK_USE_CARBON) || defined(VTK_USE_COCOA)) /* * On some apples, glPolygonMode(*,GL_LINE) does not render anything * for polys. To fix this, we use the GL_LINE_LOOP to render the polygons. */ this->UseLinesPainterForWireframes = 1; #endif } //----------------------------------------------------------------------------- vtkChooserPainter::~vtkChooserPainter() { if (this->VertPainter) this->VertPainter->Delete(); if (this->LinePainter) this->LinePainter->Delete(); if (this->PolyPainter) this->PolyPainter->Delete(); if (this->StripPainter) this->StripPainter->Delete(); } /* //----------------------------------------------------------------------------- void vtkChooserPainter::ReleaseGraphicsResources(vtkWindow* w) { if (this->VertPainter) { this->VertPainter->ReleaseGraphicsResources(w); } if (this->LinePainter) { this->LinePainter->ReleaseGraphicsResources(w); } if (this->PolyPainter) { this->PolyPainter->ReleaseGraphicsResources(w); } if (this->StripPainter) { this->StripPainter->ReleaseGraphicsResources(w); } this->Superclass::ReleaseGraphicsResources(w); } */ //----------------------------------------------------------------------------- void vtkChooserPainter::ReportReferences(vtkGarbageCollector *collector) { this->Superclass::ReportReferences(collector); vtkGarbageCollectorReport(collector, this->VertPainter, "Vert Painter"); vtkGarbageCollectorReport(collector, this->LinePainter, "Line Painter"); vtkGarbageCollectorReport(collector, this->PolyPainter, "Poly Painter"); vtkGarbageCollectorReport(collector, this->StripPainter, "Strip Painter"); } //----------------------------------------------------------------------------- void vtkChooserPainter::PrepareForRendering(vtkRenderer* ren, vtkActor* actor) { // Ensure that the renderer chain is up-to-date. if (this->PaintersChoiceTime < this->MTime || this->PaintersChoiceTime < this->Information->GetMTime() || this->LastRenderer != ren || this->PaintersChoiceTime < this->GetInput()->GetMTime()) { this->LastRenderer = ren; // Choose the painters. this->ChoosePainters(ren, actor); // Pass them the information and poly data we have. this->UpdateChoosenPainters(); this->PaintersChoiceTime.Modified(); } this->Superclass::PrepareForRendering(ren, actor); } //----------------------------------------------------------------------------- void vtkChooserPainter::UpdateChoosenPainters() { if (this->VertPainter) { this->PassInformation(this->VertPainter); } if (this->LinePainter) { this->PassInformation(this->LinePainter); } if (this->PolyPainter) { this->PassInformation(this->PolyPainter); } if (this->StripPainter) { this->PassInformation(this->StripPainter); } } //----------------------------------------------------------------------------- void vtkChooserPainter::ChoosePainters(vtkRenderer *renderer, vtkActor* actor) { const char *vertpaintertype; const char *linepaintertype; const char *polypaintertype; const char *strippaintertype; vtkPolyDataPainter* painter; this->SelectPainters(renderer, actor, vertpaintertype, linepaintertype, polypaintertype, strippaintertype); vtkDebugMacro(<< "Selected " << vertpaintertype << ", " << linepaintertype << ", " << polypaintertype << ", " << strippaintertype); if (!this->VertPainter || !this->VertPainter->IsA(vertpaintertype)) { painter = this->CreatePainter(vertpaintertype); if (painter) { this->SetVertPainter(painter); painter->Delete(); vtkStandardPolyDataPainter* sp = vtkStandardPolyDataPainter::New(); painter->SetDelegatePainter(sp); sp->Delete(); } } if (!this->LinePainter || !this->LinePainter->IsA(linepaintertype)) { if (strcmp(vertpaintertype, linepaintertype) == 0) { this->SetLinePainter(this->VertPainter); } else { painter = this->CreatePainter(linepaintertype); if (painter) { this->SetLinePainter(painter); painter->Delete(); vtkStandardPolyDataPainter* sp = vtkStandardPolyDataPainter::New(); painter->SetDelegatePainter(sp); sp->Delete(); } } } if (!this->PolyPainter || !this->PolyPainter->IsA(polypaintertype)) { if (strcmp(vertpaintertype, polypaintertype) == 0) { this->SetPolyPainter(this->VertPainter); } else if (strcmp(linepaintertype, polypaintertype) == 0) { this->SetPolyPainter(this->LinePainter); } else { painter = this->CreatePainter(polypaintertype); if (painter) { this->SetPolyPainter(painter); painter->Delete(); vtkStandardPolyDataPainter* sp = vtkStandardPolyDataPainter::New(); painter->SetDelegatePainter(sp); sp->Delete(); } } } if (!this->StripPainter || !this->StripPainter->IsA(strippaintertype)) { if (strcmp(vertpaintertype, strippaintertype) == 0) { this->SetStripPainter(this->VertPainter); } else if (strcmp(linepaintertype, strippaintertype) == 0) { this->SetStripPainter(this->LinePainter); } else if (strcmp(polypaintertype, strippaintertype) == 0) { this->SetStripPainter(this->PolyPainter); } else { painter = this->CreatePainter(strippaintertype); if (painter) { this->SetStripPainter(painter); painter->Delete(); vtkStandardPolyDataPainter* sp = vtkStandardPolyDataPainter::New(); painter->SetDelegatePainter(sp); sp->Delete(); } } } } //----------------------------------------------------------------------------- void vtkChooserPainter::SelectPainters(vtkRenderer *vtkNotUsed(renderer), vtkActor* vtkNotUsed(actor), const char *&vertptype, const char *&lineptype, const char *&polyptype, const char *&stripptype) { vertptype = "vtkPointsPainter"; lineptype = "vtkLinesPainter"; polyptype = "vtkPolygonsPainter"; stripptype = "vtkTStripsPainter"; // No elaborate selection as yet. // Merely create the pipeline as the vtkOpenGLPolyDataMapper. } //----------------------------------------------------------------------------- vtkPolyDataPainter* vtkChooserPainter::CreatePainter(const char *paintertype) { vtkPolyDataPainter* p = 0; if (strcmp(paintertype, "vtkPointsPainter") == 0) { p = vtkPointsPainter::New(); } else if (strcmp(paintertype, "vtkLinesPainter") == 0) { p = vtkLinesPainter::New(); } else if (strcmp(paintertype, "vtkPolygonsPainter") == 0) { p = vtkPolygonsPainter::New(); } else if (strcmp(paintertype, "vtkTStripsPainter") == 0) { p = vtkTStripsPainter::New(); } else { vtkErrorMacro("Cannot create painter " << paintertype); return 0; } this->ObserverPainterProgress(p); return p; } //----------------------------------------------------------------------------- void vtkChooserPainter::RenderInternal(vtkRenderer* renderer, vtkActor* actor, unsigned long typeflags, bool forceCompileOnly) { vtkPolyData* pdInput = this->GetInputAsPolyData(); vtkIdType numVerts = pdInput->GetNumberOfVerts(); vtkIdType numLines = pdInput->GetNumberOfLines(); vtkIdType numPolys = pdInput->GetNumberOfPolys(); vtkIdType numStrips = pdInput->GetNumberOfStrips(); vtkIdType total_cells = (typeflags & vtkPainter::VERTS)? pdInput->GetNumberOfVerts() : 0; total_cells += (typeflags & vtkPainter::LINES)? pdInput->GetNumberOfLines() : 0; total_cells += (typeflags & vtkPainter::POLYS)? pdInput->GetNumberOfPolys() : 0; total_cells += (typeflags & vtkPainter::STRIPS)? pdInput->GetNumberOfStrips() : 0; if (total_cells == 0) { // nothing to render. return; } this->ProgressOffset = 0.0; this->TimeToDraw = 0.0; if ((typeflags & vtkPainter::VERTS) && numVerts>0 ) { //cout << this << "Verts" << endl; this->ProgressScaleFactor = static_cast<double>(numVerts)/total_cells; this->VertPainter->Render(renderer, actor, vtkPainter::VERTS, forceCompileOnly); this->TimeToDraw += this->VertPainter->GetTimeToDraw(); this->ProgressOffset += this->ProgressScaleFactor; } if ((typeflags & vtkPainter::LINES) && numLines>0 ) { //cout << this << "Lines" << endl; this->ProgressScaleFactor = static_cast<double>(numLines)/total_cells; this->LinePainter->Render(renderer, actor, vtkPainter::LINES, forceCompileOnly); this->TimeToDraw += this->LinePainter->GetTimeToDraw(); this->ProgressOffset += this->ProgressScaleFactor; } if ((typeflags & vtkPainter::POLYS) && numPolys>0 ) { //cout << this << "Polys" << endl; this->ProgressScaleFactor = static_cast<double>(numPolys)/total_cells; if ( this->UseLinesPainterForWireframes && (actor->GetProperty()->GetRepresentation() == VTK_WIREFRAME) && !actor->GetProperty()->GetBackfaceCulling() && !actor->GetProperty()->GetFrontfaceCulling() ) { this->LinePainter->Render(renderer, actor, vtkPainter::POLYS, forceCompileOnly); this->TimeToDraw += this->LinePainter->GetTimeToDraw(); } else { this->PolyPainter->Render(renderer, actor, vtkPainter::POLYS, forceCompileOnly); this->TimeToDraw += this->PolyPainter->GetTimeToDraw(); } this->ProgressOffset += this->ProgressScaleFactor; } if ((typeflags & vtkPainter::STRIPS) && numStrips>0 ) { //cout << this << "Strips" << endl; this->ProgressScaleFactor = static_cast<double>(numStrips)/total_cells; this->StripPainter->Render(renderer, actor, vtkPainter::STRIPS, forceCompileOnly); this->TimeToDraw += this->StripPainter->GetTimeToDraw(); } this->Superclass::RenderInternal(renderer, actor, typeflags,forceCompileOnly); } //----------------------------------------------------------------------------- void vtkChooserPainter::PrintSelf(ostream &os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "VertPainter: " << this->VertPainter << endl; os << indent << "LinePainter: " << this->LinePainter << endl; os << indent << "PolyPainter: " << this->PolyPainter << endl; os << indent << "StripPainter: " << this->StripPainter << endl; os << indent << "UseLinesPainterForWireframes: " << this->UseLinesPainterForWireframes << endl; } <|endoftext|>
<commit_before>#include <cerrno> #include <cstring> #include <linux/input.h> #include <sys/ioctl.h> #include <fcntl.h> #include <ros/ros.h> #include <sensor_msgs/JoyFeedbackArray.h> class RumbleEventNode { public: RumbleEventNode() : rumble_fd(-1), device("/usr/input/gamepads/event_dft"), duration_sec(5.0), active(false), local_handle("~") { // Initialize internal structures memset(&rumble_effect, 0, sizeof(rumble_effect)); rumble_effect.type = FF_RUMBLE; rumble_effect.id = -1; // Will get populated by ioctl memset(&rumble_event, 0, sizeof(rumble_event)); rumble_event.type = EV_FF; rumble_event.code = -1; // Update ROS parameters local_handle.param<std::string>("device", device, device); local_handle.param<double>("duration_sec", duration_sec, duration_sec); // Setup subscribers set_rumble_sub = local_handle.subscribe("set_rumble", 10, &RumbleEventNode::setRumbleCB, this); }; ~RumbleEventNode() { termRumbleDevice(); }; bool initRumbleDevice() { rumble_fd = open(device.c_str(), O_RDWR); if (rumble_fd == -1) { ROS_ERROR_STREAM("Failed to open " << device); active = false; } else { active = true; } return active; }; void setRumbleCB(const sensor_msgs::JoyFeedbackArray::ConstPtr& msg) { if (!active) return; double strongMagnPct = 0, weakMagnPct = 0; bool update = false; for (const sensor_msgs::JoyFeedback& f: msg->array) { if (f.type == sensor_msgs::JoyFeedback::TYPE_RUMBLE) { if (f.id == 0) { strongMagnPct = f.intensity; update = true; } else if (f.id == 1) { weakMagnPct = f.intensity; update = true; } } } if (update) { setRumble(strongMagnPct, weakMagnPct, duration_sec); } }; void spin() { ros::spin(); }; protected: void termRumbleDevice() { if (rumble_fd >= 0) { issueRumbleEvent(false); // Stop previous rumble effect close(rumble_fd); rumble_fd = -1; } }; void issueRumbleEvent(bool active) { if (rumble_fd < 0 || rumble_effect.id < 0) return; rumble_event.code = rumble_effect.id; rumble_event.value = active; if (write(rumble_fd, (const void*) &rumble_event, sizeof(rumble_event)) == -1) { ROS_ERROR_STREAM("Failed to issue rumble event: " << strerror(errno)); active = false; termRumbleDevice(); return; } }; void setRumble(double strongMagnPct, double weakMagnPct, double durationSec, double delaySec=0) { if (rumble_fd < 0) return; // Cap and convert arguments strongMagnPct = std::min(std::max(strongMagnPct, 0.0), 1.0); weakMagnPct = std::min(std::max(weakMagnPct, 0.0), 1.0); durationSec = std::min(std::max(durationSec, 0.0), 65.535); delaySec = std::min(std::max(delaySec, 0.0), 65.535); unsigned short strong_magnitude = 65535*strongMagnPct; unsigned short weak_magnitude = 65535*weakMagnPct; unsigned short length = durationSec*1000; unsigned short delay = delaySec*1000; // Option A: stop existing event if (strong_magnitude == 0 && weak_magnitude == 0) { if (rumble_event.value) { issueRumbleEvent(false); } // else already stopped event, so ignore request return; } // Option B: re-issue existing event if (rumble_effect.id >= 0 && strong_magnitude == rumble_effect.u.rumble.strong_magnitude && weak_magnitude == rumble_effect.u.rumble.weak_magnitude && length == rumble_effect.replay.length && delay == rumble_effect.replay.delay) { issueRumbleEvent(false); issueRumbleEvent(true); return; } // Option C: stop and clear previous rumble effect ... if (rumble_effect.id >= 0) { issueRumbleEvent(false); if (ioctl(rumble_fd, EVIOCRMFF, rumble_effect.id) == -1) { ROS_ERROR_STREAM("Failed to clear rumble effect: " << strerror(errno)); active = false; termRumbleDevice(); return; } rumble_effect.id = -1; } // ... then upload new rumble effect... rumble_effect.u.rumble.strong_magnitude = strong_magnitude; rumble_effect.u.rumble.weak_magnitude = weak_magnitude; rumble_effect.replay.length = length; rumble_effect.replay.delay = delay; if (ioctl(rumble_fd, EVIOCSFF, &rumble_effect) == -1) { ROS_ERROR_STREAM("Failed to upload rumble effect: " << strerror(errno)); active = false; termRumbleDevice(); return; } // ... and start rumble issueRumbleEvent(true); }; int rumble_fd; struct ff_effect rumble_effect; struct input_event rumble_event; std::string device; double duration_sec; bool active; // Used to disconnect on failure ros::NodeHandle local_handle; ros::Subscriber set_rumble_sub; }; int main(int argc, char** argv) { ros::init(argc, argv, "rumble_event_node"); RumbleEventNode* n = new RumbleEventNode(); if (n->initRumbleDevice()) { n->spin(); } delete n; return EXIT_SUCCESS; }; <commit_msg>added auto-reconnect support<commit_after>#include <cerrno> #include <cstring> #include <linux/input.h> #include <sys/ioctl.h> #include <fcntl.h> #include <ros/ros.h> #include <sensor_msgs/JoyFeedbackArray.h> class RumbleEventNode { public: RumbleEventNode() : rumble_fd(-1), device("/usr/input/gamepads/event_dft"), duration_sec(5.0), active(false), reconnect(false), local_handle("~") { // Initialize internal structures memset(&rumble_effect, 0, sizeof(rumble_effect)); rumble_effect.type = FF_RUMBLE; rumble_effect.id = -1; // Will get populated by ioctl memset(&rumble_event, 0, sizeof(rumble_event)); rumble_event.type = EV_FF; rumble_event.code = -1; // Update ROS parameters local_handle.param<std::string>("device", device, device); local_handle.param<double>("duration_sec", duration_sec, duration_sec); // Setup subscribers set_rumble_sub = local_handle.subscribe("set_rumble", 10, &RumbleEventNode::setRumbleCB, this); }; ~RumbleEventNode() { termRumbleDevice(); }; bool initRumbleDevice() { rumble_fd = open(device.c_str(), O_RDWR); if (rumble_fd == -1) { if (!reconnect) { ROS_ERROR_STREAM("Failed to open " << device); } active = false; } else { active = true; reconnect = false; ROS_INFO_STREAM("Opened " << device); } return active; }; void setRumbleCB(const sensor_msgs::JoyFeedbackArray::ConstPtr& msg) { if (!active) return; double strongMagnPct = 0, weakMagnPct = 0; bool update = false; for (const sensor_msgs::JoyFeedback& f: msg->array) { if (f.type == sensor_msgs::JoyFeedback::TYPE_RUMBLE) { if (f.id == 0) { strongMagnPct = f.intensity; update = true; } else if (f.id == 1) { weakMagnPct = f.intensity; update = true; } } } if (update) { setRumble(strongMagnPct, weakMagnPct, duration_sec); } }; void spin() { ros::Rate hz(10); while (ros::ok()) { if (reconnect) { ROS_INFO_STREAM("attempt reconnect"); initRumbleDevice(); } ros::spinOnce(); hz.sleep(); } }; protected: void termRumbleDevice(bool forced=false) { if (rumble_fd >= 0) { if (!forced) { issueRumbleEvent(false); // Stop previous rumble effect } close(rumble_fd); rumble_effect.id = -1; rumble_event.code = -1; rumble_fd = -1; ROS_INFO_STREAM("Closed " << device); } active = false; if (forced) { reconnect = true; } }; void issueRumbleEvent(bool active) { if (rumble_fd < 0 || rumble_effect.id < 0) return; rumble_event.code = rumble_effect.id; rumble_event.value = active; if (write(rumble_fd, (const void*) &rumble_event, sizeof(rumble_event)) == -1) { ROS_ERROR_STREAM("Failed to issue rumble event: " << strerror(errno)); termRumbleDevice(true); return; } }; void setRumble(double strongMagnPct, double weakMagnPct, double durationSec, double delaySec=0) { if (rumble_fd < 0) return; // Cap and convert arguments strongMagnPct = std::min(std::max(strongMagnPct, 0.0), 1.0); weakMagnPct = std::min(std::max(weakMagnPct, 0.0), 1.0); durationSec = std::min(std::max(durationSec, 0.0), 65.535); delaySec = std::min(std::max(delaySec, 0.0), 65.535); unsigned short strong_magnitude = 65535*strongMagnPct; unsigned short weak_magnitude = 65535*weakMagnPct; unsigned short length = durationSec*1000; unsigned short delay = delaySec*1000; // Option A: stop existing event if (strong_magnitude == 0 && weak_magnitude == 0) { if (rumble_event.value) { issueRumbleEvent(false); } // else already stopped event, so ignore request return; } // Option B: re-issue existing event if (rumble_effect.id >= 0 && strong_magnitude == rumble_effect.u.rumble.strong_magnitude && weak_magnitude == rumble_effect.u.rumble.weak_magnitude && length == rumble_effect.replay.length && delay == rumble_effect.replay.delay) { issueRumbleEvent(false); issueRumbleEvent(true); return; } // Option C: stop and clear previous rumble effect ... if (rumble_effect.id >= 0) { issueRumbleEvent(false); if (ioctl(rumble_fd, EVIOCRMFF, rumble_effect.id) == -1) { ROS_ERROR_STREAM("Failed to clear rumble effect: " << strerror(errno)); termRumbleDevice(true); return; } rumble_effect.id = -1; } // ... then upload new rumble effect... rumble_effect.u.rumble.strong_magnitude = strong_magnitude; rumble_effect.u.rumble.weak_magnitude = weak_magnitude; rumble_effect.replay.length = length; rumble_effect.replay.delay = delay; if (ioctl(rumble_fd, EVIOCSFF, &rumble_effect) == -1) { ROS_ERROR_STREAM("Failed to upload rumble effect: " << strerror(errno)); termRumbleDevice(true); return; } // ... and start rumble issueRumbleEvent(true); }; int rumble_fd; struct ff_effect rumble_effect; struct input_event rumble_event; std::string device; double duration_sec; bool active; // Used to disconnect on failure bool reconnect; ros::NodeHandle local_handle; ros::Subscriber set_rumble_sub; }; int main(int argc, char** argv) { ros::init(argc, argv, "rumble_event_node"); RumbleEventNode* n = new RumbleEventNode(); if (n->initRumbleDevice()) { n->spin(); } delete n; return EXIT_SUCCESS; }; <|endoftext|>
<commit_before>/* * Copyright (c) 2015, 2016, Intel Corporation * * 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 Intel Corporation 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 LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include <string.h> #include "SampleRegulator.hpp" namespace geopm { SampleRegulator::SampleRegulator(const std::vector<int> &cpu_rank) : m_region_id_prev(0) { std::set<int> rank_set; for (auto it = cpu_rank.begin(); it != cpu_rank.end(); ++it) { rank_set.insert(*it); } m_num_rank = rank_set.size(); int i = 0; for (auto it = rank_set.begin(); it != rank_set.end(); ++it) { m_rank_idx_map.insert(std::pair<int, int>(*it, i)); ++i; } for (int i = 0; i < m_num_rank; ++i) { m_rank_sample_prev.emplace_back(M_INTERP_TYPE_LINEAR); // two samples are required for linear interpolation } } SampleRegulator::~SampleRegulator() { } void SampleRegulator::operator () (const struct geopm_time_s &platform_sample_time, std::vector<double>::const_iterator platform_sample_begin, std::vector<double>::const_iterator platform_sample_end, std::vector<std::pair<uint64_t, struct geopm_prof_message_s> >::const_iterator prof_sample_begin, std::vector<std::pair<uint64_t, struct geopm_prof_message_s> >::const_iterator prof_sample_end, std::vector<double> &aligned_signal) // result list per domain of control { // Insert new application profile data into buffers insert(prof_sample_begin, prof_sample_end); // Populate class member with input platform data insert(platform_sample_begin, platform_sample_end); // Extrapolate application profile data to time of platform telemetry sample align(platform_sample_time); aligned_signal = m_aligned_signal; } void SampleRegulator::insert(std::vector<std::pair<uint64_t, struct geopm_prof_message_s> >::const_iterator prof_sample_begin, std::vector<std::pair<uint64_t, struct geopm_prof_message_s> >::const_iterator prof_sample_end) { if (prof_sample_begin != prof_sample_end) { uint64_t region_id = (*prof_sample_begin).second.region_id; if (region_id != m_region_id_prev) { for (auto it = m_rank_sample_prev.begin(); it != m_rank_sample_prev.end(); ++it) { (*it).clear(); } m_region_id_prev = 0; } struct m_rank_sample_s rank_sample; for (auto it = prof_sample_begin; it != prof_sample_end; ++it) { if ((*it).second.region_id != region_id) { throw Exception("SampleRegulator::insert() regions do not match!!!", GEOPM_ERROR_LOGIC, __FILE__, __LINE__); } rank_sample.timestamp = (*it).second.timestamp; rank_sample.progress = (*it).second.progress; /// @todo: FIXME geopm_prof_message_s does not contain runtime // rank_sample.runtime = (*it).second.runtime; rank_sample.runtime = 0.0; // Dereference of find result below will // segfault with bad profile sample data size_t rank_idx = (*(m_rank_idx_map.find((*it).second.rank))).second; m_rank_sample_prev[rank_idx].insert(rank_sample); } m_region_id_prev = region_id; } } void SampleRegulator::insert(std::vector<double>::const_iterator platform_sample_begin, std::vector<double>::const_iterator platform_sample_end) { if (!m_aligned_signal.size()) { m_num_platform_signal = std::distance(platform_sample_begin, platform_sample_end); m_aligned_signal.resize(m_num_platform_signal + M_NUM_RANK_SIGNAL * m_num_rank); } std::copy(platform_sample_begin, platform_sample_end, m_aligned_signal.begin()); } void SampleRegulator::align(const struct geopm_time_s &timestamp) { int i = 0; double delta; double factor; double dsdt; double progress; double runtime; geopm_time_s timestamp_prev[2]; m_aligned_time = timestamp; for (auto it = m_rank_sample_prev.begin(); it != m_rank_sample_prev.end(); ++it) { switch((*it).size()) { case M_INTERP_TYPE_NONE: // if there is no data, set progress to zero and mark invalid by setting runtime to -1 m_aligned_signal[m_num_platform_signal + M_NUM_RANK_SIGNAL * i] = 0.0; m_aligned_signal[m_num_platform_signal + M_NUM_RANK_SIGNAL * i + 1] = -1.0; break; case M_INTERP_TYPE_NEAREST: // if there is only one sample insert it directly m_aligned_signal[m_num_platform_signal + M_NUM_RANK_SIGNAL * i] = (*it).value(0).progress; m_aligned_signal[m_num_platform_signal + M_NUM_RANK_SIGNAL * i + 1] = (*it).value(0).runtime; break; case M_INTERP_TYPE_LINEAR: // if there are two samples, extrapolate to the given timestamp timestamp_prev[0] = (*it).value(0).timestamp; timestamp_prev[1] = (*it).value(1).timestamp; delta = geopm_time_diff(timestamp_prev + 1, &timestamp); factor = 1.0 / geopm_time_diff(timestamp_prev, timestamp_prev + 1); dsdt = ((*it).value(1).progress - (*it).value(0).progress) * factor; dsdt = dsdt > 0.0 ? dsdt : 0.0; // progress and runtime are monotonically increasing if ((*it).value(0).progress == 0.0) { progress = 0.0; } else if ((*it).value(1).progress == 1.0) { progress = 1.0; } else { progress = (*it).value(1).progress + dsdt * delta; progress = progress >= 0.0 ? progress : 1e-9; progress = progress <= 1.0 ? progress : 1 - 1e-9; } m_aligned_signal[m_num_platform_signal + M_NUM_RANK_SIGNAL * i] = progress; dsdt = ((*it).value(1).runtime - (*it).value(0).runtime) * factor; runtime = (*it).value(1).runtime + dsdt * delta; m_aligned_signal[m_num_platform_signal + M_NUM_RANK_SIGNAL * i + 1] = runtime; break; default: throw Exception("SampleRegulator::align_prof() CircularBuffer has more than two values", GEOPM_ERROR_LOGIC, __FILE__, __LINE__); break; } ++i; } } } <commit_msg>Fix error that can occur when application marks regions but does not signal progress.<commit_after>/* * Copyright (c) 2015, 2016, Intel Corporation * * 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 Intel Corporation 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 LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include <string.h> #include "SampleRegulator.hpp" namespace geopm { SampleRegulator::SampleRegulator(const std::vector<int> &cpu_rank) : m_region_id_prev(0) { std::set<int> rank_set; for (auto it = cpu_rank.begin(); it != cpu_rank.end(); ++it) { rank_set.insert(*it); } m_num_rank = rank_set.size(); int i = 0; for (auto it = rank_set.begin(); it != rank_set.end(); ++it) { m_rank_idx_map.insert(std::pair<int, int>(*it, i)); ++i; } for (int i = 0; i < m_num_rank; ++i) { m_rank_sample_prev.emplace_back(M_INTERP_TYPE_LINEAR); // two samples are required for linear interpolation } } SampleRegulator::~SampleRegulator() { } void SampleRegulator::operator () (const struct geopm_time_s &platform_sample_time, std::vector<double>::const_iterator platform_sample_begin, std::vector<double>::const_iterator platform_sample_end, std::vector<std::pair<uint64_t, struct geopm_prof_message_s> >::const_iterator prof_sample_begin, std::vector<std::pair<uint64_t, struct geopm_prof_message_s> >::const_iterator prof_sample_end, std::vector<double> &aligned_signal) // result list per domain of control { // Insert new application profile data into buffers insert(prof_sample_begin, prof_sample_end); // Populate class member with input platform data insert(platform_sample_begin, platform_sample_end); // Extrapolate application profile data to time of platform telemetry sample align(platform_sample_time); aligned_signal = m_aligned_signal; } void SampleRegulator::insert(std::vector<std::pair<uint64_t, struct geopm_prof_message_s> >::const_iterator prof_sample_begin, std::vector<std::pair<uint64_t, struct geopm_prof_message_s> >::const_iterator prof_sample_end) { if (prof_sample_begin != prof_sample_end) { uint64_t region_id = (*prof_sample_begin).second.region_id; if (region_id != m_region_id_prev) { for (auto it = m_rank_sample_prev.begin(); it != m_rank_sample_prev.end(); ++it) { (*it).clear(); } m_region_id_prev = 0; } struct m_rank_sample_s rank_sample; for (auto it = prof_sample_begin; it != prof_sample_end; ++it) { if ((*it).second.region_id != region_id) { throw Exception("SampleRegulator::insert() regions do not match!!!", GEOPM_ERROR_LOGIC, __FILE__, __LINE__); } rank_sample.timestamp = (*it).second.timestamp; rank_sample.progress = (*it).second.progress; /// @todo: FIXME geopm_prof_message_s does not contain runtime // rank_sample.runtime = (*it).second.runtime; rank_sample.runtime = 0.0; // Dereference of find result below will // segfault with bad profile sample data size_t rank_idx = (*(m_rank_idx_map.find((*it).second.rank))).second; m_rank_sample_prev[rank_idx].insert(rank_sample); } m_region_id_prev = region_id; } } void SampleRegulator::insert(std::vector<double>::const_iterator platform_sample_begin, std::vector<double>::const_iterator platform_sample_end) { if (!m_aligned_signal.size()) { m_num_platform_signal = std::distance(platform_sample_begin, platform_sample_end); m_aligned_signal.resize(m_num_platform_signal + M_NUM_RANK_SIGNAL * m_num_rank); } std::copy(platform_sample_begin, platform_sample_end, m_aligned_signal.begin()); } void SampleRegulator::align(const struct geopm_time_s &timestamp) { int i = 0; double delta; double factor; double dsdt; double progress; double runtime; geopm_time_s timestamp_prev[2]; m_aligned_time = timestamp; for (auto it = m_rank_sample_prev.begin(); it != m_rank_sample_prev.end(); ++it) { switch((*it).size()) { case M_INTERP_TYPE_NONE: // if there is no data, set progress to zero and mark invalid by setting runtime to -1 m_aligned_signal[m_num_platform_signal + M_NUM_RANK_SIGNAL * i] = 0.0; m_aligned_signal[m_num_platform_signal + M_NUM_RANK_SIGNAL * i + 1] = -1.0; break; case M_INTERP_TYPE_NEAREST: // if there is only one sample insert it directly m_aligned_signal[m_num_platform_signal + M_NUM_RANK_SIGNAL * i] = (*it).value(0).progress; m_aligned_signal[m_num_platform_signal + M_NUM_RANK_SIGNAL * i + 1] = (*it).value(0).runtime; break; case M_INTERP_TYPE_LINEAR: // if there are two samples, extrapolate to the given timestamp timestamp_prev[0] = (*it).value(0).timestamp; timestamp_prev[1] = (*it).value(1).timestamp; delta = geopm_time_diff(timestamp_prev + 1, &timestamp); factor = 1.0 / geopm_time_diff(timestamp_prev, timestamp_prev + 1); dsdt = ((*it).value(1).progress - (*it).value(0).progress) * factor; dsdt = dsdt > 0.0 ? dsdt : 0.0; // progress and runtime are monotonically increasing if ((*it).value(1).progress == 1.0) { progress = 1.0; } else if ((*it).value(0).progress == 0.0) { progress = 0.0; } else { progress = (*it).value(1).progress + dsdt * delta; progress = progress >= 0.0 ? progress : 1e-9; progress = progress <= 1.0 ? progress : 1 - 1e-9; } m_aligned_signal[m_num_platform_signal + M_NUM_RANK_SIGNAL * i] = progress; dsdt = ((*it).value(1).runtime - (*it).value(0).runtime) * factor; runtime = (*it).value(1).runtime + dsdt * delta; m_aligned_signal[m_num_platform_signal + M_NUM_RANK_SIGNAL * i + 1] = runtime; break; default: throw Exception("SampleRegulator::align_prof() CircularBuffer has more than two values", GEOPM_ERROR_LOGIC, __FILE__, __LINE__); break; } ++i; } } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: AccessibleTreeNode.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 05:01:13 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SD_ACCESSIBILITY_ACCESSIBLE_BASE_HXX #define SD_ACCESSIBILITY_ACCESSIBLE_BASE_HXX #include "MutexOwner.hxx" #ifndef _CPPUHELPER_COMPBASE5_HXX_ #include <cppuhelper/compbase5.hxx> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_ #include <com/sun/star/accessibility/XAccessible.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLECONTEXT_HPP_ #include <com/sun/star/accessibility/XAccessibleContext.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLECOMPONENT_HPP_ #include <com/sun/star/accessibility/XAccessibleComponent.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEVENTBROADCASTER_HPP_ #include <com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_ #include <com/sun/star/accessibility/AccessibleRole.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_ #include <com/sun/star/accessibility/AccessibleStateType.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_ #include <com/sun/star/lang/DisposedException.hpp> #endif #ifndef _COM_SUN_STAR_AWT_XFOCUSLISTENER_HPP_ #include <com/sun/star/awt/XFocusListener.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XEVENTLISTENER_HPP_ #include <com/sun/star/document/XEventListener.hpp> #endif #include <unotools/accessiblestatesethelper.hxx> #include <tools/link.hxx> #include <rtl/ref.hxx> class VclWindowEvent; namespace sd { namespace toolpanel { class TreeNode; class TreeNodeStateChangeEvent; } } namespace utl { class AccessibleStateSetHelper; } namespace accessibility { class AccessibleSlideSorterObject; typedef ::cppu::WeakComponentImplHelper5< ::com::sun::star::accessibility::XAccessible, ::com::sun::star::accessibility::XAccessibleEventBroadcaster, ::com::sun::star::accessibility::XAccessibleContext, ::com::sun::star::accessibility::XAccessibleComponent, ::com::sun::star::lang::XServiceInfo > AccessibleTreeNodeBase; /** This class makes objects based on the sd::toolpanel::TreeNode accessible. */ class AccessibleTreeNode : public ::sd::MutexOwner, public AccessibleTreeNodeBase { public: /** Create a new object for the given tree node. The accessible parent is taken from the window returned by GetAccessibleParent() when called at the window of the node. @param rNode The TreeNode to make accessible. @param rsName The accessible name that will be returned by getAccessibleName(). @param rsDescription The accessible description that will be returned by getAccessibleDescription(). @param eRole The role that will be returned by getAccessibleRole(). */ AccessibleTreeNode( ::sd::toolpanel::TreeNode& rNode, const ::rtl::OUString& rsName, const ::rtl::OUString& rsDescription, sal_Int16 eRole); /** Use this variant of the constructor when the accessible parent is non-standard. @param rxParent The accessible parent that will be returned by getAccessibleParent() and that is used for computing relative coordinates. @param rNode The TreeNode to make accessible. @param rsName The accessible name that will be returned by getAccessibleName(). @param rsDescription The accessible description that will be returned by getAccessibleDescription(). @param eRole The role that will be returned by getAccessibleRole(). */ AccessibleTreeNode( const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> & rxParent, ::sd::toolpanel::TreeNode& rNode, const ::rtl::OUString& rsName, const ::rtl::OUString& rsDescription, sal_Int16 eRole); void FireAccessibleEvent ( short nEventId, const ::com::sun::star::uno::Any& rOldValue, const ::com::sun::star::uno::Any& rNewValue); virtual void SAL_CALL disposing (void); //===== XAccessible ======================================================= virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > SAL_CALL getAccessibleContext (void) throw (::com::sun::star::uno::RuntimeException); //===== XAccessibleEventBroadcaster ======================================= virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleEventListener >& rxListener) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleEventListener >& rxListener ) throw (::com::sun::star::uno::RuntimeException); //===== XAccessibleContext ============================================== /// Return the number of currently visible children. virtual sal_Int32 SAL_CALL getAccessibleChildCount (void) throw (::com::sun::star::uno::RuntimeException); /// Return the specified child or throw exception. virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL getAccessibleChild (sal_Int32 nIndex) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); /// Return a reference to the parent. virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL getAccessibleParent (void) throw (::com::sun::star::uno::RuntimeException); /// Return this objects index among the parents children. virtual sal_Int32 SAL_CALL getAccessibleIndexInParent (void) throw (::com::sun::star::uno::RuntimeException); /// Return this object's role. virtual sal_Int16 SAL_CALL getAccessibleRole (void) throw (::com::sun::star::uno::RuntimeException); /// Return this object's description. virtual ::rtl::OUString SAL_CALL getAccessibleDescription (void) throw (::com::sun::star::uno::RuntimeException); /// Return the object's current name. virtual ::rtl::OUString SAL_CALL getAccessibleName (void) throw (::com::sun::star::uno::RuntimeException); /// Return NULL to indicate that an empty relation set. virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleRelationSet> SAL_CALL getAccessibleRelationSet (void) throw (::com::sun::star::uno::RuntimeException); /// Return the set of current states. virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleStateSet> SAL_CALL getAccessibleStateSet (void) throw (::com::sun::star::uno::RuntimeException); /** Return the parents locale or throw exception if this object has no parent yet/anymore. */ virtual ::com::sun::star::lang::Locale SAL_CALL getLocale (void) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::accessibility::IllegalAccessibleComponentStateException); //===== XAccessibleComponent ================================================ virtual sal_Bool SAL_CALL containsPoint ( const ::com::sun::star::awt::Point& aPoint) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleAtPoint ( const ::com::sun::star::awt::Point& aPoint) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::awt::Rectangle SAL_CALL getBounds (void) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::awt::Point SAL_CALL getLocation (void) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::awt::Point SAL_CALL getLocationOnScreen (void) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::awt::Size SAL_CALL getSize (void) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL grabFocus (void) throw (::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getForeground (void) throw (::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getBackground (void) throw (::com::sun::star::uno::RuntimeException); //===== XServiceInfo ==================================================== /** Returns an identifier for the implementation of this object. */ virtual ::rtl::OUString SAL_CALL getImplementationName (void) throw (::com::sun::star::uno::RuntimeException); /** Return whether the specified service is supported by this class. */ virtual sal_Bool SAL_CALL supportsService (const ::rtl::OUString& sServiceName) throw (::com::sun::star::uno::RuntimeException); /** Returns a list of all supported services. */ virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL getSupportedServiceNames (void) throw (::com::sun::star::uno::RuntimeException); protected: ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> mxParent; ::sd::toolpanel::TreeNode& mrTreeNode; ::rtl::Reference< ::utl::AccessibleStateSetHelper> mrStateSet; const ::rtl::OUString msName; const ::rtl::OUString msDescription; const sal_Int16 meRole; virtual ~AccessibleTreeNode (void); /** Check whether or not the object has been disposed (or is in the state of beeing disposed). If that is the case then DisposedException is thrown to inform the (indirect) caller of the foul deed. */ void ThrowIfDisposed (void) throw (::com::sun::star::lang::DisposedException); /** Check whether or not the object has been disposed (or is in the state of beeing disposed). @return sal_True, if the object is disposed or in the course of being disposed. Otherwise, sal_False is returned. */ sal_Bool IsDisposed (void); /** Update the mpStateSet member to reflect the current state of the TreeNode. When one of the states has changed since the last call then an appropriate event is sent. */ virtual void UpdateStateSet (void); /** Update a single state and sent an event if its value changes. */ void UpdateState( sal_Int16 aState, bool bValue); DECL_LINK(StateChangeListener, ::sd::toolpanel::TreeNodeStateChangeEvent*); DECL_LINK(WindowEventListener, VclWindowEvent*); private: sal_uInt32 mnClientId; /// The common part of the constructor. void CommonConstructor (void); }; } // end of namespace ::accessibility #endif <commit_msg>INTEGRATION: CWS sdwarningsbegone (1.3.316); FILE MERGED 2006/11/22 12:41:59 cl 1.3.316.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: AccessibleTreeNode.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2006-12-12 17:31:23 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SD_ACCESSIBILITY_ACCESSIBLE_BASE_HXX #define SD_ACCESSIBILITY_ACCESSIBLE_BASE_HXX #include "MutexOwner.hxx" #ifndef _CPPUHELPER_COMPBASE5_HXX_ #include <cppuhelper/compbase5.hxx> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_ #include <com/sun/star/accessibility/XAccessible.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLECONTEXT_HPP_ #include <com/sun/star/accessibility/XAccessibleContext.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLECOMPONENT_HPP_ #include <com/sun/star/accessibility/XAccessibleComponent.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEVENTBROADCASTER_HPP_ #include <com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_ #include <com/sun/star/accessibility/AccessibleRole.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_ #include <com/sun/star/accessibility/AccessibleStateType.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_ #include <com/sun/star/lang/DisposedException.hpp> #endif #ifndef _COM_SUN_STAR_AWT_XFOCUSLISTENER_HPP_ #include <com/sun/star/awt/XFocusListener.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XEVENTLISTENER_HPP_ #include <com/sun/star/document/XEventListener.hpp> #endif #include <unotools/accessiblestatesethelper.hxx> #include <tools/link.hxx> #include <rtl/ref.hxx> class VclWindowEvent; namespace sd { namespace toolpanel { class TreeNode; class TreeNodeStateChangeEvent; } } namespace utl { class AccessibleStateSetHelper; } namespace accessibility { class AccessibleSlideSorterObject; typedef ::cppu::WeakComponentImplHelper5< ::com::sun::star::accessibility::XAccessible, ::com::sun::star::accessibility::XAccessibleEventBroadcaster, ::com::sun::star::accessibility::XAccessibleContext, ::com::sun::star::accessibility::XAccessibleComponent, ::com::sun::star::lang::XServiceInfo > AccessibleTreeNodeBase; /** This class makes objects based on the sd::toolpanel::TreeNode accessible. */ class AccessibleTreeNode : public ::sd::MutexOwner, public AccessibleTreeNodeBase { public: /** Create a new object for the given tree node. The accessible parent is taken from the window returned by GetAccessibleParent() when called at the window of the node. @param rNode The TreeNode to make accessible. @param rsName The accessible name that will be returned by getAccessibleName(). @param rsDescription The accessible description that will be returned by getAccessibleDescription(). @param eRole The role that will be returned by getAccessibleRole(). */ AccessibleTreeNode( ::sd::toolpanel::TreeNode& rNode, const ::rtl::OUString& rsName, const ::rtl::OUString& rsDescription, sal_Int16 eRole); /** Use this variant of the constructor when the accessible parent is non-standard. @param rxParent The accessible parent that will be returned by getAccessibleParent() and that is used for computing relative coordinates. @param rNode The TreeNode to make accessible. @param rsName The accessible name that will be returned by getAccessibleName(). @param rsDescription The accessible description that will be returned by getAccessibleDescription(). @param eRole The role that will be returned by getAccessibleRole(). */ AccessibleTreeNode( const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> & rxParent, ::sd::toolpanel::TreeNode& rNode, const ::rtl::OUString& rsName, const ::rtl::OUString& rsDescription, sal_Int16 eRole); void FireAccessibleEvent ( short nEventId, const ::com::sun::star::uno::Any& rOldValue, const ::com::sun::star::uno::Any& rNewValue); virtual void SAL_CALL disposing (void); //===== XAccessible ======================================================= virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > SAL_CALL getAccessibleContext (void) throw (::com::sun::star::uno::RuntimeException); //===== XAccessibleEventBroadcaster ======================================= virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleEventListener >& rxListener) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleEventListener >& rxListener ) throw (::com::sun::star::uno::RuntimeException); using cppu::WeakComponentImplHelperBase::addEventListener; using cppu::WeakComponentImplHelperBase::removeEventListener; //===== XAccessibleContext ============================================== /// Return the number of currently visible children. virtual sal_Int32 SAL_CALL getAccessibleChildCount (void) throw (::com::sun::star::uno::RuntimeException); /// Return the specified child or throw exception. virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL getAccessibleChild (sal_Int32 nIndex) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); /// Return a reference to the parent. virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL getAccessibleParent (void) throw (::com::sun::star::uno::RuntimeException); /// Return this objects index among the parents children. virtual sal_Int32 SAL_CALL getAccessibleIndexInParent (void) throw (::com::sun::star::uno::RuntimeException); /// Return this object's role. virtual sal_Int16 SAL_CALL getAccessibleRole (void) throw (::com::sun::star::uno::RuntimeException); /// Return this object's description. virtual ::rtl::OUString SAL_CALL getAccessibleDescription (void) throw (::com::sun::star::uno::RuntimeException); /// Return the object's current name. virtual ::rtl::OUString SAL_CALL getAccessibleName (void) throw (::com::sun::star::uno::RuntimeException); /// Return NULL to indicate that an empty relation set. virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleRelationSet> SAL_CALL getAccessibleRelationSet (void) throw (::com::sun::star::uno::RuntimeException); /// Return the set of current states. virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleStateSet> SAL_CALL getAccessibleStateSet (void) throw (::com::sun::star::uno::RuntimeException); /** Return the parents locale or throw exception if this object has no parent yet/anymore. */ virtual ::com::sun::star::lang::Locale SAL_CALL getLocale (void) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::accessibility::IllegalAccessibleComponentStateException); //===== XAccessibleComponent ================================================ virtual sal_Bool SAL_CALL containsPoint ( const ::com::sun::star::awt::Point& aPoint) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleAtPoint ( const ::com::sun::star::awt::Point& aPoint) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::awt::Rectangle SAL_CALL getBounds (void) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::awt::Point SAL_CALL getLocation (void) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::awt::Point SAL_CALL getLocationOnScreen (void) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::awt::Size SAL_CALL getSize (void) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL grabFocus (void) throw (::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getForeground (void) throw (::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getBackground (void) throw (::com::sun::star::uno::RuntimeException); //===== XServiceInfo ==================================================== /** Returns an identifier for the implementation of this object. */ virtual ::rtl::OUString SAL_CALL getImplementationName (void) throw (::com::sun::star::uno::RuntimeException); /** Return whether the specified service is supported by this class. */ virtual sal_Bool SAL_CALL supportsService (const ::rtl::OUString& sServiceName) throw (::com::sun::star::uno::RuntimeException); /** Returns a list of all supported services. */ virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL getSupportedServiceNames (void) throw (::com::sun::star::uno::RuntimeException); protected: ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> mxParent; ::sd::toolpanel::TreeNode& mrTreeNode; ::rtl::Reference< ::utl::AccessibleStateSetHelper> mrStateSet; const ::rtl::OUString msName; const ::rtl::OUString msDescription; const sal_Int16 meRole; virtual ~AccessibleTreeNode (void); /** Check whether or not the object has been disposed (or is in the state of beeing disposed). If that is the case then DisposedException is thrown to inform the (indirect) caller of the foul deed. */ void ThrowIfDisposed (void) throw (::com::sun::star::lang::DisposedException); /** Check whether or not the object has been disposed (or is in the state of beeing disposed). @return sal_True, if the object is disposed or in the course of being disposed. Otherwise, sal_False is returned. */ sal_Bool IsDisposed (void); /** Update the mpStateSet member to reflect the current state of the TreeNode. When one of the states has changed since the last call then an appropriate event is sent. */ virtual void UpdateStateSet (void); /** Update a single state and sent an event if its value changes. */ void UpdateState( sal_Int16 aState, bool bValue); DECL_LINK(StateChangeListener, ::sd::toolpanel::TreeNodeStateChangeEvent*); DECL_LINK(WindowEventListener, VclWindowEvent*); private: sal_uInt32 mnClientId; /// The common part of the constructor. void CommonConstructor (void); }; } // end of namespace ::accessibility #endif <|endoftext|>
<commit_before>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #include "perf_precomp.hpp" using namespace std; using namespace testing; using namespace perf; ////////////////////////////////////////////////////////////////////// // Blur DEF_PARAM_TEST(Sz_Type_KernelSz, cv::Size, MatType, int); PERF_TEST_P(Sz_Type_KernelSz, Filters_Blur, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4), Values(3, 5, 7))) { declare.time(20.0); const cv::Size size = GET_PARAM(0); const int type = GET_PARAM(1); const int ksize = GET_PARAM(2); cv::Mat src(size, type); declare.in(src, WARMUP_RNG); if (PERF_RUN_GPU()) { const cv::gpu::GpuMat d_src(src); cv::gpu::GpuMat dst; TEST_CYCLE() cv::gpu::blur(d_src, dst, cv::Size(ksize, ksize)); GPU_SANITY_CHECK(dst); } else { cv::Mat dst; TEST_CYCLE() cv::blur(src, dst, cv::Size(ksize, ksize)); CPU_SANITY_CHECK(dst); } } ////////////////////////////////////////////////////////////////////// // Sobel PERF_TEST_P(Sz_Type_KernelSz, Filters_Sobel, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4, CV_32FC1), Values(3, 5, 7, 9, 11, 13, 15))) { declare.time(20.0); const cv::Size size = GET_PARAM(0); const int type = GET_PARAM(1); const int ksize = GET_PARAM(2); cv::Mat src(size, type); declare.in(src, WARMUP_RNG); if (PERF_RUN_GPU()) { const cv::gpu::GpuMat d_src(src); cv::gpu::GpuMat dst; cv::gpu::GpuMat d_buf; TEST_CYCLE() cv::gpu::Sobel(d_src, dst, -1, 1, 1, d_buf, ksize); GPU_SANITY_CHECK(dst); } else { cv::Mat dst; TEST_CYCLE() cv::Sobel(src, dst, -1, 1, 1, ksize); CPU_SANITY_CHECK(dst); } } ////////////////////////////////////////////////////////////////////// // Scharr PERF_TEST_P(Sz_Type, Filters_Scharr, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4, CV_32FC1))) { declare.time(20.0); const cv::Size size = GET_PARAM(0); const int type = GET_PARAM(1); cv::Mat src(size, type); declare.in(src, WARMUP_RNG); if (PERF_RUN_GPU()) { const cv::gpu::GpuMat d_src(src); cv::gpu::GpuMat dst; cv::gpu::GpuMat d_buf; TEST_CYCLE() cv::gpu::Scharr(d_src, dst, -1, 1, 0, d_buf); GPU_SANITY_CHECK(dst); } else { cv::Mat dst; TEST_CYCLE() cv::Scharr(src, dst, -1, 1, 0); CPU_SANITY_CHECK(dst); } } ////////////////////////////////////////////////////////////////////// // GaussianBlur PERF_TEST_P(Sz_Type_KernelSz, Filters_GaussianBlur, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4, CV_32FC1), Values(3, 5, 7, 9, 11, 13, 15))) { declare.time(20.0); const cv::Size size = GET_PARAM(0); const int type = GET_PARAM(1); const int ksize = GET_PARAM(2); cv::Mat src(size, type); declare.in(src, WARMUP_RNG); if (PERF_RUN_GPU()) { const cv::gpu::GpuMat d_src(src); cv::gpu::GpuMat dst; cv::gpu::GpuMat d_buf; TEST_CYCLE() cv::gpu::GaussianBlur(d_src, dst, cv::Size(ksize, ksize), d_buf, 0.5); GPU_SANITY_CHECK(dst); } else { cv::Mat dst; TEST_CYCLE() cv::GaussianBlur(src, dst, cv::Size(ksize, ksize), 0.5); CPU_SANITY_CHECK(dst); } } ////////////////////////////////////////////////////////////////////// // Laplacian PERF_TEST_P(Sz_Type_KernelSz, Filters_Laplacian, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4, CV_32FC1, CV_32FC4), Values(1, 3))) { declare.time(20.0); const cv::Size size = GET_PARAM(0); const int type = GET_PARAM(1); const int ksize = GET_PARAM(2); cv::Mat src(size, type); declare.in(src, WARMUP_RNG); if (PERF_RUN_GPU()) { const cv::gpu::GpuMat d_src(src); cv::gpu::GpuMat dst; TEST_CYCLE() cv::gpu::Laplacian(d_src, dst, -1, ksize); GPU_SANITY_CHECK(dst); } else { cv::Mat dst; TEST_CYCLE() cv::Laplacian(src, dst, -1, ksize); CPU_SANITY_CHECK(dst); } } ////////////////////////////////////////////////////////////////////// // Erode PERF_TEST_P(Sz_Type, Filters_Erode, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4))) { declare.time(20.0); const cv::Size size = GET_PARAM(0); const int type = GET_PARAM(1); cv::Mat src(size, type); declare.in(src, WARMUP_RNG); const cv::Mat ker = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3)); if (PERF_RUN_GPU()) { const cv::gpu::GpuMat d_src(src); cv::gpu::GpuMat dst; cv::gpu::GpuMat d_buf; TEST_CYCLE() cv::gpu::erode(d_src, dst, ker, d_buf); GPU_SANITY_CHECK(dst); } else { cv::Mat dst; TEST_CYCLE() cv::erode(src, dst, ker); CPU_SANITY_CHECK(dst); } } ////////////////////////////////////////////////////////////////////// // Dilate PERF_TEST_P(Sz_Type, Filters_Dilate, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4))) { declare.time(20.0); const cv::Size size = GET_PARAM(0); const int type = GET_PARAM(1); cv::Mat src(size, type); declare.in(src, WARMUP_RNG); const cv::Mat ker = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3)); if (PERF_RUN_GPU()) { const cv::gpu::GpuMat d_src(src); cv::gpu::GpuMat dst; cv::gpu::GpuMat d_buf; TEST_CYCLE() cv::gpu::dilate(d_src, dst, ker, d_buf); GPU_SANITY_CHECK(dst); } else { cv::Mat dst; TEST_CYCLE() cv::dilate(src, dst, ker); CPU_SANITY_CHECK(dst); } } ////////////////////////////////////////////////////////////////////// // MorphologyEx CV_ENUM(MorphOp, MORPH_OPEN, MORPH_CLOSE, MORPH_GRADIENT, MORPH_TOPHAT, MORPH_BLACKHAT) DEF_PARAM_TEST(Sz_Type_Op, cv::Size, MatType, MorphOp); PERF_TEST_P(Sz_Type_Op, Filters_MorphologyEx, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4), MorphOp::all())) { declare.time(20.0); const cv::Size size = GET_PARAM(0); const int type = GET_PARAM(1); const int morphOp = GET_PARAM(2); cv::Mat src(size, type); declare.in(src, WARMUP_RNG); const cv::Mat ker = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3)); if (PERF_RUN_GPU()) { const cv::gpu::GpuMat d_src(src); cv::gpu::GpuMat dst; cv::gpu::GpuMat d_buf1; cv::gpu::GpuMat d_buf2; TEST_CYCLE() cv::gpu::morphologyEx(d_src, dst, morphOp, ker, d_buf1, d_buf2); GPU_SANITY_CHECK(dst); } else { cv::Mat dst; TEST_CYCLE() cv::morphologyEx(src, dst, morphOp, ker); CPU_SANITY_CHECK(dst); } } ////////////////////////////////////////////////////////////////////// // Filter2D PERF_TEST_P(Sz_Type_KernelSz, Filters_Filter2D, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4, CV_32FC1, CV_32FC4), Values(3, 5, 7, 9, 11, 13, 15))) { declare.time(20.0); const cv::Size size = GET_PARAM(0); const int type = GET_PARAM(1); const int ksize = GET_PARAM(2); cv::Mat src(size, type); declare.in(src, WARMUP_RNG); cv::Mat kernel(ksize, ksize, CV_32FC1); declare.in(kernel, WARMUP_RNG); if (PERF_RUN_GPU()) { const cv::gpu::GpuMat d_src(src); cv::gpu::GpuMat dst; TEST_CYCLE() cv::gpu::filter2D(d_src, dst, -1, kernel); GPU_SANITY_CHECK(dst); } else { cv::Mat dst; TEST_CYCLE() cv::filter2D(src, dst, -1, kernel); CPU_SANITY_CHECK(dst); } } <commit_msg>fixed BoxFilter sanity test (different rounding results)<commit_after>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #include "perf_precomp.hpp" using namespace std; using namespace testing; using namespace perf; ////////////////////////////////////////////////////////////////////// // Blur DEF_PARAM_TEST(Sz_Type_KernelSz, cv::Size, MatType, int); PERF_TEST_P(Sz_Type_KernelSz, Filters_Blur, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4), Values(3, 5, 7))) { declare.time(20.0); const cv::Size size = GET_PARAM(0); const int type = GET_PARAM(1); const int ksize = GET_PARAM(2); cv::Mat src(size, type); declare.in(src, WARMUP_RNG); if (PERF_RUN_GPU()) { const cv::gpu::GpuMat d_src(src); cv::gpu::GpuMat dst; TEST_CYCLE() cv::gpu::blur(d_src, dst, cv::Size(ksize, ksize)); GPU_SANITY_CHECK(dst, 1); } else { cv::Mat dst; TEST_CYCLE() cv::blur(src, dst, cv::Size(ksize, ksize)); CPU_SANITY_CHECK(dst); } } ////////////////////////////////////////////////////////////////////// // Sobel PERF_TEST_P(Sz_Type_KernelSz, Filters_Sobel, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4, CV_32FC1), Values(3, 5, 7, 9, 11, 13, 15))) { declare.time(20.0); const cv::Size size = GET_PARAM(0); const int type = GET_PARAM(1); const int ksize = GET_PARAM(2); cv::Mat src(size, type); declare.in(src, WARMUP_RNG); if (PERF_RUN_GPU()) { const cv::gpu::GpuMat d_src(src); cv::gpu::GpuMat dst; cv::gpu::GpuMat d_buf; TEST_CYCLE() cv::gpu::Sobel(d_src, dst, -1, 1, 1, d_buf, ksize); GPU_SANITY_CHECK(dst); } else { cv::Mat dst; TEST_CYCLE() cv::Sobel(src, dst, -1, 1, 1, ksize); CPU_SANITY_CHECK(dst); } } ////////////////////////////////////////////////////////////////////// // Scharr PERF_TEST_P(Sz_Type, Filters_Scharr, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4, CV_32FC1))) { declare.time(20.0); const cv::Size size = GET_PARAM(0); const int type = GET_PARAM(1); cv::Mat src(size, type); declare.in(src, WARMUP_RNG); if (PERF_RUN_GPU()) { const cv::gpu::GpuMat d_src(src); cv::gpu::GpuMat dst; cv::gpu::GpuMat d_buf; TEST_CYCLE() cv::gpu::Scharr(d_src, dst, -1, 1, 0, d_buf); GPU_SANITY_CHECK(dst); } else { cv::Mat dst; TEST_CYCLE() cv::Scharr(src, dst, -1, 1, 0); CPU_SANITY_CHECK(dst); } } ////////////////////////////////////////////////////////////////////// // GaussianBlur PERF_TEST_P(Sz_Type_KernelSz, Filters_GaussianBlur, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4, CV_32FC1), Values(3, 5, 7, 9, 11, 13, 15))) { declare.time(20.0); const cv::Size size = GET_PARAM(0); const int type = GET_PARAM(1); const int ksize = GET_PARAM(2); cv::Mat src(size, type); declare.in(src, WARMUP_RNG); if (PERF_RUN_GPU()) { const cv::gpu::GpuMat d_src(src); cv::gpu::GpuMat dst; cv::gpu::GpuMat d_buf; TEST_CYCLE() cv::gpu::GaussianBlur(d_src, dst, cv::Size(ksize, ksize), d_buf, 0.5); GPU_SANITY_CHECK(dst); } else { cv::Mat dst; TEST_CYCLE() cv::GaussianBlur(src, dst, cv::Size(ksize, ksize), 0.5); CPU_SANITY_CHECK(dst); } } ////////////////////////////////////////////////////////////////////// // Laplacian PERF_TEST_P(Sz_Type_KernelSz, Filters_Laplacian, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4, CV_32FC1, CV_32FC4), Values(1, 3))) { declare.time(20.0); const cv::Size size = GET_PARAM(0); const int type = GET_PARAM(1); const int ksize = GET_PARAM(2); cv::Mat src(size, type); declare.in(src, WARMUP_RNG); if (PERF_RUN_GPU()) { const cv::gpu::GpuMat d_src(src); cv::gpu::GpuMat dst; TEST_CYCLE() cv::gpu::Laplacian(d_src, dst, -1, ksize); GPU_SANITY_CHECK(dst); } else { cv::Mat dst; TEST_CYCLE() cv::Laplacian(src, dst, -1, ksize); CPU_SANITY_CHECK(dst); } } ////////////////////////////////////////////////////////////////////// // Erode PERF_TEST_P(Sz_Type, Filters_Erode, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4))) { declare.time(20.0); const cv::Size size = GET_PARAM(0); const int type = GET_PARAM(1); cv::Mat src(size, type); declare.in(src, WARMUP_RNG); const cv::Mat ker = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3)); if (PERF_RUN_GPU()) { const cv::gpu::GpuMat d_src(src); cv::gpu::GpuMat dst; cv::gpu::GpuMat d_buf; TEST_CYCLE() cv::gpu::erode(d_src, dst, ker, d_buf); GPU_SANITY_CHECK(dst); } else { cv::Mat dst; TEST_CYCLE() cv::erode(src, dst, ker); CPU_SANITY_CHECK(dst); } } ////////////////////////////////////////////////////////////////////// // Dilate PERF_TEST_P(Sz_Type, Filters_Dilate, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4))) { declare.time(20.0); const cv::Size size = GET_PARAM(0); const int type = GET_PARAM(1); cv::Mat src(size, type); declare.in(src, WARMUP_RNG); const cv::Mat ker = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3)); if (PERF_RUN_GPU()) { const cv::gpu::GpuMat d_src(src); cv::gpu::GpuMat dst; cv::gpu::GpuMat d_buf; TEST_CYCLE() cv::gpu::dilate(d_src, dst, ker, d_buf); GPU_SANITY_CHECK(dst); } else { cv::Mat dst; TEST_CYCLE() cv::dilate(src, dst, ker); CPU_SANITY_CHECK(dst); } } ////////////////////////////////////////////////////////////////////// // MorphologyEx CV_ENUM(MorphOp, MORPH_OPEN, MORPH_CLOSE, MORPH_GRADIENT, MORPH_TOPHAT, MORPH_BLACKHAT) DEF_PARAM_TEST(Sz_Type_Op, cv::Size, MatType, MorphOp); PERF_TEST_P(Sz_Type_Op, Filters_MorphologyEx, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4), MorphOp::all())) { declare.time(20.0); const cv::Size size = GET_PARAM(0); const int type = GET_PARAM(1); const int morphOp = GET_PARAM(2); cv::Mat src(size, type); declare.in(src, WARMUP_RNG); const cv::Mat ker = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3)); if (PERF_RUN_GPU()) { const cv::gpu::GpuMat d_src(src); cv::gpu::GpuMat dst; cv::gpu::GpuMat d_buf1; cv::gpu::GpuMat d_buf2; TEST_CYCLE() cv::gpu::morphologyEx(d_src, dst, morphOp, ker, d_buf1, d_buf2); GPU_SANITY_CHECK(dst); } else { cv::Mat dst; TEST_CYCLE() cv::morphologyEx(src, dst, morphOp, ker); CPU_SANITY_CHECK(dst); } } ////////////////////////////////////////////////////////////////////// // Filter2D PERF_TEST_P(Sz_Type_KernelSz, Filters_Filter2D, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4, CV_32FC1, CV_32FC4), Values(3, 5, 7, 9, 11, 13, 15))) { declare.time(20.0); const cv::Size size = GET_PARAM(0); const int type = GET_PARAM(1); const int ksize = GET_PARAM(2); cv::Mat src(size, type); declare.in(src, WARMUP_RNG); cv::Mat kernel(ksize, ksize, CV_32FC1); declare.in(kernel, WARMUP_RNG); if (PERF_RUN_GPU()) { const cv::gpu::GpuMat d_src(src); cv::gpu::GpuMat dst; TEST_CYCLE() cv::gpu::filter2D(d_src, dst, -1, kernel); GPU_SANITY_CHECK(dst); } else { cv::Mat dst; TEST_CYCLE() cv::filter2D(src, dst, -1, kernel); CPU_SANITY_CHECK(dst); } } <|endoftext|>
<commit_before>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #include "precomp.hpp" #include "grfmt_hdr.hpp" #include "rgbe.hpp" namespace cv { HdrDecoder::HdrDecoder() { m_signature = "#?RGBE"; m_signature_alt = "#?RADIANCE"; file = NULL; m_type = CV_32FC3; } HdrDecoder::~HdrDecoder() { } size_t HdrDecoder::signatureLength() const { return m_signature.size() > m_signature_alt.size() ? m_signature.size() : m_signature_alt.size(); } bool HdrDecoder::readHeader() { file = fopen(m_filename.c_str(), "rb"); if(!file) { return false; } RGBE_ReadHeader(file, &m_width, &m_height, NULL); if(m_width <= 0 || m_height <= 0) { fclose(file); file = NULL; return false; } return true; } bool HdrDecoder::readData(Mat& _img) { Mat img(m_height, m_width, CV_32FC3); if(!file) { if(!readHeader()) { return false; } } RGBE_ReadPixels_RLE(file, const_cast<float*>(img.ptr<float>()), img.cols, img.rows); fclose(file); file = NULL; if(_img.depth() == img.depth()) { img.convertTo(_img, _img.type()); } else { img.convertTo(_img, _img.type(), 255); } return true; } bool HdrDecoder::checkSignature( const String& signature ) const { if(signature.size() >= m_signature.size() && (!memcmp(signature.c_str(), m_signature.c_str(), m_signature.size()) || !memcmp(signature.c_str(), m_signature_alt.c_str(), m_signature_alt.size()))) return true; return false; } ImageDecoder HdrDecoder::newDecoder() const { return new HdrDecoder; } HdrEncoder::HdrEncoder() { m_description = "Radiance HDR (*.hdr;*.pic)"; } HdrEncoder::~HdrEncoder() { } bool HdrEncoder::write( const Mat& _img, const std::vector<int>& params ) { Mat img; CV_Assert(img.channels() == 3 || img.channels() == 1); if(img.channels() == 1) { std::vector<Mat> splitted(3, _img); merge(splitted, img); } else { _img.copyTo(img); } if(img.depth() != CV_32F) { img.convertTo(img, CV_32FC3, 1/255.0f); } CV_Assert(params.empty() || params[0] == HDR_NONE || params[0] == HDR_RLE); FILE *fout = fopen(m_filename.c_str(), "wb"); if(!fout) { return false; } RGBE_WriteHeader(fout, img.cols, img.rows, NULL); if(params.empty() || params[0] == HDR_RLE) { RGBE_WritePixels_RLE(fout, const_cast<float*>(img.ptr<float>()), img.cols, img.rows); } else { RGBE_WritePixels(fout, const_cast<float*>(img.ptr<float>()), img.cols * img.rows); } fclose(fout); return true; } ImageEncoder HdrEncoder::newEncoder() const { return new HdrEncoder; } bool HdrEncoder::isFormatSupported( int depth ) const { return depth != CV_64F; } } <commit_msg>HDR writing bug fix<commit_after>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #include "precomp.hpp" #include "grfmt_hdr.hpp" #include "rgbe.hpp" namespace cv { HdrDecoder::HdrDecoder() { m_signature = "#?RGBE"; m_signature_alt = "#?RADIANCE"; file = NULL; m_type = CV_32FC3; } HdrDecoder::~HdrDecoder() { } size_t HdrDecoder::signatureLength() const { return m_signature.size() > m_signature_alt.size() ? m_signature.size() : m_signature_alt.size(); } bool HdrDecoder::readHeader() { file = fopen(m_filename.c_str(), "rb"); if(!file) { return false; } RGBE_ReadHeader(file, &m_width, &m_height, NULL); if(m_width <= 0 || m_height <= 0) { fclose(file); file = NULL; return false; } return true; } bool HdrDecoder::readData(Mat& _img) { Mat img(m_height, m_width, CV_32FC3); if(!file) { if(!readHeader()) { return false; } } RGBE_ReadPixels_RLE(file, const_cast<float*>(img.ptr<float>()), img.cols, img.rows); fclose(file); file = NULL; if(_img.depth() == img.depth()) { img.convertTo(_img, _img.type()); } else { img.convertTo(_img, _img.type(), 255); } return true; } bool HdrDecoder::checkSignature( const String& signature ) const { if(signature.size() >= m_signature.size() && (!memcmp(signature.c_str(), m_signature.c_str(), m_signature.size()) || !memcmp(signature.c_str(), m_signature_alt.c_str(), m_signature_alt.size()))) return true; return false; } ImageDecoder HdrDecoder::newDecoder() const { return new HdrDecoder; } HdrEncoder::HdrEncoder() { m_description = "Radiance HDR (*.hdr;*.pic)"; } HdrEncoder::~HdrEncoder() { } bool HdrEncoder::write( const Mat& input_img, const std::vector<int>& params ) { Mat img; CV_Assert(input_img.channels() == 3 || input_img.channels() == 1); if(input_img.channels() == 1) { std::vector<Mat> splitted(3, input_img); merge(splitted, img); } else { input_img.copyTo(img); } if(img.depth() != CV_32F) { img.convertTo(img, CV_32FC3, 1/255.0f); } CV_Assert(params.empty() || params[0] == HDR_NONE || params[0] == HDR_RLE); FILE *fout = fopen(m_filename.c_str(), "wb"); if(!fout) { return false; } RGBE_WriteHeader(fout, img.cols, img.rows, NULL); if(params.empty() || params[0] == HDR_RLE) { RGBE_WritePixels_RLE(fout, const_cast<float*>(img.ptr<float>()), img.cols, img.rows); } else { RGBE_WritePixels(fout, const_cast<float*>(img.ptr<float>()), img.cols * img.rows); } fclose(fout); return true; } ImageEncoder HdrEncoder::newEncoder() const { return new HdrEncoder; } bool HdrEncoder::isFormatSupported( int depth ) const { return depth != CV_64F; } } <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2015-2017 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. 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. * * 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. * *********************************************************************************/ #include "shaderwidget.h" #include <modules/opengl/shader/shaderobject.h> #include <modules/opengl/shader/shaderresource.h> #include <modules/opengl/shader/shadermanager.h> #include <modules/qtwidgets/properties/syntaxhighlighter.h> #include <modules/qtwidgets/inviwoqtutils.h> #include <inviwo/core/util/filesystem.h> #include <warn/push> #include <warn/ignore/all> #include <QTextEdit> #include <QDialog> #include <QToolBar> #include <QMainWindow> #include <QMenuBar> #include <QGridLayout> #include <QCheckBox> #include <QHBoxLayout> #include <QCloseEvent> #include <warn/pop> namespace inviwo { ShaderWidget::ShaderWidget(const ShaderObject* obj, QWidget* parent) : InviwoDockWidget(utilqt::toQString(obj->getFileName()), parent, "ShaderEditorWidget") , obj_(obj) { setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea); resize(QSize(500, 700)); // default size setFloating(true); setSticky(false); QMainWindow* mainWindow = new QMainWindow(); mainWindow->setContextMenuPolicy(Qt::NoContextMenu); QToolBar* toolBar = new QToolBar(); mainWindow->addToolBar(toolBar); toolBar->setFloatable(false); toolBar->setMovable(false); setWidget(mainWindow); auto shadercode = new QTextEdit(nullptr); shadercode->setObjectName("shaderwidgetcode"); shadercode->setReadOnly(false); shadercode->setText(utilqt::toQString(obj->print(false, false))); shadercode->setStyleSheet("font: 10pt \"Courier\";"); shadercode->setWordWrapMode(QTextOption::NoWrap); SyntaxHighligther::createSyntaxHighligther<GLSL>(shadercode->document()); auto save = toolBar->addAction(QIcon(":/icons/save.png"), tr("&Save shader")); save->setShortcut(QKeySequence::Save); save->setShortcutContext(Qt::WidgetWithChildrenShortcut); mainWindow->addAction(save); connect(save, &QAction::triggered, [=]() { if (auto fr = dynamic_cast<const FileShaderResource*>(obj->getResource().get())) { auto file = filesystem::ofstream(fr->file()); file << utilqt::fromQString(shadercode->toPlainText()); file.close(); } else if (auto sr = dynamic_cast<const StringShaderResource*>(obj->getResource().get())) { // get the non-const version from the manager. auto res = ShaderManager::getPtr()->getShaderResource(sr->key()); if (auto editable = dynamic_cast<StringShaderResource*>(res.get())) { editable->setSource(utilqt::fromQString(shadercode->toPlainText())); } } }); auto showSource = toolBar->addAction("Show Sources"); showSource->setChecked(false); showSource->setCheckable(true); auto preprocess = toolBar->addAction("Show preprocess"); preprocess->setChecked(false); preprocess->setCheckable(true); auto update = [=](int /*state*/) { shadercode->setText(obj->print(showSource->isChecked(), preprocess->isChecked()).c_str()); shadercode->setReadOnly(showSource->isChecked() || preprocess->isChecked()); save->setEnabled(!showSource->isChecked() && !preprocess->isChecked()); showSource->setText(showSource->isChecked() ? "Hide Sources" : "Show Sources"); preprocess->setText(preprocess->isChecked() ? "Hide Preprocessed" : "Show Preprocessed"); }; connect(showSource, &QAction::triggered, update); connect(preprocess, &QAction::triggered, update); mainWindow->setCentralWidget(shadercode); loadState(); } ShaderWidget::~ShaderWidget() = default; void ShaderWidget::closeEvent(QCloseEvent* event) { saveState(); event->accept(); emit widgetClosed(); this->deleteLater(); } } // namespace inviwo <commit_msg>OpenGLQt: ShaderWidget fixes<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2015-2017 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. 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. * * 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. * *********************************************************************************/ #include <modules/openglqt/shaderwidget.h> #include <modules/opengl/shader/shaderobject.h> #include <modules/opengl/shader/shaderresource.h> #include <modules/opengl/shader/shadermanager.h> #include <modules/qtwidgets/properties/syntaxhighlighter.h> #include <modules/qtwidgets/inviwoqtutils.h> #include <inviwo/core/util/filesystem.h> #include <warn/push> #include <warn/ignore/all> #include <QTextEdit> #include <QDialog> #include <QToolBar> #include <QMainWindow> #include <QMenuBar> #include <QGridLayout> #include <QCheckBox> #include <QHBoxLayout> #include <QCloseEvent> #include <QFont> #include <warn/pop> namespace inviwo { ShaderWidget::ShaderWidget(const ShaderObject* obj, QWidget* parent) : InviwoDockWidget(utilqt::toQString(obj->getFileName()), parent, "ShaderEditorWidget") , obj_(obj) { setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea); resize(QSize(500, 700)); // default size setFloating(true); setSticky(false); QMainWindow* mainWindow = new QMainWindow(); mainWindow->setContextMenuPolicy(Qt::NoContextMenu); QToolBar* toolBar = new QToolBar(); mainWindow->addToolBar(toolBar); toolBar->setFloatable(false); toolBar->setMovable(false); setWidget(mainWindow); auto shadercode = new QTextEdit(nullptr); shadercode->setObjectName("shaderwidgetcode"); shadercode->setReadOnly(false); shadercode->setText(utilqt::toQString(obj->print(false, false))); shadercode->setWordWrapMode(QTextOption::NoWrap); auto syntaxHighlighter = SyntaxHighligther::createSyntaxHighligther<GLSL>(shadercode->document()); QFont fixedFont("Monospace"); fixedFont.setPointSize(10); fixedFont.setStyleHint(QFont::TypeWriter); shadercode->setFont(fixedFont); QColor bgColor = syntaxHighlighter->getBackgroundColor(); // select monospace font family and set background color matching syntax highlighting QString styleSheet(QString("QTextEdit { font-family: 'monospace'; background-color: %1; }") .arg(bgColor.name())); shadercode->setStyleSheet(styleSheet); auto save = toolBar->addAction(QIcon(":/icons/save.png"), tr("&Save shader")); save->setShortcut(QKeySequence::Save); save->setShortcutContext(Qt::WidgetWithChildrenShortcut); mainWindow->addAction(save); connect(save, &QAction::triggered, [=]() { if (auto fr = dynamic_cast<const FileShaderResource*>(obj->getResource().get())) { auto file = filesystem::ofstream(fr->file()); file << utilqt::fromQString(shadercode->toPlainText()); file.close(); } else if (auto sr = dynamic_cast<const StringShaderResource*>(obj->getResource().get())) { // get the non-const version from the manager. auto res = ShaderManager::getPtr()->getShaderResource(sr->key()); if (auto editable = dynamic_cast<StringShaderResource*>(res.get())) { editable->setSource(utilqt::fromQString(shadercode->toPlainText())); } } }); auto showSource = toolBar->addAction("Show Sources"); showSource->setChecked(false); showSource->setCheckable(true); auto preprocess = toolBar->addAction("Show preprocess"); preprocess->setChecked(false); preprocess->setCheckable(true); auto update = [=](int /*state*/) { shadercode->setText(obj->print(showSource->isChecked(), preprocess->isChecked()).c_str()); shadercode->setReadOnly(showSource->isChecked() || preprocess->isChecked()); save->setEnabled(!showSource->isChecked() && !preprocess->isChecked()); showSource->setText(showSource->isChecked() ? "Hide Sources" : "Show Sources"); preprocess->setText(preprocess->isChecked() ? "Hide Preprocessed" : "Show Preprocessed"); }; connect(showSource, &QAction::triggered, update); connect(preprocess, &QAction::triggered, update); mainWindow->setCentralWidget(shadercode); loadState(); } ShaderWidget::~ShaderWidget() = default; void ShaderWidget::closeEvent(QCloseEvent* event) { saveState(); event->accept(); emit widgetClosed(); this->deleteLater(); } } // namespace inviwo <|endoftext|>
<commit_before>#include "xmlui/LocationXmlHandler.h" #include "xmlui/XmlLocationDeserializer.h" #include "xmlui/Serializing.h" #include "model/Location.h" #include "model/Place.h" using namespace std; using namespace Poco; using namespace Poco::Net; using namespace Poco::XML; using namespace BeeeOn; using namespace BeeeOn::XmlUI; LocationXmlHandler::LocationXmlHandler( const StreamSocket &socket, const AutoPtr<Document> input, ExpirableSession::Ptr session, LocationService &locationService): AbstractXmlHandler("locations", socket, input, session), m_locationService(locationService) { } void LocationXmlHandler::handleInputImpl() { if (!requireSession()) return; Element *root = m_input->documentElement(); const string &type = root->getAttribute("type"); const string &gateid = root->getAttribute("gateid"); if (gateid.empty()) { resultInvalidInput(); return; } if (type == "getall") { handleGetAll(gateid); return; } Element *locationNode = root->getChildElement("location"); if (locationNode == NULL) { resultInvalidInput(); return; } if (type == "create") handleCreate(gateid, locationNode); else if (type == "delete") handleDelete(gateid, locationNode); else if (type == "update") handleUpdate(gateid, locationNode); else resultInvalidInput(); } void LocationXmlHandler::handleCreate( const string &gateid, Element *locationNode) { Gateway gateway(GatewayID::parse(gateid)); Location location; XmlLocationDeserializer deserializer(*locationNode); RelationWithData<Location, Gateway> input( location, deserializer, gateway); User user(session()->userID()); input.setUser(user); m_locationService.createIn(input); resultDataStart(); serialize(m_output, location); resultDataEnd(); } void LocationXmlHandler::handleDelete( const string &gateid, Element *locationNode) { Gateway gateway(GatewayID::parse(gateid)); Location location(LocationID::parse( locationNode->getAttribute("locationid"))); Relation<Location, Gateway> input(location, gateway); User user(session()->userID()); input.setUser(user); if (!m_locationService.removeFrom(input)) { resultNotFound(); return; } resultSuccess(); } void LocationXmlHandler::handleUpdate( const string &gateid, Element *locationNode) { Gateway gateway(GatewayID::parse(gateid)); Location location(LocationID::parse( locationNode->getAttribute("locationid"))); XmlLocationDeserializer update(*locationNode); RelationWithData<Location, Gateway> input( location, update, gateway); User user(session()->userID()); input.setUser(user); if (!m_locationService.updateIn(input)) { resultNotFound(); return; } resultSuccess(); } void LocationXmlHandler::handleGetAll(const string &gateid) { Gateway gateway(GatewayID::parse(gateid)); vector<Location> locations; Relation<vector<Location>, Gateway> input(locations, gateway); User user(session()->userID()); input.setUser(user); m_locationService.fetchBy(input); resultDataStart(); serialize(m_output, locations); resultDataEnd(); } LocationXmlHandlerResolver::LocationXmlHandlerResolver(): AbstractXmlHandlerResolver("locations") { injector<LocationXmlHandlerResolver, LocationService>( "locationService", &LocationXmlHandlerResolver::setLocationService); injector<LocationXmlHandlerResolver, SessionManager>( "sessionManager", &LocationXmlHandlerResolver::setSessionManager); } bool LocationXmlHandlerResolver::canHandle( const Element &root) { if (!AbstractXmlHandlerResolver::canHandle(root)) return false; if (root.getAttribute("type") == "create") return true; if (root.getAttribute("type") == "delete") return true; if (root.getAttribute("type") == "update") return true; if (root.getAttribute("type") == "getall") return true; return false; } XmlRequestHandler *LocationXmlHandlerResolver::createHandler( const StreamSocket &socket, const AutoPtr<Document> input) { ExpirableSession::Ptr session = lookupSession( *m_sessionManager, input); return new LocationXmlHandler( socket, input, session, *m_locationService); } BEEEON_OBJECT(LocationXmlHandlerResolver, BeeeOn::XmlUI::LocationXmlHandlerResolver) <commit_msg>LocationXmlHandler: remove include of Place.h<commit_after>#include "xmlui/LocationXmlHandler.h" #include "xmlui/XmlLocationDeserializer.h" #include "xmlui/Serializing.h" #include "model/Location.h" using namespace std; using namespace Poco; using namespace Poco::Net; using namespace Poco::XML; using namespace BeeeOn; using namespace BeeeOn::XmlUI; LocationXmlHandler::LocationXmlHandler( const StreamSocket &socket, const AutoPtr<Document> input, ExpirableSession::Ptr session, LocationService &locationService): AbstractXmlHandler("locations", socket, input, session), m_locationService(locationService) { } void LocationXmlHandler::handleInputImpl() { if (!requireSession()) return; Element *root = m_input->documentElement(); const string &type = root->getAttribute("type"); const string &gateid = root->getAttribute("gateid"); if (gateid.empty()) { resultInvalidInput(); return; } if (type == "getall") { handleGetAll(gateid); return; } Element *locationNode = root->getChildElement("location"); if (locationNode == NULL) { resultInvalidInput(); return; } if (type == "create") handleCreate(gateid, locationNode); else if (type == "delete") handleDelete(gateid, locationNode); else if (type == "update") handleUpdate(gateid, locationNode); else resultInvalidInput(); } void LocationXmlHandler::handleCreate( const string &gateid, Element *locationNode) { Gateway gateway(GatewayID::parse(gateid)); Location location; XmlLocationDeserializer deserializer(*locationNode); RelationWithData<Location, Gateway> input( location, deserializer, gateway); User user(session()->userID()); input.setUser(user); m_locationService.createIn(input); resultDataStart(); serialize(m_output, location); resultDataEnd(); } void LocationXmlHandler::handleDelete( const string &gateid, Element *locationNode) { Gateway gateway(GatewayID::parse(gateid)); Location location(LocationID::parse( locationNode->getAttribute("locationid"))); Relation<Location, Gateway> input(location, gateway); User user(session()->userID()); input.setUser(user); if (!m_locationService.removeFrom(input)) { resultNotFound(); return; } resultSuccess(); } void LocationXmlHandler::handleUpdate( const string &gateid, Element *locationNode) { Gateway gateway(GatewayID::parse(gateid)); Location location(LocationID::parse( locationNode->getAttribute("locationid"))); XmlLocationDeserializer update(*locationNode); RelationWithData<Location, Gateway> input( location, update, gateway); User user(session()->userID()); input.setUser(user); if (!m_locationService.updateIn(input)) { resultNotFound(); return; } resultSuccess(); } void LocationXmlHandler::handleGetAll(const string &gateid) { Gateway gateway(GatewayID::parse(gateid)); vector<Location> locations; Relation<vector<Location>, Gateway> input(locations, gateway); User user(session()->userID()); input.setUser(user); m_locationService.fetchBy(input); resultDataStart(); serialize(m_output, locations); resultDataEnd(); } LocationXmlHandlerResolver::LocationXmlHandlerResolver(): AbstractXmlHandlerResolver("locations") { injector<LocationXmlHandlerResolver, LocationService>( "locationService", &LocationXmlHandlerResolver::setLocationService); injector<LocationXmlHandlerResolver, SessionManager>( "sessionManager", &LocationXmlHandlerResolver::setSessionManager); } bool LocationXmlHandlerResolver::canHandle( const Element &root) { if (!AbstractXmlHandlerResolver::canHandle(root)) return false; if (root.getAttribute("type") == "create") return true; if (root.getAttribute("type") == "delete") return true; if (root.getAttribute("type") == "update") return true; if (root.getAttribute("type") == "getall") return true; return false; } XmlRequestHandler *LocationXmlHandlerResolver::createHandler( const StreamSocket &socket, const AutoPtr<Document> input) { ExpirableSession::Ptr session = lookupSession( *m_sessionManager, input); return new LocationXmlHandler( socket, input, session, *m_locationService); } BEEEON_OBJECT(LocationXmlHandlerResolver, BeeeOn::XmlUI::LocationXmlHandlerResolver) <|endoftext|>
<commit_before>/* * Copyright 2009-2015 The VOTCA Development Team (http://www.votca.org) * * 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 <votca/tools/linalg.h> #include <boost/numeric/ublas/matrix_proxy.hpp> #include <gsl/gsl_linalg.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_eigen.h> namespace votca { namespace tools { using namespace std; void linalg_invert( ub::matrix<double> &A, ub::matrix<double> &V){ // matrix inversion using gsl gsl_error_handler_t *handler = gsl_set_error_handler_off(); const size_t N = A.size1(); // signum s (for LU decomposition) int s; //make copy of A as A is destroyed by GSL ub::matrix<double> work=A; V.resize(N, N, false); // Define all the used matrices gsl_matrix_view A_view = gsl_matrix_view_array(&work(0,0), N, N); gsl_matrix_view V_view = gsl_matrix_view_array(&V(0,0), N, N); gsl_permutation * perm = gsl_permutation_alloc (N); // Make LU decomposition of matrix A_view gsl_linalg_LU_decomp (&A_view.matrix, perm, &s); // Invert the matrix A_view (void)gsl_linalg_LU_invert (&A_view.matrix, perm, &V_view.matrix); gsl_set_error_handler(handler); // return (status != 0); } void linalg_invert( ub::matrix<float> &A, ub::matrix<float> &V){ // matrix inversion using gsl throw std::runtime_error("linalg_invert (float) is not compiled-in due to disabling of MKL - recompile Votca Tools with MKL support"); } // not really tested bool linalg_solve(const ub::matrix<double> &A, ub::vector<double> &b){ gsl_error_handler_t *handler = gsl_set_error_handler_off(); const size_t N = A.size1(); // signum s (for LU decomposition) int s; //make copy of A as A is destroyed by GSL ub::matrix<double> work=A; ub::vector<double>x=ub::zero_vector<double>(N); // Define all the used matrices gsl_matrix_view A_view = gsl_matrix_view_array(&work(0,0), N, N); gsl_vector_view B_view = gsl_vector_view_array(&B(0), N); gsl_vector_view X_view = gsl_vector_view_array(&X(0), N); gsl_permutation * perm = gsl_permutation_alloc (N); // Make LU decomposition of matrix A_view gsl_linalg_LU_decomp (&A_view.matrix, perm, &s); // Invert the matrix A_view int info=gsl_linalg_LU_solve (&A_view.matrix, perm, &B_view.vector,&X_view.vector); gsl_set_error_handler(handler); b=x; bool success=(info==0); return success; } }} <commit_msg>error, push fast becasue breaking master is bad<commit_after>/* * Copyright 2009-2015 The VOTCA Development Team (http://www.votca.org) * * 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 <votca/tools/linalg.h> #include <boost/numeric/ublas/matrix_proxy.hpp> #include <gsl/gsl_linalg.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_eigen.h> namespace votca { namespace tools { using namespace std; void linalg_invert( ub::matrix<double> &A, ub::matrix<double> &V){ // matrix inversion using gsl gsl_error_handler_t *handler = gsl_set_error_handler_off(); const size_t N = A.size1(); // signum s (for LU decomposition) int s; //make copy of A as A is destroyed by GSL ub::matrix<double> work=A; V.resize(N, N, false); // Define all the used matrices gsl_matrix_view A_view = gsl_matrix_view_array(&work(0,0), N, N); gsl_matrix_view V_view = gsl_matrix_view_array(&V(0,0), N, N); gsl_permutation * perm = gsl_permutation_alloc (N); // Make LU decomposition of matrix A_view gsl_linalg_LU_decomp (&A_view.matrix, perm, &s); // Invert the matrix A_view (void)gsl_linalg_LU_invert (&A_view.matrix, perm, &V_view.matrix); gsl_set_error_handler(handler); // return (status != 0); } void linalg_invert( ub::matrix<float> &A, ub::matrix<float> &V){ // matrix inversion using gsl throw std::runtime_error("linalg_invert (float) is not compiled-in due to disabling of MKL - recompile Votca Tools with MKL support"); } // not really tested bool linalg_solve(const ub::matrix<double> &A, ub::vector<double> &b){ gsl_error_handler_t *handler = gsl_set_error_handler_off(); const size_t N = A.size1(); // signum s (for LU decomposition) int s; //make copy of A as A is destroyed by GSL ub::matrix<double> work=A; ub::vector<double>x=ub::zero_vector<double>(N); // Define all the used matrices gsl_matrix_view A_view = gsl_matrix_view_array(&work(0,0), N, N); gsl_vector_view B_view = gsl_vector_view_array(&b(0), N); gsl_vector_view X_view = gsl_vector_view_array(&x(0), N); gsl_permutation * perm = gsl_permutation_alloc (N); // Make LU decomposition of matrix A_view gsl_linalg_LU_decomp (&A_view.matrix, perm, &s); // Invert the matrix A_view int info=gsl_linalg_LU_solve (&A_view.matrix, perm, &B_view.vector,&X_view.vector); gsl_set_error_handler(handler); b=x; bool success=(info==0); return success; } }} <|endoftext|>
<commit_before>/* * The MIT License * * Copyright (c) 2010 Sam Day * * 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 "commit.h" #include "repository.h" #include "object_factory.h" #include "tree.h" #include <time.h> #include <stdlib.h> #include "signature.h" #define CLASS_NAME String::NewSymbol("Commit") static Persistent<String> id_symbol; static Persistent<String> message_symbol; static Persistent<String> author_symbol; static Persistent<String> committer_symbol; static Persistent<String> tree_symbol; static Persistent<String> parents_symbol; namespace gitteh { struct commit_data { char id[40]; std::string *message; git_signature *author; git_signature *committer; int parentCount; std::string **parentIds; std::string *treeId; }; struct save_commit_request { Persistent<Function> callback; Repository *repo; Persistent<Object> repoHandle; Commit *commit; int error; bool isNew; char id[40]; std::string *message; git_signature *author; git_signature *committer; int parentCount; git_oid *parentIds; git_oid treeId; }; Persistent<FunctionTemplate> Commit::constructor_template; void Commit::Init(Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); constructor_template = Persistent<FunctionTemplate>::New(t); constructor_template->SetClassName(CLASS_NAME); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "save", Save); id_symbol = NODE_PSYMBOL("id"); message_symbol = NODE_PSYMBOL("message"); author_symbol = NODE_PSYMBOL("author"); committer_symbol = NODE_PSYMBOL("committer"); tree_symbol = NODE_PSYMBOL("tree"); parents_symbol = NODE_PSYMBOL("parents"); } Handle<Value> Commit::New(const Arguments& args) { HandleScope scope; REQ_ARGS(1); REQ_EXT_ARG(0, theCommit); Commit *commit = new Commit(); commit->commit_ = (git_commit*)theCommit->Value(); commit->Wrap(args.This()); return args.This(); } Handle<Value> Commit::SaveObject(Handle<Object> commitObject, Repository *repo, Handle<Value> callback, bool isNew) { int result, parentCount, i; git_oid treeId; git_oid *parentIds; HandleScope scope; if(!commitObject->Has(message_symbol)) { THROW_ERROR("Message is required."); } if(!commitObject->Has(author_symbol)) { THROW_ERROR("Author is required."); } if(!commitObject->Has(committer_symbol)) { THROW_ERROR("Committer is required."); } if(!commitObject->Has(tree_symbol)) { THROW_ERROR("Tree is required."); } String::Utf8Value message(commitObject->Get(message_symbol)); if(!message.length()) { THROW_ERROR("Message is required."); } String::Utf8Value treeIdStr(commitObject->Get(tree_symbol)); if(!treeIdStr.length()) { THROW_ERROR("Tree is required."); } treeId; result = git_oid_mkstr(&treeId, *treeIdStr); if(result != GIT_SUCCESS) { THROW_ERROR("Tree ID is invalid."); } Handle<Array> parents; if(commitObject->Has(parents_symbol)) { Handle<Value> parentProperty = commitObject->Get(parents_symbol); if(!parentProperty->IsArray()) { if(!parentProperty->IsNull()) { parents = Array::New(1); parents->Set(0, parentProperty); } else { parents = Array::New(0); } } else { parents = Local<Array>::New(Handle<Array>::Cast(parentProperty)); } } else { parents = Array::New(0); } parentCount = parents->Length(); parentIds = new git_oid[parentCount]; for(i = 0; i < parentCount; i++) { result = git_oid_mkstr(&parentIds[i], *String::Utf8Value(parents->Get(i))); if(result != GIT_SUCCESS) { delete [] parentIds; THROW_ERROR("Parent id is invalid."); } } git_signature *committer = GetSignatureFromProperty(commitObject, committer_symbol); if(committer == NULL) { delete [] parentIds; THROW_ERROR("Committer is not a valid signature."); } git_signature *author = GetSignatureFromProperty(commitObject, author_symbol); if(author == NULL) { delete [] parentIds; git_signature_free(committer); THROW_ERROR("Author is not a valid signature."); } // Okay, we're ready to make this happen. Are we doing it asynchronously // or synchronously? if(callback->IsFunction()) { save_commit_request *request = new save_commit_request; request->message = new std::string(*message); request->parentCount = parentCount; request->parentIds = parentIds; memcpy(&request->treeId, &treeId, sizeof(git_oid)); request->committer = committer; request->author = author; request->isNew = isNew; if(!request->isNew) { request->commit = ObjectWrap::Unwrap<Commit>(commitObject); request->commit->Ref(); } else { request->commit = NULL; } request->callback = Persistent<Function>::New(Handle<Function>::Cast(callback)); request->repo = repo; request->repoHandle = Persistent<Object>::New(repo->handle_); eio_custom(EIO_Save, EIO_PRI_DEFAULT, EIO_AfterSave, request); ev_ref(EV_DEFAULT_UC); return Undefined(); } else { git_oid newId; const git_oid **parentIdsPtr; parentIdsPtr = new const git_oid*[parentCount]; for(i = 0; i < parentCount; i++) { parentIdsPtr[i] = &parentIds[i]; } result = git_commit_create(&newId, repo->repo_, NULL, author, committer, *message, &treeId, parentCount, parentIdsPtr); git_signature_free(author); git_signature_free(committer); delete [] parentIdsPtr; delete [] parentIds; if(result != GIT_SUCCESS) { THROW_GIT_ERROR("Couldn't save commit.", result); } char newIdStr[40]; git_oid_fmt(newIdStr, &newId); if(isNew) { Handle<Function> getCommitFn = Handle<Function>::Cast( repo->handle_->Get(String::New("getCommit"))); Handle<Value> arg = String::New(newIdStr, 40); return scope.Close(getCommitFn->Call(repo->handle_, 1, &arg)); } else { commitObject->Set(id_symbol, String::New(newIdStr, 40), (PropertyAttribute)(ReadOnly | DontDelete)); return scope.Close(True()); } } } Handle<Value> Commit::Save(const Arguments& args) { HandleScope scope; Commit *commit = ObjectWrap::Unwrap<Commit>(args.This()); Handle<Value> callback = Null(); if(HAS_CALLBACK_ARG) { REQ_FUN_ARG(args.Length() - 1, callbackArg); callback = callbackArg; } return scope.Close(SaveObject(args.This(), commit->repository_, callback, false)); } int Commit::EIO_Save(eio_req *req) { save_commit_request *reqData = static_cast<save_commit_request*>(req->data); const git_oid **parentIdsPtr; parentIdsPtr = new const git_oid*[reqData->parentCount]; for(int i = 0; i < reqData->parentCount; i++) { parentIdsPtr[i] = &reqData->parentIds[i]; } git_oid newId; reqData->repo->lockRepository(); reqData->error = git_commit_create(&newId, reqData->repo->repo_, NULL, reqData->author, reqData->committer, reqData->message->c_str(), &reqData->treeId, reqData->parentCount, parentIdsPtr); reqData->repo->unlockRepository(); if(reqData->error == GIT_SUCCESS) { git_oid_fmt(reqData->id, &newId); } delete [] parentIdsPtr; delete reqData->message; delete [] reqData->parentIds; git_signature_free(reqData->committer); git_signature_free(reqData->author); return 0; } int Commit::EIO_AfterSave(eio_req *req) { HandleScope scope; save_commit_request *reqData = static_cast<save_commit_request*>(req->data); reqData->repoHandle.Dispose(); ev_unref(EV_DEFAULT_UC); if(reqData->commit != NULL) reqData->commit->Unref(); Handle<Value> callbackArgs[2]; if(reqData->error != GIT_SUCCESS) { Handle<Value> error = Exception::Error(String::New("Couldn't save commit.")); callbackArgs[0] = error; callbackArgs[1] = Null(); } else { callbackArgs[0] = Null(); if(reqData->isNew) { Handle<Function> getCommitFn = Handle<Function>::Cast( reqData->repo->handle_->Get(String::New("getCommit"))); Handle<Value> arg = String::New(reqData->id, 40); callbackArgs[1] = getCommitFn->Call(reqData->repo->handle_, 1, &arg); } else { reqData->commit->handle_->ForceSet(id_symbol, String::New(reqData->id, 40), (PropertyAttribute)(ReadOnly | DontDelete)); callbackArgs[1] = True(); } } reqData->callback.Dispose(); TRIGGER_CALLBACK(); delete reqData; return 0; } void* Commit::loadInitData() { commit_data *data = new commit_data; repository_->lockRepository(); const git_oid *commitId = git_commit_id(commit_); git_oid_fmt(data->id, commitId); data->message = new std::string(git_commit_message(commit_)); data->author = git_signature_dup(git_commit_author(commit_)); data->committer = git_signature_dup(git_commit_committer(commit_)); data->parentCount = git_commit_parentcount(commit_); data->parentIds = new std::string*[data->parentCount]; for(int i = 0; i< data->parentCount; i++) { git_commit *parent; git_commit_parent(&parent, commit_, i); const git_oid *oid = git_commit_id(parent); char oidStr[40]; git_oid_fmt(oidStr, oid); data->parentIds[i] = new std::string(oidStr, 40); } git_tree *commitTree; git_commit_tree(&commitTree, commit_); const git_oid *treeOid = git_tree_id(commitTree); char treeOidStr[40]; git_oid_fmt(treeOidStr, treeOid); data->treeId = new std::string(treeOidStr, 40); repository_->unlockRepository(); return data; } void Commit::processInitData(void *data) { HandleScope scope; Handle<Object> jsObj = handle_; commit_data *commitData = static_cast<commit_data*>(data); jsObj->Set(id_symbol, String::New(commitData->id, 40), (PropertyAttribute)(ReadOnly | DontDelete)); jsObj->Set(message_symbol, String::New(commitData->message->c_str())); delete commitData->message; CREATE_PERSON_OBJ(authorObj, commitData->author); jsObj->Set(author_symbol, authorObj); git_signature_free(commitData->author); CREATE_PERSON_OBJ(committerObj, commitData->committer); jsObj->Set(committer_symbol, committerObj); git_signature_free(commitData->committer); parentCount_ = commitData->parentCount; Handle<Array> parentsArray = Array::New(parentCount_); for(int i = 0; i < parentCount_; i++) { parentsArray->Set(i, String::New(commitData->parentIds[i]->c_str())); delete commitData->parentIds[i]; } delete [] commitData->parentIds; jsObj->Set(parents_symbol, parentsArray); jsObj->Set(tree_symbol, String::New(commitData->treeId->c_str())); delete commitData->treeId; delete commitData; } void Commit::setOwner(void *owner) { repository_ = static_cast<Repository*>(owner); } Commit::Commit() : GitObjectWrap() { } Commit::~Commit() { repository_->lockRepository(); git_commit_close(commit_); repository_->unlockRepository(); } } // namespace gitteh <commit_msg>Ensure commit ID is updated on save.<commit_after>/* * The MIT License * * Copyright (c) 2010 Sam Day * * 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 "commit.h" #include "repository.h" #include "object_factory.h" #include "tree.h" #include <time.h> #include <stdlib.h> #include "signature.h" #define CLASS_NAME String::NewSymbol("Commit") static Persistent<String> id_symbol; static Persistent<String> message_symbol; static Persistent<String> author_symbol; static Persistent<String> committer_symbol; static Persistent<String> tree_symbol; static Persistent<String> parents_symbol; namespace gitteh { struct commit_data { char id[40]; std::string *message; git_signature *author; git_signature *committer; int parentCount; std::string **parentIds; std::string *treeId; }; struct save_commit_request { Persistent<Function> callback; Repository *repo; Persistent<Object> repoHandle; Commit *commit; int error; bool isNew; char id[40]; std::string *message; git_signature *author; git_signature *committer; int parentCount; git_oid *parentIds; git_oid treeId; }; Persistent<FunctionTemplate> Commit::constructor_template; void Commit::Init(Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); constructor_template = Persistent<FunctionTemplate>::New(t); constructor_template->SetClassName(CLASS_NAME); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "save", Save); id_symbol = NODE_PSYMBOL("id"); message_symbol = NODE_PSYMBOL("message"); author_symbol = NODE_PSYMBOL("author"); committer_symbol = NODE_PSYMBOL("committer"); tree_symbol = NODE_PSYMBOL("tree"); parents_symbol = NODE_PSYMBOL("parents"); } Handle<Value> Commit::New(const Arguments& args) { HandleScope scope; REQ_ARGS(1); REQ_EXT_ARG(0, theCommit); Commit *commit = new Commit(); commit->commit_ = (git_commit*)theCommit->Value(); commit->Wrap(args.This()); return args.This(); } Handle<Value> Commit::SaveObject(Handle<Object> commitObject, Repository *repo, Handle<Value> callback, bool isNew) { int result, parentCount, i; git_oid treeId; git_oid *parentIds; HandleScope scope; if(!commitObject->Has(message_symbol)) { THROW_ERROR("Message is required."); } if(!commitObject->Has(author_symbol)) { THROW_ERROR("Author is required."); } if(!commitObject->Has(committer_symbol)) { THROW_ERROR("Committer is required."); } if(!commitObject->Has(tree_symbol)) { THROW_ERROR("Tree is required."); } String::Utf8Value message(commitObject->Get(message_symbol)); if(!message.length()) { THROW_ERROR("Message is required."); } String::Utf8Value treeIdStr(commitObject->Get(tree_symbol)); if(!treeIdStr.length()) { THROW_ERROR("Tree is required."); } treeId; result = git_oid_mkstr(&treeId, *treeIdStr); if(result != GIT_SUCCESS) { THROW_ERROR("Tree ID is invalid."); } Handle<Array> parents; if(commitObject->Has(parents_symbol)) { Handle<Value> parentProperty = commitObject->Get(parents_symbol); if(!parentProperty->IsArray()) { if(!parentProperty->IsNull()) { parents = Array::New(1); parents->Set(0, parentProperty); } else { parents = Array::New(0); } } else { parents = Local<Array>::New(Handle<Array>::Cast(parentProperty)); } } else { parents = Array::New(0); } parentCount = parents->Length(); parentIds = new git_oid[parentCount]; for(i = 0; i < parentCount; i++) { result = git_oid_mkstr(&parentIds[i], *String::Utf8Value(parents->Get(i))); if(result != GIT_SUCCESS) { delete [] parentIds; THROW_ERROR("Parent id is invalid."); } } git_signature *committer = GetSignatureFromProperty(commitObject, committer_symbol); if(committer == NULL) { delete [] parentIds; THROW_ERROR("Committer is not a valid signature."); } git_signature *author = GetSignatureFromProperty(commitObject, author_symbol); if(author == NULL) { delete [] parentIds; git_signature_free(committer); THROW_ERROR("Author is not a valid signature."); } // Okay, we're ready to make this happen. Are we doing it asynchronously // or synchronously? if(callback->IsFunction()) { save_commit_request *request = new save_commit_request; request->message = new std::string(*message); request->parentCount = parentCount; request->parentIds = parentIds; memcpy(&request->treeId, &treeId, sizeof(git_oid)); request->committer = committer; request->author = author; request->isNew = isNew; if(!request->isNew) { request->commit = ObjectWrap::Unwrap<Commit>(commitObject); request->commit->Ref(); } else { request->commit = NULL; } request->callback = Persistent<Function>::New(Handle<Function>::Cast(callback)); request->repo = repo; request->repoHandle = Persistent<Object>::New(repo->handle_); eio_custom(EIO_Save, EIO_PRI_DEFAULT, EIO_AfterSave, request); ev_ref(EV_DEFAULT_UC); return Undefined(); } else { git_oid newId; const git_oid **parentIdsPtr; parentIdsPtr = new const git_oid*[parentCount]; for(i = 0; i < parentCount; i++) { parentIdsPtr[i] = &parentIds[i]; } result = git_commit_create(&newId, repo->repo_, NULL, author, committer, *message, &treeId, parentCount, parentIdsPtr); git_signature_free(author); git_signature_free(committer); delete [] parentIdsPtr; delete [] parentIds; if(result != GIT_SUCCESS) { THROW_GIT_ERROR("Couldn't save commit.", result); } char newIdStr[40]; git_oid_fmt(newIdStr, &newId); if(isNew) { Handle<Function> getCommitFn = Handle<Function>::Cast( repo->handle_->Get(String::New("getCommit"))); Handle<Value> arg = String::New(newIdStr, 40); return scope.Close(getCommitFn->Call(repo->handle_, 1, &arg)); } else { commitObject->ForceSet(id_symbol, String::New(newIdStr, 40), (PropertyAttribute)(ReadOnly | DontDelete)); return scope.Close(True()); } } } Handle<Value> Commit::Save(const Arguments& args) { HandleScope scope; Commit *commit = ObjectWrap::Unwrap<Commit>(args.This()); Handle<Value> callback = Null(); if(HAS_CALLBACK_ARG) { REQ_FUN_ARG(args.Length() - 1, callbackArg); callback = callbackArg; } return scope.Close(SaveObject(args.This(), commit->repository_, callback, false)); } int Commit::EIO_Save(eio_req *req) { save_commit_request *reqData = static_cast<save_commit_request*>(req->data); const git_oid **parentIdsPtr; parentIdsPtr = new const git_oid*[reqData->parentCount]; for(int i = 0; i < reqData->parentCount; i++) { parentIdsPtr[i] = &reqData->parentIds[i]; } git_oid newId; reqData->repo->lockRepository(); reqData->error = git_commit_create(&newId, reqData->repo->repo_, NULL, reqData->author, reqData->committer, reqData->message->c_str(), &reqData->treeId, reqData->parentCount, parentIdsPtr); reqData->repo->unlockRepository(); if(reqData->error == GIT_SUCCESS) { git_oid_fmt(reqData->id, &newId); } delete [] parentIdsPtr; delete reqData->message; delete [] reqData->parentIds; git_signature_free(reqData->committer); git_signature_free(reqData->author); return 0; } int Commit::EIO_AfterSave(eio_req *req) { HandleScope scope; save_commit_request *reqData = static_cast<save_commit_request*>(req->data); reqData->repoHandle.Dispose(); ev_unref(EV_DEFAULT_UC); if(reqData->commit != NULL) reqData->commit->Unref(); Handle<Value> callbackArgs[2]; if(reqData->error != GIT_SUCCESS) { Handle<Value> error = Exception::Error(String::New("Couldn't save commit.")); callbackArgs[0] = error; callbackArgs[1] = Null(); } else { callbackArgs[0] = Null(); if(reqData->isNew) { Handle<Function> getCommitFn = Handle<Function>::Cast( reqData->repo->handle_->Get(String::New("getCommit"))); Handle<Value> arg = String::New(reqData->id, 40); callbackArgs[1] = getCommitFn->Call(reqData->repo->handle_, 1, &arg); } else { reqData->commit->handle_->ForceSet(id_symbol, String::New(reqData->id, 40), (PropertyAttribute)(ReadOnly | DontDelete)); callbackArgs[1] = True(); } } reqData->callback.Dispose(); TRIGGER_CALLBACK(); delete reqData; return 0; } void* Commit::loadInitData() { commit_data *data = new commit_data; repository_->lockRepository(); const git_oid *commitId = git_commit_id(commit_); git_oid_fmt(data->id, commitId); data->message = new std::string(git_commit_message(commit_)); data->author = git_signature_dup(git_commit_author(commit_)); data->committer = git_signature_dup(git_commit_committer(commit_)); data->parentCount = git_commit_parentcount(commit_); data->parentIds = new std::string*[data->parentCount]; for(int i = 0; i< data->parentCount; i++) { git_commit *parent; git_commit_parent(&parent, commit_, i); const git_oid *oid = git_commit_id(parent); char oidStr[40]; git_oid_fmt(oidStr, oid); data->parentIds[i] = new std::string(oidStr, 40); } git_tree *commitTree; git_commit_tree(&commitTree, commit_); const git_oid *treeOid = git_tree_id(commitTree); char treeOidStr[40]; git_oid_fmt(treeOidStr, treeOid); data->treeId = new std::string(treeOidStr, 40); repository_->unlockRepository(); return data; } void Commit::processInitData(void *data) { HandleScope scope; Handle<Object> jsObj = handle_; commit_data *commitData = static_cast<commit_data*>(data); jsObj->Set(id_symbol, String::New(commitData->id, 40), (PropertyAttribute)(ReadOnly | DontDelete)); jsObj->Set(message_symbol, String::New(commitData->message->c_str())); delete commitData->message; CREATE_PERSON_OBJ(authorObj, commitData->author); jsObj->Set(author_symbol, authorObj); git_signature_free(commitData->author); CREATE_PERSON_OBJ(committerObj, commitData->committer); jsObj->Set(committer_symbol, committerObj); git_signature_free(commitData->committer); parentCount_ = commitData->parentCount; Handle<Array> parentsArray = Array::New(parentCount_); for(int i = 0; i < parentCount_; i++) { parentsArray->Set(i, String::New(commitData->parentIds[i]->c_str())); delete commitData->parentIds[i]; } delete [] commitData->parentIds; jsObj->Set(parents_symbol, parentsArray); jsObj->Set(tree_symbol, String::New(commitData->treeId->c_str())); delete commitData->treeId; delete commitData; } void Commit::setOwner(void *owner) { repository_ = static_cast<Repository*>(owner); } Commit::Commit() : GitObjectWrap() { } Commit::~Commit() { repository_->lockRepository(); git_commit_close(commit_); repository_->unlockRepository(); } } // namespace gitteh <|endoftext|>
<commit_before>/* * Copyright (C) 2013 midnightBITS * * 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 "pch.h" #include "settings.hpp" namespace FastCGI { namespace app { namespace reader { class GeneralSettingsPageHandler : public SettingsPageHandler { public: DEBUG_NAME("Settings: General"); protected: void prerender(const SessionPtr& session, Request& request, PageTranslation& tr) override { if (request.getVariable("close")) onPageDone(request); if (request.getVariable("posted")) { std::string newLang = request.getVariable("lang"); auto profile = session->profile(); if (newLang != profile->preferredLanguage()) { profile->preferredLanguage(newLang); // empty preferred language means "only look into Accept-Languages, when there is nothing loaded" // so we must behave as if nothing was loaded... if (newLang.empty()) session->setTranslation(nullptr); tr.init(session, request); } } auto content = std::make_shared<settings::SimpleForm>(settings::PAGE::GENERAL); request.setContent(content); Options lang_opts; lang_opts.add("", tr(lng::LNG_SETTINGS_GENERAL_DEFAULT)); auto langs = request.app().knownLanguages(); for (auto&& lang : langs) lang_opts.add(lang.m_lang, lang.m_name); auto& controls = content->controls(); controls.selection("lang", tr(lng::LNG_SETTINGS_GENERAL_LANGUAGES), lang_opts); auto feeds = controls.radio_group("feed", tr(lng::LNG_SETTINGS_GENERAL_FEED_TITLE)); feeds->radio("all", tr(lng::LNG_SETTINGS_GENERAL_FEED_ALL)); feeds->radio("unread", tr(lng::LNG_SETTINGS_GENERAL_FEED_UNREAD)); auto posts = controls.radio_group("posts", tr(lng::LNG_SETTINGS_GENERAL_POSTS_TITLE)); posts->radio("list", tr(lng::LNG_SETTINGS_GENERAL_POSTS_LIST)); posts->radio("exp", tr(lng::LNG_SETTINGS_GENERAL_POSTS_EXPANDED)); auto sort = controls.radio_group("sort", tr(lng::LNG_SETTINGS_GENERAL_SORT_TITLE)); sort->radio("newest", tr(lng::LNG_SETTINGS_GENERAL_SORT_NEWEST)); sort->radio("oldest", tr(lng::LNG_SETTINGS_GENERAL_SORT_OLDEST)); content->buttons().submit("submit", tr(lng::LNG_CMD_UPDATE)); content->buttons().submit("close", tr(lng::LNG_CMD_CLOSE), ButtonType::Narrow); Strings data; auto userInfo = FastCGI::userInfo(session); auto profile = session->profile(); data["lang"] = profile->preferredLanguage(); data["feed"] = userInfo->viewOnlyUnread() ? "unread" : "all"; data["posts"] = userInfo->viewOnlyTitles() ? "list" : "exp"; data["sort"] = userInfo->viewOldestFirst() ? "oldest" : "newest"; content->bind(request, data); if (!request.getVariable("posted")) return; if (feeds->hasUserData()) userInfo->setViewOnlyUnread(feeds->getData() == "unread"); if (posts->hasUserData()) userInfo->setViewOnlyTitles(posts->getData() == "list"); if (sort->hasUserData()) userInfo->setViewOldestFirst(sort->getData() == "oldest"); profile->storeLanguage(request.dbConn()); userInfo->storeFlags(request.dbConn()); } }; }}} // FastCGI::app::reader REGISTER_HANDLER("/settings/general", FastCGI::app::reader::GeneralSettingsPageHandler); <commit_msg>Crash fixed<commit_after>/* * Copyright (C) 2013 midnightBITS * * 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 "pch.h" #include "settings.hpp" namespace FastCGI { namespace app { namespace reader { class GeneralSettingsPageHandler : public SettingsPageHandler { public: DEBUG_NAME("Settings: General"); protected: void prerender(const SessionPtr& session, Request& request, PageTranslation& tr) override { if (request.getVariable("close")) onPageDone(request); if (request.getVariable("posted") && request.getVariable("lang")) { std::string newLang = request.getVariable("lang"); auto profile = session->profile(); if (newLang != profile->preferredLanguage()) { profile->preferredLanguage(newLang); // empty preferred language means "only look into Accept-Languages, when there is nothing loaded" // so we must behave as if nothing was loaded... if (newLang.empty()) session->setTranslation(nullptr); tr.init(session, request); } } auto content = std::make_shared<settings::SimpleForm>(settings::PAGE::GENERAL); request.setContent(content); Options lang_opts; lang_opts.add("", tr(lng::LNG_SETTINGS_GENERAL_DEFAULT)); auto langs = request.app().knownLanguages(); for (auto&& lang : langs) lang_opts.add(lang.m_lang, lang.m_name); auto& controls = content->controls(); controls.selection("lang", tr(lng::LNG_SETTINGS_GENERAL_LANGUAGES), lang_opts); auto feeds = controls.radio_group("feed", tr(lng::LNG_SETTINGS_GENERAL_FEED_TITLE)); feeds->radio("all", tr(lng::LNG_SETTINGS_GENERAL_FEED_ALL)); feeds->radio("unread", tr(lng::LNG_SETTINGS_GENERAL_FEED_UNREAD)); auto posts = controls.radio_group("posts", tr(lng::LNG_SETTINGS_GENERAL_POSTS_TITLE)); posts->radio("list", tr(lng::LNG_SETTINGS_GENERAL_POSTS_LIST)); posts->radio("exp", tr(lng::LNG_SETTINGS_GENERAL_POSTS_EXPANDED)); auto sort = controls.radio_group("sort", tr(lng::LNG_SETTINGS_GENERAL_SORT_TITLE)); sort->radio("newest", tr(lng::LNG_SETTINGS_GENERAL_SORT_NEWEST)); sort->radio("oldest", tr(lng::LNG_SETTINGS_GENERAL_SORT_OLDEST)); content->buttons().submit("submit", tr(lng::LNG_CMD_UPDATE)); content->buttons().submit("close", tr(lng::LNG_CMD_CLOSE), ButtonType::Narrow); Strings data; auto userInfo = FastCGI::userInfo(session); auto profile = session->profile(); data["lang"] = profile->preferredLanguage(); data["feed"] = userInfo->viewOnlyUnread() ? "unread" : "all"; data["posts"] = userInfo->viewOnlyTitles() ? "list" : "exp"; data["sort"] = userInfo->viewOldestFirst() ? "oldest" : "newest"; content->bind(request, data); if (!request.getVariable("posted")) return; if (feeds->hasUserData()) userInfo->setViewOnlyUnread(feeds->getData() == "unread"); if (posts->hasUserData()) userInfo->setViewOnlyTitles(posts->getData() == "list"); if (sort->hasUserData()) userInfo->setViewOldestFirst(sort->getData() == "oldest"); profile->storeLanguage(request.dbConn()); userInfo->storeFlags(request.dbConn()); } }; }}} // FastCGI::app::reader REGISTER_HANDLER("/settings/general", FastCGI::app::reader::GeneralSettingsPageHandler); <|endoftext|>
<commit_before><commit_msg>Remove redundant const_cast (#5705)<commit_after><|endoftext|>
<commit_before>/***************************************************************************** * Copyright © 2014 Sergey Radionov <rsatom_gmail.com> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "Chimera_X11.h" #include <QTimer> #include "QmlVlc/QmlVlcSurfacePlayerProxy.h" //////////////////////////////////////////////////////////////////////////////// //Chimera_X11 class //////////////////////////////////////////////////////////////////////////////// Chimera_X11::Chimera_X11() { } Chimera_X11::~Chimera_X11() { } bool Chimera_X11::onX11Event( FB::X11Event* evt, FB::PluginWindowX11* w ) { if( GDK_MAP == evt->m_event->type ) { onWindowResized( 0, w ); } return false; } bool Chimera_X11::onWindowAttached( FB::AttachedEvent* evt, FB::PluginWindowX11* w ) { m_pluginWindow.reset( QWindow::fromWinId( (WId) w->getWindow() ) ); vlcOpen(); m_quickViewPtr.reset( new QQuickView( m_pluginWindow.data() ) ); m_quickViewPtr->setTitle( QStringLiteral( "WebChimera" ) ); m_quickViewPtr->setResizeMode( QQuickView::SizeRootObjectToView ); m_quickViewPtr->setFlags( m_quickViewPtr->flags() | Qt::FramelessWindowHint ); m_quickViewPtr->setColor( get_bgColor() ); connect( this, &QmlChimera::bgcolorChanged, m_quickViewPtr.data(), &QQuickView::setColor ); m_qmlVlcPlayer = new QmlVlcSurfacePlayerProxy( (vlc::player*)this, m_quickViewPtr.data() ); m_qmlVlcPlayer->classBegin(); //have to call applyPlayerOptions() //after QmlVlcSurfacePlayerProxy::classBegin //to allow attach Proxy's vmem to plugin before play applyPlayerOptions(); //simulate resize //onWindowResized( 0, w ); setQml(); return false; } bool Chimera_X11::onWindowResized( FB::ResizedEvent*, FB::PluginWindowX11* w ) { const int newWidth = w->getWindowWidth(); const int newHeight = w->getWindowHeight(); if( m_quickViewPtr && !isFullscreen() ) { if( newWidth > 0 && newHeight > 0 ) { if( !m_quickViewPtr->isVisible() ) m_quickViewPtr->show(); m_quickViewPtr->setX( 0 ); m_quickViewPtr->setY( 0 ); m_quickViewPtr->resize( newWidth, newHeight ); } else m_quickViewPtr->hide(); } return false; } bool Chimera_X11::onWindowDetached( FB::DetachedEvent*, FB::PluginWindowX11* ) { m_quickViewPtr.reset(); m_pluginWindow.reset(); return false; } <commit_msg>X11: unused #include removed<commit_after>/***************************************************************************** * Copyright © 2014 Sergey Radionov <rsatom_gmail.com> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "Chimera_X11.h" #include "QmlVlc/QmlVlcSurfacePlayerProxy.h" //////////////////////////////////////////////////////////////////////////////// //Chimera_X11 class //////////////////////////////////////////////////////////////////////////////// Chimera_X11::Chimera_X11() { } Chimera_X11::~Chimera_X11() { } bool Chimera_X11::onX11Event( FB::X11Event* evt, FB::PluginWindowX11* w ) { if( GDK_MAP == evt->m_event->type ) { onWindowResized( 0, w ); } return false; } bool Chimera_X11::onWindowAttached( FB::AttachedEvent* evt, FB::PluginWindowX11* w ) { m_pluginWindow.reset( QWindow::fromWinId( (WId) w->getWindow() ) ); vlcOpen(); m_quickViewPtr.reset( new QQuickView( m_pluginWindow.data() ) ); m_quickViewPtr->setTitle( QStringLiteral( "WebChimera" ) ); m_quickViewPtr->setResizeMode( QQuickView::SizeRootObjectToView ); m_quickViewPtr->setFlags( m_quickViewPtr->flags() | Qt::FramelessWindowHint ); m_quickViewPtr->setColor( get_bgColor() ); connect( this, &QmlChimera::bgcolorChanged, m_quickViewPtr.data(), &QQuickView::setColor ); m_qmlVlcPlayer = new QmlVlcSurfacePlayerProxy( (vlc::player*)this, m_quickViewPtr.data() ); m_qmlVlcPlayer->classBegin(); //have to call applyPlayerOptions() //after QmlVlcSurfacePlayerProxy::classBegin //to allow attach Proxy's vmem to plugin before play applyPlayerOptions(); //simulate resize //onWindowResized( 0, w ); setQml(); return false; } bool Chimera_X11::onWindowResized( FB::ResizedEvent*, FB::PluginWindowX11* w ) { const int newWidth = w->getWindowWidth(); const int newHeight = w->getWindowHeight(); if( m_quickViewPtr && !isFullscreen() ) { if( newWidth > 0 && newHeight > 0 ) { if( !m_quickViewPtr->isVisible() ) m_quickViewPtr->show(); m_quickViewPtr->setX( 0 ); m_quickViewPtr->setY( 0 ); m_quickViewPtr->resize( newWidth, newHeight ); } else m_quickViewPtr->hide(); } return false; } bool Chimera_X11::onWindowDetached( FB::DetachedEvent*, FB::PluginWindowX11* ) { m_quickViewPtr.reset(); m_pluginWindow.reset(); return false; } <|endoftext|>
<commit_before>/* Copyright (C) 2019 European Spallation Source, ERIC. See LICENSE file */ //===----------------------------------------------------------------------===// /// /// \file /// /// \brief using nlohmann json parser to read calibrations from file //===----------------------------------------------------------------------===// #include <common/Log.h> #include <loki/geometry/Calibration.h> #include <common/JsonFile.h> namespace Loki { /// Calibration::Calibration() {}; Calibration::Calibration(std::string CalibrationFile) { nlohmann::json root = from_json_file(CalibrationFile); try { auto LokiCalibration = root["LokiCalibration"]; Mapping = LokiCalibration["Mapping"].get<std::vector<uint32_t>>(); } catch (...) { LOG(INIT, Sev::Error, "JSON calibration - error: Invalid Json file: {}", CalibrationFile); throw std::runtime_error("Invalid Json file"); return; } if (Mapping.size() <= 1) { throw std::runtime_error("Invalid Mapping array size"); } MaxPixelId = Mapping.size() - 1; } void Calibration::nullCalibration(uint32_t MaxPixels) { if (MaxPixels <= 1) { throw std::runtime_error("Invalid Mapping array size"); } Mapping.clear(); Mapping.reserve(MaxPixels); for (uint32_t i = 0; i <= MaxPixels; i++) { Mapping.push_back(i); } MaxPixelId = MaxPixels; } } // namespace Loki <commit_msg>compiler errors on linux<commit_after>/* Copyright (C) 2019 European Spallation Source, ERIC. See LICENSE file */ //===----------------------------------------------------------------------===// /// /// \file /// /// \brief using nlohmann json parser to read calibrations from file //===----------------------------------------------------------------------===// #include <common/Log.h> #include <loki/geometry/Calibration.h> #include <common/JsonFile.h> namespace Loki { /// Calibration::Calibration() {} Calibration::Calibration(std::string CalibrationFile) { nlohmann::json root = from_json_file(CalibrationFile); try { auto LokiCalibration = root["LokiCalibration"]; Mapping = LokiCalibration["Mapping"].get<std::vector<uint32_t>>(); } catch (...) { LOG(INIT, Sev::Error, "JSON calibration - error: Invalid Json file: {}", CalibrationFile); throw std::runtime_error("Invalid Json file"); return; } if (Mapping.size() <= 1) { throw std::runtime_error("Invalid Mapping array size"); } MaxPixelId = Mapping.size() - 1; } void Calibration::nullCalibration(uint32_t MaxPixels) { if (MaxPixels <= 1) { throw std::runtime_error("Invalid Mapping array size"); } Mapping.clear(); Mapping.reserve(MaxPixels); for (uint32_t i = 0; i <= MaxPixels; i++) { Mapping.push_back(i); } MaxPixelId = MaxPixels; } } // namespace Loki <|endoftext|>
<commit_before>// Copyright 2019 DeepMind Technologies Ltd. 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 "open_spiel/algorithms/dqn_torch/dqn.h" #include <torch/torch.h> #include <iostream> #include <memory> #include <string> #include <vector> #include <algorithm> #include "open_spiel/abseil-cpp/absl/random/random.h" #include "open_spiel/policy.h" #include "open_spiel/spiel.h" namespace open_spiel { namespace algorithms { namespace torch_dqn { constexpr const int kIllegalActionLogitsPenalty = -1e9; DQN::DQN(const DQNSettings& settings) : use_observation_(settings.use_observation), player_id_(settings.player_id), input_size_(settings.state_representation_size), num_actions_(settings.num_actions), hidden_layers_sizes_(settings.hidden_layers_sizes), batch_size_(settings.batch_size), update_target_network_every_(settings.update_target_network_every), learn_every_(settings.learn_every), min_buffer_size_to_learn_(settings.min_buffer_size_to_learn), discount_factor_(settings.discount_factor), epsilon_start_(settings.epsilon_start), epsilon_end_(settings.epsilon_end), epsilon_decay_duration_(settings.epsilon_decay_duration), replay_buffer_(settings.replay_buffer_capacity), q_network_(input_size_, hidden_layers_sizes_, num_actions_), target_q_network_(input_size_, hidden_layers_sizes_, num_actions_), optimizer_(q_network_->parameters(), torch::optim::SGDOptions(settings.learning_rate)), loss_str_(settings.loss_str), exists_prev_(false), prev_state_(nullptr), step_counter_(0) { } std::vector<float> DQN::GetInfoState(const State& state, Player player_id, bool use_observation) { if (use_observation) { return state.ObservationTensor(player_id); } else { return state.InformationStateTensor(player_id); } } Action DQN::Step(const State& state, bool is_evaluation, bool add_transition_record) { // Chance nodes should be handled externally to the agent. SPIEL_CHECK_TRUE(!state.IsChanceNode()); Action action; if (!state.IsTerminal() && state.CurrentPlayer() == player_id_) { std::vector<float> info_state = GetInfoState(state, player_id_, use_observation_); std::vector<Action> legal_actions = state.LegalActions(player_id_); double epsilon = GetEpsilon(is_evaluation); action = EpsilonGreedy(info_state, legal_actions, epsilon); } else { action = 0; } if (!is_evaluation) { step_counter_++; if (step_counter_ % learn_every_ == 0) { Learn(); } if (step_counter_ % update_target_network_every_ == 0) { torch::save(q_network_, "q_network.pt"); torch::load(target_q_network_, "q_network.pt"); } if (exists_prev_ && add_transition_record) { AddTransition(*prev_state_, prev_action_, state); } if (state.IsTerminal()) { exists_prev_ = false; prev_action_ = 0; return kInvalidAction; } else { exists_prev_ = true; prev_state_ = state.Clone(); prev_action_ = action; } } return action; } void DQN::AddTransition(const State& prev_state, Action prev_action, const State& state) { Transition transition = { /*info_state=*/GetInfoState(prev_state, player_id_, use_observation_), /*action=*/prev_action_, /*reward=*/state.PlayerReward(player_id_), /*next_info_state=*/GetInfoState(state, player_id_, use_observation_), /*is_final_step=*/state.IsTerminal(), /*legal_actions_mask=*/state.LegalActionsMask()}; replay_buffer_.Add(transition); } Action DQN::EpsilonGreedy(std::vector<float> info_state, std::vector<Action> legal_actions, double epsilon) { Action action; if (absl::Uniform(rng_, 0.0, 1.0) < epsilon) { ActionsAndProbs actions_probs; std::vector<double> probs(legal_actions.size(), 1.0/legal_actions.size()); for (int i = 0; i < legal_actions.size(); i++) { actions_probs.push_back({legal_actions[i], probs[i]}); } action = SampleAction(actions_probs, rng_).first; } else { torch::Tensor info_state_tensor = torch::from_blob( info_state.data(), {info_state.size()}, torch::TensorOptions().dtype(torch::kFloat32)).view({1, -1}); torch::Tensor q_value = q_network_->forward(info_state_tensor); torch::Tensor legal_actions_mask = torch::full({legal_actions.size()}, kIllegalActionLogitsPenalty, torch::TensorOptions().dtype(torch::kFloat32)); for (Action a : legal_actions) { legal_actions_mask[a] = 0; } action = (q_value.detach() + legal_actions_mask).argmax(1).item().toInt(); } return action; } double DQN::GetEpsilon(bool is_evaluation, int power) { if (is_evaluation) { return 0.0; } double decay_steps = std::min( static_cast<double>(step_counter_), epsilon_decay_duration_); double decayed_epsilon = ( epsilon_end_ + (epsilon_start_ - epsilon_end_) * std::pow((1 - decay_steps / epsilon_decay_duration_), power)); return decayed_epsilon; } void DQN::Learn() { if (replay_buffer_.Size() < batch_size_ || replay_buffer_.Size() < min_buffer_size_to_learn_) return; std::vector<Transition> transition = replay_buffer_.Sample(&rng_, batch_size_); std::vector<torch::Tensor> info_states; std::vector<torch::Tensor> next_info_states; std::vector<torch::Tensor> legal_actions_mask; std::vector<Action> actions; std::vector<float> rewards; std::vector<int> are_final_steps; for (auto t : transition) { info_states.push_back( torch::from_blob( t.info_state.data(), {1, t.info_state.size()}, torch::TensorOptions().dtype(torch::kFloat32)).clone()); next_info_states.push_back( torch::from_blob( t.next_info_state.data(), {1, t.next_info_state.size()}, torch::TensorOptions().dtype(torch::kFloat32)).clone()); legal_actions_mask.push_back( torch::from_blob( t.legal_actions_mask.data(), {1, t.legal_actions_mask.size()}, torch::TensorOptions().dtype(torch::kFloat32)) .to(torch::kInt64).clone()); actions.push_back(t.action); rewards.push_back(t.reward); are_final_steps.push_back(t.is_final_step); } torch::Tensor info_states_tensor = torch::stack(info_states, 0); torch::Tensor next_info_states_tensor = torch::stack(next_info_states, 0); torch::Tensor q_values = q_network_->forward(info_states_tensor); torch::Tensor target_q_values = target_q_network_->forward( next_info_states_tensor).detach(); torch::Tensor legal_action_masks_tensor = torch::stack(legal_actions_mask, 0); torch::Tensor illegal_actions = 1.0 - legal_action_masks_tensor; torch::Tensor illegal_logits = illegal_actions * kIllegalActionLogitsPenalty; torch::Tensor max_next_q = std::get<0>( torch::max(target_q_values + illegal_logits, 2)); torch::Tensor are_final_steps_tensor = torch::from_blob( are_final_steps.data(), {batch_size_}, torch::TensorOptions().dtype(torch::kInt32)).to(torch::kFloat32); torch::Tensor rewards_tensor = torch::from_blob( rewards.data(), {batch_size_}, torch::TensorOptions().dtype(torch::kFloat32)); torch::Tensor target = rewards_tensor + ( 1.0 - are_final_steps_tensor) * max_next_q.squeeze(1) * discount_factor_; torch::Tensor actions_tensor = torch::from_blob( actions.data(), {batch_size_}, torch::TensorOptions().dtype(torch::kInt64)); torch::Tensor predictions = q_values.index( {torch::arange(q_values.size(0)), torch::indexing::Slice(), actions_tensor}); optimizer_.zero_grad(); torch::Tensor value_loss; if (loss_str_ == "mse") { torch::nn::MSELoss mse_loss; value_loss = mse_loss(predictions.squeeze(1), target); } else if (loss_str_ == "huber") { torch::nn::SmoothL1Loss l1_loss; value_loss = l1_loss(predictions.squeeze(1), target); } else { SpielFatalError("Not implemented, choose from 'mse', 'huber'."); } value_loss.backward(); optimizer_.step(); } } // namespace torch_dqn } // namespace algorithms } // namespace open_spiel <commit_msg>More changes from @Asugara<commit_after>// Copyright 2019 DeepMind Technologies Ltd. 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 "open_spiel/algorithms/dqn_torch/dqn.h" #include <torch/torch.h> #include <iostream> #include <memory> #include <string> #include <vector> #include <algorithm> #include "open_spiel/abseil-cpp/absl/random/random.h" #include "open_spiel/policy.h" #include "open_spiel/spiel.h" namespace open_spiel { namespace algorithms { namespace torch_dqn { constexpr const int kIllegalActionLogitsPenalty = -1e9; DQN::DQN(const DQNSettings& settings) : use_observation_(settings.use_observation), player_id_(settings.player_id), input_size_(settings.state_representation_size), num_actions_(settings.num_actions), hidden_layers_sizes_(settings.hidden_layers_sizes), batch_size_(settings.batch_size), update_target_network_every_(settings.update_target_network_every), learn_every_(settings.learn_every), min_buffer_size_to_learn_(settings.min_buffer_size_to_learn), discount_factor_(settings.discount_factor), epsilon_start_(settings.epsilon_start), epsilon_end_(settings.epsilon_end), epsilon_decay_duration_(settings.epsilon_decay_duration), replay_buffer_(settings.replay_buffer_capacity), q_network_(input_size_, hidden_layers_sizes_, num_actions_), target_q_network_(input_size_, hidden_layers_sizes_, num_actions_), optimizer_(q_network_->parameters(), torch::optim::SGDOptions(settings.learning_rate)), loss_str_(settings.loss_str), exists_prev_(false), prev_state_(nullptr), step_counter_(0) { } std::vector<float> DQN::GetInfoState(const State& state, Player player_id, bool use_observation) { if (use_observation) { return state.ObservationTensor(player_id); } else { return state.InformationStateTensor(player_id); } } Action DQN::Step(const State& state, bool is_evaluation, bool add_transition_record) { // Chance nodes should be handled externally to the agent. SPIEL_CHECK_TRUE(!state.IsChanceNode()); Action action; if (!state.IsTerminal() && state.CurrentPlayer() == player_id_) { std::vector<float> info_state = GetInfoState(state, player_id_, use_observation_); std::vector<Action> legal_actions = state.LegalActions(player_id_); double epsilon = GetEpsilon(is_evaluation); action = EpsilonGreedy(info_state, legal_actions, epsilon); } else { action = 0; } if (!is_evaluation) { step_counter_++; if (step_counter_ % learn_every_ == 0) { Learn(); } if (step_counter_ % update_target_network_every_ == 0) { torch::save(q_network_, "q_network.pt"); torch::load(target_q_network_, "q_network.pt"); } if (exists_prev_ && add_transition_record) { AddTransition(*prev_state_, prev_action_, state); } if (state.IsTerminal()) { exists_prev_ = false; prev_action_ = 0; return kInvalidAction; } else { exists_prev_ = true; prev_state_ = state.Clone(); prev_action_ = action; } } return action; } void DQN::AddTransition(const State& prev_state, Action prev_action, const State& state) { Transition transition = { /*info_state=*/GetInfoState(prev_state, player_id_, use_observation_), /*action=*/prev_action_, /*reward=*/state.PlayerReward(player_id_), /*next_info_state=*/GetInfoState(state, player_id_, use_observation_), /*is_final_step=*/state.IsTerminal(), /*legal_actions_mask=*/state.LegalActionsMask()}; replay_buffer_.Add(transition); } Action DQN::EpsilonGreedy(std::vector<float> info_state, std::vector<Action> legal_actions, double epsilon) { Action action; if (absl::Uniform(rng_, 0.0, 1.0) < epsilon) { ActionsAndProbs actions_probs; std::vector<double> probs(legal_actions.size(), 1.0/legal_actions.size()); for (int i = 0; i < legal_actions.size(); i++) { actions_probs.push_back({legal_actions[i], probs[i]}); } action = SampleAction(actions_probs, rng_).first; } else { torch::Tensor info_state_tensor = torch::from_blob( info_state.data(), {info_state.size()}, torch::TensorOptions().dtype(torch::kFloat32)).view({1, -1}); q_network_->eval(); torch::Tensor q_value = q_network_->forward(info_state_tensor); torch::Tensor legal_actions_mask = torch::full({legal_actions.size()}, kIllegalActionLogitsPenalty, torch::TensorOptions().dtype(torch::kFloat32)); for (Action a : legal_actions) { legal_actions_mask[a] = 0; } action = (q_value.detach() + legal_actions_mask).argmax(1).item().toInt(); } return action; } double DQN::GetEpsilon(bool is_evaluation, int power) { if (is_evaluation) { return 0.0; } double decay_steps = std::min( static_cast<double>(step_counter_), epsilon_decay_duration_); double decayed_epsilon = ( epsilon_end_ + (epsilon_start_ - epsilon_end_) * std::pow((1 - decay_steps / epsilon_decay_duration_), power)); return decayed_epsilon; } void DQN::Learn() { if (replay_buffer_.Size() < batch_size_ || replay_buffer_.Size() < min_buffer_size_to_learn_) return; std::vector<Transition> transition = replay_buffer_.Sample(&rng_, batch_size_); std::vector<torch::Tensor> info_states; std::vector<torch::Tensor> next_info_states; std::vector<torch::Tensor> legal_actions_mask; std::vector<Action> actions; std::vector<float> rewards; std::vector<int> are_final_steps; for (auto t : transition) { info_states.push_back( torch::from_blob( t.info_state.data(), {1, t.info_state.size()}, torch::TensorOptions().dtype(torch::kFloat32)).clone()); next_info_states.push_back( torch::from_blob( t.next_info_state.data(), {1, t.next_info_state.size()}, torch::TensorOptions().dtype(torch::kFloat32)).clone()); legal_actions_mask.push_back( torch::from_blob( t.legal_actions_mask.data(), {1, t.legal_actions_mask.size()}, torch::TensorOptions().dtype(torch::kInt32)) .to(torch::kInt64).clone()); actions.push_back(t.action); rewards.push_back(t.reward); are_final_steps.push_back(t.is_final_step); } torch::Tensor info_states_tensor = torch::stack(info_states, 0); torch::Tensor next_info_states_tensor = torch::stack(next_info_states, 0); q_network_->train(); torch::Tensor q_values = q_network_->forward(info_states_tensor); target_q_network_->eval(); torch::Tensor target_q_values = target_q_network_->forward( next_info_states_tensor).detach(); torch::Tensor legal_action_masks_tensor = torch::stack(legal_actions_mask, 0); torch::Tensor illegal_actions = 1.0 - legal_action_masks_tensor; torch::Tensor illegal_logits = illegal_actions * kIllegalActionLogitsPenalty; torch::Tensor max_next_q = std::get<0>( torch::max(target_q_values + illegal_logits, 2)); torch::Tensor are_final_steps_tensor = torch::from_blob( are_final_steps.data(), {batch_size_}, torch::TensorOptions().dtype(torch::kInt32)).to(torch::kFloat32); torch::Tensor rewards_tensor = torch::from_blob( rewards.data(), {batch_size_}, torch::TensorOptions().dtype(torch::kFloat32)); torch::Tensor target = rewards_tensor + ( 1.0 - are_final_steps_tensor) * max_next_q.squeeze(1) * discount_factor_; torch::Tensor actions_tensor = torch::from_blob( actions.data(), {batch_size_}, torch::TensorOptions().dtype(torch::kInt64)); torch::Tensor predictions = q_values.index( {torch::arange(q_values.size(0)), torch::indexing::Slice(), actions_tensor}); optimizer_.zero_grad(); torch::Tensor value_loss; if (loss_str_ == "mse") { torch::nn::MSELoss mse_loss; value_loss = mse_loss(predictions.squeeze(1), target); } else if (loss_str_ == "huber") { torch::nn::SmoothL1Loss l1_loss; value_loss = l1_loss(predictions.squeeze(1), target); } else { SpielFatalError("Not implemented, choose from 'mse', 'huber'."); } value_loss.backward(); optimizer_.step(); } } // namespace torch_dqn } // namespace algorithms } // namespace open_spiel <|endoftext|>
<commit_before>/* * Copyright (c) 2003-2005 The Regents of The University of Michigan * Copyright (c) 2007 MIPS Technologies, 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 the copyright holders 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. * * Authors: Gabe Black * Korey Sewell * Jaidev Patwardhan */ #ifndef __MIPS_FAULTS_HH__ #define __MIPS_FAULTS_HH__ #include "sim/faults.hh" namespace MipsISA { typedef const Addr FaultVect; class MipsFaultBase : public FaultBase { protected: virtual bool skipFaultingInstruction() {return false;} virtual bool setRestartAddress() {return true;} public: struct FaultVals { const FaultName name; const FaultVect vect; FaultStat count; }; Addr badVAddr; Addr entryHiAsid; Addr entryHiVPN2; Addr entryHiVPN2X; Addr contextBadVPN2; #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInst::StaticInstPtr inst = StaticInst::nullStaticInstPtr) {} void setExceptionState(ThreadContext *, uint8_t); void setHandlerPC(Addr, ThreadContext *); #endif }; template <typename T> class MipsFault : public MipsFaultBase { protected: static FaultVals vals; public: FaultName name() const { return vals.name; } FaultVect vect() const { return vals.vect; } FaultStat & countStat() { return vals.count; } }; class MachineCheckFault : public MipsFault<MachineCheckFault> { public: bool isMachineCheckFault() {return true;} }; static inline Fault genMachineCheckFault() { return new MachineCheckFault; } class NonMaskableInterrupt : public MipsFault<NonMaskableInterrupt> { public: bool isNonMaskableInterrupt() {return true;} }; class AddressErrorFault : public MipsFault<AddressErrorFault> { protected: Addr vaddr; bool store; public: AddressErrorFault(Addr _vaddr, bool _store) : vaddr(_vaddr), store(_store) {} #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class ResetFault : public MipsFault<ResetFault> { public: void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); }; class SystemCallFault : public MipsFault<SystemCallFault> { public: #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class SoftResetFault : public MipsFault<SoftResetFault> { public: void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); }; class CoprocessorUnusableFault : public MipsFault<CoprocessorUnusableFault> { protected: int coProcID; public: CoprocessorUnusableFault(int _procid) : coProcID(_procid) {} void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); }; class ReservedInstructionFault : public MipsFault<ReservedInstructionFault> { public: void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); }; class ThreadFault : public MipsFault<ThreadFault> { public: void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); }; class IntegerOverflowFault : public MipsFault<IntegerOverflowFault> { protected: bool skipFaultingInstruction() {return true;} public: #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class InterruptFault : public MipsFault<InterruptFault> { protected: bool setRestartAddress() {return false;} public: #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class TrapFault : public MipsFault<TrapFault> { public: #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class BreakpointFault : public MipsFault<BreakpointFault> { public: #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class ItbRefillFault : public MipsFault<ItbRefillFault> { public: ItbRefillFault(Addr asid, Addr vaddr, Addr vpn) { entryHiAsid = asid; entryHiVPN2 = vpn >> 2; entryHiVPN2X = vpn & 0x3; badVAddr = vaddr; contextBadVPN2 = vpn >> 2; } #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class DtbRefillFault : public MipsFault<DtbRefillFault> { public: DtbRefillFault(Addr asid, Addr vaddr, Addr vpn) { entryHiAsid = asid; entryHiVPN2 = vpn >> 2; entryHiVPN2X = vpn & 0x3; badVAddr = vaddr; contextBadVPN2 = vpn >> 2; } #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class ItbInvalidFault : public MipsFault<ItbInvalidFault> { public: ItbInvalidFault(Addr asid, Addr vaddr, Addr vpn) { entryHiAsid = asid; entryHiVPN2 = vpn >> 2; entryHiVPN2X = vpn & 0x3; badVAddr = vaddr; contextBadVPN2 = vpn >> 2; } #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class TLBModifiedFault : public MipsFault<TLBModifiedFault> { public: TLBModifiedFault(Addr asid, Addr vaddr, Addr vpn) { entryHiAsid = asid; entryHiVPN2 = vpn >> 2; entryHiVPN2X = vpn & 0x3; badVAddr = vaddr; contextBadVPN2 = vpn >> 2; } #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class DtbInvalidFault : public MipsFault<DtbInvalidFault> { public: DtbInvalidFault(Addr asid, Addr vaddr, Addr vpn) { entryHiAsid = asid; entryHiVPN2 = vpn >> 2; entryHiVPN2X = vpn & 0x3; badVAddr = vaddr; contextBadVPN2 = vpn >> 2; } #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInst::StaticInstPtr inst = nullStaticInstPtr); #endif }; class DspStateDisabledFault : public MipsFault<DspStateDisabledFault> { public: void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); }; } // namespace MipsISA #endif // __MIPS_FAULTS_HH__ <commit_msg>MIPS: Get rid of the unused "count" field in FaultVals.<commit_after>/* * Copyright (c) 2003-2005 The Regents of The University of Michigan * Copyright (c) 2007 MIPS Technologies, 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 the copyright holders 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. * * Authors: Gabe Black * Korey Sewell * Jaidev Patwardhan */ #ifndef __MIPS_FAULTS_HH__ #define __MIPS_FAULTS_HH__ #include "sim/faults.hh" namespace MipsISA { typedef const Addr FaultVect; class MipsFaultBase : public FaultBase { protected: virtual bool skipFaultingInstruction() {return false;} virtual bool setRestartAddress() {return true;} public: struct FaultVals { const FaultName name; const FaultVect vect; }; Addr badVAddr; Addr entryHiAsid; Addr entryHiVPN2; Addr entryHiVPN2X; Addr contextBadVPN2; #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInst::StaticInstPtr inst = StaticInst::nullStaticInstPtr) {} void setExceptionState(ThreadContext *, uint8_t); void setHandlerPC(Addr, ThreadContext *); #endif }; template <typename T> class MipsFault : public MipsFaultBase { protected: static FaultVals vals; public: FaultName name() const { return vals.name; } FaultVect vect() const { return vals.vect; } }; class MachineCheckFault : public MipsFault<MachineCheckFault> { public: bool isMachineCheckFault() {return true;} }; static inline Fault genMachineCheckFault() { return new MachineCheckFault; } class NonMaskableInterrupt : public MipsFault<NonMaskableInterrupt> { public: bool isNonMaskableInterrupt() {return true;} }; class AddressErrorFault : public MipsFault<AddressErrorFault> { protected: Addr vaddr; bool store; public: AddressErrorFault(Addr _vaddr, bool _store) : vaddr(_vaddr), store(_store) {} #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class ResetFault : public MipsFault<ResetFault> { public: void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); }; class SystemCallFault : public MipsFault<SystemCallFault> { public: #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class SoftResetFault : public MipsFault<SoftResetFault> { public: void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); }; class CoprocessorUnusableFault : public MipsFault<CoprocessorUnusableFault> { protected: int coProcID; public: CoprocessorUnusableFault(int _procid) : coProcID(_procid) {} void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); }; class ReservedInstructionFault : public MipsFault<ReservedInstructionFault> { public: void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); }; class ThreadFault : public MipsFault<ThreadFault> { public: void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); }; class IntegerOverflowFault : public MipsFault<IntegerOverflowFault> { protected: bool skipFaultingInstruction() {return true;} public: #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class InterruptFault : public MipsFault<InterruptFault> { protected: bool setRestartAddress() {return false;} public: #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class TrapFault : public MipsFault<TrapFault> { public: #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class BreakpointFault : public MipsFault<BreakpointFault> { public: #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class ItbRefillFault : public MipsFault<ItbRefillFault> { public: ItbRefillFault(Addr asid, Addr vaddr, Addr vpn) { entryHiAsid = asid; entryHiVPN2 = vpn >> 2; entryHiVPN2X = vpn & 0x3; badVAddr = vaddr; contextBadVPN2 = vpn >> 2; } #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class DtbRefillFault : public MipsFault<DtbRefillFault> { public: DtbRefillFault(Addr asid, Addr vaddr, Addr vpn) { entryHiAsid = asid; entryHiVPN2 = vpn >> 2; entryHiVPN2X = vpn & 0x3; badVAddr = vaddr; contextBadVPN2 = vpn >> 2; } #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class ItbInvalidFault : public MipsFault<ItbInvalidFault> { public: ItbInvalidFault(Addr asid, Addr vaddr, Addr vpn) { entryHiAsid = asid; entryHiVPN2 = vpn >> 2; entryHiVPN2X = vpn & 0x3; badVAddr = vaddr; contextBadVPN2 = vpn >> 2; } #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class TLBModifiedFault : public MipsFault<TLBModifiedFault> { public: TLBModifiedFault(Addr asid, Addr vaddr, Addr vpn) { entryHiAsid = asid; entryHiVPN2 = vpn >> 2; entryHiVPN2X = vpn & 0x3; badVAddr = vaddr; contextBadVPN2 = vpn >> 2; } #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class DtbInvalidFault : public MipsFault<DtbInvalidFault> { public: DtbInvalidFault(Addr asid, Addr vaddr, Addr vpn) { entryHiAsid = asid; entryHiVPN2 = vpn >> 2; entryHiVPN2X = vpn & 0x3; badVAddr = vaddr; contextBadVPN2 = vpn >> 2; } #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInst::StaticInstPtr inst = nullStaticInstPtr); #endif }; class DspStateDisabledFault : public MipsFault<DspStateDisabledFault> { public: void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); }; } // namespace MipsISA #endif // __MIPS_FAULTS_HH__ <|endoftext|>
<commit_before>/***************************************************************************** * Internal.hpp: Wraps an internal vlc type. ***************************************************************************** * Copyright © 2014 VideoLAN * * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifndef VLCPP_H #define VLCPP_H #include <cassert> #include <stdlib.h> #include <vlc/libvlc.h> #include <memory> #include <stdexcept> namespace VLC { /// /// @brief The Internal class is a helper to wrap a raw libvlc type in a common /// C++ type. /// template <typename T, typename Releaser = void(*)(T*)> class Internal { public: using InternalType = T; using InternalPtr = T*; using Pointer = std::shared_ptr<T>; /// /// \brief get returns the underlying libvlc type, or nullptr if this /// is an empty instance /// InternalPtr get() const { return m_obj.get(); } /// /// \brief isValid returns true if this instance isn't wrapping a nullptr /// \return /// bool isValid() const { return (bool)m_obj; } /// /// \brief operator T * helper to convert to the underlying libvlc type /// operator T*() const { return m_obj.get(); } protected: Internal() = default; Internal( InternalPtr obj, Releaser releaser ) : m_obj{ obj, releaser } { } Internal(Releaser releaser) : m_obj{ nullptr, releaser } { } protected: Pointer m_obj; }; } #endif // VLCPP_H <commit_msg>Revert "Internal: Don't throw when wrapping a null instance"<commit_after>/***************************************************************************** * Internal.hpp: Wraps an internal vlc type. ***************************************************************************** * Copyright © 2014 VideoLAN * * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifndef VLCPP_H #define VLCPP_H #include <cassert> #include <stdlib.h> #include <vlc/libvlc.h> #include <memory> #include <stdexcept> namespace VLC { /// /// @brief The Internal class is a helper to wrap a raw libvlc type in a common /// C++ type. /// template <typename T, typename Releaser = void(*)(T*)> class Internal { public: using InternalType = T; using InternalPtr = T*; using Pointer = std::shared_ptr<T>; /// /// \brief get returns the underlying libvlc type, or nullptr if this /// is an empty instance /// InternalPtr get() const { return m_obj.get(); } /// /// \brief isValid returns true if this instance isn't wrapping a nullptr /// \return /// bool isValid() const { return (bool)m_obj; } /// /// \brief operator T * helper to convert to the underlying libvlc type /// operator T*() const { return m_obj.get(); } protected: Internal() = default; Internal( InternalPtr obj, Releaser releaser ) : m_obj{ obj, releaser } { if ( obj == nullptr ) throw std::runtime_error("Wrapping a NULL instance"); } Internal(Releaser releaser) : m_obj{ nullptr, releaser } { } protected: Pointer m_obj; }; } #endif // VLCPP_H <|endoftext|>
<commit_before>#ifndef RBX_CAPI_HANDLE_HPP #define RBX_CAPI_HANDLE_HPP #include "detection.hpp" #ifdef OS_X_10_5 #ifndef RBX_HAVE_TR1_HASH #include "missing/leopard_hashtable.hpp" #endif #endif #include "vm.hpp" #include "gc/root.hpp" #include "capi/value.hpp" #include <tr1/unordered_set> #ifndef RIO #define RIO rb_io_t #endif struct RArray; struct RString; struct RData; struct RFloat; struct RIO; struct RFile; namespace rubinius { class NativeMethodEnvironment; namespace capi { enum HandleType { cUnknown, cRArray, cRString, cRData, cRFloat, cRIO, cRFile }; class Handle { Object* object_; HandleType type_; int references_; unsigned int checksum_; typedef void (*CApiCacheFlusher)(NativeMethodEnvironment* env, Handle* handle); typedef void (*CApiCacheUpdater)(NativeMethodEnvironment* env, Handle* handle); CApiCacheFlusher flush_; CApiCacheUpdater update_; union { RArray* rarray; RString* rstring; RData* rdata; RFloat* rfloat; RIO* rio; RFile* rfile; uintptr_t next_index_; intptr_t cache_data; } as_; public: Handle() : object_(NULL) , type_(cUnknown) , references_(0) , checksum_(0) , flush_(0) , update_(0) { as_.cache_data = 0; } static bool valid_handle_p(STATE, Handle* handle); void flush(NativeMethodEnvironment* env) { if(flush_) (*flush_)(env, this); } void update(NativeMethodEnvironment* env) { if(update_) (*update_)(env, this); } #define RBX_CAPI_HANDLE_CHECKSUM 0xffff bool valid_p() const { return checksum_ == RBX_CAPI_HANDLE_CHECKSUM; } void validate() { checksum_ = RBX_CAPI_HANDLE_CHECKSUM; } void invalidate() { checksum_ = 0; } Object* object() const { return object_; } bool in_use_p() const { return object_ != 0; } void set_object(Object* obj) { object_ = obj; } bool weak_p() const { return references_ == 0; } void ref() { references_++; } void deref() { references_--; } void debug_print(); // Explict conversion functions, to keep the code clean. VALUE as_value() const { return reinterpret_cast<VALUE>(this); } static Handle* from(VALUE val) { return reinterpret_cast<Handle*>(val); } bool is_rarray() const { return type_ == cRArray; } bool is_rdata() const { return type_ == cRData; } bool is_rstring() const { return type_ == cRString; } bool is_rfloat() const { return type_ == cRFloat; } bool is_rio() const { return type_ == cRIO; } bool is_rfile() const { return type_ == cRFile; } HandleType type() const { return type_; } void clear() { forget_object(); type_ = cUnknown; references_ = 0; flush_ = 0; update_ = 0; } void forget_object() { free_data(); invalidate(); object_ = 0; } RString* get_rstring() const { return as_.rstring; } uintptr_t next() const { return as_.next_index_; } void set_next(uintptr_t next_index) { as_.next_index_ = next_index; } RData* as_rdata(NativeMethodEnvironment* env); RArray* as_rarray(NativeMethodEnvironment* env); RString* as_rstring(NativeMethodEnvironment* env, int cache_level); RFloat* as_rfloat(NativeMethodEnvironment* env); RIO* as_rio(NativeMethodEnvironment* env); RFile* as_rfile(NativeMethodEnvironment* env); void free_data(); bool rio_close(); }; class GlobalHandle { private: Handle** handle_; const char* file_; int line_; public: GlobalHandle(Handle** handle, const char* file, int line) : handle_(handle) , file_(file) , line_(line) {} GlobalHandle(Handle** handle) : handle_(handle) , file_(NULL) , line_(0) {} Handle** handle() { return handle_; } const char* file() { return file_; } int line() { return line_; } }; typedef std::tr1::unordered_set<Handle*> SlowHandleSet; class HandleSet { public: const static int cFastHashSize = 16; private: SlowHandleSet* slow_; Handle* table_[cFastHashSize]; public: HandleSet(); ~HandleSet() { if(slow_) delete slow_; } void deref_all(); void flush_all(NativeMethodEnvironment* env); void update_all(NativeMethodEnvironment* env); bool add_if_absent(Handle* handle) { // ref() ONLY if it's not already in there! // otherwise the refcount is wrong and we leak handles. if(unlikely(slow_)) { return slow_add_if_absent(handle); } else { for(int i = 0; i < cFastHashSize; i++) { if(!table_[i]) { table_[i] = handle; handle->ref(); return true; } if(table_[i] == handle) return false; } make_slow_and_add(handle); return true; } } private: void make_slow_and_add(Handle* handle); bool slow_add_if_absent(Handle* handle); }; } } #endif <commit_msg>Use std::set since it never invalidates on insert()<commit_after>#ifndef RBX_CAPI_HANDLE_HPP #define RBX_CAPI_HANDLE_HPP #include "detection.hpp" #ifdef OS_X_10_5 #ifndef RBX_HAVE_TR1_HASH #include "missing/leopard_hashtable.hpp" #endif #endif #include "vm.hpp" #include "gc/root.hpp" #include "capi/value.hpp" #include <set> #ifndef RIO #define RIO rb_io_t #endif struct RArray; struct RString; struct RData; struct RFloat; struct RIO; struct RFile; namespace rubinius { class NativeMethodEnvironment; namespace capi { enum HandleType { cUnknown, cRArray, cRString, cRData, cRFloat, cRIO, cRFile }; class Handle { Object* object_; HandleType type_; int references_; unsigned int checksum_; typedef void (*CApiCacheFlusher)(NativeMethodEnvironment* env, Handle* handle); typedef void (*CApiCacheUpdater)(NativeMethodEnvironment* env, Handle* handle); CApiCacheFlusher flush_; CApiCacheUpdater update_; union { RArray* rarray; RString* rstring; RData* rdata; RFloat* rfloat; RIO* rio; RFile* rfile; uintptr_t next_index_; intptr_t cache_data; } as_; public: Handle() : object_(NULL) , type_(cUnknown) , references_(0) , checksum_(0) , flush_(0) , update_(0) { as_.cache_data = 0; } static bool valid_handle_p(STATE, Handle* handle); void flush(NativeMethodEnvironment* env) { if(flush_) (*flush_)(env, this); } void update(NativeMethodEnvironment* env) { if(update_) (*update_)(env, this); } #define RBX_CAPI_HANDLE_CHECKSUM 0xffff bool valid_p() const { return checksum_ == RBX_CAPI_HANDLE_CHECKSUM; } void validate() { checksum_ = RBX_CAPI_HANDLE_CHECKSUM; } void invalidate() { checksum_ = 0; } Object* object() const { return object_; } bool in_use_p() const { return object_ != 0; } void set_object(Object* obj) { object_ = obj; } bool weak_p() const { return references_ == 0; } void ref() { references_++; } void deref() { references_--; } void debug_print(); // Explict conversion functions, to keep the code clean. VALUE as_value() const { return reinterpret_cast<VALUE>(this); } static Handle* from(VALUE val) { return reinterpret_cast<Handle*>(val); } bool is_rarray() const { return type_ == cRArray; } bool is_rdata() const { return type_ == cRData; } bool is_rstring() const { return type_ == cRString; } bool is_rfloat() const { return type_ == cRFloat; } bool is_rio() const { return type_ == cRIO; } bool is_rfile() const { return type_ == cRFile; } HandleType type() const { return type_; } void clear() { forget_object(); type_ = cUnknown; references_ = 0; flush_ = 0; update_ = 0; } void forget_object() { free_data(); invalidate(); object_ = 0; } RString* get_rstring() const { return as_.rstring; } uintptr_t next() const { return as_.next_index_; } void set_next(uintptr_t next_index) { as_.next_index_ = next_index; } RData* as_rdata(NativeMethodEnvironment* env); RArray* as_rarray(NativeMethodEnvironment* env); RString* as_rstring(NativeMethodEnvironment* env, int cache_level); RFloat* as_rfloat(NativeMethodEnvironment* env); RIO* as_rio(NativeMethodEnvironment* env); RFile* as_rfile(NativeMethodEnvironment* env); void free_data(); bool rio_close(); }; class GlobalHandle { private: Handle** handle_; const char* file_; int line_; public: GlobalHandle(Handle** handle, const char* file, int line) : handle_(handle) , file_(file) , line_(line) {} GlobalHandle(Handle** handle) : handle_(handle) , file_(NULL) , line_(0) {} Handle** handle() { return handle_; } const char* file() { return file_; } int line() { return line_; } }; typedef std::set<Handle*> SlowHandleSet; class HandleSet { public: const static int cFastHashSize = 16; private: SlowHandleSet* slow_; Handle* table_[cFastHashSize]; public: HandleSet(); ~HandleSet() { if(slow_) delete slow_; } void deref_all(); void flush_all(NativeMethodEnvironment* env); void update_all(NativeMethodEnvironment* env); bool add_if_absent(Handle* handle) { // ref() ONLY if it's not already in there! // otherwise the refcount is wrong and we leak handles. if(unlikely(slow_)) { return slow_add_if_absent(handle); } else { for(int i = 0; i < cFastHashSize; i++) { if(!table_[i]) { table_[i] = handle; handle->ref(); return true; } if(table_[i] == handle) return false; } make_slow_and_add(handle); return true; } } private: void make_slow_and_add(Handle* handle); bool slow_add_if_absent(Handle* handle); }; } } #endif <|endoftext|>
<commit_before>/* An Environment is the toplevel class for Rubinius. It manages multiple * VMs, as well as imports C data from the process into Rubyland. */ #include "prelude.hpp" #include "environment.hpp" #include "config_parser.hpp" #include "compiled_file.hpp" #include "vm/exception.hpp" #include "builtin/array.hpp" #include "builtin/class.hpp" #include "builtin/exception.hpp" #include "builtin/string.hpp" #include "builtin/symbol.hpp" #include "builtin/module.hpp" #include "builtin/taskprobe.hpp" #ifdef ENABLE_LLVM #include "llvm/jit.hpp" #include <llvm/System/Threading.h> #endif #ifdef linux #include <execinfo.h> #endif #include "signal.hpp" #include "object_utils.hpp" #include "native_thread.hpp" #include "inline_cache.hpp" #include "agent.hpp" #include <iostream> #include <fstream> #include <sstream> #include <string> namespace rubinius { Environment::Environment() : agent(0) { #ifdef ENABLE_LLVM assert(llvm::llvm_start_multithreaded() && "llvm doesn't support threading!"); #endif shared = new SharedState(config, config_parser); state = shared->new_vm(); } Environment::~Environment() { VM::discard(state); SharedState::discard(shared); } void Environment::load_config_argv(int argc, char** argv) { config_parser.process_argv(argc, argv); config_parser.update_configuration(config); if(config.print_config > 1) { std::cout << "========= Configuration =========\n"; config.print(true); std::cout << "=================================\n"; } else if(config.print_config) { config.print(); } } void cpp_exception_bug() { std::cerr << "[BUG] Uncaught C++ internal exception\n"; std::cerr << "So sorry, it appears that you've encountered an internal\n"; std::cerr << "bug. Please report this on the rubinius issue tracker.\n"; std::cerr << "Include the following backtrace in the issue:\n\n"; rubinius::abort(); } void Environment::setup_cpp_terminate() { // Install a better terminate function to tell the user // there was a rubinius bug. std::set_terminate(cpp_exception_bug); } void Environment::enable_preemption() { state->setup_preemption(); } static void null_func(int sig) {} #ifdef linux static void segv_handler(int sig) { static int crashing = 0; void *array[32]; size_t size; // So we don't recurse! if(crashing) exit(101); crashing = 1; // print out all the frames to stderr static const char msg[] = "Error: signal "; if(write(2, msg, 14) == 0) exit(101); switch(sig) { case SIGSEGV: if(write(2, "SIGSEGV\n", 8) == 0) exit(101); break; case SIGBUS: if(write(2, "SIGBUS\n", 7) == 0) exit(101); break; case SIGILL: if(write(2, "SIGILL\n", 7) == 0) exit(101); break; case SIGABRT: if(write(2, "SIGABRT\n", 8) == 0) exit(101); break; case SIGFPE: if(write(2, "SIGFPE\n", 7) == 0) exit(101); break; default: if(write(2, "UNKNOWN\n", 8) == 0) exit(101); break; } // Try to get the output to flush... if(write(2, "\n\n", 2) == 0) exit(101); // get void*'s for all entries on the stack size = backtrace(array, 32); backtrace_symbols_fd(array, size, 2); // Try to get the output to flush... if(write(2, "\n\n", 2) == 0) exit(101); exit(100); } #endif static void quit_handler(int sig) { static const char msg[] = "Terminated: signal "; if(write(2, msg, sizeof(msg)) == 0) exit(1); switch(sig) { case SIGHUP: if(write(2, "SIGHUP\n", 6) == 0) exit(1); break; case SIGTERM: if(write(2, "SIGTERM\n", 7) == 0) exit(1); break; case SIGUSR1: if(write(2, "SIGUSR1\n", 7) == 0) exit(1); break; case SIGUSR2: if(write(2, "SIGUSR2\n", 7) == 0) exit(1); break; default: if(write(2, "UNKNOWN\n", 8) == 0) exit(1); break; } exit(1); } void Environment::start_signals() { struct sigaction action; action.sa_handler = null_func; action.sa_flags = SA_RESTART; sigfillset(&action.sa_mask); sigaction(NativeThread::cWakeupSignal, &action, NULL); state->set_run_signals(true); shared->set_signal_handler(new SignalHandler(state)); // Ignore sigpipe. signal(SIGPIPE, SIG_IGN); // On linux, setup some crash handlers #ifdef linux signal(SIGSEGV, segv_handler); signal(SIGBUS, segv_handler); signal(SIGILL, segv_handler); signal(SIGFPE, segv_handler); signal(SIGABRT, segv_handler); // Force glibc to load the shared library containing backtrace() // now, so that we don't have to try and load it in the signal // handler. void* ary[1]; backtrace(ary, 1); #endif // Setup some other signal that normally just cause the process // to terminate so that we print out a message, then terminate. signal(SIGHUP, quit_handler); signal(SIGTERM, quit_handler); signal(SIGUSR1, quit_handler); signal(SIGUSR2, quit_handler); } void Environment::load_argv(int argc, char** argv) { bool process_xflags = true; state->set_const("ARG0", String::create(state, argv[0])); Array* ary = Array::create(state, argc - 1); int which_arg = 0; for(int i=1; i < argc; i++) { char* arg = argv[i]; if(arg[0] != '-' || strcmp(arg, "--") == 0) { process_xflags = false; } if(!process_xflags || strncmp(arg, "-X", 2) != 0) { ary->set(state, which_arg++, String::create(state, arg)->taint(state)); } } state->set_const("ARGV", ary); } void Environment::load_directory(std::string dir) { std::string path = dir + "/load_order.txt"; std::ifstream stream(path.c_str()); if(!stream) { throw std::runtime_error("Unable to load directory, load_order.txt is missing"); } while(!stream.eof()) { std::string line; stream >> line; stream.get(); // eat newline // skip empty lines if(line.size() == 0) continue; run_file(dir + "/" + line); } } void Environment::load_platform_conf(std::string dir) { std::string path = dir + "/platform.conf"; std::ifstream stream(path.c_str()); if(!stream) { std::string error = "Unable to load " + path + ", it is missing"; throw std::runtime_error(error); } config_parser.import_stream(stream); } void Environment::load_conf(std::string path) { std::ifstream stream(path.c_str()); if(!stream) { std::string error = "Unable to load " + path + ", it is missing"; throw std::runtime_error(error); } config_parser.import_stream(stream); } void Environment::load_string(std::string str) { config_parser.import_many(str); } void Environment::boot_vm() { if(config.qa_port > 0) start_agent(config.qa_port); // Respect -Xint if(config.jit_force_off) { config.jit_enabled.set("no"); } state->initialize(); state->boot(); TaskProbe* probe = TaskProbe::create(state); state->probe.set(probe->parse_env(NULL) ? probe : (TaskProbe*)Qnil); } void Environment::run_file(std::string file) { if(!state->probe->nil_p()) state->probe->load_runtime(state, file); std::ifstream stream(file.c_str()); if(!stream) { std::string msg = std::string("Unable to open file to run: "); msg.append(file); throw std::runtime_error(msg); } CompiledFile* cf = CompiledFile::load(stream); if(cf->magic != "!RBIX") throw std::runtime_error("Invalid file"); /** @todo Redundant? CompiledFile::execute() does this. --rue */ state->thread_state()->clear_exception(true); // TODO check version number cf->execute(state); if(state->thread_state()->raise_reason() == cException) { Exception* exc = as<Exception>(state->thread_state()->raise_value()); std::ostringstream msg; msg << "exception detected at toplevel: "; if(!exc->message()->nil_p()) { if(String* str = try_as<String>(exc->message())) { msg << str->c_str(); } else { msg << "<non-string Exception message>"; } } else if(Exception::argument_error_p(state, exc)) { msg << "given " << as<Fixnum>(exc->get_ivar(state, state->symbol("@given")))->to_native() << ", expected " << as<Fixnum>(exc->get_ivar(state, state->symbol("@expected")))->to_native(); } msg << " (" << exc->klass()->name()->c_str(state) << ")"; std::cout << msg.str() << "\n"; exc->print_locations(state); Assertion::raise(msg.str().c_str()); } delete cf; } void Environment::halt() { if(state->shared.config.ic_stats) { state->shared.ic_registry()->print_stats(state); } #ifdef ENABLE_LLVM LLVMState::shutdown(state); #endif state->shared.stop_the_world(); } int Environment::exit_code() { if(state->thread_state()->raise_reason() == cExit) { if(Fixnum* fix = try_as<Fixnum>(state->thread_state()->raise_value())) { return fix->to_native(); } else { return -1; } } return 0; } void Environment::start_agent(int port) { agent = new QueryAgent(*shared, port); if(config.qa_verbose) agent->set_verbose(); agent->run(); } } <commit_msg>Not only setup segv_handler when on linux, but if execinfo.h is available<commit_after>/* An Environment is the toplevel class for Rubinius. It manages multiple * VMs, as well as imports C data from the process into Rubyland. */ #include "prelude.hpp" #include "environment.hpp" #include "config_parser.hpp" #include "compiled_file.hpp" #include "vm/exception.hpp" #include "builtin/array.hpp" #include "builtin/class.hpp" #include "builtin/exception.hpp" #include "builtin/string.hpp" #include "builtin/symbol.hpp" #include "builtin/module.hpp" #include "builtin/taskprobe.hpp" #ifdef ENABLE_LLVM #include "llvm/jit.hpp" #include <llvm/System/Threading.h> #endif #ifdef USE_EXECINFO #include <execinfo.h> #endif #include "signal.hpp" #include "object_utils.hpp" #include "native_thread.hpp" #include "inline_cache.hpp" #include "agent.hpp" #include <iostream> #include <fstream> #include <sstream> #include <string> namespace rubinius { Environment::Environment() : agent(0) { #ifdef ENABLE_LLVM assert(llvm::llvm_start_multithreaded() && "llvm doesn't support threading!"); #endif shared = new SharedState(config, config_parser); state = shared->new_vm(); } Environment::~Environment() { VM::discard(state); SharedState::discard(shared); } void Environment::load_config_argv(int argc, char** argv) { config_parser.process_argv(argc, argv); config_parser.update_configuration(config); if(config.print_config > 1) { std::cout << "========= Configuration =========\n"; config.print(true); std::cout << "=================================\n"; } else if(config.print_config) { config.print(); } } void cpp_exception_bug() { std::cerr << "[BUG] Uncaught C++ internal exception\n"; std::cerr << "So sorry, it appears that you've encountered an internal\n"; std::cerr << "bug. Please report this on the rubinius issue tracker.\n"; std::cerr << "Include the following backtrace in the issue:\n\n"; rubinius::abort(); } void Environment::setup_cpp_terminate() { // Install a better terminate function to tell the user // there was a rubinius bug. std::set_terminate(cpp_exception_bug); } void Environment::enable_preemption() { state->setup_preemption(); } static void null_func(int sig) {} #ifdef USE_EXECINFO static void segv_handler(int sig) { static int crashing = 0; void *array[32]; size_t size; // So we don't recurse! if(crashing) exit(101); crashing = 1; // print out all the frames to stderr static const char msg[] = "Error: signal "; if(write(2, msg, 14) == 0) exit(101); switch(sig) { case SIGSEGV: if(write(2, "SIGSEGV\n", 8) == 0) exit(101); break; case SIGBUS: if(write(2, "SIGBUS\n", 7) == 0) exit(101); break; case SIGILL: if(write(2, "SIGILL\n", 7) == 0) exit(101); break; case SIGABRT: if(write(2, "SIGABRT\n", 8) == 0) exit(101); break; case SIGFPE: if(write(2, "SIGFPE\n", 7) == 0) exit(101); break; default: if(write(2, "UNKNOWN\n", 8) == 0) exit(101); break; } // Try to get the output to flush... if(write(2, "\n\n", 2) == 0) exit(101); // get void*'s for all entries on the stack size = backtrace(array, 32); backtrace_symbols_fd(array, size, 2); // Try to get the output to flush... if(write(2, "\n\n", 2) == 0) exit(101); exit(100); } #endif static void quit_handler(int sig) { static const char msg[] = "Terminated: signal "; if(write(2, msg, sizeof(msg)) == 0) exit(1); switch(sig) { case SIGHUP: if(write(2, "SIGHUP\n", 6) == 0) exit(1); break; case SIGTERM: if(write(2, "SIGTERM\n", 7) == 0) exit(1); break; case SIGUSR1: if(write(2, "SIGUSR1\n", 7) == 0) exit(1); break; case SIGUSR2: if(write(2, "SIGUSR2\n", 7) == 0) exit(1); break; default: if(write(2, "UNKNOWN\n", 8) == 0) exit(1); break; } exit(1); } void Environment::start_signals() { struct sigaction action; action.sa_handler = null_func; action.sa_flags = SA_RESTART; sigfillset(&action.sa_mask); sigaction(NativeThread::cWakeupSignal, &action, NULL); state->set_run_signals(true); shared->set_signal_handler(new SignalHandler(state)); // Ignore sigpipe. signal(SIGPIPE, SIG_IGN); // If we have execinfo, setup some crash handlers #ifdef USE_EXECINFO signal(SIGSEGV, segv_handler); signal(SIGBUS, segv_handler); signal(SIGILL, segv_handler); signal(SIGFPE, segv_handler); signal(SIGABRT, segv_handler); // Force glibc to load the shared library containing backtrace() // now, so that we don't have to try and load it in the signal // handler. void* ary[1]; backtrace(ary, 1); #endif // Setup some other signal that normally just cause the process // to terminate so that we print out a message, then terminate. signal(SIGHUP, quit_handler); signal(SIGTERM, quit_handler); signal(SIGUSR1, quit_handler); signal(SIGUSR2, quit_handler); } void Environment::load_argv(int argc, char** argv) { bool process_xflags = true; state->set_const("ARG0", String::create(state, argv[0])); Array* ary = Array::create(state, argc - 1); int which_arg = 0; for(int i=1; i < argc; i++) { char* arg = argv[i]; if(arg[0] != '-' || strcmp(arg, "--") == 0) { process_xflags = false; } if(!process_xflags || strncmp(arg, "-X", 2) != 0) { ary->set(state, which_arg++, String::create(state, arg)->taint(state)); } } state->set_const("ARGV", ary); } void Environment::load_directory(std::string dir) { std::string path = dir + "/load_order.txt"; std::ifstream stream(path.c_str()); if(!stream) { throw std::runtime_error("Unable to load directory, load_order.txt is missing"); } while(!stream.eof()) { std::string line; stream >> line; stream.get(); // eat newline // skip empty lines if(line.size() == 0) continue; run_file(dir + "/" + line); } } void Environment::load_platform_conf(std::string dir) { std::string path = dir + "/platform.conf"; std::ifstream stream(path.c_str()); if(!stream) { std::string error = "Unable to load " + path + ", it is missing"; throw std::runtime_error(error); } config_parser.import_stream(stream); } void Environment::load_conf(std::string path) { std::ifstream stream(path.c_str()); if(!stream) { std::string error = "Unable to load " + path + ", it is missing"; throw std::runtime_error(error); } config_parser.import_stream(stream); } void Environment::load_string(std::string str) { config_parser.import_many(str); } void Environment::boot_vm() { if(config.qa_port > 0) start_agent(config.qa_port); // Respect -Xint if(config.jit_force_off) { config.jit_enabled.set("no"); } state->initialize(); state->boot(); TaskProbe* probe = TaskProbe::create(state); state->probe.set(probe->parse_env(NULL) ? probe : (TaskProbe*)Qnil); } void Environment::run_file(std::string file) { if(!state->probe->nil_p()) state->probe->load_runtime(state, file); std::ifstream stream(file.c_str()); if(!stream) { std::string msg = std::string("Unable to open file to run: "); msg.append(file); throw std::runtime_error(msg); } CompiledFile* cf = CompiledFile::load(stream); if(cf->magic != "!RBIX") throw std::runtime_error("Invalid file"); /** @todo Redundant? CompiledFile::execute() does this. --rue */ state->thread_state()->clear_exception(true); // TODO check version number cf->execute(state); if(state->thread_state()->raise_reason() == cException) { Exception* exc = as<Exception>(state->thread_state()->raise_value()); std::ostringstream msg; msg << "exception detected at toplevel: "; if(!exc->message()->nil_p()) { if(String* str = try_as<String>(exc->message())) { msg << str->c_str(); } else { msg << "<non-string Exception message>"; } } else if(Exception::argument_error_p(state, exc)) { msg << "given " << as<Fixnum>(exc->get_ivar(state, state->symbol("@given")))->to_native() << ", expected " << as<Fixnum>(exc->get_ivar(state, state->symbol("@expected")))->to_native(); } msg << " (" << exc->klass()->name()->c_str(state) << ")"; std::cout << msg.str() << "\n"; exc->print_locations(state); Assertion::raise(msg.str().c_str()); } delete cf; } void Environment::halt() { if(state->shared.config.ic_stats) { state->shared.ic_registry()->print_stats(state); } #ifdef ENABLE_LLVM LLVMState::shutdown(state); #endif state->shared.stop_the_world(); } int Environment::exit_code() { if(state->thread_state()->raise_reason() == cExit) { if(Fixnum* fix = try_as<Fixnum>(state->thread_state()->raise_value())) { return fix->to_native(); } else { return -1; } } return 0; } void Environment::start_agent(int port) { agent = new QueryAgent(*shared, port); if(config.qa_verbose) agent->set_verbose(); agent->run(); } } <|endoftext|>
<commit_before>#pragma once #include <cstdint> #include <array> #include <vector> #include <functional> #include "vm/utils.hpp" namespace yagbe { class palette_entry { public: palette_entry(uint8_t entry) : _entry(entry) { } uint8_t color_index(int i) const { return (_entry >> i*2) & 0b11; } yagbe::color color(int i) const { return colors()[color_index(i)]; } constexpr static std::array<yagbe::color, 4> black_white_colors() { return std::array<yagbe::color, 4>{ yagbe::color{ 250,250,250,255 }, yagbe::color{ 116,116,116,255 }, yagbe::color{ 188,188,188,255 }, yagbe::color{ 0,0,0,255 }, }; } constexpr static std::array<yagbe::color, 4> lcd_colors() { return std::array<yagbe::color, 4>{ yagbe::color{ 252,232,140,255 }, yagbe::color{ 152,124,60,255 }, yagbe::color{ 220,180,92,255 }, yagbe::color{ 76,60,28,255 }, }; } constexpr static std::array<yagbe::color, 4> colors() { return lcd_colors(); } protected: uint8_t _entry; }; class sprite_palette_entry { public: sprite_palette_entry(uint8_t entry) : _entry(entry) { } uint8_t color_index(int i) const { return (_entry >> i * 2) & 0b11; } yagbe::color color(int i) const { return colors()[color_index(i)]; } constexpr static std::array<yagbe::color, 4> colors() { return std::array<yagbe::color, 4>{ palette_entry::colors()[2], palette_entry::colors()[1], palette_entry::colors()[2], palette_entry::colors()[3], }; } protected: uint8_t _entry; }; };<commit_msg>fixed compilation on old gcc<commit_after>#pragma once #include <cstdint> #include <array> #include <vector> #include <functional> #include "vm/utils.hpp" namespace yagbe { class palette_entry { public: palette_entry(uint8_t entry) : _entry(entry) { } uint8_t color_index(int i) const { return (_entry >> i*2) & 0b11; } yagbe::color color(int i) const { return colors()[color_index(i)]; } constexpr static std::array<yagbe::color, 4> black_white_colors() { return std::array<yagbe::color, 4>{ yagbe::color{ 250,250,250,255 }, yagbe::color{ 116,116,116,255 }, yagbe::color{ 188,188,188,255 }, yagbe::color{ 0,0,0,255 }, }; } constexpr static std::array<yagbe::color, 4> lcd_colors() { return std::array<yagbe::color, 4>{ yagbe::color{ 252,232,140,255 }, yagbe::color{ 152,124,60,255 }, yagbe::color{ 220,180,92,255 }, yagbe::color{ 76,60,28,255 }, }; } constexpr static std::array<yagbe::color, 4> colors() { return lcd_colors(); } protected: uint8_t _entry; }; class sprite_palette_entry { public: sprite_palette_entry(uint8_t entry) : _entry(entry) { } uint8_t color_index(int i) const { return (_entry >> i * 2) & 0b11; } yagbe::color color(int i) const { return colors()[color_index(i)]; } constexpr static std::array<yagbe::color, 4> colors() { return std::array<yagbe::color, 4>{ yagbe::color{ 220,180,92,255 }, yagbe::color{ 152,124,60,255 }, yagbe::color{ 220,180,92,255 }, yagbe::color{ 76,60,28,255 }, }; } protected: uint8_t _entry; }; };<|endoftext|>
<commit_before>/* ============================================================================ DELLY: Structural variant discovery by integrated PE mapping and SR analysis ============================================================================ This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ============================================================================ Contact: Tobias Rausch (rausch@embl.de) ============================================================================ */ #define _SECURE_SCL 0 #define _SCL_SECURE_NO_WARNINGS #include <iostream> #include <fstream> #define BOOST_DISABLE_ASSERTS #ifdef OPENMP #include <omp.h> #endif #ifdef PROFILE #include "gperftools/profiler.h" #endif #include "version.h" #include "delly.h" #include "filter.h" #include "merge.h" using namespace torali; inline void displayUsage() { std::cout << "Usage: delly <command> <arguments>" << std::endl; std::cout << std::endl; std::cout << "Commands:" << std::endl; std::cout << std::endl; std::cout << " call discover and genotype structural variants" << std::endl; std::cout << " merge merge structural variants across VCF/BCF files and within a single VCF/BCF file" << std::endl; std::cout << " filter filter somatic or germline structural variants" << std::endl; std::cout << std::endl; std::cout << std::endl; } int main(int argc, char **argv) { if (argc < 2) { printTitle("Delly"); displayUsage(); return 0; } if ((std::string(argv[1]) == "version") || (std::string(argv[1]) == "--version") || (std::string(argv[1]) == "--version-only") || (std::string(argv[1]) == "-v")) { std::cout << "Delly version: v" << dellyVersionNumber << std::endl; return 0; } else if ((std::string(argv[1]) == "help") || (std::string(argv[1]) == "--help") || (std::string(argv[1]) == "-h") || (std::string(argv[1]) == "-?")) { printTitle("Delly"); displayUsage(); return 0; } else if ((std::string(argv[1]) == "warranty") || (std::string(argv[1]) == "--warranty") || (std::string(argv[1]) == "-w")) { displayWarranty(); return 0; } else if ((std::string(argv[1]) == "license") || (std::string(argv[1]) == "--license") || (std::string(argv[1]) == "-l")) { gplV3(); return 0; } else if ((std::string(argv[1]) == "call")) { return delly(argc-1,argv+1); } else if ((std::string(argv[1]) == "filter")) { return filter(argc-1,argv+1); } else if ((std::string(argv[1]) == "merge")) { return merge(argc-1,argv+1); } std::cerr << "Unrecognized command " << std::string(argv[1]) << std::endl; return 1; } <commit_msg>boost and htslib versions<commit_after>/* ============================================================================ DELLY: Structural variant discovery by integrated PE mapping and SR analysis ============================================================================ This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ============================================================================ Contact: Tobias Rausch (rausch@embl.de) ============================================================================ */ #define _SECURE_SCL 0 #define _SCL_SECURE_NO_WARNINGS #include <iostream> #include <fstream> #define BOOST_DISABLE_ASSERTS #ifdef OPENMP #include <omp.h> #endif #ifdef PROFILE #include "gperftools/profiler.h" #endif #include "version.h" #include "delly.h" #include "filter.h" #include "merge.h" using namespace torali; inline void displayUsage() { std::cout << "Usage: delly <command> <arguments>" << std::endl; std::cout << std::endl; std::cout << "Commands:" << std::endl; std::cout << std::endl; std::cout << " call discover and genotype structural variants" << std::endl; std::cout << " merge merge structural variants across VCF/BCF files and within a single VCF/BCF file" << std::endl; std::cout << " filter filter somatic or germline structural variants" << std::endl; std::cout << std::endl; std::cout << std::endl; } int main(int argc, char **argv) { if (argc < 2) { printTitle("Delly"); displayUsage(); return 0; } if ((std::string(argv[1]) == "version") || (std::string(argv[1]) == "--version") || (std::string(argv[1]) == "--version-only") || (std::string(argv[1]) == "-v")) { std::cout << "Delly version: v" << dellyVersionNumber << std::endl; std::cout << " using Boost: v" << BOOST_VERSION / 100000 << "." << BOOST_VERSION / 100 % 1000 << "." << BOOST_VERSION % 100 << std::endl; std::cout << " using HTSlib: v" << hts_version() << std::endl; return 0; } else if ((std::string(argv[1]) == "help") || (std::string(argv[1]) == "--help") || (std::string(argv[1]) == "-h") || (std::string(argv[1]) == "-?")) { printTitle("Delly"); displayUsage(); return 0; } else if ((std::string(argv[1]) == "warranty") || (std::string(argv[1]) == "--warranty") || (std::string(argv[1]) == "-w")) { displayWarranty(); return 0; } else if ((std::string(argv[1]) == "license") || (std::string(argv[1]) == "--license") || (std::string(argv[1]) == "-l")) { gplV3(); return 0; } else if ((std::string(argv[1]) == "call")) { return delly(argc-1,argv+1); } else if ((std::string(argv[1]) == "filter")) { return filter(argc-1,argv+1); } else if ((std::string(argv[1]) == "merge")) { return merge(argc-1,argv+1); } std::cerr << "Unrecognized command " << std::string(argv[1]) << std::endl; return 1; } <|endoftext|>
<commit_before>#include <opencv2/objdetect/objdetect.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> #include <stdio.h> using namespace std; using namespace cv; void help() { cout << "\nThis program demonstrates the haar cascade recognizer\n" "this classifier can recognize many ~rigid objects, it's most known use is for faces.\n" "Usage:\n" "./facedetect [--cascade=<cascade_path> this is the primary trained classifier such as frontal face]\n" " [--nested-cascade[=nested_cascade_path this an optional secondary classifier such as eyes]]\n" " [--scale=<image scale greater or equal to 1, try 1.3 for example>\n" " [filename|camera_index]\n\n" "see facedetect.cmd for one call:\n" "./facedetect --cascade=\"../../data/haarcascades/haarcascade_frontalface_alt.xml\" --nested-cascade=\"../../data/haarcascades/haarcascade_eye.xml\" --scale=1.3 \n" "Hit any key to quit.\n" << endl; } void detectAndDraw( Mat& img, CascadeClassifier& cascade, CascadeClassifier& nestedCascade, double scale); String cascadeName = "../../data/haarcascades/haarcascade_frontalface_alt.xml"; String nestedCascadeName = "../../data/haarcascades/haarcascade_eye_tree_eyeglasses.xml"; int main( int argc, const char** argv ) { CvCapture* capture = 0; Mat frame, frameCopy, image; const String scaleOpt = "--scale="; size_t scaleOptLen = scaleOpt.length(); const String cascadeOpt = "--cascade="; size_t cascadeOptLen = cascadeOpt.length(); const String nestedCascadeOpt = "--nested-cascade"; size_t nestedCascadeOptLen = nestedCascadeOpt.length(); String inputName; help(); CascadeClassifier cascade, nestedCascade; double scale = 1; for( int i = 1; i < argc; i++ ) { cout << "Processing " << i << " " << argv[i] << endl; if( cascadeOpt.compare( 0, cascadeOptLen, argv[i], cascadeOptLen ) == 0 ) { cascadeName.assign( argv[i] + cascadeOptLen ); cout << " from which we have cascadeName= " << cascadeName << endl; } else if( nestedCascadeOpt.compare( 0, nestedCascadeOptLen, argv[i], nestedCascadeOptLen ) == 0 ) { if( argv[i][nestedCascadeOpt.length()] == '=' ) nestedCascadeName.assign( argv[i] + nestedCascadeOpt.length() + 1 ); if( !nestedCascade.load( nestedCascadeName ) ) cerr << "WARNING: Could not load classifier cascade for nested objects" << endl; } else if( scaleOpt.compare( 0, scaleOptLen, argv[i], scaleOptLen ) == 0 ) { if( !sscanf( argv[i] + scaleOpt.length(), "%lf", &scale ) || scale < 1 ) scale = 1; cout << " from which we read scale = " << scale << endl; } else if( argv[i][0] == '-' ) { cerr << "WARNING: Unknown option %s" << argv[i] << endl; } else inputName.assign( argv[i] ); } if( !cascade.load( cascadeName ) ) { cerr << "ERROR: Could not load classifier cascade" << endl; cerr << "Usage: facedetect [--cascade=<cascade_path>]\n" " [--nested-cascade[=nested_cascade_path]]\n" " [--scale[=<image scale>\n" " [filename|camera_index]\n" << endl ; return -1; } if( inputName.empty() || (isdigit(inputName.c_str()[0]) && inputName.c_str()[1] == '\0') ) { capture = cvCaptureFromCAM( inputName.empty() ? 0 : inputName.c_str()[0] - '0' ); int c = inputName.empty() ? 0 : inputName.c_str()[0] - '0' ; if(!capture) cout << "Capture from CAM " << c << " didn't work" << endl; } else if( inputName.size() ) { image = imread( inputName, 1 ); if( image.empty() ) { capture = cvCaptureFromAVI( inputName.c_str() ); if(!capture) cout << "Capture from AVI didn't work" << endl; } } else { image = imread( "lena.jpg", 1 ); if(image.empty()) cout << "Couldn't read lena.jpg" << endl; } cvNamedWindow( "result", 1 ); if( capture ) { cout << "In capture ..." << endl; for(;;) { IplImage* iplImg = cvQueryFrame( capture ); frame = iplImg; if( frame.empty() ) break; if( iplImg->origin == IPL_ORIGIN_TL ) frame.copyTo( frameCopy ); else flip( frame, frameCopy, 0 ); detectAndDraw( frameCopy, cascade, nestedCascade, scale ); if( waitKey( 10 ) >= 0 ) goto _cleanup_; } waitKey(0); _cleanup_: cvReleaseCapture( &capture ); } else { cout << "In image read" << endl; if( !image.empty() ) { detectAndDraw( image, cascade, nestedCascade, scale ); waitKey(0); } else if( !inputName.empty() ) { /* assume it is a text file containing the list of the image filenames to be processed - one per line */ FILE* f = fopen( inputName.c_str(), "rt" ); if( f ) { char buf[1000+1]; while( fgets( buf, 1000, f ) ) { int len = (int)strlen(buf), c; while( len > 0 && isspace(buf[len-1]) ) len--; buf[len] = '\0'; cout << "file " << buf << endl; image = imread( buf, 1 ); if( !image.empty() ) { detectAndDraw( image, cascade, nestedCascade, scale ); c = waitKey(0); if( c == 27 || c == 'q' || c == 'Q' ) break; } else { cerr << "Aw snap, couldn't read image " << buf << endl; } } fclose(f); } } } cvDestroyWindow("result"); return 0; } void detectAndDraw( Mat& img, CascadeClassifier& cascade, CascadeClassifier& nestedCascade, double scale) { int i = 0; double t = 0; vector<Rect> faces; const static Scalar colors[] = { CV_RGB(0,0,255), CV_RGB(0,128,255), CV_RGB(0,255,255), CV_RGB(0,255,0), CV_RGB(255,128,0), CV_RGB(255,255,0), CV_RGB(255,0,0), CV_RGB(255,0,255)} ; Mat gray, smallImg( cvRound (img.rows/scale), cvRound(img.cols/scale), CV_8UC1 ); cvtColor( img, gray, CV_BGR2GRAY ); resize( gray, smallImg, smallImg.size(), 0, 0, INTER_LINEAR ); equalizeHist( smallImg, smallImg ); t = (double)cvGetTickCount(); cascade.detectMultiScale( smallImg, faces, 1.1, 2, 0 //|CV_HAAR_FIND_BIGGEST_OBJECT //|CV_HAAR_DO_ROUGH_SEARCH |CV_HAAR_SCALE_IMAGE , Size(30, 30) ); t = (double)cvGetTickCount() - t; printf( "detection time = %g ms\n", t/((double)cvGetTickFrequency()*1000.) ); for( vector<Rect>::const_iterator r = faces.begin(); r != faces.end(); r++, i++ ) { Mat smallImgROI; vector<Rect> nestedObjects; Point center; Scalar color = colors[i%8]; int radius; center.x = cvRound((r->x + r->width*0.5)*scale); center.y = cvRound((r->y + r->height*0.5)*scale); radius = cvRound((r->width + r->height)*0.25*scale); circle( img, center, radius, color, 3, 8, 0 ); if( nestedCascade.empty() ) continue; smallImgROI = smallImg(*r); nestedCascade.detectMultiScale( smallImgROI, nestedObjects, 1.1, 2, 0 //|CV_HAAR_FIND_BIGGEST_OBJECT //|CV_HAAR_DO_ROUGH_SEARCH //|CV_HAAR_DO_CANNY_PRUNING |CV_HAAR_SCALE_IMAGE , Size(30, 30) ); for( vector<Rect>::const_iterator nr = nestedObjects.begin(); nr != nestedObjects.end(); nr++ ) { center.x = cvRound((r->x + nr->x + nr->width*0.5)*scale); center.y = cvRound((r->y + nr->y + nr->height*0.5)*scale); radius = cvRound((nr->width + nr->height)*0.25*scale); circle( img, center, radius, color, 3, 8, 0 ); } } cv::imshow( "result", img ); } <commit_msg>revamped<commit_after>#include <opencv2/objdetect/objdetect.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> #include <stdio.h> using namespace std; using namespace cv; void help() { cout << "\nThis program demonstrates the haar cascade recognizer\n" "this classifier can recognize many ~rigid objects, it's most known use is for faces.\n" "Usage:\n" "./facedetect [--cascade=<cascade_path> this is the primary trained classifier such as frontal face]\n" " [--nested-cascade[=nested_cascade_path this an optional secondary classifier such as eyes]]\n" " [--scale=<image scale greater or equal to 1, try 1.3 for example>\n" " [filename|camera_index]\n\n" "see facedetect.cmd for one call:\n" "./facedetect --cascade=\"../../data/haarcascades/haarcascade_frontalface_alt.xml\" --nested-cascade=\"../../data/haarcascades/haarcascade_eye.xml\" --scale=1.3 \n" "Hit any key to quit.\n" "Using OpenCV version %s\n" << CV_VERSION << "\n" << endl; } void detectAndDraw( Mat& img, CascadeClassifier& cascade, CascadeClassifier& nestedCascade, double scale); String cascadeName = "../../data/haarcascades/haarcascade_frontalface_alt.xml"; String nestedCascadeName = "../../data/haarcascades/haarcascade_eye_tree_eyeglasses.xml"; int main( int argc, const char** argv ) { CvCapture* capture = 0; Mat frame, frameCopy, image; const String scaleOpt = "--scale="; size_t scaleOptLen = scaleOpt.length(); const String cascadeOpt = "--cascade="; size_t cascadeOptLen = cascadeOpt.length(); const String nestedCascadeOpt = "--nested-cascade"; size_t nestedCascadeOptLen = nestedCascadeOpt.length(); String inputName; help(); CascadeClassifier cascade, nestedCascade; double scale = 1; for( int i = 1; i < argc; i++ ) { cout << "Processing " << i << " " << argv[i] << endl; if( cascadeOpt.compare( 0, cascadeOptLen, argv[i], cascadeOptLen ) == 0 ) { cascadeName.assign( argv[i] + cascadeOptLen ); cout << " from which we have cascadeName= " << cascadeName << endl; } else if( nestedCascadeOpt.compare( 0, nestedCascadeOptLen, argv[i], nestedCascadeOptLen ) == 0 ) { if( argv[i][nestedCascadeOpt.length()] == '=' ) nestedCascadeName.assign( argv[i] + nestedCascadeOpt.length() + 1 ); if( !nestedCascade.load( nestedCascadeName ) ) cerr << "WARNING: Could not load classifier cascade for nested objects" << endl; } else if( scaleOpt.compare( 0, scaleOptLen, argv[i], scaleOptLen ) == 0 ) { if( !sscanf( argv[i] + scaleOpt.length(), "%lf", &scale ) || scale < 1 ) scale = 1; cout << " from which we read scale = " << scale << endl; } else if( argv[i][0] == '-' ) { cerr << "WARNING: Unknown option %s" << argv[i] << endl; } else inputName.assign( argv[i] ); } if( !cascade.load( cascadeName ) ) { cerr << "ERROR: Could not load classifier cascade" << endl; cerr << "Usage: facedetect [--cascade=<cascade_path>]\n" " [--nested-cascade[=nested_cascade_path]]\n" " [--scale[=<image scale>\n" " [filename|camera_index]\n" << endl ; return -1; } if( inputName.empty() || (isdigit(inputName.c_str()[0]) && inputName.c_str()[1] == '\0') ) { capture = cvCaptureFromCAM( inputName.empty() ? 0 : inputName.c_str()[0] - '0' ); int c = inputName.empty() ? 0 : inputName.c_str()[0] - '0' ; if(!capture) cout << "Capture from CAM " << c << " didn't work" << endl; } else if( inputName.size() ) { image = imread( inputName, 1 ); if( image.empty() ) { capture = cvCaptureFromAVI( inputName.c_str() ); if(!capture) cout << "Capture from AVI didn't work" << endl; } } else { image = imread( "lena.jpg", 1 ); if(image.empty()) cout << "Couldn't read lena.jpg" << endl; } cvNamedWindow( "result", 1 ); if( capture ) { cout << "In capture ..." << endl; for(;;) { IplImage* iplImg = cvQueryFrame( capture ); frame = iplImg; if( frame.empty() ) break; if( iplImg->origin == IPL_ORIGIN_TL ) frame.copyTo( frameCopy ); else flip( frame, frameCopy, 0 ); detectAndDraw( frameCopy, cascade, nestedCascade, scale ); if( waitKey( 10 ) >= 0 ) goto _cleanup_; } waitKey(0); _cleanup_: cvReleaseCapture( &capture ); } else { cout << "In image read" << endl; if( !image.empty() ) { detectAndDraw( image, cascade, nestedCascade, scale ); waitKey(0); } else if( !inputName.empty() ) { /* assume it is a text file containing the list of the image filenames to be processed - one per line */ FILE* f = fopen( inputName.c_str(), "rt" ); if( f ) { char buf[1000+1]; while( fgets( buf, 1000, f ) ) { int len = (int)strlen(buf), c; while( len > 0 && isspace(buf[len-1]) ) len--; buf[len] = '\0'; cout << "file " << buf << endl; image = imread( buf, 1 ); if( !image.empty() ) { detectAndDraw( image, cascade, nestedCascade, scale ); c = waitKey(0); if( c == 27 || c == 'q' || c == 'Q' ) break; } else { cerr << "Aw snap, couldn't read image " << buf << endl; } } fclose(f); } } } cvDestroyWindow("result"); return 0; } void detectAndDraw( Mat& img, CascadeClassifier& cascade, CascadeClassifier& nestedCascade, double scale) { int i = 0; double t = 0; vector<Rect> faces; const static Scalar colors[] = { CV_RGB(0,0,255), CV_RGB(0,128,255), CV_RGB(0,255,255), CV_RGB(0,255,0), CV_RGB(255,128,0), CV_RGB(255,255,0), CV_RGB(255,0,0), CV_RGB(255,0,255)} ; Mat gray, smallImg( cvRound (img.rows/scale), cvRound(img.cols/scale), CV_8UC1 ); cvtColor( img, gray, CV_BGR2GRAY ); resize( gray, smallImg, smallImg.size(), 0, 0, INTER_LINEAR ); equalizeHist( smallImg, smallImg ); t = (double)cvGetTickCount(); cascade.detectMultiScale( smallImg, faces, 1.1, 2, 0 //|CV_HAAR_FIND_BIGGEST_OBJECT //|CV_HAAR_DO_ROUGH_SEARCH |CV_HAAR_SCALE_IMAGE , Size(30, 30) ); t = (double)cvGetTickCount() - t; printf( "detection time = %g ms\n", t/((double)cvGetTickFrequency()*1000.) ); for( vector<Rect>::const_iterator r = faces.begin(); r != faces.end(); r++, i++ ) { Mat smallImgROI; vector<Rect> nestedObjects; Point center; Scalar color = colors[i%8]; int radius; center.x = cvRound((r->x + r->width*0.5)*scale); center.y = cvRound((r->y + r->height*0.5)*scale); radius = cvRound((r->width + r->height)*0.25*scale); circle( img, center, radius, color, 3, 8, 0 ); if( nestedCascade.empty() ) continue; smallImgROI = smallImg(*r); nestedCascade.detectMultiScale( smallImgROI, nestedObjects, 1.1, 2, 0 //|CV_HAAR_FIND_BIGGEST_OBJECT //|CV_HAAR_DO_ROUGH_SEARCH //|CV_HAAR_DO_CANNY_PRUNING |CV_HAAR_SCALE_IMAGE , Size(30, 30) ); for( vector<Rect>::const_iterator nr = nestedObjects.begin(); nr != nestedObjects.end(); nr++ ) { center.x = cvRound((r->x + nr->x + nr->width*0.5)*scale); center.y = cvRound((r->y + nr->y + nr->height*0.5)*scale); radius = cvRound((nr->width + nr->height)*0.25*scale); circle( img, center, radius, color, 3, 8, 0 ); } } cv::imshow( "result", img ); } <|endoftext|>
<commit_before>// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. // Most code came from: chrome/browser/chrome_browser_main_posix.cc. #include "atom/browser/atom_browser_main_parts.h" #include <errno.h> #include <limits.h> #include <pthread.h> #include <signal.h> #include <sys/resource.h> #include <unistd.h> #include "atom/browser/browser.h" #include "base/posix/eintr_wrapper.h" #include "content/public/browser/browser_thread.h" using content::BrowserThread; namespace atom { namespace { // See comment in |PreEarlyInitialization()|, where sigaction is called. void SIGCHLDHandler(int signal) { } // The OSX fork() implementation can crash in the child process before // fork() returns. In that case, the shutdown pipe will still be // shared with the parent process. To prevent child crashes from // causing parent shutdowns, |g_pipe_pid| is the pid for the process // which registered |g_shutdown_pipe_write_fd|. // See <http://crbug.com/175341>. pid_t g_pipe_pid = -1; int g_shutdown_pipe_write_fd = -1; int g_shutdown_pipe_read_fd = -1; // Common code between SIG{HUP, INT, TERM}Handler. void GracefulShutdownHandler(int signal) { // Reinstall the default handler. We had one shot at graceful shutdown. struct sigaction action; memset(&action, 0, sizeof(action)); action.sa_handler = SIG_DFL; RAW_CHECK(sigaction(signal, &action, NULL) == 0); RAW_CHECK(g_pipe_pid == getpid()); RAW_CHECK(g_shutdown_pipe_write_fd != -1); RAW_CHECK(g_shutdown_pipe_read_fd != -1); size_t bytes_written = 0; do { int rv = HANDLE_EINTR( write(g_shutdown_pipe_write_fd, reinterpret_cast<const char*>(&signal) + bytes_written, sizeof(signal) - bytes_written)); RAW_CHECK(rv >= 0); bytes_written += rv; } while (bytes_written < sizeof(signal)); } // See comment in |PostMainMessageLoopStart()|, where sigaction is called. void SIGHUPHandler(int signal) { RAW_CHECK(signal == SIGHUP); GracefulShutdownHandler(signal); } // See comment in |PostMainMessageLoopStart()|, where sigaction is called. void SIGINTHandler(int signal) { RAW_CHECK(signal == SIGINT); GracefulShutdownHandler(signal); } // See comment in |PostMainMessageLoopStart()|, where sigaction is called. void SIGTERMHandler(int signal) { RAW_CHECK(signal == SIGTERM); GracefulShutdownHandler(signal); } class ShutdownDetector : public base::PlatformThread::Delegate { public: explicit ShutdownDetector(int shutdown_fd); void ThreadMain() override; private: const int shutdown_fd_; DISALLOW_COPY_AND_ASSIGN(ShutdownDetector); }; ShutdownDetector::ShutdownDetector(int shutdown_fd) : shutdown_fd_(shutdown_fd) { CHECK_NE(shutdown_fd_, -1); } // These functions are used to help us diagnose crash dumps that happen // during the shutdown process. NOINLINE void ShutdownFDReadError() { // Ensure function isn't optimized away. asm(""); sleep(UINT_MAX); } NOINLINE void ShutdownFDClosedError() { // Ensure function isn't optimized away. asm(""); sleep(UINT_MAX); } NOINLINE void ExitPosted() { // Ensure function isn't optimized away. asm(""); sleep(UINT_MAX); } void ShutdownDetector::ThreadMain() { base::PlatformThread::SetName("CrShutdownDetector"); int signal; size_t bytes_read = 0; ssize_t ret; do { ret = HANDLE_EINTR( read(shutdown_fd_, reinterpret_cast<char*>(&signal) + bytes_read, sizeof(signal) - bytes_read)); if (ret < 0) { NOTREACHED() << "Unexpected error: " << strerror(errno); ShutdownFDReadError(); break; } else if (ret == 0) { NOTREACHED() << "Unexpected closure of shutdown pipe."; ShutdownFDClosedError(); break; } bytes_read += ret; } while (bytes_read < sizeof(signal)); VLOG(1) << "Handling shutdown for signal " << signal << "."; base::Closure task = base::Bind(&Browser::Quit, base::Unretained(Browser::Get())); if (!BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, task)) { // Without a UI thread to post the exit task to, there aren't many // options. Raise the signal again. The default handler will pick it up // and cause an ungraceful exit. RAW_LOG(WARNING, "No UI thread, exiting ungracefully."); kill(getpid(), signal); // The signal may be handled on another thread. Give that a chance to // happen. sleep(3); // We really should be dead by now. For whatever reason, we're not. Exit // immediately, with the exit status set to the signal number with bit 8 // set. On the systems that we care about, this exit status is what is // normally used to indicate an exit by this signal's default handler. // This mechanism isn't a de jure standard, but even in the worst case, it // should at least result in an immediate exit. RAW_LOG(WARNING, "Still here, exiting really ungracefully."); _exit(signal | (1 << 7)); } ExitPosted(); } } // namespace void AtomBrowserMainParts::HandleSIGCHLD() { // We need to accept SIGCHLD, even though our handler is a no-op because // otherwise we cannot wait on children. (According to POSIX 2001.) struct sigaction action; memset(&action, 0, sizeof(action)); action.sa_handler = SIGCHLDHandler; CHECK(sigaction(SIGCHLD, &action, NULL) == 0); } void AtomBrowserMainParts::HandleShutdownSignals() { int pipefd[2]; int ret = pipe(pipefd); if (ret < 0) { PLOG(DFATAL) << "Failed to create pipe"; } else { g_pipe_pid = getpid(); g_shutdown_pipe_read_fd = pipefd[0]; g_shutdown_pipe_write_fd = pipefd[1]; #if !defined(ADDRESS_SANITIZER) && !defined(KEEP_SHADOW_STACKS) const size_t kShutdownDetectorThreadStackSize = PTHREAD_STACK_MIN * 2; #else // ASan instrumentation and -finstrument-functions (used for keeping the // shadow stacks) bloat the stack frames, so we need to increase the stack // size to avoid hitting the guard page. const size_t kShutdownDetectorThreadStackSize = PTHREAD_STACK_MIN * 4; #endif // TODO(viettrungluu,willchan): crbug.com/29675 - This currently leaks, so // if you change this, you'll probably need to change the suppression. if (!base::PlatformThread::CreateNonJoinable( kShutdownDetectorThreadStackSize, new ShutdownDetector(g_shutdown_pipe_read_fd))) { LOG(DFATAL) << "Failed to create shutdown detector task."; } } // Setup signal handlers for shutdown AFTER shutdown pipe is setup because // it may be called right away after handler is set. // If adding to this list of signal handlers, note the new signal probably // needs to be reset in child processes. See // base/process_util_posix.cc:LaunchProcess. // We need to handle SIGTERM, because that is how many POSIX-based distros ask // processes to quit gracefully at shutdown time. struct sigaction action; memset(&action, 0, sizeof(action)); action.sa_handler = SIGTERMHandler; CHECK(sigaction(SIGTERM, &action, NULL) == 0); // Also handle SIGINT - when the user terminates the browser via Ctrl+C. If // the browser process is being debugged, GDB will catch the SIGINT first. action.sa_handler = SIGINTHandler; CHECK(sigaction(SIGINT, &action, NULL) == 0); // And SIGHUP, for when the terminal disappears. On shutdown, many Linux // distros send SIGHUP, SIGTERM, and then SIGKILL. action.sa_handler = SIGHUPHandler; CHECK(sigaction(SIGHUP, &action, NULL) == 0); } } // namespace atom <commit_msg>Fix cpplint warnings<commit_after>// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. // Most code came from: chrome/browser/chrome_browser_main_posix.cc. #include "atom/browser/atom_browser_main_parts.h" #include <errno.h> #include <limits.h> #include <pthread.h> #include <signal.h> #include <sys/resource.h> #include <unistd.h> #include "atom/browser/browser.h" #include "base/posix/eintr_wrapper.h" #include "content/public/browser/browser_thread.h" using content::BrowserThread; namespace atom { namespace { // See comment in |PreEarlyInitialization()|, where sigaction is called. void SIGCHLDHandler(int signal) { } // The OSX fork() implementation can crash in the child process before // fork() returns. In that case, the shutdown pipe will still be // shared with the parent process. To prevent child crashes from // causing parent shutdowns, |g_pipe_pid| is the pid for the process // which registered |g_shutdown_pipe_write_fd|. // See <http://crbug.com/175341>. pid_t g_pipe_pid = -1; int g_shutdown_pipe_write_fd = -1; int g_shutdown_pipe_read_fd = -1; // Common code between SIG{HUP, INT, TERM}Handler. void GracefulShutdownHandler(int signal) { // Reinstall the default handler. We had one shot at graceful shutdown. struct sigaction action; memset(&action, 0, sizeof(action)); action.sa_handler = SIG_DFL; RAW_CHECK(sigaction(signal, &action, NULL) == 0); RAW_CHECK(g_pipe_pid == getpid()); RAW_CHECK(g_shutdown_pipe_write_fd != -1); RAW_CHECK(g_shutdown_pipe_read_fd != -1); size_t bytes_written = 0; do { int rv = HANDLE_EINTR( write(g_shutdown_pipe_write_fd, reinterpret_cast<const char*>(&signal) + bytes_written, sizeof(signal) - bytes_written)); RAW_CHECK(rv >= 0); bytes_written += rv; } while (bytes_written < sizeof(signal)); } // See comment in |PostMainMessageLoopStart()|, where sigaction is called. void SIGHUPHandler(int signal) { RAW_CHECK(signal == SIGHUP); GracefulShutdownHandler(signal); } // See comment in |PostMainMessageLoopStart()|, where sigaction is called. void SIGINTHandler(int signal) { RAW_CHECK(signal == SIGINT); GracefulShutdownHandler(signal); } // See comment in |PostMainMessageLoopStart()|, where sigaction is called. void SIGTERMHandler(int signal) { RAW_CHECK(signal == SIGTERM); GracefulShutdownHandler(signal); } class ShutdownDetector : public base::PlatformThread::Delegate { public: explicit ShutdownDetector(int shutdown_fd); void ThreadMain() override; private: const int shutdown_fd_; DISALLOW_COPY_AND_ASSIGN(ShutdownDetector); }; ShutdownDetector::ShutdownDetector(int shutdown_fd) : shutdown_fd_(shutdown_fd) { CHECK_NE(shutdown_fd_, -1); } // These functions are used to help us diagnose crash dumps that happen // during the shutdown process. NOINLINE void ShutdownFDReadError() { // Ensure function isn't optimized away. asm(""); sleep(UINT_MAX); } NOINLINE void ShutdownFDClosedError() { // Ensure function isn't optimized away. asm(""); sleep(UINT_MAX); } NOINLINE void ExitPosted() { // Ensure function isn't optimized away. asm(""); sleep(UINT_MAX); } void ShutdownDetector::ThreadMain() { base::PlatformThread::SetName("CrShutdownDetector"); int signal; size_t bytes_read = 0; ssize_t ret; do { ret = HANDLE_EINTR( read(shutdown_fd_, reinterpret_cast<char*>(&signal) + bytes_read, sizeof(signal) - bytes_read)); if (ret < 0) { NOTREACHED() << "Unexpected error: " << strerror(errno); ShutdownFDReadError(); break; } else if (ret == 0) { NOTREACHED() << "Unexpected closure of shutdown pipe."; ShutdownFDClosedError(); break; } bytes_read += ret; } while (bytes_read < sizeof(signal)); VLOG(1) << "Handling shutdown for signal " << signal << "."; base::Closure task = base::Bind(&Browser::Quit, base::Unretained(Browser::Get())); if (!BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, task)) { // Without a UI thread to post the exit task to, there aren't many // options. Raise the signal again. The default handler will pick it up // and cause an ungraceful exit. RAW_LOG(WARNING, "No UI thread, exiting ungracefully."); kill(getpid(), signal); // The signal may be handled on another thread. Give that a chance to // happen. sleep(3); // We really should be dead by now. For whatever reason, we're not. Exit // immediately, with the exit status set to the signal number with bit 8 // set. On the systems that we care about, this exit status is what is // normally used to indicate an exit by this signal's default handler. // This mechanism isn't a de jure standard, but even in the worst case, it // should at least result in an immediate exit. RAW_LOG(WARNING, "Still here, exiting really ungracefully."); _exit(signal | (1 << 7)); } ExitPosted(); } } // namespace void AtomBrowserMainParts::HandleSIGCHLD() { // We need to accept SIGCHLD, even though our handler is a no-op because // otherwise we cannot wait on children. (According to POSIX 2001.) struct sigaction action; memset(&action, 0, sizeof(action)); action.sa_handler = SIGCHLDHandler; CHECK_EQ(sigaction(SIGCHLD, &action, NULL), 0); } void AtomBrowserMainParts::HandleShutdownSignals() { int pipefd[2]; int ret = pipe(pipefd); if (ret < 0) { PLOG(DFATAL) << "Failed to create pipe"; } else { g_pipe_pid = getpid(); g_shutdown_pipe_read_fd = pipefd[0]; g_shutdown_pipe_write_fd = pipefd[1]; #if !defined(ADDRESS_SANITIZER) && !defined(KEEP_SHADOW_STACKS) const size_t kShutdownDetectorThreadStackSize = PTHREAD_STACK_MIN * 2; #else // ASan instrumentation and -finstrument-functions (used for keeping the // shadow stacks) bloat the stack frames, so we need to increase the stack // size to avoid hitting the guard page. const size_t kShutdownDetectorThreadStackSize = PTHREAD_STACK_MIN * 4; #endif // TODO(viettrungluu,willchan): crbug.com/29675 - This currently leaks, so // if you change this, you'll probably need to change the suppression. if (!base::PlatformThread::CreateNonJoinable( kShutdownDetectorThreadStackSize, new ShutdownDetector(g_shutdown_pipe_read_fd))) { LOG(DFATAL) << "Failed to create shutdown detector task."; } } // Setup signal handlers for shutdown AFTER shutdown pipe is setup because // it may be called right away after handler is set. // If adding to this list of signal handlers, note the new signal probably // needs to be reset in child processes. See // base/process_util_posix.cc:LaunchProcess. // We need to handle SIGTERM, because that is how many POSIX-based distros ask // processes to quit gracefully at shutdown time. struct sigaction action; memset(&action, 0, sizeof(action)); action.sa_handler = SIGTERMHandler; CHECK_EQ(sigaction(SIGTERM, &action, NULL), 0); // Also handle SIGINT - when the user terminates the browser via Ctrl+C. If // the browser process is being debugged, GDB will catch the SIGINT first. action.sa_handler = SIGINTHandler; CHECK_EQ(sigaction(SIGINT, &action, NULL), 0); // And SIGHUP, for when the terminal disappears. On shutdown, many Linux // distros send SIGHUP, SIGTERM, and then SIGKILL. action.sa_handler = SIGHUPHandler; CHECK_EQ(sigaction(SIGHUP, &action, NULL), 0); } } // namespace atom <|endoftext|>
<commit_before>/* * This file is part of Poedit (http://www.poedit.net) * * Copyright (C) 1999-2010 Vaclav Slavik * * 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 <wx/wxprec.h> #include <wx/wx.h> #include <wx/config.h> #include <wx/fs_zip.h> #include <wx/image.h> #include <wx/cmdline.h> #include <wx/log.h> #include <wx/xrc/xmlres.h> #include <wx/xrc/xh_all.h> #include <wx/stdpaths.h> #include <wx/filename.h> #include <wx/sysopt.h> #ifdef USE_SPARKLE #include <Sparkle/SUCarbonAPI.h> #include "osx/userdefaults.h" #endif // USE_SPARKLE #ifdef __WXMSW__ #include <winsparkle.h> #endif #if !wxUSE_UNICODE #error "Unicode build of wxWidgets is required by Poedit" #endif #include "edapp.h" #include "edframe.h" #include "manager.h" #include "prefsdlg.h" #include "parser.h" #include "chooselang.h" #include "icons.h" #include "version.h" #include "transmem.h" #include "utility.h" IMPLEMENT_APP(PoeditApp); wxString PoeditApp::GetAppPath() const { #if defined(__UNIX__) wxString home; if (!wxGetEnv(_T("POEDIT_PREFIX"), &home)) home = wxString::FromAscii(POEDIT_PREFIX); return home; #elif defined(__WXMSW__) wxString exedir; wxFileName::SplitPath(wxStandardPaths::Get().GetExecutablePath(), &exedir, NULL, NULL); wxFileName fn = wxFileName::DirName(exedir); fn.RemoveLastDir(); return fn.GetFullPath(); #else #error "Unsupported platform!" #endif } wxString PoeditApp::GetAppVersion() const { return wxString::FromAscii(POEDIT_VERSION); } static wxArrayString gs_filesToOpen; extern void InitXmlResource(); bool PoeditApp::OnInit() { if (!wxApp::OnInit()) return false; #if defined(__WXMAC__) && wxCHECK_VERSION(2,8,5) wxSystemOptions::SetOption(wxMAC_TEXTCONTROL_USE_SPELL_CHECKER, 1); #endif #ifdef __WXMAC__ SetExitOnFrameDelete(false); #endif #if defined(__UNIX__) && !defined(__WXMAC__) wxString home = wxGetHomeDir() + _T("/"); // create Poedit cfg dir, move ~/.poedit to ~/.poedit/config // (upgrade from older versions of Poedit which used ~/.poedit file) if (!wxDirExists(home + _T(".poedit"))) { if (wxFileExists(home + _T(".poedit"))) wxRenameFile(home + _T(".poedit"), home + _T(".poedit2")); wxMkdir(home + _T(".poedit")); if (wxFileExists(home + _T(".poedit2"))) wxRenameFile(home + _T(".poedit2"), home + _T(".poedit/config")); } #endif SetVendorName(_T("Vaclav Slavik")); SetAppName(_T("Poedit")); #if defined(__WXMAC__) #define CFG_FILE (wxStandardPaths::Get().GetUserConfigDir() + _T("/net.poedit.Poedit.cfg")) #elif defined(__UNIX__) #define CFG_FILE (home + _T(".poedit/config")) #else #define CFG_FILE wxEmptyString #endif #ifdef __WXMAC__ // upgrade from the old location of config file: wxString oldcfgfile = wxStandardPaths::Get().GetUserConfigDir() + _T("/poedit.cfg"); if (wxFileExists(oldcfgfile) && !wxFileExists(CFG_FILE)) { wxRenameFile(oldcfgfile, CFG_FILE); } #endif wxConfigBase::Set( new wxConfig(wxEmptyString, wxEmptyString, CFG_FILE, wxEmptyString, wxCONFIG_USE_GLOBAL_FILE | wxCONFIG_USE_LOCAL_FILE)); wxConfigBase::Get()->SetExpandEnvVars(false); wxImage::AddHandler(new wxGIFHandler); wxImage::AddHandler(new wxPNGHandler); wxXmlResource::Get()->InitAllHandlers(); InitXmlResource(); SetDefaultCfg(wxConfig::Get()); wxArtProvider::Insert(new PoeditArtProvider); #ifdef __WXMAC__ wxLocale::AddCatalogLookupPathPrefix( wxStandardPaths::Get().GetResourcesDir() + _T("/locale")); #else wxLocale::AddCatalogLookupPathPrefix(GetAppPath() + _T("/share/locale")); #endif m_locale.Init(GetUILanguage()); m_locale.AddCatalog(_T("poedit")); #ifdef __WXMSW__ // Italian version of Windows uses just "?" for "Help" menu. This is // correctly handled by wxWidgets catalogs, but Poedit catalog has "Help" // entry too, so we add wxmsw.mo catalog again so that it takes // precedence over poedit.mo: m_locale.AddCatalog(_T("wxmsw")); #endif #ifdef __WXMAC__ // so that help menu is correctly merged with system-provided menu // (see http://sourceforge.net/tracker/index.php?func=detail&aid=1600747&group_id=9863&atid=309863) s_macHelpMenuTitleName = _("&Help"); #endif #ifdef USE_TRANSMEM // NB: It's important to do this before TM is used for the first time. TranslationMemory::MoveLegacyDbIfNeeded(); #endif // NB: opening files or creating empty window is handled differently on // Macs, using MacOpenFile() and MacNewFile(), so don't create empty // window if no files are given on command line; but still support // passing files on command line if (!gs_filesToOpen.empty()) { for (size_t i = 0; i < gs_filesToOpen.GetCount(); i++) OpenFile(gs_filesToOpen[i]); gs_filesToOpen.clear(); } #ifndef __WXMAC__ else { OpenNewFile(); } #endif // !__WXMAC__ #ifdef USE_SPARKLE // Remove config key for Sparkle < 1.5. UserDefaults::RemoveValue("SUCheckAtStartup"); SUSparkleInitializeForCarbon(); #endif // USE_SPARKLE #ifdef __WXMSW__ const char *appcast = "https://dl.updatica.com/poedit-win/appcast"; if ( GetAppVersion().Contains(_T("beta")) || GetAppVersion().Contains(_T("rc")) ) { // Beta versions use unstable feed. appcast = "https://dl.updatica.com/poedit-win/appcast/beta"; } win_sparkle_set_appcast_url(appcast); win_sparkle_init(); #endif return true; } int PoeditApp::OnExit() { #ifdef __WXMSW__ win_sparkle_cleanup(); #endif return wxApp::OnExit(); } void PoeditApp::OpenNewFile() { if (wxConfig::Get()->Read(_T("manager_startup"), (long)false)) ManagerFrame::Create()->Show(true); else PoeditFrame::Create(wxEmptyString); } void PoeditApp::OpenFile(const wxString& name) { PoeditFrame::Create(name); } void PoeditApp::SetDefaultParsers(wxConfigBase *cfg) { ParsersDB pdb; bool changed = false; wxString defaultsVersion = cfg->Read(_T("Parsers/DefaultsVersion"), _T("1.2.x")); pdb.Read(cfg); // Add parsers for languages supported by gettext itself (but only if the // user didn't already add language with this name himself): static struct { const wxChar *name; const wxChar *exts; } s_gettextLangs[] = { { _T("C/C++"), _T("*.c;*.cpp;*.h;*.hpp;*.cc;*.C;*.cxx;*.hxx") }, { _T("C#"), _T("*.cs") }, { _T("Java"), _T("*.java") }, { _T("Perl"), _T("*.pl") }, { _T("PHP"), _T("*.php") }, { _T("Python"), _T("*.py") }, { _T("TCL"), _T("*.tcl") }, { NULL, NULL } }; for (size_t i = 0; s_gettextLangs[i].name != NULL; i++) { // if this lang is already registered, don't overwrite it: if (pdb.FindParser(s_gettextLangs[i].name) != -1) continue; wxString langflag; if ( wxStrcmp(s_gettextLangs[i].name, _T("C/C++")) == 0 ) langflag = _T(" --language=C++"); else langflag = wxString(_T(" --language=")) + s_gettextLangs[i].name; // otherwise add new parser: Parser p; p.Name = s_gettextLangs[i].name; p.Extensions = s_gettextLangs[i].exts; p.Command = wxString(_T("xgettext")) + langflag + _T(" --force-po -o %o %C %K %F"); p.KeywordItem = _T("-k%k"); p.FileItem = _T("%f"); p.CharsetItem = _T("--from-code=%c"); pdb.Add(p); changed = true; } // If upgrading Poedit to 1.2.4, add dxgettext parser for Delphi: #ifdef __WINDOWS__ if (defaultsVersion == _T("1.2.x")) { Parser p; p.Name = _T("Delphi (dxgettext)"); p.Extensions = _T("*.pas;*.dpr;*.xfm;*.dfm"); p.Command = _T("dxgettext --so %o %F"); p.KeywordItem = wxEmptyString; p.FileItem = _T("%f"); pdb.Add(p); changed = true; } #endif // If upgrading Poedit to 1.2.5, update C++ parser to handle --from-code: if (defaultsVersion == _T("1.2.x") || defaultsVersion == _T("1.2.4")) { int cpp = pdb.FindParser(_T("C/C++")); if (cpp != -1) { if (pdb[cpp].Command == _T("xgettext --force-po -o %o %K %F")) { pdb[cpp].Command = _T("xgettext --force-po -o %o %C %K %F"); pdb[cpp].CharsetItem = _T("--from-code=%c"); changed = true; } } } if (changed) { pdb.Write(cfg); cfg->Write(_T("Parsers/DefaultsVersion"), GetAppVersion()); } } void PoeditApp::SetDefaultCfg(wxConfigBase *cfg) { SetDefaultParsers(cfg); if (cfg->Read(_T("version"), wxEmptyString) == GetAppVersion()) return; if (cfg->Read(_T("TM/search_paths"), wxEmptyString).empty()) { wxString paths; #if defined(__UNIX__) paths = wxGetHomeDir() + _T(":/usr/share/locale:/usr/local/share/locale"); #elif defined(__WXMSW__) paths = _T("C:"); #endif cfg->Write(_T("TM/search_paths"), paths); } cfg->Write(_T("version"), GetAppVersion()); } namespace { const wxChar *CL_KEEP_TEMP_FILES = _T("keep-temp-files"); } void PoeditApp::OnInitCmdLine(wxCmdLineParser& parser) { wxApp::OnInitCmdLine(parser); parser.AddSwitch(_T(""), CL_KEEP_TEMP_FILES, _("don't delete temporary files (for debugging)")); parser.AddParam(_T("catalog.po"), wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL | wxCMD_LINE_PARAM_MULTIPLE); } bool PoeditApp::OnCmdLineParsed(wxCmdLineParser& parser) { if (!wxApp::OnCmdLineParsed(parser)) return false; if ( parser.Found(CL_KEEP_TEMP_FILES) ) TempDirectory::KeepFiles(); for (size_t i = 0; i < parser.GetParamCount(); i++) gs_filesToOpen.Add(parser.GetParam(i)); return true; } <commit_msg>wxArtProvider::Insert is deprecated since 2.9.0 so use PushBack instead if on new version<commit_after>/* * This file is part of Poedit (http://www.poedit.net) * * Copyright (C) 1999-2010 Vaclav Slavik * * 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 <wx/wxprec.h> #include <wx/wx.h> #include <wx/config.h> #include <wx/fs_zip.h> #include <wx/image.h> #include <wx/cmdline.h> #include <wx/log.h> #include <wx/xrc/xmlres.h> #include <wx/xrc/xh_all.h> #include <wx/stdpaths.h> #include <wx/filename.h> #include <wx/sysopt.h> #ifdef USE_SPARKLE #include <Sparkle/SUCarbonAPI.h> #include "osx/userdefaults.h" #endif // USE_SPARKLE #ifdef __WXMSW__ #include <winsparkle.h> #endif #if !wxUSE_UNICODE #error "Unicode build of wxWidgets is required by Poedit" #endif #include "edapp.h" #include "edframe.h" #include "manager.h" #include "prefsdlg.h" #include "parser.h" #include "chooselang.h" #include "icons.h" #include "version.h" #include "transmem.h" #include "utility.h" IMPLEMENT_APP(PoeditApp); wxString PoeditApp::GetAppPath() const { #if defined(__UNIX__) wxString home; if (!wxGetEnv(_T("POEDIT_PREFIX"), &home)) home = wxString::FromAscii(POEDIT_PREFIX); return home; #elif defined(__WXMSW__) wxString exedir; wxFileName::SplitPath(wxStandardPaths::Get().GetExecutablePath(), &exedir, NULL, NULL); wxFileName fn = wxFileName::DirName(exedir); fn.RemoveLastDir(); return fn.GetFullPath(); #else #error "Unsupported platform!" #endif } wxString PoeditApp::GetAppVersion() const { return wxString::FromAscii(POEDIT_VERSION); } static wxArrayString gs_filesToOpen; extern void InitXmlResource(); bool PoeditApp::OnInit() { if (!wxApp::OnInit()) return false; #if defined(__WXMAC__) && wxCHECK_VERSION(2,8,5) wxSystemOptions::SetOption(wxMAC_TEXTCONTROL_USE_SPELL_CHECKER, 1); #endif #ifdef __WXMAC__ SetExitOnFrameDelete(false); #endif #if defined(__UNIX__) && !defined(__WXMAC__) wxString home = wxGetHomeDir() + _T("/"); // create Poedit cfg dir, move ~/.poedit to ~/.poedit/config // (upgrade from older versions of Poedit which used ~/.poedit file) if (!wxDirExists(home + _T(".poedit"))) { if (wxFileExists(home + _T(".poedit"))) wxRenameFile(home + _T(".poedit"), home + _T(".poedit2")); wxMkdir(home + _T(".poedit")); if (wxFileExists(home + _T(".poedit2"))) wxRenameFile(home + _T(".poedit2"), home + _T(".poedit/config")); } #endif SetVendorName(_T("Vaclav Slavik")); SetAppName(_T("Poedit")); #if defined(__WXMAC__) #define CFG_FILE (wxStandardPaths::Get().GetUserConfigDir() + _T("/net.poedit.Poedit.cfg")) #elif defined(__UNIX__) #define CFG_FILE (home + _T(".poedit/config")) #else #define CFG_FILE wxEmptyString #endif #ifdef __WXMAC__ // upgrade from the old location of config file: wxString oldcfgfile = wxStandardPaths::Get().GetUserConfigDir() + _T("/poedit.cfg"); if (wxFileExists(oldcfgfile) && !wxFileExists(CFG_FILE)) { wxRenameFile(oldcfgfile, CFG_FILE); } #endif wxConfigBase::Set( new wxConfig(wxEmptyString, wxEmptyString, CFG_FILE, wxEmptyString, wxCONFIG_USE_GLOBAL_FILE | wxCONFIG_USE_LOCAL_FILE)); wxConfigBase::Get()->SetExpandEnvVars(false); wxImage::AddHandler(new wxGIFHandler); wxImage::AddHandler(new wxPNGHandler); wxXmlResource::Get()->InitAllHandlers(); InitXmlResource(); SetDefaultCfg(wxConfig::Get()); #if wxCHECK_VERSION(2,9,0) wxArtProvider::PushBack(new PoeditArtProvider); #else wxArtProvider::Insert(new PoeditArtProvider); #endif #ifdef __WXMAC__ wxLocale::AddCatalogLookupPathPrefix( wxStandardPaths::Get().GetResourcesDir() + _T("/locale")); #else wxLocale::AddCatalogLookupPathPrefix(GetAppPath() + _T("/share/locale")); #endif m_locale.Init(GetUILanguage()); m_locale.AddCatalog(_T("poedit")); #ifdef __WXMSW__ // Italian version of Windows uses just "?" for "Help" menu. This is // correctly handled by wxWidgets catalogs, but Poedit catalog has "Help" // entry too, so we add wxmsw.mo catalog again so that it takes // precedence over poedit.mo: m_locale.AddCatalog(_T("wxmsw")); #endif #ifdef __WXMAC__ // so that help menu is correctly merged with system-provided menu // (see http://sourceforge.net/tracker/index.php?func=detail&aid=1600747&group_id=9863&atid=309863) s_macHelpMenuTitleName = _("&Help"); #endif #ifdef USE_TRANSMEM // NB: It's important to do this before TM is used for the first time. TranslationMemory::MoveLegacyDbIfNeeded(); #endif // NB: opening files or creating empty window is handled differently on // Macs, using MacOpenFile() and MacNewFile(), so don't create empty // window if no files are given on command line; but still support // passing files on command line if (!gs_filesToOpen.empty()) { for (size_t i = 0; i < gs_filesToOpen.GetCount(); i++) OpenFile(gs_filesToOpen[i]); gs_filesToOpen.clear(); } #ifndef __WXMAC__ else { OpenNewFile(); } #endif // !__WXMAC__ #ifdef USE_SPARKLE // Remove config key for Sparkle < 1.5. UserDefaults::RemoveValue("SUCheckAtStartup"); SUSparkleInitializeForCarbon(); #endif // USE_SPARKLE #ifdef __WXMSW__ const char *appcast = "https://dl.updatica.com/poedit-win/appcast"; if ( GetAppVersion().Contains(_T("beta")) || GetAppVersion().Contains(_T("rc")) ) { // Beta versions use unstable feed. appcast = "https://dl.updatica.com/poedit-win/appcast/beta"; } win_sparkle_set_appcast_url(appcast); win_sparkle_init(); #endif return true; } int PoeditApp::OnExit() { #ifdef __WXMSW__ win_sparkle_cleanup(); #endif return wxApp::OnExit(); } void PoeditApp::OpenNewFile() { if (wxConfig::Get()->Read(_T("manager_startup"), (long)false)) ManagerFrame::Create()->Show(true); else PoeditFrame::Create(wxEmptyString); } void PoeditApp::OpenFile(const wxString& name) { PoeditFrame::Create(name); } void PoeditApp::SetDefaultParsers(wxConfigBase *cfg) { ParsersDB pdb; bool changed = false; wxString defaultsVersion = cfg->Read(_T("Parsers/DefaultsVersion"), _T("1.2.x")); pdb.Read(cfg); // Add parsers for languages supported by gettext itself (but only if the // user didn't already add language with this name himself): static struct { const wxChar *name; const wxChar *exts; } s_gettextLangs[] = { { _T("C/C++"), _T("*.c;*.cpp;*.h;*.hpp;*.cc;*.C;*.cxx;*.hxx") }, { _T("C#"), _T("*.cs") }, { _T("Java"), _T("*.java") }, { _T("Perl"), _T("*.pl") }, { _T("PHP"), _T("*.php") }, { _T("Python"), _T("*.py") }, { _T("TCL"), _T("*.tcl") }, { NULL, NULL } }; for (size_t i = 0; s_gettextLangs[i].name != NULL; i++) { // if this lang is already registered, don't overwrite it: if (pdb.FindParser(s_gettextLangs[i].name) != -1) continue; wxString langflag; if ( wxStrcmp(s_gettextLangs[i].name, _T("C/C++")) == 0 ) langflag = _T(" --language=C++"); else langflag = wxString(_T(" --language=")) + s_gettextLangs[i].name; // otherwise add new parser: Parser p; p.Name = s_gettextLangs[i].name; p.Extensions = s_gettextLangs[i].exts; p.Command = wxString(_T("xgettext")) + langflag + _T(" --force-po -o %o %C %K %F"); p.KeywordItem = _T("-k%k"); p.FileItem = _T("%f"); p.CharsetItem = _T("--from-code=%c"); pdb.Add(p); changed = true; } // If upgrading Poedit to 1.2.4, add dxgettext parser for Delphi: #ifdef __WINDOWS__ if (defaultsVersion == _T("1.2.x")) { Parser p; p.Name = _T("Delphi (dxgettext)"); p.Extensions = _T("*.pas;*.dpr;*.xfm;*.dfm"); p.Command = _T("dxgettext --so %o %F"); p.KeywordItem = wxEmptyString; p.FileItem = _T("%f"); pdb.Add(p); changed = true; } #endif // If upgrading Poedit to 1.2.5, update C++ parser to handle --from-code: if (defaultsVersion == _T("1.2.x") || defaultsVersion == _T("1.2.4")) { int cpp = pdb.FindParser(_T("C/C++")); if (cpp != -1) { if (pdb[cpp].Command == _T("xgettext --force-po -o %o %K %F")) { pdb[cpp].Command = _T("xgettext --force-po -o %o %C %K %F"); pdb[cpp].CharsetItem = _T("--from-code=%c"); changed = true; } } } if (changed) { pdb.Write(cfg); cfg->Write(_T("Parsers/DefaultsVersion"), GetAppVersion()); } } void PoeditApp::SetDefaultCfg(wxConfigBase *cfg) { SetDefaultParsers(cfg); if (cfg->Read(_T("version"), wxEmptyString) == GetAppVersion()) return; if (cfg->Read(_T("TM/search_paths"), wxEmptyString).empty()) { wxString paths; #if defined(__UNIX__) paths = wxGetHomeDir() + _T(":/usr/share/locale:/usr/local/share/locale"); #elif defined(__WXMSW__) paths = _T("C:"); #endif cfg->Write(_T("TM/search_paths"), paths); } cfg->Write(_T("version"), GetAppVersion()); } namespace { const wxChar *CL_KEEP_TEMP_FILES = _T("keep-temp-files"); } void PoeditApp::OnInitCmdLine(wxCmdLineParser& parser) { wxApp::OnInitCmdLine(parser); parser.AddSwitch(_T(""), CL_KEEP_TEMP_FILES, _("don't delete temporary files (for debugging)")); parser.AddParam(_T("catalog.po"), wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL | wxCMD_LINE_PARAM_MULTIPLE); } bool PoeditApp::OnCmdLineParsed(wxCmdLineParser& parser) { if (!wxApp::OnCmdLineParsed(parser)) return false; if ( parser.Found(CL_KEEP_TEMP_FILES) ) TempDirectory::KeepFiles(); for (size_t i = 0; i < parser.GetParamCount(); i++) gs_filesToOpen.Add(parser.GetParam(i)); return true; } <|endoftext|>
<commit_before>/* * Copyright (c) 2015 The Jackson Laboratory * * This software was developed by Gary Churchill's Lab at The Jackson * Laboratory (see http://research.jax.org/faculty/churchill). * * This is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software. If not, see <http://www.gnu.org/licenses/>. */ // // populase.cpp // // // Created by Glen Beane on 8/20/14. // // #include <iostream> #include <getopt.h> #include "alignment_incidence_matrix.h" #include "sample_allelic_expression.h" #include "python_interface.h" #include "kallisto_import.h" void print_help(); int main(int argc, char **argv) { AlignmentIncidenceMatrix *aim; bool binary_input = false; int num_iterations; int max_iterations = 200; int read_length = 100; SampleAllelicExpression::model model = SampleAllelicExpression::MODEL_2; int m; clock_t t1, t2; float diff; std::string input_filename; std::string output_filename; std::string transcript_length_file; std::string extension = ".pcl.bz2"; std::string gene_file; //getopt related variables int c; int option_index = 0; bool bad_args = false; static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"model", required_argument, 0, 'm'}, {"output", required_argument, 0, 'o'}, {"read-length", required_argument, 0, 'k'}, {"transcript-lengths", required_argument, 0, 'l'}, {"max-iterations", required_argument, 0, 'i'}, {"bin", no_argument, 0, 'b'}, {"gene-mappings", required_argument, 0, 'g'}, {0, 0, 0, 0} }; while ((c = getopt_long(argc, argv, "hm:o:k:l:i:bg:", long_options, &option_index)) != -1) { switch (c) { case 'h': print_help(); return 0; case 'm': m = std::stoi(optarg); if (m < 1 || m > 4) { std::cerr << "Invalid model number specified. Valid options: 1, 2, 3, 4\n"; } switch (m) { case 1: model = SampleAllelicExpression::MODEL_1; break; case 2: model = SampleAllelicExpression::MODEL_2; break; case 3: std::cerr << "Model 3 is currently unimplemented, please specify a different model\n"; return 1; case 4: model = SampleAllelicExpression::MODEL_4; break; } break; case 'o': output_filename = std::string(optarg); break; case 'k': read_length = std::stoi(optarg); break; case 'l': transcript_length_file = std::string(optarg); break; case 'i': max_iterations = std::stoi(optarg); break; case 'b': binary_input = true; break; case 'g': gene_file = std::string(optarg); break; case '?': bad_args = true; } } if (bad_args) { print_help(); return 1; } if (argc - optind == 1) { input_filename = argv[optind]; } else { std::cerr << "Missing required argument (input file name)\n"; print_help(); return 1; } if (!binary_input && (extension.size() >= input_filename.size() || !std::equal(extension.rbegin(), extension.rend(), input_filename.rbegin()))) { std::cerr << "Error, expected file with .pcl.bz2 extension. Input file should be prepared with bam_to_pcl.py script.\n"; return 1; } if (output_filename.empty()) { //use default, based on the input file name but placed in current working directdory if (!binary_input) { output_filename = input_filename.substr(0, input_filename.size() - extension.size()).append(".stacksum.tsv"); } else { output_filename = input_filename; output_filename.append(".stacksum.tsv"); } //check to see if there was a path in the input file name. If so, trim it off std::size_t found = output_filename.rfind('/'); if (found != std::string::npos) { output_filename = output_filename.substr(found+1); } } if (binary_input) { std::cout << "Loading " << input_filename << "..." << std::endl; aim = loadFromBin(input_filename); if (!aim) { std::cerr << "Error loading binary input file\n"; return 1; } } else { PythonInterface pi = PythonInterface(); if (pi.init()){ std::cerr << "Error importing TranscriptHits Python module.\n"; std::cerr << '\t' << pi.getErrorString() << std::endl; return 1; } std::cout << "Loading " << input_filename << ". This may take a while..." << std::endl; aim = pi.load(input_filename); if (!aim) { std::cerr << "Error loading pcl file\n"; std::cerr << '\t' << pi.getErrorString() << std::endl; return 1; } } std::cout << "Alignment Incidence file " << input_filename << std::endl; std::vector<std::string> hap_names = aim->get_haplotype_names(); std::cout << "File had the following haplotype names:\n"; for (std::vector<std::string>::iterator it = hap_names.begin(); it != hap_names.end(); ++it) { std::cout << *it << "\t"; } std::cout << std::endl; std::cout << aim->num_reads() << " reads loaded\n"; std::cout << aim->num_transcripts() << " transcripts\n"; std::cout << std::endl; if (!transcript_length_file.empty()) { std::cout << "Loading Transcript Length File " << transcript_length_file << std::endl; aim->loadTranscriptLengths(transcript_length_file); } if (!gene_file.empty()) { std::cout << "Loading Gene Mapping File " << gene_file << std::endl; aim->loadGeneMappings(gene_file); } if (model != SampleAllelicExpression::MODEL_4 && !aim->has_gene_mappings()) { std::cerr << "File does not contain transcript to gene mapping information. Only normalization Model 4 can be used.\n"; return 1; } t1 = clock(); SampleAllelicExpression sae(aim, read_length); t2 = clock(); diff = ((float)t2-(float)t1)/CLOCKS_PER_SEC; std::cout << "Time for initializing stack sum = " << diff << "s" << std::endl; if (max_iterations > 0) { num_iterations = 0; std::cout << "Beginning EM Iterations" << std::endl; t1 = clock(); do { sae.update(model); } while (++num_iterations < max_iterations && !sae.converged()); t2 = clock(); diff = ((float)t2-(float)t1)/CLOCKS_PER_SEC; std::cout << "Time for " << num_iterations << " iterations = " << diff << "s\n"; std::cout << "Time per iteration " << diff/num_iterations << "s\n"; } std::cout << "Saving results to " << output_filename << std::endl; sae.saveStackSums(output_filename); std::cout << "Done.\n"; return 0; } void print_help() { std::cout << std::endl << std::endl << "EMASE Help\n" << "----------\n\n" << "USAGE: emase [options] <alignment_incidence>\n\n" << "INPUT: Alignment Incidence file prepared with bam_to_pcl.py script\n\n" << "OPTIONS\n" << " --model (-m) : Specify normalization model (can be 1-4, default=2)\n" << " --output (-o) : Specify filename for output file (default is input_basename.stacksum.tsv)\n" << " --transcript-lengths (-l) : Filename for transcript length file. Format is \"transcript_id\tlength\"\n" << " --read-length (-k) : Specify read length for use when applying transcript length adjustment.\n" << " Ignored unless combined with --transcript-lengths. (Default 100)\n" << " --max-iterations (-i) : Specify the maximum number of EM iterations. (Default 200)\n" << " --help (-h) : Print this message and exit\n\n"; } <commit_msg>update --help output<commit_after>/* * Copyright (c) 2015 The Jackson Laboratory * * This software was developed by Gary Churchill's Lab at The Jackson * Laboratory (see http://research.jax.org/faculty/churchill). * * This is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software. If not, see <http://www.gnu.org/licenses/>. */ // // populase.cpp // // // Created by Glen Beane on 8/20/14. // // #include <iostream> #include <getopt.h> #include "alignment_incidence_matrix.h" #include "sample_allelic_expression.h" #include "python_interface.h" #include "kallisto_import.h" void print_help(); int main(int argc, char **argv) { AlignmentIncidenceMatrix *aim; bool binary_input = false; int num_iterations; int max_iterations = 200; int read_length = 100; SampleAllelicExpression::model model = SampleAllelicExpression::MODEL_2; int m; clock_t t1, t2; float diff; std::string input_filename; std::string output_filename; std::string transcript_length_file; std::string extension = ".pcl.bz2"; std::string gene_file; //getopt related variables int c; int option_index = 0; bool bad_args = false; static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"model", required_argument, 0, 'm'}, {"output", required_argument, 0, 'o'}, {"read-length", required_argument, 0, 'k'}, {"transcript-lengths", required_argument, 0, 'l'}, {"max-iterations", required_argument, 0, 'i'}, {"bin", no_argument, 0, 'b'}, {"gene-mappings", required_argument, 0, 'g'}, {0, 0, 0, 0} }; while ((c = getopt_long(argc, argv, "hm:o:k:l:i:bg:", long_options, &option_index)) != -1) { switch (c) { case 'h': print_help(); return 0; case 'm': m = std::stoi(optarg); if (m < 1 || m > 4) { std::cerr << "Invalid model number specified. Valid options: 1, 2, 3, 4\n"; } switch (m) { case 1: model = SampleAllelicExpression::MODEL_1; break; case 2: model = SampleAllelicExpression::MODEL_2; break; case 3: std::cerr << "Model 3 is currently unimplemented, please specify a different model\n"; return 1; case 4: model = SampleAllelicExpression::MODEL_4; break; } break; case 'o': output_filename = std::string(optarg); break; case 'k': read_length = std::stoi(optarg); break; case 'l': transcript_length_file = std::string(optarg); break; case 'i': max_iterations = std::stoi(optarg); break; case 'b': binary_input = true; break; case 'g': gene_file = std::string(optarg); break; case '?': bad_args = true; } } if (bad_args) { print_help(); return 1; } if (argc - optind == 1) { input_filename = argv[optind]; } else { std::cerr << "Missing required argument (input file name)\n"; print_help(); return 1; } if (!binary_input && (extension.size() >= input_filename.size() || !std::equal(extension.rbegin(), extension.rend(), input_filename.rbegin()))) { std::cerr << "Error, expected file with .pcl.bz2 extension. Input file should be prepared with bam_to_pcl.py script.\n"; return 1; } if (output_filename.empty()) { //use default, based on the input file name but placed in current working directdory if (!binary_input) { output_filename = input_filename.substr(0, input_filename.size() - extension.size()).append(".stacksum.tsv"); } else { output_filename = input_filename; output_filename.append(".stacksum.tsv"); } //check to see if there was a path in the input file name. If so, trim it off std::size_t found = output_filename.rfind('/'); if (found != std::string::npos) { output_filename = output_filename.substr(found+1); } } if (binary_input) { std::cout << "Loading " << input_filename << "..." << std::endl; aim = loadFromBin(input_filename); if (!aim) { std::cerr << "Error loading binary input file\n"; return 1; } } else { PythonInterface pi = PythonInterface(); if (pi.init()){ std::cerr << "Error importing TranscriptHits Python module.\n"; std::cerr << '\t' << pi.getErrorString() << std::endl; return 1; } std::cout << "Loading " << input_filename << ". This may take a while..." << std::endl; aim = pi.load(input_filename); if (!aim) { std::cerr << "Error loading pcl file\n"; std::cerr << '\t' << pi.getErrorString() << std::endl; return 1; } } std::cout << "Alignment Incidence file " << input_filename << std::endl; std::vector<std::string> hap_names = aim->get_haplotype_names(); std::cout << "File had the following haplotype names:\n"; for (std::vector<std::string>::iterator it = hap_names.begin(); it != hap_names.end(); ++it) { std::cout << *it << "\t"; } std::cout << std::endl; std::cout << aim->num_reads() << " reads loaded\n"; std::cout << aim->num_transcripts() << " transcripts\n"; std::cout << std::endl; if (!transcript_length_file.empty()) { std::cout << "Loading Transcript Length File " << transcript_length_file << std::endl; aim->loadTranscriptLengths(transcript_length_file); } if (!gene_file.empty()) { std::cout << "Loading Gene Mapping File " << gene_file << std::endl; aim->loadGeneMappings(gene_file); } if (model != SampleAllelicExpression::MODEL_4 && !aim->has_gene_mappings()) { std::cerr << "File does not contain transcript to gene mapping information. Only normalization Model 4 can be used.\n"; return 1; } t1 = clock(); SampleAllelicExpression sae(aim, read_length); t2 = clock(); diff = ((float)t2-(float)t1)/CLOCKS_PER_SEC; std::cout << "Time for initializing stack sum = " << diff << "s" << std::endl; if (max_iterations > 0) { num_iterations = 0; std::cout << "Beginning EM Iterations" << std::endl; t1 = clock(); do { sae.update(model); } while (++num_iterations < max_iterations && !sae.converged()); t2 = clock(); diff = ((float)t2-(float)t1)/CLOCKS_PER_SEC; std::cout << "Time for " << num_iterations << " iterations = " << diff << "s\n"; std::cout << "Time per iteration " << diff/num_iterations << "s\n"; } std::cout << "Saving results to " << output_filename << std::endl; sae.saveStackSums(output_filename); std::cout << "Done.\n"; return 0; } void print_help() { std::cout << std::endl << std::endl << "EMASE Help\n" << "----------\n\n" << "USAGE: emase2 [options] <alignment_incidence_file>\n\n" << "INPUT: Alignment Incidence file prepared with bam_to_pcl.py script\n\n" << "OPTIONS\n" << " --model (-m) : Specify normalization model (can be 1-4, default=2)\n" << " --bin (-b) : Binary input mode, with this option emase2 will expect a binary\n" << " file exported from Kallisto as input\n" << " --output (-o) : Specify filename for output file (default is\n" << " input_basename.stacksum.tsv)\n" << " --transcript-lengths (-l) : Filename for transcript length file. Format is\n" << " \"transcript_id\tlength\"\n" << " --gene-mappings (-g) : Filename containing transcript to gene mapping. Tab\n" << " delimited file where the first field is the gene ID,\n" << " all other fields are the transcript IDs that belong\n" << " to that gene\n" << " --read-length (-k) : Specify read length for use when applying transcript\n" << " length adjustment. Ignored unless combined with\n" << " --transcript-lengths. (Default 100)\n" << " --max-iterations (-i) : Specify the maximum number of EM iterations.\n" << " (Default 200)\n" << " --help (-h) : Print this message and exit\n\n"; } <|endoftext|>
<commit_before>/* * engine.cc * * Author: Lunatic */ #include "engine.h" #include "alarm.h" #include <cstdlib> namespace Script { static void assert(bool cond, const std::string& msg, const Position& pos) { if (!cond) error(msg, pos); } static long long str2int(const std::string& val) { //char *err = NULL; //long long retval = std::strtoll(val.c_str(), &err, 10); //if (*err == '\0') //return retval; //忽略错误 return std::strtoll(val.c_str(), NULL, 10); } static std::string get_val(Env& env, Token& token) { if (token.type == kName) { //处理变量 assert(env.exist_var(token.content), "变量未定义!", token.pos); return env.get_var(token.content); } return token.content; } struct Commands { static void exit_cmd(Env& env, Instruction& pc) { //std::exit(0); throw "Bye-bye"; } // static void add_cmd(Env& env) { // return x + y; // } static void goto_cmd(Env& env, Instruction& pc) { assert(pc.params.size() == 1 && pc.params[0].type == kName, "语法错误", pc.pos); Log::debug(pc.params[0].content); int ret = env.get_goto_Idx(pc.params[0].content); assert(ret != -1, "找不到跳转位置!", pc.pos); env.set_idx((size_t) ret); } static void say_cmd(Env& env, Instruction& pc) { assert(pc.params.size() > 0, "语法错误!", pc.pos); for (std::vector<Token>::iterator it = pc.params.begin(); it != pc.params.end(); ++it) { if (it->type == kName) { assert(env.exist_var(it->content), "变量未定义!", it->pos); std::cout << env.get_var(it->content) << ' '; //sep by ' ' } else std::cout << it->content; } std::cout << std::endl; } static void read_cmd(Env& env, Instruction& pc) { assert(pc.params.size() == 1 && pc.params[0].type == kName, "语法错误", pc.pos); std::string temp; std::cin >> temp; env.set_var(pc.params[0].content, temp); } static void if_cmd(Env& env, Instruction& pc) { //if value1 [opcode value2] goto label bool jmp = false; assert(pc.params.size() == 5 && pc.params[1].type == KCmp, "goto语法错误!", pc.pos); //if val goto label std::string left = get_val(env, pc.params[0]); std::string right = get_val(env, pc.params[2]); if (pc.params[1].content == "==") { jmp = left == right; } else if (pc.params[1].content == "!=") { jmp = left != right; } else if (pc.params[1].content == "<") { jmp = str2int(left) < str2int(right); } else if (pc.params[1].content == ">") { jmp = str2int(left) > str2int(right); } else if (pc.params[1].content == "<=") { jmp = str2int(left) <= str2int(right); } else if (pc.params[1].content == ">=") { jmp = str2int(left) < str2int(right); } if (jmp && pc.params[3].type == kName && pc.params[3].content == "goto" && pc.params[4].type == kName) { Token copy = pc.params[4]; pc.pos = pc.params[3].pos; pc.params.clear(); pc.params.push_back(copy); goto_cmd(env, pc); } else if (jmp) { error("goto语句后面必须带有一个跳转Label", pc.params[4].pos); } } static void shell_cmd(Env& env, Instruction& pc) { assert(pc.params.size() > 0, "语法错误!", pc.pos); std::string command; std::vector<Token>::iterator it = pc.params.begin(); for (; it != pc.params.end(); it++) { Log::debug("val name: %s",it->content.c_str()); command.append(get_val(env, *it)); command.append(" "); } command = command.substr(0, command.size() - 1); Log::debug("Shell: %s", command.c_str()); std::system(command.c_str()); } }; bool Env::exist_var(const std::string& name) { return vars.find(name) != vars.end(); } std::string Env::get_var(const std::string& name) { return vars.find(name)->second; } void Env::set_var(const std::string& name, const std::string& value) { vars[name] = value; } void Env::load(const std::string& text) { Lexer lexer(text); Parser parser(lexer); parser.parse(insts, labels); } Engine::Engine() { cmds["exit"] = Commands::exit_cmd; cmds["goto"] = Commands::goto_cmd; cmds["say"] = Commands::say_cmd; cmds["read"] = Commands::read_cmd; cmds["if"] = Commands::if_cmd; cmds["shell"] = Commands::shell_cmd; } void Engine::launch(Env& env) { while (!env.finish()) { Instruction& pc = env.next_inst(); Log::debug("当前执行指令:%s", pc.to_str().c_str()); func f = get_cmd(pc.name); if (f == NULL) { Log::error("无法识别的命令“%s”", pc.name.c_str()); error("无法识别的命令!", pc.pos); } f(env, pc); } } } <commit_msg>add print cmd<commit_after>/* * engine.cc * * Author: Lunatic */ #include "engine.h" #include "alarm.h" #include <cstdlib> namespace Script { static void assert(bool cond, const std::string& msg, const Position& pos) { if (!cond) error(msg, pos); } static long long str2int(const std::string& val) { //char *err = NULL; //long long retval = std::strtoll(val.c_str(), &err, 10); //if (*err == '\0') //return retval; //忽略错误 return std::strtoll(val.c_str(), NULL, 10); } static std::string get_val(Env& env, Token& token) { if (token.type == kName) { //处理变量 assert(env.exist_var(token.content), "变量未定义!", token.pos); return env.get_var(token.content); } return token.content; } struct Commands { static void exit_cmd(Env& env, Instruction& pc) { //std::exit(0); throw "Bye-bye"; } // static void add_cmd(Env& env) { // return x + y; // } static void goto_cmd(Env& env, Instruction& pc) { assert(pc.params.size() == 1 && pc.params[0].type == kName, "语法错误", pc.pos); Log::debug(pc.params[0].content); int ret = env.get_goto_Idx(pc.params[0].content); assert(ret != -1, "找不到跳转位置!", pc.pos); env.set_idx((size_t) ret); } static void say_cmd(Env& env, Instruction& pc) { assert(pc.params.size() > 0, "语法错误!", pc.pos); for (std::vector<Token>::iterator it = pc.params.begin(); it != pc.params.end(); ++it) { if (it->type == kName) { assert(env.exist_var(it->content), "变量未定义!", it->pos); std::cout << env.get_var(it->content) << ' '; //sep by ' ' } else std::cout << it->content; } std::cout << std::endl; } static void read_cmd(Env& env, Instruction& pc) { assert(pc.params.size() == 1 && pc.params[0].type == kName, "语法错误", pc.pos); std::string temp; std::cin >> temp; env.set_var(pc.params[0].content, temp); } static void if_cmd(Env& env, Instruction& pc) { //if value1 [opcode value2] goto label bool jmp = false; assert(pc.params.size() == 5 && pc.params[1].type == KCmp, "goto语法错误!", pc.pos); //if val goto label std::string left = get_val(env, pc.params[0]); std::string right = get_val(env, pc.params[2]); if (pc.params[1].content == "==") { jmp = left == right; } else if (pc.params[1].content == "!=") { jmp = left != right; } else if (pc.params[1].content == "<") { jmp = str2int(left) < str2int(right); } else if (pc.params[1].content == ">") { jmp = str2int(left) > str2int(right); } else if (pc.params[1].content == "<=") { jmp = str2int(left) <= str2int(right); } else if (pc.params[1].content == ">=") { jmp = str2int(left) < str2int(right); } if (jmp && pc.params[3].type == kName && pc.params[3].content == "goto" && pc.params[4].type == kName) { Token copy = pc.params[4]; pc.pos = pc.params[3].pos; pc.params.clear(); pc.params.push_back(copy); goto_cmd(env, pc); } else if (jmp) { error("goto语句后面必须带有一个跳转Label", pc.params[4].pos); } } static void shell_cmd(Env& env, Instruction& pc) { assert(pc.params.size() > 0, "语法错误!", pc.pos); std::string command; std::vector<Token>::iterator it = pc.params.begin(); for (; it != pc.params.end(); it++) { Log::debug("val name: %s",it->content.c_str()); command.append(get_val(env, *it)); command.append(" "); } command = command.substr(0, command.size() - 1); Log::debug("Shell: %s", command.c_str()); std::system(command.c_str()); } }; bool Env::exist_var(const std::string& name) { return vars.find(name) != vars.end(); } std::string Env::get_var(const std::string& name) { return vars.find(name)->second; } void Env::set_var(const std::string& name, const std::string& value) { vars[name] = value; } void Env::load(const std::string& text) { Lexer lexer(text); Parser parser(lexer); parser.parse(insts, labels); } Engine::Engine() { cmds["exit"] = Commands::exit_cmd; cmds["goto"] = Commands::goto_cmd; cmds["say"] = Commands::say_cmd; cmds["print"] = Commands::say_cmd; cmds["read"] = Commands::read_cmd; cmds["if"] = Commands::if_cmd; cmds["shell"] = Commands::shell_cmd; } void Engine::launch(Env& env) { while (!env.finish()) { Instruction& pc = env.next_inst(); Log::debug("当前执行指令:%s", pc.to_str().c_str()); func f = get_cmd(pc.name); if (f == NULL) { Log::error("无法识别的命令“%s”", pc.name.c_str()); error("无法识别的命令!", pc.pos); } f(env, pc); } } } <|endoftext|>
<commit_before>/* * The MIT License (MIT) * * Copyright (c) 2013 Ahmed H. Ismail * * 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 "weather_service.hpp" static const char * version = "0.1.0 Alpha"; static void print_help() { std::cout << "cweather weather utility version : " << version << "\nusage cweather [COUNTRY] [CITY]" << "\nor cweather [OPTION]" << "\nValid options : " << "\n--help or -h :\n\tprints this help message." << "\n--about or --version or -v :\n\tprints version and copyright notice.\n"; } static void print_info() { std::cout << "cweather weather utility version : " << version << ".\nCopytight (C) 2013 Ahmed H. Ismail." << "\nReleased under MIT License." << "\nSource code and License can be found at http://github.com/ah450/cweather .\n"; } int main( int argc, const char * argv[] ) { if( argc >= 3 ) { cweather::service::WebServiceXWeatherService to_test; try { auto data = to_test.get_weather_data( argv[1], argv[2] ); std::cout << "Temperature : " << data.temperature << " C." << "\nWind Speed : " << data.wind_speed << " KPH." << "\nWind Direction : " << data.wind_direction << " Degrees." << "\nPressure : " << data.pressure << " Pascal." << "\nVisibility : " << data.visibility << " Kilometers." << "\nHumidity : " << data.humidity * 100 << "%." ; return 0; } catch( cweather::exceptions::IncorrectLocationException& ) { std::cerr << "Incorrect paramaters.\nrun cweather --help for usage information.\n"; } } else if ( argc == 2 ) { auto argument = std::string( argv[1] ); if( argument == "--about" || argument == "--version" || argument == "-v" ) { print_info(); return 0; } else { print_help(); } } else { print_help(); return -1; } }<commit_msg>Updates command line help output.<commit_after>/* * The MIT License (MIT) * * Copyright (c) 2013 Ahmed H. Ismail * * 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 "weather_service.hpp" static const char * version = "0.1.0 Alpha"; static void print_help() { std::cout << "cweather weather utility version : " << version << "\nusage cweather [COUNTRY] [CITY]" << "\nTo use with multi word city or country name use the following syntax : " << "\n\tcweather 'COUNTRY_WORD_ONE COUNTRY_WORD_TWO' 'CITY_WORD_ONE CITY_WORD_TWO'" << "\nor cweather [OPTION]" << "\nValid options : " << "\n--help or -h :\n\tprints this help message." << "\n--about or --version or -v :\n\tprints version and copyright notice.\n"; } static void print_info() { std::cout << "cweather weather utility version : " << version << ".\nCopytight (C) 2013 Ahmed H. Ismail." << "\nReleased under MIT License." << "\nSource code and License can be found at http://github.com/ah450/cweather .\n"; } int main( int argc, const char * argv[] ) { if( argc >= 3 ) { cweather::service::WebServiceXWeatherService to_test; try { auto data = to_test.get_weather_data( argv[1], argv[2] ); std::cout << "Temperature : " << data.temperature << " C." << "\nWind Speed : " << data.wind_speed << " KPH." << "\nWind Direction : " << data.wind_direction << " Degrees." << "\nPressure : " << data.pressure << " Pascal." << "\nVisibility : " << data.visibility << " Kilometers." << "\nHumidity : " << data.humidity * 100 << "%.\n" ; return 0; } catch( cweather::exceptions::IncorrectLocationException& ) { std::cerr << "Incorrect paramaters.\nrun cweather --help for usage information.\n"; } } else if ( argc == 2 ) { auto argument = std::string( argv[1] ); if( argument == "--about" || argument == "--version" || argument == "-v" ) { print_info(); return 0; } else { print_help(); } } else { print_help(); return -1; } }<|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg 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 the author 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. */ #include "libtorrent/pch.hpp" #include <algorithm> #include <iostream> #include <iomanip> #include "libtorrent/entry.hpp" #include "libtorrent/config.hpp" #if defined(_MSC_VER) namespace std { using ::isprint; } #define for if (false) {} else for #endif namespace { template <class T> void call_destructor(T* o) { TORRENT_ASSERT(o); o->~T(); } struct compare_string { compare_string(char const* s): m_str(s) {} bool operator()( std::pair<std::string , libtorrent::entry> const& e) const { return m_str && e.first == m_str; } char const* m_str; }; } namespace libtorrent { namespace detail { TORRENT_EXPORT char const* integer_to_str(char* buf, int size, entry::integer_type val) { int sign = 0; if (val < 0) { sign = 1; val = -val; } buf[--size] = '\0'; if (val == 0) buf[--size] = '0'; for (; size > sign && val != 0;) { buf[--size] = '0' + char(val % 10); val /= 10; } if (sign) buf[--size] = '-'; return buf + size; } } entry& entry::operator[](char const* key) { dictionary_type::iterator i = dict().find(key); if (i != dict().end()) return i->second; dictionary_type::iterator ret = dict().insert( dict().begin() , std::make_pair(std::string(key), entry())); return ret->second; } entry& entry::operator[](std::string const& key) { return (*this)[key.c_str()]; } entry* entry::find_key(char const* key) { dictionary_type::iterator i = std::find_if( dict().begin() , dict().end() , compare_string(key)); if (i == dict().end()) return 0; return &i->second; } entry const* entry::find_key(char const* key) const { dictionary_type::const_iterator i = dict().find(key); if (i == dict().end()) return 0; return &i->second; } #ifndef BOOST_NO_EXCEPTIONS const entry& entry::operator[](char const* key) const { dictionary_type::const_iterator i = dict().find(key); if (i == dict().end()) throw type_error( (std::string("key not found: ") + key).c_str()); return i->second; } const entry& entry::operator[](std::string const& key) const { return (*this)[key.c_str()]; } #endif entry::entry() : m_type(undefined_t) { #ifndef NDEBUG m_type_queried = true; #endif } entry::entry(data_type t) : m_type(undefined_t) { construct(t); #ifndef NDEBUG m_type_queried = true; #endif } entry::entry(const entry& e) : m_type(undefined_t) { copy(e); #ifndef NDEBUG m_type_queried = e.m_type_queried; #endif } entry::entry(dictionary_type const& v) : m_type(undefined_t) { #ifndef NDEBUG m_type_queried = true; #endif new(data) dictionary_type(v); m_type = dictionary_t; } entry::entry(string_type const& v) : m_type(undefined_t) { #ifndef NDEBUG m_type_queried = true; #endif new(data) string_type(v); m_type = string_t; } entry::entry(list_type const& v) : m_type(undefined_t) { #ifndef NDEBUG m_type_queried = true; #endif new(data) list_type(v); m_type = list_t; } entry::entry(integer_type const& v) : m_type(undefined_t) { #ifndef NDEBUG m_type_queried = true; #endif new(data) integer_type(v); m_type = int_t; } void entry::operator=(dictionary_type const& v) { destruct(); new(data) dictionary_type(v); m_type = dictionary_t; #ifndef NDEBUG m_type_queried = true; #endif } void entry::operator=(string_type const& v) { destruct(); new(data) string_type(v); m_type = string_t; #ifndef NDEBUG m_type_queried = true; #endif } void entry::operator=(list_type const& v) { destruct(); new(data) list_type(v); m_type = list_t; #ifndef NDEBUG m_type_queried = true; #endif } void entry::operator=(integer_type const& v) { destruct(); new(data) integer_type(v); m_type = int_t; #ifndef NDEBUG m_type_queried = true; #endif } bool entry::operator==(entry const& e) const { if (m_type != e.m_type) return false; switch(m_type) { case int_t: return integer() == e.integer(); case string_t: return string() == e.string(); case list_t: return list() == e.list(); case dictionary_t: return dict() == e.dict(); default: TORRENT_ASSERT(m_type == undefined_t); return true; } } void entry::construct(data_type t) { switch(t) { case int_t: new(data) integer_type; break; case string_t: new(data) string_type; break; case list_t: new(data) list_type; break; case dictionary_t: new (data) dictionary_type; break; default: TORRENT_ASSERT(t == undefined_t); } m_type = t; #ifndef NDEBUG m_type_queried = true; #endif } void entry::copy(entry const& e) { switch (e.type()) { case int_t: new(data) integer_type(e.integer()); break; case string_t: new(data) string_type(e.string()); break; case list_t: new(data) list_type(e.list()); break; case dictionary_t: new (data) dictionary_type(e.dict()); break; default: TORRENT_ASSERT(e.type() == undefined_t); } m_type = e.type(); #ifndef NDEBUG m_type_queried = true; #endif } void entry::destruct() { switch(m_type) { case int_t: call_destructor(reinterpret_cast<integer_type*>(data)); break; case string_t: call_destructor(reinterpret_cast<string_type*>(data)); break; case list_t: call_destructor(reinterpret_cast<list_type*>(data)); break; case dictionary_t: call_destructor(reinterpret_cast<dictionary_type*>(data)); break; default: TORRENT_ASSERT(m_type == undefined_t); break; } m_type = undefined_t; #ifndef NDEBUG m_type_queried = false; #endif } void entry::swap(entry& e) { // not implemented TORRENT_ASSERT(false); } void entry::print(std::ostream& os, int indent) const { TORRENT_ASSERT(indent >= 0); for (int i = 0; i < indent; ++i) os << " "; switch (m_type) { case int_t: os << integer() << "\n"; break; case string_t: { bool binary_string = false; for (std::string::const_iterator i = string().begin(); i != string().end(); ++i) { if (!std::isprint(static_cast<unsigned char>(*i))) { binary_string = true; break; } } if (binary_string) { os.unsetf(std::ios_base::dec); os.setf(std::ios_base::hex); for (std::string::const_iterator i = string().begin(); i != string().end(); ++i) os << std::setfill('0') << std::setw(2) << static_cast<unsigned int>((unsigned char)*i); os.unsetf(std::ios_base::hex); os.setf(std::ios_base::dec); os << "\n"; } else { os << string() << "\n"; } } break; case list_t: { os << "list\n"; for (list_type::const_iterator i = list().begin(); i != list().end(); ++i) { i->print(os, indent+1); } } break; case dictionary_t: { os << "dictionary\n"; for (dictionary_type::const_iterator i = dict().begin(); i != dict().end(); ++i) { for (int j = 0; j < indent+1; ++j) os << " "; os << "[" << i->first << "]"; if (i->second.type() != entry::string_t && i->second.type() != entry::int_t) os << "\n"; else os << " "; i->second.print(os, indent+2); } } break; default: os << "<uninitialized>\n"; } } } <commit_msg>fixed include issue in entry.cpp<commit_after>/* Copyright (c) 2003, Arvid Norberg 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 the author 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. */ #include "libtorrent/pch.hpp" #include <algorithm> #include <iostream> #include <iomanip> #include <iostream> #include "libtorrent/entry.hpp" #include "libtorrent/config.hpp" #if defined(_MSC_VER) namespace std { using ::isprint; } #define for if (false) {} else for #endif namespace { template <class T> void call_destructor(T* o) { TORRENT_ASSERT(o); o->~T(); } struct compare_string { compare_string(char const* s): m_str(s) {} bool operator()( std::pair<std::string , libtorrent::entry> const& e) const { return m_str && e.first == m_str; } char const* m_str; }; } namespace libtorrent { namespace detail { TORRENT_EXPORT char const* integer_to_str(char* buf, int size, entry::integer_type val) { int sign = 0; if (val < 0) { sign = 1; val = -val; } buf[--size] = '\0'; if (val == 0) buf[--size] = '0'; for (; size > sign && val != 0;) { buf[--size] = '0' + char(val % 10); val /= 10; } if (sign) buf[--size] = '-'; return buf + size; } } entry& entry::operator[](char const* key) { dictionary_type::iterator i = dict().find(key); if (i != dict().end()) return i->second; dictionary_type::iterator ret = dict().insert( dict().begin() , std::make_pair(std::string(key), entry())); return ret->second; } entry& entry::operator[](std::string const& key) { return (*this)[key.c_str()]; } entry* entry::find_key(char const* key) { dictionary_type::iterator i = std::find_if( dict().begin() , dict().end() , compare_string(key)); if (i == dict().end()) return 0; return &i->second; } entry const* entry::find_key(char const* key) const { dictionary_type::const_iterator i = dict().find(key); if (i == dict().end()) return 0; return &i->second; } #ifndef BOOST_NO_EXCEPTIONS const entry& entry::operator[](char const* key) const { dictionary_type::const_iterator i = dict().find(key); if (i == dict().end()) throw type_error( (std::string("key not found: ") + key).c_str()); return i->second; } const entry& entry::operator[](std::string const& key) const { return (*this)[key.c_str()]; } #endif entry::entry() : m_type(undefined_t) { #ifndef NDEBUG m_type_queried = true; #endif } entry::entry(data_type t) : m_type(undefined_t) { construct(t); #ifndef NDEBUG m_type_queried = true; #endif } entry::entry(const entry& e) : m_type(undefined_t) { copy(e); #ifndef NDEBUG m_type_queried = e.m_type_queried; #endif } entry::entry(dictionary_type const& v) : m_type(undefined_t) { #ifndef NDEBUG m_type_queried = true; #endif new(data) dictionary_type(v); m_type = dictionary_t; } entry::entry(string_type const& v) : m_type(undefined_t) { #ifndef NDEBUG m_type_queried = true; #endif new(data) string_type(v); m_type = string_t; } entry::entry(list_type const& v) : m_type(undefined_t) { #ifndef NDEBUG m_type_queried = true; #endif new(data) list_type(v); m_type = list_t; } entry::entry(integer_type const& v) : m_type(undefined_t) { #ifndef NDEBUG m_type_queried = true; #endif new(data) integer_type(v); m_type = int_t; } void entry::operator=(dictionary_type const& v) { destruct(); new(data) dictionary_type(v); m_type = dictionary_t; #ifndef NDEBUG m_type_queried = true; #endif } void entry::operator=(string_type const& v) { destruct(); new(data) string_type(v); m_type = string_t; #ifndef NDEBUG m_type_queried = true; #endif } void entry::operator=(list_type const& v) { destruct(); new(data) list_type(v); m_type = list_t; #ifndef NDEBUG m_type_queried = true; #endif } void entry::operator=(integer_type const& v) { destruct(); new(data) integer_type(v); m_type = int_t; #ifndef NDEBUG m_type_queried = true; #endif } bool entry::operator==(entry const& e) const { if (m_type != e.m_type) return false; switch(m_type) { case int_t: return integer() == e.integer(); case string_t: return string() == e.string(); case list_t: return list() == e.list(); case dictionary_t: return dict() == e.dict(); default: TORRENT_ASSERT(m_type == undefined_t); return true; } } void entry::construct(data_type t) { switch(t) { case int_t: new(data) integer_type; break; case string_t: new(data) string_type; break; case list_t: new(data) list_type; break; case dictionary_t: new (data) dictionary_type; break; default: TORRENT_ASSERT(t == undefined_t); } m_type = t; #ifndef NDEBUG m_type_queried = true; #endif } void entry::copy(entry const& e) { switch (e.type()) { case int_t: new(data) integer_type(e.integer()); break; case string_t: new(data) string_type(e.string()); break; case list_t: new(data) list_type(e.list()); break; case dictionary_t: new (data) dictionary_type(e.dict()); break; default: TORRENT_ASSERT(e.type() == undefined_t); } m_type = e.type(); #ifndef NDEBUG m_type_queried = true; #endif } void entry::destruct() { switch(m_type) { case int_t: call_destructor(reinterpret_cast<integer_type*>(data)); break; case string_t: call_destructor(reinterpret_cast<string_type*>(data)); break; case list_t: call_destructor(reinterpret_cast<list_type*>(data)); break; case dictionary_t: call_destructor(reinterpret_cast<dictionary_type*>(data)); break; default: TORRENT_ASSERT(m_type == undefined_t); break; } m_type = undefined_t; #ifndef NDEBUG m_type_queried = false; #endif } void entry::swap(entry& e) { // not implemented TORRENT_ASSERT(false); } void entry::print(std::ostream& os, int indent) const { TORRENT_ASSERT(indent >= 0); for (int i = 0; i < indent; ++i) os << " "; switch (m_type) { case int_t: os << integer() << "\n"; break; case string_t: { bool binary_string = false; for (std::string::const_iterator i = string().begin(); i != string().end(); ++i) { if (!std::isprint(static_cast<unsigned char>(*i))) { binary_string = true; break; } } if (binary_string) { os.unsetf(std::ios_base::dec); os.setf(std::ios_base::hex); for (std::string::const_iterator i = string().begin(); i != string().end(); ++i) os << std::setfill('0') << std::setw(2) << static_cast<unsigned int>((unsigned char)*i); os.unsetf(std::ios_base::hex); os.setf(std::ios_base::dec); os << "\n"; } else { os << string() << "\n"; } } break; case list_t: { os << "list\n"; for (list_type::const_iterator i = list().begin(); i != list().end(); ++i) { i->print(os, indent+1); } } break; case dictionary_t: { os << "dictionary\n"; for (dictionary_type::const_iterator i = dict().begin(); i != dict().end(); ++i) { for (int j = 0; j < indent+1; ++j) os << " "; os << "[" << i->first << "]"; if (i->second.type() != entry::string_t && i->second.type() != entry::int_t) os << "\n"; else os << " "; i->second.print(os, indent+2); } } break; default: os << "<uninitialized>\n"; } } } <|endoftext|>
<commit_before>#include "event.hpp" #include "widget/Widget.hpp" namespace rack { namespace event { void State::setHovered(widget::Widget *w) { if (w == hoveredWidget) return; if (hoveredWidget) { // Leave Leave eLeave; hoveredWidget->onLeave(eLeave); hoveredWidget = NULL; } if (w) { // Enter Context cEnter; cEnter.target = w; Enter eEnter; eEnter.context = &cEnter; w->onEnter(eEnter); hoveredWidget = cEnter.target; } } void State::setDragged(widget::Widget *w, int button) { if (w == draggedWidget) return; if (draggedWidget) { // DragEnd DragEnd eDragEnd; eDragEnd.button = dragButton; draggedWidget->onDragEnd(eDragEnd); draggedWidget = NULL; } dragButton = button; if (w) { // DragStart Context cDragStart; cDragStart.target = w; DragStart eDragStart; eDragStart.context = &cDragStart; eDragStart.button = dragButton; w->onDragStart(eDragStart); draggedWidget = cDragStart.target; } } void State::setDragHovered(widget::Widget *w) { if (w == dragHoveredWidget) return; if (dragHoveredWidget) { // DragLeave DragLeave eDragLeave; eDragLeave.button = dragButton; eDragLeave.origin = draggedWidget; dragHoveredWidget->onDragLeave(eDragLeave); dragHoveredWidget = NULL; } if (w) { // DragEnter Context cDragEnter; cDragEnter.target = w; DragEnter eDragEnter; eDragEnter.context = &cDragEnter; eDragEnter.button = dragButton; eDragEnter.origin = draggedWidget; w->onDragEnter(eDragEnter); dragHoveredWidget = cDragEnter.target; } } void State::setSelected(widget::Widget *w) { if (w == selectedWidget) return; if (selectedWidget) { // Deselect Deselect eDeselect; selectedWidget->onDeselect(eDeselect); selectedWidget = NULL; } if (w) { // Select Context cSelect; cSelect.target = w; Select eSelect; eSelect.context = &cSelect; w->onSelect(eSelect); selectedWidget = cSelect.target; } } void State::finalizeWidget(widget::Widget *w) { if (hoveredWidget == w) setHovered(NULL); if (draggedWidget == w) setDragged(NULL, 0); if (dragHoveredWidget == w) setDragHovered(NULL); if (selectedWidget == w) setSelected(NULL); if (lastClickedWidget == w) lastClickedWidget = NULL; } bool State::handleButton(math::Vec pos, int button, int action, int mods) { // Button Context cButton; Button eButton; eButton.context = &cButton; eButton.pos = pos; eButton.button = button; eButton.action = action; eButton.mods = mods; rootWidget->onButton(eButton); widget::Widget *clickedWidget = cButton.target; if (action == GLFW_PRESS) { setDragged(clickedWidget, button); } if (action == GLFW_RELEASE) { setDragHovered(NULL); if (clickedWidget && draggedWidget) { // DragDrop DragDrop eDragDrop; eDragDrop.button = dragButton; eDragDrop.origin = draggedWidget; clickedWidget->onDragDrop(eDragDrop); } setDragged(NULL, 0); } if (button == GLFW_MOUSE_BUTTON_LEFT) { if (action == GLFW_PRESS) { setSelected(clickedWidget); } if (action == GLFW_PRESS) { const double doubleClickDuration = 0.3; double clickTime = glfwGetTime(); if (clickedWidget && clickTime - lastClickTime <= doubleClickDuration && lastClickedWidget == clickedWidget) { // DoubleClick DoubleClick eDoubleClick; clickedWidget->onDoubleClick(eDoubleClick); // Reset double click lastClickTime = -INFINITY; lastClickedWidget = NULL; } else { lastClickTime = clickTime; lastClickedWidget = clickedWidget; } } } return !!clickedWidget; } bool State::handleHover(math::Vec pos, math::Vec mouseDelta) { // Fake a key RACK_HELD event for each held key int mods = 0; //APP->window->getMods(); for (int key : heldKeys) { int scancode = glfwGetKeyScancode(key); handleKey(pos, key, scancode, RACK_HELD, mods); } if (draggedWidget) { // DragMove DragMove eDragMove; eDragMove.button = dragButton; eDragMove.mouseDelta = mouseDelta; draggedWidget->onDragMove(eDragMove); // DragHover Context cDragHover; DragHover eDragHover; eDragHover.context = &cDragHover; eDragHover.button = dragButton; eDragHover.pos = pos; eDragHover.mouseDelta = mouseDelta; eDragHover.origin = draggedWidget; rootWidget->onDragHover(eDragHover); setDragHovered(cDragHover.target); if (cDragHover.target) return true; } // Hover Context cHover; Hover eHover; eHover.context = &cHover; eHover.pos = pos; eHover.mouseDelta = mouseDelta; rootWidget->onHover(eHover); setHovered(cHover.target); return !!cHover.target; } bool State::handleLeave() { heldKeys.clear(); setDragHovered(NULL); setHovered(NULL); return true; } bool State::handleScroll(math::Vec pos, math::Vec scrollDelta) { // HoverScroll Context cHoverScroll; HoverScroll eHoverScroll; eHoverScroll.context = &cHoverScroll; eHoverScroll.pos = pos; eHoverScroll.scrollDelta = scrollDelta; rootWidget->onHoverScroll(eHoverScroll); return !!cHoverScroll.target; } bool State::handleDrop(math::Vec pos, const std::vector<std::string> &paths) { // PathDrop Context cPathDrop; PathDrop ePathDrop(paths); ePathDrop.context = &cPathDrop; ePathDrop.pos = pos; rootWidget->onPathDrop(ePathDrop); return !!cPathDrop.target; } bool State::handleText(math::Vec pos, int codepoint) { if (selectedWidget) { // SelectText Context cSelectText; SelectText eSelectText; eSelectText.context = &cSelectText; eSelectText.codepoint = codepoint; selectedWidget->onSelectText(eSelectText); if (cSelectText.target) return true; } // HoverText Context cHoverText; HoverText eHoverText; eHoverText.context = &cHoverText; eHoverText.pos = pos; eHoverText.codepoint = codepoint; rootWidget->onHoverText(eHoverText); return !!cHoverText.target; } bool State::handleKey(math::Vec pos, int key, int scancode, int action, int mods) { // Update heldKey state if (action == GLFW_PRESS) { heldKeys.insert(key); } else if (action == GLFW_RELEASE) { auto it = heldKeys.find(key); if (it != heldKeys.end()) heldKeys.erase(it); } if (selectedWidget) { // SelectKey Context cSelectKey; SelectKey eSelectKey; eSelectKey.context = &cSelectKey; eSelectKey.key = key; eSelectKey.scancode = scancode; eSelectKey.action = action; eSelectKey.mods = mods; selectedWidget->onSelectKey(eSelectKey); if (cSelectKey.target) return true; } // HoverKey Context cHoverKey; HoverKey eHoverKey; eHoverKey.context = &cHoverKey; eHoverKey.pos = pos; eHoverKey.key = key; eHoverKey.scancode = scancode; eHoverKey.action = action; eHoverKey.mods = mods; rootWidget->onHoverKey(eHoverKey); return !!cHoverKey.target; } bool State::handleZoom() { // Zoom Context cZoom; Zoom eZoom; eZoom.context = &cZoom; rootWidget->onZoom(eZoom); return true; } } // namespace event } // namespace rack <commit_msg>Use correct key mods in HoverKey and SelectKey for RACK_HELD action.<commit_after>#include "event.hpp" #include "widget/Widget.hpp" #include "app.hpp" #include "window.hpp" namespace rack { namespace event { void State::setHovered(widget::Widget *w) { if (w == hoveredWidget) return; if (hoveredWidget) { // Leave Leave eLeave; hoveredWidget->onLeave(eLeave); hoveredWidget = NULL; } if (w) { // Enter Context cEnter; cEnter.target = w; Enter eEnter; eEnter.context = &cEnter; w->onEnter(eEnter); hoveredWidget = cEnter.target; } } void State::setDragged(widget::Widget *w, int button) { if (w == draggedWidget) return; if (draggedWidget) { // DragEnd DragEnd eDragEnd; eDragEnd.button = dragButton; draggedWidget->onDragEnd(eDragEnd); draggedWidget = NULL; } dragButton = button; if (w) { // DragStart Context cDragStart; cDragStart.target = w; DragStart eDragStart; eDragStart.context = &cDragStart; eDragStart.button = dragButton; w->onDragStart(eDragStart); draggedWidget = cDragStart.target; } } void State::setDragHovered(widget::Widget *w) { if (w == dragHoveredWidget) return; if (dragHoveredWidget) { // DragLeave DragLeave eDragLeave; eDragLeave.button = dragButton; eDragLeave.origin = draggedWidget; dragHoveredWidget->onDragLeave(eDragLeave); dragHoveredWidget = NULL; } if (w) { // DragEnter Context cDragEnter; cDragEnter.target = w; DragEnter eDragEnter; eDragEnter.context = &cDragEnter; eDragEnter.button = dragButton; eDragEnter.origin = draggedWidget; w->onDragEnter(eDragEnter); dragHoveredWidget = cDragEnter.target; } } void State::setSelected(widget::Widget *w) { if (w == selectedWidget) return; if (selectedWidget) { // Deselect Deselect eDeselect; selectedWidget->onDeselect(eDeselect); selectedWidget = NULL; } if (w) { // Select Context cSelect; cSelect.target = w; Select eSelect; eSelect.context = &cSelect; w->onSelect(eSelect); selectedWidget = cSelect.target; } } void State::finalizeWidget(widget::Widget *w) { if (hoveredWidget == w) setHovered(NULL); if (draggedWidget == w) setDragged(NULL, 0); if (dragHoveredWidget == w) setDragHovered(NULL); if (selectedWidget == w) setSelected(NULL); if (lastClickedWidget == w) lastClickedWidget = NULL; } bool State::handleButton(math::Vec pos, int button, int action, int mods) { // Button Context cButton; Button eButton; eButton.context = &cButton; eButton.pos = pos; eButton.button = button; eButton.action = action; eButton.mods = mods; rootWidget->onButton(eButton); widget::Widget *clickedWidget = cButton.target; if (action == GLFW_PRESS) { setDragged(clickedWidget, button); } if (action == GLFW_RELEASE) { setDragHovered(NULL); if (clickedWidget && draggedWidget) { // DragDrop DragDrop eDragDrop; eDragDrop.button = dragButton; eDragDrop.origin = draggedWidget; clickedWidget->onDragDrop(eDragDrop); } setDragged(NULL, 0); } if (button == GLFW_MOUSE_BUTTON_LEFT) { if (action == GLFW_PRESS) { setSelected(clickedWidget); } if (action == GLFW_PRESS) { const double doubleClickDuration = 0.3; double clickTime = glfwGetTime(); if (clickedWidget && clickTime - lastClickTime <= doubleClickDuration && lastClickedWidget == clickedWidget) { // DoubleClick DoubleClick eDoubleClick; clickedWidget->onDoubleClick(eDoubleClick); // Reset double click lastClickTime = -INFINITY; lastClickedWidget = NULL; } else { lastClickTime = clickTime; lastClickedWidget = clickedWidget; } } } return !!clickedWidget; } bool State::handleHover(math::Vec pos, math::Vec mouseDelta) { // Fake a key RACK_HELD event for each held key int mods = APP->window->getMods(); for (int key : heldKeys) { int scancode = glfwGetKeyScancode(key); handleKey(pos, key, scancode, RACK_HELD, mods); } if (draggedWidget) { // DragMove DragMove eDragMove; eDragMove.button = dragButton; eDragMove.mouseDelta = mouseDelta; draggedWidget->onDragMove(eDragMove); // DragHover Context cDragHover; DragHover eDragHover; eDragHover.context = &cDragHover; eDragHover.button = dragButton; eDragHover.pos = pos; eDragHover.mouseDelta = mouseDelta; eDragHover.origin = draggedWidget; rootWidget->onDragHover(eDragHover); setDragHovered(cDragHover.target); if (cDragHover.target) return true; } // Hover Context cHover; Hover eHover; eHover.context = &cHover; eHover.pos = pos; eHover.mouseDelta = mouseDelta; rootWidget->onHover(eHover); setHovered(cHover.target); return !!cHover.target; } bool State::handleLeave() { heldKeys.clear(); setDragHovered(NULL); setHovered(NULL); return true; } bool State::handleScroll(math::Vec pos, math::Vec scrollDelta) { // HoverScroll Context cHoverScroll; HoverScroll eHoverScroll; eHoverScroll.context = &cHoverScroll; eHoverScroll.pos = pos; eHoverScroll.scrollDelta = scrollDelta; rootWidget->onHoverScroll(eHoverScroll); return !!cHoverScroll.target; } bool State::handleDrop(math::Vec pos, const std::vector<std::string> &paths) { // PathDrop Context cPathDrop; PathDrop ePathDrop(paths); ePathDrop.context = &cPathDrop; ePathDrop.pos = pos; rootWidget->onPathDrop(ePathDrop); return !!cPathDrop.target; } bool State::handleText(math::Vec pos, int codepoint) { if (selectedWidget) { // SelectText Context cSelectText; SelectText eSelectText; eSelectText.context = &cSelectText; eSelectText.codepoint = codepoint; selectedWidget->onSelectText(eSelectText); if (cSelectText.target) return true; } // HoverText Context cHoverText; HoverText eHoverText; eHoverText.context = &cHoverText; eHoverText.pos = pos; eHoverText.codepoint = codepoint; rootWidget->onHoverText(eHoverText); return !!cHoverText.target; } bool State::handleKey(math::Vec pos, int key, int scancode, int action, int mods) { // Update heldKey state if (action == GLFW_PRESS) { heldKeys.insert(key); } else if (action == GLFW_RELEASE) { auto it = heldKeys.find(key); if (it != heldKeys.end()) heldKeys.erase(it); } if (selectedWidget) { // SelectKey Context cSelectKey; SelectKey eSelectKey; eSelectKey.context = &cSelectKey; eSelectKey.key = key; eSelectKey.scancode = scancode; eSelectKey.action = action; eSelectKey.mods = mods; selectedWidget->onSelectKey(eSelectKey); if (cSelectKey.target) return true; } // HoverKey Context cHoverKey; HoverKey eHoverKey; eHoverKey.context = &cHoverKey; eHoverKey.pos = pos; eHoverKey.key = key; eHoverKey.scancode = scancode; eHoverKey.action = action; eHoverKey.mods = mods; rootWidget->onHoverKey(eHoverKey); return !!cHoverKey.target; } bool State::handleZoom() { // Zoom Context cZoom; Zoom eZoom; eZoom.context = &cZoom; rootWidget->onZoom(eZoom); return true; } } // namespace event } // namespace rack <|endoftext|>
<commit_before>// just one implementation for now #include "field_5x52.cpp" extern "C" { static const unsigned char secp256k1_fe_consts_p[] = { 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F }; void static secp256k1_fe_start(void) { if (secp256k1_fe_consts == NULL) { secp256k1_fe_consts_t *ret = (secp256k1_fe_consts_t*)malloc(sizeof(secp256k1_fe_t)); secp256k1_num_set_bin(&ret->p, secp256k1_fe_consts_p, sizeof(secp256k1_fe_consts_p)); secp256k1_fe_consts = ret; } } void static secp256k1_fe_stop(void) { if (secp256k1_fe_consts != NULL) { free((void*)secp256k1_fe_consts); secp256k1_fe_consts = NULL; } } void static secp256k1_fe_get_hex(char *r, int *rlen, const secp256k1_fe_t *a) { if (*rlen < 65) { *rlen = 65; return; } *rlen = 65; unsigned char tmp[32]; secp256k1_fe_t b = *a; secp256k1_fe_normalize(&b); secp256k1_fe_get_b32(tmp, &b); for (int i=0; i<32; i++) { static const char *c = "0123456789ABCDEF"; r[2*i] = c[(tmp[i] >> 4) & 0xF]; r[2*i+1] = c[(tmp[i]) & 0xF]; } r[64] = 0x00; } void static secp256k1_fe_set_hex(secp256k1_fe_t *r, const char *a, int alen) { unsigned char tmp[32] = {}; static const int cvt[256] = {0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0, 0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0, 0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0, 0, 1, 2, 3, 4, 5, 6,7,8,9,0,0,0,0,0,0, 0,10,11,12,13,14,15,0,0,0,0,0,0,0,0,0, 0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0, 0,10,11,12,13,14,15,0,0,0,0,0,0,0,0,0, 0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0, 0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0, 0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0, 0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0, 0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0, 0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0, 0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0, 0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0, 0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0}; for (int i=0; i<32; i++) { if (alen > i*2) tmp[32 - alen/2 + i] = (cvt[(unsigned char)a[2*i]] << 4) + cvt[(unsigned char)a[2*i+1]]; } secp256k1_fe_set_b32(r, tmp); } void static secp256k1_fe_sqrt(secp256k1_fe_t *r, const secp256k1_fe_t *a) { // calculate a^p, with p={15,780,1022,1023} secp256k1_fe_t a2; secp256k1_fe_sqr(&a2, a); secp256k1_fe_t a3; secp256k1_fe_mul(&a3, &a2, a); secp256k1_fe_t a6; secp256k1_fe_sqr(&a6, &a3); secp256k1_fe_t a12; secp256k1_fe_sqr(&a12, &a6); secp256k1_fe_t a15; secp256k1_fe_mul(&a15, &a12, &a3); secp256k1_fe_t a30; secp256k1_fe_sqr(&a30, &a15); secp256k1_fe_t a60; secp256k1_fe_sqr(&a60, &a30); secp256k1_fe_t a120; secp256k1_fe_sqr(&a120, &a60); secp256k1_fe_t a240; secp256k1_fe_sqr(&a240, &a120); secp256k1_fe_t a255; secp256k1_fe_mul(&a255, &a240, &a15); secp256k1_fe_t a510; secp256k1_fe_sqr(&a510, &a255); secp256k1_fe_t a750; secp256k1_fe_mul(&a750, &a510, &a240); secp256k1_fe_t a780; secp256k1_fe_mul(&a780, &a750, &a30); secp256k1_fe_t a1020; secp256k1_fe_sqr(&a1020, &a510); secp256k1_fe_t a1022; secp256k1_fe_mul(&a1022, &a1020, &a2); secp256k1_fe_t a1023; secp256k1_fe_mul(&a1023, &a1022, a); secp256k1_fe_t x = a15; for (int i=0; i<21; i++) { for (int j=0; j<10; j++) secp256k1_fe_sqr(&x, &x); secp256k1_fe_mul(&x, &x, &a1023); } for (int j=0; j<10; j++) secp256k1_fe_sqr(&x, &x); secp256k1_fe_mul(&x, &x, &a1022); for (int i=0; i<2; i++) { for (int j=0; j<10; j++) secp256k1_fe_sqr(&x, &x); secp256k1_fe_mul(&x, &x, &a1023); } for (int j=0; j<10; j++) secp256k1_fe_sqr(&x, &x); secp256k1_fe_mul(r, &x, &a780); } void static secp256k1_fe_inv(secp256k1_fe_t *r, const secp256k1_fe_t *a) { // calculate a^p, with p={45,63,1019,1023} secp256k1_fe_t a2; secp256k1_fe_sqr(&a2, a); secp256k1_fe_t a3; secp256k1_fe_mul(&a3, &a2, a); secp256k1_fe_t a4; secp256k1_fe_sqr(&a4, &a2); secp256k1_fe_t a5; secp256k1_fe_mul(&a5, &a4, a); secp256k1_fe_t a10; secp256k1_fe_sqr(&a10, &a5); secp256k1_fe_t a11; secp256k1_fe_mul(&a11, &a10, a); secp256k1_fe_t a21; secp256k1_fe_mul(&a21, &a11, &a10); secp256k1_fe_t a42; secp256k1_fe_sqr(&a42, &a21); secp256k1_fe_t a45; secp256k1_fe_mul(&a45, &a42, &a3); secp256k1_fe_t a63; secp256k1_fe_mul(&a63, &a42, &a21); secp256k1_fe_t a126; secp256k1_fe_sqr(&a126, &a63); secp256k1_fe_t a252; secp256k1_fe_sqr(&a252, &a126); secp256k1_fe_t a504; secp256k1_fe_sqr(&a504, &a252); secp256k1_fe_t a1008; secp256k1_fe_sqr(&a1008, &a504); secp256k1_fe_t a1019; secp256k1_fe_mul(&a1019, &a1008, &a11); secp256k1_fe_t a1023; secp256k1_fe_mul(&a1023, &a1019, &a4); secp256k1_fe_t x = a63; for (int i=0; i<21; i++) { for (int j=0; j<10; j++) secp256k1_fe_sqr(&x, &x); secp256k1_fe_mul(&x, &x, &a1023); } for (int j=0; j<10; j++) secp256k1_fe_sqr(&x, &x); secp256k1_fe_mul(&x, &x, &a1019); for (int i=0; i<2; i++) { for (int j=0; j<10; j++) secp256k1_fe_sqr(&x, &x); secp256k1_fe_mul(&x, &x, &a1023); } for (int j=0; j<10; j++) secp256k1_fe_sqr(&x, &x); secp256k1_fe_mul(r, &x, &a45); } void static secp256k1_fe_inv_var(secp256k1_fe_t *r, const secp256k1_fe_t *a) { #if defined(USE_FIELD_INV_BUILTIN) secp256k1_fe_inv(r, a); #else unsigned char b[32]; secp256k1_fe_t c = *a; secp256k1_fe_normalize(&c); secp256k1_fe_get_b32(b, &c); secp256k1_num_t n; secp256k1_num_init(&n); secp256k1_num_set_bin(&n, b, 32); secp256k1_num_mod_inverse(&n, &n, &secp256k1_fe_consts->p); secp256k1_num_get_bin(b, 32, &n); secp256k1_num_free(&n); secp256k1_fe_set_b32(&c, b); #endif } } <commit_msg>Bugfix: secp256k1_fe_inv_var correct output<commit_after>// just one implementation for now #include "field_5x52.cpp" extern "C" { static const unsigned char secp256k1_fe_consts_p[] = { 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F }; void static secp256k1_fe_start(void) { if (secp256k1_fe_consts == NULL) { secp256k1_fe_consts_t *ret = (secp256k1_fe_consts_t*)malloc(sizeof(secp256k1_fe_t)); secp256k1_num_set_bin(&ret->p, secp256k1_fe_consts_p, sizeof(secp256k1_fe_consts_p)); secp256k1_fe_consts = ret; } } void static secp256k1_fe_stop(void) { if (secp256k1_fe_consts != NULL) { free((void*)secp256k1_fe_consts); secp256k1_fe_consts = NULL; } } void static secp256k1_fe_get_hex(char *r, int *rlen, const secp256k1_fe_t *a) { if (*rlen < 65) { *rlen = 65; return; } *rlen = 65; unsigned char tmp[32]; secp256k1_fe_t b = *a; secp256k1_fe_normalize(&b); secp256k1_fe_get_b32(tmp, &b); for (int i=0; i<32; i++) { static const char *c = "0123456789ABCDEF"; r[2*i] = c[(tmp[i] >> 4) & 0xF]; r[2*i+1] = c[(tmp[i]) & 0xF]; } r[64] = 0x00; } void static secp256k1_fe_set_hex(secp256k1_fe_t *r, const char *a, int alen) { unsigned char tmp[32] = {}; static const int cvt[256] = {0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0, 0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0, 0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0, 0, 1, 2, 3, 4, 5, 6,7,8,9,0,0,0,0,0,0, 0,10,11,12,13,14,15,0,0,0,0,0,0,0,0,0, 0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0, 0,10,11,12,13,14,15,0,0,0,0,0,0,0,0,0, 0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0, 0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0, 0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0, 0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0, 0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0, 0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0, 0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0, 0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0, 0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0}; for (int i=0; i<32; i++) { if (alen > i*2) tmp[32 - alen/2 + i] = (cvt[(unsigned char)a[2*i]] << 4) + cvt[(unsigned char)a[2*i+1]]; } secp256k1_fe_set_b32(r, tmp); } void static secp256k1_fe_sqrt(secp256k1_fe_t *r, const secp256k1_fe_t *a) { // calculate a^p, with p={15,780,1022,1023} secp256k1_fe_t a2; secp256k1_fe_sqr(&a2, a); secp256k1_fe_t a3; secp256k1_fe_mul(&a3, &a2, a); secp256k1_fe_t a6; secp256k1_fe_sqr(&a6, &a3); secp256k1_fe_t a12; secp256k1_fe_sqr(&a12, &a6); secp256k1_fe_t a15; secp256k1_fe_mul(&a15, &a12, &a3); secp256k1_fe_t a30; secp256k1_fe_sqr(&a30, &a15); secp256k1_fe_t a60; secp256k1_fe_sqr(&a60, &a30); secp256k1_fe_t a120; secp256k1_fe_sqr(&a120, &a60); secp256k1_fe_t a240; secp256k1_fe_sqr(&a240, &a120); secp256k1_fe_t a255; secp256k1_fe_mul(&a255, &a240, &a15); secp256k1_fe_t a510; secp256k1_fe_sqr(&a510, &a255); secp256k1_fe_t a750; secp256k1_fe_mul(&a750, &a510, &a240); secp256k1_fe_t a780; secp256k1_fe_mul(&a780, &a750, &a30); secp256k1_fe_t a1020; secp256k1_fe_sqr(&a1020, &a510); secp256k1_fe_t a1022; secp256k1_fe_mul(&a1022, &a1020, &a2); secp256k1_fe_t a1023; secp256k1_fe_mul(&a1023, &a1022, a); secp256k1_fe_t x = a15; for (int i=0; i<21; i++) { for (int j=0; j<10; j++) secp256k1_fe_sqr(&x, &x); secp256k1_fe_mul(&x, &x, &a1023); } for (int j=0; j<10; j++) secp256k1_fe_sqr(&x, &x); secp256k1_fe_mul(&x, &x, &a1022); for (int i=0; i<2; i++) { for (int j=0; j<10; j++) secp256k1_fe_sqr(&x, &x); secp256k1_fe_mul(&x, &x, &a1023); } for (int j=0; j<10; j++) secp256k1_fe_sqr(&x, &x); secp256k1_fe_mul(r, &x, &a780); } void static secp256k1_fe_inv(secp256k1_fe_t *r, const secp256k1_fe_t *a) { // calculate a^p, with p={45,63,1019,1023} secp256k1_fe_t a2; secp256k1_fe_sqr(&a2, a); secp256k1_fe_t a3; secp256k1_fe_mul(&a3, &a2, a); secp256k1_fe_t a4; secp256k1_fe_sqr(&a4, &a2); secp256k1_fe_t a5; secp256k1_fe_mul(&a5, &a4, a); secp256k1_fe_t a10; secp256k1_fe_sqr(&a10, &a5); secp256k1_fe_t a11; secp256k1_fe_mul(&a11, &a10, a); secp256k1_fe_t a21; secp256k1_fe_mul(&a21, &a11, &a10); secp256k1_fe_t a42; secp256k1_fe_sqr(&a42, &a21); secp256k1_fe_t a45; secp256k1_fe_mul(&a45, &a42, &a3); secp256k1_fe_t a63; secp256k1_fe_mul(&a63, &a42, &a21); secp256k1_fe_t a126; secp256k1_fe_sqr(&a126, &a63); secp256k1_fe_t a252; secp256k1_fe_sqr(&a252, &a126); secp256k1_fe_t a504; secp256k1_fe_sqr(&a504, &a252); secp256k1_fe_t a1008; secp256k1_fe_sqr(&a1008, &a504); secp256k1_fe_t a1019; secp256k1_fe_mul(&a1019, &a1008, &a11); secp256k1_fe_t a1023; secp256k1_fe_mul(&a1023, &a1019, &a4); secp256k1_fe_t x = a63; for (int i=0; i<21; i++) { for (int j=0; j<10; j++) secp256k1_fe_sqr(&x, &x); secp256k1_fe_mul(&x, &x, &a1023); } for (int j=0; j<10; j++) secp256k1_fe_sqr(&x, &x); secp256k1_fe_mul(&x, &x, &a1019); for (int i=0; i<2; i++) { for (int j=0; j<10; j++) secp256k1_fe_sqr(&x, &x); secp256k1_fe_mul(&x, &x, &a1023); } for (int j=0; j<10; j++) secp256k1_fe_sqr(&x, &x); secp256k1_fe_mul(r, &x, &a45); } void static secp256k1_fe_inv_var(secp256k1_fe_t *r, const secp256k1_fe_t *a) { #if defined(USE_FIELD_INV_BUILTIN) secp256k1_fe_inv(r, a); #else unsigned char b[32]; secp256k1_fe_t c = *a; secp256k1_fe_normalize(&c); secp256k1_fe_get_b32(b, &c); secp256k1_num_t n; secp256k1_num_init(&n); secp256k1_num_set_bin(&n, b, 32); secp256k1_num_mod_inverse(&n, &n, &secp256k1_fe_consts->p); secp256k1_num_get_bin(b, 32, &n); secp256k1_num_free(&n); secp256k1_fe_set_b32(r, b); #endif } } <|endoftext|>
<commit_before>#include "LogHandler.hpp" INITIALIZE_EASYLOGGINGPP namespace et { el::Configurations LogHandler::setupLogHandler(int *argc, char ***argv) { // easylogging parse verbose arguments, see [Application Arguments] // in https://github.com/muflihun/easyloggingpp/blob/master/README.md START_EASYLOGGINGPP(*argc, *argv); // Easylogging configurations el::Configurations defaultConf; defaultConf.setToDefault(); // doc says %thread_name, but %thread is the right one defaultConf.setGlobally(el::ConfigurationType::Format, "[%level %datetime %thread %fbase:%line] %msg"); defaultConf.setGlobally(el::ConfigurationType::Enabled, "true"); defaultConf.setGlobally(el::ConfigurationType::SubsecondPrecision, "3"); defaultConf.setGlobally(el::ConfigurationType::PerformanceTracking, "false"); defaultConf.setGlobally(el::ConfigurationType::LogFlushThreshold, "1"); defaultConf.set(el::Level::Verbose, el::ConfigurationType::Format, "[%levshort%vlevel %datetime %thread %fbase:%line] %msg"); return defaultConf; } void LogHandler::setupLogFile(el::Configurations *defaultConf, string filename, string maxlogsize) { // Enable strict log file size check el::Loggers::addFlag(el::LoggingFlag::StrictLogFileSizeCheck); defaultConf->setGlobally(el::ConfigurationType::Filename, filename); defaultConf->setGlobally(el::ConfigurationType::ToFile, "true"); defaultConf->setGlobally(el::ConfigurationType::MaxLogFileSize, maxlogsize); } void LogHandler::rolloutHandler(const char *filename, std::size_t size) { // SHOULD NOT LOG ANYTHING HERE BECAUSE LOG FILE IS CLOSED! std::stringstream ss; // REMOVE OLD LOG ss << "rm " << filename; system(ss.str().c_str()); } string LogHandler::stderrToFile(const string &pathPrefix) { time_t rawtime; struct tm *timeinfo; char buffer[80]; time(&rawtime); timeinfo = localtime(&rawtime); strftime(buffer, sizeof(buffer), "%Y-%m-%d_%I-%M", timeinfo); string current_time(buffer); string stderrFilename = pathPrefix + "_stderr_" + current_time; FILE *stderr_stream = freopen(stderrFilename.c_str(), "w", stderr); setvbuf(stderr_stream, NULL, _IOLBF, BUFSIZ); // set to line buffering return stderrFilename; } } // namespace et <commit_msg>Use remove() instead of system() to remove log files, allowing compilation on iOS (#217)<commit_after>#include "LogHandler.hpp" INITIALIZE_EASYLOGGINGPP namespace et { el::Configurations LogHandler::setupLogHandler(int *argc, char ***argv) { // easylogging parse verbose arguments, see [Application Arguments] // in https://github.com/muflihun/easyloggingpp/blob/master/README.md START_EASYLOGGINGPP(*argc, *argv); // Easylogging configurations el::Configurations defaultConf; defaultConf.setToDefault(); // doc says %thread_name, but %thread is the right one defaultConf.setGlobally(el::ConfigurationType::Format, "[%level %datetime %thread %fbase:%line] %msg"); defaultConf.setGlobally(el::ConfigurationType::Enabled, "true"); defaultConf.setGlobally(el::ConfigurationType::SubsecondPrecision, "3"); defaultConf.setGlobally(el::ConfigurationType::PerformanceTracking, "false"); defaultConf.setGlobally(el::ConfigurationType::LogFlushThreshold, "1"); defaultConf.set(el::Level::Verbose, el::ConfigurationType::Format, "[%levshort%vlevel %datetime %thread %fbase:%line] %msg"); return defaultConf; } void LogHandler::setupLogFile(el::Configurations *defaultConf, string filename, string maxlogsize) { // Enable strict log file size check el::Loggers::addFlag(el::LoggingFlag::StrictLogFileSizeCheck); defaultConf->setGlobally(el::ConfigurationType::Filename, filename); defaultConf->setGlobally(el::ConfigurationType::ToFile, "true"); defaultConf->setGlobally(el::ConfigurationType::MaxLogFileSize, maxlogsize); } void LogHandler::rolloutHandler(const char *filename, std::size_t size) { // SHOULD NOT LOG ANYTHING HERE BECAUSE LOG FILE IS CLOSED! // REMOVE OLD LOG remove(filename); } string LogHandler::stderrToFile(const string &pathPrefix) { time_t rawtime; struct tm *timeinfo; char buffer[80]; time(&rawtime); timeinfo = localtime(&rawtime); strftime(buffer, sizeof(buffer), "%Y-%m-%d_%I-%M", timeinfo); string current_time(buffer); string stderrFilename = pathPrefix + "_stderr_" + current_time; FILE *stderr_stream = freopen(stderrFilename.c_str(), "w", stderr); setvbuf(stderr_stream, NULL, _IOLBF, BUFSIZ); // set to line buffering return stderrFilename; } } // namespace et <|endoftext|>
<commit_before>// Formatting library for C++ // // Copyright (c) 2012 - 2016, Victor Zverovich // All rights reserved. // // For the license information refer to format.h. #include "fmt/format-inl.h" FMT_BEGIN_NAMESPACE namespace detail { template <typename T> int format_float(char* buf, std::size_t size, const char* format, int precision, T value) { #ifdef FMT_FUZZ if (precision > 100000) throw std::runtime_error( "fuzz mode - avoid large allocation inside snprintf"); #endif // Suppress the warning about nonliteral format string. int (*snprintf_ptr)(char*, size_t, const char*, ...) = FMT_SNPRINTF; return precision < 0 ? snprintf_ptr(buf, size, format, value) : snprintf_ptr(buf, size, format, precision, value); } template FMT_API dragonbox::decimal_fp<float> dragonbox::to_decimal(float x) FMT_NOEXCEPT; template FMT_API dragonbox::decimal_fp<double> dragonbox::to_decimal(double x) FMT_NOEXCEPT; // DEPRECATED! This function exists for ABI compatibility. template <typename Char> typename basic_format_context<std::back_insert_iterator<buffer<Char>>, Char>::iterator vformat_to(buffer<Char>& buf, basic_string_view<Char> format_str, basic_format_args<basic_format_context< std::back_insert_iterator<buffer<type_identity_t<Char>>>, type_identity_t<Char>>> args) { using iterator = std::back_insert_iterator<buffer<char>>; using context = basic_format_context< std::back_insert_iterator<buffer<type_identity_t<Char>>>, type_identity_t<Char>>; auto out = iterator(buf); format_handler<iterator, Char, context> h(out, format_str, args, {}); parse_format_string<false>(format_str, h); return out; } template basic_format_context<std::back_insert_iterator<buffer<char>>, char>::iterator vformat_to(buffer<char>&, string_view, basic_format_args<basic_format_context< std::back_insert_iterator<buffer<type_identity_t<char>>>, type_identity_t<char>>>); } // namespace detail // Clang doesn't allow dllexport on template instantiation definitions (LLVM // D61118). template struct detail::basic_data<void>; // Workaround a bug in MSVC2013 that prevents instantiation of format_float. int (*instantiate_format_float)(double, int, detail::float_specs, detail::buffer<char>&) = detail::format_float; #ifndef FMT_STATIC_THOUSANDS_SEPARATOR template FMT_API detail::locale_ref::locale_ref(const std::locale& loc); template FMT_API std::locale detail::locale_ref::get<std::locale>() const; #endif // Explicit instantiations for char. template FMT_API std::string detail::grouping_impl<char>(locale_ref); template FMT_API char detail::thousands_sep_impl(locale_ref); template FMT_API char detail::decimal_point_impl(locale_ref); template FMT_API void detail::buffer<char>::append(const char*, const char*); template FMT_API void detail::vformat_to( detail::buffer<char>&, string_view, basic_format_args<FMT_BUFFER_CONTEXT(char)>, detail::locale_ref); template FMT_API int detail::snprintf_float(double, int, detail::float_specs, detail::buffer<char>&); template FMT_API int detail::snprintf_float(long double, int, detail::float_specs, detail::buffer<char>&); template FMT_API int detail::format_float(double, int, detail::float_specs, detail::buffer<char>&); template FMT_API int detail::format_float(long double, int, detail::float_specs, detail::buffer<char>&); // Explicit instantiations for wchar_t. template FMT_API std::string detail::grouping_impl<wchar_t>(locale_ref); template FMT_API wchar_t detail::thousands_sep_impl(locale_ref); template FMT_API wchar_t detail::decimal_point_impl(locale_ref); template FMT_API void detail::buffer<wchar_t>::append(const wchar_t*, const wchar_t*); FMT_END_NAMESPACE <commit_msg>Add a link to llvm diff<commit_after>// Formatting library for C++ // // Copyright (c) 2012 - 2016, Victor Zverovich // All rights reserved. // // For the license information refer to format.h. #include "fmt/format-inl.h" FMT_BEGIN_NAMESPACE namespace detail { template <typename T> int format_float(char* buf, std::size_t size, const char* format, int precision, T value) { #ifdef FMT_FUZZ if (precision > 100000) throw std::runtime_error( "fuzz mode - avoid large allocation inside snprintf"); #endif // Suppress the warning about nonliteral format string. int (*snprintf_ptr)(char*, size_t, const char*, ...) = FMT_SNPRINTF; return precision < 0 ? snprintf_ptr(buf, size, format, value) : snprintf_ptr(buf, size, format, precision, value); } template FMT_API dragonbox::decimal_fp<float> dragonbox::to_decimal(float x) FMT_NOEXCEPT; template FMT_API dragonbox::decimal_fp<double> dragonbox::to_decimal(double x) FMT_NOEXCEPT; // DEPRECATED! This function exists for ABI compatibility. template <typename Char> typename basic_format_context<std::back_insert_iterator<buffer<Char>>, Char>::iterator vformat_to(buffer<Char>& buf, basic_string_view<Char> format_str, basic_format_args<basic_format_context< std::back_insert_iterator<buffer<type_identity_t<Char>>>, type_identity_t<Char>>> args) { using iterator = std::back_insert_iterator<buffer<char>>; using context = basic_format_context< std::back_insert_iterator<buffer<type_identity_t<Char>>>, type_identity_t<Char>>; auto out = iterator(buf); format_handler<iterator, Char, context> h(out, format_str, args, {}); parse_format_string<false>(format_str, h); return out; } template basic_format_context<std::back_insert_iterator<buffer<char>>, char>::iterator vformat_to(buffer<char>&, string_view, basic_format_args<basic_format_context< std::back_insert_iterator<buffer<type_identity_t<char>>>, type_identity_t<char>>>); } // namespace detail // Clang doesn't allow dllexport on template instantiation definitions: // https://reviews.llvm.org/D61118. template struct detail::basic_data<void>; // Workaround a bug in MSVC2013 that prevents instantiation of format_float. int (*instantiate_format_float)(double, int, detail::float_specs, detail::buffer<char>&) = detail::format_float; #ifndef FMT_STATIC_THOUSANDS_SEPARATOR template FMT_API detail::locale_ref::locale_ref(const std::locale& loc); template FMT_API std::locale detail::locale_ref::get<std::locale>() const; #endif // Explicit instantiations for char. template FMT_API std::string detail::grouping_impl<char>(locale_ref); template FMT_API char detail::thousands_sep_impl(locale_ref); template FMT_API char detail::decimal_point_impl(locale_ref); template FMT_API void detail::buffer<char>::append(const char*, const char*); template FMT_API void detail::vformat_to( detail::buffer<char>&, string_view, basic_format_args<FMT_BUFFER_CONTEXT(char)>, detail::locale_ref); template FMT_API int detail::snprintf_float(double, int, detail::float_specs, detail::buffer<char>&); template FMT_API int detail::snprintf_float(long double, int, detail::float_specs, detail::buffer<char>&); template FMT_API int detail::format_float(double, int, detail::float_specs, detail::buffer<char>&); template FMT_API int detail::format_float(long double, int, detail::float_specs, detail::buffer<char>&); // Explicit instantiations for wchar_t. template FMT_API std::string detail::grouping_impl<wchar_t>(locale_ref); template FMT_API wchar_t detail::thousands_sep_impl(locale_ref); template FMT_API wchar_t detail::decimal_point_impl(locale_ref); template FMT_API void detail::buffer<wchar_t>::append(const wchar_t*, const wchar_t*); FMT_END_NAMESPACE <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #ifdef _MSC_VER #pragma warning( 4: 4786) #endif #include <stdio.h> #include <iostream> #include <map> #include <string> #include "BZAdminClient.h" #include "BZAdminUI.h" #include "OptionParser.h" #include "UIMap.h" // causes persistent rebuilding to obtain build versioning #include "version.h" int debugLevel = 0; #ifdef _WIN32 void Player::setDeadReckoning() { } #endif /** @file This is the main file for bzadmin, the bzflag text client. */ int main(int argc, char** argv) { #ifdef _WIN32 // startup winsock { static const int major = 2, minor = 2; WSADATA wsaData; if (WSAStartup(MAKEWORD(major, minor), &wsaData)) { std::cerr << "Could not initialise WinSock."; return 1; } if (LOBYTE(wsaData.wVersion) != major || HIBYTE(wsaData.wVersion) != minor) { std::cerr << "Invalid WinSock version (got " << (int) LOBYTE(wsaData.wVersion) << '.' << (int) HIBYTE(wsaData.wVersion) << ", expected" << major << '.' << minor << ')'; WSACleanup(); return 1; } } #endif // command line options std::string uiName("curses"); std::vector<std::string> visibleMsgs; std::vector<std::string> invisibleMsgs; // no curses, use stdboth as default instead const UIMap& interfaces = UIMap::instance(); if (interfaces.find("curses") == interfaces.end()) uiName = "stdboth"; // build a usage string with all interfaces UIMap::const_iterator uiIter; std::string uiUsage; for (uiIter = interfaces.begin(); uiIter != interfaces.end(); ++uiIter) uiUsage += uiIter->first + '|'; uiUsage = std::string("[-ui ") + uiUsage.substr(0, uiUsage.size() - 1) + ']'; // register and parse command line arguments OptionParser op(std::string("bzadmin ") + getAppVersion(), "CALLSIGN@HOST[:PORT] [COMMAND] [COMMAND] ..."); const std::string uiOption("ui"); const std::string uiMsg = "choose a user interface"; op.registerVariable(uiOption, uiName, uiUsage, uiMsg); op.registerVector("show", visibleMsgs, "[-show msgtype{,msgtype}*]", "tell bzadmin to show these message types"); op.registerVector("hide", invisibleMsgs, "[-hide msgtype{,msgtype}*]", "tell bzadmin not to show these message types"); if (!op.parse(argc, argv)) return 1; // check that we have callsign and host in the right format and extract them int atPos; std::string name = "", host = ""; if (!(op.getParameters().size() > 0 && (atPos = op.getParameters()[0].find('@')) > 0)) { // input callsign and host interactively std::cout << "No callsign@host specified. Please input them" << std::endl; std::cout << "Callsign: "; std::getline(std::cin, name); if (name.size() <= 1) { std::cerr << "You must specify a callsign. Exiting." << std::endl; return 1; } std::cout << "Server to connect to: "; std::getline(std::cin, host); if (host.size() <= 1) { std::cerr << "You must specify a host name to connect to. Exiting." << std::endl; return 1; } } else { // callsign/host on command line name = op.getParameters()[0].substr(0, atPos); host = op.getParameters()[0].substr(atPos + 1); } int port = ServerPort; int cPos = host.find(':'); if (cPos != -1) { port = atoi(host.substr(cPos + 1).c_str()); host = host.substr(0, cPos); } // check that the ui is valid uiIter = UIMap::instance().find(uiName); if (uiIter == UIMap::instance().end()) { std::cerr<<"There is no interface called \""<<uiName<<"\"."<<std::endl; return 1; } // try to connect BZAdminClient client(name, host, port); if (!client.isValid()) { std::cerr << "Could not connect to " << host << ':' << port << std::endl; return 1; } unsigned int i; for (i = 0; i < visibleMsgs.size(); ++i) client.showMessageType(visibleMsgs[i]); for (i = 0; i < invisibleMsgs.size(); ++i) client.ignoreMessageType(invisibleMsgs[i]); // if we got commands as arguments, send them and exit if (op.getParameters().size() > 1) { for (unsigned int i = 1; i < op.getParameters().size(); ++i) { if (op.getParameters()[i] == "/quit") { client.waitForServer(); return 0; } client.sendMessage(op.getParameters()[i], AllPlayers); } } // create UI and run the main loop BZAdminUI* ui = uiIter->second(client); client.setUI(ui); client.runLoop(); delete ui; return 0; } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>whoops, BZAdminClient.cxx already does all that garbage.<commit_after>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #ifdef _MSC_VER #pragma warning( 4: 4786) #endif #include <stdio.h> #include <iostream> #include <map> #include <string> #include "BZAdminClient.h" #include "BZAdminUI.h" #include "OptionParser.h" #include "UIMap.h" // causes persistent rebuilding to obtain build versioning #include "version.h" int debugLevel = 0; #ifdef _WIN32 void Player::setDeadReckoning() { } #endif /** @file This is the main file for bzadmin, the bzflag text client. */ int main(int argc, char** argv) { #ifdef _WIN32 // startup winsock { static const int major = 2, minor = 2; WSADATA wsaData; if (WSAStartup(MAKEWORD(major, minor), &wsaData)) { std::cerr << "Could not initialise WinSock."; return 1; } if (LOBYTE(wsaData.wVersion) != major || HIBYTE(wsaData.wVersion) != minor) { std::cerr << "Invalid WinSock version (got " << (int) LOBYTE(wsaData.wVersion) << '.' << (int) HIBYTE(wsaData.wVersion) << ", expected" << major << '.' << minor << ')'; WSACleanup(); return 1; } } #endif // command line options std::string uiName("curses"); std::vector<std::string> visibleMsgs; std::vector<std::string> invisibleMsgs; // no curses, use stdboth as default instead const UIMap& interfaces = UIMap::instance(); if (interfaces.find("curses") == interfaces.end()) uiName = "stdboth"; // build a usage string with all interfaces UIMap::const_iterator uiIter; std::string uiUsage; for (uiIter = interfaces.begin(); uiIter != interfaces.end(); ++uiIter) uiUsage += uiIter->first + '|'; uiUsage = std::string("[-ui ") + uiUsage.substr(0, uiUsage.size() - 1) + ']'; // register and parse command line arguments OptionParser op(std::string("bzadmin ") + getAppVersion(), "CALLSIGN@HOST[:PORT] [COMMAND] [COMMAND] ..."); const std::string uiOption("ui"); const std::string uiMsg = "choose a user interface"; op.registerVariable(uiOption, uiName, uiUsage, uiMsg); op.registerVector("show", visibleMsgs, "[-show msgtype{,msgtype}*]", "tell bzadmin to show these message types"); op.registerVector("hide", invisibleMsgs, "[-hide msgtype{,msgtype}*]", "tell bzadmin not to show these message types"); if (!op.parse(argc, argv)) return 1; // check that we have callsign and host in the right format and extract them int atPos; std::string name = "", host = ""; if (!(op.getParameters().size() > 0 && (atPos = op.getParameters()[0].find('@')) > 0)) { // input callsign and host interactively std::cout << "No callsign@host specified. Please input them" << std::endl; std::cout << "Callsign: "; std::getline(std::cin, name); if (name.size() <= 1) { std::cerr << "You must specify a callsign. Exiting." << std::endl; return 1; } std::cout << "Server to connect to: "; std::getline(std::cin, host); if (host.size() <= 1) { std::cerr << "You must specify a host name to connect to. Exiting." << std::endl; return 1; } } else { // callsign/host on command line name = op.getParameters()[0].substr(0, atPos); host = op.getParameters()[0].substr(atPos + 1); } int port = ServerPort; int cPos = host.find(':'); if (cPos != -1) { port = atoi(host.substr(cPos + 1).c_str()); host = host.substr(0, cPos); } // check that the ui is valid uiIter = UIMap::instance().find(uiName); if (uiIter == UIMap::instance().end()) { std::cerr<<"There is no interface called \""<<uiName<<"\"."<<std::endl; return 1; } // try to connect BZAdminClient client(name, host, port); if (!client.isValid()) return 1; unsigned int i; for (i = 0; i < visibleMsgs.size(); ++i) client.showMessageType(visibleMsgs[i]); for (i = 0; i < invisibleMsgs.size(); ++i) client.ignoreMessageType(invisibleMsgs[i]); // if we got commands as arguments, send them and exit if (op.getParameters().size() > 1) { for (unsigned int i = 1; i < op.getParameters().size(); ++i) { if (op.getParameters()[i] == "/quit") { client.waitForServer(); return 0; } client.sendMessage(op.getParameters()[i], AllPlayers); } } // create UI and run the main loop BZAdminUI* ui = uiIter->second(client); client.setUI(ui); client.runLoop(); delete ui; return 0; } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>/* * fMBT, free Model Based Testing tool * Copyright (c) 2011, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include <string> #include <vector> #include <cstdio> #include <cstring> #include <cstdlib> #ifndef DROI #include <boost/regex.hpp> #include <glib.h> #include <glib-object.h> #else #include <cctype> #include <cstdio> #endif #include <string> #include <vector> #include <sstream> #include <fstream> #include <dlfcn.h> bool human_readable=true; void escape_free(const char* msg) { #ifdef DROI delete [] msg; #else g_free((void*)msg); #endif } void *load_lib(const std::string& libname,std::string& model_filename) { std::string name_candidate(libname); std::string errormessages; if (model_filename!="") { return dlopen(model_filename.c_str(),RTLD_NOW); } void* handle=dlopen(name_candidate.c_str(),RTLD_NOW); if (!handle) { errormessages += dlerror() + std::string("\n"); name_candidate="./"+name_candidate; handle=dlopen(name_candidate.c_str(),RTLD_NOW); } if (!handle) { errormessages += dlerror() + std::string("\n"); name_candidate=libname+".so"; handle=dlopen(name_candidate.c_str(),RTLD_NOW); } if (!handle) { errormessages += dlerror() + std::string("\n"); name_candidate="./"+name_candidate; handle=dlopen(name_candidate.c_str(),RTLD_NOW); } if (!handle) { errormessages += dlerror() + std::string("\n"); name_candidate="lib"+libname+".so"; handle=dlopen(name_candidate.c_str(),RTLD_NOW); } if (!handle) { errormessages += dlerror() + std::string("\n"); name_candidate="./"+name_candidate; handle=dlopen(name_candidate.c_str(),RTLD_NOW); } if (!handle) { fprintf(stderr, "%s", errormessages.c_str()); } return handle; } int find(const std::vector<std::string> &v,const std::string s) { for(unsigned i=0;i<v.size();i++) { if (v[i]==s) { return i; } } return 0; } bool isOutputName(const std::string& name) { return (name.c_str()[0]=='o'); } bool isInputName(const std::string& name) { return (name.c_str()[0]=='i') || (name.c_str()[0]=='d'); } void clear_whitespace(std::string& s){ std::string white (" \t\f\v\n\r"); /* more whilespace? */ size_t pos; pos=s.find_last_not_of(white); if (pos==std::string::npos) { s.clear(); pos=s.find_first_not_of(white); if (pos!=std::string::npos) { s=s.substr(pos); } } else { s.erase(pos+1); } } void clear_coding(std::string& s){ std::string coding ("\""); size_t pos; pos=s.find_last_not_of(coding); if (pos==std::string::npos) { s.clear(); } else { s.erase(pos+1); pos=s.find_first_not_of(coding); if (pos!=std::string::npos) { s=s.substr(pos); } } } std::string removehash(std::string& s); std::string filetype(std::string& _s) { std::string s=removehash(_s); size_t found=s.find_last_of("."); std::string r=s.substr(found+1); found=r.find_last_of("#"); if (found==r.npos) { return r; } return r.substr(0,found); } bool isxrules(std::string& s) { std::string s1(".xrules"); return (s.substr(s.size()-s1.size())==s1); } char* unescape_string(char* msg) { int l=std::strlen(msg); int j=0; for(int i=0;i<l;i++) { if (msg[i]=='%') { char* endp; char s[] = { msg[i+1],msg[i+2],0 }; char c=strtol(s,&endp,16); if (endp!=s) { msg[j]=c; i+=2; } else { msg[j]=msg[i]; } } else { msg[j]=msg[i]; } j++; } msg[j]=0; return msg; } void unescape_string(std::string& msg) { char* tmp=strdup(msg.c_str()); unescape_string(tmp); msg=tmp; free(tmp); } char* escape_string(const char* msg) { #ifdef DROI int len=std::strlen(msg); char* endp=new char[3*len+1]; char* ret=endp; endp[0]=0; for(int i=0;i<len;i++) { char c=msg[i]; if (isalnum(c)) { *endp=c; endp++; } else { endp+=std::sprintf(endp,"%%%X",c); } } *endp=0; return ret; #else return g_uri_escape_string(msg,NULL,TRUE); #endif } std::string removehash(std::string& s) { unsigned long cutpos = s.find_last_of("#"); if (cutpos == s.npos) { return s; } else { return s.substr(0,cutpos); } return ""; } #ifndef DROI char* readfile(const char* filename,const char* preprocess) { char* out=NULL; int status; if (preprocess==NULL) { return readfile(filename,false); } std::string s(preprocess); s=s + " " + filename; if (!g_spawn_command_line_sync(s.c_str(),&out,NULL,&status,NULL)) { throw (int)(24); } return out; } #endif char* readfile(const char* filename,bool preprocess) { std::string fn(filename); unsigned long cutpos = fn.find_last_of("#"); if (cutpos == fn.npos) { #ifndef DROI if (preprocess) { GString *gs=g_string_new(""); g_string_printf(gs,"/bin/sh -c \"cpp '%s'|grep -v ^#\"",filename); char* out=readfile(filename,gs->str); //g_free(gs); return out; } else { char* out=NULL; g_file_get_contents(filename,&out,NULL,NULL); return out; } #else /* read file contents always without preprocessing when glib not * available */ std::ifstream f; int file_len; f.open(filename, std::fstream::in | std::fstream::ate); if (!f.is_open()) return NULL; file_len = f.tellg(); f.seekg(0, std::ios::beg); char *contents = (char*)malloc(file_len+1); if (!contents) { f.close(); return NULL; } f.read(contents, file_len); f.close(); contents[file_len] = '\0'; return contents; #endif } else { return unescape_string(strdup(fn.substr(cutpos+1).c_str())); } } std::string capsulate(std::string s) { if (s=="") { return "\""; } std::ostringstream t(std::ios::out | std::ios::binary); if (human_readable) { t << ":" << s.length() << ":" << s << "\""; } else { char* sesc=escape_string(s.c_str()); t << "#" << sesc << "\""; escape_free(sesc); } return t.str(); } void string2vector(char* s,std::vector<int>& a) { int v; int i=0; char* endp; char* ss=s; v=strtol(ss,&endp,10); a.resize(0); while (endp!=ss) { a.push_back(v); ss=endp; v=strtol(ss,&endp,10); i++; } } #ifndef DROI std::string replace(boost::regex& expression, const char* format_string, std::string::iterator first, std::string::iterator last) { std::ostringstream t(std::ios::out | std::ios::binary); std::ostream_iterator<char> oi(t); std::string s; boost::regex_replace(oi,first,last,expression,format_string, boost::match_default | boost::format_all | boost::format_first_only); s=t.str(); return s; } #endif void print_vectors(int* v,unsigned size,std::vector<std::string>& s,const char* prefix,int add) { for(unsigned i=0;i<size;i++) { if (s[v[i]]!="") printf("%s%i:%s\n",prefix,i+add,s[v[i]].c_str()); } } void print_vector(std::vector<std::string>& s,const char* prefix,int add) { for(unsigned i=0;i<s.size();i++) { if (s[i]!="") { printf("%s%i:%s\n",prefix,i+add,s[i].c_str()); } } } std::string to_string(const int t) { std::stringstream ss; ss << t; return ss.str(); } std::string to_string(const int cnt, int* t, std::vector<std::string>& st) { std::string ret; if (cnt==0) { return ret; } ret=st[t[0]]; for(int i=1;i<cnt;i++) { ret+=" "+st[t[i]]; } return ret; } void strvec(std::vector<std::string>& v,std::string& s, std::string& separator) { unsigned long cutpos; while ((cutpos=s.find_first_of(separator))!=s.npos) { std::string a=s.substr(0,cutpos); v.push_back(a); s=s.substr(cutpos+1); } v.push_back(s); } <commit_msg>cpp dropped<commit_after>/* * fMBT, free Model Based Testing tool * Copyright (c) 2011, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include <string> #include <vector> #include <cstdio> #include <cstring> #include <cstdlib> #ifndef DROI #include <boost/regex.hpp> #include <glib.h> #include <glib-object.h> #else #include <cctype> #include <cstdio> #endif #include <string> #include <vector> #include <sstream> #include <fstream> #include <dlfcn.h> bool human_readable=true; void escape_free(const char* msg) { #ifdef DROI delete [] msg; #else g_free((void*)msg); #endif } void *load_lib(const std::string& libname,std::string& model_filename) { std::string name_candidate(libname); std::string errormessages; if (model_filename!="") { return dlopen(model_filename.c_str(),RTLD_NOW); } void* handle=dlopen(name_candidate.c_str(),RTLD_NOW); if (!handle) { errormessages += dlerror() + std::string("\n"); name_candidate="./"+name_candidate; handle=dlopen(name_candidate.c_str(),RTLD_NOW); } if (!handle) { errormessages += dlerror() + std::string("\n"); name_candidate=libname+".so"; handle=dlopen(name_candidate.c_str(),RTLD_NOW); } if (!handle) { errormessages += dlerror() + std::string("\n"); name_candidate="./"+name_candidate; handle=dlopen(name_candidate.c_str(),RTLD_NOW); } if (!handle) { errormessages += dlerror() + std::string("\n"); name_candidate="lib"+libname+".so"; handle=dlopen(name_candidate.c_str(),RTLD_NOW); } if (!handle) { errormessages += dlerror() + std::string("\n"); name_candidate="./"+name_candidate; handle=dlopen(name_candidate.c_str(),RTLD_NOW); } if (!handle) { fprintf(stderr, "%s", errormessages.c_str()); } return handle; } int find(const std::vector<std::string> &v,const std::string s) { for(unsigned i=0;i<v.size();i++) { if (v[i]==s) { return i; } } return 0; } bool isOutputName(const std::string& name) { return (name.c_str()[0]=='o'); } bool isInputName(const std::string& name) { return (name.c_str()[0]=='i') || (name.c_str()[0]=='d'); } void clear_whitespace(std::string& s){ std::string white (" \t\f\v\n\r"); /* more whilespace? */ size_t pos; pos=s.find_last_not_of(white); if (pos==std::string::npos) { s.clear(); pos=s.find_first_not_of(white); if (pos!=std::string::npos) { s=s.substr(pos); } } else { s.erase(pos+1); } } void clear_coding(std::string& s){ std::string coding ("\""); size_t pos; pos=s.find_last_not_of(coding); if (pos==std::string::npos) { s.clear(); } else { s.erase(pos+1); pos=s.find_first_not_of(coding); if (pos!=std::string::npos) { s=s.substr(pos); } } } std::string removehash(std::string& s); std::string filetype(std::string& _s) { std::string s=removehash(_s); size_t found=s.find_last_of("."); std::string r=s.substr(found+1); found=r.find_last_of("#"); if (found==r.npos) { return r; } return r.substr(0,found); } bool isxrules(std::string& s) { std::string s1(".xrules"); return (s.substr(s.size()-s1.size())==s1); } char* unescape_string(char* msg) { int l=std::strlen(msg); int j=0; for(int i=0;i<l;i++) { if (msg[i]=='%') { char* endp; char s[] = { msg[i+1],msg[i+2],0 }; char c=strtol(s,&endp,16); if (endp!=s) { msg[j]=c; i+=2; } else { msg[j]=msg[i]; } } else { msg[j]=msg[i]; } j++; } msg[j]=0; return msg; } void unescape_string(std::string& msg) { char* tmp=strdup(msg.c_str()); unescape_string(tmp); msg=tmp; free(tmp); } char* escape_string(const char* msg) { #ifdef DROI int len=std::strlen(msg); char* endp=new char[3*len+1]; char* ret=endp; endp[0]=0; for(int i=0;i<len;i++) { char c=msg[i]; if (isalnum(c)) { *endp=c; endp++; } else { endp+=std::sprintf(endp,"%%%X",c); } } *endp=0; return ret; #else return g_uri_escape_string(msg,NULL,TRUE); #endif } std::string removehash(std::string& s) { unsigned long cutpos = s.find_last_of("#"); if (cutpos == s.npos) { return s; } else { return s.substr(0,cutpos); } return ""; } #ifndef DROI char* readfile(const char* filename,const char* preprocess) { char* out=NULL; int status; if (preprocess==NULL) { return readfile(filename,false); } std::string s(preprocess); s=s + " " + filename; if (!g_spawn_command_line_sync(s.c_str(),&out,NULL,&status,NULL)) { throw (int)(24); } return out; } #endif char* readfile(const char* filename,bool preprocess) { std::string fn(filename); unsigned long cutpos = fn.find_last_of("#"); if (cutpos == fn.npos) { #ifndef DROI if (preprocess) { GString *gs=g_string_new(""); g_string_printf(gs,"/bin/sh -c \"cat '%s'|grep -v ^#\"",filename); char* out=readfile(filename,gs->str); //g_free(gs); return out; } else { char* out=NULL; g_file_get_contents(filename,&out,NULL,NULL); return out; } #else /* read file contents always without preprocessing when glib not * available */ std::ifstream f; int file_len; f.open(filename, std::fstream::in | std::fstream::ate); if (!f.is_open()) return NULL; file_len = f.tellg(); f.seekg(0, std::ios::beg); char *contents = (char*)malloc(file_len+1); if (!contents) { f.close(); return NULL; } f.read(contents, file_len); f.close(); contents[file_len] = '\0'; return contents; #endif } else { return unescape_string(strdup(fn.substr(cutpos+1).c_str())); } } std::string capsulate(std::string s) { if (s=="") { return "\""; } std::ostringstream t(std::ios::out | std::ios::binary); if (human_readable) { t << ":" << s.length() << ":" << s << "\""; } else { char* sesc=escape_string(s.c_str()); t << "#" << sesc << "\""; escape_free(sesc); } return t.str(); } void string2vector(char* s,std::vector<int>& a) { int v; int i=0; char* endp; char* ss=s; v=strtol(ss,&endp,10); a.resize(0); while (endp!=ss) { a.push_back(v); ss=endp; v=strtol(ss,&endp,10); i++; } } #ifndef DROI std::string replace(boost::regex& expression, const char* format_string, std::string::iterator first, std::string::iterator last) { std::ostringstream t(std::ios::out | std::ios::binary); std::ostream_iterator<char> oi(t); std::string s; boost::regex_replace(oi,first,last,expression,format_string, boost::match_default | boost::format_all | boost::format_first_only); s=t.str(); return s; } #endif void print_vectors(int* v,unsigned size,std::vector<std::string>& s,const char* prefix,int add) { for(unsigned i=0;i<size;i++) { if (s[v[i]]!="") printf("%s%i:%s\n",prefix,i+add,s[v[i]].c_str()); } } void print_vector(std::vector<std::string>& s,const char* prefix,int add) { for(unsigned i=0;i<s.size();i++) { if (s[i]!="") { printf("%s%i:%s\n",prefix,i+add,s[i].c_str()); } } } std::string to_string(const int t) { std::stringstream ss; ss << t; return ss.str(); } std::string to_string(const int cnt, int* t, std::vector<std::string>& st) { std::string ret; if (cnt==0) { return ret; } ret=st[t[0]]; for(int i=1;i<cnt;i++) { ret+=" "+st[t[i]]; } return ret; } void strvec(std::vector<std::string>& v,std::string& s, std::string& separator) { unsigned long cutpos; while ((cutpos=s.find_first_of(separator))!=s.npos) { std::string a=s.substr(0,cutpos); v.push_back(a); s=s.substr(cutpos+1); } v.push_back(s); } <|endoftext|>
<commit_before>// if s1 starts with s2 returns true, else false // len is the length of s1 // s2 should be null-terminated static bool starts_with(const char *s1, int len, const char *s2) { int n = 0; while (*s2 && n < len) { if (*s1++ != *s2++) return false; n++; } return *s2 == 0; } static int parse_mouse_event(struct tb_event *event, const char *buf, int len) { if (len >= 6 && starts_with(buf, len, "\033[M")) { // X10 mouse encoding, the simplest one // \033 [ M Cb Cx Cy int b = buf[3] - 32; switch (b & 3) { case 0: if ((b & 64) != 0) event->key = TB_KEY_MOUSE_WHEEL_UP; else event->key = TB_KEY_MOUSE_LEFT; break; case 1: if ((b & 64) != 0) event->key = TB_KEY_MOUSE_WHEEL_DOWN; else event->key = TB_KEY_MOUSE_MIDDLE; break; case 2: event->key = TB_KEY_MOUSE_RIGHT; break; case 3: event->key = TB_KEY_MOUSE_RELEASE; break; default: return -6; } event->type = TB_EVENT_MOUSE; // TB_EVENT_KEY by default if ((b & 32) != 0) event->mod |= TB_MOD_MOTION; // the coord is 1,1 for upper left event->x = (uint8_t)buf[4] - 1 - 32; event->y = (uint8_t)buf[5] - 1 - 32; return 6; } else if (starts_with(buf, len, "\033[<") || starts_with(buf, len, "\033[")) { // xterm 1006 extended mode or urxvt 1015 extended mode // xterm: \033 [ < Cb ; Cx ; Cy (M or m) // urxvt: \033 [ Cb ; Cx ; Cy M int i, mi = -1, starti = -1; int isM, isU, s1 = -1, s2 = -1; int n1 = 0, n2 = 0, n3 = 0; for (i = 0; i < len; i++) { // We search the first (s1) and the last (s2) ';' if (buf[i] == ';') { if (s1 == -1) s1 = i; s2 = i; } // We search for the first 'm' or 'M' if ((buf[i] == 'm' || buf[i] == 'M') && mi == -1) { mi = i; break; } } if (mi == -1) return 0; // whether it's a capital M or not isM = (buf[mi] == 'M'); if (buf[2] == '<') { isU = 0; starti = 3; } else { isU = 1; starti = 2; } if (s1 == -1 || s2 == -1 || s1 == s2) return 0; n1 = strtoul(&buf[starti], NULL, 10); n2 = strtoul(&buf[s1 + 1], NULL, 10); n3 = strtoul(&buf[s2 + 1], NULL, 10); if (isU) n1 -= 32; switch (n1 & 3) { case 0: if ((n1&64) != 0) { event->key = TB_KEY_MOUSE_WHEEL_UP; } else { event->key = TB_KEY_MOUSE_LEFT; } break; case 1: if ((n1&64) != 0) { event->key = TB_KEY_MOUSE_WHEEL_DOWN; } else { event->key = TB_KEY_MOUSE_MIDDLE; } break; case 2: event->key = TB_KEY_MOUSE_RIGHT; break; case 3: event->key = TB_KEY_MOUSE_RELEASE; break; default: return mi + 1; } if (!isM) { // on xterm mouse release is signaled by lowercase m event->key = TB_KEY_MOUSE_RELEASE; } event->type = TB_EVENT_MOUSE; // TB_EVENT_KEY by default if ((n1&32) != 0) event->mod |= TB_MOD_MOTION; event->x = (uint8_t)n2 - 1; event->y = (uint8_t)n3 - 1; return mi + 1; } return 0; } // convert escape sequence to event, and return consumed bytes on success (failure == 0) static int parse_escape_seq(struct tb_event *event, const char *buf, int len) { int mouse_parsed = parse_mouse_event(event, buf, len); if (mouse_parsed != 0) return mouse_parsed; // it's pretty simple here, find 'starts_with' match and return // success, else return failure int i; for (i = 0; keys[i]; i++) { if (starts_with(buf, len, keys[i])) { event->ch = 0; event->key = 0xFFFF-i; return strlen(keys[i]); } } return 0; } static bool extract_event(struct tb_event *event, struct bytebuffer *inbuf, int inputmode) { const char *buf = inbuf->buf; const int len = inbuf->len; if (len == 0) return false; if (buf[0] == '\033') { int n = parse_escape_seq(event, buf, len); if (n != 0) { bool success = true; if (n < 0) { success = false; n = -n; } bytebuffer_truncate(inbuf, n); return success; } else { // it's not escape sequence, then it's ALT or ESC, // check inputmode if (inputmode&TB_INPUT_ESC) { // if we're in escape mode, fill ESC event, pop // buffer, return success event->ch = 0; event->key = TB_KEY_ESC; event->mod = 0; bytebuffer_truncate(inbuf, 1); return true; } else if (inputmode&TB_INPUT_ALT) { // if we're in alt mode, set ALT modifier to // event and redo parsing event->mod = TB_MOD_ALT; bytebuffer_truncate(inbuf, 1); return extract_event(event, inbuf, inputmode); } assert(!"never got here"); } } // if we're here, this is not an escape sequence and not an alt sequence // so, it's a FUNCTIONAL KEY or a UNICODE character // first of all check if it's a functional key if ((unsigned char)buf[0] <= TB_KEY_SPACE || (unsigned char)buf[0] == TB_KEY_BACKSPACE2) { // fill event, pop buffer, return success */ event->ch = 0; event->key = (uint16_t)buf[0]; bytebuffer_truncate(inbuf, 1); return true; } // feh... we got utf8 here // check if there is all bytes if (len >= tb_utf8_char_length(buf[0])) { /* everything ok, fill event, pop buffer, return success */ tb_utf8_char_to_unicode(&event->ch, buf); event->key = 0; bytebuffer_truncate(inbuf, tb_utf8_char_length(buf[0])); return true; } // event isn't recognized, perhaps there is not enough bytes in utf8 // sequence return false; } <commit_msg>input.inl: Remove starts_with(), use strncmp() instead<commit_after>static int parse_mouse_event(struct tb_event *event, const char *buf, int len) { if (len >= 6 && strncmp(buf, "\033[M", len) == 0) { // X10 mouse encoding, the simplest one // \033 [ M Cb Cx Cy int b = buf[3] - 32; switch (b & 3) { case 0: if ((b & 64) != 0) event->key = TB_KEY_MOUSE_WHEEL_UP; else event->key = TB_KEY_MOUSE_LEFT; break; case 1: if ((b & 64) != 0) event->key = TB_KEY_MOUSE_WHEEL_DOWN; else event->key = TB_KEY_MOUSE_MIDDLE; break; case 2: event->key = TB_KEY_MOUSE_RIGHT; break; case 3: event->key = TB_KEY_MOUSE_RELEASE; break; default: return -6; } event->type = TB_EVENT_MOUSE; // TB_EVENT_KEY by default if ((b & 32) != 0) event->mod |= TB_MOD_MOTION; // the coord is 1,1 for upper left event->x = (uint8_t)buf[4] - 1 - 32; event->y = (uint8_t)buf[5] - 1 - 32; return 6; } else if (strncmp(buf, "\033[<", len) == 0 || strncmp(buf, "\033[", len) == 0) { // xterm 1006 extended mode or urxvt 1015 extended mode // xterm: \033 [ < Cb ; Cx ; Cy (M or m) // urxvt: \033 [ Cb ; Cx ; Cy M int i, mi = -1, starti = -1; int isM, isU, s1 = -1, s2 = -1; int n1 = 0, n2 = 0, n3 = 0; for (i = 0; i < len; i++) { // We search the first (s1) and the last (s2) ';' if (buf[i] == ';') { if (s1 == -1) s1 = i; s2 = i; } // We search for the first 'm' or 'M' if ((buf[i] == 'm' || buf[i] == 'M') && mi == -1) { mi = i; break; } } if (mi == -1) return 0; // whether it's a capital M or not isM = (buf[mi] == 'M'); if (buf[2] == '<') { isU = 0; starti = 3; } else { isU = 1; starti = 2; } if (s1 == -1 || s2 == -1 || s1 == s2) return 0; n1 = strtoul(&buf[starti], NULL, 10); n2 = strtoul(&buf[s1 + 1], NULL, 10); n3 = strtoul(&buf[s2 + 1], NULL, 10); if (isU) n1 -= 32; switch (n1 & 3) { case 0: if ((n1&64) != 0) { event->key = TB_KEY_MOUSE_WHEEL_UP; } else { event->key = TB_KEY_MOUSE_LEFT; } break; case 1: if ((n1&64) != 0) { event->key = TB_KEY_MOUSE_WHEEL_DOWN; } else { event->key = TB_KEY_MOUSE_MIDDLE; } break; case 2: event->key = TB_KEY_MOUSE_RIGHT; break; case 3: event->key = TB_KEY_MOUSE_RELEASE; break; default: return mi + 1; } if (!isM) { // on xterm mouse release is signaled by lowercase m event->key = TB_KEY_MOUSE_RELEASE; } event->type = TB_EVENT_MOUSE; // TB_EVENT_KEY by default if ((n1&32) != 0) event->mod |= TB_MOD_MOTION; event->x = (uint8_t)n2 - 1; event->y = (uint8_t)n3 - 1; return mi + 1; } return 0; } // convert escape sequence to event, and return consumed bytes on success (failure == 0) static int parse_escape_seq(struct tb_event *event, const char *buf, int len) { int mouse_parsed = parse_mouse_event(event, buf, len); if (mouse_parsed != 0) return mouse_parsed; // it's pretty simple here, find 'strncmp' match and return // success, else return failure int i; for (i = 0; keys[i]; i++) { if (strncmp(buf, keys[i], len) == 0) { event->ch = 0; event->key = 0xFFFF-i; return strlen(keys[i]); } } return 0; } static bool extract_event(struct tb_event *event, struct bytebuffer *inbuf, int inputmode) { const char *buf = inbuf->buf; const int len = inbuf->len; if (len == 0) return false; if (buf[0] == '\033') { int n = parse_escape_seq(event, buf, len); if (n != 0) { bool success = true; if (n < 0) { success = false; n = -n; } bytebuffer_truncate(inbuf, n); return success; } else { // it's not escape sequence, then it's ALT or ESC, // check inputmode if (inputmode&TB_INPUT_ESC) { // if we're in escape mode, fill ESC event, pop // buffer, return success event->ch = 0; event->key = TB_KEY_ESC; event->mod = 0; bytebuffer_truncate(inbuf, 1); return true; } else if (inputmode&TB_INPUT_ALT) { // if we're in alt mode, set ALT modifier to // event and redo parsing event->mod = TB_MOD_ALT; bytebuffer_truncate(inbuf, 1); return extract_event(event, inbuf, inputmode); } assert(!"never got here"); } } // if we're here, this is not an escape sequence and not an alt sequence // so, it's a FUNCTIONAL KEY or a UNICODE character // first of all check if it's a functional key if ((unsigned char)buf[0] <= TB_KEY_SPACE || (unsigned char)buf[0] == TB_KEY_BACKSPACE2) { // fill event, pop buffer, return success */ event->ch = 0; event->key = (uint16_t)buf[0]; bytebuffer_truncate(inbuf, 1); return true; } // feh... we got utf8 here // check if there is all bytes if (len >= tb_utf8_char_length(buf[0])) { /* everything ok, fill event, pop buffer, return success */ tb_utf8_char_to_unicode(&event->ch, buf); event->key = 0; bytebuffer_truncate(inbuf, tb_utf8_char_length(buf[0])); return true; } // event isn't recognized, perhaps there is not enough bytes in utf8 // sequence return false; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: animatedsprite.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2004-11-26 19:12:10 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SLIDESHOW_ANIMATEDSPRITE_HXX #define _SLIDESHOW_ANIMATEDSPRITE_HXX #ifndef _CPPCANVAS_CUSTOMSPRITE_HXX #include <cppcanvas/customsprite.hxx> #endif #ifndef BOOST_SHARED_PTR_HPP_INCLUDED #include <boost/shared_ptr.hpp> #endif #ifndef _BGFX_VECTOR_B2DSIZE_HXX #include <basegfx/vector/b2dsize.hxx> #endif #ifndef _BGFX_POINT_B2DPOINT_HXX #include <basegfx/point/b2dpoint.hxx> #endif #ifndef _BGFX_POLYGON_B2DPOLYPOLYGON_HXX #include <basegfx/polygon/b2dpolypolygon.hxx> #endif #ifndef _COMPHELPER_OPTIONALVALUE_HXX #include <comphelper/optionalvalue.hxx> #endif #include <viewlayer.hxx> /* Definition of AnimatedSprite class */ namespace presentation { namespace internal { /** This class provides the sprite for animated shapes. Besides encapsulating the Canvas sprite for animated shapes, this class also handles dynamic sprite resizing and all the gory details of offset calculations and rounding prevention. */ class AnimatedSprite { public: /** Create a new AnimatedSprite, for the given metafile shape. @param rViewLayer The destination view layer, on which the animation should appear @param rSpriteSizePixel The overall size of the sprite in device coordinate space, sufficient to display all transformations, shape changes and clips. */ AnimatedSprite( const ViewLayerSharedPtr& rViewLayer, const ::basegfx::B2DSize& rSpriteSizePixel ); ~AnimatedSprite(); /** Resize the sprite. @param rSpriteSizePixel The new size in pixel @return true, if the resize was successful. If false is returned, the sprite might be invalid. */ bool resize( const ::basegfx::B2DSize& rSpriteSizePixel ); /// Show the sprite void show(); /// Hide the sprite void hide(); /** Query the content canvas for the current sprite. Note that this method must be called <em>everytime</em> something is rendered to the sprite, because XCustomSprite does not guarantee the validity of the canvas after a render operation. Furthermore, the view transformation on the returned canvas is already correctly setup, matching the associated destination canvas. */ ::cppcanvas::CanvasSharedPtr getContentCanvas() const; /** Move the sprite in user coordinate space. If the sprite is not yet created, this method has no effect. */ void move( const ::basegfx::B2DPoint& rNewPos ); /** Move the sprite in device pixel space. If the sprite is not yet created, this method has no effect. */ void movePixel( const ::basegfx::B2DPoint& rNewPos ); /** Set the alpha value of the sprite. If the sprite is not yet created, this method has no effect. */ void setAlpha( double rAlpha ); /** Set a sprite clip in user coordinate space. If the sprite is not yet created, this method has no effect. */ void clip( const ::basegfx::B2DPolyPolygon& rClip ); /** Set the sprite priority. The sprite priority determines the ordering of the sprites on screen, i.e. which sprite lies before which. @param rPrio The new sprite prio. Must be in the range [0,1] */ void setPriority( double rPrio ); private: // default: disabled copy/assignment AnimatedSprite(const AnimatedSprite&); AnimatedSprite& operator=( const AnimatedSprite& ); ViewLayerSharedPtr mpViewLayer; ::cppcanvas::CustomSpriteSharedPtr mpSprite; ::basegfx::B2DSize maEffectiveSpriteSizePixel; double mnAlpha; ::comphelper::OptionalValue< ::basegfx::B2DPoint > maPosPixel; ::comphelper::OptionalValue< ::basegfx::B2DPoint > maPos; ::comphelper::OptionalValue< ::basegfx::B2DPolyPolygon > maClip; bool mbSpriteVisible; }; typedef ::boost::shared_ptr< AnimatedSprite > AnimatedSpriteSharedPtr; } } #endif /* _SLIDESHOW_ANIMATEDSPRITE_HXX */ <commit_msg>INTEGRATION: CWS presfixes03 (1.2.22); FILE MERGED 2005/04/11 17:42:35 thb 1.2.22.1: #i36190# #i44807# Implemented reduction of subset animations to the actual subset bounding box: relegated some common code to tools.cxx; completely overhauled viewshape.cxx; removed duplicate subset vector entry from DrawShapeSubsetting; corrected auto-reverse mode (fixed broken 'put on the brakes' effect); fixed AnimationSetNode deactivate behaviour (made the sequence activate->process activity->deactivate explicit (was by chance before and currently actually broken))<commit_after>/************************************************************************* * * $RCSfile: animatedsprite.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2005-04-18 09:51:13 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SLIDESHOW_ANIMATEDSPRITE_HXX #define _SLIDESHOW_ANIMATEDSPRITE_HXX #ifndef _CPPCANVAS_CUSTOMSPRITE_HXX #include <cppcanvas/customsprite.hxx> #endif #ifndef BOOST_SHARED_PTR_HPP_INCLUDED #include <boost/shared_ptr.hpp> #endif #ifndef _BGFX_MATRIX_B2DHOMMATRIX_HXX #include <basegfx/matrix/b2dhommatrix.hxx> #endif #ifndef _BGFX_VECTOR_B2DSIZE_HXX #include <basegfx/vector/b2dsize.hxx> #endif #ifndef _BGFX_POINT_B2DPOINT_HXX #include <basegfx/point/b2dpoint.hxx> #endif #ifndef _BGFX_POLYGON_B2DPOLYPOLYGON_HXX #include <basegfx/polygon/b2dpolypolygon.hxx> #endif #ifndef _COMPHELPER_OPTIONALVALUE_HXX #include <comphelper/optionalvalue.hxx> #endif #include <viewlayer.hxx> /* Definition of AnimatedSprite class */ namespace presentation { namespace internal { /** This class provides the sprite for animated shapes. Besides encapsulating the Canvas sprite for animated shapes, this class also handles dynamic sprite resizing and all the gory details of offset calculations and rounding prevention. */ class AnimatedSprite { public: /** Create a new AnimatedSprite, for the given metafile shape. @param rViewLayer The destination view layer, on which the animation should appear @param rSpriteSizePixel The overall size of the sprite in device coordinate space, sufficient to display all transformations, shape changes and clips. */ AnimatedSprite( const ViewLayerSharedPtr& rViewLayer, const ::basegfx::B2DSize& rSpriteSizePixel ); ~AnimatedSprite(); /** Resize the sprite. @param rSpriteSizePixel The new size in pixel @return true, if the resize was successful. If false is returned, the sprite might be invalid. */ bool resize( const ::basegfx::B2DSize& rSpriteSizePixel ); /** Set an offset for the content output in pixel This method offsets the output on the sprite content canvas by the specified amount of device pixel (for subsequent render operations). */ void setPixelOffset( const ::basegfx::B2DSize& rPixelOffset ); /// Retrieve current pixel offset for content output. ::basegfx::B2DSize getPixelOffset() const; /// Show the sprite void show(); /// Hide the sprite void hide(); /** Query the content canvas for the current sprite. Note that this method must be called <em>everytime</em> something is rendered to the sprite, because XCustomSprite does not guarantee the validity of the canvas after a render operation. Furthermore, the view transformation on the returned canvas is already correctly setup, matching the associated destination canvas. */ ::cppcanvas::CanvasSharedPtr getContentCanvas() const; /** Move the sprite in user coordinate space. If the sprite is not yet created, this method has no effect. */ void move( const ::basegfx::B2DPoint& rNewPos ); /** Move the sprite in device pixel space. If the sprite is not yet created, this method has no effect. */ void movePixel( const ::basegfx::B2DPoint& rNewPos ); /** Set the alpha value of the sprite. If the sprite is not yet created, this method has no effect. */ void setAlpha( double rAlpha ); /** Set a sprite clip in user coordinate space. If the sprite is not yet created, this method has no effect. */ void clip( const ::basegfx::B2DPolyPolygon& rClip ); /** Set a sprite transformation. If the sprite is not yet created, this method has no effect. */ void transform( const ::basegfx::B2DHomMatrix& rTransform ); /** Set the sprite priority. The sprite priority determines the ordering of the sprites on screen, i.e. which sprite lies before which. @param rPrio The new sprite prio. Must be in the range [0,1] */ void setPriority( double rPrio ); private: // default: disabled copy/assignment AnimatedSprite(const AnimatedSprite&); AnimatedSprite& operator=( const AnimatedSprite& ); ViewLayerSharedPtr mpViewLayer; ::cppcanvas::CustomSpriteSharedPtr mpSprite; ::basegfx::B2DSize maEffectiveSpriteSizePixel; ::basegfx::B2DSize maContentPixelOffset; double mnAlpha; ::comphelper::OptionalValue< ::basegfx::B2DPoint > maPosPixel; ::comphelper::OptionalValue< ::basegfx::B2DPoint > maPos; ::comphelper::OptionalValue< ::basegfx::B2DPolyPolygon > maClip; ::comphelper::OptionalValue< ::basegfx::B2DHomMatrix > maTransform; bool mbSpriteVisible; }; typedef ::boost::shared_ptr< AnimatedSprite > AnimatedSpriteSharedPtr; } } #endif /* _SLIDESHOW_ANIMATEDSPRITE_HXX */ <|endoftext|>
<commit_before>#include <stdexcept> #include <iostream> #include <string.h> #include <libshm.hpp> namespace shm{ template <key_t KEY, typename T> int Shm<KEY, T>::shmid_ = -1; template <key_t KEY, typename T> Shm<KEY, T>::Shm():shm_(0){ get(); attach(); } template <key_t KEY, typename T> Shm<KEY, T>::~Shm(){ if(shm_ != nullptr){ shmdt(shm_); shm_ = 0; } } template <key_t KEY, typename T> void Shm<KEY, T>::setElement(const T *data){ memcpy(shm_, data, sizeof(T)); } template <key_t KEY, typename T> const T* Shm<KEY, T>::getElement(){ T* ptr = new(shm_) T; return ptr; } template <key_t KEY, typename T> void Shm<KEY, T>::attach(){ if ((shm_ = shmat(shmid_, NULL, 0)) == (char *) -1){ throw std::runtime_error("Failed attach shm"); } } } <commit_msg>memcopy on mem element<commit_after>#include <stdexcept> #include <iostream> #include <string.h> #include <libshm.hpp> namespace shm{ template <key_t KEY, typename T> int Shm<KEY, T>::shmid_ = -1; template <key_t KEY, typename T> Shm<KEY, T>::Shm():shm_(0){ get(); attach(); } template <key_t KEY, typename T> Shm<KEY, T>::~Shm(){ if(shm_ != nullptr){ shmdt(shm_); shm_ = 0; } } template <key_t KEY, typename T> void Shm<KEY, T>::setElement(const T *data){ memcpy(shm_, data, sizeof(T)); } template <key_t KEY, typename T> const T* Shm<KEY, T>::getElement(){ T* tmp_ptr = new(shm_) T; T* ptr = new T; memcpy(ptr, tmp_ptr, sizeof(T)); return ptr; } template <key_t KEY, typename T> void Shm<KEY, T>::attach(){ if ((shm_ = shmat(shmid_, NULL, 0)) == (char *) -1){ throw std::runtime_error("Failed attach shm"); } } } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: wrap_ITKAlgorithms.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifdef CABLE_CONFIGURATION #include "itkCSwigMacros.h" namespace _cable_ { const char* const package = ITK_WRAP_PACKAGE_NAME(ITK_WRAP_PACKAGE); const char* const groups[] = { ITK_WRAP_GROUP(itkCurvatureFlowImageFilter), ITK_WRAP_GROUP(itkDemonsRegistrationFilter), ITK_WRAP_GROUP(itkHistogramMatchingImageFilter), ITK_WRAP_GROUP(itkImageRegistrationMethod), ITK_WRAP_GROUP(itkImageToImageMetric), ITK_WRAP_GROUP(itkMeanSquaresImageToImageMetric), ITK_WRAP_GROUP(itkMutualInformationImageToImageMetric), ITK_WRAP_GROUP(itkMultiResolutionImageRegistrationMethod), ITK_WRAP_GROUP(itkNormalizedCorrelationImageToImageMetric), ITK_WRAP_GROUP(itkOtsuThresholdImageCalculator), ITK_WRAP_GROUP(itkMeanReciprocalSquareDifferenceImageToImageMetric), ITK_WRAP_GROUP(itkThresholdSegmentationLevelSetImageFilter), ITK_WRAP_GROUP(itkGeodesicActiveContourLevelSetImageFilter), ITK_WRAP_GROUP(itkShapeDetectionLevelSetImageFilter), ITK_WRAP_GROUP(itkCurvesLevelSetImageFilter), ITK_WRAP_GROUP(itkNarrowBandLevelSetImageFilter), ITK_WRAP_GROUP(itkNarrowBandCurvesLevelSetImageFilter), ITK_WRAP_GROUP(itkMattesMutualInformationImageToImageMetric), ITK_WRAP_GROUP(itkPDEDeformableRegistrationFilter), ITK_WRAP_GROUP(itkRecursiveMultiResolutionPyramidImageFilter), ITK_WRAP_GROUP(itkVoronoiSegmentationImageFilter), ITK_WRAP_GROUP(itkWatershedImageFilter), ITK_WRAP_GROUP(itkSegmentationLevelSetImageFilter), ITK_WRAP_GROUP(itkTreeNodeSO) }; } #endif <commit_msg>COMP: added itkSparseFieldLevelSetImageFilter wrap<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: wrap_ITKAlgorithms.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifdef CABLE_CONFIGURATION #include "itkCSwigMacros.h" namespace _cable_ { const char* const package = ITK_WRAP_PACKAGE_NAME(ITK_WRAP_PACKAGE); const char* const groups[] = { ITK_WRAP_GROUP(itkCurvatureFlowImageFilter), ITK_WRAP_GROUP(itkDemonsRegistrationFilter), ITK_WRAP_GROUP(itkHistogramMatchingImageFilter), ITK_WRAP_GROUP(itkImageRegistrationMethod), ITK_WRAP_GROUP(itkImageToImageMetric), ITK_WRAP_GROUP(itkMeanSquaresImageToImageMetric), ITK_WRAP_GROUP(itkMutualInformationImageToImageMetric), ITK_WRAP_GROUP(itkMultiResolutionImageRegistrationMethod), ITK_WRAP_GROUP(itkNormalizedCorrelationImageToImageMetric), ITK_WRAP_GROUP(itkOtsuThresholdImageCalculator), ITK_WRAP_GROUP(itkMeanReciprocalSquareDifferenceImageToImageMetric), ITK_WRAP_GROUP(itkThresholdSegmentationLevelSetImageFilter), ITK_WRAP_GROUP(itkGeodesicActiveContourLevelSetImageFilter), ITK_WRAP_GROUP(itkShapeDetectionLevelSetImageFilter), ITK_WRAP_GROUP(itkCurvesLevelSetImageFilter), ITK_WRAP_GROUP(itkNarrowBandLevelSetImageFilter), ITK_WRAP_GROUP(itkNarrowBandCurvesLevelSetImageFilter), ITK_WRAP_GROUP(itkMattesMutualInformationImageToImageMetric), ITK_WRAP_GROUP(itkPDEDeformableRegistrationFilter), ITK_WRAP_GROUP(itkRecursiveMultiResolutionPyramidImageFilter), ITK_WRAP_GROUP(itkVoronoiSegmentationImageFilter), ITK_WRAP_GROUP(itkWatershedImageFilter), ITK_WRAP_GROUP(itkSegmentationLevelSetImageFilter), ITK_WRAP_GROUP(itkTreeNodeSO), ITK_WRAP_GROUP(itkSparseFieldLevelSetImageFilter) }; } #endif <|endoftext|>
<commit_before>/*********************************************************/ //SISTEMA DE ENSAYO DE CAJA Y CUBOS AUTOMATIZADO (ABBT)// //Luis Ángel García Astudillo// //Grado en Ingeniería en Tecnologías Industriales// //Universidad Carlos III de Madrid// /********************************************************/ #include "stdafx.h" #include <strsafe.h> #include "resource.h" #include "DepthBasics.h" #include <opencv2/opencv.hpp> using namespace cv; CDepthBasics::CDepthBasics() : m_fFreq(0), m_pKinectSensor(NULL), m_pDepthFrameReader(NULL) { LARGE_INTEGER qpf = {0}; if (QueryPerformanceFrequency(&qpf)){ m_fFreq = double(qpf.QuadPart); } } CDepthBasics::~CDepthBasics(){ SafeRelease(m_pDepthFrameReader); // done with depth frame reader if (m_pKinectSensor){ // close the Kinect Sensor m_pKinectSensor->Close(); } SafeRelease(m_pKinectSensor); } void CDepthBasics::update(Mat &m){ if (!m_pDepthFrameReader){ return; } IDepthFrame* pDepthFrame = NULL; HRESULT hr = m_pDepthFrameReader->AcquireLatestFrame(&pDepthFrame); if (SUCCEEDED(hr)){ imageCaptured = 1; INT64 nTime = 0; IFrameDescription* pFrameDescription = NULL; int nWidth = 0; int nHeight = 0; USHORT nDepthMinReliableDistance = 0; USHORT nDepthMaxDistance = 0; const UINT nBufferSize = cDepthHeight*cDepthWidth; UINT16 pBuffer[nBufferSize]; UINT16 depthB; hr = pDepthFrame->get_RelativeTime(&nTime); if (SUCCEEDED(hr)){ hr = pDepthFrame->get_FrameDescription(&pFrameDescription); } if (SUCCEEDED(hr)){ hr = pFrameDescription->get_Width(&nWidth); } if (SUCCEEDED(hr)){ hr = pFrameDescription->get_Height(&nHeight); } if (SUCCEEDED(hr)){ hr = pDepthFrame->get_DepthMinReliableDistance(&nDepthMinReliableDistance); } if (SUCCEEDED(hr)){ // In order to see the full range of depth (including the less reliable far field depth) // we are setting nDepthMaxDistance to the extreme potential depth threshold nDepthMaxDistance = USHRT_MAX; // Note: If you wish to filter by reliable depth distance, uncomment the following line. hr = pDepthFrame->get_DepthMaxReliableDistance(&nDepthMaxDistance); } if (SUCCEEDED(hr)){ hr = pDepthFrame->CopyFrameDataToArray(nBufferSize, pBuffer); if (SUCCEEDED(hr)) { for (UINT i = 0; i < nBufferSize; i++) { depthB = pBuffer[i]; m.at<UINT8>(i) = LOWORD(depthB); } } } SafeRelease(pFrameDescription); } else { imageCaptured = 0; } SafeRelease(pDepthFrame); } HRESULT CDepthBasics::initializeDefaultSensor(){ HRESULT hr; hr = GetDefaultKinectSensor(&m_pKinectSensor); if (FAILED(hr)){ return hr; } if (m_pKinectSensor){ // Initialize the Kinect and get the depth reader IDepthFrameSource* pDepthFrameSource = NULL; hr = m_pKinectSensor->Open(); if (SUCCEEDED(hr)){ hr = m_pKinectSensor->get_DepthFrameSource(&pDepthFrameSource); } if (SUCCEEDED(hr)){ hr = pDepthFrameSource->OpenReader(&m_pDepthFrameReader); } SafeRelease(pDepthFrameSource); } return hr; } <commit_msg>Delete DepthBasics.cpp<commit_after><|endoftext|>
<commit_before><commit_msg>Add support for serializing a FormData structure that has no elements. This is important for supporting cached form submissions of empty data, which occurs with some sites like Gmail.<commit_after><|endoftext|>
<commit_before>#include "cnn/conv.h" #include <sstream> #include <limits> #include <cmath> #include <stdexcept> #include "cnn/functors.h" #if HAVE_CUDA #include "cnn/cuda.h" #include "cnn/gpu-ops.h" #endif using namespace std; namespace cnn { string AddVectorToAllColumns::as_string(const vector<string>& arg_names) const { ostringstream os; os << "fold_rows(" << arg_names[0] << ", " << arg_names[1] << ')'; return os.str(); } Dim AddVectorToAllColumns::dim_forward(const vector<Dim>& xs) const { if (xs.size() != 2 || xs[0].rows() != xs[1].rows() || xs[0].ndims() != 2 || xs[1].ndims() != 1) { cerr << "Bad input dimensions in AddVectorToAllColumns: " << xs << endl; throw std::invalid_argument("bad input dimensions in AddVectorToAllColumns"); } return xs[0]; } void AddVectorToAllColumns::forward(const vector<const Tensor*>& xs, Tensor& fx) const { auto y = *fx; auto x = **xs[0]; auto b = **xs[1]; y = x.colwise() + b.col(0); } void AddVectorToAllColumns::backward(const vector<const Tensor*>& xs, const Tensor& fx, const Tensor& dEdf, unsigned i, Tensor& dEdxi) const { assert(i < 2); if (i == 0) { // x (*dEdxi) += (*dEdf); } else { // bias (*dEdxi).col(0) += (*dEdf).rowwise().sum(); } } string FoldRows::as_string(const vector<string>& arg_names) const { ostringstream os; os << "fold_rows(" << arg_names[0] << ", nrows=" << nrows << ')'; return os.str(); } Dim FoldRows::dim_forward(const vector<Dim>& xs) const { int orows = xs[0].rows() / nrows; if ((orows * nrows != xs[0].rows()) || xs.size() != 1 || xs[0].ndims() != 2) { cerr << "Bad input dimensions in FoldRows: " << xs << endl; throw std::invalid_argument("bad input dimensions in FoldRows"); } return Dim({orows, xs[0].cols()}); } void FoldRows::forward(const vector<const Tensor*>& xs, Tensor& fx) const { auto x = **xs[0]; auto y = *fx; int orows = y.rows(); for (int i = 0; i < orows; ++i) { for (unsigned j = 0; j < nrows; ++j) { if (j) y.row(i) += x.row(i * nrows + j); else // j = 0 y.row(i) = x.row(i * nrows); } } } void FoldRows::backward(const vector<const Tensor*>& xs, const Tensor& fx, const Tensor& dEdf, unsigned i, Tensor& dEdxi) const { int orows = fx.d.rows(); auto d = *dEdf; auto di = *dEdxi; for (int i = 0; i < orows; ++i) for (unsigned j = 0; j < nrows; ++j) di.row(i * nrows + j) += d.row(i); } string Conv1DNarrow::as_string(const vector<string>& arg_names) const { ostringstream os; os << "conv1d_narrow(" << arg_names[0] << ", f=" << arg_names[1] << ')'; return os.str(); } Dim Conv1DNarrow::dim_forward(const vector<Dim>& xs) const { if (xs.size() != 2) { cerr << "Conv1DNarrow requires two inputs: " << xs << endl; throw std::invalid_argument("Conv1DNarrow requires 2 dimensions"); } int ocols = xs[0].cols() - xs[1].cols() + 1; if (xs[0].ndims() != 2 || xs[1].ndims() != 2 || xs[0].rows() != xs[1].rows() || ocols < 1) { cerr << "Bad input dimensions in Conv1DNarrow: " << xs << endl; throw std::invalid_argument("bad input dimensions in Conv1DNarrow"); } return Dim({xs[0].rows(), ocols}); } void Conv1DNarrow::forward(const vector<const Tensor*>& xs, Tensor& fx) const { // TODO this is a bad implementation- rewrite to use unsupported Eigen tensor library auto x = **xs[0]; // input auto f = **xs[1]; // filter auto y = *fx; const unsigned rows = x.rows(); const unsigned ycols = dim.cols(); const unsigned fcols = f.cols(); for (unsigned i = 0; i < rows; ++i) { for (unsigned j = 0; j < ycols; ++j) { float t = 0; for (unsigned k = 0; k < fcols; ++k) t += f(i, k) * x(i, j + k); y(i, j) = t; } } } void Conv1DNarrow::backward(const vector<const Tensor*>& xs, const Tensor& fx, const Tensor& dEdf, unsigned i, Tensor& dEdxi) const { // TODO this is a bad implementation- rewrite to use unsupported Eigen tensor library assert(i < 2); const unsigned rows = xs[0]->d.rows(); const unsigned ycols = dim.cols(); const unsigned fcols = xs[1]->d.cols(); auto d = *dEdf; auto di = *dEdxi; if (i == 0) { // derivative wrt input x auto f = **xs[1]; for (unsigned i = 0; i < rows; ++i) { for (unsigned j = 0; j < ycols; ++j) { for (unsigned k = 0; k < fcols; ++k) di(i, j + k) += f(i, k) * d(i, j); } } } else { // derivative wrt filter f auto x = **xs[0]; for (unsigned i = 0; i < rows; ++i) { for (unsigned j = 0; j < ycols; ++j) { for (unsigned k = 0; k < fcols; ++k) di(i, k) += x(i, j + k) * d(i, j); } } } } string Conv1DWide::as_string(const vector<string>& arg_names) const { ostringstream os; os << "conv1d_wide(" << arg_names[0] << ", f=" << arg_names[1] << ')'; return os.str(); } Dim Conv1DWide::dim_forward(const vector<Dim>& xs) const { if (xs.size() != 2) { cerr << "Conv1DWide requires two inputs: " << xs << endl; throw std::invalid_argument("Conv1DWide requires two inputs"); } int ocols = xs[0].cols() + xs[1].cols() - 1; if (xs[0].ndims() != 2 || xs[1].ndims() != 2 || xs[0].rows() != xs[1].rows()) { cerr << "Bad input dimensions in Conv1DWide: " << xs << endl; throw std::invalid_argument("bad input dimensions in Conv1DWide"); } return Dim({xs[0].rows(), ocols}); } void Conv1DWide::forward(const vector<const Tensor*>& xs, Tensor& fx) const { TensorTools::Zero(fx); auto x = **xs[0]; // input auto f = **xs[1]; // filter auto y = *fx; const unsigned rows = x.rows(); const unsigned xcols = x.cols(); const unsigned fcols = f.cols(); for (unsigned i = 0; i < rows; ++i) { for (unsigned j = 0; j < xcols; ++j) { const float xij = x(i, j); for (unsigned k = 0; k < fcols; ++k) y(i, j + k) += f(i, k) * xij; } } } void Conv1DWide::backward(const vector<const Tensor*>& xs, const Tensor& fx, const Tensor& dEdf, unsigned i, Tensor& dEdxi) const { assert(i < 2); const unsigned rows = xs[0]->d.rows(); const unsigned xcols = xs[0]->d.cols(); const unsigned fcols = xs[1]->d.cols(); auto d = *dEdf; auto di = *dEdxi; if (i == 0) { // derivative wrt input x auto f = **xs[1]; for (unsigned i = 0; i < rows; ++i) { for (unsigned j = 0; j < xcols; ++j) { for (unsigned k = 0; k < fcols; ++k) di(i, j) += f(i, k) * d(i, j + k); } } } else { // derivative wrt filter f auto x = **xs[0]; for (unsigned i = 0; i < rows; ++i) { for (unsigned j = 0; j < xcols; ++j) { const float xij = x(i, j); for (unsigned k = 0; k < fcols; ++k) di(i, k) += xij * d(i, j + k); } } } } string KMaxPooling::as_string(const vector<string>& arg_names) const { ostringstream os; os << "kmaxpool(" << arg_names[0] << ", k=" << k << ')'; return os.str(); } Dim KMaxPooling::dim_forward(const vector<Dim>& xs) const { if (k < 1) { cerr << "Bad bad k in KMaxPooling: " << k << endl; throw std::invalid_argument("bad k in KMaxPooling"); } if (xs[0].ndims() != 2 || (xs[0].cols() < k)) { cerr << "Bad input dimensions in KMaxPooling: " << xs << endl; throw std::invalid_argument("bad input dimensions in KMaxPooling"); } return Dim({long(xs[0].rows()), long(k)}); } size_t KMaxPooling::aux_storage_size() const { // map of where the entries in f(x) go to entries in x return sizeof(int) * dim.size(); } void KMaxPooling::forward(const vector<const Tensor*>& xs, Tensor& fx) const { auto x=**xs[0]; auto y=*fx; float *tmp; tmp = new float[x.cols()]; int mi = 0; const unsigned rows = x.rows(); const unsigned xcols = x.cols(); int* maxmap = static_cast<int*>(aux_mem); for (unsigned i=0; i < rows; ++i) { //cerr << "row(" << i << ")=" << x.row(i) << endl; for (unsigned j=0; j < xcols; ++j) tmp[j] = -x(i,j); nth_element(tmp, tmp + (k-1), tmp + xcols); const float c = -tmp[k-1]; // kth largest element in row i int tt = 0; for (unsigned j = 0; j < xcols; ++j) { const float xij = x(i,j); if (xij >= c) { //cerr << xij << ' '; y(i,tt) = xij; //assert(mi < dim.size()); maxmap[mi++] = j; ++tt; if (tt == k) break; // could happen in case of ties } } //cerr << endl; abort(); } delete tmp; assert(mi == dim.size()); } void KMaxPooling::backward(const vector<const Tensor*>& xs, const Tensor& fx, const Tensor& dEdf, unsigned i, Tensor& dEdxi) const { const unsigned rows = dim.rows(); const unsigned cols = dim.cols(); const int* maxmap = static_cast<const int*>(aux_mem); for (unsigned i = 0; i < rows; ++i) { int mi = 0; for (unsigned j = 0; j < cols; ++j) { assert(mi < dim.size()); const int oj = maxmap[mi++]; if (oj > (*dEdxi).cols() || oj < 0) { cerr << dim << (*fx) << endl << (*dEdxi) << endl; cerr << "MM:"; for (int k=0;k < dim.size(); ++k) cerr << ' ' << maxmap[k]; cerr << endl; cerr << "BAD: " << oj << endl; abort(); } (*dEdxi)(i, oj) += (*dEdf)(i, j); } } } } // namespace cnn <commit_msg>use shared pointer to new pointer<commit_after>#include "cnn/conv.h" #include <sstream> #include <limits> #include <cmath> #include <stdexcept> #include <boost/shared_ptr.hpp> #include "cnn/functors.h" #if HAVE_CUDA #include "cnn/cuda.h" #include "cnn/gpu-ops.h" #endif using namespace std; namespace cnn { string AddVectorToAllColumns::as_string(const vector<string>& arg_names) const { ostringstream os; os << "fold_rows(" << arg_names[0] << ", " << arg_names[1] << ')'; return os.str(); } Dim AddVectorToAllColumns::dim_forward(const vector<Dim>& xs) const { if (xs.size() != 2 || xs[0].rows() != xs[1].rows() || xs[0].ndims() != 2 || xs[1].ndims() != 1) { cerr << "Bad input dimensions in AddVectorToAllColumns: " << xs << endl; throw std::invalid_argument("bad input dimensions in AddVectorToAllColumns"); } return xs[0]; } void AddVectorToAllColumns::forward(const vector<const Tensor*>& xs, Tensor& fx) const { auto y = *fx; auto x = **xs[0]; auto b = **xs[1]; y = x.colwise() + b.col(0); } void AddVectorToAllColumns::backward(const vector<const Tensor*>& xs, const Tensor& fx, const Tensor& dEdf, unsigned i, Tensor& dEdxi) const { assert(i < 2); if (i == 0) { // x (*dEdxi) += (*dEdf); } else { // bias (*dEdxi).col(0) += (*dEdf).rowwise().sum(); } } string FoldRows::as_string(const vector<string>& arg_names) const { ostringstream os; os << "fold_rows(" << arg_names[0] << ", nrows=" << nrows << ')'; return os.str(); } Dim FoldRows::dim_forward(const vector<Dim>& xs) const { int orows = xs[0].rows() / nrows; if ((orows * nrows != xs[0].rows()) || xs.size() != 1 || xs[0].ndims() != 2) { cerr << "Bad input dimensions in FoldRows: " << xs << endl; throw std::invalid_argument("bad input dimensions in FoldRows"); } return Dim({orows, xs[0].cols()}); } void FoldRows::forward(const vector<const Tensor*>& xs, Tensor& fx) const { auto x = **xs[0]; auto y = *fx; int orows = y.rows(); for (int i = 0; i < orows; ++i) { for (unsigned j = 0; j < nrows; ++j) { if (j) y.row(i) += x.row(i * nrows + j); else // j = 0 y.row(i) = x.row(i * nrows); } } } void FoldRows::backward(const vector<const Tensor*>& xs, const Tensor& fx, const Tensor& dEdf, unsigned i, Tensor& dEdxi) const { int orows = fx.d.rows(); auto d = *dEdf; auto di = *dEdxi; for (int i = 0; i < orows; ++i) for (unsigned j = 0; j < nrows; ++j) di.row(i * nrows + j) += d.row(i); } string Conv1DNarrow::as_string(const vector<string>& arg_names) const { ostringstream os; os << "conv1d_narrow(" << arg_names[0] << ", f=" << arg_names[1] << ')'; return os.str(); } Dim Conv1DNarrow::dim_forward(const vector<Dim>& xs) const { if (xs.size() != 2) { cerr << "Conv1DNarrow requires two inputs: " << xs << endl; throw std::invalid_argument("Conv1DNarrow requires 2 dimensions"); } int ocols = xs[0].cols() - xs[1].cols() + 1; if (xs[0].ndims() != 2 || xs[1].ndims() != 2 || xs[0].rows() != xs[1].rows() || ocols < 1) { cerr << "Bad input dimensions in Conv1DNarrow: " << xs << endl; throw std::invalid_argument("bad input dimensions in Conv1DNarrow"); } return Dim({xs[0].rows(), ocols}); } void Conv1DNarrow::forward(const vector<const Tensor*>& xs, Tensor& fx) const { // TODO this is a bad implementation- rewrite to use unsupported Eigen tensor library auto x = **xs[0]; // input auto f = **xs[1]; // filter auto y = *fx; const unsigned rows = x.rows(); const unsigned ycols = dim.cols(); const unsigned fcols = f.cols(); for (unsigned i = 0; i < rows; ++i) { for (unsigned j = 0; j < ycols; ++j) { float t = 0; for (unsigned k = 0; k < fcols; ++k) t += f(i, k) * x(i, j + k); y(i, j) = t; } } } void Conv1DNarrow::backward(const vector<const Tensor*>& xs, const Tensor& fx, const Tensor& dEdf, unsigned i, Tensor& dEdxi) const { // TODO this is a bad implementation- rewrite to use unsupported Eigen tensor library assert(i < 2); const unsigned rows = xs[0]->d.rows(); const unsigned ycols = dim.cols(); const unsigned fcols = xs[1]->d.cols(); auto d = *dEdf; auto di = *dEdxi; if (i == 0) { // derivative wrt input x auto f = **xs[1]; for (unsigned i = 0; i < rows; ++i) { for (unsigned j = 0; j < ycols; ++j) { for (unsigned k = 0; k < fcols; ++k) di(i, j + k) += f(i, k) * d(i, j); } } } else { // derivative wrt filter f auto x = **xs[0]; for (unsigned i = 0; i < rows; ++i) { for (unsigned j = 0; j < ycols; ++j) { for (unsigned k = 0; k < fcols; ++k) di(i, k) += x(i, j + k) * d(i, j); } } } } string Conv1DWide::as_string(const vector<string>& arg_names) const { ostringstream os; os << "conv1d_wide(" << arg_names[0] << ", f=" << arg_names[1] << ')'; return os.str(); } Dim Conv1DWide::dim_forward(const vector<Dim>& xs) const { if (xs.size() != 2) { cerr << "Conv1DWide requires two inputs: " << xs << endl; throw std::invalid_argument("Conv1DWide requires two inputs"); } int ocols = xs[0].cols() + xs[1].cols() - 1; if (xs[0].ndims() != 2 || xs[1].ndims() != 2 || xs[0].rows() != xs[1].rows()) { cerr << "Bad input dimensions in Conv1DWide: " << xs << endl; throw std::invalid_argument("bad input dimensions in Conv1DWide"); } return Dim({xs[0].rows(), ocols}); } void Conv1DWide::forward(const vector<const Tensor*>& xs, Tensor& fx) const { TensorTools::Zero(fx); auto x = **xs[0]; // input auto f = **xs[1]; // filter auto y = *fx; const unsigned rows = x.rows(); const unsigned xcols = x.cols(); const unsigned fcols = f.cols(); for (unsigned i = 0; i < rows; ++i) { for (unsigned j = 0; j < xcols; ++j) { const float xij = x(i, j); for (unsigned k = 0; k < fcols; ++k) y(i, j + k) += f(i, k) * xij; } } } void Conv1DWide::backward(const vector<const Tensor*>& xs, const Tensor& fx, const Tensor& dEdf, unsigned i, Tensor& dEdxi) const { assert(i < 2); const unsigned rows = xs[0]->d.rows(); const unsigned xcols = xs[0]->d.cols(); const unsigned fcols = xs[1]->d.cols(); auto d = *dEdf; auto di = *dEdxi; if (i == 0) { // derivative wrt input x auto f = **xs[1]; for (unsigned i = 0; i < rows; ++i) { for (unsigned j = 0; j < xcols; ++j) { for (unsigned k = 0; k < fcols; ++k) di(i, j) += f(i, k) * d(i, j + k); } } } else { // derivative wrt filter f auto x = **xs[0]; for (unsigned i = 0; i < rows; ++i) { for (unsigned j = 0; j < xcols; ++j) { const float xij = x(i, j); for (unsigned k = 0; k < fcols; ++k) di(i, k) += xij * d(i, j + k); } } } } string KMaxPooling::as_string(const vector<string>& arg_names) const { ostringstream os; os << "kmaxpool(" << arg_names[0] << ", k=" << k << ')'; return os.str(); } Dim KMaxPooling::dim_forward(const vector<Dim>& xs) const { if (k < 1) { cerr << "Bad bad k in KMaxPooling: " << k << endl; throw std::invalid_argument("bad k in KMaxPooling"); } if (xs[0].ndims() != 2 || (xs[0].cols() < k)) { cerr << "Bad input dimensions in KMaxPooling: " << xs << endl; throw std::invalid_argument("bad input dimensions in KMaxPooling"); } return Dim({long(xs[0].rows()), long(k)}); } size_t KMaxPooling::aux_storage_size() const { // map of where the entries in f(x) go to entries in x return sizeof(int) * dim.size(); } void KMaxPooling::forward(const vector<const Tensor*>& xs, Tensor& fx) const { auto x=**xs[0]; auto y=*fx; boost::shared_ptr<float> shared_tmp(new float[x.cols()]); float * tmp = shared_tmp.get(); int mi = 0; const unsigned rows = x.rows(); const unsigned xcols = x.cols(); int* maxmap = static_cast<int*>(aux_mem); for (unsigned i=0; i < rows; ++i) { //cerr << "row(" << i << ")=" << x.row(i) << endl; for (unsigned j=0; j < xcols; ++j) tmp[j] = -x(i,j); nth_element(tmp, tmp + (k-1), tmp + xcols); const float c = -tmp[k-1]; // kth largest element in row i int tt = 0; for (unsigned j = 0; j < xcols; ++j) { const float xij = x(i,j); if (xij >= c) { //cerr << xij << ' '; y(i,tt) = xij; //assert(mi < dim.size()); maxmap[mi++] = j; ++tt; if (tt == k) break; // could happen in case of ties } } //cerr << endl; abort(); } assert(mi == dim.size()); } void KMaxPooling::backward(const vector<const Tensor*>& xs, const Tensor& fx, const Tensor& dEdf, unsigned i, Tensor& dEdxi) const { const unsigned rows = dim.rows(); const unsigned cols = dim.cols(); const int* maxmap = static_cast<const int*>(aux_mem); for (unsigned i = 0; i < rows; ++i) { int mi = 0; for (unsigned j = 0; j < cols; ++j) { assert(mi < dim.size()); const int oj = maxmap[mi++]; if (oj > (*dEdxi).cols() || oj < 0) { cerr << dim << (*fx) << endl << (*dEdxi) << endl; cerr << "MM:"; for (int k=0;k < dim.size(); ++k) cerr << ' ' << maxmap[k]; cerr << endl; cerr << "BAD: " << oj << endl; abort(); } (*dEdxi)(i, oj) += (*dEdf)(i, j); } } } } // namespace cnn <|endoftext|>
<commit_before>#include <iostream> #include "cnn/cnn.h" #include "cnn/cuda.h" #include <cudnn.h> #include <curand.h> #pragma comment(lib,"cublas.lib") #pragma comment(lib,"cudart_static.lib") /// need to include library C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\lib\x64 that has cublas.lib to project #pragma comment(lib, "cudnn.lib") using namespace std; namespace cnn { cublasHandle_t cublas_handle; cudnnHandle_t cudnn_handle; cudnnDataType_t cudnnDataType; curandGenerator_t curndGeneratorHandle; void Initialize_CUDNN() { cudnn_handle = nullptr; if (sizeof(cnn::real) == sizeof(float) ) cudnnDataType = CUDNN_DATA_FLOAT; else if (sizeof(cnn::real) == sizeof(double)) cudnnDataType = CUDNN_DATA_DOUBLE; else throw std::runtime_error("not supported data type"); CHECK_CUDNN(cudnnCreate(&cudnn_handle)); } void Initialize_Consts_And_Store_In_GPU() { kSCALAR_ONE_OVER_INT.resize(MEM_PRE_ALLOCATED_CONSTS_NUMBERS); for (int i = 0; i < MEM_PRE_ALLOCATED_CONSTS_NUMBERS; i++) { cnn::real flt = 1./(i+2); cnn::real *flt_val; CUDA_CHECK(cudaMalloc(&flt_val, sizeof(cnn::real))); CUDA_CHECK(cudaMemcpyAsync(flt_val, &flt, sizeof(cnn::real), cudaMemcpyHostToDevice)); kSCALAR_ONE_OVER_INT[i] = flt_val; } } void Free_GPU() { #ifdef HAVE_CUDA CHECK_CUDNN(cudnnDestroy(cudnn_handle)); CUBLAS_CHECK(cublasDestroy(cublas_handle)); CHECK_CURND(curandDestroyGenerator(curndGeneratorHandle)); #endif } void Initialize_GPU(int& argc, char**& argv, unsigned random_seed, int prefered_device_id) { int nDevices; CUDA_CHECK(cudaGetDeviceCount(&nDevices)); if (nDevices < 1) { cerr << "[cnn] No GPUs found, recompile without DENABLE_CUDA=1\n"; throw std::runtime_error("No GPUs found but CNN compiled with CUDA support."); } size_t free_bytes, total_bytes, max_free = 0; int selected = 0; int i = 0; if (prefered_device_id < 0) i = 0; else{ /// only use a particular GPU i = prefered_device_id; } for (; i < nDevices; i++) { cudaDeviceProp prop; CUDA_CHECK(cudaSetDevice(i)); CUDA_CHECK(cudaGetDeviceProperties(&prop, i)); cerr << "[cnn] Device Number: " << i << endl; cerr << "[cnn] Device name: " << prop.name << endl; cerr << "[cnn] Memory Clock Rate (KHz): " << prop.memoryClockRate << endl; cerr << "[cnn] Memory Bus Width (bits): " << prop.memoryBusWidth << endl; cerr << "[cnn] Unified Addressing : " << prop.unifiedAddressing << endl; cerr << "[cnn] Peak Memory Bandwidth (GB/s): " << (2.0*prop.memoryClockRate*(prop.memoryBusWidth / 8) / 1.0e6) << endl << endl; CUDA_CHECK(cudaMemGetInfo( &free_bytes, &total_bytes )); CUDA_CHECK(cudaDeviceReset()); cerr << "[cnn] Memory Free (MB): " << (int)free_bytes/1.0e6 << "/" << (int)total_bytes/1.0e6 << endl << endl; if(free_bytes > max_free) { max_free = free_bytes; selected = i; } if (prefered_device_id >= 0) break; } cerr << "[cnn] **USING DEVICE: " << selected << endl; CUDA_CHECK(cudaSetDevice(selected)); device_id = selected; CUBLAS_CHECK(cublasCreate(&cublas_handle)); CUBLAS_CHECK(cublasSetPointerMode(cublas_handle, CUBLAS_POINTER_MODE_DEVICE)); CUDA_CHECK(cudaMalloc(&kSCALAR_MINUSONE, sizeof(cnn::real))); CUDA_CHECK(cudaMalloc(&kSCALAR_ONE, sizeof(cnn::real))); CUDA_CHECK(cudaMalloc(&kSCALAR_ZERO, sizeof(cnn::real))); cnn::real minusone = -1; CUDA_CHECK(cudaMemcpyAsync(kSCALAR_MINUSONE, &minusone, sizeof(cnn::real), cudaMemcpyHostToDevice)); cnn::real one = 1; CUDA_CHECK(cudaMemcpyAsync(kSCALAR_ONE, &one, sizeof(cnn::real), cudaMemcpyHostToDevice)); cnn::real zero = 0; CUDA_CHECK(cudaMemcpyAsync(kSCALAR_ZERO, &zero, sizeof(cnn::real), cudaMemcpyHostToDevice)); Initialize_Consts_And_Store_In_GPU(); Initialize_CUDNN(); /// initialize curnd CHECK_CURND(curandCreateGenerator(&curndGeneratorHandle, CURAND_RNG_PSEUDO_MT19937)); CHECK_CURND(curandSetPseudoRandomGeneratorSeed(curndGeneratorHandle, random_seed)); } } // namespace cnn <commit_msg>have a global pinned memory, dellocate<commit_after>#include <iostream> #include "cnn/cnn.h" #include "cnn/cuda.h" #include <cudnn.h> #include <curand.h> #pragma comment(lib,"cublas.lib") #pragma comment(lib,"cudart_static.lib") /// need to include library C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\lib\x64 that has cublas.lib to project #pragma comment(lib, "cudnn.lib") using namespace std; namespace cnn { cublasHandle_t cublas_handle; cudnnHandle_t cudnn_handle; cudnnDataType_t cudnnDataType; curandGenerator_t curndGeneratorHandle; extern cnn::real* glb_gpu_accessible_host_mem; void Initialize_CUDNN() { cudnn_handle = nullptr; if (sizeof(cnn::real) == sizeof(float) ) cudnnDataType = CUDNN_DATA_FLOAT; else if (sizeof(cnn::real) == sizeof(double)) cudnnDataType = CUDNN_DATA_DOUBLE; else throw std::runtime_error("not supported data type"); CHECK_CUDNN(cudnnCreate(&cudnn_handle)); } void Initialize_Consts_And_Store_In_GPU() { kSCALAR_ONE_OVER_INT.resize(MEM_PRE_ALLOCATED_CONSTS_NUMBERS); for (int i = 0; i < MEM_PRE_ALLOCATED_CONSTS_NUMBERS; i++) { cnn::real flt = 1./(i+2); cnn::real *flt_val; CUDA_CHECK(cudaMalloc(&flt_val, sizeof(cnn::real))); CUDA_CHECK(cudaMemcpyAsync(flt_val, &flt, sizeof(cnn::real), cudaMemcpyHostToDevice)); kSCALAR_ONE_OVER_INT[i] = flt_val; } } void Free_GPU() { #ifdef HAVE_CUDA CHECK_CUDNN(cudnnDestroy(cudnn_handle)); CUBLAS_CHECK(cublasDestroy(cublas_handle)); CHECK_CURND(curandDestroyGenerator(curndGeneratorHandle)); if (glb_gpu_accessible_host_mem != nullptr) CUDA_CHECK(cudaFreeHost(glb_gpu_accessible_host_mem)); #endif } void Initialize_GPU(int& argc, char**& argv, unsigned random_seed, int prefered_device_id) { int nDevices; CUDA_CHECK(cudaGetDeviceCount(&nDevices)); if (nDevices < 1) { cerr << "[cnn] No GPUs found, recompile without DENABLE_CUDA=1\n"; throw std::runtime_error("No GPUs found but CNN compiled with CUDA support."); } size_t free_bytes, total_bytes, max_free = 0; int selected = 0; int i = 0; if (prefered_device_id < 0) i = 0; else{ /// only use a particular GPU i = prefered_device_id; } for (; i < nDevices; i++) { cudaDeviceProp prop; CUDA_CHECK(cudaSetDevice(i)); CUDA_CHECK(cudaGetDeviceProperties(&prop, i)); cerr << "[cnn] Device Number: " << i << endl; cerr << "[cnn] Device name: " << prop.name << endl; cerr << "[cnn] Memory Clock Rate (KHz): " << prop.memoryClockRate << endl; cerr << "[cnn] Memory Bus Width (bits): " << prop.memoryBusWidth << endl; cerr << "[cnn] Unified Addressing : " << prop.unifiedAddressing << endl; cerr << "[cnn] Peak Memory Bandwidth (GB/s): " << (2.0*prop.memoryClockRate*(prop.memoryBusWidth / 8) / 1.0e6) << endl << endl; CUDA_CHECK(cudaMemGetInfo( &free_bytes, &total_bytes )); CUDA_CHECK(cudaDeviceReset()); cerr << "[cnn] Memory Free (MB): " << (int)free_bytes/1.0e6 << "/" << (int)total_bytes/1.0e6 << endl << endl; if(free_bytes > max_free) { max_free = free_bytes; selected = i; } if (prefered_device_id >= 0) break; } cerr << "[cnn] **USING DEVICE: " << selected << endl; CUDA_CHECK(cudaSetDevice(selected)); device_id = selected; CUBLAS_CHECK(cublasCreate(&cublas_handle)); CUBLAS_CHECK(cublasSetPointerMode(cublas_handle, CUBLAS_POINTER_MODE_DEVICE)); CUDA_CHECK(cudaMalloc(&kSCALAR_MINUSONE, sizeof(cnn::real))); CUDA_CHECK(cudaMalloc(&kSCALAR_ONE, sizeof(cnn::real))); CUDA_CHECK(cudaMalloc(&kSCALAR_ZERO, sizeof(cnn::real))); cnn::real minusone = -1; CUDA_CHECK(cudaMemcpyAsync(kSCALAR_MINUSONE, &minusone, sizeof(cnn::real), cudaMemcpyHostToDevice)); cnn::real one = 1; CUDA_CHECK(cudaMemcpyAsync(kSCALAR_ONE, &one, sizeof(cnn::real), cudaMemcpyHostToDevice)); cnn::real zero = 0; CUDA_CHECK(cudaMemcpyAsync(kSCALAR_ZERO, &zero, sizeof(cnn::real), cudaMemcpyHostToDevice)); Initialize_Consts_And_Store_In_GPU(); Initialize_CUDNN(); /// initialize curnd CHECK_CURND(curandCreateGenerator(&curndGeneratorHandle, CURAND_RNG_PSEUDO_MT19937)); CHECK_CURND(curandSetPseudoRandomGeneratorSeed(curndGeneratorHandle, random_seed)); } } // namespace cnn <|endoftext|>
<commit_before>#include "cnn/init.h" #include "cnn/aligned-mem-pool.h" #include "cnn/cnn.h" #include <iostream> #include <random> #include <cmath> #if HAVE_CUDA #include "cnn/cuda.h" #include <device_launch_parameters.h> #endif using namespace std; namespace cnn { const unsigned ALIGN = 6; AlignedMemoryPool<ALIGN>* fxs = nullptr; AlignedMemoryPool<ALIGN>* dEdfs = nullptr; AlignedMemoryPool<ALIGN>* ps = nullptr; mt19937* rndeng = nullptr; static void RemoveArgs(int& argc, char**& argv, int& argi, int n) { for (int i = argi + n; i < argc; ++i) argv[i - n] = argv[i]; argc -= n; assert(argc >= 0); } void Initialize(int& argc, char**& argv, unsigned random_seed, bool shared_parameters) { #if HAVE_CUDA cerr << "[cnn] using GPU\n"; Initialize_GPU(argc, argv); #else cerr << "[cnn] using CPU\n"; kSCALAR_MINUSONE = (float*) cnn_mm_malloc(sizeof(float), 256); *kSCALAR_MINUSONE = -1; kSCALAR_ONE = (float*) cnn_mm_malloc(sizeof(float), 256); *kSCALAR_ONE = 1; kSCALAR_ZERO = (float*) cnn_mm_malloc(sizeof(float), 256); *kSCALAR_ZERO = 0; #endif unsigned long num_mb = 512UL; int argi = 1; while(argi < argc) { string arg = argv[argi]; if (arg == "--cnn-mem") { if ((argi + 1) > argc) { cerr << "[cnn] --cnn-mem expects an argument (the memory, in megabytes, to reserve)\n"; abort(); } else { string a2 = argv[argi+1]; istringstream c(a2); c >> num_mb; RemoveArgs(argc, argv, argi, 2); } } else if (arg == "--cnn-seed") { if ((argi + 1) > argc) { cerr << "[cnn] --cnn-seed expects an argument (the random number seed)\n"; abort(); } else { string a2 = argv[argi+1]; istringstream c(a2); c >> random_seed; RemoveArgs(argc, argv, argi, 2); } } else if (arg.find("--cnn") == 0) { cerr << "[cnn] Bad command line argument: " << arg << endl; abort(); } else { break; } } if (random_seed == 0) { random_device rd; random_seed = rd(); } cerr << "[cnn] random seed: " << random_seed << endl; rndeng = new mt19937(random_seed); cerr << "[cnn] allocating memory: " << num_mb << "MB\n"; fxs = new AlignedMemoryPool<ALIGN>(num_mb << 20); // node values dEdfs = new AlignedMemoryPool<ALIGN>(num_mb << 20); // node gradients ps = new AlignedMemoryPool<ALIGN>(num_mb << 20, shared_parameters); // parameters cerr << "[cnn] memory allocation done.\n"; } void Cleanup() { delete rndeng; delete fxs; delete dEdfs; delete ps; } } // namespace cnn <commit_msg>In options, allow for hyphen or underbar<commit_after>#include "cnn/init.h" #include "cnn/aligned-mem-pool.h" #include "cnn/cnn.h" #include <iostream> #include <random> #include <cmath> #if HAVE_CUDA #include "cnn/cuda.h" #include <device_launch_parameters.h> #endif using namespace std; namespace cnn { const unsigned ALIGN = 6; AlignedMemoryPool<ALIGN>* fxs = nullptr; AlignedMemoryPool<ALIGN>* dEdfs = nullptr; AlignedMemoryPool<ALIGN>* ps = nullptr; mt19937* rndeng = nullptr; static void RemoveArgs(int& argc, char**& argv, int& argi, int n) { for (int i = argi + n; i < argc; ++i) argv[i - n] = argv[i]; argc -= n; assert(argc >= 0); } void Initialize(int& argc, char**& argv, unsigned random_seed, bool shared_parameters) { #if HAVE_CUDA cerr << "[cnn] using GPU\n"; Initialize_GPU(argc, argv); #else cerr << "[cnn] using CPU\n"; kSCALAR_MINUSONE = (float*) cnn_mm_malloc(sizeof(float), 256); *kSCALAR_MINUSONE = -1; kSCALAR_ONE = (float*) cnn_mm_malloc(sizeof(float), 256); *kSCALAR_ONE = 1; kSCALAR_ZERO = (float*) cnn_mm_malloc(sizeof(float), 256); *kSCALAR_ZERO = 0; #endif unsigned long num_mb = 512UL; int argi = 1; while(argi < argc) { string arg = argv[argi]; if (arg == "--cnn-mem" || arg == "--cnn_mem") { if ((argi + 1) > argc) { cerr << "[cnn] --cnn-mem expects an argument (the memory, in megabytes, to reserve)\n"; abort(); } else { string a2 = argv[argi+1]; istringstream c(a2); c >> num_mb; RemoveArgs(argc, argv, argi, 2); } } else if (arg == "--cnn-seed" || arg == "--cnn_seed") { if ((argi + 1) > argc) { cerr << "[cnn] --cnn-seed expects an argument (the random number seed)\n"; abort(); } else { string a2 = argv[argi+1]; istringstream c(a2); c >> random_seed; RemoveArgs(argc, argv, argi, 2); } } else if (arg.find("--cnn") == 0) { cerr << "[cnn] Bad command line argument: " << arg << endl; abort(); } else { break; } } if (random_seed == 0) { random_device rd; random_seed = rd(); } cerr << "[cnn] random seed: " << random_seed << endl; rndeng = new mt19937(random_seed); cerr << "[cnn] allocating memory: " << num_mb << "MB\n"; fxs = new AlignedMemoryPool<ALIGN>(num_mb << 20); // node values dEdfs = new AlignedMemoryPool<ALIGN>(num_mb << 20); // node gradients ps = new AlignedMemoryPool<ALIGN>(num_mb << 20, shared_parameters); // parameters cerr << "[cnn] memory allocation done.\n"; } void Cleanup() { delete rndeng; delete fxs; delete dEdfs; delete ps; } } // namespace cnn <|endoftext|>
<commit_before>//===- Symbols.cpp --------------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Symbols.h" #include "Chunks.h" #include "Error.h" #include "InputFiles.h" #include "llvm/ADT/STLExtras.h" using namespace llvm; using namespace llvm::object; using namespace llvm::ELF; using namespace lld; using namespace lld::elf2; static uint8_t getMinVisibility(uint8_t VA, uint8_t VB) { if (VA == STV_DEFAULT) return VB; if (VB == STV_DEFAULT) return VA; return std::min(VA, VB); } // Returns 1, 0 or -1 if this symbol should take precedence // over the Other, tie or lose, respectively. template <class ELFT> int SymbolBody::compare(SymbolBody *Other) { assert(!isLazy() && !Other->isLazy()); std::pair<bool, bool> L(isDefined(), !isWeak()); std::pair<bool, bool> R(Other->isDefined(), !Other->isWeak()); // Normalize if (L > R) return -Other->compare<ELFT>(this); uint8_t LV = getMostConstrainingVisibility(); uint8_t RV = Other->getMostConstrainingVisibility(); MostConstrainingVisibility = getMinVisibility(LV, RV); Other->MostConstrainingVisibility = MostConstrainingVisibility; IsUsedInRegularObj |= Other->IsUsedInRegularObj; Other->IsUsedInRegularObj |= IsUsedInRegularObj; if (L != R) return -1; if (L.first && L.second) { if (isCommon()) { if (Other->isCommon()) { auto *ThisC = cast<DefinedCommon<ELFT>>(this); auto *OtherC = cast<DefinedCommon<ELFT>>(Other); typename DefinedCommon<ELFT>::uintX_t MaxAlign = std::max(ThisC->MaxAlignment, OtherC->MaxAlignment); if (ThisC->Sym.st_size >= OtherC->Sym.st_size) { ThisC->MaxAlignment = MaxAlign; return 1; } OtherC->MaxAlignment = MaxAlign; return -1; } return -1; } if (Other->isCommon()) return 1; return 0; } return 1; } std::unique_ptr<InputFile> Lazy::getMember() { MemoryBufferRef MBRef = File->getMember(&Sym); // getMember returns an empty buffer if the member was already // read from the library. if (MBRef.getBuffer().empty()) return std::unique_ptr<InputFile>(nullptr); return createELFFile<ObjectFile>(MBRef); } template int SymbolBody::compare<ELF32LE>(SymbolBody *Other); template int SymbolBody::compare<ELF32BE>(SymbolBody *Other); template int SymbolBody::compare<ELF64LE>(SymbolBody *Other); template int SymbolBody::compare<ELF64BE>(SymbolBody *Other); <commit_msg>ELF2: Return early. NFC.<commit_after>//===- Symbols.cpp --------------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Symbols.h" #include "Chunks.h" #include "Error.h" #include "InputFiles.h" #include "llvm/ADT/STLExtras.h" using namespace llvm; using namespace llvm::object; using namespace llvm::ELF; using namespace lld; using namespace lld::elf2; static uint8_t getMinVisibility(uint8_t VA, uint8_t VB) { if (VA == STV_DEFAULT) return VB; if (VB == STV_DEFAULT) return VA; return std::min(VA, VB); } // Returns 1, 0 or -1 if this symbol should take precedence // over the Other, tie or lose, respectively. template <class ELFT> int SymbolBody::compare(SymbolBody *Other) { assert(!isLazy() && !Other->isLazy()); std::pair<bool, bool> L(isDefined(), !isWeak()); std::pair<bool, bool> R(Other->isDefined(), !Other->isWeak()); // Normalize if (L > R) return -Other->compare<ELFT>(this); uint8_t LV = getMostConstrainingVisibility(); uint8_t RV = Other->getMostConstrainingVisibility(); MostConstrainingVisibility = getMinVisibility(LV, RV); Other->MostConstrainingVisibility = MostConstrainingVisibility; IsUsedInRegularObj |= Other->IsUsedInRegularObj; Other->IsUsedInRegularObj |= IsUsedInRegularObj; if (L != R) return -1; if (!L.first || !L.second) return 1; if (isCommon()) { if (Other->isCommon()) { auto *ThisC = cast<DefinedCommon<ELFT>>(this); auto *OtherC = cast<DefinedCommon<ELFT>>(Other); typename DefinedCommon<ELFT>::uintX_t MaxAlign = std::max(ThisC->MaxAlignment, OtherC->MaxAlignment); if (ThisC->Sym.st_size >= OtherC->Sym.st_size) { ThisC->MaxAlignment = MaxAlign; return 1; } OtherC->MaxAlignment = MaxAlign; return -1; } return -1; } if (Other->isCommon()) return 1; return 0; } std::unique_ptr<InputFile> Lazy::getMember() { MemoryBufferRef MBRef = File->getMember(&Sym); // getMember returns an empty buffer if the member was already // read from the library. if (MBRef.getBuffer().empty()) return std::unique_ptr<InputFile>(nullptr); return createELFFile<ObjectFile>(MBRef); } template int SymbolBody::compare<ELF32LE>(SymbolBody *Other); template int SymbolBody::compare<ELF32BE>(SymbolBody *Other); template int SymbolBody::compare<ELF64LE>(SymbolBody *Other); template int SymbolBody::compare<ELF64BE>(SymbolBody *Other); <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <mixpanel/mixpanel.hpp> #include <mixpanel/detail/worker.hpp> #include "../../source/dependencies/nano/include/nanowww/nanowww.h" #include "test_config.hpp" // // Ensure "Retry-After" HTTP header is respected // TEST(MixpanelNetwork, RetryAfter) { mixpanel::Mixpanel mp(mp_token); mixpanel::detail::Worker worker(&mp); nanowww::Response retry_after_response; retry_after_response.push_header("Retry-After", "51"); auto retry_after_time = worker.parse_www_retry_after(retry_after_response); auto back_off_duration = retry_after_time - time(0); ASSERT_EQ(back_off_duration, 51); } // // Ensure successive failures result in an exponential back // off time. // TEST(MixpanelNetwork, BackOffTime) { mixpanel::Mixpanel mp(mp_token); mixpanel::detail::Worker worker(&mp); nanowww::Response failure_response; failure_response.set_status(503); // We need 2 consecutive failures to enable exponential back off worker.parse_www_retry_after(failure_response); auto retry_after_time = worker.parse_www_retry_after(failure_response); auto back_off_duration = retry_after_time - time(0); // Should back off randomly between 120 - 150s ASSERT_GT(back_off_duration, 115); ASSERT_LE(back_off_duration, 150); // Test a third failure retry_after_time = worker.parse_www_retry_after(failure_response); back_off_duration = retry_after_time - time(0); // Should back off randomly between 240 - 270s ASSERT_GT(back_off_duration, 235); ASSERT_LE(back_off_duration, 270); } // // A single success after a number of failures should reset the back off time. // TEST(MixpanelNetwork, FailureRecovery) { mixpanel::Mixpanel mp(mp_token); mixpanel::detail::Worker worker(&mp); nanowww::Response failure_response; failure_response.set_status(503); // We need 2 consecutive failures to enable exponential back off worker.parse_www_retry_after(failure_response); worker.parse_www_retry_after(failure_response); // Followed by 1 success to reset the back off nanowww::Response success_response; success_response.set_status(200); auto retry_after_time = worker.parse_www_retry_after(success_response); auto back_off_duration = retry_after_time - time(0); // Back off time should be reset ASSERT_EQ(back_off_duration, 0); } <commit_msg>Add failure_count assertions to unit tests.<commit_after>#include <gtest/gtest.h> #include <mixpanel/mixpanel.hpp> #include <mixpanel/detail/worker.hpp> #include "../../source/dependencies/nano/include/nanowww/nanowww.h" #include "test_config.hpp" // // Ensure "Retry-After" HTTP header is respected // TEST(MixpanelNetwork, RetryAfter) { mixpanel::Mixpanel mp(mp_token); mixpanel::detail::Worker worker(&mp); nanowww::Response retry_after_response; retry_after_response.push_header("Retry-After", "51"); auto retry_after_time = worker.parse_www_retry_after(retry_after_response); auto back_off_duration = retry_after_time - time(0); ASSERT_EQ(back_off_duration, 51); ASSERT_EQ(worker.failure_count, 0); } // // Ensure successive failures result in an exponential back // off time. // TEST(MixpanelNetwork, BackOffTime) { mixpanel::Mixpanel mp(mp_token); mixpanel::detail::Worker worker(&mp); nanowww::Response failure_response; failure_response.set_status(503); // We need 2 consecutive failures to enable exponential back off worker.parse_www_retry_after(failure_response); ASSERT_EQ(worker.failure_count, 1); auto retry_after_time = worker.parse_www_retry_after(failure_response); ASSERT_EQ(worker.failure_count, 2); auto back_off_duration = retry_after_time - time(0); // Should back off randomly between 120 - 150s ASSERT_GT(back_off_duration, 115); ASSERT_LE(back_off_duration, 150); // Test a third failure retry_after_time = worker.parse_www_retry_after(failure_response); ASSERT_EQ(worker.failure_count, 3); back_off_duration = retry_after_time - time(0); // Should back off randomly between 240 - 270s ASSERT_GT(back_off_duration, 235); ASSERT_LE(back_off_duration, 270); } // // A single success after a number of failures should reset the back off time. // TEST(MixpanelNetwork, FailureRecovery) { mixpanel::Mixpanel mp(mp_token); mixpanel::detail::Worker worker(&mp); nanowww::Response failure_response; failure_response.set_status(503); // We need 2 consecutive failures to enable exponential back off worker.parse_www_retry_after(failure_response); ASSERT_EQ(worker.failure_count, 1); worker.parse_www_retry_after(failure_response); ASSERT_EQ(worker.failure_count, 2); // Followed by 1 success to reset the back off nanowww::Response success_response; success_response.set_status(200); auto retry_after_time = worker.parse_www_retry_after(success_response); ASSERT_EQ(worker.failure_count, 0); auto back_off_duration = retry_after_time - time(0); // Back off time should be reset ASSERT_EQ(back_off_duration, 0); } <|endoftext|>
<commit_before><commit_msg>Linux: Fallback to SSL if server closes early during TLS handshake. BUG=http://crbug.com/14092 TEST=See bug for example TLS-intolerant server.<commit_after><|endoftext|>
<commit_before>/* Copyright libCellML Contributors 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 "libcellml/model.h" #include <algorithm> #include <fstream> #include <map> #include <sstream> #include <stack> #include <utility> #include <vector> #include "libcellml/component.h" #include "libcellml/importsource.h" #include "libcellml/parser.h" #include "libcellml/units.h" #include "libcellml/variable.h" #include "internaltypes.h" #include "utilities.h" #include "xmldoc.h" #include "xmlutils.h" namespace libcellml { /** * @brief The Model::ModelImpl struct. * * This struct is the private implementation struct for the Model class. Separating * the implementation from the definition allows for greater flexibility when * distributing the code. */ struct Model::ModelImpl { std::vector<UnitsPtr> mUnits; std::vector<ImportSourcePtr> mImports; std::vector<UnitsPtr>::iterator findUnits(const std::string &name); std::vector<UnitsPtr>::iterator findUnits(const UnitsPtr &units); }; std::vector<UnitsPtr>::iterator Model::ModelImpl::findUnits(const std::string &name) { return std::find_if(mUnits.begin(), mUnits.end(), [=](const UnitsPtr &u) -> bool { return u->name() == name; }); } std::vector<UnitsPtr>::iterator Model::ModelImpl::findUnits(const UnitsPtr &units) { return std::find_if(mUnits.begin(), mUnits.end(), [=](const UnitsPtr &u) -> bool { return units->name().empty() ? false : u->name() == units->name() && Units::equivalent(u, units); }); } Model::Model() : mPimpl(new ModelImpl()) { } Model::Model(const std::string &name) : mPimpl(new ModelImpl()) { setName(name); } ModelPtr Model::create() noexcept { return std::shared_ptr<Model> {new Model {}}; } ModelPtr Model::create(const std::string &name) noexcept { return std::shared_ptr<Model> {new Model {name}}; } Model::~Model() { delete mPimpl; } bool Model::doAddComponent(const ComponentPtr &component) { if (component->hasParent()) { auto parent = component->parent(); removeComponentFromEntity(parent, component); } component->setParent(shared_from_this()); if (component->isImport()) { auto importSource = component->importSource(); addImportSource(importSource); } return ComponentEntity::doAddComponent(component); } bool Model::addUnits(const UnitsPtr &units) { if (units == nullptr) { return false; } // Prevent adding multiple times to list. if (hasUnits(units)) { return false; } // Prevent adding to multiple models: move units to this model. if (units->hasParent()) { auto otherParent = std::dynamic_pointer_cast<Model>(units->parent()); otherParent->removeUnits(units); } mPimpl->mUnits.push_back(units); units->setParent(shared_from_this()); if (units->isImport()) { addImportSource(units->importSource()); } return true; } bool Model::removeUnits(size_t index) { bool status = false; if (index < mPimpl->mUnits.size()) { auto units = *(mPimpl->mUnits.begin() + int64_t(index)); units->removeParent(); mPimpl->mUnits.erase(mPimpl->mUnits.begin() + int64_t(index)); status = true; } return status; } bool Model::removeUnits(const std::string &name) { bool status = false; auto result = mPimpl->findUnits(name); if (result != mPimpl->mUnits.end()) { (*result)->removeParent(); mPimpl->mUnits.erase(result); status = true; } return status; } bool Model::removeUnits(const UnitsPtr &units) { bool status = false; auto result = mPimpl->findUnits(units); if (result != mPimpl->mUnits.end()) { units->removeParent(); mPimpl->mUnits.erase(result); status = true; } return status; } void Model::removeAllUnits() { for (const auto &u : mPimpl->mUnits) { u->removeParent(); } mPimpl->mUnits.clear(); } bool Model::hasUnits(const std::string &name) const { return mPimpl->findUnits(name) != mPimpl->mUnits.end(); } bool Model::hasUnits(const UnitsPtr &units) const { return mPimpl->findUnits(units) != mPimpl->mUnits.end(); } UnitsPtr Model::units(size_t index) const { UnitsPtr units = nullptr; if (index < mPimpl->mUnits.size()) { units = mPimpl->mUnits.at(index); } return units; } UnitsPtr Model::units(const std::string &name) const { UnitsPtr units = nullptr; auto result = mPimpl->findUnits(name); if (result != mPimpl->mUnits.end()) { units = *result; } return units; } UnitsPtr Model::takeUnits(size_t index) { UnitsPtr units = nullptr; if (index < mPimpl->mUnits.size()) { units = mPimpl->mUnits.at(index); removeUnits(index); units->removeParent(); } return units; } UnitsPtr Model::takeUnits(const std::string &name) { return takeUnits(size_t(mPimpl->findUnits(name) - mPimpl->mUnits.begin())); } bool Model::replaceUnits(size_t index, const UnitsPtr &units) { bool status = false; if (removeUnits(index)) { mPimpl->mUnits.insert(mPimpl->mUnits.begin() + int64_t(index), units); status = true; } return status; } bool Model::replaceUnits(const std::string &name, const UnitsPtr &units) { return replaceUnits(size_t(mPimpl->findUnits(name) - mPimpl->mUnits.begin()), units); } bool Model::replaceUnits(const UnitsPtr &oldUnits, const UnitsPtr &newUnits) { return replaceUnits(size_t(mPimpl->findUnits(oldUnits) - mPimpl->mUnits.begin()), newUnits); } size_t Model::unitsCount() const { return mPimpl->mUnits.size(); } bool Model::hasImportSource(const ImportSourcePtr &importSrc) const { return std::find(mPimpl->mImports.begin(), mPimpl->mImports.end(), importSrc) != mPimpl->mImports.end(); } bool Model::addImportSource(const ImportSourcePtr &importSrc) { if (importSrc == nullptr) { return false; } if (hasImportSource(importSrc)) { return false; } auto otherModel = owningModel(importSrc); if (otherModel != nullptr) { otherModel->removeImportSource(importSrc); } importSrc->setParent(shared_from_this()); mPimpl->mImports.push_back(importSrc); return true; } size_t Model::importSourceCount() const { return mPimpl->mImports.size(); } ImportSourcePtr Model::importSource(size_t index) const { ImportSourcePtr importSrc = nullptr; if (index < mPimpl->mImports.size()) { importSrc = mPimpl->mImports.at(index); } return importSrc; } bool Model::removeImportSource(size_t index) { bool status = false; auto importSrc = importSource(index); status = removeImportSource(importSrc); return status; } bool Model::removeImportSource(const ImportSourcePtr &importSrc) { bool status = false; auto result = std::find(mPimpl->mImports.begin(), mPimpl->mImports.end(), importSrc); if (result != mPimpl->mImports.end()) { importSrc->removeParent(); mPimpl->mImports.erase(result); status = true; } return status; } bool Model::removeAllImportSources() { bool status = true; for (const auto &imp : mPimpl->mImports) { imp->removeParent(); } mPimpl->mImports.clear(); return status; } bool Model::linkUnits() { bool status = true; for (size_t index = 0; index < componentCount(); ++index) { auto c = component(index); status = status && traverseComponentTreeLinkingUnits(c); } return status; } bool traverseComponentTreeForUnlinkedUnits(const ComponentPtr &component, const LoggerPtr &logger) { bool unlinkedUnits = areComponentVariableUnitsUnlinked(component); for (size_t index = 0; index < component->componentCount() && !unlinkedUnits; ++index) { auto c = component->component(index); unlinkedUnits = traverseComponentTreeForUnlinkedUnits(c, logger); } return unlinkedUnits; } bool traverseComponentTreeForUnlinkedUnits(const ComponentPtr &component) { return traverseComponentTreeForUnlinkedUnits(component, nullptr); } bool Model::hasUnlinkedUnits() { bool unlinkedUnits = false; for (size_t index = 0; index < componentCount() && !unlinkedUnits; ++index) { auto c = component(index); unlinkedUnits = traverseComponentTreeForUnlinkedUnits(c); } return unlinkedUnits; } bool isUnresolvedImport(const ImportedEntityPtr &importedEntity) { bool unresolvedImport = false; if (importedEntity->isImport()) { ImportSourcePtr importedSource = importedEntity->importSource(); unresolvedImport = !importedSource->hasModel(); } return unresolvedImport; } bool hasUnresolvedComponentImports(const ComponentEntityConstPtr &parentComponentEntity); bool doHasUnresolvedComponentImports(const ComponentPtr &component) { bool unresolvedImports = false; if (component->isImport()) { unresolvedImports = isUnresolvedImport(component); if (!unresolvedImports) { // Check that the imported component can import all it needs from its model. auto importedSource = component->importSource(); auto importedModel = importedSource->model(); auto importedComponent = importedModel->component(component->importReference()); if (importedComponent == nullptr) { unresolvedImports = true; } else { unresolvedImports = doHasUnresolvedComponentImports(importedComponent); } } } else { unresolvedImports = hasUnresolvedComponentImports(component); } return unresolvedImports; } bool hasUnresolvedComponentImports(const ComponentEntityConstPtr &parentComponentEntity) { bool unresolvedImports = false; for (size_t n = 0; n < parentComponentEntity->componentCount() && !unresolvedImports; ++n) { libcellml::ComponentPtr component = parentComponentEntity->component(n); unresolvedImports = doHasUnresolvedComponentImports(component); } return unresolvedImports; } bool Model::hasUnresolvedImports() const { bool unresolvedImports = false; for (size_t n = 0; n < unitsCount() && !unresolvedImports; ++n) { libcellml::UnitsPtr units = Model::units(n); unresolvedImports = isUnresolvedImport(units); } if (!unresolvedImports) { unresolvedImports = hasUnresolvedComponentImports(shared_from_this()); } return unresolvedImports; } bool hasComponentImports(const ComponentEntityConstPtr &componentEntity) { bool importsPresent = false; for (size_t n = 0; n < componentEntity->componentCount() && !importsPresent; ++n) { libcellml::ComponentPtr childComponent = componentEntity->component(n); importsPresent = childComponent->isImport(); if (!importsPresent) { importsPresent = hasComponentImports(childComponent); } } return importsPresent; } bool Model::hasImports() const { bool importsPresent = false; for (size_t n = 0; n < unitsCount() && !importsPresent; ++n) { libcellml::UnitsPtr units = Model::units(n); if (units->isImport()) { importsPresent = true; } } if (!importsPresent) { importsPresent = hasComponentImports(shared_from_this()); } return importsPresent; } ModelPtr Model::clone() const { auto m = create(); m->setId(id()); m->setName(name()); m->setEncapsulationId(encapsulationId()); for (size_t index = 0; index < mPimpl->mUnits.size(); ++index) { m->addUnits(units(index)->clone()); } for (size_t index = 0; index < componentCount(); ++index) { m->addComponent(component(index)->clone()); } // Generate equivalence map starting from the models components. EquivalenceMap map; IndexStack indexStack; for (size_t index = 0; index < componentCount(); ++index) { indexStack.push_back(index); auto c = component(index); recordVariableEquivalences(c, map, indexStack); generateEquivalenceMap(c, map, indexStack); indexStack.pop_back(); } applyEquivalenceMapToModel(map, m); return m; } bool Model::fixVariableInterfaces() { VariablePtrs variables; for (size_t index = 0; index < componentCount(); ++index) { findAllVariablesWithEquivalences(component(index), variables); } bool allOk = true; for (const auto &variable : variables) { Variable::InterfaceType interfaceType = determineInterfaceType(variable); if (interfaceType == Variable::InterfaceType::NONE) { allOk = false; } else if (!variable->hasInterfaceType(interfaceType)) { variable->setInterfaceType(interfaceType); } } return allOk; } } // namespace libcellml <commit_msg>removed unneeded overload<commit_after>/* Copyright libCellML Contributors 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 "libcellml/model.h" #include <algorithm> #include <fstream> #include <map> #include <sstream> #include <stack> #include <utility> #include <vector> #include "libcellml/component.h" #include "libcellml/importsource.h" #include "libcellml/parser.h" #include "libcellml/units.h" #include "libcellml/variable.h" #include "internaltypes.h" #include "utilities.h" #include "xmldoc.h" #include "xmlutils.h" namespace libcellml { /** * @brief The Model::ModelImpl struct. * * This struct is the private implementation struct for the Model class. Separating * the implementation from the definition allows for greater flexibility when * distributing the code. */ struct Model::ModelImpl { std::vector<UnitsPtr> mUnits; std::vector<ImportSourcePtr> mImports; std::vector<UnitsPtr>::iterator findUnits(const std::string &name); std::vector<UnitsPtr>::iterator findUnits(const UnitsPtr &units); }; std::vector<UnitsPtr>::iterator Model::ModelImpl::findUnits(const std::string &name) { return std::find_if(mUnits.begin(), mUnits.end(), [=](const UnitsPtr &u) -> bool { return u->name() == name; }); } std::vector<UnitsPtr>::iterator Model::ModelImpl::findUnits(const UnitsPtr &units) { return std::find_if(mUnits.begin(), mUnits.end(), [=](const UnitsPtr &u) -> bool { return units->name().empty() ? false : u->name() == units->name() && Units::equivalent(u, units); }); } Model::Model() : mPimpl(new ModelImpl()) { } Model::Model(const std::string &name) : mPimpl(new ModelImpl()) { setName(name); } ModelPtr Model::create() noexcept { return std::shared_ptr<Model> {new Model {}}; } ModelPtr Model::create(const std::string &name) noexcept { return std::shared_ptr<Model> {new Model {name}}; } Model::~Model() { delete mPimpl; } bool Model::doAddComponent(const ComponentPtr &component) { if (component->hasParent()) { auto parent = component->parent(); removeComponentFromEntity(parent, component); } component->setParent(shared_from_this()); if (component->isImport()) { auto importSource = component->importSource(); addImportSource(importSource); } return ComponentEntity::doAddComponent(component); } bool Model::addUnits(const UnitsPtr &units) { if (units == nullptr) { return false; } // Prevent adding multiple times to list. if (hasUnits(units)) { return false; } // Prevent adding to multiple models: move units to this model. if (units->hasParent()) { auto otherParent = std::dynamic_pointer_cast<Model>(units->parent()); otherParent->removeUnits(units); } mPimpl->mUnits.push_back(units); units->setParent(shared_from_this()); if (units->isImport()) { addImportSource(units->importSource()); } return true; } bool Model::removeUnits(size_t index) { bool status = false; if (index < mPimpl->mUnits.size()) { auto units = *(mPimpl->mUnits.begin() + int64_t(index)); units->removeParent(); mPimpl->mUnits.erase(mPimpl->mUnits.begin() + int64_t(index)); status = true; } return status; } bool Model::removeUnits(const std::string &name) { bool status = false; auto result = mPimpl->findUnits(name); if (result != mPimpl->mUnits.end()) { (*result)->removeParent(); mPimpl->mUnits.erase(result); status = true; } return status; } bool Model::removeUnits(const UnitsPtr &units) { bool status = false; auto result = mPimpl->findUnits(units); if (result != mPimpl->mUnits.end()) { units->removeParent(); mPimpl->mUnits.erase(result); status = true; } return status; } void Model::removeAllUnits() { for (const auto &u : mPimpl->mUnits) { u->removeParent(); } mPimpl->mUnits.clear(); } bool Model::hasUnits(const std::string &name) const { return mPimpl->findUnits(name) != mPimpl->mUnits.end(); } bool Model::hasUnits(const UnitsPtr &units) const { return mPimpl->findUnits(units) != mPimpl->mUnits.end(); } UnitsPtr Model::units(size_t index) const { UnitsPtr units = nullptr; if (index < mPimpl->mUnits.size()) { units = mPimpl->mUnits.at(index); } return units; } UnitsPtr Model::units(const std::string &name) const { UnitsPtr units = nullptr; auto result = mPimpl->findUnits(name); if (result != mPimpl->mUnits.end()) { units = *result; } return units; } UnitsPtr Model::takeUnits(size_t index) { UnitsPtr units = nullptr; if (index < mPimpl->mUnits.size()) { units = mPimpl->mUnits.at(index); removeUnits(index); units->removeParent(); } return units; } UnitsPtr Model::takeUnits(const std::string &name) { return takeUnits(size_t(mPimpl->findUnits(name) - mPimpl->mUnits.begin())); } bool Model::replaceUnits(size_t index, const UnitsPtr &units) { bool status = false; if (removeUnits(index)) { mPimpl->mUnits.insert(mPimpl->mUnits.begin() + int64_t(index), units); status = true; } return status; } bool Model::replaceUnits(const std::string &name, const UnitsPtr &units) { return replaceUnits(size_t(mPimpl->findUnits(name) - mPimpl->mUnits.begin()), units); } bool Model::replaceUnits(const UnitsPtr &oldUnits, const UnitsPtr &newUnits) { return replaceUnits(size_t(mPimpl->findUnits(oldUnits) - mPimpl->mUnits.begin()), newUnits); } size_t Model::unitsCount() const { return mPimpl->mUnits.size(); } bool Model::hasImportSource(const ImportSourcePtr &importSrc) const { return std::find(mPimpl->mImports.begin(), mPimpl->mImports.end(), importSrc) != mPimpl->mImports.end(); } bool Model::addImportSource(const ImportSourcePtr &importSrc) { if (importSrc == nullptr) { return false; } if (hasImportSource(importSrc)) { return false; } auto otherModel = owningModel(importSrc); if (otherModel != nullptr) { otherModel->removeImportSource(importSrc); } importSrc->setParent(shared_from_this()); mPimpl->mImports.push_back(importSrc); return true; } size_t Model::importSourceCount() const { return mPimpl->mImports.size(); } ImportSourcePtr Model::importSource(size_t index) const { ImportSourcePtr importSrc = nullptr; if (index < mPimpl->mImports.size()) { importSrc = mPimpl->mImports.at(index); } return importSrc; } bool Model::removeImportSource(size_t index) { bool status = false; auto importSrc = importSource(index); status = removeImportSource(importSrc); return status; } bool Model::removeImportSource(const ImportSourcePtr &importSrc) { bool status = false; auto result = std::find(mPimpl->mImports.begin(), mPimpl->mImports.end(), importSrc); if (result != mPimpl->mImports.end()) { importSrc->removeParent(); mPimpl->mImports.erase(result); status = true; } return status; } bool Model::removeAllImportSources() { bool status = true; for (const auto &imp : mPimpl->mImports) { imp->removeParent(); } mPimpl->mImports.clear(); return status; } bool Model::linkUnits() { bool status = true; for (size_t index = 0; index < componentCount(); ++index) { auto c = component(index); status = status && traverseComponentTreeLinkingUnits(c); } return status; } bool traverseComponentTreeForUnlinkedUnits(const ComponentPtr &component) { bool unlinkedUnits = areComponentVariableUnitsUnlinked(component); for (size_t index = 0; index < component->componentCount() && !unlinkedUnits; ++index) { auto c = component->component(index); unlinkedUnits = traverseComponentTreeForUnlinkedUnits(c); } return unlinkedUnits; } bool Model::hasUnlinkedUnits() { bool unlinkedUnits = false; for (size_t index = 0; index < componentCount() && !unlinkedUnits; ++index) { auto c = component(index); unlinkedUnits = traverseComponentTreeForUnlinkedUnits(c); } return unlinkedUnits; } bool isUnresolvedImport(const ImportedEntityPtr &importedEntity) { bool unresolvedImport = false; if (importedEntity->isImport()) { ImportSourcePtr importedSource = importedEntity->importSource(); unresolvedImport = !importedSource->hasModel(); } return unresolvedImport; } bool hasUnresolvedComponentImports(const ComponentEntityConstPtr &parentComponentEntity); bool doHasUnresolvedComponentImports(const ComponentPtr &component) { bool unresolvedImports = false; if (component->isImport()) { unresolvedImports = isUnresolvedImport(component); if (!unresolvedImports) { // Check that the imported component can import all it needs from its model. auto importedSource = component->importSource(); auto importedModel = importedSource->model(); auto importedComponent = importedModel->component(component->importReference()); if (importedComponent == nullptr) { unresolvedImports = true; } else { unresolvedImports = doHasUnresolvedComponentImports(importedComponent); } } } else { unresolvedImports = hasUnresolvedComponentImports(component); } return unresolvedImports; } bool hasUnresolvedComponentImports(const ComponentEntityConstPtr &parentComponentEntity) { bool unresolvedImports = false; for (size_t n = 0; n < parentComponentEntity->componentCount() && !unresolvedImports; ++n) { libcellml::ComponentPtr component = parentComponentEntity->component(n); unresolvedImports = doHasUnresolvedComponentImports(component); } return unresolvedImports; } bool Model::hasUnresolvedImports() const { bool unresolvedImports = false; for (size_t n = 0; n < unitsCount() && !unresolvedImports; ++n) { libcellml::UnitsPtr units = Model::units(n); unresolvedImports = isUnresolvedImport(units); } if (!unresolvedImports) { unresolvedImports = hasUnresolvedComponentImports(shared_from_this()); } return unresolvedImports; } bool hasComponentImports(const ComponentEntityConstPtr &componentEntity) { bool importsPresent = false; for (size_t n = 0; n < componentEntity->componentCount() && !importsPresent; ++n) { libcellml::ComponentPtr childComponent = componentEntity->component(n); importsPresent = childComponent->isImport(); if (!importsPresent) { importsPresent = hasComponentImports(childComponent); } } return importsPresent; } bool Model::hasImports() const { bool importsPresent = false; for (size_t n = 0; n < unitsCount() && !importsPresent; ++n) { libcellml::UnitsPtr units = Model::units(n); if (units->isImport()) { importsPresent = true; } } if (!importsPresent) { importsPresent = hasComponentImports(shared_from_this()); } return importsPresent; } ModelPtr Model::clone() const { auto m = create(); m->setId(id()); m->setName(name()); m->setEncapsulationId(encapsulationId()); for (size_t index = 0; index < mPimpl->mUnits.size(); ++index) { m->addUnits(units(index)->clone()); } for (size_t index = 0; index < componentCount(); ++index) { m->addComponent(component(index)->clone()); } // Generate equivalence map starting from the models components. EquivalenceMap map; IndexStack indexStack; for (size_t index = 0; index < componentCount(); ++index) { indexStack.push_back(index); auto c = component(index); recordVariableEquivalences(c, map, indexStack); generateEquivalenceMap(c, map, indexStack); indexStack.pop_back(); } applyEquivalenceMapToModel(map, m); return m; } bool Model::fixVariableInterfaces() { VariablePtrs variables; for (size_t index = 0; index < componentCount(); ++index) { findAllVariablesWithEquivalences(component(index), variables); } bool allOk = true; for (const auto &variable : variables) { Variable::InterfaceType interfaceType = determineInterfaceType(variable); if (interfaceType == Variable::InterfaceType::NONE) { allOk = false; } else if (!variable->hasInterfaceType(interfaceType)) { variable->setInterfaceType(interfaceType); } } return allOk; } } // namespace libcellml <|endoftext|>
<commit_before>// Copyright (c) 2017 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // 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 HOLDER 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. #include <atomic> #include <cstdlib> #include <iostream> #include <memory> #include <deque> #include <vector> #include <set> #include <boost/asio.hpp> #include "chat_protocol.h" using boost::asio::ip::tcp; using ChatMessageQueue = std::deque<ChatMessage>; class ChatParticipant { public: virtual ~ChatParticipant(void) {} virtual void deliver(const ChatMessage& msg) = 0; }; using ChatParticipantPtr = std::shared_ptr<ChatParticipant>; class ChatRoom : private boost::noncopyable { enum { RECENT_NMSGS_MAX = 100 }; std::set<ChatParticipantPtr> participants_; ChatMessageQueue recent_msgs_; static std::atomic<std::int64_t> s_id_; public: void join_in(const ChatParticipantPtr& participant) { participants_.insert(participant); for (const auto& msg : recent_msgs_) participant->deliver(msg); } void leave_out(const ChatParticipantPtr& participant) { participants_.erase(participant); } void deliver(const ChatMessage& msg) { recent_msgs_.push_back(msg); while (recent_msgs_.size() > RECENT_NMSGS_MAX) recent_msgs_.pop_front(); for (const auto& participant : participants_) participant->deliver(msg); } static std::int64_t gen_id(void) { return ++s_id_; } }; std::atomic<std::int64_t> ChatRoom::s_id_; class ChatSession : public ChatParticipant, public std::enable_shared_from_this<ChatSession> { tcp::socket socket_; ChatRoom& chat_room_; ChatMessage readmsg_; ChatMessageQueue writmsg_queue_; void do_write_session(void) { char buf[64]{}; std::snprintf(buf, sizeof(buf), "%08lld", ChatRoom::gen_id()); ChatMessage msg = gen_chat_message(ChatProtocol::CP_SESSION, buf, std::strlen(buf)); deliver(msg); } void do_read_header(void) { auto self(shared_from_this()); boost::asio::async_read(socket_, boost::asio::buffer(readmsg_.data(), ChatProtocol::NHEADER), [this, self](const boost::system::error_code& ec, std::size_t /*n*/) { if (!ec && readmsg_.decode_header()) do_read_body(); else chat_room_.leave_out(shared_from_this()); }); } void do_read_body(void) { auto self(shared_from_this()); boost::asio::async_read(socket_, boost::asio::buffer(readmsg_.body(), readmsg_.get_nbody()), [this, self](const boost::system::error_code& ec, std::size_t /*n*/) { if (!ec) { chat_room_.deliver(readmsg_); do_read_header(); } else { chat_room_.leave_out(shared_from_this()); } }); } void do_write(void) { auto self(shared_from_this()); boost::asio::async_write(socket_, boost::asio::buffer(writmsg_queue_.front().data(), writmsg_queue_.front().size()), [this, self](const boost::system::error_code& ec, std::size_t /*n*/) { if (!ec) { writmsg_queue_.pop_front(); if (!writmsg_queue_.empty()) do_write(); } else { chat_room_.leave_out(shared_from_this()); } }); } public: ChatSession(tcp::socket&& socket, ChatRoom& chat_room) : socket_(std::move(socket)) , chat_room_(chat_room) { } void start(void) { chat_room_.join_in(shared_from_this()); do_write_session(); do_read_header(); } void deliver(const ChatMessage& msg) { bool write_in_progress = !writmsg_queue_.empty(); writmsg_queue_.push_back(msg); if (!write_in_progress) do_write(); } }; class ChatServer : private boost::noncopyable { tcp::acceptor acceptor_; tcp::socket socket_; ChatRoom chat_room_; void do_accept(void) { acceptor_.async_accept(socket_, [this](const boost::system::error_code& ec) { if (!ec) std::make_shared<ChatSession>(std::move(socket_), chat_room_)->start(); do_accept(); }); } public: ChatServer(boost::asio::io_service& io_service, const tcp::endpoint& endpoint) : acceptor_(io_service, endpoint) , socket_(io_service) { } void start(void) { do_accept(); } }; int main(int argc, char* argv[]) { (void)argc, (void)argv; return 0; } <commit_msg>:construction: chore(chat.server): updated the chat server implmentation<commit_after>// Copyright (c) 2017 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // 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 HOLDER 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. #include <atomic> #include <cstdlib> #include <iostream> #include <memory> #include <deque> #include <vector> #include <set> #include <boost/asio.hpp> #include "chat_protocol.h" using boost::asio::ip::tcp; using ChatMessageQueue = std::deque<ChatMessage>; class ChatParticipant { public: virtual ~ChatParticipant(void) {} virtual void deliver(const ChatMessage& msg) = 0; }; using ChatParticipantPtr = std::shared_ptr<ChatParticipant>; class ChatRoom : private boost::noncopyable { enum { RECENT_NMSGS_MAX = 100 }; std::set<ChatParticipantPtr> participants_; ChatMessageQueue recent_msgs_; static std::atomic<std::int64_t> s_id_; public: void join_in(const ChatParticipantPtr& participant) { participants_.insert(participant); for (const auto& msg : recent_msgs_) participant->deliver(msg); } void leave_out(const ChatParticipantPtr& participant) { participants_.erase(participant); } void deliver(const ChatMessage& msg) { recent_msgs_.push_back(msg); while (recent_msgs_.size() > RECENT_NMSGS_MAX) recent_msgs_.pop_front(); for (const auto& participant : participants_) participant->deliver(msg); } static std::int64_t gen_id(void) { return ++s_id_; } }; std::atomic<std::int64_t> ChatRoom::s_id_; class ChatSession : public ChatParticipant, public std::enable_shared_from_this<ChatSession> { tcp::socket socket_; ChatRoom& chat_room_; ChatMessage readmsg_; ChatMessageQueue writmsg_queue_; void do_write_session(void) { char buf[64]{}; std::snprintf(buf, sizeof(buf), "%08lld", ChatRoom::gen_id()); ChatMessage msg = gen_chat_message(ChatProtocol::CP_SESSION, buf, std::strlen(buf)); deliver(msg); } void do_read_header(void) { auto self(shared_from_this()); boost::asio::async_read(socket_, boost::asio::buffer(readmsg_.data(), ChatProtocol::NHEADER), [this, self](const boost::system::error_code& ec, std::size_t /*n*/) { if (!ec && readmsg_.decode_header()) do_read_body(); else chat_room_.leave_out(shared_from_this()); }); } void do_read_body(void) { auto self(shared_from_this()); boost::asio::async_read(socket_, boost::asio::buffer(readmsg_.body(), readmsg_.get_nbody()), [this, self](const boost::system::error_code& ec, std::size_t /*n*/) { if (!ec) { chat_room_.deliver(readmsg_); do_read_header(); } else { chat_room_.leave_out(shared_from_this()); } }); } void do_write(void) { auto self(shared_from_this()); boost::asio::async_write(socket_, boost::asio::buffer(writmsg_queue_.front().data(), writmsg_queue_.front().size()), [this, self](const boost::system::error_code& ec, std::size_t /*n*/) { if (!ec) { writmsg_queue_.pop_front(); if (!writmsg_queue_.empty()) do_write(); } else { chat_room_.leave_out(shared_from_this()); } }); } public: ChatSession(tcp::socket&& socket, ChatRoom& chat_room) : socket_(std::move(socket)) , chat_room_(chat_room) { } void start(void) { chat_room_.join_in(shared_from_this()); do_write_session(); do_read_header(); } void deliver(const ChatMessage& msg) { bool write_in_progress = !writmsg_queue_.empty(); writmsg_queue_.push_back(msg); if (!write_in_progress) do_write(); } }; class ChatServer : private boost::noncopyable { tcp::acceptor acceptor_; tcp::socket socket_; ChatRoom chat_room_; void do_accept(void) { acceptor_.async_accept(socket_, [this](const boost::system::error_code& ec) { if (!ec) std::make_shared<ChatSession>(std::move(socket_), chat_room_)->start(); do_accept(); }); } public: ChatServer(boost::asio::io_service& io_service, const tcp::endpoint& endpoint) : acceptor_(io_service, endpoint) , socket_(io_service) { } void start(void) { do_accept(); } }; int main(int argc, char* argv[]) { (void)argc, (void)argv; try { boost::asio::io_service io_service; std::vector<std::unique_ptr<ChatServer>> servers; for (int i = 0; i < 5; ++i) { tcp::endpoint endpoint(tcp::v4(), 5555); servers.emplace_back(new ChatServer(io_service, endpoint)); } io_service.run(); } catch (std::exception& ex) { std::cerr << "exception: " << ex.what() << std::endl; } return 0; } <|endoftext|>
<commit_before>#include "nodes.hpp" namespace lang { Variable* resolveNameFrom(ASTNode* localNode, std::string identifier) { if (localNode == nullptr) return nullptr; // Reached tree root and didn't find anything. try { return localNode->getScope()->at(identifier); } catch(std::out_of_range& oor) { return resolveNameFrom(localNode->getParent(), identifier); } } void printIndent(int level) { for (int i = 0; i < level; ++i) print(" "); } ASTNode::ASTNode() {} ASTNode::~ASTNode() {} void ASTNode::addChild(ASTNode* child) { child->setParent(this); children.push_back(child); } std::vector<ASTNode*>& ASTNode::getChildren() { return children; } void ASTNode::setParent(ASTNode* parent) { this->parent = parent; } ASTNode* ASTNode::getParent() { return parent; } Scope* ASTNode::getScope() { return &local; } Scope* ASTNode::getParentScope() { return &this->parent->local; } void ASTNode::setLineNumber(int lines) { this->lines = lines; } int ASTNode::getLineNumber() { return this->lines; } std::string ASTNode::getNodeType() { return "ASTNode"; } void ASTNode::printTree(int level) { printIndent(level); print("Plain ASTNode"); for (auto child : children) { child->printTree(level + 1); } } SingleChildNode::SingleChildNode() {}; void SingleChildNode::addChild(ASTNode* child) { if (this->getChildren().size() >= 1) throw std::runtime_error("Trying to add more than one child to SingleChildNode."); else { this->ASTNode::addChild(child); } } ASTNode* SingleChildNode::getChild() { return children[0]; } std::string SingleChildNode::getNodeType() { return "SingleChildNode"; } void SingleChildNode::printTree(int level) { printIndent(level); auto child = dynamic_cast<SingleChildNode*>(this->getChild()); if (child == nullptr) { print("SingleChildNode, empty", "\n"); return; } print("SingleChildNode with: ", child, "\n"); child->printTree(level + 1); } DeclarationNode::DeclarationNode(std::vector<std::string> typeNames, Token identifier) { this->typeNames = typeNames; this->identifier = identifier; } void DeclarationNode::addChild(ASTNode* child) { auto node = dynamic_cast<ExpressionNode*>(child); if (node == nullptr) throw std::invalid_argument("DeclarationNode only accepts an ExpressionNode as its child."); this->SingleChildNode::addChild(node); } std::string DeclarationNode::getNodeType() { return "DeclarationNode"; } void DeclarationNode::printTree(int level) { printIndent(level); print("Declared ", this->typeNames, " as ", this->identifier, "\n"); if (this->getChildren().size() == 1) dynamic_cast<ExpressionNode*>(this->getChild())->printTree(level + 1); } FunctionNode::FunctionNode(std::string name, Arguments* arguments, std::vector<std::string> returnTypes): name(name), defaultArguments(arguments), returnTypes(returnTypes) {} void FunctionNode::addChild(ASTNode* child) { auto node = dynamic_cast<BlockNode*>(child); if (node == nullptr) throw std::invalid_argument("FunctionNode only accepts a BlockNode as its child."); this->SingleChildNode::addChild(node); } std::string FunctionNode::getNodeType() {return "FunctionNode";} void FunctionNode::printTree(int level) { printIndent(level); print("Function " + name, "\n"); if (this->getChildren().size() == 1) dynamic_cast<BlockNode*>(this->getChild())->printTree(level + 1); } std::string FunctionNode::getName() { return name; } Arguments* FunctionNode::getArguments() { return defaultArguments; } TypeList FunctionNode::getReturnTypes() { return returnTypes; } std::vector<TokenType> ExpressionNode::validOperandTypes { INTEGER, FLOAT, STRING, BOOLEAN, ARRAY, TYPE, VARIABLE, FUNCTION, MEMBER }; ExpressionNode::ExpressionNode(std::vector<Token>& tokens) { for (uint64 i = 0; i < tokens.size(); ++i) { if (EXPRESSION_STEPS) { for (auto tok : outStack) print(tok.data, " "); print("\n-------\n"); for (auto tok : opStack) print(tok.data, " "); print("\n=======\n"); } if (contains(tokens[i].type, validOperandTypes)) { outStack.push_back(tokens[i]); } else if (tokens[i].type == OPERATOR) { /* * This prevents crash when there's no operators. * Or when it found a parenthesis, because they're not really operators. */ if (opStack.size() == 0 || opStack.back().data == "(") { opStack.push_back(tokens[i]); continue; } Operator current = *static_cast<Operator*>(tokens[i].typeData); Operator topOfStack = *static_cast<Operator*>(opStack.back().typeData); while (opStack.size() != 0) { if ((current.getAssociativity() == ASSOCIATE_FROM_LEFT && current.getPrecedence() <= topOfStack.getPrecedence()) || (current.getAssociativity() == ASSOCIATE_FROM_RIGHT && current.getPrecedence() < topOfStack.getPrecedence())) { popToOut(); } else break; // Non-operators (eg parenthesis) will crash on next line, and must break to properly evaluate expression if (opStack.back().type != OPERATOR) break; // Get new top of stack if (opStack.size() != 0) topOfStack = *static_cast<Operator*>(opStack.back().typeData); } opStack.push_back(tokens[i]); } else if (tokens[i].type == CONSTRUCT) { if (isNewLine(tokens[i])) break; if (tokens[i].data != "(" && tokens[i].data != ")") { throw Error("Illegal construct in expression: \"" + tokens[i].data + "\"", "SyntaxError", tokens[i].line); } else if (tokens[i].data == "(") { opStack.push_back(tokens[i]); } else if (tokens[i].data == ")") { while (opStack.size() != 0 && opStack.back().data != "(") popToOut(); if (opStack.back().data != "(") throw Error("Mismatched parenthesis in expression", "SyntaxError", outStack.back().line); opStack.pop_back(); // Get rid of "(" if (opStack.back().type == FUNCTION) popToOut(); } } } while (opStack.size() > 0) popToOut(); } std::vector<Token> ExpressionNode::getRPNOutput() { return outStack; } void ExpressionNode::buildSubtree(void) { std::vector<Token> stackCopy(outStack); ExpressionChildNode* node; if (stackCopy.size() >= 1) { auto tok = stackCopy.back(); stackCopy.pop_back(); node = new ExpressionChildNode(tok, stackCopy); node->setLineNumber(this->lines); } else { throw std::runtime_error("Empty expression.\n"); } this->children.clear(); this->addChild(node); } std::string ExpressionNode::getNodeType() { return "ExpressionNode"; } void ExpressionNode::printTree(int level) { auto top = static_cast<ExpressionChildNode*>(this->getChildren()[0]); top->printTree(level); } ExpressionChildNode::ExpressionChildNode(Token operand): t(operand) {}; ExpressionChildNode::ExpressionChildNode(Token op, std::vector<Token>& operands): t(op) { if (operands.size() == 0) return; auto arity = static_cast<Operator*>(op.typeData)->getArity(); for (int i = 0; i < arity; ++i) { auto next = operands[operands.size() - 1]; if (next.type == OPERATOR) { operands.pop_back(); auto branch = new ExpressionChildNode(next, operands); branch->setLineNumber(op.line); this->addChild(branch); } else { operands.pop_back(); auto leaf = new ExpressionChildNode(next); leaf->setLineNumber(op.line); this->addChild(leaf); } } }; std::string ExpressionChildNode::getNodeType() { return "ExpressionChildNode"; } void ExpressionChildNode::printTree(int level) { printIndent(level); print(this->t, "\n"); for (auto child : this->getChildren()) { static_cast<ExpressionChildNode*>(child)->printTree(level + 1); } } BlockNode::BlockNode() {} std::string BlockNode::getNodeType() { return "BlockNode"; } void BlockNode::printTree(int level) { printIndent(level); print("BlockNode\n"); for (auto node : children) { node->printTree(level + 1); } } ConditionalNode::ConditionalNode(ExpressionNode* condition, BlockNode* trueBlock, BlockNode* falseBlock) { this->children.push_back(condition); this->children.push_back(trueBlock); this->children.push_back(falseBlock); condition->setParent(this); trueBlock->setParent(this); falseBlock->setParent(this); } ExpressionNode* ConditionalNode::getCondition() {return dynamic_cast<ExpressionNode*>(children[0]);} BlockNode* ConditionalNode::getTrueBlock() {return dynamic_cast<BlockNode*>(children[1]);} BlockNode* ConditionalNode::getFalseBlock() {return dynamic_cast<BlockNode*>(children[2]);} void ConditionalNode::addChild(ASTNode* child) { children[this->block]->addChild(child); } void ConditionalNode::nextBlock() { static bool wasCalled = false; if (!wasCalled) { wasCalled = true; this->block++; } else throw Error("Multiple else statements", "SyntaxError", children[2]->getLineNumber()); } std::string ConditionalNode::getNodeType() { return "ConditionalNode"; } void ConditionalNode::printTree(int level) { printIndent(level); print("Condition\n"); this->getCondition()->printTree(level + 1); } WhileNode::WhileNode(ExpressionNode* condition, BlockNode* loop) { this->children.push_back(condition); this->children.push_back(loop); condition->setParent(this); loop->setParent(this); } ExpressionNode* WhileNode::getCondition() {return dynamic_cast<ExpressionNode*>(children[0]);} BlockNode* WhileNode::getLoopNode() {return dynamic_cast<BlockNode*>(children[1]);} void WhileNode::addChild(ASTNode* child) { children[1]->addChild(child); } std::string WhileNode::getNodeType() { return "WhileNode"; } void WhileNode::printTree(int level) { printIndent(level); print("While Condition\n"); this->getCondition()->printTree(level + 1); } AST::AbstractSyntaxTree() { Type* integerType = new Type(std::string("Integer"), { // Static members {"MAX_VALUE", new Member(new Variable(new Integer(LLONG_MAX), {}), PUBLIC)}, {"MIN_VALUE", new Member(new Variable(new Integer(LLONG_MIN), {}), PUBLIC)} }, { // Instance members // TODO add members }); (*root.getScope())[std::string("Integer")] = new Variable(integerType, {}); // Do not allow assignment by not specifying any allowed types for the Variable Type* floatType = new Type(std::string("Float"), { // Static members {"MAX_VALUE", new Member(new Variable(new Float(FLT_MAX), {}), PUBLIC)}, {"MIN_VALUE", new Member(new Variable(new Float(FLT_MIN), {}), PUBLIC)} }, { // Instance members // TODO add members }); (*root.getScope())[std::string("Float")] = new Variable(floatType, {}); Type* stringType = new Type(std::string("String"), { // Static members }, { // Instance members // TODO add members }); (*root.getScope())[std::string("String")] = new Variable(stringType, {}); Type* booleanType = new Type(std::string("Boolean"), { // Static members }, { // Instance members // TODO add members }); (*root.getScope())[std::string("Boolean")] = new Variable(booleanType, {}); Type* functionType = new Type(std::string("Function"), { // Static members }, { // Instance members // TODO add members }); (*root.getScope())[std::string("Function")] = new Variable(functionType, {}); } void AST::addRootChild(ASTNode* node) { root.addChild(node); } ChildrenNodes AST::getRootChildren() { return root.getChildren(); } } /* namespace lang */ <commit_msg>Formatting<commit_after>#include "nodes.hpp" namespace lang { Variable* resolveNameFrom(ASTNode* localNode, std::string identifier) { if (localNode == nullptr) return nullptr; // Reached tree root and didn't find anything. try { return localNode->getScope()->at(identifier); } catch(std::out_of_range& oor) { return resolveNameFrom(localNode->getParent(), identifier); } } void printIndent(int level) { for (int i = 0; i < level; ++i) print(" "); } ASTNode::ASTNode() {} ASTNode::~ASTNode() {} void ASTNode::addChild(ASTNode* child) { child->setParent(this); children.push_back(child); } std::vector<ASTNode*>& ASTNode::getChildren() {return children;} void ASTNode::setParent(ASTNode* parent) {this->parent = parent;} ASTNode* ASTNode::getParent() {return parent;} Scope* ASTNode::getScope() {return &local;} Scope* ASTNode::getParentScope() {return &this->parent->local;} void ASTNode::setLineNumber(int lines) {this->lines = lines;} int ASTNode::getLineNumber() {return this->lines;} std::string ASTNode::getNodeType() {return "ASTNode";} void ASTNode::printTree(int level) { printIndent(level); print("Plain ASTNode"); for (auto child : children) { child->printTree(level + 1); } } SingleChildNode::SingleChildNode() {}; void SingleChildNode::addChild(ASTNode* child) { if (this->getChildren().size() >= 1) throw std::runtime_error("Trying to add more than one child to SingleChildNode."); else { this->ASTNode::addChild(child); } } ASTNode* SingleChildNode::getChild() {return children[0];} std::string SingleChildNode::getNodeType() {return "SingleChildNode";} void SingleChildNode::printTree(int level) { printIndent(level); auto child = dynamic_cast<SingleChildNode*>(this->getChild()); if (child == nullptr) { print("SingleChildNode, empty", "\n"); return; } print("SingleChildNode with: ", child, "\n"); child->printTree(level + 1); } DeclarationNode::DeclarationNode(std::vector<std::string> typeNames, Token identifier) { this->typeNames = typeNames; this->identifier = identifier; } void DeclarationNode::addChild(ASTNode* child) { auto node = dynamic_cast<ExpressionNode*>(child); if (node == nullptr) throw std::invalid_argument("DeclarationNode only accepts an ExpressionNode as its child."); this->SingleChildNode::addChild(node); } std::string DeclarationNode::getNodeType() {return "DeclarationNode";} void DeclarationNode::printTree(int level) { printIndent(level); print("Declared ", this->typeNames, " as ", this->identifier, "\n"); if (this->getChildren().size() == 1) dynamic_cast<ExpressionNode*>(this->getChild())->printTree(level + 1); } FunctionNode::FunctionNode(std::string name, Arguments* arguments, std::vector<std::string> returnTypes): name(name), defaultArguments(arguments), returnTypes(returnTypes) {} void FunctionNode::addChild(ASTNode* child) { auto node = dynamic_cast<BlockNode*>(child); if (node == nullptr) throw std::invalid_argument("FunctionNode only accepts a BlockNode as its child."); this->SingleChildNode::addChild(node); } std::string FunctionNode::getNodeType() {return "FunctionNode";} void FunctionNode::printTree(int level) { printIndent(level); print("Function " + name, "\n"); if (this->getChildren().size() == 1) dynamic_cast<BlockNode*>(this->getChild())->printTree(level + 1); } std::string FunctionNode::getName() {return name;} Arguments* FunctionNode::getArguments() {return defaultArguments;} TypeList FunctionNode::getReturnTypes() {return returnTypes;} std::vector<TokenType> ExpressionNode::validOperandTypes { INTEGER, FLOAT, STRING, BOOLEAN, ARRAY, TYPE, VARIABLE, FUNCTION, MEMBER }; ExpressionNode::ExpressionNode(std::vector<Token>& tokens) { for (uint64 i = 0; i < tokens.size(); ++i) { if (EXPRESSION_STEPS) { for (auto tok : outStack) print(tok.data, " "); print("\n-------\n"); for (auto tok : opStack) print(tok.data, " "); print("\n=======\n"); } if (contains(tokens[i].type, validOperandTypes)) { outStack.push_back(tokens[i]); } else if (tokens[i].type == OPERATOR) { /* * This prevents crash when there's no operators. * Or when it found a parenthesis, because they're not really operators. */ if (opStack.size() == 0 || opStack.back().data == "(") { opStack.push_back(tokens[i]); continue; } Operator current = *static_cast<Operator*>(tokens[i].typeData); Operator topOfStack = *static_cast<Operator*>(opStack.back().typeData); while (opStack.size() != 0) { if ((current.getAssociativity() == ASSOCIATE_FROM_LEFT && current.getPrecedence() <= topOfStack.getPrecedence()) || (current.getAssociativity() == ASSOCIATE_FROM_RIGHT && current.getPrecedence() < topOfStack.getPrecedence())) { popToOut(); } else break; // Non-operators (eg parenthesis) will crash on next line, and must break to properly evaluate expression if (opStack.back().type != OPERATOR) break; // Get new top of stack if (opStack.size() != 0) topOfStack = *static_cast<Operator*>(opStack.back().typeData); } opStack.push_back(tokens[i]); } else if (tokens[i].type == CONSTRUCT) { if (isNewLine(tokens[i])) break; if (tokens[i].data != "(" && tokens[i].data != ")") { throw Error("Illegal construct in expression: \"" + tokens[i].data + "\"", "SyntaxError", tokens[i].line); } else if (tokens[i].data == "(") { opStack.push_back(tokens[i]); } else if (tokens[i].data == ")") { while (opStack.size() != 0 && opStack.back().data != "(") popToOut(); if (opStack.back().data != "(") throw Error("Mismatched parenthesis in expression", "SyntaxError", outStack.back().line); opStack.pop_back(); // Get rid of "(" if (opStack.back().type == FUNCTION) popToOut(); } } } while (opStack.size() > 0) popToOut(); } std::vector<Token> ExpressionNode::getRPNOutput() {return outStack;} void ExpressionNode::buildSubtree(void) { std::vector<Token> stackCopy(outStack); ExpressionChildNode* node; if (stackCopy.size() >= 1) { auto tok = stackCopy.back(); stackCopy.pop_back(); node = new ExpressionChildNode(tok, stackCopy); node->setLineNumber(this->lines); } else { throw std::runtime_error("Empty expression.\n"); } this->children.clear(); this->addChild(node); } std::string ExpressionNode::getNodeType() {return "ExpressionNode";} void ExpressionNode::printTree(int level) { auto top = static_cast<ExpressionChildNode*>(this->getChildren()[0]); top->printTree(level); } ExpressionChildNode::ExpressionChildNode(Token operand): t(operand) {}; ExpressionChildNode::ExpressionChildNode(Token op, std::vector<Token>& operands): t(op) { if (operands.size() == 0) return; auto arity = static_cast<Operator*>(op.typeData)->getArity(); for (int i = 0; i < arity; ++i) { auto next = operands[operands.size() - 1]; if (next.type == OPERATOR) { operands.pop_back(); auto branch = new ExpressionChildNode(next, operands); branch->setLineNumber(op.line); this->addChild(branch); } else { operands.pop_back(); auto leaf = new ExpressionChildNode(next); leaf->setLineNumber(op.line); this->addChild(leaf); } } }; std::string ExpressionChildNode::getNodeType() {return "ExpressionChildNode";} void ExpressionChildNode::printTree(int level) { printIndent(level); print(this->t, "\n"); for (auto child : this->getChildren()) { static_cast<ExpressionChildNode*>(child)->printTree(level + 1); } } BlockNode::BlockNode() {} std::string BlockNode::getNodeType() {return "BlockNode";} void BlockNode::printTree(int level) { printIndent(level); print("BlockNode\n"); for (auto node : children) { node->printTree(level + 1); } } ConditionalNode::ConditionalNode(ExpressionNode* condition, BlockNode* trueBlock, BlockNode* falseBlock) { this->children.push_back(condition); this->children.push_back(trueBlock); this->children.push_back(falseBlock); condition->setParent(this); trueBlock->setParent(this); falseBlock->setParent(this); } ExpressionNode* ConditionalNode::getCondition() {return dynamic_cast<ExpressionNode*>(children[0]);} BlockNode* ConditionalNode::getTrueBlock() {return dynamic_cast<BlockNode*>(children[1]);} BlockNode* ConditionalNode::getFalseBlock() {return dynamic_cast<BlockNode*>(children[2]);} void ConditionalNode::addChild(ASTNode* child) { children[this->block]->addChild(child); } void ConditionalNode::nextBlock() { static bool wasCalled = false; if (!wasCalled) { wasCalled = true; this->block++; } else throw Error("Multiple else statements", "SyntaxError", children[2]->getLineNumber()); } std::string ConditionalNode::getNodeType() {return "ConditionalNode";} void ConditionalNode::printTree(int level) { printIndent(level); print("Condition\n"); this->getCondition()->printTree(level + 1); } WhileNode::WhileNode(ExpressionNode* condition, BlockNode* loop) { this->children.push_back(condition); this->children.push_back(loop); condition->setParent(this); loop->setParent(this); } ExpressionNode* WhileNode::getCondition() {return dynamic_cast<ExpressionNode*>(children[0]);} BlockNode* WhileNode::getLoopNode() {return dynamic_cast<BlockNode*>(children[1]);} void WhileNode::addChild(ASTNode* child) { children[1]->addChild(child); } std::string WhileNode::getNodeType() {return "WhileNode";} void WhileNode::printTree(int level) { printIndent(level); print("While Condition\n"); this->getCondition()->printTree(level + 1); } AST::AbstractSyntaxTree() { Type* integerType = new Type(std::string("Integer"), { // Static members {"MAX_VALUE", new Member(new Variable(new Integer(LLONG_MAX), {}), PUBLIC)}, {"MIN_VALUE", new Member(new Variable(new Integer(LLONG_MIN), {}), PUBLIC)} }, { // Instance members // TODO add members }); (*root.getScope())[std::string("Integer")] = new Variable(integerType, {}); // Do not allow assignment by not specifying any allowed types for the Variable Type* floatType = new Type(std::string("Float"), { // Static members {"MAX_VALUE", new Member(new Variable(new Float(FLT_MAX), {}), PUBLIC)}, {"MIN_VALUE", new Member(new Variable(new Float(FLT_MIN), {}), PUBLIC)} }, { // Instance members // TODO add members }); (*root.getScope())[std::string("Float")] = new Variable(floatType, {}); Type* stringType = new Type(std::string("String"), { // Static members }, { // Instance members // TODO add members }); (*root.getScope())[std::string("String")] = new Variable(stringType, {}); Type* booleanType = new Type(std::string("Boolean"), { // Static members }, { // Instance members // TODO add members }); (*root.getScope())[std::string("Boolean")] = new Variable(booleanType, {}); Type* functionType = new Type(std::string("Function"), { // Static members }, { // Instance members // TODO add members }); (*root.getScope())[std::string("Function")] = new Variable(functionType, {}); } void AST::addRootChild(ASTNode* node) { root.addChild(node); } ChildrenNodes AST::getRootChildren() { return root.getChildren(); } } /* namespace lang */ <|endoftext|>
<commit_before>/****************************************************************************** This source file is part of the Avogadro project. Copyright 2013 Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 "obfileformat.h" #include "obprocess.h" #include <avogadro/io/cmlformat.h> #include <nlohmann/json.hpp> #include <QtCore/QCoreApplication> #include <QtCore/QFileInfo> #include <QtCore/QTimer> using json = nlohmann::json; namespace Avogadro { namespace QtPlugins { /** * @brief The ProcessListener class allows synchronous use of OBProcess. */ class OBFileFormat::ProcessListener : public QObject { Q_OBJECT public: ProcessListener() : QObject(), m_finished(false) {} bool waitForOutput(QByteArray& output, int msTimeout = 120000) { if (!wait(msTimeout)) return false; // success! output = m_output; return true; } public slots: void responseReceived(const QByteArray& output) { m_finished = true; m_output = output; } private: bool wait(int msTimeout) { QTimer timer; timer.start(msTimeout); while (timer.isActive() && !m_finished) qApp->processEvents(QEventLoop::AllEvents, 500); return m_finished; } OBProcess* m_process; bool m_finished; QByteArray m_output; }; OBFileFormat::OBFileFormat(const std::string& name_, const std::string& identifier_, const std::string& description_, const std::string& specificationUrl_, const std::vector<std::string> fileExtensions_, const std::vector<std::string> mimeTypes_, bool fileOnly_) : Io::FileFormat(), m_description(description_), m_fileExtensions(fileExtensions_), m_mimeTypes(mimeTypes_), m_identifier(identifier_), m_name(name_), m_specificationUrl(specificationUrl_), m_fileOnly(fileOnly_) { } OBFileFormat::~OBFileFormat() { } bool OBFileFormat::read(std::istream& in, Core::Molecule& molecule) { json opts; if (!options().empty()) opts = json::parse(options(), nullptr, false); else opts = json::object(); // Allow blocking until the read is completed. OBProcess proc; ProcessListener listener; QObject::connect(&proc, SIGNAL(convertFinished(QByteArray)), &listener, SLOT(responseReceived(QByteArray))); // Just grab the first file extension from the list -- all extensions for a // given format map to the same parsers in OB. if (m_fileExtensions.empty()) { appendError("Internal error: No file extensions set."); return false; } // If we are reading a pure-2D format, generate 3D coordinates: QStringList options; QStringList formats2D; formats2D << "smi" << "inchi" << "can"; if (formats2D.contains(QString::fromStdString(m_fileExtensions.front()))) options << "--gen3d"; // Check if we have extra arguments for open babel json extraArgs = opts.value("arguments", json::object()); if (extraArgs.is_array()) { for (const auto& arg : extraArgs) { if (arg.is_string()) options << arg.get<std::string>().c_str(); } } if (!m_fileOnly) { // Determine length of data in.seekg(0, std::ios_base::end); std::istream::pos_type length = in.tellg(); in.seekg(0, std::ios_base::beg); in.clear(); // Extract char data QByteArray input; input.resize(static_cast<int>(length)); in.read(input.data(), length); if (in.gcount() != length) { appendError("Error reading stream into buffer!"); return false; } // Perform the conversion. if (!proc.convert(input, QString::fromStdString(m_fileExtensions.front()), "cml", options)) { appendError("OpenBabel conversion failed!"); return false; } } else { // Can only read files. Need absolute path. QString filename = QString::fromStdString(fileName()); if (!QFileInfo(filename).isAbsolute()) { appendError("Internal error -- filename must be absolute! " + filename.toStdString()); return false; } // Perform the conversion. if (!proc.convert(filename, QString::fromStdString(m_fileExtensions.front()), "cml", options)) { appendError("OpenBabel conversion failed!"); return false; } } QByteArray cmlOutput; if (!listener.waitForOutput(cmlOutput)) { appendError(std::string("Conversion timed out.")); return false; } if (cmlOutput.isEmpty()) { appendError(std::string("OpenBabel error: conversion failed.")); return false; } Io::CmlFormat cmlReader; if (!cmlReader.readString(std::string(cmlOutput.constData()), molecule)) { appendError(std::string("Error while reading OpenBabel-generated CML:")); appendError(cmlReader.error()); return false; } return true; } bool OBFileFormat::write(std::ostream& out, const Core::Molecule& molecule) { json opts; if (!options().empty()) opts = json::parse(options(), nullptr, false); else opts = json::object(); // Check if we have extra arguments for open babel QStringList options; json extraArgs = opts.value("arguments", json::object()); if (extraArgs.is_array()) { for (const auto& arg : extraArgs) { if (arg.is_string()) options << arg.get<std::string>().c_str(); } } // Generate CML to give to OpenBabel std::string cml; Io::CmlFormat cmlWriter; if (!cmlWriter.writeString(cml, molecule)) { appendError(std::string("Error while writing CML:")); appendError(cmlWriter.error()); return false; } // Block until the OpenBabel conversion finishes: OBProcess proc; ProcessListener listener; QObject::connect(&proc, SIGNAL(convertFinished(QByteArray)), &listener, SLOT(responseReceived(QByteArray))); // Just grab the first file extension from the list -- all extensions for a // given format map to the same parsers in OB. if (m_fileExtensions.empty()) { appendError("Internal error: No file extensions set."); return false; } proc.convert(QByteArray(cml.c_str()), "cml", QString::fromStdString(m_fileExtensions.front()), options); QByteArray output; if (!listener.waitForOutput(output)) { appendError(std::string("Conversion timed out.")); return false; } if (output.isEmpty()) { appendError(std::string("OpenBabel error: conversion failed.")); return false; } out.write(output.constData(), output.size()); return true; } void OBFileFormat::clear() { Io::FileFormat::clear(); } Io::FileFormat* OBFileFormat::newInstance() const { return new OBFileFormat(m_name, m_identifier, m_description, m_specificationUrl, m_fileExtensions, m_mimeTypes, m_fileOnly); } } // namespace QtPlugins } // namespace Avogadro #include "obfileformat.moc" <commit_msg>Make sure to include .smiles in "need to --gen3d"<commit_after>/****************************************************************************** This source file is part of the Avogadro project. Copyright 2013 Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 "obfileformat.h" #include "obprocess.h" #include <avogadro/io/cmlformat.h> #include <nlohmann/json.hpp> #include <QtCore/QCoreApplication> #include <QtCore/QFileInfo> #include <QtCore/QTimer> using json = nlohmann::json; namespace Avogadro { namespace QtPlugins { /** * @brief The ProcessListener class allows synchronous use of OBProcess. */ class OBFileFormat::ProcessListener : public QObject { Q_OBJECT public: ProcessListener() : QObject(), m_finished(false) {} bool waitForOutput(QByteArray& output, int msTimeout = 120000) { if (!wait(msTimeout)) return false; // success! output = m_output; return true; } public slots: void responseReceived(const QByteArray& output) { m_finished = true; m_output = output; } private: bool wait(int msTimeout) { QTimer timer; timer.start(msTimeout); while (timer.isActive() && !m_finished) qApp->processEvents(QEventLoop::AllEvents, 500); return m_finished; } OBProcess* m_process; bool m_finished; QByteArray m_output; }; OBFileFormat::OBFileFormat(const std::string& name_, const std::string& identifier_, const std::string& description_, const std::string& specificationUrl_, const std::vector<std::string> fileExtensions_, const std::vector<std::string> mimeTypes_, bool fileOnly_) : Io::FileFormat(), m_description(description_), m_fileExtensions(fileExtensions_), m_mimeTypes(mimeTypes_), m_identifier(identifier_), m_name(name_), m_specificationUrl(specificationUrl_), m_fileOnly(fileOnly_) { } OBFileFormat::~OBFileFormat() { } bool OBFileFormat::read(std::istream& in, Core::Molecule& molecule) { json opts; if (!options().empty()) opts = json::parse(options(), nullptr, false); else opts = json::object(); // Allow blocking until the read is completed. OBProcess proc; ProcessListener listener; QObject::connect(&proc, SIGNAL(convertFinished(QByteArray)), &listener, SLOT(responseReceived(QByteArray))); // Just grab the first file extension from the list -- all extensions for a // given format map to the same parsers in OB. if (m_fileExtensions.empty()) { appendError("Internal error: No file extensions set."); return false; } // If we are reading a pure-2D format, generate 3D coordinates: QStringList options; QStringList formats2D; formats2D << "smi" << "smiles" << "can" << "inchi" << "wln"; if (formats2D.contains(QString::fromStdString(m_fileExtensions.front()))) options << "--gen3d"; // Check if we have extra arguments for open babel json extraArgs = opts.value("arguments", json::object()); if (extraArgs.is_array()) { for (const auto& arg : extraArgs) { if (arg.is_string()) options << arg.get<std::string>().c_str(); } } if (!m_fileOnly) { // Determine length of data in.seekg(0, std::ios_base::end); std::istream::pos_type length = in.tellg(); in.seekg(0, std::ios_base::beg); in.clear(); // Extract char data QByteArray input; input.resize(static_cast<int>(length)); in.read(input.data(), length); if (in.gcount() != length) { appendError("Error reading stream into buffer!"); return false; } // Perform the conversion. if (!proc.convert(input, QString::fromStdString(m_fileExtensions.front()), "cml", options)) { appendError("OpenBabel conversion failed!"); return false; } } else { // Can only read files. Need absolute path. QString filename = QString::fromStdString(fileName()); if (!QFileInfo(filename).isAbsolute()) { appendError("Internal error -- filename must be absolute! " + filename.toStdString()); return false; } // Perform the conversion. if (!proc.convert(filename, QString::fromStdString(m_fileExtensions.front()), "cml", options)) { appendError("OpenBabel conversion failed!"); return false; } } QByteArray cmlOutput; if (!listener.waitForOutput(cmlOutput)) { appendError(std::string("Conversion timed out.")); return false; } if (cmlOutput.isEmpty()) { appendError(std::string("OpenBabel error: conversion failed.")); return false; } Io::CmlFormat cmlReader; if (!cmlReader.readString(std::string(cmlOutput.constData()), molecule)) { appendError(std::string("Error while reading OpenBabel-generated CML:")); appendError(cmlReader.error()); return false; } return true; } bool OBFileFormat::write(std::ostream& out, const Core::Molecule& molecule) { json opts; if (!options().empty()) opts = json::parse(options(), nullptr, false); else opts = json::object(); // Check if we have extra arguments for open babel QStringList options; json extraArgs = opts.value("arguments", json::object()); if (extraArgs.is_array()) { for (const auto& arg : extraArgs) { if (arg.is_string()) options << arg.get<std::string>().c_str(); } } // Generate CML to give to OpenBabel std::string cml; Io::CmlFormat cmlWriter; if (!cmlWriter.writeString(cml, molecule)) { appendError(std::string("Error while writing CML:")); appendError(cmlWriter.error()); return false; } // Block until the OpenBabel conversion finishes: OBProcess proc; ProcessListener listener; QObject::connect(&proc, SIGNAL(convertFinished(QByteArray)), &listener, SLOT(responseReceived(QByteArray))); // Just grab the first file extension from the list -- all extensions for a // given format map to the same parsers in OB. if (m_fileExtensions.empty()) { appendError("Internal error: No file extensions set."); return false; } proc.convert(QByteArray(cml.c_str()), "cml", QString::fromStdString(m_fileExtensions.front()), options); QByteArray output; if (!listener.waitForOutput(output)) { appendError(std::string("Conversion timed out.")); return false; } if (output.isEmpty()) { appendError(std::string("OpenBabel error: conversion failed.")); return false; } out.write(output.constData(), output.size()); return true; } void OBFileFormat::clear() { Io::FileFormat::clear(); } Io::FileFormat* OBFileFormat::newInstance() const { return new OBFileFormat(m_name, m_identifier, m_description, m_specificationUrl, m_fileExtensions, m_mimeTypes, m_fileOnly); } } // namespace QtPlugins } // namespace Avogadro #include "obfileformat.moc" <|endoftext|>
<commit_before>#ifndef NEU_LAYER_READY_MADE_DEEPCNET_HPP #define NEU_LAYER_READY_MADE_DEEPCNET_HPP //20160129 #include <neu/layer/any_layer.hpp> #include <neu/layer/any_layer_vector.hpp> #include <neu/layer/convolution.hpp> #include <neu/layer/convolution_optimized.hpp> #include <neu/layer/max_pooling.hpp> #include <neu/layer/activation/leaky_rectifier.hpp> #include <neu/layer/bias.hpp> #include <neu/layer/shared_dropout.hpp> #include <neu/layer/batch_normalization.hpp> #include <neu/layer/activation/softmax_loss.hpp> #include <neu/layer/dropout_cpu.hpp> namespace neu { namespace layer { namespace ready_made { template<typename Rng, typename OptGen> decltype(auto) make_deepcnet( std::vector<neu::layer::any_layer>& nn, int batch_size, int input_width, int label_num, int l, int k, scalar dropout_base_probability, Rng&& g, OptGen const& optgen, boost::compute::command_queue& queue) { std::cout << "dro:" << dropout_base_probability << std::endl; for(int li = 0; li < l+1; ++li) { const auto glp = [&nn, li, input_width, k]() { if(li == 0) { return geometric_layer_property{ input_width, 3, 3, (li+1)*k, 1, input_width}; } else { return geometric_layer_property{ output_width(nn), 2, output_channel_num(nn), (li+1)*k, 1, 0}; } }(); // dropout_cpu nn.push_back(neu::layer::dropout_cpu( neu::layer::input_dim(glp), batch_size, 1.f-dropout_base_probability*li, queue)); // dropout /* nn.push_back(neu::layer::dropout( neu::layer::input_dim(glp), batch_size, 1.f-dropout_base_probability*li, queue)); */ // shared_dropout /* nn.push_back(neu::layer::shared_dropout( batch_size, neu::layer::input_dim(glp), glp.input_width*glp.input_width, 1.f-dropout_base_probability*li, queue)); std::cout << li << ": dropout: " << (1.f-dropout_base_probability*li) << std::endl; */ // conv nn.push_back(make_convolution_optimized_xavier( glp, batch_size, g, optgen(neu::layer::filters_size(glp)), queue)); auto output_width = neu::layer::output_width(nn.back()); auto output_channel_num = neu::layer::output_channel_num(nn.back()); // bias //TODO shared /* nn.push_back(neu::layer::make_bias( output_dim(nn), batch_size, [](){ return 0; }, optgen(output_dim(nn)), queue)); */ /* // bn nn.push_back(neu::layer::make_batch_normalization( batch_size, neu::layer::output_dim(nn), optgen(output_dim(nn)), optgen(output_dim(nn)), queue)); */ if(li != l) { // leaky relu nn.push_back(neu::layer::make_leaky_rectifier( neu::layer::output_dim(nn), batch_size, 0.33f)); } if(li != l) { // max pooling neu::layer::geometric_layer_property glp{ output_width, 2, output_channel_num, output_channel_num, 2, 0 }; nn.push_back(neu::layer::max_pooling( glp, batch_size, queue.get_context())); } } // inner_product nn.push_back(neu::layer::make_inner_product_xavier( neu::layer::output_dim(nn), label_num, batch_size, g, optgen(neu::layer::output_dim(nn)*label_num), queue)); // bias //TODO shared /* nn.push_back(neu::layer::make_bias( output_dim(nn), batch_size, [](){ return 0; }, optgen(output_dim(nn)), queue)); */ /* // bn nn.push_back(neu::layer::make_batch_normalization( batch_size, neu::layer::output_dim(nn), optgen(output_dim(nn)), optgen(output_dim(nn)), queue)); */ // softmax_loss nn.push_back(neu::layer::make_softmax_loss( neu::layer::output_dim(nn), batch_size, queue.get_context())); return nn; } } } }// namespace neu #endif //NEU_LAYER_READY_MADE_DEEPCNET_HPP <commit_msg>add wr into deepcnet<commit_after>#ifndef NEU_LAYER_READY_MADE_DEEPCNET_HPP #define NEU_LAYER_READY_MADE_DEEPCNET_HPP //20160129 #include <neu/layer/any_layer.hpp> #include <neu/layer/any_layer_vector.hpp> #include <neu/layer/convolution.hpp> #include <neu/layer/convolution_optimized.hpp> #include <neu/layer/convolution_optimized_wr.hpp> #include <neu/layer/inner_product_wr.hpp> #include <neu/layer/max_pooling.hpp> #include <neu/layer/activation/leaky_rectifier.hpp> #include <neu/layer/bias.hpp> #include <neu/layer/shared_dropout.hpp> #include <neu/layer/batch_normalization.hpp> #include <neu/layer/activation/softmax_loss.hpp> #include <neu/layer/dropout_cpu.hpp> namespace neu { namespace layer { namespace ready_made { template<typename Rng, typename OptGen> decltype(auto) make_deepcnet( std::vector<neu::layer::any_layer>& nn, int batch_size, int input_width, int label_num, int l, int k, scalar dropout_base_probability, Rng&& g, OptGen const& optgen, boost::compute::command_queue& queue) { scalar c = 1.f; std::cout << "dro:" << dropout_base_probability << std::endl; for(int li = 0; li < l+1; ++li) { const auto glp = [&nn, li, input_width, k]() { if(li == 0) { return geometric_layer_property{ input_width, 3, 3, (li+1)*k, 1, input_width}; } else { return geometric_layer_property{ output_width(nn), 2, output_channel_num(nn), (li+1)*k, 1, 0}; } }(); // dropout_cpu nn.push_back(neu::layer::dropout_cpu( neu::layer::input_dim(glp), batch_size, 1.f-dropout_base_probability*li, queue)); // dropout /* nn.push_back(neu::layer::dropout( neu::layer::input_dim(glp), batch_size, 1.f-dropout_base_probability*li, queue)); */ // shared_dropout /* nn.push_back(neu::layer::shared_dropout( batch_size, neu::layer::input_dim(glp), glp.input_width*glp.input_width, 1.f-dropout_base_probability*li, queue)); std::cout << li << ": dropout: " << (1.f-dropout_base_probability*li) << std::endl; */ // conv nn.push_back(make_convolution_optimized_wr_xavier( glp, batch_size, c, g, optgen(neu::layer::filters_size(glp)), queue)); auto output_width = neu::layer::output_width(nn.back()); auto output_channel_num = neu::layer::output_channel_num(nn.back()); // bias //TODO shared /* nn.push_back(neu::layer::make_bias( output_dim(nn), batch_size, [](){ return 0; }, optgen(output_dim(nn)), queue)); */ /* // bn nn.push_back(neu::layer::make_batch_normalization( batch_size, neu::layer::output_dim(nn), optgen(output_dim(nn)), optgen(output_dim(nn)), queue)); */ if(li != l) { // leaky relu nn.push_back(neu::layer::make_leaky_rectifier( neu::layer::output_dim(nn), batch_size, 0.33f)); } if(li != l) { // max pooling neu::layer::geometric_layer_property glp{ output_width, 2, output_channel_num, output_channel_num, 2, 0 }; nn.push_back(neu::layer::max_pooling( glp, batch_size, queue.get_context())); } } // inner_product nn.push_back(neu::layer::make_inner_product_wr_xavier( neu::layer::output_dim(nn), label_num, batch_size, c, g, optgen(neu::layer::output_dim(nn)*label_num), queue)); // bias //TODO shared /* nn.push_back(neu::layer::make_bias( output_dim(nn), batch_size, [](){ return 0; }, optgen(output_dim(nn)), queue)); */ /* // bn nn.push_back(neu::layer::make_batch_normalization( batch_size, neu::layer::output_dim(nn), optgen(output_dim(nn)), optgen(output_dim(nn)), queue)); */ // softmax_loss nn.push_back(neu::layer::make_softmax_loss( neu::layer::output_dim(nn), batch_size, queue.get_context())); return nn; } } } }// namespace neu #endif //NEU_LAYER_READY_MADE_DEEPCNET_HPP <|endoftext|>
<commit_before>// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("Satoshi"); // Client version number #ifdef NEBLIO_REST #define CLIENT_VERSION_SUFFIX "-REST-Enabled" #else #define CLIENT_VERSION_SUFFIX "-TESTNET-BETA" #endif // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 0 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "" # define GIT_COMMIT_DATE "$Format:%cD" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <commit_msg>Remove version suffix<commit_after>// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("Satoshi"); // Client version number #ifdef NEBLIO_REST #define CLIENT_VERSION_SUFFIX "-REST-Enabled" #else #define CLIENT_VERSION_SUFFIX "" #endif // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 0 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "" # define GIT_COMMIT_DATE "$Format:%cD" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <|endoftext|>
<commit_before>#include "cnn/devices.h" #include <boost/algorithm/string.hpp> #include <iostream> #include <unsupported/Eigen/CXX11/Tensor> #include "cnn/cuda.h" #include "cnn/cnn.h" using namespace std; namespace cnn { DeviceMempoolSizes::DeviceMempoolSizes(size_t total_size) { used[0] = total_size/3; used[1] = total_size/3; used[2] = total_size/3; } DeviceMempoolSizes::DeviceMempoolSizes(size_t fx_s, size_t dEdfs_s, size_t ps_s) { used[0] = fx_s; used[1] = dEdfs_s; used[2] = ps_s; } DeviceMempoolSizes::DeviceMempoolSizes(const std::string & descriptor) { vector<string> strs; boost::algorithm::split(strs, descriptor, boost::is_any_of(",")); if(strs.size() == 1) { size_t total_size = stoi(strs[0]); used[0] = total_size/3; used[1] = total_size/3; used[2] = total_size/3; } else if(strs.size() == 3) { used[0] = stoi(strs[0]); used[1] = stoi(strs[1]); used[2] = stoi(strs[2]); } cerr << "used[0] == " << used[0] << endl; cerr << "used[1] == " << used[1] << endl; cerr << "used[2] == " << used[2] << endl; } Device::~Device() {} DeviceMempoolSizes Device::mark(ComputationGraph *cg) { cg->incremental_forward(); // needed so that we actually allocate the needed memory // for all existing nodes. return DeviceMempoolSizes(pools[0]->used, pools[1]->used, pools[2]->used); } void Device::revert(const DeviceMempoolSizes & cp) { assert(cp.used[0] <= pools[0]->used); pools[0]->used = cp.used[0]; assert(cp.used[1] <= pools[1]->used); pools[1]->used = cp.used[1]; assert(cp.used[2] <= pools[2]->used); pools[2]->used = cp.used[2]; } void Device::allocate_tensor(DeviceMempool mp, Tensor & tens) { assert(mp != DeviceMempool::NONE); assert(pools[(int)mp] != nullptr); tens.v = (float*)pools[(int)mp]->allocate(tens.d.size() * sizeof(float)); tens.mem_pool = mp; } #if HAVE_CUDA Device_GPU::Device_GPU(int my_id, const DeviceMempoolSizes & mbs, int device_id) : Device(my_id, DeviceType::GPU, &gpu_mem), cuda_device_id(device_id), gpu_mem(device_id) { CUDA_CHECK(cudaSetDevice(device_id)); CUBLAS_CHECK(cublasCreate(&cublas_handle)); CUBLAS_CHECK(cublasSetPointerMode(cublas_handle, CUBLAS_POINTER_MODE_DEVICE)); kSCALAR_MINUSONE = (float*)gpu_mem.malloc(sizeof(float)); kSCALAR_ONE = (float*)gpu_mem.malloc(sizeof(float)); kSCALAR_ZERO = (float*)gpu_mem.malloc(sizeof(float)); float minusone = -1; CUDA_CHECK(cudaMemcpyAsync(kSCALAR_MINUSONE, &minusone, sizeof(float), cudaMemcpyHostToDevice)); float one = 1; CUDA_CHECK(cudaMemcpyAsync(kSCALAR_ONE, &one, sizeof(float), cudaMemcpyHostToDevice)); float zero = 0; CUDA_CHECK(cudaMemcpyAsync(kSCALAR_ZERO, &zero, sizeof(float), cudaMemcpyHostToDevice)); // Initialize the Eigen device estream = new Eigen::CudaStreamDevice(device_id); edevice = new Eigen::GpuDevice(estream); // this is the big memory allocation. for(size_t i = 0; i < 3; ++i) pools[i] = new AlignedMemoryPool((mbs.used[i] << 20), &gpu_mem); } Device_GPU::~Device_GPU() {} #endif Device_CPU::Device_CPU(int my_id, const DeviceMempoolSizes & mbs, bool shared) : Device(my_id, DeviceType::CPU, &cpu_mem), shmem(mem) { if (shared) shmem = new SharedAllocator(); kSCALAR_MINUSONE = (float*) mem->malloc(sizeof(float)); *kSCALAR_MINUSONE = -1; kSCALAR_ONE = (float*) mem->malloc(sizeof(float)); *kSCALAR_ONE = 1; kSCALAR_ZERO = (float*) mem->malloc(sizeof(float)); *kSCALAR_ZERO = 0; // Initialize the Eigen device edevice = new Eigen::DefaultDevice; // this is the big memory allocation. for(size_t i = 0; i < 3; ++i) pools[i] = new AlignedMemoryPool((mbs.used[i] << 20), &cpu_mem); } Device_CPU::~Device_CPU() {} } // namespace cnn <commit_msg>Removed rougue debugging message<commit_after>#include "cnn/devices.h" #include <boost/algorithm/string.hpp> #include <iostream> #include <unsupported/Eigen/CXX11/Tensor> #include "cnn/cuda.h" #include "cnn/cnn.h" using namespace std; namespace cnn { DeviceMempoolSizes::DeviceMempoolSizes(size_t total_size) { used[0] = total_size/3; used[1] = total_size/3; used[2] = total_size/3; } DeviceMempoolSizes::DeviceMempoolSizes(size_t fx_s, size_t dEdfs_s, size_t ps_s) { used[0] = fx_s; used[1] = dEdfs_s; used[2] = ps_s; } DeviceMempoolSizes::DeviceMempoolSizes(const std::string & descriptor) { vector<string> strs; boost::algorithm::split(strs, descriptor, boost::is_any_of(",")); if(strs.size() == 1) { size_t total_size = stoi(strs[0]); used[0] = total_size/3; used[1] = total_size/3; used[2] = total_size/3; } else if(strs.size() == 3) { used[0] = stoi(strs[0]); used[1] = stoi(strs[1]); used[2] = stoi(strs[2]); } } Device::~Device() {} DeviceMempoolSizes Device::mark(ComputationGraph *cg) { cg->incremental_forward(); // needed so that we actually allocate the needed memory // for all existing nodes. return DeviceMempoolSizes(pools[0]->used, pools[1]->used, pools[2]->used); } void Device::revert(const DeviceMempoolSizes & cp) { assert(cp.used[0] <= pools[0]->used); pools[0]->used = cp.used[0]; assert(cp.used[1] <= pools[1]->used); pools[1]->used = cp.used[1]; assert(cp.used[2] <= pools[2]->used); pools[2]->used = cp.used[2]; } void Device::allocate_tensor(DeviceMempool mp, Tensor & tens) { assert(mp != DeviceMempool::NONE); assert(pools[(int)mp] != nullptr); tens.v = (float*)pools[(int)mp]->allocate(tens.d.size() * sizeof(float)); tens.mem_pool = mp; } #if HAVE_CUDA Device_GPU::Device_GPU(int my_id, const DeviceMempoolSizes & mbs, int device_id) : Device(my_id, DeviceType::GPU, &gpu_mem), cuda_device_id(device_id), gpu_mem(device_id) { CUDA_CHECK(cudaSetDevice(device_id)); CUBLAS_CHECK(cublasCreate(&cublas_handle)); CUBLAS_CHECK(cublasSetPointerMode(cublas_handle, CUBLAS_POINTER_MODE_DEVICE)); kSCALAR_MINUSONE = (float*)gpu_mem.malloc(sizeof(float)); kSCALAR_ONE = (float*)gpu_mem.malloc(sizeof(float)); kSCALAR_ZERO = (float*)gpu_mem.malloc(sizeof(float)); float minusone = -1; CUDA_CHECK(cudaMemcpyAsync(kSCALAR_MINUSONE, &minusone, sizeof(float), cudaMemcpyHostToDevice)); float one = 1; CUDA_CHECK(cudaMemcpyAsync(kSCALAR_ONE, &one, sizeof(float), cudaMemcpyHostToDevice)); float zero = 0; CUDA_CHECK(cudaMemcpyAsync(kSCALAR_ZERO, &zero, sizeof(float), cudaMemcpyHostToDevice)); // Initialize the Eigen device estream = new Eigen::CudaStreamDevice(device_id); edevice = new Eigen::GpuDevice(estream); // this is the big memory allocation. for(size_t i = 0; i < 3; ++i) pools[i] = new AlignedMemoryPool((mbs.used[i] << 20), &gpu_mem); } Device_GPU::~Device_GPU() {} #endif Device_CPU::Device_CPU(int my_id, const DeviceMempoolSizes & mbs, bool shared) : Device(my_id, DeviceType::CPU, &cpu_mem), shmem(mem) { if (shared) shmem = new SharedAllocator(); kSCALAR_MINUSONE = (float*) mem->malloc(sizeof(float)); *kSCALAR_MINUSONE = -1; kSCALAR_ONE = (float*) mem->malloc(sizeof(float)); *kSCALAR_ONE = 1; kSCALAR_ZERO = (float*) mem->malloc(sizeof(float)); *kSCALAR_ZERO = 0; // Initialize the Eigen device edevice = new Eigen::DefaultDevice; // this is the big memory allocation. for(size_t i = 0; i < 3; ++i) pools[i] = new AlignedMemoryPool((mbs.used[i] << 20), &cpu_mem); } Device_CPU::~Device_CPU() {} } // namespace cnn <|endoftext|>
<commit_before>#include "Pid.hpp" #include <cstring> #include <stdio.h> #include <iostream> #include <math.h> using namespace std; Pid::Pid(float p, float i, float d, unsigned int windup) { _windupLoc = 0; _errSum = 0; _oldErr = 0; _lastErr = 0; kp = p; ki = i; kd = d; _windup = 0; setWindup(windup); } Pid::~Pid() { if (_oldErr) { delete[] _oldErr; _oldErr = nullptr; } } void Pid::setWindup(unsigned int w) { if (w > 0) { if (w != _windup) { _windup = w; _oldErr = new float[_windup]; memset(_oldErr, 0, sizeof(float)*_windup); } } else { if (_oldErr) delete[] _oldErr; _oldErr = nullptr; } } float Pid::run(const float err) { if (isnan(err)) { return 0; } float dErr = err - _lastErr; _lastErr = err; _errSum += err; if (_oldErr) { _errSum -= _oldErr[_windupLoc]; _oldErr[_windupLoc] = err; _windupLoc = (_windupLoc + 1) % _windup; } return (err * kp) + (_errSum * ki) + (dErr * kd); } void Pid::clearWindup() { if (_oldErr) { for (unsigned int i=0 ; i<_windup ; ++i) { _oldErr[i] = 0; } } } <commit_msg>Fix Memleak and stuff<commit_after>#include "Pid.hpp" #include <cstring> #include <stdio.h> #include <iostream> #include <math.h> using namespace std; Pid::Pid(float p, float i, float d, unsigned int windup) { _windupLoc = 0; _errSum = 0; _oldErr = 0; _lastErr = 0; kp = p; ki = i; kd = d; _windup = 0; setWindup(windup); } Pid::~Pid() { if (_oldErr) { delete[] _oldErr; _oldErr = nullptr; } } void Pid::setWindup(unsigned int w) { if (w != _windup) { if (_oldErr) delete[] _oldErr; if (w > 0) { if (w != _windup) { _windup = w; _oldErr = new float[_windup](); _errSum=0; } } } } float Pid::run(const float err) { if (isnan(err)) { return 0; } float dErr = err - _lastErr; _lastErr = err; _errSum += err; if (_oldErr) { _errSum -= _oldErr[_windupLoc]; _oldErr[_windupLoc] = err; _windupLoc = (_windupLoc + 1) % _windup; } return (err * kp) + (_errSum * ki) + (dErr * kd); } void Pid::clearWindup() { if (_oldErr) { memset(_oldErr, 0, sizeof(float)*_windup); } } <|endoftext|>
<commit_before>#include "complex.hpp" #include <QStringList> #include "debug.hpp" const Complex Complex::Zero = Complex::fromReal(Real::Zero); const Complex Complex::One = Complex::fromReal(Real::One); const Complex Complex::I = Complex::fromReal(Real::Zero, Real::One); QString Complex::toString(int p) const { QString r = _r.toString(p); QString i = _i.toString(p); if (r == "0") { if (i == "0") { return "0"; } else if (i == "1") { return "i"; } else if (i == "-1") { return "-i"; } else { return i; } } else { if (i == "0") { return r; } else if (i == "1") { return QString("%1 + i").arg(r); } else if (i == "-1") { return QString("%1 - i").arg(r); } else { if (Real::isSmallerThan(imag(), Real::fromDouble(0))) { return QString("%1 - %2i").arg(_r.toString(p)).arg(Real::mul(_i, Real::MinusOne).toString(p)); } else { return QString("%1 + %2i").arg(_r.toString(p)).arg(_i.toString(p)); } } } } Complex Complex::fromString(const QString& s_) { QString s = s_.trimmed(); Real r, i; if (s.contains('i') == false) { if (s.startsWith('-') || s.startsWith('+')) { ASSERT(s.right(s.size()-1).contains('-') == false && s.right(s.size()-1).contains('+') == false); } else { ASSERT(s.contains('-') == false && s.contains('+') == false); } r.set(Real::fromString(s)); i.set(Real::Zero); } else { if (s.startsWith('-')) { if (s.indexOf('-', 1) == -1 && s.indexOf('+', 1) == -1) { // -#i s.prepend("0"); // 0-#i } } if (s.contains('-') == false && s.contains('+') == false) { // #i s.prepend("+"); //+#i } bool rneg = s.startsWith('-'); if (rneg) {s.remove(0, 1);} char sep = s.contains('-') ? '-' : '+'; QStringList l = s.split(sep); ASSERT(l.size() == 2); l[0] = l[0].trimmed(); if (l[0].isEmpty()) {l[0] = "0";} l[1] = l[1].remove('i').trimmed(); if (l[1].isEmpty()) {l[1] = "1";} r.set(Real::fromString(rneg ? "-" + l[0] : l[0])); i.set(sep == '+' ? Real::fromString(l[1]) : Real::mul(Real::fromString(l[1]), Real::MinusOne)); } return Complex::fromReal(r, i); } QDebug operator<<(QDebug s, const Complex& c) { s << c.toString(); return s; } <commit_msg>fix: wrong string formatting<commit_after>#include "complex.hpp" #include <QStringList> #include "debug.hpp" const Complex Complex::Zero = Complex::fromReal(Real::Zero); const Complex Complex::One = Complex::fromReal(Real::One); const Complex Complex::I = Complex::fromReal(Real::Zero, Real::One); QString Complex::toString(int p) const { QString r = _r.toString(p); QString i = _i.toString(p); if (r == "0") { if (i == "0") { return "0"; } else if (i == "1") { return "i"; } else if (i == "-1") { return "-i"; } else { return i + "i"; } } else { if (i == "0") { return r; } else if (i == "1") { return QString("%1 + i").arg(r); } else if (i == "-1") { return QString("%1 - i").arg(r); } else { if (Real::isSmallerThan(imag(), Real::fromDouble(0))) { return QString("%1 - %2i").arg(_r.toString(p)).arg(Real::mul(_i, Real::MinusOne).toString(p)); } else { return QString("%1 + %2i").arg(_r.toString(p)).arg(_i.toString(p)); } } } } Complex Complex::fromString(const QString& s_) { QString s = s_.trimmed(); Real r, i; if (s.contains('i') == false) { if (s.startsWith('-') || s.startsWith('+')) { ASSERT(s.right(s.size()-1).contains('-') == false && s.right(s.size()-1).contains('+') == false); } else { ASSERT(s.contains('-') == false && s.contains('+') == false); } r.set(Real::fromString(s)); i.set(Real::Zero); } else { if (s.startsWith('-')) { if (s.indexOf('-', 1) == -1 && s.indexOf('+', 1) == -1) { // -#i s.prepend("0"); // 0-#i } } if (s.contains('-') == false && s.contains('+') == false) { // #i s.prepend("+"); //+#i } bool rneg = s.startsWith('-'); if (rneg) {s.remove(0, 1);} char sep = s.contains('-') ? '-' : '+'; QStringList l = s.split(sep); ASSERT(l.size() == 2); l[0] = l[0].trimmed(); if (l[0].isEmpty()) {l[0] = "0";} l[1] = l[1].remove('i').trimmed(); if (l[1].isEmpty()) {l[1] = "1";} r.set(Real::fromString(rneg ? "-" + l[0] : l[0])); i.set(sep == '+' ? Real::fromString(l[1]) : Real::mul(Real::fromString(l[1]), Real::MinusOne)); } return Complex::fromReal(r, i); } QDebug operator<<(QDebug s, const Complex& c) { s << c.toString(); return s; } <|endoftext|>
<commit_before>#ifndef _PNMC_PN_NET_HH_ #define _PNMC_PN_NET_HH_ #pragma GCC diagnostic push #if defined(__GNUC__) && !defined(__clang__) # pragma GCC diagnostic ignored "-Wunused-local-typedefs" #endif #include <boost/multi_index_container.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/identity.hpp> #include <boost/multi_index/member.hpp> #include <boost/multi_index/sequenced_index.hpp> #pragma GCC diagnostic pop #include "pn/module.hh" #include "pn/place.hh" #include "pn/transition.hh" namespace pnmc { namespace pn { /*------------------------------------------------------------------------------------------------*/ using namespace boost::multi_index; /*------------------------------------------------------------------------------------------------*/ struct net { private: /// @brief A tag to identify the view ordered by insertion order for boost::multi_index. struct insertion_index{}; /// @brief A tag to identify the view ordered by idendifiers for boost::multi_index. struct id_index{}; /// @brief A tag to identify the view ordered by markings for boost::multi_index. struct marking_index{}; /// @brief A tag to identify the view ordered by indices for boost::multi_index. struct index_index{}; public: /// @brief The type of the set of all places. typedef multi_index_container< place , indexed_by< // keep insertion order sequenced<tag<insertion_index>> // sort by id , ordered_unique< tag<id_index> , member<place, const std::string, &place::id>> // sort by marking , ordered_non_unique< tag<marking_index> , member<place, unsigned int, &place::marking>> > > places_type; /// @brief The type of the set of all transitions. typedef multi_index_container< transition , indexed_by< // sort by id ordered_unique< tag<id_index> , member<transition, const std::string, &transition::id>> // sort by index , ordered_unique< tag<index_index> , member<transition, const std::size_t, &transition::index>> > > transitions_type; /// @brief The net's name. std::string name; /// @brief The set of places. places_type places_set; /// @brief The set of transitions. transitions_type transitions_set; /// @brief The hierarchical description, if any, of this Petri net. module modules; /// @brief Default constructor. net(); /// @brief Add a place. /// /// If the place already exist, its marking is updated. const place& add_place(const std::string& id, unsigned int marking); /// @brief Add a transition. /// /// If the transition already exists, no operation is done. const transition& add_transition(const std::string& tid); /// @brief Add a post place to a transition. /// /// If the place doesn't exist, it is created with a marking set to 0. void add_post_place(const std::string& tid, const std::string& post, unsigned int marking); /// @brief Add a pre place to a transition. /// /// If the place doesn't exist, it is created with a marking set to 0. void add_pre_place(const std::string& tid, const std::string& pre, unsigned int marking); /// @brief Return all places by insertion order. const places_type::index<insertion_index>::type& places() const noexcept; /// @brief Return all places by identifier. const places_type::index<id_index>::type& places_by_id() const noexcept; /// @brief Return all transitions. const transitions_type::index<id_index>::type& transitions() const noexcept; /// @brief Get a transition using its index. const transition& get_transition_by_index(std::size_t index) const; /// @brief Add a time interval to a transition. void add_time_interval(const std::string& tid, unsigned int low, unsigned int high); }; /*------------------------------------------------------------------------------------------------*/ }} // namespace pnmc::pn #endif // _PNMC_PN_NET_HH_ <commit_msg>Code cleanup.<commit_after>#ifndef _PNMC_PN_NET_HH_ #define _PNMC_PN_NET_HH_ #pragma GCC diagnostic push #if defined(__GNUC__) && !defined(__clang__) # pragma GCC diagnostic ignored "-Wunused-local-typedefs" #endif #include <boost/multi_index_container.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/identity.hpp> #include <boost/multi_index/member.hpp> #include <boost/multi_index/sequenced_index.hpp> #pragma GCC diagnostic pop #include "pn/module.hh" #include "pn/place.hh" #include "pn/transition.hh" namespace pnmc { namespace pn { /*------------------------------------------------------------------------------------------------*/ using namespace boost::multi_index; /*------------------------------------------------------------------------------------------------*/ struct net { private: /// @brief A tag to identify the view ordered by insertion order for boost::multi_index. struct insertion_index{}; /// @brief A tag to identify the view ordered by identifiers for boost::multi_index. struct id_index{}; /// @brief A tag to identify the view ordered by markings for boost::multi_index. struct marking_index{}; /// @brief A tag to identify the view ordered by indices for boost::multi_index. struct index_index{}; public: /// @brief The type of the set of all places. using places_type = multi_index_container< place , indexed_by< // keep insertion order sequenced<tag<insertion_index>> // sort by id , ordered_unique< tag<id_index> , member<place, const std::string, &place::id>> // sort by marking , ordered_non_unique< tag<marking_index> , member<place, unsigned int, &place::marking>>>>; /// @brief The type of the set of all transitions. using transitions_type = multi_index_container< transition , indexed_by< // sort by id ordered_unique< tag<id_index> , member<transition, const std::string, &transition::id>> // sort by index , ordered_unique< tag<index_index> , member<transition, const std::size_t, &transition::index>>>>; /// @brief The net's name. std::string name; /// @brief The set of places. places_type places_set; /// @brief The set of transitions. transitions_type transitions_set; /// @brief The hierarchical description, if any, of this Petri net. module modules; /// @brief Default constructor. net(); /// @brief Add a place. /// /// If the place already exist, its marking is updated. const place& add_place(const std::string& id, unsigned int marking); /// @brief Add a transition. /// /// If the transition already exists, no operation is done. const transition& add_transition(const std::string& tid); /// @brief Add a post place to a transition. /// /// If the place doesn't exist, it is created with a marking set to 0. void add_post_place(const std::string& tid, const std::string& post, unsigned int marking); /// @brief Add a pre place to a transition. /// /// If the place doesn't exist, it is created with a marking set to 0. void add_pre_place(const std::string& tid, const std::string& pre, unsigned int marking); /// @brief Return all places by insertion order. const places_type::index<insertion_index>::type& places() const noexcept; /// @brief Return all places by identifier. const places_type::index<id_index>::type& places_by_id() const noexcept; /// @brief Return all transitions. const transitions_type::index<id_index>::type& transitions() const noexcept; /// @brief Get a transition using its index. const transition& get_transition_by_index(std::size_t index) const; /// @brief Add a time interval to a transition. void add_time_interval(const std::string& tid, unsigned int low, unsigned int high); }; /*------------------------------------------------------------------------------------------------*/ }} // namespace pnmc::pn #endif // _PNMC_PN_NET_HH_ <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkInteractorStyleSwitch.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen 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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 REGENTS 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. =========================================================================*/ #include "vtkInteractorStyleSwitch.h" #include "vtkObjectFactory.h" //---------------------------------------------------------------------------- vtkInteractorStyleSwitch *vtkInteractorStyleSwitch::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkInteractorStyleSwitch"); if(ret) { return (vtkInteractorStyleSwitch*)ret; } // If the factory was unable to create the object, then create it here. return new vtkInteractorStyleSwitch; } //---------------------------------------------------------------------------- vtkInteractorStyleSwitch::vtkInteractorStyleSwitch() { this->JoystickActor = vtkInteractorStyleJoystickActor::New(); this->JoystickCamera = vtkInteractorStyleJoystickCamera::New(); this->TrackballActor = vtkInteractorStyleTrackballActor::New(); this->TrackballCamera = vtkInteractorStyleTrackballCamera::New(); this->JoystickOrTrackball = VTKIS_JOYSTICK; this->CameraOrActor = VTKIS_CAMERA; } //---------------------------------------------------------------------------- vtkInteractorStyleSwitch::~vtkInteractorStyleSwitch() { this->JoystickActor->Delete(); this->JoystickActor = NULL; this->JoystickCamera->Delete(); this->JoystickCamera = NULL; this->TrackballActor->Delete(); this->TrackballActor = NULL; this->TrackballCamera->Delete(); this->TrackballCamera = NULL; } //---------------------------------------------------------------------------- void vtkInteractorStyleSwitch::OnChar(int ctrl, int shift, char keycode, int repeatcount) { switch (keycode) { case 'j': case 'J': this->JoystickOrTrackball = VTKIS_JOYSTICK; break; case 't': case 'T': this->JoystickOrTrackball = VTKIS_TRACKBALL; break; case 'c': case 'C': this->CameraOrActor = VTKIS_CAMERA; break; case 'a': case 'A': this->CameraOrActor = VTKIS_ACTOR; break; default: vtkInteractorStyle::OnChar(ctrl, shift, keycode, repeatcount); break; } } //---------------------------------------------------------------------------- void vtkInteractorStyleSwitch::OnMouseMove(int ctrl, int shift, int x, int y) { if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_CAMERA) { this->JoystickCamera->OnMouseMove(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_ACTOR) { this->JoystickActor->OnMouseMove(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_CAMERA) { this->TrackballCamera->OnMouseMove(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_ACTOR) { this->TrackballActor->OnMouseMove(ctrl, shift, x, y); } } //---------------------------------------------------------------------------- void vtkInteractorStyleSwitch::OnLeftButtonDown(int ctrl, int shift, int x, int y) { if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_CAMERA) { this->JoystickCamera->OnLeftButtonDown(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_ACTOR) { this->JoystickActor->OnLeftButtonDown(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_CAMERA) { this->TrackballCamera->OnLeftButtonDown(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_ACTOR) { this->TrackballActor->OnLeftButtonDown(ctrl, shift, x, y); } } //---------------------------------------------------------------------------- void vtkInteractorStyleSwitch::OnLeftButtonUp(int ctrl, int shift, int x, int y) { if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_CAMERA) { this->JoystickCamera->OnLeftButtonUp(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_ACTOR) { this->JoystickActor->OnLeftButtonUp(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_CAMERA) { this->TrackballCamera->OnLeftButtonUp(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_ACTOR) { this->TrackballActor->OnLeftButtonUp(ctrl, shift, x, y); } } //---------------------------------------------------------------------------- void vtkInteractorStyleSwitch::OnMiddleButtonDown(int ctrl, int shift, int x, int y) { if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_CAMERA) { this->JoystickCamera->OnMiddleButtonDown(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_ACTOR) { this->JoystickActor->OnMiddleButtonDown(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_CAMERA) { this->TrackballCamera->OnMiddleButtonDown(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_ACTOR) { this->TrackballActor->OnMiddleButtonDown(ctrl, shift, x, y); } } //---------------------------------------------------------------------------- void vtkInteractorStyleSwitch::OnMiddleButtonUp(int ctrl, int shift, int x, int y) { if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_CAMERA) { this->JoystickCamera->OnMiddleButtonUp(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_ACTOR) { this->JoystickActor->OnMiddleButtonUp(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_CAMERA) { this->TrackballCamera->OnMiddleButtonUp(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_ACTOR) { this->TrackballActor->OnMiddleButtonUp(ctrl, shift, x, y); } } //---------------------------------------------------------------------------- void vtkInteractorStyleSwitch::OnRightButtonDown(int ctrl, int shift, int x, int y) { if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_CAMERA) { this->JoystickCamera->OnRightButtonDown(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_ACTOR) { this->JoystickActor->OnRightButtonDown(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_CAMERA) { this->TrackballCamera->OnRightButtonDown(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_ACTOR) { this->TrackballActor->OnRightButtonDown(ctrl, shift, x, y); } } //---------------------------------------------------------------------------- void vtkInteractorStyleSwitch::OnRightButtonUp(int ctrl, int shift, int x, int y) { if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_CAMERA) { this->JoystickCamera->OnRightButtonUp(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_ACTOR) { this->JoystickActor->OnRightButtonUp(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_CAMERA) { this->TrackballCamera->OnRightButtonUp(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_ACTOR) { this->TrackballActor->OnRightButtonUp(ctrl, shift, x, y); } } //---------------------------------------------------------------------------- void vtkInteractorStyleSwitch::SetInteractor(vtkRenderWindowInteractor *iren) { this->JoystickActor->SetInteractor(iren); this->JoystickCamera->SetInteractor(iren); this->TrackballActor->SetInteractor(iren); this->TrackballCamera->SetInteractor(iren); this->vtkInteractorStyle::SetInteractor(iren); } //---------------------------------------------------------------------------- void vtkInteractorStyleSwitch::OnTimer(void) { if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_CAMERA) { this->JoystickCamera->OnTimer(); } else if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_ACTOR) { this->JoystickActor->OnTimer(); } } <commit_msg>BUG: set the last position on mouse move, so Key events can use it.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkInteractorStyleSwitch.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen 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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 REGENTS 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. =========================================================================*/ #include "vtkInteractorStyleSwitch.h" #include "vtkObjectFactory.h" //---------------------------------------------------------------------------- vtkInteractorStyleSwitch *vtkInteractorStyleSwitch::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkInteractorStyleSwitch"); if(ret) { return (vtkInteractorStyleSwitch*)ret; } // If the factory was unable to create the object, then create it here. return new vtkInteractorStyleSwitch; } //---------------------------------------------------------------------------- vtkInteractorStyleSwitch::vtkInteractorStyleSwitch() { this->JoystickActor = vtkInteractorStyleJoystickActor::New(); this->JoystickCamera = vtkInteractorStyleJoystickCamera::New(); this->TrackballActor = vtkInteractorStyleTrackballActor::New(); this->TrackballCamera = vtkInteractorStyleTrackballCamera::New(); this->JoystickOrTrackball = VTKIS_JOYSTICK; this->CameraOrActor = VTKIS_CAMERA; } //---------------------------------------------------------------------------- vtkInteractorStyleSwitch::~vtkInteractorStyleSwitch() { this->JoystickActor->Delete(); this->JoystickActor = NULL; this->JoystickCamera->Delete(); this->JoystickCamera = NULL; this->TrackballActor->Delete(); this->TrackballActor = NULL; this->TrackballCamera->Delete(); this->TrackballCamera = NULL; } //---------------------------------------------------------------------------- void vtkInteractorStyleSwitch::OnChar(int ctrl, int shift, char keycode, int repeatcount) { switch (keycode) { case 'j': case 'J': this->JoystickOrTrackball = VTKIS_JOYSTICK; break; case 't': case 'T': this->JoystickOrTrackball = VTKIS_TRACKBALL; break; case 'c': case 'C': this->CameraOrActor = VTKIS_CAMERA; break; case 'a': case 'A': this->CameraOrActor = VTKIS_ACTOR; break; default: vtkInteractorStyle::OnChar(ctrl, shift, keycode, repeatcount); break; } } //---------------------------------------------------------------------------- void vtkInteractorStyleSwitch::OnMouseMove(int ctrl, int shift, int x, int y) { // Call the parent so the LastPos is set vtkInteractorStyle::OnMouseMove(ctrl, shift, x, y); if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_CAMERA) { this->JoystickCamera->OnMouseMove(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_ACTOR) { this->JoystickActor->OnMouseMove(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_CAMERA) { this->TrackballCamera->OnMouseMove(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_ACTOR) { this->TrackballActor->OnMouseMove(ctrl, shift, x, y); } } //---------------------------------------------------------------------------- void vtkInteractorStyleSwitch::OnLeftButtonDown(int ctrl, int shift, int x, int y) { if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_CAMERA) { this->JoystickCamera->OnLeftButtonDown(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_ACTOR) { this->JoystickActor->OnLeftButtonDown(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_CAMERA) { this->TrackballCamera->OnLeftButtonDown(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_ACTOR) { this->TrackballActor->OnLeftButtonDown(ctrl, shift, x, y); } } //---------------------------------------------------------------------------- void vtkInteractorStyleSwitch::OnLeftButtonUp(int ctrl, int shift, int x, int y) { if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_CAMERA) { this->JoystickCamera->OnLeftButtonUp(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_ACTOR) { this->JoystickActor->OnLeftButtonUp(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_CAMERA) { this->TrackballCamera->OnLeftButtonUp(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_ACTOR) { this->TrackballActor->OnLeftButtonUp(ctrl, shift, x, y); } } //---------------------------------------------------------------------------- void vtkInteractorStyleSwitch::OnMiddleButtonDown(int ctrl, int shift, int x, int y) { if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_CAMERA) { this->JoystickCamera->OnMiddleButtonDown(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_ACTOR) { this->JoystickActor->OnMiddleButtonDown(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_CAMERA) { this->TrackballCamera->OnMiddleButtonDown(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_ACTOR) { this->TrackballActor->OnMiddleButtonDown(ctrl, shift, x, y); } } //---------------------------------------------------------------------------- void vtkInteractorStyleSwitch::OnMiddleButtonUp(int ctrl, int shift, int x, int y) { if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_CAMERA) { this->JoystickCamera->OnMiddleButtonUp(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_ACTOR) { this->JoystickActor->OnMiddleButtonUp(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_CAMERA) { this->TrackballCamera->OnMiddleButtonUp(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_ACTOR) { this->TrackballActor->OnMiddleButtonUp(ctrl, shift, x, y); } } //---------------------------------------------------------------------------- void vtkInteractorStyleSwitch::OnRightButtonDown(int ctrl, int shift, int x, int y) { if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_CAMERA) { this->JoystickCamera->OnRightButtonDown(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_ACTOR) { this->JoystickActor->OnRightButtonDown(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_CAMERA) { this->TrackballCamera->OnRightButtonDown(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_ACTOR) { this->TrackballActor->OnRightButtonDown(ctrl, shift, x, y); } } //---------------------------------------------------------------------------- void vtkInteractorStyleSwitch::OnRightButtonUp(int ctrl, int shift, int x, int y) { if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_CAMERA) { this->JoystickCamera->OnRightButtonUp(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_ACTOR) { this->JoystickActor->OnRightButtonUp(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_CAMERA) { this->TrackballCamera->OnRightButtonUp(ctrl, shift, x, y); } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_ACTOR) { this->TrackballActor->OnRightButtonUp(ctrl, shift, x, y); } } //---------------------------------------------------------------------------- void vtkInteractorStyleSwitch::SetInteractor(vtkRenderWindowInteractor *iren) { this->JoystickActor->SetInteractor(iren); this->JoystickCamera->SetInteractor(iren); this->TrackballActor->SetInteractor(iren); this->TrackballCamera->SetInteractor(iren); this->vtkInteractorStyle::SetInteractor(iren); } //---------------------------------------------------------------------------- void vtkInteractorStyleSwitch::OnTimer(void) { if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_CAMERA) { this->JoystickCamera->OnTimer(); } else if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_ACTOR) { this->JoystickActor->OnTimer(); } } <|endoftext|>
<commit_before>// bdls_memoryutil.t.cpp -*-C++-*- // ---------------------------------------------------------------------------- // NOTICE // // This component is not up to date with current BDE coding standards, and // should not be used as an example for new development. // ---------------------------------------------------------------------------- #include <bdls_memoryutil.h> #include <bslim_testutil.h> // TBD: this needs to test setting memory to executable #include <bsls_platform.h> #include <bsl_iostream.h> #include <bsl_cstdio.h> #include <bsl_cstdlib.h> #include <bsl_cstring.h> #ifdef BSLS_PLATFORM_OS_WINDOWS #include <windows.h> #endif #ifdef BSLS_PLATFORM_OS_UNIX #include <sys/resource.h> #endif using namespace BloombergLP; using namespace bsl; // automatically added by script // ============================================================================ // STANDARD BDE ASSERT TEST FUNCTION // ---------------------------------------------------------------------------- namespace { int testStatus = 0; void aSsErT(bool condition, const char *message, int line) { if (condition) { cout << "Error " __FILE__ "(" << line << "): " << message << " (failed)" << endl; if (0 <= testStatus && testStatus <= 100) { ++testStatus; } } } } // close unnamed namespace // ============================================================================ // STANDARD BDE TEST DRIVER MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ASSERT BSLIM_TESTUTIL_ASSERT #define ASSERTV BSLIM_TESTUTIL_ASSERTV #define LOOP_ASSERT BSLIM_TESTUTIL_LOOP_ASSERT #define LOOP0_ASSERT BSLIM_TESTUTIL_LOOP0_ASSERT #define LOOP1_ASSERT BSLIM_TESTUTIL_LOOP1_ASSERT #define LOOP2_ASSERT BSLIM_TESTUTIL_LOOP2_ASSERT #define LOOP3_ASSERT BSLIM_TESTUTIL_LOOP3_ASSERT #define LOOP4_ASSERT BSLIM_TESTUTIL_LOOP4_ASSERT #define LOOP5_ASSERT BSLIM_TESTUTIL_LOOP5_ASSERT #define LOOP6_ASSERT BSLIM_TESTUTIL_LOOP6_ASSERT #define Q BSLIM_TESTUTIL_Q // Quote identifier literally. #define P BSLIM_TESTUTIL_P // Print identifier and value. #define P_ BSLIM_TESTUTIL_P_ // P(X) without '\n'. #define T_ BSLIM_TESTUTIL_T_ // Print a tab (w/o newline). #define L_ BSLIM_TESTUTIL_L_ // current Line number // ============================================================================ // MAIN PROGRAM // ---------------------------------------------------------------------------- int main(int argc, char *argv[]) { int test = argc > 1 ? bsl::atoi(argv[1]) : 0; bool verbose = argc > 2; // bool veryVerbose = argc > 3; // bool veryVeryVerbose = argc > 4; // bool veryVeryVeryVerbose = argc > 5; #ifdef BSLS_PLATFORM_OS_WINDOWS { // disable popup on crash SetErrorMode(SEM_NOGPFAULTERRORBOX); } #endif #ifdef BSLS_PLATFORM_OS_UNIX // disable core dumps { struct rlimit rl; rl.rlim_cur = rl.rlim_max = 0; setrlimit(RLIMIT_CORE, &rl); } #endif switch (test) { case 0: // Zero is always the leading case. case 2: { // --------------------------------------------------------------- // Concern: functionality of protect() // // Test plan: enumerate all possible access mode combinations and try // reading, writing and executing the memory with these protection // modes. Verify the actual protection modes match the specified ones. // --------------------------------------------------------------- // this test expects k_ACCESS_READ==1, k_ACCESS_WRITE==2, // k_ACCESS_EXECUTE==4 ASSERT(bdls::MemoryUtil::k_ACCESS_READ == 1); ASSERT(bdls::MemoryUtil::k_ACCESS_WRITE == 2); ASSERT(bdls::MemoryUtil::k_ACCESS_EXECUTE == 4); static const char*const operations[] = { "read", "write" }; static const char* const modes[] = { "k_ACCESS_NONE", "k_ACCESS_READ", "k_ACCESS_WRITE", "k_ACCESS_READ_WRITE", "k_ACCESS_EXECUTE", "k_ACCESS_READ_EXECUTE", "k_ACCESS_WRITE_EXECUTE", "k_ACCESS_READ_WRITE_EXECUTE", }; // test all 8 modes for (unsigned int mode=0; mode<sizeof(modes)/sizeof(*modes); ++mode) { // do not try to set executable bit when on HP-UX #ifdef BSLS_PLATFORM_OS_HPUX if (mode & bdls::MemoryUtil::k_ACCESS_EXECUTE) { continue; } #endif // test read & write for (unsigned int op=0; op<sizeof(operations)/sizeof(*operations); ++op) { if (op == 0 && mode != bdls::MemoryUtil::k_ACCESS_NONE && !(mode & bdls::MemoryUtil::k_ACCESS_READ)) { // do not test disabled read with write/execute allowed: // most platforms do not have fine-grained read access // control if (verbose) cout << "Skipping op:" << operations[op] << ", mode:" << modes[mode] << bsl::endl; continue; } int expected_rc = !(mode & (1<<op)); if (verbose) { cout << "Testing op:" << operations[op] << ", mode:" << modes[mode] << ", expected to " << ( expected_rc ? "fail" : "succeed" ) << bsl::endl; } enum { ARBITRARY_BUT_SUFFICIENT_BUFFER_SIZE = 1000 }; char buffer[ARBITRARY_BUT_SUFFICIENT_BUFFER_SIZE]; #ifdef BSLS_PLATFORM_OS_WINDOWS const char* redirectToNull = " >NUL 2>&1"; #else const char* redirectToNull = " >/dev/null 2>&1"; #endif bsl::sprintf(buffer, "%s -1 %s %d %d%s", argv[0], argv[0], -10-op, mode, verbose ? "" : redirectToNull); int rc = system(buffer); LOOP4_ASSERT(modes[mode], operations[op], rc, expected_rc, !rc == !expected_rc); } } } break; case 1: { ///USAGE EXAMPLE ///------------- // // First, allocate one page of memory. int pageSize = bdls::MemoryUtil::pageSize(); char* data = (char*)bdls::MemoryUtil::allocate(pageSize); // Write into the allocated buffer. data[0] = 1; // Make the memory write protected bdls::MemoryUtil::protect(data, pageSize, bdls::MemoryUtil::k_ACCESS_READ); // Once again, try writing into the buffer. This should crash our // process. // data[0] = 2; // Restore read/write access and free the allocated memory. Actually, // this will never be executed, as the process has already crashed. bdls::MemoryUtil::protect(data, pageSize, bdls::MemoryUtil::k_ACCESS_READ_WRITE); bdls::MemoryUtil::deallocate(data); } break; case -1: { // -------------------------------------------------------------------- // Helper test case for case 2 // // This case implements the system command, it allows case 2 to call // system within system, and thereby make abort messages redirectable. // -------------------------------------------------------------------- char buffer[1000]; buffer[0] = 0; for (int i = 2; i < argc; ++i) { strcat(buffer, " "); strcat(buffer, argv[i]); } cout << "Within system: " << buffer << endl; return !!system(buffer); // RETURN } break; case -10: { // -------------------------------------------------------------------- // Helper test case for case 2 // // Plan: allocate some memory with protection mode specified in argv[2] // and verify it is readable. Note that it is normal for this test // case to fail for some values of argv[2]. // -------------------------------------------------------------------- int size = bdls::MemoryUtil::pageSize(); char* ptr = (char*) bdls::MemoryUtil::allocate(size); memset(ptr, 0x55, size); int rc = bdls::MemoryUtil::protect(ptr, size, atoi(argv[2])); ASSERT(0 == rc); for(int i=0; i<size; ++i) { ASSERT(((volatile char*)ptr)[i] == 0x55); } rc = bdls::MemoryUtil::protect(ptr, size, bdls::MemoryUtil::k_ACCESS_READ_WRITE); ASSERT(0 == rc); rc = bdls::MemoryUtil::deallocate(ptr); ASSERT(0 == rc); } break; case -11: { // -------------------------------------------------------------------- // Helper test case for case 2 // // Plan: allocate some memory with protection mode specified in argv[2] // and verify it is writable. Note that it is normal for this test // case to fail for some values of argv[2]. // -------------------------------------------------------------------- int size = bdls::MemoryUtil::pageSize(); char* ptr = (char*) bdls::MemoryUtil::allocate(size); int rc = bdls::MemoryUtil::protect(ptr, size, atoi(argv[2])); ASSERT(0 == rc); for(int i=0; i<size; ++i) { ((volatile char*)ptr)[i] = 0x55; } rc = bdls::MemoryUtil::protect(ptr, size, bdls::MemoryUtil::k_ACCESS_READ_WRITE); ASSERT(0 == rc); rc = bdls::MemoryUtil::deallocate(ptr); ASSERT(0 == rc); } break; default: { cerr << "WARNING: CASE `" << test << "' NOT FOUND." << endl; testStatus = -1; } } if (testStatus > 0) { cerr << "Error, non-zero test status = " << testStatus << "." << endl; } return testStatus; } // ---------------------------------------------------------------------------- // Copyright 2015 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ---------------------------------- <commit_msg>DRQS 123193362 Stop crash reports on Mac.<commit_after>// bdls_memoryutil.t.cpp -*-C++-*- // ---------------------------------------------------------------------------- // NOTICE // // This component is not up to date with current BDE coding standards, and // should not be used as an example for new development. // ---------------------------------------------------------------------------- #include <bdls_memoryutil.h> #include <bslim_testutil.h> // TBD: this needs to test setting memory to executable #include <bsls_platform.h> #include <bsl_iostream.h> #include <bsl_cstdio.h> #include <bsl_cstdlib.h> #include <bsl_cstring.h> #ifdef BSLS_PLATFORM_OS_WINDOWS #include <windows.h> #endif #ifdef BSLS_PLATFORM_OS_UNIX #include <sys/resource.h> #include <unistd.h> #include <signal.h> #endif using namespace BloombergLP; using namespace bsl; // automatically added by script // ============================================================================ // STANDARD BDE ASSERT TEST FUNCTION // ---------------------------------------------------------------------------- namespace { int testStatus = 0; void aSsErT(bool condition, const char *message, int line) { if (condition) { cout << "Error " __FILE__ "(" << line << "): " << message << " (failed)" << endl; if (0 <= testStatus && testStatus <= 100) { ++testStatus; } } } } // close unnamed namespace // ============================================================================ // STANDARD BDE TEST DRIVER MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ASSERT BSLIM_TESTUTIL_ASSERT #define ASSERTV BSLIM_TESTUTIL_ASSERTV #define LOOP_ASSERT BSLIM_TESTUTIL_LOOP_ASSERT #define LOOP0_ASSERT BSLIM_TESTUTIL_LOOP0_ASSERT #define LOOP1_ASSERT BSLIM_TESTUTIL_LOOP1_ASSERT #define LOOP2_ASSERT BSLIM_TESTUTIL_LOOP2_ASSERT #define LOOP3_ASSERT BSLIM_TESTUTIL_LOOP3_ASSERT #define LOOP4_ASSERT BSLIM_TESTUTIL_LOOP4_ASSERT #define LOOP5_ASSERT BSLIM_TESTUTIL_LOOP5_ASSERT #define LOOP6_ASSERT BSLIM_TESTUTIL_LOOP6_ASSERT #define Q BSLIM_TESTUTIL_Q // Quote identifier literally. #define P BSLIM_TESTUTIL_P // Print identifier and value. #define P_ BSLIM_TESTUTIL_P_ // P(X) without '\n'. #define T_ BSLIM_TESTUTIL_T_ // Print a tab (w/o newline). #define L_ BSLIM_TESTUTIL_L_ // current Line number // ============================================================================ // SIGNAL HANDLER // ---------------------------------------------------------------------------- extern "C" void _exiting_handler(int signum) { _exit(1); } // ============================================================================ // MAIN PROGRAM // ---------------------------------------------------------------------------- int main(int argc, char *argv[]) { int test = argc > 1 ? bsl::atoi(argv[1]) : 0; bool verbose = argc > 2; // bool veryVerbose = argc > 3; // bool veryVeryVerbose = argc > 4; // bool veryVeryVeryVerbose = argc > 5; #ifdef BSLS_PLATFORM_OS_WINDOWS { // disable popup on crash SetErrorMode(SEM_NOGPFAULTERRORBOX); } #endif #ifdef BSLS_PLATFORM_OS_UNIX { // disable core dumps and Mac popup on crash struct sigaction sa; sa.sa_handler = _exiting_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGSEGV, &sa, NULL); sigaction(SIGBUS, &sa, NULL); } #endif switch (test) { case 0: // Zero is always the leading case. case 2: { // --------------------------------------------------------------- // Concern: functionality of protect() // // Test plan: enumerate all possible access mode combinations and try // reading, writing and executing the memory with these protection // modes. Verify the actual protection modes match the specified ones. // --------------------------------------------------------------- // this test expects k_ACCESS_READ==1, k_ACCESS_WRITE==2, // k_ACCESS_EXECUTE==4 ASSERT(bdls::MemoryUtil::k_ACCESS_READ == 1); ASSERT(bdls::MemoryUtil::k_ACCESS_WRITE == 2); ASSERT(bdls::MemoryUtil::k_ACCESS_EXECUTE == 4); static const char*const operations[] = { "read", "write" }; static const char* const modes[] = { "k_ACCESS_NONE", "k_ACCESS_READ", "k_ACCESS_WRITE", "k_ACCESS_READ_WRITE", "k_ACCESS_EXECUTE", "k_ACCESS_READ_EXECUTE", "k_ACCESS_WRITE_EXECUTE", "k_ACCESS_READ_WRITE_EXECUTE", }; // test all 8 modes for (unsigned int mode=0; mode<sizeof(modes)/sizeof(*modes); ++mode) { // do not try to set executable bit when on HP-UX #ifdef BSLS_PLATFORM_OS_HPUX if (mode & bdls::MemoryUtil::k_ACCESS_EXECUTE) { continue; } #endif // test read & write for (unsigned int op=0; op<sizeof(operations)/sizeof(*operations); ++op) { if (op == 0 && mode != bdls::MemoryUtil::k_ACCESS_NONE && !(mode & bdls::MemoryUtil::k_ACCESS_READ)) { // do not test disabled read with write/execute allowed: // most platforms do not have fine-grained read access // control if (verbose) cout << "Skipping op:" << operations[op] << ", mode:" << modes[mode] << bsl::endl; continue; } int expected_rc = !(mode & (1<<op)); if (verbose) { cout << "Testing op:" << operations[op] << ", mode:" << modes[mode] << ", expected to " << ( expected_rc ? "fail" : "succeed" ) << bsl::endl; } enum { ARBITRARY_BUT_SUFFICIENT_BUFFER_SIZE = 1000 }; char buffer[ARBITRARY_BUT_SUFFICIENT_BUFFER_SIZE]; #ifdef BSLS_PLATFORM_OS_WINDOWS const char* redirectToNull = " >NUL 2>&1"; #else const char* redirectToNull = " >/dev/null 2>&1"; #endif bsl::sprintf(buffer, "%s -1 %s %d %d%s", argv[0], argv[0], -10-op, mode, verbose ? "" : redirectToNull); int rc = system(buffer); LOOP4_ASSERT(modes[mode], operations[op], rc, expected_rc, !rc == !expected_rc); } } } break; case 1: { ///USAGE EXAMPLE ///------------- // // First, allocate one page of memory. int pageSize = bdls::MemoryUtil::pageSize(); char* data = (char*)bdls::MemoryUtil::allocate(pageSize); // Write into the allocated buffer. data[0] = 1; // Make the memory write protected bdls::MemoryUtil::protect(data, pageSize, bdls::MemoryUtil::k_ACCESS_READ); // Once again, try writing into the buffer. This should crash our // process. // data[0] = 2; // Restore read/write access and free the allocated memory. Actually, // this will never be executed, as the process has already crashed. bdls::MemoryUtil::protect(data, pageSize, bdls::MemoryUtil::k_ACCESS_READ_WRITE); bdls::MemoryUtil::deallocate(data); } break; case -1: { // -------------------------------------------------------------------- // Helper test case for case 2 // // This case implements the system command, it allows case 2 to call // system within system, and thereby make abort messages redirectable. // -------------------------------------------------------------------- char buffer[1000]; buffer[0] = 0; for (int i = 2; i < argc; ++i) { strcat(buffer, " "); strcat(buffer, argv[i]); } cout << "Within system: " << buffer << endl; return !!system(buffer); // RETURN } break; case -10: { // -------------------------------------------------------------------- // Helper test case for case 2 // // Plan: allocate some memory with protection mode specified in argv[2] // and verify it is readable. Note that it is normal for this test // case to fail for some values of argv[2]. // -------------------------------------------------------------------- int size = bdls::MemoryUtil::pageSize(); char* ptr = (char*) bdls::MemoryUtil::allocate(size); memset(ptr, 0x55, size); int rc = bdls::MemoryUtil::protect(ptr, size, atoi(argv[2])); ASSERT(0 == rc); for(int i=0; i<size; ++i) { ASSERT(((volatile char*)ptr)[i] == 0x55); } rc = bdls::MemoryUtil::protect(ptr, size, bdls::MemoryUtil::k_ACCESS_READ_WRITE); ASSERT(0 == rc); rc = bdls::MemoryUtil::deallocate(ptr); ASSERT(0 == rc); } break; case -11: { // -------------------------------------------------------------------- // Helper test case for case 2 // // Plan: allocate some memory with protection mode specified in argv[2] // and verify it is writable. Note that it is normal for this test // case to fail for some values of argv[2]. // -------------------------------------------------------------------- int size = bdls::MemoryUtil::pageSize(); char* ptr = (char*) bdls::MemoryUtil::allocate(size); int rc = bdls::MemoryUtil::protect(ptr, size, atoi(argv[2])); ASSERT(0 == rc); for(int i=0; i<size; ++i) { ((volatile char*)ptr)[i] = 0x55; } rc = bdls::MemoryUtil::protect(ptr, size, bdls::MemoryUtil::k_ACCESS_READ_WRITE); ASSERT(0 == rc); rc = bdls::MemoryUtil::deallocate(ptr); ASSERT(0 == rc); } break; default: { cerr << "WARNING: CASE `" << test << "' NOT FOUND." << endl; testStatus = -1; } } if (testStatus > 0) { cerr << "Error, non-zero test status = " << testStatus << "." << endl; } return testStatus; } // ---------------------------------------------------------------------------- // Copyright 2015 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ---------------------------------- <|endoftext|>
<commit_before>#include "DELSTUFF.H" #include "SPECIFIC.H" #include "LARA.H" #include "SETUP.H" #include "DRAW.H" #include "CALCLARA.H" #include "COLLIDE.H" #if PC_VERSION #include "SETUP.H" #elif PSX_VERSION || PSXPC_VERSION || SAT_VERSION || PS2_VERSION #include "MATHS.H" #endif struct MATRIX3D lara_joint_matrices[15]; struct MATRIX3D lara_matrices[15]; CVECTOR LaraNodeAmbient[2]; short* GLaraShadowframe; unsigned char LaraNodeUnderwater[15]; long LaraGlobalClipFlag = -1; char lara_underwater_skin_sweetness_table[15] = { 0, 2, 3, 0, 5, 6, 7, 9, 0xA, 0xB, 0xC, 0xD, 0xE, 8, 0 }; int lara_mesh_sweetness_table[15] = { 0, 1, 2, 3, 4, 5, 6, 7, 0xE, 8, 9, 0xA, 0xB, 0xC, 0xD }; unsigned char SkinUseMatrix[14][2] = { { 0xFF, 0xFF }, { 1, 2 }, { 0xFF, 0xFF }, { 0xFF, 0xFF }, { 4, 5 }, { 0xFF, 0xFF }, { 0xFF, 0xFF }, { 0xFF, 0xFF }, { 9, 0xA }, { 0xFF, 0xFF }, { 0xFF, 0xFF }, { 0xC, 0xD }, { 0xFF, 0xFF }, { 0xFF, 0xFF } }; char NodesToStashToScratch[14][2] = { { 1, 3 }, { 4, 5 }, { 6, 7 }, { 2, 8 }, { 9, 0xA }, { 0xB, 0xC }, { 0, 0xD }, { 0xE, 0x11 }, { 0x12, 0x13 }, { 0x14, 0x15 }, { 0xF, 0x16 }, { 0x17, 0x18 }, { 0x19, 0x1A }, { 0x10, 0x1B } }; char NodesToStashFromScratch[15][4] = { { 0, 1, 2, -1 }, { 3, 4, -1, 0 }, { 5, 6, -1, 0 }, { 7, -1, 0, 0 }, { 8, 9, -1, 0 }, { 0xA, 0xB, -1, 0 }, { 0xC, -1, 0, 0 }, { 0xD, 0x10, 0xE, 0xF }, { 0x1B, 0x1C, 0x22, -1 }, { 0x11, 0x12, -1, 0 }, { 0x13, 0x14, -1, 0 }, { 0x15, -1, 0, 0 }, { 0x16, 0x17, -1, 0 }, { 0x18, 0x19, -1, 0 }, { 0x1A, -1, 0, 0 } }; char HairRotScratchVertNums[5][12] = { { 4, 5, 6, 7, -1, 0, 0, 0, 0, 0, 0, 0 }, { 5, 6, 7, 4, -1, 0, 0, 0, 0, 0, 0, 0 }, { 6, 7, 4, 5, -1, 0, 0, 0, 0, 0, 0, 0 }, { 7, 4, 5, 6, -1, 0, 0, 0, 0, 0, 0, 0 }, { 4, 5, 6, 7, -1, 0, 0, 0, 0, 0, 0, 0 } }; void CalcLaraMatrices(int flag)//2C1DC, 2C504 { #if PC_VERSION short* frm[2]; if (lara.hit_direction >= 0) { int anim = -1; switch(lara.hit_direction) { case NORTH: anim = lara.IsDucked ? ANIMATION_LARA_CROUCH_SMASH_BACKWARD : ANIMATION_LARA_AH_FORWARD; break; case EAST: anim = lara.IsDucked ? ANIMATION_LARA_CROUCH_SMASH_RIGHT : ANIMATION_LARA_AH_LEFT; break; case SOUTH: anim = lara.IsDucked ? ANIMATION_LARA_CROUCH_SMASH_FORWARD : ANIMATION_LARA_AH_BACKWARD; break; case WEST: anim = lara.IsDucked ? ANIMATION_LARA_CROUCH_SMASH_LEFT : ANIMATION_LARA_AH_RIGHT; break; } frm[0] = &anims[anim].frame_ptr[lara.hit_frame * (anims[anim].interpolation >> 8)]; } else { int rate; long frac = GetFrames(lara_item, frm, &rate); if (frac != 0) { GLaraShadowframe = GetBoundsAccurate(lara_item); S_Warn("[CalcLaraMatrices] - Unimplemented if body\n"); DEL_CalcLaraMatrices_Interpolated_ASM(frm[0], frm[1], frac, rate);// todo, check params return; } } DEL_CalcLaraMatrices_Normal_ASM(frm[0], &bones[objects[lara_item->object_number].bone_index], flag); #elif PSX_VERSION || PSXPC_TEST struct object_info* object; short* frame; short* frmptr[2]; int frac; int rate; struct ITEM_INFO* item; long* bone; short spaz; struct ANIM_STRUCT* anim; int size; item = lara_item; object = &objects[item->object_number]; bone = &bones[object->bone_index]; if (lara.hit_direction < 0) { frac = GetFrames(item, &frmptr[0], &rate); if (frac != 0) { GLaraShadowframe = GetBoundsAccurate(item); DEL_CalcLaraMatrices_Interpolated_ASM(frmptr[0], frmptr[1], frac, rate, bone, flag); return; } }//loc_2C2A4 else { //loc_2C294 //loc_2C2A4 if (lara.hit_direction == 1) { //loc_2C318 if (lara.IsDucked) { spaz = 295; } else { spaz = 127; } //loc_2C34C } else if (lara.hit_direction == 2) { //loc_2C2FC if (lara.IsDucked) { spaz = 293; } else { spaz = 126; } } else if (lara.hit_direction == 0) { //loc_2C2E0 if (lara.IsDucked) { spaz = 294; } else { spaz = 125; } } else { if (lara.IsDucked) { spaz = 296; } else { spaz = 128; } } //loc_2C34C anim = &anims[spaz]; frame = &anim->frame_ptr[(lara.hit_frame * ((anim->interpolation << 16) >> 24))]; DEL_CalcLaraMatrices_Normal_ASM(frame, bone, flag); return; } //loc_2C390 DEL_CalcLaraMatrices_Normal_ASM(frmptr[0], bone, flag); #endif }<commit_msg>[Game]: Correct CalcLaraMatrices<commit_after>#include "DELSTUFF.H" #include "SPECIFIC.H" #include "LARA.H" #include "SETUP.H" #include "DRAW.H" #include "CALCLARA.H" #include "COLLIDE.H" #if PC_VERSION #include "SETUP.H" #elif PSX_VERSION || PSXPC_VERSION || SAT_VERSION || PS2_VERSION #include "MATHS.H" #endif struct MATRIX3D lara_joint_matrices[15]; struct MATRIX3D lara_matrices[15]; CVECTOR LaraNodeAmbient[2]; short* GLaraShadowframe; unsigned char LaraNodeUnderwater[15]; long LaraGlobalClipFlag = -1; char lara_underwater_skin_sweetness_table[15] = { 0, 2, 3, 0, 5, 6, 7, 9, 0xA, 0xB, 0xC, 0xD, 0xE, 8, 0 }; int lara_mesh_sweetness_table[15] = { 0, 1, 2, 3, 4, 5, 6, 7, 0xE, 8, 9, 0xA, 0xB, 0xC, 0xD }; unsigned char SkinUseMatrix[14][2] = { { 0xFF, 0xFF }, { 1, 2 }, { 0xFF, 0xFF }, { 0xFF, 0xFF }, { 4, 5 }, { 0xFF, 0xFF }, { 0xFF, 0xFF }, { 0xFF, 0xFF }, { 9, 0xA }, { 0xFF, 0xFF }, { 0xFF, 0xFF }, { 0xC, 0xD }, { 0xFF, 0xFF }, { 0xFF, 0xFF } }; char NodesToStashToScratch[14][2] = { { 1, 3 }, { 4, 5 }, { 6, 7 }, { 2, 8 }, { 9, 0xA }, { 0xB, 0xC }, { 0, 0xD }, { 0xE, 0x11 }, { 0x12, 0x13 }, { 0x14, 0x15 }, { 0xF, 0x16 }, { 0x17, 0x18 }, { 0x19, 0x1A }, { 0x10, 0x1B } }; char NodesToStashFromScratch[15][4] = { { 0, 1, 2, -1 }, { 3, 4, -1, 0 }, { 5, 6, -1, 0 }, { 7, -1, 0, 0 }, { 8, 9, -1, 0 }, { 0xA, 0xB, -1, 0 }, { 0xC, -1, 0, 0 }, { 0xD, 0x10, 0xE, 0xF }, { 0x1B, 0x1C, 0x22, -1 }, { 0x11, 0x12, -1, 0 }, { 0x13, 0x14, -1, 0 }, { 0x15, -1, 0, 0 }, { 0x16, 0x17, -1, 0 }, { 0x18, 0x19, -1, 0 }, { 0x1A, -1, 0, 0 } }; char HairRotScratchVertNums[5][12] = { { 4, 5, 6, 7, -1, 0, 0, 0, 0, 0, 0, 0 }, { 5, 6, 7, 4, -1, 0, 0, 0, 0, 0, 0, 0 }, { 6, 7, 4, 5, -1, 0, 0, 0, 0, 0, 0, 0 }, { 7, 4, 5, 6, -1, 0, 0, 0, 0, 0, 0, 0 }, { 4, 5, 6, 7, -1, 0, 0, 0, 0, 0, 0, 0 } }; void CalcLaraMatrices(int flag)//2C1DC, 2C504 { #if PC_VERSION short* frm[2]; if (lara.hit_direction >= 0) { int anim = -1; switch (lara.hit_direction) { case NORTH: anim = lara.IsDucked ? ANIMATION_LARA_CROUCH_SMASH_BACKWARD : ANIMATION_LARA_AH_FORWARD; break; case EAST: anim = lara.IsDucked ? ANIMATION_LARA_CROUCH_SMASH_RIGHT : ANIMATION_LARA_AH_LEFT; break; case SOUTH: anim = lara.IsDucked ? ANIMATION_LARA_CROUCH_SMASH_FORWARD : ANIMATION_LARA_AH_BACKWARD; break; case WEST: anim = lara.IsDucked ? ANIMATION_LARA_CROUCH_SMASH_LEFT : ANIMATION_LARA_AH_RIGHT; break; } frm[0] = &anims[anim].frame_ptr[lara.hit_frame * (anims[anim].interpolation >> 8)]; } else { int rate; long frac = GetFrames(lara_item, frm, &rate); if (frac != 0) { GLaraShadowframe = GetBoundsAccurate(lara_item); S_Warn("[CalcLaraMatrices] - Unimplemented if body\n"); DEL_CalcLaraMatrices_Interpolated_ASM(frm[0], frm[1], frac, rate);// todo, check params return; } } DEL_CalcLaraMatrices_Normal_ASM(frm[0], &bones[objects[lara_item->object_number].bone_index], flag); #elif PSX_VERSION || PSXPC_TEST struct object_info* object; short* frame; short* frmptr[2]; int frac; int rate; struct ITEM_INFO* item; long* bone; short spaz; struct ANIM_STRUCT* anim; int size; item = lara_item; object = &objects[item->object_number]; bone = &bones[object->bone_index]; if (lara.hit_direction < 0) { frac = GetFrames(item, &frmptr[0], &rate); if (frac != 0) { GLaraShadowframe = GetBoundsAccurate(item); DEL_CalcLaraMatrices_Interpolated_ASM(frmptr[0], frmptr[1], frac, rate, bone, flag); return; } }//loc_2C2A4 //loc_2C294 //loc_2C2A4 if (lara.hit_direction >= 0) { if (lara.hit_direction == 1) { //loc_2C318 if (lara.IsDucked) { spaz = 295; } else { spaz = 127; } //loc_2C34C } else if (lara.hit_direction == 2) { //loc_2C2FC if (lara.IsDucked) { spaz = 293; } else { spaz = 126; } } else if (lara.hit_direction == 0) { //loc_2C2E0 if (lara.IsDucked) { spaz = 294; } else { spaz = 125; } } else { if (lara.IsDucked) { spaz = 296; } else { spaz = 128; } } //loc_2C34C anim = &anims[spaz]; frame = &anim->frame_ptr[(lara.hit_frame * ((anim->interpolation << 16) >> 24))]; DEL_CalcLaraMatrices_Normal_ASM(frame, bone, flag); return; } //loc_2C390 DEL_CalcLaraMatrices_Normal_ASM(frmptr[0], bone, flag); #endif }<|endoftext|>
<commit_before>// Copyright (C) 2009, Vaclav Haisman. All rights reserved. // // Redistribution and use in source and binary forms, with or without modifica- // tion, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. 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. // // THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 // APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU- // DING, 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. #include <log4cplus/config.hxx> #ifndef LOG4CPLUS_SINGLE_THREADED #include <log4cplus/helpers/queue.h> #include <log4cplus/helpers/loglog.h> #include <log4cplus/thread/syncprims-pub-impl.h> #include <stdexcept> namespace log4cplus { namespace thread { Queue::Queue (unsigned len) : ev_consumer (false) , sem (len, len) , flags (DRAIN) { } Queue::~Queue () { } Queue::flags_type Queue::put_event (spi::InternalLoggingEvent const & ev) { flags_type ret_flags = ERROR_BIT; try { // Make sure that the event will have NDC and thread ID of the // calling thread and not the queue worker thread. ev.getThread (); ev.getNDC (); SemaphoreGuard semguard (sem); MutexGuard mguard (mutex); ret_flags |= flags; if (flags & EXIT) { ret_flags &= ~(ERROR_BIT | ERROR_AFTER); return ret_flags; } else { queue.push_front (ev); ret_flags |= ERROR_AFTER; semguard.detach (); flags |= QUEUE; ret_flags |= flags; ev_consumer.signal (); } } catch (std::runtime_error const & e) { (void)e; return ret_flags; } ret_flags &= ~(ERROR_BIT | ERROR_AFTER); return ret_flags; } Queue::flags_type Queue::signal_exit (bool drain) { flags_type ret_flags = 0; try { MutexGuard mguard (mutex); ret_flags |= flags; if (! (flags & EXIT)) { if (drain) flags |= DRAIN; else flags &= ~DRAIN; flags |= EXIT; ret_flags = flags; ev_consumer.signal (); } } catch (std::runtime_error const & e) { (void)e; ret_flags |= ERROR_BIT; return ret_flags; } return ret_flags; } Queue::flags_type Queue::get_event (spi::InternalLoggingEvent & ev) { flags_type ret_flags = 0; try { while (true) { MutexGuard mguard (mutex); ret_flags = flags; if (((QUEUE & flags) && ! (EXIT & flags)) || ((EXIT | DRAIN | QUEUE) & flags) == (EXIT | DRAIN | QUEUE)) { assert (! queue.empty ()); ev.swap (queue.back ()); queue.pop_back (); if (queue.empty ()) flags &= ~QUEUE; sem.unlock (); ret_flags = flags | EVENT; break; } else if (((EXIT | QUEUE) & flags) == (EXIT | QUEUE)) { assert (! queue.empty ()); queue.clear (); flags &= ~QUEUE; ev_consumer.reset (); sem.unlock (); ret_flags = flags; break; } else if (EXIT & flags) break; else { ev_consumer.reset (); mguard.unlock (); mguard.detach (); ev_consumer.wait (); } } } catch (std::runtime_error const & e) { (void)e; ret_flags |= ERROR_BIT; } return ret_flags; } } } // namespace log4cplus { namespace thread { #endif // LOG4CPLUS_SINGLE_THREADED <commit_msg>queue.cxx: Unlock and detach from queue mutex before signaling the consumer thread. This is to avoid unblocking the consumer thread just so that it can immediately block on the queue mutex.<commit_after>// Copyright (C) 2009, Vaclav Haisman. All rights reserved. // // Redistribution and use in source and binary forms, with or without modifica- // tion, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. 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. // // THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 // APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU- // DING, 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. #include <log4cplus/config.hxx> #ifndef LOG4CPLUS_SINGLE_THREADED #include <log4cplus/helpers/queue.h> #include <log4cplus/helpers/loglog.h> #include <log4cplus/thread/syncprims-pub-impl.h> #include <stdexcept> namespace log4cplus { namespace thread { Queue::Queue (unsigned len) : ev_consumer (false) , sem (len, len) , flags (DRAIN) { } Queue::~Queue () { } Queue::flags_type Queue::put_event (spi::InternalLoggingEvent const & ev) { flags_type ret_flags = ERROR_BIT; try { // Make sure that the event will have NDC and thread ID of the // calling thread and not the queue worker thread. ev.getThread (); ev.getNDC (); SemaphoreGuard semguard (sem); MutexGuard mguard (mutex); ret_flags |= flags; if (flags & EXIT) { ret_flags &= ~(ERROR_BIT | ERROR_AFTER); return ret_flags; } else { queue.push_front (ev); ret_flags |= ERROR_AFTER; semguard.detach (); flags |= QUEUE; ret_flags |= flags; mguard.unlock (); mguard.detach (); ev_consumer.signal (); } } catch (std::runtime_error const & e) { (void)e; return ret_flags; } ret_flags &= ~(ERROR_BIT | ERROR_AFTER); return ret_flags; } Queue::flags_type Queue::signal_exit (bool drain) { flags_type ret_flags = 0; try { MutexGuard mguard (mutex); ret_flags |= flags; if (! (flags & EXIT)) { if (drain) flags |= DRAIN; else flags &= ~DRAIN; flags |= EXIT; ret_flags = flags; mguard.unlock (); mguard.detach (); ev_consumer.signal (); } } catch (std::runtime_error const & e) { (void)e; ret_flags |= ERROR_BIT; return ret_flags; } return ret_flags; } Queue::flags_type Queue::get_event (spi::InternalLoggingEvent & ev) { flags_type ret_flags = 0; try { while (true) { MutexGuard mguard (mutex); ret_flags = flags; if (((QUEUE & flags) && ! (EXIT & flags)) || ((EXIT | DRAIN | QUEUE) & flags) == (EXIT | DRAIN | QUEUE)) { assert (! queue.empty ()); ev.swap (queue.back ()); queue.pop_back (); if (queue.empty ()) flags &= ~QUEUE; sem.unlock (); ret_flags = flags | EVENT; break; } else if (((EXIT | QUEUE) & flags) == (EXIT | QUEUE)) { assert (! queue.empty ()); queue.clear (); flags &= ~QUEUE; ev_consumer.reset (); sem.unlock (); ret_flags = flags; break; } else if (EXIT & flags) break; else { ev_consumer.reset (); mguard.unlock (); mguard.detach (); ev_consumer.wait (); } } } catch (std::runtime_error const & e) { (void)e; ret_flags |= ERROR_BIT; } return ret_flags; } } } // namespace log4cplus { namespace thread { #endif // LOG4CPLUS_SINGLE_THREADED <|endoftext|>
<commit_before>#include <v8.h> #include <node.h> #include <node_buffer.h> #include <string.h> #include <assert.h> #include "reader.h" using namespace hiredis; static void *tryParentize(const redisReadTask *task, const Local<Value> &v) { Reader *r = reinterpret_cast<Reader*>(task->privdata); size_t pidx, vidx; if (task->parent != NULL) { pidx = (size_t)task->parent->obj; assert(pidx > 0 && pidx < 9); /* When there is a parent, it should be an array. */ Local<Value> lvalue = NanPersistentToLocal(r->handle[pidx]); assert(lvalue->IsArray()); Local<Array> larray = lvalue.As<Array>(); larray->Set(task->idx,v); /* Store the handle when this is an inner array. Otherwise, hiredis * doesn't care about the return value as long as the value is set in * its parent array. */ vidx = pidx+1; if (v->IsArray()) { NanDispose(r->handle[vidx]); NanAssignPersistent(Value, r->handle[vidx], v); return (void*)vidx; } else { /* Return value doesn't matter for inner value, as long as it is * not NULL (which means OOM for hiredis). */ return (void*)0xcafef00d; } } else { /* There is no parent, so this value is the root object. */ NanAssignPersistent(Value, r->handle[1], v); return (void*)1; } } static void *createArray(const redisReadTask *task, int size) { Local<Value> v(Array::New(size)); return tryParentize(task,v); } static void *createString(const redisReadTask *task, char *str, size_t len) { Reader *r = reinterpret_cast<Reader*>(task->privdata); Local<Value> v(r->createString(str,len)); if (task->type == REDIS_REPLY_ERROR) v = Exception::Error(v->ToString()); return tryParentize(task,v); } static void *createInteger(const redisReadTask *task, long long value) { Local<Value> v(Number::New(value)); return tryParentize(task,v); } static void *createNil(const redisReadTask *task) { Local<Value> v(NanNewLocal<Value>(Null())); return tryParentize(task,v); } static redisReplyObjectFunctions v8ReplyFunctions = { createString, createArray, createInteger, createNil, NULL /* No free function: cleanup is done in Reader::Get. */ }; Reader::Reader(bool return_buffers) : return_buffers(return_buffers) { reader = redisReaderCreate(); reader->fn = &v8ReplyFunctions; reader->privdata = this; #if _USE_CUSTOM_BUFFER_POOL if (return_buffers) { Local<Object> global = Context::GetCurrent()->Global(); Local<Value> bv = global->Get(String::NewSymbol("Buffer")); assert(bv->IsFunction()); Local<Function> bf = Local<Function>::Cast(bv); buffer_fn = Persistent<Function>::New(bf); buffer_pool_length = 8*1024; /* Same as node */ buffer_pool_offset = 0; Buffer *b = Buffer::New(buffer_pool_length); buffer_pool = Persistent<Object>::New(b->handle_); } #endif } Reader::~Reader() { redisReaderFree(reader); } /* Don't use a HandleScope here, so the objects are created within the scope of * the caller (Reader::Get) and we don't have to the pay the overhead. */ inline Local<Value> Reader::createString(char *str, size_t len) { if (return_buffers) { #if _USE_CUSTOM_BUFFER_POOL if (len > buffer_pool_length) { Buffer *b = Buffer::New(str,len); return Local<Value>::New(b->handle_); } else { return createBufferFromPool(str,len); } #else return NanNewBufferHandle(str,len); #endif } else { return String::New(str,len); } } #if _USE_CUSTOM_BUFFER_POOL Local<Value> Reader::createBufferFromPool(char *str, size_t len) { HandleScope scope; Local<Value> argv[3]; Local<Object> instance; assert(len <= buffer_pool_length); if (buffer_pool_length - buffer_pool_offset < len) { Buffer *b = Buffer::New(buffer_pool_length); buffer_pool.Dispose(); buffer_pool = Persistent<Object>::New(b->handle_); buffer_pool_offset = 0; } memcpy(Buffer::Data(buffer_pool)+buffer_pool_offset,str,len); argv[0] = Local<Value>::New(buffer_pool); argv[1] = Integer::New(len); argv[2] = Integer::New(buffer_pool_offset); instance = buffer_fn->NewInstance(3,argv); buffer_pool_offset += len; return scope.Close(instance); } #endif NAN_METHOD(Reader::New) { NanScope(); bool return_buffers = false; if (args.Length() > 0 && args[0]->IsObject()) { Local<Value> bv = args[0].As<Object>()->Get(String::New("return_buffers")); if (bv->IsBoolean()) return_buffers = bv->ToBoolean()->Value(); } Reader *r = new Reader(return_buffers); r->Wrap(args.This()); NanReturnValue(args.This()); } void Reader::Initialize(Handle<Object> target) { NanScope(); Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "feed", Feed); NODE_SET_PROTOTYPE_METHOD(t, "get", Get); target->Set(String::NewSymbol("Reader"), t->GetFunction()); } NAN_METHOD(Reader::Feed) { NanScope(); Reader *r = ObjectWrap::Unwrap<Reader>(args.This()); if (args.Length() == 0) { NanThrowTypeError("First argument must be a string or buffer"); } else { if (Buffer::HasInstance(args[0])) { Local<Object> buffer_object = args[0].As<Object>(); char *data; size_t length; data = Buffer::Data(buffer_object); length = Buffer::Length(buffer_object); /* Can't handle OOM for now. */ assert(redisReaderFeed(r->reader, data, length) == REDIS_OK); } else if (args[0]->IsString()) { String::Utf8Value str(args[0].As<String>()); redisReplyReaderFeed(r->reader, *str, str.length()); } else { NanThrowError("Invalid argument"); } } NanReturnValue(args.This()); } NAN_METHOD(Reader::Get) { NanScope(); Reader *r = ObjectWrap::Unwrap<Reader>(args.This()); void *index = NULL; Local<Value> reply; int i; if (redisReaderGetReply(r->reader,&index) == REDIS_OK) { if (index == 0) { NanReturnUndefined(); } else { /* Complete replies should always have a root object at index 1. */ assert((size_t)index == 1); reply = NanNewLocal<Value>(NanPersistentToLocal(r->handle[1])); /* Dispose and clear used handles. */ for (i = 1; i < 3; i++) { NanDispose(r->handle[i]); } } } else { NanThrowError(r->reader->errstr); } NanReturnValue(reply); } <commit_msg>Don't refer to HandleScope in comment<commit_after>#include <v8.h> #include <node.h> #include <node_buffer.h> #include <string.h> #include <assert.h> #include "reader.h" using namespace hiredis; static void *tryParentize(const redisReadTask *task, const Local<Value> &v) { Reader *r = reinterpret_cast<Reader*>(task->privdata); size_t pidx, vidx; if (task->parent != NULL) { pidx = (size_t)task->parent->obj; assert(pidx > 0 && pidx < 9); /* When there is a parent, it should be an array. */ Local<Value> lvalue = NanPersistentToLocal(r->handle[pidx]); assert(lvalue->IsArray()); Local<Array> larray = lvalue.As<Array>(); larray->Set(task->idx,v); /* Store the handle when this is an inner array. Otherwise, hiredis * doesn't care about the return value as long as the value is set in * its parent array. */ vidx = pidx+1; if (v->IsArray()) { NanDispose(r->handle[vidx]); NanAssignPersistent(Value, r->handle[vidx], v); return (void*)vidx; } else { /* Return value doesn't matter for inner value, as long as it is * not NULL (which means OOM for hiredis). */ return (void*)0xcafef00d; } } else { /* There is no parent, so this value is the root object. */ NanAssignPersistent(Value, r->handle[1], v); return (void*)1; } } static void *createArray(const redisReadTask *task, int size) { Local<Value> v(Array::New(size)); return tryParentize(task,v); } static void *createString(const redisReadTask *task, char *str, size_t len) { Reader *r = reinterpret_cast<Reader*>(task->privdata); Local<Value> v(r->createString(str,len)); if (task->type == REDIS_REPLY_ERROR) v = Exception::Error(v->ToString()); return tryParentize(task,v); } static void *createInteger(const redisReadTask *task, long long value) { Local<Value> v(Number::New(value)); return tryParentize(task,v); } static void *createNil(const redisReadTask *task) { Local<Value> v(NanNewLocal<Value>(Null())); return tryParentize(task,v); } static redisReplyObjectFunctions v8ReplyFunctions = { createString, createArray, createInteger, createNil, NULL /* No free function: cleanup is done in Reader::Get. */ }; Reader::Reader(bool return_buffers) : return_buffers(return_buffers) { reader = redisReaderCreate(); reader->fn = &v8ReplyFunctions; reader->privdata = this; #if _USE_CUSTOM_BUFFER_POOL if (return_buffers) { Local<Object> global = Context::GetCurrent()->Global(); Local<Value> bv = global->Get(String::NewSymbol("Buffer")); assert(bv->IsFunction()); Local<Function> bf = Local<Function>::Cast(bv); buffer_fn = Persistent<Function>::New(bf); buffer_pool_length = 8*1024; /* Same as node */ buffer_pool_offset = 0; Buffer *b = Buffer::New(buffer_pool_length); buffer_pool = Persistent<Object>::New(b->handle_); } #endif } Reader::~Reader() { redisReaderFree(reader); } /* Don't declare an extra scope here, so the objects are created within the * scope inherited from the caller (Reader::Get) and we don't have to the pay * the overhead. */ inline Local<Value> Reader::createString(char *str, size_t len) { if (return_buffers) { #if _USE_CUSTOM_BUFFER_POOL if (len > buffer_pool_length) { Buffer *b = Buffer::New(str,len); return Local<Value>::New(b->handle_); } else { return createBufferFromPool(str,len); } #else return NanNewBufferHandle(str,len); #endif } else { return String::New(str,len); } } #if _USE_CUSTOM_BUFFER_POOL Local<Value> Reader::createBufferFromPool(char *str, size_t len) { HandleScope scope; Local<Value> argv[3]; Local<Object> instance; assert(len <= buffer_pool_length); if (buffer_pool_length - buffer_pool_offset < len) { Buffer *b = Buffer::New(buffer_pool_length); buffer_pool.Dispose(); buffer_pool = Persistent<Object>::New(b->handle_); buffer_pool_offset = 0; } memcpy(Buffer::Data(buffer_pool)+buffer_pool_offset,str,len); argv[0] = Local<Value>::New(buffer_pool); argv[1] = Integer::New(len); argv[2] = Integer::New(buffer_pool_offset); instance = buffer_fn->NewInstance(3,argv); buffer_pool_offset += len; return scope.Close(instance); } #endif NAN_METHOD(Reader::New) { NanScope(); bool return_buffers = false; if (args.Length() > 0 && args[0]->IsObject()) { Local<Value> bv = args[0].As<Object>()->Get(String::New("return_buffers")); if (bv->IsBoolean()) return_buffers = bv->ToBoolean()->Value(); } Reader *r = new Reader(return_buffers); r->Wrap(args.This()); NanReturnValue(args.This()); } void Reader::Initialize(Handle<Object> target) { NanScope(); Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "feed", Feed); NODE_SET_PROTOTYPE_METHOD(t, "get", Get); target->Set(String::NewSymbol("Reader"), t->GetFunction()); } NAN_METHOD(Reader::Feed) { NanScope(); Reader *r = ObjectWrap::Unwrap<Reader>(args.This()); if (args.Length() == 0) { NanThrowTypeError("First argument must be a string or buffer"); } else { if (Buffer::HasInstance(args[0])) { Local<Object> buffer_object = args[0].As<Object>(); char *data; size_t length; data = Buffer::Data(buffer_object); length = Buffer::Length(buffer_object); /* Can't handle OOM for now. */ assert(redisReaderFeed(r->reader, data, length) == REDIS_OK); } else if (args[0]->IsString()) { String::Utf8Value str(args[0].As<String>()); redisReplyReaderFeed(r->reader, *str, str.length()); } else { NanThrowError("Invalid argument"); } } NanReturnValue(args.This()); } NAN_METHOD(Reader::Get) { NanScope(); Reader *r = ObjectWrap::Unwrap<Reader>(args.This()); void *index = NULL; Local<Value> reply; int i; if (redisReaderGetReply(r->reader,&index) == REDIS_OK) { if (index == 0) { NanReturnUndefined(); } else { /* Complete replies should always have a root object at index 1. */ assert((size_t)index == 1); reply = NanNewLocal<Value>(NanPersistentToLocal(r->handle[1])); /* Dispose and clear used handles. */ for (i = 1; i < 3; i++) { NanDispose(r->handle[i]); } } } else { NanThrowError(r->reader->errstr); } NanReturnValue(reply); } <|endoftext|>
<commit_before>#ifndef CLOCK_UNORDERED_MAP #define CLOCK_UNORDERED_MAP #include<functional> //equal_to, hash #include<memory> //allocator #include<mutex> #include<shared_mutex> #include<tuple> #include<unordered_map> #include<utility> //forward, move namespace nThread { template<class Key,class T,class Hash=std::hash<Key>,class KeyEqual=std::equal_to<Key>,class Alloc=std::allocator<std::pair<const Key,T>>> class CLock_unordered_map { public: using key_type=Key; using mapped_type=T; private: std::unordered_map<key_type,mapped_type,Hash,KeyEqual,Alloc> map_; mutable std::shared_mutex mut_; template<class Key_typeFwdRef,class Gen> bool emplace_if_not_exist_(Key_typeFwdRef &&key,Gen &&gen) { if(find_not_ts_(key)) return false; map_.emplace(std::piecewise_construct,std::forward_as_tuple(std::forward<decltype(key)>(key)),std::forward_as_tuple(std::forward<decltype(gen)>(gen)())); return true; } inline bool find_not_ts_(const key_type &key) const { return map_.find(key)!=map_.end(); } template<class Key_typeFwdRef> mapped_type& subscript_(Key_typeFwdRef &&key) { std::lock_guard<std::shared_mutex> lock{mut_}; return map_[std::forward<decltype(key)>(key)]; } template<class Key_typeFwdRef,class ... Args> bool try_emplace_(Key_typeFwdRef &&key,Args &&...args) { std::lock_guard<std::shared_mutex> lock{mut_}; return map_.try_emplace(std::forward<decltype(key)>(key),std::forward<decltype(args)>(args)...).second; } template<class Key_typeFwdRef,class Gen> bool try_emplace_gen_(Key_typeFwdRef &&key,Gen &&gen) { std::lock_guard<std::shared_mutex> lock{mut_}; return emplace_if_not_exist_(std::forward<decltype(key)>(key),std::forward<decltype(gen)>(gen)); } template<class Key_typeFwdRef,class Gen> int try_lock_emplace_gen_(Key_typeFwdRef &&key,Gen &&gen) { std::unique_lock<std::shared_mutex> lock{mut_,std::defer_lock}; if(lock.try_lock()) return emplace_if_not_exist_(std::forward<decltype(key)>(key),std::forward<decltype(gen)>(gen)); return -1; } public: CLock_unordered_map()=default; CLock_unordered_map(const CLock_unordered_map &)=delete; mapped_type& at(const key_type &key) { std::shared_lock<std::shared_mutex> lock{mut_}; return map_.at(key); } const mapped_type& at(const key_type &key) const { std::shared_lock<std::shared_mutex> lock{mut_}; return map_.at(key); } bool find(const key_type &key) const { std::shared_lock<std::shared_mutex> lock{mut_}; return find_not_ts_(key); } template<class ... Args> bool emplace(Args &&...args) { std::lock_guard<std::shared_mutex> lock{mut_}; return map_.emplace(std::forward<decltype(args)>(args)...).second; } mapped_type& read(const key_type &key) { std::shared_lock<std::shared_mutex> lock{mut_}; return map_.find(key)->second; } const mapped_type& read(const key_type &key) const { std::shared_lock<std::shared_mutex> lock{mut_}; return map_.find(key)->second; } template<class ... Args> inline bool try_emplace(const key_type &key,Args &&...args) { return try_emplace_(key,std::forward<decltype(args)>(args)...); } template<class ... Args> inline bool try_emplace(key_type &&key,Args &&...args) { return try_emplace_(std::move(key),std::forward<decltype(args)>(args)...); } template<class Gen> inline bool try_emplace_gen(const key_type &key,Gen &&gen) { return try_emplace_gen_(key,std::forward<decltype(gen)>(gen)); } template<class Gen> inline bool try_emplace_gen(key_type &&key,Gen &&gen) { return try_emplace_gen_(std::move(key),std::forward<decltype(gen)>(gen)); } template<class Gen> inline int try_lock_emplace_gen(const key_type &key,Gen &&gen) { return try_lock_emplace_gen_(key,std::forward<decltype(gen)>(gen)); } template<class Gen> inline int try_lock_emplace_gen(key_type &&key,Gen &&gen) { return try_lock_emplace_gen_(std::move(key),std::forward<decltype(gen)>(gen)); } inline std::unordered_map<key_type,mapped_type,Hash,KeyEqual,Alloc>& unordered_map() noexcept { return map_; } inline const std::unordered_map<key_type,mapped_type,Hash,KeyEqual,Alloc>& unordered_map() const noexcept { return map_; } CLock_unordered_map& operator=(const CLock_unordered_map &)=delete; inline mapped_type& operator[](const key_type &key) { return subscript_(key); } inline mapped_type& operator[](key_type &&key) { return subscript_(std::move(key)); } }; } #endif<commit_msg>using namespace std in function<commit_after>#ifndef CLOCK_UNORDERED_MAP #define CLOCK_UNORDERED_MAP #include<functional> //equal_to, hash #include<memory> //allocator #include<mutex> #include<shared_mutex> #include<tuple> #include<unordered_map> #include<utility> //forward, move namespace nThread { template<class Key,class T,class Hash=std::hash<Key>,class KeyEqual=std::equal_to<Key>,class Alloc=std::allocator<std::pair<const Key,T>>> class CLock_unordered_map { public: using key_type=Key; using mapped_type=T; private: std::unordered_map<key_type,mapped_type,Hash,KeyEqual,Alloc> map_; mutable std::shared_mutex mut_; template<class Key_typeFwdRef,class Gen> bool emplace_if_not_exist_(Key_typeFwdRef &&key,Gen &&gen) { using namespace std; if(find_not_ts_(key)) return false; map_.emplace(piecewise_construct,forward_as_tuple(forward<decltype(key)>(key)),forward_as_tuple(forward<decltype(gen)>(gen)())); return true; } inline bool find_not_ts_(const key_type &key) const { return map_.find(key)!=map_.end(); } template<class Key_typeFwdRef> mapped_type& subscript_(Key_typeFwdRef &&key) { std::lock_guard<std::shared_mutex> lock{mut_}; return map_[std::forward<decltype(key)>(key)]; } template<class Key_typeFwdRef,class ... Args> bool try_emplace_(Key_typeFwdRef &&key,Args &&...args) { std::lock_guard<std::shared_mutex> lock{mut_}; return map_.try_emplace(std::forward<decltype(key)>(key),std::forward<decltype(args)>(args)...).second; } template<class Key_typeFwdRef,class Gen> bool try_emplace_gen_(Key_typeFwdRef &&key,Gen &&gen) { std::lock_guard<std::shared_mutex> lock{mut_}; return emplace_if_not_exist_(std::forward<decltype(key)>(key),std::forward<decltype(gen)>(gen)); } template<class Key_typeFwdRef,class Gen> int try_lock_emplace_gen_(Key_typeFwdRef &&key,Gen &&gen) { using namespace std; unique_lock<shared_mutex> lock{mut_,defer_lock}; if(lock.try_lock()) return emplace_if_not_exist_(forward<decltype(key)>(key),forward<decltype(gen)>(gen)); return -1; } public: CLock_unordered_map()=default; CLock_unordered_map(const CLock_unordered_map &)=delete; mapped_type& at(const key_type &key) { std::shared_lock<std::shared_mutex> lock{mut_}; return map_.at(key); } const mapped_type& at(const key_type &key) const { std::shared_lock<std::shared_mutex> lock{mut_}; return map_.at(key); } bool find(const key_type &key) const { std::shared_lock<std::shared_mutex> lock{mut_}; return find_not_ts_(key); } template<class ... Args> bool emplace(Args &&...args) { std::lock_guard<std::shared_mutex> lock{mut_}; return map_.emplace(std::forward<decltype(args)>(args)...).second; } mapped_type& read(const key_type &key) { std::shared_lock<std::shared_mutex> lock{mut_}; return map_.find(key)->second; } const mapped_type& read(const key_type &key) const { std::shared_lock<std::shared_mutex> lock{mut_}; return map_.find(key)->second; } template<class ... Args> inline bool try_emplace(const key_type &key,Args &&...args) { return try_emplace_(key,std::forward<decltype(args)>(args)...); } template<class ... Args> inline bool try_emplace(key_type &&key,Args &&...args) { return try_emplace_(std::move(key),std::forward<decltype(args)>(args)...); } template<class Gen> inline bool try_emplace_gen(const key_type &key,Gen &&gen) { return try_emplace_gen_(key,std::forward<decltype(gen)>(gen)); } template<class Gen> inline bool try_emplace_gen(key_type &&key,Gen &&gen) { return try_emplace_gen_(std::move(key),std::forward<decltype(gen)>(gen)); } template<class Gen> inline int try_lock_emplace_gen(const key_type &key,Gen &&gen) { return try_lock_emplace_gen_(key,std::forward<decltype(gen)>(gen)); } template<class Gen> inline int try_lock_emplace_gen(key_type &&key,Gen &&gen) { return try_lock_emplace_gen_(std::move(key),std::forward<decltype(gen)>(gen)); } inline std::unordered_map<key_type,mapped_type,Hash,KeyEqual,Alloc>& unordered_map() noexcept { return map_; } inline const std::unordered_map<key_type,mapped_type,Hash,KeyEqual,Alloc>& unordered_map() const noexcept { return map_; } CLock_unordered_map& operator=(const CLock_unordered_map &)=delete; inline mapped_type& operator[](const key_type &key) { return subscript_(key); } inline mapped_type& operator[](key_type &&key) { return subscript_(std::move(key)); } }; } #endif<|endoftext|>
<commit_before>/* * Copyright (C) 2009 Toni Gundogdu. * * This file is part of cclive. * * cclive is free software: you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * cclive is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ #include "config.h" #include <string> #include <sstream> #include <climits> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HOST_W32 #include <windows.h> #define sleep(n) Sleep(n*1000) #endif #include "except.h" #include "video.h" #include "curl.h" #include "log.h" #include "opts.h" #include "retry.h" RetryMgr::RetryMgr() : retries(0), retryUntilRetrievedFlag(false) { } void RetryMgr::reset() { retries = 0; retryUntilRetrievedFlag = false; } void RetryMgr::handle(const CurlMgr::FetchException& x) { logmgr.cerr(x); const long httpcode = x.getHTTPCode(); if (httpcode >= 400 && httpcode < 500) throw x; // Pass the exception without retrying. const Options opts = optsmgr.getOptions(); int maxRetry = opts.retry_arg; if (retryUntilRetrievedFlag) maxRetry = 0; // Override --retry limit for file downloads if (++retries <= opts.retry_arg || maxRetry == 0) { std::stringstream b; b << "retry #" << retries << "/" << maxRetry << " ... wait " << opts.retry_wait_arg << " second(s)."; logmgr.cerr(b.str(), false, false, false); sleep(opts.retry_wait_arg); logmgr.cerr() << std::endl; if (retries == INT_MAX-1) retries = 0; } throw x; // Pass the exception, retries not within our range. } void RetryMgr::setRetryUntilRetrievedFlag() { retryUntilRetrievedFlag = true; } const bool& RetryMgr::getRetryUntilRetrievedFlag() const { return retryUntilRetrievedFlag; } <commit_msg>Fix: passing the exception.<commit_after>/* * Copyright (C) 2009 Toni Gundogdu. * * This file is part of cclive. * * cclive is free software: you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * cclive is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ #include "config.h" #include <string> #include <sstream> #include <climits> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HOST_W32 #include <windows.h> #define sleep(n) Sleep(n*1000) #endif #include "except.h" #include "video.h" #include "curl.h" #include "log.h" #include "opts.h" #include "retry.h" RetryMgr::RetryMgr() : retries(0), retryUntilRetrievedFlag(false) { } void RetryMgr::reset() { retries = 0; retryUntilRetrievedFlag = false; } void RetryMgr::handle(const CurlMgr::FetchException& x) { logmgr.cerr(x); const long httpcode = x.getHTTPCode(); if (httpcode >= 400 && httpcode < 500) throw x; // Pass the exception without retrying const Options opts = optsmgr.getOptions(); int maxRetry = opts.retry_arg; if (retryUntilRetrievedFlag) maxRetry = 0; // Override --retry limit for file downloads if (++retries <= opts.retry_arg || maxRetry == 0) { std::stringstream b; b << "retry #" << retries << "/" << maxRetry << " ... wait " << opts.retry_wait_arg << " second(s)."; logmgr.cerr(b.str(), false, false, false); sleep(opts.retry_wait_arg); logmgr.cerr() << std::endl; if (retries == INT_MAX-1) retries = 0; } else throw x; // Pass the exception, retries count not within our range } void RetryMgr::setRetryUntilRetrievedFlag() { retryUntilRetrievedFlag = true; } const bool& RetryMgr::getRetryUntilRetrievedFlag() const { return retryUntilRetrievedFlag; } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <boost/tokenizer.hpp> #include <vector> using namespace std; using namespace boost; class Connectors { private: string a[100]; bool state = 1; public: void setbool(bool b) { state = b; } bool getbool() { return state; } bool run(string arr[], bool k) == 0; }; class Semicolon { public: void run(string arr[]) { } }; class And { public: void run(string arr[]) { } }; class Or { public: void run(string arr[]) { } }; int main() { cout << "$ "; //outputs terminal $ string input; getline(cin, input); //gets user input vector<string> e_input; tokenizer<> tok(input); //uses tokenizer to parse the input for (tokenizer<>::iterator itr = tok.begin(); itr != tok.end(); ++itr) { if (*itr == ";" || ) { e_input.push_back(*itr); } } <commit_msg>Parsed and created objects in main<commit_after>#include <iostream> #include <string> #include <boost/tokenizer.hpp> #include <vector> #include <queue> using namespace std; using namespace boost; class Connectors { private: string a[100]; bool state; public: Connectors() { state = 1; } void setbool(bool b) { state = b; } bool getbool() { return state; } virtual bool run(string arr[], bool k) = 0; }; class Semicolon { public: void run(string arr[]) { } }; class And { public: void run(string arr[]) { } }; class Or { public: void run(string arr[]) { } }; int main() { cout << "$ "; //outputs terminal $ string input; getline(cin, input); //gets user input //containers we'll use for storage vector< vector<string> > v; vector<Connectors*> objects; queue<string> q; bool check = 0; int column = 0; typedef tokenizer<char_separator<char> > tokenizer; char_separator<char> sep(" ", ";"); tokenizer tokens(input, sep); for (tokenizer::iterator itr = tokens.begin(); itr != tokens.end(); ++itr) { if (*itr == ";" && "||" && "&&") { q.push(*itr); v.at(column).push_back(NULL); column = column + 1; } else if (*itr == "#") { break; //if commented, break out of loop } else { v.at(column).push_back(*itr); } } vector<string> current; for (unsigned i = 0; i < v.at(i).size(); ++i) { for (unsigned j = 0; j < v.at(i).at(j).size(); ++j) { current.push_back(v.at(i).at(j)); } if (q.front() == ";") { Semicolon s = new Semicolon(current); objects.push_back(s); } if (q.front() == "||") { Or o = new Or(current); objects.push_back(o); } if (q.front() == "&&") { And a = new And(current); objects.push_back(a); } q.pop(); current.clear(); } } <|endoftext|>
<commit_before>#include "./scene.h" #include <QCursor> #include <Eigen/Core> #include <Eigen/Geometry> #include <string> #include <vector> #include "./graphics/gl.h" #include "./input/invoke_manager.h" #include "./graphics/render_data.h" #include "./camera_controller.h" #include "./camera_rotation_controller.h" #include "./camera_zoom_controller.h" #include "./camera_move_controller.h" #include "./nodes.h" #include "./label_node.h" #include "./forces/labeller_frame_data.h" #include "./eigen_qdebug.h" #include "./importer.h" Scene::Scene(std::shared_ptr<InvokeManager> invokeManager, std::shared_ptr<Nodes> nodes, std::shared_ptr<Labels> labels, std::shared_ptr<Forces::Labeller> labeller) : nodes(nodes), labels(labels), labeller(labeller), frustumOptimizer(nodes) { cameraController = std::make_shared<CameraController>(camera); cameraRotationController = std::make_shared<CameraRotationController>(camera); cameraZoomController = std::make_shared<CameraZoomController>(camera); cameraMoveController = std::make_shared<CameraMoveController>(camera); invokeManager->addHandler("cam", cameraController.get()); invokeManager->addHandler("cameraRotation", cameraRotationController.get()); invokeManager->addHandler("cameraZoom", cameraZoomController.get()); invokeManager->addHandler("cameraMove", cameraMoveController.get()); fbo = std::unique_ptr<Graphics::FrameBufferObject>( new Graphics::FrameBufferObject()); } Scene::~Scene() { qDebug() << "Destructor of Scene"; } void Scene::initialize() { glAssert(gl->glClearColor(0.9f, 0.9f, 0.8f, 1.0f)); quad = std::make_shared<Graphics::Quad>(); Importer importer; anchorMesh = importer.import("assets/anchor.dae", 0); anchorMesh->initialize(gl); fbo->initialize(gl, width, height); haBuffer = std::make_shared<Graphics::HABuffer>(Eigen::Vector2i(width, height)); haBuffer->initialize(gl); } void Scene::update(double frameTime, QSet<Qt::Key> keysPressed) { this->frameTime = frameTime; cameraController->setFrameTime(frameTime); cameraRotationController->setFrameTime(frameTime); cameraZoomController->setFrameTime(frameTime); cameraMoveController->setFrameTime(frameTime); /* frustumOptimizer.update(camera.getViewMatrix()); camera.updateNearAndFarPlanes(frustumOptimizer.getNear(), frustumOptimizer.getFar()); */ /* auto newPositions = labeller->update(Forces::LabellerFrameData( frameTime, camera.getProjectionMatrix(), camera.getViewMatrix())); for (auto &labelNode : nodes->getLabelNodes()) { labelNode->labelPosition = newPositions[labelNode->label.id]; } */ } void Scene::render() { if (shouldResize) { camera.resize(width, height); fbo->resize(width, height); shouldResize = false; } glAssert(gl->glViewport(0, 0, width, height)); glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); // fbo->bind(); glAssert(gl->glViewport(0, 0, width, height)); glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); RenderData renderData; renderData.projectionMatrix = camera.getProjectionMatrix(); renderData.viewMatrix = camera.getViewMatrix(); renderData.cameraPosition = camera.getPosition(); Eigen::Affine3f modelTransform(Eigen::Translation3f(0, 0, 0) * Eigen::Scaling(0.4f)); renderData.modelMatrix = modelTransform.matrix(); // renderData.modelMatrix = Eigen::Matrix4f::Identity(); haBuffer->clear(); // nodes->render(gl, haBuffer, renderData); anchorMesh->render(gl, haBuffer, renderData); Eigen::Affine3f modelTransform2(Eigen::Translation3f(1, 0, 0) * Eigen::Scaling(0.4f)); renderData.modelMatrix = modelTransform2.matrix(); anchorMesh->render(gl, haBuffer, renderData); haBuffer->end(); haBuffer->render(); doPick(); // fbo->unbind(); // renderScreenQuad(); } void Scene::renderScreenQuad() { RenderData renderData; renderData.projectionMatrix = Eigen::Matrix4f::Identity(); renderData.viewMatrix = Eigen::Matrix4f::Identity(); renderData.modelMatrix = Eigen::Affine3f(Eigen::AlignedScaling3f(1, -1, 1)).matrix(); fbo->bindColorTexture(GL_TEXTURE0); // fbo->bindDepthTexture(GL_TEXTURE0); quad->renderToFrameBuffer(gl, renderData); } void Scene::resize(int width, int height) { this->width = width; this->height = height; shouldResize = true; } void Scene::pick(int id, Eigen::Vector2f position) { pickingPosition = position; performPicking = true; pickingLabelId = id; } void Scene::doPick() { if (!performPicking) return; float depth = -2.0f; fbo->bindDepthTexture(GL_TEXTURE0); glAssert(gl->glReadPixels(pickingPosition.x(), height - pickingPosition.y() - 1, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth)); Eigen::Vector4f positionNDC(pickingPosition.x() * 2.0f / width - 1.0f, pickingPosition.y() * -2.0f / height + 1.0f, depth * 2.0f - 1.0f, 1.0f); Eigen::Matrix4f viewProjection = camera.getProjectionMatrix() * camera.getViewMatrix(); Eigen::Vector4f positionWorld = viewProjection.inverse() * positionNDC; positionWorld = positionWorld / positionWorld.w(); qWarning() << "picked:" << positionWorld; performPicking = false; auto label = labels->getById(pickingLabelId); label.anchorPosition = toVector3f(positionWorld); labels->update(label); } <commit_msg>Readd nodes to scene.<commit_after>#include "./scene.h" #include <QCursor> #include <Eigen/Core> #include <Eigen/Geometry> #include <string> #include <vector> #include "./graphics/gl.h" #include "./input/invoke_manager.h" #include "./graphics/render_data.h" #include "./camera_controller.h" #include "./camera_rotation_controller.h" #include "./camera_zoom_controller.h" #include "./camera_move_controller.h" #include "./nodes.h" #include "./label_node.h" #include "./forces/labeller_frame_data.h" #include "./eigen_qdebug.h" #include "./importer.h" Scene::Scene(std::shared_ptr<InvokeManager> invokeManager, std::shared_ptr<Nodes> nodes, std::shared_ptr<Labels> labels, std::shared_ptr<Forces::Labeller> labeller) : nodes(nodes), labels(labels), labeller(labeller), frustumOptimizer(nodes) { cameraController = std::make_shared<CameraController>(camera); cameraRotationController = std::make_shared<CameraRotationController>(camera); cameraZoomController = std::make_shared<CameraZoomController>(camera); cameraMoveController = std::make_shared<CameraMoveController>(camera); invokeManager->addHandler("cam", cameraController.get()); invokeManager->addHandler("cameraRotation", cameraRotationController.get()); invokeManager->addHandler("cameraZoom", cameraZoomController.get()); invokeManager->addHandler("cameraMove", cameraMoveController.get()); fbo = std::unique_ptr<Graphics::FrameBufferObject>( new Graphics::FrameBufferObject()); } Scene::~Scene() { qDebug() << "Destructor of Scene"; } void Scene::initialize() { glAssert(gl->glClearColor(0.9f, 0.9f, 0.8f, 1.0f)); quad = std::make_shared<Graphics::Quad>(); Importer importer; anchorMesh = importer.import("assets/anchor.dae", 0); anchorMesh->initialize(gl); fbo->initialize(gl, width, height); haBuffer = std::make_shared<Graphics::HABuffer>(Eigen::Vector2i(width, height)); haBuffer->initialize(gl); } void Scene::update(double frameTime, QSet<Qt::Key> keysPressed) { this->frameTime = frameTime; cameraController->setFrameTime(frameTime); cameraRotationController->setFrameTime(frameTime); cameraZoomController->setFrameTime(frameTime); cameraMoveController->setFrameTime(frameTime); /* frustumOptimizer.update(camera.getViewMatrix()); camera.updateNearAndFarPlanes(frustumOptimizer.getNear(), frustumOptimizer.getFar()); */ /* auto newPositions = labeller->update(Forces::LabellerFrameData( frameTime, camera.getProjectionMatrix(), camera.getViewMatrix())); for (auto &labelNode : nodes->getLabelNodes()) { labelNode->labelPosition = newPositions[labelNode->label.id]; } */ } void Scene::render() { if (shouldResize) { camera.resize(width, height); fbo->resize(width, height); shouldResize = false; } glAssert(gl->glViewport(0, 0, width, height)); glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); // fbo->bind(); glAssert(gl->glViewport(0, 0, width, height)); glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); RenderData renderData; renderData.projectionMatrix = camera.getProjectionMatrix(); renderData.viewMatrix = camera.getViewMatrix(); renderData.cameraPosition = camera.getPosition(); Eigen::Affine3f modelTransform(Eigen::Translation3f(0, 0, 0) * Eigen::Scaling(0.4f)); renderData.modelMatrix = modelTransform.matrix(); // renderData.modelMatrix = Eigen::Matrix4f::Identity(); haBuffer->clear(); nodes->render(gl, haBuffer, renderData); anchorMesh->render(gl, haBuffer, renderData); Eigen::Affine3f modelTransform2(Eigen::Translation3f(1, 0, 0) * Eigen::Scaling(0.4f)); renderData.modelMatrix = modelTransform2.matrix(); anchorMesh->render(gl, haBuffer, renderData); haBuffer->end(); haBuffer->render(); doPick(); // fbo->unbind(); // renderScreenQuad(); } void Scene::renderScreenQuad() { RenderData renderData; renderData.projectionMatrix = Eigen::Matrix4f::Identity(); renderData.viewMatrix = Eigen::Matrix4f::Identity(); renderData.modelMatrix = Eigen::Affine3f(Eigen::AlignedScaling3f(1, -1, 1)).matrix(); fbo->bindColorTexture(GL_TEXTURE0); // fbo->bindDepthTexture(GL_TEXTURE0); quad->renderToFrameBuffer(gl, renderData); } void Scene::resize(int width, int height) { this->width = width; this->height = height; shouldResize = true; } void Scene::pick(int id, Eigen::Vector2f position) { pickingPosition = position; performPicking = true; pickingLabelId = id; } void Scene::doPick() { if (!performPicking) return; float depth = -2.0f; fbo->bindDepthTexture(GL_TEXTURE0); glAssert(gl->glReadPixels(pickingPosition.x(), height - pickingPosition.y() - 1, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth)); Eigen::Vector4f positionNDC(pickingPosition.x() * 2.0f / width - 1.0f, pickingPosition.y() * -2.0f / height + 1.0f, depth * 2.0f - 1.0f, 1.0f); Eigen::Matrix4f viewProjection = camera.getProjectionMatrix() * camera.getViewMatrix(); Eigen::Vector4f positionWorld = viewProjection.inverse() * positionNDC; positionWorld = positionWorld / positionWorld.w(); qWarning() << "picked:" << positionWorld; performPicking = false; auto label = labels->getById(pickingLabelId); label.anchorPosition = toVector3f(positionWorld); labels->update(label); } <|endoftext|>
<commit_before>/** * PANDA 3D SOFTWARE * Copyright (c) Carnegie Mellon University. All rights reserved. * * All use of this software is subject to the terms of the revised BSD * license. You should have received a copy of this license along * with this source code in a file named "LICENSE." * * @file gamepadButton.cxx * @author rdb * @date 2015-08-21 */ #include "gamepadButton.h" #include "buttonRegistry.h" #define DEFINE_GAMEPAD_BUTTON_HANDLE(KeyName) \ static ButtonHandle _##KeyName; \ ButtonHandle GamepadButton::KeyName() { return _##KeyName; } DEFINE_GAMEPAD_BUTTON_HANDLE(lstick) DEFINE_GAMEPAD_BUTTON_HANDLE(rstick) DEFINE_GAMEPAD_BUTTON_HANDLE(lshoulder) DEFINE_GAMEPAD_BUTTON_HANDLE(rshoulder) DEFINE_GAMEPAD_BUTTON_HANDLE(ltrigger) DEFINE_GAMEPAD_BUTTON_HANDLE(rtrigger) DEFINE_GAMEPAD_BUTTON_HANDLE(dpad_left) DEFINE_GAMEPAD_BUTTON_HANDLE(dpad_right) DEFINE_GAMEPAD_BUTTON_HANDLE(dpad_up) DEFINE_GAMEPAD_BUTTON_HANDLE(dpad_down) DEFINE_GAMEPAD_BUTTON_HANDLE(back) DEFINE_GAMEPAD_BUTTON_HANDLE(guide) DEFINE_GAMEPAD_BUTTON_HANDLE(start) DEFINE_GAMEPAD_BUTTON_HANDLE(next) DEFINE_GAMEPAD_BUTTON_HANDLE(previous) DEFINE_GAMEPAD_BUTTON_HANDLE(action_a) DEFINE_GAMEPAD_BUTTON_HANDLE(action_b) DEFINE_GAMEPAD_BUTTON_HANDLE(action_c) DEFINE_GAMEPAD_BUTTON_HANDLE(action_x) DEFINE_GAMEPAD_BUTTON_HANDLE(action_y) DEFINE_GAMEPAD_BUTTON_HANDLE(action_z) DEFINE_GAMEPAD_BUTTON_HANDLE(action_1) DEFINE_GAMEPAD_BUTTON_HANDLE(action_2) DEFINE_GAMEPAD_BUTTON_HANDLE(trigger) DEFINE_GAMEPAD_BUTTON_HANDLE(hat_up) DEFINE_GAMEPAD_BUTTON_HANDLE(hat_down) DEFINE_GAMEPAD_BUTTON_HANDLE(hat_left) DEFINE_GAMEPAD_BUTTON_HANDLE(hat_right) /** * Returns the ButtonHandle associated with the particular numbered joystick * button (zero-based), if there is one, or ButtonHandle::none() if there is * not. */ ButtonHandle GamepadButton:: joystick(int button_number) { if (button_number >= 0) { // "button1" does not exist, it is called "trigger" instead static pvector<ButtonHandle> buttons(1, _trigger); while (button_number >= buttons.size()) { char numstr[20]; sprintf(numstr, "joystick%d", (int)buttons.size() + 1); ButtonHandle handle; ButtonRegistry::ptr()->register_button(handle, numstr); buttons.push_back(handle); } return buttons[button_number]; } return ButtonHandle::none(); } /** * This is intended to be called only once, by the static initialization * performed in config_util.cxx. */ void GamepadButton:: init_gamepad_buttons() { ButtonRegistry::ptr()->register_button(_lstick, "lstick"); ButtonRegistry::ptr()->register_button(_rstick, "rstick"); ButtonRegistry::ptr()->register_button(_lshoulder, "lshoulder"); ButtonRegistry::ptr()->register_button(_rshoulder, "rshoulder"); ButtonRegistry::ptr()->register_button(_ltrigger, "ltrigger"); ButtonRegistry::ptr()->register_button(_rtrigger, "rtrigger"); ButtonRegistry::ptr()->register_button(_dpad_left, "dpad_left"); ButtonRegistry::ptr()->register_button(_dpad_right, "dpad_right"); ButtonRegistry::ptr()->register_button(_dpad_up, "dpad_up"); ButtonRegistry::ptr()->register_button(_dpad_down, "dpad_down"); ButtonRegistry::ptr()->register_button(_back, "back"); ButtonRegistry::ptr()->register_button(_guide, "guide"); ButtonRegistry::ptr()->register_button(_start, "start"); ButtonRegistry::ptr()->register_button(_next, "next"); ButtonRegistry::ptr()->register_button(_previous, "previous"); ButtonRegistry::ptr()->register_button(_action_a, "action_a"); ButtonRegistry::ptr()->register_button(_action_b, "action_b"); ButtonRegistry::ptr()->register_button(_action_c, "action_c"); ButtonRegistry::ptr()->register_button(_action_x, "action_x"); ButtonRegistry::ptr()->register_button(_action_y, "action_y"); ButtonRegistry::ptr()->register_button(_action_z, "action_z"); ButtonRegistry::ptr()->register_button(_action_1, "action_1"); ButtonRegistry::ptr()->register_button(_action_2, "action_2"); ButtonRegistry::ptr()->register_button(_trigger, "trigger"); ButtonRegistry::ptr()->register_button(_hat_up, "hat_up"); ButtonRegistry::ptr()->register_button(_hat_down, "hat_down"); ButtonRegistry::ptr()->register_button(_hat_left, "hat_left"); ButtonRegistry::ptr()->register_button(_hat_right, "hat_right"); } <commit_msg>putil: fix a compiler warning<commit_after>/** * PANDA 3D SOFTWARE * Copyright (c) Carnegie Mellon University. All rights reserved. * * All use of this software is subject to the terms of the revised BSD * license. You should have received a copy of this license along * with this source code in a file named "LICENSE." * * @file gamepadButton.cxx * @author rdb * @date 2015-08-21 */ #include "gamepadButton.h" #include "buttonRegistry.h" #define DEFINE_GAMEPAD_BUTTON_HANDLE(KeyName) \ static ButtonHandle _##KeyName; \ ButtonHandle GamepadButton::KeyName() { return _##KeyName; } DEFINE_GAMEPAD_BUTTON_HANDLE(lstick) DEFINE_GAMEPAD_BUTTON_HANDLE(rstick) DEFINE_GAMEPAD_BUTTON_HANDLE(lshoulder) DEFINE_GAMEPAD_BUTTON_HANDLE(rshoulder) DEFINE_GAMEPAD_BUTTON_HANDLE(ltrigger) DEFINE_GAMEPAD_BUTTON_HANDLE(rtrigger) DEFINE_GAMEPAD_BUTTON_HANDLE(dpad_left) DEFINE_GAMEPAD_BUTTON_HANDLE(dpad_right) DEFINE_GAMEPAD_BUTTON_HANDLE(dpad_up) DEFINE_GAMEPAD_BUTTON_HANDLE(dpad_down) DEFINE_GAMEPAD_BUTTON_HANDLE(back) DEFINE_GAMEPAD_BUTTON_HANDLE(guide) DEFINE_GAMEPAD_BUTTON_HANDLE(start) DEFINE_GAMEPAD_BUTTON_HANDLE(next) DEFINE_GAMEPAD_BUTTON_HANDLE(previous) DEFINE_GAMEPAD_BUTTON_HANDLE(action_a) DEFINE_GAMEPAD_BUTTON_HANDLE(action_b) DEFINE_GAMEPAD_BUTTON_HANDLE(action_c) DEFINE_GAMEPAD_BUTTON_HANDLE(action_x) DEFINE_GAMEPAD_BUTTON_HANDLE(action_y) DEFINE_GAMEPAD_BUTTON_HANDLE(action_z) DEFINE_GAMEPAD_BUTTON_HANDLE(action_1) DEFINE_GAMEPAD_BUTTON_HANDLE(action_2) DEFINE_GAMEPAD_BUTTON_HANDLE(trigger) DEFINE_GAMEPAD_BUTTON_HANDLE(hat_up) DEFINE_GAMEPAD_BUTTON_HANDLE(hat_down) DEFINE_GAMEPAD_BUTTON_HANDLE(hat_left) DEFINE_GAMEPAD_BUTTON_HANDLE(hat_right) /** * Returns the ButtonHandle associated with the particular numbered joystick * button (zero-based), if there is one, or ButtonHandle::none() if there is * not. */ ButtonHandle GamepadButton:: joystick(int button_number) { if (button_number >= 0) { // "button1" does not exist, it is called "trigger" instead static pvector<ButtonHandle> buttons(1, _trigger); while ((size_t)button_number >= buttons.size()) { char numstr[20]; sprintf(numstr, "joystick%d", (int)buttons.size() + 1); ButtonHandle handle; ButtonRegistry::ptr()->register_button(handle, numstr); buttons.push_back(handle); } return buttons[button_number]; } return ButtonHandle::none(); } /** * This is intended to be called only once, by the static initialization * performed in config_util.cxx. */ void GamepadButton:: init_gamepad_buttons() { ButtonRegistry::ptr()->register_button(_lstick, "lstick"); ButtonRegistry::ptr()->register_button(_rstick, "rstick"); ButtonRegistry::ptr()->register_button(_lshoulder, "lshoulder"); ButtonRegistry::ptr()->register_button(_rshoulder, "rshoulder"); ButtonRegistry::ptr()->register_button(_ltrigger, "ltrigger"); ButtonRegistry::ptr()->register_button(_rtrigger, "rtrigger"); ButtonRegistry::ptr()->register_button(_dpad_left, "dpad_left"); ButtonRegistry::ptr()->register_button(_dpad_right, "dpad_right"); ButtonRegistry::ptr()->register_button(_dpad_up, "dpad_up"); ButtonRegistry::ptr()->register_button(_dpad_down, "dpad_down"); ButtonRegistry::ptr()->register_button(_back, "back"); ButtonRegistry::ptr()->register_button(_guide, "guide"); ButtonRegistry::ptr()->register_button(_start, "start"); ButtonRegistry::ptr()->register_button(_next, "next"); ButtonRegistry::ptr()->register_button(_previous, "previous"); ButtonRegistry::ptr()->register_button(_action_a, "action_a"); ButtonRegistry::ptr()->register_button(_action_b, "action_b"); ButtonRegistry::ptr()->register_button(_action_c, "action_c"); ButtonRegistry::ptr()->register_button(_action_x, "action_x"); ButtonRegistry::ptr()->register_button(_action_y, "action_y"); ButtonRegistry::ptr()->register_button(_action_z, "action_z"); ButtonRegistry::ptr()->register_button(_action_1, "action_1"); ButtonRegistry::ptr()->register_button(_action_2, "action_2"); ButtonRegistry::ptr()->register_button(_trigger, "trigger"); ButtonRegistry::ptr()->register_button(_hat_up, "hat_up"); ButtonRegistry::ptr()->register_button(_hat_down, "hat_down"); ButtonRegistry::ptr()->register_button(_hat_left, "hat_left"); ButtonRegistry::ptr()->register_button(_hat_right, "hat_right"); } <|endoftext|>
<commit_before>// Copyright (c) 2014-2016 The Dash developers // Copyright (c) 2016-2018 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "masternode-budget.h" #include "messagesigner.h" #include "net.h" #include "spork.h" #include "sporkdb.h" #define MAKE_SPORK_DEF(name, defaultValue) CSporkDef(name, defaultValue, #name) std::vector<CSporkDef> sporkDefs = { MAKE_SPORK_DEF(SPORK_2_SWIFTTX, 0), // ON MAKE_SPORK_DEF(SPORK_3_SWIFTTX_BLOCK_FILTERING, 0), // ON MAKE_SPORK_DEF(SPORK_5_MAX_VALUE, 1000), // 1000 PIV MAKE_SPORK_DEF(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_10_MASTERNODE_PAY_UPDATED_NODES, 0), // OFF MAKE_SPORK_DEF(SPORK_13_ENABLE_SUPERBLOCKS, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_14_NEW_PROTOCOL_ENFORCEMENT, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_16_ZEROCOIN_MAINTENANCE_MODE, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_17_COLDSTAKING_ENFORCEMENT, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_18_ZEROCOIN_PUBLICSPEND_V4, 4070908800ULL), // OFF }; CSporkManager sporkManager; std::map<uint256, CSporkMessage> mapSporks; CSporkManager::CSporkManager() { for (auto& sporkDef : sporkDefs) { sporkDefsById.emplace(sporkDef.sporkId, &sporkDef); sporkDefsByName.emplace(sporkDef.name, &sporkDef); } } void CSporkManager::Clear() { strMasterPrivKey = ""; mapSporksActive.clear(); } // PIVX: on startup load spork values from previous session if they exist in the sporkDB void CSporkManager::LoadSporksFromDB() { for (const auto& sporkDef : sporkDefs) { // attempt to read spork from sporkDB CSporkMessage spork; if (!pSporkDB->ReadSpork(sporkDef.sporkId, spork)) { LogPrintf("%s : no previous value for %s found in database\n", __func__, sporkDef.name); continue; } // add spork to memory mapSporks[spork.GetHash()] = spork; mapSporksActive[spork.nSporkID] = spork; std::time_t result = spork.nValue; // If SPORK Value is greater than 1,000,000 assume it's actually a Date and then convert to a more readable format if (spork.nValue > 1000000) { LogPrintf("%s : loaded spork %s with value %d : %s", __func__, sporkManager.GetSporkNameByID(spork.nSporkID), spork.nValue, std::ctime(&result)); } else { LogPrintf("%s : loaded spork %s with value %d\n", __func__, sporkManager.GetSporkNameByID(spork.nSporkID), spork.nValue); } } } void CSporkManager::ProcessSpork(CNode* pfrom, std::string& strCommand, CDataStream& vRecv) { if (fLiteMode || chainActive.Tip() == nullptr) return; // disable all obfuscation/masternode related functionality if (strCommand == "spork") { CSporkMessage spork; vRecv >> spork; // Ignore spork messages about unknown/deleted sporks std::string strSpork = sporkManager.GetSporkNameByID(spork.nSporkID); if (strSpork == "Unknown") return; // Do not accept sporks signed way too far into the future if (spork.nTimeSigned > GetAdjustedTime() + 2 * 60 * 60) { LOCK(cs_main); LogPrintf("%s : ERROR: too far into the future\n", __func__); Misbehaving(pfrom->GetId(), 100); return; } // reject old signatures 600 blocks after hard-fork if (spork.nMessVersion != MessageVersion::MESS_VER_HASH) { int nHeight; { LOCK(cs_main); nHeight = chainActive.Height(); } if (Params().NewSigsActive(nHeight - 600)) { LogPrintf("%s : nMessVersion=%d not accepted anymore at block %d", __func__, spork.nMessVersion, nHeight); return; } } uint256 hash = spork.GetHash(); { LOCK(cs); if (mapSporksActive.count(spork.nSporkID)) { // spork is active if (mapSporksActive[spork.nSporkID].nTimeSigned >= spork.nTimeSigned) { // spork in memory has been signed more recently if (fDebug) LogPrintf("%s : seen %s block %d \n", __func__, hash.ToString(), chainActive.Tip()->nHeight); return; } else { // update active spork if (fDebug) LogPrintf("%s : got updated spork %s block %d \n", __func__, hash.ToString(), chainActive.Tip()->nHeight); } } else { // spork is not active if (fDebug) LogPrintf("%s : got new spork %s block %d \n", __func__, hash.ToString(), chainActive.Tip()->nHeight); } } LogPrintf("%s : new %s ID %d Time %d bestHeight %d\n", __func__, hash.ToString(), spork.nSporkID, spork.nValue, chainActive.Tip()->nHeight); const bool fRequireNew = spork.nTimeSigned >= Params().NewSporkStart(); bool fValidSig = spork.CheckSignature(); if (!fValidSig && !fRequireNew) { // See if window is open that allows for old spork key to sign messages if (GetAdjustedTime() < Params().RejectOldSporkKey()) { CPubKey pubkeyold = spork.GetPublicKeyOld(); fValidSig = spork.CheckSignature(pubkeyold); } } if (!fValidSig) { LOCK(cs_main); LogPrintf("%s : Invalid Signature\n", __func__); Misbehaving(pfrom->GetId(), 100); return; } { LOCK(cs); mapSporks[hash] = spork; mapSporksActive[spork.nSporkID] = spork; } spork.Relay(); // PIVX: add to spork database. pSporkDB->WriteSpork(spork.nSporkID, spork); } if (strCommand == "getsporks") { LOCK(cs); std::map<SporkId, CSporkMessage>::iterator it = mapSporksActive.begin(); while (it != mapSporksActive.end()) { pfrom->PushMessage("spork", it->second); it++; } } } bool CSporkManager::UpdateSpork(SporkId nSporkID, int64_t nValue) { bool fNewSigs = false; { LOCK(cs_main); fNewSigs = chainActive.NewSigsActive(); } CSporkMessage spork = CSporkMessage(nSporkID, nValue, GetTime()); if(spork.Sign(strMasterPrivKey, fNewSigs)){ spork.Relay(); LOCK(cs); mapSporks[spork.GetHash()] = spork; mapSporksActive[nSporkID] = spork; return true; } return false; } // grab the spork value, and see if it's off bool CSporkManager::IsSporkActive(SporkId nSporkID) { return GetSporkValue(nSporkID) < GetAdjustedTime(); } // grab the value of the spork on the network, or the default int64_t CSporkManager::GetSporkValue(SporkId nSporkID) { LOCK(cs); if (mapSporksActive.count(nSporkID)) { return mapSporksActive[nSporkID].nValue; } else { auto it = sporkDefsById.find(nSporkID); if (it != sporkDefsById.end()) { return it->second->defaultValue; } else { LogPrintf("%s : Unknown Spork %d\n", __func__, nSporkID); } } return -1; } SporkId CSporkManager::GetSporkIDByName(std::string strName) { auto it = sporkDefsByName.find(strName); if (it == sporkDefsByName.end()) { LogPrintf("%s : Unknown Spork name '%s'\n", __func__, strName); return SPORK_INVALID; } return it->second->sporkId; } std::string CSporkManager::GetSporkNameByID(SporkId nSporkID) { auto it = sporkDefsById.find(nSporkID); if (it == sporkDefsById.end()) { LogPrint("%s : Unknown Spork ID %d\n", __func__, nSporkID); return "Unknown"; } return it->second->name; } bool CSporkManager::SetPrivKey(std::string strPrivKey) { CSporkMessage spork; spork.Sign(strPrivKey, true); const bool fRequireNew = GetTime() >= Params().NewSporkStart(); bool fValidSig = spork.CheckSignature(); if (!fValidSig && !fRequireNew) { // See if window is open that allows for old spork key to sign messages if (GetAdjustedTime() < Params().RejectOldSporkKey()) { CPubKey pubkeyold = spork.GetPublicKeyOld(); fValidSig = spork.CheckSignature(pubkeyold); } } if (fValidSig) { LOCK(cs); // Test signing successful, proceed LogPrintf("%s : Successfully initialized as spork signer\n", __func__); strMasterPrivKey = strPrivKey; return true; } return false; } std::string CSporkManager::ToString() const { LOCK(cs); return strprintf("Sporks: %llu", mapSporksActive.size()); } uint256 CSporkMessage::GetSignatureHash() const { CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << nMessVersion; ss << nSporkID; ss << nValue; ss << nTimeSigned; return ss.GetHash(); } std::string CSporkMessage::GetStrMessage() const { return std::to_string(nSporkID) + std::to_string(nValue) + std::to_string(nTimeSigned); } const CPubKey CSporkMessage::GetPublicKey(std::string& strErrorRet) const { return CPubKey(ParseHex(Params().SporkPubKey())); } const CPubKey CSporkMessage::GetPublicKeyOld() const { return CPubKey(ParseHex(Params().SporkPubKeyOld())); } void CSporkMessage::Relay() { CInv inv(MSG_SPORK, GetHash()); RelayInv(inv); } <commit_msg>[Spork] Segfault when spork value exceeds the bounds of ctime conversion fixed.<commit_after>// Copyright (c) 2014-2016 The Dash developers // Copyright (c) 2016-2018 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "masternode-budget.h" #include "messagesigner.h" #include "net.h" #include "spork.h" #include "sporkdb.h" #include <iostream> #define MAKE_SPORK_DEF(name, defaultValue) CSporkDef(name, defaultValue, #name) std::vector<CSporkDef> sporkDefs = { MAKE_SPORK_DEF(SPORK_2_SWIFTTX, 0), // ON MAKE_SPORK_DEF(SPORK_3_SWIFTTX_BLOCK_FILTERING, 0), // ON MAKE_SPORK_DEF(SPORK_5_MAX_VALUE, 1000), // 1000 PIV MAKE_SPORK_DEF(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_10_MASTERNODE_PAY_UPDATED_NODES, 0), // OFF MAKE_SPORK_DEF(SPORK_13_ENABLE_SUPERBLOCKS, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_14_NEW_PROTOCOL_ENFORCEMENT, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_16_ZEROCOIN_MAINTENANCE_MODE, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_17_COLDSTAKING_ENFORCEMENT, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_18_ZEROCOIN_PUBLICSPEND_V4, 4070908800ULL), // OFF }; CSporkManager sporkManager; std::map<uint256, CSporkMessage> mapSporks; CSporkManager::CSporkManager() { for (auto& sporkDef : sporkDefs) { sporkDefsById.emplace(sporkDef.sporkId, &sporkDef); sporkDefsByName.emplace(sporkDef.name, &sporkDef); } } void CSporkManager::Clear() { strMasterPrivKey = ""; mapSporksActive.clear(); } // PIVX: on startup load spork values from previous session if they exist in the sporkDB void CSporkManager::LoadSporksFromDB() { for (const auto& sporkDef : sporkDefs) { // attempt to read spork from sporkDB CSporkMessage spork; if (!pSporkDB->ReadSpork(sporkDef.sporkId, spork)) { LogPrintf("%s : no previous value for %s found in database\n", __func__, sporkDef.name); continue; } // add spork to memory mapSporks[spork.GetHash()] = spork; mapSporksActive[spork.nSporkID] = spork; std::time_t result = spork.nValue; // If SPORK Value is greater than 1,000,000 assume it's actually a Date and then convert to a more readable format std::string sporkName = sporkManager.GetSporkNameByID(spork.nSporkID); if (spork.nValue > 1000000) { char* res = std::ctime(&result); LogPrintf("%s : loaded spork %s with value %d : %s\n", __func__, sporkName.c_str(), spork.nValue, ((res) ? res : "no time") ); } else { LogPrintf("%s : loaded spork %s with value %d\n", __func__, sporkName, spork.nValue); } } } void CSporkManager::ProcessSpork(CNode* pfrom, std::string& strCommand, CDataStream& vRecv) { if (fLiteMode || chainActive.Tip() == nullptr) return; // disable all obfuscation/masternode related functionality if (strCommand == "spork") { CSporkMessage spork; vRecv >> spork; // Ignore spork messages about unknown/deleted sporks std::string strSpork = sporkManager.GetSporkNameByID(spork.nSporkID); if (strSpork == "Unknown") return; // Do not accept sporks signed way too far into the future if (spork.nTimeSigned > GetAdjustedTime() + 2 * 60 * 60) { LOCK(cs_main); LogPrintf("%s : ERROR: too far into the future\n", __func__); Misbehaving(pfrom->GetId(), 100); return; } // reject old signatures 600 blocks after hard-fork if (spork.nMessVersion != MessageVersion::MESS_VER_HASH) { int nHeight; { LOCK(cs_main); nHeight = chainActive.Height(); } if (Params().NewSigsActive(nHeight - 600)) { LogPrintf("%s : nMessVersion=%d not accepted anymore at block %d", __func__, spork.nMessVersion, nHeight); return; } } uint256 hash = spork.GetHash(); { LOCK(cs); if (mapSporksActive.count(spork.nSporkID)) { // spork is active if (mapSporksActive[spork.nSporkID].nTimeSigned >= spork.nTimeSigned) { // spork in memory has been signed more recently if (fDebug) LogPrintf("%s : seen %s block %d \n", __func__, hash.ToString(), chainActive.Tip()->nHeight); return; } else { // update active spork if (fDebug) LogPrintf("%s : got updated spork %s block %d \n", __func__, hash.ToString(), chainActive.Tip()->nHeight); } } else { // spork is not active if (fDebug) LogPrintf("%s : got new spork %s block %d \n", __func__, hash.ToString(), chainActive.Tip()->nHeight); } } LogPrintf("%s : new %s ID %d Time %d bestHeight %d\n", __func__, hash.ToString(), spork.nSporkID, spork.nValue, chainActive.Tip()->nHeight); const bool fRequireNew = spork.nTimeSigned >= Params().NewSporkStart(); bool fValidSig = spork.CheckSignature(); if (!fValidSig && !fRequireNew) { // See if window is open that allows for old spork key to sign messages if (GetAdjustedTime() < Params().RejectOldSporkKey()) { CPubKey pubkeyold = spork.GetPublicKeyOld(); fValidSig = spork.CheckSignature(pubkeyold); } } if (!fValidSig) { LOCK(cs_main); LogPrintf("%s : Invalid Signature\n", __func__); Misbehaving(pfrom->GetId(), 100); return; } { LOCK(cs); mapSporks[hash] = spork; mapSporksActive[spork.nSporkID] = spork; } spork.Relay(); // PIVX: add to spork database. pSporkDB->WriteSpork(spork.nSporkID, spork); } if (strCommand == "getsporks") { LOCK(cs); std::map<SporkId, CSporkMessage>::iterator it = mapSporksActive.begin(); while (it != mapSporksActive.end()) { pfrom->PushMessage("spork", it->second); it++; } } } bool CSporkManager::UpdateSpork(SporkId nSporkID, int64_t nValue) { bool fNewSigs = false; { LOCK(cs_main); fNewSigs = chainActive.NewSigsActive(); } CSporkMessage spork = CSporkMessage(nSporkID, nValue, GetTime()); if(spork.Sign(strMasterPrivKey, fNewSigs)){ spork.Relay(); LOCK(cs); mapSporks[spork.GetHash()] = spork; mapSporksActive[nSporkID] = spork; return true; } return false; } // grab the spork value, and see if it's off bool CSporkManager::IsSporkActive(SporkId nSporkID) { return GetSporkValue(nSporkID) < GetAdjustedTime(); } // grab the value of the spork on the network, or the default int64_t CSporkManager::GetSporkValue(SporkId nSporkID) { LOCK(cs); if (mapSporksActive.count(nSporkID)) { return mapSporksActive[nSporkID].nValue; } else { auto it = sporkDefsById.find(nSporkID); if (it != sporkDefsById.end()) { return it->second->defaultValue; } else { LogPrintf("%s : Unknown Spork %d\n", __func__, nSporkID); } } return -1; } SporkId CSporkManager::GetSporkIDByName(std::string strName) { auto it = sporkDefsByName.find(strName); if (it == sporkDefsByName.end()) { LogPrintf("%s : Unknown Spork name '%s'\n", __func__, strName); return SPORK_INVALID; } return it->second->sporkId; } std::string CSporkManager::GetSporkNameByID(SporkId nSporkID) { auto it = sporkDefsById.find(nSporkID); if (it == sporkDefsById.end()) { LogPrint("%s : Unknown Spork ID %d\n", __func__, nSporkID); return "Unknown"; } return it->second->name; } bool CSporkManager::SetPrivKey(std::string strPrivKey) { CSporkMessage spork; spork.Sign(strPrivKey, true); const bool fRequireNew = GetTime() >= Params().NewSporkStart(); bool fValidSig = spork.CheckSignature(); if (!fValidSig && !fRequireNew) { // See if window is open that allows for old spork key to sign messages if (GetAdjustedTime() < Params().RejectOldSporkKey()) { CPubKey pubkeyold = spork.GetPublicKeyOld(); fValidSig = spork.CheckSignature(pubkeyold); } } if (fValidSig) { LOCK(cs); // Test signing successful, proceed LogPrintf("%s : Successfully initialized as spork signer\n", __func__); strMasterPrivKey = strPrivKey; return true; } return false; } std::string CSporkManager::ToString() const { LOCK(cs); return strprintf("Sporks: %llu", mapSporksActive.size()); } uint256 CSporkMessage::GetSignatureHash() const { CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << nMessVersion; ss << nSporkID; ss << nValue; ss << nTimeSigned; return ss.GetHash(); } std::string CSporkMessage::GetStrMessage() const { return std::to_string(nSporkID) + std::to_string(nValue) + std::to_string(nTimeSigned); } const CPubKey CSporkMessage::GetPublicKey(std::string& strErrorRet) const { return CPubKey(ParseHex(Params().SporkPubKey())); } const CPubKey CSporkMessage::GetPublicKeyOld() const { return CPubKey(ParseHex(Params().SporkPubKeyOld())); } void CSporkMessage::Relay() { CInv inv(MSG_SPORK, GetHash()); RelayInv(inv); } <|endoftext|>
<commit_before>// Copyright (C) 2015 Jack Maloney. All Rights Reserved. // // This Source Code Form is subject to the terms of the Mozilla Public License, // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #include "voltz-internal.h" #include <stdlib.h> String BoxStringPhase1(const char* str) { String rv = (String) malloc(sizeof(struct voltz_string)); rv->isa = StringClass; rv->refs = 1; rv->weaks = 0; rv->value = strdup(str); return rv; } String (*voltz::BoxString)(const char*) = BoxStringPhase1; char* UnboxStringPhase1(String value) { return strdup(value->value); } char* (*voltz::UnboxString)(String) = UnboxStringPhase1;<commit_msg>Update string.cc<commit_after>// Copyright (C) 2015 Jack Maloney. All Rights Reserved. // // This Source Code Form is subject to the terms of the Mozilla Public License, // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #include "voltz-internal.h" #include <stdlib.h> #include <string.h> String BoxStringPhase1(const char* str) { String rv = (String) malloc(sizeof(struct voltz_string)); rv->isa = StringClass; rv->refs = 1; rv->weaks = 0; rv->value = strdup(str); return rv; } String (*voltz::BoxString)(const char*) = BoxStringPhase1; char* UnboxStringPhase1(String value) { return strdup(value->value); } char* (*voltz::UnboxString)(String) = UnboxStringPhase1; <|endoftext|>
<commit_before>#ifdef HAVE_CONFIG_H #include <config.h> #endif #if defined(USE_GETOPT_LONG) && !defined(_GNU_SOURCE) #define _GNU_SOURCE 1 #endif #include <iostream> #include <fstream> #include <clocale> #include <locale> #include <exception> #include <stdexcept> #ifdef HAVE_GETOPT_H #include <getopt.h> #endif #include "interp.hxx" #include "cmd/list.hxx" #include "options.hxx" #include "common.hxx" using namespace std; using namespace tglng; static void parse_cmdline_args(unsigned, const char*const*); int main(int argc, const char*const* argv) { wstring out; Interpreter interp; setlocale(LC_ALL, ""); setlocale(LC_NUMERIC, "C"); try { locale::global(locale("")); } catch (runtime_error& re) { /* When GNU libstdc++ is used on top of a non-GNU libc, no locales other than "C" are supported. On some versions of libstdc++, trying to set the default locale throws a runtime_error(). See: http://gcc.gnu.org/ml/libstdc++/2003-02/msg00345.html Unfortunately, no --use-my-systems-libc-dammit option seems to exist yet, especially not one usable at compilation time. If we catch the runtime_error, just ignore it and carry on --- there's nothing else we can do. */ } parse_cmdline_args(argc, argv); //Try to read from standard configuration file. //TODO: Change this to something more sensible { wifstream in("rc.default"); if (!interp.exec(out, in, Interpreter::ParseModeCommand)) { wcerr << L"Error reading user library." << endl; return EXIT_EXEC_ERROR_IN_USER_LIBRARY; } } if (interp.exec(out, wcin, Interpreter::ParseModeLiteral)) { wcout << out; Interpreter::freeGlobalBindings(); return 0; } else { wcerr << L"Failed." << endl; return EXIT_EXEC_ERROR_IN_INPUT; } } static void print_usage(void); static void parse_cmdline_args(unsigned argc, const char*const* argv) { #ifdef USE_GETOPT_LONG static const struct option long_options[] = { { "help", 0, NULL, 'h' }, { "file", 1, NULL, 'f' }, { "no-chdir", 0, NULL, 'H' }, { "config", 1, NULL, 'c' }, { "no-system-config", 0, NULL, 'C' }, { "script", 1, NULL, 'e' }, { "register", 1, NULL, 'D' }, { "dry-run", 0, NULL, 'd' }, { "locate-parse-error", 0, NULL, 'l' }, {0} }; #endif static const char short_options[] = "hf:Hc:Ce:D:dl"; int cmdstat; wstring wstr; do { #ifdef USE_GETOPT_LONG cmdstat = getopt_long(argc, const_cast<char**>(argv), short_options, long_options, NULL); #else cmdstat = getopt(argc, argv, short_options); #endif switch (cmdstat) { case -1: break; case 'h': case '?': print_usage(); if ('h' == cmdstat) exit(0); else exit(EXIT_INCORRECT_USAGE); break; case 'f': if (!ntbstowstr(operationalFile, optarg)) { wcerr << L"Unable to decode option for -f or --file" << endl; exit(EXIT_PLATFORM_ERROR); } break; case 'H': implicitChdir = false; break; case 'c': if (!ntbstowstr(wstr, optarg)) { wcerr << L"Unable to decode option for -c or --config" << endl; exit(EXIT_PLATFORM_ERROR); } tglng::list::lappend(userConfigs, wstr); break; case 'C': enableSystemConfig = false; break; case 'e': if (!ntbstowstr(wstr, optarg)) { wcerr << L"Unable to decode option for -e or --script" << endl; exit(EXIT_PLATFORM_ERROR); } scriptInputs.push_back(wstr); break; case 'D': if (!ntbstowstr(wstr, optarg)) { wcerr << L"Unable to decode option for -D or --define" << endl; exit(EXIT_PLATFORM_ERROR); } if (wstr.size() < 2) { wcerr << L"-D or --define must have an argument of the form X=..." << endl; exit(EXIT_INCORRECT_USAGE); } initialRegisters[wstr[0]] = wstr.substr(2); break; case 'd': dryRun = true; break; case 'l': locateParseError = true; break; default: wcerr << L"BUG: Unhandled cmdstat: " << cmdstat << endl; abort(); } } while (-1 != cmdstat); if ((unsigned)optind != argc) { wcerr << L"Extraneous arguments after options" << endl; print_usage(); exit(EXIT_INCORRECT_USAGE); } } static void print_usage(void) { } <commit_msg>Add usage information.<commit_after>#ifdef HAVE_CONFIG_H #include <config.h> #endif #if defined(USE_GETOPT_LONG) && !defined(_GNU_SOURCE) #define _GNU_SOURCE 1 #endif #include <iostream> #include <fstream> #include <clocale> #include <locale> #include <exception> #include <stdexcept> #ifdef HAVE_GETOPT_H #include <getopt.h> #endif #include "interp.hxx" #include "cmd/list.hxx" #include "options.hxx" #include "common.hxx" using namespace std; using namespace tglng; static void parseCmdlineArgs(unsigned, const char*const*); int main(int argc, const char*const* argv) { wstring out; Interpreter interp; setlocale(LC_ALL, ""); setlocale(LC_NUMERIC, "C"); try { locale::global(locale("")); } catch (runtime_error& re) { /* When GNU libstdc++ is used on top of a non-GNU libc, no locales other than "C" are supported. On some versions of libstdc++, trying to set the default locale throws a runtime_error(). See: http://gcc.gnu.org/ml/libstdc++/2003-02/msg00345.html Unfortunately, no --use-my-systems-libc-dammit option seems to exist yet, especially not one usable at compilation time. If we catch the runtime_error, just ignore it and carry on --- there's nothing else we can do. */ } parseCmdlineArgs(argc, argv); //Try to read from standard configuration file. //TODO: Change this to something more sensible { wifstream in("rc.default"); if (!interp.exec(out, in, Interpreter::ParseModeCommand)) { wcerr << L"Error reading user library." << endl; return EXIT_EXEC_ERROR_IN_USER_LIBRARY; } } if (interp.exec(out, wcin, Interpreter::ParseModeLiteral)) { wcout << out; Interpreter::freeGlobalBindings(); return 0; } else { wcerr << L"Failed." << endl; return EXIT_EXEC_ERROR_IN_INPUT; } } static void printUsage(bool); static void parseCmdlineArgs(unsigned argc, const char*const* argv) { #ifdef USE_GETOPT_LONG static const struct option long_options[] = { { "help", 0, NULL, 'h' }, { "file", 1, NULL, 'f' }, { "no-chdir", 0, NULL, 'H' }, { "config", 1, NULL, 'c' }, { "no-system-config", 0, NULL, 'C' }, { "script", 1, NULL, 'e' }, { "register", 1, NULL, 'D' }, { "dry-run", 0, NULL, 'd' }, { "locate-parse-error", 0, NULL, 'l' }, {0} }; #endif static const char short_options[] = "hf:Hc:Ce:D:dl"; int cmdstat; wstring wstr; do { #ifdef USE_GETOPT_LONG cmdstat = getopt_long(argc, const_cast<char**>(argv), short_options, long_options, NULL); #else cmdstat = getopt(argc, argv, short_options); #endif switch (cmdstat) { case -1: break; case 'h': case '?': printUsage('h' != cmdstat); exit('h' == cmdstat? 0 : EXIT_INCORRECT_USAGE); break; case 'f': if (!ntbstowstr(operationalFile, optarg)) { wcerr << L"Unable to decode option for -f or --file" << endl; exit(EXIT_PLATFORM_ERROR); } break; case 'H': implicitChdir = false; break; case 'c': if (!ntbstowstr(wstr, optarg)) { wcerr << L"Unable to decode option for -c or --config" << endl; exit(EXIT_PLATFORM_ERROR); } tglng::list::lappend(userConfigs, wstr); break; case 'C': enableSystemConfig = false; break; case 'e': if (!ntbstowstr(wstr, optarg)) { wcerr << L"Unable to decode option for -e or --script" << endl; exit(EXIT_PLATFORM_ERROR); } scriptInputs.push_back(wstr); break; case 'D': if (!ntbstowstr(wstr, optarg)) { wcerr << L"Unable to decode option for -D or --define" << endl; exit(EXIT_PLATFORM_ERROR); } if (wstr.size() < 2) { wcerr << L"-D or --define must have an argument of the form X=..." << endl; exit(EXIT_INCORRECT_USAGE); } initialRegisters[wstr[0]] = wstr.substr(2); break; case 'd': dryRun = true; break; case 'l': locateParseError = true; break; default: wcerr << L"BUG: Unhandled cmdstat: " << cmdstat << endl; abort(); } } while (-1 != cmdstat); if ((unsigned)optind != argc) { wcerr << L"Extraneous arguments after options" << endl; printUsage(true); exit(EXIT_INCORRECT_USAGE); } } static void printUsage(bool error) { (error? wcerr : wcout) << "Usage: tglng [OPTIONS...]\n" "Possible options are listed below. Arguments mandatory for long options\n" "are mandatory for the corresponding short options as well.\n" " -h, -?, --help\n" " Show this help message and exit.\n" " -f, --file=<filename>\n" " Indicates that the text produced by TglNG is expected to be added to\n" " a file named by <filename>. By default, TglNG will chdir() into the\n" " directory containing <filename>, unless --no-chdir is specified. It\n" " is also possible for user configuration to change based on the value\n" " of this option.\n" " -H, --no-chdir\n" " Suppress implicit chdir() into directory containing filename\n" " specified via --file.\n" " -c, --config=<file>\n" " Instead of reading user configuration from ~/.tglng, read it from\n" " <file>. This option may be specified multiple times; all listed\n" " files will be read for user configuration.\n" " -C, --no-system-config\n" " Suppress implicit reading of system-wide configuration. Note that\n" " quite a bit of TglNG functionality, including the handling of several\n" " command line arguments listed here, is implemented in the default\n" " system configuration.\n" " -e, --script=<file>\n" " Read primary program from <file> instead of standard input.\n" " Specifying this argument multiple times causes all listed files to\n" " be read and executed.\n" " -D, --define=<definition> <definition> ::= X=str\n" " Specifies that register <X> will initially have value <str>. This is\n" " applied whenever the reset-registers command is executed.\n" " -d, --dry-run\n" " Do everything but execute the primary input. In the case of multiple\n" " files specified by --script, each listed file is parsed but not\n" " executed.\n" " -l, --locate-parse-error\n" " If a parse error occurs, print the zero-based character offset of\n" " the primary input where the error was encountered to standard\n" " output, in addition to writing information about the error to\n" " standard output.\n" #ifndef USE_GETOPT_LONG "\n(Long options are not available on your system.)" #endif << endl; } <|endoftext|>
<commit_before>/* * ipop-tincan * Copyright 2015, University of Florida * * 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 <cstdio> #include <iostream> #if defined(LINUX) #include <ifaddrs.h> #elif defined(ANDROID) #include "talk/base/ifaddrs-android.h" #endif #include "talk/base/ssladapter.h" #include "controlleraccess.h" #include "tincanconnectionmanager.h" #include "tincan_utils.h" #include "xmppnetwork.h" #define SEGMENT_SIZE 3 #define SEGMENT_OFFSET 4 #define CMP_SIZE 7 namespace tincan { int kUdpPort = 5800; string kTapName ("ipop"); } class SendRunnable : public talk_base::Runnable { public: SendRunnable(thread_opts_t *opts) : opts_(opts) {} virtual void Run(talk_base::Thread *thread) { ipop_send_thread(opts_); } private: thread_opts_t *opts_; }; class RecvRunnable : public talk_base::Runnable { public: RecvRunnable(thread_opts_t *opts) : opts_(opts) {} virtual void Run(talk_base::Thread *thread) { ipop_recv_thread(opts_); } private: thread_opts_t *opts_; }; int get_free_network_ip(char *ip_addr, size_t len) { #if defined(LINUX) || defined(ANDROID) struct ifaddrs* interfaces; if (getifaddrs(&interfaces) != 0) return -1; // TODO - we should loop again whenever ip address changes char tmp_addr[NI_MAXHOST]; for (struct ifaddrs* ifa = interfaces; ifa != 0; ifa = ifa->ifa_next) { if (ifa->ifa_addr != 0 && ifa->ifa_addr->sa_family == AF_INET) { int error = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), tmp_addr, sizeof(tmp_addr), NULL, 0, NI_NUMERICHOST); if (error == 0) { if (strncmp(ip_addr, tmp_addr, CMP_SIZE) == 0) { char segment[SEGMENT_SIZE] = { '\0' }; memcpy(segment, ip_addr + SEGMENT_OFFSET, sizeof(segment) - 1); int i = atoi(segment) - 1; snprintf(ip_addr + SEGMENT_OFFSET, sizeof(segment), "%d", i); ip_addr[CMP_SIZE - 1] = '.'; // snprintf adds extra null } } } } freeifaddrs(interfaces); #endif return 0; } // TODO - Implement some kind of verification mechanism bool SSLVerificationCallback(void* cert) { return true; } /* The below method parses the arguments supplied to tincan*/ void parse_args(int argc,char **args) { if (argc == 2 && strncmp(args[1], "-v", 2)==0) { std::cout<<endl << "-----tincan version is-----"<< endl << tincan::kIpopVerMjr << "." << tincan::kIpopVerMnr << "." << tincan::kIpopVerRev << endl; exit(0); } if (argc == 2 && strncmp(args[1], "-h", 2)==0) { std::cout<<endl<<"---OPTIONAL---"<<endl << "To configure the name of tap device and listener port."<<endl << "pass tap-name as first arg and port as second."<<endl << "example--sudo sh -c './ipop-tincan looptap 5805 1> out.log 2> err.log &'"<< endl exit(0); } if (argc == 3) { tincan::kTapName = args[1]; tincan::kUdpPort = atoi(args[2]); } } int main(int argc, char **argv) { // Parse arguments parse_args(argc,argv); talk_base::InitializeSSL(SSLVerificationCallback); peerlist_init(); thread_opts_t opts; #if defined(LINUX) || defined(ANDROID) opts.tap = tap_open(tincan::kTapName.c_str(), opts.mac); if (opts.tap < 0) return -1; #elif defined(WIN32) opts.win32_tap = open_tap(tincan::kTapName.c_str(), opts.mac); if (opts.win32_tap < 0) return -1; #endif opts.translate = 0; opts.switchmode = 0; talk_base::Thread packet_handling_thread, send_thread, recv_thread; talk_base::AutoThread link_setup_thread; link_setup_thread.WrapCurrent(); tincan::PeerSignalSender signal_sender; tincan::TinCanConnectionManager manager(&signal_sender, &link_setup_thread, &packet_handling_thread, &opts); tincan::XmppNetwork xmpp(&link_setup_thread); xmpp.HandlePeer.connect(&manager, &tincan::TinCanConnectionManager::HandlePeer); talk_base::BasicPacketSocketFactory packet_factory; tincan::ControllerAccess controller(manager, xmpp, &packet_factory, &opts); signal_sender.add_service(0, &controller); signal_sender.add_service(1, &xmpp); opts.send_func = &tincan::TinCanConnectionManager::DoPacketSend; opts.recv_func = &tincan::TinCanConnectionManager::DoPacketRecv; // Checks to see if network is available, changes IP if not char ip_addr[NI_MAXHOST] = { '\0' }; manager.ipv4().copy(ip_addr, sizeof(ip_addr)); if (get_free_network_ip(ip_addr, sizeof(ip_addr)) == 0) { manager.set_ip(ip_addr); } // Setup/run threads SendRunnable send_runnable(&opts); RecvRunnable recv_runnable(&opts); send_thread.Start(&send_runnable); recv_thread.Start(&recv_runnable); packet_handling_thread.Start(); link_setup_thread.Run(); return 0; } <commit_msg>Added missing semicolon.<commit_after>/* * ipop-tincan * Copyright 2015, University of Florida * * 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 <cstdio> #include <iostream> #if defined(LINUX) #include <ifaddrs.h> #elif defined(ANDROID) #include "talk/base/ifaddrs-android.h" #endif #include "talk/base/ssladapter.h" #include "controlleraccess.h" #include "tincanconnectionmanager.h" #include "tincan_utils.h" #include "xmppnetwork.h" #define SEGMENT_SIZE 3 #define SEGMENT_OFFSET 4 #define CMP_SIZE 7 namespace tincan { int kUdpPort = 5800; string kTapName ("ipop"); } class SendRunnable : public talk_base::Runnable { public: SendRunnable(thread_opts_t *opts) : opts_(opts) {} virtual void Run(talk_base::Thread *thread) { ipop_send_thread(opts_); } private: thread_opts_t *opts_; }; class RecvRunnable : public talk_base::Runnable { public: RecvRunnable(thread_opts_t *opts) : opts_(opts) {} virtual void Run(talk_base::Thread *thread) { ipop_recv_thread(opts_); } private: thread_opts_t *opts_; }; int get_free_network_ip(char *ip_addr, size_t len) { #if defined(LINUX) || defined(ANDROID) struct ifaddrs* interfaces; if (getifaddrs(&interfaces) != 0) return -1; // TODO - we should loop again whenever ip address changes char tmp_addr[NI_MAXHOST]; for (struct ifaddrs* ifa = interfaces; ifa != 0; ifa = ifa->ifa_next) { if (ifa->ifa_addr != 0 && ifa->ifa_addr->sa_family == AF_INET) { int error = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), tmp_addr, sizeof(tmp_addr), NULL, 0, NI_NUMERICHOST); if (error == 0) { if (strncmp(ip_addr, tmp_addr, CMP_SIZE) == 0) { char segment[SEGMENT_SIZE] = { '\0' }; memcpy(segment, ip_addr + SEGMENT_OFFSET, sizeof(segment) - 1); int i = atoi(segment) - 1; snprintf(ip_addr + SEGMENT_OFFSET, sizeof(segment), "%d", i); ip_addr[CMP_SIZE - 1] = '.'; // snprintf adds extra null } } } } freeifaddrs(interfaces); #endif return 0; } // TODO - Implement some kind of verification mechanism bool SSLVerificationCallback(void* cert) { return true; } /* The below method parses the arguments supplied to tincan*/ void parse_args(int argc,char **args) { if (argc == 2 && strncmp(args[1], "-v", 2)==0) { std::cout<<endl << "-----tincan version is-----"<< endl << tincan::kIpopVerMjr << "." << tincan::kIpopVerMnr << "." << tincan::kIpopVerRev << endl; exit(0); } if (argc == 2 && strncmp(args[1], "-h", 2)==0) { std::cout<<endl<<"---OPTIONAL---"<<endl << "To configure the name of tap device and listener port."<<endl << "pass tap-name as first arg and port as second."<<endl << "example--sudo sh -c './ipop-tincan looptap 5805 1> out.log 2> err.log &'"<< endl; exit(0); } if (argc == 3) { tincan::kTapName = args[1]; tincan::kUdpPort = atoi(args[2]); } } int main(int argc, char **argv) { // Parse arguments parse_args(argc,argv); talk_base::InitializeSSL(SSLVerificationCallback); peerlist_init(); thread_opts_t opts; #if defined(LINUX) || defined(ANDROID) opts.tap = tap_open(tincan::kTapName.c_str(), opts.mac); if (opts.tap < 0) return -1; #elif defined(WIN32) opts.win32_tap = open_tap(tincan::kTapName.c_str(), opts.mac); if (opts.win32_tap < 0) return -1; #endif opts.translate = 0; opts.switchmode = 0; talk_base::Thread packet_handling_thread, send_thread, recv_thread; talk_base::AutoThread link_setup_thread; link_setup_thread.WrapCurrent(); tincan::PeerSignalSender signal_sender; tincan::TinCanConnectionManager manager(&signal_sender, &link_setup_thread, &packet_handling_thread, &opts); tincan::XmppNetwork xmpp(&link_setup_thread); xmpp.HandlePeer.connect(&manager, &tincan::TinCanConnectionManager::HandlePeer); talk_base::BasicPacketSocketFactory packet_factory; tincan::ControllerAccess controller(manager, xmpp, &packet_factory, &opts); signal_sender.add_service(0, &controller); signal_sender.add_service(1, &xmpp); opts.send_func = &tincan::TinCanConnectionManager::DoPacketSend; opts.recv_func = &tincan::TinCanConnectionManager::DoPacketRecv; // Checks to see if network is available, changes IP if not char ip_addr[NI_MAXHOST] = { '\0' }; manager.ipv4().copy(ip_addr, sizeof(ip_addr)); if (get_free_network_ip(ip_addr, sizeof(ip_addr)) == 0) { manager.set_ip(ip_addr); } // Setup/run threads SendRunnable send_runnable(&opts); RecvRunnable recv_runnable(&opts); send_thread.Start(&send_runnable); recv_thread.Start(&recv_runnable); packet_handling_thread.Start(); link_setup_thread.Run(); return 0; } <|endoftext|>