text:
Other potential future criteria
=========================

Here are some other potential criteria.

We currently plan to launch with a single badge level (once it is ready).
There may eventually be multiple levels (bronze, silver, gold) or
other badges (with a prerequisite) later.
We are currently leaning towards using the Olympic system naming
(bronze, silver, gold) since these are widely known; the LEED naming
(with platinum at the top) is less well-known, and using the Olympic
naming would provide room for another (platinum) level if needed.
Then the "basic" level would be the same as a "bronze" level.

To help organize these potential criteria, they are currently grouped
in terms of a potential future silver, potential future gold, and
other potential criteria.
There is no guarantee that the final criteria will be the same,
or even grouped the same way.
This list of potential future criteria is even less mature than the
list of basic best practices; recommendations welcome.
As the criteria become more mature, we expect some criteria to move between
the current criteria and these potential future criteria (in both directions).
In particular, we expect a number of the SHOULD or RECOMMENDED criteria
at lower levels to become MUST in higher/later badges.

Eventually these criteria will be worded per
[RFC 2119](https://tools.ietf.org/html/rfc2119).

Potential silver criteria
-------------------------

*   **Achieve the lower (basic/bronze) badge**.
*   **Build and test:**
    -   **Continuous integration**.
        An automated test suite MUST applied on each check-in to a shared repository, at least for some branches, with a generated report available to at least project members on success or failure of the tests.  This test suite SHOULD be applied across many platforms where appropriate.  *Rationale*:  Continuous integration provides much more rapid feedback on whether or not changes will cause test failures, including regressions.
    -   *Tests are rigorously added for new functionality*.
        There MUST be a stated policy that when major new functionality is added, tests of that functionality MUST be added to an automated test suite, at least in the documentation for creating change proposals.  There MUST be evidence that such tests are being added in the most recent major changes to the project.
    -   *Regression tests*.
        When a bug is fixed, a regression test MUST normally be added to the automated test suite to prevent its reoccurrence.
    -   *Reproduceable build*.
         It MUST be possible to rebuild executables that are bit-for-bit identical, given the same executables of the tools used for building.  This criterion is automatically met if there is no process for creating a separate executable or package.  *Rationale*:  Reproduceable builds make it much easier to verify that the executable and source code of a program correspond, countering certain kinds of malicious attacks.
*   Code/build requirements:
    -   Coding standards / coding style guide (typically by pointing to something).  There are a number of coding standards that can be recommended for specific languages.  Widely-used coding standards that include ways to reduce the likelihood of defects (including vulnerabilities) might be especially helpful.  Projects can create their own coding standard by referring to an existing one and then adding their own additions or exceptions.  There are a number of secure coding standards, e.g., the SEI CERT's at https://www.securecoding.cert.org/
    -   Program can use the local version of system library/applications (so vulnerable ones easily replaced).  Many OSS programs are distributed with "convenience libraries" that are local copies of standard libraries (possibly forked).  However, if the program *must* use these local (forked) copies, then updating the "standard" libraries as a security update will leaved these additional copies still vulnerable. This is especially an issue for cloud-based systems (e.g., Heroku); if the cloud provider updates their "standard" libaries but the program won't use them, then the updates don't actually help.  In some cases it's important to use the "other" version; the goal here is to make it *possible* to easily use the standard version. See, e.g., http://spot.livejournal.com/312320.html .
*   Security analysis:
    -   Dependencies (including embedded dependencies) are periodically checked for known vulnerabilities (using an origin analyzer, e.g., Sonatype, Black Duck, Codenomicon AppScan, OWASP Dependency-Check), and if they have known vulnerabilities, they are updated or verified as unexploitable.  It is acceptable if the components' vulnerability cannot be exploited, but this analysis is difficult and it is sometimes easier to simply update or fix the part.  Developers must periodically re-scan to look for newly found publicly known vulnerabilities in the components they use, since new vulnerabilities are continuously being discovered.
*   Release:
    -   Releases MUST be cryptographically signed.  These may be implemented as signed git tags (using cryptographic digital signatures).  There MUST be a way for users to obtain the public keys used for signing so that they can verify the signature, and there MUST be a documented process explaining to users how they can verify the signature.
    -   Releases MUST be downloadable through a channel that both encrypts and authenticates (e.g., TLS).  That way, third parties will not be able to determine exactly what version is being downloaded, and this also provides some verification that the correct software is being downloaded from the site.

It would be quite plausible to add many requirements specific to security.
For example, it would be plausible to require that a system meet the
requirements (or a specified subset) of the
[OWASP Application Security Verification Standard Project](https://www.owasp.org/index.php/Category:OWASP_Application_Security_Verification_Standard_Project)
or the
[Securing Web Application Technologies (SWAT) Checklist](https://software-security.sans.org/resources/swat).
Note that both of these focus only on web applications.

Potential gold criteria
-----------------------

*   Achieve the lower (silver) badge.
*   General criteria:
    -   Roadmap exists.  There should be some information on where the project is going or not going.
    -   Posted list of small project tasks for new users.  These new tasks need not be adding functionality; they can be improving documentation, adding test cases, or anything else that aids the project and helps the contributor understand more about the project.  There SHOULD be at least 3 small tasks made available over a one-year period that have been accepted by a relatively new contributor (those who started contributing less than a year ago) or left available (unimplemented by experienced developers) for at least 3 weeks.  *Rationale*:  Identified small tasks make it easier for new potential contributors to become involved in a project, and projects with more contributors have an increased likelihood of continuing.
    -   Multiple contributors from more than one organization.
    -   License statement in each file (aka per-file licensing).
    -   (Ideal) Copyright notice in each file, e.g., "Copyright [year project started] - [current year], [project founder] and the [project name] contributors."
*   Quality:
    -   Commits reviewed.  There should be evidence that at least one other person (other than the committer) are normally reviewing commits.
    -   Automated test suite covers 100% of branches in source code.  We will *not* add 100% branch coverage to the *basic* set of criteria.  Some projects (like SQLite) do achieve this, but for some projects (such as the Linux kernel) this would be exceptionally difficult to achieve.  Some higher/different related badge *might* add 100% branch coverage.

Potential other criteria
------------------------

*   Issue tracking (This must be different for big projects like the Linux kernel; it is not clear how to capture that.):
    -   Issue tracking for defects.
    -   Issue tracking for requirements/enhancement requests.
    -   Bug/vulnerability report responsiveness, e.g., commitment to respond to any vulnerability report within (say) 14 days.
    -   If this is a project fork, actively working to become sustainable by either growing its community *or* working to heal the fork (e.g., contribute to the mainline).
*   Quality:
    -   Automated test suite covers >=X% branches of source code (80% considered good).
    -   Documented test plan.
*   Security:
    -   "Announcement" mailing list for new versions (at least for security updates).
    -   All inputs from untrusted sources checked against whitelist (not a blacklist) and/or escaped before being transmitted to other users.
    -   Privileges limited/minimized.
    -   Attack surface documented and minimized.
    -   Automated regression test suite includes at least one check for rejection of invalid data for each input field.  Rationale: Many regression test suites check only for perfect data; attackers will instead provide invalid data, and programs need to protect themselves against it.
    -   If passwords are stored to allow users to log into the software, the passwords must be stored as iterated per-user salted cryptographic hashes (at least) and *not* in the clear or as simple hashes.
    -   Developers contributing a majority of the software (over 50%) have learned how to develop secure software.
    -   Standard security advisory template and a pre-notification process (useful for big projects; see Xen project as an example).
    -   All inputs from potentially untrusted sources are checked to ensure they are valid (a *whitelist*).  Invalid inputs are rejected.  Note that comparing against a list of "bad formats" (a *blacklist*) is not enough.  In particular, numbers are converted and checked if they are between their minimum and maximum (inclusive), and text strings are checked to ensure that they are valid text patterns.
    -   OWASP Application Security Verification Standard (ASVS).
    -   SANS' Securing Web Application Technologies (SWAT) criteria.
    -   Privacy requirements.  The distribution system does not reveal to third parties what software or version number is being distributed, or to who.  The distribution system does not require users to identify themselves nor does it perform passive machine fingerprinting.
*   Security analysis:
    -   Current/past security review of the code.
    -   Must have a process for rapidly fixing vulnerabilities and releasing the updated software.  Note that having a good test suite makes it easier to make changes and be confident the system still works.  Also note that OSS projects are often embedded in larger systems and projects cannot control the larger projects they are in.
    -   An automated test suite must achieve at least an aggregate 80% branch coverage (the goal is to cover a significant portion of the program; this can be a combination of unit tests and larger integration tests).

We are considering moving the criteria continuous integration
and reproduceable builds into the basic best practices criteria.

In the future we might add some criteria that a project has to meet
some subset of (e.g., it must meet at least 3 of 5 criteria).

Improving the criteria
======================

We are hoping to get good suggestions and feedback from the public;
please contribute!

See [criteria](./criteria.md) for the main current set of criteria.
You may also want to see the "[background](./background.md)" file
for more information about these criteria,
and the "[implementation](./implementation.md)" notes
about the BadgeApp application.


text:
Deface::Override.new(
  virtual_path: "spree/admin/products/_form",
  name: "solidus_subscriptions_product_subscribable_checkbox",
  insert_after: "[data-hook='admin_product_form_promotionable']",
  partial: "spree/admin/products/subscribable_checkbox"
)

redpajama_set_name: RedPajamaGithub


text:
A simple curses client for Google Play Music.

![Queue mode screenshot][ss1]

I started this project because [thunner][thunner] didn't support Two-Factor
Authentication... or at least I couldn't figure it out. Anyways, writing your
own tool is half the fun, right?

## Disclaimer

This project isn't really all that great to use. So far, it has the absolutely
minimum amount of functionality/usability that I needed and I've basically
stopped there. Please don't expect a full-featured client at this point!

## Dependencies

`gpmplayer` depends on the wonderful [gmusicapi][gmusicapi]. It also uses
appdirs for figuring out where to put its files.

It also uses `mplayer` to actually, y'know, *play* the songs. So you'll need
that installed (and obviously in your PATH) as well.

```bash
sudo pip2 install gmusicapi appdirs
```

## Config

You just need a `config.ini` in `$XDG_CONFIG_HOME/gpmplayer/` in the following format:

```ini
[gpmplayer]
email = your_google_email@example.com
password = app_specific_password
mobile-id = your_device_id
```

You can read elsewhere on how to get the device ID. Apparently you can use your
MAC address or something as well or something, but whatever. You're a smart
person and you'll figure it out.

Once your config is ready, you can fire up the app.

## Usage

Here are the controls:

    j     - Move down
    k     - Move up
    Enter - Select
    p     - Jump to your list of playlists
    z     - Toggle shuffle

Fairly self-explanatory, I think.

## Install

    sudo ln -s "$PWD/gpmplayer" /usr/bin/gpmplayer

## Uninstall

    sudo rm -f /usr/bin/gpmplayer

## Bugs

* None at this moment...? Lots of missing functionality...

## To Do

* Jump to queue view
* Shortcuts (and functionality) for next song, pause, prev song, etc.
* In-playlist/in-queue fuzzy search
* Some way to pipe status out (for displaying on bar)
* Google Play Search/radio functionality
* Moar configuration options
* Better queue management
* Show song progress
* Skipping around in songs
* Non-sucky, configurable interface
* Async goodness
* Parallelize where possible
* Prefetching next few songs
* Caching requests that generally return a larger payload

## License

You can find it [here][license].

[ss1]: https://github.com/lytedev/gpmplayer/blob/pr-assets/screenshots/1.png?raw=true
[thunner]: https://github.com/malcolmstill/thunner
[gmusicapi]: https://github.com/simon-weber/gmusicapi
[license]: https://github.com/lytedev/gpmplayer/blob/master/LICENSE


text:
namespace web {

struct FakeJavaScriptDialog {
  FakeJavaScriptDialog();
  ~FakeJavaScriptDialog();
  WebState* web_state = nullptr;
  GURL origin_url;
  JavaScriptDialogType java_script_dialog_type;
  NSString* message_text;
  NSString* default_prompt_text;
  DialogClosedCallback callback;
};

// Fake presenter to check that the JavaScriptDialogPresenter methods are called
// as expected. `RunJavaScriptDialog` always calls `callback` with
// `callback_success_argument` and `callback_user_input_argument` values.
class FakeJavaScriptDialogPresenter : public JavaScriptDialogPresenter {
 public:
  FakeJavaScriptDialogPresenter();
  ~FakeJavaScriptDialogPresenter() override;

  // JavaScriptDialogPresenter overrides:
  void RunJavaScriptDialog(WebState* web_state,
                           const GURL& origin_url,
                           JavaScriptDialogType java_script_dialog_type,
                           NSString* message_text,
                           NSString* default_prompt_text,
                           DialogClosedCallback callback) override;
  void CancelDialogs(WebState* web_state) override;

  // Whether callback execution is paused.  If a dialog presentation is
  // requested while true, the callback will not be executed until unpaused.
  bool callback_execution_paused() const { return callback_execution_paused_; }
  void set_callback_execution_paused(bool callback_execution_paused) {
    if (callback_execution_paused_ == callback_execution_paused)
      return;
    callback_execution_paused_ = callback_execution_paused;
    if (!callback_execution_paused_)
      ExecuteAllDialogCallbacks();
  }

  // True if the JavaScriptDialogPresenter CancelDialogs method has been called.
  bool cancel_dialogs_called() const { return cancel_dialogs_called_; }

  // Returns a vector of requested dialogs.
  const std::vector<std::unique_ptr<FakeJavaScriptDialog>>& requested_dialogs()
      const {
    return requested_dialogs_;
  }

  // Sets `success` argument to be used for RunJavaScriptDialog callback.
  void set_callback_success_argument(bool success) {
    callback_success_argument_ = success;
  }

  // Sets `user_input` argument to be used for RunJavaScriptDialog callback.
  void set_callback_user_input_argument(NSString* user_input) {
    callback_user_input_argument_ = user_input;
  }

 private:
  // Executes all non-executed callbacks in `requested_dialogs_`.
  void ExecuteAllDialogCallbacks();
  // Executes the callback for `dialog`.
  void ExecuteDialogCallback(FakeJavaScriptDialog* dialog);

  bool callback_execution_paused_ = false;
  bool cancel_dialogs_called_ = false;
  std::vector<std::unique_ptr<FakeJavaScriptDialog>> requested_dialogs_;
  bool callback_success_argument_ = false;
  NSString* callback_user_input_argument_;
};

}  // namespace web

#endif  // IOS_WEB_PUBLIC_TEST_FAKES_FAKE_JAVA_SCRIPT_DIALOG_PRESENTER_H_


text:
function str = get_arch_id ()
    % str = GET_ARCH_ID ()
    %
    % Retrieves OpenCV arch identifier for Windows platforms (i.e., x86 for
    % win32 and x64 for win64). For other platforms, an empty string is
    % returned.
    %
    % This function is primarily aimed for determining OpenCV library or
    % binary path in build/configuration scripts.

    if ispc()
        if isequal(computer('arch'), 'win64')
            str = 'x64';
        else
            str = 'x86';
        end
    else
        str = '';
    end
end


text:
<!doctype html>

    <title>Code coverage report for lib/cache/Cache.js</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="../../prettify.css" />
    <link rel="stylesheet" href="../../base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

      all files / lib/cache/ Cache.js

        100%
        Statements
        46/46

        100%
        Branches
        16/16

        100%
        Functions
        9/9

        100%
        Lines
        46/46

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108

1×
1×
1×
1×

1×

1×
720×

720×
1×

719×
3×

719×
719×

719×
719×
719×
719×

1×

178×

178×
178×
113×

65×
4×
4×
4×

61×

61×
8×
8×

61×

1×
4703×
18×
18×

4703×
4703×

1×
71×
71×

1×
4×
4×

1×
4×

1×

'use strict';

var _ = require('underscore');
var CacheEntry = require('./CacheEntry');
var CacheStats = require('./CacheStats');
var MemoryStore = require('./MemoryStore');

/**
 * Cache defaults
 * @type {{store: (*|MemoryStore|exports), ttl: number, tti: number}}
 */
var defaults = {
  store: MemoryStore,
  ttl: 5 * 60,
  tti: 5 * 60
};

/**
 * Cache abstractions
 * A unified interface to different implementations of data caching.
 *
 * @param [store=MemoryStore]
 * @param {number=} [ttl=5*60] - time to live in seconds
 * @param {number=} [tti=5*60] - time to idle in seconds
 * @params {object} options - cache configuration options
 * @constructor
 */
function Cache(options) {
  options = options || {};

  if (!(this instanceof Cache)) {
    return new Cache(options);
  }

  if (typeof options === 'function'){
    options = { store: options };
  }

  _.defaults(options, defaults);
  var Store = options.store;

  this.ttl = options.ttl;
  this.tti = options.tti;
  this.store = new Store(options);
  this.stats = new CacheStats();
}

Cache.prototype.get = function (key, cb) {

  var self = this;

  self.store.get(key, function (err, entry) {
    if (err || !entry) {
      return cb(err, null);
    }

    if (entry.isExpired(self.ttl, self.tti)) {
      self.stats.miss(true);
      return self.store.delete(key, function (err) {
        return cb(err, null);
      });
    }

    self.stats.hit();
    // what point to touch entry if we not updating cache store
    // will work for memory store but will not for redis store

    if (self.ttl !== self.tti) {
      entry.touch();
      self.store.set(key, entry, function(){});
    }

    return cb(null, entry.value);
  });
};

/**
 *
 * @param key
 * @param value
 * @param {boolean|function} [_new=true]
 * @param {function} cb
 */
Cache.prototype.put = function (key, value, _new, cb) {
  if (typeof _new === 'function') {
    cb = _new;
    _new = true;
  }
  this.stats.put(_new);
  this.store.set(key, new CacheEntry(value), cb);
};

Cache.prototype.delete = function (key, cb) {
  this.stats.delete();
  this.store.delete(key, cb);
};

Cache.prototype.clear = function (cb) {
  this.stats.clear();
  this.store.clear(cb);
};

Cache.prototype.size = function (cb) {
  this.store.size(cb);
};

module.exports = Cache;

  Code coverage
  generated by istanbul at Thu Mar 24 2016 15:28:42 GMT-0700 (PDT)


text:
#include "controllers/keyvalue/KeyValueStoreService.h"

namespace org::apache::nifi::minifi::controllers {

KeyValueStoreService::KeyValueStoreService(std::string name, const utils::Identifier& uuid /*= utils::Identifier()*/)
    : ControllerService(std::move(name), uuid) {
}

KeyValueStoreService::~KeyValueStoreService() = default;

void KeyValueStoreService::yield() {
}

bool KeyValueStoreService::isRunning() {
  return getState() == core::controller::ControllerServiceState::ENABLED;
}

bool KeyValueStoreService::isWorkAvailable() {
  return false;
}

}  // namespace org::apache::nifi::minifi::controllers


text:
import datetime
import urlparse
import re
import lmdb
import pytz
import iso8601
import justext
import xmlrpclib
import urllib2
import threading
from BeautifulSoup import BeautifulSoup

from models import Page, Site, Label

DB_PATH = '/tmp/dbtest'
now = datetime.datetime.utcnow().replace(tzinfo=pytz.utc)

def __open_env():
    ''' Open LMDB instance'''
    return lmdb.open(DB_PATH, max_dbs=1)

def rebuild_url_lookup():
    ''' Rebuld URL lookup data'''
    print "Rebuilding URL"
    env = __open_env()
    urls = env.open_db('urls')
    with env.begin(db=urls, write=True) as txn:
        cursor = txn.cursor()
        for k, v in cursor:
            txn.delete(k)
        for item in Page.objects():
            t = item.url.encode('utf-8')
            txn.put(t, '1')
    print "Done"
    env.close()

env = __open_env()

rebuild = False
with env.begin(write=True) as txn:
    tres = txn.get('lastdate')
    print tres
    if tres:
        res = iso8601.parse_date(tres)
        res.replace(tzinfo=pytz.utc)
        delta = now - res
        if delta > datetime.timedelta(days=1):
            rebuild = True
    else:
        rebuild = True
    txn.put('lastdate', now.isoformat())

    if rebuild:
        rebuild_url_lookup()
    else:
        print "URLs OK"

env.close()

def add_to_lookup(url):
    '''
    Add URL to URL lookup

    :param url: URL to add
    :type url: str
    '''
    env = __open_env()
    urls = env.open_db('urls')
    with env.begin(db=urls, write=True) as txn:
        txn.put(url.encode('utf-8'), '1')
    env.close()

def addtodb(page, lookupurl, classes):
    '''
    Add page to MongoDB

    :param page: info about page
    :type page: dict
    :param lookupurl: URL of parent site
    :type lookupurl: str
    :param classes: result of classification for given page
    :type classes: array of ints
    '''
    parent = Site.objects(url=lookupurl).first()
    nov = Page(url=page['url'], btext=page['btext'])
    if parent:
        nov.parent = parent
    for c in classes:
        label = Label.objects(id=c).first()
        nov.label_model.append(label)
        print "label added"
    nov.save()
    add_to_lookup(page['url'])
    print "Page added to db"

client = xmlrpclib.ServerProxy('http://localhost:8001', allow_none=True)

def crawl_page(url, parenturl=None):
    '''
    Crawl single page and add it to db

    :param url: URL of webpage to be crawled
    :type url: str
    :param parenturl: URL of parent website, obtained automatically if ommited
    :type parenturl: str
    '''
    if not newurl(url):
        return
    # if not parenturl:
    #     parsed = urlparse.urlparse(url)
    #     parenturl = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed)
    res = []
    urls = []
    try:
        response = urllib2.urlopen(url)
    except Exception:
        return urls
    if response.info().maintype == 'text':
        print url
        body = response.read()
        response.close()
        soup = BeautifulSoup(body)

        for tag in soup.findAll('a', href=True):
            tag['href'] = urlparse.urljoin(url, tag['href'])
            urls.append(tag['href'])

        if not body:
            return urls
        paragraphs = justext.justext(body, justext.get_stoplist("Czech"))
        for para in paragraphs:
            if not para.is_boilerplate:
                res.append(para.text)
        btext = ' '.join(res)
        isedu = client.classify_edu(btext)[0]
        page = {'url': url, 'btext': btext}
        print isedu
        if isedu == 2:  # is educational
            cls = client.classify(btext)
            addtodb(page, parenturl, cls)
    return urls

def __crawl_address(site):
    '''
    Crawl entire site

    :param url: URL of website
    :type url: str
    '''
    print site
    urls_queue = [site]
    urls_found = []
    urls_done = []
    domain = ''

    mre = re.match('^https?://[^/]*', site, re.IGNORECASE)
    if mre:
        domain = mre.group(0)

    while len(urls_queue) > 0:

        url = urls_queue.pop()
        urls_done.append(url)

        found = crawl_page(url)

        for uf in found:
            if not uf.startswith(domain):
                continue

            if uf not in urls_found:
                urls_found.append(uf)

            if uf not in urls_queue and uf not in urls_done:
                urls_queue.append(uf)

        print "Done %d; Queued %d; Found %d" % (len(urls_done), len(urls_queue), len(urls_found))

def newurl(url):
    '''
    Is URL new? (ie. not in lookup)

    :param url: URL to check
    :type url: str
    :returns: is URL new?
    :rtype: bool
    '''
    env = __open_env()
    urls = env.open_db('urls')
    with env.begin(db=urls, write=True) as txn:
        t = url.encode('utf-8')
        tres = txn.get(t)
        if tres:
            res = False
        else:
            res = True
    env.close()
    print res
    return res

def crawl(url):
    '''
    Crawl entire site

    :param url: URL of website
    :type url: str
    '''
    if not url.startswith('http://') and not url.startswith('https://'):
        url = 'http://%s/' % url
    if newurl(url):
        print "New URL"
    else:
        print "URL already in DB"
        return
    print url
    # get correct title, detect language
    p = Site(title=url, url=url, show=0)
    p.published = datetime.datetime.today()
    p.save()

    thr = threading.Thread(target=__crawl_address, args=[url], kwargs={})
    thr.start()
    return


text:
Imports System.Data
Imports System.Data.SqlClient

Partial Class members_grantphotoreq
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub

    Protected Sub Page_LoadComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LoadComplete
        Dim cf As New comonfunctions
        Dim sql As String = ""
        Dim myreader As SqlDataReader
        Dim myreader2 As SqlDataReader
        Dim cn As New SqlConnection
        Dim cmd As New SqlCommand
        Dim cmd2 As New SqlCommand

        Dim email As String = ""
        Dim passw As String = ""
        Dim regmsg As String = ""
        Dim msg As String = ""

        Try
            sql = "select email from profile where pid=" & Request.QueryString("pid") & ""
            cn.ConnectionString = cf.friendshipdb
            cn.Open()

            cmd.Connection = cn
            cmd.CommandText = sql
            myreader = cmd.ExecuteReader

            If myreader.HasRows = True Then
                While myreader.Read
                    email = myreader.GetString(0).ToString
                End While
            End If

            '//after getting email send the password
            sql = "select top 1 passw from photo where pid=" & Session("pid") & " "
            cmd2.Connection = cn
            cmd2.CommandText = sql

            myreader2 = cmd2.ExecuteReader

            If myreader2.HasRows = True Then
                While myreader2.Read
                    passw = myreader2.GetValue(0).ToString
                End While
            End If

            regmsg = "
 " & Session("fname").ToString & " had given you photo password"
            regmsg = regmsg & "
 Your Photo Password Request Granted
 you can see
 http://www." & cf.websitename & "/viewprofile.aspx?pid=" & Session("pid")
            regmsg = regmsg & "
 Password is " & passw & "
"

            msg = cf.send25("requestgranted", "Photo Password Request Granted", email, regmsg)

            passw = cf.delrecordset("delete from passwordrequests where frompid=" & Request.QueryString("pid").ToString & " and topid=" & Session("pid").ToString & "")

            Label1.Text = msg

            cn.Close()
        Catch ex As Exception
            Response.Write(ex.Message)
        End Try

    End Sub
End Class


text:
@dir = "/var/www/web"

worker_processes 2
working_directory @dir

timeout 30

listen "#{@dir}/tmp/sockets/unicorn.sock", :backlog => 64

pid "#{@dir}/tmp/pids/unicorn.pid"

stderr_path "#{@dir}/log/unicorn.stderr.log"
stdout_path "#{@dir}/log/unicorn.stdout.log"


text:
from juriscraper.opinions.united_states.state import kan

class Site(kan.Site):
    def __init__(self):
        super(Site, self).__init__()
        self.court_id = self.__module__
        self.court_index = 2


text:
<!DOCTYPE html>
<meta charset=utf-8>
<title>invalid value attribute: userinfo-password-contains-pile-of-poo</title>
<input type=url value="http://foo:💩@example.com">


text:
package org.asynchttpclient.providers.netty3.request.body;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;

public class NettyByteArrayBody extends NettyDirectBody {

    private final byte[] bytes;
    private final String contentType;

    public NettyByteArrayBody(byte[] bytes) {
        this(bytes, null);
    }

    public NettyByteArrayBody(byte[] bytes, String contentType) {
        this.bytes = bytes;
        this.contentType = contentType;
    }

    @Override
    public long getContentLength() {
        return bytes.length;
    }

    @Override
    public String getContentType() {
        return contentType;
    }

    @Override
    public ChannelBuffer channelBuffer() {
        return ChannelBuffers.wrappedBuffer(bytes);
    }
}


text:
package com.badlogic.gdx.utils;

import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.reflect.ArrayReflection;

import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException;

/** A resizable, ordered or unordered array of objects. If unordered, this class avoids a memory copy when removing elements (the
 * last element is moved to the removed element's position).
 * @author Nathan Sweet */
public class Array<T> implements Iterable<T> {
	/** Provides direct access to the underlying array. If the Array's generic type is not Object, this field may only be accessed
	 * if the {@link Array#Array(boolean, int, Class)} constructor was used. */
	public T[] items;

	public int size;
	public boolean ordered;

	private ArrayIterable iterable;
	private Predicate.PredicateIterable<T> predicateIterable;

	/** Creates an ordered array with a capacity of 16. */
	public Array () {
		this(true, 16);
	}

	/** Creates an ordered array with the specified capacity. */
	public Array (int capacity) {
		this(true, capacity);
	}

	/** @param ordered If false, methods that remove elements may change the order of other elements in the array, which avoids a
	 *           memory copy.
	 * @param capacity Any elements added beyond this will cause the backing array to be grown. */
	public Array (boolean ordered, int capacity) {
		this.ordered = ordered;
		items = (T[])new Object[capacity];
	}

	/** Creates a new array with {@link #items} of the specified type.
	 * @param ordered If false, methods that remove elements may change the order of other elements in the array, which avoids a
	 *           memory copy.
	 * @param capacity Any elements added beyond this will cause the backing array to be grown. */
	public Array (boolean ordered, int capacity, Class arrayType) {
		this.ordered = ordered;
		items = (T[])ArrayReflection.newInstance(arrayType, capacity);
	}

	/** Creates an ordered array with {@link #items} of the specified type and a capacity of 16. */
	public Array (Class arrayType) {
		this(true, 16, arrayType);
	}

	/** Creates a new array containing the elements in the specified array. The new array will have the same type of backing array
	 * and will be ordered if the specified array is ordered. The capacity is set to the number of elements, so any subsequent
	 * elements added will cause the backing array to be grown. */
	public Array (Array<? extends T> array) {
		this(array.ordered, array.size, array.items.getClass().getComponentType());
		size = array.size;
		System.arraycopy(array.items, 0, items, 0, size);
	}

	/** Creates a new ordered array containing the elements in the specified array. The new array will have the same type of backing
	 * array. The capacity is set to the number of elements, so any subsequent elements added will cause the backing array to be
	 * grown. */
	public Array (T[] array) {
		this(true, array, 0, array.length);
	}

	/** Creates a new array containing the elements in the specified array. The new array will have the same type of backing array.
	 * The capacity is set to the number of elements, so any subsequent elements added will cause the backing array to be grown.
	 * @param ordered If false, methods that remove elements may change the order of other elements in the array, which avoids a
	 *           memory copy. */
	public Array (boolean ordered, T[] array, int start, int count) {
		this(ordered, count, (Class)array.getClass().getComponentType());
		size = count;
		System.arraycopy(array, 0, items, 0, size);
	}

	public void add (T value) {
		T[] items = this.items;
		if (size == items.length) items = resize(Math.max(8, (int)(size * 1.75f)));
		items[size++] = value;
	}

	public void addAll (Array<? extends T> array) {
		addAll(array, 0, array.size);
	}

	public void addAll (Array<? extends T> array, int offset, int length) {
		if (offset + length > array.size)
			throw new IllegalArgumentException("offset + length must be <= size: " + offset + " + " + length + " <= " + array.size);
		addAll((T[])array.items, offset, length);
	}

	public void addAll (T... array) {
		addAll(array, 0, array.length);
	}

	public void addAll (T[] array, int offset, int length) {
		T[] items = this.items;
		int sizeNeeded = size + length;
		if (sizeNeeded > items.length) items = resize(Math.max(8, (int)(sizeNeeded * 1.75f)));
		System.arraycopy(array, offset, items, size, length);
		size += length;
	}

	public T get (int index) {
		if (index >= size) throw new IndexOutOfBoundsException("index can't be >= size: " + index + " >= " + size);
		return items[index];
	}

	public void set (int index, T value) {
		if (index >= size) throw new IndexOutOfBoundsException("index can't be >= size: " + index + " >= " + size);
		items[index] = value;
	}

	public void insert (int index, T value) {
		if (index > size) throw new IndexOutOfBoundsException("index can't be > size: " + index + " > " + size);
		T[] items = this.items;
		if (size == items.length) items = resize(Math.max(8, (int)(size * 1.75f)));
		if (ordered)
			System.arraycopy(items, index, items, index + 1, size - index);
		else
			items[size] = items[index];
		size++;
		items[index] = value;
	}

	public void swap (int first, int second) {
		if (first >= size) throw new IndexOutOfBoundsException("first can't be >= size: " + first + " >= " + size);
		if (second >= size) throw new IndexOutOfBoundsException("second can't be >= size: " + second + " >= " + size);
		T[] items = this.items;
		T firstValue = items[first];
		items[first] = items[second];
		items[second] = firstValue;
	}

	/** Returns if this array contains value.
	 * @param identity If true, == comparison will be used. If false, .equals() comparison will be used.
	 * @return true if array contains value, false if it doesn't */
	public boolean contains (T value, boolean identity) {
		T[] items = this.items;
		int i = size - 1;
		if (identity || value == null) {
			while (i >= 0)
				if (items[i--] == value) return true;
		} else {
			while (i >= 0)
				if (value.equals(items[i--])) return true;
		}
		return false;
	}

	/** Returns an index of first occurrence of value in array or -1 if no such value exists
	 * @param identity If true, == comparison will be used. If false, .equals() comparison will be used.
	 * @return An index of first occurrence of value in array or -1 if no such value exists */
	public int indexOf (T value, boolean identity) {
		T[] items = this.items;
		if (identity || value == null) {
			for (int i = 0, n = size; i < n; i++)
				if (items[i] == value) return i;
		} else {
			for (int i = 0, n = size; i < n; i++)
				if (value.equals(items[i])) return i;
		}
		return -1;
	}

	/** Returns an index of last occurrence of value in array or -1 if no such value exists. Search is started from the end of an
	 * array.
	 * @param identity If true, == comparison will be used. If false, .equals() comparison will be used.
	 * @return An index of last occurrence of value in array or -1 if no such value exists */
	public int lastIndexOf (T value, boolean identity) {
		T[] items = this.items;
		if (identity || value == null) {
			for (int i = size - 1; i >= 0; i--)
				if (items[i] == value) return i;
		} else {
			for (int i = size - 1; i >= 0; i--)
				if (value.equals(items[i])) return i;
		}
		return -1;
	}

	/** Removes the first instance of the specified value in the array.
	 * @param identity If true, == comparison will be used. If false, .equals() comparison will be used.
	 * @return true if value was found and removed, false otherwise */
	public boolean removeValue (T value, boolean identity) {
		T[] items = this.items;
		if (identity || value == null) {
			for (int i = 0, n = size; i < n; i++) {
				if (items[i] == value) {
					removeIndex(i);
					return true;
				}
			}
		} else {
			for (int i = 0, n = size; i < n; i++) {
				if (value.equals(items[i])) {
					removeIndex(i);
					return true;
				}
			}
		}
		return false;
	}

	/** Removes and returns the item at the specified index. */
	public T removeIndex (int index) {
		if (index >= size) throw new IndexOutOfBoundsException("index can't be >= size: " + index + " >= " + size);
		T[] items = this.items;
		T value = (T)items[index];
		size--;
		if (ordered)
			System.arraycopy(items, index + 1, items, index, size - index);
		else
			items[index] = items[size];
		items[size] = null;
		return value;
	}

	/** Removes from this array all of elements contained in the specified array.
	 * @param identity True to use ==, false to use .equals().
	 * @return true if this array was modified. */
	public boolean removeAll (Array<? extends T> array, boolean identity) {
		int size = this.size;
		int startSize = size;
		T[] items = this.items;
		if (identity) {
			for (int i = 0, n = array.size; i < n; i++) {
				T item = array.get(i);
				for (int ii = 0; ii < size; ii++) {
					if (item == items[ii]) {
						removeIndex(ii);
						size--;
						break;
					}
				}
			}
		} else {
			for (int i = 0, n = array.size; i < n; i++) {
				T item = array.get(i);
				for (int ii = 0; ii < size; ii++) {
					if (item.equals(items[ii])) {
						removeIndex(ii);
						size--;
						break;
					}
				}
			}
		}
		return size != startSize;
	}

	/** Removes and returns the last item. */
	public T pop () {
		if (size == 0) throw new IllegalStateException("Array is empty.");
		--size;
		T item = items[size];
		items[size] = null;
		return item;
	}

	/** Returns the last item. */
	public T peek () {
		if (size == 0) throw new IllegalStateException("Array is empty.");
		return items[size - 1];
	}

	/** Returns the first item. */
	public T first () {
		if (size == 0) throw new IllegalStateException("Array is empty.");
		return items[0];
	}

	public void clear () {
		T[] items = this.items;
		for (int i = 0, n = size; i < n; i++)
			items[i] = null;
		size = 0;
	}

	/** Reduces the size of the backing array to the size of the actual items. This is useful to release memory when many items have
	 * been removed, or if it is known that more items will not be added. */
	public void shrink () {
		if (items.length == size) return;
		resize(size);
	}

	/** Increases the size of the backing array to acommodate the specified number of additional items. Useful before adding many
	 * items to avoid multiple backing array resizes.
	 * @return {@link #items} */
	public T[] ensureCapacity (int additionalCapacity) {
		int sizeNeeded = size + additionalCapacity;
		if (sizeNeeded > items.length) resize(Math.max(8, sizeNeeded));
		return items;
	}

	/** Creates a new backing array with the specified size containing the current items. */
	protected T[] resize (int newSize) {
		T[] items = this.items;
		T[] newItems = (T[])ArrayReflection.newInstance(items.getClass().getComponentType(), newSize);
		System.arraycopy(items, 0, newItems, 0, Math.min(size, newItems.length));
		this.items = newItems;
		return newItems;
	}

	/** Sorts this array. The array elements must implement {@link Comparable}. This method is not thread safe (uses
	 * {@link Sort#instance()}). */
	public void sort () {
		Sort.instance().sort(items, 0, size);
	}

	/** Sorts the array. This method is not thread safe (uses {@link Sort#instance()}). */
	public void sort (Comparator<? super T> comparator) {
		Sort.instance().sort(items, comparator, 0, size);
	}

	/** Selects the nth-lowest element from the Array according to Comparator ranking. This might partially sort the Array. The
	 * array must have a size greater than 0, or a {@link com.badlogic.gdx.utils.GdxRuntimeException} will be thrown.
	 * @see Select
	 * @param comparator used for comparison
	 * @param kthLowest rank of desired object according to comparison, n is based on ordinal numbers, not array indices. for min
	 *           value use 1, for max value use size of array, using 0 results in runtime exception.
	 * @return the value of the Nth lowest ranked object. */
	public T selectRanked (Comparator<T> comparator, int kthLowest) {
		if (kthLowest < 1) {
			throw new GdxRuntimeException("nth_lowest must be greater than 0, 1 = first, 2 = second...");
		}
		return Select.instance().select(items, comparator, kthLowest, size);
	}

	/** @see Array#selectRanked(java.util.Comparator, int)
	 * @param comparator used for comparison
	 * @param kthLowest rank of desired object according to comparison, n is based on ordinal numbers, not array indices. for min
	 *           value use 1, for max value use size of array, using 0 results in runtime exception.
	 * @return the index of the Nth lowest ranked object. */
	public int selectRankedIndex (Comparator<T> comparator, int kthLowest) {
		if (kthLowest < 1) {
			throw new GdxRuntimeException("nth_lowest must be greater than 0, 1 = first, 2 = second...");
		}
		return Select.instance().selectIndex(items, comparator, kthLowest, size);
	}

	public void reverse () {
		T[] items = this.items;
		for (int i = 0, lastIndex = size - 1, n = size / 2; i < n; i++) {
			int ii = lastIndex - i;
			T temp = items[i];
			items[i] = items[ii];
			items[ii] = temp;
		}
	}

	public void shuffle () {
		T[] items = this.items;
		for (int i = size - 1; i >= 0; i--) {
			int ii = MathUtils.random(i);
			T temp = items[i];
			items[i] = items[ii];
			items[ii] = temp;
		}
	}

	/** Returns an iterator for the items in the array. Remove is supported. Note that the same iterator instance is returned each
	 * time this method is called. Use the {@link ArrayIterator} constructor for nested or multithreaded iteration. */
	public Iterator<T> iterator () {
		if (iterable == null) iterable = new ArrayIterable(this);
		return iterable.iterator();
	}

	/** Returns an iterable for the selected items in the array. Remove is supported, but not between hasNext() and next(). Note
	 * that the same iterable instance is returned each time this method is called. Use the {@link Predicate.PredicateIterable}
	 * constructor for nested or multithreaded iteration. */
	public Iterable<T> select (Predicate<T> predicate) {
		if (predicateIterable == null)
			predicateIterable = new Predicate.PredicateIterable<T>(this, predicate);
		else
			predicateIterable.set(this, predicate);
		return predicateIterable;
	}

	/** Reduces the size of the array to the specified size. If the array is already smaller than the specified size, no action is
	 * taken. */
	public void truncate (int newSize) {
		if (size <= newSize) return;
		for (int i = newSize; i < size; i++)
			items[i] = null;
		size = newSize;
	}

	/** Returns a random item from the array, or null if the array is empty. */
	public T random () {
		if (size == 0) return null;
		return items[MathUtils.random(0, size - 1)];
	}

	/** Returns the items as an array. Note the array is typed, so the {@link #Array(Class)} constructor must have been used.
	 * Otherwise use {@link #toArray(Class)} to specify the array type. */
	public T[] toArray () {
		return (T[])toArray(items.getClass().getComponentType());
	}

	public <V> V[] toArray (Class type) {
		V[] result = (V[])ArrayReflection.newInstance(type, size);
		System.arraycopy(items, 0, result, 0, size);
		return result;
	}

	public boolean equals (Object object) {
		if (object == this) return true;
		if (!(object instanceof Array)) return false;
		Array array = (Array)object;
		int n = size;
		if (n != array.size) return false;
		Object[] items1 = this.items;
		Object[] items2 = array.items;
		for (int i = 0; i < n; i++) {
			Object o1 = items1[i];
			Object o2 = items2[i];
			if (!(o1 == null ? o2 == null : o1.equals(o2))) return false;
		}
		return true;
	}

	public String toString () {
		if (size == 0) return "[]";
		T[] items = this.items;
		StringBuilder buffer = new StringBuilder(32);
		buffer.append('[');
		buffer.append(items[0]);
		for (int i = 1; i < size; i++) {
			buffer.append(", ");
			buffer.append(items[i]);
		}
		buffer.append(']');
		return buffer.toString();
	}

	public String toString (String separator) {
		if (size == 0) return "";
		T[] items = this.items;
		StringBuilder buffer = new StringBuilder(32);
		buffer.append(items[0]);
		for (int i = 1; i < size; i++) {
			buffer.append(separator);
			buffer.append(items[i]);
		}
		return buffer.toString();
	}

	/** @see #Array(Class) */
	static public <T> Array<T> of (Class<T> arrayType) {
		return new Array<T>(arrayType);
	}

	/** @see #Array(boolean, int, Class) */
	static public <T> Array<T> of (boolean ordered, int capacity, Class<T> arrayType) {
		return new Array<T>(ordered, capacity, arrayType);
	}

	static public class ArrayIterator<T> implements Iterator<T>, Iterable<T> {
		private final Array<T> array;
		private final boolean allowRemove;
		int index;
		boolean valid = true;

		public ArrayIterator (Array<T> array) {
			this(array, true);
		}

		public ArrayIterator (Array<T> array, boolean allowRemove) {
			this.array = array;
			this.allowRemove = allowRemove;
		}

		public boolean hasNext () {
			if (!valid) throw new GdxRuntimeException("#iterator() cannot be used nested.");
			return index < array.size;
		}

		public T next () {
			if (index >= array.size) throw new NoSuchElementException(String.valueOf(index));
			if (!valid) throw new GdxRuntimeException("#iterator() cannot be used nested.");
			return array.items[index++];
		}

		public void remove () {
			if (!allowRemove) throw new GdxRuntimeException("Remove not allowed.");
			index--;
			array.removeIndex(index);
		}

		public void reset () {
			index = 0;
		}

		public Iterator<T> iterator () {
			return this;
		}
	}

	static public class ArrayIterable<T> implements Iterable<T> {
		private final Array<T> array;
		private final boolean allowRemove;
		private ArrayIterator iterator1, iterator2;

		public ArrayIterable (Array<T> array) {
			this(array, true);
		}

		public ArrayIterable (Array<T> array, boolean allowRemove) {
			this.array = array;
			this.allowRemove = allowRemove;
		}

		public Iterator<T> iterator () {
			if (iterator1 == null) {
				iterator1 = new ArrayIterator(array, allowRemove);
				iterator2 = new ArrayIterator(array, allowRemove);
			}
			if (!iterator1.valid) {
				iterator1.index = 0;
				iterator1.valid = true;
				iterator2.valid = false;
				return iterator1;
			}
			iterator2.index = 0;
			iterator2.valid = true;
			iterator1.valid = false;
			return iterator2;
		}
	}
}


text:
package com.ait.lienzo.client.core.event;

import com.google.gwt.event.dom.client.MouseEvent;
import com.google.gwt.event.dom.client.MouseUpEvent;

public class NodeMouseUpEvent extends AbstractNodeMouseEvent<MouseEvent<?>, NodeMouseUpHandler>
{
    private static final Type<NodeMouseUpHandler> TYPE = new Type<NodeMouseUpHandler>();

    public static final Type<NodeMouseUpHandler> getType()
    {
        return TYPE;
    }

    public NodeMouseUpEvent(final MouseUpEvent event)
    {
        super(event);
    }

    @Override
    public final Type<NodeMouseUpHandler> getAssociatedType()
    {
        return TYPE;
    }

    @Override
    protected void dispatch(final NodeMouseUpHandler handler)
    {
        handler.onNodeMouseUp(this);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/tools"

   >
<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingRight="8dp"
        android:paddingTop="8dp"
        android:paddingBottom="8dp">

        <!--<LinearLayout-->
            <!--android:orientation="vertical"-->
            <!--android:layout_width="0dp"-->
            <!--android:layout_weight="2"-->
            <!--android:layout_height="wrap_content">-->

            <!--<LinearLayout-->
                <!--android:orientation="vertical"-->
                <!--android:layout_width="wrap_content"-->
                <!--android:layout_height="wrap_content"-->
                <!--android:layout_gravity="center_vertical">-->

                <!--<de.hdodenhof.circleimageview.CircleImageView-->
                    <!--android:id="@+id/imageView_vendor"-->
                    <!--android:layout_width="64dp"-->
                    <!--android:layout_height="64dp" />-->

            <!--</LinearLayout>-->

            <!--<LinearLayout-->
                <!--android:orientation="vertical"-->
                <!--android:paddingLeft="8dp"-->
                <!--android:layout_width="fill_parent"-->
                <!--android:layout_height="wrap_content">-->

                <!--<RelativeLayout-->
                    <!--android:layout_width="match_parent"-->
                    <!--android:layout_height="wrap_content">-->

                    <!--<TextView-->
                        <!--android:id="@+id/vendor_name"-->
                        <!--android:textSize="18dp"-->
                        <!--android:layout_width="wrap_content"-->
                        <!--android:layout_height="wrap_content"-->
                        <!--android:textColor="@color/black"-->
                        <!--android:layout_centerVertical="true" />-->

                    <!--<TextView-->
                        <!--android:padding="6dp"-->
                        <!--android:background="@drawable/rounded_corner"-->
                        <!--android:textColor="@color/black"-->
                        <!--android:id="@+id/vendor_rating"-->

                        <!--android:textSize="14dp"-->
                        <!--android:layout_alignParentRight="true"-->
                        <!--android:layout_width="36dp"-->
                        <!--android:layout_height="32dp"-->
                        <!--android:gravity="center_vertical|center_horizontal" />-->

                <!--</RelativeLayout>-->

                <!--<TextView-->
                    <!--android:textSize="16dp"-->
                    <!--android:id="@+id/textView_address"-->
                    <!--android:layout_width="match_parent"-->
                    <!--android:layout_height="wrap_content"-->
                    <!--android:paddingBottom="4dp"-->
                    <!--android:textColor="@color/black"/>-->

                <!--<LinearLayout-->
                    <!--android:orientation="horizontal"-->
                    <!--android:layout_width="match_parent"-->
                    <!--android:layout_height="wrap_content">-->

                    <!--<TextView-->
                        <!--android:paddingLeft="4dp"-->
                        <!--android:textSize="14sp"-->
                        <!--android:id="@+id/textView_hour"-->
                        <!--android:visibility="gone"-->
                        <!--android:layout_width="wrap_content"-->
                        <!--android:layout_height="wrap_content"-->
                        <!--android:textColor="@color/black"-->
                        <!--android:layout_gravity="center_vertical" />-->

                <!--</LinearLayout>-->

                <!--<!–<View–>-->
                <!--<!–android:layout_marginTop="12dp"–>-->
                <!--<!–android:layout_width="fill_parent"–>-->
                <!--<!–android:layout_height="1dp"–>-->
                <!--<!–android:background="@color/dividerColor"/>–>-->
                <!--<!–<TextView–>-->
                <!--<!–android:id="@+id/vendor_rating"–>-->
                <!--<!–android:layout_width="wrap_content"–>-->
                <!--<!–android:layout_height="wrap_content"–>-->
                <!--<!–android:textColor="@color/black"/>–>-->

                <!--<!–<ImageView–>-->
                <!--<!–android:layout_width="wrap_content"–>-->
                <!--<!–android:layout_height="wrap_content"–>-->
                <!--<!–android:src="@drawable/favoriteborder"–>-->
                <!--<!–android:layout_gravity="right"–>-->
                <!--<!–/>–>-->

            <!--</LinearLayout>-->

        <!--</LinearLayout>-->

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="0dp"
            android:layout_weight="2"
            android:layout_height="wrap_content">

            <de.hdodenhof.circleimageview.CircleImageView
                android:id="@+id/user_review_user_picture"
                android:layout_width="64dp"
                android:layout_height="64dp"
                android:layout_gravity="center" />

         </LinearLayout>

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="0dp"
            android:layout_weight="4"
            android:layout_height="wrap_content">

            <TextView
                    android:id="@+id/user_review_writer"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textColor="@color/primaryColorDark"
                    android:textStyle="bold"
                    android:textSize="18dp"
                    android:typeface="monospace"
                    android:paddingLeft="10dp"
                    android:layout_marginTop="20dp"
                    />

        </LinearLayout>

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="0dp"
            android:layout_weight="3"
            android:layout_height="wrap_content"
            >

            <TextView
                android:gravity="right"
                android:layout_gravity="center_vertical|right"
                android:textColor="@color/black"
                android:id="@+id/user_review_date"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal" android:layout_weight="1"
                android:gravity="right"
                android:layout_gravity="center_vertical|right"
                android:layout_marginTop="5dp">

                <ImageView
                    android:layout_gravity="center_vertical|center_horizontal"
                    android:id="@+id/grade_1"
                    android:visibility="gone"
                    android:src="@drawable/orange_star"
                    android:layout_width="18dp"
                    android:layout_height="18dp"
                    android:layout_margin="0dp"/>

                <ImageView
                    android:layout_gravity="center_vertical|center_horizontal"
                    android:id="@+id/grade_2"
                    android:visibility="gone"
                    android:src="@drawable/orange_star"
                    android:layout_width="18dp"
                    android:layout_height="18dp"
                    android:layout_margin="0dp" />

                <ImageView
                    android:layout_gravity="center_vertical|center_horizontal"
                    android:id="@+id/grade_3"
                    android:visibility="gone"
                    android:src="@drawable/orange_star"

                    android:layout_width="18dp"
                    android:layout_height="18dp"
                    android:layout_margin="0dp"/>

                <ImageView
                    android:layout_gravity="center_vertical|center_horizontal"
                    android:id="@+id/grade_4"
                    android:visibility="gone"
                    android:src="@drawable/orange_star"
                    android:layout_width="18dp"
                    android:layout_height="18dp"
                    android:layout_margin="0dp"/>

                <ImageView
                    android:layout_gravity="center_vertical|center_horizontal"
                    android:id="@+id/grade_5"
                    android:visibility="gone"
                    android:src="@drawable/orange_star"
                    android:layout_width="18dp"
                    android:layout_height="18dp"
                    android:layout_margin="0dp" />

            </LinearLayout>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal" android:layout_weight="1"
                android:gravity="right"
                android:layout_gravity="center_vertical|right"
                android:layout_marginTop="5dp">

                <TextView
                    android:id="@+id/user_review_how_many"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:textColor="@color/white"
                    android:typeface="monospace"
                    android:textSize="16dp"
                    android:background="@drawable/rounded_corner_blue"
                    android:textStyle="normal"
                    android:gravity="center"
                   />

            </LinearLayout>
        </LinearLayout>

    </LinearLayout>
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="8dp"
        android:paddingRight="8dp"
        android:paddingBottom="8dp">
        <TextView
            android:textStyle="bold"
            android:textColor="@color/black"
            android:id="@+id/user_review_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="17dp" />

        <TextView

            android:textColor="@color/black"
            android:id="@+id/user_review_description"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="16dp"
            android:textIsSelectable="false" />
    </LinearLayout>
</LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/dividerColor"/>

</FrameLayout>


text:
"Collection of specialized notebook vizualization tools"
from .confusion_matrix_viz import confusion_matrix  # noqa
from .neighbors_viz import viz_neigbors_imgs  # noqa
from .projector import projector  # noqa
from .vizualize_views import visualize_views  # noqa


text:
namespace Azure.ResourceManager.SecurityInsights.Models
{
    /// <summary> Common field for data type in data connectors. </summary>
    public partial class DataConnectorDataTypeCommon
    {
        /// <summary> Initializes a new instance of DataConnectorDataTypeCommon. </summary>
        /// <param name="state"> Describe whether this data type connection is enabled or not. </param>
        public DataConnectorDataTypeCommon(DataTypeState state)
        {
            State = state;
        }

        /// <summary> Describe whether this data type connection is enabled or not. </summary>
        public DataTypeState State { get; set; }
    }
}


text:
from django.conf.urls.defaults import patterns, url

from .views import IndexView, DetailView

urlpatterns = patterns('',
    url(r'^$', IndexView.as_view(), name='index'),
    url(r'^(?P<volume_id>[^/]+)/$', DetailView.as_view(), name='detail'),
)


text:
require 'spec_helper'

describe 'Invites' do
  let(:user) { create(:user) }
  let(:owner) { create(:user, name: 'John Doe') }
  let(:group) { create(:group, name: 'Owned') }
  let(:project) { create(:project, :repository, namespace: group) }
  let(:group_invite) { group.group_members.invite.last }

  before do
    project.add_maintainer(owner)
    group.add_user(owner, Gitlab::Access::OWNER)
    group.add_developer('user@example.com', owner)
    group_invite.generate_invite_token!
  end

  def confirm_email_and_sign_in(new_user)
    new_user_token = User.find_by_email(new_user.email).confirmation_token

    visit user_confirmation_path(confirmation_token: new_user_token)
    fill_in_sign_in_form(new_user)
  end

  def fill_in_sign_up_form(new_user)
    fill_in 'new_user_name',                with: new_user.name
    fill_in 'new_user_username',            with: new_user.username
    fill_in 'new_user_email',               with: new_user.email
    fill_in 'new_user_email_confirmation',  with: new_user.email
    fill_in 'new_user_password',            with: new_user.password
    click_button "Register"
  end

  def fill_in_sign_in_form(user)
    fill_in 'user_login', with: user.email
    fill_in 'user_password', with: user.password
    check 'user_remember_me'
    click_button 'Sign in'
  end

  context 'when signed out' do
    before do
      visit invite_path(group_invite.raw_invite_token)
    end

    it 'renders sign in page with sign in notice' do
      expect(current_path).to eq(new_user_session_path)
      expect(page).to have_content('To accept this invitation, sign in')
    end

    it 'sign in and redirects to invitation page' do
      fill_in_sign_in_form(user)

      expect(current_path).to eq(invite_path(group_invite.raw_invite_token))
      expect(page).to have_content(
        'You have been invited by John Doe to join group Owned as Developer.'
      )
      expect(page).to have_link('Accept invitation')
      expect(page).to have_link('Decline')
    end
  end

  context 'when signed in as an exists member' do
    before do
      sign_in(owner)
    end

    it 'shows message user already a member' do
      visit invite_path(group_invite.raw_invite_token)
      expect(page).to have_content('However, you are already a member of this group.')
    end
  end

  describe 'accepting the invitation' do
    before do
      sign_in(user)
      visit invite_path(group_invite.raw_invite_token)
    end

    it 'grants access and redirects to group page' do
      page.click_link 'Accept invitation'
      expect(current_path).to eq(group_path(group))
      expect(page).to have_content(
        'You have been granted Developer access to group Owned.'
      )
    end
  end

  describe 'declining the application' do
    context 'when signed in' do
      before do
        sign_in(user)
        visit invite_path(group_invite.raw_invite_token)
      end

      it 'declines application and redirects to dashboard' do
        page.click_link 'Decline'
        expect(current_path).to eq(dashboard_projects_path)
        expect(page).to have_content(
          'You have declined the invitation to join group Owned.'
        )
      end
    end

    context 'when signed out' do
      before do
        visit decline_invite_path(group_invite.raw_invite_token)
      end

      it 'declines application and redirects to sign in page' do
        expect(current_path).to eq(new_user_session_path)
        expect(page).to have_content(
          'You have declined the invitation to join group Owned.'
        )
      end
    end
  end

  describe 'invite an user using their email address' do
    let(:new_user) { build_stubbed(:user) }
    let(:invite_email) { new_user.email }
    let(:group_invite) { create(:group_member, :invited, group: group, invite_email: invite_email) }
    let!(:project_invite) { create(:project_member, :invited, project: project, invite_email: invite_email) }

    before do
      stub_application_setting(send_user_confirmation_email: send_email_confirmation)
      visit invite_path(group_invite.raw_invite_token)
    end

    context 'email confirmation disabled' do
      let(:send_email_confirmation) { false }

      it 'signs up and redirects to the dashboard page with all the projects/groups invitations automatically accepted' do
        fill_in_sign_up_form(new_user)

        expect(current_path).to eq(dashboard_projects_path)
        expect(page).to have_content(project.full_name)
        visit group_path(group)
        expect(page).to have_content(group.full_name)
      end

      context 'the user sign-up using a different email address' do
        let(:invite_email) { build_stubbed(:user).email }

        it 'signs up and redirects to the invitation page' do
          fill_in_sign_up_form(new_user)

          expect(current_path).to eq(invite_path(group_invite.raw_invite_token))
        end
      end
    end

    context 'email confirmation enabled' do
      let(:send_email_confirmation) { true }

      it 'signs up and redirects to root page with all the project/groups invitation automatically accepted' do
        fill_in_sign_up_form(new_user)
        confirm_email_and_sign_in(new_user)

        expect(current_path).to eq(root_path)
        expect(page).to have_content(project.full_name)
        visit group_path(group)
        expect(page).to have_content(group.full_name)
      end

      it "doesn't accept invitations until the user confirm his email" do
        fill_in_sign_up_form(new_user)
        sign_in(owner)

        visit project_project_members_path(project)
        expect(page).to have_content 'Invited'
      end

      context 'the user sign-up using a different email address' do
        let(:invite_email) { build_stubbed(:user).email }

        it 'signs up and redirects to the invitation page' do
          fill_in_sign_up_form(new_user)
          confirm_email_and_sign_in(new_user)

          expect(current_path).to eq(invite_path(group_invite.raw_invite_token))
        end
      end
    end
  end
end


text:
"""

This program is a part of The Commotion Client

Copyright (C) 2014  Seamus Tuohy s2e@opentechinstitute.org

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""
"""
zip_extensions.py

This module takes all extensions in the commotion_client/extension/ directory and prepares them as commotion packages.
"""

import zipfile
import os

def get_extensions(main_directory):
    """Gets all extension sub-directories within a given directory.

    Args:
      main_directory (string): The path to the main extension directory to check for extensions within.

    Returns:
      A list containing of all of the extension directories within the main_directory.
        ['path/to/extension01', 'path/to/extension02', 'path/to/extension03']
    """
    #if not a directory... shame on them
    if not os.path.isdir(main_directory):
                raise NotADirectoryError("{0} is not a directory.".format(main_directory))
    extensions = []
    #walk the directory and add all sub-directories as extensions.
    for dirpath, dirnames, filenames in os.walk(main_directory):
        for directory in dirnames:
            #don't add pycache if it exists
            if directory != "__pycache__":
                extensions.append(os.path.join(dirpath, directory))
        break
    return extensions

def zip_extension(source, destination):
    """short description

    long description

    Args:
      source (string): The relative path to the source directory which contains the extension files.
      destination (string): The relative path to the destination directory where the zipfile will be placed.

    """
    #if extension is not a directory then this won't work
    if not os.path.isdir(source):
                raise NotADirectoryError("{0} is not a directory.".format(main_directory))
    extension_name = os.path.basename(os.path.normpath(source))
    to_zip = []
    #walk the full extension directory.
    for dirpath, dirnames, filenames in os.walk(source):
        if "__init__.py" not in filenames:
            touch_init(dirpath)
            to_zip.append(os.path.join(dirpath, "__init__.py"))
        for zip_file in filenames:
            to_zip.append(os.path.join(dirpath, zip_file))
    #create and populate zipfile
    with zipfile.ZipFile(os.path.join(destination, extension_name), 'a') as compressed_extension:
        for ready_file in to_zip:
            extension_path = os.path.relpath(ready_file, source)
            compressed_extension.write(ready_file, extension_path)

def touch_init(extension_dir):
    """ Touches the init file in each directory of an extension to make sure it exists.

    Args:
      extension_dir (string): The path to a directory an __init__.py file should exist within.
    """
    with open(os.path.join(extension_dir, "__init__.py"), 'a') as f:
        os.utime("__init__.py")

def zip_all():
    """Zip's all extensions in the main commotion_client directory and moves them into the build directories resources folder.
    """
    main_directory = os.path.join("commotion_client", "extensions")
    zip_directory = os.path.join("build", "resources")
    extension_paths = get_extensions(main_directory)
    for extension_directory in extension_paths:
        zip_extension(extension_directory, zip_directory)

if __name__ == "__main__":
    zip_all()


text:
package com.github.mpjct.jmpjct.mysql.proto;

import org.junit.*;
import static org.junit.Assert.*;

public class Local_Infile_ResponseTest {
    @Test
    public void test1() {
        byte[] packet = Proto.packet_string_to_bytes(""
            + "05 00 00 00 00 FF FE FD FC"
        );

        Local_Infile_Response pkt = Local_Infile_Response.loadFromPacket(packet);

        assertArrayEquals(packet, pkt.toPacket());
    }
}


text:
<?php

defined('IN_MANAGER_MODE') or die('Error');

/** @var DocumentParser $modx */

require __DIR__ . '/surveys.class.php';
require __DIR__ . '/surveymodulecontroller.class.php';

$survey = new Surveys($modx);
$controller = new SurveyModuleController($survey);
$action = isset($_GET['action']) ? (string) $_GET['action'] : 'index';

echo $controller->run($action);


text:
import * as React from 'react';
import cx = require('classnames');
import { ListItemComponent, ListItemProps } from './types';

const ListItem: ListItemComponent = (props: ListItemProps) => {
    const classNames = cx('list-group-item', props.className, {
        active: props.active
    });
    const rest = Object.assign({}, props);
    delete rest.active;

    return (
        <li {...rest} className={classNames}>
            {props.children}
        </li>
    );
};

export default ListItem;


text:
from datetime import timedelta
import operator
from sys import getsizeof
from typing import Union
import warnings

import numpy as np

from pandas._libs import index as libindex
import pandas.compat as compat
from pandas.compat.numpy import function as nv
from pandas.util._decorators import Appender, cache_readonly

from pandas.core.dtypes import concat as _concat
from pandas.core.dtypes.common import (
    ensure_python_int, is_int64_dtype, is_integer, is_scalar,
    is_timedelta64_dtype)
from pandas.core.dtypes.generic import (
    ABCDataFrame, ABCSeries, ABCTimedeltaIndex)

from pandas.core import ops
import pandas.core.common as com
import pandas.core.indexes.base as ibase
from pandas.core.indexes.base import Index, _index_shared_docs
from pandas.core.indexes.numeric import Int64Index

from pandas.io.formats.printing import pprint_thing

class RangeIndex(Int64Index):
    """
    Immutable Index implementing a monotonic integer range.

    RangeIndex is a memory-saving special case of Int64Index limited to
    representing monotonic ranges. Using RangeIndex may in some instances
    improve computing speed.

    This is the default index type used
    by DataFrame and Series when no explicit index is provided by the user.

    Parameters
    ----------
    start : int (default: 0), or other RangeIndex instance
        If int and "stop" is not given, interpreted as "stop" instead.
    stop : int (default: 0)
    step : int (default: 1)
    name : object, optional
        Name to be stored in the index
    copy : bool, default False
        Unused, accepted for homogeneity with other index types.

    Attributes
    ----------
    start
    stop
    step

    Methods
    -------
    from_range

    See Also
    --------
    Index : The base pandas Index type.
    Int64Index : Index of int64 data.
    """

    _typ = 'rangeindex'
    _engine_type = libindex.Int64Engine
    _range = None  # type: range

    # check whether self._data has benn called
    _cached_data = None  # type: np.ndarray
    # --------------------------------------------------------------------
    # Constructors

    def __new__(cls, start=None, stop=None, step=None,
                dtype=None, copy=False, name=None, fastpath=None):

        if fastpath is not None:
            warnings.warn("The 'fastpath' keyword is deprecated, and will be "
                          "removed in a future version.",
                          FutureWarning, stacklevel=2)
            if fastpath:
                return cls._simple_new(range(start, stop, step), name=name)

        cls._validate_dtype(dtype)

        # RangeIndex
        if isinstance(start, RangeIndex):
            name = start.name if name is None else name
            start = start._range
            return cls._simple_new(start, dtype=dtype, name=name)

        # validate the arguments
        if com._all_none(start, stop, step):
            raise TypeError("RangeIndex(...) must be called with integers")

        start = ensure_python_int(start) if start is not None else 0

        if stop is None:
            start, stop = 0, start
        else:
            stop = ensure_python_int(stop)

        step = ensure_python_int(step) if step is not None else 1
        if step == 0:
            raise ValueError("Step must not be zero")

        rng = range(start, stop, step)
        return cls._simple_new(rng, dtype=dtype, name=name)

    @classmethod
    def from_range(cls, data, name=None, dtype=None):
        """
        Create RangeIndex from a range object.

        Returns
        -------
        RangeIndex
        """
        if not isinstance(data, range):
            raise TypeError(
                '{0}(...) must be called with object coercible to a '
                'range, {1} was passed'.format(cls.__name__, repr(data)))

        cls._validate_dtype(dtype)
        return cls._simple_new(data, dtype=dtype, name=name)

    @classmethod
    def _simple_new(cls, values, name=None, dtype=None, **kwargs):
        result = object.__new__(cls)

        # handle passed None, non-integers
        if values is None:
            # empty
            values = range(0, 0, 1)
        elif not isinstance(values, range):
            return Index(values, dtype=dtype, name=name, **kwargs)

        result._range = values

        result.name = name
        for k, v in kwargs.items():
            setattr(result, k, v)

        result._reset_identity()
        return result

    # --------------------------------------------------------------------

    @staticmethod
    def _validate_dtype(dtype):
        """ require dtype to be None or int64 """
        if not (dtype is None or is_int64_dtype(dtype)):
            raise TypeError('Invalid to pass a non-int64 dtype to RangeIndex')

    @cache_readonly
    def _constructor(self):
        """ return the class to use for construction """
        return Int64Index

    @property
    def _data(self):
        """
        An int array that for performance reasons is created only when needed.

        The constructed array is saved in ``_cached_data``. This allows us to
        check if the array has been created without accessing ``_data`` and
        triggering the construction.
        """
        if self._cached_data is None:
            self._cached_data = np.arange(self.start, self.stop, self.step,
                                          dtype=np.int64)
        return self._cached_data

    @cache_readonly
    def _int64index(self):
        return Int64Index._simple_new(self._data, name=self.name)

    def _get_data_as_items(self):
        """ return a list of tuples of start, stop, step """
        rng = self._range
        return [('start', rng.start),
                ('stop', rng.stop),
                ('step', rng.step)]

    def __reduce__(self):
        d = self._get_attributes_dict()
        d.update(dict(self._get_data_as_items()))
        return ibase._new_Index, (self.__class__, d), None

    # --------------------------------------------------------------------
    # Rendering Methods

    def _format_attrs(self):
        """
        Return a list of tuples of the (attr, formatted_value)
        """
        attrs = self._get_data_as_items()
        if self.name is not None:
            attrs.append(('name', ibase.default_pprint(self.name)))
        return attrs

    def _format_data(self, name=None):
        # we are formatting thru the attributes
        return None

    def _format_with_header(self, header, na_rep='NaN', **kwargs):
        return header + list(map(pprint_thing, self._range))

    # --------------------------------------------------------------------
    _deprecation_message = ("RangeIndex.{} is deprecated and will be "
                            "removed in a future version. Use RangeIndex.{} "
                            "instead")

    @cache_readonly
    def start(self):
        """
        The value of the `start` parameter (``0`` if this was not supplied)
        """
        # GH 25710
        return self._range.start

    @property
    def _start(self):
        """
        The value of the `start` parameter (``0`` if this was not supplied)

         .. deprecated:: 0.25.0
            Use ``start`` instead.
        """
        warnings.warn(self._deprecation_message.format("_start", "start"),
                      DeprecationWarning, stacklevel=2)
        return self.start

    @cache_readonly
    def stop(self):
        """
        The value of the `stop` parameter
        """
        return self._range.stop

    @property
    def _stop(self):
        """
        The value of the `stop` parameter

         .. deprecated:: 0.25.0
            Use ``stop`` instead.
        """
        # GH 25710
        warnings.warn(self._deprecation_message.format("_stop", "stop"),
                      DeprecationWarning, stacklevel=2)
        return self.stop

    @cache_readonly
    def step(self):
        """
        The value of the `step` parameter (``1`` if this was not supplied)
        """
        # GH 25710
        return self._range.step

    @property
    def _step(self):
        """
        The value of the `step` parameter (``1`` if this was not supplied)

         .. deprecated:: 0.25.0
            Use ``step`` instead.
        """
        # GH 25710
        warnings.warn(self._deprecation_message.format("_step", "step"),
                      DeprecationWarning, stacklevel=2)
        return self.step

    @cache_readonly
    def nbytes(self):
        """
        Return the number of bytes in the underlying data.
        """
        rng = self._range
        return getsizeof(rng) + sum(getsizeof(getattr(rng, attr_name))
                                    for attr_name in ['start', 'stop', 'step'])

    def memory_usage(self, deep=False):
        """
        Memory usage of my values

        Parameters
        ----------
        deep : bool
            Introspect the data deeply, interrogate
            `object` dtypes for system-level memory consumption

        Returns
        -------
        bytes used

        Notes
        -----
        Memory usage does not include memory consumed by elements that
        are not components of the array if deep=False

        See Also
        --------
        numpy.ndarray.nbytes
        """
        return self.nbytes

    @property
    def dtype(self):
        return np.dtype(np.int64)

    @property
    def is_unique(self):
        """ return if the index has unique values """
        return True

    @cache_readonly
    def is_monotonic_increasing(self):
        return self._range.step > 0 or len(self) <= 1

    @cache_readonly
    def is_monotonic_decreasing(self):
        return self._range.step < 0 or len(self) <= 1

    @property
    def has_duplicates(self):
        return False

    def __contains__(self, key: Union[int, np.integer]) -> bool:
        hash(key)
        try:
            key = ensure_python_int(key)
        except TypeError:
            return False
        return key in self._range

    @Appender(_index_shared_docs['get_loc'])
    def get_loc(self, key, method=None, tolerance=None):
        if is_integer(key) and method is None and tolerance is None:
            new_key = int(key)
            try:
                return self._range.index(new_key)
            except ValueError:
                raise KeyError(key)
        return super().get_loc(key, method=method, tolerance=tolerance)

    def tolist(self):
        return list(self._range)

    @Appender(_index_shared_docs['_shallow_copy'])
    def _shallow_copy(self, values=None, **kwargs):
        if values is None:
            name = kwargs.get("name", self.name)
            return self._simple_new(self._range, name=name)
        else:
            kwargs.setdefault('name', self.name)
            return self._int64index._shallow_copy(values, **kwargs)

    @Appender(ibase._index_shared_docs['copy'])
    def copy(self, name=None, deep=False, dtype=None, **kwargs):
        self._validate_dtype(dtype)
        if name is None:
            name = self.name
        return self.from_range(self._range, name=name)

    def _minmax(self, meth):
        no_steps = len(self) - 1
        if no_steps == -1:
            return np.nan
        elif ((meth == 'min' and self.step > 0) or
              (meth == 'max' and self.step < 0)):
            return self.start

        return self.start + self.step * no_steps

    def min(self, axis=None, skipna=True, *args, **kwargs):
        """The minimum value of the RangeIndex"""
        nv.validate_minmax_axis(axis)
        nv.validate_min(args, kwargs)
        return self._minmax('min')

    def max(self, axis=None, skipna=True, *args, **kwargs):
        """The maximum value of the RangeIndex"""
        nv.validate_minmax_axis(axis)
        nv.validate_max(args, kwargs)
        return self._minmax('max')

    def argsort(self, *args, **kwargs):
        """
        Returns the indices that would sort the index and its
        underlying data.

        Returns
        -------
        argsorted : numpy array

        See Also
        --------
        numpy.ndarray.argsort
        """
        nv.validate_argsort(args, kwargs)

        if self._range.step > 0:
            return np.arange(len(self))
        else:
            return np.arange(len(self) - 1, -1, -1)

    def equals(self, other):
        """
        Determines if two Index objects contain the same elements.
        """
        if isinstance(other, RangeIndex):
            return self._range == other._range
        return super().equals(other)

    def intersection(self, other, sort=False):
        """
        Form the intersection of two Index objects.

        Parameters
        ----------
        other : Index or array-like
        sort : False or None, default False
            Sort the resulting index if possible

            .. versionadded:: 0.24.0

            .. versionchanged:: 0.24.1

               Changed the default to ``False`` to match the behaviour
               from before 0.24.0.

        Returns
        -------
        intersection : Index
        """
        self._validate_sort_keyword(sort)

        if self.equals(other):
            return self._get_reconciled_name_object(other)

        if not isinstance(other, RangeIndex):
            return super().intersection(other, sort=sort)

        if not len(self) or not len(other):
            return self._simple_new(None)

        first = self._range[::-1] if self.step < 0 else self._range
        second = other._range[::-1] if other.step < 0 else other._range

        # check whether intervals intersect
        # deals with in- and decreasing ranges
        int_low = max(first.start, second.start)
        int_high = min(first.stop, second.stop)
        if int_high <= int_low:
            return self._simple_new(None)

        # Method hint: linear Diophantine equation
        # solve intersection problem
        # performance hint: for identical step sizes, could use
        # cheaper alternative
        gcd, s, t = self._extended_gcd(first.step, second.step)

        # check whether element sets intersect
        if (first.start - second.start) % gcd:
            return self._simple_new(None)

        # calculate parameters for the RangeIndex describing the
        # intersection disregarding the lower bounds
        tmp_start = first.start + (second.start - first.start) * \
            first.step // gcd * s
        new_step = first.step * second.step // gcd
        new_range = range(tmp_start, int_high, new_step)
        new_index = self._simple_new(new_range)

        # adjust index to limiting interval
        new_start = new_index._min_fitting_element(int_low)
        new_range = range(new_start, new_index.stop, new_index.step)
        new_index = self._simple_new(new_range)

        if (self.step < 0 and other.step < 0) is not (new_index.step < 0):
            new_index = new_index[::-1]
        if sort is None:
            new_index = new_index.sort_values()
        return new_index

    def _min_fitting_element(self, lower_limit):
        """Returns the smallest element greater than or equal to the limit"""
        no_steps = -(-(lower_limit - self.start) // abs(self.step))
        return self.start + abs(self.step) * no_steps

    def _max_fitting_element(self, upper_limit):
        """Returns the largest element smaller than or equal to the limit"""
        no_steps = (upper_limit - self.start) // abs(self.step)
        return self.start + abs(self.step) * no_steps

    def _extended_gcd(self, a, b):
        """
        Extended Euclidean algorithms to solve Bezout's identity:
           a*x + b*y = gcd(x, y)
        Finds one particular solution for x, y: s, t
        Returns: gcd, s, t
        """
        s, old_s = 0, 1
        t, old_t = 1, 0
        r, old_r = b, a
        while r:
            quotient = old_r // r
            old_r, r = r, old_r - quotient * r
            old_s, s = s, old_s - quotient * s
            old_t, t = t, old_t - quotient * t
        return old_r, old_s, old_t

    def _union(self, other, sort):
        """
        Form the union of two Index objects and sorts if possible

        Parameters
        ----------
        other : Index or array-like

        sort : False or None, default None
            Whether to sort resulting index. ``sort=None`` returns a
            monotonically increasing ``RangeIndex`` if possible or a sorted
            ``Int64Index`` if not. ``sort=False`` always returns an
            unsorted ``Int64Index``

            .. versionadded:: 0.25.0

        Returns
        -------
        union : Index
        """
        if not len(other) or self.equals(other) or not len(self):
            return super()._union(other, sort=sort)

        if isinstance(other, RangeIndex) and sort is None:
            start_s, step_s = self.start, self.step
            end_s = self.start + self.step * (len(self) - 1)
            start_o, step_o = other.start, other.step
            end_o = other.start + other.step * (len(other) - 1)
            if self.step < 0:
                start_s, step_s, end_s = end_s, -step_s, start_s
            if other.step < 0:
                start_o, step_o, end_o = end_o, -step_o, start_o
            if len(self) == 1 and len(other) == 1:
                step_s = step_o = abs(self.start - other.start)
            elif len(self) == 1:
                step_s = step_o
            elif len(other) == 1:
                step_o = step_s
            start_r = min(start_s, start_o)
            end_r = max(end_s, end_o)
            if step_o == step_s:
                if ((start_s - start_o) % step_s == 0 and
                        (start_s - end_o) <= step_s and
                        (start_o - end_s) <= step_s):
                    return self.__class__(start_r, end_r + step_s, step_s)
                if ((step_s % 2 == 0) and
                        (abs(start_s - start_o) <= step_s / 2) and
                        (abs(end_s - end_o) <= step_s / 2)):
                    return self.__class__(start_r,
                                          end_r + step_s / 2,
                                          step_s / 2)
            elif step_o % step_s == 0:
                if ((start_o - start_s) % step_s == 0 and
                        (start_o + step_s >= start_s) and
                        (end_o - step_s <= end_s)):
                    return self.__class__(start_r, end_r + step_s, step_s)
            elif step_s % step_o == 0:
                if ((start_s - start_o) % step_o == 0 and
                        (start_s + step_o >= start_o) and
                        (end_s - step_o <= end_o)):
                    return self.__class__(start_r, end_r + step_o, step_o)
        return self._int64index._union(other, sort=sort)

    @Appender(_index_shared_docs['join'])
    def join(self, other, how='left', level=None, return_indexers=False,
             sort=False):
        if how == 'outer' and self is not other:
            # note: could return RangeIndex in more circumstances
            return self._int64index.join(other, how, level, return_indexers,
                                         sort)

        return super().join(other, how, level, return_indexers, sort)

    def _concat_same_dtype(self, indexes, name):
        return _concat._concat_rangeindex_same_dtype(indexes).rename(name)

    def __len__(self):
        """
        return the length of the RangeIndex
        """
        return len(self._range)

    @property
    def size(self):
        return len(self)

    def __getitem__(self, key):
        """
        Conserve RangeIndex type for scalar and slice keys.
        """
        if isinstance(key, slice):
            new_range = self._range[key]
            return self._simple_new(new_range, name=self.name)
        elif is_integer(key):
            new_key = int(key)
            try:
                return self._range[new_key]
            except IndexError:
                raise IndexError("index {key} is out of bounds for axis 0 "
                                 "with size {size}".format(key=key,
                                                           size=len(self)))
        elif is_scalar(key):
            raise IndexError("only integers, slices (`:`), "
                             "ellipsis (`...`), numpy.newaxis (`None`) "
                             "and integer or boolean "
                             "arrays are valid indices")
        # fall back to Int64Index
        return super().__getitem__(key)

    def __floordiv__(self, other):
        if isinstance(other, (ABCSeries, ABCDataFrame)):
            return NotImplemented

        if is_integer(other) and other != 0:
            if (len(self) == 0 or
                    self.start % other == 0 and
                    self.step % other == 0):
                start = self.start // other
                step = self.step // other
                stop = start + len(self) * step
                new_range = range(start, stop, step or 1)
                return self._simple_new(new_range, name=self.name)
            if len(self) == 1:
                start = self.start // other
                new_range = range(start, start + 1, 1)
                return self._simple_new(new_range, name=self.name)
        return self._int64index // other

    def all(self) -> bool:
        return 0 not in self._range

    def any(self) -> bool:
        return any(self._range)

    @classmethod
    def _add_numeric_methods_binary(cls):
        """ add in numeric methods, specialized to RangeIndex """

        def _make_evaluate_binop(op, step=False):
            """
            Parameters
            ----------
            op : callable that accepts 2 parms
                perform the binary op
            step : callable, optional, default to False
                op to apply to the step parm if not None
                if False, use the existing step
            """

            def _evaluate_numeric_binop(self, other):
                if isinstance(other, (ABCSeries, ABCDataFrame)):
                    return NotImplemented
                elif isinstance(other, ABCTimedeltaIndex):
                    # Defer to TimedeltaIndex implementation
                    return NotImplemented
                elif isinstance(other, (timedelta, np.timedelta64)):
                    # GH#19333 is_integer evaluated True on timedelta64,
                    # so we need to catch these explicitly
                    return op(self._int64index, other)
                elif is_timedelta64_dtype(other):
                    # Must be an np.ndarray; GH#22390
                    return op(self._int64index, other)

                other = self._validate_for_numeric_binop(other, op)
                attrs = self._get_attributes_dict()
                attrs = self._maybe_update_attributes(attrs)

                left, right = self, other

                try:
                    # apply if we have an override
                    if step:
                        with np.errstate(all='ignore'):
                            rstep = step(left.step, right)

                        # we don't have a representable op
                        # so return a base index
                        if not is_integer(rstep) or not rstep:
                            raise ValueError

                    else:
                        rstep = left.step

                    with np.errstate(all='ignore'):
                        rstart = op(left.start, right)
                        rstop = op(left.stop, right)

                    result = self.__class__(rstart, rstop, rstep, **attrs)

                    # for compat with numpy / Int64Index
                    # even if we can represent as a RangeIndex, return
                    # as a Float64Index if we have float-like descriptors
                    if not all(is_integer(x) for x in
                               [rstart, rstop, rstep]):
                        result = result.astype('float64')

                    return result

                except (ValueError, TypeError, ZeroDivisionError):
                    # Defer to Int64Index implementation
                    return op(self._int64index, other)
                    # TODO: Do attrs get handled reliably?

            name = '__{name}__'.format(name=op.__name__)
            return compat.set_function_name(_evaluate_numeric_binop, name, cls)

        cls.__add__ = _make_evaluate_binop(operator.add)
        cls.__radd__ = _make_evaluate_binop(ops.radd)
        cls.__sub__ = _make_evaluate_binop(operator.sub)
        cls.__rsub__ = _make_evaluate_binop(ops.rsub)
        cls.__mul__ = _make_evaluate_binop(operator.mul, step=operator.mul)
        cls.__rmul__ = _make_evaluate_binop(ops.rmul, step=ops.rmul)
        cls.__truediv__ = _make_evaluate_binop(operator.truediv,
                                               step=operator.truediv)
        cls.__rtruediv__ = _make_evaluate_binop(ops.rtruediv,
                                                step=ops.rtruediv)

RangeIndex._add_numeric_methods()