text:
yqlcpp
======

yqlcpp is a lightweight C++ API for performing Yahoo Query Language queries.

At this time it is intended to be a simple interface with minimal error
checking and no concern for thread safety. Built on top of and requires libcurl.

Licensed under the MIT license.

## Usage

```
#include "yqlcpp.hpp"

// query setup, optional parameter to specify JSON/XML defaulting to JSON
yqlcpp::yqlquery query("select * from yahoo.finance.quotes where symbol='AAPL'");

// execute the query
query.execute();

// get the response string
std::string jsonData = query.getResponse();

// optional save response data to file
query.toFile("aaplquote.json");
```

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/renderer/safe_browsing/phishing_classifier_delegate.h"

#include "base/memory/scoped_ptr.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/common/safe_browsing/csd.pb.h"
#include "chrome/common/safe_browsing/safebrowsing_messages.h"
#include "chrome/renderer/safe_browsing/features.h"
#include "chrome/renderer/safe_browsing/phishing_classifier.h"
#include "chrome/renderer/safe_browsing/scorer.h"
#include "chrome/test/base/chrome_render_view_test.h"
#include "chrome/test/base/chrome_unit_test_suite.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_view.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "third_party/WebKit/public/platform/WebURL.h"
#include "third_party/WebKit/public/platform/WebURLRequest.h"
#include "url/gurl.h"

using base::ASCIIToUTF16;
using ::testing::_;
using ::testing::InSequence;
using ::testing::Mock;
using ::testing::Pointee;
using ::testing::StrictMock;

namespace safe_browsing {

namespace {

class MockPhishingClassifier : public PhishingClassifier {
 public:
  explicit MockPhishingClassifier(content::RenderFrame* render_frame)
      : PhishingClassifier(render_frame, NULL /* clock */) {}

  virtual ~MockPhishingClassifier() {}

  MOCK_METHOD2(BeginClassification,
               void(const base::string16*, const DoneCallback&));
  MOCK_METHOD0(CancelPendingClassification, void());

 private:
  DISALLOW_COPY_AND_ASSIGN(MockPhishingClassifier);
};

class MockScorer : public Scorer {
 public:
  MockScorer() : Scorer() {}
  virtual ~MockScorer() {}

  MOCK_CONST_METHOD1(ComputeScore, double(const FeatureMap&));

 private:
  DISALLOW_COPY_AND_ASSIGN(MockScorer);
};
}  // namespace

class FakeRenderThread : public ChromeMockRenderThread {
 public:
  // Instead of sending this message, we verify its content here.
  bool Send(IPC::Message* msg) override {
    // handle and verify message here.
    IPC_BEGIN_MESSAGE_MAP(FakeRenderThread, *msg)
      IPC_MESSAGE_HANDLER(SafeBrowsingHostMsg_PhishingDetectionDone,
                          VerifyMessageContent)
    IPC_END_MESSAGE_MAP()
    if (msg) {  // Prevent memory leak.
      delete msg;
      msg = nullptr;
    }
    // Return true anyway, since we don't want to block other IPC.
    return true;
  }

  void VerifyMessageContent(const std::string& verdict_str) {
    ClientPhishingRequest verdict;
    if (verdict.ParseFromString(verdict_str)) {
      EXPECT_EQ("http://host.com/", verdict.url());
      EXPECT_EQ(0.8f, verdict.client_score());
      EXPECT_EQ(false, verdict.is_phishing());
    } else {
      NOTREACHED() << "Cannot parse IPC content. Test failed.";
    }
  }
};

class PhishingClassifierDelegateTest : public ChromeRenderViewTest {
 protected:
  void SetUp() override {
    ChromeUnitTestSuite::InitializeProviders();
    ChromeUnitTestSuite::InitializeResourceBundle();

    // Plug-in FakeRenderThread.
    chrome_render_thread_ = new FakeRenderThread();
    render_thread_.reset(chrome_render_thread_);

    content::RenderViewTest::SetUp();

    content::RenderFrame* render_frame = view_->GetMainRenderFrame();
    classifier_ = new StrictMock<MockPhishingClassifier>(render_frame);
    delegate_ = PhishingClassifierDelegate::Create(render_frame, classifier_);
  }

  // Runs the ClassificationDone callback, then verify if message sent
  // by FakeRenderThread is correct.
  void RunAndVerifyClassificationDone(const ClientPhishingRequest& verdict) {
    delegate_->ClassificationDone(verdict);
  }

  void OnStartPhishingDetection(const GURL& url) {
    delegate_->OnStartPhishingDetection(url);
  }

  void PageCaptured(base::string16* page_text,
                    bool preliminary_capture,
                    const GURL& page_url) {
    if (preliminary_capture)
      return;

    delegate_->CancelPendingClassification(
        PhishingClassifierDelegate::PAGE_RECAPTURED);
    delegate_->last_finished_load_url_ = page_url;
    delegate_->classifier_page_text_.swap(*page_text);
    delegate_->have_page_text_ = true;
    delegate_->MaybeStartClassification();
  }

  void SimulateRedirection(const GURL& redir_url) {
    delegate_->last_url_received_from_browser_ = redir_url;
  }

  void SimulatePageTrantitionForwardOrBack(const char* html, const char* url) {
    LoadHTMLWithUrlOverride(html, url);
    delegate_->last_main_frame_transition_ = ui::PAGE_TRANSITION_FORWARD_BACK;
  }

