text:
title: "Must read: James Socol's Best Basic Security Practices (Especially with Django)"
date: 2012-08-24
tags: [must read, django, security]
abstract: James Socol, the Community Platforms Manager at Mozilla, is writing a great summary about best security pratices web developers must be aware of. Even if mainly focused on Django ironing, it's a must read for every web developer.

Point your browser on [James Socol's website, Cofffe on the keyboard](http://coffeeonthekeyboard.com) and bookmark it. James - the Community Platforms Manager at Mozilla - is writing a great summary about web security focused on Django applications, but valid nonetheless for every framework.

These are the arguments he's covering:

* Basics: locking your car doors.
    * Password Storage
    * XSS: Cross-Site Scripting
    * CSRF: Cross-Site Request Forgeries
    * Injections, SQL and Otherwise
    * Access Control
    * Session Fixation and Hijacking
    * Server Configuration
    * Click-jacking and a little Phishing
    * Stay Up to Date
* Advanced: Some gotchas from my experience and some things you may well see.
    * Mass Assignment
    * Cache Poisoning
    * Bots: Spam, Brute-force, and User Experience
    * PCI-DSS
    * CEF Logging
* What browsers are doing to help.
    * Content Security Policy
    * X-Frame-Options
    * Do Not Track
** Sandboxing

[This](http://coffeeonthekeyboard.com/best-basic-security-practices-especially-with-django-697/) is the link to the summary article.

## Mozilla and Django

Maybe you don't know it, but Mozilla uses Django for a lot of things. For example, addons.mozilla.org is based on Django and the [sources are available on GitHub](https://github.com/mozilla/zamboni).

If you're interested about Django and Mozilla, you should check [Mozilla Webdev blog](http://blog.mozilla.org/webdev/tag/django/).

## Read it!

I can't stress it enough: it's a must read for every web developer.


text:
body {
   margin: 0;
   padding: 0;
   border: 0;
   width: 100%;
   height: 100%;
   overflow: hidden;
}

a {
  color: #337ab7;
  text-decoration: none;
}
a:hover,
a:focus {
  color: #23527c;
  text-decoration: none;
}

/*.mini-grid-headerCell-inner {
   line-height: 34px !important;
}*/

.mini-toolbar {
   border: none !important;
   background: #fff !important
}

.mini-grid-row .mini-grid-cell,
.mini-grid-row .mini-grid-headerCell,
.mini-grid-row .mini-grid-filterCell,
.mini-grid-summaryCell {
   padding-top: 3px !important;
   padding-bottom: 3px !important;
}

.mini-panel-header {
   border-bottom: #f2f2f2 !important;
}

.mini-panel-header-inner {
   background: #f2f2f2 !important;
   border-bottom: none !important;
}
/*
   .mini-panel-header-inner .mini-panel-title{
     display:block !important;
     width:100% !important;
     text-align:center !important
 }
*/

label {
   font-weight: normal !important;
}

/* GDH 2016.12.15---------------*/
.list-action-cannot{
  text-decoration:none;color:lightgrey;
}
.list-action-can{
  cursor:pointer;text-decoration:none;
}
/* ---------------GDH 2016.12.15*/

redpajama_set_name: RedPajamaGithub


text:
package com.github.dan4ik95dv.famousartists.model.yandex;

import com.github.dan4ik95dv.famousartists.model.realm.RealmInteger;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import io.realm.RealmList;
import io.realm.RealmObject;

public class Artists extends RealmObject {

    @SerializedName("items")
    @Expose
    private RealmList<Item> items;
    @SerializedName("total")
    @Expose
    private RealmInteger total;
    @SerializedName("perPage")
    @Expose
    private RealmInteger perPage;

    /**
     * @return The items
     */
    public RealmList<Item> getItems() {
        return items;
    }

    /**
     * @param items The items
     */
    public void setItems(RealmList<Item> items) {
        this.items = items;
    }

    /**
     * @return The total
     */
    public Integer getTotal() {
        return total.getValue();
    }

    /**
     * @param total The total
     */
    public void setTotal(Integer total) {
        this.total = new RealmInteger(total);
    }

    /**
     * @return The perPage
     */
    public Integer getPerPage() {
        return perPage.getValue();
    }

    /**
     * @param perPage The perPage
     */
    public void setPerPage(Integer perPage) {
        this.perPage = new RealmInteger(perPage);
    }

}


text:
Images

  Images are vertically aligned to the middle of container and have
  box-sizing set to content-box.

  Replace any element that contains text with an image:

@include img-replace($path, $width, $height);

  Usage:

.logo {
  @include img-replace('path/to/img.svg', 100px, 40px);
}

Image Helpers


text:
void fl_register_plugins(FlPluginRegistry* registry) {
  g_autoptr(FlPluginRegistrar) cronet_registrar =
      fl_plugin_registry_get_registrar_for_plugin(registry, "CronetPlugin");
  cronet_plugin_register_with_registrar(cronet_registrar);
}


text:
package twitter4s.request

import http.client.method.HttpMethod
import http.client.request.{CompletionEvaluation, OrElseCompletionEvaluation, TrueCompletionEvaluation}
import http.client.response.{HttpHeader, HttpResponse}
import play.api.libs.json.{JsSuccess, Json}
import twitter4s.response.TwitterEmptyResponseBodyCompletionEvaluation
import play.api.libs.json.JsError

object TwitterTimelineRequest {
  case class DataId(id: Long)
  implicit val dataIdFmt = Json.format[DataId]
}

case class TwitterTimelineRequest(
  baseUrl:                   String,
  relativeUrl:               String,
  headers:                   Seq[HttpHeader],
  queryString:               Map[String, Seq[String]],
  body:                      Option[Array[Byte]],
  method:                    HttpMethod,
  paginated:                 Boolean,
  authHeaderGen:             (TwitterRequest) ⇒ TwitterAuthorizationHeader,
  customCompletionEvaluator: Option[CompletionEvaluation]                  = None)
    extends TwitterRequest {

  override val completionEvaluator = if (paginated) {
    customCompletionEvaluator match {
      case Some(c) ⇒ OrElseCompletionEvaluation(customCompletionEvaluator.get, TrueCompletionEvaluation)
      case _       ⇒ TwitterEmptyResponseBodyCompletionEvaluation
    }
  } else TrueCompletionEvaluation

  override def nextRequest(response: HttpResponse): TwitterRequest = {
    // take last item in data, take it's ID, subtract 1 from it, and set it as max_id.
    response.json.validate[Array[TwitterTimelineRequest.DataId]] match {
      case s: JsSuccess[Array[TwitterTimelineRequest.DataId]] ⇒
        // we subtract 1 in order not to re-include the last item in the timeline

        // TODO: make sure we remove max_id before adding the new one

        val newQS = queryString + ("max_id" → Seq((s.get.last.id - 1).toString))
        val requestWithnewQS = copy(queryString = newQS)
        requestWithnewQS.copy(
          headers = TwitterRequest.newAuthHeaderForRequest(requestWithnewQS))

      case e: JsError ⇒

        // sometimes it's not an array
        response.json.validate[TwitterTimelineRequest.DataId] match {
          case s1: JsSuccess[TwitterTimelineRequest.DataId] ⇒
            val newQS = queryString + ("max_id" → Seq((s1.get.id - 1).toString))
            val requestWithnewQS = copy(queryString = newQS)
            requestWithnewQS.copy(
              headers = TwitterRequest.newAuthHeaderForRequest(requestWithnewQS))

          case e1: JsError ⇒
            // TODO: how do we handle this case?
            println(s"OH NO! Could not find data with an id in \n${response.json.toString}\n Caused by JsError.toJson(e).toString")
            val newQS = queryString + ("max_id" → Seq(0.toString))
            val requestWithnewQS = copy(queryString = newQS)
            requestWithnewQS.copy(
              headers = TwitterRequest.newAuthHeaderForRequest(requestWithnewQS))
        }
    }
  }

  override protected def withoutHeader(httpHeaderName: String): TwitterRequest = {
    copy(headers = headers.filterNot(_.name == httpHeaderName))
  }
}


text:
package org.febit.schedule.cron;

import org.febit.lang.Time;

/**
 *
 * @author zqq90
 */
public interface Matcher {

    final static Matcher MATCH_ALL = (Time time) -> true;

    boolean match(Time time);
}


text:
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "tensorflow/lite/delegates/flex/delegate.h"
#include "tensorflow/lite/delegates/flex/delegate_data.h"
#include "tensorflow/lite/delegates/flex/test_util.h"

extern const std::string GetDimsDebugString(const TfLiteIntArray* dims);

namespace tflite {
namespace flex {
namespace testing {

using ::testing::ContainsRegex;
using ::testing::ElementsAre;
using ::testing::ElementsAreArray;

// A testing flex delegate that supports every node regardless whether it's
// actually supported or not. It's only for testing certain scenarios.
class TestFlexDelegate : public FlexDelegate {
 protected:
  bool IsNodeSupportedByDelegate(const TfLiteRegistration* registration,
                                 const TfLiteNode* node,
                                 TfLiteContext* context) const override {
    return true;
  }
};

class KernelTest : public testing::FlexModelTest {
 public:
  static constexpr int kOnes = 1;  // This is the index of a tensor of 1's.
  static constexpr int kTwos = 2;  // This is the index of a tensor of 2's.
  static constexpr int kMaxTensors = 30;

  KernelTest() { interpreter_.reset(new Interpreter(&error_reporter_)); }

  void ApplyFlexDelegate(std::unique_ptr<FlexDelegate> delegate = nullptr) {
    auto flex_delegate = FlexDelegate::Create(std::move(delegate));
    auto* delegate_data =
        reinterpret_cast<FlexDelegate*>(flex_delegate->data_)->mutable_data();
    CHECK(delegate_data->Prepare(tensorflow::SessionOptions{}).ok());
    CHECK(interpreter_->ModifyGraphWithDelegate(std::move(flex_delegate)) ==
          kTfLiteOk);
  }
};

TEST_F(KernelTest, FullGraph) {
  // Define the graph.
  AddTensors(9, {0, 3}, {8}, kTfLiteFloat32, {3});

  AddTfOp(testing::kUnpack, {0}, {1, 2});
  AddTfOp(testing::kUnpack, {3}, {4, 5});
  AddTfOp(testing::kAdd, {1, 4}, {6});
  AddTfOp(testing::kAdd, {2, 5}, {7});
  AddTfOp(testing::kMul, {6, 7}, {8});

  ApplyFlexDelegate();

  // Define inputs.
  SetShape(0, {2, 2, 1});
  SetValues(0, {1.1f, 2.2f, 3.3f, 4.4f});
  SetShape(3, {2, 2, 1});
  SetValues(3, {1.1f, 2.2f, 3.3f, 4.4f});

  ASSERT_TRUE(Invoke());

  ASSERT_THAT(GetShape(8), ElementsAre(2, 1));
  ASSERT_THAT(GetValues(8), ElementsAre(14.52f, 38.72f));

  // Try again with different inputs
  SetShape(0, {2, 3, 1});
  SetValues(0, {2.0f, 2.0f, 3.0f, 3.0f, 4.0f, 4.0f});
  SetShape(3, {2, 3, 1});
  SetValues(3, {2.0f, 2.0f, 3.0f, 3.0f, 4.0f, 4.0f});

  ASSERT_TRUE(Invoke());

  ASSERT_THAT(GetShape(8), ElementsAre(3, 1));
  ASSERT_THAT(GetValues(8), ElementsAre(24.0f, 32.0f, 48.0f));
}

TEST_F(KernelTest, BadTensorFlowOp) {
  AddTensors(2, {0}, {1}, kTfLiteFloat32, {3});
  AddTfOp(testing::kNonExistent, {0}, {1});

  ApplyFlexDelegate(std::unique_ptr<FlexDelegate>(new TestFlexDelegate()));

  ASSERT_NE(interpreter_->AllocateTensors(), kTfLiteOk);
  ASSERT_THAT(error_reporter().error_messages(),
              ContainsRegex("Op type not registered 'NonExistentOp'"));
}

TEST_F(KernelTest, BadNumberOfOutputs) {
  AddTensors(3, {0}, {1, 2}, kTfLiteFloat32, {3});
  AddTfOp(testing::kIdentity, {0}, {1, 2});

  ApplyFlexDelegate();

  SetShape(0, {2, 2, 1});
  SetValues(0, {1.1f, 2.2f, 3.3f, 4.4f});

  ASSERT_FALSE(Invoke());
  ASSERT_THAT(error_reporter().error_messages(),
              ContainsRegex("Unexpected number of outputs"));
}

TEST_F(KernelTest, IncompatibleNodeDef) {
  AddTensors(2, {0}, {1}, kTfLiteFloat32, {3});

  // Cast is a TF op, but we don't add the proper nodedef to it in AddTfOp.
  AddTfOp(testing::kIncompatibleNodeDef, {0}, {1});

  ApplyFlexDelegate();

  SetShape(0, {2, 2, 1});
  SetValues(0, {1.1f, 2.2f, 3.3f, 4.4f});

  ASSERT_FALSE(Invoke());
  ASSERT_THAT(error_reporter().error_messages(),
              ContainsRegex("while executing 'Cast' via Eager"));
}

TEST_F(KernelTest, WrongSetOfNodes) {
  AddTensors(4, {0}, {3}, kTfLiteFloat32, {3});
  AddTfOp(testing::kUnpack, {0}, {1, 2});
  AddTfLiteMulOp({1, 2}, {3});

  // Specify that testing::kMul (#1) is supported when it actually isn't so that
  // we choose to use the TestFlexDelegate that supports every node regardless
  // whether it's actually supported or not.
  ApplyFlexDelegate(std::unique_ptr<FlexDelegate>(new TestFlexDelegate()));

  ASSERT_NE(interpreter_->AllocateTensors(), kTfLiteOk);
  ASSERT_THAT(error_reporter().error_messages(),
              ContainsRegex("Cannot convert empty data into a valid NodeDef"));
}

TEST_F(KernelTest, MixedGraph) {
  AddTensors(9, {0, 3}, {8}, kTfLiteFloat32, {3});

  AddTfOp(testing::kUnpack, {0}, {1, 2});
  AddTfOp(testing::kUnpack, {3}, {4, 5});
  AddTfOp(testing::kAdd, {1, 4}, {6});
  AddTfOp(testing::kAdd, {2, 5}, {7});
  AddTfLiteMulOp({6, 7}, {8});

  ApplyFlexDelegate();

  SetShape(0, {2, 2, 1});
  SetValues(0, {1.1f, 2.2f, 3.3f, 4.4f});
  SetShape(3, {2, 2, 1});
  SetValues(3, {1.1f, 2.2f, 3.3f, 4.4f});

  ASSERT_TRUE(Invoke());

  ASSERT_THAT(GetShape(8), ElementsAre(2, 1));
  ASSERT_THAT(GetValues(8), ElementsAre(14.52f, 38.72f));
}

// We will build a complex graph where most of the ops are TF ops, but one
// of them, right in the middle is handle natively by TF Lite. This results
// in two flex subgraphs to handle the TF ops, and some of the tensors
// connect those two subgraphs directly.
TEST_F(KernelTest, SplitGraph) {
  std::vector<float> a = {3.0f, 1.0f, 0.5f, -1.0f, 4.0f, -1.0f, -2.0f, 5.0f};
  std::vector<float> b = {0.0f, 1.0f, 1.5f, 3.0f};

  AddTensors(18, {0, 1}, {17}, kTfLiteFloat32, {3});

  // Split the first input. Each branch below uses one half of it.
  AddTfOp(testing::kUnpack, {0}, {2, 10});

  // The left branch: l = (a0 + b0) * (a2 + b2) + (a1 + b1) * (a3 + b3) = 10
  AddTfOp(testing::kAdd, {1, 2}, {3});     // => 3, 2, 2, 2
  AddTfOp(testing::kUnpack, {3}, {4, 5});  // => 3, 2 --- 2, 2
  AddTfLiteMulOp({4, 5}, {6});             // => 6, 4
  AddTfOp(testing::kUnpack, {6}, {7, 8});  // => 6 -- 4
  AddTfOp(testing::kAdd, {7, 8}, {9});     // => 10

  // The right branch: r = (a4 + a6) + (a5 + a7) = 6
  AddTfOp(testing::kUnpack, {10}, {11, 12});  // => 4, -1 --- -2, 5
  AddTfOp(testing::kAdd, {11, 12}, {13});     // => 2, 4
  AddTfOp(testing::kUnpack, {13}, {14, 15});  // => 2 --- 4
  AddTfOp(testing::kAdd, {14, 15}, {16});     // => 6

  // The two branches added together:
  AddTfOp(testing::kAdd, {9, 16}, {17});  // => 16

  ApplyFlexDelegate();

  SetShape(0, {2, 2, 2, 1});
  SetValues(0, a);
  SetShape(1, {2, 2, 1});
  SetValues(1, b);

  ASSERT_TRUE(Invoke());

  ASSERT_THAT(GetShape(17), ElementsAre(1));
  ASSERT_THAT(GetValues(17), ElementsAre(16.0f));

  // Same as above but with slightly different output.
  // We still expect the result to be l + r where
  //     l = (a0 + b0) * (a2 + b2) + (a1 + b1) * (a3 + b3)
  //     r = (a4 + a6) + (a5 + a7)
  SetShape(0, {2, 2, 2, 1});
  SetValues(0, {4.0f, 1.0f, 1.5f, -2.0f, 2.0f, 0.0f, -2.0f, 3.0f});
  SetShape(1, {2, 2, 1});
  SetValues(1, {0.0f, 2.0f, 1.5f, 3.0f});
  // So l = (4 + 0) * (1.5 + 1.5) + (1 + 2) * (-2 + 3) =  12 + 3 = 15
  //    r = (2 - 2) + (0 + 3) = 3

  ASSERT_TRUE(Invoke());

  ASSERT_THAT(GetShape(17), ElementsAre(1));
  ASSERT_THAT(GetValues(17), ElementsAre(18.0f));
}

class MultipleSubgraphsTest : public KernelTest {
 public:
  static constexpr int kInput = 0;

  void PrepareInterpreter(const std::vector<float>& input) {
    ApplyFlexDelegate();

    SetShape(kOnes, {3});
    SetValues(kOnes, {1.0f, 1.0f, 1.0f});
    SetShape(kTwos, {3});
    SetValues(kTwos, {2.0f, 2.0f, 2.0f});

    SetValues(kInput, input);
  }

  std::vector<float> Apply(const std::vector<float>& input,
                           std::function<float(float)> function) {
    std::vector<float> result;
    for (float f : input) {
      result.push_back(function(f));
    }
    return result;
  }
};

TEST_F(MultipleSubgraphsTest, ForwardabilityIsLocal) {
  AddTensors(kMaxTensors, {kInput, kOnes, kTwos}, {12}, kTfLiteFloat32, {3});

  // Only TF tensors can be forwarded, so we build a small first graph
  // to produce tensor #10. Here #10 is forwardable, because it is only
  // used once, as an output.
  AddTfOp(testing::kAdd, {0, kOnes}, {3});
  AddTfOp(testing::kAdd, {0, kOnes}, {10});

  // The second TF graph, separated from the former by a TF Lite
  // multiplication, will consume tensor #10, which is not forwardable here
  // since it is used by more than one op. The existing code will forward the
  // tensor anyway, because it was deemed to be forwardable by the previous
  // subgraph.
  AddTfLiteMulOp({3, kTwos}, {4});
  AddTfOp(testing::kAdd, {10, 4}, {11});
  AddTfOp(testing::kAdd, {11, 10}, {7});

  // And a simple TF Lite op trying to access tensor #10, which was removed
  // from the buffer map. It will cause Invoke() to fail.
  AddTfLiteMulOp({10, 7}, {12});

  auto input = {3.0f, 4.0f, 5.0f};
  PrepareInterpreter(input);

  ASSERT_TRUE(Invoke());
  ASSERT_THAT(GetValues(12), ElementsAreArray(Apply(input, [](float in) {
                return (4 * in + 4) * (in + 1);
              })));
}

// Subgraphs should not remove input tensors from the buffer_map, since
// they could be necessary for downstream graphs.
TEST_F(MultipleSubgraphsTest, DoNotRemoveInputTensors) {
  AddTensors(kMaxTensors, {kInput, kOnes, kTwos}, {12}, kTfLiteFloat32, {3});

  // Only TF tensors can be removed, so we build a small first graph
  // to produce tensor #10. We make sure it is used by more than one
  // op, so it is not forwardable here.
  AddTfOp(testing::kAdd, {0, kOnes}, {3});
  AddTfOp(testing::kAdd, {0, kOnes}, {10});
  AddTfOp(testing::kAdd, {10, kOnes}, {15});
  AddTfOp(testing::kAdd, {10, kOnes}, {16});

  // The second TF graph, separated from the former by a TF Lite
  // multiplication, will consume tensor #10. The existing code will remove
  // from the buffer_map all tensors that are not outputs, so #10 will
  // disappear. Note that we are using #10 in two ops, so it is not forwardable
  // either.
  AddTfLiteMulOp({3, kTwos}, {4});
  AddTfOp(testing::kAdd, {10, 4}, {11});
  AddTfOp(testing::kAdd, {10, 11}, {7});

  // And a simple TF Lite op trying to access tensor #10, which was removed
  // from the buffer map. It will cause Invoke() to fail.
  AddTfLiteMulOp({10, 7}, {12});

  auto input = {3.0f, 4.0f, 5.0f};
  PrepareInterpreter(input);

  ASSERT_TRUE(Invoke());
  ASSERT_THAT(GetValues(12), ElementsAreArray(Apply(input, [](float in) {
                return (4 * in + 4) * (in + 1);
              })));
}

// A tensor is deemed forwardable but it happens to be the input to
// more than one subgraph. It should not be forwarded, otherwise its
// contents will be overwritten.
TEST_F(MultipleSubgraphsTest, DoNotForwardInputTensors) {
  AddTensors(kMaxTensors, {kInput, kOnes, kTwos}, {12}, kTfLiteFloat32, {3});

  // Only TF tensors can be forwarded, so we build a small first graph
  // to produce tensor #10.
  AddTfOp(testing::kAdd, {0, kOnes}, {3});
  AddTfOp(testing::kAdd, {0, kOnes}, {10});

  // The second TF graph, separated from the former by a TF Lite
  // multiplication, will consume tensor #10 and will think it is forwardable
  // because it is used by a single op. However, the subgraph doesn't have
  // enough information to make that judgment, as the input tensor could be
  // used by another graph further downstream. The existing code will forward
  // the tensor and remove it from the buffer_map, causing a failure later.
  AddTfLiteMulOp({3, kTwos}, {4});
  AddTfOp(testing::kAdd, {10, 4}, {11});
  AddTfOp(testing::kAdd, {11, 4}, {7});

  // And a simple TF Lite op trying to access tensor #10, which was removed
  // from the buffer map. It will cause Invoke() to fail.
  AddTfLiteMulOp({10, 7}, {12});

  auto input = {3.0f, 4.0f, 5.0f};
  PrepareInterpreter(input);

  ASSERT_TRUE(Invoke());
  ASSERT_THAT(GetValues(12), ElementsAreArray(Apply(input, [](float in) {
                return (5 * in + 5) * (in + 1);
              })));
}

tensorflow::OpDef MakeOpDef(int num_inputs, int num_outputs) {
  tensorflow::OpRegistrationData op_reg_data;
  tensorflow::OpDefBuilder b("dummy");
  for (int i = 0; i < num_inputs; ++i) {
    b.Input(tensorflow::strings::StrCat("i", i, ": float"));
  }
  for (int i = 0; i < num_outputs; ++i) {
    b.Output(tensorflow::strings::StrCat("o", i, ": float"));
  }
  CHECK(b.Attr("foo:string").Finalize(&op_reg_data).ok());
  return op_reg_data.op_def;
}

tensorflow::PartialTensorShape S(
    std::initializer_list<tensorflow::int64> dims) {
  return tensorflow::PartialTensorShape(dims);
}

TEST(ValidateOutputTensorShapeConsistencyTest, ShapeHandleDebugString) {
  // Setup test to contain an input tensor list of size 3.
  tensorflow::OpDef op_def = MakeOpDef(4, 1);
  tensorflow::NodeDef def;
  tensorflow::shape_inference::InferenceContext c(
      0, def, op_def, {S({1}), S({2, 3}), S({4, 5, 6}), {}}, {}, {}, {});
  c.SetInput(3, c.UnknownShape());

  std::vector<tensorflow::shape_inference::ShapeHandle> shapes;
  EXPECT_EQ("[1]", c.DebugString(c.input(0)));
  EXPECT_EQ("[2,3]", c.DebugString(c.input(1)));
  EXPECT_EQ("[4,5,6]", c.DebugString(c.input(2)));
  // c.DebugString() returns "?" for the unknown shape which is different with
  // "-1" of TFLite. But this is intended behavior since we should use dynamic
  // tensor for unknown shape so the shape comparison must fail.
  EXPECT_EQ("?", c.DebugString(c.input(3)));
}

TEST(ValidateOutputTensorShapeConsistencyTest, GetDimsDebugString) {
  TfLiteIntArray* dims1 = TfLiteIntArrayCreate(1);
  dims1->data[0] = 1;
  EXPECT_EQ("[1]", GetDimsDebugString(dims1));
  free(dims1);

  TfLiteIntArray* dims2 = TfLiteIntArrayCreate(2);
  dims2->data[0] = 2;
  dims2->data[1] = 3;
  EXPECT_EQ("[2,3]", GetDimsDebugString(dims2));
  free(dims2);

  TfLiteIntArray* dims3 = TfLiteIntArrayCreate(3);
  dims3->data[0] = 4;
  dims3->data[1] = 5;
  dims3->data[2] = 6;
  EXPECT_EQ("[4,5,6]", GetDimsDebugString(dims3));
  free(dims3);
}

}  // namespace testing
}  // namespace flex
}  // namespace tflite


text:
package source

import (
	"fmt"
	"go/ast"
	"go/token"
	"go/types"
	"path/filepath"
	"strings"
)

func DetectLanguage(langID, filename string) FileKind {
	switch langID {
	case "go":
		return Go
	case "go.mod":
		return Mod
	case "go.sum":
		return Sum
	}
	// Fallback to detecting the language based on the file extension.
	switch filepath.Ext(filename) {
	case ".mod":
		return Mod
	case ".sum":
		return Sum
	default: // fallback to Go
		return Go
	}
}

func (k FileKind) String() string {
	switch k {
	case Mod:
		return "go.mod"
	case Sum:
		return "go.sum"
	default:
		return "go"
	}
}

// indexExprAtPos returns the index of the expression containing pos.
func indexExprAtPos(pos token.Pos, args []ast.Expr) int {
	for i, expr := range args {
		if expr.Pos() <= pos && pos <= expr.End() {
			return i
		}
	}
	return len(args)
}

func exprAtPos(pos token.Pos, args []ast.Expr) ast.Expr {
	for _, expr := range args {
		if expr.Pos() <= pos && pos <= expr.End() {
			return expr
		}
	}
	return nil
}

// fieldSelections returns the set of fields that can
// be selected from a value of type T.
func fieldSelections(T types.Type) (fields []*types.Var) {
	// TODO(adonovan): this algorithm doesn't exclude ambiguous
	// selections that match more than one field/method.
	// types.NewSelectionSet should do that for us.

	seen := make(map[*types.Var]bool) // for termination on recursive types

	var visit func(T types.Type)
	visit = func(T types.Type) {
		if T, ok := deref(T).Underlying().(*types.Struct); ok {
			for i := 0; i < T.NumFields(); i++ {
				f := T.Field(i)
				if seen[f] {
					continue
				}
				seen[f] = true
				fields = append(fields, f)
				if f.Anonymous() {
					visit(f.Type())
				}
			}
		}
	}
	visit(T)

	return fields
}

// resolveInvalid traverses the node of the AST that defines the scope
// containing the declaration of obj, and attempts to find a user-friendly
// name for its invalid type. The resulting Object and its Type are fake.
func resolveInvalid(obj types.Object, node ast.Node, info *types.Info) types.Object {
	// Construct a fake type for the object and return a fake object with this type.
	formatResult := func(expr ast.Expr) types.Object {
		var typename string
		switch t := expr.(type) {
		case *ast.SelectorExpr:
			typename = fmt.Sprintf("%s.%s", t.X, t.Sel)
		case *ast.Ident:
			typename = t.String()
		default:
			return nil
		}
		typ := types.NewNamed(types.NewTypeName(token.NoPos, obj.Pkg(), typename, nil), types.Typ[types.Invalid], nil)
		return types.NewVar(obj.Pos(), obj.Pkg(), obj.Name(), typ)
	}
	var resultExpr ast.Expr
	ast.Inspect(node, func(node ast.Node) bool {
		switch n := node.(type) {
		case *ast.ValueSpec:
			for _, name := range n.Names {
				if info.Defs[name] == obj {
					resultExpr = n.Type
				}
			}
			return false
		case *ast.Field: // This case handles parameters and results of a FuncDecl or FuncLit.
			for _, name := range n.Names {
				if info.Defs[name] == obj {
					resultExpr = n.Type
				}
			}
			return false
		// TODO(rstambler): Handle range statements.
		default:
			return true
		}
	})
	return formatResult(resultExpr)
}

func lookupBuiltinDecl(v View, name string) interface{} {
	builtinPkg := v.BuiltinPackage()
	if builtinPkg == nil || builtinPkg.Scope == nil {
		return nil
	}
	obj := builtinPkg.Scope.Lookup(name)
	if obj == nil {
		return nil
	}
	return obj.Decl
}

func isPointer(T types.Type) bool {
	_, ok := T.(*types.Pointer)
	return ok
}

// deref returns a pointer's element type; otherwise it returns typ.
func deref(typ types.Type) types.Type {
	if p, ok := typ.Underlying().(*types.Pointer); ok {
		return p.Elem()
	}
	return typ
}

func isTypeName(obj types.Object) bool {
	_, ok := obj.(*types.TypeName)
	return ok
}

func isFunc(obj types.Object) bool {
	_, ok := obj.(*types.Func)
	return ok
}

// typeConversion returns the type being converted to if call is a type
// conversion expression.
func typeConversion(call *ast.CallExpr, info *types.Info) types.Type {
	var ident *ast.Ident
	switch expr := call.Fun.(type) {
	case *ast.Ident:
		ident = expr
	case *ast.SelectorExpr:
		ident = expr.Sel
	default:
		return nil
	}

	// Type conversion (e.g. "float64(foo)").
	if fun, _ := info.ObjectOf(ident).(*types.TypeName); fun != nil {
		return fun.Type()
	}

	return nil
}

func formatParams(tup *types.Tuple, variadic bool, qf types.Qualifier) []string {
	params := make([]string, 0, tup.Len())
	for i := 0; i < tup.Len(); i++ {
		el := tup.At(i)
		typ := types.TypeString(el.Type(), qf)

		// Handle a variadic parameter (can only be the final parameter).
		if variadic && i == tup.Len()-1 {
			typ = strings.Replace(typ, "[]", "...", 1)
		}

		if el.Name() == "" {
			params = append(params, typ)
		} else {
			params = append(params, el.Name()+" "+typ)
		}
	}
	return params
}

func formatResults(tup *types.Tuple, qf types.Qualifier) ([]string, bool) {
	var writeResultParens bool
	results := make([]string, 0, tup.Len())
	for i := 0; i < tup.Len(); i++ {
		if i >= 1 {
			writeResultParens = true
		}
		el := tup.At(i)
		typ := types.TypeString(el.Type(), qf)

		if el.Name() == "" {
			results = append(results, typ)
		} else {
			if i == 0 {
				writeResultParens = true
			}
			results = append(results, el.Name()+" "+typ)
		}
	}
	return results, writeResultParens
}

// formatType returns the detail and kind for an object of type *types.TypeName.
func formatType(typ types.Type, qf types.Qualifier) (detail string, kind CompletionItemKind) {
	if types.IsInterface(typ) {
		detail = "interface{...}"
		kind = InterfaceCompletionItem
	} else if _, ok := typ.(*types.Struct); ok {
		detail = "struct{...}"
		kind = StructCompletionItem
	} else if typ != typ.Underlying() {
		detail, kind = formatType(typ.Underlying(), qf)
	} else {
		detail = types.TypeString(typ, qf)
		kind = TypeCompletionItem
	}
	return detail, kind
}

func formatFunction(params []string, results []string, writeResultParens bool) string {
	var detail strings.Builder

	detail.WriteByte('(')
	for i, p := range params {
		if i > 0 {
			detail.WriteString(", ")
		}
		detail.WriteString(p)
	}
	detail.WriteByte(')')

	// Add space between parameters and results.
	if len(results) > 0 {
		detail.WriteByte(' ')
	}

	if writeResultParens {
		detail.WriteByte('(')
	}
	for i, p := range results {
		if i > 0 {
			detail.WriteString(", ")
		}
		detail.WriteString(p)
	}
	if writeResultParens {
		detail.WriteByte(')')
	}

	return detail.String()
}


text:
<?php

class Google_Service_ToolResults_AvailableDeepLinks extends Google_Model
{
}


text:
var	nMemcached = require( '../' ),
	memcached;

// connect to our memcached server on host 10.211.55.5, port 11211
memcached = new nMemcached( "10.211.55.5:11211" );

memcached.slabs( function( err, result ){
	if( err ) console.error( err );

	console.log( JSON.stringify ( result ));
	memcached.end(); // as we are 100% certain we are not going to use the connection again, we are going to end it
});


text:
  class Applicant < ActiveRecord::Base
  include Progress

  progress_includes :identity
  progress_includes_collection :household_members
  progress_includes_collection :residences
  progress_includes_collection :incomes
  progress_includes_collection :employments
  progress_includes_collection :criminal_histories
  progress_includes_collection :contacts

  has_many :people
  has_many :household_members, dependent: :destroy
  has_many :household_members_people, through: :household_members, source: :person, class_name: "Person", dependent: :destroy
  accepts_nested_attributes_for :household_members, allow_destroy: true

  has_many :contacts, dependent: :destroy
  has_many :contacts_people, through: :contacts, source: :person, class_name: "Contact", dependent: :destroy
  accepts_nested_attributes_for :contacts, allow_destroy: true

  belongs_to :identity, class_name: "Person", dependent: :destroy
  accepts_nested_attributes_for :identity

  has_many :residences, ->{ order(end: :desc) }, dependent: :destroy
  accepts_nested_attributes_for :residences, allow_destroy: true
  has_many :landlords, through: :residences, class_name: "Person", dependent: :destroy
  accepts_nested_attributes_for :landlords, allow_destroy: true

  belongs_to :user

  has_many :incomes, through: :people
  has_many :employments, through: :people
  has_many :criminal_histories, through: :people

  has_one :salesforce_applicant

  has_and_belongs_to_many :housing_forms

  before_validation :initialize_applicant
  validates_associated :identity, :household_members, :residences, :employments, :incomes, :criminal_histories, :contacts
  validates :identity, presence: true
  validates :user, presence: true

  def initialize_applicant
    self.identity ||= Person.create
  end

  def household_members_including_self
    [identity, household_members_people].flatten.compact.uniq
  end

  # The many kinds of addresses an applicant has
  has_many :residence_addresses, through: :residences, source: :address, dependent: :destroy
  has_many :household_members_people_mail_addresses, through: :household_members_people, source: :mail_address, class_name: "Address", dependent: :destroy
  has_many :employment_addresses, through: :employments, source: :address, dependent: :destroy

  def addresses
    [identity.mail_address,
     residence_addresses,
     household_members_people_mail_addresses,
     employment_addresses
    ].flatten.compact.uniq { |a| a.to_s }
  end

  def preferred_attrs_for field_names
    field_names.map do |field_name|
      begin
        preferred_items field_name
      rescue Dragoman::NoMatchError
        nil
      end
    end.flatten.reject(&:nil?).to_set
  end

  def current_residence
    residences.where(current: true).first
  end

  def to_s
    identity.to_s
  end

  def field field_name
    value_for_field(field_name).to_s
  end

  def delegate_field_to item, field_name
    item && item.value_for_field(field_name) || ""
  end

  def value_for_field field_name
    case field_name
    when /^HH(\d+)(.*)$/
      index = $1.to_i - 1
      delegate_field_to household_members[index], $2
    when /^LL(\d+)(.*)$/
      index = $1.to_i - 1
      delegate_field_to landlords[index], $2
    when /^Residence(\d+)(.*)$/
      index = $1.to_i - 1
      delegate_field_to residences[index], $2
    when /^Residence(.*)$/
      delegate_field_to residences[0], $1
    when /^Address(\d+)(.*)$/
      index = $1.to_i - 1
      delegate_field_to residences[index], $2
    when /^Address(.*)$/
      delegate_field_to residences[0], $1
    when /^Job(\d+)(.+)$/
      index = $1.to_i - 1
      delegate_field_to employments[index], $2
    when /^Job(.+)$/
      delegate_field_to employments[0], $1
    when /^Contact(\d+)(.+)$/
      index = $1.to_i - 1
      delegate_field_to contacts[index], $2
    when /^Contact(.+)$/
      delegate_field_to contacts[0], $1
    when /^Income(\d+)(.+)$/
      index = $1.to_i - 1
      delegate_field_to incomes[index], $2
    when /^Income(.+)$/
      delegate_field_to incomes[0], $1
    when /^Crime(\d+)(.+)$/
      index = $1.to_i - 1
      delegate_field_to criminal_histories[index], $2
    when /^Crime(.+)$/
      delegate_field_to criminal_histories[0], $1
    else
      identity && identity.value_for_field(field_name) || ""
    end
  end

end


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class com.google.android.apps.common.testing.ui.espresso.DataInteraction (TestKit 1.1 API)</title>
<meta name="date" content="2014-01-07">
<link rel="stylesheet" type="text/css" href="../../../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
com.google.android.apps.common.testing.ui.espresso.DataInteraction

Packages that use DataInteraction

Package
Description

com.google.android.apps.common.testing.ui.espresso

Uses of DataInteraction in com.google.android.apps.common.testing.ui.espresso

Methods in com.google.android.apps.common.testing.ui.espresso that return DataInteraction

Modifier and Type
Method and Description

DataInteraction
DataInteraction.atPosition(Integer atPosition)

Selects the view which matches the nth position on the adapter
 based on the data matcher.

DataInteraction
DataInteraction.inAdapterView(org.hamcrest.Matcher<android.view.View> adapterMatcher)

Selects a particular adapter view to operate on, by default we operate on any adapter view
 on the screen.

DataInteraction
DataInteraction.inRoot(org.hamcrest.Matcher<Root> rootMatcher)

Causes this data interaction to work within the Root specified by the given root matcher.

DataInteraction
DataInteraction.onChildView(org.hamcrest.Matcher<android.view.View> childMatcher)

Causes perform and check methods to take place on a specific child view of the view returned
 by Adapter.getView()

static DataInteraction
Espresso.onData(org.hamcrest.Matcher<Object> dataMatcher)

Creates an DataInteraction for a data object displayed by the application.

DataInteraction
DataInteraction.usingAdapterViewProtocol(AdapterViewProtocol adapterViewProtocol)

Use a different AdapterViewProtocol if the Adapter implementation does not
 satisfy the AdapterView contract like (@code ExpandableListView)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2014. All rights reserved.


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xunit;

namespace Simple.OData.Client.Tests.Core;

public class RequestWriterV3Tests : RequestWriterTests
{
	public override string MetadataFile => "Northwind3.xml";
	public override IFormatSettings FormatSettings => new ODataV3Format();

	protected async override Task<IRequestWriter> CreateRequestWriter()
	{
		return new V3.Adapter.RequestWriter(_session, await _client.GetMetadataAsync<Microsoft.Data.Edm.IEdmModel>().ConfigureAwait(false), null);
	}
}

public class RequestWriterV4Tests : RequestWriterTests
{
	public override string MetadataFile => "Northwind4.xml";
	public override IFormatSettings FormatSettings => new ODataV4Format();

	protected async override Task<IRequestWriter> CreateRequestWriter()
	{
		return new V4.Adapter.RequestWriter(_session, await _client.GetMetadataAsync<Microsoft.OData.Edm.IEdmModel>().ConfigureAwait(false), null);
	}
}

public abstract class RequestWriterTests : CoreTestBase
{
	protected abstract Task<IRequestWriter> CreateRequestWriter();

	[Fact]
	public async Task CreateUpdateRequest_NoPreferredVerb_PartialProperties_Patch()
	{
		var requestWriter = await CreateRequestWriter().ConfigureAwait(false);
		var result = await requestWriter.CreateUpdateRequestAsync("Products", "",
					new Dictionary<string, object>() { { "ProductID", 1 } },
					new Dictionary<string, object>() { { "ProductName", "Chai" } }, false).ConfigureAwait(false);
		Assert.Equal("PATCH", result.Method);
	}

	[Fact]
	public async Task CreateUpdateRequest_NoPreferredVerb_AllProperties_Patch()
	{
		var requestWriter = await CreateRequestWriter().ConfigureAwait(false);
		var result = await requestWriter.CreateUpdateRequestAsync("Products", "",
					new Dictionary<string, object>() { { "ProductID", 1 } },
					new Dictionary<string, object>()
					{
							{ "ProductID", 1 },
							{ "SupplierID", 2 },
							{ "CategoryID", 3 },
							{ "ProductName", "Chai" },
							{ "EnglishName", "Tea" },
							{ "QuantityPerUnit", "10" },
							{ "UnitPrice", 20m },
							{ "UnitsInStock", 100 },
							{ "UnitsOnOrder", 1000 },
							{ "ReorderLevel", 500 },
							{ "Discontinued", false },
					}, false).ConfigureAwait(false);
		Assert.Equal("PATCH", result.Method);
	}

	[Fact]
	public async Task CreateUpdateRequest_PreferredVerbPut_AllProperties_Put()
	{
		var preferredUpdateMethod = _session.Settings.PreferredUpdateMethod;
		try
		{
			_session.Settings.PreferredUpdateMethod = ODataUpdateMethod.Put;
			var requestWriter = await CreateRequestWriter().ConfigureAwait(false);
			var result = await requestWriter.CreateUpdateRequestAsync("Products", "",
						new Dictionary<string, object>() { { "ProductID", 1 } },
						new Dictionary<string, object>()
					{
							{ "ProductID", 1 },
							{ "SupplierID", 2 },
							{ "CategoryID", 3 },
							{ "ProductName", "Chai" },
							{ "EnglishName", "Tea" },
							{ "QuantityPerUnit", "10" },
							{ "UnitPrice", 20m },
							{ "UnitsInStock", 100 },
							{ "UnitsOnOrder", 1000 },
							{ "ReorderLevel", 500 },
							{ "Discontinued", false },
					}, false).ConfigureAwait(false);
			Assert.Equal("PUT", result.Method);
		}
		finally
		{
			_session.Settings.PreferredUpdateMethod = preferredUpdateMethod;
		}
	}

	[Fact]
	public async Task CreateUpdateRequest_PreferredVerbPatch_ChangedKey_Put()
	{
		var requestWriter = await CreateRequestWriter().ConfigureAwait(false);
		var result = await requestWriter.CreateUpdateRequestAsync("Products", "",
					new Dictionary<string, object>() { { "ProductID", 1 } },
					new Dictionary<string, object>()
					{
							{ "ProductID", 10 },
							{ "SupplierID", 2 },
							{ "CategoryID", 3 },
							{ "ProductName", "Chai" },
							{ "EnglishName", "Tea" },
							{ "QuantityPerUnit", "10" },
							{ "UnitPrice", 20m },
							{ "UnitsInStock", 100 },
							{ "UnitsOnOrder", 1000 },
							{ "ReorderLevel", 500 },
							{ "Discontinued", false },
					}, false).ConfigureAwait(false);
		Assert.Equal("PUT", result.Method);
	}

	[Fact]
	public async Task CreateInsertRequest_Post()
	{
		var requestWriter = await CreateRequestWriter().ConfigureAwait(false);
		var result = await requestWriter.CreateInsertRequestAsync("Employees", "",
			new Dictionary<string, object>()
			{
					{ "FirstName", "John" },
					{ "LastName", "Smith" },
			}, false).ConfigureAwait(false);
		Assert.Equal("POST", result.Method);
	}

	[Fact]
	public async Task CreateInsertRequest_DateTime_Not_Null_Post()
	{
		var requestWriter = await CreateRequestWriter().ConfigureAwait(false);
		var result = await requestWriter.CreateInsertRequestAsync("Employees", "",
			new Dictionary<string, object>()
			{
					{ "FirstName", "John" },
					{ "LastName", "Smith" },
					{ "BirthDate", DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Unspecified) },
			}, false).ConfigureAwait(false);
		Assert.Equal("POST", result.Method);
	}

	[Fact]
	public async Task CreateInsertRequest_DateTime_Null_Post()
	{
		var requestWriter = await CreateRequestWriter().ConfigureAwait(false);
		var result = await requestWriter.CreateInsertRequestAsync("Employees", "",
			new Dictionary<string, object>()
			{
					{ "FirstName", "John" },
					{ "LastName", "Smith" },
					{ "BirthDate", null },
			}, false).ConfigureAwait(false);
		Assert.Equal("POST", result.Method);
	}

	[Fact]
	public async Task CreateInsertRequest_DateTimeOffset_Not_Null_Post()
	{
		var requestWriter = await CreateRequestWriter().ConfigureAwait(false);
		var result = await requestWriter.CreateInsertRequestAsync("Employees", "",
			new Dictionary<string, object>()
			{
					{ "FirstName", "John" },
					{ "LastName", "Smith" },
					{ "BirthDate", DateTimeOffset.Now },
			}, false).ConfigureAwait(false);
		Assert.Equal("POST", result.Method);
	}

	[Fact]
	public async Task CreateInsertRequest_DateTimeOffset_Null_Post()
	{
		var requestWriter = await CreateRequestWriter().ConfigureAwait(false);
		var result = await requestWriter.CreateInsertRequestAsync("Employees", "",
			new Dictionary<string, object>()
			{
					{ "FirstName", "John" },
					{ "LastName", "Smith" },
					{ "BirthDate", null },
			}, false).ConfigureAwait(false);
		Assert.Equal("POST", result.Method);
	}

	[Fact]
	public async Task CreateInsertRequest_Date_Not_Null_Post()
	{
		var requestWriter = await CreateRequestWriter().ConfigureAwait(false);
		var result = await requestWriter.CreateInsertRequestAsync("Employees", "",
			new Dictionary<string, object>()
			{
					{ "FirstName", "John" },
					{ "LastName", "Smith" },
					{ "HireDate", DateTimeOffset.Now },
			}, false).ConfigureAwait(false);
		Assert.Equal("POST", result.Method);
	}

	[Fact]
	public async Task CreateInsertRequest_Date_Null_Post()
	{
		var requestWriter = await CreateRequestWriter().ConfigureAwait(false);
		var result = await requestWriter.CreateInsertRequestAsync("Employees", "",
			new Dictionary<string, object>()
			{
					{ "FirstName", "John" },
					{ "LastName", "Smith" },
					{ "HireDate", null },
			}, false).ConfigureAwait(false);
		Assert.Equal("POST", result.Method);
	}

	[Fact]
	public async Task CreateInsertRequest_With_Headers()
	{
		var requestWriter = await CreateRequestWriter().ConfigureAwait(false);
		var result = await requestWriter.CreateInsertRequestAsync("Employees", "",
			new Dictionary<string, object>()
			{
					{ "FirstName", "John" },
			}, false,
			new Dictionary<string, string>
			{
					{ "header1" , "header1Value" },
					{ "header2" , "header2Value" }
			}).ConfigureAwait(false);

		Assert.Equal("header1Value", result.Headers["header1"]);
		Assert.Equal("header2Value", result.Headers["header2"]);
	}
}


text:
package com.infinities.skyport.cache.impl.service.compute;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicBoolean;

import org.dasein.cloud.CloudException;
import org.dasein.cloud.InternalException;
import org.dasein.cloud.compute.Snapshot;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.infinities.skyport.async.AsyncResult;
import com.infinities.skyport.async.service.compute.AsyncSnapshotSupport;
import com.infinities.skyport.cache.impl.CachedServiceProviderImpl;
import com.infinities.skyport.cache.service.CachedComputeServices.ComputeQuartzType;
import com.infinities.skyport.cache.service.compute.CachedSnapshotSupport;
import com.infinities.skyport.distributed.DistributedCache;
import com.infinities.skyport.distributed.DistributedMap;
import com.infinities.skyport.distributed.DistributedObjectFactory;
import com.infinities.skyport.model.Time;
import com.infinities.skyport.model.compute.SnapshotSupportProxy;
import com.infinities.skyport.model.configuration.Configuration;
import com.infinities.skyport.model.configuration.compute.SnapshotConfiguration;
import com.infinities.skyport.proxy.SnapshotProxy;
import com.infinities.skyport.quartz.QuartzConfiguration;
import com.infinities.skyport.quartz.QuartzConfiguration.Precondition;
import com.infinities.skyport.quartz.QuartzServiceImpl;
import com.infinities.skyport.quartz.callable.SnapshotCallable;
import com.infinities.skyport.service.ConfigurationHome;
import com.infinities.skyport.service.ConfigurationLifeCycleListener;
import com.infinities.skyport.service.event.FirstLevelDispatcher;
import com.infinities.skyport.service.event.compute.snapshot.SnapshotFailureEvent;
import com.infinities.skyport.service.event.compute.snapshot.SnapshotRefreshedEvent;

public class CachedSnapshotSupportImpl extends SnapshotSupportProxy implements CachedSnapshotSupport,
		ConfigurationLifeCycleListener {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	private static final Logger logger = LoggerFactory.getLogger(CachedSnapshotSupportImpl.class);
	private final AsyncSnapshotSupport inner;
	private final Configuration configuration;
	private final DistributedObjectFactory objectFactory;
	private final FirstLevelDispatcher dispatcher;
	private final AtomicBoolean isInitialized = new AtomicBoolean(false);
	private final DistributedMap<ComputeQuartzType, ComputeQuartzType> typeMap;
	private final DistributedCache<String, SnapshotProxy> snapshotCache;
	private final QuartzServiceImpl<ComputeQuartzType> quartzService;
	private final Map<ComputeQuartzType, QuartzConfiguration<?>> quartzs = Maps.newEnumMap(ComputeQuartzType.class);
	private final List<CachedSnapshotListener> snapshotListeners = new ArrayList<CachedSnapshotListener>();

	public CachedSnapshotSupportImpl(ConfigurationHome home, AsyncSnapshotSupport inner, Configuration configuration,
			QuartzServiceImpl<ComputeQuartzType> quartz, DistributedMap<ComputeQuartzType, ComputeQuartzType> typeMap,
			FirstLevelDispatcher dispatcher, DistributedObjectFactory objectFactory) {
		super(inner);
		home.addLifeCycleListener(this);
		this.inner = inner;
		this.configuration = configuration;
		this.quartzService = quartz;
		this.typeMap = typeMap;
		this.dispatcher = dispatcher;
		this.objectFactory = objectFactory;
		snapshotCache =
				objectFactory.getCache("snapshotCache", new IllegalStateException(CachedServiceProviderImpl.COLLECTING));
	}

	public synchronized void initialize() {
		if (isInitialized.compareAndSet(false, true)) {
			// super.initialize();
			setUpSchedule(configuration.getComputeConfiguration().getSnapshotConfiguration());
			logger.info("initialize cache");
		} else {
			throw new IllegalStateException("object has been initialized");
		}
	}

	public synchronized void close() {
		if (isInitialized.compareAndSet(true, false)) {
			try {
				snapshotCache.destroy();
			} catch (Exception e) {
				logger.warn("ignore", e);
			}
			for (Iterator<CachedSnapshotListener> it = snapshotListeners.iterator(); it.hasNext();) {
				CachedSnapshotListener listener = it.next();
				try {
					dispatcher.removeListener(listener);
				} catch (Exception e) {
					logger.warn("ignore", e);
				}
				it.remove();
			}
		}

	}

	private void setUpSchedule(SnapshotConfiguration snapshotConfiguration) {
		if (configuration.getStatus()) {
			Time snapshotTime = snapshotConfiguration.getListSnapshots().getDelay();

			Precondition snapshotCondition = new Precondition() {

				@Override
				public boolean check() {
					return typeMap.containsKey(ComputeQuartzType.Snapshot);
				}

			};
			QuartzConfiguration<Iterable<Snapshot>> snapshotConfig =
					new QuartzConfiguration.Builder<Iterable<Snapshot>>(new SnapshotCallable(inner.getSupport()),
							snapshotCondition).addCallback(getSnapshotCallback()).delay(snapshotTime)
							.initialDelay(CachedServiceProviderImpl.INITIAL_DELAY)
							.name("Snapshot:" + configuration.getCloudName()).build();
			quartzs.put(ComputeQuartzType.Snapshot, snapshotConfig);

			fireQuartz();
		}
	}

	private FutureCallback<Iterable<Snapshot>> getSnapshotCallback() {
		return new FutureCallback<Iterable<Snapshot>>() {

			@Override
			public void onSuccess(Iterable<Snapshot> result) {
				List<Snapshot> snapshotList = Lists.newArrayList(result);
				String name = configuration.getCloudName();
				String id = configuration.getId();
				logger.debug("list {} snapshot success: {}", new Object[] { name, snapshotList.size() });
				refreshSnapshotCache(result);
				dispatcher.fireRefreshedEvent(new SnapshotRefreshedEvent(snapshotCache.values(), id));
			}

			@Override
			public void onFailure(Throwable t) {
				String name = configuration.getCloudName();
				String id = configuration.getId();
				logger.warn("list {} snapshot failed", name);
				logger.warn("list snapshot failed", t);
				snapshotCache.reload(t);
				dispatcher.fireFaiureEvent(new SnapshotFailureEvent(id, t));
			}

		};
	}

	protected void refreshSnapshotCache(Iterable<Snapshot> result) {
		Map<String, SnapshotProxy> snapshotMap = new HashMap<String, SnapshotProxy>();
		Iterator<Snapshot> iterator = result.iterator();
		while (iterator.hasNext()) {
			String configName = configuration.getCloudName();
			String configId = configuration.getId();
			Snapshot snapshot = iterator.next();
			SnapshotProxy proxy =
					new SnapshotProxy(snapshot, configName, configId, this.getObjectFactory().getAtomicLong(
							"snapshot_" + snapshot.getProviderSnapshotId()));
			snapshotMap.put(snapshot.getProviderSnapshotId(), proxy);
		}
		this.snapshotCache.reload(snapshotMap);
	}

	private void fireQuartz() {
		for (Entry<ComputeQuartzType, QuartzConfiguration<?>> quartz : quartzs.entrySet()) {
			try {
				quartzService.schedule(quartz.getKey(), quartz.getValue()).get();
			} catch (Exception e) {
				logger.warn("data collecting failed", e);
			}
		}
	}

	protected DistributedObjectFactory getObjectFactory() {
		return objectFactory;
	}

	@Override
	public AsyncResult<Iterable<Snapshot>> listSnapshots() throws InternalException, CloudException {
		Iterable<Snapshot> list = new ArrayList<Snapshot>(snapshotCache.values());
		ListenableFuture<Iterable<Snapshot>> future = Futures.immediateFuture(list);
		AsyncResult<Iterable<Snapshot>> ret = new AsyncResult<Iterable<Snapshot>>(future);
		return ret;
	}

	@Override
	public synchronized void addSnapshotListener(CachedSnapshotListener service) {
		if (!isInitialized.get()) {
			throw new IllegalStateException("service provider has not been initialized yet");
		}
		Preconditions.checkNotNull(service);
		if (!snapshotListeners.contains(service)) {
			dispatcher.addListener(service);
			snapshotListeners.add(service);
		}
	}

	@Override
	public synchronized void removeSnapshotListener(CachedSnapshotListener service) {
		if (snapshotListeners.contains(service)) {
			dispatcher.removeListener(service);
			snapshotListeners.remove(service);
		}
	}

	@Override
	public void persist(Configuration configuration) {
		// ignore
	}

	@Override
	public synchronized void lightMerge(Configuration configuration) {
		if (configuration.getId().equals(this.configuration.getId())) {
			// change listSnapshots delay
			Time delay = configuration.getComputeConfiguration().getSnapshotConfiguration().getListSnapshots().getDelay();
			if (quartzs.containsKey(ComputeQuartzType.Snapshot)) {
				Time oldDelay = quartzs.get(ComputeQuartzType.Snapshot).getTime();
				if (!oldDelay.equals(delay)) {
					quartzs.get(ComputeQuartzType.Snapshot).setTime(delay);
				}
			}
		}
	}

	@Override
	public void heavyMerge(Configuration configuration) {
		// ignore
	}

	@Override
	public void remove(Configuration configuration) {
		// ignore
	}

	@Override
	public void clear() {
		// ignore
	}

}


text:
package t3.xml;

/**
 *
 * @author Mathieu Debove <mad@teecu.be>
 *
 */
public abstract class XMLVisitor<T> implements XMLFromPropertiesMapping {

    private T visited = null;

    public XMLVisitor(T visited) {
        this.visited = visited;
    }

    @SuppressWarnings("unchecked") // must check!
    protected T visited() {
        return visited != null ? visited : (T) this;
    }

}


text:
An engine build atop the LibGDX Framework

Ensure the active branch is [PBR](https://github.com/ncguy2/Argent/tree/PBR)


text:
package com.linecorp.armeria.server.docs;

import static java.util.Objects.requireNonNull;

import java.util.Objects;

import javax.annotation.Nullable;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.MoreObjects;
import com.google.common.base.Strings;

import com.linecorp.armeria.common.util.UnstableApi;

/**
 * Metadata about an enum value.
 */
@UnstableApi
public final class EnumValueInfo {

    private final String name;
    @Nullable
    private final String docString;
    @Nullable
    private final Integer intValue;

    /**
     * Creates a new instance.
     *
     * @param name the name of the enum value
     */
    public EnumValueInfo(String name) {
        this(name, null, null);
    }

    /**
     * Creates a new instance.
     *
     * @param name the name of the enum value
     * @param intValue the integer value of the enum value
     */
    public EnumValueInfo(String name, @Nullable Integer intValue) {
        this(name, intValue, null);
    }

    /**
     * Creates a new instance.
     *
     * @param name the name of the enum value
     * @param intValue the integer value of the enum value
     * @param docString the documentation string that describes the enum value
     */
    public EnumValueInfo(String name, @Nullable Integer intValue, @Nullable String docString) {
        this.name = requireNonNull(name, "name");
        this.intValue = intValue;
        this.docString = Strings.emptyToNull(docString);
    }

    /**
     * Returns the name of the enum value.
     */
    @JsonProperty
    public String name() {
        return name;
    }

    /**
     * Returns the integer value of the enum value.
     */
    @JsonProperty
    @JsonInclude(Include.NON_NULL)
    @Nullable
    public Integer intValue() {
        return intValue;
    }

    /**
     * Returns the documentation string that describes the enum value.
     */
    @JsonProperty
    @JsonInclude(Include.NON_NULL)
    @Nullable
    public String docString() {
        return docString;
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, intValue);
    }

    @Override
    public boolean equals(@Nullable Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof EnumValueInfo)) {
            return false;
        }

        final EnumValueInfo that = (EnumValueInfo) o;
        return name.equals(that.name) && Objects.equals(intValue, that.intValue);
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                          .omitNullValues()
                          .add("name", name)
                          .add("intValue", intValue)
                          .add("docString", docString)
                          .toString();
    }
}


