text:
#pragma once

#include <tuple>
#include <iod/callable_traits.hh>
#include <iod/utils.hh>
#include <iod/apply.hh>

namespace iod
{
  template <typename ...T>
  struct sio;

  template <typename ...T>
  inline auto D(T&&... args);

  namespace internal
  {

    template <size_t N, typename F, typename... T>
    decltype(auto) tuple_foreach_i(F f, T&&... ts)
    {
      return f(std::get<N>(ts)...);
    }

    template<typename Ret, typename F, size_t... TSize, typename... T>
    inline void
    tuple_foreach_impl(std::enable_if_t<std::is_same<void, Ret>::value>*,
                       std::index_sequence<TSize...>,
                       F f, T&&... ts)
    {
      return (void)std::initializer_list<int>{
        ((void)tuple_foreach_i<TSize>(f, std::forward<T>(ts)...), 0)...};
    }

    template<typename Ret, typename F, size_t... TSize, typename... T>
    inline decltype(auto)
      tuple_foreach_impl(std::enable_if_t<!std::is_same<void, Ret>::value>*,
                         std::index_sequence<TSize...>,
                         F f, T&&... ts)
    {
      return std::make_tuple(iod::internal::tuple_foreach_i<TSize>(f, std::forward<T>(ts)...)...);
    }

    template <size_t N, typename F, typename... T>
    decltype(auto) sio_foreach_i(F f, T&&... ts)
    {
      return f(ts.template get_nth_member<N>()...);
    }

    template<typename Ret, typename F, size_t... TSize, typename... T>
    inline void
    sio_foreach_impl(std::enable_if_t<std::is_same<void, Ret>::value>*,
                     std::index_sequence<TSize...>,
                     F f, T&&... ts)
    {
      return (void)std::initializer_list<int>{
        ((void)sio_foreach_i<TSize>(f, std::forward<T>(ts)...), 0)...};
    }

    template<typename Ret, typename F, size_t... TSize, typename... T>
    inline decltype(auto)
    sio_foreach_impl(std::enable_if_t<!std::is_same<void, Ret>::value>*,
                     std::index_sequence<TSize...> /*si*/,
                     F f, T&&... ts)
    {
      return D(iod::internal::sio_foreach_i<TSize>(f, std::forward<T>(ts)...)...);
    }

    template<unsigned N, unsigned SIZE, typename F, typename A, typename... R>
    inline
    auto
    foreach2_loop_sio(std::enable_if_t<N == SIZE>*, F, A&&, R&&... results)
    {
      return static_if<sizeof...(R) == 0>(
        [] () {},
        [&] () { return D(results...);});
    }

    template<unsigned N, unsigned SIZE, typename F, typename A, typename... R>
    inline
    auto
    foreach2_loop_sio(std::enable_if_t<N < SIZE>*, F f, A&& args_tuple, R&&... results)
    {
      auto h = [] (auto&& a) -> auto&& // avoid the lambda to convert references to values.
        {
          return std::forward<decltype(a.template get_nth_member<N>())>(a.template get_nth_member<N>());
        };
      typedef decltype(h) H;
      typedef decltype(proxy_apply(args_tuple, std::declval<H>(), f)) return_type;

      return static_if<std::is_same<return_type, void>::value>(
        [&] (auto& args_tuple)
             {
               proxy_apply(args_tuple, h, f);
               return foreach2_loop_sio<N + 1, SIZE>(0, f, args_tuple, results...);
             },
        [&] (auto& args_tuple)
             {
               return foreach2_loop_sio<N + 1, SIZE>
                 (0, f, args_tuple, results..., proxy_apply(args_tuple, h, f));
             }, args_tuple);

    }

    template<typename F, typename... T>
    inline void tuple_foreach(F, std::tuple<>, T&&...)
    {
    }

    template<typename F, typename T1, typename... T>
    inline decltype(auto) tuple_foreach(F f, T1&& t1 , T&&... ts)
    {
      using seq = std::make_index_sequence<std::tuple_size<std::decay_t<T1>>::value>;
      using Ret = decltype(f(std::get<0>(t1), std::get<0>(ts)...));
      return iod::internal::tuple_foreach_impl<Ret>(0, seq{},
                                                    f, t1, std::forward<T>(ts)...);
    }

    template<typename F, typename T1, typename... T>
    inline void sio_foreach(std::enable_if_t<std::remove_reference_t<T1>::_size == 0>*,
                            F /*f*/, T1&& /*t1*/, T&&... /*ts*/)
    {
    }

    template<typename F, typename T1, typename... T>
    inline decltype(auto) sio_foreach(std::enable_if_t<std::remove_reference_t<T1>::_size != 0>*,
                                      F f, T1&& t1 , T&&... ts)
    {
      const size_t size = std::remove_reference_t<T1>::_size;
      using seq = std::make_index_sequence<size>;
      using Ret = decltype(f(t1.template get_nth_member<0>(), ts.template get_nth_member<0>()...));
      return iod::internal::sio_foreach_impl<Ret>(0, seq{},
                                                  f, t1, std::forward<T>(ts)...);
    }

    template <typename T>
    struct foreach_tuple_caller
    {
      foreach_tuple_caller(T&& t) : t_(t) {}

      template <typename F, size_t... I>
      decltype(auto) run(F f, std::index_sequence<I...>)
      {
        return iod::internal::tuple_foreach(f, std::get<I>(t_)...);
      }

      template <typename F>
      decltype(auto) operator|(F f)
      {
        return run(f, std::make_index_sequence<std::tuple_size<T>::value>{});
      }

      const T t_;
    };

    template <typename T>
    struct foreach_sio_caller
    {
      foreach_sio_caller(T&& t) : t_(t) {}

      template <typename F, size_t... I>
      decltype(auto) run(F f, std::index_sequence<I...>)
      {
        return iod::internal::sio_foreach(0, f, std::get<I>(t_)...);
      }

      template <typename F>
      decltype(auto) operator|(F f)
      {
        return run(f, std::make_index_sequence<std::tuple_size<T>::value>{});
      }

      const T t_;
    };

    template <typename T>
    struct foreach2_sio_caller
    {
      foreach2_sio_caller(T&& t) : t_(t) {}

      template <typename F>
      auto operator|(F f)
      {
        const int size = std::remove_reference_t<decltype(std::get<0>(t_))>::_size;
        return internal::foreach2_loop_sio<0, size>(0, f, t_);
      }

      const T t_;
    };

  }

  template <typename... S, typename... T>
  auto foreach(std::tuple<S...>& a1, T&&... args)
  {
    return internal::foreach_tuple_caller<decltype(std::forward_as_tuple(a1, args...))>
      (std::forward_as_tuple(a1, args...));
  }

  template <typename... S, typename... T>
  auto foreach(const std::tuple<S...>& a1, T&&... args)
  {
    return internal::foreach_tuple_caller<decltype(std::forward_as_tuple(a1, args...))>
      (std::forward_as_tuple(a1, args...));
  }

  template <typename... S, typename... T>
  auto foreach(sio<S...>& a1, T&&... args)
  {
    return internal::foreach_sio_caller<decltype(std::forward_as_tuple(a1, args...))>
      (std::forward_as_tuple(a1, args...));
  }

  template <typename... S, typename... T>
  auto foreach(const sio<S...>& a1, T&&... args)
  {
    return internal::foreach_sio_caller<decltype(std::forward_as_tuple(a1, args...))>
      (std::forward_as_tuple(a1, args...));
  }

  template <typename... S, typename... T>
  auto foreach2(sio<S...>& a1, T&&... args)
  {
    return internal::foreach2_sio_caller<decltype(std::forward_as_tuple(a1, args...))>
      (std::forward_as_tuple(a1, args...));
  }

  template <typename... S, typename... T>
  auto foreach2(const sio<S...>& a1, T&&... args)
  {
    return internal::foreach2_sio_caller<decltype(std::forward_as_tuple(a1, args...))>
      (std::forward_as_tuple(a1, args...));
  }

  namespace internal
  {

    template<unsigned N, unsigned SIZE, typename F, typename A, typename P, typename... R>
    inline
    auto
    foreach_loop_tuple_prev(std::enable_if_t<N == SIZE>*, F, A&&,
                            P, R&&... results)
    {
      return static_if<sizeof...(R) == 0>(
        [] () {},
        [&] () { return std::forward_as_tuple(results...);}); }

    template<unsigned N, unsigned SIZE, typename F, typename A, typename... R>
    inline
    auto
    foreach_loop_tuple_prev(std::enable_if_t<N < SIZE>*, F f, A&& args_tuple, R&&... results)
    {
      auto h = [] (auto&& a) -> auto&& // avoid the lambda to convert references to values.
        {
          return std::forward<decltype(std::get<N>(a))>(std::get<N>(a));
        };

      auto results_tuple = std::forward_as_tuple(results...);
      auto prev = std::get<std::tuple_size<decltype(results_tuple)>::value - 1>(results_tuple);

      // typedef decltype(h) H;
      typedef decltype(apply(std::tuple_cat(foreach(args_tuple) | h, std::forward_as_tuple(prev)), f)) return_type;
      //typedef decltype(proxy_apply(args_tuple, std::declval<H>(), f)) return_type;

      return static_if<std::is_same<return_type, void>::value>(
        [&] (auto& args_tuple, auto& h, auto& f)
             {
               apply(std::tuple_cat(foreach(args_tuple) | h, std::forward_as_tuple(prev)), f);
               return foreach_loop_tuple_prev<N + 1, SIZE>(0, f, args_tuple, results...);
             },
        [&] (auto& args_tuple, auto& h, auto& f)
             {
               return foreach_loop_tuple_prev<N + 1, SIZE>
                 (0, f, args_tuple, results...,
                  apply(std::tuple_cat(foreach(args_tuple) | h, std::forward_as_tuple(prev)), f));
             }, args_tuple, h, f);
    }

    template <typename T, typename P>
    struct foreach_tuple_caller_prev
    {
      foreach_tuple_caller_prev(T&& t, P prev_init) : t_(t), prev_init_(prev_init) {}

      template <typename F>
      auto operator|(F f)
      {
        const int size = std::tuple_size<std::remove_reference_t<decltype(std::get<0>(t_))>>::value;
        return internal::foreach_loop_tuple_prev<0, size>(0, f, t_, prev_init_);
      }

      const T t_;
      P prev_init_;
    };

  }

  template <typename P, typename... S, typename... T>
  auto foreach_prev(std::tuple<S...>& a1, P prev_init, T&&... args)
  {
    return internal::foreach_tuple_caller_prev<decltype(std::forward_as_tuple(a1, args...)), P>
      (std::forward_as_tuple(a1, args...), prev_init);
  }

  template <typename P, typename... S, typename... T>
  auto foreach_prev(const std::tuple<S...>& a1, P prev_init, T&&... args)
  {
    return internal::foreach_tuple_caller_prev<decltype(std::forward_as_tuple(a1, args...)), P>
      (std::forward_as_tuple(a1, args...), prev_init);
  }

  template<unsigned N, unsigned SIZE, typename F, typename O, typename P>
  inline
  auto
  sio_iterate_loop(std::enable_if_t<N < SIZE>*, F f, const O& o, const P& prev)
  {
    auto new_prev = f(o.template get_nth_member<N>(), prev);
    return sio_iterate_loop<N+1, SIZE>(0, f, o, new_prev);
  }

  template<unsigned N, unsigned SIZE, typename F, typename O, typename P>
  inline
  auto
  sio_iterate_loop(std::enable_if_t<N == SIZE>*, F /*f*/, const O& /*o*/, const P& prev)
  {
    return prev;
  }

  template <typename O, typename P>
  struct sio_iterate_caller
  {
    sio_iterate_caller(O o, P init) : o_(o), init_(init) {}

    template <typename F>
    auto operator|(F f)
      {
        const int size = O::size();
        return sio_iterate_loop<0, size>(0, f, o_, init_);
      }

    const O o_;
    P init_;
  };

  template <typename O, typename I>
  auto sio_iterate(O o, I init)
  {
    return sio_iterate_caller<O, I>(o, init);
  }

}


