text:
#nullable enable

using Pchp.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace Peachpie.Library.PDO
{
    partial class PDO
    {
        /// <summary>
        /// Lazily initialized set of explicitly set attributes.
        /// If not specified, the attributed has its default value.
        /// </summary>
        private protected Dictionary<PDO_ATTR, PhpValue>? _lazyAttributes;

        /// <summary>
        /// Lazily initializes <see cref="_lazyAttributes"/>.
        /// </summary>
        private protected Dictionary<PDO_ATTR, PhpValue> GetOrCreateAttributes() => _lazyAttributes ??= new Dictionary<PDO_ATTR, PhpValue>();

        /// <summary>
        /// "Oracle" handling of NULL and empty strings.
        /// </summary>
        private protected PDO_NULL _oracle_nulls; // = PDO_NULL.NULL_NATURAL; // 0

        /// <summary>
        /// <c>ATTR_STRINGIFY_FETCHES</c> option.
        /// Instructs the ResultResource to convert values to strings.
        /// </summary>
        [PhpHidden]
        public bool Stringify { get; set; } = true;

        private protected bool TryGetAttribute(PDO_ATTR attribute, out PhpValue value)
        {
            if (_lazyAttributes != null && _lazyAttributes.TryGetValue(attribute, out value))
            {
                return true;
            }

            // default values:
            switch (attribute)
            {
                case PDO_ATTR.ATTR_DRIVER_NAME: value = Driver.Name; return true;
                case PDO_ATTR.ATTR_SERVER_VERSION: value = Connection.ServerVersion; return true;
                case PDO_ATTR.ATTR_CLIENT_VERSION: value = Driver.ClientVersion; return true;
                case PDO_ATTR.ATTR_ORACLE_NULLS: value = (int)_oracle_nulls; return true;

                case PDO_ATTR.ATTR_AUTOCOMMIT: value = PhpValue.True; return true;
                case PDO_ATTR.ATTR_PREFETCH: value = 0; return true;
                case PDO_ATTR.ATTR_TIMEOUT: value = 30; return true;
                case PDO_ATTR.ATTR_ERRMODE: value = ERRMODE_EXCEPTION; return true;
                case PDO_ATTR.ATTR_SERVER_INFO: value = PhpValue.Null; return true;
                case PDO_ATTR.ATTR_CONNECTION_STATUS: value = PhpValue.Null; return true;
                case PDO_ATTR.ATTR_CASE: value = (int)PDO_CASE.CASE_LOWER; return true;
                case PDO_ATTR.ATTR_CURSOR_NAME: value = PhpValue.Null; return true;
                case PDO_ATTR.ATTR_CURSOR: value = PhpValue.Null; return true;
                case PDO_ATTR.ATTR_PERSISTENT: value = PhpValue.False; return true;
                case PDO_ATTR.ATTR_STATEMENT_CLASS: value = PhpValue.Null; return true;
                case PDO_ATTR.ATTR_FETCH_CATALOG_NAMES: value = PhpValue.Null; return true;
                case PDO_ATTR.ATTR_FETCH_TABLE_NAMES: value = PhpValue.Null; return true;
                case PDO_ATTR.ATTR_STRINGIFY_FETCHES: value = this.Stringify; return true;
                case PDO_ATTR.ATTR_MAX_COLUMN_LEN: value = PhpValue.Null; return true;
                case PDO_ATTR.ATTR_DEFAULT_FETCH_MODE: value = 0; return true;
                case PDO_ATTR.ATTR_EMULATE_PREPARES: value = PhpValue.False; return true;

                default:
                    // driver specific:
                    if (attribute > PDO_ATTR.ATTR_DRIVER_SPECIFIC)
                    {
                        value = Driver.GetAttribute(this, (int)attribute);
                        return Operators.IsSet(value);
                    }

                    //TODO : what to do on unknown attribute ?
                    value = PhpValue.Null;
                    return false;
            }
        }

        /// <summary>
        /// Retrieve a database connection attribute
        /// </summary>
        /// <param name="attribute">The attribute.</param>
        /// <returns>A successful call returns the value of the requested PDO attribute. An unsuccessful call returns <c>null</c>.</returns>
        public virtual PhpValue getAttribute(PDO_ATTR attribute) => TryGetAttribute(attribute, out var value) ? value : PhpValue.Null;

        /// <summary>
        /// Set an attribute.
        /// </summary>
        /// <param name="attribute">The attribute.</param>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public virtual bool setAttribute(PDO_ATTR attribute, PhpValue value)
        {
            long l; // temp value

            switch (attribute)
            {
                //readonly
                case PDO_ATTR.ATTR_SERVER_INFO:
                case PDO_ATTR.ATTR_SERVER_VERSION:
                case PDO_ATTR.ATTR_CLIENT_VERSION:
                case PDO_ATTR.ATTR_CONNECTION_STATUS:
                case PDO_ATTR.ATTR_DRIVER_NAME:
                    return false;

                //boolean

                case PDO_ATTR.ATTR_AUTOCOMMIT:
                case PDO_ATTR.ATTR_EMULATE_PREPARES:
                    GetOrCreateAttributes()[attribute] = value.ToBoolean();
                    return true;

                case PDO_ATTR.ATTR_STRINGIFY_FETCHES:
                    Driver.TrySetStringifyFetches(this, value.ToBoolean());
                    return true; // always returns TRUE

                //strict positif integers

                case PDO_ATTR.ATTR_PREFETCH:
                case PDO_ATTR.ATTR_TIMEOUT:
                    // TODO: strict positif integers
                    GetOrCreateAttributes()[attribute] = value.GetValue().DeepCopy();
                    return true;

                //remaining

                case PDO_ATTR.ATTR_ERRMODE:
                    l = value.ToLong();
                    if (Enum.IsDefined(typeof(PDO_ERRMODE), (int)l))
                    {
                        GetOrCreateAttributes()[attribute] = l;
                        return true;
                    }
                    else
                    {
                        // Warning: PDO::setAttribute(): SQLSTATE[HY000]: General error: invalid error mode
                        // TODO: this.RaiseError( ... ) ?
                        PhpException.InvalidArgument(nameof(value));
                        return false;
                    }
                case PDO_ATTR.ATTR_CASE:
                    l = value.ToLong();
                    if (Enum.IsDefined(typeof(PDO_CASE), (int)l))
                    {
                        GetOrCreateAttributes()[attribute] = l;
                        return true;
                    }
                    return false;
                case PDO_ATTR.ATTR_CURSOR:
                    l = value.ToLong();
                    if (Enum.IsDefined(typeof(PDO_CURSOR), (int)l))
                    {
                        GetOrCreateAttributes()[attribute] = l;
                        return true;
                    }
                    return false;
                case PDO_ATTR.ATTR_DEFAULT_FETCH_MODE:
                    l = value.ToLong();
                    if (Enum.IsDefined(typeof(PDO_FETCH), (int)l))
                    {
                        GetOrCreateAttributes()[attribute] = l;
                        return true;
                    }
                    return false;

                case PDO_ATTR.ATTR_STATEMENT_CLASS:
                    if (value.IsPhpArray(out var arr) && arr != null && arr.Count != 0)
                    {
                        GetOrCreateAttributes()[attribute] = arr.DeepCopy();
                        return true;
                    }
                    return false;

                case PDO_ATTR.ATTR_ORACLE_NULLS:
                    if (value.IsLong(out l))
                    {
                        Debug.Assert(l == (long)PDO_NULL.NULL_NATURAL, "nonstandard ATTR_ORACLE_NULLS is not yet supported");
                        _oracle_nulls = (PDO_NULL)l;
                        return true;
                    }
                    else
                    {
                        HandleError("attribute value must be an integer");
                        return false;
                    }

                case PDO_ATTR.ATTR_FETCH_CATALOG_NAMES:
                case PDO_ATTR.ATTR_FETCH_TABLE_NAMES:
                case PDO_ATTR.ATTR_MAX_COLUMN_LEN:
                case PDO_ATTR.ATTR_PERSISTENT:
                    throw new NotImplementedException($"setAttribute({attribute})");

                //statement only
                case PDO_ATTR.ATTR_CURSOR_NAME:
                    return false;

                default:

                    // driver specific
                    try
                    {
                        if (attribute >= PDO_ATTR.ATTR_DRIVER_SPECIFIC)
                        {
                            return Driver.TrySetAttribute(GetOrCreateAttributes(), (int)attribute, value);
                        }
                    }
                    catch (System.Exception ex)
                    {
                        this.HandleError(ex);
                        return false;
                    }

                    // invalid attribute:
                    Debug.WriteLine($"PDO_ATTR {attribute} is not known.");
                    return false;
            }

        }
    }
}


text:
 /*
 *  *  Programação de Computadores e Algoritmos
 *     Trabalho 5
 *     Questão 5.03
 *     Equipe:
 *     Benjamin Borges
 *     Jackson Gomes
 *     Richardson Souza
 *     Luiz Brandão
 *     Wilson Calixto
 */

#include <string.h>
#include <stdio.h>
#include "funcao.h"

int main(int argc, const char *argv[]){
	int n;
	printf("Digite um número: ");
	scanf("%d",&n);
	printf("O número %d em binário é %s\n",n,int2binary(n));
	return 0;
}

redpajama_set_name: RedPajamaGithub


text:
using ConfigServer.Core;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace ConfigServer.Server
{
    internal class CreateUpdateClientCommandHandler : ICommandHandler<CreateUpdateClientCommand>
    {
        private readonly IConfigClientRepository configClientRepository;
        private readonly IEventService eventService;

        public CreateUpdateClientCommandHandler(IConfigClientRepository configClientRepository, IEventService eventService)
        {
            this.configClientRepository = configClientRepository;
            this.eventService = eventService;
        }

        public async Task<CommandResult> Handle(CreateUpdateClientCommand command)
        {
            if (command.Client == null)
                return CommandResult.Failure("Invalid client");
            var client = Map(command.Client);
            await configClientRepository.UpdateClientAsync(client);
            await eventService.Publish(new ConfigurationClientUpdatedEvent(client.ClientId));
            return CommandResult.Success();
        }

        private ConfigurationClient Map(ConfigurationClientPayload payload)
        {
            var result = new ConfigurationClient
            {
                ClientId = string.IsNullOrWhiteSpace(payload.ClientId) ? Guid.NewGuid().ToString() : payload.ClientId,
                Name = payload.Name,
                Description = payload.Description,
                Group = payload.Group,
                ReadClaim = payload.ReadClaim,
                ConfiguratorClaim = payload.ConfiguratorClaim,
                Enviroment = payload.Enviroment,
                Tags = payload.Tags
            };
            foreach (var setting in payload.Settings)
                result.Settings.Add(setting.Key, setting);
            return result;

        }
    }
}


