text:
package de.danoeh.antennapod.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import de.danoeh.antennapod.R;
import de.danoeh.antennapod.activity.MainActivity;
import de.danoeh.antennapod.adapter.EpisodeItemListAdapter;
import de.danoeh.antennapod.core.event.DownloadEvent;
import de.danoeh.antennapod.core.event.DownloaderUpdate;
import de.danoeh.antennapod.core.event.FeedItemEvent;
import de.danoeh.antennapod.core.event.PlaybackHistoryEvent;
import de.danoeh.antennapod.core.event.PlaybackPositionEvent;
import de.danoeh.antennapod.core.event.PlayerStatusEvent;
import de.danoeh.antennapod.core.event.UnreadItemsUpdateEvent;
import de.danoeh.antennapod.model.feed.FeedItem;
import de.danoeh.antennapod.core.storage.DBReader;
import de.danoeh.antennapod.core.storage.DBWriter;
import de.danoeh.antennapod.core.util.FeedItemUtil;
import de.danoeh.antennapod.menuhandler.FeedItemMenuHandler;
import de.danoeh.antennapod.view.EmptyViewHandler;
import de.danoeh.antennapod.view.EpisodeItemListRecyclerView;
import de.danoeh.antennapod.view.viewholder.EpisodeItemViewHolder;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

public class PlaybackHistoryFragment extends Fragment implements Toolbar.OnMenuItemClickListener {
    public static final String TAG = "PlaybackHistoryFragment";
    private static final String KEY_UP_ARROW = "up_arrow";