text:
package resources

import (
	"fmt"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/ec2"
	"github.com/pkg/errors"
	"k8s.io/klog"
)

// Clean-up ENIs

type NetworkInterfaces struct{}

func (NetworkInterfaces) MarkAndSweep(sess *session.Session, account string, region string, set *Set) error {
	svc := ec2.New(sess, &aws.Config{Region: aws.String(region)})

	var toDelete []*networkInterface // Paged call, defer deletion until we have the whole list.

	pageFunc := func(page *ec2.DescribeNetworkInterfacesOutput, _ bool) bool {
		for _, eni := range page.NetworkInterfaces {
			a := &networkInterface{Region: region, Account: account, ID: *eni.NetworkInterfaceId}
			if eni.Attachment != nil {
				a.AttachmentID = *eni.Attachment.AttachmentId
			}
			if set.Mark(a) {
				klog.Warningf("%s: deleting %T", a.ARN(), a)
				toDelete = append(toDelete, a)
			}
		}
		return true
	}

	if err := svc.DescribeNetworkInterfacesPages(&ec2.DescribeNetworkInterfacesInput{}, pageFunc); err != nil {
		return err
	}

	for _, eni := range toDelete {
		if eni.AttachmentID != "" {
			detachInput := &ec2.DetachNetworkInterfaceInput{
				AttachmentId: aws.String(eni.AttachmentID),
			}
			if _, err := svc.DetachNetworkInterface(detachInput); err != nil {
				klog.Warningf("%s: detach failed: %v", eni.ARN(), err)
			}
		}

		deleteInput := &ec2.DeleteNetworkInterfaceInput{
			NetworkInterfaceId: aws.String(eni.ID),
		}

		if _, err := svc.DeleteNetworkInterface(deleteInput); err != nil {
			klog.Warningf("%s: delete failed: %v", eni.ARN(), err)
		}
	}

	return nil
}

