text:
namespace blaze {

using blaze_util::die;
using blaze_util::pdie;
using blaze_exit_code::INTERNAL_ERROR;

using std::string;
using std::vector;

SignalHandler SignalHandler::INSTANCE;

// The number of the last received signal that should cause the client
// to shutdown.  This is saved so that the client's WTERMSIG can be set
// correctly.  (Currently only SIGPIPE uses this mechanism.)
static volatile sig_atomic_t signal_handler_received_signal = 0;

// Signal handler.
static void handler(int signum) {
  int saved_errno = errno;

  static volatile sig_atomic_t sigint_count = 0;

  switch (signum) {
    case SIGINT:
      if (++sigint_count >= 3) {
        SigPrintf(
            "\n%s caught third interrupt signal; killed.\n\n",
            SignalHandler::Get().GetGlobals()->options->product_name.c_str());
        if (SignalHandler::Get().GetGlobals()->server_pid != -1) {
          KillServerProcess(
              SignalHandler::Get().GetGlobals()->server_pid,
              SignalHandler::Get().GetGlobals()->options->output_base);
        }
        _exit(1);
      }
      SigPrintf(
          "\n%s caught interrupt signal; shutting down.\n\n",
          SignalHandler::Get().GetGlobals()->options->product_name.c_str());
      SignalHandler::Get().CancelServer();
      break;
    case SIGTERM:
      SigPrintf(
          "\n%s caught terminate signal; shutting down.\n\n",
          SignalHandler::Get().GetGlobals()->options->product_name.c_str());
      SignalHandler::Get().CancelServer();
      break;
    case SIGPIPE:
      signal_handler_received_signal = SIGPIPE;
      break;
    case SIGQUIT:
      SigPrintf("\nSending SIGQUIT to JVM process %d (see %s).\n\n",
                SignalHandler::Get().GetGlobals()->server_pid,
                SignalHandler::Get().GetGlobals()->jvm_log_file.c_str());
      kill(SignalHandler::Get().GetGlobals()->server_pid, SIGQUIT);
      break;
  }

  errno = saved_errno;
}

void SignalHandler::Install(GlobalVariables* globals,
                            SignalHandler::Callback cancel_server) {
  _globals = globals;
  _cancel_server = cancel_server;

  // Unblock all signals.
  sigset_t sigset;
  sigemptyset(&sigset);
  sigprocmask(SIG_SETMASK, &sigset, NULL);

  signal(SIGINT, handler);
  signal(SIGTERM, handler);
  signal(SIGPIPE, handler);
  signal(SIGQUIT, handler);
}

ATTRIBUTE_NORETURN void SignalHandler::PropagateSignalOrExit(int exit_code) {
  if (signal_handler_received_signal) {
    // Kill ourselves with the same signal, so that callers see the
    // right WTERMSIG value.
    signal(signal_handler_received_signal, SIG_DFL);
    raise(signal_handler_received_signal);
    exit(1);  // (in case raise didn't kill us for some reason)
  } else {
    exit(exit_code);
  }
}

string GetProcessIdAsString() {
  return ToString(getpid());
}

string GetHomeDir() { return GetEnv("HOME"); }

string FindSystemWideBlazerc() {
  string path = "/etc/bazel.bazelrc";
  if (blaze_util::CanReadFile(path)) {
    return path;
  }
  return "";
}

string GetJavaBinaryUnderJavabase() { return "bin/java"; }

// NB: execve() requires pointers to non-const char arrays but .c_str() returns
// a pointer to const char arrays. We could do the const_cast in this function,
// but it's better to violate const correctness as late as possible. No one
// cares about what happens just before execve() because we'll soon become a new
// binary anyway.
const char** ConvertStringVectorToArgv(const vector<string>& args) {
  const char** argv = new const char*[args.size() + 1];
  for (size_t i = 0; i < args.size(); i++) {
    argv[i] = args[i].c_str();
  }

  argv[args.size()] = NULL;

  return argv;
}

void ExecuteProgram(const string &exe, const vector<string> &args_vector) {
  if (VerboseLogging()) {
    string dbg;
    for (const auto &s : args_vector) {
      dbg.append(s);
      dbg.append(" ");
    }

    string cwd = blaze_util::GetCwd();
    fprintf(stderr, "Invoking binary %s in %s:\n  %s\n", exe.c_str(),
            cwd.c_str(), dbg.c_str());
  }

  const char** argv = ConvertStringVectorToArgv(args_vector);
  execv(exe.c_str(), const_cast<char **>(argv));
}

std::string ConvertPath(const std::string &path) { return path; }

std::string ConvertPathList(const std::string& path_list) { return path_list; }

std::string PathAsJvmFlag(const std::string& path) { return path; }

const char kListSeparator = ':';

bool SymlinkDirectories(const string &target, const string &link) {
  return symlink(target.c_str(), link.c_str()) == 0;
}

// Causes the current process to become a daemon (i.e. a child of
// init, detached from the terminal, in its own session.)  We don't
// change cwd, though.
static void Daemonize(const char* daemon_output) {
  // Don't call die() or exit() in this function; we're already in a
  // child process so it won't work as expected.  Just don't do
  // anything that can possibly fail. :)

  signal(SIGHUP, SIG_IGN);
  if (fork() > 0) {
    // This second fork is required iff there's any chance cmd will
    // open an specific tty explicitly, e.g., open("/dev/tty23"). If
    // not, this fork can be removed.
    _exit(blaze_exit_code::SUCCESS);
  }

  setsid();

  close(0);
  close(1);
  close(2);

  open("/dev/null", O_RDONLY);  // stdin
  // stdout:
  if (open(daemon_output, O_WRONLY | O_CREAT | O_TRUNC, 0666) == -1) {
    // In a daemon, no-one can hear you scream.
    open("/dev/null", O_WRONLY);
  }
  (void) dup(STDOUT_FILENO);  // stderr (2>&1)
}

// Notifies the client about the death of the server process by keeping a socket
// open in the server. If the server dies for any reason, the socket will be
// closed, which can be detected by the client.
class SocketBlazeServerStartup : public BlazeServerStartup {
 public:
  SocketBlazeServerStartup(int pipe_fd);
  virtual ~SocketBlazeServerStartup();
  virtual bool IsStillAlive();

 private:
  int fd;
};

SocketBlazeServerStartup::SocketBlazeServerStartup(int fd)
    : fd(fd) {
}

SocketBlazeServerStartup::~SocketBlazeServerStartup() {
  close(fd);
}

bool SocketBlazeServerStartup::IsStillAlive() {
  struct pollfd pfd;
  pfd.fd = fd;
  pfd.events = POLLIN;
  int result;
  do {
    result = poll(&pfd, 1, 0);
  } while (result < 0 && errno == EINTR);
  if (result == 0) {
    // Timeout, server is still alive
    return true;
  } else {
    // Whether it's an error or pfd.revents & POLLHUP > 0, we assume child is
    // dead.
    return false;
  }
}

// NB: There should only be system calls in this function. See the comment
// before ExecuteDaemon() to understand why. strerror() and strlen() are
// hopefully okay.
static void DieAfterFork(const char* message) {
  char* error_string = strerror(errno);  // strerror is hopefully okay
  write(STDERR_FILENO, message, strlen(message));  // strlen should be OK
  write(STDERR_FILENO, ": ", 2);
  write(STDERR_FILENO, error_string, strlen(error_string));
  write(STDERR_FILENO, "\n", 1);
  _exit(blaze_exit_code::INTERNAL_ERROR);
}

// NB: There should only be system calls in this function. See the comment
// before ExecuteDaemon() to understand why.
static void ReadFromFdWithRetryEintr(
    int fd, void *buf, size_t count, const char* error_message) {
  ssize_t result;
  do {
    result = read(fd, buf, count);
  } while (result < 0 && errno == EINTR);
  if (result < 0 || static_cast<size_t>(result) != count) {
    DieAfterFork(error_message);
  }
}

// NB: There should only be system calls in this function. See the comment
// before ExecuteDaemon() to understand why.
static void WriteToFdWithRetryEintr(
    int fd, void *buf, size_t count, const char* error_message) {
  ssize_t result;
  do {
    // Ideally, we'd use send(..., MSG_NOSIGNAL), but that's not available on
    // Darwin.
    result = write(fd, buf, count);
  } while (result < 0 && errno == EINTR);
  if (result < 0 || static_cast<size_t>(result) != count) {
    DieAfterFork(error_message);
  }
}

void WriteSystemSpecificProcessIdentifier(
    const string& server_dir, pid_t server_pid);

// We do a lot of seemingly-needless complications to avoid doing anything
// complex after a fork(). The reason is that forking in multi-threaded
// programs is fraught with peril.
//
// One root cause is that fork() only forks the thread it was called from. If
// another thread holds a lock, it will never be relinquished in the child
// process, and malloc() sometimes does lock. Thus, we need to avoid allocating
// any dynamic memory in the child process, which is hard if any C++ feature is
// used.
//
// We also don't know what libc does behind the scenes, so it's advisable to
// avoid anything that's not a system call. read(), write(), fork() and execv()
// aren't guaranteed to be pure system calls, either, but we can't get any
// closer to this ideal without writing logic specific to each POSIX system we
// run on.
//
// Another way to tackle this issue would be to pre-fork a child process before
// spawning any threads which is then used to fork all the other necessary
// child processes. However, then we'd need to invent a protocol that can handle
// sending stdout/stderr back and forking multiple times, which isn't trivial,
// either.
//
// Yet another fix would be not to use multiple threads before forking. However,
// we need to use gRPC to figure out if a server process is already present and
// gRPC currently cannot be convinced not to spawn any threads.
//
// Another way would be to use posix_spawn(). However, since we need to create a
// daemon process, we'd need to posix_spawn() a little child process that
// daemonizes then exec()s the actual JVM, which is also non-trivial. So I hope
// this will be good enough because for all its flaws, this solution is at least
// localized here.
void ExecuteDaemon(const string& exe,
                   const std::vector<string>& args_vector,
                   const string& daemon_output, const string& server_dir,
                   BlazeServerStartup** server_startup) {
  int fds[2];

  if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds)) {
    pdie(blaze_exit_code::INTERNAL_ERROR, "socket creation failed");
  }

  const char* daemon_output_chars = daemon_output.c_str();
  const char** argv = ConvertStringVectorToArgv(args_vector);
  const char* exe_chars = exe.c_str();

  int child = fork();
  if (child == -1) {
    pdie(blaze_exit_code::INTERNAL_ERROR, "fork() failed");
  } else if (child > 0) {
    // Parent process (i.e. the client)
    close(fds[1]);  // parent keeps one side...
    int unused_status;
    waitpid(child, &unused_status, 0);  // child double-forks
    pid_t server_pid;
    ReadFromFdWithRetryEintr(fds[0], &server_pid, sizeof server_pid,
                        "cannot read server PID from server");
    string pid_file = blaze_util::JoinPath(server_dir, kServerPidFile);
    if (!blaze_util::WriteFile(ToString(server_pid), pid_file)) {
      pdie(blaze_exit_code::INTERNAL_ERROR, "cannot write PID file");
    }

    WriteSystemSpecificProcessIdentifier(server_dir, server_pid);
    char dummy = 'a';
    WriteToFdWithRetryEintr(fds[0], &dummy, 1,
                       "cannot notify server about having written PID file");
    *server_startup = new SocketBlazeServerStartup(fds[0]);
    return;
  } else {
    // Child process (i.e. the server)
    // NB: There should only be system calls in this branch. See the comment
    // before ExecuteDaemon() to understand why.
    close(fds[0]);  // ...child keeps the other.

    Daemonize(daemon_output_chars);

    pid_t server_pid = getpid();
    WriteToFdWithRetryEintr(fds[1], &server_pid, sizeof server_pid,
                            "cannot communicate server PID to client");
    // We wait until the client writes the PID file so that there is no race
    // condition; the server expects the PID file to already be there so that
    // it can read it and know its own PID (see the ctor GrpcServerImpl) and so
    // that it can kill itself if the PID file is deleted (see
    // GrpcServerImpl.PidFileWatcherThread)
    char dummy;
    ReadFromFdWithRetryEintr(
        fds[1], &dummy, 1,
        "cannot get PID file write acknowledgement from client");

    execv(exe_chars, const_cast<char**>(argv));
    DieAfterFork("Cannot execute daemon");
  }
}