    private List<FeedItem> playbackHistory;
    private PlaybackHistoryListAdapter adapter;
    private Disposable disposable;
    private EpisodeItemListRecyclerView recyclerView;
    private EmptyViewHandler emptyView;
    private ProgressBar progressBar;
    private Toolbar toolbar;
    private boolean displayUpArrow;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.simple_list_fragment, container, false);
        toolbar = root.findViewById(R.id.toolbar);
        toolbar.setTitle(R.string.playback_history_label);
        toolbar.setOnMenuItemClickListener(this);
        displayUpArrow = getParentFragmentManager().getBackStackEntryCount() != 0;
        if (savedInstanceState != null) {
            displayUpArrow = savedInstanceState.getBoolean(KEY_UP_ARROW);
        }
        ((MainActivity) getActivity()).setupToolbarToggle(toolbar, displayUpArrow);
        toolbar.inflateMenu(R.menu.playback_history);
        refreshToolbarState();

        recyclerView = root.findViewById(R.id.recyclerView);
        recyclerView.setRecycledViewPool(((MainActivity) getActivity()).getRecycledViewPool());
        adapter = new PlaybackHistoryListAdapter((MainActivity) getActivity());
        recyclerView.setAdapter(adapter);
        progressBar = root.findViewById(R.id.progLoading);

        emptyView = new EmptyViewHandler(getActivity());
        emptyView.setIcon(R.drawable.ic_history);
        emptyView.setTitle(R.string.no_history_head_label);
        emptyView.setMessage(R.string.no_history_label);
        emptyView.attachToRecyclerView(recyclerView);
        return root;
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
        loadItems();
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
        if (disposable != null) {
            disposable.dispose();
        }
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        outState.putBoolean(KEY_UP_ARROW, displayUpArrow);
        super.onSaveInstanceState(outState);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(FeedItemEvent event) {
        Log.d(TAG, "onEventMainThread() called with: " + "event = [" + event + "]");
        if (playbackHistory == null) {
            return;
        } else if (adapter == null) {
            loadItems();
            return;
        }
        for (int i = 0, size = event.items.size(); i < size; i++) {
            FeedItem item = event.items.get(i);
            int pos = FeedItemUtil.indexOfItemWithId(playbackHistory, item.getId());
            if (pos >= 0) {
                playbackHistory.remove(pos);
                playbackHistory.add(pos, item);
                adapter.notifyItemChangedCompat(pos);
            }
        }
    }

    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DownloadEvent event) {
        Log.d(TAG, "onEventMainThread() called with: " + "event = [" + event + "]");
        DownloaderUpdate update = event.update;
        if (adapter != null && update.mediaIds.length > 0) {
            for (long mediaId : update.mediaIds) {
                int pos = FeedItemUtil.indexOfItemWithMediaId(playbackHistory, mediaId);
                if (pos >= 0) {
                    adapter.notifyItemChangedCompat(pos);
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(PlaybackPositionEvent event) {
        if (adapter != null) {
            for (int i = 0; i < adapter.getItemCount(); i++) {
                EpisodeItemViewHolder holder = (EpisodeItemViewHolder) recyclerView.findViewHolderForAdapterPosition(i);
                if (holder != null && holder.isCurrentlyPlayingItem()) {
                    holder.notifyPlaybackPositionUpdated(event);
                    break;
                }
            }
        }
    }

    public void refreshToolbarState() {
        boolean hasHistory = playbackHistory != null && !playbackHistory.isEmpty();
        toolbar.getMenu().findItem(R.id.clear_history_item).setVisible(hasHistory);
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        if (item.getItemId() == R.id.clear_history_item) {
            DBWriter.clearPlaybackHistory();
            return true;
        }
        return false;
    }

    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
        FeedItem selectedItem = adapter.getLongPressedItem();
        if (selectedItem == null) {
            Log.i(TAG, "Selected item at current position was null, ignoring selection");
            return super.onContextItemSelected(item);
        }
        return FeedItemMenuHandler.onMenuItemClicked(this, item.getItemId(), selectedItem);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onHistoryUpdated(PlaybackHistoryEvent event) {
        loadItems();
        refreshToolbarState();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPlayerStatusChanged(PlayerStatusEvent event) {
        loadItems();
        refreshToolbarState();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUnreadItemsChanged(UnreadItemsUpdateEvent event) {
        loadItems();
        refreshToolbarState();
    }

    private void onFragmentLoaded() {
        adapter.notifyDataSetChanged();
        refreshToolbarState();
    }

    private void loadItems() {
        if (disposable != null) {
            disposable.dispose();
        }
        progressBar.setVisibility(View.VISIBLE);
        emptyView.hide();
        disposable = Observable.fromCallable(this::loadData)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    progressBar.setVisibility(View.GONE);
                    playbackHistory = result;
                    adapter.updateItems(playbackHistory);
                    onFragmentLoaded();
                }, error -> Log.e(TAG, Log.getStackTraceString(error)));
    }

    @NonNull
    private List<FeedItem> loadData() {
        List<FeedItem> history = DBReader.getPlaybackHistory();
        DBReader.loadAdditionalFeedItemListData(history);
        return history;
    }

    private static class PlaybackHistoryListAdapter extends EpisodeItemListAdapter {

        public PlaybackHistoryListAdapter(MainActivity mainActivity) {
            super(mainActivity);
        }

        @Override
        protected void afterBindViewHolder(EpisodeItemViewHolder holder, int pos) {
            // played items shouldn't be transparent for this fragment since, *all* items
            // in this fragment will, by definition, be played. So it serves no purpose and can make
            // it harder to read.
            holder.itemView.setAlpha(1.0f);
        }
    }
}


text:
package models

type CollectionContent struct {
	Completeness float32         `json:"completeness"`
	Count        int             `json:"count"`
	ResourceType string          `json:"resourceType"`
	Links        map[string]Link `json:"links"`
	Id           string          `json:"id"`
}

redpajama_set_name: RedPajamaGithub


text:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace Systran.GeographicClientLib.Model
{

    /// <summary>
    ///
    /// </summary>
    [DataContract]
    public class DestinationDetailsResponse
    {

        /* Error at request level */
        [DataMember(Name = "error", EmitDefaultValue = false)]
        public ErrorResponse Error { get; set; }

        /* Full destination data */
        [DataMember(Name = "result", EmitDefaultValue = false)]
        public FullDestination Result { get; set; }

        /// <summary>
        /// Get the string presentation of the object
        /// </summary>
        /// <returns>String presentation of the object</returns>
        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.Append("class DestinationDetailsResponse {\n");

            sb.Append("  Error: ").Append(Error).Append("\n");

            sb.Append("  Result: ").Append(Result).Append("\n");

            sb.Append("}\n");
            return sb.ToString();
        }

        /// <summary>
        /// Get the JSON string presentation of the object
        /// </summary>
        /// <returns>JSON string presentation of the object</returns>
        public string ToJson()
        {
            return JsonConvert.SerializeObject(this, Formatting.Indented);
        }

    }

}


text:
require 'test_helper'

class TermsControllerTest < ActionDispatch::IntegrationTest

  context "as admin" do
    setup do
      @admin_user = create(:user)
      log_user_in(@admin_user)
    end

    should "be able to create term" do

      assert_difference "Term.count", 1 do
        attrs = attributes_for(:term)
        post terms_path, params: { term: attrs }
      end

      assert_redirected_to term_path(assigns(:term))
    end

    should "be able to edit" do
       term = create(:term)
       term.name = "woot"

       patch term_path(term), params: { term: { name: term.name, start_date: term.start_date, end_date: term.end_date } }
       assert_redirected_to term_path(term)
       t = Term.find(term.id)
       assert_equal "woot", t.name
    end

    should "be able to destroy" do
      term = create(:term)
      assert_difference "Term.count", -1 do
        delete term_path(term)
      end
    end

    should "show term and list all courses alphabetically" do
      term = create(:term)
      create(:course, title: "a", term: term)
      create(:course, title: "x", term: term)

       get term_path(term)
       term = assigns(:term)
       assert term
       assert_equal term.courses.size, 2
       assert_equal term.courses.first.title, "a"
       assert_equal term.courses.last.title, "x"
    end

    should "show all active and last 10 archived terms" do
      create_list(:term, 10)
      create_list(:term, 20, end_date: Date.today - 2.months, start_date: Date.today - 1.year)

      get terms_path

      assert_response :success
      terms = assigns(:terms)
      archived_terms = assigns(:archived_terms)

      assert terms, "terms can't be null"
      assert archived_terms, "archived terms can't be null"

      assert_equal 10, terms.size, "Active terms should show all"
      assert_equal 10, archived_terms.size, "Archived should only show max 10"

    end

    should "not return courses if the term is expired when searching" do
      term = create(:term, name: "expired", start_date: Date.today - 1.year, end_date:  Date.today - 2.months)
      create(:course, title: "search for me", term: term)

      get  search_courses_terms_path, params: { q: "search" }

      assert_response :success
      courses = assigns(:courses)
      assert_equal 0, courses.size

    end

  end

end


text:
package com.opengamma.strata.function.calculation.rate;

import static com.opengamma.strata.collect.Guavate.toImmutableMap;

import java.util.Set;
import java.util.function.Function;

import com.google.common.collect.ImmutableMap;
import com.opengamma.strata.basics.currency.Currency;
import com.opengamma.strata.basics.index.Index;
import com.opengamma.strata.engine.marketdata.SingleCalculationMarketData;
import com.opengamma.strata.market.curve.NodalCurve;
import com.opengamma.strata.market.key.IndexRateKey;
import com.opengamma.strata.pricer.rate.ImmutableRatesProvider;
import com.opengamma.strata.pricer.rate.RatesProvider;

/**
 * Utilities for manipulating market data.
 */
public final class MarketDataUtils {

  /**
   * Restricted constructor.
   */
  private MarketDataUtils() {
  }

  //-------------------------------------------------------------------------
  /**
   * Creates a rates provider from a set of market data containing a single discounting curve,
   * and forward curves and fixing series for a given set of indices.
   * All curves are overridden by a given replacement.
   *
   * @param marketData  the market data
   * @param currency  the currency of the discounting curve
   * @param indices  the indices
   * @param curveOverride  the curve override
   * @return the rates provider
   */
  public static RatesProvider toSingleCurveRatesProvider(
      SingleCalculationMarketData marketData,
      Currency currency,
      Set<? extends Index> indices,
      NodalCurve curveOverride) {

    // TODO - we should be able to replace curves more easily than having to pick out all the
    // market data into a new rates provider.

    return ImmutableRatesProvider.builder()
        .valuationDate(marketData.getValuationDate())
        .discountCurves(ImmutableMap.of(currency, curveOverride))
        .indexCurves(indices.stream()
            .collect(toImmutableMap(Function.identity(), k -> curveOverride)))
        .timeSeries(indices.stream()
            .collect(toImmutableMap(Function.identity(), k -> marketData.getTimeSeries(IndexRateKey.of(k)))))
        .build();
  }

}


text:
<?php

namespace ApplicationTest\Service;

use Application\Model\Geoname;
use Application\Model\Questionnaire;
use Application\Model\Survey;
use Application\Service\Hydrator;

/**
 * @group Service
 */
class HydratorTest extends \ApplicationTest\Controller\AbstractController
{

    /**
     * @var \Application\Model\Question\Choice
     */
    private $choice1;

    /**
     * @var \Application\Model\Question\Choice
     */
    private $choice2;

    /**
     * @var Hydrator
     */
    private $hydrator;

    public function setUp()
    {
        parent::setUp();

        $this->user = new \Application\Model\User('John');
        $this->choice1 = new \Application\Model\Question\Choice();
        $this->choice2 = new \Application\Model\Question\Choice();

        // Create a stub for the Hydrator class with predetermined values, so we don't have to mess with database
        $this->hydrator = $this->getMock('\Application\Service\Hydrator', ['getObject'], [], '', false);
        $this->hydrator->expects($this->any())
                ->method('getObject')
                ->will($this->returnValueMap([
                            [\Application\Model\Question\Choice::class, 1, $this->choice1],
                            [\Application\Model\Question\Choice::class, 2, $this->choice2],
        ]));
    }

    public function testDot()
    {
        $closure = function () {
            return 123;
        };

        $actual = $this->hydrator->initializePropertyStructure([
            'name',
            'subobject',
            'subobject.name',
            'subobject.subsubobject.name',
            'othersub.name',
            'closure' => $closure,
            'children.__recursive',
            'new1.new2.new3.new4', // new object, not referenced before, should not have any issue
        ]);

        $expected = [
            'name',
            'subobject' => [
                'name',
                'subsubobject' => [
                    'name',
                ],
            ],
            'othersub' => [
                'name',
            ],
            'closure' => $closure,
            'children' => '__recursive',
            'new1' => [
                'new2' => [
                    'new3' => [
                        'new4',
                    ],
                ],
            ],
        ];

        $this->assertEquals($expected, $actual);
    }

    public function testMetadata()
    {
        $in = [
            'metadata',
            'creator.gravatar',
        ];
        $expected = [
            'dateCreated',
            'dateModified',
            'creator' => [
                'gravatar',
            ],
            3 => 'modifier',
        ];

        $actual = $this->hydrator->initializePropertyStructure($in);
        $this->assertEquals($expected, $actual);
    }

    public function testCanHydrateAndExtract()
    {
        $data = [
            'name' => 'John Connor',
            'email' => 'john.connor@skynet.net',
            'state' => null,
            'lastLogin' => '1997-08-29T01:02:03+0000',
        ];

        $this->hydrator->hydrate($data, $this->user);

        $this->assertEquals($data['name'], $this->user->getName());
        $this->assertEquals($data['email'], $this->user->getEmail());

        $actual = $this->hydrator->extract($this->user, ['name', 'email']);
        unset($actual['id']);
        $this->assertEquals($data, $actual, 'it must be exactly same as input, except the id');
    }

    public function testCanHydrateAndExtractJSONproperty()
    {
        $data = [
            'alternateNames' => [
                123 => 'alternate 1',
                456 => 'alternate 2',
            ],
        ];

        $question = new \Application\Model\Question\NumericQuestion('tst question');
        $this->assertEquals(\Application\Model\Question\AbstractQuestion::EMPTY_ASSOCIATIVE_ARRAY, $question->getAlternateNames());

        $this->hydrator->hydrate($data, $question);
        $this->assertEquals($data['alternateNames'], $question->getAlternateNames());

        $actual = $this->hydrator->extract($question, ['alternateNames']);
        $this->assertEquals($data['alternateNames'], $actual['alternateNames'], 'it must be exactly same as input');
    }

    public function testDoesNotModifySubobject()
    {
        $survey = new Survey('original name');
        $questionnaire = new \Application\Model\Questionnaire();
        $questionnaire->setSurvey($survey);

        $data = [
//            'comments' => 'some comments',
            'survey' => [
                'id' => 12345,
                'name' => 'this should not overwrite the original name',
            ],
        ];

        // Create a stub for the \Application\Service\Hydrator class, so we don't have to mess with database
        $mockHydrator = $this->getMock('\Application\Service\Hydrator', ['getObject'], [], '', false);
        $mockHydrator->expects($this->any())
                ->method('getObject')
                ->will($this->returnValue($survey));

        $mockHydrator->hydrate($data, $questionnaire);
        $this->assertEquals('original name', $survey->getName());
    }

    public function testHydrateUnknownPropertiesFailSilently()
    {
        $data = [
            'foo' => 'bar',
            'name' => 'John Connor',
        ];

        $this->hydrator->hydrate($data, $this->user);
        $this->assertEquals($data['name'], $this->user->getName());
        $this->assertArrayNotHasKey('foo', $this->hydrator->extract($this->user, ['foo']));
    }

    public function testSensitivePropertiesCannotBeHydrated()
    {
        $data = [
            'id' => 12345,
            'password' => 'foo',
            'activationToken' => 'foo',
        ];

        $this->hydrator->hydrate($data, $this->user);
        $this->assertNull($this->user->getId());
        $this->assertNull($this->user->getPassword());
    }

    public function testSensitivePropertiesCannotBeExtracted()
    {
        $data = [
            'password',
            'activationToken',
        ];

        $this->assertArrayNotHasKey('password', $this->hydrator->extract($this->user, $data));
        $this->assertArrayNotHasKey('activationToken', $this->hydrator->extract($this->user, $data));
    }

    public function testExtractArray()
    {
        $user2 = clone $this->user;
        $user2->setName('Bob');

        $this->assertEquals([
            0 => [
                'id' => null,
                'name' => 'John',
                'email' => null,
                'state' => 0,
                'lastLogin' => null,
            ],
            1 => [
                'id' => null,
                'name' => 'Bob',
                'email' => null,
                'state' => 0,
                'lastLogin' => null,
            ],
        ], $this->hydrator->extractArray([$this->user, $user2], ['name']));
    }

    public function testCanHydrateCollectionExistingInDatabase()
    {
        $choices = new \Doctrine\Common\Collections\ArrayCollection();
        $choices->add($this->choice1);
        $choices->add($this->choice2);
        $question = new \Application\Model\Question\ChoiceQuestion();

        $data = [
            'name' => 'What is your name ?',
            'choices' => [
                1,
                2,
            ],
        ];
        $this->hydrator->hydrate($data, $question);

        $this->assertEquals($choices, $question->getChoices(), 'question should have the two new choices');
    }

    public function testExtractSubObject()
    {
        $questionnaire = new \Application\Model\Questionnaire('filter 1');
        $questionnaire->setComments('test comments');
        $survey = new \Application\Model\Survey('test survey');
        $survey->setCode('tst');
        $questionnaire->setSurvey($survey);
        $questionnaire->setGeoname(new Geoname('test geoname'));

        $this->assertEquals([
            'id' => null,
            'name' => 'tst - test geoname',
            'comments' => 'test comments',
            'status' => 'new',
            'survey' => [
                'id' => null,
                'name' => 'test survey',
                'code' => 'tst',
                'isActive' => false,
                'year' => null,
                'dateStart' => null,
                'dateEnd' => null,
            ],
                ], $this->hydrator->extract($questionnaire, [
                    'comments',
                    'survey' => ['name'],
                    'unkown properties' => ['foo', 'bar'],
                ]), 'should return subobject, but only known one');
    }

    /**
     * @test
     */
    public function extractSurveyWithPropertyQuestionnairesAndCheckResultContainsKeyQuestionnaires()
    {
        $actual = $this->hydrator->extract($this->getFakeSurvey(), ['name', 'questionnaires']);
        $this->assertArrayHasKey('questionnaires', $actual);
    }

    /**
     * @test
     */
    public function extractSurveyWithPropertyQuestionnairesAndQuestionnairesNameAndCheckResultContainsKeyQuestionnairesName()
    {
        $actual = $this->hydrator->extract($this->getFakeSurvey(), ['name', 'questionnaires', 'questionnaires.name']);
        $this->assertInternalType('array', $actual['questionnaires']);
        $this->assertNotEmpty($actual['questionnaires']);
    }

    public function testExtractSubObjects()
    {
        $filter1 = new \Application\Model\Filter('filter 1');
        $filter2 = new \Application\Model\Filter('filter 2');
        $filter1->addChild($filter2);

        $this->assertEquals([
            'id' => null,
            'name' => 'filter 1',
            'children' => [
                [
                    'id' => null,
                    'name' => 'filter 2',
                ],
            ],
                ], $this->hydrator->extract($filter1, [
                    'name',
                    'children' => ['name'],
                ]), 'should return array of subobjects, but only known ones');
    }

    public function testExtractSubObjectWithRecursiveConfiguration()
    {
        $filter1 = new \Application\Model\Filter('filter 1');
        $filter2 = new \Application\Model\Filter('filter 2');
        $filter1->addChild($filter2);

        $expected = [
            'id' => null,
            'name' => 'filter 1',
            'color' => $filter1->getColor(),
            'children' => [
                [
                    'id' => null,
                    'name' => 'filter 2',
                    'color' => $filter2->getColor(),
                    'children' => [],
                ],
            ],
        ];

        $this->assertEquals($expected, $this->hydrator->extract($filter1, [
                    'color',
                    'children' => '__recursive',
                ]), 'should return same properties for children and parent');
    }

    public function testExtractBooleanProperty()
    {
        $filter1 = new \Application\Model\Filter('filter 1');
        $filter1->setColor('c0ffee');

        $this->assertEquals([
            'id' => null,
            'name' => 'filter 1',
            'color' => 'c0ffee',
                ], $this->hydrator->extract($filter1, [
                    'color',
                ]), 'should use correct getter for boolean properties');
    }

    public function testExtractWithClosure()
    {
        $this->assertEquals([
            'id' => null,
            'name' => 'John',
            'email' => null,
            'state' => 0,
            'lastLogin' => null,
            'custom name' => 'Mr. John Connor',
                ], $this->hydrator->extract($this->user, [
                    'custom name' => function (Hydrator $hydrator, \Application\Model\User $user) {
                        return 'Mr. ' . $user->getName() . ' Connor';
                    },
                ]), 'should allow custom properties via Closure');
    }

    public function testExtractDateTimeAsString()
    {
        $this->user->timestampCreation();
        $this->assertEquals([
            'id' => null,
            'email' => null,
            'state' => 0,
            'lastLogin' => null,
            'dateCreated' => $this->user->getDateCreated()->format(\DateTime::ISO8601),
            'name' => 'John',
                ], $this->hydrator->extract($this->user, [
                    'dateCreated',
                ]), 'should serialize DateTime');
    }

    public function testHydrateAssociationWithSuboject()
    {
        $questionnaire = new \Application\Model\Questionnaire();
        $survey = new \Application\Model\Survey('test survey');

        // Create a stub for the \Application\Service\Hydrator class, so we don't have to mess with database
        $mockHydrator = $this->getMock('\Application\Service\Hydrator', ['getObject'], [], '', false);
        $mockHydrator->expects($this->any())
                ->method('getObject')
                ->will($this->returnValue($survey));

        $mockHydrator->hydrate([
            'survey' => [
                'id' => 12345,
                'name' => 'name that should not be hydrated',
            ],
                ], $questionnaire);
        $this->assertEquals($survey, $questionnaire->getSurvey(), 'can set subobject');

        $questionnaire = new \Application\Model\Questionnaire();
        $this->assertNull($questionnaire->getSurvey());
        $mockHydrator->hydrate(['survey' => 12345], $questionnaire);
        $this->assertEquals($survey, $questionnaire->getSurvey(), 'can also use short syntax with only ID');
        $this->assertEquals('test survey', $questionnaire->getSurvey()->getName(), 'properties of subobject should never be modified');
    }

    public function testCanHydrateBoolean()
    {
        $chapter = new \Application\Model\Question\Chapter();
        $this->assertFalse($chapter->isFinal(), 'default is false');

        $this->hydrator->hydrate(['isFinal' => true], $chapter);
        $this->assertTrue($chapter->isFinal(), 'can set to true');

        $this->hydrator->hydrate(['isFinal' => false], $chapter);
        $this->assertFalse($chapter->isFinal(), 'can set to true');

        $this->hydrator->hydrate(['isFinal' => '1'], $chapter);
        $this->assertTrue($chapter->isFinal(), 'can set to 1');

        $this->hydrator->hydrate(['isFinal' => '0'], $chapter);
        $this->assertFalse($chapter->isFinal(), 'can set to 0');
    }

    public function testCanExtractBoolean()
    {
        $chapter = new \Application\Model\Question\Chapter();

        $actual = $this->hydrator->extract($chapter, ['isFinal']);
        $this->assertArrayHasKey('isFinal', $actual);
        $this->assertFalse($actual['isFinal']);
    }

    public function testCanExtractNonBooleanStartingWithIs()
    {
        $geoname = new \Application\Model\Geoname();
        $geoname->setIso3('abc');

        $actual = $this->hydrator->extract($geoname, ['iso3']);
        $this->assertArrayHasKey('iso3', $actual);
        $this->assertEquals($geoname->getIso3(), $actual['iso3']);
    }

    /**
     * Return a fake survey for the sake of the test.
     *
     * @return Survey
     */
    private function getFakeSurvey()
    {
        $survey = new Survey('test survey');
        $survey->setIsActive(true);
        $survey->setCode('code test survey');
        $survey->setYear(2010);

        $geoname = new Geoname('test geoname');

        $questionnaire = new Questionnaire();
        $questionnaire->setSurvey($survey);
        $questionnaire->setDateObservationStart(new \DateTime('2010-01-01T00:00:00+0100'));
        $questionnaire->setDateObservationEnd(new \DateTime('2011-01-01T00:00:00+0100'));
        $questionnaire->setGeoname($geoname);

        return $survey;
    }
}


text:
package com.ittianyu.pocenter.common.utils;

import android.content.Context;
import android.content.SharedPreferences;

/**
 * Created by yu.
 * read and write config utils
 */
public class ConfigUtils {
    private static final String NAME = "config";

    public static final String KEY_TYPE = "type";

    /**
     * Put a key-value into config
     * @param context context
     * @param key the key
     * @param value the value
     */
    public static void putString(Context context, String key, String value) {
        SharedPreferences sp = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString(key, value)
                .commit();
    }

    /**
     * Get value by key in config
     * @param context context
     * @param key the key
     * @param defaultValue if can't find the value of key, will return default value
     * @return value
     */
    public static String getString(Context context, String key, String defaultValue) {
        SharedPreferences sp = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
        return sp.getString(key, defaultValue);
    }

    /**
     * Put a key-value into config
     * @param context context
     * @param key the key
     * @param value the value
     */
    public static void putInt(Context context, String key, int value) {
        SharedPreferences sp = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putInt(key, value)
                .commit();
    }

    /**
     * Get value by key in config
     * @param context context
     * @param key the key
     * @param defaultValue if can't find the value of key, will return default value
     * @return value
     */
    public static int getInt(Context context, String key, int defaultValue) {
        SharedPreferences sp = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
        return sp.getInt(key, defaultValue);
    }

}


text:
author: jerome
tags: [WeeklyWiki, Projet]
imagefeature: https://wiki.fablab-lannion.org/images/f/fa/Aquarium_dessin.png
layout: post
slug: WeeklyWiki-2-Projet-AquaMarium
date: 2018-11-24
title: "Projet: AquaMarium"
comments: True
---

Réalisation d'un aquarium à marée, voici l'AquaMarium v1. Projet récompensé lors du défi Data+ en 2015.

Chaque semaine, le Fablab vous propose de (re)découvrir une page du [Wiki](https://wiki.fablab-lannion.org). Cela peut être un projet documenté, une formation ou une page consacrée à l'organisation.

Cet aquarium, un peu particulier, vous permet de voir la hauteur d'eau d'un port en temps réel. Équivalent à une horloge à marée, mais beaucoup plus visuel, il a été réalisé lors du défunt Défi Data+.

Projet estampillé Fablab, de nombreuses bonnes volontés se sont regroupées pour y participer : Philippe, Anatole, Yann ou encore Jérôme.

Il a aussi donné naissance à une autre projet, une [pompe péristaltique](https://wiki.fablab-lannion.org/index.php?title=Pompe_P%C3%A9ristaltique) qui permet de déplacer du liquide sans qu'aucune partie de la pompe ne soit en contact avec celui-ci.

Ces pages ne vivent que grâce à nous/vous. Tout le monde est grandement incité à les commenter, voir les corriger !

Bien sur, vous retrouverez tous les détails et plus encore dans notre Wiki : [AquaMarium](https://wiki.fablab-lannion.org/index.php?title=AquaMarium)

À la semaine prochaine, et n'oubliez pas de documenter vos projets !


text:
Reports methods whose body contains a single synchronized statement.
A lock expression for this synchronized statement must be equal to
this for instance methods or [ClassName].class for static methods.

  To improve readability of such methods,
  you can remove the synchronized wrapper and mark the method as synchronized.

Example:

  public int generateInt(int x) {
    synchronized (this) {
      return 1;
    }
  }

After the quick-fix is applied:

  public synchronized int generateInt(int x) {
    return 1;
  }


text:
namespace v8 {
namespace internal {

// Public V8 debugger API message handler function. This function just delegates
// to the debugger agent through it's data parameter.
void DebuggerAgentMessageHandler(const v8::Debug::Message& message) {
  DebuggerAgent* agent = Isolate::Current()->debugger_agent_instance();
  ASSERT(agent != NULL);
  agent->DebuggerMessage(message);
}

// Debugger agent main thread.
void DebuggerAgent::Run() {
  const int kOneSecondInMicros = 1000000;

  // Allow this socket to reuse port even if still in TIME_WAIT.
  server_->SetReuseAddress(true);

  // First bind the socket to the requested port.
  bool bound = false;
  while (!bound && !terminate_) {
    bound = server_->Bind(port_);

    // If an error occurred wait a bit before retrying. The most common error
    // would be that the port is already in use so this avoids a busy loop and
    // make the agent take over the port when it becomes free.
    if (!bound) {
      PrintF("Failed to open socket on port %d, "
          "waiting %d ms before retrying\n", port_, kOneSecondInMicros / 1000);
      terminate_now_->Wait(kOneSecondInMicros);
    }
  }

  // Accept connections on the bound port.
  while (!terminate_) {
    bool ok = server_->Listen(1);
    listening_->Signal();
    if (ok) {
      // Accept the new connection.
      Socket* client = server_->Accept();
      ok = client != NULL;
      if (ok) {
        // Create and start a new session.
        CreateSession(client);
      }
    }
  }
}

void DebuggerAgent::Shutdown() {
  // Set the termination flag.
  terminate_ = true;

  // Signal termination and make the server exit either its listen call or its
  // binding loop. This makes sure that no new sessions can be established.
  terminate_now_->Signal();
  server_->Shutdown();
  Join();

  // Close existing session if any.
  CloseSession();
}

void DebuggerAgent::WaitUntilListening() {
  listening_->Wait();
}

static const char* kCreateSessionMessage =
    "Remote debugging session already active\r\n";

void DebuggerAgent::CreateSession(Socket* client) {
  ScopedLock with(session_access_);

  // If another session is already established terminate this one.
  if (session_ != NULL) {
    client->Send(kCreateSessionMessage, StrLength(kCreateSessionMessage));
    delete client;
    return;
  }

  // Create a new session and hook up the debug message handler.
  session_ = new DebuggerAgentSession(this, client);
  isolate_->debugger()->SetMessageHandler(DebuggerAgentMessageHandler);
  session_->Start();
}

void DebuggerAgent::CloseSession() {
  ScopedLock with(session_access_);

  // Terminate the session.
  if (session_ != NULL) {
    session_->Shutdown();
    session_->Join();
    delete session_;
    session_ = NULL;
  }
}

void DebuggerAgent::DebuggerMessage(const v8::Debug::Message& message) {
  ScopedLock with(session_access_);

  // Forward the message handling to the session.
  if (session_ != NULL) {
    v8::String::Value val(message.GetJSON());
    session_->DebuggerMessage(Vector<uint16_t>(const_cast<uint16_t*>(*val),
                              val.length()));
  }
}

void DebuggerAgent::OnSessionClosed(DebuggerAgentSession* session) {
  // Don't do anything during termination.
  if (terminate_) {
    return;
  }

  // Terminate the session.
  ScopedLock with(session_access_);
  ASSERT(session == session_);
  if (session == session_) {
    session_->Shutdown();
    delete session_;
    session_ = NULL;
  }
}

void DebuggerAgentSession::Run() {
  // Send the hello message.
  bool ok = DebuggerAgentUtil::SendConnectMessage(client_, *agent_->name_);
  if (!ok) return;

  while (true) {
    // Read data from the debugger front end.
    SmartArrayPointer<char> message =
        DebuggerAgentUtil::ReceiveMessage(client_);

    const char* msg = *message;
    bool is_closing_session = (msg == NULL);

    if (msg == NULL) {
      // If we lost the connection, then simulate a disconnect msg:
      msg = "{\"seq\":1,\"type\":\"request\",\"command\":\"disconnect\"}";

    } else {
      // Check if we're getting a disconnect request:
      const char* disconnectRequestStr =
          "\"type\":\"request\",\"command\":\"disconnect\"}";
      const char* result = strstr(msg, disconnectRequestStr);
      if (result != NULL) {
        is_closing_session = true;
      }
    }

    // Convert UTF-8 to UTF-16.
    unibrow::Utf8InputBuffer<> buf(msg, StrLength(msg));
    int len = 0;
    while (buf.has_more()) {
      buf.GetNext();
      len++;
    }
    ScopedVector<int16_t> temp(len + 1);
    buf.Reset(msg, StrLength(msg));
    for (int i = 0; i < len; i++) {
      temp[i] = buf.GetNext();
    }

    // Send the request received to the debugger.
    v8::Debug::SendCommand(reinterpret_cast<const uint16_t *>(temp.start()),
                           len,
                           NULL,
                           reinterpret_cast<v8::Isolate*>(agent_->isolate()));

    if (is_closing_session) {
      // Session is closed.
      agent_->OnSessionClosed(this);
      return;
    }
  }
}

void DebuggerAgentSession::DebuggerMessage(Vector<uint16_t> message) {
  DebuggerAgentUtil::SendMessage(client_, message);
}

void DebuggerAgentSession::Shutdown() {
  // Shutdown the socket to end the blocking receive.
  client_->Shutdown();
}

const char* const DebuggerAgentUtil::kContentLength = "Content-Length";

SmartArrayPointer<char> DebuggerAgentUtil::ReceiveMessage(const Socket* conn) {
  int received;

  // Read header.
  int content_length = 0;
  while (true) {
    const int kHeaderBufferSize = 80;
    char header_buffer[kHeaderBufferSize];
    int header_buffer_position = 0;
    char c = '\0';  // One character receive buffer.
    char prev_c = '\0';  // Previous character.

    // Read until CRLF.
    while (!(c == '\n' && prev_c == '\r')) {
      prev_c = c;
      received = conn->Receive(&c, 1);
      if (received == 0) {
        PrintF("Error %d\n", Socket::LastError());
        return SmartArrayPointer<char>();
      }

      // Add character to header buffer.
      if (header_buffer_position < kHeaderBufferSize) {
        header_buffer[header_buffer_position++] = c;
      }
    }

    // Check for end of header (empty header line).
    if (header_buffer_position == 2) {  // Receive buffer contains CRLF.
      break;
    }

    // Terminate header.
    ASSERT(header_buffer_position > 1);  // At least CRLF is received.
    ASSERT(header_buffer_position <= kHeaderBufferSize);
    header_buffer[header_buffer_position - 2] = '\0';

    // Split header.
    char* key = header_buffer;
    char* value = NULL;
    for (int i = 0; header_buffer[i] != '\0'; i++) {
      if (header_buffer[i] == ':') {
        header_buffer[i] = '\0';
        value = header_buffer + i + 1;
        while (*value == ' ') {
          value++;
        }
        break;
      }
    }

    // Check that key is Content-Length.
    if (strcmp(key, kContentLength) == 0) {
      // Get the content length value if present and within a sensible range.
      if (value == NULL || strlen(value) > 7) {
        return SmartArrayPointer<char>();
      }
      for (int i = 0; value[i] != '\0'; i++) {
        // Bail out if illegal data.
        if (value[i] < '0' || value[i] > '9') {
          return SmartArrayPointer<char>();
        }
        content_length = 10 * content_length + (value[i] - '0');
      }
    } else {
      // For now just print all other headers than Content-Length.
      PrintF("%s: %s\n", key, value != NULL ? value : "(no value)");
    }
  }

  // Return now if no body.
  if (content_length == 0) {
    return SmartArrayPointer<char>();
  }

  // Read body.
  char* buffer = NewArray<char>(content_length + 1);
  received = ReceiveAll(conn, buffer, content_length);
  if (received < content_length) {
    PrintF("Error %d\n", Socket::LastError());
    return SmartArrayPointer<char>();
  }
  buffer[content_length] = '\0';

  return SmartArrayPointer<char>(buffer);
}

bool DebuggerAgentUtil::SendConnectMessage(const Socket* conn,
                                           const char* embedding_host) {
  static const int kBufferSize = 80;
  char buffer[kBufferSize];  // Sending buffer.
  bool ok;
  int len;

  // Send the header.
  len = OS::SNPrintF(Vector<char>(buffer, kBufferSize),
                     "Type: connect\r\n");
  ok = conn->Send(buffer, len);
  if (!ok) return false;

  len = OS::SNPrintF(Vector<char>(buffer, kBufferSize),
                     "V8-Version: %s\r\n", v8::V8::GetVersion());
  ok = conn->Send(buffer, len);
  if (!ok) return false;

  len = OS::SNPrintF(Vector<char>(buffer, kBufferSize),
                     "Protocol-Version: 1\r\n");
  ok = conn->Send(buffer, len);
  if (!ok) return false;

  if (embedding_host != NULL) {
    len = OS::SNPrintF(Vector<char>(buffer, kBufferSize),
                       "Embedding-Host: %s\r\n", embedding_host);
    ok = conn->Send(buffer, len);
    if (!ok) return false;
  }

  len = OS::SNPrintF(Vector<char>(buffer, kBufferSize),
                     "%s: 0\r\n", kContentLength);
  ok = conn->Send(buffer, len);
  if (!ok) return false;

  // Terminate header with empty line.
  len = OS::SNPrintF(Vector<char>(buffer, kBufferSize), "\r\n");
  ok = conn->Send(buffer, len);
  if (!ok) return false;

  // No body for connect message.

  return true;
}

bool DebuggerAgentUtil::SendMessage(const Socket* conn,
                                    const Vector<uint16_t> message) {
  static const int kBufferSize = 80;
  char buffer[kBufferSize];  // Sending buffer both for header and body.

  // Calculate the message size in UTF-8 encoding.
  int utf8_len = 0;
  int previous = unibrow::Utf16::kNoPreviousCharacter;
  for (int i = 0; i < message.length(); i++) {
    uint16_t character = message[i];
    utf8_len += unibrow::Utf8::Length(character, previous);
    previous = character;
  }

  // Send the header.
  int len;
  len = OS::SNPrintF(Vector<char>(buffer, kBufferSize),
                     "%s: %d\r\n", kContentLength, utf8_len);
  conn->Send(buffer, len);

  // Terminate header with empty line.
  len = OS::SNPrintF(Vector<char>(buffer, kBufferSize), "\r\n");
  conn->Send(buffer, len);

  // Send message body as UTF-8.
  int buffer_position = 0;  // Current buffer position.
  previous = unibrow::Utf16::kNoPreviousCharacter;
  for (int i = 0; i < message.length(); i++) {
    // Write next UTF-8 encoded character to buffer.
    uint16_t character = message[i];
    buffer_position +=
        unibrow::Utf8::Encode(buffer + buffer_position, character, previous);
    ASSERT(buffer_position <= kBufferSize);

    // Send buffer if full or last character is encoded.
    if (kBufferSize - buffer_position <
          unibrow::Utf16::kMaxExtraUtf8BytesForOneUtf16CodeUnit ||
        i == message.length() - 1) {
      if (unibrow::Utf16::IsLeadSurrogate(character)) {
        const int kEncodedSurrogateLength =
            unibrow::Utf16::kUtf8BytesToCodeASurrogate;
        ASSERT(buffer_position >= kEncodedSurrogateLength);
        conn->Send(buffer, buffer_position - kEncodedSurrogateLength);
        for (int i = 0; i < kEncodedSurrogateLength; i++) {
          buffer[i] = buffer[buffer_position + i];
        }
        buffer_position = kEncodedSurrogateLength;
      } else {
        conn->Send(buffer, buffer_position);
        buffer_position = 0;
      }
    }
    previous = character;
  }

  return true;
}

bool DebuggerAgentUtil::SendMessage(const Socket* conn,
                                    const v8::Handle<v8::String> request) {
  static const int kBufferSize = 80;
  char buffer[kBufferSize];  // Sending buffer both for header and body.

  // Convert the request to UTF-8 encoding.
  v8::String::Utf8Value utf8_request(request);

  // Send the header.
  int len;
  len = OS::SNPrintF(Vector<char>(buffer, kBufferSize),
                     "Content-Length: %d\r\n", utf8_request.length());
  conn->Send(buffer, len);

  // Terminate header with empty line.
  len = OS::SNPrintF(Vector<char>(buffer, kBufferSize), "\r\n");
  conn->Send(buffer, len);

  // Send message body as UTF-8.
  conn->Send(*utf8_request, utf8_request.length());

  return true;
}

// Receive the full buffer before returning unless an error occours.
int DebuggerAgentUtil::ReceiveAll(const Socket* conn, char* data, int len) {
  int total_received = 0;
  while (total_received < len) {
    int received = conn->Receive(data + total_received, len - total_received);
    if (received == 0) {
      return total_received;
    }
    total_received += received;
  }
  return total_received;
}

} }  // namespace v8::internal

#endif  // ENABLE_DEBUGGER_SUPPORT


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddTaxIdFromProductProviderTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('product_providers', function(Blueprint $table){
            $table->dropColumn('taxes');
        });

        Schema::table('products', function(Blueprint $table){
            $table->dropColumn('taxes');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
}


text:
1.0.4 / 2014-09-02
==================

 * Added serf agent and supervisor scripts

1.0.3 / 2014-08-26
==================

 * Version bump in Dockerfile
 * Fixed echo CMD statement

1.0.2 / 2014-08-26
==================

 * Updated packages, removed some packages, added some packages. All in all it is 200MB less ;)

1.0.1 / 2014-08-23
==================

 * Added more details in README and some links to more infos

1.0.0 / 2014-08-23
==================

 * Moved to seperate repo. Added envsubst to base packages
 * Initial commit


text:
using System;

namespace DbFriend.Core.Generator.Targets
{
    public interface IDbObjectStreamWriterAdapter : IDisposable
    {
        string Write();
    }
}


text:
                    event.title

                         dfgsd

                        dfgsd

                        dfgsd

                        dfgsd

    <md-divider></md-divider>

        <md-button ng-repeat="tag in [1,2,3]" style="cursor: default;border-radius: 5px;font-size:12px;float: left;box-sizing:border-box;max-width: 100%;position: relative;background-color:rgb(224, 224, 224);color: rgb(66,66,66);"> {{tag.name}}</md-button>

    <md-divider></md-divider>

                    {{event.title}}

                        {{event.subtitle}}
                <md-list layout="column" layout-align="start start">
                    <md-list-item layout="row">
                        <md-icon md-svg-icon="calendar-clock" class=" grey-text" aria-label="Alarm Icon"></md-icon>

                                    {{event.timings.from.date | date: ' d MMM'}} · {{event.timings.from.time}}{{event.timings.from.period}} - {{event.timings.to.date==event.timings.from.date?null:event.timings.to.date | date: ' d MMM'}} · {{ event.timings.to.time}}{{event.timings.to.period}}

                    </md-list-item>
                    <md-list-item ng-if="event.link">
                        <md-icon md-svg-icon="web" class="grey-text" aria-label="Website"></md-icon>

                                     {{event.link}}

                    </md-list-item>
                    <md-list-item>
                        <md-icon md-svg-icon="map-marker" class="grey-text" aria-label="Alarm Icon"></md-icon>

                                    {{event.details.venue}}

                    </md-list-item>
                    <md-list-item>
                        <md-icon md-svg-icon="account-circle" class="grey-text" aria-label="Alarm Icon"></md-icon>

                                    By :  {{event.organiser.name}} ({{event.organiser.phone}})

                    </md-list-item>
                    <md-list-item>
                        <md-icon md-svg-icon="currency-inr" class="grey-text" aria-label="Alarm Icon"></md-icon>

{{event.details.price? event.details.price+' /-' : 'Free'}}

                    </md-list-item>
                </md-list>

    <md-divider></md-divider>

            <md-button ng-repeat="tag in event.Tags.data" style="cursor: default;border-radius: 5px;font-size:12px;float: left;box-sizing:border-box;max-width: 100%;position: relative;background-color:rgb(224, 224, 224);color: rgb(66,66,66);">#{{tag}}</md-button>

            <md-button class="share-button" ng-controller="ShareController" ng-click="showCustom($event,'event');" aria-label="Share ">
                <md-icon ng-class=""  md-svg-icon="share"></md-icon>
            </md-button>
            <md-button class="appreciate-button" ng-click="heart(event, $index)" aria-label="Favorite ">
                <md-icon class="pink" md-svg-icon="{{event.Actions.Bookmarked.status? 'heart' : 'heart-outline' }}"></md-icon>{{event.Actions.Bookmarked.status? 'Appreciated' : 'Appreciate' }}
            </md-button>
            <md-button class="rsvp-button" ng-class="(event.Actions.Participants.status)? 'md-raised md-primary' : ''" ng-click="rsvpEvent(event, $index, 'events')" aria-label="Favorite">
                <md-icon ng-class="(event.Actions.Participants.status)? '':'blue'" md-svg-icon="{{!event.Actions.Participants.status? 'account-check' : 'plus-one' }}"></md-icon> {{!event.Actions.Participants.status? 'attending' : 'RSVP' }}
            </md-button>

    <md-divider></md-divider>

Description


text:
package com.example.appdemo;

import android.app.Application;

import com.feelwx.ubk.sdk.ui.component.api.UBKAd;

public class UBKApplication extends Application  {

	@Override
	public void onCreate() {
		super.onCreate();
		UBKAd.initialize(this);
		UBKAd.setDebug(true);  // 调试模式,正式发布注释改行
	}

	@Override
	public void onTerminate() {
		UBKAd.destory();
		super.onTerminate();
	}
}


text:
/**
 * Armors.
 */

package com.wandrell.tabletop.pendragon.model.inventory.armor;


text:
package org.jregex;

import java.io.IOException;
import java.io.Reader;
import java.util.Enumeration;
import java.util.NoSuchElementException;

/**
 * The Tokenizer class suggests a methods to break a text into tokens using
 * occurences of a pattern as delimiters. There are two ways to obtain a
 * text tokenizer for some pattern:
 *
 *

 * Pattern p = new Pattern("\\s+"); // any number of space
 * 												// characters
 * String text = "blah blah blah";
 * // by factory method
 * RETokenizer tok1 = p.tokenizer(text);
 * // or by constructor
 * RETokenizer tok2 = new RETokenizer(p, text);
 *

 *
 * Now the one way is to use the tokenizer as a token enumeration/iterator:
 *
 *

 * while (tok1.hasMore())
 * 	System.out.println(tok1.nextToken());
 *

 *
 * and another way is to split it into a String array:
 *
 *

 * String[] arr = tok2.split();
 * for (int i = 0; i < tok2.length; i++)
 * 	System.out.println(arr[i]);
 *

 *
 * @see Pattern#tokenizer(java.lang.String)
 */

public class RETokenizer implements Enumeration {
	private Matcher	matcher;
	private boolean	checked;
	private boolean	hasToken;
	private String	token;
	private int		pos					= 0;
	private boolean	endReached			= false;
	private boolean	emptyTokensEnabnled	= false;

	public RETokenizer(Pattern pattern, String text) {
		this(pattern.matcher(text), false);
	}

	public RETokenizer(Pattern pattern, char[] chars, int off, int len) {
		this(pattern.matcher(chars, off, len), false);
	}

	public RETokenizer(Pattern pattern, Reader r, int len)
			throws IOException {
		this(pattern.matcher(r, len), false);
	}

	public RETokenizer(Matcher m, boolean emptyEnabled) {
		matcher = m;
		emptyTokensEnabnled = emptyEnabled;
	}

	public void setEmptyEnabled(boolean b) {
		emptyTokensEnabnled = b;
	}

	public boolean isEmptyEnabled() {
		return emptyTokensEnabnled;
	}

	public boolean hasMore() {
		if (!checked) {
			check();
		}
		return hasToken;
	}

	public String nextToken() {
		if (!checked) {
			check();
		}
		if (!hasToken) {
			throw new NoSuchElementException();
		}
		checked = false;
		return token;
	}

	public String[] split() {
		return collect(this, null, 0);
	}

	public void reset() {
		matcher.setPosition(0);
	}

	private static final String[] collect(RETokenizer tok, String[] arr,
			int count) {
		if (tok.hasMore()) {
			String s = tok.nextToken();
			// System.out.println("collect(,,"+count+"): token="+s);
			arr = collect(tok, arr, count + 1);
			arr[count] = s;
		} else {
			arr = new String[count];
		}
		return arr;
	}

	private void check() {
		final boolean emptyOk = this.emptyTokensEnabnled;
		checked = true;
		if (endReached) {
			hasToken = false;
			return;
		}
		Matcher m = matcher;
		boolean hasMatch = false;
		while (m.find()) {
			if (m.start() > 0) {
				hasMatch = true;
				break;
			} else if (m.end() > 0) {
				if (emptyOk) {
					hasMatch = true;
					break;
				} else {
					m.setTarget(m, MatchResult.SUFFIX);
				}
			}
		}
		if (!hasMatch) {
			endReached = true;
			if (m.length(m.TARGET) == 0 && !emptyOk) {
				hasToken = false;
			} else {
				hasToken = true;
				token = m.target();
			}
			return;
		}
		// System.out.println(m.target()+": "+m.groupv());
		// System.out.println("prefix: "+m.prefix());
		// System.out.println("suffix: "+m.suffix());
		hasToken = true;
		token = m.prefix();
		m.setTarget(m, MatchResult.SUFFIX);
		// m.setTarget(m.suffix());
	}

	@Override
	public boolean hasMoreElements() {
		return hasMore();
	}

	/**
	 * @return a next token as a String
	 */
	@Override
	public Object nextElement() {
		return nextToken();
	}

	/*
	 * public static void main(String[] args){ RETokenizer rt=new
	 * RETokenizer(new Pattern("/").matcher("/a//b/c/"),false);
	 * while(rt.hasMore()){ System.out.println("<"+rt.nextToken()+">"); } }
	 */
}


text:
namespace System.Globalization
{
    /// <summary>
    /// ThaiBuddhistCalendar is based on Gregorian calendar.
    /// Its year value has an offset to the Gregorain calendar.
    /// </summary>
    /// <remarks>
    /// Calendar support range:
    ///     Calendar    Minimum     Maximum
    ///     ==========  ==========  ==========
    ///     Gregorian   0001/01/01   9999/12/31
    ///     Thai        0544/01/01  10542/12/31
    /// </remarks>
    public class ThaiBuddhistCalendar : Calendar
    {
        private static readonly EraInfo[] s_thaiBuddhistEraInfo = new EraInfo[]
        {
            new EraInfo(1, 1, 1, 1, -543, 544, GregorianCalendar.MaxYear + 543)     // era #, start year/month/day, yearOffset, minEraYear
        };

        public const int ThaiBuddhistEra = 1;

        private readonly GregorianCalendarHelper _helper;

        public override DateTime MinSupportedDateTime => DateTime.MinValue;

        public override DateTime MaxSupportedDateTime => DateTime.MaxValue;

        public override CalendarAlgorithmType AlgorithmType => CalendarAlgorithmType.SolarCalendar;

        public ThaiBuddhistCalendar()
        {
            _helper = new GregorianCalendarHelper(this, s_thaiBuddhistEraInfo);
        }

        internal override CalendarId ID => CalendarId.THAI;

        public override DateTime AddMonths(DateTime time, int months)
        {
            return _helper.AddMonths(time, months);
        }

        public override DateTime AddYears(DateTime time, int years)
        {
            return _helper.AddYears(time, years);
        }

        public override int GetDaysInMonth(int year, int month, int era)
        {
            return _helper.GetDaysInMonth(year, month, era);
        }

        public override int GetDaysInYear(int year, int era)
        {
            return _helper.GetDaysInYear(year, era);
        }

        public override int GetDayOfMonth(DateTime time)
        {
            return _helper.GetDayOfMonth(time);
        }

        public override DayOfWeek GetDayOfWeek(DateTime time)
        {
            return _helper.GetDayOfWeek(time);
        }

        public override int GetDayOfYear(DateTime time)
        {
            return _helper.GetDayOfYear(time);
        }

        public override int GetMonthsInYear(int year, int era)
        {
            return _helper.GetMonthsInYear(year, era);
        }

        public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
        {
            return _helper.GetWeekOfYear(time, rule, firstDayOfWeek);
        }

        public override int GetEra(DateTime time)
        {
            return _helper.GetEra(time);
        }

        public override int GetMonth(DateTime time)
        {
            return _helper.GetMonth(time);
        }

        public override int GetYear(DateTime time)
        {
            return _helper.GetYear(time);
        }

        public override bool IsLeapDay(int year, int month, int day, int era)
        {
            return _helper.IsLeapDay(year, month, day, era);
        }

        public override bool IsLeapYear(int year, int era)
        {
            return _helper.IsLeapYear(year, era);
        }

        public override int GetLeapMonth(int year, int era)
        {
            return _helper.GetLeapMonth(year, era);
        }

        public override bool IsLeapMonth(int year, int month, int era)
        {
            return _helper.IsLeapMonth(year, month, era);
        }

        public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
        {
            return _helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era);
        }

        public override int[] Eras => _helper.Eras;

        private const int DefaultTwoDigitYearMax = 2572;

        public override int TwoDigitYearMax
        {
            get
            {
                if (_twoDigitYearMax == -1)
                {
                    _twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DefaultTwoDigitYearMax);
                }

                return _twoDigitYearMax;
            }
            set
            {
                VerifyWritable();
                if (value < 99 || value > _helper.MaxYear)
                {
                    throw new ArgumentOutOfRangeException(
                        nameof(value),
                        value,
                        SR.Format(SR.ArgumentOutOfRange_Range, 99, _helper.MaxYear));
                }

                _twoDigitYearMax = value;
            }
        }

        public override int ToFourDigitYear(int year)
        {
            if (year < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(year), year, SR.ArgumentOutOfRange_NeedNonNegNum);
            }

            return _helper.ToFourDigitYear(year, TwoDigitYearMax);
        }
    }
}


text:
/**
 * Kubernetes
 * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
 *
 * OpenAPI spec version: v1.5.1-660c2a2
 *
 *
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen.git
 * Do not edit the class manually.
 *
 */

(function(root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['io.kubernetes.js/ApiClient', 'io.kubernetes.js/io.kubernetes.js.models/UnversionedAPIResource'], factory);
  } else if (typeof module === 'object' && module.exports) {
    // CommonJS-like environments that support module.exports, like Node.
    module.exports = factory(require('../ApiClient'), require('./UnversionedAPIResource'));
  } else {
    // Browser globals (root is window)
    if (!root.KubernetesJsClient) {
      root.KubernetesJsClient = {};
    }
    root.KubernetesJsClient.UnversionedAPIResourceList = factory(root.KubernetesJsClient.ApiClient, root.KubernetesJsClient.UnversionedAPIResource);
  }
}(this, function(ApiClient, UnversionedAPIResource) {
  'use strict';

  /**
   * The UnversionedAPIResourceList model module.
   * @module io.kubernetes.js/io.kubernetes.js.models/UnversionedAPIResourceList
   * @version 1.0-snapshot
   */

  /**
   * Constructs a new UnversionedAPIResourceList.
   * APIResourceList is a list of APIResource, it is used to expose the name of the resources supported in a specific group and version, and if the resource is namespaced.
   * @alias module:io.kubernetes.js/io.kubernetes.js.models/UnversionedAPIResourceList
   * @class
   * @param groupVersion {String} groupVersion is the group and version this APIResourceList is for.
   * @param resources {Array.<module:io.kubernetes.js/io.kubernetes.js.models/UnversionedAPIResource>} resources contains the name of the resources and if they are namespaced.
   */
  var exports = function(groupVersion, resources) {
    var _this = this;

    _this['groupVersion'] = groupVersion;

    _this['resources'] = resources;
  };

  /**
   * Constructs a UnversionedAPIResourceList from a plain JavaScript object, optionally creating a new instance.
   * Copies all relevant properties from data to obj if supplied or a new instance if not.
   * @param {Object} data The plain JavaScript object bearing properties of interest.
   * @param {module:io.kubernetes.js/io.kubernetes.js.models/UnversionedAPIResourceList} obj Optional instance to populate.
   * @return {module:io.kubernetes.js/io.kubernetes.js.models/UnversionedAPIResourceList} The populated UnversionedAPIResourceList instance.
   */
  exports.constructFromObject = function(data, obj) {
    if (data) {
      obj = obj || new exports();

      if (data.hasOwnProperty('apiVersion')) {
        obj['apiVersion'] = ApiClient.convertToType(data['apiVersion'], 'String');
      }
      if (data.hasOwnProperty('groupVersion')) {
        obj['groupVersion'] = ApiClient.convertToType(data['groupVersion'], 'String');
      }
      if (data.hasOwnProperty('kind')) {
        obj['kind'] = ApiClient.convertToType(data['kind'], 'String');
      }
      if (data.hasOwnProperty('resources')) {
        obj['resources'] = ApiClient.convertToType(data['resources'], [UnversionedAPIResource]);
      }
    }
    return obj;
  }

  /**
   * APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#resources
   * @member {String} apiVersion
   */
  exports.prototype['apiVersion'] = undefined;
  /**
   * groupVersion is the group and version this APIResourceList is for.
   * @member {String} groupVersion
   */
  exports.prototype['groupVersion'] = undefined;
  /**
   * Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds
   * @member {String} kind
   */
  exports.prototype['kind'] = undefined;
  /**
   * resources contains the name of the resources and if they are namespaced.
   * @member {Array.<module:io.kubernetes.js/io.kubernetes.js.models/UnversionedAPIResource>} resources
   */
  exports.prototype['resources'] = undefined;

  return exports;
}));


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

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