func (NetworkInterfaces) ListAll(sess *session.Session, acct, region string) (*Set, error) {
	c := ec2.New(sess, aws.NewConfig().WithRegion(region))
	set := NewSet(0)
	input := &ec2.DescribeNetworkInterfacesInput{}

	err := c.DescribeNetworkInterfacesPages(input, func(enis *ec2.DescribeNetworkInterfacesOutput, isLast bool) bool {
		now := time.Now()
		for _, eni := range enis.NetworkInterfaces {
			arn := networkInterface{
				Region:  region,
				Account: acct,
				ID:      aws.StringValue(eni.NetworkInterfaceId),
			}.ARN()
			set.firstSeen[arn] = now
		}

		return true
	})

	return set, errors.Wrapf(err, "couldn't describe network interfaces for %q in %q", acct, region)
}

type networkInterface struct {
	Region       string
	Account      string
	AttachmentID string
	ID           string
}

func (eni networkInterface) ARN() string {
	return fmt.Sprintf("arn:aws:ec2:%s:%s:network-interface/%s", eni.Region, eni.Account, eni.ID)
}

func (eni networkInterface) ResourceKey() string {
	return eni.ARN()
}


text:
"""
This scripts reads a bag file containing RGBD data, adds the corresponding
PointCloud2 messages, and saves it again into a bag file. Optional arguments
allow to select only a portion of the original bag file.
"""

