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

describe "Taggable" do
  before(:each) do
    clean_database!
    @taggable = TaggableModel.new(:name => "Bob Jones")
    @taggables = [@taggable, TaggableModel.new(:name => "John Doe")]
  end

  it "should have tag types" do
    [:tags, :languages, :skills, :needs, :offerings].each do |type|
      TaggableModel.tag_types.should include type
    end

    @taggable.tag_types.should == TaggableModel.tag_types
  end

  it "should have tag_counts_on" do
    TaggableModel.tag_counts_on(:tags).all.should be_empty

    @taggable.tag_list = ["awesome", "epic"]
    @taggable.save

    TaggableModel.tag_counts_on(:tags).length.should == 2
    @taggable.tag_counts_on(:tags).length.should == 2
  end

  it "should be able to create tags" do
    @taggable.skill_list = "ruby, rails, css"
    @taggable.instance_variable_get("@skill_list").instance_of?(ActsAsTaggableOn::TagList).should be_true

    lambda {
      @taggable.save
    }.should change(ActsAsTaggableOn::Tag, :count).by(3)

    @taggable.reload
    @taggable.skill_list.sort.should == %w(ruby rails css).sort
  end

  it "should be able to create tags through the tag list directly" do
    @taggable.tag_list_on(:test).add("hello")
    @taggable.tag_list_cache_on(:test).should_not be_empty
    @taggable.tag_list_on(:test).should == ["hello"]

    @taggable.save
    @taggable.save_tags

    @taggable.reload
    @taggable.tag_list_on(:test).should == ["hello"]
  end

  it "should differentiate between contexts" do
    @taggable.skill_list = "ruby, rails, css"
    @taggable.tag_list = "ruby, bob, charlie"
    @taggable.save
    @taggable.reload
    @taggable.skill_list.should include("ruby")
    @taggable.skill_list.should_not include("bob")
  end

  it "should be able to remove tags through list alone" do
    @taggable.skill_list = "ruby, rails, css"
    @taggable.save
    @taggable.reload
    @taggable.should have(3).skills
    @taggable.skill_list = "ruby, rails"
    @taggable.save
    @taggable.reload
    @taggable.should have(2).skills
  end

  it "should be able to select taggables by subset of tags using ActiveRelation methods" do
    @taggables[0].tag_list = "bob"
    @taggables[1].tag_list = "charlie"
    @taggables[0].skill_list = "ruby"
    @taggables[1].skill_list = "css"
    @taggables.each{|taggable| taggable.save}

    @found_taggables_by_tag = TaggableModel.joins(:tags).where(:tags => {:name => ["bob"]})
    @found_taggables_by_skill = TaggableModel.joins(:skills).where(:tags => {:name => ["ruby"]})

    @found_taggables_by_tag.should include @taggables[0]
    @found_taggables_by_tag.should_not include @taggables[1]
    @found_taggables_by_skill.should include @taggables[0]
    @found_taggables_by_skill.should_not include @taggables[1]
  end

  it "should be able to find by tag" do
    @taggable.skill_list = "ruby, rails, css"
    @taggable.save

    TaggableModel.tagged_with("ruby").first.should == @taggable
  end

  it "should be able to find by tag with context" do
    @taggable.skill_list = "ruby, rails, css"
    @taggable.tag_list = "bob, charlie"
    @taggable.save

    TaggableModel.tagged_with("ruby").first.should == @taggable
    TaggableModel.tagged_with("ruby, css").first.should == @taggable
    TaggableModel.tagged_with("bob", :on => :skills).first.should_not == @taggable
    TaggableModel.tagged_with("bob", :on => :tags).first.should == @taggable
  end

  it "should not care about case" do
    bob = TaggableModel.create(:name => "Bob", :tag_list => "ruby")
    frank = TaggableModel.create(:name => "Frank", :tag_list => "Ruby")

    ActsAsTaggableOn::Tag.find(:all).size.should == 1
    TaggableModel.tagged_with("ruby").to_a.should == TaggableModel.tagged_with("Ruby").to_a
  end

  it "should be able to get tag counts on model as a whole" do
    bob = TaggableModel.create(:name => "Bob", :tag_list => "ruby, rails, css")
    frank = TaggableModel.create(:name => "Frank", :tag_list => "ruby, rails")
    charlie = TaggableModel.create(:name => "Charlie", :skill_list => "ruby")
    TaggableModel.tag_counts.all.should_not be_empty
    TaggableModel.skill_counts.all.should_not be_empty
  end

  it "should be able to get all tag counts on model as whole" do
    bob = TaggableModel.create(:name => "Bob", :tag_list => "ruby, rails, css")
    frank = TaggableModel.create(:name => "Frank", :tag_list => "ruby, rails")
    charlie = TaggableModel.create(:name => "Charlie", :skill_list => "ruby")

    TaggableModel.all_tag_counts.all.should_not be_empty
    TaggableModel.all_tag_counts(:order => 'tags.id').first.count.should == 3 # ruby
  end

  it "should be able to use named scopes to chain tag finds by any tags by context" do
    bob   = TaggableModel.create(:name => "Bob",   :need_list => "rails", :offering_list => "c++")
    frank = TaggableModel.create(:name => "Frank", :need_list => "css",   :offering_list => "css")
    steve = TaggableModel.create(:name => 'Steve', :need_list => "c++",   :offering_list => "java")

    # Let's only find those who need rails or css and are offering c++ or java
    TaggableModel.tagged_with(['rails, css'], :on => :needs, :any => true).tagged_with(['c++', 'java'], :on => :offerings, :any => true).to_a.should == [bob]
  end

  if ActiveRecord::VERSION::MAJOR >= 3
    it "should not return read-only records" do
      TaggableModel.create(:name => "Bob", :tag_list => "ruby, rails, css")
      TaggableModel.tagged_with("ruby").first.should_not be_readonly
    end
  else
    xit "should not return read-only records" do
      # apparantly, there is no way to set readonly to false in a scope if joins are made
    end

    it "should be possible to return writable records" do
      TaggableModel.create(:name => "Bob", :tag_list => "ruby, rails, css")
      TaggableModel.tagged_with("ruby").first(:readonly => false).should_not be_readonly
    end
  end

  it "should be able to get scoped tag counts" do
    bob = TaggableModel.create(:name => "Bob", :tag_list => "ruby, rails, css")
    frank = TaggableModel.create(:name => "Frank", :tag_list => "ruby, rails")
    charlie = TaggableModel.create(:name => "Charlie", :skill_list => "ruby")

    TaggableModel.tagged_with("ruby").tag_counts(:order => 'tags.id').first.count.should == 2   # ruby
    TaggableModel.tagged_with("ruby").skill_counts.first.count.should == 1 # ruby
  end

  it "should be able to get all scoped tag counts" do
    bob = TaggableModel.create(:name => "Bob", :tag_list => "ruby, rails, css")
    frank = TaggableModel.create(:name => "Frank", :tag_list => "ruby, rails")
    charlie = TaggableModel.create(:name => "Charlie", :skill_list => "ruby")

    TaggableModel.tagged_with("ruby").all_tag_counts(:order => 'tags.id').first.count.should == 3 # ruby
  end

  it 'should only return tag counts for the available scope' do
    bob = TaggableModel.create(:name => "Bob", :tag_list => "ruby, rails, css")
    frank = TaggableModel.create(:name => "Frank", :tag_list => "ruby, rails")
    charlie = TaggableModel.create(:name => "Charlie", :skill_list => "ruby, java")

    TaggableModel.tagged_with('rails').all_tag_counts.should have(3).items
    TaggableModel.tagged_with('rails').all_tag_counts.any? { |tag| tag.name == 'java' }.should be_false

    # Test specific join syntaxes:
    frank.untaggable_models.create!
    TaggableModel.tagged_with('rails').scoped(:joins => :untaggable_models).all_tag_counts.should have(2).items
    TaggableModel.tagged_with('rails').scoped(:joins => { :untaggable_models => :taggable_model }).all_tag_counts.should have(2).items
    TaggableModel.tagged_with('rails').scoped(:joins => [:untaggable_models]).all_tag_counts.should have(2).items
  end

  it "should be able to set a custom tag context list" do
    bob = TaggableModel.create(:name => "Bob")
    bob.set_tag_list_on(:rotors, "spinning, jumping")
    bob.tag_list_on(:rotors).should == ["spinning","jumping"]
    bob.save
    bob.reload
    bob.tags_on(:rotors).should_not be_empty
  end

  it "should be able to find tagged" do
    bob = TaggableModel.create(:name => "Bob", :tag_list => "fitter, happier, more productive", :skill_list => "ruby, rails, css")
    frank = TaggableModel.create(:name => "Frank", :tag_list => "weaker, depressed, inefficient", :skill_list => "ruby, rails, css")
    steve = TaggableModel.create(:name => 'Steve', :tag_list => 'fitter, happier, more productive', :skill_list => 'c++, java, ruby')

    TaggableModel.tagged_with("ruby", :order => 'taggable_models.name').to_a.should == [bob, frank, steve]
    TaggableModel.tagged_with("ruby, rails", :order => 'taggable_models.name').to_a.should == [bob, frank]
    TaggableModel.tagged_with(["ruby", "rails"], :order => 'taggable_models.name').to_a.should == [bob, frank]
  end

  it "should be able to find tagged with quotation marks" do
    bob = TaggableModel.create(:name => "Bob", :tag_list => "fitter, happier, more productive, 'I love the ,comma,'")
    TaggableModel.tagged_with("'I love the ,comma,'").should include(bob)
  end

  it "should be able to find tagged with invalid tags" do
    bob = TaggableModel.create(:name => "Bob", :tag_list => "fitter, happier, more productive")
    TaggableModel.tagged_with("sad, happier").should_not include(bob)
  end

  it "should be able to find tagged with any tag" do
    bob = TaggableModel.create(:name => "Bob", :tag_list => "fitter, happier, more productive", :skill_list => "ruby, rails, css")
    frank = TaggableModel.create(:name => "Frank", :tag_list => "weaker, depressed, inefficient", :skill_list => "ruby, rails, css")
    steve = TaggableModel.create(:name => 'Steve', :tag_list => 'fitter, happier, more productive', :skill_list => 'c++, java, ruby')

    TaggableModel.tagged_with(["ruby", "java"], :order => 'taggable_models.name', :any => true).to_a.should == [bob, frank, steve]
    TaggableModel.tagged_with(["c++", "fitter"], :order => 'taggable_models.name', :any => true).to_a.should == [bob, steve]
    TaggableModel.tagged_with(["depressed", "css"], :order => 'taggable_models.name', :any => true).to_a.should == [bob, frank]
  end

  it "should be able to find tagged on a custom tag context" do
    bob = TaggableModel.create(:name => "Bob")
    bob.set_tag_list_on(:rotors, "spinning, jumping")
    bob.tag_list_on(:rotors).should == ["spinning","jumping"]
    bob.save

    TaggableModel.tagged_with("spinning", :on => :rotors).to_a.should == [bob]
  end

  it "should be able to use named scopes to chain tag finds" do
    bob = TaggableModel.create(:name => "Bob", :tag_list => "fitter, happier, more productive", :skill_list => "ruby, rails, css")
    frank = TaggableModel.create(:name => "Frank", :tag_list => "weaker, depressed, inefficient", :skill_list => "ruby, rails, css")
    steve = TaggableModel.create(:name => 'Steve', :tag_list => 'fitter, happier, more productive', :skill_list => 'c++, java, python')

    # Let's only find those productive Rails developers
    TaggableModel.tagged_with('rails', :on => :skills, :order => 'taggable_models.name').to_a.should == [bob, frank]
    TaggableModel.tagged_with('happier', :on => :tags, :order => 'taggable_models.name').to_a.should == [bob, steve]
    TaggableModel.tagged_with('rails', :on => :skills).tagged_with('happier', :on => :tags).to_a.should == [bob]
    TaggableModel.tagged_with('rails').tagged_with('happier', :on => :tags).to_a.should == [bob]
  end

  it "should be able to find tagged with only the matching tags" do
    bob = TaggableModel.create(:name => "Bob", :tag_list => "lazy, happier")
    frank = TaggableModel.create(:name => "Frank", :tag_list => "fitter, happier, inefficient")
    steve = TaggableModel.create(:name => 'Steve', :tag_list => "fitter, happier")

    TaggableModel.tagged_with("fitter, happier", :match_all => true).to_a.should == [steve]
  end

  it "should be able to find tagged with some excluded tags" do
    bob = TaggableModel.create(:name => "Bob", :tag_list => "happier, lazy")
    frank = TaggableModel.create(:name => "Frank", :tag_list => "happier")
    steve = TaggableModel.create(:name => 'Steve', :tag_list => "happier")

    TaggableModel.tagged_with("lazy", :exclude => true).to_a.should == [frank, steve]
  end

  it "should return an empty scope for empty tags" do
    TaggableModel.tagged_with('').should == []
    TaggableModel.tagged_with(' ').should == []
    TaggableModel.tagged_with(nil).should == []
  end

  it "should not create duplicate taggings" do
    bob = TaggableModel.create(:name => "Bob")
    lambda {
      bob.tag_list << "happier"
      bob.tag_list << "happier"
      bob.save
    }.should change(ActsAsTaggableOn::Tagging, :count).by(1)
  end

  describe "Associations" do
    before(:each) do
      @taggable = TaggableModel.create(:tag_list => "awesome, epic")
    end

    it "should not remove tags when creating associated objects" do
      @taggable.untaggable_models.create!
      @taggable.reload
      @taggable.tag_list.should have(2).items
    end
  end

  describe "grouped_column_names_for method" do
    it "should return all column names joined for Tag GROUP clause" do
      @taggable.grouped_column_names_for(ActsAsTaggableOn::Tag).should == "tags.id, tags.name"
    end

    it "should return all column names joined for TaggableModel GROUP clause" do
      @taggable.grouped_column_names_for(TaggableModel).should == "taggable_models.id, taggable_models.name, taggable_models.type"
    end

    it "should return all column names joined for NonStandardIdTaggableModel GROUP clause" do
      @taggable.grouped_column_names_for(TaggableModel).should == "taggable_models.#{TaggableModel.primary_key}, taggable_models.name, taggable_models.type"
    end
  end

  describe "Single Table Inheritance" do
    before do
      @taggable = TaggableModel.new(:name => "taggable")
      @inherited_same = InheritingTaggableModel.new(:name => "inherited same")
      @inherited_different = AlteredInheritingTaggableModel.new(:name => "inherited different")
    end

    it "should be able to save tags for inherited models" do
      @inherited_same.tag_list = "bob, kelso"
      @inherited_same.save
      InheritingTaggableModel.tagged_with("bob").first.should == @inherited_same
    end

    it "should find STI tagged models on the superclass" do
      @inherited_same.tag_list = "bob, kelso"
      @inherited_same.save
      TaggableModel.tagged_with("bob").first.should == @inherited_same
    end

    it "should be able to add on contexts only to some subclasses" do
      @inherited_different.part_list = "fork, spoon"
      @inherited_different.save
      InheritingTaggableModel.tagged_with("fork", :on => :parts).should be_empty
      AlteredInheritingTaggableModel.tagged_with("fork", :on => :parts).first.should == @inherited_different
    end

    it "should have different tag_counts_on for inherited models" do
      @inherited_same.tag_list = "bob, kelso"
      @inherited_same.save!
      @inherited_different.tag_list = "fork, spoon"
      @inherited_different.save!

      InheritingTaggableModel.tag_counts_on(:tags, :order => 'tags.id').map(&:name).should == %w(bob kelso)
      AlteredInheritingTaggableModel.tag_counts_on(:tags, :order => 'tags.id').map(&:name).should == %w(fork spoon)
      TaggableModel.tag_counts_on(:tags, :order => 'tags.id').map(&:name).should == %w(bob kelso fork spoon)
    end

    it 'should store same tag without validation conflict' do
      @taggable.tag_list = 'one'
      @taggable.save!

      @inherited_same.tag_list = 'one'
      @inherited_same.save!

      @inherited_same.update_attributes! :name => 'foo'
    end
  end

  describe "NonStandardIdTaggable" do
    before(:each) do
      clean_database!
      @taggable = NonStandardIdTaggableModel.new(:name => "Bob Jones")
      @taggables = [@taggable, NonStandardIdTaggableModel.new(:name => "John Doe")]
    end

    it "should have tag types" do
      [:tags, :languages, :skills, :needs, :offerings].each do |type|
        NonStandardIdTaggableModel.tag_types.should include type
      end

      @taggable.tag_types.should == NonStandardIdTaggableModel.tag_types
    end

    it "should have tag_counts_on" do
      NonStandardIdTaggableModel.tag_counts_on(:tags).all.should be_empty

      @taggable.tag_list = ["awesome", "epic"]
      @taggable.save

      NonStandardIdTaggableModel.tag_counts_on(:tags).length.should == 2
      @taggable.tag_counts_on(:tags).length.should == 2
    end

    it "should be able to create tags" do
      @taggable.skill_list = "ruby, rails, css"
      @taggable.instance_variable_get("@skill_list").instance_of?(ActsAsTaggableOn::TagList).should be_true

      lambda {
        @taggable.save
      }.should change(ActsAsTaggableOn::Tag, :count).by(3)

      @taggable.reload
      @taggable.skill_list.sort.should == %w(ruby rails css).sort
    end

    it "should be able to create tags through the tag list directly" do
      @taggable.tag_list_on(:test).add("hello")
      @taggable.tag_list_cache_on(:test).should_not be_empty
      @taggable.tag_list_on(:test).should == ["hello"]

      @taggable.save
      @taggable.save_tags

      @taggable.reload
      @taggable.tag_list_on(:test).should == ["hello"]
    end
  end