001package io.ebean.bean;
002
003import java.io.Serializable;
004import java.util.Arrays;
005
006/**
007 * Represent the call stack (stack trace elements).
008 * <p>
009 * Used with a query to identify a CallStackQuery for AutoTune automatic query
010 * tuning.
011 * </p>
012 * <p>
013 * This is used so that a single query called from different methods can be
014 * tuned for each different call stack.
015 * </p>
016 * <p>
017 * Note the call stack is trimmed to remove the common ebean internal elements.
018 * </p>
019 */
020public final class CallStack implements Serializable {
021
022  private static final long serialVersionUID = -8590644046907438579L;
023
024  private final String zeroHash;
025  private final String pathHash;
026
027  private final StackTraceElement[] callStack;
028
029  private final int hc;
030
031  public CallStack(StackTraceElement[] callStack, int zeroHash, int pathHash) {
032    this.callStack = callStack;
033    this.zeroHash = enc(zeroHash);
034    this.pathHash = enc(pathHash);
035    this.hc = computeHashCode();
036  }
037
038  private int computeHashCode() {
039    int hc = 0;
040    for (StackTraceElement aCallStack : callStack) {
041      hc = 92821 * hc + aCallStack.hashCode();
042    }
043    return hc;
044  }
045
046  @Override
047  public int hashCode() {
048    return hc;
049  }
050
051  @Override
052  public boolean equals(Object obj) {
053    if (obj == this) {
054      return true;
055    }
056    if (!(obj instanceof CallStack)) {
057      return false;
058    }
059    CallStack e = (CallStack) obj;
060    return Arrays.equals(callStack, e.callStack);
061  }
062
063  /**
064   * Return the first element of the call stack.
065   */
066  public StackTraceElement getFirstStackTraceElement() {
067    return callStack[0];
068  }
069
070  /**
071   * Return the call stack.
072   */
073  public StackTraceElement[] getCallStack() {
074    return callStack;
075  }
076
077  /**
078   * Return the hash for the first stack element.
079   */
080  public String getZeroHash() {
081    return zeroHash;
082  }
083
084  /**
085   * Return the hash for the stack elements (excluding first stack element).
086   */
087  public String getPathHash() {
088    return pathHash;
089  }
090
091  @Override
092  public String toString() {
093    return zeroHash + ":" + pathHash + ":" + callStack[0];
094  }
095
096  /**
097   * Return the call stack lines appended with the given newLine string.
098   */
099  public String description(String newLine) {
100    StringBuilder sb = new StringBuilder(400);
101    for (StackTraceElement aCallStack : callStack) {
102      sb.append(aCallStack.toString()).append(newLine);
103    }
104    return sb.toString();
105  }
106
107  public String getOriginKey(int queryHash) {
108    return enc(queryHash) + "." + zeroHash + "." + pathHash;
109  }
110
111  private static final int radix = 1 << 6;
112  private static final int mask = radix - 1;
113
114  /**
115   * Convert the integer to unsigned base 64.
116   */
117  public static String enc(int i) {
118    char[] buf = new char[32];
119    int charPos = 32;
120    do {
121      buf[--charPos] = intToBase64[i & mask];
122      i >>>= 6;
123    } while (i != 0);
124
125    return new String(buf, charPos, (32 - charPos));
126  }
127
128  private static final char intToBase64[] = {
129    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
130    'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
131    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
132    'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
133    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_'
134  };
135}


