text:
#include "tensorflow/core/platform/cloud/http_request.h"

#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/gtl/map_util.h"
#include "tensorflow/core/lib/strings/scanner.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/public/version.h"

namespace tensorflow {

namespace {

// Windows is not currently supported.
constexpr char kCurlLibLinux[] = "libcurl.so.3";
constexpr char kCurlLibMac[] = "/usr/lib/libcurl.3.dylib";

constexpr char kCertsPath[] = "/etc/ssl/certs";

// Set to 1 to enable verbose debug output from curl.
constexpr uint64 kVerboseOutput = 0;

// Timeout for the whole request. Set only to prevent hanging indefinitely.
constexpr uint32 kRequestTimeoutSeconds = 3600;  // 1 hour
// Timeout for the connection phase.
constexpr uint32 kConnectTimeoutSeconds = 120;  // 2 minutes

/// An implementation that dynamically loads libcurl and forwards calls to it.
class LibCurlProxy : public LibCurl {
 public:
  static LibCurlProxy* Load() {
    static LibCurlProxy* libcurl = []() -> LibCurlProxy* {
      std::unique_ptr<LibCurlProxy> libcurl(new LibCurlProxy);
      Status status = libcurl->LoadAndBind();
      if (!status.ok()) {
        return nullptr;
      }
      libcurl->curl_global_init_(CURL_GLOBAL_ALL);
      return libcurl.release();
    }();

    return libcurl;
  }

  CURL* curl_easy_init() override {
    return curl_easy_init_();
  }

  CURLcode curl_easy_setopt(CURL* curl, CURLoption option,
                            uint64 param) override {
    return curl_easy_setopt_(curl, option, param);
  }

  CURLcode curl_easy_setopt(CURL* curl, CURLoption option,
                            const char* param) override {
    return curl_easy_setopt_(curl, option, param);
  }
  CURLcode curl_easy_setopt(CURL* curl, CURLoption option,
                            void* param) override {
    return curl_easy_setopt_(curl, option, param);
  }
  CURLcode curl_easy_setopt(CURL* curl, CURLoption option,
                            size_t (*param)(void*, size_t, size_t,
                                            FILE*)) override {
    return curl_easy_setopt_(curl, option, param);
  }
  CURLcode curl_easy_setopt(CURL* curl, CURLoption option,
                            size_t (*param)(const void*, size_t, size_t,
                                            void*)) override {
    return curl_easy_setopt_(curl, option, param);
  }

  CURLcode curl_easy_perform(CURL* curl) override {
    return curl_easy_perform_(curl);
  }

  CURLcode curl_easy_getinfo(CURL* curl, CURLINFO info,
                             uint64* value) override {
    return curl_easy_getinfo_(curl, info, value);
  }
  CURLcode curl_easy_getinfo(CURL* curl, CURLINFO info,
                             double* value) override {
    return curl_easy_getinfo_(curl, info, value);
  }
  void curl_easy_cleanup(CURL* curl) override {
    return curl_easy_cleanup_(curl);
  }
  char* curl_easy_escape(CURL* curl, const char* str, int length) override {
    return curl_easy_escape_(curl, str, length);
  }

  curl_slist* curl_slist_append(curl_slist* list, const char* str) override {
    return curl_slist_append_(list, str);
  }

  void curl_slist_free_all(curl_slist* list) override {
    return curl_slist_free_all_(list);
  }

  void curl_free(void* p) override {
    curl_free_(p);
  }

 private:
  Status LoadAndBind() {
    auto TryLoadAndBind = [this](const char* name, void** handle) -> Status {
      TF_RETURN_IF_ERROR(Env::Default()->LoadLibrary(name, handle));
#define BIND_CURL_FUNC(function)                             \
  do {                                                       \
    void* symbol_ptr = nullptr;                              \
    TF_RETURN_IF_ERROR(Env::Default()->GetSymbolFromLibrary( \
        *handle, #function, &symbol_ptr));                   \
    *reinterpret_cast<void**>(&(function##_)) = symbol_ptr;  \
  } while (0)

      BIND_CURL_FUNC(curl_global_init);
      BIND_CURL_FUNC(curl_easy_init);
      BIND_CURL_FUNC(curl_easy_setopt);
      BIND_CURL_FUNC(curl_easy_perform);
      BIND_CURL_FUNC(curl_easy_getinfo);
      BIND_CURL_FUNC(curl_slist_append);
      BIND_CURL_FUNC(curl_slist_free_all);
      BIND_CURL_FUNC(curl_easy_cleanup);
      BIND_CURL_FUNC(curl_easy_escape);
      BIND_CURL_FUNC(curl_free);
#undef BIND_CURL_FUNC
      return Status::OK();
    };

    // This may have been linked statically; if curl_easy_init is in the
    // current binary, no need to search for a dynamic version.
    Status status = TryLoadAndBind(nullptr, &handle_);
    if (status.ok()) {
      return status;
    }
    status = TryLoadAndBind(kCurlLibLinux, &handle_);
    if (status.ok()) {
      return status;
    }
    return TryLoadAndBind(kCurlLibMac, &handle_);
  }

  void* handle_ = nullptr;
  CURLcode (*curl_global_init_)(int64) = nullptr;
  CURL* (*curl_easy_init_)(void) = nullptr;
  CURLcode (*curl_easy_setopt_)(CURL*, CURLoption, ...) = nullptr;
  CURLcode (*curl_easy_perform_)(CURL* curl) = nullptr;
  CURLcode (*curl_easy_getinfo_)(CURL* curl, CURLINFO info, ...) = nullptr;
  void (*curl_easy_cleanup_)(CURL* curl) = nullptr;
  curl_slist* (*curl_slist_append_)(curl_slist* list,
                                    const char* str) = nullptr;
  void (*curl_slist_free_all_)(curl_slist* list) = nullptr;
  char* (*curl_easy_escape_)(CURL* curl, const char* str, int length) = nullptr;
  void (*curl_free_)(void* p) = nullptr;
};
}  // namespace

HttpRequest::HttpRequest() : HttpRequest(LibCurlProxy::Load()) {}

HttpRequest::HttpRequest(LibCurl* libcurl)
    : libcurl_(libcurl),
      default_response_buffer_(new char[CURL_MAX_WRITE_SIZE]) {}

HttpRequest::~HttpRequest() {
  if (curl_headers_) {
    libcurl_->curl_slist_free_all(curl_headers_);
  }
  if (put_body_) {
    fclose(put_body_);
  }
  if (curl_) {
    libcurl_->curl_easy_cleanup(curl_);
  }
}

Status HttpRequest::Init() {
  if (is_initialized_) {
    return errors::FailedPrecondition("Already initialized.");
  }
  if (!libcurl_) {
    return errors::FailedPrecondition(
        "Could not initialize the libcurl library. Please make sure that "
        "libcurl is installed in the OS or statically linked to the "
        "TensorFlow binary.");
  }
  curl_ = libcurl_->curl_easy_init();
  if (!curl_) {
    return errors::Internal("Couldn't initialize a curl session.");
  }

  libcurl_->curl_easy_setopt(curl_, CURLOPT_VERBOSE, kVerboseOutput);
  libcurl_->curl_easy_setopt(curl_, CURLOPT_CAPATH, kCertsPath);
  libcurl_->curl_easy_setopt(
      curl_, CURLOPT_USERAGENT,
      strings::StrCat("TensorFlow/", TF_VERSION_STRING).c_str());
  // Do not use signals for timeouts - does not work in multi-threaded programs.
  libcurl_->curl_easy_setopt(curl_, CURLOPT_NOSIGNAL, 1L);
  libcurl_->curl_easy_setopt(curl_, CURLOPT_TIMEOUT, kRequestTimeoutSeconds);
  libcurl_->curl_easy_setopt(curl_, CURLOPT_CONNECTTIMEOUT,
                             kConnectTimeoutSeconds);
  libcurl_->curl_easy_setopt(curl_, CURLOPT_HTTP_VERSION,
                             CURL_HTTP_VERSION_2_0);

  // If response buffer is not set, libcurl will print results to stdout,
  // so we always set it.
  is_initialized_ = true;
  auto s = SetResultBuffer(default_response_buffer_.get(), CURL_MAX_WRITE_SIZE,
                           &default_response_string_piece_);
  if (!s.ok()) {
    is_initialized_ = false;
    return s;
  }
  return Status::OK();
}

string HttpRequest::EscapeString(const string& str) {
  char* out_char_str = libcurl_->curl_easy_escape(curl_, str.c_str(), 0);
  string out_str(out_char_str);
  libcurl_->curl_free(out_char_str);
  return out_str;
}

Status HttpRequest::SetUri(const string& uri) {
  TF_RETURN_IF_ERROR(CheckInitialized());
  TF_RETURN_IF_ERROR(CheckNotSent());
  is_uri_set_ = true;
  libcurl_->curl_easy_setopt(curl_, CURLOPT_URL, uri.c_str());
  return Status::OK();
}

Status HttpRequest::SetRange(uint64 start, uint64 end) {
  TF_RETURN_IF_ERROR(CheckInitialized());
  TF_RETURN_IF_ERROR(CheckNotSent());
  libcurl_->curl_easy_setopt(curl_, CURLOPT_RANGE,
                             strings::StrCat(start, "-", end).c_str());
  return Status::OK();
}

Status HttpRequest::AddHeader(const string& name, const string& value) {
  TF_RETURN_IF_ERROR(CheckInitialized());
  TF_RETURN_IF_ERROR(CheckNotSent());
  curl_headers_ = libcurl_->curl_slist_append(
      curl_headers_, strings::StrCat(name, ": ", value).c_str());
  return Status::OK();
}

Status HttpRequest::AddAuthBearerHeader(const string& auth_token) {
  TF_RETURN_IF_ERROR(CheckInitialized());
  TF_RETURN_IF_ERROR(CheckNotSent());
  if (!auth_token.empty()) {
    return AddHeader("Authorization", strings::StrCat("Bearer ", auth_token));
  }
  return Status::OK();
}

Status HttpRequest::SetDeleteRequest() {
  TF_RETURN_IF_ERROR(CheckInitialized());
  TF_RETURN_IF_ERROR(CheckNotSent());
  TF_RETURN_IF_ERROR(CheckMethodNotSet());
  is_method_set_ = true;
  libcurl_->curl_easy_setopt(curl_, CURLOPT_CUSTOMREQUEST, "DELETE");
  return Status::OK();
}

Status HttpRequest::SetPutFromFile(const string& body_filepath, size_t offset) {
  TF_RETURN_IF_ERROR(CheckInitialized());
  TF_RETURN_IF_ERROR(CheckNotSent());
  TF_RETURN_IF_ERROR(CheckMethodNotSet());
  is_method_set_ = true;
  if (put_body_) {
    fclose(put_body_);
  }
  put_body_ = fopen(body_filepath.c_str(), "r");
  if (!put_body_) {
    return errors::InvalidArgument("Couldn't open the specified file: " +
                                   body_filepath);
  }
  fseek(put_body_, 0, SEEK_END);
  const auto size = ftell(put_body_) - offset;
  fseek(put_body_, offset, SEEK_SET);

  curl_headers_ = libcurl_->curl_slist_append(
      curl_headers_, strings::StrCat("Content-Length: ", size).c_str());
  libcurl_->curl_easy_setopt(curl_, CURLOPT_PUT, 1);
  libcurl_->curl_easy_setopt(curl_, CURLOPT_READDATA,
                             reinterpret_cast<void*>(put_body_));
  return Status::OK();
}

Status HttpRequest::SetPutEmptyBody() {
  TF_RETURN_IF_ERROR(CheckInitialized());
  TF_RETURN_IF_ERROR(CheckNotSent());
  TF_RETURN_IF_ERROR(CheckMethodNotSet());
  is_method_set_ = true;
  libcurl_->curl_easy_setopt(curl_, CURLOPT_PUT, 1);
  curl_headers_ =
      libcurl_->curl_slist_append(curl_headers_, "Content-Length: 0");
  libcurl_->curl_easy_setopt(curl_, CURLOPT_READFUNCTION,
                             &HttpRequest::ReadCallback);
  return Status::OK();
}

Status HttpRequest::SetPostFromBuffer(const char* buffer, size_t size) {
  TF_RETURN_IF_ERROR(CheckInitialized());
  TF_RETURN_IF_ERROR(CheckNotSent());
  TF_RETURN_IF_ERROR(CheckMethodNotSet());
  is_method_set_ = true;
  curl_headers_ = libcurl_->curl_slist_append(
      curl_headers_, strings::StrCat("Content-Length: ", size).c_str());
  libcurl_->curl_easy_setopt(curl_, CURLOPT_POST, 1);
  libcurl_->curl_easy_setopt(curl_, CURLOPT_READDATA,
                             reinterpret_cast<void*>(this));
  libcurl_->curl_easy_setopt(curl_, CURLOPT_READFUNCTION,
                             &HttpRequest::ReadCallback);
  post_body_buffer_ = StringPiece(buffer, size);
  return Status::OK();
}

Status HttpRequest::SetPostEmptyBody() {
  TF_RETURN_IF_ERROR(CheckInitialized());
  TF_RETURN_IF_ERROR(CheckNotSent());
  TF_RETURN_IF_ERROR(CheckMethodNotSet());
  is_method_set_ = true;
  libcurl_->curl_easy_setopt(curl_, CURLOPT_POST, 1);
  curl_headers_ =
      libcurl_->curl_slist_append(curl_headers_, "Content-Length: 0");
  libcurl_->curl_easy_setopt(curl_, CURLOPT_READFUNCTION,
                             &HttpRequest::ReadCallback);
  return Status::OK();
}

Status HttpRequest::SetResultBuffer(char* scratch, size_t size,
                                    StringPiece* result) {
  TF_RETURN_IF_ERROR(CheckInitialized());
  TF_RETURN_IF_ERROR(CheckNotSent());
  if (!scratch) {
    return errors::InvalidArgument("scratch cannot be null");
  }
  if (!result) {
    return errors::InvalidArgument("result cannot be null");
  }
  if (size <= 0) {
    return errors::InvalidArgument("buffer size should be positive");
  }

  response_buffer_ = scratch;
  response_buffer_size_ = size;
  response_string_piece_ = result;
  response_buffer_written_ = 0;

  libcurl_->curl_easy_setopt(curl_, CURLOPT_WRITEDATA,
                             reinterpret_cast<void*>(this));
  libcurl_->curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION,
                             &HttpRequest::WriteCallback);
  return Status::OK();
}

size_t HttpRequest::WriteCallback(const void* ptr, size_t size, size_t nmemb,
                                  void* this_object) {
  CHECK(ptr);
  auto that = reinterpret_cast<HttpRequest*>(this_object);
  CHECK(that->response_buffer_);
  CHECK(that->response_buffer_size_ >= that->response_buffer_written_);
  const size_t bytes_to_copy =
      std::min(size * nmemb,
               that->response_buffer_size_ - that->response_buffer_written_);
  memcpy(that->response_buffer_ + that->response_buffer_written_, ptr,
         bytes_to_copy);
  that->response_buffer_written_ += bytes_to_copy;
  return bytes_to_copy;
}

size_t HttpRequest::ReadCallback(void* ptr, size_t size, size_t nmemb,
                                 FILE* this_object) {
  CHECK(ptr);
  auto that = reinterpret_cast<HttpRequest*>(this_object);
  CHECK(that->post_body_read_ <= that->post_body_buffer_.size());
  const size_t bytes_to_copy = std::min(
      size * nmemb, that->post_body_buffer_.size() - that->post_body_read_);
  memcpy(ptr, that->post_body_buffer_.data() + that->post_body_read_,
         bytes_to_copy);
  that->post_body_read_ += bytes_to_copy;
  return bytes_to_copy;
}

size_t HttpRequest::HeaderCallback(const void* ptr, size_t size, size_t nmemb,
                                   void* this_object) {
  CHECK(ptr);
  auto that = reinterpret_cast<HttpRequest*>(this_object);
  StringPiece header(reinterpret_cast<const char*>(ptr), size * nmemb);
  StringPiece name, value;
  // The supplied header has the form "<name>: <value>", parse it.
  if (strings::Scanner(header)
          .ScanEscapedUntil(':')
          .StopCapture()
          .OneLiteral(": ")
          .GetResult(&value, &name)) {
    string str_value = value.ToString();
    str_util::StripTrailingWhitespace(&str_value);
    that->response_headers_[name.ToString()] = str_value;
  }
  return size * nmemb;
}

Status HttpRequest::Send() {
  TF_RETURN_IF_ERROR(CheckInitialized());
  TF_RETURN_IF_ERROR(CheckNotSent());
  is_sent_ = true;
  if (!is_uri_set_) {
    return errors::FailedPrecondition("URI has not been set.");
  }
  if (curl_headers_) {
    libcurl_->curl_easy_setopt(curl_, CURLOPT_HTTPHEADER, curl_headers_);
  }
  libcurl_->curl_easy_setopt(curl_, CURLOPT_HEADERDATA,
                             reinterpret_cast<void*>(this));
  libcurl_->curl_easy_setopt(curl_, CURLOPT_HEADERFUNCTION,
                             &HttpRequest::HeaderCallback);

  char error_buffer[CURL_ERROR_SIZE];
  libcurl_->curl_easy_setopt(curl_, CURLOPT_ERRORBUFFER, error_buffer);

  const auto curl_result = libcurl_->curl_easy_perform(curl_);

  double written_size = 0;
  libcurl_->curl_easy_getinfo(curl_, CURLINFO_SIZE_DOWNLOAD, &written_size);

  libcurl_->curl_easy_getinfo(curl_, CURLINFO_RESPONSE_CODE, &response_code_);

  switch (response_code_) {
    case 200:  // OK
    case 201:  // Created
    case 204:  // No Content
    case 206:  // Partial Content
      if (curl_result != CURLE_OK) {
        // UNAVAILABLE can be retried by the caller, e.g by RetryingFileSystem.
        return errors::Unavailable(
            strings::StrCat("libcurl failed with error code ", curl_result,
                            ": ", error_buffer));
      }
      if (response_buffer_ && response_string_piece_) {
        *response_string_piece_ = StringPiece(response_buffer_, written_size);
      }
      return Status::OK();
    case 401:
    case 403:
      return errors::PermissionDenied("Not authorized to access the resource.");
    case 404:
      return errors::NotFound("The requested resource was not found.");
    case 416:  // Requested Range Not Satisfiable
      if (response_string_piece_) {
        *response_string_piece_ = StringPiece();
      }
      return Status::OK();
    default:
      // UNAVAILABLE can be retried by the caller, e.g by RetryingFileSystem.
      return errors::Unavailable(
          strings::StrCat("Unexpected response code ", response_code_));
  }
}

Status HttpRequest::CheckInitialized() const {
  if (!is_initialized_) {
    return errors::FailedPrecondition("The object has not been initialized.");
  }
  return Status::OK();
}

Status HttpRequest::CheckMethodNotSet() const {
  if (is_method_set_) {
    return errors::FailedPrecondition("HTTP method has been already set.");
  }
  return Status::OK();
}

Status HttpRequest::CheckNotSent() const {
  if (is_sent_) {
    return errors::FailedPrecondition("The request has already been sent.");
  }
  return Status::OK();
}

string HttpRequest::GetResponseHeader(const string& name) const {
  const auto& header = response_headers_.find(name);
  return header != response_headers_.end() ? header->second : "";
}

uint64 HttpRequest::GetResponseCode() const { return response_code_; }

}  // namespace tensorflow


text:
package org.apache.hadoop.mapred.uploader;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;

/**
 * Framework uploaded exception type.
 */
@InterfaceAudience.Private
@InterfaceStability.Stable
class UploaderException extends Exception {