end


text:
package riviere.blitzcrank.commands.misc;

import com.jagrosh.jdautilities.command.Command;
import com.jagrosh.jdautilities.command.CommandEvent;
import riviere.blitzcrank.Blitzcrank;

public class ShardsCommand extends Command {
    private final Blitzcrank blitzcrank;

    public ShardsCommand(Blitzcrank blitzcrank) {
        this.name = "shards";
        this.ownerCommand = true;
        this.guildOnly = false;
        this.blitzcrank = blitzcrank;
    }

    @Override
    protected void execute(CommandEvent event) {
        if (event.getArgs().equals("restart")) restart();
        String message = "";
        for (int i = 0; i < blitzcrank.getShardManager().getShards().size(); i++) {
            message += "Shard " + i + ": " + blitzcrank.getShardManager().getShardById(i).getStatus() + " " + blitzcrank.getShardManager().getShardById(i).getPing() + "\n";
        }
        event.reply(message);
    }

    private void restart() {
        for (int i = 0; i < blitzcrank.getShardManager().getShards().size(); i++) {
            blitzcrank.getShardManager().restart(i);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import json
import uuid

from openstackclient.tests.functional.network.v2 import common

class TestMeterRule(common.NetworkTests):
    """Functional tests for meter rule"""

    METER_ID = None
    METER_RULE_ID = None

    @classmethod
    def setUpClass(cls):
        common.NetworkTests.setUpClass()
        if cls.haz_network:
            cls.METER_NAME = uuid.uuid4().hex

            json_output = json.loads(cls.openstack(
                'network meter create -f json ' +
                cls.METER_NAME
            ))
            cls.METER_ID = json_output.get('id')

    @classmethod
    def tearDownClass(cls):
        try:
            if cls.haz_network:
                raw_output = cls.openstack(
                    'network meter delete ' +
                    cls.METER_ID
                )
                cls.assertOutput('', raw_output)
        finally:
            common.NetworkTests.tearDownClass()

    def setUp(self):
        super(TestMeterRule, self).setUp()
        # Nothing in this class works with Nova Network
        if not self.haz_network:
            self.skipTest("No Network service present")

    def test_meter_rule_delete(self):
        """test create, delete"""
        json_output = json.loads(self.openstack(
            'network meter rule create -f json ' +
            '--remote-ip-prefix 10.0.0.0/8 ' +
            self.METER_ID
        ))
        rule_id = json_output.get('id')
        re_ip = json_output.get('remote_ip_prefix')

        self.addCleanup(
            self.openstack,
            'network meter rule delete ' + rule_id
        )
        self.assertIsNotNone(re_ip)
        self.assertIsNotNone(rule_id)
        self.assertEqual(
            '10.0.0.0/8', re_ip
        )

    def test_meter_rule_list(self):
        """Test create, list, delete"""
        json_output = json.loads(self.openstack(
            'network meter rule create -f json ' +
            '--remote-ip-prefix 10.0.0.0/8 ' +
            self.METER_ID
        ))
        rule_id_1 = json_output.get('id')
        self.addCleanup(
            self.openstack,
            'network meter rule delete ' + rule_id_1
        )
        self.assertEqual(
            '10.0.0.0/8',
            json_output.get('remote_ip_prefix')
        )

        json_output_1 = json.loads(self.openstack(
            'network meter rule create -f json ' +
            '--remote-ip-prefix 11.0.0.0/8 ' +
            self.METER_ID
        ))
        rule_id_2 = json_output_1.get('id')
        self.addCleanup(
            self.openstack,
            'network meter rule delete ' + rule_id_2
        )
        self.assertEqual(
            '11.0.0.0/8',
            json_output_1.get('remote_ip_prefix')
        )

        json_output = json.loads(self.openstack(
            'network meter rule list -f json'
        ))
        rule_id_list = [item.get('ID') for item in json_output]
        ip_prefix_list = [item.get('Remote IP Prefix') for item in json_output]
        self.assertIn(rule_id_1, rule_id_list)
        self.assertIn(rule_id_2, rule_id_list)
        self.assertIn('10.0.0.0/8', ip_prefix_list)
        self.assertIn('11.0.0.0/8', ip_prefix_list)

    def test_meter_rule_show(self):
        """Test create, show, delete"""
        json_output = json.loads(self.openstack(
            'network meter rule create -f json ' +
            '--remote-ip-prefix 10.0.0.0/8 ' +
            '--egress ' +
            self.METER_ID
        ))
        rule_id = json_output.get('id')

        self.assertEqual(
            'egress',
            json_output.get('direction')
        )

        json_output = json.loads(self.openstack(
            'network meter rule show -f json ' + rule_id
        ))
        self.assertEqual(
            '10.0.0.0/8',
            json_output.get('remote_ip_prefix')
        )
        self.assertIsNotNone(rule_id)

        self.addCleanup(
            self.openstack,
            'network meter rule delete ' + rule_id
        )


text:
package eu.cloud4soa.adapter.rest.response;

import java.io.Serializable;

/**
 *
 * @author Denis Neuling (dn@cloudcontrol.de)
 */
public class DeleteApplicationResponse extends
		Response<DeleteApplicationResponse> implements Serializable {
	private static final long serialVersionUID = -8954246275281219228L;

	public DeleteApplicationResponse() {
	}

	@Override
	public String toString() {
		return "DeleteApplicationResponse [Response=" + super.toString() + "]";
	}
}


text:
package net.safedata.springboot.training.d02.s05;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * A small Spring Boot app used to demo the usage of a local PostgreSQL database, using a custom configured
 * {@link javax.sql.DataSource}
 *
 * @author bogdan.solga
 */
@SpringBootApplication//(exclude = DataSourceAutoConfiguration.class)
public class CustomDataSourceDemo {

    public static void main(String[] args) {
        SpringApplication.run(CustomDataSourceDemo.class, args);
    }
}


text:
import sys
import os
import sys
import setuptools
from setuptools import find_packages
from setuptools.command.test import test as TestCommand
from distutils.version import StrictVersion
from setuptools import __version__ as setuptools_version

if StrictVersion(setuptools_version) < StrictVersion('38.3.0'):
    raise SystemExit(
        'Your `setuptools` version is old. '
        'Please upgrade setuptools by running `pip install -U setuptools` '
        'and try again.'
    )
def readme():
    with open('README.md') as f:
        return f.read()
setuptools.setup(
    name='pclip',
    version='0.2.7',
    packages={'pclip': ['aoi.json']},
    package_data={'pclip': ['aoi.json']},
    url='https://github.com/samapriya/Clip-Ship-Planet-CLI',
    install_requires=['planet>=1.1.0','psutil>=5.2.2','urllib3>=1.22','requests>=2.18.4','retrying>=1.3.3','pyshp>=1.2.12','progressbar2>=3.34.3',          'pypiwin32; platform_system == "Windows"','pywin32; platform_system == "Windows"'],
    license='Apache 2.0',
    long_description=open('README.rst').read(),
    classifiers=(
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Developers',
        'Intended Audience :: Science/Research',
        'Natural Language :: English',
        'License :: OSI Approved :: Apache Software License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.6',
        'Operating System :: OS Independent',
        'Topic :: Scientific/Engineering :: GIS',
    ),
    author='Samapriya Roy',
    author_email='samapriya.roy@gmail.com',
    description='Planet Clip-Ship Tools CLI',
    entry_points={
        'console_scripts': [
            'pclip=pclip.pclip:main',
        ],
    },
)


text:
require 'sinatra'
require 'haml'
require "gcloud"

set :bind, '0.0.0.0'

get '/' do
  "Updated"
end

get "/upload" do
  haml :upload
end

# Handle POST-request (Receive and save the uploaded file)
post "/upload" do
  gcloud = Gcloud.new "zinc-computer-124720", "service-account-key.json"
  storage = gcloud.storage

  bucket = storage.bucket "zinc-computer-124720"

  bucket.create_file params['myfile'][:tempfile], params['myfile'][:filename]

  return "The file was successfully uploaded!"
end


text:
package com.evolveum.midpoint.notifications.impl.api.transports;

import java.io.IOException;
import java.util.Date;
import java.util.Properties;

import javax.annotation.PostConstruct;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.evolveum.midpoint.notifications.api.NotificationManager;
import com.evolveum.midpoint.notifications.api.transports.Message;
import com.evolveum.midpoint.notifications.api.transports.Transport;
import com.evolveum.midpoint.notifications.impl.NotificationsUtil;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.crypto.EncryptionException;
import com.evolveum.midpoint.prism.crypto.Protector;
import com.evolveum.midpoint.repo.api.RepositoryService;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.MailConfigurationType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.MailServerConfigurationType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.MailTransportSecurityType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType;
import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType;

/**
 * @author mederly
 */
@Component
public class MailTransport implements Transport {

    private static final Trace LOGGER = TraceManager.getTrace(MailTransport.class);

    private static final String NAME = "mail";

    private static final String DOT_CLASS = MailTransport.class.getName() + ".";

    @Autowired(required = true)
    @Qualifier("cacheRepositoryService")
    private transient RepositoryService cacheRepositoryService;

    @Autowired
    private Protector protector;

    @Autowired
    private NotificationManager notificationManager;

    @PostConstruct
    public void init() {
        notificationManager.registerTransport(NAME, this);
    }

    @Override
    public void send(Message mailMessage, String transportName, Task task, OperationResult parentResult) {

        OperationResult result = parentResult.createSubresult(DOT_CLASS + "send");
        result.addCollectionOfSerializablesAsParam("mailMessage recipient(s)", mailMessage.getTo());
        result.addParam("mailMessage subject", mailMessage.getSubject());

        SystemConfigurationType systemConfiguration = NotificationsUtil.getSystemConfiguration(cacheRepositoryService, new OperationResult("dummy"));
        if (systemConfiguration == null || systemConfiguration.getNotificationConfiguration() == null
                || systemConfiguration.getNotificationConfiguration().getMail() == null) {
            String msg = "No notifications are configured. Mail notification to " + mailMessage.getTo() + " will not be sent.";
            LOGGER.warn(msg) ;
            result.recordWarning(msg);
            return;
        }

        MailConfigurationType mailConfigurationType = systemConfiguration.getNotificationConfiguration().getMail();
        if (mailConfigurationType.getRedirectToFile() != null) {
            try {
                TransportUtil.appendToFile(mailConfigurationType.getRedirectToFile(), formatToFile(mailMessage));
                result.recordSuccess();
            } catch (IOException e) {
                LoggingUtils.logException(LOGGER, "Couldn't write to mail redirect file {}", e, mailConfigurationType.getRedirectToFile());
                result.recordPartialError("Couldn't write to mail redirect file " + mailConfigurationType.getRedirectToFile(), e);
            }
            return;
        }

        if (mailConfigurationType.getServer().isEmpty()) {
            String msg = "Mail server(s) are not defined, mail notification to " + mailMessage.getTo() + " will not be sent.";
            LOGGER.warn(msg) ;
            result.recordWarning(msg);
            return;
        }

        String from = mailConfigurationType.getDefaultFrom() != null ? mailConfigurationType.getDefaultFrom() : "nobody@nowhere.org";

        for (MailServerConfigurationType mailServerConfigurationType : mailConfigurationType.getServer()) {

            OperationResult resultForServer = result.createSubresult(DOT_CLASS + "send.forServer");
            resultForServer.addContext("server", mailServerConfigurationType.getHost());
            resultForServer.addContext("port", mailServerConfigurationType.getPort());

            Properties properties = System.getProperties();
            properties.setProperty("mail.smtp.host", mailServerConfigurationType.getHost());
            if (mailServerConfigurationType.getPort() != null) {
                properties.setProperty("mail.smtp.port", String.valueOf(mailServerConfigurationType.getPort()));
            }
            MailTransportSecurityType mailTransportSecurityType = mailServerConfigurationType.getTransportSecurity();

            boolean sslEnabled = false, starttlsEnable = false, starttlsRequired = false;
            switch (mailTransportSecurityType) {
                case STARTTLS_ENABLED: starttlsEnable = true; break;
                case STARTTLS_REQUIRED: starttlsEnable = true; starttlsRequired = true; break;
                case SSL: sslEnabled = true; break;
            }
            properties.put("mail.smtp.ssl.enable", "" + sslEnabled);
            properties.put("mail.smtp.starttls.enable", "" + starttlsEnable);
            properties.put("mail.smtp.starttls.required", "" + starttlsRequired);
            if (Boolean.TRUE.equals(mailConfigurationType.isDebug())) {
                properties.put("mail.debug", "true");
            }

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Using mail properties: ");
                for (Object key : properties.keySet()) {
                    if (key instanceof String && ((String) key).startsWith("mail.")) {
                        LOGGER.debug(" - " + key + " = " + properties.get(key));
                    }
                }
            }

            Session session = Session.getInstance(properties);

            try {
                MimeMessage mimeMessage = new MimeMessage(session);
                mimeMessage.setFrom(new InternetAddress(from));
                for (String recipient : mailMessage.getTo()) {
                    mimeMessage.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient));
                }
                mimeMessage.setSubject(mailMessage.getSubject(), "utf-8");
                String contentType = mailMessage.getContentType();
                if (StringUtils.isEmpty(contentType)) {
                    contentType = "text/plain; charset=UTF-8";
                }
                mimeMessage.setContent(mailMessage.getBody(), contentType);
                javax.mail.Transport t = session.getTransport("smtp");
                if (StringUtils.isNotEmpty(mailServerConfigurationType.getUsername())) {
                    ProtectedStringType passwordProtected = mailServerConfigurationType.getPassword();
                    String password = null;
                    if (passwordProtected != null) {
                        try {
                            password = protector.decryptString(passwordProtected);
                        } catch (EncryptionException e) {
                            String msg = "Couldn't send mail message to " + mailMessage.getTo() + " via " + mailServerConfigurationType.getHost() + ", because the plaintext password value couldn't be obtained. Trying another mail server, if there is any.";
                            LoggingUtils.logException(LOGGER, msg, e);
                            resultForServer.recordFatalError(msg, e);
                            continue;
                        }
                    }
                    t.connect(mailServerConfigurationType.getUsername(), password);
                } else {
                    t.connect();
                }
                t.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
                LOGGER.info("Message sent successfully to " + mailMessage.getTo() + " via server " + mailServerConfigurationType.getHost() + ".");
                resultForServer.recordSuccess();
                result.recordSuccess();
                return;
            } catch (MessagingException e) {
                String msg = "Couldn't send mail message to " + mailMessage.getTo() + " via " + mailServerConfigurationType.getHost() + ", trying another mail server, if there is any";
                LoggingUtils.logException(LOGGER, msg, e);
                resultForServer.recordFatalError(msg, e);
            }
        }
        LOGGER.warn("No more mail servers to try, mail notification to " + mailMessage.getTo() + " will not be sent.") ;
        result.recordWarning("Mail notification to " + mailMessage.getTo() + " could not be sent.");
    }

