问:
V8 "segmentation fault (core dumped)" Error Displayed By Sample Shell Application
V8 Version: 8.2.0

OS: Ubuntu v18.04.3 LTS

Architecture: x64

What steps will reproduce the problem?

Followed instructions on https://v8.dev/docs/source-code and https://v8.dev/docs/build to build and compile v8

Compiled the shell.cc in samples folder

After successful compilation the shell app is executed

What is the expected output?

shell application should work just like the d8 shell application. In the d8 shell when the enter key is clicked the d8 shell prompt is returned and d8 shell does not exit the application.

What do you see instead?

When I hit the enter key I get the error "Segmentation fault (Core Dump)" and the shell app exits.

Code in the shell.cc is below. Same as the code in the v8 samples folder at https://github.com/v8/v8/blob/master/samples/shell.cc

```<code>#include <include/v8.h>

#include <include/libplatform/libplatform.h>

#include <assert.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/**
 * This sample program shows how to implement a simple javascript shell
 * based on V8.  This includes initializing V8 with command line options,
 * creating global functions, compiling and executing strings.
 *
 * For a more sophisticated shell, consider using the debug shell D8.
 */

v8::Local<v8::Context> CreateShellContext(v8::Isolate* isolate);
void RunShell(v8::Local<v8::Context> context, v8::Platform* platform);
int RunMain(v8::Isolate* isolate, v8::Platform* platform, int argc,
            char* argv[]);
bool ExecuteString(v8::Isolate* isolate, v8::Local<v8::String> source,
                   v8::Local<v8::Value> name, bool print_result,
                   bool report_exceptions);
void Print(const v8::FunctionCallbackInfo<v8::Value>& args);
void Read(const v8::FunctionCallbackInfo<v8::Value>& args);
void Load(const v8::FunctionCallbackInfo<v8::Value>& args);
void Quit(const v8::FunctionCallbackInfo<v8::Value>& args);
void Version(const v8::FunctionCallbackInfo<v8::Value>& args);
v8::MaybeLocal<v8::String> ReadFile(v8::Isolate* isolate, const char* name);
void ReportException(v8::Isolate* isolate, v8::TryCatch* handler);

static bool run_shell;

int main(int argc, char* argv[]) {
  v8::V8::InitializeICUDefaultLocation(argv[0]);
  v8::V8::InitializeExternalStartupData(argv[0]);
  std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform();
  v8::V8::InitializePlatform(platform.get());
  v8::V8::Initialize();
  v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
  v8::Isolate::CreateParams create_params;
  create_params.array_buffer_allocator =
      v8::ArrayBuffer::Allocator::NewDefaultAllocator();
  v8::Isolate* isolate = v8::Isolate::New(create_params);
  run_shell = (argc == 1);
  int result;
  {
    v8::Isolate::Scope isolate_scope(isolate);
    v8::HandleScope handle_scope(isolate);
    v8::Local<v8::Context> context = CreateShellContext(isolate);
    if (context.IsEmpty()) {
      fprintf(stderr, "Error creating context\n");
      return 1;
    }
    v8::Context::Scope context_scope(context);
    result = RunMain(isolate, platform.get(), argc, argv);
    if (run_shell) RunShell(context, platform.get());
  }
  isolate->Dispose();
  v8::V8::Dispose();
  v8::V8::ShutdownPlatform();
  delete create_params.array_buffer_allocator;
  return result;
}

// Extracts a C string from a V8 Utf8Value.
const char* ToCString(const v8::String::Utf8Value& value) {
  return *value ? *value : "<string conversion failed>";
}

// Creates a new execution environment containing the built-in
// functions.
v8::Local<v8::Context> CreateShellContext(v8::Isolate* isolate) {
  // Create a template for the global object.
  v8::Local<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate);
  // Bind the global 'print' function to the C++ Print callback.
  global->Set(
      v8::String::NewFromUtf8(isolate, "print", v8::NewStringType::kNormal)
          .ToLocalChecked(),
      v8::FunctionTemplate::New(isolate, Print));
  // Bind the global 'read' function to the C++ Read callback.
  global->Set(v8::String::NewFromUtf8(
                  isolate, "read", v8::NewStringType::kNormal).ToLocalChecked(),
              v8::FunctionTemplate::New(isolate, Read));
  // Bind the global 'load' function to the C++ Load callback.
  global->Set(v8::String::NewFromUtf8(
                  isolate, "load", v8::NewStringType::kNormal).ToLocalChecked(),
              v8::FunctionTemplate::New(isolate, Load));
  // Bind the 'quit' function
  global->Set(v8::String::NewFromUtf8(
                  isolate, "quit", v8::NewStringType::kNormal).ToLocalChecked(),
              v8::FunctionTemplate::New(isolate, Quit));
  // Bind the 'version' function
  global->Set(
      v8::String::NewFromUtf8(isolate, "version", v8::NewStringType::kNormal)
          .ToLocalChecked(),
      v8::FunctionTemplate::New(isolate, Version));

  return v8::Context::New(isolate, NULL, global);
}

// The callback that is invoked by v8 whenever the JavaScript 'print'
// function is called.  Prints its arguments on stdout separated by
// spaces and ending with a newline.
void Print(const v8::FunctionCallbackInfo<v8::Value>& args) {
  bool first = true;
  for (int i = 0; i < args.Length(); i++) {
    v8::HandleScope handle_scope(args.GetIsolate());
    if (first) {
      first = false;
    } else {
      printf(" ");
    }
    v8::String::Utf8Value str(args.GetIsolate(), args[i]);
    const char* cstr = ToCString(str);
    printf("%s", cstr);
  }
  printf("\n");
  fflush(stdout);
}

// The callback that is invoked by v8 whenever the JavaScript 'read'
// function is called.  This function loads the content of the file named in
// the argument into a JavaScript string.
void Read(const v8::FunctionCallbackInfo<v8::Value>& args) {
  if (args.Length() != 1) {
    args.GetIsolate()->ThrowException(
        v8::String::NewFromUtf8(args.GetIsolate(), "Bad parameters",
                                v8::NewStringType::kNormal).ToLocalChecked());
    return;
  }
  v8::String::Utf8Value file(args.GetIsolate(), args[0]);
  if (*file == NULL) {
    args.GetIsolate()->ThrowException(
        v8::String::NewFromUtf8(args.GetIsolate(), "Error loading file",
                                v8::NewStringType::kNormal).ToLocalChecked());
    return;
  }
  v8::Local<v8::String> source;
  if (!ReadFile(args.GetIsolate(), *file).ToLocal(&source)) {
    args.GetIsolate()->ThrowException(
        v8::String::NewFromUtf8(args.GetIsolate(), "Error loading file",
                                v8::NewStringType::kNormal).ToLocalChecked());
    return;
  }

  args.GetReturnValue().Set(source);
}

// The callback that is invoked by v8 whenever the JavaScript 'load'
// function is called.  Loads, compiles and executes its argument
// JavaScript file.
void Load(const v8::FunctionCallbackInfo<v8::Value>& args) {
  for (int i = 0; i < args.Length(); i++) {
    v8::HandleScope handle_scope(args.GetIsolate());
    v8::String::Utf8Value file(args.GetIsolate(), args[i]);
    if (*file == NULL) {
      args.GetIsolate()->ThrowException(
          v8::String::NewFromUtf8(args.GetIsolate(), "Error loading file",
                                  v8::NewStringType::kNormal).ToLocalChecked());
      return;
    }
    v8::Local<v8::String> source;
    if (!ReadFile(args.GetIsolate(), *file).ToLocal(&source)) {
      args.GetIsolate()->ThrowException(
          v8::String::NewFromUtf8(args.GetIsolate(), "Error loading file",
                                  v8::NewStringType::kNormal).ToLocalChecked());
      return;
    }
    if (!ExecuteString(args.GetIsolate(), source, args[i], false, false)) {
      args.GetIsolate()->ThrowException(
          v8::String::NewFromUtf8(args.GetIsolate(), "Error executing file",
                                  v8::NewStringType::kNormal).ToLocalChecked());
      return;
    }
  }
}

// The callback that is invoked by v8 whenever the JavaScript 'quit'
// function is called.  Quits.
void Quit(const v8::FunctionCallbackInfo<v8::Value>& args) {
  // If not arguments are given args[0] will yield undefined which
  // converts to the integer value 0.
  int exit_code =
      args[0]->Int32Value(args.GetIsolate()->GetCurrentContext()).FromMaybe(0);
  fflush(stdout);
  fflush(stderr);
  exit(exit_code);
}

void Version(const v8::FunctionCallbackInfo<v8::Value>& args) {
  args.GetReturnValue().Set(
      v8::String::NewFromUtf8(args.GetIsolate(), v8::V8::GetVersion(),
                              v8::NewStringType::kNormal).ToLocalChecked());
}

// Reads a file into a v8 string.
v8::MaybeLocal<v8::String> ReadFile(v8::Isolate* isolate, const char* name) {
  FILE* file = fopen(name, "rb");
  if (file == NULL) return v8::MaybeLocal<v8::String>();

  fseek(file, 0, SEEK_END);
  size_t size = ftell(file);
  rewind(file);

  char* chars = new char[size + 1];
  chars[size] = '\0';
  for (size_t i = 0; i < size;) {
    i += fread(&chars[i], 1, size - i, file);
    if (ferror(file)) {
      fclose(file);
      return v8::MaybeLocal<v8::String>();
    }
  }
  fclose(file);
  v8::MaybeLocal<v8::String> result = v8::String::NewFromUtf8(
      isolate, chars, v8::NewStringType::kNormal, static_cast<int>(size));
  delete[] chars;
  return result;
}

// Process remaining command line arguments and execute files
int RunMain(v8::Isolate* isolate, v8::Platform* platform, int argc,
            char* argv[]) {
  for (int i = 1; i < argc; i++) {
    const char* str = argv[i];
    if (strcmp(str, "--shell") == 0) {
      run_shell = true;
    } else if (strcmp(str, "-f") == 0) {
      // Ignore any -f flags for compatibility with the other stand-
      // alone JavaScript engines.
      continue;
    } else if (strncmp(str, "--", 2) == 0) {
      fprintf(stderr,
              "Warning: unknown flag %s.\nTry --help for options\n", str);
    } else if (strcmp(str, "-e") == 0 && i + 1 < argc) {
      // Execute argument given to -e option directly.
      v8::Local<v8::String> file_name =
          v8::String::NewFromUtf8(isolate, "unnamed",
                                  v8::NewStringType::kNormal).ToLocalChecked();
      v8::Local<v8::String> source;
      if (!v8::String::NewFromUtf8(isolate, argv[++i],
                                   v8::NewStringType::kNormal)
               .ToLocal(&source)) {
        return 1;
      }
      bool success = ExecuteString(isolate, source, file_name, false, true);
      while (v8::platform::PumpMessageLoop(platform, isolate)) continue;
      if (!success) return 1;
    } else {
      // Use all other arguments as names of files to load and run.
      v8::Local<v8::String> file_name =
          v8::String::NewFromUtf8(isolate, str, v8::NewStringType::kNormal)
              .ToLocalChecked();
      v8::Local<v8::String> source;
      if (!ReadFile(isolate, str).ToLocal(&source)) {
        fprintf(stderr, "Error reading '%s'\n", str);
        continue;
      }
      bool success = ExecuteString(isolate, source, file_name, false, true);
      while (v8::platform::PumpMessageLoop(platform, isolate)) continue;
      if (!success) return 1;
    }
  }
  return 0;
}

// The read-eval-execute loop of the shell.
void RunShell(v8::Local<v8::Context> context, v8::Platform* platform) {
  fprintf(stderr, "V8 version %s [sample shell]\n", v8::V8::GetVersion());
  static const int kBufferSize = 256;
  // Enter the execution environment before evaluating any code.
  v8::Context::Scope context_scope(context);
  v8::Local<v8::String> name(
      v8::String::NewFromUtf8(context->GetIsolate(), "(shell)",
                              v8::NewStringType::kNormal).ToLocalChecked());
  while (true) {
    char buffer[kBufferSize];
    fprintf(stderr, "> ");
    char* str = fgets(buffer, kBufferSize, stdin);
    if (str == NULL) break;
    v8::HandleScope handle_scope(context->GetIsolate());
    ExecuteString(
        context->GetIsolate(),
        v8::String::NewFromUtf8(context->GetIsolate(), str,
                                v8::NewStringType::kNormal).ToLocalChecked(),
        name, true, true);
    while (v8::platform::PumpMessageLoop(platform, context->GetIsolate()))
      continue;
  }
  fprintf(stderr, "\n");
}

// Executes a string within the current v8 context.
bool ExecuteString(v8::Isolate* isolate, v8::Local<v8::String> source,
                   v8::Local<v8::Value> name, bool print_result,
                   bool report_exceptions) {
  v8::HandleScope handle_scope(isolate);
  v8::TryCatch try_catch(isolate);
  v8::ScriptOrigin origin(name);
  v8::Local<v8::Context> context(isolate->GetCurrentContext());
  v8::Local<v8::Script> script;
  if (!v8::Script::Compile(context, source, &origin).ToLocal(&script)) {
    // Print errors that happened during compilation.
    if (report_exceptions)
      ReportException(isolate, &try_catch);
    return false;
  } else {
    v8::Local<v8::Value> result;
    if (!script->Run(context).ToLocal(&result)) {
      assert(try_catch.HasCaught());
      // Print errors that happened during execution.
      if (report_exceptions)
        ReportException(isolate, &try_catch);
      return false;
    } else {
      assert(!try_catch.HasCaught());
      if (print_result && !result->IsUndefined()) {
        // If all went well and the result wasn't undefined then print
        // the returned value.
        v8::String::Utf8Value str(isolate, result);
        const char* cstr = ToCString(str);
        printf("%s\n", cstr);
      }
      return true;
    }
  }
}

void ReportException(v8::Isolate* isolate, v8::TryCatch* try_catch) {
  v8::HandleScope handle_scope(isolate);
  v8::String::Utf8Value exception(isolate, try_catch->Exception());
  const char* exception_string = ToCString(exception);
  v8::Local<v8::Message> message = try_catch->Message();
  if (message.IsEmpty()) {
    // V8 didn't provide any extra information about this error; just
    // print the exception.
    fprintf(stderr, "%s\n", exception_string);
  } else {
    // Print (filename):(line number): (message).
    v8::String::Utf8Value filename(isolate,
                                   message->GetScriptOrigin().ResourceName());
    v8::Local<v8::Context> context(isolate->GetCurrentContext());
    const char* filename_string = ToCString(filename);
    int linenum = message->GetLineNumber(context).FromJust();
    fprintf(stderr, "%s:%i: %s\n", filename_string, linenum, exception_string);
    // Print line of source code.
    v8::String::Utf8Value sourceline(
        isolate, message->GetSourceLine(context).ToLocalChecked());
    const char* sourceline_string = ToCString(sourceline);
    fprintf(stderr, "%s\n", sourceline_string);
    // Print wavy underline (GetUnderline is deprecated).
    int start = message->GetStartColumn(context).FromJust();
    for (int i = 0; i < start; i++) {
      fprintf(stderr, " ");
    }
    int end = message->GetEndColumn(context).FromJust();
    for (int i = start; i < end; i++) {
      fprintf(stderr, "^");
    }
    fprintf(stderr, "\n");
    v8::Local<v8::Value> stack_trace_string;
    if (try_catch->StackTrace(context).ToLocal(&stack_trace_string) &&
        stack_trace_string->IsString() &&
        v8::Local<v8::String>::Cast(stack_trace_string)->Length() > 0) {
      v8::String::Utf8Value stack_trace(isolate, stack_trace_string);
      const char* stack_trace_string = ToCString(stack_trace);
      fprintf(stderr, "%s\n", stack_trace_string);
    }
  }
}
</code>```