static string RunProgram(const string& exe,
                         const std::vector<string>& args_vector) {
  int fds[2];
  if (pipe(fds)) {
    pdie(blaze_exit_code::INTERNAL_ERROR, "pipe creation failed");
  }
  int recv_socket = fds[0];
  int send_socket = fds[1];

  const char* exe_chars = exe.c_str();
  const char** argv = ConvertStringVectorToArgv(args_vector);

  int child = fork();
  if (child == -1) {
    pdie(blaze_exit_code::INTERNAL_ERROR, "fork() failed");
  } else if (child > 0) {  // we're the parent
    close(send_socket);    // parent keeps only the reading side
    string result;
    bool success = blaze_util::ReadFrom(recv_socket, &result);
    close(recv_socket);
    if (!success) {
      pdie(blaze_exit_code::INTERNAL_ERROR, "Cannot read subprocess output");
    }
    return result;
  } else {                 // We're the child
    // NB: There should only be system calls in this branch. See the comment
    // before ExecuteDaemon() to understand why.

    close(recv_socket);    // child keeps only the writing side
    // Redirect output to the writing side of the dup.
    dup2(send_socket, STDOUT_FILENO);
    dup2(send_socket, STDERR_FILENO);
    // Execute the binary
    execv(exe_chars, const_cast<char**>(argv));
    DieAfterFork("Failed to run program");
  }
  return string("");  //  We cannot reach here, just placate the compiler.
}

string GetJvmVersion(const string& java_exe) {
  vector<string> args;
  args.push_back("java");
  args.push_back("-version");

  string version_string = RunProgram(java_exe, args);
  return ReadJvmVersion(version_string);
}

bool CompareAbsolutePaths(const string& a, const string& b) {
  return a == b;
}

string GetHashedBaseDir(const string& root, const string& hashable) {
  unsigned char buf[blaze_util::Md5Digest::kDigestLength];
  blaze_util::Md5Digest digest;
  digest.Update(hashable.data(), hashable.size());
  digest.Finish(buf);
  return blaze_util::JoinPath(root, digest.String());
}

void CreateSecureOutputRoot(const string& path) {
  const char* root = path.c_str();
  struct stat fileinfo = {};

  if (!blaze_util::MakeDirectories(root, 0755)) {
    pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR, "mkdir('%s')", root);
  }

  // The path already exists.
  // Check ownership and mode, and verify that it is a directory.

  if (lstat(root, &fileinfo) < 0) {
    pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR, "lstat('%s')", root);
  }

  if (fileinfo.st_uid != geteuid()) {
    die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR, "'%s' is not owned by me",
        root);
  }

  if ((fileinfo.st_mode & 022) != 0) {
    int new_mode = fileinfo.st_mode & (~022);
    if (chmod(root, new_mode) < 0) {
      die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
          "'%s' has mode %o, chmod to %o failed", root,
          fileinfo.st_mode & 07777, new_mode);
    }
  }

  if (stat(root, &fileinfo) < 0) {
    pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR, "stat('%s')", root);
  }

  if (!S_ISDIR(fileinfo.st_mode)) {
    die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR, "'%s' is not a directory",
        root);
  }

  ExcludePathFromBackup(root);
}

string GetEnv(const string& name) {
  char* result = getenv(name.c_str());
  return result != NULL ? string(result) : "";
}

void SetEnv(const string& name, const string& value) {
  setenv(name.c_str(), value.c_str(), 1);
}

void UnsetEnv(const string& name) {
  unsetenv(name.c_str());
}

bool WarnIfStartedFromDesktop() { return false; }

void SetupStdStreams() {
  // Set non-buffered output mode for stderr/stdout. The server already
  // line-buffers messages where it makes sense, so there's no need to do set
  // line-buffering here. On the other hand the server sometimes sends binary
  // output (when for example a query returns results as proto), in which case
  // we must not perform line buffering on the client side. So turn off
  // buffering here completely.
  setvbuf(stdout, NULL, _IONBF, 0);
  setvbuf(stderr, NULL, _IONBF, 0);

  // Ensure we have three open fds.  Otherwise we can end up with
  // bizarre things like stdout going to the lock file, etc.
  if (fcntl(STDIN_FILENO, F_GETFL) == -1) open("/dev/null", O_RDONLY);
  if (fcntl(STDOUT_FILENO, F_GETFL) == -1) open("/dev/null", O_WRONLY);
  if (fcntl(STDERR_FILENO, F_GETFL) == -1) open("/dev/null", O_WRONLY);
}

// A signal-safe version of fprintf(stderr, ...).
//
// WARNING: any output from the blaze client may be interleaved
// with output from the blaze server.  In --curses mode,
// the Blaze server often erases the previous line of output.
// So, be sure to end each such message with TWO newlines,
// otherwise it may be erased by the next message from the
// Blaze server.
// Also, it's a good idea to start each message with a newline,
// in case the Blaze server has written a partial line.
void SigPrintf(const char *format, ...) {
  char buf[1024];
  va_list ap;
  va_start(ap, format);
  int r = vsnprintf(buf, sizeof buf, format, ap);
  va_end(ap);
  if (write(STDERR_FILENO, buf, r) <= 0) {
    // We don't care, just placate the compiler.
  }
}

static int setlk(int fd, struct flock *lock) {
#ifdef __linux__
// If we're building with glibc <2.20, or another libc which predates
// OFD locks, define the constant ourselves.  This assumes that the libc
// and kernel definitions for struct flock are identical.
#ifndef F_OFD_SETLK
#define F_OFD_SETLK 37
#endif
#endif
#ifdef F_OFD_SETLK
  // Prefer OFD locks if available.  POSIX locks can be lost "accidentally"
  // due to any close() on the lock file, and are not reliably preserved
  // across execve() on Linux, which we need for --batch mode.
  if (fcntl(fd, F_OFD_SETLK, lock) == 0) return 0;
  if (errno != EINVAL) {
    if (errno != EACCES && errno != EAGAIN) {
      pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
           "unexpected result from F_OFD_SETLK");
    }
    return -1;
  }
  // F_OFD_SETLK was added in Linux 3.15.  Older kernels return EINVAL.
  // Fall back to F_SETLK in that case.
#endif
  if (fcntl(fd, F_SETLK, lock) == 0) return 0;
  if (errno != EACCES && errno != EAGAIN) {
    pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
         "unexpected result from F_SETLK");
  }
  return -1;
}

uint64_t AcquireLock(const string& output_base, bool batch_mode, bool block,
                     BlazeLock* blaze_lock) {
  string lockfile = blaze_util::JoinPath(output_base, "lock");
  int lockfd = open(lockfile.c_str(), O_CREAT|O_RDWR, 0644);

  if (lockfd < 0) {
    pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
         "cannot open lockfile '%s' for writing", lockfile.c_str());
  }

  // Keep server from inheriting a useless fd if we are not in batch mode
  if (!batch_mode) {
    if (fcntl(lockfd, F_SETFD, FD_CLOEXEC) == -1) {
      pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
           "fcntl(F_SETFD) failed for lockfile");
    }
  }

  struct flock lock = {};
  lock.l_type = F_WRLCK;
  lock.l_whence = SEEK_SET;
  lock.l_start = 0;
  // This doesn't really matter now, but allows us to subdivide the lock
  // later if that becomes meaningful.  (Ranges beyond EOF can be locked.)
  lock.l_len = 4096;

  // Take the exclusive server lock.  If we fail, we busy-wait until the lock
  // becomes available.
  //
  // We used to rely on fcntl(F_SETLKW) to lazy-wait for the lock to become
  // available, which is theoretically fine, but doing so prevents us from
  // determining if the PID of the server holding the lock has changed under the
  // hood.  There have been multiple bug reports where users (especially macOS
  // ones) mention that the Blaze invocation hangs on a non-existent PID.  This
  // should help troubleshoot those scenarios in case there really is a bug
  // somewhere.
  size_t attempts = 0;
  string owner;
  const uint64_t start_time = GetMillisecondsMonotonic();
  while (setlk(lockfd, &lock) == -1) {
    string buffer(4096, 0);
    ssize_t r = pread(lockfd, &buffer[0], buffer.size(), 0);
    if (r < 0) {
      fprintf(stderr, "warning: pread() lock file: %s\n", strerror(errno));
      r = 0;
    }
    buffer.resize(r);
    if (owner != buffer) {
      // Each time we learn a new lock owner, print it out.
      owner = buffer;
      if (attempts > 0) {
        fprintf(stderr, " client lock owner changed\n");
      }
      fprintf(stderr, "Another command holds the client lock: \n%s\n",
              owner.c_str());
      if (block) {
        fprintf(stderr, "Waiting for it to complete...");
        fflush(stderr);
      }
    }

    if (!block) {
      die(blaze_exit_code::BAD_ARGV,
          "Exiting because the lock is held and --noblock_for_lock was given.");
    }

    TrySleep(500);
    attempts += 1;
  }
  if (attempts > 0) {
    fprintf(stderr, " done!\n");
  }
  const uint64_t end_time = GetMillisecondsMonotonic();

  // If we took the lock on the first try, force the reported wait time to 0 to
  // avoid unnecessary noise in the logs.  In this metric, we are only
  // interested in knowing how long it took for other commands to complete, not
  // how fast acquiring a lock is.
  const uint64_t wait_time = attempts == 0 ? 0 : end_time - start_time;

  // Identify ourselves in the lockfile.
  // The contents are printed for human consumption when another client
  // fails to take the lock, but not parsed otherwise.
  (void) ftruncate(lockfd, 0);
  lseek(lockfd, 0, SEEK_SET);
  // Arguably we should ensure this fits in the 4KB we lock.  In practice no one
  // will have a cwd long enough to overflow that, and nothing currently uses
  // the rest of the lock file anyway.
  dprintf(lockfd, "pid=%d\nowner=client\n", getpid());
  string cwd = blaze_util::GetCwd();
  dprintf(lockfd, "cwd=%s\n", cwd.c_str());
  if (const char *tty = ttyname(STDIN_FILENO)) {  // NOLINT (single-threaded)
    dprintf(lockfd, "tty=%s\n", tty);
  }
  blaze_lock->lockfd = lockfd;
  return wait_time;
}

void ReleaseLock(BlazeLock* blaze_lock) {
  close(blaze_lock->lockfd);
}

bool KillServerProcess(int pid, const string& output_base) {
  // Kill the process and make sure it's dead before proceeding.
  killpg(pid, SIGKILL);
  if (!AwaitServerProcessTermination(pid, output_base,
                                     kPostKillGracePeriodSeconds)) {
    die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
        "Attempted to kill stale server process (pid=%d) using "
        "SIGKILL, but it did not die in a timely fashion.",
        pid);
  }
  return true;
}

