text:
package com.dotech_hosting.listahu.services;

import android.os.Handler;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.dotech_hosting.listahu.RealmManager;
import com.dotech_hosting.listahu.models.Denuncia;
import com.dotech_hosting.listahu.support.AppHelpers;

import io.realm.Realm;

/**
 * Created by emilio on 10/22/15.
 */
public class CallStateListener extends PhoneStateListener {
    private static final String TAG = CallStateListener.class.getSimpleName();

    @Override
    public void onCallStateChanged(int state, final String incomingNumber) {
        switch (state) {
            case TelephonyManager.CALL_STATE_RINGING:

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        checkNumber(incomingNumber);
                    }
                }, 2500);

                break;
        }
    }

    private void checkNumber(String incoming_number) {
        Realm realm = null;
        try {
            realm = Realm.getDefaultInstance();
            final Denuncia denuncia = new RealmManager(realm).isReported(incoming_number);

            if (denuncia != null) {
                new AppHelpers(denuncia).NotifyUser();
            }

        } finally {
            if (realm != null) {
                realm.close();
            }
        }
    }
}


text:
require 'spec_helper'

describe Spree::Promotion, :type => :model do
  let(:promotion) { Spree::Promotion.new }

  describe "validations" do
    before :each do
      @valid_promotion = Spree::Promotion.new :name => "A promotion"
    end

    it "valid_promotion is valid" do
      expect(@valid_promotion).to be_valid
    end

    it "validates usage limit" do
      @valid_promotion.usage_limit = -1
      expect(@valid_promotion).not_to be_valid

      @valid_promotion.usage_limit = 100
      expect(@valid_promotion).to be_valid
    end

    it "validates name" do
      @valid_promotion.name = nil
      expect(@valid_promotion).not_to be_valid
    end
  end

  describe ".applied" do
    it "scopes promotions that have been applied to an order only" do
      promotion = Spree::Promotion.create! name: "test"
      expect(Spree::Promotion.applied).to be_empty

      promotion.orders << create(:order)
      expect(Spree::Promotion.applied.first).to eq promotion
    end
  end

  describe ".advertised" do
    let(:promotion) { create(:promotion) }
    let(:advertised_promotion) { create(:promotion, :advertise => true) }

    it "only shows advertised promotions" do
      advertised = Spree::Promotion.advertised
      expect(advertised).to include(advertised_promotion)
      expect(advertised).not_to include(promotion)
    end
  end

  describe "#apply_automatically" do
    subject { build(:promotion) }

    it "defaults to false" do
      expect(subject.apply_automatically).to eq(false)
    end

    context "when set to true" do
      before { subject.apply_automatically = true }

      it "should remain valid" do
        expect(subject).to be_valid
      end

      it "invalidates the promotion when it has a code" do
        subject.codes.build(value: "foo")
        expect(subject).to_not be_valid
        expect(subject.errors).to include(:apply_automatically)
      end

      it "invalidates the promotion when it has a path" do
        subject.path = "foo"
        expect(subject).to_not be_valid
        expect(subject.errors).to include(:apply_automatically)
      end
    end
  end

  describe "#save" do
    let(:promotion) { Spree::Promotion.create(:name => "delete me") }

    before(:each) do
      promotion.actions << Spree::Promotion::Actions::CreateAdjustment.new
      promotion.rules << Spree::Promotion::Rules::FirstOrder.new
      promotion.save!
    end

    it "should deeply autosave records and preferences" do
      promotion.actions[0].calculator.preferred_flat_percent = 10
      promotion.save!
      expect(Spree::Calculator.first.preferred_flat_percent).to eq(10)
    end
  end

  describe "#activate" do
    let(:promotion) { create(:promotion) }

    before do
      @action1 = Spree::Promotion::Actions::CreateAdjustment.create!
      @action2 = Spree::Promotion::Actions::CreateAdjustment.create!
      allow(@action1).to receive_messages perform: true
      allow(@action2).to receive_messages perform: true

      promotion.promotion_actions = [@action1, @action2]
      promotion.created_at = 2.days.ago

      @user = create(:user)
      @order = create(:order, user: @user, created_at: DateTime.now)
      @payload = { :order => @order, :user => @user }
    end

    it "should check path if present" do
      promotion.path = 'content/cvv'
      @payload[:path] = 'content/cvv'
      expect(@action1).to receive(:perform).with(hash_including(@payload))
      expect(@action2).to receive(:perform).with(hash_including(@payload))
      promotion.activate(@payload)
    end

    it "does not perform actions against an order in a finalized state" do
      expect(@action1).not_to receive(:perform)

      @order.state = 'complete'
      promotion.activate(@payload)

      @order.state = 'awaiting_return'
      promotion.activate(@payload)

      @order.state = 'returned'
      promotion.activate(@payload)
    end

    it "does activate if newer then order" do
      expect(@action1).to receive(:perform).with(hash_including(@payload))
      promotion.created_at = DateTime.now + 2
      expect(promotion.activate(@payload)).to be true
    end

    context "keeps track of the orders" do
      context "when activated" do
        it "assigns the order" do
          expect(promotion.orders).to be_empty
          expect(promotion.activate(@payload)).to be true
          expect(promotion.orders.first).to eql @order
        end
      end
      context "when not activated" do
        it "will not assign the order" do
          @order.state = 'complete'
          expect(promotion.orders).to be_empty
          expect(promotion.activate(@payload)).to be_falsey
          expect(promotion.orders).to be_empty
        end
      end
      context "when the order is already associated" do
        before do
          expect(promotion.orders).to be_empty
          expect(promotion.activate(@payload)).to be true
          expect(promotion.orders.to_a).to eql [@order]
        end

        it "will not assign the order again" do
          expect(promotion.activate(@payload)).to be true
          expect(promotion.orders.reload.to_a).to eql [@order]
        end
      end

    end

    context "when there is a code" do
      let(:promotion_code) { create(:promotion_code) }
      let(:promotion) { promotion_code.promotion }

      it "assigns the code" do
        expect(promotion.activate(order: @order, promotion_code: promotion_code)).to be true
        expect(promotion.order_promotions.map(&:promotion_code)).to eq [promotion_code]
      end
    end
  end

  describe "#usage_limit_exceeded?" do
    subject { promotion.usage_limit_exceeded? }

    shared_examples "it should" do
      context "when there is a usage limit" do
        context "and the limit is not exceeded" do
          let(:usage_limit) { 10 }
          it { is_expected.to be_falsy }
        end
        context "and the limit is exceeded" do
          let(:usage_limit) { 1 }
          context "on a different order" do
            before do
              FactoryGirl.create(
                :completed_order_with_promotion,
                promotion: promotion
              )
              promotion.actions.first.adjustments.update_all(eligible: true)
            end
            it { is_expected.to be_truthy }
          end
          context "on the same order" do
            it { is_expected.to be_falsy }
          end
        end
      end
      context "when there is no usage limit" do
        let(:usage_limit) { nil }
        it { is_expected.to be_falsy }
      end
    end

    context "with an order-level adjustment" do
      let(:promotion) do
        FactoryGirl.create(
          :promotion,
          :with_order_adjustment,
          code: "discount",
          usage_limit: usage_limit
        )
      end
      let(:promotable) do
        FactoryGirl.create(
          :completed_order_with_promotion,
          promotion: promotion
        )
      end
      it_behaves_like "it should"
    end

    context "with an item-level adjustment" do
      let(:promotion) do
        FactoryGirl.create(
          :promotion,
          :with_line_item_adjustment,
          code: "discount",
          usage_limit: usage_limit
        )
      end
      before do
        promotion.actions.first.perform({
          order: order,
          promotion: promotion,
          promotion_code: promotion.codes.first
        })
      end
      context "when there are multiple line items" do
        let(:order) { FactoryGirl.create(:order_with_line_items, line_items_count: 2) }
        describe "the first item" do
          let(:promotable) { order.line_items.first }
          it_behaves_like "it should"
        end
        describe "the second item" do
          let(:promotable) { order.line_items.last }
          it_behaves_like "it should"
        end
      end
      context "when there is a single line item" do
        let(:order) { FactoryGirl.create(:order_with_line_items) }
        let(:promotable) { order.line_items.first }
        it_behaves_like "it should"
      end
    end
  end

  describe "#usage_count" do
    let(:promotion) do
      FactoryGirl.create(
        :promotion,
        :with_order_adjustment,
        code: "discount"
      )
    end

    subject { promotion.usage_count }

    context "when the code is applied to a non-complete order" do
      let(:order) { FactoryGirl.create(:order_with_line_items) }
      before { promotion.activate(order: order, promotion_code: promotion.codes.first) }
      it { is_expected.to eq 0 }
    end
    context "when the code is applied to a complete order" do
      let!(:order) do
        FactoryGirl.create(
          :completed_order_with_promotion,
          promotion: promotion
        )
      end
      context "and the promo is eligible" do
        it { is_expected.to eq 1 }
      end
      context "and the promo is ineligible" do
        before { order.adjustments.promotion.update_all(eligible: false) }
        it { is_expected.to eq 0 }
      end
    end
  end

  context "#expired" do
    it "should not be exipired" do
      expect(promotion).not_to be_expired
    end

    it "should be expired if it hasn't started yet" do
      promotion.starts_at = Time.now + 1.day
      expect(promotion).to be_expired
    end

    it "should be expired if it has already ended" do
      promotion.expires_at = Time.now - 1.day
      expect(promotion).to be_expired
    end

    it "should not be expired if it has started already" do
      promotion.starts_at = Time.now - 1.day
      expect(promotion).not_to be_expired
    end

    it "should not be expired if it has not ended yet" do
      promotion.expires_at = Time.now + 1.day
      expect(promotion).not_to be_expired
    end

    it "should not be expired if current time is within starts_at and expires_at range" do
      promotion.starts_at = Time.now - 1.day
      promotion.expires_at = Time.now + 1.day
      expect(promotion).not_to be_expired
    end
  end

  context "#active" do
    it "should be active" do
      expect(promotion.active?).to eq(true)
    end

    it "should not be active if it hasn't started yet" do
      promotion.starts_at = Time.now + 1.day
      expect(promotion.active?).to eq(false)
    end

    it "should not be active if it has already ended" do
      promotion.expires_at = Time.now - 1.day
      expect(promotion.active?).to eq(false)
    end

    it "should be active if it has started already" do
      promotion.starts_at = Time.now - 1.day
      expect(promotion.active?).to eq(true)
    end

    it "should be active if it has not ended yet" do
      promotion.expires_at = Time.now + 1.day
      expect(promotion.active?).to eq(true)
    end

    it "should be active if current time is within starts_at and expires_at range" do
      promotion.starts_at = Time.now - 1.day
      promotion.expires_at = Time.now + 1.day
      expect(promotion.active?).to eq(true)
    end

    it "should be active if there are no start and end times set" do
      promotion.starts_at = nil
      promotion.expires_at = nil
      expect(promotion.active?).to eq(true)
    end
  end

  context "#usage_count" do
    let!(:promotion) do
      create(
        :promotion,
        name: "Foo",
        code: "XXX",
      )
    end

    let!(:action) do
      calculator = Spree::Calculator::FlatRate.new
      action_params = { :promotion => promotion, :calculator => calculator }
      action = Spree::Promotion::Actions::CreateAdjustment.create(action_params)
      promotion.actions << action
      action
    end

    let!(:adjustment) do
      order = create(:order)
      Spree::Adjustment.create!(
        order:      order,
        adjustable: order,
        source:     action,
        promotion_code: promotion.codes.first,
        amount:     10,
        label:      'Promotional adjustment'
      )
    end

    it "counts eligible adjustments" do
      adjustment.update_column(:eligible, true)
      expect(promotion.usage_count).to eq(0)
    end

    # Regression test for #4112
    it "does not count ineligible adjustments" do
      adjustment.update_column(:eligible, false)
      expect(promotion.usage_count).to eq(0)
    end
  end

  context "#products" do
    let(:promotion) { create(:promotion) }

    context "when it has product rules with products associated" do
      let(:promotion_rule) { Spree::Promotion::Rules::Product.new }

      before do
        promotion_rule.promotion = promotion
        promotion_rule.products << create(:product)
        promotion_rule.save
      end

      it "should have products" do
        expect(promotion.reload.products.size).to eq(1)
      end
    end

    context "when there's no product rule associated" do
      it "should not have products but still return an empty array" do
        expect(promotion.products).to be_blank
      end
    end
  end

  context "#eligible?" do
    subject do
      promotion.eligible?(promotable)
    end

    let(:promotable) { create :order }

    it { is_expected.to be true }

    context "when promotion is expired" do
      before { promotion.expires_at = Time.now - 10.days }
      it { is_expected.to be false }
    end

    context "when the promotion's usage limit is exceeded" do
      let(:order) { FactoryGirl.create(:completed_order_with_promotion, promotion: promotion) }
      let(:promotion) { FactoryGirl.create(:promotion, :with_order_adjustment) }

      before do
        FactoryGirl.create(
          :completed_order_with_promotion,
          promotion: promotion
        )
        promotion.usage_limit = 1
      end

      it "returns false" do
        expect(promotion.eligible?(promotable)).to eq(false)
      end
    end

    context "when the promotion code's usage limit is exceeded" do
      let(:order) { FactoryGirl.create(:completed_order_with_promotion, promotion: promotion) }
      let(:promotion) { create(:promotion, :with_order_adjustment, code: 'abc123', per_code_usage_limit: 1) }
      let(:promotion_code) { promotion.codes.first }

      before do
        FactoryGirl.create(
          :completed_order_with_promotion,
          promotion: promotion
        )
        promotion_code.adjustments.update_all(eligible: true)
      end

      it "returns false" do
        expect(promotion.eligible?(promotable, promotion_code: promotion_code)).to eq(false)
      end
    end

    context "when promotable is a Spree::LineItem" do
      let(:promotable) { create :line_item }
      let(:product) { promotable.product }

      before do
        product.promotionable = promotionable
      end

      context "and product is promotionable" do
        let(:promotionable) { true }
        it { is_expected.to be true }
      end

      context "and product is not promotionable" do
        let(:promotionable) { false }
        it { is_expected.to be false }
      end
    end

    context "when promotable is a Spree::Order" do
      let(:promotable) { create :order }

      context "and it is empty" do
        it { is_expected.to be true }
      end

      context "and it contains items" do
        let!(:line_item) { create(:line_item, order: promotable) }
        let!(:line_item2) { create(:line_item, order: promotable) }

        context "and at least one item is non-promotionable" do
          before do
            line_item.product.update_column(:promotionable, false)
          end
          it { is_expected.to be false }
        end

        context "and the items are all non-promotionable" do
          before do
            line_item.product.update_column(:promotionable, false)
            line_item2.product.update_column(:promotionable, false)
          end
          it { is_expected.to be false }
        end

        context "and at least one item is promotionable" do
          it { is_expected.to be true }
        end
      end
    end
  end

  context "#eligible_rules" do
    let(:promotable) { double('Promotable') }
    it "true if there are no rules" do
      expect(promotion.eligible_rules(promotable)).to eq []
    end

    it "true if there are no applicable rules" do
      promotion.promotion_rules = [stub_model(Spree::PromotionRule, :eligible? => true, :applicable? => false)]
      allow(promotion.promotion_rules).to receive(:for).and_return([])
      expect(promotion.eligible_rules(promotable)).to eq []
    end

    context "with 'all' match policy" do
      let(:rule1) { Spree::PromotionRule.create!(promotion: promotion) }
      let(:rule2) { Spree::PromotionRule.create!(promotion: promotion) }

      before { promotion.match_policy = 'all' }

      context "when all rules are eligible" do
        before do
          allow(rule1).to receive_messages(eligible?: true, applicable?: true)
          allow(rule2).to receive_messages(eligible?: true, applicable?: true)

          promotion.promotion_rules = [rule1, rule2]
          allow(promotion.promotion_rules).to receive(:for).and_return(promotion.promotion_rules)
        end
        it "returns the eligible rules" do
          expect(promotion.eligible_rules(promotable)).to eq [rule1, rule2]
        end
        it "does set anything to eligiblity errors" do
          promotion.eligible_rules(promotable)
          expect(promotion.eligibility_errors).to be_nil
        end
      end

      context "when any of the rules is not eligible" do
        let(:errors) { double ActiveModel::Errors, empty?: false }
        before do
          allow(rule1).to receive_messages(eligible?: true, applicable?: true, eligibility_errors: nil)
          allow(rule2).to receive_messages(eligible?: false, applicable?: true, eligibility_errors: errors)

          promotion.promotion_rules = [rule1, rule2]
          allow(promotion.promotion_rules).to receive(:for).and_return(promotion.promotion_rules)
        end
        it "returns nil" do
          expect(promotion.eligible_rules(promotable)).to be_nil
        end
        it "sets eligibility errors to the first non-nil one" do
          promotion.eligible_rules(promotable)
          expect(promotion.eligibility_errors).to eq errors
        end
      end
    end

    context "with 'any' match policy" do
      let(:promotion) { Spree::Promotion.create(:name => "Promo", :match_policy => 'any') }
      let(:promotable) { double('Promotable') }

      it "should have eligible rules if any of the rules are eligible" do
        allow_any_instance_of(Spree::PromotionRule).to receive_messages(:applicable? => true)
        true_rule = Spree::PromotionRule.create(:promotion => promotion)
        allow(true_rule).to receive_messages(:eligible? => true)
        allow(promotion).to receive_messages(:rules => [true_rule])
        allow(promotion).to receive_message_chain(:rules, :for).and_return([true_rule])
        expect(promotion.eligible_rules(promotable)).to eq [true_rule]
      end

      context "when none of the rules are eligible" do
        let(:rule) { Spree::PromotionRule.create!(promotion: promotion) }
        let(:errors) { double ActiveModel::Errors, empty?: false }
        before do
          allow(rule).to receive_messages(eligible?: false, applicable?: true, eligibility_errors: errors)

          promotion.promotion_rules = [rule]
          allow(promotion.promotion_rules).to receive(:for).and_return(promotion.promotion_rules)
        end
        it "returns nil" do
          expect(promotion.eligible_rules(promotable)).to be_nil
        end
        it "sets eligibility errors to the first non-nil one" do
          promotion.eligible_rules(promotable)
          expect(promotion.eligibility_errors).to eq errors
        end
      end
    end
  end

  describe '#line_item_actionable?' do
    let(:order) { double Spree::Order }
    let(:line_item) { double Spree::LineItem}
    let(:true_rule) { double Spree::PromotionRule, eligible?: true, applicable?: true, actionable?: true }
    let(:false_rule) { double Spree::PromotionRule, eligible?: true, applicable?: true, actionable?: false }
    let(:rules) { [] }

    before do
      allow(promotion).to receive(:rules) { rules }
      allow(rules).to receive(:for) { rules }
    end

    subject { promotion.line_item_actionable? order, line_item }

    context 'when the order is eligible for promotion' do
      context 'when there are no rules' do
        it { is_expected.to be }
      end

      context 'when there are rules' do
        context 'when the match policy is all' do
          before { promotion.match_policy = 'all' }

          context 'when all rules allow action on the line item' do
            let(:rules) { [true_rule] }
            it { is_expected.to be}
          end

          context 'when at least one rule does not allow action on the line item' do
            let(:rules) { [true_rule, false_rule] }
            it { is_expected.not_to be}
          end
        end

        context 'when the match policy is any' do
          before { promotion.match_policy = 'any' }

          context 'when at least one rule allows action on the line item' do
            let(:rules) { [true_rule, false_rule] }
            it { is_expected.to be }
          end

          context 'when no rules allow action on the line item' do
            let(:rules) { [false_rule] }
            it { is_expected.not_to be}
          end
        end
      end
    end

    context 'when the order is not eligible for the promotion' do
      context "due to promotion expiration" do
        before { promotion.starts_at = Time.current + 2.days }
        it { is_expected.not_to be }
      end

      context "due to promotion code not being eligible" do
        let(:order) { create(:order) }
        let(:promotion) { create(:promotion, per_code_usage_limit: 0) }
        let(:promotion_code) { create(:promotion_code, promotion: promotion) }

        subject { promotion.line_item_actionable? order, line_item, promotion_code: promotion_code }

        it "returns false" do
          expect(subject).to eq false
        end
      end
    end
  end

  # regression for #4059
  # admin form posts the code and path as empty string
  describe "normalize blank values for path" do
    it "will save blank value as nil value instead" do
      promotion = Spree::Promotion.create(:name => "A promotion", :path => "")
      expect(promotion.path).to be_nil
    end
  end

  describe '#used_by?' do
    subject { promotion.used_by? user, [excluded_order] }

    let(:promotion) { create :promotion, :with_order_adjustment }
    let(:user) { create :user }
    let(:order) { create :order_with_line_items, user: user }
    let(:excluded_order) { create :order_with_line_items, user: user }

    before do
      order.user_id = user.id
      order.save!
    end

    context 'when the user has used this promo' do
      before do
        promotion.activate(order: order)
        order.update!
        order.completed_at = Time.now
        order.save!
      end

      context 'when the order is complete' do
        it { is_expected.to be true }

        context 'when the promotion was not eligible' do
          let(:adjustment) { order.adjustments.first }

          before do
            adjustment.eligible = false
            adjustment.save!
          end

          it { is_expected.to be false }
        end

        context 'when the only matching order is the excluded order' do
          let(:excluded_order) { order }
          it { is_expected.to be false }
        end
      end

      context 'when the order is not complete' do
        let(:order) { create :order, user: user }
        it { is_expected.to be false }
      end
    end

    context 'when the user has not used this promo' do
      it { is_expected.to be false }
    end
  end

  describe "adding items to the cart" do
    let(:order) { create :order }
    let(:line_item) { create :line_item, order: order }
    let(:promo) { create :promotion_with_item_adjustment, adjustment_rate: 5, code: 'promo' }
    let(:promotion_code) { promo.codes.first }
    let(:variant) { create :variant }

    it "updates the promotions for new line items" do
      expect(line_item.adjustments).to be_empty
      expect(order.adjustment_total).to eq 0

      promo.activate order: order, promotion_code: promotion_code
      order.update!

      expect(line_item.adjustments.size).to eq(1)
      expect(order.adjustment_total).to eq -5

      other_line_item = order.contents.add(variant, 1, currency: order.currency)

      expect(other_line_item).not_to eq line_item
      expect(other_line_item.adjustments.size).to eq(1)
      expect(order.adjustment_total).to eq -10
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
var fse = require('fs-extra');
var path = require('path');
var utils = require('./utils');
var moment = require('moment');