  private static final long serialVersionUID = 1L;

  UploaderException(String message) {
    super(message);
  }
}

redpajama_set_name: RedPajamaGithub


text:
package org.workcraft.plugins.policy.converters;

import org.workcraft.dom.math.MathNode;
import org.workcraft.plugins.petri.Place;
import org.workcraft.plugins.petri.Transition;
import org.workcraft.plugins.petri.VisualPetri;
import org.workcraft.plugins.petri.converters.DefaultPetriConverter;
import org.workcraft.plugins.policy.BundledTransition;
import org.workcraft.plugins.policy.Policy;
import org.workcraft.plugins.policy.VisualPolicy;

import java.util.Map;

public class PetriToPolicyConverter extends DefaultPetriConverter<VisualPetri, VisualPolicy> {

    public PetriToPolicyConverter(VisualPetri srcModel) {
        super(srcModel, new VisualPolicy(new Policy()));
    }

    @Override
    public Map<Class<? extends MathNode>, Class<? extends MathNode>> getComponentClassMap() {
        Map<Class<? extends MathNode>, Class<? extends MathNode>> result = super.getComponentClassMap();
        result.put(Place.class, Place.class);
        result.put(Transition.class, BundledTransition.class);
        return result;
    }

}


text:
'use strict'

var fs = require('fs')
var path = require('path')

module.exports = write

function write(ctx, next) {
  var dir = path.dirname(ctx.examplePath)
  var extname = path.extname(ctx.examplePath)
  var filePath = path.join(dir, ctx.id + extname)

  fs.writeFile(filePath, ctx.exampleInstrumented, onwrite)

  function onwrite(err) {
    /* istanbul ignore if - Doesn't happen consistently */
    if (err) {
      return next(new Error('Could not write example: ' + err))
    }

    ctx.exampleInstrumentedPath = filePath
    next()
  }
}


text:
@extends('layout.dashboard')

@section('content')

        @if(isset($sub_menu))
        @include('dashboard.partials.sub-sidebar')
        @endif

                     {{ trans_choice('dashboard.components.groups.groups', 2) }}

                    {{ trans('dashboard.components.groups.add.title') }}

                    @forelse($groups as $group)

id }}">

                                @if($groups->count() > 1)

                                @endif
                                {{ $group->name }}
                                {{ $group->components->count() }}

                            id]) }}" class="btn btn-default">{{ trans('forms.edit') }}
                            id }}/delete" class="btn btn-danger confirm-action" data-method="DELETE">{{ trans('forms.delete') }}

                    @empty

{{ trans('dashboard.components.groups.no_components') }}

                    @endforelse

@stop


text:
<?php
namespace LancerHe\Http\Parse\Decorator;

use LancerHe\Http\Parse\Decorator;

/**
 * Class LoggerFile
 *
 * @package LancerHe\Http\Parse\Decorator
 * @author  Lancer He <lancer.he@gmail.com>
 */
class LoggerFile extends Decorator {
    /**
     * @var string
     */
    protected $_outputFile = '/tmp/httpparse.log';

    /**
     * @param $file
     */
    public function setOutputFile($file) {
        $this->_outputFile = $file;
    }

    /**
     * @return mixed
     */
    public function parse() {
        $parse = parent::parse();
        $this->outputFile($parse);
        return $parse;
    }

    /**
     * @param $parse
     */
    public function outputFile($parse) {
        $output = [
            'datetime' => date('Y-m-d H:i:s'),
            'origin'   => $this->getRequest(),
            'decode'   => $parse,
        ];
        $output = var_export($output, true) . PHP_EOL;
        file_put_contents($this->_outputFile, $output, FILE_APPEND);
    }
}