text:
package com.happyplayer.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.RelativeLayout;

/**
 *
 * 锁屏按钮
 *
 */
public class CopyOfLockPalyOrPauseButtonRelativeLayout extends RelativeLayout {
	private Paint progressPaint;
	private Paint paint;
	private boolean isTouch = false;

	private int maxProgress = 0;
	private int playingProgress = 0;

	public CopyOfLockPalyOrPauseButtonRelativeLayout(Context context,
			AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init(context);
	}

	public CopyOfLockPalyOrPauseButtonRelativeLayout(Context context,
			AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}

	public CopyOfLockPalyOrPauseButtonRelativeLayout(Context context) {
		super(context);
		init(context);
	}

	private void init(Context context) {
		paint = new Paint();
		paint.setDither(true);
		paint.setAntiAlias(true);

		progressPaint = new Paint();
		progressPaint.setDither(true);
		progressPaint.setAntiAlias(true);
	}

	public void setPressed(boolean pressed) {
		isTouch = pressed;
		invalidate();
		super.setPressed(pressed);
	}

	private double PI = 3.1416;

	@Override
	protected void dispatchDraw(Canvas canvas) {
		if (isTouch) {
			paint.setColor(Color.rgb(37, 158, 247));
			paint.setStyle(Paint.Style.FILL);
			paint.setStrokeWidth(3);
			int cx = getWidth() / 2;
			int cy = getHeight() / 2;
			canvas.drawCircle(cx, cy, getWidth() / 3, paint);
		} else {
			paint.setColor(Color.WHITE);
			paint.setStyle(Paint.Style.STROKE);
			paint.setStrokeWidth(3);
			int cx = getWidth() / 2;
			int cy = getHeight() / 2;
			int r = getWidth() / 3;
			canvas.drawCircle(cx, cy, r, paint);
			if (maxProgress != 0) {
				// save和restore是为了剪切操作不影响画布的其它元素
				canvas.save();

				double c = 2 * PI * r * playingProgress / maxProgress / r;
				double h = r * Math.cos(c);
				h = Math.abs(h);
				int dRx = 0;
				if (playingProgress <= maxProgress / 4) {
					dRx = (int) (getWidth() / 2 - h);
				} else if (playingProgress <= maxProgress / 2) {
					dRx = (int) (getWidth() / 2 + h);
				} else {
					dRx = getWidth();
				}
				// 右矩形
				int rightRectButtom = dRx;
				canvas.clipRect(getWidth() / 2, 0, getWidth(), rightRectButtom);

				progressPaint.setColor(Color.rgb(37, 158, 247));
				progressPaint.setStyle(Paint.Style.STROKE);
				progressPaint.setStrokeWidth(5);
				canvas.drawCircle(cx, cy, getWidth() / 3, progressPaint);

				canvas.restore();

				// save和restore是为了剪切操作不影响画布的其它元素
				canvas.save();

				int dLx = 0;
				if (playingProgress >= maxProgress / 2 && playingProgress  < maxProgress * 3 / 4) {
					dLx = (int) (getWidth() / 2 + h);
				} else if (playingProgress >= maxProgress * 3 / 4) {
					dLx = (int) (getWidth() / 2 - h);
				} else {
					dLx = getHeight();
				}

				// // 左矩形
				int leftRectButtom = dLx;
				canvas.clipRect(0, leftRectButtom, getWidth() / 2, getHeight());

				canvas.drawCircle(cx, cy, getWidth() / 3, progressPaint);

				canvas.restore();
			}

		}
		super.dispatchDraw(canvas);
	}

	public void setMaxProgress(int maxProgress) {
		this.maxProgress = maxProgress;
	}

	public void setPlayingProgress(int playingProgress) {
		this.playingProgress = playingProgress;
	}

}

redpajama_set_name: RedPajamaGithub


text:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe Mailjet::Resource do

  let(:resource_path) { "test" }
  let(:connection){ MiniTest::Mock.new }

  subject do
    class TestResource
      include Mailjet::Resource
      self.resource_path = "test"
    end
    TestResource.connection = connection
    TestResource
  end

  context "connection is not defined" do
    before(:each) do
      subject.connection = nil
    end

    describe ".connection" do
      it "returns a Mailjet::Connection referring to the \"test\" resource" do
        connection = subject.connection
        connection.must_be_instance_of Mailjet::Connection
        connection.url.must_match "#{Mailjet.config.end_point}/#{resource_path}"
      end
    end
  end

  context "connection is defined" do

    context "GET /test?Limit=1 returns '{\"Data\" : [{ \"Test\" : \"Value\" }]}'" do
      before(:each) do
        @response = '{"Data" : [{ "Test" : "Value" }]}'
        connection.expect :get, @response, [params: {limit: 1}]
      end

      describe ".first" do
        it "creates a new TestResource object" do
          instance = subject.first
          instance.must_be_instance_of TestResource
        end

        it "populates object with attributes returned by the API" do
          instance = subject.first
          instance.test.must_equal "Value"
        end
      end
    end

    context "GET /test returns '{\"Data\" : [{ \"Test1\" : \"Value1\", \"Test1\" : \"Value1\" }]}'" do
      before(:each) do
        @response = '{"Data" : [{ "Test" : "Value1" }, { "Test" : "Value2" }]}'
        connection.expect :get, @response, [params: {}]
      end

      describe ".all" do
        it "creates an array of TestResource objects" do
          instances = subject.all
          instances.each{ |instance| instance.must_be_instance_of TestResource }
        end

        it "populates objects with attributes returned by the API" do
          instances = subject.all
          instances[0].test.must_equal "Value1"
          instances[1].test.must_equal "Value2"
        end
      end
    end

    context "GET /test/id returns '{\"Data\" : [{ \"ID\" : 1, \"Test1\" : \"Value1\"}]}'" do
      before(:each) do
        @id = 1
        @response = "{\"Data\" : [{ \"ID\" : #{@id}, \"Test\" : \"Value1\" }]}"
        connection.expect :[], connection, [@id]
        connection.expect :get, @response
      end

      describe ".find(id)" do

        it "creates an array of TestResource objects" do
          instance = subject.find(@id)
        instance.must_be_instance_of TestResource
        end

        it "populates object with attributes returned by the API" do
          instance = subject.find(@id)
          instance.id.must_equal @id
          instance.test.must_equal "Value1"
        end
      end
    end
  end
end


text: require('gsap/src/uncompressed/plugins/CSSRulePlugin.js');


text:
package test.retryAnalyzer.issue1697;

import org.testng.IRetryAnalyzer;
import org.testng.ITestResult;

public class SimpleRetrier implements IRetryAnalyzer {
  @Override
  public boolean retry(ITestResult result) {
    return true;
  }
}


text:
DVB-T Stream capture testing
============================

A simple DVB library and tools for capturing DVB-T transmission data.

Howto compile:
--------------

Use make :)

Documentation
-------------

See https://katajakasa.fi/projects/dvblib/


text:
class AddDefaultsForFrequenciesToSnps < ActiveRecord::Migration
  def change
    change_column :snps, :allele_frequency, :string, default: "---\nA: 0\nT: 0\nG: 0\nC: 0\n"
    change_column :snps, :genotype_frequency, :string, default: "--- {}\n"
    change_column :snps, :ranking, :integer, default: 0
  end
end


text:
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { Cordova, CordovaInstance, Plugin, pluginWarn, InstanceProperty } from './plugin';
/**
 * @name SQLite
 *
 * @description
 * Access SQLite databases on the device.
 *
 * @usage
 *
 * ```typescript
 * import { SQLite } from 'ionic-native';
 *
 * // OPTION A: Use static constructor
 * SQLite.openDatabase({
 *   name: 'data.db',
 *   location: 'default'
 * })
 *   .then((db: SQLite) => {
 *
 *     db.executeSQL('create table danceMoves(name VARCHAR(32))').then(() => {}).catch(() => {});
 *
 *   })
 *   .catch(error => console.error('Error openening database', error);
 *
 *
 * // OPTION B: Create a new instance of SQLite
 * let db = new SQLite();
 * db.openDatabase({
 *   name: 'data.db',
 *   location: 'default' // the location field is required
 * }).then(() => {
 *   db.executeSql('create table danceMoves(name VARCHAR(32))', {}).then(() => {
 *
 *   }, (err) => {
 *     console.error('Unable to execute sql: ', err);
 *   });
 * }, (err) => {
 *   console.error('Unable to open database: ', err);
 * });
 * ```
 *
 */
export var SQLite = (function () {
    function SQLite() {
    }
    SQLite.openDatabase = function (config) {
        return new SQLite().openDatabase(config);
    };
    /**
     * Open or create a SQLite database file.
     *
     * See the plugin docs for an explanation of all options: https://github.com/litehelpers/Cordova-sqlite-storage#opening-a-database
     *
     * @param config the config for opening the database.
     */
    SQLite.prototype.openDatabase = function (config) {
        var _this = this;
        return new Promise(function (resolve, reject) {
            if (typeof sqlitePlugin !== 'undefined') {
                sqlitePlugin.openDatabase(config, function (db) {
                    _this._objectInstance = db;
                    resolve(db);
                }, function (error) {
                    console.warn(error);
                    reject(error);
                });
            }
            else {
                pluginWarn({
                    pluginName: 'SQLite',
                    plugin: 'cordova-sqlite-storage'
                });
            }
        });
    };
    SQLite.prototype.addTransaction = function (transaction) { };
    /**
     * @param fn {any}
     * @returns {Promise<any>}
     */
    SQLite.prototype.transaction = function (fn) { return; };
    /**
     * @param fn {any}
     * @returns {Promise<any>}
     */
    SQLite.prototype.readTransaction = function (fn) { return; };
    SQLite.prototype.startNextTransaction = function () { };
    /**
     * @returns {Promise<any>}
     */
    SQLite.prototype.close = function () { return; };
    SQLite.prototype.start = function () { };
    /**
     * Execute SQL on the opened database. Note, you must call `openDatabase` first, and
     * ensure it resolved and successfully opened the database.
     */
    SQLite.prototype.executeSql = function (statement, params) { return; };
    /**
     * @param sql
     * @param values
     * @returns {Promise<any>}
     */
    SQLite.prototype.addStatement = function (sql, values) { return; };
    /**
     * @param sqlStatements {any}
     * @returns {Promise<any>}
     */
    SQLite.prototype.sqlBatch = function (sqlStatements) { return; };
    SQLite.prototype.abortallPendingTransactions = function () { };
    /**
     @param handler
     @param response
     */
    SQLite.prototype.handleStatementSuccess = function (handler, response) { };
    /**
     * @param handler
     * @param response
     */
    SQLite.prototype.handleStatementFailure = function (handler, response) { };
    SQLite.prototype.run = function () { };
    /**
     * @param txFailure
     */
    SQLite.prototype.abort = function (txFailure) { };
    SQLite.prototype.finish = function () { };
    /**
     * @param sqlerror
     */
    SQLite.prototype.abortFromQ = function (sqlerror) { };
    /**
     * @returns {Promise<any>}
     */
    SQLite.echoTest = function () { return; };
    /**
     * @param first
     * @returns {Promise<any>}
     */
    SQLite.deleteDatabase = function (first) { return; };
    __decorate([
        InstanceProperty
    ], SQLite.prototype, "databaseFeatures", void 0);
    __decorate([
        CordovaInstance({
            sync: true
        })
    ], SQLite.prototype, "addTransaction", null);
    __decorate([
        CordovaInstance({
            successIndex: 2,
            errorIndex: 1
        })
    ], SQLite.prototype, "transaction", null);
    __decorate([
        CordovaInstance()
    ], SQLite.prototype, "readTransaction", null);
    __decorate([
        CordovaInstance({
            sync: true
        })
    ], SQLite.prototype, "startNextTransaction", null);
    __decorate([
        CordovaInstance()
    ], SQLite.prototype, "close", null);
    __decorate([
        CordovaInstance({
            sync: true
        })
    ], SQLite.prototype, "start", null);
    __decorate([
        CordovaInstance()
    ], SQLite.prototype, "executeSql", null);
    __decorate([
        CordovaInstance()
    ], SQLite.prototype, "addStatement", null);
    __decorate([
        CordovaInstance()
    ], SQLite.prototype, "sqlBatch", null);
    __decorate([
        CordovaInstance({
            sync: true
        })
    ], SQLite.prototype, "abortallPendingTransactions", null);
    __decorate([
        CordovaInstance({
            sync: true
        })
    ], SQLite.prototype, "handleStatementSuccess", null);
    __decorate([
        CordovaInstance({
            sync: true
        })
    ], SQLite.prototype, "handleStatementFailure", null);
    __decorate([
        CordovaInstance({
            sync: true
        })
    ], SQLite.prototype, "run", null);
    __decorate([
        CordovaInstance({
            sync: true
        })
    ], SQLite.prototype, "abort", null);
    __decorate([
        CordovaInstance({
            sync: true
        })
    ], SQLite.prototype, "finish", null);
    __decorate([
        CordovaInstance({
            sync: true
        })
    ], SQLite.prototype, "abortFromQ", null);
    __decorate([
        Cordova()
    ], SQLite, "echoTest", null);
    __decorate([
        Cordova()
    ], SQLite, "deleteDatabase", null);
    SQLite = __decorate([
        Plugin({
            pluginName: 'SQLite',
            pluginRef: 'sqlitePlugin',
            plugin: 'cordova-sqlite-storage',
            repo: 'https://github.com/litehelpers/Cordova-sqlite-storage'
        })
    ], SQLite);
    return SQLite;
}());
//# sourceMappingURL=sqlite.js.map