text:
class CreateNavigations < ActiveRecord::Migration
  def change
    create_table :navigations do |t|

      t.string  :title, limit: 50
      t.integer :position
      t.string  :permalink
      t.boolean :admin,   default: false

      t.timestamps
    end
  end
end


text:
using content::BrowserThread;

namespace {

static const base::FilePath::CharType kTranslationCacheDirectoryName[] =
    FILE_PATH_LITERAL("PnaclTranslationCache");
// Delay to wait for initialization of the cache backend
static const int kTranslationCacheInitializationDelayMs = 20;

void CloseBaseFile(base::File auto_file_closer) {
}

void CloseScopedFile(std::unique_ptr<base::File> auto_file_closer) {}

}  // namespace

namespace pnacl {

class FileProxy {
 public:
  FileProxy(std::unique_ptr<base::File> file,
            base::WeakPtr<pnacl::PnaclHost> host);
  int Write(scoped_refptr<net::DrainableIOBuffer> buffer);
  void WriteDone(const PnaclHost::TranslationID& id, int result);

 private:
  std::unique_ptr<base::File> file_;
  base::WeakPtr<pnacl::PnaclHost> host_;
};

FileProxy::FileProxy(std::unique_ptr<base::File> file,
                     base::WeakPtr<pnacl::PnaclHost> host)
    : file_(std::move(file)), host_(host) {}

int FileProxy::Write(scoped_refptr<net::DrainableIOBuffer> buffer) {
  int rv = file_->Write(0, buffer->data(), buffer->size());
  if (rv == -1)
    PLOG(ERROR) << "FileProxy::Write error";
  return rv;
}

void FileProxy::WriteDone(const PnaclHost::TranslationID& id, int result) {
  if (host_) {
    host_->OnBufferCopiedToTempFile(id, std::move(file_), result);
  } else {
    BrowserThread::PostBlockingPoolTask(
        FROM_HERE,
        base::Bind(CloseScopedFile, Passed(&file_)));
  }
}

PnaclHost::PnaclHost()
    : pending_backend_operations_(0),
      cache_state_(CacheUninitialized),
      weak_factory_(this) {}

PnaclHost::~PnaclHost() {
  // When PnaclHost is destroyed, it's too late to post anything to the cache
  // thread (it will hang shutdown). So just leak the cache backend.
  pnacl::PnaclTranslationCache* cache = disk_cache_.release();
  (void)cache;
}

PnaclHost* PnaclHost::GetInstance() {
  return base::Singleton<PnaclHost>::get();
}

PnaclHost::PendingTranslation::PendingTranslation()
    : process_handle(base::kNullProcessHandle),
      render_view_id(0),
      nexe_fd(NULL),
      got_nexe_fd(false),
      got_cache_reply(false),
      got_cache_hit(false),
      is_incognito(false),
      callback(NexeFdCallback()),
      cache_info(nacl::PnaclCacheInfo()) {
}

PnaclHost::PendingTranslation::PendingTranslation(
    const PendingTranslation& other) = default;

PnaclHost::PendingTranslation::~PendingTranslation() {
  if (nexe_fd)
    delete nexe_fd;
}

bool PnaclHost::TranslationMayBeCached(
    const PendingTranslationMap::iterator& entry) {
  return !entry->second.is_incognito &&
         !entry->second.cache_info.has_no_store_header;
}

/////////////////////////////////////// Initialization

static base::FilePath GetCachePath() {
  NaClBrowserDelegate* browser_delegate = nacl::NaClBrowser::GetDelegate();
  // Determine where the translation cache resides in the file system.  It
  // exists in Chrome's cache directory and is not tied to any specific
  // profile. If we fail, return an empty path.
  // Start by finding the user data directory.
  base::FilePath user_data_dir;
  if (!browser_delegate ||
      !browser_delegate->GetUserDirectory(&user_data_dir)) {
    return base::FilePath();
  }
  // The cache directory may or may not be the user data directory.
  base::FilePath cache_file_path;
  browser_delegate->GetCacheDirectory(&cache_file_path);

  // Append the base file name to the cache directory.
  return cache_file_path.Append(kTranslationCacheDirectoryName);
}

void PnaclHost::OnCacheInitialized(int net_error) {
  DCHECK(thread_checker_.CalledOnValidThread());
  // If the cache was cleared before the load completed, ignore.
  if (cache_state_ == CacheReady)
    return;
  if (net_error != net::OK) {
    // This will cause the cache to attempt to re-init on the next call to
    // GetNexeFd.
    cache_state_ = CacheUninitialized;
  } else {
    cache_state_ = CacheReady;
  }
}

void PnaclHost::Init() {
  // Extra check that we're on the real IO thread since this version of
  // Init isn't used in unit tests.
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  DCHECK(thread_checker_.CalledOnValidThread());
  base::FilePath cache_path(GetCachePath());
  if (cache_path.empty() || cache_state_ != CacheUninitialized)
    return;
  disk_cache_.reset(new pnacl::PnaclTranslationCache());
  cache_state_ = CacheInitializing;
  int rv = disk_cache_->InitOnDisk(
      cache_path,
      base::Bind(&PnaclHost::OnCacheInitialized, weak_factory_.GetWeakPtr()));
  if (rv != net::ERR_IO_PENDING)
    OnCacheInitialized(rv);
}

// Initialize for testing, optionally using the in-memory backend, and manually
// setting the temporary file directory instead of using the system directory.
void PnaclHost::InitForTest(base::FilePath temp_dir, bool in_memory) {
  DCHECK(thread_checker_.CalledOnValidThread());
  disk_cache_.reset(new pnacl::PnaclTranslationCache());
  cache_state_ = CacheInitializing;
  temp_dir_ = temp_dir;
  int rv;
  if (in_memory) {
    rv = disk_cache_->InitInMemory(
      base::Bind(&PnaclHost::OnCacheInitialized, weak_factory_.GetWeakPtr()));
  } else {
    rv = disk_cache_->InitOnDisk(
      temp_dir,
      base::Bind(&PnaclHost::OnCacheInitialized, weak_factory_.GetWeakPtr()));
  }
  if (rv != net::ERR_IO_PENDING)
    OnCacheInitialized(rv);
}

///////////////////////////////////////// Temp files

// Create a temporary file on the blocking pool
// static
void PnaclHost::DoCreateTemporaryFile(base::FilePath temp_dir,
                                      TempFileCallback cb) {
  DCHECK(BrowserThread::GetBlockingPool()->RunsTasksOnCurrentThread());

  base::FilePath file_path;
  base::File file;
  bool rv = temp_dir.empty()
                ? base::CreateTemporaryFile(&file_path)
                : base::CreateTemporaryFileInDir(temp_dir, &file_path);
  if (!rv) {
    PLOG(ERROR) << "Temp file creation failed.";
  } else {
    file.Initialize(
        file_path,
        base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_READ |
            base::File::FLAG_WRITE | base::File::FLAG_TEMPORARY |
            base::File::FLAG_DELETE_ON_CLOSE);

    if (!file.IsValid())
      PLOG(ERROR) << "Temp file open failed: " << file.error_details();
  }
  BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
                          base::Bind(cb, Passed(std::move(file))));
}

void PnaclHost::CreateTemporaryFile(TempFileCallback cb) {
  if (!BrowserThread::PostBlockingPoolSequencedTask(
           "PnaclHostCreateTempFile",
           FROM_HERE,
           base::Bind(&PnaclHost::DoCreateTemporaryFile, temp_dir_, cb))) {
    DCHECK(thread_checker_.CalledOnValidThread());
    cb.Run(base::File());
  }
}

///////////////////////////////////////// GetNexeFd implementation
////////////////////// Common steps

void PnaclHost::GetNexeFd(int render_process_id,
                          int render_view_id,
                          int pp_instance,
                          bool is_incognito,
                          const nacl::PnaclCacheInfo& cache_info,
                          const NexeFdCallback& cb) {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (cache_state_ == CacheUninitialized) {
    Init();
  }
  if (cache_state_ != CacheReady) {
    // If the backend hasn't yet initialized, try the request again later.
    BrowserThread::PostDelayedTask(BrowserThread::IO,
                                   FROM_HERE,
                                   base::Bind(&PnaclHost::GetNexeFd,
                                              weak_factory_.GetWeakPtr(),
                                              render_process_id,
                                              render_view_id,
                                              pp_instance,
                                              is_incognito,
                                              cache_info,
                                              cb),
                                   base::TimeDelta::FromMilliseconds(
                                       kTranslationCacheInitializationDelayMs));
    return;
  }

  TranslationID id(render_process_id, pp_instance);
  PendingTranslationMap::iterator entry = pending_translations_.find(id);
  if (entry != pending_translations_.end()) {
    // Existing translation must have been abandonded. Clean it up.
    LOG(ERROR) << "GetNexeFd for already-pending translation";
    pending_translations_.erase(entry);
  }

  std::string cache_key(disk_cache_->GetKey(cache_info));
  if (cache_key.empty()) {
    LOG(ERROR) << "GetNexeFd: Invalid cache info";
    cb.Run(base::File(), false);
    return;
  }

  PendingTranslation pt;
  pt.render_view_id = render_view_id;
  pt.callback = cb;
  pt.cache_info = cache_info;
  pt.cache_key = cache_key;
  pt.is_incognito = is_incognito;
  pending_translations_[id] = pt;
  SendCacheQueryAndTempFileRequest(cache_key, id);
}

// Dispatch the cache read request and the temp file creation request
// simultaneously; currently we need a temp file regardless of whether the
// request hits.
void PnaclHost::SendCacheQueryAndTempFileRequest(const std::string& cache_key,
                                                 const TranslationID& id) {
  pending_backend_operations_++;
  disk_cache_->GetNexe(
      cache_key,
      base::Bind(
          &PnaclHost::OnCacheQueryReturn, weak_factory_.GetWeakPtr(), id));

  CreateTemporaryFile(
      base::Bind(&PnaclHost::OnTempFileReturn, weak_factory_.GetWeakPtr(), id));
}