text:
// Patterns: 1
// Matches: Foo.cs
// NotMatches: Bar.cs

using Autofac;
using TestApplication.Types;

namespace TestApplication.Autofac
{
    public class RegisterWithLambdaAs : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            // ReSharper disable once RedundantCast
            builder.Register(context => new Foo() as Foo);
        }
    }
}


text:
package org.bouncycastle.cert.crmf;

/**
 * An encrypted value padder is used to make sure that prior to a value been
 * encrypted the data is padded to a standard length.
 */
public interface EncryptedValuePadder
{
    /**
     * Return a byte array of padded data.
     *
     * @param data the data to be padded.
     * @return a padded byte array containing data.
     */
    byte[] getPaddedData(byte[] data);

    /**
     * Return a byte array of with padding removed.
     *
     * @param paddedData the data to be padded.
     * @return an array containing the original unpadded data.
     */
    byte[] getUnpaddedData(byte[] paddedData);
}


text:
var Follows = Parse.Object.extend("Follows");

Parse.Cloud.define('hello', function(req, res) {
  res.success('Hi');
});

Parse.Cloud.define('follows', function(request, response) {
  //Parse.Cloud.useMasterKey();

  var user = request.user;
  if (!user) {
    return response.success([]);
  }

  new Parse.Query(Follows)
    .equalTo('userFrom', user)
    .include('userTo')
    .find()
    .then(
      (value) => { response.success(value); },
      (error) => { response.error(error); }
    );

});

Parse.Cloud.define('follows-create', function(request, response) {

  var currentUser = request.user;
  if (!currentUser) {
    return response.error({message: 'Not logged in'});
  }

  var params = request.params;
  if (!params.id) {
    return response.error({message: 'Need user id for following.'});
  }

  if(params.id == currentUser.id) {
    // ParseError.VALIDATION_ERROR = 142; (Error code indicating that a Cloud Code validation failed.)
    response.error( {code: 142, message: "input param ("+params.id+") is same with current user"} );
    return;
  }

  var user = new Parse.User();
  user.id = params.id;

  new Parse.Query(Follows)
    .equalTo('userFrom', currentUser)
    .equalTo('userTo', user)
    .first()
    .then(
      (result) => {

        if(!result) {

          var follow = new Follows();
          follow.set("userFrom", currentUser);
          follow.set("userTo", user);
          follow.save()
          .then(
            (value) => { response.success(value); },
            (error) => { response.error(error); }
          );

        }else{
          response.success(null);
        }

    },
    (error) => {
      response.error(error);
    }
  );

});

Parse.Cloud.define('follows-remove', function(request, response) {

  var currentUser = request.user;
  if (!currentUser) {
    return response.error({message: 'Not logged in'});
  }

  var params = request.params;
  if (!params.id) {
    return response.error({message: 'Need user id for following.'});
  }

  if(params.id == currentUser.id) {
    // ParseError.VALIDATION_ERROR = 142; (Error code indicating that a Cloud Code validation failed.)
    response.error( {code: 142, message: "input param ("+params.id+") is same with current user"} );
    return;
  }

  var user = new Parse.User();
  user.id = params.id;

  new Parse.Query(Follows)
    .equalTo('userFrom', currentUser)
    .equalTo('userTo', user)
    .first()
    .then(
      (result) => {

        if(result) {
          result.destroy().then(
            (object)  => { response.success(object);  },
            (error)   => { response.error(error);     }
          );
        } else {
          // ParseError.OBJECT_NOT_FOUND = 101 (Error code indicating the specified object doesn't exist.)
          response.error( {code: 101, message: "object doesn't exist."} );
        }

      },
      (error) => {
        response.error(error);
      }

    );

});


text:
<!DOCTYPE html>

  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">

<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

  <meta name="google-site-verification" content="true" />

  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />

<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />

  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.ico?v=5.1.4">

  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico?v=5.1.4">

  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico?v=5.1.4">

  <link rel="mask-icon" href="/images/favicon.ico?v=5.1.4" color="#222">

  <meta name="keywords" content="Hexo, NexT" />

<meta name="description" content="k3mdeblog">
<meta property="og:type" content="website">
<meta property="og:title" content="k3m_blog">
<meta property="og:url" content="https://easonlius.github.io/archives/page/6/index.html">
<meta property="og:site_name" content="k3m_blog">
<meta property="og:description" content="k3mdeblog">
<meta property="og:locale" content="zh-Hans">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="k3m_blog">
<meta name="twitter:description" content="k3mdeblog">

  <link rel="canonical" href="https://easonlius.github.io/archives/page/6/"/>

  <title>归档 | k3m_blog</title>

        k3m_blog

    <button>

    </button>

            首页

            关于

            标签

            归档

            Bug bounty

            Nav Websites

            Nav Tools

            Friends links

        好! 目前共计 51 篇日志。 继续努力。

2015

                读书笔记

        <time class="post-time" itemprop="dateCreated"
              datetime="2015-07-22T00:00:00+08:00"
              content="2015-07-22" >
          07-22
        </time>

    1…56

k3m@SST

k3mdeblog

                  51
                  日志

                  15
                  分类

                  52
                  标签

© 2019

  k3m@SST

由 Hexo 强力驱动

  |

主题 — NexT.Pisces v5.1.4

      访问人数

      总访问量

      次


text:
import csv
import os

try:
    import unittest2 as unittest
except ImportError:
    import unittest

import agate
import agatecharts

TEST_FILENAME = '.test.png'

class TestLineChart(unittest.TestCase):
    def setUp(self):
        text_type = agate.Text()
        number_type = agate.Number()

        columns = (
            ('gender', text_type),
            ('month', number_type),
            ('median', number_type),
            ('stdev', number_type),
            ('1st', number_type),
            ('3rd', number_type),
            ('5th', number_type),
            ('15th', number_type),
            ('25th', number_type),
            ('50th', number_type),
            ('75th', number_type),
            ('85th', number_type),
            ('95th', number_type),
            ('97th', number_type),
            ('99th', number_type)
        )

        with open('examples/heights.csv') as f:
            # Create a csv reader
            reader = csv.reader(f)

            # Skip header
            next(f)

            # Create the table
            self.table = agate.Table(reader, columns)

        if os.path.exists(TEST_FILENAME):
            os.remove(TEST_FILENAME)

    def test_single(self):
        self.table.line_chart('month', 'median', filename=TEST_FILENAME)

        self.assertTrue(os.path.exists(TEST_FILENAME))

    def test_many(self):
        self.table.line_chart('month', ['median', 'stdev'], filename=TEST_FILENAME)

        self.assertTrue(os.path.exists(TEST_FILENAME))

    def test_multiples(self):
        genders = self.table.group_by('gender')

        genders.line_chart('month', 'median', filename=TEST_FILENAME)

        self.assertTrue(os.path.exists(TEST_FILENAME))


text:
package org.apache.servicecomb.swagger.invocation.response.producer;

import java.lang.reflect.Type;

import org.apache.servicecomb.swagger.invocation.response.ResponseMapperFactorys;

public class DefaultProducerResponseMapperFactory implements ProducerResponseMapperFactory {
  @Override
  public int getOrder() {
    return Integer.MAX_VALUE;
  }

  @Override
  public boolean isMatch(Type producerType) {
    return true;
  }

  @Override
  public ProducerResponseMapper createResponseMapper(ResponseMapperFactorys<ProducerResponseMapper> factorys,
      Type producerType) {
    return new DefaultProducerResponseMapper();
  }
}


text:
package com.dfyy.bussiness;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import org.codehaus.jackson.annotate.JsonIgnoreProperties;

@Entity
@Table(name = "b2b_seed")
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
public class DjzSeed implements Serializable {

	private static final long serialVersionUID = -7362540539295291323L;

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "id")
	@XmlElement
	private Integer id;

	@Column(name = "chknumber")
	@XmlElement
	private String code;

	@Column(name = "name")
	@XmlElement
	private String name;

	@Column(name = "category")
	@XmlElement
	private String category;

	@Column(name = "chkyear")
	@XmlElement
	private String chkyear;

	@Column(name = "chkunit")
	@XmlElement
	private String chkunit;

	@Column(name = "apply_unit")
	@XmlElement
	private String applyUnit;

	@Column(name = "source")
	@XmlElement
	private String source;

	@Column(name = "transgenosis")
	@XmlElement
	private String transgenosis;

	@Column(name = "feature")
	@XmlElement
	private String feature;

	@Column(name = "output")
	@XmlElement
	private String output;

	@Column(name = "planting_zone")
	@XmlElement
	private String plantingZone;

	@Column(name = "experimental")
	@XmlElement
	private String experimental;

	@Column(name = "service_tel")
	@XmlElement
	private String servicetel;

	@Column(name = "website")
	@XmlElement
	private String website;

	@Column(name = "status")
	private Integer status;

	public Integer getId() {
		return id;
	}

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

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getCategory() {
		return category;
	}

	public void setCategory(String category) {
		this.category = category;
	}

	public String getChkyear() {
		return chkyear;
	}

	public void setChkyear(String chkyear) {
		this.chkyear = chkyear;
	}

	public String getChkunit() {
		return chkunit;
	}

	public void setChkunit(String chkunit) {
		this.chkunit = chkunit;
	}

	public String getApplyUnit() {
		return applyUnit;
	}

	public void setApplyUnit(String applyUnit) {
		this.applyUnit = applyUnit;
	}

	public String getSource() {
		return source;
	}

	public void setSource(String source) {
		this.source = source;
	}

	public String getTransgenosis() {
		return transgenosis;
	}

	public void setTransgenosis(String transgenosis) {
		this.transgenosis = transgenosis;
	}

	public String getFeature() {
		return feature;
	}

	public void setFeature(String feature) {
		this.feature = feature;
	}

	public String getOutput() {
		return output;
	}

	public void setOutput(String output) {
		this.output = output;
	}

	public String getPlantingZone() {
		return plantingZone;
	}

	public void setPlantingZone(String plantingZone) {
		this.plantingZone = plantingZone;
	}

	public String getExperimental() {
		return experimental;
	}

	public void setExperimental(String experimental) {
		this.experimental = experimental;
	}

	public String getServicetel() {
		return servicetel;
	}

	public void setServicetel(String servicetel) {
		this.servicetel = servicetel;
	}

	public String getWebsite() {
		return website;
	}

	public void setWebsite(String website) {
		this.website = website;
	}

	public Integer getStatus() {
		return status;
	}

	public void setStatus(Integer status) {
		this.status = status;
	}

}


text:
function beta = IWT_AI(wc,L,D,F,EF)
% IWT_AI -- Inverse transform, average-interpolating wavelets
%  Usage
%    x = IWT_AI(wc,L,D)
%  Inputs
%    wc    1-d wavelet transform; length(x) = 2^J
%    L     coarsest resolution. L << J
%    D     degree of polynomials for average interpolation
%  Outputs
%    x     1-d signal reconstructed from wc
%
%  Description
%    IWT_AI implements a 1-d inverse wavelet transform of data which
%    arise as the outputs of boxcar integrators.  The ideas are
%    described in ``Smooth Wavelet Decompositions with Blocky
%    Coefficient Kernels.''  See BlockyDemo and the directory
%    Scripts/Blocky.
%
%  See Also
%    FWT_AI, FWT_DD, FWT_PO
%

        if nargin == 3,
	  F = MakeAIFilter(D);
	  EF = MakeAIBdryFilter(D);
	end

	[n,J] = dyadlength(wc);
	w     = ShapeAsRow(wc);
	beta  = w(1:(2^L));