text:
from msrest.serialization import Model

class PropertiesItem(Model):
    """Defines an item.

    You probably want to use the sub-classes and not this class directly. Known
    sub-classes are: Rating

    Variables are only populated by the server, and will be ignored when
    sending a request.

    All required parameters must be populated in order to send to Azure.

    :ivar text: Text representation of an item.
    :vartype text: str
    :param _type: Required. Constant filled by server.
    :type _type: str
    """

    _validation = {
        'text': {'readonly': True},
        '_type': {'required': True},
    }

    _attribute_map = {
        'text': {'key': 'text', 'type': 'str'},
        '_type': {'key': '_type', 'type': 'str'},
    }

    _subtype_map = {
        '_type': {'Rating': 'Rating'}
    }

    def __init__(self, **kwargs):
        super(PropertiesItem, self).__init__(**kwargs)
        self.text = None
        self._type = None


text:
package org.c02e.jpgpj;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;

import org.bouncycastle.bcpg.PublicKeyAlgorithmTags;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPKeyFlags;
import org.bouncycastle.openpgp.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPSecretKey;
import org.bouncycastle.openpgp.PGPSignature;
import org.bouncycastle.openpgp.PGPSignatureSubpacketVector;
import org.bouncycastle.openpgp.operator.PBESecretKeyDecryptor;
import org.c02e.jpgpj.util.Util;

/**
 * A single public-key pair from a full {@link Key}. It may consist of only
 * the public part of the pair, or it may include both the public
 * and private parts. Each subkey is designated for a specific
 * cryptographic purpose (or purposes), typically either certification
 * (ie signing other keys), encryption, or signing (ie signing messages).
 * The passphrase for a subkey must be provided in order to use its
 * private part (the private part is needed for signing and decryption).
 *

 * The purpose of a subkey is indicated by these four methods:
 *

 *
{@link #isForSigning}: true if should be used for signing messages
 *
{@link #isForVerification}: true if should be used for verifying messages
 *
{@link #isForEncryption}: true if should be used for encrypting messages
 *
{@link #isForDecryption}: true if should be used for decrypting messages
 *

 *

 * By default, when a subkey with a "sign data" flag is loaded, its
 * forVerification property will be set to true; and if the subkey
 * includes the private part of its public-key pair, its
 * forSigning property will also be set to true.
 * When a subkey with a "encrypt communications" or "encrypt storage" flag
 * is loaded, its forEncryption property will be set to true;
 * and if the subkey includes the private part of its public-key pair, its
 * forDecryption property will also be set to true.
 *

 * However, before actually using a subkey for signing or decryption,
 * you must also set the subkey's passphrase, either via the
 * {@link #setPassphraseChars} method on the subkey, or the
 * {@link Key#setPassphraseChars} on its containing {@link Key}.
 * If the subkey does not have a passphrase, set the passphrase to the
 * {@link Key#NO_PASSPHRASE} constant (or use {@link #setNoPassphrase}).
 *

 * When a subkey is used for signing or decryption, its private key material
 * is extracted and cached in memory. To release this memory, call the subkey's
 * {@link #clearSecrets} method. This method will zero-out the subkey's
 * passphrase (if the passphrase had been set as a char[] via
 * {@link #setPassphraseChars}) and release the cached private key material
 * (however, the private key material will not be zeroed-out; also, the
 * passphrase will not be zeroed-out if it was set via {@link #setPassphrase}).
 */
public class Subkey implements Cloneable {
    private static final char[] NO_PASSPHRASE = Key.NO_PASSPHRASE.toCharArray();
    private static final char[] EMPTY_PASSPHRASE = new char[0];

    protected boolean forSigning;
    protected boolean forVerification;
    protected boolean forEncryption;
    protected boolean forDecryption;
    protected char[] passphraseChars;
    /** @deprecated Null unless explicitly set by user. */
    @Deprecated
    protected String passphrase;
    protected PGPPublicKey publicKey;
    protected PGPSecretKey secretKey;
    /** Decrypted private key material. Null unless decrypted. */
    protected PGPPrivateKey privateKey;

    /** Constructs a blank subkey. */
    public Subkey() {
        setPassphraseChars(null);
    }

    /**
     * Display string for the subkey, including its usage flags,
     * short ID, and user IDs.
     */
    @Override
    public String toString() {
        if (publicKey == null) return "nul";

        StringBuilder b = new StringBuilder();
        b.append(secretKey != null ? "sec" : "pub");
        b.append(Util.isEmpty(passphraseChars) && privateKey == null ? ' ' : '+');
        if (forVerification)
            b.append('v');
        else if (forEncryption)
            b.append('e');
        else
            b.append(' ');
        if (forSigning)
            b.append('s');
        else if (forDecryption)
            b.append('d');
        else
            b.append(' ');
        b.append(' ');
        b.append(getShortId());
        int count = 0;
        for (String uid : getUids()) {
            if (count++ > 0)
                b.append(',');
            b.append(' ');
            b.append(uid);
        }
        return b.toString();
    }

    @Override
    public Subkey clone() {
        try {
            Subkey other = getClass().cast(super.clone());
            // Do not use setPassphrasesChars since it checks if different password provided
            other.passphraseChars = (this.passphraseChars == null) ? null : this.passphraseChars.clone();
            return other;
        } catch (CloneNotSupportedException e) {
            throw new UnsupportedOperationException("Unexpected clone failure for " + this);
        }
    }

    /** True if the subkey should be used for signing messages. */
    public boolean isForSigning() {
        return forSigning;
    }

    /** True if the subkey should be used for signing messages. */
    public void setForSigning(boolean x) {
        forSigning = x;
    }

    /** True if the subkey should be used for verifying messages. */
    public boolean isForVerification() {
        return forVerification;
    }

    /** True if the subkey should be used for verifying messages. */
    public void setForVerification(boolean x) {
        forVerification = x;
    }

    /** True if the subkey should be used for encrypting messages. */
    public boolean isForEncryption() {
        return forEncryption;
    }

    /** True if the subkey should be used for encrypting messages. */
    public void setForEncryption(boolean x) {
        forEncryption = x;
    }

    /** True if the subkey should be used for decrypting messages. */
    public boolean isForDecryption() {
        return forDecryption;
    }

    /** True if the subkey should be used for decrypting messages. */
    public void setForDecryption(boolean x) {
        forDecryption = x;
    }

    /** True if technically usable for signing. */
    public boolean isUsableForSigning() {
        return isUsableForVerification() &&
            secretKey != null && !secretKey.isPrivateKeyEmpty();
    }

    /** True if technically usable for verification. */
    public boolean isUsableForVerification() {
        int algorithm = publicKey != null ? publicKey.getAlgorithm() : 0;
        return algorithm == PublicKeyAlgorithmTags.RSA_GENERAL ||
               algorithm == PublicKeyAlgorithmTags.RSA_SIGN ||
               algorithm == PublicKeyAlgorithmTags.DSA ||
               algorithm == PublicKeyAlgorithmTags.ECDSA ||
               algorithm == PublicKeyAlgorithmTags.EDDSA;
    }

    /** True if technically usable for encryption. */
    public boolean isUsableForEncryption() {
        return publicKey != null && publicKey.isEncryptionKey();
    }

    /** True if technically usable for decryption. */
    public boolean isUsableForDecryption() {
        return isUsableForEncryption() &&
            secretKey != null && !secretKey.isPrivateKeyEmpty();
    }

    /**
     * Passphrase needed to unlock the private part
     * of the subkey's public key-pair; or empty char[].
     * Use {@link Key#NO_PASSPHRASE} to signal the private part of the subkey
     * is not protected by a passphrase.
     * Note that this char[] itself (and not a copy) will be cached and used
     * by the subkey until {@link #clearSecrets} is called (or
     * {@link #setPassphraseChars} is called again with a different passphrase),
     * and then the char[] will be zeroed.
     */
    public char[] getPassphraseChars() {
        return passphraseChars;
    }

    /**
     * Passphrase needed to unlock the private part
     * of the subkey's public key-pair; or empty char[].
     * Use {@link Key#NO_PASSPHRASE} to signal the private part of the subkey
     * is not protected by a passphrase.
     * Note that this char[] itself (and not a copy) will be cached and used
     * by the subkey until {@link #clearSecrets} is called (or
     * {@link #setPassphraseChars} is called again with a different passphrase),
     * and then the char[] will be zeroed.
     */
    public void setPassphraseChars(char[] x) {
        if (x == null)
            x = EMPTY_PASSPHRASE;

        if (!Arrays.equals(x, passphraseChars)) {
            clearSecrets();
            passphraseChars = x;
        }
    }

    /**
     * Passphrase needed to unlock the private part
     * of the subkey's public key-pair; or empty string.
     * Prefer {@link #getPassphraseChars} to avoid creating extra copies
     * of the passphrase in memory that cannot be cleaned up.
     * Use {@link Key#NO_PASSPHRASE} to signal the private part of the subkey
     * is not protected by a passphrase.
     * @see #getPassphraseChars
     */
    public String getPassphrase() {
        if (passphrase == null)
            passphrase = new String(passphraseChars);
        return passphrase;
    }

    /**
     * Passphrase needed to unlock the private part
     * of the subkey's public key-pair; or empty string.
     * Prefer {@link #setPassphraseChars} to avoid creating extra copies
     * of the passphrase in memory that cannot be cleaned up.
     * Use {@link Key#NO_PASSPHRASE} to signal the private part of the subkey
     * is not protected by a passphrase.
     * @see #setPassphraseChars
     */
    public void setPassphrase(String x) {
        setPassphraseChars(x != null ? x.toCharArray() : null);
        passphrase = x;
    }

    /**
     * True if no passphrase is needed to unlock the private part
     * of the subkey's public key-pair.
     */
    public boolean isNoPassphrase() {
        return Arrays.equals(passphraseChars, NO_PASSPHRASE);
    }

    /**
     * True if no passphrase is needed to unlock the private part
     * of the subkey's public key-pair.
     */
    public void setNoPassphrase(boolean x) {
        if (x != isNoPassphrase())
            setPassphrase(x ? Key.NO_PASSPHRASE : null);
    }

    /**
     * Bouncy castle public-key pair,
     * containing only the public part of the pair; or null.
     */
    public PGPPublicKey getPublicKey() {
        return publicKey;
    }

    /**
     * Bouncy castle public-key pair,
     * containing only the public part of the pair; or null.
     */
    public void setPublicKey(PGPPublicKey x) throws PGPException {
        publicKey = x;
        calculateUsage();
    }