module.exports = function(dir) {
	dir = dir || '.';
	//创建基本目录
	fse.mkdirsSync(path.resolve(dir, '_layout'));
	fse.mkdirsSync(path.resolve(dir, '_posts'));
	fse.mkdirsSync(path.resolve(dir, 'assets'));
	fse.mkdirsSync(path.resolve(dir, 'posts'));

	console.log('begin creat');

	//复制文件
	var tmplDir = path.resolve(__dirname, '../posts');
	fse.copySync(tmplDir, dir);

	//创建文章
	newPost(dir, 'hello,world', '我的第一篇文章');
	console.log('creat ok')

}

function newPost(dir, title, content) {
	var data = [
		'---',
		'',
		'title: ' + title,
		'date: ' + moment().format('YYYY-MM-DD'),
		'',
		'---',
		'',
		content
	].join('\r\n');
	var name = moment().format('YYYY-MM') + 'hello-world.md';
	var file = path.resolve(dir, '_posts', name);
	fse.outputFileSync(file, data);
}


text:
import java.io.ByteArrayInputStream;
import java.io.IOException;
import junit.framework.AssertionFailedError;
import static org.junit.Assert.*;

class Test {

  public void javaAssertionPositive1() {
    try {
      <warning descr="'assert' cannot fail as it's suppressed by a surrounding 'catch'">assert 1 == 1;</warning>
    } catch (AssertionError e) {}
  }