%
	for j=L:(J-1) ,
	   beta = AIDyadUp(beta,w(dyad(j)),D,F,EF);
	end
%
	x = ShapeLike(beta,wc);

%
%  Part of Wavelab Version 850
%  Built Tue Jan  3 13:20:40 EST 2006
%  This is Copyrighted Material
%  For Copying permissions see COPYING.m
%  Comments? e-mail wavelab@stat.stanford.edu


text:
extern "C" {
#endif
#define FX_Alloc(type, size)						(type*)calloc(size, sizeof(type))
#define FX_Realloc(type, ptr, size)					(type*)realloc(ptr, sizeof(type) * (size))
#define FX_AllocNL(type, size)						FX_Alloc(type, size)
#define FX_ReallocNL(type, ptr, size)				FX_Realloc(type, ptr, size)
#define FX_Free(ptr)								free(ptr)
void*	FXMEM_DefaultAlloc(size_t byte_size, int flags);
void*	FXMEM_DefaultRealloc(void* pointer, size_t new_size, int flags);
void	FXMEM_DefaultFree(void* pointer, int flags);
#ifdef __cplusplus
}
#endif
#ifdef __cplusplus
class CFX_Object
{
public:
    void*			operator new (size_t size, FX_LPCSTR file, int line)
    {
        return malloc(size);
    }
    void			operator delete (void* p, FX_LPCSTR file, int line)
    {
        free(p);
    }
    void*			operator new (size_t size)
    {
        return malloc(size);
    }
    void			operator delete (void* p)
    {
        free(p);
    }
    void*			operator new[] (size_t size, FX_LPCSTR file, int line)
    {
        return malloc(size);
    }
    void			operator delete[] (void* p, FX_LPCSTR file, int line)
    {
        free(p);
    }
    void*			operator new[] (size_t size)
    {
        return malloc(size);
    }
    void			operator delete[] (void* p)
    {
        free(p);
    }
    void*			operator new (size_t, void* buf)
    {
        return buf;
    }
    void			operator delete (void*, void*)							{}
};
#endif
#ifdef __cplusplus
#if defined(_DEBUG)
#define FX_NEW new(__FILE__, __LINE__)
#else

#define FX_NEW new
#endif
#define FX_NEW_VECTOR(Pointer, Class, Count) \
    { \
        Pointer = FX_Alloc(Class, Count); \
        if (Pointer) { \
            for (int i = 0; i < (Count); i ++) new (Pointer + i) Class; \
        } \
    }
#define FX_DELETE_VECTOR(Pointer, Class, Count) \
    { \
        for (int i = 0; i < (Count); i ++) Pointer[i].~Class(); \
        FX_Free(Pointer); \
    }
class CFX_DestructObject : public CFX_Object
{
public:

    virtual ~CFX_DestructObject() {}
};
class CFX_GrowOnlyPool : public CFX_Object
{
public:

    CFX_GrowOnlyPool(size_t trunk_size = 16384);

    ~CFX_GrowOnlyPool();

    void	SetTrunkSize(size_t trunk_size)
    {
        m_TrunkSize = trunk_size;
    }

    void*	AllocDebug(size_t size, FX_LPCSTR file, int line)
    {
        return Alloc(size);
    }

    void*	Alloc(size_t size);

    void*	ReallocDebug(void* p, size_t new_size, FX_LPCSTR file, int line)
    {
        return NULL;
    }

    void*	Realloc(void* p, size_t new_size)
    {
        return NULL;
    }

    void	Free(void*) {}

    void	FreeAll();
private:

    size_t	m_TrunkSize;

    void*	m_pFirstTrunk;
};
#endif
#endif


text:
module Main ( main ) where

import Data.Map ( Map )
import Data.Monoid
import Data.Set ( Set )
import System.Environment ( getArgs, withArgs )
import System.FilePath
import Test.HUnit ( assertEqual )

import LLVM.Analysis
import LLVM.Analysis.AccessPath
import LLVM.Analysis.CallGraph
import LLVM.Analysis.CallGraphSCCTraversal
import LLVM.Analysis.Util.Testing
import LLVM.Parse

import Foreign.Inference.Interface
import Foreign.Inference.Preprocessing
import Foreign.Inference.Analysis.Finalize
import Foreign.Inference.Analysis.IndirectCallResolver
import Foreign.Inference.Analysis.SAP
import Foreign.Inference.Analysis.SAPPTRel
import Foreign.Inference.Analysis.Util.CompositeSummary

main :: IO ()
main = do
  args <- getArgs
  let pattern = case args of
        [] -> "tests/sap/return/*.c"
        [infile] -> infile
        _ -> error "At most one argument allowed"
  ds <- loadDependencies [] []
  let testDescriptors = [
        TestDescriptor { testPattern = pattern
                       , testExpectedMapping = (<.> "expected")
                       , testResultBuilder = analyzeSAPs ds
                       , testResultComparator = assertEqual
                       }
        ]
  withArgs [] $ testAgainstExpected requiredOptimizations bcParser testDescriptors
  where
    bcParser = parseLLVMFile defaultParserOptions

type Summary = (Int, String, [AccessType])

analyzeSAPs :: DependencySummary -> Module -> Map String (Set Summary)
analyzeSAPs ds m =
  sapReturnResultToTestFormat (_sapSummary res)
  where
    ics = identifyIndirectCallTargets m
    cg = callGraph m ics []
    analyses :: [ComposableAnalysis AnalysisSummary FunctionMetadata]
    analyses = [ identifyFinalizers ds ics finalizerSummary
               , identifySAPPTRels ds sapPTRelSummary
               , identifySAPs ds ics sapSummary sapPTRelSummary finalizerSummary
               ]
    analysisFunc = callGraphComposeAnalysis analyses
    res = callGraphSCCTraversal cg analysisFunc mempty


text:
package com.github.yashk.contacts;

import org.apache.commons.collections4.trie.PatriciaTrie;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by ykochare on 6/12/16.
 */
public class PatriciaTrieContactsBook implements ContactsBook {

    /**
     * Using PatriciaTrie data structure from apache commons-collections for efficient prefix based string search.
     * https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/trie/PatriciaTrie.html
     */
    public PatriciaTrie<Contact> trie = new PatriciaTrie<>();

    /**
     * adds a
     * @param contact
     * into ContactsBook
     */
    @Override
    public void addContact(Contact contact) {

        trie.put(contact.getFirstName()+contact.getLastName(),contact);
        if((!contact.getLastName().isEmpty() )) {
            trie.put(contact.getLastName()+contact.getFirstName(),contact);
        }
    }

    /**
     * returns a list of matching contacts given a
     * @param searchTerm
     *
     */
    @Override
    public List<Contact> searchContacts(String searchTerm) {
       return trie.prefixMap(searchTerm).values().stream().collect(Collectors.toList());
    }
}


text:
"""Root Cinder module."""

import os

# Ensure compatibility issues are covered with pythondsn
os.environ['EVENTLET_NO_GREENDNS'] = 'yes'

# Make sure eventlet is loaded
import eventlet  # noqa


text:
struct skynet_context {
	void * instance;
	struct skynet_module * mod;
	void * cb_ud;
	skynet_cb cb;
	struct message_queue *queue;
	FILE * logfile;
	char result[32];
	uint32_t handle;
	int session_id;
	int ref;
	bool init;
	bool endless;

	CHECKCALLING_DECL
};

struct skynet_node {
	int total;
	int init;
	uint32_t monitor_exit;
	pthread_key_t handle_key;
};

static struct skynet_node G_NODE;

int
skynet_context_total() {
	return G_NODE.total;
}

static void
context_inc() {
	__sync_fetch_and_add(&G_NODE.total,1);
}

static void
context_dec() {
	__sync_fetch_and_sub(&G_NODE.total,1);
}

uint32_t
skynet_current_handle(void) {
	if (G_NODE.init) {
		void * handle = pthread_getspecific(G_NODE.handle_key);
		return (uint32_t)(uintptr_t)handle;
	} else {
		uintptr_t v = (uint32_t)(-THREAD_MAIN);
		return v;
	}
}

static void
id_to_hex(char * str, uint32_t id) {
	int i;
	static char hex[16] = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' };
	str[0] = ':';
	for (i=0;i<8;i++) {
		str[i+1] = hex[(id >> ((7-i) * 4))&0xf];
	}
	str[9] = '\0';
}

struct drop_t {
	uint32_t handle;
};

static void
drop_message(struct skynet_message *msg, void *ud) {
	struct drop_t *d = ud;
	skynet_free(msg->data);
	uint32_t source = d->handle;
	assert(source);
	// report error to the message source
	skynet_send(NULL, source, msg->source, PTYPE_ERROR, 0, NULL, 0);
}

struct skynet_context *
skynet_context_new(const char * name, const char *param) {
	struct skynet_module * mod = skynet_module_query(name);

	if (mod == NULL)
		return NULL;

	void *inst = skynet_module_instance_create(mod);
	if (inst == NULL)
		return NULL;
	struct skynet_context * ctx = skynet_malloc(sizeof(*ctx));
	CHECKCALLING_INIT(ctx)

	ctx->mod = mod;
	ctx->instance = inst;
	ctx->ref = 2;
	ctx->cb = NULL;
	ctx->cb_ud = NULL;
	ctx->session_id = 0;
	ctx->logfile = NULL;

	ctx->init = false;
	ctx->endless = false;
	// Should set to 0 first to avoid skynet_handle_retireall get an uninitialized handle
	ctx->handle = 0;
	ctx->handle = skynet_handle_register(ctx);
	struct message_queue * queue = ctx->queue = skynet_mq_create(ctx->handle);
	// init function maybe use ctx->handle, so it must init at last
	context_inc();

	CHECKCALLING_BEGIN(ctx)
	int r = skynet_module_instance_init(mod, inst, ctx, param);
	CHECKCALLING_END(ctx)
	if (r == 0) {
		struct skynet_context * ret = skynet_context_release(ctx);
		if (ret) {
			ctx->init = true;
		}
		skynet_globalmq_push(queue);
		if (ret) {
			skynet_error(ret, "LAUNCH %s %s", name, param ? param : "");
		}
		return ret;
	} else {
		skynet_error(ctx, "FAILED launch %s", name);
		uint32_t handle = ctx->handle;
		skynet_context_release(ctx);
		skynet_handle_retire(handle);
		struct drop_t d = { handle };
		skynet_mq_release(queue, drop_message, &d);
		return NULL;
	}
}

int
skynet_context_newsession(struct skynet_context *ctx) {
	// session always be a positive number
	int session = (++ctx->session_id) & 0x7fffffff;
	return session;
}

void
skynet_context_grab(struct skynet_context *ctx) {
	__sync_add_and_fetch(&ctx->ref,1);
}

static void
delete_context(struct skynet_context *ctx) {
	if (ctx->logfile) {
		fclose(ctx->logfile);
	}
	skynet_module_instance_release(ctx->mod, ctx->instance);
	skynet_mq_mark_release(ctx->queue);
	skynet_free(ctx);
	context_dec();
}

struct skynet_context *
skynet_context_release(struct skynet_context *ctx) {
	if (__sync_sub_and_fetch(&ctx->ref,1) == 0) {
		delete_context(ctx);
		return NULL;
	}
	return ctx;
}

int
skynet_context_push(uint32_t handle, struct skynet_message *message) {
	struct skynet_context * ctx = skynet_handle_grab(handle);
	if (ctx == NULL) {
		return -1;
	}
	skynet_mq_push(ctx->queue, message);
	skynet_context_release(ctx);

	return 0;
}