import argparse
import sys
import os

if __name__ == '__main__':

    # parse command line
    parser = argparse.ArgumentParser(description='''
    This scripts reads a bag file containing RGBD data,
    adds the corresponding PointCloud2 messages, and saves it again into a bag file.
    Optional arguments allow to select only a portion of the original bag file.
    ''')
    parser.add_argument('--start', help='skip the first N seconds of  input bag file (default: 0.0)',default=0.00)
    parser.add_argument('--duration', help='only process N seconds of input bag file (default: off)')
    parser.add_argument('--nth', help='only process every N-th frame of input bag file (default: 15)',default=15)
    parser.add_argument('--skip', help='skip N blocks in the beginning (default: 1)', default=1)
    parser.add_argument('--compress', help='compress output bag file', action='store_true')
    parser.add_argument('inputbag', help='input bag file')
    parser.add_argument('outputbag', nargs='?',help='output bag file')
    args = parser.parse_args()

    import roslib; roslib.load_manifest('rgbd_benchmark_tools')
    import rospy
    import rosbag
    import sensor_msgs.msg
    import cv
    from cv_bridge import CvBridge, CvBridgeError
    import struct
    import tf

    if not args.outputbag:
        args.outputbag = os.path.splitext(args.inputbag)[0] + "-points.bag"

    print "Processing bag file:"
    print "  in:",args.inputbag
    print "  out:",args.outputbag
    print "  starting from: %s seconds"%(args.start)

    if args.duration:
        print "  duration: %s seconds"%(args.duration)

    print "  saving every %s-th frame"%(args.nth)
    args.skip = float(args.skip)
    print "  skipping %s blocks"%(args.skip)

    inbag = rosbag.Bag(args.inputbag,'r')
    if args.compress:
        param_compression = rosbag.bag.Compression.BZ2
    else:
        param_compression = rosbag.bag.Compression.NONE

    outbag = rosbag.Bag(args.outputbag, 'w', compression=param_compression)

    depth_camera_info = None
    rgb_camera_info = None
    depth_image = None
    rgb_image_color = None
    cortex = None

    nan = float('nan')
    bridge = CvBridge()
    frame = 0
    transforms = dict()

    time_start = None
    for topic, msg, t in inbag.read_messages():
        if time_start==None:
            time_start=t
        if t - time_start < rospy.Duration.from_sec(float(args.start)):
            continue
        if args.duration and (t - time_start > rospy.Duration.from_sec(float(args.start) + float(args.duration))):
            break
        print "t=%f\r"%(t-time_start).to_sec(),
        if topic == "/tf":
            for transform in msg.transforms:
                transforms[ (transform.header.frame_id,transform.child_frame_id) ] = transform
            continue
        if topic == "/imu":
            imu = msg
            continue
        if topic == "/camera/depth/camera_info":
            depth_camera_info = msg
            continue
        if topic == "/camera/rgb/camera_info":
            rgb_camera_info = msg
            continue
        if topic == "/camera/rgb/image_color" and rgb_camera_info:
            rgb_image_color = msg
            continue
        if topic == "/camera/depth/image" and depth_camera_info and rgb_image_color and rgb_camera_info:# and imu:
            depth_image = msg
            # now process frame

            if depth_image.header.stamp - rgb_image_color.header.stamp > rospy.Duration.from_sec(1/30.0):
                continue

            frame += 1
            if frame % float(args.nth) ==0:
                if args.skip > 0:
                    args.skip -= 1
                else:
                    # store messages
                    msg = tf.msg.tfMessage()
                    msg.transforms = list( transforms.itervalues() )
                    outbag.write("/tf",msg,t)
                    transforms = dict()