    /**
     * Bouncy castle public-key pair,
     * containing both the public and private parts of the pair; or null.
     */
    public PGPSecretKey getSecretKey() {
        return secretKey;
    }

    /**
     * Bouncy castle public-key pair,
     * containing both the public and private parts of the pair; or null.
     */
    public void setSecretKey(PGPSecretKey x) throws PGPException {
        secretKey = x;
        if (secretKey != null)
            setPublicKey(secretKey.getPublicKey());
    }

    /**
     * Extracts the Bouncy castle private-key material
     * from this subkey's secret key, using the subkey's passphrase,
     * and caches it in memory until {@link #clearSecrets} is called.
     * @return null if this subkey does not have a secret key.
     * @throws PassphraseException if passphrase is incorrect.
     */
    public PGPPrivateKey getPrivateKey() throws PGPException {
        if (privateKey == null)
            privateKey = extractPrivateKey(passphraseChars);
        return privateKey;
    }

    /**
     * Fingerprint of public key,
     * or empty string if no public key.
     */
    public String getFingerprint() {
        if (publicKey == null) return "";
        return Util.formatAsHex(publicKey.getFingerprint());
    }

    /**
     * Full '0xlong' format of public key,
     * or empty string if no public key.
     */
    public String getId() {
        if (publicKey == null) return "";
        return "0x" + String.format("%016X", publicKey.getKeyID());
    }

    /**
     * Abbreviated 'short' format of public key,
     * or empty string if no public key.
     */
    public String getShortId() {
        if (publicKey == null) return "";
        return String.format("%016X", publicKey.getKeyID()).substring(8);
    }

    /**
     * User ID strings of public key
     * (ex ["My Name (comment) <me@example.com>"]), or empty list.
     */
    public List<String> getUids() {
        if (publicKey == null) return Collections.emptyList();

        ArrayList<String> result = new ArrayList<String>();
        Iterator<String> uids = publicKey.getUserIDs();
        while (uids.hasNext())
            result.add(uids.next());
        return result;
    }

    /**
     * Usage flags as Bouncy castle {@link PGPKeyFlags} bits.
     */
    public int getUsageFlags() throws PGPException {
        if (publicKey == null) return 0;

        int flags = 0;
        // actually only need POSITIVE_CERTIFICATION (for master key)
        // and SUBKEY_BINDING (for subkeys)
        @SuppressWarnings("unchecked")
        Iterator<PGPSignature> signatures = publicKey.getSignatures();
        while (signatures.hasNext()) {
            PGPSignature signature = signatures.next();
            PGPSignatureSubpacketVector hashedSubPackets =
                signature.getHashedSubPackets();

            if (hashedSubPackets != null)
                flags |= hashedSubPackets.getKeyFlags();
        }
        return flags;
    }

    /**
     * True if the string is a case-insensitive substring of either:
     *

     *
the subkey's full ID (eg "0x1234567890ABCDEF");
     *
the subkey's fingerprint (eg "1234567890ABCDEF1234567890ABCDEF12345678");
     *
any subkey's user IDs (eg "Alice (work) <alice@example.com>")
     *

     *

     * So for example, a string "0x1234" would match the above full ID;
     * a string "90ab" would match the above fingerprint;
     * and a string "alice (work)" would match the above user ID.
     */
    public boolean matches(String id) {
        if (Util.isEmpty(id)) return false;

        Pattern regex = Pattern.compile(id,
            Pattern.CASE_INSENSITIVE | Pattern.LITERAL);
        return matches(regex);
    }

    /**
     * True if the specified pattern matches any part of either:
     *

     *
the subkey's full ID (eg "0x1234567890ABCDEF");
     *
the subkey's fingerprint (eg "1234567890ABCDEF1234567890ABCDEF12345678");
     *
any subkey's user IDs (eg "Alice (work) <alice@example.com>")
     *

     *

     * So for example, a pattern /0x1234/ would match the above full ID;
     * a pattern /(?i)90ab/ would match the above fingerprint;
     * and a pattern /Alice .work./ would match the above user ID.
     */
    public boolean matches(Pattern id) {
        if (id == null || publicKey == null) return false;
        if (id.matcher(getFingerprint()).find()) return true;
        if (id.matcher(getId()).find()) return true;

        Iterator<String> uids = publicKey.getUserIDs();
        while (uids.hasNext()) {
            String uid = uids.next();
            if (id.matcher(uid).find()) return true;
        }
        return false;
    }

    /**
     * True if the private key material has been extracted from this subkey's
     * secret key and is currently cached in memory.
     */
    public boolean isUnlocked() {
        return privateKey != null;
    }

    /**
     * Extracts the private key material from this subkey's secret key
     * using the specified passphrase, and caches it in memory
     * until {@link #clearSecrets} is called. Does not cache the passphrase.
     * Does nothing if this subkey does not have a secret key.
     * @throws PassphraseException if passphrase is incorrect.
     */
    public void unlock(char[] passphraseChars) throws PGPException {
        privateKey = extractPrivateKey(passphraseChars);
    }

    /**
     * Zeroes-out the cached passphrase for this subkey,
     * and releases the extracted private key material for garbage collection.
     * Note that if {@link #getPassphrase} or {@link #setPassphrase} is
     * used to access the passphrase, the passphrase data cannot be zeroed
     * (so instead use {@link #getPassphraseChars} and
     * {@link #setPassphraseChars}).
     */
    public void clearSecrets() {
        // zero-out passphrase data
        if (passphraseChars != null)
            Arrays.fill(passphraseChars, (char) 0);
        // flag as empty
        passphraseChars = EMPTY_PASSPHRASE;
        // cannot cleanup futher, release for GC
        passphrase = null;
        // cannot cleanup futher, release for GC
        privateKey = null;
    }

    /**
     * Extracts the private key from this subkey's secret key
     * using the specified passphrase.
     */
    protected PGPPrivateKey extractPrivateKey(char[] passphraseChars)
    throws PGPException {
        if (secretKey == null) return null;
        try {
            return secretKey.extractPrivateKey(buildDecryptor(passphraseChars));
        } catch (PGPException e) {
            throw new PassphraseException(
                "incorrect passphrase for subkey " + this, e);
        }
    }

    /**
     * Builds a secret key decryptor for the specified passphrase.
     */
    protected PBESecretKeyDecryptor buildDecryptor(char[] passphraseChars) throws PGPException {
        char[] chars = passphraseChars != null &&
            !Arrays.equals(passphraseChars, NO_PASSPHRASE) ?
            passphraseChars : EMPTY_PASSPHRASE;
        return JcaContextHelper.getJcePBESecretKeyDecryptorBuilder().build(chars);
    }

    /**
     * Sets forSigning etc flags based on key data.
     */
    protected void calculateUsage() throws PGPException {
        int flags = getUsageFlags();

        boolean canSign = (flags & PGPKeyFlags.CAN_SIGN) ==
            PGPKeyFlags.CAN_SIGN;
        boolean canEncrypt = ((flags & PGPKeyFlags.CAN_ENCRYPT_COMMS) ==
                PGPKeyFlags.CAN_ENCRYPT_COMMS) ||
            ((flags & PGPKeyFlags.CAN_ENCRYPT_STORAGE) ==
                PGPKeyFlags.CAN_ENCRYPT_STORAGE);

        forSigning = canSign && isUsableForSigning();
        forVerification = canSign && isUsableForVerification();
        forEncryption = canEncrypt && isUsableForEncryption();
        forDecryption = canEncrypt && isUsableForDecryption();
    }
}


text:
package com.scwang.smart.refresh.header.material;

import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.support.annotation.ColorInt;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.Transformation;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.List;

/**
 * Fancy progress indicator for Material theme.
 */
@SuppressWarnings({"WeakerAccess"})
public class MaterialProgressDrawable extends Drawable implements Animatable {
    private static final Interpolator LINEAR_INTERPOLATOR = new LinearInterpolator();
    static final Interpolator MATERIAL_INTERPOLATOR = new FastOutSlowInInterpolator();

    private static final float FULL_ROTATION = 1080.0f;

    @Retention(RetentionPolicy.SOURCE)
    @IntDef({LARGE, DEFAULT})
    public @interface ProgressDrawableSize {}

    // Maps to ProgressBar.Large style
    public static final byte LARGE = 0;
    // Maps to ProgressBar default style
    public static final byte DEFAULT = 1;

    // Maps to ProgressBar default style
    private static final byte CIRCLE_DIAMETER = 40;
    private static final float CENTER_RADIUS = 8.75f; //should add up to 10 when + stroke_width
    private static final float STROKE_WIDTH = 2.5f;

    // Maps to ProgressBar.Large style
    private static final byte CIRCLE_DIAMETER_LARGE = 56;
    private static final float CENTER_RADIUS_LARGE = 12.5f;
    private static final float STROKE_WIDTH_LARGE = 3f;

    private static final int[] COLORS = new int[] {
        Color.BLACK
    };

    /**
     * The value in the linear interpolator for animating the drawable at which
     * the color transition should start
     */
    private static final float COLOR_START_DELAY_OFFSET = 0.75f;
    private static final float END_TRIM_START_DELAY_OFFSET = 0.5f;
    private static final float START_TRIM_DURATION_OFFSET = 0.5f;

    /** The duration of a single progress spin in milliseconds. */
    private static final int ANIMATION_DURATION = 1332;

    /** The number of points in the progress "star". */
    private static final byte NUM_POINTS = 5;
    /** The list of animators operating on this drawable. */
    private final List<Animation> mAnimators = new ArrayList<>();

    /** The indicator ring, used to manage animation state. */
    private final Ring mRing = new Ring();

    /** Canvas rotation in degrees. */
    private float mRotation;

    /** Layout info for the arrowhead in dp */
    private static final byte ARROW_WIDTH = 10;
    private static final byte ARROW_HEIGHT = 5;
    private static final float ARROW_OFFSET_ANGLE = 5;

    /** Layout info for the arrowhead for the large spinner in dp */
    private static final byte ARROW_WIDTH_LARGE = 12;
    private static final byte ARROW_HEIGHT_LARGE = 6;
    private static final float MAX_PROGRESS_ARC = .8f;

    private View mParent;
    private Animation mAnimation;
    float mRotationCount;
    private float mWidth;
    private float mHeight;
    boolean mFinishing;
    boolean mIsRunning;

    public MaterialProgressDrawable(View parent) {
        mParent = parent;
        setColorSchemeColors(COLORS);
        updateSizes(DEFAULT);
        setupAnimators();
    }

    private void setSizeParameters(int progressCircleWidth, int progressCircleHeight,
                                   float centerRadius, float strokeWidth, float arrowWidth, float arrowHeight) {
        final DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
        final float screenDensity = metrics.density;

        mWidth = progressCircleWidth * screenDensity;
        mHeight = progressCircleHeight * screenDensity;
        mRing.setColorIndex(0);
        mRing.mPaint.setStrokeWidth(strokeWidth * screenDensity);
        mRing.mStrokeWidth = strokeWidth * screenDensity;
        mRing.mRingCenterRadius = (centerRadius * screenDensity);
        mRing.mArrowWidth = (int) (arrowWidth * screenDensity);
        mRing.mArrowHeight = (int) (arrowHeight * screenDensity);
        mRing.setInsets((int) mWidth, (int) mHeight);
        final Drawable thisDrawable = this;
        thisDrawable.invalidateSelf();
    }

    /*
     * Set the overall size for the progress spinner. This updates the radius
     * and stroke width of the ring.
     */
    public void updateSizes(@ProgressDrawableSize int size) {
        if (size == LARGE) {
            setSizeParameters(CIRCLE_DIAMETER_LARGE, CIRCLE_DIAMETER_LARGE, CENTER_RADIUS_LARGE,
                    STROKE_WIDTH_LARGE, ARROW_WIDTH_LARGE, ARROW_HEIGHT_LARGE);
        } else {
            setSizeParameters(CIRCLE_DIAMETER, CIRCLE_DIAMETER, CENTER_RADIUS, STROKE_WIDTH,
                    ARROW_WIDTH, ARROW_HEIGHT);
        }
    }