Teminal Output:

```<code>➜  cd v8
➜  ./shell
V8 version 8.2.0 (candidate) [sample shell]
>
[1]    2119 segmentation fault (core dumped)  ./shell
➜
</code>```

答:
tried a bug report but no response

It seems the bug is https://bugs.chromium.org/p/v8/issues/detail?id=10214; as I write this, the bug was filed 8 hours ago, and this question was asked 6 hours ago, so you waited all of 2 hours on a Sunday (where nobody is at work) until giving up?

I get the error "Segmentation fault (Core Dump)" and the shell app exits

When you get a segfault in any C/C++ program, then what you do is:

compile in Debug mode

Run in a debugger

Trigger the crash

Get a backtrace.

The backtrace will either tell you what's wrong, or at least it will provide important information for anyone who might try to help you.

And please, don't post text (including console output) as images! Neither screenshots nor actual photos are appropriate. Copy-paste the text!

FWIW, the official shell sample works just fine (I just tried: ninja -C out/x64.debug v8_shell && out/x64.debug/v8_shell). There must be something that you're doing differently, but you didn't say what that might be.

Body:
V8 Version: 8.2.0

OS: Ubuntu v18.04.3 LTS

Architecture: x64

What steps will reproduce the problem?

Followed instructions on https://v8.dev/docs/source-code and https://v8.dev/docs/build to build and compile v8

Compiled the shell.cc in samples folder

After successful compilation the shell app is executed

What is the expected output?

shell application should work just like the d8 shell application. In the d8 shell when the enter key is clicked the d8 shell prompt is returned and d8 shell does not exit the application.

What do you see instead?

When I hit the enter key I get the error "Segmentation fault (Core Dump)" and the shell app exits.

Code in the shell.cc is below. Same as the code in the v8 samples folder at https://github.com/v8/v8/blob/master/samples/shell.cc

#include <include/v8.h>

#include <include/libplatform/libplatform.h>

#include <assert.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/**
 * This sample program shows how to implement a simple javascript shell
 * based on V8.  This includes initializing V8 with command line options,
 * creating global functions, compiling and executing strings.
 *
 * For a more sophisticated shell, consider using the debug shell D8.
 */

v8::Local<v8::Context> CreateShellContext(v8::Isolate* isolate);
void RunShell(v8::Local<v8::Context> context, v8::Platform* platform);
int RunMain(v8::Isolate* isolate, v8::Platform* platform, int argc,
            char* argv[]);
bool ExecuteString(v8::Isolate* isolate, v8::Local<v8::String> source,
                   v8::Local<v8::Value> name, bool print_result,
                   bool report_exceptions);
void Print(const v8::FunctionCallbackInfo<v8::Value>& args);
void Read(const v8::FunctionCallbackInfo<v8::Value>& args);
void Load(const v8::FunctionCallbackInfo<v8::Value>& args);
void Quit(const v8::FunctionCallbackInfo<v8::Value>& args);
void Version(const v8::FunctionCallbackInfo<v8::Value>& args);
v8::MaybeLocal<v8::String> ReadFile(v8::Isolate* isolate, const char* name);
void ReportException(v8::Isolate* isolate, v8::TryCatch* handler);

static bool run_shell;

int main(int argc, char* argv[]) {
  v8::V8::InitializeICUDefaultLocation(argv[0]);
  v8::V8::InitializeExternalStartupData(argv[0]);
  std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform();
  v8::V8::InitializePlatform(platform.get());
  v8::V8::Initialize();
  v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
  v8::Isolate::CreateParams create_params;
  create_params.array_buffer_allocator =
      v8::ArrayBuffer::Allocator::NewDefaultAllocator();
  v8::Isolate* isolate = v8::Isolate::New(create_params);
  run_shell = (argc == 1);
  int result;
  {
    v8::Isolate::Scope isolate_scope(isolate);
    v8::HandleScope handle_scope(isolate);
    v8::Local<v8::Context> context = CreateShellContext(isolate);
    if (context.IsEmpty()) {
      fprintf(stderr, "Error creating context\n");
      return 1;
    }
    v8::Context::Scope context_scope(context);
    result = RunMain(isolate, platform.get(), argc, argv);
    if (run_shell) RunShell(context, platform.get());
  }
  isolate->Dispose();
  v8::V8::Dispose();
  v8::V8::ShutdownPlatform();
  delete create_params.array_buffer_allocator;
  return result;
}

// Extracts a C string from a V8 Utf8Value.
const char* ToCString(const v8::String::Utf8Value& value) {
  return *value ? *value : "<string conversion failed>";
}

// Creates a new execution environment containing the built-in
// functions.
v8::Local<v8::Context> CreateShellContext(v8::Isolate* isolate) {
  // Create a template for the global object.
  v8::Local<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate);
  // Bind the global 'print' function to the C++ Print callback.
  global->Set(
      v8::String::NewFromUtf8(isolate, "print", v8::NewStringType::kNormal)
          .ToLocalChecked(),
      v8::FunctionTemplate::New(isolate, Print));
  // Bind the global 'read' function to the C++ Read callback.
  global->Set(v8::String::NewFromUtf8(
                  isolate, "read", v8::NewStringType::kNormal).ToLocalChecked(),
              v8::FunctionTemplate::New(isolate, Read));
  // Bind the global 'load' function to the C++ Load callback.
  global->Set(v8::String::NewFromUtf8(
                  isolate, "load", v8::NewStringType::kNormal).ToLocalChecked(),
              v8::FunctionTemplate::New(isolate, Load));
  // Bind the 'quit' function
  global->Set(v8::String::NewFromUtf8(
                  isolate, "quit", v8::NewStringType::kNormal).ToLocalChecked(),
              v8::FunctionTemplate::New(isolate, Quit));
  // Bind the 'version' function
  global->Set(
      v8::String::NewFromUtf8(isolate, "version", v8::NewStringType::kNormal)
          .ToLocalChecked(),
      v8::FunctionTemplate::New(isolate, Version));

  return v8::Context::New(isolate, NULL, global);
}