  public void javaAssertionPositive2() {
    try {
      int a = 1;
      <warning descr="'assert' cannot fail as it's suppressed by a surrounding 'catch'">assert 1 == 1;</warning>
    } catch (AssertionError e) {}
  }

  public void javaAssertionPositive3() {
    try {
      <warning descr="'assert' cannot fail as it's suppressed by a surrounding 'catch'">assert 1 == 1;</warning>
    } catch (Error e) {}
  }

  public void javaAssertionPositive4() {
    try {
      <warning descr="'assert' cannot fail as it's suppressed by a surrounding 'catch'">assert 1 == 1;</warning>
    } catch (Throwable e) {}
  }

  public void javaAssertionPositive5() {
    try {
      <warning descr="'assert' cannot fail as it's suppressed by a surrounding 'catch'">assert 1 == 1;</warning>
    } catch (AssertionFailedError e) {
    } catch (AssertionError e) {
    }
  }

  public void javaAssertionNegative1() {
    try {
      assert 1 == 1;
    } catch (AssertionError e) {
      System.out.println();
    }
  }

  public void javaAssertionNegative2() {
    try {
      assert 1 == 1;
      int a = 1;
    } catch (AssertionError e) {
    }
  }

  public void javaAssertionNegative3() {
    try {
      assert 1 == 1;
    } catch (Exception e) {
    }
  }

  public void assertSamePositive1() {
    try {
      <warning descr="'assertSame()' cannot fail as it's suppressed by a surrounding 'catch'">assertSame(1, 1)</warning>;
    } catch (AssertionError e) {}
  }

  public void assertSamePositive2() {
    try {
      int a = 1;
      <warning descr="'assertSame()' cannot fail as it's suppressed by a surrounding 'catch'">assertSame(1, 1)</warning>;
    } catch (AssertionError e) {}
  }

  public void assertSameNegative1() {
    try {
      assertSame(1, 1);
    } catch (AssertionError e) {
      System.out.println();
    }
  }

  public void assertSameNegative2() {
    try {
      assertSame(1, 1);
      int a = 1;
    } catch (AssertionError e) {
    }
  }

  public void assertSameNegative3() throws IOException {
    try(ByteArrayInputStream bis = new ByteArrayInputStream(new byte[8192])) {
      assertSame(1, 1);
    }
  }

  public void failPositive1() {
    try {
      <warning descr="'fail()' cannot fail as it's suppressed by a surrounding 'catch'">fail()</warning>;
    } catch (AssertionError e) {}
  }

  public void failPositive2() {
    try {
      int a = 1;
      <warning descr="'fail()' cannot fail as it's suppressed by a surrounding 'catch'">fail()</warning>;
    } catch (AssertionError e) {}
  }

  public void failPositive3() {
    try {
      <warning descr="'fail()' cannot fail as it's suppressed by a surrounding 'catch'">fail()</warning>;
    } catch (Exception e1) {
    } catch (AssertionError e2) {}
  }

  public void failPositive4() {
    try {
      <warning descr="'fail()' cannot fail as it's suppressed by a surrounding 'catch'">fail()</warning>;
    } catch (AssertionFailedError e) {
    } catch (AssertionError e) {
    }
  }

  public void failPositive5() {
    try {
      <warning descr="'fail()' cannot fail as it's suppressed by a surrounding 'catch'">fail()</warning>;
    } catch (NullPointerException | AssertionError e) {
    } catch (Throwable e) {
      System.out.println();
    }
  }

  public void failNegative1() {
    try {
      fail();
    } catch (AssertionError e) {
      System.out.println();
    }
  }

  public void failNegative2() {
    try {
      fail();
      int a = 1;
    } catch (AssertionError e) {
    }
  }

  public void failNegative3() {
    try {
      fail();
    } finally {
    }
  }

  public void failNegative4() {
    try {
      fail();
    } catch (AssertionFailedError e) {
      System.out.println();
    } catch (AssertionError e) {
    }
  }
}


text:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Document</title>
</head>
<body>
<!-- trace:example/src/index.src.html -->
en

Hello world!
</body>
</html>


text:
#ifndef CORE_HPP
#define CORE_HPP

#include "Utils.hpp"
#include "InlineDetour.hpp"
#include "SubstitutionManager.hpp"

#include <QObject>
#include <ida.hpp>
#include <demangle.hpp>
#include <memory>
#include <kernwin.hpp>

// ============================================================================================== //
// [Core]                                                                                //
// ============================================================================================== //

/**
 * @brief   Plugin core singleton.
 */
class Core : public QObject, public Utils::Singleton<Core>
{
    Q_OBJECT

    SubstitutionManager m_substitutionManager;
    typedef InlineDetour<demangler_t> DemanglerDetour;
    std::unique_ptr<DemanglerDetour> m_demanglerDetour;
    demangler_t *m_originalMangler;
public:
    /**
     * @brief   Default constructor.
     */
    Core();
    /**
     * @brief   Destructor.
     */
    ~Core();
    /**
     * @brief   Runs the plugin.
     */
    void runPlugin();
    /**
     * @brief   Replacement function for IDA's @c demangle routine.
     * @param   answer          The output buffer for the demangled name.
     * @param   answerLength    Length of @c answer bufer.
     * @param   str             The mangled name.
     * @param   disableMask     See @c demangle.hpp in IDA SDK.
     * @return  See @c demangle.hpp in IDA SDK.
     */
    static int32 idaapi demanglerHookCallback(char* answer, uint answerLength,
        const char* str, uint32 disableMask);
private:
#if IDA_SDK_VERSION >= 670
    struct OptionsMenuItemClickedAction : public action_handler_t
    {
        int idaapi activate(action_activation_ctx_t *ctx);
        action_state_t idaapi update(action_update_ctx_t *ctx);
    } m_optionsMenuItemClickedAction;
#endif
    /**
     * @brief   Handles clicks on the "Edit name substitutions" menu entry in IDA.
     * @param   userData    @c this.
     * @return  Always 0.
     */
    static bool idaapi onOptionsMenuItemClicked(void* userData);
private slots:
    /**
     * @brief   Saves the rules from the substitution manager to the settings.
     */
    void saveToSettings();
};

// ============================================================================================== //

#endif


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<artifactId>library</artifactId>
	<packaging>jar</packaging>
	<name>EMV Paycard - Library</name>

	<parent>
		<groupId>com.github.devnied.emvnfccard</groupId>
		<artifactId>parent</artifactId>
		<version>3.0.2-SNAPSHOT</version>
		<relativePath>../</relativePath>
	</parent>

	<dependencies>
		<dependency>
			<groupId>com.github.devnied</groupId>
			<artifactId>bit-lib4j</artifactId>
		</dependency>

		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
		</dependency>

		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-collections4</artifactId>
		</dependency>

		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
		</dependency>

		<dependency>
			<groupId>net.sf.scuba</groupId>
			<artifactId>scuba-smartcards</artifactId>
		</dependency>

		<!-- Unit test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.13.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.easytesting</groupId>
			<artifactId>fest-assert</artifactId>
			<version>1.4</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.7.5</version>
			<scope>test</scope>
		</dependency>

	</dependencies>
	<build>
		<finalName>emv-paycard-library-${project.version}</finalName>
		<plugins>
			<plugin>
				<groupId>org.eluder.coveralls</groupId>
				<artifactId>coveralls-maven-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>cobertura-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/break-electron.iml" filepath="$PROJECT_DIR$/.idea/break-electron.iml" />
    </modules>
  </component>
</project>


text:
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;

namespace System.Linq.Parallel
{
    /// <summary>
    /// The operator type for Select statements. This operator transforms elements as it
    /// enumerates them through the use of a selector delegate.
    /// </summary>
    /// <typeparam name="TInput"></typeparam>
    /// <typeparam name="TOutput"></typeparam>
    internal sealed class SelectQueryOperator<TInput, TOutput> : UnaryQueryOperator<TInput, TOutput>
    {
        // Selector function. Used to project elements to a transformed view during execution.
        private Func<TInput, TOutput> _selector;