void TrySleep(unsigned int milliseconds) {
  time_t seconds_part = (time_t)(milliseconds / 1000);
  long nanoseconds_part = ((long)(milliseconds % 1000)) * 1000 * 1000;
  struct timespec sleeptime = {seconds_part, nanoseconds_part};
  nanosleep(&sleeptime, NULL);
}

string GetUserName() {
  string user = GetEnv("USER");
  if (!user.empty()) {
    return user;
  }
  errno = 0;
  passwd *pwent = getpwuid(getuid());  // NOLINT (single-threaded)
  if (pwent == NULL || pwent->pw_name == NULL) {
    pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
         "$USER is not set, and unable to look up name of current user");
  }
  return pwent->pw_name;
}

bool IsEmacsTerminal() {
  string emacs = GetEnv("EMACS");
  string inside_emacs = GetEnv("INSIDE_EMACS");
  // GNU Emacs <25.1 (and ~all non-GNU emacsen) set EMACS=t, but >=25.1 doesn't
  // do that and instead sets INSIDE_EMACS=<stuff> (where <stuff> can look like
  // e.g. "25.1.1,comint").  So we check both variables for maximum
  // compatibility.
  return emacs == "t" || !inside_emacs.empty();
}

// Returns true iff both stdout and stderr are connected to a
// terminal, and it can support color and cursor movement
// (this is computed heuristically based on the values of
// environment variables).
bool IsStandardTerminal() {
  string term = GetEnv("TERM");
  if (term.empty() || term == "dumb" || term == "emacs" ||
      term == "xterm-mono" || term == "symbolics" || term == "9term" ||
      IsEmacsTerminal()) {
    return false;
  }
  return isatty(STDOUT_FILENO) && isatty(STDERR_FILENO);
}

// Returns the number of columns of the terminal to which stdout is
// connected, or $COLUMNS (default 80) if there is no such terminal.
int GetTerminalColumns() {
  struct winsize ws;
  if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) != -1) {
    return ws.ws_col;
  }
  string columns_env = GetEnv("COLUMNS");
  if (!columns_env.empty()) {
    char* endptr;
    int columns = blaze_util::strto32(columns_env.c_str(), &endptr, 10);
    if (*endptr == '\0') {  // $COLUMNS is a valid number
      return columns;
    }
  }
  return 80;  // default if not a terminal.
}

// Raises a resource limit to the maximum allowed value.
//
// This function raises the limit of the resource given in "resource" from its
// soft limit to its hard limit. If the hard limit is unlimited, uses the
// kernel-level limit fetched from the sysctl property given in "sysctl_name"
// because setting the soft limit to unlimited may not work.
//
// Note that this is a best-effort operation. Any failure during this process
// will result in a warning but execution will continue.
static bool UnlimitResource(const int resource) {
  struct rlimit rl;
  if (getrlimit(resource, &rl) == -1) {
    fprintf(stderr, "Warning: failed to get resource limit %d: %s\n", resource,
            strerror(errno));
    return false;
  }

  if (rl.rlim_cur == rl.rlim_max) {
    // Nothing to do. Return early to prevent triggering any warnings caused by
    // the code below. This way, we will only show warnings the first time the
    // Blaze server is started and not on each command invocation.
    return true;
  }

  rl.rlim_cur = rl.rlim_max;
  if (rl.rlim_cur == RLIM_INFINITY) {
    const rlim_t explicit_limit = GetExplicitSystemLimit(resource);
    if (explicit_limit <= 0) {
      // If not implemented (-1) or on an error (0), do nothing and try to
      // increase the soft limit to the hard one. This might fail, but it's good
      // to try anyway.
      assert(rl.rlim_cur == rl.rlim_max);
    } else {
      rl.rlim_cur = explicit_limit;
    }
  }

  if (setrlimit(resource, &rl) == -1) {
    fprintf(stderr, "Warning: failed to raise resource limit %d to %" PRIdMAX
            ": %s\n", resource, static_cast<intmax_t>(rl.rlim_cur),
            strerror(errno));
    return false;
  }

  return true;
}

bool UnlimitResources() {
  bool success = true;
  success &= UnlimitResource(RLIMIT_NOFILE);
  success &= UnlimitResource(RLIMIT_NPROC);
  return success;
}

void DetectBashOrDie() {
  // do nothing.
}

void EnsurePythonPathOption(vector<string>* options) {
  // do nothing.
}

}   // namespace blaze.


text:
package com.github.mjeanroy.junit.servers.exceptions;

/**
 * Exception thrown when URL cannot be built because of syntax error.
 */
@SuppressWarnings("serial")
public class UrlException extends AbstractException {

	/**
	 * Scheme used to build malformed URL.
	 */
	private final String scheme;

	/**
	 * Host used to build malformed URL.
	 */
	private final String host;

	/**
	 * Port used to build malformed URL.
	 */
	private final int port;

	/**
	 * Path used to build malformed URL.
	 */
	private final String path;

	/**
	 * Create the exception.
	 *
	 * @param scheme HTTP Url scheme.
	 * @param host HTTP Url host.
	 * @param port HTTP Url port.
	 * @param path HTTP Url path.
	 * @param cause Original cause.
	 */
	public UrlException(String scheme, String host, int port, String path, Throwable cause) {
		super(cause);

		this.scheme = scheme;
		this.host = host;
		this.port = port;
		this.path = path;
	}

	/**
	 * The scheme used to build malformed URL.
	 *
	 * @return URL scheme.
	 */
	public String getScheme() {
		return scheme;
	}

	/**
	 * The host used to build malformed URL.
	 *
	 * @return URL host.
	 */
	public String getHost() {
		return host;
	}

	/**
	 * The port used to build malformed URL.
	 *
	 * @return URL port.
	 */
	public int getPort() {
		return port;
	}

	/**
	 * The path used to build malformed URL.
	 *
	 * @return URL path.
	 */
	public String getPath() {
		return path;
	}
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>E-Index</title>
<meta name="date" content="2014-06-14">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G L M O P R S T W

E

EmailGenerator - Class in org.nvonop.selenium.framework.datagenerator

exists() - Method in class org.nvonop.selenium.framework.controls.BaseControl

exists() - Method in interface org.nvonop.selenium.framework.controls.interfaces.Detectable

This method determines whether or not the control is visible.

A B C D E F G L M O P R S T W

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
from twilio.rest import TwilioRestClient

# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = TwilioRestClient(account_sid, auth_token)

# A list of transcription objects with the properties described above
transcriptions = client.transcriptions.list()


text:
module Neo4jSpecHelpers
  extend ActiveSupport::Concern

  class << self
    attr_accessor :expect_queries_count
  end

  self.expect_queries_count = 0

  ActiveGraph::Base.subscribe_to_query do |_message|
    self.expect_queries_count += 1
  end

  def expect_queries(count, &block)
    expect(queries_count(&block)).to eq(count)
  end

  def queries_count
    start_count = Neo4jSpecHelpers.expect_queries_count
    yield
    Neo4jSpecHelpers.expect_queries_count - start_count
  end

  def new_query
    ActiveGraph::Base.new_query
  end

  def driver
    ActiveGraph::Base.driver
  end

  def neo4j_query(*args)
    ActiveGraph::Base.query(*args)
  end

  def action_controller_params(args)
    ActionController::Parameters.new(args)
  end

  class_methods do
    def let_config(var_name, value)
      around do |example|
        old_value = ActiveGraph::Config[var_name]
        ActiveGraph::Config[var_name] = value
        example.run
        ActiveGraph::Config[var_name] = old_value
      end
    end

    def capture_output!(variable)
      around do |example|
        @captured_stream = StringIO.new

        original_stream = $stdout
        $stdout = @captured_stream

        example.run

        $stdout = original_stream
      end
      let(variable) { @captured_stream.string }
    end

    def let_env_variable(var_name)
      around do |example|
        old_value = ENV[var_name.to_s]
        ENV[var_name.to_s] = yield
        example.run
        ENV[var_name.to_s] = old_value
      end
    end
  end
end


text:
These settings apply only when `--azureresourceschema` is specified on the command line.

### AzureResourceSchema multi-api

``` yaml $(azureresourceschema) && $(multiapi)
batch:
  - tag: schema-powerbi-2016-01-29

```

Please also specify `--azureresourceschema-folder=<path to the root directory of your azure-resource-manager-schemas clone>`.

### Tag: schema-powerbi-2016-01-29 and azureresourceschema

``` yaml $(tag) == 'schema-powerbi-2016-01-29' && $(azureresourceschema)
output-folder: $(azureresourceschema-folder)/schemas

# all the input files in this apiVersion
input-file:
  - Microsoft.PowerBI/stable/2016-01-29/powerbiembedded.json

```


text:
class SchedulersController < ApplicationController
  rescue_from ActionView::MissingTemplate do |_exception|
    redirect_to("/home/error_404")
  end
  action_auth_level :index, :instructor
  def index
    @schedulers = Scheduler.where(course_id: @course.id)
  end

  action_auth_level :show, :instructor
  def show
    @scheduler = Scheduler.find(params[:id])
  end

  action_auth_level :new, :instructor
  def new; end

  action_auth_level :create, :instructor
  def create
    @scheduler = @course.scheduler.new(scheduler_params)
    if @scheduler.save
      flash[:success] = "Scheduler created!"
      redirect_to(course_schedulers_path(@course)) and return
    else
      flash[:error] = "Create failed. Please check all fields."
      redirect_to(action: "new") and return
    end
  end

  action_auth_level :edit, :instructor
  def edit
    @scheduler = Scheduler.find(params[:id])
  end

  action_auth_level :run, :instructor
  def run
    @scheduler = Scheduler.find(params[:scheduler_id])
  end

  action_auth_level :visual_run, :instructor
  def visual_run
    action = Scheduler.find(params[:scheduler_id])
    @log = "Executing #{Rails.root.join(action.action)}\n"
    mod_name = Rails.root.join(action.action)
    begin
      require mod_name
      Updater.update(action.course)
    rescue ScriptError, StandardError => e
      @log << ("Error in '#{@course.name}' updater: #{e.message}\n")
      @log << (e.backtrace.join("\n\t"))
    end
    @log << "\nCompleted running action."
    render partial: "visual_test"
  end

  action_auth_level :update, :instructor
  def update
    @scheduler = Scheduler.find(params[:id])
    if @scheduler.update(scheduler_params)
      flash[:success] = "Edit success!"
      redirect_to(course_schedulers_path(@course)) and return
    else
      flash[:error] = "Scheduler edit failed! Please check your fields."
      redirect_to(action: "edit") and return
    end
  end

  action_auth_level :destroy, :instructor
  def destroy
    @scheduler = Scheduler.find(params[:id])
    if @scheduler.destroy
      flash[:success] = "Scheduler destroyed."
    else
      flash[:error] = "Scheduler destroy failed! Please check your fields."
      redirect_to(action: "edit") and return
    end
    redirect_to(action: "index") and return
  end

private

  def scheduler_params
    params.require(:scheduler).permit(:action, :next, :interval)
  end
end


text:
package edu.wm.service;

import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import edu.wm.something.domain.MyUser;

public class UserServiceImpl implements UserDetailsService{

	@Autowired
	PasswordEncoder passwordEncoder;

	@Override
	public UserDetails loadUserByUsername(String arg0)
			throws UsernameNotFoundException, DataAccessException {
		// TODO Auto-generated method stub
		return null;
	}