    private String formatToFile(Message mailMessage) {
        return "============================================ " + new Date() + "\n" + mailMessage.toString() + "\n\n";
    }

    @Override
    public String getDefaultRecipientAddress(UserType recipient) {
        return recipient.getEmailAddress();
    }

    @Override
    public String getName() {
        return NAME;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication5
{
    class ExamTaskFour
    {
        static void Main(string[] args)
        {
            string[] rectInput = new string[2];

            rectInput = Console.ReadLine().Split(' ');
            double Ax = double.Parse(rectInput[0]);
            double Ay = double.Parse(rectInput[1]);
            rectInput = Console.ReadLine().Split(' ');
            double Bx = double.Parse(rectInput[0]);
            double By = double.Parse(rectInput[1]);
            rectInput = Console.ReadLine().Split(' ');
            double Cx = double.Parse(rectInput[0]);
            double Cy = double.Parse(rectInput[1]);
            rectInput = Console.ReadLine().Split(' ');
            double Dx = double.Parse(rectInput[0]);
            double Dy = double.Parse(rectInput[1]);

            double radius = double.Parse(Console.ReadLine());
            double step = double.Parse(Console.ReadLine());

            //double rektTop = Cy;
            //double rektLeft = Cx;
            //double rektHeight = Cy - By;
            //double rektWidth = Cx - Dx;

            //double startTop = rektTop;
            //double startLeft = rektLeft;

            int validPoints = 0;

            for (double i =  Ax + 0.2; i < Bx; i += step)
            {
                for (double j = By + 0.2; j < Cy; j += step)
                {
                    if (isPointInCircle(i, j, 0, 0, radius))
                    {
                        validPoints++;
                    }
                }
            }

            Console.WriteLine(validPoints);
        }

        //private static bool isPointInRectangle(double pointX, double pointY, double rektTop, double rektLeft, double rektWidth, double rektHeight)
        //{
        //    if (pointY <= rektTop && pointY >= rektTop - rektHeight &&
        //        pointX >= rektLeft && pointX <= rektLeft + rektWidth)
        //        return true;
        //    else
        //        return false;
        //}

        private static bool isPointInCircle(double pointX, double pointY, double circleX, double circleY, double circleR)
        {
            if (Math.Pow(pointX - circleX, 2) + Math.Pow(pointY - circleY, 2) <= Math.Pow(circleR, 2))
                return true;
            else
                return false;
        }
    }
}


text:
module API42
    class ServerError < Exception
    end
end


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace xEntry
{
    public partial class frflash : Form
    {
        public frflash()
        {
            InitializeComponent();
        }

        private void tmrFlash_Tick(object sender, EventArgs e)
        {
            tmrFlash.Interval = 2000;
            tmrFlash.Tick += new System.EventHandler(OnTimerEvent);
        }

        public void OnTimerEvent(object sender, EventArgs e)
        {
            this.Hide();
            tmrFlash.Enabled = false;

            mdiMainForm mainform = new mdiMainForm();
            mainform.Show();
        }

        private void frflash_Load(object sender, EventArgs e)
        {
            tmrFlash.Enabled = true;
        }
    }
}


text:
<?php

namespace Arcamy\HomeBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use FOS\RestBundle\View\View;
use FOS\RestBundle\Controller\Annotations,
    FOS\RestBundle\Controller\Annotations\NoRoute,
    FOS\RestBundle\Controller\Annotations\Get,
    FOS\RestBundle\Controller\Annotations\Delete,
    FOS\RestBundle\Controller\Annotations\Put,
    FOS\RestBundle\Controller\Annotations\Post;

class RestController extends Controller
{
    /**
     * @Get("/vegetals")
     *
     */
    public function getVegetalsAction()
    {
        $vegetals = $this->getDoctrine()
                           ->getEntityManager()
                           ->getRepository('HomeBundle:Vegetal')
                           ->getAllVegetals();
        $view = View::create()
          ->setStatusCode(200)
          ->setData($vegetals);

        return $view;
    } // "get_vegetals"    [GET] /vegetals

    /**
     * @DELETE("/vegetal/{id}")
     *
     */
    public function deleteVegetalAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();
        $guest = $em->getRepository('HomeBundle:Vegetal')->find($id);

        if (!$guest) {
            throw $this->createNotFoundException('No guest found for id '.$id);
        }

        $em->remove($guest);
        $em->flush();

        $view = View::create()
          ->setStatusCode(200);

        return $view;
    } // "delete_vegetal"    [DELETE] /vegetal/{id}

    /**
     * @GET("/vegetal/{id}")
     *
     */
    public function getVegetalAction($id)
    {
        $vegetals = $this->getDoctrine()
                           ->getEntityManager()
                           ->getRepository('HomeBundle:Vegetal')
                           ->getVegetalById($id);
        $view = View::create()
          ->setStatusCode(200)
          ->setData($vegetals);

        return $view;
    } // "get_vegetal"    [GET] /vegetal/{id}

    /**
     * @POST("/vegetal")
     *
     */
    public function postVegetalAction(Request $request)
    {
        $em = $this->getDoctrine()->getEntityManager();
        $type = $em->getRepository('HomeBundle:Type')->find($request->get('type'));

        $vegetable = new \Arcamy\HomeBundle\Entity\Vegetal();
        $vegetable->setName($request->get('name'));
        $vegetable->setDescription($request->get('description'));
        $vegetable->setType($type);
        //$vegetable->setCreatedAt(time());

        $em->persist($vegetable);
        $em->flush();

        $view = View::create()
          ->setStatusCode(200);

        return $view;
    } // "post_vegetal"    [POST] /vegetal

    /**
     * @PUT("/vegetal/{id}")
     *
     */
    public function putVegetalAction(Request $request)
    {
        $em = $this->getDoctrine()->getEntityManager();
        $vegetable = $em->getRepository('HomeBundle:Vegetal')->find($request->get('id'));
        $type = $em->getRepository('HomeBundle:Type')->find($request->get('type'));

        $vegetable->setName($request->get('name'));
        $vegetable->setDescription($request->get('description'));
        $vegetable->setType($type);
        //$vegetable->setCreatedAt(time());

        $em->persist($vegetable);
        $em->flush();

        $view = View::create()
          ->setStatusCode(200);

        return $view;
    } // "put_vegetal"    [PUT] /vegetal

    /**
     * @GET("/types")
     *
     */
    public function getTypesAction()
    {
        $em = $this->getDoctrine()->getEntityManager();
        $type = $em->getRepository('HomeBundle:Type')->findAll();

        $view = View::create()
          ->setStatusCode(200)
          ->setData($type);

        return $view;
    } // "get_types"    [GET] /types
}


text:
default[:mongodb][:user]  = "mongodb"
default[:mongodb][:group] = "mongodb"

default[:mongodb][:bind_address] = "127.0.0.1"
default[:mongodb][:port]         = "27017"

default[:mongodb][:version]   = '2.0.0'
default[:mongodb][:file_name] = "mongodb-linux-#{kernel[:machine] || 'i686'}-#{mongodb[:version]}"
default[:mongodb][:url]       = "http://fastdl.mongodb.org/linux/#{mongodb[:file_name]}.tgz"

default[:mongodb][:root]       = "/usr/local/mongodb"
default[:mongodb][:bin_path]   = "/usr/local/bin/mongod"
default[:mongodb][:data_dir]   = "/data/db"
default[:mongodb][:log_dir]    = "/var/log/mongodb"
default[:mongodb][:config_dir] = "/etc/mongodb"
default[:mongodb][:pid_dir]    = "/var/run"
default[:mongodb][:pid_path]   = "#{mongodb[:pid_dir]}/mongod.pid"

default[:mongodb][:username] = ''
default[:mongodb][:password] = ''
default[:mongodb][:database] = ''

default[:mongodb][:auth] = 'false'


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <parent>
    <artifactId>parent</artifactId>
    <groupId>de.utkast.ozark.loadtests</groupId>
    <version>1.0-SNAPSHOT</version>
  </parent>