void
skynet_context_endless(uint32_t handle) {
	struct skynet_context * ctx = skynet_handle_grab(handle);
	if (ctx == NULL) {
		return;
	}
	ctx->endless = true;
	skynet_context_release(ctx);
}

int
skynet_isremote(struct skynet_context * ctx, uint32_t handle, int * harbor) {
	int ret = skynet_harbor_message_isremote(handle);
	if (harbor) {
		*harbor = (int)(handle >> HANDLE_REMOTE_SHIFT);
	}
	return ret;
}

static void
dispatch_message(struct skynet_context *ctx, struct skynet_message *msg) {
	assert(ctx->init);
	CHECKCALLING_BEGIN(ctx)
	pthread_setspecific(G_NODE.handle_key, (void *)(uintptr_t)(ctx->handle));
	int type = msg->sz >> HANDLE_REMOTE_SHIFT;
	size_t sz = msg->sz & HANDLE_MASK;
	if (ctx->logfile) {
		skynet_log_output(ctx->logfile, msg->source, type, msg->session, msg->data, sz);
	}
	if (!ctx->cb(ctx, ctx->cb_ud, type, msg->session, msg->source, msg->data, sz)) {
		skynet_free(msg->data);
	}
	CHECKCALLING_END(ctx)
}

void
skynet_context_dispatchall(struct skynet_context * ctx) {
	// for skynet_error
	struct skynet_message msg;
	struct message_queue *q = ctx->queue;
	while (!skynet_mq_pop(q,&msg)) {
		dispatch_message(ctx, &msg);
	}
}

struct message_queue *
skynet_context_message_dispatch(struct skynet_monitor *sm, struct message_queue *q, int weight) {
	if (q == NULL) {
		q = skynet_globalmq_pop();
		if (q==NULL)
			return NULL;
	}

	uint32_t handle = skynet_mq_handle(q);

	struct skynet_context * ctx = skynet_handle_grab(handle);
	if (ctx == NULL) {
		struct drop_t d = { handle };
		skynet_mq_release(q, drop_message, &d);
		return skynet_globalmq_pop();
	}

	int i,n=1;
	struct skynet_message msg;

	for (i=0;i<n;i++) {
		if (skynet_mq_pop(q,&msg)) {
			skynet_context_release(ctx);
			return skynet_globalmq_pop();
		} else if (i==0 && weight >= 0) {
			n = skynet_mq_length(q);
			n >>= weight;
		}

		skynet_monitor_trigger(sm, msg.source , handle);

		if (ctx->cb == NULL) {
			skynet_free(msg.data);
		} else {
			dispatch_message(ctx, &msg);
		}

		skynet_monitor_trigger(sm, 0,0);
	}

	assert(q == ctx->queue);
	struct message_queue *nq = skynet_globalmq_pop();
	if (nq) {
		// If global mq is not empty , push q back, and return next queue (nq)
		// Else (global mq is empty or block, don't push q back, and return q again (for next dispatch)
		skynet_globalmq_push(q);
		q = nq;
	}
	skynet_context_release(ctx);

	return q;
}

static void
copy_name(char name[GLOBALNAME_LENGTH], const char * addr) {
	int i;
	for (i=0;i<GLOBALNAME_LENGTH && addr[i];i++) {
		name[i] = addr[i];
	}
	for (;i<GLOBALNAME_LENGTH;i++) {
		name[i] = '\0';
	}
}

uint32_t
skynet_queryname(struct skynet_context * context, const char * name) {
	switch(name[0]) {
	case ':':
		return strtoul(name+1,NULL,16);
	case '.':
		return skynet_handle_findname(name + 1);
	}
	skynet_error(context, "Don't support query global name %s",name);
	return 0;
}

static void
handle_exit(struct skynet_context * context, uint32_t handle) {
	if (handle == 0) {
		handle = context->handle;
		skynet_error(context, "KILL self");
	} else {
		skynet_error(context, "KILL :%0x", handle);
	}
	if (G_NODE.monitor_exit) {
		skynet_send(context,  handle, G_NODE.monitor_exit, PTYPE_CLIENT, 0, NULL, 0);
	}
	skynet_handle_retire(handle);
}

// skynet command

struct command_func {
	const char *name;
	const char * (*func)(struct skynet_context * context, const char * param);
};

static const char *
cmd_timeout(struct skynet_context * context, const char * param) {
	char * session_ptr = NULL;
	int ti = strtol(param, &session_ptr, 10);
	int session = skynet_context_newsession(context);
	skynet_timeout(context->handle, ti, session);
	sprintf(context->result, "%d", session);
	return context->result;
}

static const char *
cmd_reg(struct skynet_context * context, const char * param) {
	if (param == NULL || param[0] == '\0') {
		sprintf(context->result, ":%x", context->handle);
		return context->result;
	} else if (param[0] == '.') {
		return skynet_handle_namehandle(context->handle, param + 1);
	} else {
		skynet_error(context, "Can't register global name %s in C", param);
		return NULL;
	}
}

static const char *
cmd_query(struct skynet_context * context, const char * param) {
	if (param[0] == '.') {
		uint32_t handle = skynet_handle_findname(param+1);
		if (handle) {
			sprintf(context->result, ":%x", handle);
			return context->result;
		}
	}
	return NULL;
}

static const char *
cmd_name(struct skynet_context * context, const char * param) {
	int size = strlen(param);
	char name[size+1];
	char handle[size+1];
	sscanf(param,"%s %s",name,handle);
	if (handle[0] != ':') {
		return NULL;
	}
	uint32_t handle_id = strtoul(handle+1, NULL, 16);
	if (handle_id == 0) {
		return NULL;
	}
	if (name[0] == '.') {
		return skynet_handle_namehandle(handle_id, name + 1);
	} else {
		skynet_error(context, "Can't set global name %s in C", name);
	}
	return NULL;
}

static const char *
cmd_now(struct skynet_context * context, const char * param) {
	uint32_t ti = skynet_gettime();
	sprintf(context->result,"%u",ti);
	return context->result;
}

static const char *
cmd_exit(struct skynet_context * context, const char * param) {
	handle_exit(context, 0);
	return NULL;
}

static uint32_t
tohandle(struct skynet_context * context, const char * param) {
	uint32_t handle = 0;
	if (param[0] == ':') {
		handle = strtoul(param+1, NULL, 16);
	} else if (param[0] == '.') {
		handle = skynet_handle_findname(param+1);
	} else {
		skynet_error(context, "Can't convert %s to handle",param);
	}

	return handle;
}

static const char *
cmd_kill(struct skynet_context * context, const char * param) {
	uint32_t handle = tohandle(context, param);
	if (handle) {
		handle_exit(context, handle);
	}
	return NULL;
}

static const char *
cmd_launch(struct skynet_context * context, const char * param) {
	size_t sz = strlen(param);
	char tmp[sz+1];
	strcpy(tmp,param);
	char * args = tmp;
	char * mod = strsep(&args, " \t\r\n");
	args = strsep(&args, "\r\n");
	struct skynet_context * inst = skynet_context_new(mod,args);
	if (inst == NULL) {
		return NULL;
	} else {
		id_to_hex(context->result, inst->handle);
		return context->result;
	}
}

static const char *
cmd_getenv(struct skynet_context * context, const char * param) {
	return skynet_getenv(param);
}

static const char *
cmd_setenv(struct skynet_context * context, const char * param) {
	size_t sz = strlen(param);
	char key[sz+1];
	int i;
	for (i=0;param[i] != ' ' && param[i];i++) {
		key[i] = param[i];
	}
	if (param[i] == '\0')
		return NULL;

	key[i] = '\0';
	param += i+1;

	skynet_setenv(key,param);
	return NULL;
}

static const char *
cmd_starttime(struct skynet_context * context, const char * param) {
	uint32_t sec = skynet_gettime_fixsec();
	sprintf(context->result,"%u",sec);
	return context->result;
}

static const char *
cmd_endless(struct skynet_context * context, const char * param) {
	if (context->endless) {
		strcpy(context->result, "1");
		context->endless = false;
		return context->result;
	}
	return NULL;
}

static const char *
cmd_abort(struct skynet_context * context, const char * param) {
	skynet_handle_retireall();
	return NULL;
}

static const char *
cmd_monitor(struct skynet_context * context, const char * param) {
	uint32_t handle=0;
	if (param == NULL || param[0] == '\0') {
		if (G_NODE.monitor_exit) {
			// return current monitor serivce
			sprintf(context->result, ":%x", G_NODE.monitor_exit);
			return context->result;
		}
		return NULL;
	} else {
		handle = tohandle(context, param);
	}
	G_NODE.monitor_exit = handle;
	return NULL;
}

static const char *
cmd_mqlen(struct skynet_context * context, const char * param) {
	int len = skynet_mq_length(context->queue);
	sprintf(context->result, "%d", len);
	return context->result;
}

static const char *
cmd_logon(struct skynet_context * context, const char * param) {
	uint32_t handle = tohandle(context, param);
	if (handle == 0)
		return NULL;
	struct skynet_context * ctx = skynet_handle_grab(handle);
	if (ctx == NULL)
		return NULL;
	FILE *f = NULL;
	FILE * lastf = ctx->logfile;
	if (lastf == NULL) {
		f = skynet_log_open(context, handle);
		if (f) {
			if (!__sync_bool_compare_and_swap(&ctx->logfile, NULL, f)) {
				// logfile opens in other thread, close this one.
				fclose(f);
			}
		}
	}
	skynet_context_release(ctx);
	return NULL;
}

static const char *
cmd_logoff(struct skynet_context * context, const char * param) {
	uint32_t handle = tohandle(context, param);
	if (handle == 0)
		return NULL;
	struct skynet_context * ctx = skynet_handle_grab(handle);
	if (ctx == NULL)
		return NULL;
	FILE * f = ctx->logfile;
	if (f) {
		// logfile may close in other thread
		if (__sync_bool_compare_and_swap(&ctx->logfile, f, NULL)) {
			skynet_log_close(context, f, handle);
		}
	}
	skynet_context_release(ctx);
	return NULL;
}

static struct command_func cmd_funcs[] = {
	{ "TIMEOUT", cmd_timeout },
	{ "REG", cmd_reg },
	{ "QUERY", cmd_query },
	{ "NAME", cmd_name },
	{ "NOW", cmd_now },
	{ "EXIT", cmd_exit },
	{ "KILL", cmd_kill },
	{ "LAUNCH", cmd_launch },
	{ "GETENV", cmd_getenv },
	{ "SETENV", cmd_setenv },
	{ "STARTTIME", cmd_starttime },
	{ "ENDLESS", cmd_endless },
	{ "ABORT", cmd_abort },
	{ "MONITOR", cmd_monitor },
	{ "MQLEN", cmd_mqlen },
	{ "LOGON", cmd_logon },
	{ "LOGOFF", cmd_logoff },
	{ NULL, NULL },
};

const char *
skynet_command(struct skynet_context * context, const char * cmd , const char * param) {
	struct command_func * method = &cmd_funcs[0];
	while(method->name) {
		if (strcmp(cmd, method->name) == 0) {
			return method->func(context, param);
		}
		++method;
	}

	return NULL;
}

static void
_filter_args(struct skynet_context * context, int type, int *session, void ** data, size_t * sz) {
	int needcopy = !(type & PTYPE_TAG_DONTCOPY);
	int allocsession = type & PTYPE_TAG_ALLOCSESSION;
	type &= 0xff;

	if (allocsession) {
		assert(*session == 0);
		*session = skynet_context_newsession(context);
	}

	if (needcopy && *data) {
		char * msg = skynet_malloc(*sz+1);
		memcpy(msg, *data, *sz);
		msg[*sz] = '\0';
		*data = msg;
	}

	*sz |= type << HANDLE_REMOTE_SHIFT;
}