        //---------------------------------------------------------------------------------------
        // Initializes a new select operator.
        //
        // Arguments:
        //    child         - the child operator or data source from which to pull data
        //    selector      - a delegate representing the selector function
        //
        // Assumptions:
        //    selector must be non null.
        //

        internal SelectQueryOperator(IEnumerable<TInput> child, Func<TInput, TOutput> selector)
            : base(child)
        {
            Debug.Assert(child != null, "child data source cannot be null");
            Debug.Assert(selector != null, "need a selector function");

            _selector = selector;
            SetOrdinalIndexState(Child.OrdinalIndexState);
        }

        internal override void WrapPartitionedStream<TKey>(
            PartitionedStream<TInput, TKey> inputStream, IPartitionedStreamRecipient<TOutput> recipient, bool preferStriping, QuerySettings settings)
        {
            PartitionedStream<TOutput, TKey> outputStream =
                new PartitionedStream<TOutput, TKey>(inputStream.PartitionCount, inputStream.KeyComparer, OrdinalIndexState);
            for (int i = 0; i < inputStream.PartitionCount; i++)
            {
                outputStream[i] = new SelectQueryOperatorEnumerator<TKey>(inputStream[i], _selector);
            }

            recipient.Receive(outputStream);
        }

        //---------------------------------------------------------------------------------------
        // Just opens the current operator, including opening the child and wrapping it with
        // partitions as needed.
        //

        internal override QueryResults<TOutput> Open(QuerySettings settings, bool preferStriping)
        {
            QueryResults<TInput> childQueryResults = Child.Open(settings, preferStriping);
            return SelectQueryOperatorResults.NewResults(childQueryResults, this, settings, preferStriping);
        }

        internal override IEnumerable<TOutput> AsSequentialQuery(CancellationToken token)
        {
            return Child.AsSequentialQuery(token).Select(_selector);
        }

        //---------------------------------------------------------------------------------------
        // Whether this operator performs a premature merge that would not be performed in
        // a similar sequential operation (i.e., in LINQ to Objects).
        //

        internal override bool LimitsParallelism
        {
            get { return false; }
        }

        //---------------------------------------------------------------------------------------
        // The enumerator type responsible for projecting elements as it is walked.
        //

        class SelectQueryOperatorEnumerator<TKey> : QueryOperatorEnumerator<TOutput, TKey>
        {
            private readonly QueryOperatorEnumerator<TInput, TKey> _source; // The data source to enumerate.
            private readonly Func<TInput, TOutput> _selector;  // The actual select function.

            //---------------------------------------------------------------------------------------
            // Instantiates a new select enumerator.
            //

            internal SelectQueryOperatorEnumerator(QueryOperatorEnumerator<TInput, TKey> source, Func<TInput, TOutput> selector)
            {
                Debug.Assert(source != null);
                Debug.Assert(selector != null);
                _source = source;
                _selector = selector;
            }

            //---------------------------------------------------------------------------------------
            // Straightforward IEnumerator<T> methods.
            //

            internal override bool MoveNext(ref TOutput currentElement, ref TKey currentKey)
            {
                // So long as the source has a next element, we have an element.
                TInput element = default(TInput);
                if (_source.MoveNext(ref element, ref currentKey))
                {
                    Debug.Assert(_selector != null, "expected a compiled operator");
                    currentElement = _selector(element);
                    return true;
                }

                return false;
            }

            protected override void Dispose(bool disposing)
            {
                _source.Dispose();
            }
        }

        //-----------------------------------------------------------------------------------
        // Query results for a Select operator. The results are indexable if the child
        // results were indexable.
        //

        class SelectQueryOperatorResults : UnaryQueryOperatorResults
        {
            private Func<TInput, TOutput> _selector; // Selector function
            private int _childCount; // The number of elements in child results

            public static QueryResults<TOutput> NewResults(
                QueryResults<TInput> childQueryResults, SelectQueryOperator<TInput, TOutput> op,
                QuerySettings settings, bool preferStriping)
            {
                if (childQueryResults.IsIndexible)
                {
                    return new SelectQueryOperatorResults(childQueryResults, op, settings, preferStriping);
                }
                else
                {
                    return new UnaryQueryOperatorResults(childQueryResults, op, settings, preferStriping);
                }
            }

            private SelectQueryOperatorResults(
                QueryResults<TInput> childQueryResults, SelectQueryOperator<TInput, TOutput> op,
                QuerySettings settings, bool preferStriping)
                : base(childQueryResults, op, settings, preferStriping)
            {
                Debug.Assert(op._selector != null);
                _selector = op._selector;
                Debug.Assert(_childQueryResults.IsIndexible);
                _childCount = _childQueryResults.ElementsCount;
            }

            internal override bool IsIndexible
            {
                get { return true; }
            }

            internal override int ElementsCount
            {
                get { return _childCount; }
            }

            internal override TOutput GetElement(int index)
            {
                Debug.Assert(index >= 0);
                Debug.Assert(index < ElementsCount);

                return _selector(_childQueryResults.GetElement(index));
            }
        }
    }
}


text:
package com.spectralogic.ds3autogen.python.utils;

import com.spectralogic.ds3autogen.api.models.Arguments;
import com.spectralogic.ds3autogen.api.models.enums.Classification;
import com.spectralogic.ds3autogen.api.models.apispec.Ds3Request;
import com.spectralogic.ds3autogen.api.models.enums.Requirement;
import com.spectralogic.ds3autogen.utils.models.NotificationType;

import static com.spectralogic.ds3autogen.utils.ConverterUtil.isEmpty;
import static com.spectralogic.ds3autogen.utils.Ds3RequestClassificationUtil.*;
import static com.spectralogic.ds3autogen.utils.Ds3RequestUtils.hasBucketNameInPath;
import static com.spectralogic.ds3autogen.utils.Helper.camelToUnderscore;
import static com.spectralogic.ds3autogen.utils.NormalizingContractNamesUtil.removePath;
import static com.spectralogic.ds3autogen.utils.RequestConverterUtil.*;

/**
 * Provides a series of static utility functions that are used within
 * the Python package generators to convert the data from Ds3Requests and
 * Ds3Types into models that are then used within the templates
 */
public final class GeneratorUtils {

    private GeneratorUtils() {
        //pass
    }

    /**
     * Creates the Python request path code for a Ds3 request
     */
    public static String toRequestPath(final Ds3Request ds3Request) {
        if (ds3Request.getClassification() == Classification.amazons3) {
            return getAmazonS3RequestPath(ds3Request);
        }
        //Spectra internal requests have the same path construction as SpectraDs3
        return getSpectraDs3RequestPath(ds3Request);
    }

    /**
     * Creates the Python request path code for an AmazonS3 request
     */
    protected static String getAmazonS3RequestPath(final Ds3Request ds3Request) {
        final StringBuilder builder = new StringBuilder();
        if (ds3Request.getClassification() != Classification.amazons3) {
            return builder.toString();
        }
        builder.append("'/'");
        if (ds3Request.getBucketRequirement() == Requirement.REQUIRED) {
            builder.append(" + bucket_name");
        }
        if (ds3Request.getObjectRequirement() == Requirement.REQUIRED) {
            builder.append(" + '/' + object_name");
        }
        return builder.toString();
    }

    /**
     * Creates the Python request path code for a SpectraS3 request
     */
    protected static String getSpectraDs3RequestPath(final Ds3Request ds3Request) {
        final StringBuilder builder = new StringBuilder();
        if (ds3Request.getClassification() != Classification.spectrads3) {
            return builder.toString();
        }
        if (ds3Request.getResource() == null) {
            return builder.append("'/_rest_/'").toString();
        }

        builder.append("'/_rest_/").append(ds3Request.getResource().toString().toLowerCase());
        if (isNotificationRequest(ds3Request)
                && ds3Request.getIncludeInPath()
                && (getNotificationType(ds3Request) == NotificationType.DELETE
                || getNotificationType(ds3Request) == NotificationType.GET)) {
            builder.append("/'").append(" + notification_id");
        } else if (hasBucketNameInPath(ds3Request)) {
            builder.append("/'").append(" + bucket_name");
        } else if (isResourceAnArg(ds3Request.getResource(), ds3Request.getIncludeInPath())) {
            final Arguments resourceArg = getArgFromResource(ds3Request.getResource());
            builder.append("/'").append(" + ").append(camelToUnderscore(resourceArg.getName()));
        } else {
            builder.append("'");
        }
        return builder.toString();
    }

    /**
     * Get parser model descriptor name for specified type
     */
    public static String getParserModelName(final String type) {
        if (isEmpty(type)) {
            return "None";
        }
        return removePath(type);
    }

    /**
     * Determines if the Ds3Request has a request payload of type FileObjectList
     */
    public static boolean hasFileObjectListPayload(final Ds3Request ds3Request) {
        return hasRequiredFileObjectListPayload(ds3Request) || isEjectStorageDomainBlobsRequest(ds3Request);
    }

    /**
     * Determines if the Ds3Request has a request payload of type FileObjectList
     */
    public static boolean hasRequiredFileObjectListPayload(final Ds3Request ds3Request) {
        return isBulkGetRequest(ds3Request)
                || isBulkPutRequest(ds3Request)
                || isPhysicalPlacementRequest(ds3Request);
    }
}


text:
python-simplox
==============

A Python client for simplox


text:
<?php

namespace Sylius\Bundle\ContactBundle\Form\Type;

use Sylius\Bundle\ResourceBundle\Form\Type\AbstractResourceType;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * Sylius contact topic form type.
 *
 * @author Michał Marcinkowski <michal.marcinkowski@lakion.com>
 * @author Gustavo Perdomo <gperdomor@gmail.com>
 */
class TopicType extends AbstractResourceType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('translations', 'a2lix_translationsForms', array(
                'form_type' => 'sylius_contact_topic_translation',
                'label'    => 'sylius.form.contact_topic.title',
            ))
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'sylius_contact_topic';
    }
}


text:
#ifndef __APP_SVC_DB_H__
#define __APP_SVC_DB_H__

#include <sqlite3.h>
#include <time.h>
#include <sys/types.h>

#ifdef __cplusplus
extern "C"
{
#endif

int _svc_db_add_app(const char *op, const char *mime_type, const char *uri, const char *pkg_name);
int _svc_db_delete_with_pkgname(const char *pkg_name);
char* _svc_db_get_app(const char *op, const char *mime_type, const char *uri);
int _svc_db_is_defapp(const char *pkg_name);
int _svc_db_get_list_with_collation(char *op, char *uri, char *mime, GSList **pkg_list);

#ifdef __cplusplus
}
#endif