  <artifactId>base</artifactId>
  <packaging>jar</packaging>

  <dependencies>
    <dependency>
      <groupId>javax.mvc</groupId>
      <artifactId>javax.mvc-api</artifactId>
      <version>${version.mvc}</version>
    </dependency>
    <dependency>
      <groupId>org.glassfish.ozark</groupId>
      <artifactId>ozark</artifactId>
      <version>${version.ozark}</version>
    </dependency>
    <dependency>
      <groupId>javax</groupId>
      <artifactId>javaee-web-api</artifactId>
      <version>7.0</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>

</project>


text:
<?php

namespace Elastica\Test\Aggregation;

use Elastica\Aggregation\Nested;
use Elastica\Aggregation\ReverseNested;
use Elastica\Aggregation\Terms;
use Elastica\Document;
use Elastica\Index;
use Elastica\Mapping;
use Elastica\Query;

/**
 * @internal
 */
class ReverseNestedTest extends BaseAggregationTest
{
    /**
     * @group unit
     */
    public function testPathNotSetIfNull(): void
    {
        $agg = new ReverseNested('nested');
        $this->assertFalse($agg->hasParam('path'));
    }

    /**
     * @group unit
     */
    public function testPathSetIfNotNull(): void
    {
        $agg = new ReverseNested('nested', 'some_field');
        $this->assertEquals('some_field', $agg->getParam('path'));
    }

    /**
     * @group functional
     */
    public function testReverseNestedAggregation(): void
    {
        $agg = new Nested('comments', 'comments');
        $names = new Terms('name');
        $names->setField('comments.name');

        $tags = new Terms('tags');
        $tags->setField('tags');

        $reverseNested = new ReverseNested('main');
        $reverseNested->addAggregation($tags);

        $names->addAggregation($reverseNested);

        $agg->addAggregation($names);

        $query = new Query();
        $query->addAggregation($agg);
        $results = $this->_getIndexForTest()->search($query)->getAggregation('comments');

        $this->assertArrayHasKey('name', $results);
        $nameResults = $results['name'];

        $this->assertCount(3, $nameResults['buckets']);

        // bob
        $this->assertEquals('bob', $nameResults['buckets'][0]['key']);
        $tags = [
            ['key' => 'foo', 'doc_count' => 2],
            ['key' => 'bar', 'doc_count' => 1],
            ['key' => 'baz', 'doc_count' => 1],
        ];
        $this->assertEquals($tags, $nameResults['buckets'][0]['main']['tags']['buckets']);

        // john
        $this->assertEquals('john', $nameResults['buckets'][1]['key']);
        $tags = [
            ['key' => 'bar', 'doc_count' => 1],
            ['key' => 'foo', 'doc_count' => 1],
        ];
        $this->assertEquals($tags, $nameResults['buckets'][1]['main']['tags']['buckets']);

        // susan
        $this->assertEquals('susan', $nameResults['buckets'][2]['key']);
        $tags = [
            ['key' => 'baz', 'doc_count' => 1],
            ['key' => 'foo', 'doc_count' => 1],
        ];
        $this->assertEquals($tags, $nameResults['buckets'][2]['main']['tags']['buckets']);
    }

    protected function _getIndexForTest(): Index
    {
        $index = $this->_createIndex();
        $mapping = new Mapping();
        $mapping->setProperties([
            'comments' => [
                'type' => 'nested',
                'properties' => [
                    'name' => ['type' => 'keyword'],
                    'body' => ['type' => 'text'],
                ],
            ],
            'tags' => ['type' => 'keyword'],
        ]);

        $index->setMapping($mapping);

        $index->addDocuments([
            new Document('1', [
                'comments' => [
                    [
                        'name' => 'bob',
                        'body' => 'this is bobs comment',
                    ],
                    [
                        'name' => 'john',
                        'body' => 'this is johns comment',
                    ],
                ],
                'tags' => ['foo', 'bar'],
            ]),
            new Document('2', [
                'comments' => [
                    [
                        'name' => 'bob',
                        'body' => 'this is another comment from bob',
                    ],
                    [
                        'name' => 'susan',
                        'body' => 'this is susans comment',
                    ],
                ],
                'tags' => ['foo', 'baz'],
            ]),
        ]);

        $index->refresh();

        return $index;
    }
}


text:
//------------------------------------------------------------------------------
// <copyright file="AceJumpCommand.cs" company="Company">
//     Copyright (c) Company.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

using System;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Windows.Forms;
using AceJump;
using AceJumpPackage.Interfaces;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;

namespace AceJumpPackage
{
    /// <summary>
    /// Command handler
    /// </summary>
    public sealed class AceJumpCommand
    {
        /// <summary>
        /// Command ID.
        /// </summary>
        public const int CommandId = 0x0100;

        /// <summary>
        /// Command menu group (command set GUID).
        /// </summary>
        public static readonly Guid CommandSet = new Guid("20929872-63f6-48df-bc23-04798035c26f");

        /// <summary>
        /// VS Package that provides this command, not null.
        /// </summary>
        private readonly Package myPackage;

        private const string VsVimSetDisabled = "VsVim.SetDisabled";

        private const string VsVimSetEnabled = "VsVim.SetEnabled";

        private readonly ICommandExecutorService myCommandExecutorService;
        private readonly IViewProvider myViewProvider;

        /// <summary>
        /// Initializes a new instance of the <see cref="AceJumpCommand"/> class.
        /// Adds our command handlers for menu (commands must exist in the command table file)
        /// </summary>
        /// <param name="package">Owner package, not null.</param>
        /// <param name="commandExecutor"></param>
        /// <param name="viewProvider"></param>
        private AceJumpCommand(IServiceProvider package, ICommandExecutorService commandExecutor, IViewProvider viewProvider)
        {
            if (package == null)
            {
                throw new ArgumentNullException(nameof(package));
            }

            if (commandExecutor == null)
            {
                throw new ArgumentNullException(nameof(commandExecutor));
            }

            if (viewProvider == null)
            {
                throw new ArgumentNullException(nameof(viewProvider));
            }

            this._serviceProvider = package;
            this.myCommandExecutorService = commandExecutor;
            myViewProvider = viewProvider;

            OleMenuCommandService commandService = this._serviceProvider.GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
            if (commandService != null)
            {
                var menuCommandID = new CommandID(CommandSet, CommandId);
                var menuItem = new MenuCommand(this.MenuItemCallback, menuCommandID);
                commandService.AddCommand(menuItem);
            }
        }