// Callback from the translation cache query. |id| is bound from
// SendCacheQueryAndTempFileRequest, |net_error| is a net::Error code (which for
// our purposes means a hit if it's net::OK (i.e. 0). |buffer| is allocated
// by PnaclTranslationCache and now belongs to PnaclHost.
// (Bound callbacks must re-lookup the TranslationID because the translation
// could be cancelled before they get called).
void PnaclHost::OnCacheQueryReturn(
    const TranslationID& id,
    int net_error,
    scoped_refptr<net::DrainableIOBuffer> buffer) {
  DCHECK(thread_checker_.CalledOnValidThread());
  pending_backend_operations_--;
  PendingTranslationMap::iterator entry(pending_translations_.find(id));
  if (entry == pending_translations_.end()) {
    LOG(ERROR) << "OnCacheQueryReturn: id not found";
    DeInitIfSafe();
    return;
  }
  PendingTranslation* pt = &entry->second;
  pt->got_cache_reply = true;
  pt->got_cache_hit = (net_error == net::OK);
  if (pt->got_cache_hit)
    pt->nexe_read_buffer = buffer;
  CheckCacheQueryReady(entry);
}

// Callback from temp file creation. |id| is bound from
// SendCacheQueryAndTempFileRequest, and |file| is the created file.
// If there was an error, file is invalid.
// (Bound callbacks must re-lookup the TranslationID because the translation
// could be cancelled before they get called).
void PnaclHost::OnTempFileReturn(const TranslationID& id,
                                 base::File file) {
  DCHECK(thread_checker_.CalledOnValidThread());
  PendingTranslationMap::iterator entry(pending_translations_.find(id));
  if (entry == pending_translations_.end()) {
    // The renderer may have signaled an error or closed while the temp
    // file was being created.
    LOG(ERROR) << "OnTempFileReturn: id not found";
    BrowserThread::PostBlockingPoolTask(
        FROM_HERE, base::Bind(CloseBaseFile, Passed(std::move(file))));
    return;
  }
  if (!file.IsValid()) {
    // This translation will fail, but we need to retry any translation
    // waiting for its result.
    LOG(ERROR) << "OnTempFileReturn: temp file creation failed";
    std::string key(entry->second.cache_key);
    entry->second.callback.Run(base::File(), false);
    bool may_be_cached = TranslationMayBeCached(entry);
    pending_translations_.erase(entry);
    // No translations will be waiting for entries that will not be stored.
    if (may_be_cached)
      RequeryMatchingTranslations(key);
    return;
  }
  PendingTranslation* pt = &entry->second;
  pt->got_nexe_fd = true;
  pt->nexe_fd = new base::File(std::move(file));
  CheckCacheQueryReady(entry);
}

// Check whether both the cache query and the temp file have returned, and check
// whether we actually got a hit or not.
void PnaclHost::CheckCacheQueryReady(
    const PendingTranslationMap::iterator& entry) {
  PendingTranslation* pt = &entry->second;
  if (!(pt->got_cache_reply && pt->got_nexe_fd))
    return;
  if (!pt->got_cache_hit) {
    // Check if there is already a pending translation for this file. If there
    // is, we will wait for it to come back, to avoid redundant translations.
    for (PendingTranslationMap::iterator it = pending_translations_.begin();
         it != pending_translations_.end();
         ++it) {
      // Another translation matches if it's a request for the same file,
      if (it->second.cache_key == entry->second.cache_key &&
          // and it's not this translation,
          it->first != entry->first &&
          // and it can be stored in the cache,
          TranslationMayBeCached(it) &&
          // and it's already gotten past this check and returned the miss.
          it->second.got_cache_reply &&
          it->second.got_nexe_fd) {
        return;
      }
    }
    ReturnMiss(entry);
    return;
  }

  std::unique_ptr<base::File> file(pt->nexe_fd);
  pt->nexe_fd = NULL;
  pt->got_nexe_fd = false;
  FileProxy* proxy(new FileProxy(std::move(file), weak_factory_.GetWeakPtr()));

  if (!base::PostTaskAndReplyWithResult(
           BrowserThread::GetBlockingPool(),
           FROM_HERE,
           base::Bind(&FileProxy::Write, base::Unretained(proxy),
                      pt->nexe_read_buffer),
           base::Bind(&FileProxy::WriteDone, base::Owned(proxy),
                      entry->first))) {
    pt->callback.Run(base::File(), false);
  }
}

//////////////////// GetNexeFd miss path
// Return the temp fd to the renderer, reporting a miss.
void PnaclHost::ReturnMiss(const PendingTranslationMap::iterator& entry) {
  // Return the fd
  PendingTranslation* pt = &entry->second;
  NexeFdCallback cb(pt->callback);
  cb.Run(*pt->nexe_fd, false);
  if (!pt->nexe_fd->IsValid()) {
    // Bad FD is unrecoverable, so clear out the entry.
    pending_translations_.erase(entry);
  }
}

// On error, just return a null refptr.
// static
scoped_refptr<net::DrainableIOBuffer> PnaclHost::CopyFileToBuffer(
    std::unique_ptr<base::File> file) {
  scoped_refptr<net::DrainableIOBuffer> buffer;

  // TODO(eroman): Maximum size should be changed to size_t once that is
  // what IOBuffer requires. crbug.com/488553. Also I don't think the
  // max size should be inclusive here...
  int64_t file_size = file->GetLength();
  if (file_size < 0 || file_size > std::numeric_limits<int>::max()) {
    PLOG(ERROR) << "Get file length failed " << file_size;
    return buffer;
  }

  buffer = new net::DrainableIOBuffer(
      new net::IOBuffer(base::CheckedNumeric<size_t>(file_size).ValueOrDie()),
      base::CheckedNumeric<size_t>(file_size).ValueOrDie());
  if (file->Read(0, buffer->data(), buffer->size()) != file_size) {
    PLOG(ERROR) << "CopyFileToBuffer file read failed";
    buffer = nullptr;
  }
  return buffer;
}

// Called by the renderer in the miss path to report a finished translation
void PnaclHost::TranslationFinished(int render_process_id,
                                    int pp_instance,
                                    bool success) {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (cache_state_ != CacheReady)
    return;
  TranslationID id(render_process_id, pp_instance);
  PendingTranslationMap::iterator entry(pending_translations_.find(id));
  if (entry == pending_translations_.end()) {
    LOG(ERROR) << "TranslationFinished: TranslationID " << render_process_id
               << "," << pp_instance << " not found.";
    return;
  }
  bool store_nexe = true;
  // If this is a premature response (i.e. we haven't returned a temp file
  // yet) or if it's an unsuccessful translation, or if we are incognito,
  // don't store in the cache.
  // TODO(dschuff): use a separate in-memory cache for incognito
  // translations.
  if (!entry->second.got_nexe_fd || !entry->second.got_cache_reply ||
      !success || !TranslationMayBeCached(entry)) {
    store_nexe = false;
  } else {
    std::unique_ptr<base::File> file(entry->second.nexe_fd);
    entry->second.nexe_fd = NULL;
    entry->second.got_nexe_fd = false;

    if (!base::PostTaskAndReplyWithResult(
             BrowserThread::GetBlockingPool(),
             FROM_HERE,
             base::Bind(&PnaclHost::CopyFileToBuffer, Passed(&file)),
             base::Bind(&PnaclHost::StoreTranslatedNexe,
                        weak_factory_.GetWeakPtr(),
                        id))) {
      store_nexe = false;
    }
  }

  if (!store_nexe) {
    // If store_nexe is true, the fd will be closed by CopyFileToBuffer.
    if (entry->second.got_nexe_fd) {
      std::unique_ptr<base::File> file(entry->second.nexe_fd);
      entry->second.nexe_fd = NULL;
      BrowserThread::PostBlockingPoolTask(
          FROM_HERE,
          base::Bind(CloseScopedFile, Passed(&file)));
    }
    pending_translations_.erase(entry);
  }
}

// Store the translated nexe in the translation cache. Called back with the
// TranslationID from the host and the result of CopyFileToBuffer.
// (Bound callbacks must re-lookup the TranslationID because the translation
// could be cancelled before they get called).
void PnaclHost::StoreTranslatedNexe(
    TranslationID id,
    scoped_refptr<net::DrainableIOBuffer> buffer) {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (cache_state_ != CacheReady)
    return;
  PendingTranslationMap::iterator it(pending_translations_.find(id));
  if (it == pending_translations_.end()) {
    LOG(ERROR) << "StoreTranslatedNexe: TranslationID " << id.first << ","
               << id.second << " not found.";
    return;
  }

  if (buffer.get() == NULL) {
    LOG(ERROR) << "Error reading translated nexe";
    return;
  }
  pending_backend_operations_++;
  disk_cache_->StoreNexe(it->second.cache_key,
                         buffer.get(),
                         base::Bind(&PnaclHost::OnTranslatedNexeStored,
                                    weak_factory_.GetWeakPtr(),
                                    it->first));
}

// After we know the nexe has been stored, we can clean up, and unblock any
// outstanding requests for the same file.
// (Bound callbacks must re-lookup the TranslationID because the translation
// could be cancelled before they get called).
void PnaclHost::OnTranslatedNexeStored(const TranslationID& id, int net_error) {
  PendingTranslationMap::iterator entry(pending_translations_.find(id));
  pending_backend_operations_--;
  if (entry == pending_translations_.end()) {
    // If the renderer closed while we were storing the nexe, we land here.
    // Make sure we try to de-init.
    DeInitIfSafe();
    return;
  }
  std::string key(entry->second.cache_key);
  pending_translations_.erase(entry);
  RequeryMatchingTranslations(key);
}

// Check if any pending translations match |key|. If so, re-issue the cache
// query. In the overlapped miss case, we expect a hit this time, but a miss
// is also possible in case of an error.
void PnaclHost::RequeryMatchingTranslations(const std::string& key) {
  // Check for outstanding misses to this same file
  for (PendingTranslationMap::iterator it = pending_translations_.begin();
       it != pending_translations_.end();
       ++it) {
    if (it->second.cache_key == key) {
      // Re-send the cache read request. This time we expect a hit, but if
      // something goes wrong, it will just handle it like a miss.
      it->second.got_cache_reply = false;
      pending_backend_operations_++;
      disk_cache_->GetNexe(key,
                           base::Bind(&PnaclHost::OnCacheQueryReturn,
                                      weak_factory_.GetWeakPtr(),
                                      it->first));
    }
  }
}

//////////////////// GetNexeFd hit path