#endif		/* __APP_SVC_DB_H__ */


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

<TITLE>
DirectResponse (Authorize.Net Java SDK)
</TITLE>

<META NAME="date" CONTENT="2011-08-25">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

net.authorize.data.cim

Class DirectResponse

java.lang.Object
  net.authorize.data.cim.DirectResponse

public class DirectResponse
extends java.lang.Object

Field Summary

static java.lang.String
RESPONSE_DELIMITER

Method Summary

static DirectResponse
createDirectResponse(java.lang.String directResponseString)

          Create a validation direct response from a passed in string.

 java.util.Map<ResponseField,java.lang.String>
getDirectResponseMap()

 java.lang.String
getDirectResponseString()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

RESPONSE_DELIMITER

public static final java.lang.String RESPONSE_DELIMITER

See Also:
Constant Field Values

Method Detail

createDirectResponse

public static DirectResponse createDirectResponse(java.lang.String directResponseString)

Create a validation direct response from a passed in string.

Parameters:
directResponseString -

Returns:
DirectResponse object

getDirectResponseString

public java.lang.String getDirectResponseString()

Returns:
the directResponseString

getDirectResponseMap

public java.util.Map<ResponseField,java.lang.String> getDirectResponseMap()

Returns:
the directResponseMap

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.ys.yoosir.circleprogressbar.MainActivity">

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:text="Hello World!" />

    <com.ys.yoosir.view.CircleImageView
        android:id="@+id/circleProgressBar"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_centerInParent="true"
        app:backgroundColor="#fefefe"
        app:radius="40dp"
        />
</RelativeLayout>


text:
#pragma once

/**
 * \file sal/logger/worker.hpp
 * Logging channels' worker, marshalling event records from channels to sinks.
 *
 * \addtogroup logger
 * \{
 */

#include <sal/config.hpp>
#include <sal/logger/__bits/channel.hpp>
#include <sal/logger/channel.hpp>
#include <sal/assert.hpp>
#include <unordered_map>

__sal_begin

namespace logger {

/**
 * Return option to configure channel's sink.
 */
inline auto set_channel_sink (const sink_ptr &sink) noexcept
{
  sal_check_ptr(sink.get());
  return __bits::channel_sink(sink);
}

/**
 * Return option to configure channel's sink with \a os of type std::ostream.
 */
inline auto set_channel_sink (std::ostream &os) noexcept
{
  return __bits::channel_sink(ostream_sink(os));
}

/**
 * Base class for different worker implementations. This class provides
 * functionality to create, configure and query channels. Each channel is
 * identified by name (e.g. module names that use it to log events etc).
 * Worker remains owner of channel throughout whole lifetime.
 *
 * Each worker owns default channel that is created and configured during
 * worker construction. It's attributes are used as defaults when adding
 * new channels. Also, when querying for non-existing channel, default one
 * is returned.
 *
 * Inherited classes should provide method to allocate and initialise event:
 * \code
 * event_ptr make_event (const channel_t<Worker> &channel);
 * \endcode
 * Create new event (or fetch from pool) and initialize it's members.
 * Inherited implementation should also provide custom deleter that writes
 * event message to final destination and releases (or returns to poool) used
 * event.
 *
 * \see worker_t
 * \see async_worker_t
 *
 * \note After creation, channel remains immutable (except enabled/disabled
 * flag) until worker is destructed. This approach prevents threading issues.
 */
template <typename Worker>
class basic_worker_t
{
public:

  /// Channel type for specified \a Worker
  using channel_type = channel_t<Worker>;

  /**
   * Construct worker: create and configure default channel using \a options
   *
   * \note Specified options become default values for new channels if their
   * own options are not set or set partially.
   *
   * \see set_channel_sink()
   */
  template <typename... Options>
  basic_worker_t (Options &&...options)
    : default_channel_(
        channels_.emplace(std::piecewise_construct,
          std::forward_as_tuple(""),
          std::forward_as_tuple("",
            static_cast<Worker &>(*this),
            std::forward<Options>(options)...
          )
        ).first->second
      )
  {}

  /**
   * Return reference to default channel created during worker construction
   */
  channel_type default_channel () noexcept
  {
    return default_channel_;
  }

  /**
   * Return previously created channel with \a name or default channel if not
   * found.
   */
  channel_type get_channel (const std::string &name) noexcept
  {
    auto it = channels_.find(name);
    return it != channels_.end() ? it->second : default_channel_;
  }

  /**
   * Create new channel \a with name, using \a options. If some or none of
   * options are specified, corresponding defaults are taken from
   * default_channel()
   *
   * \see set_channel_sink()
   */
  template <typename... Options>
  channel_type make_channel (const std::string &name, Options &&...options)
  {
    return channels_.emplace(std::piecewise_construct,
      std::forward_as_tuple(name),
      std::forward_as_tuple(name,
        static_cast<Worker &>(*this),
        set_channel_sink(default_channel_.sink),
        std::forward<Options>(options)...
      )
    ).first->second;
  }

  /**
   * Visit each channel and set it's \a enabled state if \a filter predicate
   * returns true. Signature of the \a filter should be equivalent of:
   * \code{.cpp}
   * bool filter (const std::string &channel_name);
   * \endcode
   *
   * This method help to turn on/off group of channels. Example, turn off all
   * channels that has suffix '.debug' in their name:
   * \code
   * worker.set_enabled_if(false,
   *   [](auto channel_name)
   *   {
   *     return ends_with(channel_name, ".debug");
   *   }
   * )
   * \endcode
   */
  template <typename Filter>
  void set_enabled_if (bool enabled, Filter &&filter)
  {
    for (auto &channel: channels_)
    {
      if (std::forward<Filter>(filter)(channel.second.name))
      {
        channel.second.is_enabled = enabled;
      }
    }
  }

private:

  std::unordered_map<std::string, __bits::channel_t<Worker>> channels_{};
  __bits::channel_t<Worker> &default_channel_;
};

/**
 * Simple synchronous logger. It is direct descendant of basic_worker_t that
 * holds single event per thread that is used for logging. It implies that
 * application's each thread have single event logging in progress at any
 * time. It is ok for multiple threads doing logging same time.
 *
 * While simple and doesn't do any memory allocations, any thread can block
 * if event message writing blocks. If such blocking is undesirable, it might
 * be better to use async_worker_t.
 */
class worker_t
  : public basic_worker_t<worker_t>
{
public:

  // inherit ctor, no additional functionality
  using basic_worker_t::basic_worker_t;

  /**
   * Create global default logging worker with \a options. This worker is used
   * by logging macros that do not specify channel explicitly.
   *
   * \note This method can be called only once.
   */
  template <typename... Options>
  static worker_t &make_default (Options &&...options)
  {
    sal_assert(default_ == nullptr);
    default_ = std::make_unique<worker_t>(std::forward<Options>(options)...);
    return *sal_check_ptr(default_.get());
  }

  /**
   * Return global default logger worker. If not created yet, it will
   * internally call worker_t::make_default() with no arguments i.e. using
   * default settings.
   */
  static worker_t &get_default ()
  {
    static auto &worker_(default_ ? *default_ : make_default());
    return worker_;
  }

private:

  event_ptr make_event (const channel_type &channel);
  friend class channel_t<worker_t>;

  static std::unique_ptr<worker_t> default_;
};

/**
 * Create global default logging worker with \a options
 * \see worker_t::make_default()
 */
template <typename... Options>
inline worker_t &make_default_worker (Options &&...options)
{
  return worker_t::make_default(std::forward<Options>(options)...);
}

/**
 * Return global default logger worker.
 * \see worker_t::get_default()
 */
inline worker_t &default_worker ()
{
  return worker_t::get_default();
}

/**
 * Return global default channel for worker_t::get_default() worker.
 */
inline channel_t<worker_t> &default_channel ()
{
  static auto channel_(default_worker().default_channel());
  return channel_;
}

} // namespace logger

__sal_end

/// \}


text:
/* Generated by the protocol buffer compiler.  DO NOT EDIT! */

#ifndef PROTOBUF_C_osmformat_2eproto__INCLUDED
#define PROTOBUF_C_osmformat_2eproto__INCLUDED

#include <google/protobuf-c/protobuf-c.h>

PROTOBUF_C_BEGIN_DECLS

typedef struct _OSMPBF__HeaderBlock OSMPBF__HeaderBlock;
typedef struct _OSMPBF__HeaderBBox OSMPBF__HeaderBBox;
typedef struct _OSMPBF__PrimitiveBlock OSMPBF__PrimitiveBlock;
typedef struct _OSMPBF__PrimitiveGroup OSMPBF__PrimitiveGroup;
typedef struct _OSMPBF__StringTable OSMPBF__StringTable;
typedef struct _OSMPBF__Info OSMPBF__Info;
typedef struct _OSMPBF__DenseInfo OSMPBF__DenseInfo;
typedef struct _OSMPBF__ChangeSet OSMPBF__ChangeSet;
typedef struct _OSMPBF__Node OSMPBF__Node;
typedef struct _OSMPBF__DenseNodes OSMPBF__DenseNodes;
typedef struct _OSMPBF__Way OSMPBF__Way;
typedef struct _OSMPBF__Relation OSMPBF__Relation;

/* --- enums --- */

typedef enum _OSMPBF__Relation__MemberType {
  OSMPBF__RELATION__MEMBER_TYPE__NODE = 0,
  OSMPBF__RELATION__MEMBER_TYPE__WAY = 1,
  OSMPBF__RELATION__MEMBER_TYPE__RELATION = 2
} OSMPBF__Relation__MemberType;

/* --- messages --- */

struct  _OSMPBF__HeaderBlock
{
  ProtobufCMessage base;
  OSMPBF__HeaderBBox *bbox;
  size_t n_required_features;
  char **required_features;
  size_t n_optional_features;
  char **optional_features;
  char *writingprogram;
  char *source;
};
#define OSMPBF__HEADER_BLOCK__INIT \
 { PROTOBUF_C_MESSAGE_INIT (&osmpbf__header_block__descriptor) \
    , NULL, 0,NULL, 0,NULL, NULL, NULL }

struct  _OSMPBF__HeaderBBox
{
  ProtobufCMessage base;
  int64_t left;
  int64_t right;
  int64_t top;
  int64_t bottom;
};
#define OSMPBF__HEADER_BBOX__INIT \
 { PROTOBUF_C_MESSAGE_INIT (&osmpbf__header_bbox__descriptor) \
    , 0, 0, 0, 0 }