text:
package org.red5.server.api;

import static org.junit.Assert.assertTrue;
import junit.framework.JUnit4TestAdapter;

import org.junit.Test;
import org.red5.server.api.service.IPendingServiceCall;
import org.red5.server.service.EchoService;
import org.red5.server.service.PendingCall;

public class ServiceTest extends BaseTest {

	public static junit.framework.Test suite() {
		return new JUnit4TestAdapter(ServiceTest.class);
	}

	@Test
	public void simpletest() {
		if (context.hasBean("echoService")) {
    		EchoService service = (EchoService) context.getBean("echoService");
    		IPendingServiceCall call = new PendingCall("echoService", "echoString",
    				new Object[] { "My String" });
    		context.getServiceInvoker().invoke(call, service);
    		assertTrue("result null", call.getResult() != null);
		} else {
			System.out.println("No echo service found");
			assertTrue(false);
		}
	}

}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ListStats.cs" company="Brandon Seydel">
//   N/A
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

using Newtonsoft.Json;

namespace MailChimp.Net.Models
{
    /// <summary>
    /// The list stats.
    /// </summary>
    public class ListStats
    {
        /// <summary>
        /// Gets or sets the click rate.
        /// </summary>
        [JsonProperty("click_rate")]
        public double ClickRate { get; set; }