#                    outbag.write("/imu",imu,t)
                    outbag.write("/camera/depth/camera_info",depth_camera_info,t)
                    outbag.write("/camera/depth/image",depth_image,t)
                    outbag.write("/camera/rgb/camera_info",rgb_camera_info,t)
                    outbag.write("/camera/rgb/image_color",rgb_image_color,t)

                    # generate monochrome image from color image
                    cv_rgb_image_mono = bridge.imgmsg_to_cv(rgb_image_color, "mono8")
                    rgb_image_mono = bridge.cv_to_imgmsg(cv_rgb_image_mono)
                    rgb_image_mono.header = rgb_image_color.header
                    outbag.write("/camera/rgb/image_mono",rgb_image_mono,t)

                    # generate depth and colored point cloud
                    cv_depth_image = bridge.imgmsg_to_cv(depth_image, "passthrough")
                    cv_rgb_image_color = bridge.imgmsg_to_cv(rgb_image_color, "bgr8")
    #
                    centerX = depth_camera_info.K[2]
                    centerY = depth_camera_info.K[5]
                    depthFocalLength = depth_camera_info.K[0]
                    depth_points = sensor_msgs.msg.PointCloud2()
                    depth_points.header = depth_image.header
                    depth_points.width = depth_image.width
                    depth_points.height  = depth_image.height
                    depth_points.fields.append(sensor_msgs.msg.PointField(
                        name = "x",offset = 0,datatype = sensor_msgs.msg.PointField.FLOAT32,count = 1 ))
                    depth_points.fields.append(sensor_msgs.msg.PointField(
                        name = "y",offset = 4,datatype = sensor_msgs.msg.PointField.FLOAT32,count = 1 ))
                    depth_points.fields.append(sensor_msgs.msg.PointField(
                        name = "z",offset = 8,datatype = sensor_msgs.msg.PointField.FLOAT32,count = 1 ))
                    depth_points.point_step = 16
                    depth_points.row_step = depth_points.point_step * depth_points.width
                    buffer = []
                    buffer_rgb = []
                    for v in range(depth_image.height):
                        for u in range(depth_image.width):
                            d = cv_depth_image[v,u]
                            ptx = (u - centerX) * d / depthFocalLength;
                            pty = (v - centerY) * d / depthFocalLength;
                            ptz = d;
                            buffer.append(struct.pack('ffff',ptx,pty,ptz,1.0))
                    depth_points.data = "".join(buffer)
                    outbag.write("/camera/depth/points", depth_points, t)

                    centerX = depth_camera_info.K[2]
                    centerY = depth_camera_info.K[5]
                    depthFocalLength = depth_camera_info.K[0]
                    rgb_points = sensor_msgs.msg.PointCloud2()
                    rgb_points.header = rgb_image_color.header
                    rgb_points.width = depth_image.width
                    rgb_points.height  = depth_image.height
                    rgb_points.fields.append(sensor_msgs.msg.PointField(
                        name = "x",offset = 0,datatype = sensor_msgs.msg.PointField.FLOAT32,count = 1 ))
                    rgb_points.fields.append(sensor_msgs.msg.PointField(
                        name = "y",offset = 4,datatype = sensor_msgs.msg.PointField.FLOAT32,count = 1 ))
                    rgb_points.fields.append(sensor_msgs.msg.PointField(
                        name = "z",offset = 8,datatype = sensor_msgs.msg.PointField.FLOAT32,count = 1 ))
                    rgb_points.fields.append(sensor_msgs.msg.PointField(
                        name = "rgb",offset = 16,datatype = sensor_msgs.msg.PointField.FLOAT32,count = 1 ))
                    rgb_points.point_step = 32
                    rgb_points.row_step = rgb_points.point_step * rgb_points.width
                    buffer = []
                    for v in range(depth_image.height):
                        for u in range(depth_image.width):
                            d = cv_depth_image[v,u]
                            rgb = cv_rgb_image_color[v,u]
                            ptx = (u - centerX) * d / depthFocalLength;
                            pty = (v - centerY) * d / depthFocalLength;
                            ptz = d;
                            buffer.append(struct.pack('ffffBBBBIII',
                                ptx,pty,ptz,1.0,
                                rgb[0],rgb[1],rgb[2],0,
                                0,0,0))
                    rgb_points.data = "".join(buffer)
                    outbag.write("/camera/rgb/points", rgb_points, t)
            # consume the images