        private void InputListenerOnKeyPressed(object sender, KeyPressEventArgs keyPressEventArgs)
        {
            if (_jumpControler.ControlJump(keyPressEventArgs.KeyChar))
            {
                _input.KeyPressed -= InputListenerOnKeyPressed;
                _input.RemoveFilter();
                TryEnableVsVim();
            }
        }

        /// <summary>
        /// Gets the instance of the command.
        /// </summary>
        public static AceJumpCommand Instance
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the service provider from the owner package.
        /// </summary>
        private IServiceProvider _serviceProvider;

        private JumpControler _jumpControler;
        private InputListener _input;

        /// <summary>
        /// Initializes the singleton instance of the command.
        /// </summary>
        /// <param name="package">Owner package, not null.</param>
        /// <param name="commandExecutor">command executor, not null. Needed to turn off VsVim during command execution</param>
        /// <param name="viewProvider">service to get current view</param>
        public static void Initialize(IServiceProvider package, ICommandExecutorService commandExecutor, IViewProvider viewProvider)
        {
            Instance = new AceJumpCommand(package, commandExecutor, viewProvider);
        }

        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void MenuItemCallback(object sender, EventArgs e)
        {
            if (_jumpControler != null && _jumpControler.Active())
                return;

            IVsTextView view = myViewProvider.GetActiveView();
            if (view == null)
            {
                Debug.WriteLine("AceJumpCommand.cs | MenuItemCallback | could not retrieve current view");
                return;
            }

            var textView = myViewProvider.GetActiveWpfView(view);

            _jumpControler?.Close();
            var ace = new AceJump.AceJump();
            ace.SetView(textView);

            _jumpControler = new JumpControler(ace);
            _jumpControler.ShowJumpEditor();

            TryDisableVsVim();
            CreateInputListener(view, textView);
        }

        private void TryDisableVsVim()
        {
            if (myCommandExecutorService.IsCommandAvailable(VsVimSetDisabled))
            {
                myCommandExecutorService.Execute(VsVimSetDisabled);
            }
        }

        private void TryEnableVsVim()
        {
            if (myCommandExecutorService.IsCommandAvailable(VsVimSetEnabled))
            {
                myCommandExecutorService.Execute(VsVimSetEnabled);
            }
        }

        private void CreateInputListener(IVsTextView view, IWpfTextView textView)
        {
            _input = new InputListener(view, textView);
            _input.AddFilter();
            _input.KeyPressed += InputListenerOnKeyPressed;
        }
    }
}


text:
#ifndef __FTTextureGlyphImpl__
#define __FTTextureGlyphImpl__

#include "FTGlyphImpl.h"

class FTTextureGlyphImpl : public FTGlyphImpl
{
    friend class FTTextureGlyph;
    friend class FTTextureFontImpl;

    protected:
        FTTextureGlyphImpl(FT_GlyphSlot glyph, int id, int xOffset,
                           int yOffset, int width, int height);

        virtual ~FTTextureGlyphImpl();

        virtual const FTPoint& RenderImpl(const FTPoint& pen, int renderMode);

    private:
        /**
         * Kept for backwards compatability with FTGL.
         */
        static void ResetActiveTexture() {}

        /**
         * The width of the glyph 'image'
         */
        int destWidth;

        /**
         * The height of the glyph 'image'
         */
        int destHeight;

        /**
         * Vector from the pen position to the topleft corner of the pixmap
         */
        FTPoint corner;

        /**
         * The texture co-ords of this glyph within the texture.
         */
        FTPoint uv[2];

        /**
         * The texture index that this glyph is contained in.
         */
        int glTextureID;
};

#endif  //  __FTTextureGlyphImpl__


text:
from django.contrib.admin.utils import quote, unquote
from django.core.paginator import Paginator
from django.shortcuts import get_object_or_404
from django.template.response import TemplateResponse
from django.urls import reverse
from django.utils.translation import gettext as _
from django.views.generic.base import View

from wagtail.admin.forms.search import SearchForm
from wagtail.admin.modal_workflow import render_modal_workflow
from wagtail.admin.ui.tables import Table, TitleColumn
from wagtail.core.models import Locale, TranslatableMixin
from wagtail.search.backends import get_search_backend
from wagtail.search.index import class_is_indexed
from wagtail.snippets.views.snippets import get_snippet_model_from_url_params

class SnippetTitleColumn(TitleColumn):
    def __init__(self, name, model, **kwargs):
        self.model_opts = model._meta
        super().__init__(name, **kwargs)

    def get_value(self, instance):
        return str(instance)

    def get_link_url(self, instance, parent_context):
        return reverse(
            'wagtailsnippets:chosen', args=[self.model_opts.app_label, self.model_opts.model_name, quote(instance.pk)]
        )

class BaseChooseView(View):
    def get(self, request, app_label, model_name):
        self.model = get_snippet_model_from_url_params(app_label, model_name)

        items = self.model.objects.all()

        # Preserve the snippet's model-level ordering if specified, but fall back on PK if not
        # (to ensure pagination is consistent)
        if not items.ordered:
            items = items.order_by('pk')

        # Filter by locale
        self.locale = None
        self.locale_filter = None
        self.selected_locale = None
        if issubclass(self.model, TranslatableMixin):
            # 'locale' is the Locale of the object that this snippet is being chosen for
            if request.GET.get('locale'):
                self.locale = get_object_or_404(Locale, language_code=request.GET['locale'])

            # 'locale_filter' is the current value of the "Locale" selector in the UI
            if request.GET.get('locale_filter'):
                self.locale_filter = get_object_or_404(Locale, language_code=request.GET['locale_filter'])

            self.selected_locale = self.locale_filter or self.locale

            if self.selected_locale:
                items = items.filter(locale=self.selected_locale)

        # Search
        self.is_searchable = class_is_indexed(self.model)
        self.is_searching = False
        self.search_query = None
        if self.is_searchable and 'q' in request.GET:
            self.search_form = SearchForm(request.GET, placeholder=_("Search %(snippet_type_name)s") % {
                'snippet_type_name': self.model._meta.verbose_name
            })

            if self.search_form.is_valid():
                self.search_query = self.search_form.cleaned_data['q']

                search_backend = get_search_backend()
                items = search_backend.search(self.search_query, items)
                self.is_searching = True

        else:
            self.search_form = SearchForm(placeholder=_("Search %(snippet_type_name)s") % {
                'snippet_type_name': self.model._meta.verbose_name
            })

        # Pagination
        paginator = Paginator(items, per_page=25)
        self.paginated_items = paginator.get_page(request.GET.get('p'))

        self.table = Table([
            SnippetTitleColumn('title', self.model, label=_('Title'), link_classname='snippet-choice'),
        ], self.paginated_items)

        return self.render_to_response()

    def render_to_response(self):
        raise NotImplementedError()

class ChooseView(BaseChooseView):
    # Return the choose view as a ModalWorkflow response
    def render_to_response(self):
        return render_modal_workflow(
            self.request,
            'wagtailsnippets/chooser/choose.html', None,
            {
                'model_opts': self.model._meta,
                'items': self.paginated_items,
                'table': self.table,
                'is_searchable': self.is_searchable,
                'search_form': self.search_form,
                'query_string': self.search_query,
                'is_searching': self.is_searching,
                'locale': self.locale,
                'locale_filter': self.locale_filter,
                'selected_locale': self.selected_locale,
                'locale_options': Locale.objects.all() if issubclass(self.model, TranslatableMixin) else [],
            }, json_data={'step': 'choose'}
        )

class ChooseResultsView(BaseChooseView):
    # Return just the HTML fragment for the results
    def render_to_response(self):
        return TemplateResponse(self.request, "wagtailsnippets/chooser/results.html", {
            'model_opts': self.model._meta,
            'items': self.paginated_items,
            'table': self.table,
            'query_string': self.search_query,
            'is_searching': self.is_searching,
        })

def chosen(request, app_label, model_name, pk):
    model = get_snippet_model_from_url_params(app_label, model_name)
    item = get_object_or_404(model, pk=unquote(pk))

    snippet_data = {
        'id': str(item.pk),
        'string': str(item),
        'edit_link': reverse('wagtailsnippets:edit', args=(
            app_label, model_name, quote(item.pk)))
    }

    return render_modal_workflow(
        request,
        None, None,
        None, json_data={'step': 'chosen', 'result': snippet_data}
    )


text:
/*
 * Deserialize.hpp
 *
 *  Created on: Dec 9, 2015
 *      Author: apertuscus
 */

#include <sys/socket.h>
#include <arpa/inet.h>
#include "utils.hpp"
#include "Deserialize_structs.hpp"
#ifndef SRC_DESERIALIZE_HPP_
#define SRC_DESERIALIZE_HPP_
using namespace std;

class URdata
{
protected:
	std::string type;

	bool configured;
public:
	URdata(): type("UNSET"),
		configured(false){}

	typedef boost::shared_ptr<URdata> Ptr;
	virtual ~URdata(){}
	/**
	 * @brief read the data structure from the data
	 * @param sockfd socket descriptor
	 * @return  negative with an error (to be doumented in specific implementations)
	 *		otherwise the bytes read
	 */
	virtual int readURdata(const int sockfd)=0;

	/** @name Getter functions
	 *  These functions all returns -1 if they are not
	 *  implemented in the derived class,
	 * Other errors (negative values) can depend on specific implementation
	 */
	///@{

	virtual int getType(string  &t)const{t=type; return -1;}

	virtual int getIsRobotConnected  ( bool&t)const {return -1;}
	virtual int getIsEmergencyStopped  ( bool&t)const {return -1;}
	virtual int getIsProgramRunning  ( bool&t)const {return -1;}
	virtual int getIsProgramPaused  ( bool&t)const {return -1;}