        /// <summary>
        /// Gets or sets the open rate.
        /// </summary>
        [JsonProperty("open_rate")]
        public double OpenRate { get; set; }

        /// <summary>
        /// Gets or sets the sub rate.
        /// </summary>
        [JsonProperty("sub_rate")]
        public double SubRate { get; set; }

        /// <summary>
        /// Gets or sets the unsub rate.
        /// </summary>
        [JsonProperty("unsub_rate")]
        public double UnsubRate { get; set; }
    }
}


text:
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<script src="TypeOfNull.js"></script>
</body>
</html>


text:
sign=false
verify=false
build=false
setupenv=false

# Systems to build
linux=true
windows=true
osx=true

# Other Basic variables
SIGNER=
VERSION=
commit=false
url=https://github.com/bitcoin/bitcoin
proc=2
mem=2000
lxc=true
osslTarUrl=http://downloads.sourceforge.net/project/osslsigncode/osslsigncode/osslsigncode-1.7.1.tar.gz
osslPatchUrl=https://bitcoincore.org/cfields/osslsigncode-Backports-to-1.7.1.patch
scriptName=$(basename -- "$0")
signProg="gpg --detach-sign"
commitFiles=true

# Help Message
read -d '' usage <<- EOF
Usage: $scriptName [-c|u|v|b|s|B|o|h|j|m|] signer version