int
skynet_send(struct skynet_context * context, uint32_t source, uint32_t destination , int type, int session, void * data, size_t sz) {
	if ((sz & HANDLE_MASK) != sz) {
		skynet_error(context, "The message to %x is too large (sz = %lu)", destination, sz);
		skynet_free(data);
		return -1;
	}
	_filter_args(context, type, &session, (void **)&data, &sz);

	if (source == 0) {
		source = context->handle;
	}

	if (destination == 0) {
		return session;
	}
	if (skynet_harbor_message_isremote(destination)) {
		struct remote_message * rmsg = skynet_malloc(sizeof(*rmsg));
		rmsg->destination.handle = destination;
		rmsg->message = data;
		rmsg->sz = sz;
		skynet_harbor_send(rmsg, source, session);
	} else {
		struct skynet_message smsg;
		smsg.source = source;
		smsg.session = session;
		smsg.data = data;
		smsg.sz = sz;

		if (skynet_context_push(destination, &smsg)) {
			skynet_free(data);
			return -1;
		}
	}
	return session;
}

int
skynet_sendname(struct skynet_context * context, uint32_t source, const char * addr , int type, int session, void * data, size_t sz) {
	if (source == 0) {
		source = context->handle;
	}
	uint32_t des = 0;
	if (addr[0] == ':') {
		des = strtoul(addr+1, NULL, 16);
	} else if (addr[0] == '.') {
		des = skynet_handle_findname(addr + 1);
		if (des == 0) {
			if (type & PTYPE_TAG_DONTCOPY) {
				skynet_free(data);
			}
			return session;
		}
	} else {
		_filter_args(context, type, &session, (void **)&data, &sz);

		struct remote_message * rmsg = skynet_malloc(sizeof(*rmsg));
		copy_name(rmsg->destination.name, addr);
		rmsg->destination.handle = 0;
		rmsg->message = data;
		rmsg->sz = sz;

		skynet_harbor_send(rmsg, source, session);
		return session;
	}

	return skynet_send(context, source, des, type, session, data, sz);
}

uint32_t
skynet_context_handle(struct skynet_context *ctx) {
	return ctx->handle;
}

void
skynet_callback(struct skynet_context * context, void *ud, skynet_cb cb) {
	context->cb = cb;
	context->cb_ud = ud;
}

void
skynet_context_send(struct skynet_context * ctx, void * msg, size_t sz, uint32_t source, int type, int session) {
	struct skynet_message smsg;
	smsg.source = source;
	smsg.session = session;
	smsg.data = msg;
	smsg.sz = sz | type << HANDLE_REMOTE_SHIFT;

	skynet_mq_push(ctx->queue, &smsg);
}

void
skynet_globalinit(void) {
	G_NODE.total = 0;
	G_NODE.monitor_exit = 0;
	G_NODE.init = 1;
	if (pthread_key_create(&G_NODE.handle_key, NULL)) {
		fprintf(stderr, "pthread_key_create failed");
		exit(1);
	}
	// set mainthread's key
	skynet_initthread(THREAD_MAIN);
}

void
skynet_globalexit(void) {
	pthread_key_delete(G_NODE.handle_key);
}

void
skynet_initthread(int m) {
	uintptr_t v = (uint32_t)(-m);
	pthread_setspecific(G_NODE.handle_key, (void *)v);
}


text:
  <input type="search" class="form-control" placeholder="Search" ng-model="list.query">

        {{field | labelCase}}

       {{contact[field][0]}}


text:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">
    <meta name="repository" content="{{ site.repository }}">
    <meta name="updated_at" content="{{ site.time | date_to_xmlschema }}">
    <meta name="established_at" content="{{ site.established_at }}">
    {% seo %}
    <link rel="stylesheet" type="text/css" href="//unpkg.com/fomantic-ui/dist/semantic.min.css">
    <link rel="stylesheet" type="text/css" href="{{ '/assets/css/common.css' | relative_url }}">
    {% if page.active_key == 'home' %}<link rel="stylesheet" type="text/css" href="{{ '/assets/css/home.css' | relative_url }}">{% endif %}
    {% if page.active_key == 'customize' %}<link rel="stylesheet" type="text/css" href="{{ '/assets/css/customize.css' | relative_url }}">{% endif %}
    {% if page.active_key == 'analytics' %}<link rel="stylesheet" type="text/css" href="{{ '/assets/css/analytics.css' | relative_url }}">{% endif %}
    {% if page.active_key == 'donate' %}<link rel="stylesheet" type="text/css" href="{{ '/assets/css/donate.css' | relative_url }}">{% endif %}
    {% if page.active_key == 'search' %}<link rel="stylesheet" type="text/css" href="{{ '/assets/css/search.css' | relative_url }}">{% endif %}
    {% if page.active_key == 'error' %}<link rel="stylesheet" type="text/css" href="{{ '/assets/css/error.css' | relative_url }}">{% endif %}
    <link rel="stylesheet" type="text/css" href="{{ '/assets/css/masthead.css' | relative_url }}">
    {% if page.active_key == 'home' and site.data.style.memorial %}<link rel="stylesheet" type="text/css" href="{{ '/assets/css/grayscale.css' | relative_url }}">{% endif %}
    <link rel="apple-touch-icon" type="image/png" href="{{ '/apple-touch-icon.png' | relative_url }}">
    <link rel="icon" type="image/x-icon" href="{{ '/favicon.ico' | relative_url }}">
    {% include analytics.html %}
</head>
<body>
    {% include following_menu.html %}
    {% include sidebar.html %}
    <div class="pusher">
        {% include header.html %}
        {{ content }}
        {% include footer.html %}
    </div>
    <script type="text/javascript" src="//unpkg.com/jquery/dist/jquery.min.js"></script>
    <script type="text/javascript" src="//unpkg.com/fomantic-ui/dist/semantic.min.js"></script>
    <script type="text/javascript" src="{{ '/assets/js/common.js' | relative_url }}"></script>
    {% if page.active_key == 'home' %}<script type="text/javascript" src="//unpkg.com/dayjs/dayjs.min.js"></script>
    <script type="text/javascript" src="//unpkg.com/dayjs/locale/zh-cn.js"></script>
    <script type="text/javascript" src="//unpkg.com/dayjs/plugin/relativeTime.js"></script>
    <script type="text/javascript" src="//unpkg.com/js-cookie/dist/js.cookie.min.js"></script>
    <script type="text/javascript" src="{{ '/assets/js/suggest-query.min.js' | relative_url }}"></script>
    {% if site.data.banner.message.hitokoto %}<script type="text/javascript" src="{{ '/assets/js/hitokoto.js' | relative_url }}"></script>{% endif %}
    <script type="text/javascript" src="{{ '/assets/js/home.js' | relative_url }}"></script>{% endif %}
    {% if page.active_key == 'customize' %}<script type="text/javascript" src="//unpkg.com/js-cookie/dist/js.cookie.min.js"></script>
    <script type="text/javascript" src="{{ '/assets/js/customize.js' | relative_url }}"></script>{% endif %}
    {% if page.active_key == 'analytics' %}<script type="text/javascript" src="//unpkg.com/jquery-countdown/dist/jquery.countdown.min.js"></script>
    <script type="text/javascript" src="//unpkg.com/countup.js@1.9.3/dist/countUp.min.js"></script>
    <script type="text/javascript" src="//unpkg.com/echarts@4.9.0/dist/echarts.min.js"></script>
    <script type="text/javascript" src="//unpkg.com/echarts@4.9.0/map/js/world.js"></script>
    <script type="text/javascript" src="{{ '/assets/js/analytics.js' | relative_url }}"></script>{% endif %}
    {% if page.active_key == 'search' %}<script type="text/javascript" src="//unpkg.com/js-url/url.min.js"></script>
    <script type="text/javascript" src="{{ '/assets/js/search.js' | relative_url }}"></script>{% endif %}
</body>
</html>


text:
package edu.umd.cs.findbugs.detect;

import java.util.Iterator;

import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ARETURN;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.ReferenceType;

import edu.umd.cs.findbugs.FindBugsAnalysisFeatures;
import edu.umd.cs.findbugs.SystemProperties;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.CFG;
import edu.umd.cs.findbugs.ba.CFGBuilderException;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.DataflowAnalysisException;
import edu.umd.cs.findbugs.ba.Location;
import edu.umd.cs.findbugs.ba.XFactory;
import edu.umd.cs.findbugs.ba.XMethod;
import edu.umd.cs.findbugs.ba.npe.IsNullValue;
import edu.umd.cs.findbugs.ba.npe.IsNullValueDataflow;
import edu.umd.cs.findbugs.ba.npe.IsNullValueFrame;

/**
 * Build database of methods that return values guaranteed to be nonnull
 *
 */
public class BuildNonnullReturnDatabase {
    public static final boolean VERBOSE_DEBUG = SystemProperties.getBoolean("fnd.debug.nullarg.verbose");

    private static final boolean DEBUG = SystemProperties.getBoolean("fnd.debug.nullarg") || VERBOSE_DEBUG;

    public void visitClassContext(ClassContext classContext) {
        boolean fullAnalysis = AnalysisContext.currentAnalysisContext().getBoolProperty(
                FindBugsAnalysisFeatures.INTERPROCEDURAL_ANALYSIS_OF_REFERENCED_CLASSES);
        if (!fullAnalysis && !AnalysisContext.currentAnalysisContext()./*
                                                                        * getSubtypes
                                                                        * ().
                                                                        */isApplicationClass(classContext.getJavaClass()))
            return;
        if (VERBOSE_DEBUG)
            System.out.println("Visiting class " + classContext.getJavaClass().getClassName());

        for (Method m : classContext.getMethodsInCallOrder())
            considerMethod(classContext, m);
    }

    private void considerMethod(ClassContext classContext, Method method) {
        if ((method.getReturnType() instanceof ReferenceType) && classContext.getMethodGen(method) != null) {
            if (VERBOSE_DEBUG)
                System.out.println("Check " + method);
            analyzeMethod(classContext, method);
        }
    }

    protected int returnsReference;

    protected int returnsNonNull;

    private void analyzeMethod(ClassContext classContext, Method method) {
        returnsReference++;
        try {
            CFG cfg = classContext.getCFG(method);

            IsNullValueDataflow inv = classContext.getIsNullValueDataflow(method);
            boolean guaranteedNonNull = true;
            for (Iterator<Location> i = cfg.locationIterator(); i.hasNext();) {
                Location location = i.next();
                InstructionHandle handle = location.getHandle();
                Instruction ins = handle.getInstruction();

                if (!(ins instanceof ARETURN))
                    continue;
                IsNullValueFrame frame = inv.getFactAtLocation(location);
                if (!frame.isValid())
                    continue;
                IsNullValue value = frame.getTopValue();
                if (!value.isDefinitelyNotNull()) {
                    guaranteedNonNull = false;
                    break;
                }

            }

            XMethod xmethod = XFactory.createXMethod(classContext.getJavaClass(), method);
            if (guaranteedNonNull) {
                returnsNonNull++;
                AnalysisContext.currentAnalysisContext().getReturnValueNullnessPropertyDatabase()
                        .setProperty(xmethod.getMethodDescriptor(), guaranteedNonNull);
                if (DEBUG)
                    System.out.println("Unconditional deref: " + xmethod + "=" + guaranteedNonNull);

            }

        } catch (CFGBuilderException e) {
            XMethod xmethod = XFactory.createXMethod(classContext.getJavaClass(), method);

            AnalysisContext.currentAnalysisContext().getLookupFailureCallback()
                    .logError("Error analyzing " + xmethod + " for unconditional deref training", e);
        } catch (DataflowAnalysisException e) {
            XMethod xmethod = XFactory.createXMethod(classContext.getJavaClass(), method);
            AnalysisContext.currentAnalysisContext().getLookupFailureCallback()
                    .logError("Error analyzing " + xmethod + " for unconditional deref training", e);
        }
    }

}