void PnaclHost::OnBufferCopiedToTempFile(const TranslationID& id,
                                         std::unique_ptr<base::File> file,
                                         int file_error) {
  DCHECK(thread_checker_.CalledOnValidThread());
  PendingTranslationMap::iterator entry(pending_translations_.find(id));
  if (entry == pending_translations_.end()) {
    BrowserThread::PostBlockingPoolTask(
        FROM_HERE,
        base::Bind(CloseScopedFile, Passed(&file)));
    return;
  }
  if (file_error == -1) {
    // Write error on the temp file. Request a new file and start over.
    BrowserThread::PostBlockingPoolTask(
        FROM_HERE,
        base::Bind(CloseScopedFile, Passed(&file)));
    CreateTemporaryFile(base::Bind(&PnaclHost::OnTempFileReturn,
                                   weak_factory_.GetWeakPtr(),
                                   entry->first));
    return;
  }
  entry->second.callback.Run(*file.get(), true);
  BrowserThread::PostBlockingPoolTask(
      FROM_HERE,
      base::Bind(CloseScopedFile, Passed(&file)));
  pending_translations_.erase(entry);
}

///////////////////

void PnaclHost::RendererClosing(int render_process_id) {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (cache_state_ != CacheReady)
    return;
  for (PendingTranslationMap::iterator it = pending_translations_.begin();
       it != pending_translations_.end();) {
    PendingTranslationMap::iterator to_erase(it++);
    if (to_erase->first.first == render_process_id) {
      // Clean up the open files.
      std::unique_ptr<base::File> file(to_erase->second.nexe_fd);
      to_erase->second.nexe_fd = NULL;
      BrowserThread::PostBlockingPoolTask(
          FROM_HERE,
          base::Bind(CloseScopedFile, Passed(&file)));
      std::string key(to_erase->second.cache_key);
      bool may_be_cached = TranslationMayBeCached(to_erase);
      pending_translations_.erase(to_erase);
      // No translations will be waiting for entries that will not be stored.
      if (may_be_cached)
        RequeryMatchingTranslations(key);
    }
  }
  BrowserThread::PostTask(
      BrowserThread::IO,
      FROM_HERE,
      base::Bind(&PnaclHost::DeInitIfSafe, weak_factory_.GetWeakPtr()));
}

////////////////// Cache data removal
void PnaclHost::ClearTranslationCacheEntriesBetween(
    base::Time initial_time,
    base::Time end_time,
    const base::Closure& callback) {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (cache_state_ == CacheUninitialized) {
    Init();
  }
  if (cache_state_ == CacheInitializing) {
    // If the backend hasn't yet initialized, try the request again later.
    BrowserThread::PostDelayedTask(
        BrowserThread::IO,
        FROM_HERE,
        base::Bind(&PnaclHost::ClearTranslationCacheEntriesBetween,
                   weak_factory_.GetWeakPtr(),
                   initial_time,
                   end_time,
                   callback),
        base::TimeDelta::FromMilliseconds(
            kTranslationCacheInitializationDelayMs));
    return;
  }
  pending_backend_operations_++;
  int rv = disk_cache_->DoomEntriesBetween(
      initial_time,
      end_time,
      base::Bind(
          &PnaclHost::OnEntriesDoomed, weak_factory_.GetWeakPtr(), callback));
  if (rv != net::ERR_IO_PENDING)
    OnEntriesDoomed(callback, rv);
}

void PnaclHost::OnEntriesDoomed(const base::Closure& callback, int net_error) {
  DCHECK(thread_checker_.CalledOnValidThread());
  BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, callback);
  pending_backend_operations_--;
  // When clearing the cache, the UI is blocked on all the cache-clearing
  // operations, and freeing the backend actually blocks the IO thread. So
  // instead of calling DeInitIfSafe directly, post it for later.
  BrowserThread::PostTask(
      BrowserThread::IO,
      FROM_HERE,
      base::Bind(&PnaclHost::DeInitIfSafe, weak_factory_.GetWeakPtr()));
}

// Destroying the cache backend causes it to post tasks to the cache thread to
// flush to disk. Because PnaclHost is a singleton, it does not get destroyed
// until all the browser threads have gone away and it's too late to post
// anything (attempting to do so hangs shutdown).  So we make sure to destroy it
// when we no longer have any outstanding operations that need it. These include
// pending translations, cache clear requests, and requests to read or write
// translated nexes.  We check when renderers close, when cache clear requests
// finish, and when backend operations complete.

// It is not safe to delete the backend while it is initializing, nor if it has
// outstanding entry open requests; it is in theory safe to delete it with
// outstanding read/write requests, but because that distinction is hidden
// inside PnaclTranslationCache, we do not delete the backend if there are any
// backend requests in flight.  As a last resort in the destructor, we just leak
// the backend to avoid hanging shutdown.
void PnaclHost::DeInitIfSafe() {
  DCHECK(pending_backend_operations_ >= 0);
  if (pending_translations_.empty() &&
      pending_backend_operations_ <= 0 &&
      cache_state_ == CacheReady) {
    cache_state_ = CacheUninitialized;
    disk_cache_.reset();
  }
}

}  // namespace pnacl


text:
from __future__ import unicode_literals