    /*
     * @param show Set to true to display the arrowhead on the progress spinner.
     */
    public void showArrow(boolean show) {
        if (mRing.mShowArrow != show) {
            mRing.mShowArrow = show;
            final Drawable thisDrawable = this;
            thisDrawable.invalidateSelf();
        }
    }

    /*
     * @param scale Set the scale of the arrowhead for the spinner.
     */
    public void setArrowScale(float scale) {
        if (mRing.mArrowScale != scale) {
            mRing.mArrowScale = scale;
            final Drawable thisDrawable = this;
            thisDrawable.invalidateSelf();
        }
    }

    /*
     * Set the start and end trim for the progress spinner arc.
     *
     * @param startAngle start angle
     * @param endAngle end angle
     */
    public void setStartEndTrim(float startAngle, float endAngle) {
        mRing.mStartTrim = (startAngle);
        mRing.mEndTrim = (endAngle);
        final Drawable thisDrawable = this;
        thisDrawable.invalidateSelf();
    }

    /*
     * Set the amount of rotation to apply to the progress spinner.
     *
     * @param rotation Rotation is from [0..1]
     */
    public void setProgressRotation(float rotation) {
        mRing.mRotation = (rotation);
        final Drawable thisDrawable = this;
        thisDrawable.invalidateSelf();
    }

    /*
     * Update the background color of the circle image view.
     */
//    public void setBackgroundColor(@ColorInt int color) {
//        mRing.mBackgroundColor = (color);
//    }

    /*
     * Set the colors used in the progress animation from color resources.
     * The first color will also be the color of the bar that grows in response
     * to a user swipe gesture.
     *
     * @param colors
     */
    public void setColorSchemeColors(@ColorInt int... colors) {
        mRing.mColors = (colors);
        mRing.setColorIndex(0);
    }

    @Override
    public int getIntrinsicHeight() {
        return (int) mHeight;
    }

    @Override
    public int getIntrinsicWidth() {
        return (int) mWidth;
    }

    @Override
    public void draw(@NonNull Canvas c) {
        final Drawable thisDrawable = this;
        final Rect bounds = thisDrawable.getBounds();
        final int saveCount = c.save();
        c.rotate(mRotation, bounds.exactCenterX(), bounds.exactCenterY());
        mRing.draw(c, bounds);
        c.restoreToCount(saveCount);
    }

    @Override
    public void setAlpha(int alpha) {
//        mRing.mAlpha = (alpha);
    }

//    public int getAlpha() {
//        return mRing.mAlpha;
//    }

    @Override
    public void setColorFilter(ColorFilter colorFilter) {
        mRing.mPaint.setColorFilter(colorFilter);
        final Drawable thisDrawable = this;
        thisDrawable.invalidateSelf();
    }

    void setRotation(float rotation) {
        mRotation = rotation;
        final Drawable thisDrawable = this;
        thisDrawable.invalidateSelf();
    }

    @Override
    public int getOpacity() {
        return PixelFormat.TRANSLUCENT;
    }

    @Override
    public boolean isRunning() {
        return mIsRunning;
//        final List<Animation> animators = mAnimators;
//        final int N = animators.size();
//        for (int i = 0; i < N; i++) {
//            final Animation animator = animators.get(i);
//            if (animator.hasStarted() && !animator.hasEnded()) {
//                return true;
//            }
//        }
//        return false;
    }

    @Override
    public void start() {
        if (!mIsRunning) {
            mAnimation.reset();
            mRing.storeOriginals();
            // Already showing some part of the ring
            if (mRing.mEndTrim != mRing.mStartTrim) {
                mFinishing = true;
                mAnimation.setDuration(ANIMATION_DURATION / 2);
                mParent.startAnimation(mAnimation);
            } else {
                mRing.setColorIndex(0);
                mRing.resetOriginals();
                mAnimation.setDuration(ANIMATION_DURATION);
                mParent.startAnimation(mAnimation);
            }
            mIsRunning = true;
        }
    }

    @Override
    public void stop() {
        if (mIsRunning) {
            mParent.clearAnimation();
            mRing.setColorIndex(0);
            mRing.resetOriginals();
            showArrow(false);
            setRotation(0);
            mIsRunning = false;
        }
    }

    float getMinProgressArc(Ring ring) {
        return (float) Math.toRadians(
                ring.mStrokeWidth / (2 * Math.PI * ring.mRingCenterRadius));
    }

    // Adapted from ArgbEvaluator.java
    @SuppressWarnings("RedundantCast")
    private int evaluateColorChange(float fraction, int startValue, int endValue) {
        int startA = (startValue >> 24) & 0xff;
        int startR = (startValue >> 16) & 0xff;
        int startG = (startValue >> 8) & 0xff;
        int startB = startValue & 0xff;

        int endA = (endValue >> 24) & 0xff;
        int endR = (endValue >> 16) & 0xff;
        int endG = (endValue >> 8) & 0xff;
        int endB = endValue & 0xff;

        return (int) ((startA + (int) (fraction * (endA - startA))) << 24)
                | (int) ((startR + (int) (fraction * (endR - startR))) << 16)
                | (int) ((startG + (int) (fraction * (endG - startG))) << 8)
                | (int) ((startB + (int) (fraction * (endB - startB))));
    }

    /*
     * Update the ring color if this is within the last 25% of the animation.
     * The new ring color will be a translation from the starting ring color to
     * the next color.
     */
    void updateRingColor(float interpolatedTime, Ring ring) {
        if (interpolatedTime > COLOR_START_DELAY_OFFSET) {
            // scale the interpolatedTime so that the full
            // transformation from 0 - 1 takes place in the
            // remaining time
            ring.mCurrentColor = (evaluateColorChange((interpolatedTime - COLOR_START_DELAY_OFFSET)
                    / (1.0f - COLOR_START_DELAY_OFFSET), ring.getStartingColor(),
                    ring.getNextColor()));
        }
    }

    void applyFinishTranslation(float interpolatedTime, Ring ring) {
        // shrink back down and complete a full rotation before
        // starting other circles
        // Rotation goes between [0..1].
        updateRingColor(interpolatedTime, ring);
        float targetRotation = (float) (Math.floor(ring.mStartingRotation / MAX_PROGRESS_ARC)
                + 1f);
        final float minProgressArc = getMinProgressArc(ring);
        final float startTrim = ring.mStartingStartTrim
                + (ring.mStartingEndTrim - minProgressArc - ring.mStartingStartTrim)
                * interpolatedTime;
        setStartEndTrim(startTrim, ring.mStartingEndTrim);
        final float rotation = ring.mStartingRotation
                + ((targetRotation - ring.mStartingRotation) * interpolatedTime);
        setProgressRotation(rotation);
    }

    private void setupAnimators() {
        final Ring ring = mRing;
        final Animation animation = new Animation() {
                @Override
            public void applyTransformation(float interpolatedTime, Transformation t) {
                if (mFinishing) {
                    applyFinishTranslation(interpolatedTime, ring);
                } else {
                    // The minProgressArc is calculated from 0 to create an
                    // angle that matches the stroke width.
                    final float minProgressArc = getMinProgressArc(ring);
                    final float startingEndTrim = ring.mStartingEndTrim;
                    final float startingTrim = ring.mStartingStartTrim;
                    final float startingRotation = ring.mStartingRotation;

                    updateRingColor(interpolatedTime, ring);

                    // Moving the start trim only occurs in the first 50% of a
                    // single ring animation
                    if (interpolatedTime <= START_TRIM_DURATION_OFFSET) {
                        // scale the interpolatedTime so that the full
                        // transformation from 0 - 1 takes place in the
                        // remaining time
                        final float scaledTime = (interpolatedTime)
                                / (1.0f - START_TRIM_DURATION_OFFSET);
                        ring.mStartTrim = (startingTrim
                                + ((MAX_PROGRESS_ARC - minProgressArc) * MATERIAL_INTERPOLATOR
                                        .getInterpolation(scaledTime)));
                    }

                    // Moving the end trim starts after 50% of a single ring
                    // animation completes
                    if (interpolatedTime > END_TRIM_START_DELAY_OFFSET) {
                        // scale the interpolatedTime so that the full
                        // transformation from 0 - 1 takes place in the
                        // remaining time
                        final float minArc = MAX_PROGRESS_ARC - minProgressArc;
                        float scaledTime = (interpolatedTime - START_TRIM_DURATION_OFFSET)
                                / (1.0f - START_TRIM_DURATION_OFFSET);
                        ring.mEndTrim = (startingEndTrim
                                + (minArc * MATERIAL_INTERPOLATOR.getInterpolation(scaledTime)));
                    }

                    setProgressRotation(startingRotation + (0.25f * interpolatedTime));

                    float groupRotation = ((FULL_ROTATION / NUM_POINTS) * interpolatedTime)
                            + (FULL_ROTATION * (mRotationCount / NUM_POINTS));
                    setRotation(groupRotation);
                }
            }
        };
        animation.setRepeatCount(Animation.INFINITE);
        animation.setRepeatMode(Animation.RESTART);
        animation.setInterpolator(LINEAR_INTERPOLATOR);
        animation.setAnimationListener(new Animation.AnimationListener() {

                @Override
            public void onAnimationStart(Animation animation) {
                mRotationCount = 0;
            }

                @Override
            public void onAnimationEnd(Animation animation) {
                // do nothing
            }

                @Override
            public void onAnimationRepeat(Animation animation) {
                ring.storeOriginals();
                ring.goToNextColor();
                ring.mStartTrim = (ring.mEndTrim);
                if (mFinishing) {
                    // finished closing the last ring from the swipe gesture; go
                    // into progress mode
                    mFinishing = false;
                    animation.setDuration(ANIMATION_DURATION);
                    showArrow(false);
                } else {
                    mRotationCount = (mRotationCount + 1) % (NUM_POINTS);
                }
            }
        });
        mAnimation = animation;
    }

    private class Ring {
        final RectF mTempBounds = new RectF();
        final Paint mPaint = new Paint();
        final Paint mArrowPaint = new Paint();

        float mStartTrim = 0.0f;
        float mEndTrim = 0.0f;
        float mRotation = 0.0f;
        float mStrokeWidth = 5.0f;
        float mStrokeInset = 2.5f;

        int[] mColors;
        // mColorIndex represents the offset into the available mColors that the
        // progress circle should currently display. As the progress circle is
        // animating, the mColorIndex moves by one to the next available color.
        int mColorIndex;
        float mStartingStartTrim;
        float mStartingEndTrim;
        float mStartingRotation;
        boolean mShowArrow;
        Path mArrow;
        float mArrowScale;
        double mRingCenterRadius;
        int mArrowWidth;
        int mArrowHeight;
//        int mAlpha;
//        final Paint mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
//        int mBackgroundColor;
        int mCurrentColor;

        Ring() {
            mPaint.setStrokeCap(Paint.Cap.SQUARE);
            mPaint.setAntiAlias(true);
            mPaint.setStyle(Style.STROKE);

            mArrowPaint.setStyle(Style.FILL);
            mArrowPaint.setAntiAlias(true);
        }

        /*
         * Draw the progress spinner
         */
        public void draw(Canvas c, Rect bounds) {
            final RectF arcBounds = mTempBounds;
            arcBounds.set(bounds);
            arcBounds.inset(mStrokeInset, mStrokeInset);

            final float startAngle = (mStartTrim + mRotation) * 360;
            final float endAngle = (mEndTrim + mRotation) * 360;
            float sweepAngle = endAngle - startAngle;

            if (sweepAngle != 0) {
                mPaint.setColor(mCurrentColor);
                c.drawArc(arcBounds, startAngle, sweepAngle, false, mPaint);
            }

            drawTriangle(c, startAngle, sweepAngle, bounds);

//            if (mAlpha < 255) {
//                mCirclePaint.setColor(mBackgroundColor);
//                mCirclePaint.setAlpha(255 - mAlpha);
//                c.drawCircle(bounds.exactCenterX(), bounds.exactCenterY(), bounds.width() / 2f,
//                        mCirclePaint);
//            }
        }