text:
package org.destinationsol.game.screens;

import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import org.destinationsol.Const;
import org.destinationsol.GameOptions;
import org.destinationsol.SolApplication;
import org.destinationsol.common.SolColor;
import org.destinationsol.game.SolGame;
import org.destinationsol.game.item.ItemContainer;
import org.destinationsol.game.item.SolItem;
import org.destinationsol.menu.MenuLayout;
import org.destinationsol.ui.*;

import java.util.ArrayList;
import java.util.List;

public class InventoryScreen implements SolUiScreen {
  public static final ItemContainer EMPTY_CONTAINER = new ItemContainer();
  private static final int BTN_ROWS = 4;

  private static final float IMG_COL_PERC = .1f;
  private static final float EQUI_COL_PERC = .1f;
  private static final float PRICE_COL_PERC = .1f;
  private static final float AMT_COL_PERC = .1f;

  public static final float HEADER_TEXT_OFFS = .005f;

  public final ShowInventory showInventory;
  public final BuyItems buyItems;
  public final SellItems sellItems;
  public final ChangeShip changeShip;
  public final HireShips hireShips;

  private final List<SolUiControl> myControls;
  private final Rectangle myArea;
  private final Rectangle myListArea;
  private final Rectangle myDetailArea;
  private final Rectangle myItemCtrlArea;
  private final SolUiControl myPrevCtrl;
  public final SolUiControl nextCtrl;
  public final SolUiControl[] itemCtrls;
  public final SolUiControl closeCtrl;
  private final SolUiControl myUpCtrl;
  public final SolUiControl downCtrl;
  private final Vector2 myDetailHeaderPos;

  private InventoryOperations myOperations;
  private int myPage;
  private List<SolItem> mySelected;
  private final Vector2 myListHeaderPos;
  public static final float SMALL_GAP = .004f;

  public InventoryScreen(float r, GameOptions gameOptions) {
    myControls = new ArrayList<SolUiControl>();

    float contentW = .8f;
    float col0 = r / 2 - contentW / 2;
    float row0 = .2f;
    float row = row0;
    float bgGap = MenuLayout.BG_BORDER;
    float bigGap = SMALL_GAP * 6;
    float headerH = .03f;

    // list header & controls
    myListHeaderPos = new Vector2(col0 + HEADER_TEXT_OFFS, row + HEADER_TEXT_OFFS); // offset hack
    float listCtrlW = contentW * .15f;
    Rectangle nextArea = new Rectangle(col0 + contentW - listCtrlW, row, listCtrlW, headerH);
    nextCtrl = new SolUiControl(nextArea, true, gameOptions.getKeyRight());
    nextCtrl.setDisplayName(">");
    myControls.add(nextCtrl);
    Rectangle prevArea = new Rectangle(nextArea.x - SMALL_GAP - listCtrlW, row, listCtrlW, headerH);
    myPrevCtrl = new SolUiControl(prevArea, true, gameOptions.getKeyLeft());
    myPrevCtrl.setDisplayName("<");
    myControls.add(myPrevCtrl);
    row += headerH + SMALL_GAP;

    // list
    float itemRowH = .04f;
    float listRow0 = row;
    itemCtrls = new SolUiControl[Const.ITEM_GROUPS_PER_PAGE];
    for (int i = 0; i < Const.ITEM_GROUPS_PER_PAGE; i++) {
      Rectangle itemR = new Rectangle(col0, row, contentW, itemRowH);
      SolUiControl itemCtrl = new SolUiControl(itemR, true);
      itemCtrls[i] = itemCtrl;
      myControls.add(itemCtrl);
      row += itemRowH + SMALL_GAP;
    }
    myListArea = new Rectangle(col0, row, contentW, row - SMALL_GAP - listRow0);
    row += bigGap;

    // detail header & area
    myDetailHeaderPos = new Vector2(col0 + HEADER_TEXT_OFFS, row + HEADER_TEXT_OFFS); // offset hack
    row += headerH + SMALL_GAP;
    float itemCtrlAreaW = contentW * .4f;
    myItemCtrlArea = new Rectangle(col0 + contentW - itemCtrlAreaW, row, itemCtrlAreaW, .2f);
    myDetailArea = new Rectangle(col0, row, contentW - itemCtrlAreaW - SMALL_GAP, myItemCtrlArea.height);
    row += myDetailArea.height;

    // whole
    myArea = new Rectangle(col0 - bgGap, row0 - bgGap, contentW + bgGap * 2, row - row0 + bgGap * 2);

    closeCtrl = new SolUiControl(itemCtrl(3), true, gameOptions.getKeyClose());
    closeCtrl.setDisplayName("Close");
    myControls.add(closeCtrl);

    showInventory = new ShowInventory(this, gameOptions);
    buyItems = new BuyItems(this, gameOptions);
    sellItems = new SellItems(this, gameOptions);
    changeShip = new ChangeShip(this, gameOptions);
    hireShips = new HireShips(this, gameOptions);
    myUpCtrl = new SolUiControl(null, true, gameOptions.getKeyUp());
    myControls.add(myUpCtrl);
    downCtrl = new SolUiControl(null, true, gameOptions.getKeyDown());
    myControls.add(downCtrl);
  }

  @Override
  public List<SolUiControl> getControls() {
    return myControls;
  }

  @Override
  public void updateCustom(SolApplication cmp, SolInputManager.Ptr[] ptrs, boolean clickedOutside) {
    if (clickedOutside) {
      closeCtrl.maybeFlashPressed(cmp.getOptions().getKeyClose());
      return;
    }
    if (closeCtrl.isJustOff()) {
      cmp.getInputMan().setScreen(cmp, cmp.getGame().getScreens().mainScreen);
      if (myOperations != showInventory) cmp.getInputMan().addScreen(cmp, cmp.getGame().getScreens().talkScreen);
      return;
    }
    if (myPrevCtrl.isJustOff()) myPage--;
    if (nextCtrl.isJustOff()) myPage++;

    ItemContainer ic = myOperations.getItems(cmp.getGame());
    if (ic == null) ic = EMPTY_CONTAINER;
    int groupCount = ic.groupCount();
    int pageCount = groupCount / Const.ITEM_GROUPS_PER_PAGE;
    if (pageCount == 0 || pageCount * Const.ITEM_GROUPS_PER_PAGE < groupCount) pageCount += 1;
    if (myPage < 0) myPage = 0;
    if (myPage >= pageCount) myPage = pageCount - 1;

    myPrevCtrl.setEnabled(0 < myPage);
    nextCtrl.setEnabled(myPage < pageCount - 1);

    if (!ic.containsGroup(mySelected)) mySelected = null;
    int selIdx = -1;
    int offset = myPage * Const.ITEM_GROUPS_PER_PAGE;
    boolean hNew = showingHeroItems();
    for (int i = 0; i < itemCtrls.length; i++) {
      SolUiControl itemCtrl = itemCtrls[i];
      int groupIdx = offset + i;
      boolean ctrlEnabled = groupIdx < groupCount;
      itemCtrl.setEnabled(ctrlEnabled);
      if (!ctrlEnabled) continue;
      List<SolItem> group = ic.getGroup(groupIdx);
      if (hNew && ic.isNew(group)) itemCtrl.enableWarn();
      if (itemCtrl.isJustOff()) {
        mySelected = group;
      }
      if (mySelected == group) selIdx = groupIdx;
    }
    if (selIdx < 0 && groupCount > 0) {
      mySelected = ic.getGroup(offset);
    }
    if (myUpCtrl.isJustOff() && selIdx > 0) {
      selIdx--;
      mySelected = ic.getGroup(selIdx);
      if (selIdx < offset) myPage--;
    }
    if (downCtrl.isJustOff() && selIdx < groupCount - 1) {
      selIdx++;
      mySelected = ic.getGroup(selIdx);
      if (selIdx >= offset + Const.ITEM_GROUPS_PER_PAGE) myPage++;
    }
    if (mySelected != null) ic.seen(mySelected);
  }

  @Override
  public boolean isCursorOnBg(SolInputManager.Ptr ptr) {
    return myArea.contains(ptr.x, ptr.y);
  }

  @Override
  public void onAdd(SolApplication cmp) {
    if (myOperations != null) cmp.getInputMan().addScreen(cmp, myOperations);
    myPage = 0;
    mySelected = null;
  }

  @Override
  public void drawBg(UiDrawer uiDrawer, SolApplication cmp) {
    uiDrawer.draw(myArea, SolColor.UI_BG);
  }

  @Override
  public void drawImgs(UiDrawer uiDrawer, SolApplication cmp) {
    SolGame game = cmp.getGame();
    ItemContainer ic = myOperations.getItems(game);
    if (ic == null) ic = EMPTY_CONTAINER;

    float imgColW = myListArea.width * IMG_COL_PERC;
    float rowH = itemCtrls[0].getScreenArea().height;
    float imgSz = imgColW < rowH ? imgColW : rowH;

    uiDrawer.draw(myDetailArea, SolColor.UI_INACTIVE);
    for (int i = 0; i < itemCtrls.length; i++) {
      int groupIdx = myPage * Const.ITEM_GROUPS_PER_PAGE + i;
      int groupCount = ic.groupCount();
      if (groupCount <= groupIdx) continue;
      SolUiControl itemCtrl = itemCtrls[i];
      List<SolItem> group = ic.getGroup(groupIdx);
      SolItem item = group.get(0);
      TextureAtlas.AtlasRegion tex = item.getIcon(game);
      Rectangle rect = itemCtrl.getScreenArea();
      float rowCenterY = rect.y + rect.height / 2;
      uiDrawer.draw(uiDrawer.whiteTex, imgSz, imgSz, imgSz/2, imgSz/2, rect.x + imgColW/2, rowCenterY, 0, item.getItemType().uiColor);
      uiDrawer.draw(tex, imgSz, imgSz, imgSz/2, imgSz/2, rect.x + imgColW/2, rowCenterY, 0, SolColor.W);
    }
  }

  @Override
  public void drawText(UiDrawer uiDrawer, SolApplication cmp) {
    SolGame game = cmp.getGame();
    ItemContainer ic = myOperations.getItems(game);
    if (ic == null) ic = EMPTY_CONTAINER;

    float imgColW = myListArea.width * IMG_COL_PERC;
    float equiColW = myListArea.width * EQUI_COL_PERC;
    float priceWidth = myListArea.width * PRICE_COL_PERC;
    float amtWidth = myListArea.width * AMT_COL_PERC;
    float nameWidth = myListArea.width - imgColW - equiColW - priceWidth - amtWidth;
    for (int i = 0; i < itemCtrls.length; i++) {
      int groupIdx = myPage * Const.ITEM_GROUPS_PER_PAGE + i;
      int groupCount = ic.groupCount();
      if (groupCount <= groupIdx) continue;
      SolUiControl itemCtrl = itemCtrls[i];
      List<SolItem> group = ic.getGroup(groupIdx);
      SolItem item = group.get(0);
      Rectangle rect = itemCtrl.getScreenArea();
      float rowCenterY = rect.y + rect.height / 2;
      if (myOperations.isUsing(game, item)) uiDrawer.drawString("using", rect.x + imgColW + equiColW/2, rowCenterY, FontSize.WINDOW, true, SolColor.W);
      uiDrawer.drawString(item.getDisplayName(), rect.x + equiColW + imgColW + nameWidth/2, rowCenterY, FontSize.WINDOW, true, mySelected == group ? SolColor.W : SolColor.G);
      int count = ic.getCount(groupIdx);
      if (count > 1) {
        uiDrawer.drawString("x" + count, rect.x + rect.width - amtWidth/2, rowCenterY, FontSize.WINDOW, true, SolColor.W);
      }
      float mul = myOperations.getPriceMul();
      if (mul > 0) {
        float price = item.getPrice() * mul;
        uiDrawer.drawString("$" + (int)price, rect.x + rect.width - amtWidth - priceWidth/2, rowCenterY, FontSize.WINDOW, true, SolColor.LG);
      }
    }

    uiDrawer.drawString(myOperations.getHeader(), myListHeaderPos.x, myListHeaderPos.y, FontSize.WINDOW, false, SolColor.W);
    uiDrawer.drawString("Selected Item:", myDetailHeaderPos.x, myDetailHeaderPos.y, FontSize.WINDOW, false, SolColor.W);
    if (mySelected != null && !mySelected.isEmpty()) {
      SolItem selItem = mySelected.get(0);
      String desc = selItem.getDisplayName() + "\n" + selItem.getDesc();
      uiDrawer.drawString(desc, myDetailArea.x + .015f, myDetailArea.y + .015f, FontSize.WINDOW, false, SolColor.W);
    }
  }