import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('auth', '0008_alter_user_username_max_length'),
    ]

    operations = [
        migrations.CreateModel(
            name='User',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('password', models.CharField(max_length=128, verbose_name='password')),
                ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
                ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
                ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
                ('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')),
                ('last_name', models.CharField(blank=True, max_length=30, verbose_name='last name')),
                ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
                ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
                ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
                ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
            ],
            options={
                'verbose_name': 'user',
                'verbose_name_plural': 'users',
                'abstract': False,
            },
            managers=[
                ('objects', django.contrib.auth.models.UserManager()),
            ],
        ),
        migrations.CreateModel(
            name='Banco',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('telefone', models.CharField(max_length=50)),
                ('fax', models.CharField(max_length=50)),
                ('email', models.EmailField(max_length=254)),
                ('logradouro', models.CharField(max_length=50)),
                ('numero', models.IntegerField()),
                ('bairro', models.CharField(max_length=50)),
                ('cidade', models.CharField(max_length=50)),
                ('uf', models.CharField(max_length=2, verbose_name='UF')),
                ('cep', models.CharField(max_length=50, verbose_name='CEP')),
                ('nome', models.CharField(max_length=50)),
                ('agencia', models.IntegerField(verbose_name='agência')),
                ('contato', models.CharField(max_length=50, verbose_name='pessoa de contato')),
                ('data_cadastro', models.DateField()),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='Cliente',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('telefone', models.CharField(max_length=50)),
                ('fax', models.CharField(max_length=50)),
                ('email', models.EmailField(max_length=254)),
                ('logradouro', models.CharField(max_length=50)),
                ('numero', models.IntegerField()),
                ('bairro', models.CharField(max_length=50)),
                ('cidade', models.CharField(max_length=50)),
                ('uf', models.CharField(max_length=2, verbose_name='UF')),
                ('cep', models.CharField(max_length=50, verbose_name='CEP')),
                ('nome', models.CharField(max_length=50)),
                ('cpf', models.CharField(max_length=50, verbose_name='CPF')),
                ('rg', models.CharField(max_length=50, verbose_name='RG')),
                ('data_cadastro', models.DateField()),
                ('negativado', models.BooleanField()),
                ('limite_compra', models.FloatField(verbose_name='limite de compra')),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='Emitido',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('numero_cheque', models.IntegerField()),
                ('tipo', models.IntegerField(choices=[(1, 'Cheque Pré')])),
                ('data_entrada', models.DateField()),
                ('data_desconto', models.DateField()),
                ('valor', models.FloatField()),
                ('data_cadastro', models.DateField()),
                ('numero_nota', models.IntegerField()),
                ('observacao', models.TextField()),
                ('banco', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.Banco')),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='Empresa',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('logradouro', models.CharField(max_length=50)),
                ('numero', models.IntegerField()),
                ('bairro', models.CharField(max_length=50)),
                ('cidade', models.CharField(max_length=50)),
                ('uf', models.CharField(max_length=2, verbose_name='UF')),
                ('cep', models.CharField(max_length=50, verbose_name='CEP')),
                ('nome', models.CharField(max_length=50)),
                ('cnpj', models.CharField(max_length=50, verbose_name='CPF/CNPJ')),
                ('ie', models.CharField(blank=True, max_length=50, null=True, verbose_name='inscrição estadual')),
                ('telefone', models.CharField(max_length=50)),
                ('fax', models.CharField(max_length=50)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='Fornecedor',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('telefone', models.CharField(max_length=50)),
                ('fax', models.CharField(max_length=50)),
                ('email', models.EmailField(max_length=254)),
                ('logradouro', models.CharField(max_length=50)),
                ('numero', models.IntegerField()),
                ('bairro', models.CharField(max_length=50)),
                ('cidade', models.CharField(max_length=50)),
                ('uf', models.CharField(max_length=2, verbose_name='UF')),
                ('cep', models.CharField(max_length=50, verbose_name='CEP')),
                ('nome', models.CharField(max_length=50)),
                ('tipo', models.IntegerField(choices=[(1, 'Física'), (2, 'Jurídica')], verbose_name='Tipo de pessoa')),
                ('cpf_cnpj', models.CharField(max_length=50, verbose_name='CPF/CNPJ')),
                ('ie', models.CharField(blank=True, max_length=50, null=True, verbose_name='inscrição estadual')),
                ('rg', models.CharField(blank=True, max_length=50, null=True, verbose_name='RG')),
                ('responsavel', models.CharField(max_length=50, verbose_name='responsável')),
                ('data_cadastro', models.DateField()),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='Recebido',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('numero_cheque', models.IntegerField()),
                ('tipo', models.IntegerField(choices=[(1, 'Cheque Pré')])),
                ('data_entrada', models.DateField()),
                ('data_desconto', models.DateField()),
                ('valor', models.FloatField()),
                ('data_cadastro', models.DateField()),
                ('data_lancamento', models.DateField()),
                ('banco', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.Banco')),
                ('emitente', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.Cliente')),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.AddField(
            model_name='emitido',
            name='fornecedor',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.Fornecedor'),
        ),
        migrations.AddField(
            model_name='user',
            name='empresa',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='core.Empresa'),
        ),
        migrations.AddField(
            model_name='user',
            name='groups',
            field=models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups'),
        ),
        migrations.AddField(
            model_name='user',
            name='user_permissions',
            field=models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions'),
        ),
    ]


text:
title: Media Berpetualang Dekat Rumah (Mlampah)
date: 2011-09-16 11:08:00 +07:00
nohibah: 382
inisiator: Achmad Habanal Huda
lokasi: Jember, Jawa Timur
dana: 200 Juta Rupiah
topik: Meretas batas – kebhinekaan bermedia
lama: Januari-desember 2012 (satu tahun) untuk tahap awal selanjutnya sampai batas
  waktu yang tidak ditentukan
deskripsi: Sebuah proyek dalam upaya pemaksimalan media promosi bagi pariwisata lokal
  dengan mengkampanyekan kepada masyarakat lokal, nasional maupun internasional untuk
  datang ke daerah tersebut. Melalui traveling and adventure documentary dalam bentuk
  video, foto dan tulisan, yang disebarkan melalui media internet (web resmi, social
  networking, dan media promo lain) diharapkan dapat mengurangi kesenjangan media
  promosi bagi wisata-wisata lokal yang kurang terperhatikan. Tahap awal proyek dilakukan
  pada kota jember dan sekitarnya (jember, banyuwangi, bondowoso, lumajang,situbondo)
  selama satu tahun. Yang kemudian berlanjut ke kota-kota lain dengan bekerja sama
  dengan pemerintah setempat, serta membangun jaringan dengan insan lokal lainnya.
masalah: Kurangnya pengetahuan dan antusiasme masyarakat terhadap pariwisata, seni,
  dan budaya lokal yang disebabkan kurangnya promosi dari pemerintah daerah serta
  tidak tersentuh oleh media nasional. Kesenjangan mediapun terjadi hanya tertuju
  pada sektor pariwisata tertentu dan tidak merata. Dengan menggali potensi-potensi
  pariwisata yang ada (wisata seni dan budaya, wisata alam, wisata kuliner) daerah
  setempat, diharapkan mampu terekspos ke masyarakat luas sehingga mengurangi kesenjangan
  media di dunia pariwisata. Dan dengan tersedianya pengetahuan wisata local akan
  merangsang antusiasme masyarakat tentang kebutuhan estetis ini.
solusi: Dengan memproduksi traveling and adventure documentary dalam bentuk video,
  foto dan tulisan mengenai tempat-tempat menarik yang patut dikunjungi di kota tersebut
  yang dikemas secara kreatif dan menarik yang melibatkan anak muda kota tersebut
  sebagai karakter/lakon dalam seri video, foto dan tulisan yang diproduksi berikut
  dengan info akses yang kemudian disebarluaskan melalui internet baik berupa situs
  resmi, jejaring sosial, maupun forum-forum internet. Melakukan kampanye sadar wisata
  lokal khususnya pada masyarakat setempat melalui kerja sama dengan pemerintah daerah
  setempat dan pengelola warnet maupun spot-spot internet untuk promo website. Pihak
  yang diuntungkan adalah pemuda lokal dengan rekruitmen sebagai talent, pengelola
  industri wisata lokal, pemerintah daerah, dan masyarakat lokal pada khususnya dan
  masyarakat luas pada umumya
keberhasilan: |-
  1. Memproduksi minimal 100 artikel dalam setahun (meliputi video, foto dan tulisan)
  2. Berdasarkan statistik jumlah pengunjung website (minimal 1 juta pengunjung dalam setahun)
  3. Mengukur peningkatan volume wisatawan lokal maupun asing yang berkunjung melalui pendataan secara periodik yang bekerja sama dengan instansi terkait.
  4. Adanya kesadaran dan respon positif masyarakat terhadap wisata lokal melalui survey secara berkala
  5. Respon positif masyarakat lokal terhadap proyek ini.
organisasi: NA
diuntungkan: pemuda lokal dengan rekruitmen sebagai talent, pengelola industri wisata
  lokal, pemerintah daerah, dan masyarakat lokal pada khususnya dan masyarakat luas
  pada umumya
layout: hibahcmb
---

![382](/static/img/hibahcmb/382.png){: .img-responsive }{: width="382" }

### {{ page.nohibah }} - {{ page.title }}

---


text:
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as actions from '../../actions/homeActions';
import Home from '../../components/Home/Home';

const mapStateToProps = state => ({
    isHovered: state.home.isHovered
});

const mapDispatchToProps = dispatch => {
    return bindActionCreators(actions, dispatch);
};

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(Home);


text:
.. This file is part of the OpenDSA eTextbook project. See
.. http://algoviz.org/OpenDSA for more details.
.. Copyright (c) 2012-2013 by the OpenDSA Project Contributors, and
.. distributed under an MIT open source license.

.. avmetadata::
   :author: Nabanita Maji
   :prerequisites:
   :topic: NP-completeness

.. odsalink:: AV/Development/NP/hamiltonianCycleCON.css

The Hamiltonian Cycle Problem
=============================

HAMILTONIAN CYCLE PROBLEM.

.. inlineav:: hamiltonianCycleCON ss
   :output: show

Try out an instance of the Hamiltonian Cycle problem on your own.

.. avembed:: Exercises/Development/hamiltonianCycle_KA.html ka

.. odsascript:: AV/Development/NP/hamiltonianCycleCON.js


text:
package org.gradoop.flink.model.impl.operators.sampling.functions;

import org.apache.flink.api.common.functions.FilterFunction;
import org.gradoop.common.model.impl.pojo.Vertex;
import org.gradoop.flink.model.impl.operators.sampling.PageRankSampling;

/**
 * Retains all vertices with a PageRank-score greater or equal/smaller than a given
 * sampling threshold - depending on the Boolean set in {@code sampleGreaterThanThreshold}.
 */
public class PageRankResultVertexFilter implements FilterFunction<Vertex> {

  /**
   * Sampling threshold for PageRankScore
   */
  private final double threshold;
  /**
   * Whether to sample vertices with PageRank-score greater (true) or equal/smaller (false)
   * the threshold
   */
  private final boolean sampleGreaterThanThreshold;
  /**
   * Whether to sample all vertices (true) or none of them (false), in case all vertices got the
   * same PageRank-score.
   */
  private final boolean keepVerticesIfSameScore;

  /**
   * Creates a new filter instance.
   *
   * @param threshold The threshold for the PageRank-score (ranging between 0 and 1 when scaled),
   *                  determining if a vertex is sampled, e.g. 0.5
   * @param sampleGreaterThanThreshold Whether to sample vertices with PageRank-score
   *                                   greater (true) or equal/smaller (false) the threshold
   * @param keepVerticesIfSameScore Whether to sample all vertices (true) or none of them (false)
   *                                in case all vertices got the same PageRank-score.
   */
  public PageRankResultVertexFilter(double threshold, boolean sampleGreaterThanThreshold,
    boolean keepVerticesIfSameScore) {
    this.threshold = threshold;
    this.sampleGreaterThanThreshold = sampleGreaterThanThreshold;
    this.keepVerticesIfSameScore = keepVerticesIfSameScore;
  }

  @Override
  public boolean filter(Vertex v) throws Exception {
    if (v.hasProperty(PageRankSampling.SCALED_PAGE_RANK_SCORE_PROPERTY_KEY)) {
      double pr = v.getPropertyValue(PageRankSampling.SCALED_PAGE_RANK_SCORE_PROPERTY_KEY)
        .getDouble();
      if (sampleGreaterThanThreshold) {
        return pr > threshold;
      } else {
        return pr <= threshold;
      }
    } else {
      return keepVerticesIfSameScore;
    }
  }
}


text:
use crate::ImlSfaError;
use async_trait::async_trait;
use futures::{future, TryFutureExt};
use iml_wire_types::sfa::wbem_interop::{
    SfaController, SfaDiskDrive, SfaEnclosure, SfaJob, SfaPowerSupply, SfaStorageSystem,
};
use std::convert::TryInto as _;
use url::Url;
use wbem_client::{resp::Instance, Client, ClientExt};

#[async_trait(?Send)]
pub trait SfaClassExt: ClientExt {
    async fn fetch_sfa_storage_system(&self, url: Url) -> Result<SfaStorageSystem, ImlSfaError>;
    async fn fetch_sfa_enclosures(&self, url: Url) -> Result<Vec<SfaEnclosure>, ImlSfaError>;
    async fn fetch_sfa_disk_drives(&self, url: Url) -> Result<Vec<SfaDiskDrive>, ImlSfaError>;
    async fn fetch_sfa_jobs(&self, url: Url) -> Result<Vec<SfaJob>, ImlSfaError>;
    async fn fetch_sfa_power_supply(&self, url: Url) -> Result<Vec<SfaPowerSupply>, ImlSfaError>;
    async fn fetch_sfa_controllers(&self, url: Url) -> Result<Vec<SfaController>, ImlSfaError>;
}

#[async_trait(?Send)]
impl SfaClassExt for Client {
    async fn fetch_sfa_storage_system(&self, url: Url) -> Result<SfaStorageSystem, ImlSfaError> {
        let x = self
            .get_instance(url, "root/ddn", "DDN_SFAStorageSystem")
            .await?;

        let x: SfaStorageSystem = x.try_into()?;

        Ok(x)
    }
    async fn fetch_sfa_enclosures(&self, url: Url) -> Result<Vec<SfaEnclosure>, ImlSfaError> {
        let x = self.fetch_sfa_storage_system(url.clone());

        let ys = self
            .enumerate_instances(url, "root/ddn", "DDN_SFAEnclosure")
            .err_into();

        let (x, ys) = future::try_join(x, ys).await?;

        let ys = Vec::<Instance>::from(ys)
            .into_iter()
            .map(|y| (x.uuid.clone(), y).try_into())
            .collect::<Result<Vec<_>, _>>()?;

        Ok(ys)
    }
    async fn fetch_sfa_disk_drives(&self, url: Url) -> Result<Vec<SfaDiskDrive>, ImlSfaError> {
        let x = self.fetch_sfa_storage_system(url.clone());

        let ys = self
            .enumerate_instances(url, "root/ddn", "DDN_SFADiskDrive")
            .err_into();

        let (x, ys) = future::try_join(x, ys).await?;

        let ys = Vec::<Instance>::from(ys)
            .into_iter()
            .map(|y| (x.uuid.clone(), y).try_into())
            .collect::<Result<Vec<_>, _>>()?;

        Ok(ys)
    }
    async fn fetch_sfa_jobs(&self, url: Url) -> Result<Vec<SfaJob>, ImlSfaError> {
        let x = self.fetch_sfa_storage_system(url.clone());

        let ys = self
            .enumerate_instances(url, "root/ddn", "DDN_SFAJob")
            .err_into();

        let (x, ys) = future::try_join(x, ys).await?;

        let ys = Vec::<Instance>::from(ys)
            .into_iter()
            .map(|y| (x.uuid.clone(), y).try_into())
            .collect::<Result<Vec<_>, _>>()?;

        Ok(ys)
    }
    async fn fetch_sfa_power_supply(&self, url: Url) -> Result<Vec<SfaPowerSupply>, ImlSfaError> {
        let x = self.fetch_sfa_storage_system(url.clone());

        let ys = self
            .enumerate_instances(url, "root/ddn", "DDN_SFAPowerSupply")
            .err_into();

        let (x, ys) = future::try_join(x, ys).await?;

        let ys = Vec::<Instance>::from(ys)
            .into_iter()
            .map(|y| (x.uuid.clone(), y).try_into())
            .collect::<Result<Vec<_>, _>>()?;

        Ok(ys)
    }
    async fn fetch_sfa_controllers(&self, url: Url) -> Result<Vec<SfaController>, ImlSfaError> {
        let x = self.fetch_sfa_storage_system(url.clone());

        let ys = self
            .enumerate_instances(url, "root/ddn", "DDN_SFAController")
            .err_into();

        let (x, ys) = future::try_join(x, ys).await?;

        let ys = Vec::<Instance>::from(ys)
            .into_iter()
            .map(|y| (x.uuid.clone(), y).try_into())
            .collect::<Result<Vec<_>, _>>()?;

        Ok(ys)
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
<title>TestDurability xref</title>
<link type="text/css" rel="stylesheet" href="../../../../../../stylesheet.css" />

1
18
19  package org.apache.hadoop.hbase.regionserver.wal;
20
21  import static org.junit.Assert.*;
22
23  import java.io.IOException;
24  import java.util.List;
25
26  import org.apache.hadoop.conf.Configuration;
27  import org.apache.hadoop.fs.FileSystem;
28  import org.apache.hadoop.fs.Path;
29  import org.apache.hadoop.hbase.HBaseConfiguration;
30  import org.apache.hadoop.hbase.HBaseTestingUtility;
31  import org.apache.hadoop.hbase.HColumnDescriptor;
32  import org.apache.hadoop.hbase.HRegionInfo;
33  import org.apache.hadoop.hbase.HTableDescriptor;
34  import org.apache.hadoop.hbase.MediumTests;
35  import org.apache.hadoop.hbase.client.Durability;
36  import org.apache.hadoop.hbase.client.Put;
37  import org.apache.hadoop.hbase.regionserver.HRegion;
38  import org.apache.hadoop.hbase.util.Bytes;
39  import org.apache.hadoop.hdfs.MiniDFSCluster;
40  import org.junit.AfterClass;
41  import org.junit.BeforeClass;
42  import org.junit.Test;
43  import org.junit.experimental.categories.Category;
44
45  /**
46   * Tests for HLog write durability
47   */
48  @Category(MediumTests.class)
49  public class TestDurability {
50    private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
51    private static FileSystem FS;
52    private static MiniDFSCluster CLUSTER;
53    private static Configuration CONF;
54    private static final Path DIR = TEST_UTIL.getDataTestDir("TestDurability");
55
56    private static byte[] FAMILY = Bytes.toBytes("family");
57    private static byte[] ROW = Bytes.toBytes("row");
58    private static byte[] COL = Bytes.toBytes("col");
59
60
61    @BeforeClass
62    public static void setUpBeforeClass() throws Exception {
63      CONF = TEST_UTIL.getConfiguration();
64      CONF.setLong("hbase.regionserver.optionallogflushinterval", 500*1000);
65      TEST_UTIL.startMiniDFSCluster(1);
66
67      CLUSTER = TEST_UTIL.getDFSCluster();
68      FS = CLUSTER.getFileSystem();
69    }
70
71    @AfterClass
72    public static void tearDownAfterClass() throws Exception {
73      TEST_UTIL.shutdownMiniCluster();
74    }
75
76    @Test
77    public void testDurability() throws Exception {
78      HLog wal = new HLog(FS, new Path(DIR, "hlogdir"),
79          new Path(DIR, "hlogdir_archive"), CONF);
80      byte[] tableName = Bytes.toBytes("TestDurability");
81      HRegion region = createHRegion(tableName, "region", wal, false);
82      HRegion deferredRegion = createHRegion(tableName, "deferredRegion", wal, true);
83
84      region.put(newPut(null));
85
86      verifyHLogCount(wal, 1);
87
88      // a put through the deferred table does not write to the wal immdiately
89      deferredRegion.put(newPut(null));
90      verifyHLogCount(wal, 1);
91      // but will after we sync the wal
92      wal.sync();
93      verifyHLogCount(wal, 2);
94
95      // a put through a deferred table will be sync with the put sync'ed put
96      deferredRegion.put(newPut(null));
97      verifyHLogCount(wal, 2);
98      region.put(newPut(null));
99      verifyHLogCount(wal, 4);
100
101     // a put through a deferred table will be sync with the put sync'ed put
102     deferredRegion.put(newPut(Durability.USE_DEFAULT));
103     verifyHLogCount(wal, 4);
104     region.put(newPut(Durability.USE_DEFAULT));
105     verifyHLogCount(wal, 6);
106
107     // SKIP_WAL never writes to the wal
108     region.put(newPut(Durability.SKIP_WAL));
109     deferredRegion.put(newPut(Durability.SKIP_WAL));
110     verifyHLogCount(wal, 6);
111     wal.sync();
112     verifyHLogCount(wal, 6);
113
114     // async overrides sync table default
115     region.put(newPut(Durability.ASYNC_WAL));
116     deferredRegion.put(newPut(Durability.ASYNC_WAL));
117     verifyHLogCount(wal, 6);
118     wal.sync();
119     verifyHLogCount(wal, 8);
120
121     // sync overrides async table default
122     region.put(newPut(Durability.SYNC_WAL));
123     deferredRegion.put(newPut(Durability.SYNC_WAL));
124     verifyHLogCount(wal, 10);
125
126     // fsync behaves like sync
127     region.put(newPut(Durability.FSYNC_WAL));
128     deferredRegion.put(newPut(Durability.FSYNC_WAL));
129     verifyHLogCount(wal, 12);
130   }
131
132   private Put[] newPut(Durability durability) {
133     Put p = new Put(ROW);
134     p.add(FAMILY, COL, COL);
135     if (durability != null) {
136       p.setDurability(durability);
137     }
138     return new Put[]{p};
139   }
140
141   private void verifyHLogCount(HLog log, int expected) throws Exception {
142     Path walPath = log.computeFilename();
143     HLog.Reader reader = HLog.getReader(FS, walPath, CONF);
144     int count = 0;
145     HLog.Entry entry = new HLog.Entry();
146     while (reader.next(entry) != null) count++;
147     reader.close();
148     assertEquals(expected, count);
149   }
150
151   // lifted from TestAtomicOperation
152   private HRegion createHRegion (byte [] tableName, String callingMethod, HLog log, boolean isDeferredLogFlush)
153     throws IOException {
154       HTableDescriptor htd = new HTableDescriptor(tableName);
155       htd.setDeferredLogFlush(isDeferredLogFlush);
156       HColumnDescriptor hcd = new HColumnDescriptor(FAMILY);
157       htd.addFamily(hcd);
158       HRegionInfo info = new HRegionInfo(htd.getName(), null, null, false);
159       Path path = new Path(DIR + callingMethod);
160       if (FS.exists(path)) {
161         if (!FS.delete(path, true)) {
162           throw new IOException("Failed delete of " + path);
163         }
164       }
165       return HRegion.createHRegion(info, path, HBaseConfiguration.create(), htd, log);
166     }
167
168 }

This page was automatically generated by Maven


text:
package lab.s2jh.sys.entity;

import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

/**
 * @see http://logback.qos.ch/manual/configuration.html #DBAppender
 */
@Entity
@Table(name = "logging_event_property")
@Cache(usage = CacheConcurrencyStrategy.NONE)
public class LoggingEventProperty implements java.io.Serializable {

    private LoggingEventPropertyId id;
    private LoggingEvent loggingEvent;
    private String mappedValue;

    @EmbeddedId
    @AttributeOverrides({
            @AttributeOverride(name = "eventId", column = @Column(name = "event_id", nullable = false)),
            @AttributeOverride(name = "mappedKey", column = @Column(name = "mapped_key", nullable = false, length = 254)) })
    public LoggingEventPropertyId getId() {
        return this.id;
    }

    public void setId(LoggingEventPropertyId id) {
        this.id = id;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "event_id", nullable = false, insertable = false, updatable = false)
    public LoggingEvent getLoggingEvent() {
        return this.loggingEvent;
    }

    public void setLoggingEvent(LoggingEvent loggingEvent) {
        this.loggingEvent = loggingEvent;
    }

    @Lob
    @Column(name = "mapped_value")
    public String getMappedValue() {
        return this.mappedValue;
    }

    public void setMappedValue(String mappedValue) {
        this.mappedValue = mappedValue;
    }

}


text:
layout: global
displayTitle: Use Cases
title: Use Cases
description: Gearpump Use Cases
---

Gearpump is a primary component of Intel's [TAP](https://trustedanalytics.org).
Several key use cases covering involving both IoT and Analytics are being developed

1.  [Levi's and RFID](http://www.retaildive.com/news/levis-taps-into-massive-amounts-of-store-data-with-intel-tech/408600/)
2.  [Honeywell and wearable sensors](https://www.honeywellfirstresponder.com/en-us/Pages/default.aspx)


text:
<?php
namespace Maria;

use Arc\Core\Route\Dispatcher;

require ROOT . 'vendor/autoload.php';

$environment = 'development';

/**
 * Register Flip\Whoops error handler
 */
$whoops = new \Whoops\Run;
if($environment === 'development') {
    error_reporting(E_ALL);
    ini_set('display_errors', "1");

    $whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler);
} else {
    error_reporting(~E_ALL);
    ini_set('display_errors', "0");

    $whoops->pushHandler(function ($ex) {
        echo 'There has been an error. Please try again or contact purwinr@gmail.com';
        \Arc\Helpers\Logger::exception($ex);
    });
}
$whoops->register();

$injector = include('dependencies.php');
$request = $injector->make('Http\HttpRequest');
$response = $injector->make('Http\HttpResponse');
$session = $injector->make('Arc\Helpers\Session');
$session->start();

$routeCollector = $injector->make('FastRoute\RouteCollector');
$routes = include('routes.php');

$user = $injector->make('Maria\Helpers\User');
if($user->isAdminLogged() && $user->isAuthorized()) {
    $adminRoutes = include('routes_admin.php');
    $routes = array_merge($routes, $adminRoutes);
}
foreach ($routes as $route) {
    $routeCollector->addRoute($route[0], $route[1], $route[2]);
}

$injector->define('Arc\Core\Route\Dispatcher', [
    ':routes' => $routeCollector->getData()
]);

$dispatcher = $injector->make('Arc\Core\Route\Dispatcher');
$routeInfo = $dispatcher->dispatch($request->getMethod(), $request->getPath());
$renderer = $injector->make('Arc\Template\Renderer');

switch ($routeInfo[0]) {
    case \FastRoute\Dispatcher::NOT_FOUND:
        $notFoundHtml = $renderer->render('page/error/404');
        $response->setContent($notFoundHtml);
        $response->setStatusCode(404);
        break;
    case \FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
        $methodNotAllowed = $renderer->render('page/error/405');
        $response->setContent($methodNotAllowed);
        $response->setStatusCode(405);
        break;
    case \FastRoute\Dispatcher::FOUND:
        $className = $routeInfo[1][0];
        $method = $routeInfo[1][1];
        $vars = $routeInfo[2];

        $class = $injector->make($className);
        $class->$method($vars);
        break;
}

foreach ($response->getHeaders() as $header) {
    header($header, false);
}

echo $response->getContent();


text:
/**
 *
 */
package com.android.aid;

import android.content.Context;

/**
 * @author wangpeifeng
 *
 */
public class DBSchemaReportAppGroup extends DBSchemaReport {

	public DBSchemaReportAppGroup(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	@Override
	protected String getSchemaName() {
		// TODO Auto-generated method stub
		return "app_group_report";
	}

	@Override
	protected String getUpdateSQL(int updateVersion) {
		// TODO Auto-generated method stub
		return null;
	}

}


text:
A nice and easy way to get a Minecraft server up and running using docker. For
help on getting started with docker see the [official getting started guide][0].
For more information on Minecraft and check out it's [website][1].

## Building docker-minecraft

Running this will build you a docker image with the latest version of both
docker-minecraft and Minecraft itself.

    git clone https://github.com/idxbroker/docker-minecraft
    cd docker-minecraft
    sudo docker build -t idxbroker/minecraft .

## Running docker-minecraft

Running the first time will set your port to a static port of your choice so
that you can easily map a proxy to. If this is the only thing running on your
system you can map the port to 25565 and no proxy is needed. i.e.
`-p=25565:25565` . If you want to enable the query protocol you need
to add another -p=25565:25565/udp to forward the UDP protocol on the
same port as well.
Also be sure your mounted directory on your host machine is
already created before running `mkdir -p /mnt/minecraft`.

    sudo docker run -d=true -p=25565:25565 -v=/mnt/minecraft:/data idxbroker/minecraft /start

From now on when you start/stop docker-minecraft you should use the container id
with the following commands. To get your container id, after you initial run
type `sudo docker ps` and it will show up on the left side followed by the
image name which is `idxbroker/minecraft:latest`.

    sudo docker start <container_id>
    sudo docker stop <container_id>

### Notes on the run command

 + `-v` is the volume you are mounting `-v=host_dir:docker_dir`
 + `idxbroker/minecraft` is simply what I called my docker build of this image
 + `-d=true` allows this to run cleanly as a daemon, remove for debugging
 + `-p` is the port it connects to, `-p=host_port:docker_port`

## Connecting to the minecraft server console

To do this in a convenient way you should install a application called
[nsenter][3] and some conviniet helper scripts.
If you want to install nsenter to your /usr/local/bin, just do this:

    docker run --rm -v /usr/local/bin:/target jpetazzo/nsenter

This will actually create a docker machine for you where the command is
being built. If that sounds to scary read the instructions on the webpage.

After installing you will have a script called docker-enter that uses
nsenter which lets you connect to a live container and run commands.
Since we are using supervisor to run the server we will connect to
supervisorctl and from there do whats needed like restarting,
connecting to the shell etc.

To use docker-enter you will need the name of the container.

    sudo docker-enter my_awesome_container supervisorctl

Now you will be able to control the supervisor process that is previously
defined and called minecraft.

To connect to the shell of the server just type.

    fg minecraft

Now you are able to control the server just like normally.
When you are done, just press Ctrl+c to send it to the background again.

To disconnect from supervisorctl just type `exit` and press enter.
Now you are disconnected from the container as well.

[0]: http://www.docker.io/gettingstarted/
[1]: http://minecraft.net/
[3]: https://github.com/jpetazzo/nsenter


text:
This section explains the [`ConnectableObservable`](http://reactivex.io/RxJava/javadoc/rx/observables/ConnectableObservable.html) subclass and its operators:

* [**`ConnectableObservable.connect( )`**](http://reactivex.io/documentation/operators/connect.html) — instructs a Connectable Observable to begin emitting items
* [**`Observable.publish( )`**](http://reactivex.io/documentation/operators/publish.html) — represents an Observable as a Connectable Observable
* [**`Observable.replay( )`**](http://reactivex.io/documentation/operators/replay.html) — ensures that all Subscribers see the same sequence of emitted items, even if they subscribe after the Observable begins emitting the items
* [**`ConnectableObservable.refCount( )`**](http://reactivex.io/documentation/operators/refcount.html) — makes a Connectable Observable behave like an ordinary Observable

A Connectable Observable resembles an ordinary Observable, except that it does not begin emitting items when it is subscribed to, but only when its `connect()` method is called. In this way you can wait for all intended Subscribers to subscribe to the Observable before the Observable begins emitting items.

The following example code shows two Subscribers subscribing to the same Observable. In the first case, they subscribe to an ordinary Observable; in the second case, they subscribe to a Connectable Observable that only connects after both Subscribers subscribe. Note the difference in the output:

**Example #1:**
```groovy
def firstMillion  = Observable.range( 1, 1000000 ).sample(7, java.util.concurrent.TimeUnit.MILLISECONDS);

firstMillion.subscribe(
   { println("Subscriber #1:" + it); },       // onNext
   { println("Error: " + it.getMessage()); }, // onError
   { println("Sequence #1 complete"); }       // onCompleted
);

firstMillion.subscribe(
    { println("Subscriber #2:" + it); },       // onNext
    { println("Error: " + it.getMessage()); }, // onError
    { println("Sequence #2 complete"); }       // onCompleted
);
```
```
Subscriber #1:211128
Subscriber #1:411633
Subscriber #1:629605
Subscriber #1:841903
Sequence #1 complete
Subscriber #2:244776
Subscriber #2:431416
Subscriber #2:621647
Subscriber #2:826996
Sequence #2 complete
```
**Example #2:**
```groovy
def firstMillion  = Observable.range( 1, 1000000 ).sample(7, java.util.concurrent.TimeUnit.MILLISECONDS).publish();

firstMillion.subscribe(
   { println("Subscriber #1:" + it); },       // onNext
   { println("Error: " + it.getMessage()); }, // onError
   { println("Sequence #1 complete"); }       // onCompleted
);

firstMillion.subscribe(
   { println("Subscriber #2:" + it); },       // onNext
   { println("Error: " + it.getMessage()); }, // onError
   { println("Sequence #2 complete"); }       // onCompleted
);

firstMillion.connect();
```
```
Subscriber #2:208683
Subscriber #1:208683
Subscriber #2:432509
Subscriber #1:432509
Subscriber #2:644270
Subscriber #1:644270
Subscriber #2:887885
Subscriber #1:887885
Sequence #2 complete
Sequence #1 complete
```

#### see also:
* javadoc: `ConnectableObservable`
* Introduction to Rx: Publish and Connect


text:
require 'test_helper'

class ValidationTest < ActiveSupport::TestCase
  setup do
    User.reset_callbacks(:validate)
    User._validators.clear
  end

  test 'no validation' do
    assert User.new.valid?
  end

  sub_test_case 'without attributes' do
    test 'without options' do
      User.validates do
        presence_of :name
      end

      user = User.new
      refute user.valid?
      assert_equal 1, user.errors.count
      assert_equal 1, user.errors[:name].count
    end

    test 'with an option' do
      User.validates do
        numericality_of :age, greater_than: 0
      end

      user = User.new age: -1
      refute user.valid?
      assert_equal 1, user.errors.count
      assert_equal 1, user.errors[:age].count
    end
  end

  sub_test_case 'with an attribute' do
    test 'without options' do
      User.validates :email do
        presence
      end

      user = User.new
      refute user.valid?
      assert_equal 1, user.errors.count
      assert_equal 1, user.errors[:email].count
    end

    test 'with an option' do
      User.validates :age do
        numericality greater_than: 0
      end

      user = User.new age: -1
      refute user.valid?
      assert_equal 1, user.errors.count
      assert_equal 1, user.errors[:age].count
    end
  end

  test 'mixtures' do
    User.class_eval do
      validates :email do
        size maximum: 100
        format with: /@/
      end
      validates :name, :age do
        presence
      end
    end

    user = User.new email: 'a' * 101
    refute user.valid?
    assert_equal 4, user.errors.count
    assert_equal 2, user.errors[:email].count
    assert_equal 1, user.errors[:name].count
    assert_equal 1, user.errors[:age].count
  end
end


text:
package com.yw.fastviewlibrary.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by heinigger on 2017/4/26.
 */

public class ProgressView extends View {

    private Paint mPaint;
    //进度的颜色
    private int mProgressColor = Color.RED;
    //默认的颜色
    private int defaultColor = Color.DKGRAY;
    private int progress = 50;

    private int TOTALSIZE = 100;

    public ProgressView(Context context) {
        this(context, null);
    }

    public ProgressView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ProgressView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        iniPaint();
    }

    private void iniPaint() {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
        mPaint.setColor(defaultColor);
    }

    public void setProgress(int progress) {
        this.progress = progress;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mPaint.setColor(defaultColor);
        canvas.drawRoundRect(new RectF(0, 0, getWidth(), getMeasuredHeight()), getMeasuredWidth() / 2, getMeasuredWidth() / 2, mPaint);
        mPaint.setColor(mProgressColor);
        canvas.drawRoundRect(new RectF(0, 0, getWidth() * (progress / (float) TOTALSIZE), getMeasuredHeight()), getMeasuredWidth() / 2, getMeasuredWidth() / 2, mPaint);
    }
}


text:
class ErrorPageTest : public UITest {
 protected:
  bool WaitForTitleMatching(const std::wstring& title) {
    for (int i = 0; i < 10; ++i) {
      if (GetActiveTabTitle() == title)
        return true;
      base::PlatformThread::Sleep(TestTimeouts::action_timeout_ms());
    }
    EXPECT_EQ(title, GetActiveTabTitle());
    return false;
  }
};

TEST_F(ErrorPageTest, DNSError_Basic) {
  GURL test_url(URLRequestFailedDnsJob::kTestUrl);

  // The first navigation should fail, and the second one should be the error
  // page.
  NavigateToURLBlockUntilNavigationsComplete(test_url, 2);

  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
}

TEST_F(ErrorPageTest, DNSError_GoBack1) {
  // Test that a DNS error occuring in the main frame does not result in an
  // additional session history entry.
  GURL test_url(URLRequestFailedDnsJob::kTestUrl);

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));
  // The first navigation should fail, and the second one should be the error
  // page.
  NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));

  EXPECT_TRUE(GetActiveTab()->GoBack());

  EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}

// Flaky on Linux, see http://crbug.com/19361
#if defined(OS_LINUX)
#define MAYBE_DNSError_GoBack2 FLAKY_DNSError_GoBack2
#else
#define MAYBE_DNSError_GoBack2 DNSError_GoBack2
#endif
TEST_F(ErrorPageTest, MAYBE_DNSError_GoBack2) {
  // Test that a DNS error occuring in the main frame does not result in an
  // additional session history entry.
  GURL test_url(URLRequestFailedDnsJob::kTestUrl);

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));
  // The first navigation should fail, and the second one should be the error
  // page.
  NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title3.html"))));

  // The first navigation should fail, and the second one should be the error
  // page.
  EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  EXPECT_TRUE(GetActiveTab()->GoBack());

  EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}

// Flaky on Linux, see http://crbug.com/19361
#if defined(OS_LINUX)
#define MAYBE_DNSError_GoBack2AndForward FLAKY_DNSError_GoBack2AndForward
#else
#define MAYBE_DNSError_GoBack2AndForward DNSError_GoBack2AndForward
#endif
TEST_F(ErrorPageTest, MAYBE_DNSError_GoBack2AndForward) {
  // Test that a DNS error occuring in the main frame does not result in an
  // additional session history entry.

  GURL test_url(URLRequestFailedDnsJob::kTestUrl);

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));
  // The first navigation should fail, and the second one should be the error
  // page.
  NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title3.html"))));

  // The first navigation should fail, and the second one should be the error
  // page.
  EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  EXPECT_TRUE(GetActiveTab()->GoBack());
  // The first navigation should fail, and the second one should be the error
  // page.
  EXPECT_TRUE(GetActiveTab()->GoForwardBlockUntilNavigationsComplete(2));

  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
}

// Flaky on Linux, see http://crbug.com/19361
#if defined(OS_LINUX)
#define MAYBE_DNSError_GoBack2Forward2 FLAKY_DNSError_GoBack2Forward2
#else
#define MAYBE_DNSError_GoBack2Forward2 DNSError_GoBack2Forward2
#endif
TEST_F(ErrorPageTest, MAYBE_DNSError_GoBack2Forward2) {
  // Test that a DNS error occuring in the main frame does not result in an
  // additional session history entry.

  GURL test_url(URLRequestFailedDnsJob::kTestUrl);

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title3.html"))));
  // The first navigation should fail, and the second one should be the error
  // page.
  NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));

  // The first navigation should fail, and the second one should be the error
  // page.
  EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  EXPECT_TRUE(GetActiveTab()->GoBack());
  // The first navigation should fail, and the second one should be the error
  // page.
  EXPECT_TRUE(GetActiveTab()->GoForwardBlockUntilNavigationsComplete(2));
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  EXPECT_TRUE(GetActiveTab()->GoForward());

  EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}