  StrictMock<MockPhishingClassifier>* classifier_;  // Owned by |delegate_|.
  PhishingClassifierDelegate* delegate_;            // Owned by the RenderFrame.
};

TEST_F(PhishingClassifierDelegateTest, Navigation) {
  MockScorer scorer;
  delegate_->SetPhishingScorer(&scorer);
  ASSERT_TRUE(classifier_->is_ready());

  // Test an initial load.  We expect classification to happen normally.
  EXPECT_CALL(*classifier_, CancelPendingClassification());
  std::string html = "dummy";
  GURL url("http://host.com/index.html");
  LoadHTMLWithUrlOverride(html.c_str(), url.spec().c_str());
  Mock::VerifyAndClearExpectations(classifier_);

  OnStartPhishingDetection(url);
  base::string16 page_text = ASCIIToUTF16("dummy");
  {
    InSequence s;
    EXPECT_CALL(*classifier_, CancelPendingClassification());
    EXPECT_CALL(*classifier_, BeginClassification(Pointee(page_text), _));
    PageCaptured(&page_text, false, url);
    Mock::VerifyAndClearExpectations(classifier_);
  }

  // Reloading the same page should not trigger a reclassification.
  // However, it will cancel any pending classification since the
  // content is being replaced.
  EXPECT_CALL(*classifier_, CancelPendingClassification());
  LoadHTMLWithUrlOverride(html.c_str(), url.spec().c_str());
  Mock::VerifyAndClearExpectations(classifier_);

  OnStartPhishingDetection(url);
  page_text = ASCIIToUTF16("dummy");
  EXPECT_CALL(*classifier_, CancelPendingClassification());
  PageCaptured(&page_text, false, url);
  Mock::VerifyAndClearExpectations(classifier_);

  OnStartPhishingDetection(url);
  page_text = ASCIIToUTF16("dummy");
  EXPECT_CALL(*classifier_, CancelPendingClassification());
  PageCaptured(&page_text, false, url);
  Mock::VerifyAndClearExpectations(classifier_);

  // Navigating within page works similarly to a subframe navigation, but
  // see the TODO in PhishingClassifierDelegate::DidCommitProvisionalLoad.
  EXPECT_CALL(*classifier_, CancelPendingClassification());
  DidNavigateWithinPage(GetMainFrame(), true);
  Mock::VerifyAndClearExpectations(classifier_);

  OnStartPhishingDetection(url);
  page_text = ASCIIToUTF16("dummy");
  EXPECT_CALL(*classifier_, CancelPendingClassification());
  PageCaptured(&page_text, false, url);
  Mock::VerifyAndClearExpectations(classifier_);

  // Now load a new toplevel page, which should trigger another classification.
  EXPECT_CALL(*classifier_, CancelPendingClassification());
  GURL new_url("http://host2.com");
  LoadHTMLWithUrlOverride("dummy2", new_url.spec().c_str());
  Mock::VerifyAndClearExpectations(classifier_);

  page_text = ASCIIToUTF16("dummy2");
  OnStartPhishingDetection(new_url);
  {
    InSequence s;
    EXPECT_CALL(*classifier_, CancelPendingClassification());
    EXPECT_CALL(*classifier_, BeginClassification(Pointee(page_text), _));
    PageCaptured(&page_text, false, new_url);
    Mock::VerifyAndClearExpectations(classifier_);
  }

  // No classification should happen on back/forward navigation.
  // Note: in practice, the browser will not send a StartPhishingDetection IPC
  // in this case.  However, we want to make sure that the delegate behaves
  // correctly regardless.
  EXPECT_CALL(*classifier_, CancelPendingClassification()).Times(1);
  // Simulate a go back navigation, i.e. back to http://host.com/index.html.
  SimulatePageTrantitionForwardOrBack(html.c_str(), url.spec().c_str());
  Mock::VerifyAndClearExpectations(classifier_);
  page_text = ASCIIToUTF16("dummy");
  OnStartPhishingDetection(new_url);
  EXPECT_CALL(*classifier_, CancelPendingClassification());
  PageCaptured(&page_text, false, new_url);
  Mock::VerifyAndClearExpectations(classifier_);

  EXPECT_CALL(*classifier_, CancelPendingClassification());
  // Simulate a go forward navigation, i.e. forward to http://host.com
  SimulatePageTrantitionForwardOrBack("dummy2", new_url.spec().c_str());
  Mock::VerifyAndClearExpectations(classifier_);

  page_text = ASCIIToUTF16("dummy2");
  OnStartPhishingDetection(url);
  EXPECT_CALL(*classifier_, CancelPendingClassification());
  PageCaptured(&page_text, false, url);
  Mock::VerifyAndClearExpectations(classifier_);

  // Now go back again and navigate to a different place within
  // the same page. No classification should happen.
  EXPECT_CALL(*classifier_, CancelPendingClassification());
  // Simulate a go back again to http://host.com/index.html
  SimulatePageTrantitionForwardOrBack(html.c_str(), url.spec().c_str());
  Mock::VerifyAndClearExpectations(classifier_);

  page_text = ASCIIToUTF16("dummy");
  OnStartPhishingDetection(url);
  EXPECT_CALL(*classifier_, CancelPendingClassification());
  PageCaptured(&page_text, false, url);
  Mock::VerifyAndClearExpectations(classifier_);

  EXPECT_CALL(*classifier_, CancelPendingClassification());
  // In-page navigation.
  DidNavigateWithinPage(GetMainFrame(), true);
  Mock::VerifyAndClearExpectations(classifier_);

  OnStartPhishingDetection(url);
  page_text = ASCIIToUTF16("dummy");
  EXPECT_CALL(*classifier_, CancelPendingClassification());
  PageCaptured(&page_text, false, url);
  Mock::VerifyAndClearExpectations(classifier_);

  // The delegate will cancel pending classification on destruction.
  EXPECT_CALL(*classifier_, CancelPendingClassification());
}

TEST_F(PhishingClassifierDelegateTest, NoScorer) {
  // For this test, we'll create the delegate with no scorer available yet.
  ASSERT_FALSE(classifier_->is_ready());

  // Queue up a pending classification, cancel it, then queue up another one.
  GURL url("http://host.com");
  base::string16 page_text = ASCIIToUTF16("dummy");
  LoadHTMLWithUrlOverride("dummy", url.spec().c_str());
  OnStartPhishingDetection(url);
  PageCaptured(&page_text, false, url);

  GURL url2("http://host2.com");
  page_text = ASCIIToUTF16("dummy");
  LoadHTMLWithUrlOverride("dummy", url2.spec().c_str());
  OnStartPhishingDetection(url2);
  PageCaptured(&page_text, false, url2);

  // Now set a scorer, which should cause a classifier to be created and
  // the classification to proceed.
  page_text = ASCIIToUTF16("dummy");
  EXPECT_CALL(*classifier_, BeginClassification(Pointee(page_text), _));
  MockScorer scorer;
  delegate_->SetPhishingScorer(&scorer);
  Mock::VerifyAndClearExpectations(classifier_);

  // If we set a new scorer while a classification is going on the
  // classification should be cancelled.
  EXPECT_CALL(*classifier_, CancelPendingClassification());
  delegate_->SetPhishingScorer(&scorer);
  Mock::VerifyAndClearExpectations(classifier_);

  // The delegate will cancel pending classification on destruction.
  EXPECT_CALL(*classifier_, CancelPendingClassification());
}

TEST_F(PhishingClassifierDelegateTest, NoScorer_Ref) {
  // Similar to the last test, but navigates within the page before
  // setting the scorer.
  ASSERT_FALSE(classifier_->is_ready());

  // Queue up a pending classification, cancel it, then queue up another one.
  GURL url("http://host.com");
  base::string16 page_text = ASCIIToUTF16("dummy");
  LoadHTMLWithUrlOverride("dummy", url.spec().c_str());
  OnStartPhishingDetection(url);
  PageCaptured(&page_text, false, url);

  page_text = ASCIIToUTF16("dummy");
  OnStartPhishingDetection(url);
  PageCaptured(&page_text, false, url);

  // Now set a scorer, which should cause a classifier to be created and
  // the classification to proceed.
  page_text = ASCIIToUTF16("dummy");
  EXPECT_CALL(*classifier_, BeginClassification(Pointee(page_text), _));
  MockScorer scorer;
  delegate_->SetPhishingScorer(&scorer);
  Mock::VerifyAndClearExpectations(classifier_);

  // If we set a new scorer while a classification is going on the
  // classification should be cancelled.
  EXPECT_CALL(*classifier_, CancelPendingClassification());
  delegate_->SetPhishingScorer(&scorer);
  Mock::VerifyAndClearExpectations(classifier_);

  // The delegate will cancel pending classification on destruction.
  EXPECT_CALL(*classifier_, CancelPendingClassification());
}

TEST_F(PhishingClassifierDelegateTest, NoStartPhishingDetection) {
  // Tests the behavior when OnStartPhishingDetection has not yet been called
  // when the page load finishes.
  MockScorer scorer;
  delegate_->SetPhishingScorer(&scorer);
  ASSERT_TRUE(classifier_->is_ready());

  EXPECT_CALL(*classifier_, CancelPendingClassification());
  GURL url("http://host.com");
  LoadHTMLWithUrlOverride("phish",
                          url.spec().c_str());
  Mock::VerifyAndClearExpectations(classifier_);
  base::string16 page_text = ASCIIToUTF16("phish");
  EXPECT_CALL(*classifier_, CancelPendingClassification());
  PageCaptured(&page_text, false, url);
  Mock::VerifyAndClearExpectations(classifier_);
  // Now simulate the StartPhishingDetection IPC.  We expect classification
  // to begin.
  page_text = ASCIIToUTF16("phish");
  EXPECT_CALL(*classifier_, BeginClassification(Pointee(page_text), _));
  OnStartPhishingDetection(url);
  Mock::VerifyAndClearExpectations(classifier_);

  // Now try again, but this time we will navigate the page away before
  // the IPC is sent.
  EXPECT_CALL(*classifier_, CancelPendingClassification());
  GURL url2("http://host2.com");
  LoadHTMLWithUrlOverride("phish",
                          url2.spec().c_str());
  Mock::VerifyAndClearExpectations(classifier_);
  page_text = ASCIIToUTF16("phish");
  EXPECT_CALL(*classifier_, CancelPendingClassification());
  PageCaptured(&page_text, false, url2);
  Mock::VerifyAndClearExpectations(classifier_);

  EXPECT_CALL(*classifier_, CancelPendingClassification());
  GURL url3("http://host3.com");
  LoadHTMLWithUrlOverride("phish",
                          url3.spec().c_str());
  Mock::VerifyAndClearExpectations(classifier_);
  OnStartPhishingDetection(url);

  // In this test, the original page is a redirect, which we do not get a
  // StartPhishingDetection IPC for.  We simulate the redirection event to
  // load a new page while reusing the original session history entry, and
  // check that classification begins correctly for the landing page.
  EXPECT_CALL(*classifier_, CancelPendingClassification());
  GURL url4("http://host4.com");
  LoadHTMLWithUrlOverride("phish",
                          url4.spec().c_str());
  Mock::VerifyAndClearExpectations(classifier_);
  page_text = ASCIIToUTF16("abc");
  EXPECT_CALL(*classifier_, CancelPendingClassification());
  PageCaptured(&page_text, false, url4);
  Mock::VerifyAndClearExpectations(classifier_);
  EXPECT_CALL(*classifier_, CancelPendingClassification());

  GURL redir_url("http://host4.com/redir");
  LoadHTMLWithUrlOverride("123", redir_url.spec().c_str());
  Mock::VerifyAndClearExpectations(classifier_);
  OnStartPhishingDetection(url4);
  page_text = ASCIIToUTF16("123");
  {
    InSequence s;
    EXPECT_CALL(*classifier_, CancelPendingClassification());
    EXPECT_CALL(*classifier_, BeginClassification(Pointee(page_text), _));
    SimulateRedirection(redir_url);
    PageCaptured(&page_text, false, redir_url);
    Mock::VerifyAndClearExpectations(classifier_);
  }

  // The delegate will cancel pending classification on destruction.
  EXPECT_CALL(*classifier_, CancelPendingClassification());
}

TEST_F(PhishingClassifierDelegateTest, IgnorePreliminaryCapture) {
  // Tests that preliminary PageCaptured notifications are ignored.
  MockScorer scorer;
  delegate_->SetPhishingScorer(&scorer);
  ASSERT_TRUE(classifier_->is_ready());

  EXPECT_CALL(*classifier_, CancelPendingClassification());
  GURL url("http://host.com");
  LoadHTMLWithUrlOverride("phish",
                          url.spec().c_str());
  Mock::VerifyAndClearExpectations(classifier_);
  OnStartPhishingDetection(url);
  base::string16 page_text = ASCIIToUTF16("phish");
  PageCaptured(&page_text, true, url);

  // Once the non-preliminary capture happens, classification should begin.
  page_text = ASCIIToUTF16("phish");
  {
    InSequence s;
    EXPECT_CALL(*classifier_, CancelPendingClassification());
    EXPECT_CALL(*classifier_, BeginClassification(Pointee(page_text), _));
    PageCaptured(&page_text, false, url);
    Mock::VerifyAndClearExpectations(classifier_);
  }

  // The delegate will cancel pending classification on destruction.
  EXPECT_CALL(*classifier_, CancelPendingClassification());
}

TEST_F(PhishingClassifierDelegateTest, DuplicatePageCapture) {
  // Tests that a second PageCaptured notification causes classification to
  // be cancelled.
  MockScorer scorer;
  delegate_->SetPhishingScorer(&scorer);
  ASSERT_TRUE(classifier_->is_ready());

  EXPECT_CALL(*classifier_, CancelPendingClassification());
  GURL url("http://host.com");
  LoadHTMLWithUrlOverride("phish",
                          url.spec().c_str());
  Mock::VerifyAndClearExpectations(classifier_);
  OnStartPhishingDetection(url);
  base::string16 page_text = ASCIIToUTF16("phish");
  {
    InSequence s;
    EXPECT_CALL(*classifier_, CancelPendingClassification());
    EXPECT_CALL(*classifier_, BeginClassification(Pointee(page_text), _));
    PageCaptured(&page_text, false, url);
    Mock::VerifyAndClearExpectations(classifier_);
  }

  page_text = ASCIIToUTF16("phish");
  EXPECT_CALL(*classifier_, CancelPendingClassification());
  PageCaptured(&page_text, false, url);
  Mock::VerifyAndClearExpectations(classifier_);

  // The delegate will cancel pending classification on destruction.
  EXPECT_CALL(*classifier_, CancelPendingClassification());
}

TEST_F(PhishingClassifierDelegateTest, PhishingDetectionDone) {
  // Tests that a SafeBrowsingHostMsg_PhishingDetectionDone IPC is
  // sent to the browser whenever we finish classification.
  MockScorer scorer;
  delegate_->SetPhishingScorer(&scorer);
  ASSERT_TRUE(classifier_->is_ready());

  // Start by loading a page to populate the delegate's state.
  EXPECT_CALL(*classifier_, CancelPendingClassification());
  GURL url("http://host.com");
  LoadHTMLWithUrlOverride("phish",
                          url.spec().c_str());
  Mock::VerifyAndClearExpectations(classifier_);
  base::string16 page_text = ASCIIToUTF16("phish");
  OnStartPhishingDetection(url);
  {
    InSequence s;
    EXPECT_CALL(*classifier_, CancelPendingClassification());
    EXPECT_CALL(*classifier_, BeginClassification(Pointee(page_text), _));
    PageCaptured(&page_text, false, url);
    Mock::VerifyAndClearExpectations(classifier_);
  }

  // Now run the callback to simulate the classifier finishing.
  ClientPhishingRequest verdict;
  verdict.set_url(url.spec());
  verdict.set_client_score(0.8f);
  verdict.set_is_phishing(false);  // Send IPC even if site is not phishing.
  RunAndVerifyClassificationDone(verdict);

  // The delegate will cancel pending classification on destruction.
  EXPECT_CALL(*classifier_, CancelPendingClassification());
}

}  // namespace safe_browsing


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawerLayout"
    android:fitsSystemWindows="true"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="foodrev.org.foodrev.presentation.ui.activities.rapidprototype.messaging.ui.activities.MessageMainActivity">

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:layout_alignParentTop="true"
            android:minHeight="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@id/toolbar"
            android:paddingBottom="@dimen/activity_vertical_margin"
            android:paddingLeft="@dimen/activity_horizontal_margin"
            android:paddingRight="@dimen/activity_horizontal_margin"
            >
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_alignParentTop="true"
                android:id="@+id/channel_bar"
                android:paddingTop="8dp"
                android:paddingBottom="8dp">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/pound"
                    android:layout_marginRight="@dimen/activity_horizontal_margin"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/currentChannelName"
                    />
            </LinearLayout>
            <android.support.v7.widget.RecyclerView
                android:id="@+id/messageRecyclerView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_below="@id/channel_bar"
                android:layout_above="@+id/linearLayout"/>

            <LinearLayout
                android:id="@+id/linearLayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:orientation="vertical"
                android:weightSum="2">

                <EditText
                    android:id="@+id/messageEditText"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:hint="@string/enter_message"
                    android:inputType="textMultiLine"
                    android:paddingTop="20dp"/>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:gravity="end"
                    android:orientation="horizontal">

                    <android.support.design.widget.FloatingActionButton
                        android:id="@+id/sendButton"
                        android:elevation="100dp"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:src="@drawable/ic_send_black_24"/>
                </LinearLayout>

            </LinearLayout>

            <ProgressBar
                android:id="@+id/progressBar"
                style="?android:attr/progressBarStyleLarge"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"/>
        </RelativeLayout>

    </RelativeLayout>
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer"/>

