text:
'use strict';

require('mocha');
const assert = require('assert');
const repoName = require('./');

describe('git-repo-name', () => {
  describe('async', () => {
    it('should return a promise', async() => {
      assert.equal(await repoName(), 'git-repo-name');
    });

    it('should take a callback', cb => {
      repoName((err, res) => {
        if (err) return cb(err);
        assert.equal(res, 'git-repo-name');
        cb();
      });
    });

    it('should take cwd as a string', cb => {
      repoName(process.cwd(), (err, res) => {
        if (err) return cb(err);
        assert.equal(repoName.sync(), 'git-repo-name');
        cb();
      });
    });

    it('should error when .git folder does not exist', cb => {
      repoName('foo', (err, res) => {
        assert.equal(err.message, 'cannot find ".git/config"');
        cb();
      });
    });
  });

  describe('sync', () => {
    it('should return the name from git config:', () => {
      assert.equal(repoName.sync(), 'git-repo-name');
    });

    it('should take cwd as a string', () => {
      assert.equal(repoName.sync('.'), 'git-repo-name');
    });
  });
});


text:
$(document).ready(function () {

    // This basically works by adding an element to the DOM to display
    // the label and then replacing the html of the .hover_info
    // element with the appropriate data-count attribute from the
    // .bin_inner class on mouseover.

    // get the counts from all of the data-count attributes on
    // .bin_inner and store them in a data array
    var data = [];
    d3.selectAll(".flux_timeseries_container .flux_timeseries .timeseries")
	.each(function (d, i){

	    var default_message = "";

	    // add the label box for each .timeseries
	    var hover_info = d3.select(this).insert("p", ":first-child")
	    	.attr("class", "hover_info")
		.html(default_message);

	    // display a label on mouseover for every .bin_outer
	    d3.select(this).selectAll(".bin_outer").each(function (e, j) {
		d3.select(this).on("mouseover", function (d, i){
		    d3.select(this).select(".bin_inner").datum(function () {
			hover_info.html(this.dataset["count"]);
		    });
		}).on("mouseout", function (d, i){
		    d3.select(this).select(".bin_inner").datum(function () {
			hover_info.html(default_message);
		    });
		});
	    });
	});

});

redpajama_set_name: RedPajamaGithub


text:
export class X01Settings {
  public legsToWin: number = 3;
  public setsToWin: number = 2;
  public isDoubleOut: boolean = true;
  public initialScore: number = 501;
}


text:
if RUBY_PLATFORM =~ /java/
  require 'abstract_unit'
  require 'active_support/xml_mini'
  require 'active_support/core_ext/hash/conversions'

  class JDOMEngineTest < ActiveSupport::TestCase
    include ActiveSupport

    FILES_DIR = File.dirname(__FILE__) + '/../fixtures/xml'

    def setup
      @default_backend = XmlMini.backend
      XmlMini.backend = 'JDOM'
    end

    def teardown
      XmlMini.backend = @default_backend
    end

    def test_file_from_xml
       hash = Hash.from_xml(<<-eoxml)
         <blog>
           <logo type="file" name="logo.png" content_type="image/png">
           </logo>
         </blog>
       eoxml
       assert hash.has_key?('blog')
       assert hash['blog'].has_key?('logo')

       file = hash['blog']['logo']
       assert_equal 'logo.png', file.original_filename
       assert_equal 'image/png', file.content_type
    end

    def test_not_allowed_to_expand_entities_to_files
      attack_xml = <<-EOT
      <!DOCTYPE member [
        <!ENTITY a SYSTEM "file://#{FILES_DIR}/jdom_include.txt">
      ]>
      <member>x&a;</member>
      EOT
      assert_equal 'x', Hash.from_xml(attack_xml)["member"]
    end

    def test_not_allowed_to_expand_parameter_entities_to_files
      attack_xml = <<-EOT
      <!DOCTYPE member [
        <!ENTITY % b SYSTEM "file://#{FILES_DIR}/jdom_entities.txt">
        %b;
      ]>
      <member>x&a;</member>
      EOT
      assert_raise Java::OrgXmlSax::SAXParseException do
        assert_equal 'x', Hash.from_xml(attack_xml)["member"]
      end
    end

    def test_not_allowed_to_load_external_doctypes
      attack_xml = <<-EOT
      <!DOCTYPE member SYSTEM "file://#{FILES_DIR}/jdom_doctype.dtd">
      <member>x&a;</member>
      EOT
      assert_equal 'x', Hash.from_xml(attack_xml)["member"]
    end

    def test_exception_thrown_on_expansion_attack
      assert_raise Java::OrgXmlSax::SAXParseException do
        attack_xml = <<-EOT
      <!DOCTYPE member [
        <!ENTITY a "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;">
        <!ENTITY b "&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;">
        <!ENTITY c "&d;&d;&d;&d;&d;&d;&d;&d;&d;&d;">
        <!ENTITY d "&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;">
        <!ENTITY e "&f;&f;&f;&f;&f;&f;&f;&f;&f;&f;">
        <!ENTITY f "&g;&g;&g;&g;&g;&g;&g;&g;&g;&g;">
        <!ENTITY g "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx">
      ]>
      <member>
      &a;
      </member>
        EOT
        Hash.from_xml(attack_xml)
      end
    end

    def test_setting_JDOM_as_backend
      XmlMini.backend = 'JDOM'
      assert_equal XmlMini_JDOM, XmlMini.backend
    end

    def test_blank_returns_empty_hash
      assert_equal({}, XmlMini.parse(nil))
      assert_equal({}, XmlMini.parse(''))
    end

    def test_array_type_makes_an_array
      assert_equal_rexml(<<-eoxml)
      <blog>
        <posts type="array">
          <post>a post</post>
          <post>another post</post>
        </posts>
      </blog>
      eoxml
    end

    def test_one_node_document_as_hash
      assert_equal_rexml(<<-eoxml)
    <products/>
      eoxml
    end

    def test_one_node_with_attributes_document_as_hash
      assert_equal_rexml(<<-eoxml)
    <products foo="bar"/>
      eoxml
    end

    def test_products_node_with_book_node_as_hash
      assert_equal_rexml(<<-eoxml)
    <products>
      <book name="awesome" id="12345" />
    </products>
      eoxml
    end

    def test_products_node_with_two_book_nodes_as_hash
      assert_equal_rexml(<<-eoxml)
    <products>
      <book name="awesome" id="12345" />
      <book name="america" id="67890" />
    </products>
      eoxml
    end

    def test_single_node_with_content_as_hash
      assert_equal_rexml(<<-eoxml)
      <products>
        hello world
      </products>
      eoxml
    end

    def test_children_with_children
      assert_equal_rexml(<<-eoxml)
    <root>
      <products>
        <book name="america" id="67890" />
      </products>
    </root>
      eoxml
    end

    def test_children_with_text
      assert_equal_rexml(<<-eoxml)
    <root>
      <products>
        hello everyone
      </products>
    </root>
      eoxml
    end

    def test_children_with_non_adjacent_text
      assert_equal_rexml(<<-eoxml)
    <root>
      good
      <products>
        hello everyone
      </products>
      morning
    </root>
      eoxml
    end

    private
      def assert_equal_rexml(xml)
        parsed_xml = XmlMini.parse(xml)
        hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) }
        assert_equal(hash, parsed_xml)
      end
  end

else
  # don't run these test because we aren't running in JRuby
end


text:
<?php

declare(strict_types=1);

namespace Doctrine\Tests\ORM\Mapping;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Id\SequenceGenerator as IdSequenceGenerator;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Mapping\ClassMetadataFactory;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\DiscriminatorColumn;
use Doctrine\ORM\Mapping\DiscriminatorMap;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\GeneratedValue;
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\Index;
use Doctrine\ORM\Mapping\InheritanceType;
use Doctrine\ORM\Mapping\JoinColumn;
use Doctrine\ORM\Mapping\MappedSuperclass;
use Doctrine\ORM\Mapping\MappingException;
use Doctrine\ORM\Mapping\OneToOne;
use Doctrine\ORM\Mapping\SequenceGenerator;
use Doctrine\ORM\Mapping\Table;
use Doctrine\ORM\Mapping\UniqueConstraint;
use Doctrine\Persistence\Mapping\RuntimeReflectionService;
use Doctrine\Tests\Models\DDC869\DDC869ChequePayment;
use Doctrine\Tests\Models\DDC869\DDC869CreditCardPayment;
use Doctrine\Tests\Models\DDC869\DDC869Payment;
use Doctrine\Tests\Models\DDC869\DDC869PaymentRepository;
use Doctrine\Tests\OrmTestCase;

use function assert;
use function serialize;
use function unserialize;

class BasicInheritanceMappingTest extends OrmTestCase
{
    /** @var ClassMetadataFactory */
    private $cmf;

    protected function setUp(): void
    {
        $this->cmf = new ClassMetadataFactory();

        $this->cmf->setEntityManager($this->getTestEntityManager());
    }

    public function testGetMetadataForTransientClassThrowsException(): void
    {
        $this->expectException(MappingException::class);

        $this->cmf->getMetadataFor(TransientBaseClass::class);
    }

    public function testGetMetadataForSubclassWithTransientBaseClass(): void
    {
        $class = $this->cmf->getMetadataFor(EntitySubClass::class);

        self::assertEmpty($class->subClasses);
        self::assertEmpty($class->parentClasses);
        self::assertArrayHasKey('id', $class->fieldMappings);
        self::assertArrayHasKey('name', $class->fieldMappings);
    }

    public function testGetMetadataForSubclassWithMappedSuperclass(): void
    {
        $class = $this->cmf->getMetadataFor(EntitySubClass2::class);

        self::assertEmpty($class->subClasses);
        self::assertEmpty($class->parentClasses);

        self::assertArrayHasKey('mapped1', $class->fieldMappings);
        self::assertArrayHasKey('mapped2', $class->fieldMappings);
        self::assertArrayHasKey('id', $class->fieldMappings);
        self::assertArrayHasKey('name', $class->fieldMappings);

        self::assertArrayNotHasKey('inherited', $class->fieldMappings['mapped1']);
        self::assertArrayNotHasKey('inherited', $class->fieldMappings['mapped2']);
        self::assertArrayNotHasKey('transient', $class->fieldMappings);

        self::assertArrayHasKey('mappedRelated1', $class->associationMappings);
    }

    /**
     * @group DDC-869
     */
    public function testGetMetadataForSubclassWithMappedSuperclassWithRepository(): void
    {
        $class = $this->cmf->getMetadataFor(DDC869CreditCardPayment::class);

        self::assertArrayHasKey('id', $class->fieldMappings);
        self::assertArrayHasKey('value', $class->fieldMappings);
        self::assertArrayHasKey('creditCardNumber', $class->fieldMappings);
        self::assertEquals($class->customRepositoryClassName, DDC869PaymentRepository::class);

        $class = $this->cmf->getMetadataFor(DDC869ChequePayment::class);

        self::assertArrayHasKey('id', $class->fieldMappings);
        self::assertArrayHasKey('value', $class->fieldMappings);
        self::assertArrayHasKey('serialNumber', $class->fieldMappings);
        self::assertEquals($class->customRepositoryClassName, DDC869PaymentRepository::class);

        // override repositoryClass
        $class = $this->cmf->getMetadataFor(SubclassWithRepository::class);

        self::assertArrayHasKey('id', $class->fieldMappings);
        self::assertArrayHasKey('value', $class->fieldMappings);
        self::assertEquals($class->customRepositoryClassName, EntityRepository::class);
    }