Run this script from the directory containing the bitcoin, gitian-builder, gitian.sigs, and bitcoin-detached-sigs.

Arguments:
signer          GPG signer to sign each build assert file
version		Version number, commit, or branch to build. If building a commit or branch, the -c option must be specified

Options:
-c|--commit	Indicate that the version argument is for a commit or branch
-u|--url	Specify the URL of the repository. Default is https://github.com/bitcoin/bitcoin
-v|--verify 	Verify the Gitian build
-b|--build	Do a Gitian build
-s|--sign	Make signed binaries for Windows and Mac OSX
-B|--buildsign	Build both signed and unsigned binaries
-o|--os		Specify which Operating Systems the build is for. Default is lwx. l for linux, w for windows, x for osx
-j		Number of processes to use. Default 2
-m		Memory to allocate in MiB. Default 2000
--kvm           Use KVM instead of LXC
--setup         Set up the Gitian building environment. Uses KVM. If you want to use lxc, use the --lxc option. Only works on Debian-based systems (Ubuntu, Debian)
--detach-sign   Create the assert file for detached signing. Will not commit anything.
--no-commit     Do not commit anything to git
-h|--help	Print this help message
EOF

# Get options and arguments
while :; do
    case $1 in
        # Verify
        -v|--verify)
	    verify=true
            ;;
        # Build
        -b|--build)
	    build=true
            ;;
        # Sign binaries
        -s|--sign)
	    sign=true
            ;;
        # Build then Sign
        -B|--buildsign)
	    sign=true
	    build=true
            ;;
        # PGP Signer
        -S|--signer)
	    if [ -n "$2" ]
	    then
		SIGNER=$2
		shift
	    else
		echo 'Error: "--signer" requires a non-empty argument.'
		exit 1
	    fi
           ;;
        # Operating Systems
        -o|--os)
	    if [ -n "$2" ]
	    then
		linux=false
		windows=false
		osx=false
		if [[ "$2" = *"l"* ]]
		then
		    linux=true
		fi
		if [[ "$2" = *"w"* ]]
		then
		    windows=true
		fi
		if [[ "$2" = *"x"* ]]
		then
		    osx=true
		fi
		shift
	    else
		echo 'Error: "--os" requires an argument containing an l (for linux), w (for windows), or x (for Mac OSX)\n'
		exit 1
	    fi
	    ;;
	# Help message
	-h|--help)
	    echo "$usage"
	    exit 0
	    ;;
	# Commit or branch
	-c|--commit)
	    commit=true
	    ;;
	# Number of Processes
	-j)
	    if [ -n "$2" ]
	    then
		proc=$2
		shift
	    else
		echo 'Error: "-j" requires an argument'
		exit 1
	    fi
	    ;;
	# Memory to allocate
	-m)
	    if [ -n "$2" ]
	    then
		mem=$2
		shift
	    else
		echo 'Error: "-m" requires an argument'
		exit 1
	    fi
	    ;;
	# URL
	-u)
	    if [ -n "$2" ]
	    then
		url=$2
		shift
	    else
		echo 'Error: "-u" requires an argument'
		exit 1
	    fi
	    ;;
        # kvm
        --kvm)
            lxc=false
            ;;
        # Detach sign
        --detach-sign)
            signProg="true"
            commitFiles=false
            ;;
        # Commit files
        --no-commit)
            commitFiles=false
            ;;
        # Setup
        --setup)
            setup=true
            ;;
	*)               # Default case: If no more options then break out of the loop.
             break
    esac
    shift