	@SuppressWarnings("deprecation")
	public MyUser createUser(String username, String password){
		String hashedPass = passwordEncoder.encodePassword(password, "INREOUHG984N5V9V98N54W8");
		Random rand = new Random();
		int value = rand.nextInt(5);
		Boolean isWerewolf = false;
		if (value == 0){//20% chance of being a werewolf
			isWerewolf = true;
		}

		MyUser newUser = new MyUser(username, hashedPass, "pictureurl", isWerewolf);
		return newUser;
	}

}


text:
import Cookies from 'js-cookie';
import _ from 'underscore';

export default class GroupName {
  constructor() {
    this.titleContainer = document.querySelector('.js-title-container');
    this.title = this.titleContainer.querySelector('.title');

    if (this.title) {
      this.titleWidth = this.title.offsetWidth;
      this.groupTitle = this.titleContainer.querySelector('.group-title');
      this.groups = this.titleContainer.querySelectorAll('.group-path');
      this.toggle = null;
      this.isHidden = false;
      this.init();
    }
  }

  init() {
    if (this.groups.length > 0) {
      this.groups[this.groups.length - 1].classList.remove('hidable');
      this.toggleHandler();
      window.addEventListener('resize', _.debounce(this.toggleHandler.bind(this), 100));
    }
    this.render();
  }

  toggleHandler() {
    if (this.titleWidth > this.titleContainer.offsetWidth) {
      if (!this.toggle) this.createToggle();
      this.showToggle();
    } else if (this.toggle) {
      this.hideToggle();
    }
  }

  createToggle() {
    this.toggle = document.createElement('button');
    this.toggle.setAttribute('type', 'button');
    this.toggle.className = 'text-expander group-name-toggle';
    this.toggle.setAttribute('aria-label', 'Toggle full path');
    if (Cookies.get('new_nav') === 'true') {
      this.toggle.innerHTML = '<i class="fa fa-ellipsis-h" aria-hidden="true"></i>';
    } else {
      this.toggle.innerHTML = '...';
    }
    this.toggle.addEventListener('click', this.toggleGroups.bind(this));
    if (Cookies.get('new_nav') === 'true') {
      this.title.insertBefore(this.toggle, this.groupTitle);
    } else {
      this.titleContainer.insertBefore(this.toggle, this.title);
    }
    this.toggleGroups();
  }

  showToggle() {
    this.title.classList.add('wrap');
    this.toggle.classList.remove('hidden');
    if (this.isHidden) this.groupTitle.classList.add('hidden');
  }

  hideToggle() {
    this.title.classList.remove('wrap');
    this.toggle.classList.add('hidden');
    if (this.isHidden) this.groupTitle.classList.remove('hidden');
  }

  toggleGroups() {
    this.isHidden = !this.isHidden;
    this.groupTitle.classList.toggle('hidden');
  }

  render() {
    this.title.classList.remove('initializing');
  }
}


text:
package org.apache.commons.functor.core.algorithm;

import static org.junit.Assert.assertEquals;

import java.io.Serializable;

import org.apache.commons.functor.BaseFunctorTest;
import org.apache.commons.functor.NullaryProcedure;
import org.apache.commons.functor.core.Offset;
import org.junit.Test;

/**
 * Tests {@link DoUntil} algorithm.
 */
public class TestDoUntil extends BaseFunctorTest {

    // Functor Testing Framework
    // ------------------------------------------------------------------------

    @Override
    protected Object makeFunctor() throws Exception {
        Counter counter = new Counter();
        return new DoUntil(counter, new Offset(10));
    }

    @Test
    public void testDoUntil() {
        for(int i=0;i<3;++i){
            Counter counter = new Counter();
            new DoUntil(counter, new Offset(i)).run();
            assertEquals(i+1,counter.count);
        }
    }

    // Classes
    // ------------------------------------------------------------------------

    static class Counter implements NullaryProcedure, Serializable {
        private static final long serialVersionUID = 1L;
        public void run() {
            count++;
        }
        public int count = 0;

        @Override
        public boolean equals(Object obj) {
            if(this == obj) {
                return true;
            }
            if (obj == null || !obj.getClass().equals(getClass())) {
                return false;
            }
            Counter that = (Counter)obj;
            return this.count == that.count;
        }

        @Override
        public int hashCode() {
            int hash = "Counter".hashCode();
            hash <<= 2;
            hash ^= this.count;
            return hash;
        }
    }

}


text:
module V1
  module MediaTypes
    class User < Praxis::MediaType
      identifier 'application/json'

      domain_model 'V1::Resources::User'
      description 'A user in the system'

      attributes do
        attribute :id, Integer
        attribute :uuid, String
        attribute :email, String
        attribute :first_name, String
        attribute :last_name, String
      end
    end
  end
end


text:
package org.apache.ignite.ml.tree.data;

import java.util.Arrays;
import org.apache.ignite.ml.tree.TreeFilter;

/**
 * Index for representing sorted dataset rows for each features.
 * It may be reused while decision tree learning at several levels through filter method.
 */
public class TreeDataIndex {
    /** Index containing IDs of rows as if they is sorted by feature values. */
    private final int[][] idx;

    /** Original features table. */
    private final double[][] features;

    /** Original labels. */
    private final double[] labels;

    /**
     * Constructs an instance of TreeDataIndex.
     *
     * @param features Features.
     * @param labels Labels.
     */
    public TreeDataIndex(double[][] features, double[] labels) {
        this.features = features;
        this.labels = labels;

        int rows = features.length;
        int cols = features.length == 0 ? 0 : features[0].length;

        double[][] featuresCp = new double[rows][cols];
        idx = new int[rows][cols];
        for (int row = 0; row < rows; row++) {
            Arrays.fill(idx[row], row);
            featuresCp[row] = Arrays.copyOf(features[row], cols);
        }

        for (int col = 0; col < cols; col++)
            sortIndex(featuresCp, col, 0, rows - 1);
    }

    /**
     * Constructs an instance of TreeDataIndex
     *
     * @param idxProj Index projection.
     * @param features Features.
     * @param labels Labels.
     */
    private TreeDataIndex(int[][] idxProj, double[][] features, double[] labels) {
        this.idx = idxProj;
        this.features = features;
        this.labels = labels;
    }

    /**
     * Returns label for kth order statistic for target feature.
     *
     * @param k K.
     * @param featureId Feature id.
     * @return Label value.
     */
    public double labelInSortedOrder(int k, int featureId) {
        return labels[idx[k][featureId]];
    }

    /**
     * Returns vector of original features for kth order statistic for target feature.
     *
     * @param k K.
     * @param featureId Feature id.
     * @return Features vector.
     */
    public double[] featuresInSortedOrder(int k, int featureId) {
        return features[idx[k][featureId]];
    }

    /**
     * Returns feature value for kth order statistic for target feature.
     *
     * @param k K.
     * @param featureId Feature id.
     * @return Feature value.
     */
    public double featureInSortedOrder(int k, int featureId) {
        return featuresInSortedOrder(k, featureId)[featureId];
    }

    /**
     * Creates projection of current index in according to {@link TreeFilter}.
     *
     * @param filter Filter.
     * @return Projection of current index onto smaller index in according to rows filter.
     */
    public TreeDataIndex filter(TreeFilter filter) {
        int projSize = 0;
        for (int i = 0; i < rowsCount(); i++) {
            if (filter.test(featuresInSortedOrder(i, 0)))
                projSize++;
        }

        int[][] prj = new int[projSize][columnsCount()];
        for (int feature = 0; feature < columnsCount(); feature++) {
            int ptr = 0;
            for (int row = 0; row < rowsCount(); row++) {
                if (filter.test(featuresInSortedOrder(row, feature)))
                    prj[ptr++][feature] = idx[row][feature];
            }
        }

        return new TreeDataIndex(prj, features, labels);
    }

    /**
     * @return count of rows in current index.
     */
    public int rowsCount() {
        return idx.length;
    }

    /**
     * @return count of columns in current index.
     */
    public int columnsCount() {
        return rowsCount() == 0 ? 0 : idx[0].length;
    }