	///@}

};

/** @name Class that are Ok for most of the versions
 */
///@{
class joints{
	static const int id=0;
public:
	data_joints data;
	int read_data(const int sockfd)
	{
		int n = read(sockfd,&data,sizeof(data));
		for (int i=0;i<6;i++)
		{
			swap(data.joint[i].q_actual);
			swap(data.joint[i].q_target);
			swap(data.joint[i].qd_actual);
			swap(data.joint[i].I_actual);
			swap(data.joint[i].V_actual);
			swap(data.joint[i].T_motor);
			swap(data.joint[i].T_micro);
			swap(data.joint[i].jointMode);
		}
		return n;
	}
} ;

class pkg_descriptor{
public:
	data_package_descriptor data;
	int read_data(const int sockfd)
	{
		int n = read(sockfd,&data,sizeof(data));
		data.packageSize=ntohl(data.packageSize);
		return n;
	}
};
///@}

class robot_mode_v31{
	static const int id=0;
public:
	data_robot_mode_v31 data;
	int read_data(const int sockfd)
	{
		int n = read(sockfd,&data,sizeof(data));
		swap(data.timestamp);
		ntohd(data.targetSpeedFraction);
		ntohd(data.speedScaling);
		return n;
	}
} ;

class URdataV31:public URdata
{
public:
	URdataV31(){type="3.1";}
	robot_mode_v31 robot_mode_value;
	joints joints_value;
	char buffer[4096];
	int readURdata(const int sockfd)
	{
		//first read an integer to get the size of the package.
		pkg_descriptor pkg_descr;

		int n = pkg_descr.read_data(sockfd);
		int byte_total=pkg_descr.data.packageSize;
		int bytes_left =byte_total;
		bytes_left-=n;
#ifndef NDEBUG
		cout<<"read 1: bites read: "<<n
		   <<"\n\tpkg_descr.packageSize (byte total):"<<pkg_descr.data.packageSize
		  <<"\n\tpkg_descr.packageType: "<< (int)pkg_descr.data.packageType
		 <<"\n\tbytes_left= "<<bytes_left<<endl;
#endif
		if ((int)pkg_descr.data.packageType!=16)
		{//error
			n = read(sockfd,&buffer,sizeof(buffer));
			return -1;
		}

		int last_read=-1;
		bool ok=true;
		while(bytes_left>0)
		{
			n = pkg_descr.read_data(sockfd);
			bytes_left-=n;
#ifndef NDEBUG
			cout<<"\n\tpkg_descr.packageSize (byte total):"<<pkg_descr.data.packageSize
			   <<"\n\tpkg_descr.packageType: "<< (int)pkg_descr.data.packageType<<bytes_left<<endl;
#endif
			if(last_read<=(int)pkg_descr.data.packageType)
			{
				cout<<"last_read:\t"<<last_read<<"\tread: "<<(int)pkg_descr.data.packageType<<endl;
			}
			else last_read=(int)pkg_descr.data.packageType;

			switch((int)pkg_descr.data.packageType) {
			case 0:
				n=  robot_mode_value.read_data(sockfd);
				bytes_left-=n;
#ifndef NDEBUG
				cout<<"read package: bites read: "<<n
				   <<"\n\trobot_mode_value :"<<robot_mode_value.data.timestamp
				  <<endl;
#endif
				break;
			case 1:
				n=  joints_value.read_data(sockfd);
				bytes_left-=n;
#ifndef NDEBUG
				cout<<"read robot_mode_value: bites read: "<<n
				   <<"\n\t j1:"<<joints_value.data.joint[0].q_actual/3.14*180
				  <<"\n\t j2:"<<joints_value.data.joint[1].q_actual/3.14*180
				 <<"\n\t j3:"<<joints_value.data.joint[2].q_actual/3.14*180
				<<"\n\t j4:"<<joints_value.data.joint[3].q_actual/3.14*180
				<<"\n\t j5:"<<joints_value.data.joint[4].q_actual/3.14*180
				<<"\n\t j6:"<<joints_value.data.joint[5].q_actual/3.14*180
				<<endl;
#endif
			default:
				ok=false;
				break;
			}
			if (!ok) break;

		}
		// read the rest
		n = read(sockfd,&buffer,bytes_left);
#ifndef NDEBUG
		cout<<"END: bites read to flush: "<<n
		   <<"\n\t expected:"<<bytes_left<<endl;
#endif

		return byte_total;
	}

	 int getType(string  &t)const{t=type; return -1;}

	int getIsRobotConnected  ( bool&t)const
	{
		t=robot_mode_value.data.isRobotConnected;
		return 1;
	}

	int getIsEmergencyStopped  ( bool&t)const
	{
		t=robot_mode_value.data.isEmergencyStopped;
		return 1;
	}
	int getIsProgramRunning  ( bool&t)const
	{
		t=robot_mode_value.data.isProgramRunning;
		return 1;
	}
	int getIsProgramPaused  ( bool&t)const
	{
		t=robot_mode_value.data.isProgramPaused;
		return 1;
	}
private:

};

#endif /* SRC_RTDESERIALIZE_HPP_ */


text:
package com.github.sviengine.animation;

import com.github.sviengine.SVIEngineDesc;
import com.github.sviengine.SVIEngineThreadProtection;
import com.github.sviengine.animation.SVIPropertyAnimation;
import com.github.sviengine.basetype.SVIColor;
import com.github.sviengine.basetype.SVIPoint;
import com.github.sviengine.basetype.SVIRect;
import com.github.sviengine.basetype.SVIVector3;
import com.github.sviengine.basetype.SVIVector4;
import com.github.sviengine.glsurface.SVIGLSurface;
import com.github.sviengine.slide.SVISlide.ImageScaleType;

/**
 * SVIKeyFrameAnimation Class
 * This Class is make animation use Key frame. you can use key frame time ( 0.0f ~ 1.0f) to control animation
 * Key frame must bigger than past key frame value. (etc. 0.0f -> 0.5f -> 1.0f)
 */
public class SVIKeyFrameAnimation extends SVIPropertyAnimation {
	public SVIKeyFrameAnimation(int type) {
		this(null, type);
	}

	public SVIKeyFrameAnimation(int type, int lightType) {
		this(null, type, lightType);
	}

    /**
     * constructor
     *
     * @see SVIPropertyAnimation
     * @param type > property type
     */
    SVIKeyFrameAnimation(SVIGLSurface saglSurface, int type) {
    	super(saglSurface);

        initializeKeyFrameAnimation(type);
    }

    /**
     * constructor use LightType
     *
     * @see SVIPropertyAnimation
     * @param type > property type
     * @param lightType > @see LightType
     */
    SVIKeyFrameAnimation(SVIGLSurface saglSurface, int type, int lightType) {
    	super(saglSurface);

        mLightType = lightType;
        initializeKeyFrameAnimation(type);
    }

    /**
     * initialize
     *
     * @see SVIPropertyAnimation
     * @param type > property type
     */
    public void initializeKeyFrameAnimation(int type){
    	SVIEngineThreadProtection.validateMainThread();
        if (type == PropertyAnimationType.SCALETOFIT_REGION)
            mScaleType = ImageScaleType.MATRIX;
        mAnimationType = type;
        mClassType = SVIAnimationClass.KEYFRAME;
        mNativeAnimation = nativeCreateSVIKeyFrameAnimation(type, mSVIGLSurface.getNativeHandle());
    }

    /**
     * add key property use float
     *
     * @param keyTime > 0.0f ~ 1.0f
     * @param value > float (etc. opacity ...)
     */
    public void addKeyProperty(float keyTime, float value) {
    	SVIEngineThreadProtection.validateMainThread();
        float[] data = {value};
        nativeAddKeyProperty(mNativeAnimation, mAnimationType, keyTime, data);
    }

    /**
     * add key property use SVIPoint
     *
     * @param keyTime > 0.0f ~ 1.0f
     * @param point > SVIPoint (etc. point ... )
     */
    public void addKeyProperty(float keyTime, SVIPoint point) {
    	SVIEngineThreadProtection.validateMainThread();
        float[] data = {point.mX, point.mY};
        nativeAddKeyProperty(mNativeAnimation, mAnimationType, keyTime, data);
    }

    /**
     * add key property use SVIRect
     *
     * @param keyTime > 0.0f ~ 1.0f
     * @param rect > SVIRect (etc. region ... )
     */
    public void addKeyProperty(float keyTime, SVIRect rect) {
    	SVIEngineThreadProtection.validateMainThread();
        float[] data = {rect.mOrigin.mX, rect.mOrigin.mY, rect.mSize.mWidth, rect.mSize.mHeight};
        nativeAddKeyProperty(mNativeAnimation, mAnimationType, keyTime, data);
    }

    /**
     * add key property use SVIColor
     *
     * @param keyTime >  0.0f ~ 1.0f
     * @param color > SVIColor (etc. color ... )
     */
    public void addKeyProperty(float keyTime, SVIColor color) {
    	SVIEngineThreadProtection.validateMainThread();
        float[] data = {color.mR, color.mG, color.mB, color.mA};
        nativeAddKeyProperty(mNativeAnimation, mAnimationType, keyTime, data);
    }

    /**
     * add key property use SVIVector3
     *
     * @param keyTime >  0.0f ~ 1.0f
     * @param value > SVIVector3 (etc. rotation ... )
     */
    public void addKeyProperty(float keyTime, SVIVector3 value) {
    	SVIEngineThreadProtection.validateMainThread();
        float[] data = {value.mX, value.mY, value.mZ};
        nativeAddKeyProperty(mNativeAnimation, mAnimationType, keyTime, data);
    }

    /**
     * add key property use SVIVector4
     *
     * @param keyTime >  0.0f ~ 1.0f
     * @param value > SVIVector4 (etc. rotation ... )
     */
    public void addKeyProperty(float keyTime, SVIVector4 value) {
    	SVIEngineThreadProtection.validateMainThread();
        float[] data = {value.mX, value.mY, value.mZ, value.mW};
        nativeAddKeyProperty(mNativeAnimation, mAnimationType, keyTime, data);
    }

    /**
     * add key property use float[]
     *
     * @param keyTime >  0.0f ~ 1.0f
     * @param value > float array (etc. color ... )
     */
    public void addKeyProperty(float keyTime, float[] value) {
    	SVIEngineThreadProtection.validateMainThread();
        //float[] data = {value.mX, value.mY, value.mZ};
        nativeAddKeyProperty(mNativeAnimation, mAnimationType, keyTime, value);
    }

    /**
     * finalize
     * @see com.github.sviengine.animation.SVIAnimation#finalize()
     */
    protected void finalize() throws Throwable {
    	super.finalize();
    	deleteNativeAnimationHandle();
    }

    /** SVIKeyFrameAnimation native interface.*/
    static {
    	System.loadLibrary(SVIEngineDesc.mName);
    }

    private static native int nativeCreateSVIKeyFrameAnimation(int type, int nativeGLSurface);
    private static native void nativeAddKeyProperty(int aniHandle, int type, float keyTime, float[] value);
}


text:
var ss = require('../')
  , should = require('should');

var push = ss.socket('push')
  , pull = ss.socket('pull');

// basic 1-1 push/pull bind pull

var n = 0
  , closed;

pull.bind(4000);
push.connect(4000);
push.send('foo');
push.send('bar');

pull.on('message', function(msg){
  msg.should.be.an.instanceof(Buffer);
  msg.should.have.length(3);
  msg = msg.toString();
  switch (n++) {
    case 0:
      msg.should.equal('foo');
      break;
    case 1:
      msg.should.equal('bar');
      break;
    case 2:
      msg.should.equal('baz');
      pull.close();
      push.close();
      closed = true;
      break;
  }
});

push.on('connect', function(){
  push.send('baz');
});

process.on('exit', function(){
  should.equal(true, closed);
});


text:
@extends('layouts.inner')

@section('title', 'Ubah Stasiun')
@section('head', 'Ubah Stasiun')
@section('description', '* = Wajib diisi')

@section('breadcrumbs')

Stasiun

id) }}">{{ $station->id }}

Ubah

@endsection

@section('content')
<form id="form-station-edit" method="post" action="{{ url('api/station') }}" class="form-horizontal">
	{!! csrf_field() !!}
	<input type="hidden" name="id" value="{{ $station->id }}">

Profil Stasiun

						Nama Stasiun

							<input type="text" class="form-control" name="name" placeholder="{{ $station->name }}">

						Nomor Telepon

							<input type="text" class="form-control" name="phone" placeholder="{{ $station->phone }}">

						Tipe Stasiun

							<select name="type" class="form-control">
								<option value="SPPBE" @if($station->type === 'SPPBE') selected @endif>SPPBE</option>
								<option value="SPPEK" @if($station->type === 'SPPEK') selected @endif>SPPEK</option>
								<option value="SPBU" @if($station->type === 'SPBU') selected @endif>SPBU</option>
							</select>

Alamat

						Provinsi

							<select name="address_province" class="form-control">
								<option value="" data-id="null" disabled selected>Pilih Provinsi...</option>
							</select>

Data Sebelumnya: {{ $station->address->province }}

						Kabupaten/Kota

							<select name="address_regency" class="form-control" disabled>
								<option value="" data-id="null" disabled selected>Pilih Kabupaten/Kota...</option>
							</select>

Data Sebelumnya: {{ $station->address->regency }}

						Kecamatan

							<select name="address_district" class="form-control" disabled>
								<option value="" data-id="null" disabled selected>Pilih Kecamatan...</option>
							</select>

Data Sebelumnya: {{ $station->address->district }}

						Kelurahan/Desa

							<select name="address_subdistrict" class="form-control" disabled>
								<option value="" disabled selected>Pilih Kelurahan/Desa...</option>
							</select>