// The callback that is invoked by v8 whenever the JavaScript 'print'
// function is called.  Prints its arguments on stdout separated by
// spaces and ending with a newline.
void Print(const v8::FunctionCallbackInfo<v8::Value>& args) {
  bool first = true;
  for (int i = 0; i < args.Length(); i++) {
    v8::HandleScope handle_scope(args.GetIsolate());
    if (first) {
      first = false;
    } else {
      printf(" ");
    }
    v8::String::Utf8Value str(args.GetIsolate(), args[i]);
    const char* cstr = ToCString(str);
    printf("%s", cstr);
  }
  printf("\n");
  fflush(stdout);
}

// The callback that is invoked by v8 whenever the JavaScript 'read'
// function is called.  This function loads the content of the file named in
// the argument into a JavaScript string.
void Read(const v8::FunctionCallbackInfo<v8::Value>& args) {
  if (args.Length() != 1) {
    args.GetIsolate()->ThrowException(
        v8::String::NewFromUtf8(args.GetIsolate(), "Bad parameters",
                                v8::NewStringType::kNormal).ToLocalChecked());
    return;
  }
  v8::String::Utf8Value file(args.GetIsolate(), args[0]);
  if (*file == NULL) {
    args.GetIsolate()->ThrowException(
        v8::String::NewFromUtf8(args.GetIsolate(), "Error loading file",
                                v8::NewStringType::kNormal).ToLocalChecked());
    return;
  }
  v8::Local<v8::String> source;
  if (!ReadFile(args.GetIsolate(), *file).ToLocal(&source)) {
    args.GetIsolate()->ThrowException(
        v8::String::NewFromUtf8(args.GetIsolate(), "Error loading file",
                                v8::NewStringType::kNormal).ToLocalChecked());
    return;
  }

  args.GetReturnValue().Set(source);
}

// The callback that is invoked by v8 whenever the JavaScript 'load'
// function is called.  Loads, compiles and executes its argument
// JavaScript file.
void Load(const v8::FunctionCallbackInfo<v8::Value>& args) {
  for (int i = 0; i < args.Length(); i++) {
    v8::HandleScope handle_scope(args.GetIsolate());
    v8::String::Utf8Value file(args.GetIsolate(), args[i]);
    if (*file == NULL) {
      args.GetIsolate()->ThrowException(
          v8::String::NewFromUtf8(args.GetIsolate(), "Error loading file",
                                  v8::NewStringType::kNormal).ToLocalChecked());
      return;
    }
    v8::Local<v8::String> source;
    if (!ReadFile(args.GetIsolate(), *file).ToLocal(&source)) {
      args.GetIsolate()->ThrowException(
          v8::String::NewFromUtf8(args.GetIsolate(), "Error loading file",
                                  v8::NewStringType::kNormal).ToLocalChecked());
      return;
    }
    if (!ExecuteString(args.GetIsolate(), source, args[i], false, false)) {
      args.GetIsolate()->ThrowException(
          v8::String::NewFromUtf8(args.GetIsolate(), "Error executing file",
                                  v8::NewStringType::kNormal).ToLocalChecked());
      return;
    }
  }
}

// The callback that is invoked by v8 whenever the JavaScript 'quit'
// function is called.  Quits.
void Quit(const v8::FunctionCallbackInfo<v8::Value>& args) {
  // If not arguments are given args[0] will yield undefined which
  // converts to the integer value 0.
  int exit_code =
      args[0]->Int32Value(args.GetIsolate()->GetCurrentContext()).FromMaybe(0);
  fflush(stdout);
  fflush(stderr);
  exit(exit_code);
}

void Version(const v8::FunctionCallbackInfo<v8::Value>& args) {
  args.GetReturnValue().Set(
      v8::String::NewFromUtf8(args.GetIsolate(), v8::V8::GetVersion(),
                              v8::NewStringType::kNormal).ToLocalChecked());
}

// Reads a file into a v8 string.
v8::MaybeLocal<v8::String> ReadFile(v8::Isolate* isolate, const char* name) {
  FILE* file = fopen(name, "rb");
  if (file == NULL) return v8::MaybeLocal<v8::String>();

  fseek(file, 0, SEEK_END);
  size_t size = ftell(file);
  rewind(file);

  char* chars = new char[size + 1];
  chars[size] = '\0';
  for (size_t i = 0; i < size;) {
    i += fread(&chars[i], 1, size - i, file);
    if (ferror(file)) {
      fclose(file);
      return v8::MaybeLocal<v8::String>();
    }
  }
  fclose(file);
  v8::MaybeLocal<v8::String> result = v8::String::NewFromUtf8(
      isolate, chars, v8::NewStringType::kNormal, static_cast<int>(size));
  delete[] chars;
  return result;
}

// Process remaining command line arguments and execute files
int RunMain(v8::Isolate* isolate, v8::Platform* platform, int argc,
            char* argv[]) {
  for (int i = 1; i < argc; i++) {
    const char* str = argv[i];
    if (strcmp(str, "--shell") == 0) {
      run_shell = true;
    } else if (strcmp(str, "-f") == 0) {
      // Ignore any -f flags for compatibility with the other stand-
      // alone JavaScript engines.
      continue;
    } else if (strncmp(str, "--", 2) == 0) {
      fprintf(stderr,
              "Warning: unknown flag %s.\nTry --help for options\n", str);
    } else if (strcmp(str, "-e") == 0 && i + 1 < argc) {
      // Execute argument given to -e option directly.
      v8::Local<v8::String> file_name =
          v8::String::NewFromUtf8(isolate, "unnamed",
                                  v8::NewStringType::kNormal).ToLocalChecked();
      v8::Local<v8::String> source;
      if (!v8::String::NewFromUtf8(isolate, argv[++i],
                                   v8::NewStringType::kNormal)
               .ToLocal(&source)) {
        return 1;
      }
      bool success = ExecuteString(isolate, source, file_name, false, true);
      while (v8::platform::PumpMessageLoop(platform, isolate)) continue;
      if (!success) return 1;
    } else {
      // Use all other arguments as names of files to load and run.
      v8::Local<v8::String> file_name =
          v8::String::NewFromUtf8(isolate, str, v8::NewStringType::kNormal)
              .ToLocalChecked();
      v8::Local<v8::String> source;
      if (!ReadFile(isolate, str).ToLocal(&source)) {
        fprintf(stderr, "Error reading '%s'\n", str);
        continue;
      }
      bool success = ExecuteString(isolate, source, file_name, false, true);
      while (v8::platform::PumpMessageLoop(platform, isolate)) continue;
      if (!success) return 1;
    }
  }
  return 0;
}

// The read-eval-execute loop of the shell.
void RunShell(v8::Local<v8::Context> context, v8::Platform* platform) {
  fprintf(stderr, "V8 version %s [sample shell]\n", v8::V8::GetVersion());
  static const int kBufferSize = 256;
  // Enter the execution environment before evaluating any code.
  v8::Context::Scope context_scope(context);
  v8::Local<v8::String> name(
      v8::String::NewFromUtf8(context->GetIsolate(), "(shell)",
                              v8::NewStringType::kNormal).ToLocalChecked());
  while (true) {
    char buffer[kBufferSize];
    fprintf(stderr, "> ");
    char* str = fgets(buffer, kBufferSize, stdin);
    if (str == NULL) break;
    v8::HandleScope handle_scope(context->GetIsolate());
    ExecuteString(
        context->GetIsolate(),
        v8::String::NewFromUtf8(context->GetIsolate(), str,
                                v8::NewStringType::kNormal).ToLocalChecked(),
        name, true, true);
    while (v8::platform::PumpMessageLoop(platform, context->GetIsolate()))
      continue;
  }
  fprintf(stderr, "\n");
}

// Executes a string within the current v8 context.
bool ExecuteString(v8::Isolate* isolate, v8::Local<v8::String> source,
                   v8::Local<v8::Value> name, bool print_result,
                   bool report_exceptions) {
  v8::HandleScope handle_scope(isolate);
  v8::TryCatch try_catch(isolate);
  v8::ScriptOrigin origin(name);
  v8::Local<v8::Context> context(isolate->GetCurrentContext());
  v8::Local<v8::Script> script;
  if (!v8::Script::Compile(context, source, &origin).ToLocal(&script)) {
    // Print errors that happened during compilation.
    if (report_exceptions)
      ReportException(isolate, &try_catch);
    return false;
  } else {
    v8::Local<v8::Value> result;
    if (!script->Run(context).ToLocal(&result)) {
      assert(try_catch.HasCaught());
      // Print errors that happened during execution.
      if (report_exceptions)
        ReportException(isolate, &try_catch);
      return false;
    } else {
      assert(!try_catch.HasCaught());
      if (print_result && !result->IsUndefined()) {
        // If all went well and the result wasn't undefined then print
        // the returned value.
        v8::String::Utf8Value str(isolate, result);
        const char* cstr = ToCString(str);
        printf("%s\n", cstr);
      }
      return true;
    }
  }
}

void ReportException(v8::Isolate* isolate, v8::TryCatch* try_catch) {
  v8::HandleScope handle_scope(isolate);
  v8::String::Utf8Value exception(isolate, try_catch->Exception());
  const char* exception_string = ToCString(exception);
  v8::Local<v8::Message> message = try_catch->Message();
  if (message.IsEmpty()) {
    // V8 didn't provide any extra information about this error; just
    // print the exception.
    fprintf(stderr, "%s\n", exception_string);
  } else {
    // Print (filename):(line number): (message).
    v8::String::Utf8Value filename(isolate,
                                   message->GetScriptOrigin().ResourceName());
    v8::Local<v8::Context> context(isolate->GetCurrentContext());
    const char* filename_string = ToCString(filename);
    int linenum = message->GetLineNumber(context).FromJust();
    fprintf(stderr, "%s:%i: %s\n", filename_string, linenum, exception_string);
    // Print line of source code.
    v8::String::Utf8Value sourceline(
        isolate, message->GetSourceLine(context).ToLocalChecked());
    const char* sourceline_string = ToCString(sourceline);
    fprintf(stderr, "%s\n", sourceline_string);
    // Print wavy underline (GetUnderline is deprecated).
    int start = message->GetStartColumn(context).FromJust();
    for (int i = 0; i < start; i++) {
      fprintf(stderr, " ");
    }
    int end = message->GetEndColumn(context).FromJust();
    for (int i = start; i < end; i++) {
      fprintf(stderr, "^");
    }
    fprintf(stderr, "\n");
    v8::Local<v8::Value> stack_trace_string;
    if (try_catch->StackTrace(context).ToLocal(&stack_trace_string) &&
        stack_trace_string->IsString() &&
        v8::Local<v8::String>::Cast(stack_trace_string)->Length() > 0) {
      v8::String::Utf8Value stack_trace(isolate, stack_trace_string);
      const char* stack_trace_string = ToCString(stack_trace);
      fprintf(stderr, "%s\n", stack_trace_string);
    }
  }
}