</android.support.v4.widget.DrawerLayout>


text:
package chrome.desktopCapture

import bindings._
import chrome.tabs.bindings.Tab
import scala.concurrent.{Promise, Future}
import scala.scalajs.js
import scala.scalajs.js.JSConverters._
import utils.ErrorHandling.lastErrorOrValue

class DesktopMediaRequest(id: DesktopMediaRequestId, val result: Future[StreamId]) {
  def cancel(): Unit = DesktopCapture.cancelChooseDesktopMedia(id)
}

object DesktopCapture {

  def chooseDesktopMedia(sources: List[DesktopCaptureSourceType],
                         targetTab: js.UndefOr[Tab]): DesktopMediaRequest = {
    val promise = Promise[StreamId]()
    val id = bindings.DesktopCapture.chooseDesktopMedia(sources.toJSArray, targetTab, (streamId: StreamId) => {
      promise.complete(lastErrorOrValue(streamId))
    })
    new DesktopMediaRequest(id, promise.future)
  }

  def cancelChooseDesktopMedia(desktopMediaRequestId: DesktopMediaRequestId): Unit =
    bindings.DesktopCapture.cancelChooseDesktopMedia(desktopMediaRequestId)

}


text:
<?xml version="1.0"?>
<!--

  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

-->
<project name="ASDocs Test Experimental" default="main" basedir=".">
    <property name="FLEX_HOME" value="${basedir}/../.."/>
    <property name="flexlib" location="${FLEX_HOME}/frameworks"/>

    <property file="${FLEX_HOME}/env.properties"/>
    <property environment="env"/>
    <property file="${FLEX_HOME}/build.properties"/>

    <available file="${FLEX_HOME}/../flex-tlf/textLayout"
               type="dir"
               property="TLF_HOME"
               value="${FLEX_HOME}/../flex-tlf"/>

    <available file="${FLEX_HOME}/../tlf/textLayout"
               type="dir"
               property="TLF_HOME"
               value="${FLEX_HOME}/../tlf"/>

    <target name="main" depends="clean,doc" description="Clean build of all ASDocs"/>

    <target name="clean" description="Cleans all ASDocs">
        <delete dir="${FLEX_HOME}/asdoc-output"/>
    </target>

    <target name="doc" description="generate ASDOC for SampleExperimental class">
        <path id="flexTasks.path">
            <fileset dir="${FLEX_HOME}">
                <include name="lib/flexTasks.jar"/>
            </fileset>
        </path>
        <taskdef resource="flexTasks.tasks" classpathref="flexTasks.path"/>
        <asdoc output="${FLEX_HOME}/asdoc-output" lenient="${lenient}" failonerror="true" warnings="false"
               keep-xml="true"
               skip-xsl="false"
               strict="false" locale="en_US" fork="true">
            <doc-classes class="SampleExperimental"/>
            <compiler.source-path path-element="${basedir}/doc_src"/>
        </asdoc>
    </target>
