text:
<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Dosis;

/**
 * DosisSearch represents the model behind the search form about `app\models\Dosis`.
 */
class DosisSearch extends Dosis
{
    /**
     * @inheritdoc
     */

    public $insumo;

    public function rules()
    {
        return [
            [['id_dosis', 'insumo_id'], 'integer'],
            [['cantidad'], 'number'],
            ['insumo', 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Dosis::find();

        $query->joinWith(['insumo']);

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        $dataProvider->sort->attributes['insumo'] = [
            'asc' => ['insumo.nombre_insumo' => SORT_ASC],
            'desc' => ['insumo.nombre_insumo' => SORT_DESC],
        ];

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id_dosis' => $this->id_dosis,
            'insumo_id' => $this->insumo_id,
            'cantidad' => $this->cantidad,
        ]);

        $query->andFilterWhere(['like', 'insumo.nombre_insumo', $this->insumo]);

        return $dataProvider;
    }
}


text:
package org.vivek.algo.wk2;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class QuickSortTest {

	private QuickSort firstElementBased;
	private QuickSort lastElementBased;
	private QuickSort medianElementBased;

	@Before
	public void setUp() throws Exception {
		firstElementBased = new FirstElementBasedQuickSort();
		lastElementBased = new LastElementBasedQuickSort();
		medianElementBased = new MedianElementBasedQuickSort();
	}

	@After
	public void tearDown() throws Exception {

	}

	@Test
	public void testSortFor10() throws Exception {

		String fileName = "10.txt";
		assertEquals(Long.valueOf(25), firstElementBased.sort(fileName));
		assertEquals(Long.valueOf(29), lastElementBased.sort(fileName));
		assertEquals(Long.valueOf(21), medianElementBased.sort(fileName));
	}

	@Test
	public void testSortFor100() throws Exception {

		String fileName = "100.txt";
		assertEquals(Long.valueOf(615), firstElementBased.sort(fileName));
		assertEquals(Long.valueOf(587), lastElementBased.sort(fileName));
		assertEquals(Long.valueOf(518), medianElementBased.sort(fileName));
	}

	@Test
	public void testSortFor1000() throws Exception {

		String fileName = "1000.txt";
		assertEquals(Long.valueOf(10297), firstElementBased.sort(fileName));
		assertEquals(Long.valueOf(10184), lastElementBased.sort(fileName));
		assertEquals(Long.valueOf(8921), medianElementBased.sort(fileName));
	}
}

redpajama_set_name: RedPajamaGithub


text:
var $collectionHolder;