Teminal Output:

➜  cd v8
➜  ./shell
V8 version 8.2.0 (candidate) [sample shell]
>
[1]    2119 segmentation fault (core dumped)  ./shell
➜


来源: stackexchange

问:
How can I redirect unauthenticated Blazor Azure AD users to a different page than authenticated users?
I'm using the Blazor Server templates included with Visual Studio 2019.

In the template application that uses local authentication, When I view the page without being authenticated, the AuthorizeView tags work as expected, and the log in/out buttons on the navbar are displayed dynamically based on these tags. I am able to view the counter and weather forecast pages as a guest.

In the template application that uses Azure AD authentication, whenever I try and view a page without being authenticated, I'm redirected to the Microsoft login prompt. I'm still able to use the AuthorizeView tags to dynamically display components in the navbar, but what I want to be able to do is view the counter and weather forecast pages as a guest without getting redirected.

Is there any way to achieve this? Am I maybe missing something in App.razor?

Edit:

If I log out using the navbar link, and then navigate back with my browser, I can view the pages without authorization. But then when I refresh the page, I get sent back to https://login.microsoftonline.com/. What could be causing this? I want to view an unauthorized home page without getting redirected.

答:
The behaviour you see is by design.

To change it you can make this change inside Startup.Configure :

```<code>services.AddControllersWithViews(options =>
{
    var policy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
    //options.Filters.Add(new AuthorizeFilter(policy));
});
</code>```

(and of course reduce this code to just services.AddControllersWithViews(); when you want to keep it this way.)

With this change  you will have to block private pages with @attribute [Authorize] or with <AuthorizeView> and there is no automatic redirect to the login page.

ContentLicense: CC BY-SA 4.0

Body:
The behaviour you see is by design.

To change it you can make this change inside Startup.Configure :

services.AddControllersWithViews(options =>
{
    var policy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
    //options.Filters.Add(new AuthorizeFilter(policy));
});

(and of course reduce this code to just services.AddControllersWithViews(); when you want to keep it this way.)

With this change  you will have to block private pages with @attribute [Authorize] or with <AuthorizeView> and there is no automatic redirect to the login page.


问:
String translation won't show in android studio
I have this textView

```<code><TextView
            android:id="@+id/author"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/article_image"
            android:layout_marginStart="10dp"
            android:layout_marginTop="5dp"
            android:layout_toEndOf="@+id/cover_details"
            android:maxLines="1"
            android:text="@string/authorBy"
            android:textAlignment="viewStart"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:textSize="12sp" />
</code>```

It simply shows a word By: and it supposed to show translations of that word when app language is changed, while my app is translated fully to another locale, this string still stays on By: and won't get translated word.

any suggestion?

Update

Here is how my string files and structure looks like:

my strings.xml file

```<code><resources>
    <string name="app_name">ISP</string>
    <string name="navigation_drawer_open">Open navigation drawer</string>
    <string name="navigation_drawer_close">Close navigation drawer</string>
    <string name="nav_header_title">ISP</string>
    <string name="nav_header_subtitle">info@example.com</string>
    <string name="nav_header_desc">Navigation header</string>
    <string name="language_settings">Change Language</string>

    <string name="menu_home">Home</string>
    <string name="menu_gallery">Gallery</string>
    <string name="menu_slideshow">Slideshow</string>
    <string name="menu_our_apps">Our Apps</string>
    <string name="menu_share">Share</string>
    <string name="menu_send">Send</string>
    <string name="title">list title</string>
    <string name="description">list description</string>
    <string name="Image">image</string>
    <string name="image">image</string>
    <string name="category_posts_here">Category posts here</string>
    <string name="title_activity_articles_detail">Articles Detail</string>
    <string name="textViewSample">Sample Text</string>
    <string name="asset_statements" translatable="false">[{ \"include\": \"https://example.com/.well-known/assetlinks.json\" }]</string>
    <string name="title_activity_settings">Settings</string>

    <!-- Preference Titles -->
    <string name="settings_header">Settings</string>

    <!-- Messages Preferences -->
    <string name="select_language">Select Language</string>

    <!-- Sync Preferences -->
    <string name="communicate">Communicate</string>
    <string name="arabic">Arabic</string>
    <string name="Bahasa">Bahasa</string>
    <string name="persian">Persian</string>
    <string name="english">English</string>
    <string name="authorBy">By:</string>
</resources>
</code>```

答:
Ahlan! Looks like your alternative language is Arabic?

If you you may need to enable Right to Left support, in your AndroidManifest file.

https://developer.android.com/guide/topics/manifest/application-element#supportsrtl

Declares whether your application is willing to support right-to-left (RTL) layouts.
  If set to true and targetSdkVersion is set to 17 or higher, various RTL APIs will be activated and used by the system so your app can display RTL layouts. If set to false or if targetSdkVersion is set to 16 or lower, the RTL APIs will be ignored or will have no effect and your app will behave the same regardless of the layout direction associated to the user's Locale choice (your layouts will always be left-to-right).

The default value of this attribute is false.

i.e.

```<code><application
   android:supportsRtl="true"
   ...
</code>```

Body:
I have this textView

<TextView
            android:id="@+id/author"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/article_image"
            android:layout_marginStart="10dp"
            android:layout_marginTop="5dp"
            android:layout_toEndOf="@+id/cover_details"
            android:maxLines="1"
            android:text="@string/authorBy"
            android:textAlignment="viewStart"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:textSize="12sp" />

It simply shows a word By: and it supposed to show translations of that word when app language is changed, while my app is translated fully to another locale, this string still stays on By: and won't get translated word.

any suggestion?

Update

Here is how my string files and structure looks like:

my strings.xml file

