text:
<?php

namespace Oko\MainBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * @ORM\Entity
 * @ORM\Table(name="snipt")
 * @ORM\HasLifecycleCallbacks()
 */

class Snipt
{

    /**
     * @Gedmo\Slug(fields={"title"}, updatable=false, separator="_")
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     * @var integer $id
     */
    protected $id;

    /**
	 * @ORM\Column(type="string", length=255)
     * @var string $title
     * @Assert\NotBlank
     */
    protected $title;

    /**
     * @ORM\Column(type="text")
     * @var string $body
     * @Assert\NotBlank
     */
    protected $body;

	/**
    * @ORM\ManyToOne(targetEntity="UserAdmin", inversedBy="snipts")
    * @ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE")
    */
    protected $user;

/***********************************/

    public function getId(){
        return $this->id;
    }

	public function getUser(){
        return $this->user;
    }

    public function setUser( $value ){
		$this->user = $value;
    }

    public function getSlug(){
        return $this->slug;
    }

    public function setSlug( $value ){
	$this->slug = $value;
    }

    public function getTitle(){
        return $this->title;
    }

    public function setTitle( $value ){
        $this->title = $value;
    }

    public function getBody(){
        return $this->body;
    }

    public function setBody( $value ){
        $this->body = $value;
    }

    public function __construct()
    {

    }
}


text:
/*
 * Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0
 * Changes may cause incorrect behavior and will be lost if the code is
 * regenerated.
 */

'use strict';

const models = require('./index');

/**
 * Describes Storage Resource Usage.
 *
 */
class Usage {
  /**
   * Create a Usage.
   * @member {string} unit Gets the unit of measurement. Possible values
   * include: 'Count', 'Bytes', 'Seconds', 'Percent', 'CountsPerSecond',
   * 'BytesPerSecond'
   * @member {number} currentValue Gets the current count of the allocated
   * resources in the subscription.
   * @member {number} limit Gets the maximum count of the resources that can be
   * allocated in the subscription.
   * @member {object} name Gets the name of the type of usage.
   * @member {string} [name.value] Gets a string describing the resource name.
   * @member {string} [name.localizedValue] Gets a localized string describing
   * the resource name.
   */
  constructor() {
  }

  /**
   * Defines the metadata of Usage
   *
   * @returns {object} metadata of Usage
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'Usage',
      type: {
        name: 'Composite',
        className: 'Usage',
        modelProperties: {
          unit: {
            required: true,
            serializedName: 'unit',
            type: {
              name: 'Enum',
              allowedValues: [ 'Count', 'Bytes', 'Seconds', 'Percent', 'CountsPerSecond', 'BytesPerSecond' ]
            }
          },
          currentValue: {
            required: true,
            serializedName: 'currentValue',
            type: {
              name: 'Number'
            }
          },
          limit: {
            required: true,
            serializedName: 'limit',
            type: {
              name: 'Number'
            }
          },
          name: {
            required: true,
            serializedName: 'name',
            type: {
              name: 'Composite',
              className: 'UsageName'
            }
          }
        }
      }
    };
  }
}

module.exports = Usage;

redpajama_set_name: RedPajamaGithub


text:
setlocal

call C:\development\java\local\settings.bat

call %MAVEN_HOME%\bin\mvn clean

endlocal


text:
//
//  TKCalendarMonthView.h
//  Created by Devin Ross on 6/10/10.
//

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@class TKCalendarMonthTiles;
@protocol TKCalendarMonthViewDelegate, TKCalendarMonthViewDataSource;

/** `TKCalendarMonthView` imitates the month grid in the Calendar app on iPhone. */
@interface TKCalendarMonthView : UIView {