struct  _OSMPBF__PrimitiveBlock
{
  ProtobufCMessage base;
  OSMPBF__StringTable *stringtable;
  size_t n_primitivegroup;
  OSMPBF__PrimitiveGroup **primitivegroup;
  protobuf_c_boolean has_granularity;
  int32_t granularity;
  protobuf_c_boolean has_lat_offset;
  int64_t lat_offset;
  protobuf_c_boolean has_lon_offset;
  int64_t lon_offset;
  protobuf_c_boolean has_date_granularity;
  int32_t date_granularity;
};
#define OSMPBF__PRIMITIVE_BLOCK__INIT \
 { PROTOBUF_C_MESSAGE_INIT (&osmpbf__primitive_block__descriptor) \
    , NULL, 0,NULL, 0,100, 0,0, 0,0, 0,1000 }

struct  _OSMPBF__PrimitiveGroup
{
  ProtobufCMessage base;
  size_t n_nodes;
  OSMPBF__Node **nodes;
  OSMPBF__DenseNodes *dense;
  size_t n_ways;
  OSMPBF__Way **ways;
  size_t n_relations;
  OSMPBF__Relation **relations;
  size_t n_changesets;
  OSMPBF__ChangeSet **changesets;
};
#define OSMPBF__PRIMITIVE_GROUP__INIT \
 { PROTOBUF_C_MESSAGE_INIT (&osmpbf__primitive_group__descriptor) \
    , 0,NULL, NULL, 0,NULL, 0,NULL, 0,NULL }

struct  _OSMPBF__StringTable
{
  ProtobufCMessage base;
  size_t n_s;
  ProtobufCBinaryData *s;
};
#define OSMPBF__STRING_TABLE__INIT \
 { PROTOBUF_C_MESSAGE_INIT (&osmpbf__string_table__descriptor) \
    , 0,NULL }

struct  _OSMPBF__Info
{
  ProtobufCMessage base;
  protobuf_c_boolean has_version;
  int32_t version;
  protobuf_c_boolean has_timestamp;
  int64_t timestamp;
  protobuf_c_boolean has_changeset;
  int64_t changeset;
  protobuf_c_boolean has_uid;
  int32_t uid;
  protobuf_c_boolean has_user_sid;
  uint32_t user_sid;
  protobuf_c_boolean has_visible;
  protobuf_c_boolean visible;
};
#define OSMPBF__INFO__INIT \
 { PROTOBUF_C_MESSAGE_INIT (&osmpbf__info__descriptor) \
    , 0,-1, 0,0, 0,0, 0,0, 0,0, 0,0 }

struct  _OSMPBF__DenseInfo
{
  ProtobufCMessage base;
  size_t n_version;
  int32_t *version;
  size_t n_timestamp;
  int64_t *timestamp;
  size_t n_changeset;
  int64_t *changeset;
  size_t n_uid;
  int32_t *uid;
  size_t n_user_sid;
  int32_t *user_sid;
  size_t n_visible;
  protobuf_c_boolean *visible;
};
#define OSMPBF__DENSE_INFO__INIT \
 { PROTOBUF_C_MESSAGE_INIT (&osmpbf__dense_info__descriptor) \
    , 0,NULL, 0,NULL, 0,NULL, 0,NULL, 0,NULL, 0,NULL }

struct  _OSMPBF__ChangeSet
{
  ProtobufCMessage base;
  int64_t id;
};
#define OSMPBF__CHANGE_SET__INIT \
 { PROTOBUF_C_MESSAGE_INIT (&osmpbf__change_set__descriptor) \
    , 0 }

struct  _OSMPBF__Node
{
  ProtobufCMessage base;
  int64_t id;
  size_t n_keys;
  uint32_t *keys;
  size_t n_vals;
  uint32_t *vals;
  OSMPBF__Info *info;
  int64_t lat;
  int64_t lon;
};
#define OSMPBF__NODE__INIT \
 { PROTOBUF_C_MESSAGE_INIT (&osmpbf__node__descriptor) \
    , 0, 0,NULL, 0,NULL, NULL, 0, 0 }

struct  _OSMPBF__DenseNodes
{
  ProtobufCMessage base;
  size_t n_id;
  int64_t *id;
  OSMPBF__DenseInfo *denseinfo;
  size_t n_lat;
  int64_t *lat;
  size_t n_lon;
  int64_t *lon;
  size_t n_keys_vals;
  int32_t *keys_vals;
};
#define OSMPBF__DENSE_NODES__INIT \
 { PROTOBUF_C_MESSAGE_INIT (&osmpbf__dense_nodes__descriptor) \
    , 0,NULL, NULL, 0,NULL, 0,NULL, 0,NULL }

struct  _OSMPBF__Way
{
  ProtobufCMessage base;
  int64_t id;
  size_t n_keys;
  uint32_t *keys;
  size_t n_vals;
  uint32_t *vals;
  OSMPBF__Info *info;
  size_t n_refs;
  int64_t *refs;
};
#define OSMPBF__WAY__INIT \
 { PROTOBUF_C_MESSAGE_INIT (&osmpbf__way__descriptor) \
    , 0, 0,NULL, 0,NULL, NULL, 0,NULL }

struct  _OSMPBF__Relation
{
  ProtobufCMessage base;
  int64_t id;
  size_t n_keys;
  uint32_t *keys;
  size_t n_vals;
  uint32_t *vals;
  OSMPBF__Info *info;
  size_t n_roles_sid;
  int32_t *roles_sid;
  size_t n_memids;
  int64_t *memids;
  size_t n_types;
  OSMPBF__Relation__MemberType *types;
};
#define OSMPBF__RELATION__INIT \
 { PROTOBUF_C_MESSAGE_INIT (&osmpbf__relation__descriptor) \
    , 0, 0,NULL, 0,NULL, NULL, 0,NULL, 0,NULL, 0,NULL }

/* OSMPBF__HeaderBlock methods */
void   osmpbf__header_block__init
                     (OSMPBF__HeaderBlock         *message);
size_t osmpbf__header_block__get_packed_size
                     (const OSMPBF__HeaderBlock   *message);
size_t osmpbf__header_block__pack
                     (const OSMPBF__HeaderBlock   *message,
                      uint8_t             *out);
size_t osmpbf__header_block__pack_to_buffer
                     (const OSMPBF__HeaderBlock   *message,
                      ProtobufCBuffer     *buffer);
OSMPBF__HeaderBlock *
       osmpbf__header_block__unpack
                     (ProtobufCAllocator  *allocator,
                      size_t               len,
                      const uint8_t       *data);
void   osmpbf__header_block__free_unpacked
                     (OSMPBF__HeaderBlock *message,
                      ProtobufCAllocator *allocator);
/* OSMPBF__HeaderBBox methods */
void   osmpbf__header_bbox__init
                     (OSMPBF__HeaderBBox         *message);
size_t osmpbf__header_bbox__get_packed_size
                     (const OSMPBF__HeaderBBox   *message);
size_t osmpbf__header_bbox__pack
                     (const OSMPBF__HeaderBBox   *message,
                      uint8_t             *out);
size_t osmpbf__header_bbox__pack_to_buffer
                     (const OSMPBF__HeaderBBox   *message,
                      ProtobufCBuffer     *buffer);
OSMPBF__HeaderBBox *
       osmpbf__header_bbox__unpack
                     (ProtobufCAllocator  *allocator,
                      size_t               len,
                      const uint8_t       *data);
void   osmpbf__header_bbox__free_unpacked
                     (OSMPBF__HeaderBBox *message,
                      ProtobufCAllocator *allocator);
/* OSMPBF__PrimitiveBlock methods */
void   osmpbf__primitive_block__init
                     (OSMPBF__PrimitiveBlock         *message);
size_t osmpbf__primitive_block__get_packed_size
                     (const OSMPBF__PrimitiveBlock   *message);
size_t osmpbf__primitive_block__pack
                     (const OSMPBF__PrimitiveBlock   *message,
                      uint8_t             *out);
size_t osmpbf__primitive_block__pack_to_buffer
                     (const OSMPBF__PrimitiveBlock   *message,
                      ProtobufCBuffer     *buffer);
OSMPBF__PrimitiveBlock *
       osmpbf__primitive_block__unpack
                     (ProtobufCAllocator  *allocator,
                      size_t               len,
                      const uint8_t       *data);
void   osmpbf__primitive_block__free_unpacked
                     (OSMPBF__PrimitiveBlock *message,
                      ProtobufCAllocator *allocator);
/* OSMPBF__PrimitiveGroup methods */
void   osmpbf__primitive_group__init
                     (OSMPBF__PrimitiveGroup         *message);
size_t osmpbf__primitive_group__get_packed_size
                     (const OSMPBF__PrimitiveGroup   *message);
size_t osmpbf__primitive_group__pack
                     (const OSMPBF__PrimitiveGroup   *message,
                      uint8_t             *out);
size_t osmpbf__primitive_group__pack_to_buffer
                     (const OSMPBF__PrimitiveGroup   *message,
                      ProtobufCBuffer     *buffer);
OSMPBF__PrimitiveGroup *
       osmpbf__primitive_group__unpack
                     (ProtobufCAllocator  *allocator,
                      size_t               len,
                      const uint8_t       *data);
void   osmpbf__primitive_group__free_unpacked
                     (OSMPBF__PrimitiveGroup *message,
                      ProtobufCAllocator *allocator);
/* OSMPBF__StringTable methods */
void   osmpbf__string_table__init
                     (OSMPBF__StringTable         *message);
size_t osmpbf__string_table__get_packed_size
                     (const OSMPBF__StringTable   *message);
size_t osmpbf__string_table__pack
                     (const OSMPBF__StringTable   *message,
                      uint8_t             *out);
size_t osmpbf__string_table__pack_to_buffer
                     (const OSMPBF__StringTable   *message,
                      ProtobufCBuffer     *buffer);
OSMPBF__StringTable *
       osmpbf__string_table__unpack
                     (ProtobufCAllocator  *allocator,
                      size_t               len,
                      const uint8_t       *data);
void   osmpbf__string_table__free_unpacked
                     (OSMPBF__StringTable *message,
                      ProtobufCAllocator *allocator);
/* OSMPBF__Info methods */
void   osmpbf__info__init
                     (OSMPBF__Info         *message);
size_t osmpbf__info__get_packed_size
                     (const OSMPBF__Info   *message);
size_t osmpbf__info__pack
                     (const OSMPBF__Info   *message,
                      uint8_t             *out);
size_t osmpbf__info__pack_to_buffer
                     (const OSMPBF__Info   *message,
                      ProtobufCBuffer     *buffer);
OSMPBF__Info *
       osmpbf__info__unpack
                     (ProtobufCAllocator  *allocator,
                      size_t               len,
                      const uint8_t       *data);
void   osmpbf__info__free_unpacked
                     (OSMPBF__Info *message,
                      ProtobufCAllocator *allocator);