</project>


text:
- fix: readme refs (thanks to @danferreira)
- Fix generate_and_sign examples in guides' documentation (thanks to @f-francine)
- Remove no_return from methods that can return (thanks to @jsmestad)
- Fix typos (thanks to @kianmeng)

## [2.4.0] - 2021-08-15

### Changed

- Major docs reviews and corrections (thanks to @kianmeng, @andreasknoepfle, Jon Forsyth, @fuelen)
- Change of CI pipeline (thanks to @dolfinus)
- Now uses Elixir 1.8 as minimum (and actually test the minimum version on CI)

### Fixed

- Fixed arity of `Joken.Config.validate` (thanks to @blagh)
- Compatibility with OTP 24.0 with JOSE update to 1.11.2

## [2.3.0] - 2020-09-27

### Changed

- (@supersimple with @bryanjos) Update CHANGELOG.md (#257)
- (@victorolinasc) chore: add public PEM only signer test
- (@victorolinasc) chore: update deps
- (@victorolinasc) Adding error handling (#277)
- (@ideaMarcos) Update common_use_cases.md (#285)
- (@victorolinasc) Clean up versions and compatibility with OTP 23 (#291)

### Fixed

- (@woylie) fix type specs and doc (#266)

## [2.2.0] - 2019-11-08

### Added

- (@bryanjos) Update .travis.yml to deploy to hex on tag (#232)
- (@thefuture2029) Access current_time_adapter in runtime instead of compile time (#252)
- (@victorolinasc) feat: add required claims hook (#250)

### Changed

- Bump benchee from 0.14.0 to 1.0.1
- Bump stream_data from 0.4.2 to 0.4.3 (#227)
- Bump ex_doc from 0.19.3 to 0.20.2 (#230)
- Bump dialyxir from 1.0.0-rc.4 to 1.0.0-rc.6
- Bump credo from 1.0.2 to 1.0.5
- Bump excoveralls from 0.10.5 to 0.11.1 (#233)
- Bump ex_doc from 0.20.2 to 0.21.1 (#240)
- Bump ex_doc from 0.21.1 to 0.21.2 (#246)
- Bump excoveralls from 0.11.1 to 0.11.2 (#243)
- Bump junit_formatter from 3.0.0 to 3.0.1 (#238)
- Bump dialyxir from 1.0.0-rc.6 to 1.0.0-rc.7 (#248)
- Bump credo from 1.0.5 to 1.1.5 (#253)
- Bump excoveralls from 0.11.2 to 0.12.0 (#254)

### Fixed

- (@llxff) Fix small typo in "Asymmetric cryptography signers" guide (#235)
- (@polvalente) fix: treat improper token properly (#237)
- (@chulkilee) Use short identifier from SPDX License List (#255)

## [2.1.0] - 2019-05-27

### Added

- (@tgturner) Allow custom error messages on claim validation (#221)

### Changed

- (@sgtpepper43) Get default signer at runtime (#212)
- (@balena) Update to JOSE 1.9 and remove Jason dependency (#216)
- (@victorolinasc) chore: deps update, docs update, removed unused application (#219)

### Fixed

- (@maartenvanvliet) Plural time units are deprecated >= elixir1.8 (#213)
- (@oo6) Fixed documentation (#218)
- (@popo63301) fix typo (#220)
- (@HeroicEric) Fix some typos in configuration guide (#222)

## [2.0.1] - 2019-02-17

### Changed

- Get default signer at runtime (#212) @sgtpepper43
- Update to JOSE 1.9 and remove Jason dependency (#216) @balena

### Fixed

- Plural time units are deprecated >= elixir1.8 (#213) @maartenvanvliet
- Fixed documentation (#218) @oo6

## [v2.0.0] - 2019-01-02

This is a re-write with a focus on making a clearer API surface with less ambiguity and more future proof without breaking backwards compatibility once again.

For changes on versions 1.x look on the v1.5 branch.

### Enhancements

- Ease of key configuration. We provide optional built-in support with Elixir's `Mix.Config` system. See our configuration guide for more details;
- Portable configuration using `Joken.Claim`;
- Encapsulate your token logic in a module with `Joken.Config`;
- Better error handling. We provide a lot more context in error messages;
- A good performance analysis for ensuring this hot-path in APIs won't be your bottleneck. Please see our performance documentation to check what we are talking about;
- Hooks for extending Joken functionality. All core actions in Joken have a corresponding hook for extending its functionality;
- Guides for common patterns;

### Backwards incompatible changes

- There is no `Joken.Plug` module anymore. Depending on requests we can bring that back, but we believe it is better to be on a different library;
- The API surface changed a lot but you can still use Joken with the same [token pattern as versions 1.x](http://trivelop.de/2018/05/14/flow-elixir-designing-apis/). Please see our [migrating guide](https://github.com/joken-elixir/joken/blob/master/guides/migration_from_1.md).


text:
package bcd

import (
	"errors"
	"fmt"
	"os"
	"os/exec"
	"os/signal"
	"reflect"
	"runtime"
	"strconv"
	"strings"
	"sync"
	"time"
)

var (
	// Only one tracer should be running on a process at any time; this is
	// global to all created tracers.
	traceLock chan struct{}

	// Configuration applicable to all tracer invocations.
	state globalState
)

type globalState struct {
	c GlobalConfig
	m sync.RWMutex
}

type GlobalConfig struct {
	// If the tracer's timeout expires and the tracer cannot be killed,
	// generate a run-time panic.
	//
	// Defaults to true.
	PanicOnKillFailure bool

	// Upon receipt of a signal and execution of the tracer, re-sends the
	// signal to the default Go signal handler for the signal and stops
	// listening for the signal.
	// Note: this will call signal.Reset(signal) on the received signal,
	// which undoes the effect of any signal.Notify() calls for the signal.
	//
	// Defaults to true.
	ResendSignal bool

	// Length of time to wait after completion of a tracer's
	// execution before allowing the next tracer to run.
	//
	// Defaults to 3 seconds.
	RateLimit time.Duration

	// If bcd.Trace() has been configured to attempt an upload immediately,
	// wait for the Tracer to finish uploading its results (instead of
	// asynchronously uploading in a new goroutine) before returning
	// from bcd.Trace().
	//
	// Defaults to true.
	SynchronousPut bool
}

func init() {
	// Tracer execution timeouts are supported, which is why we use a
	// channel here instead of sync.Mutex.
	traceLock = make(chan struct{}, 1)
	traceLock <- struct{}{}

	state = globalState{
		c: GlobalConfig{
			PanicOnKillFailure: true,
			ResendSignal:       true,
			RateLimit:          time.Second * 3,
			SynchronousPut:     true}}
}

// Update global Tracer configuration.
func UpdateConfig(c GlobalConfig) {
	state.m.Lock()
	defer state.m.Unlock()

	state.c = c
}

// A generic out-of-process tracer interface.
//
// This is used primarily by the top-level functions of the bcd package,
// like bcd.Trace, to handle execution and synchronization of various
// generic tracers.
//
// Tracers are not limited to this interface and may provide additional
// utility methods; see specific tracer implementation (e.g. BTTracer)
// documentation for details.
//
// The methods in this interface are expected to be goroutine safe; multiple
// trace requests (which ultimately call into these methods) from different
// goroutines may run concurrently.
type Tracer interface {
	// Store the options provided by v.
	//
	// If the options slice is non-nil, the provided options should be
	// stored in it; otherwise, the options are added to the Tracer's
	// base set of options.
	// Returns the final options slice if the provided options slice is
	// non-nil.
	AddOptions(options []string, v ...string) []string

	// Add a key-value attribute.
	//
	// See AddOptions for rules regarding the specified options slice and
	// the return value.
	AddKV(options []string, key, val string) []string

	// Add a thread filter option using the specified tid. If any thread
	// filter options are added, all non-matching threads and goroutines
	// are expected to be excluded from the generated snapshot.
	//
	// See AddOptions for rules regarding the specified options slice and
	// the return value.
	AddThreadFilter(options []string, tid int) []string

	// Add a faulted thread option using the specified tid. Threads and
	// goroutines matching any faulted thread options are marked as faulted
	// and subject to analysis and grouping.
	//
	// See AddOptions for rules regarding the specified options slice and
	// the return value.
	AddFaultedThread(options []string, tid int) []string

	// Add a caller goroutine option using the specified goid.
	//
	// See AddOptions for rules regarding the specified options slice and
	// the return value.
	AddCallerGo(options []string, goid int) []string

	// Add a classification to the generated snapshot.
	//
	// See AddOptions for rules regarding the specified options slice and
	// the return value.
	AddClassifier(options []string, classifier string) []string

	// Returns a copy of the base set of options for the Tracer.
	Options() []string

	// Clears the base set of options for the Tracer.
	ClearOptions()

	// Returns the default TraceOptions used in bcd.Trace() if an override
	// is not specified as an argument to it.
	DefaultTraceOptions() *TraceOptions

	// Accepts a final set of options and returns a Command object
	// representing a tracer that is ready to run. This will be executed
	// on the current process.
	Finalize(options []string) *exec.Cmd

	// Determines when and to what the Tracer will log.
	Log

	// String representation of a Tracer.
	fmt.Stringer

	// Returns whether the Tracer should upload its results to a remote
	// server after successful tracer execution.
	PutOnTrace() bool

	// Uploads Tracer results given by the snapshot argument, which is
	// the stdout of the Tracer process, to the configured remote server.
	//
	// As this is part of the generic Tracer interface, callers know
	// nothing about the contents of the output; thus, it is passed
	// unfiltered to the specific underlying implementation.
	Put(snapshot []byte) error
}

// Options determining actions taken during Tracer execution.
type TraceOptions struct {
	// If true, the calling thread/goroutine will be marked as faulted
	// (i.e. the cause of the error or trace request).
	//
	// This is a Linux-specific option; it results in a noop on other
	// systems.
	Faulted bool

	// If true, only the calling thread/goroutine will be traced; all others
	// will be excluded from the generated snapshot.
	//
	// This is a Linux-specific option; it results in a noop on other
	// systems.
	CallerOnly bool

	// If true and a non-nil error object is passed to bcd.Trace(), a
	// classifier will be added based on the specified error's type.
	ErrClassification bool

	// If non-nil, all contained strings will be added as classifiers to
	// the generated snapshot.
	Classifications []string

	// Amount of time to wait for the tracer to finish execution.
	// If 0 is specified, Tracer.DefaultTraceOptions()'s timeout will be
	// used. If <0 is specified, no timeout will be used; the Tracer command
	// will run until it exits.
	Timeout time.Duration

	// If non-nil, any goroutines spawned during the Trace() request will
	// be added to the wait group. This facilitates waiting for things like
	// asynchronous snapshot uploads to complete before exiting the
	// application.
	SpawnedGs *sync.WaitGroup
}

type Log interface {
	// Logs the specified message if the specified log level is enabled.
	Logf(level LogPriority, format string, v ...interface{})

	// Sets the log level to the specified bitmask of LogPriorities; all
	// priorities excluded from the mask are ignored.
	SetLogLevel(level LogPriority)
}

type LogPriority int

const (
	LogDebug = 1 << iota
	LogWarning
	LogError
	LogMax = (1 << iota) - 1
)

// This is a superset of the generic Tracer interface for those that wish
// to support signal handling. The methods unique to this interface are
// not expected to be goroutine-safe.
type TracerSig interface {
	Tracer

	// Sets the desired set of signals for which to invoke the Tracer upon
	// receipt of the signal.
	SetSigset(sigs ...os.Signal)

	// Returns the desired signal set.
	Sigset() []os.Signal

	// Sets the channel through which the Tracer will respond to signals.
	SetSigchan(sc chan os.Signal)

	// Returns the channel through which the Tracer will respond to signals.
	Sigchan() chan os.Signal
}

// Create a unique error to pass to a Trace request.
type signalError struct {
	s os.Signal
}

func (s *signalError) Error() string {
	return s.s.String()
}

// Registers a signal handler to execute the specified Tracer upon receipt of
// any signal in the set specified by TracerSig.Sigset().
// If the GlobalConfiguration value ResendSignal is true, then when a signal is
// received through this handler, all handlers for that signal will be reset
// with signal.Reset(s) after tracer execution completes. The signal will then
// be resent to the default Go handler for that signal.
func Register(t TracerSig) {
	ss := t.Sigset()
	if ss == nil || len(ss) == 0 {
		t.Logf(LogError, "Failed to register signal handler: empty "+
			"sigset\n")
		return
	}

	c := t.Sigchan()
	if c != nil {
		unregisterInternal(t, c)
	}

	c = make(chan os.Signal, len(ss))
	t.SetSigchan(c)

	signal.Notify(c, ss...)

	t.Logf(LogDebug, "Registered tracer %s (signal set: %v)\n", t, ss)

	state.m.RLock()
	rs := state.c.ResendSignal
	state.m.RUnlock()

	go func(t TracerSig) {
		for s := range c {
			t.Logf(LogDebug, "Received %v; executing tracer\n", s)

			Trace(t, &signalError{s}, nil)

			if !rs {
				continue
			}

			t.Logf(LogDebug, "Resending %v to default handler\n", s)

			// Re-handle the signal with the default Go behavior.
			signal.Reset(s)
			p, err := os.FindProcess(os.Getpid())
			if err != nil {
				t.Logf(LogError, "Failed to resend signal: "+
					"cannot find process object")
				return
			}

			p.Signal(s)
		}

		t.Logf(LogDebug, "Signal channel closed; exiting goroutine\n")
	}(t)

	return
}

// Stops the specified TracerSig from handling any signals it was previously
// registered to handle via bcd.Register().
func Unregister(t TracerSig) {
	c := t.Sigchan()
	if c == nil {
		return
	}

	unregisterInternal(t, c)
}

func unregisterInternal(t TracerSig, c chan os.Signal) {
	t.Logf(LogDebug, "Stopping signal channel...\n")
	signal.Stop(c)

	t.Logf(LogDebug, "Closing signal channel...\n")
	close(c)

	t.SetSigchan(nil)
	t.Logf(LogDebug, "Tracer unregistered\n")
}

type tracerResult struct {
	stdOut []byte
	err    error
}

// Executes the specified Tracer on the current process.
//
// If e is non-nil, it will be used to augment the trace according to the
// TraceOptions.
// If traceOptions is non-nil, it will be used instead of the Tracer's
// DefaultTraceOptions(). See TraceOptions for details on the various options.
//
// This is goroutine-safe; multiple goroutines may share the same Tracer and
// execute Trace() concurrently. Only one tracer will be allowed to run at
// any point; others will wait to acquire resources (locks) or timeout (if
// timeouts are not disabled). Trace execution will be rate-limited according
// to the GlobalConfig settings.
//
// This may also be called in a new goroutine via go Trace(...). In that case,
// ensure TraceOptions.CallerOnly is false (you will likely also want to set
// TraceOptions.Faulted to false); otherwise, only the newly spawned goroutine
// will be traced.
//
// Output of specific Tracer execution depends on the implementation; most
// Tracers will have options for specifying output paths.
func Trace(t Tracer, e error, traceOptions *TraceOptions) (err error) {
	if traceOptions == nil {
		traceOptions = t.DefaultTraceOptions()
	}

	// If no timeouts are specified, the timeout channel will block
	// forever (i.e. it will return only after the tracer exits).
	// We create the timer first to account for the work below, but
	// we won't wrap setup in a timeout as it's unlikely to be
	// a bottleneck.
	var timeout <-chan time.Time

	if traceOptions.Timeout == 0 {
		to := t.DefaultTraceOptions().Timeout
		timeout = time.After(to)
		t.Logf(LogDebug, "Tracer timeout: %v\n", to)
	} else if traceOptions.Timeout > 0 {
		timeout = time.After(traceOptions.Timeout)
		t.Logf(LogDebug, "Tracer timeout: %v\n", traceOptions.Timeout)
	}

	// We create a new options slice to avoid modifying the base
	// set of tracer options just for this particular trace
	// invocation.
	options := t.Options()

	// If the caller has requested a trace with thread-specific options,
	// then add the relevant thread specifications to the options list.
	if traceOptions.CallerOnly || traceOptions.Faulted {
		runtime.LockOSThread()
		defer runtime.UnlockOSThread()

		if tid, err := gettid(); err == nil {
			t.Logf(LogDebug, "Retrieved tid: %v\n", tid)

			if traceOptions.CallerOnly {
				options = t.AddThreadFilter(options, tid)
			}

			if traceOptions.Faulted {
				options = t.AddFaultedThread(options, tid)
			}
		} else {
			t.Logf(LogWarning, "Failed to retrieve tid: %v\n", err)
		}
	}

	// Report caller's goid
	var buf [64]byte
	n := runtime.Stack(buf[:], false)
	idField := strings.Fields(strings.TrimPrefix(string(buf[:n]), "goroutine "))[0]
	if goid, err := strconv.Atoi(idField); err == nil {
		t.Logf(LogDebug, "Retrieved goid: %v\n", goid)
		options = t.AddCallerGo(options, goid)
	} else {
		t.Logf(LogWarning, "Failed to retrieve goid: %v\n", err)
	}

	if e != nil {
		options = t.AddKV(options, "error", e.Error())
		if traceOptions.ErrClassification {
			options = t.AddClassifier(options,
				reflect.TypeOf(e).String())
		}
	}

	for _, c := range traceOptions.Classifications {
		options = t.AddClassifier(options, c)
	}

	state.m.RLock()
	kfPanic := state.c.PanicOnKillFailure
	rl := state.c.RateLimit
	synchronousPut := state.c.SynchronousPut
	state.m.RUnlock()

	select {
	case <-timeout:
		err = errors.New("Tracer lock acquisition timed out")
		t.Logf(LogError, "%v\n", err)

		return
	case <-traceLock:
		break
	}

	// We now hold the trace lock.
	// Allow another tracer to execute (i.e. by re-populating the
	// traceLock channel) as long as the current tracer has
	// exited.
	defer func() {
		go traceUnlockRL(t, rl)
	}()

	done := make(chan tracerResult, 1)
	tracer := t.Finalize(options)

	if traceOptions.SpawnedGs != nil {
		traceOptions.SpawnedGs.Add(1)
	}

	go func() {
		if traceOptions.SpawnedGs != nil {
			defer traceOptions.SpawnedGs.Done()
		}

		t.Logf(LogDebug, "Starting tracer %v\n", tracer)

		var res tracerResult

		res.stdOut, res.err = tracer.Output()
		done <- res

		t.Logf(LogDebug, "Tracer finished execution\n")
	}()

	t.Logf(LogDebug, "Waiting for tracer completion...\n")

	var res tracerResult

	select {
	case <-timeout:
		if err = tracer.Process.Kill(); err != nil {
			t.Logf(LogError,
				"Failed to kill tracer upon timeout: %v\n",
				err)

			if kfPanic {
				t.Logf(LogWarning,
					"PanicOnKillFailure set; "+
						"panicking\n")
				panic(err)
			}
		}

		err = errors.New("Tracer execution timed out")
		t.Logf(LogError, "%v; process killed\n", err)

		return
	case res = <-done:
		break
	}

	// Tracer execution has completed by this point.
	if res.err != nil {
		t.Logf(LogError, "Tracer failed to run: %v\n",
			res.err)
		err = res.err

		return
	}

	if t.PutOnTrace() == false {
		t.Logf(LogDebug, "Trace request complete\n")

		return
	}

	putFn := func() error {
		t.Logf(LogDebug, "Uploading snapshot...")

		if err := t.Put(res.stdOut); err != nil {
			t.Logf(LogError, "Failed to upload snapshot: %s",
				err)

			return err
		}

		t.Logf(LogDebug, "Successfully uploaded snapshot\n")

		return nil
	}

	if synchronousPut {
		err = putFn()
	} else {
		t.Logf(LogDebug, "Starting asynchronous put...\n")

		if traceOptions.SpawnedGs != nil {
			traceOptions.SpawnedGs.Add(1)
		}

		go func() {
			if traceOptions.SpawnedGs != nil {
				defer traceOptions.SpawnedGs.Done()
			}

			putFn()
		}()
	}

	t.Logf(LogDebug, "Trace request complete\n")

	return
}

func traceUnlockRL(t Tracer, rl time.Duration) {
	t.Logf(LogDebug, "Waiting for ratelimit (%v)\n", rl)
	<-time.After(rl)
	t.Logf(LogDebug, "Unlocking traceLock\n")
	traceLock <- struct{}{}
}

// Create a unique error type to use during panic recovery.
type panicError struct {
	v interface{}
}

func (p *panicError) Error() string {
	return fmt.Sprintf("%v", p.v)
}

// Establishes a panic handler that will execute the specified Tracer in
// response. If repanic is true, this will repanic again after Tracer execution
// completes (with the original value returned by recover()).
// This must be used with Go's defer, panic, and recover pattern; see
// https://blog.golang.org/defer-panic-and-recover.
func Recover(t Tracer, repanic bool, options *TraceOptions) {
	if r := recover(); r != nil {
		err, ok := r.(error)
		if !ok {
			// We use the runtime type of the error object for
			// classification (and thus potential grouping);
			// *bcd.PanicError is a more descriptive classifier
			// than something like *errors.errorString.
			err = &panicError{r}
		}

		Trace(t, err, options)

		if repanic {
			panic(r)
		}
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Anais Soc. Biol. Pernambuco 13(1): 191 (1955)

#### Original name
Microcallis ceibae Bat. & I.H. Lima

### Remarks
null


text:
package reaktor.scct

import org.specs2.mutable._

class EnvSpec extends Specification {
  "Env" should {
    "provide Option[String]'s" in {
      val propName = "scct.test."+System.currentTimeMillis
      try {
        Env.sysOption(propName) mustEqual None
        System.setProperty(propName, "1")
        Env.sysOption(propName) mustEqual Some("1")
      } finally {
        System.clearProperty(propName)
      }
    }
    "read from prop file" in {
      val env = new Env {
        override val props = Env.envProps("/scct-example.properties")
      }
      env.projectId mustEqual "Foobar"
      env.reportHook mustEqual "shutdown"
    }
  }
}


text:
http://stackoverflow.com/questions/897366/how-do-pointer-to-pointers-work-in-c

https://github.com/stephan202

http://stackoverflow.com/users/3153/brian-r-bondy

http://grisha.org/blog/2013/04/02/linus-on-understanding-pointers/

https://github.com/grisha


text:
<?php

namespace Home\Controller;
use Think\Controller;
use Vendor\Page;
class VocationlistmainController extends ComController {
    public function index(){

		//判断当前语言
		$language = L('language');
		$this->assign('language',$language);

		$id = $_REQUEST['id'];

		//行业介绍
		$industry = M('industry');
		$iycontent['id'] = $id;
		$iyjieshao ="id,".$language."nameiy as nameiy,".$language."iycontent as iycontent,".$language."iylogo as iylogo,"
		.$language."logoshow as logoshow,".$language."anli1 as anli1,".$language."anli2 as anli2,"
		.$language."anli3 as anli3,"
		.$language."anli1show as anli1show,".$language."anli2show as anli2show,".$language."anli3show as anli3show,".$language."linksiy as linksiy,"
		.$language."logoshow,".$language."anliname1 as anliname1,".$language."anliname2 as anliname2,".$language."anliname3 as anliname3";
		$iyjieshaos = $industry->where($iycontent)->field($iyjieshao)->find();
		$this->assign('iyjieshaos',$iyjieshaos);

		//行业轮播图
		$industryimgs = M('industryimgs');
		$iywhereimgs['iyid'] = $id;
		$iyimgs ="id,".$language."iyimgs as iyimgs";
		/* print_r($iyimgs);exit; */
		$iyimgss = $industryimgs->where($iywhereimgs)->order('iyimgssort')->field($iyimgs)->select();
		//print_r($industryimgs);exit;
		$this->assign('iyimgss',$iyimgss);
		//print_r($iyimgss);exit;
		//print_r($iyjieshaos);exit;
		$this -> display();
    }

}


text:
package org.spongepowered.api.status;

import org.spongepowered.api.GameRegistry;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
import java.net.URL;

/**
 * Represents an icon for the server sent in the {@link StatusResponse}. It can
 * be loaded by calling one of the {@code loadFavicon} methods on {@link GameRegistry}
 * .
 *
 * @see GameRegistry#loadFavicon(String)
 * @see GameRegistry#loadFavicon(File)
 * @see GameRegistry#loadFavicon(URL)
 * @see GameRegistry#loadFavicon(InputStream)
 */
public interface Favicon {

    /**
     * Gets the decoded image of this favicon.
     *
     * @return The decoded image
     */
    BufferedImage getImage();

    /**
     * Checks if this is a flowerpot.
     *
     * @return Whether this is a flowerpot
     */
    boolean isFlowerPot();
}


text:
@interface GYEssenceController()<UIScrollViewDelegate>

@property(nonatomic,strong)UIView *titleView;

@property(nonatomic,strong)UIButton *selectedButton;

@property(nonatomic,strong)UIView *underline;

@property(nonatomic,strong)UIScrollView *scrollView;

@end

@implementation GYEssenceController

-(void)viewDidLoad{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];

    [self setupChildVC];

    [self setupNaviItem];

    [self setupScrollView];

    [self setupTitleView];
    //加载第一个view
    NSInteger index = 0;
    CGFloat width = self.scrollView.gy_width;
    CGFloat height = self.scrollView.gy_height;
    UIView *childView = self.childViewControllers[index].view;
    childView.frame = CGRectMake(index * width, 0, width, height);
    [self.scrollView addSubview:childView];

}

-(void)setupChildVC{
    GYAllViewController *all =  [[GYAllViewController alloc]init];
    // all.type = TopicTypeAll;
    [self addChildViewController:all];

    GYVideoViewController *video =  [[GYVideoViewController alloc]init];
  //  video.type = TopicTypeVideo;
    [self addChildViewController:video];

    GYVoiceViewController *voice =  [[GYVoiceViewController alloc]init];
   // voice.type = TopicTypeVoice;
    [self addChildViewController:voice];

    GYPictureViewController * picture = [[GYPictureViewController alloc]init];
    //picture.type = TopicTypePicture;
    [self addChildViewController:picture];

    GYWordViewController *word =  [[GYWordViewController alloc]init];
   // word.type = TopicTypeWord;
    [self addChildViewController:word];

}

- (void)setupTitleView{
    UIView *titleView = [[UIView alloc]init];
    [self.view addSubview:titleView];
    titleView.frame = CGRectMake(0, 64, ScreenWidth, 44);
    titleView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.5];
    self.titleView = titleView;

    [self setupButtons];
    [self setupUnderLine];

}

-(void)setupUnderLine{
    UIButton *firstButton = self.titleView.subviews.firstObject;
    //默认点击第一个titlebutton

    self.selectedButton = firstButton;

    UIView *underline = [[UIView alloc]init];
    self.underline = underline;
    underline.gy_height = 2;
    underline.gy_y = self.titleView.gy_height - underline.gy_height;
    //下划线长度
//    NSMutableDictionary *attr = [NSMutableDictionary dictionary];
//    attr[NSFontAttributeName] = firstButton.titleLabel.font;
//    self.underline.gy_width = [[firstButton currentTitle] sizeWithAttributes:attr].width;
    //下划线长度第二中计算方法
//    self.underline.gy_width = firstButton.titleLabel.gy_width;
//
//    self.underline.gy_centerX = firstButton.gy_centerX;

    [self.titleView addSubview:underline];
    underline .backgroundColor = [firstButton titleColorForState:UIControlStateSelected];

    //不写这一句 出不来下划线
    [firstButton.titleLabel sizeToFit];
    [self buttonClick:firstButton];
}

-(void)setupButtons{
    NSInteger count = 5;
    CGFloat buttonWidth = ScreenWidth/count;
    NSArray *title = @[@"全部",@"视频",@"声音",@"图片",@"段子"];
    CGFloat buttonHeight = 44;
    for (int i = 0; i < count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.titleView addSubview:button];

        button.frame = CGRectMake(i * buttonWidth, 0, buttonWidth, buttonHeight);
        [button setTitle:title[i] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal ];
        [button setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
        button.tag = i;

        [button  addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];

    }
}

#pragma mark -- cilck title button
-(void)buttonClick:(UIButton *)button{
    if (self.selectedButton == button) {//重复点击title button
        [[NSNotificationCenter defaultCenter]postNotificationName:@"titleButtonSelected" object:nil];
    }
    [self dealWithbuttonClick:button];
  }

- (void)dealWithbuttonClick:(UIButton *)button{
    self.selectedButton.selected = NO;
    button.selected = YES;
    self.selectedButton = button;

    NSInteger index = button.tag;
    CGFloat width = self.scrollView.gy_width;
    CGFloat height = self.scrollView.gy_height;

    [UIView animateWithDuration:0.25 animations:^{
        //underline 的width 和文字宽度一致
        //        NSMutableDictionary *attr = [NSMutableDictionary dictionary];
        //        attr[NSFontAttributeName] = button.titleLabel.font;
        //        self.underline.gy_width = [[button currentTitle] sizeWithAttributes:attr].width;
        self.underline.gy_width = button.titleLabel.gy_width;
        self.underline.gy_centerX = button.gy_centerX;

        //点击按钮 scrollView 滑动到指定的页面
        CGFloat offsetX = ScreenWidth *button.tag;
        self.scrollView.contentOffset = CGPointMake(offsetX, self.scrollView.contentOffset.y);

    } completion:^(BOOL finished) {//懒加载view
        UIView *childView = self.childViewControllers[index].view;
        childView.frame = CGRectMake(index * width, 0, width, height);
        [self.scrollView addSubview:childView];

    }];
    //scroll to top
    for (int i = 0; i < self.childViewControllers.count; i ++) {
        UIViewController *childVC = self.childViewControllers[i];
        if (!childVC.isViewLoaded) continue;
        UIScrollView *scroll = (UIScrollView *)childVC.view;
        if (![scroll isKindOfClass:[UIScrollView class]]) continue;
        scroll.scrollsToTop = (i == index);

    }

}

#pragma mark -- scrollview set up

-(void)setupScrollView{
    UIScrollView *scrollView = [[UIScrollView alloc]init];
    scrollView.frame = self.view.bounds;
    self.scrollView = scrollView;
    scrollView.delegate = self;

    self.automaticallyAdjustsScrollViewInsets = NO;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.showsHorizontalScrollIndicator  = NO;
    scrollView.pagingEnabled = YES;
    scrollView.scrollsToTop = NO;
    [self.view addSubview:scrollView];
//
//    CGFloat width = scrollView.gy_width;
//    CGFloat height = scrollView.gy_height;
//    CGFloat y = 0;
//    for (int i = 0; i < 5; i++) {//子控制器的view加到scrollView上
//        UIView *childView = self.childViewControllers[i].view;
//        childView.frame = CGRectMake(i * width, y, width, height);
//        [scrollView addSubview:childView];
//    }
    scrollView.contentSize = CGSizeMake(5 *scrollView.gy_width, 0);
}

#pragma mark -- scrollView delegate
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSInteger  index = scrollView.contentOffset.x/ScreenWidth;
    UIButton *button = self.titleView.subviews[index];
    //[self buttonClick:button];
    [self dealWithbuttonClick:button];
}

-(void)setupNaviItem{
    //left;
    UIBarButtonItem *left =  [UIBarButtonItem setupBarButtonItemWithImage:[UIImage imageNamed:@"nav_item_game_icon"] withHighlightedImage:[UIImage imageNamed:@"nav_item_game_click_icon"] withTarget:self action:@selector(game)];
    self.navigationItem.leftBarButtonItem =left;
    //right
    UIBarButtonItem *right =[UIBarButtonItem setupBarButtonItemWithImage:[UIImage imageNamed:@"navigationButtonRandom"] withHighlightedImage:[UIImage imageNamed:@"navigationButtonRandomClick"] withTarget:self action:@selector(game)];
    self.navigationItem.rightBarButtonItem = right;
    //title

    self.navigationItem.titleView =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"MainTitle"]];

}

-(void)game{
    function;
}

@end


text:
package com.nec.harvest.service;

import com.nec.harvest.exception.ServiceException;
import com.nec.harvest.model.Message;

/**
 * A service for Message that can be used to created, retrieved, removed
 * ... or something like that for the give Message type object
 *
 * @author sondn
 *
 */
public interface MessageService extends AbstractService {

	/**
	 * Get a message by message's code
	 *
	 * @param msgCode
	 * @return
	 * @throws ServiceException
	 */
	Message findByMsgCode(String msgCode) throws ServiceException;

}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.1" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="default">
  	<class>br.edu.fema.sacheti.model.Usuario</class>
  	<class>br.edu.fema.sacheti.model.Ticket</class>
  	<class>br.edu.fema.sacheti.model.Operador</class>
  	<class>br.edu.fema.sacheti.model.Cliente</class>
  	<class>br.edu.fema.sacheti.model.Interacao</class>
    <properties>
      <property name="javax.persistence.jdbc.user" value="postgres"/>
      <property name="javax.persistence.jdbc.password" value="masterkey"/>
      <property name="hibernate.show_sql" value="true"/>
      <property name="hibernate.format_sql" value="true"/>
      <property name="hibernate.hbm2ddl.auto" value="update"/>
<!--       <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/> -->
      <property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost/sacheti"/>
      <property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
    </properties>
  </persistence-unit>
</persistence>


text:
<?php

use PHPUnit\Framework\TestCase;
use Obullo\PageEvent;
use Obullo\Http\ServerRequest;
use Laminas\Diactoros\Uri;
use Laminas\Diactoros\Response;
use Laminas\View\Model\ViewModel;
use Laminas\Psr7Bridge\Psr7ServerRequest;
use Laminas\ServiceManager\ServiceManager;

class PageEventTest extends TestCase
{
    public function setUp() : void
    {
        $appConfig = require __DIR__ . '/config/application.config.php';
        $smConfig = isset($appConfig['service_manager']) ? $appConfig['service_manager'] : [];
        $smConfig = new Obullo\Container\ServiceManagerConfig($smConfig);

        // setup service manager
        //
        $this->container = new ServiceManager;
        $smConfig->configureServiceManager($this->container);
        $this->container->setService('appConfig', $appConfig);

        // load app modules
        //
        $this->container->get('ModuleManager')->loadModules();
        $this->container->setAllowOverride(true);
    }

    public function testGetApplication()
    {
        $event = new PageEvent;
        $event->setApplication($this->container->get('Application'));

        $this->assertInstanceOf('Obullo\Application', $event->getApplication());
    }

    public function testGetRouter()
    {
        $event = new PageEvent;
        $event->setRouter($this->container->get('Router'));

        $this->assertInstanceOf('Laminas\Router\RouteStackInterface', $event->getRouter());
    }

    public function testGetRouteMatch()
    {
        $request = new ServerRequest(
            $serverParams = [],
            $uploadedFiles = [],
            new Uri('http://example.com/test'),
            'GET',
            $body = 'php://input',
            $headers = [],
            $cookies = [],
            $queryParams = [],
            $parsedBody = [],
            $protocol = '1.1'
        );
        $router = $this->container->get('Router');
        $routeMatch = $router->match(Psr7ServerRequest::toLaminas($request, true));
        $event = new PageEvent;
        $event->setRouteMatch($routeMatch);

        $this->assertInstanceOf('Laminas\Router\RouteMatch', $event->getRouteMatch());
    }

    public function testGetController()
    {
        $event = new PageEvent;
        $event->setController('App\Pages\TestModel');

        $this->assertEquals('App\Pages\TestModel', $event->getController());
    }

    public function testGetResolvedModuleName()
    {
        $event = new PageEvent;
        $event->setController('Test\Pages\TestModel');
        $event->setResolvedModuleName();

        $this->assertEquals('Test', $event->getResolvedModuleName());
    }

    public function testGetRequest()
    {
        $event = new PageEvent;
        $event->setRequest($this->container->get('Request'));

        $this->assertInstanceOf('Psr\Http\Message\ServerRequestInterface', $event->getRequest());
    }

    public function testGetResponse()
    {
        $event = new PageEvent;
        $event->setResponse(new Response);

        $this->assertInstanceOf('Psr\Http\Message\ResponseInterface', $event->getResponse());
    }

    public function testGetPageModel()
    {
        $event = new PageEvent;
        $event->setPageModel('Test\Handler', new StdClass);

        $this->assertInstanceOf('stdClass', $event->getPageModel('Test\Handler'));
    }
}


text:
<?php

defined("_VALID_ACCESS") || die('Direct access forbidden');

class Base_EssClientInstall extends ModuleInstall {

    public function install() {
		Base_ThemeCommon::install_default_theme($this->get_type());
        return true;
    }

    public function uninstall() {
		Base_ThemeCommon::uninstall_default_theme($this->get_type());
        return true;
    }

    public function version() {
        return array("1.0");
    }

    public function requires($v) {
        return array(
            array('name' => Base_AdminInstall::module_name(), 'version' => 0),
            array('name' => Base_LangInstall::module_name(), 'version' => 0),
			array('name' => Base_MenuInstall::module_name(), 'version' => 0),
  			array('name' => Utils_FrontPageInstall::module_name(),'version' => 0),
            array('name' => Libs_QuickFormInstall::module_name(), 'version' => 0));
    }

    public static function info() {
        return array(
            'Description' => 'Perform requests to Epesi Services Servers. Allows installation registration.',
            'Author' => 'abukowski@telaxus.com',
            'License' => 'MIT');
    }

    public static function simple_setup() {
		return __('EPESI Core');
    }

}

?>


text:
package org.platanios.tensorflow.api.learn.hooks

import org.platanios.tensorflow.api.core.client.{Executable, Fetchable}
import org.platanios.tensorflow.api.ops.{Op, Output}
import org.platanios.tensorflow.api.tensors.Tensor

import com.typesafe.scalalogging.Logger
import org.slf4j.LoggerFactory

/** Monitors the provided tensors and stops training if, at any point, any of them contains any `NaN` values.
  *
  * This hook can either fail with an exception or just stop training.
  *
  * @param  tensorNames Names of the tensors to monitor.
  * @param  failOnNaN   If `true`, an exception is thrown when `NaN` values are encountered. Otherwise, training stops.
  *
  * @author Emmanouil Antonios Platanios
  */
class NaNChecker protected (
    val tensorNames: Set[String],
    val failOnNaN: Boolean = true
) extends Hook {
  private[this] var outputs: Seq[Output] = _

  override protected def begin(): Unit = {
    // Convert tensor names to op outputs.
    outputs = tensorNames.map(Op.currentGraph.getOutputByName).toSeq
  }

  override protected def beforeSessionRun[F, E, R](runContext: Hook.SessionRunContext[F, E, R])(implicit
      executableEv: Executable[E],
      fetchableEv: Fetchable.Aux[F, R]
  ): Option[Hook.SessionRunArgs[Seq[Output], Traversable[Op], Seq[Tensor]]] = {
    Some(Hook.SessionRunArgs(fetches = outputs))
  }

  @throws[IllegalStateException]
  override protected def afterSessionRun[F, E, R](
      runContext: Hook.SessionRunContext[F, E, R],
      runResult: Hook.SessionRunResult[Seq[Output], Seq[Tensor]]
  )(implicit
      executableEv: Executable[E],
      fetchableEv: Fetchable.Aux[F, R]
  ): Unit = {
    runResult.values.filter(_.isNaN.any().scalar.asInstanceOf[Boolean]).foreach(value => {
      val message = s"Encountered NaN values in tensor: $value."
      if (failOnNaN) {
        NaNChecker.logger.error(message)
        throw new IllegalStateException(message)
      } else {
        NaNChecker.logger.warn(message)
        // We do not raise an error but we request to stop iterating without throwing an exception.
        runContext.requestStop()
      }
    })
  }
}

object NaNChecker {
  private[NaNChecker] val logger = Logger(LoggerFactory.getLogger("Learn / Hooks / Tensor NaN"))

  def apply(tensorNames: Set[String], failOnNaN: Boolean = true): NaNChecker = {
    new NaNChecker(tensorNames, failOnNaN)
  }
}


text:
import * as types from 'src/vuex/types'
import * as accountUtils from 'src/utils/account'

const state = {
  account: accountUtils.getAccount(),
  loggedIn: false
}

const mutations = {
  [types.ACCOUNT_GET_ACCOUNT_SUCCESS] (state, account) {
    accountUtils.setAccount(account)
    state.account = account
    state.loggedIn = true
  },
  [types.ACCOUNT_GET_ACCOUNT_FAIL] (state, err) {
    state.loggedIn = false
    console.log(err)
  }
}

export default {
  state,
  mutations
}