        private void drawTriangle(Canvas c, float startAngle, float sweepAngle, Rect bounds) {
            if (mShowArrow) {
                if (mArrow == null) {
                    mArrow = new Path();
                    mArrow.setFillType(Path.FillType.EVEN_ODD);
                } else {
                    mArrow.reset();
                }

                // Adjust the position of the triangle so that it is inset as
                // much as the arc, but also centered on the arc.
                float inset = (float) ((int) mStrokeInset / 2) * mArrowScale;
                float x = (float) (mRingCenterRadius * Math.cos(0) + bounds.exactCenterX());
                float y = (float) (mRingCenterRadius * Math.sin(0) + bounds.exactCenterY());

                // Update the path each time. This works around an issue in SKIA
                // where concatenating a rotation matrix to a scale matrix
                // ignored a starting negative rotation. This appears to have
                // been fixed as of API 21.
                mArrow.moveTo(0, 0);
                mArrow.lineTo(mArrowWidth * mArrowScale, 0);
                mArrow.lineTo((mArrowWidth * mArrowScale / 2), (mArrowHeight
                        * mArrowScale));
                mArrow.offset(x - inset, y);
                mArrow.close();
                // draw a triangle
                mArrowPaint.setColor(mCurrentColor);
                c.rotate(startAngle + sweepAngle - ARROW_OFFSET_ANGLE, bounds.exactCenterX(),
                        bounds.exactCenterY());
                c.drawPath(mArrow, mArrowPaint);
            }
        }

        /*
         * @param index Index into the color array of the color to display in
         *            the progress spinner.
         */
        public void setColorIndex(int index) {
            mColorIndex = index;
            mCurrentColor = mColors[mColorIndex];
        }

        /*
         * @return int describing the next color the progress spinner should use when drawing.
         */
        public int getNextColor() {
            return mColors[getNextColorIndex()];
        }

        private int getNextColorIndex() {
            return (mColorIndex + 1) % (mColors.length);
        }

        /*
         * Proceed to the next available ring color. This will automatically
         * wrap back to the beginning of colors.
         */
        public void goToNextColor() {
            setColorIndex(getNextColorIndex());
        }

        public int getStartingColor() {
            return mColors[mColorIndex];
        }

        public void setInsets(int width, int height) {
            final float minEdge = (float) Math.min(width, height);
            float insets;
            if (mRingCenterRadius <= 0 || minEdge < 0) {
                insets = (float) Math.ceil(mStrokeWidth / 2.0f);
            } else {
                insets = (float) (minEdge / 2.0f - mRingCenterRadius);
            }
            mStrokeInset = insets;
        }

        /*
         * If the start / end trim are offset to begin with, store them so that
         * animation starts from that offset.
         */
        public void storeOriginals() {
            mStartingStartTrim = mStartTrim;
            mStartingEndTrim = mEndTrim;
            mStartingRotation = mRotation;
        }

        /*
         * Reset the progress spinner to default rotation, start and end angles.
         */
        public void resetOriginals() {
            mStartingStartTrim = 0;
            mStartingEndTrim = 0;
            mStartingRotation = 0;
            mStartTrim = (0);
            mEndTrim = (0);
            mRotation = (0);
        }
    }
}


text:
import * as assert from 'assert';
import {describe} from 'mocha';

import {BindingTarget} from '../../common/binding/target';
import {NumberColorInputPlugin} from './plugin-number';

describe('NumberColorInputPlugin', () => {
	[
		{
			view: 'color',
		},
		{
			color: {},
		},
		{
			color: {type: 'float'},
		},
	].forEach((params) => {
		context(`when params=${JSON.stringify(params)}`, () => {
			const input = {
				color: 0x00000000,
			};
			const result = NumberColorInputPlugin.accept(input.color, params);

			it('should accept params', () => {
				assert.ok(result !== null);
			});
		});
	});

	[
		{
			params: {
				view: 'color',
			},
			expected: 1,
		},
		{
			params: {
				alpha: true,
				view: 'color',
			},
			expected: 0,
		},
		{
			params: {
				color: {
					alpha: true,
				},
			},
			expected: 0,
		},
	].forEach(({params, expected}) => {
		context(`when params=${JSON.stringify(params)}`, () => {
			const input = {
				color: 0xffffff00,
			};
			const result = NumberColorInputPlugin.accept(input.color, params);
			if (!result) {
				throw new Error('unexpected result');
			}
			const reader = NumberColorInputPlugin.binding.reader({
				initialValue: input.color,
				params: result.params,
				target: new BindingTarget(input, 'color'),
			});

			it('should apply alpha', () => {
				const c = reader(input.color);
				assert.strictEqual(c.getComponents('rgb', 'int')[3], expected);
			});
		});
	});
});


text:
package com.unitybars.r2d2.service.sender;

import com.unitybars.r2d2.entity.CheckLog;
import com.unitybars.r2d2.entity.MailSettings;
import com.unitybars.r2d2.entity.Recipient;
import com.unitybars.r2d2.exception.ContentTransformationException;
import com.unitybars.r2d2.service.SettingsService;
import freemarker.template.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * Created by oleg.nestyuk
 * Date: 19-Dec-16.
 */
@Service
public class MailSender implements Sender {
    @Autowired
    private SettingsService settingsService;
    @Autowired
    private Configuration freemarkerConfiguration;

    private Logger logger = LoggerFactory.getLogger(MailSender.class);

    public void setSettingsService(SettingsService settingsService) {
        this.settingsService = settingsService;
    }

    @Override
    public void send(String subject, String message, List<Recipient> recipients) {
        if (recipients != null && recipients.size() > 0) {
            try {
                JavaMailSender javaMailSender = createJavaMailSender();
                MimeMessage mimeMessage = javaMailSender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, false, "utf-8");
                mimeMessage.setContent(message, "text/html; charset=UTF-8");
                helper.setTo(recipients.stream().map(Recipient::getEmail).toArray(String[]::new));
                helper.setSubject(subject);
                helper.setFrom(settingsService.getMailSettings().getUsername());
                javaMailSender.send(mimeMessage);
            } catch (MessagingException e) {
                logger.error("Error happened when try to send message" + e);
            }
        }
    }

    @Override
    public String transform(CheckLog checkLog) throws ContentTransformationException {
        try {
            Map<String, Object> objectsMap = new HashMap<String, Object>() {
                {
                    put("status", checkLog.getStatus());
                    put("checklog", checkLog);
                }
            };
            return FreeMarkerTemplateUtils.processTemplateIntoString(
                    freemarkerConfiguration.getTemplate("mail.html"), objectsMap);
        } catch (Exception e) {
            logger.error("Exception occurred while processing fmtemplate:", e);
            throw new ContentTransformationException();
        }
    }

    public JavaMailSender createJavaMailSender() {
        MailSettings mailSettings = settingsService.getMailSettings();
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        Properties mailProperties = new Properties();
        if (mailSettings.isStartTlsEnable()) {
            mailProperties.put("mail.smtp.starttls.enable", true);
        }
        mailSender.setJavaMailProperties(mailProperties);
        mailSender.setHost(mailSettings.getHost());
        mailSender.setPort(Integer.parseInt(mailSettings.getPort()));
        mailSender.setProtocol("smtp");
        mailSender.setUsername(mailSettings.getUsername());
        mailSender.setPassword(mailSettings.getPassword());
        return mailSender;
    }
}


text:
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Frapid.ApplicationState.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Frapid.Config.DataAccess;
using Frapid.Config.Api.Fakes;
using Xunit;

namespace Frapid.Config.Api.Tests
{
    public class FilterNameViewTests
    {
        public static FilterNameViewController Fixture()
        {
            FilterNameViewController controller = new FilterNameViewController(new FilterNameViewRepository(), "", new LoginView());
            return controller;
        }

        [Fact]
        [Conditional("Debug")]
        public void Count()
        {
            long count = Fixture().Count();
            Assert.Equal(1, count);
        }

        [Fact]
        [Conditional("Debug")]
        public void Get()
        {
            int count = Fixture().Get().Count();
            Assert.Equal(1, count);
        }

        [Fact]
        [Conditional("Debug")]
        public void GetPaginatedResult()
        {
            int count = Fixture().GetPaginatedResult().Count();
            Assert.Equal(1, count);

            count = Fixture().GetPaginatedResult(1).Count();
            Assert.Equal(1, count);
        }

        [Fact]
        [Conditional("Debug")]
        public void CountWhere()
        {
            long count = Fixture().CountWhere(new JArray());
            Assert.Equal(1, count);
        }

        [Fact]
        [Conditional("Debug")]
        public void GetWhere()
        {
            int count = Fixture().GetWhere(1, new JArray()).Count();
            Assert.Equal(1, count);
        }

        [Fact]
        [Conditional("Debug")]
        public void CountFiltered()
        {
            long count = Fixture().CountFiltered("");
            Assert.Equal(1, count);
        }

        [Fact]
        [Conditional("Debug")]
        public void GetFiltered()
        {
            int count = Fixture().GetFiltered(1, "").Count();
            Assert.Equal(1, count);
        }

    }
}