  @Override
  public boolean reactsToClickOutside() {
    return true;
  }

  @Override
  public void blurCustom(SolApplication cmp) {
    if (!showingHeroItems()) return;
    SolGame game = cmp.getGame();
    ItemContainer items = myOperations.getItems(game);
    if (items != null) items.seenAll();
  }

  private boolean showingHeroItems() {
    return myOperations == showInventory || myOperations == sellItems;
  }

  public void setOperations(InventoryOperations operations) {
    myOperations = operations;
  }

  public Rectangle itemCtrl(int row) {
    float h = (myItemCtrlArea.height - SMALL_GAP * (BTN_ROWS - 1)) / BTN_ROWS;
    return new Rectangle(myItemCtrlArea.x, myItemCtrlArea.y + (h + SMALL_GAP) * row, myItemCtrlArea.width, h);
  }

  public List<SolItem> getSelected() {
    return mySelected;
  }

  public SolItem getSelectedItem() {
    return mySelected == null || mySelected.isEmpty() ? null : mySelected.get(0);
  }

  public void setSelected(List<SolItem> selected) {
    mySelected = selected;
  }

  public InventoryOperations getOperations() {
    return myOperations;
  }

  public int getPage() {
    return myPage;
  }
}


text:
<!doctype html>

    <title>Code coverage report for lib/strategy/EnrichIntegrationFromRemoteConfigStrategy.js</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="../../prettify.css" />
    <link rel="stylesheet" href="../../base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

      all files / lib/strategy/ EnrichIntegrationFromRemoteConfigStrategy.js

        85.44%
        Statements
        88/103

        66.67%
        Branches
        38/57

        89.29%
        Functions
        25/28

        85.44%
        Lines
        88/103

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246

1×
1×
1×

1×
1×

1×
6×
6×
1×

5×

1×
5×
5×

5×
1×
4×
1×

3×

1×
3×
3×

3×

3×

1×
3×
3×

3×
3×

3×
1×
1×

1×
1×
1×

1×

1×

1×
1×
1×

1×

1×
1×

1×
1×

1×
1×

1×

3×

1×
3×

3×
3×

3×

3×
1×

1×
1×

2×

1×
7×
2×

5×
10×

5×
13×
13×

13×

5×
5×

5×

5×
1×

4×
4×

4×

4×

4×

1×
6×

6×

6×

6×
6×

6×

6×
6×
6×

1×

'use strict';

var async = require('async');
var extend = require('cloneextend').extend;
var strings = require('../strings');

/**
 * Retrieves Stormpath settings from the API service, and ensures the local
 * configuration object properly reflects these settings.
 *
 * @class
*/
function EnrichIntegrationFromRemoteConfigStrategy (clientFactory) {
  this.clientFactory = clientFactory;
}

EnrichIntegrationFromRemoteConfigStrategy.prototype._resolveApplication = function (config, callback) {
  var application = config.application;
  if (!application || !application.href || !application.getAccountStoreMappings) {
    callback(new Error(strings.UNABLE_TO_RESOLVE_APP));
  } else {
    callback(null, config.application);
  }
};

EnrichIntegrationFromRemoteConfigStrategy.prototype._validateAccountStore = function (config, app, callback) {
  app.getAccountStoreMappings(function (err, mappings) {
    Iif (err) {
      return callback(err);
    }

    if (mappings.size === 0) {
      return callback(new Error(strings.NO_ACCOUNT_STORES_MAPPED));
    } else if (config.web.register.enabled && app.defaultAccountStoreMapping === null) {
      return callback(new Error(strings.NO_DEFAULT_ACCOUNT_STORE_MAPPED));
    }

    callback(null, app);
  });
};

// Returns the OAuth policy of the Stormpath Application.
EnrichIntegrationFromRemoteConfigStrategy.prototype._enrichWithOAuthPolicy = function (app, callback) {
  app.getOAuthPolicy(function(err, policy) {
    Iif (err) {
      return callback(err);
    }

    app.oAuthPolicy = policy;

    return callback(null, app);
  });
};

// Iterate over all account stores on the given Application, looking for all
// Social providers.  We'll then create a config.providers array which we'll
// use later on to dynamically populate all social login configurations ^^
EnrichIntegrationFromRemoteConfigStrategy.prototype._enrichWithSocialProviders = function (config, application, callback) {
  application.getAccountStoreMappings(function(err, mappings) {
    Iif (err) {
      return callback(err);
    }

    Eif (!config.socialProviders) {
      config.socialProviders = {};
    }

    mappings.each(function (mapping, next) {
      mapping.getAccountStore(function (err, accountStore) {
        Iif (err) {
          return next(err);
        }

        // Iterate directories
        Eif (/\/directories/.test(accountStore.href)) {
          accountStore.getProvider(function(err, remoteProvider) {
            Iif (err) {
              return next(err);
            }

            var providerId = remoteProvider.providerId;

            // If the provider isn't a Stormpath, AD, or LDAP directory it's a social directory.
            Eif (['stormpath', 'ad', 'ldap'].indexOf(providerId) === -1) {
              // Remove unnecessary properties that clutter our config.
              delete remoteProvider.href;
              delete remoteProvider.createdAt;
              delete remoteProvider.updatedAt;

              var localProvider = config.socialProviders[providerId];

              Eif (!localProvider) {
                localProvider = config.socialProviders[providerId] = {};
              }

              Eif (!localProvider.callbackUri) {
                localProvider.callbackUri = '/callbacks/' + remoteProvider.providerId;
              }

              extend(remoteProvider, { enabled: true });
              extend(localProvider, remoteProvider);
            }

            next();
          });
        } else {
          next();
        }
      });
    }, function(err) {
      callback(err, application);
    });
  });
};

// Finds and returns an Application's default Account Store (Directory)
// object.  If one doesn't exist, nothing will be returned.
EnrichIntegrationFromRemoteConfigStrategy.prototype._resolveDirectoryHref = function (app, callback) {
  var outerScope = this;

  app.getAccountStoreMappings(function(err, mappings) {
    Iif (err) {
      return callback(err);
    }

    mappings.detect(function(mapping, detectCallback) {
      detectCallback(mapping.isDefaultAccountStore);
    }, function(defaultMapping) {
      if (defaultMapping) {
        var href = defaultMapping.accountStore.href;

        Eif (href.match(/directories/)) {
          return callback(null, href);
        }

        if (href.match(/group/)) {
          outerScope.client.getGroup(href, function(err, group) {
            return callback(err, group && group.directory.href);
          });
        } else {
          return callback(null, null);
        }
      } else {
        return callback(null, null);
      }
    });
  });
};

// Pulls down all of a Directory's configuration settings,
// and applies them to the local configuration.
EnrichIntegrationFromRemoteConfigStrategy.prototype._enrichWithDirectoryPolicies = function (client, config, directoryHref, callback) {
  if (!directoryHref) {
    return callback(null, null);
  }

  // Helper method that checks if a status is set to "enabled".
  var isEnabled = function (status) {
    return status === 'ENABLED';
  };

  // Returns the callback immediately if there is an error.
  // Continues processing if there isn't.
  var stopIfError = function (process) {
    return function (err, result) {
      Iif (err) {
        callback(err);
      } else {
        process(result);
      }
    }
  };

  // Enrich config with with directory policies.
  client.getDirectory(directoryHref, { expand: 'passwordPolicy,accountCreationPolicy' }, stopIfError(function (directory) {
    var resetEmailStatusEnabled = isEnabled(directory.passwordPolicy.resetEmailStatus);

    // Enrich config with account policies.
    extend(config, {
      web: {
        forgotPassword: {
          enabled: resetEmailStatusEnabled
        },
        changePassword: {
          enabled: resetEmailStatusEnabled
        },
        verifyEmail: {
          enabled: isEnabled(directory.accountCreationPolicy.verificationEmailStatus)
        }
      }
    });

    // Validate that auto login and email verification aren't enabled at the same time.
    if (config.web.register.autoLogin && config.web.verifyEmail.enabled) {
      return callback(new Error(strings.CONFLICTING_AUTO_LOGIN_AND_EMAIL_VERIFICATION_CONFIG));
    }

    // Enrich config with password policies.
    directory.getPasswordPolicy(stopIfError(function (policy) {
      policy.getStrength(stopIfError(function (strength) {
        // Remove the href property from the Strength Resource, we don't want
        // this to clutter up our nice passwordPolicy configuration
        // dictionary!
        delete strength.href;

        config.passwordPolicy = strength;

        callback(null, null);
      }));
    }));
  }));
};

EnrichIntegrationFromRemoteConfigStrategy.prototype.process = function (config, callback) {
  var tasks = [];

  Iif (config.skipRemoteConfig) {
    return callback(null, config);
  }

  var client = this.clientFactory(config);

  Eif (config.application && config.application.href) {
    tasks = tasks.concat([
      this._resolveApplication.bind(this, config),
      this._validateAccountStore.bind(this, config),
      this._enrichWithOAuthPolicy.bind(this),
      this._enrichWithSocialProviders.bind(this, config),
      this._resolveDirectoryHref.bind(this),
      this._enrichWithDirectoryPolicies.bind(this, client, config)
    ]);
  }

  client.on('error', function (err) {
    callback(err);
  });

  client.on('ready', function () {
    async.waterfall(tasks, function (err) {
      callback(err, err ? null : config);
    });
  });
};

module.exports = EnrichIntegrationFromRemoteConfigStrategy;

  Code coverage
  generated by istanbul at Thu Feb 18 2016 20:10:44 GMT-0800 (PST)


text:
module MotionPrime
  class SlidingCellElement < BaseElement
    def view_class
      "SlidingCellView"
    end
  end
end


text:
/**
 * A sample application to show how to get Area Learning Data using Project
 * Tango API.
 */
package com.projecttango.examples.java.helloareadescription;


text:
Code

{% highlight js %}
Ink.requireModules(['Ink.Util.String_1'], function(InkString) {

    var result1 = InkString.unescape('\x000063');
    Ink.log(result1); // c

    var result2 = InkString.unescape('\x0000E7');
    Ink.log(result2); // ç
});
{% endhighlight %}


text:
<?php

namespace ErrorStream\ErrorStream\Facades;

use Illuminate\Support\Facades\Facade;

class ErrorStream extends Facade
{
    protected static function getFacadeAccessor()
    {
        return 'errorstream';
    }
}