    /**
     * @group DDC-388
     */
    public function testSerializationWithPrivateFieldsFromMappedSuperclass(): void
    {
        $class = $this->cmf->getMetadataFor(EntitySubClass2::class);

        $class2 = unserialize(serialize($class));
        $class2->wakeupReflection(new RuntimeReflectionService());

        self::assertArrayHasKey('mapped1', $class2->reflFields);
        self::assertArrayHasKey('mapped2', $class2->reflFields);
        self::assertArrayHasKey('mappedRelated1', $class2->reflFields);
    }

    /**
     * @group DDC-1203
     */
    public function testUnmappedSuperclassInHierarchy(): void
    {
        $class = $this->cmf->getMetadataFor(HierarchyD::class);

        self::assertArrayHasKey('id', $class->fieldMappings);
        self::assertArrayHasKey('a', $class->fieldMappings);
        self::assertArrayHasKey('d', $class->fieldMappings);
    }

    /**
     * @group DDC-1204
     */
    public function testUnmappedEntityInHierarchy(): void
    {
        $this->expectException(MappingException::class);
        $this->expectExceptionMessage(
            'Entity \'Doctrine\Tests\ORM\Mapping\HierarchyBEntity\' has to be part of the discriminator map'
            . ' of \'Doctrine\Tests\ORM\Mapping\HierarchyBase\' to be properly mapped in the inheritance hierarchy.'
            . ' Alternatively you can make \'Doctrine\Tests\ORM\Mapping\HierarchyBEntity\' an abstract class to'
            . ' avoid this exception from occurring.'
        );

        $this->cmf->getMetadataFor(HierarchyE::class);
    }

    /**
     * @group DDC-1204
     * @group DDC-1203
     */
    public function testMappedSuperclassWithId(): void
    {
        $class = $this->cmf->getMetadataFor(SuperclassEntity::class);

        self::assertArrayHasKey('id', $class->fieldMappings);
    }

    /**
     * @group DDC-1156
     * @group DDC-1218
     */
    public function testGeneratedValueFromMappedSuperclass(): void
    {
        $class = $this->cmf->getMetadataFor(SuperclassEntity::class);
        assert($class instanceof ClassMetadata);

        self::assertInstanceOf(IdSequenceGenerator::class, $class->idGenerator);
        self::assertEquals(
            ['allocationSize' => 1, 'initialValue' => 10, 'sequenceName' => 'foo'],
            $class->sequenceGeneratorDefinition
        );
    }

    /**
     * @group DDC-1156
     * @group DDC-1218
     */
    public function testSequenceDefinitionInHierarchyWithSandwichMappedSuperclass(): void
    {
        $class = $this->cmf->getMetadataFor(HierarchyD::class);
        assert($class instanceof ClassMetadata);

        self::assertInstanceOf(IdSequenceGenerator::class, $class->idGenerator);
        self::assertEquals(
            ['allocationSize' => 1, 'initialValue' => 10, 'sequenceName' => 'foo'],
            $class->sequenceGeneratorDefinition
        );
    }

    /**
     * @group DDC-1156
     * @group DDC-1218
     */
    public function testMultipleMappedSuperclasses(): void
    {
        $class = $this->cmf->getMetadataFor(MediumSuperclassEntity::class);
        assert($class instanceof ClassMetadata);

        self::assertInstanceOf(IdSequenceGenerator::class, $class->idGenerator);
        self::assertEquals(
            ['allocationSize' => 1, 'initialValue' => 10, 'sequenceName' => 'foo'],
            $class->sequenceGeneratorDefinition
        );
    }

    /**
     * Ensure indexes are inherited from the mapped superclass.
     *
     * @group DDC-3418
     */
    public function testMappedSuperclassIndex(): void
    {
        $class = $this->cmf->getMetadataFor(EntityIndexSubClass::class);
        assert($class instanceof ClassMetadata);

        self::assertArrayHasKey('mapped1', $class->fieldMappings);
        self::assertArrayHasKey('IDX_NAME_INDEX', $class->table['uniqueConstraints']);
        self::assertArrayHasKey('IDX_MAPPED1_INDEX', $class->table['uniqueConstraints']);
        self::assertArrayHasKey('IDX_MAPPED2_INDEX', $class->table['indexes']);
    }
}

class TransientBaseClass
{
    /** @var mixed */
    private $transient1;

    /** @var mixed */
    private $transient2;
}

/** @Entity */
class EntitySubClass extends TransientBaseClass
{
    /**
     * @var int
     * @Id
     * @Column(type="integer")
     */
    private $id;

    /**
     * @var string
     * @Column(type="string")
     */
    private $name;
}

/** @MappedSuperclass */
class MappedSuperclassBase
{
    /**
     * @var int
     * @Column(type="integer")
     */
    private $mapped1;

    /**
     * @var string
     * @Column(type="string")
     */
    private $mapped2;

    /**
     * @var MappedSuperclassRelated1
     * @OneToOne(targetEntity="MappedSuperclassRelated1")
     * @JoinColumn(name="related1_id", referencedColumnName="id")
     */
    private $mappedRelated1;

    /** @var mixed */
    private $transient;
}

class MappedSuperclassRelated1
{
}

/** @Entity */
class EntitySubClass2 extends MappedSuperclassBase
{
    /**
     * @var int
     * @Id
     * @Column(type="integer")
     */
    private $id;

    /**
     * @var string
     * @Column(type="string")
     */
    private $name;
}

/**
 * @MappedSuperclass
 * @Table(
 *  uniqueConstraints={@UniqueConstraint(name="IDX_MAPPED1_INDEX",columns={"mapped1"})},
 *  indexes={@Index(name="IDX_MAPPED2_INDEX", columns={"mapped2"})}
 * )
 */
class MappedSuperclassBaseIndex
{
    /**
     * @var string
     * @Column(type="string")
     */
    private $mapped1;
    /**
     * @var string
     * @Column(type="string")
     */
    private $mapped2;
}

/** @Entity @Table(uniqueConstraints={@UniqueConstraint(name="IDX_NAME_INDEX",columns={"name"})}) */
class EntityIndexSubClass extends MappedSuperclassBaseIndex
{
    /**
     * @var int
     * @Id
     * @Column(type="integer")
     */
    private $id;

    /**
     * @var string
     * @Column(type="string")
     */
    private $name;
}

/**
 * @Entity
 * @InheritanceType("SINGLE_TABLE")
 * @DiscriminatorColumn(name="type", type="string", length=20)
 * @DiscriminatorMap({
 *     "c"   = "HierarchyC",
 *     "d"   = "HierarchyD",
 *     "e"   = "HierarchyE"
 * })
 */
abstract class HierarchyBase
{
    /**
     * @Column(type="integer") @Id @GeneratedValue(strategy="SEQUENCE")
     * @SequenceGenerator(sequenceName="foo", initialValue=10)
     * @var int
     */
    public $id;
}

/** @MappedSuperclass */
abstract class HierarchyASuperclass extends HierarchyBase
{
    /**
     * @var string
     * @Column(type="string")
     */
    public $a;
}

/** @Entity */
class HierarchyBEntity extends HierarchyBase
{
    /**
     * @var string
     * @Column(type="string")
     */
    public $b;
}

/** @Entity */
class HierarchyC extends HierarchyBase
{
    /**
     * @var string
     * @Column(type="string")
     */
    public $c;
}

/** @Entity */
class HierarchyD extends HierarchyASuperclass
{
    /**
     * @var string
     * @Column(type="string")
     */
    public $d;
}

/** @Entity */
class HierarchyE extends HierarchyBEntity
{
    /**
     * @var string
     * @Column(type="string")
     */
    public $e;
}

/** @Entity */
class SuperclassEntity extends SuperclassBase
{
}

/** @MappedSuperclass */
abstract class SuperclassBase
{
    /**
     * @var int
     * @Column(type="integer")
     * @Id
     * @GeneratedValue(strategy="SEQUENCE")
     * @SequenceGenerator(sequenceName="foo", initialValue=10)
     */
    public $id;
}

/** @MappedSuperclass */
abstract class MediumSuperclassBase extends SuperclassBase
{
}

/** @Entity */
class MediumSuperclassEntity extends MediumSuperclassBase
{
}

/** @Entity(repositoryClass = "Doctrine\ORM\EntityRepository") */
class SubclassWithRepository extends DDC869Payment
{
}


text:
@interface HomeBanner : NSObject

@property (nonatomic,strong) NSString *img_url;
@property (nonatomic,strong) NSString *jump_url;
@property (nonatomic,strong) NSString *title;

@end


text:
import {RouterException} from "./RouterException";

export class TooManyRequestsException extends RouterException {
    constructor(message: any, error?: Error) {
        message = message || "Too Many Requests";
        super(429, message, error);
    }
}


text:
Although we are always happy to make improvements to Shoulda Matchers, we also
welcome changes and improvements from the community!

Have a fix for a problem you've been running into or an idea for a new feature
you think would be useful? Here's what you need to do:

1. [Read and understand the Code of Conduct](#code-of-conduct).
1. Fork this repo and clone your fork to somewhere on your machine.
1. [Ensure that you have a working environment](#setting-up-your-environment).
1. Read up on the [architecture of the gem](#architecture), [how to run
   tests](#running-tests), and [the code style we use in this
   project](#code-style).
1. Cut a new branch and write a failing test for the feature or bugfix you plan
   on implementing.
1. [Make sure your branch is well managed as you go
   along](#managing-your-branch).
1. [Update the inline documentation if you're making a change to the
   API](#documentation).
1. [Refrain from updating the changelog.](#a-word-on-the-changelog)
1. Push to your fork and submit a pull request.
1. [Ensure that the test suite passes on GitHub Actions and make any necessary
   changes to your branch to bring it to green.](#continuous-integration)

Although we maintain Shoulda Matchers in our free time, we try to respond to
contributions in a timely manner. Once we look at your pull request, we may give
you feedback. For instance, we may suggest some changes to make to your code to
fit within the project style or discuss alternate ways of addressing the issue
in question. Assuming we're happy with everything, we'll then bring your changes
into main. Now you're a contributor!

---

## Code of Conduct

If this is your first time contributing, please read the [Code of Conduct]. We
want to create a space in which everyone is allowed to contribute, and we
enforce the policies outline in this document.

[Code of Conduct]: https://thoughtbot.com/open-source-code-of-conduct

## Setting up your environment

The setup script will install all dependencies necessary for working on the
project:

```bash
bin/setup
```

## Architecture

This project follows the typical structure for a gem: code is located in `lib`
and tests are in `spec`.

### Matchers

All of the matchers are broken up by the type of example group they apply to:

* `{lib,spec/unit}/shoulda/matchers/action_controller*` for ActionController
  matchers
* `{lib,spec/unit}/shoulda/matchers/active_model*` for ActiveModel matchers
* `{lib,spec/unit}/shoulda/matchers/active_record*` for ActiveRecord matchers
* `{lib,spec/unit}/shoulda/matchers/independent*` for matchers that can be used
  in any example group

There are other files in the project, of course, but these are likely the ones
you'll be most interested in.

### Tests

In addition, tests are broken up into two categories:

* `spec/unit` — low-level tests for individual matchers (you're probably
  interested in these)
* `spec/acceptance` — high-level tests to ensure that the gem works in Rails
  projects, plain Ruby projects, etc. (these do not need to get updated often)

A word about the tests, by the way: they're admittedly the most complicated part
of this gem, and there are a few different strategies that we've introduced at
various points in time to set up objects for tests across all specs, some of
which are old and some of which are new. The best approach for writing tests is
probably to copy an existing test in the same file as where you want to add a
new test.

## Code style

We follow a derivative of the [unofficial Ruby style guide] created by the
Rubocop developers. You can view our Rubocop configuration [here], but here are
some key differences:

* Use single quotes for strings.
* When breaking up methods across multiple lines, place the `.` at the end of
  the line instead of the beginning.
* Don't use conditional modifiers (i.e. `x if y`); place the beginning and
  ending of conditionals on their own lines.
* Use an 80-character line-length except for `describe`, `context`, `it`, and
  `specify` lines in tests.
* For arrays, hashes, and method arguments that span multiple lines, place a
  trailing comma at the end of the last item.
* Collection methods are spelled `detect`, `inject`, `map`, and `select`.

[unofficial Ruby style guide]: https://github.com/rubocop-hq/ruby-style-guide
[here]: .rubocop.yml

## Running tests

### A word about Appraisals

Because the gem supports multiple Ruby and Rails versions, we have to be able
to test against them as well.

Oftentimes it is enough to use whatever Ruby version you have on your computer,
but if you are fixing a bug that targets a specific Ruby version, you'll want to
make sure to switch to that using your Ruby manager of choice before you run any
tests.

If you are fixing a bug for a specific _Rails_ version, then you'll want to use
a specific "appraisal" when running a test. [Appraisals] are Gemfiles centered
around a Rails version. What this means is that when running tests, you have to
specify which one to use. You do this by using this command:

```bash
bundle exec appraisal <appraisal name> ...
```

You can find the available list of appraisals by running:

```bash
bundle exec appraisal list
```

[Appraisals]: https://github.com/thoughtbot/appraisal

### Unit tests

Unit tests are the most common kind of tests in the gem. They exercise matcher
code file by file in the context of a real Rails application. This application
is created and loaded every time you start running tests.

To run a unit test, you might say something like:

```bash
bundle exec appraisal rails_5_2 rspec spec/unit/shoulda/matchers/active_model/validate_inclusion_of_matcher_spec.rb
```

### Acceptance tests

The acceptance tests exercise matchers in the context of a real Ruby or Rails
application. Unlike unit tests, this application is set up and torn down for
each test.

To run an acceptance test, you might say something like:

```bash
bundle exec appraisal rails_5_2 rspec spec/acceptance/rails_integration_spec.rb
```

### All tests

In order to run all of the tests, simply run:

```bash
bundle exec rake
```

## Managing your branch

* Use well-crafted commit messages, providing context if possible. [Tim Pope's
  guide] was a wonderful piece on this topic when it came out and we still find
  it to be helpful even today.
* Squash "WIP" commits and remove merge commits by rebasing your branch against
  `main`. We try to keep our commit history as clean as possible.

[Tim Pope's guide]: https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html

## Documentation

As you navigate the codebase, you may notice certain classes and methods that
are prefaced with inline documentation. This documentation is written and
generated using [YARD][yard] and is published [online][rubydocs].

[rubydocs]: https://matchers.shoulda.io/docs
[yard]: https://github.com/lsegal/yard

We ensure that the documentation is up to date before we issue a release, but
sometimes we don't catch everything. So if your changes end up extending or
updating the API, it helps us greatly to update the docs at the same time.

## A word on the changelog

You may also notice that we have a changelog in the form of
[CHANGELOG.md](CHANGELOG.md). You may be tempted to include changes to this in
your branch, but don't worry about this — we'll take care of it!

## Continuous integration

While running `bundle exec rake` is a great way to check your work, this command
will only run your tests against the latest supported Ruby and Rails version.
Ultimately, though, you'll want to ensure that your changes work in all possible
environments. We make use of [GitHub Actions][gh-actions] to do this work for
us. GitHub Actions will kick in after you push up a branch or open a PR.
It takes 20-30 minutes to run a complete build, which you are free to
[monitor as it progresses][shoulda-matchers-on-gh-actions]. First-time
contributors may need to wait until a maintainer approves the build.

[shoulda-matchers-on-gh-actions]: https://github.com/thoughtbot/shoulda-matchers/actions

What happens if the build fails in some way? Don't fear! Click on a failed job
and scroll through its output to determine the cause of the failure. You'll want
to make changes to your branch and push them up until the entire build is green.
It may take a bit of time, but overall it is worth it and it helps us immensely!

[gh-actions]: https://github.com/features/actions


text:
require 'helper'

class TestCloud < ParseTestCase
  # functions stored in test/cloud_functions/MyCloudCode
  # see https://parse.com/docs/cloud_code_guide to learn how to use Parse Cloud Code
  #
  # Parse.Cloud.define('trivial', function(request, response) {
  #   response.success(request.params);
  # });

  def test_cloud_function_initialize
    cloud_function = Parse::Cloud::Function.new('trivial', @client)
    assert cloud_function.function_name == 'trivial'
  end

  def test_cloud_function_uri
    assert Parse::Cloud::Function.new('trivial', @client).uri
  end

  def test_cloud_function_call
    skip('this should automate the parse deploy command by committing that binary to the repo')

    VCR.use_cassette('test_cloud_function_call') do
      function = Parse::Cloud::Function.new('trivial', @client)
      params = { 'foo' => 'bar' }
      resp = function.call(params)
      assert_equal resp, params
    end
  end
end


text:
jtxlib
======

Web-oriented Java library


text:
package org.auraframework.util.type.converter;

import java.util.ArrayList;

import org.auraframework.ds.serviceloader.AuraServiceProvider;
import org.auraframework.util.type.Converter;

import aQute.bnd.annotation.component.Component;

/**
 * Used by aura.util.type.TypeUtil
 */
@SuppressWarnings("rawtypes")
@Component (provide=AuraServiceProvider.class)
public class ArrayListToStringArrayConverter implements Converter<ArrayList, String[]> {

    @SuppressWarnings("unchecked")
    @Override
    public String[] convert(ArrayList value) {
        String[] retArray = null;
        if (value != null) {
            retArray = new String[value.size()];
            for (int i = 0; i < value.size(); i++) {
                retArray[i] = ((ArrayList<String>) value).get(i).trim();
            }
        }
        return retArray;
    }

    @Override
    public Class<ArrayList> getFrom() {
        return ArrayList.class;
    }

    @Override
    public Class<String[]> getTo() {
        return String[].class;
    }

    @Override
    public Class<?>[] getToParameters() {
        return null;
    }

}


text:
namespace sapi {

struct GeneratorOptions {
  template <typename ContainerT>
  GeneratorOptions& set_function_names(const ContainerT& value) {
    function_names.clear();
    function_names.insert(std::begin(value), std::end(value));
    return *this;
  }

  template <typename ContainerT>
  GeneratorOptions& set_in_files(const ContainerT& value) {
    in_files.clear();
    in_files.insert(std::begin(value), std::end(value));
    return *this;
  }

  GeneratorOptions& set_limit_scan_depth(bool value) {
    limit_scan_depth = value;
    return *this;
  }

  bool has_namespace() const { return !namespace_name.empty(); }

  absl::flat_hash_set<std::string> function_names;
  absl::flat_hash_set<std::string> in_files;
  bool limit_scan_depth = false;

  // Output options
  std::string work_dir;
  std::string name;            // Name of the Sandboxed API
  std::string namespace_name;  // Namespace to wrap the SAPI in
  // Output path of the generated header. Used to build the header include
  // guard.
  std::string out_file = "out_file.cc";
  std::string embed_dir;   // Directory with embedded includes
  std::string embed_name;  // Identifier of the embed object
};

class GeneratorASTVisitor
    : public clang::RecursiveASTVisitor<GeneratorASTVisitor> {
 public:
  explicit GeneratorASTVisitor(const GeneratorOptions& options)
      : options_(options) {}

  bool VisitTypeDecl(clang::TypeDecl* decl);
  bool VisitFunctionDecl(clang::FunctionDecl* decl);

  TypeCollector& collector() { return collector_; }

  const std::vector<clang::FunctionDecl*>& functions() const {
    return functions_;
  }

 private:
  TypeCollector collector_;
  std::vector<clang::FunctionDecl*> functions_;
  const GeneratorOptions& options_;
};

class GeneratorASTConsumer : public clang::ASTConsumer {
 public:
  GeneratorASTConsumer(std::string in_file, Emitter& emitter,
                       const GeneratorOptions& options)
      : in_file_(std::move(in_file)), visitor_(options), emitter_(emitter) {}

 private:
  void HandleTranslationUnit(clang::ASTContext& context) override;

  std::string in_file_;
  GeneratorASTVisitor visitor_;
  Emitter& emitter_;
};

class GeneratorAction : public clang::ASTFrontendAction {
 public:
  GeneratorAction(Emitter& emitter, const GeneratorOptions& options)
      : emitter_(emitter), options_(options) {}

 private:
  std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(
      clang::CompilerInstance&, llvm::StringRef in_file) override {
    return std::make_unique<GeneratorASTConsumer>(std::string(in_file),
                                                  emitter_, options_);
  }

  bool hasCodeCompletionSupport() const override { return false; }

  Emitter& emitter_;
  const GeneratorOptions& options_;
};

class GeneratorFactory : public clang::tooling::FrontendActionFactory {
 public:
  // Does not take ownership
  GeneratorFactory(Emitter& emitter, const GeneratorOptions& options)
      : emitter_(emitter), options_(options) {}

 private:
#if LLVM_VERSION_MAJOR >= 10
  std::unique_ptr<clang::FrontendAction> create() override {
    return std::make_unique<GeneratorAction>(emitter_, options_);
  }
#else
  clang::FrontendAction* create() override {
    return new GeneratorAction(emitter_, options_);
  }
#endif

  bool runInvocation(
      std::shared_ptr<clang::CompilerInvocation> invocation,
      clang::FileManager* files,
      std::shared_ptr<clang::PCHContainerOperations> pch_container_ops,
      clang::DiagnosticConsumer* diag_consumer) override;

  Emitter& emitter_;
  const GeneratorOptions& options_;
};

std::string GetOutputFilename(absl::string_view source_file);

inline absl::string_view ToStringView(llvm::StringRef ref) {
  return absl::string_view(ref.data(), ref.size());
}

}  // namespace sapi

#endif  // SANDBOXED_API_TOOLS_CLANG_GENERATOR_GENERATOR_H_


text:
'use strict';

var app = angular
  .module('codeApp', [
    'ngCookies',
    'ngResource',
    'ngSanitize',
    'ngRoute',
    'ngAnimate'
  ]);
app.config(function ($routeProvider) {
    $routeProvider
    .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
    })
    .when('/about', {
        templateUrl: 'views/about.html',
        controller: 'AboutCtrl'
    })
    .when('/projects', {
        templateUrl: 'views/projects.html',
        controller: 'ProjectsCtrl'
    })
    .when('/blog', {
        templateUrl: 'views/blog.html',
        controller: 'BlogCtrl'
    })
    .when('/contact', {
        templateUrl: 'views/contact.html',
        controller: 'ContactCtrl'
    })
    .otherwise({
        redirectTo: '/'
    });
});


text:
package io.finch

trait ValidationRules {
  /**
   * A [[ValidationRule]] that makes sure the numeric value is greater than given `n`.
   */
  def beGreaterThan[A](n: A)(implicit ev: Numeric[A]): ValidationRule[A] =
    ValidationRule(s"be greater than $n")(ev.gt(_, n))

  /**
   * A [[ValidationRule]] that makes sure the numeric value is less than given `n`.
   */
  def beLessThan[A](n: A)(implicit ev: Numeric[A]): ValidationRule[A] =
    ValidationRule(s"be less than $n")(ev.lt(_, n))

  /**
   * A [[ValidationRule]] that makes sure the string value is longer than `n` symbols.
   */
  def beLongerThan(n: Int): ValidationRule[String] =
    ValidationRule(s"be longer than $n symbols")(_.length > n)

  /**
   * A [[ValidationRule]] that makes sure the string value is shorter than `n` symbols.
   */
  def beShorterThan(n: Int): ValidationRule[String] =
    ValidationRule(s"be shorter than $n symbols")(_.length < n)

  /**
   * Implicit conversion that allows the same inline rules to be used for required and optional
   * values. If the optional value is non-empty, it gets validated (and validation may fail,
   * producing error), but if it is empty, it is always treated as valid.
   *
   * In order to help the compiler determine the case when inline rule should be converted, the type
   * of the validated value should be specified explicitly.
   *
   * {{{
   *   paramOption("foo").should("be greater than 50") { i: Int => i > 50 }
   * }}}
   *
   * @param fn the underlying function to convert
   */
  implicit def toOptionalInlineRule[A](fn: A => Boolean): Option[A] => Boolean = {
    case Some(value) => fn(value)
    case None => true
  }
}


text:
package com.intellij.ide.actions;

import com.intellij.ide.ui.LafManager;
import com.intellij.ide.ui.UISettings;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.idea.ActionsBundle;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.ActionCallback;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ex.ToolWindowManagerEx;
import com.intellij.openapi.wm.impl.DesktopLayout;
import com.intellij.openapi.wm.impl.IdeFrameImpl;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.JBUI;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.plaf.FontUIResource;
import java.awt.*;
import java.util.Enumeration;
import java.util.Map;

/**
 * @author Konstantin Bulenkov
 */
public class TogglePresentationModeAction extends AnAction implements DumbAware {
  private static final Map<Object, Object> ourSavedValues = ContainerUtil.newLinkedHashMap();
  private static float ourSavedScaleFactor = JBUI.scale(1f);
  private static int ourSavedConsoleFontSize;

  @Override
  public void update(@NotNull AnActionEvent e) {
    boolean selected = UISettings.getInstance().getPresentationMode();
    //noinspection ConditionalExpressionWithIdenticalBranches
    e.getPresentation().setText(selected ? ActionsBundle.message("action.TogglePresentationMode.exit")
                                         : ActionsBundle.message("action.TogglePresentationMode.enter"));
  }

  @Override
  public void actionPerformed(@NotNull AnActionEvent e){
    UISettings settings = UISettings.getInstance();
    Project project = e.getProject();

    setPresentationMode(project, !settings.getPresentationMode());
  }

  //public static void restorePresentationMode() {
  //  UISettings instance = UISettings.getInstance();
  //  tweakUIDefaults(instance, true);
  //  tweakEditorAndFireUpdateUI(instance, true);
  //}

  public static void setPresentationMode(final Project project, final boolean inPresentation) {
    final UISettings settings = UISettings.getInstance();
    settings.setPresentationMode(inPresentation);

    final boolean layoutStored = storeToolWindows(project);

    tweakUIDefaults(settings, inPresentation);

    ActionCallback callback = project == null ? ActionCallback.DONE : tweakFrameFullScreen(project, inPresentation);
    callback.doWhenProcessed(() -> {
      tweakEditorAndFireUpdateUI(settings, inPresentation);

      restoreToolWindows(project, layoutStored, inPresentation);
    });
  }

  private static ActionCallback tweakFrameFullScreen(Project project, boolean inPresentation) {
    Window window = IdeFrameImpl.getActiveFrame();
    if (window instanceof IdeFrameImpl) {
      IdeFrameImpl frame = (IdeFrameImpl)window;
      PropertiesComponent propertiesComponent = PropertiesComponent.getInstance(project);
      if (inPresentation) {
        propertiesComponent.setValue("full.screen.before.presentation.mode", String.valueOf(frame.isInFullScreen()));
        return frame.toggleFullScreen(true);
      }
      else {
        if (frame.isInFullScreen()) {
          final String value = propertiesComponent.getValue("full.screen.before.presentation.mode");
          return frame.toggleFullScreen("true".equalsIgnoreCase(value));
        }
      }
    }
    return ActionCallback.DONE;
  }

  private static void tweakEditorAndFireUpdateUI(UISettings settings, boolean inPresentation) {
    EditorColorsScheme globalScheme = EditorColorsManager.getInstance().getGlobalScheme();
    int fontSize = inPresentation ? settings.getPresentationModeFontSize() : globalScheme.getEditorFontSize();
    if (inPresentation) {
      ourSavedConsoleFontSize = globalScheme.getConsoleFontSize();
      globalScheme.setConsoleFontSize(fontSize);
    }
    else {
      globalScheme.setConsoleFontSize(ourSavedConsoleFontSize);
    }
    for (Editor editor : EditorFactory.getInstance().getAllEditors()) {
      if (editor instanceof EditorEx) {
        ((EditorEx)editor).setFontSize(fontSize);
      }
    }
    UISettings.getInstance().fireUISettingsChanged();
    LafManager.getInstance().updateUI();
    EditorUtil.reinitSettings();
  }

  private static void tweakUIDefaults(UISettings settings, boolean inPresentation) {
    UIDefaults defaults = UIManager.getDefaults();
    Enumeration<Object> keys = defaults.keys();
    if (inPresentation) {
      while (keys.hasMoreElements()) {
        Object key = keys.nextElement();
        if (key instanceof String) {
          String name = (String)key;
          if (name.endsWith(".font")) {
            Font font = defaults.getFont(key);
            ourSavedValues.put(key, font);
          }
          else if (name.endsWith(".rowHeight")) {
            ourSavedValues.put(key, defaults.getInt(key));
          }
        }
      }
      float scaleFactor = JBUI.getFontScale(settings.getPresentationModeFontSize());
      ourSavedScaleFactor = JBUI.scale(1f);
      JBUI.setUserScaleFactor(scaleFactor);
      for (Object key : ourSavedValues.keySet()) {
        Object v = ourSavedValues.get(key);
        if (v instanceof Font) {
          Font font = (Font)v;
          defaults.put(key, new FontUIResource(font.getName(), font.getStyle(), JBUI.scale(font.getSize())));
        }
        else if (v instanceof Integer) {
          defaults.put(key, JBUI.scale(((Integer)v).intValue()));
        }
      }
    }
    else {
      for (Object key : ourSavedValues.keySet()) {
        defaults.put(key, ourSavedValues.get(key));
      }
      JBUI.setUserScaleFactor(ourSavedScaleFactor);
      ourSavedValues.clear();
    }
  }

  private static boolean hideAllToolWindows(ToolWindowManagerEx manager) {
    // to clear windows stack
    manager.clearSideStack();

    String[] ids = manager.getToolWindowIds();
    boolean hasVisible = false;
    for (String id : ids) {
      final ToolWindow toolWindow = manager.getToolWindow(id);
      if (toolWindow.isVisible()) {
        toolWindow.hide(null);
        hasVisible = true;
      }
    }
    return hasVisible;
  }

  static boolean storeToolWindows(@Nullable Project project) {
    if (project == null) return false;
    ToolWindowManagerEx manager = ToolWindowManagerEx.getInstanceEx(project);

    DesktopLayout layout = new DesktopLayout();
    layout.copyFrom(manager.getLayout());
    boolean hasVisible = hideAllToolWindows(manager);

    if (hasVisible) {
      manager.setLayoutToRestoreLater(layout);
      manager.activateEditorComponent();
    }
    return hasVisible;
  }

  static void restoreToolWindows(Project project, boolean needsRestore, boolean inPresentation) {
    if (project == null || !needsRestore) return;
    ToolWindowManagerEx manager = ToolWindowManagerEx.getInstanceEx(project);
    DesktopLayout restoreLayout = manager.getLayoutToRestoreLater();
    if (!inPresentation && restoreLayout != null) {
      manager.setLayout(restoreLayout);
    }
  }
}


text:
package ephertest

import (
	"math/rand"
	"net/http"
	"testing"

	"github.com/aybabtme/epher/cluster"
	"github.com/aybabtme/epher/codec"
	"github.com/aybabtme/epher/merkle"
	"github.com/aybabtme/epher/service"
	"github.com/aybabtme/epher/store"
)

func startService(t *testing.T, r *rand.Rand, rc cluster.RemoteCluster, st merkle.Store) service.Svc {
	cd := codec.Binary()
	svc, err := service.Start(r, rc, cd, st, func(nd cluster.Node) merkle.Store {
		return store.HTTPClient(nd.Addr, cd, &http.Client{})
	})
	if err != nil {
		t.Fatal(err)
	}
	return svc
}


text:
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/password_manager/core/browser/move_password_to_account_store_helper.h"

#include <utility>

#include "components/password_manager/core/browser/form_fetcher_impl.h"
#include "components/password_manager/core/browser/password_form_digest.h"
#include "components/password_manager/core/browser/password_form_metrics_recorder.h"
#include "components/password_manager/core/browser/password_save_manager_impl.h"

namespace password_manager {

MovePasswordToAccountStoreHelper::MovePasswordToAccountStoreHelper(
    const PasswordForm& form,
    PasswordManagerClient* client,
    metrics_util::MoveToAccountStoreTrigger trigger,
    base::OnceClosure done_callback)
    : form_(form),
      client_(client),
      trigger_(trigger),
      done_callback_(std::move(done_callback)),
      form_fetcher_(std::make_unique<FormFetcherImpl>(
          PasswordFormDigest(form),
          client,
          /*should_migrate_http_passwords=*/true)) {
  form_fetcher_->Fetch();
  form_fetcher_->AddConsumer(this);
}

MovePasswordToAccountStoreHelper::~MovePasswordToAccountStoreHelper() {
  form_fetcher_->RemoveConsumer(this);
}

void MovePasswordToAccountStoreHelper::OnFetchCompleted() {
  auto save_manager = std::make_unique<PasswordSaveManagerImpl>(client_);
  save_manager->Init(client_, form_fetcher_.get(), /*metrics_recorder=*/nullptr,
                     /*votes_uploader=*/nullptr);
  save_manager->CreatePendingCredentials(form_, {}, {}, /*is_http_auth=*/false,
                                         /*is_credential_api_save=*/false);
  save_manager->MoveCredentialsToAccountStore(trigger_);
  std::move(done_callback_).Run();
  // |this| might be deleted now!
}

}  // namespace password_manager


text:
typedef struct class1 {
    class1& operator=(const class1&);
} class1;

class class2 : public class1 { };


text:
#include <stdio.h>
#include <stdlib.h>

#include <sunmatrix/sunmatrix_dense.h>
#include <sundials/sundials_math.h>

#define ZERO RCONST(0.0)
#define ONE  RCONST(1.0)

/* Private function prototypes */
static booleantype SMCompatible_Dense(SUNMatrix A, SUNMatrix B);
static booleantype SMCompatible2_Dense(SUNMatrix A, N_Vector x, N_Vector y);

/*
 * -----------------------------------------------------------------
 * exported functions
 * -----------------------------------------------------------------
 */

/* ----------------------------------------------------------------------------
 * Function to create a new dense matrix
 */

SUNMatrix SUNDenseMatrix(sunindextype M, sunindextype N, SUNContext sunctx)
{
  SUNMatrix A;
  SUNMatrixContent_Dense content;
  sunindextype j;

  /* return with NULL matrix on illegal dimension input */
  if ( (M <= 0) || (N <= 0) ) return(NULL);

  /* Create an empty matrix object */
  A = NULL;
  A = SUNMatNewEmpty(sunctx);
  if (A == NULL) return(NULL);

  /* Attach operations */
  A->ops->getid     = SUNMatGetID_Dense;
  A->ops->clone     = SUNMatClone_Dense;
  A->ops->destroy   = SUNMatDestroy_Dense;
  A->ops->zero      = SUNMatZero_Dense;
  A->ops->copy      = SUNMatCopy_Dense;
  A->ops->scaleadd  = SUNMatScaleAdd_Dense;
  A->ops->scaleaddi = SUNMatScaleAddI_Dense;
  A->ops->matvec    = SUNMatMatvec_Dense;
  A->ops->space     = SUNMatSpace_Dense;

  /* Create content */
  content = NULL;
  content = (SUNMatrixContent_Dense) malloc(sizeof *content);
  if (content == NULL) { SUNMatDestroy(A); return(NULL); }

  /* Attach content */
  A->content = content;

  /* Fill content */
  content->M     = M;
  content->N     = N;
  content->ldata = M*N;
  content->data  = NULL;
  content->cols  = NULL;

  /* Allocate content */
  content->data = (realtype *) calloc(M * N, sizeof(realtype));
  if (content->data == NULL) { SUNMatDestroy(A); return(NULL); }

  content->cols = (realtype **) malloc(N * sizeof(realtype *));
  if (content->cols == NULL) { SUNMatDestroy(A); return(NULL); }
  for (j=0; j<N; j++) content->cols[j] = content->data + j * M;

  return(A);
}

/* ----------------------------------------------------------------------------
 * Function to print the dense matrix
 */

void SUNDenseMatrix_Print(SUNMatrix A, FILE* outfile)
{
  sunindextype i, j;

  /* should not be called unless A is a dense matrix;
     otherwise return immediately */
  if (SUNMatGetID(A) != SUNMATRIX_DENSE)
    return;

  /* perform operation */
  STAN_SUNDIALS_FPRINTF(outfile,"\n");
  for (i=0; i<SM_ROWS_D(A); i++) {
    for (j=0; j<SM_COLUMNS_D(A); j++) {
#if defined(SUNDIALS_EXTENDED_PRECISION)
      STAN_SUNDIALS_FPRINTF(outfile,"%12Lg  ", SM_ELEMENT_D(A,i,j));
#elif defined(SUNDIALS_DOUBLE_PRECISION)
      STAN_SUNDIALS_FPRINTF(outfile,"%12g  ", SM_ELEMENT_D(A,i,j));
#else
      STAN_SUNDIALS_FPRINTF(outfile,"%12g  ", SM_ELEMENT_D(A,i,j));
#endif
    }
    STAN_SUNDIALS_FPRINTF(outfile,"\n");
  }
  STAN_SUNDIALS_FPRINTF(outfile,"\n");
  return;
}

/* ----------------------------------------------------------------------------
 * Functions to access the contents of the dense matrix structure
 */

sunindextype SUNDenseMatrix_Rows(SUNMatrix A)
{
  if (SUNMatGetID(A) == SUNMATRIX_DENSE)
    return SM_ROWS_D(A);
  else
    return SUNMAT_ILL_INPUT;
}

sunindextype SUNDenseMatrix_Columns(SUNMatrix A)
{
  if (SUNMatGetID(A) == SUNMATRIX_DENSE)
    return SM_COLUMNS_D(A);
  else
    return SUNMAT_ILL_INPUT;
}

sunindextype SUNDenseMatrix_LData(SUNMatrix A)
{
  if (SUNMatGetID(A) == SUNMATRIX_DENSE)
    return SM_LDATA_D(A);
  else
    return SUNMAT_ILL_INPUT;
}

realtype* SUNDenseMatrix_Data(SUNMatrix A)
{
  if (SUNMatGetID(A) == SUNMATRIX_DENSE)
    return SM_DATA_D(A);
  else
    return NULL;
}

realtype** SUNDenseMatrix_Cols(SUNMatrix A)
{
  if (SUNMatGetID(A) == SUNMATRIX_DENSE)
    return SM_COLS_D(A);
  else
    return NULL;
}

realtype* SUNDenseMatrix_Column(SUNMatrix A, sunindextype j)
{
  if (SUNMatGetID(A) == SUNMATRIX_DENSE)
    return SM_COLUMN_D(A,j);
  else
    return NULL;
}

/*
 * -----------------------------------------------------------------
 * implementation of matrix operations
 * -----------------------------------------------------------------
 */

SUNMatrix_ID SUNMatGetID_Dense(SUNMatrix A)
{
  return SUNMATRIX_DENSE;
}

SUNMatrix SUNMatClone_Dense(SUNMatrix A)
{
  SUNMatrix B = SUNDenseMatrix(SM_ROWS_D(A), SM_COLUMNS_D(A), A->sunctx);
  return(B);
}

void SUNMatDestroy_Dense(SUNMatrix A)
{
  if (A == NULL) return;

  /* free content */
  if (A->content != NULL) {
    /* free data array */
    if (SM_DATA_D(A) != NULL) {
      free(SM_DATA_D(A));
      SM_DATA_D(A) = NULL;
    }
    /* free column pointers */
    if (SM_CONTENT_D(A)->cols != NULL) {
      free(SM_CONTENT_D(A)->cols);
      SM_CONTENT_D(A)->cols = NULL;
    }
    /* free content struct */
    free(A->content);
    A->content = NULL;
  }

  /* free ops and matrix */
  if (A->ops) { free(A->ops); A->ops = NULL; }
  free(A); A = NULL;

  return;
}

int SUNMatZero_Dense(SUNMatrix A)
{
  sunindextype i;
  realtype *Adata;

  /* Perform operation */
  Adata = SM_DATA_D(A);
  for (i=0; i<SM_LDATA_D(A); i++)
    Adata[i] = ZERO;
  return SUNMAT_SUCCESS;
}

int SUNMatCopy_Dense(SUNMatrix A, SUNMatrix B)
{
  sunindextype i, j;

  /* Verify that A and B are compatible */
  if (!SMCompatible_Dense(A, B))
    return SUNMAT_ILL_INPUT;

  /* Perform operation */
  for (j=0; j<SM_COLUMNS_D(A); j++)
    for (i=0; i<SM_ROWS_D(A); i++)
      SM_ELEMENT_D(B,i,j) = SM_ELEMENT_D(A,i,j);
  return SUNMAT_SUCCESS;
}

int SUNMatScaleAddI_Dense(realtype c, SUNMatrix A)
{
  sunindextype i, j;

  /* Perform operation */
  for (j=0; j<SM_COLUMNS_D(A); j++)
    for (i=0; i<SM_ROWS_D(A); i++) {
      SM_ELEMENT_D(A,i,j) *= c;
      if (i == j)
        SM_ELEMENT_D(A,i,j) += ONE;
    }
  return SUNMAT_SUCCESS;
}

int SUNMatScaleAdd_Dense(realtype c, SUNMatrix A, SUNMatrix B)
{
  sunindextype i, j;

  /* Verify that A and B are compatible */
  if (!SMCompatible_Dense(A, B))
    return SUNMAT_ILL_INPUT;

  /* Perform operation */
  for (j=0; j<SM_COLUMNS_D(A); j++)
    for (i=0; i<SM_ROWS_D(A); i++)
      SM_ELEMENT_D(A,i,j) = c*SM_ELEMENT_D(A,i,j) + SM_ELEMENT_D(B,i,j);
  return SUNMAT_SUCCESS;
}

int SUNMatMatvec_Dense(SUNMatrix A, N_Vector x, N_Vector y)
{
  sunindextype i, j;
  realtype *col_j, *xd, *yd;

  /* Verify that A, x and y are compatible */
  if (!SMCompatible2_Dense(A, x, y))
    return SUNMAT_ILL_INPUT;

  /* access vector data (return if failure) */
  xd = N_VGetArrayPointer(x);
  yd = N_VGetArrayPointer(y);
  if ((xd == NULL) || (yd == NULL) || (xd == yd))
    return SUNMAT_MEM_FAIL;

  /* Perform operation */
  for (i=0; i<SM_ROWS_D(A); i++)
    yd[i] = ZERO;
  for(j=0; j<SM_COLUMNS_D(A); j++) {
    col_j = SM_COLUMN_D(A,j);
    for (i=0; i<SM_ROWS_D(A); i++)
      yd[i] += col_j[i]*xd[j];
  }
  return SUNMAT_SUCCESS;
}

int SUNMatSpace_Dense(SUNMatrix A, long int *lenrw, long int *leniw)
{
  *lenrw = SM_LDATA_D(A);
  *leniw = 3 + SM_COLUMNS_D(A);
  return SUNMAT_SUCCESS;
}

/*
 * -----------------------------------------------------------------
 * private functions
 * -----------------------------------------------------------------
 */

static booleantype SMCompatible_Dense(SUNMatrix A, SUNMatrix B)
{
  /* both matrices must be SUNMATRIX_DENSE */
  if (SUNMatGetID(A) != SUNMATRIX_DENSE)
    return SUNFALSE;
  if (SUNMatGetID(B) != SUNMATRIX_DENSE)
    return SUNFALSE;

  /* both matrices must have the same shape */
  if (SM_ROWS_D(A) != SM_ROWS_D(B))
    return SUNFALSE;
  if (SM_COLUMNS_D(A) != SM_COLUMNS_D(B))
    return SUNFALSE;

  return SUNTRUE;
}

static booleantype SMCompatible2_Dense(SUNMatrix A, N_Vector x, N_Vector y)
{
  /*   vectors must be one of {SERIAL, OPENMP, PTHREADS} */
  if ( (N_VGetVectorID(x) != SUNDIALS_NVEC_SERIAL) &&
       (N_VGetVectorID(x) != SUNDIALS_NVEC_OPENMP) &&
       (N_VGetVectorID(x) != SUNDIALS_NVEC_PTHREADS) )
    return SUNFALSE;

  /* Optimally we would verify that the dimensions of A, x and y agree,
   but since there is no generic 'length' routine for N_Vectors we cannot */

  return SUNTRUE;
}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('app', '0021_auto_20151008_1616'),
    ]

    operations = [
        migrations.AlterField(
            model_name='campaign',
            name='hashtag',
            field=models.CharField(help_text=b"Max length 20 characters (do not include '#')", max_length=20, null=True),
        ),
    ]


text:
nutroll
=======

[![Python](https://img.shields.io/badge/language-python-blue.svg)](https://github.com/gregkrsak/nutroll/blob/master/nutroll)

This is a sample Python-language application intended to demonstrate connecting to Reddit via the [PRAW] library.

What you'll need to to start
----------------------------

* Download and install [Python], if you haven't already.

* Install the [PRAW] library (You may be able to do this with the administrator command ```pip install praw```).

* [Create a "script" app on Reddit] (The "redirect uri" field can be ```http://localhost```).

* Modify the ```nutroll``` file to include your Reddit app credentials:
```python
return praw.Reddit(
  client_id='mHJAei1MCbztxw',
  client_secret='G74uVCX9K5MnyBcNhDFwpwqVZtY',
  #...
)
```

Where the ```client_id``` and ```client_secret``` are obtained from your Reddit app settings.

Example of running the ```nutroll``` application:
----------------------------------------------------

* Success:
```
$ ./nutroll your_reddit_username
Scanning for nut rolls (this may take several seconds)...
Nut roll detected: https://www.reddit.com/comments/6alu1h
```
* Failure:
```
$ ./nutroll your_reddit_username
Scanning for nut rolls (this may take several seconds)...
No nut rolls this week.

```
* PEBKAC:
```
$ ./nutroll your_reddit_username
Scanning for nut rolls (this may take several seconds)...
Unable to reach Reddit. Did you setup your credentials properly?

```

Additional resources
--------------------

* [How do I use Git?]

* [Download GitHub Desktop for Windows or Mac]

* [Download Git for Linux]

* http://en.wikipedia.org/wiki/Git_(software)

About
-----

nutroll was developed by [Greg M. Krsak] using [PyCharm] Community 2017.1 on [Linux Mint] 18.1.

Please submit bugs to [the issues page] and feel free to contribute pull requests.

  [PRAW]: https://github.com/praw-dev/praw
  [Python]: https://www.python.org/
  [Create a "script" app on Reddit]: https://www.reddit.com/prefs/apps
  [How do I use Git?]: http://git-scm.com/documentation
  [Download GitHub Desktop for Windows or Mac]: https://desktop.github.com/
  [Download Git for Linux]: http://git-scm.com/download/linux
  [Greg M. Krsak]: https://github.com/gregkrsak
  [PyCharm]: https://www.jetbrains.com/pycharm/
  [Linux Mint]: https://linuxmint.com/
  [the issues page]: https://github.com/gregkrsak/nutroll/issues


text:
package com.google.idea.blaze.base.toolwindow;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.idea.blaze.base.scope.output.PrintOutput;
import com.google.idea.blaze.base.scope.output.StateUpdate;
import com.google.idea.blaze.base.scope.output.StatusOutput;
import com.intellij.execution.filters.Filter;
import com.intellij.execution.filters.HyperlinkInfo;
import com.intellij.openapi.project.Project;
import java.time.Instant;

/** Service that controls the Blaze Outputs Tool Window. */
public interface TasksToolWindowService {

  /** Provider for the current value of "now" for users of {@code java.time}. */
  @FunctionalInterface
  @VisibleForTesting
  interface TimeSource {
    /** Returns the current {@link Instant} according to this time source. */
    Instant now();
  }

  static TasksToolWindowService getInstance(Project project) {
    return project.getService(TasksToolWindowService.class);
  }

  void startTask(Task task, ImmutableList<Filter> consoleFilters);

  void output(Task task, PrintOutput output);

  void status(Task task, StatusOutput output);

  void state(Task task, StateUpdate output);

  void finishTask(Task task, boolean hasErrors, boolean isCancelled);

  void moveTask(Task task, Task newParent);

  void makeTaskRoot(Task task);

  void navigate(Task task, HyperlinkInfo link, int offset);

  void removeTask(Task task);

  void activate();

  void setStopHandler(Task task, Runnable runnable);

  void removeStopHandler(Task task);
}


text:
export interface ISendToMenuService {
  registerMenuItem(receiverName: string, menuPath: string);
  updateContext(contextName: string, context: Object);
  buildMenuTree(inclusions?: Array<string> , exclusions?: Array<string>): Object;
  sendTo(path: string, data: Buffer, scope: any);
}

export class SendToMenuService implements ISendToMenuService {
  public items: any = {};
  public memory: any = {};

  private $timeout: ng.ITimeoutService;
  private $parse: ng.IParseService;

  public static Factory() {
    let service = ($timeout: ng.ITimeoutService, $parse: ng.IParseService) => {
      return new SendToMenuService($timeout, $parse);
    };

    service.$inject = ["$timeout", "$parse"];

    return service;
  }

  constructor($timeout: ng.ITimeoutService, $parse: ng.IParseService) {
    this.$timeout = $timeout;
    this.$parse = $parse;
  }

  public updateContext(contextName: string, context: Object) {

    _.forOwn(this.memory, (cb, propName) => {
      if (propName.indexOf(contextName) !== 0) {
        return;
      }
      cb.call(null, context);
      delete this.memory[propName];
    });

  }

  public registerMenuItem(menuItemName: string, menuPath: string) {
    this.items[menuItemName] = {
      menuPath: menuPath
    };
  };

  public buildMenuTree(inclusions?: Array<string> , exclusions?: Array <string> ) {

    // TODO: support filtering
    // let filteredMenuItems = _(this.items).pickBy((value, key) => {
    //   return !inclusions || inclusions.length === 0 ||
    //     _.find(inclusions, elt => {
    //       return _.startsWith(key, elt);
    //     }) !== undefined;
    // }).pickBy((value, key) => {
    //   return !exclusions || exclusions.length === 0 ||
    //     _.find(exclusions, elt => {
    //       return _.startsWith(key, elt);
    //     }) === undefined;
    // }).value();

    let menu = {};

    _.forEach(this.items, (value, key) => {

      let parentItem = menu;
      let pathElts = value.menuPath.split(".");
      for (let idx = 0; idx < pathElts.length; idx++) {
        let pathElt = pathElts[idx];
        if (!parentItem[pathElt]) {
          parentItem[pathElt] = {};
        }

        if (idx === pathElts.length - 1) {
          parentItem[pathElt] = key;
        } else {
          parentItem = parentItem[pathElt];
        }
      }
    });

    return menu;
  }

  public sendTo(name: string, data: Buffer, scope: any) {

    let dotIndex = name.indexOf(".");
    let scopeName = name.substring(0, dotIndex);
    let propertyName = name.substring(dotIndex + 1);
    let self = this;

    let updateFunc = function(aScope) {
      self.$timeout(() => {
        let setter = self.$parse(propertyName).assign;
        setter(aScope, new Buffer(data.toString("hex"), "hex"));
      });
    };

    if (scope[scopeName]) {
      updateFunc.call(null, scope[scopeName]);
    } else {
      this.memory[name] = updateFunc;
    }

  };
}


text:
(function() {
'use strict';

function defer(thisArg, cb, delay) {
    setTimeout(function() {
        cb.call(thisArg);
    }, delay || 1);
}
var delay = defer;

/// ## *store.Product* object ##
///
/// Most events methods give you access to a `product` object.

store.Product = function(options) {

    if (!options)
        options = {};

    ///
    /// Products object have the following fields and methods.
    ///
    /// ### *store.Product* public attributes
    ///

    ///  - `product.id` - Identifier of the product on the store
    this.id = options.id || null;

    ///  - `product.alias` - Alias that can be used for more explicit [queries](#queries)
    this.alias = options.alias || options.id || null;

    ///  - `product.type` - Family of product, should be one of the defined [product types](#product-types).
    var type = this.type = options.type || null;
    if (type !== store.CONSUMABLE && type !== store.NON_CONSUMABLE && type !== store.PAID_SUBSCRIPTION && type !== store.FREE_SUBSCRIPTION)
        throw new TypeError("Invalid product type");

    ///  - `product.state` - Current state the product is in (see [life-cycle](#life-cycle) below). Should be one of the defined [product states](#product-states)
    this.state = options.state || "";

    ///  - `product.title` - Localized name or short description
    this.title = options.title || options.localizedTitle || null;

    ///  - `product.description` - Localized longer description
    this.description = options.description || options.localizedDescription || null;

    ///  - `product.price` - Localized price, with currency symbol
    this.price = options.price || null;

    ///  - `product.currency` - Currency code (optionaly)
    this.currency = options.currency || null;

    //  - `product.localizedTitle` - Localized name or short description ready for display
    // this.localizedTitle = options.localizedTitle || options.title || null;

    //  - `product.localizedDescription` - Localized longer description ready for display
    // this.localizedDescription = options.localizedDescription || options.description || null;

    //  - `product.localizedPrice` - Localized price (with currency) ready for display
    // this.localizedPrice = options.localizedPrice || null;

    ///  - `product.loaded` - Product has been loaded from server, however it can still be either `valid` or not
    this.loaded = options.loaded;

    ///  - `product.valid` - Product has been loaded and is a valid product
    this.valid  = options.valid;

    ///  - `product.canPurchase` - Product is in a state where it can be purchased
    this.canPurchase = options.canPurchase;

    ///  - `product.owned` - Product is owned
    this.owned = options.owned;

    ///  - `product.transaction` - Latest transaction data for this product (see [transactions](#transactions)).
    this.transaction = null;

    this.stateChanged();
};

///
/// ### *store.Product* public methods
///

/// #### `product.finish()` ##
///
/// Call `product.finish()` to confirm to the store that an approved order has been delivered.
/// This will change the product state from `APPROVED` to `FINISHED` (see [life-cycle](#life-cycle)).
///
/// As long as you keep the product in state `APPROVED`:
///
///  - the money may not be in your account (i.e. user isn't charged)
///  - you will receive the `approved` event each time the application starts,
///    where you should try again to finish the pending transaction.
///
/// ##### example use
/// ```js
/// store.when("product.id").approved(function(product){
///     // synchronous
///     app.unlockFeature();
///     product.finish();
/// });
/// ```
///
/// ```js
/// store.when("product.id").approved(function(product){
///     // asynchronous
///     app.downloadFeature(function() {
///         product.finish();
///     });
/// });
/// ```
store.Product.prototype.finish = function() {
    store.log.debug("product -> defer finishing " + this.id);
    defer(this, function() {
        store.log.debug("product -> finishing " + this.id);
        if (this.state !== store.FINISHED) {
            this.set('state', store.FINISHED);
            // The platform store should now handle the FINISHED event
            // and change the product status to VALID or OWNED.
        }
    });
};

/// #### `product.verify()` ##
///
/// Initiate purchase validation as defined by the [`store.validator`](#validator).
///
store.Product.prototype.verify = function() {
    var that = this;

    var nRetry = 0;

    // Callbacks set by the Promise
    var noop      = function() {};
    var doneCb    = noop;
    var successCb = noop;
    var expiredCb = noop;
    var errorCb   = noop;

    var tryValidation = function() {

        // No need to verifiy a which status isn't approved
        // It means it already has been
        if (that.state !== store.APPROVED)
            return;

        store._validator(that, function(success, data) {
            store.log.debug("verify -> " + JSON.stringify(success));
            if (success) {
                store.log.debug("verify -> success: " + JSON.stringify(data));
                store.utils.callExternal('verify.success', successCb, that, data);
                store.utils.callExternal('verify.done', doneCb, that);
                that.trigger("verified");
            }
            else {
                store.log.debug("verify -> error: " + JSON.stringify(data));
                var msg = (data && data.error && data.error.message ? data.error.message : '');
                var err = new store.Error({
                    code: store.ERR_VERIFICATION_FAILED,
                    message: "Transaction verification failed: " + msg
                });
                if (data.code === store.PURCHASE_EXPIRED) {
                    err = new store.Error({
                        code: store.ERR_PAYMENT_EXPIRED,
                        message: "Transaction expired: " + msg
                    });
                }
                if (data.code === store.PURCHASE_EXPIRED) {
                    if (nRetry < 2 && store._refreshForValidation) {
                        nRetry += 1;
                        store._refreshForValidation(function() {
                            delay(that, tryValidation, 300);
                        });
                    }
                    else {
                        store.error(err);
                        store.utils.callExternal('verify.error', errorCb, err);
                        store.utils.callExternal('verify.done', doneCb, that);
                        that.trigger("expired");
                        that.set("state", store.VALID);
                        store.utils.callExternal('verify.expired', expiredCb, that);
                    }
                }
                else if (nRetry < 4) {
                    // It failed... let's try one more time. Maybe the appStoreReceipt wasn't updated yet.
                    nRetry += 1;
                    delay(this, tryValidation, 1000 * nRetry * nRetry);
                }
                else {
                    store.log.debug("validation failed 5 times, stop retrying, trigger an error");
                    store.error(err);
                    store.utils.callExternal('verify.error', errorCb, err);
                    store.utils.callExternal('verify.done', doneCb, that);
                    that.trigger("unverified");
                }
            }
        });
    };

    defer(this, function() {
        if (that.state !== store.APPROVED) {
            var err = new store.Error({
                code: store.ERR_VERIFICATION_FAILED,
                message: "Product isn't in the APPROVED state"
            });
            store.error(err);
            store.utils.callExternal('verify.error', errorCb, err);
            store.utils.callExternal('verify.done', doneCb, that);
            return;
        }
    });

    // For some reason, the appStoreReceipt isn't always immediately available.
    delay(this, tryValidation, 1000);

    /// ##### return value
    /// A Promise with the following methods:
    ///
    var ret = {
        ///  - `done(function(product){})`
        ///    - called whether verification failed or succeeded.
        done:    function(cb) { doneCb = cb;    return this; },
        ///  - `expiredCb(function(product){})`
        ///    - called if the purchase expired.
        expired: function(cb) { expiredCb = cb; return this; },
        ///  - `success(function(product, purchaseData){})`
        ///    - called if the purchase is valid and verified.
        ///    - `purchaseData` is the device dependent transaction details
        ///      returned by the validator, which you can most probably ignore.
        success: function(cb) { successCb = cb; return this; },
        ///  - `error(function(err){})`
        ///    - validation failed, either because of expiry or communication
        ///      failure.
        ///    - `err` is a [store.Error object](#errors), with a code expected to be
        ///      `store.ERR_PAYMENT_EXPIRED` or `store.ERR_VERIFICATION_FAILED`.
        error:   function(cb) { errorCb = cb;   return this; }
    };
    ///

    return ret;
};

///
/// ### life-cycle
///
/// A product will change state during the application execution.
///
/// Find below a diagram of the different states a product can pass by.
///
///     REGISTERED +--> INVALID
///                |
///                +--> VALID +--> REQUESTED +--> INITIATED +-+
///                                                           |
///                     ^      +------------------------------+
///                     |      |
///                     |      +--> APPROVED +--> FINISHED +--> OWNED
///                     |                                  |
///                     +----------------------------------+
///
/// #### states definitions
///
///  - `REGISTERED`: right after being declared to the store using [`store.register()`](#register)
///  - `INVALID`: the server didn't recognize this product, it cannot be used.
///  - `VALID`: the server sent extra information about the product (`title`, `price` and such).
///  - `REQUESTED`: order (purchase) requested by the user
///  - `INITIATED`: order transmitted to the server
///  - `APPROVED`: purchase approved by server
///  - `FINISHED`: purchase delivered by the app (see [Finish a Purchase](#finish-a-purchase))
///  - `OWNED`: purchase is owned (only for non-consumable and subscriptions)
///
/// #### Notes
///
///  - When finished, a consumable product will get back to the `VALID` state, while other will enter the `OWNED` state.
///  - Any error in the purchase process will bring a product back to the `VALID` state.
///  - During application startup, products may go instantly from `REGISTERED` to `APPROVED` or `OWNED`, for example if they are purchased non-consumables or non-expired subscriptions.
///
/// #### state changes
///
/// Each time the product changes state, appropriate events is triggered.
///
/// Learn more about events [here](#events) and about listening to events [here](#when).
///

})();


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Lilloa 25: 292 (1952)

#### Original name
Conocybe tenerrima Singer

### Remarks
null


text:
org.apache.cassandra.auth
与认证(authenticate)和受权(authorize)相关的模块

认证包括CREATE/ALTER/DROP USER语句
受权包括GRANT/REVOKE/LIST PERMISSIONS语句

通过把信息存入表中来实现,keyspace是system_auth,总共有三张表
system_auth.users        在org.apache.cassandra.auth.Auth中建立
system_auth.credentials  在org.apache.cassandra.auth.PasswordAuthenticator中建立
system_auth.permissions  在org.apache.cassandra.auth.CassandraAuthorizer中建立

//注意,此表并不存密码,而是放到system_auth.credentials中
CREATE TABLE system_auth.users (
    name text,
    super boolean,
    PRIMARY KEY(name)
) WITH gc_grace_seconds=90 * 24 * 60 * 60 // 3 months(相当于有效期是3个月)

默认的超级用户是cassandra密码也是cassandra

CREATE TABLE system_auth.credentials (
    username text,
    salted_hash text, //使用BCrypt算法
	options map<text,text>, //这个字段目前未使用
    PRIMARY KEY(username)
) WITH gc_grace_seconds=90 * 24 * 60 * 60 // 3 months

CREATE TABLE system_auth.permissions (
    username text,
    resource text,
	permissions set<text>,
    PRIMARY KEY(username, resource)
) WITH gc_grace_seconds=90 * 24 * 60 * 60 // 3 months

上面三个表都是分布式的


text:
package com.jpeng.demo;

import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioGroup;
import com.jpeng.jptabbar.JPTabBar;
import com.jpeng.jptabbar.animate.AnimationType;

/**
 * Created by jpeng on 16-11-14.
 */
public class Tab2Pager extends Fragment implements RadioGroup.OnCheckedChangeListener {

    private RadioGroup mGroup;

    private JPTabBar mTabBar;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View layout =inflater.inflate(R.layout.tab2,null);
        init(layout);
        return layout;
    }

    private void init(View layout) {
        mTabBar = ((MainActivity)getActivity()).getTabbar();
        mGroup = (RadioGroup) layout.findViewById(R.id.radioGroup);
        mGroup.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        switch (checkedId){
            case R.id.radioButton1:
                mTabBar.setAnimation(AnimationType.SCALE);
                break;
            case R.id.radioButton2:
                mTabBar.setAnimation(AnimationType.SCALE2);
                break;
            case R.id.radioButton3:
                mTabBar.setAnimation(AnimationType.JUMP);
                break;
            case R.id.radioButton4:
                mTabBar.setAnimation(AnimationType.FLIP);

                break;
            case R.id.radioButton5:
                mTabBar.setAnimation(AnimationType.ROTATE);
                break;
        }
    }

}


text:
import { expect } from 'chai';
import Draft, { EditorState, SelectionState } from 'draft-js';

import applyBlockData from '../applyBlockData';

describe('applyBlockData', () => {
  const beforeRawContentState = {
    entityMap: {},
    blocks: [{
      key: 'item1',
      text: '',
      type: 'unstyled',
      depth: 0,
      inlineStyleRanges: [],
      entityRanges: [],
      data: {}
    }]
  };

  const afterRawContentState = {
    entityMap: {},
    blocks: [{
      key: 'item1',
      text: 'Changed text',
      type: 'header-one',
      depth: 0,
      inlineStyleRanges: [],
      entityRanges: [],
      data: {}
    }]
  };
  const selection = new SelectionState({
    anchorKey: 'item1',
    anchorOffset: 0,
    focusKey: 'item1',
    focusOffset: 0,
    isBackward: false,
    hasFocus: true
  });
  const contentState = Draft.convertFromRaw(beforeRawContentState);
  const editorState = EditorState.forceSelection(
    EditorState.createWithContent(contentState),
    selection
  );
  it('apply data', () => {
    const newEditorState = applyBlockData(editorState, 'item1', { text: 'Changed text', type: 'header-one' });
    expect(newEditorState).not.to.equal(editorState);
    const expected = Draft.convertToRaw(newEditorState.getCurrentContent());
    expect(
      expected
    ).to.deep.equal(
      afterRawContentState
    );
  });
});


text: <!DOCTYPE html>


text:
<?php
/*
	--------------------------------------------------------
	minimalstats
	created by Nicolas Da Mutten, www.nicolas.damutten.ch
	--------------------------------------------------------
*/
	namespace MinimalStats;

	use \Exception as Exception;

	class MSException extends Exception {

		protected $data;

		public function __construct($message = null, $code = 0, Exception $previous = null, $data = null) {

			$this->data = $data;

			parent::__construct($message, $code, $previous);

		}

		public function getData() {

			return $this->data;

		}
	}


text:
package com.oneliang.util.common;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public final class ClassUtil{

	private static final Map<Class<?>,ClassType> classTypeMap=new ConcurrentHashMap<Class<?>, ClassType>();

	private static final Map<Class<?>,Class<?>> baseClassMap=new ConcurrentHashMap<Class<?>,Class<?>>();
	private static final Map<Class<?>,Class<?>> simpleClassMap=new ConcurrentHashMap<Class<?>,Class<?>>();
	private static final Map<Class<?>,Class<?>> baseArrayMap=new ConcurrentHashMap<Class<?>,Class<?>>();
	private static final Map<Class<?>,Class<?>> simpleArrayMap=new ConcurrentHashMap<Class<?>,Class<?>>();
	private static final Map<String,Class<?>> baseClassNameMap=new ConcurrentHashMap<String,Class<?>>();
	private static final Map<String,Class<?>> simpleClassNameMap=new ConcurrentHashMap<String,Class<?>>();

	public static final ClassProcessor DEFAULT_CLASS_PROCESSOR=new DefaultClassProcessor();

	private ClassUtil(){}

	public static enum ClassType {
		JAVA_LANG_STRING,JAVA_LANG_CHARACTER,JAVA_LANG_SHORT,JAVA_LANG_INTEGER,JAVA_LANG_LONG,
		JAVA_LANG_FLOAT,JAVA_LANG_DOUBLE,JAVA_LANG_BOOLEAN,JAVA_LANG_BYTE,JAVA_UTIL_DATE,
		CHAR,BYTE,SHORT,INT,LONG,FLOAT,DOUBLE,BOOLEAN,
		JAVA_LANG_STRING_ARRAY,JAVA_LANG_CHARACTER_ARRAY,JAVA_LANG_SHORT_ARRAY,JAVA_LANG_INTEGER_ARRAY,JAVA_LANG_LONG_ARRAY,
		JAVA_LANG_FLOAT_ARRAY,JAVA_LANG_DOUBLE_ARRAY,JAVA_LANG_BOOLEAN_ARRAY,JAVA_LANG_BYTE_ARRAY,
		CHAR_ARRAY,BYTE_ARRAY,SHORT_ARRAY,INT_ARRAY,LONG_ARRAY,FLOAT_ARRAY,DOUBLE_ARRAY,BOOLEAN_ARRAY
	}

	static{
		classTypeMap.put(String.class, ClassType.JAVA_LANG_STRING);
		classTypeMap.put(Character.class, ClassType.JAVA_LANG_CHARACTER);
		classTypeMap.put(Short.class, ClassType.JAVA_LANG_SHORT);
		classTypeMap.put(Integer.class, ClassType.JAVA_LANG_INTEGER);
		classTypeMap.put(Long.class, ClassType.JAVA_LANG_LONG);
		classTypeMap.put(Float.class, ClassType.JAVA_LANG_FLOAT);
		classTypeMap.put(Double.class, ClassType.JAVA_LANG_DOUBLE);
		classTypeMap.put(Boolean.class, ClassType.JAVA_LANG_BOOLEAN);
		classTypeMap.put(Byte.class, ClassType.JAVA_LANG_BYTE);
		classTypeMap.put(Date.class, ClassType.JAVA_UTIL_DATE);
		classTypeMap.put(char.class, ClassType.CHAR);
		classTypeMap.put(byte.class, ClassType.BYTE);
		classTypeMap.put(short.class, ClassType.SHORT);
		classTypeMap.put(int.class, ClassType.INT);
		classTypeMap.put(long.class, ClassType.LONG);
		classTypeMap.put(float.class, ClassType.FLOAT);
		classTypeMap.put(double.class, ClassType.DOUBLE);
		classTypeMap.put(boolean.class, ClassType.BOOLEAN);

		classTypeMap.put(String[].class, ClassType.JAVA_LANG_STRING_ARRAY);
		classTypeMap.put(Character[].class, ClassType.JAVA_LANG_CHARACTER_ARRAY);
		classTypeMap.put(Short[].class, ClassType.JAVA_LANG_SHORT_ARRAY);
		classTypeMap.put(Integer[].class, ClassType.JAVA_LANG_INTEGER_ARRAY);
		classTypeMap.put(Long[].class, ClassType.JAVA_LANG_LONG_ARRAY);
		classTypeMap.put(Float[].class, ClassType.JAVA_LANG_FLOAT_ARRAY);
		classTypeMap.put(Double[].class, ClassType.JAVA_LANG_DOUBLE_ARRAY);
		classTypeMap.put(Boolean[].class, ClassType.JAVA_LANG_BOOLEAN_ARRAY);
		classTypeMap.put(Byte[].class, ClassType.JAVA_LANG_BYTE_ARRAY);
		classTypeMap.put(char[].class, ClassType.CHAR_ARRAY);
		classTypeMap.put(byte[].class, ClassType.BYTE_ARRAY);
		classTypeMap.put(short[].class, ClassType.SHORT_ARRAY);
		classTypeMap.put(int[].class, ClassType.INT_ARRAY);
		classTypeMap.put(long[].class, ClassType.LONG_ARRAY);
		classTypeMap.put(float[].class, ClassType.FLOAT_ARRAY);
		classTypeMap.put(double[].class, ClassType.DOUBLE_ARRAY);
		classTypeMap.put(boolean[].class, ClassType.BOOLEAN_ARRAY);

		baseClassMap.put(char.class, char.class);
		baseClassMap.put(byte.class, byte.class);
		baseClassMap.put(short.class, short.class);
		baseClassMap.put(int.class, int.class);
		baseClassMap.put(long.class, long.class);
		baseClassMap.put(float.class, float.class);
		baseClassMap.put(double.class, double.class);
		baseClassMap.put(boolean.class, boolean.class);

		simpleClassMap.put(String.class, String.class);
		simpleClassMap.put(Character.class, Character.class);
		simpleClassMap.put(Byte.class, Byte.class);
		simpleClassMap.put(Short.class, Short.class);
		simpleClassMap.put(Integer.class, Integer.class);
		simpleClassMap.put(Long.class, Long.class);
		simpleClassMap.put(Float.class, Float.class);
		simpleClassMap.put(Double.class, Double.class);
		simpleClassMap.put(Boolean.class, Boolean.class);

		baseArrayMap.put(char[].class, char[].class);
		baseArrayMap.put(byte[].class, byte[].class);
		baseArrayMap.put(short[].class, short[].class);
		baseArrayMap.put(int[].class, int[].class);
		baseArrayMap.put(long[].class, long[].class);
		baseArrayMap.put(float[].class, float[].class);
		baseArrayMap.put(double[].class, double[].class);
		baseArrayMap.put(boolean[].class, boolean[].class);

		simpleArrayMap.put(String[].class, String[].class);
		simpleArrayMap.put(Character[].class, Character[].class);
		simpleArrayMap.put(Short[].class, Short[].class);
		simpleArrayMap.put(Integer[].class, Integer[].class);
		simpleArrayMap.put(Long[].class, Long[].class);
		simpleArrayMap.put(Float[].class, Float[].class);
		simpleArrayMap.put(Double[].class, Double[].class);
		simpleArrayMap.put(Boolean[].class, Boolean[].class);
		simpleArrayMap.put(Byte[].class, Byte[].class);

		baseClassNameMap.put(char.class.getName(), char.class);
		baseClassNameMap.put(byte.class.getName(), byte.class);
		baseClassNameMap.put(short.class.getName(), short.class);
		baseClassNameMap.put(int.class.getName(), int.class);
		baseClassNameMap.put(long.class.getName(), long.class);
		baseClassNameMap.put(float.class.getName(), float.class);
		baseClassNameMap.put(double.class.getName(), double.class);
		baseClassNameMap.put(boolean.class.getName(), boolean.class);

		simpleClassNameMap.put(String.class.getName(), String.class);
		simpleClassNameMap.put(Character.class.getName(), Character.class);
		simpleClassNameMap.put(Byte.class.getName(), Byte.class);
		simpleClassNameMap.put(Short.class.getName(), Short.class);
		simpleClassNameMap.put(Integer.class.getName(), Integer.class);
		simpleClassNameMap.put(Long.class.getName(), Long.class);
		simpleClassNameMap.put(Float.class.getName(), Float.class);
		simpleClassNameMap.put(Double.class.getName(), Double.class);
		simpleClassNameMap.put(Boolean.class.getName(), Boolean.class);
	}

	/**
	 * get class with class name
	 * @param className
	 * @return Type
	 * @throws Exception class not found
	 */
	public static Class<?> getClass(final ClassLoader classLoader, final String className) throws Exception{
		Class<?> clazz=null;
		if(classLoader!=null&&className!=null){
			if(baseClassNameMap.containsKey(className)){
				clazz=baseClassNameMap.get(className);
			}else{
				clazz=classLoader.loadClass(className);
			}
		}
		return clazz;
	}

	/**
	 * getClassType,for manual judge use
	 * @param clazz
	 * @return ClassType
	 */
	public static ClassType getClassType(Class<?> clazz){
		return classTypeMap.get(clazz);
	}

	/**
	 * is base class or not
	 * include boolean short int long float double byte char
	 * @param clazz
	 * @return boolean
	 */
	public static boolean isBaseClass(Class<?> clazz){
		boolean result=false;
		if(clazz!=null){
			if(baseClassMap.containsKey(clazz)){
				result=true;
			}
		}
		return result;
	}

	/**
	 * is base class or not
	 * include boolean short int long float double byte char
	 * @param className
	 * @return boolean
	 */
	public static boolean isBaseClass(String className){
		boolean result=false;
		if(className!=null){
			if(baseClassNameMap.containsKey(className)){
				result=true;
			}
		}
		return result;
	}

	/**
	 * simple class or not
	 * include Boolean Short Integer Long Float Double Byte String
	 * @param clazz
	 * @return boolean
	 */
	public static boolean isSimpleClass(Class<?> clazz){
		boolean result=false;
		if(clazz!=null){
			if(simpleClassMap.containsKey(clazz)){
				result=true;
			}
		}
		return result;
	}

	/**
	 * simple class or not
	 * include Boolean Short Integer Long Float Double Byte String
	 * @param className
	 * @return boolean
	 */
	public static boolean isSimpleClass(String className){
		boolean result=false;
		if(className!=null){
			if(simpleClassNameMap.containsKey(className)){
				result=true;
			}
		}
		return result;
	}

	/**
	 * basic array or not
	 * @param clazz
	 * @return boolean
	 */
	public static boolean isBaseArray(Class<?> clazz){
		boolean result=false;
		if(clazz!=null){
			if(baseArrayMap.containsKey(clazz)){
				result=true;
			}
		}
		return result;
	}

	/**
	 * simple array or not
	 * @param clazz
	 * @return boolean
	 */
	public static boolean isSimpleArray(Class<?> clazz){
		boolean result=false;
		if(clazz!=null){
			if(simpleArrayMap.containsKey(clazz)){
				result=true;
			}
		}
		return result;
	}

	/**
	 * change type
	 * @param <T>
	 * @param clazz
	 * @param values
	 * @return Object
	 */
	public static <T extends Object> T changeType(Class<T> clazz,String[] values){
		return changeType(clazz,values,null,DEFAULT_CLASS_PROCESSOR);
	}

	/**
	 * change type width class processor
	 * @param <T>
	 * @param clazz
	 * @param values
	 * @param classProcessor
	 * @return Object
	 */
	public static <T extends Object> T changeType(Class<T> clazz,String[] values,ClassProcessor classProcessor){
		return changeType(clazz, values, null, classProcessor);
	}

	/**
	 * change type
	 * @param <T>
	 * @param clazz
	 * @param values
	 * @param fieldName is null if not exist
	 * @return Object
	 */
	public static <T extends Object> T changeType(Class<T> clazz,String[] values,String fieldName){
		return changeType(clazz,values,fieldName,DEFAULT_CLASS_PROCESSOR);
	}

	/**
	 * change type width class processor
	 * @param <T>
	 * @param clazz
	 * @param values
	 * @param fieldName is null if not exist
	 * @param classProcessor
	 * @return Object
	 */
	@SuppressWarnings("unchecked")
	public static <T extends Object> T changeType(Class<T> clazz,String[] values,String fieldName,ClassProcessor classProcessor){
		Object object=null;
		if(classProcessor!=null){
			object=classProcessor.changeClassProcess(clazz, values,fieldName);
		}else{
			throw new NullPointerException("ClassProcessor can not be null.");
		}
		return (T)object;
	}

	public static interface ClassProcessor{

		/**
		 * change class process
		 * @param clazz
		 * @param values
		 * @param fieldName is null if not exist
		 * @return Object
		 */
		public abstract Object changeClassProcess(Class<?> clazz,String[] values,String fieldName);
	}
}


text:
Please read the following resources to get an overview of Ruby and Rails security before opening PRs.

[Ruby on Rails Security Cheatsheet](https://www.owasp.org/index.php/Ruby_on_Rails_Cheatsheet)

Get familiar with Brakeman and run it often. It runs as part of the build but it is easier to run it before opening your PR and fixing it there.

[Brakeman Scanner](http://brakemanscanner.org/)

### Cryptography
If you need to encrypt, sign or hash something here are the recommended libraries. Do not roll your own library and use only libraries that have been reviewed by the community.

#### Hashing
Ruby has built in hash function that can be used. MD5 and SHA1 are considered broken and should not be used. SHA2 is still considered secure.

Example:
```
> require 'digest'
> Digest::SHA2.hexdigest 'abc'
> "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
```

#### Password hashing
Bcrypt or Scrypt are the preferred methods for hashing passwords. More details are here:

[Bcrypt](https://github.com/codahale/bcrypt-ruby)

#### Encryption
RbNaCl is a great library that makes encryption in Ruby relatively easy. Be cautious when deciding to use encryption, there are a million ways to make a mistake and they're often overlooked.

[RbNaCl](https://github.com/cryptosphere/rbnacl)

#### Signing
Rails has a built in method to sign messages.

[Message Verifier](http://api.rubyonrails.org/classes/ActiveSupport/MessageVerifier.html)

#### Random Token
If you need to generate a random token, for a reset password email for example, use SecureRandom that is built into Ruby.

[SecureRandom](https://ruby-doc.org/stdlib-2.3.0/libdoc/securerandom/rdoc/SecureRandom.html)

#### More reading:

Checkout [this document]( https://github.com/DCAFEngineering/dcaf_case_management/docs/SECURITY_INTRO.md) on basic Ruby on Rails security.

[Ruby on Rails Security Guide](http://guides.rubyonrails.org/security.html)

[An Overview of Cryptography](http://www.garykessler.net/library/crypto.html)

[Password Hashing](https://crackstation.net/hashing-security.htm)