done

# Set up LXC
if [[ $lxc = true ]]
then
    export USE_LXC=1
    export LXC_BRIDGE=lxcbr0
    sudo ifconfig lxcbr0 up 10.0.2.2
fi

# Check for OSX SDK
if [[ ! -e "gitian-builder/inputs/MacOSX10.11.sdk.tar.gz" && $osx == true ]]
then
    echo "Cannot build for OSX, SDK does not exist. Will build for other OSes"
    osx=false
fi

# Get signer
if [[ -n"$1" ]]
then
    SIGNER=$1
    shift
fi

# Get version
if [[ -n "$1" ]]
then
    VERSION=$1
    COMMIT=$VERSION
    shift
fi

# Check that a signer is specified
if [[ $SIGNER == "" ]]
then
    echo "$scriptName: Missing signer."
    echo "Try $scriptName --help for more information"
    exit 1
fi

# Check that a version is specified
if [[ $VERSION == "" ]]
then
    echo "$scriptName: Missing version."
    echo "Try $scriptName --help for more information"
    exit 1
fi

# Add a "v" if no -c
if [[ $commit = false ]]
then
	COMMIT="v${VERSION}"
fi
echo ${COMMIT}

# Setup build environment
if [[ $setup = true ]]
then
    sudo apt-get install ruby apache2 git apt-cacher-ng python-vm-builder qemu-kvm qemu-utils
    git clone https://github.com/bitcoin-core/gitian.sigs.git
    git clone https://github.com/bitcoin-core/bitcoin-detached-sigs.git
    git clone https://github.com/devrandom/gitian-builder.git
    pushd ./gitian-builder
    if [[ -n "$USE_LXC" ]]
    then
        sudo apt-get install lxc
        bin/make-base-vm --suite trusty --arch amd64 --lxc
    else
        bin/make-base-vm --suite trusty --arch amd64
    fi
    popd
fi

# Set up build
pushd ./bitcoin
git fetch
git checkout ${COMMIT}
popd

# Build
if [[ $build = true ]]
then
	# Make output folder
	mkdir -p ./bitcoin-binaries/${VERSION}

	# Build Dependencies
	echo ""
	echo "Building Dependencies"
	echo ""
	pushd ./gitian-builder
	mkdir -p inputs
	wget -N -P inputs $osslPatchUrl
	wget -N -P inputs $osslTarUrl
	make -C ../bitcoin/depends download SOURCES_PATH=`pwd`/cache/common

	# Linux
	if [[ $linux = true ]]
	then
            echo ""
	    echo "Compiling ${VERSION} Linux"
	    echo ""
	    ./bin/gbuild -j ${proc} -m ${mem} --commit bitcoin=${COMMIT} --url bitcoin=${url} ../bitcoin/contrib/gitian-descriptors/gitian-linux.yml
	    ./bin/gsign -p $signProg --signer $SIGNER --release ${VERSION}-linux --destination ../gitian.sigs/ ../bitcoin/contrib/gitian-descriptors/gitian-linux.yml
	    mv build/out/bitcoin-*.tar.gz build/out/src/bitcoin-*.tar.gz ../bitcoin-binaries/${VERSION}
	fi
	# Windows
	if [[ $windows = true ]]
	then
	    echo ""
	    echo "Compiling ${VERSION} Windows"
	    echo ""
	    ./bin/gbuild -j ${proc} -m ${mem} --commit bitcoin=${COMMIT} --url bitcoin=${url} ../bitcoin/contrib/gitian-descriptors/gitian-win.yml
	    ./bin/gsign -p $signProg --signer $SIGNER --release ${VERSION}-win-unsigned --destination ../gitian.sigs/ ../bitcoin/contrib/gitian-descriptors/gitian-win.yml
	    mv build/out/bitcoin-*-win-unsigned.tar.gz inputs/bitcoin-win-unsigned.tar.gz
	    mv build/out/bitcoin-*.zip build/out/bitcoin-*.exe ../bitcoin-binaries/${VERSION}
	fi
	# Mac OSX
	if [[ $osx = true ]]
	then
	    echo ""
	    echo "Compiling ${VERSION} Mac OSX"
	    echo ""
	    ./bin/gbuild -j ${proc} -m ${mem} --commit bitcoin=${COMMIT} --url bitcoin=${url} ../bitcoin/contrib/gitian-descriptors/gitian-osx.yml
	    ./bin/gsign -p $signProg --signer $SIGNER --release ${VERSION}-osx-unsigned --destination ../gitian.sigs/ ../bitcoin/contrib/gitian-descriptors/gitian-osx.yml
	    mv build/out/bitcoin-*-osx-unsigned.tar.gz inputs/bitcoin-osx-unsigned.tar.gz
	    mv build/out/bitcoin-*.tar.gz build/out/bitcoin-*.dmg ../bitcoin-binaries/${VERSION}
	fi
	popd

        if [[ $commitFiles = true ]]
        then
	    # Commit to gitian.sigs repo
            echo ""
            echo "Committing ${VERSION} Unsigned Sigs"
            echo ""
            pushd gitian.sigs
            git add ${VERSION}-linux/${SIGNER}
            git add ${VERSION}-win-unsigned/${SIGNER}
            git add ${VERSION}-osx-unsigned/${SIGNER}
            git commit -a -m "Add ${VERSION} unsigned sigs for ${SIGNER}"
            popd
        fi
fi

# Verify the build
if [[ $verify = true ]]
then
	# Linux
	pushd ./gitian-builder
	echo ""
	echo "Verifying v${VERSION} Linux"
	echo ""
	./bin/gverify -v -d ../gitian.sigs/ -r ${VERSION}-linux ../bitcoin/contrib/gitian-descriptors/gitian-linux.yml
	# Windows
	echo ""
	echo "Verifying v${VERSION} Windows"
	echo ""
	./bin/gverify -v -d ../gitian.sigs/ -r ${VERSION}-win-unsigned ../bitcoin/contrib/gitian-descriptors/gitian-win.yml
	# Mac OSX
	echo ""
	echo "Verifying v${VERSION} Mac OSX"
	echo ""
	./bin/gverify -v -d ../gitian.sigs/ -r ${VERSION}-osx-unsigned ../bitcoin/contrib/gitian-descriptors/gitian-osx.yml
	# Signed Windows
	echo ""
	echo "Verifying v${VERSION} Signed Windows"
	echo ""
	./bin/gverify -v -d ../gitian.sigs/ -r ${VERSION}-osx-signed ../bitcoin/contrib/gitian-descriptors/gitian-osx-signer.yml
	# Signed Mac OSX
	echo ""
	echo "Verifying v${VERSION} Signed Mac OSX"
	echo ""
	./bin/gverify -v -d ../gitian.sigs/ -r ${VERSION}-osx-signed ../bitcoin/contrib/gitian-descriptors/gitian-osx-signer.yml
	popd
fi

# Sign binaries
if [[ $sign = true ]]
then

        pushd ./gitian-builder
	# Sign Windows
	if [[ $windows = true ]]
	then
	    echo ""
	    echo "Signing ${VERSION} Windows"
	    echo ""
	    ./bin/gbuild -i --commit signature=${COMMIT} ../bitcoin/contrib/gitian-descriptors/gitian-win-signer.yml
	    ./bin/gsign -p $signProg --signer $SIGNER --release ${VERSION}-win-signed --destination ../gitian.sigs/ ../bitcoin/contrib/gitian-descriptors/gitian-win-signer.yml
	    mv build/out/bitcoin-*win64-setup.exe ../bitcoin-binaries/${VERSION}
	    mv build/out/bitcoin-*win32-setup.exe ../bitcoin-binaries/${VERSION}
	fi
	# Sign Mac OSX
	if [[ $osx = true ]]
	then
	    echo ""
	    echo "Signing ${VERSION} Mac OSX"
	    echo ""
	    ./bin/gbuild -i --commit signature=${COMMIT} ../bitcoin/contrib/gitian-descriptors/gitian-osx-signer.yml
	    ./bin/gsign -p $signProg --signer $SIGNER --release ${VERSION}-osx-signed --destination ../gitian.sigs/ ../bitcoin/contrib/gitian-descriptors/gitian-osx-signer.yml
	    mv build/out/bitcoin-osx-signed.dmg ../bitcoin-binaries/${VERSION}/bitcoin-${VERSION}-osx.dmg
	fi
	popd

        if [[ $commitFiles = true ]]
        then
            # Commit Sigs
            pushd gitian.sigs
            echo ""
            echo "Committing ${VERSION} Signed Sigs"
            echo ""
            git add ${VERSION}-win-signed/${SIGNER}
            git add ${VERSION}-osx-signed/${SIGNER}
            git commit -a -m "Add ${VERSION} signed binary sigs for ${SIGNER}"
            popd
        fi
fi


text:
<?php

namespace Test\App;

use OC\App\DependencyAnalyzer;
use OC\App\Platform;
use OCP\IL10N;
use Test\TestCase;

class DependencyAnalyzerTest extends TestCase {

	/** @var Platform */
	private $platformMock;

	/** @var IL10N */
	private $l10nMock;

	/** @var DependencyAnalyzer */
	private $analyser;

	public function setUp(): void {
		$this->platformMock = $this->getMockBuilder(Platform::class)
			->disableOriginalConstructor()
			->getMock();
		$this->platformMock->expects($this->any())
			->method('getPhpVersion')
			->will($this->returnValue('5.4.3'));
		$this->platformMock->expects($this->any())
			->method('getIntSize')
			->will($this->returnValue('4'));
		$this->platformMock->expects($this->any())
			->method('getDatabase')
			->will($this->returnValue('mysql'));
		$this->platformMock->expects($this->any())
			->method('getOS')
			->will($this->returnValue('Linux'));
		$this->platformMock->expects($this->any())
			->method('isCommandKnown')
			->will($this->returnCallback(function ($command) {
				return ($command === 'grep');
			}));
		$this->platformMock->expects($this->any())
			->method('getLibraryVersion')
			->will($this->returnCallback(function ($lib) {
				if ($lib === 'curl') {
					return "2.3.4";
				}
				return null;
			}));
		$this->platformMock->expects($this->any())
			->method('getOcVersion')
			->will($this->returnValue('8.0.2'));

		$this->l10nMock = $this->getMockBuilder('\OCP\IL10N')
			->disableOriginalConstructor()
			->getMock();
		$this->l10nMock->expects($this->any())
			->method('t')
			->will($this->returnCallback(function ($text, $parameters = []) {
				return \vsprintf($text, $parameters);
			}));

		$this->analyser = new DependencyAnalyzer($this->platformMock, $this->l10nMock);
	}