// setup an "add a tag" link
var $addTagLink = $('Adicionar Dependente');
var $newLinkLi = $('

').append($addTagLink);
function addTagForm($collectionHolder, $newLinkLi) {
    // Get the data-prototype explained earlier
    var prototype = $collectionHolder.data('prototype');

    // get the new index
    var index = $collectionHolder.data('index');

    // Replace '__name__' in the prototype's HTML to
    // instead be a number based on how many items we have
    var newForm = prototype.replace(/__name__/g, index);

    // increase the index with one for the next item
    $collectionHolder.data('index', index + 1);

    // Display the form in the page in an li, before the "Add a tag" link li
    var $newFormLi = $('

').append(newForm);
    $newLinkLi.before($newFormLi);

    addTagFormDeleteLink($newFormLi);
}

function addTagFormDeleteLink($tagFormLi) {
    var $removeFormA = $('Excluir Dependente');
    $tagFormLi.append($removeFormA);

    $removeFormA.on('click', function(e) {
        // prevent the link from creating a "#" on the URL
        e.preventDefault();

        // remove the li for the tag form
        $tagFormLi.remove();
    });
}
jQuery(document).ready(function() {
    // Get the ul that holds the collection of tags
    $collectionHolder = $('#dadosfuncionario_dependentes');

    // add the "add a tag" anchor and li to the tags ul
    $collectionHolder.append($newLinkLi);

    // count the current form inputs we have (e.g. 2), use that as the new
    // index when inserting a new item (e.g. 2)
    $collectionHolder.data('index', $collectionHolder.find(':input').length);

    $addTagLink.on('click', function(e) {
        // prevent the link from creating a "#" on the URL
        e.preventDefault();

        // add a new tag form (see next code block)
        addTagForm($collectionHolder, $newLinkLi);
    });

    // add a delete link to all of the existing tag form li elements
    $collectionHolder.find('.tag_form').each(function() {
        addTagFormDeleteLink($(this));
    });
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:activiti="http://activiti.org/bpmn" targetNamespace="Examples">

  <process id="TestFixture62.nestedSingleEmbeddedSubprocess">

    <startEvent id="outerStart" />
    <sequenceFlow sourceRef="outerStart" targetRef="outerProcess" />
    <subProcess id="outerProcess">

      <startEvent id="theStart" />
      <sequenceFlow sourceRef="theStart" targetRef="scope1" />
      <subProcess id="scope1">

        <startEvent id="startInside1" />
        <sequenceFlow sourceRef="startInside1" targetRef="waitInside1" />

        <userTask id="waitInside1" />

        <sequenceFlow sourceRef="waitInside1" targetRef="endInside1" />
        <endEvent id="endInside1" />

      </subProcess>
      <sequenceFlow sourceRef="scope1" targetRef="theEnd" />
      <endEvent id="theEnd" />

    </subProcess>
    <sequenceFlow sourceRef="outerProcess" targetRef="outerEnd" />
    <endEvent id="outerEnd" />

  </process>

</definitions>


text:
"""
Command line tool for baking AMI's and otherwise working with them.
"""

from __future__ import print_function
import sys
import argparse
from collections import OrderedDict

from bin import print_table
from disco_aws_automation import DiscoBake, HostclassTemplating
from disco_aws_automation.disco_aws_util import run_gracefully
from disco_aws_automation.disco_logging import configure_logging

# R0912 Allow more than 12 branches so we can parse a lot of commands..
# pylint: disable=R0912,R0915
def get_parser():
    '''Returns command line parser'''
    parser = argparse.ArgumentParser(description='Disco AWS image creation & management')
    parser.add_argument('--debug', dest='debug', action='store_const', const=True, default=False,
                        help='Log in debug level.')
    parser.add_argument('--truncate', dest='truncate', action='store_true',
                        help='Truncate extra long fields in output.')
    subparsers = parser.add_subparsers(help='Sub-command help')

    parser_promote = subparsers.add_parser("promote", help="promote / demote an ami to an env.")
    parser_promote.set_defaults(mode="promote")
    parser_promote.add_argument("--ami", dest="ami", required=True,
                                help="AMI image id", type=str)
    parser_promote.add_argument("--stage", dest="stage", required=True,
                                help="Which stage to promote to", type=str)
    parser_promote.add_argument('--promote-to-prod', dest='promote_to_prod', action='store_const', const=True,
                                default=False, help='Make the AMI executable by prod account')

    parser_hostclass_promote = subparsers.add_parser(
        "hostclasspromote",
        help="Promote youngest AMI of latest stage to production.")
    parser_hostclass_promote.set_defaults(mode="hostclasspromote")
    parser_hostclass_promote.add_argument(
        "--hostclass", dest="hostclass", required=True,
        help="Name of hostclass to promote", type=str)

    parser_listamis = subparsers.add_parser('listamis', help='List all AMIs')
    parser_listamis.set_defaults(mode="listamis")
    parser_listamis.add_argument('--ami', dest='ami', required=False, help='AMI image id',
                                 type=str, default=None)
    parser_listamis.add_argument('--instance', dest='instance', required=False, help='Instance id',
                                 type=str, default=None)
    parser_listamis.add_argument('--stage', dest='stage', required=False,
                                 help='Only show amis available to this stage.', type=str, default=None)
    parser_listamis.add_argument('--productline', dest='product_line', required=False,
                                 help='Only show amis baked by this product line.', type=str, default=None)
    parser_listamis.add_argument('--state', dest='state', required=False,
                                 help='Only show amis in this state.', type=str, default=None)
    parser_listamis.add_argument('--hostclass', dest='hostclass', required=False,
                                 help='Only show amis for this hostclass.', type=str, default=None)
    parser_listamis.add_argument('--in-prod', dest='in_prod', action='store_const', const=True,
                                 help='Show whether AMI is executable in prod.', default=False)
    parser_listamis.add_argument('--show-tags', dest='show_tags', action='store_const', const=True,
                                 help='Show any additional tags on the AMI', default=False)

    parser_liststragglers = subparsers.add_parser(
        'liststragglers', help='List hostclasses for which AMIs have not been recently promoted')
    parser_liststragglers.set_defaults(mode="liststragglers")
    parser_liststragglers.add_argument(
        '--days', dest='days', required=False,
        help='Set how recently AMI must have been promoted', type=int, default=3)

    parser_listlatestami = subparsers.add_parser(
        'listlatestami', help='Lists the latest ami for a given hostclass and stage')
    parser_listlatestami.set_defaults(mode="listlatestami")
    parser_listlatestami.add_argument('--stage', dest='stage', required=True,
                                      help='Display the latest ami for this stage or later', type=str)
    parser_listlatestami.add_argument('--hostclass', dest='hostclass', required=True,
                                      help='Display the latest ami for this hostclass.', type=str)
    parser_listlatestami.add_argument('--in-prod', dest='in_prod', action='store_const', const=True,
                                      help='Show whether AMI is executable in prod.', default=False)
    parser_listlatestami.add_argument('--show-tags', dest='show_tags', action='store_const', const=True,
                                      help='Show any additional tags on the AMI', default=False)

    parser_deleteami = subparsers.add_parser('deleteami', help='Delete AMI')
    parser_deleteami.set_defaults(mode="deleteami")
    parser_deleteami.add_argument('--ami', dest='ami', required=True, help='AMI image id',
                                  type=str, default=None)

    parser_cleanupamis = subparsers.add_parser('cleanupamis', help='Delete old (by date, or count) amis')
    parser_cleanupamis.set_defaults(mode="cleanupamis")
    parser_cleanupamis.add_argument('--stage', dest='stage', required=True,
                                    help='Restrict to environment type', type=str, default=None)
    parser_cleanupamis.add_argument('--keep', dest='count', required=False,
                                    help='Minimum number of images to keep', type=int, default=3)
    parser_cleanupamis.add_argument('--age', dest='days', required=False,
                                    help='Minimum age of images to expire', type=int, default=14)
    parser_cleanupamis.add_argument('--hostclass', type=str, required=False,
                                    help='Restrict to this hostclass', default=None)
    parser_cleanupamis.add_argument('--productline', dest="product_line", type=str, required=False,
                                    help='Restrict to this productline', default=None)
    parser_cleanupamis.add_argument('--dryrun', dest='dryrun', action='store_const', const=True,
                                    default=False, help='Print out amis to be deleted without deleting them')
    parser_cleanupamis.add_argument('--exclude-amis', dest='exclude_amis', type=str, default='',
                                    help="A comma seperated list of AMIs to not delete")

    parser_bake = subparsers.add_parser('bake', help="Create an ami",
                                        description="Phase1 AMI is created if hostclass is omited. "
                                        "Else latest AMI is used to generate phase2, "
                                        "hostclass specific image.")
    parser_bake.set_defaults(mode="bake")
    parser_bake.add_argument('--hostclass', type=str, default=None)
    parser_bake.add_argument('--no-destroy', dest='no_destroy', action='store_const', const=True,
                             default=False, help='If bake fails do not terminate instance')
    parser_bake.add_argument("--stage", dest="stage", default=None,
                             help="Which stage to tag baked ami with", type=str)
    parser_bake.add_argument('--source-ami', type=str, default=None,
                             help='The ami to be used as a base for baking')
    parser_bake.add_argument('--use-local-ip', dest='use_local_ip', action='store_const',
                             const=True, default=False,
                             help="Use instances' local ip address for operations. "
                             "Set this flag when baking from same subnet as where the baking is occuring.")
    parser_bake.add_argument('--tag', dest='tags', required=False, action='append', type=str, default=[],
                             help='The key:value pair used to tag the AMI '
                                  '(Example: --tag application:dnext)')
    parser_bake.add_argument('--private', dest='is_private', action='store_const', const=True,
                             default=False, help='Tag the baked ami as "private". The AMI will not be visible'
                                                 ' to disco_deploy.py or disco_aws.py provision.')

    parser_create = subparsers.add_parser(
        'create', help="Create a hostclass",
        description="Creates the necessary bits for a generic hostclass")
    parser_create.set_defaults(mode="create")
    parser_create.add_argument('--hostclass', type=str, default=None, required=True)

    parser_list_repo = subparsers.add_parser('listrepo', help="Print info about repo instance",
                                             description="")
    parser_list_repo.set_defaults(mode="listrepo")

    return parser

def run():
    """Parses command line and dispatches the commands"""
    parser = get_parser()
    args = parser.parse_args()
    configure_logging(args.debug)

    if args.mode == "bake":
        extra_tags = OrderedDict(tag.split(':', 1) for tag in args.tags)
        bakery = DiscoBake(use_local_ip=args.use_local_ip)
        bakery.bake_ami(args.hostclass, args.no_destroy, args.source_ami, args.stage, args.is_private,
                        extra_tags=extra_tags)
    elif args.mode == "create":
        HostclassTemplating.create_hostclass(args.hostclass)
    elif args.mode == "promote":
        bakery = DiscoBake()
        ami = bakery.get_image(args.ami)
        bakery.promote_ami(ami, args.stage)
        if args.promote_to_prod:
            bakery.promote_ami_to_production(ami)
    elif args.mode == "hostclasspromote":
        bakery = DiscoBake()
        bakery.promote_latest_ami_to_production(args.hostclass)
    elif args.mode == "listrepo":
        bakery = DiscoBake()
        repo = bakery.repo_instance()
        if repo:
            print(repo.ip_address)
    elif args.mode == "listamis":
        ami_ids = [args.ami] if args.ami else None
        instance_ids = [args.instance] if args.instance else None
        bakery = DiscoBake()
        amis = sorted(
            bakery.list_amis(
                ami_ids,
                instance_ids,
                args.stage,
                args.product_line,
                args.state,
                args.hostclass
            ),
            key=bakery.ami_timestamp
        )
        headers, output = bakery.tabilize_amis(
            amis=amis,
            in_prod=args.in_prod,
            show_tags=args.show_tags
        )
        print_table(headers=headers, rows=output)
        if not amis:
            sys.exit(1)
    elif args.mode == "liststragglers":
        bakery = DiscoBake()
        for hostclass, image in bakery.list_stragglers(args.days).iteritems():
            print("{0}\t{1}".format(hostclass, image.id if image else '-'))
    elif args.mode == "listlatestami":
        bakery = DiscoBake()
        ami = bakery.find_ami(args.stage, args.hostclass)
        if ami:
            headers, output = bakery.tabilize_amis(
                amis=[ami],
                in_prod=args.in_prod,
                show_tags=args.show_tags
            )
            print_table(headers=headers, rows=output)
        else:
            sys.exit(1)
    elif args.mode == "deleteami":
        bakery = DiscoBake()
        bakery.delete_ami(args.ami)
    elif args.mode == "cleanupamis":
        bakery = DiscoBake()
        exclude_amis = args.exclude_amis.split(',')
        bakery.cleanup_amis(
            args.hostclass,
            args.product_line,
            args.stage,
            args.days,
            args.count,
            args.dryrun,
            exclude_amis
        )

if __name__ == "__main__":
    run_gracefully(run)


text:
require 'spec_helper'

describe ActiveData::Model::Attributes do
  let(:model) do
    stub_model do
      include ActiveData::Model::Associations
      include ActiveData::Model::Localization

      attribute :id, Integer
      attribute :full_name, String
      alias_attribute :name, :full_name

      localized :t, String
      alias_attribute :title, :t

      embeds_one(:author) {}
      embeds_many(:projects) {}
    end
  end

  describe '.reflect_on_attribute' do
    specify { expect(model.reflect_on_attribute(:full_name).name).to eq('full_name') }
    specify { expect(model.reflect_on_attribute('full_name').name).to eq('full_name') }
    specify { expect(model.reflect_on_attribute(:name).name).to eq('full_name') }
    specify { expect(model.reflect_on_attribute(:foobar)).to be_nil }
  end

  describe '.has_attribute?' do
    specify { expect(model.has_attribute?(:full_name)).to eq(true) }
    specify { expect(model.has_attribute?('full_name')).to eq(true) }
    specify { expect(model.has_attribute?(:name)).to eq(true) }
    specify { expect(model.has_attribute?(:foobar)).to eq(false) }
  end

  describe '.attribute_names' do
    specify { expect(stub_model.attribute_names).to eq([]) }
    specify { expect(model.attribute_names).to eq(%w[id full_name t author projects]) }
    specify { expect(model.attribute_names(false)).to eq(%w[id full_name t]) }
  end

  describe '.inspect' do
    specify { expect(stub_model.inspect).to match(/#<Class:0x\w+>\(no attributes\)/) }
    specify { expect(stub_model(:user).inspect).to eq('User(no attributes)') }
    specify do
      expect(stub_model do
               include ActiveData::Model::Primary
               primary :count, Integer
               attribute :object, Object
             end.inspect).to match(/#<Class:0x\w+>\(\*count: Integer, object: Object\)/) end
    specify do
      expect(stub_model(:user) do
               include ActiveData::Model::Primary
               primary :count, Integer
               attribute :object, Object
             end.inspect).to match('User(*count: Integer, object: Object)') end
  end

  describe '#==' do
    let(:model) do
      stub_model do
        attribute :name, String
        attribute :count, Float, default: 0
      end
    end
    subject { model.new name: 'hello', count: 42 }

    it { is_expected.not_to eq(nil) }
    it { is_expected.not_to eq('hello') }
    it { is_expected.not_to eq(Object.new) }
    it { is_expected.not_to eq(model.new) }
    it { is_expected.not_to eq(model.new(name: 'hello1', count: 42)) }
    it { is_expected.not_to eq(model.new(name: 'hello', count: 42.1)) }
    it { is_expected.to eq(model.new(name: 'hello', count: 42)) }

    it { is_expected.not_to eql(nil) }
    it { is_expected.not_to eql('hello') }
    it { is_expected.not_to eql(Object.new) }
    it { is_expected.not_to eql(model.new) }
    it { is_expected.not_to eql(model.new(name: 'hello1', count: 42)) }
    it { is_expected.not_to eql(model.new(name: 'hello', count: 42.1)) }
    it { is_expected.to eql(model.new(name: 'hello', count: 42)) }
  end

  describe '#attribute' do
    let(:instance) { model.new }
    specify { expect(instance.attribute(:full_name).reflection.name).to eq('full_name') }
    specify { expect(instance.attribute('full_name').reflection.name).to eq('full_name') }
    specify { expect(instance.attribute(:name).reflection.name).to eq('full_name') }
    specify { expect(instance.attribute(:foobar)).to be_nil }

    specify { expect(instance.attribute('full_name')).to equal(instance.attribute(:name)) }
  end

  describe '#has_attribute?' do
    specify { expect(model.new.has_attribute?(:full_name)).to eq(true) }
    specify { expect(model.new.has_attribute?('full_name')).to eq(true) }
    specify { expect(model.new.has_attribute?(:name)).to eq(true) }
    specify { expect(model.new.has_attribute?(:foobar)).to eq(false) }
  end

  describe '#attribute_names' do
    specify { expect(stub_model.new.attribute_names).to eq([]) }
    specify { expect(model.new.attribute_names).to eq(%w[id full_name t author projects]) }
    specify { expect(model.new.attribute_names(false)).to eq(%w[id full_name t]) }
  end

  describe '#attribute_present?' do
    specify { expect(model.new.attribute_present?(:name)).to be(false) }
    specify { expect(model.new(name: '').attribute_present?(:name)).to be(false) }
    specify { expect(model.new(name: 'Name').attribute_present?(:name)).to be(true) }
  end

  describe '#attributes' do
    specify { expect(stub_model.new.attributes).to eq({}) }
    specify do
      expect(model.new(name: 'Name').attributes)
        .to match('id' => nil, 'full_name' => 'Name', 't' => {}, 'author' => nil, 'projects' => nil)
    end
    specify do
      expect(model.new(name: 'Name').attributes(false))
        .to match('id' => nil, 'full_name' => 'Name', 't' => {})
    end
  end

  describe '#assign_attributes' do
    let(:attributes) { {id: 42, full_name: 'Name', missed: 'value'} }
    subject { model.new }

    specify { expect { subject.assign_attributes(attributes) }.to change { subject.id }.to(42) }
    specify { expect { subject.assign_attributes(attributes) }.to change { subject.full_name }.to('Name') }

    context 'features stack and assign order' do
      let(:model) do
        stub_model do
          attr_reader :logger

          def self.log(a)
            define_method("#{a}=") do |*args|
              log(a)
              super(*args)
            end
          end

          def log(o)
            (@logger ||= []).push(o)
          end

          attribute :plain1, String
          attribute :plain2, String
          log(:plain1)
          log(:plain2)
        end
      end
      subject { model.new }

      specify do
        expect { subject.assign_attributes(plain1: 'value', plain2: 'value') }
          .to change { subject.logger }.to(%i[plain1 plain2])
      end

      specify do
        expect { subject.assign_attributes(plain2: 'value', plain1: 'value') }
          .to change { subject.logger }.to(%i[plain2 plain1])
      end

      context do
        before do
          model.class_eval do
            include ActiveData::Model::Representation
            include ActiveData::Model::Associations

            embeds_one :assoc do
              attribute :assoc_plain, String
            end
            accepts_nested_attributes_for :assoc

            represents :assoc_plain, of: :assoc

            log(:assoc_attributes)
            log(:assoc_plain)

            def assign_attributes(attrs)
              super attrs.merge(attrs.extract!('plain2'))
            end
          end
        end

        specify do
          expect { subject.assign_attributes(assoc_plain: 'value', assoc_attributes: {}, plain1: 'value', plain2: 'value') }
            .to change { subject.logger }.to(%i[plain1 assoc_attributes assoc_plain plain2])
        end

        specify do
          expect { subject.assign_attributes(plain1: 'value', plain2: 'value', assoc_plain: 'value', assoc_attributes: {}) }
            .to change { subject.logger }.to(%i[plain1 assoc_attributes assoc_plain plain2])
        end
      end
    end
  end

  describe '#inspect' do
    specify { expect(stub_model.new.inspect).to match(/#<#<Class:0x\w+> \(no attributes\)>/) }
    specify { expect(stub_model(:user).new.inspect).to match(/#<User \(no attributes\)>/) }
    specify do
      expect(stub_model do
               include ActiveData::Model::Primary
               primary :count, Integer
               attribute :object, Object
             end.new(object: 'String').inspect).to match(/#<#<Class:0x\w+> \*count: nil, object: "String">/) end
    specify do
      expect(stub_model(:user) do
               include ActiveData::Model::Primary
               primary :count, Integer
               attribute :object, Object
             end.new.inspect).to match(/#<User \*count: nil, object: nil>/) end
  end

  context 'attributes integration' do
    let(:model) do
      stub_class do
        include ActiveData::Model::Attributes
        include ActiveData::Model::Associations
        attr_accessor :name

        attribute :id, Integer
        attribute :hello, Object
        attribute :string, String, default: ->(record) { record.name }
        attribute :count, Integer, default: '10'
        attribute(:calc, Integer) { 2 + 3 }
        attribute :enum, Integer, enum: [1, 2, 3]
        attribute :enum_with_default, Integer, enum: [1, 2, 3], default: '2'
        attribute :foo, Boolean, default: false
        collection :array, Integer, enum: [1, 2, 3], default: 7

        def initialize(name = nil)
          super()
          @name = name
        end
      end
    end

    subject { model.new('world') }

    its(:enum_values) { should == [1, 2, 3] }
    its(:string_default) { should == 'world' }
    its(:count_default) { should == '10' }
    its(:name) { should == 'world' }
    its(:hello) { should eq(nil) }
    its(:hello?) { should eq(false) }
    its(:count) { should == 10 }
    its(:count_before_type_cast) { should == '10' }
    its(:count_came_from_user?) { should eq(false) }
    its(:count?) { should eq(true) }
    its(:calc) { should == 5 }
    its(:enum?) { should eq(false) }
    its(:enum_with_default?) { should eq(true) }
    specify { expect { subject.hello = 'worlds' }.to change { subject.hello }.from(nil).to('worlds') }
    specify { expect { subject.count = 20 }.to change { subject.count }.from(10).to(20) }
    specify { expect { subject.calc = 15 }.to change { subject.calc }.from(5).to(15) }
    specify { expect { subject.count = '11' }.to change { subject.count_came_from_user? }.from(false).to(true) }

    context 'enums' do
      specify do
        subject.enum = 3
        expect(subject.enum).to eq(3)
      end
      specify do
        subject.enum = '3'
        expect(subject.enum).to eq(3)
      end
      specify do
        subject.enum = 10
        expect(subject.enum).to eq(nil)
      end
      specify do
        subject.enum = 'hello'
        expect(subject.enum).to eq(nil)
      end
      specify do
        subject.enum_with_default = 3
        expect(subject.enum_with_default).to eq(3)
      end
      specify do
        subject.enum_with_default = 10
        expect(subject.enum_with_default).to be_nil
      end
    end

    context 'array' do
      specify do
        subject.array = [2, 4]
        expect(subject.array).to eq([2, nil])
      end
      specify do
        subject.array = [2, 4]
        expect(subject.array?).to eq(true)
      end
      specify do
        subject.array = [2, 4]
        expect(subject.array_values).to eq([1, 2, 3])
      end
      specify do
        subject.array = [2, 4]
        expect(subject.array_default).to eq(7)
      end
    end

    context 'attribute caching' do
      before do
        subject.hello = 'blabla'
        subject.hello
        subject.hello = 'newnewnew'
      end

      specify { expect(subject.hello).to eq('newnewnew') }
    end
  end

  context 'inheritance' do
    let!(:ancestor) do
      Class.new do
        include ActiveData::Model::Attributes
        attribute :foo, String
      end
    end

    let!(:descendant1) do
      Class.new ancestor do
        attribute :bar, String
      end
    end

    let!(:descendant2) do
      Class.new ancestor do
        attribute :baz, String
        attribute :moo, String
      end
    end

    specify { expect(ancestor._attributes.keys).to eq(['foo']) }
    specify { expect(ancestor.instance_methods).to include :foo, :foo= }
    specify { expect(ancestor.instance_methods).not_to include :bar, :bar=, :baz, :baz= }
    specify { expect(descendant1._attributes.keys).to eq(%w[foo bar]) }
    specify { expect(descendant1.instance_methods).to include :foo, :foo=, :bar, :bar= }
    specify { expect(descendant1.instance_methods).not_to include :baz, :baz= }
    specify { expect(descendant2._attributes.keys).to eq(%w[foo baz moo]) }
    specify { expect(descendant2.instance_methods).to include :foo, :foo=, :baz, :baz=, :moo, :moo= }
    specify { expect(descendant2.instance_methods).not_to include :bar, :bar= }
  end
end


text:
MuzeiBGG
========

BoardGameGeek for Muzei

A wallpaper source for Muzei that displays the images from BoardGameGeek.com's Hotness list.

1. Install [Muzei](https://play.google.com/store/apps/details?id=net.nurik.roman.muzei) from the Play Store
2. Install [MuzeiBGG](https://play.google.com/store/apps/details?id=com.eaux.app.muzei.bgg) from the Play Store
3. Launch Muzei and choose BoardGameGeek as the source. An image from the hotness list will be displayed as your wallpaper.


text:
require('dotenv').config();
const nodemailer = require('nodemailer');
const utils = require('util');
Parse.Cloud.define('hello', function (req, res) {
  res.success('Hi');
});

const qp = { useMasterKey: true };

Parse.Cloud.beforeSave("Package", function (request, response) {
  if (typeof request.object.id !== 'undefined') {
    response.success();
  }

  var query = new Parse.Query("Package");
  query.descending("packageId");
  query.first(qp)
    .then(pkg => {
      var serialNumber = 999;
      if (typeof pkg !== 'undefined' && pkg) {
        serialNumber = pkg.get("packageId");
      }
      request.object.set("packageId", serialNumber + 1);
      response.success();
    })
    .catch(err => {
      console.log("CloudCode::Package::beforeSave::Error -->", err)
      response.error("internal server error");
    });
});

var transporter = nodemailer.createTransport({
  host: process.env.SMTP_HOST,
  port: process.env.SMTP_PORT || 2525,
  auth: {
    user: process.env.SMTP_USER,
    pass: process.env.SMTP_PASSWORD
  }
});

Parse.Cloud.afterSave("Package", function (request) {
  const mapper = o => o.toJSON();
  let query = new Parse.Query('Package');
  query.equalTo('objectId', request.object.id);
  query.include('owner');
  query.include('vendor');
  query.include('pickedBy');
  query.find(qp).then((result) => {
    const package = result.map(mapper)[0];
    var passcode = package.objectId;
    var arrivalNotified = package.arrivalNotified || false;
    var collectionNotified = package.collectionNotified || false;
    var mailOptions = {
      from: process.env.SMTP_FROM_EMAIL,
      to: package.owner.email
    };

    // Send package arrival notification
    if (package.status == false && arrivalNotified == false) {
      mailOptions.subject = utils.format(`Your parcel has arrived.`);
      mailOptions.text = utils.format('Your parcel has arrived. Please pickup your parcel from security desk.\n\nParcel details:\nParcel Number : %s\nVendor : %s\nAWB Number : %s\nPasscode : %s\n\nUse either your access card or given passcode to collect your parcel from security desk.', package.packageId, package.vendor.name, package.awpNo, passcode);

      transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
          return console.log(error);
        }
        console.log('Parcel arrival message %s sent: %s', info.messageId, info.response);

        package.set("arrivalNotified", true);
        package.save(null, qp);
      });
    }

    // Send package collection notification
    if (package.status && collectionNotified == false) {
      mailOptions.subject = `Your parcel has been picked up.`;
      mailOptions.text = utils.format('Your parcel has been collected from security desk by %s\n\nParcel details:\nParcel Number : %s\nVendor : %s\nAWB Number : %s', package.pickedBy.name, package.packageId, package.vendor.name, package.awpNo);

      transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
          return console.log(error);
        }
        console.log('Parcel picked up message %s sent: %s', info.messageId, info.response);

        package.set("collectionNotified", true);
        package.save(null, qp);
      });
    }
  })
    .catch(err => {
      console.log("CloudCode::Package::afterSave::Error -->", err)
    });
});

Parse.Cloud.beforeSave("CardSwipeLog", function (request, response) {
  const CardSwipeLog = Parse.Object.extend('CardSwipeLog');
  let query = new Parse.Query(CardSwipeLog);
  query.find({
    success: function (result) {
      Parse.Object.destroyAll(result).then(
        function (success) {
          response.success();
        }, function (error) {
          response.error("internal server error");
        });;
    }
  });
});


text:
package edu.cmu.ece.privacylens.context;

import javax.annotation.Nonnull;

import org.opensaml.messaging.context.BaseContext;

import com.google.common.base.MoreObjects;

import edu.cmu.ece.privacylens.Reminder;
import net.shibboleth.utilities.java.support.annotation.constraint.Live;

/**
 * Context representing the state of a reminder flow.
 * Why not use ReminderInterval
 *
 * Holds Reminder info.
 */
public class ReminderContext extends BaseContext {

    /** Current reminder object */
    @Nonnull
    private final Reminder currentReminder;

    /** Target reminder object */
    @Nonnull
    private final Reminder targetReminder;

    /** Constructor. */
    public ReminderContext() {
        currentReminder = new Reminder();
        targetReminder = new Reminder();
    }

    /**
     * Get the current reminder
     *
     * @return the reminder
     */
    @Nonnull
    @Live
    public Reminder getCurrentReminder() {
        return currentReminder;
    }

    /**
     * Get the target reminder
     *
     * @return the reminder
     */
    @Nonnull
    @Live
    public Reminder getTargetReminder() {
        return targetReminder;
    }

    /** {@inheritDoc} */
    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .add("currentReminder", currentReminder)
                .add("targetReminder", targetReminder)
                .toString();
    }

}


text:
OH_MY_ZSH="${HOME}/.oh-my-zsh"
ZSH_CUSTOM="${OH_MY_ZSH}/custom"

function update
{
    if [[ -z "$1" ]]; then
        return
    fi
    if [[ -f /usr/bin/git ]]; then
        echo "Updating repository in $1"
        pushd $1
        git pull origin master --quiet
        git submodule update --recursive --quiet
        popd
    fi
}

if [[ -f /usr/bin/apt-get ]]; then
    OS="deb"
elif [[ -f /usr/bin/yum || -f /usr/bin/dnf ]]; then
    OS="rpm"
elif [[ -f /sbin/apk ]]; then
    OS="apk"
else
    echo "Error determining package manager"
    OS="UNKNOWN"
fi

if [[ $OSTYPE == "linux-gnu"* ]]; then
    OS_SPECIFIC_SUBDIR="linux"
elif [[ $OSTYPE == "darwin"* ]]; then
    OS_SPECIFIC_SUBDIR="macos"
else
    echo "Unable to determine operating system (checked either for linux or mac)"
    OS_SPECIFIC_SUBDIR=""
fi

if [[ $OSTYPE == "darwin"* ]]; then
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
fi

# Installs the git files by rsynching them... call this after updating your repo
# copy git
rsync -azP git/.gitconfig $HOME/
rsync -azP git/.gitignore $HOME/

# copy .gdbinit
rsync -azP gdb/.gdbinit $HOME/

mkdir -p $HOME/bin
rsync -azP bin/ $HOME/bin/

# copy tmux
rsync -azP tmux/$OS_SPECIFIC_SUBDIR/.tmux.conf $HOME/

if [[ $OSTYPE == "darwin"* ]]; then
    brew install vim
    brew link vim
fi

if [[ $OSTYPE == "linux-gnu"* ]]; then
    echo "Install pyenv manually"
elif [[ $OSTYPE == "darwin"* ]]; then
    brew install pyenv
    CONFIGURE_OPTS=--enabled-shared pyenv install 3.9.1
    pyenv global 3.9.1
else
    echo "Dunno OS"
fi

# copy vim
rsync -azP vim/.vimrc $HOME/
# Start VIM plugin install
vim +PluginInstall +qall

# copy fish
if [ ! -d "$HOME/.config/fish" ]
then
    mkdir -p "$HOME/.config/fish"
fi

# Install virtualfish
PIP2=$(which pip2)
PIP3=$(which pip3)

if [ -z ${PIP2+x} ]; then pip2 install --upgrade virtualfish thefuck; fi
if [ -z ${PIP3+x} ]; then pip3 install --upgrade virtualfish thefuck; fi

echo "If using FISH, see http://virtualfish.readthedocs.io/en/latest/install.html#customizing-your-fish-prompt to customize your FISH prompt for virtualenvwrapper"

rsync -azP fish/config.fish $HOME/.config/fish/
rsync -azP fish/functions $HOME/.config/fish/
rsync -azP fish/fishd "$HOME/.config/fish/fishd.`hostname`"

# copy i3
if [[ $OSTYPE == "linux-gnu"* ]]; then
    rsync -azP i3/.i3 $HOME/
    sudo cp i3/i3lock.service /etc/systemd/system/
    sudo systemctl enable i3lock.service
fi

# copy zsh stuff
if [[ ! -d $HOME/.oh-my-zsh ]]; then
    git clone https://github.com/robbyrussell/oh-my-zsh.git $HOME/.oh-my-zsh
else
    update $HOME/.oh-my-zsh
fi
git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM}/plugins/zsh-autosuggestions
git clone https://github.com/denysdovhan/spaceship-prompt.git "${ZSH_CUSTOM}/themes/spaceship-prompt"
ln -s "${ZSH_CUSTOM}/themes/spaceship-prompt/spaceship.zsh-theme" "${OH_MY_ZSH}/themes/spaceship.zsh-theme"
mkdir -p ~/.oh-my-zsh/plugins/bazel
wget -P ~/.oh-my-zsh/plugins https://raw.githubusercontent.com/bazelbuild/bazel/master/scripts/zsh_completion/_bazel

rsync -azP zsh/$OS_SPECIFIC_SUBDIR/.zshrc $HOME/.zshrc

# copy systemd scripts
if [[ $OSTYPE == "linux-gnu"* ]]; then
    rsync -azP systemd $HOME/.config/
fi

# copy screenlayouts
if [[ $OSTYPE == "linux-gnu"* ]]; then
    rsync -azP screenlayout/.screenlayout $HOME/
fi

if [[ ! -d ~/.fzf ]]; then
    pushd $HOME
    git clone --depth 1 https://github.com/junegunn/fzf.git $HOME/.fzf
    popd
else
    update $HOME/.fzf
fi

# Run installer everytime since the zsh file is overwritten
~/.fzf/install --all

# Install git
if [[ ! -f /usr/bin/git ]]; then
    if [[ "$OS" == "deb" ]]; then sudo apt-get install -y git; fi
    if [[ "$OS" == "rpm" ]]; then sudo yum install -y git; fi
    if [[ $OSTYPE == "darwin"* ]]; then
        brew install git
    fi
fi

# Install AG
if [[ "$OS" == "deb" ]]; then sudo apt-get install -y silversearcher-ag; fi
if [[ "$OS" == "rpm" ]]; then
    sudo yum install -y pcre-devel xz-devel
    pushd /usr/local/src
    if [[ ! -d /usr/local/src/the_silver_searcher ]]; then
        sudo git clone https://github.com/ggreer/the_silver_searcher.git
    else
        update /usr/local/src/the_silver_searcher
    fi
    cd the_silver_searcher
    sudo ./build.sh
    sudo make install
    popd
fi

# Install tmux plugin manager
if [[ ! -d ~/.tmux/plugins/tpm ]]; then
    git clone https://github.com/tmux-plugins/tpm $HOME/.tmux/plugins/tpm
else
    update $HOME/.tmux/plugins/tpm
fi

if [[ $OSTYPE == "darwin"* ]]; then
    brew install alacritty
    cp -r alacritty ~/.config/
fi

# Install Pyenv
if [[ -f /usr/bin/git ]]; then
    git clone https://github.com/pyenv/pyenv.git ~/.pyenv
    cd ~/.pyenv && src/configure && make -C src

    echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.zprofile
    echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.zprofile
    echo 'eval "$(pyenv init --path)"' >> ~/.zprofile

    echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.profile
    echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.profile
    echo 'eval "$(pyenv init --path)"' >> ~/.profile

    echo 'eval "$(pyenv init -)"' >> ~/.zshrc
fi


text:
![Alt text](https://github.com/frhan/study/blob/master/images/Screen%20Shot%202019-03-10%20at%201.37.35%20AM.png)
### Getting a Database Connection
- There are two main ways to get a `Connection`:
`DriverManager` or `DataSource`.

    - `DriverManager` is the one covered on the exam. Do not use a `DriverManager` in code someone is paying you to write.

    - A `DataSource` is a factory, and it has more features than `DriverManager`

```java
import java.sql.*;
public class TestConnect {
public static void main(String[] args) throws SQLException {
    Connection conn = DriverManager.getConnection("jdbc:derby:zoo"); System.out.println(conn);
}
}

```
- a `DataSource` maintains a connection pool so that you can keep reusing the same connection rather than needing to get a new one each time.

- When `Class.forName()` is used, the error about an invalid class occurs on that line and throws a `ClassNotFoundException`:

```java
    Class.forName("not.a.driver");
```

![Alt text](https://github.com/frhan/study/blob/master/images/Screen%20Shot%202019-03-10%20at%201.41.49%20AM.png)


text:
from collections import OrderedDict
import functools
import re
from typing import (
    Dict,
    Mapping,
    Optional,
    AsyncIterable,
    Awaitable,
    AsyncIterator,
    Sequence,
    Tuple,
    Type,
    Union,
)
import pkg_resources

from google.api_core.client_options import ClientOptions
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials  # type: ignore
from google.oauth2 import service_account  # type: ignore

try:
    OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]
except AttributeError:  # pragma: NO COVER
    OptionalRetry = Union[retries.Retry, object]  # type: ignore

from google.cloud.pubsublite_v1.types import publisher
from .transports.base import PublisherServiceTransport, DEFAULT_CLIENT_INFO
from .transports.grpc_asyncio import PublisherServiceGrpcAsyncIOTransport
from .client import PublisherServiceClient

class PublisherServiceAsyncClient:
    """The service that a publisher client application uses to publish
    messages to topics. Published messages are retained by the service
    for the duration of the retention period configured for the
    respective topic, and are delivered to subscriber clients upon
    request (via the ``SubscriberService``).
    """

    _client: PublisherServiceClient

    DEFAULT_ENDPOINT = PublisherServiceClient.DEFAULT_ENDPOINT
    DEFAULT_MTLS_ENDPOINT = PublisherServiceClient.DEFAULT_MTLS_ENDPOINT

    common_billing_account_path = staticmethod(
        PublisherServiceClient.common_billing_account_path
    )
    parse_common_billing_account_path = staticmethod(
        PublisherServiceClient.parse_common_billing_account_path
    )
    common_folder_path = staticmethod(PublisherServiceClient.common_folder_path)
    parse_common_folder_path = staticmethod(
        PublisherServiceClient.parse_common_folder_path
    )
    common_organization_path = staticmethod(
        PublisherServiceClient.common_organization_path
    )
    parse_common_organization_path = staticmethod(
        PublisherServiceClient.parse_common_organization_path
    )
    common_project_path = staticmethod(PublisherServiceClient.common_project_path)
    parse_common_project_path = staticmethod(
        PublisherServiceClient.parse_common_project_path
    )
    common_location_path = staticmethod(PublisherServiceClient.common_location_path)
    parse_common_location_path = staticmethod(
        PublisherServiceClient.parse_common_location_path
    )

    @classmethod
    def from_service_account_info(cls, info: dict, *args, **kwargs):
        """Creates an instance of this client using the provided credentials
            info.

        Args:
            info (dict): The service account private key info.
            args: Additional arguments to pass to the constructor.
            kwargs: Additional arguments to pass to the constructor.

        Returns:
            PublisherServiceAsyncClient: The constructed client.
        """
        return PublisherServiceClient.from_service_account_info.__func__(PublisherServiceAsyncClient, info, *args, **kwargs)  # type: ignore

    @classmethod
    def from_service_account_file(cls, filename: str, *args, **kwargs):
        """Creates an instance of this client using the provided credentials
            file.

        Args:
            filename (str): The path to the service account private key json
                file.
            args: Additional arguments to pass to the constructor.
            kwargs: Additional arguments to pass to the constructor.

        Returns:
            PublisherServiceAsyncClient: The constructed client.
        """
        return PublisherServiceClient.from_service_account_file.__func__(PublisherServiceAsyncClient, filename, *args, **kwargs)  # type: ignore

    from_service_account_json = from_service_account_file

    @classmethod
    def get_mtls_endpoint_and_cert_source(
        cls, client_options: Optional[ClientOptions] = None
    ):
        """Return the API endpoint and client cert source for mutual TLS.

        The client cert source is determined in the following order:
        (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
        client cert source is None.
        (2) if `client_options.client_cert_source` is provided, use the provided one; if the
        default client cert source exists, use the default one; otherwise the client cert
        source is None.

        The API endpoint is determined in the following order:
        (1) if `client_options.api_endpoint` if provided, use the provided one.
        (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
        default mTLS endpoint; if the environment variabel is "never", use the default API
        endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
        use the default API endpoint.

        More details can be found at https://google.aip.dev/auth/4114.

        Args:
            client_options (google.api_core.client_options.ClientOptions): Custom options for the
                client. Only the `api_endpoint` and `client_cert_source` properties may be used
                in this method.

        Returns:
            Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
                client cert source to use.

        Raises:
            google.auth.exceptions.MutualTLSChannelError: If any errors happen.
        """
        return PublisherServiceClient.get_mtls_endpoint_and_cert_source(client_options)  # type: ignore

    @property
    def transport(self) -> PublisherServiceTransport:
        """Returns the transport used by the client instance.

        Returns:
            PublisherServiceTransport: The transport used by the client instance.
        """
        return self._client.transport

    get_transport_class = functools.partial(
        type(PublisherServiceClient).get_transport_class, type(PublisherServiceClient)
    )

    def __init__(
        self,
        *,
        credentials: ga_credentials.Credentials = None,
        transport: Union[str, PublisherServiceTransport] = "grpc_asyncio",
        client_options: ClientOptions = None,
        client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
    ) -> None:
        """Instantiates the publisher service client.

        Args:
            credentials (Optional[google.auth.credentials.Credentials]): The
                authorization credentials to attach to requests. These
                credentials identify the application to the service; if none
                are specified, the client will attempt to ascertain the
                credentials from the environment.
            transport (Union[str, ~.PublisherServiceTransport]): The
                transport to use. If set to None, a transport is chosen
                automatically.
            client_options (ClientOptions): Custom options for the client. It
                won't take effect if a ``transport`` instance is provided.
                (1) The ``api_endpoint`` property can be used to override the
                default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
                environment variable can also be used to override the endpoint:
                "always" (always use the default mTLS endpoint), "never" (always
                use the default regular endpoint) and "auto" (auto switch to the
                default mTLS endpoint if client certificate is present, this is
                the default value). However, the ``api_endpoint`` property takes
                precedence if provided.
                (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
                is "true", then the ``client_cert_source`` property can be used
                to provide client certificate for mutual TLS transport. If
                not provided, the default SSL client certificate will be used if
                present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
                set, no client certificate will be used.

        Raises:
            google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
                creation failed for any reason.
        """
        self._client = PublisherServiceClient(
            credentials=credentials,
            transport=transport,
            client_options=client_options,
            client_info=client_info,
        )

    def publish(
        self,
        requests: AsyncIterator[publisher.PublishRequest] = None,
        *,
        retry: OptionalRetry = gapic_v1.method.DEFAULT,
        timeout: float = None,
        metadata: Sequence[Tuple[str, str]] = (),
    ) -> Awaitable[AsyncIterable[publisher.PublishResponse]]:
        r"""Establishes a stream with the server for publishing
        messages. Once the stream is initialized, the client
        publishes messages by sending publish requests on the
        stream. The server responds with a PublishResponse for
        each PublishRequest sent by the client, in the same
        order that the requests were sent. Note that multiple
        PublishRequests can be in flight simultaneously, but
        they will be processed by the server in the order that
        they are sent by the client on a given stream.

        .. code-block:: python

            # This snippet has been automatically generated and should be regarded as a
            # code template only.
            # It will require modifications to work:
            # - It may require correct/in-range values for request initialization.
            # - It may require specifying regional endpoints when creating the service
            #   client as shown in:
            #   https://googleapis.dev/python/google-api-core/latest/client_options.html
            from google.cloud import pubsublite_v1

            async def sample_publish():
                # Create a client
                client = pubsublite_v1.PublisherServiceAsyncClient()

                # Initialize request argument(s)
                request = pubsublite_v1.PublishRequest(
                )

                # This method expects an iterator which contains
                # 'pubsublite_v1.PublishRequest' objects
                # Here we create a generator that yields a single `request` for
                # demonstrative purposes.
                requests = [request]

                def request_generator():
                    for request in requests:
                        yield request

                # Make the request
                stream = await client.publish(requests=request_generator())

                # Handle the response
                async for response in stream:
                    print(response)

        Args:
            requests (AsyncIterator[`google.cloud.pubsublite_v1.types.PublishRequest`]):
                The request object AsyncIterator. Request sent from the client to the
                server on a stream.
            retry (google.api_core.retry.Retry): Designation of what errors, if any,
                should be retried.
            timeout (float): The timeout for this request.
            metadata (Sequence[Tuple[str, str]]): Strings which should be
                sent along with the request as metadata.

        Returns:
            AsyncIterable[google.cloud.pubsublite_v1.types.PublishResponse]:
                Response to a PublishRequest.
        """

        # Wrap the RPC method; this adds retry and timeout information,
        # and friendly error handling.
        rpc = gapic_v1.method_async.wrap_method(
            self._client._transport.publish,
            default_timeout=None,
            client_info=DEFAULT_CLIENT_INFO,
        )

        # Send the request.
        response = rpc(
            requests,
            retry=retry,
            timeout=timeout,
            metadata=metadata,
        )

        # Done; return the response.
        return response

    async def __aenter__(self):
        return self

    async def __aexit__(self, exc_type, exc, tb):
        await self.transport.close()

try:
    DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
        gapic_version=pkg_resources.get_distribution(
            "google-cloud-pubsublite",
        ).version,
    )
except pkg_resources.DistributionNotFound:
    DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()

__all__ = ("PublisherServiceAsyncClient",)


text:
'''
Created on Nov 9, 2015

@author: nlp
'''

# 计算P(w|c)
def calc_w_c(one_word, class_lable, positive_list, negative_list, vocabulary_size, positive_size, negative_size):
    if class_lable > 0:
        count = 0
        for words in positive_list:
            for w in words:
                if w == one_word:
                    count += 1
        if count == 0:
            count = 1
        return float(count) / float(positive_size + vocabulary_size)
    else:
        count = 0
        for words in negative_list:
            for w in words:
                if w == one_word:
                    count += 1
        if count == 0:
            count = 1
        return float(count) / float(negative_size + vocabulary_size)

# 计算P(c)
def calc_p_c(positive_list, negative_list, class_lable):
    p = len(positive_list)
    n = len(negative_list)
    return float(p) / float(p + n) if class_lable > 0 else float(n) / float(p + n)

# 计算当前句子属于所说类的概率
def cal_sentence_pro(words_list, class_lable, positive_list, negative_list, vocabulary_size, positive_size, negative_size):
    pro = calc_p_c(positive_list, negative_list, class_lable)
    for one_word in words_list:
        pro *= calc_w_c(one_word, class_lable, positive_list, negative_list, vocabulary_size, positive_size, negative_size)
    return pro

# 1,binaized
if __name__ == '__main__':
    file_lable = open('train2.rlabelclass')
    file_tran = open('merged_train2.txt')

    lable_dict = {}

    for lable_line in file_lable.readlines():
        name_lable = lable_line[:-1].split(' ')
        lable_dict[name_lable[0]] = name_lable[1]

    # # 对 train 文件的处理
    positive_list = []
    negative_list = []
    vocabulary_size = 0
    positive_size = 0
    negative_size = 0
    for tran_line in file_tran.readlines():
        file_name = tran_line[1:tran_line.find(']')]
        file_words = tran_line[tran_line.rfind('['):-1].split(' ')
        vocabulary_size += len(file_words)
        if lable_dict[file_name] == u'+1':
            positive_size += len(file_words)
            positive_list.append(list(file_words))
        else:
            negative_size += len(file_words)
            negative_list.append(list(file_words))

    # # 对 test 文件进行预测
    test_file_lable = open('test2.rlabelclass')
    test_file = open('merged_test2.txt')

    test_lable_dict = {}
    for lable_line in test_file_lable.readlines():
        name_lable = lable_line[:-1].split(' ')
        test_lable_dict[name_lable[0]] = int(name_lable[1])

    predicted_lable_dict = {}
    for test_line in test_file.readlines():
        file_name = test_line[1:test_line.find(']')]
        file_words = set(test_line[test_line.rfind('['):-1].split(' '))
        positive = cal_sentence_pro(file_words, 1, positive_list, negative_list, vocabulary_size, positive_size, negative_size)
        negtive = cal_sentence_pro(file_words, -1, positive_list, negative_list, vocabulary_size, positive_size, negative_size)
        predicted_lable_dict[file_name] = 1 if positive - negtive > 0.00000001 else -1

    # # 对分类结果进行评价
    TP = 0
    TN = 0
    FP = 0
    FN = 0
    for file_name in test_lable_dict.keys():
        if test_lable_dict[file_name] > 0 and test_lable_dict[file_name] == predicted_lable_dict[file_name]:
            TP += 1
        if test_lable_dict[file_name] < 0 and test_lable_dict[file_name] == predicted_lable_dict[file_name]:
            TN += 1
        if test_lable_dict[file_name] > 0 and test_lable_dict[file_name] != predicted_lable_dict[file_name]:
            FN += 1
        if test_lable_dict[file_name] < 0 and test_lable_dict[file_name] != predicted_lable_dict[file_name]:
            FP += 1

    print TP, FN, FP, TN
    print '精确率:', float(TP) / float(TP + FP)
    print '召回率:', float(TP) / float(TP + FN)
    print 'F1值:', float(2 * TP) / float(2 * TP + FP + FN)
    pass


text:
var Modbus = require("./Modbus");
var Buff    = require("./Buffer");

exports.IllegalFunction                    = 0x01;
exports.IllegalDataAddress                 = 0x02;
exports.IllegalDataValue                   = 0x03;
exports.ServerDeviceFailure                = 0x04;
exports.Aknowledge                         = 0x05;
exports.ServerDeviceBusy                   = 0x06;
exports.MemoryParityError                  = 0x08;
exports.GatewayPathUnavailable             = 0x0A;
exports.GatewayTargetDeviceFailedToRespond = 0x0B;

exports.load = function (functs) {
	for (var f in functs) {
		if (typeof functs[f] != "object" || !functs[f].hasOwnProperty("Code")) continue;

		functs[f].Exception = prepareException(f, functs[f]);
	}
};

exports.error = function (reason) {
	if (typeof reason == "string") {
		var err = new Error(reason);
		err.code = exports[reason];

		return err;
	}

	for (var k in exports) {
		if (typeof exports[k] != "number") continue;
		if (exports[k] != reason) continue

		var err = new Error(k);
		err.code = exports[k];

		return err;
	}

	return new Error("" + reason);
};

exports.build = function (fcode, code) {
	return Buff.from([ fcode | 0x80, (typeof code == "string" ? exports[code] : code) ]);
};

exports.parse = function (buffer) {
	var data = {
		code      : buffer[0] & 0x7F,
		exception : buffer[1]
	};

	for (var k in Modbus) {
		if (typeof Modbus[k] == "object" && Modbus[k].Code == data.code) {
			data.code = k;
			break;
		}
	}

	for (var k in exports) {
		if (exports[k] == data.exception) {
			data.exception = k;
			break;
		}
	}

	return data;
};

function prepareException(name, funct) {
	return {
		build: function (code) {
			return Buff.from([ funct.Code | 0x80, code ]);
		},
		parse: function (buffer) {
			var exception = buffer[buffer.length - 1];

			for (var k in exports) {
				if (exports[k] == exception) {
					exception = k;
					break;
				}
			}

			return exception;
		}
	};
}


text:
//===- TypedEvaluator.cpp --------------------------------------*- C++ --*-===//
// Copyright 2014  Google
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//===----------------------------------------------------------------------===//

#include "Evaluator.h"
#include "SSAPass.h"
#include "TypedEvaluator.h"

namespace ohmu {
namespace til  {

void TypedEvaluator::enterCFG(SCFG *Cfg) {
  Super::enterCFG(Cfg);
  scope()->setCurrentContinuation(Builder.currentCFG()->exit());
  Builder.beginBlock(Builder.currentCFG()->entry());
}

void TypedEvaluator::exitCFG(SCFG *Cfg) {
  auto* ncfg = Builder.currentCFG();
  processPendingBlocks();
  Super::exitCFG(Cfg);

  ncfg->computeNormalForm();

  /*
  std::cout << "Lowered CFG: \n";
  TILDebugPrinter::print(ncfg, std::cout);

  std::cout << "Convert to SSA: \n";
  */
  SSAPass ssaPass(Builder.arena());
  // indices start at 1, so we push debruin-1 onto the stack.
  ssaPass.scope()->enterNullScope(Builder.deBruinIndex()-1);
  // TODO: also enter builder scope
  ssaPass.traverseAll(ncfg);

  /*
  TILDebugPrinter::print(ncfg, std::cout);
  */
}

static TypedCopyAttr::Relation
getRelationFromVarDecl(VarDecl::VariableKind K) {
  switch (K) {
    case VarDecl::VK_Fun:  return TypedCopyAttr::BT_Type;
    case VarDecl::VK_SFun: return TypedCopyAttr::BT_ExactType;
    case VarDecl::VK_Let:  return TypedCopyAttr::BT_Equivalent;
  }
  return TypedCopyAttr::BT_Type;
}

/// Set the BaseType of i, based on the type expression e.
static void setBaseTypeFromExpr(Instruction* I, SExpr* Typ) {
  if (!Typ)
    return;

  if (auto *F = dyn_cast<Future>(Typ))
    Typ = F->force();

  switch (Typ->opcode()) {
    case COP_Function:
    case COP_Code:
    case COP_Field:
    case COP_Record:
      I->setBaseType(BaseType::getBaseType<void*>());
      break;
    case COP_ScalarType:
      I->setBaseType(cast<ScalarType>(Typ)->baseType());
      break;
    case COP_Literal:
      I->setBaseType(cast<Literal>(Typ)->baseType());
      break;
    default:
      assert(false && "Type expression must be a value.");
      break;
  }
}

void TypedEvaluator::reduceScalarType(ScalarType *Orig) {
  auto& Res = resultAttr();
  // Scalar types are globally defined; we share pointers.
  Res.Exp      = Orig;
  Res.Rel      = TypedCopyAttr::BT_Equivalent;
  Res.TypeExpr = Orig;
}

void TypedEvaluator::reduceFunction(Function *Orig) {
  Super::reduceFunction(Orig);

  auto& Res    = resultAttr();
  Res.Rel      = TypedCopyAttr::BT_Equivalent;
  Res.TypeExpr = Res.Exp;
  Res.Subst.init( Builder.deBruinIndex() );
}

void TypedEvaluator::reduceRecord(Record *Orig) {
  Super::reduceRecord(Orig);

  auto& Res    = resultAttr();
  Res.Rel      = TypedCopyAttr::BT_Equivalent;
  Res.TypeExpr = Res.Exp;
  Res.Subst.init( Builder.deBruinIndex() );
}

void TypedEvaluator::reduceCode(Code *Orig) {
  Super::reduceCode(Orig);

  auto& Res    = resultAttr();
  Res.Rel      = TypedCopyAttr::BT_Equivalent;
  Res.TypeExpr = Res.Exp;
  Res.Subst.init( Builder.deBruinIndex() );
}

void TypedEvaluator::reduceField(Field *Orig) {
  Super::reduceField(Orig);

  auto& Res    = resultAttr();
  Res.Rel      = TypedCopyAttr::BT_Equivalent;
  Res.TypeExpr = Res.Exp;
  Res.Subst.init( Builder.deBruinIndex() );
}

// If At.TypeExpr is an expression, then evaluate it.
void TypedEvaluator::evaluateTypeExpr(TypedCopyAttr &At) {
  if (At.TypeExpr->isValue())
    return;

  // Create a new scope from the substitution.
  ScopeCPS Ns( std::move(At.Subst) );

  auto* S = switchScope(&Ns);
  computeAttrType(At, At.TypeExpr);
  restoreScope(S);
}

// Set the TypeExpr for At by evaluating E
void TypedEvaluator::computeAttrType(TypedCopyAttr &At, SExpr *E) {
  auto M = switchEvalMode(TEval_WeakHead);
  auto B = Builder.disableEmit();

  traverse(E, TRV_Decl);     // Type of E is stored in lastAttr()
  At.moveType(lastAttr());   // Copy type to original attribute
  popAttr();

  Builder.restoreEmit(B);
  restoreEvalMode(M);

  if (Instruction* I = dyn_cast_or_null<Instruction>(At.Exp))
    setBaseTypeFromExpr(I, At.TypeExpr);
}

// Promote the variable V, and store the result in resultAttr().
// Used by reduceVariable(), and reduceIdentifier().
void TypedEvaluator::promoteVariable(Variable *V) {
  auto& Res = resultAttr();

  Res.Exp = V;
  Res.Rel = getRelationFromVarDecl(V->variableDecl()->kind());

  // V is a variable in the output scope.
  // Thus, we need to create a new scope to evaluate the variable type,
  // with null substitutions for anything that V depends on.

  unsigned Vidx = V->variableDecl()->varIndex();
  ScopeCPS Ns(Vidx);
  auto* S = switchScope(&Ns);
  computeAttrType(Res, V->variableDecl()->definition());
  restoreScope(S);
}

/// Shared code between reduceVariable and reduceIdentifier
void TypedEvaluator::reduceVarSubstitution(unsigned Vidx) {
  // We substitute for variables, so look up the substitution.
  auto& At = scope()->var( Vidx );
  if (At.TypeExpr) {
    // If we have a typed substitution, then return it.
    resultAttr() = At;
    return;
  }
  if (Variable* V = dyn_cast_or_null<Variable>(At.Exp)) {
    // If the substitution maps to another variable, then promote that one.
    promoteVariable(V);
    return;
  }
  if (Instruction* I = dyn_cast<Instruction>(At.Exp)) {
    // If the substitution is a simply-typed expression or phi node,
    // then return it.
    if (I->baseType().isSimple() || I->opcode() == COP_Phi) {
      resultAttr() = At;
      return;
    }
  }
  assert(false && "Invalid substitution.");
}

void TypedEvaluator::reduceVariable(Variable *Orig) {
  unsigned Idx = Orig->variableDecl()->varIndex();

  if (scope()->isNull(Idx)) {
    // No substitution, so just promote the variable.
    promoteVariable(Orig);
    return;
  }

  reduceVarSubstitution(Orig->variableDecl()->varIndex());
}

void TypedEvaluator::reduceApply(Apply *Orig) {
  auto& Res = resultAttr();
  auto& Fa  = attr(0);
  auto& Aa  = attr(1);

  auto* Fe  = Fa.Exp;
  auto* Ft  = Fa.TypeExpr;
  auto* F   = dyn_cast_or_null<Function>(Ft);

  if (!F) {
    // Undefined marks a previous error, so omit the warning.
    if (!isa<Undefined>(Fe))
      diag().error("Expression is not a function: ") << Fe;
    Res.Exp = Builder.newUndefined();
    return;
  }

  // Set the result type, substituting arguments for variables.
  Res.TypeExpr = F->body();     // TODO -- evaluate body
  Res.Rel = Fa.Rel;

  // Do lazy substitution
  if (!Aa.Exp && Orig->applyKind() == Apply::FAK_SApply) {
    // Handle implicit self-parameters
    TypedCopyAttr Facpy = Fa;            // copy Fa
    Res.stealSubstitution(Fa);           // move from Fa
    Res.pushSubst( std::move(Facpy) );
  }
  else {
    Res.stealSubstitution(Fa);
    Res.pushSubst( std::move(Aa) );
  }

  evaluateTypeExpr(Res);

  // Set the result residual.
  // TODO: we may not have a residual for Aa.Exp
  if (Fe) {
    auto* E = Builder.newApply(Fe, Aa.Exp, Orig->applyKind());
    setBaseTypeFromExpr(E, Res.TypeExpr);
    Res.Exp = E;
  }
}

void TypedEvaluator::reduceProject(Project *Orig) {
  auto& Res = resultAttr();
  auto& Ra  = attr(0);
  auto* Re  = Ra.Exp;
  auto* Rt  = Ra.TypeExpr;
  auto* R   = dyn_cast_or_null<Record>(Rt);

  /*
  if (!R) {
    // syntactic sugar: automatically insert self-applications if necessary.
    auto* Sf = dyn_cast_or_null<Function>(Rt);
    if (Sf && Sf->isSelfApplicable()) {
      resultArgs_.push_back(e);                   // push self-argument.
      r = dyn_cast<Record>(sfuntyp->body());
      e = newApply(e, nullptr, Apply::FAK_SApply);
    }
  }
  */

  if (!R) {
    // Undefined marks a previous error, so omit the warning.
    if (!isa<Undefined>(Re))
      diag().error("Expression is not a record: ") << Re;
    Res.Exp = Builder.newUndefined();
    return;
  }

  Slot* S = R->findSlot(Orig->slotName());
  if (!S) {
    diag().error("Slot not found: ") << Orig->slotName();
    Res.Exp = Builder.newUndefined();
    return;
  }

  // Set the result type.
  Res.TypeExpr = S->definition();
  Res.Rel      = Ra.Rel;
  Res.stealSubstitution(Ra);
  evaluateTypeExpr(Res);

  // Set the result residual.
  if (Re) {
    auto* E = Builder.newProject(Re, Orig->slotName());
    setBaseTypeFromExpr(E, Res.TypeExpr);
    Res.Exp = E;
  }
}

void TypedEvaluator::reduceCall(Call *Orig) {
  auto& Res = resultAttr();
  auto& Ca  = attr(0);
  auto* Ce  = Ca.Exp;
  auto* Ct  = Ca.TypeExpr;
  auto* C   = dyn_cast_or_null<Code>(Ct);

  if (!C) {
    if (!isa<Undefined>(Ce))
      diag().error("Expression is not a code block: ") << Ce;
    Res.Exp = Builder.newUndefined();
    return;
  }

  if (reduceNestedCall(Orig, C))
    return;

  // Set the result type.
  Res.TypeExpr = C->returnType();
  Res.Rel      = TypedCopyAttr::BT_Type;
  Res.stealSubstitution(Ca);

  // TODO: FIXME!!  Res is not a stable reference; it may be invalidated.
  evaluateTypeExpr(Res);

  // Set the result residual.
  if (Ce) {
    auto* E = Builder.newCall(Ce);
    setBaseTypeFromExpr(E, Res.TypeExpr);
    Res.Exp = E;
  }
}

void TypedEvaluator::reduceAlloc(Alloc *Orig) {
  auto& Res = resultAttr();
  auto* Ve = attr(0).Exp;

  if (!Ve->isValue()) {
    diag().error("Argument to alloc is not a value: ") << Ve;
    Ve = Builder.newUndefined();
  }

  Res.Exp = Builder.newAlloc(Ve, Orig->allocKind());
  Res.TypeExpr = Ve;
  Res.Rel = TypedCopyAttr::BT_Type;
  Res.Subst.init( Builder.deBruinIndex() );
}

void TypedEvaluator::reduceLoad(Load *Orig) {
  auto& Res = resultAttr();
  auto& Fa  = attr(0);
  auto* Fe  = Fa.Exp;
  auto* Ft  = Fa.TypeExpr;
  auto* F   = dyn_cast_or_null<Field>(Ft);

  if (!F) {
    if (!isa<Undefined>(Fe))
      diag().error("Expression is not a field: ") << Fe;
    Res.Exp = Builder.newUndefined();
    return;
  }

  if (Future *Fut = dyn_cast<Future>(F->range()))
    Fut->force();

  Res.TypeExpr = F->range();
  Res.Rel      = TypedCopyAttr::BT_Type;
  Res.stealSubstitution(Fa);
  evaluateTypeExpr(Res);

  if (Fe) {
    auto* E = Builder.newLoad(Fe);
    setBaseTypeFromExpr(E, Res.TypeExpr);
    Res.Exp = E;
  }
}

void TypedEvaluator::reduceUnaryOp(UnaryOp *Orig) {
  auto& Res = resultAttr();
  Instruction* I0 = dyn_cast<Instruction>(attr(0).Exp);

  if (!I0) {
    diag().error("Invalid use of arithmetic operator: ") << Orig;
    Res.Exp = Builder.newUndefined();
    return;
  }

  switch (Orig->unaryOpcode()) {
    case UOP_Negative: {
      if (!I0->baseType().isNumeric())
        diag().error("Operator requires a numeric type: ") << Orig;
      break;
    }
    case UOP_BitNot: {
      if (I0->baseType().Base != BaseType::BT_Int)
        diag().error("Bitwise operations require integer type.") << Orig;
      break;
    }
    case UOP_LogicNot: {
      if (I0->baseType().Base != BaseType::BT_Bool)
        diag().error("Logical operations require boolean type.") << Orig;
      break;
    }
  }

  auto *Re = Builder.newUnaryOp(Orig->unaryOpcode(), I0);
  Re->setBaseType(I0->baseType());

  Res.Exp = Re;
  Res.Rel = TypedCopyAttr::BT_Type;
  Res.TypeExpr = nullptr;
}

bool TypedEvaluator::checkAndExtendTypes(Instruction*& I0, Instruction*& I1) {
  BaseType Bt0 = I0->baseType();
  BaseType Bt1 = I1->baseType();

  bool NeedsPromotion = Bt0.promoteInteger() || Bt1.promoteInteger();

  if (I0->baseType() == I1->baseType() && !NeedsPromotion)
    return true;

  TIL_CastOpcode Op = typeConvertable(I0->baseType(), I1->baseType());
  if (Op != CAST_none) {
    I0 = Builder.newCast(Op, I0);
    I0->setBaseType(I1->baseType());
    return true;
  }
  Op = typeConvertable(I1->baseType(), I0->baseType());
  if (Op != CAST_none) {
    I1 = Builder.newCast(Op, I1);
    I1->setBaseType(I0->baseType());
    return true;
  }

  return false;
}

void TypedEvaluator::reduceBinaryOp(BinaryOp *Orig) {
  auto& Res = resultAttr();
  Instruction* I0 = dyn_cast<Instruction>(attr(0).Exp);
  Instruction* I1 = dyn_cast<Instruction>(attr(1).Exp);

  if (!I0 || !I1) {
    diag().error("Invalid use of arithmetic operator: ") << Orig;
    Res.Exp = Builder.newUndefined();
    return;
  }

  if (!checkAndExtendTypes(I0, I1)) {
    diag().error("Arithmetic operation on incompatible types: ")
        << Orig << " [" << I0 << ", " << I1 << "]";
  }

  if (Literal* L0 = dyn_cast<Literal>(I0)) {
    if (Literal* L1 = dyn_cast<Literal>(I1)) {
      Res.Exp = evaluateBinaryOp(Orig->binaryOpcode(), L0->baseType(), arena(),
                                 L0, L1);
      Res.Rel = TypedCopyAttr::BT_Type;
      Res.TypeExpr = nullptr;
      return;
    }
  }

  Instruction* Re = nullptr;
  BaseType Vt = BaseType::getBaseType<void>();
  switch (Orig->binaryOpcode()) {
    case BOP_Add:
    case BOP_Sub:
    case BOP_Mul:
    case BOP_Div:
    case BOP_Rem: {
      if (!I0->baseType().isNumeric())
        diag().error("Operator requires a numeric type: ") << Orig;
      Vt = I0->baseType();
      break;
    }
    case BOP_Shl:
    case BOP_Shr:
    case BOP_BitAnd:
    case BOP_BitXor:
    case BOP_BitOr: {
      if (I0->baseType().Base != BaseType::BT_Int)
        diag().error("Bitwise operations require integer type.") << Orig;
      Vt = I0->baseType();
      break;
    }
    case BOP_Eq:
    case BOP_Neq:
    case BOP_Lt:
    case BOP_Leq: {
      Vt = BaseType::getBaseType<bool>();
      break;
    }
    case BOP_Gt: {
      // rewrite > to <
      Re = Builder.newBinaryOp(BOP_Lt, I1, I0);
      Vt = BaseType::getBaseType<bool>();
      break;
    }
    case BOP_Geq: {
      // rewrite >= to <=
      Re = Builder.newBinaryOp(BOP_Leq, I1, I0);
      Vt = BaseType::getBaseType<bool>();
      break;
    }
    case BOP_LogicAnd:
    case BOP_LogicOr: {
      if (I0->baseType().Base != BaseType::BT_Bool)
        diag().error("Logical operations require boolean type.") << Orig;
      Vt = BaseType::getBaseType<bool>();
      break;
    }
  }
  if (!Re)
    Re = Builder.newBinaryOp(Orig->binaryOpcode(), I0, I1);
  Re->setBaseType(Vt);

  Res.Exp = Re;
  Res.Rel = TypedCopyAttr::BT_Type;
  Res.TypeExpr = nullptr;
}

void TypedEvaluator::reduceIdentifier(Identifier *Orig) {
  auto& Res = resultAttr();

  StringRef Idstr = Orig->idString();

  for (unsigned i = scope()->size() - 1; i > 0; --i) {
    VarDecl *Vd = scope()->varDecl(i);
    if (!Vd)
      continue;

    // First check to see if the identifier refers to a named variable.
    if (Vd->varName() == Idstr) {
      reduceVarSubstitution(i);
      return;
    }
    // Otherwise look up slot names in enclosing records.
    else if (Vd->kind() == VarDecl::VK_SFun) {
      auto &At = scope()->var(i);

      auto* Sv = dyn_cast_or_null<Variable>(At.Exp);
      if (!Sv)
        continue;
      auto* Svd = Sv->variableDecl();

      if (!Svd->definition())
        continue;

      auto* Sfun = cast<Function>(Svd->definition());
      auto* Rec  = dyn_cast<Record>(Sfun->body());
      if (!Rec)
        continue;
      auto* Slt = Rec->findSlot(Idstr);
      if (!Slt)
        continue;

      auto* Sdef = Slt->definition();
      if (Slt->hasModifier(Slot::SLT_Final) && Sdef->isTrivial()) {
        // Simply return the trivial value (i.e. call reduceTrivial())
        // TODO: this is a hack.
        Res.Exp      = Sdef;
        Res.Rel      = TypedCopyAttr::BT_Equivalent;
        Res.TypeExpr = Sdef;
        return;
      }

      auto* Eapp  = Builder.newApply(Sv, nullptr, Apply::FAK_SApply);
      Eapp->setBaseType(BaseType::getBaseType<void*>());

      auto* Eproj = Builder.newProject(Eapp, Idstr);
      setBaseTypeFromExpr(cast<Instruction>(Eproj), Sdef);

      // TODO -- evaluate definition
      Res.Exp      = Eproj;
      Res.Rel      = TypedCopyAttr::BT_Type;
      Res.TypeExpr = Sdef;

      unsigned Vidx =  Sv->variableDecl()->varIndex();
      assert(Vidx > 0 && "Variable index is not set.");

      Res.Subst.init(Vidx);
      Res.pushSubst( TypedCopyAttr(Sv) );
      return;
    }
  }

  diag().error("Identifier not found: ") << Idstr;
  Super::reduceIdentifier(Orig);
}

void TypedEvaluator::traverseFunction(Function *Orig) {
  if (EvalMode == TEval_WeakHead) {
    auto& Res    = resultAttr();
    // We do not copy values, but instead construct a delayed substitution.
    // There is no valid residual, because the substitution hasn't been done.
    Res.Exp      = nullptr;
    Res.Rel      = TypedCopyAttr::BT_Equivalent;
    Res.TypeExpr = Orig;
    Res.Subst    = scope()->substitution();
    return;
  }
  SuperTv::traverseFunction(Orig);
}

void TypedEvaluator::traverseRecord(Record *Orig) {
  if (EvalMode == TEval_WeakHead) {
    // We do not copy values, but instead construct a delayed substitution.
    // There is no valid residual, because the substitution hasn't been done.
    auto& Res    = resultAttr();
    Res.Exp      = nullptr;
    Res.Rel      = TypedCopyAttr::BT_Equivalent;
    Res.TypeExpr = Orig;
    Res.Subst    = scope()->substitution();
    return;
  }
  SuperTv::traverseRecord(Orig);
}

void TypedEvaluator::traverseCode(Code *Orig) {
  if (EvalMode == TEval_WeakHead) {
    // We do not copy values, but instead construct a delayed substitution.
    // There is no valid residual, because the substitution hasn't been done.
    auto& Res    = resultAttr();
    Res.Exp      = nullptr;
    Res.Rel      = TypedCopyAttr::BT_Equivalent;
    Res.TypeExpr = Orig;
    Res.Subst    = scope()->substitution();
    return;
  }

  if (Builder.currentBB()) {
    traverseNestedCode(Orig);
    return;
  }

  // Push the return type onto the stack.
  traverse(Orig->returnType(), TRV_Type);
  if (!Orig->body()) {
    traverseNull();
  }
  else {
    // We don't forward to Super here, because we have to use CFGFuture.
    // Make a new CFGFuture for the code body, and push it on the stack.
    auto *F = new (arena()) TypedEvalFuture(this, Orig->body(),
                                            scope()->clone(),
                                            Builder.currentState(), true);
    FutureQueue.push(F);
    auto *A = pushAttr();
    A->Exp = F;
  }
  reduceCode(Orig);
}

void TypedEvaluator::traverseField(Field *Orig) {
  if (EvalMode == TEval_WeakHead) {
    // We do not copy values, but instead construct a delayed substitution.
    // There is no valid residual, because the substitution hasn't been done.
    auto& Res    = resultAttr();
    Res.Exp      = nullptr;
    Res.Rel      = TypedCopyAttr::BT_Equivalent;
    Res.TypeExpr = Orig;
    Res.Subst    = scope()->substitution();
    return;
  }
  SuperTv::traverseField(Orig);
}

void TypedEvaluator::traverseLet(Let *Orig) {
  if (!Builder.emitInstrs()) {
    SuperTv::traverseLet(Orig);
    return;
  }

  // Eliminate the let by substituting for the let-variable.
  traverse(Orig->variableDecl()->definition(), TRV_Decl);
  auto* E = lastAttr().Exp;
  if (auto* I = dyn_cast_or_null<Instruction>(E)) {
    I->setInstrName(Builder, Orig->variableDecl()->varName());
  }

  scope()->enterScope(Orig->variableDecl(), std::move(lastAttr()));

  traverse(Orig->body(), TRV_Tail);
  scope()->exitScope();

  // Return the result of traversing the body.
  resultAttr() = std::move( lastAttr() );
}

void TypedEvaluator::traverseIfThenElse(IfThenElse *Orig) {
  traverseArg(Orig->condition());

  // Type-check the conditional...
  Instruction* Nc = dyn_cast<Instruction>(lastAttr().Exp);
  if (!Nc || Nc->baseType().Base != BaseType::BT_Bool)
    diag().error("Branch condition is not a boolean: ") << Nc;

  // Eliminate static conditionals
  Literal* Lc = dyn_cast<Literal>(lastAttr().Exp);
  if (Lc && Lc->baseType().Base == BaseType::BT_Bool) {
    bool Cb = Lc->as<bool>()->value();
    if (Cb)
      traverse(Orig->thenExpr(), TRV_Tail);
    else
      traverse(Orig->elseExpr(), TRV_Tail);
    resultAttr() = lastAttr();
    return;
  }

  // Just do a normal traversal if we're not currently rewriting in a CFG.
  if (!Builder.emitInstrs()) {
    self()->traverse(Orig->thenExpr(), TRV_Arg);
    self()->traverse(Orig->elseExpr(), TRV_Arg);
    self()->reduceIfThenElse(Orig);
    return;
  }

  // Otherwise convert conditionals to CFG branches
  BasicBlock* Tb = Builder.newBlock();
  BasicBlock* Eb = Builder.newBlock();
  Branch* Br = Builder.newBranch(Nc, Tb, Eb);

  // If the current continuation is null, then make a new one.
  BasicBlock* CurrCont = scope()->currentContinuation();
  BasicBlock* Cont     = CurrCont;
  if (!Cont)
    Cont = Builder.newBlock(1);

  // Process the then and else blocks
  Builder.beginBlock(Br->thenBlock());
  scope()->setCurrentContinuation(Cont);
  traverse(Orig->thenExpr(), TRV_Tail);

  Builder.beginBlock(Br->elseBlock());
  scope()->setCurrentContinuation(Cont);
  traverse(Orig->elseExpr(), TRV_Tail);

  scope()->setCurrentContinuation(CurrCont);   // restore old continuation

  // If we had an existing continuation, then we're done.
  // The then/else blocks will call the continuation.
  if (CurrCont)
    return;

  // Otherwise, if we created a new continuation, then start processing it.
  Builder.beginBlock(Cont);
  auto &Res = resultAttr();
  Res.Exp = Builder.currentBB()->arguments()[0];
}

void TypedEvaluator::traverseFuture(Future* Orig) {
  SExpr *Res = Orig->force();
  traverse(Res, TRV_Decl);
  resultAttr() = std::move( lastAttr() );
}

void TypedEvaluator::traverseNestedCode(Code* Orig) {
  // Code blocks within a CFG are eliminated; we add them to pendingBlocks.
  // TODO: prevent nested blocks from escaping.
  // TODO: this whole thing is a hack right now.

  traverse(Orig->returnType(), TRV_Type);
  traverseNull();
  reduceCode(Orig);
  Code* Nc = cast<Code>(resultAttr().Exp);

  // Create a new block, and add it to pending blocks.
  // The new block will be enqueued on the first call to it,
  // and the queue will be processed before we leave the current CFG.

  // Create a new scope, where args point to phi nodes in the new block.
  unsigned Nargs = Builder.deBruinIndex() -
      Builder.deBruinIndexOfEnclosingNestedFunction();
  unsigned Vidx = scope()->size() - Nargs;

  auto* Nb = Builder.newBlock(Nargs);
  auto* Ns = scope()->clone();
  for (unsigned i=0; i < Nargs; ++i) {
    // TODO: (FIXME) Hack to deal with self-variables.
    auto *Vd = Ns->varDecl(Vidx + i);
    if (!Vd || Vd->kind() == VarDecl::VK_SFun)
      continue;
    assert(Vd->kind() != VarDecl::VK_Let);

    auto &At    = Ns->var(Vidx + i);
    At.Exp      = Nb->arguments()[i];
    At.Rel      = TypedCopyAttr::BT_Equivalent;
    At.TypeExpr = Nb->arguments()[i];
  }

  // Add pending block.
  auto* Pb = new PendingBlock(Orig->body(), Nb, Ns);
  PendingBlks.emplace_back(Pb);
  CodeMap.insert(std::make_pair(Nc, Pb));
}

bool TypedEvaluator::reduceNestedCall(Call* Orig, Code* C) {
  // See if this is a call to a nested function.
  auto It = CodeMap.find(C);
  if (It == CodeMap.end())
    return false;

  auto& Ca  = attr(0);
  auto& Res = resultAttr();

  PendingBlock *Pb = It->second;
  if (Pb->Cont == nullptr) {
    // Set the continuation of PB to the current continuation,
    // and add PB to the queue.
    if (!scope()->currentContinuation()) {
      diag().error("Call to nested function must be a tail call.") << Orig;
      Res.Exp = Builder.newUndefined();
      return true;
    }
    Pb->Cont = scope()->currentContinuation();
    PendingBlockQueue.push(Pb);
  }
  else if (Pb->Cont != scope()->currentContinuation()) {
    // check that the continuations match.
    diag().error("Calls to nested function are not a valid CFG.") << Orig;
    Res.Exp = Builder.newUndefined();
    return true;
  }
  if (Ca.Subst.numSubstVars() != Pb->Block->arguments().size()) {
    diag().error("Invalid number of arguments to function call.") << Orig;
    Res.Exp = Builder.newUndefined();
    return true;
  }

  // Insert a Goto to the new block.
  std::vector<SExpr*> Args;
  for (auto& At : Ca.Subst.varAttrs()) {
    // TODO: (FIXME) Ugly hack to deal with self-arguments.
    if (isa<Function>(At.Exp)) {
      Args.push_back(nullptr);
      continue;
    }
    if (Variable* V = dyn_cast_or_null<Variable>(At.Exp)) {
      if (V->variableDecl()->kind() == VarDecl::VK_SFun) {
        Args.push_back(nullptr);
        continue;
      }
    }
    Args.push_back(At.Exp);
  }
  Builder.newGoto(Pb->Block, ArrayRef<SExpr*>(&Args[0], Args.size()));

  return true;
}

void TypedEvaluator::processPendingBlocks() {
  while (!PendingBlockQueue.empty()) {
    auto* Pb = PendingBlockQueue.front();
    PendingBlockQueue.pop();

    Builder.beginBlock(Pb->Block);
    Pb->Scope->setCurrentContinuation(Pb->Cont);
    auto *S = switchScope(Pb->Scope);

    traverse(Pb->Exp, TRV_Tail);
    popAttr();

    restoreScope(S);
  }
  PendingBlks.clear();
}

}  // end namespace til
}  // end namespace ohmu


text:
class FriendshipsController < ApplicationController
	before_action :authenticate_user!
	before_action :set_user, only: [:create]
	before_action :set_friendship, only: [:destroy, :accept]

	def create
		@friendship = current_user.request_friendship(@user)
		respond_to do |format|
			format.html {redirect_to users_path, notice: "Friendship Created"}
		end
	end

	def destroy
		@friendship.destroy
		respond_to do |format|
			format.html {redirect_to users_path, notice: "Friendship Deleted"}
		end
	end

	def accept
		@friendship.accept_friendship
		@friendship.create_activity key: 'friendship.accepted', owner: @friendship.user, recipient: @friendship.friend
		@friendship.create_activity key: 'friendship.accepted', owner: @friendship.friend, recipient: @friendship.user
		respond_to do |format|
			format.html {redirect_to users_path, notice: "Friendship Accepted"}
		end
	end

	private

	def set_user
		@user = User.find(params[:user_id])
	end

	def set_friendship
		@friendship = Friendship.find(params[:id])
	end
end


text:
/**
 * Handles toggling the navigation menu for small screens and
 * accessibility for submenu items.
 */
( function() {
	var nav = document.getElementById( 'site-navigation' ), button, menu;
	if ( ! nav ) {
		return;
	}

	button = nav.getElementsByTagName( 'button' )[0];
	menu   = nav.getElementsByTagName( 'ul' )[0];
	if ( ! button ) {
		return;
	}

	// Hide button if menu is missing or empty.
	if ( ! menu || ! menu.childNodes.length ) {
		button.style.display = 'none';
		return;
	}

	button.onclick = function() {
		if ( -1 === menu.className.indexOf( 'nav-menu' ) ) {
			menu.className = 'nav-menu';
		}

		if ( -1 !== button.className.indexOf( 'toggled-on' ) ) {
			button.className = button.className.replace( ' toggled-on', '' );
			menu.className = menu.className.replace( ' toggled-on', '' );
		} else {
			button.className += ' toggled-on';
			menu.className += ' toggled-on';
		}
	};
} )();

// Better focus for hidden submenu items for accessibility.
( function( $ ) {
	$( '.main-navigation' ).find( 'a' ).on( 'focus.twentytwelve blur.twentytwelve', function() {
		$( this ).parents( '.menu-item, .page_item' ).toggleClass( 'focus' );
	} );

  if ( 'ontouchstart' in window ) {
    $( '.menu-item-has-children > a' ).on( 'touchstart.twentytwelve', function( e ) {
      var el = $( this ).parent( 'li' );

      if ( ! el.hasClass( 'focus' ) ) {
        e.preventDefault();
        el.toggleClass( 'focus' );
        el.siblings( '.focus').removeClass( 'focus' );
      }
    } );
  }
} )( jQuery );


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Runtime;
using System.ServiceModel;
using System.Xml;

namespace System.ServiceModel.Channels
{
    internal sealed class TerminateSequenceResponse : BodyWriter
    {
        public TerminateSequenceResponse() : base(true)
        {
        }

        public TerminateSequenceResponse(UniqueId identifier)
            : base(true)
        {
            this.Identifier = identifier;
        }

        public UniqueId Identifier { get; set; }

        public static TerminateSequenceResponseInfo Create(XmlDictionaryReader reader)
        {
            if (reader == null)
            {
                Fx.Assert("Argument reader cannot be null.");
            }

            TerminateSequenceResponseInfo terminateSequenceInfo = new TerminateSequenceResponseInfo();
            XmlDictionaryString wsrmNs = WsrmIndex.GetNamespace(ReliableMessagingVersion.WSReliableMessaging11);

            reader.ReadStartElement(DXD.Wsrm11Dictionary.TerminateSequenceResponse, wsrmNs);

            reader.ReadStartElement(XD.WsrmFeb2005Dictionary.Identifier, wsrmNs);
            terminateSequenceInfo.Identifier = reader.ReadContentAsUniqueId();
            reader.ReadEndElement();

            while (reader.IsStartElement())
            {
                reader.Skip();
            }

            reader.ReadEndElement();

            return terminateSequenceInfo;
        }

        protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
        {
            XmlDictionaryString wsrmNs = WsrmIndex.GetNamespace(ReliableMessagingVersion.WSReliableMessaging11);
            writer.WriteStartElement(DXD.Wsrm11Dictionary.TerminateSequenceResponse, wsrmNs);
            writer.WriteStartElement(XD.WsrmFeb2005Dictionary.Identifier, wsrmNs);
            writer.WriteValue(this.Identifier);
            writer.WriteEndElement();
            writer.WriteEndElement();
        }
    }
}


text:
package org.kohsuke.stapler.jelly;

import org.apache.commons.jelly.JellyTagException;
import org.apache.commons.jelly.XMLOutput;
import org.kohsuke.stapler.framework.adjunct.AdjunctManager;
import org.kohsuke.stapler.framework.adjunct.AdjunctsInPage;
import org.xml.sax.SAXException;
import org.jvnet.maven.jellydoc.annotation.NoContent;
import org.jvnet.maven.jellydoc.annotation.Required;

import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Writes out links to adjunct CSS and JavaScript, if not done so already.
 *
 * @author Kohsuke Kawaguchi
 */
@NoContent
public class AdjunctTag extends AbstractStaplerTag {
    private String[] includes;
    private String[] assumes;

    /**
     * Comma-separated adjunct names.
     */
    public void setIncludes(String _includes) {
        includes = parse(_includes);
    }

    /**
     * Comma-separated adjunct names that are externally included in the page
     * and should be suppressed.
     */
    public void setAssumes(String _assumes) {
        assumes = parse(_assumes);
    }

    private String[] parse(String s) {
        String[] r = s.split(",");
        for (int i = 0; i < r.length; i++)
              r[i] = r[i].trim();
        return r;
    }

    public void doTag(XMLOutput out) throws JellyTagException {
        AdjunctManager m = AdjunctManager.get(getServletContext());
        if(m==null) {
            LOGGER.log(Level.WARNING,"AdjunctManager is not installed for this application. Skipping <adjunct> tags", new Exception());
            return;
        }

        try {
            AdjunctsInPage a = AdjunctsInPage.get();
            if (assumes!=null)
                a.assumeIncluded(assumes);
            if (includes!=null)
                a.generate(out, includes);
        } catch (IOException e) {
            throw new JellyTagException(e);
        } catch (SAXException e) {
            throw new JellyTagException(e);
        }
    }

    private static final Logger LOGGER = Logger.getLogger(AdjunctTag.class.getName());
}


text:
<TITLE>Review for Last of the Mohicans, The (1992)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Last of the Mohicans, The (1992)

reviewed by
sun!megatest!jao (John Oswalt)

                         THE LAST OF THE MOHICANS
                       A film review by John Oswalt
                        Copyright 1992 John Oswalt

2 hours, R (violence)
Writers: Michael Mann, Christopher Crowe
Director: Michael Mann
Cast: Daniel Day-Lewis, Madeleine Stowe, Wes Studi, Steven Waddington,
      Jodhi May, Eric Schweig

     About twenty years ago I saw the Masterpiece Theatre series "The
Last Of The Mohicans," and loved it.  I went straight to the library and
read the book.  The current movie, which is a much looser adaptation of
James Fenimore Cooper's 1826 novel, suffers in comparison both to the
book, and to the PBS series.  (Or at least to my twenty-year-old
memories of them.)

     However, THE LAST OF THE MOHICANS, 1992 style, is not all that
bad.  It is generally entertaining, and contains some beautiful scenery.
After the movie, my companion, having watched two hours of action set in
verdant forests with waterfalls at every turn, figured that the movie
was filmed in Hawaii or New Zealand.  Actually, it was filmed in North
Carolina.  It is good to know that there are such beautiful places left.
I am afraid that the West Coaster's view of the East coast is of
factories, endless cities, and acid rain denuded forests.

        I have a lot of quibbles with the movie.  The plot is very
predictable.  When you see a party of red-coats marching through a
clearing in the forest, you just know that some Indians are going to
massacre them, as the European's ritualized formation fighting is
hopelessly outclassed by the guerrilla tactics of the Indians.  Just as
certainly, you know that the main characters will miraculously be
spared.

     I found myself frowning at a lot of the dialogue, which is full of
snappy one-liner comebacks common in today's films.  This is fine for
Dirty Harry, but is the antithesis of Cooper's flowery, wordy style.
(The San Jose Mercury News reviewer, Glenn Lovell, whom I generally
respect, approved of this change.  I suspect that does not have the fond
memories that I have of James Fenimore Cooper's books.  He describes the
book THE LAST OF THE MOHICANS as one which "many of us waded through in
high school and college.")

     It is amazing how clean the main characters' clothes and hair
remain considering all that they go through.  Natty Bumppo always has a
gun ready when he needs it, but we never see him reload.  The women in
the movie don't do much besides cower and swoon.  The fight scenes, of
which there are plenty, are toned down to preserve the R rating.  There
are scenes in which dozens of people get tomahawked, but no guts and
very little blood is shown.  Most of the movie takes place sneaking
around in the dense forest, or at night, or both, and things are a
little hard to see.

     This brings up a pet peeve of mine.  I have seen many Technicolor
movies made in the 30's, 40's, and 50's, and the color in them is far
superior to that in the movies made today.  I recently saw a restored
print of LEAVE HER TO HEAVEN, which was made in Technicolor in 1945.
When I compare that movie, which contains a lot of upstate New York
scenery, with this one, I just shake my head.  Why, Hollywood, did you
abandon a process which produces such beautiful true-to-life colors, for
the washed-out look of today?  With all the millions spent on movie
production you would think that they could use good film.

     However, these are all only quibbles, and considering the current
movie-making conventions and context, THE LAST OF THE MOHICANS is
pretty good.  It even overcomes a few trends.  It is an action picture
with no car chases.  Despite PC, the main bad guy is an American Indian.
There are no product placements.

     I rate it 7 on the 0-10 scale, or a high 0 on the Mark Leeper -4 to
+4 scale.

John Oswalt  (..!sun!megatest!jao)

.

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
@media only screen and (min-width: 64.063em) {
    .media {
        background: transparent url('data:image/gif;base64,R0lGODlhAQABAIAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==') no-repeat left top scroll;
    }
}