#            imu = None
            depth_image = None
            rgb_image_color = None
            continue
        if topic not in ["/tf","/imu",
                         "/camera/depth/camera_info","/camera/rgb/camera_info",
                         "/camera/rgb/image_color","/camera/depth/image"]:
            # anything else: pass thru
            outbag.write(topic,msg,t)

    outbag.close()
    print


text:
if [ ! -f "Dockerfile" ]; then
	echo "Dockerfile not found"
	exit 1
fi

if [ ! -f "target/spring-cloud-stream-module-launcher-1.0.0.BUILD-SNAPSHOT-exec.jar" ]; then
	echo "JAR not available; run mvn package first"
	exit 1
fi

docker build -t 192.168.59.103:5000/module-launcher .


text:
#ifdef INTEL_MKL

#define EIGEN_USE_THREADS

#include "dnnl.hpp"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/type_traits.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/graph/mkl_graph_util.h"
#include "tensorflow/core/kernels/meta_support.h"
#include "tensorflow/core/kernels/quantization_utils.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/util/mkl_util.h"

using dnnl::primitive_attr;
using dnnl::stream;

namespace tensorflow {

typedef Eigen::ThreadPoolDevice CPUDevice;

template <typename Device, typename T, bool native_format = false>
class MklDequantizeOp : public OpKernel {
 public:
  explicit MklDequantizeOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
    string mode_string;
    OP_REQUIRES_OK(ctx, ctx->GetAttr("mode", &mode_string));
    OP_REQUIRES(ctx, mode_string == "SCALED",
                errors::InvalidArgument(
                    "MklDequantizeOp only supports 'SCALED' mode, but got '" +
                    mode_string + "'"));
  }

  void Compute(OpKernelContext* ctx) override {
    try {
      // Using CPU device
      auto cpu_engine = engine(engine::kind::cpu, 0);

      // Get the inputs
      const Tensor& src_tensor = MklGetInput(ctx, kSrcIndex);
      const float min_range =
          MklGetInput(ctx, kMinIndex).template flat<float>()(0);
      const float max_range =
          MklGetInput(ctx, kMaxIndex).template flat<float>()(0);

      // Get MklShape
      MklDnnShape src_mkl_shape;
      GetMklShape(ctx, kSrcIndex, &src_mkl_shape, native_format);

      // src_dims is the dimension of src_tensor
      // output_dims are same as src_dims
      auto src_dims = src_mkl_shape.IsMklTensor()
                          ? src_mkl_shape.GetSizesAsMklDnnDims()
                          : TFShapeToMklDnnDims(src_tensor.shape());
      auto output_dims = src_dims;

      // Create reorder memory for src and dst
      MklDnnData<T> src(&cpu_engine);
      MklDnnData<float> dst(&cpu_engine);

      std::shared_ptr<stream> reorder_stream;
      MklDnnThreadPool eigen_tp(ctx);
      reorder_stream.reset(CreateStream(&eigen_tp, cpu_engine));

      // If input is in MKL layout, then simply grab input layout; otherwise,
      // construct input TF layout. For TF layout, although input shape
      // (src_dims) required is in MKL-DNN order, the layout is Tensorflow's
      // layout
      auto src_md =
          src_mkl_shape.IsMklTensor()
              ? src_mkl_shape.GetMklLayout()
              : memory::desc(src_dims, MklDnnType<T>(),
                             src_dims.size() == 4 ? memory::format_tag::nhwc
                                                  : memory::format_tag::nc);

      src.SetUsrMem(src_md, &src_tensor);
      src.SetUsrMemDataHandle(&src_tensor, reorder_stream);

      Tensor* output_tensor = nullptr;
      MklDnnShape output_mkl_shape;
      TensorShape output_tf_shape;
      memory::desc dst_md = memory::desc();
      if (src_mkl_shape.IsMklTensor()) {
        dst_md = memory::desc(src_mkl_shape.GetMklLayout().data);
        // There is no API in MKL-DNN v1.x to construct memory descriptor with
        // same .data field but different type.
        dst_md.data.data_type = memory::convert_to_c(MklDnnType<float>());
      } else {
        dst_md = memory::desc(src_dims, MklDnnType<float>(),
                              src_dims.size() == 4 ? memory::format_tag::nhwc
                                                   : memory::format_tag::nc);
      }

      // If input is MKL shape, output is also MKL shape.
      // If input is TF shape, output is also TF shape.
      if (src_mkl_shape.IsMklTensor()) {
        output_mkl_shape.SetMklTensor(true);
        output_mkl_shape.SetMklLayout(&dst_md);
        output_mkl_shape.SetElemType(MklDnnType<float>());
        output_mkl_shape.SetTfLayout(src_mkl_shape.GetDimension(),
                                     src_mkl_shape.GetSizesAsMklDnnDims(),
                                     src_mkl_shape.GetTfDataFormat());
        output_tf_shape.AddDim(dst_md.get_size() / sizeof(float));
      } else {
        output_mkl_shape.SetMklTensor(false);
        output_tf_shape = MklDnnDimsToTFShape(output_dims);
      }

      // Allocate MKL or TF output shape based on the above
      AllocateOutputSetMklShape(ctx, 0, &output_tensor, output_tf_shape,
                                output_mkl_shape, native_format);
      dst.SetUsrMem(dst_md, output_tensor);
      dst.SetUsrMemDataHandle(output_tensor, reorder_stream);

      // The quantization logic here for mode SCALED is similar to the logic
      // in QuantizeAndDequantizeV2 and QuantizeAndDequantizeV3.
      static constexpr int num_bits = sizeof(T) * 8;
      const float max_abs = std::max(std::abs(min_range), std::abs(max_range));
      bool is_signed = std::is_signed<T>::value;
      // If it is signed, we try to keep 0.0 being 0 and drop one bucket. For
      // example, if it is 8 bits, we have the range [-127, 127]. So for input
      // range of [-x, x], the scale should be (2*x)/254.
      //
      // If it is unsigned and num_bits == 8, the range with 8 bits is [0, 255].
      // If the input range is [0, x], then the scale is x/255 instead of 254 as
      // in the case above.
      const int target_bits = is_signed ? (num_bits - 1) : num_bits;
      const float target_range =
          static_cast<float>((uint64_t{1} << target_bits) - 1);
      const float scale_factor = max_abs / target_range;
      std::vector<float> scales;
      scales.push_back(scale_factor);
      primitive_attr attr;
      attr.set_output_scales(0, scales);
      std::vector<primitive> net;

      // Create reorder primitive and then execute.
      auto reorder_pd =
          ReorderPd(cpu_engine, src.GetUsrMem()->get_desc(), cpu_engine,
                    dst.GetUsrMem()->get_desc(), attr);
      net.push_back(reorder(reorder_pd));
      std::vector<std::unordered_map<int, memory>> reorder_net_args;
      reorder_net_args.push_back(
          {{DNNL_ARG_FROM, *src.GetUsrMem()}, {DNNL_ARG_TO, *dst.GetUsrMem()}});
      execute_primitives(net, reorder_stream, reorder_net_args);
    } catch (dnnl::error& e) {
      string error_msg = "Status: " + std::to_string(e.status) +
                         ", message: " + string(e.message) + ", in file " +
                         string(__FILE__) + ":" + std::to_string(__LINE__);
      OP_REQUIRES_OK(
          ctx, errors::Aborted("Operation received an exception:", error_msg));
    }
  }