TEST_F(ErrorPageTest, IFrameDNSError_Basic) {
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));
  EXPECT_TRUE(WaitForTitleMatching(L"Blah"));
}

TEST_F(ErrorPageTest, IFrameDNSError_GoBack) {
  // Test that a DNS error occuring in an iframe does not result in an
  // additional session history entry.

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));

  EXPECT_TRUE(GetActiveTab()->GoBack());

  EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}

TEST_F(ErrorPageTest, IFrameDNSError_GoBackAndForward) {
  // Test that a DNS error occuring in an iframe does not result in an
  // additional session history entry.

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));

  EXPECT_TRUE(GetActiveTab()->GoBack());
  EXPECT_TRUE(GetActiveTab()->GoForward());

  EXPECT_TRUE(WaitForTitleMatching(L"Blah"));
}

// Checks that the Link Doctor is not loaded when we receive an actual 404 page.
TEST_F(ErrorPageTest, Page404) {
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("page404.html"))));

  EXPECT_TRUE(WaitForTitleMatching(L"SUCCESS"));
}


text:
__all__ = ['image_mutual_information']

from .. import utils

def image_mutual_information(image1, image2):
    """
    Compute mutual information between two ANTsImage types

    ANTsR function: `antsImageMutualInformation`

    Arguments
    ---------
    image1 : ANTsImage
        image 1

    image2 : ANTsImage
        image 2

    Returns
    -------
    scalar

    Example
    -------
    >>> import ants
    >>> fi = ants.image_read( ants.get_ants_data('r16') ).clone('float')
    >>> mi = ants.image_read( ants.get_ants_data('r64') ).clone('float')
    >>> mival = ants.image_mutual_information(fi, mi) # -0.1796141
    """
    if (image1.pixeltype != 'float') or (image2.pixeltype != 'float'):
        raise ValueError('Both images must have float pixeltype')

    if image1.dimension != image2.dimension:
        raise ValueError('Both images must have same dimension')

    libfn = utils.get_lib_fn('antsImageMutualInformation%iD' % image1.dimension)
    return libfn(image1.pointer, image2.pointer)