/* OSMPBF__DenseInfo methods */
void   osmpbf__dense_info__init
                     (OSMPBF__DenseInfo         *message);
size_t osmpbf__dense_info__get_packed_size
                     (const OSMPBF__DenseInfo   *message);
size_t osmpbf__dense_info__pack
                     (const OSMPBF__DenseInfo   *message,
                      uint8_t             *out);
size_t osmpbf__dense_info__pack_to_buffer
                     (const OSMPBF__DenseInfo   *message,
                      ProtobufCBuffer     *buffer);
OSMPBF__DenseInfo *
       osmpbf__dense_info__unpack
                     (ProtobufCAllocator  *allocator,
                      size_t               len,
                      const uint8_t       *data);
void   osmpbf__dense_info__free_unpacked
                     (OSMPBF__DenseInfo *message,
                      ProtobufCAllocator *allocator);
/* OSMPBF__ChangeSet methods */
void   osmpbf__change_set__init
                     (OSMPBF__ChangeSet         *message);
size_t osmpbf__change_set__get_packed_size
                     (const OSMPBF__ChangeSet   *message);
size_t osmpbf__change_set__pack
                     (const OSMPBF__ChangeSet   *message,
                      uint8_t             *out);
size_t osmpbf__change_set__pack_to_buffer
                     (const OSMPBF__ChangeSet   *message,
                      ProtobufCBuffer     *buffer);
OSMPBF__ChangeSet *
       osmpbf__change_set__unpack
                     (ProtobufCAllocator  *allocator,
                      size_t               len,
                      const uint8_t       *data);
void   osmpbf__change_set__free_unpacked
                     (OSMPBF__ChangeSet *message,
                      ProtobufCAllocator *allocator);
/* OSMPBF__Node methods */
void   osmpbf__node__init
                     (OSMPBF__Node         *message);
size_t osmpbf__node__get_packed_size
                     (const OSMPBF__Node   *message);
size_t osmpbf__node__pack
                     (const OSMPBF__Node   *message,
                      uint8_t             *out);
size_t osmpbf__node__pack_to_buffer
                     (const OSMPBF__Node   *message,
                      ProtobufCBuffer     *buffer);
OSMPBF__Node *
       osmpbf__node__unpack
                     (ProtobufCAllocator  *allocator,
                      size_t               len,
                      const uint8_t       *data);
void   osmpbf__node__free_unpacked
                     (OSMPBF__Node *message,
                      ProtobufCAllocator *allocator);
/* OSMPBF__DenseNodes methods */
void   osmpbf__dense_nodes__init
                     (OSMPBF__DenseNodes         *message);
size_t osmpbf__dense_nodes__get_packed_size
                     (const OSMPBF__DenseNodes   *message);
size_t osmpbf__dense_nodes__pack
                     (const OSMPBF__DenseNodes   *message,
                      uint8_t             *out);
size_t osmpbf__dense_nodes__pack_to_buffer
                     (const OSMPBF__DenseNodes   *message,
                      ProtobufCBuffer     *buffer);
OSMPBF__DenseNodes *
       osmpbf__dense_nodes__unpack
                     (ProtobufCAllocator  *allocator,
                      size_t               len,
                      const uint8_t       *data);
void   osmpbf__dense_nodes__free_unpacked
                     (OSMPBF__DenseNodes *message,
                      ProtobufCAllocator *allocator);
/* OSMPBF__Way methods */
void   osmpbf__way__init
                     (OSMPBF__Way         *message);
size_t osmpbf__way__get_packed_size
                     (const OSMPBF__Way   *message);
size_t osmpbf__way__pack
                     (const OSMPBF__Way   *message,
                      uint8_t             *out);
size_t osmpbf__way__pack_to_buffer
                     (const OSMPBF__Way   *message,
                      ProtobufCBuffer     *buffer);
OSMPBF__Way *
       osmpbf__way__unpack
                     (ProtobufCAllocator  *allocator,
                      size_t               len,
                      const uint8_t       *data);
void   osmpbf__way__free_unpacked
                     (OSMPBF__Way *message,
                      ProtobufCAllocator *allocator);
/* OSMPBF__Relation methods */
void   osmpbf__relation__init
                     (OSMPBF__Relation         *message);
size_t osmpbf__relation__get_packed_size
                     (const OSMPBF__Relation   *message);
size_t osmpbf__relation__pack
                     (const OSMPBF__Relation   *message,
                      uint8_t             *out);
size_t osmpbf__relation__pack_to_buffer
                     (const OSMPBF__Relation   *message,
                      ProtobufCBuffer     *buffer);
OSMPBF__Relation *
       osmpbf__relation__unpack
                     (ProtobufCAllocator  *allocator,
                      size_t               len,
                      const uint8_t       *data);
void   osmpbf__relation__free_unpacked
                     (OSMPBF__Relation *message,
                      ProtobufCAllocator *allocator);
/* --- per-message closures --- */

typedef void (*OSMPBF__HeaderBlock_Closure)
                 (const OSMPBF__HeaderBlock *message,
                  void *closure_data);
typedef void (*OSMPBF__HeaderBBox_Closure)
                 (const OSMPBF__HeaderBBox *message,
                  void *closure_data);
typedef void (*OSMPBF__PrimitiveBlock_Closure)
                 (const OSMPBF__PrimitiveBlock *message,
                  void *closure_data);
typedef void (*OSMPBF__PrimitiveGroup_Closure)
                 (const OSMPBF__PrimitiveGroup *message,
                  void *closure_data);
typedef void (*OSMPBF__StringTable_Closure)
                 (const OSMPBF__StringTable *message,
                  void *closure_data);
typedef void (*OSMPBF__Info_Closure)
                 (const OSMPBF__Info *message,
                  void *closure_data);
typedef void (*OSMPBF__DenseInfo_Closure)
                 (const OSMPBF__DenseInfo *message,
                  void *closure_data);
typedef void (*OSMPBF__ChangeSet_Closure)
                 (const OSMPBF__ChangeSet *message,
                  void *closure_data);
typedef void (*OSMPBF__Node_Closure)
                 (const OSMPBF__Node *message,
                  void *closure_data);
typedef void (*OSMPBF__DenseNodes_Closure)
                 (const OSMPBF__DenseNodes *message,
                  void *closure_data);
typedef void (*OSMPBF__Way_Closure)
                 (const OSMPBF__Way *message,
                  void *closure_data);
typedef void (*OSMPBF__Relation_Closure)
                 (const OSMPBF__Relation *message,
                  void *closure_data);

/* --- services --- */

/* --- descriptors --- */

extern const ProtobufCMessageDescriptor osmpbf__header_block__descriptor;
extern const ProtobufCMessageDescriptor osmpbf__header_bbox__descriptor;
extern const ProtobufCMessageDescriptor osmpbf__primitive_block__descriptor;
extern const ProtobufCMessageDescriptor osmpbf__primitive_group__descriptor;
extern const ProtobufCMessageDescriptor osmpbf__string_table__descriptor;
extern const ProtobufCMessageDescriptor osmpbf__info__descriptor;
extern const ProtobufCMessageDescriptor osmpbf__dense_info__descriptor;
extern const ProtobufCMessageDescriptor osmpbf__change_set__descriptor;
extern const ProtobufCMessageDescriptor osmpbf__node__descriptor;
extern const ProtobufCMessageDescriptor osmpbf__dense_nodes__descriptor;
extern const ProtobufCMessageDescriptor osmpbf__way__descriptor;
extern const ProtobufCMessageDescriptor osmpbf__relation__descriptor;
extern const ProtobufCEnumDescriptor    osmpbf__relation__member_type__descriptor;

PROTOBUF_C_END_DECLS

#endif  /* PROTOBUF_osmformat_2eproto__INCLUDED */


text:
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division

from math import log
import tensorflow as tf

from tensorforce import util
from tensorforce.core.networks import Linear
from tensorforce.core.distributions import Distribution

class Beta(Distribution):
    """
    Beta distribution, for bounded continuous actions.
    """

    def __init__(self, shape, min_value, max_value, alpha=0.0, beta=0.0, scope='beta', summary_labels=()):
        """
        Beta distribution.

        Args:
            shape: Action shape.
            min_value: Minimum value of continuous actions.
            max_value: Maximum value of continuous actions.
            alpha: Optional distribution bias for the alpha value.
            beta: Optional distribution bias for the beta value.
        """
        assert min_value is None or max_value > min_value
        self.shape = shape
        self.min_value = min_value
        self.max_value = max_value
        action_size = util.prod(self.shape)

        self.alpha = Linear(size=action_size, bias=alpha, scope='alpha')
        self.beta = Linear(size=action_size, bias=beta, scope='beta')

        super(Beta, self).__init__(shape=shape, scope=scope, summary_labels=summary_labels)

    def tf_parameterize(self, x):
        # Softplus to ensure alpha and beta >= 1
        # epsilon < 1.0, hence negative
        log_eps = log(util.epsilon)

        alpha = self.alpha.apply(x=x)
        alpha = tf.clip_by_value(t=alpha, clip_value_min=log_eps, clip_value_max=-log_eps)
        alpha = tf.log(x=(tf.exp(x=alpha) + 1.0)) + 1.0

        beta = self.beta.apply(x=x)
        beta = tf.clip_by_value(t=beta, clip_value_min=log_eps, clip_value_max=-log_eps)
        beta = tf.log(x=(tf.exp(x=beta) + 1.0)) + 1.0

        shape = (-1,) + self.shape
        alpha = tf.reshape(tensor=alpha, shape=shape)
        beta = tf.reshape(tensor=beta, shape=shape)

        alpha_beta = tf.maximum(x=(alpha + beta), y=util.epsilon)
        log_norm = tf.lgamma(x=alpha) + tf.lgamma(x=beta) - tf.lgamma(x=alpha_beta)

        return alpha, beta, alpha_beta, log_norm

    def tf_sample(self, distr_params, deterministic):
        alpha, beta, alpha_beta, _ = distr_params

        # Deterministic: mean as action
        definite = beta / alpha_beta

        # Non-deterministic: sample action using gamma distribution
        alpha_sample = tf.random_gamma(shape=(), alpha=alpha)
        beta_sample = tf.random_gamma(shape=(), alpha=beta)

        sampled = beta_sample / tf.maximum(x=(alpha_sample + beta_sample), y=util.epsilon)

        return self.min_value + (self.max_value - self.min_value) * \
            tf.where(condition=deterministic, x=definite, y=sampled)

    def tf_log_probability(self, distr_params, action):
        alpha, beta, _, log_norm = distr_params
        action = (action - self.min_value) / (self.max_value - self.min_value)
        action = tf.minimum(x=action, y=(1.0 - util.epsilon))
        return (beta - 1.0) * tf.log(x=tf.maximum(x=action, y=util.epsilon)) + \
            (alpha - 1.0) * tf.log1p(x=-action) - log_norm

    def tf_entropy(self, distr_params):
        alpha, beta, alpha_beta, log_norm = distr_params
        return log_norm - (beta - 1.0) * tf.digamma(x=beta) - (alpha - 1.0) * tf.digamma(x=alpha) + \
            (alpha_beta - 2.0) * tf.digamma(x=alpha_beta)

    def tf_kl_divergence(self, distr_params1, distr_params2):
        alpha1, beta1, alpha_beta1, log_norm1 = distr_params1
        alpha2, beta2, alpha_beta2, log_norm2 = distr_params2
        return log_norm2 - log_norm1 - tf.digamma(x=beta1) * (beta2 - beta1) - \
            tf.digamma(x=alpha1) * (alpha2 - alpha1) + tf.digamma(x=alpha_beta1) * (alpha_beta2 - alpha_beta1)

    def tf_regularization_loss(self):
        regularization_loss = super(Beta, self).tf_regularization_loss()
        if regularization_loss is None:
            losses = list()
        else:
            losses = [regularization_loss]

        regularization_loss = self.alpha.regularization_loss()
        if regularization_loss is not None:
            losses.append(regularization_loss)

        regularization_loss = self.beta.regularization_loss()
        if regularization_loss is not None:
            losses.append(regularization_loss)

        if len(losses) > 0:
            return tf.add_n(inputs=losses)
        else:
            return None

    def get_variables(self, include_nontrainable=False):
        distribution_variables = super(Beta, self).get_variables(include_nontrainable=include_nontrainable)
        alpha_variables = self.alpha.get_variables(include_nontrainable=include_nontrainable)
        beta_variables = self.beta.get_variables(include_nontrainable=include_nontrainable)

        return distribution_variables + alpha_variables + beta_variables

    def get_summaries(self):
        distribution_summaries = super(Beta, self).get_summaries()
        alpha_summaries = self.alpha.get_summaries()
        beta_summaries = self.beta.get_summaries()

        return distribution_summaries + alpha_summaries + beta_summaries