 private:
  const size_t kSrcIndex = 0;
  const size_t kMinIndex = 1;
  const size_t kMaxIndex = 2;
};

REGISTER_KERNEL_BUILDER(Name("_MklDequantize")
                            .Device(DEVICE_CPU)
                            .TypeConstraint<quint8>("T")
                            .Label(mkl_op_registry::kMklQuantizedOpLabel),
                        MklDequantizeOp<CPUDevice, quint8, true>);
REGISTER_KERNEL_BUILDER(Name("_MklDequantize")
                            .Device(DEVICE_CPU)
                            .TypeConstraint<qint8>("T")
                            .Label(mkl_op_registry::kMklQuantizedOpLabel),
                        MklDequantizeOp<CPUDevice, qint8, true>);

}  // namespace tensorflow

#endif  // INTEL_MKL


text:
package apple.audiotoolbox.struct;

import org.moe.natj.c.StructObject;
import org.moe.natj.c.ann.Structure;
import org.moe.natj.c.ann.StructureField;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.Generated;

@Generated
@Structure()
public final class AudioFilePacketTableInfo extends StructObject {
    private static long __natjCache;

    static {
        NatJ.register();
    }

    @Generated
    public AudioFilePacketTableInfo() {
        super(AudioFilePacketTableInfo.class);
    }

    @Generated
    protected AudioFilePacketTableInfo(Pointer peer) {
        super(peer);
    }

    @Generated
    public AudioFilePacketTableInfo(long mNumberValidFrames, int mPrimingFrames, int mRemainderFrames) {
        super(AudioFilePacketTableInfo.class);
        setMNumberValidFrames(mNumberValidFrames);
        setMPrimingFrames(mPrimingFrames);
        setMRemainderFrames(mRemainderFrames);
    }

    @Generated
    @StructureField(order = 0, isGetter = true)
    public native long mNumberValidFrames();

    @Generated
    @StructureField(order = 0, isGetter = false)
    public native void setMNumberValidFrames(long value);

    @Generated
    @StructureField(order = 1, isGetter = true)
    public native int mPrimingFrames();

    @Generated
    @StructureField(order = 1, isGetter = false)
    public native void setMPrimingFrames(int value);

    @Generated
    @StructureField(order = 2, isGetter = true)
    public native int mRemainderFrames();

    @Generated
    @StructureField(order = 2, isGetter = false)
    public native void setMRemainderFrames(int value);
}


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W27483_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans22.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">NORTH DAKOTA
Oil and Gas Division 97% 3
Lynn D. Helms ~ Director Bruce E. Hicks — Assistant Director Department of Mineral Resources Lynn D. Helms - Director
North Dakota Industrial Commission on. AN!) GAS DIVISION www.dmr.nd.gov/oilgas

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">December 15, 2014

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">EMERALD OIL, INC 1600 BROADWAY, SUITE 1360 DENVER, CO 80202

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">JOEL GOODSEN 4-32-29H SESW Sec. 32-149N—102W MCKENZIE COUNTY WELL FILE NO. 27483

    <p class="styleSans12.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Gentlemen:
The records and files of the Industrial Commission indicate that the above referenced permit will expire January 16, 2015.
Permits to drill are only valid for one year in the State of North Dakota. If you would like to renew for another year, please submit a Form 4 along with the $100.00 filing fee. Alternatively, you may elect to send in a Form 4 cancelling the permit. If you have any questions, please
contact Todd Holweger.

    <p class="styleSans27.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Sincerely,
96W"?
Jeanette Bean Administrative Assistant

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">
600 E Boulevard Ave - Dept 405, Bismarck, North Dakota 58505-0840 Phone (701)328—8020 Fax (701)328-8022

    <p class="styleSans15.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">aflw


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports System.IO
Imports System.Text