text:
/*
 * Decompiled with CFR 0_79.
 *
 * Could not load the following classes:
 *  android.app.Activity
 *  android.content.Context
 *  android.content.Intent
 *  android.net.Uri
 *  android.os.Bundle
 *  android.view.View
 *  android.view.View$OnClickListener
 *  android.view.Window
 *  android.widget.Button
 */
package com.SixClawWorm.application;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import com.SixClawWorm.application.inTrodutionActivity;
import com.SixClawWorm.utils.ExitApplication;

public class aboutActivity
extends Activity {
    private Button Mlayer;
    private Button Myt_Btn;
    private Button about_logoBtn;
    private Button backBtn;
    private Button facebook_Btn;
    private Button mtwitter_button;
    private Button wow_Btn;

    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        this.requestWindowFeature(1);
        this.getWindow().setFlags(1024, 1024);
        this.setContentView(2130903040);
        ExitApplication.getInstance().addActivity((Activity)this);
        this.backBtn = (Button)this.findViewById(2131099650);
        this.backBtn.setOnClickListener((View.OnClickListener)new View.OnClickListener(){

            public void onClick(View view) {
                aboutActivity.this.finish();
            }
        });
        this.Mlayer = (Button)this.findViewById(2131099649);
        this.Mlayer.setOnClickListener((View.OnClickListener)new View.OnClickListener(){

            public void onClick(View view) {
                Intent intent = new Intent((Context)aboutActivity.this, (Class)inTrodutionActivity.class);
                aboutActivity.this.startActivity(intent);
            }
        });
        this.wow_Btn = (Button)this.findViewById(2131099651);
        this.wow_Btn.setOnClickListener((View.OnClickListener)new View.OnClickListener(){

            public void onClick(View view) {
                Uri uri = Uri.parse((String)"http://www.WowStuff.com");
                aboutActivity.this.startActivity(new Intent("android.intent.action.VIEW", uri));
            }
        });
        this.facebook_Btn = (Button)this.findViewById(2131099652);
        this.facebook_Btn.setOnClickListener((View.OnClickListener)new View.OnClickListener(){

            public void onClick(View view) {
                Uri uri = Uri.parse((String)"http://www.Facebook.com/CombatCreatures");
                aboutActivity.this.startActivity(new Intent("android.intent.action.VIEW", uri));
            }
        });
        this.mtwitter_button = (Button)this.findViewById(2131099653);
        this.mtwitter_button.setOnClickListener((View.OnClickListener)new View.OnClickListener(){

            public void onClick(View view) {
                Uri uri = Uri.parse((String)"http://www.Twitter.com/CombatCreatures");
                aboutActivity.this.startActivity(new Intent("android.intent.action.VIEW", uri));
            }
        });
        this.Myt_Btn = (Button)this.findViewById(2131099654);
        this.Myt_Btn.setOnClickListener((View.OnClickListener)new View.OnClickListener(){

            public void onClick(View view) {
                Uri uri = Uri.parse((String)"http://www.YouTube.com/WowStuffOnline");
                aboutActivity.this.startActivity(new Intent("android.intent.action.VIEW", uri));
            }
        });
        this.about_logoBtn = (Button)this.findViewById(2131099648);
        this.about_logoBtn.setOnClickListener((View.OnClickListener)new View.OnClickListener(){

            public void onClick(View view) {
                Uri uri = Uri.parse((String)"http://www.CombatCreatures.com");
                aboutActivity.this.startActivity(new Intent("android.intent.action.VIEW", uri));
            }
        });
    }

}