	TKCalendarMonthTiles *currentTile,*oldTile;
	//UIButton *leftArrow, *rightArrow;
	//UIImageView *topBackground, *shadow;
	//UILabel *monthYear;
	BOOL sunday;

}

/** Initialize a Calendar Month Grid.
 @param sunday Flag to setup the grid with Monday or Sunday as the leftmost day.
 @return A `TKCalendarMonthView` object or nil.
 */
- (id) initWithSundayAsFirst:(BOOL)sunday; // or Monday

/** The delegate must adopt the `TKCalendarMonthViewDelegate` protocol. The delegate is not retained. */
@property (nonatomic,assign) id <TKCalendarMonthViewDelegate> delegate;

/** The data soruce must adopt the `TKCalendarMonthViewDataSource` protocol. The data source is not retained. */
@property (nonatomic,assign) id <TKCalendarMonthViewDataSource> dataSource;

/** The current date highlighted on the month grid.
 @return An `NSDate` object set to the month, year and day of the current selection.
 */
- (NSDate*) dateSelected;

/** The current month date being displayed.
 @return An `NSDate` object set to the month and year of the current month grid.
 */
- (NSDate*) monthDate;

/** Selects a specific date in the month grid.
 @param date The date that will be highlighed.
 */
- (void) selectDate:(NSDate*)date;

/** Reloads the current month grid. */
- (void) reload;

@end

/** The delegate of a `TKCalendarMonthView` object must adopt the `TKCalendarMonthViewDelegate` protocol. */
@protocol TKCalendarMonthViewDelegate <NSObject>
@optional

/** The highlighed date changed.
 @param monthView The calendar month view.
 @param date The highlighted date.
 */
- (void) calendarMonthView:(TKCalendarMonthView*)monthView didSelectDate:(NSDate*)date;

/** The calendar should change the current month to grid shown.
 @param monthView The calendar month view.
 @param month The month date.
 @param animated Animation flag
 @return YES if the month should change. NO otherwise
 */
- (BOOL) calendarMonthView:(TKCalendarMonthView*)monthView monthShouldChange:(NSDate*)month animated:(BOOL)animated;

/** The calendar will change the current month to grid shown.
 @param monthView The calendar month view.
 @param month The month date.
 @param animated Animation flag
 */
- (void) calendarMonthView:(TKCalendarMonthView*)monthView monthWillChange:(NSDate*)month animated:(BOOL)animated;

/** The calendar did change the current month to grid shown.
 @param monthView The calendar month view.
 @param month The month date.
 @param animated Animation flag
 */
- (void) calendarMonthView:(TKCalendarMonthView*)monthView monthDidChange:(NSDate*)month animated:(BOOL)animated;
@end

/** The data source of a `TKCalendarMonthView` object must adopt the `TKCalendarMonthViewDataSource` protocol. */
@protocol TKCalendarMonthViewDataSource <NSObject>

/** A data source that will correspond to marks for the calendar month grid for a particular month.

 @param monthView The calendar month grid.
 @param startDate The first date shown by the calendar month grid.
 @param lastDate The last date shown by the calendar month grid.
 @return Returns an array of NSNumber objects corresponding the number of days specified in the start and last day parameters. Each NSNumber variable will give a BOOL value that will be used to display a dot under the day.

 */
- (NSArray*) calendarMonthView:(TKCalendarMonthView*)monthView marksFromDate:(NSDate*)startDate toDate:(NSDate*)lastDate;

@end


text:
//
//  HLM3U8Info.h
//  HLHLS
//
//  Created by hl on 16/10/2017.
//  Copyright © 2017 HL. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "HLM3U8SegmentBase.h"

/*!
 * @class           HLM3U8Playlist
 *
 * @abstract        playlist主文件
 *
 * @discussion      之所以从segmetbase继承,是由于playlist可能嵌套,分为多个不同分辨率的playlist
 *                  直播的需要不断刷新更新ts地址--暂时不考虑处理
 *                  只处理以及获取的
 *                  ?? 什么时候去解析sub playlist
 *
 */

//由于Variant playlist,的sub playlist需要单独的解析,这里需要成功用库

typedef void(^HLM3U8SegmentsCallback)(HLM3U8Segment * arr);
@interface HLM3U8Playlist : HLM3U8SegmentBase

@property (nonatomic, strong) NSString * uniqueID;
@property (nonatomic, strong) NSString * version;
@property (nonatomic) BOOL isDecode;      //VariablesPlist分了分辨率了subplaylist,并不是以获取就全部解析,造成没必要浪费,lazyload

- (BOOL) isVariantPlaylist;
- (void)addSegment:(HLM3U8SegmentBase*)segment;

- (NSArray *)segmentsListWithResolution:(id)resolution;
- (NSArray *)urlStringForResolution:(id)resolution;
- (HLM3U8Program*)programWithResolution:(id)resolution;

- (NSString *)uri;
@end


text:
title: "Consider using a fluent API"
weight: 8
---

{{% notice info %}}
 Page being translated from
English to Dutch. Do you speak Dutch? Help us to translate
it by sending us pull requests!
{{% /notice %}}

Martin Fowler coined the term ["Fluent API"](//www.martinfowler.com/bliki/FluentInterface.html).
Selenium already implements something like this in their `FluentWait` class which is
meant as an alternative to the standard Wait class.
You could enable the Fluent API design pattern in your page object
and then query the Google search page with a code snippet like this one:

```java
driver.get( "http://www.google.com/webhp?hl=en&tab=ww" );
GoogleSearchPage gsp = new GoogleSearchPage();
gsp.withFluent().setSearchString().clickSearchButton();
```

The Google page object class with this fluent behavior
might look like this:

```java
public class GoogleSearchPage extends LoadableComponent<GoogleSearchPage> {
  private final WebDriver driver;
  private GSPFluentInterface gspfi;

  public class GSPFluentInterface {
    private GoogleSearchPage gsp;

    public GSPFluentInterface(GoogleSearchPage googleSearchPage) {
        gsp = googleSearchPage;
    }

    public GSPFluentInterface clickSearchButton() {
        gsp.searchButton.click();
        return this;
    }

    public GSPFluentInterface setSearchString( String sstr ) {
        clearAndType( gsp.searchField, sstr );
        return this;
    }
  }

  @FindBy(id = "gbqfq") private WebElement searchField;
  @FindBy(id = "gbqfb") private WebElement searchButton;
  public GoogleSearchPage(WebDriver driver) {
    gspfi = new GSPFluentInterface( this );
    this.get(); // If load() fails, calls isLoaded() until page is finished loading
    PageFactory.initElements(driver, this); // Initialize WebElements on page
  }

  public GSPFluentInterface withFluent() {
    return gspfi;
  }

  public void clickSearchButton() {
    searchButton.click();
  }

  public void setSearchString( String sstr ) {
    clearAndType( searchField, sstr );
  }

  @Override
  protected void isLoaded() throws Error {
    Assert.assertTrue("Google search page is not yet loaded.", isSearchFieldVisible() );
  }

  @Override
  protected void load() {
    if ( isSFieldPresent ) {
      Wait<WebDriver> wait = new WebDriverWait( driver, 3 );
      wait.until( visibilityOfElementLocated( By.id("gbqfq") ) ).click();
    }
  }
}
```


text:
package com.dtflys.forest.logging;

/**
 * 请求日志配置信息
 *
 * @author gongjun[dt_flys@hotmail.com]
 * @since 1.5.0-BETA5
 */
public class LogConfiguration {

    /**
     * 是否允许打印请求/响应日志
     */
    private boolean logEnabled;

    /**
     * 是否允许打印请求日志
     */
    private boolean logRequest;

    /**
     * 是否允许打印响应状态日志
     */
    private boolean logResponseStatus;

    /**
     * 是否允许打印响应内容日志
     */
    private boolean logResponseContent;

    /**
     * 日志处理器
     */
    private ForestLogHandler logHandler;

    /**
     * 是否允许打印请求/响应日志
     * @return 允许为 {@code true}, 否则为 {@code false}
     */
    public boolean isLogEnabled() {
        return logEnabled;
    }

    public void setLogEnabled(boolean logEnabled) {
        this.logEnabled = logEnabled;
    }

    /**
     * 是否允许打印请求日志
     * @return 允许为 {@code true}, 否则为 {@code false}
     */
    public boolean isLogRequest() {
        return logRequest;
    }

    public void setLogRequest(boolean logRequest) {
        this.logRequest = logRequest;
    }

    /**
     * 是否允许打印响应日志
     * @return 允许为 {@code true}, 否则为 {@code false}
     */
    public boolean isLogResponseStatus() {
        return logResponseStatus;
    }

    public void setLogResponseStatus(boolean logResponseStatus) {
        this.logResponseStatus = logResponseStatus;
    }

    /**
     * 是否允许打印响应日志
     * @return 允许为 {@code true}, 否则为 {@code false}
     */
    public boolean isLogResponseContent() {
        return logResponseContent;
    }

    public void setLogResponseContent(boolean logResponseContent) {
        this.logResponseContent = logResponseContent;
    }

    /**
     * 获取日志处理器
     * @return 日志处理器接口实例
     */
    public ForestLogHandler getLogHandler() {
        return logHandler;
    }

    public void setLogHandler(ForestLogHandler logHandler) {
        this.logHandler = logHandler;
    }
}


text:
using testing::_;
using testing::ContainerEq;
using testing::Eq;
using testing::Return;

namespace offline_items_collection {
namespace {

using GetVisualsOptions = OfflineContentProvider::GetVisualsOptions;

struct CompareOfflineItemsById {
  bool operator()(const OfflineItem& a, const OfflineItem& b) const {
    return a.id < b.id;
  }
};

// A custom comparator that makes sure two vectors contain the same elements.
// TODO(dtrainor): Look into building a better matcher that works with gmock.
template <typename T>
bool VectorContentsEq(const std::vector<T>& list1,
                      const std::vector<T>& list2) {
  if (list1.size() != list2.size())
    return false;

  std::map<T, int, CompareOfflineItemsById> occurance_counts;
  for (auto it = list1.begin(); it != list1.end(); it++)
    occurance_counts[*it]++;

  for (auto it = list2.begin(); it != list2.end(); it++)
    occurance_counts[*it]--;

  for (auto it = occurance_counts.begin(); it != occurance_counts.end(); it++) {
    if (it->second != 0)
      return false;
  }

  return true;
}

MATCHER_P(OpenParamsEqual, params, "") {
  return arg.launch_location == params.launch_location;
}

// Helper class that automatically unregisters itself from the aggregator in the
// case that someone calls OpenItem on it.
class OpenItemRemovalOfflineContentProvider
    : public ScopedMockOfflineContentProvider {
 public:
  OpenItemRemovalOfflineContentProvider(const std::string& name_space,
                                        OfflineContentAggregator* aggregator)
      : ScopedMockOfflineContentProvider(name_space, aggregator) {}
  ~OpenItemRemovalOfflineContentProvider() override {}

  void OpenItem(const OpenParams& open_params, const ContentId& id) override {
    ScopedMockOfflineContentProvider::OpenItem(open_params, id);
    Unregister();
  }
};

// A helper class that delays GetAllItems() callback until RunCallback()
// is called.
class DelayedGetAllItemOfflineContentProvider
    : public ScopedMockOfflineContentProvider {
 public:
  DelayedGetAllItemOfflineContentProvider(const std::string& name_space,
                                          OfflineContentAggregator* aggregator)
      : ScopedMockOfflineContentProvider(name_space, aggregator) {}
  ~DelayedGetAllItemOfflineContentProvider() override = default;

  void GetAllItems(MultipleItemCallback callback) override {
    callback_ = std::move(callback);
  }

  void RunCallback(const OfflineItemList& items) {
    std::move(callback_).Run(items);
  }

 private:
  MultipleItemCallback callback_;
};

class OfflineContentAggregatorTest : public testing::Test {
 public:
  OfflineContentAggregatorTest()
      : task_runner_(new base::TestMockTimeTaskRunner), handle_(task_runner_) {}
  ~OfflineContentAggregatorTest() override {}

 protected:
  MOCK_METHOD1(OnGetAllItemsDone,
               void(const OfflineContentProvider::OfflineItemList&));
  MOCK_METHOD1(OnGetItemByIdDone, void(const absl::optional<OfflineItem>&));

  void GetAllItemsAndVerify(
      OfflineContentProvider* provider,
      const OfflineContentProvider::OfflineItemList& expected);
  void GetSingleItemAndVerify(OfflineContentProvider* provider,
                              const ContentId& id,
                              const absl::optional<OfflineItem>& expected);

  scoped_refptr<base::TestMockTimeTaskRunner> task_runner_;
  base::ThreadTaskRunnerHandle handle_;
  OfflineContentAggregator aggregator_;
  base::WeakPtrFactory<OfflineContentAggregatorTest> weak_ptr_factory_{this};
};

void OfflineContentAggregatorTest::GetAllItemsAndVerify(
    OfflineContentProvider* provider,
    const OfflineContentProvider::OfflineItemList& expected) {
  EXPECT_CALL(*this, OnGetAllItemsDone(expected)).Times(1);
  provider->GetAllItems(
      base::BindOnce(&OfflineContentAggregatorTest::OnGetAllItemsDone,
                     weak_ptr_factory_.GetWeakPtr()));
  task_runner_->RunUntilIdle();
}

void OfflineContentAggregatorTest::GetSingleItemAndVerify(
    OfflineContentProvider* provider,
    const ContentId& id,
    const absl::optional<OfflineItem>& expected) {
  EXPECT_CALL(*this, OnGetItemByIdDone(expected)).Times(1);
  provider->GetItemById(
      id, base::BindOnce(&OfflineContentAggregatorTest::OnGetItemByIdDone,
                         weak_ptr_factory_.GetWeakPtr()));
  task_runner_->RunUntilIdle();
}

TEST_F(OfflineContentAggregatorTest, QueryingItemsWith2Providers) {
  ScopedMockOfflineContentProvider provider1("1", &aggregator_);
  ScopedMockOfflineContentProvider provider2("2", &aggregator_);

  OfflineContentProvider::OfflineItemList items1;
  items1.push_back(OfflineItem(ContentId("1", "A")));
  items1.push_back(OfflineItem(ContentId("1", "B")));

  OfflineContentProvider::OfflineItemList items2;
  items2.push_back(OfflineItem(ContentId("2", "C")));
  items2.push_back(OfflineItem(ContentId("2", "D")));

  provider1.SetItems(items1);
  provider2.SetItems(items2);

  GetAllItemsAndVerify(&provider1, items1);
  GetAllItemsAndVerify(&provider2, items2);
  OfflineContentProvider::OfflineItemList combined_items(items1);
  combined_items.insert(combined_items.end(), items2.begin(), items2.end());
  GetAllItemsAndVerify(&aggregator_, combined_items);
}

TEST_F(OfflineContentAggregatorTest, QueryingItemFromRemovedProvider) {
  ContentId id("1", "A");
  OfflineItem item(id);

  {
    ScopedMockOfflineContentProvider provider("1", &aggregator_);
    provider.SetItems({item});
    GetSingleItemAndVerify(&aggregator_, id, item);
  }

  GetSingleItemAndVerify(&aggregator_, id, absl::nullopt);
}

TEST_F(OfflineContentAggregatorTest, GetItemByIdPropagatesToRightProvider) {
  ScopedMockOfflineContentProvider provider1("1", &aggregator_);
  ScopedMockOfflineContentProvider provider2("2", &aggregator_);

  ContentId id1("1", "A");
  ContentId id2("2", "B");
  ContentId id3("1", "C");
  ContentId id4("3", "D");
  OfflineItem item1(id1);
  OfflineItem item2(id2);

  provider1.SetItems({item1});
  provider2.SetItems({item2});
  GetSingleItemAndVerify(&aggregator_, id1, item1);
  GetSingleItemAndVerify(&aggregator_, id2, item2);
  GetSingleItemAndVerify(&aggregator_, id3, absl::nullopt);
  GetSingleItemAndVerify(&aggregator_, id4, absl::nullopt);
}

TEST_F(OfflineContentAggregatorTest, ActionPropagatesToRightProvider) {
  ScopedMockOfflineContentProvider provider1("1", &aggregator_);
  ScopedMockOfflineContentProvider provider2("2", &aggregator_);

  testing::InSequence sequence;
  ContentId id1("1", "A");
  ContentId id2("2", "B");
  EXPECT_CALL(
      provider1,
      OpenItem(OpenParamsEqual(OpenParams(LaunchLocation::DOWNLOAD_HOME)), id1))
      .Times(1);
  EXPECT_CALL(
      provider2,
      OpenItem(OpenParamsEqual(OpenParams(LaunchLocation::NOTIFICATION)), id2))
      .Times(1);
  EXPECT_CALL(provider1, RemoveItem(id1)).Times(1);
  EXPECT_CALL(provider2, RemoveItem(id2)).Times(1);
  EXPECT_CALL(provider1, CancelDownload(id1)).Times(1);
  EXPECT_CALL(provider2, CancelDownload(id2)).Times(1);
  EXPECT_CALL(provider1, ResumeDownload(id1, false)).Times(1);
  EXPECT_CALL(provider2, ResumeDownload(id2, true)).Times(1);
  EXPECT_CALL(provider1, PauseDownload(id1)).Times(1);
  EXPECT_CALL(provider2, PauseDownload(id2)).Times(1);
  EXPECT_CALL(provider1, GetVisualsForItem_(id1, _, _)).Times(1);
  EXPECT_CALL(provider2, GetVisualsForItem_(id2, _, _)).Times(1);
  EXPECT_CALL(provider1, GetShareInfoForItem(id1, _)).Times(1);
  EXPECT_CALL(provider2, GetShareInfoForItem(id2, _)).Times(1);
  aggregator_.OpenItem(OpenParams(LaunchLocation::DOWNLOAD_HOME), id1);
  aggregator_.OpenItem(OpenParams(LaunchLocation::NOTIFICATION), id2);
  aggregator_.RemoveItem(id1);
  aggregator_.RemoveItem(id2);
  aggregator_.CancelDownload(id1);
  aggregator_.CancelDownload(id2);
  aggregator_.ResumeDownload(id1, false);
  aggregator_.ResumeDownload(id2, true);
  aggregator_.PauseDownload(id1);
  aggregator_.PauseDownload(id2);
  aggregator_.GetVisualsForItem(id1, GetVisualsOptions::IconOnly(),
                                OfflineContentProvider::VisualsCallback());
  aggregator_.GetVisualsForItem(id2, GetVisualsOptions::IconOnly(),
                                OfflineContentProvider::VisualsCallback());
  aggregator_.GetShareInfoForItem(id1, OfflineContentProvider::ShareCallback());
  aggregator_.GetShareInfoForItem(id2, OfflineContentProvider::ShareCallback());
}

TEST_F(OfflineContentAggregatorTest, ActionPropagatesImmediately) {
  ScopedMockOfflineContentProvider provider1("1", &aggregator_);
  ScopedMockOfflineContentProvider provider2("2", &aggregator_);

  ContentId id1("1", "A");
  ContentId id2("2", "B");
  ContentId id3("2", "C");

  testing::InSequence sequence;
  EXPECT_CALL(provider1, PauseDownload(id1)).Times(1);
  EXPECT_CALL(provider1, ResumeDownload(id1, true)).Times(1);
  EXPECT_CALL(
      provider1,
      OpenItem(OpenParamsEqual(OpenParams(LaunchLocation::DOWNLOAD_HOME)), id1))
      .Times(1);
  EXPECT_CALL(
      provider2,
      OpenItem(OpenParamsEqual(OpenParams(LaunchLocation::NOTIFICATION)), id2))
      .Times(1);
  EXPECT_CALL(provider2, RemoveItem(id3)).Times(1);

  aggregator_.PauseDownload(id1);
  aggregator_.ResumeDownload(id1, true);
  aggregator_.OpenItem(OpenParams(LaunchLocation::DOWNLOAD_HOME), id1);
  aggregator_.OpenItem(OpenParams(LaunchLocation::NOTIFICATION), id2);
  aggregator_.RemoveItem(id3);
}

TEST_F(OfflineContentAggregatorTest, OnItemsAddedPropagatedToObservers) {
  ScopedMockOfflineContentProvider provider1("1", &aggregator_);
  ScopedMockOfflineContentProvider provider2("2", &aggregator_);

  ScopedMockOfflineContentProvider::ScopedMockObserver observer1(&aggregator_);
  ScopedMockOfflineContentProvider::ScopedMockObserver observer2(&aggregator_);

  task_runner_->RunUntilIdle();

  OfflineContentProvider::OfflineItemList items1;
  items1.push_back(OfflineItem(ContentId("1", "A")));
  items1.push_back(OfflineItem(ContentId("1", "B")));

  OfflineContentProvider::OfflineItemList items2;
  items2.push_back(OfflineItem(ContentId("2", "C")));
  items2.push_back(OfflineItem(ContentId("2", "D")));

  EXPECT_CALL(observer1, OnItemsAdded(items1)).Times(1);
  EXPECT_CALL(observer1, OnItemsAdded(items2)).Times(1);
  EXPECT_CALL(observer2, OnItemsAdded(items1)).Times(1);
  EXPECT_CALL(observer2, OnItemsAdded(items2)).Times(1);
  provider1.NotifyOnItemsAdded(items1);
  provider2.NotifyOnItemsAdded(items2);
}

TEST_F(OfflineContentAggregatorTest, OnItemRemovedPropagatedToObservers) {
  ScopedMockOfflineContentProvider provider1("1", &aggregator_);
  ScopedMockOfflineContentProvider provider2("2", &aggregator_);

  ScopedMockOfflineContentProvider::ScopedMockObserver observer1(&aggregator_);
  ScopedMockOfflineContentProvider::ScopedMockObserver observer2(&aggregator_);

  task_runner_->RunUntilIdle();

  ContentId id1("1", "A");
  ContentId id2("2", "B");

  EXPECT_CALL(observer1, OnItemRemoved(id1)).Times(1);
  EXPECT_CALL(observer1, OnItemRemoved(id2)).Times(1);
  EXPECT_CALL(observer2, OnItemRemoved(id1)).Times(1);
  EXPECT_CALL(observer2, OnItemRemoved(id2)).Times(1);
  provider1.NotifyOnItemRemoved(id1);
  provider2.NotifyOnItemRemoved(id2);
}

TEST_F(OfflineContentAggregatorTest, OnItemUpdatedPropagatedToObservers) {
  ScopedMockOfflineContentProvider provider1("1", &aggregator_);
  ScopedMockOfflineContentProvider provider2("2", &aggregator_);

  ScopedMockOfflineContentProvider::ScopedMockObserver observer1(&aggregator_);
  ScopedMockOfflineContentProvider::ScopedMockObserver observer2(&aggregator_);

  task_runner_->RunUntilIdle();

  OfflineItem item1(ContentId("1", "A"));
  OfflineItem item2(ContentId("2", "B"));

  EXPECT_CALL(observer1, OnItemUpdated(item1, Eq(absl::nullopt))).Times(1);
  EXPECT_CALL(observer1, OnItemUpdated(item2, Eq(absl::nullopt))).Times(1);
  EXPECT_CALL(observer2, OnItemUpdated(item1, Eq(absl::nullopt))).Times(1);
  EXPECT_CALL(observer2, OnItemUpdated(item2, Eq(absl::nullopt))).Times(1);
  provider1.NotifyOnItemUpdated(item1, absl::nullopt);
  provider2.NotifyOnItemUpdated(item2, absl::nullopt);
}

TEST_F(OfflineContentAggregatorTest, ProviderRemovedDuringCallbackFlush) {
  OpenItemRemovalOfflineContentProvider provider1("1", &aggregator_);

  ContentId id1("1", "A");
  ContentId id2("1", "B");

  EXPECT_CALL(
      provider1,
      OpenItem(OpenParamsEqual(OpenParams(LaunchLocation::DOWNLOAD_HOME)), id1))
      .Times(1);
  EXPECT_CALL(provider1, RemoveItem(id2)).Times(0);

  aggregator_.OpenItem(OpenParams(LaunchLocation::DOWNLOAD_HOME), id1);
  aggregator_.OpenItem(OpenParams(LaunchLocation::NOTIFICATION), id2);
  aggregator_.RemoveItem(id2);
}

TEST_F(OfflineContentAggregatorTest, SameProviderWithMultipleNamespaces) {
  MockOfflineContentProvider provider;
  ScopedMockOfflineContentProvider::ScopedMockObserver observer(&aggregator_);

  ContentId id1("1", "A");
  ContentId id2("2", "B");
  OfflineItem item1(id1);
  OfflineItem item2(id2);
  OfflineContentProvider::OfflineItemList items;
  items.push_back(item1);
  items.push_back(item2);
  provider.SetItems(items);

  aggregator_.RegisterProvider("1", &provider);
  aggregator_.RegisterProvider("2", &provider);
  EXPECT_TRUE(provider.HasObserver(&aggregator_));

  GetAllItemsAndVerify(&aggregator_, items);
  GetSingleItemAndVerify(&aggregator_, id1, item1);
  GetSingleItemAndVerify(&aggregator_, id2, item2);

  aggregator_.UnregisterProvider("1");
  EXPECT_TRUE(provider.HasObserver(&aggregator_));
  GetSingleItemAndVerify(&aggregator_, id1, absl::nullopt);
  GetSingleItemAndVerify(&aggregator_, id2, item2);

  aggregator_.UnregisterProvider("2");
  EXPECT_FALSE(provider.HasObserver(&aggregator_));
}

// Tests that if the aggregator is in the mid of GetAllItems() call and is
// waiting from multiple providers, it will remove deleted items from its
// response when notified.
TEST_F(OfflineContentAggregatorTest,
       ItemRemovedWhileWaitingForItemsFromOtherProviders) {
  ScopedMockOfflineContentProvider provider1("1", &aggregator_);
  DelayedGetAllItemOfflineContentProvider provider2("2", &aggregator_);

  ContentId id1 = ContentId("1", "A");
  OfflineContentProvider::OfflineItemList items1;
  OfflineItem item1(id1);
  OfflineItem item2(ContentId("1", "B"));
  items1.push_back(item1);
  items1.push_back(item2);

  OfflineContentProvider::OfflineItemList items2;
  items2.push_back(OfflineItem(ContentId("2", "C")));
  items2.push_back(OfflineItem(ContentId("2", "D")));

  provider1.SetItems(items1);
  provider2.SetItems(items2);

  OfflineContentProvider::OfflineItemList combined_items;
  combined_items.push_back(item2);
  combined_items.insert(combined_items.end(), items2.begin(), items2.end());
  GetAllItemsAndVerify(&aggregator_, combined_items);
  provider1.NotifyOnItemRemoved(id1);
  provider2.RunCallback(items2);
}

// Tests that if the aggregator is in the mid of GetAllItems() call and is
// waiting from multiple providers, it will properly update items in its
// response when notified.
TEST_F(OfflineContentAggregatorTest,
       ItemUpdatedWhileWaitingForItemsFromOtherProviders) {
  ScopedMockOfflineContentProvider provider1("1", &aggregator_);
  DelayedGetAllItemOfflineContentProvider provider2("2", &aggregator_);

  OfflineContentProvider::OfflineItemList items1;
  OfflineItem item1(ContentId("1", "A"));
  OfflineItem item2(ContentId("1", "B"));
  items1.push_back(item1);
  items1.push_back(item2);

  OfflineContentProvider::OfflineItemList items2;
  items2.push_back(OfflineItem(ContentId("2", "C")));
  items2.push_back(OfflineItem(ContentId("2", "D")));

  provider1.SetItems(items1);
  provider2.SetItems(items2);

  OfflineContentProvider::OfflineItemList combined_items;
  item1.title = "test";
  combined_items.push_back(item1);
  combined_items.push_back(item2);
  combined_items.insert(combined_items.end(), items2.begin(), items2.end());
  GetAllItemsAndVerify(&aggregator_, combined_items);
  provider1.NotifyOnItemUpdated(item1, absl::nullopt);
  provider2.RunCallback(items2);
}

}  // namespace
}  // namespace offline_items_collection


text:
package org.wso2.carbon.registry.core;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.jdbc.dataobjects.ResourceDO;

import java.util.*;

/**
 * The default registry implementation of the Collection interface.
 */
public class CollectionImpl extends ResourceImpl implements Collection {

    private static final Log log = LogFactory.getLog(CollectionImpl.class);

    /**
     * The number of children in this collection.
     */
    protected int childCount;

    /**
     * The default constructor of the CollectionImpl, Create an empty collection with no children.
     */
    public CollectionImpl() {
        childCount = -1;
    }

    /**
     * Construct a collection with the provided children paths.
     *
     * @param paths the children paths.
     */
    public CollectionImpl(String[] paths) {
        try {
            setChildren(paths);
        } catch (RegistryException e) {
            log.warn("Unable to set child paths to this collection.", e);
        }
    }

    /**
     * Construct a collection with the provided path and the resource data object.
     *
     * @param path       the path of the collection.
     * @param resourceDO the resource data object.
     */
    public CollectionImpl(String path, ResourceDO resourceDO) {
        super(path, resourceDO);
        childCount = -1;
    }

    /**
     * A copy constructor used to create a shallow-copy of this collection.
     *
     * @param collection the collection of which the copy is created.
     */
    public CollectionImpl(CollectionImpl collection) {
        super(collection);
        try {
            pullContentFromOriginal();
        } catch (RegistryException ignored) {
            // we are not interested in handling any failures here.
        }
        if (this.content != null) {
            if (this.content instanceof String[]) {
                String[] paths = (String[]) this.content;
                int length = paths.length;
                String[] output = new String[length];
                System.arraycopy(paths, 0, output, 0, length);
                this.content = output;
            }  else if (this.content instanceof Comment[]) {
                Comment[] paths = (Comment[]) this.content;
                int length = paths.length;
                Comment[] output = new Comment[length];
                System.arraycopy(paths, 0, output, 0, length);
                for (int i = 0; i < length; i++) {
                    output[i] = new Comment(output[i]);
                }
                this.content = output;
            } else if (this.content instanceof Resource[]) {
                Resource[] paths = (Resource[]) this.content;
                int length = paths.length;
                Resource[] output = new Resource[length];
                System.arraycopy(paths, 0, output, 0, length);
                for (int i = 0; i < length; i++) {
                    if (output[i] instanceof CollectionVersionImpl) {
                        output[i] = new CollectionVersionImpl((CollectionVersionImpl) output[i]);
                    } else if (output[i] instanceof CollectionImpl) {
                        output[i] = new CollectionImpl((CollectionImpl) output[i]);
                    } else if (output[i] instanceof Comment) {
                        output[i] = new Comment((Comment) output[i]);
                    } else if (output[i] instanceof ResourceImpl) {
                        output[i] = new ResourceImpl((ResourceImpl) output[i]);
                    }
                }
                this.content = output;
            }
        }
        this.childCount = collection.childCount;
    }

    /**
     * Implementation for the setContent. Here the content should always be a array of strings which
     * corresponding to the children paths.
     *
     * @param content array of strings which corresponding to the children paths.
     *
     * @throws RegistryException if the operation fails.
     */
    public void setContent(Object content) throws RegistryException {
        if (content == null) {
            return;
        }
        // note that string contents are allowed in collection to support custom generated UIs.
        if (content instanceof String[]) {
//                  super.setContent(content);
            //We do not update the last modified time when a child resource added to a collection
            super.setContentWithNoUpdate(content);
            childCount = ((String[])content).length;
            return;
        } else if (content instanceof Resource[]) {
//                  super.setContent(content);
            //We do not update the last modified time when a child resource added to a collection
            super.setContentWithNoUpdate(content);
            childCount = ((Resource[])content).length;
            return;
        } else if (content instanceof String) {
//                  super.setContent(content);
            //We do not update the last modified time when a child resource added to a collection
            super.setContentWithNoUpdate(content);

            return;
        }
        throw new IllegalArgumentException("Invalid content for collection. " +
                "Content of type " + content.getClass().toString() +
                " is not allowed for collections.");
    }

    /**
     * Set the resource content without marking the collection as updated.Here the content should
     * always be a array of strings which corresponding to the children paths.
     *
     * @param content array of strings which corresponding to the children paths.
     *
     * @throws RegistryException if the operation fails.
     */
    public void setContentWithNoUpdate(Object content) throws RegistryException {
        if (content == null) {
            return;
        }
        // note that string contents are allowed in collection to support custom generated UIs.
        if (content instanceof String[] ||
                content instanceof Resource[] ||
                content instanceof String) {
            super.setContentWithNoUpdate(content);
            return;
        }
        throw new IllegalArgumentException("Invalid content for collection. " +
                "Content of type " + content.getClass().toString() +
                " is not allowed for collections.");
    }

    /**
     * Method to set the absolute paths of the children belonging to this collection. Absolute paths
     * begin from the ROOT collection.
     *
     * @param paths the array of absolute paths of the children
     *
     * @throws RegistryException if the operation fails.
     */
    public void setChildren(String[] paths) throws RegistryException {
        String[] temp = fixPaths(paths);
        content = temp;
        childCount = temp.length;
    }

    /**
     * Method to return the children.
     *
     * @return an array of children paths.
     * @throws RegistryException if the operation fails.
     */
    public String[] getChildren() throws RegistryException {
        if (getContent() instanceof String[]) {
            return fixPaths((String[])getContent());
        } else {
            return new String[0];
        }
    }

    /**
     * Method to return the paths of the selected range of children.
     *
     * @param start   the starting number of children.
     * @param pageLen the number of entries to retrieve.
     *
     * @return an array of paths of the selected range of children.
     * @throws RegistryException if the operation fails.
     */
    public String[] getChildren(int start, int pageLen) throws RegistryException {
        setSessionInformation();
        try {
            pullContentFromOriginal();
            if (content == null) {
                if (resourceDAO == null) {
                    String msg = "The data access object for resources has not been created.";
                    log.error(msg);
                    throw new RegistryException(msg);
                }
                return fixPaths(resourceDAO.getChildren(this, start, pageLen, dataAccessManager));

            } else {

                if (content instanceof String[]) {

                    String childNodes[] = (String[]) content;
                    int limit = start + pageLen;
                    if (start > childNodes.length) {
                        return new String[0];
                    }
                    if (limit > childNodes.length) {
                        limit = childNodes.length;
                    }

                    return fixPaths(Arrays.copyOfRange(childNodes, start, limit));
                }
            }
            return new String[0];
        } finally {
            clearSessionInformation();
        }
    }

    /**
     * Method to return the the number of children.
     *
     * @return the number of children.
     * @throws RegistryException if the operation fails.
     */
    public int getChildCount() throws RegistryException {

        try {
            setSessionInformation();
            pullContentFromOriginal();
            if (childCount != -1) {
                return childCount;

            } else if (content != null && content instanceof String[]) {

                String[] childPaths = (String[]) content;
                return fixPaths(childPaths).length;

            }
            if (resourceDAO == null) {
                String msg = "The data access object for resources has not been created.";
                log.error(msg);
                throw new RegistryException(msg);
            }
            return resourceDAO.getChildCount(this, dataAccessManager);
        } finally {
            clearSessionInformation();
        }
    }

    /**
     * Method to set the child count.
     *
     * @param count the child count.
     */
    public void setChildCount(int count) {
        childCount = count;
    }

    /**
     * Collection's content is a string array, which contains paths of its children. These paths are
     * loaded on demand to increase performance. It is recommended to use {@link #getChildren()}
     * method to get child paths of a collection, which provides pagination. Calling this method
     * will load all child paths.
     *
     * @return String array of child paths.
     * @throws RegistryException On any error.
     */
    public Object getContent() throws RegistryException {
        setSessionInformation();
        try {
            pullContentFromOriginal();
            if (content == null) {
                if (resourceDAO == null) {
                    String msg = "The data access object for resources has not been created.";
                    log.error(msg);
                    throw new RegistryException(msg);
                }
                resourceDAO.fillChildren(this, dataAccessManager);
            }
            return content;
        } finally {
            clearSessionInformation();
        }
    }

    /**
     * Method to return a shallow copy of a collection.
     *
     * @return the shallow copy of the collection.
     * @throws RegistryException if the operation fails.
     */
    public ResourceImpl getShallowCopy() throws RegistryException {
        CollectionImpl newCollection = new CollectionImpl();
        fillCollectionCopy(newCollection);
        return newCollection;
    }

    /**
     * Copy all the values of the current collection attribute to the passed collection.
     *
     * @param collection the collection to get all the current collection attribute copied.
     *
     * @throws RegistryException if the operation fails.
     */
    public void fillCollectionCopy(CollectionImpl collection) throws RegistryException {
        super.fillResourceCopy(collection);
        collection.setChildCount(this.childCount);
    }

    /**
     * Method to fix duplicated entries in a collection's child paths.
     * @param paths the collection's child paths.
     * @return the distinct set of children.
     */
    @SuppressWarnings("ManualArrayToCollectionCopy")
    protected String[] fixPaths(String[] paths) {
        Set<String> temp = new LinkedHashSet<String>();
        // We want to make sure that each element is added one after the other in the exact order
        // that they were passed in.
        for (String path : paths) {
            temp.add(path);
        }
        return temp.toArray(new String[temp.size()]);
    }
}


text:
name 'test'
maintainer 'Chef Software, Inc.'
maintainer_email 'cookbooks@chef.io'
license 'Apache 2.0'
description 'A test cookbook for lvm'
version '0.1.0'

depends 'lvm'


text:
#include <jni.h>
#include <time.h>
#include <android/log.h>
#include <android/bitmap.h>

#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

/***********************common function*************************/
#define  LOG_TAG    "libes2test.so"
#define  LOGI(...)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
#define  LOGE(...)  __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)

const static GLfloat PI = 3.1415f;

static void printGLString(const char *name, GLenum s) {
    const char *v = (const char *) glGetString(s);
    LOGI("GL %s = %s\n", name, v);
}

static void checkGlError(const char* op) {
    for (GLint error = glGetError(); error; error
            = glGetError()) {
        LOGI("after %s() glError (0x%x)\n", op, error);
    }
}

//data
const GLfloat gVertices[] = { 0.75f, 0.75f, 0.0f, 1.0f,
		0.75f, -0.75f, 0.0f, 1.0f,
		-0.75f, -0.75f, 0.0f, 1.0f, };
const GLfloat gTexCoords[] = { 0, 1, 1, 1, 0, 0, 1, 0};

GLuint textureID;

GLuint positionBufferObject;
GLuint vao;

static void InitializeVertexBuffer()
{
	glGenBuffers(1, &positionBufferObject);

	glBindBuffer(GL_ARRAY_BUFFER, positionBufferObject);
	glBufferData(GL_ARRAY_BUFFER, sizeof(gVertices), gVertices, GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
}

static const char gVertexShader[] =
		"attribute vec4 a_Position;\n"
		"void main()\n"
		"{\n"
		"   gl_Position = position;\n"
		"}\n";

static const char gFragmentShader[] =
	    "precision mediump float;\n"
		"void main()\n"
		"{\n"
		"   gl_FragColor = vec4(1.0f, 1.0f, 1.0f, 1.0f);\n"
		"}\n";

GLuint loadShader(GLenum shaderType, const char* pSource) {
    GLuint shader = glCreateShader(shaderType);
    if (shader) {
        glShaderSource(shader, 1, &pSource, NULL);
        glCompileShader(shader);
        GLint compiled = 0;
        glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
        if (!compiled) {
            GLint infoLen = 0;
            glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen);
            if (infoLen) {
                char* buf = (char*) malloc(infoLen);
                if (buf) {
                    glGetShaderInfoLog(shader, infoLen, NULL, buf);
                    LOGE("Could not compile shader %d:\n%s\n",
                            shaderType, buf);
                    free(buf);
                }
                glDeleteShader(shader);
                shader = 0;
            }
        }
    }
    return shader;
}

GLuint createProgram(const char* pVertexSource, const char* pFragmentSource) {
    GLuint vertexShader = loadShader(GL_VERTEX_SHADER, pVertexSource);
    if (!vertexShader) {
        return 0;
    }

    GLuint pixelShader = loadShader(GL_FRAGMENT_SHADER, pFragmentSource);
    if (!pixelShader) {
        return 0;
    }

    GLuint program = glCreateProgram();
    if (program) {
        glAttachShader(program, vertexShader);
        checkGlError("glAttachShader");
        glAttachShader(program, pixelShader);
        checkGlError("glAttachShader");
        glLinkProgram(program);
        GLint linkStatus = GL_FALSE;
        glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
        if (linkStatus != GL_TRUE) {
            GLint bufLength = 0;
            glGetProgramiv(program, GL_INFO_LOG_LENGTH, &bufLength);
            if (bufLength) {
                char* buf = (char*) malloc(bufLength);
                if (buf) {
                    glGetProgramInfoLog(program, bufLength, NULL, buf);
                    LOGE("Could not link program:\n%s\n", buf);
                    free(buf);
                }
            }
            glDeleteProgram(program);
            program = 0;
        }
    }
    return program;
}

GLuint gProgram;
GLuint gPositionHandle;
GLuint gTexCoordsHandle;
GLuint gTexHandle;

static void loadTexture(JNIEnv * env, jobject bitmap)
{
	AndroidBitmapInfo  info;
	void*  pixels;
	int format;
	int ret;
	if ((ret = AndroidBitmap_getInfo(env, bitmap, &info)) < 0) {
	        LOGE("AndroidBitmap_getInfo() failed ! error=%d", ret);
	        return;
	    }

	    if (info.format == ANDROID_BITMAP_FORMAT_RGBA_8888) {
	        LOGI("Bitmap format is  RGBA_8888 !");
	        format = GL_RGBA;
	    } else if (info.format == ANDROID_BITMAP_FORMAT_RGB_565) {
	        LOGI("Bitmap format is  RGB_565 !");
	        format = GL_RGB;
	    }

	    if ((ret = AndroidBitmap_lockPixels(env, bitmap, &pixels)) < 0) {
	        LOGE("AndroidBitmap_lockPixels() failed ! error=%d", ret);
	    }

	    glGenTextures(1, &textureID);
	    glBindTexture(GL_TEXTURE_2D, textureID);
        // Set filtering
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        glTexImage2D(GL_TEXTURE_2D, 0, format, info.width, info.height, 0, format, GL_UNSIGNED_BYTE, pixels);

	    AndroidBitmap_unlockPixels(env, bitmap);
}

static void init(JNIEnv * env, jobject bitmap)
{
		InitializeVertexBuffer();

	    gProgram = createProgram(gVertexShader, gFragmentShader);
	    if (!gProgram) {
	        LOGE("Could not create program.");
	        return ;
	    }
	    gPositionHandle = glGetAttribLocation(gProgram, "a_Position");
	    checkGlError("glGetAttribLocation");
	    LOGI("glGetAttribLocation(\"a_Position\") = %d\n",
	            gPositionHandle);
/*
	    gTexCoordsHandle = glGetAttribLocation(gProgram, "a_TexCoords");
	    checkGlError("glGetAttribLocation");
	    LOGI("glGetAttribLocation(\"a_TexCoords\") = %d\n",
	    		gTexCoordsHandle);
	    gTexHandle = glGetUniformLocation(gProgram, "u_Texture");
	    checkGlError("glGetUniformLocation");
	    LOGI("glGetUniformLocation(\"u_Texture\") = %d\n",
	    		gTexHandle);
*/
}

static void resize(int w, int h)
{
	   if (h==0)								// ·ÀÖ¹±»Áã³ý
	  {
			  h=1;							// ½«HeightÉèΪ1
	  }

	  glViewport(0, 0, w, h);					// ÖØÖõ±Ç°µÄÊÓ¿Ú

}

static void update()
{
	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
	glClear(GL_COLOR_BUFFER_BIT );

    glUseProgram(gProgram);
    checkGlError("glUseProgram");
    glBindBuffer(GL_ARRAY_BUFFER, positionBufferObject);
    checkGlError("glBindBuffer");
	glEnableVertexAttribArray(0);
	checkGlError("glEnableVertexAttribArray");
	glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
	checkGlError("glVertexAttribPointer");
	glDrawArrays(GL_TRIANGLES, 0, 3);
	checkGlError("glDrawArrays");

	glDisableVertexAttribArray(0);
	glUseProgram(0);
}

extern "C" {
    JNIEXPORT void JNICALL Java_com_fyj_demo_es_jni_Test1Renderer_resize(JNIEnv * env, jobject obj,  jint width, jint height);
    JNIEXPORT void JNICALL Java_com_fyj_demo_es_jni_Test1Renderer_draw(JNIEnv * env, jobject obj);
    JNIEXPORT void JNICALL Java_com_fyj_demo_es_jni_Test1Renderer_init(JNIEnv * env, jobject obj, jobject bitmap);
};

JNIEXPORT void JNICALL Java_com_fyj_demo_es_jni_Test1Renderer_resize(JNIEnv * env, jobject obj,  jint width, jint height)
{
	resize(width, height);
}

JNIEXPORT void JNICALL Java_com_fyj_demo_es_jni_Test1Renderer_draw(JNIEnv * env, jobject obj)
{
	update();
}

JNIEXPORT void JNICALL Java_com_fyj_demo_es_jni_Test1Renderer_init(JNIEnv * env, jobject obj, jobject bitmap)
{
	init(env, bitmap);
}


text:
var sLoadingClass = "Loading",
    oEventGridContainer = $("#eventGrid"),
    iTotalEvent = 0,
    oEventData = null,
    events = '',
    iIterator = 0

function loadEvents() {
    oEventGridContainer.html("").addClass(sLoadingClass);
    $("#loadingicon").html("").addClass("CaseStudyLoading");
    $.ajax({
        url: 'https://www.blogger.com/feeds/8920013036459621984/posts/default?max-results=999',
        type: 'GET',
        dataType: 'jsonp',
        success: function (sResponse) {
            var parser = new DOMParser();
            oEventData = parser.parseFromString(sResponse, "text/xml");
            entries = oEventData.getElementsByTagName('entry');
            entries = Object.values(entries);
            sortedEntries = [];
            iTotalEntries = entries.length;
            for (iIterator = 0; iIterator < iTotalEntries-1; iIterator++)
            {
                // Find the minimum element in unsorted array
                min_idx = iIterator;
                for (j = iIterator + 1; j < iTotalEntries; j++) {
                    iDate = new Date(entries[iIterator].getElementsByTagName('category')[0].attributes["term"].nodeValue)
                    jDate = new Date(entries[j].getElementsByTagName('category')[0].attributes["term"].nodeValue)
                    if (jDate < iDate) {
                        min_idx = j;
                    }
                }
                // Swap the found minimum element with the first element
                [entries[min_idx], entries[iIterator]] = [ entries[iIterator],entries[min_idx]]
            }
            for (iIterator = 0; iIterator < iTotalEntries; iIterator++) {
                entry = entries[iIterator];
                eventHTML = entry.getElementsByTagName('content')[0].childNodes[0].nodeValue;
                events += eventHTML;
            }
            $("#eventGrid").append(events);
        }
    });
    oEventGridContainer.removeClass(sLoadingClass);
    $("#loadingicon").hide();
}


text:
import { shadowUI, nativeMethods } from './deps/hammerhead';
import { styleUtils, eventUtils } from './deps/testcafe-core';
import uiRoot from './ui-root';

//Const
const LOADING_TEXT                         = 'Loading page...';
const BACKGROUND_CLASS                     = 'modal-background';
const LOADING_TEXT_CLASS                   = 'loading-text';
const BACKGROUND_OPACITY                   = 0.7;
const BACKGROUND_OPACITY_WITH_LOADING_TEXT = 0.8;

const LOADING_ICON_CLASS = 'loading-icon';

//Globals
var backgroundDiv  = null;
var loadingTextDiv = null;
var loadingIconDiv = null;
var initialized    = false;

//Markup
function createBackground () {
    var root = uiRoot.element();

    backgroundDiv = document.createElement('div');
    root.appendChild(backgroundDiv);
    shadowUI.addClass(backgroundDiv, BACKGROUND_CLASS);

    loadingTextDiv = document.createElement('div');

    nativeMethods.nodeTextContentSetter.call(loadingTextDiv, LOADING_TEXT);
    root.appendChild(loadingTextDiv);
    shadowUI.addClass(loadingTextDiv, LOADING_TEXT_CLASS);

    loadingIconDiv = document.createElement('div');
    styleUtils.set(loadingIconDiv, 'visibility', 'hidden');
    root.appendChild(loadingIconDiv);
    shadowUI.addClass(loadingIconDiv, LOADING_ICON_CLASS);
}

//Behavior
function adjustLoadingTextPos () {
    var wHeight           = styleUtils.getHeight(window);
    var wWidth            = styleUtils.getWidth(window);
    var loadingTextHidden = !styleUtils.hasDimensions(loadingTextDiv);

    if (loadingTextHidden) {
        styleUtils.set(loadingTextDiv, 'visibility', 'hidden');
        styleUtils.set(loadingTextDiv, 'display', 'block');
    }

    styleUtils.set(loadingTextDiv, {
        left: Math.max((wWidth - styleUtils.getWidth(loadingTextDiv)) / 2, 0) + 'px',
        top:  Math.max((wHeight - styleUtils.getHeight(loadingTextDiv)) / 2, 0) + 'px'
    });

    if (loadingTextHidden) {
        styleUtils.set(loadingTextDiv, 'display', 'none');
        styleUtils.set(loadingTextDiv, 'visibility', '');
    }
}

function initSizeAdjustments () {
    var adjust = function () {
        var wHeight = styleUtils.getHeight(window);
        var wWidth  = styleUtils.getWidth(window);

        styleUtils.set(backgroundDiv, 'width', wWidth + 'px');
        styleUtils.set(backgroundDiv, 'height', wHeight + 'px');

        styleUtils.set(loadingIconDiv, {
            left: Math.round((wWidth - styleUtils.getWidth(loadingIconDiv)) / 2) + 'px',
            top:  Math.round((wHeight - styleUtils.getHeight(loadingIconDiv)) / 2) + 'px'
        });
    };

    adjust();

    eventUtils.bind(window, 'resize', adjust);
}

function init () {
    createBackground();
    initSizeAdjustments();
    adjustLoadingTextPos();

    initialized = true;
}

export function initAndShowLoadingText () {
    var shown = false;

    //NOTE: init and show modal background as soon as possible
    var initAndShow = function () {
        init();

        styleUtils.set(backgroundDiv, 'opacity', BACKGROUND_OPACITY_WITH_LOADING_TEXT);
        styleUtils.set(backgroundDiv, 'display', 'block');
        styleUtils.set(loadingTextDiv, 'display', 'block');

        shown = true;
    };

    var tryShowBeforeReady = function () {
        if (!shown) {
            if (document.body)
                initAndShow();
            else
                nativeMethods.setTimeout.call(window, tryShowBeforeReady, 0);
        }
    };

    tryShowBeforeReady();

    //NOTE: ensure that background was shown on ready
    eventUtils
        .documentReady()
        .then(() => {
            if (!shown)
                initAndShow();
        });
}

export function show (transparent) {
    if (!initialized)
        init();

    styleUtils.set(backgroundDiv, 'opacity', transparent ? 0 : BACKGROUND_OPACITY);
    styleUtils.set(backgroundDiv, 'display', 'block');
}

export function hide () {
    if (!initialized)
        return;

    styleUtils.set(loadingTextDiv, 'display', 'none');
    styleUtils.set(backgroundDiv, 'display', 'none');
}

export function showLoadingIcon () {
    styleUtils.set(loadingIconDiv, 'visibility', 'visible');
}

export function hideLoadingIcon () {
    styleUtils.set(loadingIconDiv, 'visibility', 'hidden');
}


text:
// ========================================================================
// Copyright (c) Webtide LLC
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.apache.org/licenses/LICENSE-2.0.txt
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.mortbay.jetty.webapp.verifier.rules;

import java.io.File;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.mortbay.jetty.webapp.verifier.AbstractArchiveScanningRule;
import org.mortbay.jetty.webapp.verifier.rules.asm.ASMUtil;
import org.mortbay.jetty.webapp.verifier.rules.asm.AbstractClassVisitor;

/**
 * Ensure all compiled classes within webapp are within the supported JVM range.
 */
public class JavaSupportLevelRule extends AbstractArchiveScanningRule
{
    class ClassVersionVisitor extends AbstractClassVisitor
    {
        private double classVersion = -1;

        public double getClassVersion()
        {
            return classVersion;
        }

        private double getJavaClassVersion(int version)
        {
            int major = version & 0xFFFF;
            int minor = version >>> 16;

            // Java Versions to Class Version (major.minor)
            // Java 1.6 = 50.0
            // Java 1.5 = 49.0
            // Java 1.4 = 48.0
            // Java 1.3 = 47.0
            // Java 1.2 = 46.0
            // Java 1.1 = 45.3

            // TODO: check these since they are > instead of >=
            if (major >= 50)
            {
                return 1.6;
            }
            else if (major >= 49)
            {
                return 1.5;
            }
            else if (major >= 48)
            {
                return 1.4;
            }
            else if (major >= 47)
            {
                return 1.3;
            }
            else if (major >= 46)
            {
                return 1.2;
            }
            else if (major >= 45)
            {
                if (minor >= 3)
                {
                    return 1.1;
                }
                return 1.0;
            }

            return 0.0;
        }

        public void reset()
        {
            this.classVersion = (-1);
        }

        @Override
        public void visit(int version, int access, String name, String signature, String superName, String[] interfaces)
        {
            this.classVersion = getJavaClassVersion(version);
        }
    }

    private double supportedVersion = 1.5;
    private ClassVersionVisitor visitor;

    @Override
    public String getDescription()
    {
        return "Ensure all compiled classes within webapp are within the supported JVM";
    }

    @Override
    public String getName()
    {
        return "java-support-level";
    }

    public double getSupportedVersion()
    {
        return supportedVersion;
    }

    public void setSupportedVersion(double supportedVersion)
    {
        this.supportedVersion = supportedVersion;
    }

    @Override
    public void visitArchiveClass(String path, String className, ZipFile archive, ZipEntry archiveEntry)
    {
        try
        {
            visitor.reset();
            ASMUtil.visitClass(archive.getInputStream(archiveEntry),visitor,0);
            if (visitor.classVersion > supportedVersion)
            {
                error(path,"Class is compiled for java version [" + visitor.classVersion + "] which is over supported java version [" + supportedVersion + "]");
            }
        }
        catch (IOException e)
        {
            exception(path,"Unable to read class",e);
        }
    }

    @Override
    public void visitWebappStart(String path, File dir)
    {
        visitor = new ClassVersionVisitor();
    }

    @Override
    public void visitWebInfClass(String path, String className, File classFile)
    {
        try
        {
            visitor.reset();
            ASMUtil.visitClassFile(classFile,visitor,0);
            if (visitor.classVersion > supportedVersion)
            {
                error(path,"Class is compiled for java version [" + visitor.classVersion + "] which is over supported java version [" + supportedVersion + "]");
            }
        }
        catch (IOException e)
        {
            exception(path,"Unable to read class",e);
        }
    }
}


text:
import invariant from 'shared/invariant';

let invokeGuardedCallbackImpl = function<A, B, C, D, E, F, Context>(
  name: string | null,
  func: (a: A, b: B, c: C, d: D, e: E, f: F) => mixed,
  context: Context,
  a: A,
  b: B,
  c: C,
  d: D,
  e: E,
  f: F,
) {
  const funcArgs = Array.prototype.slice.call(arguments, 3);
  try {
    func.apply(context, funcArgs);
  } catch (error) {
    this.onError(error);
  }
};

if (__DEV__) {
  // In DEV mode, we swap out invokeGuardedCallback for a special version
  // that plays more nicely with the browser's DevTools. The idea is to preserve
  // "Pause on exceptions" behavior. Because React wraps all user-provided
  // functions in invokeGuardedCallback, and the production version of
  // invokeGuardedCallback uses a try-catch, all user exceptions are treated
  // like caught exceptions, and the DevTools won't pause unless the developer
  // takes the extra step of enabling pause on caught exceptions. This is
  // untintuitive, though, because even though React has caught the error, from
  // the developer's perspective, the error is uncaught.
  //
  // To preserve the expected "Pause on exceptions" behavior, we don't use a
  // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake
  // DOM node, and call the user-provided callback from inside an event handler
  // for that fake event. If the callback throws, the error is "captured" using
  // a global event handler. But because the error happens in a different
  // event loop context, it does not interrupt the normal program flow.
  // Effectively, this gives us try-catch behavior without actually using
  // try-catch. Neat!

  // Check that the browser supports the APIs we need to implement our special
  // DEV version of invokeGuardedCallback
  if (
    typeof window !== 'undefined' &&
    typeof window.dispatchEvent === 'function' &&
    typeof document !== 'undefined' &&
    typeof document.createEvent === 'function'
  ) {
    const fakeNode = document.createElement('react');

    const invokeGuardedCallbackDev = function<A, B, C, D, E, F, Context>(
      name: string | null,
      func: (a: A, b: B, c: C, d: D, e: E, f: F) => mixed,
      context: Context,
      a: A,
      b: B,
      c: C,
      d: D,
      e: E,
      f: F,
    ) {
      // If document doesn't exist we know for sure we will crash in this method
      // when we call document.createEvent(). However this can cause confusing
      // errors: https://github.com/facebookincubator/create-react-app/issues/3482
      // So we preemptively throw with a better message instead.
      invariant(
        typeof document !== 'undefined',
        'The `document` global was defined when React was initialized, but is not ' +
          'defined anymore. This can happen in a test environment if a component ' +
          'schedules an update from an asynchronous callback, but the test has already ' +
          'finished running. To solve this, you can either unmount the component at ' +
          'the end of your test (and ensure that any asynchronous operations get ' +
          'canceled in `componentWillUnmount`), or you can change the test itself ' +
          'to be asynchronous.',
      );
      const evt = document.createEvent('Event');

      // Keeps track of whether the user-provided callback threw an error. We
      // set this to true at the beginning, then set it to false right after
      // calling the function. If the function errors, `didError` will never be
      // set to false. This strategy works even if the browser is flaky and
      // fails to call our global error handler, because it doesn't rely on
      // the error event at all.
      let didError = true;

      // Keeps track of the value of window.event so that we can reset it
      // during the callback to let user code access window.event in the
      // browsers that support it.
      let windowEvent = window.event;

      // Create an event handler for our fake event. We will synchronously
      // dispatch our fake event using `dispatchEvent`. Inside the handler, we
      // call the user-provided callback.
      const funcArgs = Array.prototype.slice.call(arguments, 3);
      function callCallback() {
        // We immediately remove the callback from event listeners so that
        // nested `invokeGuardedCallback` calls do not clash. Otherwise, a
        // nested call would trigger the fake event handlers of any call higher
        // in the stack.
        fakeNode.removeEventListener(evtType, callCallback, false);

        // We check for window.hasOwnProperty('event') to prevent the
        // window.event assignment in both IE <= 10 as they throw an error
        // "Member not found" in strict mode, and in Firefox which does not
        // support window.event.
        if (
          typeof window.event !== 'undefined' &&
          window.hasOwnProperty('event')
        ) {
          window.event = windowEvent;
        }

        func.apply(context, funcArgs);
        didError = false;
      }

      // Create a global error event handler. We use this to capture the value
      // that was thrown. It's possible that this error handler will fire more
      // than once; for example, if non-React code also calls `dispatchEvent`
      // and a handler for that event throws. We should be resilient to most of
      // those cases. Even if our error event handler fires more than once, the
      // last error event is always used. If the callback actually does error,
      // we know that the last error event is the correct one, because it's not
      // possible for anything else to have happened in between our callback
      // erroring and the code that follows the `dispatchEvent` call below. If
      // the callback doesn't error, but the error event was fired, we know to
      // ignore it because `didError` will be false, as described above.
      let error;
      // Use this to track whether the error event is ever called.
      let didSetError = false;
      let isCrossOriginError = false;

      function handleWindowError(event) {
        error = event.error;
        didSetError = true;
        if (error === null && event.colno === 0 && event.lineno === 0) {
          isCrossOriginError = true;
        }
        if (event.defaultPrevented) {
          // Some other error handler has prevented default.
          // Browsers silence the error report if this happens.
          // We'll remember this to later decide whether to log it or not.
          if (error != null && typeof error === 'object') {
            try {
              error._suppressLogging = true;
            } catch (inner) {
              // Ignore.
            }
          }
        }
      }

      // Create a fake event type.
      const evtType = `react-${name ? name : 'invokeguardedcallback'}`;

      // Attach our event handlers
      window.addEventListener('error', handleWindowError);
      fakeNode.addEventListener(evtType, callCallback, false);

      // Synchronously dispatch our fake event. If the user-provided function
      // errors, it will trigger our global error handler.
      evt.initEvent(evtType, false, false);
      fakeNode.dispatchEvent(evt);

      if (didError) {
        if (!didSetError) {
          // The callback errored, but the error event never fired.
          error = new Error(
            'An error was thrown inside one of your components, but React ' +
              "doesn't know what it was. This is likely due to browser " +
              'flakiness. React does its best to preserve the "Pause on ' +
              'exceptions" behavior of the DevTools, which requires some ' +
              "DEV-mode only tricks. It's possible that these don't work in " +
              'your browser. Try triggering the error in production mode, ' +
              'or switching to a modern browser. If you suspect that this is ' +
              'actually an issue with React, please file an issue.',
          );
        } else if (isCrossOriginError) {
          error = new Error(
            "A cross-origin error was thrown. React doesn't have access to " +
              'the actual error object in development. ' +
              'See https://fb.me/react-crossorigin-error for more information.',
          );
        }
        this.onError(error);
      }

      // Remove our event listeners
      window.removeEventListener('error', handleWindowError);
    };

    invokeGuardedCallbackImpl = invokeGuardedCallbackDev;
  }
}

export default invokeGuardedCallbackImpl;


text:
package com.jdon.jivejdon.presentation.form;

import java.beans.BeanDescriptor;
import java.beans.PropertyDescriptor;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionMapping;

import com.jdon.jivejdon.model.message.MessageRendering;

/**
 * @author banq
 *
 */
public class FiltersForm extends BaseForm {
    private BeanDescriptor[] availableDescriptors; //all filter's Descriptors

    private Collection unInstalledDescriptors; //unInstalled filter's Descriptors

    private BeanDescriptor[] descriptors; //Installed filter's Descriptors

    private MessageRendering[] filters; //Installed filters

    private Map propertyDescriptors = new HashMap();

    private int filterCount;
    private int filterIndex;
    private int pos;
    private boolean up;
    private boolean down;

    /**
     * @return Returns the down.
     */
    public boolean isDown() {
        return down;
    }
    /**
     * @param down The down to set.
     */
    public void setDown(boolean down) {
        this.down = down;
    }
    /**
     * @return Returns the filterIndex.
     */
    public int getFilterIndex() {
        return filterIndex;
    }
    /**
     * @param filterIndex The filterIndex to set.
     */
    public void setFilterIndex(int filterIndex) {
        this.filterIndex = filterIndex;
    }
    /**
     * @return Returns the up.
     */
    public boolean isUp() {
        return up;
    }
    /**
     * @param up The up to set.
     */
    public void setUp(boolean up) {
        this.up = up;
    }

    /**
     * @return Returns the availableDescriptors.
     */
    public BeanDescriptor[] getAvailableDescriptors() {
        return availableDescriptors;
    }
    /**
     * @param availableDescriptors The availableDescriptors to set.
     */
    public void setAvailableDescriptors(BeanDescriptor[] availableDescriptors) {
        this.availableDescriptors = availableDescriptors;
    }
    /**
     * @return Returns the filtersSize.
     */
    public int getFiltersSize() {
        return availableDescriptors.length;
    }
    /**
     * @return Returns the filters.
     */
    public MessageRendering[] getFilters() {
        return filters;
    }

    public MessageRendering getFiltersIndexed(Integer index) {
        return (MessageRendering)filters[index.intValue()];
    }

    public void setStringIndexed(int index, MessageRendering filter) {
        filters[index] = filter;
    }
    /**
     * @param filters The filters to set.
     */
    public void setFilters(MessageRendering[] filters) {
        this.filters = filters;
    }
    /**
     * @return Returns the propertyDescriptors.
     */
    public PropertyDescriptor[] getPropertyDescriptors(BeanDescriptor descriptor) {
        return (PropertyDescriptor[])propertyDescriptors.get(descriptor);
    }

    /**
     * @param propertyDescriptors The propertyDescriptors to set.
     */
    public void setPropertyDescriptors(BeanDescriptor descriptor,  PropertyDescriptor[] propertyDescriptors) {
        this.propertyDescriptors.put(descriptor, propertyDescriptors);
    }
    /**
     * @return Returns the filterCount.
     */
    public int getFilterCount() {
        return filterCount;
    }

    /**
     * @param filterCount The filterCount to set.
     */
    public void setFilterCount(int filterCount) {
        this.filterCount = filterCount;
    }

    /**
     * @return Returns the descriptors.
     */
    public BeanDescriptor[] getDescriptors() {
        return descriptors;
    }
    /**
     * @param descriptors The descriptors to set.
     */
    public void setDescriptors(BeanDescriptor[] descriptors) {
        this.descriptors = descriptors;
    }

    /**
     * @return Returns the pos.
     */
    public int getPos() {
        return pos;
    }
    /**
     * @param pos The pos to set.
     */
    public void setPos(int pos) {
        this.pos = pos;
    }

    /**
     * @return Returns the propertyDescriptors.
     */
    public Map getPropertyDescriptors() {
        return propertyDescriptors;
    }

    /**
     * @param propertyDescriptors The propertyDescriptors to set.
     */
    public void setPropertyDescriptors(Map propertyDescriptors) {
        this.propertyDescriptors = propertyDescriptors;
    }

    /**
     * @return Returns the unInstalledDescriptors.
     */
    public Collection getUnInstalledDescriptors() {
        return unInstalledDescriptors;
    }
    /**
     * @param unInstalledDescriptors The unInstalledDescriptors to set.
     */
    public void setUnInstalledDescriptors(Collection unInstalledDescriptors) {
        this.unInstalledDescriptors = unInstalledDescriptors;
    }

    /* (non-Javadoc)
     * @see com.jdon.jivejdon.presentation.form.BaseForm#doValidate(org.apache.struts.action.ActionMapping, javax.servlet.http.HttpServletRequest, java.util.List)
     */
    public void doValidate(ActionMapping mapping, HttpServletRequest request, List errors) {
        // TODO Auto-generated method stub

    }

}


text:
package io.crate.sql.tree;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

public abstract class PrivilegeStatement extends Statement {

    protected final List<String> userNames;
    protected final List<String> privilegeTypes;
    private final List<QualifiedName> tableOrSchemaNames;
    private final String clazz;
    protected final boolean all;

    public PrivilegeStatement(List<String> userNames, String clazz, List<QualifiedName> tableOrSchemaNames) {
        this.userNames = userNames;
        privilegeTypes = Collections.emptyList();
        all = true;
        this.clazz = clazz;
        this.tableOrSchemaNames = tableOrSchemaNames;
    }

    public PrivilegeStatement(List<String> userNames, List<String> privilegeTypes, String clazz, List<QualifiedName> tableOrSchemaNames) {
        this.userNames = userNames;
        this.privilegeTypes = privilegeTypes;
        this.all = false;
        this.clazz = clazz;
        this.tableOrSchemaNames = tableOrSchemaNames;
    }

    public List<String> privileges() {
        return privilegeTypes;
    }

    public List<String> userNames() {
        return userNames;
    }

    public boolean all() {
        return all;
    }

    public List<QualifiedName> privilegeIdents() {
        return tableOrSchemaNames;
    }

    public String clazz() {
        return clazz;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        PrivilegeStatement that = (PrivilegeStatement) o;
        return all == that.all &&
               Objects.equals(userNames, that.userNames) &&
               Objects.equals(privilegeTypes, that.privilegeTypes);
    }

    @Override
    public int hashCode() {
        return Objects.hash(userNames, privilegeTypes, all);
    }

}


text:
package org.phenoscape.owlet

import org.junit.{Assert, Test}
import org.phenoscape.owlet.OwletManchesterSyntaxDataType._
import org.phenoscape.owlet.SPARQLComposer._
import org.semanticweb.owlapi.apibinding.OWLManager
import org.semanticweb.owlapi.model.IRI
import org.semanticweb.owlapi.vocab.OWLRDFVocabulary

import scala.language.postfixOps

class TestSPARQLComposer {

  val omn = Owlet.MANCHESTER
  val factory = OWLManager.getOWLDataFactory

  @Test
  def testZeroOrMorePropertyPath(): Unit = {
    val head = factory.getOWLClass(IRI.create("http://example.org/head"))
    val muscle = factory.getOWLClass(IRI.create("http://example.org/muscle"))
    val part_of = factory.getOWLObjectProperty(IRI.create("http://example.org/part_of"))
    val expression = factory.getOWLObjectIntersectionOf(muscle, factory.getOWLObjectSomeValuesFrom(part_of, head))
    val rdfsSubClassOf = factory.getOWLObjectProperty(OWLRDFVocabulary.RDFS_SUBCLASS_OF.getIRI)
    val rdfType = factory.getOWLObjectProperty(OWLRDFVocabulary.RDF_TYPE.getIRI)
    val query = select_distinct('phenotype) from "http://kb.phenoscape.org/" where (
      bgp(
        t('eq, rdfsSubClassOf*, 'absence),
        t('phenotype, rdfType, 'eq)),
        service("http://owlery.phenoscape.org/sparql",
          bgp(
            t('eq, rdfsSubClassOf, "part_of some blah" ^^ omn),
            t('eq, rdfsSubClassOf, expression.asOMN)))) order_by 'phenotype
    println(query)
  }

  @Test
  def constructQuery(): Unit = {
    val head = factory.getOWLClass(IRI.create("http://example.org/head"))
    val muscle = factory.getOWLClass(IRI.create("http://example.org/muscle"))
    val part_of = factory.getOWLObjectProperty(IRI.create("http://example.org/part_of"))
    val expression = factory.getOWLObjectIntersectionOf(muscle, factory.getOWLObjectSomeValuesFrom(part_of, head))
    val rdfsSubClassOf = factory.getOWLObjectProperty(OWLRDFVocabulary.RDFS_SUBCLASS_OF.getIRI)
    val rdfType = factory.getOWLObjectProperty(OWLRDFVocabulary.RDF_TYPE.getIRI)
    val query = construct(t('phenotype, rdfType, 'eq)) from "http://kb.phenoscape.org/" where (
      bgp(
        t('eq, rdfsSubClassOf*, 'absence),
        t('phenotype, rdfType, 'eq),
        t('foo, 'pred, 'bar)),
        service("http://owlery.phenoscape.org/sparql",
          bgp(
            t('eq, rdfsSubClassOf, "part_of some blah" ^^ omn),
            t('blah, rdfsSubClassOf / rdfType, 'blah),
            t('blah, rdfsSubClassOf / (rdfType *), 'blah),
            t('blah, rdfsSubClassOf | (rdfType*) / part_of, 'blah),
            t('blah, rdfsSubClassOf ?, 'blah),
            t('blah, rdfsSubClassOf +, 'blah),
            t('foo, 'pred, 'bar),
            t('eq, rdfsSubClassOf, expression.asOMN)),
          filter('eq in (owlEntityToNode(rdfType) :: owlEntityToNode(rdfsSubClassOf) :: Nil)))) order_by 'phenotype
    println(query)
  }

  @Test
  def testManchesterSyntaxRenderer(): Unit = {

    val head = factory.getOWLClass(IRI.create("http://example.org/head"))
    val muscle = factory.getOWLClass(IRI.create("http://example.org/muscle"))
    val part_of = factory.getOWLObjectProperty(IRI.create("http://example.org/part_of"))
    val expression = factory.getOWLObjectIntersectionOf(muscle, factory.getOWLObjectSomeValuesFrom(part_of, head))
    Assert.assertEquals("\"<http://example.org/muscle> and (<http://example.org/part_of> some <http://example.org/head>)\"^^http://purl.org/phenoscape/owlet/syntax#omn",
      expression.asOMN.toString)
  }

}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../openssl_sys/constant.EVP_PKEY_X25519.html">

Redirecting to ../../openssl_sys/constant.EVP_PKEY_X25519.html...


text:
package com.uwics.uwidiscover.classes.models;

import java.util.ArrayList;

/**
 * Created by Howard on 1/22/2016.
 */
public class Project {

    String id;
    String title;
    String description;
    ArrayList<Media> media;
    ArrayList<Representative> moderators;
    ArrayList<Feedback> feedback;
    Location location;

    public Project(String id, String title, String description, ArrayList<Media> media,
                   ArrayList<Representative> moderators, ArrayList<Feedback> feedback,
                   Location location) {
        this.id = id;
        this.title = title;
        this.description = description;
        this.media = media;
        this.moderators = moderators;
        this.feedback = feedback;
        this.location = location;
    }

    public String getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public ArrayList<Media> getMedia() {
        return media;
    }

    public void setMedia(ArrayList<Media> media) {
        this.media = media;
    }

    public ArrayList<Representative> getModerators() {
        return moderators;
    }

    public void setModerators(ArrayList<Representative> moderators) {
        this.moderators = moderators;
    }

    public ArrayList<Feedback> getFeedback() {
        return feedback;
    }

    public void setFeedback(ArrayList<Feedback> feedback) {
        this.feedback = feedback;
    }

    public Location getLocation() {
        return location;
    }

    public void setLocation(Location location) {
        this.location = location;
    }
}


text:
"""
tokenize.py -
Tokenizer for langid.py training system. This takes a list of files and tokenizes them
in parallel.

Marco Lui, January 2013

Copyright 2013 Marco Lui <saffsd@gmail.com>. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice, this list of
      conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright notice, this list
      of conditions and the following disclaimer in the documentation and/or other materials
      provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ``AS IS'' AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The views and conclusions contained in the software and documentation are those of the
authors and should not be interpreted as representing official policies, either expressed
or implied, of the copyright holder.
"""

######
# Default values
# Can be overriden with command-line options
######
MAX_NGRAM_ORDER = 4 # largest order of n-grams to consider
TOP_DOC_FREQ = 15000 # number of tokens to consider for each order
NUM_BUCKETS = 64 # number of buckets to use in k-v pair generation
CHUNKSIZE = 50 # maximum size of chunk (number of files tokenized - less = less memory use)

import os, sys, argparse
import csv
import shutil
import tempfile
import marshal
import multiprocessing as mp
import atexit

from itertools import tee
from collections import defaultdict

from common import makedir, chunk, MapPool

class NGramTokenizer(object):
  def __init__(self, min_order=1, max_order=3):
    self.min_order = min_order
    self.max_order = max_order

  def __call__(self, seq):
    min_order = self.min_order
    max_order = self.max_order
    t = tee(seq, max_order)
    for i in xrange(max_order):
      for j in xrange(i):
        # advance iterators, ignoring result
        t[i].next()
    while True:
      token = ''.join(tn.next() for tn in t)
      if len(token) < max_order: break
      for n in xrange(min_order-1, max_order):
        yield token[:n+1]
    for a in xrange(max_order-1):
      for b in xrange(min_order, max_order-a):
        yield token[a:a+b]

@atexit.register
def cleanup():
  global b_dirs, complete
  try:
    if not complete:
      for d in b_dirs:
        shutil.rmtree(d)
  except NameError:
    # Failed before globals defined, nothing to clean
    pass

def setup_pass_tokenize(tokenizer, b_dirs):
  global __tokenizer, __b_dirs
  __tokenizer = tokenizer
  __b_dirs = b_dirs

def pass_tokenize(chunk_items):
  """
  Chunk files into a doc->term mapping,
  and simultaneously build a term->df count.
  The term->df counts are redistributed to
  buckets via python's in-built hash function.
  This is basically an inversion step, so that
  now we are chunked on the term axis rather
  than the document axis.
  """
  global __maxorder, __b_dirs, __extractor
  __procname = mp.current_process().name
  b_freq_lang = [tempfile.mkstemp(prefix=__procname+'-', suffix='.lang', dir=p)[0] for p in __b_dirs]
  b_freq_domain = [tempfile.mkstemp(prefix=__procname+'-', suffix='.domain', dir=p)[0] for p in __b_dirs]

  extractor = __tokenizer
  term_lng_freq = defaultdict(lambda: defaultdict(int))
  term_dom_freq = defaultdict(lambda: defaultdict(int))

  for doc_index, (domain_id, lang_id, path) in enumerate(chunk_items):
    with open(path) as f:
      tokenset = set(extractor(f.read()))
      for token in tokenset:
        term_lng_freq[token][lang_id] += 1
        term_dom_freq[token][domain_id] += 1

  for term in term_lng_freq:
    bucket_index = hash(term) % len(b_freq_lang)
    for lang, count in term_lng_freq[term].iteritems():
      os.write(b_freq_lang[bucket_index], marshal.dumps((term, lang, count)))
    for domain, count in term_dom_freq[term].iteritems():
      os.write(b_freq_domain[bucket_index], marshal.dumps((term, domain, count)))

  # Close all the open files
  for f in b_freq_lang + b_freq_domain:
    os.close(f)

  return len(term_lng_freq)

def build_index(items, tokenizer, outdir, buckets=NUM_BUCKETS, jobs=None, chunksize=CHUNKSIZE):
  """
  @param items a list of (domain, language, path) tuples
  """
  global b_dirs, complete

  # Our exitfunc uses this to know whether to delete the tokenized files
  complete = False

  if jobs is None:
    jobs = mp.cpu_count() + 4

  b_dirs = [ tempfile.mkdtemp(prefix="tokenize-",suffix='-{0}'.format(tokenizer.__class__.__name__), dir=outdir) for i in range(buckets) ]

  # PASS 1: Tokenize documents into sets of terms

  # If there are few items, make the chunk size such that each job
  # will have 2 chunks
  chunk_size = max(1,min(len(items) / (jobs * 2), chunksize))
  item_chunks = list(chunk(items, chunk_size))
  pass_tokenize_globals = (tokenizer, b_dirs)

  with MapPool(jobs, setup_pass_tokenize, pass_tokenize_globals) as f:
    pass_tokenize_out = f(pass_tokenize, item_chunks)

    doc_count = defaultdict(int)
    chunk_count = len(item_chunks)
    print "chunk size: {0} ({1} chunks)".format(chunk_size, chunk_count)
    print "job count: {0}".format(jobs)

    for i, keycount in enumerate(pass_tokenize_out):
      print "tokenized chunk (%d/%d) [%d keys]" % (i+1,chunk_count, keycount)

  complete = True

  return b_dirs

if __name__ == "__main__":
  parser = argparse.ArgumentParser()
  parser.add_argument("-j","--jobs", type=int, metavar='N', help="spawn N processes (set to 1 for no paralleization)")
  parser.add_argument("-s", "--scanner", metavar='SCANNER', help="use SCANNER for tokenizing")
  parser.add_argument("--buckets", type=int, metavar='N', help="distribute features into N buckets", default=NUM_BUCKETS)
  parser.add_argument("--max_order", type=int, help="highest n-gram order to use")
  parser.add_argument("--word", action='store_true', default=False, help="use 'word' tokenization (currently str.split)")
  parser.add_argument("--chunksize", type=int, help="max chunk size (number of files to tokenize at a time - smaller should reduce memory use)", default=CHUNKSIZE)
  parser.add_argument("-t", "--temp", metavar='TEMP_DIR', help="store buckets in TEMP_DIR instead of in MODEL_DIR/buckets")
  parser.add_argument("model", metavar='MODEL_DIR', help="read index and produce output in MODEL_DIR")

  args = parser.parse_args()

  if args.temp:
    buckets_dir = args.temp
  else:
    buckets_dir = os.path.join(args.model, 'buckets')
  makedir(buckets_dir)

  bucketlist_path = os.path.join(args.model, 'bucketlist')
  index_path = os.path.join(args.model, 'paths')

  # display paths
  print "index path:", index_path
  print "bucketlist path:", bucketlist_path
  print "buckets path:", buckets_dir

  with open(index_path) as f:
    reader = csv.reader(f)
    items = list(reader)

  if sum(map(bool,(args.scanner, args.max_order, args.word))) > 1:
    parser.error('can only specify one of --word, --scanner and --max_order')

  # Tokenize
  print "will tokenize %d files" % len(items)
  if args.scanner:
    from scanner import Scanner
    tokenizer = Scanner.from_file(args.scanner)
    print "using provided scanner: ", args.scanner
  elif args.word:
    tokenizer = str.split
    print "using str.split to tokenize"
  else:
    max_order = args.max_order if args.max_order else MAX_NGRAM_ORDER
    tokenizer = NGramTokenizer(1,max_order)
    print "using n-gram tokenizer: max_order({0})".format(max_order)
  b_dirs = build_index(items, tokenizer, buckets_dir, args.buckets, args.jobs, args.chunksize)

  # output the paths to the buckets
  with open(bucketlist_path,'w') as f:
    for d in b_dirs:
      f.write(d+'\n')


text:
/*
  * $Id: DeleteCriteria.java,v 1.3 2004/05/20 22:37:09 gmartone Exp $
  */
package org.jdbf.engine.criteria;

/**
 *
 * DeleteCriteria represent condition to append
 * to delete statement
 *
 * @author Giovanni Martone

 * @version $Revision: 1.3 $

 * last changed by $Author: gmartone $
 */
public class DeleteCriteria extends Criteria{

    /**
     * Create DeleteCriteria given repositoryViewName
     * @param repositoryName
     */
    public DeleteCriteria(String repositoryName){
        super(repositoryName);
    }
}

/*
 *
 * $Log: DeleteCriteria.java,v $
 * Revision 1.3  2004/05/20 22:37:09  gmartone
 * Changed for task 99073 (Coverage Javadocs)
 *
 *
 */


text:
from time import time
import yaml
import os

class dotdict(dict):
    marker = object()
    def __init__(self, value=None):
        if value is None:
            pass
        elif isinstance(value, dict):
            for key in value:
                self.__setitem__(key, value[key])
        else:
            raise TypeError('expected dict')

    def __setitem__(self, key, value):
        if isinstance(value, dict) and not isinstance(value, dotdict):
            value = dotdict(value)
        super(dotdict, self).__setitem__(key, value)

    def __getitem__(self, key):
        found = self.get(key, dotdict.marker)
        if found is dotdict.marker:
            found = dotdict()
            super(dotdict, self).__setitem__(key, found)
        return found

    __setattr__ = __setitem__
    __getattr__ = __getitem__

target = os.path.dirname(os.path.realpath(__file__)) + "/config.yaml"
with open(target, 'r') as config_file:
    config_yaml = config_file.read()

config = dotdict(yaml.load(config_yaml))

class Timer(object):

    def __init__(self):
        self.val = time()

    def millis(self):
        return round((time() - self.val)*1e3)

    def micros(self):
        return round((time() - self.val)*1e6)

    def set(self, new_value):
        self.val = new_value

    def reset(self):
        self.val = time()


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Orchard.Localization;
using Orchard.Logging;
using Orchard.Mvc;
using Orchard.Mvc.Extensions;
using Orchard.Roles.Models;
using Orchard.Roles.Services;
using Orchard.Roles.ViewModels;
using Orchard.Security;
using Orchard.UI.Notify;

namespace Orchard.Roles.Controllers {
    [ValidateInput(false)]
    public class AdminController : Controller {
        private readonly IRoleService _roleService;
        private readonly IAuthorizationService _authorizationService;

        public AdminController(
            IOrchardServices services,
            IRoleService roleService,
            INotifier notifier,
            IAuthorizationService authorizationService) {
            Services = services;
            _roleService = roleService;
            _authorizationService = authorizationService;

            T = NullLocalizer.Instance;
            Logger = NullLogger.Instance;
        }

        public IOrchardServices Services { get; set; }
        public Localizer T { get; set; }
        public ILogger Logger { get; set; }

        public ActionResult Index() {
            if (!Services.Authorizer.Authorize(Permissions.ManageRoles, T("Not authorized to manage roles")))
                return new HttpUnauthorizedResult();

            var model = new RolesIndexViewModel { Rows = _roleService.GetRoles().OrderBy(r => r.Name).ToList() };

            return View(model);
        }

        [HttpPost, ActionName("Index")]
        public ActionResult IndexPOST() {
            if (!Services.Authorizer.Authorize(Permissions.ManageRoles, T("Not authorized to manage roles")))
                return new HttpUnauthorizedResult();

            foreach (string key in Request.Form.Keys) {
                if (key.StartsWith("Checkbox.") && Request.Form[key] == "true") {
                    int roleId = Convert.ToInt32(key.Substring("Checkbox.".Length));
                    _roleService.DeleteRole(roleId);
                }
            }
            return RedirectToAction("Index");
        }

        public ActionResult Create() {
            if (!Services.Authorizer.Authorize(Permissions.ManageRoles, T("Not authorized to manage roles")))
                return new HttpUnauthorizedResult();

            var model = new RoleCreateViewModel { FeaturePermissions = _roleService.GetInstalledPermissions() };
            return View(model);
        }

        [HttpPost, ActionName("Create")]
        public ActionResult CreatePOST() {
            if (!Services.Authorizer.Authorize(Permissions.ManageRoles, T("Not authorized to manage roles")))
                return new HttpUnauthorizedResult();

            var viewModel = new RoleCreateViewModel();
            TryUpdateModel(viewModel);

            if(String.IsNullOrEmpty(viewModel.Name)) {
                ModelState.AddModelError("Name", T("Role name can't be empty"));
            }

            var role = _roleService.GetRoleByName(viewModel.Name);
            if (role != null) {
                ModelState.AddModelError("Name", T("Role with same name already exists"));
            }

            if (!ModelState.IsValid) {
                viewModel.FeaturePermissions = _roleService.GetInstalledPermissions();
                return View(viewModel);
            }

            _roleService.CreateRole(viewModel.Name);
            foreach (string key in Request.Form.Keys) {
                if (key.StartsWith("Checkbox.") && Request.Form[key] == "true") {
                    string permissionName = key.Substring("Checkbox.".Length);
                    _roleService.CreatePermissionForRole(viewModel.Name,
                                                            permissionName);
                }
            }
            return RedirectToAction("Index");
        }

        public ActionResult Edit(int id) {
            if (!Services.Authorizer.Authorize(Permissions.ManageRoles, T("Not authorized to manage roles")))
                return new HttpUnauthorizedResult();

            var role = _roleService.GetRole(id);
            if (role == null) {
                return HttpNotFound();
            }

            var model = new RoleEditViewModel { Name = role.Name, Id = role.Id,
                                                RoleCategoryPermissions = _roleService.GetInstalledPermissions(),
                                                CurrentPermissions = _roleService.GetPermissionsForRole(id)};

            var simulation = UserSimulation.Create(role.Name);
            model.EffectivePermissions = model.RoleCategoryPermissions
                .SelectMany(group => group.Value)
                .Where(permission => _authorizationService.TryCheckAccess(permission, simulation, null))
                .Select(permission=>permission.Name)
                .Distinct()
                .ToList();

            return View(model);
        }

        [HttpPost, ActionName("Edit")]
        [FormValueRequired("submit.Save")]
        public ActionResult EditSavePOST(int id) {
            if (!Services.Authorizer.Authorize(Permissions.ManageRoles, T("Not authorized to manage roles")))
                return new HttpUnauthorizedResult();

            var viewModel = new RoleEditViewModel();
            TryUpdateModel(viewModel);

            if (String.IsNullOrEmpty(viewModel.Name)) {
                ModelState.AddModelError("Name", T("Role name can't be empty"));
            }

            var role = _roleService.GetRoleByName(viewModel.Name);
            if (role != null && role.Id != id) {
                ModelState.AddModelError("Name", T("Role with same name already exists"));
            }

            if (!ModelState.IsValid) {
                return Edit(id);
            }

            // Save
            List<string> rolePermissions = new List<string>();
            foreach (string key in Request.Form.Keys) {
                if (key.StartsWith("Checkbox.") && Request.Form[key] == "true") {
                    string permissionName = key.Substring("Checkbox.".Length);
                    rolePermissions.Add(permissionName);
                }
            }
            _roleService.UpdateRole(viewModel.Id, viewModel.Name, rolePermissions);

            Services.Notifier.Information(T("Your Role has been saved."));
            return RedirectToAction("Edit", new { id });
        }

        [HttpPost, ActionName("Edit")]
        [FormValueRequired("submit.Delete")]
        public ActionResult EditDeletePOST(int id) {
            return Delete(id, null);
        }

        [HttpPost]
        public ActionResult Delete(int id, string returnUrl) {
            if (!Services.Authorizer.Authorize(Permissions.ManageRoles, T("Not authorized to manage roles")))
                return new HttpUnauthorizedResult();

            _roleService.DeleteRole(id);
            Services.Notifier.Information(T("Role was successfully deleted."));

            return this.RedirectLocal(returnUrl, () => RedirectToAction("Index"));
        }
    }
}