text:
import nltk
import string
import re
import numpy as np
import pandas as pd
import pickle
import sys
import numpy as np
import os
import pandas as pd
from sklearn import preprocessing
import re
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
from nltk.corpus import stopwords
from sklearn.ensemble import RandomForestClassifier
from sklearn.naive_bayes import MultinomialNB
from sklearn.svm import SVC
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import accuracy_score , roc_auc_score , log_loss
import sklearn.linear_model as lm
from sklearn.model_selection import GridSearchCV
import Stemmer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics import roc_auc_score, log_loss
from numpy import linalg as LA
from sklearn import neighbors
from sklearn.neural_network import MLPClassifier
from bs4 import BeautifulSoup
#import xgboost as xgb
import matplotlib.pyplot as plt
import seaborn as sns
from nltk.stem.porter import *
from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.corpus import stopwords
from sklearn.feature_extraction import stop_words
from collections import Counter
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.decomposition import LatentDirichletAllocation
import numpy as np
import pandas as pd
from sklearn.model_selection import KFold
from sklearn.linear_model import Ridge
from sklearn.pipeline import FeatureUnion
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.metrics import mean_squared_log_error
from sklearn.metrics import fbeta_score, make_scorer

def split_cat(text):
    try: return text.split("/")
    except: return ("Other", "Other", "Other")

train = pd.read_csv('train.tsv', sep='\t')
test = pd.read_csv('test.tsv', sep='\t')
sample_submission = pd.read_csv("sample_submission.csv")

#train = train.iloc[:1000,:]
#test = test.iloc[:1000,:]

print(train.shape)
print(test.shape)

#
train['general_cat'], train['subcat_1'], train['subcat_2'] = zip(*train['category_name'].apply(lambda x: split_cat(x)))
test['general_cat'], test['subcat_1'], test['subcat_2'] = zip(*test['category_name'].apply(lambda x: split_cat(x)))

#
y_train = np.log1p(train['price'])
train = train.drop(['price'],axis=1)
#train['category_name'] = train['category_name'].fillna('Other').astype(str)
train['name'] = train['name'].fillna('Other').astype(str)
train['general_cat'] = train['general_cat'].fillna('Other').astype(str)
train['subcat_1'] = train['subcat_1'].fillna('Other').astype(str)
train['subcat_2'] = train['subcat_2'].fillna('Other').astype(str)
train['brand_name'] = train['brand_name'].fillna('Other').astype(str)
train['shipping'] = train['shipping'].fillna('None').astype(str)
train['item_condition_id'] = train['item_condition_id'].astype(str)
train['item_description'] = train['item_description'].fillna('None').astype(str)

test['name'] = test['name'].fillna('Other').astype(str)
test['general_cat'] = test['general_cat'].fillna('Other').astype(str)
test['subcat_1'] = test['subcat_1'].fillna('Other').astype(str)
test['subcat_2'] = test['subcat_2'].fillna('Other').astype(str)
test['brand_name'] = test['brand_name'].fillna('Other').astype(str)
test['shipping'] = test['shipping'].fillna('None').astype(str)
test['item_condition_id'] = test['item_condition_id'].astype(str)
test['item_description'] = test['item_description'].fillna('None').astype(str)
all_data = pd.concat([train,test],axis=0)
# we need a custom pre-processor to extract correct field,
# but want to also use default scikit-learn preprocessing (e.g. lowercasing)
default_preprocessor = CountVectorizer().build_preprocessor()
def build_preprocessor(field):
    field_idx = list(all_data.columns).index(field)
    return lambda x: default_preprocessor(x[field_idx])

vectorizer = FeatureUnion([
    ('name', CountVectorizer(
        ngram_range=(1, 2),
        max_features=50000,
        preprocessor=build_preprocessor('name'))),
    ('general_cat', CountVectorizer(
        token_pattern='.+',
        preprocessor=build_preprocessor('general_cat'))),
    ('subcat_1', CountVectorizer(
        token_pattern='.+',
        preprocessor=build_preprocessor('subcat_1'))),
    ('subcat_2', CountVectorizer(
        token_pattern='.+',
        preprocessor=build_preprocessor('subcat_2'))),
    ('brand_name', CountVectorizer(
        token_pattern='.+',
        preprocessor=build_preprocessor('brand_name'))),
    ('shipping', CountVectorizer(
        token_pattern='\d+',
        preprocessor=build_preprocessor('shipping'))),
    ('item_condition_id', CountVectorizer(
        token_pattern='\d+',
        preprocessor=build_preprocessor('item_condition_id'))),
    ('item_description', TfidfVectorizer(
        ngram_range=(1, 3),
        max_features=100000,
        preprocessor=build_preprocessor('item_description'))),
])
all_data_train = vectorizer.fit_transform(all_data.values)

train_obs = train.shape[0]
Xtrain = all_data_train[:train_obs,:]
Xtest = all_data_train[train_obs:,:]
assert Xtrain.shape[0] == train.shape[0]
assert Xtest.shape[0] == test.shape[0]

del train, test, all_data_train

#def my_rmsle(y_true, y_pred):
#	    return np.sqrt(mean_squared_log_error(np.expm1(y_true), np.expm1(y_pred)))
	    #return np.sqrt(mean_squared_log_error(y_true, y_pred))
	#rmsle_scorer = make_scorer(my_rmsle)

def my_rmsle(y_true,y_pred):
   #y_true = np.expm1(y_true)
   #y_pred = np.expm1(y_pred)
   assert len(y_true) == len(y_pred)
   return np.sqrt(np.mean(np.power(np.log1p(y_pred)-np.log1p(y_true), 2)))
   #return np.square(np.log(y_pred + 1) - np.log(y_true + 1)).mean() ** 0.5

## Whether score_func is a score function (default), meaning high is good, or a loss function, meaning low is good.
## In the latter case, the scorer object will sign-flip the outcome of the score_func.
rmsle_scorer = make_scorer(my_rmsle, greater_is_better=False)

model = Ridge(alpha=0.5)
grid_clf = GridSearchCV(estimator=model, param_grid={'alpha': [0.1,0.3,0.5,0,8,1,1.2,5,7,10,50],'fit_intercept': [True, False]},cv=4, scoring=rmsle_scorer, n_jobs=10, iid=False)

print(np.expm1(y_train).head())
grid_clf.fit(Xtrain, y_train)
print("best params:",grid_clf.best_params_)

print(grid_clf.cv_results_['mean_test_score'])

best_idx = grid_clf.best_index_
print("best rmsle:", -1*grid_clf.cv_results_['mean_test_score'][best_idx] , " - std:",grid_clf.cv_results_['std_test_score'][best_idx])
sys.stdout.flush()

grid = pd.DataFrame({'alpha' : [grid_clf.best_params_['alpha']],
	'fit_intercept': [grid_clf.best_params_['fit_intercept']],
	'best_rmsle': [-1*grid_clf.cv_results_['mean_test_score'][best_idx]] ,
	'best_rmsle_std': [grid_clf.cv_results_['std_test_score'][best_idx]]})

grid.to_csv('best_rmsle_ridge.csv',index=False)

print(">> predicting on test set ... ")
pred_test = grid_clf.predict(Xtest)
sample_submission['price'] = np.expm1(pred_test)
print(">> sample submission")
print(sample_submission.head())
grid.to_csv('ridge_sub.csv.gz',index=False,compression='gzip')


text:
'use strict';

import { WebviewExtension } from '../webview_extension';

export class KeyboardCallbacksExtension implements WebviewExtension {
    public generateContent(): string {
        return `\
document.addEventListener('keydown', function(evt) {
    const i = evt.keyCode;
    if (i >= 0 && i <= 255) {
        // Key is being held, don't register input
        if (keyBoardData[i] == 0) {
            keyBoardData[i] = 255; // Held
            keyBoardData[i + 256] = 255; // Pressed
            keyBoardData[i + 512] = (keyBoardData[i + 512] == 255 ? 0 : 255); // Toggled

            if (keyBoardData[i + 512] > 0) {
                toggledKeys.push(i);
            }
            else {
                toggledKeys = toggledKeys.filter(function(value, index, arr){
                    return value != i;
                });
            }

            pressedKeys.push(i);
            keyBoardTexture.needsUpdate = true;
        }
    }
});
document.addEventListener('keyup', function(evt) {
    const i = evt.keyCode;
    if (i >= 0 && i <= 255) {
        keyBoardData[i] = 0; // Not held
        keyBoardData[i + 768] = 255; // Released
        releasedKeys.push(i);
        keyBoardTexture.needsUpdate = true;
    }
});`;
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Gautieria morchelliformis var. globispora Pilát

### Remarks
null