Data Sebelumnya: {{ $station->address->subdistrict }}

						Alamat Lengkap

							<textarea class="form-control" name="address_detail" placeholder="{{ $station->address->detail }}"></textarea>

Tuliskan nama jalan, nama gang, nomor pada jalan, dan RT/RW bila perlu.

						Kode Pos

							<input type="text" class="form-control" name="address_postal_code" placeholder="{{ $station->address->postal_code }}">

Lokasi Pada Peta

Klik pada peta untuk menentukan lokasi.

						Lokasi

							<input type="text" class="form-control" name="location" placeholder="{{ implode(',', $station->location) }}" readonly>

Klik ulang pada peta untuk mengubah lokasi.

			<button type="submit" class="btn btn-primary"> Ubah Data</button>
			Kembali

</form>
@endsection

@section('scripts')

@endsection


text:
class FontMountainsOfChristmas < Cask
  url 'https://github.com/w0ng/googlefontdirectory/trunk/fonts/mountainsofchristmas',
      :using      => :svn,
      :revision   => '50',
      :trust_cert => true
  homepage 'http://www.google.com/fonts/specimen/Mountains%20of%20Christmas'
  version '1.002'
  sha256 :no_check
  font 'MountainsofChristmas-Bold.ttf'
  font 'MountainsofChristmas-Regular.ttf'
end


text:
namespace {

ui::EventType WebTouchPointStateToEventType(
    blink::WebTouchPoint::State state) {
  switch (state) {
    case blink::WebTouchPoint::StateReleased:
      return ui::ET_TOUCH_RELEASED;

    case blink::WebTouchPoint::StatePressed:
      return ui::ET_TOUCH_PRESSED;

    case blink::WebTouchPoint::StateMoved:
      return ui::ET_TOUCH_MOVED;

    case blink::WebTouchPoint::StateCancelled:
      return ui::ET_TOUCH_CANCELLED;

    default:
      return ui::ET_UNKNOWN;
  }
}

}  // namespace

namespace content {

bool MakeUITouchEventsFromWebTouchEvents(
    const TouchEventWithLatencyInfo& touch_with_latency,
    ScopedVector<ui::TouchEvent>* list,
    TouchEventCoordinateSystem coordinate_system) {
  const blink::WebTouchEvent& touch = touch_with_latency.event;
  ui::EventType type = ui::ET_UNKNOWN;
  switch (touch.type) {
    case blink::WebInputEvent::TouchStart:
      type = ui::ET_TOUCH_PRESSED;
      break;
    case blink::WebInputEvent::TouchEnd:
      type = ui::ET_TOUCH_RELEASED;
      break;
    case blink::WebInputEvent::TouchMove:
      type = ui::ET_TOUCH_MOVED;
      break;
    case blink::WebInputEvent::TouchCancel:
      type = ui::ET_TOUCH_CANCELLED;
      break;
    default:
      NOTREACHED();
      return false;
  }

  int flags = WebEventModifiersToEventFlags(touch.modifiers);
  base::TimeDelta timestamp = base::TimeDelta::FromMicroseconds(
      static_cast<int64>(touch.timeStampSeconds * 1000000));
  for (unsigned i = 0; i < touch.touchesLength; ++i) {
    const blink::WebTouchPoint& point = touch.touches[i];
    if (WebTouchPointStateToEventType(point.state) != type)
      continue;
    // ui events start in the co-ordinate space of the EventDispatcher.
    gfx::PointF location;
    if (coordinate_system == LOCAL_COORDINATES)
      location = point.position;
    else
      location = point.screenPosition;
    ui::TouchEvent* uievent = new ui::TouchEvent(type,
          location,
          flags,
          point.id,
          timestamp,
          point.radiusX,
          point.radiusY,
          point.rotationAngle,
          point.force);
    uievent->set_latency(touch_with_latency.latency);
    list->push_back(uievent);
  }
  return true;
}

blink::WebGestureEvent MakeWebGestureEventFromUIEvent(
    const ui::GestureEvent& event) {
  return CreateWebGestureEvent(event.details(),
                               event.time_stamp(),
                               event.location_f(),
                               event.root_location_f(),
                               event.flags());
}

}  // namespace content


text:
Imports System.Runtime.InteropServices
Imports Word06AddinVB4

<ComVisible(True), InterfaceType(ComInterfaceType.InterfaceIsDual), Guid("CD610128-44B7-4AFD-AF34-F8AD9FF1BD8E")>
Public Interface ITimeComponent

    <DispId(1)>
    Function GetTime() As String

End Interface

Public Class TimeComponent
    Implements ITimeComponent

    Public Function GetTime() As String Implements ITimeComponent.GetTime
        Return DateTime.Now.ToString()
    End Function

End Class


text:
import React from 'react';
import axios from 'axios';
import _ from 'lodash';
import { Button, Menu, Container } from 'semantic-ui-react';
import PropTypes from 'prop-types';
import DisplayPost from '../../common/post/DisplayPost';
import Auth from '../../auth/modules/Auth';
import User from '../../auth/modules/User';
import browserHistory from '../../history';

const fetchPostById = postId =>
  (axios.get(`/api/user/posts/${postId}`, {
    headers: {
      Authorization: `bearer ${Auth.getToken()}`,
    },
  })
    .then((resp) => {
      console.log('response is ', resp);
      const post = resp.data;
      post.stipend = `${post.stipend}`;
      post.duration = `${post.duration}`;
      return post;
    })
    .catch(console.error));

class PostView extends React.Component {
  constructor(props) {
    super(props);
    this.state = { post: null };
    this.handleApply = () => {
      const userId = User.getId();
      axios.post(`/api/user/posts/${this.state.post._id}/addStudent`, { userId }, {
        headers: {
          Authorization: `bearer ${Auth.getToken()}`,
        },
      })
        .then(() => {
          this.props.history.goBack();
        })
        .catch(console.error);
    };
  }

  componentWillMount() {
    fetchPostById(this.props.match.params.id)
      .then(post => this.setState({ ...this.state, post }));
    // console.log('hiii', this.state);
  }

  render() {
    if (!this.state.post) {
      return
Loading...
;
    }
    return (
      <Container text className="main" textAlign="justified">

          <DisplayPost
            internshipDetails={this.state.post}
          />
          <Menu>
            <Menu.Menu position="right">
              <Menu.Item>
                <Button primary floated="right" onClick={this.handleApply} >Apply</Button>
              </Menu.Item>
            </Menu.Menu>
          </Menu>

      </Container>
    );
  }
}
/* const SubmitPostPage = () => (
  <SubmitPostForm />
); */

PostView.propTypes = {
  match: PropTypes.shape({
    params: PropTypes.shape({
      id: PropTypes.string.isRequired,
    }).isRequired,
  }).isRequired,
  history: PropTypes.shape({
    goBack: PropTypes.func.isRequired,
    replace: PropTypes.func.isRequired,
  }).isRequired,
};
export default PostView;

/* SubmitPostPage.propTypes = {
  history: PropTypes.shape({
    goBack: PropTypes.func.isRequired,
    replace: PropTypes.func.isRequired,
  }).isRequired,
};
*/


text:
<?php $id = uniqid('qe_assoc_table') ?>

<div id="<?= $id ?>" class="assoc-table question-editor-extension">

                Добавить пару

<input type="text" class="form-control">

<input type="text" class="form-control">

<input type="text" class="form-control" placeholder="Комментарий">

Удалить


text:
using System;
using System.Globalization;
using Microsoft.Xna.Framework;
using Newtonsoft.Json;

namespace MonoGame.Extended.Serialization
{
    public class Vector2JsonConverter : JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var vector2 = (Vector2) value;
            writer.WriteValue($"{vector2.X} {vector2.Y}");
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
            JsonSerializer serializer)
        {
            var value = (string) reader.Value;
            var fields = value.Split(' ');
            var x = float.Parse(fields[0], CultureInfo.InvariantCulture.NumberFormat);
            var y = float.Parse(fields[1], CultureInfo.InvariantCulture.NumberFormat);
            return new Vector2(x, y);
        }

        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(Vector2);
        }
    }
}


text:
package org.jboss.resteasy.plugins.server.netty.cdi;

import org.jboss.resteasy.core.SynchronousDispatcher;
import org.jboss.resteasy.plugins.server.netty.NettyJaxrsServer;
import org.jboss.resteasy.plugins.server.netty.RequestDispatcher;

import javax.enterprise.context.Dependent;

/**
 * A CDI aware Netty Jaxrs Server.
 */
@Dependent
public class CdiNettyJaxrsServer extends NettyJaxrsServer {
    @Override
    protected RequestDispatcher createRequestDispatcher() {
        return new CdiRequestDispatcher((SynchronousDispatcher)super.deployment.getDispatcher(),
                                super.deployment.getProviderFactory(), super.domain);
    }
}


text:
// This file is generated by FBC.

#include "SimpleLiftController.h"
#include <string.h>
#include <stdio.h>

/* Function block initialization function */
void SimpleLiftControllerinit(SimpleLiftController* me)
{
    me->_input.events = 0;
    me->_output.events = 0;
    UnitControlinit(&me->UnitControl);
    RequestResolverinit(&me->RequestResolver);
}