text:
[![Build Status](https://api.travis-ci.com/realityforge/ssrs-api.svg?branch=master)](http://travis-ci.com/realityforge/ssrs-api)

This is a small library to abstract interaction with SSRS server via SOAP. Mostly used from [rptman](https://github.com/realityforge/rptman).


text:
import logging
import os
import sys

from celery import Celery
from kombu import Exchange, Queue

app = Celery('celery_bungiesearch')
app.config_from_object('django.conf:settings')

logging.getLogger('elasticsearch').setLevel(logging.ERROR)
logging.getLogger('urllib3').setLevel(logging.ERROR)

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
sys.path.insert(0, BASE_DIR)

SECRET_KEY = 'bungiesearching'
INSTALLED_APPS = (
    'bungiesearch',
    'celery_bungiesearch',
    'core',
    'djcelery'
)
ROOT_URLCONF = 'urls'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': ':memory:',
    }
}

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_TZ = True
DEBUG = False
MIDDLEWARE_CLASSES = ()
DEFAULT_INDEX_TABLESPACE = ''

BUNGIESEARCH = {
    'URLS': [os.getenv('ELASTIC_SEARCH_URL', 'http://127.0.0.1:9200')],
    'INDICES': {'celery_bungiesearch_demo': 'core.indices'},
    'SIGNALS': {
        'SIGNAL_CLASS': 'celery_bungiesearch.signals.CelerySignalProcessor',
        'BUFFER_SIZE': 1
    },
    'TIMEOUT': 5,
    'ES_SETTINGS': {'http_auth': os.getenv('ELASTIC_SEARCH_AUTH')}
}

CELERY_ALWAYS_EAGER = True
CELERY_IGNORE_RESULT = True
CELERYD_LOG_LEVEL = 'ERROR'
CELERY_DEFAULT_QUEUE = 'celery-bungiesearch'
CELERY_BUNGIESEARCH_QUEUE = Queue('default', Exchange('default'), routing_key='default')
CELERY_BUNGIESEARCH_CUSTOM_TASK = 'tests.core.custom_task.CustomTask'


text:
<?php

namespace App\Http\Livewire;

use App\Models\Configs;
use Config;
use Livewire\Component;

class Header extends Component
{
	/**
	 * @var string
	 */
	public $title = '';

	/**
	 * @var string
	 */
	public $mode;

	public function mount(?string $mode = 'albums', $album = null)
	{
		$this->title = Configs::get_value('site_title', Config::get('defines.defaults.SITE_TITLE'));
		if ($album != null) {
			$this->title = $album->title;
		}
		$this->mode = $mode ?? 'albums';
	}

	public function render()
	{
		return view('livewire.header');
	}
}


text:
namespace DotNetThumborTest.TestThumborFilters
{
    using DotNetThumbor;

    using FluentAssertions;

    using NUnit.Framework;

    [TestFixture]
    public class TestNoise
    {
        [Test]
        [TestCase(2)]
        [TestCase(20)]
        public void ThumborNoiseFilter(int noise)
        {
            var thumbor = new Thumbor("http://localhost/");
            var resizedUrl = thumbor.BuildImage("http://localhost/image.jpg")
                                    .Noise(noise)
                                    .ToFullUrl();
            resizedUrl.Should().Be(string.Format("http://localhost/unsafe/filters:noise({0})/http://localhost/image.jpg", noise));
        }
    }
}


text:
package redis

import (
	"fmt"
	"net"
	"strconv"
	"strings"
	"time"

	"golang.org/x/net/context"

	"github.com/CodisLabs/codis/pkg/utils/errors"
	"github.com/CodisLabs/codis/pkg/utils/sync2/atomic2"

	redigo "github.com/garyburd/redigo/redis"
)

type Sentinel struct {
	context.Context
	Cancel context.CancelFunc

	Product, Auth string

	LogFunc func(format string, args ...interface{})
	ErrFunc func(err error, format string, args ...interface{})
}

func NewSentinel(product, auth string) *Sentinel {
	s := &Sentinel{Product: product, Auth: auth}
	s.Context, s.Cancel = context.WithCancel(context.Background())
	return s
}

func (s *Sentinel) IsCanceled() bool {
	select {
	case <-s.Context.Done():
		return true
	default:
		return false
	}
}

func (s *Sentinel) NodeName(gid int) string {
	return fmt.Sprintf("%s-%d", s.Product, gid)
}

func (s *Sentinel) isSameProduct(name string) (gid int, _ bool) {
	if !strings.HasPrefix(name, s.Product) {
		return 0, false
	}
	var suffix = name[len(s.Product):]
	if len(suffix) <= 1 || suffix[0] != '-' {
		return 0, false
	}
	n, err := strconv.Atoi(suffix[1:])
	if err != nil {
		return 0, false
	}
	return n, true
}

func (s *Sentinel) printf(format string, args ...interface{}) {
	if s.LogFunc != nil {
		s.LogFunc(format, args...)
	}
}

func (s *Sentinel) errorf(err error, format string, args ...interface{}) {
	if s.ErrFunc != nil {
		s.ErrFunc(err, format, args...)
	}
}

func (s *Sentinel) do(sentinel string, timeout time.Duration,
	fn func(client *Client) error) error {
	c, err := NewClientNoAuth(sentinel, timeout)
	if err != nil {
		return err
	}
	defer c.Close()
	return fn(c)
}

func (s *Sentinel) dispatch(ctx context.Context, sentinel string, timeout time.Duration,
	fn func(client *Client) error) error {
	c, err := NewClientNoAuth(sentinel, timeout)
	if err != nil {
		return err
	}
	defer c.Close()

	var exit = make(chan error, 1)

	go func() {
		exit <- fn(c)
	}()

	select {
	case <-ctx.Done():
		return errors.Trace(ctx.Err())
	case err := <-exit:
		return err
	}
}

func (s *Sentinel) subscribeCommand(client *Client, sentinel string,
	onSubscribed func()) error {
	var channels = []interface{}{"+switch-master"}
	go func() {
		client.conn.Send("SUBSCRIBE", channels...)
		client.conn.Flush()
	}()
	for _, sub := range channels {
		values, err := redigo.Values(client.Receive())
		if err != nil {
			return errors.Trace(err)
		} else if len(values) != 3 {
			return errors.Errorf("invalid response = %v", values)
		}
		s, err := redigo.Strings(values[:2], nil)
		if err != nil || s[0] != "subscribe" || s[1] != sub.(string) {
			return errors.Errorf("invalid response = %v", values)
		}
	}
	onSubscribed()
	for {
		values, err := redigo.Values(client.Receive())
		if err != nil {
			return errors.Trace(err)
		} else if len(values) < 2 {
			return errors.Errorf("invalid response = %v", values)
		}
		message, err := redigo.Strings(values, nil)
		if err != nil || message[0] != "message" {
			return errors.Errorf("invalid response = %v", values)
		}
		s.printf("sentinel-[%s] subscribe event %v", sentinel, message)

		switch message[1] {
		case "+switch-master":
			if len(message) != 3 {
				return errors.Errorf("invalid response = %v", values)
			}
			var params = strings.SplitN(message[2], " ", 2)
			if len(params) != 2 {
				return errors.Errorf("invalid response = %v", values)
			}
			_, yes := s.isSameProduct(params[0])
			if yes {
				return nil
			}
		}
	}
}

func (s *Sentinel) subscribeDispatch(ctx context.Context, sentinel string, timeout time.Duration,
	onSubscribed func()) (bool, error) {
	var err = s.dispatch(ctx, sentinel, timeout, func(c *Client) error {
		return s.subscribeCommand(c, sentinel, onSubscribed)
	})
	if err != nil {
		switch errors.Cause(err) {
		case context.Canceled, context.DeadlineExceeded:
			return false, nil
		default:
			return false, err
		}
	}
	return true, nil
}

func (s *Sentinel) Subscribe(sentinels []string, timeout time.Duration, onMajoritySubscribed func()) bool {
	cntx, cancel := context.WithTimeout(s.Context, timeout)
	defer cancel()

	timeout += time.Second * 5
	results := make(chan bool, len(sentinels))

	var majority = 1 + len(sentinels)/2

	var subscribed atomic2.Int64
	for i := range sentinels {
		go func(sentinel string) {
			notified, err := s.subscribeDispatch(cntx, sentinel, timeout, func() {
				if subscribed.Incr() == int64(majority) {
					onMajoritySubscribed()
				}
			})
			if err != nil {
				s.errorf(err, "sentinel-[%s] subscribe failed", sentinel)
			}
			results <- notified
		}(sentinels[i])
	}

	for alive := len(sentinels); ; alive-- {
		if alive < majority {
			if cntx.Err() == nil {
				s.printf("sentinel subscribe lost majority (%d/%d)", alive, len(sentinels))
			}
			return false
		}
		select {
		case <-cntx.Done():
			if cntx.Err() != context.DeadlineExceeded {
				s.printf("sentinel subscribe canceled (%v)", cntx.Err())
			}
			return false
		case notified := <-results:
			if notified {
				s.printf("sentinel subscribe notified +switch-master")
				return true
			}
		}
	}
}

func (s *Sentinel) existsCommand(client *Client, names []string) (map[string]bool, error) {
	go func() {
		for _, name := range names {
			client.conn.Send("SENTINEL", "get-master-addr-by-name", name)
		}
		if len(names) != 0 {
			client.conn.Flush()
		}
	}()
	exists := make(map[string]bool, len(names))
	for _, name := range names {
		r, err := client.Receive()
		if err != nil {
			return nil, errors.Trace(err)
		}
		exists[name] = (r != nil)
	}
	return exists, nil
}

func (s *Sentinel) slavesCommand(client *Client, names []string) (map[string][]map[string]string, error) {
	exists, err := s.existsCommand(client, names)
	if err != nil {
		return nil, err
	}
	go func() {
		var pending int
		for _, name := range names {
			if !exists[name] {
				continue
			}
			pending++
			client.conn.Send("SENTINEL", "slaves", name)
		}
		if pending != 0 {
			client.conn.Flush()
		}
	}()
	results := make(map[string][]map[string]string, len(names))
	for _, name := range names {
		if !exists[name] {
			continue
		}
		values, err := redigo.Values(client.Receive())
		if err != nil {
			return nil, errors.Trace(err)
		}
		var slaves []map[string]string
		for i := range values {
			m, err := redigo.StringMap(values[i], nil)
			if err != nil {
				return nil, errors.Trace(err)
			}
			slaves = append(slaves, m)
		}
		results[name] = slaves
	}
	return results, nil
}

func (s *Sentinel) mastersCommand(client *Client) (map[int]map[string]string, error) {
	values, err := redigo.Values(client.Do("SENTINEL", "masters"))
	if err != nil {
		return nil, errors.Trace(err)
	}
	var masters = make(map[int]map[string]string)
	for i := range values {
		p, err := redigo.StringMap(values[i], nil)
		if err != nil {
			return nil, errors.Trace(err)
		}
		gid, yes := s.isSameProduct(p["name"])
		if yes {
			masters[gid] = p
		}
	}
	return masters, nil
}

func (s *Sentinel) mastersDispatch(ctx context.Context, sentinel string, timeout time.Duration) (map[int]*SentinelMaster, error) {
	var masters = make(map[int]*SentinelMaster)
	var err = s.dispatch(ctx, sentinel, timeout, func(c *Client) error {
		p, err := s.mastersCommand(c)
		if err != nil {
			return err
		}
		for gid, master := range p {
			epoch, err := strconv.ParseInt(master["config-epoch"], 10, 64)
			if err != nil {
				s.printf("sentinel-[%s] masters parse %s failed, config-epoch = '%s', %s",
					sentinel, master["name"], master["config-epoch"], err)
				continue
			}
			var ip, port = master["ip"], master["port"]
			if ip == "" || port == "" {
				s.printf("sentinel-[%s] masters parse %s failed, ip:port = '%s:%s'",
					sentinel, master["name"], ip, port)
				continue
			}
			masters[gid] = &SentinelMaster{
				Addr: net.JoinHostPort(ip, port),
				Info: master, Epoch: epoch,
			}
		}
		return nil
	})
	if err != nil {
		switch errors.Cause(err) {
		case context.Canceled:
			return nil, nil
		default:
			return nil, err
		}
	}
	return masters, nil
}

type SentinelMaster struct {
	Addr  string
	Info  map[string]string
	Epoch int64
}

func (s *Sentinel) Masters(sentinels []string, timeout time.Duration) (map[int]string, error) {
	cntx, cancel := context.WithTimeout(s.Context, timeout)
	defer cancel()

	timeout += time.Second * 5
	results := make(chan map[int]*SentinelMaster, len(sentinels))

	var majority = 1 + len(sentinels)/2

	for i := range sentinels {
		go func(sentinel string) {
			masters, err := s.mastersDispatch(cntx, sentinel, timeout)
			if err != nil {
				s.errorf(err, "sentinel-[%s] masters failed", sentinel)
			}
			results <- masters
		}(sentinels[i])
	}

	masters := make(map[int]string)
	current := make(map[int]*SentinelMaster)

	var voted int
	for alive := len(sentinels); ; alive-- {
		if alive == 0 {
			switch {
			case cntx.Err() != context.DeadlineExceeded && cntx.Err() != nil:
				s.printf("sentinel masters canceled (%v)", cntx.Err())
				return nil, errors.Trace(cntx.Err())
			case voted != len(sentinels):
				s.printf("sentinel masters voted = (%d/%d) masters = %d (%v)", voted, len(sentinels), len(masters), cntx.Err())
			}
			if voted < majority {
				return nil, errors.Errorf("lost majority (%d/%d)", voted, len(sentinels))
			}
			return masters, nil
		}
		select {
		case <-cntx.Done():
			switch {
			case cntx.Err() != context.DeadlineExceeded:
				s.printf("sentinel masters canceled (%v)", cntx.Err())
				return nil, errors.Trace(cntx.Err())
			default:
				s.printf("sentinel masters voted = (%d/%d) masters = %d (%v)", voted, len(sentinels), len(masters), cntx.Err())
			}
			if voted < majority {
				return nil, errors.Errorf("lost majority (%d/%d)", voted, len(sentinels))
			}
			return masters, nil
		case m := <-results:
			if m == nil {
				continue
			}
			for gid, master := range m {
				if current[gid] == nil || current[gid].Epoch < master.Epoch {
					current[gid] = master
					masters[gid] = master.Addr
				}
			}
			voted += 1
		}
	}
}

type MonitorConfig struct {
	Quorum          int
	ParallelSyncs   int
	DownAfter       time.Duration
	FailoverTimeout time.Duration

	NotificationScript   string
	ClientReconfigScript string
}

func (s *Sentinel) monitorGroupsCommand(client *Client, sentniel string, config *MonitorConfig, groups map[int]*net.TCPAddr) error {
	var names []string
	for gid := range groups {
		names = append(names, s.NodeName(gid))
	}
	if err := s.removeCommand(client, names); err != nil {
		return err
	}
	go func() {
		for gid, tcpAddr := range groups {
			var ip, port = tcpAddr.IP.String(), tcpAddr.Port
			client.conn.Send("SENTINEL", "monitor", s.NodeName(gid), ip, port, config.Quorum)
		}
		if len(groups) != 0 {
			client.conn.Flush()
		}
	}()
	for range groups {
		_, err := client.Receive()
		if err != nil {
			return errors.Trace(err)
		}
	}
	go func() {
		for gid := range groups {
			var args = []interface{}{"set", s.NodeName(gid)}
			if config.ParallelSyncs != 0 {
				args = append(args, "parallel-syncs", config.ParallelSyncs)
			}
			if config.DownAfter != 0 {
				args = append(args, "down-after-milliseconds", int(config.DownAfter/time.Millisecond))
			}
			if config.FailoverTimeout != 0 {
				args = append(args, "failover-timeout", int(config.FailoverTimeout/time.Millisecond))
			}
			if s.Auth != "" {
				args = append(args, "auth-pass", s.Auth)
			}
			if config.NotificationScript != "" {
				args = append(args, "notification-script", config.NotificationScript)
			}
			if config.ClientReconfigScript != "" {
				args = append(args, "client-reconfig-script", config.ClientReconfigScript)
			}
			client.conn.Send("SENTINEL", args...)
		}
		if len(groups) != 0 {
			client.conn.Flush()
		}
	}()
	for range groups {
		_, err := client.Receive()
		if err != nil {
			return errors.Trace(err)
		}
	}
	return nil
}

func (s *Sentinel) monitorGroupsDispatch(ctx context.Context, sentinel string, timeout time.Duration,
	config *MonitorConfig, groups map[int]*net.TCPAddr) error {
	var err = s.dispatch(ctx, sentinel, timeout, func(c *Client) error {
		return s.monitorGroupsCommand(c, sentinel, config, groups)
	})
	if err != nil {
		switch errors.Cause(err) {
		case context.Canceled:
			return nil
		default:
			return err
		}
	}
	return nil
}

func (s *Sentinel) MonitorGroups(sentinels []string, timeout time.Duration, config *MonitorConfig, groups map[int]string) error {
	cntx, cancel := context.WithTimeout(s.Context, timeout)
	defer cancel()

	resolve := make(map[int]*net.TCPAddr)

	var exit = make(chan error, 1)

	go func() (err error) {
		defer func() {
			exit <- err
		}()
		for gid, addr := range groups {
			if err := cntx.Err(); err != nil {
				return errors.Trace(err)
			}
			tcpAddr, err := net.ResolveTCPAddr("tcp", addr)
			if err != nil {
				s.printf("sentinel monitor resolve tcp address of %s failed, %s", addr, err)
				return errors.Trace(err)
			}
			resolve[gid] = tcpAddr
		}
		return nil
	}()

	select {
	case <-cntx.Done():
		if cntx.Err() != context.DeadlineExceeded {
			s.printf("sentinel monitor canceled (%v)", cntx.Err())
		} else {
			s.printf("sentinel montior resolve tcp address (%v)", cntx.Err())
		}
		return errors.Trace(cntx.Err())
	case err := <-exit:
		if err != nil {
			return err
		}
	}

	timeout += time.Second * 5
	results := make(chan error, len(sentinels))

	for i := range sentinels {
		go func(sentinel string) {
			err := s.monitorGroupsDispatch(cntx, sentinel, timeout, config, resolve)
			if err != nil {
				s.errorf(err, "sentinel-[%s] monitor failed", sentinel)
			}
			results <- err
		}(sentinels[i])
	}

	var last error
	for range sentinels {
		select {
		case <-cntx.Done():
			if last != nil {
				return last
			}
			return errors.Trace(cntx.Err())
		case err := <-results:
			if err != nil {
				last = err
			}
		}
	}
	return last
}

func (s *Sentinel) removeCommand(client *Client, names []string) error {
	exists, err := s.existsCommand(client, names)
	if err != nil {
		return err
	}
	go func() {
		var pending int
		for _, name := range names {
			if !exists[name] {
				continue
			}
			pending++
			client.conn.Send("SENTINEL", "remove", name)
		}
		if pending != 0 {
			client.conn.Flush()
		}
	}()
	for _, name := range names {
		if !exists[name] {
			continue
		}
		_, err := client.Receive()
		if err != nil {
			return errors.Trace(err)
		}
	}
	return nil
}

func (s *Sentinel) removeGroupsDispatch(ctx context.Context, sentinel string, timeout time.Duration,
	groups map[int]bool) error {
	var names []string
	for gid := range groups {
		names = append(names, s.NodeName(gid))
	}
	var err = s.dispatch(ctx, sentinel, timeout, func(c *Client) error {
		return s.removeCommand(c, names)
	})
	if err != nil {
		switch errors.Cause(err) {
		case context.Canceled:
			return nil
		default:
			return err
		}
	}
	return nil
}

func (s *Sentinel) RemoveGroups(sentinels []string, timeout time.Duration, groups map[int]bool) error {
	cntx, cancel := context.WithTimeout(s.Context, timeout)
	defer cancel()

	timeout += time.Second * 5
	results := make(chan error, len(sentinels))

	for i := range sentinels {
		go func(sentinel string) {
			err := s.removeGroupsDispatch(cntx, sentinel, timeout, groups)
			if err != nil {
				s.errorf(err, "sentinel-[%s] remove failed", sentinel)
			}
			results <- err
		}(sentinels[i])
	}

	var last error
	for range sentinels {
		select {
		case <-cntx.Done():
			if last != nil {
				return last
			}
			return errors.Trace(cntx.Err())
		case err := <-results:
			if err != nil {
				last = err
			}
		}
	}
	return last
}

func (s *Sentinel) removeGroupsAllDispatch(ctx context.Context, sentinel string, timeout time.Duration) error {
	var err = s.dispatch(ctx, sentinel, timeout, func(c *Client) error {
		masters, err := s.mastersCommand(c)
		if err != nil {
			return err
		}
		var names []string
		for gid := range masters {
			names = append(names, s.NodeName(gid))
		}
		return s.removeCommand(c, names)
	})
	if err != nil {
		switch errors.Cause(err) {
		case context.Canceled:
			return nil
		default:
			return err
		}
	}
	return nil
}

func (s *Sentinel) RemoveGroupsAll(sentinels []string, timeout time.Duration) error {
	cntx, cancel := context.WithTimeout(s.Context, timeout)
	defer cancel()

	timeout += time.Second * 5
	results := make(chan error, len(sentinels))

	for i := range sentinels {
		go func(sentinel string) {
			err := s.removeGroupsAllDispatch(cntx, sentinel, timeout)
			if err != nil {
				s.errorf(err, "sentinel-[%s] remove failed", sentinel)
			}
			results <- err
		}(sentinels[i])
	}

	var last error
	for range sentinels {
		select {
		case <-cntx.Done():
			if last != nil {
				return last
			}
			return errors.Trace(cntx.Err())
		case err := <-results:
			if err != nil {
				last = err
			}
		}
	}
	return last
}

type SentinelGroup struct {
	Master map[string]string   `json:"master"`
	Slaves []map[string]string `json:"slaves,omitempty"`
}

func (s *Sentinel) MastersAndSlavesClient(client *Client) (map[string]*SentinelGroup, error) {
	masters, err := s.mastersCommand(client)
	if err != nil {
		return nil, err
	}
	var names []string
	for gid := range masters {
		names = append(names, s.NodeName(gid))
	}
	slaves, err := s.slavesCommand(client, names)
	if err != nil {
		return nil, err
	}
	results := make(map[string]*SentinelGroup, len(masters))
	for gid, master := range masters {
		var name = s.NodeName(gid)
		results[name] = &SentinelGroup{
			Master: master, Slaves: slaves[name],
		}
	}
	return results, nil
}

func (s *Sentinel) MastersAndSlaves(sentinel string, timeout time.Duration) (map[string]*SentinelGroup, error) {
	var results map[string]*SentinelGroup
	var err = s.do(sentinel, timeout, func(c *Client) error {
		m, err := s.MastersAndSlavesClient(c)
		if err != nil {
			return err
		}
		results = m
		return nil
	})
	if err != nil {
		return nil, err
	}
	return results, nil
}

func (s *Sentinel) FlushConfig(sentinel string, timeout time.Duration) error {
	return s.do(sentinel, timeout, func(c *Client) error {
		_, err := c.Do("SENTINEL", "flushconfig")
		if err != nil {
			return err
		}
		return nil
	})
}


text:
package br.edu.ifmt.cba.java.projeto.supermercado;

import java.util.Date;

import javax.swing.JOptionPane;

import br.edu.ifmt.cba.java.projeto.supermercado.exception.PessoaException;

public class Cliente extends PessoaFisica {

	private int numeroFidelidade;
	private int pontosFidelidade;

	public Cliente() {
		super();
		this.numeroFidelidade = 0;
		this.pontosFidelidade = 0;
	}

	public Cliente(String nome, Date dataNascimento, String rg, String cpf, int numeroFidelidade, int pontosFidelidade) throws PessoaException {
		super(nome, dataNascimento,rg,cpf);
		this.numeroFidelidade = numeroFidelidade;
		this.pontosFidelidade = pontosFidelidade;
	}

	public int getNumeroFidelidade() {
		return numeroFidelidade;
	}
	public int getPontosFidelidade() {
		return pontosFidelidade;
	}
	public void setNumeroFidelidade(int numeroFidelidade) {
		this.numeroFidelidade = numeroFidelidade;
	}
	public void setPontosFidelidade(int pontosFidelidade) {
		this.pontosFidelidade = pontosFidelidade;
	}

	@Override
	public String toString() {
		return super.toString() + "Nœm, Fidelidade: " + numeroFidelidade + "\n" +
							      "Pontos: " + pontosFidelidade + "\n";
	}

}


text:
<!DOCTYPE html>
<html lang='{{LANGUAGE_CODE}}'>

    {# Base template for the whole site. #}

    <head>
        <meta charset="UTF-8" />
        {% block title %}
            {% if user_profile and user_profile.realm.name %}
                <title>{{user_profile.realm.name}} - Zulip</title>
            {% else %}
                {% if OPEN_GRAPH_TITLE %}
                <title>{{ OPEN_GRAPH_TITLE }}</title>
                {% else %}
                <title>Zulip</title>
                {% endif %}
            {% endif %}
        {% endblock %}
        <link id="favicon" rel="icon" href="/static/images/favicon.svg?v=4" />
        <link rel="alternate icon" href="/static/images/favicon.png?v=4" />
        {% block meta_viewport %}
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        {% endblock %}
        {% if not user_profile %}
        {% include 'zerver/meta_tags.html' %}
        {% endif %}

        {% block webpack %}
            {% for filename in webpack_entry(entrypoint) -%}
                {% if filename.endswith(".css") -%}
                    <link href="{{ filename }}" rel="stylesheet" {% if csp_nonce %}nonce="{{ csp_nonce }}"{% endif %} />
                {% elif filename.endswith(".js") -%}
                    <script src="{{ filename }}" defer {% if csp_nonce %}nonce="{{ csp_nonce }}"{% endif %}></script>
                {% endif -%}
            {% endfor %}
        {% endblock %}

        {% block customhead %}
        {% endblock %}
    </head>

    <body {% if color_scheme == 1 %} class="color-scheme-automatic" {% elif color_scheme == 2 %} class="night-mode" {% endif %}>
        {% block content %}
        {% endblock %}

        {% set all_page_params = default_page_params.copy() %}
        {% set _ = all_page_params.update(page_params|default({})) %}
        <div hidden id="page-params" data-params='{{ all_page_params|tojson }}'></div>
    </body>

</html>

{% set entrypoint = entrypoint|default("common") %}


text:
title:            "Shop Homepage"
slug:             shop-homepage
category:         templates
src:              /templates/shop-homepage
layout:           preview
type:             template
meta-title:       Shop Homepage - Template Preview
migrated:         true
---