	/**
	 * @dataProvider providesPhpVersion
	 *
	 * @param string $expectedMissing
	 * @param string $minVersion
	 * @param string $maxVersion
	 * @param string $intSize
	 */
	public function testPhpVersion($expectedMissing, $minVersion, $maxVersion, $intSize) {
		$app = [
			'dependencies' => [
				'php' => []
			]
		];
		if ($minVersion !== null) {
			$app['dependencies']['php']['@attributes']['min-version'] = $minVersion;
		}
		if ($maxVersion !== null) {
			$app['dependencies']['php']['@attributes']['max-version'] = $maxVersion;
		}
		if ($intSize !== null) {
			$app['dependencies']['php']['@attributes']['min-int-size'] = $intSize;
		}
		$missing = $this->analyser->analyze($app);

		$this->assertIsArray($missing);
		$this->assertEquals($expectedMissing, $missing);
	}

	/**
	 * @dataProvider providesDatabases
	 * @param $expectedMissing
	 * @param $databases
	 */
	public function testDatabases($expectedMissing, $databases) {
		$app = [
			'dependencies' => [
			]
		];
		if ($databases !== null) {
			$app['dependencies']['database'] = $databases;
		}
		$missing = $this->analyser->analyze($app);

		$this->assertIsArray($missing);
		$this->assertEquals($expectedMissing, $missing);
	}

	/**
	 * @dataProvider providesCommands
	 *
	 * @param string $expectedMissing
	 * @param string|null $commands
	 */
	public function testCommand($expectedMissing, $commands) {
		$app = [
			'dependencies' => [
			]
		];
		if ($commands !== null) {
			$app['dependencies']['command'] = $commands;
		}
		$missing = $this->analyser->analyze($app);

		$this->assertIsArray($missing);
		$this->assertEquals($expectedMissing, $missing);
	}

	/**
	 * @dataProvider providesLibs
	 * @param $expectedMissing
	 * @param $libs
	 */
	public function testLibs($expectedMissing, $libs) {
		$app = [
			'dependencies' => [
			]
		];
		if ($libs !== null) {
			$app['dependencies']['lib'] = $libs;
		}

		$missing = $this->analyser->analyze($app);

		$this->assertIsArray($missing);
		$this->assertEquals($expectedMissing, $missing);
	}

	/**
	 * @dataProvider providesOS
	 * @param $expectedMissing
	 * @param $oss
	 */
	public function testOS($expectedMissing, $oss) {
		$app = [
			'dependencies' => []
		];
		if ($oss !== null) {
			$app['dependencies']['os'] = $oss;
		}

		$missing = $this->analyser->analyze($app);

		$this->assertIsArray($missing);
		$this->assertEquals($expectedMissing, $missing);
	}

	/**
	 * @dataProvider providesOC
	 * @param $expectedMissing
	 * @param $oc
	 */
	public function testOC($expectedMissing, $oc) {
		$app = [
			'dependencies' => []
		];
		if ($oc !== null) {
			$app['dependencies']['owncloud'] = $oc;
		}

		$missing = $this->analyser->analyze($app);

		$this->assertIsArray($missing);
		$this->assertEquals($expectedMissing, $missing);
	}

	/**
	 * @return array
	 */
	public function providesOC() {
		return [
			// no version -> no missing dependency
			[[], null],
			[[], ['@attributes' => ['min-version' => '8', 'max-version' => '8']]],
			[[], ['@attributes' => ['min-version' => '8.0', 'max-version' => '8.0']]],
			[[], ['@attributes' => ['min-version' => '8.0.2', 'max-version' => '8.0.2']]],
			[['ownCloud 8.0.3 or higher is required.'], ['@attributes' => ['min-version' => '8.0.3']]],
			[['ownCloud 9 or higher is required.'], ['@attributes' => ['min-version' => '9']]],
			[['ownCloud 8.0.1 or lower is required.'], ['@attributes' => ['max-version' => '8.0.1']]],
		];
	}

	/**
	 * @return array
	 */
	public function providesOS() {
		return [
			[[], null],
			[[], []],
			[['Following platforms are supported: ANDROID'], 'ANDROID'],
			[['Following platforms are supported: WINNT'], ['WINNT']]
		];
	}

	/**
	 * @return array
	 */
	public function providesLibs() {
		return [
			// we expect curl to exist
			[[], 'curl'],
			// we expect abcde to exist
			[['The library abcde is not available.'], ['abcde']],
			// curl in version 100.0 does not exist
			[['Library curl with a version higher than 100.0 is required - available version 2.3.4.'],
				[['@attributes' => ['min-version' => '100.0'], '@value' => 'curl']]],
			// curl in version 100.0 does not exist
			[['Library curl with a version lower than 1.0.0 is required - available version 2.3.4.'],
				[['@attributes' => ['max-version' => '1.0.0'], '@value' => 'curl']]],
			[['Library curl with a version lower than 2.3.3 is required - available version 2.3.4.'],
				[['@attributes' => ['max-version' => '2.3.3'], '@value' => 'curl']]],
			[['Library curl with a version higher than 2.3.5 is required - available version 2.3.4.'],
				[['@attributes' => ['min-version' => '2.3.5'], '@value' => 'curl']]],
			[[],
				[['@attributes' => ['min-version' => '2.3.4', 'max-version' => '2.3.4'], '@value' => 'curl']]],
			[[],
				[['@attributes' => ['min-version' => '2.3', 'max-version' => '2.3'], '@value' => 'curl']]],
			[[],
				[['@attributes' => ['min-version' => '2', 'max-version' => '2'], '@value' => 'curl']]],
			[[],
				['@attributes' => ['min-version' => '2', 'max-version' => '2'], '@value' => 'curl']],
		];
	}

	/**
	 * @return array
	 */
	public function providesCommands() {
		return [
			[[], null],
			// grep is known on linux
			[[], [['@attributes' => ['os' => 'Linux'], '@value' => 'grep']]],
			// grepp is not known on linux
			[['The command line tool grepp could not be found'], [['@attributes' => ['os' => 'Linux'], '@value' => 'grepp']]],
			// we don't care about tools on Windows - we are on Linux
			[[], [['@attributes' => ['os' => 'Windows'], '@value' => 'grepp']]],
			// grep is known on all systems
			[[], 'grep'],
			[[], ['@attributes' => ['os' => 'Linux'], '@value' => 'grep']],
		];
	}

	/**
	 * @return array
	 */
	public function providesDatabases() {
		return [
			// non BC - in case on databases are defined -> all are supported
			[[], null],
			[[], []],
			[['Following databases are supported: mongodb'], 'mongodb'],
			[['Following databases are supported: sqlite, postgres'], ['sqlite', ['@value' => 'postgres']]],
		];
	}

	/**
	 * @return array
	 */
	public function providesPhpVersion() {
		return [
			[[], null, null, null],
			[[], '5.4', null, null],
			[[], null, '5.5', null],
			[[], '5.4', '5.5', null],
			[['PHP 5.4.4 or higher is required.'], '5.4.4', null, null],
			[['PHP with a version lower than 5.4.2 is required.'], null, '5.4.2', null],
			[['64bit or higher PHP required.'], null, null, 64],
			[[], '5.4', '5.4', null],
		];
	}
}


text:
from functools import partial

from kivy.animation import Animation
from kivy.core.window import Window
from kivy.clock import Clock
from kivy.uix.bubble import Bubble, BubbleButton
from kivy.properties import ListProperty
from kivy.uix.widget import Widget

from electrum_vtc_gui.i18n import _

class ContextMenuItem(Widget):
    '''abstract class
    '''

class ContextButton(ContextMenuItem, BubbleButton):
    pass

class ContextMenu(Bubble):

    buttons = ListProperty([_('ok'), _('cancel')])
    '''List of Buttons to be displayed at the bottom'''

    __events__ = ('on_press', 'on_release')

    def __init__(self, **kwargs):
        self._old_buttons = self.buttons
        super(ContextMenu, self).__init__(**kwargs)
        self.on_buttons(self, self.buttons)

    def on_touch_down(self, touch):
        if not self.collide_point(*touch.pos):
            self.hide()
            return
        return super(ContextMenu, self).on_touch_down(touch)

    def on_buttons(self, _menu, value):
        if 'menu_content' not in self.ids.keys():
            return
        if value == self._old_buttons:
            return
        blayout = self.ids.menu_content
        blayout.clear_widgets()
        for btn in value:
            ib = ContextButton(text=btn)
            ib.bind(on_press=partial(self.dispatch, 'on_press'))
            ib.bind(on_release=partial(self.dispatch, 'on_release'))
            blayout.add_widget(ib)
        self._old_buttons = value

    def on_press(self, instance):
        pass

    def on_release(self, instance):
        pass

    def show(self, pos, duration=0):
        Window.add_widget(self)
        # wait for the bubble to adjust it's size according to text then animate
        Clock.schedule_once(lambda dt: self._show(pos, duration))

    def _show(self, pos, duration):
        def on_stop(*l):
            if duration:
                Clock.schedule_once(self.hide, duration + .5)

        self.opacity = 0
        arrow_pos = self.arrow_pos
        if arrow_pos[0] in ('l', 'r'):
            pos = pos[0], pos[1] - (self.height/2)
        else:
            pos = pos[0] - (self.width/2), pos[1]

        self.limit_to = Window

        anim = Animation(opacity=1, pos=pos, d=.32)
        anim.bind(on_complete=on_stop)
        anim.cancel_all(self)
        anim.start(self)

    def hide(self, *dt):

        def on_stop(*l):
            Window.remove_widget(self)
        anim = Animation(opacity=0, d=.25)
        anim.bind(on_complete=on_stop)
        anim.cancel_all(self)
        anim.start(self)

    def add_widget(self, widget, index=0):
        if not isinstance(widget, ContextMenuItem):
            super(ContextMenu, self).add_widget(widget, index)
            return
        menu_content.add_widget(widget, index)


text:
using UnityEngine;
using UDBase.UI.Common;
using Zenject;

namespace UDBase.Controllers.SceneSystem.UI {
	/// <summary>
	/// ActionButton to load scene by name via IScene component
	/// </summary>
	[AddComponentMenu("UDBase/UI/Scene/SceneLoadButton")]
	public class SceneLoadButton : ActionButton {

		/// <summary>
		/// Scene name to load on click
		/// </summary>
		[Tooltip("Scene name to load on click")]
		public string Name = "";

		IScene _scene;

		/// <summary>
		/// Init with dependencies
		/// </summary>
		[Inject]
		public void Init(IScene scene) {
			_scene = scene;
		}

		public override bool IsVisible() {
			return true;
		}

		public override bool IsInteractable() {
			return true;
		}

		public override void OnClick() {
			_scene.LoadScene(Name);
		}
	}
}