text:
<?php

/**
 * adminPassenger actions.
 *
 * @package    sf_sandbox
 * @subpackage adminPassenger
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class adminPassengerActions extends sfActions
{
  public function executeIndex(sfWebRequest $request)
  {
    $this->aoi_passengers = Doctrine_Core::getTable('AoiPassenger')
      ->createQuery('a')
      ->execute();
  }

  public function executeNew(sfWebRequest $request)
  {
    $this->form = new AoiPassengerForm();
  }

  public function executeCreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));

    $this->form = new AoiPassengerForm();

    $this->processForm($request, $this->form);

    $this->setTemplate('new');
  }

  public function executeEdit(sfWebRequest $request)
  {
    $this->forward404Unless($aoi_passenger = Doctrine_Core::getTable('AoiPassenger')->find(array($request->getParameter('id'))), sprintf('Object aoi_passenger does not exist (%s).', $request->getParameter('id')));
    $this->form = new AoiPassengerForm($aoi_passenger);
  }

  public function executeUpdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($aoi_passenger = Doctrine_Core::getTable('AoiPassenger')->find(array($request->getParameter('id'))), sprintf('Object aoi_passenger does not exist (%s).', $request->getParameter('id')));
    $this->form = new AoiPassengerForm($aoi_passenger);

    $this->processForm($request, $this->form);

    $this->setTemplate('edit');
  }

  public function executeDelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();

    $this->forward404Unless($aoi_passenger = Doctrine_Core::getTable('AoiPassenger')->find(array($request->getParameter('id'))), sprintf('Object aoi_passenger does not exist (%s).', $request->getParameter('id')));
    $aoi_passenger->delete();

    $this->redirect('adminPassenger/index');
  }

  protected function processForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $aoi_passenger = $form->save();

      $this->redirect('adminPassenger/edit?id='.$aoi_passenger->getId());
    }
  }
}