<resources>
    <string name="app_name">ISP</string>
    <string name="navigation_drawer_open">Open navigation drawer</string>
    <string name="navigation_drawer_close">Close navigation drawer</string>
    <string name="nav_header_title">ISP</string>
    <string name="nav_header_subtitle">info@example.com</string>
    <string name="nav_header_desc">Navigation header</string>
    <string name="language_settings">Change Language</string>

    <string name="menu_home">Home</string>
    <string name="menu_gallery">Gallery</string>
    <string name="menu_slideshow">Slideshow</string>
    <string name="menu_our_apps">Our Apps</string>
    <string name="menu_share">Share</string>
    <string name="menu_send">Send</string>
    <string name="title">list title</string>
    <string name="description">list description</string>
    <string name="Image">image</string>
    <string name="image">image</string>
    <string name="category_posts_here">Category posts here</string>
    <string name="title_activity_articles_detail">Articles Detail</string>
    <string name="textViewSample">Sample Text</string>
    <string name="asset_statements" translatable="false">[{ \"include\": \"https://example.com/.well-known/assetlinks.json\" }]</string>
    <string name="title_activity_settings">Settings</string>

    <string name="settings_header">Settings</string>

    <string name="select_language">Select Language</string>

    <string name="communicate">Communicate</string>
    <string name="arabic">Arabic</string>
    <string name="Bahasa">Bahasa</string>
    <string name="persian">Persian</string>
    <string name="english">English</string>
    <string name="authorBy">By:</string>
</resources>

Body:
Ahlan! Looks like your alternative language is Arabic?

If you you may need to enable Right to Left support, in your AndroidManifest file.

https://developer.android.com/guide/topics/manifest/application-element#supportsrtl

Declares whether your application is willing to support right-to-left (RTL) layouts.
  If set to true and targetSdkVersion is set to 17 or higher, various RTL APIs will be activated and used by the system so your app can display RTL layouts. If set to false or if targetSdkVersion is set to 16 or lower, the RTL APIs will be ignored or will have no effect and your app will behave the same regardless of the layout direction associated to the user's Locale choice (your layouts will always be left-to-right).

The default value of this attribute is false.

i.e.

<application
   android:supportsRtl="true"
   ...


问:
How to use Django annotate?
I'd like to ask, how I could shrink this to one command? I understand that annotate is proper way to do this,but don't understand how.

Here is my code, which is too slow:

```<code>sum = 0
for contact in self.contacts.all():
   sum += (contact.orders.aggregate(models.Sum('total'))['total__sum'])
return sum
</code>```

I'd like to get Sum for each contact, all records in total column of relevant orders.

Code above produces sum, but is sluggishly slow. It is my understand it can be done with annotate,but not sure how to use it.

Here is Contact:

```<code>class Contact(models.Model):
    company = models.ForeignKey(
        Company, related_name="contacts", on_delete=models.PROTECT)
    first_name = models.CharField(max_length=80)
    last_name = models.CharField(max_length=80, blank=True)
    email = models.EmailField()
</code>```

And here is Orders:

```<code>class Order(models.Model):
    order_number = models.CharField(max_length=80)
    company = models.ForeignKey(Company, related_name="orders")
    contact = models.ForeignKey(Contact, related_name="orders")
    total = models.DecimalField(max_digits=12, decimal_places=6)
    order_date = models.DateTimeField(null=True, blank=True)
</code>```

Help please

答:
You can annotate your queryset on the Contract model with:

```<code>from django.db.models import <b>Sum</b>

Contract.objects.annotate(
    <b>total_orders=Sum('orders__total')</b>
)</code>```

The Contract objects that arise from this queryset will have an extra attribute .total_orders that contains the sum of the total field of the related Order objects.

This will thus create a query that looks like:

```<code>SELECT contract.*, <b>SUM(order.total)</b>
FROM contract
LEFT OUTER JOIN order ON order.contract_id = contract.id
<b>GROUP BY contract.id</b></code>```

Title: How to use Django annotate?

Body:
I'd like to ask, how I could shrink this to one command? I understand that annotate is proper way to do this,but don't understand how.

Here is my code, which is too slow:

sum = 0
for contact in self.contacts.all():
   sum += (contact.orders.aggregate(models.Sum('total'))['total__sum'])
return sum

I'd like to get Sum for each contact, all records in total column of relevant orders.

Code above produces sum, but is sluggishly slow. It is my understand it can be done with annotate,but not sure how to use it.

Here is Contact:

class Contact(models.Model):
    company = models.ForeignKey(
        Company, related_name="contacts", on_delete=models.PROTECT)
    first_name = models.CharField(max_length=80)
    last_name = models.CharField(max_length=80, blank=True)
    email = models.EmailField()

And here is Orders:

class Order(models.Model):
    order_number = models.CharField(max_length=80)
    company = models.ForeignKey(Company, related_name="orders")
    contact = models.ForeignKey(Contact, related_name="orders")
    total = models.DecimalField(max_digits=12, decimal_places=6)
    order_date = models.DateTimeField(null=True, blank=True)

Help please

Body:
You can annotate your queryset on the Contract model with:

from django.db.models import Sum

Contract.objects.annotate(
    total_orders=Sum('orders__total')
)

The Contract objects that arise from this queryset will have an extra attribute .total_orders that contains the sum of the total field of the related Order objects.

This will thus create a query that looks like:

SELECT contract.*, SUM(order.total)
FROM contract
LEFT OUTER JOIN order ON order.contract_id = contract.id
GROUP BY contract.id


问:
PHP mysql Select query calling more than specified data
I've been working and testing with queries, and I came across this issue which I don't understand why it's happening.

I have this code:

```<code><?php
        $query = "
    SELECT sc.course_code
         , c.course_name
      FROM student_course sc
         , courses  c
     WHERE sc.course_code= 'MC 101'
       AND sc.id_num='A0001'
    ";
        $result = mysqli_query($conn, $query);
        if(mysqli_num_rows($result) > 0)
        {
        while($row = mysqli_fetch_array($result))
        {
        ?>
     <p> <h4 style="w3-wide"> <?php echo $row["course_name"];?> </h3>
           <h4 style="w3-wide"><?php echo $row["course_code"];?>  </h3>
         <button type="button" class="w3-button w3-theme-d2 w3-margin-bottom" style = "float:right"><i></i><a href="schedule mc101.php"> View Course</a></button></p>
    <br>
</code>```

And based on what I know, it should call a single data which satisfies the conditions student_course.course_code = 'MC 101'  and student_course.id_num='A0001' which should only be

```<code>Statistics in Computing
MC 101
</code>```

However, this is what I'm getting:

The course names are correct, but all of them have the same code. Does anyone know why this is happening? Much appreciated!

答:
You missed a join condition,
it must me something like ON sc.course_id = c.id

```<code>SELECT sc.course_code, c.course_name
  FROM student_course sc
  JOIN courses c ON sc.course_id = c.id
 WHERE sc.course_code= 'MC 101'
   AND sc.id_num='A0001'
</code>```

Body:
I've been working and testing with queries, and I came across this issue which I don't understand why it's happening.

I have this code:

<?php
        $query = "
    SELECT sc.course_code
         , c.course_name
      FROM student_course sc
         , courses  c
     WHERE sc.course_code= 'MC 101'
       AND sc.id_num='A0001'
    ";
        $result = mysqli_query($conn, $query);
        if(mysqli_num_rows($result) > 0)
        {
        while($row = mysqli_fetch_array($result))
        {
        ?>

 <?php echo $row["course_name"];?>

<?php echo $row["course_code"];?>

         <button type="button" class="w3-button w3-theme-d2 w3-margin-bottom" style = "float:right"> View Course</button>

And based on what I know, it should call a single data which satisfies the conditions student_course.course_code = 'MC 101'  and student_course.id_num='A0001' which should only be

Statistics in Computing
MC 101

However, this is what I'm getting:

The course names are correct, but all of them have the same code. Does anyone know why this is happening? Much appreciated!

Body:
You missed a join condition,
it must me something like ON sc.course_id = c.id

SELECT sc.course_code, c.course_name
  FROM student_course sc
  JOIN courses c ON sc.course_id = c.id
 WHERE sc.course_code= 'MC 101'
   AND sc.id_num='A0001'


问:
C++: Using a single get function to return the variables related to an object
I am a novice programmer working on a coding project for school.

The problem domain is as follows:

Write a C++ program related to a clock

Define a class called Clock , saved in a separate file, that includes the following members:

three member variables related to the hours, minutes and seconds

one accessor function that returns the values of the three variables (hint: use pointers)

one mutator function that modifies all variables (hint: use three arguments)

functions to increment each variable with 1 (hint: three function)

overloading functions to increment the variables with a value entered by the user (hint: the value is the argument of the function)

one default constructor that sets the clock to 0 hours, 0 minutes and 0 seconds

an overloading constructor that sets the clock to a given time (hr, min, sec)

Define a second class, saved in a separate file, that includes

a static member variable

a static member function

Include in the previously defined files C++ code that insures that a class will not be loaded twice in the main program

Define a main program, saved in a separate file, that

instantiates three objects, one with the default constructor of Clock, one with the overloaded constructor of Clock, and one based on the second class

uses the objects to call all the functions defined in the two classes:

use several ”cin” statement to read from the user the desired time and use the values as parameters for the corresponding functions that required

call each function only once, using one of the defined objects

use the accessor function to print the time after each function call that modifies the variables of the Clock class

includes code that uses the static members of the second class

we have done many examples in class where we are able to use separate get\set functions but this is the first time we are trying to do this with a single get function and pointers. Quite frankly, I am lost

Here is the contents of my header file:

```<code>// default class definition
#ifndef CLOCK1_H
#define CLOCK1_H

#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;

class Clock
{
private:
    int hours;
    int minutes;
    int seconds;

public:
    int Clock::getInitialTime();
    int Clock::setClockTime();
    Clock::Clock();             // default constructor
    Clock::~Clock();                // default destructor
};
#endif
</code>```

Here is the contents of my source code file:

```<code>// function declarations \ main program
//

#include "stdafx.h"
#include "Clock1.h"
#include <iostream>
#include <conio.h>
using namespace std;

int Clock::getInitialTime()
{
    return hours, minutes, seconds;
}

//void Clock::setClockTime(int hr,min,sec)
//{
//  hours=hr;
//  minutes=min;
//  seconds=sec;
//}

// default constructor
Clock::Clock()
{
    hours=0;
    minutes=0;
    seconds=0;
}

// default destructor
Clock::~Clock()
{
    cin.get();
    cin.get();
}

int main()
{
    Clock defaultObj;
    defaultObj.getInitialTime();
    cout << "The initial time is " << defaultObj.getInitialTime() << endl;
    return 0;
}
</code>```

I am trying to take this in small steps, the first goal being to be able to output the initial values for the hours, minutes, seconds. once this is done, I can add additional constructor(s) with additional arguments.

My first guess is that I need to add the following:

Constructor:
add the appropriate arguments to the default constructor

```<code>Clock::Clock(int *hourPrt, int *minutePtr, int *secondPrt)
</code>```

create the pointers

```<code>Clock *hourPtr;
Clock *minutePtr;
Clock *secondPtr;
</code>```

associate them with the object's attributes

```<code>hourPrt=defaultObj.hours
minutePtr=defaultObj.minutes
secondPrt=defaultObj.seconds
</code>```

getInitialTime function
modify it some how

function call in main
modify it some how

Can anyone help me with this?

Thanks

答:
To "return" more than one argument, you have to use pointers:

```<code>void get_values(int *hours, int *minutes, int *seconds) {
  *hours = this->hours;
  *minutes = this->minutes;
  *seconds = this->seconds;
}
</code>```

Usage:

```<code>int hours, minutes, seconds;
clock.get_values(&hours, &minutes, &seconds);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am a novice programmer working on a coding project for school.

The problem domain is as follows:

Write a C++ program related to a clock

Define a class called Clock , saved in a separate file, that includes the following members:

three member variables related to the hours, minutes and seconds

one accessor function that returns the values of the three variables (hint: use pointers)

one mutator function that modifies all variables (hint: use three arguments)

functions to increment each variable with 1 (hint: three function)

overloading functions to increment the variables with a value entered by the user (hint: the value is the argument of the function)

one default constructor that sets the clock to 0 hours, 0 minutes and 0 seconds

an overloading constructor that sets the clock to a given time (hr, min, sec)

Define a second class, saved in a separate file, that includes

a static member variable

a static member function

Include in the previously defined files C++ code that insures that a class will not be loaded twice in the main program

Define a main program, saved in a separate file, that

instantiates three objects, one with the default constructor of Clock, one with the overloaded constructor of Clock, and one based on the second class

uses the objects to call all the functions defined in the two classes:

use several ”cin” statement to read from the user the desired time and use the values as parameters for the corresponding functions that required

call each function only once, using one of the defined objects

use the accessor function to print the time after each function call that modifies the variables of the Clock class

includes code that uses the static members of the second class

we have done many examples in class where we are able to use separate get\set functions but this is the first time we are trying to do this with a single get function and pointers. Quite frankly, I am lost

Here is the contents of my header file:

// default class definition
#ifndef CLOCK1_H
#define CLOCK1_H

#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;

class Clock
{
private:
    int hours;
    int minutes;
    int seconds;

public:
    int Clock::getInitialTime();
    int Clock::setClockTime();
    Clock::Clock();             // default constructor
    Clock::~Clock();                // default destructor
};
#endif

Here is the contents of my source code file:

// function declarations \ main program
//

#include "stdafx.h"
#include "Clock1.h"
#include <iostream>
#include <conio.h>
using namespace std;

int Clock::getInitialTime()
{
    return hours, minutes, seconds;
}

//void Clock::setClockTime(int hr,min,sec)
//{
//  hours=hr;
//  minutes=min;
//  seconds=sec;
//}

// default constructor
Clock::Clock()
{
    hours=0;
    minutes=0;
    seconds=0;
}

// default destructor
Clock::~Clock()
{
    cin.get();
    cin.get();
}

int main()
{
    Clock defaultObj;
    defaultObj.getInitialTime();
    cout << "The initial time is " << defaultObj.getInitialTime() << endl;
    return 0;
}

I am trying to take this in small steps, the first goal being to be able to output the initial values for the hours, minutes, seconds. once this is done, I can add additional constructor(s) with additional arguments.

My first guess is that I need to add the following:

Constructor:
add the appropriate arguments to the default constructor

Clock::Clock(int *hourPrt, int *minutePtr, int *secondPrt)

create the pointers

Clock *hourPtr;
Clock *minutePtr;
Clock *secondPtr;

associate them with the object's attributes

hourPrt=defaultObj.hours
minutePtr=defaultObj.minutes
secondPrt=defaultObj.seconds

getInitialTime function
modify it some how

function call in main
modify it some how

Can anyone help me with this?

Thanks

Body:
To "return" more than one argument, you have to use pointers:

void get_values(int *hours, int *minutes, int *seconds) {
  *hours = this->hours;
  *minutes = this->minutes;
  *seconds = this->seconds;
}

Usage:

int hours, minutes, seconds;
clock.get_values(&hours, &minutes, &seconds);


问:
Use cURL to fetch XML and JSON data from my API
I gave myself a project that involves basic CRUD operations with Spring-boot Java as back-end and PHP as front-end. I have my API up and running, I have tested the routes with Postman and I am getting back a response depending on the header I set in postman like so. Here you can also see in my Java backend code I make sure my API can return both XML and JSON.

```<code>@GetMapping(path = "/cabbage",
        produces = {
                MediaType.APPLICATION_XML_VALUE,
                MediaType.APPLICATION_JSON_VALUE,
        })
public @ResponseBody
Iterable<CabbageFarm> getCabbageData() {
    return cabbageRepo.findAll();
}
</code>```

The problem now for me is consuming the route with cURL in order to store the JSON or XML values I get in an array for further manipulation but when ever I do, I get NULL. Here is my php code.

```<code><?php

    $ch = curl_init();
    $url = "localhost:8080/cabbage";
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: Accept:application/json"));
    $result = curl_exec($ch);
    curl_close($ch);
    $data = json_decode($result, true);

    var_dump($data);
?>
</code>```

In this code above I am attempting to consume JSON hence the

curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: Accept:application/json"))

答:
Perhaps because you close curl resource too early, try to reverse these lines </p>

```<code>curl_close($ch); $data = json_decode($result, true);
</code>```

<p>like this </p>

```<code>$data = json_decode($result, true); curl_close($ch);
</code>```

Body:
I gave myself a project that involves basic CRUD operations with Spring-boot Java as back-end and PHP as front-end. I have my API up and running, I have tested the routes with Postman and I am getting back a response depending on the header I set in postman like so. Here you can also see in my Java backend code I make sure my API can return both XML and JSON.

@GetMapping(path = "/cabbage",
        produces = {
                MediaType.APPLICATION_XML_VALUE,
                MediaType.APPLICATION_JSON_VALUE,
        })
public @ResponseBody
Iterable<CabbageFarm> getCabbageData() {
    return cabbageRepo.findAll();
}

The problem now for me is consuming the route with cURL in order to store the JSON or XML values I get in an array for further manipulation but when ever I do, I get NULL. Here is my php code.

<?php

    $ch = curl_init();
    $url = "localhost:8080/cabbage";
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: Accept:application/json"));
    $result = curl_exec($ch);
    curl_close($ch);
    $data = json_decode($result, true);

    var_dump($data);
?>

In this code above I am attempting to consume JSON hence the

curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: Accept:application/json"))

Body:
Perhaps because you close curl resource too early, try to reverse these lines

curl_close($ch); $data = json_decode($result, true);

like this

$data = json_decode($result, true); curl_close($ch);


问:
Laravel 5.6 Notifications "Cannot send message without a sender address"
I am trying to send an email notification after a user registers through the default login page, but it's displaying this error

But checking everything and the last time I used it, it was properly sending me an email

Here are my configs:

.env file

```<code>MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=587
MAIL_USERNAME=""
MAIL_PASSWORD=""
MAIL_FROM_ADDRESS=""
MAIL_FROM_NAME=""
MAIL_ENCRYPTION=tls
</code>```

omitted some details above, but please presume I have entered the right gmail credentials

-----------------------------------------------

mail.php:

```<code><?php

return [

    /*
    |--------------------------------------------------------------------------
    | Mail Driver
    |--------------------------------------------------------------------------
    |
    | Laravel supports both SMTP and PHP's "mail" function as drivers for the
    | sending of e-mail. You may specify which one you're using throughout
    | your application here. By default, Laravel is setup for SMTP mail.
    |
    | Supported: "smtp", "sendmail", "mailgun", "mandrill", "ses",
    |            "sparkpost", "log", "array"
    |
    */

    // 'driver' => env('MAIL_DRIVER', 'smtp'),
    'driver' => env('MAIL_DRIVER', 'sendmail'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Host Address
    |--------------------------------------------------------------------------
    |
    | Here you may provide the host address of the SMTP server used by your
    | applications. A default option is provided that is compatible with
    | the Mailgun mail service which will provide reliable deliveries.
    |
    */

    'host' => env('MAIL_HOST', 'smtp.mailgun.org'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Host Port
    |--------------------------------------------------------------------------
    |
    | This is the SMTP port used by your application to deliver e-mails to
    | users of the application. Like the host we have set this value to
    | stay compatible with the Mailgun e-mail application by default.
    |
    */

    'port' => env('MAIL_PORT', 587),

    /*
    |--------------------------------------------------------------------------
    | Global "From" Address
    |--------------------------------------------------------------------------
    |
    | You may wish for all e-mails sent by your application to be sent from
    | the same address. Here, you may specify a name and address that is
    | used globally for all e-mails that are sent by your application.
    |
    */

    'from' => [
        'address' => env('MAIL_FROM_ADDRESS'),
        'name' => env('MAIL_FROM_NAME'),
    ],

    /*
    |--------------------------------------------------------------------------
    | E-Mail Encryption Protocol
    |--------------------------------------------------------------------------
    |
    | Here you may specify the encryption protocol that should be used when
    | the application send e-mail messages. A sensible default using the
    | transport layer security protocol should provide great security.
    |
    */

    'encryption' => env('MAIL_ENCRYPTION', 'tls'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Server Username
    |--------------------------------------------------------------------------
    |
    | If your SMTP server requires a username for authentication, you should
    | set it here. This will get used to authenticate with your server on
    | connection. You may also set the "password" value below this one.
    |
    */

    'username' => env('MAIL_USERNAME'),

    'password' => env('MAIL_PASSWORD'),

    /*
    |--------------------------------------------------------------------------
    | Sendmail System Path
    |--------------------------------------------------------------------------
    |
    | When using the "sendmail" driver to send e-mails, we will need to know
    | the path to where Sendmail lives on this server. A default path has
    | been provided here, which will work well on most of your systems.
    |
    */

    'sendmail' => '/usr/sbin/sendmail -bs',
    //'sendmail' => '/usr/sbin/sendmail -t -i',

    /*
    |--------------------------------------------------------------------------
    | Markdown Mail Settings
    |--------------------------------------------------------------------------
    |
    | If you are using Markdown based email rendering, you may configure your
    | theme and component paths here, allowing you to customize the design
    | of the emails. Or, you may simply stick with the Laravel defaults!
    |
    */

    'markdown' => [
        'theme' => 'default',

        'paths' => [
            resource_path('views/vendor/mail'),
        ],
    ],

];
</code>```

-----------------------------------------------

User Model:

```<code><?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends \TCG\Voyager\Models\User
{
    use Notifiable;

    const ACTIVE = 1;
    const INACTIVE = 0;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'fname', 'lname', 'email', 'password', 'institute', 'cellphone_no', 'telephone_no', 'token', 'active'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function events(){
        return $this->belongsToMany('App\Event');
    }
}
</code>```

-----------------------------------------------

RegisterController@create method:

```<code>use App\User;
use App\Notifications\UserActivate;

protected function create(array $data)
{
    $user = User::create([
        'fname' => ucfirst(strtolower($data['fname'])),
        'lname' => ucfirst(strtolower($data['lname'])),
        'name'  => $data['fname'] . " " . $data['lname'],
        'institute' => $data['institute'],
        'cellphone_no' => $data['cellphone_no'],
        'telephone_no' => $data['telephone_no'],
        'lname' => ucfirst(strtolower($data['lname'])),
        'lname' => ucfirst(strtolower($data['lname'])),
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
        'token' => str_random(40) . time(),
    ]);

    $user->notify(new UserActivate($user));

    return $user;
}
</code>```

-----------------------------------------------

UserActivate Notification:

```<code><?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class UserActivate extends Notification
{
    use Queueable;

    /**
     * Create a new notification instance.
     *
     * @param $user
     * @return void
     */
    public function __construct($user)
    {
        $this->user = $user;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
            ->from(env('MAIL_USERNAME'))
            ->subject('Account Activation')
            ->greeting(sprintf('Hi, %s', $this->user->name))
            ->line('We just noticed that you created a new account. You will need to activate your account to sign in.')
            ->action('Activate', route('activate', [$this->user->token]))
            ->line('Thank you and welcome!');
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

?>
</code>```

I'm really confused because with my previous Laravel projects, the Notification already accepts the email of the $user object and then sends it right away. But now, it's asking for the sender address... Am I missing anything? Been fixing this since yesterday

Thank you very much in advance!

答:
There's nothing I see wrong with your code.

The error indicates it is the "From" (sender) address missing.

Make sure MAIL_FROM_ADDRESS and MAIL_FROM are set in your .env and refresh config cache, if you're using it (./artisan cache:config).

Body:
I am trying to send an email notification after a user registers through the default login page, but it's displaying this error

But checking everything and the last time I used it, it was properly sending me an email

Here are my configs:

.env file

MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=587
MAIL_USERNAME=""
MAIL_PASSWORD=""
MAIL_FROM_ADDRESS=""
MAIL_FROM_NAME=""
MAIL_ENCRYPTION=tls

omitted some details above, but please presume I have entered the right gmail credentials

-----------------------------------------------

mail.php:

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Mail Driver
    |--------------------------------------------------------------------------
    |
    | Laravel supports both SMTP and PHP's "mail" function as drivers for the
    | sending of e-mail. You may specify which one you're using throughout
    | your application here. By default, Laravel is setup for SMTP mail.
    |
    | Supported: "smtp", "sendmail", "mailgun", "mandrill", "ses",
    |            "sparkpost", "log", "array"
    |
    */

    // 'driver' => env('MAIL_DRIVER', 'smtp'),
    'driver' => env('MAIL_DRIVER', 'sendmail'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Host Address
    |--------------------------------------------------------------------------
    |
    | Here you may provide the host address of the SMTP server used by your
    | applications. A default option is provided that is compatible with
    | the Mailgun mail service which will provide reliable deliveries.
    |
    */

    'host' => env('MAIL_HOST', 'smtp.mailgun.org'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Host Port
    |--------------------------------------------------------------------------
    |
    | This is the SMTP port used by your application to deliver e-mails to
    | users of the application. Like the host we have set this value to
    | stay compatible with the Mailgun e-mail application by default.
    |
    */

    'port' => env('MAIL_PORT', 587),

    /*
    |--------------------------------------------------------------------------
    | Global "From" Address
    |--------------------------------------------------------------------------
    |
    | You may wish for all e-mails sent by your application to be sent from
    | the same address. Here, you may specify a name and address that is
    | used globally for all e-mails that are sent by your application.
    |
    */

    'from' => [
        'address' => env('MAIL_FROM_ADDRESS'),
        'name' => env('MAIL_FROM_NAME'),
    ],

    /*
    |--------------------------------------------------------------------------
    | E-Mail Encryption Protocol
    |--------------------------------------------------------------------------
    |
    | Here you may specify the encryption protocol that should be used when
    | the application send e-mail messages. A sensible default using the
    | transport layer security protocol should provide great security.
    |
    */

    'encryption' => env('MAIL_ENCRYPTION', 'tls'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Server Username
    |--------------------------------------------------------------------------
    |
    | If your SMTP server requires a username for authentication, you should
    | set it here. This will get used to authenticate with your server on
    | connection. You may also set the "password" value below this one.
    |
    */

    'username' => env('MAIL_USERNAME'),

    'password' => env('MAIL_PASSWORD'),

    /*
    |--------------------------------------------------------------------------
    | Sendmail System Path
    |--------------------------------------------------------------------------
    |
    | When using the "sendmail" driver to send e-mails, we will need to know
    | the path to where Sendmail lives on this server. A default path has
    | been provided here, which will work well on most of your systems.
    |
    */

    'sendmail' => '/usr/sbin/sendmail -bs',
    //'sendmail' => '/usr/sbin/sendmail -t -i',

    /*
    |--------------------------------------------------------------------------
    | Markdown Mail Settings
    |--------------------------------------------------------------------------
    |
    | If you are using Markdown based email rendering, you may configure your
    | theme and component paths here, allowing you to customize the design
    | of the emails. Or, you may simply stick with the Laravel defaults!
    |
    */

    'markdown' => [
        'theme' => 'default',

        'paths' => [
            resource_path('views/vendor/mail'),
        ],
    ],

];

-----------------------------------------------

User Model:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends \TCG\Voyager\Models\User
{
    use Notifiable;

    const ACTIVE = 1;
    const INACTIVE = 0;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'fname', 'lname', 'email', 'password', 'institute', 'cellphone_no', 'telephone_no', 'token', 'active'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function events(){
        return $this->belongsToMany('App\Event');
    }
}

-----------------------------------------------

RegisterController@create method:

use App\User;
use App\Notifications\UserActivate;

protected function create(array $data)
{
    $user = User::create([
        'fname' => ucfirst(strtolower($data['fname'])),
        'lname' => ucfirst(strtolower($data['lname'])),
        'name'  => $data['fname'] . " " . $data['lname'],
        'institute' => $data['institute'],
        'cellphone_no' => $data['cellphone_no'],
        'telephone_no' => $data['telephone_no'],
        'lname' => ucfirst(strtolower($data['lname'])),
        'lname' => ucfirst(strtolower($data['lname'])),
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
        'token' => str_random(40) . time(),
    ]);

    $user->notify(new UserActivate($user));

    return $user;
}

-----------------------------------------------

UserActivate Notification:

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class UserActivate extends Notification
{
    use Queueable;

    /**
     * Create a new notification instance.
     *
     * @param $user
     * @return void
     */
    public function __construct($user)
    {
        $this->user = $user;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
            ->from(env('MAIL_USERNAME'))
            ->subject('Account Activation')
            ->greeting(sprintf('Hi, %s', $this->user->name))
            ->line('We just noticed that you created a new account. You will need to activate your account to sign in.')
            ->action('Activate', route('activate', [$this->user->token]))
            ->line('Thank you and welcome!');
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

?>

I'm really confused because with my previous Laravel projects, the Notification already accepts the email of the $user object and then sends it right away. But now, it's asking for the sender address... Am I missing anything? Been fixing this since yesterday

Thank you very much in advance!


问:
Type or namespace SigninManager<> could not be found Identity 3.1.1 Mediatr 8.0.0
I am trying to implement Identity using the Mediatr library and pattern...

The code i am using did work in dotnetcore 2.x and identity 2.2 but is broken in dotnetcore 3.x and identity 3.1.1...

My Application class library is netstandard2.1 and hase the following dependencies set.

```<code><PackageReference Include="FluentValidation.AspNetCore" Version="8.6.1" />
<PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.1.1" />
</code>```

I have my request handler like so;

```<code>public class Handler : IRequestHandler<Query, AppUser>
    {
            private readonly UserManager<AppUser> _userManager;
            private readonly SignInManager<AppUser> _signInManager;

            public Handler(UserManager<AppUser> userManager, SignInManager<AppUser> signInManager)
            {
                _userManager = userManager;
                _signInManager = signInManager;
            }

            public async Task<AppUser> Handle(Query request, CancellationToken cancellationToken)
            {
                var user = await _userManager.FindByEmailAsync(request.Email);

                if (user == null)
                {
                    throw new Exception("Unauthorized");
                }

                // var result = await _signInManager.CheckPasswordSignInAsync(user, request.Password, false);
                var result = await _userManager.CheckPasswordAsync(user, request.Password);

                if (result)
                {
                    return user;
                }

                throw new Exception("Unauthorized");
            }
    }
</code>```

The issue I am having here is that I cannot resolve SignInManager anymore and I am not sure why. I cannot find much info about any of the breaking changes around this between identity versions either.
Where has the SignInManager gone? I thought UserManager were in the same namespace and UserManager resolves just fine. Super confused right now, as you can see, i am about ready to cheat my way out but it doesn't sit right with me.

With the same dependencies in my API project I can reference SignInManager with the same namespace and i can use it to sign in directly in the controller. How can i decouple this in to a Mediatr Handler?

答:
Starting with version 3.0, ASP.NET Core is no longer fully distributed through NuGet. Instead, it is shipped as part of the .NET Core runtime as a shared framework. Only optional packages, like the Microsoft.AspNetCore.Identity.EntityFrameworkCore are still distributed through NuGet. However, those packages do not have transient dependencies defined which will automatically work, so you will still need to properly reference this shared framework in order to use these types.

In order to do this, you will need to switch your project to target netcoreapp3.1 since ASP.NET Core only runs on .NET Core and won’t work with .NET Standard.

Once you have done that, you can reference the shared framework using a framework reference. So your project file should look like this:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <FrameworkReference Include="Microsoft.AspNetCore.App" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="FluentValidation.AspNetCore" Version="8.6.1" />
    <PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="8.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.1.1" />
  </ItemGroup>

</Project>
```

Body:
I am trying to implement Identity using the Mediatr library and pattern...

The code i am using did work in dotnetcore 2.x and identity 2.2 but is broken in dotnetcore 3.x and identity 3.1.1...

My Application class library is netstandard2.1 and hase the following dependencies set.

<PackageReference Include="FluentValidation.AspNetCore" Version="8.6.1" />
<PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.1.1" />

I have my request handler like so;

public class Handler : IRequestHandler<Query, AppUser>
    {
            private readonly UserManager<AppUser> _userManager;
            private readonly SignInManager<AppUser> _signInManager;

            public Handler(UserManager<AppUser> userManager, SignInManager<AppUser> signInManager)
            {
                _userManager = userManager;
                _signInManager = signInManager;
            }

            public async Task<AppUser> Handle(Query request, CancellationToken cancellationToken)
            {
                var user = await _userManager.FindByEmailAsync(request.Email);

                if (user == null)
                {
                    throw new Exception("Unauthorized");
                }

                // var result = await _signInManager.CheckPasswordSignInAsync(user, request.Password, false);
                var result = await _userManager.CheckPasswordAsync(user, request.Password);

                if (result)
                {
                    return user;
                }

                throw new Exception("Unauthorized");
            }
    }

The issue I am having here is that I cannot resolve SignInManager anymore and I am not sure why. I cannot find much info about any of the breaking changes around this between identity versions either.
Where has the SignInManager gone? I thought UserManager were in the same namespace and UserManager resolves just fine. Super confused right now, as you can see, i am about ready to cheat my way out but it doesn't sit right with me.

With the same dependencies in my API project I can reference SignInManager with the same namespace and i can use it to sign in directly in the controller. How can i decouple this in to a Mediatr Handler?


问:
How to extract tr table row values using Selenium from a hidden chart? (Overflow:hidden)
This is the source I want to scrape data from https://www.fxstreet.com/economic-calendar/world-interest-rates

When you click on each bank's name, a chart would pops up and there are table rows and data values.

However, this charts are hidden. Because the attribute overflow:hidden.

How do I extract all the values that are in the chart?

I have already wrote a code that manages to iterate through and click each bank's name to display the chart.

But I have no idea how to extract the values from the charts. Please help. Thanks.

This is my code:

```<code>driver = webdriver.Chrome('chromedriver.exe')
driver.get('https://www.fxstreet.com/economic-calendar/world-interest-rates')
time.sleep(10)
soup = BeautifulSoup(driver.page_source,"lxml")
time.sleep(10)

read_mores = driver.find_elements_by_xpath('//a[@href="#"]')

for read in read_mores:
    driver.execute_script("arguments[0].scrollIntoView();", read)
    driver.execute_script("(arguments[0]).click();", read)
    time.sleep(1)

    list_of_rows = []
    table = soup.select("table")[0]
    for row in table.findAll('tr'):
        list_of_cells = []
        for cell in row.findAll(["th","td"]):
            list_of_cells.append(cell.text)
            list_of_rows.append(list_of_cells)

    for item in list_of_rows:
        print(' '.join(item))

    time.sleep(1)

driver.quit()
</code>```

答:
I'm not sure I got your question correctly, but if you need to extract the hidden table values of the chart you can try something like below.

After you click on the chart link try the below code to get the table values. (my code is in java)

```<code>List<WebElement> trs = driver().findElements((By.xpath("//div[contains(@aria-label,'tabular')]/table/tbody/tr")));
        for(WebElement tr : trs) {
            //  String name = we.getText();
            List<WebElement> tds = tr.findElements(By.tagName("td"));
            String date = tds.get(0).getAttribute("textContent");
            String rate = tds.get(1).getAttribute("textContent");
            System.out.println(date);
            System.out.println(rate);
        }
</code>```

OUTPUT

Feb 15, 1990

16.5

Apr 4, 1990

15

Aug 2, 1990

14

Body:
This is the source I want to scrape data from https://www.fxstreet.com/economic-calendar/world-interest-rates

When you click on each bank's name, a chart would pops up and there are table rows and data values.

However, this charts are hidden. Because the attribute overflow:hidden.

How do I extract all the values that are in the chart?

I have already wrote a code that manages to iterate through and click each bank's name to display the chart.

But I have no idea how to extract the values from the charts. Please help. Thanks.

This is my code:

driver = webdriver.Chrome('chromedriver.exe')
driver.get('https://www.fxstreet.com/economic-calendar/world-interest-rates')
time.sleep(10)
soup = BeautifulSoup(driver.page_source,"lxml")
time.sleep(10)

read_mores = driver.find_elements_by_xpath('//a[@href="#"]')

for read in read_mores:
    driver.execute_script("arguments[0].scrollIntoView();", read)
    driver.execute_script("(arguments[0]).click();", read)
    time.sleep(1)

    list_of_rows = []
    table = soup.select("table")[0]
    for row in table.findAll('tr'):
        list_of_cells = []
        for cell in row.findAll(["th","td"]):
            list_of_cells.append(cell.text)
            list_of_rows.append(list_of_cells)

    for item in list_of_rows:
        print(' '.join(item))

    time.sleep(1)

driver.quit()

Body:
I'm not sure I got your question correctly, but if you need to extract the hidden table values of the chart you can try something like below.

After you click on the chart link try the below code to get the table values. (my code is in java)

List<WebElement> trs = driver().findElements((By.xpath("//div[contains(@aria-label,'tabular')]/table/tbody/tr")));
        for(WebElement tr : trs) {
            //  String name = we.getText();
            List<WebElement> tds = tr.findElements(By.tagName("td"));
            String date = tds.get(0).getAttribute("textContent");
            String rate = tds.get(1).getAttribute("textContent");
            System.out.println(date);
            System.out.println(rate);
        }

OUTPUT

Feb 15, 1990

16.5

Apr 4, 1990

15

Aug 2, 1990

14


问:
when is it appropriate to use get vs post request
Background

Let's assume i have some data as follows that i collect based on some survey users fill out in a form:

```<code>{
  "brand": "Nike",
  "size": [
    "small",
    "medium"
  ]
}
</code>```

Now let's say I want to pass this data to some api , in my case  i will create api gateway that will forward this request to a aws lambda function. The lambda function request will process this request and look at my rds instance to get all the shirts that are small and medium and return me data as response.

My question:

When I make the ajax call to the api would this be a get request or a post request??

Technically I am not really going to modify the database but rather do a read on the database something like select * from nike where size = 'small' and size = 'medium'

I am confused because i assumed whenever we are trying to "GET"/read some data we do a GET request. However I came across THIS stackoverflow post. where the accepted answer suggests that when we are passing data long like i am above we should rather make a POST request.

So my ajax call would look something like this possibly:

```<code>var data =  {
      "brand": "Nike",
      "size": [
        "small",
        "medium"
      ]
    }

$.ajax({
  type: "POST",
  url: "apigatewayendpointblahblah",
  data: data,
  success: success,
  dataType: dataType
});
</code>```

答:
The Rest Protocol has strict definitions for the methods you should use.
when you're fetching data without modifying it, you should use GET request.

Notice that GET required query params rather than body params, which then can be used as a link for sharing pages.

Refer to https://restfulapi.net/http-methods/ for more info

Body:
Background

Let's assume i have some data as follows that i collect based on some survey users fill out in a form:

{
  "brand": "Nike",
  "size": [
    "small",
    "medium"
  ]
}

Now let's say I want to pass this data to some api , in my case  i will create api gateway that will forward this request to a aws lambda function. The lambda function request will process this request and look at my rds instance to get all the shirts that are small and medium and return me data as response.

My question:

When I make the ajax call to the api would this be a get request or a post request??

Technically I am not really going to modify the database but rather do a read on the database something like select * from nike where size = 'small' and size = 'medium'

I am confused because i assumed whenever we are trying to "GET"/read some data we do a GET request. However I came across THIS stackoverflow post. where the accepted answer suggests that when we are passing data long like i am above we should rather make a POST request.

So my ajax call would look something like this possibly:

var data =  {
      "brand": "Nike",
      "size": [
        "small",
        "medium"
      ]
    }

$.ajax({
  type: "POST",
  url: "apigatewayendpointblahblah",
  data: data,
  success: success,
  dataType: dataType
});


问:
Keep zoomable image in center of UIScrollView
In my iPhone app, I need to provide the user with an ability to zoom/pan a large-ish image on the screen.  This is quite simple: I use UIScrollView, set max/min scale factors and zooming/panning works as expected.  Here's where things get interesting.  The image is a dynamic one, received from a server.  It can have any dimensions.  When the image first loads, it's scaled down (if needed) to fit completely into the UIScrollView and is centered in the scroll view - the screenshot is below:

Because the proportions of the image are different from those of the scroll view, there's white space added above and below the image so that the image is centered.  However when I start zooming the image, the actual image becomes large enough to fill the whole of the scrollview viewport, therefore white paddings at top/bottom are not needed anymore, however they remain there, as can be seen from this screenshot:

I believe this is due to the fact that the UIImageView containing the image is automatically sized to fill the whole of UIScrollView and when zoomed, it just grows proportionally.  It has scale mode set to Aspect Fit.  UIScrollView's delegate viewForZoomingInScrollView simply returns the image view.

I attempted to recalculate and re-set UIScrollView, contentSize and image view's size in scrollViewDidEndZooming method:

```<code>CGSize imgViewSize = imageView.frame.size;
CGSize imageSize = imageView.image.size;

CGSize realImgSize;
if(imageSize.width / imageSize.height > imgViewSize.width / imgViewSize.height) {
    realImgSize = CGSizeMake(imgViewSize.width, imgViewSize.width / imageSize.width * imageSize.height);
}
else {
    realImgSize = CGSizeMake(imgViewSize.height / imageSize.height * imageSize.width, imgViewSize.height);
}
scrollView.contentSize = realImgSize;

CGRect fr = CGRectMake(0, 0, 0, 0);
fr.size = realImgSize;
imageView.frame = fr;
</code>```

However this was only making things worse (with bounds still being there but panning not working in the vertical direction).

Is there any way to automatically reduce that whitespace as it becomes unneeded and then increment again during zoom-in?  I suspect the work will need to be done in scrollViewDidEndZooming, but I'm not too sure what that code needs to be.

答:
Analogous to different answers based on setting contentInset, but shorter. Remember about setting scrollView.delegate.

```<code>func scrollViewDidZoom(_ scrollView: UIScrollView) {
    let offsetX = max((scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5, 0.0)
    let offsetY = max((scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5, 0.0)

    scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: offsetY, right: offsetX);
}
</code>```

If you want to take a look on a few different strategies, here is a place worth to look: github & post.

Body:
In my iPhone app, I need to provide the user with an ability to zoom/pan a large-ish image on the screen.  This is quite simple: I use UIScrollView, set max/min scale factors and zooming/panning works as expected.  Here's where things get interesting.  The image is a dynamic one, received from a server.  It can have any dimensions.  When the image first loads, it's scaled down (if needed) to fit completely into the UIScrollView and is centered in the scroll view - the screenshot is below:

Because the proportions of the image are different from those of the scroll view, there's white space added above and below the image so that the image is centered.  However when I start zooming the image, the actual image becomes large enough to fill the whole of the scrollview viewport, therefore white paddings at top/bottom are not needed anymore, however they remain there, as can be seen from this screenshot:

I believe this is due to the fact that the UIImageView containing the image is automatically sized to fill the whole of UIScrollView and when zoomed, it just grows proportionally.  It has scale mode set to Aspect Fit.  UIScrollView's delegate viewForZoomingInScrollView simply returns the image view.

I attempted to recalculate and re-set UIScrollView, contentSize and image view's size in scrollViewDidEndZooming method:

CGSize imgViewSize = imageView.frame.size;
CGSize imageSize = imageView.image.size;

CGSize realImgSize;
if(imageSize.width / imageSize.height > imgViewSize.width / imgViewSize.height) {
    realImgSize = CGSizeMake(imgViewSize.width, imgViewSize.width / imageSize.width * imageSize.height);
}
else {
    realImgSize = CGSizeMake(imgViewSize.height / imageSize.height * imageSize.width, imgViewSize.height);
}
scrollView.contentSize = realImgSize;

CGRect fr = CGRectMake(0, 0, 0, 0);
fr.size = realImgSize;
imageView.frame = fr;

However this was only making things worse (with bounds still being there but panning not working in the vertical direction).

Is there any way to automatically reduce that whitespace as it becomes unneeded and then increment again during zoom-in?  I suspect the work will need to be done in scrollViewDidEndZooming, but I'm not too sure what that code needs to be.

Body:
Analogous to different answers based on setting contentInset, but shorter. Remember about setting scrollView.delegate.

func scrollViewDidZoom(_ scrollView: UIScrollView) {
    let offsetX = max((scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5, 0.0)
    let offsetY = max((scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5, 0.0)

    scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: offsetY, right: offsetX);
}

If you want to take a look on a few different strategies, here is a place worth to look: github & post.


问:
ExtJS or SmartClient?
I would like your opinion about these two frameworks. I like a lot the features of ExtJS, but recently I saw SmartClient and it seems to be great too, and free (its Client side features) for commercial projects. I tried a little of SmartClient and it seems to be easier than ExtJS, and it has a better documentation tnan ExtJS.

BUT.. I didn't work with any of these frameworks and maybe I'm wrong. That's why I would like the opinion of people who has worked with them.

And BTW.. how does the license of ExtJS work? you've to but one license for each developer and then you're able to develop and sell every app you want or you have to buy a license for each app you sell?

Thanks in advance for your help.

答:
I use SmartClient and am quite happy with it and the support provided by Isomorphic. The U/I widgets aren't the nicest out there, but you can see that they've been around for some time by the richness of their API.

It's also quite easy to roll out your own custom controls when the built-in ones don't suit your needs. For example, we integrated Raphael pie chart SVG drawings inside custom Isomorphic canvas classes. We also integrated Mondrian/JPivot analytical technologies which are legacy JSP pages, using Smartclient's HtmlFlow control. It's quite powerful what can be achieved.

One thing I regret about Smartclient versus other technologies such as jQuery, is a clearer separation between the work a web designer does versus the work a developer/programmer does.

With Smartclient, it's mostly done thru code, even the layout of components. There's no HTML per say. They've separated very well the skinning (css), but that's about it. Everything else needs to be done by a developer/programmer thru Javascript code. Smartclient is good for single-page apps.

I can't speak for ExtJS as I haven't used it real production environments, but in the end I think it all boils down to the licensing model and programing/design model you want to be using.

ContentLicense: CC BY-SA 2.5

Title: ExtJS or SmartClient?


问:
Breaking up a string into a list of tokens using another string as a delimiter?
Let's say I have this string:

```<code>char *myTestString = "Hello AND test AND test2";
</code>```

I want to break this down into the set { Hello, test, test2 }, which I can finally iterate over.

Or I have

```<code>char *myTestString2 = "Hi AND there AND test AND test2";
</code>```

I want to break this down into the set { Hi, there, test, test2 }, which I can later iterate over.

How do I achieve this using C?

EDIT:
Another example is splitting "Hello there AND test" should give out set { Hello there, test }.
For clarification "AND" is delimiter here.

答:
When code  does not want to alter the source string, use strcspn(s, delimet) to look for initial portion of a s not  make up of delimit.  It returns the offset.

Use strspn(s, delimet) to look for initial portion of a s made up of delimit.  It returns the offset.

Body:
Let's say I have this string:

char *myTestString = "Hello AND test AND test2";

I want to break this down into the set { Hello, test, test2 }, which I can finally iterate over.

Or I have

char *myTestString2 = "Hi AND there AND test AND test2";

I want to break this down into the set { Hi, there, test, test2 }, which I can later iterate over.

How do I achieve this using C?

EDIT:
Another example is splitting "Hello there AND test" should give out set { Hello there, test }.
For clarification "AND" is delimiter here.