    /**
     * Constructs index structure in according to features table.
     *
     * @param features Features.
     * @param col Column.
     * @param from From.
     * @param to To.
     */
    private void sortIndex(double[][] features, int col, int from, int to) {
        if (from < to) {
            double pivot = features[(from + to) / 2][col];

            int i = from, j = to;

            while (i <= j) {
                while (features[i][col] < pivot)
                    i++;
                while (features[j][col] > pivot)
                    j--;

                if (i <= j) {
                    double tmpFeature = features[i][col];
                    features[i][col] = features[j][col];
                    features[j][col] = tmpFeature;

                    int tmpLb = idx[i][col];
                    idx[i][col] = idx[j][col];
                    idx[j][col] = tmpLb;

                    i++;
                    j--;
                }
            }

            sortIndex(features, col, from, j);
            sortIndex(features, col, i, to);
        }
    }
}


text:
$(function  () {
   // $("ul.place-sortable").sortable();
    $( "ul.place-sortable" ).sortable({
        onDrop: function($item, container, _super, event ) {
           // var order = $("ul.place-sortable").sortable("serialize", {key:'order[]'});
            //$( "p" ).html( order );
            $item.removeClass(container.group.options.draggedClass).removeAttr("style")
            $("body").removeClass(container.group.options.bodyClass)
            $('.splace-id').each(function (i) {
               $('li.pid-'+$(this).val()).find('.place-order-number').text(i+1);
            //console.log($(this).val());
            });
            loadWayPoint();
        }
    });

});


text:
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.

Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations
    Public Class CovarianceModifierKeywordRecommenderTests
        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Async Function InAfterOfInInterfaceTypeParamTest() As Task
            Await VerifyRecommendationsContainAsync(<File>Interface IGoo(Of |</File>, "In")
        End Function

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Async Function OutAfterOfInInterfaceTypeParamTest() As Task
            Await VerifyRecommendationsContainAsync(<File>Interface IGoo(Of |</File>, "In")
        End Function

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Async Function InNotInClassTypeParamTest() As Task
            Await VerifyRecommendationsMissingAsync(<File>Class Goo(Of |</File>, "In")
        End Function

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Async Function OutNotInClassTypeParamTest() As Task
            Await VerifyRecommendationsMissingAsync(<File>Class Goo(Of |</File>, "Out")
        End Function

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Async Function InNotInStructureTypeParamTest() As Task
            Await VerifyRecommendationsMissingAsync(<File>Structure Goo(Of |</File>, "In")
        End Function

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Async Function OutNotInStructureTypeParamTest() As Task
            Await VerifyRecommendationsMissingAsync(<File>Structure Goo(Of |</File>, "Out")
        End Function

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Async Function InForSecondInterfaceTypeParamTest() As Task
            Await VerifyRecommendationsContainAsync(<File>Interface IGoo(Of T, |</File>, "In")
        End Function

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Async Function OutForSecondInterfaceTypeParamTest() As Task
            Await VerifyRecommendationsContainAsync(<File>Interface IGoo(Of T, |</File>, "In")
        End Function

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Async Function InNotInMultipleConstraintsTest() As Task
            Await VerifyRecommendationsMissingAsync(<File>Interface IGoo(Of T As {New, |</File>, "In")
        End Function

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Async Function OutNotInMultipleConstraintsTest() As Task
            Await VerifyRecommendationsMissingAsync(<File>Interface IGoo(Of T As {New, |</File>, "In")
        End Function

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Async Function InAfterOfInDelegateTypeParamTest() As Task
            Await VerifyRecommendationsContainAsync(<File>Delegate Sub Goo(Of |</File>, "In")
        End Function

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Async Function OutAfterOfInDelegateTypeParamTest() As Task
            Await VerifyRecommendationsContainAsync(<File>Delegate Sub Goo(Of |</File>, "In")
        End Function

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Async Function InForSecondDelegateTypeParamTest() As Task
            Await VerifyRecommendationsContainAsync(<File>Delegate Sub Goo(Of |</File>, "In")
        End Function

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Async Function OutForSecondDelegateTypeParamTest() As Task
            Await VerifyRecommendationsContainAsync(<File>Delegate Sub Goo(Of |</File>, "In")
        End Function

        <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")>
        <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Async Function AfterEolTest() As Task
            Await VerifyRecommendationsContainAsync(
<File>Delegate Sub Goo(Of
    |</File>, "In")
        End Function
    End Class
End Namespace


text:
using System;
using System.Linq;
using System.Reflection;
using System.Web.Http;
using Autofac;
using Autofac.Integration.WebApi;
using HostApp.Core.Constants;
using HostApp.Core.DTO;
using HostApp.Core.Interfaces;
using HostApp.Core.Repository;
using HostApp.Core.Utility;

namespace HostApp.BootStrap
{
    public class LoadIOC
    {
        /// <summary>
        /// Finds all the methods that implement IConfigurIOC and call them.
        /// </summary>
        /// <param name="appConfig"></param>
        /// <param name="apiService"></param>
        /// <param name="container"></param>
        /// <returns></returns>
        public IContainer Get(object appConfig, IService apiService, IContainer container)
        {
            var hostImps = AssemblyHelper.GetImplementations(typeof(IConfigureIOC));
            if (hostImps != null)
            {
                var hostIoc = hostImps.ToArray();

                var builder = new ContainerBuilder();

                var config = (IRestServiceConfiguration)appConfig;

                builder.RegisterInstance(apiService).As<IService>();
                builder.RegisterType<Startup>().As<IConfigureWebAPIService>();

                //Config
                builder.RegisterInstance(appConfig).As<IApplicationConfiguration>();
                builder.RegisterInstance(appConfig).As<IRestServiceConfiguration>();

                //Controllers
                var dllcontrollers = AssemblyHelper.GetImplementations(typeof(ApiController));
                var assembly = Assembly.GetExecutingAssembly();
                builder.RegisterApiControllers(assembly);
                foreach (var dllcontroller in dllcontrollers)
                {
                    builder.RegisterApiControllers(Assembly.GetAssembly(dllcontroller));

                }
                if (config.IsConfigured)
                {

                    ////Mongo Connections
                    builder.Register(
                        c => new ContextMongoDB<SubscriptionSettingDTO>(config.MongoDBConnection, MongoConstants.ConfigurationDatabase))
                        .As<IContextMongoDB<SubscriptionSettingDTO>>();

                    ////Repos
                    AutofacHelper.RegisterDLL(builder, "Host*.dll", "Repository");

                    ////Logic
                    AutofacHelper.RegisterDLL(builder, "Host*.exe", "Logic");
                    AutofacHelper.RegisterDLL(builder, "Host*.dll", "Logic");

                    if (hostIoc.Any())
                    {
                        foreach (var hostImp in hostIoc)
                        {
                            var theInstance = (IConfigureIOC)Activator.CreateInstance(hostImp);

                            theInstance?.Configure(builder, appConfig);
                        }
                    }

                }
                if (container == null)
                {
                    var newcontainer = builder.Build();
                    return newcontainer;
                }

                builder.Update(container);
                return container;
            }
            return null;
        }
    }
}


text:
An example OpenMETA model for the preliminary design of a spacecraft.

## Installation instructions

In addition to cloning this repository, you will need to install a number of software tools to be able to successfully run some of the test benches in this model.

### OpenModelica

OpenModelica is used to simulate the system dynamics of the spacecraft. To install OpenModelica you simply need to download and install the OpenModelica 1.9.2 version installer that is available [here](https://build.openmodelica.org/omc/builds/windows/releases/1.9/2/).

## Models

### OpenMETA Project

The `CyPhy_Model` folder holds the OpenMETA project representing a Spacecraft. The `Spacecraft.xme` model is based heavily on the work done at the Vanderbilt Institute for Software Integration and Systems to model a Spacecraft using the OpenMETA tools. The version found here makes some slight modifications to the original model to standardize naming conventions and model organization, but most significantly it seeks to replace all the Connectors in the model with instances of "Connector" archetypes in the Connectors folder; this was necessary for mapping them to SysML "Interface Blocks."

### Cameo Project

The `SysML_Model` folder contains a project `Spacecraft.mdzip` that corresponds to the one in the `CyPhy_Model` folder, `Spacecraft.xme`. This project includes a number of SysML functional and operational models in addition to the structural models that correspond to the OpenMETA project and components.


text:
<?php

namespace PhpToZephir\Converter\Printer\Expr\BinaryOp;

use PhpParser\Node\Expr\BinaryOp;
use PhpToZephir\Converter\SimplePrinter;

class LogicalAndPrinter extends SimplePrinter
{
    public static function getType()
    {
        return 'pExpr_BinaryOp_LogicalAnd';
    }

    public function convert(BinaryOp\LogicalAnd $node)
    {
        return $this->dispatcher->pInfixOp('Expr_BinaryOp_LogicalAnd', $node->left, ' and ', $node->right);
    }
}


text:
'use babel'

// Returns the type of an linter resolution from its classess array
function resolutionType(classes) {
  for (var i = 0; i < classes.length; i++) {
    if (classes[i] === 'warning') {
      return 'Warning'
    }
    else if (classes[i] === 'error') {
      return 'Error'
    }
  }
  return 'Info'
}

// Helper fuction to create array of character counts per each line
function lineEndingsIndices(textBuffer)  {
  let index = 0
  var indices = []
  for (let ch of textBuffer) {
    if (ch === '\n') {  // API Blueprint uses only LFs for the time being
      indices.push(index)
    }
    index++
  }

  return indices;
}

// Resolve position of an index within the indices map
function resolvePosition(endingsIndices, index) {
  var row = 0
  var column = 0
  var previousEndingIndex = 0

  for (var i = 0; i < endingsIndices.length; i++) {
    if (index <= endingsIndices[i]) {
      row = i
      column = index - previousEndingIndex - 1

      // TODO: Remove
      // console.log('\n r: ' + row + ' c: ' + column +'\n');

      return [row, column]
    }

    previousEndingIndex = endingsIndices[i]
  }

  return [row, column]
}

// Create range from a refract Source Map attribute (array of Source Map elements)
function resolutionRange(endingsIndices, sourceMapAttribute) {
  const DefaultRange = [[0,0], [0,1]]

  if (endingsIndices === undefined ||
      endingsIndices.length === 0) {
    return DefaultRange
  }

  if (sourceMapAttribute === undefined ||
      sourceMapAttribute.length === 0) {
    return DefaultRange
  }

  // Consider only first Source Map element
  const sourceMapElement = sourceMapAttribute[0]
  const indices = sourceMapElement.content
  var startIndex = 0
  var endIndex = 0

  if (indices === undefined ||
      indices.length === 0) {
    return DefaultRange
  }
  else {
    startIndex = indices[0][0]
    if (indices.length === 1) {
      endIndex = indices[0][0] + indices[0][1] - 1
    }
    else {
      endIndex = indices[indices.length - 1][0] + indices[indices.length - 1][1] - 1
    }
  }

  return [resolvePosition(endingsIndices, startIndex), resolvePosition(endingsIndices, endIndex)]
}

// Create Linter resolve value from a Source Annotation element
function createResolution(endingsIndices, filePath, annotation) {
  return {
    filePath,
    type: resolutionType(annotation.meta.classes),
    text: annotation.content,
    range: resolutionRange(endingsIndices, annotation.attributes.sourceMap)
  }
}

module.exports = {
  lineEndingsIndices,
  resolutionType,
  resolutionRange,
  createResolution
}


text:
class QueryCountMatcher
  def initialize(num)
    @expected_count = num
  end

  def matches?(block)
    run(block)

    if @expected_count.respond_to? :include?
      @expected_count.include? @count
    else
      @count == @expected_count
    end
  end

  def run(block)
    $query_count = 0
    $query_sql = []
    block.call
  ensure
    @queries = $query_sql.dup
    @count = $query_count
  end

  def performed_queries
    @queries
  end

  def failure_message
    "expected #{@expected_count} queries, got #{@count}\n#{@queries.join("\n")}"
  end

  def negative_failure_message
    "expected query count not to be #{@expected_count}"
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Fung. mecklenb. sel. (Lüneburg) 1: 1 (1790)

#### Original name
Spermodermia clandestina Tode

### Remarks
null


text:
using System;
using System.Xml.Serialization;

namespace Aop.Api.Response
{
    /// <summary>
    /// AlipayOfflineMarketingVoucherCodeUploadResponse.
    /// </summary>
    public class AlipayOfflineMarketingVoucherCodeUploadResponse : AopResponse
    {
        /// <summary>
        /// 码库id
        /// </summary>
        [XmlElement("code_inventory_id")]
        public string CodeInventoryId { get; set; }
    }
}


text:
package com.google.cloud.storage.spi.v1;

import com.google.api.services.storage.model.Bucket;
import com.google.api.services.storage.model.BucketAccessControl;
import com.google.api.services.storage.model.ObjectAccessControl;
import com.google.api.services.storage.model.Policy;
import com.google.api.services.storage.model.StorageObject;
import com.google.api.services.storage.model.TestIamPermissionsResponse;
import com.google.cloud.ServiceRpc;
import com.google.cloud.Tuple;
import com.google.cloud.storage.StorageException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public interface StorageRpc extends ServiceRpc {

  // These options are part of the Google Cloud storage header options
  enum Option {
    PREDEFINED_ACL("predefinedAcl"),
    PREDEFINED_DEFAULT_OBJECT_ACL("predefinedDefaultObjectAcl"),
    IF_METAGENERATION_MATCH("ifMetagenerationMatch"),
    IF_METAGENERATION_NOT_MATCH("ifMetagenerationNotMatch"),
    IF_GENERATION_MATCH("ifGenerationMatch"),
    IF_GENERATION_NOT_MATCH("ifGenerationNotMatch"),
    IF_SOURCE_METAGENERATION_MATCH("ifSourceMetagenerationMatch"),
    IF_SOURCE_METAGENERATION_NOT_MATCH("ifSourceMetagenerationNotMatch"),
    IF_SOURCE_GENERATION_MATCH("ifSourceGenerationMatch"),
    IF_SOURCE_GENERATION_NOT_MATCH("ifSourceGenerationNotMatch"),
    PREFIX("prefix"),
    MAX_RESULTS("maxResults"),
    PAGE_TOKEN("pageToken"),
    DELIMITER("delimiter"),
    VERSIONS("versions"),
    FIELDS("fields"),
    CUSTOMER_SUPPLIED_KEY("customerSuppliedKey");

    private final String value;

    Option(String value) {
      this.value = value;
    }

    public String value() {
      return value;
    }

    @SuppressWarnings("unchecked")
    <T> T get(Map<Option, ?> options) {
      return (T) options.get(this);
    }

    String getString(Map<Option, ?> options) {
      return get(options);
    }

    Long getLong(Map<Option, ?> options) {
      return get(options);
    }

    Boolean getBoolean(Map<Option, ?> options) {
      return get(options);
    }
  }

  class RewriteRequest {

    public final StorageObject source;
    public final Map<StorageRpc.Option, ?> sourceOptions;
    public final boolean overrideInfo;
    public final StorageObject target;
    public final Map<StorageRpc.Option, ?> targetOptions;
    public final Long megabytesRewrittenPerCall;

    public RewriteRequest(StorageObject source, Map<StorageRpc.Option, ?> sourceOptions,
        boolean overrideInfo, StorageObject target, Map<StorageRpc.Option, ?> targetOptions,
        Long megabytesRewrittenPerCall) {
      this.source = source;
      this.sourceOptions = sourceOptions;
      this.overrideInfo = overrideInfo;
      this.target = target;
      this.targetOptions = targetOptions;
      this.megabytesRewrittenPerCall = megabytesRewrittenPerCall;
    }

    @Override
    public boolean equals(Object obj) {
      if (obj == null) {
        return false;
      }
      if (!(obj instanceof RewriteRequest)) {
        return false;
      }
      final RewriteRequest other = (RewriteRequest) obj;
      return Objects.equals(this.source, other.source)
          && Objects.equals(this.sourceOptions, other.sourceOptions)
          && Objects.equals(this.overrideInfo, other.overrideInfo)
          && Objects.equals(this.target, other.target)
          && Objects.equals(this.targetOptions, other.targetOptions)
          && Objects.equals(this.megabytesRewrittenPerCall, other.megabytesRewrittenPerCall);
    }

    @Override
    public int hashCode() {
      return Objects.hash(source, sourceOptions, overrideInfo, target, targetOptions,
          megabytesRewrittenPerCall);
    }
  }

  class RewriteResponse {

    public final RewriteRequest rewriteRequest;
    public final StorageObject result;
    public final long blobSize;
    public final boolean isDone;
    public final String rewriteToken;
    public final long totalBytesRewritten;

    public RewriteResponse(RewriteRequest rewriteRequest, StorageObject result, long blobSize,
        boolean isDone, String rewriteToken, long totalBytesRewritten) {
      this.rewriteRequest = rewriteRequest;
      this.result = result;
      this.blobSize = blobSize;
      this.isDone = isDone;
      this.rewriteToken = rewriteToken;
      this.totalBytesRewritten = totalBytesRewritten;
    }

    @Override
    public boolean equals(Object obj) {
      if (obj == null) {
        return false;
      }
      if (!(obj instanceof RewriteResponse)) {
        return false;
      }
      final RewriteResponse other = (RewriteResponse) obj;
      return Objects.equals(this.rewriteRequest, other.rewriteRequest)
          && Objects.equals(this.result, other.result)
          && Objects.equals(this.rewriteToken, other.rewriteToken)
          && this.blobSize == other.blobSize
          && Objects.equals(this.isDone, other.isDone)
          && this.totalBytesRewritten == other.totalBytesRewritten;
    }

    @Override
    public int hashCode() {
      return Objects.hash(rewriteRequest, result, blobSize, isDone, rewriteToken,
          totalBytesRewritten);
    }
  }

  /**
   * Creates a new bucket.
   *
   * @throws StorageException upon failure
   */
  Bucket create(Bucket bucket, Map<Option, ?> options);

  /**
   * Creates a new storage object.
   *
   * @throws StorageException upon failure
   */
  StorageObject create(StorageObject object, InputStream content, Map<Option, ?> options);

  /**
   * Lists the project's buckets.
   *
   * @throws StorageException upon failure
   */
  Tuple<String, Iterable<Bucket>> list(Map<Option, ?> options);

  /**
   * Lists the bucket's blobs.
   *
   * @throws StorageException upon failure
   */
  Tuple<String, Iterable<StorageObject>> list(String bucket, Map<Option, ?> options);

  /**
   * Returns the requested bucket or {@code null} if not found.
   *
   * @throws StorageException upon failure
   */
  Bucket get(Bucket bucket, Map<Option, ?> options);

  /**
   * Returns the requested storage object or {@code null} if not found.
   *
   * @throws StorageException upon failure
   */
  StorageObject get(StorageObject object, Map<Option, ?> options);

  /**
   * Updates bucket information.
   *
   * @throws StorageException upon failure
   */
  Bucket patch(Bucket bucket, Map<Option, ?> options);

  /**
   * Updates the storage object's information. Original metadata are merged with metadata in the
   * provided {@code storageObject}.
   *
   * @throws StorageException upon failure
   */
  StorageObject patch(StorageObject storageObject, Map<Option, ?> options);

  /**
   * Deletes the requested bucket.
   *
   * @return {@code true} if the bucket was deleted, {@code false} if it was not found
   * @throws StorageException upon failure
   */
  boolean delete(Bucket bucket, Map<Option, ?> options);

  /**
   * Deletes the requested storage object.
   *
   * @return {@code true} if the storage object was deleted, {@code false} if it was not found
   * @throws StorageException upon failure
   */
  boolean delete(StorageObject object, Map<Option, ?> options);

  /**
   * Creates an empty batch.
   */
  RpcBatch createBatch();

  /**
   * Sends a compose request.
   *
   * @throws StorageException upon failure
   */
  StorageObject compose(Iterable<StorageObject> sources, StorageObject target,
      Map<Option, ?> targetOptions);

  /**
   * Reads all the bytes from a storage object.
   *
   * @throws StorageException upon failure
   */
  byte[] load(StorageObject storageObject, Map<Option, ?> options);

  /**
   * Reads the given amount of bytes from a storage object at the given position.
   *
   * @throws StorageException upon failure
   */
  Tuple<String, byte[]> read(StorageObject from, Map<Option, ?> options, long position, int bytes);

  /**
   * Opens a resumable upload channel for a given storage object.
   *
   * @throws StorageException upon failure
   */
  String open(StorageObject object, Map<Option, ?> options);

  /**
   * Writes the provided bytes to a storage object at the provided location.
   *
   * @throws StorageException upon failure
   */
  void write(String uploadId, byte[] toWrite, int toWriteOffset, long destOffset, int length,
      boolean last);

  /**
   * Sends a rewrite request to open a rewrite channel.
   *
   * @throws StorageException upon failure
   */
  RewriteResponse openRewrite(RewriteRequest rewriteRequest);

  /**
   * Continues rewriting on an already open rewrite channel.
   *
   * @throws StorageException upon failure
   */
  RewriteResponse continueRewrite(RewriteResponse previousResponse);

  /**
   * Returns the ACL entry for the specified entity on the specified bucket or {@code null} if not
   * found.
   *
   * @throws StorageException upon failure
   */
  BucketAccessControl getAcl(String bucket, String entity);

  /**
   * Deletes the ACL entry for the specified entity on the specified bucket.
   *
   * @return {@code true} if the ACL was deleted, {@code false} if it was not found
   * @throws StorageException upon failure
   */
  boolean deleteAcl(String bucket, String entity);

  /**
   * Creates a new ACL entry on the specified bucket.
   *
   * @throws StorageException upon failure
   */
  BucketAccessControl createAcl(BucketAccessControl acl);

  /**
   * Updates an ACL entry on the specified bucket.
   *
   * @throws StorageException upon failure
   */
  BucketAccessControl patchAcl(BucketAccessControl acl);

  /**
   * Lists the ACL entries for the provided bucket.
   *
   * @throws StorageException upon failure
   */
  List<BucketAccessControl> listAcls(String bucket);

  /**
   * Returns the default object ACL entry for the specified entity on the specified bucket or
   * {@code null} if not found.
   *
   * @throws StorageException upon failure
   */
  ObjectAccessControl getDefaultAcl(String bucket, String entity);

  /**
   * Deletes the default object ACL entry for the specified entity on the specified bucket.
   *
   * @return {@code true} if the ACL was deleted, {@code false} if it was not found
   * @throws StorageException upon failure
   */
  boolean deleteDefaultAcl(String bucket, String entity);

  /**
   * Creates a new default object ACL entry on the specified bucket.
   *
   * @throws StorageException upon failure
   */
  ObjectAccessControl createDefaultAcl(ObjectAccessControl acl);

  /**
   * Updates a default object ACL entry on the specified bucket.
   *
   * @throws StorageException upon failure
   */
  ObjectAccessControl patchDefaultAcl(ObjectAccessControl acl);

  /**
   * Lists the default object ACL entries for the provided bucket.
   *
   * @throws StorageException upon failure
   */
  List<ObjectAccessControl> listDefaultAcls(String bucket);

  /**
   * Returns the ACL entry for the specified entity on the specified object or {@code null} if not
   * found.
   *
   * @throws StorageException upon failure
   */
  ObjectAccessControl getAcl(String bucket, String object, Long generation, String entity);

  /**
   * Deletes the ACL entry for the specified entity on the specified object.
   *
   * @return {@code true} if the ACL was deleted, {@code false} if it was not found
   * @throws StorageException upon failure
   */
  boolean deleteAcl(String bucket, String object, Long generation, String entity);

  /**
   * Creates a new ACL entry on the specified object.
   *
   * @throws StorageException upon failure
   */
  ObjectAccessControl createAcl(ObjectAccessControl acl);

  /**
   * Updates an ACL entry on the specified object.
   *
   * @throws StorageException upon failure
   */
  ObjectAccessControl patchAcl(ObjectAccessControl acl);

  /**
   * Lists the ACL entries for the provided object.
   *
   * @throws StorageException upon failure
   */
  List<ObjectAccessControl> listAcls(String bucket, String object, Long generation);

  /**
   * Returns the IAM policy for the specified bucket.
   *
   * @throws StorageException upon failure
   */
  Policy getIamPolicy(String bucket);

  /**
   * Updates the IAM policy for the specified bucket.
   *
   * @throws StorageException upon failure
   */
  Policy setIamPolicy(String bucket, Policy policy);

  /**
   * Tests whether the caller holds the specified permissions for the specified bucket.
   *
   * @throws StorageException upon failure
   */
  TestIamPermissionsResponse testIamPermissions(String bucket, List<String> permissions);
}


text:
import os
import re

from setuptools import setup

CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))

with open(os.path.join(CURRENT_DIR, "README.rst")) as file:
    README = file.read()

with open(os.path.join(CURRENT_DIR, 'LICENSE')) as file:
    LICENSE = file.read()

with open(os.path.join(CURRENT_DIR, 'catzzz', '__init__.py')) as file:
    version_line = ''
    for line in file.readlines():
        if '__version__' in line:
            version_line = line
            break

    version_line = version_line.strip()

    match = re.match("__version__ = '(\d+\.\d+\.\d+)'", version_line)

    if not match:
        raise ValueError('No catzzz version info found.')

    version = match.group(1)

CLASSIFIERS = [
    'Development Status :: 3 - Alpha',
    'Intended Audience :: Developers',
    'License :: OSI Approved :: BSD License',
    'Programming Language :: Python'
]

setup(name='catzzz',
      version=version,
      author='Paul Logston',
      author_email='code@logston.me',
      url='http://github.com/logston/catzzz',
      description='A package for getting more cats into your code.',
      long_description=README,
      license=LICENSE,
      classifiers=CLASSIFIERS,
      packages=['catzzz'],
      include_package_data=True,
      package_data={'': ['LICENSE', 'README.rst']})


text:
namespace network {

// A PendingSharedURLLoaderFactory that wraps a SharedURLLoaderFactory.  The
// PendingSharedURLLoaderFactory can be used on any thread to create a new
// SharedURLLoaderFactory that will post tasks to another thread to invoke
// methods on the original factory. SharedURLLoaderFactory subclasses can use
// this class to easily implement the Clone() method.
//
// It must be created on the thread |base_factory| lives on.  Note that if
// objects created via it are indeed used on a different thread from
// |base_factory|'s, an extra thread hop will be introduced.
class COMPONENT_EXPORT(NETWORK_CPP) CrossThreadPendingSharedURLLoaderFactory
    : public PendingSharedURLLoaderFactory {
 public:
  explicit CrossThreadPendingSharedURLLoaderFactory(
      scoped_refptr<SharedURLLoaderFactory> base_factory);
  ~CrossThreadPendingSharedURLLoaderFactory() override;

 protected:
  scoped_refptr<SharedURLLoaderFactory> CreateFactory() override;

 private:
  friend class CrossThreadSharedURLLoaderFactory;

  class State;
  struct StateDeleterTraits;

  // This constructor is used when something equivalent to
  // this->CreateFactory()->Clone() occurs, sharing information on underlying
  // SharedURLLoaderFactory and its task runner with the new
  // CrossThreadPendingSharedURLLoaderFactory object.
  explicit CrossThreadPendingSharedURLLoaderFactory(scoped_refptr<State> state);

  scoped_refptr<State> state_;
};

}  // namespace network

#endif  // SERVICES_NETWORK_PUBLIC_CPP_CROSS_THREAD_PENDING_SHARED_URL_LOADER_FACTORY_H_


text:
using System;
using System.Collections.Generic;

namespace BreezeCRM.Models
{
    public partial class CustomerASuppliersByCity
    {
        public string City { get; set; }
        public string CompanyName { get; set; }
        public string ContactName { get; set; }
        public string Relationship { get; set; }
    }
}


text:
<md-toolbar layout-padding ng-controller="NavbarCtrl" class="md-whiteframe-z2">
  <md-toolbar-tools ui-sref="main">

 ManaTicket

  </md-toolbar-tools>

Hola {{userName}}

    <md-button class="md-accent" ng-click="logout()">Logout</md-button>

</md-toolbar>


text:
void *nm_malloc(size_t size);
void *nm_realloc(void *ptr, size_t size);
void *nm_calloc(size_t count, size_t size);
void *nm_strdup(const char *s);
void *nm_strndup(const char *s, size_t size);
void nm_asprintf(char **strp, const char *fmt, ...);
#define nm_free(ptr) do { if(ptr) { free(ptr); ptr = NULL; } } while(0)
#endif


text:
package jasy.lang;

public interface ClassBytesTransformer {
    void initialize(ClassLoader classLoader);
    byte[] transform(ClassLoader classLoader, byte[] classBytes);
}


text:
<?php

namespace SbS\AdminLTEBundle\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\Console\Application;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

/**
 * This is the class that loads and manages your bundle configuration.
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class SbSAdminLTEExtension extends Extension implements PrependExtensionInterface
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container): void
    {
        $loader = new Loader\XmlFileLoader($container, new FileLocator(\dirname(__DIR__) . '/Resources/config'));
        $loader->load('services.xml');

        if (\class_exists(Application::class)) {
            $loader->load('console.xml');
        }
    }

    /**
     * Allow an extension to prepend the extension configurations.
     *
     * @param ContainerBuilder $container
     */
    public function prepend(ContainerBuilder $container): void
    {
        $bundles = $container->getParameter('kernel.bundles');

        if (isset($bundles['TwigBundle'])) {
            $container->prependExtensionConfig(
                'twig',
                [
                    'form_themes' => ['bootstrap_3_layout.html.twig'],
                ]
            );
        }
    }
}


text:
<iq type='set'
    from='agent@vnsw.contrailsystems.com'
    to='bgp.contrail.com/bgp-peer'
    id='sub1'>
    <pubsub xmlns='http://jabber.org/protocol/pubsub'>
        <unsubscribe node='red'/>
    </pubsub>
</iq>


text:
package edu.ucdenver.ccp.datasource.identifiers;

import lombok.Getter;

public class RepairedStringDataSourceIdentifier extends StringDataSourceIdentifier {
	@Getter
	private final String originalIdentifierStr;
	@Getter
	private final StringDataSourceIdentifier repairedId;

	public RepairedStringDataSourceIdentifier(StringDataSourceIdentifier repairedId, String originalIdentifierStr) {
		super(repairedId.getId(), repairedId.getDataSource());
		this.originalIdentifierStr = originalIdentifierStr;
		this.repairedId = repairedId;
	}

	@Override
	public String validate(String resourceID) throws IllegalArgumentException {
		return repairedId.validate(resourceID);
	}

	@Override
	public boolean equals(Object o) {
		return repairedId.equals(o);
	}

	@Override
	public int hashCode() {
		return repairedId.hashCode();
	}

}


text:
using namespace std;

namespace Wrench
{
	class Waypoint
	{
	protected:
		Vector3 position;
		vector<Waypoint *> adjacentWaypoints;
	public:
		Waypoint(const Vector3 &nPosition);
		void SetAdjacent(int index, Waypoint *wp);
		void AddAdjacent(Waypoint *wp);
		void ClearAdjacent();
		int AmountAdjacent();

		Waypoint *GetAdjacent(int index);

		Vector3 Position();
		void SetPosition(const Vector3 &nPosition);
	};
}

#endif


text:
define(["require", "exports", '../has', "./dom/Label"], function (require, exports, has) {
    var Label;
    if (has('host-browser')) {
        Label = require('./dom/Label');
    }
    return Label;
});
//# sourceMappingURL=../_debug/ui/Label.js.map


text:
#pragma once
#include <aws/wafv2/WAFV2_EXPORTS.h>
#include <aws/wafv2/WAFV2Request.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace WAFV2
{
namespace Model
{

  /**
   */
  class AWS_WAFV2_API ListTagsForResourceRequest : public WAFV2Request
  {
  public:
    ListTagsForResourceRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "ListTagsForResource"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
When you request a list of objects with a Limit setting, if the
     * number of objects that are still available for retrieval exceeds the limit, WAF
     * returns a NextMarker value in the response. To retrieve the next
     * batch of objects, provide the marker from the prior call in your next
     * request.

     */
    inline const Aws::String& GetNextMarker() const{ return m_nextMarker; }

    /**
     *
When you request a list of objects with a Limit setting, if the
     * number of objects that are still available for retrieval exceeds the limit, WAF
     * returns a NextMarker value in the response. To retrieve the next
     * batch of objects, provide the marker from the prior call in your next
     * request.

     */
    inline bool NextMarkerHasBeenSet() const { return m_nextMarkerHasBeenSet; }

    /**
     *
When you request a list of objects with a Limit setting, if the
     * number of objects that are still available for retrieval exceeds the limit, WAF
     * returns a NextMarker value in the response. To retrieve the next
     * batch of objects, provide the marker from the prior call in your next
     * request.

     */
    inline void SetNextMarker(const Aws::String& value) { m_nextMarkerHasBeenSet = true; m_nextMarker = value; }

    /**
     *
When you request a list of objects with a Limit setting, if the
     * number of objects that are still available for retrieval exceeds the limit, WAF
     * returns a NextMarker value in the response. To retrieve the next
     * batch of objects, provide the marker from the prior call in your next
     * request.

     */
    inline void SetNextMarker(Aws::String&& value) { m_nextMarkerHasBeenSet = true; m_nextMarker = std::move(value); }

    /**
     *
When you request a list of objects with a Limit setting, if the
     * number of objects that are still available for retrieval exceeds the limit, WAF
     * returns a NextMarker value in the response. To retrieve the next
     * batch of objects, provide the marker from the prior call in your next
     * request.

     */
    inline void SetNextMarker(const char* value) { m_nextMarkerHasBeenSet = true; m_nextMarker.assign(value); }

    /**
     *
When you request a list of objects with a Limit setting, if the
     * number of objects that are still available for retrieval exceeds the limit, WAF
     * returns a NextMarker value in the response. To retrieve the next
     * batch of objects, provide the marker from the prior call in your next
     * request.

     */
    inline ListTagsForResourceRequest& WithNextMarker(const Aws::String& value) { SetNextMarker(value); return *this;}

    /**
     *
When you request a list of objects with a Limit setting, if the
     * number of objects that are still available for retrieval exceeds the limit, WAF
     * returns a NextMarker value in the response. To retrieve the next
     * batch of objects, provide the marker from the prior call in your next
     * request.

     */
    inline ListTagsForResourceRequest& WithNextMarker(Aws::String&& value) { SetNextMarker(std::move(value)); return *this;}

    /**
     *
When you request a list of objects with a Limit setting, if the
     * number of objects that are still available for retrieval exceeds the limit, WAF
     * returns a NextMarker value in the response. To retrieve the next
     * batch of objects, provide the marker from the prior call in your next
     * request.

     */
    inline ListTagsForResourceRequest& WithNextMarker(const char* value) { SetNextMarker(value); return *this;}

    /**
     *
The maximum number of objects that you want WAF to return for this request.
     * If more objects are available, in the response, WAF provides a
     * NextMarker value that you can use in a subsequent call to get the
     * next batch of objects.

     */
    inline int GetLimit() const{ return m_limit; }

    /**
     *
The maximum number of objects that you want WAF to return for this request.
     * If more objects are available, in the response, WAF provides a
     * NextMarker value that you can use in a subsequent call to get the
     * next batch of objects.

     */
    inline bool LimitHasBeenSet() const { return m_limitHasBeenSet; }

    /**
     *
The maximum number of objects that you want WAF to return for this request.
     * If more objects are available, in the response, WAF provides a
     * NextMarker value that you can use in a subsequent call to get the
     * next batch of objects.

     */
    inline void SetLimit(int value) { m_limitHasBeenSet = true; m_limit = value; }

    /**
     *
The maximum number of objects that you want WAF to return for this request.
     * If more objects are available, in the response, WAF provides a
     * NextMarker value that you can use in a subsequent call to get the
     * next batch of objects.

     */
    inline ListTagsForResourceRequest& WithLimit(int value) { SetLimit(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the resource.

     */
    inline const Aws::String& GetResourceARN() const{ return m_resourceARN; }

    /**
     *
The Amazon Resource Name (ARN) of the resource.

     */
    inline bool ResourceARNHasBeenSet() const { return m_resourceARNHasBeenSet; }

    /**
     *
The Amazon Resource Name (ARN) of the resource.

     */
    inline void SetResourceARN(const Aws::String& value) { m_resourceARNHasBeenSet = true; m_resourceARN = value; }

    /**
     *
The Amazon Resource Name (ARN) of the resource.

     */
    inline void SetResourceARN(Aws::String&& value) { m_resourceARNHasBeenSet = true; m_resourceARN = std::move(value); }

    /**
     *
The Amazon Resource Name (ARN) of the resource.

     */
    inline void SetResourceARN(const char* value) { m_resourceARNHasBeenSet = true; m_resourceARN.assign(value); }

    /**
     *
The Amazon Resource Name (ARN) of the resource.

     */
    inline ListTagsForResourceRequest& WithResourceARN(const Aws::String& value) { SetResourceARN(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the resource.

     */
    inline ListTagsForResourceRequest& WithResourceARN(Aws::String&& value) { SetResourceARN(std::move(value)); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the resource.

     */
    inline ListTagsForResourceRequest& WithResourceARN(const char* value) { SetResourceARN(value); return *this;}

  private:

    Aws::String m_nextMarker;
    bool m_nextMarkerHasBeenSet;

    int m_limit;
    bool m_limitHasBeenSet;

    Aws::String m_resourceARN;
    bool m_resourceARNHasBeenSet;
  };

} // namespace Model
} // namespace WAFV2
} // namespace Aws


text:
docker build --tag vvakame/review:local-build .
docker run -t --rm vvakame/review:local-build /bin/bash -ci "mkdir /book && cd /book && review-init test && cd ./test && rake pdf && rake epub"


text:
/**
 * This code has been downloaded from https://github.com/LEOAlg/HM and adapted
 *in order to integrate it inside Nornir. The behaviour of this algorithm is
 *described in the paper "A Probabilistic Graphical Model-based Approach for
 *Minimizing Energy Under Performance Constraints" by Mishra, Nikita and Zhang,
 *Huazhe and Lafferty, John D. and Hoffmann, Henry.
 **/

#ifdef ENABLE_ARMADILLO
#include <nornir/leo.h>

using namespace std;
using namespace arma;

#include <cfloat>

namespace leo {

#ifndef typedef_emParam_t
#define typedef_emParam_t
typedef struct {
  vec mu;
  mat C;
  mat T;
  double sigma;
} emParam_t;
#endif // typedef_emParam_t

#ifndef typedef_emValue_t
#define typedef_emValue_t
typedef struct {
  vec w;
  emParam_t em_t;
} emReturn_t;
#endif // typedef_emValue_t

void init_EMParam(emParam_t *Old, int n);
void EM(emParam_t *Old, mat *W, mat *y_em, int i, int ep, int iteration_limit,
        emReturn_t *Appl);
double residualAccuracy(vec A, vec B);
long Time_Difference(struct timeval end, struct timeval start);

void init_EMParam(emParam_t *Old, int n) {
  Old->mu = zeros<vec>(n);
  Old->C = eye<mat>(n, n);
  Old->T = zeros<mat>(n, n);
  Old->sigma = 1;
}

void EM(emParam_t *Old, mat *W, mat *y_em, int i, int ep, int iteration_limit,
        emReturn_t *Appl) {

  int n = y_em->n_rows;
  int m = y_em->n_cols;
  int numSamples = sum(sum(*W));
  double pi = 1;
  double tau = 1;
  // double error = INFINITY;
  mat I = diagmat(*W);
  double sigma = Old->sigma;
  vec mu = Old->mu;
  mat C = Old->C;
  mat wl = zeros<mat>(n, m);

  for (int iterator = 1; iterator <= iteration_limit; iterator++) {
    mat Cinv = inv(C);
    mat Cl0 = inv(I / sigma + Cinv);
    mat Cll = inv(eye<mat>(n, n) / sigma + Cinv);

    wl = (Cll / sigma) * (*y_em) + repmat(Cinv * mu, 1, m);
    wl.col(0) = Cl0 * ((y_em->col(0)) / sigma + Cinv * mu);

    double normSum =
        pow(norm(I * (y_em->col(0) - wl.col(0)), 2), 2) + trace(I * Cl0);
    vec wlSum = sum(wl, 1);
    mat ClSum = eye<mat>(n, n) + Cl0 + (m - 1) * Cll;
    mat wlSumCov = eye<mat>(n, n) + (wl.col(0) - mu) * trans(wl.col(0) - mu);
    for (int l = 1; l < m; l++) {
      wlSumCov = wlSumCov + (wl.col(l) - mu) * trans(wl.col(l) - mu);
      normSum =
          normSum + pow(norm(y_em->col(l) - wl.col(l), 2), 2) + trace(Cll);
    }
    mu = ((1.0 / (double) (pi + m)) * wlSum);
    C = ((1.0 / (double) (tau + m)) *
         (pi * (mu * trans(mu)) + tau * eye<mat>(n, n) + ClSum + wlSumCov));
    sigma = (1.0 / (double) ((m - 1) * n + numSamples)) * normSum;
    // error = norm(Old->mu - mu,"fro")+ norm(Old->C - C,"fro") + abs(Old->sigma
    // - sigma);
    Old->mu = mu;
    Old->C = C;
    Old->sigma = sigma;
  }

  Appl->w = wl.col(0);
  Appl->em_t = *Old;
}

long Time_Difference(struct timeval end, struct timeval start) {
  long mtime, seconds, useconds;
  seconds = end.tv_sec - start.tv_sec;
  useconds = end.tv_usec - start.tv_usec;

  mtime = ((seconds) *1000 + useconds / 1000.0) + 0.5;

  return mtime;
}

double residualAccuracy(vec A, vec B) {
  double n = A.n_elem;
  double rss = pow(norm(A - B, 2), 2);
  double tss = pow(norm(A - mean(A), 2), 2);
  double residualsquare = 1 - rss / tss;
  return (1 - (1 - residualsquare) * (n - 1) / (n - 2)) * 100.0;
}

double minNonZero(const mat *data) {
  double min = DBL_MAX;
  for (auto &val : *data) {
    if (val && val < min) {
      min = val;
    }
  }
  return min;
}

mat normalize(const mat *data, double low = 0, double high = 100.0) {
  double min = minNonZero(data);
  double max = data->max();

  double rng = max - min;
  mat copy = *data;

  for (auto &val : copy) {
    if (val) {
      val = high - (((high - low) * (max - val)) / rng);
    }
  }
  return copy;
}

vec denormalize(vec *data, mat *origData, double low = 0, double high = 100.0) {
  double min = minNonZero(origData);
  double max = origData->max();
  double rng = max - min;
  vec copy = *data;

  for (auto &val : copy) {
    val = max + (((val - high) * rng) / (high - low));
  }
  return copy;
}

void loadData(uint appId, mat *data, vec *trueData, mat *W,
              std::string dataFile, const vec *sampledData,
              bool perColumnNormalization, bool computeError = false) {
  int n; //, numSamples = 0;
  mat SupPower, SupPerf;

  // numSamples = 20;

  data->load(dataFile.c_str());
  n = data->n_rows; // # CONFIGURATIONS
  *W = zeros<vec>(n);

  for (size_t i = 0; i < sampledData->size(); i++) {
    if (sampledData->at(i) != 0) {
      //++numSamples;
      (*W)(i) = 1;
    }
  }

  if (computeError) {
    if (perColumnNormalization) {
      mat tmp(data->col(appId));
      *trueData = normalize(&tmp);
    } else {
      *trueData = normalize(data).col(appId);
    }
  }

  data->col(appId) = *sampledData;
  data->swap_cols(0, appId);
}

PredictionResults compute(uint appId, const std::string &dataFile,
                          const arma::vec *sampledData,
                          bool perColumnNormalization, bool computeError) {
  int n;
  mat data, normData, y_em, W;
  vec trueData;
  emParam_t oldData;
  emReturn_t applData;

  // LOAD DATA AND MISSING VALUES, BS is the name of target application
  loadData(appId, &data, &trueData, &W, dataFile, sampledData,
           perColumnNormalization, computeError);

  // Normalization
  if (perColumnNormalization) {
    for (size_t i = 0; i < data.n_cols; i++) {
      mat tmp(data.col(i));
      normData.insert_cols(i, normalize(&tmp));
    }
  } else {
    normData = normalize(&data);
  }

  n = data.n_rows; // # CONFIGURATIONS
  // m = data.n_cols;    // # APPLICATIONS

  init_EMParam(&oldData, n);
  EM(&oldData, &W, &normData, 0, 10000, 5, &applData);

  PredictionResults pr;
  if (computeError) {
    pr.accuracy = residualAccuracy(applData.w, trueData);
  } else {
    pr.accuracy = -1;
  }

  if (perColumnNormalization) {
    mat tmp(data.col(0));
    pr.predictions = denormalize(&(applData.w), &tmp);
  } else {
    pr.predictions = denormalize(&(applData.w), &data);
  }
  return pr;
}
} // namespace leo

#ifdef TESTMAIN
int main(int argc, char **argv) {
  int appId = atoi(argv[1]);
  char *powerFile = argv[2];
  char *bandwidthFile = argv[3];

  vec sampledPower, sampledPerformance;
  mat powerData, perfData;
  powerData.load(powerFile);
  perfData.load(bandwidthFile);
  sampledPower = powerData.col(appId);
  sampledPerformance = perfData.col(appId);

  size_t n = 312; // ATTENTION: This must be set equal to the number of columns
                  // in file (TODO)
  for (size_t i = 0; i < n; i++) {
    if (i % ((n / 20 + 1)) == 0) {
      sampledPower[i] = powerData.col(appId)[i];
      sampledPerformance[i] = perfData.col(appId)[i];
    } else {
      sampledPower[i] = 0;
      sampledPerformance[i] = 0;
    }
  }

  leo::PredictionResults pr =
      leo::compute(appId, bandwidthFile, &sampledPerformance, true, true);
  std::cout << pr.accuracy << std::endl;

  pr = leo::compute(appId, powerFile, &sampledPower, false, true);
  std::cout << pr.accuracy << std::endl;
}
#endif

#endif


text:
package sgraph;

import com.jogamp.opengl.GL3;
import org.joml.Matrix4f;

import java.util.Map;
import java.util.Stack;

/**
 * This node represents the leaf of a scene graph. It is the only type of node that has
 * actual geometry to render.
 * @author Amit Shesh
 */
public class LeafNode extends AbstractNode
{
    /**
     * The name of the object instance that this leaf contains. All object instances are stored
     * in the scene graph itself, so that an instance can be reused in several leaves
     */
    protected String objInstanceName;
    /**
     * The material associated with the object instance at this leaf
     */
    protected util.Material material;

    protected String textureName;

    public LeafNode(String instanceOf,IScenegraph graph,String name)
    {
        super(graph,name);
        this.objInstanceName = instanceOf;
    }

    /*
	 *Set the material of each vertex in this object
	 */
    @Override
    public void setMaterial(util.Material mat)
    {
        material = new util.Material(mat);
    }

    /**
     * Set texture ID of the texture to be used for this leaf
     * @param name
     */
    @Override
    public void setTextureName(String name)
    {
        textureName = name;
    }

    /*
     * gets the material
     */
    public util.Material getMaterial()
    {
        return material;
    }

    @Override
    public INode clone()
    {
        LeafNode newclone = new LeafNode(this.objInstanceName,scenegraph,name);
        newclone.setMaterial(this.getMaterial());
        return newclone;
    }

    /**
     * Delegates to the scene graph for rendering. This has two advantages:
     *

     *
It keeps the leaf light.

     *
It abstracts the actual drawing to the specific implementation of the scene graph renderer

     *

     * @param context the generic renderer context {@link sgraph.IScenegraphRenderer}
     * @param modelView the stack of modelview matrices
     * @throws IllegalArgumentException
     */
    @Override
    public void draw(IScenegraphRenderer context,Stack<Matrix4f> modelView) throws IllegalArgumentException
    {
        if (objInstanceName.length()>0)
        {
            context.drawMesh(objInstanceName,material,textureName,modelView.peek());
        }
    }

}


text:
<?php

namespace Qlake\Payment;

interface GatewayInterface
{
	public function __construct(array $config);

	public function purchase($amount, $receiptId);

	public function send();

	//public function redirect();

	//public function handle();

	//public function verify();
}


text:
enyo.depends(
	"$lib/layout",
	"$lib/onyx",	// To theme Onyx using Theme.less, change this line to $lib/onyx/source,
	//"Theme.less",	// uncomment this line, and follow the steps described in Theme.less
	"$lib/webos-lib",
	"$lib/more-arrangers",
	//Main App
	"App.css",
	"App.js"
);


text:
On initialization, essentially as soon as a FakeItEasy type is
accessed, FakeItEasy uses reflection to look for internal and
user-supplied extension points. In most cases, there is no _need_ for
users to define any extensions, but they may be used to enhance the
power and usability of FakeItEasy.

There are currently three kinds of extension points defined:

* [Custom Dummy Creation](custom-dummy-creation.md) rules,
* [Implicit Creation Options](implicit-creation-options.md), and
* [Argument Value Formatters](formatting-argument-values.md)

Please see their individual documentation to learn how each of these is used.

## The scanning process

On startup, FakeItEasy searches the following assemblies for classes that
implement the various extensions points:

* its own assembly,
* assemblies already loaded in the current AppDomain, if they reference
  FakeItEasy,
* assemblies referenced by assemblies from the previous bullet point, if they
  reference FakeItEasy,
* additional assemblies identified by the [Bootstrapper](bootstrapper.md)'s
  `GetAssemblyFileNamesToScanForExtensions` method, if they reference
  FakeItEasy.

Any such classes found are added to a catalogue and used at need.