/* Function block execution function */
void SimpleLiftControllerrun(SimpleLiftController* me)
{
    me->UnitControl._RequestValue = me->RequestResolver._requestValue;
    me->UnitControl._FloorSensorValue = me->_FloorSensorValue;
    me->UnitControl._input.event.Request = me->RequestResolver._output.event.request;
    me->UnitControl._input.event.TimerExpired = me->_input.event.TimerExpired;
    me->UnitControl._input.event.FloorSensor = me->_input.event.FloorSensor;
    {
        int i;
        for (i = 0; i < 4; i++) {
            me->RequestResolver._UpCallValue[i] = me->_UpCallValue[i];
        }
    }
    {
        int i;
        for (i = 0; i < 4; i++) {
            me->RequestResolver._CabinCallValue[i] = me->_CabinCallValue[i];
        }
    }
    me->RequestResolver._input.event.UpCall = me->_input.event.UpCall;
    me->RequestResolver._input.event.CabinCall = me->_input.event.CabinCall;
    {
        int i;
        for (i = 0; i < 4; i++) {
            me->RequestResolver._DownCallValue[i] = me->_DownCallValue[i];
        }
    }
    me->RequestResolver._input.event.FloorSensor = me->_input.event.FloorSensor;
    me->RequestResolver._input.event.MotorDirectionIdle = me->UnitControl._output.event.MotorDirectionIdle;
    me->RequestResolver._FloorSensorValue = me->_FloorSensorValue;
    me->RequestResolver._input.event.StoppedAtFloor = me->UnitControl._output.event.StoppedAtFloor;
    me->RequestResolver._input.event.DownCall = me->_input.event.DownCall;
    me->RequestResolver._StoppedAtFloorValue = me->UnitControl._StoppedAtFloorValue;
    me->RequestResolver._input.event.MotorDirectionUp = me->UnitControl._output.event.MotorDirectionUp;
    me->RequestResolver._input.event.MotorDirectionDown = me->UnitControl._output.event.MotorDirectionDown;

    UnitControlrun(&me->UnitControl);
    RequestResolverrun(&me->RequestResolver);

    me->_output.event.PendingDownCall = me->RequestResolver._output.event.PendingDownCall;
    {
        int i;
        for (i = 0; i < 4; i++) {
            me->_PendingUpCallValue[i] = me->RequestResolver._PendingUpCallValue[i];
        }
    }
    me->_output.event.MotorDirectionIdle = me->UnitControl._output.event.MotorDirectionIdle;
    me->_output.event.DoorClose = me->UnitControl._output.event.DoorClose;
    {
        int i;
        for (i = 0; i < 4; i++) {
            me->_PendingReqValue[i] = me->RequestResolver._PendingReqValue[i];
        }
    }
    me->_output.event.StoppedAtFloor = me->UnitControl._output.event.StoppedAtFloor;
    me->_output.event.PendingCabinCall = me->RequestResolver._output.event.PendingCabinCall;
    me->_StoppedAtFloorValue = me->UnitControl._StoppedAtFloorValue;
    me->_output.event.DoorOpen = me->UnitControl._output.event.DoorOpen;
    me->_output.event.MotorDirectionUp = me->UnitControl._output.event.MotorDirectionUp;
    {
        int i;
        for (i = 0; i < 4; i++) {
            me->_PendingCabinCallValue[i] = me->RequestResolver._PendingCabinCallValue[i];
        }
    }
    me->_CurrentPriorityValue = me->RequestResolver._CurrentPriorityValue;
    me->_output.event.PendingReq = me->RequestResolver._output.event.PendingReq;
    me->_output.event.MotorDirectionDown = me->UnitControl._output.event.MotorDirectionDown;
    {
        int i;
        for (i = 0; i < 4; i++) {
            me->_PendingDownCallValue[i] = me->RequestResolver._PendingDownCallValue[i];
        }
    }
    {
        int i;
        for (i = 0; i < 4; i++) {
            me->_PendingCallValue[i] = me->RequestResolver._PendingCallValue[i];
        }
    }
    me->_output.event.CurrentPriority = me->RequestResolver._output.event.CurrentPriority;
    me->_output.event.PendingCall = me->RequestResolver._output.event.PendingCall;
    me->_output.event.StartTimer = me->UnitControl._output.event.StartTimer;
    me->_output.event.PendingUpCall = me->RequestResolver._output.event.PendingUpCall;
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.7"/>
<title>App Engine Python SDK: google.appengine._internal.django.core.files.locks Namespace Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="common.css" rel="stylesheet" type="text/css"/>

App Engine Python SDK
    v1.6.9 rev.445

The Python runtime is available as an experimental Preview feature.

google

appengine

_internal

django

core

files

locks

Functions |
Variables

google.appengine._internal.django.core.files.locks Namespace Reference

Functions

def 	fd

def 	lock

def 	unlock

Variables

tuple 	__all__ = ('LOCK_EX','LOCK_SH','LOCK_NB','lock','unlock')

 	system_type = None

 	LOCK_EX = win32con.LOCKFILE_EXCLUSIVE_LOCK

int 	LOCK_SH = 0

 	LOCK_NB = win32con.LOCKFILE_FAIL_IMMEDIATELY

tuple 	__overlapped = pywintypes.OVERLAPPED()

Detailed Description

Portable file locking utilities.

Based partially on example by Jonathan Feignberg <jdf@pobox.com> in the Python
Cookbook, licensed under the Python Software License.

    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65203

Example Usage::

    >>> from google.appengine._internal.django.core.files import locks
    >>> f = open('./file', 'wb')
    >>> locks.lock(f, locks.LOCK_EX)
    >>> f.write('Django')
    >>> f.close()

Function Documentation

          def google.appengine._internal.django.core.files.locks.fd
          (

          f	)

Get a filedescriptor from something which could be a file or an fd.

<address class="footer">
    Maintained by tzmartin
</address>


text:
namespace glkernel
{

namespace scale
{

template <typename T, typename std::enable_if<std::is_floating_point<T>::value>::type * = nullptr>
void range(tkernel<T> & kernel, T rangeToLower, T rangeToUpper, T rangeFromLower = 0, T rangeFromUpper = 1);

template <typename V, typename std::enable_if<std::is_floating_point<typename V::value_type>::value>::type * = nullptr>
void range(tkernel<V> & kernel, typename V::value_type rangeToLower, typename V::value_type rangeToUpper, typename V::value_type rangeFromLower = 0, typename V::value_type rangeFromUpper = 1);

} // namespace scale

} // namespace glkernel

#include <glkernel/scale.hpp>


text:
package com.stephenmac.incorporate.commands;

import java.util.Set;

import com.stephenmac.incorporate.ArgParser;
import com.stephenmac.incorporate.Executor;
import com.stephenmac.incorporate.Permission;

public class ListApplicantsCommand extends Command {

	public ListApplicantsCommand(ArgParser p, Executor cmdExec) {
		super(p, cmdExec);
		perms.add(Permission.HIRE);
	}

	@Override
	public String execute() {
		StringBuilder r = new StringBuilder();
		Set<String> applicants = corp.getApplicantSet();

		r.append("Applicants (" + Integer.toString(applicants.size()) + "):\n");
		for (String s : applicants){
			r.append("* " + s + "\n");
		}
		return r.toString();
	}

}


text:
package com.github.dakusui.crest.core;

import com.github.dakusui.crest.utils.InternalUtils;
import com.github.dakusui.crest.utils.ReflectionUtils;
import com.github.dakusui.crest.utils.ReflectiveFunctions;

import java.util.Arrays;
import java.util.function.Function;

import static com.github.dakusui.crest.utils.ReflectiveFunctions.THIS;
import static java.util.Objects.requireNonNull;

/**
 * An interface of a builder for a function that transforms a "target object" into
 * another value by calling a chain of methods on it and a value from a previous call.
 *

 * That is, you can build a function that does following if a StringBuilder is given as
 * its input,
 * {@code
 * (StringBuilder b) -> b.append("hello").append(1).append("world").append("everyone").toString()
 * }
 * By following code,
 * {@code
 * Function func = Call.create("append", "hello")
 * .andThen("append", 1)
 * .andThen("append", "everyone")
 * .andThen("toString")
 * .$()
 * }
 *

 * The benefit of using this class is to be able to print what you are going to do
 * in a pretty format in "Crest" library's output. If you call {@code toString}
 * method on the {@code func} object, you will get,
 *

 * {@code
 * "@append[hello]->@append[1]->@append[everyone]->@toString[]"
 * }
 *

 * , which is far more understandable than a string that you will get for a function
 * built in a normal way mentioned above such as
 *
 *

 *   "com.github.dakusui.crest.ut.CrestTest$CallMechanismTest$$Lambda$9/1556956098@4aa8f0b4"
 *

 */
public interface Call {

  /**
   * Add a method call of a method specified by {@code methodName} and {@code args}
   * to this builder on the current target object.
   *

   * If you need to invoke a method on other than the current target object,
   * you need to use {@code andThenOn} method.
   * n
   *
   * @param methodName a name of method to be invoked.
   * @param args       Arguments with which the method is invoked.
   * @return This object.
   */
  default Call andThen(String methodName, Object... args) {
    return andThenOn(THIS, methodName, args);
  }

  /**
   * Adds a call of a method specified by {@code object}, {@code methodName} and
   * {@code args}.
   *
   * @param object     An object on which the method should be invoked.
   * @param methodName A name of the method to be invoked
   * @param args       Arguments with which the method is invoked.
   * @return This object.
   */
  Call andThenOn(Object object, String methodName, Object... args);

  /**
   * Builds a function.
   *
   * @param <T> Type of the result of the function to be built.
   * @return The function.
   */
  <T> Function<Object, T> build();

  /**
   * A synonym of {@code build} method.
   *
   * @param <T> The type of the returned value.
   * @return A built function.
   */
  default <T> Function<Object, T> $() {
    return build();
  }

  /**
   * A synonym of {@code Call.create(Functions.THIS, methodName, args)}.
   *
   * @param methodName A name of the method to be invoked.
   * @param args       Arguements with which the method is invoked.
   * @return The result of the invocation.
   * @see Call#createOn(Object, String, Object...)
   */
  static Call create(String methodName, Object... args) {
    return createOn(THIS, methodName, args);
  }

  /**
   * Creates a {@code Call} object which invokes a method specified by a {@code methodName},
   * {@code args}, and {@code object}.
   *

   * If the {@code object} is {@code null}, an exception will be thrown.
   * If the {@code object} is {@code Functions#THIS}, the method is searched from
   * the target object.
   * If the {@code object} is an instance of {@code java.lang.Class}, the method is
   * searched from the class described by the {@code object}.
   * Otherwise, the method will be searched from the class of the {@code object}
   * itself.
   *

   * The method is searched by a {@code InternalUtils.findMethod}.
   *
   * @param object     An object on which the method is invoked
   * @param methodName A name to specify a method to be invoked
   * @param args       Argument values with which the method is invoked
   * @return A result of the invocation.
   * @see ReflectiveFunctions#THIS
   * @see InternalUtils#findMethod(Class, String, Object[])
   */
  static Call createOn(Object object, String methodName, Object... args) {
    return new Call.Impl(null, object, methodName, args);
  }

  interface Arg<T> {
    Class<T> type();

    T value();

    static <T> Arg<T> of(Class<T> type, T value) {
      return new Arg<T>() {
        @Override
        public Class<T> type() {
          return type;
        }

        @Override
        public T value() {
          return value;
        }

        @Override
        public String toString() {
          return String.format(
              "%s %s",
              type.getSimpleName(),
              value == null
                  ? null
                  : value.getClass().isArray()
                  ? Arrays.toString((Object[]) value)
                  : value);
        }
      };
    }
  }

  class Impl implements Call {
    private final String   methodName;
    private final Object[] args;
    private final Call     parent;
    private final Object   object;

    /**
     * Creates a new {@code Call.Impl} object.
     *
     * @param parent     This can be {@code null} when a head of chain is created.
     * @param object     An object on which a method specified by {@code methodName}
     *                   and {@code args} is invoked.
     * @param methodName A name of a method to be invoked.
     * @param args       Arguments of a method to be invoked.
     */
    Impl(Call parent, Object object, String methodName, Object... args) {
      this.parent = parent;
      this.object = requireNonNull(object);
      this.methodName = requireNonNull(methodName);
      this.args = args;
    }

    @Override
    public Call andThenOn(Object object, String methodName, Object... args) {
      return new Impl(this, object, methodName, args);
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> Function<Object, T> build() {
      return this.parent == null
          ? toFunction()
          : this.parent.build().andThen(toFunction());
    }

    @SuppressWarnings({ "unchecked", "RedundantCast", "rawtypes" })
    private Function toFunction() {
      return ChainedFunction.create(
          this.object instanceof Class
              ? (Function) ReflectionUtils.invokeStatic((Class<?>) this.object, methodName, args)
              : (Function) ReflectionUtils.invokeOn(this.object, methodName, args)
      );
    }
  }
}


text:
#pragma once

#include "testInterface.h"
#include "configurer.h"

class PwmTest
		: public QObject
		, public TestInterface
{
	Q_OBJECT
	Q_INTERFACES(TestInterface)
	Q_PLUGIN_METADATA(IID "com.trikset.teststand.pwm")
public:
	TestInterface::Result run(trikControl::BrickInterface &mBrick, QStringList &mLog);

private:
	trikControl::BrickInterface *mBrick;
	QStringList *mLog;
	QList<Configurer::Stage> mStages;

	QList<Configurer::Value> mValues;
	TestInterface::Result result;

	void performStage(Configurer::Stage const &stage);
};


text:
set -ex

# Run the Designate DevStack exercises
$BASE/new/devstack/exercises/designate.sh


text:
//$Id$
package org.hibernate.test.annotations.inheritance.joined;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

/**
 * @author Emmanuel Bernard
 */
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "TBLASSET")
public class Asset {
	private Integer id;

	private Parent parent = null;

	@Id @GeneratedValue public Integer getId() {
		return id;
	}

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

	@ManyToOne(targetEntity = Parent.class)
	@JoinColumn(name = "PARENTID")
	public Parent getParent() {
		return parent;
	}

	public void setParent(Parent parent) {
		this.parent = parent;
	}
}