Friend Module Program
    Public Function Main(args As String()) As Integer
        If args.Length <> 2 Then
            Console.WriteLine(
"Usage: VBErrorFactsGenerator.exe input output
  input     The path to Errors.vb
  output    The path to ErrorFacts.Generated.vb")
            Return -1
        End If

        Dim inputPath = args(0)
        Dim outputPath = args(1)

        Dim outputText = New StringBuilder
        outputText.AppendLine("Namespace Microsoft.CodeAnalysis.VisualBasic")
        outputText.AppendLine("    Friend Partial Module ErrorFacts")

        Dim warningCodeNames, fatalCodeNames, infoCodeNames, hiddenCodeNames As New List(Of String)
        For Each line In From l In File.ReadAllLines(inputPath) Select l.Trim
            If line.StartsWith("WRN_", StringComparison.OrdinalIgnoreCase) Then
                warningCodeNames.Add(line.Substring(0, line.IndexOf(" "c)))
            ElseIf line.StartsWith("FTL_", StringComparison.OrdinalIgnoreCase) Then
                fatalCodeNames.Add(line.Substring(0, line.IndexOf(" "c)))
            ElseIf line.StartsWith("INF_", StringComparison.OrdinalIgnoreCase) Then
                infoCodeNames.Add(line.Substring(0, line.IndexOf(" "c)))
            ElseIf line.StartsWith("HDN_", StringComparison.OrdinalIgnoreCase) Then
                hiddenCodeNames.Add(line.Substring(0, line.IndexOf(" "c)))
            End If
        Next

        GenerateErrorFactsFunction("IsWarning", warningCodeNames, outputText)
        outputText.AppendLine()
        GenerateErrorFactsFunction("IsFatal", fatalCodeNames, outputText)
        outputText.AppendLine()
        GenerateErrorFactsFunction("IsInfo", infoCodeNames, outputText)
        outputText.AppendLine()
        GenerateErrorFactsFunction("IsHidden", hiddenCodeNames, outputText)

        outputText.AppendLine("    End Module")
        outputText.AppendLine("End Namespace")
        File.WriteAllText(outputPath, outputText.ToString())

        Return 0
    End Function

    Private Sub GenerateErrorFactsFunction(functionName As String, codeNames As List(Of String), outputText As StringBuilder)
        outputText.AppendLine(String.Format("        Public Function {0}(code as ERRID) As Boolean", functionName))
        outputText.AppendLine("            Select Case code")
        Dim index = 0
        For Each name In codeNames
            If index = 0 Then
                outputText.Append("                Case ERRID.")
            Else
                outputText.Append("                     ERRID.")
            End If
            outputText.Append(name)
            index += 1
            If index = codeNames.Count Then
                outputText.AppendLine()
                outputText.AppendLine("                    Return True")
            Else
                outputText.AppendLine(",")
            End If
        Next
        outputText.AppendLine("                Case Else")
        outputText.AppendLine("                    Return False")
        outputText.AppendLine("            End Select")
        outputText.AppendLine("        End Function")
    End Sub
End Module


text:
#include "perfetto/ext/base/subprocess.h"

#if PERFETTO_HAS_SUBPROCESS()
#include <thread>

#include <signal.h>
#include <sys/stat.h>
#include <unistd.h>

#include "perfetto/ext/base/file_utils.h"
#include "perfetto/ext/base/temp_file.h"
#include "test/gtest_and_gmock.h"

namespace perfetto {
namespace base {
namespace {

std::string GenLargeString() {
  std::string contents;
  for (int i = 0; i < 4096; i++) {
    contents += "very long text " + std::to_string(i) + "\n";
  }
  // Make sure that |contents| is > the default pipe buffer on Linux (4 pages).
  PERFETTO_DCHECK(contents.size() > 4096 * 4);
  return contents;
}

TEST(SubprocessTest, InvalidPath) {
  Subprocess p({"/usr/bin/invalid_1337"});
  EXPECT_FALSE(p.Call());
  EXPECT_EQ(p.status(), Subprocess::kExited);
  EXPECT_EQ(p.returncode(), 128);
  EXPECT_EQ(p.output(), "execve() failed\n");
}

TEST(SubprocessTest, StdoutOnly) {
  Subprocess p({"sh", "-c", "(echo skip_err >&2); echo out_only"});
  p.args.stdout_mode = Subprocess::kBuffer;
  p.args.stderr_mode = Subprocess::kDevNull;
  EXPECT_TRUE(p.Call());
  EXPECT_EQ(p.status(), Subprocess::kExited);
  EXPECT_EQ(p.output(), "out_only\n");
}

TEST(SubprocessTest, StderrOnly) {
  Subprocess p({"sh", "-c", "(echo err_only >&2); echo skip_out"});
  p.args.stdout_mode = Subprocess::kDevNull;
  p.args.stderr_mode = Subprocess::kBuffer;
  EXPECT_TRUE(p.Call());
  EXPECT_EQ(p.output(), "err_only\n");
}

TEST(SubprocessTest, BothStdoutAndStderr) {
  Subprocess p({"sh", "-c", "echo out; (echo err >&2); echo out2"});
  p.args.stdout_mode = Subprocess::kBuffer;
  p.args.stderr_mode = Subprocess::kBuffer;
  EXPECT_TRUE(p.Call());
  EXPECT_EQ(p.output(), "out\nerr\nout2\n");
}

TEST(SubprocessTest, BinTrue) {
  Subprocess p({"true"});
  EXPECT_TRUE(p.Call());
  EXPECT_EQ(p.status(), Subprocess::kExited);
  EXPECT_EQ(p.returncode(), 0);
}

TEST(SubprocessTest, BinFalse) {
  Subprocess p({"false"});
  EXPECT_FALSE(p.Call());
  EXPECT_EQ(p.status(), Subprocess::kExited);
  EXPECT_EQ(p.returncode(), 1);
}

TEST(SubprocessTest, Echo) {
  Subprocess p({"echo", "-n", "foobar"});
  p.args.stdout_mode = Subprocess::kBuffer;
  EXPECT_TRUE(p.Call());
  EXPECT_EQ(p.status(), Subprocess::kExited);
  EXPECT_EQ(p.returncode(), 0);
  EXPECT_EQ(p.output(), "foobar");
}

TEST(SubprocessTest, FeedbackLongInput) {
  std::string contents = GenLargeString();
  Subprocess p({"cat", "-"});
  p.args.stdout_mode = Subprocess::kBuffer;
  p.args.input = contents;
  EXPECT_TRUE(p.Call());
  EXPECT_EQ(p.status(), Subprocess::kExited);
  EXPECT_EQ(p.returncode(), 0);
  EXPECT_EQ(p.output(), contents);
}

TEST(SubprocessTest, CatLargeFile) {
  std::string contents = GenLargeString();
  TempFile tf = TempFile::Create();
  WriteAll(tf.fd(), contents.data(), contents.size());
  FlushFile(tf.fd());
  Subprocess p({"cat", tf.path().c_str()});
  p.args.stdout_mode = Subprocess::kBuffer;
  EXPECT_TRUE(p.Call());
  EXPECT_EQ(p.output(), contents);
}

TEST(SubprocessTest, Timeout) {
  Subprocess p({"sleep", "60"});
  EXPECT_FALSE(p.Call(/*timeout_ms=*/1));
  EXPECT_EQ(p.status(), Subprocess::kKilledBySignal);
}

TEST(SubprocessTest, TimeoutNotHit) {
  Subprocess p({"sleep", "0.01"});
  EXPECT_TRUE(p.Call(/*timeout_ms=*/100000));
}

TEST(SubprocessTest, TimeoutStopOutput) {
  Subprocess p({"sh", "-c", "while true; do echo stuff; done"});
  p.args.stdout_mode = Subprocess::kDevNull;
  EXPECT_FALSE(p.Call(/*timeout_ms=*/10));
  EXPECT_EQ(p.status(), Subprocess::kKilledBySignal);
}

TEST(SubprocessTest, ExitBeforeReadingStdin) {
  // 'sh -c' is to avoid closing stdin (sleep closes it before sleeping).
  Subprocess p({"sh", "-c", "sleep 0.01"});
  p.args.stdout_mode = Subprocess::kDevNull;
  p.args.stderr_mode = Subprocess::kDevNull;
  p.args.input = GenLargeString();
  EXPECT_TRUE(p.Call());
  EXPECT_EQ(p.status(), Subprocess::kExited);
  EXPECT_EQ(p.returncode(), 0);
}

TEST(SubprocessTest, StdinWriteStall) {
  // 'sh -c' is to avoid closing stdin (sleep closes it before sleeping).
  // This causes a situation where the write on the stdin will stall because
  // nobody reads it and the pipe buffer fills up. In this situation we should
  // still handle the timeout properly.
  Subprocess p({"sh", "-c", "sleep 10"});
  p.args.stdout_mode = Subprocess::kDevNull;
  p.args.stderr_mode = Subprocess::kDevNull;
  p.args.input = GenLargeString();
  EXPECT_FALSE(p.Call(/*timeout_ms=*/10));
  EXPECT_EQ(p.status(), Subprocess::kKilledBySignal);
}

TEST(SubprocessTest, StartAndWait) {
  Subprocess p({"sleep", "1000"});
  p.Start();
  EXPECT_EQ(p.Poll(), Subprocess::kRunning);
  p.KillAndWaitForTermination();
  EXPECT_EQ(p.status(), Subprocess::kKilledBySignal);
  EXPECT_EQ(p.Poll(), Subprocess::kKilledBySignal);
  EXPECT_EQ(p.returncode(), 128 + SIGKILL);
}

TEST(SubprocessTest, PollBehavesProperly) {
  Subprocess p({"sh", "-c", "echo foobar"});
  p.args.stdout_mode = Subprocess::kBuffer;
  p.args.input = "ignored";
  p.Start();

  // Here we use kill() as a way to tell if the process is still running.
  // SIGWINCH is ignored by default.
  while (kill(p.pid(), SIGWINCH) == 0) {
    usleep(1000);
  }

  // At this point Poll() must detect the termination.
  EXPECT_EQ(p.Poll(), Subprocess::kExited);
  EXPECT_EQ(p.returncode(), 0);
}

// Test the case of passing a lambda in |entrypoint| but no cmd.c
TEST(SubprocessTest, Entrypoint) {
  Subprocess p;
  p.args.input = "ping\n";
  p.args.stdout_mode = Subprocess::kBuffer;
  p.args.entrypoint_for_testing = [] {
    char buf[32]{};
    PERFETTO_CHECK(fgets(buf, sizeof(buf), stdin));
    PERFETTO_CHECK(strcmp(buf, "ping\n") == 0);
    printf("pong\n");
    fflush(stdout);
    _exit(42);
  };
  EXPECT_FALSE(p.Call());
  EXPECT_EQ(p.returncode(), 42);
  EXPECT_EQ(p.output(), "pong\n");
}

// Test the case of passing both a lambda entrypoint and a process to exec.
TEST(SubprocessTest, EntrypointAndExec) {
  base::Pipe pipe1 = base::Pipe::Create();
  base::Pipe pipe2 = base::Pipe::Create();
  int pipe1_wr = *pipe1.wr;
  int pipe2_wr = *pipe2.wr;

  Subprocess p({"echo", "123"});
  p.args.stdout_mode = Subprocess::kBuffer;
  p.args.preserve_fds.push_back(pipe2_wr);
  p.args.entrypoint_for_testing = [pipe1_wr, pipe2_wr] {
    base::ignore_result(write(pipe1_wr, "fail", 4));
    base::ignore_result(write(pipe2_wr, "pass", 4));
  };

  p.Start();
  pipe1.wr.reset();
  pipe2.wr.reset();

  char buf[8];
  EXPECT_LE(read(*pipe1.rd, buf, sizeof(buf)), 0);
  EXPECT_EQ(read(*pipe2.rd, buf, sizeof(buf)), 4);
  buf[4] = '\0';
  EXPECT_STREQ(buf, "pass");
  EXPECT_TRUE(p.Wait());
  EXPECT_EQ(p.status(), Subprocess::kExited);
  EXPECT_EQ(p.output(), "123\n");
}

TEST(SubprocessTest, Wait) {
  Subprocess p({"sleep", "10000"});
  p.Start();
  for (int i = 0; i < 3; i++) {
    EXPECT_FALSE(p.Wait(1 /*ms*/));
    EXPECT_EQ(p.status(), Subprocess::kRunning);
  }
  kill(p.pid(), SIGBUS);
  EXPECT_TRUE(p.Wait(30000 /*ms*/));
  EXPECT_TRUE(p.Wait());  // Should be a no-op.
  EXPECT_EQ(p.status(), Subprocess::kKilledBySignal);
  EXPECT_EQ(p.returncode(), 128 + SIGBUS);
}

TEST(SubprocessTest, KillOnDtor) {
  // Here we use kill(SIGWINCH) as a way to tell if the process is still alive.
  // SIGWINCH is one of the few signals that has default ignore disposition.
  int pid;
  {
    Subprocess p({"sleep", "10000"});
    p.Start();
    pid = p.pid();
    EXPECT_EQ(kill(pid, SIGWINCH), 0);
  }
  EXPECT_EQ(kill(pid, SIGWINCH), -1);
}

}  // namespace
}  // namespace base
}  // namespace perfetto

#endif  // PERFETTO_HAS_SUBPROCESS()


text:
explain plan for select * from (
-- Verification for DRILL-3653
select
        count(c_integer),
        count(c_integer) over (partition by c_boolean order by c_date desc)
from
        j1_v
group by
        c_boolean,
        c_integer,
        c_date
order by
        row_number()   over (order by c_date)

) t limit 0;


text:
namespace chrono {
namespace vehicle {
namespace hmmwv {

/// @addtogroup vehicle_models_hmmwv
/// @{

/// HMMWV vehicle system using full double wishbone suspension (control arms modeled using rigid bodies)
class CH_MODELS_API HMMWV_VehicleFull : public HMMWV_Vehicle {
  public:
    HMMWV_VehicleFull(const bool fixed = false,
                      DrivelineType drive_type = DrivelineType::AWD,
                      ChMaterialSurface::ContactMethod contact_method = ChMaterialSurface::NSC,
                      ChassisCollisionType chassis_collision_type = ChassisCollisionType::NONE);

    HMMWV_VehicleFull(ChSystem* system,
                      const bool fixed = false,
                      DrivelineType drive_type = DrivelineType::AWD,
                      ChassisCollisionType chassis_collision_type = ChassisCollisionType::NONE);

    ~HMMWV_VehicleFull();

    double GetSpringForce(const WheelID& wheel_id) const;
    double GetSpringLength(const WheelID& wheel_id) const;
    double GetSpringDeformation(const WheelID& wheel_id) const;

    double GetShockForce(const WheelID& wheel_id) const;
    double GetShockLength(const WheelID& wheel_id) const;
    double GetShockVelocity(const WheelID& wheel_id) const;

    virtual void Initialize(const ChCoordsys<>& chassisPos, double chassisFwdVel = 0) override;

    // Log debugging information
    void LogHardpointLocations();  /// suspension hardpoints at design
    void DebugLog(int what);       /// shock forces and lengths, constraints, etc.

  private:
    void Create(bool fixed, ChassisCollisionType chassis_collision_type);
};

/// @} vehicle_models_hmmwv

}  // end namespace hmmwv
}  // end namespace vehicle
}  // end namespace chrono

#endif


text:
<?php
return array (
  'Could not find requested file!' => 'Den begärda filen hittades inte!',
  'Insufficient permissions!' => 'Otillräckliga rättigheter!',
);


text:
<title>ToonTalk - Toon Talk e Java</title>
<link rel="stylesheet" type="text/css" href="../toontalk.css">

início •
busca •
compra •
manual •
novidades •
dúvidas •
suporte •
download •
imprensa •
contato

Toon Talk e Java

O Toon Talk pode produzir um applet Java a partir de um programa do Toon Talk.

Deve-se apanhar a interface para traduzir para um applet Java, pressionar pausa, então clicar em "Come Back Later"( Retornar Depois). Você agora se mudou, metaforicamente, do Toon Talk, e está no ambiente Windows. Se tudo correr bem, um navegador será lançado e você verá seu programa rodando.
Para tentar por si mesmo, vá para a agenda de exemplos na página 6 e apanhe o robô que acrescenta repetidamente 1 na página 2.
Pressione pausa e clique em "Come Back Later" (Retornar Depois). Quando o applet aparecer em seu navegador, clique em "Start" e observe o número crescer. Apenas os robôs, caminhões e imagens gerarão um aplicativo Java se forem segurados enquanto o Toon Talk é suspenso. Um robô correrá com uma caixa como a que ele foi treinado. Quando estiver carregando o caminhão, você precisará pressionar F8 para pará-lo, para dirigi-lo. Você pode colocar um grupo de texto no caminhão para nomear o aplicativo.
Se você desejar que seus robôs utilizem uma agenda especial, terá de colocar uma cópia da agenda no caminhão. Para nomear um aplicativo gerado por uma imagem (tipicamente com robôs atrás), apenas acrescente um grupo de texto atrás da imagem.

Um aplicativo pode interrogar o usuário sobre os
valores. Se você traduzir para Java alguma coisa com um ninho
em uma caixa (e o pássaro para  aquele ninho não foi também traduzido para Java) e você tem de colocar uma etiqueta sob a abertura, então quando o aplicativo precisar de um valor e encontrar o ninho ele perguntará ao usuário pelo valor, imprimindo a etiqueta.
De forma similar, se um pássaro está numa abertura etiquetada e recebe algo, a etiqueta é impressa com uma descrição da coisa dada ao pássaro. A idéia é que os pássaros
e ninhos estão sendo usados para comunicação para, e a partir de, um aplicativo Java.

Esta capacidade exige um browser habilitado para Java, tal como o Microsoft Internet Explorer 4.0 (disponível no CD-Rom do Toon Talk ou em www.microsoft.com/ie) ou o Nestcape Navigator 4.0 (disponível em www.netscape.com).
  O Java para o compilador de códigos de byte roda apenas em Windows 95 ou NT. Conseqüentemente, no Windows 3.1, o Toon Talk  pode gerar Java, mas você precisará compilá-lo de algum modo. (Você pode utilizar um serviço grátis de compilação na net.)

O Microsoft Internet Explorer (versão 4.0 SP1) (parte da primeira versão do Windows 98) algumas vezes tem uma "falha de página inválida" quando se tenta rodar um aplicativo Java gerado pelo Toon Talk. Algumas vezes, o navegador trava ou relata uma mensagem de erro. Você pode selecionar "Opções da Internet", sob o menu "Exibir", clicar na aba "Avançadas" e fazer a rolagem até "Compilador do Java JIT ativado". Assegure-se de que a marca de checagem está removida. Isto deve corrigir o problema, mas tornará mais lentas todas as aplicações de Java. Este problema com o Internet Explorer foi reportado para a Microsoft e foi corrigido na versão 5.0 Beta. Por favor, comunique quaisquer problemas que persistirem com o JIT desligado.

Para ver e rodar alguns programas de amostra traduzidos do Toon Talk para Java, clique aqui.

início •
busca •
compra •
manual •
novidades •
dúvidas •
suporte •
download •
imprensa •
contato


text:
'use strict';

import React from 'react/addons';
import Artist from '../src/Artist';

var TestUtils = React.addons.TestUtils;

describe('Artist', () => {
  var component;

  beforeEach(() => {
    component = TestUtils.renderIntoDocument(<Artist name="Run the Jewels" />);
  });

  it('should display the correct artist name', () => {
    expect(component.getDOMNode().textContent).toMatch(/Artist name: Run the Jewels/);
  });
});